zooid 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +36 -444
  3. package/dist/bin.js +1797 -0
  4. package/dist/bin.js.map +1 -0
  5. package/dist/chunk-N5POSZX5.js +31000 -0
  6. package/dist/chunk-N5POSZX5.js.map +1 -0
  7. package/dist/index.d.ts +40 -0
  8. package/dist/index.js +4 -3790
  9. package/dist/index.js.map +1 -0
  10. package/dist/web/assets/geist-cyrillic-wght-normal-CHSlOQsW.woff2 +0 -0
  11. package/dist/web/assets/geist-latin-ext-wght-normal-DMtmJ5ZE.woff2 +0 -0
  12. package/dist/web/assets/geist-latin-wght-normal-Dm3htQBi.woff2 +0 -0
  13. package/dist/web/assets/index-BT_v3DKu.js +295 -0
  14. package/dist/web/assets/index-DJTghnF-.css +1 -0
  15. package/dist/web/assets/index-JZMMlqDP.js +118066 -0
  16. package/dist/web/assets/reaction-picker-emoji-Kh7emgFa.js +716 -0
  17. package/dist/web/favicon.svg +1 -0
  18. package/dist/web/index.html +14 -0
  19. package/package.json +42 -22
  20. package/src/bin.ts +112 -0
  21. package/src/bootstrap/admin.test.ts +69 -0
  22. package/src/bootstrap/admin.ts +37 -0
  23. package/src/bootstrap/configs.test.ts +24 -0
  24. package/src/bootstrap/configs.ts +64 -0
  25. package/src/bootstrap/data-layout.test.ts +25 -0
  26. package/src/bootstrap/data-layout.ts +20 -0
  27. package/src/bootstrap/derive.test.ts +74 -0
  28. package/src/bootstrap/derive.ts +40 -0
  29. package/src/bootstrap/paths.test.ts +22 -0
  30. package/src/bootstrap/paths.ts +27 -0
  31. package/src/bootstrap/tokens.test.ts +44 -0
  32. package/src/bootstrap/tokens.ts +43 -0
  33. package/src/build-registry.context.test.ts +61 -0
  34. package/src/build-registry.test.ts +59 -0
  35. package/src/build-registry.ts +142 -0
  36. package/src/build-registry.zod043.test.ts +64 -0
  37. package/src/commands/dev-cascade.test.ts +38 -0
  38. package/src/commands/dev-cascade.ts +35 -0
  39. package/src/commands/dev-data-layout.test.ts +55 -0
  40. package/src/commands/dev.ts +308 -0
  41. package/src/commands/init/generators.test.ts +97 -0
  42. package/src/commands/init/generators.ts +119 -0
  43. package/src/commands/init/prompts.ts +123 -0
  44. package/src/commands/init/registry.test.ts +33 -0
  45. package/src/commands/init/registry.ts +75 -0
  46. package/src/commands/init/sniff.test.ts +41 -0
  47. package/src/commands/init/sniff.ts +30 -0
  48. package/src/commands/init.test.ts +131 -0
  49. package/src/commands/init.ts +158 -0
  50. package/src/commands/logs.test.ts +105 -0
  51. package/src/commands/logs.ts +108 -0
  52. package/src/commands/start.ts +28 -0
  53. package/src/commands/status.test.ts +73 -0
  54. package/src/commands/status.ts +100 -0
  55. package/src/daemon/start-daemon.test.ts +67 -0
  56. package/src/daemon/start-daemon.ts +243 -0
  57. package/src/index.ts +2 -0
  58. package/src/observability/capture-agent.ts +58 -0
  59. package/src/observability/capture-tuwunel.test.ts +57 -0
  60. package/src/observability/capture-tuwunel.ts +24 -0
  61. package/src/observability/file-sink.test.ts +68 -0
  62. package/src/observability/file-sink.ts +78 -0
  63. package/src/observability/observability.integration.test.ts +162 -0
  64. package/src/observability/paths.test.ts +104 -0
  65. package/src/observability/paths.ts +94 -0
  66. package/src/services/tuwunel.test.ts +64 -0
  67. package/src/services/tuwunel.ts +91 -0
  68. package/src/web/resolve.test.ts +50 -0
  69. package/src/web/resolve.ts +31 -0
  70. package/src/web/static.test.ts +51 -0
  71. package/src/web/static.ts +61 -0
  72. package/src/web/watch.ts +103 -0
  73. package/dist/chunk-67ZRMVHO.js +0 -174
  74. package/dist/chunk-AR456MHY.js +0 -29
  75. package/dist/chunk-VBGU2NST.js +0 -139
  76. package/dist/client-4VMFEFDX.js +0 -22
  77. package/dist/config-2KK5GX42.js +0 -27
  78. package/dist/template-T5IB4YWC.js +0 -92
@@ -0,0 +1,295 @@
1
+ var mU=Object.defineProperty;var gU=(r,e,t)=>e in r?mU(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var De=(r,e,t)=>gU(r,typeof e!="symbol"?e+"":e,t);function yU(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const o=Object.getOwnPropertyDescriptor(n,i);o&&Object.defineProperty(r,i,o.get?o:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function t(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(i){if(i.ep)return;i.ep=!0;const o=t(i);fetch(i.href,o)}})();var wi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ka(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function SU(r){if(r.__esModule)return r;var e=r.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var ax={exports:{}},mv={},lx={exports:{}},nt={};/**
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 ef=Symbol.for("react.element"),bU=Symbol.for("react.portal"),_U=Symbol.for("react.fragment"),EU=Symbol.for("react.strict_mode"),wU=Symbol.for("react.profiler"),TU=Symbol.for("react.provider"),RU=Symbol.for("react.context"),CU=Symbol.for("react.forward_ref"),kU=Symbol.for("react.suspense"),IU=Symbol.for("react.memo"),xU=Symbol.for("react.lazy"),T0=Symbol.iterator;function OU(r){return r===null||typeof r!="object"?null:(r=T0&&r[T0]||r["@@iterator"],typeof r=="function"?r:null)}var cx={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ux=Object.assign,dx={};function Ic(r,e,t){this.props=r,this.context=e,this.refs=dx,this.updater=t||cx}Ic.prototype.isReactComponent={};Ic.prototype.setState=function(r,e){if(typeof r!="object"&&typeof r!="function"&&r!=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,r,e,"setState")};Ic.prototype.forceUpdate=function(r){this.updater.enqueueForceUpdate(this,r,"forceUpdate")};function fx(){}fx.prototype=Ic.prototype;function k_(r,e,t){this.props=r,this.context=e,this.refs=dx,this.updater=t||cx}var I_=k_.prototype=new fx;I_.constructor=k_;ux(I_,Ic.prototype);I_.isPureReactComponent=!0;var R0=Array.isArray,hx=Object.prototype.hasOwnProperty,x_={current:null},px={key:!0,ref:!0,__self:!0,__source:!0};function vx(r,e,t){var n,i={},o=null,s=null;if(e!=null)for(n in e.ref!==void 0&&(s=e.ref),e.key!==void 0&&(o=""+e.key),e)hx.call(e,n)&&!px.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=t;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];i.children=l}if(r&&r.defaultProps)for(n in a=r.defaultProps,a)i[n]===void 0&&(i[n]=a[n]);return{$$typeof:ef,type:r,key:o,ref:s,props:i,_owner:x_.current}}function PU(r,e){return{$$typeof:ef,type:r.type,key:e,ref:r.ref,props:r.props,_owner:r._owner}}function O_(r){return typeof r=="object"&&r!==null&&r.$$typeof===ef}function MU(r){var e={"=":"=0",":":"=2"};return"$"+r.replace(/[=:]/g,function(t){return e[t]})}var C0=/\/+/g;function Hm(r,e){return typeof r=="object"&&r!==null&&r.key!=null?MU(""+r.key):e.toString(36)}function Rh(r,e,t,n,i){var o=typeof r;(o==="undefined"||o==="boolean")&&(r=null);var s=!1;if(r===null)s=!0;else switch(o){case"string":case"number":s=!0;break;case"object":switch(r.$$typeof){case ef:case bU:s=!0}}if(s)return s=r,i=i(s),r=n===""?"."+Hm(s,0):n,R0(i)?(t="",r!=null&&(t=r.replace(C0,"$&/")+"/"),Rh(i,e,t,"",function(c){return c})):i!=null&&(O_(i)&&(i=PU(i,t+(!i.key||s&&s.key===i.key?"":(""+i.key).replace(C0,"$&/")+"/")+r)),e.push(i)),1;if(s=0,n=n===""?".":n+":",R0(r))for(var a=0;a<r.length;a++){o=r[a];var l=n+Hm(o,a);s+=Rh(o,e,t,l,i)}else if(l=OU(r),typeof l=="function")for(r=l.call(r),a=0;!(o=r.next()).done;)o=o.value,l=n+Hm(o,a++),s+=Rh(o,e,t,l,i);else if(o==="object")throw e=String(r),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(r).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return s}function Mf(r,e,t){if(r==null)return r;var n=[],i=0;return Rh(r,n,"","",function(o){return e.call(t,o,i++)}),n}function AU(r){if(r._status===-1){var e=r._result;e=e(),e.then(function(t){(r._status===0||r._status===-1)&&(r._status=1,r._result=t)},function(t){(r._status===0||r._status===-1)&&(r._status=2,r._result=t)}),r._status===-1&&(r._status=0,r._result=e)}if(r._status===1)return r._result.default;throw r._result}var nn={current:null},Ch={transition:null},DU={ReactCurrentDispatcher:nn,ReactCurrentBatchConfig:Ch,ReactCurrentOwner:x_};function mx(){throw Error("act(...) is not supported in production builds of React.")}nt.Children={map:Mf,forEach:function(r,e,t){Mf(r,function(){e.apply(this,arguments)},t)},count:function(r){var e=0;return Mf(r,function(){e++}),e},toArray:function(r){return Mf(r,function(e){return e})||[]},only:function(r){if(!O_(r))throw Error("React.Children.only expected to receive a single React element child.");return r}};nt.Component=Ic;nt.Fragment=_U;nt.Profiler=wU;nt.PureComponent=k_;nt.StrictMode=EU;nt.Suspense=kU;nt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=DU;nt.act=mx;nt.cloneElement=function(r,e,t){if(r==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+r+".");var n=ux({},r.props),i=r.key,o=r.ref,s=r._owner;if(e!=null){if(e.ref!==void 0&&(o=e.ref,s=x_.current),e.key!==void 0&&(i=""+e.key),r.type&&r.type.defaultProps)var a=r.type.defaultProps;for(l in e)hx.call(e,l)&&!px.hasOwnProperty(l)&&(n[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)n.children=t;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];n.children=a}return{$$typeof:ef,type:r.type,key:i,ref:o,props:n,_owner:s}};nt.createContext=function(r){return r={$$typeof:RU,_currentValue:r,_currentValue2:r,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},r.Provider={$$typeof:TU,_context:r},r.Consumer=r};nt.createElement=vx;nt.createFactory=function(r){var e=vx.bind(null,r);return e.type=r,e};nt.createRef=function(){return{current:null}};nt.forwardRef=function(r){return{$$typeof:CU,render:r}};nt.isValidElement=O_;nt.lazy=function(r){return{$$typeof:xU,_payload:{_status:-1,_result:r},_init:AU}};nt.memo=function(r,e){return{$$typeof:IU,type:r,compare:e===void 0?null:e}};nt.startTransition=function(r){var e=Ch.transition;Ch.transition={};try{r()}finally{Ch.transition=e}};nt.unstable_act=mx;nt.useCallback=function(r,e){return nn.current.useCallback(r,e)};nt.useContext=function(r){return nn.current.useContext(r)};nt.useDebugValue=function(){};nt.useDeferredValue=function(r){return nn.current.useDeferredValue(r)};nt.useEffect=function(r,e){return nn.current.useEffect(r,e)};nt.useId=function(){return nn.current.useId()};nt.useImperativeHandle=function(r,e,t){return nn.current.useImperativeHandle(r,e,t)};nt.useInsertionEffect=function(r,e){return nn.current.useInsertionEffect(r,e)};nt.useLayoutEffect=function(r,e){return nn.current.useLayoutEffect(r,e)};nt.useMemo=function(r,e){return nn.current.useMemo(r,e)};nt.useReducer=function(r,e,t){return nn.current.useReducer(r,e,t)};nt.useRef=function(r){return nn.current.useRef(r)};nt.useState=function(r){return nn.current.useState(r)};nt.useSyncExternalStore=function(r,e,t){return nn.current.useSyncExternalStore(r,e,t)};nt.useTransition=function(){return nn.current.useTransition()};nt.version="18.3.1";lx.exports=nt;var E=lx.exports;const pe=Ka(E),gv=yU({__proto__:null,default:pe},[E]);/**
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 NU=E,LU=Symbol.for("react.element"),UU=Symbol.for("react.fragment"),jU=Object.prototype.hasOwnProperty,FU=NU.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,BU={key:!0,ref:!0,__self:!0,__source:!0};function gx(r,e,t){var n,i={},o=null,s=null;t!==void 0&&(o=""+t),e.key!==void 0&&(o=""+e.key),e.ref!==void 0&&(s=e.ref);for(n in e)jU.call(e,n)&&!BU.hasOwnProperty(n)&&(i[n]=e[n]);if(r&&r.defaultProps)for(n in e=r.defaultProps,e)i[n]===void 0&&(i[n]=e[n]);return{$$typeof:LU,type:r,key:o,ref:s,props:i,_owner:FU.current}}mv.Fragment=UU;mv.jsx=gx;mv.jsxs=gx;ax.exports=mv;var y=ax.exports,yx={exports:{}},Kn={},Sx={exports:{}},bx={};/**
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(r){function e(q,z){var Q=q.length;q.push(z);e:for(;0<Q;){var Ie=Q-1>>>1,Y=q[Ie];if(0<i(Y,z))q[Ie]=z,q[Q]=Y,Q=Ie;else break e}}function t(q){return q.length===0?null:q[0]}function n(q){if(q.length===0)return null;var z=q[0],Q=q.pop();if(Q!==z){q[0]=Q;e:for(var Ie=0,Y=q.length,le=Y>>>1;Ie<le;){var B=2*(Ie+1)-1,W=q[B],A=B+1,D=q[A];if(0>i(W,Q))A<Y&&0>i(D,W)?(q[Ie]=D,q[A]=Q,Ie=A):(q[Ie]=W,q[B]=Q,Ie=B);else if(A<Y&&0>i(D,Q))q[Ie]=D,q[A]=Q,Ie=A;else break e}}return z}function i(q,z){var Q=q.sortIndex-z.sortIndex;return Q!==0?Q:q.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;r.unstable_now=function(){return o.now()}}else{var s=Date,a=s.now();r.unstable_now=function(){return s.now()-a}}var l=[],c=[],u=1,d=null,f=3,p=!1,h=!1,m=!1,w=typeof setTimeout=="function"?setTimeout:null,g=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(q){for(var z=t(c);z!==null;){if(z.callback===null)n(c);else if(z.startTime<=q)n(c),z.sortIndex=z.expirationTime,e(l,z);else break;z=t(c)}}function k(q){if(m=!1,R(q),!h)if(t(l)!==null)h=!0,re(O);else{var z=t(c);z!==null&&ae(k,z.startTime-q)}}function O(q,z){h=!1,m&&(m=!1,g(C),C=-1),p=!0;var Q=f;try{for(R(z),d=t(l);d!==null&&(!(d.expirationTime>z)||q&&!H());){var Ie=d.callback;if(typeof Ie=="function"){d.callback=null,f=d.priorityLevel;var Y=Ie(d.expirationTime<=z);z=r.unstable_now(),typeof Y=="function"?d.callback=Y:d===t(l)&&n(l),R(z)}else n(l);d=t(l)}if(d!==null)var le=!0;else{var B=t(c);B!==null&&ae(k,B.startTime-z),le=!1}return le}finally{d=null,f=Q,p=!1}}var T=!1,x=null,C=-1,N=5,F=-1;function H(){return!(r.unstable_now()-F<N)}function ie(){if(x!==null){var q=r.unstable_now();F=q;var z=!0;try{z=x(!0,q)}finally{z?$():(T=!1,x=null)}}else T=!1}var $;if(typeof b=="function")$=function(){b(ie)};else if(typeof MessageChannel<"u"){var X=new MessageChannel,oe=X.port2;X.port1.onmessage=ie,$=function(){oe.postMessage(null)}}else $=function(){w(ie,0)};function re(q){x=q,T||(T=!0,$())}function ae(q,z){C=w(function(){q(r.unstable_now())},z)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(q){q.callback=null},r.unstable_continueExecution=function(){h||p||(h=!0,re(O))},r.unstable_forceFrameRate=function(q){0>q||125<q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<q?Math.floor(1e3/q):5},r.unstable_getCurrentPriorityLevel=function(){return f},r.unstable_getFirstCallbackNode=function(){return t(l)},r.unstable_next=function(q){switch(f){case 1:case 2:case 3:var z=3;break;default:z=f}var Q=f;f=z;try{return q()}finally{f=Q}},r.unstable_pauseExecution=function(){},r.unstable_requestPaint=function(){},r.unstable_runWithPriority=function(q,z){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var Q=f;f=q;try{return z()}finally{f=Q}},r.unstable_scheduleCallback=function(q,z,Q){var Ie=r.unstable_now();switch(typeof Q=="object"&&Q!==null?(Q=Q.delay,Q=typeof Q=="number"&&0<Q?Ie+Q:Ie):Q=Ie,q){case 1:var Y=-1;break;case 2:Y=250;break;case 5:Y=1073741823;break;case 4:Y=1e4;break;default:Y=5e3}return Y=Q+Y,q={id:u++,callback:z,priorityLevel:q,startTime:Q,expirationTime:Y,sortIndex:-1},Q>Ie?(q.sortIndex=Q,e(c,q),t(l)===null&&q===t(c)&&(m?(g(C),C=-1):m=!0,ae(k,Q-Ie))):(q.sortIndex=Y,e(l,q),h||p||(h=!0,re(O))),q},r.unstable_shouldYield=H,r.unstable_wrapCallback=function(q){var z=f;return function(){var Q=f;f=z;try{return q.apply(this,arguments)}finally{f=Q}}}})(bx);Sx.exports=bx;var KU=Sx.exports;/**
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 VU=E,Bn=KU;function he(r){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+r,t=1;t<arguments.length;t++)e+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+r+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var _x=new Set,ud={};function Va(r,e){nc(r,e),nc(r+"Capture",e)}function nc(r,e){for(ud[r]=e,r=0;r<e.length;r++)_x.add(e[r])}var xo=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Uy=Object.prototype.hasOwnProperty,$U=/^[: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]*$/,k0={},I0={};function WU(r){return Uy.call(I0,r)?!0:Uy.call(k0,r)?!1:$U.test(r)?I0[r]=!0:(k0[r]=!0,!1)}function qU(r,e,t,n){if(t!==null&&t.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:t!==null?!t.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function GU(r,e,t,n){if(e===null||typeof e>"u"||qU(r,e,t,n))return!0;if(n)return!1;if(t!==null)switch(t.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function on(r,e,t,n,i,o,s){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=t,this.propertyName=r,this.type=e,this.sanitizeURL=o,this.removeEmptyString=s}var Lr={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){Lr[r]=new on(r,0,!1,r,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var e=r[0];Lr[e]=new on(e,1,!1,r[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(r){Lr[r]=new on(r,2,!1,r.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){Lr[r]=new on(r,2,!1,r,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(r){Lr[r]=new on(r,3,!1,r.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(r){Lr[r]=new on(r,3,!0,r,null,!1,!1)});["capture","download"].forEach(function(r){Lr[r]=new on(r,4,!1,r,null,!1,!1)});["cols","rows","size","span"].forEach(function(r){Lr[r]=new on(r,6,!1,r,null,!1,!1)});["rowSpan","start"].forEach(function(r){Lr[r]=new on(r,5,!1,r.toLowerCase(),null,!1,!1)});var P_=/[\-:]([a-z])/g;function M_(r){return r[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(r){var e=r.replace(P_,M_);Lr[e]=new on(e,1,!1,r,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var e=r.replace(P_,M_);Lr[e]=new on(e,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(r){var e=r.replace(P_,M_);Lr[e]=new on(e,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(r){Lr[r]=new on(r,1,!1,r.toLowerCase(),null,!1,!1)});Lr.xlinkHref=new on("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(r){Lr[r]=new on(r,1,!1,r.toLowerCase(),null,!0,!0)});function A_(r,e,t,n){var i=Lr.hasOwnProperty(e)?Lr[e]:null;(i!==null?i.type!==0:n||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(GU(e,t,i,n)&&(t=null),n||i===null?WU(e)&&(t===null?r.removeAttribute(e):r.setAttribute(e,""+t)):i.mustUseProperty?r[i.propertyName]=t===null?i.type===3?!1:"":t:(e=i.attributeName,n=i.attributeNamespace,t===null?r.removeAttribute(e):(i=i.type,t=i===3||i===4&&t===!0?"":""+t,n?r.setAttributeNS(n,e,t):r.setAttribute(e,t))))}var Lo=VU.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Af=Symbol.for("react.element"),Tl=Symbol.for("react.portal"),Rl=Symbol.for("react.fragment"),D_=Symbol.for("react.strict_mode"),jy=Symbol.for("react.profiler"),Ex=Symbol.for("react.provider"),wx=Symbol.for("react.context"),N_=Symbol.for("react.forward_ref"),Fy=Symbol.for("react.suspense"),By=Symbol.for("react.suspense_list"),L_=Symbol.for("react.memo"),as=Symbol.for("react.lazy"),Tx=Symbol.for("react.offscreen"),x0=Symbol.iterator;function Xc(r){return r===null||typeof r!="object"?null:(r=x0&&r[x0]||r["@@iterator"],typeof r=="function"?r:null)}var Ut=Object.assign,zm;function Cu(r){if(zm===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);zm=e&&e[1]||""}return`
34
+ `+zm+r}var Ym=!1;function Jm(r,e){if(!r||Ym)return"";Ym=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(c){var n=c}Reflect.construct(r,[],e)}else{try{e.call()}catch(c){n=c}r.call(e.prototype)}else{try{throw Error()}catch(c){n=c}r()}}catch(c){if(c&&n&&typeof c.stack=="string"){for(var i=c.stack.split(`
35
+ `),o=n.stack.split(`
36
+ `),s=i.length-1,a=o.length-1;1<=s&&0<=a&&i[s]!==o[a];)a--;for(;1<=s&&0<=a;s--,a--)if(i[s]!==o[a]){if(s!==1||a!==1)do if(s--,a--,0>a||i[s]!==o[a]){var l=`
37
+ `+i[s].replace(" at new "," at ");return r.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",r.displayName)),l}while(1<=s&&0<=a);break}}}finally{Ym=!1,Error.prepareStackTrace=t}return(r=r?r.displayName||r.name:"")?Cu(r):""}function HU(r){switch(r.tag){case 5:return Cu(r.type);case 16:return Cu("Lazy");case 13:return Cu("Suspense");case 19:return Cu("SuspenseList");case 0:case 2:case 15:return r=Jm(r.type,!1),r;case 11:return r=Jm(r.type.render,!1),r;case 1:return r=Jm(r.type,!0),r;default:return""}}function Ky(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case Rl:return"Fragment";case Tl:return"Portal";case jy:return"Profiler";case D_:return"StrictMode";case Fy:return"Suspense";case By:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case wx:return(r.displayName||"Context")+".Consumer";case Ex:return(r._context.displayName||"Context")+".Provider";case N_:var e=r.render;return r=r.displayName,r||(r=e.displayName||e.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case L_:return e=r.displayName||null,e!==null?e:Ky(r.type)||"Memo";case as:e=r._payload,r=r._init;try{return Ky(r(e))}catch{}}return null}function zU(r){var e=r.type;switch(r.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=e.render,r=r.displayName||r.name||"",e.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ky(e);case 8:return e===D_?"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 e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function xs(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Rx(r){var e=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function YU(r){var e=Rx(r)?"checked":"value",t=Object.getOwnPropertyDescriptor(r.constructor.prototype,e),n=""+r[e];if(!r.hasOwnProperty(e)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var i=t.get,o=t.set;return Object.defineProperty(r,e,{configurable:!0,get:function(){return i.call(this)},set:function(s){n=""+s,o.call(this,s)}}),Object.defineProperty(r,e,{enumerable:t.enumerable}),{getValue:function(){return n},setValue:function(s){n=""+s},stopTracking:function(){r._valueTracker=null,delete r[e]}}}}function Df(r){r._valueTracker||(r._valueTracker=YU(r))}function Cx(r){if(!r)return!1;var e=r._valueTracker;if(!e)return!0;var t=e.getValue(),n="";return r&&(n=Rx(r)?r.checked?"true":"false":r.value),r=n,r!==t?(e.setValue(r),!0):!1}function ap(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function Vy(r,e){var t=e.checked;return Ut({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??r._wrapperState.initialChecked})}function O0(r,e){var t=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;t=xs(e.value!=null?e.value:t),r._wrapperState={initialChecked:n,initialValue:t,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function kx(r,e){e=e.checked,e!=null&&A_(r,"checked",e,!1)}function $y(r,e){kx(r,e);var t=xs(e.value),n=e.type;if(t!=null)n==="number"?(t===0&&r.value===""||r.value!=t)&&(r.value=""+t):r.value!==""+t&&(r.value=""+t);else if(n==="submit"||n==="reset"){r.removeAttribute("value");return}e.hasOwnProperty("value")?Wy(r,e.type,t):e.hasOwnProperty("defaultValue")&&Wy(r,e.type,xs(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(r.defaultChecked=!!e.defaultChecked)}function P0(r,e,t){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+r._wrapperState.initialValue,t||e===r.value||(r.value=e),r.defaultValue=e}t=r.name,t!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,t!==""&&(r.name=t)}function Wy(r,e,t){(e!=="number"||ap(r.ownerDocument)!==r)&&(t==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+t&&(r.defaultValue=""+t))}var ku=Array.isArray;function Fl(r,e,t,n){if(r=r.options,e){e={};for(var i=0;i<t.length;i++)e["$"+t[i]]=!0;for(t=0;t<r.length;t++)i=e.hasOwnProperty("$"+r[t].value),r[t].selected!==i&&(r[t].selected=i),i&&n&&(r[t].defaultSelected=!0)}else{for(t=""+xs(t),e=null,i=0;i<r.length;i++){if(r[i].value===t){r[i].selected=!0,n&&(r[i].defaultSelected=!0);return}e!==null||r[i].disabled||(e=r[i])}e!==null&&(e.selected=!0)}}function qy(r,e){if(e.dangerouslySetInnerHTML!=null)throw Error(he(91));return Ut({},e,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function M0(r,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(he(92));if(ku(t)){if(1<t.length)throw Error(he(93));t=t[0]}e=t}e==null&&(e=""),t=e}r._wrapperState={initialValue:xs(t)}}function Ix(r,e){var t=xs(e.value),n=xs(e.defaultValue);t!=null&&(t=""+t,t!==r.value&&(r.value=t),e.defaultValue==null&&r.defaultValue!==t&&(r.defaultValue=t)),n!=null&&(r.defaultValue=""+n)}function A0(r){var e=r.textContent;e===r._wrapperState.initialValue&&e!==""&&e!==null&&(r.value=e)}function xx(r){switch(r){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 Gy(r,e){return r==null||r==="http://www.w3.org/1999/xhtml"?xx(e):r==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var Nf,Ox=function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,t,n,i){MSApp.execUnsafeLocalFunction(function(){return r(e,t,n,i)})}:r}(function(r,e){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=e;else{for(Nf=Nf||document.createElement("div"),Nf.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=Nf.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;e.firstChild;)r.appendChild(e.firstChild)}});function dd(r,e){if(e){var t=r.firstChild;if(t&&t===r.lastChild&&t.nodeType===3){t.nodeValue=e;return}}r.textContent=e}var Vu={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},JU=["Webkit","ms","Moz","O"];Object.keys(Vu).forEach(function(r){JU.forEach(function(e){e=e+r.charAt(0).toUpperCase()+r.substring(1),Vu[e]=Vu[r]})});function Px(r,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||Vu.hasOwnProperty(r)&&Vu[r]?(""+e).trim():e+"px"}function Mx(r,e){r=r.style;for(var t in e)if(e.hasOwnProperty(t)){var n=t.indexOf("--")===0,i=Px(t,e[t],n);t==="float"&&(t="cssFloat"),n?r.setProperty(t,i):r[t]=i}}var XU=Ut({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 Hy(r,e){if(e){if(XU[r]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(he(137,r));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(he(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(he(61))}if(e.style!=null&&typeof e.style!="object")throw Error(he(62))}}function zy(r,e){if(r.indexOf("-")===-1)return typeof e.is=="string";switch(r){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 Yy=null;function U_(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Jy=null,Bl=null,Kl=null;function D0(r){if(r=nf(r)){if(typeof Jy!="function")throw Error(he(280));var e=r.stateNode;e&&(e=Ev(e),Jy(r.stateNode,r.type,e))}}function Ax(r){Bl?Kl?Kl.push(r):Kl=[r]:Bl=r}function Dx(){if(Bl){var r=Bl,e=Kl;if(Kl=Bl=null,D0(r),e)for(r=0;r<e.length;r++)D0(e[r])}}function Nx(r,e){return r(e)}function Lx(){}var Xm=!1;function Ux(r,e,t){if(Xm)return r(e,t);Xm=!0;try{return Nx(r,e,t)}finally{Xm=!1,(Bl!==null||Kl!==null)&&(Lx(),Dx())}}function fd(r,e){var t=r.stateNode;if(t===null)return null;var n=Ev(t);if(n===null)return null;t=n[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(r=r.type,n=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!n;break e;default:r=!1}if(r)return null;if(t&&typeof t!="function")throw Error(he(231,e,typeof t));return t}var Xy=!1;if(xo)try{var Qc={};Object.defineProperty(Qc,"passive",{get:function(){Xy=!0}}),window.addEventListener("test",Qc,Qc),window.removeEventListener("test",Qc,Qc)}catch{Xy=!1}function QU(r,e,t,n,i,o,s,a,l){var c=Array.prototype.slice.call(arguments,3);try{e.apply(t,c)}catch(u){this.onError(u)}}var $u=!1,lp=null,cp=!1,Qy=null,ZU={onError:function(r){$u=!0,lp=r}};function e2(r,e,t,n,i,o,s,a,l){$u=!1,lp=null,QU.apply(ZU,arguments)}function t2(r,e,t,n,i,o,s,a,l){if(e2.apply(this,arguments),$u){if($u){var c=lp;$u=!1,lp=null}else throw Error(he(198));cp||(cp=!0,Qy=c)}}function $a(r){var e=r,t=r;if(r.alternate)for(;e.return;)e=e.return;else{r=e;do e=r,e.flags&4098&&(t=e.return),r=e.return;while(r)}return e.tag===3?t:null}function jx(r){if(r.tag===13){var e=r.memoizedState;if(e===null&&(r=r.alternate,r!==null&&(e=r.memoizedState)),e!==null)return e.dehydrated}return null}function N0(r){if($a(r)!==r)throw Error(he(188))}function r2(r){var e=r.alternate;if(!e){if(e=$a(r),e===null)throw Error(he(188));return e!==r?null:r}for(var t=r,n=e;;){var i=t.return;if(i===null)break;var o=i.alternate;if(o===null){if(n=i.return,n!==null){t=n;continue}break}if(i.child===o.child){for(o=i.child;o;){if(o===t)return N0(i),r;if(o===n)return N0(i),e;o=o.sibling}throw Error(he(188))}if(t.return!==n.return)t=i,n=o;else{for(var s=!1,a=i.child;a;){if(a===t){s=!0,t=i,n=o;break}if(a===n){s=!0,n=i,t=o;break}a=a.sibling}if(!s){for(a=o.child;a;){if(a===t){s=!0,t=o,n=i;break}if(a===n){s=!0,n=o,t=i;break}a=a.sibling}if(!s)throw Error(he(189))}}if(t.alternate!==n)throw Error(he(190))}if(t.tag!==3)throw Error(he(188));return t.stateNode.current===t?r:e}function Fx(r){return r=r2(r),r!==null?Bx(r):null}function Bx(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var e=Bx(r);if(e!==null)return e;r=r.sibling}return null}var Kx=Bn.unstable_scheduleCallback,L0=Bn.unstable_cancelCallback,n2=Bn.unstable_shouldYield,i2=Bn.unstable_requestPaint,Jt=Bn.unstable_now,o2=Bn.unstable_getCurrentPriorityLevel,j_=Bn.unstable_ImmediatePriority,Vx=Bn.unstable_UserBlockingPriority,up=Bn.unstable_NormalPriority,s2=Bn.unstable_LowPriority,$x=Bn.unstable_IdlePriority,yv=null,zi=null;function a2(r){if(zi&&typeof zi.onCommitFiberRoot=="function")try{zi.onCommitFiberRoot(yv,r,void 0,(r.current.flags&128)===128)}catch{}}var Si=Math.clz32?Math.clz32:u2,l2=Math.log,c2=Math.LN2;function u2(r){return r>>>=0,r===0?32:31-(l2(r)/c2|0)|0}var Lf=64,Uf=4194304;function Iu(r){switch(r&-r){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 r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function dp(r,e){var t=r.pendingLanes;if(t===0)return 0;var n=0,i=r.suspendedLanes,o=r.pingedLanes,s=t&268435455;if(s!==0){var a=s&~i;a!==0?n=Iu(a):(o&=s,o!==0&&(n=Iu(o)))}else s=t&~i,s!==0?n=Iu(s):o!==0&&(n=Iu(o));if(n===0)return 0;if(e!==0&&e!==n&&!(e&i)&&(i=n&-n,o=e&-e,i>=o||i===16&&(o&4194240)!==0))return e;if(n&4&&(n|=t&16),e=r.entangledLanes,e!==0)for(r=r.entanglements,e&=n;0<e;)t=31-Si(e),i=1<<t,n|=r[t],e&=~i;return n}function d2(r,e){switch(r){case 1:case 2:case 4:return e+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 e+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 f2(r,e){for(var t=r.suspendedLanes,n=r.pingedLanes,i=r.expirationTimes,o=r.pendingLanes;0<o;){var s=31-Si(o),a=1<<s,l=i[s];l===-1?(!(a&t)||a&n)&&(i[s]=d2(a,e)):l<=e&&(r.expiredLanes|=a),o&=~a}}function Zy(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function Wx(){var r=Lf;return Lf<<=1,!(Lf&4194240)&&(Lf=64),r}function Qm(r){for(var e=[],t=0;31>t;t++)e.push(r);return e}function tf(r,e,t){r.pendingLanes|=e,e!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,e=31-Si(e),r[e]=t}function h2(r,e){var t=r.pendingLanes&~e;r.pendingLanes=e,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=e,r.mutableReadLanes&=e,r.entangledLanes&=e,e=r.entanglements;var n=r.eventTimes;for(r=r.expirationTimes;0<t;){var i=31-Si(t),o=1<<i;e[i]=0,n[i]=-1,r[i]=-1,t&=~o}}function F_(r,e){var t=r.entangledLanes|=e;for(r=r.entanglements;t;){var n=31-Si(t),i=1<<n;i&e|r[n]&e&&(r[n]|=e),t&=~i}}var ft=0;function qx(r){return r&=-r,1<r?4<r?r&268435455?16:536870912:4:1}var Gx,B_,Hx,zx,Yx,eS=!1,jf=[],ys=null,Ss=null,bs=null,hd=new Map,pd=new Map,ds=[],p2="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 U0(r,e){switch(r){case"focusin":case"focusout":ys=null;break;case"dragenter":case"dragleave":Ss=null;break;case"mouseover":case"mouseout":bs=null;break;case"pointerover":case"pointerout":hd.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":pd.delete(e.pointerId)}}function Zc(r,e,t,n,i,o){return r===null||r.nativeEvent!==o?(r={blockedOn:e,domEventName:t,eventSystemFlags:n,nativeEvent:o,targetContainers:[i]},e!==null&&(e=nf(e),e!==null&&B_(e)),r):(r.eventSystemFlags|=n,e=r.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),r)}function v2(r,e,t,n,i){switch(e){case"focusin":return ys=Zc(ys,r,e,t,n,i),!0;case"dragenter":return Ss=Zc(Ss,r,e,t,n,i),!0;case"mouseover":return bs=Zc(bs,r,e,t,n,i),!0;case"pointerover":var o=i.pointerId;return hd.set(o,Zc(hd.get(o)||null,r,e,t,n,i)),!0;case"gotpointercapture":return o=i.pointerId,pd.set(o,Zc(pd.get(o)||null,r,e,t,n,i)),!0}return!1}function Jx(r){var e=Sa(r.target);if(e!==null){var t=$a(e);if(t!==null){if(e=t.tag,e===13){if(e=jx(t),e!==null){r.blockedOn=e,Yx(r.priority,function(){Hx(t)});return}}else if(e===3&&t.stateNode.current.memoizedState.isDehydrated){r.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}r.blockedOn=null}function kh(r){if(r.blockedOn!==null)return!1;for(var e=r.targetContainers;0<e.length;){var t=tS(r.domEventName,r.eventSystemFlags,e[0],r.nativeEvent);if(t===null){t=r.nativeEvent;var n=new t.constructor(t.type,t);Yy=n,t.target.dispatchEvent(n),Yy=null}else return e=nf(t),e!==null&&B_(e),r.blockedOn=t,!1;e.shift()}return!0}function j0(r,e,t){kh(r)&&t.delete(e)}function m2(){eS=!1,ys!==null&&kh(ys)&&(ys=null),Ss!==null&&kh(Ss)&&(Ss=null),bs!==null&&kh(bs)&&(bs=null),hd.forEach(j0),pd.forEach(j0)}function eu(r,e){r.blockedOn===e&&(r.blockedOn=null,eS||(eS=!0,Bn.unstable_scheduleCallback(Bn.unstable_NormalPriority,m2)))}function vd(r){function e(i){return eu(i,r)}if(0<jf.length){eu(jf[0],r);for(var t=1;t<jf.length;t++){var n=jf[t];n.blockedOn===r&&(n.blockedOn=null)}}for(ys!==null&&eu(ys,r),Ss!==null&&eu(Ss,r),bs!==null&&eu(bs,r),hd.forEach(e),pd.forEach(e),t=0;t<ds.length;t++)n=ds[t],n.blockedOn===r&&(n.blockedOn=null);for(;0<ds.length&&(t=ds[0],t.blockedOn===null);)Jx(t),t.blockedOn===null&&ds.shift()}var Vl=Lo.ReactCurrentBatchConfig,fp=!0;function g2(r,e,t,n){var i=ft,o=Vl.transition;Vl.transition=null;try{ft=1,K_(r,e,t,n)}finally{ft=i,Vl.transition=o}}function y2(r,e,t,n){var i=ft,o=Vl.transition;Vl.transition=null;try{ft=4,K_(r,e,t,n)}finally{ft=i,Vl.transition=o}}function K_(r,e,t,n){if(fp){var i=tS(r,e,t,n);if(i===null)lg(r,e,n,hp,t),U0(r,n);else if(v2(i,r,e,t,n))n.stopPropagation();else if(U0(r,n),e&4&&-1<p2.indexOf(r)){for(;i!==null;){var o=nf(i);if(o!==null&&Gx(o),o=tS(r,e,t,n),o===null&&lg(r,e,n,hp,t),o===i)break;i=o}i!==null&&n.stopPropagation()}else lg(r,e,n,null,t)}}var hp=null;function tS(r,e,t,n){if(hp=null,r=U_(n),r=Sa(r),r!==null)if(e=$a(r),e===null)r=null;else if(t=e.tag,t===13){if(r=jx(e),r!==null)return r;r=null}else if(t===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;r=null}else e!==r&&(r=null);return hp=r,null}function Xx(r){switch(r){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(o2()){case j_:return 1;case Vx:return 4;case up:case s2:return 16;case $x:return 536870912;default:return 16}default:return 16}}var ps=null,V_=null,Ih=null;function Qx(){if(Ih)return Ih;var r,e=V_,t=e.length,n,i="value"in ps?ps.value:ps.textContent,o=i.length;for(r=0;r<t&&e[r]===i[r];r++);var s=t-r;for(n=1;n<=s&&e[t-n]===i[o-n];n++);return Ih=i.slice(r,1<n?1-n:void 0)}function xh(r){var e=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&e===13&&(r=13)):r=e,r===10&&(r=13),32<=r||r===13?r:0}function Ff(){return!0}function F0(){return!1}function Vn(r){function e(t,n,i,o,s){this._reactName=t,this._targetInst=i,this.type=n,this.nativeEvent=o,this.target=s,this.currentTarget=null;for(var a in r)r.hasOwnProperty(a)&&(t=r[a],this[a]=t?t(o):o[a]);return this.isDefaultPrevented=(o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===!1)?Ff:F0,this.isPropagationStopped=F0,this}return Ut(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=Ff)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=Ff)},persist:function(){},isPersistent:Ff}),e}var xc={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},$_=Vn(xc),rf=Ut({},xc,{view:0,detail:0}),S2=Vn(rf),Zm,eg,tu,Sv=Ut({},rf,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:W_,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==tu&&(tu&&r.type==="mousemove"?(Zm=r.screenX-tu.screenX,eg=r.screenY-tu.screenY):eg=Zm=0,tu=r),Zm)},movementY:function(r){return"movementY"in r?r.movementY:eg}}),B0=Vn(Sv),b2=Ut({},Sv,{dataTransfer:0}),_2=Vn(b2),E2=Ut({},rf,{relatedTarget:0}),tg=Vn(E2),w2=Ut({},xc,{animationName:0,elapsedTime:0,pseudoElement:0}),T2=Vn(w2),R2=Ut({},xc,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),C2=Vn(R2),k2=Ut({},xc,{data:0}),K0=Vn(k2),I2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},x2={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"},O2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function P2(r){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(r):(r=O2[r])?!!e[r]:!1}function W_(){return P2}var M2=Ut({},rf,{key:function(r){if(r.key){var e=I2[r.key]||r.key;if(e!=="Unidentified")return e}return r.type==="keypress"?(r=xh(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?x2[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:W_,charCode:function(r){return r.type==="keypress"?xh(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?xh(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),A2=Vn(M2),D2=Ut({},Sv,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),V0=Vn(D2),N2=Ut({},rf,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:W_}),L2=Vn(N2),U2=Ut({},xc,{propertyName:0,elapsedTime:0,pseudoElement:0}),j2=Vn(U2),F2=Ut({},Sv,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),B2=Vn(F2),K2=[9,13,27,32],q_=xo&&"CompositionEvent"in window,Wu=null;xo&&"documentMode"in document&&(Wu=document.documentMode);var V2=xo&&"TextEvent"in window&&!Wu,Zx=xo&&(!q_||Wu&&8<Wu&&11>=Wu),$0=" ",W0=!1;function eO(r,e){switch(r){case"keyup":return K2.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function tO(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Cl=!1;function $2(r,e){switch(r){case"compositionend":return tO(e);case"keypress":return e.which!==32?null:(W0=!0,$0);case"textInput":return r=e.data,r===$0&&W0?null:r;default:return null}}function W2(r,e){if(Cl)return r==="compositionend"||!q_&&eO(r,e)?(r=Qx(),Ih=V_=ps=null,Cl=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return Zx&&e.locale!=="ko"?null:e.data;default:return null}}var q2={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 q0(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e==="input"?!!q2[r.type]:e==="textarea"}function rO(r,e,t,n){Ax(n),e=pp(e,"onChange"),0<e.length&&(t=new $_("onChange","change",null,t,n),r.push({event:t,listeners:e}))}var qu=null,md=null;function G2(r){hO(r,0)}function bv(r){var e=xl(r);if(Cx(e))return r}function H2(r,e){if(r==="change")return e}var nO=!1;if(xo){var rg;if(xo){var ng="oninput"in document;if(!ng){var G0=document.createElement("div");G0.setAttribute("oninput","return;"),ng=typeof G0.oninput=="function"}rg=ng}else rg=!1;nO=rg&&(!document.documentMode||9<document.documentMode)}function H0(){qu&&(qu.detachEvent("onpropertychange",iO),md=qu=null)}function iO(r){if(r.propertyName==="value"&&bv(md)){var e=[];rO(e,md,r,U_(r)),Ux(G2,e)}}function z2(r,e,t){r==="focusin"?(H0(),qu=e,md=t,qu.attachEvent("onpropertychange",iO)):r==="focusout"&&H0()}function Y2(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return bv(md)}function J2(r,e){if(r==="click")return bv(e)}function X2(r,e){if(r==="input"||r==="change")return bv(e)}function Q2(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var Ti=typeof Object.is=="function"?Object.is:Q2;function gd(r,e){if(Ti(r,e))return!0;if(typeof r!="object"||r===null||typeof e!="object"||e===null)return!1;var t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;for(n=0;n<t.length;n++){var i=t[n];if(!Uy.call(e,i)||!Ti(r[i],e[i]))return!1}return!0}function z0(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function Y0(r,e){var t=z0(r);r=0;for(var n;t;){if(t.nodeType===3){if(n=r+t.textContent.length,r<=e&&n>=e)return{node:t,offset:e-r};r=n}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=z0(t)}}function oO(r,e){return r&&e?r===e?!0:r&&r.nodeType===3?!1:e&&e.nodeType===3?oO(r,e.parentNode):"contains"in r?r.contains(e):r.compareDocumentPosition?!!(r.compareDocumentPosition(e)&16):!1:!1}function sO(){for(var r=window,e=ap();e instanceof r.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)r=e.contentWindow;else break;e=ap(r.document)}return e}function G_(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e&&(e==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||e==="textarea"||r.contentEditable==="true")}function Z2(r){var e=sO(),t=r.focusedElem,n=r.selectionRange;if(e!==t&&t&&t.ownerDocument&&oO(t.ownerDocument.documentElement,t)){if(n!==null&&G_(t)){if(e=n.start,r=n.end,r===void 0&&(r=e),"selectionStart"in t)t.selectionStart=e,t.selectionEnd=Math.min(r,t.value.length);else if(r=(e=t.ownerDocument||document)&&e.defaultView||window,r.getSelection){r=r.getSelection();var i=t.textContent.length,o=Math.min(n.start,i);n=n.end===void 0?o:Math.min(n.end,i),!r.extend&&o>n&&(i=n,n=o,o=i),i=Y0(t,o);var s=Y0(t,n);i&&s&&(r.rangeCount!==1||r.anchorNode!==i.node||r.anchorOffset!==i.offset||r.focusNode!==s.node||r.focusOffset!==s.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),r.removeAllRanges(),o>n?(r.addRange(e),r.extend(s.node,s.offset)):(e.setEnd(s.node,s.offset),r.addRange(e)))}}for(e=[],r=t;r=r.parentNode;)r.nodeType===1&&e.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t<e.length;t++)r=e[t],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var ej=xo&&"documentMode"in document&&11>=document.documentMode,kl=null,rS=null,Gu=null,nS=!1;function J0(r,e,t){var n=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;nS||kl==null||kl!==ap(n)||(n=kl,"selectionStart"in n&&G_(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),Gu&&gd(Gu,n)||(Gu=n,n=pp(rS,"onSelect"),0<n.length&&(e=new $_("onSelect","select",null,e,t),r.push({event:e,listeners:n}),e.target=kl)))}function Bf(r,e){var t={};return t[r.toLowerCase()]=e.toLowerCase(),t["Webkit"+r]="webkit"+e,t["Moz"+r]="moz"+e,t}var Il={animationend:Bf("Animation","AnimationEnd"),animationiteration:Bf("Animation","AnimationIteration"),animationstart:Bf("Animation","AnimationStart"),transitionend:Bf("Transition","TransitionEnd")},ig={},aO={};xo&&(aO=document.createElement("div").style,"AnimationEvent"in window||(delete Il.animationend.animation,delete Il.animationiteration.animation,delete Il.animationstart.animation),"TransitionEvent"in window||delete Il.transitionend.transition);function _v(r){if(ig[r])return ig[r];if(!Il[r])return r;var e=Il[r],t;for(t in e)if(e.hasOwnProperty(t)&&t in aO)return ig[r]=e[t];return r}var lO=_v("animationend"),cO=_v("animationiteration"),uO=_v("animationstart"),dO=_v("transitionend"),fO=new Map,X0="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 js(r,e){fO.set(r,e),Va(e,[r])}for(var og=0;og<X0.length;og++){var sg=X0[og],tj=sg.toLowerCase(),rj=sg[0].toUpperCase()+sg.slice(1);js(tj,"on"+rj)}js(lO,"onAnimationEnd");js(cO,"onAnimationIteration");js(uO,"onAnimationStart");js("dblclick","onDoubleClick");js("focusin","onFocus");js("focusout","onBlur");js(dO,"onTransitionEnd");nc("onMouseEnter",["mouseout","mouseover"]);nc("onMouseLeave",["mouseout","mouseover"]);nc("onPointerEnter",["pointerout","pointerover"]);nc("onPointerLeave",["pointerout","pointerover"]);Va("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Va("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Va("onBeforeInput",["compositionend","keypress","textInput","paste"]);Va("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Va("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Va("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var xu="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(" "),nj=new Set("cancel close invalid load scroll toggle".split(" ").concat(xu));function Q0(r,e,t){var n=r.type||"unknown-event";r.currentTarget=t,t2(n,e,void 0,r),r.currentTarget=null}function hO(r,e){e=(e&4)!==0;for(var t=0;t<r.length;t++){var n=r[t],i=n.event;n=n.listeners;e:{var o=void 0;if(e)for(var s=n.length-1;0<=s;s--){var a=n[s],l=a.instance,c=a.currentTarget;if(a=a.listener,l!==o&&i.isPropagationStopped())break e;Q0(i,a,c),o=l}else for(s=0;s<n.length;s++){if(a=n[s],l=a.instance,c=a.currentTarget,a=a.listener,l!==o&&i.isPropagationStopped())break e;Q0(i,a,c),o=l}}}if(cp)throw r=Qy,cp=!1,Qy=null,r}function Ct(r,e){var t=e[lS];t===void 0&&(t=e[lS]=new Set);var n=r+"__bubble";t.has(n)||(pO(e,r,2,!1),t.add(n))}function ag(r,e,t){var n=0;e&&(n|=4),pO(t,r,n,e)}var Kf="_reactListening"+Math.random().toString(36).slice(2);function yd(r){if(!r[Kf]){r[Kf]=!0,_x.forEach(function(t){t!=="selectionchange"&&(nj.has(t)||ag(t,!1,r),ag(t,!0,r))});var e=r.nodeType===9?r:r.ownerDocument;e===null||e[Kf]||(e[Kf]=!0,ag("selectionchange",!1,e))}}function pO(r,e,t,n){switch(Xx(e)){case 1:var i=g2;break;case 4:i=y2;break;default:i=K_}t=i.bind(null,e,t,r),i=void 0,!Xy||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(i=!0),n?i!==void 0?r.addEventListener(e,t,{capture:!0,passive:i}):r.addEventListener(e,t,!0):i!==void 0?r.addEventListener(e,t,{passive:i}):r.addEventListener(e,t,!1)}function lg(r,e,t,n,i){var o=n;if(!(e&1)&&!(e&2)&&n!==null)e:for(;;){if(n===null)return;var s=n.tag;if(s===3||s===4){var a=n.stateNode.containerInfo;if(a===i||a.nodeType===8&&a.parentNode===i)break;if(s===4)for(s=n.return;s!==null;){var l=s.tag;if((l===3||l===4)&&(l=s.stateNode.containerInfo,l===i||l.nodeType===8&&l.parentNode===i))return;s=s.return}for(;a!==null;){if(s=Sa(a),s===null)return;if(l=s.tag,l===5||l===6){n=o=s;continue e}a=a.parentNode}}n=n.return}Ux(function(){var c=o,u=U_(t),d=[];e:{var f=fO.get(r);if(f!==void 0){var p=$_,h=r;switch(r){case"keypress":if(xh(t)===0)break e;case"keydown":case"keyup":p=A2;break;case"focusin":h="focus",p=tg;break;case"focusout":h="blur",p=tg;break;case"beforeblur":case"afterblur":p=tg;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":p=B0;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":p=_2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":p=L2;break;case lO:case cO:case uO:p=T2;break;case dO:p=j2;break;case"scroll":p=S2;break;case"wheel":p=B2;break;case"copy":case"cut":case"paste":p=C2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":p=V0}var m=(e&4)!==0,w=!m&&r==="scroll",g=m?f!==null?f+"Capture":null:f;m=[];for(var b=c,R;b!==null;){R=b;var k=R.stateNode;if(R.tag===5&&k!==null&&(R=k,g!==null&&(k=fd(b,g),k!=null&&m.push(Sd(b,k,R)))),w)break;b=b.return}0<m.length&&(f=new p(f,h,null,t,u),d.push({event:f,listeners:m}))}}if(!(e&7)){e:{if(f=r==="mouseover"||r==="pointerover",p=r==="mouseout"||r==="pointerout",f&&t!==Yy&&(h=t.relatedTarget||t.fromElement)&&(Sa(h)||h[Oo]))break e;if((p||f)&&(f=u.window===u?u:(f=u.ownerDocument)?f.defaultView||f.parentWindow:window,p?(h=t.relatedTarget||t.toElement,p=c,h=h?Sa(h):null,h!==null&&(w=$a(h),h!==w||h.tag!==5&&h.tag!==6)&&(h=null)):(p=null,h=c),p!==h)){if(m=B0,k="onMouseLeave",g="onMouseEnter",b="mouse",(r==="pointerout"||r==="pointerover")&&(m=V0,k="onPointerLeave",g="onPointerEnter",b="pointer"),w=p==null?f:xl(p),R=h==null?f:xl(h),f=new m(k,b+"leave",p,t,u),f.target=w,f.relatedTarget=R,k=null,Sa(u)===c&&(m=new m(g,b+"enter",h,t,u),m.target=R,m.relatedTarget=w,k=m),w=k,p&&h)t:{for(m=p,g=h,b=0,R=m;R;R=el(R))b++;for(R=0,k=g;k;k=el(k))R++;for(;0<b-R;)m=el(m),b--;for(;0<R-b;)g=el(g),R--;for(;b--;){if(m===g||g!==null&&m===g.alternate)break t;m=el(m),g=el(g)}m=null}else m=null;p!==null&&Z0(d,f,p,m,!1),h!==null&&w!==null&&Z0(d,w,h,m,!0)}}e:{if(f=c?xl(c):window,p=f.nodeName&&f.nodeName.toLowerCase(),p==="select"||p==="input"&&f.type==="file")var O=H2;else if(q0(f))if(nO)O=X2;else{O=Y2;var T=z2}else(p=f.nodeName)&&p.toLowerCase()==="input"&&(f.type==="checkbox"||f.type==="radio")&&(O=J2);if(O&&(O=O(r,c))){rO(d,O,t,u);break e}T&&T(r,f,c),r==="focusout"&&(T=f._wrapperState)&&T.controlled&&f.type==="number"&&Wy(f,"number",f.value)}switch(T=c?xl(c):window,r){case"focusin":(q0(T)||T.contentEditable==="true")&&(kl=T,rS=c,Gu=null);break;case"focusout":Gu=rS=kl=null;break;case"mousedown":nS=!0;break;case"contextmenu":case"mouseup":case"dragend":nS=!1,J0(d,t,u);break;case"selectionchange":if(ej)break;case"keydown":case"keyup":J0(d,t,u)}var x;if(q_)e:{switch(r){case"compositionstart":var C="onCompositionStart";break e;case"compositionend":C="onCompositionEnd";break e;case"compositionupdate":C="onCompositionUpdate";break e}C=void 0}else Cl?eO(r,t)&&(C="onCompositionEnd"):r==="keydown"&&t.keyCode===229&&(C="onCompositionStart");C&&(Zx&&t.locale!=="ko"&&(Cl||C!=="onCompositionStart"?C==="onCompositionEnd"&&Cl&&(x=Qx()):(ps=u,V_="value"in ps?ps.value:ps.textContent,Cl=!0)),T=pp(c,C),0<T.length&&(C=new K0(C,r,null,t,u),d.push({event:C,listeners:T}),x?C.data=x:(x=tO(t),x!==null&&(C.data=x)))),(x=V2?$2(r,t):W2(r,t))&&(c=pp(c,"onBeforeInput"),0<c.length&&(u=new K0("onBeforeInput","beforeinput",null,t,u),d.push({event:u,listeners:c}),u.data=x))}hO(d,e)})}function Sd(r,e,t){return{instance:r,listener:e,currentTarget:t}}function pp(r,e){for(var t=e+"Capture",n=[];r!==null;){var i=r,o=i.stateNode;i.tag===5&&o!==null&&(i=o,o=fd(r,t),o!=null&&n.unshift(Sd(r,o,i)),o=fd(r,e),o!=null&&n.push(Sd(r,o,i))),r=r.return}return n}function el(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function Z0(r,e,t,n,i){for(var o=e._reactName,s=[];t!==null&&t!==n;){var a=t,l=a.alternate,c=a.stateNode;if(l!==null&&l===n)break;a.tag===5&&c!==null&&(a=c,i?(l=fd(t,o),l!=null&&s.unshift(Sd(t,l,a))):i||(l=fd(t,o),l!=null&&s.push(Sd(t,l,a)))),t=t.return}s.length!==0&&r.push({event:e,listeners:s})}var ij=/\r\n?/g,oj=/\u0000|\uFFFD/g;function eT(r){return(typeof r=="string"?r:""+r).replace(ij,`
38
+ `).replace(oj,"")}function Vf(r,e,t){if(e=eT(e),eT(r)!==e&&t)throw Error(he(425))}function vp(){}var iS=null,oS=null;function sS(r,e){return r==="textarea"||r==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var aS=typeof setTimeout=="function"?setTimeout:void 0,sj=typeof clearTimeout=="function"?clearTimeout:void 0,tT=typeof Promise=="function"?Promise:void 0,aj=typeof queueMicrotask=="function"?queueMicrotask:typeof tT<"u"?function(r){return tT.resolve(null).then(r).catch(lj)}:aS;function lj(r){setTimeout(function(){throw r})}function cg(r,e){var t=e,n=0;do{var i=t.nextSibling;if(r.removeChild(t),i&&i.nodeType===8)if(t=i.data,t==="/$"){if(n===0){r.removeChild(i),vd(e);return}n--}else t!=="$"&&t!=="$?"&&t!=="$!"||n++;t=i}while(t);vd(e)}function _s(r){for(;r!=null;r=r.nextSibling){var e=r.nodeType;if(e===1||e===3)break;if(e===8){if(e=r.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return r}function rT(r){r=r.previousSibling;for(var e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="$"||t==="$!"||t==="$?"){if(e===0)return r;e--}else t==="/$"&&e++}r=r.previousSibling}return null}var Oc=Math.random().toString(36).slice(2),Wi="__reactFiber$"+Oc,bd="__reactProps$"+Oc,Oo="__reactContainer$"+Oc,lS="__reactEvents$"+Oc,cj="__reactListeners$"+Oc,uj="__reactHandles$"+Oc;function Sa(r){var e=r[Wi];if(e)return e;for(var t=r.parentNode;t;){if(e=t[Oo]||t[Wi]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(r=rT(r);r!==null;){if(t=r[Wi])return t;r=rT(r)}return e}r=t,t=r.parentNode}return null}function nf(r){return r=r[Wi]||r[Oo],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function xl(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(he(33))}function Ev(r){return r[bd]||null}var cS=[],Ol=-1;function Fs(r){return{current:r}}function It(r){0>Ol||(r.current=cS[Ol],cS[Ol]=null,Ol--)}function wt(r,e){Ol++,cS[Ol]=r.current,r.current=e}var Os={},qr=Fs(Os),_n=Fs(!1),Ia=Os;function ic(r,e){var t=r.type.contextTypes;if(!t)return Os;var n=r.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in t)i[o]=e[o];return n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=e,r.__reactInternalMemoizedMaskedChildContext=i),i}function En(r){return r=r.childContextTypes,r!=null}function mp(){It(_n),It(qr)}function nT(r,e,t){if(qr.current!==Os)throw Error(he(168));wt(qr,e),wt(_n,t)}function vO(r,e,t){var n=r.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return t;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(he(108,zU(r)||"Unknown",i));return Ut({},t,n)}function gp(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||Os,Ia=qr.current,wt(qr,r),wt(_n,_n.current),!0}function iT(r,e,t){var n=r.stateNode;if(!n)throw Error(he(169));t?(r=vO(r,e,Ia),n.__reactInternalMemoizedMergedChildContext=r,It(_n),It(qr),wt(qr,r)):It(_n),wt(_n,t)}var go=null,wv=!1,ug=!1;function mO(r){go===null?go=[r]:go.push(r)}function dj(r){wv=!0,mO(r)}function Bs(){if(!ug&&go!==null){ug=!0;var r=0,e=ft;try{var t=go;for(ft=1;r<t.length;r++){var n=t[r];do n=n(!0);while(n!==null)}go=null,wv=!1}catch(i){throw go!==null&&(go=go.slice(r+1)),Kx(j_,Bs),i}finally{ft=e,ug=!1}}return null}var Pl=[],Ml=0,yp=null,Sp=0,Wn=[],qn=0,xa=null,bo=1,_o="";function sa(r,e){Pl[Ml++]=Sp,Pl[Ml++]=yp,yp=r,Sp=e}function gO(r,e,t){Wn[qn++]=bo,Wn[qn++]=_o,Wn[qn++]=xa,xa=r;var n=bo;r=_o;var i=32-Si(n)-1;n&=~(1<<i),t+=1;var o=32-Si(e)+i;if(30<o){var s=i-i%5;o=(n&(1<<s)-1).toString(32),n>>=s,i-=s,bo=1<<32-Si(e)+i|t<<i|n,_o=o+r}else bo=1<<o|t<<i|n,_o=r}function H_(r){r.return!==null&&(sa(r,1),gO(r,1,0))}function z_(r){for(;r===yp;)yp=Pl[--Ml],Pl[Ml]=null,Sp=Pl[--Ml],Pl[Ml]=null;for(;r===xa;)xa=Wn[--qn],Wn[qn]=null,_o=Wn[--qn],Wn[qn]=null,bo=Wn[--qn],Wn[qn]=null}var Un=null,Ln=null,Pt=!1,vi=null;function yO(r,e){var t=Gn(5,null,null,0);t.elementType="DELETED",t.stateNode=e,t.return=r,e=r.deletions,e===null?(r.deletions=[t],r.flags|=16):e.push(t)}function oT(r,e){switch(r.tag){case 5:var t=r.type;return e=e.nodeType!==1||t.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(r.stateNode=e,Un=r,Ln=_s(e.firstChild),!0):!1;case 6:return e=r.pendingProps===""||e.nodeType!==3?null:e,e!==null?(r.stateNode=e,Un=r,Ln=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=xa!==null?{id:bo,overflow:_o}:null,r.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=Gn(18,null,null,0),t.stateNode=e,t.return=r,r.child=t,Un=r,Ln=null,!0):!1;default:return!1}}function uS(r){return(r.mode&1)!==0&&(r.flags&128)===0}function dS(r){if(Pt){var e=Ln;if(e){var t=e;if(!oT(r,e)){if(uS(r))throw Error(he(418));e=_s(t.nextSibling);var n=Un;e&&oT(r,e)?yO(n,t):(r.flags=r.flags&-4097|2,Pt=!1,Un=r)}}else{if(uS(r))throw Error(he(418));r.flags=r.flags&-4097|2,Pt=!1,Un=r}}}function sT(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;Un=r}function $f(r){if(r!==Un)return!1;if(!Pt)return sT(r),Pt=!0,!1;var e;if((e=r.tag!==3)&&!(e=r.tag!==5)&&(e=r.type,e=e!=="head"&&e!=="body"&&!sS(r.type,r.memoizedProps)),e&&(e=Ln)){if(uS(r))throw SO(),Error(he(418));for(;e;)yO(r,e),e=_s(e.nextSibling)}if(sT(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(he(317));e:{for(r=r.nextSibling,e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="/$"){if(e===0){Ln=_s(r.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}r=r.nextSibling}Ln=null}}else Ln=Un?_s(r.stateNode.nextSibling):null;return!0}function SO(){for(var r=Ln;r;)r=_s(r.nextSibling)}function oc(){Ln=Un=null,Pt=!1}function Y_(r){vi===null?vi=[r]:vi.push(r)}var fj=Lo.ReactCurrentBatchConfig;function ru(r,e,t){if(r=t.ref,r!==null&&typeof r!="function"&&typeof r!="object"){if(t._owner){if(t=t._owner,t){if(t.tag!==1)throw Error(he(309));var n=t.stateNode}if(!n)throw Error(he(147,r));var i=n,o=""+r;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===o?e.ref:(e=function(s){var a=i.refs;s===null?delete a[o]:a[o]=s},e._stringRef=o,e)}if(typeof r!="string")throw Error(he(284));if(!t._owner)throw Error(he(290,r))}return r}function Wf(r,e){throw r=Object.prototype.toString.call(e),Error(he(31,r==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":r))}function aT(r){var e=r._init;return e(r._payload)}function bO(r){function e(g,b){if(r){var R=g.deletions;R===null?(g.deletions=[b],g.flags|=16):R.push(b)}}function t(g,b){if(!r)return null;for(;b!==null;)e(g,b),b=b.sibling;return null}function n(g,b){for(g=new Map;b!==null;)b.key!==null?g.set(b.key,b):g.set(b.index,b),b=b.sibling;return g}function i(g,b){return g=Rs(g,b),g.index=0,g.sibling=null,g}function o(g,b,R){return g.index=R,r?(R=g.alternate,R!==null?(R=R.index,R<b?(g.flags|=2,b):R):(g.flags|=2,b)):(g.flags|=1048576,b)}function s(g){return r&&g.alternate===null&&(g.flags|=2),g}function a(g,b,R,k){return b===null||b.tag!==6?(b=gg(R,g.mode,k),b.return=g,b):(b=i(b,R),b.return=g,b)}function l(g,b,R,k){var O=R.type;return O===Rl?u(g,b,R.props.children,k,R.key):b!==null&&(b.elementType===O||typeof O=="object"&&O!==null&&O.$$typeof===as&&aT(O)===b.type)?(k=i(b,R.props),k.ref=ru(g,b,R),k.return=g,k):(k=Lh(R.type,R.key,R.props,null,g.mode,k),k.ref=ru(g,b,R),k.return=g,k)}function c(g,b,R,k){return b===null||b.tag!==4||b.stateNode.containerInfo!==R.containerInfo||b.stateNode.implementation!==R.implementation?(b=yg(R,g.mode,k),b.return=g,b):(b=i(b,R.children||[]),b.return=g,b)}function u(g,b,R,k,O){return b===null||b.tag!==7?(b=Ta(R,g.mode,k,O),b.return=g,b):(b=i(b,R),b.return=g,b)}function d(g,b,R){if(typeof b=="string"&&b!==""||typeof b=="number")return b=gg(""+b,g.mode,R),b.return=g,b;if(typeof b=="object"&&b!==null){switch(b.$$typeof){case Af:return R=Lh(b.type,b.key,b.props,null,g.mode,R),R.ref=ru(g,null,b),R.return=g,R;case Tl:return b=yg(b,g.mode,R),b.return=g,b;case as:var k=b._init;return d(g,k(b._payload),R)}if(ku(b)||Xc(b))return b=Ta(b,g.mode,R,null),b.return=g,b;Wf(g,b)}return null}function f(g,b,R,k){var O=b!==null?b.key:null;if(typeof R=="string"&&R!==""||typeof R=="number")return O!==null?null:a(g,b,""+R,k);if(typeof R=="object"&&R!==null){switch(R.$$typeof){case Af:return R.key===O?l(g,b,R,k):null;case Tl:return R.key===O?c(g,b,R,k):null;case as:return O=R._init,f(g,b,O(R._payload),k)}if(ku(R)||Xc(R))return O!==null?null:u(g,b,R,k,null);Wf(g,R)}return null}function p(g,b,R,k,O){if(typeof k=="string"&&k!==""||typeof k=="number")return g=g.get(R)||null,a(b,g,""+k,O);if(typeof k=="object"&&k!==null){switch(k.$$typeof){case Af:return g=g.get(k.key===null?R:k.key)||null,l(b,g,k,O);case Tl:return g=g.get(k.key===null?R:k.key)||null,c(b,g,k,O);case as:var T=k._init;return p(g,b,R,T(k._payload),O)}if(ku(k)||Xc(k))return g=g.get(R)||null,u(b,g,k,O,null);Wf(b,k)}return null}function h(g,b,R,k){for(var O=null,T=null,x=b,C=b=0,N=null;x!==null&&C<R.length;C++){x.index>C?(N=x,x=null):N=x.sibling;var F=f(g,x,R[C],k);if(F===null){x===null&&(x=N);break}r&&x&&F.alternate===null&&e(g,x),b=o(F,b,C),T===null?O=F:T.sibling=F,T=F,x=N}if(C===R.length)return t(g,x),Pt&&sa(g,C),O;if(x===null){for(;C<R.length;C++)x=d(g,R[C],k),x!==null&&(b=o(x,b,C),T===null?O=x:T.sibling=x,T=x);return Pt&&sa(g,C),O}for(x=n(g,x);C<R.length;C++)N=p(x,g,C,R[C],k),N!==null&&(r&&N.alternate!==null&&x.delete(N.key===null?C:N.key),b=o(N,b,C),T===null?O=N:T.sibling=N,T=N);return r&&x.forEach(function(H){return e(g,H)}),Pt&&sa(g,C),O}function m(g,b,R,k){var O=Xc(R);if(typeof O!="function")throw Error(he(150));if(R=O.call(R),R==null)throw Error(he(151));for(var T=O=null,x=b,C=b=0,N=null,F=R.next();x!==null&&!F.done;C++,F=R.next()){x.index>C?(N=x,x=null):N=x.sibling;var H=f(g,x,F.value,k);if(H===null){x===null&&(x=N);break}r&&x&&H.alternate===null&&e(g,x),b=o(H,b,C),T===null?O=H:T.sibling=H,T=H,x=N}if(F.done)return t(g,x),Pt&&sa(g,C),O;if(x===null){for(;!F.done;C++,F=R.next())F=d(g,F.value,k),F!==null&&(b=o(F,b,C),T===null?O=F:T.sibling=F,T=F);return Pt&&sa(g,C),O}for(x=n(g,x);!F.done;C++,F=R.next())F=p(x,g,C,F.value,k),F!==null&&(r&&F.alternate!==null&&x.delete(F.key===null?C:F.key),b=o(F,b,C),T===null?O=F:T.sibling=F,T=F);return r&&x.forEach(function(ie){return e(g,ie)}),Pt&&sa(g,C),O}function w(g,b,R,k){if(typeof R=="object"&&R!==null&&R.type===Rl&&R.key===null&&(R=R.props.children),typeof R=="object"&&R!==null){switch(R.$$typeof){case Af:e:{for(var O=R.key,T=b;T!==null;){if(T.key===O){if(O=R.type,O===Rl){if(T.tag===7){t(g,T.sibling),b=i(T,R.props.children),b.return=g,g=b;break e}}else if(T.elementType===O||typeof O=="object"&&O!==null&&O.$$typeof===as&&aT(O)===T.type){t(g,T.sibling),b=i(T,R.props),b.ref=ru(g,T,R),b.return=g,g=b;break e}t(g,T);break}else e(g,T);T=T.sibling}R.type===Rl?(b=Ta(R.props.children,g.mode,k,R.key),b.return=g,g=b):(k=Lh(R.type,R.key,R.props,null,g.mode,k),k.ref=ru(g,b,R),k.return=g,g=k)}return s(g);case Tl:e:{for(T=R.key;b!==null;){if(b.key===T)if(b.tag===4&&b.stateNode.containerInfo===R.containerInfo&&b.stateNode.implementation===R.implementation){t(g,b.sibling),b=i(b,R.children||[]),b.return=g,g=b;break e}else{t(g,b);break}else e(g,b);b=b.sibling}b=yg(R,g.mode,k),b.return=g,g=b}return s(g);case as:return T=R._init,w(g,b,T(R._payload),k)}if(ku(R))return h(g,b,R,k);if(Xc(R))return m(g,b,R,k);Wf(g,R)}return typeof R=="string"&&R!==""||typeof R=="number"?(R=""+R,b!==null&&b.tag===6?(t(g,b.sibling),b=i(b,R),b.return=g,g=b):(t(g,b),b=gg(R,g.mode,k),b.return=g,g=b),s(g)):t(g,b)}return w}var sc=bO(!0),_O=bO(!1),bp=Fs(null),_p=null,Al=null,J_=null;function X_(){J_=Al=_p=null}function Q_(r){var e=bp.current;It(bp),r._currentValue=e}function fS(r,e,t){for(;r!==null;){var n=r.alternate;if((r.childLanes&e)!==e?(r.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),r===t)break;r=r.return}}function $l(r,e){_p=r,J_=Al=null,r=r.dependencies,r!==null&&r.firstContext!==null&&(r.lanes&e&&(Sn=!0),r.firstContext=null)}function Xn(r){var e=r._currentValue;if(J_!==r)if(r={context:r,memoizedValue:e,next:null},Al===null){if(_p===null)throw Error(he(308));Al=r,_p.dependencies={lanes:0,firstContext:r}}else Al=Al.next=r;return e}var ba=null;function Z_(r){ba===null?ba=[r]:ba.push(r)}function EO(r,e,t,n){var i=e.interleaved;return i===null?(t.next=t,Z_(e)):(t.next=i.next,i.next=t),e.interleaved=t,Po(r,n)}function Po(r,e){r.lanes|=e;var t=r.alternate;for(t!==null&&(t.lanes|=e),t=r,r=r.return;r!==null;)r.childLanes|=e,t=r.alternate,t!==null&&(t.childLanes|=e),t=r,r=r.return;return t.tag===3?t.stateNode:null}var ls=!1;function eE(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function wO(r,e){r=r.updateQueue,e.updateQueue===r&&(e.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function Ro(r,e){return{eventTime:r,lane:e,tag:0,payload:null,callback:null,next:null}}function Es(r,e,t){var n=r.updateQueue;if(n===null)return null;if(n=n.shared,st&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Po(r,t)}return i=n.interleaved,i===null?(e.next=e,Z_(n)):(e.next=i.next,i.next=e),n.interleaved=e,Po(r,t)}function Oh(r,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194240)!==0)){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,F_(r,t)}}function lT(r,e){var t=r.updateQueue,n=r.alternate;if(n!==null&&(n=n.updateQueue,t===n)){var i=null,o=null;if(t=t.firstBaseUpdate,t!==null){do{var s={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};o===null?i=o=s:o=o.next=s,t=t.next}while(t!==null);o===null?i=o=e:o=o.next=e}else i=o=e;t={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:n.shared,effects:n.effects},r.updateQueue=t;return}r=t.lastBaseUpdate,r===null?t.firstBaseUpdate=e:r.next=e,t.lastBaseUpdate=e}function Ep(r,e,t,n){var i=r.updateQueue;ls=!1;var o=i.firstBaseUpdate,s=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var l=a,c=l.next;l.next=null,s===null?o=c:s.next=c,s=l;var u=r.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==s&&(a===null?u.firstBaseUpdate=c:a.next=c,u.lastBaseUpdate=l))}if(o!==null){var d=i.baseState;s=0,u=c=l=null,a=o;do{var f=a.lane,p=a.eventTime;if((n&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var h=r,m=a;switch(f=e,p=t,m.tag){case 1:if(h=m.payload,typeof h=="function"){d=h.call(p,d,f);break e}d=h;break e;case 3:h.flags=h.flags&-65537|128;case 0:if(h=m.payload,f=typeof h=="function"?h.call(p,d,f):h,f==null)break e;d=Ut({},d,f);break e;case 2:ls=!0}}a.callback!==null&&a.lane!==0&&(r.flags|=64,f=i.effects,f===null?i.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(c=u=p,l=d):u=u.next=p,s|=f;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;f=a,a=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(u===null&&(l=d),i.baseState=l,i.firstBaseUpdate=c,i.lastBaseUpdate=u,e=i.shared.interleaved,e!==null){i=e;do s|=i.lane,i=i.next;while(i!==e)}else o===null&&(i.shared.lanes=0);Pa|=s,r.lanes=s,r.memoizedState=d}}function cT(r,e,t){if(r=e.effects,e.effects=null,r!==null)for(e=0;e<r.length;e++){var n=r[e],i=n.callback;if(i!==null){if(n.callback=null,n=t,typeof i!="function")throw Error(he(191,i));i.call(n)}}}var of={},Yi=Fs(of),_d=Fs(of),Ed=Fs(of);function _a(r){if(r===of)throw Error(he(174));return r}function tE(r,e){switch(wt(Ed,e),wt(_d,r),wt(Yi,of),r=e.nodeType,r){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:Gy(null,"");break;default:r=r===8?e.parentNode:e,e=r.namespaceURI||null,r=r.tagName,e=Gy(e,r)}It(Yi),wt(Yi,e)}function ac(){It(Yi),It(_d),It(Ed)}function TO(r){_a(Ed.current);var e=_a(Yi.current),t=Gy(e,r.type);e!==t&&(wt(_d,r),wt(Yi,t))}function rE(r){_d.current===r&&(It(Yi),It(_d))}var Nt=Fs(0);function wp(r){for(var e=r;e!==null;){if(e.tag===13){var t=e.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var dg=[];function nE(){for(var r=0;r<dg.length;r++)dg[r]._workInProgressVersionPrimary=null;dg.length=0}var Ph=Lo.ReactCurrentDispatcher,fg=Lo.ReactCurrentBatchConfig,Oa=0,Lt=null,ur=null,_r=null,Tp=!1,Hu=!1,wd=0,hj=0;function jr(){throw Error(he(321))}function iE(r,e){if(e===null)return!1;for(var t=0;t<e.length&&t<r.length;t++)if(!Ti(r[t],e[t]))return!1;return!0}function oE(r,e,t,n,i,o){if(Oa=o,Lt=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,Ph.current=r===null||r.memoizedState===null?gj:yj,r=t(n,i),Hu){o=0;do{if(Hu=!1,wd=0,25<=o)throw Error(he(301));o+=1,_r=ur=null,e.updateQueue=null,Ph.current=Sj,r=t(n,i)}while(Hu)}if(Ph.current=Rp,e=ur!==null&&ur.next!==null,Oa=0,_r=ur=Lt=null,Tp=!1,e)throw Error(he(300));return r}function sE(){var r=wd!==0;return wd=0,r}function ji(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return _r===null?Lt.memoizedState=_r=r:_r=_r.next=r,_r}function Qn(){if(ur===null){var r=Lt.alternate;r=r!==null?r.memoizedState:null}else r=ur.next;var e=_r===null?Lt.memoizedState:_r.next;if(e!==null)_r=e,ur=r;else{if(r===null)throw Error(he(310));ur=r,r={memoizedState:ur.memoizedState,baseState:ur.baseState,baseQueue:ur.baseQueue,queue:ur.queue,next:null},_r===null?Lt.memoizedState=_r=r:_r=_r.next=r}return _r}function Td(r,e){return typeof e=="function"?e(r):e}function hg(r){var e=Qn(),t=e.queue;if(t===null)throw Error(he(311));t.lastRenderedReducer=r;var n=ur,i=n.baseQueue,o=t.pending;if(o!==null){if(i!==null){var s=i.next;i.next=o.next,o.next=s}n.baseQueue=i=o,t.pending=null}if(i!==null){o=i.next,n=n.baseState;var a=s=null,l=null,c=o;do{var u=c.lane;if((Oa&u)===u)l!==null&&(l=l.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),n=c.hasEagerState?c.eagerState:r(n,c.action);else{var d={lane:u,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};l===null?(a=l=d,s=n):l=l.next=d,Lt.lanes|=u,Pa|=u}c=c.next}while(c!==null&&c!==o);l===null?s=n:l.next=a,Ti(n,e.memoizedState)||(Sn=!0),e.memoizedState=n,e.baseState=s,e.baseQueue=l,t.lastRenderedState=n}if(r=t.interleaved,r!==null){i=r;do o=i.lane,Lt.lanes|=o,Pa|=o,i=i.next;while(i!==r)}else i===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function pg(r){var e=Qn(),t=e.queue;if(t===null)throw Error(he(311));t.lastRenderedReducer=r;var n=t.dispatch,i=t.pending,o=e.memoizedState;if(i!==null){t.pending=null;var s=i=i.next;do o=r(o,s.action),s=s.next;while(s!==i);Ti(o,e.memoizedState)||(Sn=!0),e.memoizedState=o,e.baseQueue===null&&(e.baseState=o),t.lastRenderedState=o}return[o,n]}function RO(){}function CO(r,e){var t=Lt,n=Qn(),i=e(),o=!Ti(n.memoizedState,i);if(o&&(n.memoizedState=i,Sn=!0),n=n.queue,aE(xO.bind(null,t,n,r),[r]),n.getSnapshot!==e||o||_r!==null&&_r.memoizedState.tag&1){if(t.flags|=2048,Rd(9,IO.bind(null,t,n,i,e),void 0,null),Tr===null)throw Error(he(349));Oa&30||kO(t,e,i)}return i}function kO(r,e,t){r.flags|=16384,r={getSnapshot:e,value:t},e=Lt.updateQueue,e===null?(e={lastEffect:null,stores:null},Lt.updateQueue=e,e.stores=[r]):(t=e.stores,t===null?e.stores=[r]:t.push(r))}function IO(r,e,t,n){e.value=t,e.getSnapshot=n,OO(e)&&PO(r)}function xO(r,e,t){return t(function(){OO(e)&&PO(r)})}function OO(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!Ti(r,t)}catch{return!0}}function PO(r){var e=Po(r,1);e!==null&&bi(e,r,1,-1)}function uT(r){var e=ji();return typeof r=="function"&&(r=r()),e.memoizedState=e.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Td,lastRenderedState:r},e.queue=r,r=r.dispatch=mj.bind(null,Lt,r),[e.memoizedState,r]}function Rd(r,e,t,n){return r={tag:r,create:e,destroy:t,deps:n,next:null},e=Lt.updateQueue,e===null?(e={lastEffect:null,stores:null},Lt.updateQueue=e,e.lastEffect=r.next=r):(t=e.lastEffect,t===null?e.lastEffect=r.next=r:(n=t.next,t.next=r,r.next=n,e.lastEffect=r)),r}function MO(){return Qn().memoizedState}function Mh(r,e,t,n){var i=ji();Lt.flags|=r,i.memoizedState=Rd(1|e,t,void 0,n===void 0?null:n)}function Tv(r,e,t,n){var i=Qn();n=n===void 0?null:n;var o=void 0;if(ur!==null){var s=ur.memoizedState;if(o=s.destroy,n!==null&&iE(n,s.deps)){i.memoizedState=Rd(e,t,o,n);return}}Lt.flags|=r,i.memoizedState=Rd(1|e,t,o,n)}function dT(r,e){return Mh(8390656,8,r,e)}function aE(r,e){return Tv(2048,8,r,e)}function AO(r,e){return Tv(4,2,r,e)}function DO(r,e){return Tv(4,4,r,e)}function NO(r,e){if(typeof e=="function")return r=r(),e(r),function(){e(null)};if(e!=null)return r=r(),e.current=r,function(){e.current=null}}function LO(r,e,t){return t=t!=null?t.concat([r]):null,Tv(4,4,NO.bind(null,e,r),t)}function lE(){}function UO(r,e){var t=Qn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&iE(e,n[1])?n[0]:(t.memoizedState=[r,e],r)}function jO(r,e){var t=Qn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&iE(e,n[1])?n[0]:(r=r(),t.memoizedState=[r,e],r)}function FO(r,e,t){return Oa&21?(Ti(t,e)||(t=Wx(),Lt.lanes|=t,Pa|=t,r.baseState=!0),e):(r.baseState&&(r.baseState=!1,Sn=!0),r.memoizedState=t)}function pj(r,e){var t=ft;ft=t!==0&&4>t?t:4,r(!0);var n=fg.transition;fg.transition={};try{r(!1),e()}finally{ft=t,fg.transition=n}}function BO(){return Qn().memoizedState}function vj(r,e,t){var n=Ts(r);if(t={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null},KO(r))VO(e,t);else if(t=EO(r,e,t,n),t!==null){var i=Zr();bi(t,r,n,i),$O(t,e,n)}}function mj(r,e,t){var n=Ts(r),i={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null};if(KO(r))VO(e,i);else{var o=r.alternate;if(r.lanes===0&&(o===null||o.lanes===0)&&(o=e.lastRenderedReducer,o!==null))try{var s=e.lastRenderedState,a=o(s,t);if(i.hasEagerState=!0,i.eagerState=a,Ti(a,s)){var l=e.interleaved;l===null?(i.next=i,Z_(e)):(i.next=l.next,l.next=i),e.interleaved=i;return}}catch{}finally{}t=EO(r,e,i,n),t!==null&&(i=Zr(),bi(t,r,n,i),$O(t,e,n))}}function KO(r){var e=r.alternate;return r===Lt||e!==null&&e===Lt}function VO(r,e){Hu=Tp=!0;var t=r.pending;t===null?e.next=e:(e.next=t.next,t.next=e),r.pending=e}function $O(r,e,t){if(t&4194240){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,F_(r,t)}}var Rp={readContext:Xn,useCallback:jr,useContext:jr,useEffect:jr,useImperativeHandle:jr,useInsertionEffect:jr,useLayoutEffect:jr,useMemo:jr,useReducer:jr,useRef:jr,useState:jr,useDebugValue:jr,useDeferredValue:jr,useTransition:jr,useMutableSource:jr,useSyncExternalStore:jr,useId:jr,unstable_isNewReconciler:!1},gj={readContext:Xn,useCallback:function(r,e){return ji().memoizedState=[r,e===void 0?null:e],r},useContext:Xn,useEffect:dT,useImperativeHandle:function(r,e,t){return t=t!=null?t.concat([r]):null,Mh(4194308,4,NO.bind(null,e,r),t)},useLayoutEffect:function(r,e){return Mh(4194308,4,r,e)},useInsertionEffect:function(r,e){return Mh(4,2,r,e)},useMemo:function(r,e){var t=ji();return e=e===void 0?null:e,r=r(),t.memoizedState=[r,e],r},useReducer:function(r,e,t){var n=ji();return e=t!==void 0?t(e):e,n.memoizedState=n.baseState=e,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:e},n.queue=r,r=r.dispatch=vj.bind(null,Lt,r),[n.memoizedState,r]},useRef:function(r){var e=ji();return r={current:r},e.memoizedState=r},useState:uT,useDebugValue:lE,useDeferredValue:function(r){return ji().memoizedState=r},useTransition:function(){var r=uT(!1),e=r[0];return r=pj.bind(null,r[1]),ji().memoizedState=r,[e,r]},useMutableSource:function(){},useSyncExternalStore:function(r,e,t){var n=Lt,i=ji();if(Pt){if(t===void 0)throw Error(he(407));t=t()}else{if(t=e(),Tr===null)throw Error(he(349));Oa&30||kO(n,e,t)}i.memoizedState=t;var o={value:t,getSnapshot:e};return i.queue=o,dT(xO.bind(null,n,o,r),[r]),n.flags|=2048,Rd(9,IO.bind(null,n,o,t,e),void 0,null),t},useId:function(){var r=ji(),e=Tr.identifierPrefix;if(Pt){var t=_o,n=bo;t=(n&~(1<<32-Si(n)-1)).toString(32)+t,e=":"+e+"R"+t,t=wd++,0<t&&(e+="H"+t.toString(32)),e+=":"}else t=hj++,e=":"+e+"r"+t.toString(32)+":";return r.memoizedState=e},unstable_isNewReconciler:!1},yj={readContext:Xn,useCallback:UO,useContext:Xn,useEffect:aE,useImperativeHandle:LO,useInsertionEffect:AO,useLayoutEffect:DO,useMemo:jO,useReducer:hg,useRef:MO,useState:function(){return hg(Td)},useDebugValue:lE,useDeferredValue:function(r){var e=Qn();return FO(e,ur.memoizedState,r)},useTransition:function(){var r=hg(Td)[0],e=Qn().memoizedState;return[r,e]},useMutableSource:RO,useSyncExternalStore:CO,useId:BO,unstable_isNewReconciler:!1},Sj={readContext:Xn,useCallback:UO,useContext:Xn,useEffect:aE,useImperativeHandle:LO,useInsertionEffect:AO,useLayoutEffect:DO,useMemo:jO,useReducer:pg,useRef:MO,useState:function(){return pg(Td)},useDebugValue:lE,useDeferredValue:function(r){var e=Qn();return ur===null?e.memoizedState=r:FO(e,ur.memoizedState,r)},useTransition:function(){var r=pg(Td)[0],e=Qn().memoizedState;return[r,e]},useMutableSource:RO,useSyncExternalStore:CO,useId:BO,unstable_isNewReconciler:!1};function ui(r,e){if(r&&r.defaultProps){e=Ut({},e),r=r.defaultProps;for(var t in r)e[t]===void 0&&(e[t]=r[t]);return e}return e}function hS(r,e,t,n){e=r.memoizedState,t=t(n,e),t=t==null?e:Ut({},e,t),r.memoizedState=t,r.lanes===0&&(r.updateQueue.baseState=t)}var Rv={isMounted:function(r){return(r=r._reactInternals)?$a(r)===r:!1},enqueueSetState:function(r,e,t){r=r._reactInternals;var n=Zr(),i=Ts(r),o=Ro(n,i);o.payload=e,t!=null&&(o.callback=t),e=Es(r,o,i),e!==null&&(bi(e,r,i,n),Oh(e,r,i))},enqueueReplaceState:function(r,e,t){r=r._reactInternals;var n=Zr(),i=Ts(r),o=Ro(n,i);o.tag=1,o.payload=e,t!=null&&(o.callback=t),e=Es(r,o,i),e!==null&&(bi(e,r,i,n),Oh(e,r,i))},enqueueForceUpdate:function(r,e){r=r._reactInternals;var t=Zr(),n=Ts(r),i=Ro(t,n);i.tag=2,e!=null&&(i.callback=e),e=Es(r,i,n),e!==null&&(bi(e,r,n,t),Oh(e,r,n))}};function fT(r,e,t,n,i,o,s){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(n,o,s):e.prototype&&e.prototype.isPureReactComponent?!gd(t,n)||!gd(i,o):!0}function WO(r,e,t){var n=!1,i=Os,o=e.contextType;return typeof o=="object"&&o!==null?o=Xn(o):(i=En(e)?Ia:qr.current,n=e.contextTypes,o=(n=n!=null)?ic(r,i):Os),e=new e(t,o),r.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=Rv,r.stateNode=e,e._reactInternals=r,n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=o),e}function hT(r,e,t,n){r=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(t,n),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(t,n),e.state!==r&&Rv.enqueueReplaceState(e,e.state,null)}function pS(r,e,t,n){var i=r.stateNode;i.props=t,i.state=r.memoizedState,i.refs={},eE(r);var o=e.contextType;typeof o=="object"&&o!==null?i.context=Xn(o):(o=En(e)?Ia:qr.current,i.context=ic(r,o)),i.state=r.memoizedState,o=e.getDerivedStateFromProps,typeof o=="function"&&(hS(r,e,o,t),i.state=r.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(e=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),e!==i.state&&Rv.enqueueReplaceState(i,i.state,null),Ep(r,t,i,n),i.state=r.memoizedState),typeof i.componentDidMount=="function"&&(r.flags|=4194308)}function lc(r,e){try{var t="",n=e;do t+=HU(n),n=n.return;while(n);var i=t}catch(o){i=`
39
+ Error generating stack: `+o.message+`
40
+ `+o.stack}return{value:r,source:e,stack:i,digest:null}}function vg(r,e,t){return{value:r,source:null,stack:t??null,digest:e??null}}function vS(r,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var bj=typeof WeakMap=="function"?WeakMap:Map;function qO(r,e,t){t=Ro(-1,t),t.tag=3,t.payload={element:null};var n=e.value;return t.callback=function(){kp||(kp=!0,RS=n),vS(r,e)},t}function GO(r,e,t){t=Ro(-1,t),t.tag=3;var n=r.type.getDerivedStateFromError;if(typeof n=="function"){var i=e.value;t.payload=function(){return n(i)},t.callback=function(){vS(r,e)}}var o=r.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(t.callback=function(){vS(r,e),typeof n!="function"&&(ws===null?ws=new Set([this]):ws.add(this));var s=e.stack;this.componentDidCatch(e.value,{componentStack:s!==null?s:""})}),t}function pT(r,e,t){var n=r.pingCache;if(n===null){n=r.pingCache=new bj;var i=new Set;n.set(e,i)}else i=n.get(e),i===void 0&&(i=new Set,n.set(e,i));i.has(t)||(i.add(t),r=Dj.bind(null,r,e,t),e.then(r,r))}function vT(r){do{var e;if((e=r.tag===13)&&(e=r.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return r;r=r.return}while(r!==null);return null}function mT(r,e,t,n,i){return r.mode&1?(r.flags|=65536,r.lanes=i,r):(r===e?r.flags|=65536:(r.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(e=Ro(-1,1),e.tag=2,Es(t,e,1))),t.lanes|=1),r)}var _j=Lo.ReactCurrentOwner,Sn=!1;function Yr(r,e,t,n){e.child=r===null?_O(e,null,t,n):sc(e,r.child,t,n)}function gT(r,e,t,n,i){t=t.render;var o=e.ref;return $l(e,i),n=oE(r,e,t,n,o,i),t=sE(),r!==null&&!Sn?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,Mo(r,e,i)):(Pt&&t&&H_(e),e.flags|=1,Yr(r,e,n,i),e.child)}function yT(r,e,t,n,i){if(r===null){var o=t.type;return typeof o=="function"&&!mE(o)&&o.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=o,HO(r,e,o,n,i)):(r=Lh(t.type,null,n,e,e.mode,i),r.ref=e.ref,r.return=e,e.child=r)}if(o=r.child,!(r.lanes&i)){var s=o.memoizedProps;if(t=t.compare,t=t!==null?t:gd,t(s,n)&&r.ref===e.ref)return Mo(r,e,i)}return e.flags|=1,r=Rs(o,n),r.ref=e.ref,r.return=e,e.child=r}function HO(r,e,t,n,i){if(r!==null){var o=r.memoizedProps;if(gd(o,n)&&r.ref===e.ref)if(Sn=!1,e.pendingProps=n=o,(r.lanes&i)!==0)r.flags&131072&&(Sn=!0);else return e.lanes=r.lanes,Mo(r,e,i)}return mS(r,e,t,n,i)}function zO(r,e,t){var n=e.pendingProps,i=n.children,o=r!==null?r.memoizedState:null;if(n.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},wt(Nl,An),An|=t;else{if(!(t&1073741824))return r=o!==null?o.baseLanes|t:t,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:r,cachePool:null,transitions:null},e.updateQueue=null,wt(Nl,An),An|=r,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=o!==null?o.baseLanes:t,wt(Nl,An),An|=n}else o!==null?(n=o.baseLanes|t,e.memoizedState=null):n=t,wt(Nl,An),An|=n;return Yr(r,e,i,t),e.child}function YO(r,e){var t=e.ref;(r===null&&t!==null||r!==null&&r.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function mS(r,e,t,n,i){var o=En(t)?Ia:qr.current;return o=ic(e,o),$l(e,i),t=oE(r,e,t,n,o,i),n=sE(),r!==null&&!Sn?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,Mo(r,e,i)):(Pt&&n&&H_(e),e.flags|=1,Yr(r,e,t,i),e.child)}function ST(r,e,t,n,i){if(En(t)){var o=!0;gp(e)}else o=!1;if($l(e,i),e.stateNode===null)Ah(r,e),WO(e,t,n),pS(e,t,n,i),n=!0;else if(r===null){var s=e.stateNode,a=e.memoizedProps;s.props=a;var l=s.context,c=t.contextType;typeof c=="object"&&c!==null?c=Xn(c):(c=En(t)?Ia:qr.current,c=ic(e,c));var u=t.getDerivedStateFromProps,d=typeof u=="function"||typeof s.getSnapshotBeforeUpdate=="function";d||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==n||l!==c)&&hT(e,s,n,c),ls=!1;var f=e.memoizedState;s.state=f,Ep(e,n,s,i),l=e.memoizedState,a!==n||f!==l||_n.current||ls?(typeof u=="function"&&(hS(e,t,u,n),l=e.memoizedState),(a=ls||fT(e,t,a,n,f,l,c))?(d||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount()),typeof s.componentDidMount=="function"&&(e.flags|=4194308)):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=n,e.memoizedState=l),s.props=n,s.state=l,s.context=c,n=a):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),n=!1)}else{s=e.stateNode,wO(r,e),a=e.memoizedProps,c=e.type===e.elementType?a:ui(e.type,a),s.props=c,d=e.pendingProps,f=s.context,l=t.contextType,typeof l=="object"&&l!==null?l=Xn(l):(l=En(t)?Ia:qr.current,l=ic(e,l));var p=t.getDerivedStateFromProps;(u=typeof p=="function"||typeof s.getSnapshotBeforeUpdate=="function")||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==d||f!==l)&&hT(e,s,n,l),ls=!1,f=e.memoizedState,s.state=f,Ep(e,n,s,i);var h=e.memoizedState;a!==d||f!==h||_n.current||ls?(typeof p=="function"&&(hS(e,t,p,n),h=e.memoizedState),(c=ls||fT(e,t,c,n,f,h,l)||!1)?(u||typeof s.UNSAFE_componentWillUpdate!="function"&&typeof s.componentWillUpdate!="function"||(typeof s.componentWillUpdate=="function"&&s.componentWillUpdate(n,h,l),typeof s.UNSAFE_componentWillUpdate=="function"&&s.UNSAFE_componentWillUpdate(n,h,l)),typeof s.componentDidUpdate=="function"&&(e.flags|=4),typeof s.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof s.componentDidUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=1024),e.memoizedProps=n,e.memoizedState=h),s.props=n,s.state=h,s.context=l,n=c):(typeof s.componentDidUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=1024),n=!1)}return gS(r,e,t,n,o,i)}function gS(r,e,t,n,i,o){YO(r,e);var s=(e.flags&128)!==0;if(!n&&!s)return i&&iT(e,t,!1),Mo(r,e,o);n=e.stateNode,_j.current=e;var a=s&&typeof t.getDerivedStateFromError!="function"?null:n.render();return e.flags|=1,r!==null&&s?(e.child=sc(e,r.child,null,o),e.child=sc(e,null,a,o)):Yr(r,e,a,o),e.memoizedState=n.state,i&&iT(e,t,!0),e.child}function JO(r){var e=r.stateNode;e.pendingContext?nT(r,e.pendingContext,e.pendingContext!==e.context):e.context&&nT(r,e.context,!1),tE(r,e.containerInfo)}function bT(r,e,t,n,i){return oc(),Y_(i),e.flags|=256,Yr(r,e,t,n),e.child}var yS={dehydrated:null,treeContext:null,retryLane:0};function SS(r){return{baseLanes:r,cachePool:null,transitions:null}}function XO(r,e,t){var n=e.pendingProps,i=Nt.current,o=!1,s=(e.flags&128)!==0,a;if((a=s)||(a=r!==null&&r.memoizedState===null?!1:(i&2)!==0),a?(o=!0,e.flags&=-129):(r===null||r.memoizedState!==null)&&(i|=1),wt(Nt,i&1),r===null)return dS(e),r=e.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?(e.mode&1?r.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(s=n.children,r=n.fallback,o?(n=e.mode,o=e.child,s={mode:"hidden",children:s},!(n&1)&&o!==null?(o.childLanes=0,o.pendingProps=s):o=Iv(s,n,0,null),r=Ta(r,n,t,null),o.return=e,r.return=e,o.sibling=r,e.child=o,e.child.memoizedState=SS(t),e.memoizedState=yS,r):cE(e,s));if(i=r.memoizedState,i!==null&&(a=i.dehydrated,a!==null))return Ej(r,e,s,n,a,i,t);if(o){o=n.fallback,s=e.mode,i=r.child,a=i.sibling;var l={mode:"hidden",children:n.children};return!(s&1)&&e.child!==i?(n=e.child,n.childLanes=0,n.pendingProps=l,e.deletions=null):(n=Rs(i,l),n.subtreeFlags=i.subtreeFlags&14680064),a!==null?o=Rs(a,o):(o=Ta(o,s,t,null),o.flags|=2),o.return=e,n.return=e,n.sibling=o,e.child=n,n=o,o=e.child,s=r.child.memoizedState,s=s===null?SS(t):{baseLanes:s.baseLanes|t,cachePool:null,transitions:s.transitions},o.memoizedState=s,o.childLanes=r.childLanes&~t,e.memoizedState=yS,n}return o=r.child,r=o.sibling,n=Rs(o,{mode:"visible",children:n.children}),!(e.mode&1)&&(n.lanes=t),n.return=e,n.sibling=null,r!==null&&(t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)),e.child=n,e.memoizedState=null,n}function cE(r,e){return e=Iv({mode:"visible",children:e},r.mode,0,null),e.return=r,r.child=e}function qf(r,e,t,n){return n!==null&&Y_(n),sc(e,r.child,null,t),r=cE(e,e.pendingProps.children),r.flags|=2,e.memoizedState=null,r}function Ej(r,e,t,n,i,o,s){if(t)return e.flags&256?(e.flags&=-257,n=vg(Error(he(422))),qf(r,e,s,n)):e.memoizedState!==null?(e.child=r.child,e.flags|=128,null):(o=n.fallback,i=e.mode,n=Iv({mode:"visible",children:n.children},i,0,null),o=Ta(o,i,s,null),o.flags|=2,n.return=e,o.return=e,n.sibling=o,e.child=n,e.mode&1&&sc(e,r.child,null,s),e.child.memoizedState=SS(s),e.memoizedState=yS,o);if(!(e.mode&1))return qf(r,e,s,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var a=n.dgst;return n=a,o=Error(he(419)),n=vg(o,n,void 0),qf(r,e,s,n)}if(a=(s&r.childLanes)!==0,Sn||a){if(n=Tr,n!==null){switch(s&-s){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&(n.suspendedLanes|s)?0:i,i!==0&&i!==o.retryLane&&(o.retryLane=i,Po(r,i),bi(n,r,i,-1))}return vE(),n=vg(Error(he(421))),qf(r,e,s,n)}return i.data==="$?"?(e.flags|=128,e.child=r.child,e=Nj.bind(null,r),i._reactRetry=e,null):(r=o.treeContext,Ln=_s(i.nextSibling),Un=e,Pt=!0,vi=null,r!==null&&(Wn[qn++]=bo,Wn[qn++]=_o,Wn[qn++]=xa,bo=r.id,_o=r.overflow,xa=e),e=cE(e,n.children),e.flags|=4096,e)}function _T(r,e,t){r.lanes|=e;var n=r.alternate;n!==null&&(n.lanes|=e),fS(r.return,e,t)}function mg(r,e,t,n,i){var o=r.memoizedState;o===null?r.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:n,tail:t,tailMode:i}:(o.isBackwards=e,o.rendering=null,o.renderingStartTime=0,o.last=n,o.tail=t,o.tailMode=i)}function QO(r,e,t){var n=e.pendingProps,i=n.revealOrder,o=n.tail;if(Yr(r,e,n.children,t),n=Nt.current,n&2)n=n&1|2,e.flags|=128;else{if(r!==null&&r.flags&128)e:for(r=e.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&_T(r,t,e);else if(r.tag===19)_T(r,t,e);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===e)break e;for(;r.sibling===null;){if(r.return===null||r.return===e)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}n&=1}if(wt(Nt,n),!(e.mode&1))e.memoizedState=null;else switch(i){case"forwards":for(t=e.child,i=null;t!==null;)r=t.alternate,r!==null&&wp(r)===null&&(i=t),t=t.sibling;t=i,t===null?(i=e.child,e.child=null):(i=t.sibling,t.sibling=null),mg(e,!1,i,t,o);break;case"backwards":for(t=null,i=e.child,e.child=null;i!==null;){if(r=i.alternate,r!==null&&wp(r)===null){e.child=i;break}r=i.sibling,i.sibling=t,t=i,i=r}mg(e,!0,t,null,o);break;case"together":mg(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function Ah(r,e){!(e.mode&1)&&r!==null&&(r.alternate=null,e.alternate=null,e.flags|=2)}function Mo(r,e,t){if(r!==null&&(e.dependencies=r.dependencies),Pa|=e.lanes,!(t&e.childLanes))return null;if(r!==null&&e.child!==r.child)throw Error(he(153));if(e.child!==null){for(r=e.child,t=Rs(r,r.pendingProps),e.child=t,t.return=e;r.sibling!==null;)r=r.sibling,t=t.sibling=Rs(r,r.pendingProps),t.return=e;t.sibling=null}return e.child}function wj(r,e,t){switch(e.tag){case 3:JO(e),oc();break;case 5:TO(e);break;case 1:En(e.type)&&gp(e);break;case 4:tE(e,e.stateNode.containerInfo);break;case 10:var n=e.type._context,i=e.memoizedProps.value;wt(bp,n._currentValue),n._currentValue=i;break;case 13:if(n=e.memoizedState,n!==null)return n.dehydrated!==null?(wt(Nt,Nt.current&1),e.flags|=128,null):t&e.child.childLanes?XO(r,e,t):(wt(Nt,Nt.current&1),r=Mo(r,e,t),r!==null?r.sibling:null);wt(Nt,Nt.current&1);break;case 19:if(n=(t&e.childLanes)!==0,r.flags&128){if(n)return QO(r,e,t);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),wt(Nt,Nt.current),n)break;return null;case 22:case 23:return e.lanes=0,zO(r,e,t)}return Mo(r,e,t)}var ZO,bS,eP,tP;ZO=function(r,e){for(var t=e.child;t!==null;){if(t.tag===5||t.tag===6)r.appendChild(t.stateNode);else if(t.tag!==4&&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;t=t.return}t.sibling.return=t.return,t=t.sibling}};bS=function(){};eP=function(r,e,t,n){var i=r.memoizedProps;if(i!==n){r=e.stateNode,_a(Yi.current);var o=null;switch(t){case"input":i=Vy(r,i),n=Vy(r,n),o=[];break;case"select":i=Ut({},i,{value:void 0}),n=Ut({},n,{value:void 0}),o=[];break;case"textarea":i=qy(r,i),n=qy(r,n),o=[];break;default:typeof i.onClick!="function"&&typeof n.onClick=="function"&&(r.onclick=vp)}Hy(t,n);var s;t=null;for(c in i)if(!n.hasOwnProperty(c)&&i.hasOwnProperty(c)&&i[c]!=null)if(c==="style"){var a=i[c];for(s in a)a.hasOwnProperty(s)&&(t||(t={}),t[s]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(ud.hasOwnProperty(c)?o||(o=[]):(o=o||[]).push(c,null));for(c in n){var l=n[c];if(a=i!=null?i[c]:void 0,n.hasOwnProperty(c)&&l!==a&&(l!=null||a!=null))if(c==="style")if(a){for(s in a)!a.hasOwnProperty(s)||l&&l.hasOwnProperty(s)||(t||(t={}),t[s]="");for(s in l)l.hasOwnProperty(s)&&a[s]!==l[s]&&(t||(t={}),t[s]=l[s])}else t||(o||(o=[]),o.push(c,t)),t=l;else c==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(o=o||[]).push(c,l)):c==="children"?typeof l!="string"&&typeof l!="number"||(o=o||[]).push(c,""+l):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(ud.hasOwnProperty(c)?(l!=null&&c==="onScroll"&&Ct("scroll",r),o||a===l||(o=[])):(o=o||[]).push(c,l))}t&&(o=o||[]).push("style",t);var c=o;(e.updateQueue=c)&&(e.flags|=4)}};tP=function(r,e,t,n){t!==n&&(e.flags|=4)};function nu(r,e){if(!Pt)switch(r.tailMode){case"hidden":e=r.tail;for(var t=null;e!==null;)e.alternate!==null&&(t=e),e=e.sibling;t===null?r.tail=null:t.sibling=null;break;case"collapsed":t=r.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e||r.tail===null?r.tail=null:r.tail.sibling=null:n.sibling=null}}function Fr(r){var e=r.alternate!==null&&r.alternate.child===r.child,t=0,n=0;if(e)for(var i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags&14680064,n|=i.flags&14680064,i.return=r,i=i.sibling;else for(i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags,n|=i.flags,i.return=r,i=i.sibling;return r.subtreeFlags|=n,r.childLanes=t,e}function Tj(r,e,t){var n=e.pendingProps;switch(z_(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Fr(e),null;case 1:return En(e.type)&&mp(),Fr(e),null;case 3:return n=e.stateNode,ac(),It(_n),It(qr),nE(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(r===null||r.child===null)&&($f(e)?e.flags|=4:r===null||r.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,vi!==null&&(IS(vi),vi=null))),bS(r,e),Fr(e),null;case 5:rE(e);var i=_a(Ed.current);if(t=e.type,r!==null&&e.stateNode!=null)eP(r,e,t,n,i),r.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!n){if(e.stateNode===null)throw Error(he(166));return Fr(e),null}if(r=_a(Yi.current),$f(e)){n=e.stateNode,t=e.type;var o=e.memoizedProps;switch(n[Wi]=e,n[bd]=o,r=(e.mode&1)!==0,t){case"dialog":Ct("cancel",n),Ct("close",n);break;case"iframe":case"object":case"embed":Ct("load",n);break;case"video":case"audio":for(i=0;i<xu.length;i++)Ct(xu[i],n);break;case"source":Ct("error",n);break;case"img":case"image":case"link":Ct("error",n),Ct("load",n);break;case"details":Ct("toggle",n);break;case"input":O0(n,o),Ct("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!o.multiple},Ct("invalid",n);break;case"textarea":M0(n,o),Ct("invalid",n)}Hy(t,o),i=null;for(var s in o)if(o.hasOwnProperty(s)){var a=o[s];s==="children"?typeof a=="string"?n.textContent!==a&&(o.suppressHydrationWarning!==!0&&Vf(n.textContent,a,r),i=["children",a]):typeof a=="number"&&n.textContent!==""+a&&(o.suppressHydrationWarning!==!0&&Vf(n.textContent,a,r),i=["children",""+a]):ud.hasOwnProperty(s)&&a!=null&&s==="onScroll"&&Ct("scroll",n)}switch(t){case"input":Df(n),P0(n,o,!0);break;case"textarea":Df(n),A0(n);break;case"select":case"option":break;default:typeof o.onClick=="function"&&(n.onclick=vp)}n=i,e.updateQueue=n,n!==null&&(e.flags|=4)}else{s=i.nodeType===9?i:i.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=xx(t)),r==="http://www.w3.org/1999/xhtml"?t==="script"?(r=s.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof n.is=="string"?r=s.createElement(t,{is:n.is}):(r=s.createElement(t),t==="select"&&(s=r,n.multiple?s.multiple=!0:n.size&&(s.size=n.size))):r=s.createElementNS(r,t),r[Wi]=e,r[bd]=n,ZO(r,e,!1,!1),e.stateNode=r;e:{switch(s=zy(t,n),t){case"dialog":Ct("cancel",r),Ct("close",r),i=n;break;case"iframe":case"object":case"embed":Ct("load",r),i=n;break;case"video":case"audio":for(i=0;i<xu.length;i++)Ct(xu[i],r);i=n;break;case"source":Ct("error",r),i=n;break;case"img":case"image":case"link":Ct("error",r),Ct("load",r),i=n;break;case"details":Ct("toggle",r),i=n;break;case"input":O0(r,n),i=Vy(r,n),Ct("invalid",r);break;case"option":i=n;break;case"select":r._wrapperState={wasMultiple:!!n.multiple},i=Ut({},n,{value:void 0}),Ct("invalid",r);break;case"textarea":M0(r,n),i=qy(r,n),Ct("invalid",r);break;default:i=n}Hy(t,i),a=i;for(o in a)if(a.hasOwnProperty(o)){var l=a[o];o==="style"?Mx(r,l):o==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&Ox(r,l)):o==="children"?typeof l=="string"?(t!=="textarea"||l!=="")&&dd(r,l):typeof l=="number"&&dd(r,""+l):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(ud.hasOwnProperty(o)?l!=null&&o==="onScroll"&&Ct("scroll",r):l!=null&&A_(r,o,l,s))}switch(t){case"input":Df(r),P0(r,n,!1);break;case"textarea":Df(r),A0(r);break;case"option":n.value!=null&&r.setAttribute("value",""+xs(n.value));break;case"select":r.multiple=!!n.multiple,o=n.value,o!=null?Fl(r,!!n.multiple,o,!1):n.defaultValue!=null&&Fl(r,!!n.multiple,n.defaultValue,!0);break;default:typeof i.onClick=="function"&&(r.onclick=vp)}switch(t){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return Fr(e),null;case 6:if(r&&e.stateNode!=null)tP(r,e,r.memoizedProps,n);else{if(typeof n!="string"&&e.stateNode===null)throw Error(he(166));if(t=_a(Ed.current),_a(Yi.current),$f(e)){if(n=e.stateNode,t=e.memoizedProps,n[Wi]=e,(o=n.nodeValue!==t)&&(r=Un,r!==null))switch(r.tag){case 3:Vf(n.nodeValue,t,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&Vf(n.nodeValue,t,(r.mode&1)!==0)}o&&(e.flags|=4)}else n=(t.nodeType===9?t:t.ownerDocument).createTextNode(n),n[Wi]=e,e.stateNode=n}return Fr(e),null;case 13:if(It(Nt),n=e.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(Pt&&Ln!==null&&e.mode&1&&!(e.flags&128))SO(),oc(),e.flags|=98560,o=!1;else if(o=$f(e),n!==null&&n.dehydrated!==null){if(r===null){if(!o)throw Error(he(318));if(o=e.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(he(317));o[Wi]=e}else oc(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Fr(e),o=!1}else vi!==null&&(IS(vi),vi=null),o=!0;if(!o)return e.flags&65536?e:null}return e.flags&128?(e.lanes=t,e):(n=n!==null,n!==(r!==null&&r.memoizedState!==null)&&n&&(e.child.flags|=8192,e.mode&1&&(r===null||Nt.current&1?fr===0&&(fr=3):vE())),e.updateQueue!==null&&(e.flags|=4),Fr(e),null);case 4:return ac(),bS(r,e),r===null&&yd(e.stateNode.containerInfo),Fr(e),null;case 10:return Q_(e.type._context),Fr(e),null;case 17:return En(e.type)&&mp(),Fr(e),null;case 19:if(It(Nt),o=e.memoizedState,o===null)return Fr(e),null;if(n=(e.flags&128)!==0,s=o.rendering,s===null)if(n)nu(o,!1);else{if(fr!==0||r!==null&&r.flags&128)for(r=e.child;r!==null;){if(s=wp(r),s!==null){for(e.flags|=128,nu(o,!1),n=s.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),e.subtreeFlags=0,n=t,t=e.child;t!==null;)o=t,r=n,o.flags&=14680066,s=o.alternate,s===null?(o.childLanes=0,o.lanes=r,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=s.childLanes,o.lanes=s.lanes,o.child=s.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=s.memoizedProps,o.memoizedState=s.memoizedState,o.updateQueue=s.updateQueue,o.type=s.type,r=s.dependencies,o.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),t=t.sibling;return wt(Nt,Nt.current&1|2),e.child}r=r.sibling}o.tail!==null&&Jt()>cc&&(e.flags|=128,n=!0,nu(o,!1),e.lanes=4194304)}else{if(!n)if(r=wp(s),r!==null){if(e.flags|=128,n=!0,t=r.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),nu(o,!0),o.tail===null&&o.tailMode==="hidden"&&!s.alternate&&!Pt)return Fr(e),null}else 2*Jt()-o.renderingStartTime>cc&&t!==1073741824&&(e.flags|=128,n=!0,nu(o,!1),e.lanes=4194304);o.isBackwards?(s.sibling=e.child,e.child=s):(t=o.last,t!==null?t.sibling=s:e.child=s,o.last=s)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=Jt(),e.sibling=null,t=Nt.current,wt(Nt,n?t&1|2:t&1),e):(Fr(e),null);case 22:case 23:return pE(),n=e.memoizedState!==null,r!==null&&r.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?An&1073741824&&(Fr(e),e.subtreeFlags&6&&(e.flags|=8192)):Fr(e),null;case 24:return null;case 25:return null}throw Error(he(156,e.tag))}function Rj(r,e){switch(z_(e),e.tag){case 1:return En(e.type)&&mp(),r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 3:return ac(),It(_n),It(qr),nE(),r=e.flags,r&65536&&!(r&128)?(e.flags=r&-65537|128,e):null;case 5:return rE(e),null;case 13:if(It(Nt),r=e.memoizedState,r!==null&&r.dehydrated!==null){if(e.alternate===null)throw Error(he(340));oc()}return r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 19:return It(Nt),null;case 4:return ac(),null;case 10:return Q_(e.type._context),null;case 22:case 23:return pE(),null;case 24:return null;default:return null}}var Gf=!1,$r=!1,Cj=typeof WeakSet=="function"?WeakSet:Set,xe=null;function Dl(r,e){var t=r.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(n){Wt(r,e,n)}else t.current=null}function _S(r,e,t){try{t()}catch(n){Wt(r,e,n)}}var ET=!1;function kj(r,e){if(iS=fp,r=sO(),G_(r)){if("selectionStart"in r)var t={start:r.selectionStart,end:r.selectionEnd};else e:{t=(t=r.ownerDocument)&&t.defaultView||window;var n=t.getSelection&&t.getSelection();if(n&&n.rangeCount!==0){t=n.anchorNode;var i=n.anchorOffset,o=n.focusNode;n=n.focusOffset;try{t.nodeType,o.nodeType}catch{t=null;break e}var s=0,a=-1,l=-1,c=0,u=0,d=r,f=null;t:for(;;){for(var p;d!==t||i!==0&&d.nodeType!==3||(a=s+i),d!==o||n!==0&&d.nodeType!==3||(l=s+n),d.nodeType===3&&(s+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===r)break t;if(f===t&&++c===i&&(a=s),f===o&&++u===n&&(l=s),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(oS={focusedElem:r,selectionRange:t},fp=!1,xe=e;xe!==null;)if(e=xe,r=e.child,(e.subtreeFlags&1028)!==0&&r!==null)r.return=e,xe=r;else for(;xe!==null;){e=xe;try{var h=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(h!==null){var m=h.memoizedProps,w=h.memoizedState,g=e.stateNode,b=g.getSnapshotBeforeUpdate(e.elementType===e.type?m:ui(e.type,m),w);g.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var R=e.stateNode.containerInfo;R.nodeType===1?R.textContent="":R.nodeType===9&&R.documentElement&&R.removeChild(R.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(he(163))}}catch(k){Wt(e,e.return,k)}if(r=e.sibling,r!==null){r.return=e.return,xe=r;break}xe=e.return}return h=ET,ET=!1,h}function zu(r,e,t){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&r)===r){var o=i.destroy;i.destroy=void 0,o!==void 0&&_S(e,t,o)}i=i.next}while(i!==n)}}function Cv(r,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var t=e=e.next;do{if((t.tag&r)===r){var n=t.create;t.destroy=n()}t=t.next}while(t!==e)}}function ES(r){var e=r.ref;if(e!==null){var t=r.stateNode;switch(r.tag){case 5:r=t;break;default:r=t}typeof e=="function"?e(r):e.current=r}}function rP(r){var e=r.alternate;e!==null&&(r.alternate=null,rP(e)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(e=r.stateNode,e!==null&&(delete e[Wi],delete e[bd],delete e[lS],delete e[cj],delete e[uj])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function nP(r){return r.tag===5||r.tag===3||r.tag===4}function wT(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||nP(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function wS(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.nodeType===8?t.parentNode.insertBefore(r,e):t.insertBefore(r,e):(t.nodeType===8?(e=t.parentNode,e.insertBefore(r,t)):(e=t,e.appendChild(r)),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=vp));else if(n!==4&&(r=r.child,r!==null))for(wS(r,e,t),r=r.sibling;r!==null;)wS(r,e,t),r=r.sibling}function TS(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.insertBefore(r,e):t.appendChild(r);else if(n!==4&&(r=r.child,r!==null))for(TS(r,e,t),r=r.sibling;r!==null;)TS(r,e,t),r=r.sibling}var xr=null,fi=!1;function Wo(r,e,t){for(t=t.child;t!==null;)iP(r,e,t),t=t.sibling}function iP(r,e,t){if(zi&&typeof zi.onCommitFiberUnmount=="function")try{zi.onCommitFiberUnmount(yv,t)}catch{}switch(t.tag){case 5:$r||Dl(t,e);case 6:var n=xr,i=fi;xr=null,Wo(r,e,t),xr=n,fi=i,xr!==null&&(fi?(r=xr,t=t.stateNode,r.nodeType===8?r.parentNode.removeChild(t):r.removeChild(t)):xr.removeChild(t.stateNode));break;case 18:xr!==null&&(fi?(r=xr,t=t.stateNode,r.nodeType===8?cg(r.parentNode,t):r.nodeType===1&&cg(r,t),vd(r)):cg(xr,t.stateNode));break;case 4:n=xr,i=fi,xr=t.stateNode.containerInfo,fi=!0,Wo(r,e,t),xr=n,fi=i;break;case 0:case 11:case 14:case 15:if(!$r&&(n=t.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var o=i,s=o.destroy;o=o.tag,s!==void 0&&(o&2||o&4)&&_S(t,e,s),i=i.next}while(i!==n)}Wo(r,e,t);break;case 1:if(!$r&&(Dl(t,e),n=t.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=t.memoizedProps,n.state=t.memoizedState,n.componentWillUnmount()}catch(a){Wt(t,e,a)}Wo(r,e,t);break;case 21:Wo(r,e,t);break;case 22:t.mode&1?($r=(n=$r)||t.memoizedState!==null,Wo(r,e,t),$r=n):Wo(r,e,t);break;default:Wo(r,e,t)}}function TT(r){var e=r.updateQueue;if(e!==null){r.updateQueue=null;var t=r.stateNode;t===null&&(t=r.stateNode=new Cj),e.forEach(function(n){var i=Lj.bind(null,r,n);t.has(n)||(t.add(n),n.then(i,i))})}}function oi(r,e){var t=e.deletions;if(t!==null)for(var n=0;n<t.length;n++){var i=t[n];try{var o=r,s=e,a=s;e:for(;a!==null;){switch(a.tag){case 5:xr=a.stateNode,fi=!1;break e;case 3:xr=a.stateNode.containerInfo,fi=!0;break e;case 4:xr=a.stateNode.containerInfo,fi=!0;break e}a=a.return}if(xr===null)throw Error(he(160));iP(o,s,i),xr=null,fi=!1;var l=i.alternate;l!==null&&(l.return=null),i.return=null}catch(c){Wt(i,e,c)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)oP(e,r),e=e.sibling}function oP(r,e){var t=r.alternate,n=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(oi(e,r),Mi(r),n&4){try{zu(3,r,r.return),Cv(3,r)}catch(m){Wt(r,r.return,m)}try{zu(5,r,r.return)}catch(m){Wt(r,r.return,m)}}break;case 1:oi(e,r),Mi(r),n&512&&t!==null&&Dl(t,t.return);break;case 5:if(oi(e,r),Mi(r),n&512&&t!==null&&Dl(t,t.return),r.flags&32){var i=r.stateNode;try{dd(i,"")}catch(m){Wt(r,r.return,m)}}if(n&4&&(i=r.stateNode,i!=null)){var o=r.memoizedProps,s=t!==null?t.memoizedProps:o,a=r.type,l=r.updateQueue;if(r.updateQueue=null,l!==null)try{a==="input"&&o.type==="radio"&&o.name!=null&&kx(i,o),zy(a,s);var c=zy(a,o);for(s=0;s<l.length;s+=2){var u=l[s],d=l[s+1];u==="style"?Mx(i,d):u==="dangerouslySetInnerHTML"?Ox(i,d):u==="children"?dd(i,d):A_(i,u,d,c)}switch(a){case"input":$y(i,o);break;case"textarea":Ix(i,o);break;case"select":var f=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!o.multiple;var p=o.value;p!=null?Fl(i,!!o.multiple,p,!1):f!==!!o.multiple&&(o.defaultValue!=null?Fl(i,!!o.multiple,o.defaultValue,!0):Fl(i,!!o.multiple,o.multiple?[]:"",!1))}i[bd]=o}catch(m){Wt(r,r.return,m)}}break;case 6:if(oi(e,r),Mi(r),n&4){if(r.stateNode===null)throw Error(he(162));i=r.stateNode,o=r.memoizedProps;try{i.nodeValue=o}catch(m){Wt(r,r.return,m)}}break;case 3:if(oi(e,r),Mi(r),n&4&&t!==null&&t.memoizedState.isDehydrated)try{vd(e.containerInfo)}catch(m){Wt(r,r.return,m)}break;case 4:oi(e,r),Mi(r);break;case 13:oi(e,r),Mi(r),i=r.child,i.flags&8192&&(o=i.memoizedState!==null,i.stateNode.isHidden=o,!o||i.alternate!==null&&i.alternate.memoizedState!==null||(fE=Jt())),n&4&&TT(r);break;case 22:if(u=t!==null&&t.memoizedState!==null,r.mode&1?($r=(c=$r)||u,oi(e,r),$r=c):oi(e,r),Mi(r),n&8192){if(c=r.memoizedState!==null,(r.stateNode.isHidden=c)&&!u&&r.mode&1)for(xe=r,u=r.child;u!==null;){for(d=xe=u;xe!==null;){switch(f=xe,p=f.child,f.tag){case 0:case 11:case 14:case 15:zu(4,f,f.return);break;case 1:Dl(f,f.return);var h=f.stateNode;if(typeof h.componentWillUnmount=="function"){n=f,t=f.return;try{e=n,h.props=e.memoizedProps,h.state=e.memoizedState,h.componentWillUnmount()}catch(m){Wt(n,t,m)}}break;case 5:Dl(f,f.return);break;case 22:if(f.memoizedState!==null){CT(d);continue}}p!==null?(p.return=f,xe=p):CT(d)}u=u.sibling}e:for(u=null,d=r;;){if(d.tag===5){if(u===null){u=d;try{i=d.stateNode,c?(o=i.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none"):(a=d.stateNode,l=d.memoizedProps.style,s=l!=null&&l.hasOwnProperty("display")?l.display:null,a.style.display=Px("display",s))}catch(m){Wt(r,r.return,m)}}}else if(d.tag===6){if(u===null)try{d.stateNode.nodeValue=c?"":d.memoizedProps}catch(m){Wt(r,r.return,m)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===r)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===r)break e;for(;d.sibling===null;){if(d.return===null||d.return===r)break e;u===d&&(u=null),d=d.return}u===d&&(u=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:oi(e,r),Mi(r),n&4&&TT(r);break;case 21:break;default:oi(e,r),Mi(r)}}function Mi(r){var e=r.flags;if(e&2){try{e:{for(var t=r.return;t!==null;){if(nP(t)){var n=t;break e}t=t.return}throw Error(he(160))}switch(n.tag){case 5:var i=n.stateNode;n.flags&32&&(dd(i,""),n.flags&=-33);var o=wT(r);TS(r,o,i);break;case 3:case 4:var s=n.stateNode.containerInfo,a=wT(r);wS(r,a,s);break;default:throw Error(he(161))}}catch(l){Wt(r,r.return,l)}r.flags&=-3}e&4096&&(r.flags&=-4097)}function Ij(r,e,t){xe=r,sP(r)}function sP(r,e,t){for(var n=(r.mode&1)!==0;xe!==null;){var i=xe,o=i.child;if(i.tag===22&&n){var s=i.memoizedState!==null||Gf;if(!s){var a=i.alternate,l=a!==null&&a.memoizedState!==null||$r;a=Gf;var c=$r;if(Gf=s,($r=l)&&!c)for(xe=i;xe!==null;)s=xe,l=s.child,s.tag===22&&s.memoizedState!==null?kT(i):l!==null?(l.return=s,xe=l):kT(i);for(;o!==null;)xe=o,sP(o),o=o.sibling;xe=i,Gf=a,$r=c}RT(r)}else i.subtreeFlags&8772&&o!==null?(o.return=i,xe=o):RT(r)}}function RT(r){for(;xe!==null;){var e=xe;if(e.flags&8772){var t=e.alternate;try{if(e.flags&8772)switch(e.tag){case 0:case 11:case 15:$r||Cv(5,e);break;case 1:var n=e.stateNode;if(e.flags&4&&!$r)if(t===null)n.componentDidMount();else{var i=e.elementType===e.type?t.memoizedProps:ui(e.type,t.memoizedProps);n.componentDidUpdate(i,t.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var o=e.updateQueue;o!==null&&cT(e,o,n);break;case 3:var s=e.updateQueue;if(s!==null){if(t=null,e.child!==null)switch(e.child.tag){case 5:t=e.child.stateNode;break;case 1:t=e.child.stateNode}cT(e,s,t)}break;case 5:var a=e.stateNode;if(t===null&&e.flags&4){t=a;var l=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&t.focus();break;case"img":l.src&&(t.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var c=e.alternate;if(c!==null){var u=c.memoizedState;if(u!==null){var d=u.dehydrated;d!==null&&vd(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(he(163))}$r||e.flags&512&&ES(e)}catch(f){Wt(e,e.return,f)}}if(e===r){xe=null;break}if(t=e.sibling,t!==null){t.return=e.return,xe=t;break}xe=e.return}}function CT(r){for(;xe!==null;){var e=xe;if(e===r){xe=null;break}var t=e.sibling;if(t!==null){t.return=e.return,xe=t;break}xe=e.return}}function kT(r){for(;xe!==null;){var e=xe;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{Cv(4,e)}catch(l){Wt(e,t,l)}break;case 1:var n=e.stateNode;if(typeof n.componentDidMount=="function"){var i=e.return;try{n.componentDidMount()}catch(l){Wt(e,i,l)}}var o=e.return;try{ES(e)}catch(l){Wt(e,o,l)}break;case 5:var s=e.return;try{ES(e)}catch(l){Wt(e,s,l)}}}catch(l){Wt(e,e.return,l)}if(e===r){xe=null;break}var a=e.sibling;if(a!==null){a.return=e.return,xe=a;break}xe=e.return}}var xj=Math.ceil,Cp=Lo.ReactCurrentDispatcher,uE=Lo.ReactCurrentOwner,zn=Lo.ReactCurrentBatchConfig,st=0,Tr=null,nr=null,Nr=0,An=0,Nl=Fs(0),fr=0,Cd=null,Pa=0,kv=0,dE=0,Yu=null,yn=null,fE=0,cc=1/0,po=null,kp=!1,RS=null,ws=null,Hf=!1,vs=null,Ip=0,Ju=0,CS=null,Dh=-1,Nh=0;function Zr(){return st&6?Jt():Dh!==-1?Dh:Dh=Jt()}function Ts(r){return r.mode&1?st&2&&Nr!==0?Nr&-Nr:fj.transition!==null?(Nh===0&&(Nh=Wx()),Nh):(r=ft,r!==0||(r=window.event,r=r===void 0?16:Xx(r.type)),r):1}function bi(r,e,t,n){if(50<Ju)throw Ju=0,CS=null,Error(he(185));tf(r,t,n),(!(st&2)||r!==Tr)&&(r===Tr&&(!(st&2)&&(kv|=t),fr===4&&fs(r,Nr)),wn(r,n),t===1&&st===0&&!(e.mode&1)&&(cc=Jt()+500,wv&&Bs()))}function wn(r,e){var t=r.callbackNode;f2(r,e);var n=dp(r,r===Tr?Nr:0);if(n===0)t!==null&&L0(t),r.callbackNode=null,r.callbackPriority=0;else if(e=n&-n,r.callbackPriority!==e){if(t!=null&&L0(t),e===1)r.tag===0?dj(IT.bind(null,r)):mO(IT.bind(null,r)),aj(function(){!(st&6)&&Bs()}),t=null;else{switch(qx(n)){case 1:t=j_;break;case 4:t=Vx;break;case 16:t=up;break;case 536870912:t=$x;break;default:t=up}t=pP(t,aP.bind(null,r))}r.callbackPriority=e,r.callbackNode=t}}function aP(r,e){if(Dh=-1,Nh=0,st&6)throw Error(he(327));var t=r.callbackNode;if(Wl()&&r.callbackNode!==t)return null;var n=dp(r,r===Tr?Nr:0);if(n===0)return null;if(n&30||n&r.expiredLanes||e)e=xp(r,n);else{e=n;var i=st;st|=2;var o=cP();(Tr!==r||Nr!==e)&&(po=null,cc=Jt()+500,wa(r,e));do try{Mj();break}catch(a){lP(r,a)}while(!0);X_(),Cp.current=o,st=i,nr!==null?e=0:(Tr=null,Nr=0,e=fr)}if(e!==0){if(e===2&&(i=Zy(r),i!==0&&(n=i,e=kS(r,i))),e===1)throw t=Cd,wa(r,0),fs(r,n),wn(r,Jt()),t;if(e===6)fs(r,n);else{if(i=r.current.alternate,!(n&30)&&!Oj(i)&&(e=xp(r,n),e===2&&(o=Zy(r),o!==0&&(n=o,e=kS(r,o))),e===1))throw t=Cd,wa(r,0),fs(r,n),wn(r,Jt()),t;switch(r.finishedWork=i,r.finishedLanes=n,e){case 0:case 1:throw Error(he(345));case 2:aa(r,yn,po);break;case 3:if(fs(r,n),(n&130023424)===n&&(e=fE+500-Jt(),10<e)){if(dp(r,0)!==0)break;if(i=r.suspendedLanes,(i&n)!==n){Zr(),r.pingedLanes|=r.suspendedLanes&i;break}r.timeoutHandle=aS(aa.bind(null,r,yn,po),e);break}aa(r,yn,po);break;case 4:if(fs(r,n),(n&4194240)===n)break;for(e=r.eventTimes,i=-1;0<n;){var s=31-Si(n);o=1<<s,s=e[s],s>i&&(i=s),n&=~o}if(n=i,n=Jt()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*xj(n/1960))-n,10<n){r.timeoutHandle=aS(aa.bind(null,r,yn,po),n);break}aa(r,yn,po);break;case 5:aa(r,yn,po);break;default:throw Error(he(329))}}}return wn(r,Jt()),r.callbackNode===t?aP.bind(null,r):null}function kS(r,e){var t=Yu;return r.current.memoizedState.isDehydrated&&(wa(r,e).flags|=256),r=xp(r,e),r!==2&&(e=yn,yn=t,e!==null&&IS(e)),r}function IS(r){yn===null?yn=r:yn.push.apply(yn,r)}function Oj(r){for(var e=r;;){if(e.flags&16384){var t=e.updateQueue;if(t!==null&&(t=t.stores,t!==null))for(var n=0;n<t.length;n++){var i=t[n],o=i.getSnapshot;i=i.value;try{if(!Ti(o(),i))return!1}catch{return!1}}}if(t=e.child,e.subtreeFlags&16384&&t!==null)t.return=e,e=t;else{if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function fs(r,e){for(e&=~dE,e&=~kv,r.suspendedLanes|=e,r.pingedLanes&=~e,r=r.expirationTimes;0<e;){var t=31-Si(e),n=1<<t;r[t]=-1,e&=~n}}function IT(r){if(st&6)throw Error(he(327));Wl();var e=dp(r,0);if(!(e&1))return wn(r,Jt()),null;var t=xp(r,e);if(r.tag!==0&&t===2){var n=Zy(r);n!==0&&(e=n,t=kS(r,n))}if(t===1)throw t=Cd,wa(r,0),fs(r,e),wn(r,Jt()),t;if(t===6)throw Error(he(345));return r.finishedWork=r.current.alternate,r.finishedLanes=e,aa(r,yn,po),wn(r,Jt()),null}function hE(r,e){var t=st;st|=1;try{return r(e)}finally{st=t,st===0&&(cc=Jt()+500,wv&&Bs())}}function Ma(r){vs!==null&&vs.tag===0&&!(st&6)&&Wl();var e=st;st|=1;var t=zn.transition,n=ft;try{if(zn.transition=null,ft=1,r)return r()}finally{ft=n,zn.transition=t,st=e,!(st&6)&&Bs()}}function pE(){An=Nl.current,It(Nl)}function wa(r,e){r.finishedWork=null,r.finishedLanes=0;var t=r.timeoutHandle;if(t!==-1&&(r.timeoutHandle=-1,sj(t)),nr!==null)for(t=nr.return;t!==null;){var n=t;switch(z_(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&mp();break;case 3:ac(),It(_n),It(qr),nE();break;case 5:rE(n);break;case 4:ac();break;case 13:It(Nt);break;case 19:It(Nt);break;case 10:Q_(n.type._context);break;case 22:case 23:pE()}t=t.return}if(Tr=r,nr=r=Rs(r.current,null),Nr=An=e,fr=0,Cd=null,dE=kv=Pa=0,yn=Yu=null,ba!==null){for(e=0;e<ba.length;e++)if(t=ba[e],n=t.interleaved,n!==null){t.interleaved=null;var i=n.next,o=t.pending;if(o!==null){var s=o.next;o.next=i,n.next=s}t.pending=n}ba=null}return r}function lP(r,e){do{var t=nr;try{if(X_(),Ph.current=Rp,Tp){for(var n=Lt.memoizedState;n!==null;){var i=n.queue;i!==null&&(i.pending=null),n=n.next}Tp=!1}if(Oa=0,_r=ur=Lt=null,Hu=!1,wd=0,uE.current=null,t===null||t.return===null){fr=1,Cd=e,nr=null;break}e:{var o=r,s=t.return,a=t,l=e;if(e=Nr,a.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var c=l,u=a,d=u.tag;if(!(u.mode&1)&&(d===0||d===11||d===15)){var f=u.alternate;f?(u.updateQueue=f.updateQueue,u.memoizedState=f.memoizedState,u.lanes=f.lanes):(u.updateQueue=null,u.memoizedState=null)}var p=vT(s);if(p!==null){p.flags&=-257,mT(p,s,a,o,e),p.mode&1&&pT(o,c,e),e=p,l=c;var h=e.updateQueue;if(h===null){var m=new Set;m.add(l),e.updateQueue=m}else h.add(l);break e}else{if(!(e&1)){pT(o,c,e),vE();break e}l=Error(he(426))}}else if(Pt&&a.mode&1){var w=vT(s);if(w!==null){!(w.flags&65536)&&(w.flags|=256),mT(w,s,a,o,e),Y_(lc(l,a));break e}}o=l=lc(l,a),fr!==4&&(fr=2),Yu===null?Yu=[o]:Yu.push(o),o=s;do{switch(o.tag){case 3:o.flags|=65536,e&=-e,o.lanes|=e;var g=qO(o,l,e);lT(o,g);break e;case 1:a=l;var b=o.type,R=o.stateNode;if(!(o.flags&128)&&(typeof b.getDerivedStateFromError=="function"||R!==null&&typeof R.componentDidCatch=="function"&&(ws===null||!ws.has(R)))){o.flags|=65536,e&=-e,o.lanes|=e;var k=GO(o,a,e);lT(o,k);break e}}o=o.return}while(o!==null)}dP(t)}catch(O){e=O,nr===t&&t!==null&&(nr=t=t.return);continue}break}while(!0)}function cP(){var r=Cp.current;return Cp.current=Rp,r===null?Rp:r}function vE(){(fr===0||fr===3||fr===2)&&(fr=4),Tr===null||!(Pa&268435455)&&!(kv&268435455)||fs(Tr,Nr)}function xp(r,e){var t=st;st|=2;var n=cP();(Tr!==r||Nr!==e)&&(po=null,wa(r,e));do try{Pj();break}catch(i){lP(r,i)}while(!0);if(X_(),st=t,Cp.current=n,nr!==null)throw Error(he(261));return Tr=null,Nr=0,fr}function Pj(){for(;nr!==null;)uP(nr)}function Mj(){for(;nr!==null&&!n2();)uP(nr)}function uP(r){var e=hP(r.alternate,r,An);r.memoizedProps=r.pendingProps,e===null?dP(r):nr=e,uE.current=null}function dP(r){var e=r;do{var t=e.alternate;if(r=e.return,e.flags&32768){if(t=Rj(t,e),t!==null){t.flags&=32767,nr=t;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{fr=6,nr=null;return}}else if(t=Tj(t,e,An),t!==null){nr=t;return}if(e=e.sibling,e!==null){nr=e;return}nr=e=r}while(e!==null);fr===0&&(fr=5)}function aa(r,e,t){var n=ft,i=zn.transition;try{zn.transition=null,ft=1,Aj(r,e,t,n)}finally{zn.transition=i,ft=n}return null}function Aj(r,e,t,n){do Wl();while(vs!==null);if(st&6)throw Error(he(327));t=r.finishedWork;var i=r.finishedLanes;if(t===null)return null;if(r.finishedWork=null,r.finishedLanes=0,t===r.current)throw Error(he(177));r.callbackNode=null,r.callbackPriority=0;var o=t.lanes|t.childLanes;if(h2(r,o),r===Tr&&(nr=Tr=null,Nr=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||Hf||(Hf=!0,pP(up,function(){return Wl(),null})),o=(t.flags&15990)!==0,t.subtreeFlags&15990||o){o=zn.transition,zn.transition=null;var s=ft;ft=1;var a=st;st|=4,uE.current=null,kj(r,t),oP(t,r),Z2(oS),fp=!!iS,oS=iS=null,r.current=t,Ij(t),i2(),st=a,ft=s,zn.transition=o}else r.current=t;if(Hf&&(Hf=!1,vs=r,Ip=i),o=r.pendingLanes,o===0&&(ws=null),a2(t.stateNode),wn(r,Jt()),e!==null)for(n=r.onRecoverableError,t=0;t<e.length;t++)i=e[t],n(i.value,{componentStack:i.stack,digest:i.digest});if(kp)throw kp=!1,r=RS,RS=null,r;return Ip&1&&r.tag!==0&&Wl(),o=r.pendingLanes,o&1?r===CS?Ju++:(Ju=0,CS=r):Ju=0,Bs(),null}function Wl(){if(vs!==null){var r=qx(Ip),e=zn.transition,t=ft;try{if(zn.transition=null,ft=16>r?16:r,vs===null)var n=!1;else{if(r=vs,vs=null,Ip=0,st&6)throw Error(he(331));var i=st;for(st|=4,xe=r.current;xe!==null;){var o=xe,s=o.child;if(xe.flags&16){var a=o.deletions;if(a!==null){for(var l=0;l<a.length;l++){var c=a[l];for(xe=c;xe!==null;){var u=xe;switch(u.tag){case 0:case 11:case 15:zu(8,u,o)}var d=u.child;if(d!==null)d.return=u,xe=d;else for(;xe!==null;){u=xe;var f=u.sibling,p=u.return;if(rP(u),u===c){xe=null;break}if(f!==null){f.return=p,xe=f;break}xe=p}}}var h=o.alternate;if(h!==null){var m=h.child;if(m!==null){h.child=null;do{var w=m.sibling;m.sibling=null,m=w}while(m!==null)}}xe=o}}if(o.subtreeFlags&2064&&s!==null)s.return=o,xe=s;else e:for(;xe!==null;){if(o=xe,o.flags&2048)switch(o.tag){case 0:case 11:case 15:zu(9,o,o.return)}var g=o.sibling;if(g!==null){g.return=o.return,xe=g;break e}xe=o.return}}var b=r.current;for(xe=b;xe!==null;){s=xe;var R=s.child;if(s.subtreeFlags&2064&&R!==null)R.return=s,xe=R;else e:for(s=b;xe!==null;){if(a=xe,a.flags&2048)try{switch(a.tag){case 0:case 11:case 15:Cv(9,a)}}catch(O){Wt(a,a.return,O)}if(a===s){xe=null;break e}var k=a.sibling;if(k!==null){k.return=a.return,xe=k;break e}xe=a.return}}if(st=i,Bs(),zi&&typeof zi.onPostCommitFiberRoot=="function")try{zi.onPostCommitFiberRoot(yv,r)}catch{}n=!0}return n}finally{ft=t,zn.transition=e}}return!1}function xT(r,e,t){e=lc(t,e),e=qO(r,e,1),r=Es(r,e,1),e=Zr(),r!==null&&(tf(r,1,e),wn(r,e))}function Wt(r,e,t){if(r.tag===3)xT(r,r,t);else for(;e!==null;){if(e.tag===3){xT(e,r,t);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(ws===null||!ws.has(n))){r=lc(t,r),r=GO(e,r,1),e=Es(e,r,1),r=Zr(),e!==null&&(tf(e,1,r),wn(e,r));break}}e=e.return}}function Dj(r,e,t){var n=r.pingCache;n!==null&&n.delete(e),e=Zr(),r.pingedLanes|=r.suspendedLanes&t,Tr===r&&(Nr&t)===t&&(fr===4||fr===3&&(Nr&130023424)===Nr&&500>Jt()-fE?wa(r,0):dE|=t),wn(r,e)}function fP(r,e){e===0&&(r.mode&1?(e=Uf,Uf<<=1,!(Uf&130023424)&&(Uf=4194304)):e=1);var t=Zr();r=Po(r,e),r!==null&&(tf(r,e,t),wn(r,t))}function Nj(r){var e=r.memoizedState,t=0;e!==null&&(t=e.retryLane),fP(r,t)}function Lj(r,e){var t=0;switch(r.tag){case 13:var n=r.stateNode,i=r.memoizedState;i!==null&&(t=i.retryLane);break;case 19:n=r.stateNode;break;default:throw Error(he(314))}n!==null&&n.delete(e),fP(r,t)}var hP;hP=function(r,e,t){if(r!==null)if(r.memoizedProps!==e.pendingProps||_n.current)Sn=!0;else{if(!(r.lanes&t)&&!(e.flags&128))return Sn=!1,wj(r,e,t);Sn=!!(r.flags&131072)}else Sn=!1,Pt&&e.flags&1048576&&gO(e,Sp,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;Ah(r,e),r=e.pendingProps;var i=ic(e,qr.current);$l(e,t),i=oE(null,e,n,r,i,t);var o=sE();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,En(n)?(o=!0,gp(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,eE(e),i.updater=Rv,e.stateNode=i,i._reactInternals=e,pS(e,n,r,t),e=gS(null,e,n,!0,o,t)):(e.tag=0,Pt&&o&&H_(e),Yr(null,e,i,t),e=e.child),e;case 16:n=e.elementType;e:{switch(Ah(r,e),r=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=jj(n),r=ui(n,r),i){case 0:e=mS(null,e,n,r,t);break e;case 1:e=ST(null,e,n,r,t);break e;case 11:e=gT(null,e,n,r,t);break e;case 14:e=yT(null,e,n,ui(n.type,r),t);break e}throw Error(he(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),mS(r,e,n,i,t);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),ST(r,e,n,i,t);case 3:e:{if(JO(e),r===null)throw Error(he(387));n=e.pendingProps,o=e.memoizedState,i=o.element,wO(r,e),Ep(e,n,null,t);var s=e.memoizedState;if(n=s.element,o.isDehydrated)if(o={element:n,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},e.updateQueue.baseState=o,e.memoizedState=o,e.flags&256){i=lc(Error(he(423)),e),e=bT(r,e,n,t,i);break e}else if(n!==i){i=lc(Error(he(424)),e),e=bT(r,e,n,t,i);break e}else for(Ln=_s(e.stateNode.containerInfo.firstChild),Un=e,Pt=!0,vi=null,t=_O(e,null,n,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(oc(),n===i){e=Mo(r,e,t);break e}Yr(r,e,n,t)}e=e.child}return e;case 5:return TO(e),r===null&&dS(e),n=e.type,i=e.pendingProps,o=r!==null?r.memoizedProps:null,s=i.children,sS(n,i)?s=null:o!==null&&sS(n,o)&&(e.flags|=32),YO(r,e),Yr(r,e,s,t),e.child;case 6:return r===null&&dS(e),null;case 13:return XO(r,e,t);case 4:return tE(e,e.stateNode.containerInfo),n=e.pendingProps,r===null?e.child=sc(e,null,n,t):Yr(r,e,n,t),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),gT(r,e,n,i,t);case 7:return Yr(r,e,e.pendingProps,t),e.child;case 8:return Yr(r,e,e.pendingProps.children,t),e.child;case 12:return Yr(r,e,e.pendingProps.children,t),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,o=e.memoizedProps,s=i.value,wt(bp,n._currentValue),n._currentValue=s,o!==null)if(Ti(o.value,s)){if(o.children===i.children&&!_n.current){e=Mo(r,e,t);break e}}else for(o=e.child,o!==null&&(o.return=e);o!==null;){var a=o.dependencies;if(a!==null){s=o.child;for(var l=a.firstContext;l!==null;){if(l.context===n){if(o.tag===1){l=Ro(-1,t&-t),l.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?l.next=l:(l.next=u.next,u.next=l),c.pending=l}}o.lanes|=t,l=o.alternate,l!==null&&(l.lanes|=t),fS(o.return,t,e),a.lanes|=t;break}l=l.next}}else if(o.tag===10)s=o.type===e.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(he(341));s.lanes|=t,a=s.alternate,a!==null&&(a.lanes|=t),fS(s,t,e),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===e){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}Yr(r,e,i.children,t),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,$l(e,t),i=Xn(i),n=n(i),e.flags|=1,Yr(r,e,n,t),e.child;case 14:return n=e.type,i=ui(n,e.pendingProps),i=ui(n.type,i),yT(r,e,n,i,t);case 15:return HO(r,e,e.type,e.pendingProps,t);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),Ah(r,e),e.tag=1,En(n)?(r=!0,gp(e)):r=!1,$l(e,t),WO(e,n,i),pS(e,n,i,t),gS(null,e,n,!0,r,t);case 19:return QO(r,e,t);case 22:return zO(r,e,t)}throw Error(he(156,e.tag))};function pP(r,e){return Kx(r,e)}function Uj(r,e,t,n){this.tag=r,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Gn(r,e,t,n){return new Uj(r,e,t,n)}function mE(r){return r=r.prototype,!(!r||!r.isReactComponent)}function jj(r){if(typeof r=="function")return mE(r)?1:0;if(r!=null){if(r=r.$$typeof,r===N_)return 11;if(r===L_)return 14}return 2}function Rs(r,e){var t=r.alternate;return t===null?(t=Gn(r.tag,e,r.key,r.mode),t.elementType=r.elementType,t.type=r.type,t.stateNode=r.stateNode,t.alternate=r,r.alternate=t):(t.pendingProps=e,t.type=r.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=r.flags&14680064,t.childLanes=r.childLanes,t.lanes=r.lanes,t.child=r.child,t.memoizedProps=r.memoizedProps,t.memoizedState=r.memoizedState,t.updateQueue=r.updateQueue,e=r.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=r.sibling,t.index=r.index,t.ref=r.ref,t}function Lh(r,e,t,n,i,o){var s=2;if(n=r,typeof r=="function")mE(r)&&(s=1);else if(typeof r=="string")s=5;else e:switch(r){case Rl:return Ta(t.children,i,o,e);case D_:s=8,i|=8;break;case jy:return r=Gn(12,t,e,i|2),r.elementType=jy,r.lanes=o,r;case Fy:return r=Gn(13,t,e,i),r.elementType=Fy,r.lanes=o,r;case By:return r=Gn(19,t,e,i),r.elementType=By,r.lanes=o,r;case Tx:return Iv(t,i,o,e);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Ex:s=10;break e;case wx:s=9;break e;case N_:s=11;break e;case L_:s=14;break e;case as:s=16,n=null;break e}throw Error(he(130,r==null?r:typeof r,""))}return e=Gn(s,t,e,i),e.elementType=r,e.type=n,e.lanes=o,e}function Ta(r,e,t,n){return r=Gn(7,r,n,e),r.lanes=t,r}function Iv(r,e,t,n){return r=Gn(22,r,n,e),r.elementType=Tx,r.lanes=t,r.stateNode={isHidden:!1},r}function gg(r,e,t){return r=Gn(6,r,null,e),r.lanes=t,r}function yg(r,e,t){return e=Gn(4,r.children!==null?r.children:[],r.key,e),e.lanes=t,e.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},e}function Fj(r,e,t,n,i){this.tag=e,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Qm(0),this.expirationTimes=Qm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Qm(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function gE(r,e,t,n,i,o,s,a,l){return r=new Fj(r,e,t,a,l),e===1?(e=1,o===!0&&(e|=8)):e=0,o=Gn(3,null,null,e),r.current=o,o.stateNode=r,o.memoizedState={element:n,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},eE(o),r}function Bj(r,e,t){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Tl,key:n==null?null:""+n,children:r,containerInfo:e,implementation:t}}function vP(r){if(!r)return Os;r=r._reactInternals;e:{if($a(r)!==r||r.tag!==1)throw Error(he(170));var e=r;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(En(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(he(171))}if(r.tag===1){var t=r.type;if(En(t))return vO(r,t,e)}return e}function mP(r,e,t,n,i,o,s,a,l){return r=gE(t,n,!0,r,i,o,s,a,l),r.context=vP(null),t=r.current,n=Zr(),i=Ts(t),o=Ro(n,i),o.callback=e??null,Es(t,o,i),r.current.lanes=i,tf(r,i,n),wn(r,n),r}function xv(r,e,t,n){var i=e.current,o=Zr(),s=Ts(i);return t=vP(t),e.context===null?e.context=t:e.pendingContext=t,e=Ro(o,s),e.payload={element:r},n=n===void 0?null:n,n!==null&&(e.callback=n),r=Es(i,e,s),r!==null&&(bi(r,i,s,o),Oh(r,i,s)),s}function Op(r){if(r=r.current,!r.child)return null;switch(r.child.tag){case 5:return r.child.stateNode;default:return r.child.stateNode}}function OT(r,e){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var t=r.retryLane;r.retryLane=t!==0&&t<e?t:e}}function yE(r,e){OT(r,e),(r=r.alternate)&&OT(r,e)}function Kj(){return null}var gP=typeof reportError=="function"?reportError:function(r){console.error(r)};function SE(r){this._internalRoot=r}Ov.prototype.render=SE.prototype.render=function(r){var e=this._internalRoot;if(e===null)throw Error(he(409));xv(r,e,null,null)};Ov.prototype.unmount=SE.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var e=r.containerInfo;Ma(function(){xv(null,r,null,null)}),e[Oo]=null}};function Ov(r){this._internalRoot=r}Ov.prototype.unstable_scheduleHydration=function(r){if(r){var e=zx();r={blockedOn:null,target:r,priority:e};for(var t=0;t<ds.length&&e!==0&&e<ds[t].priority;t++);ds.splice(t,0,r),t===0&&Jx(r)}};function bE(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Pv(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function PT(){}function Vj(r,e,t,n,i){if(i){if(typeof n=="function"){var o=n;n=function(){var c=Op(s);o.call(c)}}var s=mP(e,n,r,0,null,!1,!1,"",PT);return r._reactRootContainer=s,r[Oo]=s.current,yd(r.nodeType===8?r.parentNode:r),Ma(),s}for(;i=r.lastChild;)r.removeChild(i);if(typeof n=="function"){var a=n;n=function(){var c=Op(l);a.call(c)}}var l=gE(r,0,!1,null,null,!1,!1,"",PT);return r._reactRootContainer=l,r[Oo]=l.current,yd(r.nodeType===8?r.parentNode:r),Ma(function(){xv(e,l,t,n)}),l}function Mv(r,e,t,n,i){var o=t._reactRootContainer;if(o){var s=o;if(typeof i=="function"){var a=i;i=function(){var l=Op(s);a.call(l)}}xv(e,s,r,i)}else s=Vj(t,e,r,i,n);return Op(s)}Gx=function(r){switch(r.tag){case 3:var e=r.stateNode;if(e.current.memoizedState.isDehydrated){var t=Iu(e.pendingLanes);t!==0&&(F_(e,t|1),wn(e,Jt()),!(st&6)&&(cc=Jt()+500,Bs()))}break;case 13:Ma(function(){var n=Po(r,1);if(n!==null){var i=Zr();bi(n,r,1,i)}}),yE(r,1)}};B_=function(r){if(r.tag===13){var e=Po(r,134217728);if(e!==null){var t=Zr();bi(e,r,134217728,t)}yE(r,134217728)}};Hx=function(r){if(r.tag===13){var e=Ts(r),t=Po(r,e);if(t!==null){var n=Zr();bi(t,r,e,n)}yE(r,e)}};zx=function(){return ft};Yx=function(r,e){var t=ft;try{return ft=r,e()}finally{ft=t}};Jy=function(r,e,t){switch(e){case"input":if($y(r,t),e=t.name,t.type==="radio"&&e!=null){for(t=r;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<t.length;e++){var n=t[e];if(n!==r&&n.form===r.form){var i=Ev(n);if(!i)throw Error(he(90));Cx(n),$y(n,i)}}}break;case"textarea":Ix(r,t);break;case"select":e=t.value,e!=null&&Fl(r,!!t.multiple,e,!1)}};Nx=hE;Lx=Ma;var $j={usingClientEntryPoint:!1,Events:[nf,xl,Ev,Ax,Dx,hE]},iu={findFiberByHostInstance:Sa,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},Wj={bundleType:iu.bundleType,version:iu.version,rendererPackageName:iu.rendererPackageName,rendererConfig:iu.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Lo.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=Fx(r),r===null?null:r.stateNode},findFiberByHostInstance:iu.findFiberByHostInstance||Kj,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var zf=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!zf.isDisabled&&zf.supportsFiber)try{yv=zf.inject(Wj),zi=zf}catch{}}Kn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=$j;Kn.createPortal=function(r,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!bE(e))throw Error(he(200));return Bj(r,e,null,t)};Kn.createRoot=function(r,e){if(!bE(r))throw Error(he(299));var t=!1,n="",i=gP;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(n=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=gE(r,1,!1,null,null,t,!1,n,i),r[Oo]=e.current,yd(r.nodeType===8?r.parentNode:r),new SE(e)};Kn.findDOMNode=function(r){if(r==null)return null;if(r.nodeType===1)return r;var e=r._reactInternals;if(e===void 0)throw typeof r.render=="function"?Error(he(188)):(r=Object.keys(r).join(","),Error(he(268,r)));return r=Fx(e),r=r===null?null:r.stateNode,r};Kn.flushSync=function(r){return Ma(r)};Kn.hydrate=function(r,e,t){if(!Pv(e))throw Error(he(200));return Mv(null,r,e,!0,t)};Kn.hydrateRoot=function(r,e,t){if(!bE(r))throw Error(he(405));var n=t!=null&&t.hydratedSources||null,i=!1,o="",s=gP;if(t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onRecoverableError!==void 0&&(s=t.onRecoverableError)),e=mP(e,null,r,1,t??null,i,!1,o,s),r[Oo]=e.current,yd(r),n)for(r=0;r<n.length;r++)t=n[r],i=t._getVersion,i=i(t._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[t,i]:e.mutableSourceEagerHydrationData.push(t,i);return new Ov(e)};Kn.render=function(r,e,t){if(!Pv(e))throw Error(he(200));return Mv(null,r,e,!1,t)};Kn.unmountComponentAtNode=function(r){if(!Pv(r))throw Error(he(40));return r._reactRootContainer?(Ma(function(){Mv(null,null,r,!1,function(){r._reactRootContainer=null,r[Oo]=null})}),!0):!1};Kn.unstable_batchedUpdates=hE;Kn.unstable_renderSubtreeIntoContainer=function(r,e,t,n){if(!Pv(t))throw Error(he(200));if(r==null||r._reactInternals===void 0)throw Error(he(38));return Mv(r,e,t,!1,n)};Kn.version="18.3.1-next-f1338f8080-20240426";function yP(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(yP)}catch(r){console.error(r)}}yP(),yx.exports=Kn;var Av=yx.exports;const SP=Ka(Av);var bP,MT=Av;bP=MT.createRoot,MT.hydrateRoot;/**
41
+ * @remix-run/router v1.23.2
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 kd(){return kd=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},kd.apply(this,arguments)}var Hn;(function(r){r.Pop="POP",r.Push="PUSH",r.Replace="REPLACE"})(Hn||(Hn={}));const AT="popstate";function qj(r){r===void 0&&(r={});let{initialEntries:e=["/"],initialIndex:t,v5Compat:n=!1}=r,i;i=e.map((p,h)=>u(p,typeof p=="string"?null:p.state,h===0?"default":void 0));let o=l(t??i.length-1),s=Hn.Pop,a=null;function l(p){return Math.min(Math.max(p,0),i.length-1)}function c(){return i[o]}function u(p,h,m){h===void 0&&(h=null);let w=Pp(i?c().pathname:"/",p,h,m);return Dv(w.pathname.charAt(0)==="/","relative pathnames are not supported in memory history: "+JSON.stringify(p)),w}function d(p){return typeof p=="string"?p:Id(p)}return{get index(){return o},get action(){return s},get location(){return c()},createHref:d,createURL(p){return new URL(d(p),"http://localhost")},encodeLocation(p){let h=typeof p=="string"?Wa(p):p;return{pathname:h.pathname||"",search:h.search||"",hash:h.hash||""}},push(p,h){s=Hn.Push;let m=u(p,h);o+=1,i.splice(o,i.length,m),n&&a&&a({action:s,location:m,delta:1})},replace(p,h){s=Hn.Replace;let m=u(p,h);i[o]=m,n&&a&&a({action:s,location:m,delta:0})},go(p){s=Hn.Pop;let h=l(o+p),m=i[h];o=h,a&&a({action:s,location:m,delta:p})},listen(p){return a=p,()=>{a=null}}}}function Gj(r){r===void 0&&(r={});function e(n,i){let{pathname:o,search:s,hash:a}=n.location;return Pp("",{pathname:o,search:s,hash:a},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function t(n,i){return typeof i=="string"?i:Id(i)}return zj(e,t,null,r)}function Ht(r,e){if(r===!1||r===null||typeof r>"u")throw new Error(e)}function Dv(r,e){if(!r){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function Hj(){return Math.random().toString(36).substr(2,8)}function DT(r,e){return{usr:r.state,key:r.key,idx:e}}function Pp(r,e,t,n){return t===void 0&&(t=null),kd({pathname:typeof r=="string"?r:r.pathname,search:"",hash:""},typeof e=="string"?Wa(e):e,{state:t,key:e&&e.key||n||Hj()})}function Id(r){let{pathname:e="/",search:t="",hash:n=""}=r;return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Wa(r){let e={};if(r){let t=r.indexOf("#");t>=0&&(e.hash=r.substr(t),r=r.substr(0,t));let n=r.indexOf("?");n>=0&&(e.search=r.substr(n),r=r.substr(0,n)),r&&(e.pathname=r)}return e}function zj(r,e,t,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:o=!1}=n,s=i.history,a=Hn.Pop,l=null,c=u();c==null&&(c=0,s.replaceState(kd({},s.state,{idx:c}),""));function u(){return(s.state||{idx:null}).idx}function d(){a=Hn.Pop;let w=u(),g=w==null?null:w-c;c=w,l&&l({action:a,location:m.location,delta:g})}function f(w,g){a=Hn.Push;let b=Pp(m.location,w,g);c=u()+1;let R=DT(b,c),k=m.createHref(b);try{s.pushState(R,"",k)}catch(O){if(O instanceof DOMException&&O.name==="DataCloneError")throw O;i.location.assign(k)}o&&l&&l({action:a,location:m.location,delta:1})}function p(w,g){a=Hn.Replace;let b=Pp(m.location,w,g);c=u();let R=DT(b,c),k=m.createHref(b);s.replaceState(R,"",k),o&&l&&l({action:a,location:m.location,delta:0})}function h(w){let g=i.location.origin!=="null"?i.location.origin:i.location.href,b=typeof w=="string"?w:Id(w);return b=b.replace(/ $/,"%20"),Ht(g,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,g)}let m={get action(){return a},get location(){return r(i,s)},listen(w){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(AT,d),l=w,()=>{i.removeEventListener(AT,d),l=null}},createHref(w){return e(i,w)},createURL:h,encodeLocation(w){let g=h(w);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:f,replace:p,go(w){return s.go(w)}};return m}var NT;(function(r){r.data="data",r.deferred="deferred",r.redirect="redirect",r.error="error"})(NT||(NT={}));function Yj(r,e,t){return t===void 0&&(t="/"),Jj(r,e,t)}function Jj(r,e,t,n){let i=typeof e=="string"?Wa(e):e,o=_E(i.pathname||"/",t);if(o==null)return null;let s=_P(r);Xj(s);let a=null;for(let l=0;a==null&&l<s.length;++l){let c=TP(o);a=sF(s[l],c)}return a}function _P(r,e,t,n){e===void 0&&(e=[]),t===void 0&&(t=[]),n===void 0&&(n="");let i=(o,s,a)=>{let l={relativePath:a===void 0?o.path||"":a,caseSensitive:o.caseSensitive===!0,childrenIndex:s,route:o};l.relativePath.startsWith("/")&&(Ht(l.relativePath.startsWith(n),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(n.length));let c=Cs([n,l.relativePath]),u=t.concat(l);o.children&&o.children.length>0&&(Ht(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),_P(o.children,e,u,c)),!(o.path==null&&!o.index)&&e.push({path:c,score:iF(c,o.index),routesMeta:u})};return r.forEach((o,s)=>{var a;if(o.path===""||!((a=o.path)!=null&&a.includes("?")))i(o,s);else for(let l of EP(o.path))i(o,s,l)}),e}function EP(r){let e=r.split("/");if(e.length===0)return[];let[t,...n]=e,i=t.endsWith("?"),o=t.replace(/\?$/,"");if(n.length===0)return i?[o,""]:[o];let s=EP(n.join("/")),a=[];return a.push(...s.map(l=>l===""?o:[o,l].join("/"))),i&&a.push(...s),a.map(l=>r.startsWith("/")&&l===""?"/":l)}function Xj(r){r.sort((e,t)=>e.score!==t.score?t.score-e.score:oF(e.routesMeta.map(n=>n.childrenIndex),t.routesMeta.map(n=>n.childrenIndex)))}const Qj=/^:[\w-]+$/,Zj=3,eF=2,tF=1,rF=10,nF=-2,LT=r=>r==="*";function iF(r,e){let t=r.split("/"),n=t.length;return t.some(LT)&&(n+=nF),e&&(n+=eF),t.filter(i=>!LT(i)).reduce((i,o)=>i+(Qj.test(o)?Zj:o===""?tF:rF),n)}function oF(r,e){return r.length===e.length&&r.slice(0,-1).every((n,i)=>n===e[i])?r[r.length-1]-e[e.length-1]:0}function sF(r,e,t){let{routesMeta:n}=r,i={},o="/",s=[];for(let a=0;a<n.length;++a){let l=n[a],c=a===n.length-1,u=o==="/"?e:e.slice(o.length)||"/",d=wP({path:l.relativePath,caseSensitive:l.caseSensitive,end:c},u),f=l.route;if(!d)return null;Object.assign(i,d.params),s.push({params:i,pathname:Cs([o,d.pathname]),pathnameBase:fF(Cs([o,d.pathnameBase])),route:f}),d.pathnameBase!=="/"&&(o=Cs([o,d.pathnameBase]))}return s}function wP(r,e){typeof r=="string"&&(r={path:r,caseSensitive:!1,end:!0});let[t,n]=aF(r.path,r.caseSensitive,r.end),i=e.match(t);if(!i)return null;let o=i[0],s=o.replace(/(.)\/+$/,"$1"),a=i.slice(1);return{params:n.reduce((c,u,d)=>{let{paramName:f,isOptional:p}=u;if(f==="*"){let m=a[d]||"";s=o.slice(0,o.length-m.length).replace(/(.)\/+$/,"$1")}const h=a[d];return p&&!h?c[f]=void 0:c[f]=(h||"").replace(/%2F/g,"/"),c},{}),pathname:o,pathnameBase:s,pattern:r}}function aF(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!0),Dv(r==="*"||!r.endsWith("*")||r.endsWith("/*"),'Route path "'+r+'" will be treated as if it were '+('"'+r.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+r.replace(/\*$/,"/*")+'".'));let n=[],i="^"+r.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(s,a,l)=>(n.push({paramName:a,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return r.endsWith("*")?(n.push({paramName:"*"}),i+=r==="*"||r==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?i+="\\/*$":r!==""&&r!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),n]}function TP(r){try{return r.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return Dv(!1,'The URL path "'+r+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),r}}function _E(r,e){if(e==="/")return r;if(!r.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,n=r.charAt(t);return n&&n!=="/"?null:r.slice(t)||"/"}const lF=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,cF=r=>lF.test(r);function uF(r,e){e===void 0&&(e="/");let{pathname:t,search:n="",hash:i=""}=typeof r=="string"?Wa(r):r,o;if(t)if(cF(t))o=t;else{if(t.includes("//")){let s=t;t=t.replace(/\/\/+/g,"/"),Dv(!1,"Pathnames cannot have embedded double slashes - normalizing "+(s+" -> "+t))}t.startsWith("/")?o=UT(t.substring(1),"/"):o=UT(t,e)}else o=e;return{pathname:o,search:hF(n),hash:pF(i)}}function UT(r,e){let t=e.replace(/\/+$/,"").split("/");return r.split("/").forEach(i=>{i===".."?t.length>1&&t.pop():i!=="."&&t.push(i)}),t.length>1?t.join("/"):"/"}function Sg(r,e,t,n){return"Cannot include a '"+r+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+t+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function dF(r){return r.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function EE(r,e){let t=dF(r);return e?t.map((n,i)=>i===t.length-1?n.pathname:n.pathnameBase):t.map(n=>n.pathnameBase)}function wE(r,e,t,n){n===void 0&&(n=!1);let i;typeof r=="string"?i=Wa(r):(i=kd({},r),Ht(!i.pathname||!i.pathname.includes("?"),Sg("?","pathname","search",i)),Ht(!i.pathname||!i.pathname.includes("#"),Sg("#","pathname","hash",i)),Ht(!i.search||!i.search.includes("#"),Sg("#","search","hash",i)));let o=r===""||i.pathname==="",s=o?"/":i.pathname,a;if(s==null)a=t;else{let d=e.length-1;if(!n&&s.startsWith("..")){let f=s.split("/");for(;f[0]==="..";)f.shift(),d-=1;i.pathname=f.join("/")}a=d>=0?e[d]:"/"}let l=uF(i,a),c=s&&s!=="/"&&s.endsWith("/"),u=(o||s===".")&&t.endsWith("/");return!l.pathname.endsWith("/")&&(c||u)&&(l.pathname+="/"),l}const Cs=r=>r.join("/").replace(/\/\/+/g,"/"),fF=r=>r.replace(/\/+$/,"").replace(/^\/*/,"/"),hF=r=>!r||r==="?"?"":r.startsWith("?")?r:"?"+r,pF=r=>!r||r==="#"?"":r.startsWith("#")?r:"#"+r;function vF(r){return r!=null&&typeof r.status=="number"&&typeof r.statusText=="string"&&typeof r.internal=="boolean"&&"data"in r}const RP=["post","put","patch","delete"];new Set(RP);const mF=["get",...RP];new Set(mF);/**
50
+ * React Router v6.30.3
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 xd(){return xd=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},xd.apply(this,arguments)}const TE=E.createContext(null),gF=E.createContext(null),Ks=E.createContext(null),Nv=E.createContext(null),eo=E.createContext({outlet:null,matches:[],isDataRoute:!1}),CP=E.createContext(null);function yF(r,e){let{relative:t}=e===void 0?{}:e;qa()||Ht(!1);let{basename:n,navigator:i}=E.useContext(Ks),{hash:o,pathname:s,search:a}=IP(r,{relative:t}),l=s;return n!=="/"&&(l=s==="/"?n:Cs([n,s])),i.createHref({pathname:l,search:a,hash:o})}function qa(){return E.useContext(Nv)!=null}function Ga(){return qa()||Ht(!1),E.useContext(Nv).location}function SF(r){qa()||Ht(!1);let{pathname:e}=Ga();return E.useMemo(()=>wP(r,TP(e)),[e,r])}function kP(r){E.useContext(Ks).static||E.useLayoutEffect(r)}function Pc(){let{isDataRoute:r}=E.useContext(eo);return r?NF():bF()}function bF(){qa()||Ht(!1);let r=E.useContext(TE),{basename:e,future:t,navigator:n}=E.useContext(Ks),{matches:i}=E.useContext(eo),{pathname:o}=Ga(),s=JSON.stringify(EE(i,t.v7_relativeSplatPath)),a=E.useRef(!1);return kP(()=>{a.current=!0}),E.useCallback(function(c,u){if(u===void 0&&(u={}),!a.current)return;if(typeof c=="number"){n.go(c);return}let d=wE(c,JSON.parse(s),o,u.relative==="path");r==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:Cs([e,d.pathname])),(u.replace?n.replace:n.push)(d,u.state,u)},[e,n,s,o,r])}const _F=E.createContext(null);function EF(r){let e=E.useContext(eo).outlet;return e&&E.createElement(_F.Provider,{value:r},e)}function wF(){let{matches:r}=E.useContext(eo),e=r[r.length-1];return e?e.params:{}}function IP(r,e){let{relative:t}=e===void 0?{}:e,{future:n}=E.useContext(Ks),{matches:i}=E.useContext(eo),{pathname:o}=Ga(),s=JSON.stringify(EE(i,n.v7_relativeSplatPath));return E.useMemo(()=>wE(r,JSON.parse(s),o,t==="path"),[r,s,o,t])}function TF(r,e){return RF(r,e)}function RF(r,e,t,n){qa()||Ht(!1);let{navigator:i}=E.useContext(Ks),{matches:o}=E.useContext(eo),s=o[o.length-1],a=s?s.params:{};s&&s.pathname;let l=s?s.pathnameBase:"/";s&&s.route;let c=Ga(),u;if(e){var d;let w=typeof e=="string"?Wa(e):e;l==="/"||(d=w.pathname)!=null&&d.startsWith(l)||Ht(!1),u=w}else u=c;let f=u.pathname||"/",p=f;if(l!=="/"){let w=l.replace(/^\//,"").split("/");p="/"+f.replace(/^\//,"").split("/").slice(w.length).join("/")}let h=Yj(r,{pathname:p}),m=OF(h&&h.map(w=>Object.assign({},w,{params:Object.assign({},a,w.params),pathname:Cs([l,i.encodeLocation?i.encodeLocation(w.pathname).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?l:Cs([l,i.encodeLocation?i.encodeLocation(w.pathnameBase).pathname:w.pathnameBase])})),o,t,n);return e&&m?E.createElement(Nv.Provider,{value:{location:xd({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:Hn.Pop}},m):m}function CF(){let r=DF(),e=vF(r)?r.status+" "+r.statusText:r instanceof Error?r.message:JSON.stringify(r),t=r instanceof Error?r.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return E.createElement(E.Fragment,null,E.createElement("h2",null,"Unexpected Application Error!"),E.createElement("h3",{style:{fontStyle:"italic"}},e),t?E.createElement("pre",{style:i},t):null,null)}const kF=E.createElement(CF,null);class IF extends E.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return this.state.error!==void 0?E.createElement(eo.Provider,{value:this.props.routeContext},E.createElement(CP.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function xF(r){let{routeContext:e,match:t,children:n}=r,i=E.useContext(TE);return i&&i.static&&i.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=t.route.id),E.createElement(eo.Provider,{value:e},n)}function OF(r,e,t,n){var i;if(e===void 0&&(e=[]),t===void 0&&(t=null),n===void 0&&(n=null),r==null){var o;if(!t)return null;if(t.errors)r=t.matches;else if((o=n)!=null&&o.v7_partialHydration&&e.length===0&&!t.initialized&&t.matches.length>0)r=t.matches;else return null}let s=r,a=(i=t)==null?void 0:i.errors;if(a!=null){let u=s.findIndex(d=>d.route.id&&(a==null?void 0:a[d.route.id])!==void 0);u>=0||Ht(!1),s=s.slice(0,Math.min(s.length,u+1))}let l=!1,c=-1;if(t&&n&&n.v7_partialHydration)for(let u=0;u<s.length;u++){let d=s[u];if((d.route.HydrateFallback||d.route.hydrateFallbackElement)&&(c=u),d.route.id){let{loaderData:f,errors:p}=t,h=d.route.loader&&f[d.route.id]===void 0&&(!p||p[d.route.id]===void 0);if(d.route.lazy||h){l=!0,c>=0?s=s.slice(0,c+1):s=[s[0]];break}}}return s.reduceRight((u,d,f)=>{let p,h=!1,m=null,w=null;t&&(p=a&&d.route.id?a[d.route.id]:void 0,m=d.route.errorElement||kF,l&&(c<0&&f===0?(LF("route-fallback"),h=!0,w=null):c===f&&(h=!0,w=d.route.hydrateFallbackElement||null)));let g=e.concat(s.slice(0,f+1)),b=()=>{let R;return p?R=m:h?R=w:d.route.Component?R=E.createElement(d.route.Component,null):d.route.element?R=d.route.element:R=u,E.createElement(xF,{match:d,routeContext:{outlet:u,matches:g,isDataRoute:t!=null},children:R})};return t&&(d.route.ErrorBoundary||d.route.errorElement||f===0)?E.createElement(IF,{location:t.location,revalidation:t.revalidation,component:m,error:p,children:b(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):b()},null)}var xP=function(r){return r.UseBlocker="useBlocker",r.UseRevalidator="useRevalidator",r.UseNavigateStable="useNavigate",r}(xP||{}),OP=function(r){return r.UseBlocker="useBlocker",r.UseLoaderData="useLoaderData",r.UseActionData="useActionData",r.UseRouteError="useRouteError",r.UseNavigation="useNavigation",r.UseRouteLoaderData="useRouteLoaderData",r.UseMatches="useMatches",r.UseRevalidator="useRevalidator",r.UseNavigateStable="useNavigate",r.UseRouteId="useRouteId",r}(OP||{});function PF(r){let e=E.useContext(TE);return e||Ht(!1),e}function MF(r){let e=E.useContext(gF);return e||Ht(!1),e}function AF(r){let e=E.useContext(eo);return e||Ht(!1),e}function PP(r){let e=AF(),t=e.matches[e.matches.length-1];return t.route.id||Ht(!1),t.route.id}function DF(){var r;let e=E.useContext(CP),t=MF(),n=PP();return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function NF(){let{router:r}=PF(xP.UseNavigateStable),e=PP(OP.UseNavigateStable),t=E.useRef(!1);return kP(()=>{t.current=!0}),E.useCallback(function(i,o){o===void 0&&(o={}),t.current&&(typeof i=="number"?r.navigate(i):r.navigate(i,xd({fromRouteId:e},o)))},[r,e])}const jT={};function LF(r,e,t){jT[r]||(jT[r]=!0)}function MP(r,e){r==null||r.v7_startTransition,r==null||r.v7_relativeSplatPath}const UF="startTransition",FT=gv[UF];function jF(r){let{basename:e,children:t,initialEntries:n,initialIndex:i,future:o}=r,s=E.useRef();s.current==null&&(s.current=qj({initialEntries:n,initialIndex:i,v5Compat:!0}));let a=s.current,[l,c]=E.useState({action:a.action,location:a.location}),{v7_startTransition:u}=o||{},d=E.useCallback(f=>{u&&FT?FT(()=>c(f)):c(f)},[c,u]);return E.useLayoutEffect(()=>a.listen(d),[a,d]),E.useEffect(()=>MP(o),[o]),E.createElement(AP,{basename:e,children:t,location:l.location,navigationType:l.action,navigator:a,future:o})}function Mp(r){let{to:e,replace:t,state:n,relative:i}=r;qa()||Ht(!1);let{future:o,static:s}=E.useContext(Ks),{matches:a}=E.useContext(eo),{pathname:l}=Ga(),c=Pc(),u=wE(e,EE(a,o.v7_relativeSplatPath),l,i==="path"),d=JSON.stringify(u);return E.useEffect(()=>c(JSON.parse(d),{replace:t,state:n,relative:i}),[c,d,i,t,n]),null}function FF(r){return EF(r.context)}function ml(r){Ht(!1)}function AP(r){let{basename:e="/",children:t=null,location:n,navigationType:i=Hn.Pop,navigator:o,static:s=!1,future:a}=r;qa()&&Ht(!1);let l=e.replace(/^\/*/,"/"),c=E.useMemo(()=>({basename:l,navigator:o,static:s,future:xd({v7_relativeSplatPath:!1},a)}),[l,a,o,s]);typeof n=="string"&&(n=Wa(n));let{pathname:u="/",search:d="",hash:f="",state:p=null,key:h="default"}=n,m=E.useMemo(()=>{let w=_E(u,l);return w==null?null:{location:{pathname:w,search:d,hash:f,state:p,key:h},navigationType:i}},[l,u,d,f,p,h,i]);return m==null?null:E.createElement(Ks.Provider,{value:c},E.createElement(Nv.Provider,{children:t,value:m}))}function BF(r){let{children:e,location:t}=r;return TF(xS(e),t)}new Promise(()=>{});function xS(r,e){e===void 0&&(e=[]);let t=[];return E.Children.forEach(r,(n,i)=>{if(!E.isValidElement(n))return;let o=[...e,i];if(n.type===E.Fragment){t.push.apply(t,xS(n.props.children,o));return}n.type!==ml&&Ht(!1),!n.props.index||!n.props.children||Ht(!1);let s={id:n.props.id||o.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(s.children=xS(n.props.children,o)),t.push(s)}),t}/**
59
+ * React Router DOM v6.30.3
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 OS(){return OS=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},OS.apply(this,arguments)}function KF(r,e){if(r==null)return{};var t={},n=Object.keys(r),i,o;for(o=0;o<n.length;o++)i=n[o],!(e.indexOf(i)>=0)&&(t[i]=r[i]);return t}function VF(r){return!!(r.metaKey||r.altKey||r.ctrlKey||r.shiftKey)}function $F(r,e){return r.button===0&&(!e||e==="_self")&&!VF(r)}function PS(r){return r===void 0&&(r=""),new URLSearchParams(typeof r=="string"||Array.isArray(r)||r instanceof URLSearchParams?r:Object.keys(r).reduce((e,t)=>{let n=r[t];return e.concat(Array.isArray(n)?n.map(i=>[t,i]):[[t,n]])},[]))}function WF(r,e){let t=PS(r);return e&&e.forEach((n,i)=>{t.has(i)||e.getAll(i).forEach(o=>{t.append(i,o)})}),t}const qF=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],GF="6";try{window.__reactRouterVersion=GF}catch{}const HF="startTransition",BT=gv[HF];function zF(r){let{basename:e,children:t,future:n,window:i}=r,o=E.useRef();o.current==null&&(o.current=Gj({window:i,v5Compat:!0}));let s=o.current,[a,l]=E.useState({action:s.action,location:s.location}),{v7_startTransition:c}=n||{},u=E.useCallback(d=>{c&&BT?BT(()=>l(d)):l(d)},[l,c]);return E.useLayoutEffect(()=>s.listen(u),[s,u]),E.useEffect(()=>MP(n),[n]),E.createElement(AP,{basename:e,children:t,location:a.location,navigationType:a.action,navigator:s,future:n})}const YF=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",JF=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,XF=E.forwardRef(function(e,t){let{onClick:n,relative:i,reloadDocument:o,replace:s,state:a,target:l,to:c,preventScrollReset:u,viewTransition:d}=e,f=KF(e,qF),{basename:p}=E.useContext(Ks),h,m=!1;if(typeof c=="string"&&JF.test(c)&&(h=c,YF))try{let R=new URL(window.location.href),k=c.startsWith("//")?new URL(R.protocol+c):new URL(c),O=_E(k.pathname,p);k.origin===R.origin&&O!=null?c=O+k.search+k.hash:m=!0}catch{}let w=yF(c,{relative:i}),g=QF(c,{replace:s,state:a,target:l,preventScrollReset:u,relative:i,viewTransition:d});function b(R){n&&n(R),R.defaultPrevented||g(R)}return E.createElement("a",OS({},f,{href:h||w,onClick:m||o?n:b,ref:t,target:l}))});var KT;(function(r){r.UseScrollRestoration="useScrollRestoration",r.UseSubmit="useSubmit",r.UseSubmitFetcher="useSubmitFetcher",r.UseFetcher="useFetcher",r.useViewTransitionState="useViewTransitionState"})(KT||(KT={}));var VT;(function(r){r.UseFetcher="useFetcher",r.UseFetchers="useFetchers",r.UseScrollRestoration="useScrollRestoration"})(VT||(VT={}));function QF(r,e){let{target:t,replace:n,state:i,preventScrollReset:o,relative:s,viewTransition:a}=e===void 0?{}:e,l=Pc(),c=Ga(),u=IP(r,{relative:s});return E.useCallback(d=>{if($F(d,t)){d.preventDefault();let f=n!==void 0?n:Id(c)===Id(u);l(r,{replace:f,state:i,preventScrollReset:o,relative:s,viewTransition:a})}},[c,l,u,n,i,t,r,o,s,a])}function DP(r){let e=E.useRef(PS(r)),t=E.useRef(!1),n=Ga(),i=E.useMemo(()=>WF(n.search,t.current?null:e.current),[n.search]),o=Pc(),s=E.useCallback((a,l)=>{const c=PS(typeof a=="function"?a(i):a);t.current=!0,o("?"+c,l)},[o,i]);return[i,s]}var ZF=(r,e,t,n,i,o,s,a)=>{let l=document.documentElement,c=["light","dark"];function u(p){(Array.isArray(r)?r:[r]).forEach(h=>{let m=h==="class",w=m&&o?i.map(g=>o[g]||g):i;m?(l.classList.remove(...w),l.classList.add(o&&o[p]?o[p]:p)):l.setAttribute(h,p)}),d(p)}function d(p){a&&c.includes(p)&&(l.style.colorScheme=p)}function f(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(n)u(n);else try{let p=localStorage.getItem(e)||t,h=s&&p==="system"?f():p;u(h)}catch{}},eB=E.createContext(void 0),tB={setTheme:r=>{},themes:[]},rB=()=>{var r;return(r=E.useContext(eB))!=null?r:tB};E.memo(({forcedTheme:r,storageKey:e,attribute:t,enableSystem:n,enableColorScheme:i,defaultTheme:o,value:s,themes:a,nonce:l,scriptProps:c})=>{let u=JSON.stringify([t,e,o,r,a,s,n,i]).slice(1,-1);return E.createElement("script",{...c,suppressHydrationWarning:!0,nonce:typeof window>"u"?l:"",dangerouslySetInnerHTML:{__html:`(${ZF.toString()})(${u})`}})});function nB(r){if(typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}const iB=r=>{switch(r){case"success":return aB;case"info":return cB;case"warning":return lB;case"error":return uB;default:return null}},oB=Array(12).fill(0),sB=({visible:r,className:e})=>pe.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":r},pe.createElement("div",{className:"sonner-spinner"},oB.map((t,n)=>pe.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),aB=pe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},pe.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),lB=pe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},pe.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),cB=pe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},pe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),uB=pe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},pe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),dB=pe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},pe.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),pe.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),fB=()=>{const[r,e]=pe.useState(document.hidden);return pe.useEffect(()=>{const t=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",t),()=>window.removeEventListener("visibilitychange",t)},[]),r};let MS=1;class hB{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{const t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;const{message:n,...i}=e,o=typeof(e==null?void 0:e.id)=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:MS++,s=this.toasts.find(l=>l.id===o),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),s?this.toasts=this.toasts.map(l=>l.id===o?(this.publish({...l,...e,id:o,title:n}),{...l,...e,id:o,dismissible:a,title:n}):l):this.addToast({title:n,...i,dismissible:a,id:o}),o},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(t=>{this.subscribers.forEach(n=>n({id:t.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));const i=Promise.resolve(e instanceof Function?e():e);let o=n!==void 0,s;const a=i.then(async c=>{if(s=["resolve",c],pe.isValidElement(c))o=!1,this.create({id:n,type:"default",message:c});else if(vB(c)&&!c.ok){o=!1;const d=typeof t.error=="function"?await t.error(`HTTP error! status: ${c.status}`):t.error,f=typeof t.description=="function"?await t.description(`HTTP error! status: ${c.status}`):t.description,h=typeof d=="object"&&!pe.isValidElement(d)?d:{message:d};this.create({id:n,type:"error",description:f,...h})}else if(c instanceof Error){o=!1;const d=typeof t.error=="function"?await t.error(c):t.error,f=typeof t.description=="function"?await t.description(c):t.description,h=typeof d=="object"&&!pe.isValidElement(d)?d:{message:d};this.create({id:n,type:"error",description:f,...h})}else if(t.success!==void 0){o=!1;const d=typeof t.success=="function"?await t.success(c):t.success,f=typeof t.description=="function"?await t.description(c):t.description,h=typeof d=="object"&&!pe.isValidElement(d)?d:{message:d};this.create({id:n,type:"success",description:f,...h})}}).catch(async c=>{if(s=["reject",c],t.error!==void 0){o=!1;const u=typeof t.error=="function"?await t.error(c):t.error,d=typeof t.description=="function"?await t.description(c):t.description,p=typeof u=="object"&&!pe.isValidElement(u)?u:{message:u};this.create({id:n,type:"error",description:d,...p})}}).finally(()=>{o&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),l=()=>new Promise((c,u)=>a.then(()=>s[0]==="reject"?u(s[1]):c(s[1])).catch(u));return typeof n!="string"&&typeof n!="number"?{unwrap:l}:Object.assign(n,{unwrap:l})},this.custom=(e,t)=>{const n=(t==null?void 0:t.id)||MS++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const mn=new hB,pB=(r,e)=>{const t=(e==null?void 0:e.id)||MS++;return mn.addToast({title:r,...e,id:t}),t},vB=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",mB=pB,gB=()=>mn.toasts,yB=()=>mn.getActiveToasts();Object.assign(mB,{success:mn.success,info:mn.info,warning:mn.warning,error:mn.error,custom:mn.custom,message:mn.message,promise:mn.promise,dismiss:mn.dismiss,loading:mn.loading},{getHistory:gB,getToasts:yB});nB("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Yf(r){return r.label!==void 0}const SB=3,bB="24px",_B="16px",$T=4e3,EB=356,wB=14,TB=45,RB=200;function Ai(...r){return r.filter(Boolean).join(" ")}function CB(r){const[e,t]=r.split("-"),n=[];return e&&n.push(e),t&&n.push(t),n}const kB=r=>{var e,t,n,i,o,s,a,l,c;const{invert:u,toast:d,unstyled:f,interacting:p,setHeights:h,visibleToasts:m,heights:w,index:g,toasts:b,expanded:R,removeToast:k,defaultRichColors:O,closeButton:T,style:x,cancelButtonStyle:C,actionButtonStyle:N,className:F="",descriptionClassName:H="",duration:ie,position:$,gap:X,expandByDefault:oe,classNames:re,icons:ae,closeButtonAriaLabel:q="Close toast"}=r,[z,Q]=pe.useState(null),[Ie,Y]=pe.useState(null),[le,B]=pe.useState(!1),[W,A]=pe.useState(!1),[D,P]=pe.useState(!1),[M,I]=pe.useState(!1),[j,U]=pe.useState(!1),[K,G]=pe.useState(0),[ee,se]=pe.useState(0),Ce=pe.useRef(d.duration||ie||$T),Re=pe.useRef(null),ge=pe.useRef(null),He=g===0,Qe=g+1<=m,$e=d.type,ve=d.dismissible!==!1,We=d.className||"",un=d.descriptionClassName||"",Rr=pe.useMemo(()=>w.findIndex(Le=>Le.toastId===d.id)||0,[w,d.id]),gt=pe.useMemo(()=>{var Le;return(Le=d.closeButton)!=null?Le:T},[d.closeButton,T]),vr=pe.useMemo(()=>d.duration||ie||$T,[d.duration,ie]),mr=pe.useRef(0),Rt=pe.useRef(0),Rn=pe.useRef(0),ye=pe.useRef(null),[de,J]=$.split("-"),te=pe.useMemo(()=>w.reduce((Le,pt,Kt)=>Kt>=Rr?Le:Le+pt.height,0),[w,Rr]),ne=fB(),ue=d.invert||u,_e=$e==="loading";Rt.current=pe.useMemo(()=>Rr*X+te,[Rr,te]),pe.useEffect(()=>{Ce.current=vr},[vr]),pe.useEffect(()=>{B(!0)},[]),pe.useEffect(()=>{const Le=ge.current;if(Le){const pt=Le.getBoundingClientRect().height;return se(pt),h(Kt=>[{toastId:d.id,height:pt,position:d.position},...Kt]),()=>h(Kt=>Kt.filter(Gr=>Gr.toastId!==d.id))}},[h,d.id]),pe.useLayoutEffect(()=>{if(!le)return;const Le=ge.current,pt=Le.style.height;Le.style.height="auto";const Kt=Le.getBoundingClientRect().height;Le.style.height=pt,se(Kt),h(Gr=>Gr.find(tt=>tt.toastId===d.id)?Gr.map(tt=>tt.toastId===d.id?{...tt,height:Kt}:tt):[{toastId:d.id,height:Kt,position:d.position},...Gr])},[le,d.title,d.description,h,d.id,d.jsx,d.action,d.cancel]);const we=pe.useCallback(()=>{A(!0),G(Rt.current),h(Le=>Le.filter(pt=>pt.toastId!==d.id)),setTimeout(()=>{k(d)},RB)},[d,k,h,Rt]);pe.useEffect(()=>{if(d.promise&&$e==="loading"||d.duration===1/0||d.type==="loading")return;let Le;return R||p||ne?(()=>{if(Rn.current<mr.current){const Gr=new Date().getTime()-mr.current;Ce.current=Ce.current-Gr}Rn.current=new Date().getTime()})():(()=>{Ce.current!==1/0&&(mr.current=new Date().getTime(),Le=setTimeout(()=>{d.onAutoClose==null||d.onAutoClose.call(d,d),we()},Ce.current))})(),()=>clearTimeout(Le)},[R,p,d,$e,ne,we]),pe.useEffect(()=>{d.delete&&(we(),d.onDismiss==null||d.onDismiss.call(d,d))},[we,d.delete]);function ze(){var Le;if(ae!=null&&ae.loading){var pt;return pe.createElement("div",{className:Ai(re==null?void 0:re.loader,d==null||(pt=d.classNames)==null?void 0:pt.loader,"sonner-loader"),"data-visible":$e==="loading"},ae.loading)}return pe.createElement(sB,{className:Ai(re==null?void 0:re.loader,d==null||(Le=d.classNames)==null?void 0:Le.loader),visible:$e==="loading"})}const dt=d.icon||(ae==null?void 0:ae[$e])||iB($e);var ht,Bt;return pe.createElement("li",{tabIndex:0,ref:ge,className:Ai(F,We,re==null?void 0:re.toast,d==null||(e=d.classNames)==null?void 0:e.toast,re==null?void 0:re.default,re==null?void 0:re[$e],d==null||(t=d.classNames)==null?void 0:t[$e]),"data-sonner-toast":"","data-rich-colors":(ht=d.richColors)!=null?ht:O,"data-styled":!(d.jsx||d.unstyled||f),"data-mounted":le,"data-promise":!!d.promise,"data-swiped":j,"data-removed":W,"data-visible":Qe,"data-y-position":de,"data-x-position":J,"data-index":g,"data-front":He,"data-swiping":D,"data-dismissible":ve,"data-type":$e,"data-invert":ue,"data-swipe-out":M,"data-swipe-direction":Ie,"data-expanded":!!(R||oe&&le),"data-testid":d.testId,style:{"--index":g,"--toasts-before":g,"--z-index":b.length-g,"--offset":`${W?K:Rt.current}px`,"--initial-height":oe?"auto":`${ee}px`,...x,...d.style},onDragEnd:()=>{P(!1),Q(null),ye.current=null},onPointerDown:Le=>{Le.button!==2&&(_e||!ve||(Re.current=new Date,G(Rt.current),Le.target.setPointerCapture(Le.pointerId),Le.target.tagName!=="BUTTON"&&(P(!0),ye.current={x:Le.clientX,y:Le.clientY})))},onPointerUp:()=>{var Le,pt,Kt;if(M||!ve)return;ye.current=null;const Gr=Number(((Le=ge.current)==null?void 0:Le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Qa=Number(((pt=ge.current)==null?void 0:pt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),tt=new Date().getTime()-((Kt=Re.current)==null?void 0:Kt.getTime()),or=z==="x"?Gr:Qa,Za=Math.abs(or)/tt;if(Math.abs(or)>=TB||Za>.11){G(Rt.current),d.onDismiss==null||d.onDismiss.call(d,d),Y(z==="x"?Gr>0?"right":"left":Qa>0?"down":"up"),we(),I(!0);return}else{var dn,Hr;(dn=ge.current)==null||dn.style.setProperty("--swipe-amount-x","0px"),(Hr=ge.current)==null||Hr.style.setProperty("--swipe-amount-y","0px")}U(!1),P(!1),Q(null)},onPointerMove:Le=>{var pt,Kt,Gr;if(!ye.current||!ve||((pt=window.getSelection())==null?void 0:pt.toString().length)>0)return;const tt=Le.clientY-ye.current.y,or=Le.clientX-ye.current.x;var Za;const dn=(Za=r.swipeDirections)!=null?Za:CB($);!z&&(Math.abs(or)>1||Math.abs(tt)>1)&&Q(Math.abs(or)>Math.abs(tt)?"x":"y");let Hr={x:0,y:0};const Jc=Pi=>1/(1.5+Math.abs(Pi)/20);if(z==="y"){if(dn.includes("top")||dn.includes("bottom"))if(dn.includes("top")&&tt<0||dn.includes("bottom")&&tt>0)Hr.y=tt;else{const Pi=tt*Jc(tt);Hr.y=Math.abs(Pi)<Math.abs(tt)?Pi:tt}}else if(z==="x"&&(dn.includes("left")||dn.includes("right")))if(dn.includes("left")&&or<0||dn.includes("right")&&or>0)Hr.x=or;else{const Pi=or*Jc(or);Hr.x=Math.abs(Pi)<Math.abs(or)?Pi:or}(Math.abs(Hr.x)>0||Math.abs(Hr.y)>0)&&U(!0),(Kt=ge.current)==null||Kt.style.setProperty("--swipe-amount-x",`${Hr.x}px`),(Gr=ge.current)==null||Gr.style.setProperty("--swipe-amount-y",`${Hr.y}px`)}},gt&&!d.jsx&&$e!=="loading"?pe.createElement("button",{"aria-label":q,"data-disabled":_e,"data-close-button":!0,onClick:_e||!ve?()=>{}:()=>{we(),d.onDismiss==null||d.onDismiss.call(d,d)},className:Ai(re==null?void 0:re.closeButton,d==null||(n=d.classNames)==null?void 0:n.closeButton)},(Bt=ae==null?void 0:ae.close)!=null?Bt:dB):null,($e||d.icon||d.promise)&&d.icon!==null&&((ae==null?void 0:ae[$e])!==null||d.icon)?pe.createElement("div",{"data-icon":"",className:Ai(re==null?void 0:re.icon,d==null||(i=d.classNames)==null?void 0:i.icon)},d.promise||d.type==="loading"&&!d.icon?d.icon||ze():null,d.type!=="loading"?dt:null):null,pe.createElement("div",{"data-content":"",className:Ai(re==null?void 0:re.content,d==null||(o=d.classNames)==null?void 0:o.content)},pe.createElement("div",{"data-title":"",className:Ai(re==null?void 0:re.title,d==null||(s=d.classNames)==null?void 0:s.title)},d.jsx?d.jsx:typeof d.title=="function"?d.title():d.title),d.description?pe.createElement("div",{"data-description":"",className:Ai(H,un,re==null?void 0:re.description,d==null||(a=d.classNames)==null?void 0:a.description)},typeof d.description=="function"?d.description():d.description):null),pe.isValidElement(d.cancel)?d.cancel:d.cancel&&Yf(d.cancel)?pe.createElement("button",{"data-button":!0,"data-cancel":!0,style:d.cancelButtonStyle||C,onClick:Le=>{Yf(d.cancel)&&ve&&(d.cancel.onClick==null||d.cancel.onClick.call(d.cancel,Le),we())},className:Ai(re==null?void 0:re.cancelButton,d==null||(l=d.classNames)==null?void 0:l.cancelButton)},d.cancel.label):null,pe.isValidElement(d.action)?d.action:d.action&&Yf(d.action)?pe.createElement("button",{"data-button":!0,"data-action":!0,style:d.actionButtonStyle||N,onClick:Le=>{Yf(d.action)&&(d.action.onClick==null||d.action.onClick.call(d.action,Le),!Le.defaultPrevented&&we())},className:Ai(re==null?void 0:re.actionButton,d==null||(c=d.classNames)==null?void 0:c.actionButton)},d.action.label):null)};function WT(){if(typeof window>"u"||typeof document>"u")return"ltr";const r=document.documentElement.getAttribute("dir");return r==="auto"||!r?window.getComputedStyle(document.documentElement).direction:r}function IB(r,e){const t={};return[r,e].forEach((n,i)=>{const o=i===1,s=o?"--mobile-offset":"--offset",a=o?_B:bB;function l(c){["top","right","bottom","left"].forEach(u=>{t[`${s}-${u}`]=typeof c=="number"?`${c}px`:c})}typeof n=="number"||typeof n=="string"?l(n):typeof n=="object"?["top","right","bottom","left"].forEach(c=>{n[c]===void 0?t[`${s}-${c}`]=a:t[`${s}-${c}`]=typeof n[c]=="number"?`${n[c]}px`:n[c]}):l(a)}),t}const xB=pe.forwardRef(function(e,t){const{id:n,invert:i,position:o="bottom-right",hotkey:s=["altKey","KeyT"],expand:a,closeButton:l,className:c,offset:u,mobileOffset:d,theme:f="light",richColors:p,duration:h,style:m,visibleToasts:w=SB,toastOptions:g,dir:b=WT(),gap:R=wB,icons:k,containerAriaLabel:O="Notifications"}=e,[T,x]=pe.useState([]),C=pe.useMemo(()=>n?T.filter(le=>le.toasterId===n):T.filter(le=>!le.toasterId),[T,n]),N=pe.useMemo(()=>Array.from(new Set([o].concat(C.filter(le=>le.position).map(le=>le.position)))),[C,o]),[F,H]=pe.useState([]),[ie,$]=pe.useState(!1),[X,oe]=pe.useState(!1),[re,ae]=pe.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),q=pe.useRef(null),z=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),Q=pe.useRef(null),Ie=pe.useRef(!1),Y=pe.useCallback(le=>{x(B=>{var W;return(W=B.find(A=>A.id===le.id))!=null&&W.delete||mn.dismiss(le.id),B.filter(({id:A})=>A!==le.id)})},[]);return pe.useEffect(()=>mn.subscribe(le=>{if(le.dismiss){requestAnimationFrame(()=>{x(B=>B.map(W=>W.id===le.id?{...W,delete:!0}:W))});return}setTimeout(()=>{SP.flushSync(()=>{x(B=>{const W=B.findIndex(A=>A.id===le.id);return W!==-1?[...B.slice(0,W),{...B[W],...le},...B.slice(W+1)]:[le,...B]})})})}),[T]),pe.useEffect(()=>{if(f!=="system"){ae(f);return}if(f==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ae("dark"):ae("light")),typeof window>"u")return;const le=window.matchMedia("(prefers-color-scheme: dark)");try{le.addEventListener("change",({matches:B})=>{ae(B?"dark":"light")})}catch{le.addListener(({matches:W})=>{try{ae(W?"dark":"light")}catch(A){console.error(A)}})}},[f]),pe.useEffect(()=>{T.length<=1&&$(!1)},[T]),pe.useEffect(()=>{const le=B=>{var W;if(s.every(P=>B[P]||B.code===P)){var D;$(!0),(D=q.current)==null||D.focus()}B.code==="Escape"&&(document.activeElement===q.current||(W=q.current)!=null&&W.contains(document.activeElement))&&$(!1)};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[s]),pe.useEffect(()=>{if(q.current)return()=>{Q.current&&(Q.current.focus({preventScroll:!0}),Q.current=null,Ie.current=!1)}},[q.current]),pe.createElement("section",{ref:t,"aria-label":`${O} ${z}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},N.map((le,B)=>{var W;const[A,D]=le.split("-");return C.length?pe.createElement("ol",{key:le,dir:b==="auto"?WT():b,tabIndex:-1,ref:q,className:c,"data-sonner-toaster":!0,"data-sonner-theme":re,"data-y-position":A,"data-x-position":D,style:{"--front-toast-height":`${((W=F[0])==null?void 0:W.height)||0}px`,"--width":`${EB}px`,"--gap":`${R}px`,...m,...IB(u,d)},onBlur:P=>{Ie.current&&!P.currentTarget.contains(P.relatedTarget)&&(Ie.current=!1,Q.current&&(Q.current.focus({preventScroll:!0}),Q.current=null))},onFocus:P=>{P.target instanceof HTMLElement&&P.target.dataset.dismissible==="false"||Ie.current||(Ie.current=!0,Q.current=P.relatedTarget)},onMouseEnter:()=>$(!0),onMouseMove:()=>$(!0),onMouseLeave:()=>{X||$(!1)},onDragEnd:()=>$(!1),onPointerDown:P=>{P.target instanceof HTMLElement&&P.target.dataset.dismissible==="false"||oe(!0)},onPointerUp:()=>oe(!1)},C.filter(P=>!P.position&&B===0||P.position===le).map((P,M)=>{var I,j;return pe.createElement(kB,{key:P.id,icons:k,index:M,toast:P,defaultRichColors:p,duration:(I=g==null?void 0:g.duration)!=null?I:h,className:g==null?void 0:g.className,descriptionClassName:g==null?void 0:g.descriptionClassName,invert:i,visibleToasts:w,closeButton:(j=g==null?void 0:g.closeButton)!=null?j:l,interacting:X,position:le,style:g==null?void 0:g.style,unstyled:g==null?void 0:g.unstyled,classNames:g==null?void 0:g.classNames,cancelButtonStyle:g==null?void 0:g.cancelButtonStyle,actionButtonStyle:g==null?void 0:g.actionButtonStyle,closeButtonAriaLabel:g==null?void 0:g.closeButtonAriaLabel,removeToast:Y,toasts:C.filter(U=>U.position==P.position),heights:F.filter(U=>U.position==P.position),setHeights:H,expandByDefault:a,gap:R,expanded:ie,swipeDirections:e.swipeDirections})})):null}))});/**
68
+ * @license lucide-react v1.14.0 - ISC
69
+ *
70
+ * This source code is licensed under the ISC license.
71
+ * See the LICENSE file in the root directory of this source tree.
72
+ */const NP=(...r)=>r.filter((e,t,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===t).join(" ").trim();/**
73
+ * @license lucide-react v1.14.0 - ISC
74
+ *
75
+ * This source code is licensed under the ISC license.
76
+ * See the LICENSE file in the root directory of this source tree.
77
+ */const OB=r=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
78
+ * @license lucide-react v1.14.0 - ISC
79
+ *
80
+ * This source code is licensed under the ISC license.
81
+ * See the LICENSE file in the root directory of this source tree.
82
+ */const PB=r=>r.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase());/**
83
+ * @license lucide-react v1.14.0 - ISC
84
+ *
85
+ * This source code is licensed under the ISC license.
86
+ * See the LICENSE file in the root directory of this source tree.
87
+ */const qT=r=>{const e=PB(r);return e.charAt(0).toUpperCase()+e.slice(1)};/**
88
+ * @license lucide-react v1.14.0 - ISC
89
+ *
90
+ * This source code is licensed under the ISC license.
91
+ * See the LICENSE file in the root directory of this source tree.
92
+ */var bg={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
93
+ * @license lucide-react v1.14.0 - ISC
94
+ *
95
+ * This source code is licensed under the ISC license.
96
+ * See the LICENSE file in the root directory of this source tree.
97
+ */const MB=r=>{for(const e in r)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},AB=E.createContext({}),DB=()=>E.useContext(AB),NB=E.forwardRef(({color:r,size:e,strokeWidth:t,absoluteStrokeWidth:n,className:i="",children:o,iconNode:s,...a},l)=>{const{size:c=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f="currentColor",className:p=""}=DB()??{},h=n??d?Number(t??u)*24/Number(e??c):t??u;return E.createElement("svg",{ref:l,...bg,width:e??c??bg.width,height:e??c??bg.height,stroke:r??f,strokeWidth:h,className:NP("lucide",p,i),...!o&&!MB(a)&&{"aria-hidden":"true"},...a},[...s.map(([m,w])=>E.createElement(m,w)),...Array.isArray(o)?o:[o]])});/**
98
+ * @license lucide-react v1.14.0 - ISC
99
+ *
100
+ * This source code is licensed under the ISC license.
101
+ * See the LICENSE file in the root directory of this source tree.
102
+ */const jt=(r,e)=>{const t=E.forwardRef(({className:n,...i},o)=>E.createElement(NB,{ref:o,iconNode:e,className:NP(`lucide-${OB(qT(r))}`,`lucide-${r}`,n),...i}));return t.displayName=qT(r),t};/**
103
+ * @license lucide-react v1.14.0 - ISC
104
+ *
105
+ * This source code is licensed under the ISC license.
106
+ * See the LICENSE file in the root directory of this source tree.
107
+ */const LB=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],UB=jt("arrow-left",LB);/**
108
+ * @license lucide-react v1.14.0 - ISC
109
+ *
110
+ * This source code is licensed under the ISC license.
111
+ * See the LICENSE file in the root directory of this source tree.
112
+ */const jB=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],LP=jt("check",jB);/**
113
+ * @license lucide-react v1.14.0 - ISC
114
+ *
115
+ * This source code is licensed under the ISC license.
116
+ * See the LICENSE file in the root directory of this source tree.
117
+ */const FB=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],UP=jt("chevron-down",FB);/**
118
+ * @license lucide-react v1.14.0 - ISC
119
+ *
120
+ * This source code is licensed under the ISC license.
121
+ * See the LICENSE file in the root directory of this source tree.
122
+ */const BB=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],jP=jt("chevron-right",BB);/**
123
+ * @license lucide-react v1.14.0 - ISC
124
+ *
125
+ * This source code is licensed under the ISC license.
126
+ * See the LICENSE file in the root directory of this source tree.
127
+ */const KB=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],VB=jt("circle-check",KB);/**
128
+ * @license lucide-react v1.14.0 - ISC
129
+ *
130
+ * This source code is licensed under the ISC license.
131
+ * See the LICENSE file in the root directory of this source tree.
132
+ */const $B=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],WB=jt("ellipsis",$B);/**
133
+ * @license lucide-react v1.14.0 - ISC
134
+ *
135
+ * This source code is licensed under the ISC license.
136
+ * See the LICENSE file in the root directory of this source tree.
137
+ */const qB=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],GB=jt("file-pen",qB);/**
138
+ * @license lucide-react v1.14.0 - ISC
139
+ *
140
+ * This source code is licensed under the ISC license.
141
+ * See the LICENSE file in the root directory of this source tree.
142
+ */const HB=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"11.5",cy:"14.5",r:"2.5",key:"1bq0ko"}],["path",{d:"M13.3 16.3 15 18",key:"2quom7"}]],zB=jt("file-search",HB);/**
143
+ * @license lucide-react v1.14.0 - ISC
144
+ *
145
+ * This source code is licensed under the ISC license.
146
+ * See the LICENSE file in the root directory of this source tree.
147
+ */const YB=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],JB=jt("globe",YB);/**
148
+ * @license lucide-react v1.14.0 - ISC
149
+ *
150
+ * This source code is licensed under the ISC license.
151
+ * See the LICENSE file in the root directory of this source tree.
152
+ */const XB=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],QB=jt("info",XB);/**
153
+ * @license lucide-react v1.14.0 - ISC
154
+ *
155
+ * This source code is licensed under the ISC license.
156
+ * See the LICENSE file in the root directory of this source tree.
157
+ */const ZB=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]],eK=jt("list-checks",ZB);/**
158
+ * @license lucide-react v1.14.0 - ISC
159
+ *
160
+ * This source code is licensed under the ISC license.
161
+ * See the LICENSE file in the root directory of this source tree.
162
+ */const tK=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Lv=jt("loader-circle",tK);/**
163
+ * @license lucide-react v1.14.0 - ISC
164
+ *
165
+ * This source code is licensed under the ISC license.
166
+ * See the LICENSE file in the root directory of this source tree.
167
+ */const rK=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],FP=jt("message-square",rK);/**
168
+ * @license lucide-react v1.14.0 - ISC
169
+ *
170
+ * This source code is licensed under the ISC license.
171
+ * See the LICENSE file in the root directory of this source tree.
172
+ */const nK=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],iK=jt("octagon-x",nK);/**
173
+ * @license lucide-react v1.14.0 - ISC
174
+ *
175
+ * This source code is licensed under the ISC license.
176
+ * See the LICENSE file in the root directory of this source tree.
177
+ */const oK=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],BP=jt("panel-left",oK);/**
178
+ * @license lucide-react v1.14.0 - ISC
179
+ *
180
+ * This source code is licensed under the ISC license.
181
+ * See the LICENSE file in the root directory of this source tree.
182
+ */const sK=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],GT=jt("plus",sK);/**
183
+ * @license lucide-react v1.14.0 - ISC
184
+ *
185
+ * This source code is licensed under the ISC license.
186
+ * See the LICENSE file in the root directory of this source tree.
187
+ */const aK=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],lK=jt("search",aK);/**
188
+ * @license lucide-react v1.14.0 - ISC
189
+ *
190
+ * This source code is licensed under the ISC license.
191
+ * See the LICENSE file in the root directory of this source tree.
192
+ */const cK=[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]],uK=jt("send-horizontal",cK);/**
193
+ * @license lucide-react v1.14.0 - ISC
194
+ *
195
+ * This source code is licensed under the ISC license.
196
+ * See the LICENSE file in the root directory of this source tree.
197
+ */const dK=[["path",{d:"M22 11v1a10 10 0 1 1-9-10",key:"ew0xw9"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}],["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}]],fK=jt("smile-plus",dK);/**
198
+ * @license lucide-react v1.14.0 - ISC
199
+ *
200
+ * This source code is licensed under the ISC license.
201
+ * See the LICENSE file in the root directory of this source tree.
202
+ */const hK=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],pK=jt("star",hK);/**
203
+ * @license lucide-react v1.14.0 - ISC
204
+ *
205
+ * This source code is licensed under the ISC license.
206
+ * See the LICENSE file in the root directory of this source tree.
207
+ */const vK=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],HT=jt("terminal",vK);/**
208
+ * @license lucide-react v1.14.0 - ISC
209
+ *
210
+ * This source code is licensed under the ISC license.
211
+ * See the LICENSE file in the root directory of this source tree.
212
+ */const mK=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],KP=jt("triangle-alert",mK);/**
213
+ * @license lucide-react v1.14.0 - ISC
214
+ *
215
+ * This source code is licensed under the ISC license.
216
+ * See the LICENSE file in the root directory of this source tree.
217
+ */const gK=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],RE=jt("x",gK),zT=({...r})=>{const{theme:e="system"}=rB();return y.jsx(xB,{theme:e,className:"toaster group",icons:{success:y.jsx(VB,{className:"size-4"}),info:y.jsx(QB,{className:"size-4"}),warning:y.jsx(KP,{className:"size-4"}),error:y.jsx(iK,{className:"size-4"}),loading:y.jsx(Lv,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},toastOptions:{classNames:{toast:"cn-toast"}},...r})};function YT(r,e){if(typeof r=="function")return r(e);r!=null&&(r.current=e)}function Ao(...r){return e=>{let t=!1;const n=r.map(i=>{const o=YT(i,e);return!t&&typeof o=="function"&&(t=!0),o});if(t)return()=>{for(let i=0;i<n.length;i++){const o=n[i];typeof o=="function"?o():YT(r[i],null)}}}}function _t(...r){return E.useCallback(Ao(...r),r)}function Aa(r){const e=SK(r),t=E.forwardRef((n,i)=>{const{children:o,...s}=n,a=E.Children.toArray(o),l=a.find(_K);if(l){const c=l.props.children,u=a.map(d=>d===l?E.Children.count(c)>1?E.Children.only(null):E.isValidElement(c)?c.props.children:null:d);return y.jsx(e,{...s,ref:i,children:E.isValidElement(c)?E.cloneElement(c,void 0,u):null})}return y.jsx(e,{...s,ref:i,children:o})});return t.displayName=`${r}.Slot`,t}var yK=Aa("Slot");function SK(r){const e=E.forwardRef((t,n)=>{const{children:i,...o}=t;if(E.isValidElement(i)){const s=wK(i),a=EK(o,i.props);return i.type!==E.Fragment&&(a.ref=n?Ao(n,s):s),E.cloneElement(i,a)}return E.Children.count(i)>1?E.Children.only(null):null});return e.displayName=`${r}.SlotClone`,e}var VP=Symbol("radix.slottable");function bK(r){const e=({children:t})=>y.jsx(y.Fragment,{children:t});return e.displayName=`${r}.Slottable`,e.__radixId=VP,e}function _K(r){return E.isValidElement(r)&&typeof r.type=="function"&&"__radixId"in r.type&&r.type.__radixId===VP}function EK(r,e){const t={...e};for(const n in e){const i=r[n],o=e[n];/^on[A-Z]/.test(n)?i&&o?t[n]=(...a)=>{const l=o(...a);return i(...a),l}:i&&(t[n]=i):n==="style"?t[n]={...i,...o}:n==="className"&&(t[n]=[i,o].filter(Boolean).join(" "))}return{...r,...t}}function wK(r){var n,i;let e=(n=Object.getOwnPropertyDescriptor(r.props,"ref"))==null?void 0:n.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?r.ref:(e=(i=Object.getOwnPropertyDescriptor(r,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?r.props.ref:r.props.ref||r.ref)}var TK=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Je=TK.reduce((r,e)=>{const t=Aa(`Primitive.${e}`),n=E.forwardRef((i,o)=>{const{asChild:s,...a}=i,l=s?t:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),y.jsx(l,{...a,ref:o})});return n.displayName=`Primitive.${e}`,{...r,[e]:n}},{});function $P(r,e){r&&Av.flushSync(()=>r.dispatchEvent(e))}var RK=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),CK="VisuallyHidden",WP=E.forwardRef((r,e)=>y.jsx(Je.span,{...r,ref:e,style:{...RK,...r.style}}));WP.displayName=CK;var kK=WP;function IK(r,e){const t=E.createContext(e),n=o=>{const{children:s,...a}=o,l=E.useMemo(()=>a,Object.values(a));return y.jsx(t.Provider,{value:l,children:s})};n.displayName=r+"Provider";function i(o){const s=E.useContext(t);if(s)return s;if(e!==void 0)return e;throw new Error(`\`${o}\` must be used within \`${r}\``)}return[n,i]}function to(r,e=[]){let t=[];function n(o,s){const a=E.createContext(s),l=t.length;t=[...t,s];const c=d=>{var g;const{scope:f,children:p,...h}=d,m=((g=f==null?void 0:f[r])==null?void 0:g[l])||a,w=E.useMemo(()=>h,Object.values(h));return y.jsx(m.Provider,{value:w,children:p})};c.displayName=o+"Provider";function u(d,f){var m;const p=((m=f==null?void 0:f[r])==null?void 0:m[l])||a,h=E.useContext(p);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[c,u]}const i=()=>{const o=t.map(s=>E.createContext(s));return function(a){const l=(a==null?void 0:a[r])||o;return E.useMemo(()=>({[`__scope${r}`]:{...a,[r]:l}}),[a,l])}};return i.scopeName=r,[n,xK(i,...e)]}function xK(...r){const e=r[0];if(r.length===1)return e;const t=()=>{const n=r.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const s=n.reduce((a,{useScope:l,scopeName:c})=>{const d=l(o)[`__scope${c}`];return{...a,...d}},{});return E.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return t.scopeName=e.scopeName,t}function qP(r){const e=r+"CollectionProvider",[t,n]=to(e),[i,o]=t(e,{collectionRef:{current:null},itemMap:new Map}),s=m=>{const{scope:w,children:g}=m,b=pe.useRef(null),R=pe.useRef(new Map).current;return y.jsx(i,{scope:w,itemMap:R,collectionRef:b,children:g})};s.displayName=e;const a=r+"CollectionSlot",l=Aa(a),c=pe.forwardRef((m,w)=>{const{scope:g,children:b}=m,R=o(a,g),k=_t(w,R.collectionRef);return y.jsx(l,{ref:k,children:b})});c.displayName=a;const u=r+"CollectionItemSlot",d="data-radix-collection-item",f=Aa(u),p=pe.forwardRef((m,w)=>{const{scope:g,children:b,...R}=m,k=pe.useRef(null),O=_t(w,k),T=o(u,g);return pe.useEffect(()=>(T.itemMap.set(k,{ref:k,...R}),()=>void T.itemMap.delete(k))),y.jsx(f,{[d]:"",ref:O,children:b})});p.displayName=u;function h(m){const w=o(r+"CollectionConsumer",m);return pe.useCallback(()=>{const b=w.collectionRef.current;if(!b)return[];const R=Array.from(b.querySelectorAll(`[${d}]`));return Array.from(w.itemMap.values()).sort((T,x)=>R.indexOf(T.ref.current)-R.indexOf(x.ref.current))},[w.collectionRef,w.itemMap])}return[{Provider:s,Slot:c,ItemSlot:p},h,n]}function Me(r,e,{checkForDefaultPrevented:t=!0}={}){return function(i){if(r==null||r(i),t===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}var Zn=globalThis!=null&&globalThis.document?E.useLayoutEffect:()=>{},OK=gv[" useInsertionEffect ".trim().toString()]||Zn;function Uv({prop:r,defaultProp:e,onChange:t=()=>{},caller:n}){const[i,o,s]=PK({defaultProp:e,onChange:t}),a=r!==void 0,l=a?r:i;{const u=E.useRef(r!==void 0);E.useEffect(()=>{const d=u.current;d!==a&&console.warn(`${n} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,n])}const c=E.useCallback(u=>{var d;if(a){const f=MK(u)?u(r):u;f!==r&&((d=s.current)==null||d.call(s,f))}else o(u)},[a,r,o,s]);return[l,c]}function PK({defaultProp:r,onChange:e}){const[t,n]=E.useState(r),i=E.useRef(t),o=E.useRef(e);return OK(()=>{o.current=e},[e]),E.useEffect(()=>{var s;i.current!==t&&((s=o.current)==null||s.call(o,t),i.current=t)},[t,i]),[t,n,o]}function MK(r){return typeof r=="function"}function AK(r,e){return E.useReducer((t,n)=>e[t][n]??t,r)}var sn=r=>{const{present:e,children:t}=r,n=DK(e),i=typeof t=="function"?t({present:n.isPresent}):E.Children.only(t),o=_t(n.ref,NK(i));return typeof t=="function"||n.isPresent?E.cloneElement(i,{ref:o}):null};sn.displayName="Presence";function DK(r){const[e,t]=E.useState(),n=E.useRef(null),i=E.useRef(r),o=E.useRef("none"),s=r?"mounted":"unmounted",[a,l]=AK(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return E.useEffect(()=>{const c=Jf(n.current);o.current=a==="mounted"?c:"none"},[a]),Zn(()=>{const c=n.current,u=i.current;if(u!==r){const f=o.current,p=Jf(c);r?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),i.current=r}},[r,l]),Zn(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,d=p=>{const m=Jf(n.current).includes(CSS.escape(p.animationName));if(p.target===e&&m&&(l("ANIMATION_END"),!i.current)){const w=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=w)})}},f=p=>{p.target===e&&(o.current=Jf(n.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:E.useCallback(c=>{n.current=c?getComputedStyle(c):null,t(c)},[])}}function Jf(r){return(r==null?void 0:r.animationName)||"none"}function NK(r){var n,i;let e=(n=Object.getOwnPropertyDescriptor(r.props,"ref"))==null?void 0:n.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?r.ref:(e=(i=Object.getOwnPropertyDescriptor(r,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?r.props.ref:r.props.ref||r.ref)}var LK=gv[" useId ".trim().toString()]||(()=>{}),UK=0;function jn(r){const[e,t]=E.useState(LK());return Zn(()=>{t(n=>n??String(UK++))},[r]),r||(e?`radix-${e}`:"")}var jK=E.createContext(void 0);function CE(r){const e=E.useContext(jK);return r||e||"ltr"}function Pr(r){const e=E.useRef(r);return E.useEffect(()=>{e.current=r}),E.useMemo(()=>(...t)=>{var n;return(n=e.current)==null?void 0:n.call(e,...t)},[])}function FK(r,e=globalThis==null?void 0:globalThis.document){const t=Pr(r);E.useEffect(()=>{const n=i=>{i.key==="Escape"&&t(i)};return e.addEventListener("keydown",n,{capture:!0}),()=>e.removeEventListener("keydown",n,{capture:!0})},[t,e])}var BK="DismissableLayer",AS="dismissableLayer.update",KK="dismissableLayer.pointerDownOutside",VK="dismissableLayer.focusOutside",JT,GP=E.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),sf=E.forwardRef((r,e)=>{const{disableOutsidePointerEvents:t=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:s,onDismiss:a,...l}=r,c=E.useContext(GP),[u,d]=E.useState(null),f=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=E.useState({}),h=_t(e,x=>d(x)),m=Array.from(c.layers),[w]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=m.indexOf(w),b=u?m.indexOf(u):-1,R=c.layersWithOutsidePointerEventsDisabled.size>0,k=b>=g,O=qK(x=>{const C=x.target,N=[...c.branches].some(F=>F.contains(C));!k||N||(i==null||i(x),s==null||s(x),x.defaultPrevented||a==null||a())},f),T=GK(x=>{const C=x.target;[...c.branches].some(F=>F.contains(C))||(o==null||o(x),s==null||s(x),x.defaultPrevented||a==null||a())},f);return FK(x=>{b===c.layers.size-1&&(n==null||n(x),!x.defaultPrevented&&a&&(x.preventDefault(),a()))},f),E.useEffect(()=>{if(u)return t&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(JT=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),XT(),()=>{t&&c.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=JT)}},[u,f,t,c]),E.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),XT())},[u,c]),E.useEffect(()=>{const x=()=>p({});return document.addEventListener(AS,x),()=>document.removeEventListener(AS,x)},[]),y.jsx(Je.div,{...l,ref:h,style:{pointerEvents:R?k?"auto":"none":void 0,...r.style},onFocusCapture:Me(r.onFocusCapture,T.onFocusCapture),onBlurCapture:Me(r.onBlurCapture,T.onBlurCapture),onPointerDownCapture:Me(r.onPointerDownCapture,O.onPointerDownCapture)})});sf.displayName=BK;var $K="DismissableLayerBranch",WK=E.forwardRef((r,e)=>{const t=E.useContext(GP),n=E.useRef(null),i=_t(e,n);return E.useEffect(()=>{const o=n.current;if(o)return t.branches.add(o),()=>{t.branches.delete(o)}},[t.branches]),y.jsx(Je.div,{...r,ref:i})});WK.displayName=$K;function qK(r,e=globalThis==null?void 0:globalThis.document){const t=Pr(r),n=E.useRef(!1),i=E.useRef(()=>{});return E.useEffect(()=>{const o=a=>{if(a.target&&!n.current){let l=function(){HP(KK,t,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",i.current),i.current=l,e.addEventListener("click",i.current,{once:!0})):l()}else e.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{e.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(s),e.removeEventListener("pointerdown",o),e.removeEventListener("click",i.current)}},[e,t]),{onPointerDownCapture:()=>n.current=!0}}function GK(r,e=globalThis==null?void 0:globalThis.document){const t=Pr(r),n=E.useRef(!1);return E.useEffect(()=>{const i=o=>{o.target&&!n.current&&HP(VK,t,{originalEvent:o},{discrete:!1})};return e.addEventListener("focusin",i),()=>e.removeEventListener("focusin",i)},[e,t]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function XT(){const r=new CustomEvent(AS);document.dispatchEvent(r)}function HP(r,e,t,{discrete:n}){const i=t.originalEvent.target,o=new CustomEvent(r,{bubbles:!1,cancelable:!0,detail:t});e&&i.addEventListener(r,e,{once:!0}),n?$P(i,o):i.dispatchEvent(o)}var _g="focusScope.autoFocusOnMount",Eg="focusScope.autoFocusOnUnmount",QT={bubbles:!1,cancelable:!0},HK="FocusScope",jv=E.forwardRef((r,e)=>{const{loop:t=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...s}=r,[a,l]=E.useState(null),c=Pr(i),u=Pr(o),d=E.useRef(null),f=_t(e,m=>l(m)),p=E.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;E.useEffect(()=>{if(n){let m=function(R){if(p.paused||!a)return;const k=R.target;a.contains(k)?d.current=k:Qo(d.current,{select:!0})},w=function(R){if(p.paused||!a)return;const k=R.relatedTarget;k!==null&&(a.contains(k)||Qo(d.current,{select:!0}))},g=function(R){if(document.activeElement===document.body)for(const O of R)O.removedNodes.length>0&&Qo(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",w);const b=new MutationObserver(g);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",w),b.disconnect()}}},[n,a,p.paused]),E.useEffect(()=>{if(a){eR.add(p);const m=document.activeElement;if(!a.contains(m)){const g=new CustomEvent(_g,QT);a.addEventListener(_g,c),a.dispatchEvent(g),g.defaultPrevented||(zK(ZK(zP(a)),{select:!0}),document.activeElement===m&&Qo(a))}return()=>{a.removeEventListener(_g,c),setTimeout(()=>{const g=new CustomEvent(Eg,QT);a.addEventListener(Eg,u),a.dispatchEvent(g),g.defaultPrevented||Qo(m??document.body,{select:!0}),a.removeEventListener(Eg,u),eR.remove(p)},0)}}},[a,c,u,p]);const h=E.useCallback(m=>{if(!t&&!n||p.paused)return;const w=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,g=document.activeElement;if(w&&g){const b=m.currentTarget,[R,k]=YK(b);R&&k?!m.shiftKey&&g===k?(m.preventDefault(),t&&Qo(R,{select:!0})):m.shiftKey&&g===R&&(m.preventDefault(),t&&Qo(k,{select:!0})):g===b&&m.preventDefault()}},[t,n,p.paused]);return y.jsx(Je.div,{tabIndex:-1,...s,ref:f,onKeyDown:h})});jv.displayName=HK;function zK(r,{select:e=!1}={}){const t=document.activeElement;for(const n of r)if(Qo(n,{select:e}),document.activeElement!==t)return}function YK(r){const e=zP(r),t=ZT(e,r),n=ZT(e.reverse(),r);return[t,n]}function zP(r){const e=[],t=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const i=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||i?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)e.push(t.currentNode);return e}function ZT(r,e){for(const t of r)if(!JK(t,{upTo:e}))return t}function JK(r,{upTo:e}){if(getComputedStyle(r).visibility==="hidden")return!0;for(;r;){if(e!==void 0&&r===e)return!1;if(getComputedStyle(r).display==="none")return!0;r=r.parentElement}return!1}function XK(r){return r instanceof HTMLInputElement&&"select"in r}function Qo(r,{select:e=!1}={}){if(r&&r.focus){const t=document.activeElement;r.focus({preventScroll:!0}),r!==t&&XK(r)&&e&&r.select()}}var eR=QK();function QK(){let r=[];return{add(e){const t=r[0];e!==t&&(t==null||t.pause()),r=tR(r,e),r.unshift(e)},remove(e){var t;r=tR(r,e),(t=r[0])==null||t.resume()}}}function tR(r,e){const t=[...r],n=t.indexOf(e);return n!==-1&&t.splice(n,1),t}function ZK(r){return r.filter(e=>e.tagName!=="A")}var e5="Portal",Fv=E.forwardRef((r,e)=>{var a;const{container:t,...n}=r,[i,o]=E.useState(!1);Zn(()=>o(!0),[]);const s=t||i&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return s?SP.createPortal(y.jsx(Je.div,{...n,ref:e}),s):null});Fv.displayName=e5;var wg=0;function kE(){E.useEffect(()=>{const r=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",r[0]??rR()),document.body.insertAdjacentElement("beforeend",r[1]??rR()),wg++,()=>{wg===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),wg--}},[])}function rR(){const r=document.createElement("span");return r.setAttribute("data-radix-focus-guard",""),r.tabIndex=0,r.style.outline="none",r.style.opacity="0",r.style.position="fixed",r.style.pointerEvents="none",r}var qi=function(){return qi=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},qi.apply(this,arguments)};function YP(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t}function t5(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))}var Uh="right-scroll-bar-position",jh="width-before-scroll-bar",r5="with-scroll-bars-hidden",n5="--removed-body-scroll-bar-size";function Tg(r,e){return typeof r=="function"?r(e):r&&(r.current=e),r}function i5(r,e){var t=E.useState(function(){return{value:r,callback:e,facade:{get current(){return t.value},set current(n){var i=t.value;i!==n&&(t.value=n,t.callback(n,i))}}}})[0];return t.callback=e,t.facade}var o5=typeof window<"u"?E.useLayoutEffect:E.useEffect,nR=new WeakMap;function s5(r,e){var t=i5(null,function(n){return r.forEach(function(i){return Tg(i,n)})});return o5(function(){var n=nR.get(t);if(n){var i=new Set(n),o=new Set(r),s=t.current;i.forEach(function(a){o.has(a)||Tg(a,null)}),o.forEach(function(a){i.has(a)||Tg(a,s)})}nR.set(t,r)},[r]),t}function a5(r){return r}function l5(r,e){e===void 0&&(e=a5);var t=[],n=!1,i={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return t.length?t[t.length-1]:r},useMedium:function(o){var s=e(o,n);return t.push(s),function(){t=t.filter(function(a){return a!==s})}},assignSyncMedium:function(o){for(n=!0;t.length;){var s=t;t=[],s.forEach(o)}t={push:function(a){return o(a)},filter:function(){return t}}},assignMedium:function(o){n=!0;var s=[];if(t.length){var a=t;t=[],a.forEach(o),s=t}var l=function(){var u=s;s=[],u.forEach(o)},c=function(){return Promise.resolve().then(l)};c(),t={push:function(u){s.push(u),c()},filter:function(u){return s=s.filter(u),t}}}};return i}function c5(r){r===void 0&&(r={});var e=l5(null);return e.options=qi({async:!0,ssr:!1},r),e}var JP=function(r){var e=r.sideCar,t=YP(r,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=e.read();if(!n)throw new Error("Sidecar medium not found");return E.createElement(n,qi({},t))};JP.isSideCarExport=!0;function u5(r,e){return r.useMedium(e),JP}var XP=c5(),Rg=function(){},Bv=E.forwardRef(function(r,e){var t=E.useRef(null),n=E.useState({onScrollCapture:Rg,onWheelCapture:Rg,onTouchMoveCapture:Rg}),i=n[0],o=n[1],s=r.forwardProps,a=r.children,l=r.className,c=r.removeScrollBar,u=r.enabled,d=r.shards,f=r.sideCar,p=r.noRelative,h=r.noIsolation,m=r.inert,w=r.allowPinchZoom,g=r.as,b=g===void 0?"div":g,R=r.gapMode,k=YP(r,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),O=f,T=s5([t,e]),x=qi(qi({},k),i);return E.createElement(E.Fragment,null,u&&E.createElement(O,{sideCar:XP,removeScrollBar:c,shards:d,noRelative:p,noIsolation:h,inert:m,setCallbacks:o,allowPinchZoom:!!w,lockRef:t,gapMode:R}),s?E.cloneElement(E.Children.only(a),qi(qi({},x),{ref:T})):E.createElement(b,qi({},x,{className:l,ref:T}),a))});Bv.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Bv.classNames={fullWidth:jh,zeroRight:Uh};var d5=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function f5(){if(!document)return null;var r=document.createElement("style");r.type="text/css";var e=d5();return e&&r.setAttribute("nonce",e),r}function h5(r,e){r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}function p5(r){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(r)}var v5=function(){var r=0,e=null;return{add:function(t){r==0&&(e=f5())&&(h5(e,t),p5(e)),r++},remove:function(){r--,!r&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},m5=function(){var r=v5();return function(e,t){E.useEffect(function(){return r.add(e),function(){r.remove()}},[e&&t])}},QP=function(){var r=m5(),e=function(t){var n=t.styles,i=t.dynamic;return r(n,i),null};return e},g5={left:0,top:0,right:0,gap:0},Cg=function(r){return parseInt(r||"",10)||0},y5=function(r){var e=window.getComputedStyle(document.body),t=e[r==="padding"?"paddingLeft":"marginLeft"],n=e[r==="padding"?"paddingTop":"marginTop"],i=e[r==="padding"?"paddingRight":"marginRight"];return[Cg(t),Cg(n),Cg(i)]},S5=function(r){if(r===void 0&&(r="margin"),typeof window>"u")return g5;var e=y5(r),t=document.documentElement.clientWidth,n=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,n-t+e[2]-e[0])}},b5=QP(),ql="data-scroll-locked",_5=function(r,e,t,n){var i=r.left,o=r.top,s=r.right,a=r.gap;return t===void 0&&(t="margin"),`
218
+ .`.concat(r5,` {
219
+ overflow: hidden `).concat(n,`;
220
+ padding-right: `).concat(a,"px ").concat(n,`;
221
+ }
222
+ body[`).concat(ql,`] {
223
+ overflow: hidden `).concat(n,`;
224
+ overscroll-behavior: contain;
225
+ `).concat([e&&"position: relative ".concat(n,";"),t==="margin"&&`
226
+ padding-left: `.concat(i,`px;
227
+ padding-top: `).concat(o,`px;
228
+ padding-right: `).concat(s,`px;
229
+ margin-left:0;
230
+ margin-top:0;
231
+ margin-right: `).concat(a,"px ").concat(n,`;
232
+ `),t==="padding"&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),`
233
+ }
234
+
235
+ .`).concat(Uh,` {
236
+ right: `).concat(a,"px ").concat(n,`;
237
+ }
238
+
239
+ .`).concat(jh,` {
240
+ margin-right: `).concat(a,"px ").concat(n,`;
241
+ }
242
+
243
+ .`).concat(Uh," .").concat(Uh,` {
244
+ right: 0 `).concat(n,`;
245
+ }
246
+
247
+ .`).concat(jh," .").concat(jh,` {
248
+ margin-right: 0 `).concat(n,`;
249
+ }
250
+
251
+ body[`).concat(ql,`] {
252
+ `).concat(n5,": ").concat(a,`px;
253
+ }
254
+ `)},iR=function(){var r=parseInt(document.body.getAttribute(ql)||"0",10);return isFinite(r)?r:0},E5=function(){E.useEffect(function(){return document.body.setAttribute(ql,(iR()+1).toString()),function(){var r=iR()-1;r<=0?document.body.removeAttribute(ql):document.body.setAttribute(ql,r.toString())}},[])},w5=function(r){var e=r.noRelative,t=r.noImportant,n=r.gapMode,i=n===void 0?"margin":n;E5();var o=E.useMemo(function(){return S5(i)},[i]);return E.createElement(b5,{styles:_5(o,!e,i,t?"":"!important")})},DS=!1;if(typeof window<"u")try{var Xf=Object.defineProperty({},"passive",{get:function(){return DS=!0,!0}});window.addEventListener("test",Xf,Xf),window.removeEventListener("test",Xf,Xf)}catch{DS=!1}var tl=DS?{passive:!1}:!1,T5=function(r){return r.tagName==="TEXTAREA"},ZP=function(r,e){if(!(r instanceof Element))return!1;var t=window.getComputedStyle(r);return t[e]!=="hidden"&&!(t.overflowY===t.overflowX&&!T5(r)&&t[e]==="visible")},R5=function(r){return ZP(r,"overflowY")},C5=function(r){return ZP(r,"overflowX")},oR=function(r,e){var t=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=eM(r,n);if(i){var o=tM(r,n),s=o[1],a=o[2];if(s>a)return!0}n=n.parentNode}while(n&&n!==t.body);return!1},k5=function(r){var e=r.scrollTop,t=r.scrollHeight,n=r.clientHeight;return[e,t,n]},I5=function(r){var e=r.scrollLeft,t=r.scrollWidth,n=r.clientWidth;return[e,t,n]},eM=function(r,e){return r==="v"?R5(e):C5(e)},tM=function(r,e){return r==="v"?k5(e):I5(e)},x5=function(r,e){return r==="h"&&e==="rtl"?-1:1},O5=function(r,e,t,n,i){var o=x5(r,window.getComputedStyle(e).direction),s=o*n,a=t.target,l=e.contains(a),c=!1,u=s>0,d=0,f=0;do{if(!a)break;var p=tM(r,a),h=p[0],m=p[1],w=p[2],g=m-w-o*h;(h||g)&&eM(r,a)&&(d+=g,f+=h);var b=a.parentNode;a=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!l&&a!==document.body||l&&(e.contains(a)||e===a));return(u&&Math.abs(d)<1||!u&&Math.abs(f)<1)&&(c=!0),c},Qf=function(r){return"changedTouches"in r?[r.changedTouches[0].clientX,r.changedTouches[0].clientY]:[0,0]},sR=function(r){return[r.deltaX,r.deltaY]},aR=function(r){return r&&"current"in r?r.current:r},P5=function(r,e){return r[0]===e[0]&&r[1]===e[1]},M5=function(r){return`
255
+ .block-interactivity-`.concat(r,` {pointer-events: none;}
256
+ .allow-interactivity-`).concat(r,` {pointer-events: all;}
257
+ `)},A5=0,rl=[];function D5(r){var e=E.useRef([]),t=E.useRef([0,0]),n=E.useRef(),i=E.useState(A5++)[0],o=E.useState(QP)[0],s=E.useRef(r);E.useEffect(function(){s.current=r},[r]),E.useEffect(function(){if(r.inert){document.body.classList.add("block-interactivity-".concat(i));var m=t5([r.lockRef.current],(r.shards||[]).map(aR),!0).filter(Boolean);return m.forEach(function(w){return w.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),m.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(i))})}}},[r.inert,r.lockRef.current,r.shards]);var a=E.useCallback(function(m,w){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!s.current.allowPinchZoom;var g=Qf(m),b=t.current,R="deltaX"in m?m.deltaX:b[0]-g[0],k="deltaY"in m?m.deltaY:b[1]-g[1],O,T=m.target,x=Math.abs(R)>Math.abs(k)?"h":"v";if("touches"in m&&x==="h"&&T.type==="range")return!1;var C=window.getSelection(),N=C&&C.anchorNode,F=N?N===T||N.contains(T):!1;if(F)return!1;var H=oR(x,T);if(!H)return!0;if(H?O=x:(O=x==="v"?"h":"v",H=oR(x,T)),!H)return!1;if(!n.current&&"changedTouches"in m&&(R||k)&&(n.current=O),!O)return!0;var ie=n.current||O;return O5(ie,w,m,ie==="h"?R:k)},[]),l=E.useCallback(function(m){var w=m;if(!(!rl.length||rl[rl.length-1]!==o)){var g="deltaY"in w?sR(w):Qf(w),b=e.current.filter(function(O){return O.name===w.type&&(O.target===w.target||w.target===O.shadowParent)&&P5(O.delta,g)})[0];if(b&&b.should){w.cancelable&&w.preventDefault();return}if(!b){var R=(s.current.shards||[]).map(aR).filter(Boolean).filter(function(O){return O.contains(w.target)}),k=R.length>0?a(w,R[0]):!s.current.noIsolation;k&&w.cancelable&&w.preventDefault()}}},[]),c=E.useCallback(function(m,w,g,b){var R={name:m,delta:w,target:g,should:b,shadowParent:N5(g)};e.current.push(R),setTimeout(function(){e.current=e.current.filter(function(k){return k!==R})},1)},[]),u=E.useCallback(function(m){t.current=Qf(m),n.current=void 0},[]),d=E.useCallback(function(m){c(m.type,sR(m),m.target,a(m,r.lockRef.current))},[]),f=E.useCallback(function(m){c(m.type,Qf(m),m.target,a(m,r.lockRef.current))},[]);E.useEffect(function(){return rl.push(o),r.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,tl),document.addEventListener("touchmove",l,tl),document.addEventListener("touchstart",u,tl),function(){rl=rl.filter(function(m){return m!==o}),document.removeEventListener("wheel",l,tl),document.removeEventListener("touchmove",l,tl),document.removeEventListener("touchstart",u,tl)}},[]);var p=r.removeScrollBar,h=r.inert;return E.createElement(E.Fragment,null,h?E.createElement(o,{styles:M5(i)}):null,p?E.createElement(w5,{noRelative:r.noRelative,gapMode:r.gapMode}):null)}function N5(r){for(var e=null;r!==null;)r instanceof ShadowRoot&&(e=r.host,r=r.host),r=r.parentNode;return e}const L5=u5(XP,D5);var Kv=E.forwardRef(function(r,e){return E.createElement(Bv,qi({},r,{ref:e,sideCar:L5}))});Kv.classNames=Bv.classNames;var U5=function(r){if(typeof document>"u")return null;var e=Array.isArray(r)?r[0]:r;return e.ownerDocument.body},nl=new WeakMap,Zf=new WeakMap,eh={},kg=0,rM=function(r){return r&&(r.host||rM(r.parentNode))},j5=function(r,e){return e.map(function(t){if(r.contains(t))return t;var n=rM(t);return n&&r.contains(n)?n:(console.error("aria-hidden",t,"in not contained inside",r,". Doing nothing"),null)}).filter(function(t){return!!t})},F5=function(r,e,t,n){var i=j5(e,Array.isArray(r)?r:[r]);eh[t]||(eh[t]=new WeakMap);var o=eh[t],s=[],a=new Set,l=new Set(i),c=function(d){!d||a.has(d)||(a.add(d),c(d.parentNode))};i.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(a.has(f))u(f);else try{var p=f.getAttribute(n),h=p!==null&&p!=="false",m=(nl.get(f)||0)+1,w=(o.get(f)||0)+1;nl.set(f,m),o.set(f,w),s.push(f),m===1&&h&&Zf.set(f,!0),w===1&&f.setAttribute(t,"true"),h||f.setAttribute(n,"true")}catch(g){console.error("aria-hidden: cannot operate on ",f,g)}})};return u(e),a.clear(),kg++,function(){s.forEach(function(d){var f=nl.get(d)-1,p=o.get(d)-1;nl.set(d,f),o.set(d,p),f||(Zf.has(d)||d.removeAttribute(n),Zf.delete(d)),p||d.removeAttribute(t)}),kg--,kg||(nl=new WeakMap,nl=new WeakMap,Zf=new WeakMap,eh={})}},IE=function(r,e,t){t===void 0&&(t="data-aria-hidden");var n=Array.from(Array.isArray(r)?r:[r]),i=U5(r);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live], script"))),F5(n,i,t,"aria-hidden")):function(){return null}},Vv="Dialog",[nM]=to(Vv),[B5,Ii]=nM(Vv),iM=r=>{const{__scopeDialog:e,children:t,open:n,defaultOpen:i,onOpenChange:o,modal:s=!0}=r,a=E.useRef(null),l=E.useRef(null),[c,u]=Uv({prop:n,defaultProp:i??!1,onChange:o,caller:Vv});return y.jsx(B5,{scope:e,triggerRef:a,contentRef:l,contentId:jn(),titleId:jn(),descriptionId:jn(),open:c,onOpenChange:u,onOpenToggle:E.useCallback(()=>u(d=>!d),[u]),modal:s,children:t})};iM.displayName=Vv;var oM="DialogTrigger",K5=E.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(oM,t),o=_t(e,i.triggerRef);return y.jsx(Je.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":PE(i.open),...n,ref:o,onClick:Me(r.onClick,i.onOpenToggle)})});K5.displayName=oM;var xE="DialogPortal",[V5,sM]=nM(xE,{forceMount:void 0}),aM=r=>{const{__scopeDialog:e,forceMount:t,children:n,container:i}=r,o=Ii(xE,e);return y.jsx(V5,{scope:e,forceMount:t,children:E.Children.map(n,s=>y.jsx(sn,{present:t||o.open,children:y.jsx(Fv,{asChild:!0,container:i,children:s})}))})};aM.displayName=xE;var Ap="DialogOverlay",lM=E.forwardRef((r,e)=>{const t=sM(Ap,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,o=Ii(Ap,r.__scopeDialog);return o.modal?y.jsx(sn,{present:n||o.open,children:y.jsx(W5,{...i,ref:e})}):null});lM.displayName=Ap;var $5=Aa("DialogOverlay.RemoveScroll"),W5=E.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(Ap,t);return y.jsx(Kv,{as:$5,allowPinchZoom:!0,shards:[i.contentRef],children:y.jsx(Je.div,{"data-state":PE(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),Da="DialogContent",cM=E.forwardRef((r,e)=>{const t=sM(Da,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,o=Ii(Da,r.__scopeDialog);return y.jsx(sn,{present:n||o.open,children:o.modal?y.jsx(q5,{...i,ref:e}):y.jsx(G5,{...i,ref:e})})});cM.displayName=Da;var q5=E.forwardRef((r,e)=>{const t=Ii(Da,r.__scopeDialog),n=E.useRef(null),i=_t(e,t.contentRef,n);return E.useEffect(()=>{const o=n.current;if(o)return IE(o)},[]),y.jsx(uM,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Me(r.onCloseAutoFocus,o=>{var s;o.preventDefault(),(s=t.triggerRef.current)==null||s.focus()}),onPointerDownOutside:Me(r.onPointerDownOutside,o=>{const s=o.detail.originalEvent,a=s.button===0&&s.ctrlKey===!0;(s.button===2||a)&&o.preventDefault()}),onFocusOutside:Me(r.onFocusOutside,o=>o.preventDefault())})}),G5=E.forwardRef((r,e)=>{const t=Ii(Da,r.__scopeDialog),n=E.useRef(!1),i=E.useRef(!1);return y.jsx(uM,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var s,a;(s=r.onCloseAutoFocus)==null||s.call(r,o),o.defaultPrevented||(n.current||(a=t.triggerRef.current)==null||a.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var l,c;(l=r.onInteractOutside)==null||l.call(r,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;((c=t.triggerRef.current)==null?void 0:c.contains(s))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),uM=E.forwardRef((r,e)=>{const{__scopeDialog:t,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,...s}=r,a=Ii(Da,t),l=E.useRef(null),c=_t(e,l);return kE(),y.jsxs(y.Fragment,{children:[y.jsx(jv,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:y.jsx(sf,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":PE(a.open),...s,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),y.jsxs(y.Fragment,{children:[y.jsx(H5,{titleId:a.titleId}),y.jsx(Y5,{contentRef:l,descriptionId:a.descriptionId})]})]})}),OE="DialogTitle",dM=E.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(OE,t);return y.jsx(Je.h2,{id:i.titleId,...n,ref:e})});dM.displayName=OE;var fM="DialogDescription",hM=E.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(fM,t);return y.jsx(Je.p,{id:i.descriptionId,...n,ref:e})});hM.displayName=fM;var pM="DialogClose",vM=E.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(pM,t);return y.jsx(Je.button,{type:"button",...n,ref:e,onClick:Me(r.onClick,()=>i.onOpenChange(!1))})});vM.displayName=pM;function PE(r){return r?"open":"closed"}var mM="DialogTitleWarning",[Ete,gM]=IK(mM,{contentName:Da,titleName:OE,docsSlug:"dialog"}),H5=({titleId:r})=>{const e=gM(mM),t=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users.
258
+
259
+ If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
260
+
261
+ For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return E.useEffect(()=>{r&&(document.getElementById(r)||console.error(t))},[t,r]),null},z5="DialogDescriptionWarning",Y5=({contentRef:r,descriptionId:e})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${gM(z5).contentName}}.`;return E.useEffect(()=>{var o;const i=(o=r.current)==null?void 0:o.getAttribute("aria-describedby");e&&i&&(document.getElementById(e)||console.warn(n))},[n,r,e]),null},ME=iM,AE=aM,DE=lM,NE=cM,yM=dM,SM=hM,LE=vM,bM={exports:{}},_M={};/**
262
+ * @license React
263
+ * use-sync-external-store-shim.production.js
264
+ *
265
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
266
+ *
267
+ * This source code is licensed under the MIT license found in the
268
+ * LICENSE file in the root directory of this source tree.
269
+ */var uc=E;function J5(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var X5=typeof Object.is=="function"?Object.is:J5,Q5=uc.useState,Z5=uc.useEffect,e3=uc.useLayoutEffect,t3=uc.useDebugValue;function r3(r,e){var t=e(),n=Q5({inst:{value:t,getSnapshot:e}}),i=n[0].inst,o=n[1];return e3(function(){i.value=t,i.getSnapshot=e,Ig(i)&&o({inst:i})},[r,t,e]),Z5(function(){return Ig(i)&&o({inst:i}),r(function(){Ig(i)&&o({inst:i})})},[r]),t3(t),t}function Ig(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!X5(r,t)}catch{return!0}}function n3(r,e){return e()}var i3=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n3:r3;_M.useSyncExternalStore=uc.useSyncExternalStore!==void 0?uc.useSyncExternalStore:i3;bM.exports=_M;var o3=bM.exports;function s3(){return o3.useSyncExternalStore(a3,()=>!0,()=>!1)}function a3(){return()=>{}}var UE="Avatar",[l3]=to(UE),[c3,EM]=l3(UE),wM=E.forwardRef((r,e)=>{const{__scopeAvatar:t,...n}=r,[i,o]=E.useState("idle");return y.jsx(c3,{scope:t,imageLoadingStatus:i,onImageLoadingStatusChange:o,children:y.jsx(Je.span,{...n,ref:e})})});wM.displayName=UE;var TM="AvatarImage",u3=E.forwardRef((r,e)=>{const{__scopeAvatar:t,src:n,onLoadingStatusChange:i=()=>{},...o}=r,s=EM(TM,t),a=d3(n,o),l=Pr(c=>{i(c),s.onImageLoadingStatusChange(c)});return Zn(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?y.jsx(Je.img,{...o,ref:e,src:n}):null});u3.displayName=TM;var RM="AvatarFallback",CM=E.forwardRef((r,e)=>{const{__scopeAvatar:t,delayMs:n,...i}=r,o=EM(RM,t),[s,a]=E.useState(n===void 0);return E.useEffect(()=>{if(n!==void 0){const l=window.setTimeout(()=>a(!0),n);return()=>window.clearTimeout(l)}},[n]),s&&o.imageLoadingStatus!=="loaded"?y.jsx(Je.span,{...i,ref:e}):null});CM.displayName=RM;function lR(r,e){return r?e?(r.src!==e&&(r.src=e),r.complete&&r.naturalWidth>0?"loaded":"loading"):"error":"idle"}function d3(r,{referrerPolicy:e,crossOrigin:t}){const n=s3(),i=E.useRef(null),o=n?(i.current||(i.current=new window.Image),i.current):null,[s,a]=E.useState(()=>lR(o,r));return Zn(()=>{a(lR(o,r))},[o,r]),Zn(()=>{const l=d=>()=>{a(d)};if(!o)return;const c=l("loaded"),u=l("error");return o.addEventListener("load",c),o.addEventListener("error",u),e&&(o.referrerPolicy=e),typeof t=="string"&&(o.crossOrigin=t),()=>{o.removeEventListener("load",c),o.removeEventListener("error",u)}},[o,t,e]),s}var f3=wM,h3=CM;function p3(r){const[e,t]=E.useState(void 0);return Zn(()=>{if(r){t({width:r.offsetWidth,height:r.offsetHeight});const n=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let s,a;if("borderBoxSize"in o){const l=o.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=r.offsetWidth,a=r.offsetHeight;t({width:s,height:a})});return n.observe(r,{box:"border-box"}),()=>n.unobserve(r)}else t(void 0)},[r]),e}const v3=["top","right","bottom","left"],Ps=Math.min,Nn=Math.max,Dp=Math.round,th=Math.floor,Ji=r=>({x:r,y:r}),m3={left:"right",right:"left",bottom:"top",top:"bottom"};function NS(r,e,t){return Nn(r,Ps(e,t))}function Do(r,e){return typeof r=="function"?r(e):r}function No(r){return r.split("-")[0]}function Mc(r){return r.split("-")[1]}function jE(r){return r==="x"?"y":"x"}function FE(r){return r==="y"?"height":"width"}function Hi(r){const e=r[0];return e==="t"||e==="b"?"y":"x"}function BE(r){return jE(Hi(r))}function g3(r,e,t){t===void 0&&(t=!1);const n=Mc(r),i=BE(r),o=FE(i);let s=i==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(s=Np(s)),[s,Np(s)]}function y3(r){const e=Np(r);return[LS(r),e,LS(e)]}function LS(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}const cR=["left","right"],uR=["right","left"],S3=["top","bottom"],b3=["bottom","top"];function _3(r,e,t){switch(r){case"top":case"bottom":return t?e?uR:cR:e?cR:uR;case"left":case"right":return e?S3:b3;default:return[]}}function E3(r,e,t,n){const i=Mc(r);let o=_3(No(r),t==="start",n);return i&&(o=o.map(s=>s+"-"+i),e&&(o=o.concat(o.map(LS)))),o}function Np(r){const e=No(r);return m3[e]+r.slice(e.length)}function w3(r){return{top:0,right:0,bottom:0,left:0,...r}}function kM(r){return typeof r!="number"?w3(r):{top:r,right:r,bottom:r,left:r}}function Lp(r){const{x:e,y:t,width:n,height:i}=r;return{width:n,height:i,top:t,left:e,right:e+n,bottom:t+i,x:e,y:t}}function dR(r,e,t){let{reference:n,floating:i}=r;const o=Hi(e),s=BE(e),a=FE(s),l=No(e),c=o==="y",u=n.x+n.width/2-i.width/2,d=n.y+n.height/2-i.height/2,f=n[a]/2-i[a]/2;let p;switch(l){case"top":p={x:u,y:n.y-i.height};break;case"bottom":p={x:u,y:n.y+n.height};break;case"right":p={x:n.x+n.width,y:d};break;case"left":p={x:n.x-i.width,y:d};break;default:p={x:n.x,y:n.y}}switch(Mc(e)){case"start":p[s]-=f*(t&&c?-1:1);break;case"end":p[s]+=f*(t&&c?-1:1);break}return p}async function T3(r,e){var t;e===void 0&&(e={});const{x:n,y:i,platform:o,rects:s,elements:a,strategy:l}=r,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=Do(e,r),h=kM(p),w=a[f?d==="floating"?"reference":"floating":d],g=Lp(await o.getClippingRect({element:(t=await(o.isElement==null?void 0:o.isElement(w)))==null||t?w:w.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),b=d==="floating"?{x:n,y:i,width:s.floating.width,height:s.floating.height}:s.reference,R=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),k=await(o.isElement==null?void 0:o.isElement(R))?await(o.getScale==null?void 0:o.getScale(R))||{x:1,y:1}:{x:1,y:1},O=Lp(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:R,strategy:l}):b);return{top:(g.top-O.top+h.top)/k.y,bottom:(O.bottom-g.bottom+h.bottom)/k.y,left:(g.left-O.left+h.left)/k.x,right:(O.right-g.right+h.right)/k.x}}const R3=50,C3=async(r,e,t)=>{const{placement:n="bottom",strategy:i="absolute",middleware:o=[],platform:s}=t,a=s.detectOverflow?s:{...s,detectOverflow:T3},l=await(s.isRTL==null?void 0:s.isRTL(e));let c=await s.getElementRects({reference:r,floating:e,strategy:i}),{x:u,y:d}=dR(c,n,l),f=n,p=0;const h={};for(let m=0;m<o.length;m++){const w=o[m];if(!w)continue;const{name:g,fn:b}=w,{x:R,y:k,data:O,reset:T}=await b({x:u,y:d,initialPlacement:n,placement:f,strategy:i,middlewareData:h,rects:c,platform:a,elements:{reference:r,floating:e}});u=R??u,d=k??d,h[g]={...h[g],...O},T&&p<R3&&(p++,typeof T=="object"&&(T.placement&&(f=T.placement),T.rects&&(c=T.rects===!0?await s.getElementRects({reference:r,floating:e,strategy:i}):T.rects),{x:u,y:d}=dR(c,f,l)),m=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:h}},k3=r=>({name:"arrow",options:r,async fn(e){const{x:t,y:n,placement:i,rects:o,platform:s,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=Do(r,e)||{};if(c==null)return{};const d=kM(u),f={x:t,y:n},p=BE(i),h=FE(p),m=await s.getDimensions(c),w=p==="y",g=w?"top":"left",b=w?"bottom":"right",R=w?"clientHeight":"clientWidth",k=o.reference[h]+o.reference[p]-f[p]-o.floating[h],O=f[p]-o.reference[p],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(c));let x=T?T[R]:0;(!x||!await(s.isElement==null?void 0:s.isElement(T)))&&(x=a.floating[R]||o.floating[h]);const C=k/2-O/2,N=x/2-m[h]/2-1,F=Ps(d[g],N),H=Ps(d[b],N),ie=F,$=x-m[h]-H,X=x/2-m[h]/2+C,oe=NS(ie,X,$),re=!l.arrow&&Mc(i)!=null&&X!==oe&&o.reference[h]/2-(X<ie?F:H)-m[h]/2<0,ae=re?X<ie?X-ie:X-$:0;return{[p]:f[p]+ae,data:{[p]:oe,centerOffset:X-oe-ae,...re&&{alignmentOffset:ae}},reset:re}}}),I3=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;const{placement:i,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:m=!0,...w}=Do(r,e);if((t=o.arrow)!=null&&t.alignmentOffset)return{};const g=No(i),b=Hi(a),R=No(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),O=f||(R||!m?[Np(a)]:y3(a)),T=h!=="none";!f&&T&&O.push(...E3(a,m,h,k));const x=[a,...O],C=await l.detectOverflow(e,w),N=[];let F=((n=o.flip)==null?void 0:n.overflows)||[];if(u&&N.push(C[g]),d){const X=g3(i,s,k);N.push(C[X[0]],C[X[1]])}if(F=[...F,{placement:i,overflows:N}],!N.every(X=>X<=0)){var H,ie;const X=(((H=o.flip)==null?void 0:H.index)||0)+1,oe=x[X];if(oe&&(!(d==="alignment"?b!==Hi(oe):!1)||F.every(q=>Hi(q.placement)===b?q.overflows[0]>0:!0)))return{data:{index:X,overflows:F},reset:{placement:oe}};let re=(ie=F.filter(ae=>ae.overflows[0]<=0).sort((ae,q)=>ae.overflows[1]-q.overflows[1])[0])==null?void 0:ie.placement;if(!re)switch(p){case"bestFit":{var $;const ae=($=F.filter(q=>{if(T){const z=Hi(q.placement);return z===b||z==="y"}return!0}).map(q=>[q.placement,q.overflows.filter(z=>z>0).reduce((z,Q)=>z+Q,0)]).sort((q,z)=>q[1]-z[1])[0])==null?void 0:$[0];ae&&(re=ae);break}case"initialPlacement":re=a;break}if(i!==re)return{reset:{placement:re}}}return{}}}};function fR(r,e){return{top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function hR(r){return v3.some(e=>r[e]>=0)}const x3=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){const{rects:t,platform:n}=e,{strategy:i="referenceHidden",...o}=Do(r,e);switch(i){case"referenceHidden":{const s=await n.detectOverflow(e,{...o,elementContext:"reference"}),a=fR(s,t.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:hR(a)}}}case"escaped":{const s=await n.detectOverflow(e,{...o,altBoundary:!0}),a=fR(s,t.floating);return{data:{escapedOffsets:a,escaped:hR(a)}}}default:return{}}}}},IM=new Set(["left","top"]);async function O3(r,e){const{placement:t,platform:n,elements:i}=r,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),s=No(t),a=Mc(t),l=Hi(t)==="y",c=IM.has(s)?-1:1,u=o&&l?-1:1,d=Do(e,r);let{mainAxis:f,crossAxis:p,alignmentAxis:h}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof h=="number"&&(p=a==="end"?h*-1:h),l?{x:p*u,y:f*c}:{x:f*c,y:p*u}}const P3=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;const{x:i,y:o,placement:s,middlewareData:a}=e,l=await O3(e,r);return s===((t=a.offset)==null?void 0:t.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}},M3=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){const{x:t,y:n,placement:i,platform:o}=e,{mainAxis:s=!0,crossAxis:a=!1,limiter:l={fn:g=>{let{x:b,y:R}=g;return{x:b,y:R}}},...c}=Do(r,e),u={x:t,y:n},d=await o.detectOverflow(e,c),f=Hi(No(i)),p=jE(f);let h=u[p],m=u[f];if(s){const g=p==="y"?"top":"left",b=p==="y"?"bottom":"right",R=h+d[g],k=h-d[b];h=NS(R,h,k)}if(a){const g=f==="y"?"top":"left",b=f==="y"?"bottom":"right",R=m+d[g],k=m-d[b];m=NS(R,m,k)}const w=l.fn({...e,[p]:h,[f]:m});return{...w,data:{x:w.x-t,y:w.y-n,enabled:{[p]:s,[f]:a}}}}}},A3=function(r){return r===void 0&&(r={}),{options:r,fn(e){const{x:t,y:n,placement:i,rects:o,middlewareData:s}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=Do(r,e),u={x:t,y:n},d=Hi(i),f=jE(d);let p=u[f],h=u[d];const m=Do(a,e),w=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const R=f==="y"?"height":"width",k=o.reference[f]-o.floating[R]+w.mainAxis,O=o.reference[f]+o.reference[R]-w.mainAxis;p<k?p=k:p>O&&(p=O)}if(c){var g,b;const R=f==="y"?"width":"height",k=IM.has(No(i)),O=o.reference[d]-o.floating[R]+(k&&((g=s.offset)==null?void 0:g[d])||0)+(k?0:w.crossAxis),T=o.reference[d]+o.reference[R]+(k?0:((b=s.offset)==null?void 0:b[d])||0)-(k?w.crossAxis:0);h<O?h=O:h>T&&(h=T)}return{[f]:p,[d]:h}}}},D3=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){var t,n;const{placement:i,rects:o,platform:s,elements:a}=e,{apply:l=()=>{},...c}=Do(r,e),u=await s.detectOverflow(e,c),d=No(i),f=Mc(i),p=Hi(i)==="y",{width:h,height:m}=o.floating;let w,g;d==="top"||d==="bottom"?(w=d,g=f===(await(s.isRTL==null?void 0:s.isRTL(a.floating))?"start":"end")?"left":"right"):(g=d,w=f==="end"?"top":"bottom");const b=m-u.top-u.bottom,R=h-u.left-u.right,k=Ps(m-u[w],b),O=Ps(h-u[g],R),T=!e.middlewareData.shift;let x=k,C=O;if((t=e.middlewareData.shift)!=null&&t.enabled.x&&(C=R),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(x=b),T&&!f){const F=Nn(u.left,0),H=Nn(u.right,0),ie=Nn(u.top,0),$=Nn(u.bottom,0);p?C=h-2*(F!==0||H!==0?F+H:Nn(u.left,u.right)):x=m-2*(ie!==0||$!==0?ie+$:Nn(u.top,u.bottom))}await l({...e,availableWidth:C,availableHeight:x});const N=await s.getDimensions(a.floating);return h!==N.width||m!==N.height?{reset:{rects:!0}}:{}}}};function $v(){return typeof window<"u"}function Ac(r){return xM(r)?(r.nodeName||"").toLowerCase():"#document"}function Fn(r){var e;return(r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function ro(r){var e;return(e=(xM(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function xM(r){return $v()?r instanceof Node||r instanceof Fn(r).Node:!1}function Ri(r){return $v()?r instanceof Element||r instanceof Fn(r).Element:!1}function Uo(r){return $v()?r instanceof HTMLElement||r instanceof Fn(r).HTMLElement:!1}function pR(r){return!$v()||typeof ShadowRoot>"u"?!1:r instanceof ShadowRoot||r instanceof Fn(r).ShadowRoot}function af(r){const{overflow:e,overflowX:t,overflowY:n,display:i}=Ci(r);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&i!=="inline"&&i!=="contents"}function N3(r){return/^(table|td|th)$/.test(Ac(r))}function Wv(r){try{if(r.matches(":popover-open"))return!0}catch{}try{return r.matches(":modal")}catch{return!1}}const L3=/transform|translate|scale|rotate|perspective|filter/,U3=/paint|layout|strict|content/,Js=r=>!!r&&r!=="none";let xg;function KE(r){const e=Ri(r)?Ci(r):r;return Js(e.transform)||Js(e.translate)||Js(e.scale)||Js(e.rotate)||Js(e.perspective)||!VE()&&(Js(e.backdropFilter)||Js(e.filter))||L3.test(e.willChange||"")||U3.test(e.contain||"")}function j3(r){let e=Ms(r);for(;Uo(e)&&!dc(e);){if(KE(e))return e;if(Wv(e))return null;e=Ms(e)}return null}function VE(){return xg==null&&(xg=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),xg}function dc(r){return/^(html|body|#document)$/.test(Ac(r))}function Ci(r){return Fn(r).getComputedStyle(r)}function qv(r){return Ri(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function Ms(r){if(Ac(r)==="html")return r;const e=r.assignedSlot||r.parentNode||pR(r)&&r.host||ro(r);return pR(e)?e.host:e}function OM(r){const e=Ms(r);return dc(e)?r.ownerDocument?r.ownerDocument.body:r.body:Uo(e)&&af(e)?e:OM(e)}function Od(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const i=OM(r),o=i===((n=r.ownerDocument)==null?void 0:n.body),s=Fn(i);if(o){const a=US(s);return e.concat(s,s.visualViewport||[],af(i)?i:[],a&&t?Od(a):[])}else return e.concat(i,Od(i,[],t))}function US(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function PM(r){const e=Ci(r);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=Uo(r),o=i?r.offsetWidth:t,s=i?r.offsetHeight:n,a=Dp(t)!==o||Dp(n)!==s;return a&&(t=o,n=s),{width:t,height:n,$:a}}function $E(r){return Ri(r)?r:r.contextElement}function Gl(r){const e=$E(r);if(!Uo(e))return Ji(1);const t=e.getBoundingClientRect(),{width:n,height:i,$:o}=PM(e);let s=(o?Dp(t.width):t.width)/n,a=(o?Dp(t.height):t.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}const F3=Ji(0);function MM(r){const e=Fn(r);return!VE()||!e.visualViewport?F3:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function B3(r,e,t){return e===void 0&&(e=!1),!t||e&&t!==Fn(r)?!1:e}function Na(r,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const i=r.getBoundingClientRect(),o=$E(r);let s=Ji(1);e&&(n?Ri(n)&&(s=Gl(n)):s=Gl(r));const a=B3(o,t,n)?MM(o):Ji(0);let l=(i.left+a.x)/s.x,c=(i.top+a.y)/s.y,u=i.width/s.x,d=i.height/s.y;if(o){const f=Fn(o),p=n&&Ri(n)?Fn(n):n;let h=f,m=US(h);for(;m&&n&&p!==h;){const w=Gl(m),g=m.getBoundingClientRect(),b=Ci(m),R=g.left+(m.clientLeft+parseFloat(b.paddingLeft))*w.x,k=g.top+(m.clientTop+parseFloat(b.paddingTop))*w.y;l*=w.x,c*=w.y,u*=w.x,d*=w.y,l+=R,c+=k,h=Fn(m),m=US(h)}}return Lp({width:u,height:d,x:l,y:c})}function Gv(r,e){const t=qv(r).scrollLeft;return e?e.left+t:Na(ro(r)).left+t}function AM(r,e){const t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-Gv(r,t),i=t.top+e.scrollTop;return{x:n,y:i}}function K3(r){let{elements:e,rect:t,offsetParent:n,strategy:i}=r;const o=i==="fixed",s=ro(n),a=e?Wv(e.floating):!1;if(n===s||a&&o)return t;let l={scrollLeft:0,scrollTop:0},c=Ji(1);const u=Ji(0),d=Uo(n);if((d||!d&&!o)&&((Ac(n)!=="body"||af(s))&&(l=qv(n)),d)){const p=Na(n);c=Gl(n),u.x=p.x+n.clientLeft,u.y=p.y+n.clientTop}const f=s&&!d&&!o?AM(s,l):Ji(0);return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+u.x+f.x,y:t.y*c.y-l.scrollTop*c.y+u.y+f.y}}function V3(r){return Array.from(r.getClientRects())}function $3(r){const e=ro(r),t=qv(r),n=r.ownerDocument.body,i=Nn(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),o=Nn(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let s=-t.scrollLeft+Gv(r);const a=-t.scrollTop;return Ci(n).direction==="rtl"&&(s+=Nn(e.clientWidth,n.clientWidth)-i),{width:i,height:o,x:s,y:a}}const vR=25;function W3(r,e){const t=Fn(r),n=ro(r),i=t.visualViewport;let o=n.clientWidth,s=n.clientHeight,a=0,l=0;if(i){o=i.width,s=i.height;const u=VE();(!u||u&&e==="fixed")&&(a=i.offsetLeft,l=i.offsetTop)}const c=Gv(n);if(c<=0){const u=n.ownerDocument,d=u.body,f=getComputedStyle(d),p=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,h=Math.abs(n.clientWidth-d.clientWidth-p);h<=vR&&(o-=h)}else c<=vR&&(o+=c);return{width:o,height:s,x:a,y:l}}function q3(r,e){const t=Na(r,!0,e==="fixed"),n=t.top+r.clientTop,i=t.left+r.clientLeft,o=Uo(r)?Gl(r):Ji(1),s=r.clientWidth*o.x,a=r.clientHeight*o.y,l=i*o.x,c=n*o.y;return{width:s,height:a,x:l,y:c}}function mR(r,e,t){let n;if(e==="viewport")n=W3(r,t);else if(e==="document")n=$3(ro(r));else if(Ri(e))n=q3(e,t);else{const i=MM(r);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return Lp(n)}function DM(r,e){const t=Ms(r);return t===e||!Ri(t)||dc(t)?!1:Ci(t).position==="fixed"||DM(t,e)}function G3(r,e){const t=e.get(r);if(t)return t;let n=Od(r,[],!1).filter(a=>Ri(a)&&Ac(a)!=="body"),i=null;const o=Ci(r).position==="fixed";let s=o?Ms(r):r;for(;Ri(s)&&!dc(s);){const a=Ci(s),l=KE(s);!l&&a.position==="fixed"&&(i=null),(o?!l&&!i:!l&&a.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||af(s)&&!l&&DM(r,s))?n=n.filter(u=>u!==s):i=a,s=Ms(s)}return e.set(r,n),n}function H3(r){let{element:e,boundary:t,rootBoundary:n,strategy:i}=r;const s=[...t==="clippingAncestors"?Wv(e)?[]:G3(e,this._c):[].concat(t),n],a=mR(e,s[0],i);let l=a.top,c=a.right,u=a.bottom,d=a.left;for(let f=1;f<s.length;f++){const p=mR(e,s[f],i);l=Nn(p.top,l),c=Ps(p.right,c),u=Ps(p.bottom,u),d=Nn(p.left,d)}return{width:c-d,height:u-l,x:d,y:l}}function z3(r){const{width:e,height:t}=PM(r);return{width:e,height:t}}function Y3(r,e,t){const n=Uo(e),i=ro(e),o=t==="fixed",s=Na(r,!0,o,e);let a={scrollLeft:0,scrollTop:0};const l=Ji(0);function c(){l.x=Gv(i)}if(n||!n&&!o)if((Ac(e)!=="body"||af(i))&&(a=qv(e)),n){const p=Na(e,!0,o,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else i&&c();o&&!n&&i&&c();const u=i&&!n&&!o?AM(i,a):Ji(0),d=s.left+a.scrollLeft-l.x-u.x,f=s.top+a.scrollTop-l.y-u.y;return{x:d,y:f,width:s.width,height:s.height}}function Og(r){return Ci(r).position==="static"}function gR(r,e){if(!Uo(r)||Ci(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return ro(r)===t&&(t=t.ownerDocument.body),t}function NM(r,e){const t=Fn(r);if(Wv(r))return t;if(!Uo(r)){let i=Ms(r);for(;i&&!dc(i);){if(Ri(i)&&!Og(i))return i;i=Ms(i)}return t}let n=gR(r,e);for(;n&&N3(n)&&Og(n);)n=gR(n,e);return n&&dc(n)&&Og(n)&&!KE(n)?t:n||j3(r)||t}const J3=async function(r){const e=this.getOffsetParent||NM,t=this.getDimensions,n=await t(r.floating);return{reference:Y3(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function X3(r){return Ci(r).direction==="rtl"}const Q3={convertOffsetParentRelativeRectToViewportRelativeRect:K3,getDocumentElement:ro,getClippingRect:H3,getOffsetParent:NM,getElementRects:J3,getClientRects:V3,getDimensions:z3,getScale:Gl,isElement:Ri,isRTL:X3};function LM(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function Z3(r,e){let t=null,n;const i=ro(r);function o(){var a;clearTimeout(n),(a=t)==null||a.disconnect(),t=null}function s(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),o();const c=r.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=c;if(a||e(),!f||!p)return;const h=th(d),m=th(i.clientWidth-(u+f)),w=th(i.clientHeight-(d+p)),g=th(u),R={rootMargin:-h+"px "+-m+"px "+-w+"px "+-g+"px",threshold:Nn(0,Ps(1,l))||1};let k=!0;function O(T){const x=T[0].intersectionRatio;if(x!==l){if(!k)return s();x?s(!1,x):n=setTimeout(()=>{s(!1,1e-7)},1e3)}x===1&&!LM(c,r.getBoundingClientRect())&&s(),k=!1}try{t=new IntersectionObserver(O,{...R,root:i.ownerDocument})}catch{t=new IntersectionObserver(O,R)}t.observe(r)}return s(!0),o}function eV(r,e,t,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=n,c=$E(r),u=i||o?[...c?Od(c):[],...e?Od(e):[]]:[];u.forEach(g=>{i&&g.addEventListener("scroll",t,{passive:!0}),o&&g.addEventListener("resize",t)});const d=c&&a?Z3(c,t):null;let f=-1,p=null;s&&(p=new ResizeObserver(g=>{let[b]=g;b&&b.target===c&&p&&e&&(p.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var R;(R=p)==null||R.observe(e)})),t()}),c&&!l&&p.observe(c),e&&p.observe(e));let h,m=l?Na(r):null;l&&w();function w(){const g=Na(r);m&&!LM(m,g)&&t(),m=g,h=requestAnimationFrame(w)}return t(),()=>{var g;u.forEach(b=>{i&&b.removeEventListener("scroll",t),o&&b.removeEventListener("resize",t)}),d==null||d(),(g=p)==null||g.disconnect(),p=null,l&&cancelAnimationFrame(h)}}const tV=P3,rV=M3,nV=I3,iV=D3,oV=x3,yR=k3,sV=A3,aV=(r,e,t)=>{const n=new Map,i={platform:Q3,...t},o={...i.platform,_c:n};return C3(r,e,{...i,platform:o})};var lV=typeof document<"u",cV=function(){},Fh=lV?E.useLayoutEffect:cV;function Up(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="function"&&r.toString()===e.toString())return!0;let t,n,i;if(r&&e&&typeof r=="object"){if(Array.isArray(r)){if(t=r.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!Up(r[n],e[n]))return!1;return!0}if(i=Object.keys(r),t=i.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,i[n]))return!1;for(n=t;n--!==0;){const o=i[n];if(!(o==="_owner"&&r.$$typeof)&&!Up(r[o],e[o]))return!1}return!0}return r!==r&&e!==e}function UM(r){return typeof window>"u"?1:(r.ownerDocument.defaultView||window).devicePixelRatio||1}function SR(r,e){const t=UM(r);return Math.round(e*t)/t}function Pg(r){const e=E.useRef(r);return Fh(()=>{e.current=r}),e}function uV(r){r===void 0&&(r={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:i,elements:{reference:o,floating:s}={},transform:a=!0,whileElementsMounted:l,open:c}=r,[u,d]=E.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[f,p]=E.useState(n);Up(f,n)||p(n);const[h,m]=E.useState(null),[w,g]=E.useState(null),b=E.useCallback(q=>{q!==T.current&&(T.current=q,m(q))},[]),R=E.useCallback(q=>{q!==x.current&&(x.current=q,g(q))},[]),k=o||h,O=s||w,T=E.useRef(null),x=E.useRef(null),C=E.useRef(u),N=l!=null,F=Pg(l),H=Pg(i),ie=Pg(c),$=E.useCallback(()=>{if(!T.current||!x.current)return;const q={placement:e,strategy:t,middleware:f};H.current&&(q.platform=H.current),aV(T.current,x.current,q).then(z=>{const Q={...z,isPositioned:ie.current!==!1};X.current&&!Up(C.current,Q)&&(C.current=Q,Av.flushSync(()=>{d(Q)}))})},[f,e,t,H,ie]);Fh(()=>{c===!1&&C.current.isPositioned&&(C.current.isPositioned=!1,d(q=>({...q,isPositioned:!1})))},[c]);const X=E.useRef(!1);Fh(()=>(X.current=!0,()=>{X.current=!1}),[]),Fh(()=>{if(k&&(T.current=k),O&&(x.current=O),k&&O){if(F.current)return F.current(k,O,$);$()}},[k,O,$,F,N]);const oe=E.useMemo(()=>({reference:T,floating:x,setReference:b,setFloating:R}),[b,R]),re=E.useMemo(()=>({reference:k,floating:O}),[k,O]),ae=E.useMemo(()=>{const q={position:t,left:0,top:0};if(!re.floating)return q;const z=SR(re.floating,u.x),Q=SR(re.floating,u.y);return a?{...q,transform:"translate("+z+"px, "+Q+"px)",...UM(re.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:z,top:Q}},[t,a,re.floating,u.x,u.y]);return E.useMemo(()=>({...u,update:$,refs:oe,elements:re,floatingStyles:ae}),[u,$,oe,re,ae])}const dV=r=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:r,fn(t){const{element:n,padding:i}=typeof r=="function"?r(t):r;return n&&e(n)?n.current!=null?yR({element:n.current,padding:i}).fn(t):{}:n?yR({element:n,padding:i}).fn(t):{}}}},fV=(r,e)=>{const t=tV(r);return{name:t.name,fn:t.fn,options:[r,e]}},hV=(r,e)=>{const t=rV(r);return{name:t.name,fn:t.fn,options:[r,e]}},pV=(r,e)=>({fn:sV(r).fn,options:[r,e]}),vV=(r,e)=>{const t=nV(r);return{name:t.name,fn:t.fn,options:[r,e]}},mV=(r,e)=>{const t=iV(r);return{name:t.name,fn:t.fn,options:[r,e]}},gV=(r,e)=>{const t=oV(r);return{name:t.name,fn:t.fn,options:[r,e]}},yV=(r,e)=>{const t=dV(r);return{name:t.name,fn:t.fn,options:[r,e]}};var SV="Arrow",jM=E.forwardRef((r,e)=>{const{children:t,width:n=10,height:i=5,...o}=r;return y.jsx(Je.svg,{...o,ref:e,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:r.asChild?t:y.jsx("polygon",{points:"0,0 30,0 15,10"})})});jM.displayName=SV;var bV=jM,WE="Popper",[FM,Dc]=to(WE),[_V,BM]=FM(WE),KM=r=>{const{__scopePopper:e,children:t}=r,[n,i]=E.useState(null);return y.jsx(_V,{scope:e,anchor:n,onAnchorChange:i,children:t})};KM.displayName=WE;var VM="PopperAnchor",$M=E.forwardRef((r,e)=>{const{__scopePopper:t,virtualRef:n,...i}=r,o=BM(VM,t),s=E.useRef(null),a=_t(e,s),l=E.useRef(null);return E.useEffect(()=>{const c=l.current;l.current=(n==null?void 0:n.current)||s.current,c!==l.current&&o.onAnchorChange(l.current)}),n?null:y.jsx(Je.div,{...i,ref:a})});$M.displayName=VM;var qE="PopperContent",[EV,wV]=FM(qE),WM=E.forwardRef((r,e)=>{var D,P,M,I,j,U;const{__scopePopper:t,side:n="bottom",sideOffset:i=0,align:o="center",alignOffset:s=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:h,...m}=r,w=BM(qE,t),[g,b]=E.useState(null),R=_t(e,K=>b(K)),[k,O]=E.useState(null),T=p3(k),x=(T==null?void 0:T.width)??0,C=(T==null?void 0:T.height)??0,N=n+(o!=="center"?"-"+o:""),F=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},H=Array.isArray(c)?c:[c],ie=H.length>0,$={padding:F,boundary:H.filter(RV),altBoundary:ie},{refs:X,floatingStyles:oe,placement:re,isPositioned:ae,middlewareData:q}=uV({strategy:"fixed",placement:N,whileElementsMounted:(...K)=>eV(...K,{animationFrame:p==="always"}),elements:{reference:w.anchor},middleware:[fV({mainAxis:i+C,alignmentAxis:s}),l&&hV({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?pV():void 0,...$}),l&&vV({...$}),mV({...$,apply:({elements:K,rects:G,availableWidth:ee,availableHeight:se})=>{const{width:Ce,height:Re}=G.reference,ge=K.floating.style;ge.setProperty("--radix-popper-available-width",`${ee}px`),ge.setProperty("--radix-popper-available-height",`${se}px`),ge.setProperty("--radix-popper-anchor-width",`${Ce}px`),ge.setProperty("--radix-popper-anchor-height",`${Re}px`)}}),k&&yV({element:k,padding:a}),CV({arrowWidth:x,arrowHeight:C}),f&&gV({strategy:"referenceHidden",...$})]}),[z,Q]=HM(re),Ie=Pr(h);Zn(()=>{ae&&(Ie==null||Ie())},[ae,Ie]);const Y=(D=q.arrow)==null?void 0:D.x,le=(P=q.arrow)==null?void 0:P.y,B=((M=q.arrow)==null?void 0:M.centerOffset)!==0,[W,A]=E.useState();return Zn(()=>{g&&A(window.getComputedStyle(g).zIndex)},[g]),y.jsx("div",{ref:X.setFloating,"data-radix-popper-content-wrapper":"",style:{...oe,transform:ae?oe.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:W,"--radix-popper-transform-origin":[(I=q.transformOrigin)==null?void 0:I.x,(j=q.transformOrigin)==null?void 0:j.y].join(" "),...((U=q.hide)==null?void 0:U.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:r.dir,children:y.jsx(EV,{scope:t,placedSide:z,onArrowChange:O,arrowX:Y,arrowY:le,shouldHideArrow:B,children:y.jsx(Je.div,{"data-side":z,"data-align":Q,...m,ref:R,style:{...m.style,animation:ae?void 0:"none"}})})})});WM.displayName=qE;var qM="PopperArrow",TV={top:"bottom",right:"left",bottom:"top",left:"right"},GM=E.forwardRef(function(e,t){const{__scopePopper:n,...i}=e,o=wV(qM,n),s=TV[o.placedSide];return y.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:y.jsx(bV,{...i,ref:t,style:{...i.style,display:"block"}})})});GM.displayName=qM;function RV(r){return r!==null}var CV=r=>({name:"transformOrigin",options:r,fn(e){var w,g,b;const{placement:t,rects:n,middlewareData:i}=e,s=((w=i.arrow)==null?void 0:w.centerOffset)!==0,a=s?0:r.arrowWidth,l=s?0:r.arrowHeight,[c,u]=HM(t),d={start:"0%",center:"50%",end:"100%"}[u],f=(((g=i.arrow)==null?void 0:g.x)??0)+a/2,p=(((b=i.arrow)==null?void 0:b.y)??0)+l/2;let h="",m="";return c==="bottom"?(h=s?d:`${f}px`,m=`${-l}px`):c==="top"?(h=s?d:`${f}px`,m=`${n.floating.height+l}px`):c==="right"?(h=`${-l}px`,m=s?d:`${p}px`):c==="left"&&(h=`${n.floating.width+l}px`,m=s?d:`${p}px`),{data:{x:h,y:m}}}});function HM(r){const[e,t="center"]=r.split("-");return[e,t]}var zM=KM,Hv=$M,GE=WM,HE=GM,Mg="rovingFocusGroup.onEntryFocus",kV={bubbles:!1,cancelable:!0},lf="RovingFocusGroup",[jS,YM,IV]=qP(lf),[xV,JM]=to(lf,[IV]),[OV,PV]=xV(lf),XM=E.forwardRef((r,e)=>y.jsx(jS.Provider,{scope:r.__scopeRovingFocusGroup,children:y.jsx(jS.Slot,{scope:r.__scopeRovingFocusGroup,children:y.jsx(MV,{...r,ref:e})})}));XM.displayName=lf;var MV=E.forwardRef((r,e)=>{const{__scopeRovingFocusGroup:t,orientation:n,loop:i=!1,dir:o,currentTabStopId:s,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...d}=r,f=E.useRef(null),p=_t(e,f),h=CE(o),[m,w]=Uv({prop:s,defaultProp:a??null,onChange:l,caller:lf}),[g,b]=E.useState(!1),R=Pr(c),k=YM(t),O=E.useRef(!1),[T,x]=E.useState(0);return E.useEffect(()=>{const C=f.current;if(C)return C.addEventListener(Mg,R),()=>C.removeEventListener(Mg,R)},[R]),y.jsx(OV,{scope:t,orientation:n,dir:h,loop:i,currentTabStopId:m,onItemFocus:E.useCallback(C=>w(C),[w]),onItemShiftTab:E.useCallback(()=>b(!0),[]),onFocusableItemAdd:E.useCallback(()=>x(C=>C+1),[]),onFocusableItemRemove:E.useCallback(()=>x(C=>C-1),[]),children:y.jsx(Je.div,{tabIndex:g||T===0?-1:0,"data-orientation":n,...d,ref:p,style:{outline:"none",...r.style},onMouseDown:Me(r.onMouseDown,()=>{O.current=!0}),onFocus:Me(r.onFocus,C=>{const N=!O.current;if(C.target===C.currentTarget&&N&&!g){const F=new CustomEvent(Mg,kV);if(C.currentTarget.dispatchEvent(F),!F.defaultPrevented){const H=k().filter(re=>re.focusable),ie=H.find(re=>re.active),$=H.find(re=>re.id===m),oe=[ie,$,...H].filter(Boolean).map(re=>re.ref.current);eA(oe,u)}}O.current=!1}),onBlur:Me(r.onBlur,()=>b(!1))})})}),QM="RovingFocusGroupItem",ZM=E.forwardRef((r,e)=>{const{__scopeRovingFocusGroup:t,focusable:n=!0,active:i=!1,tabStopId:o,children:s,...a}=r,l=jn(),c=o||l,u=PV(QM,t),d=u.currentTabStopId===c,f=YM(t),{onFocusableItemAdd:p,onFocusableItemRemove:h,currentTabStopId:m}=u;return E.useEffect(()=>{if(n)return p(),()=>h()},[n,p,h]),y.jsx(jS.ItemSlot,{scope:t,id:c,focusable:n,active:i,children:y.jsx(Je.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...a,ref:e,onMouseDown:Me(r.onMouseDown,w=>{n?u.onItemFocus(c):w.preventDefault()}),onFocus:Me(r.onFocus,()=>u.onItemFocus(c)),onKeyDown:Me(r.onKeyDown,w=>{if(w.key==="Tab"&&w.shiftKey){u.onItemShiftTab();return}if(w.target!==w.currentTarget)return;const g=NV(w,u.orientation,u.dir);if(g!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let R=f().filter(k=>k.focusable).map(k=>k.ref.current);if(g==="last")R.reverse();else if(g==="prev"||g==="next"){g==="prev"&&R.reverse();const k=R.indexOf(w.currentTarget);R=u.loop?LV(R,k+1):R.slice(k+1)}setTimeout(()=>eA(R))}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:m!=null}):s})})});ZM.displayName=QM;var AV={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function DV(r,e){return e!=="rtl"?r:r==="ArrowLeft"?"ArrowRight":r==="ArrowRight"?"ArrowLeft":r}function NV(r,e,t){const n=DV(r.key,t);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return AV[n]}function eA(r,e=!1){const t=document.activeElement;for(const n of r)if(n===t||(n.focus({preventScroll:e}),document.activeElement!==t))return}function LV(r,e){return r.map((t,n)=>r[(e+n)%r.length])}var UV=XM,jV=ZM,FS=["Enter"," "],FV=["ArrowDown","PageUp","Home"],tA=["ArrowUp","PageDown","End"],BV=[...FV,...tA],KV={ltr:[...FS,"ArrowRight"],rtl:[...FS,"ArrowLeft"]},VV={ltr:["ArrowLeft"],rtl:["ArrowRight"]},cf="Menu",[Pd,$V,WV]=qP(cf),[Ha,rA]=to(cf,[WV,Dc,JM]),zv=Dc(),nA=JM(),[qV,za]=Ha(cf),[GV,uf]=Ha(cf),iA=r=>{const{__scopeMenu:e,open:t=!1,children:n,dir:i,onOpenChange:o,modal:s=!0}=r,a=zv(e),[l,c]=E.useState(null),u=E.useRef(!1),d=Pr(o),f=CE(i);return E.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),y.jsx(zM,{...a,children:y.jsx(qV,{scope:e,open:t,onOpenChange:d,content:l,onContentChange:c,children:y.jsx(GV,{scope:e,onClose:E.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:s,children:n})})})};iA.displayName=cf;var HV="MenuAnchor",zE=E.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r,i=zv(t);return y.jsx(Hv,{...i,...n,ref:e})});zE.displayName=HV;var YE="MenuPortal",[zV,oA]=Ha(YE,{forceMount:void 0}),sA=r=>{const{__scopeMenu:e,forceMount:t,children:n,container:i}=r,o=za(YE,e);return y.jsx(zV,{scope:e,forceMount:t,children:y.jsx(sn,{present:t||o.open,children:y.jsx(Fv,{asChild:!0,container:i,children:n})})})};sA.displayName=YE;var Yn="MenuContent",[YV,JE]=Ha(Yn),aA=E.forwardRef((r,e)=>{const t=oA(Yn,r.__scopeMenu),{forceMount:n=t.forceMount,...i}=r,o=za(Yn,r.__scopeMenu),s=uf(Yn,r.__scopeMenu);return y.jsx(Pd.Provider,{scope:r.__scopeMenu,children:y.jsx(sn,{present:n||o.open,children:y.jsx(Pd.Slot,{scope:r.__scopeMenu,children:s.modal?y.jsx(JV,{...i,ref:e}):y.jsx(XV,{...i,ref:e})})})})}),JV=E.forwardRef((r,e)=>{const t=za(Yn,r.__scopeMenu),n=E.useRef(null),i=_t(e,n);return E.useEffect(()=>{const o=n.current;if(o)return IE(o)},[]),y.jsx(XE,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:t.open,disableOutsideScroll:!0,onFocusOutside:Me(r.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>t.onOpenChange(!1)})}),XV=E.forwardRef((r,e)=>{const t=za(Yn,r.__scopeMenu);return y.jsx(XE,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>t.onOpenChange(!1)})}),QV=Aa("MenuContent.ScrollLock"),XE=E.forwardRef((r,e)=>{const{__scopeMenu:t,loop:n=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:h,...m}=r,w=za(Yn,t),g=uf(Yn,t),b=zv(t),R=nA(t),k=$V(t),[O,T]=E.useState(null),x=E.useRef(null),C=_t(e,x,w.onContentChange),N=E.useRef(0),F=E.useRef(""),H=E.useRef(0),ie=E.useRef(null),$=E.useRef("right"),X=E.useRef(0),oe=h?Kv:E.Fragment,re=h?{as:QV,allowPinchZoom:!0}:void 0,ae=z=>{var D,P;const Q=F.current+z,Ie=k().filter(M=>!M.disabled),Y=document.activeElement,le=(D=Ie.find(M=>M.ref.current===Y))==null?void 0:D.textValue,B=Ie.map(M=>M.textValue),W=u4(B,Q,le),A=(P=Ie.find(M=>M.textValue===W))==null?void 0:P.ref.current;(function M(I){F.current=I,window.clearTimeout(N.current),I!==""&&(N.current=window.setTimeout(()=>M(""),1e3))})(Q),A&&setTimeout(()=>A.focus())};E.useEffect(()=>()=>window.clearTimeout(N.current),[]),kE();const q=E.useCallback(z=>{var Ie,Y;return $.current===((Ie=ie.current)==null?void 0:Ie.side)&&f4(z,(Y=ie.current)==null?void 0:Y.area)},[]);return y.jsx(YV,{scope:t,searchRef:F,onItemEnter:E.useCallback(z=>{q(z)&&z.preventDefault()},[q]),onItemLeave:E.useCallback(z=>{var Q;q(z)||((Q=x.current)==null||Q.focus(),T(null))},[q]),onTriggerLeave:E.useCallback(z=>{q(z)&&z.preventDefault()},[q]),pointerGraceTimerRef:H,onPointerGraceIntentChange:E.useCallback(z=>{ie.current=z},[]),children:y.jsx(oe,{...re,children:y.jsx(jv,{asChild:!0,trapped:i,onMountAutoFocus:Me(o,z=>{var Q;z.preventDefault(),(Q=x.current)==null||Q.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:y.jsx(sf,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:y.jsx(UV,{asChild:!0,...R,dir:g.dir,orientation:"vertical",loop:n,currentTabStopId:O,onCurrentTabStopIdChange:T,onEntryFocus:Me(l,z=>{g.isUsingKeyboardRef.current||z.preventDefault()}),preventScrollOnEntryFocus:!0,children:y.jsx(GE,{role:"menu","aria-orientation":"vertical","data-state":wA(w.open),"data-radix-menu-content":"",dir:g.dir,...b,...m,ref:C,style:{outline:"none",...m.style},onKeyDown:Me(m.onKeyDown,z=>{const Ie=z.target.closest("[data-radix-menu-content]")===z.currentTarget,Y=z.ctrlKey||z.altKey||z.metaKey,le=z.key.length===1;Ie&&(z.key==="Tab"&&z.preventDefault(),!Y&&le&&ae(z.key));const B=x.current;if(z.target!==B||!BV.includes(z.key))return;z.preventDefault();const A=k().filter(D=>!D.disabled).map(D=>D.ref.current);tA.includes(z.key)&&A.reverse(),l4(A)}),onBlur:Me(r.onBlur,z=>{z.currentTarget.contains(z.target)||(window.clearTimeout(N.current),F.current="")}),onPointerMove:Me(r.onPointerMove,Md(z=>{const Q=z.target,Ie=X.current!==z.clientX;if(z.currentTarget.contains(Q)&&Ie){const Y=z.clientX>X.current?"right":"left";$.current=Y,X.current=z.clientX}}))})})})})})})});aA.displayName=Yn;var ZV="MenuGroup",QE=E.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r;return y.jsx(Je.div,{role:"group",...n,ref:e})});QE.displayName=ZV;var e4="MenuLabel",lA=E.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r;return y.jsx(Je.div,{...n,ref:e})});lA.displayName=e4;var jp="MenuItem",bR="menu.itemSelect",Yv=E.forwardRef((r,e)=>{const{disabled:t=!1,onSelect:n,...i}=r,o=E.useRef(null),s=uf(jp,r.__scopeMenu),a=JE(jp,r.__scopeMenu),l=_t(e,o),c=E.useRef(!1),u=()=>{const d=o.current;if(!t&&d){const f=new CustomEvent(bR,{bubbles:!0,cancelable:!0});d.addEventListener(bR,p=>n==null?void 0:n(p),{once:!0}),$P(d,f),f.defaultPrevented?c.current=!1:s.onClose()}};return y.jsx(cA,{...i,ref:l,disabled:t,onClick:Me(r.onClick,u),onPointerDown:d=>{var f;(f=r.onPointerDown)==null||f.call(r,d),c.current=!0},onPointerUp:Me(r.onPointerUp,d=>{var f;c.current||(f=d.currentTarget)==null||f.click()}),onKeyDown:Me(r.onKeyDown,d=>{const f=a.searchRef.current!=="";t||f&&d.key===" "||FS.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});Yv.displayName=jp;var cA=E.forwardRef((r,e)=>{const{__scopeMenu:t,disabled:n=!1,textValue:i,...o}=r,s=JE(jp,t),a=nA(t),l=E.useRef(null),c=_t(e,l),[u,d]=E.useState(!1),[f,p]=E.useState("");return E.useEffect(()=>{const h=l.current;h&&p((h.textContent??"").trim())},[o.children]),y.jsx(Pd.ItemSlot,{scope:t,disabled:n,textValue:i??f,children:y.jsx(jV,{asChild:!0,...a,focusable:!n,children:y.jsx(Je.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...o,ref:c,onPointerMove:Me(r.onPointerMove,Md(h=>{n?s.onItemLeave(h):(s.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Me(r.onPointerLeave,Md(h=>s.onItemLeave(h))),onFocus:Me(r.onFocus,()=>d(!0)),onBlur:Me(r.onBlur,()=>d(!1))})})})}),t4="MenuCheckboxItem",uA=E.forwardRef((r,e)=>{const{checked:t=!1,onCheckedChange:n,...i}=r;return y.jsx(vA,{scope:r.__scopeMenu,checked:t,children:y.jsx(Yv,{role:"menuitemcheckbox","aria-checked":Fp(t)?"mixed":t,...i,ref:e,"data-state":ew(t),onSelect:Me(i.onSelect,()=>n==null?void 0:n(Fp(t)?!0:!t),{checkForDefaultPrevented:!1})})})});uA.displayName=t4;var dA="MenuRadioGroup",[r4,n4]=Ha(dA,{value:void 0,onValueChange:()=>{}}),fA=E.forwardRef((r,e)=>{const{value:t,onValueChange:n,...i}=r,o=Pr(n);return y.jsx(r4,{scope:r.__scopeMenu,value:t,onValueChange:o,children:y.jsx(QE,{...i,ref:e})})});fA.displayName=dA;var hA="MenuRadioItem",pA=E.forwardRef((r,e)=>{const{value:t,...n}=r,i=n4(hA,r.__scopeMenu),o=t===i.value;return y.jsx(vA,{scope:r.__scopeMenu,checked:o,children:y.jsx(Yv,{role:"menuitemradio","aria-checked":o,...n,ref:e,"data-state":ew(o),onSelect:Me(n.onSelect,()=>{var s;return(s=i.onValueChange)==null?void 0:s.call(i,t)},{checkForDefaultPrevented:!1})})})});pA.displayName=hA;var ZE="MenuItemIndicator",[vA,i4]=Ha(ZE,{checked:!1}),mA=E.forwardRef((r,e)=>{const{__scopeMenu:t,forceMount:n,...i}=r,o=i4(ZE,t);return y.jsx(sn,{present:n||Fp(o.checked)||o.checked===!0,children:y.jsx(Je.span,{...i,ref:e,"data-state":ew(o.checked)})})});mA.displayName=ZE;var o4="MenuSeparator",gA=E.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r;return y.jsx(Je.div,{role:"separator","aria-orientation":"horizontal",...n,ref:e})});gA.displayName=o4;var s4="MenuArrow",yA=E.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r,i=zv(t);return y.jsx(HE,{...i,...n,ref:e})});yA.displayName=s4;var a4="MenuSub",[wte,SA]=Ha(a4),Ou="MenuSubTrigger",bA=E.forwardRef((r,e)=>{const t=za(Ou,r.__scopeMenu),n=uf(Ou,r.__scopeMenu),i=SA(Ou,r.__scopeMenu),o=JE(Ou,r.__scopeMenu),s=E.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=o,c={__scopeMenu:r.__scopeMenu},u=E.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return E.useEffect(()=>u,[u]),E.useEffect(()=>{const d=a.current;return()=>{window.clearTimeout(d),l(null)}},[a,l]),y.jsx(zE,{asChild:!0,...c,children:y.jsx(cA,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":t.open,"aria-controls":i.contentId,"data-state":wA(t.open),...r,ref:Ao(e,i.onTriggerChange),onClick:d=>{var f;(f=r.onClick)==null||f.call(r,d),!(r.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),t.open||t.onOpenChange(!0))},onPointerMove:Me(r.onPointerMove,Md(d=>{o.onItemEnter(d),!d.defaultPrevented&&!r.disabled&&!t.open&&!s.current&&(o.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{t.onOpenChange(!0),u()},100))})),onPointerLeave:Me(r.onPointerLeave,Md(d=>{var p,h;u();const f=(p=t.content)==null?void 0:p.getBoundingClientRect();if(f){const m=(h=t.content)==null?void 0:h.dataset.side,w=m==="right",g=w?-5:5,b=f[w?"left":"right"],R=f[w?"right":"left"];o.onPointerGraceIntentChange({area:[{x:d.clientX+g,y:d.clientY},{x:b,y:f.top},{x:R,y:f.top},{x:R,y:f.bottom},{x:b,y:f.bottom}],side:m}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(d),d.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Me(r.onKeyDown,d=>{var p;const f=o.searchRef.current!=="";r.disabled||f&&d.key===" "||KV[n.dir].includes(d.key)&&(t.onOpenChange(!0),(p=t.content)==null||p.focus(),d.preventDefault())})})})});bA.displayName=Ou;var _A="MenuSubContent",EA=E.forwardRef((r,e)=>{const t=oA(Yn,r.__scopeMenu),{forceMount:n=t.forceMount,...i}=r,o=za(Yn,r.__scopeMenu),s=uf(Yn,r.__scopeMenu),a=SA(_A,r.__scopeMenu),l=E.useRef(null),c=_t(e,l);return y.jsx(Pd.Provider,{scope:r.__scopeMenu,children:y.jsx(sn,{present:n||o.open,children:y.jsx(Pd.Slot,{scope:r.__scopeMenu,children:y.jsx(XE,{id:a.contentId,"aria-labelledby":a.triggerId,...i,ref:c,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var d;s.isUsingKeyboardRef.current&&((d=l.current)==null||d.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:Me(r.onFocusOutside,u=>{u.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Me(r.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:Me(r.onKeyDown,u=>{var p;const d=u.currentTarget.contains(u.target),f=VV[s.dir].includes(u.key);d&&f&&(o.onOpenChange(!1),(p=a.trigger)==null||p.focus(),u.preventDefault())})})})})})});EA.displayName=_A;function wA(r){return r?"open":"closed"}function Fp(r){return r==="indeterminate"}function ew(r){return Fp(r)?"indeterminate":r?"checked":"unchecked"}function l4(r){const e=document.activeElement;for(const t of r)if(t===e||(t.focus(),document.activeElement!==e))return}function c4(r,e){return r.map((t,n)=>r[(e+n)%r.length])}function u4(r,e,t){const i=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,o=t?r.indexOf(t):-1;let s=c4(r,Math.max(o,0));i.length===1&&(s=s.filter(c=>c!==t));const l=s.find(c=>c.toLowerCase().startsWith(i.toLowerCase()));return l!==t?l:void 0}function d4(r,e){const{x:t,y:n}=r;let i=!1;for(let o=0,s=e.length-1;o<e.length;s=o++){const a=e[o],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>n!=f>n&&t<(d-c)*(n-u)/(f-u)+c&&(i=!i)}return i}function f4(r,e){if(!e)return!1;const t={x:r.clientX,y:r.clientY};return d4(t,e)}function Md(r){return e=>e.pointerType==="mouse"?r(e):void 0}var h4=iA,p4=zE,v4=sA,m4=aA,g4=QE,y4=lA,S4=Yv,b4=uA,_4=fA,E4=pA,w4=mA,T4=gA,R4=yA,C4=bA,k4=EA,Jv="DropdownMenu",[I4]=to(Jv,[rA]),an=rA(),[x4,TA]=I4(Jv),RA=r=>{const{__scopeDropdownMenu:e,children:t,dir:n,open:i,defaultOpen:o,onOpenChange:s,modal:a=!0}=r,l=an(e),c=E.useRef(null),[u,d]=Uv({prop:i,defaultProp:o??!1,onChange:s,caller:Jv});return y.jsx(x4,{scope:e,triggerId:jn(),triggerRef:c,contentId:jn(),open:u,onOpenChange:d,onOpenToggle:E.useCallback(()=>d(f=>!f),[d]),modal:a,children:y.jsx(h4,{...l,open:u,onOpenChange:d,dir:n,modal:a,children:t})})};RA.displayName=Jv;var CA="DropdownMenuTrigger",kA=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,disabled:n=!1,...i}=r,o=TA(CA,t),s=an(t);return y.jsx(p4,{asChild:!0,...s,children:y.jsx(Je.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...i,ref:Ao(e,o.triggerRef),onPointerDown:Me(r.onPointerDown,a=>{!n&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:Me(r.onKeyDown,a=>{n||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});kA.displayName=CA;var O4="DropdownMenuPortal",IA=r=>{const{__scopeDropdownMenu:e,...t}=r,n=an(e);return y.jsx(v4,{...n,...t})};IA.displayName=O4;var xA="DropdownMenuContent",OA=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=TA(xA,t),o=an(t),s=E.useRef(!1);return y.jsx(m4,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...n,ref:e,onCloseAutoFocus:Me(r.onCloseAutoFocus,a=>{var l;s.current||(l=i.triggerRef.current)==null||l.focus(),s.current=!1,a.preventDefault()}),onInteractOutside:Me(r.onInteractOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;(!i.modal||u)&&(s.current=!0)}),style:{...r.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});OA.displayName=xA;var P4="DropdownMenuGroup",M4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(g4,{...i,...n,ref:e})});M4.displayName=P4;var A4="DropdownMenuLabel",D4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(y4,{...i,...n,ref:e})});D4.displayName=A4;var N4="DropdownMenuItem",PA=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(S4,{...i,...n,ref:e})});PA.displayName=N4;var L4="DropdownMenuCheckboxItem",U4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(b4,{...i,...n,ref:e})});U4.displayName=L4;var j4="DropdownMenuRadioGroup",F4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(_4,{...i,...n,ref:e})});F4.displayName=j4;var B4="DropdownMenuRadioItem",K4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(E4,{...i,...n,ref:e})});K4.displayName=B4;var V4="DropdownMenuItemIndicator",$4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(w4,{...i,...n,ref:e})});$4.displayName=V4;var W4="DropdownMenuSeparator",MA=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(T4,{...i,...n,ref:e})});MA.displayName=W4;var q4="DropdownMenuArrow",G4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(R4,{...i,...n,ref:e})});G4.displayName=q4;var H4="DropdownMenuSubTrigger",z4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(C4,{...i,...n,ref:e})});z4.displayName=H4;var Y4="DropdownMenuSubContent",J4=E.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return y.jsx(k4,{...i,...n,ref:e,style:{...r.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});J4.displayName=Y4;var X4=RA,Q4=kA,Z4=IA,e$=OA,t$=PA,r$=MA,n$="Label",AA=E.forwardRef((r,e)=>y.jsx(Je.label,{...r,ref:e,onMouseDown:t=>{var i;t.target.closest("button, input, select, textarea")||((i=r.onMouseDown)==null||i.call(r,t),!t.defaultPrevented&&t.detail>1&&t.preventDefault())}}));AA.displayName=n$;var i$=AA;function o$(r,[e,t]){return Math.min(t,Math.max(e,r))}var Xv="Popover",[DA]=to(Xv,[Dc]),df=Dc(),[s$,Vs]=DA(Xv),NA=r=>{const{__scopePopover:e,children:t,open:n,defaultOpen:i,onOpenChange:o,modal:s=!1}=r,a=df(e),l=E.useRef(null),[c,u]=E.useState(!1),[d,f]=Uv({prop:n,defaultProp:i??!1,onChange:o,caller:Xv});return y.jsx(zM,{...a,children:y.jsx(s$,{scope:e,contentId:jn(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:E.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:c,onCustomAnchorAdd:E.useCallback(()=>u(!0),[]),onCustomAnchorRemove:E.useCallback(()=>u(!1),[]),modal:s,children:t})})};NA.displayName=Xv;var LA="PopoverAnchor",a$=E.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=Vs(LA,t),o=df(t),{onCustomAnchorAdd:s,onCustomAnchorRemove:a}=i;return E.useEffect(()=>(s(),()=>a()),[s,a]),y.jsx(Hv,{...o,...n,ref:e})});a$.displayName=LA;var UA="PopoverTrigger",jA=E.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=Vs(UA,t),o=df(t),s=_t(e,i.triggerRef),a=y.jsx(Je.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":$A(i.open),...n,ref:s,onClick:Me(r.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:y.jsx(Hv,{asChild:!0,...o,children:a})});jA.displayName=UA;var tw="PopoverPortal",[l$,c$]=DA(tw,{forceMount:void 0}),FA=r=>{const{__scopePopover:e,forceMount:t,children:n,container:i}=r,o=Vs(tw,e);return y.jsx(l$,{scope:e,forceMount:t,children:y.jsx(sn,{present:t||o.open,children:y.jsx(Fv,{asChild:!0,container:i,children:n})})})};FA.displayName=tw;var fc="PopoverContent",BA=E.forwardRef((r,e)=>{const t=c$(fc,r.__scopePopover),{forceMount:n=t.forceMount,...i}=r,o=Vs(fc,r.__scopePopover);return y.jsx(sn,{present:n||o.open,children:o.modal?y.jsx(d$,{...i,ref:e}):y.jsx(f$,{...i,ref:e})})});BA.displayName=fc;var u$=Aa("PopoverContent.RemoveScroll"),d$=E.forwardRef((r,e)=>{const t=Vs(fc,r.__scopePopover),n=E.useRef(null),i=_t(e,n),o=E.useRef(!1);return E.useEffect(()=>{const s=n.current;if(s)return IE(s)},[]),y.jsx(Kv,{as:u$,allowPinchZoom:!0,children:y.jsx(KA,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Me(r.onCloseAutoFocus,s=>{var a;s.preventDefault(),o.current||(a=t.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Me(r.onPointerDownOutside,s=>{const a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;o.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:Me(r.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),f$=E.forwardRef((r,e)=>{const t=Vs(fc,r.__scopePopover),n=E.useRef(!1),i=E.useRef(!1);return y.jsx(KA,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var s,a;(s=r.onCloseAutoFocus)==null||s.call(r,o),o.defaultPrevented||(n.current||(a=t.triggerRef.current)==null||a.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var l,c;(l=r.onInteractOutside)==null||l.call(r,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;((c=t.triggerRef.current)==null?void 0:c.contains(s))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),KA=E.forwardRef((r,e)=>{const{__scopePopover:t,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=r,f=Vs(fc,t),p=df(t);return kE(),y.jsx(jv,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:y.jsx(sf,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>f.onOpenChange(!1),children:y.jsx(GE,{"data-state":$A(f.open),role:"dialog",id:f.contentId,...p,...d,ref:e,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),VA="PopoverClose",h$=E.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=Vs(VA,t);return y.jsx(Je.button,{type:"button",...n,ref:e,onClick:Me(r.onClick,()=>i.onOpenChange(!1))})});h$.displayName=VA;var p$="PopoverArrow",v$=E.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=df(t);return y.jsx(HE,{...i,...n,ref:e})});v$.displayName=p$;function $A(r){return r?"open":"closed"}var m$=NA,g$=jA,y$=FA,S$=BA;function b$(r,e){return E.useReducer((t,n)=>e[t][n]??t,r)}var rw="ScrollArea",[WA]=to(rw),[_$,ri]=WA(rw),qA=E.forwardRef((r,e)=>{const{__scopeScrollArea:t,type:n="hover",dir:i,scrollHideDelay:o=600,...s}=r,[a,l]=E.useState(null),[c,u]=E.useState(null),[d,f]=E.useState(null),[p,h]=E.useState(null),[m,w]=E.useState(null),[g,b]=E.useState(0),[R,k]=E.useState(0),[O,T]=E.useState(!1),[x,C]=E.useState(!1),N=_t(e,H=>l(H)),F=CE(i);return y.jsx(_$,{scope:t,type:n,dir:F,scrollHideDelay:o,scrollArea:a,viewport:c,onViewportChange:u,content:d,onContentChange:f,scrollbarX:p,onScrollbarXChange:h,scrollbarXEnabled:O,onScrollbarXEnabledChange:T,scrollbarY:m,onScrollbarYChange:w,scrollbarYEnabled:x,onScrollbarYEnabledChange:C,onCornerWidthChange:b,onCornerHeightChange:k,children:y.jsx(Je.div,{dir:F,...s,ref:N,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":R+"px",...r.style}})})});qA.displayName=rw;var GA="ScrollAreaViewport",HA=E.forwardRef((r,e)=>{const{__scopeScrollArea:t,children:n,nonce:i,...o}=r,s=ri(GA,t),a=E.useRef(null),l=_t(e,a,s.onViewportChange);return y.jsxs(y.Fragment,{children:[y.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),y.jsx(Je.div,{"data-radix-scroll-area-viewport":"",...o,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...r.style},children:y.jsx("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});HA.displayName=GA;var no="ScrollAreaScrollbar",zA=E.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=ri(no,r.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:s}=i,a=r.orientation==="horizontal";return E.useEffect(()=>(a?o(!0):s(!0),()=>{a?o(!1):s(!1)}),[a,o,s]),i.type==="hover"?y.jsx(E$,{...n,ref:e,forceMount:t}):i.type==="scroll"?y.jsx(w$,{...n,ref:e,forceMount:t}):i.type==="auto"?y.jsx(YA,{...n,ref:e,forceMount:t}):i.type==="always"?y.jsx(nw,{...n,ref:e}):null});zA.displayName=no;var E$=E.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=ri(no,r.__scopeScrollArea),[o,s]=E.useState(!1);return E.useEffect(()=>{const a=i.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),s(!0)},u=()=>{l=window.setTimeout(()=>s(!1),i.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",u),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",u)}}},[i.scrollArea,i.scrollHideDelay]),y.jsx(sn,{present:t||o,children:y.jsx(YA,{"data-state":o?"visible":"hidden",...n,ref:e})})}),w$=E.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=ri(no,r.__scopeScrollArea),o=r.orientation==="horizontal",s=Zv(()=>l("SCROLL_END"),100),[a,l]=b$("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return E.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,i.scrollHideDelay,l]),E.useEffect(()=>{const c=i.viewport,u=o?"scrollLeft":"scrollTop";if(c){let d=c[u];const f=()=>{const p=c[u];d!==p&&(l("SCROLL"),s()),d=p};return c.addEventListener("scroll",f),()=>c.removeEventListener("scroll",f)}},[i.viewport,o,l,s]),y.jsx(sn,{present:t||a!=="hidden",children:y.jsx(nw,{"data-state":a==="hidden"?"hidden":"visible",...n,ref:e,onPointerEnter:Me(r.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:Me(r.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),YA=E.forwardRef((r,e)=>{const t=ri(no,r.__scopeScrollArea),{forceMount:n,...i}=r,[o,s]=E.useState(!1),a=r.orientation==="horizontal",l=Zv(()=>{if(t.viewport){const c=t.viewport.offsetWidth<t.viewport.scrollWidth,u=t.viewport.offsetHeight<t.viewport.scrollHeight;s(a?c:u)}},10);return hc(t.viewport,l),hc(t.content,l),y.jsx(sn,{present:n||o,children:y.jsx(nw,{"data-state":o?"visible":"hidden",...i,ref:e})})}),nw=E.forwardRef((r,e)=>{const{orientation:t="vertical",...n}=r,i=ri(no,r.__scopeScrollArea),o=E.useRef(null),s=E.useRef(0),[a,l]=E.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=e1(a.viewport,a.content),u={...n,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:f=>o.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function d(f,p){return x$(f,s.current,a,p)}return t==="horizontal"?y.jsx(T$,{...u,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const f=i.viewport.scrollLeft,p=_R(f,a,i.dir);o.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:f=>{i.viewport&&(i.viewport.scrollLeft=f)},onDragScroll:f=>{i.viewport&&(i.viewport.scrollLeft=d(f,i.dir))}}):t==="vertical"?y.jsx(R$,{...u,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const f=i.viewport.scrollTop,p=_R(f,a);o.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:f=>{i.viewport&&(i.viewport.scrollTop=f)},onDragScroll:f=>{i.viewport&&(i.viewport.scrollTop=d(f))}}):null}),T$=E.forwardRef((r,e)=>{const{sizes:t,onSizesChange:n,...i}=r,o=ri(no,r.__scopeScrollArea),[s,a]=E.useState(),l=E.useRef(null),c=_t(e,l,o.onScrollbarXChange);return E.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),y.jsx(XA,{"data-orientation":"horizontal",...i,ref:c,sizes:t,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Qv(t)+"px",...r.style},onThumbPointerDown:u=>r.onThumbPointerDown(u.x),onDragScroll:u=>r.onDragScroll(u.x),onWheelScroll:(u,d)=>{if(o.viewport){const f=o.viewport.scrollLeft+u.deltaX;r.onWheelScroll(f),r1(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&o.viewport&&s&&n({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Kp(s.paddingLeft),paddingEnd:Kp(s.paddingRight)}})}})}),R$=E.forwardRef((r,e)=>{const{sizes:t,onSizesChange:n,...i}=r,o=ri(no,r.__scopeScrollArea),[s,a]=E.useState(),l=E.useRef(null),c=_t(e,l,o.onScrollbarYChange);return E.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),y.jsx(XA,{"data-orientation":"vertical",...i,ref:c,sizes:t,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Qv(t)+"px",...r.style},onThumbPointerDown:u=>r.onThumbPointerDown(u.y),onDragScroll:u=>r.onDragScroll(u.y),onWheelScroll:(u,d)=>{if(o.viewport){const f=o.viewport.scrollTop+u.deltaY;r.onWheelScroll(f),r1(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&o.viewport&&s&&n({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Kp(s.paddingTop),paddingEnd:Kp(s.paddingBottom)}})}})}),[C$,JA]=WA(no),XA=E.forwardRef((r,e)=>{const{__scopeScrollArea:t,sizes:n,hasThumb:i,onThumbChange:o,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:u,onResize:d,...f}=r,p=ri(no,t),[h,m]=E.useState(null),w=_t(e,N=>m(N)),g=E.useRef(null),b=E.useRef(""),R=p.viewport,k=n.content-n.viewport,O=Pr(u),T=Pr(l),x=Zv(d,10);function C(N){if(g.current){const F=N.clientX-g.current.left,H=N.clientY-g.current.top;c({x:F,y:H})}}return E.useEffect(()=>{const N=F=>{const H=F.target;(h==null?void 0:h.contains(H))&&O(F,k)};return document.addEventListener("wheel",N,{passive:!1}),()=>document.removeEventListener("wheel",N,{passive:!1})},[R,h,k,O]),E.useEffect(T,[n,T]),hc(h,x),hc(p.content,x),y.jsx(C$,{scope:t,scrollbar:h,hasThumb:i,onThumbChange:Pr(o),onThumbPointerUp:Pr(s),onThumbPositionChange:T,onThumbPointerDown:Pr(a),children:y.jsx(Je.div,{...f,ref:w,style:{position:"absolute",...f.style},onPointerDown:Me(r.onPointerDown,N=>{N.button===0&&(N.target.setPointerCapture(N.pointerId),g.current=h.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),C(N))}),onPointerMove:Me(r.onPointerMove,C),onPointerUp:Me(r.onPointerUp,N=>{const F=N.target;F.hasPointerCapture(N.pointerId)&&F.releasePointerCapture(N.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),g.current=null})})})}),Bp="ScrollAreaThumb",QA=E.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=JA(Bp,r.__scopeScrollArea);return y.jsx(sn,{present:t||i.hasThumb,children:y.jsx(k$,{ref:e,...n})})}),k$=E.forwardRef((r,e)=>{const{__scopeScrollArea:t,style:n,...i}=r,o=ri(Bp,t),s=JA(Bp,t),{onThumbPositionChange:a}=s,l=_t(e,d=>s.onThumbChange(d)),c=E.useRef(void 0),u=Zv(()=>{c.current&&(c.current(),c.current=void 0)},100);return E.useEffect(()=>{const d=o.viewport;if(d){const f=()=>{if(u(),!c.current){const p=O$(d,a);c.current=p,a()}};return a(),d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,u,a]),y.jsx(Je.div,{"data-state":s.hasThumb?"visible":"hidden",...i,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:Me(r.onPointerDownCapture,d=>{const p=d.target.getBoundingClientRect(),h=d.clientX-p.left,m=d.clientY-p.top;s.onThumbPointerDown({x:h,y:m})}),onPointerUp:Me(r.onPointerUp,s.onThumbPointerUp)})});QA.displayName=Bp;var iw="ScrollAreaCorner",ZA=E.forwardRef((r,e)=>{const t=ri(iw,r.__scopeScrollArea),n=!!(t.scrollbarX&&t.scrollbarY);return t.type!=="scroll"&&n?y.jsx(I$,{...r,ref:e}):null});ZA.displayName=iw;var I$=E.forwardRef((r,e)=>{const{__scopeScrollArea:t,...n}=r,i=ri(iw,t),[o,s]=E.useState(0),[a,l]=E.useState(0),c=!!(o&&a);return hc(i.scrollbarX,()=>{var d;const u=((d=i.scrollbarX)==null?void 0:d.offsetHeight)||0;i.onCornerHeightChange(u),l(u)}),hc(i.scrollbarY,()=>{var d;const u=((d=i.scrollbarY)==null?void 0:d.offsetWidth)||0;i.onCornerWidthChange(u),s(u)}),c?y.jsx(Je.div,{...n,ref:e,style:{width:o,height:a,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...r.style}}):null});function Kp(r){return r?parseInt(r,10):0}function e1(r,e){const t=r/e;return isNaN(t)?0:t}function Qv(r){const e=e1(r.viewport,r.content),t=r.scrollbar.paddingStart+r.scrollbar.paddingEnd,n=(r.scrollbar.size-t)*e;return Math.max(n,18)}function x$(r,e,t,n="ltr"){const i=Qv(t),o=i/2,s=e||o,a=i-s,l=t.scrollbar.paddingStart+s,c=t.scrollbar.size-t.scrollbar.paddingEnd-a,u=t.content-t.viewport,d=n==="ltr"?[0,u]:[u*-1,0];return t1([l,c],d)(r)}function _R(r,e,t="ltr"){const n=Qv(e),i=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,o=e.scrollbar.size-i,s=e.content-e.viewport,a=o-n,l=t==="ltr"?[0,s]:[s*-1,0],c=o$(r,l);return t1([0,s],[0,a])(c)}function t1(r,e){return t=>{if(r[0]===r[1]||e[0]===e[1])return e[0];const n=(e[1]-e[0])/(r[1]-r[0]);return e[0]+n*(t-r[0])}}function r1(r,e){return r>0&&r<e}var O$=(r,e=()=>{})=>{let t={left:r.scrollLeft,top:r.scrollTop},n=0;return function i(){const o={left:r.scrollLeft,top:r.scrollTop},s=t.left!==o.left,a=t.top!==o.top;(s||a)&&e(),t=o,n=window.requestAnimationFrame(i)}(),()=>window.cancelAnimationFrame(n)};function Zv(r,e){const t=Pr(r),n=E.useRef(0);return E.useEffect(()=>()=>window.clearTimeout(n.current),[]),E.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(t,e)},[t,e])}function hc(r,e){const t=Pr(e);Zn(()=>{let n=0;if(r){const i=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(t)});return i.observe(r),()=>{window.cancelAnimationFrame(n),i.unobserve(r)}}},[r,t])}var P$=qA,M$=HA,A$=ZA,D$="Separator",ER="horizontal",N$=["horizontal","vertical"],n1=E.forwardRef((r,e)=>{const{decorative:t,orientation:n=ER,...i}=r,o=L$(n)?n:ER,a=t?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return y.jsx(Je.div,{"data-orientation":o,...a,...i,ref:e})});n1.displayName=D$;function L$(r){return N$.includes(r)}var U$=n1,[em]=to("Tooltip",[Dc]),ow=Dc(),i1="TooltipProvider",j$=700,wR="tooltip.open",[F$,o1]=em(i1),s1=r=>{const{__scopeTooltip:e,delayDuration:t=j$,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:o}=r,s=E.useRef(!0),a=E.useRef(!1),l=E.useRef(0);return E.useEffect(()=>{const c=l.current;return()=>window.clearTimeout(c)},[]),y.jsx(F$,{scope:e,isOpenDelayedRef:s,delayDuration:t,onOpen:E.useCallback(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:E.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,n)},[n]),isPointerInTransitRef:a,onPointerInTransitChange:E.useCallback(c=>{a.current=c},[]),disableHoverableContent:i,children:o})};s1.displayName=i1;var a1="Tooltip",[Tte,tm]=em(a1),BS="TooltipTrigger",B$=E.forwardRef((r,e)=>{const{__scopeTooltip:t,...n}=r,i=tm(BS,t),o=o1(BS,t),s=ow(t),a=E.useRef(null),l=_t(e,a,i.onTriggerChange),c=E.useRef(!1),u=E.useRef(!1),d=E.useCallback(()=>c.current=!1,[]);return E.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),y.jsx(Hv,{asChild:!0,...s,children:y.jsx(Je.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:l,onPointerMove:Me(r.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),u.current=!0)}),onPointerLeave:Me(r.onPointerLeave,()=>{i.onTriggerLeave(),u.current=!1}),onPointerDown:Me(r.onPointerDown,()=>{i.open&&i.onClose(),c.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Me(r.onFocus,()=>{c.current||i.onOpen()}),onBlur:Me(r.onBlur,i.onClose),onClick:Me(r.onClick,i.onClose)})})});B$.displayName=BS;var K$="TooltipPortal",[Rte,V$]=em(K$,{forceMount:void 0}),pc="TooltipContent",$$=E.forwardRef((r,e)=>{const t=V$(pc,r.__scopeTooltip),{forceMount:n=t.forceMount,side:i="top",...o}=r,s=tm(pc,r.__scopeTooltip);return y.jsx(sn,{present:n||s.open,children:s.disableHoverableContent?y.jsx(l1,{side:i,...o,ref:e}):y.jsx(W$,{side:i,...o,ref:e})})}),W$=E.forwardRef((r,e)=>{const t=tm(pc,r.__scopeTooltip),n=o1(pc,r.__scopeTooltip),i=E.useRef(null),o=_t(e,i),[s,a]=E.useState(null),{trigger:l,onClose:c}=t,u=i.current,{onPointerInTransitChange:d}=n,f=E.useCallback(()=>{a(null),d(!1)},[d]),p=E.useCallback((h,m)=>{const w=h.currentTarget,g={x:h.clientX,y:h.clientY},b=Y$(g,w.getBoundingClientRect()),R=J$(g,b),k=X$(m.getBoundingClientRect()),O=Z$([...R,...k]);a(O),d(!0)},[d]);return E.useEffect(()=>()=>f(),[f]),E.useEffect(()=>{if(l&&u){const h=w=>p(w,u),m=w=>p(w,l);return l.addEventListener("pointerleave",h),u.addEventListener("pointerleave",m),()=>{l.removeEventListener("pointerleave",h),u.removeEventListener("pointerleave",m)}}},[l,u,p,f]),E.useEffect(()=>{if(s){const h=m=>{const w=m.target,g={x:m.clientX,y:m.clientY},b=(l==null?void 0:l.contains(w))||(u==null?void 0:u.contains(w)),R=!Q$(g,s);b?f():R&&(f(),c())};return document.addEventListener("pointermove",h),()=>document.removeEventListener("pointermove",h)}},[l,u,s,c,f]),y.jsx(l1,{...r,ref:o})}),[q$,G$]=em(a1,{isInside:!1}),H$=bK("TooltipContent"),l1=E.forwardRef((r,e)=>{const{__scopeTooltip:t,children:n,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:s,...a}=r,l=tm(pc,t),c=ow(t),{onClose:u}=l;return E.useEffect(()=>(document.addEventListener(wR,u),()=>document.removeEventListener(wR,u)),[u]),E.useEffect(()=>{if(l.trigger){const d=f=>{const p=f.target;p!=null&&p.contains(l.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]),y.jsx(sf,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:y.jsxs(GE,{"data-state":l.stateAttribute,...c,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[y.jsx(H$,{children:n}),y.jsx(q$,{scope:t,isInside:!0,children:y.jsx(kK,{id:l.contentId,role:"tooltip",children:i||n})})]})})});$$.displayName=pc;var c1="TooltipArrow",z$=E.forwardRef((r,e)=>{const{__scopeTooltip:t,...n}=r,i=ow(t);return G$(c1,t).isInside?null:y.jsx(HE,{...i,...n,ref:e})});z$.displayName=c1;function Y$(r,e){const t=Math.abs(e.top-r.y),n=Math.abs(e.bottom-r.y),i=Math.abs(e.right-r.x),o=Math.abs(e.left-r.x);switch(Math.min(t,n,i,o)){case o:return"left";case i:return"right";case t:return"top";case n:return"bottom";default:throw new Error("unreachable")}}function J$(r,e,t=5){const n=[];switch(e){case"top":n.push({x:r.x-t,y:r.y+t},{x:r.x+t,y:r.y+t});break;case"bottom":n.push({x:r.x-t,y:r.y-t},{x:r.x+t,y:r.y-t});break;case"left":n.push({x:r.x+t,y:r.y-t},{x:r.x+t,y:r.y+t});break;case"right":n.push({x:r.x-t,y:r.y-t},{x:r.x-t,y:r.y+t});break}return n}function X$(r){const{top:e,right:t,bottom:n,left:i}=r;return[{x:i,y:e},{x:t,y:e},{x:t,y:n},{x:i,y:n}]}function Q$(r,e){const{x:t,y:n}=r;let i=!1;for(let o=0,s=e.length-1;o<e.length;s=o++){const a=e[o],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>n!=f>n&&t<(d-c)*(n-u)/(f-u)+c&&(i=!i)}return i}function Z$(r){const e=r.slice();return e.sort((t,n)=>t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0),eW(e)}function eW(r){if(r.length<=1)return r.slice();const e=[];for(let n=0;n<r.length;n++){const i=r[n];for(;e.length>=2;){const o=e[e.length-1],s=e[e.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))e.pop();else break}e.push(i)}e.pop();const t=[];for(let n=r.length-1;n>=0;n--){const i=r[n];for(;t.length>=2;){const o=t[t.length-1],s=t[t.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}var tW=s1;function u1(r){var e,t,n="";if(typeof r=="string"||typeof r=="number")n+=r;else if(typeof r=="object")if(Array.isArray(r)){var i=r.length;for(e=0;e<i;e++)r[e]&&(t=u1(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function d1(){for(var r,e,t=0,n="",i=arguments.length;t<i;t++)(r=arguments[t])&&(e=u1(r))&&(n&&(n+=" "),n+=e);return n}const rW=(r,e)=>{const t=new Array(r.length+e.length);for(let n=0;n<r.length;n++)t[n]=r[n];for(let n=0;n<e.length;n++)t[r.length+n]=e[n];return t},nW=(r,e)=>({classGroupId:r,validator:e}),f1=(r=new Map,e=null,t)=>({nextPart:r,validators:e,classGroupId:t}),Vp="-",TR=[],iW="arbitrary..",oW=r=>{const e=aW(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return sW(s);const a=s.split(Vp),l=a[0]===""&&a.length>1?1:0;return h1(a,l,e)},getConflictingClassGroupIds:(s,a)=>{if(a){const l=n[s],c=t[s];return l?c?rW(c,l):l:c||TR}return t[s]||TR}}},h1=(r,e,t)=>{if(r.length-e===0)return t.classGroupId;const i=r[e],o=t.nextPart.get(i);if(o){const c=h1(r,e+1,o);if(c)return c}const s=t.validators;if(s===null)return;const a=e===0?r.join(Vp):r.slice(e).join(Vp),l=s.length;for(let c=0;c<l;c++){const u=s[c];if(u.validator(a))return u.classGroupId}},sW=r=>r.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=r.slice(1,-1),t=e.indexOf(":"),n=e.slice(0,t);return n?iW+n:void 0})(),aW=r=>{const{theme:e,classGroups:t}=r;return lW(t,e)},lW=(r,e)=>{const t=f1();for(const n in r){const i=r[n];sw(i,t,n,e)}return t},sw=(r,e,t,n)=>{const i=r.length;for(let o=0;o<i;o++){const s=r[o];cW(s,e,t,n)}},cW=(r,e,t,n)=>{if(typeof r=="string"){uW(r,e,t);return}if(typeof r=="function"){dW(r,e,t,n);return}fW(r,e,t,n)},uW=(r,e,t)=>{const n=r===""?e:p1(e,r);n.classGroupId=t},dW=(r,e,t,n)=>{if(hW(r)){sw(r(n),e,t,n);return}e.validators===null&&(e.validators=[]),e.validators.push(nW(t,r))},fW=(r,e,t,n)=>{const i=Object.entries(r),o=i.length;for(let s=0;s<o;s++){const[a,l]=i[s];sw(l,p1(e,a),t,n)}},p1=(r,e)=>{let t=r;const n=e.split(Vp),i=n.length;for(let o=0;o<i;o++){const s=n[o];let a=t.nextPart.get(s);a||(a=f1(),t.nextPart.set(s,a)),t=a}return t},hW=r=>"isThemeGetter"in r&&r.isThemeGetter===!0,pW=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=Object.create(null),n=Object.create(null);const i=(o,s)=>{t[o]=s,e++,e>r&&(e=0,n=t,t=Object.create(null))};return{get(o){let s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set(o,s){o in t?t[o]=s:i(o,s)}}},KS="!",RR=":",vW=[],CR=(r,e,t,n,i)=>({modifiers:r,hasImportantModifier:e,baseClassName:t,maybePostfixModifierPosition:n,isExternal:i}),mW=r=>{const{prefix:e,experimentalParseClassName:t}=r;let n=i=>{const o=[];let s=0,a=0,l=0,c;const u=i.length;for(let m=0;m<u;m++){const w=i[m];if(s===0&&a===0){if(w===RR){o.push(i.slice(l,m)),l=m+1;continue}if(w==="/"){c=m;continue}}w==="["?s++:w==="]"?s--:w==="("?a++:w===")"&&a--}const d=o.length===0?i:i.slice(l);let f=d,p=!1;d.endsWith(KS)?(f=d.slice(0,-1),p=!0):d.startsWith(KS)&&(f=d.slice(1),p=!0);const h=c&&c>l?c-l:void 0;return CR(o,p,f,h)};if(e){const i=e+RR,o=n;n=s=>s.startsWith(i)?o(s.slice(i.length)):CR(vW,!1,s,void 0,!0)}if(t){const i=n;n=o=>t({className:o,parseClassName:i})}return n},gW=r=>{const e=new Map;return r.orderSensitiveModifiers.forEach((t,n)=>{e.set(t,1e6+n)}),t=>{const n=[];let i=[];for(let o=0;o<t.length;o++){const s=t[o],a=s[0]==="[",l=e.has(s);a||l?(i.length>0&&(i.sort(),n.push(...i),i=[]),n.push(s)):i.push(s)}return i.length>0&&(i.sort(),n.push(...i)),n}},yW=r=>({cache:pW(r.cacheSize),parseClassName:mW(r),sortModifiers:gW(r),...oW(r)}),SW=/\s+/,bW=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:i,sortModifiers:o}=e,s=[],a=r.trim().split(SW);let l="";for(let c=a.length-1;c>=0;c-=1){const u=a[c],{isExternal:d,modifiers:f,hasImportantModifier:p,baseClassName:h,maybePostfixModifierPosition:m}=t(u);if(d){l=u+(l.length>0?" "+l:l);continue}let w=!!m,g=n(w?h.substring(0,m):h);if(!g){if(!w){l=u+(l.length>0?" "+l:l);continue}if(g=n(h),!g){l=u+(l.length>0?" "+l:l);continue}w=!1}const b=f.length===0?"":f.length===1?f[0]:o(f).join(":"),R=p?b+KS:b,k=R+g;if(s.indexOf(k)>-1)continue;s.push(k);const O=i(g,w);for(let T=0;T<O.length;++T){const x=O[T];s.push(R+x)}l=u+(l.length>0?" "+l:l)}return l},_W=(...r)=>{let e=0,t,n,i="";for(;e<r.length;)(t=r[e++])&&(n=v1(t))&&(i&&(i+=" "),i+=n);return i},v1=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=v1(r[n]))&&(t&&(t+=" "),t+=e);return t},EW=(r,...e)=>{let t,n,i,o;const s=l=>{const c=e.reduce((u,d)=>d(u),r());return t=yW(c),n=t.cache.get,i=t.cache.set,o=a,a(l)},a=l=>{const c=n(l);if(c)return c;const u=bW(l,t);return i(l,u),u};return o=s,(...l)=>o(_W(...l))},wW=[],sr=r=>{const e=t=>t[r]||wW;return e.isThemeGetter=!0,e},m1=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,g1=/^\((?:(\w[\w-]*):)?(.+)\)$/i,TW=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,RW=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,CW=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,kW=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,IW=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,xW=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,qo=r=>TW.test(r),Ze=r=>!!r&&!Number.isNaN(Number(r)),Go=r=>!!r&&Number.isInteger(Number(r)),Ag=r=>r.endsWith("%")&&Ze(r.slice(0,-1)),ao=r=>RW.test(r),y1=()=>!0,OW=r=>CW.test(r)&&!kW.test(r),aw=()=>!1,PW=r=>IW.test(r),MW=r=>xW.test(r),AW=r=>!Oe(r)&&!Pe(r),DW=r=>$s(r,_1,aw),Oe=r=>m1.test(r),Xs=r=>$s(r,E1,OW),kR=r=>$s(r,VW,Ze),NW=r=>$s(r,T1,y1),LW=r=>$s(r,w1,aw),IR=r=>$s(r,S1,aw),UW=r=>$s(r,b1,MW),rh=r=>$s(r,R1,PW),Pe=r=>g1.test(r),ou=r=>Ya(r,E1),jW=r=>Ya(r,w1),xR=r=>Ya(r,S1),FW=r=>Ya(r,_1),BW=r=>Ya(r,b1),nh=r=>Ya(r,R1,!0),KW=r=>Ya(r,T1,!0),$s=(r,e,t)=>{const n=m1.exec(r);return n?n[1]?e(n[1]):t(n[2]):!1},Ya=(r,e,t=!1)=>{const n=g1.exec(r);return n?n[1]?e(n[1]):t:!1},S1=r=>r==="position"||r==="percentage",b1=r=>r==="image"||r==="url",_1=r=>r==="length"||r==="size"||r==="bg-size",E1=r=>r==="length",VW=r=>r==="number",w1=r=>r==="family-name",T1=r=>r==="number"||r==="weight",R1=r=>r==="shadow",$W=()=>{const r=sr("color"),e=sr("font"),t=sr("text"),n=sr("font-weight"),i=sr("tracking"),o=sr("leading"),s=sr("breakpoint"),a=sr("container"),l=sr("spacing"),c=sr("radius"),u=sr("shadow"),d=sr("inset-shadow"),f=sr("text-shadow"),p=sr("drop-shadow"),h=sr("blur"),m=sr("perspective"),w=sr("aspect"),g=sr("ease"),b=sr("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],O=()=>[...k(),Pe,Oe],T=()=>["auto","hidden","clip","visible","scroll"],x=()=>["auto","contain","none"],C=()=>[Pe,Oe,l],N=()=>[qo,"full","auto",...C()],F=()=>[Go,"none","subgrid",Pe,Oe],H=()=>["auto",{span:["full",Go,Pe,Oe]},Go,Pe,Oe],ie=()=>[Go,"auto",Pe,Oe],$=()=>["auto","min","max","fr",Pe,Oe],X=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],oe=()=>["start","end","center","stretch","center-safe","end-safe"],re=()=>["auto",...C()],ae=()=>[qo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],q=()=>[qo,"screen","full","dvw","lvw","svw","min","max","fit",...C()],z=()=>[qo,"screen","full","lh","dvh","lvh","svh","min","max","fit",...C()],Q=()=>[r,Pe,Oe],Ie=()=>[...k(),xR,IR,{position:[Pe,Oe]}],Y=()=>["no-repeat",{repeat:["","x","y","space","round"]}],le=()=>["auto","cover","contain",FW,DW,{size:[Pe,Oe]}],B=()=>[Ag,ou,Xs],W=()=>["","none","full",c,Pe,Oe],A=()=>["",Ze,ou,Xs],D=()=>["solid","dashed","dotted","double"],P=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],M=()=>[Ze,Ag,xR,IR],I=()=>["","none",h,Pe,Oe],j=()=>["none",Ze,Pe,Oe],U=()=>["none",Ze,Pe,Oe],K=()=>[Ze,Pe,Oe],G=()=>[qo,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ao],breakpoint:[ao],color:[y1],container:[ao],"drop-shadow":[ao],ease:["in","out","in-out"],font:[AW],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ao],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ao],shadow:[ao],spacing:["px",Ze],text:[ao],"text-shadow":[ao],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",qo,Oe,Pe,w]}],container:["container"],columns:[{columns:[Ze,Oe,Pe,a]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:O()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:x()}],"overscroll-x":[{"overscroll-x":x()}],"overscroll-y":[{"overscroll-y":x()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{"inset-s":N(),start:N()}],end:[{"inset-e":N(),end:N()}],"inset-bs":[{"inset-bs":N()}],"inset-be":[{"inset-be":N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[Go,"auto",Pe,Oe]}],basis:[{basis:[qo,"full","auto",a,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ze,qo,"auto","initial","none",Oe]}],grow:[{grow:["",Ze,Pe,Oe]}],shrink:[{shrink:["",Ze,Pe,Oe]}],order:[{order:[Go,"first","last","none",Pe,Oe]}],"grid-cols":[{"grid-cols":F()}],"col-start-end":[{col:H()}],"col-start":[{"col-start":ie()}],"col-end":[{"col-end":ie()}],"grid-rows":[{"grid-rows":F()}],"row-start-end":[{row:H()}],"row-start":[{"row-start":ie()}],"row-end":[{"row-end":ie()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":$()}],"auto-rows":[{"auto-rows":$()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...X(),"normal"]}],"justify-items":[{"justify-items":[...oe(),"normal"]}],"justify-self":[{"justify-self":["auto",...oe()]}],"align-content":[{content:["normal",...X()]}],"align-items":[{items:[...oe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...oe(),{baseline:["","last"]}]}],"place-content":[{"place-content":X()}],"place-items":[{"place-items":[...oe(),"baseline"]}],"place-self":[{"place-self":["auto",...oe()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pbs:[{pbs:C()}],pbe:[{pbe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:re()}],mx:[{mx:re()}],my:[{my:re()}],ms:[{ms:re()}],me:[{me:re()}],mbs:[{mbs:re()}],mbe:[{mbe:re()}],mt:[{mt:re()}],mr:[{mr:re()}],mb:[{mb:re()}],ml:[{ml:re()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:ae()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...z()]}],"min-block-size":[{"min-block":["auto",...z()]}],"max-block-size":[{"max-block":["none",...z()]}],w:[{w:[a,"screen",...ae()]}],"min-w":[{"min-w":[a,"screen","none",...ae()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...ae()]}],h:[{h:["screen","lh",...ae()]}],"min-h":[{"min-h":["screen","lh","none",...ae()]}],"max-h":[{"max-h":["screen","lh",...ae()]}],"font-size":[{text:["base",t,ou,Xs]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,KW,NW]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ag,Oe]}],"font-family":[{font:[jW,LW,e]}],"font-features":[{"font-features":[Oe]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Pe,Oe]}],"line-clamp":[{"line-clamp":[Ze,"none",Pe,kR]}],leading:[{leading:[o,...C()]}],"list-image":[{"list-image":["none",Pe,Oe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Pe,Oe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:Q()}],"text-color":[{text:Q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...D(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ze,"from-font","auto",Pe,Xs]}],"text-decoration-color":[{decoration:Q()}],"underline-offset":[{"underline-offset":[Ze,"auto",Pe,Oe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Pe,Oe]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Pe,Oe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Ie()}],"bg-repeat":[{bg:Y()}],"bg-size":[{bg:le()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Go,Pe,Oe],radial:["",Pe,Oe],conic:[Go,Pe,Oe]},BW,UW]}],"bg-color":[{bg:Q()}],"gradient-from-pos":[{from:B()}],"gradient-via-pos":[{via:B()}],"gradient-to-pos":[{to:B()}],"gradient-from":[{from:Q()}],"gradient-via":[{via:Q()}],"gradient-to":[{to:Q()}],rounded:[{rounded:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:A()}],"border-w-x":[{"border-x":A()}],"border-w-y":[{"border-y":A()}],"border-w-s":[{"border-s":A()}],"border-w-e":[{"border-e":A()}],"border-w-bs":[{"border-bs":A()}],"border-w-be":[{"border-be":A()}],"border-w-t":[{"border-t":A()}],"border-w-r":[{"border-r":A()}],"border-w-b":[{"border-b":A()}],"border-w-l":[{"border-l":A()}],"divide-x":[{"divide-x":A()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":A()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...D(),"hidden","none"]}],"divide-style":[{divide:[...D(),"hidden","none"]}],"border-color":[{border:Q()}],"border-color-x":[{"border-x":Q()}],"border-color-y":[{"border-y":Q()}],"border-color-s":[{"border-s":Q()}],"border-color-e":[{"border-e":Q()}],"border-color-bs":[{"border-bs":Q()}],"border-color-be":[{"border-be":Q()}],"border-color-t":[{"border-t":Q()}],"border-color-r":[{"border-r":Q()}],"border-color-b":[{"border-b":Q()}],"border-color-l":[{"border-l":Q()}],"divide-color":[{divide:Q()}],"outline-style":[{outline:[...D(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ze,Pe,Oe]}],"outline-w":[{outline:["",Ze,ou,Xs]}],"outline-color":[{outline:Q()}],shadow:[{shadow:["","none",u,nh,rh]}],"shadow-color":[{shadow:Q()}],"inset-shadow":[{"inset-shadow":["none",d,nh,rh]}],"inset-shadow-color":[{"inset-shadow":Q()}],"ring-w":[{ring:A()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:Q()}],"ring-offset-w":[{"ring-offset":[Ze,Xs]}],"ring-offset-color":[{"ring-offset":Q()}],"inset-ring-w":[{"inset-ring":A()}],"inset-ring-color":[{"inset-ring":Q()}],"text-shadow":[{"text-shadow":["none",f,nh,rh]}],"text-shadow-color":[{"text-shadow":Q()}],opacity:[{opacity:[Ze,Pe,Oe]}],"mix-blend":[{"mix-blend":[...P(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":P()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ze]}],"mask-image-linear-from-pos":[{"mask-linear-from":M()}],"mask-image-linear-to-pos":[{"mask-linear-to":M()}],"mask-image-linear-from-color":[{"mask-linear-from":Q()}],"mask-image-linear-to-color":[{"mask-linear-to":Q()}],"mask-image-t-from-pos":[{"mask-t-from":M()}],"mask-image-t-to-pos":[{"mask-t-to":M()}],"mask-image-t-from-color":[{"mask-t-from":Q()}],"mask-image-t-to-color":[{"mask-t-to":Q()}],"mask-image-r-from-pos":[{"mask-r-from":M()}],"mask-image-r-to-pos":[{"mask-r-to":M()}],"mask-image-r-from-color":[{"mask-r-from":Q()}],"mask-image-r-to-color":[{"mask-r-to":Q()}],"mask-image-b-from-pos":[{"mask-b-from":M()}],"mask-image-b-to-pos":[{"mask-b-to":M()}],"mask-image-b-from-color":[{"mask-b-from":Q()}],"mask-image-b-to-color":[{"mask-b-to":Q()}],"mask-image-l-from-pos":[{"mask-l-from":M()}],"mask-image-l-to-pos":[{"mask-l-to":M()}],"mask-image-l-from-color":[{"mask-l-from":Q()}],"mask-image-l-to-color":[{"mask-l-to":Q()}],"mask-image-x-from-pos":[{"mask-x-from":M()}],"mask-image-x-to-pos":[{"mask-x-to":M()}],"mask-image-x-from-color":[{"mask-x-from":Q()}],"mask-image-x-to-color":[{"mask-x-to":Q()}],"mask-image-y-from-pos":[{"mask-y-from":M()}],"mask-image-y-to-pos":[{"mask-y-to":M()}],"mask-image-y-from-color":[{"mask-y-from":Q()}],"mask-image-y-to-color":[{"mask-y-to":Q()}],"mask-image-radial":[{"mask-radial":[Pe,Oe]}],"mask-image-radial-from-pos":[{"mask-radial-from":M()}],"mask-image-radial-to-pos":[{"mask-radial-to":M()}],"mask-image-radial-from-color":[{"mask-radial-from":Q()}],"mask-image-radial-to-color":[{"mask-radial-to":Q()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[Ze]}],"mask-image-conic-from-pos":[{"mask-conic-from":M()}],"mask-image-conic-to-pos":[{"mask-conic-to":M()}],"mask-image-conic-from-color":[{"mask-conic-from":Q()}],"mask-image-conic-to-color":[{"mask-conic-to":Q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Ie()}],"mask-repeat":[{mask:Y()}],"mask-size":[{mask:le()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Pe,Oe]}],filter:[{filter:["","none",Pe,Oe]}],blur:[{blur:I()}],brightness:[{brightness:[Ze,Pe,Oe]}],contrast:[{contrast:[Ze,Pe,Oe]}],"drop-shadow":[{"drop-shadow":["","none",p,nh,rh]}],"drop-shadow-color":[{"drop-shadow":Q()}],grayscale:[{grayscale:["",Ze,Pe,Oe]}],"hue-rotate":[{"hue-rotate":[Ze,Pe,Oe]}],invert:[{invert:["",Ze,Pe,Oe]}],saturate:[{saturate:[Ze,Pe,Oe]}],sepia:[{sepia:["",Ze,Pe,Oe]}],"backdrop-filter":[{"backdrop-filter":["","none",Pe,Oe]}],"backdrop-blur":[{"backdrop-blur":I()}],"backdrop-brightness":[{"backdrop-brightness":[Ze,Pe,Oe]}],"backdrop-contrast":[{"backdrop-contrast":[Ze,Pe,Oe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ze,Pe,Oe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ze,Pe,Oe]}],"backdrop-invert":[{"backdrop-invert":["",Ze,Pe,Oe]}],"backdrop-opacity":[{"backdrop-opacity":[Ze,Pe,Oe]}],"backdrop-saturate":[{"backdrop-saturate":[Ze,Pe,Oe]}],"backdrop-sepia":[{"backdrop-sepia":["",Ze,Pe,Oe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Pe,Oe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ze,"initial",Pe,Oe]}],ease:[{ease:["linear","initial",g,Pe,Oe]}],delay:[{delay:[Ze,Pe,Oe]}],animate:[{animate:["none",b,Pe,Oe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,Pe,Oe]}],"perspective-origin":[{"perspective-origin":O()}],rotate:[{rotate:j()}],"rotate-x":[{"rotate-x":j()}],"rotate-y":[{"rotate-y":j()}],"rotate-z":[{"rotate-z":j()}],scale:[{scale:U()}],"scale-x":[{"scale-x":U()}],"scale-y":[{"scale-y":U()}],"scale-z":[{"scale-z":U()}],"scale-3d":["scale-3d"],skew:[{skew:K()}],"skew-x":[{"skew-x":K()}],"skew-y":[{"skew-y":K()}],transform:[{transform:[Pe,Oe,"","none","gpu","cpu"]}],"transform-origin":[{origin:O()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:G()}],"translate-x":[{"translate-x":G()}],"translate-y":[{"translate-y":G()}],"translate-z":[{"translate-z":G()}],"translate-none":["translate-none"],accent:[{accent:Q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:Q()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Pe,Oe]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mbs":[{"scroll-mbs":C()}],"scroll-mbe":[{"scroll-mbe":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pbs":[{"scroll-pbs":C()}],"scroll-pbe":[{"scroll-pbe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Pe,Oe]}],fill:[{fill:["none",...Q()]}],"stroke-w":[{stroke:[Ze,ou,Xs,kR]}],stroke:[{stroke:["none",...Q()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},WW=EW($W);function Ue(...r){return WW(d1(r))}function OR({delayDuration:r=0,...e}){return y.jsx(tW,{"data-slot":"tooltip-provider",delayDuration:r,...e})}function PR(r,e,t,n,i,o,s){try{var a=r[o](s),l=a.value}catch(c){return void t(c)}a.done?e(l):Promise.resolve(l).then(n,i)}function _(r){return function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function s(l){PR(o,n,i,s,a,"next",l)}function a(l){PR(o,n,i,s,a,"throw",l)}s(void 0)})}}function Ad(r){"@babel/helpers - typeof";return Ad=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ad(r)}function qW(r,e){if(Ad(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(Ad(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function GW(r){var e=qW(r,"string");return Ad(e)=="symbol"?e:e+""}function v(r,e,t){return(e=GW(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var C1={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(wi,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],o={},s=null;function a(m,w){var g=m[w];if(typeof g.bind=="function")return g.bind(m);try{return Function.prototype.bind.call(g,m)}catch{return function(){return Function.prototype.apply.apply(g,[m,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(m){return m==="debug"&&(m="log"),typeof console===t?!1:m==="trace"&&n?l:console[m]!==void 0?a(console,m):console.log!==void 0?a(console,"log"):e}function u(){for(var m=this.getLevel(),w=0;w<i.length;w++){var g=i[w];this[g]=w<m?e:this.methodFactory(g,m,this.name)}if(this.log=this.debug,typeof console===t&&m<this.levels.SILENT)return"No console available for logging"}function d(m){return function(){typeof console!==t&&(u.call(this),this[m].apply(this,arguments))}}function f(m,w,g){return c(m)||d.apply(this,arguments)}function p(m,w){var g=this,b,R,k,O="loglevel";typeof m=="string"?O+=":"+m:typeof m=="symbol"&&(O=void 0);function T(H){var ie=(i[H]||"silent").toUpperCase();if(!(typeof window===t||!O)){try{window.localStorage[O]=ie;return}catch{}try{window.document.cookie=encodeURIComponent(O)+"="+ie+";"}catch{}}}function x(){var H;if(!(typeof window===t||!O)){try{H=window.localStorage[O]}catch{}if(typeof H===t)try{var ie=window.document.cookie,$=encodeURIComponent(O),X=ie.indexOf($+"=");X!==-1&&(H=/^([^;]+)/.exec(ie.slice(X+$.length+1))[1])}catch{}return g.levels[H]===void 0&&(H=void 0),H}}function C(){if(!(typeof window===t||!O)){try{window.localStorage.removeItem(O)}catch{}try{window.document.cookie=encodeURIComponent(O)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(H){var ie=H;if(typeof ie=="string"&&g.levels[ie.toUpperCase()]!==void 0&&(ie=g.levels[ie.toUpperCase()]),typeof ie=="number"&&ie>=0&&ie<=g.levels.SILENT)return ie;throw new TypeError("log.setLevel() called with invalid level: "+H)}g.name=m,g.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},g.methodFactory=w||f,g.getLevel=function(){return k??R??b},g.setLevel=function(H,ie){return k=N(H),ie!==!1&&T(k),u.call(g)},g.setDefaultLevel=function(H){R=N(H),x()||g.setLevel(H,!1)},g.resetLevel=function(){k=null,C(),u.call(g)},g.enableAll=function(H){g.setLevel(g.levels.TRACE,H)},g.disableAll=function(H){g.setLevel(g.levels.SILENT,H)},g.rebuild=function(){if(s!==g&&(b=N(s.getLevel())),u.call(g),s===g)for(var H in o)o[H].rebuild()},b=N(s?s.getLevel():"WARN");var F=x();F!=null&&(k=N(F)),u.call(g)}s=new p,s.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var g=o[w];return g||(g=o[w]=new p(w,s.methodFactory)),g};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return o},s.default=s,s})})(C1);var HW=C1.exports;const Dd=Ka(HW);var k1="matrix";Dd.methodFactory=function(r,e,t){return function(){for(var n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];this.prefix&&i.unshift(this.prefix);var s=r==="error"||r==="warn"||r==="trace"||r==="info"||r==="debug";return s?console[r](...i):console.log(...i)}};function I1(r){var e=r;e.getChild=e.withPrefix=function(t){var n=this.prefix||"";return zW(n+t)}}function zW(r){var e=Dd.getLogger("".concat(k1,"-").concat(r));return e.prefix!==r&&(I1(e),e.prefix=r,e.setLevel(Dd.levels.DEBUG,!1)),e}var S=Dd.getLogger(k1);S.setLevel(Dd.levels.DEBUG,!1);I1(S);class Cte{constructor(e,t){this.parent=e,v(this,"name",void 0),this.name=t+":"}trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.trace(this.name,...t)}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.debug(this.name,...t)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.info(this.name,...t)}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.warn(this.name,...t)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.error(this.name,...t)}}const YW="l",JW="rn",XW={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:YW,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:JW,"ⅿ":"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 x1=XW;function QW(r){return r.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}var ZW=RegExp(Object.keys(x1).map(QW).join("|"),"g");function eq(r){return x1[r]}function tq(r){return r.replace(ZW,eq)}var rq=tq;const nq=Ka(rq);var rm={exports:{}},O1={};function ei(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.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))}var iq=ei;ei.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};ei.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};ei.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};ei.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};ei.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};ei.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};ei.prototype.start=ei.prototype.try;ei.prototype.errors=function(){return this._errors};ei.prototype.attempts=function(){return this._attempts};ei.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(r[o]||0)+1;r[o]=s,s>=t&&(e=i,t=s)}return e};(function(r){var e=iq;r.operation=function(t){var n=r.timeouts(t);return new e(n,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},r.timeouts=function(t){if(t instanceof Array)return[].concat(t);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in t)n[i]=t[i];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],s=0;s<n.retries;s++)o.push(this.createTimeout(s,n));return t&&t.forever&&!o.length&&o.push(this.createTimeout(s,n)),o.sort(function(a,l){return a-l}),o},r.createTimeout=function(t,n){var i=n.randomize?Math.random()+1:1,o=Math.round(i*Math.max(n.minTimeout,1)*Math.pow(n.factor,t));return o=Math.min(o,n.maxTimeout),o},r.wrap=function(t,n,i){if(n instanceof Array&&(i=n,n=null),!i){i=[];for(var o in t)typeof t[o]=="function"&&i.push(o)}for(var s=0;s<i.length;s++){var a=i[s],l=t[a];t[a]=(function(u){var d=r.operation(n),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){d.retry(h)||(h&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){u.apply(t,f)})}).bind(t,l),t[a].options=n}}})(O1);var oq=O1;const sq=oq,aq=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class P1 extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const lq=(r,e,t)=>{const n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},cq=r=>aq.includes(r),M1=(r,e)=>new Promise((t,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};const i=sq.operation(e);i.attempt(async o=>{try{t(await r(o))}catch(s){if(!(s instanceof Error)){n(new TypeError(`Non-error was thrown: "${s}". You should only throw errors.`));return}if(s instanceof P1)i.stop(),n(s.originalError);else if(s instanceof TypeError&&!cq(s.message))i.stop(),n(s);else{lq(s,o,e);try{await e.onFailedAttempt(s)}catch(a){n(a);return}i.retry(s)||n(i.mainError())}}})});rm.exports=M1;rm.exports.default=M1;rm.exports.AbortError=P1;var uq=rm.exports;const A1=Ka(uq);let nm=class{constructor(e,t){if(this.stable=e,this.unstable=t,!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(){var e=[this.name],t=this.altName;return t&&e.push(t),e}matches(e){return this.name===e||this.altName===e}findIn(e){var t=void 0;return this.name&&(t=e==null?void 0:e[this.name]),!t&&this.altName&&(t=e==null?void 0:e[this.altName]),t}includedIn(e){var t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}};class im extends nm{constructor(){super(...arguments),v(this,"preferUnstable",!1)}setPreferUnstable(e){this.preferUnstable=e}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}}let Ft=class extends nm{constructor(e,t){if(super(e,t),!this.unstable)throw new Error("Unstable value must be supplied")}get name(){return this.unstable}get altName(){return this.stable}};var ln={},om={},ff={};Object.defineProperty(ff,"__esModule",{value:!0});ff.NamespacedMap=void 0;function dq(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=fq(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
270
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function fq(r,e){if(r){if(typeof r=="string")return MR(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return MR(r,e)}}function MR(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function hq(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function pq(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function vq(r,e,t){return e&&pq(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}function mq(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var gq=function(){function r(e){if(hq(this,r),mq(this,"internalMap",new Map),e){var t=dq(e),n;try{for(t.s();!(n=t.n()).done;){var i=n.value;this.set(i[0],i[1])}}catch(o){t.e(o)}finally{t.f()}}}return vq(r,[{key:"get",value:function(t){return t.name&&this.internalMap.has(t.name)?this.internalMap.get(t.name):t.altName&&this.internalMap.has(t.altName)?this.internalMap.get(t.altName):null}},{key:"set",value:function(t,n){t.name&&this.internalMap.set(t.name,n),t.altName&&this.internalMap.set(t.altName,n)}},{key:"has",value:function(t){return!!this.get(t)}},{key:"delete",value:function(t){t.name&&this.internalMap.delete(t.name),t.altName&&this.internalMap.delete(t.altName)}},{key:"hasNamespaced",value:function(t){return this.internalMap.has(t)}},{key:"getNamespaced",value:function(t){return this.internalMap.get(t)}}]),r}();ff.NamespacedMap=gq;var jo={};function VS(r){"@babel/helpers - typeof";return VS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},VS(r)}Object.defineProperty(jo,"__esModule",{value:!0});jo.InvalidEventError=void 0;function yq(r,e,t){return Object.defineProperty(r,"prototype",{writable:!1}),r}function Sq(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function bq(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&Nd(r,e)}function _q(r){var e=D1();return function(){var n=Ld(r),i;if(e){var o=Ld(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return Eq(this,i)}}function Eq(r,e){if(e&&(VS(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return wq(r)}function wq(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function $S(r){var e=typeof Map=="function"?new Map:void 0;return $S=function(n){if(n===null||!Tq(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(typeof e<"u"){if(e.has(n))return e.get(n);e.set(n,i)}function i(){return Bh(n,arguments,Ld(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Nd(i,n)},$S(r)}function Bh(r,e,t){return D1()?Bh=Reflect.construct:Bh=function(i,o,s){var a=[null];a.push.apply(a,o);var l=Function.bind.apply(i,a),c=new l;return s&&Nd(c,s.prototype),c},Bh.apply(null,arguments)}function D1(){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 Tq(r){return Function.toString.call(r).indexOf("[native code]")!==-1}function Nd(r,e){return Nd=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},Nd(r,e)}function Ld(r){return Ld=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Ld(r)}var Rq=function(r){bq(t,r);var e=_q(t);function t(n){return Sq(this,t),e.call(this,n)}return yq(t)}($S(Error));jo.InvalidEventError=Rq;var Nc={},io={},Ws={};Object.defineProperty(Ws,"__esModule",{value:!0});Ws.ExtensibleEvent=void 0;function Cq(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function kq(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function Iq(r,e,t){return e&&kq(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}var xq=function(){function r(e){Cq(this,r),this.wireFormat=e}return Iq(r,[{key:"wireContent",get:function(){return this.wireFormat.content}}]),r}();Ws.ExtensibleEvent=xq;var hf={};Object.defineProperty(hf,"__esModule",{value:!0});hf.isOptionalAString=Oq;hf.isProvided=N1;function Oq(r){return N1(r)&&typeof r=="string"}function N1(r){return r!=null}var Xt={},ki={};function WS(r){"@babel/helpers - typeof";return WS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},WS(r)}Object.defineProperty(ki,"__esModule",{value:!0});ki.UnstableValue=ki.NamespacedValue=void 0;function Pq(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&qS(r,e)}function qS(r,e){return qS=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},qS(r,e)}function Mq(r){var e=Nq();return function(){var n=$p(r),i;if(e){var o=$p(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return Aq(this,i)}}function Aq(r,e){if(e&&(WS(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Dq(r)}function Dq(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function Nq(){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 $p(r){return $p=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},$p(r)}function L1(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function Lq(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function U1(r,e,t){return e&&Lq(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}var j1=function(){function r(e,t){if(L1(this,r),this.stable=e,this.unstable=t,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}return U1(r,[{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(t){return!!this.name&&this.name===t||!!this.altName&&this.altName===t}},{key:"findIn",value:function(t){var n;return this.name&&(n=t==null?void 0:t[this.name]),!n&&this.altName&&(n=t==null?void 0:t[this.altName]),n}},{key:"includedIn",value:function(t){var n=!1;return this.name&&(n=t.includes(this.name)),!n&&this.altName&&(n=t.includes(this.altName)),n}}]),r}();ki.NamespacedValue=j1;var Uq=function(r){Pq(t,r);var e=Mq(t);function t(n,i){var o;if(L1(this,t),o=e.call(this,n,i),!o.unstable)throw new Error("Unstable value must be supplied");return o}return U1(t,[{key:"name",get:function(){return this.unstable}},{key:"altName",get:function(){return this.stable}}]),t}(j1);ki.UnstableValue=Uq;Object.defineProperty(Xt,"__esModule",{value:!0});Xt.M_TEXT=Xt.M_NOTICE=Xt.M_MESSAGE=Xt.M_HTML=Xt.M_EMOTE=void 0;var pf=ki,jq=new pf.UnstableValue("m.message","org.matrix.msc1767.message");Xt.M_MESSAGE=jq;var Fq=new pf.UnstableValue("m.text","org.matrix.msc1767.text");Xt.M_TEXT=Fq;var Bq=new pf.UnstableValue("m.html","org.matrix.msc1767.html");Xt.M_HTML=Bq;var Kq=new pf.UnstableValue("m.emote","org.matrix.msc1767.emote");Xt.M_EMOTE=Kq;var Vq=new pf.UnstableValue("m.notice","org.matrix.msc1767.notice");Xt.M_NOTICE=Vq;var Fo={};Object.defineProperty(Fo,"__esModule",{value:!0});Fo.isEventTypeSame=$q;function $q(r,e){if(typeof r=="string")return typeof e=="string"?e===r:e.matches(r);if(typeof e=="string")return r.matches(e);var t=e,n=r;return t.matches(n.name)||t.matches(n.altName)}function GS(r){"@babel/helpers - typeof";return GS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},GS(r)}Object.defineProperty(io,"__esModule",{value:!0});io.MessageEvent=void 0;var Wq=Ws,su=hf,Dg=jo,Cn=Xt,qq=Fo;function AR(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function DR(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?AR(Object(t),!0).forEach(function(n){Zo(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):AR(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function Gq(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function NR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function Hq(r,e,t){return e&&NR(r.prototype,e),t&&NR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function zq(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&HS(r,e)}function HS(r,e){return HS=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},HS(r,e)}function Yq(r){var e=Xq();return function(){var n=Wp(r),i;if(e){var o=Wp(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return Jq(this,i)}}function Jq(r,e){if(e&&(GS(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Kh(r)}function Kh(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function Xq(){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 Wp(r){return Wp=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Wp(r)}function Zo(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var Qq=function(r){zq(t,r);var e=Yq(t);function t(n){var i;Gq(this,t),i=e.call(this,n),Zo(Kh(i),"text",void 0),Zo(Kh(i),"html",void 0),Zo(Kh(i),"renderings",void 0);var o=Cn.M_MESSAGE.findIn(i.wireContent),s=Cn.M_TEXT.findIn(i.wireContent),a=Cn.M_HTML.findIn(i.wireContent);if((0,su.isProvided)(o)){if(!Array.isArray(o))throw new Dg.InvalidEventError("m.message contents must be an array");var l=o.find(function(u){return!(0,su.isProvided)(u.mimetype)||u.mimetype==="text/plain"}),c=o.find(function(u){return u.mimetype==="text/html"});if(!l)throw new Dg.InvalidEventError("m.message is missing a plain text representation");i.text=l.body,i.html=c==null?void 0:c.body,i.renderings=o}else if((0,su.isOptionalAString)(s))i.text=s,i.html=a,i.renderings=[{body:s,mimetype:"text/plain"}],i.html&&i.renderings.push({body:i.html,mimetype:"text/html"});else throw new Dg.InvalidEventError("Missing textual representation for event");return i}return Hq(t,[{key:"isEmote",get:function(){return Cn.M_EMOTE.matches(this.wireFormat.type)||(0,su.isProvided)(Cn.M_EMOTE.findIn(this.wireFormat.content))}},{key:"isNotice",get:function(){return Cn.M_NOTICE.matches(this.wireFormat.type)||(0,su.isProvided)(Cn.M_NOTICE.findIn(this.wireFormat.content))}},{key:"isEquivalentTo",value:function(i){return(0,qq.isEventTypeSame)(i,Cn.M_MESSAGE)}},{key:"serializeMMessageOnly",value:function(){var i=Zo({},Cn.M_MESSAGE.name,this.renderings);if(this.renderings.length===1){var o=this.renderings[0].mimetype;(o===void 0||o==="text/plain")&&(i=Zo({},Cn.M_TEXT.name,this.renderings[0].body))}return i}},{key:"serialize",value:function(){var i;return{type:"m.room.message",content:DR(DR({},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 s;return new t({type:Cn.M_MESSAGE.name,content:(s={},Zo(s,Cn.M_TEXT.name,i),Zo(s,Cn.M_HTML.name,o),s)})}}]),t}(Wq.ExtensibleEvent);io.MessageEvent=Qq;var Lc={};function zS(r){"@babel/helpers - typeof";return zS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zS(r)}Object.defineProperty(Lc,"__esModule",{value:!0});Lc.NoticeEvent=void 0;var Zq=io,ih=Xt,eG=Fo;function LR(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function tG(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function UR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function rG(r,e,t){return e&&UR(r.prototype,e),t&&UR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function Xu(){return typeof Reflect<"u"&&Reflect.get?Xu=Reflect.get:Xu=function(e,t,n){var i=nG(e,t);if(i){var o=Object.getOwnPropertyDescriptor(i,t);return o.get?o.get.call(arguments.length<3?e:n):o.value}},Xu.apply(this,arguments)}function nG(r,e){for(;!Object.prototype.hasOwnProperty.call(r,e)&&(r=La(r),r!==null););return r}function iG(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&YS(r,e)}function YS(r,e){return YS=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},YS(r,e)}function oG(r){var e=lG();return function(){var n=La(r),i;if(e){var o=La(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return sG(this,i)}}function sG(r,e){if(e&&(zS(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return aG(r)}function aG(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function lG(){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 La(r){return La=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},La(r)}var cG=function(r){iG(t,r);var e=oG(t);function t(n){return tG(this,t),e.call(this,n)}return rG(t,[{key:"isNotice",get:function(){return!0}},{key:"isEquivalentTo",value:function(i){return(0,eG.isEventTypeSame)(i,ih.M_NOTICE)||Xu(La(t.prototype),"isEquivalentTo",this).call(this,i)}},{key:"serialize",value:function(){var i=Xu(La(t.prototype),"serialize",this).call(this);return i.content.msgtype="m.notice",i}}],[{key:"from",value:function(i,o){var s;return new t({type:ih.M_NOTICE.name,content:(s={},LR(s,ih.M_TEXT.name,i),LR(s,ih.M_HTML.name,o),s)})}}]),t}(Zq.MessageEvent);Lc.NoticeEvent=cG;var Uc={};function JS(r){"@babel/helpers - typeof";return JS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},JS(r)}Object.defineProperty(Uc,"__esModule",{value:!0});Uc.EmoteEvent=void 0;var uG=io,oh=Xt,dG=Fo;function jR(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function fG(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function FR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function hG(r,e,t){return e&&FR(r.prototype,e),t&&FR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function Qu(){return typeof Reflect<"u"&&Reflect.get?Qu=Reflect.get:Qu=function(e,t,n){var i=pG(e,t);if(i){var o=Object.getOwnPropertyDescriptor(i,t);return o.get?o.get.call(arguments.length<3?e:n):o.value}},Qu.apply(this,arguments)}function pG(r,e){for(;!Object.prototype.hasOwnProperty.call(r,e)&&(r=Ua(r),r!==null););return r}function vG(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&XS(r,e)}function XS(r,e){return XS=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},XS(r,e)}function mG(r){var e=SG();return function(){var n=Ua(r),i;if(e){var o=Ua(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return gG(this,i)}}function gG(r,e){if(e&&(JS(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return yG(r)}function yG(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function SG(){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 Ua(r){return Ua=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Ua(r)}var bG=function(r){vG(t,r);var e=mG(t);function t(n){return fG(this,t),e.call(this,n)}return hG(t,[{key:"isEmote",get:function(){return!0}},{key:"isEquivalentTo",value:function(i){return(0,dG.isEventTypeSame)(i,oh.M_EMOTE)||Qu(Ua(t.prototype),"isEquivalentTo",this).call(this,i)}},{key:"serialize",value:function(){var i=Qu(Ua(t.prototype),"serialize",this).call(this);return i.content.msgtype="m.emote",i}}],[{key:"from",value:function(i,o){var s;return new t({type:oh.M_EMOTE.name,content:(s={},jR(s,oh.M_TEXT.name,i),jR(s,oh.M_HTML.name,o),s)})}}]),t}(uG.MessageEvent);Uc.EmoteEvent=bG;Object.defineProperty(Nc,"__esModule",{value:!0});Nc.LEGACY_M_ROOM_MESSAGE=void 0;Nc.parseMRoomMessage=RG;var BR=io,_G=Lc,EG=Uc,wG=ki,Ho=Xt;function KR(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function $n(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?KR(Object(t),!0).forEach(function(n){la(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):KR(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function la(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var TG=new wG.NamespacedValue("m.room.message");Nc.LEGACY_M_ROOM_MESSAGE=TG;function RG(r){var e,t,n;if(Ho.M_MESSAGE.findIn(r.content)||Ho.M_TEXT.findIn(r.content))return new BR.MessageEvent(r);var i=(e=r.content)===null||e===void 0?void 0:e.msgtype,o=(t=r.content)===null||t===void 0?void 0:t.body,s=((n=r.content)===null||n===void 0?void 0:n.format)==="org.matrix.custom.html"?r.content.formatted_body:null;if(i==="m.text"){var a;return new BR.MessageEvent($n($n({},r),{},{content:$n($n({},r.content),{},(a={},la(a,Ho.M_TEXT.name,o),la(a,Ho.M_HTML.name,s),a))}))}else if(i==="m.notice"){var l;return new _G.NoticeEvent($n($n({},r),{},{content:$n($n({},r.content),{},(l={},la(l,Ho.M_TEXT.name,o),la(l,Ho.M_HTML.name,s),l))}))}else if(i==="m.emote"){var c;return new EG.EmoteEvent($n($n({},r),{},{content:$n($n({},r.content),{},(c={},la(c,Ho.M_TEXT.name,o),la(c,Ho.M_HTML.name,s),c))}))}else return null}var sm={};Object.defineProperty(sm,"__esModule",{value:!0});sm.parseMMessage=xG;var CG=io,VR=Xt,kG=Uc,IG=Lc;function xG(r){return VR.M_EMOTE.matches(r.type)?new kG.EmoteEvent(r):VR.M_NOTICE.matches(r.type)?new IG.NoticeEvent(r):new CG.MessageEvent(r)}var Mr={};Object.defineProperty(Mr,"__esModule",{value:!0});Mr.M_POLL_START=Mr.M_POLL_RESPONSE=Mr.M_POLL_KIND_UNDISCLOSED=Mr.M_POLL_KIND_DISCLOSED=Mr.M_POLL_END=void 0;var vf=ki,OG=new vf.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed");Mr.M_POLL_KIND_DISCLOSED=OG;var PG=new vf.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed");Mr.M_POLL_KIND_UNDISCLOSED=PG;var MG=new vf.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");Mr.M_POLL_START=MG;var AG=new vf.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response");Mr.M_POLL_RESPONSE=AG;var DG=new vf.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end");Mr.M_POLL_END=DG;var am={},ja={};function QS(r){"@babel/helpers - typeof";return QS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},QS(r)}Object.defineProperty(ja,"__esModule",{value:!0});ja.PollStartEvent=ja.PollAnswerSubevent=void 0;var lo=Mr,F1=io,Pu=Xt,Vh=jo,NG=ki,LG=Fo,UG=Ws;function jG(r){return VG(r)||KG(r)||BG(r)||FG()}function FG(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
271
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function BG(r,e){if(r){if(typeof r=="string")return ZS(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return ZS(r,e)}}function KG(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function VG(r){if(Array.isArray(r))return ZS(r)}function ZS(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function $R(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function $G(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?$R(Object(t),!0).forEach(function(n){vn(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):$R(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function B1(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function WR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function K1(r,e,t){return e&&WR(r.prototype,e),t&&WR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function V1(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&eb(r,e)}function eb(r,e){return eb=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},eb(r,e)}function $1(r){var e=qG();return function(){var n=qp(r),i;if(e){var o=qp(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return WG(this,i)}}function WG(r,e){if(e&&(QS(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return va(r)}function va(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function qG(){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 qp(r){return qp=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},qp(r)}function vn(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var W1=function(r){V1(t,r);var e=$1(t);function t(n){var i;B1(this,t),i=e.call(this,n),vn(va(i),"id",void 0);var o=n.content.id;if(!o||typeof o!="string")throw new Vh.InvalidEventError("Answer ID must be a non-empty string");return i.id=o,i}return K1(t,[{key:"serialize",value:function(){return{type:"org.matrix.sdk.poll.answer",content:$G({id:this.id},this.serializeMMessageOnly())}}}],[{key:"from",value:function(i,o){return new t({type:"org.matrix.sdk.poll.answer",content:vn({id:i},Pu.M_TEXT.name,o)})}}]),t}(F1.MessageEvent);ja.PollAnswerSubevent=W1;var GG=function(r){V1(t,r);var e=$1(t);function t(n){var i;B1(this,t),i=e.call(this,n),vn(va(i),"question",void 0),vn(va(i),"kind",void 0),vn(va(i),"rawKind",void 0),vn(va(i),"maxSelections",void 0),vn(va(i),"answers",void 0);var o=lo.M_POLL_START.findIn(i.wireContent);if(!o.question)throw new Vh.InvalidEventError("A question is required");if(i.question=new F1.MessageEvent({type:"org.matrix.sdk.poll.question",content:o.question}),i.rawKind=o.kind,lo.M_POLL_KIND_DISCLOSED.matches(i.rawKind)?i.kind=lo.M_POLL_KIND_DISCLOSED:i.kind=lo.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 Vh.InvalidEventError("Poll answers must be an array");var s=o.answers.slice(0,20).map(function(a){return new W1({type:"org.matrix.sdk.poll.answer",content:a})});if(s.length<=0)throw new Vh.InvalidEventError("No answers available");return i.answers=s,i}return K1(t,[{key:"isEquivalentTo",value:function(i){return(0,LG.isEventTypeSame)(i,lo.M_POLL_START)}},{key:"serialize",value:function(){var i;return{type:lo.M_POLL_START.name,content:(i={},vn(i,lo.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})}),vn(i,Pu.M_TEXT.name,"".concat(this.question.text,`
272
+ `).concat(this.answers.map(function(o,s){return"".concat(s+1,". ").concat(o.text)}).join(`
273
+ `))),i)}}}],[{key:"from",value:function(i,o,s){var a,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;return new t({type:lo.M_POLL_START.name,content:(a={},vn(a,Pu.M_TEXT.name,i),vn(a,lo.M_POLL_START.name,{question:vn({},Pu.M_TEXT.name,i),kind:s instanceof NG.NamespacedValue?s.name:s,max_selections:l,answers:o.map(function(c){return vn({id:HG()},Pu.M_TEXT.name,c)})}),a)})}}]),t}(UG.ExtensibleEvent);ja.PollStartEvent=GG;var qR="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function HG(){return jG(Array(16)).map(function(){return qR.charAt(Math.floor(Math.random()*qR.length))}).join("")}var mf={},jc={};Object.defineProperty(jc,"__esModule",{value:!0});jc.REFERENCE_RELATION=void 0;var zG=ki,YG=new zG.NamespacedValue("m.reference");jc.REFERENCE_RELATION=YG;function tb(r){"@babel/helpers - typeof";return tb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},tb(r)}Object.defineProperty(mf,"__esModule",{value:!0});mf.PollResponseEvent=void 0;var JG=Ws,il=Mr,XG=jo,Ng=jc,QG=Fo;function ZG(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function GR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function e6(r,e,t){return e&&GR(r.prototype,e),t&&GR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function t6(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&rb(r,e)}function rb(r,e){return rb=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},rb(r,e)}function r6(r){var e=i6();return function(){var n=Gp(r),i;if(e){var o=Gp(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return n6(this,i)}}function n6(r,e){if(e&&(tb(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return $h(r)}function $h(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function i6(){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 Gp(r){return Gp=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Gp(r)}function au(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var o6=function(r){t6(t,r);var e=r6(t);function t(n){var i;ZG(this,t),i=e.call(this,n),au($h(i),"internalAnswerIds",void 0),au($h(i),"internalSpoiled",void 0),au($h(i),"pollEventId",void 0);var o=i.wireContent["m.relates_to"];if(!Ng.REFERENCE_RELATION.matches(o==null?void 0:o.rel_type)||typeof(o==null?void 0:o.event_id)!="string")throw new XG.InvalidEventError("Relationship must be a reference to an event");return i.pollEventId=o.event_id,i.validateAgainst(null),i}return e6(t,[{key:"answerIds",get:function(){return this.internalAnswerIds}},{key:"spoiled",get:function(){return this.internalSpoiled}},{key:"validateAgainst",value:function(i){var o=il.M_POLL_RESPONSE.findIn(this.wireContent);if(!Array.isArray(o==null?void 0:o.answers)){this.internalSpoiled=!0,this.internalAnswerIds=[];return}var s=o.answers;if(s.some(function(a){return typeof a!="string"})||s.length===0){this.internalSpoiled=!0,this.internalAnswerIds=[];return}if(i){if(s.some(function(a){return!i.answers.some(function(l){return l.id===a})})){this.internalSpoiled=!0,this.internalAnswerIds=[];return}s=s.slice(0,i.maxSelections)}this.internalAnswerIds=s,this.internalSpoiled=!1}},{key:"isEquivalentTo",value:function(i){return(0,QG.isEventTypeSame)(i,il.M_POLL_RESPONSE)}},{key:"serialize",value:function(){return{type:il.M_POLL_RESPONSE.name,content:au({"m.relates_to":{rel_type:Ng.REFERENCE_RELATION.name,event_id:this.pollEventId}},il.M_POLL_RESPONSE.name,{answers:this.spoiled?void 0:this.answerIds})}}}],[{key:"from",value:function(i,o){return new t({type:il.M_POLL_RESPONSE.name,content:au({"m.relates_to":{rel_type:Ng.REFERENCE_RELATION.name,event_id:o}},il.M_POLL_RESPONSE.name,{answers:i})})}}]),t}(JG.ExtensibleEvent);mf.PollResponseEvent=o6;var gf={};function nb(r){"@babel/helpers - typeof";return nb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nb(r)}Object.defineProperty(gf,"__esModule",{value:!0});gf.PollEndEvent=void 0;var lu=Mr,s6=jo,Lg=jc,a6=io,l6=Xt,c6=Fo,u6=Ws;function HR(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function d6(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?HR(Object(t),!0).forEach(function(n){gl(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):HR(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function f6(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function zR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function h6(r,e,t){return e&&zR(r.prototype,e),t&&zR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function p6(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&ib(r,e)}function ib(r,e){return ib=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},ib(r,e)}function v6(r){var e=g6();return function(){var n=Hp(r),i;if(e){var o=Hp(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return m6(this,i)}}function m6(r,e){if(e&&(nb(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ob(r)}function ob(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function g6(){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 Hp(r){return Hp=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Hp(r)}function gl(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var y6=function(r){p6(t,r);var e=v6(t);function t(n){var i;f6(this,t),i=e.call(this,n),gl(ob(i),"pollEventId",void 0),gl(ob(i),"closingMessage",void 0);var o=i.wireContent["m.relates_to"];if(!Lg.REFERENCE_RELATION.matches(o==null?void 0:o.rel_type)||typeof(o==null?void 0:o.event_id)!="string")throw new s6.InvalidEventError("Relationship must be a reference to an event");return i.pollEventId=o.event_id,i.closingMessage=new a6.MessageEvent(i.wireFormat),i}return h6(t,[{key:"isEquivalentTo",value:function(i){return(0,c6.isEventTypeSame)(i,lu.M_POLL_END)}},{key:"serialize",value:function(){return{type:lu.M_POLL_END.name,content:d6(gl({"m.relates_to":{rel_type:Lg.REFERENCE_RELATION.name,event_id:this.pollEventId}},lu.M_POLL_END.name,{}),this.closingMessage.serialize().content)}}}],[{key:"from",value:function(i,o){var s;return new t({type:lu.M_POLL_END.name,content:(s={"m.relates_to":{rel_type:Lg.REFERENCE_RELATION.name,event_id:i}},gl(s,lu.M_POLL_END.name,{}),gl(s,l6.M_TEXT.name,o),s)})}}]),t}(u6.ExtensibleEvent);gf.PollEndEvent=y6;Object.defineProperty(am,"__esModule",{value:!0});am.parseMPoll=E6;var Ug=Mr,S6=ja,b6=mf,_6=gf;function E6(r){return Ug.M_POLL_START.matches(r.type)?new S6.PollStartEvent(r):Ug.M_POLL_RESPONSE.matches(r.type)?new b6.PollResponseEvent(r):Ug.M_POLL_END.matches(r.type)?new _6.PollEndEvent(r):null}Object.defineProperty(om,"__esModule",{value:!0});om.ExtensibleEvents=void 0;var w6=ff,T6=jo,YR=Nc,jg=sm,sh=Xt,Fg=Mr,Bg=am;function R6(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=C6(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
274
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function C6(r,e){if(r){if(typeof r=="string")return JR(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return JR(r,e)}}function JR(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function k6(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function XR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function I6(r,e,t){return e&&XR(r.prototype,e),t&&XR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function sb(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var ab=function(){function r(){k6(this,r),sb(this,"interpreters",new w6.NamespacedMap([[YR.LEGACY_M_ROOM_MESSAGE,YR.parseMRoomMessage],[sh.M_MESSAGE,jg.parseMMessage],[sh.M_EMOTE,jg.parseMMessage],[sh.M_NOTICE,jg.parseMMessage],[Fg.M_POLL_START,Bg.parseMPoll],[Fg.M_POLL_RESPONSE,Bg.parseMPoll],[Fg.M_POLL_END,Bg.parseMPoll]])),sb(this,"_unknownInterpretOrder",[sh.M_MESSAGE])}return I6(r,[{key:"unknownInterpretOrder",get:function(){var t;return(t=this._unknownInterpretOrder)!==null&&t!==void 0?t:[]},set:function(t){this._unknownInterpretOrder=t}},{key:"registerInterpreter",value:function(t,n){this.interpreters.set(t,n)}},{key:"parse",value:function(t){try{if(this.interpreters.hasNamespaced(t.type))return this.interpreters.getNamespaced(t.type)(t);var n=R6(this.unknownInterpretOrder),i;try{for(n.s();!(i=n.n()).done;){var o=i.value;if(this.interpreters.has(o)){var s=this.interpreters.get(o)(t);if(s)return s}}}catch(a){n.e(a)}finally{n.f()}return null}catch(a){if(a instanceof T6.InvalidEventError)return null;throw a}}}],[{key:"defaultInstance",get:function(){return r._defaultInstance}},{key:"unknownInterpretOrder",get:function(){return r.defaultInstance.unknownInterpretOrder},set:function(t){r.defaultInstance.unknownInterpretOrder=t}},{key:"registerInterpreter",value:function(t,n){r.defaultInstance.registerInterpreter(t,n)}},{key:"parse",value:function(t){return r.defaultInstance.parse(t)}}]),r}();om.ExtensibleEvents=ab;sb(ab,"_defaultInstance",new ab);var q1={};Object.defineProperty(q1,"__esModule",{value:!0});var Fc={};Object.defineProperty(Fc,"__esModule",{value:!0});Fc.LegacyMsgType=void 0;Fc.isEventLike=x6;var Kg=Xt,Hl;Fc.LegacyMsgType=Hl;(function(r){r.Text="m.text",r.Notice="m.notice",r.Emote="m.emote"})(Hl||(Fc.LegacyMsgType=Hl={}));function x6(r,e){var t=r.content;return e===Hl.Text?Kg.M_MESSAGE.matches(r.type)||r.type==="m.room.message"&&(t==null?void 0:t.msgtype)==="m.text":e===Hl.Emote?Kg.M_EMOTE.matches(r.type)||r.type==="m.room.message"&&(t==null?void 0:t.msgtype)==="m.emote":e===Hl.Notice?Kg.M_NOTICE.matches(r.type)||r.type==="m.room.message"&&(t==null?void 0:t.msgtype)==="m.notice":!1}(function(r){Object.defineProperty(r,"__esModule",{value:!0});var e=om;Object.keys(e).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===e[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return e[T]}})});var t=q1;Object.keys(t).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===t[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return t[T]}})});var n=jo;Object.keys(n).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===n[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return n[T]}})});var i=ki;Object.keys(i).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===i[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return i[T]}})});var o=ff;Object.keys(o).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===o[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return o[T]}})});var s=hf;Object.keys(s).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===s[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return s[T]}})});var a=Fc;Object.keys(a).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===a[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return a[T]}})});var l=Fo;Object.keys(l).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===l[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return l[T]}})});var c=Nc;Object.keys(c).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===c[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return c[T]}})});var u=sm;Object.keys(u).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===u[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return u[T]}})});var d=am;Object.keys(d).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===d[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return d[T]}})});var f=jc;Object.keys(f).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===f[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return f[T]}})});var p=Ws;Object.keys(p).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===p[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return p[T]}})});var h=Xt;Object.keys(h).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===h[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return h[T]}})});var m=io;Object.keys(m).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===m[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return m[T]}})});var w=Uc;Object.keys(w).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===w[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return w[T]}})});var g=Lc;Object.keys(g).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===g[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return g[T]}})});var b=Mr;Object.keys(b).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===b[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return b[T]}})});var R=ja;Object.keys(R).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===R[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return R[T]}})});var k=mf;Object.keys(k).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===k[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return k[T]}})});var O=gf;Object.keys(O).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===O[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return O[T]}})})})(ln);function lw(r){return r!=null}var O6=new ln.UnstableValue("m.message","org.matrix.msc1767.message"),cw=new ln.UnstableValue("m.text","org.matrix.msc1767.text"),P6=new ln.UnstableValue("m.html","org.matrix.msc1767.html"),G1=new ln.NamespacedValue("m.reference");function M6(r,e){if(typeof r=="string")return typeof e=="string"?e===r:e.matches(r);if(typeof e=="string")return r.matches(e);var t=e,n=r;return t.matches(n.name)||lw(n.altName)&&t.matches(n.altName)}var vc=function(r){return r.Self="m.self",r.Pin="m.pin",r}({}),yf=new Ft("m.asset","org.matrix.msc3488.asset"),qs=new Ft("m.ts","org.matrix.msc3488.ts"),Sf=new Ft("m.location","org.matrix.msc3488.location"),Jr=function(r){return r.Read="m.read",r.FullyRead="m.fully_read",r.ReadPrivate="m.read.private",r}({}),bf="main";function QR(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function ZR(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?QR(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):QR(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Vg=new Map;function $g(r){return r instanceof String&&(r=r.toString()),Vg.has(r)||Vg.set(r,r),Vg.get(r)}function lb(r,e){var t=e??new URLSearchParams,n=function(a){o!=null&&(Array.isArray(o)?o.forEach(l=>{t.append(a,String(l))}):t.append(a,String(o)))};for(var[i,o]of Object.entries(r))n(i);return t}function eC(r,e,t){var n=ZR(ZR({},t),{},{[e]:t[r]});return delete n[r],n}function Se(r,e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];n!=null&&(r=r.replace(t,encodeURIComponent(n)))}return r}function zp(r,e,t){var n;if(t){for(n=r.length-1;n>=0;n--)if(e(r[n],n,r))return r.splice(n,1),!0}else for(n=0;n<r.length;n++)if(e(r[n],n,r))return r.splice(n,1),!0;return!1}function H1(r,e){for(var t of e)if(!r.hasOwnProperty(t))throw new Error("Missing required key: "+t)}function lm(r){return JSON.parse(JSON.stringify(r))}function Fa(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="number"&&isNaN(r)&&isNaN(e))return!0;if(r===null||e===null)return r===e;if(!(r instanceof Object)||r.constructor!==e.constructor||r.prototype!==e.prototype)return!1;if(r instanceof RegExp||r instanceof Date)return r.toString()===e.toString();if(Array.isArray(r)){if(r.length!==e.length)return!1;for(var t=0;t<r.length;t++)if(!Fa(r[t],e[t]))return!1}else{for(var n in e)if(e.hasOwnProperty(n)!==r.hasOwnProperty(n))return!1;for(var i in r)if(e.hasOwnProperty(i)!==r.hasOwnProperty(i)||!Fa(r[i],e[i]))return!1}return!0}function cb(r){if(typeof r!="object"||r==null||Array.isArray(r))return r;var e=[];for(var[t,n]of Object.entries(r))e.push([t,cb(n)]);return e.sort((i,o)=>Wh(i[0],o[0])),e}function tC(r){return typeof r=="number"&&isFinite(r)}function Ra(r){return typeof r=="string"?nq(r.normalize("NFD").replace(D6,"")):""}function ub(r){return typeof r=="string"?r.replace(/[\u202d-\u202e]/g,""):""}function A6(r){return Ra(r.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()}var D6=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g;function z1(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y1(r){return z1(r).replace(/\\\*/g,".*").replace(/\?/g,".")}function Wg(r){return r!=null&&r.endsWith("/")?r.slice(0,-1):r}function As(r,e){return new Promise(t=>{setTimeout(t,r,e)})}function xte(r,e,t){return db.apply(this,arguments)}function db(){return db=_(function*(r,e,t){var n=Date.now();try{return yield t()}finally{var i=Date.now();r.debug("[Perf]: ".concat(e," took ").concat(i-n,"ms"))}}),db.apply(this,arguments)}function N6(){return new Promise(r=>setTimeout(r))}function J1(r){return r==null}function Gs(){var r,e,t=new Promise((n,i)=>{r=n,e=i});return{resolve:r,reject:e,promise:t}}function Ll(r,e){return fb.apply(this,arguments)}function fb(){return fb=_(function*(r,e){for(var t of r)yield e(yield t)}),fb.apply(this,arguments)}function ca(r){return Promise.resolve(r())}function L6(r,e){return hb.apply(this,arguments)}function hb(){return hb=_(function*(r,e){for(var t=[],n=0;n<r.length;n+=e)t.push(...yield Promise.all(r.slice(n,n+e).map(i=>i())));return t}),hb.apply(this,arguments)}function U6(r){return A1(e=>r(e),{forever:!0,factor:2,minTimeout:3e3,maxTimeout:15e3})}var Ds=(()=>{for(var r="",e=32;e<=126;e++)r+=String.fromCharCode(e);return r})();function rC(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ds;return r.padEnd(e,t[0])}function Ud(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds,t=BigInt(e.length);if(r<=t){var n;return(n=e[Number(r)-1])!==null&&n!==void 0?n:""}var i=r/t,o=Number(r%t)-1;return o<0&&(i-=BigInt(Math.abs(o)),o=Number(t)-1),Ud(i,e)+e[o]}function Yp(r){for(var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds,t=BigInt(e.length),n=BigInt(0),i=r.length-1,o=BigInt(0);i>=0;i--,o++){var s=r.charCodeAt(i)-e.charCodeAt(0);n+=BigInt(1+s)*t**o}return n}function j6(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ds,n=Math.max(r.length,e.length),i=Yp(rC(r,n,t),t),o=Yp(rC(e,n,t),t),s=(i+o)/BigInt(2);return s===i||s==o?Ud(s,t)+t[0]:Ud(s,t)}function cu(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds;return Ud(Yp(r,e)+BigInt(1),e)}function nC(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds;return Ud(Yp(r,e)-BigInt(1),e)}function Wh(r,e){return r<e?-1:r>e?1:0}function X1(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;for(var[n,i]of Object.entries(e)){if(r[n]instanceof Object&&i){X1(r[n],i);continue}if(i!=null||!t){Xi(r,n,i);continue}}return r}function iC(r){var e;return(e=qs.findIn(r.getContent()))!==null&&e!==void 0?e:-1}function F6(r,e){return iC(e)-iC(r)}function uw(r){return[Jr.Read,Jr.ReadPrivate].includes(r)}function oC(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:(s,a)=>s===a;if(r.size!==e.size)return!1;for(var[n,i]of r){var o=e.get(n);if(o===void 0||!t(i,o))return!1}return!0}function Q1(r){return r instanceof Map?ms(r):Array.isArray(r)?r.map(e=>Q1(e)):r}function ms(r){var e=new Map;for(var[t,n]of r)e.set(t,Q1(n));return Object.fromEntries(e.entries())}function Zu(r){return r==="__proto__"||r==="prototype"||r==="constructor"}function Xi(r,e,t){if(Zu(e))throw new Error("Trying to modify prototype or constructor");r[e]=t}function mi(r){return!(Zu(r.room_id)||Zu(r.sender)||Zu(r.event_id))}class qt extends Map{constructor(e){super(),this.createDefault=e}getOrCreate(e){return this.has(e)||this.set(e,this.createDefault()),this.get(e)}}var pb="migrationState",mc=function(r){return r[r.NOT_STARTED=0]="NOT_STARTED",r[r.INITIAL_DATA_MIGRATED=1]="INITIAL_DATA_MIGRATED",r[r.OLM_SESSIONS_MIGRATED=2]="OLM_SESSIONS_MIGRATED",r[r.MEGOLM_SESSIONS_MIGRATED=3]="MEGOLM_SESSIONS_MIGRATED",r[r.ROOM_SETTINGS_MIGRATED=4]="ROOM_SETTINGS_MIGRATED",r[r.INITIAL_OWN_KEY_QUERY_DONE=5]="INITIAL_OWN_KEY_QUERY_DONE",r}({}),gc=50;function sC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function zo(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?sC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):sC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function Qs(r,e){return encodeURIComponent(r)+"/"+encodeURIComponent(e)}function qg(r){var e=r.split("/"),t=decodeURIComponent(e[0]),n=decodeURIComponent(e[1]);return{senderKey:t,sessionId:n}}class cm{constructor(){v(this,"migrationState",mc.NOT_STARTED),v(this,"outgoingRoomKeyRequests",[]),v(this,"account",null),v(this,"crossSigningKeys",null),v(this,"privateKeys",{}),v(this,"sessions",{}),v(this,"sessionProblems",{}),v(this,"notifiedErrorDevices",{}),v(this,"inboundGroupSessions",{}),v(this,"inboundGroupSessionsWithheld",{}),v(this,"deviceData",null),v(this,"rooms",{}),v(this,"sessionsNeedingBackup",{}),v(this,"sharedHistoryInboundGroupSessions",{}),v(this,"parkedSharedHistory",new Map)}containsData(){var e=this;return _(function*(){return e.account!==null})()}startup(){var e=this;return _(function*(){return e})()}deleteAllData(){return Promise.resolve()}getMigrationState(){var e=this;return _(function*(){return e.migrationState})()}setMigrationState(e){var t=this;return _(function*(){t.migrationState=e})()}getOrAddOutgoingRoomKeyRequest(e){var t=e.requestBody;return ca(()=>{var n=this._getOutgoingRoomKeyRequest(t);return n?(S.log("already have key request outstanding for "+"".concat(t.room_id," / ").concat(t.session_id,": ")+"not sending another"),n):(S.log("enqueueing key request for ".concat(t.room_id," / ")+t.session_id),this.outgoingRoomKeyRequests.push(e),e)})}getOutgoingRoomKeyRequest(e){return Promise.resolve(this._getOutgoingRoomKeyRequest(e))}_getOutgoingRoomKeyRequest(e){for(var t of this.outgoingRoomKeyRequests)if(Fa(t.requestBody,e))return t;return null}getOutgoingRoomKeyRequestByState(e){for(var t of this.outgoingRoomKeyRequests)for(var n of e)if(t.state===n)return Promise.resolve(t);return Promise.resolve(null)}getAllOutgoingRoomKeyRequestsByState(e){return Promise.resolve(this.outgoingRoomKeyRequests.filter(t=>t.state==e))}getOutgoingRoomKeyRequestsByTarget(e,t,n){var i=[];for(var o of this.outgoingRoomKeyRequests)for(var s of n)o.state===s&&o.recipients.some(a=>a.userId===e&&a.deviceId===t)&&i.push(o);return Promise.resolve(i)}updateOutgoingRoomKeyRequest(e,t,n){for(var i of this.outgoingRoomKeyRequests)if(i.requestId===e)return i.state!==t?(S.warn("Cannot update room key request from ".concat(t," ")+"as it was already updated to ".concat(i.state)),Promise.resolve(null)):(Object.assign(i,n),Promise.resolve(i));return Promise.resolve(null)}deleteOutgoingRoomKeyRequest(e,t){for(var n=0;n<this.outgoingRoomKeyRequests.length;n++){var i=this.outgoingRoomKeyRequests[n];if(i.requestId===e)return i.state!=t?(S.warn("Cannot delete room key request in state ".concat(i.state," ")+"(expected ".concat(t,")")),Promise.resolve(null)):(this.outgoingRoomKeyRequests.splice(n,1),Promise.resolve(i))}return Promise.resolve(null)}getAccount(e,t){t(this.account)}storeAccount(e,t){this.account=t}getCrossSigningKeys(e,t){t(this.crossSigningKeys)}getSecretStorePrivateKey(e,t,n){var i=this.privateKeys[n];t(i||null)}storeCrossSigningKeys(e,t){this.crossSigningKeys=t}storeSecretStorePrivateKey(e,t,n){this.privateKeys[t]=n}countEndToEndSessions(e,t){var n=0;for(var i of Object.values(this.sessions))n+=Object.keys(i).length;t(n)}getEndToEndSession(e,t,n,i){var o=this.sessions[e]||{};i(o[t]||null)}getEndToEndSessions(e,t,n){n(this.sessions[e]||{})}getAllEndToEndSessions(e,t){Object.entries(this.sessions).forEach(n=>{var[i,o]=n;Object.entries(o).forEach(s=>{var[a,l]=s;t(zo(zo({},l),{},{deviceKey:i,sessionId:a}))})})}storeEndToEndSession(e,t,n,i){var o=this.sessions[e];o===void 0&&(o={},this.sessions[e]=o),Xi(o,t,n)}storeEndToEndSessionProblem(e,t,n){var i=this;return _(function*(){var o=i.sessionProblems[e]=i.sessionProblems[e]||[];o.push({type:t,fixed:n,time:Date.now()}),o.sort((s,a)=>s.time-a.time)})()}getEndToEndSessionProblem(e,t){var n=this;return _(function*(){var i=n.sessionProblems[e]||[];if(!i.length)return null;var o=i[i.length-1];for(var s of i)if(s.time>t)return Object.assign({},s,{fixed:o.fixed});return o.fixed?null:o})()}filterOutNotifiedErrorDevices(e){var t=this;return _(function*(){var n=t.notifiedErrorDevices,i=[];for(var o of e){var{userId:s,deviceInfo:a}=o;s in n?a.deviceId in n[s]||(i.push(o),Xi(n[s],a.deviceId,!0)):(i.push(o),Xi(n,s,{[a.deviceId]:!0}))}return i})()}getEndToEndSessionsBatch(){var e=this;return _(function*(){var t=[];for(var n of Object.values(e.sessions))for(var i of Object.values(n))if(t.push(i),t.length>=gc)return t;return t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return _(function*(){for(var{deviceKey:n,sessionId:i}of e){var o=t.sessions[n]||{};delete o[i],Object.keys(o).length===0&&delete t.sessions[n]}})()}getEndToEndInboundGroupSession(e,t,n,i){var o=Qs(e,t);i(this.inboundGroupSessions[o]||null,this.inboundGroupSessionsWithheld[o]||null)}getAllEndToEndInboundGroupSessions(e,t){for(var n of Object.keys(this.inboundGroupSessions))t(zo(zo({},qg(n)),{},{sessionData:this.inboundGroupSessions[n]}));t(null)}addEndToEndInboundGroupSession(e,t,n,i){var o=Qs(e,t);this.inboundGroupSessions[o]===void 0&&(this.inboundGroupSessions[o]=n)}storeEndToEndInboundGroupSession(e,t,n,i){var o=Qs(e,t);this.inboundGroupSessions[o]=n}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){var o=Qs(e,t);this.inboundGroupSessionsWithheld[o]=n}countEndToEndInboundGroupSessions(){var e=this;return _(function*(){return Object.keys(e.inboundGroupSessions).length})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return _(function*(){var t=[];for(var[n,i]of Object.entries(e.inboundGroupSessions))if(t.push(zo(zo({},qg(n)),{},{sessionData:i,needsBackup:n in e.sessionsNeedingBackup})),t.length>=gc)return t;return t.length===0?null:t})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return _(function*(){for(var{senderKey:n,sessionId:i}of e){var o=Qs(n,i);delete t.inboundGroupSessions[o]}})()}getEndToEndDeviceData(e,t){t(this.deviceData)}storeEndToEndDeviceData(e,t){this.deviceData=e}storeEndToEndRoom(e,t,n){this.rooms[e]=t}getEndToEndRooms(e,t){t(this.rooms)}getSessionsNeedingBackup(e){var t=[];for(var n in this.sessionsNeedingBackup)if(this.inboundGroupSessions[n]&&(t.push(zo(zo({},qg(n)),{},{sessionData:this.inboundGroupSessions[n]})),e&&n.length>=e))break;return Promise.resolve(t)}countSessionsNeedingBackup(){return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length)}unmarkSessionsNeedingBackup(e){for(var t of e){var n=Qs(t.senderKey,t.sessionId);delete this.sessionsNeedingBackup[n]}return Promise.resolve()}markSessionsNeedingBackup(e){for(var t of e){var n=Qs(t.senderKey,t.sessionId);this.sessionsNeedingBackup[n]=!0}return Promise.resolve()}addSharedHistoryInboundGroupSession(e,t,n){var i=this.sharedHistoryInboundGroupSessions[e]||[];i.push([t,n]),this.sharedHistoryInboundGroupSessions[e]=i}getSharedHistoryInboundGroupSessions(e){return Promise.resolve(this.sharedHistoryInboundGroupSessions[e]||[])}addParkedSharedHistory(e,t){var n,i=(n=this.parkedSharedHistory.get(e))!==null&&n!==void 0?n:[];i.push(t),this.parkedSharedHistory.set(e,i)}takeParkedSharedHistory(e){var t,n=(t=this.parkedSharedHistory.get(e))!==null&&t!==void 0?t:[];return this.parkedSharedHistory.delete(e),Promise.resolve(n)}doTxn(e,t,n){return Promise.resolve(n(null))}}var B6=/^(?:(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?:\[[\dA-Fa-f:.]{2,45}])|(?:[A-Za-z\d\-.]{1,255}))(?::\d{1,5})?$/;function K6(r){var e=B6.exec(r);return(e==null?void 0:e[0])===r}var V6=/^[\w-]+$/;function $6(r){var e=V6.exec(r);return(e==null?void 0:e[0])===r}function um(r,e,t,n,i){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1,s=arguments.length>6?arguments[6]:void 0,a=arguments.length>7?arguments[7]:void 0;if(typeof e!="string"||!e)return"";if(!e.startsWith("mxc://"))return o?e:"";var[l,c,...u]=e.slice(6).split("/");if(u.length>0||!K6(l)||!$6(c))return"";a&&(s=!0);var d,f=!!t||!!n||!!i,p=f?"thumbnail":"download";a?d="/_matrix/client/v1/media/".concat(p):d="/_matrix/media/v3/".concat(p);var h=new URL("".concat(d,"/").concat(l,"/").concat(c),r);return t&&h.searchParams.set("width",Math.round(t).toString()),n&&h.searchParams.set("height",Math.round(n).toString()),i&&h.searchParams.set("method",i),typeof s=="boolean"&&h.searchParams.set("allow_redirect",JSON.stringify(s)),h.href}var dw={exports:{}},zl=typeof Reflect=="object"?Reflect:null,aC=zl&&typeof zl.apply=="function"?zl.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},qh;zl&&typeof zl.ownKeys=="function"?qh=zl.ownKeys:Object.getOwnPropertySymbols?qh=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:qh=function(e){return Object.getOwnPropertyNames(e)};function W6(r){console&&console.warn&&console.warn(r)}var Z1=Number.isNaN||function(e){return e!==e};function mt(){mt.init.call(this)}dw.exports=mt;dw.exports.once=z6;mt.EventEmitter=mt;mt.prototype._events=void 0;mt.prototype._eventsCount=0;mt.prototype._maxListeners=void 0;var lC=10;function dm(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(mt,"defaultMaxListeners",{enumerable:!0,get:function(){return lC},set:function(r){if(typeof r!="number"||r<0||Z1(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");lC=r}});mt.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};mt.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Z1(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function eD(r){return r._maxListeners===void 0?mt.defaultMaxListeners:r._maxListeners}mt.prototype.getMaxListeners=function(){return eD(this)};mt.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var l=o[e];if(l===void 0)return!1;if(typeof l=="function")aC(l,this,t);else for(var c=l.length,u=oD(l,c),n=0;n<c;++n)aC(u[n],this,t);return!0};function tD(r,e,t,n){var i,o,s;if(dm(t),o=r._events,o===void 0?(o=r._events=Object.create(null),r._eventsCount=0):(o.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),o=r._events),s=o[e]),s===void 0)s=o[e]=t,++r._eventsCount;else if(typeof s=="function"?s=o[e]=n?[t,s]:[s,t]:n?s.unshift(t):s.push(t),i=eD(r),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=s.length,W6(a)}return r}mt.prototype.addListener=function(e,t){return tD(this,e,t,!1)};mt.prototype.on=mt.prototype.addListener;mt.prototype.prependListener=function(e,t){return tD(this,e,t,!0)};function q6(){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 rD(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=q6.bind(n);return i.listener=t,n.wrapFn=i,i}mt.prototype.once=function(e,t){return dm(t),this.on(e,rD(this,e,t)),this};mt.prototype.prependOnceListener=function(e,t){return dm(t),this.prependListener(e,rD(this,e,t)),this};mt.prototype.removeListener=function(e,t){var n,i,o,s,a;if(dm(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():G6(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};mt.prototype.off=mt.prototype.removeListener;mt.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function nD(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?H6(i):oD(i,i.length)}mt.prototype.listeners=function(e){return nD(this,e,!0)};mt.prototype.rawListeners=function(e){return nD(this,e,!1)};mt.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):iD.call(r,e)};mt.prototype.listenerCount=iD;function iD(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}mt.prototype.eventNames=function(){return this._eventsCount>0?qh(this._events):[]};function oD(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function G6(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function H6(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function z6(r,e){return new Promise(function(t,n){function i(s){r.removeListener(e,o),n(s)}function o(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}sD(r,e,o,{once:!0}),e!=="error"&&Y6(r,i,{once:!0})})}function Y6(r,e,t){typeof r.on=="function"&&sD(r,"error",e,t)}function sD(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(o){n.once&&r.removeEventListener(e,i),t(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}var fm=dw.exports,aD=function(r){return r.NewListener="newListener",r.RemoveListener="removeListener",r.Error="error",r}({});class Tt extends fm.EventEmitter{addListener(e,t){return super.addListener(e,t)}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return super.emit(e,...n)}emitPromised(e){var t=arguments,n=this;return _(function*(){for(var i=t.length,o=new Array(i>1?i-1:0),s=1;s<i;s++)o[s-1]=t[s];var a=n.listeners(e);return Promise.allSettled(a.map(l=>l(...o))).then(()=>a.length>0)})()}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}off(e,t){return super.off(e,t)}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}prependListener(e,t){return super.prependListener(e,t)}prependOnceListener(e,t){return super.prependOnceListener(e,t)}removeAllListeners(e){return e===void 0?super.removeAllListeners():super.removeAllListeners(e)}removeListener(e,t){return super.removeListener(e,t)}rawListeners(e){return super.rawListeners(e)}}var fw=new Ft("m.beacon_info","org.matrix.msc3672.beacon_info"),vb=new Ft("m.beacon","org.matrix.msc3672.beacon"),J6=new ln.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed"),X6=new ln.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed"),Q6=new ln.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start"),jd=new ln.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response"),Jp=new ln.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end"),V=function(r){return r.RoomCanonicalAlias="m.room.canonical_alias",r.RoomCreate="m.room.create",r.RoomJoinRules="m.room.join_rules",r.RoomMember="m.room.member",r.RoomThirdPartyInvite="m.room.third_party_invite",r.RoomPowerLevels="m.room.power_levels",r.RoomName="m.room.name",r.RoomTopic="m.room.topic",r.RoomAvatar="m.room.avatar",r.RoomPinnedEvents="m.room.pinned_events",r.RoomEncryption="m.room.encryption",r.RoomHistoryVisibility="m.room.history_visibility",r.RoomGuestAccess="m.room.guest_access",r.RoomServerAcl="m.room.server_acl",r.RoomTombstone="m.room.tombstone",r.RoomPredecessor="org.matrix.msc3946.room_predecessor",r.PolicyRuleUser="m.policy.rule.user",r.PolicyRuleRoom="m.policy.rule.room",r.PolicyRuleServer="m.policy.rule.server",r.SpaceChild="m.space.child",r.SpaceParent="m.space.parent",r.RoomRedaction="m.room.redaction",r.RoomMessage="m.room.message",r.RoomMessageEncrypted="m.room.encrypted",r.Sticker="m.sticker",r.CallInvite="m.call.invite",r.CallCandidates="m.call.candidates",r.CallAnswer="m.call.answer",r.CallHangup="m.call.hangup",r.CallReject="m.call.reject",r.CallSelectAnswer="m.call.select_answer",r.CallNegotiate="m.call.negotiate",r.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",r.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",r.CallReplaces="m.call.replaces",r.CallAssertedIdentity="m.call.asserted_identity",r.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",r.CallEncryptionKeysPrefix="io.element.call.encryption_keys",r.KeyVerificationRequest="m.key.verification.request",r.KeyVerificationStart="m.key.verification.start",r.KeyVerificationCancel="m.key.verification.cancel",r.KeyVerificationMac="m.key.verification.mac",r.KeyVerificationDone="m.key.verification.done",r.KeyVerificationKey="m.key.verification.key",r.KeyVerificationAccept="m.key.verification.accept",r.KeyVerificationReady="m.key.verification.ready",r.RoomMessageFeedback="m.room.message.feedback",r.Reaction="m.reaction",r.PollStart="org.matrix.msc3381.poll.start",r.Typing="m.typing",r.Receipt="m.receipt",r.Presence="m.presence",r.FullyRead="m.fully_read",r.Tag="m.tag",r.SpaceOrder="org.matrix.msc3230.space_order",r.PushRules="m.push_rules",r.Direct="m.direct",r.IgnoredUserList="m.ignored_user_list",r.RoomKey="m.room_key",r.RoomKeyRequest="m.room_key_request",r.ForwardedRoomKey="m.forwarded_room_key",r.Dummy="m.dummy",r.GroupCallPrefix="org.matrix.msc3401.call",r.GroupCallMemberPrefix="org.matrix.msc3401.call.member",r.CallNotify="org.matrix.msc4075.call.notify",r}({}),At=function(r){return r.Annotation="m.annotation",r.Replace="m.replace",r.Reference="m.reference",r.Thread="m.thread",r}({}),xi=function(r){return r.Text="m.text",r.Emote="m.emote",r.Notice="m.notice",r.Image="m.image",r.File="m.file",r.Audio="m.audio",r.Location="m.location",r.Video="m.video",r.KeyVerificationRequest="m.key.verification.request",r}({}),Xp="type",Yl=function(r){return r.Space="m.space",r.UnstableCall="org.matrix.msc3417.call",r.ElementVideo="io.element.video",r}({}),en="org.matrix.msgid",mb=new Ft("m.room.purpose","org.matrix.msc3088.purpose"),gb=new Ft("m.enabled","org.matrix.msc3088.enabled"),yb=new Ft("m.data_tree","org.matrix.msc3089.data_tree"),lD=new Ft("m.leaf","org.matrix.msc3089.leaf"),yo=new Ft("m.branch","org.matrix.msc3089.branch"),cD=new Ft("m.room.marker","org.matrix.msc2716.marker"),Sb=new Ft("with_rel_types","org.matrix.msc3912.with_relations"),uD=new Ft("io.element.functional_members","io.element.functional_members"),Ea=new Ft("m.visibility","org.matrix.msc3531.visibility"),bb=new Ft("enabled","org.matrix.msc3881.enabled"),Z6=new Ft("device_id","org.matrix.msc3881.device_id"),dD=new Ft("m.local_notification_settings","org.matrix.msc3890.local_notification_settings"),Qp=new Ft("thread_id","org.matrix.msc4023.thread_id"),fD=new nm("membership","io.element.msc4115.membership"),Be=function(r){return r.Ban="ban",r.Invite="invite",r.Join="join",r.Knock="knock",r.Leave="leave",r}({}),Ar=function(r){return r.Membership="RoomMember.membership",r.Name="RoomMember.name",r.PowerLevel="RoomMember.powerLevel",r.Typing="RoomMember.typing",r}({});class Zp extends Tt{constructor(e,t){super(),this.roomId=e,this.userId=t,v(this,"_isOutOfBand",!1),v(this,"modified",-1),v(this,"requestedProfileInfo",!1),v(this,"typing",!1),v(this,"name",void 0),v(this,"rawDisplayName",void 0),v(this,"powerLevel",0),v(this,"powerLevelNorm",0),v(this,"user",void 0),v(this,"membership",void 0),v(this,"disambiguate",!1),v(this,"events",{}),this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){var n,i,o=(n=e.getDirectionalContent().displayname)!==null&&n!==void 0?n:"";if(e.getType()===V.RoomMember){this._isOutOfBand=!1,this.events.member=e;var s=this.membership;this.membership=e.getDirectionalContent().membership,this.membership===void 0&&S.trace("membership event with membership undefined (forwardLooking: ".concat(e.forwardLooking,")!"),e.getContent(),"prevcontent is ",e.getPrevContent()),this.disambiguate=rH(this.userId,o,t);var a=this.name;this.name=nH(this.userId,o,this.disambiguate),this.rawDisplayName=ub((i=e.getDirectionalContent().displayname)!==null&&i!==void 0?i:""),(!this.rawDisplayName||!Ra(this.rawDisplayName))&&(this.rawDisplayName=this.userId),s!==this.membership&&(this.updateModifiedTime(),this.emit(Ar.Membership,e,this,s)),a!==this.name&&(this.updateModifiedTime(),this.emit(Ar.Name,e,this,a))}}setPowerLevelEvent(e){if(!(e.getType()!==V.RoomPowerLevels||e.getStateKey()!=="")){var t=e.getDirectionalContent(),n=t.users_default||0,i=t.users||{};Object.values(i).forEach(a=>{n=Math.max(n,a)});var o=this.powerLevel,s=this.powerLevelNorm;i[this.userId]!==void 0&&Number.isInteger(i[this.userId])?this.powerLevel=i[this.userId]:t.users_default!==void 0?this.powerLevel=t.users_default:this.powerLevel=0,this.powerLevelNorm=0,n>0&&(this.powerLevelNorm=this.powerLevel*100/n),(o!==this.powerLevel||s!==this.powerLevelNorm)&&(this.updateModifiedTime(),this.emit(Ar.PowerLevel,e,this))}}setTypingEvent(e){if(e.getType()==="m.typing"){var t=this.typing;this.typing=!1;var n=e.getContent().user_ids;Array.isArray(n)&&(n.indexOf(this.userId)!==-1&&(this.typing=!0),t!==this.typing&&(this.updateModifiedTime(),this.emit(Ar.Typing,e,this)))}}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}isKicked(){return this.membership===Be.Leave&&this.events.member!==void 0&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){var e=this.events.member,t=e.getContent(),n=e.getSender();if(t.membership===Be.Join&&(t=e.getPrevContent(),n=e.getUnsigned().prev_sender),t.membership===Be.Invite&&t.is_direct)return n}}getAvatarUrl(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,s=arguments.length>5?arguments[5]:void 0,a=this.getMxcAvatarUrl();if(!a&&!o)return null;var l=um(e,a,t,n,i,s);return l||null}getMxcAvatarUrl(){if(this.events.member)return this.events.member.getDirectionalContent().avatar_url;if(this.user)return this.user.avatarUrl}}var eH=/@.+:.+/,tH=/[\u200E\u200F\u202A-\u202F]/;function rH(r,e,t){if(!e||e===r||!t)return!1;var n=Ra(e);if(!n)return!1;if(eH.test(n)||tH.test(e))return!0;var i=t.getUserIdsWithDisplayName(e);return!!i.some(o=>o!==r)}function nH(r,e,t){return!e||e===r?r:t?ub(e)+" ("+r+")":Ra(e)?ub(e):r}const iH="modulepreload",oH=function(r){return"/"+r},cC={},hD=function(e,t,n){let i=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"));i=Promise.allSettled(t.map(l=>{if(l=oH(l),l in cC)return;cC[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":iH,c||(d.as="script"),d.crossOrigin="",d.href=l,a&&d.setAttribute("nonce",a),document.head.appendChild(d),c)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return i.then(s=>{for(const a of s||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};function sH(r,e){if(r==null)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)!==-1)continue;t[n]=r[n]}return t}function aH(r,e){if(r==null)return{};var t,n,i=sH(r,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(r);for(n=0;n<o.length;n++)t=o[n],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(r,t)&&(i[t]=r[t])}return i}var ar=function(r){return r.DisplayName="User.displayName",r.AvatarUrl="User.avatarUrl",r.Presence="User.presence",r.CurrentlyActive="User.currentlyActive",r.LastPresenceTs="User.lastPresenceTs",r}({});class Co extends Tt{constructor(e){super(),this.userId=e,v(this,"modified",-1),v(this,"displayName",void 0),v(this,"rawDisplayName",void 0),v(this,"avatarUrl",void 0),v(this,"presenceStatusMsg",void 0),v(this,"presence","offline"),v(this,"lastActiveAgo",0),v(this,"lastPresenceTs",0),v(this,"currentlyActive",!1),v(this,"events",{}),this.displayName=e,this.rawDisplayName=e,this.updateModifiedTime()}static createUser(e,t){var n=new Co(e);return t.reEmitter.reEmit(n,[ar.AvatarUrl,ar.DisplayName,ar.Presence,ar.CurrentlyActive,ar.LastPresenceTs]),n}setPresenceEvent(e){if(e.getType()==="m.presence"){var t=this.events.presence===null;this.events.presence=e;var n=[];(e.getContent().presence!==this.presence||t)&&n.push(ar.Presence),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&n.push(ar.AvatarUrl),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&n.push(ar.DisplayName),e.getContent().currently_active!==void 0&&e.getContent().currently_active!==this.currentlyActive&&n.push(ar.CurrentlyActive),this.presence=e.getContent().presence,n.push(ar.LastPresenceTs),e.getContent().status_msg&&(this.presenceStatusMsg=e.getContent().status_msg),e.getContent().displayname&&(this.displayName=e.getContent().displayname),e.getContent().avatar_url&&(this.avatarUrl=e.getContent().avatar_url),this.lastActiveAgo=e.getContent().last_active_ago,this.lastPresenceTs=Date.now(),this.currentlyActive=e.getContent().currently_active,this.updateModifiedTime();for(var i of n)this.emit(i,e,this)}}setDisplayName(e){var t=this.displayName;this.displayName=e,e!==t&&this.updateModifiedTime()}setRawDisplayName(e){this.rawDisplayName=e}setAvatarUrl(e){var t=this.avatarUrl;this.avatarUrl=e,e!==t&&this.updateModifiedTime()}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getLastActiveTs(){return this.lastPresenceTs-this.lastActiveAgo}}var Ge=function(r){return r.Backward="b",r.Forward="f",r}({});class Ee{static setEventMetadata(e,t,n){var i,o;(i=e.sender)!==null&&i!==void 0&&(i=i.events)!==null&&i!==void 0&&i.member||(e.sender=t.getSentinelMember(e.getSender())),!((o=e.target)!==null&&o!==void 0&&(o=o.events)!==null&&o!==void 0&&o.member)&&e.getType()===V.RoomMember&&(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)}constructor(e){var t,n;this.eventTimelineSet=e,v(this,"roomId",void 0),v(this,"name",void 0),v(this,"events",[]),v(this,"baseIndex",0),v(this,"startState",void 0),v(this,"endState",void 0),v(this,"startToken",null),v(this,"endToken",null),v(this,"prevTimeline",null),v(this,"nextTimeline",null),v(this,"paginationRequests",{[Ge.Backward]:null,[Ge.Forward]:null}),this.roomId=(t=(n=e.room)===null||n===void 0?void 0:n.roomId)!==null&&t!==void 0?t:null,this.roomId&&(this.startState=new qd(this.roomId,void 0,!0),this.endState=new qd(this.roomId)),this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+new Date().toISOString()}initialiseState(e){var t,n,{timelineWasEmpty:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.events.length>0)throw new Error("Cannot initialise state after events are added");(t=this.startState)===null||t===void 0||t.setStateEvents(e,{timelineWasEmpty:i}),(n=this.endState)===null||n===void 0||n.setStateEvents(e,{timelineWasEmpty:i})}forkLive(e){var t=this.getState(e),n=new Ee(this.eventTimelineSet);return n.startState=t==null?void 0:t.clone(),n.endState=t,this.endState=t==null?void 0:t.clone(),n}fork(e){var t=this.getState(e),n=new Ee(this.eventTimelineSet);return n.startState=t==null?void 0:t.clone(),n.endState=t==null?void 0:t.clone(),n}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(e){if(e==Ee.BACKWARDS)return this.startState;if(e==Ee.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.roomId?this.getState(e).paginationToken:e===Ge.Backward?this.startToken:this.endToken}setPaginationToken(e,t){this.roomId?this.getState(t).paginationToken=e:t===Ge.Backward?this.startToken=e:this.endToken=e}getNeighbouringTimeline(e){if(e==Ee.BACKWARDS)return this.prevTimeline;if(e==Ee.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+e+"'")}setNeighbouringTimeline(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+t+")");if(t==Ee.BACKWARDS)this.prevTimeline=e;else if(t==Ee.FORWARDS)this.nextTimeline=e;else throw new Error("Invalid direction '"+t+"'");this.setPaginationToken(null,t)}addEvent(e){var{toStartOfTimeline:t,roomState:n,timelineWasEmpty:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{toStartOfTimeline:!1};n||(n=t?this.startState:this.endState);var o=this.getTimelineSet();if(o.room&&(Ee.setEventMetadata(e,n,t),e.isState()&&o.room.getUnfilteredTimelineSet()===o)){var s;(s=n)===null||s===void 0||s.setStateEvents([e],{timelineWasEmpty:i}),(!e.sender||e.getType()===V.RoomMember&&!t)&&Ee.setEventMetadata(e,n,t)}var a;t?a=0:a=this.events.length,this.events.splice(a,0,e),t&&this.baseIndex++}insertEvent(e,t,n){var i=this.getTimelineSet();i.room&&(Ee.setEventMetadata(e,n,!1),e.isState()&&i.room.getUnfilteredTimelineSet()===i&&(n.setStateEvents([e],{}),(!e.sender||e.getType()===V.RoomMember)&&Ee.setEventMetadata(e,n,!1))),this.events.splice(t,0,e)}removeEvent(e){for(var t=this.events.length-1;t>=0;t--){var n=this.events[t];if(n.getId()==e)return this.events.splice(t,1),t<this.baseIndex&&this.baseIndex--,n}return null}toString(){return this.name}}v(Ee,"BACKWARDS",Ge.Backward);v(Ee,"FORWARDS",Ge.Forward);var Gh=function(r){return r.Add="Relations.add",r.Remove="Relations.remove",r.Redaction="Relations.redaction",r}({}),lH=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return[t,...n].includes(e)};class hw extends Tt{constructor(e,t,n,i){var o;super(),o=this,this.relationType=e,this.eventType=t,this.altEventTypes=i,v(this,"relationEventIds",new Set),v(this,"relations",new Set),v(this,"annotationsByKey",{}),v(this,"annotationsBySender",{}),v(this,"sortedAnnotationsByKey",[]),v(this,"targetEvent",null),v(this,"creationEmitted",!1),v(this,"client",void 0),v(this,"onEventStatus",(s,a)=>{if(!s.isSending()){s.removeListener(ot.Status,this.onEventStatus);return}a===je.CANCELLED&&(s.removeListener(ot.Status,this.onEventStatus),this.removeEvent(s))}),v(this,"onBeforeRedaction",function(){var s=_(function*(a){if(o.relations.has(a)){if(o.relations.delete(a),o.relationType===At.Annotation)o.removeAnnotationFromAggregation(a);else if(o.relationType===At.Replace&&o.targetEvent&&!o.targetEvent.isState()){var l=yield o.getLastReplacement();o.targetEvent.makeReplaced(l)}a.removeListener(ot.BeforeRedaction,o.onBeforeRedaction),o.emit(Gh.Redaction,a)}});return function(a){return s.apply(this,arguments)}}()),this.client=n instanceof pm?n.client:n}addEvent(e){var t=this;return _(function*(){if(!t.relationEventIds.has(e.getId())){var n=e.getRelation();if(!n){S.error("Event must have relation info");return}var i=n.rel_type,o=e.getType();if(t.relationType!==i||!lH(o,t.eventType,t.altEventTypes)){S.error("Event relation info doesn't match this container");return}if(e.isSending()&&e.on(ot.Status,t.onEventStatus),t.relations.add(e),t.relationEventIds.add(e.getId()),t.relationType===At.Annotation)t.addAnnotationToAggregation(e);else if(t.relationType===At.Replace&&t.targetEvent&&!t.targetEvent.isState()){var s=yield t.getLastReplacement();t.targetEvent.makeReplaced(s)}e.on(ot.BeforeRedaction,t.onBeforeRedaction),t.emit(Gh.Add,e),t.maybeEmitCreated()}})()}removeEvent(e){var t=this;return _(function*(){if(t.relations.has(e)){if(t.relations.delete(e),t.relationType===At.Annotation)t.removeAnnotationFromAggregation(e);else if(t.relationType===At.Replace&&t.targetEvent&&!t.targetEvent.isState()){var n=yield t.getLastReplacement();t.targetEvent.makeReplaced(n)}t.emit(Gh.Remove,e)}})()}getRelations(){return[...this.relations]}addAnnotationToAggregation(e){var t,{key:n}=(t=e.getRelation())!==null&&t!==void 0?t:{};if(n){var i=this.annotationsByKey[n];i||(i=this.annotationsByKey[n]=new Set,this.sortedAnnotationsByKey.push([n,i])),i.add(e),this.sortedAnnotationsByKey.sort((a,l)=>{var c=a[1],u=l[1];return u.size-c.size});var o=e.getSender(),s=this.annotationsBySender[o];s||(s=this.annotationsBySender[o]=new Set),s.add(e)}}removeAnnotationFromAggregation(e){var t,{key:n}=(t=e.getRelation())!==null&&t!==void 0?t:{};if(n){var i=this.annotationsByKey[n];i&&(i.delete(e),this.sortedAnnotationsByKey.sort((a,l)=>{var c=a[1],u=l[1];return u.size-c.size}));var o=e.getSender(),s=this.annotationsBySender[o];s&&s.delete(e)}}getSortedAnnotationsByKey(){return this.relationType!==At.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==At.Annotation?null:this.annotationsBySender}getLastReplacement(){var e=this;return _(function*(){if(e.relationType!==At.Replace||!e.targetEvent)return null;var t=e.targetEvent.getServerAggregatedRelation(At.Replace),n=t==null?void 0:t.origin_server_ts,i=e.getRelations().reduce((o,s)=>s.getSender()!==e.targetEvent.getSender()||n&&n>s.getTs()||o&&o.getTs()>s.getTs()?o:s,null);return i!=null&&i.shouldAttemptDecryption()&&e.client.isCryptoEnabled()?yield i.attemptDecryption(e.client.crypto):i!=null&&i.isBeingDecrypted()&&(yield i.getDecryptionPromise()),i})()}setTargetEvent(e){var t=this;return _(function*(){if(!t.targetEvent){if(t.targetEvent=e,t.relationType===At.Replace&&!t.targetEvent.isState()){var n=yield t.getLastReplacement();n&&t.targetEvent.makeReplaced(n)}t.maybeEmitCreated()}})()}maybeEmitCreated(){this.creationEmitted||!this.targetEvent||!this.relations.size||(this.creationEmitted=!0,this.targetEvent.emit(ot.RelationsCreated,this.relationType,this.eventType))}}class pD{constructor(e,t){this.client=e,this.room=t,v(this,"relations",new Map)}getChildEventsForEvent(e,t,n){var i;return(i=this.relations.get(e))===null||i===void 0||(i=i.get(t))===null||i===void 0?void 0:i.get(n)}getAllChildEventsForEvent(e){var t,n=(t=this.relations.get(e))!==null&&t!==void 0?t:new Map,i=[];for(var o of n.values())for(var s of o.values())i.push(...s.getRelations());return i}aggregateParentEvent(e){var t=this.relations.get(e.getId());if(t)for(var n of t.values())for(var i of n.values())i.setTargetEvent(e)}aggregateChildEvent(e,t){if(!(e.isRedacted()||e.status===je.CANCELLED)){var n=e.getRelation();if(n){var i=()=>{if(e.isDecryptionFailure()){e.once(ot.Decrypted,i);return}this.aggregateChildEvent(e,t)};if(e.isBeingDecrypted()||e.shouldAttemptDecryption()){e.once(ot.Decrypted,i);return}var{event_id:o,rel_type:s}=n,a=e.getType(),l=this.relations.get(o);l||(l=new Map,this.relations.set(o,l));var c=l.get(s);c||(c=new Map,l.set(s,c));var u=c.get(a);if(!u){var d,f,p;u=new hw(s,a,this.client),c.set(a,u);var h=(d=this.room)!==null&&d!==void 0?d:t==null?void 0:t.room,m=(f=(p=t==null?void 0:t.findEventById(o))!==null&&p!==void 0?p:h==null?void 0:h.findEventById(o))!==null&&f!==void 0?f:h==null?void 0:h.getPendingEvent(o);m&&u.setTargetEvent(m)}u.addEvent(e)}}}}var yl;yl=S.log.bind(S);var ed=function(r){return r.Ignore="ignore",r.Replace="replace",r}({});class Ul extends Tt{constructor(e){var t,n,i,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0,a=arguments.length>3?arguments[3]:void 0,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null;super(),this.room=e,this.thread=a,this.threadListType=l,v(this,"relations",void 0),v(this,"timelineSupport",void 0),v(this,"displayPendingEvents",void 0),v(this,"liveTimeline",void 0),v(this,"timelines",void 0),v(this,"_eventIdToTimeline",new Map),v(this,"filter",void 0),this.timelineSupport=!!o.timelineSupport,this.liveTimeline=new Ee(this),this.displayPendingEvents=o.pendingEvents!==!1,this.timelines=[this.liveTimeline],this._eventIdToTimeline=new Map,this.filter=o.filter,this.relations=(t=(n=this.room)===null||n===void 0?void 0:n.relations)!==null&&t!==void 0?t:new pD((i=e==null?void 0:e.client)!==null&&i!==void 0?i:s)}getTimelines(){return this.timelines}getFilter(){return this.filter}setFilter(e){this.filter=e}getPendingEvents(){return!this.room||!this.displayPendingEvents?[]:this.room.getPendingEvents()}getLiveTimeline(){return this.liveTimeline}setLiveTimeline(e){this.liveTimeline=e}eventIdToTimeline(e){return this._eventIdToTimeline.get(e)}replaceEventId(e,t){var n=this._eventIdToTimeline.get(e);n&&(this._eventIdToTimeline.delete(e),this._eventIdToTimeline.set(t,n))}resetLiveTimeline(e,t){var n=!this.timelineSupport||!t,i=this.liveTimeline,o=n?i.forkLive(Ee.FORWARDS):i.fork(Ee.FORWARDS);n?(this.timelines=[o],this._eventIdToTimeline=new Map):this.timelines.push(o),t&&i.setPaginationToken(t,Ee.FORWARDS),o.setPaginationToken(e??null,Ee.BACKWARDS),this.liveTimeline=o,this.emit(fe.TimelineReset,this.room,this,n)}getTimelineForEvent(e){if(e==null)return null;var t=this._eventIdToTimeline.get(e);return t===void 0?null:t}findEventById(e){var t=this.getTimelineForEvent(e);if(t)return t.getEvents().find(function(n){return n.getId()==e})}addTimeline(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");var e=new Ee(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,n,i){if(!n)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&n==this.liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(!(this.filter&&(e=this.filter.filterRoomTimeline(e),!e.length))){var o=t?Ee.BACKWARDS:Ee.FORWARDS,s=t?Ee.FORWARDS:Ee.BACKWARDS,a=!1,l=!1;for(var c of e){var u=c.getId(),d=this._eventIdToTimeline.get(u);if(!d){this.addEventToTimeline(c,n,{toStartOfTimeline:t}),l=!0,a=!0;continue}if(l=!1,d==n){yl("Event "+u+" already in timeline "+n);continue}var f=n.getNeighbouringTimeline(o);if(f){d==f?yl("Event "+u+" in neighbouring timeline - switching to "+d):yl("Event "+u+" already in a different timeline "+d),n=d;continue}S.info("Already have timeline for "+u+" - joining timeline "+n+" to "+d);var p=d===this.liveTimeline,h=n===this.liveTimeline,m=o===Ee.BACKWARDS&&p,w=o===Ee.FORWARDS&&h;if(m||w){m&&S.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+d+")"),w&&S.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+n+")");continue}n.setNeighbouringTimeline(d,o),d.setNeighbouringTimeline(n,s),n=d,a=!0}if(l||!a){if(o===Ee.FORWARDS&&n===this.liveTimeline){S.warn({lastEventWasNew:l,didUpdate:a}),S.warn("Refusing to set forwards pagination token of live timeline "+"".concat(n," to ").concat(i));return}n.setPaginationToken(i??null,o)}}}addLiveEvent(e){var{duplicateStrategy:t,fromCache:n,roomState:i,timelineWasEmpty:o}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.filter){var s=this.filter.filterRoomTimeline([e]);if(!s.length)return}var a=this._eventIdToTimeline.get(e.getId());if(a){if(t===ed.Replace){yl("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());for(var l=a.getEvents(),c=0;c<l.length;c++)if(l[c].getId()===e.getId()){i||(i=a.getState(Ee.FORWARDS)),Ee.setEventMetadata(e,i,!1),l[c]=e;break}}else yl("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());return}this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1,fromCache:n,roomState:i,timelineWasEmpty:o})}addEventToTimeline(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,o=arguments.length>4?arguments[4]:void 0,s=!!n,a;if(typeof n=="object"?{toStartOfTimeline:s,fromCache:i=!1,roomState:o,timelineWasEmpty:a}=n:n!==void 0&&S.warn("Overload deprecated: `EventTimelineSet.addEventToTimeline(event, timeline, toStartOfTimeline, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addEventToTimeline(event, timeline, IAddEventToTimelineOptions)`"),t.getTimelineSet()!==this){var l;throw new Error("EventTimelineSet.addEventToTimeline: Timeline=".concat(t.toString(),` does not belong " +
275
+ "in timelineSet(threadId=`).concat((l=this.thread)===null||l===void 0?void 0:l.id,")"))}var c=e.getId();if(this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this),this.room&&!this.canContain(e)){var u,d="event=".concat(c);e.threadRootId&&(d+="(belongs to thread=".concat(e.threadRootId,")")),S.warn("EventTimelineSet.addEventToTimeline: Ignoring ".concat(d," that does not belong ")+"in timeline=".concat(t.toString()," timelineSet(threadId=").concat((u=this.thread)===null||u===void 0?void 0:u.id,")"));return}t.addEvent(e,{toStartOfTimeline:s,roomState:o,timelineWasEmpty:a}),this._eventIdToTimeline.set(c,t);var f={timeline:t,liveEvent:!s&&t==this.liveTimeline&&!i};this.emit(fe.Timeline,e,this.room,!!s,!1,f)}insertEventIntoTimeline(e,t,n){if(t.getTimelineSet()!==this){var i;throw new Error("EventTimelineSet.insertEventIntoTimeline: Timeline=".concat(t.toString(),` does not belong " +
276
+ "in timelineSet(threadId=`).concat((i=this.thread)===null||i===void 0?void 0:i.id,")"))}var o=e.getId();if(this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this),this.room&&!this.canContain(e)){var s,a="event=".concat(o);e.threadRootId&&(a+="(belongs to thread=".concat(e.threadRootId,")")),S.warn("EventTimelineSet.insertEventIntoTimeline: Ignoring ".concat(a," that does not belong ")+"in timeline=".concat(t.toString()," timelineSet(threadId=").concat((s=this.thread)===null||s===void 0?void 0:s.id,")"));return}var l=e.relationEventId;if(!l){this.addEventToTimeline(e,t,{toStartOfTimeline:!1,fromCache:!1,timelineWasEmpty:!1,roomState:n});return}for(var c=this.findEventById(l),u=t.getEvents(),d=c!==void 0?u.indexOf(c):0,f=d;f<u.length;f++){var p=u[f];if(p.getTs()>e.getTs())break}t.insertEvent(e,f,n),this._eventIdToTimeline.set(o,t);var h={timeline:t,liveEvent:!1};this.emit(fe.Timeline,e,this.room,!1,!1,h)}handleRemoteEcho(e,t,n){var i=this._eventIdToTimeline.get(t);i?(this._eventIdToTimeline.delete(t),this._eventIdToTimeline.set(n,i)):(!this.filter||this.filter.filterRoomTimeline([e]).length)&&this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1})}removeEvent(e){var t=this._eventIdToTimeline.get(e);if(!t)return null;var n=t.removeEvent(e);if(n){this._eventIdToTimeline.delete(e);var i={timeline:t};this.emit(fe.Timeline,n,this.room,void 0,!0,i)}return n}compareEventOrdering(e,t){if(e==t)return 0;var n=this._eventIdToTimeline.get(e),i=this._eventIdToTimeline.get(t);if(n===void 0||i===void 0)return null;if(n===i){for(var o=void 0,s=void 0,a=n.getEvents(),l=0;l<a.length&&(o===void 0||s===void 0);l++){var c=a[l].getId();c==e&&(o=l),c==t&&(s=l)}var u=o-s;return u<0?-1:u>0?1:0}for(var d=n;d;){if(d===i)return-1;d=d.getNeighbouringTimeline(Ee.FORWARDS)}for(d=n;d;){if(d===i)return 1;d=d.getNeighbouringTimeline(Ee.BACKWARDS)}return null}canContain(e){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.");var{threadId:t,shouldLiveInRoom:n,shouldLiveInThread:i}=this.room.eventShouldLiveIn(e);if(this.thread)return this.thread.id===t;if(!n&&!i){var o;S.warn("EventTimelineSet:canContain event encountered which cannot be added to any timeline roomId=".concat((o=this.room)===null||o===void 0?void 0:o.roomId," eventId=").concat(e.getId()," threadId=").concat(e.threadRootId))}return n}}var je=function(r){return r.NOT_SENT="not_sent",r.ENCRYPTING="encrypting",r.SENDING="sending",r.QUEUED="queued",r.SENT="sent",r.CANCELLED="cancelled",r}({});class vD{constructor(e,t){this.roomId=e}}class mD{constructor(e){this.target=e,v(this,"reEmitters",new WeakMap)}reEmit(e,t){var n=this,i=this.reEmitters.get(e);i||(i=new Map,this.reEmitters.set(e,i));var o=function(l){if(i.has(l))return 1;var c=function(){if(!(l==="error"&&n.target.listenerCount("error")===0)){for(var d=arguments.length,f=new Array(d),p=0;p<d;p++)f[p]=arguments[p];n.target.emit(l,...f,e)}};e.on(l,c),i.set(l,c)};for(var s of t)o(s)}stopReEmitting(e,t){var n=this.reEmitters.get(e);if(n){for(var i of t)e.off(i,n.get(i)),n.delete(i);n.size===0&&this.reEmitters.delete(e)}}}class Bc extends mD{constructor(e){super(e)}reEmit(e,t){super.reEmit(e,t)}stopReEmitting(e,t){super.stopReEmitting(e,t)}}var Fd=new im("unread_thread_notifications","org.matrix.msc3773.unread_thread_notifications");function cH(r,e){if(e.endsWith("*")){var t=e.slice(0,-1);return r.slice(0,t.length)===t}else return r===e}class uC{constructor(e,t){this.filterJson=e,this.userId=t}check(e){var t,n,i=((t=e.getUnsigned())===null||t===void 0?void 0:t["m.relations"])||{},o=Object.keys(i),s=[];return this.userId&&i!==null&&i!==void 0&&(n=i[vt.name])!==null&&n!==void 0&&n.current_user_participated&&s.push(this.userId),this.checkFields(e.getRoomId(),e.getSender(),e.getType(),e.getContent()?e.getContent().url!==void 0:!1,o,s)}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,[tc.name]:this.filterJson[tc.name]||[],[rc.name]:this.filterJson[rc.name]||[]}}checkFields(e,t,n,i,o,s){var a={rooms:function(g){return e===g},senders:function(g){return t===g},types:function(g){return cH(n,g)}};for(var l in a){var c=a[l],u="not_"+l,d=this.filterJson[u];if(d!=null&&d.some(c))return!1;var f=this.filterJson[l];if(f&&!f.some(c))return!1}var p=this.filterJson.contains_url;if(p!==void 0&&p!==i)return!1;var h=this.filterJson[rc.name];if(h!==void 0&&!this.arrayMatchesFilter(h,o))return!1;var m=this.filterJson[tc.name];return!(m!==void 0&&!this.arrayMatchesFilter(m,s))}arrayMatchesFilter(e,t){return t.length>0&&e.every(n=>t.includes(n))}filter(e){return e.filter(this.check,this)}limit(){return this.filterJson.limit!==void 0?this.filterJson.limit:10}}function dC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function ol(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?dC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):dC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function Gg(r,e,t){for(var n=e.split("."),i=r,o=0;o<n.length-1;o++)i[n[o]]||(i[n[o]]={}),i=i[n[o]];i[n[n.length-1]]=t}class gn{static fromJson(e,t,n){var i=new gn(e,t);return i.setDefinition(n),i}constructor(e,t){this.userId=e,this.filterId=t,v(this,"definition",{}),v(this,"roomFilter",void 0),v(this,"roomTimelineFilter",void 0)}getFilterId(){return this.filterId}getDefinition(){return this.definition}setDefinition(e){this.definition=e;var t=e.room,n={};t&&(t.rooms&&(n.rooms=t.rooms),t.rooms&&(n.not_rooms=t.not_rooms)),this.roomFilter=new uC(n,this.userId),this.roomTimelineFilter=new uC((t==null?void 0:t.timeline)||{},this.userId)}getRoomTimelineFilterComponent(){return this.roomTimelineFilter}filterRoomTimeline(e){return this.roomFilter&&(e=this.roomFilter.filter(e)),this.roomTimelineFilter&&(e=this.roomTimelineFilter.filter(e)),e}setTimelineLimit(e){Gg(this.definition,"room.timeline.limit",e)}setUnreadThreadNotifications(e){var t,n;this.definition=ol(ol({},this.definition),{},{room:ol(ol({},(t=this.definition)===null||t===void 0?void 0:t.room),{},{timeline:ol(ol({},(n=this.definition)===null||n===void 0||(n=n.room)===null||n===void 0?void 0:n.timeline),{},{[Fd.name]:e})})})}setLazyLoadMembers(e){Gg(this.definition,"room.state.lazy_load_members",e)}setIncludeLeaveRooms(e){Gg(this.definition,"room.include_leave",e)}}v(gn,"LAZY_LOADING_MESSAGES_FILTER",{lazy_load_members:!0});var pw=new Ft("m.topic","org.matrix.msc3765.topic");function fC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function uH(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?fC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):fC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function gD(r,e){return{msgtype:xi.Text,format:"org.matrix.custom.html",body:r,formatted_body:e}}function yD(r,e){return{msgtype:xi.Notice,format:"org.matrix.custom.html",body:r,formatted_body:e}}function SD(r,e){return{msgtype:xi.Emote,format:"org.matrix.custom.html",body:r,formatted_body:e}}function bD(r){return{msgtype:xi.Text,body:r}}function _D(r){return{msgtype:xi.Notice,body:r}}function ED(r){return{msgtype:xi.Emote,body:r}}var wD=(r,e,t,n)=>{var i="at ".concat(new Date(t).toISOString()),o=e===vc.Self?"User":void 0,s=n?'"'.concat(n,'"'):void 0;return[o,"Location",s,r,i].filter(Boolean).join(" ")},TD=(r,e,t,n,i)=>{var o=r??wD(e,i||vc.Self,t,n),s=t?{[qs.name]:t}:{};return uH({msgtype:xi.Location,body:o,geo_uri:e,[Sf.name]:{description:n,uri:e},[yf.name]:{type:i||vc.Self},[cw.name]:o},s)},dH=r=>{var e,t,n=Sf.findIn(r),i=yf.findIn(r),o=qs.findIn(r),s=cw.findIn(r),a=(e=n==null?void 0:n.uri)!==null&&e!==void 0?e:r==null?void 0:r.geo_uri,l=n==null?void 0:n.description,c=(t=i==null?void 0:i.type)!==null&&t!==void 0?t:vc.Self,u=s??r.body;return TD(u,a,o??void 0,l,c)},RD=(r,e)=>{var t=[{body:r,mimetype:"text/plain"}];return lw(e)&&t.push({body:e,mimetype:"text/html"}),{topic:r,[pw.name]:t}},fH=r=>{var e,t,n,i=pw.findIn(r);if(!Array.isArray(i))return{text:r.topic};var o=(e=i==null||(t=i.find(a=>!lw(a.mimetype)||a.mimetype==="text/plain"))===null||t===void 0?void 0:t.body)!==null&&e!==void 0?e:r.topic,s=i==null||(n=i.find(a=>a.mimetype==="text/html"))===null||n===void 0?void 0:n.body;return{text:o,html:s}},hH=(r,e,t,n,i)=>({description:t,timeout:r,live:e,[qs.name]:i||Date.now(),[yf.name]:{type:n??vc.Self}}),CD=r=>{var e,{description:t,timeout:n,live:i}=r,o=(e=qs.findIn(r))!==null&&e!==void 0?e:void 0,s=yf.findIn(r);return{description:t,timeout:n,live:i,assetType:s==null?void 0:s.type,timestamp:o}},pH=(r,e,t,n)=>({[Sf.name]:{description:n,uri:r},[qs.name]:e,"m.relates_to":{rel_type:G1.name,event_id:t}}),_b=r=>{var e,t=Sf.findIn(r),n=(e=qs.findIn(r))!==null&&e!==void 0?e:void 0;return{description:t==null?void 0:t.description,uri:t==null?void 0:t.uri,timestamp:n}};const vH=Object.freeze(Object.defineProperty({__proto__:null,getTextForLocationEvent:wD,makeBeaconContent:pH,makeBeaconInfoContent:hH,makeEmoteMessage:ED,makeHtmlEmote:SD,makeHtmlMessage:gD,makeHtmlNotice:yD,makeLocationContent:TD,makeNotice:_D,makeTextMessage:bD,makeTopicContent:RD,parseBeaconContent:_b,parseBeaconInfoContent:CD,parseLocationEvent:dH,parseTopicContent:fH},Symbol.toStringTag,{value:"Module"}));var kt=function(r){return r.New="Beacon.new",r.Update="Beacon.update",r.LivenessChange="Beacon.LivenessChange",r.Destroy="Beacon.Destroy",r.LocationUpdate="Beacon.LocationUpdate",r}({}),Eb=(r,e,t)=>t>=r&&r+e>=t,ev=r=>"".concat(r.getRoomId(),"_").concat(r.getStateKey());class kD extends Tt{constructor(e){super(),this.rootEvent=e,v(this,"roomId",void 0),v(this,"_beaconInfo",void 0),v(this,"_isLive",void 0),v(this,"livenessWatchTimeout",void 0),v(this,"_latestLocationEvent",void 0),v(this,"clearLatestLocation",()=>{this._latestLocationEvent=void 0,this.emit(kt.LocationUpdate,this.latestLocationState)}),this.roomId=this.rootEvent.getRoomId(),this.setBeaconInfo(this.rootEvent)}get isLive(){return!!this._isLive}get identifier(){return ev(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&&_b(this._latestLocationEvent.getContent())}get latestLocationEvent(){return this._latestLocationEvent}update(e){if(ev(e)!==this.identifier)throw new Error("Invalid updating event");e.getTs()<this.rootEvent.getTs()||(this.rootEvent=e,this.setBeaconInfo(this.rootEvent),this.emit(kt.Update,e,this),this.clearLatestLocation())}destroy(){this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this._isLive=!1,this.emit(kt.Destroy,this.identifier)}monitorLiveness(){if(this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this.checkLiveness(),!!this.beaconInfo)if(this.isLive){var e=this.beaconInfo.timestamp+this.beaconInfo.timeout-Date.now();e>1&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},e))}else this.beaconInfo.timestamp>Date.now()&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},this.beaconInfo.timestamp-Date.now()))}addLocations(e){var t;if(this.isLive){var n=e.filter(o=>{var s=o.getContent(),a=_b(s);if(!a.uri||!a.timestamp)return!1;var{timestamp:l}=a;return this._beaconInfo.timestamp&&Eb(this._beaconInfo.timestamp,this._beaconInfo.timeout,l)&&(!this.latestLocationState||l>this.latestLocationState.timestamp)}),i=(t=n.sort(F6))===null||t===void 0?void 0:t[0];i&&(this._latestLocationEvent=i,this.emit(kt.LocationUpdate,this.latestLocationState))}}setBeaconInfo(e){this._beaconInfo=CD(e.getContent()),this.checkLiveness()}checkLiveness(){var e=this.isLive;if(this.beaconInfo){var t=this.beaconInfo.timestamp>Date.now()?this.beaconInfo.timestamp-36e4:this.beaconInfo.timestamp;this._isLive=!!this._beaconInfo.live&&!!t&&Eb(t,this._beaconInfo.timeout,Date.now()),e!==this.isLive&&this.emit(kt.LivenessChange,this.isLive,this)}}}function hC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function mH(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?hC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):hC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function ID(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return new pr({content:{[e.getId()]:{[t]:{[r]:mH({ts:e.getTs()},!n&&{thread_id:Tc(e)})}}},type:V.Receipt,room_id:e.getRoomId()})}var sl=0,al=1;class xD extends Tt{constructor(){super(...arguments),v(this,"receipts",new qt(()=>new Map)),v(this,"receiptCacheByEventId",new Map)}getReadReceiptForUserId(e){var t,n,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Jr.Read,[s,a]=(t=(n=this.receipts.get(o))===null||n===void 0?void 0:n.get(e))!==null&&t!==void 0?t:[null,null];return i?s:a??s}compareReceipts(e,t){var n;return(n=this.getUnfilteredTimelineSet().compareEventOrdering(e.eventId,t.eventId))!==null&&n!==void 0?n:e.data.ts-t.data.ts}getEventReadUpTo(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=this.getLatestReceipt(e,t);return n&&this.receiptPointsAtConsistentEvent(n)?n.eventId:null}receiptPointsAtConsistentEvent(e){var t,n=this.findEventById(e.eventId);if(!n)return!1;if(!((t=e.data)!==null&&t!==void 0&&t.thread_id))return!0;if(e.data.thread_id===bf){var i=Wd(n);if(i)return!0}else if(n.threadRootId===e.data.thread_id)return!0;return S.warn("Ignoring receipt because its thread_id (".concat(e.data.thread_id,") disagrees ")+"with the thread root (".concat(n.threadRootId,") of the referenced event ")+"(event ID = ".concat(e.eventId,")")),!1}getLatestReceipt(e,t){var n,i,o=this.getReadReceiptForUserId(e,t,Jr.Read),s=this.getReadReceiptForUserId(e,t,Jr.ReadPrivate),a;return o!=null&&o.eventId&&s!==null&&s!==void 0&&s.eventId&&(a=this.compareReceipts(o,s)),a?(i=a<0?s:o)!==null&&i!==void 0?i:null:(n=s??o)!==null&&n!==void 0?n:null}addReceiptToStructure(e,t,n,i,o){var s,a,l=this.receipts.getOrCreate(t),c=l.get(n);c||(c=[null,null],l.set(n,c));var u=c[sl];if(o){var d;u=(d=c[al])!==null&&d!==void 0?d:c[sl]}var f={eventId:e,data:i};if(u){var p=this.compareReceipts(u,f);if(p>=0)return}var h=o?c[sl]:f,m=o?f:c[al],w=null;h&&m&&(w=this.getUnfilteredTimelineSet().compareEventOrdering(h.eventId,m.eventId));var g=w===null||w<0,b=(s=c[al])!==null&&s!==void 0?s:c[sl];o&&g?c[al]=f:o||(c[sl]=f,g||(c[al]=null));var R=(a=c[al])!==null&&a!==void 0?a:c[sl];if(b!==R){if(b&&this.receiptCacheByEventId.get(b.eventId)){var k=b.eventId;this.receiptCacheByEventId.set(k,this.receiptCacheByEventId.get(k).filter(O=>O.type!==t||O.userId!==n)),this.receiptCacheByEventId.get(k).length<1&&this.receiptCacheByEventId.delete(k)}this.receiptCacheByEventId.get(e)||this.receiptCacheByEventId.set(e,[]),this.receiptCacheByEventId.get(e).push({userId:n,type:t,data:i})}}getReceiptsForEvent(e){return this.receiptCacheByEventId.get(e.getId())||[]}fixupNotifications(e){var t=this.getReadReceiptForUserId(e,!1),n=this.timeline[this.timeline.length-1];n&&(t==null?void 0:t.eventId)===n.getId()&&e===n.getSender()&&(this.setUnread(it.Total,0),this.setUnread(it.Highlight,0))}addLocalEchoReceipt(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;this.addReceipt(ID(e,t,n,i),!0)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter(function(t){return uw(t.type)}).map(function(t){return t.userId})}}var cs=function(r){return r.New="Poll.new",r.End="Poll.end",r.Update="Poll.update",r.Responses="Poll.Responses",r.Destroy="Poll.Destroy",r.UndecryptableRelations="Poll.UndecryptableRelations",r}({}),pC=(r,e)=>{var t=r.filter(n=>{if(!n.isDecryptionFailure())return jd.matches(n.getType())&&n.getTs()<=e});return{responseEvents:t}};class OD extends Tt{constructor(e,t,n){if(super(),this.rootEvent=e,this.matrixClient=t,this.room=n,v(this,"roomId",void 0),v(this,"pollEvent",void 0),v(this,"_isFetchingResponses",!1),v(this,"relationsNextBatch",void 0),v(this,"responses",null),v(this,"endEvent",void 0),v(this,"undecryptableRelationEventIds",new Set),v(this,"countUndecryptableEvents",i=>{var o=i.filter(a=>a.isDecryptionFailure()).map(a=>a.getId()),s=this.undecryptableRelationsCount;this.undecryptableRelationEventIds=new Set([...this.undecryptableRelationEventIds,...o]),this.undecryptableRelationsCount!==s&&this.emit(cs.UndecryptableRelations,this.undecryptableRelationsCount)}),!this.rootEvent.getRoomId()||!this.rootEvent.getId())throw new Error("Invalid poll start event.");this.roomId=this.rootEvent.getRoomId(),this.pollEvent=this.rootEvent.unstableExtensibleEvent}get pollId(){return this.rootEvent.getId()}get endEventId(){var e;return(e=this.endEvent)===null||e===void 0?void 0:e.getId()}get isEnded(){return!!this.endEvent}get isFetchingResponses(){return this._isFetchingResponses}get undecryptableRelationsCount(){return this.undecryptableRelationEventIds.size}getResponses(){var e=this;return _(function*(){return e.responses||e.isFetchingResponses||(yield e.fetchResponses()),e.responses})()}onNewRelation(e){var t;if(Jp.matches(e.getType())&&this.validateEndEvent(e)&&(this.endEvent=e,this.refilterResponsesOnEnd(),this.emit(cs.End)),!!this.responses){var n=((t=this.endEvent)===null||t===void 0?void 0:t.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:i}=pC([e],n);this.countUndecryptableEvents([e]),i.length&&(i.forEach(o=>{this.responses.addEvent(o)}),this.emit(cs.Responses,this.responses))}}fetchResponses(){var e=this;return _(function*(){var t,n;e._isFetchingResponses=!0;var i=yield e.matrixClient.relations(e.roomId,e.rootEvent.getId(),"m.reference",void 0,{from:e.relationsNextBatch||void 0});yield Promise.all(i.events.map(c=>e.matrixClient.decryptEventIfNeeded(c)));var o=e.responses||new hw("m.reference",jd.name,e.matrixClient,[jd.altName]),s=i.events.find(c=>Jp.matches(c.getType()));e.validateEndEvent(s)&&(e.endEvent=s,e.refilterResponsesOnEnd(),e.emit(cs.End));var a=((t=e.endEvent)===null||t===void 0?void 0:t.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:l}=pC(i.events,a);l.forEach(c=>{o.addEvent(c)}),e.relationsNextBatch=(n=i.nextBatch)!==null&&n!==void 0?n:void 0,e.responses=o,e.countUndecryptableEvents(i.events),e.relationsNextBatch?e.fetchResponses():e._isFetchingResponses=!1,e.emit(cs.Responses,e.responses)})()}refilterResponsesOnEnd(){var e;if(this.responses){var t=((e=this.endEvent)===null||e===void 0?void 0:e.getTs())||Number.MAX_SAFE_INTEGER;this.responses.getRelations().forEach(n=>{if(n.getTs()>t){var i;(i=this.responses)===null||i===void 0||i.removeEvent(n)}}),this.emit(cs.Responses,this.responses)}}validateEndEvent(e){if(!e||this.endEvent&&this.endEvent.getTs()<e.getTs())return!1;var t=this.room.currentState,n=e.getSender();return!!n&&(n===this.rootEvent.getSender()||t.maySendRedactionForEvent(this.rootEvent,n))}}var PD=r=>{var e=r.getType();return ln.M_POLL_START.matches(e)||jd.matches(e)||Jp.matches(e)};class gH{constructor(e){v(this,"room",void 0),v(this,"threadedReceipts",void 0),v(this,"unthreadedReceipts",void 0),v(this,"danglingReceipts",void 0),v(this,"onTimelineEvent",t=>{var n=t.getId();if(n){var i=this.danglingReceipts.remove(n);i==null||i.forEach(o=>{o.receipt.thread_id?this.threadedReceipts.set(o.receipt.thread_id,o.eventId,o.receiptType,o.userId,o.receipt.ts,o.synthetic):this.unthreadedReceipts.set(n,o.receiptType,o.userId,o.receipt.ts,o.synthetic)})}}),this.room=e,this.threadedReceipts=new _H(e),this.unthreadedReceipts=new MD(e),this.danglingReceipts=new EH,e.on(fe.Timeline,this.onTimelineEvent)}add(e,t){for(var[n,i]of Object.entries(e))for(var[o,s]of Object.entries(i))for(var[a,l]of Object.entries(s)){var c=this.room.findEventById(n);c?l.thread_id?this.threadedReceipts.set(l.thread_id,n,o,a,l.ts,t):this.unthreadedReceipts.set(n,o,a,l.ts,t):this.danglingReceipts.add(new SH(n,o,a,l,t))}}hasUserReadEvent(e,t){var n=this.unthreadedReceipts.get(e);if(n&&wb(n.eventId,t,this.room))return!0;var i=this.room.findEventById(t);if(!i)return S.warn("hasUserReadEvent event ID ".concat(t," not found in room ").concat(this.room.roomId,": this shouldn't happen!")),!1;var o=Tc(i),s=this.threadedReceipts.get(o,e);return!!(s&&wb(s.eventId,t,this.room)||this.userSentLatestEventInThread(o,e))}userSentLatestEventInThread(e,t){var n,i=e===bf?this.room.getLiveTimeline().getEvents():(n=this.room.getThread(e))===null||n===void 0?void 0:n.timeline;return!!(i&&i.length>0&&i[i.length-1].getSender()===t)}}class yH{constructor(e,t,n){this.eventId=e,this.receiptType=t,this.ts=n}}class SH{constructor(e,t,n,i,o){this.eventId=e,this.receiptType=t,this.userId=n,this.receipt=i,this.synthetic=o}}class bH{constructor(e){v(this,"room",void 0),v(this,"real",void 0),v(this,"synthetic",void 0),this.room=e,this.real=void 0,this.synthetic=void 0}set(e,t){e?this.synthetic=t:this.real=t,this.synthetic&&this.real&&wb(this.real.eventId,this.synthetic.eventId,this.room)&&(this.synthetic=void 0)}get(){var e;return(e=this.synthetic)!==null&&e!==void 0?e:this.real}getByType(e){return e?this.synthetic:this.real}}class MD{constructor(e){v(this,"room",void 0),v(this,"data",void 0),this.room=e,this.data=new Map}set(e,t,n,i,o){var s=vw(this.data,n,()=>new bH(this.room)),a=s.getByType(o);a&&wH(a.eventId,e,this.room)||s.set(o,new yH(e,t,i))}get(e){var t;return(t=this.data.get(e))===null||t===void 0?void 0:t.get()}}class _H{constructor(e){v(this,"room",void 0),v(this,"data",void 0),this.room=e,this.data=new Map}set(e,t,n,i,o,s){var a=vw(this.data,e,()=>new MD(this.room));a.set(t,n,i,o,s)}get(e,t){var n;return(n=this.data.get(e))===null||n===void 0?void 0:n.get(t)}}class EH{constructor(){v(this,"data",new Map)}add(e){var t=vw(this.data,e.eventId,()=>[]);t.push(e)}remove(e){var t=this.data.get(e);return this.data.delete(e),t}}function vw(r,e,t){var n=r.get(e);if(n)return n;var i=t();return r.set(e,i),i}function wb(r,e,t){var n=t.compareEventOrdering(r,e);return n!==null&&n>=0}function wH(r,e,t){var n=t.compareEventOrdering(r,e);return n!==null&&n>0}function TH(r,e,t){var n=r.findEventById(e),i=r.findEventById(t);if(!n||!i)return null;var o=Wd(n),s=Wd(i);return o&&s?RH(r,e,t,n,i):CH(e,t,n,i)}function RH(r,e,t,n,i){var o=r.getUnfilteredTimelineSet(),s=o.compareEventOrdering(e,t);if(s!==null)return s;var a=o.getTimelineForEvent(e);if(a===o.getLiveTimeline())return 1;var l=o.getTimelineForEvent(t);return l===o.getLiveTimeline()?-1:AD(n,i)}function CH(r,e,t,n){var i=Tc(t),o=Tc(n),s=t.getThread();return s&&i===o?s.timelineSet.compareEventOrdering(r,e):AD(t,n)}function AD(r,e){var t=r.getTs(),n=e.getTs();return t<n?-1:t>n?1:0}var Z=function(r){return r.Get="GET",r.Put="PUT",r.Post="POST",r.Delete="DELETE",r.Options="OPTIONS",r.Head="HEAD",r.Patch="PATCH",r}({});function vC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function kH(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?vC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):vC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class yc extends Error{constructor(e,t,n){super(e),this.httpStatus=t,this.httpHeaders=n}isRateLimitError(){return this.httpStatus===429}getRetryAfterMs(){var e,t=(e=this.httpHeaders)===null||e===void 0?void 0:e.get("Retry-After");if(t!=null){if(/^\d+$/.test(t)){var n=Number.parseInt(t)*1e3;if(!Number.isFinite(n))throw new Error("Retry-After header integer value is too large");return n}var i=new Date(t);if(i.toUTCString()!==t)throw new Error("Retry-After header value is not a valid HTTP-date or non-negative decimal integer");return i.getTime()-Date.now()}return null}}class hr extends yc{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,s=e.error||"Unknown message";t&&(s="[".concat(t,"] ").concat(s)),n&&(s="".concat(s," (").concat(n,")")),super("MatrixError: ".concat(s),t,o),this.url=n,this.event=i,v(this,"errcode",void 0),v(this,"data",void 0),this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.data=e}isRateLimitError(){return this.errcode==="M_LIMIT_EXCEEDED"||(this.errcode==="M_UNKNOWN"||this.errcode===void 0)&&super.isRateLimitError()}getRetryAfterMs(){var e=super.getRetryAfterMs();if(e!==null)return e;if(this.errcode==="M_LIMIT_EXCEEDED"&&"retry_after_ms"in this.data){if(!Number.isInteger(this.data.retry_after_ms))throw new Error("retry_after_ms is not an integer");return this.data.retry_after_ms}return null}asWidgetApiErrorData(){var e,t,n,i,o={};if(this.httpHeaders)for(var[s,a]of this.httpHeaders)o[s]=a;return{http_status:(e=this.httpStatus)!==null&&e!==void 0?e:400,http_headers:o,url:(t=this.url)!==null&&t!==void 0?t:"",response:kH({errcode:(n=this.errcode)!==null&&n!==void 0?n:"M_UNKNOWN",error:(i=this.data.error)!==null&&i!==void 0?i:"Unknown message"},this.data)}}static fromWidgetApiErrorData(e){return new hr(e.response,e.http_status,e.url,void 0,new Headers(e.http_headers))}}function mw(r,e){if(!(r instanceof yc)||!r.isRateLimitError())return e;try{var t;return(t=r.getRetryAfterMs())!==null&&t!==void 0?t:e}catch{return e}}class _f extends Error{constructor(e,t){super(e+(t?": ".concat(t.message):""))}get name(){return"ConnectionError"}}var Tb=function(r){return r.SessionLoggedOut="Session.logged_out",r.NoConsent="no_consent",r}({});/*!
277
+ * content-type
278
+ * Copyright(c) 2015 Douglas Christopher Wilson
279
+ * MIT Licensed
280
+ */var mC=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,IH=/\\([\u000b\u0020-\u00ff])/g,xH=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,OH=PH;function PH(r){if(!r)throw new TypeError("argument string is required");var e=typeof r=="object"?MH(r):r;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var t=e.indexOf(";"),n=t!==-1?e.slice(0,t).trim():e.trim();if(!xH.test(n))throw new TypeError("invalid media type");var i=new AH(n.toLowerCase());if(t!==-1){var o,s,a;for(mC.lastIndex=t;s=mC.exec(e);){if(s.index!==t)throw new TypeError("invalid parameter format");t+=s[0].length,o=s[1].toLowerCase(),a=s[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(IH,"$1"))),i.parameters[o]=a}if(t!==e.length)throw new TypeError("invalid parameter format")}return i}function MH(r){var e;if(typeof r.getHeader=="function"?e=r.getHeader("content-type"):typeof r.headers=="object"&&(e=r.headers&&r.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function AH(r){this.parameters=Object.create(null),this.type=r}function hm(r){var e=new AbortController;return setTimeout(()=>{e.abort()},r),e.signal}function DD(r){var e=new AbortController;function t(){for(var o of r)o.removeEventListener("abort",n)}function n(){e.abort(),t()}for(var i of r){if(i.aborted){n();break}i.addEventListener("abort",n)}return{signal:e.signal,cleanup:t}}function gw(r,e){var t,n,i=gC(r)?new Headers(r.getAllResponseHeaders().trim().split(/[\r\n]+/).map(s=>{var a=s.indexOf(":");return[s.substring(0,a),s.substring(a+1)]})):r.headers,o;try{o=DH(i)}catch(s){return s}return((t=o)===null||t===void 0?void 0:t.type)==="application/json"&&e?new hr(JSON.parse(e),r.status,gC(r)?r.responseURL:r.url,void 0,i):((n=o)===null||n===void 0?void 0:n.type)==="text/plain"?new yc("Server returned ".concat(r.status," error: ").concat(e),r.status,i):new yc("Server returned ".concat(r.status," error"),r.status,i)}function gC(r){return"getResponseHeader"in r}function DH(r){var e=r.get("Content-Type");if(e===null)return null;try{return OH(e)}catch(t){throw new Error("Error parsing Content-Type '".concat(e,"': ").concat(t))}}function ND(r,e){return Rb.apply(this,arguments)}function Rb(){return Rb=_(function*(r,e){for(var t=0,n=null;t<r;)try{if(t>0){var i=1e3*Math.pow(2,t);S.log("network operation failed ".concat(t," times, retrying in ").concat(i,"ms...")),yield As(i)}return yield e()}catch(o){if(o instanceof _f)t+=1,n=o;else throw o}throw n}),Rb.apply(this,arguments)}function LD(r,e,t){return e>4||r instanceof _f&&!t||r.httpStatus&&(r.httpStatus===400||r.httpStatus===403||r.httpStatus===401)||r.name==="AbortError"||r.name==="M_TOO_LARGE"?-1:mw(r,1e3*Math.pow(2,e))}function yC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Hg(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?yC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):yC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class NH{constructor(e,t){var n;this.eventEmitter=e,this.opts=t,v(this,"abortController",new AbortController),H1(t,["baseUrl","prefix"]),t.onlyData=!!t.onlyData,t.useAuthorizationHeader=(n=t.useAuthorizationHeader)!==null&&n!==void 0?n:!0}abort(){this.abortController.abort(),this.abortController=new AbortController}fetch(e,t){return this.opts.fetchFn?this.opts.fetchFn(e,t):globalThis.fetch(e,t)}setIdBaseUrl(e){this.opts.idBaseUrl=e}idServerRequest(e,t,n,i,o){if(!this.opts.idBaseUrl)throw new Error("No identity server base URL set");var s=void 0,a=void 0;e===Z.Get?s=n:a=n;var l=this.getUrl(t,s,i,this.opts.idBaseUrl),c={json:!0,headers:{}};return o&&(c.headers.Authorization="Bearer ".concat(o)),this.requestOtherUrl(e,l,a,c)}authedRequest(e,t,n,i){var o=arguments,s=this;return _(function*(){var a=o.length>4&&o[4]!==void 0?o[4]:{};n||(n={});var l=Hg({},a);s.opts.accessToken&&(s.opts.useAuthorizationHeader?(l.headers||(l.headers={}),l.headers.Authorization||(l.headers.Authorization="Bearer "+s.opts.accessToken),n.access_token&&delete n.access_token):n.access_token||(n.access_token=s.opts.accessToken));try{var c=yield s.request(e,t,n,i,l);return c}catch(f){var u=f;if(u.errcode==="M_UNKNOWN_TOKEN"&&!l.doNotAttemptTokenRefresh){var d=yield s.tryRefreshToken();if(d)return s.authedRequest(e,t,n,i,Hg(Hg({},a),{},{doNotAttemptTokenRefresh:!0}))}throw u.errcode=="M_UNKNOWN_TOKEN"&&!(l!=null&&l.inhibitLogoutEmit)?s.eventEmitter.emit(Tb.SessionLoggedOut,u):u.errcode=="M_CONSENT_NOT_GIVEN"&&s.eventEmitter.emit(Tb.NoConsent,u.message,u.data.consent_uri),u}})()}tryRefreshToken(){var e=this;return _(function*(){if(!e.opts.refreshToken||!e.opts.tokenRefreshFunction)return!1;try{var{accessToken:t,refreshToken:n}=yield e.opts.tokenRefreshFunction(e.opts.refreshToken);return e.opts.accessToken=t,e.opts.refreshToken=n,!0}catch(o){var i;return(i=e.opts.logger)===null||i===void 0||i.warn("Failed to refresh token",o),!1}})()}request(e,t,n,i,o){var s=this.getUrl(t,n,o==null?void 0:o.prefix,o==null?void 0:o.baseUrl);return this.requestOtherUrl(e,s,i,o)}requestOtherUrl(e,t,n){var i=arguments,o=this;return _(function*(){var s,a,l,c,u,d=i.length>3&&i[3]!==void 0?i[3]:{},f=o.sanitizeUrlForLogs(t);(s=o.opts.logger)===null||s===void 0||s.debug("FetchHttpApi: --> ".concat(e," ").concat(f));var p=Object.assign({},d.headers||{}),h=(a=d.json)!==null&&a!==void 0?a:!0,m=h&&(n==null||(l=n.constructor)===null||l===void 0?void 0:l.name)===Object.name;h&&(m&&!p["Content-Type"]&&(p["Content-Type"]="application/json"),p.Accept||(p.Accept="application/json"));var w=(c=d.localTimeoutMs)!==null&&c!==void 0?c:o.opts.localTimeoutMs,g=(u=d.keepAlive)!==null&&u!==void 0?u:!1,b=[o.abortController.signal];w!==void 0&&b.push(hm(w)),d.abortSignal&&b.push(d.abortSignal);var R;m?R=JSON.stringify(n):R=n;var{signal:k,cleanup:O}=DD(b),T,x=Date.now();try{var C;T=yield o.fetch(t,{signal:k,method:e,body:R,headers:p,mode:"cors",redirect:"follow",referrer:"",referrerPolicy:"no-referrer",cache:"no-cache",credentials:"omit",keepalive:g,priority:d.priority}),(C=o.opts.logger)===null||C===void 0||C.debug("FetchHttpApi: <-- ".concat(e," ").concat(f," [").concat(Date.now()-x,"ms ").concat(T.status,"]"))}catch(F){var N;throw(N=o.opts.logger)===null||N===void 0||N.debug("FetchHttpApi: <-- ".concat(e," ").concat(f," [").concat(Date.now()-x,"ms ").concat(F,"]")),F.name==="AbortError"?F:new _f("fetch failed",F)}finally{O()}if(!T.ok)throw gw(T,yield T.text());return o.opts.onlyData?h?T.json():T.text():T})()}sanitizeUrlForLogs(e){try{var t;typeof e=="string"?t=new URL(e):t=e;var n=new URLSearchParams;for(var i of t.searchParams.keys())n.append(i,"xxx");var o=n.toString(),s=o?"?".concat(o):"";return t.origin+t.pathname+s}catch{return"??"}}getUrl(e,t,n,i){var o=i??this.opts.baseUrl,s=o.endsWith("/")?o.slice(0,-1):o,a=new URL(s+(n??this.opts.prefix)+e);return t&&lb(t,a.searchParams),a}}var Ot=function(r){return r.V1="/_matrix/client/v1",r.V3="/_matrix/client/v3",r.Unstable="/_matrix/client/unstable",r}({}),fo=function(r){return r.V2="/_matrix/identity/v2",r}({}),Jl=function(r){return r.V1="/_matrix/media/v1",r.V3="/_matrix/media/v3",r}({}),LH=1e3,UH=0,zg,Eo=[],jH=function(){};function SC(r,e){for(var t=arguments.length,n=new Array(t>2?t-2:0),i=2;i<t;i++)n[i-2]=arguments[i];e=e||0,e<0&&(e=0);var o=Date.now()+e,s=UH++,a={runAt:o,func:r,params:n,key:s},l=BH(Eo,function(c){return c.runAt-o});return Eo.splice(l,0,a),yw(),s}function bC(r){if(Eo.length!==0){var e;for(e=0;e<Eo.length;e++){var t=Eo[e];if(t.key==r){Eo.splice(e,1);break}}e===0&&yw()}}function yw(){zg&&globalThis.clearTimeout(zg);var r=Eo[0];if(r){var e=Date.now(),t=Math.min(r.runAt-e,LH);zg=globalThis.setTimeout(FH,t)}}function FH(){for(var r=Date.now(),e=[];;){var t=Eo[0];if(!t||t.runAt>r)break;var n=Eo.shift();jH("runCallbacks: popping",n.key),e.push(n)}yw();for(var i of e)try{i.func.apply(globalThis,i.params)}catch(o){S.error("Uncaught exception in callback function",o)}}function BH(r,e){for(var t=0,n=r.length;t<n;){var i=t+n>>1,o=e(r[i]);o>0?n=i:t=i+1}return t}class UD extends NH{constructor(){super(...arguments),v(this,"uploads",[])}uploadContent(e){var t,n,i,o,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=(t=s.includeFilename)!==null&&t!==void 0?t:!0,l=(n=s.abortController)!==null&&n!==void 0?n:new AbortController,c=((i=s.type)!==null&&i!==void 0?i:e.type)||"application/octet-stream",u=(o=s.name)!==null&&o!==void 0?o:e.name,d={loaded:0,total:0,abortController:l},f=Gs();if(globalThis.XMLHttpRequest){var p=new globalThis.XMLHttpRequest,h=function(){p.abort(),f.reject(new Error("Timeout"))},m=SC(h,3e4);p.onreadystatechange=function(){switch(p.readyState){case globalThis.XMLHttpRequest.DONE:bC(m);try{if(p.status===0)throw new DOMException(p.statusText,"AbortError");if(!p.responseText)throw new Error("No response body.");p.status>=400?f.reject(gw(p,p.responseText)):f.resolve(JSON.parse(p.responseText))}catch(R){if(R.name==="AbortError"){f.reject(R);return}f.reject(new _f("request failed",R))}break}},p.upload.onprogress=R=>{var k;bC(m),d.loaded=R.loaded,d.total=R.total,m=SC(h,3e4),(k=s.progressHandler)===null||k===void 0||k.call(s,{loaded:R.loaded,total:R.total})};var w=this.getUrl("/upload",void 0,Jl.V3);a&&u&&w.searchParams.set("filename",encodeURIComponent(u)),!this.opts.useAuthorizationHeader&&this.opts.accessToken&&w.searchParams.set("access_token",encodeURIComponent(this.opts.accessToken)),p.open(Z.Post,w.href),this.opts.useAuthorizationHeader&&this.opts.accessToken&&p.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),p.setRequestHeader("Content-Type",c),p.send(e),l.signal.addEventListener("abort",()=>{p.abort()})}else{var g={};a&&u&&(g.filename=u);var b={"Content-Type":c};this.authedRequest(Z.Post,"/upload",g,e,{prefix:Jl.V3,headers:b,abortSignal:l.signal}).then(R=>this.opts.onlyData?R:R.json()).then(f.resolve,f.reject)}return d.promise=f.promise.finally(()=>{zp(this.uploads,R=>R===d)}),l.signal.addEventListener("abort",()=>{zp(this.uploads,R=>R===d),f.reject(new DOMException("Aborted","AbortError"))}),this.uploads.push(d),d.promise}cancelUpload(e){var t=this.uploads.find(n=>n.promise===e);return t?(t.abortController.abort(),!0):!1}getCurrentUploads(){return this.uploads}getContentUri(){return{base:this.opts.baseUrl,path:Jl.V3+"/upload",params:{access_token:this.opts.accessToken}}}}var KH=6*60*60*1e3,VH=30*1e3,jD=function(r){return r.Stable="stable",r.Unstable="unstable",r}({});class FD{constructor(e){var t=this;this.http=e,v(this,"capabilities",void 0),v(this,"retryTimeout",void 0),v(this,"refreshTimeout",void 0),v(this,"fetchCapabilities",_(function*(){var n=yield t.http.authedRequest(Z.Get,"/capabilities");return t.capabilities=n.capabilities,t.capabilities})),v(this,"poll",_(function*(){try{yield t.fetchCapabilities(),t.clearTimeouts(),t.refreshTimeout=setTimeout(t.poll,KH),S.debug("Fetched new server capabilities")}catch(i){t.clearTimeouts();var n=Math.floor(VH+Math.random()*5e3);t.retryTimeout=setTimeout(t.poll,n),S.warn("Failed to refresh capabilities: retrying in ".concat(n,"ms"),i)}}))}start(){this.poll().then()}stop(){this.clearTimeouts()}getCachedCapabilities(){return this.capabilities}clearTimeouts(){this.refreshTimeout&&(clearInterval(this.refreshTimeout),this.refreshTimeout=void 0),this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=void 0)}}function _C(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function uu(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?_C(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):_C(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var BD="10",$H=["1","2","3","4","5","6","7","8","9","10"],WH=30,it=function(r){return r.Highlight="highlight",r.Total="total",r}({}),fe=function(r){return r.MyMembership="Room.myMembership",r.Tags="Room.tags",r.AccountData="Room.accountData",r.Receipt="Room.receipt",r.Name="Room.name",r.Redaction="Room.redaction",r.RedactionCancelled="Room.redactionCancelled",r.LocalEchoUpdated="Room.localEchoUpdated",r.Timeline="Room.timeline",r.TimelineReset="Room.timelineReset",r.TimelineRefresh="Room.TimelineRefresh",r.OldStateUpdated="Room.OldStateUpdated",r.CurrentStateUpdated="Room.CurrentStateUpdated",r.HistoryImportedWithinTimeline="Room.historyImportedWithinTimeline",r.UnreadNotifications="Room.UnreadNotifications",r.Summary="Room.Summary",r}({});class pm extends xD{constructor(e,t,n){var i,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),i=this,this.roomId=e,this.client=t,this.myUserId=n,this.opts=o,v(this,"reEmitter",void 0),v(this,"txnToEvent",new Map),v(this,"notificationCounts",{}),v(this,"threadNotifications",new Map),v(this,"cachedThreadReadReceipts",new Map),v(this,"oldestThreadedReceiptTs",1/0),v(this,"unthreadedReceipts",new Map),v(this,"timelineSets",void 0),v(this,"polls",new Map),v(this,"threadsTimelineSets",[]),v(this,"filteredTimelineSets",{}),v(this,"timelineNeedsRefresh",!1),v(this,"pendingEventList",void 0),v(this,"blacklistUnverifiedDevices",void 0),v(this,"selfMembership",void 0),v(this,"summaryHeroes",null),v(this,"getTypeWarning",!1),v(this,"getVersionWarning",!1),v(this,"membersPromise",void 0),v(this,"name",void 0),v(this,"normalizedName",void 0),v(this,"tags",{}),v(this,"accountData",new Map),v(this,"summary",null),v(this,"oldState",void 0),v(this,"currentState",void 0),v(this,"relations",void 0),v(this,"threads",new Map),v(this,"visibilityEvents",new Map),v(this,"roomReceipts",new gH(this)),v(this,"threadTimelineSetsPromise",null),v(this,"threadsReady",!1),v(this,"updateThreadRootEvents",(s,a,l)=>{if(s.length){var c;if(this.updateThreadRootEvent((c=this.threadsTimelineSets)===null||c===void 0?void 0:c[0],s,a,l),s.hasCurrentUserParticipated){var u;this.updateThreadRootEvent((u=this.threadsTimelineSets)===null||u===void 0?void 0:u[1],s,a,l)}}}),v(this,"updateThreadRootEvent",(s,a,l,c)=>{s&&a.rootEvent&&(c&&s.removeEvent(a.id),Et.hasServerSideSupport?s.addLiveEvent(a.rootEvent,{duplicateStrategy:ed.Replace,fromCache:!1,roomState:this.currentState}):s.addEventToTimeline(a.rootEvent,s.getLiveTimeline(),{toStartOfTimeline:l}))}),v(this,"applyRedaction",s=>{if(s.isRedaction()){var a=s.event.redacts,l=a?this.findEventById(a):void 0;if(l){var c=l.threadRootId;if(l.makeRedacted(s,this),l.isState()){var u=this.currentState.getStateEvents(l.getType(),l.getStateKey());(u==null?void 0:u.getId())===l.getId()&&this.currentState.setStateEvents([l])}this.emit(fe.Redaction,s,this,c),this.visibilityEvents.delete(a),l.isVisibilityEvent()&&this.redactVisibilityChangeEvent(s)}}}),this.setMaxListeners(100),this.reEmitter=new Bc(this),o.pendingEventOrdering=o.pendingEventOrdering||wc.Chronological,this.name=e,this.normalizedName=e,this.relations=new pD(this.client,this),this.on(fe.Receipt,this.onReceipt),this.timelineSets=[new Ul(this,o)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[fe.Timeline,fe.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===wc.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then(s=>{var a=this.client.getEventMapper({toDevice:!1,decrypt:!1});s.forEach(function(){var l=_(function*(c){var u=a(c);yield t.decryptEventIfNeeded(u),u.setStatus(je.NOT_SENT),i.addPendingEvent(u,u.getTxnId())});return function(c){return l.apply(this,arguments)}}())})),this.opts.lazyLoadMembers?this.membersPromise=void 0:this.membersPromise=Promise.resolve(!1)}createThreadsTimelineSets(){var e=this;return _(function*(){var t;if(e.threadTimelineSetsPromise)return e.threadTimelineSetsPromise;if((t=e.client)!==null&&t!==void 0&&t.supportsThreads())try{e.threadTimelineSetsPromise=Promise.all([e.createThreadTimelineSet(),e.createThreadTimelineSet(di.My)]);var n=yield e.threadTimelineSetsPromise;return e.threadsTimelineSets[0]=n[0],e.threadsTimelineSets[1]=n[1],n}catch{return e.threadTimelineSetsPromise=null,null}return null})()}decryptCriticalEvents(){var e=this;return _(function*(){if(e.client.isCryptoEnabled()){var t=e.getEventReadUpTo(e.client.getUserId(),!0),n=e.getLiveTimeline().getEvents(),i=n.findIndex(s=>s.event.event_id===t),o=n.slice(i).reverse().map(s=>e.client.decryptEventIfNeeded(s));yield Promise.allSettled(o)}})()}decryptAllEvents(){var e=this;return _(function*(){if(e.client.isCryptoEnabled()){var t=e.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0).reverse().map(n=>e.client.decryptEventIfNeeded(n));yield Promise.allSettled(t)}})()}getCreator(){var e,t=this.currentState.getStateEvents(V.RoomCreate,"");return(e=t==null?void 0:t.getSender())!==null&&e!==void 0?e:null}getVersion(){var e,t=this.currentState.getStateEvents(V.RoomCreate,"");return t?(e=t.getContent().room_version)!==null&&e!==void 0?e:"1":(this.getVersionWarning||(S.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}getRecommendedVersion(){var e=this;return _(function*(){var t={};try{t=yield e.client.getCapabilities()}catch{}var n=t["m.room_versions"];if(!n){n={default:BD,available:{}};for(var i of $H)n.available[i]=jD.Stable}var o=e.checkVersionAgainstCapability(n);if(o.urgent&&o.needsUpgrade){S.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");try{t=yield e.client.fetchCapabilities()}catch(s){S.warn("Failed to refresh room version capabilities",s)}if(n=t["m.room_versions"],n)o=e.checkVersionAgainstCapability(n);else return S.warn("No room version capability - assuming upgrade required."),o}return o})()}checkVersionAgainstCapability(e){var t=this.getVersion();S.log("[".concat(this.roomId,"] Current version: ").concat(t)),S.log("[".concat(this.roomId,"] Version capability: "),e);var n={version:t,needsUpgrade:!1,urgent:!1};if(t===e.default)return n;var i=Object.keys(e.available).filter(o=>e.available[o]==="stable");return i.includes(t)||(n.version=e.default,n.needsUpgrade=!0,n.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),n.urgent?S.warn("URGENT upgrade required on ".concat(this.roomId)):S.warn("Non-urgent upgrade required on ".concat(this.roomId))),n}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(V.RoomTombstone,e)}getPendingEvents(){if(!this.pendingEventList)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(!this.pendingEventList)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);var t=zp(this.pendingEventList,function(n){return n.getId()==e},!1);return this.savePendingEvents(),t}hasPendingEvent(e){var t,n;return(t=(n=this.pendingEventList)===null||n===void 0?void 0:n.some(i=>i.getId()===e))!==null&&t!==void 0?t:!1}getPendingEvent(e){var t,n;return(t=(n=this.pendingEventList)===null||n===void 0?void 0:n.find(i=>i.getId()===e))!==null&&t!==void 0?t:null}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}get timeline(){return this.getLiveTimeline().getEvents()}getLastActiveTimestamp(){var e=this.getLiveTimeline(),t=e.getEvents();if(t.length){var n=t[t.length-1];return n.getTs()}else return Number.MIN_SAFE_INTEGER}getLastLiveEvent(){var e,t,n=this.getLiveTimeline().getEvents(),i=n[n.length-1],o=this.getLastThread();if(!o)return i;var s=o.events[o.events.length-1];return((e=i==null?void 0:i.getTs())!==null&&e!==void 0?e:0)>((t=s==null?void 0:s.getTs())!==null&&t!==void 0?t:0)?i:s}getLastThread(){return this.getThreads().reduce((e,t)=>{var n,i;if(!e)return t;var o=t.events[t.events.length-1],s=e.events[e.events.length-1];return((n=o==null?void 0:o.getTs())!==null&&n!==void 0?n:0)>=((i=s==null?void 0:s.getTs())!==null&&i!==void 0?i:0)?t:e},void 0)}getMyMembership(){var e;return(e=this.selfMembership)!==null&&e!==void 0?e:Be.Leave}getDMInviter(){var e=this.getMember(this.myUserId);if(e)return e.getDMInviter();if(this.selfMembership===Be.Invite){var t=this.getInvitedAndJoinedMemberCount();if(t===2){var n;return(n=this.summaryHeroes)===null||n===void 0?void 0:n[0]}}}guessDMUserId(){var e=this.getMember(this.myUserId);if(e){var t=e.getDMInviter();if(t)return t}if(Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length)return this.summaryHeroes[0];var n=this.currentState.getMembers(),i=n.find(o=>o.userId!==this.myUserId);return i?i.userId:this.myUserId}getFunctionalMembers(){var e=this.currentState.getStateEvents(uD.name,"");return Array.isArray(e==null?void 0:e.getContent().service_members)?e.getContent().service_members:[]}getAvatarFallbackMember(){var e,t=this.getFunctionalMembers(),n=0;if(this.getMembers().forEach(f=>{f.membership!=="join"&&f.membership!=="invite"||t.includes(f.userId)||n++}),!(n>2)){var i=(e=this.summaryHeroes)===null||e===void 0?void 0:e.filter(f=>!t.includes(f)),o=Array.isArray(i)&&i.length;if(o){var s=i.map(f=>this.getMember(f)).find(f=>!!f);if(s)return s}var a=this.getMembers(),l=a==null?void 0:a.filter(f=>!t.includes(f.userId));if(l.length<=2){var c=l.find(f=>f.userId!==this.myUserId);if(c)return c}if(o){var u=i.map(f=>this.client.getUser(f)).find(f=>!!f);if(u){var d=new Zp(this.roomId,u.userId);return d.user=u,d}}}}updateMyMembership(e){var t=this.selfMembership;this.selfMembership=e,t!==e&&(e===Be.Leave&&this.cleanupAfterLeaving(),this.emit(fe.MyMembership,this,e,t))}loadMembersFromServer(){var e=this;return _(function*(){var t=e.client.store.getSyncToken(),n=yield e.client.members(e.roomId,void 0,Be.Leave,t??void 0);return n.chunk})()}loadMembers(){var e=this;return _(function*(){var t=!1,n=yield e.client.store.getOutOfBandMembers(e.roomId);(n===null||e.hasEncryptionStateEvent())&&(t=!0,n=yield e.loadMembersFromServer(),S.log("LL: got ".concat(n.length," ")+"members from server for room ".concat(e.roomId)));var i=n.filter(mi).map(e.client.getEventMapper());return{memberEvents:i,fromServer:t}})()}membersLoaded(){return this.opts.lazyLoadMembers?this.currentState.outOfBandMembersReady():!0}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();var e=this.loadMembers().then(t=>(this.currentState.setOutOfBandMembers(t.memberEvents),t.fromServer)).catch(t=>{throw this.membersPromise=void 0,this.currentState.markOutOfBandMembersFailed(),t});return e.then(t=>{if(t){var n=this.currentState.getMembers().filter(o=>o.isOutOfBand()).map(o=>{var s;return(s=o.events.member)===null||s===void 0?void 0:s.event});S.log("LL: telling store to write ".concat(n.length)+" members for room ".concat(this.roomId));var i=this.client.store;return i.setOutOfBandMembers(this.roomId,n).catch(o=>{S.log("LL: storing OOB room members failed, oh well",o)})}}).catch(t=>{S.error(t)}),this.membersPromise=e,this.membersPromise}clearLoadedMembersIfNeeded(){var e=this;return _(function*(){e.opts.lazyLoadMembers&&e.membersPromise&&(yield e.loadMembersIfNeeded(),yield e.client.store.clearOutOfBandMembers(e.roomId),e.currentState.clearOutOfBandMembers(),e.membersPromise=void 0)})()}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch(e=>{S.error("error after clearing loaded members from "+"room ".concat(this.roomId," after leaving")),S.log(e)})}refreshLiveTimeline(){var e=this;return _(function*(){var t=e.getLiveTimeline(),n=t.getPaginationToken(Ee.FORWARDS),i=t.getPaginationToken(Ee.BACKWARDS),o=t.getEvents(),s=o[o.length-1];S.log("[refreshLiveTimeline for ".concat(e.roomId,"] at ")+"mostRecentEventInTimeline=".concat(s&&s.getId()," ")+"liveTimelineBefore=".concat(t.toString()," ")+"forwardPaginationToken=".concat(n," ")+"backwardPaginationToken=".concat(i));var a=e.getUnfilteredTimelineSet(),l;s?(e.resetLiveTimeline(null,null),e.emit(fe.TimelineRefresh,e,a),l=yield e.client.getEventTimeline(a,s.getId())):l=yield e.client.getLatestTimeline(a);var c=a.getLiveTimeline();!c||c.getPaginationToken(Ge.Forward)===null&&c.getPaginationToken(Ge.Backward)===null&&c.getEvents().length===0?(S.log("[refreshLiveTimeline for ".concat(e.roomId,"] using our new live timeline")),l.setPaginationToken(n,Ee.FORWARDS),a.setLiveTimeline(l),e.fixUpLegacyTimelineFields()):S.log("[refreshLiveTimeline for ".concat(e.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."),e.setTimelineNeedsRefresh(!1),e.emit(fe.TimelineRefresh,e,a)})()}resetLiveTimeline(e,t){for(var n of this.timelineSets)n.resetLiveTimeline(e??void 0,t??void 0);for(var i of this.threads.values())i.resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){var e=this.oldState,t=this.currentState;this.oldState=this.getLiveTimeline().getState(Ee.BACKWARDS),this.currentState=this.getLiveTimeline().getState(Ee.FORWARDS),e!==this.oldState&&this.emit(fe.OldStateUpdated,this,e,this.oldState),t!==this.currentState&&(this.emit(fe.CurrentStateUpdated,this,t,this.currentState),this.reEmitter.stopReEmitting(t,[Ne.Events,Ne.Members,Ne.NewMember,Ne.Update,Ne.Marker,kt.New,kt.Update,kt.Destroy,kt.LivenessChange]),this.reEmitter.reEmit(this.currentState,[Ne.Events,Ne.Members,Ne.NewMember,Ne.Update,Ne.Marker,kt.New,kt.Update,kt.Destroy,kt.LivenessChange]))}onReceipt(e){this.hasEncryptionStateEvent()&&this.clearNotificationsOnReceipt(e)}clearNotificationsOnReceipt(e){var t=[],n=!1,i=e.getContent();for(var o of Object.values(i))for(var[s,a]of Object.entries(o))if(uw(s)&&a){for(var[l,c]of Object.entries(a))if(!(!c||typeof c!="object")){var u=c;l===this.client.getUserId()&&(u.thread_id===void 0?n=!0:typeof u.thread_id=="string"&&t.push(u.thread_id))}}n&&(t=this.getThreads().filter(O=>this.getThreadUnreadNotificationCount(O.id,it.Total)>0||this.getThreadUnreadNotificationCount(O.id,it.Highlight)>0).map(O=>O.id),t.push("main"));for(var d of t){var f,p=20,h=d==="main"?this.getLiveTimeline():(f=this.getThread(d))===null||f===void 0?void 0:f.liveTimeline;if(!h){S.warn("Couldn't find timeline for thread ID ".concat(d," in room ").concat(this.roomId));continue}for(var m=h.getEvents(),w=0,g=m.length-1;g>=0;g--){var b;if(g===m.length-p)return;var R=m[g];if(this.hasUserReadEvent(this.client.getUserId(),R.getId()))break;var k=this.client.getPushActionsForEvent(R);w+=k!=null&&(b=k.tweaks)!==null&&b!==void 0&&b.highlight?1:0}d==="main"?this.setUnreadNotificationCount(it.Highlight,w):this.setThreadUnreadNotificationCount(d,it.Highlight,w)}}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){var t=this.findEventById(e),n=this.findThreadForEvent(t);return n?n.timelineSet.getTimelineForEvent(e):this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(e){this.timelineNeedsRefresh=e}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(e){var t=this.getUnfilteredTimelineSet().findEventById(e);if(!t)for(var n=this.getThreads(),i=0;i<n.length;i++){var o=n[i];if(t=o.findEventById(e),t)return t}return t}getUnreadNotificationCount(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:it.Total,t=this.getRoomUnreadNotificationCount(e);for(var n of this.threadNotifications.values()){var i;t+=(i=n[e])!==null&&i!==void 0?i:0}return t}getUnreadCountForEventContext(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:it.Total,n=arguments.length>1?arguments[1]:void 0,i=!!n.threadRootId&&!n.isThreadRoot;return(e=i?this.getThreadUnreadNotificationCount(n.threadRootId,t):this.getRoomUnreadNotificationCount(t))!==null&&e!==void 0?e:0}getRoomUnreadNotificationCount(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:it.Total;return(e=this.notificationCounts[t])!==null&&e!==void 0?e:0}getThreadUnreadNotificationCount(e){var t,n,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:it.Total;return(t=(n=this.threadNotifications.get(e))===null||n===void 0?void 0:n[i])!==null&&t!==void 0?t:0}hasThreadUnreadNotification(){for(var e of this.threadNotifications.values()){var t,n;if(((t=e.highlight)!==null&&t!==void 0?t:0)>0||((n=e.total)!==null&&n!==void 0?n:0)>0)return!0}return!1}setThreadUnreadNotificationCount(e,t,n){var i,o,s=uu({highlight:(i=this.threadNotifications.get(e))===null||i===void 0?void 0:i.highlight,total:(o=this.threadNotifications.get(e))===null||o===void 0?void 0:o.total},{[t]:n});this.threadNotifications.set(e,s),this.emit(fe.UnreadNotifications,s,e)}get threadsAggregateNotificationType(){var e=null;for(var t of this.threadNotifications.values()){var n,i;if(((n=t.highlight)!==null&&n!==void 0?n:0)>0)return it.Highlight;((i=t.total)!==null&&i!==void 0?i:0)>0&&!e&&(e=it.Total)}return e}resetThreadUnreadNotificationCountFromSync(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=this.hasEncryptionStateEvent();for(var[n,i]of this.threadNotifications)e.includes(n)||(i.total=0,t||(i.highlight=0));this.emit(fe.UnreadNotifications)}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t,this.emit(fe.UnreadNotifications,this.notificationCounts)}setUnread(e,t){return this.setUnreadNotificationCount(e,t)}setSummary(e){var t=e["m.heroes"],n=e["m.joined_member_count"],i=e["m.invited_member_count"];Number.isInteger(n)&&this.currentState.setJoinedMemberCount(n),Number.isInteger(i)&&this.currentState.setInvitedMemberCount(i),Array.isArray(t)&&(this.summaryHeroes=t.filter(o=>o!==this.myUserId)),this.emit(fe.Summary,e)}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return this.blacklistUnverifiedDevices===void 0?null:this.blacklistUnverifiedDevices}getAvatarUrl(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,s=this.currentState.getStateEvents(V.RoomAvatar,"");if(!s&&!o)return null;var a=s?s.getContent().url:null;return a?um(e,a,t,n,i):null}getMxcAvatarUrl(){var e;return((e=this.currentState.getStateEvents(V.RoomAvatar,""))===null||e===void 0||(e=e.getContent())===null||e===void 0?void 0:e.url)||null}getCanonicalAlias(){var e=this.currentState.getStateEvents(V.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){var e=this.currentState.getStateEvents(V.RoomCanonicalAlias,"");return e?e.getContent().alt_aliases||[]:[]}addEventsToTimeline(e,t,n,i){n.getTimelineSet().addEventsToTimeline(e,t,n,i)}getThread(e){var t;return(t=this.threads.get(e))!==null&&t!==void 0?t:null}getThreads(){return Array.from(this.threads.values())}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership(Be.Join)}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter(function(t){return t.membership===e})}getEncryptionTargetMembers(){var e=this;return _(function*(){yield e.loadMembersIfNeeded();var t=e.getMembersWithMembership(Be.Join);return e.shouldEncryptForInvitedMembers()&&(t=t.concat(e.getMembersWithMembership(Be.Invite))),t})()}shouldEncryptForInvitedMembers(){var e,t=this.currentState.getStateEvents(V.RoomHistoryVisibility,"");return(t==null||(e=t.getContent())===null||e===void 0?void 0:e.history_visibility)!=="joined"}getDefaultRoomName(e){return this.calculateRoomName(e,!0)}hasMembershipState(e,t){var n=this.getMember(e);return n?n.membership===t:!1}getOrCreateFilteredTimelineSet(e){var{prepopulateTimeline:t=!0,useSyncEvents:n=!0,pendingEvents:i=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];var o=Object.assign({filter:e,pendingEvents:i},this.opts),s=new Ul(this,o);this.reEmitter.reEmit(s,[fe.Timeline,fe.TimelineReset]),n&&(this.filteredTimelineSets[e.filterId]=s,this.timelineSets.push(s));var a=this.getLiveTimeline();if(t){a.getEvents().forEach(function(u){s.addLiveEvent(u)});for(var l=a;l.getNeighbouringTimeline(Ee.BACKWARDS);)l=l.getNeighbouringTimeline(Ee.BACKWARDS);s.getLiveTimeline().setPaginationToken(l.getPaginationToken(Ee.BACKWARDS),Ee.BACKWARDS)}else if(n){var c=a.getPaginationToken(Ge.Forward);s.getLiveTimeline().setPaginationToken(c,Ge.Backward)}return s}getThreadListFilter(){var e=arguments,t=this;return _(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:di.All,i=t.client.getUserId(),o=new gn(i),s={room:{timeline:{[rc.name]:[vt.name]}}};n===di.My&&(s.room.timeline[tc.name]=[i]),o.setDefinition(s);var a=yield t.client.getOrCreateFilter("THREAD_PANEL_".concat(t.roomId,"_").concat(n),o);return o.filterId=a,o})()}createThreadTimelineSet(e){var t=this;return _(function*(){var n;if(Et.hasServerSideListSupport)n=new Ul(t,uu(uu({},t.opts),{},{pendingEvents:!1}),void 0,void 0,e??di.All),t.reEmitter.reEmit(n,[fe.Timeline,fe.TimelineReset]);else if(Et.hasServerSideSupport){var i=yield t.getThreadListFilter(e);n=t.getOrCreateFilteredTimelineSet(i,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else n=new Ul(t,{pendingEvents:!1}),Array.from(t.threads).forEach(o=>{var[,s]=o;if(s.length!==0){var a=s.timeline.some(l=>l.getSender()===t.client.getUserId());(e!==di.My||a)&&n.getLiveTimeline().addEvent(s.rootEvent,{toStartOfTimeline:!1})}});return n})()}processThreadRoots(e,t){if(this.client.supportsThreads())for(var n of e)Ee.setEventMetadata(n,this.currentState,t),this.getThread(n.getId())||this.createThread(n.getId(),n,[],t)}fetchRoomThreads(){var e=this;return _(function*(){if(!(e.threadsReady||!e.client.supportsThreads())){if(Et.hasServerSideListSupport)yield Promise.all([e.fetchRoomThreadList(di.All),e.fetchRoomThreadList(di.My)]);else{var t=yield e.getThreadListFilter(),{chunk:n}=yield e.client.createMessagesRequest(e.roomId,"",Number.MAX_SAFE_INTEGER,Ge.Backward,t);if(!n.length)return;var i=n.map(e.client.getEventMapper()).sort((f,p)=>{var h=f.getServerAggregatedRelation(vt.name),m=p.getServerAggregatedRelation(vt.name);return h.latest_event.origin_server_ts-m.latest_event.origin_server_ts}),o,s=e.getLiveTimeline().getState(Ee.FORWARDS);for(var a of i){var l,c={duplicateStrategy:ed.Ignore,fromCache:!1,roomState:s};(l=e.threadsTimelineSets[0])===null||l===void 0||l.addLiveEvent(a,c);var u=a.getServerAggregatedRelation(vt.name);if(u!=null&&u.current_user_participated){var d;(d=e.threadsTimelineSets[1])===null||d===void 0||d.addLiveEvent(a,c),o=a}}e.processThreadRoots(i,!0),e.client.decryptEventIfNeeded(i[i.length-1]),o&&e.client.decryptEventIfNeeded(o)}e.on(Xr.NewReply,e.onThreadReply),e.on(Xr.Update,e.onThreadUpdate),e.on(Xr.Delete,e.onThreadDelete),e.threadsReady=!0}})()}processPollEvents(e){var t=this;return _(function*(){for(var n of e)try{if(!n.isEncrypted()&&!PD(n))continue;yield t.client.decryptEventIfNeeded(n),t.processPollEvent(n)}catch(i){S.warn("Error processing poll event",n.getId(),i)}})()}processPollEvent(e){var t=this;return _(function*(){if(e.isDecryptionFailure()){e.once(ot.Decrypted,s=>{t.processPollEvent(s)});return}if(ln.M_POLL_START.matches(e.getType())){try{var n=new OD(e,t.client,t);t.polls.set(e.getId(),n),t.emit(cs.New,n),e.once(ot.BeforeRedaction,s=>{t.polls.delete(s.getId())})}catch{}return}var i=e.relationEventId;if(i&&t.polls.has(i)){var o=t.polls.get(i);o==null||o.onNewRelation(e)}})()}fetchRoomThreadList(e){var t=this;return _(function*(){if(t.client.supportsThreads()&&t.threadsTimelineSets.length!==0){var n=e===di.My?t.threadsTimelineSets[1]:t.threadsTimelineSets[0],{chunk:i,end:o}=yield t.client.createThreadListMessagesRequest(t.roomId,null,void 0,Ge.Backward,n.threadListType,n.getFilter());if(n.getLiveTimeline().setPaginationToken(o??null,Ge.Backward),!!i.length){var s=i.map(t.client.getEventMapper());t.processThreadRoots(s,!0);var a=t.getLiveTimeline().getState(Ee.FORWARDS);for(var l of s)n.addLiveEvent(l,{duplicateStrategy:ed.Replace,fromCache:!1,roomState:a})}}})()}onThreadUpdate(e){this.updateThreadRootEvents(e,!1,!1)}onThreadReply(e){this.updateThreadRootEvents(e,!1,!0)}onThreadDelete(e){var t;this.threads.delete(e.id);var n=this.getTimelineForEvent(e.id),i=n==null||(t=n.getEvents())===null||t===void 0?void 0:t.find(s=>s.getId()===e.id);i?e.clearEventMetadata(i):S.debug("onThreadDelete: Could not find root event in room timeline");for(var o of this.threadsTimelineSets)o.removeEvent(e.id)}removeFilteredTimelineSet(e){var t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];var n=this.timelineSets.indexOf(t);n>-1&&this.timelineSets.splice(n,1)}eventShouldLiveIn(e,t,n){var i;if(!((i=this.client)!==null&&i!==void 0&&i.supportsThreads()))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||n!=null&&n.has(e.getId()))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};var o=e.isRelation(vt.name),s=e.getAssociatedId(),a=e.threadRootId;if(s&&!o&&(a===s||n!=null&&n.has(s)))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};var l;if(s){var c;l=(c=this.findEventById(s))!==null&&c!==void 0?c:t==null?void 0:t.find(u=>u.getId()===s)}return l&&!o?this.eventShouldLiveIn(l,t,n):a!=null?{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:a}:!s||e.replyEventId?{shouldLiveInRoom:!0,shouldLiveInThread:!1}:{shouldLiveInRoom:!1,shouldLiveInThread:!1}}findThreadForEvent(e){if(!e)return null;var{threadId:t}=this.eventShouldLiveIn(e);return t?this.getThread(t):null}addThreadedEvents(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=this.getThread(e);if(i)i.addEvents(t,n);else{var o,s=(o=this.findEventById(e))!==null&&o!==void 0?o:t.find(a=>a.getId()===e);this.createThread(e,s,t,n)}}processThreadedEvents(e,t){e.forEach(this.applyRedaction);var n={};for(var i of e){var o,{threadId:s,shouldLiveInThread:a}=this.eventShouldLiveIn(i);a&&!n[s]&&(n[s]=[]),(o=n[s])===null||o===void 0||o.push(i)}Object.entries(n).map(l=>{var[c,u]=l;return this.addThreadedEvents(c,u,t)})}createThread(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],o=arguments.length>3?arguments[3]:void 0;if(this.threads.has(e))return this.threads.get(e);if(t){var s=this.relations.getAllChildEventsForEvent(t.getId());s!=null&&s.length&&(i=i.concat(s.filter(l=>!l.isRelation(At.Replace))))}var a=new Et(e,t,{room:this,client:this.client,pendingEventOrdering:this.opts.pendingEventOrdering,receipts:(n=this.cachedThreadReadReceipts.get(e))!==null&&n!==void 0?n:[]});return this.reEmitter.reEmit(a,[Xr.Delete,Xr.Update,Xr.NewReply,fe.Timeline,fe.TimelineReset]),this.cachedThreadReadReceipts.delete(e),this.threads.set(a.id,a),a.addEvents(i,!1),this.threadsReady&&a.initialEventsFetched&&this.updateThreadRootEvents(a,o,!1),this.emit(Xr.New,a,o),a}processLiveEvent(e){this.applyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e);var t=e.getUnsigned().transaction_id;if(!t&&e.getSender()===this.myUserId){for(var[n,i]of this.txnToEvent)if(i.getId()===e.getId()){S.debug("processLiveEvent: found sent event without txn ID: ",n,e.getId());var o=e.getUnsigned();o.transaction_id=n,e.setUnsigned(o);break}}}addLiveEvent(e,t){var{duplicateStrategy:n,timelineWasEmpty:i,fromCache:o}=t;for(var s of this.timelineSets)s.addLiveEvent(e,{duplicateStrategy:n,fromCache:o,timelineWasEmpty:i});e.sender&&e.getType()!==V.RoomRedaction&&this.addReceipt(ID(e.sender.userId,e,Jr.Read),!0)}addPendingEvent(e,t){if(e.status!==je.SENDING&&e.status!==je.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent.get(t))throw new Error("addPendingEvent called on an event with known txnId "+t);if(Ee.setEventMetadata(e,this.getLiveTimeline().getState(Ee.FORWARDS),!1),this.txnToEvent.set(t,e),this.pendingEventList){if(this.pendingEventList.some(s=>s.status===je.NOT_SENT)&&(S.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(je.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){var n=e.event.redacts,i=this.pendingEventList.find(s=>s.getId()===n);!i&&n&&(i=this.findEventById(n)),i&&(i.markLocallyRedacted(e),this.emit(fe.Redaction,e,this,i.threadRootId))}}else for(var o of this.timelineSets)o.getFilter()?o.getFilter().filterRoomTimeline([e]).length&&o.addEventToTimeline(e,o.getLiveTimeline(),{toStartOfTimeline:!1}):o.addEventToTimeline(e,o.getLiveTimeline(),{toStartOfTimeline:!1});this.emit(fe.LocalEchoUpdated,e,this)}savePendingEvents(){if(this.pendingEventList){var e=this.pendingEventList.map(t=>uu(uu({},t.event),{},{txn_id:t.getTxnId()})).filter(t=>{var n=t.type===V.RoomMessageEncrypted,i=this.hasEncryptionStateEvent();return n||!i});this.client.store.setPendingEvents(this.roomId,e)}}aggregateNonLiveRelation(e){this.relations.aggregateChildEvent(e)}getEventForTxnId(e){return this.txnToEvent.get(e)}handleRemoteEcho(e,t){var n=t.getId(),i=e.getId(),o=t.status;S.debug("Got remote echo for event ".concat(n," -> ").concat(i," old status ").concat(o)),this.txnToEvent.delete(e.getUnsigned().transaction_id),this.pendingEventList&&this.removePendingEvent(n),t.handleRemoteEcho(e.event);var{shouldLiveInRoom:s,threadId:a}=this.eventShouldLiveIn(e),l=a?this.getThread(a):null;if(l==null||l.setEventMetadata(t),l==null||l.timelineSet.handleRemoteEcho(t,n,i),s)for(var c of this.timelineSets)c.handleRemoteEcho(t,n,i);this.emit(fe.LocalEchoUpdated,t,this,n,o)}updatePendingEvent(e,t,n){if(S.log("setting pendingEvent status to ".concat(t," in ").concat(e.getRoomId()," ")+"event ID ".concat(e.getId()," -> ").concat(n)),t==je.SENT&&!n)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==je.SENT){var i=this.getTimelineForEvent(n);if(i){var o=this.findEventById(n),s=o==null?void 0:o.getUnsigned().transaction_id;if(!s&&o){var a=o.getUnsigned();a.transaction_id=e.getTxnId(),o.setUnsigned(a),this.removeEvent(o.getId()),this.handleRemoteEcho(o,e)}return}}var l=e.status,c=e.getId();if(!l)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");var u=qH[l];if(!(u!=null&&u.includes(t)))throw new Error("Invalid EventStatus transition ".concat(l,"->").concat(t));if(e.setStatus(t),t==je.SENT){e.replaceLocalEventId(n);var{shouldLiveInRoom:d,threadId:f}=this.eventShouldLiveIn(e),p=f?this.getThread(f):void 0;if(p==null||p.setEventMetadata(e),p==null||p.timelineSet.replaceEventId(c,n),d)for(var h of this.timelineSets)h.replaceEventId(c,n)}else if(t==je.CANCELLED){if(this.pendingEventList){var m=this.getPendingEvent(c);this.removePendingEvent(c),m!=null&&m.isRedaction()&&this.revertRedactionLocalEcho(m)}this.removeEvent(c)}this.savePendingEvents(),this.emit(fe.LocalEchoUpdated,e,this,c,l)}revertRedactionLocalEcho(e){var t=e.event.redacts;if(t){var n=this.getUnfilteredTimelineSet().findEventById(t);n&&(n.unmarkLocallyRedacted(),this.emit(fe.RedactionCancelled,e,this),n.isRelation()&&this.aggregateNonLiveRelation(n))}}assertTimelineSetsAreLive(){for(var e=0;e<this.timelineSets.length;e++){var t=this.timelineSets[e].getLiveTimeline();if(t.getPaginationToken(Ee.FORWARDS))throw new Error("live timeline "+e+" is no longer live - it has a pagination token ("+t.getPaginationToken(Ee.FORWARDS)+")");if(t.getNeighbouringTimeline(Ee.FORWARDS))throw new Error("live timeline ".concat(e," is no longer live - it has a neighbouring timeline"))}}addLiveEvents(e,t){var n=this;return _(function*(){var{duplicateStrategy:i,fromCache:o,timelineWasEmpty:s=!1}=t??{};if(i&&["replace","ignore"].indexOf(i)===-1)throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");n.assertTimelineSetsAreLive();var a=n.findThreadRoots(e),l={},c={duplicateStrategy:i,fromCache:o,timelineWasEmpty:s},u=[...e];for(var d of e){var f;if(n.processLiveEvent(d),d.getUnsigned().transaction_id){var p=n.txnToEvent.get(d.getUnsigned().transaction_id);if(p){n.handleRemoteEcho(d,p);continue}}var{shouldLiveInRoom:h,shouldLiveInThread:m,threadId:w=""}=n.eventShouldLiveIn(d,u,a);if(!m&&!h&&d.isRelation())try{var g=new pr(yield n.client.fetchRoomEvent(n.roomId,d.relationEventId));if(u.push(g),g.threadRootId){a.add(g.threadRootId);var b=d.getUnsigned();b[Qp.name]=g.threadRootId,d.setUnsigned(b)}({shouldLiveInRoom:h,shouldLiveInThread:m,threadId:w=""}=n.eventShouldLiveIn(d,u,a))}catch(R){S.error("Failed to load parent event of unhandled relation",R)}m&&!l[w]&&(l[w]=[]),(f=l[w])===null||f===void 0||f.push(d),h?n.addLiveEvent(d,c):!m&&d.isRelation()&&n.relations.aggregateChildEvent(d)}Object.entries(l).forEach(R=>{var[k,O]=R;n.addThreadedEvents(k,O,!1)})})()}partitionThreadedEvents(e){var t=0,n=1,i=2;if(this.client.supportsThreads()){var o=this.findThreadRoots(e);return e.reduce((s,a)=>{var{shouldLiveInRoom:l,shouldLiveInThread:c,threadId:u}=this.eventShouldLiveIn(a,e,o);return l&&s[t].push(a),c&&(a.setThreadId(u??""),s[n].push(a)),!c&&!l&&s[i].push(a),s},[[],[],[]])}else return[e,[],[]]}findThreadRoots(e){var t=new Set;for(var n of e){var i=n.threadRootId;i!=null&&t.add(i)}return t}addReceipt(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=e.getContent();this.roomReceipts.add(n,t),Object.keys(n).forEach(i=>{Object.keys(n[i]).forEach(o=>{Object.keys(n[i][o]).forEach(s=>{var a,l,c,u=n[i][o][s],d=!u.thread_id||u.thread_id===bf,f=d?this:this.threads.get((a=u.thread_id)!==null&&a!==void 0?a:"");if(f){if(f.addReceiptToStructure(i,o,s,u,t),!t&&this.client.isInitialSyncComplete()&&s===this.client.getUserId()){var p=f.timeline[f.timeline.length-1];p&&i===p.getId()&&s===p.getSender()&&(f.setUnread(it.Total,0),f.setUnread(it.Highlight,0))}}else{var h;this.cachedThreadReadReceipts.set(u.thread_id,[...(h=this.cachedThreadReadReceipts.get(u.thread_id))!==null&&h!==void 0?h:[],{eventId:i,receiptType:o,userId:s,receipt:u,synthetic:t}])}var m=this.client.getUserId();s===m&&!d&&u.ts<this.oldestThreadedReceiptTs&&(this.oldestThreadedReceiptTs=u.ts),!u.thread_id&&u.ts>((l=(c=this.unthreadedReceipts.get(s))===null||c===void 0?void 0:c.ts)!==null&&l!==void 0?l:0)&&this.unthreadedReceipts.set(s,u)})})}),this.emit(fe.Receipt,e,this)}addEphemeralEvents(e){for(var t of e)t.getType()===V.Typing?this.currentState.setTypingEvent(t):t.getType()===V.Receipt&&this.addReceipt(t)}removeEvents(e){for(var t of e)this.removeEvent(t)}removeEvent(e){var t=!1;for(var n of this.timelineSets){var i=n.removeEvent(e);i&&(i.isRedaction()&&this.revertRedactionLocalEcho(i),t=!0)}return t}recalculate(){var e=this.currentState.getStateEvents(V.RoomMember,this.myUserId);if(e){var t=e.getContent().membership;if(this.updateMyMembership(t),t===Be.Invite){var n=e.getUnsigned().invite_room_state||[];n.forEach(o=>{var s=this.currentState.getStateEvents(o.type,o.state_key);s||this.currentState.setStateEvents([new pr({type:o.type,state_key:o.state_key,content:o.content,event_id:"$fake"+Date.now(),room_id:this.roomId,sender:this.myUserId})])})}}var i=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=A6(this.name),this.summary=new vD(this.roomId,{title:this.name}),i!==this.name&&this.emit(fe.Name,this)}addTags(e){this.tags=e.getContent().tags||{},this.emit(fe.Tags,e,this)}addAccountData(e){for(var t of e){t.getType()==="m.tag"&&this.addTags(t);var n=t.getType(),i=this.accountData.get(n);this.accountData.set(n,t),this.emit(fe.AccountData,t,this,i)}}getAccountData(e){return this.accountData.get(e)}maySendMessage(){return this.getMyMembership()===Be.Join&&(this.hasEncryptionStateEvent()?this.currentState.maySendEvent(V.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(V.RoomMessage,this.myUserId))}canInvite(e){var t=this.getMyMembership()===Be.Join,n=this.currentState.getStateEvents(V.RoomPowerLevels,""),i=n&&n.getContent(),o=this.getMember(e);return i&&o&&i.invite>o.powerLevel&&(t=!1),t}getJoinRule(){return this.currentState.getJoinRule()}getHistoryVisibility(){return this.currentState.getHistoryVisibility()}getGuestAccess(){return this.currentState.getGuestAccess()}getType(){var e=this.currentState.getStateEvents(V.RoomCreate,"");if(!e){this.getTypeWarning||(S.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0);return}return e.getContent()[Xp]}isSpaceRoom(){return this.getType()===Yl.Space}isCallRoom(){return this.getType()===Yl.UnstableCall}isElementVideoRoom(){return this.getType()===Yl.ElementVideo}findPredecessor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.getLiveTimeline().getState(Ee.FORWARDS);return t?t.findPredecessor(e):null}roomNameGenerator(e){if(this.client.roomNameGenerator){var t=this.client.roomNameGenerator(this.roomId,e);if(t!==null)return t}switch(e.type){case Ni.Actual:return e.name;case Ni.Generated:switch(e.subtype){case"Inviting":return"Inviting ".concat(EC(e.names,e.count));default:return EC(e.names,e.count)}case Ni.EmptyRoom:return e.oldName?"Empty room (was ".concat(e.oldName,")"):"Empty room"}}calculateRoomName(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!t){var n=this.currentState.getStateEvents(V.RoomName,"");if(n!=null&&n.getContent().name)return this.roomNameGenerator({type:Ni.Actual,name:n.getContent().name})}var i=this.getCanonicalAlias();if(i)return this.roomNameGenerator({type:Ni.Actual,name:i});var o=this.currentState.getJoinedMemberCount(),s=this.currentState.getInvitedMemberCount(),a=o+s-1,l=this.getFunctionalMembers(),c=[];if(this.summaryHeroes)this.summaryHeroes.forEach(g=>{if(l.includes(g)){a--;return}var b=this.getMember(g);c.push(b?b.name:g)});else{var u=this.currentState.getMembers().filter(g=>g.userId!==e&&(g.membership===Be.Invite||g.membership===Be.Join));u=u.filter(g=>{var{userId:b}=g;return l.includes(b)?(a--,!1):!0});var d=new Intl.Collator;u.sort((g,b)=>d.compare(g.userId,b.userId)),u=u.slice(0,5),c=u.map(g=>g.name)}if(a)return this.roomNameGenerator({type:Ni.Generated,names:c,count:a});var f=this.getMyMembership();if(f==Be.Join){var p=this.currentState.getStateEvents(V.RoomThirdPartyInvite);if(p!=null&&p.length){var h=p.map(g=>g.getContent().display_name);return this.roomNameGenerator({type:Ni.Generated,subtype:"Inviting",names:h,count:h.length+1})}}var m=c;m.length||(m=this.currentState.getMembers().filter(g=>g.userId!==e&&g.membership!==Be.Invite&&g.membership!==Be.Join).map(g=>g.name));var w;return m.length&&(w=this.roomNameGenerator({type:Ni.Generated,names:m,count:m.length+1})),this.roomNameGenerator({type:Ni.EmptyRoom,oldName:w})}applyNewVisibilityEvent(e){var t=e.asVisibilityChange();if(t){var n=e.getSender();if(n){var i=Ea.name&&this.currentState.maySendStateEvent(Ea.name,n)||Ea.altName&&this.currentState.maySendStateEvent(Ea.altName,n);if(i){var o=this.visibilityEvents.get(t.eventId);if(o){for(var s=o.length-1,a=Math.max(0,o.length-WH);s>=a;--s){var l=o[s];if(l.getTs()<e.getTs())break}s===-1?o.unshift(e):o.splice(s+1,0,e)}else this.visibilityEvents.set(t.eventId,[e]);var c=this.findEventById(t.eventId);c&&c.applyVisibilityEvent(t)}}}}redactVisibilityChangeEvent(e){if(!e.isVisibilityEvent)throw new Error("expected a visibility change event");var t=e.getRelation(),n=t==null?void 0:t.event_id,i=this.visibilityEvents.get(n);if(i){var o=i.findIndex(c=>c.getId()===e.getId());if(o!==-1&&(i.splice(o,1),o===i.length)){var s=this.findEventById(n);if(!s)return;if(o===0)this.visibilityEvents.delete(n),s.applyVisibilityEvent();else{var a=i[i.length-1],l=a.asVisibilityChange();if(!l)throw new Error("at this stage, visibility changes should be well-formed");s.applyVisibilityEvent(l)}}}}applyPendingVisibilityEvents(e){var t=this.visibilityEvents.get(e.getId());if(!(!t||t.length==0)){var n=t[t.length-1],i=n.asVisibilityChange();i&&(i.visible,!(n.getTs()<e.getTs())&&e.applyVisibilityEvent(i))}}getOldestThreadedReceiptTs(){return this.oldestThreadedReceiptTs}hasUserReadEvent(e,t){return this.roomReceipts.hasUserReadEvent(e,t)}getLastUnthreadedReceiptFor(e){return this.unthreadedReceipts.get(e)}fixupNotifications(e){super.fixupNotifications(e);var t=this.getThreads().filter(i=>this.getThreadUnreadNotificationCount(i.id,it.Total)>0);for(var n of t)n.fixupNotifications(e)}compareEventOrdering(e,t){return TH(this,e,t)}hasEncryptionStateEvent(){var e;return!!(!((e=this.getLiveTimeline().getState(Ee.FORWARDS))===null||e===void 0)&&e.getStateEvents(V.RoomEncryption,""))}}var qH={[je.ENCRYPTING]:[je.SENDING,je.NOT_SENT,je.CANCELLED],[je.SENDING]:[je.ENCRYPTING,je.QUEUED,je.NOT_SENT,je.SENT],[je.QUEUED]:[je.SENDING,je.NOT_SENT,je.CANCELLED],[je.SENT]:[],[je.NOT_SENT]:[je.SENDING,je.QUEUED,je.CANCELLED],[je.CANCELLED]:[]},Ni=function(r){return r[r.EmptyRoom=0]="EmptyRoom",r[r.Generated=1]="Generated",r[r.Actual=2]="Actual",r}({});function EC(r,e){var t=e-1;if(r.length){if(r.length===1&&t<=1)return r[0];if(r.length===2&&t<=2)return"".concat(r[0]," and ").concat(r[1]);var n=t>1;return n?"".concat(r[0]," and ").concat(t," others"):"".concat(r[0]," and 1 other")}else return"Empty room"}var lr=function(r){return r[r.Stable=0]="Stable",r[r.Unstable=1]="Unstable",r[r.Unsupported=2]="Unsupported",r}({}),dr=function(r){return r.Thread="Thread",r.ThreadUnreadNotifications="ThreadUnreadNotifications",r.LoginTokenRequest="LoginTokenRequest",r.RelationBasedRedactions="RelationBasedRedactions",r.AccountDataDeletion="AccountDataDeletion",r.RelationsRecursion="RelationsRecursion",r.IntentionalMentions="IntentionalMentions",r}({}),GH={[dr.Thread]:{unstablePrefixes:["org.matrix.msc3440"],matrixVersion:"v1.3"},[dr.ThreadUnreadNotifications]:{unstablePrefixes:["org.matrix.msc3771","org.matrix.msc3773"],matrixVersion:"v1.4"},[dr.LoginTokenRequest]:{unstablePrefixes:["org.matrix.msc3882"]},[dr.RelationBasedRedactions]:{unstablePrefixes:["org.matrix.msc3912"]},[dr.AccountDataDeletion]:{unstablePrefixes:["org.matrix.msc3391"]},[dr.RelationsRecursion]:{unstablePrefixes:["org.matrix.msc3981"]},[dr.IntentionalMentions]:{unstablePrefixes:["org.matrix.msc3952_intentional_mentions"],matrixVersion:"v1.7"}};function HH(r){return Cb.apply(this,arguments)}function Cb(){return Cb=_(function*(r){var e=new Map;for(var[t,n]of Object.entries(GH)){var i,o,s,a,l=(i=(o=r.versions)===null||o===void 0?void 0:o.includes(n.matrixVersion||""))!==null&&i!==void 0?i:!1,c=(s=(a=n.unstablePrefixes)===null||a===void 0?void 0:a.every(u=>{var d;return((d=r.unstable_features)===null||d===void 0?void 0:d[u])===!0}))!==null&&s!==void 0?s:!1;l?e.set(t,lr.Stable):c?e.set(t,lr.Unstable):e.set(t,lr.Unsupported)}return e}),Cb.apply(this,arguments)}function wC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function tv(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?wC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):wC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var TC=80*1e3,zH=3,ct=function(r){return r.Error="ERROR",r.Prepared="PREPARED",r.Stopped="STOPPED",r.Syncing="SYNCING",r.Catchup="CATCHUP",r.Reconnecting="RECONNECTING",r}({}),YH=["org.matrix.msc2716v3"];function RC(r,e){return"FILTER_SYNC_".concat(r)+(e?"_"+e:"")}function xt(){S.log(...arguments)}var KD=function(r){return r.Offline="offline",r.Online="online",r.Unavailable="unavailable",r}({});function VD(r){return tv({initialSyncLimit:8,resolveInvitesToProfiles:!1,pollTimeout:30*1e3,pendingEventOrdering:wc.Chronological,threadSupport:!1},r)}function $D(r){return tv({canResetEntireTimeline:e=>!1},r)}class Mu{constructor(e,t,n){var i=this;this.client=e,v(this,"opts",void 0),v(this,"syncOpts",void 0),v(this,"_peekRoom",null),v(this,"currentSyncRequest",void 0),v(this,"abortController",void 0),v(this,"syncState",null),v(this,"syncStateData",void 0),v(this,"catchingUp",!1),v(this,"running",!1),v(this,"keepAliveTimer",void 0),v(this,"connectionReturnedDefer",void 0),v(this,"notifEvents",[]),v(this,"failedSyncCount",0),v(this,"storeIsInvalid",!1),v(this,"presence",void 0),v(this,"getPushRules",_(function*(){try{xt("Getting push rules...");var o=yield i.client.getPushRules();xt("Got push rules"),i.client.pushRules=o}catch(s){return S.error("Getting push rules failed",s),i.shouldAbortSync(s)?void 0:(xt("Waiting for saved sync before retrying push rules..."),yield i.recoverFromSyncStartupError(i.savedSyncPromise,s),i.getPushRules())}})),v(this,"buildDefaultFilter",()=>{var o=new gn(this.client.credentials.userId);return this.client.canSupport.get(dr.ThreadUnreadNotifications)!==lr.Unsupported&&o.setUnreadThreadNotifications(!0),o}),v(this,"prepareLazyLoadingForSync",_(function*(){if(xt("Prepare lazy loading for sync..."),i.client.isGuest()&&(i.opts.lazyLoadMembers=!1),i.opts.lazyLoadMembers&&(xt("Enabling lazy load on sync filter..."),i.opts.filter||(i.opts.filter=i.buildDefaultFilter()),i.opts.filter.setLazyLoadMembers(!0)),i.opts.lazyLoadMembers){var o;(o=i.syncOpts.crypto)===null||o===void 0||o.enableLazyLoading()}})),v(this,"storeClientOptions",_(function*(){try{xt("Storing client options..."),yield i.client.storeClientOptions(),xt("Stored client options")}catch(o){throw S.error("Storing client options failed",o),o}})),v(this,"getFilter",_(function*(){xt("Getting filter...");var o;i.opts.filter?o=i.opts.filter:o=i.buildDefaultFilter();var s;try{s=yield i.client.getOrCreateFilter(RC(i.client.credentials.userId),o)}catch(a){return S.error("Getting filter failed",a),i.shouldAbortSync(a)?{}:(xt("Waiting for saved sync before retrying filter..."),yield i.recoverFromSyncStartupError(i.savedSyncPromise,a),i.getFilter())}return{filter:o,filterId:s}})),v(this,"savedSyncPromise",void 0),v(this,"onOnline",()=>{xt("Browser thinks we are back online"),this.startKeepAlives(0)}),this.opts=VD(t),this.syncOpts=$D(n),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),[fe.Timeline,fe.TimelineReset])}createRoom(e){var t=WD(this.client,e,this.opts);return t.on(Ne.Marker,(n,i)=>{this.onMarkerStateEvent(t,n,i)}),t}onMarkerStateEvent(e,t){var{timelineWasEmpty:n}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(n){S.debug("MarkerState: Ignoring markerEventId=".concat(t.getId()," in roomId=").concat(e.roomId," ")+"because the timeline was empty before the marker arrived which means there is nothing to refresh.");return}var i=YH.includes(e.getVersion())||t.getSender()===e.getCreator();i?(S.debug("MarkerState: Timeline needs to be refreshed because "+"a new markerEventId=".concat(t.getId()," was sent in roomId=").concat(e.roomId)),e.setTimelineNeedsRefresh(!0),e.emit(fe.HistoryImportedWithinTimeline,t,e)):S.debug("MarkerState: Ignoring markerEventId=".concat(t.getId()," in roomId=").concat(e.roomId," because ")+"MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.")}syncLeftRooms(){var e=this;return _(function*(){var t,n=e.client,i=new gn(e.client.credentials.userId);i.setTimelineLimit(1),i.setIncludeLeaveRooms(!0);var o=e.opts.pollTimeout+TC,s=yield n.getOrCreateFilter(RC(n.credentials.userId,"LEFT_ROOMS"),i),a={timeout:0,filter:s},l=yield n.http.authedRequest(Z.Get,"/sync",a,void 0,{localTimeoutMs:o}),c=[];(t=l.rooms)!==null&&t!==void 0&&t.leave&&(c=e.mapSyncResponseToRoomArray(l.rooms.leave));var u=yield Promise.all(c.map(function(){var d=_(function*(f){var p=f.room;if(f.isBrandNewRoom){f.timeline=f.timeline||{prev_batch:null,events:[]};var h=e.mapSyncEventsFormat(f.timeline,p),m=e.mapSyncEventsFormat(f.state,p);return p.getLiveTimeline().setPaginationToken(f.timeline.prev_batch,Ee.BACKWARDS),yield e.injectRoomEvents(p,m,h),p.recalculate(),n.store.storeRoom(p),n.emit(Te.Room,p),e.processEventsForNotifs(p,h),p}});return function(f){return d.apply(this,arguments)}}()));return u.filter(Boolean)})()}peek(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;if(((t=this._peekRoom)===null||t===void 0?void 0:t.roomId)===e)return Promise.resolve(this._peekRoom);var i=this.client;return this._peekRoom=this.createRoom(e),this.client.roomInitialSync(e,n).then(o=>{var s;if(((s=this._peekRoom)===null||s===void 0?void 0:s.roomId)!==e)throw new Error("Peeking aborted");o.messages=o.messages||{chunk:[]},o.messages.chunk=o.messages.chunk||[],o.state=o.state||[];var a=lm(o.state).map(i.getEventMapper()),l=o.state.map(i.getEventMapper()),c=o.messages.chunk.map(i.getEventMapper());return Array.isArray(o.presence)&&o.presence.map(i.getEventMapper()).forEach(function(u){var d=i.store.getUser(u.getContent().user_id);d?d.setPresenceEvent(u):(d=Co.createUser(u.getContent().user_id,i),d.setPresenceEvent(u),i.store.storeUser(d)),i.emit(Te.Event,u)}),o.messages.start&&(this._peekRoom.oldState.paginationToken=o.messages.start),this._peekRoom.oldState.setStateEvents(a),this._peekRoom.currentState.setStateEvents(l),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(c.reverse(),!0,this._peekRoom.getLiveTimeline(),o.messages.start),i.store.storeRoom(this._peekRoom),i.emit(Te.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom})}stopPeeking(){this._peekRoom=null}peekPoll(e,t){var n,i=this;if(this._peekRoom!==e){xt("Stopped peeking in room %s",e.roomId);return}this.client.http.authedRequest(Z.Get,"/events",{room_id:e.roomId,timeout:String(30*1e3),from:t},void 0,{localTimeoutMs:50*1e3,abortSignal:(n=this.abortController)===null||n===void 0?void 0:n.signal}).then(function(){var o=_(function*(s){if(i._peekRoom!==e){xt("Stopped peeking in room %s",e.roomId);return}s.chunk.filter(function(l){return l.type==="m.presence"}).map(i.client.getEventMapper()).forEach(l=>{var c=i.client.store.getUser(l.getContent().user_id);c?c.setPresenceEvent(l):(c=Co.createUser(l.getContent().user_id,i.client),c.setPresenceEvent(l),i.client.store.storeUser(c)),i.client.emit(Te.Event,l)});var a=s.chunk.filter(function(l){return l.room_id===e.roomId&&l.event_id}).map(i.client.getEventMapper());yield e.addLiveEvents(a),i.peekPoll(e,s.end)});return function(s){return o.apply(this,arguments)}}(),o=>{S.error("[%s] Peek poll failed: %s",e.roomId,o),setTimeout(()=>{this.peekPoll(e,t)},30*1e3)})}getSyncState(){return this.syncState}getSyncStateData(){var e;return(e=this.syncStateData)!==null&&e!==void 0?e:null}recoverFromSyncStartupError(e,t){var n=this;return _(function*(){yield e;var i=n.startKeepAlives();n.updateSyncState(ct.Error,{error:t}),yield i})()}shouldAbortSync(e){return e.errcode==="M_UNKNOWN_TOKEN"?(S.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(ct.Error,{error:e}),!0):!1}sync(){var e=this;return _(function*(){var t,n;if(e.running=!0,e.abortController=new AbortController,(t=globalThis.window)===null||t===void 0||(n=t.addEventListener)===null||n===void 0||n.call(t,"online",e.onOnline,!1),e.client.isGuest())return e.doSync({});xt("Getting saved sync token...");var i=e.client.store.getSavedSyncToken().then(u=>(xt("Got saved sync token"),u));e.savedSyncPromise=e.client.store.getSavedSync().then(u=>{if(xt("Got reply from saved sync, exists? ".concat(!!u)),u)return e.syncFromCache(u)}).catch(u=>{S.error("Getting saved sync failed",u)}),yield e.getPushRules(),yield e.prepareLazyLoadingForSync(),yield e.storeClientOptions();var{filterId:o,filter:s}=yield e.getFilter();if(s){if(e.client.resetNotifTimelineSet(),!e.currentSyncRequest){var a=o,l=yield i;if(l)xt("Sending first sync request...");else{xt("Sending initial sync request...");var c=e.buildDefaultFilter();c.setDefinition(s.getDefinition()),c.setTimelineLimit(e.opts.initialSyncLimit),a=JSON.stringify(c.getDefinition())}e.currentSyncRequest=e.doSyncRequest({filter:a},l)}return xt("Waiting for saved sync before starting sync processing..."),yield e.savedSyncPromise,e.doSync({filter:o})}})()}stop(){var e,t,n;xt("SyncApi.stop"),(e=globalThis.window)===null||e===void 0||(t=e.removeEventListener)===null||t===void 0||t.call(e,"online",this.onOnline,!1),this.running=!1,(n=this.abortController)===null||n===void 0||n.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=void 0)}retryImmediately(){return this.connectionReturnedDefer?(this.startKeepAlives(0),!0):!1}syncFromCache(e){var t=this;return _(function*(){xt("sync(): not doing HTTP hit, instead returning stored /sync data");var n=e.nextBatch;t.client.store.setSyncToken(n);var i={nextSyncToken:n,catchingUp:!1,fromCache:!0},o={next_batch:n,rooms:e.roomsData,account_data:{events:e.accountData}};try{yield t.processSyncResponse(i,o)}catch(s){S.error("Error processing cached sync",s)}t.storeIsInvalid||t.updateSyncState(ct.Prepared,i)})()}doSync(e){var t=this;return _(function*(){for(;t.running;){var n=t.client.store.getSyncToken(),i=void 0;try{t.currentSyncRequest||(t.currentSyncRequest=t.doSyncRequest(e,n)),i=yield t.currentSyncRequest}catch(a){var o=yield t.onSyncError(a);if(o)return;continue}finally{t.currentSyncRequest=void 0}t.client.store.setSyncToken(i.next_batch),t.failedSyncCount=0;var s={oldSyncToken:n??void 0,nextSyncToken:i.next_batch,catchingUp:t.catchingUp};t.syncOpts.crypto&&(yield t.syncOpts.crypto.onSyncWillProcess(s));try{yield t.processSyncResponse(s,i)}catch(a){S.error("Caught /sync error",a),t.client.emit(Te.SyncUnexpectedError,a)}yield t.client.store.setSyncData(i),s.catchingUp=t.catchingUp,e.hasSyncedBefore||(t.updateSyncState(ct.Prepared,s),e.hasSyncedBefore=!0),t.syncOpts.cryptoCallbacks&&(yield t.syncOpts.cryptoCallbacks.onSyncCompleted(s)),t.updateSyncState(ct.Syncing,s),t.client.store.wantsSave()&&(t.syncOpts.crypto&&(yield t.syncOpts.crypto.saveDeviceList(0)),yield t.client.store.save())}t.running||(xt("Sync no longer running: exiting."),t.connectionReturnedDefer&&(t.connectionReturnedDefer.reject(),t.connectionReturnedDefer=void 0),t.updateSyncState(ct.Stopped))})()}doSyncRequest(e,t){var n,i=this.getSyncParams(e,t);return this.client.http.authedRequest(Z.Get,"/sync",i,void 0,{localTimeoutMs:i.timeout+TC,abortSignal:(n=this.abortController)===null||n===void 0?void 0:n.signal})}getSyncParams(e,t){var n=this.opts.pollTimeout;(this.getSyncState()!==ct.Syncing||this.catchingUp)&&(this.catchingUp=!0,n=0);var i=e.filter;this.client.isGuest()&&!i&&(i=this.getGuestFilter());var o={filter:i,timeout:n};return this.opts.disablePresence?o.set_presence=KD.Offline:this.presence!==void 0&&(o.set_presence=this.presence),t?o.since=t:o._cacheBuster=Date.now(),[ct.Reconnecting,ct.Error].includes(this.getSyncState())&&(o.timeout=0),o}setPresence(e){this.presence=e}onSyncError(e){var t=this;return _(function*(){if(!t.running)return xt("Sync no longer running: exiting"),t.connectionReturnedDefer&&(t.connectionReturnedDefer.reject(),t.connectionReturnedDefer=void 0),t.updateSyncState(ct.Stopped),!0;if(S.error("/sync error %s",e),t.shouldAbortSync(e))return!0;t.failedSyncCount++,S.log("Number of consecutive failed sync requests:",t.failedSyncCount),xt("Starting keep-alive");var n=t.startKeepAlives();t.currentSyncRequest=void 0,t.updateSyncState(t.failedSyncCount>=zH?ct.Error:ct.Reconnecting,{error:e});var i=yield n;return i&&t.getSyncState()===ct.Error&&t.updateSyncState(ct.Catchup,{catchingUp:!0}),!1})()}processSyncResponse(e,t){var n=this;return _(function*(){var i,o,s,a,l=n.client;if(Array.isArray((i=t.presence)===null||i===void 0?void 0:i.events)&&t.presence.events.filter(mi).map(l.getEventMapper()).forEach(function(g){var b=l.store.getUser(g.getSender());b?b.setPresenceEvent(g):(b=Co.createUser(g.getSender(),l),b.setPresenceEvent(g),l.store.storeUser(b)),l.emit(Te.Event,g)}),Array.isArray((o=t.account_data)===null||o===void 0?void 0:o.events)){var c=t.account_data.events.filter(mi).map(l.getEventMapper()),u=c.reduce((g,b)=>(g[b.getType()]=l.store.getAccountData(b.getType()),g),{});l.store.storeAccountDataEvents(c),c.forEach(function(g){if(g.getType()===V.PushRules){var b=g.getContent();l.setPushRules(b)}var R=u[g.getType()];return l.emit(Te.AccountData,g,R),g})}if(t.to_device&&Array.isArray(t.to_device.events)&&t.to_device.events.length>0){var d=t.to_device.events.filter(mi);n.syncOpts.cryptoCallbacks&&(d=yield n.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(d));var f=[];d.map(l.getEventMapper({toDevice:!0})).map(g=>{if(g.getType()==="m.key.verification.cancel"){var b=g.getContent().transaction_id;b&&f.push(b)}return g}).forEach(function(g){var b=g.getContent();if(g.getType()=="m.room.message"&&b.msgtype=="m.bad.encrypted"){S.log("Ignoring undecryptable to-device event from "+g.getSender());return}if(g.getType()==="m.key.verification.start"||g.getType()==="m.key.verification.request"){var R=b.transaction_id;f.includes(R)&&g.flagCancelled()}l.emit(Te.ToDeviceEvent,g)})}else n.catchingUp=!1;var p=[],h=[],m=[],w=[];t.rooms&&(t.rooms.invite&&(p=n.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(h=n.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(m=n.mapSyncResponseToRoomArray(t.rooms.leave)),t.rooms.knock&&(w=n.mapSyncResponseToRoomArray(t.rooms.knock))),n.notifEvents=[],yield Ll(p,function(){var g=_(function*(b){var R,k=b.room,O=n.mapSyncEventsFormat(b.invite_state,k);yield n.injectRoomEvents(k,O);var T=(R=k.currentState.getStateEvents(V.RoomMember,l.getUserId()))===null||R===void 0?void 0:R.getSender(),x=l.crypto;if(x){var C=yield x.cryptoStore.takeParkedSharedHistory(k.roomId);for(var N of C)N.senderId===T&&(yield x.olmDevice.addInboundGroupSession(k.roomId,N.senderKey,N.forwardingCurve25519KeyChain,N.sessionId,N.sessionKey,N.keysClaimed,!0,{sharedHistory:!0,untrusted:!0}))}b.isBrandNewRoom?(k.recalculate(),l.store.storeRoom(k),l.emit(Te.Room,k)):k.recalculate(),O.forEach(function(F){l.emit(Te.Event,F)})});return function(b){return g.apply(this,arguments)}}()),yield Ll(h,function(){var g=_(function*(b){var R,k=b.room,O=n.mapSyncEventsFormat(b.state,k),T=n.mapSyncEventsFormat(b.timeline,k,!1),x=n.mapSyncEventsFormat(b.ephemeral),C=n.mapSyncEventsFormat(b.account_data),N=n.isRoomEncrypted(k,O,T);if(b.unread_notifications){if(!N||b.unread_notifications.notification_count===0){var F;k.setUnreadNotificationCount(it.Total,(F=b.unread_notifications.notification_count)!==null&&F!==void 0?F:0)}if(!N||k.getUnreadNotificationCount(it.Highlight)<=0){var H;k.setUnreadNotificationCount(it.Highlight,(H=b.unread_notifications.highlight_count)!==null&&H!==void 0?H:0)}}var ie=(R=b[Fd.name])!==null&&R!==void 0?R:b[Fd.altName];if(ie){k.resetThreadUnreadNotificationCountFromSync(Object.keys(ie));for(var[$,X]of Object.entries(ie)){if(!N||X.notification_count===0){var oe;k.setThreadUnreadNotificationCount($,it.Total,(oe=X.notification_count)!==null&&oe!==void 0?oe:0)}var re=k.getThreadUnreadNotificationCount($,it.Highlight)<=0;if(!N||N&&re){var ae;k.setThreadUnreadNotificationCount($,it.Highlight,(ae=X.highlight_count)!==null&&ae!==void 0?ae:0)}}}else k.resetThreadUnreadNotificationCountFromSync();if(b.timeline=b.timeline||{},b.isBrandNewRoom)b.timeline.prev_batch!==null&&k.getLiveTimeline().setPaginationToken(b.timeline.prev_batch,Ee.BACKWARDS);else if(b.timeline.limited){for(var q=!0,z=T.length-1;z>=0;z--){var Q=T[z].getId();if(k.getTimelineForEvent(Q)){xt("Already have event ".concat(Q," in limited sync - not resetting")),q=!1,T.splice(0,z);break}}if(q){var Ie;k.resetLiveTimeline(b.timeline.prev_batch,n.syncOpts.canResetEntireTimeline(k.roomId)?null:(Ie=e.oldSyncToken)!==null&&Ie!==void 0?Ie:null),l.resetNotifTimelineSet()}}if(n.syncOpts.cryptoCallbacks)for(var Y of O.concat(T))Y.isState()&&Y.getType()===V.RoomEncryption&&Y.getStateKey()===""&&(yield n.syncOpts.cryptoCallbacks.onCryptoEvent(k,Y));try{yield n.injectRoomEvents(k,O,T,e.fromCache)}catch(B){S.error("Failed to process events on room ".concat(k.roomId,":"),B)}b.summary&&k.setSummary(b.summary),k.addEphemeralEvents(x),k.addAccountData(C),k.recalculate(),b.isBrandNewRoom&&(l.store.storeRoom(k),l.emit(Te.Room,k)),n.processEventsForNotifs(k,T);var le=B=>l.emit(Te.Event,B);O.forEach(le),T.forEach(le),x.forEach(le),C.forEach(le),k.decryptCriticalEvents()});return function(b){return g.apply(this,arguments)}}()),yield Ll(m,function(){var g=_(function*(b){var R=b.room,k=n.mapSyncEventsFormat(b.state,R),O=n.mapSyncEventsFormat(b.timeline,R),T=n.mapSyncEventsFormat(b.account_data);yield n.injectRoomEvents(R,k,O),R.addAccountData(T),R.recalculate(),b.isBrandNewRoom&&(l.store.storeRoom(R),l.emit(Te.Room,R)),n.processEventsForNotifs(R,O),k.forEach(function(x){l.emit(Te.Event,x)}),O.forEach(function(x){l.emit(Te.Event,x)}),T.forEach(function(x){l.emit(Te.Event,x)})});return function(b){return g.apply(this,arguments)}}()),yield Ll(w,function(){var g=_(function*(b){var R=b.room,k=n.mapSyncEventsFormat(b.knock_state,R);yield n.injectRoomEvents(R,k),b.isBrandNewRoom?(R.recalculate(),l.store.storeRoom(R),l.emit(Te.Room,R)):R.recalculate(),k.forEach(function(O){l.emit(Te.Event,O)})});return function(b){return g.apply(this,arguments)}}()),e.oldSyncToken&&n.notifEvents.length&&(n.notifEvents.sort(function(g,b){return g.getTs()-b.getTs()}),n.notifEvents.forEach(function(g){var b;(b=l.getNotifTimelineSet())===null||b===void 0||b.addLiveEvent(g)})),t.device_lists&&n.syncOpts.cryptoCallbacks&&(yield n.syncOpts.cryptoCallbacks.processDeviceLists(t.device_lists)),yield(s=n.syncOpts.cryptoCallbacks)===null||s===void 0?void 0:s.processKeyCounts(t.device_one_time_keys_count,(a=t.device_unused_fallback_key_types)!==null&&a!==void 0?a:t["org.matrix.msc2732.device_unused_fallback_key_types"])})()}startKeepAlives(e){return e===void 0&&(e=2e3+Math.floor(Math.random()*5e3)),this.keepAliveTimer!==null&&clearTimeout(this.keepAliveTimer),e>0?this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this),e):this.pokeKeepAlive(),this.connectionReturnedDefer||(this.connectionReturnedDefer=Gs()),this.connectionReturnedDefer.promise}pokeKeepAlive(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!this.running){clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject("SyncApi.stop() was called"),this.connectionReturnedDefer=void 0);return}var n=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.resolve(t),this.connectionReturnedDefer=void 0)};this.client.http.request(Z.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15*1e3,abortSignal:(e=this.abortController)===null||e===void 0?void 0:e.signal}).then(()=>{n()},i=>{i.httpStatus==400||i.httpStatus==404?this.keepAliveTimer=setTimeout(n,2e3):(t=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,t),5e3+Math.floor(Math.random()*5e3)),this.updateSyncState(ct.Error,{error:i}))})}mapSyncResponseToRoomArray(e){var t=this.client;return Object.keys(e).filter(n=>!Zu(n)).map(n=>{var i=t.store.getRoom(n),o=!1;return i||(i=this.createRoom(n),o=!0),tv(tv({},e[n]),{},{room:i,isBrandNewRoom:o})})}mapSyncEventsFormat(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!Array.isArray(e.events))return[];var i=this.client.getEventMapper({decrypt:n});return e.events.filter(mi).map(function(o){return t&&(o.room_id=t.roomId),i(o)})}resolveInvites(e){if(!(!e||!this.opts.resolveInvitesToProfiles)){var t=this.client;e.getMembersWithMembership(Be.Invite).forEach(function(n){if(!n.requestedProfileInfo){n.requestedProfileInfo=!0;var i=t.getUser(n.userId),o;i?o=Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):o=t.getProfileInfo(n.userId),o.then(function(s){var a=n.events.member;(a==null?void 0:a.getContent().membership)===Be.Invite&&(a.getContent().avatar_url=s.avatar_url,a.getContent().displayname=s.displayname,n.setMembershipEvent(a,e.currentState))},function(s){})}})}}findEncryptionEvent(e){return e==null?void 0:e.find(t=>t.getType()===V.RoomEncryption&&t.getStateKey()==="")}isRoomEncrypted(e,t,n){return e.hasEncryptionStateEvent()||!!this.findEncryptionEvent(t)||!!this.findEncryptionEvent(n)}injectRoomEvents(e,t,n){var i=arguments,o=this;return _(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!1,a=e.getLiveTimeline(),l=a.getEvents().length==0;if(l){for(var c of t)o.client.getPushActionsForEvent(c);a.initialiseState(t,{timelineWasEmpty:l})}o.resolveInvites(e),e.recalculate(),l||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),yield e.addLiveEvents(n||[],{fromCache:s,timelineWasEmpty:l}),o.client.processBeaconEvents(e,n)})()}processEventsForNotifs(e,t){if(this.client.getNotifTimelineSet())for(var n of t){var i,o=this.client.getPushActionsForEvent(n);o!=null&&o.notify&&(i=o.tweaks)!==null&&i!==void 0&&i.highlight&&this.notifEvents.push(n)}}getGuestFilter(){return"{}"}updateSyncState(e,t){var n=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(Te.Sync,this.syncState,n,t)}}function WD(r,e,t){var{timelineSupport:n}=r,i=new pm(e,r,r.getUserId(),{lazyLoadMembers:t.lazyLoadMembers,pendingEventOrdering:t.pendingEventOrdering,timelineSupport:n});return r.reEmitter.reEmit(i,[fe.Name,fe.Redaction,fe.RedactionCancelled,fe.Receipt,fe.Tags,fe.LocalEchoUpdated,fe.AccountData,fe.MyMembership,fe.Timeline,fe.TimelineReset,Ne.Events,Ne.Members,Ne.NewMember,Ne.Update,kt.New,kt.Update,kt.Destroy,kt.LivenessChange]),i.on(Ne.NewMember,(o,s,a)=>{var l;a.user=(l=r.getUser(a.userId))!==null&&l!==void 0?l:void 0,r.reEmitter.reEmit(a,[Ar.Name,Ar.Typing,Ar.PowerLevel,Ar.Membership])}),i}class JH{constructor(){v(this,"accountData",new Map),v(this,"fromToken",null)}isNewlyCreated(){return Promise.resolve(!0)}getSyncToken(){return this.fromToken}setSyncToken(e){this.fromToken=e}storeRoom(e){}getRoom(e){return null}getRooms(){return[]}removeRoom(e){}getRoomSummaries(){return[]}storeUser(e){}getUser(e){return null}getUsers(){return[]}scrollback(e,t){return[]}setUserCreator(e){}storeEvents(e,t,n,i){}storeFilter(e){}getFilter(e,t){return null}getFilterIdByName(e){return null}setFilterIdByName(e,t){}storeAccountDataEvents(e){}getAccountData(e){}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(){return Promise.resolve()}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return Promise.resolve()}getOutOfBandMembers(){return Promise.resolve(null)}setOutOfBandMembers(e,t){return Promise.resolve()}clearOutOfBandMembers(){return Promise.resolve()}getClientOptions(){return Promise.resolve(void 0)}storeClientOptions(e){return Promise.resolve()}getPendingEvents(e){return _(function*(){return[]})()}setPendingEvents(e,t){return Promise.resolve()}saveToDeviceBatches(e){return _(function*(){return Promise.resolve()})()}getOldestToDeviceBatch(){return Promise.resolve(null)}removeToDeviceBatch(e){return _(function*(){return Promise.resolve()})()}destroy(){return _(function*(){})()}}const kr=[];for(let r=0;r<256;++r)kr.push((r+256).toString(16).slice(1));function XH(r,e=0){return(kr[r[e+0]]+kr[r[e+1]]+kr[r[e+2]]+kr[r[e+3]]+"-"+kr[r[e+4]]+kr[r[e+5]]+"-"+kr[r[e+6]]+kr[r[e+7]]+"-"+kr[r[e+8]]+kr[r[e+9]]+"-"+kr[r[e+10]]+kr[r[e+11]]+kr[r[e+12]]+kr[r[e+13]]+kr[r[e+14]]+kr[r[e+15]]).toLowerCase()}let Yg;const QH=new Uint8Array(16);function ZH(){if(!Yg){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Yg=crypto.getRandomValues.bind(crypto)}return Yg(QH)}const ez=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),CC={randomUUID:ez};function _i(r,e,t){var i;if(CC.randomUUID&&!r)return CC.randomUUID();r=r||{};const n=r.random??((i=r.rng)==null?void 0:i.call(r))??ZH();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,XH(n)}var qD={},GD={exports:{}},kC=GD.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var e="candidate:%s %d %s %d %s %d typ %s";return e+=r.raddr!=null?" raddr %s rport %d":"%v%v",e+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(e+=" generation %d"),e+=r["network-id"]!=null?" network-id %d":"%v",e+=r["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var e="ssrc:%d";return r.attribute!=null&&(e+=" %s",r.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var e="mediaclk:";return e+=r.id!=null?"id=%s %s":"%v%s",e+=r.mediaClockValue!=null?"=%s":"",e+=r.rateNumerator!=null?" rate=%s":"",e+=r.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(kC).forEach(function(r){var e=kC[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var HD=GD.exports;(function(r){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,l,c,u){if(u&&!c)l[u]=e(a[1]);else for(var d=0;d<c.length;d+=1)a[d+1]!=null&&(l[c[d]]=e(a[d+1]))},n=function(a,l,c){var u=a.name&&a.names;a.push&&!l[a.push]?l[a.push]=[]:u&&!l[a.name]&&(l[a.name]={});var d=a.push?{}:u?l[a.name]:l;t(c.match(a.reg),d,a.names,a.name),a.push&&l[a.push].push(d)},i=HD,o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(a){var l={},c=[],u=l;return a.split(/(\r\n|\r|\n)/).filter(o).forEach(function(d){var f=d[0],p=d.slice(2);f==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var h=0;h<(i[f]||[]).length;h+=1){var m=i[f][h];if(m.reg.test(p))return n(m,u,p)}}),l.media=c,l};var s=function(a,l){var c=l.split(/=(.+)/,2);return c.length===2?a[c[0]]=e(c[1]):c.length===1&&l.length>1&&(a[c[0]]=void 0),a};r.parseParams=function(a){return a.split(/;\s?/).reduce(s,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(a){return a.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(a){for(var l=[],c=a.split(" ").map(e),u=0;u<c.length;u+=3)l.push({component:c[u],ip:c[u+1],port:c[u+2]});return l},r.parseImageAttributes=function(a){return a.split(" ").map(function(l){return l.substring(1,l.length-1).split(",").reduce(s,{})})},r.parseSimulcastStreamList=function(a){return a.split(";").map(function(l){return l.split(",").map(function(c){var u,d=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),d=!0),{scid:u,paused:d}})})}})(qD);var Jg=HD,tz=/%[sdv%]/g,rz=function(r){var e=1,t=arguments,n=t.length;return r.replace(tz,function(i){if(e>=n)return i;var o=t[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},du=function(r,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,i=[r+"="+n];if(e.names)for(var o=0;o<e.names.length;o+=1){var s=e.names[o];e.name?i.push(t[e.name][s]):i.push(t[e.names[o]])}else i.push(t[e.name]);return rz.apply(null,i)},nz=["v","o","s","i","u","e","p","c","b","t","r","z","a"],iz=["i","c","b","a"],oz=function(r,e){e=e||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var t=e.outerOrder||nz,n=e.innerOrder||iz,i=[];return t.forEach(function(o){Jg[o].forEach(function(s){s.name in r&&r[s.name]!=null?i.push(du(o,s,r)):s.push in r&&r[s.push]!=null&&r[s.push].forEach(function(a){i.push(du(o,s,a))})})}),r.media.forEach(function(o){i.push(du("m",Jg.m[0],o)),n.forEach(function(s){Jg[s].forEach(function(a){a.name in o&&o[a.name]!=null?i.push(du(s,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(l){i.push(du(s,a,l))})})})}),i.join(`\r
281
+ `)+`\r
282
+ `},Ja=qD,sz=oz,az=sz,zD=Ja.parse;Ja.parseParams;Ja.parseFmtpConfig;Ja.parsePayloads;Ja.parseRemoteCandidates;Ja.parseImageAttributes;Ja.parseSimulcastStreamList;function Qr(r){if(typeof Buffer=="function")return Buffer.from(r).toString("base64");if(typeof btoa=="function"&&r instanceof Uint8Array)return btoa(r.reduce((e,t)=>e+String.fromCharCode(t),""));throw new Error("No base64 impl found!")}function vm(r){return Qr(r).replace(/={1,2}$/,"")}function mm(r){return vm(r).replace(/\+/g,"-").replace(/\//g,"_")}function Dr(r){if(typeof Buffer=="function")return Buffer.from(r,"base64");if(typeof atob=="function"){var e=function*(){for(var n=atob(r.replace(/-/g,"+").replace(/_/g,"/")),i=0;i<n.length;++i)yield n.charCodeAt(i)};return Uint8Array.from(e())}else throw new Error("No base64 impl found!")}var lz="abcdefghijklmnopqrstuvwxyz",cz="ABCDEFGHIJKLMNOPQRSTUVWXYZ",uz="0123456789";function dz(r){var e=new Uint8Array(r);return globalThis.crypto.getRandomValues(e),mm(e)}function Ei(r){return fz(r,cz+lz+uz)}function fz(r,e){for(var t="",n=0;n<r;++n)t+=e.charAt(Math.floor(Math.random()*e.length));return t}var Yo="org.matrix.msc3077.sdp_stream_metadata",St=function(r){return r.Usermedia="m.usermedia",r.Screenshare="m.screenshare",r}({}),td=null,kb=0,hz=()=>(td===null&&(td=new AudioContext),kb++,td),pz=()=>{if(kb--,kb===0){var r;(r=td)===null||r===void 0||r.close(),td=null}},vz=200,Ib=-60,mz=8,Li=function(r){return r.NewStream="new_stream",r.MuteStateChanged="mute_state_changed",r.LocalVolumeChanged="local_volume_changed",r.VolumeChanged="volume_changed",r.ConnectedChanged="connected_changed",r.Speaking="speaking",r.Disposed="disposed",r}({});class So extends Tt{constructor(e){super(),v(this,"stream",void 0),v(this,"sdpMetadataStreamId",void 0),v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"purpose",void 0),v(this,"speakingVolumeSamples",void 0),v(this,"client",void 0),v(this,"call",void 0),v(this,"roomId",void 0),v(this,"audioMuted",void 0),v(this,"videoMuted",void 0),v(this,"localVolume",1),v(this,"measuringVolumeActivity",!1),v(this,"audioContext",void 0),v(this,"analyser",void 0),v(this,"frequencyBinCount",void 0),v(this,"speakingThreshold",Ib),v(this,"speaking",!1),v(this,"volumeLooperTimeout",void 0),v(this,"_disposed",!1),v(this,"_connected",!1),v(this,"onAddTrack",()=>{this.emit(Li.NewStream,this.stream)}),v(this,"onCallState",t=>{t===Fe.Connected?this.connected=!0:t===Fe.Connecting&&(this.connected=!1)}),v(this,"volumeLooper",()=>{if(this.analyser&&this.measuringVolumeActivity){this.analyser.getFloatFrequencyData(this.frequencyBinCount);var t=-1/0;for(var n of this.frequencyBinCount)n>t&&(t=n);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(t),this.emit(Li.VolumeChanged,t);var i=!1;for(var o of this.speakingVolumeSamples)if(o>this.speakingThreshold){i=!0;break}this.speaking!==i&&(this.speaking=i,this.emit(Li.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,vz)}}),this.client=e.client,this.call=e.call,this.roomId=e.roomId,this.userId=e.userId,this.deviceId=e.deviceId,this.purpose=e.purpose,this.audioMuted=e.audioMuted,this.videoMuted=e.videoMuted,this.speakingVolumeSamples=new Array(mz).fill(-1/0),this.sdpMetadataStreamId=e.stream.id,this.updateStream(null,e.stream),this.stream=e.stream,this.hasAudioTrack&&this.initVolumeMeasuring(),e.call&&(e.call.addListener(Ye.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit(Li.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){if(t!==e){var n=this.measuringVolumeActivity;e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?(this.initVolumeMeasuring(),n&&this.measureVolumeActivity(!0)):this.measureVolumeActivity(!1),this.emit(Li.NewStream,this.stream)}}initVolumeMeasuring(){if(this.hasAudioTrack){this.audioContext||(this.audioContext=hz()),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1;var e=this.audioContext.createMediaStreamSource(this.stream);e.connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}}getMember(){var e,t=this.client.getRoom(this.roomId);return(e=t==null?void 0:t.getMember(this.userId))!==null&&e!==void 0?e: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(e){this.updateStream(this.stream,e)}setAudioVideoMuted(e,t){e!==null&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),t!==null&&(this.videoMuted=t),this.emit(Li.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(e){if(e){if(!this.analyser||!this.frequencyBinCount||!this.hasAudioTrack)return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(Li.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){var e=this.client.getMediaHandler(),t=this.stream.clone();return S.log("CallFeed clone() cloning stream (originalStreamId=".concat(this.stream.id,", newStreamId").concat(t.id,")")),this.purpose===St.Usermedia?e.userMediaStreams.push(t):e.screensharingStreams.push(t),new So({client:this.client,roomId:this.roomId,userId:this.userId,deviceId:this.deviceId,stream:t,purpose:this.purpose,audioMuted:this.audioMuted,videoMuted:this.videoMuted})}dispose(){var e,t;clearTimeout(this.volumeLooperTimeout),(e=this.stream)===null||e===void 0||e.removeEventListener("addtrack",this.onAddTrack),(t=this.call)===null||t===void 0||t.removeListener(Ye.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,pz()),this._disposed=!0,this.emit(Li.Disposed)}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit(Li.LocalVolumeChanged,e)}}var wo=function(r){return r[r.Blocked=-1]="Blocked",r[r.Unverified=0]="Unverified",r[r.Verified=1]="Verified",r}({});class YD{constructor(e){v(this,"deviceId",void 0),v(this,"userId",void 0),v(this,"algorithms",void 0),v(this,"keys",void 0),v(this,"verified",void 0),v(this,"signatures",void 0),v(this,"displayName",void 0),v(this,"dehydrated",!1),this.deviceId=e.deviceId,this.userId=e.userId,this.algorithms=e.algorithms,this.keys=e.keys,this.verified=e.verified||wo.Unverified,this.signatures=e.signatures||new Map,this.displayName=e.displayName,this.dehydrated=!!e.dehydrated}getFingerprint(){return this.keys.get("ed25519:".concat(this.deviceId))}getIdentityKey(){return this.keys.get("curve25519:".concat(this.deviceId))}}class tn{static fromStorage(e,t){var n=new tn(t);for(var i in e)e.hasOwnProperty(i)&&(n[i]=e[i]);return n}constructor(e){this.deviceId=e,v(this,"algorithms",[]),v(this,"keys",{}),v(this,"verified",wo.Unverified),v(this,"known",!1),v(this,"unsigned",{}),v(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==wo.Blocked}isVerified(){return this.verified==wo.Verified}isUnverified(){return this.verified==wo.Unverified}isKnown(){return this.known===!0}}v(tn,"DeviceVerification",{VERIFIED:wo.Verified,UNVERIFIED:wo.Unverified,BLOCKED:wo.Blocked});var gz=3e3,xb=function(r){return r.Incoming="Call.incoming",r}({});class yz{constructor(e){v(this,"calls",void 0),v(this,"callEventBuffer",void 0),v(this,"nextSeqByCall",new Map),v(this,"toDeviceEventBuffers",new Map),v(this,"client",void 0),v(this,"candidateEventsByCall",void 0),v(this,"eventBufferPromiseChain",void 0),v(this,"onSync",()=>{var t=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then(()=>this.evaluateEventBuffer(t)):this.eventBufferPromiseChain=this.evaluateEventBuffer(t)}),v(this,"onRoomTimeline",t=>{this.callEventBuffer.push(t)}),v(this,"onToDeviceEvent",t=>{var n=t.getContent();if(!n.call_id){this.callEventBuffer.push(t);return}if(this.nextSeqByCall.has(n.call_id)||this.nextSeqByCall.set(n.call_id,0),n.seq===void 0){this.callEventBuffer.push(t);return}var i=this.nextSeqByCall.get(n.call_id)||0;if(n.seq!==i){this.toDeviceEventBuffers.has(n.call_id)||this.toDeviceEventBuffers.set(n.call_id,[]);var o=this.toDeviceEventBuffers.get(n.call_id),s=o.findIndex(u=>u.getContent().seq>n.seq);s===-1?o.push(t):o.splice(s,0,t)}else{var a=n.call_id;this.callEventBuffer.push(t),this.nextSeqByCall.set(a,n.seq+1);for(var l=this.toDeviceEventBuffers.get(a),c=l&&l.shift();c&&c.getContent().seq===this.nextSeqByCall.get(a);)this.callEventBuffer.push(c),this.nextSeqByCall.set(a,c.getContent().seq+1),c=l.shift()}}),this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(Te.Sync,this.onSync),this.client.on(fe.Timeline,this.onRoomTimeline),this.client.on(Te.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(Te.Sync,this.onSync),this.client.removeListener(fe.Timeline,this.onRoomTimeline),this.client.removeListener(Te.ToDeviceEvent,this.onToDeviceEvent)}evaluateEventBuffer(e){var t=this;return _(function*(){yield Promise.all(e.map(u=>t.client.decryptEventIfNeeded(u)));var n=e.filter(u=>{var d=u.getType();return d.startsWith("m.call.")||d.startsWith("org.matrix.call.")}),i=new Set;for(var o of n){var s=o.getType();(s===V.CallAnswer||s===V.CallHangup)&&i.add(o.getContent().call_id)}for(var a of n){var l=a.getType(),c=a.getContent().call_id;if(!(l===V.CallInvite&&i.has(c)))try{yield t.handleCallEvent(a)}catch(u){S.error("CallEventHandler evaluateEventBuffer() caught exception handling call event",u)}}})()}handleCallEvent(e){var t=this;return _(function*(){var n;t.client.emit(Te.ReceivedVoipEvent,e);var i=e.getContent(),o=e.getRoomId()||((n=t.client.groupCallEventHandler.getGroupCallById(i.conf_id))===null||n===void 0||(n=n.room)===null||n===void 0?void 0:n.roomId),s=i.conf_id,a=e.getType(),l=e.getSender(),c=i.call_id?t.calls.get(i.call_id):void 0,u,d;if(s){if(d=t.client.groupCallEventHandler.getGroupCallById(s),!d){S.warn("CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=".concat(s,", type=").concat(a,")"));return}if(u=i.device_id,!u){S.warn("CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=".concat(l,")")),d.emit(yt.Error,new QD(l));return}if(i.dest_session_id!==t.client.getSessionId()){S.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring");return}}var f=l===t.client.credentials.userId&&(u===void 0||u===t.client.getDeviceId());if(o){if(a===V.CallInvite){var p,h,m;if(f||e.getLocalAge()>i.lifetime-gz||c&&c.state===Fe.Ended||(c&&S.warn("CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=".concat(i.call_id,")")),i.invitee&&i.invitee!==t.client.getUserId()))return;var w=((p=t.client.getTurnServersExpiry())!==null&&p!==void 0?p:0)-Date.now();if(S.info("CallEventHandler handleCallEvent() current turn creds expire in "+w+" ms"),c=(h=Bd(t.client,o,{forceTURN:t.client.forceTURN,opponentDeviceId:u,groupCallId:s,opponentSessionId:i.sender_session_id}))!==null&&h!==void 0?h:void 0,!c){S.log("CallEventHandler handleCallEvent() this client does not support WebRTC (callId=".concat(i.call_id,")"));return}c.callId=i.call_id;var g=(m=d)===null||m===void 0?void 0:m.getGroupCallStats();g&&c.initStats(g);try{yield c.initWithInvite(e)}catch(N){if(N instanceof vo)if(N.code===nd.UnknownDevice){var b;(b=d)===null||b===void 0||b.emit(yt.Error,N)}else S.error(N)}if(t.calls.set(c.callId,c),t.candidateEventsByCall.get(c.callId))for(var R of t.candidateEventsByCall.get(c.callId))c.onRemoteIceCandidatesReceived(R);var k;for(var O of t.calls.values()){var T,x=[Fe.WaitLocalMedia,Fe.CreateOffer,Fe.InviteSent].includes(O.state);if(c.roomId===O.roomId&&O.direction===es.Outbound&&((T=c.getOpponentMember())===null||T===void 0?void 0:T.userId)===O.invitee&&x){k=O;break}}k?k.callId>c.callId?(S.log("CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=".concat(c.callId,", outgoingId=").concat(k.callId,")")),k.replacedBy(c)):(S.log("CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=".concat(c.callId,", outgoingId=").concat(k.callId,")")),c.hangup(qe.Replaced,!0)):t.client.emit(xb.Incoming,c);return}else if(a===V.CallCandidates){if(f)return;c?c.onRemoteIceCandidatesReceived(e):(t.candidateEventsByCall.has(i.call_id)||t.candidateEventsByCall.set(i.call_id,[]),t.candidateEventsByCall.get(i.call_id).push(e));return}else if([V.CallHangup,V.CallReject].includes(a)){if(c)c.state!==Fe.Ended&&(a===V.CallHangup?c.onHangupReceived(i):c.onRejectReceived(i),c.state===Fe.Ended&&t.calls.delete(i.call_id));else{var C;c=(C=Bd(t.client,o,{opponentDeviceId:u,opponentSessionId:i.sender_session_id}))!==null&&C!==void 0?C:void 0,c&&(c.callId=i.call_id,c.initWithHangup(e),t.calls.set(i.call_id,c))}return}if(!c||!c.hasPeerConnection){S.info("CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=".concat(a,")"));return}if(e.getContent().party_id!==c.ourPartyId)switch(a){case V.CallAnswer:f?c.state===Fe.Ringing&&c.onAnsweredElsewhere(i):c.onAnswerReceived(e);break;case V.CallSelectAnswer:c.onSelectAnswerReceived(e);break;case V.CallNegotiate:c.onNegotiateReceived(e);break;case V.CallAssertedIdentity:case V.CallAssertedIdentityPrefix:c.onAssertedIdentityReceived(e);break;case V.CallSDPStreamMetadataChanged:case V.CallSDPStreamMetadataChangedPrefix:c.onSDPStreamMetadataChangedReceived(e);break}}})()}}var Ob=function(r){return r.Incoming="GroupCall.incoming",r.Outgoing="GroupCall.outgoing",r.Ended="GroupCall.ended",r.Participants="GroupCall.participants",r}({});class Sz{constructor(e){this.client=e,v(this,"groupCalls",new Map),v(this,"roomDeferreds",new Map),v(this,"onRoomsChanged",t=>{this.createGroupCallForRoom(t)}),v(this,"onRoomStateChanged",(t,n)=>{var i=t.getType();if(i===V.GroupCallPrefix){var o=t.getStateKey(),s=t.getContent(),a=this.groupCalls.get(n.roomId);!a&&!s["m.terminated"]&&!t.isRedacted()?this.createGroupCallFromRoomStateEvent(t):a&&a.groupCallId===o?s["m.terminated"]||t.isRedacted()?a.terminate(!1):s["m.type"]!==a.type&&S.warn("GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=".concat(n.roomId,")")):a&&a.groupCallId!==o&&S.warn("GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=".concat(n.roomId,")"))}})}start(){var e=this;return _(function*(){e.client.getSyncState()!==ct.Syncing&&(S.debug("GroupCallEventHandler start() waiting for client to start syncing"),yield new Promise(i=>{var o=()=>{if(e.client.getSyncState()===ct.Syncing)return e.client.off(Te.Sync,o),i()};e.client.on(Te.Sync,o)}));var t=e.client.getRooms();for(var n of t)e.createGroupCallForRoom(n);e.client.on(Te.Room,e.onRoomsChanged),e.client.on(Ne.Events,e.onRoomStateChanged)})()}stop(){this.client.removeListener(Te.Room,this.onRoomsChanged),this.client.removeListener(Ne.Events,this.onRoomStateChanged)}getRoomDeferred(e){var t=this.roomDeferreds.get(e);if(t===void 0){var n;t={prom:new Promise(i=>{n=i})},t.resolve=n,this.roomDeferreds.set(e,t)}return t}waitUntilRoomReadyForGroupCalls(e){return this.getRoomDeferred(e).prom}getGroupCallById(e){return[...this.groupCalls.values()].find(t=>t.groupCallId===e)}createGroupCallForRoom(e){var t=e.currentState.getStateEvents(V.GroupCallPrefix),n=t.sort((s,a)=>a.getTs()-s.getTs());for(var i of n){var o=i.getContent();if(!(o["m.terminated"]||i.isRedacted())){S.debug("GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=".concat(i.getStateKey(),", ts=").concat(i.getTs(),", roomId=").concat(e.roomId,", numOfPossibleCalls=").concat(t.length,")")),this.createGroupCallFromRoomStateEvent(i);break}}this.getRoomDeferred(e.roomId).resolve()}createGroupCallFromRoomStateEvent(e){var t=e.getRoomId(),n=e.getContent(),i=this.client.getRoom(t);if(!i){S.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=".concat(t,")"));return}var o=e.getStateKey(),s=n["m.type"];if(!Object.values(gm).includes(s)){S.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=".concat(s,", roomId=").concat(t,")"));return}var a=n["m.intent"];if(!Object.values(XD).includes(a)){S.warn("Received invalid group call intent (type=".concat(s,", roomId=").concat(t,")"));return}var l=!!n["io.element.ptt"],c;if(n!=null&&n.dataChannelsEnabled&&n!==null&&n!==void 0&&n.dataChannelOptions){var{ordered:u,maxPacketLifeTime:d,maxRetransmits:f,protocol:p}=n.dataChannelOptions;c={ordered:u,maxPacketLifeTime:d,maxRetransmits:f,protocol:p}}var h=new Sw(this.client,i,s,l,a,o,(n==null?void 0:n.dataChannelsEnabled)||this.client.isVoipWithNoMediaAllowed,c,this.client.isVoipWithNoMediaAllowed,this.client.useLivekitForGroupCalls,n["io.element.livekit_service_url"]);return this.groupCalls.set(i.roomId,h),this.client.emit(Ob.Incoming,h),h}}class bz{constructor(){v(this,"bandwidth",{}),v(this,"bitrate",{}),v(this,"packetLoss",{}),v(this,"transport",[])}}class _z{static buildBandwidthReport(e){var t=e.availableIncomingBitrate,n=e.availableOutgoingBitrate;return{download:t?Math.round(t/1e3):0,upload:n?Math.round(n/1e3):0}}}class Ez{static buildReport(e,t,n,i){var o=e==null?void 0:e.get(t.localCandidateId),s=e==null?void 0:e.get(t.remoteCandidateId);if(s&&o){var a=s.ip!==void 0?s.ip:s.address,l=s.port,c="".concat(a,":").concat(l),u=o.ip!==void 0?o.ip:o.address,d=o.port,f="".concat(u,":").concat(d),p=s.protocol;n.some(h=>h.ip===c&&h.type===p&&h.localIp===f)||n.push({ip:c,type:p,localIp:f,isFocus:i,localCandidateType:o.candidateType,remoteCandidateType:s.candidateType,networkType:o.networkType,rtt:t.currentRoundTripTime?t.currentRoundTripTime*1e3:NaN})}return n}}class wz{constructor(){v(this,"ssrcToMid",{local:new Map,remote:new Map})}findMidBySsrc(e,t){var n;return this.ssrcToMid[t].forEach((i,o)=>{if(i.find(s=>s==e)){n=o;return}}),n}parse(e,t){var n=zD(e),i=new Map;n.media.forEach(o=>{if(o.mid&&o.type==="video"||o.type==="audio"){var s,a=[];(s=o.ssrcs)===null||s===void 0||s.forEach(l=>{l.attribute==="cname"&&a.push("".concat(l.id))}),i.set("".concat(o.mid),a)}}),this.ssrcToMid[t]=i}getSsrcToMidMap(e){return this.ssrcToMid[e]}}class Tz{constructor(e){this.pc=e}getLocalTracks(e){var t=n=>n!==null&&n.kind===e;return this.pc.getTransceivers().filter(n=>n.currentDirection==="sendonly"||n.currentDirection==="sendrecv").filter(n=>n.sender!==null).map(n=>n.sender).map(n=>n.track).filter(t)}getTackById(e){return this.pc.getTransceivers().map(t=>{if((t==null?void 0:t.sender.track)!==null&&t.sender.track.id===e)return t.sender.track;if((t==null?void 0:t.receiver.track)!==null&&t.receiver.track.id===e)return t.receiver.track}).find(t=>t!==void 0)}getLocalTrackIdByMid(e){var t=this.pc.getTransceivers().find(n=>n.mid===e);if(t!==void 0&&t.sender&&t.sender.track)return t.sender.track.id}getRemoteTrackIdByMid(e){var t=this.pc.getTransceivers().find(n=>n.mid===e);if(t!==void 0&&t.receiver&&t.receiver.track)return t.receiver.track.id}getActiveSimulcastStreams(){return 3}getTransceiverByTrackId(e){return this.pc.getTransceivers().find(t=>t.receiver.track.id===e||t.sender.track!==null&&t.sender.track.id===e)}}class Rz{constructor(e,t,n){this.trackId=e,this.type=t,this.kind=n,v(this,"loss",{packetsTotal:0,packetsLost:0,isDownloadStream:!1}),v(this,"bitrate",{download:0,upload:0}),v(this,"resolution",{width:-1,height:-1}),v(this,"audioConcealment",{concealedAudio:0,totalAudioDuration:0}),v(this,"framerate",0),v(this,"jitter",0),v(this,"codec",""),v(this,"isAlive",!0),v(this,"isMuted",!1),v(this,"isEnabled",!0)}getType(){return this.type}setLoss(e){this.loss=e}getLoss(){return this.loss}setResolution(e){this.resolution=e}getResolution(){return this.resolution}setFramerate(e){this.framerate=e}getFramerate(){return this.framerate}setBitrate(e){this.bitrate=e}getBitrate(){return this.bitrate}setCodec(e){return this.codec=e,!0}getCodec(){return this.codec}resetBitrate(){this.bitrate={download:0,upload:0}}set alive(e){this.isAlive=e}get alive(){return this.isAlive}set muted(e){this.isMuted=e}get muted(){return this.isMuted}set enabled(e){this.isEnabled=e}get enabled(){return this.isEnabled}setJitter(e){this.jitter=e}getJitter(){return this.jitter}setAudioConcealment(e,t){this.audioConcealment.concealedAudio=e,this.audioConcealment.totalAudioDuration=t}getAudioConcealment(){return this.audioConcealment}}class Cz{constructor(e,t){this.mediaSsrcHandler=e,this.mediaTrackHandler=t,v(this,"track2stats",new Map)}findTrack2Stats(e,t){var n;if(e.trackIdentifier)n=e.trackIdentifier;else if(e.mid)n=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid);else if(e.ssrc){var i=this.mediaSsrcHandler.findMidBySsrc(e.ssrc,t);if(!i)return;n=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid)}if(n){var o=this.track2stats.get(n);if(!o){var s=this.mediaTrackHandler.getTackById(n);if(s!==void 0){var a=s.kind==="audio"?s.kind:"video";o=new Rz(n,t,a),this.track2stats.set(n,o)}else return}return o}}findLocalVideoTrackStats(e){var t=this.mediaTrackHandler.getLocalTracks("video");if(t.length!==0)return this.findTrack2Stats(e,"local")}getTrack2stats(){return this.track2stats}findTransceiverByTrackId(e){return this.mediaTrackHandler.getTransceiverByTrackId(e)}}class ua{static getNonNegativeValue(e){var t=e;return typeof t!="number"&&(t=Number(t)),isNaN(t)?0:Math.max(0,t)}}class Pn{static buildFramerateResolution(e,t){var n={height:t.frameHeight,width:t.frameWidth},i=t.framesPerSecond;n.height&&n.width&&e.setResolution(n),e.setFramerate(Math.round(i||0))}static calculateSimulcastFramerate(e,t,n,i){var o=e.getFramerate();if(!o){if(n){var s=t.timestamp-n.timestamp;if(s>0&&t.framesSent){var a=t.framesSent-n.framesSent;o=a/s*1e3}}if(!o)return}o=i?Math.round(o/i):0,e.setFramerate(o)}static buildCodec(e,t,n){var i=e==null?void 0:e.get(n.codecId);if(i){var o=i.mimeType.split("/")[1];o&&t.setCodec(o)}}static buildBitrateReceived(e,t,n){e.setBitrate({download:Pn.calculateBitrate(t.bytesReceived,n.bytesReceived,t.timestamp,n.timestamp),upload:0})}static buildBitrateSend(e,t,n){e.setBitrate({download:0,upload:this.calculateBitrate(t.bytesSent,n.bytesSent,t.timestamp,n.timestamp)})}static buildPacketsLost(e,t,n){var i=t.type==="outbound-rtp"?"packetsSent":"packetsReceived",o=t[i];(!o||o<0)&&(o=0);var s=ua.getNonNegativeValue(n[i]),a=Math.max(0,o-s),l=ua.getNonNegativeValue(t.packetsLost),c=ua.getNonNegativeValue(n.packetsLost),u=Math.max(0,l-c);e.setLoss({packetsTotal:a+u,packetsLost:u,isDownloadStream:t.type!=="outbound-rtp"})}static calculateBitrate(e,t,n,i){var o=ua.getNonNegativeValue(e),s=ua.getNonNegativeValue(t),a=Math.max(0,o-s),l=n-i,c=0;return l>0&&(c=Math.round(a*8/l)),c}static setTrackStatsState(e,t){var n;if(t===void 0){e.alive=!1;return}var i=e.getType()==="remote"?t.receiver.track:t==null||(n=t.sender)===null||n===void 0?void 0:n.track;if(i==null){e.alive=!1;return}if(i.readyState==="ended"){e.alive=!1;return}e.muted=i.muted,e.enabled=i.enabled,e.alive=!0}static buildTrackSummary(e){var t={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},n={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},i=e.filter(s=>s.getType()==="remote"),o=i.filter(s=>s.kind==="audio");return i.forEach(s=>{var a=s.kind==="video"?t:n;if(a.count++,s.alive&&s.muted&&a.muted++,a.maxJitter<s.getJitter()&&(a.maxJitter=s.getJitter()),a.maxPacketLoss<s.getLoss().packetsLost&&(a.maxPacketLoss=s.getLoss().packetsLost),o.length>0){var l,c;a.concealedAudio+=(l=s.getAudioConcealment())===null||l===void 0?void 0:l.concealedAudio,a.totalAudio+=(c=s.getAudioConcealment())===null||c===void 0?void 0:c.totalAudioDuration}}),{audioTrackSummary:n,videoTrackSummary:t}}static buildJitter(e,t){if(t.type==="inbound-rtp"){var n=t==null?void 0:t.jitter;if(n!==void 0){var i=ua.getNonNegativeValue(n);e.setJitter(Math.round(i*1e3))}else e.setJitter(-1)}}static buildAudioConcealment(e,t){if(t.type==="inbound-rtp"){var n=1e3*(t==null?void 0:t.totalSamplesDuration)/(t==null?void 0:t.totalSamplesReceived),i=n*(t==null?void 0:t.concealedSamples),o=1e3*(t==null?void 0:t.totalSamplesDuration);e.setAudioConcealment(i,o)}}}class rd{static build(e){var t={},n={download:0,upload:0},i={download:0,upload:0},o=0,s=0,a={local:new Map,remote:new Map},l={local:new Map,remote:new Map},c={local:new Map,remote:new Map},u=new Map,d=new Map,f=0,p=0,h=0,m=0,w=0,g=0;for(var[b,R]of e){var k=R.getLoss(),O=k.isDownloadStream?"download":"upload";if(n[O]+=k.packetsTotal,i[O]+=k.packetsLost,o+=R.getBitrate().download,s+=R.getBitrate().upload,R.kind==="audio"){var T=R.getAudioConcealment();w+=T.concealedAudio,g+=T.totalAudioDuration,f+=R.getBitrate().download,p+=R.getBitrate().upload}else h+=R.getBitrate().download,m+=R.getBitrate().upload;a[R.getType()].set(b,R.getResolution()),l[R.getType()].set(b,R.getFramerate()),c[R.getType()].set(b,R.getCodec()),R.getType()==="remote"&&(u.set(b,R.getJitter()),R.kind==="audio"&&d.set(b,R.getAudioConcealment())),R.resetBitrate()}return t.bitrate={upload:s,download:o},t.bitrate.audio={upload:p,download:f},t.bitrate.video={upload:m,download:h},t.packetLoss={total:rd.calculatePacketLoss(i.download+i.upload,n.download+n.upload),download:rd.calculatePacketLoss(i.download,n.download),upload:rd.calculatePacketLoss(i.upload,n.upload)},t.audioConcealment=d,t.totalAudioConcealment={concealedAudio:w,totalAudioDuration:g},t.framerate=l,t.resolution=a,t.codec=c,t.jitter=u,t}static calculatePacketLoss(e,t){return!t||t<=0||!e||e<=0?0:Math.round(e/t*100)}}class gs{static buildCallFeedReport(e,t,n){var i=n.getTransceivers(),o=[],s=[];return i.forEach(a=>{var l,c=(l=a.sender)!==null&&l!==void 0&&l.track?gs.buildTrackStats(a.sender.track,"sender"):null,u=gs.buildTrackStats(a.receiver.track,"receiver");o.push({mid:a.mid==null?"null":a.mid,direction:a.direction,currentDirection:a.currentDirection==null?"null":a.currentDirection,sender:c,receiver:u})}),{callId:e,opponentMemberId:t,transceiver:o,callFeeds:s}}static buildTrackStats(e){var t,n,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"--",o=(t=e.getSettings())===null||t===void 0?void 0:t.deviceId,s=(n=e.getConstraints())===null||n===void 0?void 0:n.deviceId;return{id:e.id,kind:e.kind,settingDeviceId:o||"unknown",constrainDeviceId:s||"unknown",muted:e.muted,enabled:e.enabled,readyState:e.readyState,label:i}}static expandCallFeedReport(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unknown";return e.callFeeds||(e.callFeeds=[]),t.forEach(i=>{var o=i.stream.getAudioTracks(),s=i.stream.getVideoTracks(),a=o.length>0?gs.buildTrackStats(i.stream.getAudioTracks()[0],i.purpose):null,l=s.length>0?gs.buildTrackStats(i.stream.getVideoTracks()[0],i.purpose):null,c={stream:i.stream.id,type:i.isLocal()?"local":"remote",audio:a,video:l,purpose:i.purpose,prefix:n,isVideoMuted:i.isVideoMuted(),isAudioMuted:i.isAudioMuted()};e.callFeeds.push(c)}),e}}function IC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function ah(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?IC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):IC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class kz{constructor(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;this.callId=e,this.opponentMemberId=t,this.pc=n,this.emitter=i,this.isFocus=o,v(this,"isActive",!0),v(this,"previousStatsReport",void 0),v(this,"currentStatsReport",void 0),v(this,"connectionStats",new bz),v(this,"trackStats",void 0),n.addEventListener("signalingstatechange",this.onSignalStateChange.bind(this)),this.trackStats=new Cz(new wz,new Tz(n))}processStats(e,t){var n=this;return _(function*(){var i={isFirstCollection:n.previousStatsReport===void 0,receivedMedia:0,receivedAudioMedia:0,receivedVideoMedia:0,audioTrackSummary:{count:0,muted:0,maxPacketLoss:0,maxJitter:0,concealedAudio:0,totalAudio:0},videoTrackSummary:{count:0,muted:0,maxPacketLoss:0,maxJitter:0,concealedAudio:0,totalAudio:0}};if(n.isActive){var o=n.pc.getStats();if(typeof(o==null?void 0:o.then)=="function")return o.then(s=>{var a,l;n.currentStatsReport=typeof(s==null?void 0:s.result)=="function"?s.result():s;try{n.processStatsReport(e,t)}catch(u){return n.handleError(u),i}n.previousStatsReport=n.currentStatsReport,i.receivedMedia=n.connectionStats.bitrate.download,i.receivedAudioMedia=((a=n.connectionStats.bitrate.audio)===null||a===void 0?void 0:a.download)||0,i.receivedVideoMedia=((l=n.connectionStats.bitrate.video)===null||l===void 0?void 0:l.download)||0;var c=Pn.buildTrackSummary(Array.from(n.trackStats.getTrack2stats().values()));return ah(ah({},i),{},{audioTrackSummary:c.audioTrackSummary,videoTrackSummary:c.videoTrackSummary})}).catch(s=>(n.handleError(s),i));n.isActive=!1}return Promise.resolve(i)})()}processStatsReport(e,t){var n,i=new Map;i.callId=this.callId,i.opponentMemberId=this.opponentMemberId,(n=this.currentStatsReport)===null||n===void 0||n.forEach(o=>{var s=this.previousStatsReport?this.previousStatsReport.get(o.id):null;if(o.type==="candidate-pair"&&o.nominated&&o.state==="succeeded")this.connectionStats.bandwidth=_z.buildBandwidthReport(o),this.connectionStats.transport=Ez.buildReport(this.currentStatsReport,o,this.connectionStats.transport,this.isFocus);else if(o.type==="inbound-rtp"||o.type==="outbound-rtp"){var a=this.trackStats.findTrack2Stats(o,o.type==="inbound-rtp"?"remote":"local");if(!a)return;if(s&&Pn.buildPacketsLost(a,o,s),o.type==="inbound-rtp"){Pn.buildFramerateResolution(a,o),s&&Pn.buildBitrateReceived(a,o,s);var l=this.trackStats.findTransceiverByTrackId(a.trackId);Pn.setTrackStatsState(a,l),Pn.buildJitter(a,o),Pn.buildAudioConcealment(a,o)}else s&&(i.set(a.trackId,ua.getNonNegativeValue(o.bytesSent)),Pn.buildBitrateSend(a,o,s));Pn.buildCodec(this.currentStatsReport,a,o)}else if(o.type==="track"&&o.kind==="video"&&!o.remoteSource){var c=this.trackStats.findLocalVideoTrackStats(o);if(!c)return;Pn.buildFramerateResolution(c,o),Pn.calculateSimulcastFramerate(c,o,s,this.trackStats.mediaTrackHandler.getActiveSimulcastStreams())}}),this.emitter.emitByteSendReport(i),this.emitter.emitCallFeedReport(gs.buildCallFeedReport(this.callId,this.opponentMemberId,this.pc)),this.processAndEmitConnectionStatsReport()}setActive(e){this.isActive=e}getActive(){return this.isActive}handleError(e){this.isActive=!1,S.warn("CallStatsReportGatherer ".concat(this.callId," processStatsReport fails and set to inactive ").concat(e))}processAndEmitConnectionStatsReport(){var e=rd.build(this.trackStats.getTrack2stats());e.callId=this.callId,e.opponentMemberId=this.opponentMemberId,this.connectionStats.bandwidth=e.bandwidth,this.connectionStats.bitrate=e.bitrate,this.connectionStats.packetLoss=e.packetLoss,this.emitter.emitConnectionStatsReport(ah(ah({},e),{},{transport:this.connectionStats.transport})),this.connectionStats.transport=[]}stopProcessingStats(){}onSignalStateChange(){this.pc.signalingState==="stable"&&(this.pc.currentRemoteDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentRemoteDescription.sdp,"remote"),this.pc.currentLocalDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentLocalDescription.sdp,"local"))}setOpponentMemberId(e){this.opponentMemberId=e}}var To=function(r){return r.CONNECTION_STATS="StatsReport.connection_stats",r.CALL_FEED_REPORT="StatsReport.call_feed_report",r.BYTE_SENT_STATS="StatsReport.byte_sent_stats",r.SUMMARY_STATS="StatsReport.summary_stats",r}({});class Iz extends Tt{emitByteSendReport(e){this.emit(To.BYTE_SENT_STATS,e)}emitConnectionStatsReport(e){this.emit(To.CONNECTION_STATS,e)}emitCallFeedReport(e){this.emit(To.CALL_FEED_REPORT,e)}emitSummaryStatsReport(e){this.emit(To.SUMMARY_STATS,e)}}class JD{constructor(e){this.emitter=e}build(e){var t=e.filter(u=>!u.isFirstCollection),n=t.length,i=e.length;if(n!==0){var o={receivedAudio:0,receivedVideo:0,receivedMedia:0,concealedAudio:0,totalAudio:0},s=0,a=0;t.forEach(u=>{this.countTrackListReceivedMedia(o,u),this.countConcealedAudio(o,u),s=this.buildMaxJitter(s,u),a=this.buildMaxPacketLoss(a,u)});var l=5,c={percentageReceivedMedia:Number((o.receivedMedia/n).toFixed(l)),percentageReceivedVideoMedia:Number((o.receivedVideo/n).toFixed(l)),percentageReceivedAudioMedia:Number((o.receivedAudio/n).toFixed(l)),maxJitter:s,maxPacketLoss:a,percentageConcealedAudio:Number(o.totalAudio>0?(o.concealedAudio/o.totalAudio).toFixed(l):0),peerConnections:i};this.emitter.emitSummaryStatsReport(c)}}static extendSummaryReport(e,t){var n=[],i=[];for(var o of t){i.push(o);for(var s of o[1])n.push(s)}e.opponentDevicesInCall=Math.max(0,n.length-1),e.opponentUsersInCall=Math.max(0,i.length-1),e.diffDevicesToPeerConnections=Math.max(0,n.length-1)-e.peerConnections,e.ratioPeerConnectionToDevices=Math.max(0,n.length-1)==0?0:e.peerConnections/(n.length-1)}countTrackListReceivedMedia(e,t){var n=!1,i=!1;(t.receivedAudioMedia>0||t.audioTrackSummary.count===0)&&(e.receivedAudio++,n=!0),(t.receivedVideoMedia>0||t.videoTrackSummary.count===0||t.videoTrackSummary.muted>0&&t.videoTrackSummary.muted===t.videoTrackSummary.count)&&(e.receivedVideo++,i=!0),i&&n&&e.receivedMedia++}buildMaxJitter(e,t){return e<t.videoTrackSummary.maxJitter&&(e=t.videoTrackSummary.maxJitter),e<t.audioTrackSummary.maxJitter&&(e=t.audioTrackSummary.maxJitter),e}buildMaxPacketLoss(e,t){return e<t.videoTrackSummary.maxPacketLoss&&(e=t.videoTrackSummary.maxPacketLoss),e<t.audioTrackSummary.maxPacketLoss&&(e=t.audioTrackSummary.maxPacketLoss),e}countConcealedAudio(e,t){e.concealedAudio+=t.audioTrackSummary.concealedAudio,e.totalAudio+=t.audioTrackSummary.totalAudio}}class xz{constructor(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1e4;this.groupCallId=e,this.userId=t,this.interval=n,v(this,"timer",void 0),v(this,"gatherers",new Map),v(this,"reports",new Iz),v(this,"summaryStatsReportGatherer",new JD(this.reports))}start(){this.timer===void 0&&this.interval>0&&(this.timer=setInterval(()=>{this.processStats()},this.interval))}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.gatherers.forEach(e=>e.stopProcessingStats()))}hasStatsReportGatherer(e){return this.gatherers.has(e)}addStatsReportGatherer(e,t,n){return this.hasStatsReportGatherer(e)?!1:(this.gatherers.set(e,new kz(e,t,n,this.reports)),!0)}removeStatsReportGatherer(e){return this.gatherers.delete(e)}getStatsReportGatherer(e){return this.hasStatsReportGatherer(e)?this.gatherers.get(e):void 0}updateOpponentMember(e,t){var n;(n=this.getStatsReportGatherer(e))===null||n===void 0||n.setOpponentMemberId(t)}processStats(){var e=[];this.gatherers.forEach(t=>{e.push(t.processStats(this.groupCallId,this.userId))}),Promise.all(e).then(t=>this.summaryStatsReportGatherer.build(t)).catch(t=>{S.error("Could not build summary stats report",t)})}setInterval(e){this.interval=e}}function xC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function lh(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?xC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):xC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var XD=function(r){return r.Ring="m.ring",r.Prompt="m.prompt",r.Room="m.room",r}({}),gm=function(r){return r.Video="m.video",r.Voice="m.voice",r}({}),Oz=function(r){return r.CallEnded="call_ended",r}({}),yt=function(r){return r.GroupCallStateChanged="group_call_state_changed",r.ActiveSpeakerChanged="active_speaker_changed",r.CallsChanged="calls_changed",r.UserMediaFeedsChanged="user_media_feeds_changed",r.ScreenshareFeedsChanged="screenshare_feeds_changed",r.LocalScreenshareStateChanged="local_screenshare_state_changed",r.LocalMuteStateChanged="local_mute_state_changed",r.ParticipantsChanged="participants_changed",r.Error="group_call_error",r}({}),Au=function(r){return r.ConnectionStats="GroupCall.connection_stats",r.ByteSentStats="GroupCall.byte_sent_stats",r.SummaryStats="GroupCall.summary_stats",r.CallFeedStats="GroupCall.call_feed_stats",r}({}),nd=function(r){return r.NoUserMedia="no_user_media",r.UnknownDevice="unknown_device",r.PlaceCallFailed="place_call_failed",r}({});class Pb extends Error{constructor(e,t,n){n?(super(t+": "+n),v(this,"code",void 0)):(super(t),v(this,"code",void 0)),this.code=e}}class QD extends Pb{constructor(e){super(nd.UnknownDevice,"No device found for "+e),this.userId=e}}var Mt=function(r){return r.LocalCallFeedUninitialized="local_call_feed_uninitialized",r.InitializingLocalCallFeed="initializing_local_call_feed",r.LocalCallFeedInitialized="local_call_feed_initialized",r.Entered="entered",r.Ended="ended",r}({}),OC=1e3*60*60;function ch(r){var e;return((e=r.getOpponentMember())===null||e===void 0?void 0:e.userId)||r.invitee||null}class Sw extends Tt{constructor(e,t,n,i,o,s,a,l,c){var u,d,f=arguments.length>9&&arguments[9]!==void 0?arguments[9]:!1,p=arguments.length>10?arguments[10]:void 0;super(),this.client=e,this.room=t,this.type=n,this.isPtt=i,this.intent=o,this.dataChannelsEnabled=a,this.dataChannelOptions=l,this.useLivekit=f,v(this,"activeSpeakerInterval",1e3),v(this,"retryCallInterval",5e3),v(this,"participantTimeout",1e3*15),v(this,"pttMaxTransmitTime",1e3*20),v(this,"activeSpeaker",void 0),v(this,"localCallFeed",void 0),v(this,"localScreenshareFeed",void 0),v(this,"localDesktopCapturerSourceId",void 0),v(this,"userMediaFeeds",[]),v(this,"screenshareFeeds",[]),v(this,"groupCallId",void 0),v(this,"allowCallWithoutVideoAndAudio",void 0),v(this,"calls",new Map),v(this,"callHandlers",new Map),v(this,"activeSpeakerLoopInterval",void 0),v(this,"retryCallLoopInterval",void 0),v(this,"retryCallCounts",new Map),v(this,"reEmitter",void 0),v(this,"transmitTimer",null),v(this,"participantsExpirationTimer",null),v(this,"resendMemberStateTimer",null),v(this,"initWithAudioMuted",!1),v(this,"initWithVideoMuted",!1),v(this,"initCallFeedPromise",void 0),v(this,"_livekitServiceURL",void 0),v(this,"stats",void 0),v(this,"statsCollectIntervalTime",0),v(this,"onConnectionStats",h=>{this.emit(Au.ConnectionStats,{report:h})}),v(this,"onByteSentStats",h=>{this.emit(Au.ByteSentStats,{report:h})}),v(this,"onSummaryStats",h=>{JD.extendSummaryReport(h,this.participants),this.emit(Au.SummaryStats,{report:h})}),v(this,"onCallFeedReport",h=>{this.localCallFeed&&(h=gs.expandCallFeedReport(h,[this.localCallFeed],"from-local-feed"));var m=[];this.forEachCall(w=>{w.callId===h.callId&&w.getFeeds().forEach(g=>m.push(g))}),h=gs.expandCallFeedReport(h,m,"from-call-feed"),this.emit(Au.CallFeedStats,{report:h})}),v(this,"_state",Mt.LocalCallFeedUninitialized),v(this,"_participants",new Map),v(this,"_creationTs",null),v(this,"_enteredViaAnotherSession",!1),v(this,"onIncomingCall",h=>{var m,w;if(h.roomId===this.room.roomId){if(h.state!==Fe.Ringing){S.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call no longer in ringing state - ignoring"));return}if(!h.groupCallId||h.groupCallId!==this.groupCallId){S.log("GroupCall ".concat(this.groupCallId," onIncomingCall() ignored because it doesn't match the current group call")),h.reject();return}var g=(m=h.getOpponentMember())===null||m===void 0?void 0:m.userId;if(g===void 0){S.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call with no member - ignoring"));return}if(this.useLivekit){S.info("Received incoming call whilst in signaling-only mode! Ignoring.");return}var b=(w=this.calls.get(g))!==null&&w!==void 0?w:new Map,R=b.get(h.getOpponentDeviceId());if((R==null?void 0:R.callId)!==h.callId){S.log("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call (userId=").concat(g,", callId=").concat(h.callId,")")),R&&R.hangup(qe.Replaced,!1),b.set(h.getOpponentDeviceId(),h),this.calls.set(g,b),this.initCall(h);var k=this.getLocalFeeds().map(T=>T.clone());if(!this.callExpected(h))for(var O of k)tr(O.stream.getAudioTracks(),!1),tr(O.stream.getVideoTracks(),!1);h.answerWithCallFeeds(k),this.emit(yt.CallsChanged,this.calls)}}}),v(this,"onRetryCallLoop",()=>{var h=!1;for(var[{userId:m},w]of this.participants){var g=this.calls.get(m),b=this.retryCallCounts.get(m);for(var[R,k]of w){var O,T,x=g==null?void 0:g.get(R),C=(O=(T=b)===null||T===void 0?void 0:T.get(R))!==null&&O!==void 0?O:0;(x==null?void 0:x.getOpponentSessionId())!==k.sessionId&&this.wantsOutgoingCall(m,R)&&C<3&&(b===void 0&&(b=new Map,this.retryCallCounts.set(m,b)),b.set(R,C+1),h=!0)}}h&&this.placeOutgoingCalls()}),v(this,"onCallFeedsChanged",h=>{var m=ch(h),w=h.getOpponentDeviceId();if(!m)throw new Error("Cannot change call feeds without user id");var g=this.getUserMediaFeed(m,w),b=h.remoteUsermediaFeed,R=b!==g,k=this.calls.get(m),O=k==null?void 0:k.get(w);if((O==null?void 0:O.callId)===h.callId){R&&(!g&&b?this.addUserMediaFeed(b):g&&b?this.replaceUserMediaFeed(g,b):g&&!b&&this.removeUserMediaFeed(g));var T=this.getScreenshareFeed(m,w),x=h.remoteScreensharingFeed,C=x!==T;C&&(!T&&x?this.addScreenshareFeed(x):T&&x?this.replaceScreenshareFeed(T,x):T&&!x&&this.removeScreenshareFeed(T))}}),v(this,"onCallStateChanged",(h,m,w)=>{var g;if(m!==Fe.Ended){var b=this.localCallFeed.isAudioMuted();h.localUsermediaStream&&h.isMicrophoneMuted()!==b&&h.setMicrophoneMuted(b);var R=this.localCallFeed.isVideoMuted();h.localUsermediaStream&&h.isLocalVideoMuted()!==R&&h.setLocalVideoMuted(R);var k=(g=h.getOpponentMember())===null||g===void 0?void 0:g.userId;if(m===Fe.Connected&&k){var O=this.retryCallCounts.get(k);O==null||O.delete(h.getOpponentDeviceId()),(O==null?void 0:O.size)===0&&this.retryCallCounts.delete(k)}}}),v(this,"onCallHangup",h=>{var m,w;if(h.hangupReason!==qe.Replaced){var g=(m=(w=h.getOpponentMember())===null||w===void 0?void 0:w.userId)!==null&&m!==void 0?m:this.room.getMember(h.invitee).userId,b=this.calls.get(g);(b==null?void 0:b.get(h.getOpponentDeviceId()))===h&&(this.disposeCall(h,h.hangupReason),b.delete(h.getOpponentDeviceId()),b.size===0&&this.calls.delete(g),this.emit(yt.CallsChanged,this.calls))}}),v(this,"onCallReplaced",(h,m)=>{var w=h.getOpponentMember().userId,g=this.calls.get(w);g===void 0&&(g=new Map,this.calls.set(w,g)),h.hangup(qe.Replaced,!1),this.initCall(m),g.set(h.getOpponentDeviceId(),m),this.emit(yt.CallsChanged,this.calls)}),v(this,"onActiveSpeakerLoop",()=>{var h=void 0,m=void 0;for(var w of this.userMediaFeeds)if(!(w.isLocal()&&this.userMediaFeeds.length>1)){var g=w.speakingVolumeSamples.reduce((R,k)=>R+Math.max(k,Ib)),b=g/w.speakingVolumeSamples.length;(!h||b>h)&&(h=b,m=w)}m&&this.activeSpeaker!==m&&h&&h>Ib&&(this.activeSpeaker=m,this.emit(yt.ActiveSpeakerChanged,this.activeSpeaker))}),v(this,"onRoomState",()=>this.updateParticipants()),v(this,"onParticipantsChanged",()=>{this.forEachCall(h=>{var m=this.callExpected(h);for(var w of h.getLocalFeeds())tr(w.stream.getAudioTracks(),!w.isAudioMuted()&&m),tr(w.stream.getVideoTracks(),!w.isVideoMuted()&&m)}),this.state===Mt.Entered&&!this.useLivekit&&this.placeOutgoingCalls()}),v(this,"onStateChanged",(h,m)=>{(h===Mt.Entered||m===Mt.Entered||h===Mt.Ended)&&(this.updateParticipants(),this.updateMemberState().catch(w=>S.error("GroupCall ".concat(this.groupCallId,' onStateChanged() failed to update member state devices"'),w)))}),v(this,"onLocalFeedsChanged",()=>{this.state===Mt.Entered&&this.updateMemberState().catch(h=>S.error("GroupCall ".concat(this.groupCallId," onLocalFeedsChanged() failed to update member state feeds"),h))}),this.reEmitter=new mD(this),this.groupCallId=s??da(),this._livekitServiceURL=p,this.creationTs=(u=(d=t.currentState.getStateEvents(V.GroupCallPrefix,this.groupCallId))===null||d===void 0?void 0:d.getTs())!==null&&u!==void 0?u:null,this.updateParticipants(),t.on(Ne.Update,this.onRoomState),this.on(yt.ParticipantsChanged,this.onParticipantsChanged),this.on(yt.GroupCallStateChanged,this.onStateChanged),this.on(yt.LocalScreenshareStateChanged,this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!c}create(){var e=this;return _(function*(){return e.creationTs=Date.now(),e.client.groupCallEventHandler.groupCalls.set(e.room.roomId,e),e.client.emit(Ob.Outgoing,e),yield e.sendCallStateEvent(),e})()}sendCallStateEvent(){var e=this;return _(function*(){var t={"m.intent":e.intent,"m.type":e.type,"io.element.ptt":e.isPtt,dataChannelsEnabled:e.dataChannelsEnabled,dataChannelOptions:e.dataChannelsEnabled?e.dataChannelOptions:void 0};e.livekitServiceURL&&(t["io.element.livekit_service_url"]=e.livekitServiceURL),yield e.client.sendStateEvent(e.room.roomId,V.GroupCallPrefix,t,e.groupCallId)})()}get livekitServiceURL(){return this._livekitServiceURL}updateLivekitServiceURL(e){return this._livekitServiceURL=e,this.sendCallStateEvent()}get state(){return this._state}set state(e){var t=this._state;e!==t&&(this._state=e,this.emit(yt.GroupCallStateChanged,e,t))}get participants(){return this._participants}set participants(e){var t=this._participants,n=(o,s)=>o.sessionId===s.sessionId&&o.screensharing===s.screensharing,i=(o,s)=>oC(o,s,n);oC(e,t,i)||(this._participants=e,this.emit(yt.ParticipantsChanged,e))}get creationTs(){return this._creationTs}set creationTs(e){this._creationTs=e}get enteredViaAnotherSession(){return this._enteredViaAnotherSession}set enteredViaAnotherSession(e){this._enteredViaAnotherSession=e,this.updateParticipants()}forEachCall(e){for(var t of this.calls.values())for(var n of t.values())e(n)}getLocalFeeds(){var e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e,t;return(e=(t=this.participants.get(this.room.getMember(this.client.getUserId())))===null||t===void 0?void 0:t.has(this.client.getDeviceId()))!==null&&e!==void 0?e:!1}callExpected(e){var t,n=ch(e),i=n===null?null:this.room.getMember(n),o=e.getOpponentDeviceId();return i!==null&&o!==void 0&&((t=this.participants.get(i))===null||t===void 0?void 0:t.get(o))!==void 0}initLocalCallFeed(){var e=this;return _(function*(){if(e.useLivekit){S.info("Livekit group call: not starting local call feed.");return}if(e.state!==Mt.LocalCallFeedUninitialized)throw new Error('Cannot initialize local call feed in the "'.concat(e.state,'" state.'));if(e.state=Mt.InitializingLocalCallFeed,e.initCallFeedPromise)return e.initCallFeedPromise;try{e.initCallFeedPromise=e.initLocalCallFeedInternal(),yield e.initCallFeedPromise}finally{e.initCallFeedPromise=void 0}})()}initLocalCallFeedInternal(){var e=this;return _(function*(){S.log("GroupCall ".concat(e.groupCallId," initLocalCallFeedInternal() running"));var t;try{t=yield e.client.getMediaHandler().getUserMediaStream(!0,e.type===gm.Video)}catch(i){if(e.allowCallWithoutVideoAndAudio)t=new MediaStream;else throw e.state=Mt.LocalCallFeedUninitialized,i}if(e._state!==Mt.InitializingLocalCallFeed)throw e.client.getMediaHandler().stopUserMediaStream(t),new Error("Group call disposed while gathering media stream");var n=new So({client:e.client,roomId:e.room.roomId,userId:e.client.getUserId(),deviceId:e.client.getDeviceId(),stream:t,purpose:St.Usermedia,audioMuted:e.initWithAudioMuted||t.getAudioTracks().length===0||e.isPtt,videoMuted:e.initWithVideoMuted||t.getVideoTracks().length===0});tr(t.getAudioTracks(),!n.isAudioMuted()),tr(t.getVideoTracks(),!n.isVideoMuted()),e.localCallFeed=n,e.addUserMediaFeed(n),e.state=Mt.LocalCallFeedInitialized})()}updateLocalUsermediaStream(e){var t=this;return _(function*(){if(t.localCallFeed){var n=t.localCallFeed.stream;t.localCallFeed.setNewStream(e);var i=t.localCallFeed.isAudioMuted(),o=t.localCallFeed.isVideoMuted();S.log("GroupCall ".concat(t.groupCallId," updateLocalUsermediaStream() (oldStreamId=").concat(n.id,", newStreamId=").concat(e.id,", micShouldBeMuted=").concat(i,", vidShouldBeMuted=").concat(o,")")),tr(e.getAudioTracks(),!i),tr(e.getVideoTracks(),!o),t.client.getMediaHandler().stopUserMediaStream(n)}})()}enter(){var e=this;return _(function*(){if(e.state===Mt.LocalCallFeedUninitialized)yield e.initLocalCallFeed();else if(e.state!==Mt.LocalCallFeedInitialized)throw new Error('Cannot enter call in the "'.concat(e.state,'" state'));S.log("GroupCall ".concat(e.groupCallId," enter() running")),e.state=Mt.Entered,e.client.on(xb.Incoming,e.onIncomingCall);for(var t of e.client.callEventHandler.calls.values())e.onIncomingCall(t);e.useLivekit||(e.retryCallLoopInterval=setInterval(e.onRetryCallLoop,e.retryCallInterval),e.activeSpeaker=void 0,e.onActiveSpeakerLoop(),e.activeSpeakerLoopInterval=setInterval(e.onActiveSpeakerLoop,e.activeSpeakerInterval))})()}dispose(){var e;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.participantsExpirationTimer!==null&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===Mt.Entered&&(this.forEachCall(t=>t.hangup(qe.UserHangup,!1)),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(xb.Incoming,this.onIncomingCall),(e=this.stats)===null||e===void 0||e.stop())}leave(){this.dispose(),this.state=Mt.LocalCallFeedUninitialized}terminate(){var e=arguments,t=this;return _(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:!0;if(t.dispose(),t.room.off(Ne.Update,t.onRoomState),t.client.groupCallEventHandler.groupCalls.delete(t.room.roomId),t.client.emit(Ob.Ended,t),t.state=Mt.Ended,n){var i=t.room.currentState.getStateEvents(V.GroupCallPrefix,t.groupCallId);yield t.client.sendStateEvent(t.room.roomId,V.GroupCallPrefix,lh(lh({},i.getContent()),{},{"m.terminated":Oz.CallEnded}),t.groupCallId)}})()}isLocalVideoMuted(){return this.localCallFeed?this.localCallFeed.isVideoMuted():!0}isMicrophoneMuted(){return this.localCallFeed?this.localCallFeed.isAudioMuted():!0}setMicrophoneMuted(e){var t=this;return _(function*(){if(!e&&!(yield t.client.getMediaHandler().hasAudioDevice()))return!1;var n=!e&&t.isPtt;t.isPtt&&(!e&&t.isMicrophoneMuted()?t.transmitTimer=setTimeout(()=>{t.setMicrophoneMuted(!0)},t.pttMaxTransmitTime):e&&!t.isMicrophoneMuted()&&(t.transmitTimer!==null&&clearTimeout(t.transmitTimer),t.transmitTimer=null)),t.forEachCall(s=>{var a;return(a=s.localUsermediaFeed)===null||a===void 0?void 0:a.setAudioVideoMuted(e,null)});var i=function(){var s=_(function*(){var a=[];t.forEachCall(l=>a.push(l.sendMetadataUpdate())),yield Promise.all(a).catch(l=>S.info("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() failed to send some metadata updates"),l))});return function(){return s.apply(this,arguments)}}();if(n&&(yield i()),t.localCallFeed){S.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() (streamId=").concat(t.localCallFeed.stream.id,", muted=").concat(e,")"));var o=yield t.checkAudioPermissionIfNecessary(e);if(!o)return!1;t.localCallFeed.setAudioVideoMuted(e,null),tr(t.localCallFeed.stream.getAudioTracks(),!e)}else S.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no stream muted (muted=").concat(e,")")),t.initWithAudioMuted=e;return t.forEachCall(s=>tr(s.localUsermediaFeed.stream.getAudioTracks(),!e&&t.callExpected(s))),t.emit(yt.LocalMuteStateChanged,e,t.isLocalVideoMuted()),n||(yield i()),!0})()}checkAudioPermissionIfNecessary(e){var t=this;return _(function*(){try{if(!e&&t.localCallFeed&&!t.localCallFeed.hasAudioTrack){var n=yield t.client.getMediaHandler().getUserMediaStream(!0,!t.localCallFeed.isVideoMuted());if((n==null?void 0:n.getTracks().length)===0)return S.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no device to receive local stream, muted=").concat(e)),!1}}catch{return S.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no device or permission to receive local stream, muted=").concat(e)),!1}return!0})()}setLocalVideoMuted(e){var t=this;return _(function*(){if(!e&&!(yield t.client.getMediaHandler().hasVideoDevice()))return!1;if(t.localCallFeed){S.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() (stream=").concat(t.localCallFeed.stream.id,", muted=").concat(e,")"));try{var n=yield t.client.getMediaHandler().getUserMediaStream(!0,!e);yield t.updateLocalUsermediaStream(n),t.localCallFeed.setAudioVideoMuted(null,e),tr(t.localCallFeed.stream.getVideoTracks(),!e)}catch{return S.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() no device or permission to receive local stream, muted=").concat(e)),!1}}else S.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() no stream muted (muted=").concat(e,")")),t.initWithVideoMuted=e;var i=[];return t.forEachCall(o=>i.push(o.setLocalVideoMuted(e))),yield Promise.all(i),t.forEachCall(o=>tr(o.localUsermediaFeed.stream.getVideoTracks(),!e&&t.callExpected(o))),t.emit(yt.LocalMuteStateChanged,t.isMicrophoneMuted(),e),!0})()}setScreensharingEnabled(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};if(e===n.isScreensharing())return e;if(e)try{S.log("GroupCall ".concat(n.groupCallId," setScreensharingEnabled() is asking for screensharing permissions"));var o=yield n.client.getMediaHandler().getScreensharingStream(i),s=function*(c){var u=()=>{n.setScreensharingEnabled(!1),c.removeEventListener("ended",u)};c.addEventListener("ended",u)};for(var a of o.getTracks())yield*s(a);return S.log("GroupCall ".concat(n.groupCallId," setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls")),n.localDesktopCapturerSourceId=i.desktopCapturerSourceId,n.localScreenshareFeed=new So({client:n.client,roomId:n.room.roomId,userId:n.client.getUserId(),deviceId:n.client.getDeviceId(),stream:o,purpose:St.Screenshare,audioMuted:!1,videoMuted:!1}),n.addScreenshareFeed(n.localScreenshareFeed),n.emit(yt.LocalScreenshareStateChanged,!0,n.localScreenshareFeed,n.localDesktopCapturerSourceId),n.forEachCall(l=>l.pushLocalFeed(n.localScreenshareFeed.clone())),!0}catch(l){if(i.throwOnFail)throw l;return S.error("GroupCall ".concat(n.groupCallId," setScreensharingEnabled() enabling screensharing error"),l),n.emit(yt.Error,new Pb(nd.NoUserMedia,"Failed to get screen-sharing stream: ",l)),!1}else return n.forEachCall(l=>{l.localScreensharingFeed&&l.removeLocalFeed(l.localScreensharingFeed)}),n.client.getMediaHandler().stopScreensharingStream(n.localScreenshareFeed.stream),n.removeScreenshareFeed(n.localScreenshareFeed),n.localScreenshareFeed=void 0,n.localDesktopCapturerSourceId=void 0,n.emit(yt.LocalScreenshareStateChanged,!1,void 0,void 0),!1})()}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,t){var n=this.client.getUserId(),i=this.client.getDeviceId();return e>=n&&(e!==n||t>i)}placeOutgoingCalls(){var e=this,t=!1,n=function(a){var l,c=(l=e.calls.get(a))!==null&&l!==void 0?l:new Map,u=function(h){var m=c.get(h);if((m==null?void 0:m.getOpponentSessionId())!==f.sessionId&&e.wantsOutgoingCall(a,h)){t=!0,m!==void 0&&(S.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() replacing call (userId=").concat(a,", deviceId=").concat(h,", callId=").concat(m.callId,")")),m.hangup(qe.NewSession,!1));var w=Bd(e.client,e.room.roomId,{invitee:a,opponentDeviceId:h,opponentSessionId:f.sessionId,groupCallId:e.groupCallId});w===null?(S.error("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to create call (userId=").concat(a,", device=").concat(h,")")),c.delete(h)):(e.initCall(w),c.set(h,w),S.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() placing call (userId=").concat(a,", deviceId=").concat(h,", sessionId=").concat(f.sessionId,")")),w.placeCallWithCallFeeds(e.getLocalFeeds().map(g=>g.clone()),f.screensharing).then(()=>{e.dataChannelsEnabled&&w.createDataChannel("datachannel",e.dataChannelOptions)}).catch(g=>{S.warn("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to place call (userId=").concat(a,")"),g),g instanceof vo&&g.code===nd.UnknownDevice?e.emit(yt.Error,g):e.emit(yt.Error,new Pb(nd.PlaceCallFailed,"Failed to place call to ".concat(a))),w.hangup(qe.SignallingFailed,!1),c.get(h)===w&&c.delete(h)}))}};for(var[d,f]of o)u(d);c.size>0?e.calls.set(a,c):e.calls.delete(a)};for(var[{userId:i},o]of this.participants)n(i);t&&this.emit(yt.CallsChanged,this.calls)}getMemberStateEvents(e){return e===void 0?this.room.currentState.getStateEvents(V.GroupCallMemberPrefix):this.room.currentState.getStateEvents(V.GroupCallMemberPrefix,e)}initCall(e){var t=ch(e);if(!t)throw new Error("Cannot init call without user id");var n=()=>this.onCallFeedsChanged(e),i=(l,c)=>this.onCallStateChanged(e,l,c),o=this.onCallHangup,s=l=>this.onCallReplaced(e,l),a=this.callHandlers.get(t);a===void 0&&(a=new Map,this.callHandlers.set(t,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:n,onCallStateChanged:i,onCallHangup:o,onCallReplaced:s}),e.on(Ye.FeedsChanged,n),e.on(Ye.State,i),e.on(Ye.Hangup,o),e.on(Ye.Replaced,s),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(Ye)),e.initStats(this.getGroupCallStats()),n()}disposeCall(e,t){var n=ch(e),i=e.getOpponentDeviceId();if(!n)throw new Error("Cannot dispose call without user id");var o=this.callHandlers.get(n),{onCallFeedsChanged:s,onCallStateChanged:a,onCallHangup:l,onCallReplaced:c}=o.get(i);if(e.removeListener(Ye.FeedsChanged,s),e.removeListener(Ye.State,a),e.removeListener(Ye.Hangup,l),e.removeListener(Ye.Replaced,c),o.delete(n),o.size===0&&this.callHandlers.delete(n),e.hangupReason!==qe.Replaced){var u=this.getUserMediaFeed(n,i);u&&this.removeUserMediaFeed(u);var d=this.getScreenshareFeed(n,i);d&&this.removeScreenshareFeed(d)}}getUserMediaFeed(e,t){return this.userMediaFeeds.find(n=>n.userId===e&&n.deviceId===t)}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit(yt.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(e,t){var n=this.userMediaFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(n===-1)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(n,1,t),e.dispose(),t.measureVolumeActivity(!0),this.emit(yt.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(e){var t=this.userMediaFeeds.findIndex(n=>n.userId===e.userId&&n.deviceId===e.deviceId);if(t===-1)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(t,1),e.dispose(),this.emit(yt.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(yt.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(e,t){return this.screenshareFeeds.find(n=>n.userId===e&&n.deviceId===t)}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit(yt.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(e,t){var n=this.screenshareFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(n===-1)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(n,1,t),e.dispose(),this.emit(yt.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(e){var t=this.screenshareFeeds.findIndex(n=>n.userId===e.userId&&n.deviceId===e.deviceId);if(t===-1)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(t,1),e.dispose(),this.emit(yt.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){var e=this.room.getMember(this.client.getUserId());if(!e){S.warn("GroupCall ".concat(this.groupCallId," updateParticipants() tried to update participants before local room member is available"));return}if(this.participantsExpirationTimer!==null&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===Mt.Ended){this.participants=new Map;return}var t=new Map,n=Date.now(),i=this.state===Mt.Entered||this.enteredViaAnotherSession,o=1/0;for(var s of this.getMemberStateEvents()){var a=this.room.getMember(s.getStateKey()),l=s.getContent(),c=Array.isArray(l["m.calls"])?l["m.calls"]:[],u=c.find(w=>w["m.call_id"]===this.groupCallId),d=Array.isArray(u==null?void 0:u["m.devices"])?u["m.devices"]:[],f=d.filter(w=>typeof w.device_id=="string"&&typeof w.session_id=="string"&&typeof w.expires_ts=="number"&&w.expires_ts>n&&Array.isArray(w.feeds));if(!i&&(a==null?void 0:a.userId)===this.client.getUserId()&&(f=f.filter(w=>w.device_id!==this.client.getDeviceId())),f.length>0&&(a==null?void 0:a.membership)===Be.Join){var p=new Map;t.set(a,p);for(var h of f)p.set(h.device_id,{sessionId:h.session_id,screensharing:h.feeds.some(w=>w.purpose===St.Screenshare)}),h.expires_ts<o&&(o=h.expires_ts)}}if(i){var m=t.get(e);m===void 0&&(m=new Map,t.set(e,m)),m.has(this.client.getDeviceId())||m.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some(w=>w.purpose===St.Screenshare)})}this.participants=t,o<1/0&&(this.participantsExpirationTimer=setTimeout(()=>this.updateParticipants(),o-n))}updateDevices(e){var t=arguments,n=this;return _(function*(){var i,o=t.length>1&&t[1]!==void 0?t[1]:!1,s=Date.now(),a=n.client.getUserId(),l=n.getMemberStateEvents(a),c=(i=l==null?void 0:l.getContent())!==null&&i!==void 0?i:{},u=Array.isArray(c["m.calls"])?c["m.calls"]:[],d=null,f=[];for(var p of u)p["m.call_id"]===n.groupCallId?d=p:f.push(p);d===null&&(d={});var h=Array.isArray(d["m.devices"])?d["m.devices"]:[],m=h.filter(R=>typeof R.device_id=="string"&&typeof R.session_id=="string"&&typeof R.expires_ts=="number"&&R.expires_ts>s&&Array.isArray(R.feeds)),w=e(m);if(w!==null){var g=[...f];w.length>0&&g.push(lh(lh({},d),{},{"m.call_id":n.groupCallId,"m.devices":w}));var b={"m.calls":g};yield n.client.sendStateEvent(n.room.roomId,V.GroupCallMemberPrefix,b,a,{keepAlive:o})}})()}addDeviceToMemberState(){var e=this;return _(function*(){yield e.updateDevices(t=>[...t.filter(n=>n.device_id!==e.client.getDeviceId()),{device_id:e.client.getDeviceId(),session_id:e.client.getSessionId(),expires_ts:Date.now()+OC,feeds:e.getLocalFeeds().map(n=>({purpose:n.purpose}))}])})()}updateMemberState(){var e=this;return _(function*(){e.resendMemberStateTimer!==null&&(clearInterval(e.resendMemberStateTimer),e.resendMemberStateTimer=null),e.state===Mt.Entered?(yield e.addDeviceToMemberState(),e.resendMemberStateTimer=setInterval(_(function*(){S.log("GroupCall ".concat(e.groupCallId,' updateMemberState() resending call member state"'));try{yield e.addDeviceToMemberState()}catch(t){S.error("GroupCall ".concat(e.groupCallId," updateMemberState() failed to resend call member state"),t)}}),OC*3/4)):yield e.updateDevices(t=>t.filter(n=>n.device_id!==e.client.getDeviceId()),!0)})()}cleanMemberState(){var e=this;return _(function*(){var{devices:t}=yield e.client.getDevices(),n=new Map(t.map(i=>[i.device_id,i]));yield e.updateDevices(i=>{var o=i.filter(s=>{var a=n.get(s.device_id);return(a==null?void 0:a.last_seen_ts)!==void 0&&!(s.device_id===e.client.getDeviceId()&&e.state!==Mt.Entered&&!e.enteredViaAnotherSession)});return o.length===i.length?null:o})})()}getGroupCallStats(){if(this.stats===void 0){var e=this.client.getUserId()||"unknown";this.stats=new xz(this.groupCallId,e,this.statsCollectIntervalTime),this.stats.reports.on(To.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(To.BYTE_SENT_STATS,this.onByteSentStats),this.stats.reports.on(To.SUMMARY_STATS,this.onSummaryStats),this.stats.reports.on(To.CALL_FEED_REPORT,this.onCallFeedReport)}return this.stats}setGroupCallStatsInterval(e){this.statsCollectIntervalTime=e,this.stats!==void 0&&(this.stats.stop(),this.stats.setInterval(e),e>0&&this.stats.start())}}function PC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function uh(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?PC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):PC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Fe=function(r){return r.Fledgling="fledgling",r.InviteSent="invite_sent",r.WaitLocalMedia="wait_local_media",r.CreateOffer="create_offer",r.CreateAnswer="create_answer",r.Connecting="connecting",r.Connected="connected",r.Ringing="ringing",r.Ended="ended",r}({}),MC=function(r){return r.Voice="voice",r.Video="video",r}({}),es=function(r){return r.Inbound="inbound",r.Outbound="outbound",r}({}),Vt=function(r){return r.Local="local",r.Remote="remote",r}({}),Ye=function(r){return r.Hangup="hangup",r.State="state",r.Error="error",r.Replaced="replaced",r.LocalHoldUnhold="local_hold_unhold",r.RemoteHoldUnhold="remote_hold_unhold",r.HoldUnhold="hold_unhold",r.FeedsChanged="feeds_changed",r.AssertedIdentityChanged="asserted_identity_changed",r.LengthChanged="length_changed",r.DataChannel="datachannel",r.SendVoipEvent="send_voip_event",r.PeerConnectionCreated="peer_connection_created",r}({}),qe=function(r){return r.UserHangup="user_hangup",r.LocalOfferFailed="local_offer_failed",r.NoUserMedia="no_user_media",r.UnknownDevices="unknown_devices",r.SendInvite="send_invite",r.CreateAnswer="create_answer",r.CreateOffer="create_offer",r.SendAnswer="send_answer",r.SetRemoteDescription="set_remote_description",r.SetLocalDescription="set_local_description",r.AnsweredElsewhere="answered_elsewhere",r.IceFailed="ice_failed",r.InviteTimeout="invite_timeout",r.Replaced="replaced",r.SignallingFailed="signalling_timeout",r.UserBusy="user_busy",r.Transferred="transferred",r.NewSession="new_session",r}({}),Pz="1",Mz="stun:turn.matrix.org",Xg=60*1e3,Az=1e3,Dz=30*1e3,Nz=2*1e3;class vo extends Error{constructor(e,t,n){super(t+": "+n),v(this,"code",void 0),this.code=e}}function da(){return Date.now().toString()+Ei(16)}function AC(r){var e=[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:r?12e3:void 0}];return e}function si(r,e){return r+":"+e}class Lz extends Tt{constructor(e){var t,n;if(super(),t=this,v(this,"roomId",void 0),v(this,"callId",void 0),v(this,"invitee",void 0),v(this,"hangupParty",void 0),v(this,"hangupReason",void 0),v(this,"direction",void 0),v(this,"ourPartyId",void 0),v(this,"peerConn",void 0),v(this,"toDeviceSeq",0),v(this,"isPtt",!1),v(this,"_state",Fe.Fledgling),v(this,"client",void 0),v(this,"forceTURN",void 0),v(this,"turnServers",void 0),v(this,"candidateSendQueue",[]),v(this,"candidateSendTries",0),v(this,"candidatesEnded",!1),v(this,"feeds",[]),v(this,"transceivers",new Map),v(this,"inviteOrAnswerSent",!1),v(this,"waitForLocalAVStream",!1),v(this,"successor",void 0),v(this,"opponentMember",void 0),v(this,"opponentVersion",void 0),v(this,"opponentPartyId",void 0),v(this,"opponentCaps",void 0),v(this,"iceDisconnectedTimeout",void 0),v(this,"iceReconnectionTimeOut",void 0),v(this,"inviteTimeout",void 0),v(this,"removeTrackListeners",new Map),v(this,"remoteOnHold",!1),v(this,"callStatsAtEnd",void 0),v(this,"makingOffer",!1),v(this,"ignoreOffer",!1),v(this,"isSettingRemoteAnswerPending",!1),v(this,"responsePromiseChain",void 0),v(this,"remoteCandidateBuffer",new Map),v(this,"remoteAssertedIdentity",void 0),v(this,"remoteSDPStreamMetadata",void 0),v(this,"callLengthInterval",void 0),v(this,"callStartTime",void 0),v(this,"opponentDeviceId",void 0),v(this,"opponentDeviceInfo",void 0),v(this,"opponentSessionId",void 0),v(this,"groupCallId",void 0),v(this,"stopVideoTrackTimer",void 0),v(this,"isOnlyDataChannelAllowed",void 0),v(this,"stats",void 0),v(this,"gotLocalIceCandidate",o=>{if(o.candidate){if(this.candidatesEnded&&S.warn("Call ".concat(this.callId," gotLocalIceCandidate() got candidate after candidates have ended!")),S.debug("Call ".concat(this.callId," got local ICE ").concat(o.candidate.sdpMid," ").concat(o.candidate.candidate)),this.callHasEnded())return;o.candidate.candidate===""?this.queueCandidate(null):this.queueCandidate(o.candidate)}}),v(this,"onIceGatheringStateChange",o=>{var s;S.debug("Call ".concat(this.callId," onIceGatheringStateChange() ice gathering state changed to ").concat(this.peerConn.iceGatheringState)),((s=this.peerConn)===null||s===void 0?void 0:s.iceGatheringState)==="complete"&&(this.queueCandidate(null),S.debug("Call ".concat(this.callId," onIceGatheringStateChange() ice gathering state complete, set candidates have ended")))}),v(this,"getLocalOfferFailed",o=>{S.error("Call ".concat(this.callId," getLocalOfferFailed() running"),o),this.emit(Ye.Error,new vo(qe.LocalOfferFailed,"Failed to get local offer!",o),this),this.terminate(Vt.Local,qe.LocalOfferFailed,!1)}),v(this,"getUserMediaFailed",o=>{if(this.successor){this.successor.getUserMediaFailed(o);return}S.warn("Call ".concat(this.callId," getUserMediaFailed() failed to get user media - ending call"),o),this.emit(Ye.Error,new vo(qe.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",o),this),this.terminate(Vt.Local,qe.NoUserMedia,!1)}),v(this,"placeCallFailed",o=>{if(this.successor){this.successor.placeCallFailed(o);return}S.warn("Call ".concat(this.callId," placeCallWithCallFeeds() failed - ending call"),o),this.emit(Ye.Error,new vo(qe.IceFailed,"Couldn't start call! Invalid ICE server configuration.",o),this),this.terminate(Vt.Local,qe.IceFailed,!1)}),v(this,"onIceConnectionStateChanged",()=>{var o,s,a,l,c,u;if(!this.callHasEnded()){if(S.debug("Call ".concat(this.callId," onIceConnectionStateChanged() running (state=").concat((o=this.peerConn)===null||o===void 0?void 0:o.iceConnectionState,", conn=").concat((s=this.peerConn)===null||s===void 0?void 0:s.connectionState,")")),["connected","completed"].includes((a=(l=this.peerConn)===null||l===void 0?void 0:l.iceConnectionState)!==null&&a!==void 0?a:""))clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.iceReconnectionTimeOut&&clearTimeout(this.iceReconnectionTimeOut),this.state=Fe.Connected,!this.callLengthInterval&&!this.callStartTime&&(this.callStartTime=Date.now(),this.callLengthInterval=setInterval(()=>{this.emit(Ye.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3),this)},Az));else if(((c=this.peerConn)===null||c===void 0?void 0:c.iceConnectionState)=="failed"){var d;if(this.candidatesEnded=!1,(d=this.peerConn)!==null&&d!==void 0&&d.restartIce){var f;this.candidatesEnded=!1,S.debug("Call ".concat(this.callId," onIceConnectionStateChanged() ice restart (state=").concat((f=this.peerConn)===null||f===void 0?void 0:f.iceConnectionState,")")),this.peerConn.restartIce()}else S.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)")),this.hangup(qe.IceFailed,!1)}else((u=this.peerConn)===null||u===void 0?void 0:u.iceConnectionState)=="disconnected"&&(this.candidatesEnded=!1,this.iceReconnectionTimeOut=setTimeout(()=>{var h,m,w;S.info("Call ".concat(this.callId," onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=").concat((h=this.peerConn)===null||h===void 0?void 0:h.iceConnectionState,", conn=").concat((m=this.peerConn)===null||m===void 0?void 0:m.connectionState,")")),(w=this.peerConn)!==null&&w!==void 0&&w.restartIce&&(this.candidatesEnded=!1,this.peerConn.restartIce()),this.iceReconnectionTimeOut=void 0},Nz),this.iceDisconnectedTimeout=setTimeout(()=>{S.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)")),this.hangup(qe.IceFailed,!1)},Dz),this.state=Fe.Connecting);if(this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState))for(var p of this.getRemoteFeeds())p.setAudioVideoMuted(!0,!0)}}),v(this,"onSignallingStateChanged",()=>{var o;S.debug("Call ".concat(this.callId," onSignallingStateChanged() running (state=").concat((o=this.peerConn)===null||o===void 0?void 0:o.signalingState,")"))}),v(this,"onTrack",o=>{if(o.streams.length===0){S.warn("Call ".concat(this.callId," onTrack() called with streamless track streamless (kind=").concat(o.track.kind,")"));return}var s=o.streams[0];if(this.pushRemoteFeed(s),!this.removeTrackListeners.has(s)){var a=()=>{s.getTracks().length===0&&(S.info("Call ".concat(this.callId," onTrack() removing track (streamId=").concat(s.id,")")),this.deleteFeedByStream(s),s.removeEventListener("removetrack",a),this.removeTrackListeners.delete(s))};s.addEventListener("removetrack",a),this.removeTrackListeners.set(s,a)}}),v(this,"onDataChannel",o=>{this.emit(Ye.DataChannel,o.channel,this)}),v(this,"onNegotiationNeeded",_(function*(){if(S.info("Call ".concat(t.callId," onNegotiationNeeded() negotiation is needed!")),t.state!==Fe.CreateOffer&&t.opponentVersion===0){S.info("Call ".concat(t.callId," onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event"));return}t.queueGotLocalOffer()})),v(this,"onHangupReceived",o=>{S.debug("Call ".concat(this.callId," onHangupReceived() running")),this.partyIdMatches(o)||this.state===Fe.Ringing?this.terminate(Vt.Remote,o.reason||qe.UserHangup,!0):S.info("Call ".concat(this.callId," onHangupReceived() ignoring message from party ID ").concat(o.party_id,": our partner is ").concat(this.opponentPartyId))}),v(this,"onRejectReceived",o=>{S.debug("Call ".concat(this.callId," onRejectReceived() running"));var s=[Fe.InviteSent,Fe.Ringing].includes(this.state)||this.state===Fe.Fledgling&&this.direction===es.Inbound;s?this.terminate(Vt.Remote,o.reason||qe.UserHangup,!0):S.debug("Call ".concat(this.callId," onRejectReceived() called in wrong state (state=").concat(this.state,")"))}),v(this,"onAnsweredElsewhere",o=>{S.debug("Call ".concat(this.callId," onAnsweredElsewhere() running")),this.terminate(Vt.Remote,qe.AnsweredElsewhere,!0)}),this.roomId=e.roomId,this.invitee=e.invitee,this.client=e.client,!this.client.deviceId)throw new Error("Client must have a device ID to start calls");this.forceTURN=(n=e.forceTURN)!==null&&n!==void 0?n:!1,this.ourPartyId=this.client.deviceId,this.opponentDeviceId=e.opponentDeviceId,this.opponentSessionId=e.opponentSessionId,this.groupCallId=e.groupCallId,this.turnServers=e.turnServers||[],this.turnServers.length===0&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:[Mz]});for(var i of this.turnServers)H1(i,["urls"]);this.callId=da(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}placeVoiceCall(){var e=this;return _(function*(){yield e.placeCall(!0,!1)})()}placeVideoCall(){var e=this;return _(function*(){yield e.placeCall(!0,!0)})()}createDataChannel(e,t){var n=this.peerConn.createDataChannel(e,t);return this.emit(Ye.DataChannel,n,this),n}getOpponentMember(){return this.opponentMember}getOpponentDeviceId(){return this.opponentDeviceId}getOpponentSessionId(){return this.opponentSessionId}opponentCanBeTransferred(){return!!(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return!!(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get state(){return this._state}set state(e){var t=this._state;this._state=e,this.emit(Ye.State,e,t,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?MC.Video:MC.Voice}get hasLocalUserMediaVideoTrack(){var e;return!!((e=this.localUsermediaStream)!==null&&e!==void 0&&e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===St.Usermedia&&((t=e.stream)===null||t===void 0?void 0:t.getVideoTracks().length)})}get hasLocalUserMediaAudioTrack(){var e;return!!((e=this.localUsermediaStream)!==null&&e!==void 0&&e.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===St.Usermedia&&!!((t=e.stream)!==null&&t!==void 0&&t.getAudioTracks().length)})}get hasUserMediaAudioSender(){var e;return!!(!((e=this.transceivers.get(si(St.Usermedia,"audio")))===null||e===void 0)&&e.sender)}get hasUserMediaVideoSender(){var e;return!!(!((e=this.transceivers.get(si(St.Usermedia,"video")))===null||e===void 0)&&e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find(e=>e.purpose===St.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(e=>e.purpose===St.Screenshare)}get localUsermediaStream(){var e;return(e=this.localUsermediaFeed)===null||e===void 0?void 0:e.stream}get localScreensharingStream(){var e;return(e=this.localScreensharingFeed)===null||e===void 0?void 0:e.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find(e=>e.purpose===St.Usermedia)}get remoteScreensharingFeed(){return this.getRemoteFeeds().find(e=>e.purpose===St.Screenshare)}get remoteUsermediaStream(){var e;return(e=this.remoteUsermediaFeed)===null||e===void 0?void 0:e.stream}get remoteScreensharingStream(){var e;return(e=this.remoteScreensharingFeed)===null||e===void 0?void 0:e.stream}getFeedByStreamId(e){return this.getFeeds().find(t=>t.stream.id===e)}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter(e=>e.isLocal())}getRemoteFeeds(){return this.feeds.filter(e=>!e.isLocal())}initOpponentCrypto(){var e=this;return _(function*(){var t,n;if(e.opponentDeviceId&&e.client.getUseE2eForGroupCall()){if(!e.client.isCryptoEnabled()){e.opponentDeviceInfo=new tn(e.opponentDeviceId);return}if(!e.client.crypto)throw new Error("Crypto is not initialised.");var i=e.invitee||((t=e.getOpponentMember())===null||t===void 0?void 0:t.userId);if(!i)throw new Error("Couldn't find opponent user ID to init crypto");var o=yield e.client.crypto.deviceList.downloadKeys([i],!1);if(e.opponentDeviceInfo=(n=o.get(i))===null||n===void 0?void 0:n.get(e.opponentDeviceId),e.opponentDeviceInfo===void 0)throw new QD(i)}})()}getLocalSDPStreamMetadata(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t={};for(var n of this.getLocalFeeds())e&&(n.sdpMetadataStreamId=n.stream.id),t[n.sdpMetadataStreamId]={purpose:n.purpose,audio_muted:n.isAudioMuted(),video_muted:n.isVideoMuted()};return t}noIncomingFeeds(){return!this.feeds.some(e=>!e.isLocal())}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata()){this.pushRemoteFeedWithoutMetadata(e);return}var t=this.getOpponentMember().userId,n=this.remoteSDPStreamMetadata[e.id].purpose,i=this.remoteSDPStreamMetadata[e.id].audio_muted,o=this.remoteSDPStreamMetadata[e.id].video_muted;if(!n){S.warn("Call ".concat(this.callId," pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=").concat(e.id,")"));return}if(this.getFeedByStreamId(e.id)){S.warn("Call ".concat(this.callId," pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.feeds.push(new So({client:this.client,call:this,roomId:this.roomId,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:n,audioMuted:i,videoMuted:o})),this.emit(Ye.FeedsChanged,this.feeds,this),S.info("Call ".concat(this.callId," pushRemoteFeed() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,", purpose=").concat(n,")"))}pushRemoteFeedWithoutMetadata(e){var t,n=this.getOpponentMember().userId,i=St.Usermedia,o=(t=this.feeds.find(s=>!s.isLocal()))===null||t===void 0?void 0:t.stream;if(o&&e.id!==o.id){S.warn("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=").concat(e.id,")"));return}if(this.getFeedByStreamId(e.id)){S.warn("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.feeds.push(new So({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:n,deviceId:this.getOpponentDeviceId(),stream:e,purpose:i})),this.emit(Ye.FeedsChanged,this.feeds,this),S.info("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,")"))}pushNewLocalFeed(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=this.client.getUserId();if(tr(e.getAudioTracks(),!0),tr(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)){S.warn("Call ".concat(this.callId," pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.pushLocalFeed(new So({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:t}),n)}pushLocalFeed(e){var t=this,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(this.feeds.some(s=>e.stream.id===s.stream.id)){S.info("Call ".concat(this.callId," pushLocalFeed() ignoring duplicate local stream (streamId=").concat(e.stream.id,")"));return}if(this.feeds.push(e),n){var i=function(){S.info("Call ".concat(t.callId," pushLocalFeed() adding track to peer connection (id=").concat(o.id,", kind=").concat(o.kind,", streamId=").concat(e.stream.id,", streamPurpose=").concat(e.purpose,", enabled=").concat(o.enabled,")"));var a=si(e.purpose,o.kind);if(t.transceivers.has(a)){var l=t.transceivers.get(a);l.sender.replaceTrack(o),l.direction=l.direction==="inactive"?"sendonly":"sendrecv"}else{var c=t.peerConn.addTrack(o,e.stream),u=t.peerConn.getTransceivers().find(d=>d.sender===c);u?t.transceivers.set(a,u):S.warn("Call ".concat(t.callId," pushLocalFeed() didn't find a matching transceiver after adding track!"))}};for(var o of e.stream.getTracks())i()}S.info("Call ".concat(this.callId," pushLocalFeed() pushed stream (id=").concat(e.stream.id,", active=").concat(e.stream.active,", purpose=").concat(e.purpose,")")),this.emit(Ye.FeedsChanged,this.feeds,this)}removeLocalFeed(e){var t=si(e.purpose,"audio"),n=si(e.purpose,"video");for(var i of[t,n])if(this.transceivers.has(i)){var o=this.transceivers.get(i);o.sender&&this.peerConn.removeTrack(o.sender)}e.purpose===St.Screenshare&&this.client.getMediaHandler().stopScreensharingStream(e.stream),this.deleteFeed(e)}deleteAllFeeds(){for(var e of this.feeds)(!e.isLocal()||!this.groupCallId)&&e.dispose();this.feeds=[],this.emit(Ye.FeedsChanged,this.feeds,this)}deleteFeedByStream(e){var t=this.getFeedByStreamId(e.id);if(!t){S.warn("Call ".concat(this.callId," deleteFeedByStream() didn't find the feed to delete (streamId=").concat(e.id,")"));return}this.deleteFeed(t)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit(Ye.FeedsChanged,this.feeds,this)}getCurrentCallStats(){var e=this;return _(function*(){return e.callHasEnded()?e.callStatsAtEnd:e.collectCallStats()})()}collectCallStats(){var e=this;return _(function*(){if(e.peerConn){var t=yield e.peerConn.getStats(),n=[];return t.forEach(i=>{n.push(i)}),n}})()}initWithInvite(e){var t=this;return _(function*(){var n,i=e.getContent();t.direction=es.Inbound;var o=yield t.client.checkTurnServers();o||S.warn("Call ".concat(t.callId," initWithInvite() failed to get TURN credentials! Proceeding with call anyway..."));var s=i[Yo];s?t.updateRemoteSDPStreamMetadata(s):S.debug("Call ".concat(t.callId," initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams")),t.peerConn=t.createPeerConnection(),t.emit(Ye.PeerConnectionCreated,t.peerConn,t),t.chooseOpponent(e),yield t.initOpponentCrypto();try{yield t.peerConn.setRemoteDescription(i.offer),S.debug("Call ".concat(t.callId," initWithInvite() set remote description: ").concat(i.offer.type)),yield t.addBufferedIceCandidates()}catch(u){S.debug("Call ".concat(t.callId," initWithInvite() failed to set remote description"),u),t.terminate(Vt.Local,qe.SetRemoteDescription,!1);return}var a=(n=t.feeds.find(u=>!u.isLocal()))===null||n===void 0?void 0:n.stream;if(!t.isOnlyDataChannelAllowed&&(!a||a.getTracks().length===0)){S.error("Call ".concat(t.callId," initWithInvite() no remote stream or no tracks after setting remote description!")),t.terminate(Vt.Local,qe.SetRemoteDescription,!1);return}if(t.state=Fe.Ringing,e.getLocalAge()){var l=setTimeout(()=>{if(t.state==Fe.Ringing){var u;S.debug("Call ".concat(t.callId," initWithInvite() invite has expired. Hanging up.")),t.hangupParty=Vt.Remote,t.state=Fe.Ended,t.stopAllMedia(),t.peerConn.signalingState!="closed"&&t.peerConn.close(),(u=t.stats)===null||u===void 0||u.removeStatsReportGatherer(t.callId),t.emit(Ye.Hangup,t)}},i.lifetime-e.getLocalAge()),c=u=>{u!==Fe.Ringing&&(clearTimeout(l),t.off(Ye.State,c))};t.on(Ye.State,c)}})()}initWithHangup(e){this.state=Fe.Ended}shouldAnswerWithMediaType(e,t,n){return e&&!t?(S.warn("Call ".concat(this.callId," shouldAnswerWithMediaType() unable to answer with ").concat(n," because the other side isn't sending it either.")),!1):!J1(e)&&e!==t&&!this.opponentSupportsSDPStreamMetadata()?(S.warn("Call ".concat(this.callId," shouldAnswerWithMediaType() unable to answer with ").concat(n,"=").concat(e," because the other side doesn't support it. Answering with ").concat(n,"=").concat(t,".")),t):e??t}answer(e,t){var n=this;return _(function*(){if(!n.inviteOrAnswerSent){if(e===!1&&t===!1)throw new Error("You CANNOT answer a call without media");if(!n.localUsermediaStream&&!n.waitForLocalAVStream){var i=n.state,o=n.shouldAnswerWithMediaType(e,n.hasRemoteUserMediaAudioTrack,"audio"),s=n.shouldAnswerWithMediaType(t,n.hasRemoteUserMediaVideoTrack,"video");n.state=Fe.WaitLocalMedia,n.waitForLocalAVStream=!0;try{var a,l=yield n.client.getMediaHandler().getUserMediaStream(o,s);n.waitForLocalAVStream=!1;var c=new So({client:n.client,roomId:n.roomId,userId:n.client.getUserId(),deviceId:(a=n.client.getDeviceId())!==null&&a!==void 0?a:void 0,stream:l,purpose:St.Usermedia,audioMuted:!1,videoMuted:!1}),u=[c];n.localScreensharingFeed&&u.push(n.localScreensharingFeed),n.answerWithCallFeeds(u)}catch(d){if(s)S.warn("Call ".concat(n.callId," answer() failed to getUserMedia(), trying to getUserMedia() without video")),n.state=i,n.waitForLocalAVStream=!1,yield n.answer(o,!1);else{n.getUserMediaFailed(d);return}}}else n.waitForLocalAVStream&&(n.state=Fe.WaitLocalMedia)}})()}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){S.debug("Call ".concat(this.callId," replacedBy() running (newCallId=").concat(e.callId,")")),this.state===Fe.WaitLocalMedia?(S.debug("Call ".concat(this.callId," replacedBy() telling new call to wait for local media (newCallId=").concat(e.callId,")")),e.waitForLocalAVStream=!0):[Fe.CreateOffer,Fe.InviteSent].includes(this.state)&&(e.direction===es.Outbound?e.queueGotCallFeedsForAnswer([]):(S.debug("Call ".concat(this.callId," replacedBy() handing local stream to new call(newCallId=").concat(e.callId,")")),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(t=>t.clone())))),this.successor=e,this.emit(Ye.Replaced,e,this),this.hangup(qe.Replaced,!0)}hangup(e,t){if(!this.callHasEnded()&&(S.debug("Call ".concat(this.callId," hangup() ending call (reason=").concat(e,")")),this.terminate(Vt.Local,e,!t),![Fe.Fledgling,Fe.WaitLocalMedia].includes(this.state))){var n={};(this.opponentVersion&&this.opponentVersion!==0||e!==qe.UserHangup)&&(n.reason=e),this.sendVoipEvent(V.CallHangup,n)}}reject(){if(this.state!==Fe.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion===0){S.info("Call ".concat(this.callId," reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=").concat(this.opponentVersion,")")),this.hangup(qe.UserHangup,!0);return}S.debug("Rejecting call: "+this.callId),this.terminate(Vt.Local,qe.UserHangup,!0),this.sendVoipEvent(V.CallReject,{})}upgradeCall(e,t){var n=this;return _(function*(){if(!(!e&&!t)&&n.opponentSupportsSDPStreamMetadata())try{S.debug("Call ".concat(n.callId," upgradeCall() upgrading call (audio=").concat(e,", video=").concat(t,")"));var i=e||n.hasLocalUserMediaAudioTrack,o=t||n.hasLocalUserMediaVideoTrack,s=yield n.client.getMediaHandler().getUserMediaStream(i,o,!1);yield n.updateLocalUsermediaStream(s,e,t)}catch(a){S.error("Call ".concat(n.callId," upgradeCall() failed to upgrade the call"),a),n.emit(Ye.Error,new vo(qe.NoUserMedia,"Failed to get camera access: ",a),n)}})()}opponentSupportsSDPStreamMetadata(){return!!this.remoteSDPStreamMetadata}isScreensharing(){return!!this.localScreensharingStream}setScreensharingEnabled(e,t){var n=this;return _(function*(){if(e&&n.isScreensharing())return S.warn("Call ".concat(n.callId," setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!")),!0;if(!e&&!n.isScreensharing())return S.warn("Call ".concat(n.callId," setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!")),!1;if(!n.opponentSupportsSDPStreamMetadata())return n.setScreensharingEnabledWithoutMetadataSupport(e,t);if(S.debug("Call ".concat(n.callId," setScreensharingEnabled() running (enabled=").concat(e,")")),e)try{var i=yield n.client.getMediaHandler().getScreensharingStream(t);return i?(n.pushNewLocalFeed(i,St.Screenshare),!0):!1}catch(l){return S.error("Call ".concat(n.callId," setScreensharingEnabled() failed to get screen-sharing stream:"),l),!1}else{var o=n.transceivers.get(si(St.Screenshare,"audio")),s=n.transceivers.get(si(St.Screenshare,"video"));for(var a of[o,s])a&&a.sender&&n.peerConn.removeTrack(a.sender);return n.client.getMediaHandler().stopScreensharingStream(n.localScreensharingStream),n.deleteFeedByStream(n.localScreensharingStream),!1}})()}setScreensharingEnabledWithoutMetadataSupport(e,t){var n=this;return _(function*(){if(S.debug("Call ".concat(n.callId," setScreensharingEnabledWithoutMetadataSupport() running (enabled=").concat(e,")")),e)try{var i,o=yield n.client.getMediaHandler().getScreensharingStream(t);if(!o)return!1;var s=o.getTracks().find(f=>f.kind==="video"),a=(i=n.transceivers.get(si(St.Usermedia,"video")))===null||i===void 0?void 0:i.sender;return a==null||a.replaceTrack(s??null),n.pushNewLocalFeed(o,St.Screenshare,!1),!0}catch(f){return S.error("Call ".concat(n.callId," setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:"),f),!1}else{var l,c,u=(l=n.localUsermediaStream)===null||l===void 0?void 0:l.getTracks().find(f=>f.kind==="video"),d=(c=n.transceivers.get(si(St.Usermedia,"video")))===null||c===void 0?void 0:c.sender;return d==null||d.replaceTrack(u??null),n.client.getMediaHandler().stopScreensharingStream(n.localScreensharingStream),n.deleteFeedByStream(n.localScreensharingStream),!1}})()}updateLocalUsermediaStream(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2&&t[2]!==void 0?t[2]:!1,s=n.localUsermediaFeed,a=i||!s.isAudioMuted()&&!n.remoteOnHold,l=o||!s.isVideoMuted()&&!n.remoteOnHold;S.log("Call ".concat(n.callId," updateLocalUsermediaStream() running (streamId=").concat(e.id,", audio=").concat(a,", video=").concat(l,")")),tr(e.getAudioTracks(),a),tr(e.getVideoTracks(),l);for(var c of n.localUsermediaStream.getTracks())n.localUsermediaStream.removeTrack(c),c.stop();for(var u of e.getTracks())n.localUsermediaStream.addTrack(u);var d=function*(){var h=si(St.Usermedia,f.kind),m=n.transceivers.get(h),w=m==null?void 0:m.sender,g=!1;if(w)try{S.info("Call ".concat(n.callId," updateLocalUsermediaStream() replacing track (id=").concat(f.id,", kind=").concat(f.kind,", streamId=").concat(e.id,", streamPurpose=").concat(s.purpose,")")),yield w.replaceTrack(f),m.direction=m.direction==="inactive"?"sendonly":"sendrecv",g=!0}catch(k){S.warn("Call ".concat(n.callId," updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead"),k)}if(!g){S.info("Call ".concat(n.callId," updateLocalUsermediaStream() adding track to peer connection (id=").concat(f.id,", kind=").concat(f.kind,", streamId=").concat(e.id,", streamPurpose=").concat(s.purpose,")"));var b=n.peerConn.addTrack(f,n.localUsermediaStream),R=n.peerConn.getTransceivers().find(k=>k.sender===b);R?n.transceivers.set(h,R):S.warn("Call ".concat(n.callId," updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!"))}};for(var f of e.getTracks())yield*d()})()}setLocalVideoMuted(e){var t=this;return _(function*(){var n;if(S.log("Call ".concat(t.callId," setLocalVideoMuted() running ").concat(e)),!e&&t.stopVideoTrackTimer!==void 0&&(clearTimeout(t.stopVideoTrackTimer),t.stopVideoTrackTimer=void 0),!(yield t.client.getMediaHandler().hasVideoDevice()))return t.isLocalVideoMuted();if(!t.hasUserMediaVideoSender&&!e){var i;return(i=t.localUsermediaFeed)===null||i===void 0||i.setAudioVideoMuted(null,e),yield t.upgradeCall(!1,!0),t.isLocalVideoMuted()}if(!e&&t.localUsermediaStream.getVideoTracks().length===0){var o=yield t.client.getMediaHandler().getUserMediaStream(!0,!0);yield t.updateLocalUsermediaStream(o)}return(n=t.localUsermediaFeed)===null||n===void 0||n.setAudioVideoMuted(null,e),t.updateMuteStatus(),yield t.sendMetadataUpdate(),e&&(t.stopVideoTrackTimer=setTimeout(()=>{for(var s of t.localUsermediaStream.getVideoTracks())s.stop(),t.localUsermediaStream.removeTrack(s)},120)),t.isLocalVideoMuted()})()}isLocalVideoMuted(){var e,t;return(e=(t=this.localUsermediaFeed)===null||t===void 0?void 0:t.isVideoMuted())!==null&&e!==void 0?e:!1}setMicrophoneMuted(e){var t=this;return _(function*(){var n;return S.log("Call ".concat(t.callId," setMicrophoneMuted() running ").concat(e)),(yield t.client.getMediaHandler().hasAudioDevice())?!e&&(!t.hasUserMediaAudioSender||!t.hasLocalUserMediaAudioTrack)?(yield t.upgradeCall(!0,!1),t.isMicrophoneMuted()):((n=t.localUsermediaFeed)===null||n===void 0||n.setAudioVideoMuted(e,null),t.updateMuteStatus(),yield t.sendMetadataUpdate(),t.isMicrophoneMuted()):t.isMicrophoneMuted()})()}isMicrophoneMuted(){var e,t;return(e=(t=this.localUsermediaFeed)===null||t===void 0?void 0:t.isAudioMuted())!==null&&e!==void 0?e:!1}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(var t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit(Ye.RemoteHoldUnhold,this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!==Fe.Connected)return!1;var e=!0;for(var t of this.peerConn.getTransceivers()){var n=["inactive","recvonly"].includes(t.currentDirection);n||(e=!1)}return e}sendDtmfDigit(e){for(var t of this.peerConn.getSenders()){var n;if(((n=t.track)===null||n===void 0?void 0:n.kind)==="audio"&&t.dtmf){t.dtmf.insertDTMF(e);return}}throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){var e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;S.log("Call ".concat(this.callId," updateMuteStatus stream ").concat(this.localUsermediaStream.id," micShouldBeMuted ").concat(e," vidShouldBeMuted ").concat(t)),tr(this.localUsermediaStream.getAudioTracks(),!e),tr(this.localUsermediaStream.getVideoTracks(),!t)}sendMetadataUpdate(){var e=this;return _(function*(){yield e.sendVoipEvent(V.CallSDPStreamMetadataChangedPrefix,{[Yo]:e.getLocalSDPStreamMetadata()})})()}gotCallFeedsForInvite(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(this.successor){this.successor.queueGotCallFeedsForAnswer(e);return}if(this.callHasEnded()){this.stopAllMedia();return}for(var n of e)this.pushLocalFeed(n);t&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=Fe.CreateOffer,S.debug("Call ".concat(this.callId," gotUserMediaForInvite() run"))}sendAnswer(){var e=this;return _(function*(){var t={answer:{sdp:e.peerConn.localDescription.sdp,type:e.peerConn.localDescription.type},[Yo]:e.getLocalSDPStreamMetadata(!0)};t.capabilities={"m.call.transferee":e.client.supportsCallTransfer,"m.call.dtmf":!1};var n=e.discardDuplicateCandidates();S.info("Call ".concat(e.callId," sendAnswer() discarding ").concat(n," candidates that will be sent in answer"));try{yield e.sendVoipEvent(V.CallAnswer,t),e.inviteOrAnswerSent=!0}catch(s){e.state=Fe.Ringing,s instanceof hr&&s.event&&e.client.cancelPendingEvent(s.event);var i=qe.SendAnswer,o="Failed to send answer";throw s.name=="UnknownDeviceError"&&(i=qe.UnknownDevices,o="Unknown devices present in the room"),e.emit(Ye.Error,new vo(i,o,s),e),s}e.sendCandidateQueue()})()}queueGotCallFeedsForAnswer(e){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.gotCallFeedsForAnswer(e)):this.responsePromiseChain=this.gotCallFeedsForAnswer(e)}mungeSdp(e,t){var n=zD(e.sdp);n.media.forEach(i=>{var o=new Map,s=new Map;for(var a of i.rtp)o.set(a.payload,a.codec),s.set(a.codec,a.payload);for(var l of t)if(l.mediaType===i.type){if(!s.has(l.codec)){S.info("Call ".concat(this.callId," mungeSdp() ignoring SDP modifications for ").concat(l.codec," as it's not present."));continue}var c=[];l.enableDtx!==void 0&&c.push("usedtx=".concat(l.enableDtx?"1":"0")),l.maxAverageBitrate!==void 0&&c.push("maxaveragebitrate=".concat(l.maxAverageBitrate));var u=!1;for(var d of i.fmtp)o.get(d.payload)===l.codec&&(u=!0,d.config+=";"+c.join(";"));u||i.fmtp.push({payload:s.get(l.codec),config:c.join(";")})}}),e.sdp=az(n)}createOffer(){var e=this;return _(function*(){var t=yield e.peerConn.createOffer();return e.mungeSdp(t,AC(e.isPtt)),t})()}createAnswer(){var e=this;return _(function*(){var t=yield e.peerConn.createAnswer();return e.mungeSdp(t,AC(e.isPtt)),t})()}gotCallFeedsForAnswer(e){var t=this;return _(function*(){if(!t.callHasEnded()){t.waitForLocalAVStream=!1;for(var n of e)t.pushLocalFeed(n);t.state=Fe.CreateAnswer;var i;try{t.getRidOfRTXCodecs(),i=yield t.createAnswer()}catch(o){S.debug("Call ".concat(t.callId," gotCallFeedsForAnswer() failed to create answer: "),o),t.terminate(Vt.Local,qe.CreateAnswer,!0);return}try{if(yield t.peerConn.setLocalDescription(i),t.callHasEnded()||(t.state=Fe.Connecting,yield new Promise(o=>{setTimeout(o,200)}),t.callHasEnded()))return;t.sendAnswer()}catch(o){S.debug("Call ".concat(t.callId," gotCallFeedsForAnswer() error setting local description!"),o),t.terminate(Vt.Local,qe.SetLocalDescription,!0);return}}})()}onRemoteIceCandidatesReceived(e){var t=this;return _(function*(){if(!t.callHasEnded()){var n=e.getContent(),i=n.candidates;if(!i){S.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!"));return}var o=n.version===0?null:n.party_id||null;if(t.opponentPartyId===void 0){if(o){S.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() buffering ").concat(i.length," candidates until we pick an opponent"));var s=t.remoteCandidateBuffer.get(o)||[];s.push(...i),t.remoteCandidateBuffer.set(o,s)}return}if(!t.partyIdMatches(n)){S.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() ignoring candidates from party ID ").concat(n.party_id,": we have chosen party ID ").concat(t.opponentPartyId));return}yield t.addIceCandidates(i)}})()}onAnswerReceived(e){var t=this;return _(function*(){var n=e.getContent();if(S.debug("Call ".concat(t.callId," onAnswerReceived() running (hangupParty=").concat(n.party_id,")")),t.callHasEnded()){S.debug("Call ".concat(t.callId," onAnswerReceived() ignoring answer because call has ended"));return}if(t.opponentPartyId!==void 0){S.info("Call ".concat(t.callId," onAnswerReceived() ignoring answer from party ID ").concat(n.party_id,": we already have an answer/reject from ").concat(t.opponentPartyId));return}t.chooseOpponent(e),yield t.addBufferedIceCandidates(),t.state=Fe.Connecting;var i=n[Yo];i?t.updateRemoteSDPStreamMetadata(i):S.warn("Call ".concat(t.callId," onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams"));try{t.isSettingRemoteAnswerPending=!0,yield t.peerConn.setRemoteDescription(n.answer),t.isSettingRemoteAnswerPending=!1,S.debug("Call ".concat(t.callId," onAnswerReceived() set remote description: ").concat(n.answer.type))}catch(o){t.isSettingRemoteAnswerPending=!1,S.debug("Call ".concat(t.callId," onAnswerReceived() failed to set remote description"),o),t.terminate(Vt.Local,qe.SetRemoteDescription,!1);return}if(t.opponentPartyId!==null)try{yield t.sendVoipEvent(V.CallSelectAnswer,{selected_party_id:t.opponentPartyId})}catch(o){S.warn("Call ".concat(t.callId," onAnswerReceived() failed to send select_answer event"),o)}})()}onSelectAnswerReceived(e){var t=this;return _(function*(){if(t.direction!==es.Inbound){S.warn("Call ".concat(t.callId," onSelectAnswerReceived() got select_answer for an outbound call: ignoring"));return}var n=e.getContent().selected_party_id;if(n==null){S.warn("Call ".concat(t.callId," onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring"));return}n!==t.ourPartyId&&(S.info("Call ".concat(t.callId," onSelectAnswerReceived() got select_answer for party ID ").concat(n,": we are party ID ").concat(t.ourPartyId,".")),yield t.terminate(Vt.Remote,qe.AnsweredElsewhere,!0))})()}onNegotiateReceived(e){var t=this;return _(function*(){var n=e.getContent(),i=n.description;if(!i||!i.sdp||!i.type){S.info("Call ".concat(t.callId," onNegotiateReceived() ignoring invalid m.call.negotiate event"));return}var o=t.direction===es.Inbound,s=!t.makingOffer&&(t.peerConn.signalingState==="stable"||t.isSettingRemoteAnswerPending),a=i.type==="offer"&&!s;if(t.ignoreOffer=!o&&a,t.ignoreOffer){S.info("Call ".concat(t.callId," onNegotiateReceived() ignoring colliding negotiate event because we're impolite"));return}var l=t.isLocalOnHold(),c=n[Yo];c?t.updateRemoteSDPStreamMetadata(c):S.warn("Call ".concat(t.callId," onNegotiateReceived() received negotiation event without SDPStreamMetadata!"));try{if(t.isSettingRemoteAnswerPending=i.type=="answer",yield t.peerConn.setRemoteDescription(i),t.isSettingRemoteAnswerPending=!1,S.debug("Call ".concat(t.callId," onNegotiateReceived() set remote description: ").concat(i.type)),i.type==="offer"){var u,d;try{t.getRidOfRTXCodecs(),d=yield t.createAnswer()}catch(p){S.debug("Call ".concat(t.callId," onNegotiateReceived() failed to create answer: "),p),t.terminate(Vt.Local,qe.CreateAnswer,!0);return}yield t.peerConn.setLocalDescription(d),S.debug("Call ".concat(t.callId," onNegotiateReceived() create an answer")),t.sendVoipEvent(V.CallNegotiate,{lifetime:Xg,description:(u=t.peerConn.localDescription)===null||u===void 0?void 0:u.toJSON(),[Yo]:t.getLocalSDPStreamMetadata(!0)})}}catch(p){t.isSettingRemoteAnswerPending=!1,S.warn("Call ".concat(t.callId," onNegotiateReceived() failed to complete negotiation"),p)}var f=t.isLocalOnHold();l!==f&&(t.emit(Ye.LocalHoldUnhold,f,t),t.emit(Ye.HoldUnhold,f))})()}updateRemoteSDPStreamMetadata(e){this.remoteSDPStreamMetadata=X1(this.remoteSDPStreamMetadata||{},e,!0);for(var t of this.getRemoteFeeds()){var n,i=t.stream.id,o=this.remoteSDPStreamMetadata[i];t.setAudioVideoMuted(o==null?void 0:o.audio_muted,o==null?void 0:o.video_muted),t.purpose=(n=this.remoteSDPStreamMetadata[i])===null||n===void 0?void 0:n.purpose}}onSDPStreamMetadataChangedReceived(e){var t=e.getContent(),n=t[Yo];this.updateRemoteSDPStreamMetadata(n)}onAssertedIdentityReceived(e){var t=this;return _(function*(){var n=e.getContent();n.asserted_identity&&(t.remoteAssertedIdentity={id:n.asserted_identity.id,displayName:n.asserted_identity.display_name},t.emit(Ye.AssertedIdentityChanged,t))})()}callHasEnded(){return this.state===Fe.Ended}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.wrappedGotLocalOffer()):this.responsePromiseChain=this.wrappedGotLocalOffer()}wrappedGotLocalOffer(){var e=this;return _(function*(){e.makingOffer=!0;try{yield e.gotLocalOffer()}catch(t){e.getLocalOfferFailed(t);return}finally{e.makingOffer=!1}})()}gotLocalOffer(){var e=this;return _(function*(){if(S.debug("Call ".concat(e.callId," gotLocalOffer() running")),e.callHasEnded()){S.debug("Call ".concat(e.callId,' gotLocalOffer() ignoring newly created offer because the call has ended"'));return}var t;try{e.getRidOfRTXCodecs(),t=yield e.createOffer()}catch(u){S.debug("Call ".concat(e.callId," gotLocalOffer() failed to create offer: "),u),e.terminate(Vt.Local,qe.CreateOffer,!0);return}try{yield e.peerConn.setLocalDescription(t)}catch(u){S.debug("Call ".concat(e.callId," gotLocalOffer() error setting local description!"),u),e.terminate(Vt.Local,qe.SetLocalDescription,!0);return}if(e.peerConn.iceGatheringState==="gathering"&&(yield new Promise(u=>{setTimeout(u,200)})),!e.callHasEnded()){var n=e.state===Fe.CreateOffer?V.CallInvite:V.CallNegotiate,i={lifetime:Xg};if(n===V.CallInvite&&e.invitee&&(i.invitee=e.invitee),e.state===Fe.CreateOffer){var o;i.offer=(o=e.peerConn.localDescription)===null||o===void 0?void 0:o.toJSON()}else{var s;i.description=(s=e.peerConn.localDescription)===null||s===void 0?void 0:s.toJSON()}i.capabilities={"m.call.transferee":e.client.supportsCallTransfer,"m.call.dtmf":!1},i[Yo]=e.getLocalSDPStreamMetadata(!0);var a=e.discardDuplicateCandidates();S.info("Call ".concat(e.callId," gotLocalOffer() discarding ").concat(a," candidates that will be sent in offer"));try{yield e.sendVoipEvent(n,i)}catch(u){S.error("Call ".concat(e.callId," gotLocalOffer() failed to send invite"),u),u instanceof hr&&u.event&&e.client.cancelPendingEvent(u.event);var l=qe.SignallingFailed,c="Signalling failed";e.state===Fe.CreateOffer&&(l=qe.SendInvite,c="Failed to send invite"),u.name=="UnknownDeviceError"&&(l=qe.UnknownDevices,c="Unknown devices present in the room"),e.emit(Ye.Error,new vo(l,c,u),e),e.terminate(Vt.Local,l,!1);return}e.sendCandidateQueue(),e.state===Fe.CreateOffer&&(e.inviteOrAnswerSent=!0,e.state=Fe.InviteSent,e.inviteTimeout=setTimeout(()=>{e.inviteTimeout=void 0,e.state===Fe.InviteSent&&e.hangup(qe.InviteTimeout,!1)},Xg))}})()}getRidOfRTXCodecs(){if(!(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)){var e=this.transceivers.get(si(St.Screenshare,"video"));if(!(!e||!e.setCodecPreferences)){var t=RTCRtpReceiver.getCapabilities("video").codecs,n=RTCRtpSender.getCapabilities("video").codecs,i=[];for(var o of[...t,...n])if(o.mimeType!=="video/rtx"){i.push(o);try{e.setCodecPreferences(i)}catch(s){S.info("Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences",o,s),i.pop()}}}}}sendVoipEvent(e,t){var n=this;return _(function*(){var i=uh(uh({},t),{},{version:Pz,call_id:n.callId,party_id:n.ourPartyId,conf_id:n.groupCallId});if(n.opponentDeviceId){var o,s=n.toDeviceSeq++,a=uh(uh({},i),{},{device_id:n.client.deviceId,sender_session_id:n.client.getSessionId(),dest_session_id:n.opponentSessionId,seq:s,[en]:_i()});n.emit(Ye.SendVoipEvent,{type:"toDevice",eventType:e,userId:n.invitee||((o=n.getOpponentMember())===null||o===void 0?void 0:o.userId),opponentDeviceId:n.opponentDeviceId,content:a},n);var l=n.invitee||n.getOpponentMember().userId;if(n.client.getUseE2eForGroupCall()){if(!n.opponentDeviceInfo){S.warn("Call ".concat(n.callId," sendVoipEvent() failed: we do not have opponentDeviceInfo"));return}yield n.client.encryptAndSendToDevices([{userId:l,deviceInfo:n.opponentDeviceInfo}],{type:e,content:a})}else yield n.client.sendToDevice(e,new Map([[l,new Map([[n.opponentDeviceId,a]])]]))}else{var c;n.emit(Ye.SendVoipEvent,{type:"sendEvent",eventType:e,roomId:n.roomId,content:i,userId:n.invitee||((c=n.getOpponentMember())===null||c===void 0?void 0:c.userId)},n),yield n.client.sendEvent(n.roomId,e,i)}})()}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,!(this.state===Fe.Ringing||!this.inviteOrAnswerSent)){var t=this.direction===es.Inbound?500:2e3;this.candidateSendTries===0&&setTimeout(()=>{this.sendCandidateQueue()},t)}}discardDuplicateCandidates(){for(var e=0,t=[],n=0;n<this.candidateSendQueue.length;n++){var i=this.candidateSendQueue[n];i.candidate===""?t.push(i):e++}return this.candidateSendQueue=t,e}transfer(e){var t=this;return _(function*(){var n=yield t.client.getProfileInfo(e),i=da(),o={replacement_id:da(),target_user:{id:e,display_name:n.displayname,avatar_url:n.avatar_url},create_call:i};yield t.sendVoipEvent(V.CallReplaces,o),yield t.terminate(Vt.Local,qe.Transferred,!0)})()}transferToCall(e){var t=this;return _(function*(){var n,i,o=(n=e.getOpponentMember())===null||n===void 0?void 0:n.userId,s=o?yield t.client.getProfileInfo(o):void 0,a=(i=t.getOpponentMember())===null||i===void 0?void 0:i.userId,l=a?yield t.client.getProfileInfo(a):void 0,c=da(),u={replacement_id:da(),target_user:{id:a,display_name:l==null?void 0:l.displayname,avatar_url:l==null?void 0:l.avatar_url},await_call:c};yield e.sendVoipEvent(V.CallReplaces,u);var d={replacement_id:da(),target_user:{id:o,display_name:s==null?void 0:s.displayname,avatar_url:s==null?void 0:s.avatar_url},create_call:c};yield t.sendVoipEvent(V.CallReplaces,d),yield t.terminate(Vt.Local,qe.Transferred,!0),yield e.terminate(Vt.Local,qe.Transferred,!0)})()}terminate(e,t,n){var i=this;return _(function*(){var o;if(!i.callHasEnded()){i.hangupParty=e,i.hangupReason=t,i.state=Fe.Ended,i.inviteTimeout&&(clearTimeout(i.inviteTimeout),i.inviteTimeout=void 0),i.iceDisconnectedTimeout!==void 0&&(clearTimeout(i.iceDisconnectedTimeout),i.iceDisconnectedTimeout=void 0),i.callLengthInterval&&(clearInterval(i.callLengthInterval),i.callLengthInterval=void 0),i.stopVideoTrackTimer!==void 0&&(clearTimeout(i.stopVideoTrackTimer),i.stopVideoTrackTimer=void 0);for(var[s,a]of i.removeTrackListeners)s.removeEventListener("removetrack",a);i.removeTrackListeners.clear(),i.callStatsAtEnd=yield i.collectCallStats(),i.stopAllMedia(),i.deleteAllFeeds(),i.peerConn&&i.peerConn.signalingState!=="closed"&&i.peerConn.close(),(o=i.stats)===null||o===void 0||o.removeStatsReportGatherer(i.callId),n&&i.emit(Ye.Hangup,i),i.client.callEventHandler.calls.delete(i.callId)}})()}stopAllMedia(){S.debug("Call ".concat(this.callId," stopAllMedia() running"));for(var e of this.feeds)if(e.isLocal()&&e.purpose===St.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===St.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else if(!e.isLocal()){S.debug("Call ".concat(this.callId," stopAllMedia() stopping stream (streamId=").concat(e.stream.id,")"));for(var t of e.stream.getTracks())t.stop()}}checkForErrorListener(){if(this.listeners(aD.Error).length===0)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}sendCandidateQueue(){var e=this;return _(function*(){if(!(e.candidateSendQueue.length===0||e.callHasEnded())){var t=e.candidateSendQueue;e.candidateSendQueue=[],++e.candidateSendTries;var n={candidates:t.map(a=>a.toJSON())};e.candidatesEnded&&n.candidates.push({candidate:""}),S.debug("Call ".concat(e.callId," sendCandidateQueue() attempting to send ").concat(t.length," candidates"));try{yield e.sendVoipEvent(V.CallCandidates,n),e.candidateSendTries=0,e.sendCandidateQueue()}catch(a){if(a instanceof hr&&a.event&&e.client.cancelPendingEvent(a.event),e.candidateSendQueue.push(...t),e.candidateSendTries>5){S.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates on attempt ").concat(e.candidateSendTries,". Giving up on this call."),a);var i=qe.SignallingFailed,o="Signalling failed";e.emit(Ye.Error,new vo(i,o,a),e),e.hangup(i,!1);return}var s=500*Math.pow(2,e.candidateSendTries);++e.candidateSendTries,S.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates. Retrying in ").concat(s,"ms"),a),setTimeout(()=>{e.sendCandidateQueue()},s)}}})()}placeCall(e,t){var n=this;return _(function*(){if(!e)throw new Error("You CANNOT start a call without audio");n.state=Fe.WaitLocalMedia;var i;try{var o,s=yield n.client.getMediaHandler().getUserMediaStream(e,t);tr(s.getAudioTracks(),!0),tr(s.getVideoTracks(),!0),i=new So({client:n.client,roomId:n.roomId,userId:n.client.getUserId(),deviceId:(o=n.client.getDeviceId())!==null&&o!==void 0?o:void 0,stream:s,purpose:St.Usermedia,audioMuted:!1,videoMuted:!1})}catch(a){n.getUserMediaFailed(a);return}try{yield n.placeCallWithCallFeeds([i])}catch(a){n.placeCallFailed(a);return}})()}placeCallWithCallFeeds(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;n.checkForErrorListener(),n.direction=es.Outbound,yield n.initOpponentCrypto(),n.client.callEventHandler.calls.set(n.callId,n);var o=yield n.client.checkTurnServers();o||S.warn("Call ".concat(n.callId," placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...")),n.peerConn=n.createPeerConnection(),n.emit(Ye.PeerConnectionCreated,n.peerConn,n),n.gotCallFeedsForInvite(e,i)})()}createPeerConnection(){var e,t=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers.length?this.turnServers:void 0,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),t.addEventListener("signalingstatechange",this.onSignallingStateChanged),t.addEventListener("icecandidate",this.gotLocalIceCandidate),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t.addEventListener("track",this.onTrack),t.addEventListener("negotiationneeded",this.onNegotiationNeeded),t.addEventListener("datachannel",this.onDataChannel);var n=this.getOpponentMember(),i=n?n.userId:"unknown";return(e=this.stats)===null||e===void 0||e.addStatsReportGatherer(this.callId,i,t),t}partyIdMatches(e){var t=e.version===0?null:e.party_id||null;return t===this.opponentPartyId}chooseOpponent(e){var t,n=e.getContent();if(S.debug("Call ".concat(this.callId," chooseOpponent() running (partyId=").concat(n.party_id,")")),this.opponentVersion=n.version,this.opponentVersion===0?this.opponentPartyId=null:this.opponentPartyId=n.party_id||null,this.opponentCaps=n.capabilities||{},this.opponentMember=(t=this.client.getRoom(this.roomId).getMember(e.getSender()))!==null&&t!==void 0?t:void 0,this.opponentMember){var i;(i=this.stats)===null||i===void 0||i.updateOpponentMember(this.callId,this.opponentMember.userId)}}addBufferedIceCandidates(){var e=this;return _(function*(){var t=e.remoteCandidateBuffer.get(e.opponentPartyId);t&&(S.info("Call ".concat(e.callId," addBufferedIceCandidates() adding ").concat(t.length," buffered candidates for opponent ").concat(e.opponentPartyId)),yield e.addIceCandidates(t)),e.remoteCandidateBuffer.clear()})()}addIceCandidates(e){var t=this;return _(function*(){for(var n of e){(n.sdpMid===null||n.sdpMid===void 0)&&(n.sdpMLineIndex===null||n.sdpMLineIndex===void 0)?S.debug("Call ".concat(t.callId," addIceCandidates() got remote ICE end-of-candidates")):S.debug("Call ".concat(t.callId," addIceCandidates() got remote ICE candidate (sdpMid=").concat(n.sdpMid,", candidate=").concat(n.candidate,")"));try{yield t.peerConn.addIceCandidate(n)}catch(i){t.ignoreOffer?S.debug("Call ".concat(t.callId," addIceCandidates() failed to add remote ICE candidate because ignoring offer"),i):S.info("Call ".concat(t.callId," addIceCandidates() failed to add remote ICE candidate"),i)}}})()}get hasPeerConnection(){return!!this.peerConn}initStats(e){this.stats=e,this.stats.start()}}function tr(r,e){for(var t of r)t.enabled=e}function Mb(){if(typeof window>"u"||typeof document>"u")return!1;try{var r=!!(window.RTCPeerConnection||window.RTCSessionDescription||window.RTCIceCandidate||navigator.mediaDevices);if(!r)return S.error("WebRTC is not supported in this browser / environment"),!1}catch(e){return S.error("Exception thrown when trying to access WebRTC",e),!1}return!0}function Bd(r,e,t){if(!Mb())return null;var n=t?t.forceTURN:!1,i={client:r,roomId:e,invitee:t==null?void 0:t.invitee,turnServers:r.getTurnServers(),forceTURN:r.forceTURN||n,opponentDeviceId:t==null?void 0:t.opponentDeviceId,opponentSessionId:t==null?void 0:t.opponentSessionId,groupCallId:t==null?void 0:t.groupCallId},o=new Lz(i);return r.reEmitter.reEmit(o,Object.values(Ye)),o}var ks=function(r){return r.DontNotify="dont_notify",r.Notify="notify",r.Coalesce="coalesce",r}({}),bw=function(r){return r.Highlight="highlight",r.Sound="sound",r}({}),Uz=function(r){return r.ExactEquals="==",r.LessThan="<",r.GreaterThan=">",r.GreaterThanOrEqual=">=",r.LessThanOrEqual="<=",r}({}),jz="2";function Fz(r){return r==="==2"||r==="2"}var rr=function(r){return r.EventMatch="event_match",r.EventPropertyIs="event_property_is",r.EventPropertyContains="event_property_contains",r.ContainsDisplayName="contains_display_name",r.RoomMemberCount="room_member_count",r.SenderNotificationPermission="sender_notification_permission",r.CallStarted="call_started",r.CallStartedPrefix="org.matrix.msc3914.call_started",r}({}),Er=function(r){return r.Override="override",r.ContentSpecific="content",r.RoomSpecific="room",r.SenderSpecific="sender",r.Underride="underride",r}({}),br=function(r){return r.Master=".m.rule.master",r.IsUserMention=".m.rule.is_user_mention",r.IsRoomMention=".m.rule.is_room_mention",r.ContainsDisplayName=".m.rule.contains_display_name",r.ContainsUserName=".m.rule.contains_user_name",r.AtRoomNotification=".m.rule.roomnotif",r.DM=".m.rule.room_one_to_one",r.EncryptedDM=".m.rule.encrypted_room_one_to_one",r.Message=".m.rule.message",r.EncryptedMessage=".m.rule.encrypted",r.InviteToSelf=".m.rule.invite_for_me",r.MemberEvent=".m.rule.member_event",r.IncomingCall=".m.rule.call",r.SuppressNotices=".m.rule.suppress_notices",r.Tombstone=".m.rule.tombstone",r.PollStart=".m.rule.poll_start",r.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",r.PollEnd=".m.rule.poll_end",r.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",r.PollStartOneToOne=".m.rule.poll_start_one_to_one",r.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",r.PollEndOneToOne=".m.rule.poll_end_one_to_one",r.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one",r}({});function DC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function NC(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?DC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):DC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var LC=[Er.Override,Er.ContentSpecific,Er.RoomSpecific,Er.SenderSpecific,Er.Underride],Bz={".m.rule.is_room_mention":{rule_id:".m.rule.is_room_mention",default:!0,enabled:!0,conditions:[{kind:rr.EventPropertyIs,key:"content.m\\.mentions.room",value:!0},{kind:rr.SenderNotificationPermission,key:"room"}],actions:[ks.Notify,{set_tweak:bw.Highlight}]},".m.rule.reaction":{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:rr.EventMatch,key:"type",pattern:"m.reaction"}],actions:[ks.DontNotify]},".org.matrix.msc3786.rule.room.server_acl":{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:rr.EventMatch,key:"type",pattern:V.RoomServerAcl},{kind:rr.EventMatch,key:"state_key",pattern:""}],actions:[]}},_w=Symbol("UserDefinedRules"),Kz=[br.Master,_w,br.SuppressNotices,br.InviteToSelf,br.MemberEvent,br.IsUserMention,br.ContainsDisplayName,br.IsRoomMention,br.AtRoomNotification,br.Tombstone,".m.rule.reaction",".m.rule.room.server_acl",".org.matrix.msc3786.rule.room.server_acl",".m.rule.suppress_edits"],Vz={".org.matrix.msc3914.rule.room.call":{rule_id:".org.matrix.msc3914.rule.room.call",default:!0,enabled:!0,conditions:[{kind:rr.EventMatch,key:"type",pattern:"org.matrix.msc3401.call"},{kind:rr.CallStarted}],actions:[ks.Notify,{set_tweak:bw.Sound,value:"default"}]}},$z=[_w,br.IncomingCall,".org.matrix.msc3914.rule.room.call",br.EncryptedDM,br.DM,br.Message,br.EncryptedMessage];function UC(r,e,t,n){var i=e.filter(p=>p.default),o=e.filter(p=>!p.default);function s(p){p===_w?l.push(...o):p in t?(S.warn("Adding default global ".concat(r," push rule ").concat(p)),l.push(t[p])):S.warn("Missing default global ".concat(r," push rule ").concat(p))}var a=0,l=[];for(var c of i){var u=n.indexOf(c.rule_id);if(u===-1){l.push(c);continue}for(;u>a;){var d=n[a];s(d),a+=1}l.push(c),a+=1}for(var f of n.slice(a))s(f);return l}class hi{constructor(e){this.client=e,v(this,"parsedKeys",new Map)}static actionListToActionsObject(e){var t={notify:!1,tweaks:{}};for(var n of e)n===ks.Notify?t.notify=!0:typeof n=="object"&&(n.value===void 0&&(n.value=!0),t.tweaks[n.set_tweak]=n.value);return t}static rewriteDefaultRules(e){var t=JSON.parse(JSON.stringify(e));return t||(t={}),t.global||(t.global={}),t.global.override||(t.global.override=[]),t.global.underride||(t.global.underride=[]),t.global.override=UC(Er.Override,t.global.override,Bz,Kz),t.global.underride=UC(Er.Underride,t.global.underride,Vz,$z),t}updateCachedPushRuleKeys(e){e||(e={}),e.global||(e.global={}),e.global.override||(e.global.override=[]),e.global.room||(e.global.room=[]),e.global.sender||(e.global.sender=[]),e.global.underride||(e.global.underride=[]);var t=new Set(this.parsedKeys.keys());for(var n of[e.global.override,e.global.room,e.global.sender,e.global.underride])for(var i of n)if(i.conditions)for(var o of i.conditions)o.kind===rr.EventMatch&&(t.delete(o.key),this.parsedKeys.set(o.key,hi.partsForDottedKey(o.key)));t.forEach(s=>this.parsedKeys.delete(s))}matchingRuleFromKindSet(e,t){for(var n of LC){var i=t[n];if(i){for(var o of i)if(o.enabled){var s=this.templateRuleToRaw(n,o);if(s&&this.ruleMatchesEvent(s,e))return NC(NC({},o),{},{kind:n})}}}return null}templateRuleToRaw(e,t){var n={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case Er.Underride:case Er.Override:n.conditions=t.conditions;break;case Er.RoomSpecific:if(!t.rule_id)return null;n.conditions.push({kind:rr.EventMatch,key:"room_id",value:t.rule_id});break;case Er.SenderSpecific:if(!t.rule_id)return null;n.conditions.push({kind:rr.EventMatch,key:"user_id",value:t.rule_id});break;case Er.ContentSpecific:if(!t.pattern)return null;n.conditions.push({kind:rr.EventMatch,key:"content.body",pattern:t.pattern});break}return n}eventFulfillsCondition(e,t){switch(e.kind){case rr.EventMatch:return this.eventFulfillsEventMatchCondition(e,t);case rr.EventPropertyIs:return this.eventFulfillsEventPropertyIsCondition(e,t);case rr.EventPropertyContains:return this.eventFulfillsEventPropertyContains(e,t);case rr.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,t);case rr.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,t);case rr.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,t);case rr.CallStarted:case rr.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(e,t)}return!1}eventFulfillsSenderNotifPermCondition(e,t){var n=e.key;if(!n)return!1;var i=this.client.getRoom(t.getRoomId());return i!=null&&i.currentState?i.currentState.mayTriggerNotifOfType(n,t.getSender()):!1}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;var n=this.client.getRoom(t.getRoomId());if(!n||!n.currentState||!n.currentState.members)return!1;var i=n.currentState.getJoinedMemberCount(),o=e.is.match(/^([=<>]*)(\d*)$/);if(!o)return!1;var s=o[1],a=parseInt(o[2]);if(isNaN(a))return!1;switch(s){case"":case"==":return i==a;case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;default:return!1}}eventFulfillsDisplayNameCondition(e,t){var n,i=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(i=t.getClearContent()),!i||!i.body||typeof i.body!="string")return!1;var o=this.client.getRoom(t.getRoomId()),s=o==null||(n=o.currentState)===null||n===void 0?void 0:n.getMember(this.client.credentials.userId);if(!s)return!1;var a=s.name,l=new RegExp("(^|\\W)"+z1(a)+"(\\W|$)","i");return i.body.search(l)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;var n=this.valueForDottedKey(e.key,t);if(typeof n!="string")return!1;if(e.value)return e.value===n;if(typeof e.pattern!="string")return!1;var i=e.key==="content.body"?this.createCachedRegex("(^|\\W)",e.pattern,"(\\W|$)"):this.createCachedRegex("^",e.pattern,"$");return!!n.match(i)}eventFulfillsEventPropertyIsCondition(e,t){return!e.key||e.value===void 0?!1:e.value===this.valueForDottedKey(e.key,t)}eventFulfillsEventPropertyContains(e,t){if(!e.key||e.value===void 0)return!1;var n=this.valueForDottedKey(e.key,t);return Array.isArray(n)?n.includes(e.value):!1}eventFulfillsCallStartedCondition(e,t){return["m.ring","m.prompt"].includes(t.getContent()["m.intent"])&&!("m.terminated"in t.getContent())&&(t.getPrevContent()["m.terminated"]!==t.getContent()["m.terminated"]||Fa(t.getPrevContent(),{}))}createCachedRegex(e,t,n){return hi.cachedGlobToRegex[t]||(hi.cachedGlobToRegex[t]=new RegExp(e+Y1(t)+n,"i")),hi.cachedGlobToRegex[t]}static partsForDottedKey(e){var t=[],n="",i=!1;for(var o of e){if(i){o==="\\"||o==="."?n+=o:n+="\\"+o,i=!1;continue}o=="."?(t.push(n),n=""):o=="\\"?i=!0:n+=o}return i&&(n+="\\"),t.push(n),t}valueForDottedKey(e,t){var n=this.parsedKeys.get(e);n===void 0&&(n=hi.partsForDottedKey(e),this.parsedKeys.set(e,n));var i,o=n[0],s=0;for(o==="content"?(i=t.getContent(),++s):o==="type"?(i=t.getType(),++s):i=t.event;s<n.length;++s){if(J1(i))return;var a=n[s];i=i[a]}return i}matchingRuleForEventWithRulesets(e,t){return!t||e.getSender()===this.client.getSafeUserId()?null:this.matchingRuleFromKindSet(e,t.global)}pushActionsForEventAndRulesets(e,t){var n=this.matchingRuleForEventWithRulesets(e,t);if(!n)return{};var i=hi.actionListToActionsObject(n.actions);return i.tweaks.highlight===void 0&&(i.tweaks.highlight=n.kind==Er.ContentSpecific),{actions:i,rule:n}}ruleMatchesEvent(e,t){var n;return this.client.supportsIntentionalMentions()&&t.getContent()["m.mentions"]!==void 0&&(e.rule_id===br.ContainsUserName||e.rule_id===br.ContainsDisplayName||e.rule_id===br.AtRoomNotification)?!1:!((n=e.conditions)!==null&&n!==void 0&&n.some(i=>!this.eventFulfillsCondition(i,t)))}actionsForEvent(e){var{actions:t}=this.pushActionsForEventAndRulesets(e,this.client.pushRules);return t||{}}actionsAndRuleForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){var t,n=this.getPushRuleAndKindById(e);return(t=n==null?void 0:n.rule)!==null&&t!==void 0?t:null}getPushRuleAndKindById(e){for(var t of["global"]){var n;if(((n=this.client.pushRules)===null||n===void 0?void 0:n[t])!==void 0){for(var i of LC)if(this.client.pushRules[t][i]!==void 0){for(var o of this.client.pushRules[t][i])if(o.rule_id===e)return{rule:o,kind:i}}}}return null}}v(hi,"cachedGlobToRegex",{});var rv=["v1.1","v1.2","v1.3","v1.4","v1.5","v1.6","v1.7","v1.8","v1.9"];rv[0];rv[rv.length-1];var Dn=function(r){return r.SUCCESS="SUCCESS",r.IGNORE="IGNORE",r.PROMPT="PROMPT",r.FAIL_PROMPT="FAIL_PROMPT",r.FAIL_ERROR="FAIL_ERROR",r}({}),ni=function(r){return r.Invalid="Invalid homeserver discovery response",r.GenericFailure="Failed to get autodiscovery configuration from server",r.InvalidHsBaseUrl="Invalid base_url for m.homeserver",r.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",r.InvalidIsBaseUrl="Invalid base_url for m.identity_server",r.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",r.InvalidIs="Invalid identity server discovery response",r.MissingWellknown="No .well-known JSON file found",r.InvalidJson="Invalid JSON",r.UnsupportedHomeserverSpecVersion="The homeserver does not meet the version requirements",r}({});class Ke{static fromDiscoveryConfig(e){var t=this;return _(function*(){var n,i={"m.homeserver":{state:Ke.FAIL_ERROR,error:Ke.ERROR_INVALID,base_url:null},"m.identity_server":{state:Ke.PROMPT,error:null,base_url:null}};if(!(e!=null&&e["m.homeserver"]))return S.error("No m.homeserver key in config"),i["m.homeserver"].state=Ke.FAIL_PROMPT,i["m.homeserver"].error=Ke.ERROR_INVALID,Promise.resolve(i);if(!e["m.homeserver"].base_url)return S.error("No m.homeserver base_url in config"),i["m.homeserver"].state=Ke.FAIL_PROMPT,i["m.homeserver"].error=Ke.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var o=t.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!o)return S.error("Invalid base_url for m.homeserver"),i["m.homeserver"].error=Ke.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var s=yield t.fetchWellKnownObject("".concat(o,"/_matrix/client/versions"));if(!s||!Array.isArray((n=s.raw)===null||n===void 0?void 0:n.versions))return S.error("Invalid /versions response"),i["m.homeserver"].error=Ke.ERROR_INVALID_HOMESERVER,i["m.homeserver"].base_url=o,Promise.resolve(i);var a=new Set(s.raw.versions),l=!1;for(var c of rv)if(a.has(c)){l=!0;break}if(!l)return S.error("Homeserver does not meet version requirements"),i["m.homeserver"].error=Ke.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION,i["m.homeserver"].base_url=o,Promise.resolve(i);i["m.homeserver"]={state:Ke.SUCCESS,error:null,base_url:o};var u="";if(e["m.identity_server"]){var d={"m.homeserver":i["m.homeserver"],"m.identity_server":{state:Ke.FAIL_PROMPT,error:Ke.ERROR_INVALID_IS,base_url:null}};if(u=t.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!u)return S.error("Invalid base_url for m.identity_server"),d["m.identity_server"].error=Ke.ERROR_INVALID_IS_BASE_URL,Promise.resolve(d);var f=yield t.fetchWellKnownObject("".concat(u,"/_matrix/identity/v2"));if(!(f!=null&&f.raw)||f.action!==Dn.SUCCESS)return S.error("Invalid /v2 response"),d["m.identity_server"].error=Ke.ERROR_INVALID_IDENTITY_SERVER,d["m.identity_server"].base_url=u,Promise.resolve(d)}return u&&u.toString().length>0&&(i["m.identity_server"]={state:Ke.SUCCESS,error:null,base_url:u}),Object.keys(e).forEach(p=>{if(p==="m.homeserver"||p==="m.identity_server"){var h=["error","state","base_url"];for(var m of Object.keys(e[p]))h.includes(m)||(i[p][m]=e[p][m])}else i[p]=e[p]}),Promise.resolve(i)})()}static findClientConfig(e){var t=this;return _(function*(){if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");var n={"m.homeserver":{state:Ke.FAIL_ERROR,error:Ke.ERROR_INVALID,base_url:null},"m.identity_server":{state:Ke.PROMPT,error:null,base_url:null}},i=e.includes("://")?e:"https://".concat(e),o=yield t.fetchWellKnownObject("".concat(i,"/.well-known/matrix/client"));return!o||o.action!==Dn.SUCCESS?(S.error("No response or error when parsing .well-known"),o.reason&&S.error(o.reason),o.action===Dn.IGNORE?n["m.homeserver"]={state:Ke.PROMPT,error:null,base_url:null}:(n["m.homeserver"].state=Ke.FAIL_PROMPT,n["m.homeserver"].error=Ke.ERROR_INVALID),Promise.resolve(n)):Ke.fromDiscoveryConfig(o.raw)})()}static getRawClientConfig(e){var t=this;return _(function*(){var n;if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");var i=yield t.fetchWellKnownObject("https://".concat(e,"/.well-known/matrix/client"));return i?(n=i.raw)!==null&&n!==void 0?n:{}:{}})()}static sanitizeWellKnownUrl(e){if(!e)return!1;try{var t,n;try{n=new URL(e)}catch(a){S.error("Could not parse url",a)}if(!((t=n)!==null&&t!==void 0&&t.hostname)||n.protocol!=="http:"&&n.protocol!=="https:")return!1;var i=n.port?":".concat(n.port):"",o=n.pathname?n.pathname:"",s="".concat(n.protocol,"//").concat(n.hostname).concat(i).concat(o);return s.endsWith("/")&&(s=s.substring(0,s.length-1)),s}catch(a){return S.error(a),!1}}static fetch(e,t){return this.fetchFn?this.fetchFn(e,t):globalThis.fetch(e,t)}static setFetchFn(e){Ke.fetchFn=e}static fetchWellKnownObject(e){return _(function*(){var t;try{if(t=yield Ke.fetch(e,{method:Z.Get,signal:hm(5e3)}),t.status===404)return{raw:{},action:Dn.IGNORE,reason:Ke.ERROR_MISSING_WELLKNOWN};if(!t.ok)return{raw:{},action:Dn.FAIL_PROMPT,reason:"General failure"}}catch(s){var n=s,i="";return typeof n=="object"&&(i=n==null?void 0:n.message),{error:n,raw:{},action:Dn.FAIL_PROMPT,reason:i||"General failure"}}try{return{raw:yield t.json(),action:Dn.SUCCESS}}catch(s){var o=s;return{error:o,raw:{},action:Dn.FAIL_PROMPT,reason:(o==null?void 0:o.name)==="SyntaxError"?Ke.ERROR_INVALID_JSON:Ke.ERROR_INVALID}}})()}}v(Ke,"ERROR_INVALID",ni.Invalid);v(Ke,"ERROR_GENERIC_FAILURE",ni.GenericFailure);v(Ke,"ERROR_INVALID_HS_BASE_URL",ni.InvalidHsBaseUrl);v(Ke,"ERROR_INVALID_HOMESERVER",ni.InvalidHomeserver);v(Ke,"ERROR_INVALID_IS_BASE_URL",ni.InvalidIsBaseUrl);v(Ke,"ERROR_INVALID_IDENTITY_SERVER",ni.InvalidIdentityServer);v(Ke,"ERROR_INVALID_IS",ni.InvalidIs);v(Ke,"ERROR_MISSING_WELLKNOWN",ni.MissingWellknown);v(Ke,"ERROR_INVALID_JSON",ni.InvalidJson);v(Ke,"ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION",ni.UnsupportedHomeserverSpecVersion);v(Ke,"ALL_ERRORS",Object.keys(ni));v(Ke,"FAIL_ERROR",Dn.FAIL_ERROR);v(Ke,"FAIL_PROMPT",Dn.FAIL_PROMPT);v(Ke,"PROMPT",Dn.PROMPT);v(Ke,"SUCCESS",Dn.SUCCESS);v(Ke,"fetchFn",void 0);var jC=/[\\\"\x00-\x1F]/g,Bo={};for(var dh=0;dh<32;++dh)Bo[String.fromCharCode(dh)]="\\U"+("0000"+dh.toString(16)).slice(-4).toUpperCase();Bo["\b"]="\\b";Bo[" "]="\\t";Bo[`
283
+ `]="\\n";Bo["\f"]="\\f";Bo["\r"]="\\r";Bo['"']='\\"';Bo["\\"]="\\\\";function ZD(r){return jC.lastIndex=0,r.replace(jC,function(e){return Bo[e]})}function Ew(r){switch(typeof r){case"string":return'"'+ZD(r)+'"';case"number":return isFinite(r)?r:"null";case"boolean":return r;case"object":return r===null?"null":Array.isArray(r)?Wz(r):qz(r);default:throw new Error("Cannot stringify: "+typeof r)}}function Wz(r){for(var e="[",t="",n=0;n<r.length;++n)t+=e,e=",",t+=Ew(r[n]);return e!=","?"[]":t+"]"}function qz(r){var e="{",t="",n=Object.keys(r);n.sort();for(var i=0;i<n.length;++i){var o=n[i];t+=e+'"'+ZD(o)+'":',e=",",t+=Ew(r[o])}return e!=","?"{}":t+"}"}var Gz={stringify:Ew};const ko=Ka(Gz);function FC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Hz(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?FC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):FC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var ym=function(r){return r.Olm="m.olm.v1.curve25519-aes-sha2",r.Megolm="m.megolm.v1.aes-sha2",r.MegolmBackup="m.megolm_backup.v1.curve25519-aes-sha2",r}(ym||{}),wr=ym.Olm,bn=ym.Megolm,zz=ym.MegolmBackup;function Ns(r,e,t,n,i,o,s){return Ab.apply(this,arguments)}function Ab(){return Ab=_(function*(r,e,t,n,i,o,s){var a=o.getIdentityKey(),l=yield n.getSessionIdForDevice(a);if(l===null){S.log("[olmlib.encryptMessageForDevice] Unable to find Olm session for device "+"".concat(i,":").concat(o.deviceId));return}S.log("[olmlib.encryptMessageForDevice] Using Olm session ".concat(l," for device ")+"".concat(i,":").concat(o.deviceId));var c=Hz({sender:e,sender_device:t,keys:{ed25519:n.deviceEd25519Key},recipient:i,recipient_keys:{ed25519:o.getFingerprint()}},s);r[a]=yield n.encryptMessage(a,l,JSON.stringify(c))}),Ab.apply(this,arguments)}function eN(r,e,t){return Db.apply(this,arguments)}function Db(){return Db=_(function*(r,e,t){var n=new qt(()=>[]),i=new qt(()=>new Map),o=[],s=function*(u){var d=function*(h){var m=h.deviceId,w=h.getIdentityKey();o.push(_(function*(){var g=yield r.getSessionIdForDevice(w,!0);g===null?n.getOrCreate(u).push(h):i.getOrCreate(u).set(m,{device:h,sessionId:g})})())};for(var f of l)yield*d(f)};for(var[a,l]of Object.entries(t))yield*s(a);return yield Promise.all(o),[n,i]}),Db.apply(this,arguments)}function Io(r,e,t){return Nb.apply(this,arguments)}function Nb(){return Nb=_(function*(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0,o=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:S,a=[],l=new Map,c=new Map;for(var u of t.values()){var d=function*(){var re=f.getIdentityKey();if(re===r.deviceCurve25519Key)return 1;r.sessionsInProgress[re]||(r.sessionsInProgress[re]=new Promise(ae=>{c.set(re,q=>{delete r.sessionsInProgress[re],ae(q)})}))};for(var f of u)yield*d()}for(var[p,h]of t){var m=new Map;l.set(p,m);for(var w of h){var g=w.deviceId,b=w.getIdentityKey();if(b===r.deviceCurve25519Key){s.info("Attempted to start session with ourself! Ignoring"),m.set(g,{device:w,sessionId:null});continue}var R="for ".concat(b," (").concat(p,":").concat(g,")"),k=yield r.getSessionIdForDevice(b,!!c.get(b),s),O=c.get(b);k!==null&&O&&O(),(k===null||n)&&(n?s.info("Forcing new Olm session ".concat(R)):s.info("Making new Olm session ".concat(R)),a.push([p,g])),m.set(g,{device:w,sessionId:k})}}if(a.length===0)return l;var T="signed_curve25519",x,C="one-time keys for ".concat(a.length," devices");try{s.debug("Claiming ".concat(C)),x=yield e.claimOneTimeKeys(a,T,i),s.debug("Claimed ".concat(C))}catch(oe){for(var N of c.values())N();throw s.debug("Failed to claim ".concat(C),oe,a),oe}o&&"failures"in x&&o.push(...Object.keys(x.failures));var F=x.one_time_keys||{},H=[],ie=function*(re){var ae=F[re]||{},q=function*(){var Y,le=Q.deviceId,B=Q.getIdentityKey();if(B===r.deviceCurve25519Key||(Y=l.get(re))!==null&&Y!==void 0&&(Y=Y.get(le))!==null&&Y!==void 0&&Y.sessionId&&!n)return 0;var W=ae[le]||{},A=null;for(var D in W)D.indexOf(T+":")===0&&(A=W[D]);if(!A){var P;return s.warn("No one-time keys (alg=".concat(T,") ")+"for device ".concat(re,":").concat(le)),(P=c.get(B))===null||P===void 0||P(),0}H.push(Yz(r,A,re,Q).then(M=>{var I,j;(I=c.get(B))===null||I===void 0||I(M??void 0);var U=(j=l.get(re))===null||j===void 0?void 0:j.get(le);U&&(U.sessionId=M)},M=>{var I;throw(I=c.get(B))===null||I===void 0||I(),M}))},z;for(var Q of X)z=yield*q()};for(var[$,X]of t)yield*ie($);return C="Olm sessions for ".concat(H.length," devices"),s.debug("Starting ".concat(C)),yield Promise.all(H),s.debug("Started ".concat(C)),l}),Nb.apply(this,arguments)}function Yz(r,e,t,n){return Lb.apply(this,arguments)}function Lb(){return Lb=_(function*(r,e,t,n){var i=n.deviceId;try{yield Sc(r,e,t,i,n.getFingerprint())}catch(s){return S.error("Unable to verify signature on one-time key for device "+t+":"+i+":",s),null}var o;try{o=yield r.createOutboundSession(n.getIdentityKey(),e.key)}catch(s){return S.error("Error starting olm session with device "+t+":"+i+": "+s),null}return S.log("Started new olm sessionid "+o+" for device "+t+":"+i),o}),Lb.apply(this,arguments)}function Sc(r,e,t,n,i){return Ub.apply(this,arguments)}function Ub(){return Ub=_(function*(r,e,t,n,i){var o="ed25519:"+n,s=e.signatures||{},a=s[t]||{},l=a[o];if(!l)throw Error("No signature");var c=Object.assign({},e);"unsigned"in c&&delete c.unsigned,delete c.signatures;var u=ko.stringify(c);r.verifySignature(i,u,l)}),Ub.apply(this,arguments)}function Hh(r,e,t,n){var i=!1;if(e instanceof Uint8Array){var o=new globalThis.Olm.PkSigning;n=o.init_with_seed(e),e=o,i=!0}var s=r.signatures||{};delete r.signatures;var a=r.unsigned;r.unsigned&&delete r.unsigned;try{var l=s[t]||{};return s[t]=l,l["ed25519:"+n]=e.sign(ko.stringify(r))}finally{r.signatures=s,a&&(r.unsigned=a),i&&e.free()}}function Sl(r,e,t){var n="ed25519:"+e;if(!(r.signatures&&r.signatures[t]&&r.signatures[t][n]))throw new Error("No signature");var i=r.signatures[t][n],o=new globalThis.Olm.Utility,s=r.signatures;delete r.signatures;var a=r.unsigned;r.unsigned&&delete r.unsigned;try{o.ed25519_verify(e,ko.stringify(r),i)}finally{r.signatures=s,a&&(r.unsigned=a),o.free()}}function ww(r){return r.getSenderKey()?r.getWireType()!==V.RoomMessageEncrypted||!["m.olm.v1.curve25519-aes-sha2"].includes(r.getWireContent().algorithm)?(S.error("Event was not encrypted using an appropriate algorithm"),!1):!0:(S.error("Event has no sender key (not encrypted?)"),!1)}const Jz=Object.freeze(Object.defineProperty({__proto__:null,MEGOLM_ALGORITHM:bn,MEGOLM_BACKUP_ALGORITHM:zz,OLM_ALGORITHM:wr,encryptMessageForDevice:Ns,ensureOlmSessionsForDevices:Io,getExistingOlmSessions:eN,isOlmEncrypted:ww,pkSign:Hh,pkVerify:Sl,verifySignature:Sc},Symbol.toStringTag,{value:"Module"}));var jb=function(r){return r.IS="SERVICE_TYPE_IS",r.IM="SERVICE_TYPE_IM",r}({}),Tn="crypto.",BC=Tn+"migration",Qg=Tn+"account",KC=Tn+"cross_signing_keys",VC=Tn+"notified_error_devices",$C=Tn+"device_data",ts=Tn+"inboundgroupsessions/",Xz=Tn+"inboundgroupsessions.withheld/",Qz=Tn+"rooms/",Zs=Tn+"sessionsneedingbackup";function ea(r){return Tn+"sessions/"+r}function WC(r){return Tn+"session.problems/"+r}function fh(r,e){return ts+r+"/"+e}function qC(r,e){return Xz+r+"/"+e}function GC(r){return Qz+r}class Sm extends cm{static exists(e){for(var t=e.length,n=0;n<t;n++){var i;if((i=e.key(n))!==null&&i!==void 0&&i.startsWith(Tn))return!0}return!1}constructor(e){super(),this.store=e}containsData(){var e=this;return _(function*(){return Sm.exists(e.store)})()}getMigrationState(){var e=this;return _(function*(){var t;return(t=zt(e.store,BC))!==null&&t!==void 0?t:mc.NOT_STARTED})()}setMigrationState(e){var t=this;return _(function*(){hn(t.store,BC,e)})()}countEndToEndSessions(e,t){for(var n=0,i=0;i<this.store.length;++i){var o=this.store.key(i);if(o!=null&&o.startsWith(ea(""))){var s=zt(this.store,o);n+=Object.keys(s??{}).length}}t(n)}_getEndToEndSessions(e){var t=zt(this.store,ea(e)),n={};for(var[i,o]of Object.entries(t||{}))typeof o=="string"?n[i]={session:o}:n[i]=o;return n}getEndToEndSession(e,t,n,i){var o=this._getEndToEndSessions(e);i(o[t]||{})}getEndToEndSessions(e,t,n){n(this._getEndToEndSessions(e)||{})}getAllEndToEndSessions(e,t){for(var n=0;n<this.store.length;++n){var i;if((i=this.store.key(n))!==null&&i!==void 0&&i.startsWith(ea(""))){var o=this.store.key(n).split("/")[1];for(var s of Object.values(this._getEndToEndSessions(o)))t(s)}}}storeEndToEndSession(e,t,n,i){var o=this._getEndToEndSessions(e)||{};o[t]=n,hn(this.store,ea(e),o)}storeEndToEndSessionProblem(e,t,n){var i=this;return _(function*(){var o=WC(e),s=zt(i.store,o)||[];s.push({type:t,fixed:n,time:Date.now()}),s.sort((a,l)=>a.time-l.time),hn(i.store,o,s)})()}getEndToEndSessionProblem(e,t){var n=this;return _(function*(){var i=WC(e),o=zt(n.store,i)||[];if(!o.length)return null;var s=o[o.length-1];for(var a of o)if(a.time>t)return Object.assign({},a,{fixed:s.fixed});return s.fixed?null:s})()}filterOutNotifiedErrorDevices(e){var t=this;return _(function*(){var n=zt(t.store,VC)||{},i=[];for(var o of e){var{userId:s,deviceInfo:a}=o;s in n?a.deviceId in n[s]||(i.push(o),Xi(n[s],a.deviceId,!0)):(i.push(o),Xi(n,s,{[a.deviceId]:!0}))}return hn(t.store,VC,n),i})()}getEndToEndSessionsBatch(){var e=this;return _(function*(){for(var t=[],n=0;n<e.store.length;++n){var i;if((i=e.store.key(n))!==null&&i!==void 0&&i.startsWith(ea(""))){var o=e.store.key(n).split("/")[1];for(var s of Object.values(e._getEndToEndSessions(o)))if(t.push(s),t.length>=gc)return t}}return t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return _(function*(){for(var{deviceKey:n,sessionId:i}of e){var o=t._getEndToEndSessions(n)||{};delete o[i],Object.keys(o).length===0?t.store.removeItem(ea(n)):hn(t.store,ea(n),o)}})()}getEndToEndInboundGroupSession(e,t,n,i){i(zt(this.store,fh(e,t)),zt(this.store,qC(e,t)))}getAllEndToEndInboundGroupSessions(e,t){for(var n=0;n<this.store.length;++n){var i=this.store.key(n);i!=null&&i.startsWith(ts)&&t({senderKey:i.slice(ts.length,ts.length+43),sessionId:i.slice(ts.length+44),sessionData:zt(this.store,i)})}t(null)}addEndToEndInboundGroupSession(e,t,n,i){var o=zt(this.store,fh(e,t));o||this.storeEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSession(e,t,n,i){hn(this.store,fh(e,t),n)}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){hn(this.store,qC(e,t),n)}countEndToEndInboundGroupSessions(){var e=this;return _(function*(){for(var t=0,n=0;n<e.store.length;++n){var i=e.store.key(n);i!=null&&i.startsWith(ts)&&(t+=1)}return t})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return _(function*(){for(var t=zt(e.store,Zs)||{},n=[],i=0;i<e.store.length;++i){var o=e.store.key(i);if(o!=null&&o.startsWith(ts)){var s=o.slice(ts.length);if(n.push({senderKey:s.slice(0,43),sessionId:s.slice(44),sessionData:zt(e.store,o),needsBackup:s in t}),n.length>=gc)return n}}return n.length===0?null:n})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return _(function*(){for(var{senderKey:n,sessionId:i}of e){var o=fh(n,i);t.store.removeItem(o)}})()}getEndToEndDeviceData(e,t){t(zt(this.store,$C))}storeEndToEndDeviceData(e,t){hn(this.store,$C,e)}storeEndToEndRoom(e,t,n){hn(this.store,GC(e),t)}getEndToEndRooms(e,t){for(var n={},i=GC(""),o=0;o<this.store.length;++o){var s=this.store.key(o);if(s!=null&&s.startsWith(i)){var a=s.slice(i.length);n[a]=zt(this.store,s)}}t(n)}getSessionsNeedingBackup(e){var t=this,n=zt(this.store,Zs)||{},i=[],o=function(){if(Object.prototype.hasOwnProperty.call(n,s)){var l=s.slice(0,43),c=s.slice(44);if(t.getEndToEndInboundGroupSession(l,c,null,u=>{i.push({senderKey:l,sessionId:c,sessionData:u})}),e&&i.length>=e)return 1}};for(var s in n)if(o())break;return Promise.resolve(i)}countSessionsNeedingBackup(){var e=zt(this.store,Zs)||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){var t=zt(this.store,Zs)||{};for(var n of e)delete t[n.senderKey+"/"+n.sessionId];return hn(this.store,Zs,t),Promise.resolve()}markSessionsNeedingBackup(e){var t=zt(this.store,Zs)||{};for(var n of e)t[n.senderKey+"/"+n.sessionId]=!0;return hn(this.store,Zs,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(Qg),Promise.resolve()}getAccount(e,t){var n=zt(this.store,Qg);t(n)}storeAccount(e,t){hn(this.store,Qg,t)}getCrossSigningKeys(e,t){var n=zt(this.store,KC);t(n)}getSecretStorePrivateKey(e,t,n){var i=zt(this.store,Tn+"ssss_cache.".concat(n));t(i)}storeCrossSigningKeys(e,t){hn(this.store,KC,t)}storeSecretStorePrivateKey(e,t,n){hn(this.store,Tn+"ssss_cache.".concat(t),n)}doTxn(e,t,n){return Promise.resolve(n(null))}}function zt(r,e){try{return JSON.parse(r.getItem(e))}catch(t){S.log("Error: Failed to get key %s: %s",e,t.message),S.log(t.stack)}return null}function hn(r,e,t){r.setItem(e,JSON.stringify(t))}class Zz{constructor(e){this.db=e,v(this,"nextTxnId",0),e.onversionchange=()=>{S.log("versionchange for indexeddb ".concat(this.db.name,": closing")),e.close()}}containsData(){return _(function*(){throw Error("Not implemented for Backend")})()}startup(){var e=this;return _(function*(){return e})()}deleteAllData(){return _(function*(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")})()}getMigrationState(){var e=this;return _(function*(){var t=mc.NOT_STARTED;return yield e.doTxn("readonly",[be.STORE_ACCOUNT],n=>{var i=n.objectStore(be.STORE_ACCOUNT),o=i.get(pb);o.onsuccess=()=>{var s;t=(s=o.result)!==null&&s!==void 0?s:mc.NOT_STARTED}}),t})()}setMigrationState(e){var t=this;return _(function*(){yield t.doTxn("readwrite",[be.STORE_ACCOUNT],n=>{var i=n.objectStore(be.STORE_ACCOUNT);i.put(e,pb)})})()}getOrAddOutgoingRoomKeyRequest(e){var t=e.requestBody;return new Promise((n,i)=>{var o=this.db.transaction("outgoingRoomKeyRequests","readwrite");o.onerror=i,this._getOutgoingRoomKeyRequest(o,t,s=>{if(s){S.log("already have key request outstanding for "+"".concat(t.room_id," / ").concat(t.session_id,": ")+"not sending another"),n(s);return}S.log("enqueueing key request for ".concat(t.room_id," / ")+t.session_id),o.oncomplete=()=>{n(e)};var a=o.objectStore("outgoingRoomKeyRequests");a.add(e)})})}getOutgoingRoomKeyRequest(e){return new Promise((t,n)=>{var i=this.db.transaction("outgoingRoomKeyRequests","readonly");i.onerror=n,this._getOutgoingRoomKeyRequest(i,e,o=>{t(o)})})}_getOutgoingRoomKeyRequest(e,t,n){var i=e.objectStore("outgoingRoomKeyRequests"),o=i.index("session"),s=o.openCursor([t.room_id,t.session_id]);s.onsuccess=()=>{var a=s.result;if(!a){n(null);return}var l=a.value;if(Fa(l.requestBody,t)){n(l);return}a.continue()}}getOutgoingRoomKeyRequestByState(e){if(e.length===0)return Promise.resolve(null);var t=0,n;function i(){var c=this.result;if(c){n=c.value;return}if(t++,!(t>=e.length)){var u=e[t],d=this.source.openCursor(u);d.onsuccess=i}}var o=this.db.transaction("outgoingRoomKeyRequests","readonly"),s=o.objectStore("outgoingRoomKeyRequests"),a=e[t],l=s.index("state").openCursor(a);return l.onsuccess=i,ta(o).then(()=>n)}getAllOutgoingRoomKeyRequestsByState(e){return new Promise((t,n)=>{var i=this.db.transaction("outgoingRoomKeyRequests","readonly"),o=i.objectStore("outgoingRoomKeyRequests"),s=o.index("state"),a=s.getAll(e);a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error)})}getOutgoingRoomKeyRequestsByTarget(e,t,n){var i=0,o=[];function s(){var d=this.result;if(d){var f=d.value;f.recipients.some(m=>m.userId===e&&m.deviceId===t)&&o.push(f),d.continue()}else{if(i++,i>=n.length)return;var p=n[i],h=this.source.openCursor(p);h.onsuccess=s}}var a=this.db.transaction("outgoingRoomKeyRequests","readonly"),l=a.objectStore("outgoingRoomKeyRequests"),c=n[i],u=l.index("state").openCursor(c);return u.onsuccess=s,ta(a).then(()=>o)}updateOutgoingRoomKeyRequest(e,t,n){var i=null;function o(){var l=this.result;if(l){var c=l.value;if(c.state!=t){S.warn("Cannot update room key request from ".concat(t," ")+"as it was already updated to ".concat(c.state));return}Object.assign(c,n),l.update(c),i=c}}var s=this.db.transaction("outgoingRoomKeyRequests","readwrite"),a=s.objectStore("outgoingRoomKeyRequests").openCursor(e);return a.onsuccess=o,ta(s).then(()=>i)}deleteOutgoingRoomKeyRequest(e,t){var n=this.db.transaction("outgoingRoomKeyRequests","readwrite"),i=n.objectStore("outgoingRoomKeyRequests").openCursor(e);return i.onsuccess=()=>{var o=i.result;if(o){var s=o.value;if(s.state!=t){S.warn("Cannot delete room key request in state ".concat(s.state," ")+"(expected ".concat(t,")"));return}o.delete()}},ta(n)}getAccount(e,t){var n=e.objectStore("account"),i=n.get("-");i.onsuccess=function(){try{t(i.result||null)}catch(o){yr(e,o)}}}storeAccount(e,t){var n=e.objectStore("account");n.put(t,"-")}getCrossSigningKeys(e,t){var n=e.objectStore("account"),i=n.get("crossSigningKeys");i.onsuccess=function(){try{t(i.result||null)}catch(o){yr(e,o)}}}getSecretStorePrivateKey(e,t,n){var i=e.objectStore("account"),o=i.get("ssss_cache:".concat(n));o.onsuccess=function(){try{t(o.result||null)}catch(s){yr(e,s)}}}storeCrossSigningKeys(e,t){var n=e.objectStore("account");n.put(t,"crossSigningKeys")}storeSecretStorePrivateKey(e,t,n){var i=e.objectStore("account");i.put(n,"ssss_cache:".concat(t))}countEndToEndSessions(e,t){var n=e.objectStore("sessions"),i=n.count();i.onsuccess=function(){try{t(i.result)}catch(o){yr(e,o)}}}getEndToEndSessions(e,t,n){var i=t.objectStore("sessions"),o=i.index("deviceKey"),s=o.openCursor(e),a={};s.onsuccess=function(){var l=s.result;if(l)a[l.value.sessionId]={session:l.value.session,lastReceivedMessageTs:l.value.lastReceivedMessageTs},l.continue();else try{n(a)}catch(c){yr(t,c)}}}getEndToEndSession(e,t,n,i){var o=n.objectStore("sessions"),s=o.get([e,t]);s.onsuccess=function(){try{s.result?i({session:s.result.session,lastReceivedMessageTs:s.result.lastReceivedMessageTs}):i(null)}catch(a){yr(n,a)}}}getAllEndToEndSessions(e,t){var n=e.objectStore("sessions"),i=n.openCursor();i.onsuccess=function(){try{var o=i.result;o?(t(o.value),o.continue()):t(null)}catch(s){yr(e,s)}}}storeEndToEndSession(e,t,n,i){var o=i.objectStore("sessions");o.put({deviceKey:e,sessionId:t,session:n.session,lastReceivedMessageTs:n.lastReceivedMessageTs})}storeEndToEndSessionProblem(e,t,n){var i=this;return _(function*(){var o=i.db.transaction("session_problems","readwrite"),s=o.objectStore("session_problems");s.put({deviceKey:e,type:t,fixed:n,time:Date.now()}),yield ta(o)})()}getEndToEndSessionProblem(e,t){var n=this;return _(function*(){var i=null,o=n.db.transaction("session_problems","readwrite"),s=o.objectStore("session_problems"),a=s.index("deviceKey"),l=a.getAll(e);return l.onsuccess=()=>{var c=l.result;if(!c.length){i=null;return}c.sort((f,p)=>f.time-p.time);var u=c[c.length-1];for(var d of c)if(d.time>t){i=Object.assign({},d,{fixed:u.fixed});return}u.fixed?i=null:i=u},yield ta(o),i})()}filterOutNotifiedErrorDevices(e){var t=this;return _(function*(){var n=t.db.transaction("notified_error_devices","readwrite"),i=n.objectStore("notified_error_devices"),o=[];return yield Promise.all(e.map(s=>new Promise(a=>{var{userId:l,deviceInfo:c}=s,u=i.get([l,c.deviceId]);u.onsuccess=function(){u.result||(i.put({userId:l,deviceId:c.deviceId}),o.push(s)),a()}}))),o})()}getEndToEndSessionsBatch(){var e=this;return _(function*(){var t=[];return yield e.doTxn("readonly",[be.STORE_SESSIONS],n=>{var i=n.objectStore(be.STORE_SESSIONS),o=i.openCursor();o.onsuccess=function(){try{var s=o.result;s&&(t.push(s.value),t.length<gc&&s.continue())}catch(a){yr(n,a)}}}),t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return _(function*(){yield t.doTxn("readwrite",[be.STORE_SESSIONS],function(){var n=_(function*(i){try{var o=i.objectStore(be.STORE_SESSIONS),s=function*(){var u=o.delete([a,l]);yield new Promise(d=>{u.onsuccess=d})};for(var{deviceKey:a,sessionId:l}of e)yield*s()}catch(c){yr(i,c)}});return function(i){return n.apply(this,arguments)}}())})()}getEndToEndInboundGroupSession(e,t,n,i){var o=!1,s=!1,a=n.objectStore("inbound_group_sessions"),l=a.get([e,t]);l.onsuccess=function(){try{l.result?o=l.result.session:o=null,s!==!1&&i(o,s)}catch(d){yr(n,d)}};var c=n.objectStore("inbound_group_sessions_withheld"),u=c.get([e,t]);u.onsuccess=function(){try{u.result?s=u.result.session:s=null,o!==!1&&i(o,s)}catch(d){yr(n,d)}}}getAllEndToEndInboundGroupSessions(e,t){var n=e.objectStore("inbound_group_sessions"),i=n.openCursor();i.onsuccess=function(){var o=i.result;if(o){try{t({senderKey:o.value.senderCurve25519Key,sessionId:o.value.sessionId,sessionData:o.value.session})}catch(s){yr(e,s)}o.continue()}else try{t(null)}catch(s){yr(e,s)}}}addEndToEndInboundGroupSession(e,t,n,i){var o=i.objectStore("inbound_group_sessions"),s=o.add({senderCurve25519Key:e,sessionId:t,session:n});s.onerror=a=>{var l;((l=s.error)===null||l===void 0?void 0:l.name)==="ConstraintError"?(a.stopPropagation(),a.preventDefault(),S.log("Ignoring duplicate inbound group session: "+e+" / "+t)):yr(i,new Error("Failed to add inbound group session: "+s.error))}}storeEndToEndInboundGroupSession(e,t,n,i){var o=i.objectStore("inbound_group_sessions");o.put({senderCurve25519Key:e,sessionId:t,session:n})}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){var o=i.objectStore("inbound_group_sessions_withheld");o.put({senderCurve25519Key:e,sessionId:t,session:n})}countEndToEndInboundGroupSessions(){var e=this;return _(function*(){var t=0;return yield e.doTxn("readonly",[be.STORE_INBOUND_GROUP_SESSIONS],n=>{var i=n.objectStore(be.STORE_INBOUND_GROUP_SESSIONS),o=i.count();o.onsuccess=()=>{t=o.result}}),t})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return _(function*(){var t=[];return yield e.doTxn("readonly",[be.STORE_INBOUND_GROUP_SESSIONS,be.STORE_BACKUP],n=>{var i=n.objectStore(be.STORE_INBOUND_GROUP_SESSIONS),o=n.objectStore(be.STORE_BACKUP),s=i.openCursor();s.onsuccess=function(){try{var a=s.result;if(a){var l=o.get(a.key);l.onsuccess=()=>{t.push({senderKey:a.value.senderCurve25519Key,sessionId:a.value.sessionId,sessionData:a.value.session,needsBackup:l.result!==void 0}),t.length<gc&&a.continue()}}}catch(c){yr(n,c)}}}),t.length===0?null:t})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return _(function*(){yield t.doTxn("readwrite",[be.STORE_INBOUND_GROUP_SESSIONS],function(){var n=_(function*(i){try{var o=i.objectStore(be.STORE_INBOUND_GROUP_SESSIONS),s=function*(){var u=o.delete([a,l]);yield new Promise(d=>{u.onsuccess=d})};for(var{senderKey:a,sessionId:l}of e)yield*s()}catch(c){yr(i,c)}});return function(i){return n.apply(this,arguments)}}())})()}getEndToEndDeviceData(e,t){var n=e.objectStore("device_data"),i=n.get("-");i.onsuccess=function(){try{t(i.result||null)}catch(o){yr(e,o)}}}storeEndToEndDeviceData(e,t){var n=t.objectStore("device_data");n.put(e,"-")}storeEndToEndRoom(e,t,n){var i=n.objectStore("rooms");i.put(t,e)}getEndToEndRooms(e,t){var n={},i=e.objectStore("rooms"),o=i.openCursor();o.onsuccess=function(){var s=o.result;if(s)n[s.key]=s.value,s.continue();else try{t(n)}catch(a){yr(e,a)}}}getSessionsNeedingBackup(e){return new Promise((t,n)=>{var i=[],o=this.db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");o.onerror=n,o.oncomplete=function(){t(i)};var s=o.objectStore("sessions_needing_backup"),a=o.objectStore("inbound_group_sessions"),l=s.openCursor();l.onsuccess=function(){var c=l.result;if(c){var u=a.get(c.key);u.onsuccess=function(){i.push({senderKey:u.result.senderCurve25519Key,sessionId:u.result.sessionId,sessionData:u.result.session})},(!e||i.length<e)&&c.continue()}}})}countSessionsNeedingBackup(e){e||(e=this.db.transaction("sessions_needing_backup","readonly"));var t=e.objectStore("sessions_needing_backup");return new Promise((n,i)=>{var o=t.count();o.onerror=i,o.onsuccess=()=>n(o.result)})}unmarkSessionsNeedingBackup(e,t){var n=this;return _(function*(){t||(t=n.db.transaction("sessions_needing_backup","readwrite"));var i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map(o=>new Promise((s,a)=>{var l=i.delete([o.senderKey,o.sessionId]);l.onsuccess=s,l.onerror=a})))})()}markSessionsNeedingBackup(e,t){var n=this;return _(function*(){t||(t=n.db.transaction("sessions_needing_backup","readwrite"));var i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map(o=>new Promise((s,a)=>{var l=i.put({senderCurve25519Key:o.senderKey,sessionId:o.sessionId});l.onsuccess=s,l.onerror=a})))})()}addSharedHistoryInboundGroupSession(e,t,n,i){i||(i=this.db.transaction("shared_history_inbound_group_sessions","readwrite"));var o=i.objectStore("shared_history_inbound_group_sessions"),s=o.get([e]);s.onsuccess=()=>{var{sessions:a}=s.result||{sessions:[]};a.push([t,n]),o.put({roomId:e,sessions:a})}}getSharedHistoryInboundGroupSessions(e,t){t||(t=this.db.transaction("shared_history_inbound_group_sessions","readonly"));var n=t.objectStore("shared_history_inbound_group_sessions"),i=n.get([e]);return new Promise((o,s)=>{i.onsuccess=()=>{var{sessions:a}=i.result||{sessions:[]};o(a)},i.onerror=s})}addParkedSharedHistory(e,t,n){n||(n=this.db.transaction("parked_shared_history","readwrite"));var i=n.objectStore("parked_shared_history"),o=i.get([e]);o.onsuccess=()=>{var{parked:s}=o.result||{parked:[]};s.push(t),i.put({roomId:e,parked:s})}}takeParkedSharedHistory(e,t){t||(t=this.db.transaction("parked_shared_history","readwrite"));var n=t.objectStore("parked_shared_history").openCursor(e);return new Promise((i,o)=>{n.onsuccess=()=>{var s=n.result;if(!s){i([]);return}var a=s.value;s.delete(),i(a)},n.onerror=o})}doTxn(e,t,n){var i=this.db.transaction(t,e),o=ta(i),s=n(i);return o.then(()=>s)}}var tN=[r=>{t8(r)},r=>{r.createObjectStore("account")},r=>{var e=r.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]});e.createIndex("deviceKey","deviceKey")},r=>{r.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},r=>{r.createObjectStore("device_data")},r=>{r.createObjectStore("rooms")},r=>{r.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},r=>{r.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},r=>{var e=r.createObjectStore("session_problems",{keyPath:["deviceKey","time"]});e.createIndex("deviceKey","deviceKey"),r.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},r=>{r.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},r=>{r.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}],rN=tN.length;function e8(r,e){S.log("Upgrading IndexedDBCryptoStore from version ".concat(e)+" to ".concat(rN)),tN.forEach((t,n)=>{e<=n&&t(r)})}function t8(r){var e=r.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});e.createIndex("session",["requestBody.room_id","requestBody.session_id"]),e.createIndex("state","state")}function yr(r,e){r._mx_abortexception=e;try{r.abort()}catch{}}function ta(r){return new Promise((e,t)=>{r.oncomplete=()=>{r._mx_abortexception!==void 0&&t(r._mx_abortexception),e(null)},r.onerror=n=>{r._mx_abortexception!==void 0?t(r._mx_abortexception):(S.log("Error performing indexeddb txn",n),t(r.error))},r.onabort=n=>{r._mx_abortexception!==void 0?t(r._mx_abortexception):(S.log("Error performing indexeddb txn",n),t(r.error))}})}var Tw=function(r){return r.TooNew="TOO_NEW",r}({});class Rw extends Error{constructor(e){var t="Crypto store is invalid because ".concat(e,", ")+"please stop the client, delete all data and start the client again";super(t),this.reason=e,this.name="InvalidCryptoStoreError"}}v(Rw,"TOO_NEW",Tw.TooNew);class Du extends Error{constructor(e,t){super(e),this.value=t}}class r8 extends Error{constructor(){super("MatrixClient has been stopped")}}function nN(r,e){return new Promise((t,n)=>{var i=!0,o=r.open(e);o.onupgradeneeded=()=>{i=!1},o.onblocked=()=>n(o.error),o.onsuccess=()=>{var s=o.result;s.close(),i||r.deleteDatabase(e),t(i)},o.onerror=()=>n(o.error)})}class be{static exists(e,t){return nN(e,t)}static existsAndIsNotMigrated(e,t){return new Promise((n,i)=>{var o=!0,s=e.open(t);s.onupgradeneeded=()=>{o=!1},s.onblocked=()=>i(s.error),s.onsuccess=()=>{var a=s.result;if(!o)a.close(),e.deleteDatabase(t),n(!1);else{var l=a.transaction([be.STORE_ACCOUNT],"readonly"),c=l.objectStore(be.STORE_ACCOUNT),u=c.get(pb);u.onsuccess=()=>{var d,f=(d=u.result)!==null&&d!==void 0?d:mc.NOT_STARTED;n(f===mc.NOT_STARTED)},u.onerror=()=>{i(u.error)},a.close()}},s.onerror=()=>i(s.error)})}constructor(e,t){this.indexedDB=e,this.dbName=t,v(this,"backendPromise",void 0),v(this,"backend",void 0)}containsData(){var e=this;return _(function*(){return be.exists(e.indexedDB,e.dbName)})()}startup(){return this.backendPromise?this.backendPromise:(this.backendPromise=new Promise((e,t)=>{if(!this.indexedDB){t(new Error("no indexeddb support available"));return}S.log("connecting to indexeddb ".concat(this.dbName));var n=this.indexedDB.open(this.dbName,rN);n.onupgradeneeded=i=>{var o=n.result,s=i.oldVersion;e8(o,s)},n.onblocked=()=>{S.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},n.onerror=i=>{S.log("Error connecting to indexeddb",i),t(n.error)},n.onsuccess=()=>{var i=n.result;S.log("connected to indexeddb ".concat(this.dbName)),e(new Zz(i))}}).then(e=>e.doTxn("readonly",[be.STORE_INBOUND_GROUP_SESSIONS,be.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],t=>{e.getEndToEndInboundGroupSession("","",t,()=>{})}).then(()=>e)).catch(e=>{if(e.name==="VersionError")throw S.warn("Crypto DB is too new for us to use!",e),new Rw(Tw.TooNew);S.warn("unable to connect to indexeddb ".concat(this.dbName)+": falling back to localStorage store: ".concat(e));try{return new Sm(globalThis.localStorage)}catch(t){return S.warn("unable to open localStorage: falling back to in-memory store: ".concat(t)),new cm}}).then(e=>(this.backend=e,e)),this.backendPromise)}deleteAllData(){return new Promise((e,t)=>{if(!this.indexedDB){t(new Error("no indexeddb support available"));return}S.log("Removing indexeddb instance: ".concat(this.dbName));var n=this.indexedDB.deleteDatabase(this.dbName);n.onblocked=()=>{S.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},n.onerror=i=>{S.log("Error deleting data from indexeddb",i),t(n.error)},n.onsuccess=()=>{S.log("Removed indexeddb instance: ".concat(this.dbName)),e()}}).catch(e=>{S.warn("unable to delete IndexedDBCryptoStore: ".concat(e))})}getMigrationState(){return this.backend.getMigrationState()}setMigrationState(e){return this.backend.setMigrationState(e)}getOrAddOutgoingRoomKeyRequest(e){return this.backend.getOrAddOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequest(e){return this.backend.getOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequestByState(e){return this.backend.getOutgoingRoomKeyRequestByState(e)}getAllOutgoingRoomKeyRequestsByState(e){return this.backend.getAllOutgoingRoomKeyRequestsByState(e)}getOutgoingRoomKeyRequestsByTarget(e,t,n){return this.backend.getOutgoingRoomKeyRequestsByTarget(e,t,n)}updateOutgoingRoomKeyRequest(e,t,n){return this.backend.updateOutgoingRoomKeyRequest(e,t,n)}deleteOutgoingRoomKeyRequest(e,t){return this.backend.deleteOutgoingRoomKeyRequest(e,t)}getAccount(e,t){this.backend.getAccount(e,t)}storeAccount(e,t){this.backend.storeAccount(e,t)}getCrossSigningKeys(e,t){this.backend.getCrossSigningKeys(e,t)}getSecretStorePrivateKey(e,t,n){this.backend.getSecretStorePrivateKey(e,t,n)}storeCrossSigningKeys(e,t){this.backend.storeCrossSigningKeys(e,t)}storeSecretStorePrivateKey(e,t,n){this.backend.storeSecretStorePrivateKey(e,t,n)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,n,i){this.backend.getEndToEndSession(e,t,n,i)}getEndToEndSessions(e,t,n){this.backend.getEndToEndSessions(e,t,n)}getAllEndToEndSessions(e,t){this.backend.getAllEndToEndSessions(e,t)}storeEndToEndSession(e,t,n,i){this.backend.storeEndToEndSession(e,t,n,i)}storeEndToEndSessionProblem(e,t,n){return this.backend.storeEndToEndSessionProblem(e,t,n)}getEndToEndSessionProblem(e,t){return this.backend.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.backend.filterOutNotifiedErrorDevices(e)}countEndToEndInboundGroupSessions(){return this.backend.countEndToEndInboundGroupSessions()}getEndToEndSessionsBatch(){return this.backend.getEndToEndSessionsBatch()}deleteEndToEndSessionsBatch(e){return this.backend.deleteEndToEndSessionsBatch(e)}getEndToEndInboundGroupSession(e,t,n,i){this.backend.getEndToEndInboundGroupSession(e,t,n,i)}getAllEndToEndInboundGroupSessions(e,t){this.backend.getAllEndToEndInboundGroupSessions(e,t)}addEndToEndInboundGroupSession(e,t,n,i){this.backend.addEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSession(e,t,n,i){this.backend.storeEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){this.backend.storeEndToEndInboundGroupSessionWithheld(e,t,n,i)}getEndToEndInboundGroupSessionsBatch(){return this.backend.getEndToEndInboundGroupSessionsBatch()}deleteEndToEndInboundGroupSessionsBatch(e){return this.backend.deleteEndToEndInboundGroupSessionsBatch(e)}storeEndToEndDeviceData(e,t){this.backend.storeEndToEndDeviceData(e,t)}getEndToEndDeviceData(e,t){this.backend.getEndToEndDeviceData(e,t)}storeEndToEndRoom(e,t,n){this.backend.storeEndToEndRoom(e,t,n)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}getSessionsNeedingBackup(e){return this.backend.getSessionsNeedingBackup(e)}countSessionsNeedingBackup(e){return this.backend.countSessionsNeedingBackup(e)}unmarkSessionsNeedingBackup(e,t){return this.backend.unmarkSessionsNeedingBackup(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}addSharedHistoryInboundGroupSession(e,t,n,i){this.backend.addSharedHistoryInboundGroupSession(e,t,n,i)}getSharedHistoryInboundGroupSessions(e,t){return this.backend.getSharedHistoryInboundGroupSessions(e,t)}addParkedSharedHistory(e,t,n){this.backend.addParkedSharedHistory(e,t,n)}takeParkedSharedHistory(e,t){return this.backend.takeParkedSharedHistory(e,t)}doTxn(e,t,n,i){return this.backend.doTxn(e,t,n,i)}}v(be,"STORE_ACCOUNT","account");v(be,"STORE_SESSIONS","sessions");v(be,"STORE_INBOUND_GROUP_SESSIONS","inbound_group_sessions");v(be,"STORE_INBOUND_GROUP_SESSIONS_WITHHELD","inbound_group_sessions_withheld");v(be,"STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","shared_history_inbound_group_sessions");v(be,"STORE_PARKED_SHARED_HISTORY","parked_shared_history");v(be,"STORE_DEVICE_DATA","device_data");v(be,"STORE_ROOMS","rooms");v(be,"STORE_BACKUP","sessions_needing_backup");var fa=function(r){return r.Change="change",r}({}),Hs=function(r){return r[r.Unsent=1]="Unsent",r[r.Requested=2]="Requested",r[r.Ready=3]="Ready",r[r.Started=4]="Started",r[r.Cancelled=5]="Cancelled",r[r.Done=6]="Done",r}({}),bm=function(r){return r.Cancel="cancel",r.ShowSas="show_sas",r.ShowReciprocateQr="show_reciprocate_qr",r}({});function iN(r){return r.phase<Hs.Ready&&!r.accepting&&!r.declining}function n8(r){if(r.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<r.length;c++){const u=r.charAt(c),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=c}const t=r.length,n=r.charAt(0),i=Math.log(t)/Math.log(256),o=Math.log(256)/Math.log(t);function s(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let u=0,d=0,f=0;const p=c.length;for(;f!==p&&c[f]===0;)f++,u++;const h=(p-f)*o+1>>>0,m=new Uint8Array(h);for(;f!==p;){let b=c[f],R=0;for(let k=h-1;(b!==0||R<d)&&k!==-1;k--,R++)b+=256*m[k]>>>0,m[k]=b%t>>>0,b=b/t>>>0;if(b!==0)throw new Error("Non-zero carry");d=R,f++}let w=h-d;for(;w!==h&&m[w]===0;)w++;let g=n.repeat(u);for(;w<h;++w)g+=r.charAt(m[w]);return g}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let u=0,d=0,f=0;for(;c[u]===n;)d++,u++;const p=(c.length-u)*i+1>>>0,h=new Uint8Array(p);for(;u<c.length;){const b=c.charCodeAt(u);if(b>255)return;let R=e[b];if(R===255)return;let k=0;for(let O=p-1;(R!==0||k<f)&&O!==-1;O--,k++)R+=t*h[O]>>>0,h[O]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");f=k,u++}let m=p-f;for(;m!==p&&h[m]===0;)m++;const w=new Uint8Array(d+(p-m));let g=d;for(;m!==p;)w[g++]=h[m++];return w}function l(c){const u=a(c);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:s,decodeUnsafe:a,decode:l}}var i8="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const oN=n8(i8);var hs=[139,1],HC=32;function nv(r){var e,t=Buffer.alloc(hs.length+r.length+1);t.set(hs,0),t.set(r,hs.length);for(var n=0,i=0;i<t.length-1;++i)n^=t[i];t[t.length-1]=n;var o=oN.encode(t);return(e=o.match(/.{1,4}/g))===null||e===void 0?void 0:e.join(" ")}function id(r){var e=oN.decode(r.replace(/ /g,"")),t=0;for(var n of e)t^=n;if(t!==0)throw new Error("Incorrect parity");for(var i=0;i<hs.length;++i)if(e[i]!==hs[i])throw new Error("Incorrect prefix");if(e.length!==hs.length+HC+1)throw new Error("Incorrect length");return Uint8Array.from(e.slice(hs.length,hs.length+HC))}var o8=256;function Cw(r,e,t){return Fb.apply(this,arguments)}function Fb(){return Fb=_(function*(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:o8;if(!globalThis.crypto.subtle||!TextEncoder)throw new Error("Password-based backup is not available on this platform");var i=yield globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(r),{name:"PBKDF2"},!1,["deriveBits"]),o=yield globalThis.crypto.subtle.deriveBits({name:"PBKDF2",salt:new TextEncoder().encode(e),iterations:t,hash:"SHA-512"},i,n);return new Uint8Array(o)}),Fb.apply(this,arguments)}var Yt=function(r){return r.UserTrustStatusChanged="userTrustStatusChanged",r.KeyBackupStatus="crypto.keyBackupStatus",r.KeyBackupFailed="crypto.keyBackupFailed",r.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",r.KeyBackupDecryptionKeyCached="crypto.keyBackupDecryptionKeyCached",r.VerificationRequestReceived="crypto.verificationRequestReceived",r.WillUpdateDevices="crypto.willUpdateDevices",r.DevicesUpdated="crypto.devicesUpdated",r.KeysChanged="crossSigning.keysChanged",r.LegacyCryptoStoreMigrationProgress="crypto.legacyCryptoStoreMigrationProgress",r}({}),Dt=function(r){return r.MEGOLM_UNKNOWN_INBOUND_SESSION_ID="MEGOLM_UNKNOWN_INBOUND_SESSION_ID",r.MEGOLM_KEY_WITHHELD="MEGOLM_KEY_WITHHELD",r.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE="MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE",r.OLM_UNKNOWN_MESSAGE_INDEX="OLM_UNKNOWN_MESSAGE_INDEX",r.HISTORICAL_MESSAGE_NO_KEY_BACKUP="HISTORICAL_MESSAGE_NO_KEY_BACKUP",r.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED="HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED",r.HISTORICAL_MESSAGE_WORKING_BACKUP="HISTORICAL_MESSAGE_WORKING_BACKUP",r.HISTORICAL_MESSAGE_USER_NOT_JOINED="HISTORICAL_MESSAGE_USER_NOT_JOINED",r.SENDER_IDENTITY_PREVIOUSLY_VERIFIED="SENDER_IDENTITY_PREVIOUSLY_VERIFIED",r.UNSIGNED_SENDER_DEVICE="UNSIGNED_SENDER_DEVICE",r.UNKNOWN_SENDER_DEVICE="UNKNOWN_SENDER_DEVICE",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.MEGOLM_BAD_ROOM="MEGOLM_BAD_ROOM",r.MEGOLM_MISSING_FIELDS="MEGOLM_MISSING_FIELDS",r.OLM_DECRYPT_GROUP_MESSAGE_ERROR="OLM_DECRYPT_GROUP_MESSAGE_ERROR",r.OLM_BAD_ENCRYPTED_MESSAGE="OLM_BAD_ENCRYPTED_MESSAGE",r.OLM_BAD_RECIPIENT="OLM_BAD_RECIPIENT",r.OLM_BAD_RECIPIENT_KEY="OLM_BAD_RECIPIENT_KEY",r.OLM_BAD_ROOM="OLM_BAD_ROOM",r.OLM_BAD_SENDER_CHECK_FAILED="OLM_BAD_SENDER_CHECK_FAILED",r.OLM_BAD_SENDER="OLM_BAD_SENDER",r.OLM_FORWARDED_MESSAGE="OLM_FORWARDED_MESSAGE",r.OLM_MISSING_CIPHERTEXT="OLM_MISSING_CIPHERTEXT",r.OLM_NOT_INCLUDED_IN_RECIPIENTS="OLM_NOT_INCLUDED_IN_RECIPIENTS",r.UNKNOWN_ENCRYPTION_ALGORITHM="UNKNOWN_ENCRYPTION_ALGORITHM",r}({}),kw=function(r){return r[r.AllDevicesIsolationMode=0]="AllDevicesIsolationMode",r[r.OnlySignedDevicesIsolationMode=1]="OnlySignedDevicesIsolationMode",r}({});class s8{constructor(e){this.errorOnVerifiedUserProblems=e,v(this,"kind",kw.AllDevicesIsolationMode)}}class a8{constructor(){v(this,"kind",kw.OnlySignedDevicesIsolationMode)}}class od{constructor(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=n,v(this,"needsUserApproval",void 0),this.needsUserApproval=i}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}class sN{constructor(e){var t,n,i,o,s;v(this,"signedByOwner",void 0),v(this,"crossSigningVerified",void 0),v(this,"tofu",void 0),v(this,"localVerified",void 0),v(this,"trustCrossSignedDevices",void 0),this.signedByOwner=(t=e.signedByOwner)!==null&&t!==void 0?t:!1,this.crossSigningVerified=(n=e.crossSigningVerified)!==null&&n!==void 0?n:!1,this.tofu=(i=e.tofu)!==null&&i!==void 0?i:!1,this.localVerified=(o=e.localVerified)!==null&&o!==void 0?o:!1,this.trustCrossSignedDevices=(s=e.trustCrossSignedDevices)!==null&&s!==void 0?s:!1}isVerified(){return this.localVerified||this.trustCrossSignedDevices&&this.crossSigningVerified}}var Iw=function(r){return r.Master="master",r.SelfSigning="self_signing",r.UserSigning="user_signing",r}({}),rs=function(r){return r[r.NONE=0]="NONE",r[r.GREY=1]="GREY",r[r.RED=2]="RED",r}({}),bl=function(r){return r[r.UNKNOWN=0]="UNKNOWN",r[r.UNVERIFIED_IDENTITY=1]="UNVERIFIED_IDENTITY",r[r.UNSIGNED_DEVICE=2]="UNSIGNED_DEVICE",r[r.UNKNOWN_DEVICE=3]="UNKNOWN_DEVICE",r[r.AUTHENTICITY_NOT_GUARANTEED=4]="AUTHENTICITY_NOT_GUARANTEED",r[r.MISMATCHED_SENDER_KEY=5]="MISMATCHED_SENDER_KEY",r}({});const l8=Object.freeze(Object.defineProperty({__proto__:null,AllDevicesIsolationMode:s8,CrossSigningKey:Iw,CryptoEvent:Yt,DecryptionFailureCode:Dt,DeviceIsolationModeKind:kw,DeviceVerificationStatus:sN,EventShieldColour:rs,EventShieldReason:bl,OnlySignedDevicesIsolationMode:a8,UserVerificationStatus:od,VerificationPhase:Hs,VerificationRequestEvent:fa,VerifierEvent:bm,canAcceptVerificationRequest:iN,decodeRecoveryKey:id,deriveRecoveryKeyFromPassphrase:Cw,encodeRecoveryKey:nv},Symbol.toStringTag,{value:"Module"}));class cr extends Error{constructor(e,t,n){super(t),this.code=e,v(this,"detailedString",void 0),this.name="DecryptionError",this.detailedString=c8(this,n)}}function c8(r,e){var t=r.name+"[msg: "+r.message;return e&&(t+=", "+Object.keys(e).map(n=>n+": "+e[n]).join(", ")),t+="]",t}var zC=65536*3/4;class u8 extends Error{constructor(){super(...arguments),v(this,"data",{errcode:"M_TOO_LARGE",error:"Payload too large for encrypted message"})}}function YC(r){if(r===void 0)throw new Error("payloadString undefined");if(r.length>zC)throw new u8("Message too long (".concat(r.length," bytes). ")+"The maximum for an encrypted message is ".concat(zC," bytes."))}class JC{constructor(e){this.cryptoStore=e,v(this,"pickleKey","DEFAULT_KEY"),v(this,"deviceCurve25519Key",null),v(this,"deviceEd25519Key",null),v(this,"maxOneTimeKeys",null),v(this,"outboundGroupSessionStore",{}),v(this,"inboundGroupSessionMessageIndexes",{}),v(this,"sessionsInProgress",{}),v(this,"olmPrekeyPromise",Promise.resolve())}static getOlmVersion(){return globalThis.Olm.get_library_version()}init(){var e=arguments,t=this;return _(function*(){var{pickleKey:n,fromExportedDevice:i}=e.length>0&&e[0]!==void 0?e[0]:{},o,s=new globalThis.Olm.Account;try{i?(n&&S.warn("ignoring opts.pickleKey because opts.fromExportedDevice is present."),t.pickleKey=i.pickleKey,yield t.initialiseFromExportedDevice(i,s)):(n&&(t.pickleKey=n),yield t.initialiseAccount(s)),o=JSON.parse(s.identity_keys()),t.maxOneTimeKeys=s.max_number_of_one_time_keys()}finally{s.free()}t.deviceCurve25519Key=o.curve25519,t.deviceEd25519Key=o.ed25519})()}initialiseFromExportedDevice(e,t){var n=this;return _(function*(){yield n.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT,be.STORE_SESSIONS],i=>{n.cryptoStore.storeAccount(i,e.pickledAccount),e.sessions.forEach(o=>{var{deviceKey:s,sessionId:a}=o,l={session:o.session,lastReceivedMessageTs:o.lastReceivedMessageTs};n.cryptoStore.storeEndToEndSession(s,a,l,i)})}),t.unpickle(n.pickleKey,e.pickledAccount)})()}initialiseAccount(e){var t=this;return _(function*(){yield t.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],n=>{t.cryptoStore.getAccount(n,i=>{i!==null?e.unpickle(t.pickleKey,i):(e.create(),i=e.pickle(t.pickleKey),t.cryptoStore.storeAccount(n,i))})})})()}getAccount(e,t){this.cryptoStore.getAccount(e,n=>{var i=new globalThis.Olm.Account;try{i.unpickle(this.pickleKey,n),t(i)}finally{i.free()}})}storeAccount(e,t){this.cryptoStore.storeAccount(e,t.pickle(this.pickleKey))}export(){var e=this;return _(function*(){var t={pickleKey:e.pickleKey};return yield e.cryptoStore.doTxn("readonly",[be.STORE_ACCOUNT,be.STORE_SESSIONS],n=>{e.cryptoStore.getAccount(n,i=>{t.pickledAccount=i}),t.sessions=[],e.cryptoStore.getAllEndToEndSessions(n,i=>{t.sessions.push(i)})}),t})()}getSession(e,t,n,i){this.cryptoStore.getEndToEndSession(e,t,n,o=>{this.unpickleSession(o,i)})}unpickleSession(e,t){var n=new globalThis.Olm.Session;try{n.unpickle(this.pickleKey,e.session);var i=Object.assign({},e,{session:n});t(i)}finally{n.free()}}saveSession(e,t,n){var i=t.session.session_id();S.debug("Saving Olm session ".concat(i," with device ").concat(e,": ").concat(t.session.describe()));var o=Object.assign(t,{session:t.session.pickle(this.pickleKey)});this.cryptoStore.storeEndToEndSession(e,i,o,n)}getUtility(e){var t=new globalThis.Olm.Utility;try{return e(t)}finally{t.free()}}sign(e){var t=this;return _(function*(){var n;return yield t.cryptoStore.doTxn("readonly",[be.STORE_ACCOUNT],i=>{t.getAccount(i,o=>{n=o.sign(e)})}),n})()}getOneTimeKeys(){var e=this;return _(function*(){var t;return yield e.cryptoStore.doTxn("readonly",[be.STORE_ACCOUNT],n=>{e.getAccount(n,i=>{t=JSON.parse(i.one_time_keys())})}),t})()}maxNumberOfOneTimeKeys(){var e;return(e=this.maxOneTimeKeys)!==null&&e!==void 0?e:-1}markKeysAsPublished(){var e=this;return _(function*(){yield e.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],t=>{e.getAccount(t,n=>{n.mark_keys_as_published(),e.storeAccount(t,n)})})})()}generateOneTimeKeys(e){return this.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],t=>{this.getAccount(t,n=>{n.generate_one_time_keys(e),this.storeAccount(t,n)})})}generateFallbackKey(){var e=this;return _(function*(){yield e.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],t=>{e.getAccount(t,n=>{n.generate_fallback_key(),e.storeAccount(t,n)})})})()}getFallbackKey(){var e=this;return _(function*(){var t;return yield e.cryptoStore.doTxn("readonly",[be.STORE_ACCOUNT],n=>{e.getAccount(n,i=>{t=JSON.parse(i.unpublished_fallback_key())})}),t})()}forgetOldFallbackKey(){var e=this;return _(function*(){yield e.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],t=>{e.getAccount(t,n=>{n.forget_old_fallback_key(),e.storeAccount(t,n)})})})()}createOutboundSession(e,t){var n=this;return _(function*(){var i;return yield n.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT,be.STORE_SESSIONS],o=>{n.getAccount(o,s=>{var a=new globalThis.Olm.Session;try{a.create_outbound(s,e,t),i=a.session_id(),n.storeAccount(o,s);var l={session:a,lastReceivedMessageTs:Date.now()};n.saveSession(e,l,o)}finally{a.free()}})},S.getChild("[createOutboundSession]")),i})()}createInboundSession(e,t,n){var i=this;return _(function*(){if(t!==0)throw new Error("Need messageType == 0 to create inbound session");var o;return yield i.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT,be.STORE_SESSIONS],s=>{i.getAccount(s,a=>{var l=new globalThis.Olm.Session;try{l.create_inbound_from(a,e,n),a.remove_one_time_keys(l),i.storeAccount(s,a);var c=l.decrypt(t,n),u={session:l,lastReceivedMessageTs:Date.now()};i.saveSession(e,u,s),o={payload:c,session_id:l.session_id()}}finally{l.free()}})},S.getChild("[createInboundSession]")),o})()}getSessionIdsForDevice(e){var t=this;return _(function*(){var n=S.getChild("[getSessionIdsForDevice]");if(e in t.sessionsInProgress){n.debug("Waiting for Olm session for ".concat(e," to be created"));try{yield t.sessionsInProgress[e]}catch{}}var i;return yield t.cryptoStore.doTxn("readonly",[be.STORE_SESSIONS],o=>{t.cryptoStore.getEndToEndSessions(e,o,s=>{i=Object.keys(s)})},n),i})()}getSessionIdForDevice(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2?t[2]:void 0,s=yield n.getSessionInfoForDevice(e,i,o);if(s.length===0)return null;for(var a=0,l=1;l<s.length;l++){var c=s[l],u=c.lastReceivedMessageTs===void 0?0:c.lastReceivedMessageTs,d=s[a],f=d.lastReceivedMessageTs===void 0?0:d.lastReceivedMessageTs;(u>f||u===f&&c.sessionId<d.sessionId)&&(a=l)}return s[a].sessionId})()}getSessionInfoForDevice(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2&&t[2]!==void 0?t[2]:S;if(o=o.getChild("[getSessionInfoForDevice]"),e in n.sessionsInProgress&&!i){o.debug("Waiting for Olm session for ".concat(e," to be created"));try{yield n.sessionsInProgress[e]}catch{}}var s=[];return yield n.cryptoStore.doTxn("readonly",[be.STORE_SESSIONS],a=>{n.cryptoStore.getEndToEndSessions(e,a,l=>{var c=Object.keys(l).sort(),u=function(p){n.unpickleSession(l[p],h=>{s.push({lastReceivedMessageTs:h.lastReceivedMessageTs,hasReceivedMessage:h.session.has_received_message(),sessionId:p})})};for(var d of c)u(d)})},o),s})()}encryptMessage(e,t,n){var i=this;return _(function*(){YC(n);var o;return yield i.cryptoStore.doTxn("readwrite",[be.STORE_SESSIONS],s=>{i.getSession(e,t,s,a=>{var l=a.session.describe();S.log("encryptMessage: Olm Session ID "+t+" to "+e+": "+l),o=a.session.encrypt(n),i.saveSession(e,a,s)})},S.getChild("[encryptMessage]")),o})()}decryptMessage(e,t,n,i){var o=this;return _(function*(){var s;return yield o.cryptoStore.doTxn("readwrite",[be.STORE_SESSIONS],a=>{o.getSession(e,t,a,l=>{var c=l.session.describe();S.log("decryptMessage: Olm Session ID "+t+" from "+e+": "+c),s=l.session.decrypt(n,i),l.lastReceivedMessageTs=Date.now(),o.saveSession(e,l,a)})},S.getChild("[decryptMessage]")),s})()}matchesSession(e,t,n,i){var o=this;return _(function*(){if(n!==0)return!1;var s;return yield o.cryptoStore.doTxn("readonly",[be.STORE_SESSIONS],a=>{o.getSession(e,t,a,l=>{s=l.session.matches_inbound(i)})},S.getChild("[matchesSession]")),s})()}recordSessionProblem(e,t,n){var i=this;return _(function*(){S.info("Recording problem on olm session with ".concat(e," of type ").concat(t,". Recreating: ").concat(n)),yield i.cryptoStore.storeEndToEndSessionProblem(e,t,n)})()}sessionMayHaveProblems(e,t){return this.cryptoStore.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.cryptoStore.filterOutNotifiedErrorDevices(e)}saveOutboundGroupSession(e){this.outboundGroupSessionStore[e.session_id()]=e.pickle(this.pickleKey)}getOutboundGroupSession(e,t){var n=this.outboundGroupSessionStore[e];if(n===void 0)throw new Error("Unknown outbound group session "+e);var i=new globalThis.Olm.OutboundGroupSession;try{return i.unpickle(this.pickleKey,n),t(i)}finally{i.free()}}createOutboundGroupSession(){var e=new globalThis.Olm.OutboundGroupSession;try{return e.create(),this.saveOutboundGroupSession(e),e.session_id()}finally{e.free()}}encryptGroupMessage(e,t){return S.log("encrypting msg with megolm session ".concat(e)),YC(t),this.getOutboundGroupSession(e,n=>{var i=n.encrypt(t);return this.saveOutboundGroupSession(n),i})}getOutboundGroupSessionKey(e){return this.getOutboundGroupSession(e,function(t){return{chain_index:t.message_index(),key:t.session_key()}})}unpickleInboundGroupSession(e,t){var n=new globalThis.Olm.InboundGroupSession;try{return n.unpickle(this.pickleKey,e.session),t(n)}finally{n.free()}}getInboundGroupSession(e,t,n,i,o){this.cryptoStore.getEndToEndInboundGroupSession(t,n,i,(s,a)=>{if(s===null){o(null,null,a);return}if(e!==null&&e!==s.room_id)throw new Error("Mismatched room_id for inbound group session (expected "+s.room_id+", was "+e+")");this.unpickleInboundGroupSession(s,l=>{o(l,s,a)})})}addInboundGroupSession(e,t,n,i,o,s,a){var l=arguments,c=this;return _(function*(){var u=l.length>7&&l[7]!==void 0?l[7]:{};yield c.cryptoStore.doTxn("readwrite",[be.STORE_INBOUND_GROUP_SESSIONS,be.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,be.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],d=>{c.getInboundGroupSession(e,t,i,d,(f,p)=>{var h=new globalThis.Olm.InboundGroupSession;try{if(a?h.import_session(o):h.create(o),i!=h.session_id())throw new Error("Mismatched group session ID from senderKey: "+t);if(f&&(S.log("Update for megolm session ".concat(t,"|").concat(i)),f.first_known_index()<=h.first_known_index())){if(!p.untrusted||u.untrusted){S.log("Keeping existing megolm session ".concat(t,"|").concat(i));return}if(f.first_known_index()<h.first_known_index()){f.export_session(h.first_known_index())===h.export_session(h.first_known_index())?(S.info("Upgrading trust of existing megolm session "+"".concat(t,"|").concat(i," based on newly-received trusted session")),p.untrusted=!1,c.cryptoStore.storeEndToEndInboundGroupSession(t,i,p,d)):S.warn("Newly-received megolm session ".concat(t,"|$sessionId}")+" does not match existing session! Keeping existing session");return}}S.debug("Storing megolm session ".concat(t,"|").concat(i," with first index ")+h.first_known_index());var m=Object.assign({},u,{room_id:e,session:h.pickle(c.pickleKey),keysClaimed:s,forwardingCurve25519KeyChain:n});c.cryptoStore.storeEndToEndInboundGroupSession(t,i,m,d),!f&&u.sharedHistory&&c.cryptoStore.addSharedHistoryInboundGroupSession(e,t,i,d)}finally{h.free()}})},S.getChild("[addInboundGroupSession]"))})()}addInboundGroupSessionWithheld(e,t,n,i,o){var s=this;return _(function*(){yield s.cryptoStore.doTxn("readwrite",[be.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],a=>{s.cryptoStore.storeEndToEndInboundGroupSessionWithheld(t,n,{room_id:e,code:i,reason:o},a)})})()}decryptGroupMessage(e,t,n,i,o,s){var a=this;return _(function*(){var l=null,c;if(yield a.cryptoStore.doTxn("readwrite",[be.STORE_INBOUND_GROUP_SESSIONS,be.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],u=>{a.getInboundGroupSession(e,t,n,u,(d,f,p)=>{if(d===null||f===null){if(p){var h=p.code==="m.unverified"?Dt.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:Dt.MEGOLM_KEY_WITHHELD;c=new cr(h,XC(p),{session:t+"|"+n})}l=null;return}var m;try{m=d.decrypt(i)}catch(k){if((k==null?void 0:k.message)==="OLM.UNKNOWN_MESSAGE_INDEX"&&p){var w=p.code==="m.unverified"?Dt.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:Dt.MEGOLM_KEY_WITHHELD;c=new cr(w,XC(p),{session:t+"|"+n})}else c=k;return}var g=m.plaintext;if(g===void 0)g=m;else{var b=t+"|"+n+"|"+m.message_index;if(b in a.inboundGroupSessionMessageIndexes){var R=a.inboundGroupSessionMessageIndexes[b];if(R.id!==o||R.timestamp!==s){c=new Error("Duplicate message index, possible replay attack: "+b);return}}a.inboundGroupSessionMessageIndexes[b]={id:o,timestamp:s}}f.session=d.pickle(a.pickleKey),a.cryptoStore.storeEndToEndInboundGroupSession(t,n,f,u),l={result:g,keysClaimed:f.keysClaimed||{},senderKey:t,forwardingCurve25519KeyChain:f.forwardingCurve25519KeyChain||[],untrusted:!!f.untrusted}})},S.getChild("[decryptGroupMessage]")),c)throw c;return l})()}hasInboundSessionKeys(e,t,n){var i=this;return _(function*(){var o;return yield i.cryptoStore.doTxn("readonly",[be.STORE_INBOUND_GROUP_SESSIONS,be.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],s=>{i.cryptoStore.getEndToEndInboundGroupSession(t,n,s,a=>{if(a===null){o=!1;return}e!==a.room_id?(S.warn("requested keys for inbound group session ".concat(t,"|")+"".concat(n,", with incorrect room_id ")+"(expected ".concat(a.room_id,", ")+"was ".concat(e,")")),o=!1):o=!0})},S.getChild("[hasInboundSessionKeys]")),o})()}getInboundGroupSessionKey(e,t,n,i){var o=this;return _(function*(){var s=null;return yield o.cryptoStore.doTxn("readonly",[be.STORE_INBOUND_GROUP_SESSIONS,be.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],a=>{o.getInboundGroupSession(e,t,n,a,(l,c)=>{if(l===null||c===null){s=null;return}i===void 0&&(i=l.first_known_index());var u=l.export_session(i),d=c.keysClaimed||{},f=d.ed25519||null,p=c.forwardingCurve25519KeyChain||[],h="untrusted"in c?c.untrusted:p.length>0;s={chain_index:i,key:u,forwarding_curve25519_key_chain:p,sender_claimed_ed25519_key:f,shared_history:c.sharedHistory||!1,untrusted:h}})},S.getChild("[getInboundGroupSessionKey]")),s})()}exportInboundGroupSession(e,t,n){return this.unpickleInboundGroupSession(n,i=>{var o=i.first_known_index();return{sender_key:e,sender_claimed_keys:n.keysClaimed,room_id:n.room_id,session_id:t,session_key:i.export_session(o),forwarding_curve25519_key_chain:n.forwardingCurve25519KeyChain||[],first_known_index:i.first_known_index(),"org.matrix.msc3061.shared_history":n.sharedHistory||!1}})}getSharedHistoryInboundGroupSessions(e){var t=this;return _(function*(){var n;return yield t.cryptoStore.doTxn("readonly",[be.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],i=>{n=t.cryptoStore.getSharedHistoryInboundGroupSessions(e,i)},S.getChild("[getSharedHistoryInboundGroupSessionsForRoom]")),n})()}verifySignature(e,t,n){this.getUtility(function(i){i.ed25519_verify(e,t,n)})}}var iv={"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."};function XC(r){return r.code&&r.code in iv?iv[r.code]:r.reason?r.reason:"decryption key withheld"}var d8=new Uint8Array(8);function aN(r,e){return Bb.apply(this,arguments)}function Bb(){return Bb=_(function*(r,e){var t=yield globalThis.crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),n=yield globalThis.crypto.subtle.deriveBits({name:"HKDF",salt:d8,info:new TextEncoder().encode(e),hash:"SHA-256"},t,512),i=n.slice(0,32),o=n.slice(32),s=globalThis.crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["encrypt","decrypt"]),a=globalThis.crypto.subtle.importKey("raw",o,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([s,a])}),Bb.apply(this,arguments)}function Kc(r,e,t,n){return Kb.apply(this,arguments)}function Kb(){return Kb=_(function*(r,e,t,n){var i;n?i=Dr(n):(i=new Uint8Array(16),globalThis.crypto.getRandomValues(i),i[8]&=127);var[o,s]=yield aN(e,t),a=new TextEncoder().encode(r),l=yield globalThis.crypto.subtle.encrypt({name:"AES-CTR",counter:i,length:64},o,a),c=yield globalThis.crypto.subtle.sign({name:"HMAC"},s,l);return{iv:Qr(i),ciphertext:Qr(l),mac:Qr(c)}}),Kb.apply(this,arguments)}function Ef(r,e,t){return Vb.apply(this,arguments)}function Vb(){return Vb=_(function*(r,e,t){var[n,i]=yield aN(e,t),o=Dr(r.ciphertext);if(!(yield globalThis.crypto.subtle.verify({name:"HMAC"},i,Dr(r.mac),o)))throw new Error("Error decrypting secret ".concat(t,": bad MAC"));var s=yield globalThis.crypto.subtle.decrypt({name:"AES-CTR",counter:Dr(r.iv),length:64},n,o);return new TextDecoder().decode(new Uint8Array(s))}),Vb.apply(this,arguments)}var f8=1e3*60;function hh(r){return Object.values(r.keys)[0]}class gi{constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.userId=e,this.callbacks=t,this.cacheCallbacks=n,v(this,"keys",{}),v(this,"firstUse",!0),v(this,"crossSigningVerifiedBefore",!1)}static fromStorage(e,t){var n=new gi(t);for(var i in e)e.hasOwnProperty(i)&&(n[i]=e[i]);return n}toStorage(){return{keys:this.keys,firstUse:this.firstUse,crossSigningVerifiedBefore:this.crossSigningVerifiedBefore}}getCrossSigningKey(e,t){var n=this;return _(function*(){var i=["master","self_signing","user_signing"].indexOf(e)>=0;if(!n.callbacks.getCrossSigningKey)throw new Error("No getCrossSigningKey callback supplied");t===void 0&&(t=n.getId(e));function o(c){if(c){var u=new globalThis.Olm.PkSigning,d=u.init_with_seed(c);if(d===t)return[d,u];u.free()}}var s=null;n.cacheCallbacks.getCrossSigningKeyCache&&i&&(s=yield n.cacheCallbacks.getCrossSigningKeyCache(e,t));var a=o(s);if(a)return a;s=yield n.callbacks.getCrossSigningKey(e,t);var l=o(s);if(l)return n.cacheCallbacks.storeCrossSigningKeyCache&&i&&(yield n.cacheCallbacks.storeCrossSigningKeyCache(e,s)),l;throw s?new Error("Key type "+e+" from getCrossSigningKey callback did not match"):new Error("getCrossSigningKey callback for "+e+" returned falsey")})()}isStoredInSecretStorage(e){return _(function*(){var t=(yield e.isStored("m.cross_signing.master"))||{};function n(o){for(var s of Object.keys(t))o[s]||delete t[s]}for(var i of["self_signing","user_signing"])n((yield e.isStored("m.cross_signing.".concat(i)))||{});return Object.keys(t).length?t:null})()}static storeInSecretStorage(e,t){return _(function*(){for(var[n,i]of e){var o=Qr(i);yield t.store("m.cross_signing.".concat(n),o)}})()}static getFromSecretStorage(e,t){return _(function*(){var n=yield t.get("m.cross_signing.".concat(e));return n?Dr(n):null})()}isStoredInKeyCache(e){var t=this;return _(function*(){var n=t.cacheCallbacks;if(!n)return!1;var i=e?[e]:["master","self_signing","user_signing"];for(var o of i){var s;if(!(yield(s=n.getCrossSigningKeyCache)===null||s===void 0?void 0:s.call(n,o)))return!1}return!0})()}getCrossSigningKeysFromCache(){var e=this;return _(function*(){var t=new Map,n=e.cacheCallbacks;if(!n)return t;for(var i of["master","self_signing","user_signing"]){var o,s=yield(o=n.getCrossSigningKeyCache)===null||o===void 0?void 0:o.call(n,i);s&&t.set(i,s)}return t})()}getId(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"master";if(!this.keys[e])return null;var t=this.keys[e];return hh(t)}resetKeys(e){var t=this;return _(function*(){if(!t.callbacks.saveCrossSigningKeys)throw new Error("No saveCrossSigningKeys callback supplied");if(e===void 0||e&ra.MASTER||!t.keys.master)e=ra.MASTER|ra.USER_SIGNING|ra.SELF_SIGNING;else if(e===0)return;var n={},i={},o,s;try{if(e&ra.MASTER?(o=new globalThis.Olm.PkSigning,n.master=o.generate_seed(),s=o.init_with_seed(n.master),i.master={user_id:t.userId,usage:["master"],keys:{["ed25519:"+s]:s}}):[s,o]=yield t.getCrossSigningKey("master"),e&ra.SELF_SIGNING){var a=new globalThis.Olm.PkSigning;try{n.self_signing=a.generate_seed();var l=a.init_with_seed(n.self_signing);i.self_signing={user_id:t.userId,usage:["self_signing"],keys:{["ed25519:"+l]:l}},Hh(i.self_signing,o,t.userId,s)}finally{a.free()}}if(e&ra.USER_SIGNING){var c=new globalThis.Olm.PkSigning;try{n.user_signing=c.generate_seed();var u=c.init_with_seed(n.user_signing);i.user_signing={user_id:t.userId,usage:["user_signing"],keys:{["ed25519:"+u]:u}},Hh(i.user_signing,o,t.userId,s)}finally{c.free()}}Object.assign(t.keys,i),t.callbacks.saveCrossSigningKeys(n)}finally{o&&o.free()}})()}clearKeys(){this.keys={}}setKeys(e){var t={};if(e.master){if(e.master.user_id!==this.userId){var n="Mismatched user ID "+e.master.user_id+" in master key from "+this.userId;throw S.error(n),new Error(n)}this.keys.master?hh(e.master)!==this.getId()&&(this.firstUse=!1):this.firstUse=!0,t.master=e.master}else if(this.keys.master)t.master=this.keys.master;else throw new Error("Tried to set cross-signing keys without a master key");var i=hh(t.master);if(e.user_signing){if(e.user_signing.user_id!==this.userId){var o="Mismatched user ID "+e.master.user_id+" in user_signing key from "+this.userId;throw S.error(o),new Error(o)}try{Sl(e.user_signing,i,this.userId)}catch(a){throw S.error("invalid signature on user-signing key"),a}}if(e.self_signing){if(e.self_signing.user_id!==this.userId){var s="Mismatched user ID "+e.master.user_id+" in self_signing key from "+this.userId;throw S.error(s),new Error(s)}try{Sl(e.self_signing,i,this.userId)}catch(a){throw S.error("invalid signature on self-signing key"),a}}e.master&&(this.keys.master=e.master,delete this.keys.self_signing,delete this.keys.user_signing),e.self_signing&&(this.keys.self_signing=e.self_signing),e.user_signing&&(this.keys.user_signing=e.user_signing)}updateCrossSigningVerifiedBefore(e){!this.crossSigningVerifiedBefore&&e&&(this.crossSigningVerifiedBefore=!0)}signObject(e,t){var n=this;return _(function*(){if(!n.keys[t])throw new Error("Attempted to sign with "+t+" key but no such key present");var[i,o]=yield n.getCrossSigningKey(t);try{return Hh(e,o,n.userId,i),e}finally{o.free()}})()}signUser(e){var t=this;return _(function*(){if(!t.keys.user_signing){S.info("No user signing key: not signing user");return}return t.signObject(e.keys.master,"user_signing")})()}signDevice(e,t){var n=this;return _(function*(){if(e!==n.userId)throw new Error("Trying to sign ".concat(e,"'s device; can only sign our own device"));if(!n.keys.self_signing){S.info("No self signing key: not signing device");return}return n.signObject({algorithms:t.algorithms,keys:t.keys,device_id:t.deviceId,user_id:e},"self_signing")})()}checkUserTrust(e){if(this.userId===e.userId&&this.getId()&&this.getId()===e.getId()&&this.getId("self_signing")&&this.getId("self_signing")===e.getId("self_signing"))return new od(!0,!0,this.firstUse);if(!this.keys.user_signing)return new od(!1,!1,e.firstUse);var t,n=e.keys.master,i=this.getId("user_signing");try{Sl(n,i,this.userId),t=!0}catch{t=!1}return new od(t,e.crossSigningVerifiedBefore,e.firstUse)}checkDeviceTrust(e,t,n,i){var o=this.checkUserTrust(e),s=e.keys.self_signing;if(!s)return new Xl(!1,!1,n,i);var a=h8(t,e.userId);try{return Sl(s,e.getId(),e.userId),Sl(a,hh(s),e.userId),Xl.fromUserTrustLevel(o,n,i)}catch{return new Xl(!1,!1,n,i)}}getCacheCallbacks(){return this.cacheCallbacks}}function h8(r,e){return{algorithms:r.algorithms,keys:r.keys,device_id:r.deviceId,user_id:e,signatures:r.signatures}}var ra=function(r){return r[r.MASTER=4]="MASTER",r[r.USER_SIGNING=2]="USER_SIGNING",r[r.SELF_SIGNING=1]="SELF_SIGNING",r}({});class Xl extends sN{constructor(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;super({crossSigningVerified:e,tofu:t,localVerified:n,trustCrossSignedDevices:i,signedByOwner:o})}static fromUserTrustLevel(e,t,n){return new Xl(e.isCrossSigningVerified(),e.isTofu(),t,n,!0)}isCrossSigningVerified(){return this.crossSigningVerified}isLocallyVerified(){return this.localVerified}isTofu(){return this.tofu}}function lN(r,e){return{getCrossSigningKeyCache:function(){var t=_(function*(i,o){var s=yield new Promise(c=>{r.doTxn("readonly",[be.STORE_ACCOUNT],u=>{r.getSecretStorePrivateKey(u,c,i)})});if(s&&s.ciphertext){var a=Buffer.from(e.pickleKey),l=yield Ef(s,a,i);return Dr(l)}else return s});function n(i,o){return t.apply(this,arguments)}return n}(),storeCrossSigningKeyCache:function(){var t=_(function*(i,o){if(!(o instanceof Uint8Array))throw new Error("storeCrossSigningKeyCache expects Uint8Array, got ".concat(o));var s=Buffer.from(e.pickleKey),a=yield Kc(Qr(o),s,i);return r.doTxn("readwrite",[be.STORE_ACCOUNT],l=>{r.storeSecretStorePrivateKey(l,i,a)})});function n(i,o){return t.apply(this,arguments)}return n}()}}function p8(r,e,t){return $b.apply(this,arguments)}function $b(){return $b=_(function*(r,e,t){if(r.getUserId()===e)return S.log("Cross-signing: Self-verification done; requesting keys"),new Promise((n,i)=>{var o=r,s=o.crypto.crossSigningInfo,a=new gi(s.userId,{getCrossSigningKey:function(){var u=_(function*(f){S.debug("Cross-signing: requesting secret",f,t);var{promise:p}=o.requestSecret("m.cross_signing.".concat(f),[t]),h=yield p,m=Dr(h);return Uint8Array.from(m)});function d(f){return u.apply(this,arguments)}return d}()},s.getCacheCallbacks());a.keys=s.keys;var l=new Promise(u=>{setTimeout(u,f8,new Error("Timeout"))}),c=_(function*(){var u=yield o.crypto.getSessionBackupPrivateKey();if(!u){S.info("No cached backup key found. Requesting...");var d=o.requestSecret("m.megolm_backup.v1",[t]),f=yield d.promise;S.info("Got key backup key, decoding...");var p=Dr(f);S.info("Decoded backup key, storing..."),yield o.crypto.storeSessionBackupPrivateKey(Uint8Array.from(p)),S.info("Backup key stored. Starting backup restore...");var h=yield o.getKeyBackupVersion();o.restoreKeyBackupWithCache(void 0,void 0,h).then(()=>{S.info("Backup restored.")})}})();Promise.race([Promise.all([a.getCrossSigningKey("master"),a.getCrossSigningKey("self_signing"),a.getCrossSigningKey("user_signing"),c]),l]).then(n,i)}).catch(n=>{S.warn("Cross-signing: failure while requesting keys:",n)})}),$b.apply(this,arguments)}var kn=function(r){return r[r.NotTracked=0]="NotTracked",r[r.PendingDownload=1]="PendingDownload",r[r.DownloadInProgress=2]="DownloadInProgress",r[r.UpToDate=3]="UpToDate",r}({});class v8 extends Tt{constructor(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:250;super(),this.cryptoStore=t,this.keyDownloadChunkSize=i,v(this,"devices",{}),v(this,"crossSigningInfo",{}),v(this,"userByIdentityKey",{}),v(this,"deviceTrackingStatus",{}),v(this,"syncToken",null),v(this,"keyDownloadsInProgressByUser",new Map),v(this,"dirty",!1),v(this,"savePromise",null),v(this,"resolveSavePromise",null),v(this,"savePromiseTime",null),v(this,"saveTimer",null),v(this,"hasFetched",null),v(this,"serialiser",void 0),this.serialiser=new m8(e,n,this)}load(){var e=this;return _(function*(){yield e.cryptoStore.doTxn("readonly",[be.STORE_DEVICE_DATA],n=>{e.cryptoStore.getEndToEndDeviceData(n,i=>{var o;e.hasFetched=!!(i!=null&&i.devices),e.devices=i?i.devices:{},e.crossSigningInfo=i?i.crossSigningInfo||{}:{},e.deviceTrackingStatus=i?i.trackingStatus:{},e.syncToken=(o=i==null?void 0:i.syncToken)!==null&&o!==void 0?o:null,e.userByIdentityKey={};for(var s of Object.keys(e.devices)){var a=e.devices[s];for(var l of Object.keys(a)){var c=a[l].keys["curve25519:"+l];c!==void 0&&(e.userByIdentityKey[c]=s)}}})});for(var t of Object.keys(e.deviceTrackingStatus))e.deviceTrackingStatus[t]==kn.DownloadInProgress&&(e.deviceTrackingStatus[t]=kn.PendingDownload)})()}stop(){this.saveTimer!==null&&clearTimeout(this.saveTimer)}saveIfDirty(){var e=arguments,t=this;return _(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:500;if(!t.dirty)return Promise.resolve(!1);var i=Date.now()+n;t.savePromiseTime&&i<t.savePromiseTime&&(clearTimeout(t.saveTimer),t.saveTimer=null,t.savePromiseTime=null);var o=t.savePromise;if(o===null&&(o=new Promise(a=>{t.resolveSavePromise=a}),t.savePromise=o),t.saveTimer===null){var s=t.resolveSavePromise;t.savePromiseTime=i,t.saveTimer=setTimeout(()=>{S.log("Saving device tracking data",t.syncToken),t.savePromiseTime=null,t.saveTimer=null,t.savePromise=null,t.resolveSavePromise=null,t.cryptoStore.doTxn("readwrite",[be.STORE_DEVICE_DATA],a=>{var l;t.cryptoStore.storeEndToEndDeviceData({devices:t.devices,crossSigningInfo:t.crossSigningInfo,trackingStatus:t.deviceTrackingStatus,syncToken:(l=t.syncToken)!==null&&l!==void 0?l:void 0},a)}).then(()=>{t.dirty=!1,s==null||s(!0)},a=>{S.error("Failed to save device tracking data",t.syncToken),S.error(a)})},n)}return o})()}getSyncToken(){return this.syncToken}setSyncToken(e){this.syncToken=e}downloadKeys(e,t){var n=[],i=[];if(e.forEach(s=>{var a=this.deviceTrackingStatus[s];this.keyDownloadsInProgressByUser.has(s)?(S.log("downloadKeys: already have a download in progress for "+"".concat(s,": awaiting its result")),i.push(this.keyDownloadsInProgressByUser.get(s))):(t||a!=kn.UpToDate)&&n.push(s)}),n.length!=0){S.log("downloadKeys: downloading for",n);var o=this.doKeyDownload(n);i.push(o)}return i.length===0&&S.log("downloadKeys: already have all necessary keys"),Promise.all(i).then(()=>this.getDevicesFromStore(e))}getDevicesFromStore(e){var t=new Map;return e.forEach(n=>{var i,o=new Map;(i=this.getStoredDevicesForUser(n))===null||i===void 0||i.forEach(function(s){o.set(s.deviceId,s)}),t.set(n,o)}),t}getKnownUserIds(){return Object.keys(this.devices)}getStoredDevicesForUser(e){var t=this.devices[e];if(!t)return null;var n=[];for(var i in t)t.hasOwnProperty(i)&&n.push(tn.fromStorage(t[i],i));return n}getRawStoredDevicesForUser(e){return this.devices[e]}getStoredCrossSigningForUser(e){return this.crossSigningInfo[e]?gi.fromStorage(this.crossSigningInfo[e],e):null}storeCrossSigningForUser(e,t){this.crossSigningInfo[e]=t,this.dirty=!0}getStoredDevice(e,t){var n=this.devices[e];if(n!=null&&n[t])return tn.fromStorage(n[t],t)}getUserByIdentityKey(e,t){return e!==wr&&e!==bn?null:this.userByIdentityKey[t]}getDeviceByIdentityKey(e,t){var n=this.getUserByIdentityKey(e,t);if(!n)return null;var i=this.devices[n];if(!i)return null;for(var o in i)if(i.hasOwnProperty(o)){var s=i[o];for(var a in s.keys)if(s.keys.hasOwnProperty(a)&&a.indexOf("curve25519:")===0){var l=s.keys[a];if(l==t)return tn.fromStorage(s,o)}}return null}storeDevicesForUser(e,t){this.setRawStoredDevicesForUser(e,t),this.dirty=!0}startTrackingDeviceList(e){if(typeof e!="string")throw new Error("userId must be a string; was "+e);this.deviceTrackingStatus[e]||(S.log("Now tracking device list for "+e),this.deviceTrackingStatus[e]=kn.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(e){this.deviceTrackingStatus[e]&&(S.log("No longer tracking device list for "+e),this.deviceTrackingStatus[e]=kn.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(var e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]=kn.NotTracked;this.dirty=!0}invalidateUserDeviceList(e){this.deviceTrackingStatus[e]&&(S.log("Marking device list outdated for",e),this.deviceTrackingStatus[e]=kn.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();var e=[];for(var t of Object.keys(this.deviceTrackingStatus)){var n=this.deviceTrackingStatus[t];n==kn.PendingDownload&&e.push(t)}return this.doKeyDownload(e)}setRawStoredDevicesForUser(e,t){if(this.devices[e]!==void 0)for(var[n,i]of Object.entries(this.devices[e])){var o=i.keys["curve25519:"+n];delete this.userByIdentityKey[o]}this.devices[e]=t;for(var[s,a]of Object.entries(t)){var l=a.keys["curve25519:"+s];this.userByIdentityKey[l]=e}}setRawStoredCrossSigningForUser(e,t){this.crossSigningInfo[e]=t}doKeyDownload(e){if(e.length===0)return Promise.resolve();var t=this.serialiser.updateDevicesForUsers(e,this.syncToken).then(()=>{n(!0)},i=>{throw S.error("Error downloading keys for "+e+":",i),n(!1),i});e.forEach(i=>{this.keyDownloadsInProgressByUser.set(i,t);var o=this.deviceTrackingStatus[i];o==kn.PendingDownload&&(this.deviceTrackingStatus[i]=kn.DownloadInProgress)});var n=i=>{this.emit(et.WillUpdateDevices,e,!this.hasFetched),e.forEach(o=>{if(this.dirty=!0,this.keyDownloadsInProgressByUser.get(o)!==t){S.log("Another update in the queue for",o,"- not marking up-to-date");return}this.keyDownloadsInProgressByUser.delete(o);var s=this.deviceTrackingStatus[o];s==kn.DownloadInProgress&&(i?(this.deviceTrackingStatus[o]=kn.UpToDate,S.log("Device list for",o,"now up to date")):this.deviceTrackingStatus[o]=kn.PendingDownload)}),this.saveIfDirty(),this.emit(et.DevicesUpdated,e,!this.hasFetched),this.hasFetched=!0};return t}}class m8{constructor(e,t,n){this.baseApis=e,this.olmDevice=t,this.deviceList=n,v(this,"downloadInProgress",!1),v(this,"keyDownloadsQueuedByUser",{}),v(this,"queuedQueryDeferred",void 0),v(this,"syncToken",void 0)}updateDevicesForUsers(e,t){return e.forEach(n=>{this.keyDownloadsQueuedByUser[n]=!0}),this.queuedQueryDeferred||(this.queuedQueryDeferred=Gs()),this.syncToken=t,this.downloadInProgress?(S.log("Queued key download for",e),this.queuedQueryDeferred.promise):this.doQueuedQueries()}doQueuedQueries(){var e=this;if(this.downloadInProgress)throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active");var t=Object.keys(this.keyDownloadsQueuedByUser);this.keyDownloadsQueuedByUser={};var n=this.queuedQueryDeferred;this.queuedQueryDeferred=void 0,S.log("Starting key download for",t),this.downloadInProgress=!0;var i={};this.syncToken&&(i.token=this.syncToken);for(var o=[],s=function(){var c=t.slice(a,a+e.deviceList.keyDownloadChunkSize);o.push(()=>e.baseApis.downloadKeysForUsers(c,i))},a=0;a<t.length;a+=this.deviceList.keyDownloadChunkSize)s();return L6(o,3).then(function(){var l=_(function*(c){var u=Object.assign({},...c.map(m=>m.device_keys||{})),d=Object.assign({},...c.map(m=>m.master_keys||{})),f=Object.assign({},...c.map(m=>m.self_signing_keys||{})),p=Object.assign({},...c.map(m=>m.user_signing_keys||{}));for(var h of t){yield As(5);try{yield e.processQueryResponseForUser(h,u[h],{master:d==null?void 0:d[h],self_signing:f==null?void 0:f[h],user_signing:p==null?void 0:p[h]})}catch(m){S.error("Error processing keys for ".concat(h,":"),m)}}});return function(c){return l.apply(this,arguments)}}()).then(()=>{S.log("Completed key download for "+t),this.downloadInProgress=!1,n==null||n.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()},l=>{S.warn("Error downloading keys for "+t+":",l),this.downloadInProgress=!1,n==null||n.reject(l)}),n.promise}processQueryResponseForUser(e,t,n){var i=this;return _(function*(){S.log("got device keys for "+e+":",t),S.log("got cross-signing keys for "+e+":",n);{var o={},s=i.deviceList.getRawStoredDevicesForUser(e);s&&Object.keys(s).forEach(c=>{var u=tn.fromStorage(s[c],c);o[c]=u}),yield g8(i.olmDevice,e,o,t||{},i.baseApis.getUserId(),i.baseApis.deviceId);var a={};Object.keys(o).forEach(c=>{a[c]=o[c].toStorage()}),i.deviceList.setRawStoredDevicesForUser(e,a)}if(n&&(n.master||n.self_signing||n.user_signing)){var l=i.deviceList.getStoredCrossSigningForUser(e)||new gi(e);l.setKeys(n),i.deviceList.setRawStoredCrossSigningForUser(e,l.toStorage()),i.deviceList.emit(et.UserCrossSigningUpdated,e)}})()}}function g8(r,e,t,n,i,o){return Wb.apply(this,arguments)}function Wb(){return Wb=_(function*(r,e,t,n,i,o){var s=!1;for(var a in t)if(t.hasOwnProperty(a)&&!(a in n)){if(e===i&&a===o){S.warn("Local device ".concat(a," missing from sync, skipping removal"));continue}S.log("Device "+e+":"+a+" has been removed"),delete t[a],s=!0}for(var l in n)if(n.hasOwnProperty(l)){var c=n[l];if(c.user_id!==e){S.warn("Mismatched user_id "+c.user_id+" in keys from "+e+":"+l);continue}if(c.device_id!==l){S.warn("Mismatched device_id "+c.device_id+" in keys from "+e+":"+l);continue}(yield y8(r,t,c))&&(s=!0)}return s}),Wb.apply(this,arguments)}function y8(r,e,t){return qb.apply(this,arguments)}function qb(){return qb=_(function*(r,e,t){if(!t.keys)return!1;var n=t.device_id,i=t.user_id,o="ed25519:"+n,s=t.keys[o];if(!s)return S.warn("Device "+i+":"+n+" has no ed25519 key"),!1;var a=t.unsigned||{},l=t.signatures||{};try{yield Sc(r,t,i,n,s)}catch(u){return S.warn("Unable to verify signature on device "+i+":"+n+":"+u),!1}var c;if(n in e){if(c=e[n],c.getFingerprint()!=s)return S.warn("Ed25519 key for device "+i+":"+n+" has changed"),!1}else e[n]=c=new tn(n);return c.keys=t.keys||{},c.algorithms=t.algorithms||[],c.unsigned=a,c.signatures=l,!0}),qb.apply(this,arguments)}var cN=new Map,Gb=new Map;class uN{constructor(e){v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"crypto",void 0),v(this,"olmDevice",void 0),v(this,"baseApis",void 0),this.userId=e.userId,this.deviceId=e.deviceId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis}prepareToEncrypt(e){}onRoomMembership(e,t,n){}}class dN{constructor(e){v(this,"userId",void 0),v(this,"crypto",void 0),v(this,"olmDevice",void 0),v(this,"baseApis",void 0),this.userId=e.userId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis}onRoomKeyEvent(e){return _(function*(){})()}importRoomKey(e,t){return _(function*(){})()}hasKeysForKeyRequest(e){return Promise.resolve(!1)}shareKeysWithDevice(e){throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm")}retryDecryptionFromSender(e){return _(function*(){return!1})()}}class S8 extends Error{constructor(e,t,n){super(e),this.devices=t,this.event=n,this.name="UnknownDeviceError",this.devices=t}}function fN(r,e,t){cN.set(r,e),Gb.set(r,t)}var b8=tn.DeviceVerification;class _8 extends uN{constructor(){super(...arguments),v(this,"sessionPrepared",!1),v(this,"prepPromise",null)}ensureSession(e){return this.prepPromise?this.prepPromise:this.sessionPrepared?Promise.resolve():(this.prepPromise=this.crypto.downloadKeys(e).then(()=>this.crypto.ensureOlmSessionsForUsers(e)).then(()=>{this.sessionPrepared=!0}).finally(()=>{this.prepPromise=null}),this.prepPromise)}encryptMessage(e,t,n){var i=this;return _(function*(){var o=yield e.getEncryptionTargetMembers(),s=o.map(function(h){return h.userId});yield i.ensureSession(s);var a={room_id:e.roomId,type:t,content:n},l={algorithm:wr,sender_key:i.olmDevice.deviceCurve25519Key,ciphertext:{}},c=[];for(var u of s){var d=i.crypto.getStoredDevicesForUser(u)||[];for(var f of d){var p=f.getIdentityKey();p!=i.olmDevice.deviceCurve25519Key&&f.verified!=b8.BLOCKED&&c.push(Ns(l.ciphertext,i.userId,i.deviceId,i.olmDevice,u,f,a))}}return Promise.all(c).then(()=>l)})()}}class E8 extends dN{decryptEvent(e){var t=this;return _(function*(){var n=e.getWireContent(),i=n.sender_key,o=n.ciphertext;if(!o)throw new cr(Dt.OLM_MISSING_CIPHERTEXT,"Missing ciphertext");if(!(t.olmDevice.deviceCurve25519Key in o))throw new cr(Dt.OLM_NOT_INCLUDED_IN_RECIPIENTS,"Not included in recipients");var s=o[t.olmDevice.deviceCurve25519Key],a;try{a=yield t.decryptMessage(i,s)}catch(d){throw new cr(Dt.OLM_BAD_ENCRYPTED_MESSAGE,"Bad Encrypted Message",{sender:i,err:d})}var l=JSON.parse(a);if(l.recipient!=t.userId)throw new cr(Dt.OLM_BAD_RECIPIENT,"Message was intended for "+l.recipient);if(l.recipient_keys.ed25519!=t.olmDevice.deviceEd25519Key)throw new cr(Dt.OLM_BAD_RECIPIENT_KEY,"Message not intended for this device",{intended:l.recipient_keys.ed25519,our_key:t.olmDevice.deviceEd25519Key});var c=t.crypto.deviceList.getUserByIdentityKey(wr,i);if(c==null){try{yield t.crypto.deviceList.downloadKeys([e.getSender()],!1)}catch(d){throw new cr(Dt.OLM_BAD_SENDER_CHECK_FAILED,"Could not verify sender identity",{sender:i,err:d})}c=t.crypto.deviceList.getUserByIdentityKey(wr,i)}if(c!==e.getSender()&&c!==void 0&&c!==null)throw new cr(Dt.OLM_BAD_SENDER,"Message claimed to be from "+e.getSender(),{real_sender:c});if(l.sender!=e.getSender())throw new cr(Dt.OLM_FORWARDED_MESSAGE,"Message forwarded from "+l.sender,{reported_sender:e.getSender()});if(l.room_id!==e.getRoomId())throw new cr(Dt.OLM_BAD_ROOM,"Message intended for room "+l.room_id,{reported_room:e.getRoomId()||"ROOM_ID_UNDEFINED"});var u=l.keys||{};return{clearEvent:l,senderCurve25519Key:i,claimedEd25519Key:u.ed25519||null}})()}decryptMessage(e,t){if(t.type!==0)return this.reallyDecryptMessage(e,t);var n=this.olmDevice.olmPrekeyPromise.then(()=>this.reallyDecryptMessage(e,t));return this.olmDevice.olmPrekeyPromise=n.catch(()=>{}),n}reallyDecryptMessage(e,t){var n=this;return _(function*(){var i=yield n.olmDevice.getSessionIdsForDevice(e),o={};for(var s of i)try{var a=yield n.olmDevice.decryptMessage(e,s,t.type,t.body);return S.log("Decrypted Olm message from "+e+" with session "+s),a}catch(u){var l=yield n.olmDevice.matchesSession(e,s,t.type,t.body);if(l)throw new Error("Error decrypting prekey message with existing session id "+s+": "+u.message);o[s]=u.message}if(t.type!==0)throw i.length===0?new Error("No existing sessions"):new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(o));var c;try{c=yield n.olmDevice.createInboundSession(e,t.type,t.body)}catch(u){throw o["(new)"]=u.message,new Error("Error decrypting prekey message: "+JSON.stringify(o))}return S.log("created new inbound Olm session ID "+c.session_id+" with "+e),c.payload})()}}fN(wr,_8,E8);function QC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function ZC(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?QC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):QC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var w8=500,lt=function(r){return r[r.Unsent=0]="Unsent",r[r.Sent=1]="Sent",r[r.CancellationPending=2]="CancellationPending",r[r.CancellationPendingAndWillResend=3]="CancellationPendingAndWillResend",r}({});class T8{constructor(e,t,n){this.baseApis=e,this.deviceId=t,this.cryptoStore=n,v(this,"sendOutgoingRoomKeyRequestsTimer",void 0),v(this,"sendOutgoingRoomKeyRequestsRunning",!1),v(this,"clientRunning",!0)}stop(){S.log("stopping OutgoingRoomKeyRequestManager"),this.clientRunning=!1}sendQueuedRequests(){this.startTimer()}queueRoomKeyRequest(e,t){var n=arguments,i=this;return _(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!1,s=yield i.cryptoStore.getOutgoingRoomKeyRequest(e);if(!s)yield i.cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:e,recipients:t,requestId:i.baseApis.makeTxnId(),state:lt.Unsent});else switch(s.state){case lt.CancellationPendingAndWillResend:case lt.Unsent:return;case lt.CancellationPending:{var a=o?lt.CancellationPendingAndWillResend:lt.Sent;yield i.cryptoStore.updateOutgoingRoomKeyRequest(s.requestId,lt.CancellationPending,{state:a,cancellationTxnId:i.baseApis.makeTxnId()});break}case lt.Sent:{if(o){var l=lt.CancellationPendingAndWillResend,c=yield i.cryptoStore.updateOutgoingRoomKeyRequest(s.requestId,lt.Sent,{state:l,cancellationTxnId:i.baseApis.makeTxnId(),requestTxnId:i.baseApis.makeTxnId()});if(!c)return i.queueRoomKeyRequest(e,t,o);try{yield i.sendOutgoingRoomKeyRequestCancellation(c,!0)}catch(u){S.error("Error sending room key request cancellation; will retry later.",u)}}break}default:throw new Error("unhandled state: "+s.state)}})()}cancelRoomKeyRequest(e){return this.cryptoStore.getOutgoingRoomKeyRequest(e).then(t=>{if(t)switch(t.state){case lt.CancellationPending:case lt.CancellationPendingAndWillResend:return;case lt.Unsent:return S.log("deleting unnecessary room key request for "+ph(e)),this.cryptoStore.deleteOutgoingRoomKeyRequest(t.requestId,lt.Unsent);case lt.Sent:return this.cryptoStore.updateOutgoingRoomKeyRequest(t.requestId,lt.Sent,{state:lt.CancellationPending,cancellationTxnId:this.baseApis.makeTxnId()}).then(n=>{if(!n){S.log("Tried to cancel room key request for "+ph(e)+" but it was already cancelled in another tab");return}this.sendOutgoingRoomKeyRequestCancellation(n).catch(i=>{S.error("Error sending room key request cancellation; will retry later.",i),this.startTimer()})});default:throw new Error("unhandled state: "+t.state)}})}getOutgoingSentRoomKeyRequest(e,t){return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e,t,[lt.Sent])}cancelAndResendAllOutgoingRequests(){var e=this;return _(function*(){var t=yield e.cryptoStore.getAllOutgoingRoomKeyRequestsByState(lt.Sent);return Promise.all(t.map(n=>{var{requestBody:i,recipients:o}=n;return e.queueRoomKeyRequest(i,o,!0)}))})()}startTimer(){if(!this.sendOutgoingRoomKeyRequestsTimer){var e=()=>{if(this.sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");this.sendOutgoingRoomKeyRequestsRunning=!0,this.sendOutgoingRoomKeyRequests().finally(()=>{this.sendOutgoingRoomKeyRequestsRunning=!1}).catch(t=>{S.warn("error in OutgoingRoomKeyRequestManager: ".concat(t))})};this.sendOutgoingRoomKeyRequestsTimer=setTimeout(e,w8)}}sendOutgoingRoomKeyRequests(){var e=this;return _(function*(){if(!e.clientRunning){e.sendOutgoingRoomKeyRequestsTimer=void 0;return}var t=yield e.cryptoStore.getOutgoingRoomKeyRequestByState([lt.CancellationPending,lt.CancellationPendingAndWillResend,lt.Unsent]);if(!t){e.sendOutgoingRoomKeyRequestsTimer=void 0;return}try{switch(t.state){case lt.Unsent:yield e.sendOutgoingRoomKeyRequest(t);break;case lt.CancellationPending:yield e.sendOutgoingRoomKeyRequestCancellation(t);break;case lt.CancellationPendingAndWillResend:yield e.sendOutgoingRoomKeyRequestCancellation(t,!0);break}return e.sendOutgoingRoomKeyRequests()}catch(n){S.error("Error sending room key request; will retry later.",n),e.sendOutgoingRoomKeyRequestsTimer=void 0}})()}sendOutgoingRoomKeyRequest(e){S.log("Requesting keys for ".concat(ph(e.requestBody))+" from ".concat(ek(e.recipients))+"(id ".concat(e.requestId,")"));var t={action:"request",requesting_device_id:this.deviceId,request_id:e.requestId,body:e.requestBody};return this.sendMessageToDevices(t,e.recipients,e.requestTxnId||e.requestId).then(()=>this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,lt.Unsent,{state:lt.Sent}))}sendOutgoingRoomKeyRequestCancellation(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;S.log("Sending cancellation for key request for "+"".concat(ph(e.requestBody)," to ")+"".concat(ek(e.recipients)," ")+"(cancellation id ".concat(e.cancellationTxnId,")"));var n={action:"request_cancellation",requesting_device_id:this.deviceId,request_id:e.requestId};return this.sendMessageToDevices(n,e.recipients,e.cancellationTxnId).then(()=>t?this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,lt.CancellationPendingAndWillResend,{state:lt.Unsent}):this.cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,lt.CancellationPending))}sendMessageToDevices(e,t,n){var i=new qt(()=>new Map);for(var o of t){var s=i.getOrCreate(o.userId);s.set(o.deviceId,ZC(ZC({},e),{},{[en]:_i()}))}return this.baseApis.sendToDevice(V.RoomKeyRequest,i,n)}}function ph(r){return r.room_id+" / "+r.session_id}function ek(r){return"[".concat(r.map(e=>"".concat(e.userId,":").concat(e.deviceId)).join(","),"]")}function tk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function rk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?tk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):tk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function R8(r){var e,t,n=r==null||(e=r.currentState)===null||e===void 0?void 0:e.getStateEvents("m.room.history_visibility",""),i=n==null||(t=n.getContent())===null||t===void 0?void 0:t.history_visibility;return["world_readable","shared"].includes(i)}var C8=r=>typeof r.ciphertext=="string"?!!r.ciphertext.length:!!Object.keys(r.ciphertext).length;class k8{constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.sessionId=e,this.sharedHistory=t,v(this,"useCount",0),v(this,"creationTime",void 0),v(this,"sharedWithDevices",new qt(()=>new Map)),v(this,"blockedDevicesNotified",new qt(()=>new Map)),this.creationTime=new Date().getTime()}needsRotation(e,t){var n=new Date().getTime()-this.creationTime;return this.useCount>=e||n>=t?(S.log("Rotating megolm session after "+this.useCount+" messages, "+n+"ms"),!0):!1}markSharedWithDevice(e,t,n,i){this.sharedWithDevices.getOrCreate(e).set(t,{deviceKey:n,messageIndex:i})}markNotifiedBlockedDevice(e,t){this.blockedDevicesNotified.getOrCreate(e).set(t,!0)}sharedWithTooManyDevices(e){for(var[t,n]of this.sharedWithDevices){if(!e.has(t))return S.log("Starting new megolm session because we shared with "+t),!0;for(var[i]of n){var o;if(!((o=e.get(t))!==null&&o!==void 0&&o.get(i)))return S.log("Starting new megolm session because we shared with "+t+":"+i),!0}}return!1}}class I8 extends uN{constructor(e){var t,n,i,o;super(e),v(this,"setupPromise",Promise.resolve(null)),v(this,"outboundSessions",{}),v(this,"sessionRotationPeriodMsgs",void 0),v(this,"sessionRotationPeriodMs",void 0),v(this,"encryptionPreparation",void 0),v(this,"roomId",void 0),v(this,"prefixedLogger",void 0),this.roomId=e.roomId,this.prefixedLogger=S.getChild("[".concat(this.roomId," encryption]")),this.sessionRotationPeriodMsgs=(t=(n=e.config)===null||n===void 0?void 0:n.rotation_period_msgs)!==null&&t!==void 0?t:100,this.sessionRotationPeriodMs=(i=(o=e.config)===null||o===void 0?void 0:o.rotation_period_ms)!==null&&i!==void 0?i:7*24*3600*1e3}ensureOutboundSession(e,t,n){var i=arguments,o=this;return _(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!1,a=function(){var c=_(function*(u){var d=R8(e),f=yield o.prepareSession(t,d,u);return yield o.shareSession(t,d,s,n,f),f});return function(d){return c.apply(this,arguments)}}(),l=o.setupPromise.then(a);return o.setupPromise=l.catch(c=>(o.prefixedLogger.error("Failed to setup outbound session",c),null)),l})()}prepareSession(e,t,n){var i=this;return _(function*(){var o,s;return n&&t!==n.sharedHistory&&(n=null),(o=n)!==null&&o!==void 0&&o.needsRotation(i.sessionRotationPeriodMsgs,i.sessionRotationPeriodMs)&&(i.prefixedLogger.debug("Starting new megolm session because we need to rotate."),n=null),(s=n)!==null&&s!==void 0&&s.sharedWithTooManyDevices(e)&&(n=null),n||(i.prefixedLogger.debug("Starting new megolm session"),n=yield i.prepareNewSession(t),i.prefixedLogger.debug("Started new megolm session ".concat(n.sessionId)),i.outboundSessions[n.sessionId]=n),n})()}shareSession(e,t,n,i,o){var s=this;return _(function*(){var a={};for(var[l,c]of e)for(var[u,d]of c){var f,p=d.getIdentityKey();p!=s.olmDevice.deviceCurve25519Key&&((f=o.sharedWithDevices.get(l))!==null&&f!==void 0&&f.get(u)||(a[l]=a[l]||[],a[l].push(d)))}var h=s.olmDevice.getOutboundGroupSessionKey(o.sessionId),m={type:"m.room_key",content:{algorithm:bn,room_id:s.roomId,session_id:o.sessionId,session_key:h.key,chain_index:h.chain_index,"org.matrix.msc3061.shared_history":t}},[w,g]=yield eN(s.olmDevice,s.baseApis,a);yield Promise.all([_(function*(){var b=Array.from(g.entries()).map(R=>{var[k,O]=R;return Array.from(O.entries()).map(T=>{var[x,C]=T;return"".concat(k,"/").concat(x,": ").concat(C.sessionId)})}).flat(1);s.prefixedLogger.debug("Sharing keys with devices with existing Olm sessions:",b),yield s.shareKeyWithOlmSessions(o,h,m,g),s.prefixedLogger.debug("Shared keys with existing Olm sessions")})(),_(function*(){var b=Array.from(w.entries()).map(T=>{var[x,C]=T;return C.map(N=>"".concat(x,"/").concat(N.deviceId))}).flat(1);s.prefixedLogger.debug("Sharing keys (start phase 1) with devices without existing Olm sessions:",b);var R=[],k=Date.now(),O=[];yield s.shareKeyWithDevices(o,h,m,w,R,n?1e4:2e3,O),s.prefixedLogger.debug("Shared keys (end phase 1) with devices without existing Olm sessions"),!n&&Date.now()-k<1e4?_(function*(){var T=new qt(()=>[]),x=new Set;for(var C of O)x.add(C);var N=[];for(var{userId:F,deviceInfo:H}of R){var ie=F.slice(F.indexOf(":")+1);x.has(ie)?T.getOrCreate(F).push(H):N.push({userId:F,deviceInfo:H})}var $=Array.from(T.entries()).map(X=>{var[oe,re]=X;return re.map(ae=>"".concat(oe,"/").concat(ae.deviceId))}).flat(1);$.length>0&&(s.prefixedLogger.debug("Sharing keys (start phase 2) with devices without existing Olm sessions:",$),yield s.shareKeyWithDevices(o,h,m,T,N,3e4),s.prefixedLogger.debug("Shared keys (end phase 2) with devices without existing Olm sessions")),yield s.notifyFailedOlmDevices(o,h,N)})():yield s.notifyFailedOlmDevices(o,h,R)})(),_(function*(){s.prefixedLogger.debug("There are ".concat(i.size," blocked devices:"),Array.from(i.entries()).map(N=>{var[F,H]=N;return Array.from(H.entries()).map(ie=>{var[$,X]=ie;return"".concat(F,"/").concat($)})}).flat(1));var b=new qt(()=>new Map),R=0;for(var[k,O]of i)for(var[T,x]of O){var C;((C=o.blockedDevicesNotified.get(k))===null||C===void 0?void 0:C.get(T))===void 0&&(b.getOrCreate(k).set(T,{device:x}),R++)}R&&(s.prefixedLogger.debug("Notifying ".concat(R," newly blocked devices:"),Array.from(b.entries()).map(N=>{var[F,H]=N;return Object.entries(H).map(ie=>{var[$,X]=ie;return"".concat(F,"/").concat($)})}).flat(1)),yield s.notifyBlockedDevices(o,b),s.prefixedLogger.debug("Notified ".concat(R," newly blocked devices")))})()])})()}prepareNewSession(e){var t=this;return _(function*(){var n=t.olmDevice.createOutboundGroupSession(),i=t.olmDevice.getOutboundGroupSessionKey(n);return yield t.olmDevice.addInboundGroupSession(t.roomId,t.olmDevice.deviceCurve25519Key,[],n,i.key,{ed25519:t.olmDevice.deviceEd25519Key},!1,{sharedHistory:e}),t.crypto.backupManager.backupGroupSession(t.olmDevice.deviceCurve25519Key,n),new k8(n,e)})()}getDevicesWithoutSessions(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];for(var[i,o]of t){var s=e.get(i);for(var a of o){var l=a.deviceId,c=s==null?void 0:s.get(l);if(!(c!=null&&c.sessionId)){n.push({userId:i,deviceInfo:a}),s==null||s.delete(l);continue}}}return n}splitDevices(e){var t=20,n=[],i=[n];for(var[o,s]of e){for(var a of s.values())n.push({userId:o,deviceInfo:a.device});n.length>t&&(n=[],i.push(n))}return n.length===0&&i.pop(),i}encryptAndSendKeysToDevices(e,t,n,i){return this.crypto.encryptAndSendToDevices(n,i).then(()=>{for(var o of n)e.markSharedWithDevice(o.userId,o.deviceInfo.deviceId,o.deviceInfo.getIdentityKey(),t)}).catch(o=>{throw this.prefixedLogger.error("failed to encryptAndSendToDevices",o),o})}sendBlockedNotificationsToDevices(e,t,n){var i=this;return _(function*(){var o=new qt(()=>new Map);for(var s of t){var a=s.userId,l=s.deviceInfo,c=l.deviceInfo,u=c.deviceId,d=rk(rk({},n),{},{code:l.code,reason:l.reason,[en]:_i()});d.code==="m.no_olm"&&(delete d.room_id,delete d.session_id),o.getOrCreate(a).set(u,d)}yield i.baseApis.sendToDevice("m.room_key.withheld",o);for(var[f,p]of o)for(var h of p.keys())e.markNotifiedBlockedDevice(f,h)})()}reshareKeyWithDevice(e,t,n,i){var o=this;return _(function*(){var s,a=o.outboundSessions[t];if(!a){o.prefixedLogger.debug("megolm session ".concat(e,"|").concat(t," not found: not re-sharing keys"));return}if(!a.sharedWithDevices.has(n)){o.prefixedLogger.debug("megolm session ".concat(e,"|").concat(t," never shared with user ").concat(n));return}var l=(s=a.sharedWithDevices.get(n))===null||s===void 0?void 0:s.get(i.deviceId);if(l===void 0){o.prefixedLogger.debug("megolm session ".concat(e,"|").concat(t," never shared with device ").concat(n,":").concat(i.deviceId));return}if(l.deviceKey!==i.getIdentityKey()){o.prefixedLogger.warn("Megolm session ".concat(e,"|").concat(t," has been shared with device ").concat(i.deviceId," but ")+"with identity key ".concat(l.deviceKey,". Key is now ").concat(i.getIdentityKey(),"!"));return}var c=yield o.olmDevice.getInboundGroupSessionKey(o.roomId,e,t,l.messageIndex);if(!c){o.prefixedLogger.warn("No inbound session key found for megolm session ".concat(e,"|").concat(t,": not re-sharing keys"));return}yield Io(o.olmDevice,o.baseApis,new Map([[n,[i]]]));var u={type:"m.forwarded_room_key",content:{algorithm:bn,room_id:o.roomId,session_id:t,session_key:c.key,chain_index:c.chain_index,sender_key:e,sender_claimed_ed25519_key:c.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:c.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":c.shared_history||!1}},d={algorithm:wr,sender_key:o.olmDevice.deviceCurve25519Key,ciphertext:{},[en]:_i()};yield Ns(d.ciphertext,o.userId,o.deviceId,o.olmDevice,n,i,u),yield o.baseApis.sendToDevice("m.room.encrypted",new Map([[n,new Map([[i.deviceId,d]])]])),o.prefixedLogger.debug("Re-shared key for megolm session ".concat(e,"|").concat(t," with ").concat(n,":").concat(i.deviceId))})()}shareKeyWithDevices(e,t,n,i,o,s,a){var l=this;return _(function*(){var c=yield Io(l.olmDevice,l.baseApis,i,!1,s,a,l.prefixedLogger);l.getDevicesWithoutSessions(c,i,o),yield l.shareKeyWithOlmSessions(e,t,n,c)})()}shareKeyWithOlmSessions(e,t,n,i){var o=this;return _(function*(){for(var s=o.splitDevices(i),a=0;a<s.length;a++){var l="megolm keys for ".concat(e.sessionId," (slice ").concat(a+1,"/").concat(s.length,")");try{o.prefixedLogger.debug("Sharing ".concat(l),s[a].map(c=>"".concat(c.userId,"/").concat(c.deviceInfo.deviceId))),yield o.encryptAndSendKeysToDevices(e,t.chain_index,s[a],n),o.prefixedLogger.debug("Shared ".concat(l))}catch(c){throw o.prefixedLogger.error("Failed to share ".concat(l)),c}}})()}notifyFailedOlmDevices(e,t,n){var i=this;return _(function*(){i.prefixedLogger.debug("Notifying ".concat(n.length," devices we failed to create Olm sessions"));for(var{userId:o,deviceInfo:s}of n){var a=s.deviceId;e.markSharedWithDevice(o,a,s.getIdentityKey(),t.chain_index)}var l=yield i.olmDevice.filterOutNotifiedErrorDevices(n);i.prefixedLogger.debug("Need to notify ".concat(l.length," failed devices which haven't been notified before"));var c=new qt(()=>new Map);for(var{userId:u,deviceInfo:d}of l)c.getOrCreate(u).set(d.deviceId,{device:{code:"m.no_olm",reason:iv["m.no_olm"],deviceInfo:d}});yield i.notifyBlockedDevices(e,c),i.prefixedLogger.debug("Notified ".concat(l.length," devices we failed to create Olm sessions"))})()}notifyBlockedDevices(e,t){var n=this;return _(function*(){for(var i={room_id:n.roomId,session_id:e.sessionId,algorithm:bn,sender_key:n.olmDevice.deviceCurve25519Key},o=n.splitDevices(t),s=0;s<o.length;s++)try{yield n.sendBlockedNotificationsToDevices(e,o[s],i),n.prefixedLogger.debug("Completed blacklist notification for ".concat(e.sessionId," ")+"(slice ".concat(s+1,"/").concat(o.length,")"))}catch(a){throw n.prefixedLogger.debug("blacklist notification for ".concat(e.sessionId," ")+"(slice ".concat(s+1,"/").concat(o.length,") failed")),a}})()}prepareToEncrypt(e){var t=this;if(e.roomId!==this.roomId)throw new Error("MegolmEncryption.prepareToEncrypt called on unexpected room");if(this.encryptionPreparation!=null){var n=Date.now()-this.encryptionPreparation.startTime;return this.prefixedLogger.debug("Already started preparing to encrypt for this room ".concat(n,"ms ago, skipping")),this.encryptionPreparation.cancel}this.prefixedLogger.debug("Preparing to encrypt events");var i=!1,o=()=>i;return this.encryptionPreparation={startTime:Date.now(),promise:_(function*(){try{var s=yield t.getDevicesInRoom(e,!1,o);if(s===null)return;var[a,l]=s;t.crypto.globalErrorOnUnknownDevices&&t.removeUnknownDevices(a),t.prefixedLogger.debug("Ensuring outbound megolm session"),yield t.ensureOutboundSession(e,a,l,!0),t.prefixedLogger.debug("Ready to encrypt events")}catch(c){t.prefixedLogger.error("Failed to prepare to encrypt events",c)}finally{delete t.encryptionPreparation}})(),cancel:()=>{i=!0,delete this.encryptionPreparation}},this.encryptionPreparation.cancel}encryptMessage(e,t,n){var i=this;return _(function*(){if(i.prefixedLogger.debug("Starting to encrypt event"),i.encryptionPreparation!=null)try{yield i.encryptionPreparation.promise}catch{}var o=i.isVerificationEvent(t,n),[s,a]=yield i.getDevicesInRoom(e,o);i.crypto.globalErrorOnUnknownDevices&&i.checkForUnknownDevices(s);var l=yield i.ensureOutboundSession(e,s,a),c={room_id:i.roomId,type:t,content:n},u=i.olmDevice.encryptGroupMessage(l.sessionId,JSON.stringify(c)),d={algorithm:bn,sender_key:i.olmDevice.deviceCurve25519Key,ciphertext:u,session_id:l.sessionId,device_id:i.deviceId};return l.useCount++,d})()}isVerificationEvent(e,t){switch(e){case V.KeyVerificationCancel:case V.KeyVerificationDone:case V.KeyVerificationMac:case V.KeyVerificationStart:case V.KeyVerificationKey:case V.KeyVerificationReady:case V.KeyVerificationAccept:return!0;case V.RoomMessage:return t.msgtype===xi.KeyVerificationRequest;default:return!1}}forceDiscardSession(){this.setupPromise=this.setupPromise.then(()=>null)}checkForUnknownDevices(e){var t=new qt(()=>new Map);for(var[n,i]of e)for(var[o,s]of i)s.isUnverified()&&!s.isKnown()&&t.getOrCreate(n).set(o,s);if(t.size)throw new S8("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",t)}removeUnknownDevices(e){for(var[t,n]of e){for(var[i,o]of n)o.isUnverified()&&!o.isKnown()&&n.delete(i);n.size===0&&e.delete(t)}}getDevicesInRoom(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2?t[2]:void 0,s=yield e.getEncryptionTargetMembers();n.prefixedLogger.debug("Encrypting for users (shouldEncryptForInvitedMembers: ".concat(e.shouldEncryptForInvitedMembers(),"):"),s.map(R=>"".concat(R.userId," (").concat(R.membership,")")));var a=s.map(function(R){return R.userId}),l=n.crypto.globalBlacklistUnverifiedDevices,c=e.getBlacklistUnverifiedDevices();typeof c=="boolean"&&(l=c);var u=yield n.crypto.downloadKeys(a,!1);if((o==null?void 0:o())===!0)return null;var d=new qt(()=>new Map);for(var[f,p]of u)for(var[h,m]of p){if(o!==void 0&&(yield N6()),(o==null?void 0:o())===!0)return null;var w=n.crypto.checkDeviceTrust(f,h);if(m.isBlocked()||!w.isVerified()&&l&&!i){var g=d.getOrCreate(f),b=m.isBlocked();g.set(h,{code:b?"m.blacklisted":"m.unverified",reason:iv[b?"m.blacklisted":"m.unverified"],deviceInfo:m}),p.delete(h)}}return[u,d]})()}}class x8 extends dN{constructor(e){super(e),v(this,"pendingEvents",new Map),v(this,"olmlib",Jz),v(this,"roomId",void 0),v(this,"prefixedLogger",void 0),this.roomId=e.roomId,this.prefixedLogger=S.getChild("[".concat(this.roomId," decryption]"))}decryptEvent(e){var t=this;return _(function*(){var n=e.getWireContent();if(!n.sender_key||!n.session_id||!n.ciphertext)throw new cr(Dt.MEGOLM_MISSING_FIELDS,"Missing fields in input");t.addEventToPendingList(e);var i;try{i=yield t.olmDevice.decryptGroupMessage(e.getRoomId(),n.sender_key,n.session_id,n.ciphertext,e.getId(),e.getTs())}catch(c){if(c.name==="DecryptionError")throw c;var o=Dt.OLM_DECRYPT_GROUP_MESSAGE_ERROR;throw(c==null?void 0:c.message)==="OLM.UNKNOWN_MESSAGE_INDEX"&&(t.requestKeysForEvent(e),o=Dt.OLM_UNKNOWN_MESSAGE_INDEX),new cr(o,c instanceof Error?c.message:"Unknown Error: Error is undefined",{session:n.sender_key+"|"+n.session_id})}if(i===null){t.crypto.backupManager.queryKeyBackupRateLimited(e.getRoomId(),n.session_id).catch(()=>{}),t.requestKeysForEvent(e);var s=yield t.olmDevice.sessionMayHaveProblems(n.sender_key,e.getTs()-12e4);if(s){t.prefixedLogger.info("When handling UISI from ".concat(e.getSender()," (sender key ").concat(n.sender_key,"): ")+"recent session problem with that sender:",s);var a=nk[s.type]||nk.unknown;throw s.fixed&&(a+=" Trying to create a new secure channel and re-requesting the keys."),new cr(Dt.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,a,{session:n.sender_key+"|"+n.session_id})}throw new cr(Dt.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,"The sender's device has not sent us the keys for this message.",{session:n.sender_key+"|"+n.session_id})}i.untrusted||t.removeEventFromPendingList(e);var l=JSON.parse(i.result);if(l.room_id!==e.getRoomId())throw new cr(Dt.MEGOLM_BAD_ROOM,"Message intended for room "+l.room_id);return{clearEvent:l,senderCurve25519Key:i.senderKey,claimedEd25519Key:i.keysClaimed.ed25519,forwardingCurve25519KeyChain:i.forwardingCurve25519KeyChain,untrusted:i.untrusted}})()}requestKeysForEvent(e){var t=e.getWireContent(),n=e.getKeyRequestRecipients(this.userId);this.crypto.requestRoomKey({room_id:e.getRoomId(),algorithm:t.algorithm,sender_key:t.sender_key,session_id:t.session_id},n)}addEventToPendingList(e){var t,n=e.getWireContent(),i=n.sender_key,o=n.session_id;this.pendingEvents.has(i)||this.pendingEvents.set(i,new Map);var s=this.pendingEvents.get(i);s.has(o)||s.set(o,new Set),(t=s.get(o))===null||t===void 0||t.add(e)}removeEventFromPendingList(e){var t=e.getWireContent(),n=t.sender_key,i=t.session_id,o=this.pendingEvents.get(n),s=o==null?void 0:o.get(i);s&&(s.delete(e),s.size===0&&o.delete(i),o.size===0&&this.pendingEvents.delete(n))}roomKeyFromEvent(e){var t=e.getSenderKey(),n=e.getContent(),i={};if(!n.room_id||!n.session_key||!n.session_id||!n.algorithm){this.prefixedLogger.error("key event is missing fields");return}if(!ww(e)){this.prefixedLogger.error("key event not properly encrypted");return}n["org.matrix.msc3061.shared_history"]&&(i.sharedHistory=!0);var o={senderKey:t,sessionId:n.session_id,sessionKey:n.session_key,extraSessionData:i,exportFormat:!1,roomId:n.room_id,algorithm:n.algorithm,forwardingKeyChain:[],keysClaimed:e.getKeysClaimed()};return o}forwardedRoomKeyFromEvent(e){var t=this.roomKeyFromEvent(e);if(t){var n=e.getSenderKey(),i=e.getContent(),o=this.baseApis.crypto.deviceList.getUserByIdentityKey(wr,n),s=i.sender_key,a=i.sender_claimed_ed25519_key,l=Array.isArray(i.forwarding_curve25519_key_chain)?i.forwarding_curve25519_key_chain:[];if(l=l.slice(),l.push(n),o!==e.getSender()){this.prefixedLogger.error("sending device does not belong to the user it claims to be from");return}if(!s){this.prefixedLogger.error("forwarded_room_key event is missing sender_key field");return}if(!a){this.prefixedLogger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");return}var c={ed25519:a};return t.senderKey=s,t.keysClaimed=c,t.exportFormat=!0,t.forwardingKeyChain=l,t.extraSessionData.untrusted=!0,t}}shouldAcceptForwardedKey(e,t){var n=this;return _(function*(){var i,o=e.getSenderKey(),s=(i=n.crypto.deviceList.getDeviceByIdentityKey(wr,o))!==null&&i!==void 0?i:void 0,a=n.crypto.checkDeviceInfoTrust(e.getSender(),s),l=e.getSender()===n.baseApis.getUserId(),c=a.isVerified()&&l,u=yield n.wasRoomKeyRequested(e,t),d=n.wasRoomKeyForwardedByInviter(e,t),f=n.wasRoomKeyForwardedAsHistory(t);return u&&c||d&&f})()}wasRoomKeyRequested(e,t){var n=this;return _(function*(){var i=yield n.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e.getSender(),"*",[lt.Sent]);return i.some(o=>o.requestBody.room_id===t.roomId&&o.requestBody.session_id===t.sessionId)})()}wasRoomKeyForwardedByInviter(e,t){var n,i,o,s=this.baseApis.getRoom(t.roomId),a=e.getSenderKey();if(!a)return!1;var l=this.crypto.deviceList.getUserByIdentityKey(wr,a);if(!l)return!1;var c=s==null||(n=s.getMember(this.userId))===null||n===void 0?void 0:n.events.member,u=(c==null?void 0:c.getSender())===l||(c==null||(i=c.getUnsigned())===null||i===void 0?void 0:i.prev_sender)===l&&(c==null||(o=c.getPrevContent())===null||o===void 0?void 0:o.membership)===Be.Invite;return!!(s&&u)}wasRoomKeyForwardedAsHistory(e){var t=this.baseApis.getRoom(e.roomId);return!!(t&&e.extraSessionData.sharedHistory)}shouldParkForwardedKey(e){var t=this.baseApis.getRoom(e.roomId);return!!(!t&&e.extraSessionData.sharedHistory)}parkForwardedKey(e,t){var n=this;return _(function*(){var i={senderId:e.getSender(),senderKey:t.senderKey,sessionId:t.sessionId,sessionKey:t.sessionKey,keysClaimed:t.keysClaimed,forwardingCurve25519KeyChain:t.forwardingKeyChain};yield n.crypto.cryptoStore.doTxn("readwrite",["parked_shared_history"],o=>n.crypto.cryptoStore.addParkedSharedHistory(t.roomId,i,o),S.getChild("[addParkedSharedHistory]"))})()}addRoomKey(e){var t=this;return _(function*(){try{yield t.olmDevice.addInboundGroupSession(e.roomId,e.senderKey,e.forwardingKeyChain,e.sessionId,e.sessionKey,e.keysClaimed,e.exportFormat,e.extraSessionData),(yield t.retryDecryption(e.senderKey,e.sessionId,!e.extraSessionData.untrusted))&&t.crypto.cancelRoomKeyRequest({algorithm:e.algorithm,room_id:e.roomId,session_id:e.sessionId,sender_key:e.senderKey}),yield t.crypto.backupManager.backupGroupSession(e.senderKey,e.sessionId)}catch(n){t.prefixedLogger.error("Error handling m.room_key_event: ".concat(n))}})()}onForwardedRoomKey(e){var t=this;return _(function*(){var n=t.forwardedRoomKeyFromEvent(e);n&&((yield t.shouldAcceptForwardedKey(e,n))?yield t.addRoomKey(n):t.shouldParkForwardedKey(n)&&(yield t.parkForwardedKey(e,n)))})()}onRoomKeyEvent(e){var t=this;return _(function*(){if(e.getType()=="m.forwarded_room_key")yield t.onForwardedRoomKey(e);else{var n=t.roomKeyFromEvent(e);if(!n)return;yield t.addRoomKey(n)}})()}onRoomKeyWithheldEvent(e){var t=this;return _(function*(){var n=e.getContent(),i=n.sender_key;n.code==="m.no_olm"?yield t.onNoOlmWithheldEvent(e):n.code==="m.unavailable"||(yield t.olmDevice.addInboundGroupSessionWithheld(n.room_id,i,n.session_id,n.code,n.reason)),n.session_id?yield t.retryDecryption(i,n.session_id):yield t.retryDecryptionFromSender(i)})()}onNoOlmWithheldEvent(e){var t=this;return _(function*(){var n=e.getContent(),i=n.sender_key,o=e.getSender();if(t.prefixedLogger.warn("".concat(o,":").concat(i," was unable to establish an olm session with us")),yield t.olmDevice.getSessionIdForDevice(i)){t.prefixedLogger.debug("New session already created. Not creating a new one."),yield t.olmDevice.recordSessionProblem(i,"no_olm",!0);return}var s=t.crypto.deviceList.getDeviceByIdentityKey(n.algorithm,i);if(!s&&(yield t.crypto.downloadKeys([o],!1),s=t.crypto.deviceList.getDeviceByIdentityKey(n.algorithm,i),!s)){t.prefixedLogger.info("Couldn't find device for identity key "+i+": not establishing session"),yield t.olmDevice.recordSessionProblem(i,"no_olm",!1);return}yield Io(t.olmDevice,t.baseApis,new Map([[o,[s]]]),!1);var a={algorithm:wr,sender_key:t.olmDevice.deviceCurve25519Key,ciphertext:{},[en]:_i()};yield Ns(a.ciphertext,t.userId,void 0,t.olmDevice,o,s,{type:"m.dummy"}),yield t.olmDevice.recordSessionProblem(i,"no_olm",!0),yield t.baseApis.sendToDevice("m.room.encrypted",new Map([[o,new Map([[s.deviceId,a]])]]))})()}hasKeysForKeyRequest(e){var t=e.requestBody;return this.olmDevice.hasInboundSessionKeys(t.room_id,t.sender_key,t.session_id)}shareKeysWithDevice(e){var t=e.userId,n=e.deviceId,i=this.crypto.getStoredDevice(t,n),o=e.requestBody;this.olmlib.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[t,[i]]])).then(s=>{var a,l=(a=s.get(t))===null||a===void 0?void 0:a.get(n);return l!=null&&l.sessionId?(this.prefixedLogger.debug("sharing keys for session "+o.sender_key+"|"+o.session_id+" with device "+t+":"+n),this.buildKeyForwardingMessage(o.room_id,o.sender_key,o.session_id)):null}).then(s=>{var a={algorithm:wr,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[en]:_i()};return this.olmlib.encryptMessageForDevice(a.ciphertext,this.userId,void 0,this.olmDevice,t,i,s).then(()=>this.baseApis.sendToDevice("m.room.encrypted",new Map([[t,new Map([[n,a]])]])))})}buildKeyForwardingMessage(e,t,n){var i=this;return _(function*(){var o=yield i.olmDevice.getInboundGroupSessionKey(e,t,n);return{type:"m.forwarded_room_key",content:{algorithm:bn,room_id:e,sender_key:t,sender_claimed_ed25519_key:o.sender_claimed_ed25519_key,session_id:n,session_key:o.key,chain_index:o.chain_index,forwarding_curve25519_key_chain:o.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":o.shared_history||!1}}})()}importRoomKey(e){var{untrusted:t,source:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i={};return(t||e.untrusted)&&(i.untrusted=!0),e["org.matrix.msc3061.shared_history"]&&(i.sharedHistory=!0),this.olmDevice.addInboundGroupSession(e.room_id,e.sender_key,e.forwarding_curve25519_key_chain,e.session_id,e.session_key,e.sender_claimed_keys,!0,i).then(()=>{n!=="backup"&&this.crypto.backupManager.backupGroupSession(e.sender_key,e.session_id).catch(o=>{this.prefixedLogger.debug("Failed to back up megolm session",o)}),this.retryDecryption(e.sender_key,e.session_id,!i.untrusted)})}retryDecryption(e,t,n){var i=this;return _(function*(){var o,s=i.pendingEvents.get(e);if(!s)return!0;var a=s.get(t);if(!a)return!0;var l=[...a];return i.prefixedLogger.debug("Retrying decryption on events:",l.map(c=>"".concat(c.getId()))),yield Promise.all(l.map(function(){var c=_(function*(u){try{yield u.attemptDecryption(i.crypto,{isRetry:!0,forceRedecryptIfUntrusted:n})}catch{}});return function(u){return c.apply(this,arguments)}}())),!((o=i.pendingEvents.get(e))!==null&&o!==void 0&&o.has(t))})()}retryDecryptionFromSender(e){var t=this;return _(function*(){var n=t.pendingEvents.get(e);return n?(t.pendingEvents.delete(e),yield Promise.all([...n].map(function(){var i=_(function*(o){var[s,a]=o;yield Promise.all([...a].map(function(){var l=_(function*(c){try{yield c.attemptDecryption(t.crypto)}catch{}});return function(c){return l.apply(this,arguments)}}()))});return function(o){return i.apply(this,arguments)}}())),!t.pendingEvents.has(e)):!0})()}sendSharedHistoryInboundSessions(e){var t=this;return _(function*(){yield Io(t.olmDevice,t.baseApis,e);var n=yield t.olmDevice.getSharedHistoryInboundGroupSessions(t.roomId);t.prefixedLogger.debug("Sharing history in with users ".concat(Array.from(e.keys())),n.map(b=>{var[R,k]=b;return"".concat(R,"|").concat(k)}));for(var[i,o]of n){var s=yield t.buildKeyForwardingMessage(t.roomId,i,o),a=[],l=new Map;for(var[c,u]of e){var d=new Map;l.set(c,d);for(var f of u){var p={algorithm:wr,sender_key:t.olmDevice.deviceCurve25519Key,ciphertext:{},[en]:_i()};d.set(f.deviceId,p),a.push(Ns(p.ciphertext,t.userId,void 0,t.olmDevice,c,f,s))}}yield Promise.all(a);for(var[h,m]of l){for(var[w,g]of m)C8(g)||(t.prefixedLogger.debug("No ciphertext for device "+h+":"+w+": pruning"),m.delete(w));m.size===0&&(t.prefixedLogger.debug("Pruned all devices for user "+h),l.delete(h))}if(l.size===0){t.prefixedLogger.debug("No users left to send to: aborting");return}yield t.baseApis.sendToDevice("m.room.encrypted",l)}})()}}var nk={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};fN(bn,I8,x8);class ik{constructor(e,t){v(this,"accountDataClientAdapter",void 0),v(this,"crossSigningCallbacks",void 0),v(this,"ssssCryptoCallbacks",void 0),v(this,"crossSigningKeys",void 0),v(this,"keySignatures",void 0),v(this,"keyBackupInfo",void 0),v(this,"sessionBackupPrivateKey",void 0),this.accountDataClientAdapter=new P8(e),this.crossSigningCallbacks=new M8,this.ssssCryptoCallbacks=new A8(t)}addCrossSigningKeys(e,t){this.crossSigningKeys={authUpload:e,keys:t}}addSessionBackup(e){this.keyBackupInfo=e}addSessionBackupPrivateKeyToCache(e){this.sessionBackupPrivateKey=e}addKeySignature(e,t,n){this.keySignatures||(this.keySignatures={});var i=this.keySignatures[e]||{};this.keySignatures[e]=i,i[t]=n}setAccountData(e,t){var n=this;return _(function*(){yield n.accountDataClientAdapter.setAccountData(e,t)})()}buildOperation(){var e=this.accountDataClientAdapter.values;return new O8(e,this.crossSigningKeys,this.keyBackupInfo,this.keySignatures)}persist(e){var t=this;return _(function*(){if(t.crossSigningKeys){var n=lN(e.cryptoStore,e.olmDevice);for(var i of["master","self_signing","user_signing"]){var o;S.log("Cache ".concat(i," cross-signing private key locally"));var s=t.crossSigningCallbacks.privateKeys.get(i);yield(o=n.storeCrossSigningKeyCache)===null||o===void 0?void 0:o.call(n,i,s)}yield e.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],a=>{e.cryptoStore.storeCrossSigningKeys(a,t.crossSigningKeys.keys)})}t.sessionBackupPrivateKey&&(yield e.storeSessionBackupPrivateKey(t.sessionBackupPrivateKey))})()}}class O8{constructor(e,t,n,i){this.accountData=e,this.crossSigningKeys=t,this.keyBackupInfo=n,this.keySignatures=i}apply(e){var t=this;return _(function*(){var n=e.baseApis;if(t.crossSigningKeys){var i,o,s={};for(var[a,l]of Object.entries(t.crossSigningKeys.keys))s[a+"_key"]=l;yield(i=(o=t.crossSigningKeys).authUpload)===null||i===void 0?void 0:i.call(o,d=>n.uploadDeviceSigningKeys(d??void 0,s)),e.crossSigningInfo.setKeys(t.crossSigningKeys.keys)}if(t.accountData)for(var[c,u]of t.accountData)yield n.setAccountData(c,u);t.keySignatures&&(yield n.uploadKeySignatures(t.keySignatures)),t.keyBackupInfo&&(t.keyBackupInfo.version?yield n.http.authedRequest(Z.Put,"/room_keys/version/"+t.keyBackupInfo.version,void 0,{algorithm:t.keyBackupInfo.algorithm,auth_data:t.keyBackupInfo.auth_data},{prefix:Ot.V3}):yield n.http.authedRequest(Z.Post,"/room_keys/version",void 0,t.keyBackupInfo,{prefix:Ot.V3}),yield e.backupManager.checkKeyBackup())})()}}class P8 extends Tt{constructor(e){super(),this.existingValues=e,v(this,"values",new Map)}getAccountDataFromServer(e){return Promise.resolve(this.getAccountData(e))}getAccountData(e){var t=this.values.get(e);if(t)return t;var n=this.existingValues.get(e);return n?n.getContent():null}setAccountData(e,t){var n=this.values.get(e);return this.values.set(e,t),Promise.resolve().then(()=>{var i=new pr({type:e,content:t});return this.emit(Te.AccountData,i,n),{}})}}class M8{constructor(){v(this,"privateKeys",new Map)}getCrossSigningKeyCache(e,t){return this.getCrossSigningKey(e,t)}storeCrossSigningKeyCache(e,t){return this.privateKeys.set(e,t),Promise.resolve()}getCrossSigningKey(e,t){var n;return Promise.resolve((n=this.privateKeys.get(e))!==null&&n!==void 0?n:null)}saveCrossSigningKeys(e){for(var[t,n]of Object.entries(e))this.privateKeys.set(t,n)}}class A8{constructor(e){this.delegateCryptoCallbacks=e,v(this,"privateKeys",new Map)}getSecretStorageKey(e,t){var n=this;return _(function*(){var i,{keys:o}=e;for(var s of Object.keys(o)){var a=n.privateKeys.get(s);if(a)return[s,a]}if(n!=null&&(i=n.delegateCryptoCallbacks)!==null&&i!==void 0&&i.getSecretStorageKey){var l=yield n.delegateCryptoCallbacks.getSecretStorageKey({keys:o},t);if(l){var[c,u]=l;n.privateKeys.set(c,u)}return l}return null})()}addPrivateKey(e,t,n){var i,o;this.privateKeys.set(e,n),(i=this.delegateCryptoCallbacks)===null||i===void 0||(o=i.cacheSecretStorageKey)===null||o===void 0||o.call(i,e,t,n)}}var Vi="m.secret_storage.v1.aes-hmac-sha2";class Kd{constructor(e,t){this.accountDataAdapter=e,this.callbacks=t}getDefaultKeyId(){var e=this;return _(function*(){var t=yield e.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return t?t.key:null})()}setDefaultKeyId(e){return new Promise((t,n)=>{var i=o=>{o.getType()==="m.secret_storage.default_key"&&o.getContent().key===e&&(this.accountDataAdapter.removeListener(Te.AccountData,i),t())};this.accountDataAdapter.on(Te.AccountData,i),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:e}).catch(o=>{this.accountDataAdapter.removeListener(Te.AccountData,i),n(o)})})}addKey(e,t,n){var i=this;return _(function*(){if(e!==Vi)throw new Error("Unknown key algorithm ".concat(e));var o={algorithm:e};t.name&&(o.name=t.name),t.passphrase&&(o.passphrase=t.passphrase);var{iv:s,mac:a}=yield Ca(t.key);if(o.iv=s,o.mac=a,!n)do n=Ei(32);while(yield i.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(n)));return yield i.accountDataAdapter.setAccountData("m.secret_storage.key.".concat(n),o),{keyId:n,keyInfo:o}})()}getKey(e){var t=this;return _(function*(){if(e||(e=yield t.getDefaultKeyId()),!e)return null;var n=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);return n?[e,n]:null})()}hasKey(e){var t=this;return _(function*(){var n=yield t.getKey(e);return!!n})()}checkKey(e,t){return _(function*(){if(t.algorithm===Vi)if(t.mac){var{mac:n}=yield Ca(e,t.iv);return Hb(t.mac)===Hb(n)}else return!0;else throw new Error("Unknown algorithm")})()}store(e,t,n){var i=this;return _(function*(){var o={};if(!n){var s=yield i.getDefaultKeyId();if(!s)throw new Error("No keys specified and no default key present");n=[s]}if(n.length===0)throw new Error("Zero keys given to encrypt with!");for(var a of n){var l=yield i.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+a);if(!l)throw new Error("Unknown key: "+a);if(l.algorithm===Vi){var c={[a]:l},[,u]=yield i.getSecretStorageKey(c,e);o[a]=yield u.encrypt(t)}else S.warn("unknown algorithm for secret storage key "+a+": "+l.algorithm)}yield i.accountDataAdapter.setAccountData(e,{encrypted:o})})()}get(e){var t=this;return _(function*(){var n=yield t.accountDataAdapter.getAccountDataFromServer(e);if(n){if(!n.encrypted)throw new Error("Content is not encrypted!");var i={};for(var o of Object.keys(n.encrypted)){var s=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+o),a=n.encrypted[o];(s==null?void 0:s.algorithm)===Vi&&a.iv&&a.ciphertext&&a.mac&&(i[o]=s)}if(Object.keys(i).length===0)throw new Error("Could not decrypt ".concat(e," because none of ")+"the keys it is encrypted with are for a supported algorithm");var[l,c]=yield t.getSecretStorageKey(i,e),u=n.encrypted[l];return c.decrypt(u)}})()}isStored(e){var t=this;return _(function*(){var n=yield t.accountDataAdapter.getAccountDataFromServer(e);if(!(n!=null&&n.encrypted))return null;var i={};for(var o of Object.keys(n.encrypted)){var s=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+o);if(s){var a=n.encrypted[o];s.algorithm===Vi&&a.iv&&a.ciphertext&&a.mac&&(i[o]=s)}}return Object.keys(i).length?i:null})()}getSecretStorageKey(e,t){var n=this;return _(function*(){if(!n.callbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");var i=yield n.callbacks.getSecretStorageKey({keys:e},t);if(!i)throw new Error("getSecretStorageKey callback returned falsey");if(i.length<2)throw new Error("getSecretStorageKey callback returned invalid data");var[o,s]=i;if(!e[o])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[o].algorithm===Vi){var a={encrypt:function(c){return Kc(c,s,t)},decrypt:function(c){return Ef(c,s,t)}};return[o,a]}else throw new Error("Unknown key type: "+e[o].algorithm)})()}}function Hb(r){for(var e=r.length;e>=1&&r.charCodeAt(e-1)==61;)e--;return e<r.length?r.substring(0,e):r}var D8="\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 Ca(r,e){return Kc(D8,r,"",e)}const N8=Object.freeze(Object.defineProperty({__proto__:null,SECRET_STORAGE_ALGORITHM_V1_AES:Vi,ServerSideSecretStorageImpl:Kd,calculateKeyCheck:Ca,trimTrailingEquals:Hb},Symbol.toStringTag,{value:"Module"}));class L8{constructor(e,t){this.baseApis=e,this.cryptoCallbacks=t,v(this,"requests",new Map)}request(e,t){var n=this.baseApis.makeTxnId(),i=Gs();this.requests.set(n,{name:e,devices:t,deferred:i});var o=c=>{var u={action:"request_cancellation",requesting_device_id:this.baseApis.deviceId,request_id:n},d=new Map;for(var f of t)d.set(f,u);this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),d]])),i.reject(new Error(c||"Cancelled"))},s={name:e,action:"request",requesting_device_id:this.baseApis.deviceId,request_id:n,[en]:_i()},a=new Map;for(var l of t)a.set(l,s);return S.info("Request secret ".concat(e," from ").concat(t,", id ").concat(n)),this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),a]])),{requestId:n,promise:i.promise,cancel:o}}onRequestReceived(e){var t=this;return _(function*(){var n=e.getSender(),i=e.getContent();if(!(n!==t.baseApis.getUserId()||!(i.name&&i.action&&i.requesting_device_id&&i.request_id))){var o=i.requesting_device_id;if(i.action!=="request_cancellation"){if(i.action==="request"){if(o===t.baseApis.deviceId||(S.info("received request for secret ("+n+", "+o+", "+i.request_id+")"),!t.cryptoCallbacks.onSecretRequested))return;var s=yield t.cryptoCallbacks.onSecretRequested(n,o,i.request_id,i.name,t.baseApis.checkDeviceTrust(n,o));if(s){S.info("Preparing ".concat(i.name," secret for ").concat(o));var a={type:"m.secret.send",content:{request_id:i.request_id,secret:s}},l={algorithm:wr,sender_key:t.baseApis.crypto.olmDevice.deviceCurve25519Key,ciphertext:{},[en]:_i()};yield Io(t.baseApis.crypto.olmDevice,t.baseApis,new Map([[n,[t.baseApis.getStoredDevice(n,o)]]])),yield Ns(l.ciphertext,t.baseApis.getUserId(),t.baseApis.deviceId,t.baseApis.crypto.olmDevice,n,t.baseApis.getStoredDevice(n,o),a);var c=new Map([[n,new Map([[o,l]])]]);S.info("Sending ".concat(i.name," secret for ").concat(o)),t.baseApis.sendToDevice("m.room.encrypted",c)}else S.info("Request denied for ".concat(i.name," secret for ").concat(o))}}}})()}onSecretReceived(e){if(e.getSender()===this.baseApis.getUserId()){if(!ww(e)){S.error("secret event not properly encrypted");return}var t=e.getContent(),n=this.baseApis.crypto.deviceList.getUserByIdentityKey(wr,e.getSenderKey()||"");if(n!==e.getSender()){S.error("sending device does not belong to the user it claims to be from");return}S.log("got secret share for request",t.request_id);var i=this.requests.get(t.request_id);if(i){var o=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(wr,e.getSenderKey());if(!o){S.log("secret share from unknown device with key",e.getSenderKey());return}if(!i.devices.includes(o.deviceId)){S.log("unsolicited secret share from device",o.deviceId);return}var s=this.baseApis.crypto.checkDeviceInfoTrust(e.getSender(),o);if(!s.isVerified()){S.log("secret share from unverified device");return}S.log("Successfully received secret ".concat(i.name," ")+"from ".concat(o.deviceId)),i.deferred.resolve(t.secret)}}}}class U8{constructor(e,t,n){v(this,"storageImpl",void 0),v(this,"sharingImpl",void 0),this.storageImpl=new Kd(e,t),this.sharingImpl=new L8(n,t)}getDefaultKeyId(){return this.storageImpl.getDefaultKeyId()}setDefaultKeyId(e){return this.storageImpl.setDefaultKeyId(e)}addKey(e,t,n){return this.storageImpl.addKey(e,t,n)}getKey(e){return this.storageImpl.getKey(e)}hasKey(e){return this.storageImpl.hasKey(e)}checkKey(e,t){return this.storageImpl.checkKey(e,t)}store(e,t,n){return this.storageImpl.store(e,t,n)}get(e){return this.storageImpl.get(e)}isStored(e){var t=this;return _(function*(){return t.storageImpl.isStored(e)})()}request(e,t){return this.sharingImpl.request(e,t)}onRequestReceived(e){return this.sharingImpl.onRequestReceived(e)}onSecretReceived(e){this.sharingImpl.onSecretReceived(e)}}function j8(r,e,t){var n=Object.assign({},{code:r,reason:e},t);return new pr({type:V.KeyVerificationCancel,content:n})}function Ko(r,e){return function(t){return j8(r,e,t)}}var hN=Ko("m.user","Cancelled by user"),F8=Ko("m.timeout","Timed out"),sd=Ko("m.unknown_method","Unknown method"),pN=Ko("m.unexpected_message","Unexpected message"),ma=Ko("m.key_mismatch","Key mismatch"),B8=Ko("m.invalid_message","Invalid message");function zb(r){var e=r.getContent();if(e){var{code:t,reason:n}=e;return{code:t,reason:n}}else return{code:"Unknown error",reason:"m.unknown"}}var ok=new Error("Verification timed out");class Yb extends Error{constructor(e){super(),this.startEvent=e}}var K8=bm;class xw extends Tt{constructor(e,t,n,i,o,s){super(),this.channel=e,this.baseApis=t,this.userId=n,this.deviceId=i,this.startEvent=o,this.request=s,v(this,"cancelled",!1),v(this,"_done",!1),v(this,"promise",null),v(this,"transactionTimeoutTimer",null),v(this,"expectedEvent",void 0),v(this,"resolve",void 0),v(this,"reject",void 0),v(this,"resolveEvent",void 0),v(this,"rejectEvent",void 0),v(this,"started",void 0),v(this,"doVerification",void 0)}get initiatedByMe(){if(!this.startEvent)return!0;var e=this.startEvent.getSender(),t=this.startEvent.getContent();return e===this.baseApis.getUserId()&&t.from_device===this.baseApis.getDeviceId()}get hasBeenCancelled(){return this.cancelled}resetTimer(){S.info("Refreshing/starting the verification transaction timeout timer"),this.transactionTimeoutTimer!==null&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout(()=>{!this._done&&!this.cancelled&&(S.info("Triggering verification timeout"),this.cancel(ok))},10*60*1e3)}endTimer(){this.transactionTimeoutTimer!==null&&(clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=null)}send(e,t){return this.channel.send(e,t)}waitForEvent(e){if(this._done)return Promise.reject(new Error("Verification is already done"));var t=this.request.getEventFromOtherParty(e);return t?Promise.resolve(t):(this.expectedEvent=e,new Promise((n,i)=>{this.resolveEvent=n,this.rejectEvent=i}))}canSwitchStartEvent(e){return!1}switchStartEvent(e){if(this.canSwitchStartEvent(e))if(S.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){var t=this.rejectEvent;this.rejectEvent=void 0,t(new Yb(e))}else this.startEvent=e}handleEvent(e){if(!this._done){if(e.getType()===this.expectedEvent){if(this.expectedEvent!==V.KeyVerificationDone){var t;this.expectedEvent=void 0,this.rejectEvent=void 0,this.resetTimer(),(t=this.resolveEvent)===null||t===void 0||t.call(this,e)}}else if(e.getType()===V.KeyVerificationCancel){var n=this.reject;if(this.reject=void 0,n){var i=e.getContent(),{reason:o,code:s}=i;n(new Error("Other side cancelled verification "+"because ".concat(o," (").concat(s,")")))}}else if(this.expectedEvent){var a=new Error("Unexpected message: expecting "+this.expectedEvent+" but got "+e.getType());if(this.expectedEvent=void 0,this.rejectEvent){var l=this.rejectEvent;this.rejectEvent=void 0,l(a)}this.cancel(a)}}}done(){var e=this;return _(function*(){if(e.endTimer(),!e._done){var t;return e.request.onVerifierFinished(),(t=e.resolve)===null||t===void 0||t.call(e),p8(e.baseApis,e.userId,e.deviceId)}})()}cancel(e){if(this.endTimer(),!this._done){if(this.cancelled=!0,this.request.onVerifierCancelled(),this.userId&&this.deviceId)if(e===ok){var t=F8();this.send(t.getType(),t.getContent())}else if(e instanceof pr){var n=e.getSender();if(n!==this.userId){var i=e.getContent();e.getType()===V.KeyVerificationCancel?(i.code=i.code||"m.unknown",i.reason=i.reason||i.body||"Unknown reason",this.send(V.KeyVerificationCancel,i)):this.send(V.KeyVerificationCancel,{code:"m.unknown",reason:i.body||"Unknown reason"})}}else this.send(V.KeyVerificationCancel,{code:"m.unknown",reason:e.toString()});this.promise!==null?this.reject&&this.reject(e):this.promise=Promise.reject(e),this.emit(K8.Cancel,e)}}verify(){var e=this;return this.promise?this.promise:(this.promise=new Promise((t,n)=>{this.resolve=function(){e._done=!0,e.endTimer(),t(...arguments)},this.reject=i=>{this._done=!0,this.endTimer(),n(i)}}),this.doVerification&&!this.started&&(this.started=!0,this.resetTimer(),new Promise((t,n)=>{var i,o=(i=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(this.userId))===null||i===void 0?void 0:i.getId();o===this.deviceId&&n(new Error("Device ID is the same as the cross-signing ID")),t()}).then(()=>this.doVerification()).then(this.done.bind(this),this.cancel.bind(this))),this.promise)}verifyKeys(e,t,n){var i=this;return _(function*(){var o=[];for(var[s,a]of Object.entries(t)){var l=s.split(":",2)[1],c=i.baseApis.getStoredDevice(e,l);if(c)n(s,c,a),o.push([l,s,c.keys[s]]);else{var u=i.baseApis.crypto.deviceList.getStoredCrossSigningForUser(e);u&&u.getId()===l?(n(s,tn.fromStorage({keys:{[s]:l}},l),a),o.push([l,s,l])):S.warn("verification: Could not find device ".concat(l," to verify"))}}if(!o.length)throw new Error("No devices could be verified");S.info("Verification completed! Marking devices verified: ",o);for(var[d,f,p]of o)yield i.baseApis.crypto.setDeviceVerification(e,d,!0,null,null,{[f]:p});e==i.baseApis.credentials.userId&&(yield i.baseApis.checkKeyBackup())})()}get events(){}getShowSasCallbacks(){return null}getReciprocateQrCodeCallbacks(){return null}}var Ow=function(r){return r.Sas="m.sas.v1",r.ShowQrCode="m.qr_code.show.v1",r.ScanQrCode="m.qr_code.scan.v1",r.Reciprocate="m.reciprocate.v1",r}({}),V8=Ow.ShowQrCode,vN=Ow.ScanQrCode,$8=bm;class Vd extends xw{constructor(){var e;super(...arguments),e=this,v(this,"reciprocateQREvent",void 0),v(this,"doVerification",_(function*(){if(!e.startEvent)throw new Error("It is not currently possible to start verificationwith this method yet.");var{qrCodeData:t}=e.request;if(e.startEvent.getContent().secret!==(t==null?void 0:t.encodedSharedSecret))throw ma();yield new Promise((a,l)=>{e.reciprocateQREvent={confirm:a,cancel:()=>l(hN())},e.emit($8.ShowReciprocateQr,e.reciprocateQREvent)});var n={};switch(t==null?void 0:t.mode){case Mn.VerifyOtherUser:{var i=t.otherUserMasterKey;n["ed25519:".concat(i)]=i;break}case Mn.VerifySelfTrusted:{var o=e.request.targetDevice.deviceId;n["ed25519:".concat(o)]=t.otherDeviceKey;break}case Mn.VerifySelfUntrusted:{var s=t.myMasterKey;n["ed25519:".concat(s)]=s;break}}yield e.verifyKeys(e.userId,n,(a,l,c)=>{var u=n[a];if(!u)throw ma();if(c!==u)throw S.error("key ID from key info does not match"),ma();for(var d in l.keys)if(d.startsWith("ed25519")){var f=n[d];if(!f)throw ma();if(l.keys[d]!==f)throw S.error("master key does not match"),ma()}})}))}static factory(e,t,n,i,o,s){return new Vd(e,t,n,i,o,s)}static get NAME(){return"m.reciprocate.v1"}getReciprocateQrCodeCallbacks(){var e;return(e=this.reciprocateQREvent)!==null&&e!==void 0?e:null}}var W8=2,q8="MATRIX",Mn=function(r){return r[r.VerifyOtherUser=0]="VerifyOtherUser",r[r.VerifySelfTrusted=1]="VerifySelfTrusted",r[r.VerifySelfUntrusted=2]="VerifySelfUntrusted",r}(Mn||{});class us{constructor(e,t,n,i,o,s){this.mode=e,this.sharedSecret=t,this.otherUserMasterKey=n,this.otherDeviceKey=i,this.myMasterKey=o,this.buffer=s}static create(e,t){return _(function*(){var n=us.generateSharedSecret(),i=us.determineMode(e,t),o=null,s=null,a=null;if(i===Mn.VerifyOtherUser){var l=t.getStoredCrossSigningForUser(e.otherUserId);o=l.getId("master")}else if(i===Mn.VerifySelfTrusted)s=yield us.getOtherDeviceKey(e,t);else if(i===Mn.VerifySelfUntrusted){var c=t.getUserId(),u=t.getStoredCrossSigningForUser(c);a=u.getId("master")}var d=us.generateQrData(e,t,i,n,o,s,a),f=us.generateBuffer(d);return new us(i,n,o,s,a,f)})()}get encodedSharedSecret(){return this.sharedSecret}getBuffer(){return this.buffer}static generateSharedSecret(){var e=new Uint8Array(11);return globalThis.crypto.getRandomValues(e),vm(e)}static getOtherDeviceKey(e,t){return _(function*(){var n=t.getUserId(),i=e.targetDevice,o=i.deviceId?t.getStoredDevice(n,i.deviceId):void 0;if(!o)throw new Error("could not find device "+(i==null?void 0:i.deviceId));return o.getFingerprint()})()}static determineMode(e,t){var n=t.getUserId(),i=e.otherUserId,o=Mn.VerifyOtherUser;if(n===i){var s=t.checkUserTrust(n);s.isCrossSigningVerified()?o=Mn.VerifySelfTrusted:o=Mn.VerifySelfUntrusted}return o}static generateQrData(e,t,n,i,o,s,a){var l=t.getUserId(),c=e.channel.transactionId,u={prefix:q8,version:W8,mode:n,transactionId:c,firstKeyB64:"",secondKeyB64:"",secretB64:i},d=t.getStoredCrossSigningForUser(l);return n===Mn.VerifyOtherUser?(u.firstKeyB64=d.getId("master"),u.secondKeyB64=o):n===Mn.VerifySelfTrusted?(u.firstKeyB64=d.getId("master"),u.secondKeyB64=s):n===Mn.VerifySelfUntrusted&&(u.firstKeyB64=t.getDeviceEd25519Key(),u.secondKeyB64=a),u}static generateBuffer(e){var t=Buffer.alloc(0),n=a=>{var l=Buffer.from([a]);t=Buffer.concat([t,l])},i=a=>{var l=Buffer.alloc(2);l.writeInt16BE(a,0),t=Buffer.concat([t,l])},o=function(l,c){var u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,d=Buffer.from(l,c);u&&i(d.byteLength),t=Buffer.concat([t,d])},s=a=>{var l=Dr(a),c=Buffer.from(l);t=Buffer.concat([t,c])};return o(e.prefix,"ascii",!1),n(e.version),n(e.mode),o(e.transactionId,"utf-8"),s(e.firstKeyB64),s(e.secondKeyB64),s(e.secretB64),t}}function G8(r){return[(r[0]<<5|r[1]>>3)+1e3,((r[1]&7)<<10|r[2]<<2|r[3]>>6)+1e3,((r[3]&63)<<7|r[4]>>1)+1e3]}var Zg=V.KeyVerificationStart,H8=[V.KeyVerificationAccept,V.KeyVerificationKey,V.KeyVerificationMac],vh,z8=Ko("m.mismatched_sas","Mismatched short authentication string"),Y8=Ko("m.mismatched_commitment","Mismatched commitment"),J8=[["🐶","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 X8(r){var e=[r[0]>>2,(r[0]&3)<<4|r[1]>>4,(r[1]&15)<<2|r[2]>>6,r[2]&63,r[3]>>2,(r[3]&3)<<4|r[4]>>4,(r[4]&15)<<2|r[5]>>6];return e.map(t=>J8[t])}var Jb={decimal:G8,emoji:X8};function Q8(r,e){var t={};for(var n of e)n in Jb&&(t[n]=Jb[n](Array.from(r)));return t}var Z8={"hkdf-hmac-sha256":"calculate_mac","org.matrix.msc3783.hkdf-hmac-sha256":"calculate_mac_fixed_base64","hkdf-hmac-sha256.v2":"calculate_mac_fixed_base64","hmac-sha256":"calculate_mac_long_kdf"};function fu(r,e){return function(t,n){var i=r[Z8[e]](t,n);return S.log("SAS calculateMAC:",e,[t,n],i),i}}var e9={"curve25519-hkdf-sha256":function(e,t,n){var i="".concat(e.baseApis.getUserId(),"|").concat(e.baseApis.deviceId,"|")+"".concat(e.ourSASPubKey,"|"),o="".concat(e.userId,"|").concat(e.deviceId,"|").concat(e.theirSASPubKey,"|"),s="MATRIX_KEY_VERIFICATION_SAS|"+(e.initiatedByMe?i+o:o+i)+e.channel.transactionId;return t.generate_bytes(s,n)},curve25519:function(e,t,n){var i="".concat(e.baseApis.getUserId()).concat(e.baseApis.deviceId),o="".concat(e.userId).concat(e.deviceId),s="MATRIX_KEY_VERIFICATION_SAS"+(e.initiatedByMe?i+o:o+i)+e.channel.transactionId;return t.generate_bytes(s,n)}},Xb=["curve25519-hkdf-sha256","curve25519"],Qb=["sha256"],Zb=["hkdf-hmac-sha256.v2","org.matrix.msc3783.hkdf-hmac-sha256","hkdf-hmac-sha256","hmac-sha256"],mN=Object.keys(Jb),t9=new Set(Xb),r9=new Set(Qb),n9=new Set(Zb),sk=new Set(mN);function hu(r,e){return Array.isArray(r)?r.filter(t=>e.has(t)):[]}var i9=bm;class bc extends xw{constructor(){var e;super(...arguments),e=this,v(this,"waitingForAccept",void 0),v(this,"ourSASPubKey",void 0),v(this,"theirSASPubKey",void 0),v(this,"sasEvent",void 0),v(this,"doVerification",_(function*(){yield globalThis.Olm.init(),vh=vh||new globalThis.Olm.Utility,yield e.baseApis.downloadKeys([e.userId]);var t=!1;do try{return e.initiatedByMe?yield e.doSendVerification():yield e.doRespondVerification()}catch(n){if(n instanceof Yb)e.startEvent=n.startEvent,t=!0;else throw n}while(t)}))}static get NAME(){return Ow.Sas}get events(){return H8}canSwitchStartEvent(e){if(e.getType()!==Zg)return!1;var t=e.getContent();return(t==null?void 0:t.method)===bc.NAME&&!!this.waitingForAccept}sendStart(){var e=this;return _(function*(){var t=e.channel.completeContent(Zg,{method:bc.NAME,from_device:e.baseApis.deviceId,key_agreement_protocols:Xb,hashes:Qb,message_authentication_codes:Zb,short_authentication_string:mN});return yield e.channel.sendCompleted(Zg,t),t})()}verifyAndCheckMAC(e,t,n,i){var o=this;return _(function*(){var s=e9[e](o,n,6),a=new Promise((u,d)=>{o.sasEvent={sas:Q8(s,t),confirm:function(){var f=_(function*(){try{yield o.sendMAC(n,i),u()}catch(h){d(h)}});function p(){return f.apply(this,arguments)}return p}(),cancel:()=>d(hN()),mismatch:()=>d(z8())},o.emit(i9.ShowSas,o.sasEvent)}),[l]=yield Promise.all([o.waitForEvent(V.KeyVerificationMac).then(u=>(o.expectedEvent=V.KeyVerificationDone,u)),a]),c=l.getContent();yield o.checkMAC(n,c,i)})()}doSendVerification(){var e=this;return _(function*(){e.waitingForAccept=!0;var t;if(e.startEvent?t=e.channel.completedContentFromEvent(e.startEvent):t=yield e.sendStart(),!e.initiatedByMe)throw new Yb(e.startEvent);var n;try{n=yield e.waitForEvent(V.KeyVerificationAccept)}finally{e.waitingForAccept=!1}var i=n.getContent(),o=hu(i.short_authentication_string,sk);if(!(t9.has(i.key_agreement_protocol)&&r9.has(i.hash)&&n9.has(i.message_authentication_code)&&o.length))throw sd();if(typeof i.commitment!="string")throw B8();var s=i.key_agreement_protocol,a=i.message_authentication_code,l=i.commitment,c=new globalThis.Olm.SAS;try{e.ourSASPubKey=c.get_pubkey(),yield e.send(V.KeyVerificationKey,{key:e.ourSASPubKey}),n=yield e.waitForEvent(V.KeyVerificationKey),i=n.getContent();var u=i.key+ko.stringify(t);if(vh.sha256(u)!==l)throw Y8();e.theirSASPubKey=i.key,c.set_their_key(i.key),yield e.verifyAndCheckMAC(s,o,c,a)}finally{c.free()}})()}doRespondVerification(){var e=this;return _(function*(){var t=e.channel.completedContentFromEvent(e.startEvent),n=hu(Xb,new Set(t.key_agreement_protocols))[0],i=hu(Qb,new Set(t.hashes))[0],o=hu(Zb,new Set(t.message_authentication_codes))[0],s=hu(t.short_authentication_string,sk);if(!(n!==void 0&&i!==void 0&&o!==void 0&&s.length))throw sd();var a=new globalThis.Olm.SAS;try{var l=a.get_pubkey()+ko.stringify(t);yield e.send(V.KeyVerificationAccept,{key_agreement_protocol:n,hash:i,message_authentication_code:o,short_authentication_string:s,commitment:vh.sha256(l)});var c=yield e.waitForEvent(V.KeyVerificationKey);t=c.getContent(),e.theirSASPubKey=t.key,a.set_their_key(t.key),e.ourSASPubKey=a.get_pubkey(),yield e.send(V.KeyVerificationKey,{key:e.ourSASPubKey}),yield e.verifyAndCheckMAC(n,s,a,o)}finally{a.free()}})()}sendMAC(e,t){var n={},i=[],o="MATRIX_KEY_VERIFICATION_MAC"+this.baseApis.getUserId()+this.baseApis.deviceId+this.userId+this.deviceId+this.channel.transactionId,s="ed25519:".concat(this.baseApis.deviceId);n[s]=fu(e,t)(this.baseApis.getDeviceEd25519Key(),o+s),i.push(s);var a=this.baseApis.getCrossSigningId();if(a){var l="ed25519:".concat(a);n[l]=fu(e,t)(a,o+l),i.push(l)}var c=fu(e,t)(i.sort().join(","),o+"KEY_IDS");return this.send(V.KeyVerificationMac,{mac:n,keys:c})}checkMAC(e,t,n){var i=this;return _(function*(){var o="MATRIX_KEY_VERIFICATION_MAC"+i.userId+i.deviceId+i.baseApis.getUserId()+i.baseApis.deviceId+i.channel.transactionId;if(t.keys!==fu(e,n)(Object.keys(t.mac).sort().join(","),o+"KEY_IDS"))throw ma();yield i.verifyKeys(i.userId,t.mac,(s,a,l)=>{if(l!==fu(e,n)(a.keys[s],o+s))throw ma()})})()}getShowSasCallbacks(){var e;return(e=this.sasEvent)!==null&&e!==void 0?e:null}}function ak(r,e){if(!r.private_key_salt||!r.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return Cw(e,r.private_key_salt,r.private_key_iterations,r.private_key_bits)}var lk=5e5;function Pw(r){return e_.apply(this,arguments)}function e_(){return e_=_(function*(r){var e=Ei(32),t=yield Cw(r,e,lk);return{key:t,salt:e,iterations:lk}}),e_.apply(this,arguments)}var o9=10*60*1e3,s9=2*60*1e3,a9=3*1e3,Vc="m.key.verification.",at=Vc+"request",Sr=Vc+"start",yi=Vc+"cancel",l9=Vc+"done",pi=Vc+"ready",co=Hs.Unsent,ai=Hs.Requested,Fi=Hs.Ready,mo=Hs.Started,pu=Hs.Cancelled,vu=Hs.Done;class ga extends Tt{constructor(e,t,n){var i;super(),i=this,this.channel=e,this.verificationMethods=t,this.client=n,v(this,"eventsByUs",new Map),v(this,"eventsByThem",new Map),v(this,"_observeOnly",!1),v(this,"timeoutTimer",null),v(this,"_accepting",!1),v(this,"_declining",!1),v(this,"verifierHasFinished",!1),v(this,"_cancelled",!1),v(this,"_chosenMethod",null),v(this,"_qrCodeData",null),v(this,"requestReceivedAt",null),v(this,"commonMethods",[]),v(this,"_phase",void 0),v(this,"_cancellingUserId",void 0),v(this,"_verifier",void 0),v(this,"cancelOnTimeout",_(function*(){try{i.initiatedByMe?yield i.cancel({reason:"Other party didn't accept in time",code:"m.timeout"}):yield i.cancel({reason:"User didn't accept in time",code:"m.timeout"})}catch(o){S.error("Error while cancelling verification request",o)}})),this.channel.request=this,this.setPhase(co,!1)}static validateEvent(e,t,n){var i=t.getContent();return!e||!e.startsWith(Vc)?!1:i?(e===at||e===pi)&&!Array.isArray(i.methods)?(S.log("VerificationRequest: validateEvent: fail because methods"),!1):(e===at||e===pi||e===Sr)&&(typeof i.from_device!="string"||i.from_device.length===0)?(S.log("VerificationRequest: validateEvent: fail because from_device"),!1):!0:(S.log("VerificationRequest: validateEvent: no content"),!1)}get transactionId(){return this.channel.transactionId}get roomId(){return this.channel.roomId}get invalid(){return this.phase===co}get requested(){return this.phase===ai}get cancelled(){return this.phase===pu}get ready(){return this.phase===Fi}get started(){return this.phase===mo}get done(){return this.phase===vu}get methods(){return this.commonMethods}get chosenMethod(){return this._chosenMethod}calculateEventTimeout(e){var t=this.channel.getTimestamp(e)+o9;if(this.requestReceivedAt&&!this.initiatedByMe&&this.phase<=ai){var n=this.requestReceivedAt+s9;t=Math.min(t,n)}return Math.max(0,t-Date.now())}get timeout(){var e=this.getEventByEither(at);return e?this.calculateEventTimeout(e):0}get requestEvent(){return this.getEventByEither(at)}get phase(){return this._phase}get verifier(){return this._verifier}get canAccept(){return iN(this)}get accepting(){return this._accepting}get declining(){return this._declining}get pending(){return!this.observeOnly&&this._phase!==vu&&this._phase!==pu}get qrCodeData(){return this._qrCodeData}getQRCodeBytes(){var e;return(e=this._qrCodeData)===null||e===void 0?void 0:e.getBuffer()}generateQRCode(){var e=this;return _(function*(){return e.getQRCodeBytes()})()}otherPartySupportsMethod(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!t&&!this.ready&&!this.started)return!1;var n=this.eventsByThem.get(at)||this.eventsByThem.get(pi);if(!n){if(this.started&&this.initiatedByMe){var i=this.eventsByUs.get(Sr),o=i&&i.getContent(),s=o&&o.method;return e==s}return!1}var a=n.getContent();if(!a)return!1;var{methods:l}=a;return Array.isArray(l)?l.includes(e):!1}get initiatedByMe(){var e=this.eventsByUs.size+this.eventsByThem.size===0;if(this._phase===co&&e)return!0;var t=this.eventsByUs.has(at),n=this.eventsByThem.has(at);if(t&&!n)return!0;if(!t&&n)return!1;var i=this.eventsByUs.has(Sr),o=this.eventsByThem.has(Sr);return!!(i&&!o)}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 otherDeviceId(){return this.channel.deviceId}get isSelfVerification(){return this.client.getUserId()===this.otherUserId}get cancellingUserId(){var e=this.eventsByUs.get(yi),t=this.eventsByThem.get(yi);if(e&&(!t||e.getId()<t.getId()))return e.getSender();if(t)return t.getSender()}get cancellationCode(){var e=this.getEventByEither(yi);return e?e.getContent().code:null}get observeOnly(){return this._observeOnly}get targetDevice(){var e=this.eventsByThem.get(at)||this.eventsByThem.get(pi)||this.eventsByThem.get(Sr),t=e==null?void 0:e.getContent(),n=t==null?void 0:t.from_device;return{userId:this.otherUserId,deviceId:n}}beginKeyVerification(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!this.observeOnly&&!this._verifier){var n=this.phase===ai||this.phase===Fi||this.phase===co&&this.channel.canCreateRequest(Sr);if(n){if(this.commonMethods.length&&!this.commonMethods.includes(e)||(this._verifier=this.createVerifier(e,null,t),!this._verifier))throw sd();this._chosenMethod=e}}return this._verifier}startVerification(e){var t=this;return _(function*(){var n=t.beginKeyVerification(e);return n.verify(),n})()}scanQRCode(e){throw new Error("QR code scanning not supported by legacy crypto")}sendRequest(){var e=this;return _(function*(){if(!e.observeOnly&&e._phase===co){var t=[...e.verificationMethods.keys()];yield e.channel.send(at,{methods:t})}})()}cancel(){var e=arguments,t=this;return _(function*(){var{reason:n="User declined",code:i="m.user"}=e.length>0&&e[0]!==void 0?e[0]:{};if(!t.observeOnly&&t._phase!==pu){if(t._declining=!0,t.emit(fa.Change),t._verifier)return t._verifier.cancel(Ko(i,n)());t._cancellingUserId=t.client.getUserId(),yield t.channel.send(yi,{code:i,reason:n})}})()}accept(){var e=this;return _(function*(){if(!e.observeOnly&&e.phase===ai&&!e.initiatedByMe){var t=[...e.verificationMethods.keys()];e._accepting=!0,e.emit(fa.Change),yield e.channel.send(pi,{methods:t})}})()}waitFor(e){return new Promise((t,n)=>{var i=()=>{var o=!1;return e(this)?(t(this),o=!0):this.cancelled&&(n(new Error("cancelled")),o=!0),o&&this.off(fa.Change,i),o};i()||this.on(fa.Change,i)})}setPhase(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;this._phase=e,t&&this.emit(fa.Change)}getEventByEither(e){return this.eventsByThem.get(e)||this.eventsByUs.get(e)}getEventBy(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return t?this.eventsByThem.get(e):this.eventsByUs.get(e)}calculatePhaseTransitions(){var e=[{phase:co}],t=()=>e[e.length-1].phase,n=this.eventsByThem.has(at),i=this.getEventBy(at,n);i&&e.push({phase:ai,event:i});var o=i&&this.getEventBy(pi,!n);o&&t()===ai&&e.push({phase:Fi,event:o});var s;if(o||!i){var a=this.eventsByThem.get(Sr),l=this.eventsByUs.get(Sr);a&&l?s=a.getSender()<l.getSender()?a:l:s=a||l}else s=this.getEventBy(Sr,!n);if(s){var c=t()===ai&&(i==null?void 0:i.getSender())!==s.getSender(),u=t()===co&&this.channel.canCreateRequest(Sr);(c||t()===Fi||u)&&e.push({phase:mo,event:s})}var d=this.eventsByUs.get(l9);(this.verifierHasFinished||d&&t()===mo)&&e.push({phase:vu});var f=this.getEventByEither(yi);return(this._cancelled||f)&&t()!==vu&&e.push({phase:pu,event:f}),e}transitionToPhase(e){var{phase:t,event:n}=e;if((t===ai||t===Fi)&&!this.wasSentByOwnDevice(n)){var i=n.getContent();this.commonMethods=i.methods.filter(s=>this.verificationMethods.has(s))}if(this.observeOnly||(t===ai||t===mo||t===Fi)&&this.channel.receiveStartFromOtherDevices&&this.wasSentByOwnUser(n)&&!this.wasSentByOwnDevice(n)&&(this._observeOnly=!0),t===mo){var{method:o}=n.getContent();!this._verifier&&!this.observeOnly&&(this._verifier=this.createVerifier(o,n),this._verifier?this._chosenMethod=o:this.cancel({code:"m.unknown_method",reason:"Unknown method: ".concat(o)}))}}applyPhaseTransitions(){var e=this.calculatePhaseTransitions(),t=e.findIndex(o=>o.phase===this.phase),n=e.slice(t+1);for(var i of n)this.transitionToPhase(i);return n}isWinningStartRace(e){if(e.getType()!==Sr)return!1;var t=this._verifier.startEvent,n;if(this.isSelfVerification)if(t){var i=t.getContent();n=i&&i.from_device}else n=this.client.getDeviceId();else t?n=t.getSender():n=this.client.getUserId();var o;if(this.isSelfVerification){var s=e.getContent();o=s&&s.from_device}else o=e.getSender();return o<n}hasEventId(e){for(var t of this.eventsByUs.values())if(t.getId()===e)return!0;for(var n of this.eventsByThem.values())if(n.getId()===e)return!0;return!1}handleEvent(e,t,n,i,o){var s=this;return _(function*(){if(!(s.done||s.cancelled)){var a=s._observeOnly;if(s.adjustObserveOnly(t,n),!(!s.observeOnly&&!i&&(yield s.cancelOnError(e,t)))){var l=o?s.eventsByUs.has(e):s.eventsByThem.has(e);if(!l){var c=s.phase;s.addEvent(e,t,o);var u=s.applyPhaseTransitions();try{if(s._verifier&&!s.observeOnly){var d=s.isWinningStartRace(t);if(s._verifier.canSwitchStartEvent(t)&&d)s._verifier.switchStartEvent(t);else if(!i){var f;(e===yi||(f=s._verifier.events)!==null&&f!==void 0&&f.includes(e))&&s._verifier.handleEvent(t)}}if(u.length){if(n&&u.some(w=>w.phase===Fi)){var p=s.otherPartySupportsMethod(vN,!0);p&&(s._qrCodeData=yield us.create(s,s.client))}var h=u[u.length-1],{phase:m}=h;s.setupTimeout(m),s.setPhase(m)}else s._observeOnly!==a&&s.emit(fa.Change)}finally{S.log("Verification request ".concat(s.channel.transactionId,": ")+"".concat(e," event with id:").concat(t.getId(),", ")+"content:".concat(JSON.stringify(t.getContent())," ")+"deviceId:".concat(s.channel.deviceId,", ")+"sender:".concat(t.getSender(),", isSentByUs:").concat(o,", ")+"isLiveEvent:".concat(n,", isRemoteEcho:").concat(i,", ")+"phase:".concat(c,"=>").concat(s.phase,", ")+"observeOnly:".concat(a,"=>").concat(s._observeOnly))}}}}})()}setupTimeout(e){var t=!this.timeoutTimer&&!this.observeOnly&&e===ai;if(t&&(this.timeoutTimer=setTimeout(this.cancelOnTimeout,this.timeout)),this.timeoutTimer){var n=e===mo||e===Fi||e===vu||e===pu;n&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null)}}cancelOnError(e,t){var n=this;return _(function*(){if(e===Sr){var i=t.getContent().method;if(!n.verificationMethods.has(i))return yield n.cancel(zb(sd())),!0}var o=e===at&&n.phase!==co,s=e===pi&&n.phase!==ai&&n.phase!==mo;if(n.phase!==co&&(o||s)){S.warn("Cancelling, unexpected ".concat(e," verification ")+"event from ".concat(t.getSender()));var a="Unexpected ".concat(e," event in phase ").concat(n.phase);return yield n.cancel(zb(pN({reason:a}))),!0}return!1})()}adjustObserveOnly(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;t||(this._observeOnly=!0),this.calculateEventTimeout(e)<a9&&(this._observeOnly=!0)}addEvent(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(n?this.eventsByUs.set(e,t):this.eventsByThem.set(e,t),e===at){for(var[i,o]of this.eventsByThem.entries())o.getSender()!==this.otherUserId&&this.eventsByThem.delete(i);this.requestReceivedAt=Date.now()}}createVerifier(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;n||(n=this.targetDevice);var{userId:i,deviceId:o}=n,s=this.verificationMethods.get(e);if(!s){S.warn("could not find verifier constructor for method",e);return}return new s(this.channel,this.client,i,o,t,this)}wasSentByOwnUser(e){return(e==null?void 0:e.getSender())===this.client.getUserId()}wasSentByOwnDevice(e){if(!this.wasSentByOwnUser(e))return!1;var t=e.getContent();return!(!t||t.from_device!==this.client.getDeviceId())}onVerifierCancelled(){this._cancelled=!0;var e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}onVerifierFinished(){this.channel.send(V.KeyVerificationDone,{}),this.verifierHasFinished=!0;var e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}getEventFromOtherParty(e){return this.eventsByThem.get(e)}}var ck=V.RoomMessage,uk="m.reference",dk="m.relates_to";class Kr{constructor(e,t,n){this.client=e,this.roomId=t,this.userId=n,v(this,"requestEventId",void 0)}get receiveStartFromOtherDevices(){return!0}get transactionId(){return this.requestEventId}static getOtherPartyUserId(e,t){var n=Kr.getEventType(e);if(n===at){var i=t.getUserId(),o=e.getSender(),s=e.getContent(),a=s.to;if(o===i)return a;if(a===i)return o}}getTimestamp(e){return e.getTs()}static canCreateRequest(e){return e===at}canCreateRequest(e){return Kr.canCreateRequest(e)}static getTransactionId(e){if(Kr.getEventType(e)===at)return e.getId();var t=e.getRelation();if((t==null?void 0:t.rel_type)===uk)return t.event_id}static validateEvent(e,t){var n=Kr.getTransactionId(e);if(typeof n!="string"||n.length===0)return!1;var i=Kr.getEventType(e),o=e.getContent();if(i===at){if(!o||typeof o.to!="string"||!o.to.length)return S.log("InRoomChannel: validateEvent: no valid to "+o.to),!1;if(!Kr.getOtherPartyUserId(e,t))return S.log("InRoomChannel: validateEvent: "+"not directed to or sent by me: ".concat(e.getSender())+", ".concat(o.to)),!1}return ga.validateEvent(i,e,t)}static getEventType(e){var t=e.getType();if(t===ck){var n=e.getContent();if(n){var{msgtype:i}=n;if(i===at)return at}}return t&&t!==at?t:""}handleEvent(e,t){var n=arguments,i=this;return _(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!1;if(!t.hasEventId(e.getId())){var s=Kr.getEventType(e);if(e.getRoomId()===i.roomId){if(!i.userId){var a=Kr.getOtherPartyUserId(e,i.client);a&&(i.userId=a)}var l=i.client.getUserId(),c=e.getSender();if(i.userId&&c!==l&&c!==i.userId){S.log("InRoomChannel: ignoring verification event from non-participating sender ".concat(c));return}i.requestEventId||(i.requestEventId=Kr.getTransactionId(e));var u=!!e.getTxnId(),d=!!e.getUnsigned().transaction_id,f=e.getSender()===i.client.getUserId();return t.handleEvent(s,e,o,u||d,f)}}})()}completedContentFromEvent(e){var t=Object.assign({},e.getContent());return t[dk]=e.getRelation(),t}completeContent(e,t){return t=Object.assign({},t),(e===at||e===pi||e===Sr)&&(t.from_device=this.client.getDeviceId()),e===at?t={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:at,to:this.userId,from_device:t.from_device,methods:t.methods}:t[dk]={rel_type:uk,event_id:this.transactionId},t}send(e,t){var n=this.completeContent(e,t);return this.sendCompleted(e,n)}sendCompleted(e,t){var n=this;return _(function*(){var i=e;e===at&&(i=ck);var o=yield n.client.sendEvent(n.roomId,i,t);e===at&&(n.requestEventId=o.event_id)})()}}class c9{constructor(){v(this,"requestsByRoomId",new Map)}getRequest(e){var t=e.getRoomId(),n=Kr.getTransactionId(e);return this.getRequestByTxnId(t,n)}getRequestByChannel(e){return this.getRequestByTxnId(e.roomId,e.transactionId)}getRequestByTxnId(e,t){var n=this.requestsByRoomId.get(e);if(n)return n.get(t)}setRequest(e,t){this.doSetRequest(e.getRoomId(),Kr.getTransactionId(e),t)}setRequestByChannel(e,t){this.doSetRequest(e.roomId,e.transactionId,t)}doSetRequest(e,t,n){var i=this.requestsByRoomId.get(e);i||(i=new Map,this.requestsByRoomId.set(e,i)),i.set(t,n)}removeRequest(e){var t=e.getRoomId(),n=this.requestsByRoomId.get(t);n&&(n.delete(Kr.getTransactionId(e)),n.size===0&&this.requestsByRoomId.delete(t))}findRequestInProgress(e,t){var n=this.requestsByRoomId.get(e);if(n){for(var i of n.values())if(i.pending&&(t===void 0||i.requestingUserId===t))return i}}}class Br{constructor(e,t,n,i,o){this.client=e,this.userId=t,this.devices=n,this.transactionId=i,this.deviceId=o,v(this,"request",void 0)}isToDevices(e){if(e.length===this.devices.length){for(var t of e)if(!this.devices.includes(t))return!1;return!0}else return!1}static getEventType(e){return e.getType()}static getTransactionId(e){var t=e.getContent();return t&&t.transaction_id}static canCreateRequest(e){return e===at||e===Sr}canCreateRequest(e){return Br.canCreateRequest(e)}static validateEvent(e,t){if(e.isCancelled())return S.warn("Ignoring flagged verification request from "+e.getSender()),!1;var n=e.getContent();if(!n)return S.warn("ToDeviceChannel.validateEvent: invalid: no content"),!1;if(!n.transaction_id)return S.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"),!1;var i=e.getType();if(i===at){if(!Number.isFinite(n.timestamp))return S.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"),!1;if(e.getSender()===t.getUserId()&&n.from_device==t.getDeviceId())return S.warn("ToDeviceChannel.validateEvent: invalid: from own device"),!1}return ga.validateEvent(i,e,t)}getTimestamp(e){var t=e.getContent();return t&&t.timestamp}handleEvent(e,t){var n=arguments,i=this;return _(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!1,s=e.getType(),a=e.getContent();if(s===at||s===pi||s===Sr){i.transactionId||(i.transactionId=a.transaction_id);var l=a.from_device;if(!i.deviceId&&i.devices.includes(l)&&(i.deviceId=l),!i.deviceId||i.deviceId!==l){var c=i.completeContent(yi,zb(pN()));return i.sendToDevices(yi,c,[l])}}var u=t.phase===mo||t.phase===Fi;yield t.handleEvent(e.getType(),e,o,!1,!1);var d=t.phase===mo||t.phase===Fi,f=s===Sr||s===pi;if(f&&!u&&d&&i.deviceId){var p=i.devices.filter(m=>m!==i.deviceId&&m!==i.client.getDeviceId());if(p.length){var h=i.completeContent(yi,{code:"m.accepted",reason:"Verification request accepted by another device"});yield i.sendToDevices(yi,h,p)}}})()}completedContentFromEvent(e){return e.getContent()}completeContent(e,t){return t=Object.assign({},t),this.transactionId&&(t.transaction_id=this.transactionId),(e===at||e===pi||e===Sr)&&(t.from_device=this.client.getDeviceId()),e===at&&(t.timestamp=Date.now()),t}send(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};(e===at||e===Sr)&&!this.transactionId&&(this.transactionId=Br.makeTransactionId());var n=this.completeContent(e,t);return this.sendCompleted(e,n)}sendCompleted(e,t){var n=this;return _(function*(){var i;e===at||e===yi&&!n.deviceId?i=yield n.sendToDevices(e,t,n.devices):i=yield n.sendToDevices(e,t,[n.deviceId]);var o=new pr({sender:n.client.getUserId(),content:t,type:e});return yield n.request.handleEvent(e,o,!0,!0,!0),i})()}sendToDevices(e,t,n){var i=this;return _(function*(){if(n.length){var o=new Map;for(var s of n)o.set(s,t);yield i.client.sendToDevice(e,new Map([[i.userId,o]]))}})()}static makeTransactionId(){return Ei(32)}}class u9{constructor(){v(this,"requestsByUserId",new Map)}getRequest(e){return this.getRequestBySenderAndTxnId(e.getSender(),Br.getTransactionId(e))}getRequestByChannel(e){return this.getRequestBySenderAndTxnId(e.userId,e.transactionId)}getRequestBySenderAndTxnId(e,t){var n=this.requestsByUserId.get(e);if(n)return n.get(t)}setRequest(e,t){this.setRequestBySenderAndTxnId(e.getSender(),Br.getTransactionId(e),t)}setRequestByChannel(e,t){this.setRequestBySenderAndTxnId(e.userId,e.transactionId,t)}setRequestBySenderAndTxnId(e,t,n){var i=this.requestsByUserId.get(e);i||(i=new Map,this.requestsByUserId.set(e,i)),i.set(t,n)}removeRequest(e){var t=e.getSender(),n=this.requestsByUserId.get(t);n&&(n.delete(Br.getTransactionId(e)),n.size===0&&this.requestsByUserId.delete(t))}findRequestInProgress(e,t){var n=this.requestsByUserId.get(e);if(n){for(var i of n.values())if(i.pending&&i.channel.isToDevices(t))return i}}getRequestsInProgress(e){var t=this.requestsByUserId.get(e);return t?Array.from(t.values()).filter(n=>n.pending):[]}}class ov extends xw{constructor(){super(...arguments),v(this,"doVerification",_(function*(){throw new Error("Verification is not possible with this method")}))}static factory(e,t,n,i,o,s){return new ov(e,t,n,i,o,s)}static get NAME(){return"org.matrix.illegal_method"}}var zh="org.matrix.msc2697.v1.olm.libolm_pickle",fk=7*24*60*60*1e3;class d9{constructor(e){this.crypto=e,v(this,"inProgress",!1),v(this,"timeoutId",void 0),v(this,"key",void 0),v(this,"keyInfo",void 0),v(this,"deviceDisplayName",void 0),this.getDehydrationKeyFromCache()}getDehydrationKeyFromCache(){var e=this;return this.crypto.cryptoStore.doTxn("readonly",[be.STORE_ACCOUNT],t=>{this.crypto.cryptoStore.getSecretStorePrivateKey(t,function(){var n=_(function*(i){if(i){var{key:o,keyInfo:s,deviceDisplayName:a,time:l}=i,c=Buffer.from(e.crypto.olmDevice.pickleKey),u=yield Ef(o,c,zh);e.key=Dr(u),e.keyInfo=s,e.deviceDisplayName=a;var d=Date.now(),f=Math.max(1,l+fk-d);e.timeoutId=globalThis.setTimeout(e.dehydrateDevice.bind(e),f)}});return function(i){return n.apply(this,arguments)}}(),"dehydration")})}setKeyAndQueueDehydration(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{},o=t.length>2?t[2]:void 0,s=yield n.setKey(e,i,o);s||n.dehydrateDevice()})()}setKey(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{},o=t.length>2?t[2]:void 0;if(!e){n.timeoutId&&(globalThis.clearTimeout(n.timeoutId),n.timeoutId=void 0),yield n.crypto.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],l=>{n.crypto.cryptoStore.storeSecretStorePrivateKey(l,"dehydration",null)}),n.key=void 0,n.keyInfo=void 0;return}for(var s=!!n.key&&e.length==n.key.length,a=0;s&&a<e.length;a++)e[a]!=n.key[a]&&(s=!1);return s||(n.key=e,n.keyInfo=i,n.deviceDisplayName=o),s})()}dehydrateDevice(){var e=this;return _(function*(){if(e.inProgress){S.log("Dehydration already in progress -- not starting new dehydration");return}e.inProgress=!0,e.timeoutId&&(globalThis.clearTimeout(e.timeoutId),e.timeoutId=void 0);try{var t=Buffer.from(e.crypto.olmDevice.pickleKey),n=yield Kc(Qr(e.key),t,zh);yield e.crypto.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],N=>{e.crypto.cryptoStore.storeSecretStorePrivateKey(N,"dehydration",{keyInfo:e.keyInfo,key:n,deviceDisplayName:e.deviceDisplayName,time:Date.now()})}),S.log("Attempting to dehydrate device"),S.log("Creating account");var i=new globalThis.Olm.Account;i.create();var o=JSON.parse(i.identity_keys()),s=i.max_number_of_one_time_keys();i.generate_one_time_keys(s/2),i.generate_fallback_key();var a=JSON.parse(i.one_time_keys()),l=JSON.parse(i.fallback_key());i.mark_keys_as_published();var c=i.pickle(new Uint8Array(e.key)),u={algorithm:zh,account:c};e.keyInfo.passphrase&&(u.passphrase=e.keyInfo.passphrase),S.log("Uploading account to server");var d=yield e.crypto.baseApis.http.authedRequest(Z.Put,"/dehydrated_device",void 0,{device_data:u,initial_device_display_name:e.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"}),f=d.device_id;S.log("Preparing device keys",f);var p={algorithms:e.crypto.supportedAlgorithms,device_id:f,user_id:e.crypto.userId,keys:{["ed25519:".concat(f)]:o.ed25519,["curve25519:".concat(f)]:o.curve25519}},h=i.sign(ko.stringify(p));p.signatures={[e.crypto.userId]:{["ed25519:".concat(f)]:h}},e.crypto.crossSigningInfo.getId("self_signing")&&(yield e.crypto.crossSigningInfo.signObject(p,"self_signing")),S.log("Preparing one-time keys");var m={};for(var[w,g]of Object.entries(a.curve25519)){var b={key:g},R=i.sign(ko.stringify(b));b.signatures={[e.crypto.userId]:{["ed25519:".concat(f)]:R}},m["signed_curve25519:".concat(w)]=b}S.log("Preparing fallback keys");var k={};for(var[O,T]of Object.entries(l.curve25519)){var x={key:T,fallback:!0},C=i.sign(ko.stringify(x));x.signatures={[e.crypto.userId]:{["ed25519:".concat(f)]:C}},k["signed_curve25519:".concat(O)]=x}return S.log("Uploading keys to server"),yield e.crypto.baseApis.http.authedRequest(Z.Post,"/keys/upload/"+encodeURI(f),void 0,{device_keys:p,one_time_keys:m,"org.matrix.msc2732.fallback_keys":k}),S.log("Done dehydrating"),e.timeoutId=globalThis.setTimeout(e.dehydrateDevice.bind(e),fk),f}finally{e.inProgress=!1}})()}stop(){this.timeoutId&&(globalThis.clearTimeout(this.timeoutId),this.timeoutId=void 0)}}var f9=200,h9=5e3;class ka{constructor(e,t){this.baseApis=e,this.getKey=t,v(this,"algorithm",void 0),v(this,"backupInfo",void 0),v(this,"checkedForBackup",void 0),v(this,"sendingBackups",void 0),v(this,"sessionLastCheckAttemptedTime",{}),v(this,"clientRunning",!0),this.checkedForBackup=!1,this.sendingBackups=!1}stop(){this.clientRunning=!1}get version(){return this.backupInfo&&this.backupInfo.version}static checkBackupVersion(e){var t=ey[e.algorithm];if(!t)throw new Error("Unknown backup algorithm: "+e.algorithm);if(typeof e.auth_data!="object")throw new Error("Invalid backup data returned");return t.checkBackupVersion(e)}static makeAlgorithm(e,t){var n=ey[e.algorithm];if(!n)throw new Error("Unknown backup algorithm");return n.init(e.auth_data,t)}enableKeyBackup(e){var t=this;return _(function*(){t.backupInfo=e,t.algorithm&&t.algorithm.free(),t.algorithm=yield ka.makeAlgorithm(e,t.getKey),t.baseApis.emit(et.KeyBackupStatus,!0),t.scheduleKeyBackupSend()})()}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit(et.KeyBackupStatus,!1)}getKeyBackupEnabled(){return this.checkedForBackup?!!this.algorithm:null}prepareKeyBackupVersion(e,t){return _(function*(){var n=t?ey[t]:m9;if(!n)throw new Error("Unknown backup algorithm");var[i,o]=yield n.prepare(e),s=nv(i);return{algorithm:n.algorithmName,auth_data:o,recovery_key:s,privateKey:i}})()}createKeyBackupVersion(e){var t=this;return _(function*(){t.algorithm=yield ka.makeAlgorithm(e,t.getKey)})()}deleteAllKeyBackupVersions(){var e=this;return _(function*(){for(var t,n,i=(t=(n=yield e.baseApis.getKeyBackupVersion())===null||n===void 0?void 0:n.version)!==null&&t!==void 0?t:null;i!=null;){var o,s;yield e.deleteKeyBackupVersion(i),e.disableKeyBackup(),i=(o=(s=yield e.baseApis.getKeyBackupVersion())===null||s===void 0?void 0:s.version)!==null&&o!==void 0?o:null}})()}deleteKeyBackupVersion(e){var t=this;return _(function*(){var n=Se("/room_keys/version/$version",{$version:e});yield t.baseApis.http.authedRequest(Z.Delete,n,void 0,void 0,{prefix:Ot.V3})})()}checkAndStart(){var e=this;return _(function*(){if(S.log("Checking key backup status..."),e.baseApis.isGuest())return S.log("Skipping key backup check since user is guest"),e.checkedForBackup=!0,null;var t;try{var n;t=(n=yield e.baseApis.getKeyBackupVersion())!==null&&n!==void 0?n:void 0}catch(o){return S.log("Error checking for active key backup",o),o.httpStatus===404&&(e.checkedForBackup=!0),null}e.checkedForBackup=!0;var i=yield e.isKeyBackupTrusted(t);return i.usable&&!e.backupInfo?(S.log("Found usable key backup v".concat(t.version,": enabling key backups")),yield e.enableKeyBackup(t)):!i.usable&&e.backupInfo?(S.log("No usable key backup: disabling key backup"),e.disableKeyBackup()):!i.usable&&!e.backupInfo?S.log("No usable key backup: not enabling key backup"):i.usable&&e.backupInfo&&(t.version!==e.backupInfo.version?(S.log("On backup version ".concat(e.backupInfo.version," but ")+"found version ".concat(t.version,": switching.")),e.disableKeyBackup(),yield e.enableKeyBackup(t),yield e.scheduleAllGroupSessionsForBackup()):S.log("Backup version ".concat(t.version," still current"))),{backupInfo:t,trustInfo:i}})()}checkKeyBackup(){var e=this;return _(function*(){return e.checkedForBackup=!1,e.checkAndStart()})()}queryKeyBackupRateLimited(e,t){var n=this;return _(function*(){if(n.backupInfo){var i=new Date().getTime();(!n.sessionLastCheckAttemptedTime[t]||i-n.sessionLastCheckAttemptedTime[t]>h9)&&(n.sessionLastCheckAttemptedTime[t]=i,yield n.baseApis.restoreKeyBackupWithCache(e,t,n.backupInfo,{}))}})()}isKeyBackupTrusted(e){var t=this;return _(function*(){var n={usable:!1,trusted_locally:!1,sigs:[]};if(!e||!e.algorithm||!e.auth_data||!e.auth_data.signatures)return S.info("Key backup is absent or missing required data: ".concat(JSON.stringify(e))),n;var i=t.baseApis.getUserId(),o=yield t.baseApis.crypto.getSessionBackupPrivateKey();if(o){var s=null;try{s=yield ka.makeAlgorithm(e,_(function*(){return o})),(yield s.keyMatches(o))&&(S.info("Backup is trusted locally"),n.trusted_locally=!0)}catch{}finally{var a;(a=s)===null||a===void 0||a.free()}}var l=e.auth_data.signatures[i]||{};for(var c of Object.keys(l)){var u=c.split(":");if(u[0]!=="ed25519"){S.log("Ignoring unknown signature type: "+u[0]);continue}var d={deviceId:u[1]},f=t.baseApis.crypto.crossSigningInfo.getId();if(f===d.deviceId){d.crossSigningId=!0;try{yield Sc(t.baseApis.crypto.olmDevice,e.auth_data,i,d.deviceId,f),d.valid=!0}catch(h){S.warn("Bad signature from cross signing key "+f,h),d.valid=!1}n.sigs.push(d);continue}var p=t.baseApis.crypto.deviceList.getStoredDevice(i,d.deviceId);if(p){d.device=p,d.deviceTrust=t.baseApis.checkDeviceTrust(i,d.deviceId);try{yield Sc(t.baseApis.crypto.olmDevice,e.auth_data,i,p.deviceId,p.getFingerprint()),d.valid=!0}catch(h){S.info("Bad signature from key ID "+c+" userID "+t.baseApis.getUserId()+" device ID "+p.deviceId+" fingerprint: "+p.getFingerprint(),e.auth_data,h),d.valid=!1}}else d.valid=null,S.info("Ignoring signature from unknown key "+c);n.sigs.push(d)}return n.usable=n.sigs.some(h=>{var m;return h.valid&&(h.device&&((m=h.deviceTrust)===null||m===void 0?void 0:m.isVerified())||h.crossSigningId)}),n})()}scheduleKeyBackupSend(){var e=arguments,t=this;return _(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:1e4;if(S.debug("Key backup: scheduleKeyBackupSend currentSending:".concat(t.sendingBackups," delay:").concat(n)),!t.sendingBackups){t.sendingBackups=!0;try{var i=Math.random()*n;if(yield As(i),!t.clientRunning){t.sendingBackups=!1;return}for(var o=0;;){if(!t.algorithm)return;try{var s=yield t.backupPendingKeys(f9);if(s===0){t.sendingBackups=!1;return}o=0}catch(l){if(o++,S.log("Key backup request failed",l),l instanceof hr){var a=l.data.errcode;if(a=="M_NOT_FOUND"||a=="M_WRONG_ROOM_KEYS_VERSION"){t.sendingBackups=!1,t.baseApis.crypto.emit(et.KeyBackupFailed,a),yield t.checkKeyBackup();return}}}if(o&&(yield As(1e3*Math.pow(2,Math.min(o-1,4)))),!t.clientRunning){S.debug("Key backup send loop aborted, client stopped"),t.sendingBackups=!1;return}}}catch(l){S.log("Backup loop failed ".concat(l)),t.sendingBackups=!1}}})()}backupPendingKeys(e){var t=this;return _(function*(){var n=yield t.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(e);if(!n.length)return 0;var i=yield t.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();t.baseApis.crypto.emit(et.KeyBackupSessionsRemaining,i);var o={};for(var s of n){var a,l=s.sessionData.room_id;Xi(o,l,o[l]||{sessions:{}});var c=t.baseApis.crypto.olmDevice.exportInboundGroupSession(s.senderKey,s.sessionId,s.sessionData);c.algorithm=bn;var u=(c.forwarding_curve25519_key_chain||[]).length,d=t.baseApis.crypto.deviceList.getUserByIdentityKey(bn,s.senderKey),f=(a=t.baseApis.crypto.deviceList.getDeviceByIdentityKey(bn,s.senderKey))!==null&&a!==void 0?a:void 0,p=t.baseApis.crypto.checkDeviceInfoTrust(d,f).isVerified();Xi(o[l].sessions,s.sessionId,{first_message_index:c.first_known_index,forwarded_count:u,is_verified:p,session_data:yield t.algorithm.encryptSession(c)})}return yield t.baseApis.sendKeyBackup(void 0,void 0,t.backupInfo.version,{rooms:o}),yield t.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(n),i=yield t.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(),t.baseApis.crypto.emit(et.KeyBackupSessionsRemaining,i),n.length})()}backupGroupSession(e,t){var n=this;return _(function*(){yield n.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{senderKey:e,sessionId:t}]),n.backupInfo&&n.scheduleKeyBackupSend()})()}scheduleAllGroupSessionsForBackup(){var e=this;return _(function*(){yield e.flagAllGroupSessionsForBackup(),e.scheduleKeyBackupSend(0)})()}flagAllGroupSessionsForBackup(){var e=this;return _(function*(){yield e.baseApis.crypto.cryptoStore.doTxn("readwrite",[be.STORE_INBOUND_GROUP_SESSIONS,be.STORE_BACKUP],n=>{e.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(n,i=>{i!==null&&e.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([i],n)})});var t=yield e.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();return e.baseApis.emit(et.KeyBackupSessionsRemaining,t),t})()}countSessionsNeedingBackup(){return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup()}}class _c{constructor(e,t,n){this.authData=e,this.publicKey=t,this.getKey=n}static init(e,t){return _(function*(){if(!e||!("public_key"in e))throw new Error("auth_data missing required information");var n=new globalThis.Olm.PkEncryption;return n.set_recipient_key(e.public_key),new _c(e,n,t)})()}static prepare(e){return _(function*(){var t=new globalThis.Olm.PkDecryption;try{var n={};if(!e)n.public_key=t.generate_key();else if(e instanceof Uint8Array)n.public_key=t.init_with_private_key(e);else{var i=yield Pw(e);n.private_key_salt=i.salt,n.private_key_iterations=i.iterations,n.public_key=t.init_with_private_key(i.key)}var o=new globalThis.Olm.PkEncryption;return o.set_recipient_key(n.public_key),[t.get_private_key(),n]}finally{t.free()}})()}static checkBackupVersion(e){if(!("public_key"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!0}encryptSession(e){var t=this;return _(function*(){var n=Object.assign({},e);return delete n.session_id,delete n.room_id,delete n.first_known_index,t.publicKey.encrypt(JSON.stringify(n))})()}decryptSessions(e){var t=this;return _(function*(){var n=yield t.getKey(),i=new globalThis.Olm.PkDecryption;try{var o=i.init_with_private_key(n);if(o!==t.authData.public_key)throw new hr({errcode:$c.RESTORE_BACKUP_ERROR_BAD_KEY});var s=[];for(var[a,l]of Object.entries(e))try{var c=JSON.parse(i.decrypt(l.session_data.ephemeral,l.session_data.mac,l.session_data.ciphertext));c.session_id=a,s.push(c)}catch(u){S.log("Failed to decrypt megolm session from backup",u,l)}return s}finally{i.free()}})()}keyMatches(e){var t=this;return _(function*(){var n=new globalThis.Olm.PkDecryption,i;try{i=n.init_with_private_key(e)}finally{n.free()}return i===t.authData.public_key})()}free(){this.publicKey.free()}}v(_c,"algorithmName","m.megolm_backup.v1.curve25519-aes-sha2");function p9(r){var e=new Uint8Array(r);return globalThis.crypto.getRandomValues(e),e}var v9=new Ft("m.megolm_backup.v1.aes-hmac-sha2","org.matrix.msc3270.v1.aes-hmac-sha2");class $d{constructor(e,t){this.authData=e,this.key=t}static init(e,t){return _(function*(){if(!e)throw new Error("auth_data missing");var n=yield t();if(e.mac){var{mac:i}=yield Ca(n,e.iv);if(e.mac.replace(/=+$/g,"")!==i.replace(/=+/g,""))throw new Error("Key does not match")}return new $d(e,n)})()}static prepare(e){return _(function*(){var t,n={};if(!e)t=p9(32);else if(e instanceof Uint8Array)t=new Uint8Array(e);else{var i=yield Pw(e);n.private_key_salt=i.salt,n.private_key_iterations=i.iterations,t=i.key}var{iv:o,mac:s}=yield Ca(t);return n.iv=o,n.mac=s,[t,n]})()}static checkBackupVersion(e){if(!("iv"in e.auth_data&&"mac"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!1}encryptSession(e){var t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,Kc(JSON.stringify(t),this.key,e.session_id)}decryptSessions(e){var t=this;return _(function*(){var n=[];for(var[i,o]of Object.entries(e))try{var s=JSON.parse(yield Ef(o.session_data,t.key,i));s.session_id=i,n.push(s)}catch(a){S.log("Failed to decrypt megolm session from backup",a,o)}return n})()}keyMatches(e){var t=this;return _(function*(){if(t.authData.mac){var{mac:n}=yield Ca(e,t.authData.iv);return t.authData.mac.replace(/=+$/g,"")===n.replace(/=+/g,"")}else return!0})()}free(){this.key.fill(0)}}v($d,"algorithmName",v9.name);var ey={[_c.algorithmName]:_c,[$d.algorithmName]:$d},m9=_c;function hk(r){var e;return{trusted:r.usable,matchesDecryptionKey:(e=r.trusted_locally)!==null&&e!==void 0?e:!1}}class g9{constructor(e){v(this,"algorithm",void 0),v(this,"sourceTrusted",void 0),this.algorithm=e,this.sourceTrusted=!e.untrusted}free(){this.algorithm.free()}decryptSessions(e){var t=this;return _(function*(){return yield t.algorithm.decryptSessions(e)})()}}class y9{constructor(e){this.cryptoStore=e,v(this,"roomEncryption",{})}init(){var e=this;return _(function*(){yield e.cryptoStore.doTxn("readwrite",[be.STORE_ROOMS],t=>{e.cryptoStore.getEndToEndRooms(t,n=>{e.roomEncryption=n})})})()}getRoomEncryption(e){return this.roomEncryption[e]||null}isRoomEncrypted(e){return!!this.getRoomEncryption(e)}setRoomEncryption(e,t){var n=this;return _(function*(){n.roomEncryption[e]=t,yield n.cryptoStore.doTxn("readwrite",[be.STORE_ROOMS],i=>{n.cryptoStore.storeEndToEndRoom(e,t,i)})})()}}function pk(r,e){var t=new Map(Object.entries(r.keys)),n=r.getDisplayName()||void 0,i=new Map;if(r.signatures)for(var o in r.signatures)i.set(o,new Map(Object.entries(r.signatures[o])));return new YD({deviceId:r.deviceId,userId:e,keys:t,algorithms:r.algorithms,verified:r.verified,signatures:i,displayName:n})}function vk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function S9(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?vk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):vk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var uo=tn.DeviceVerification,ty={[Vd.NAME]:Vd,[bc.NAME]:bc,[V8]:ov,[vN]:ov};Vd.NAME,bc.NAME;function gN(){return!!globalThis.Olm}var b9=60*60*1e3,_9=5*60*1e3,et=function(r){return r.DeviceVerificationChanged="deviceVerificationChanged",r[r.UserTrustStatusChanged=Yt.UserTrustStatusChanged]="UserTrustStatusChanged",r.UserCrossSigningUpdated="userCrossSigningUpdated",r.RoomKeyRequest="crypto.roomKeyRequest",r.RoomKeyRequestCancellation="crypto.roomKeyRequestCancellation",r[r.KeyBackupStatus=Yt.KeyBackupStatus]="KeyBackupStatus",r[r.KeyBackupFailed=Yt.KeyBackupFailed]="KeyBackupFailed",r[r.KeyBackupSessionsRemaining=Yt.KeyBackupSessionsRemaining]="KeyBackupSessionsRemaining",r[r.KeyBackupDecryptionKeyCached=Yt.KeyBackupDecryptionKeyCached]="KeyBackupDecryptionKeyCached",r.KeySignatureUploadFailure="crypto.keySignatureUploadFailure",r.VerificationRequest="crypto.verification.request",r[r.VerificationRequestReceived=Yt.VerificationRequestReceived]="VerificationRequestReceived",r.Warning="crypto.warning",r[r.WillUpdateDevices=Yt.WillUpdateDevices]="WillUpdateDevices",r[r.DevicesUpdated=Yt.DevicesUpdated]="DevicesUpdated",r[r.KeysChanged=Yt.KeysChanged]="KeysChanged",r[r.LegacyCryptoStoreMigrationProgress=Yt.LegacyCryptoStoreMigrationProgress]="LegacyCryptoStoreMigrationProgress",r}({});class sv extends Tt{static getOlmVersion(){return JC.getOlmVersion()}constructor(e,t,n,i,o,s){var a;if(super(),a=this,this.baseApis=e,this.userId=t,this.deviceId=n,this.clientStore=i,this.cryptoStore=o,v(this,"backupManager",void 0),v(this,"crossSigningInfo",void 0),v(this,"olmDevice",void 0),v(this,"deviceList",void 0),v(this,"dehydrationManager",void 0),v(this,"secretStorage",void 0),v(this,"roomList",void 0),v(this,"reEmitter",void 0),v(this,"verificationMethods",void 0),v(this,"supportedAlgorithms",void 0),v(this,"outgoingRoomKeyRequestManager",void 0),v(this,"toDeviceVerificationRequests",void 0),v(this,"inRoomVerificationRequests",void 0),v(this,"trustCrossSignedDevices",!0),v(this,"lastOneTimeKeyCheck",null),v(this,"oneTimeKeyCheckInProgress",!1),v(this,"roomEncryptors",new Map),v(this,"roomDecryptors",new Map),v(this,"deviceKeys",{}),v(this,"globalBlacklistUnverifiedDevices",!1),v(this,"globalErrorOnUnknownDevices",!0),v(this,"receivedRoomKeyRequests",[]),v(this,"receivedRoomKeyRequestCancellations",[]),v(this,"processingRoomKeyRequests",!1),v(this,"lazyLoadMembers",!1),v(this,"roomDeviceTrackingState",{}),v(this,"forceNewSessionRetryTime",new qt(()=>new qt(()=>0))),v(this,"sendKeyRequestsImmediately",!1),v(this,"oneTimeKeyCount",void 0),v(this,"needsNewFallback",void 0),v(this,"fallbackCleanup",void 0),v(this,"onDeviceListUserCrossSigningUpdated",function(){var d=_(function*(f){if(f===a.userId){var p=a.deviceList.getStoredCrossSigningForUser(f),h=p?p.getId():null,m=a.crossSigningInfo.getId(),w=m!==h;m&&h&&!w?yield a.checkOwnCrossSigningTrust():(a.storeTrustedSelfKeys(null),a.emit(et.KeysChanged,{}),a.emit(et.UserTrustStatusChanged,a.userId,a.checkUserTrust(f)))}else{yield a.checkDeviceVerifications(f);var g=a.deviceList.getStoredCrossSigningForUser(f);g&&(g.updateCrossSigningVerifiedBefore(a.checkUserTrust(f).isCrossSigningVerified()),a.deviceList.setRawStoredCrossSigningForUser(f,g.toStorage())),a.emit(et.UserTrustStatusChanged,f,a.checkUserTrust(f))}});return function(f){return d.apply(this,arguments)}}()),v(this,"onMembership",(d,f,p)=>{try{this.onRoomMembership(d,f,p)}catch(h){S.error("Error handling membership change:",h)}}),v(this,"onToDeviceEvent",d=>{try{S.log("received to-device ".concat(d.getType()," from: ")+"".concat(d.getSender()," id: ").concat(d.getContent()[en])),d.getType()=="m.room_key"||d.getType()=="m.forwarded_room_key"?this.onRoomKeyEvent(d):d.getType()=="m.room_key_request"?this.onRoomKeyRequestEvent(d):d.getType()==="m.secret.request"?this.secretStorage.onRequestReceived(d):d.getType()==="m.secret.send"?this.secretStorage.onSecretReceived(d):d.getType()==="m.room_key.withheld"?this.onRoomKeyWithheldEvent(d):d.getContent().transaction_id?this.onKeyVerificationMessage(d):d.getContent().msgtype==="m.bad.encrypted"?this.onToDeviceBadEncrypted(d):(d.isBeingDecrypted()||d.shouldAttemptDecryption())&&(d.isBeingDecrypted()||d.attemptDecryption(this),d.once(ot.Decrypted,f=>{this.onToDeviceEvent(f)}))}catch(f){S.error("Error handling toDeviceEvent:",f)}}),v(this,"onTimelineEvent",function(d,f,p,h){var{liveEvent:m=!0}=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};if(Kr.validateEvent(d,a.baseApis)){var w=g=>{var b=new Kr(a.baseApis,g.getRoomId());return new ga(b,a.verificationMethods,a.baseApis)};a.handleVerificationEvent(d,a.inRoomVerificationRequests,w,m)}}),S.debug("Crypto: initialising roomlist..."),this.roomList=new y9(o),this.reEmitter=new Bc(this),s){this.verificationMethods=new Map;for(var l of s)typeof l=="string"?ty[l]&&this.verificationMethods.set(l,ty[l]):l.NAME?this.verificationMethods.set(l.NAME,l):S.warn("Excluding unknown verification method ".concat(l))}else this.verificationMethods=new Map(Object.entries(ty));this.backupManager=new ka(e,_(function*(){var d=yield a.getSessionBackupPrivateKey();if(d)return d;var f=yield a.secretStorage.get("m.megolm_backup.v1");if(f){var p=Yh(f);if(p){var h=yield a.secretStorage.getKey();yield a.secretStorage.store("m.megolm_backup.v1",p,[h[0]])}return Dr(p||f)}if(a.baseApis.cryptoCallbacks&&a.baseApis.cryptoCallbacks.getBackupKey)return a.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")})),this.olmDevice=new JC(o),this.deviceList=new v8(e,o,this.olmDevice),this.deviceList.on(et.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[et.DevicesUpdated,et.WillUpdateDevices]),this.supportedAlgorithms=Array.from(Gb.keys()),this.outgoingRoomKeyRequestManager=new T8(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new u9,this.inRoomVerificationRequests=new c9;var c=this.baseApis.cryptoCallbacks||{},u=lN(o,this.olmDevice);this.crossSigningInfo=new gi(t,c,u),this.secretStorage=new U8(e,c,e),this.dehydrationManager=new d9(this),!c.getCrossSigningKey&&c.getSecretStorageKey&&(c.getCrossSigningKey=function(){var d=_(function*(f){return gi.getFromSecretStorage(f,a.secretStorage)});return function(f){return d.apply(this,arguments)}}())}init(){var e=arguments,t=this;return _(function*(){var{exportedOlmDevice:n,pickleKey:i}=e.length>0&&e[0]!==void 0?e[0]:{};S.log("Crypto: initialising Olm..."),yield globalThis.Olm.init(),S.log(n?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),yield t.olmDevice.init({fromExportedDevice:n,pickleKey:i}),S.log("Crypto: loading device list..."),yield t.deviceList.load(),t.deviceKeys["ed25519:"+t.deviceId]=t.olmDevice.deviceEd25519Key,t.deviceKeys["curve25519:"+t.deviceId]=t.olmDevice.deviceCurve25519Key,S.log("Crypto: fetching own devices...");var o=t.deviceList.getRawStoredDevicesForUser(t.userId);if(o||(o={}),!o[t.deviceId]){S.log("Crypto: adding this device to the store...");var s={keys:t.deviceKeys,algorithms:t.supportedAlgorithms,verified:uo.VERIFIED,known:!0};o[t.deviceId]=s,t.deviceList.storeDevicesForUser(t.userId,o),t.deviceList.saveIfDirty()}yield t.cryptoStore.doTxn("readonly",[be.STORE_ACCOUNT],a=>{t.cryptoStore.getCrossSigningKeys(a,l=>{l&&Object.keys(l).length!==0&&(S.log("Loaded cross-signing public keys from crypto store"),t.crossSigningInfo.setKeys(l))})}),t.deviceList.startTrackingDeviceList(t.userId),S.debug("Crypto: initialising roomlist..."),yield t.roomList.init(),S.log("Crypto: checking for key backup..."),t.backupManager.checkAndStart()})()}setDeviceIsolationMode(e){throw new Error("Not supported")}getVersion(){var e=sv.getOlmVersion();return"Olm ".concat(e[0],".").concat(e[1],".").concat(e[2])}getTrustCrossSignedDevices(){return this.trustCrossSignedDevices}getCryptoTrustCrossSignedDevices(){return this.trustCrossSignedDevices}setTrustCrossSignedDevices(e){this.trustCrossSignedDevices=e;for(var t of this.deviceList.getKnownUserIds()){var n=this.deviceList.getRawStoredDevicesForUser(t);for(var i of Object.keys(n)){var o=this.checkDeviceTrust(t,i);if(!o.isLocallyVerified()&&o.isCrossSigningVerified()){var s=this.deviceList.getStoredDevice(t,i);this.emit(et.DeviceVerificationChanged,t,i,s)}}}}setCryptoTrustCrossSignedDevices(e){this.setTrustCrossSignedDevices(e)}createRecoveryKeyFromPassphrase(e){return _(function*(){var t=new globalThis.Olm.PkDecryption;try{if(e){var n=yield Pw(e);t.init_with_private_key(n.key);var i=t.get_private_key();return{keyInfo:{passphrase:{algorithm:"m.pbkdf2",iterations:n.iterations,salt:n.salt}},privateKey:i,encodedPrivateKey:nv(i)}}else{t.generate_key();var o=t.get_private_key();return{privateKey:o,encodedPrivateKey:nv(o)}}}finally{t==null||t.free()}})()}userHasCrossSigningKeys(){var e=arguments,t=this;return _(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:t.userId;return yield t.downloadKeys([n]),t.deviceList.getStoredCrossSigningForUser(n)!==null})()}isCrossSigningReady(){var e=this;return _(function*(){var t=e.crossSigningInfo.getId(),n=(yield e.crossSigningInfo.isStoredInKeyCache())||(yield e.crossSigningInfo.isStoredInSecretStorage(e.secretStorage));return!!(t&&n)})()}isSecretStorageReady(){var e=this;return _(function*(){var t=yield e.secretStorage.hasKey(),n=yield e.crossSigningInfo.isStoredInSecretStorage(e.secretStorage),i=!e.backupManager.getKeyBackupEnabled()||(yield e.baseApis.isKeyBackupKeyStored());return!!(t&&n&&i)})()}getCrossSigningStatus(){var e=this;return _(function*(){var t,n,i,o=!!e.crossSigningInfo.getId(),s=!!(yield e.crossSigningInfo.isStoredInSecretStorage(e.secretStorage)),a=e.crossSigningInfo.getCacheCallbacks(),l=!!(yield(t=a.getCrossSigningKeyCache)===null||t===void 0?void 0:t.call(a,"master")),c=!!(yield(n=a.getCrossSigningKeyCache)===null||n===void 0?void 0:n.call(a,"self_signing")),u=!!(yield(i=a.getCrossSigningKeyCache)===null||i===void 0?void 0:i.call(a,"user_signing"));return{publicKeysOnDevice:o,privateKeysInSecretStorage:s,privateKeysCachedLocally:{masterKey:l,selfSigningKey:c,userSigningKey:u}}})()}bootstrapCrossSigning(){var e=arguments,t=this;return _(function*(){var{authUploadDeviceSigningKeys:n,setupNewCrossSigning:i}=e.length>0&&e[0]!==void 0?e[0]:{};S.log("Bootstrapping cross-signing");var o=t.baseApis.cryptoCallbacks,s=new ik(t.baseApis.store.accountData,o),a=new gi(t.userId,s.crossSigningCallbacks,s.crossSigningCallbacks),l=function(){var w=_(function*(){a.resetKeys(),yield t.signObject(a.keys.master),s.addCrossSigningKeys(n,a.keys);var g=t.deviceList.getStoredDevice(t.userId,t.deviceId),b=yield a.signDevice(t.userId,g);s.addKeySignature(t.userId,t.deviceId,b),t.backupManager.backupInfo&&(yield a.signObject(t.backupManager.backupInfo.auth_data,"master"),s.addSessionBackup(t.backupManager.backupInfo))});return function(){return w.apply(this,arguments)}}(),c=t.crossSigningInfo.getId(),u=yield t.crossSigningInfo.isStoredInKeyCache(),d=yield t.crossSigningInfo.isStoredInSecretStorage(t.secretStorage),f=u||d;S.log({setupNewCrossSigning:i,publicKeysOnDevice:c,privateKeysInCache:u,privateKeysInStorage:d,privateKeysExistSomewhere:f}),!f||i?(S.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),yield l()):c&&u?S.log("Cross-signing public keys trusted and private keys found locally"):d&&(S.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),yield t.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));var p=s.crossSigningCallbacks.privateKeys;if(p.size&&!t.baseApis.cryptoCallbacks.saveCrossSigningKeys){var h=new Kd(s.accountDataClientAdapter,s.ssssCryptoCallbacks);(yield h.hasKey())&&(S.log("Storing new cross-signing private keys in secret storage"),yield gi.storeInSecretStorage(p,h))}var m=s.buildOperation();yield m.apply(t),yield s.persist(t),S.log("Cross-signing ready")})()}bootstrapSecretStorage(){var e=arguments,t=this;return _(function*(){var{createSecretStorageKey:n=_(function*(){return{}}),keyBackupInfo:i,setupNewKeyBackup:o,setupNewSecretStorage:s,getKeyBackupPassphrase:a}=e.length>0&&e[0]!==void 0?e[0]:{};S.log("Bootstrapping Secure Secret Storage");var l=t.baseApis.cryptoCallbacks,c=new ik(t.baseApis.store.accountData,l),u=new Kd(c.accountDataClientAdapter,c.ssssCryptoCallbacks),d=null,f=function(){var ae=_(function*(q){var{keyId:z,keyInfo:Q}=yield u.addKey(Vi,q);return c.ssssCryptoCallbacks.addPrivateKey(z,Q,q.key),yield u.setDefaultKeyId(z),z});return function(z){return ae.apply(this,arguments)}}(),p=function(){var ae=_(function*(q,z){if(!z.mac){var Q,Ie,Y=yield(Q=(Ie=t.baseApis.cryptoCallbacks).getSecretStorageKey)===null||Q===void 0?void 0:Q.call(Ie,{keys:{[q]:z}},"");if(Y){var le=Y[1];c.ssssCryptoCallbacks.addPrivateKey(q,z,le);var{iv:B,mac:W}=yield Ca(le);z.iv=B,z.mac=W,yield c.setAccountData("m.secret_storage.key.".concat(q),z)}}});return function(z,Q){return ae.apply(this,arguments)}}(),h=function(){var ae=_(function*(q){if(t.crossSigningInfo.getId()&&(yield t.crossSigningInfo.isStoredInKeyCache("master")))try{S.log("Adding cross-signing signature to key backup"),yield t.crossSigningInfo.signObject(q,"master")}catch(z){S.error("Signing key backup with cross-signing keys failed",z)}else S.warn("Cross-signing keys not available, skipping signature on key backup")});return function(z){return ae.apply(this,arguments)}}(),m=yield t.secretStorage.getKey(),[w,g]=m||[null,null],b=!s&&g&&g.algorithm===Vi;if(S.log({keyBackupInfo:i,setupNewKeyBackup:o,setupNewSecretStorage:s,storageExists:b,oldKeyInfo:g}),!b&&!i){S.log("Secret storage does not exist, creating new storage key");var{keyInfo:R,privateKey:k}=yield n();d=yield f({passphrase:R==null?void 0:R.passphrase,key:k,name:R==null?void 0:R.name})}else if(!b&&i){S.log("Secret storage does not exist, using key backup key");var O=(yield t.getSessionBackupPrivateKey())||(yield a==null?void 0:a()),T={key:O};i.auth_data.private_key_salt&&i.auth_data.private_key_iterations&&(T.passphrase={algorithm:"m.pbkdf2",iterations:i.auth_data.private_key_iterations,salt:i.auth_data.private_key_salt,bits:256}),d=yield f(T),yield u.store("m.megolm_backup.v1",Qr(O),[d]),yield h(i.auth_data),c.addSessionBackup(i)}else S.log("Secret storage exists"),g&&g.algorithm===Vi&&(yield p(w,g));if(!t.baseApis.cryptoCallbacks.saveCrossSigningKeys&&(yield t.isCrossSigningReady())&&(d||!(yield t.crossSigningInfo.isStoredInSecretStorage(u)))){S.log("Copying cross-signing private keys from cache to secret storage");var x=yield t.crossSigningInfo.getCrossSigningKeysFromCache();yield gi.storeInSecretStorage(x,u)}if(o&&!i){S.log("Creating new message key backup version");var C=yield t.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),N=id(C.recovery_key);yield u.store("m.megolm_backup.v1",Qr(N));var F={algorithm:C.algorithm,auth_data:C.auth_data};yield h(F.auth_data),yield t.signObject(F.auth_data),c.addSessionBackup(F)}var H=yield u.get("m.megolm_backup.v1");if(H){S.info("Got session backup key from secret storage: caching");var ie=Yh(H);if(ie){var $=d||w;yield u.store("m.megolm_backup.v1",ie,$?[$]:null)}var X=new Uint8Array(Dr(ie||H));c.addSessionBackupPrivateKeyToCache(X)}else if(t.backupManager.getKeyBackupEnabled()){var oe=(yield t.getSessionBackupPrivateKey())||(yield a==null?void 0:a());if(!oe){S.error("Key backup is enabled but couldn't get key backup key!");return}S.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),yield u.store("m.megolm_backup.v1",Qr(oe))}var re=c.buildOperation();yield re.apply(t),yield c.persist(t),S.log("Secure Secret Storage ready")})()}resetKeyBackup(){var e=this;return _(function*(){yield e.backupManager.deleteAllKeyBackupVersions();var t=yield e.backupManager.prepareKeyBackupVersion();yield e.signObject(t.auth_data);var{version:n}=yield e.baseApis.http.authedRequest(Z.Post,"/room_keys/version",void 0,t,{prefix:Ot.V3});S.log("Created backup version ".concat(n));var i=t.privateKey;yield e.secretStorage.store("m.megolm_backup.v1",Qr(i)),yield e.storeSessionBackupPrivateKey(i),yield e.backupManager.checkAndStart(),yield e.backupManager.scheduleAllGroupSessionsForBackup()})()}deleteKeyBackupVersion(e){var t=this;return _(function*(){yield t.backupManager.deleteKeyBackupVersion(e)})()}addSecretStorageKey(e,t,n){return this.secretStorage.addKey(e,t,n)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}getSecretStorageKey(e){return this.secretStorage.getKey(e)}storeSecret(e,t,n){return this.secretStorage.store(e,t,n)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){return t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId))),this.secretStorage.request(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}checkSecretStoragePrivateKey(e,t){var n=null;try{n=new globalThis.Olm.PkDecryption;var i=n.init_with_private_key(e);return i===t}finally{var o;(o=n)===null||o===void 0||o.free()}}getSessionBackupPrivateKey(){var e=this;return _(function*(){var t=yield new Promise(s=>{e.cryptoStore.doTxn("readonly",[be.STORE_ACCOUNT],a=>{e.cryptoStore.getSecretStorePrivateKey(a,s,"m.megolm_backup.v1")})}),n=null;if(typeof t=="string"&&(n=new Uint8Array(Dr(Yh(t)||t)),yield e.storeSessionBackupPrivateKey(n)),t&&typeof t=="object"&&"ciphertext"in t){var i=Buffer.from(e.olmDevice.pickleKey),o=yield Ef(t,i,"m.megolm_backup.v1");n=Dr(o)}return n})()}storeSessionBackupPrivateKey(e,t){var n=this;return _(function*(){if(!(e instanceof Uint8Array))throw new Error("storeSessionBackupPrivateKey expects Uint8Array, got ".concat(e));var i=Buffer.from(n.olmDevice.pickleKey),o=yield Kc(Qr(e),i,"m.megolm_backup.v1");return n.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],s=>{n.cryptoStore.storeSecretStorePrivateKey(s,"m.megolm_backup.v1",o)})})()}loadSessionBackupPrivateKeyFromSecretStorage(){throw new Error("Not implmeented")}getActiveSessionBackupVersion(){var e=this;return _(function*(){if(e.backupManager.getKeyBackupEnabled()){var t;return(t=e.backupManager.version)!==null&&t!==void 0?t:null}return null})()}getKeyBackupInfo(){return _(function*(){throw new Error("Not implemented")})()}isKeyBackupTrusted(e){var t=this;return _(function*(){var n=yield t.backupManager.isKeyBackupTrusted(e);return hk(n)})()}checkKeyBackupAndEnable(){var e=this;return _(function*(){var t=yield e.backupManager.checkKeyBackup();return!t||!t.backupInfo?null:{backupInfo:t.backupInfo,trustInfo:hk(t.trustInfo)}})()}checkCrossSigningPrivateKey(e,t){var n=null;try{n=new globalThis.Olm.PkSigning;var i=n.init_with_seed(e);return i===t}finally{var o;(o=n)===null||o===void 0||o.free()}}afterCrossSigningLocalKeyChange(){var e=this;return _(function*(){S.info("Starting cross-signing key change post-processing");var t=e.deviceList.getStoredDevice(e.userId,e.deviceId),n=yield e.crossSigningInfo.signDevice(e.userId,t);S.info("Starting background key sig upload for ".concat(e.deviceId));var i=f=>{var{shouldEmit:p=!1}=f;return e.baseApis.uploadKeySignatures({[e.userId]:{[e.deviceId]:n}}).then(h=>{var{failures:m}=h||{};if(Object.keys(m||[]).length>0)throw p&&e.baseApis.emit(et.KeySignatureUploadFailure,m,"afterCrossSigningLocalKeyChange",i),new Du("Key upload failed",{failures:m});S.info("Finished background key sig upload for ".concat(e.deviceId))}).catch(h=>{S.error("Error during background key sig upload for ".concat(e.deviceId),h)})};i({shouldEmit:!0});var o=e.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(o){S.info("Starting device verification upgrade");var s={};for(var[a,l]of Object.entries(e.deviceList.crossSigningInfo)){var c=yield e.checkForDeviceVerificationUpgrade(a,gi.fromStorage(l,a));c&&(s[a]=c)}if(Object.keys(s).length>0){S.info("Found ".concat(Object.keys(s).length," verif users to upgrade"));try{var u=yield o({users:s});if(u)for(var d of u)d in s&&(yield e.baseApis.setDeviceVerified(d,s[d].crossSigningInfo.getId()))}catch(f){S.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",f)}}S.info("Finished device verification upgrade")}S.info("Finished cross-signing key change post-processing")})()}checkForDeviceVerificationUpgrade(e,t){var n=this;return _(function*(){var i=n.crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!i.isVerified()){var o=n.deviceList.getRawStoredDevicesForUser(e),s=yield n.checkForValidDeviceSignature(e,t.keys.master,o);if(s.length)return{devices:s.map(a=>tn.fromStorage(o[a],a)),crossSigningInfo:t}}})()}checkForValidDeviceSignature(e,t,n){var i=this;return _(function*(){var o=[];if(n&&t.signatures&&t.signatures[e])for(var s of Object.keys(t.signatures[e])){var[,a]=s.split(":",2);if(a in n&&n[a].verified===uo.VERIFIED)try{yield Sc(i.olmDevice,t,e,a,n[a].keys[s]),o.push(a)}catch{}}return o})()}getCrossSigningKeyId(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Iw.Master;return Promise.resolve(this.getCrossSigningId(e))}getCrossSigningId(e){return this.crossSigningInfo.getId(e)}getStoredCrossSigningForUser(e){return this.deviceList.getStoredCrossSigningForUser(e)}checkUserTrust(e){var t=this.deviceList.getStoredCrossSigningForUser(e);return t?this.crossSigningInfo.checkUserTrust(t):new od(!1,!1,!1)}getUserVerificationStatus(e){var t=this;return _(function*(){return t.checkUserTrust(e)})()}pinCurrentUserIdentity(e){return _(function*(){throw new Error("not implemented")})()}getDeviceVerificationStatus(e,t){var n=this;return _(function*(){var i=n.deviceList.getStoredDevice(e,t);return i?n.checkDeviceInfoTrust(e,i):null})()}checkDeviceTrust(e,t){var n=this.deviceList.getStoredDevice(e,t);return this.checkDeviceInfoTrust(e,n)}checkDeviceInfoTrust(e,t){var n=!!(t!=null&&t.isVerified()),i=this.deviceList.getStoredCrossSigningForUser(e);if(t&&i){var o=this.trustCrossSignedDevices||e===this.userId;return this.crossSigningInfo.checkDeviceTrust(i,t,n,o)}else return new Xl(!1,!1,n,!1)}checkIfOwnDeviceCrossSigned(e){var t,n=this.deviceList.getStoredDevice(this.userId,e);if(!n)return!1;var i=this.deviceList.getStoredCrossSigningForUser(this.userId);return(t=i==null?void 0:i.checkDeviceTrust(i,n,!1,!0).isCrossSigningVerified())!==null&&t!==void 0?t:!1}checkOwnCrossSigningTrust(){var e=arguments,t=this;return _(function*(){var{allowPrivateKeyRequests:n=!1}=e.length>0&&e[0]!==void 0?e[0]:{},i=t.userId;yield t.downloadKeys([t.userId]);var o=yield t.crossSigningInfo.getCrossSigningKeysFromCache(),s=t.deviceList.getStoredCrossSigningForUser(i);if(!s){S.error("Got cross-signing update event for user "+i+" but no new cross-signing information found!");return}var a=s.getId(),l=t.crossSigningInfo.getId()!==a,c=s.getId()&&!o.has("master");if(l&&S.info("Got new master public key",a),n&&(l||c)){S.info("Attempting to retrieve cross-signing master private key");var u=null;try{var d=yield t.crossSigningInfo.getCrossSigningKey("master",a);u=d[1],S.info("Got cross-signing master private key")}finally{var f;(f=u)===null||f===void 0||f.free()}}var p=t.crossSigningInfo.getId("self_signing"),h=t.crossSigningInfo.getId("user_signing");t.storeTrustedSelfKeys(s.keys);var m=p!==s.getId("self_signing"),w=h!==s.getId("user_signing"),g=s.getId("self_signing")&&!o.has("self_signing"),b=s.getId("user_signing")&&!o.has("user_signing"),R={};if(m&&S.info("Got new self-signing key",s.getId("self_signing")),n&&(m||g)){S.info("Attempting to retrieve cross-signing self-signing private key");var k=null;try{var O=yield t.crossSigningInfo.getCrossSigningKey("self_signing",s.getId("self_signing"));k=O[1],S.info("Got cross-signing self-signing private key")}finally{var T;(T=k)===null||T===void 0||T.free()}var x=t.deviceList.getStoredDevice(t.userId,t.deviceId),C=yield t.crossSigningInfo.signDevice(t.userId,x);R[t.deviceId]=C}if(w&&S.info("Got new user-signing key",s.getId("user_signing")),n&&(w||b)){S.info("Attempting to retrieve cross-signing user-signing private key");var N=null;try{var F=yield t.crossSigningInfo.getCrossSigningKey("user_signing",s.getId("user_signing"));N=F[1],S.info("Got cross-signing user-signing private key")}finally{var H;(H=N)===null||H===void 0||H.free()}}if(l){var ie=t.crossSigningInfo.keys.master;yield t.signObject(ie);var $=ie.signatures[t.userId]["ed25519:"+t.deviceId];R[t.crossSigningInfo.getId()]=Object.assign({},ie,{signatures:{[t.userId]:{["ed25519:"+t.deviceId]:$}}})}var X=Object.keys(R);if(X.length){var oe=re=>{var{shouldEmit:ae=!1}=re;return S.info("Starting background key sig upload for ".concat(X)),t.baseApis.uploadKeySignatures({[t.userId]:R}).then(q=>{var{failures:z}=q||{};if(S.info("Finished background key sig upload for ".concat(X)),Object.keys(z||[]).length>0)throw ae&&t.baseApis.emit(et.KeySignatureUploadFailure,z,"checkOwnCrossSigningTrust",oe),new Du("Key upload failed",{failures:z})}).catch(q=>{S.error("Error during background key sig upload for ".concat(X),q)})};oe({shouldEmit:!0})}t.emit(et.UserTrustStatusChanged,i,t.checkUserTrust(i)),l&&(t.emit(et.KeysChanged,{}),yield t.afterCrossSigningLocalKeyChange()),yield t.backupManager.checkKeyBackup()})()}getBackupDecryptor(e,t){return _(function*(){if(!(t instanceof Uint8Array))throw new Error("getBackupDecryptor expects Uint8Array");var n=yield ka.makeAlgorithm(e,_(function*(){return t}));return(yield n.keyMatches(t))?new g9(n):Promise.reject(new hr({errcode:$c.RESTORE_BACKUP_ERROR_BAD_KEY}))})()}importBackedUpRoomKeys(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return n.source="backup",this.importRoomKeys(e,n)}storeTrustedSelfKeys(e){var t=this;return _(function*(){e?t.crossSigningInfo.setKeys(e):t.crossSigningInfo.clearKeys(),yield t.cryptoStore.doTxn("readwrite",[be.STORE_ACCOUNT],n=>{t.cryptoStore.storeCrossSigningKeys(n,t.crossSigningInfo.keys)})})()}checkDeviceVerifications(e){var t=this;return _(function*(){var n=t.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(n){if(S.info("Starting device verification upgrade for ".concat(e)),t.crossSigningInfo.keys.user_signing){var i=t.deviceList.getStoredCrossSigningForUser(e);if(i){var o=yield t.checkForDeviceVerificationUpgrade(e,i);if(o){var s=yield n({users:{[e]:o}});s.includes(e)&&(yield t.baseApis.setDeviceVerified(e,i.getId()))}}}S.info("Finished device verification upgrade for ".concat(e))}})()}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(e){e.on(Ar.Membership,this.onMembership),e.on(Te.ToDeviceEvent,this.onToDeviceEvent),e.on(fe.Timeline,this.onTimelineEvent),e.on(ot.Decrypted,this.onTimelineEvent)}start(){S.warn("MatrixClient.crypto.start() is deprecated")}stop(){this.outgoingRoomKeyRequestManager.stop(),this.deviceList.stop(),this.dehydrationManager.stop(),this.backupManager.stop()}getDeviceEd25519Key(){return this.olmDevice.deviceEd25519Key}getDeviceCurve25519Key(){return this.olmDevice.deviceCurve25519Key}getOwnDeviceKeys(){var e=this;return _(function*(){if(!e.olmDevice.deviceCurve25519Key)throw new Error("Curve25519 key not yet created");if(!e.olmDevice.deviceEd25519Key)throw new Error("Ed25519 key not yet created");return{ed25519:e.olmDevice.deviceEd25519Key,curve25519:e.olmDevice.deviceCurve25519Key}})()}setGlobalBlacklistUnverifiedDevices(e){this.globalBlacklistUnverifiedDevices=e}getGlobalBlacklistUnverifiedDevices(){return this.globalBlacklistUnverifiedDevices}uploadDeviceKeys(){var e={algorithms:this.supportedAlgorithms,device_id:this.deviceId,keys:this.deviceKeys,user_id:this.userId};return this.signObject(e).then(()=>this.baseApis.uploadKeysRequest({device_keys:e}))}getNeedsNewFallback(){return!!this.needsNewFallback}maybeUploadOneTimeKeys(){var e=this,t=1e3*60,n=5;if(!this.oneTimeKeyCheckInProgress){var i=Date.now();if(!(this.lastOneTimeKeyCheck!==null&&i-this.lastOneTimeKeyCheck<t)){this.lastOneTimeKeyCheck=i;var o=this.olmDevice.maxNumberOfOneTimeKeys(),s=Math.floor(o/2),a=function(){var l=_(function*(c){for(;s>c||e.getNeedsNewFallback();){if(s>c){S.info("generating oneTimeKeys");var u=Math.min(s-c,n);yield e.olmDevice.generateOneTimeKeys(u)}if(e.getNeedsNewFallback()){var d=yield e.olmDevice.getFallbackKey();(!d.curve25519||Object.keys(d.curve25519).length==0)&&(S.info("generating fallback key"),e.fallbackCleanup&&(clearTimeout(e.fallbackCleanup),delete e.fallbackCleanup),yield e.olmDevice.generateFallbackKey())}S.info("calling uploadOneTimeKeys");var f=yield e.uploadOneTimeKeys();if(f.one_time_key_counts&&f.one_time_key_counts.signed_curve25519)c=f.one_time_key_counts.signed_curve25519;else throw new Error("response for uploading keys does not contain one_time_key_counts.signed_curve25519")}});return function(u){return l.apply(this,arguments)}}();this.oneTimeKeyCheckInProgress=!0,Promise.resolve().then(()=>this.oneTimeKeyCount!==void 0?Promise.resolve(this.oneTimeKeyCount):this.baseApis.uploadKeysRequest({}).then(l=>l.one_time_key_counts.signed_curve25519||0)).then(l=>a(l)).catch(l=>{S.error("Error uploading one-time keys",l.stack||l)}).finally(()=>{this.oneTimeKeyCount=void 0,this.oneTimeKeyCheckInProgress=!1})}}}uploadOneTimeKeys(){var e=this;return _(function*(){var t=[],n;if(e.getNeedsNewFallback()){n={};var i=yield e.olmDevice.getFallbackKey();for(var[o,s]of Object.entries(i.curve25519)){var a={key:s,fallback:!0};n["signed_curve25519:"+o]=a,t.push(e.signObject(a))}e.needsNewFallback=!1}var l=yield e.olmDevice.getOneTimeKeys(),c={};for(var u in l.curve25519)if(l.curve25519.hasOwnProperty(u)){var d={key:l.curve25519[u]};c["signed_curve25519:"+u]=d,t.push(e.signObject(d))}yield Promise.all(t);var f={one_time_keys:c};n&&(f["org.matrix.msc2732.fallback_keys"]=n,f.fallback_keys=n);var p=yield e.baseApis.uploadKeysRequest(f);return n&&(e.fallbackCleanup=setTimeout(()=>{delete e.fallbackCleanup,e.olmDevice.forgetOldFallbackKey()},60*60*1e3)),yield e.olmDevice.markKeysAsPublished(),p})()}downloadKeys(e,t){return this.deviceList.downloadKeys(e,!!t)}getStoredDevicesForUser(e){return this.deviceList.getStoredDevicesForUser(e)}getUserDeviceInfo(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=new Map,s=[],a=function*(d){var f=yield n.getStoredDevicesForUser(d);if(f){var p=new Map(f.map(h=>[h.deviceId,pk(h,d)]));o.set(d,p)}else s.push(d)};for(var l of e)yield*a(l);if(i&&s.length>0){var c=yield n.downloadKeys(s);c.forEach((u,d)=>{var f=new Map;u.forEach((p,h)=>f.set(h,pk(p,d))),o.set(d,f)})}return o})()}getStoredDevice(e,t){return this.deviceList.getStoredDevice(e,t)}saveDeviceList(e){return this.deviceList.saveIfDirty(e)}setDeviceVerified(e,t){var n=arguments,i=this;return _(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!0;yield i.setDeviceVerification(e,t,o)})()}crossSignDevice(e){var t=this;return _(function*(){yield t.setDeviceVerified(t.userId,e,!0)})()}setDeviceVerification(e,t){var n=arguments,i=this;return _(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:null,s=n.length>3&&n[3]!==void 0?n[3]:null,a=n.length>4&&n[4]!==void 0?n[4]:null,l=n.length>5?n[5]:void 0,c=i.deviceList.getStoredCrossSigningForUser(e);if((c==null?void 0:c.getId())===t){if(s!==null||a!==null)throw new Error("Cannot set blocked or known for a cross-signing key");if(!o)throw new Error("Cannot set a cross-signing key as unverified");var u=l?Object.values(l)[0]:null;if(l&&(Object.values(l).length!==1||u!==c.getId()))throw new Error("Key did not match expected value: expected ".concat(c.getId(),", got ").concat(u));if(!i.crossSigningInfo.getId()&&e===i.crossSigningInfo.userId&&(i.storeTrustedSelfKeys(c.keys),i.emit(et.UserTrustStatusChanged,i.userId,i.checkUserTrust(e))),e!==i.userId){S.info("Master key "+c.getId()+" for "+e+" marked verified. Signing...");var d=yield i.crossSigningInfo.signUser(c);if(d){var f=function(){var x=_(function*(C){var{shouldEmit:N=!1}=C;S.info("Uploading signature for "+e+"...");var F=yield i.baseApis.uploadKeySignatures({[e]:{[t]:d}}),{failures:H}=F||{};if(Object.keys(H||[]).length>0)throw N&&i.baseApis.emit(et.KeySignatureUploadFailure,H,"setDeviceVerification",f),new Du("Key upload failed",{failures:H})});return function(N){return x.apply(this,arguments)}}();yield f({shouldEmit:!0})}return d}else return c}var p=i.deviceList.getRawStoredDevicesForUser(e);if(!p||!p[t])throw new Error("Unknown device "+e+":"+t);var h=p[t],m=h.verified;if(o){if(l){for(var[w,g]of Object.entries(l))if(h.keys[w]!==g)throw new Error("Key did not match expected value: expected ".concat(g,", got ").concat(h.keys[w]))}m=uo.VERIFIED}else o!==null&&m==uo.VERIFIED&&(m=uo.UNVERIFIED);s?m=uo.BLOCKED:s!==null&&m==uo.BLOCKED&&(m=uo.UNVERIFIED);var b=h.known;if(a!==null&&(b=a),(h.verified!==m||h.known!==b)&&(h.verified=m,h.known=b,i.deviceList.storeDevicesForUser(e,p),i.deviceList.saveIfDirty()),o&&e===i.userId){S.info("Own device "+t+" marked verified: signing");var R,k=i.checkDeviceTrust(e,t);if(k.isCrossSigningVerified()?S.log("Own device ".concat(t," already cross-signing verified")):R=yield i.crossSigningInfo.signDevice(e,tn.fromStorage(h,t)),R){var O=function(){var x=_(function*(C){var{shouldEmit:N=!1}=C;S.info("Uploading signature for "+t);var F=yield i.baseApis.uploadKeySignatures({[e]:{[t]:R}}),{failures:H}=F||{};if(Object.keys(H||[]).length>0)throw N&&i.baseApis.emit(et.KeySignatureUploadFailure,H,"setDeviceVerification",O),new Du("Key upload failed",{failures:H})});return function(N){return x.apply(this,arguments)}}();yield O({shouldEmit:!0})}}var T=tn.fromStorage(h,t);return i.emit(et.DeviceVerificationChanged,e,t,T),T})()}findVerificationRequestDMInProgress(e,t){return this.inRoomVerificationRequests.findRequestInProgress(e,t)}getVerificationRequestsToDeviceInProgress(e){return this.toDeviceVerificationRequests.getRequestsInProgress(e)}requestVerificationDM(e,t){var n=this.inRoomVerificationRequests.findRequestInProgress(t);if(n)return Promise.resolve(n);var i=new Kr(this.baseApis,t,e);return this.requestVerificationWithChannel(e,i,this.inRoomVerificationRequests)}requestVerification(e,t){t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(e)));var n=this.toDeviceVerificationRequests.findRequestInProgress(e,t);if(n)return Promise.resolve(n);var i=new Br(this.baseApis,e,t,Br.makeTransactionId());return this.requestVerificationWithChannel(e,i,this.toDeviceVerificationRequests)}requestOwnUserVerification(){return this.requestVerification(this.userId)}requestDeviceVerification(e,t){return this.requestVerification(e,[t])}requestVerificationWithChannel(e,t,n){var i=this;return _(function*(){var o=new ga(t,i.verificationMethods,i.baseApis);t.transactionId&&n.setRequestByChannel(t,o),yield o.sendRequest();var s=n.getRequestByChannel(t);return s?o=s:(S.log("Crypto: adding new request to "+"requestsByTxnId with id ".concat(t.transactionId," ").concat(t.roomId)),n.setRequestByChannel(t,o)),o})()}beginKeyVerification(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,o;if(i){if(o=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(t,i),!o)throw new Error("No request found for user ".concat(t," with ")+"transactionId ".concat(i))}else{i=Br.makeTransactionId();var s=new Br(this.baseApis,t,[n],i,n);o=new ga(s,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(t,i,o)}return o.beginKeyVerification(e,{userId:t,deviceId:n})}legacyDeviceVerification(e,t,n){var i=this;return _(function*(){var o=Br.makeTransactionId(),s=new Br(i.baseApis,e,[t],o,t),a=new ga(s,i.verificationMethods,i.baseApis);i.toDeviceVerificationRequests.setRequestBySenderAndTxnId(e,o,a);var l=a.beginKeyVerification(n,{userId:e,deviceId:t});return yield Promise.race([l.verify(),a.waitFor(c=>c.started)]),a})()}getOlmSessionsForUser(e){var t=this;return _(function*(){var n=t.getStoredDevicesForUser(e)||[],i={};for(var o of n){var s=o.getIdentityKey(),a=yield t.olmDevice.getSessionInfoForDevice(s);i[o.deviceId]={deviceIdKey:s,sessions:a}}return i})()}getEventSenderDeviceInfo(e){var t=e.getSenderKey(),n=e.getWireContent().algorithm;if(!t||!n||e.isKeySourceUntrusted())return null;var i=this.deviceList.getDeviceByIdentityKey(n,t);if(i===null)return null;var o=e.getClaimedEd25519Key();return o?o!==i.getFingerprint()?(S.warn("Event "+e.getId()+" claims ed25519 key "+o+" but sender device has key "+i.getFingerprint()),null):i:(S.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(e){var t,n,i={};if(i.senderKey=(t=e.getSenderKey())!==null&&t!==void 0?t:void 0,i.algorithm=e.getWireContent().algorithm,!i.senderKey||!i.algorithm)return i.encrypted=!1,i;i.encrypted=!0,e.isKeySourceUntrusted()?i.authenticated=!1:i.authenticated=!0,i.sender=(n=this.deviceList.getDeviceByIdentityKey(i.algorithm,i.senderKey))!==null&&n!==void 0?n:void 0;var o=e.getClaimedEd25519Key();return o||(S.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),i.mismatchedSender=!0),i.sender&&o!==i.sender.getFingerprint()&&(S.warn("Event "+e.getId()+" claims ed25519 key "+o+"but sender device has key "+i.sender.getFingerprint()),i.mismatchedSender=!0),i}getEncryptionInfoForEvent(e){var t=this;return _(function*(){var n=t.getEventEncryptionInfo(e);if(!n.encrypted)return null;var i=e.getSender();if(!i||n.mismatchedSender)return{shieldColour:rs.RED,shieldReason:bl.MISMATCHED_SENDER_KEY};var o=t.checkUserTrust(i);if(!o.isCrossSigningVerified())return n.authenticated?{shieldColour:rs.NONE,shieldReason:null}:{shieldColour:rs.GREY,shieldReason:bl.AUTHENTICITY_NOT_GUARANTEED};var s=i&&n.sender&&(yield t.getDeviceVerificationStatus(i,n.sender.deviceId));return s?s.isVerified()?n.authenticated?{shieldColour:rs.NONE,shieldReason:null}:{shieldColour:rs.GREY,shieldReason:bl.AUTHENTICITY_NOT_GUARANTEED}:{shieldColour:rs.RED,shieldReason:bl.UNSIGNED_DEVICE}:{shieldColour:rs.GREY,shieldReason:bl.UNKNOWN_DEVICE}})()}forceDiscardSession(e){var t=this.roomEncryptors.get(e);if(t===void 0)throw new Error("Room not encrypted");if(t.forceDiscardSession===void 0)throw new Error("Room encryption algorithm doesn't support session discarding");return t.forceDiscardSession(),Promise.resolve()}setRoomEncryption(e,t,n){var i=this;return _(function*(){var o=i.clientStore.getRoom(e);if(!o)throw new Error("Unable to enable encryption tracking devices in unknown room ".concat(e));yield i.setRoomEncryptionImpl(o,t),!i.lazyLoadMembers&&!n&&i.deviceList.refreshOutdatedDeviceLists()})()}setRoomEncryptionImpl(e,t){var n=this;return _(function*(){var i=e.roomId;if(!t.algorithm){S.log("Ignoring setRoomEncryption with no algorithm");return}var o=n.roomList.getRoomEncryption(i);if(o&&JSON.stringify(o)!=JSON.stringify(t)){S.error("Ignoring m.room.encryption event which requests a change of config in "+i);return}var s=n.roomEncryptors.get(i);if(!s){var a=null;o||(a=n.roomList.setRoomEncryption(i,t));var l=cN.get(t.algorithm);if(!l)throw new Error("Unable to encrypt with "+t.algorithm);var c=new l({userId:n.userId,deviceId:n.deviceId,crypto:n,olmDevice:n.olmDevice,baseApis:n.baseApis,roomId:i,config:t});if(n.roomEncryptors.set(i,c),a&&(yield a),S.log("Enabling encryption in ".concat(i)),e.membersLoaded())yield n.trackRoomDevicesImpl(e);else{var u=d=>{e.off(Ne.Update,u),e.membersLoaded()&&n.trackRoomDevicesImpl(e).catch(f=>{S.error("Error enabling device tracking in ".concat(i),f)})};e.on(Ne.Update,u)}}})()}trackRoomDevices(e){var t=this.clientStore.getRoom(e);if(!t)throw new Error("Unable to start tracking devices in unknown room ".concat(e));return this.trackRoomDevicesImpl(t)}trackRoomDevicesImpl(e){var t=this,n=e.roomId,i=function(){var s=_(function*(){if(t.roomEncryptors.has(n)){S.log("Starting to track devices for room ".concat(n," ..."));var a=yield e.getEncryptionTargetMembers();a.forEach(l=>{t.deviceList.startTrackingDeviceList(l.userId)})}});return function(){return s.apply(this,arguments)}}(),o=this.roomDeviceTrackingState[n];return o||(o=i(),this.roomDeviceTrackingState[n]=o.catch(s=>{throw delete this.roomDeviceTrackingState[n],s})),o}ensureOlmSessionsForUsers(e,t){var n=new Map;for(var i of e){var o=[];n.set(i,o);var s=this.getStoredDevicesForUser(i)||[];for(var a of s){var l=a.getIdentityKey();l!=this.olmDevice.deviceCurve25519Key&&a.verified!=uo.BLOCKED&&o.push(a)}}return Io(this.olmDevice,this.baseApis,n,t)}exportRoomKeys(){var e=this;return _(function*(){var t=[];return yield e.cryptoStore.doTxn("readonly",[be.STORE_INBOUND_GROUP_SESSIONS],n=>{e.cryptoStore.getAllEndToEndInboundGroupSessions(n,i=>{if(i!==null){var o=e.olmDevice.exportInboundGroupSession(i.senderKey,i.sessionId,i.sessionData);delete o.first_known_index,o.algorithm=bn,t.push(o)}})}),t})()}exportRoomKeysAsJson(){var e=this;return _(function*(){return JSON.stringify(yield e.exportRoomKeys())})()}importRoomKeys(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=0,i=0,o=e.length;function s(){var a;(a=t.progressCallback)===null||a===void 0||a.call(t,{stage:"load_keys",successes:n,failures:i,total:o})}return Promise.all(e.map(a=>{if(!a.room_id||!a.algorithm)return S.warn("ignoring room key entry with missing fields",a),i++,t.progressCallback&&s(),null;var l=this.getRoomDecryptor(a.room_id,a.algorithm);return l.importRoomKey(a,t).finally(()=>{n++,t.progressCallback&&s()})})).then()}importRoomKeysAsJson(e,t){var n=this;return _(function*(){return yield n.importRoomKeys(JSON.parse(e))})()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(e){var t=this.roomEncryptors.get(e.roomId);t&&t.prepareToEncrypt(e)}encryptEvent(e,t){var n=this;return _(function*(){var i=e.getRoomId(),o=n.roomEncryptors.get(i);if(!o)throw new Error("Room "+i+" was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");yield n.trackRoomDevicesImpl(t);var s=e.getContent(),a=s["m.relates_to"];a&&(s=Object.assign({},s),delete s["m.relates_to"]);var l=s["io.element.performance_metrics"];l&&(s=Object.assign({},s),delete s["io.element.performance_metrics"]);var c=yield o.encryptMessage(t,e.getType(),s);a&&(c["m.relates_to"]=a),l&&(c["io.element.performance_metrics"]=l),e.makeEncrypted("m.room.encrypted",c,n.olmDevice.deviceCurve25519Key,n.olmDevice.deviceEd25519Key)})()}decryptEvent(e){var t=this;return _(function*(){if(e.isRedacted()){var n=new pr(S9({room_id:e.getRoomId()},e.getUnsigned().redacted_because)),i=e.getUnsigned().redacted_because;if(n.isEncrypted())try{var o=yield t.decryptEvent(n);i=o.clearEvent}catch(l){S.warn("Decryption of redaction failed. Falling back to unencrypted event.",l)}return{clearEvent:{room_id:e.getRoomId(),type:"m.room.message",content:{},unsigned:{redacted_because:i}}}}else{var s=e.getWireContent(),a=t.getRoomDecryptor(e.getRoomId(),s.algorithm);return a.decryptEvent(e)}})()}processDeviceLists(e){var t=this;return _(function*(){yield t.evalDeviceListChanges(e)})()}requestRoomKey(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(e,t,n).then(()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()}).catch(i=>{S.error("Error requesting key for event",i)})}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch(t=>{S.warn("Error clearing pending room key requests",t)})}cancelAndResendAllOutgoingKeyRequests(){var e=this;return _(function*(){yield e.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()})()}onCryptoEvent(e,t){var n=this;return _(function*(){var i=t.getContent();yield n.setRoomEncryptionImpl(e,i)})()}onSyncWillProcess(e){var t=this;return _(function*(){e.oldSyncToken||(S.log("Initial sync performed - resetting device tracking state"),t.deviceList.stopTrackingAllDeviceLists(),t.deviceList.startTrackingDeviceList(t.userId),t.roomDeviceTrackingState={}),t.sendKeyRequestsImmediately=!1})()}onSyncCompleted(e){var t=this;return _(function*(){var n;t.deviceList.setSyncToken((n=e.nextSyncToken)!==null&&n!==void 0?n:null),t.deviceList.saveIfDirty(),t.deviceList.startTrackingDeviceList(t.userId),t.deviceList.refreshOutdatedDeviceLists(),e.catchingUp||(t.maybeUploadOneTimeKeys(),t.processReceivedRoomKeyRequests(),t.outgoingRoomKeyRequestManager.sendQueuedRequests(),t.sendKeyRequestsImmediately=!0)})()}evalDeviceListChanges(e){var t=this;return _(function*(){if(Array.isArray(e==null?void 0:e.changed)&&e.changed.forEach(i=>{t.deviceList.invalidateUserDeviceList(i)}),Array.isArray(e==null?void 0:e.left)&&e.left.length){var n=new Set(yield t.getTrackedE2eUsers());e.left.forEach(i=>{n.has(i)||t.deviceList.stopTrackingDeviceList(i)})}})()}getTrackedE2eUsers(){var e=this;return _(function*(){var t=[];for(var n of e.getTrackedE2eRooms()){var i=yield n.getEncryptionTargetMembers();for(var o of i)t.push(o.userId)}return t})()}getTrackedE2eRooms(){return this.clientStore.getRooms().filter(e=>{var t=this.roomEncryptors.get(e.roomId);if(!t||!this.roomDeviceTrackingState[e.roomId])return!1;var n=e.getMyMembership();return n===Be.Join||n===Be.Invite})}encryptAndSendToDevices(e,t){var n=this;return _(function*(){try{var i=yield n.prepareToDeviceBatch(e,t);try{yield n.baseApis.queueToDevice(i)}catch(o){throw S.error("sendToDevice failed",o),o}}catch(o){throw S.error("encryptAndSendToDevices promises failed",o),o}})()}prepareToDeviceBatch(e,t){var n=this;return _(function*(){var i={eventType:V.RoomMessageEncrypted,batch:[]};return yield Promise.all(e.map(function(){var o=_(function*(s){var{userId:a,deviceInfo:l}=s,c=l.deviceId,u={algorithm:wr,sender_key:n.olmDevice.deviceCurve25519Key,ciphertext:{},[en]:_i()};i.batch.push({userId:a,deviceId:c,payload:u}),yield Io(n.olmDevice,n.baseApis,new Map([[a,[l]]])),yield Ns(u.ciphertext,n.userId,n.deviceId,n.olmDevice,a,l,t)});return function(s){return o.apply(this,arguments)}}())),i.batch=i.batch.filter(o=>Object.keys(o.payload.ciphertext).length>0?!0:(S.log("No ciphertext for device ".concat(o.userId,":").concat(o.deviceId,": pruning")),!1)),i})()}encryptToDeviceMessages(e,t,n){var i=this;return _(function*(){var o=new Set(t.map(l=>{var{userId:c}=l;return c})),s=yield i.downloadKeys(Array.from(o),!1),a=[];return t.forEach(l=>{var{userId:c,deviceId:u}=l,d=s.get(c);if(!d){S.warn("No devices found for user ".concat(c));return}d.has(u)?a.push({userId:c,deviceInfo:d.get(u)}):S.warn("No device found for user ".concat(c," with id ").concat(u))}),i.prepareToDeviceBatch(a,n)})()}preprocessToDeviceMessages(e){return _(function*(){return e.filter(t=>{var n;return t.type===V.RoomMessageEncrypted&&!["m.olm.v1.curve25519-aes-sha2"].includes((n=t.content)===null||n===void 0?void 0:n.algorithm)?(S.log("Ignoring invalid encrypted to-device event from "+t.sender),!1):!0})})()}updateOneTimeKeyCount(e){if(isFinite(e))this.oneTimeKeyCount=e;else throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number")}processKeyCounts(e,t){return e!==void 0&&this.updateOneTimeKeyCount(e.signed_curve25519||0),t!==void 0&&(this.needsNewFallback=!t.includes("signed_curve25519")),Promise.resolve()}onRoomKeyEvent(e){var t=e.getContent();if(!t.room_id||!t.algorithm){S.error("key event is missing fields");return}this.backupManager.checkedForBackup||this.backupManager.checkAndStart();var n=this.getRoomDecryptor(t.room_id,t.algorithm);n.onRoomKeyEvent(e)}onRoomKeyWithheldEvent(e){var t=e.getContent();if(t.code!=="m.no_olm"&&(!t.room_id||!t.session_id)||!t.algorithm||!t.sender_key){S.error("key withheld event is missing fields");return}S.info("Got room key withheld event from ".concat(e.getSender()," ")+"for ".concat(t.algorithm," session ").concat(t.sender_key,"|").concat(t.session_id," ")+"in room ".concat(t.room_id," with code ").concat(t.code," (").concat(t.reason,")"));var n=this.getRoomDecryptor(t.room_id,t.algorithm);if(n.onRoomKeyWithheldEvent&&n.onRoomKeyWithheldEvent(e),!t.room_id){var i=this.getRoomDecryptors(t.algorithm);for(var o of i)o.retryDecryptionFromSender(t.sender_key)}}onKeyVerificationMessage(e){if(Br.validateEvent(e,this.baseApis)){var t=n=>{if(Br.canCreateRequest(Br.getEventType(n))){var i=n.getContent(),o=i&&i.from_device;if(o){var s=n.getSender(),a=new Br(this.baseApis,s,[o]);return new ga(a,this.verificationMethods,this.baseApis)}}};this.handleVerificationEvent(e,this.toDeviceVerificationRequests,t)}}handleVerificationEvent(e,t,n){var i=arguments,o=this;return _(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!0;if(e.isSending()&&e.status!=je.SENT){var a,l;try{yield new Promise((f,p)=>{a=f,l=()=>{e.status==je.CANCELLED&&p(new Error("Event status set to CANCELLED."))},e.once(ot.LocalEventIdReplaced,a),e.on(ot.Status,l)})}catch(f){S.error("error while waiting for the verification event to be sent: ",f);return}finally{e.removeListener(ot.LocalEventIdReplaced,a),e.removeListener(ot.Status,l)}}var c=t.getRequest(e),u=!1;if(!c){if(c=n(e),!c){S.log("Crypto: could not find VerificationRequest for "+"".concat(e.getType(),", and could not create one, so ignoring."));return}u=!0,t.setRequest(e,c)}e.setVerificationRequest(c);try{yield c.channel.handleEvent(e,c,s)}catch(f){S.error("error while handling verification event",f)}var d=u&&!c.initiatedByMe&&!c.invalid&&!c.observeOnly;d&&(o.baseApis.emit(et.VerificationRequest,c),o.baseApis.emit(et.VerificationRequestReceived,c))})()}onToDeviceBadEncrypted(e){var t=this;return _(function*(){var n=e.getWireContent(),i=e.getSender(),o=n.algorithm,s=n.sender_key;t.baseApis.emit(Te.UndecryptableToDeviceEvent,e);var a=()=>{var m=t.getRoomDecryptors(bn);for(var w of m)w.retryDecryptionFromSender(s)};if(!(i===void 0||s===void 0||s===void 0)){var l=t.forceNewSessionRetryTime.getOrCreate(i),c=l.getOrCreate(s);if(c>Date.now()){S.debug("New session already forced with device ".concat(i,":").concat(s,": ")+"not forcing another until at least ".concat(new Date(c).toUTCString())),yield t.olmDevice.recordSessionProblem(s,"wedged",!0),a();return}l.set(s,Date.now()+_9);var u=t.deviceList.getDeviceByIdentityKey(o,s);if(!u&&(yield t.downloadKeys([i],!1),u=t.deviceList.getDeviceByIdentityKey(o,s),!u)){S.info("Couldn't find device for identity key "+s+": not re-establishing session"),yield t.olmDevice.recordSessionProblem(s,"wedged",!1),a();return}var d=new Map([[i,[u]]]);yield Io(t.olmDevice,t.baseApis,d,!0),l.set(s,Date.now()+b9);var f={algorithm:wr,sender_key:t.olmDevice.deviceCurve25519Key,ciphertext:{},[en]:_i()};yield Ns(f.ciphertext,t.userId,t.deviceId,t.olmDevice,i,u,{type:"m.dummy"}),yield t.olmDevice.recordSessionProblem(s,"wedged",!0),a(),yield t.baseApis.sendToDevice("m.room.encrypted",new Map([[i,new Map([[u.deviceId,f]])]]));var p=yield t.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(i,u.deviceId);for(var h of p)t.requestRoomKey(h.requestBody,h.recipients,!0)}})()}onRoomMembership(e,t,n){var i=t.roomId,o=this.roomEncryptors.get(i);if(o){if(i in this.roomDeviceTrackingState){var s;t.membership==Be.Join?(S.log("Join event for "+t.userId+" in "+i),this.deviceList.startTrackingDeviceList(t.userId)):t.membership==Be.Invite&&(s=this.clientStore.getRoom(i))!==null&&s!==void 0&&s.shouldEncryptForInvitedMembers()&&(S.log("Invite event for "+t.userId+" in "+i),this.deviceList.startTrackingDeviceList(t.userId))}o.onRoomMembership(e,t,n)}}onRoomKeyRequestEvent(e){var t=e.getContent();if(t.action==="request"){var n=new E9(e);this.receivedRoomKeyRequests.push(n)}else if(t.action==="request_cancellation"){var i=new w9(e);this.receivedRoomKeyRequestCancellations.push(i)}}processReceivedRoomKeyRequests(){var e=this;return _(function*(){if(!e.processingRoomKeyRequests){e.processingRoomKeyRequests=!0;try{var t=e.receivedRoomKeyRequests;e.receivedRoomKeyRequests=[];var n=e.receivedRoomKeyRequestCancellations;e.receivedRoomKeyRequestCancellations=[],yield Promise.all(t.map(i=>e.processReceivedRoomKeyRequest(i))),yield Promise.all(n.map(i=>e.processReceivedRoomKeyRequestCancellation(i)))}catch(i){S.error("Error processing room key requsts: ".concat(i))}finally{e.processingRoomKeyRequests=!1}}})()}processReceivedRoomKeyRequest(e){var t=this;return _(function*(){var n=e.userId,i=e.deviceId,o=e.requestBody,s=o.room_id,a=o.algorithm;if(S.log("m.room_key_request from ".concat(n,":").concat(i)+" for ".concat(s," / ").concat(o.session_id," (id ").concat(e.requestId,")")),n!==t.userId){if(!t.roomEncryptors.get(s)){S.debug("room key request for unencrypted room ".concat(s));return}var l=t.roomEncryptors.get(s),c=t.deviceList.getStoredDevice(n,i);if(!c){S.debug("Ignoring keyshare for unknown device ".concat(n,":").concat(i));return}try{yield l.reshareKeyWithDevice(o.sender_key,o.session_id,n,c)}catch(d){S.warn("Failed to re-share keys for session "+o.session_id+" with device "+n+":"+c.deviceId,d)}return}if(i===t.deviceId){S.log("Ignoring room key request from ourselves");return}if(!t.roomDecryptors.has(s)){S.log("room key request for unencrypted room ".concat(s));return}var u=t.roomDecryptors.get(s).get(a);if(!u){S.log("room key request for unknown alg ".concat(a," in room ").concat(s));return}if(!(yield u.hasKeysForKeyRequest(e))){S.log("room key request for unknown session ".concat(s," / ")+o.session_id);return}if(e.share=()=>{u.shareKeysWithDevice(e)},t.checkDeviceTrust(n,i).isVerified()){S.log("device is already verified: sharing keys"),e.share();return}t.emit(et.RoomKeyRequest,e)})()}processReceivedRoomKeyRequestCancellation(e){var t=this;return _(function*(){S.log("m.room_key_request cancellation for ".concat(e.userId,":")+"".concat(e.deviceId," (id ").concat(e.requestId,")")),t.emit(et.RoomKeyRequestCancellation,e)})()}getRoomDecryptor(e,t){var n,i;if(e&&(n=this.roomDecryptors.get(e),n||(n=new Map,this.roomDecryptors.set(e,n)),i=n.get(t),i))return i;var o=Gb.get(t);if(!o)throw new cr(Dt.UNKNOWN_ENCRYPTION_ALGORITHM,'Unknown encryption algorithm "'+t+'".');return i=new o({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:e??void 0}),n&&n.set(t,i),i}getRoomDecryptors(e){var t=[];for(var n of this.roomDecryptors.values())n.has(e)&&t.push(n.get(e));return t}signObject(e){var t=this;return _(function*(){var n=new Map(Object.entries(e.signatures||{})),i=e.unsigned;delete e.signatures,delete e.unsigned;var o=n.get(t.userId)||{};n.set(t.userId,o),o["ed25519:"+t.deviceId]=yield t.olmDevice.sign(ko.stringify(e)),e.signatures=ms(n),i!==void 0&&(e.unsigned=i)})()}isRoomEncrypted(e){return this.roomList.isRoomEncrypted(e)}isEncryptionEnabledInRoom(e){var t=this;return _(function*(){return t.isRoomEncrypted(e)})()}getRoomEncryption(e){return this.roomList.getRoomEncryption(e)}isDehydrationSupported(){return _(function*(){return!1})()}startDehydration(e){return _(function*(){throw new Error("Not implemented")})()}restoreKeyBackup(e){throw new Error("Not implemented")}restoreKeyBackupWithPassphrase(e,t){throw new Error("Not implemented")}}function Yh(r){if(typeof r!="string"||r.indexOf(",")<0)return null;var e=Uint8Array.from(r.split(","),t=>parseInt(t));return Qr(e)}class E9{constructor(e){v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"requestId",void 0),v(this,"requestBody",void 0),v(this,"share",void 0);var t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id,this.requestBody=t.body||{},this.share=()=>{throw new Error("don't know how to share keys for this request yet")}}}class w9{constructor(e){v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"requestId",void 0);var t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id}}class T9{constructor(e){this.ourEvent=e,v(this,"timeline",void 0),v(this,"ourEventIndex",0),v(this,"paginateTokens",{[Ge.Backward]:null,[Ge.Forward]:null}),this.timeline=[e]}getEvent(){return this.timeline[this.ourEventIndex]}getTimeline(){return this.timeline}getOurEventIndex(){return this.ourEventIndex}getPaginateToken(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return this.paginateTokens[e?Ge.Backward:Ge.Forward]}setPaginateToken(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.paginateTokens[t?Ge.Backward:Ge.Forward]=e??null}addEvents(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}class _m{static fromJson(e,t){var n=e.context||{},i=(n.events_before||[]).map(t),o=(n.events_after||[]).map(t),s=new T9(t(e.result)),a=s.ourEvent.threadRootId;return i=i.filter(l=>l.threadRootId===a),o=o.filter(l=>l.threadRootId===a),s.setPaginateToken(n.start,!0),s.addEvents(i,!0),s.addEvents(o,!1),s.setPaginateToken(n.end,!1),new _m(e.rank,s)}constructor(e,t){this.rank=e,this.context=t}}var R9=function(r){return r.Public="public",r.Private="private",r}({}),Mw=function(r){return r.PrivateChat="private_chat",r.TrustedPrivateChat="trusted_private_chat",r.PublicChat="public_chat",r}({}),yN=function(r){return r.Public="public",r.Invite="invite",r.Private="private",r.Knock="knock",r.Restricted="restricted",r}({}),C9=function(r){return r.RoomMembership="m.room_membership",r}({}),av=function(r){return r.CanJoin="can_join",r.Forbidden="forbidden",r}({}),Aw=function(r){return r.Invited="invited",r.Joined="joined",r.Shared="shared",r.WorldReadable="world_readable",r}({});function mk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function gk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?mk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):mk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function k9(r,e){var t=!!e.preventReEmit,n=e.decrypt!==!1;function i(o){e.toDevice&&delete o.room_id;var s=r.getRoom(o.room_id),a;s&&o.state_key===void 0&&(a=s.findEventById(o.event_id)),!a||a.status?a=new pr(o):(a.setUnsigned(gk(gk({},a.getUnsigned()),o.unsigned)),t=!0);var l=a.getServerAggregatedRelation(At.Replace);if(l!=null&&l.content){var c=i(l);a.makeReplaced(c)}var u=s==null?void 0:s.findThreadForEvent(a);return u&&a.setThread(u),a.isEncrypted()&&(t||r.reEmitter.reEmit(a,[ot.Decrypted]),n&&r.decryptEventIfNeeded(a)),t||(r.reEmitter.reEmit(a,[ot.Replaced,ot.VisibilityChange]),s==null||s.reEmitter.reEmit(a,[ot.BeforeRedaction])),a}return i}function yk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Jo(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?yk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):yk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class Sk{constructor(e,t,n){this.client=e,this.indexEvent=t,this.directory=n}get id(){var e=this.indexEvent.getStateKey();if(!e)throw new Error("State key not found for branch");return e}get isActive(){return this.indexEvent.getContent().active===!0}get version(){var e;return(e=this.indexEvent.getContent().version)!==null&&e!==void 0?e:1}get roomId(){return this.indexEvent.getRoomId()}delete(){var e=this;return _(function*(){yield e.client.sendStateEvent(e.roomId,yo.name,{},e.id),yield e.client.redactEvent(e.roomId,e.id);var t=(yield e.getVersionHistory())[1];t&&(yield t.delete())})()}getName(){return this.indexEvent.getContent().name||"Unnamed File"}setName(e){var t=this;return _(function*(){yield t.client.sendStateEvent(t.roomId,yo.name,Jo(Jo({},t.indexEvent.getContent()),{},{name:e}),t.id)})()}isLocked(){return this.indexEvent.getContent().locked||!1}setLocked(e){var t=this;return _(function*(){yield t.client.sendStateEvent(t.roomId,yo.name,Jo(Jo({},t.indexEvent.getContent()),{},{locked:e}),t.id)})()}getFileInfo(){var e=this;return _(function*(){var t=yield e.getFileEvent(),n=t.getOriginalContent().file,i=e.client.mxcUrlToHttp(n.url);if(!i)throw new Error("No HTTP URL available for ".concat(n.url));return{info:n,httpUrl:i}})()}getFileEvent(){var e=this;return _(function*(){var t=e.client.getRoom(e.roomId);if(!t)throw new Error("Unknown room");for(var n=t.getUnfilteredTimelineSet().findEventById(e.id);!n&&t.getLiveTimeline().getState(Ee.BACKWARDS).paginationToken;)yield e.client.scrollback(t,100),n=t.getUnfilteredTimelineSet().findEventById(e.id);if(!n)throw new Error("Failed to find event");return yield e.client.decryptEventIfNeeded(n),n})()}createNewVersion(e,t,n,i){var o=this;return _(function*(){var s=yield o.directory.createFile(e,t,n,Jo(Jo({},i??{}),{},{"m.new_content":!0,"m.relates_to":{rel_type:At.Replace,event_id:o.id}}));return yield o.client.sendStateEvent(o.roomId,yo.name,{active:!0,name:e,version:o.version+1},s.event_id),yield o.client.sendStateEvent(o.roomId,yo.name,Jo(Jo({},o.indexEvent.getContent()),{},{active:!1}),o.id),s})()}getVersionHistory(){var e=this;return _(function*(){var t=[];t.push(e);var n=e.client.getRoom(e.roomId);if(!n)throw new Error("Invalid or unknown room");var i=[...n.getLiveTimeline().getEvents()].reverse(),o,s=yield e.getFileEvent();do if(o=i.find(l=>l.replacingEventId()===s.getId()),o){var a=e.directory.getFile(o.getId());if(a)t.push(a),s=o;else break}while(o);return t})()}}function bk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function na(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?bk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):bk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var I9={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[V.RoomPowerLevels]:100,[V.RoomHistoryVisibility]:100,[V.RoomTombstone]:100,[V.RoomEncryption]:100,[V.RoomName]:50,[V.RoomMessage]:50,[V.RoomMessageEncrypted]:50,[V.Sticker]:50},users:{}},ll=function(r){return r.Viewer="viewer",r.Editor="editor",r.Owner="owner",r}({});class _k{constructor(e,t){if(this.client=e,this.roomId=t,v(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(){var e=this.room.currentState.getStateEvents(V.SpaceParent);return e!=null&&e.length?e.every(t=>{var n;return!((n=t.getContent())!==null&&n!==void 0&&n.via)}):!0}setName(e){var t=this;return _(function*(){yield t.client.sendStateEvent(t.roomId,V.RoomName,{name:e},"")})()}invite(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!0,o=[n.retryInvite(e)];i&&o.push(...n.getDirectories().map(s=>s.invite(e,i))),yield Promise.all(o)})()}retryInvite(e){var t=this;return U6(_(function*(){yield t.client.invite(t.roomId,e).catch(n=>{throw(n==null?void 0:n.errcode)==="M_FORBIDDEN"?new A1.AbortError(n):n})}))}setPermissions(e,t){var n=this;return _(function*(){var i,o=n.room.currentState.getStateEvents(V.RoomPowerLevels,"");if(Array.isArray(o))throw new Error("Unexpected return type for power levels");var s=(o==null?void 0:o.getContent())||{},a=s.users_default||0,l=s.events_default||50,c=((i=s.events)===null||i===void 0?void 0:i[V.RoomPowerLevels])||100,u=s.users||{};switch(t){case ll.Viewer:u[e]=a;break;case ll.Editor:u[e]=l;break;case ll.Owner:u[e]=c;break;default:throw new Error("Invalid role: "+t)}s.users=u,yield n.client.sendStateEvent(n.roomId,V.RoomPowerLevels,s,"")})()}getPermissions(e){var t,n,i=this.room.currentState.getStateEvents(V.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");var o=(i==null?void 0:i.getContent())||{},s=o.users_default||0,a=o.events_default||50,l=((t=o.events)===null||t===void 0?void 0:t[V.RoomPowerLevels])||100,c=((n=o.users)===null||n===void 0?void 0:n[e])||s;return c>=l?ll.Owner:c>=a?ll.Editor:ll.Viewer}createDirectory(e){var t=this;return _(function*(){var n=yield t.client.unstableCreateFileTree(e);return yield t.client.sendStateEvent(t.roomId,V.SpaceChild,{via:[t.client.getDomain()]},n.roomId),yield t.client.sendStateEvent(n.roomId,V.SpaceParent,{via:[t.client.getDomain()]},t.roomId),n})()}getDirectories(){var e=[],t=this.room.currentState.getStateEvents(V.SpaceChild);for(var n of t)try{var i=n.getStateKey();if(i){var o=this.client.unstableGetFileTreeSpace(i);o&&e.push(o)}}catch(s){S.warn("Unable to create tree space instance for listing. Are we joined?",s)}return e}getDirectory(e){return this.getDirectories().find(t=>t.roomId===e)}delete(){var e=this;return _(function*(){var t=e.getDirectories();for(var n of t)yield n.delete();var i=[Be.Invite,Be.Knock,Be.Join],o=e.room.currentState.getStateEvents(V.RoomMember);for(var s of o){var a=s.getStateKey()!==e.client.getUserId();if(a&&i.includes(s.getContent().membership)){var l=s.getStateKey();if(!l)throw new Error("State key not found for branch");yield e.client.kick(e.roomId,l,"Room deleted")}}yield e.client.leave(e.roomId)})()}getOrderedChildren(e){var t=e.map(n=>({roomId:n.getStateKey(),order:n.getContent().order})).filter(n=>n.roomId);return t.sort((n,i)=>{if(n.order&&!i.order)return-1;if(!n.order&&i.order)return 1;if(!n.order&&!i.order){var o,s,a,l,c=this.client.getRoom(n.roomId),u=this.client.getRoom(i.roomId);if(!c||!u)return Wh(n.roomId,i.roomId);var d=(o=(s=c.currentState.getStateEvents(V.RoomCreate,""))===null||s===void 0?void 0:s.getTs())!==null&&o!==void 0?o:0,f=(a=(l=u.currentState.getStateEvents(V.RoomCreate,""))===null||l===void 0?void 0:l.getTs())!==null&&a!==void 0?a:0;return d===f?Wh(n.roomId,i.roomId):d-f}else return Wh(n.order,i.order)}),t}getParentRoom(){var e=this.room.currentState.getStateEvents(V.SpaceParent),t=e[0];if(!t)throw new Error("Expected to have a parent in a non-top level space");var n=t.getStateKey();if(!n)throw new Error("No state key found for parent");var i=this.client.getRoom(n);if(!i)throw new Error("Unable to locate room for parent");return i}getOrder(){if(this.isTopLevel)return-1;var e=this.getParentRoom(),t=e.currentState.getStateEvents(V.SpaceChild),n=this.getOrderedChildren(t);return n.findIndex(i=>i.roomId===this.roomId)}setOrder(e){var t=this;return _(function*(){var n;if(t.isTopLevel)throw new Error("Cannot set order of top level spaces currently");var i=t.getParentRoom(),o=i.currentState.getStateEvents(V.SpaceChild),s=t.getOrderedChildren(o);e=Math.max(Math.min(e,s.length-1),0);var a=t.getOrder(),l=a<e;l&&e===s.length-1?e--:!l&&e===0&&e++;var c=s[l?e:e-1],u=s[l?e+1:e],d=Ds[0],f=!1;if(!c)u!=null&&u.order&&(d=nC(u.order));else if(e===s.length-1)u!=null&&u.order&&(d=cu(u.order));else{var p=c==null?void 0:c.order,h=u==null?void 0:u.order;p&&h?p===h?d=cu(p):d=j6(p,h):p?d=cu(p):h?d=nC(h):f=!0}if(f){for(var m,w=0;w<=e;w++){var g=s[w];if(w===0&&(m=g.order),g.order)m=g.order;else{var b;m=m?cu(m):Ds[0];var R=i.currentState.getStateEvents(V.SpaceChild,g.roomId),k=(b=R==null?void 0:R.getContent())!==null&&b!==void 0?b:{via:[t.client.getDomain()]};yield t.client.sendStateEvent(i.roomId,V.SpaceChild,na(na({},k),{},{order:m}),g.roomId)}}m&&(d=cu(m))}var O=i.currentState.getStateEvents(V.SpaceChild,t.roomId),T=(n=O==null?void 0:O.getContent())!==null&&n!==void 0?n:{via:[t.client.getDomain()]};yield t.client.sendStateEvent(i.roomId,V.SpaceChild,na(na({},T),{},{order:d}),t.roomId)})()}createFile(e,t,n,i){var o=this;return _(function*(){var s,{content_uri:a}=yield o.client.uploadContent(t,{includeFilename:!1});n.url=a;var l={msgtype:xi.File,body:e,url:a,file:n};i=(s=i)!==null&&s!==void 0?s:{},i["m.new_content"]&&(i["m.new_content"]=l);var c=yield o.client.sendMessage(o.roomId,na(na(na({},i),l),{},{[lD.name]:{}}));return yield o.client.sendStateEvent(o.roomId,yo.name,{active:!0,name:e},c.event_id),c})()}getFile(e){var t=this.room.currentState.getStateEvents(yo.name,e);return t?new Sk(this.client,t,this):null}listFiles(){return this.listAllFiles().filter(e=>e.isActive)}listAllFiles(){var e,t=(e=this.room.currentState.getStateEvents(yo.name))!==null&&e!==void 0?e:[];return t.map(n=>new Sk(this.client,n,this))}}var SN=function(r){return r.Recent="recent",r.Rank="rank",r}({}),ha=function(r){return r.LocalStreamsChanged="local_streams_changed",r}({});class x9 extends Tt{constructor(e){super(),this.client=e,v(this,"audioInput",void 0),v(this,"audioSettings",void 0),v(this,"videoInput",void 0),v(this,"localUserMediaStream",void 0),v(this,"userMediaStreams",[]),v(this,"screensharingStreams",[]),v(this,"getMediaStreamPromise",void 0)}restoreMediaSettings(e,t){this.audioInput=e,this.videoInput=t}setAudioInput(e){var t=this;return _(function*(){S.info("MediaHandler setAudioInput() running (deviceId=".concat(e,")")),t.audioInput!==e&&(t.audioInput=e,yield t.updateLocalUsermediaStreams())})()}setAudioSettings(e){var t=this;return _(function*(){S.info("MediaHandler setAudioSettings() running (opts=".concat(JSON.stringify(e),")")),t.audioSettings=Object.assign({},e),yield t.updateLocalUsermediaStreams()})()}setVideoInput(e){var t=this;return _(function*(){S.info("MediaHandler setVideoInput() running (deviceId=".concat(e,")")),t.videoInput!==e&&(t.videoInput=e,yield t.updateLocalUsermediaStreams())})()}setMediaInputs(e,t){var n=this;return _(function*(){S.log("MediaHandler setMediaInputs() running (audioInput: ".concat(e," videoInput: ").concat(t,")")),n.audioInput=e,n.videoInput=t,yield n.updateLocalUsermediaStreams()})()}updateLocalUsermediaStreams(){var e=this;return _(function*(){if(e.userMediaStreams.length!==0){var t=new Map;for(var n of e.client.callEventHandler.calls.values())t.set(n.callId,{audio:n.hasLocalUserMediaAudioTrack,video:n.hasLocalUserMediaVideoTrack});for(var i of e.userMediaStreams){S.log("MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=".concat(i.id,")"));for(var o of i.getTracks())o.stop()}e.userMediaStreams=[],e.localUserMediaStream=void 0;for(var s of e.client.callEventHandler.calls.values())if(!(s.callHasEnded()||!t.has(s.callId))){var{audio:a,video:l}=t.get(s.callId);S.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=".concat(s.callId,")"));var c=yield e.getUserMediaStream(a,l);s.callHasEnded()||(yield s.updateLocalUsermediaStream(c))}for(var u of e.client.groupCallEventHandler.groupCalls.values())if(u.localCallFeed){S.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=".concat(u.groupCallId,")"));var d=yield e.getUserMediaStream(!0,u.type===gm.Video);u.state!==Mt.Ended&&(yield u.updateLocalUsermediaStream(d))}e.emit(ha.LocalStreamsChanged)}})()}hasAudioDevice(){return _(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(t=>t.kind==="audioinput").length>0}catch(t){return S.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",t),!1}})()}hasVideoDevice(){return _(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(t=>t.kind==="videoinput").length>0}catch(t){return S.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",t),!1}})()}getUserMediaStream(e,t){var n=arguments,i=this;return _(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!0;return i.getMediaStreamPromise?i.getMediaStreamPromise=i.getMediaStreamPromise.then(()=>i.getUserMediaStreamInternal(e,t,o)):i.getMediaStreamPromise=i.getUserMediaStreamInternal(e,t,o),i.getMediaStreamPromise})()}getUserMediaStreamInternal(e,t,n){var i=this;return _(function*(){var o=e&&(yield i.hasAudioDevice()),s=t&&(yield i.hasVideoDevice()),a,l=!0;if(i.localUserMediaStream){var c,u;o!==i.localUserMediaStream.getAudioTracks().length>0&&(l=!1),s!==i.localUserMediaStream.getVideoTracks().length>0&&(l=!1),o&&((c=i.localUserMediaStream.getAudioTracks()[0])===null||c===void 0||(c=c.getSettings())===null||c===void 0?void 0:c.deviceId)!==i.audioInput&&(l=!1),s&&((u=i.localUserMediaStream.getVideoTracks()[0])===null||u===void 0||(u=u.getSettings())===null||u===void 0?void 0:u.deviceId)!==i.videoInput&&(l=!1)}else l=!1;if(l){var h;if(a=i.localUserMediaStream.clone(),S.log("MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=".concat((h=i.localUserMediaStream)===null||h===void 0?void 0:h.id," newStreamId=").concat(a.id," shouldRequestAudio=").concat(o," shouldRequestVideo=").concat(s,")")),!o)for(var m of a.getAudioTracks())a.removeTrack(m);if(!s)for(var w of a.getVideoTracks())a.removeTrack(w)}else{var d=i.getUserMediaContraints(o,s);a=yield navigator.mediaDevices.getUserMedia(d),S.log("MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=".concat(a.id,", shouldRequestAudio=").concat(o,", shouldRequestVideo=").concat(s,", constraints=").concat(JSON.stringify(d),")"));for(var f of a.getTracks()){var p=f.getSettings();f.kind==="audio"?i.audioInput=p.deviceId:f.kind==="video"&&(i.videoInput=p.deviceId)}n&&(i.localUserMediaStream=a)}return n&&i.userMediaStreams.push(a),i.emit(ha.LocalStreamsChanged),a})()}stopUserMediaStream(e){S.log("MediaHandler stopUserMediaStream() stopping (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop();var n=this.userMediaStreams.indexOf(e);if(n!==-1&&(S.debug("MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=".concat(e.id,")"),e.id),this.userMediaStreams.splice(n,1)),this.emit(ha.LocalStreamsChanged),this.localUserMediaStream===e)this.localUserMediaStream=void 0;else for(var i of e.getTracks()){var o;if((o=this.localUserMediaStream)!==null&&o!==void 0&&o.getTrackById(i.id)){this.stopUserMediaStream(this.localUserMediaStream);break}}}getScreensharingStream(){var e=arguments,t=this;return _(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:{},i=e.length>1&&e[1]!==void 0?e[1]:!0,o;if(t.screensharingStreams.length===0){var s=t.getScreenshareContraints(n);n.desktopCapturerSourceId?(S.debug("MediaHandler getScreensharingStream() calling getUserMedia() (opts=".concat(JSON.stringify(n),")")),o=yield navigator.mediaDevices.getUserMedia(s)):(S.debug("MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=".concat(JSON.stringify(n),")")),o=yield navigator.mediaDevices.getDisplayMedia(s))}else{var a=t.screensharingStreams[t.screensharingStreams.length-1];S.log("MediaHandler getScreensharingStream() cloning (streamId=".concat(a.id,")")),o=a.clone()}return i&&t.screensharingStreams.push(o),t.emit(ha.LocalStreamsChanged),o})()}stopScreensharingStream(e){S.debug("MediaHandler stopScreensharingStream() stopping stream (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop();var n=this.screensharingStreams.indexOf(e);n!==-1&&(S.debug("MediaHandler stopScreensharingStream() splicing stream out (streamId=".concat(e.id,")")),this.screensharingStreams.splice(n,1)),this.emit(ha.LocalStreamsChanged)}stopAllStreams(){for(var e of this.userMediaStreams){S.log("MediaHandler stopAllStreams() stopping (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop()}for(var n of this.screensharingStreams)for(var i of n.getTracks())i.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0,this.emit(ha.LocalStreamsChanged)}getUserMediaContraints(e,t){var n=!!navigator.webkitGetUserMedia;return{audio:e?{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:t?{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:n?{exact:640}:{ideal:640},height:n?{exact:360}:{ideal:360}}:!1}}getScreenshareContraints(e){var{desktopCapturerSourceId:t,audio:n}=e;return t?{audio:n??!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t}}}:{audio:n??!1,video:!0}}}var Ek=function(r){return r.RequestFinished="FINISHED",r.Complete="COMPLETE",r}({}),wf=function(r){return r.PreProcess="ExtState.PreProcess",r.PostProcess="ExtState.PostProcess",r}({}),t_=function(r){return r.RoomData="SlidingSync.RoomData",r.Lifecycle="SlidingSync.Lifecycle",r.List="SlidingSync.List",r}({}),O9=3;class P9{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return wf.PreProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return _(function*(){e.device_lists&&(yield t.crypto.processDeviceLists(e.device_lists)),yield t.crypto.processKeyCounts(e.device_one_time_keys_count,e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]),t.crypto.onSyncCompleted({})})()}}class M9{constructor(e,t){this.client=e,this.cryptoCallbacks=t,v(this,"nextBatch",null)}name(){return"to_device"}when(){return wf.PreProcess}onRequest(e){var t={since:this.nextBatch!==null?this.nextBatch:void 0};return e&&(t.limit=100,t.enabled=!0),t}onResponse(e){var t=this;return _(function*(){var n=[],i=e.events||[];i.length>0&&t.cryptoCallbacks&&(i=yield t.cryptoCallbacks.preprocessToDeviceMessages(i)),i.map(t.client.getEventMapper()).map(o=>{if(o.getType()==="m.key.verification.cancel"){var s=o.getContent().transaction_id;s&&n.push(s)}return o}).forEach(o=>{var s=o.getContent();if(o.getType()=="m.room.message"&&s.msgtype=="m.bad.encrypted"){S.log("Ignoring undecryptable to-device event from "+o.getSender());return}if(o.getType()==="m.key.verification.start"||o.getType()==="m.key.verification.request"){var a=s.transaction_id;n.includes(a)&&o.flagCancelled()}t.client.emit(Te.ToDeviceEvent,o)}),t.nextBatch=e.next_batch})()}}class A9{constructor(e){this.client=e}name(){return"account_data"}when(){return wf.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return _(function*(){e.global&&e.global.length>0&&t.processGlobalAccountData(e.global);for(var n in e.rooms){var i=Ql(t.client,n,e.rooms[n]),o=t.client.getRoom(n);if(!o){S.warn("got account data for room but room doesn't exist on client:",n);continue}o.addAccountData(i),i.forEach(s=>{t.client.emit(Te.Event,s)})}})()}processGlobalAccountData(e){var t=Ql(this.client,void 0,e),n=t.reduce((i,o)=>(i[o.getType()]=this.client.store.getAccountData(o.getType()),i),{});this.client.store.storeAccountDataEvents(t),t.forEach(i=>{if(i.getType()===V.PushRules){var o=i.getContent();this.client.setPushRules(o)}var s=n[i.getType()];return this.client.emit(Te.AccountData,i,s),i})}}class D9{constructor(e){this.client=e}name(){return"typing"}when(){return wf.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return _(function*(){if(e!=null&&e.rooms)for(var n in e.rooms)_N(t.client,n,[e.rooms[n]])})()}}class N9{constructor(e){this.client=e}name(){return"receipts"}when(){return wf.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return _(function*(){if(e!=null&&e.rooms)for(var n in e.rooms)_N(t.client,n,[e.rooms[n]])})()}}class bN{constructor(e,t,n,i){this.slidingSync=e,this.client=t,v(this,"opts",void 0),v(this,"syncOpts",void 0),v(this,"syncState",null),v(this,"syncStateData",void 0),v(this,"lastPos",null),v(this,"failCount",0),v(this,"notifEvents",[]),this.opts=VD(n),this.syncOpts=$D(i),t.getNotifTimelineSet()&&t.reEmitter.reEmit(t.getNotifTimelineSet(),[fe.Timeline,fe.TimelineReset]),this.slidingSync.on(t_.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(t_.RoomData,this.onRoomData.bind(this));var o=[new M9(this.client,this.syncOpts.cryptoCallbacks),new A9(this.client),new D9(this.client),new N9(this.client)];this.syncOpts.crypto&&o.push(new P9(this.syncOpts.crypto)),o.forEach(s=>{this.slidingSync.registerExtension(s)})}onRoomData(e,t){var n=this;return _(function*(){var i=n.client.store.getRoom(e);if(!i){if(!t.initial){S.debug("initial flag not set but no stored room exists for room ",e,t);return}i=WD(n.client,e,n.opts)}yield n.processRoomData(n.client,i,t)})()}onLifecycle(e,t,n){switch(n&&S.debug("onLifecycle",e,n),e){case Ek.Complete:if(this.purgeNotifications(),!t)break;this.lastPos||this.updateSyncState(ct.Prepared,{oldSyncToken:void 0,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(ct.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.lastPos=t.pos;break;case Ek.RequestFinished:if(n){if(this.failCount+=1,this.updateSyncState(this.failCount>O9?ct.Error:ct.Reconnecting,{error:new hr(n)}),this.shouldAbortSync(new hr(n)))return}else this.failCount=0;break}}syncLeftRooms(){return _(function*(){return[]})()}peek(e){return _(function*(){return null})()}stopPeeking(){}setPresence(e){}getSyncState(){return this.syncState}getSyncStateData(){var e;return(e=this.syncStateData)!==null&&e!==void 0?e:null}createRoom(e){var{timelineSupport:t}=this.client,n=new pm(e,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t});return this.client.reEmitter.reEmit(n,[fe.Name,fe.Redaction,fe.RedactionCancelled,fe.Receipt,fe.Tags,fe.LocalEchoUpdated,fe.AccountData,fe.MyMembership,fe.Timeline,fe.TimelineReset]),this.registerStateListeners(n),n}registerStateListeners(e){this.client.reEmitter.reEmit(e.currentState,[Ne.Events,Ne.Members,Ne.NewMember,Ne.Update]),e.currentState.on(Ne.NewMember,(t,n,i)=>{var o;i.user=(o=this.client.getUser(i.userId))!==null&&o!==void 0?o:void 0,this.client.reEmitter.reEmit(i,[Ar.Name,Ar.Typing,Ar.PowerLevel,Ar.Membership])})}shouldAbortSync(e){return e.errcode==="M_UNKNOWN_TOKEN"?(S.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(ct.Error,{error:e}),!0):!1}processRoomData(e,t,n){var i=this;return _(function*(){n=L9(e,t.roomId,n);var o=Ql(i.client,t.roomId,n.required_state),s=Ql(i.client,t.roomId,n.timeline,!1),a=[];if(n.initial){var l=new Set;t.getLiveTimeline().getEvents().forEach(b=>{l.add(b.getId())});for(var c=[],u=[],d=!1,f=s.length-1;f>=0;f--){var p=s[f];if(l.has(p.getId())){d=!0;continue}d?c.push(p):u.unshift(p)}s=u,c.length>0&&t.addEventsToTimeline(c,!0,t.getLiveTimeline(),n.prev_batch)}var h=t.hasEncryptionStateEvent();if(n.notification_count!=null&&t.setUnreadNotificationCount(it.Total,n.notification_count),n.highlight_count!=null&&(!h||h&&t.getUnreadNotificationCount(it.Highlight)<=0)&&t.setUnreadNotificationCount(it.Highlight,n.highlight_count),Number.isInteger(n.invited_count)&&t.currentState.setInvitedMemberCount(n.invited_count),Number.isInteger(n.joined_count)&&t.currentState.setJoinedMemberCount(n.joined_count),n.invite_state){var m=Ql(i.client,t.roomId,n.invite_state);yield i.injectRoomEvents(t,m),n.initial&&(t.recalculate(),i.client.store.storeRoom(t),i.client.emit(Te.Room,t)),m.forEach(b=>{i.client.emit(Te.Event,b)}),t.updateMyMembership(Be.Invite);return}if(n.initial){var w;t.getLiveTimeline().setPaginationToken((w=n.prev_batch)!==null&&w!==void 0?w:null,Ee.BACKWARDS)}yield i.injectRoomEvents(t,o,s,n.num_live),t.addEphemeralEvents(a),t.updateMyMembership(Be.Join),t.recalculate(),n.initial&&(e.store.storeRoom(t),e.emit(Te.Room,t)),i.addNotifications(s);var g=function(){var b=_(function*(R){e.emit(Te.Event,R),R.isState()&&R.getType()==V.RoomEncryption&&i.syncOpts.cryptoCallbacks&&(yield i.syncOpts.cryptoCallbacks.onCryptoEvent(t,R))});return function(k){return b.apply(this,arguments)}}();yield Ll(o,g),yield Ll(s,g),a.forEach(function(b){e.emit(Te.Event,b)}),t.decryptCriticalEvents()})()}injectRoomEvents(e,t,n,i){var o=this;return _(function*(){n=n||[],t=t||[],i=i||0;var s=e.getLiveTimeline(),a=s.getEvents().length==0;if(a){for(var l of t)o.client.getPushActionsForEvent(l);s.initialiseState(t)}a||(e.oldState.setStateEvents(t),e.currentState.setStateEvents(t));var c=[];i>0&&(c=n.slice(-1*i),n=n.slice(0,-1*c.length)),yield e.addLiveEvents(n,{fromCache:!0}),c.length>0&&(yield e.addLiveEvents(c,{fromCache:!1})),e.recalculate(),o.resolveInvites(e)})()}resolveInvites(e){if(!(!e||!this.opts.resolveInvitesToProfiles)){var t=this.client;e.getMembersWithMembership(Be.Invite).forEach(function(n){if(!n.requestedProfileInfo){n.requestedProfileInfo=!0;var i=t.getUser(n.userId),o;i?o=Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):o=t.getProfileInfo(n.userId),o.then(function(s){var a=n.events.member;a.getContent().membership===Be.Invite&&(a.getContent().avatar_url=s.avatar_url,a.getContent().displayname=s.displayname,n.setMembershipEvent(a,e.currentState))},function(s){})}})}}retryImmediately(){return!0}sync(){var e=this;return _(function*(){for(S.debug("Sliding sync init loop");!e.client.isGuest();)try{S.debug("Getting push rules...");var t=yield e.client.getPushRules();S.debug("Got push rules"),e.client.pushRules=t;break}catch(n){if(S.error("Getting push rules failed",n),e.shouldAbortSync(n))return}yield e.slidingSync.start()})()}stop(){S.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,t){var n=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(Te.Sync,this.syncState,n,t)}addNotifications(e){if(this.client.getNotifTimelineSet())for(var t of e){var n=this.client.getPushActionsForEvent(t);n&&n.notify&&n.tweaks&&n.tweaks.highlight&&this.notifEvents.push(t)}}purgeNotifications(){this.notifEvents.sort(function(e,t){return e.getTs()-t.getTs()}),this.notifEvents.forEach(e=>{var t;(t=this.client.getNotifTimelineSet())===null||t===void 0||t.addLiveEvent(e)}),this.notifEvents=[]}}function L9(r,e,t){if(!t.name)return t;for(var n of t.required_state)if(n.type===V.RoomName&&n.state_key==="")return n.content={name:t.name},t;return t.required_state.push({event_id:"$fake-sliding-sync-name-event-"+e,state_key:"",type:V.RoomName,content:{name:t.name},sender:r.getUserId(),origin_server_ts:new Date().getTime()}),t}function Ql(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=r.getEventMapper({decrypt:n});return t.map(function(o){return o.room_id=e,i(o)})}function _N(r,e,t){var n=Ql(r,e,t),i=r.getRoom(e);if(!i){S.warn("got ephemeral events for room but room doesn't exist on client:",e);return}i.addEphemeralEvents(n),n.forEach(o=>{r.emit(Te.Event,o)})}class Ec{static RETRY_BACKOFF_RATELIMIT(e,t,n){return LD(n,t,!1)}static QUEUE_MESSAGES(e){return e.getType()===V.RoomMessage||e.hasAssociation()?"message":null}constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ec.RETRY_BACKOFF_RATELIMIT,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ec.QUEUE_MESSAGES;this.retryAlgorithm=e,this.queueAlgorithm=t,v(this,"queues",{}),v(this,"activeQueues",[]),v(this,"procFn",null),v(this,"processQueue",n=>{var i=this.peekNextEvent(n);if(!i){this.disableQueue(n);return}this.queues[n].length,Promise.resolve().then(()=>this.procFn(i.event)).then(o=>{this.removeNextEvent(n),i.event.getId(),i.defer.resolve(o),this.processQueue(n)},o=>{i.attempts+=1;var s=this.retryAlgorithm(i.event,i.attempts,o);i.attempts,i.event.getId(),s===-1?(S.info("Queue '%s' giving up on event %s",n,i.event.getId()),this.clearQueue(n,o)):setTimeout(this.processQueue,s,n)})})}getQueueForEvent(e){var t=this.queueAlgorithm(e);return!t||!this.queues[t]?null:this.queues[t].map(function(n){return n.event})}removeEventFromQueue(e){var t=this.queueAlgorithm(e);if(!t||!this.queues[t])return!1;var n=!1;return zp(this.queues[t],i=>i.event.getId()===e.getId()?(n=!0,!0):!1),n}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){var t=this.queueAlgorithm(e);if(!t)return null;this.queues[t]||(this.queues[t]=[]);var n=Gs();return this.queues[t].push({event:e,defer:n,attempts:0}),e.getId(),this.startProcessingQueues(),n.promise}startProcessingQueues(){this.procFn&&Object.keys(this.queues).filter(e=>this.activeQueues.indexOf(e)===-1&&this.queues[e].length>0).forEach(e=>{this.activeQueues.push(e),this.processQueue(e)})}disableQueue(e){var t=this.activeQueues.indexOf(e);t>=0&&this.activeQueues.splice(t,1),S.info("Stopping queue '%s' as it is now empty",e)}clearQueue(e,t){S.info("clearing queue '%s'",e);for(var n;n=this.removeNextEvent(e);)n.defer.reject(t);this.disableQueue(e)}peekNextEvent(e){var t=this.queues[e];if(Array.isArray(t))return t[0]}removeNextEvent(e){var t=this.queues[e];if(Array.isArray(t))return t.shift()}}var wk=20;class U9{constructor(e){var t=this;this.client=e,v(this,"sending",!1),v(this,"running",!0),v(this,"retryTimeout",null),v(this,"retryAttempts",0),v(this,"sendQueue",_(function*(){if(t.retryTimeout!==null&&clearTimeout(t.retryTimeout),t.retryTimeout=null,!(t.sending||!t.running)){S.debug("Attempting to send queued to-device messages"),t.sending=!0;var n;try{for(;t.running&&(n=yield t.client.store.getOldestToDeviceBatch(),n!==null);)yield t.sendBatch(n),yield t.client.store.removeToDeviceBatch(n.id),t.retryAttempts=0;if(!t.running)return;S.debug("All queued to-device messages sent")}catch(o){++t.retryAttempts;var i=Ec.RETRY_BACKOFF_RATELIMIT(null,t.retryAttempts,o);if(i===-1){Math.floor(o.httpStatus/100)===4?(S.error("Fatal error when sending to-device message - dropping to-device batch!",o),yield t.client.store.removeToDeviceBatch(n.id)):S.info("Automatic retry limit reached for to-device messages.");return}S.info("Failed to send batch of to-device messages. Will retry in ".concat(i,"ms"),o),t.retryTimeout=setTimeout(t.sendQueue,i)}finally{t.sending=!1}}})),v(this,"onResumedSync",(n,i)=>{n===ct.Syncing&&i!==ct.Syncing&&(S.info("Resuming queue after resumed sync"),this.sendQueue())})}start(){this.running=!0,this.sendQueue(),this.client.on(Te.Sync,this.onResumedSync)}stop(){this.running=!1,this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.client.removeListener(Te.Sync,this.onResumedSync)}queueBatch(e){var t=this;return _(function*(){for(var n=[],i=0;i<e.batch.length;i+=wk){var o={eventType:e.eventType,batch:e.batch.slice(i,i+wk),txnId:t.client.makeTxnId()};n.push(o);var s=o.batch.map(a=>"".concat(a.userId,"/").concat(a.deviceId," (msgid ").concat(a.payload[en],")"));S.info("Enqueuing batch of to-device messages. type=".concat(e.eventType," txnid=").concat(o.txnId),s)}yield t.client.store.saveToDeviceBatches(n),t.sendQueue()})()}sendBatch(e){var t=this;return _(function*(){var n=new qt(()=>new Map);for(var i of e.batch)n.getOrCreate(i.userId).set(i.deviceId,i.payload);S.info("Sending batch of ".concat(e.batch.length," to-device messages with ID ").concat(e.id," and txnId ").concat(e.txnId)),yield t.client.sendToDevice(e.eventType,n,e.txnId)})()}}var ry=new ln.UnstableValue("m.policies","org.matrix.msc3847.policies"),mh=new ln.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites"),Tk=function(r){return r.Ban="m.ban",r}({}),Zl=function(r){return r.User="m.policy.user",r.Room="m.policy.room",r.Server="m.policy.server",r}({}),Rk={[Zl.User]:V.PolicyRuleUser,[Zl.Room]:V.PolicyRuleRoom,[Zl.Server]:V.PolicyRuleServer};class j9{constructor(e){this.client=e}addRule(e,t,n){var i=this;return _(function*(){var o=yield i.getOrCreateTargetRoom(),s=yield i.client.sendStateEvent(o.roomId,Rk[e],{entity:t,reason:n,recommendation:Tk.Ban});return s.event_id})()}removeRule(e){var t=this;return _(function*(){yield t.client.redactEvent(e.getRoomId(),e.getId())})()}addSource(e){var t=this;return _(function*(){yield t.client.joinRoom(e);var n=(yield t.getOrCreateSourceRooms()).map(i=>i.roomId);return n.includes(e)?!1:(n.push(e),yield t.withIgnoreInvitesPolicies(i=>{i.sources=n}),!0)})()}getRuleForInvite(e){var t=this;return _(function*(){var{sender:n,roomId:i}=e,o=yield t.getOrCreateSourceRooms(),s=n.split(":")[1],a=i.split(":")[1];for(var l of o){var c=l.getUnfilteredTimelineSet().getLiveTimeline().getState(Ee.FORWARDS);for(var{scope:u,entities:d}of[{scope:Zl.Room,entities:[i]},{scope:Zl.User,entities:[n]},{scope:Zl.Server,entities:[s,a]}]){var f=c.getStateEvents(Rk[u]);for(var p of f){var h=p.getContent();if((h==null?void 0:h.recommendation)==Tk.Ban){var m=h==null?void 0:h.entity;if(m){var w=void 0;try{w=new RegExp(Y1(m))}catch{continue}for(var g of d)if(g&&w.test(g))return p}}}}}return null})()}getOrCreateTargetRoom(){var e=this;return _(function*(){var t=e.getIgnoreInvitesPolicies(),n=t.target;if(typeof n!="string"&&(n=null),n){var i=e.client.getRoom(n);if(i)return i;n=null}return n=(yield e.client.createRoom({name:"Individual Policy Room",preset:Mw.PrivateChat})).room_id,yield e.withIgnoreInvitesPolicies(o=>{o.target=n}),e.client.getRoom(n)})()}getOrCreateSourceRooms(){var e=this;return _(function*(){var t=e.getIgnoreInvitesPolicies(),n=t.sources,i=!1;Array.isArray(n)||(i=!0,n=[]);var o=n.filter(a=>typeof a=="string").map(a=>e.client.getRoom(a)).filter(a=>!!a);if(o.length!=n.length&&(i=!0),o.length==0){var s=yield e.getOrCreateTargetRoom();i=!0,o=[s]}return i&&(yield e.withIgnoreInvitesPolicies(a=>{a.sources=n})),o})()}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}withIgnoreInvitesPolicies(e){var t=this;return _(function*(){var{policies:n,ignoreInvitesPolicies:i}=t.getPoliciesAndIgnoreInvitesPolicies();e(i),n[mh.name]=i,yield t.client.setAccountData(ry.name,n)})()}getPoliciesAndIgnoreInvitesPolicies(){var e={};for(var t of[ry.name,ry.altName]){var n;if(t){var i=(n=this.client.getAccountData(t))===null||n===void 0?void 0:n.getContent();if(i){e=i;break}}}var o={},s=!1;for(var a of[mh.name,mh.altName])if(a){var l=e[a];if(l&&typeof l=="object"){o=l,s=!0;break}}return s||(e[mh.name]=o),{policies:e,ignoreInvitesPolicies:o}}}var ny="matrix-js-sdk",Jh=function(r){return r.Cancel="cancel",r.Restart="restart",r.Send="send",r}({}),EN=r=>r.type==="livekit"&&"focus_selection"in r,F9=(r,e)=>{var t,n="Malformed session membership event: ";return typeof r.device_id!="string"&&e.push(n+"device_id must be string"),typeof r.call_id!="string"&&e.push(n+"call_id must be string"),typeof r.application!="string"&&e.push(n+"application must be a string"),typeof((t=r.focus_active)===null||t===void 0?void 0:t.type)!="string"&&e.push(n+"focus_active.type must be a string"),Array.isArray(r.foci_preferred)||e.push(n+"foci_preferred must be an array"),r.created_ts&&typeof r.created_ts!="number"&&e.push(n+"created_ts must be number"),r.scope&&typeof r.scope!="string"&&e.push(n+"scope must be string"),e.length===0},ns=r=>"membershipID"in r,B9=(r,e)=>{var t="Malformed legacy rtc membership event: ";return"expires"in r||"expires_ts"in r||e.push(t+"expires_ts or expires must be present"),"expires"in r&&typeof r.expires!="number"&&e.push(t+"expires must be numeric"),"expires_ts"in r&&typeof r.expires_ts!="number"&&e.push(t+"expires_ts must be numeric"),typeof r.device_id!="string"&&e.push(t+"device_id must be string"),typeof r.call_id!="string"&&e.push(t+"call_id must be string"),typeof r.application!="string"&&e.push(t+"application must be a string"),typeof r.membershipID!="string"&&e.push(t+"membershipID must be a string"),r.created_ts&&typeof r.created_ts!="number"&&e.push(t+"created_ts must be number"),r.scope&&typeof r.scope!="string"&&e.push(t+"scope must be string"),e.length===0};class mu{static equal(e,t){return Fa(e.membershipData,t.membershipData)}constructor(e,t){this.parentEvent=e,v(this,"membershipData",void 0);var n=[],i=[];if(!F9(t,n)&&!B9(t,i))throw Error("unknown CallMembership data. Does not match legacy call.member (".concat(i.join(" & "),") events nor MSC4143 (").concat(n.join(" & "),")"));this.membershipData=t}get sender(){return this.parentEvent.getSender()}get eventId(){return this.parentEvent.getId()}get callId(){return this.membershipData.call_id}get deviceId(){return this.membershipData.device_id}get application(){return this.membershipData.application}get scope(){return this.membershipData.scope}get membershipID(){return ns(this.membershipData)?this.membershipData.membershipID:this.createdTs().toString()}createdTs(){var e;return(e=this.membershipData.created_ts)!==null&&e!==void 0?e:this.parentEvent.getTs()}getAbsoluteExpiry(){if(ns(this.membershipData))return"expires"in this.membershipData?this.createdTs()+this.membershipData.expires:this.membershipData.expires_ts}getLocalExpiry(){if(ns(this.membershipData))if("expires"in this.membershipData){var e=this.parentEvent.getTs()-this.createdTs(),t=this.parentEvent.localTimestamp-e;return t+this.membershipData.expires}else return this.membershipData.expires_ts}getMsUntilExpiry(){if(ns(this.membershipData))return this.getAbsoluteExpiry()-Date.now()}isExpired(){return ns(this.membershipData)?this.getMsUntilExpiry()<=0:!1}getPreferredFoci(){var e;return ns(this.membershipData)?(e=this.membershipData.foci_active)!==null&&e!==void 0?e:[]:this.membershipData.foci_preferred}getFocusSelection(){if(ns(this.membershipData))return"oldest_membership";var e=this.membershipData.focus_active;if(EN(e))return e.focus_selection}}function Ck(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function K9(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ck(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Ck(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Ve=S.getChild("MatrixRTCSession"),Xh=(r,e)=>"".concat(r,":").concat(e),iy=r=>Xh(r.sender,r.deviceId);function V9(r,e){return r===e?!0:!!r&&!!e&&r.length===e.length&&r.every((t,n)=>t===e[n])}var cl=function(r){return r.MembershipsChanged="memberships_changed",r.JoinStateChanged="join_state_changed",r.EncryptionKeyChanged="encryption_key_changed",r}({});class ec extends Tt{get membershipExpiryTimeout(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeout)!==null&&e!==void 0?e:60*60*1e3}get memberEventCheckPeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.memberEventCheckPeriod)!==null&&e!==void 0?e:2*60*1e3}get callMemberEventRetryDelayMinimum(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryDelayMinimum)!==null&&e!==void 0?e:3e3}get updateEncryptionKeyThrottle(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.updateEncryptionKeyThrottle)!==null&&e!==void 0?e:3e3}get makeKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.makeKeyDelay)!==null&&e!==void 0?e:3e3}get useKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.useKeyDelay)!==null&&e!==void 0?e:5e3}get membershipServerSideExpiryTimeout(){var e,t,n;return(e=(t=this.membershipServerSideExpiryTimeoutOverride)!==null&&t!==void 0?t:(n=this.joinConfig)===null||n===void 0?void 0:n.membershipServerSideExpiryTimeout)!==null&&e!==void 0?e:8e3}get membershipKeepAlivePeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipKeepAlivePeriod)!==null&&e!==void 0?e:5e3}get callMemberEventRetryJitter(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryJitter)!==null&&e!==void 0?e:2e3}get callId(){return this._callId}static callMembershipsForRoom(e){var t=e.getLiveTimeline().getState(Ee.FORWARDS);if(!t)throw Ve.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);var n=t.getStateEvents(V.GroupCallMemberPrefix),i=[];for(var o of n){var s=o.getContent(),a=Object.keys(s).length;if(a!==0){var l=[];if(a>1&&"focus_active"in s)l.push(s);else if(a===1&&"memberships"in s){if(!Array.isArray(s.memberships)){Ve.warn("Malformed member event from ".concat(o.getSender(),": memberships is not an array"));continue}l=s.memberships}if(l.length!==0)for(var c of l)try{var u,d=new mu(o,c);if(d.callId!==""||d.scope!=="m.room"){Ve.info("Ignoring user-scoped call");continue}if(d.isExpired()){Ve.info("Ignoring expired device membership ".concat(d.sender,"/").concat(d.deviceId));continue}if(!e.hasMembershipState((u=d.sender)!==null&&u!==void 0?u:"",Be.Join)){Ve.info("Ignoring membership of user ".concat(d.sender," who is not in the room."));continue}i.push(d)}catch(f){Ve.warn("Couldn't construct call membership: ",f)}}}return i.sort((f,p)=>f.createdTs()-p.createdTs()),i.length>1&&Ve.debug("Call memberships in room ".concat(e.roomId,", in order: "),i.map(f=>[f.createdTs(),f.sender])),i}static roomSessionForRoom(e,t){var n=ec.callMembershipsForRoom(t);return new ec(e,t,n)}constructor(e,t,n){var i,o;super(),i=this,this.client=e,this.room=t,this.memberships=n,v(this,"_callId",void 0),v(this,"relativeExpiry",void 0),v(this,"joinConfig",void 0),v(this,"membershipServerSideExpiryTimeoutOverride",void 0),v(this,"membershipId",void 0),v(this,"memberEventTimeout",void 0),v(this,"expiryTimeout",void 0),v(this,"keysEventUpdateTimeout",void 0),v(this,"makeNewKeyTimeout",void 0),v(this,"setNewKeyTimeouts",new Set),v(this,"ownFocusActive",void 0),v(this,"ownFociPreferred",void 0),v(this,"updateCallMembershipRunning",!1),v(this,"needCallMembershipUpdate",!1),v(this,"manageMediaKeys",!1),v(this,"useLegacyMemberEvents",!0),v(this,"encryptionKeys",new Map),v(this,"lastEncryptionKeyUpdateRequest",void 0),v(this,"disconnectDelayId",void 0),v(this,"lastMembershipFingerprints",void 0),v(this,"currentEncryptionKeyIndex",-1),v(this,"statistics",{counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}}),v(this,"sendEncryptionKeysEvent",function(){var a=_(function*(l){if(i.keysEventUpdateTimeout!==void 0&&(clearTimeout(i.keysEventUpdateTimeout),i.keysEventUpdateTimeout=void 0),i.lastEncryptionKeyUpdateRequest=Date.now(),!!i.isJoined()){Ve.info("Sending encryption keys event. indexToSend=".concat(l));var c=i.client.getUserId(),u=i.client.getDeviceId();if(!c)throw new Error("No userId");if(!u)throw new Error("No deviceId");var d=i.getKeysForParticipant(c,u);if(!d){Ve.warn("Tried to send encryption keys event but no keys found!");return}if(typeof l!="number"&&i.currentEncryptionKeyIndex===-1){Ve.warn("Tried to send encryption keys event but no current key index found!");return}var f=l??i.currentEncryptionKeyIndex,p=d[f];try{var h={keys:[{index:f,key:vm(p)}],device_id:u,call_id:"",sent_ts:Date.now()};i.statistics.counters.roomEventEncryptionKeysSent+=1,yield i.client.sendEvent(i.room.roomId,V.CallEncryptionKeysPrefix,h),Ve.debug("Embedded-E2EE-LOG updateEncryptionKeyEvent participantId=".concat(c,":").concat(u," numKeys=").concat(d.length," currentKeyIndex=").concat(i.currentEncryptionKeyIndex," keyIndexToSend=").concat(f),i.encryptionKeys)}catch(g){var m=g;if(m.event&&i.client.cancelPendingEvent(m.event),i.keysEventUpdateTimeout===void 0){var w=mw(m,5e3);Ve.warn("Failed to send m.call.encryption_key, retrying in ".concat(w),g),i.keysEventUpdateTimeout=setTimeout(i.sendEncryptionKeysEvent,w)}else Ve.info("Not scheduling key resend as another re-send is already pending")}}});return function(l){return a.apply(this,arguments)}}()),v(this,"onCallEncryption",a=>{var l=a.getSender(),c=a.getContent(),u=c.device_id,d=c.call_id;if(!l){Ve.warn("Received m.call.encryption_keys with no userId: callId=".concat(d));return}if(d!==""){Ve.warn("Received m.call.encryption_keys with unsupported callId: userId=".concat(l,", deviceId=").concat(u,", callId=").concat(d));return}if(!Array.isArray(c.keys)){Ve.warn("Received m.call.encryption_keys where keys wasn't an array: callId=".concat(d));return}if(l===this.client.getUserId()&&u===this.client.getDeviceId()){Ve.info("Ignoring our own keys event");return}this.statistics.counters.roomEventEncryptionKeysReceived+=1;var f=Date.now()-(typeof c.sent_ts=="number"?c.sent_ts:a.getTs());this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=f;for(var p of c.keys){if(!p){Ve.info("Ignoring false-y key in keys event");continue}var h=p.key,m=p.index;!h||m===void 0||m===null||d===void 0||d===null||typeof u!="string"||typeof d!="string"||typeof h!="string"||typeof m!="number"?Ve.warn("Malformed call encryption_key: userId=".concat(l,", deviceId=").concat(u,", encryptionKeyIndex=").concat(m," callId=").concat(d)):(Ve.debug("Embedded-E2EE-LOG onCallEncryption userId=".concat(l,":").concat(u," encryptionKeyIndex=").concat(m," age=").concat(f,"ms"),this.encryptionKeys),this.setEncryptionKey(l,u,m,h,a.getTs()))}}),v(this,"isMyMembership",a=>a.sender===this.client.getUserId()&&a.deviceId===this.client.getDeviceId()),v(this,"onMembershipUpdate",()=>{var a,l,c=this.memberships;this.memberships=ec.callMembershipsForRoom(this.room),this._callId=(a=this._callId)!==null&&a!==void 0?a:(l=this.memberships[0])===null||l===void 0?void 0:l.callId;var u=c.length!=this.memberships.length||c.some((b,R)=>!mu.equal(b,this.memberships[R]));if(u&&(Ve.info("Memberships for call in room ".concat(this.room.roomId," have changed: emitting")),this.emit(cl.MembershipsChanged,c,this.memberships),this.isJoined()&&!this.memberships.some(this.isMyMembership)&&(Ve.warn("Missing own membership: force re-join"),this.triggerCallMembershipEventUpdate())),this.manageMediaKeys&&this.isJoined()&&this.makeNewKeyTimeout===void 0){var d=new Set(c.filter(b=>!this.isMyMembership(b)).map(iy)),f=new Set(this.memberships.filter(b=>!this.isMyMembership(b)).map(iy)),p=Array.from(d).some(b=>!f.has(b)),h=Array.from(f).some(b=>!d.has(b)),m=this.lastMembershipFingerprints;if(this.storeLastMembershipFingerprints(),p)Ve.debug("Member(s) have left: queueing sender key rotation"),this.makeNewKeyTimeout=setTimeout(this.onRotateKeyTimeout,this.makeKeyDelay);else if(h)Ve.debug("New member(s) have joined: re-sending keys"),this.requestSendCurrentKey();else if(m){var w=this.lastMembershipFingerprints,g=Array.from(m).some(b=>!w.has(b))||Array.from(w).some(b=>!m.has(b));g&&(Ve.debug("Member(s) have updated/reconnected: re-sending keys to everyone"),this.requestSendCurrentKey())}}this.setExpiryTimer()}),v(this,"triggerCallMembershipEventUpdate",_(function*(){if(i.updateCallMembershipRunning){i.needCallMembershipUpdate=!0;return}i.updateCallMembershipRunning=!0;try{do i.needCallMembershipUpdate=!1,yield i.updateCallMembershipEvent();while(i.needCallMembershipUpdate)}finally{i.updateCallMembershipRunning=!1}})),v(this,"delayDisconnection",_(function*(){try{var a=i.disconnectDelayId;yield ul(()=>i.client._unstable_updateDelayedEvent(a,Jh.Restart)),i.scheduleDelayDisconnection()}catch(l){Ve.error("Failed to delay our disconnection event:",l)}})),v(this,"onRotateKeyTimeout",()=>{if(this.manageMediaKeys){this.makeNewKeyTimeout=void 0,Ve.info("Making new sender key for key rotation");var a=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(a)}}),this._callId=(o=n[0])===null||o===void 0?void 0:o.callId;var s=this.room.getLiveTimeline().getState(Ee.FORWARDS);s==null||s.on(Ne.Members,this.onMembershipUpdate),this.setExpiryTimer()}isJoined(){return this.relativeExpiry!==void 0}stop(){var e=this;return _(function*(){yield e.leaveRoomSession(1e3),e.expiryTimeout&&(clearTimeout(e.expiryTimeout),e.expiryTimeout=void 0),e.memberEventTimeout&&(clearTimeout(e.memberEventTimeout),e.memberEventTimeout=void 0);var t=e.room.getLiveTimeline().getState(Ee.FORWARDS);t==null||t.off(Ne.Members,e.onMembershipUpdate)})()}joinRoomSession(e,t,n){var i,o;if(this.isJoined()){Ve.info("Already joined to session in room ".concat(this.room.roomId,": ignoring join call"));return}this.ownFocusActive=t,this.ownFociPreferred=e,this.joinConfig=n,this.relativeExpiry=this.membershipExpiryTimeout,this.manageMediaKeys=(i=n==null?void 0:n.manageMediaKeys)!==null&&i!==void 0?i:this.manageMediaKeys,this.useLegacyMemberEvents=(o=n==null?void 0:n.useLegacyMemberEvents)!==null&&o!==void 0?o:this.useLegacyMemberEvents,this.membershipId=Ei(5),Ve.info("Joining call session in room ".concat(this.room.roomId," with manageMediaKeys=").concat(this.manageMediaKeys)),n!=null&&n.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey()),this.triggerCallMembershipEventUpdate(),this.emit(cl.JoinStateChanged,!0)}leaveRoomSession(){var e=arguments,t=this;return _(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:void 0;if(!t.isJoined())return Ve.info("Not joined to session in room ".concat(t.room.roomId,": ignoring leave call")),!1;var i=t.client.getUserId(),o=t.client.getDeviceId();if(!i)throw new Error("No userId");if(!o)throw new Error("No deviceId");t.encryptionKeys.set(Xh(i,o),[]),t.makeNewKeyTimeout!==void 0&&(clearTimeout(t.makeNewKeyTimeout),t.makeNewKeyTimeout=void 0);for(var s of t.setNewKeyTimeouts)clearTimeout(s);if(t.setNewKeyTimeouts.clear(),Ve.info("Leaving call session in room ".concat(t.room.roomId)),t.joinConfig=void 0,t.relativeExpiry=void 0,t.ownFocusActive=void 0,t.manageMediaKeys=!1,t.membershipId=void 0,t.emit(cl.JoinStateChanged,!1),n){var a=yield Promise.race([t.triggerCallMembershipEventUpdate(),As(n,"timeout")]);return a!=="timeout"}else return yield t.triggerCallMembershipEventUpdate(),!0})()}getActiveFocus(){if(this.ownFocusActive&&EN(this.ownFocusActive)&&this.ownFocusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}if(!this.ownFocusActive){var t=this.getOldestMembership();return t==null?void 0:t.getPreferredFoci()[0]}}reemitEncryptionKeys(){this.encryptionKeys.forEach((e,t)=>{e.forEach((n,i)=>{this.emit(cl.EncryptionKeyChanged,n.key,i,t)})})}getKeysForParticipant(e,t){return this.getKeysForParticipantInternal(e,t)}getKeysForParticipantInternal(e,t){var n;return(n=this.encryptionKeys.get(Xh(e,t)))===null||n===void 0?void 0:n.map(i=>i.key)}getEncryptionKeys(){return Array.from(this.encryptionKeys.entries()).map(e=>{var[t,n]=e;return[t,n.map(i=>i.key)]}).values()}getNewEncryptionKeyIndex(){return this.currentEncryptionKeyIndex===-1?0:(this.currentEncryptionKeyIndex+1)%256}setEncryptionKey(e,t,n,i,o){var s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1,a=Dr(i),l=Xh(e,t);this.encryptionKeys.has(l)||this.encryptionKeys.set(l,[]);var c=this.encryptionKeys.get(l),u=c[n];if(u){if(u.timestamp>o){Ve.info("Ignoring new key at index ".concat(n," for ").concat(l," as it is older than existing known key"));return}if(V9(u.key,a)){u.timestamp=o;return}}if(c[n]={key:a,timestamp:o},s){var d=setTimeout(()=>{this.setNewKeyTimeouts.delete(d),Ve.info("Delayed-emitting key changed event for ".concat(l," idx ").concat(n)),e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=n),this.emit(cl.EncryptionKeyChanged,a,n,l)},this.useKeyDelay);this.setNewKeyTimeouts.add(d)}else e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=n),this.emit(cl.EncryptionKeyChanged,a,n,l)}makeNewSenderKey(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.client.getUserId(),n=this.client.getDeviceId();if(!t)throw new Error("No userId");if(!n)throw new Error("No deviceId");var i=dz(16),o=this.getNewEncryptionKeyIndex();return Ve.info("Generated new key at index "+o),this.setEncryptionKey(t,n,o,i,Date.now(),e),o}requestSendCurrentKey(){if(this.manageMediaKeys){if(this.lastEncryptionKeyUpdateRequest&&this.lastEncryptionKeyUpdateRequest+this.updateEncryptionKeyThrottle>Date.now()){Ve.info("Last encryption key event sent too recently: postponing"),this.keysEventUpdateTimeout===void 0&&(this.keysEventUpdateTimeout=setTimeout(this.sendEncryptionKeysEvent,this.updateEncryptionKeyThrottle));return}this.sendEncryptionKeysEvent()}}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);var e;for(var t of this.memberships){var n=t.getMsUntilExpiry();n!==void 0&&(e===void 0||n<e)&&(e=n)}e!=null&&(this.expiryTimeout=setTimeout(this.onMembershipUpdate,e))}getOldestMembership(){return this.memberships[0]}getFocusInUse(){var e=this.getOldestMembership();if((e==null?void 0:e.getFocusSelection())==="oldest_membership")return e.getPreferredFoci()[0]}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.memberships.filter(e=>!this.isMyMembership(e)).map(e=>"".concat(iy(e),":").concat(e.membershipID,":").concat(e.createdTs())))}makeMyMembershipLegacy(e,t){if(this.relativeExpiry===void 0)throw new Error("Tried to create our own membership event when we're not joined!");if(this.membershipId===void 0)throw new Error("Tried to create our own membership event when we have no membership ID!");var n=t==null?void 0:t.createdTs();return K9({call_id:"",scope:"m.room",application:"m.call",device_id:e,expires:this.relativeExpiry,expires_ts:this.relativeExpiry+(n??Date.now()),foci_active:this.ownFociPreferred,membershipID:this.membershipId},n?{created_ts:n}:{})}makeMyMembership(e){var t;return{call_id:"",scope:"m.room",application:"m.call",device_id:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(t=this.ownFociPreferred)!==null&&t!==void 0?t:[]}}membershipEventNeedsUpdate(e,t){if(t&&t.getMsUntilExpiry()===void 0)return!1;if(!this.isJoined())return!!e;if(!t)return!0;var n=t.getMsUntilExpiry();return n!==void 0&&n<this.membershipExpiryTimeout/2?(this.relativeExpiry+=this.membershipExpiryTimeout,!0):!1}makeNewMembership(e){return this.isJoined()?this.makeMyMembership(e):{}}makeNewLegacyMemberships(e,t,n,i){var o=l=>{var c;try{c=new mu(n,l)}catch{return!1}return!c.isExpired()},s=l=>(l.created_ts===void 0&&(l.created_ts=n.getTs()),l),a=e.filter(o).filter(l=>l.device_id!==t);return a=a.map(s),this.isJoined()&&a.push(this.makeMyMembershipLegacy(t,i)),{memberships:a}}updateCallMembershipEvent(){var e=this;return _(function*(){e.memberEventTimeout&&(clearTimeout(e.memberEventTimeout),e.memberEventTimeout=void 0);var t=e.room.getLiveTimeline().getState(Ee.FORWARDS);if(!t)throw new Error("Couldn't get room state for room "+e.room.roomId);var n=e.client.getUserId(),i=e.client.getDeviceId();if(!n||!i)throw new Error("User ID or device ID was null!");var o=t.events.get(V.GroupCallMemberPrefix),s=e.stateEventsContainOngoingLegacySession(o),a={};if(s){var l,c=o==null?void 0:o.get(n),u=(l=c==null?void 0:c.getContent())!==null&&l!==void 0?l:{},d,f=Array.isArray(u.memberships)?u.memberships:[],p=f.find(k=>k.device_id===i);try{c&&p&&ns(p)&&p.membershipID===e.membershipId&&(d=new mu(c,p))}catch(k){Ve.warn("Our previous call membership was invalid - this shouldn't happen.",k)}if(d&&Ve.debug("".concat(d.getMsUntilExpiry()," until our membership expires")),!e.membershipEventNeedsUpdate(p,d)){e.memberEventTimeout=setTimeout(e.triggerCallMembershipEventUpdate,e.memberEventCheckPeriod);return}a=e.makeNewLegacyMemberships(f,i,c,d)}else a=e.makeNewMembership(i);try{if(s)yield e.client.sendStateEvent(e.room.roomId,V.GroupCallMemberPrefix,a,n),e.isJoined()&&(e.memberEventTimeout=setTimeout(e.triggerCallMembershipEventUpdate,e.memberEventCheckPeriod));else if(e.isJoined()){var h=e.makeMembershipStateKey(n,i),m=function(){var k=_(function*(){try{var O=yield ul(()=>e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.membershipServerSideExpiryTimeout},V.GroupCallMemberPrefix,{},h));e.disconnectDelayId=O.delay_id}catch(x){if(x instanceof hr&&x.errcode==="M_UNKNOWN"&&x.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var T=x.data["org.matrix.msc4140.max_delay"];if(typeof T=="number"&&e.membershipServerSideExpiryTimeout>T)return e.membershipServerSideExpiryTimeoutOverride=T,m()}Ve.error("Failed to prepare delayed disconnection event:",x)}});return function(){return k.apply(this,arguments)}}();if(yield m(),yield ul(()=>e.client.sendStateEvent(e.room.roomId,V.GroupCallMemberPrefix,a,h)),e.disconnectDelayId!==void 0)try{var w=e.disconnectDelayId;yield ul(()=>e.client._unstable_updateDelayedEvent(w,Jh.Restart))}catch(k){Ve.warn("Failed to update delayed disconnection event, prepare it again:",k),e.disconnectDelayId=void 0,yield m()}e.disconnectDelayId!==void 0&&e.scheduleDelayDisconnection()}else{var g=!1;if(e.disconnectDelayId!==void 0){try{var b=e.disconnectDelayId;yield ul(()=>e.client._unstable_updateDelayedEvent(b,Jh.Send)),g=!0}catch(k){Ve.error("Failed to send our delayed disconnection event:",k)}e.disconnectDelayId=void 0}g||(yield ul(()=>e.client.sendStateEvent(e.room.roomId,V.GroupCallMemberPrefix,{},e.makeMembershipStateKey(n,i))))}Ve.info("Sent updated call member event.")}catch(k){var R=e.callMemberEventRetryDelayMinimum+Math.random()*e.callMemberEventRetryJitter;Ve.warn("Failed to send call member event (retrying in ".concat(R,"): ").concat(k)),yield As(R),yield e.triggerCallMembershipEventUpdate()}})()}scheduleDelayDisconnection(){this.memberEventTimeout=setTimeout(this.delayDisconnection,this.membershipKeepAlivePeriod)}stateEventsContainOngoingLegacySession(e){if(!(e!=null&&e.size))return this.useLegacyMemberEvents;var t=!1,n=!1;for(var i of e.values()){var o=i.getContent();if(Array.isArray(o.memberships)){for(var s of o.memberships)if(!new mu(i,s).isExpired())return!0}else Object.keys(o).length>0&&(t||(t=!0),n||(n=!("focus_active"in o)))}return t&&!n?!1:this.useLegacyMemberEvents}makeMembershipStateKey(e,t){var n="".concat(e,"_").concat(t);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?n:"_".concat(n)}}function ul(r){return r_.apply(this,arguments)}function r_(){return r_=_(function*(r){for(var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;;)try{return yield r()}catch(o){if(e>0&&o instanceof yc&&o.isRateLimitError()){e--;var t=void 0,n=5e3;try{var i;t=(i=o.getRetryAfterMs())!==null&&i!==void 0?i:n,Ve.info("Rate limited by server, retrying in ".concat(t,"ms"))}catch(s){Ve.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(n),s),t=n}yield As(t)}else throw o}}),r_.apply(this,arguments)}var gu=S.getChild("MatrixRTCSessionManager"),kk=function(r){return r.SessionStarted="session_started",r.SessionEnded="session_ended",r}({});class $9 extends Tt{constructor(e){super(),this.client=e,v(this,"roomSessions",new Map),v(this,"onTimeline",t=>{this.consumeCallEncryptionEvent(t)}),v(this,"onRoom",t=>{this.refreshRoom(t)}),v(this,"onRoomState",(t,n)=>{var i=this.client.getRoom(t.getRoomId());if(!i){gu.error("Got room state event for unknown room ".concat(t.getRoomId(),"!"));return}t.getType()==V.GroupCallMemberPrefix&&this.refreshRoom(i)})}start(){for(var e of(t=this.client.getRooms())!==null&&t!==void 0?t:[]){var t,n=ec.roomSessionForRoom(this.client,e);n.memberships.length>0&&this.roomSessions.set(e.roomId,n)}this.client.on(Te.Room,this.onRoom),this.client.on(fe.Timeline,this.onTimeline),this.client.on(Ne.Events,this.onRoomState)}stop(){for(var e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(Te.Room,this.onRoom),this.client.off(fe.Timeline,this.onTimeline),this.client.off(Ne.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,ec.roomSessionForRoom(this.client,e)),this.roomSessions.get(e.roomId)}consumeCallEncryptionEvent(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;if(yield n.client.decryptEventIfNeeded(e),e.isDecryptionFailure()){i?gu.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason)):(gu.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason," will retry once only")),setTimeout(()=>n.consumeCallEncryptionEvent(e,!0),1e3));return}else i&&gu.info("Decryption succeeded for event ".concat(e.getId()," after retry"));if(e.getType()!==V.CallEncryptionKeysPrefix)return Promise.resolve();var o=n.client.getRoom(e.getRoomId());if(!o)return gu.error("Got room state event for unknown room ".concat(e.getRoomId(),"!")),Promise.resolve();n.getRoomSession(o).onCallEncryption(e)})()}refreshRoom(e){var t=!this.roomSessions.has(e.roomId),n=this.getRoomSession(e),i=n.memberships.length>0&&!t;n.onMembershipUpdate();var o=n.memberships.length>0;i&&!o?this.emit(kk.SessionEnded,e.roomId,this.roomSessions.get(e.roomId)):!i&&o&&this.emit(kk.SessionStarted,e.roomId,this.roomSessions.get(e.roomId))}}function oy(r){return e=>{var t,n;return((t=e.content)===null||t===void 0||(t=t["m.relates_to"])===null||t===void 0?void 0:t.event_id)!==r||((n=e.content)===null||n===void 0||(n=n["m.relates_to"])===null||n===void 0?void 0:n.rel_type)===vt.name}}function wN(r){return n_.apply(this,arguments)}function n_(){return n_=_(function*(r){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");var e=new TextEncoder().encode(r),t=yield globalThis.crypto.subtle.digest("SHA-256",e);return t}),n_.apply(this,arguments)}var W9=["server","limit","since"];function Ik(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Cr(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ik(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Ik(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var q9=3e3,G9=gN(),xk=10*60*1e3,H9=new Ft("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent"),wc=function(r){return r.Chronological="chronological",r.Detached="detached",r}({}),z9=new nm("m.get_login_token","org.matrix.msc3882.get_login_token"),TN="uk.half-shot.msc2666",RN="uk.half-shot.msc2666.mutual_rooms",CN="uk.half-shot.msc2666.query_mutual_rooms",$i="org.matrix.msc4140",kN="uk.tcpip.msc4133",Di="$",Te=function(r){return r.Sync="sync",r.Event="event",r.ToDeviceEvent="toDeviceEvent",r.AccountData="accountData",r.Room="Room",r.DeleteRoom="deleteRoom",r.SyncUnexpectedError="sync.unexpectedError",r.ClientWellKnown="WellKnown.client",r.ReceivedVoipEvent="received_voip_event",r.UndecryptableToDeviceEvent="toDeviceEvent.undecryptable",r.TurnServers="turnServers",r.TurnServersError="turnServers.error",r}({}),Y9=new Ft("action","org.matrix.msc3824.action");class $c extends Tt{constructor(e){var t,n,i,o;super(),i=this,v(this,"logger",void 0),v(this,"reEmitter",new Bc(this)),v(this,"olmVersion",null),v(this,"usingExternalCrypto",!1),v(this,"_store",void 0),v(this,"deviceId",void 0),v(this,"credentials",void 0),v(this,"pickleKey",void 0),v(this,"scheduler",void 0),v(this,"clientRunning",!1),v(this,"timelineSupport",!1),v(this,"urlPreviewCache",{}),v(this,"identityServer",void 0),v(this,"http",void 0),v(this,"crypto",void 0),v(this,"cryptoBackend",void 0),v(this,"cryptoCallbacks",void 0),v(this,"callEventHandler",void 0),v(this,"groupCallEventHandler",void 0),v(this,"supportsCallTransfer",!1),v(this,"forceTURN",!1),v(this,"iceCandidatePoolSize",0),v(this,"idBaseUrl",void 0),v(this,"baseUrl",void 0),v(this,"isVoipWithNoMediaAllowed",void 0),v(this,"useLivekitForGroupCalls",void 0),v(this,"canSupportVoip",!1),v(this,"peekSync",null),v(this,"isGuestAccount",!1),v(this,"ongoingScrollbacks",{}),v(this,"notifTimelineSet",null),v(this,"cryptoStore",void 0),v(this,"verificationMethods",void 0),v(this,"fallbackICEServerAllowed",!1),v(this,"syncApi",void 0),v(this,"roomNameGenerator",void 0),v(this,"pushRules",void 0),v(this,"syncLeftRoomsPromise",void 0),v(this,"syncedLeftRooms",!1),v(this,"clientOpts",void 0),v(this,"clientWellKnownIntervalID",void 0),v(this,"canResetTimelineCallback",void 0),v(this,"canSupport",new Map),v(this,"pushProcessor",new hi(this)),v(this,"serverVersionsPromise",void 0),v(this,"clientWellKnown",void 0),v(this,"clientWellKnownPromise",void 0),v(this,"turnServers",[]),v(this,"turnServersExpiry",0),v(this,"checkTurnServersIntervalID",void 0),v(this,"exportedOlmDeviceToImport",void 0),v(this,"txnCtr",0),v(this,"mediaHandler",new x9(this)),v(this,"sessionId",void 0),v(this,"eventsBeingEncrypted",new Set),v(this,"useE2eForGroupCall",!0),v(this,"toDeviceMessageQueue",void 0),v(this,"livekitServiceURL",void 0),v(this,"_secretStorage",void 0),v(this,"ignoredInvites",void 0),v(this,"matrixRTC",void 0),v(this,"serverCapabilitiesService",void 0),v(this,"startCallEventHandler",()=>{this.isInitialSyncComplete()&&(Mb()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off(Te.Sync,this.startCallEventHandler))}),v(this,"startMatrixRTC",()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off(Te.Sync,this.startMatrixRTC))}),v(this,"fixupRoomNotifications",()=>{if(this.isInitialSyncComplete()){var a,l=((a=this.getRooms())!==null&&a!==void 0?a:[]).filter(d=>d.getUnreadNotificationCount(it.Total)>0);for(var c of l){var u=this.getSafeUserId();c.fixupNotifications(u)}this.off(Te.Sync,this.fixupRoomNotifications)}}),this.logger=(t=e.logger)!==null&&t!==void 0?t:S,e.baseUrl=Wg(e.baseUrl),e.idBaseUrl=Wg(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=(n=e.usingExternalCrypto)!==null&&n!==void 0?n:!1,this.store=e.store||new JH,this.deviceId=e.deviceId||null,this.sessionId=Ei(10);var s=e.userId||null;this.credentials={userId:s},this.http=new UD(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:Ot.V3,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader,logger:this.logger}),e.deviceToImport?this.deviceId?this.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?this.logger.warn("not importing device because user ID is provided to constructor independently of exported data"):e.deviceToImport.deviceId?(this.deviceId=e.deviceToImport.deviceId,this.credentials.userId=e.deviceToImport.userId,this.exportedOlmDeviceToImport=e.deviceToImport.olmDevice):this.logger.warn("not importing device because no device ID in exported data"):e.pickleKey&&(this.pickleKey=e.pickleKey),this.useLivekitForGroupCalls=!!e.useLivekitForGroupCalls,this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(function(){var a=_(function*(l){var c=i.getRoom(l.getRoomId());l.status!==je.SENDING&&i.updatePendingEventStatus(c,l,je.SENDING);var u=yield i.sendEventHttpRequest(l);return c&&c.updatePendingEvent(l,je.SENT,u.event_id),u});return function(l){return a.apply(this,arguments)}}()),Mb()&&(this.callEventHandler=new yz(this),this.groupCallEventHandler=new Sz(this),this.canSupportVoip=!0,this.on(Te.Sync,this.startCallEventHandler)),this.matrixRTC=new $9(this),this.serverCapabilitiesService=new FD(this.http),this.on(Te.Sync,this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.cryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=e.iceCandidatePoolSize===void 0?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,e.useE2eForGroupCall!==void 0&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.livekitServiceURL=e.livekitServiceURL,this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new U9(this),this.on(ot.Decrypted,a=>{IN(this,a)}),this.ignoredInvites=new j9(this),this._secretStorage=new Kd(this,(o=e.cryptoCallbacks)!==null&&o!==void 0?o:{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(t=>Co.createUser(t,this))}get store(){return this._store}startClient(e){var t=this;return _(function*(){if(!t.clientRunning){t.clientRunning=!0,t.on(Te.Sync,t.startMatrixRTC);var n=t.getUserId();n&&t.store.storeUser(new Co(n)),t.canSupportVoip&&(t.checkTurnServersIntervalID=setInterval(()=>{t.checkTurnServers()},xk),t.checkTurnServers()),t.syncApi&&(t.logger.error("Still have sync object whilst not running: stopping old one"),t.syncApi.stop());try{yield t.getVersions();var{threads:i,list:o,fwdPagination:s}=yield t.doesServerSupportThread();Et.setServerSideSupport(i),Et.setServerSideListSupport(o),Et.setServerSideFwdPaginationSupport(s)}catch(a){t.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",a)}t.clientOpts=e??{},t.clientOpts.slidingSync?t.syncApi=new bN(t.clientOpts.slidingSync,t,t.clientOpts,t.buildSyncApiOptions()):t.syncApi=new Mu(t,t.clientOpts,t.buildSyncApiOptions()),t.syncApi.sync().catch(a=>t.logger.info("Sync startup aborted with an error:",a)),t.clientOpts.clientWellKnownPollPeriod!==void 0&&(t.clientWellKnownIntervalID=setInterval(()=>{t.fetchClientWellKnown()},1e3*t.clientOpts.clientWellKnownPollPeriod),t.fetchClientWellKnown()),t.toDeviceMessageQueue.start(),t.serverCapabilitiesService.start()}})()}buildSyncApiOptions(){return{crypto:this.crypto,cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1}}stopClient(){var e,t,n,i,o;(e=this.cryptoBackend)===null||e===void 0||e.stop(),this.off(Te.Sync,this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(t=this.syncApi)===null||t===void 0||t.stop(),this.syncApi=void 0,(n=this.peekSync)===null||n===void 0||n.stopPeeking(),(i=this.callEventHandler)===null||i===void 0||i.stop(),(o=this.groupCallEventHandler)===null||o===void 0||o.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,globalThis.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.clientWellKnownIntervalID!==void 0&&globalThis.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop(),this.matrixRTC.stop(),this.serverCapabilitiesService.stop())}rehydrateDevice(){var e=this;return _(function*(){if(e.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(e.cryptoCallbacks.getDehydrationKey){var t=yield e.getDehydratedDevice();if(t){if(!t.device_data||!t.device_id){e.logger.info("no dehydrated device found");return}var n=new globalThis.Olm.Account;try{var i=t.device_data;if(i.algorithm!==zh){e.logger.warn("Wrong algorithm for dehydrated device");return}e.logger.debug("unpickling dehydrated device");var o=yield e.cryptoCallbacks.getDehydrationKey(i,l=>{n.unpickle(new Uint8Array(l),i.account)});n.unpickle(o,i.account),e.logger.debug("unpickled device");var s=yield e.http.authedRequest(Z.Post,"/dehydrated_device/claim",void 0,{device_id:t.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"});if(s.success){e.deviceId=t.device_id,e.logger.info("using dehydrated device");var a=e.pickleKey||"DEFAULT_KEY";return e.exportedOlmDeviceToImport={pickledAccount:n.pickle(a),sessions:[],pickleKey:a},n.free(),e.deviceId}else{n.free(),e.logger.info("not using dehydrated device");return}}catch(l){n.free(),e.logger.warn("could not unpickle",l)}}}})()}getDehydratedDevice(){var e=this;return _(function*(){try{return yield e.http.authedRequest(Z.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(t){e.logger.info("could not get dehydrated device",t);return}})()}setDehydrationKey(e,t,n){var i=this;return _(function*(){if(!i.crypto){i.logger.warn("not dehydrating device if crypto is not enabled");return}return i.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,n)})()}createDehydratedDevice(e,t,n){var i=this;return _(function*(){if(!i.crypto){i.logger.warn("not dehydrating device if crypto is not enabled");return}return yield i.crypto.dehydrationManager.setKey(e,t,n),i.crypto.dehydrationManager.dehydrateDevice()})()}exportDevice(){var e=this;return _(function*(){if(!e.crypto){e.logger.warn("not exporting device if crypto is not enabled");return}return{userId:e.credentials.userId,deviceId:e.deviceId,olmDevice:yield e.crypto.olmDevice.export()}})()}clearStores(){var e=this;if(this.clientRunning)throw new Error("Cannot clear stores while client is running");var t=[];t.push(this.store.deleteAllData()),this.cryptoStore&&t.push(this.cryptoStore.deleteAllData());var n=function(){var i=_(function*(){var o;try{if(o=globalThis.indexedDB,!o)return}catch{return}var s=function*(c){var u=new Promise((d,f)=>{e.logger.info("Removing IndexedDB instance ".concat(c));var p=o.deleteDatabase(c);p.onsuccess=h=>{e.logger.info("Removed IndexedDB instance ".concat(c)),d(0)},p.onerror=h=>{e.logger.warn("Failed to remove IndexedDB instance ".concat(c,":"),h),d(0)},p.onblocked=h=>{e.logger.info("cannot yet remove IndexedDB instance ".concat(c))}});yield u};for(var a of["".concat(ny,"::matrix-sdk-crypto"),"".concat(ny,"::matrix-sdk-crypto-meta")])yield*s(a)});return function(){return i.apply(this,arguments)}}();return t.push(n()),Promise.all(t).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getSafeUserId(){var e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}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(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(e){return Bd(this,e)}createGroupCall(e,t,n,i,o,s){var a=this;return _(function*(){if(a.getGroupCallForRoom(e))throw new Error("".concat(e," already has an existing group call"));var l=a.getRoom(e);if(!l)throw new Error("Cannot find room ".concat(e));return new Sw(a,l,t,n,i,void 0,o||a.isVoipWithNoMediaAllowed,s,a.isVoipWithNoMediaAllowed,a.useLivekitForGroupCalls,a.livekitServiceURL).create()})()}getLivekitServiceURL(){return this.livekitServiceURL}setLivekitServiceURL(e){this.livekitServiceURL=e}waitUntilRoomReadyForGroupCalls(e){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(e)}getGroupCallForRoom(e){return this.groupCallEventHandler.groupCalls.get(e)||null}getSyncState(){var e,t;return(e=(t=this.syncApi)===null||t===void 0?void 0:t.getSyncState())!==null&&e!==void 0?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){var e=this.getSyncState();return e?e===ct.Prepared||e===ct.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),(e=(t=this.syncApi)===null||t===void 0?void 0:t.retryImmediately())!==null&&e!==void 0?e:!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(){var e=this;return _(function*(){var t=e.serverCapabilitiesService.getCachedCapabilities();return t||e.serverCapabilitiesService.fetchCapabilities()})()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}initCrypto(){var e=this;return _(function*(){if(!gN())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(e.cryptoBackend){e.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}if(!e.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");e.logger.debug("Crypto: Starting up crypto store..."),yield e.cryptoStore.startup();var t=e.getUserId();if(t===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(e.deviceId===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");var n=new sv(e,t,e.deviceId,e.store,e.cryptoStore,e.verificationMethods);e.reEmitter.reEmit(n,[et.KeyBackupFailed,et.KeyBackupSessionsRemaining,et.RoomKeyRequest,et.RoomKeyRequestCancellation,et.Warning,et.DevicesUpdated,et.WillUpdateDevices,et.DeviceVerificationChanged,et.UserTrustStatusChanged,et.KeysChanged]),e.logger.debug("Crypto: initialising crypto object..."),yield n.init({exportedOlmDevice:e.exportedOlmDeviceToImport,pickleKey:e.pickleKey}),delete e.exportedOlmDeviceToImport,e.olmVersion=sv.getOlmVersion(),n.registerEventHandlers(e),e.cryptoBackend=e.crypto=n,e.crypto.uploadDeviceKeys().catch(i=>{e.logger.error("Error uploading device keys",i)})})()}initRustCrypto(){var e=arguments,t=this;return _(function*(){var n,i=e.length>0&&e[0]!==void 0?e[0]:{};if(t.cryptoBackend){t.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}var o=t.getUserId();if(o===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");var s=t.getDeviceId();if(s===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");t.logger.debug("Downloading Rust crypto library");var a=yield hD(()=>import("./index-JZMMlqDP.js"),[]),l=yield a.initRustCrypto({logger:t.logger,http:t.http,userId:o,deviceId:s,secretStorage:t.secretStorage,cryptoCallbacks:t.cryptoCallbacks,storePrefix:i.useIndexedDB===!1?null:ny,storeKey:i.storageKey,storePassphrase:i.storagePassword,legacyCryptoStore:t.cryptoStore,legacyPickleKey:(n=t.pickleKey)!==null&&n!==void 0?n:"DEFAULT_KEY",legacyMigrationProgressListener:(c,u)=>{t.emit(Yt.LegacyCryptoStoreMigrationProgress,c,u)}});l.setSupportedVerificationMethods(t.verificationMethods),t.cryptoBackend=l,t.on(Ar.Membership,l.onRoomMembership.bind(l)),t.on(Te.Event,c=>{l.onLiveEventFromSync(c)}),t.reEmitter.reEmit(l,[Yt.VerificationRequestReceived,Yt.UserTrustStatusChanged,Yt.KeyBackupStatus,Yt.KeyBackupSessionsRemaining,Yt.KeyBackupFailed,Yt.KeyBackupDecryptionKeyCached,Yt.KeysChanged,Yt.DevicesUpdated,Yt.WillUpdateDevices])})()}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isCryptoEnabled(){return!!this.cryptoBackend}getDeviceEd25519Key(){var e,t;return(e=(t=this.crypto)===null||t===void 0?void 0:t.getDeviceEd25519Key())!==null&&e!==void 0?e:null}getDeviceCurve25519Key(){var e,t;return(e=(t=this.crypto)===null||t===void 0?void 0:t.getDeviceCurve25519Key())!==null&&e!==void 0?e:null}uploadKeys(){var e=this;return _(function*(){e.logger.warn("MatrixClient.uploadKeys is deprecated")})()}downloadKeys(e,t){return this.crypto?this.crypto.downloadKeys(e,t):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(e)||[]}getStoredDevice(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(e,t)||null}setDeviceVerified(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=this.setDeviceVerification(e,t,n,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),i}setDeviceBlocked(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return this.setDeviceVerification(e,t,null,n,null)}setDeviceKnown(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return this.setDeviceVerification(e,t,null,null,n)}setDeviceVerification(e,t,n,i,o){var s=this;return _(function*(){if(!s.crypto)throw new Error("End-to-end encryption disabled");yield s.crypto.setDeviceVerification(e,t,n,i,o)})()}requestVerificationDM(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerificationDM(e,t)}findVerificationRequestDMInProgress(e){if(this.cryptoBackend){if(!this.crypto)return}else throw new Error("End-to-end encryption disabled");return this.crypto.findVerificationRequestDMInProgress(e)}getVerificationRequestsToDeviceInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getVerificationRequestsToDeviceInProgress(e)}requestVerification(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerification(e,t)}beginKeyVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(e,t,n)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}setGlobalBlacklistUnverifiedDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices=e,e}getGlobalBlacklistUnverifiedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices}setGlobalErrorOnUnknownDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.globalErrorOnUnknownDevices=e}getGlobalErrorOnUnknownDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalErrorOnUnknownDevices}getCrossSigningId(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Iw.Master;if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(e)}getStoredCrossSigningForUser(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getStoredCrossSigningForUser(e)}checkUserTrust(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkDeviceTrust(e,t)}checkIfOwnDeviceCrossSigned(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkIfOwnDeviceCrossSigned(e)}checkOwnCrossSigningTrust(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkOwnCrossSigningTrust(e)}checkCrossSigningPrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(e,t)}legacyDeviceVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,n)}prepareToEncrypt(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.prepareToEncrypt(e)}userHasCrossSigningKeys(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.userHasCrossSigningKeys()}isCrossSigningReady(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.isCrossSigningReady()}bootstrapCrossSigning(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.bootstrapCrossSigning(e)}getCryptoTrustCrossSignedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.setTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getEventEncryptionInfo(e)}createRecoveryKeyFromPassphrase(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.createRecoveryKeyFromPassphrase(e)}isSecretStorageReady(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.isSecretStorageReady()}bootstrapSecretStorage(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.bootstrapSecretStorage(e)}addSecretStorageKey(e,t,n){return this.secretStorage.addKey(e,t,n)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}storeSecret(e,t,n){return this.secretStorage.store(e,t,n)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStoragePrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(e,t)}getEventSenderDeviceInfo(e){var t=this;return _(function*(){return t.crypto?t.crypto.getEventSenderDeviceInfo(e):null})()}isEventSenderVerified(e){var t=this;return _(function*(){var n=yield t.getEventSenderDeviceInfo(e);return n?n.isVerified():!1})()}getOutgoingRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");var t=e.getWireContent(),n={session_id:t.session_id,sender_key:t.sender_key,algorithm:t.algorithm,room_id:e.getRoomId()};return!n.session_id||!n.sender_key||!n.algorithm||!n.room_id?Promise.resolve(null):this.crypto.cryptoStore.getOutgoingRoomKeyRequest(n)}cancelAndResendEventRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");return e.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(e,t)}isRoomEncrypted(e){var t,n,i=this.getRoom(e);return i?i.hasEncryptionStateEvent()?!0:(t=(n=this.crypto)===null||n===void 0?void 0:n.isRoomEncrypted(e))!==null&&t!==void 0?t:!1:!1}encryptAndSendToDevices(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.encryptAndSendToDevices(e,t)}forceDiscardSession(e){if(!this.cryptoBackend)throw new Error("End-to-End encryption disabled");this.cryptoBackend.forceDiscardSession(e)}exportRoomKeys(){return this.cryptoBackend?this.cryptoBackend.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(e,t){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.importRoomKeys(e,t)}checkKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.checkKeyBackup()}getKeyBackupVersion(){var e=this;return _(function*(){var t;try{t=yield e.http.authedRequest(Z.Get,"/room_keys/version",void 0,void 0,{prefix:Ot.V3})}catch(n){if(n.errcode==="M_NOT_FOUND")return null;throw n}return ka.checkBackupVersion(t),t})()}isKeyBackupTrusted(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.isKeyBackupTrusted(e)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(e)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}prepareKeyBackupVersion(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{secureSecretStorage:!1};if(!n.crypto)throw new Error("End-to-end encryption disabled");var{algorithm:o,auth_data:s,recovery_key:a,privateKey:l}=yield n.crypto.backupManager.prepareKeyBackupVersion(e);return i.secureSecretStorage&&(yield n.secretStorage.store("m.megolm_backup.v1",Qr(l)),n.logger.info("Key backup private key stored in secret storage")),{algorithm:o,auth_data:s,recovery_key:a}})()}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}createKeyBackupVersion(e){var t=this;return _(function*(){if(!t.crypto)throw new Error("End-to-end encryption disabled");yield t.crypto.backupManager.createKeyBackupVersion(e);var n={algorithm:e.algorithm,auth_data:e.auth_data};yield t.crypto.signObject(n.auth_data),t.cryptoCallbacks.getCrossSigningKey&&t.crypto.crossSigningInfo.getId()&&(yield t.crypto.crossSigningInfo.signObject(n.auth_data,"master"));var i=yield t.http.authedRequest(Z.Post,"/room_keys/version",void 0,n);return yield t.checkKeyBackup(),t.getKeyBackupEnabled()||t.logger.error("Key backup not usable even though we just created it"),i})()}deleteKeyBackupVersion(e){var t=this;return _(function*(){if(!t.cryptoBackend)throw new Error("End-to-end encryption disabled");yield t.cryptoBackend.deleteKeyBackupVersion(e)})()}makeKeyBackupPath(e,t,n){var i;t!==void 0?i=Se("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):e!==void 0?i=Se("/room_keys/keys/$roomId",{$roomId:e}):i="/room_keys/keys";var o=n===void 0?void 0:{version:n};return{path:i,queryData:o}}sendKeyBackup(e,t,n,i){var o=this;return _(function*(){if(!o.crypto)throw new Error("End-to-end encryption disabled");var s=o.makeKeyBackupPath(e,t,n);yield o.http.authedRequest(Z.Put,s.path,s.queryData,i,{prefix:Ot.V3})})()}scheduleAllGroupSessionsForBackup(){var e=this;return _(function*(){if(!e.crypto)throw new Error("End-to-end encryption disabled");yield e.crypto.backupManager.scheduleAllGroupSessionsForBackup()})()}flagAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.flagAllGroupSessionsForBackup()}isValidRecoveryKey(e){try{return id(e),!0}catch{return!1}}keyBackupKeyFromPassword(e,t){return ak(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return id(e)}restoreKeyBackupWithPassword(e,t,n,i,o){var s=this;return _(function*(){var a=yield ak(i.auth_data,e);return s.restoreKeyBackup(a,t,n,i,o)})()}restoreKeyBackupWithSecretStorage(e,t,n,i){var o=this;return _(function*(){if(!o.cryptoBackend)throw new Error("End-to-end encryption disabled");var s=yield o.secretStorage.get("m.megolm_backup.v1"),a=Yh(s);if(a){var l=yield o.secretStorage.getKey();yield o.secretStorage.store("m.megolm_backup.v1",a,[l[0]])}var c=Dr(a||s);return o.restoreKeyBackup(c,t,n,e,i)})()}restoreKeyBackupWithRecoveryKey(e,t,n,i,o){var s=id(e);return this.restoreKeyBackup(s,t,n,i,o)}restoreKeyBackupWithCache(e,t,n,i){var o=this;return _(function*(){if(!o.cryptoBackend)throw new Error("End-to-end encryption disabled");var s=yield o.cryptoBackend.getSessionBackupPrivateKey();if(!s)throw new Error("Couldn't get key");return o.restoreKeyBackup(s,e,t,n,i)})()}restoreKeyBackup(e,t,n,i,o){var s=this;return _(function*(){var a=o==null?void 0:o.cacheCompleteCallback,l=o==null?void 0:o.progressCallback;if(!s.cryptoBackend)throw new Error("End-to-end encryption disabled");if(!i.version)throw new Error("Backup version must be defined");var c=i.version,u=0,d=0,f=0,p=s.makeKeyBackupPath(t,n,c),h=yield s.cryptoBackend.getBackupDecryptor(i,e),m=!h.sourceTrusted;try{if(!(e instanceof Uint8Array))throw new Error("restoreKeyBackup expects Uint8Array, got ".concat(e));s.cryptoBackend.storeSessionBackupPrivateKey(e,c).catch(O=>{s.logger.warn("Error caching session backup key:",O)}).then(a),l&&l({stage:"fetch"});var w=yield s.http.authedRequest(Z.Get,p.path,p.queryData,void 0,{prefix:Ot.V3});if(l&&l({stage:"load_keys"}),w.rooms)u=s.getTotalKeyCount(w),yield s.handleDecryptionOfAFullBackup(w,h,200,function(){var O=_(function*(T){try{var x=i.version;yield s.cryptoBackend.importBackedUpRoomKeys(T,x,{untrusted:m}),f+=T.length}catch(C){d+=T.length,S.error("Error importing keys from backup",C)}l&&l({total:u,successes:f,stage:"load_keys",failures:d})});return function(T){return O.apply(this,arguments)}}());else if(w.sessions){var g=w.sessions;u=Object.keys(g).length;var b=yield h.decryptSessions(g);for(var R of b)R.room_id=t;yield s.cryptoBackend.importBackedUpRoomKeys(b,c,{progressCallback:l,untrusted:m}),f=b.length}else{u=1;try{var[k]=yield h.decryptSessions({[n]:w});k.room_id=t,k.session_id=n,yield s.cryptoBackend.importBackedUpRoomKeys([k],c,{progressCallback:l,untrusted:m}),f=1}catch(O){s.logger.debug("Failed to decrypt megolm session from backup",O)}}}finally{h.free()}return yield s.cryptoBackend.checkKeyBackupAndEnable(),{total:u,imported:f}})()}getTotalKeyCount(e){var t=e.rooms,n=0;for(var i of Object.values(t))i.sessions&&(n+=Object.keys(i.sessions).length);return n}handleDecryptionOfAFullBackup(e,t,n,i){return _(function*(){var o=e.rooms,s=0,a=new Map,l=function(){var h=_(function*(m){var w=[];for(var g of m.keys()){var b=yield t.decryptSessions(m.get(g));for(var R in b){var k=b[R];k.room_id=g,w.push(k)}}yield i(w)});return function(w){return h.apply(this,arguments)}}();for(var[c,u]of Object.entries(o))if(u.sessions){a.set(c,{});for(var[d,f]of Object.entries(u.sessions)){var p=a.get(c);p[d]=f,s+=1,s>=n&&(yield l(a),a=new Map,a.set(c,{}),s=0)}}s>0&&(yield l(a))})()}deleteKeysFromBackup(e,t,n){var i=this;return _(function*(){var o=i.makeKeyBackupPath(e,t,n);yield i.http.authedRequest(Z.Delete,o.path,o.queryData,void 0,{prefix:Ot.V3})})()}getMediaConfig(){return this.http.authedRequest(Z.Get,"/config",void 0,void 0,{prefix:Jl.V3})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.store.getRooms(),n=new Set;for(var i of t){var o,s=(o=i.findPredecessor(e))===null||o===void 0?void 0:o.roomId;s&&n.add(s)}return t.filter(a=>{var l=a.currentState.getStateEvents(V.RoomTombstone,"");return!(l&&n.has(a.roomId))})}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t){var n=Se("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return ND(5,()=>this.http.authedRequest(Z.Put,n,void 0,t))}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var t=this;return _(function*(){if(t.isInitialSyncComplete()){var n=t.store.getAccountData(e);return n?n.getContent():null}var i=Se("/user/$userId/account_data/$type",{$userId:t.credentials.userId,$type:e});try{return yield t.http.authedRequest(Z.Get,i)}catch(s){var o;if(((o=s.data)===null||o===void 0?void 0:o.errcode)==="M_NOT_FOUND")return null;throw s}})()}deleteAccountData(e){var t=this;return _(function*(){var n=t.canSupport.get(dr.AccountDataDeletion);if(n===lr.Unsupported){yield t.setAccountData(e,{});return}var i=Se("/user/$userId/account_data/$type",{$userId:t.getSafeUserId(),$type:e}),o=n===lr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield t.http.authedRequest(Z.Delete,i,void 0,void 0,o)})()}getIgnoredUsers(){var e=this.getAccountData("m.ignored_user_list");return!e||!e.getContent()||!e.getContent().ignored_users?[]:Object.keys(e.getContent().ignored_users)}setIgnoredUsers(e){var t={ignored_users:{}};return e.forEach(n=>{t.ignored_users[n]={}}),this.setAccountData("m.ignored_user_list",t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};i.syncRoom===void 0&&(i.syncRoom=!0);var o=n.getRoom(e);if(o!=null&&o.hasMembershipState(n.credentials.userId,Be.Join))return o;var s=Promise.resolve();if(i.inviteSignUrl){var a=new URL(i.inviteSignUrl);a.searchParams.set("mxid",n.credentials.userId),s=n.http.requestOtherUrl(Z.Post,a)}var l={};i.viaServers&&(l.server_name=i.viaServers,l.via=i.viaServers);var c={},u=yield s;u&&(c.third_party_signed=u);var d=Se("/join/$roomid",{$roomid:e}),f=yield n.http.authedRequest(Z.Post,d,l,c),p=f.room_id,h=n.getRoom(p);if(h!=null&&h.hasMembershipState(n.credentials.userId,Be.Join))return h;var m=new Mu(n,n.clientOpts,n.buildSyncApiOptions()),w=m.createRoom(p);return i.syncRoom,w})()}knockRoom(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=this.getRoom(e);if(n!=null&&n.hasMembershipState(this.credentials.userId,Be.Knock))return Promise.resolve({room_id:n.roomId});var i=Se("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),o={};t.viaServers&&(o.server_name=t.viaServers,o.via=t.viaServers);var s={};return t.reason&&(s.reason=t.reason),this.http.authedRequest(Z.Post,i,o,s)}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,je.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![je.QUEUED,je.NOT_SENT,je.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===je.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===je.QUEUED&&this.scheduler.removeEventFromQueue(e);var t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,je.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,V.RoomName,{name:t})}setRoomTopic(e,t,n){var i=RD(t,n);return this.sendStateEvent(e,V.RoomTopic,i)}getRoomTags(e){var t=Se("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(Z.Get,t)}setRoomTag(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=Se("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(Z.Put,i,void 0,n)}deleteRoomTag(e,t){var n=Se("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(Z.Delete,n)}setRoomAccountData(e,t,n){var i=Se("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(Z.Put,i,void 0,n)}setPowerLevel(e,t,n){var i=this;return _(function*(){var o,s;if(i.clientRunning&&i.isInitialSyncComplete()){var a;s=(a=i.getRoom(e))===null||a===void 0||(a=a.currentState)===null||a===void 0||(a=a.getStateEvents(V.RoomPowerLevels,""))===null||a===void 0?void 0:a.getContent()}if(!s)try{s=yield i.getStateEvent(e,V.RoomPowerLevels,"")}catch(u){if(u instanceof hr&&u.errcode==="M_NOT_FOUND")s={};else throw u}s=lm(s),(o=s)!==null&&o!==void 0&&o.users||(s.users={});var l=Array.isArray(t)?t:[t];for(var c of l)n==null?delete s.users[c]:s.users[c]=n;return i.sendStateEvent(e,V.RoomPowerLevels,s,"")})()}unstable_createLiveBeacon(e,t){var n=this;return _(function*(){return n.unstable_setLiveBeacon(e,t)})()}unstable_setLiveBeacon(e,t){var n=this;return _(function*(){return n.sendStateEvent(e,fw.name,t,n.getUserId())})()}sendEvent(e,t,n,i,o){var s,a,l,c;return!(t!=null&&t.startsWith(Di))&&t!==null?(c=i,l=n,a=t,s=null):(c=o,l=i,a=n,s=t),this.addThreadRelationIfNeeded(l,s,e),this.sendCompleteEvent(e,s,{type:a,content:l},c)}addThreadRelationIfNeeded(e,t,n){var i;if(t&&!((i=e["m.relates_to"])!==null&&i!==void 0&&i.rel_type)){var o,s,a=!!((o=e["m.relates_to"])!==null&&o!==void 0&&o["m.in_reply_to"]);e["m.relates_to"]=Cr(Cr({},e["m.relates_to"]),{},{rel_type:vt.name,event_id:t,is_falling_back:!a});var l=(s=this.getRoom(n))===null||s===void 0?void 0:s.getThread(t);if(l&&!a){var c,u;e["m.relates_to"]["m.in_reply_to"]={event_id:(c=(u=l.lastReply(d=>d.isRelation(vt.name)&&!d.status))===null||u===void 0?void 0:u.getId())!==null&&c!==void 0?c:t}}}}sendCompleteEvent(e,t,n,i,o){var s,a;typeof i=="string"?a=i:(s=i,a=o),a||(a=this.makeTxnId());var l=new pr(Object.assign(n,{event_id:"~"+e+":"+a,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:new Date().getTime()})),c=this.getRoom(e),u=t?c==null?void 0:c.getThread(t):void 0;u&&l.setThread(u),s||(this.reEmitter.reEmit(l,[ot.Replaced,ot.VisibilityChange]),c==null||c.reEmitter.reEmit(l,[ot.BeforeRedaction]));var d=l.getAssociatedId();if(d!=null&&d.startsWith("~")){var f=c==null?void 0:c.getPendingEvents().find(h=>h.getId()===d);f==null||f.once(ot.LocalEventIdReplaced,()=>{l.updateAssociatedId(f.getId())})}var p=l.getType();return this.logger.debug("sendEvent of type ".concat(p," in ").concat(e," with txnId ").concat(a).concat(s?" (delayed event)":"")),l.setTxnId(a),l.setStatus(je.SENDING),s?this.encryptAndSendEvent(c,l,s):(c==null||c.addPendingEvent(l,a),l.status===je.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(c,l))}encryptAndSendEvent(e,t,n){var i=this;return _(function*(){if(n)return i.sendEventHttpRequest(t,n);try{var o;i.eventsBeingEncrypted.add(t.getId());try{yield i.encryptEventIfNeeded(t,e??void 0)}finally{o=!i.eventsBeingEncrypted.delete(t.getId())}if(o)return{};t.status===je.ENCRYPTING&&i.updatePendingEventStatus(e,t,je.SENDING);var s=null;return i.scheduler&&(s=i.scheduler.queueEvent(t),s&&i.scheduler.getQueueForEvent(t).length>1&&i.updatePendingEventStatus(e,t,je.QUEUED)),s||(s=i.sendEventHttpRequest(t),e&&(s=s.then(a=>(e.updatePendingEvent(t,je.SENT,a.event_id),a)))),yield s}catch(a){i.logger.error("Error sending event",a);try{t.error=a,i.updatePendingEventStatus(e,t,je.NOT_SENT)}catch(l){i.logger.error("Exception in error handler!",l)}throw a instanceof hr&&(a.event=t),a}})()}encryptEventIfNeeded(e,t){var n=this;return _(function*(){if(t&&(yield n.shouldEncryptEventForRoom(e,t))&&!(!n.cryptoBackend&&n.usingExternalCrypto)){if(!n.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");n.updatePendingEventStatus(t,e,je.ENCRYPTING),yield n.cryptoBackend.encryptEvent(e,t)}})()}shouldEncryptEventForRoom(e,t){var n=this;return _(function*(){var i;return e.isEncrypted()||e.getType()===V.Reaction||e.isRedaction()?!1:!!(t.hasEncryptionStateEvent()||(yield(i=n.cryptoBackend)===null||i===void 0?void 0:i.isEncryptionEnabledInRoom(t.roomId)))})()}getEncryptedIfNeededEventType(e,t){var n;return t===V.Reaction?t:(n=this.getRoom(e))!==null&&n!==void 0&&n.hasEncryptionStateEvent()?V.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,n){e?e.updatePendingEvent(t,n):t.setStatus(n)}sendEventHttpRequest(e,t){var n=e.getTxnId();n||(n=this.makeTxnId(),e.setTxnId(n));var i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:n},o;if(e.isState()){var s="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(s="/rooms/$roomId/state/$eventType/$stateKey"),o=Se(s,i)}else if(e.isRedaction()&&e.event.redacts){var a="/rooms/$roomId/redact/$redactsEventId/$txnId";o=Se(a,Cr({$redactsEventId:e.event.redacts},i))}else o=Se("/rooms/$roomId/send/$eventType/$txnId",i);var l=e.getWireContent();return t?this.http.authedRequest(Z.Put,o,Ok(t),l):this.http.authedRequest(Z.Put,o,void 0,l).then(c=>(this.logger.debug("Event sent to ".concat(e.getRoomId()," with event id ").concat(c.event_id)),c))}redactEvent(e,t,n,i,o){var s,a,l;(s=n)!==null&&s!==void 0&&s.startsWith(Di)||(o=i,i=n,n=t,t=null);var c=(a=o)===null||a===void 0?void 0:a.reason,u={reason:c};if(((l=o)===null||l===void 0?void 0:l.with_rel_types)!==void 0){if(this.canSupport.get(dr.RelationBasedRedactions)===lr.Unsupported)throw new Error("Server does not support relation based redactions "+"roomId ".concat(e," eventId ").concat(n," txnId: ").concat(i," threadId ").concat(t));var d=this.canSupport.get(dr.RelationBasedRedactions)===lr.Stable?Sb.stable:Sb.unstable;u[d]=o.with_rel_types}return this.sendCompleteEvent(e,t,{type:V.RoomRedaction,content:u,redacts:n},i)}sendMessage(e,t,n,i){typeof t!="string"&&t!==null&&(i=n,n=t,t=null);var o=V.RoomMessage,s=n;return this.sendEvent(e,t,o,s,i)}sendTextMessage(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=bD(n);return this.sendMessage(e,t,s,i)}sendNotice(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=_D(n);return this.sendMessage(e,t,s,i)}sendEmoteMessage(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=ED(n);return this.sendMessage(e,t,s,i)}sendImageMessage(e,t,n,i){var o,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Image";!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(s=i||"Image",i=n,n=t,t=null);var a={msgtype:xi.Image,url:n,info:i,body:s};return this.sendMessage(e,t,a)}sendStickerMessage(e,t,n,i){var o,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Sticker";!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(s=i||"Sticker",i=n,n=t,t=null);var a={url:n,info:i,body:s};return this.sendEvent(e,t,V.Sticker,a)}sendHtmlMessage(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=gD(n,i);return this.sendMessage(e,t,s)}sendHtmlNotice(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=yD(n,i);return this.sendMessage(e,t,s)}sendHtmlEmote(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=SD(n,i);return this.sendMessage(e,t,s)}_unstable_sendDelayedEvent(e,t,n,i,o,s){var a=this;return _(function*(){if(!(yield a.doesServerSupportUnstableFeature($i)))throw Error("Server does not support the delayed events API");return a.addThreadRelationIfNeeded(o,n,e),a.sendCompleteEvent(e,n,{type:i,content:o},t,s)})()}_unstable_sendDelayedStateEvent(e,t,n,i){var o=arguments,s=this;return _(function*(){var a=o.length>4&&o[4]!==void 0?o[4]:"",l=o.length>5&&o[5]!==void 0?o[5]:{};if(!(yield s.doesServerSupportUnstableFeature($i)))throw Error("Server does not support the delayed events API");var c={$roomId:e,$eventType:n,$stateKey:a},u=Se("/rooms/$roomId/state/$eventType",c);return a!==void 0&&(u=Se(u+"/$stateKey",c)),s.http.authedRequest(Z.Put,u,Ok(t),i,l)})()}_unstable_getDelayedEvents(e){var t=this;return _(function*(){if(!(yield t.doesServerSupportUnstableFeature($i)))throw Error("Server does not support the delayed events API");var n=e?{from:e}:void 0;return yield t.http.authedRequest(Z.Get,"/delayed_events",n,void 0,{prefix:"".concat(Ot.Unstable,"/").concat($i)})})()}_unstable_updateDelayedEvent(e,t){var n=this;return _(function*(){if(!(yield n.doesServerSupportUnstableFeature($i)))throw Error("Server does not support the delayed events API");var i=Se("/delayed_events/$delayId",{$delayId:e}),o={action:t};return yield n.http.authedRequest(Z.Post,i,void 0,o,{prefix:"".concat(Ot.Unstable,"/").concat($i)})})()}sendReceipt(e,t,n){var i=arguments,o=this;return _(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!1;if(o.isGuest())return Promise.resolve({});var a=Se("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),l=!s&&o.supportsThreads(),c=l?Cr(Cr({},n),{},{thread_id:Tc(e)}):n,u=o.http.authedRequest(Z.Post,a,void 0,c||{}),d=o.getRoom(e.getRoomId());return d&&o.credentials.userId&&d.addLocalEchoReceipt(o.credentials.userId,e,t,s),u})()}sendReadReceipt(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:Jr.Read,o=t.length>2&&t[2]!==void 0?t[2]:!1;if(e){var s=e.getId(),a=n.getRoom(e.getRoomId());if(a!=null&&a.hasPendingEvent(s))throw new Error("Cannot set read receipt to a pending event (".concat(s,")"));return n.sendReceipt(e,i,{},o)}})()}setRoomReadMarkers(e,t,n,i){var o=this;return _(function*(){var s=o.getRoom(e);if(s!=null&&s.hasPendingEvent(t))throw new Error("Cannot set read marker to a pending event (".concat(t,")"));var a;if(n){if(a=n.getId(),s!=null&&s.hasPendingEvent(a))throw new Error("Cannot set read receipt to a pending event (".concat(a,")"));s==null||s.addLocalEchoReceipt(o.credentials.userId,n,Jr.Read)}var l;if(i){if(l=i.getId(),s!=null&&s.hasPendingEvent(l))throw new Error("Cannot set read receipt to a pending event (".concat(l,")"));s==null||s.addLocalEchoReceipt(o.credentials.userId,i,Jr.ReadPrivate)}return yield o.setRoomReadMarkersHttpRequest(e,t,a,l)})()}getUrlPreview(e,t){t=Math.floor(t/6e4)*6e4;var n=new URL(e);n.hash="",e=n.toString();var i=t+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];var o=this.http.authedRequest(Z.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:Jl.V3,priority:"low"});return this.urlPreviewCache[i]=o,o}sendTyping(e,t,n){if(this.isGuest())return Promise.resolve({});var i=Se("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),o={typing:t};return t&&(o.timeout=n||2e4),this.http.authedRequest(Z.Put,i,void 0,o)}getRoomUpgradeHistory(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=this.getRoom(e);if(!i)return[];var o=this.findPredecessorRooms(i,t,n),s=this.findSuccessorRooms(i,t,n);return[...o,i,...s]}findPredecessorRooms(e,t,n){for(var i,o=[],s=new Set([e.roomId]),a=(i=e.findPredecessor(n))===null||i===void 0?void 0:i.roomId;a!==null;){var l;if(a){if(s.has(a))break;s.add(a)}var c=this.getRoom(a);if(c===null)break;if(t){var u=c.currentState.getStateEvents(V.RoomTombstone,"");if(!u||u.getContent().replacement_room!==e.roomId)break}o.splice(0,0,c),e=c,a=(l=e.findPredecessor(n))===null||l===void 0?void 0:l.roomId}return o}findSuccessorRooms(e,t,n){for(var i=[],o=e.currentState.getStateEvents(V.RoomTombstone,"");o;){var s=this.getRoom(o.getContent().replacement_room);if(!s||s.roomId===e.roomId)break;if(t){var a,l=(a=s.findPredecessor(n))===null||a===void 0?void 0:a.roomId;if(!l||l!==e.roomId)break}i.push(s);var c=new Set(i.map(u=>u.roomId));if(c.size<i.length)return i.slice(0,i.length-1);e=s,o=e.currentState.getStateEvents(V.RoomTombstone,"")}return i}invite(e,t,n){return this.membershipChange(e,t,Be.Invite,n)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}inviteByThreePid(e,t,n){var i=this;return _(function*(){var o,s=Se("/rooms/$roomId/invite",{$roomId:e}),a=i.getIdentityServerUrl(!0);if(!a)return Promise.reject(new hr({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));var l={id_server:a,medium:t,address:n};if((o=i.identityServer)!==null&&o!==void 0&&o.getAccessToken){var c=yield i.identityServer.getAccessToken();c&&(l.id_access_token=c)}return i.http.authedRequest(Z.Post,s,void 0,l)})()}leave(e){return this.membershipChange(e,void 0,Be.Leave)}leaveRoomChain(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,n=this.getRoomUpgradeHistory(e),i=n;if(!t){i=[];for(var o of n)if(i.push(o),o.roomId===e)break}var s={},a=[],l=u=>this.leave(u).then(()=>{delete s[u]}).catch(d=>{s[u]=d});for(var c of i)a.push(l(c.roomId));return Promise.all(a).then(()=>s)}ban(e,t,n){return this.membershipChange(e,t,Be.Ban,n)}forget(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!0,o=Se("/rooms/$room_id/forget",{$room_id:e}),s=yield n.http.authedRequest(Z.Post,o);return i&&(n.store.removeRoom(e),n.emit(Te.DeleteRoom,e)),s})()}unban(e,t){var n=Se("/rooms/$roomId/unban",{$roomId:e}),i={user_id:t};return this.http.authedRequest(Z.Post,n,void 0,i)}kick(e,t,n){var i=Se("/rooms/$roomId/kick",{$roomId:e}),o={user_id:t,reason:n};return this.http.authedRequest(Z.Post,i,void 0,o)}membershipChange(e,t,n,i){var o=Se("/rooms/$room_id/$membership",{$room_id:e,$membership:n});return this.http.authedRequest(Z.Post,o,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushActions()||t){var{actions:n,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(n,i)}return e.getPushActions()}getPushDetailsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushDetails()||t){var{actions:n,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(n,i)}return e.getPushDetails()}setProfileInfo(e,t){var n=Se("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(Z.Put,n,void 0,t)}setDisplayName(e){var t=this;return _(function*(){var n=yield t.setProfileInfo("displayname",{displayname:e}),i=t.getUser(t.getUserId());return i&&(i.displayName=e,i.emit(ar.DisplayName,i.events.presence,i)),n})()}setAvatarUrl(e){var t=this;return _(function*(){var n=yield t.setProfileInfo("avatar_url",{avatar_url:e}),i=t.getUser(t.getUserId());return i&&(i.avatarUrl=e,i.emit(ar.AvatarUrl,i.events.presence,i)),n})()}mxcUrlToHttp(e,t,n,i,o,s,a){return um(this.baseUrl,e,t,n,i,o,s,a)}setSyncPresence(e){var t=this;return _(function*(){var n;(n=t.syncApi)===null||n===void 0||n.setPresence(e)})()}setPresence(e){var t=this;return _(function*(){var n=Se("/presence/$userId/status",{$userId:t.credentials.userId}),i=["offline","online","unavailable"];if(i.indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);yield t.http.authedRequest(Z.Put,n,void 0,e)})()}getPresence(e){var t=Se("/presence/$userId/status",{$userId:e});return this.http.authedRequest(Z.Get,t)}scrollback(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:30,n=0,i=this.ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){var o=Date.now()-i.errorTs;n=Math.max(q9-o,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);var s=this.store.scrollback(e,t).length;if(s===t)return Promise.resolve(e);t=t-s;var a=new Promise((l,c)=>{As(n).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,Ge.Backward)).then(u=>{var d,f,p=u.chunk.map(this.getEventMapper());if(u.state){var h=u.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(h)}var[m,w,g]=e.partitionThreadedEvents(p);this.processAggregatedTimelineEvents(e,m),e.addEventsToTimeline(m,!0,e.getLiveTimeline()),this.processThreadEvents(e,w,!0),g.forEach(b=>e.relations.aggregateChildEvent(b)),e.oldState.paginationToken=(d=u.end)!==null&&d!==void 0?d:null,u.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,p,(f=u.end)!==null&&f!==void 0?f:null,!0),delete this.ongoingScrollbacks[e.roomId],l(e)}).catch(u=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},c(u)})});return i={promise:a},this.ongoingScrollbacks[e.roomId]=i,a}getEventMapper(e){return k9(this,e||{})}getEventTimeline(e,t){var n=this;return _(function*(){var i,o,s,a;if(!n.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!(e!=null&&e.room))throw new Error("getEventTimeline only supports room timelines");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);if(e.thread&&n.supportsThreads())return n.getThreadTimeline(e,t);var l=Se("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),c=void 0;(i=n.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(c={filter:JSON.stringify(gn.LAZY_LOADING_MESSAGES_FILTER)});var u=yield n.http.authedRequest(Z.Get,l,c);if(!u.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);var d=n.getEventMapper(),f=d(u.event);if(f.isRelation(vt.name)){n.logger.warn("Tried loading a regular timeline at the position of a thread event");return}var p=[...u.events_after.reverse().map(d),f,...u.events_before.map(d)],h=e.getTimelineForEvent(p[0].getId());h?h.getState(Ee.BACKWARDS).setUnknownStateEvents(u.state.map(d)):(h=e.addTimeline(),h.initialiseState(u.state.map(d)),h.getState(Ee.FORWARDS).paginationToken=u.end);var[m,w,g]=e.room.partitionThreadedEvents(p);return e.addEventsToTimeline(m,!0,h,u.start),n.processThreadEvents(e.room,w,!0),n.processAggregatedTimelineEvents(e.room,m),g.forEach(b=>e.relations.aggregateChildEvent(b)),(o=(s=e.getTimelineForEvent(t))!==null&&s!==void 0?s:(a=e.room.findThreadForEvent(f))===null||a===void 0?void 0:a.liveTimeline)!==null&&o!==void 0?o:h})()}getThreadTimeline(e,t){var n=this;return _(function*(){var i;if(!n.supportsThreads())throw new Error("could not get thread timeline: no client support");if(!e.room)throw new Error("could not get thread timeline: not a room timeline");if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var o=Se("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),s={limit:"0"};(i=n.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(s.filter=JSON.stringify(gn.LAZY_LOADING_MESSAGES_FILTER));var a=yield n.http.authedRequest(Z.Get,o,s),l=n.getEventMapper(),c=l(a.event);if(e.canContain(c)){var u=n.canSupport.get(dr.RelationsRecursion)!==lr.Unsupported;if(Et.hasServerSideSupport)if(Et.hasServerSideFwdPaginationSupport){var d,f,p;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var h=e.thread,m=yield n.fetchRelations(e.room.roomId,h.id,null,null,{dir:Ge.Backward,from:a.start,recurse:u||void 0}),w=yield n.fetchRelations(e.room.roomId,h.id,null,null,{dir:Ge.Forward,from:a.end,recurse:u||void 0}),g=[...w.chunk.reverse().filter(oy(h.id)).map(l),c,...m.chunk.filter(oy(h.id)).map(l)];for(var b of g){var R;yield(R=e.thread)===null||R===void 0?void 0:R.processEvent(b)}var k=e.getTimelineForEvent(c.getId());if(k?k.getState(Ee.BACKWARDS).setUnknownStateEvents(a.state.map(l)):(k=e.addTimeline(),k.initialiseState(a.state.map(l))),e.addEventsToTimeline(g,!0,k,w.next_batch),!m.next_batch){var O=yield n.fetchRoomEvent(e.room.roomId,h.id);e.addEventsToTimeline([l(O)],!0,k,null)}return k.setPaginationToken((d=m.next_batch)!==null&&d!==void 0?d:null,Ge.Backward),k.setPaginationToken((f=w.next_batch)!==null&&f!==void 0?f:null,Ge.Forward),n.processAggregatedTimelineEvents(e.room,g),(p=e.getTimelineForEvent(t))!==null&&p!==void 0?p:k}else{for(var T,x=e.thread,C=yield n.fetchRelations(e.room.roomId,x.id,vt.name,null,{dir:Ge.Backward,from:a.start,recurse:u||void 0}),N=[],F=a.end;F;){var H,ie=yield n.fetchRelations(e.room.roomId,x.id,vt.name,null,{dir:Ge.Forward,from:F,recurse:u||void 0});F=(H=ie.next_batch)!==null&&H!==void 0?H:null,N.push(...ie.chunk)}var $=[...N.reverse().map(l),c,...C.chunk.map(l)];for(var X of $){var oe;yield(oe=e.thread)===null||oe===void 0?void 0:oe.processEvent(X)}var re=e.getLiveTimeline();if(re.getState(Ee.BACKWARDS).setUnknownStateEvents(a.state.map(l)),e.addEventsToTimeline($,!0,re,null),!C.next_batch){var ae=yield n.fetchRoomEvent(e.room.roomId,x.id);e.addEventsToTimeline([l(ae)],!0,re,null)}return re.setPaginationToken((T=C.next_batch)!==null&&T!==void 0?T:null,Ge.Backward),re.setPaginationToken(null,Ge.Forward),n.processAggregatedTimelineEvents(e.room,$),re}}})()}getLatestTimeline(e){var t=this;return _(function*(){if(!t.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!e.room)throw new Error("getLatestTimeline only supports room timelines");var n;if(e.threadListType!==null){var i,o=yield t.createThreadListMessagesRequest(e.room.roomId,null,1,Ge.Backward,e.threadListType,e.getFilter());n=(i=o.chunk)===null||i===void 0?void 0:i[0]}else if(e.thread&&Et.hasServerSideSupport){var s,a=t.canSupport.get(dr.RelationsRecursion)!==lr.Unsupported,l=yield t.fetchRelations(e.room.roomId,e.thread.id,vt.name,null,{dir:Ge.Backward,limit:1,recurse:a||void 0});n=(s=l.chunk)===null||s===void 0?void 0:s[0]}else{var c,u,d=Se("/rooms/$roomId/messages",{$roomId:e.room.roomId}),f={dir:"b"};(c=t.clientOpts)!==null&&c!==void 0&&c.lazyLoadMembers&&(f.filter=JSON.stringify(gn.LAZY_LOADING_MESSAGES_FILTER));var p=yield t.http.authedRequest(Z.Get,d,f);n=(u=p.chunk)===null||u===void 0?void 0:u[0]}if(!n)throw new Error("No message returned when trying to construct getLatestTimeline");return t.getEventTimeline(e,n.event_id)})()}createMessagesRequest(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,o=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0,a=Se("/rooms/$roomId/messages",{$roomId:e}),l={limit:i.toString(),dir:o};t&&(l.from=t);var c=null;if((n=this.clientOpts)!==null&&n!==void 0&&n.lazyLoadMembers&&(c=Object.assign({},gn.LAZY_LOADING_MESSAGES_FILTER)),s){var u;c=c||{},Object.assign(c,(u=s.getRoomTimelineFilterComponent())===null||u===void 0?void 0:u.toJSON())}return c&&(l.filter=JSON.stringify(c)),this.http.authedRequest(Z.Get,a,l)}createThreadListMessagesRequest(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Ge.Backward,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:di.All,a=arguments.length>5?arguments[5]:void 0,l=Se("/rooms/$roomId/threads",{$roomId:e}),c={limit:i.toString(),dir:o,include:xN(s)};t&&(c.from=t);var u={};if((n=this.clientOpts)!==null&&n!==void 0&&n.lazyLoadMembers&&(u=Cr({},gn.LAZY_LOADING_MESSAGES_FILTER)),a){var d;u=Cr(Cr({},u),(d=a.getRoomTimelineFilterComponent())===null||d===void 0?void 0:d.toJSON())}Object.keys(u).length&&(c.filter=JSON.stringify(u));var f={prefix:Et.hasServerSideListSupport===Vr.Stable?Ot.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(Z.Get,l,c,void 0,f).then(p=>{var h;return Cr(Cr({},p),{},{chunk:(h=p.chunk)===null||h===void 0?void 0:h.reverse(),start:p.prev_batch,end:p.next_batch})})}paginateEventTimeline(e,t){var n=this,i=e.getTimelineSet()===this.notifTimelineSet,o=this.getRoom(e.getRoomId()),s=e.getTimelineSet().threadListType,a=e.getTimelineSet().thread;t=t||{};var l=t.backwards||!1;if(i&&!l)throw new Error("paginateNotifTimeline can only paginate backwards");var c=l?Ee.BACKWARDS:Ee.FORWARDS,u=e.getPaginationToken(c),d=e.paginationRequests[c];if(d)return d;var f,p,h;if(i){var m;f="/notifications",p={limit:((m=t.limit)!==null&&m!==void 0?m:30).toString(),only:"highlight"},u&&u!=="end"&&(p.from=u),h=this.http.authedRequest(Z.Get,f,p).then(function(){var k=_(function*(O){var T=O.next_token,x=[];O.notifications=O.notifications.filter(mi);for(var C=0;C<O.notifications.length;C++){var N=O.notifications[C],F=n.getEventMapper()(N.event);n.getPushDetailsForEvent(F,!0),F.event.room_id=N.room_id,x[C]=F}var H=e.getTimelineSet();return H.addEventsToTimeline(x,l,e,T),n.processAggregatedTimelineEvents(H.room,x),l&&!O.next_token&&e.setPaginationToken(null,c),!!O.next_token});return function(O){return k.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}else if(s!==null){if(!o)throw new Error("Unknown room "+e.getRoomId());if(!Et.hasServerSideFwdPaginationSupport&&c===Ge.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");h=this.createThreadListMessagesRequest(e.getRoomId(),u,t.limit,c,s,e.getFilter()).then(k=>{if(k.state){var O=e.getState(c),T=k.state.filter(mi).map(this.getEventMapper());O.setUnknownStateEvents(T)}var x=k.end,C=k.chunk.filter(mi).map(this.getEventMapper()),N=e.getTimelineSet();return N.addEventsToTimeline(C,l,e,x),this.processAggregatedTimelineEvents(o,C),this.processThreadRoots(o,C,l),l&&k.end==k.start&&e.setPaginationToken(null,c),k.end!==k.start}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}else if(a){var w,g,b=this.getRoom((w=e.getRoomId())!==null&&w!==void 0?w:void 0);if(!b)throw new Error("Unknown room "+e.getRoomId());var R=this.canSupport.get(dr.RelationsRecursion)!==lr.Unsupported;h=this.fetchRelations((g=e.getRoomId())!==null&&g!==void 0?g:"",a.id,null,null,{dir:c,limit:t.limit,from:u??void 0,recurse:R||void 0}).then(function(){var k=_(function*(O){var T=n.getEventMapper(),x=O.chunk.filter(mi).filter(oy(a.id)).map(T);for(var C of x.slice().reverse()){yield a==null?void 0:a.processEvent(C);var N=C.getSender();(!l||(a==null?void 0:a.getEventReadUpTo(N))===null)&&b.addLocalEchoReceipt(N,C,Jr.Read)}var F=O.next_batch,H=e.getTimelineSet();if(H.addEventsToTimeline(x,l,e,F??null),!F&&l){var ie,$,X=(ie=a.rootEvent)!==null&&ie!==void 0?ie:T(yield n.fetchRoomEvent(($=e.getRoomId())!==null&&$!==void 0?$:"",a.id));H.addEventsToTimeline([X],!0,e,null)}return n.processAggregatedTimelineEvents(H.room,x),l&&!F&&e.setPaginationToken(null,c),!!F});return function(O){return k.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}else{if(!o)throw new Error("Unknown room "+e.getRoomId());h=this.createMessagesRequest(e.getRoomId(),u,t.limit,c,e.getFilter()).then(k=>{if(k.state){var O=e.getState(c),T=k.state.filter(mi).map(this.getEventMapper());O.setUnknownStateEvents(T)}var x=k.end,C=k.chunk.filter(mi).map(this.getEventMapper()),N=e.getTimelineSet(),[F,,H]=o.partitionThreadedEvents(C);N.addEventsToTimeline(F,l,e,x),this.processAggregatedTimelineEvents(o,F),this.processThreadRoots(o,F.filter($=>$.getServerAggregatedRelation(vt.name)),!1),H.forEach($=>o.relations.aggregateChildEvent($));var ie=k.end===void 0||k.end===k.start;return l&&ie&&e.setPaginationToken(null,c),!ie}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}return h}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;return(t=this.peekSync)===null||t===void 0||t.stopPeeking(),this.peekSync=new Mu(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,n)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){var n=this.sendStateEvent(e,V.RoomGuestAccess,{guest_access:t.allowJoin?av.CanJoin:av.Forbidden},""),i=Promise.resolve();return t.allowRead&&(i=this.sendStateEvent(e,V.RoomHistoryVisibility,{history_visibility:Aw.WorldReadable},"")),Promise.all([i,n]).then()}requestRegisterEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestRegisterMsisdnToken(e,t,n,i,o){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:o})}requestAdd3pidEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestAdd3pidMsisdnToken(e,t,n,i,o){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:o})}requestPasswordEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestPasswordMsisdnToken(e,t,n,i,o){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:o})}requestTokenFromEndpoint(e,t){var n=this;return _(function*(){var i=Object.assign({},t);return n.http.request(Z.Post,e,void 0,i)})()}getRoomPushRule(e,t){if(this.pushRules){var n;return(n=this.pushRules[e])===null||n===void 0||(n=n.room)===null||n===void 0?void 0:n.find(i=>i.rule_id===t)}else throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,n){var i,o=!1,s=this.getRoomPushRule(e,t);if(s!=null&&s.actions.includes(ks.DontNotify)&&(o=!0),!n)o&&(i=this.deletePushRule(e,Er.RoomSpecific,s.rule_id));else if(!s)i=this.addPushRule(e,Er.RoomSpecific,t,{actions:[ks.DontNotify]});else if(!o){var a=Gs();this.deletePushRule(e,Er.RoomSpecific,s.rule_id).then(()=>{this.addPushRule(e,Er.RoomSpecific,t,{actions:[ks.DontNotify]}).then(()=>{a.resolve()}).catch(l=>{a.reject(l)})}).catch(l=>{a.reject(l)}),i=a.promise}if(i)return new Promise((l,c)=>{i.then(()=>{this.getPushRules().then(u=>{this.pushRules=u,l()}).catch(u=>{c(u)})}).catch(u=>{this.getPushRules().then(d=>{this.pushRules=d,c(u)}).catch(d=>{c(u)})})})}searchMessageText(e){var t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){var t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:SN.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},n={_query:t,results:[],highlights:[]};return this.search({body:t}).then(i=>this.processRoomEventsSearch(n,i))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;var t={body:e._query,next_batch:e.next_batch},n=this.search(t,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=n,n}processRoomEventsSearch(e,t){var n,i,o=t.search_categories.room_events;e.count=o.count,e.next_batch=o.next_batch;var s=new Set(o.highlights);e.highlights.forEach(h=>{s.add(h)}),e.highlights=Array.from(s);for(var a=this.getEventMapper(),l=(n=(i=o.results)===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0,c=0;c<l;c++){var u=_m.fromJson(o.results[c],a),d=this.getRoom(u.context.getEvent().getRoomId());if(d)for(var f of u.context.getTimeline()){var p=d.getMember(f.getSender());!f.sender&&p&&(f.sender=p)}e.results.push(u)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;var e=new Mu(this,this.clientOpts,this.buildSyncApiOptions());return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then(()=>{this.logger.debug("Marking success of sync left room request"),this.syncedLeftRooms=!0}).finally(()=>{this.syncLeftRoomsPromise=void 0}),this.syncLeftRoomsPromise}createFilter(e){var t=Se("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(Z.Post,t,void 0,e).then(n=>{var i=gn.fromJson(this.credentials.userId,n.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,t,n){if(n){var i=this.store.getFilter(e,t);if(i)return Promise.resolve(i)}var o=Se("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(Z.Get,o).then(s=>{var a=gn.fromJson(e,t,s);return this.store.storeFilter(a),a})}getOrCreateFilter(e,t){var n=this;return _(function*(){var i=n.store.getFilterIdByName(e),o;if(i){try{var s=yield n.getFilter(n.credentials.userId,i,!0);if(s){var a=s.getDefinition(),l=t.getDefinition();Fa(a,l)&&(o=i)}}catch(u){if(u.errcode!=="M_UNKNOWN"&&u.errcode!=="M_NOT_FOUND")throw u}o||n.store.setFilterIdByName(e,void 0)}if(o)return o;var c=yield n.createFilter(t.getDefinition());return n.store.setFilterIdByName(e,c.filterId),c.filterId})()}getOpenIdToken(){var e=Se("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(Z.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(Z.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}checkTurnServers(){var e=this;return _(function*(){if(e.canSupportVoip){var t=!1,n=e.turnServersExpiry-Date.now();if(n>xk)e.logger.debug("TURN creds are valid for another "+n+" ms: not fetching new ones."),t=!0;else{e.logger.debug("Fetching new TURN credentials");try{var i=yield e.turnServer();if(i.uris){e.logger.debug("Got TURN URIs: "+i.uris+" refresh in "+i.ttl+" secs");var o={urls:i.uris,username:i.username,credential:i.password};e.turnServers=[o],e.turnServersExpiry=Date.now()+i.ttl*1e3,t=!0,e.emit(Te.TurnServers,e.turnServers)}}catch(s){e.logger.error("Failed to get TURN URIs",s),s.httpStatus===403?(e.logger.info("TURN access unavailable for this account: stopping credentials checks"),e.checkTurnServersIntervalID!==null&&globalThis.clearInterval(e.checkTurnServersIntervalID),e.checkTurnServersIntervalID=void 0,e.emit(Te.TurnServersError,s,!0)):e.emit(Te.TurnServersError,s,!1)}}return t}})()}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){var e=Se("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(Z.Get,e,void 0,void 0,{prefix:""}).then(t=>t.admin)}whoisSynapseUser(e){var t=Se("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(Z.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){var t=Se("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(Z.Post,t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e=this;return _(function*(){var t;e.clientWellKnownPromise=Ke.getRawClientConfig((t=e.getDomain())!==null&&t!==void 0?t:void 0),e.clientWellKnown=yield e.clientWellKnownPromise,e.emit(Te.ClientWellKnown,e.clientWellKnown)})()}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){var e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter(n=>{var[i,o]=n;return e.includes(typeof o)}).reduce((n,i)=>{var[o,s]=i;return n[o]=s,n},{});return this.store.storeClientOptions(t)}_unstable_getSharedRooms(e){var t=this;return _(function*(){var n=yield t.doesServerSupportUnstableFeature(TN),i=yield t.doesServerSupportUnstableFeature(RN),o=yield t.doesServerSupportUnstableFeature(CN);if(!n&&!i&&!o)throw Error("Server does not support the Mutual Rooms API");var s,a;o?(s="/uk.half-shot.msc2666/user/mutual_rooms",a={user_id:e}):(s=Se("/uk.half-shot.msc2666/user/".concat(i?"mutual_rooms":"shared_rooms","/$userId"),{$userId:e}),a={});var l=[],c=null;do{var u={};c!=null&&o&&(u.batch_token=c);var d=yield t.http.authedRequest(Z.Get,s,Cr(Cr({},a),u),void 0,{prefix:Ot.Unstable});l.push(...d.joined),d.next_batch_token!==void 0?c=d.next_batch_token:c=null}while(c!=null);return l})()}getVersions(){var e=this;return _(function*(){if(e.serverVersionsPromise)return e.serverVersionsPromise;e.serverVersionsPromise=e.http.authedRequest(Z.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(n=>{throw e.serverVersionsPromise=void 0,n});var t=yield e.serverVersionsPromise;return e.canSupport=yield HH(t),e.serverVersionsPromise})()}isVersionSupported(e){var t=this;return _(function*(){var{versions:n}=yield t.getVersions();return n&&n.includes(e)})()}doesServerSupportUnstableFeature(e){var t=this;return _(function*(){var n=yield t.getVersions();if(!n)return!1;var i=n.unstable_features;return i&&!!i[e]})()}doesServerForceEncryptionForPreset(e){var t=this;return _(function*(){var n=yield t.getVersions();if(!n)return!1;var i=n.unstable_features,o=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return i&&!!i["io.element.e2ee_forced.".concat(o)]})()}doesServerSupportThread(){var e=this;return _(function*(){if(yield e.isVersionSupported("v1.4"))return{threads:Vr.Stable,list:Vr.Stable,fwdPagination:Vr.Stable};try{var[t,n,i,o,s,a]=yield Promise.all([e.doesServerSupportUnstableFeature("org.matrix.msc3440"),e.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),e.doesServerSupportUnstableFeature("org.matrix.msc3856"),e.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),e.doesServerSupportUnstableFeature("org.matrix.msc3715"),e.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:Qh(n,t),list:Qh(o,i),fwdPagination:Qh(a,s)}}catch{return{threads:Vr.None,list:Vr.None,fwdPagination:Vr.None}}})()}hasLazyLoadMembersEnabled(){var e;return!!((e=this.clientOpts)!==null&&e!==void 0&&e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,n,i){var o=arguments,s=this;return _(function*(){var a,l,c=o.length>4&&o[4]!==void 0?o[4]:{dir:Ge.Backward},u=i?s.getEncryptedIfNeededEventType(e,i):null,[d,f]=yield Promise.all([s.fetchRoomEvent(e,t),s.fetchRelations(e,t,n,u,c)]),p=s.getEventMapper(),h=d?p(d):void 0,m=f.chunk.map(p);if(u===V.RoomMessageEncrypted){var w=h?m.concat(h):m;yield Promise.all(w.map(g=>s.decryptEventIfNeeded(g))),i!==null&&(m=m.filter(g=>g.getType()===i))}return h&&n===At.Replace&&(m=m.filter(g=>g.getSender()===h.getSender())),{originalEvent:h??null,events:m,nextBatch:(a=f.next_batch)!==null&&a!==void 0?a:null,prevBatch:(l=f.prev_batch)!==null&&l!==void 0?l:null}})()}getCrossSigningCacheCallbacks(){var e;return(e=this.crypto)===null||e===void 0?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return Ei(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.isCryptoEnabled()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case jb.IS:return this.http.getUrl("/terms",void 0,fo.V2,t);case jb.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(){var e,t,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return n&&((e=this.idBaseUrl)!==null&&e!==void 0&&e.startsWith("http://")||(t=this.idBaseUrl)!==null&&t!==void 0&&t.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=Wg(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}getRefreshToken(){var e;return(e=this.http.opts.refreshToken)!==null&&e!==void 0?e:null}setAccessToken(e){this.http.opts.accessToken=e,this.serverVersionsPromise=void 0}isLoggedIn(){return this.http.opts.accessToken!==void 0}makeTxnId(){return"m"+new Date().getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(Z.Get,"/register/available",{username:e}).then(t=>t.available).catch(t=>t.errcode==="M_USER_IN_USE"?!1:Promise.reject(t))}register(e,t,n,i,o,s,a){n&&(i.session=n);var l={auth:i,refresh_token:!0};return e!=null&&(l.username=e),t!=null&&(l.password=t),s!=null&&(l.guest_access_token=s),a!=null&&(l.inhibit_login=a),this.registerRequest(l)}registerGuest(){var{body:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.registerRequest(e||{},"guest")}registerRequest(e,t){var n={};return t&&(n.kind=t),this.http.request(Z.Post,"/register",n,e)}refreshToken(e){var t=n=>this.http.authedRequest(Z.Post,"/refresh",void 0,{refresh_token:e},{prefix:n,inhibitLogoutEmit:!0});return t(Ot.V3).catch(n=>{if(n.errcode==="M_UNRECOGNIZED")return t(Ot.V1);throw n})}loginFlows(){return this.http.request(Z.Get,"/login")}login(e,t){return this.http.authedRequest(Z.Post,"/login",void 0,Cr(Cr({},t),{},{type:e})).then(n=>(n.access_token&&n.user_id&&(this.http.opts.accessToken=n.access_token,this.credentials={userId:n.user_id}),n))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"sso",n=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,o="/login/"+t+"/redirect";n&&(o+="/"+n);var s={redirectUrl:e,[Y9.unstable]:i};return this.http.getUrl(o,s).href}loginWithToken(e){return this.login("m.login.token",{token:e})}logout(){var e=arguments,t=this;return _(function*(){var n,i=e.length>0&&e[0]!==void 0?e[0]:!1;if((n=t.crypto)!==null&&n!==void 0&&(n=n.backupManager)!==null&&n!==void 0&&n.getKeyBackupEnabled())try{for(;(yield t.crypto.backupManager.backupPendingKeys(200))>0;);}catch(o){t.logger.error("Key backup request failed when logging out. Some keys may be missing from backup",o)}return i&&(t.stopClient(),t.http.abort()),t.http.authedRequest(Z.Post,"/logout")})()}deactivateAccount(e,t){var n={};return e&&(n.auth=e),t!==void 0&&(n.erase=t),this.http.authedRequest(Z.Post,"/account/deactivate",void 0,n)}requestLoginToken(e){var t=this;return _(function*(){var n={auth:e};return t.http.authedRequest(Z.Post,"/login/get_token",void 0,n,{prefix:Ot.V1})})()}getFallbackAuthUrl(e,t){var n=Se("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(n,{session:t}).href}createRoom(e){var t=this;return _(function*(){var n,i=(e.invite_3pid||[]).filter(a=>!a.id_access_token);if(i.length>0&&(n=t.identityServer)!==null&&n!==void 0&&n.getAccessToken){var o=yield t.identityServer.getAccessToken();if(o)for(var s of i)s.id_access_token=o}return t.http.authedRequest(Z.Post,"/createRoom",void 0,e)})()}fetchRelations(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{dir:Ge.Backward},s=o;Et.hasServerSideFwdPaginationSupport===Vr.Experimental&&(s=eC("dir","org.matrix.msc3715.dir",s)),this.canSupport.get(dr.RelationsRecursion)===lr.Unstable&&(s=eC("recurse","org.matrix.msc3981.recurse",s));var a=lb(s),l="/rooms/$roomId/relations/$eventId";n!==null?(l+="/$relationType",i!==null&&(l+="/$eventType")):i!==null&&(this.logger.warn("eventType: ".concat(i,` ignored when fetching
284
+ relations as relationType is null`)),i=null);var c=Se(l+"?"+a,{$roomId:e,$eventId:t,$relationType:n,$eventType:i});return this.http.authedRequest(Z.Get,c,void 0,void 0,{prefix:Ot.V1})}roomState(e){var t=Se("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(Z.Get,t)}fetchRoomEvent(e,t){var n=Se("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(Z.Get,n)}members(e,t,n,i){var o={};t&&(o.membership=t),n&&(o.not_membership=n),i&&(o.at=i);var s=lb(o),a=Se("/rooms/$roomId/members?"+s,{$roomId:e});return this.http.authedRequest(Z.Get,a)}upgradeRoom(e,t){var n=Se("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(Z.Post,n,void 0,{new_version:t})}getStateEvent(e,t,n){var i={$roomId:e,$eventType:t,$stateKey:n},o=Se("/rooms/$roomId/state/$eventType",i);return n!==void 0&&(o=Se(o+"/$stateKey",i)),this.http.authedRequest(Z.Get,o)}sendStateEvent(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"",o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},s={$roomId:e,$eventType:t,$stateKey:i},a=Se("/rooms/$roomId/state/$eventType",s);return i!==void 0&&(a=Se(a+"/$stateKey",s)),this.http.authedRequest(Z.Put,a,void 0,n,o)}roomInitialSync(e,t){var n,i=Se("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(Z.Get,i,{limit:(n=t==null?void 0:t.toString())!==null&&n!==void 0?n:"30"})}setRoomReadMarkersHttpRequest(e,t,n,i){var o=this;return _(function*(){var s=Se("/rooms/$roomId/read_markers",{$roomId:e}),a={[Jr.FullyRead]:t,[Jr.Read]:n};return((yield o.doesServerSupportUnstableFeature("org.matrix.msc2285.stable"))||(yield o.isVersionSupported("v1.4")))&&(a[Jr.ReadPrivate]=i),o.http.authedRequest(Z.Post,s,void 0,a)})()}getJoinedRooms(){var e=Se("/joined_rooms",{});return this.http.authedRequest(Z.Get,e)}getJoinedRoomMembers(e){var t=Se("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(Z.Get,t)}publicRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{server:t,limit:n,since:i}=e,o=aH(e,W9);if(Object.keys(o).length===0){var s={server:t,limit:n,since:i};return this.http.authedRequest(Z.Get,"/publicRooms",s)}else{var a={server:t},l=Cr({limit:n,since:i},o);return this.http.authedRequest(Z.Post,"/publicRooms",a,l)}}createAlias(e,t){var n=Se("/directory/room/$alias",{$alias:e}),i={room_id:t};return this.http.authedRequest(Z.Put,n,void 0,i)}deleteAlias(e){var t=Se("/directory/room/$alias",{$alias:e});return this.http.authedRequest(Z.Delete,t)}getLocalAliases(e){var t=Se("/rooms/$roomId/aliases",{$roomId:e}),n=Ot.V3;return this.http.authedRequest(Z.Get,t,void 0,void 0,{prefix:n})}getRoomIdForAlias(e){var t=Se("/directory/room/$alias",{$alias:e});return this.http.authedRequest(Z.Get,t)}getRoomDirectoryVisibility(e){var t=Se("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(Z.Get,t)}setRoomDirectoryVisibility(e,t){var n=Se("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(Z.Put,n,void 0,{visibility:t})}searchUserDirectory(e){var{term:t,limit:n}=e,i={search_term:t};return n!==void 0&&(i.limit=n),this.http.authedRequest(Z.Post,"/user_directory/search",void 0,i)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){var n=t?Se("/profile/$userId/$info",{$userId:e,$info:t}):Se("/profile/$userId",{$userId:e});return this.http.authedRequest(Z.Get,n)}doesServerSupportExtendedProfiles(){var e=this;return _(function*(){return e.doesServerSupportUnstableFeature(kN)})()}getExtendedProfileRequestPrefix(){var e=this;return _(function*(){return(yield e.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable"))?Ot.V3:"/_matrix/client/unstable/uk.tcpip.msc4133"})()}getExtendedProfile(e){var t=this;return _(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");return t.http.authedRequest(Z.Get,Se("/profile/$userId",{$userId:e}),void 0,void 0,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}getExtendedProfileProperty(e,t){var n=this;return _(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=yield n.http.authedRequest(Z.Get,Se("/profile/$userId/$key",{$userId:e,$key:t}),void 0,void 0,{prefix:yield n.getExtendedProfileRequestPrefix()});return i[t]})()}setExtendedProfileProperty(e,t){var n=this;return _(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=n.getUserId();yield n.http.authedRequest(Z.Put,Se("/profile/$userId/$key",{$userId:i,$key:e}),void 0,{[e]:t},{prefix:yield n.getExtendedProfileRequestPrefix()})})()}deleteExtendedProfileProperty(e){var t=this;return _(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var n=t.getUserId();yield t.http.authedRequest(Z.Delete,Se("/profile/$userId/$key",{$userId:n,$key:e}),void 0,void 0,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}patchExtendedProfile(e){var t=this;return _(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var n=t.getUserId();return t.http.authedRequest(Z.Patch,Se("/profile/$userId",{$userId:n}),{},e,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}setExtendedProfile(e){var t=this;return _(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var n=t.getUserId();yield t.http.authedRequest(Z.Put,Se("/profile/$userId",{$userId:n}),{},e,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}getThreePids(){return this.http.authedRequest(Z.Get,"/account/3pid")}addThreePidOnly(e){var t=this;return _(function*(){var n="/account/3pid/add";return t.http.authedRequest(Z.Post,n,void 0,e)})()}bindThreePid(e){var t=this;return _(function*(){var n="/account/3pid/bind";return t.http.authedRequest(Z.Post,n,void 0,e)})()}unbindThreePid(e,t){var n=this;return _(function*(){var i="/account/3pid/unbind",o={medium:e,address:t,id_server:n.getIdentityServerUrl(!0)};return n.http.authedRequest(Z.Post,i,void 0,o)})()}deleteThreePid(e,t){var n="/account/3pid/delete";return this.http.authedRequest(Z.Post,n,void 0,{medium:e,address:t})}setPassword(e,t,n){var i="/account/password",o={auth:e,new_password:t,logout_devices:n};return this.http.authedRequest(Z.Post,i,void 0,o)}getDevices(){return this.http.authedRequest(Z.Get,"/devices")}getDevice(e){var t=Se("/devices/$device_id",{$device_id:e});return this.http.authedRequest(Z.Get,t)}setDeviceDetails(e,t){var n=Se("/devices/$device_id",{$device_id:e});return this.http.authedRequest(Z.Put,n,void 0,t)}deleteDevice(e,t){var n=Se("/devices/$device_id",{$device_id:e}),i={};return t&&(i.auth=t),this.http.authedRequest(Z.Delete,n,void 0,i)}deleteMultipleDevices(e,t){var n={devices:e};t&&(n.auth=t);var i="/delete_devices";return this.http.authedRequest(Z.Post,i,void 0,n)}getPushers(){var e=this;return _(function*(){var t=yield e.http.authedRequest(Z.Get,"/pushers");return(yield e.doesServerSupportUnstableFeature("org.matrix.msc3881"))||(t.pushers=t.pushers.map(n=>(n.hasOwnProperty(bb.name)||(n[bb.name]=!0),n))),t})()}setPusher(e){var t="/pushers/set";return this.http.authedRequest(Z.Post,t,void 0,e)}removePusher(e,t){var n="/pushers/set",i={pushkey:e,app_id:t,kind:null};return this.http.authedRequest(Z.Post,n,void 0,i)}setLocalNotificationSettings(e,t){var n="".concat(dD.name,".").concat(e);return this.setAccountData(n,t)}getPushRules(){return this.http.authedRequest(Z.Get,"/pushrules/").then(e=>(this.setPushRules(e),this.pushRules))}setPushRules(e){this.pushRules=hi.rewriteDefaultRules(e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,n,i){var o=Se("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Put,o,void 0,i)}deletePushRule(e,t,n){var i=Se("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Delete,i)}setPushRuleEnabled(e,t,n,i){var o=Se("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Put,o,void 0,{enabled:i})}setPushRuleActions(e,t,n,i){var o=Se("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Put,o,void 0,{actions:i})}search(e,t){var{body:n,next_batch:i}=e,o={};return i&&(o.next_batch=i),this.http.authedRequest(Z.Post,"/search",o,n,{abortSignal:t})}uploadKeysRequest(e,t){return this.http.authedRequest(Z.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(Z.Post,"/keys/signatures/upload",void 0,e)}downloadKeysForUsers(e){var{token:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n={device_keys:{}};return t!==void 0&&(n.token=t),e.forEach(i=>{n.device_keys[i]=[]}),this.http.authedRequest(Z.Post,"/keys/query",void 0,n)}claimOneTimeKeys(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"signed_curve25519",n=arguments.length>2?arguments[2]:void 0,i={};t===void 0&&(t="signed_curve25519");for(var[o,s]of e){var a=i[o]||{};Xi(i,o,a),Xi(a,s,t)}var l={one_time_keys:i};n&&(l.timeout=n);var c="/keys/claim";return this.http.authedRequest(Z.Post,c,void 0,l)}getKeyChanges(e,t){var n={from:e,to:t};return this.http.authedRequest(Z.Get,"/keys/changes",n)}uploadDeviceSigningKeys(e,t){var n=Object.assign({},t);return e&&Object.assign(n,{auth:e}),this.http.authedRequest(Z.Post,"/keys/device_signing/upload",void 0,n,{prefix:Ot.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");var t=this.http.getUrl("/account/register",void 0,fo.V2,this.idBaseUrl);return this.http.requestOtherUrl(Z.Post,t,e)}requestEmailToken(e,t,n,i,o){var s={client_secret:t,email:e,send_attempt:n==null?void 0:n.toString()};return i&&(s.next_link=i),this.http.idServerRequest(Z.Post,"/validate/email/requestToken",s,fo.V2,o)}requestMsisdnToken(e,t,n,i,o,s){var a={client_secret:n,country:e,phone_number:t,send_attempt:i==null?void 0:i.toString()};return o&&(a.next_link=o),this.http.idServerRequest(Z.Post,"/validate/msisdn/requestToken",a,fo.V2,s)}submitMsisdnToken(e,t,n,i){var o={sid:e,client_secret:t,token:n};return this.http.idServerRequest(Z.Post,"/validate/msisdn/submitToken",o,fo.V2,i??void 0)}submitMsisdnTokenOtherUrl(e,t,n,i){var o={sid:t,client_secret:n,token:i};return this.http.requestOtherUrl(Z.Post,e,o)}getIdentityHashDetails(e){return this.http.idServerRequest(Z.Get,"/hash_details",void 0,fo.V2,e)}identityHashedLookup(e,t){var n=this;return _(function*(){var i={},o=yield n.getIdentityHashDetails(t);if(!o||!o.lookup_pepper||!o.algorithms)throw new Error("Unsupported identity server: bad response");i.pepper=o.lookup_pepper;var s={};if(o.algorithms.includes("sha256"))i.addresses=yield Promise.all(e.map(function(){var f=_(function*(p){var h=p[0].toLowerCase(),m=p[1].toLowerCase(),w=yield wN("".concat(h," ").concat(m," ").concat(i.pepper)),g=mm(w);return s[g]=p[0],g});return function(p){return f.apply(this,arguments)}}())),i.algorithm="sha256";else if(o.algorithms.includes("none"))i.addresses=e.map(f=>{var p=f[0].toLowerCase(),h=f[1].toLowerCase(),m="".concat(p," ").concat(h);return s[m]=f[0],m}),i.algorithm="none";else throw new Error("Unsupported identity server: unknown hash algorithm");var a=yield n.http.idServerRequest(Z.Post,"/lookup",i,fo.V2,t);if(!(a!=null&&a.mappings))return[];var l=[];for(var c of Object.keys(a.mappings)){var u=a.mappings[c],d=s[c];if(!d)throw new Error("Identity server returned more results than expected");l.push({address:d,mxid:u})}return l})()}lookupThreePid(e,t,n){var i=this;return _(function*(){var o=yield i.identityHashedLookup([[t,e]],n),s=o.find(l=>l.address===t);if(!s)return{};var a={address:t,medium:e,mxid:s.mxid};return a})()}bulkLookupThreePids(e,t){var n=this;return _(function*(){var i=yield n.identityHashedLookup(e.map(l=>[l[1],l[0]]),t),o=[],s=function*(c){var u=e.find(d=>d[1]===c.address);if(!u)throw new Error("Identity sever returned unexpected results");o.push([u[0],c.address,c.mxid])};for(var a of i)yield*s(a);return{threepids:o}})()}getIdentityAccount(e){return this.http.idServerRequest(Z.Get,"/account",void 0,fo.V2,e)}sendToDevice(e,t,n){var i=Se("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:n||this.makeTxnId()}),o={messages:ms(t)},s=new Map;for(var[a,l]of t)s.set(a,Array.from(l.keys()));return this.logger.debug("PUT ".concat(i),s),this.http.authedRequest(Z.Put,i,void 0,o)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(Z.Get,"/thirdparty/protocols").then(e=>{if(!e||typeof e!="object")throw new Error("/thirdparty/protocols did not return an object: ".concat(e));return e})}getThirdpartyLocation(e,t){var n=Se("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(Z.Get,n,t)}getThirdpartyUser(e,t){var n=Se("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(Z.Get,n,t)}getTerms(e,t){var n=this.termsUrlForService(e,t);return this.http.requestOtherUrl(Z.Get,n)}agreeToTerms(e,t,n,i){var o=this.termsUrlForService(e,t),s={Authorization:"Bearer "+n};return this.http.requestOtherUrl(Z.Post,o,{user_accepts:i},{headers:s})}reportEvent(e,t,n,i){var o=Se("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(Z.Post,o,void 0,{score:n,reason:i})}getRoomHierarchy(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,o=arguments.length>4?arguments[4]:void 0,s=Se("/rooms/$roomId/hierarchy",{$roomId:e}),a={suggested_only:String(i),max_depth:n==null?void 0:n.toString(),from:o,limit:t==null?void 0:t.toString()};return this.http.authedRequest(Z.Get,s,a,void 0,{prefix:Ot.V1}).catch(l=>{if(l.errcode==="M_UNRECOGNIZED")return this.http.authedRequest(Z.Get,s,a,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw l})}unstableCreateFileTree(e){var t=this;return _(function*(){var{room_id:n}=yield t.createRoom({name:e,preset:Mw.PrivateChat,power_level_content_override:Cr(Cr({},I9),{},{users:{[t.getUserId()]:100}}),creation_content:{[Xp]:Yl.Space},initial_state:[{type:mb.name,state_key:yb.name,content:{[gb.name]:!0}},{type:V.RoomEncryption,state_key:"",content:{algorithm:bn}}]});return new _k(t,n)})()}unstableGetFileTreeSpace(e){var t,n,i=this.getRoom(e);if((i==null?void 0:i.getMyMembership())!==Be.Join)return null;var o=i.currentState.getStateEvents(V.RoomCreate,""),s=i.currentState.getStateEvents(mb.name,yb.name);if(!o)throw new Error("Expected single room create event");return!(s!=null&&(t=s.getContent())!==null&&t!==void 0&&t[gb.name])||((n=o.getContent())===null||n===void 0?void 0:n[Xp])!==Yl.Space?null:new _k(this,e)}slidingSync(e,t,n){var i={};e.pos&&(i.pos=e.pos,delete e.pos),e.timeout&&(i.timeout=e.timeout,delete e.timeout);var o=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(Z.Post,"/sync",i,e,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:t,localTimeoutMs:o,abortSignal:n})}supportsThreads(){var e;return((e=this.clientOpts)===null||e===void 0?void 0:e.threadSupport)||!1}supportsIntentionalMentions(){return this.canSupport.get(dr.IntentionalMentions)!==lr.Unsupported}getRoomSummary(e,t){var n=this;return _(function*(){var i={prefix:"/_matrix/client/unstable/im.nheko.summary"};try{var o=Se("/summary/$roomid",{$roomid:e});return yield n.http.authedRequest(Z.Get,o,{via:t},void 0,i)}catch(a){if(a instanceof hr&&a.errcode==="M_UNRECOGNIZED"){var s=Se("/rooms/$roomid/summary",{$roomid:e});return yield n.http.authedRequest(Z.Get,s,{via:t},void 0,i)}else throw a}})()}processThreadEvents(e,t,n){e.processThreadedEvents(t,n)}processThreadRoots(e,t,n){this.supportsThreads()&&e.processThreadRoots(t,n)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){t!=null&&t.length&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}whoami(){var e=this;return _(function*(){return e.http.authedRequest(Z.Get,"/account/whoami")})()}timestampToEvent(e,t,n){var i=this;return _(function*(){var o=Se("/rooms/$roomId/timestamp_to_event",{$roomId:e}),s={ts:t.toString(),dir:n};try{return yield i.http.authedRequest(Z.Get,o,s,void 0,{prefix:Ot.V1})}catch(a){if(a.errcode==="M_UNRECOGNIZED"&&(a.httpStatus===400||a.httpStatus===404||a.httpStatus===405))return yield i.http.authedRequest(Z.Get,o,s,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw a}})()}getAuthIssuer(){var e=this;return _(function*(){return e.http.request(Z.Get,"/auth_issuer",void 0,void 0,{prefix:Ot.Unstable+"/org.matrix.msc2965"})})()}}v($c,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY");function Ok(r){return Object.fromEntries(Object.entries(r).map(e=>{var[t,n]=e;return["".concat($i,".").concat(t),n]}))}function IN(r,e){var t,n=r.getUserId(),i=e.getId(),o=r.getRoom(e.getRoomId());if(!(!o||!n||!i)){if(!o.findEventById(i)){S.info("Decrypted event ".concat(e.getId()," is not in room ").concat(o.roomId,": ignoring"));return}var s=!!e.threadRootId&&!e.isThreadRoot,a;if(s){var l=o.getThread(e.threadRootId);a=l?l.hasUserReadEvent(n,i):!0}else a=o.hasUserReadEvent(n,i);if(!a){var c=r.getPushActionsForEvent(e,!0),u=!!(c!=null&&(t=c.tweaks)!==null&&t!==void 0&&t.highlight);if(u){var d=o.getUnreadCountForEventContext(it.Highlight,e)+1;s?o.setThreadUnreadNotificationCount(e.threadRootId,it.Highlight,d):o.setUnreadNotificationCount(it.Highlight,d)}var f=!!(c!=null&&c.notify);if(f){var p=o.getUnreadCountForEventContext(it.Total,e)+1;s?o.setThreadUnreadNotificationCount(e.threadRootId,it.Total,p):o.setUnreadNotificationCount(it.Total,p)}}}}function Tc(r){return Wd(r)?bf:r.threadRootId}function Wd(r){if(!r.threadRootId||r.isThreadRoot)return!0;if(!r.isRelation())return S.warn("Event is not a relation or a thread root, but still has a threadRootId! id=".concat(r.getId())),!0;if(r.isRelation(vt.name))return!1;var e=r.relationEventId===r.threadRootId;return e}function Pk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Mk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Pk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Pk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Xr=function(r){return r.New="Thread.new",r.Update="Thread.update",r.NewReply="Thread.newReply",r.ViewThread="Thread.viewThread",r.Delete="Thread.delete",r}({}),Vr=function(r){return r[r.None=0]="None",r[r.Experimental=1]="Experimental",r[r.Stable=2]="Stable",r}({});function Qh(r,e){return r?Vr.Stable:e?Vr.Experimental:Vr.None}class Et extends xD{constructor(e,t,n){var i,o;if(super(),i=this,this.id=e,this.rootEvent=t,v(this,"timelineSet",void 0),v(this,"_currentUserParticipated",!1),v(this,"reEmitter",void 0),v(this,"lastEvent",void 0),v(this,"replyCount",0),v(this,"lastPendingEvent",void 0),v(this,"pendingReplyCount",0),v(this,"room",void 0),v(this,"client",void 0),v(this,"pendingEventOrdering",void 0),v(this,"processRootEventPromise",void 0),v(this,"initialEventsFetched",!Et.hasServerSideSupport),v(this,"initalEventFetchProm",void 0),v(this,"replayEvents",[]),v(this,"onTimelineReset",_(function*(){yield i.processRootEventPromise,i.processRootEventPromise=void 0})),v(this,"onBeforeRedaction",(s,a)=>{s!=null&&s.isRelation(vt.name)&&this.room.eventShouldLiveIn(s).threadId===this.id&&s.getId()!==this.id&&!a.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(Xr.Update,this))}),v(this,"onRedaction",function(){var s=_(function*(a,l,c){if(c===i.id)if(i.replyCount<=0){for(var u of i.timeline)i.clearEventMetadata(u);i.lastEvent=i.rootEvent,i._currentUserParticipated=!1,i.emit(Xr.Delete,i)}else{var d;((d=i.lastEvent)===null||d===void 0?void 0:d.getId())===a.getAssociatedId()&&(yield i.processRootEventPromise,i.processRootEventPromise=void 0),yield i.updateThreadMetadata()}});return function(a,l,c){return s.apply(this,arguments)}}()),v(this,"onTimelineEvent",(s,a,l)=>{if(!l){var c=s.getSender();c&&a&&this.shouldSendLocalEchoReceipt(c,s)&&a.addLocalEchoReceipt(c,s,Jr.Read),s.getId()!==this.id&&s.isRelation(vt.name)&&this.replyCount++}this.onEcho(s,l??!1)}),v(this,"onLocalEcho",s=>{this.onEcho(s,!1)}),v(this,"onEcho",function(){var s=_(function*(a,l){a.threadRootId===i.id&&i.lastEvent!==a&&(yield i.updateThreadMetadata(),a.isRelation(vt.name)&&(l||(i.lastEvent=void 0,i.emit(Xr.NewReply,i,a))))});return function(a,l){return s.apply(this,arguments)}}()),this.setMaxListeners(1e3),!(n!=null&&n.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=n.room,this.client=n.client,this.pendingEventOrdering=(o=n.pendingEventOrdering)!==null&&o!==void 0?o:wc.Chronological,this.timelineSet=new Ul(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new Bc(this),this.reEmitter.reEmit(this.timelineSet,[fe.Timeline,fe.TimelineReset]),this.room.on(ot.BeforeRedaction,this.onBeforeRedaction),this.room.on(fe.Redaction,this.onRedaction),this.room.on(fe.LocalEchoUpdated,this.onLocalEcho),this.room.on(fe.TimelineReset,this.onTimelineReset),this.timelineSet.on(fe.Timeline,this.onTimelineEvent),this.processReceipts(n.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}fetchRootEvent(){var e=this;return _(function*(){try{var t=yield e.client.fetchRoomEvent(e.roomId,e.id),n=e.client.getEventMapper();e.rootEvent=n(t)}catch(i){S.error("Failed to fetch thread root to construct thread with",i)}yield e.processEvent(e.rootEvent)})()}static setServerSideSupport(e){Et.hasServerSideSupport=e,e!==Vr.Stable&&(tc.setPreferUnstable(!0),rc.setPreferUnstable(!0),vt.setPreferUnstable(!0))}static setServerSideListSupport(e){Et.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){Et.hasServerSideFwdPaginationSupport=e}shouldSendLocalEchoReceipt(e,t){var n,i=(n=this.client.canSupport.get(dr.RelationsRecursion))!==null&&n!==void 0?n:lr.Unsupported;if(i===lr.Unsupported){var o,s=(o=this.getReadReceiptForUserId(e))===null||o===void 0?void 0:o.eventId;if(s){var a=this.findEventById(s);if(a&&a.getTs()>t.getTs())return!1}}return!0}get roomState(){return this.room.getLiveTimeline().getState(Ee.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState})}insertEventIntoTimeline(e){var t=e.getId();t&&(this.findEventById(t)||this.timelineSet.insertEventIntoTimeline(e,this.liveTimeline,this.roomState))}addEvents(e,t){e.forEach(n=>this.addEvent(n,t,!1)),this.updateThreadMetadata()}addEvent(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;this.setEventMetadata(e);var i=this.lastReply(),o=!i||e.localTimestamp>=i.localTimestamp;if(!Et.hasServerSideSupport)this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e);else if(e.isRelation(At.Annotation)||e.isRelation(At.Replace)){this.addRelatedThreadEvent(e,t);return}else!t&&o?(this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e)):t?this.addEventToTimeline(e,t):this.insertEventIntoTimeline(e);e.getId()!==this.id&&e.isRelation(vt.name)&&!t&&o&&(this.lastEvent=void 0),n&&(this.emit(Xr.NewReply,this,e),this.updateThreadMetadata())}addRelatedThreadEvent(e,t){var n,i;if(this.initialEventsFetched){var s,a=(s=this.client.canSupport.get(dr.RelationsRecursion))!==null&&s!==void 0?s:lr.Unsupported;a===lr.Unsupported?this.insertEventIntoTimeline(e):this.addEventToTimeline(e,t)}else{var o;(o=this.replayEvents)===null||o===void 0||o.push(e)}(n=this.timelineSet.relations)===null||n===void 0||n.aggregateParentEvent(e),(i=this.timelineSet.relations)===null||i===void 0||i.aggregateChildEvent(e,this.timelineSet)}processEvent(e){var t=this;return _(function*(){e&&(t.setEventMetadata(e),yield t.fetchEditsWhereNeeded(e))})()}processReceipts(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];for(var{eventId:t,receiptType:n,userId:i,receipt:o,synthetic:s}of e)this.addReceiptToStructure(t,n,i,o,s)}getRootEventBundledRelationship(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.rootEvent;return e==null?void 0:e.getServerAggregatedRelation(vt.name)}processRootEvent(){var e=this;return _(function*(){var t=e.getRootEventBundledRelationship();if(Et.hasServerSideSupport&&t){e.replyCount=t.count,e._currentUserParticipated=!!t.current_user_participated;var n=e.client.getEventMapper();e.lastEvent=n(Mk(Mk({},t.latest_event),{},{room_id:e.roomId})),e.updatePendingReplyCount(),yield e.processEvent(e.lastEvent)}})()}updatePendingReplyCount(){var e=this.pendingEventOrdering===wc.Detached?this.room.getPendingEvents():this.events,t=e.filter(n=>{var i;return n.threadRootId===this.id&&n.isRelation(vt.name)&&n.status!==null&&n.getId()!==((i=this.lastEvent)===null||i===void 0?void 0:i.getId())});this.lastPendingEvent=t.length?t[t.length-1]:void 0,this.pendingReplyCount=t.length}resetLiveTimeline(e,t){var n=this;return _(function*(){var i=n.liveTimeline;n.timelineSet.resetLiveTimeline(e??void 0,t??void 0);var o=n.liveTimeline,s,a;if(e){var l=yield n.client.createMessagesRequest(n.roomId,e,1,Ge.Forward);s=l.end}if(t){var c=yield n.client.createMessagesRequest(n.roomId,t,1,Ge.Backward);a=c.start}if(t&&i.getPaginationToken(Ge.Forward)===t){var u;i.setPaginationToken((u=a)!==null&&u!==void 0?u:null,Ge.Forward)}if(e&&o.getPaginationToken(Ge.Backward)===e){var d;o.setPaginationToken((d=s)!==null&&d!==void 0?d:null,Ge.Backward)}})()}updateThreadFromRootEvent(){var e=this;return _(function*(){Et.hasServerSideSupport&&(!e.initialEventsFetched&&!e.lastEvent&&(yield e.processRootEvent()),yield e.fetchRootEvent()),yield e.processRootEvent()})()}updateThreadMetadata(){var e=this;return _(function*(){if(e.updatePendingReplyCount(),e.processRootEventPromise||(e.processRootEventPromise=e.updateThreadFromRootEvent()),yield e.processRootEventPromise,!e.initialEventsFetched)if(e.initalEventFetchProm)yield e.initalEventFetchProm;else try{e.timelineSet.resetLiveTimeline(),e.replyCount===0&&e.rootEvent?(e.timelineSet.addEventsToTimeline([e.rootEvent],!0,e.liveTimeline,null),e.liveTimeline.setPaginationToken(null,Ge.Backward)):(e.initalEventFetchProm=e.client.paginateEventTimeline(e.liveTimeline,{backwards:!0}),yield e.initalEventFetchProm),e.initialEventsFetched=!0;for(var t of e.replayEvents)e.addEvent(t,!1);e.replayEvents=null,e.emit(fe.TimelineReset,e.room,e.timelineSet,!0)}catch(n){S.error("Failed to load start of newly created thread: ",n),e.initialEventsFetched=!1}e.emit(Xr.Update,e)})()}fetchEditsWhereNeeded(){var e=arguments,t=this;return _(function*(){var n,i=(n=t.client.canSupport.get(dr.RelationsRecursion))!==null&&n!==void 0?n:lr.Unsupported;if(i===lr.Unsupported){for(var o=e.length,s=new Array(o),a=0;a<o;a++)s[a]=e[a];return Promise.all(s.filter(J9).map(function(){var l=_(function*(c){try{var u=yield t.client.relations(t.roomId,c.getId(),At.Replace,c.getType(),{limit:1});if(u.events.length){var d=u.events[0];c.makeReplaced(d),t.insertEventIntoTimeline(d)}}catch(f){S.error("Failed to load edits for encrypted thread event",f)}});return function(c){return l.apply(this,arguments)}}()))}})()}setEventMetadata(e){e&&(Ee.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){if(e){var t;e.setThread(void 0),(t=e.event)===null||t===void 0||(t=t.unsigned)===null||t===void 0||(t=t["m.relations"])===null||t===void 0||delete t[vt.name]}}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:i=>i.isRelation(vt.name),t=this.timeline.length-1;t>=0;t--){var n=this.timeline[t];if(e(n))return n}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,t;return(e=(t=this.lastPendingEvent)!==null&&t!==void 0?t:this.lastEvent)!==null&&e!==void 0?e:this.lastReply()}get timeline(){return this.events}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof pr}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(e,t){throw new Error("Unsupported function on the thread model")}getEventReadUpTo(e,t){var n=e===this.client.getUserId(),i=this.timeline[this.timeline.length-1];if(n&&i){var o=i.getTs()<this.room.getOldestThreadedReceiptTs(),s=i.getId();if(o&&s)return s}var a=super.getEventReadUpTo(e,t);if(i){var l=this.room.getLastUnthreadedReceiptFor(e);if(!l)return a;for(var c=((u=this.timeline)===null||u===void 0?void 0:u.length)-1;c>=0;--c){var u,d,f=this.timeline[c];if(f.getId()===a)return a;if(f.getTs()<l.ts)return(d=f.getId())!==null&&d!==void 0?d:a}}return a}hasUserReadEvent(e,t){if(e===this.client.getUserId()){var n,i,o,s,a,l,c=((n=(i=this.lastReply())===null||i===void 0?void 0:i.getTs())!==null&&n!==void 0?n:0)<this.room.getOldestThreadedReceiptTs(),u=(o=(s=this.room.getLastUnthreadedReceiptFor(e))===null||s===void 0?void 0:s.ts)!==null&&o!==void 0?o:0,d=((a=this===null||this===void 0||(l=this.lastReply())===null||l===void 0?void 0:l.getTs())!==null&&a!==void 0?a:0)<u;if(c||d)return!0}return this.room.hasUserReadEvent(e,t)}setUnread(e,t){return this.room.setThreadUnreadNotificationCount(this.id,e,t)}getLastUnthreadedReceiptFor(e){return this.room.getLastUnthreadedReceiptFor(e)}}v(Et,"hasServerSideSupport",Vr.None);v(Et,"hasServerSideListSupport",Vr.None);v(Et,"hasServerSideFwdPaginationSupport",Vr.None);function J9(r){return r.isEncrypted()&&(r.isRelation(vt.name)||r.isThreadRoot)}var tc=new im("related_by_senders","io.element.relation_senders"),rc=new im("related_by_rel_types","io.element.relation_types"),vt=new im("m.thread","io.element.thread"),di=function(r){return r[r.My=0]="My",r[r.All=1]="All",r}({});function xN(r){switch(r){case di.My:return"participated";default:return"all"}}var Ak=Object.freeze({visible:!0}),ot=function(r){return r.Decrypted="Event.decrypted",r.BeforeRedaction="Event.beforeRedaction",r.VisibilityChange="Event.visibilityChange",r.LocalEventIdReplaced="Event.localEventIdReplaced",r.Status="Event.status",r.Replaced="Event.replaced",r.RelationsCreated="Event.relationsCreated",r}({});class pr extends Tt{constructor(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.event=t,v(this,"pushDetails",{}),v(this,"_replacingEvent",null),v(this,"_localRedactionEvent",null),v(this,"_isCancelled",!1),v(this,"clearEvent",void 0),v(this,"visibility",Ak),v(this,"_hasCachedExtEv",!1),v(this,"_cachedExtEv",void 0),v(this,"_decryptionFailureReason",null),v(this,"senderCurve25519Key",null),v(this,"claimedEd25519Key",null),v(this,"forwardingCurve25519KeyChain",[]),v(this,"untrusted",null),v(this,"decryptionPromise",null),v(this,"retryDecryption",!1),v(this,"txnId",void 0),v(this,"thread",void 0),v(this,"threadId",void 0),v(this,"localTimestamp",void 0),v(this,"sender",null),v(this,"target",null),v(this,"status",null),v(this,"error",null),v(this,"forwardLooking",!0),v(this,"verificationRequest",void 0),v(this,"reEmitter",void 0),["state_key","type","sender","room_id","membership"].forEach(i=>{typeof t[i]=="string"&&(t[i]=$g(t[i]))}),["membership","avatar_url","displayname"].forEach(i=>{var o;typeof((o=t.content)===null||o===void 0?void 0:o[i])=="string"&&(t.content[i]=$g(t.content[i]))}),["rel_type"].forEach(i=>{var o;typeof((o=t.content)===null||o===void 0||(o=o["m.relates_to"])===null||o===void 0?void 0:o[i])=="string"&&(t.content["m.relates_to"][i]=$g(t.content["m.relates_to"][i]))}),this.txnId=t.txn_id;var n=this.getAge();this.localTimestamp=n!==void 0?Date.now()-n:(e=this.getTs())!==null&&e!==void 0?e:Date.now(),this.reEmitter=new Bc(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=ln.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){var e=Object.assign({},this.getContent());if(this.getWireType()===V.RoomMessageEncrypted)for(var[t,n]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||e[t]===void 0&&(e[t]=n);return Object.assign({},this.event,this.clearEvent,{content:e})}getId(){return this.event.event_id}getSender(){return this.event.sender}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(){var e=this.getRoomId();if(e){var t;return"id=".concat(this.getId()," type=").concat(this.getWireType()," sender=").concat(this.getSender()," room=").concat(e," ts=").concat((t=this.getDate())===null||t===void 0?void 0:t.toISOString())}else{var n=this.getContent()[en];return"msgid=".concat(n," type=").concat(this.getWireType()," sender=").concat(this.getSender())}}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 e;if(!this.isState()){var t=(e=this.getWireContent())===null||e===void 0?void 0:e["m.relates_to"];if((t==null?void 0:t.rel_type)===vt.name)return t.event_id;if(this.thread)return this.thread.id;if(this.threadId!==void 0)return this.threadId;var n=this.getUnsigned();if(typeof n[Qp.name]=="string")return n[Qp.name]}}get isThreadRoot(){if(this.isState())return!1;var e=this.getServerAggregatedRelation(vt.name);return!!e||this.threadRootId===this.getId()}get replyEventId(){var e;return(e=this.getWireContent()["m.relates_to"])===null||e===void 0||(e=e["m.in_reply_to"])===null||e===void 0?void 0:e.event_id}get relationEventId(){var e;return(e=this.getWireContent())===null||e===void 0||(e=e["m.relates_to"])===null||e===void 0?void 0:e.event_id}getPrevContent(){return this.getUnsigned().prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return this.event.state_key!==void 0}getMembershipAtEvent(){var e=this.getUnsigned();return fD.findIn(e)}makeEncrypted(e,t,n,i){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=n,this.claimedEd25519Key=i}isBeingDecrypted(){return this.decryptionPromise!=null}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){return this._decryptionFailureReason!==null}get decryptionFailureReason(){return this._decryptionFailureReason}get isEncryptedDisabledForUnverifiedDevices(){return this.decryptionFailureReason===Dt.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE}shouldAttemptDecryption(){return!(this.isRedacted()||this.isBeingDecrypted()||this.clearEvent||!this.isEncrypted())}attemptDecryption(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};if(!n.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");var o=n.clearEvent&&!n.isDecryptionFailure(),s=i.forceRedecryptIfUntrusted&&n.isKeySourceUntrusted();if(o&&!s)throw new Error("Attempt to decrypt event which has already been decrypted");return n.decryptionPromise?(S.log("Event ".concat(n.getId()," already being decrypted; queueing a retry")),n.retryDecryption=!0,n.decryptionPromise):(n.decryptionPromise=n.decryptionLoop(e,i),n.decryptionPromise)})()}cancelAndResendKeyRequest(e,t){var n=this.getWireContent();return e.requestRoomKey({algorithm:n.algorithm,room_id:this.getRoomId(),session_id:n.session_id,sender_key:n.sender_key},this.getKeyRequestRecipients(t),!0)}getKeyRequestRecipients(e){var t=[{userId:e,deviceId:"*"}];return t}decryptionLoop(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};for(yield Promise.resolve();;){n.retryDecryption=!1;var o=void 0;try{var s=yield e.decryptEvent(n);i.isRetry===!0&&S.info("Decrypted event on retry (".concat(n.getDetails(),")")),n.setClearData(s),n._decryptionFailureReason=null}catch(l){var a=l instanceof cr?l.detailedString:String(l);if(o=l,n.retryDecryption){S.log("Error decrypting event (".concat(n.getDetails(),"), but retrying: ").concat(a));continue}S.warn("Error decrypting event (".concat(n.getDetails(),"): ").concat(a)),n.setClearDataForDecryptionFailure(String(l)),n._decryptionFailureReason=l instanceof cr?l.code:Dt.UNKNOWN_ERROR}n.decryptionPromise=null,n.retryDecryption=!1,n.setPushDetails(),i.emit!==!1&&n.emit(ot.Decrypted,n,o);return}})()}setClearData(e){var t,n;this.clearEvent=e.clearEvent,this.senderCurve25519Key=(t=e.senderCurve25519Key)!==null&&t!==void 0?t:null,this.claimedEd25519Key=(n=e.claimedEd25519Key)!==null&&n!==void 0?n:null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.invalidateExtensibleEvent()}setClearDataForDecryptionFailure(e){this.clearEvent={type:V.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: ".concat(e," **")}},this.senderCurve25519Key=null,this.claimedEd25519Key=null,this.forwardingCurve25519KeyChain=[],this.untrusted=!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===V.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(e){this.event.unsigned=e}unmarkLocallyRedacted(){var e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=void 0),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit(ot.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var t,n,i=(t=e==null?void 0:e.visible)!==null&&t!==void 0?t:!0,o=(n=e==null?void 0:e.reason)!==null&&n!==void 0?n:null,s=!1;(this.visibility.visible!==i||!this.visibility.visible&&this.visibility.reason!==o)&&(s=!0),s&&(i?this.visibility=Ak:this.visibility=Object.freeze({visible:!1,reason:o}),this.emit(ot.VisibilityChange,this,i))}messageVisibility(){return this.visibility}makeRedacted(e,t){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(ot.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(var n in this.event)this.event.hasOwnProperty(n)&&!X9.has(n)&&delete this.event[n];this.isEncrypted()&&(this.clearEvent=void 0);var i=this.getType()in Dk?Dk[this.getType()]:{},o=this.getContent();for(var s in o)o.hasOwnProperty(s)&&!i[s]&&delete o[s];!this.isThreadRoot&&this.threadRootId&&this.threadRootId!==this.getId()&&(this.moveAllRelatedToMainTimeline(t),e.moveToMainTimeline(t)),this.invalidateExtensibleEvent()}moveAllRelatedToMainTimeline(e){var t=this.thread;if(this.moveToMainTimeline(e),t)for(var n of t.events){var i;((i=n.getRelation())===null||i===void 0?void 0:i.event_id)===this.getId()&&n.moveAllRelatedToMainTimeline(e)}}moveToMainTimeline(e){var t;(t=this.thread)===null||t===void 0||t.timelineSet.removeEvent(this.getId()),this.setThread(void 0);var n=e.getLiveTimeline();n.getTimelineSet().insertEventIntoTimeline(this,n,n.getState(Ee.FORWARDS))}isRedacted(){return!!this.getUnsigned().redacted_because}isRedaction(){return this.getType()===V.RoomRedaction}asVisibilityChange(){if(!Ea.matches(this.getType()))return null;var e=this.getRelation();if(!e||e.rel_type!="m.reference")return null;var t=e.event_id;if(!t)return null;var n=this.getWireContent(),i=!!n.visible,o=n.reason;return o&&typeof o!="string"?null:{visible:i,reason:o,eventId:t}}isVisibilityEvent(){return Ea.matches(this.getType())}getRedactionEvent(){var e,t;if(!this.isRedacted())return null;if((e=this.clearEvent)!==null&&e!==void 0&&e.unsigned){var n,i;return(n=(i=this.clearEvent)===null||i===void 0?void 0:i.unsigned.redacted_because)!==null&&n!==void 0?n:null}else return(t=this.event.unsigned)!==null&&t!==void 0&&t.redacted_because?this.event.unsigned.redacted_because:{}}getPushActions(){return this.pushDetails.actions||null}getPushDetails(){return this.pushDetails}setPushDetails(e,t){this.pushDetails={actions:e,rule:t}}handleRemoteEcho(e){var t=this.getUnsigned(),n=this.getId();this.event=e,t.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=t.redacted_because),this.setStatus(null),this.getId()!==n&&this.emit(ot.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(ot.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(ot.LocalEventIdReplaced,this)}isRelation(e){var t,n=(t=this.getWireContent())===null||t===void 0?void 0:t["m.relates_to"];return this.isState()&&(n!=null&&n.rel_type)&&[At.Replace,At.Thread].includes(n.rel_type)?!1:!!(n!=null&&n.rel_type&&n.event_id&&(!e||n.rel_type===e))}getRelation(){var e;return this.isRelation()&&(e=this.getWireContent()["m.relates_to"])!==null&&e!==void 0?e:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=e??null,this.emit(ot.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return(t=this.getUnsigned()["m.relations"])===null||t===void 0?void 0:t[e]}replacingEventId(){var e=this.getServerAggregatedRelation(At.Replace);if(e)return e.event_id;if(this._replacingEvent)return this._replacingEvent.getId()}replacingEvent(){return this._replacingEvent}replacingEventDate(){var e=this.getServerAggregatedRelation(At.Replace);if(e){var t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent){var n;return(n=this._replacingEvent.getDate())!==null&&n!==void 0?n:void 0}}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){var e=this.getRelation();if(this.replyEventId)return this.replyEventId;if(e)return e.event_id;if(this.isRedaction())return this.event.redacts}hasAssociation(){return!!this.getAssociatedId()}updateAssociatedId(e){var t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){var e=new pr(JSON.parse(JSON.stringify(this.event)));for(var[t,n]of Object.entries(this))t!=="event"&&(e[t]=n);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;var t=cb(this.event),n=cb(e.event);return JSON.stringify(t)===JSON.stringify(n)}toJSON(){var e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setVerificationRequest(e){this.verificationRequest=e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}setThread(e){this.isState()||(this.thread&&this.reEmitter.stopReEmitting(this.thread,[Xr.Update]),this.thread=e,this.setThreadId(e==null?void 0:e.id),e&&this.reEmitter.reEmit(e,[Xr.Update]))}getThread(){return this.thread}setThreadId(e){this.threadId=e}}var X9=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),Dk={[V.RoomMember]:{membership:1},[V.RoomJoinRules]:{join_rule:1},[V.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}},In=function(r){return r[r.NotStarted=0]="NotStarted",r[r.InProgress=1]="InProgress",r[r.Finished=2]="Finished",r}(In||{}),Ne=function(r){return r.Events="RoomState.events",r.Members="RoomState.members",r.NewMember="RoomState.newMember",r.Update="RoomState.update",r.BeaconLiveness="RoomState.BeaconLiveness",r.Marker="RoomState.Marker",r}({});class qd extends Tt{constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{status:In.NotStarted},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;super(),this.roomId=e,this.oobMemberFlags=t,this.isStartTimelineState=n,v(this,"reEmitter",new Bc(this)),v(this,"sentinels",{}),v(this,"displayNameToUserIds",new Map),v(this,"userIdsToDisplayNames",{}),v(this,"tokenToInvite",{}),v(this,"joinedMemberCount",null),v(this,"summaryJoinedMemberCount",null),v(this,"invitedMemberCount",null),v(this,"summaryInvitedMemberCount",null),v(this,"modified",-1),v(this,"members",{}),v(this,"events",new Map),v(this,"paginationToken",null),v(this,"beacons",new Map),v(this,"_liveBeaconIds",[]),this.updateModifiedTime()}getJoinedMemberCount(){return this.summaryJoinedMemberCount!==null?this.summaryJoinedMemberCount:(this.joinedMemberCount===null&&(this.joinedMemberCount=this.getMembers().reduce((e,t)=>t.membership===Be.Join?e+1:e,0)),this.joinedMemberCount)}setJoinedMemberCount(e){this.summaryJoinedMemberCount=e}getInvitedMemberCount(){return this.summaryInvitedMemberCount!==null?this.summaryInvitedMemberCount:(this.invitedMemberCount===null&&(this.invitedMemberCount=this.getMembers().reduce((e,t)=>t.membership===Be.Invite?e+1:e,0)),this.invitedMemberCount)}setInvitedMemberCount(e){this.summaryInvitedMemberCount=e}getMembers(){return Object.values(this.members)}getMembersExcept(e){return this.getMembers().filter(t=>!e.includes(t.userId))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;var t=this.sentinels[e];if(t===void 0){t=new Zp(this.roomId,e);var n=this.members[e];n!=null&&n.events.member&&t.setMembershipEvent(n.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return t===void 0?[]:null;if(t===void 0)return Array.from(this.events.get(e).values());var n=this.events.get(e).get(t);return n||null}get hasLiveBeacons(){var e;return!!((e=this.liveBeaconIds)!==null&&e!==void 0&&e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){var e=new qd(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=In.NotStarted,Array.from(this.events.values()).forEach(n=>{e.setStateEvents(Array.from(n.values()))}),this.oobMemberFlags.status=t,this.summaryInvitedMemberCount!==null&&e.setInvitedMemberCount(this.getInvitedMemberCount()),this.summaryJoinedMemberCount!==null&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==In.Finished&&this.getMembers().forEach(n=>{if(n.isOutOfBand()){var i;(i=e.getMember(n.userId))===null||i===void 0||i.markOutOfBand()}}),e}setUnknownStateEvents(e){var t=e.filter(n=>!this.events.has(n.getType())||!this.events.get(n.getType()).has(n.getStateKey()));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach(n=>{var i,o;if(!(n.getRoomId()!==this.roomId||!n.isState())){fw.matches(n.getType())&&this.setBeacon(n);var s=this.getStateEventMatching(n),a=s==null||(i=s.event.unsigned)===null||i===void 0?void 0:i.replaces_state,l=s==null?void 0:s.event.event_id,c=(o=n.event.unsigned)===null||o===void 0?void 0:o.replaces_state,u=n.event.event_id;if(this.isStartTimelineState){if(c&&l&&c===l)return}else if(a&&u&&a===u)return;if(this.setStateEvent(n),n.getType()===V.RoomMember){var d;this.updateDisplayNameCache(n.getStateKey(),(d=n.getContent().displayname)!==null&&d!==void 0?d:""),this.updateThirdPartyTokenCache(n)}this.emit(Ne.Events,n,this,s)}}),this.onBeaconLivenessChange(),e.forEach(n=>{if(!(n.getRoomId()!==this.roomId||!n.isState()))if(n.getType()===V.RoomMember){var i=n.getStateKey();(n.getContent().membership===Be.Leave||n.getContent().membership===Be.Ban)&&(n.getContent().avatar_url=n.getContent().avatar_url||n.getPrevContent().avatar_url,n.getContent().displayname=n.getContent().displayname||n.getPrevContent().displayname);var o=this.getOrCreateMember(i,n);o.setMembershipEvent(n,this),this.updateMember(o),this.emit(Ne.Members,n,this,o)}else if(n.getType()===V.RoomPowerLevels){if(n.getStateKey()!=="")return;var s=Object.values(this.members);s.forEach(a=>{var l=a.getLastModifiedTime();a.setPowerLevelEvent(n),l!==a.getLastModifiedTime()&&this.emit(Ne.Members,n,this,a)}),this.sentinels={}}else cD.matches(n.getType())&&this.emit(Ne.Marker,n,t)}),this.emit(Ne.Update,this)}processBeaconEvents(e,t){var n=this;return _(function*(){if(!(!e.length||!n.beacons.size)){var i=[...n.beacons.values()].reduce((c,u)=>(c[u.beaconInfoId]=u,c),{}),o=(c,u)=>{if(vb.matches(u.getType())){var d=i[c];d&&d.addLocations([u])}},s=function*(u){var d,f=(d=u.getRelation())===null||d===void 0?void 0:d.event_id;if(!f||!i[f])return{v:void 0};if(!vb.matches(u.getType())&&!u.isEncrypted())return{v:void 0};try{yield t.decryptEventIfNeeded(u),o(f,u)}catch{u.isDecryptionFailure()&&u.once(ot.Decrypted,_(function*(){o(f,u)}))}},a;for(var l of e)if(a=yield*s(l),a)return a.v}})()}getOrCreateMember(e,t){var n=this.members[e];return n||(n=new Zp(this.roomId,e),this.members[e]=n,this.emit(Ne.NewMember,t,this,n)),n}setStateEvent(e){this.events.has(e.getType())||this.events.set(e.getType(),new Map),this.events.get(e.getType()).set(e.getStateKey(),e)}setBeacon(e){var t=ev(e);if(this.beacons.has(t)){var n=this.beacons.get(t);if(e.isRedacted()){var i;n.beaconInfoId===((i=e.getRedactionEvent())===null||i===void 0?void 0:i.redacts)&&(n.destroy(),this.beacons.delete(t));return}return n.update(e)}if(!e.isRedacted()){var o=new kD(e);this.reEmitter.reEmit(o,[kt.New,kt.Update,kt.Destroy,kt.LivenessChange]),this.emit(kt.New,e,o),o.on(kt.LivenessChange,this.onBeaconLivenessChange.bind(this)),o.on(kt.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(o.identifier,o)}}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter(e=>e.isLive).map(e=>e.identifier),this.emit(Ne.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,n;return(t=(n=this.events.get(e.getType()))===null||n===void 0?void 0:n.get(e.getStateKey()))!==null&&t!==void 0?t:null}updateMember(e){var t=this.getStateEvents(V.RoomPowerLevels,"");t&&e.setPowerLevelEvent(t),delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===In.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===In.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===In.NotStarted&&(this.oobMemberFlags.status=In.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===In.InProgress&&(this.oobMemberFlags.status=In.NotStarted)}clearOutOfBandMembers(){var e=0;Object.keys(this.members).forEach(t=>{var n=this.members[t];n.isOutOfBand()&&(++e,delete this.members[t])}),S.log("LL: RoomState removed ".concat(e," members...")),this.oobMemberFlags.status=In.NotStarted}setOutOfBandMembers(e){S.log("LL: RoomState about to set ".concat(e.length," OOB members ...")),this.oobMemberFlags.status===In.InProgress&&(S.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=In.Finished,e.forEach(t=>this.setOutOfBandMember(t)),this.emit(Ne.Update,this))}setOutOfBandMember(e){if(e.getType()===V.RoomMember){var t=e.getStateKey(),n=this.getMember(t);if(!(n&&!n.isOutOfBand())){var i=this.getOrCreateMember(t,e);i.setMembershipEvent(e,this),i.markOutOfBand(),this.updateDisplayNameCache(i.userId,i.name),this.setStateEvent(e),this.updateMember(i),this.emit(Ne.Members,e,this,i)}}}setTypingEvent(e){Object.values(this.members).forEach(function(t){t.setTypingEvent(e)})}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return(t=this.displayNameToUserIds.get(Ra(e)))!==null&&t!==void 0?t:[]}maySendRedactionForEvent(e,t){var n=this.getMember(t);if(!n||n.membership===Be.Leave||e.status||e.isRedacted())return!1;var i=this.maySendEvent(V.RoomRedaction,t);return i?e.getSender()===t?!0:this.hasSufficientPowerLevelFor("redact",n.powerLevel):!1}hasSufficientPowerLevelFor(e,t){var n=this.getStateEvents(V.RoomPowerLevels,""),i={};n&&(i=n.getContent());var o=50;return tC(i[e])&&(o=i[e]),t>=o}maySendMessage(e){return this.maySendEventOfType(V.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return t.isGuest()||!t.credentials.userId?!1:this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,n){var i=this.getStateEvents(V.RoomPowerLevels,""),o,s={},a=0,l=0,c=0;if(i){o=i.getContent(),s=o.events||{},Number.isSafeInteger(o.state_default)?a=o.state_default:a=50;var u=o.users&&o.users[t];Number.isSafeInteger(u)?c=u:Number.isSafeInteger(o.users_default)&&(c=o.users_default),Number.isSafeInteger(o.events_default)&&(l=o.events_default)}var d=n?a:l;return Number.isSafeInteger(s[e])&&(d=s[e]),c>=d}mayTriggerNotifOfType(e,t){var n=this.getMember(t);if(!n)return!1;var i=this.getStateEvents(V.RoomPowerLevels,""),o=50;return i&&i.getContent()&&i.getContent().notifications&&tC(i.getContent().notifications[e])&&(o=i.getContent().notifications[e]),n.powerLevel>=o}getJoinRule(){var e,t=this.getStateEvents(V.RoomJoinRules,""),n=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return n.join_rule||yN.Invite}getHistoryVisibility(){var e,t=this.getStateEvents(V.RoomHistoryVisibility,""),n=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return n.history_visibility||Aw.Shared}getGuestAccess(){var e,t=this.getStateEvents(V.RoomGuestAccess,""),n=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return n.guest_access||av.Forbidden}findPredecessor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(e){var t=this.getStateEvents(V.RoomPredecessor,"");if(t){var n=t.getContent(),i=n.predecessor_room_id,o=n.last_known_event_id;typeof o!="string"&&(o=void 0);var s=n.via_servers;if(Array.isArray(s)||(s=void 0),typeof i=="string")return{roomId:i,eventId:o,viaServers:s}}}var a=this.getStateEvents(V.RoomCreate,"");if(a){var l=a.getContent().predecessor;if(l){var c=l.room_id;if(typeof c=="string"){var u=l.event_id;return(typeof u!="string"||u==="")&&(u=void 0),{roomId:c,eventId:u}}}}return null}updateThirdPartyTokenCache(e){if(e.getContent().third_party_invite){var t=(e.getContent().third_party_invite.signed||{}).token;if(t){var n=this.getStateEvents(V.RoomThirdPartyInvite,t);n&&(this.tokenToInvite[t]=e)}}}updateDisplayNameCache(e,t){var n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){var i=Ra(n),o=this.displayNameToUserIds.get(i);if(o){var s=o.filter(u=>u!==e);this.displayNameToUserIds.set(i,s)}}this.userIdsToDisplayNames[e]=t;var a=t&&Ra(t);if(a){var l,c=(l=this.displayNameToUserIds.get(a))!==null&&l!==void 0?l:[];c.push(e),this.displayNameToUserIds.set(a,c)}}}function Nk(r){var e=typeof r=="string"&&!!r&&r!=="undefined"&&r!=="null";return e||typeof r=="number"}class Em{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};v(this,"rooms",{}),v(this,"users",{}),v(this,"syncToken",null),v(this,"filters",new qt(()=>new Map)),v(this,"accountData",new Map),v(this,"localStorage",void 0),v(this,"oobMembers",new Map),v(this,"pendingEvents",{}),v(this,"clientOptions",void 0),v(this,"pendingToDeviceBatches",[]),v(this,"nextToDeviceBatchId",0),v(this,"createUser",void 0),v(this,"onRoomMember",(t,n,i)=>{var o;if(i.membership!==Be.Invite){var s=this.users[i.userId]||((o=this.createUser)===null||o===void 0?void 0:o.call(this,i.userId));i.name&&(s.setDisplayName(i.name),i.events.member&&s.setRawDisplayName(i.events.member.getDirectionalContent().displayname)),i.events.member&&i.events.member.getContent().avatar_url&&s.setAvatarUrl(i.events.member.getContent().avatar_url),this.users[s.userId]=s}}),this.localStorage=e.localStorage}getSyncToken(){return this.syncToken}isNewlyCreated(){return Promise.resolve(!0)}setSyncToken(e){this.syncToken=e}storeRoom(e){this.rooms[e.roomId]=e,e.currentState.on(Ne.Members,this.onRoomMember),e.currentState.getMembers().forEach(t=>{this.onRoomMember(null,e.currentState,t)})}setUserCreator(e){this.createUser=e}getRoom(e){return this.rooms[e]||null}getRooms(){return Object.values(this.rooms)}removeRoom(e){this.rooms[e]&&this.rooms[e].currentState.removeListener(Ne.Members,this.onRoomMember),delete this.rooms[e]}getRoomSummaries(){return Object.values(this.rooms).map(function(e){return e.summary})}storeUser(e){this.users[e.userId]=e}getUser(e){return this.users[e]||null}getUsers(){return Object.values(this.users)}scrollback(e,t){return[]}storeEvents(e,t,n,i){}storeFilter(e){!(e!=null&&e.userId)||!(e!=null&&e.filterId)||this.filters.getOrCreate(e.userId).set(e.filterId,e)}getFilter(e,t){var n;return((n=this.filters.get(e))===null||n===void 0?void 0:n.get(t))||null}getFilterIdByName(e){if(!this.localStorage)return null;var t="mxjssdk_memory_filter_"+e;try{var n=this.localStorage.getItem(t);if(Nk(n))return n}catch{}return null}setFilterIdByName(e,t){if(this.localStorage){var n="mxjssdk_memory_filter_"+e;try{Nk(t)?this.localStorage.setItem(n,t):this.localStorage.removeItem(n)}catch{}}}storeAccountDataEvents(e){e.forEach(t=>{var n=!Object.keys(t.getContent()).length;n?this.accountData.delete(t.getType()):this.accountData.set(t.getType(),t)})}getAccountData(e){return this.accountData.get(e)}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(e){return Promise.resolve()}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=new qt(()=>new Map),this.accountData=new Map,Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers.get(e)||null)}setOutOfBandMembers(e,t){return this.oobMembers.set(e,t),Promise.resolve()}clearOutOfBandMembers(e){return this.oobMembers.delete(e),Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(e){return this.clientOptions=Object.assign({},e),Promise.resolve()}getPendingEvents(e){var t=this;return _(function*(){var n;return(n=t.pendingEvents[e])!==null&&n!==void 0?n:[]})()}setPendingEvents(e,t){var n=this;return _(function*(){n.pendingEvents[e]=t})()}saveToDeviceBatches(e){for(var t of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:t.eventType,txnId:t.txnId,batch:t.batch});return Promise.resolve()}getOldestToDeviceBatch(){var e=this;return _(function*(){return e.pendingToDeviceBatches.length===0?null:e.pendingToDeviceBatches[0]})()}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter(t=>t.id!==e),Promise.resolve()}destroy(){return _(function*(){})()}}var sy={},ia={},Xa={};Object.defineProperty(Xa,"__esModule",{value:!0});Xa.WidgetApiDirection=void 0;Xa.invertedDirection=Q9;var Nu=function(r){return r.ToWidget="toWidget",r.FromWidget="fromWidget",r}({});Xa.WidgetApiDirection=Nu;function Q9(r){if(r===Nu.ToWidget)return Nu.FromWidget;if(r===Nu.FromWidget)return Nu.ToWidget;throw new Error("Invalid direction")}var Qi={};Object.defineProperty(Qi,"__esModule",{value:!0});Qi.UnstableApiVersion=Qi.MatrixApiVersion=Qi.CurrentApiVersions=void 0;var i_=function(r){return r.Prerelease1="0.0.1",r.Prerelease2="0.0.2",r}({});Qi.MatrixApiVersion=i_;var xn=function(r){return r.MSC2762="org.matrix.msc2762",r.MSC2762_UPDATE_STATE="org.matrix.msc2762_update_state",r.MSC2871="org.matrix.msc2871",r.MSC2873="org.matrix.msc2873",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",r.MSC3973="org.matrix.msc3973",r.MSC4039="org.matrix.msc4039",r}({});Qi.UnstableApiVersion=xn;var Z9=[i_.Prerelease1,i_.Prerelease2,xn.MSC2762,xn.MSC2762_UPDATE_STATE,xn.MSC2871,xn.MSC2873,xn.MSC2931,xn.MSC2974,xn.MSC2876,xn.MSC3819,xn.MSC3846,xn.MSC3869,xn.MSC3973,xn.MSC4039];Qi.CurrentApiVersions=Z9;var yu={},Lk;function Dw(){if(Lk)return yu;Lk=1,Object.defineProperty(yu,"__esModule",{value:!0}),yu.PostmessageTransport=void 0;var r=fm,e=Im(),t=["message"];function n(T){"@babel/helpers - typeof";return n=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},n(T)}function i(T,x){if(T==null)return{};var C=o(T,x),N,F;if(Object.getOwnPropertySymbols){var H=Object.getOwnPropertySymbols(T);for(F=0;F<H.length;F++)N=H[F],!(x.indexOf(N)>=0)&&Object.prototype.propertyIsEnumerable.call(T,N)&&(C[N]=T[N])}return C}function o(T,x){if(T==null)return{};var C={},N=Object.keys(T),F,H;for(H=0;H<N.length;H++)F=N[H],!(x.indexOf(F)>=0)&&(C[F]=T[F]);return C}function s(T,x){var C=Object.keys(T);if(Object.getOwnPropertySymbols){var N=Object.getOwnPropertySymbols(T);x&&(N=N.filter(function(F){return Object.getOwnPropertyDescriptor(T,F).enumerable})),C.push.apply(C,N)}return C}function a(T){for(var x=1;x<arguments.length;x++){var C=arguments[x]!=null?arguments[x]:{};x%2?s(Object(C),!0).forEach(function(N){b(T,N,C[N])}):Object.getOwnPropertyDescriptors?Object.defineProperties(T,Object.getOwnPropertyDescriptors(C)):s(Object(C)).forEach(function(N){Object.defineProperty(T,N,Object.getOwnPropertyDescriptor(C,N))})}return T}function l(T,x){if(!(T instanceof x))throw new TypeError("Cannot call a class as a function")}function c(T,x){for(var C=0;C<x.length;C++){var N=x[C];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(T,R(N.key),N)}}function u(T,x,C){return x&&c(T.prototype,x),Object.defineProperty(T,"prototype",{writable:!1}),T}function d(T,x){if(typeof x!="function"&&x!==null)throw new TypeError("Super expression must either be null or a function");T.prototype=Object.create(x&&x.prototype,{constructor:{value:T,writable:!0,configurable:!0}}),Object.defineProperty(T,"prototype",{writable:!1}),x&&f(T,x)}function f(T,x){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(N,F){return N.__proto__=F,N},f(T,x)}function p(T){var x=w();return function(){var N=g(T),F;if(x){var H=g(this).constructor;F=Reflect.construct(N,arguments,H)}else F=N.apply(this,arguments);return h(this,F)}}function h(T,x){if(x&&(n(x)==="object"||typeof x=="function"))return x;if(x!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return m(T)}function m(T){if(T===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return T}function w(){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 g(T){return g=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(C){return C.__proto__||Object.getPrototypeOf(C)},g(T)}function b(T,x,C){return x=R(x),x in T?Object.defineProperty(T,x,{value:C,enumerable:!0,configurable:!0,writable:!0}):T[x]=C,T}function R(T){var x=k(T,"string");return n(x)==="symbol"?x:String(x)}function k(T,x){if(n(T)!=="object"||T===null)return T;var C=T[Symbol.toPrimitive];if(C!==void 0){var N=C.call(T,x);if(n(N)!=="object")return N;throw new TypeError("@@toPrimitive must return a primitive value.")}return(x==="string"?String:Number)(T)}var O=function(T){d(C,T);var x=p(C);function C(N,F,H,ie){var $;return l(this,C),$=x.call(this),$.sendDirection=N,$.transportWindow=H,$.inboundWindow=ie,b(m($),"strictOriginCheck",!1),b(m($),"targetOrigin","*"),b(m($),"timeoutSeconds",10),b(m($),"_ready",!1),b(m($),"_widgetId",void 0),b(m($),"outboundRequests",new Map),b(m($),"stopController",new AbortController),b(m($),"handleMessage",function(X){if(!$.stopController.signal.aborted&&X.data&&!($.strictOriginCheck&&X.origin!==globalThis.origin)){var oe=X.data;if(!(!oe.action||!oe.requestId||!oe.widgetId))if(oe.response){if(oe.api!==$.sendDirection)return;$.handleResponse(oe)}else{var re=oe;if(re.api!==(0,e.invertedDirection)($.sendDirection))return;$.handleRequest(re)}}}),$._widgetId=F,$}return u(C,[{key:"ready",get:function(){return this._ready}},{key:"widgetId",get:function(){return this._widgetId||null}},{key:"nextRequestId",get:function(){for(var F="widgetapi-".concat(Date.now()),H=0,ie=F;this.outboundRequests.has(ie);)ie="".concat(F,"-").concat(H++);return this.outboundRequests.set(ie,null),ie}},{key:"sendInternal",value:function(F){console.log("[PostmessageTransport] Sending object to ".concat(this.targetOrigin,": "),F),this.transportWindow.postMessage(F,this.targetOrigin)}},{key:"reply",value:function(F,H){return this.sendInternal(a(a({},F),{},{response:H}))}},{key:"send",value:function(F,H){return this.sendComplete(F,H).then(function(ie){return ie.response})}},{key:"sendComplete",value:function(F,H){var ie=this;if(!this.ready||!this.widgetId)return Promise.reject(new Error("Not ready or unknown widget ID"));var $={api:this.sendDirection,widgetId:this.widgetId,requestId:this.nextRequestId,action:F,data:H};return F===e.WidgetApiToWidgetAction.UpdateVisibility&&($.visible=H.visible),new Promise(function(X,oe){var re=function(Y){Q(),X(Y)},ae=function(Y){Q(),oe(Y)},q=setTimeout(function(){return ae(new Error("Request timed out"))},(ie.timeoutSeconds||1)*1e3),z=function(){return ae(new Error("Transport stopped"))};ie.stopController.signal.addEventListener("abort",z);var Q=function(){ie.outboundRequests.delete($.requestId),clearTimeout(q),ie.stopController.signal.removeEventListener("abort",z)};ie.outboundRequests.set($.requestId,{request:$,resolve:re,reject:ae}),ie.sendInternal($)})}},{key:"start",value:function(){this.inboundWindow.addEventListener("message",this.handleMessage),this._ready=!0}},{key:"stop",value:function(){this._ready=!1,this.stopController.abort(),this.inboundWindow.removeEventListener("message",this.handleMessage)}},{key:"handleRequest",value:function(F){if(this.widgetId){if(this.widgetId!==F.widgetId)return}else this._widgetId=F.widgetId;this.emit("message",new CustomEvent("message",{detail:F}))}},{key:"handleResponse",value:function(F){if(F.widgetId===this.widgetId){var H=this.outboundRequests.get(F.requestId);if(H)if((0,e.isErrorResponse)(F.response)){var ie=F.response.error,$=ie.message,X=i(ie,t);H.reject(new e.WidgetApiResponseError($,X))}else H.resolve(F)}}}]),C}(r.EventEmitter);return yu.PostmessageTransport=O,yu}var Ls={};Object.defineProperty(Ls,"__esModule",{value:!0});Ls.WidgetApiToWidgetAction=Ls.WidgetApiFromWidgetAction=void 0;var e7=function(r){return r.SupportedApiVersions="supported_api_versions",r.Capabilities="capabilities",r.NotifyCapabilities="notify_capabilities",r.ThemeChange="theme_change",r.LanguageChange="language_change",r.TakeScreenshot="screenshot",r.UpdateVisibility="visibility",r.OpenIDCredentials="openid_credentials",r.WidgetConfig="widget_config",r.CloseModalWidget="close_modal",r.ButtonClicked="button_clicked",r.SendEvent="send_event",r.SendToDevice="send_to_device",r.UpdateState="update_state",r.UpdateTurnServers="update_turn_servers",r}({});Ls.WidgetApiToWidgetAction=e7;var t7=function(r){return r.SupportedApiVersions="supported_api_versions",r.ContentLoaded="content_loaded",r.SendSticker="m.sticker",r.UpdateAlwaysOnScreen="set_always_on_screen",r.GetOpenIDCredentials="get_openid",r.CloseModalWidget="close_modal",r.OpenModalWidget="open_modal",r.SetModalButtonEnabled="set_button_enabled",r.SendEvent="send_event",r.SendToDevice="send_to_device",r.WatchTurnServers="watch_turn_servers",r.UnwatchTurnServers="unwatch_turn_servers",r.BeeperReadRoomAccountData="com.beeper.read_room_account_data",r.MSC2876ReadEvents="org.matrix.msc2876.read_events",r.MSC2931Navigate="org.matrix.msc2931.navigate",r.MSC2974RenegotiateCapabilities="org.matrix.msc2974.request_capabilities",r.MSC3869ReadRelations="org.matrix.msc3869.read_relations",r.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",r.MSC4039GetMediaConfigAction="org.matrix.msc4039.get_media_config",r.MSC4039UploadFileAction="org.matrix.msc4039.upload_file",r.MSC4039DownloadFileAction="org.matrix.msc4039.download_file",r.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",r}({});Ls.WidgetApiFromWidgetAction=t7;var Wc={};Object.defineProperty(Wc,"__esModule",{value:!0});Wc.OpenIDRequestState=void 0;var r7=function(r){return r.Allowed="allowed",r.Blocked="blocked",r.PendingUserConfirmation="request",r}({});Wc.OpenIDRequestState=r7;var Tf={};Object.defineProperty(Tf,"__esModule",{value:!0});Tf.MatrixWidgetType=void 0;var n7=function(r){return r.Custom="m.custom",r.JitsiMeet="m.jitsi",r.Stickerpicker="m.stickerpicker",r}({});Tf.MatrixWidgetType=n7;var Rf={};Object.defineProperty(Rf,"__esModule",{value:!0});Rf.BuiltInModalButtonID=void 0;var i7=function(r){return r.Close="m.close",r}({});Rf.BuiltInModalButtonID=i7;var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0});Zi.WidgetEventCapability=Zi.EventKind=Zi.EventDirection=void 0;function Gd(r){"@babel/helpers - typeof";return Gd=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Gd(r)}function o7(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=s7(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
285
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function s7(r,e){if(r){if(typeof r=="string")return Uk(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Uk(r,e)}}function Uk(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function a7(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function jk(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,c7(n.key),n)}}function l7(r,e,t){return e&&jk(r.prototype,e),t&&jk(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function c7(r){var e=u7(r,"string");return Gd(e)==="symbol"?e:String(e)}function u7(r,e){if(Gd(r)!=="object"||r===null)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(Gd(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(r)}var On=function(r){return r.Event="event",r.State="state_event",r.ToDevice="to_device",r.RoomAccount="room_account",r}({});Zi.EventKind=On;var is=function(r){return r.Send="send",r.Receive="receive",r}({});Zi.EventDirection=is;var d7=function(){function r(e,t,n,i,o){a7(this,r),this.direction=e,this.eventType=t,this.kind=n,this.keyStr=i,this.raw=o}return l7(r,[{key:"matchesAsStateEvent",value:function(t,n,i){return this.kind!==On.State||this.direction!==t||this.eventType!==n?!1:this.keyStr===null||this.keyStr===i}},{key:"matchesAsToDeviceEvent",value:function(t,n){return!(this.kind!==On.ToDevice||this.direction!==t||this.eventType!==n)}},{key:"matchesAsRoomEvent",value:function(t,n){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this.kind!==On.Event||this.direction!==t||this.eventType!==n)return!1;if(this.eventType==="m.room.message"){if(this.keyStr===null||this.keyStr===i)return!0}else return!0;return!1}},{key:"matchesAsRoomAccountData",value:function(t,n){return!(this.kind!==On.RoomAccount||this.direction!==t||this.eventType!==n)}}],[{key:"forStateEvent",value:function(t,n,i){n=n.replace(/#/g,"\\#"),i=i!=null?"#".concat(i):"";var o="org.matrix.msc2762.".concat(t,".state_event:").concat(n).concat(i);return r.findEventCapabilities([o])[0]}},{key:"forToDeviceEvent",value:function(t,n){var i="org.matrix.msc3819.".concat(t,".to_device:").concat(n);return r.findEventCapabilities([i])[0]}},{key:"forRoomEvent",value:function(t,n){var i="org.matrix.msc2762.".concat(t,".event:").concat(n);return r.findEventCapabilities([i])[0]}},{key:"forRoomMessageEvent",value:function(t,n){n=n??"";var i="org.matrix.msc2762.".concat(t,".event:m.room.message#").concat(n);return r.findEventCapabilities([i])[0]}},{key:"forRoomAccountData",value:function(t,n){var i="com.beeper.capabilities.".concat(t,".room_account_data:").concat(n);return r.findEventCapabilities([i])[0]}},{key:"findEventCapabilities",value:function(t){var n=[],i=o7(t),o;try{for(i.s();!(o=i.n()).done;){var s=o.value,a=null,l=void 0,c=null;if(s.startsWith("org.matrix.msc2762.send.event:")?(a=is.Send,c=On.Event,l=s.substring(30)):s.startsWith("org.matrix.msc2762.send.state_event:")?(a=is.Send,c=On.State,l=s.substring(36)):s.startsWith("org.matrix.msc3819.send.to_device:")?(a=is.Send,c=On.ToDevice,l=s.substring(34)):s.startsWith("org.matrix.msc2762.receive.event:")?(a=is.Receive,c=On.Event,l=s.substring(33)):s.startsWith("org.matrix.msc2762.receive.state_event:")?(a=is.Receive,c=On.State,l=s.substring(39)):s.startsWith("org.matrix.msc3819.receive.to_device:")?(a=is.Receive,c=On.ToDevice,l=s.substring(37)):s.startsWith("com.beeper.capabilities.receive.room_account_data:")&&(a=is.Receive,c=On.RoomAccount,l=s.substring(50)),!(a===null||c===null||l===void 0)){var u=l.startsWith("m.room.message#")||c===On.State,d=null;if(l.includes("#")&&u){var f=l.split("#"),p=f.findIndex(function(h){return!h.endsWith("\\")});l=f.slice(0,p+1).map(function(h){return h.endsWith("\\")?h.substring(0,h.length-1):h}).join("#"),d=f.slice(p+1).join("#")}n.push(new r(a,l,c,d,s))}}}catch(h){i.e(h)}finally{i.f()}return n}}]),r}();Zi.WidgetEventCapability=d7;var qc={};Object.defineProperty(qc,"__esModule",{value:!0});qc.Symbols=void 0;var f7=function(r){return r.AnyRoom="*",r}({});qc.Symbols=f7;var Gc={};Object.defineProperty(Gc,"__esModule",{value:!0});Gc.UpdateDelayedEventAction=void 0;var h7=function(r){return r.Cancel="cancel",r.Restart="restart",r.Send="send",r}({});Gc.UpdateDelayedEventAction=h7;var Fk;function p7(){if(Fk)return ia;Fk=1;function r(A){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(D){return typeof D}:function(D){return D&&typeof Symbol=="function"&&D.constructor===Symbol&&D!==Symbol.prototype?"symbol":typeof D},r(A)}Object.defineProperty(ia,"__esModule",{value:!0}),ia.WidgetApiResponseError=ia.WidgetApi=void 0;var e=fm,t=Xa,n=Qi,i=Dw(),o=Ls,s=Wc,a=Tf,l=Rf,c=Zi,u=qc,d=Gc;function f(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */f=function(){return A};var A={},D=Object.prototype,P=D.hasOwnProperty,M=Object.defineProperty||function(J,te,ne){J[te]=ne.value},I=typeof Symbol=="function"?Symbol:{},j=I.iterator||"@@iterator",U=I.asyncIterator||"@@asyncIterator",K=I.toStringTag||"@@toStringTag";function G(J,te,ne){return Object.defineProperty(J,te,{value:ne,enumerable:!0,configurable:!0,writable:!0}),J[te]}try{G({},"")}catch{G=function(ne,ue,_e){return ne[ue]=_e}}function ee(J,te,ne,ue){var _e=te&&te.prototype instanceof Re?te:Re,we=Object.create(_e.prototype),ze=new Rn(ue||[]);return M(we,"_invoke",{value:gt(J,ne,ze)}),we}function se(J,te,ne){try{return{type:"normal",arg:J.call(te,ne)}}catch(ue){return{type:"throw",arg:ue}}}A.wrap=ee;var Ce={};function Re(){}function ge(){}function He(){}var Qe={};G(Qe,j,function(){return this});var $e=Object.getPrototypeOf,ve=$e&&$e($e(ye([])));ve&&ve!==D&&P.call(ve,j)&&(Qe=ve);var We=He.prototype=Re.prototype=Object.create(Qe);function un(J){["next","throw","return"].forEach(function(te){G(J,te,function(ne){return this._invoke(te,ne)})})}function Rr(J,te){function ne(_e,we,ze,dt){var ht=se(J[_e],J,we);if(ht.type!=="throw"){var Bt=ht.arg,Le=Bt.value;return Le&&r(Le)=="object"&&P.call(Le,"__await")?te.resolve(Le.__await).then(function(pt){ne("next",pt,ze,dt)},function(pt){ne("throw",pt,ze,dt)}):te.resolve(Le).then(function(pt){Bt.value=pt,ze(Bt)},function(pt){return ne("throw",pt,ze,dt)})}dt(ht.arg)}var ue;M(this,"_invoke",{value:function(we,ze){function dt(){return new te(function(ht,Bt){ne(we,ze,ht,Bt)})}return ue=ue?ue.then(dt,dt):dt()}})}function gt(J,te,ne){var ue="suspendedStart";return function(_e,we){if(ue==="executing")throw new Error("Generator is already running");if(ue==="completed"){if(_e==="throw")throw we;return de()}for(ne.method=_e,ne.arg=we;;){var ze=ne.delegate;if(ze){var dt=vr(ze,ne);if(dt){if(dt===Ce)continue;return dt}}if(ne.method==="next")ne.sent=ne._sent=ne.arg;else if(ne.method==="throw"){if(ue==="suspendedStart")throw ue="completed",ne.arg;ne.dispatchException(ne.arg)}else ne.method==="return"&&ne.abrupt("return",ne.arg);ue="executing";var ht=se(J,te,ne);if(ht.type==="normal"){if(ue=ne.done?"completed":"suspendedYield",ht.arg===Ce)continue;return{value:ht.arg,done:ne.done}}ht.type==="throw"&&(ue="completed",ne.method="throw",ne.arg=ht.arg)}}}function vr(J,te){var ne=te.method,ue=J.iterator[ne];if(ue===void 0)return te.delegate=null,ne==="throw"&&J.iterator.return&&(te.method="return",te.arg=void 0,vr(J,te),te.method==="throw")||ne!=="return"&&(te.method="throw",te.arg=new TypeError("The iterator does not provide a '"+ne+"' method")),Ce;var _e=se(ue,J.iterator,te.arg);if(_e.type==="throw")return te.method="throw",te.arg=_e.arg,te.delegate=null,Ce;var we=_e.arg;return we?we.done?(te[J.resultName]=we.value,te.next=J.nextLoc,te.method!=="return"&&(te.method="next",te.arg=void 0),te.delegate=null,Ce):we:(te.method="throw",te.arg=new TypeError("iterator result is not an object"),te.delegate=null,Ce)}function mr(J){var te={tryLoc:J[0]};1 in J&&(te.catchLoc=J[1]),2 in J&&(te.finallyLoc=J[2],te.afterLoc=J[3]),this.tryEntries.push(te)}function Rt(J){var te=J.completion||{};te.type="normal",delete te.arg,J.completion=te}function Rn(J){this.tryEntries=[{tryLoc:"root"}],J.forEach(mr,this),this.reset(!0)}function ye(J){if(J){var te=J[j];if(te)return te.call(J);if(typeof J.next=="function")return J;if(!isNaN(J.length)){var ne=-1,ue=function _e(){for(;++ne<J.length;)if(P.call(J,ne))return _e.value=J[ne],_e.done=!1,_e;return _e.value=void 0,_e.done=!0,_e};return ue.next=ue}}return{next:de}}function de(){return{value:void 0,done:!0}}return ge.prototype=He,M(We,"constructor",{value:He,configurable:!0}),M(He,"constructor",{value:ge,configurable:!0}),ge.displayName=G(He,K,"GeneratorFunction"),A.isGeneratorFunction=function(J){var te=typeof J=="function"&&J.constructor;return!!te&&(te===ge||(te.displayName||te.name)==="GeneratorFunction")},A.mark=function(J){return Object.setPrototypeOf?Object.setPrototypeOf(J,He):(J.__proto__=He,G(J,K,"GeneratorFunction")),J.prototype=Object.create(We),J},A.awrap=function(J){return{__await:J}},un(Rr.prototype),G(Rr.prototype,U,function(){return this}),A.AsyncIterator=Rr,A.async=function(J,te,ne,ue,_e){_e===void 0&&(_e=Promise);var we=new Rr(ee(J,te,ne,ue),_e);return A.isGeneratorFunction(te)?we:we.next().then(function(ze){return ze.done?ze.value:we.next()})},un(We),G(We,K,"Generator"),G(We,j,function(){return this}),G(We,"toString",function(){return"[object Generator]"}),A.keys=function(J){var te=Object(J),ne=[];for(var ue in te)ne.push(ue);return ne.reverse(),function _e(){for(;ne.length;){var we=ne.pop();if(we in te)return _e.value=we,_e.done=!1,_e}return _e.done=!0,_e}},A.values=ye,Rn.prototype={constructor:Rn,reset:function(te){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(Rt),!te)for(var ne in this)ne.charAt(0)==="t"&&P.call(this,ne)&&!isNaN(+ne.slice(1))&&(this[ne]=void 0)},stop:function(){this.done=!0;var te=this.tryEntries[0].completion;if(te.type==="throw")throw te.arg;return this.rval},dispatchException:function(te){if(this.done)throw te;var ne=this;function ue(Bt,Le){return ze.type="throw",ze.arg=te,ne.next=Bt,Le&&(ne.method="next",ne.arg=void 0),!!Le}for(var _e=this.tryEntries.length-1;_e>=0;--_e){var we=this.tryEntries[_e],ze=we.completion;if(we.tryLoc==="root")return ue("end");if(we.tryLoc<=this.prev){var dt=P.call(we,"catchLoc"),ht=P.call(we,"finallyLoc");if(dt&&ht){if(this.prev<we.catchLoc)return ue(we.catchLoc,!0);if(this.prev<we.finallyLoc)return ue(we.finallyLoc)}else if(dt){if(this.prev<we.catchLoc)return ue(we.catchLoc,!0)}else{if(!ht)throw new Error("try statement without catch or finally");if(this.prev<we.finallyLoc)return ue(we.finallyLoc)}}}},abrupt:function(te,ne){for(var ue=this.tryEntries.length-1;ue>=0;--ue){var _e=this.tryEntries[ue];if(_e.tryLoc<=this.prev&&P.call(_e,"finallyLoc")&&this.prev<_e.finallyLoc){var we=_e;break}}we&&(te==="break"||te==="continue")&&we.tryLoc<=ne&&ne<=we.finallyLoc&&(we=null);var ze=we?we.completion:{};return ze.type=te,ze.arg=ne,we?(this.method="next",this.next=we.finallyLoc,Ce):this.complete(ze)},complete:function(te,ne){if(te.type==="throw")throw te.arg;return te.type==="break"||te.type==="continue"?this.next=te.arg:te.type==="return"?(this.rval=this.arg=te.arg,this.method="return",this.next="end"):te.type==="normal"&&ne&&(this.next=ne),Ce},finish:function(te){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ue=this.tryEntries[ne];if(ue.finallyLoc===te)return this.complete(ue.completion,ue.afterLoc),Rt(ue),Ce}},catch:function(te){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ue=this.tryEntries[ne];if(ue.tryLoc===te){var _e=ue.completion;if(_e.type==="throw"){var we=_e.arg;Rt(ue)}return we}}throw new Error("illegal catch attempt")},delegateYield:function(te,ne,ue){return this.delegate={iterator:ye(te),resultName:ne,nextLoc:ue},this.method==="next"&&(this.arg=void 0),Ce}},A}function p(A,D,P,M,I,j,U){try{var K=A[j](U),G=K.value}catch(ee){P(ee);return}K.done?D(G):Promise.resolve(G).then(M,I)}function h(A){return function(){var D=this,P=arguments;return new Promise(function(M,I){var j=A.apply(D,P);function U(G){p(j,M,I,U,K,"next",G)}function K(G){p(j,M,I,U,K,"throw",G)}U(void 0)})}}function m(A,D){var P=Object.keys(A);if(Object.getOwnPropertySymbols){var M=Object.getOwnPropertySymbols(A);D&&(M=M.filter(function(I){return Object.getOwnPropertyDescriptor(A,I).enumerable})),P.push.apply(P,M)}return P}function w(A){for(var D=1;D<arguments.length;D++){var P=arguments[D]!=null?arguments[D]:{};D%2?m(Object(P),!0).forEach(function(M){k(A,M,P[M])}):Object.getOwnPropertyDescriptors?Object.defineProperties(A,Object.getOwnPropertyDescriptors(P)):m(Object(P)).forEach(function(M){Object.defineProperty(A,M,Object.getOwnPropertyDescriptor(P,M))})}return A}function g(A,D){var P=typeof Symbol<"u"&&A[Symbol.iterator]||A["@@iterator"];if(!P){if(Array.isArray(A)||(P=b(A))||D){P&&(A=P);var M=0,I=function(){};return{s:I,n:function(){return M>=A.length?{done:!0}:{done:!1,value:A[M++]}},e:function(ee){throw ee},f:I}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
286
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var j=!0,U=!1,K;return{s:function(){P=P.call(A)},n:function(){var ee=P.next();return j=ee.done,ee},e:function(ee){U=!0,K=ee},f:function(){try{!j&&P.return!=null&&P.return()}finally{if(U)throw K}}}}function b(A,D){if(A){if(typeof A=="string")return R(A,D);var P=Object.prototype.toString.call(A).slice(8,-1);if(P==="Object"&&A.constructor&&(P=A.constructor.name),P==="Map"||P==="Set")return Array.from(A);if(P==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(P))return R(A,D)}}function R(A,D){(D==null||D>A.length)&&(D=A.length);for(var P=0,M=new Array(D);P<D;P++)M[P]=A[P];return M}function k(A,D,P){return D=x(D),D in A?Object.defineProperty(A,D,{value:P,enumerable:!0,configurable:!0,writable:!0}):A[D]=P,A}function O(A,D){for(var P=0;P<D.length;P++){var M=D[P];M.enumerable=M.enumerable||!1,M.configurable=!0,"value"in M&&(M.writable=!0),Object.defineProperty(A,x(M.key),M)}}function T(A,D,P){return D&&O(A.prototype,D),Object.defineProperty(A,"prototype",{writable:!1}),A}function x(A){var D=C(A,"string");return r(D)==="symbol"?D:String(D)}function C(A,D){if(r(A)!=="object"||A===null)return A;var P=A[Symbol.toPrimitive];if(P!==void 0){var M=P.call(A,D);if(r(M)!=="object")return M;throw new TypeError("@@toPrimitive must return a primitive value.")}return(D==="string"?String:Number)(A)}function N(A,D){if(!(A instanceof D))throw new TypeError("Cannot call a class as a function")}function F(A,D){if(typeof D!="function"&&D!==null)throw new TypeError("Super expression must either be null or a function");A.prototype=Object.create(D&&D.prototype,{constructor:{value:A,writable:!0,configurable:!0}}),Object.defineProperty(A,"prototype",{writable:!1}),D&&q(A,D)}function H(A){var D=re();return function(){var M=z(A),I;if(D){var j=z(this).constructor;I=Reflect.construct(M,arguments,j)}else I=M.apply(this,arguments);return ie(this,I)}}function ie(A,D){if(D&&(r(D)==="object"||typeof D=="function"))return D;if(D!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return $(A)}function $(A){if(A===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return A}function X(A){var D=typeof Map=="function"?new Map:void 0;return X=function(M){if(M===null||!ae(M))return M;if(typeof M!="function")throw new TypeError("Super expression must either be null or a function");if(typeof D<"u"){if(D.has(M))return D.get(M);D.set(M,I)}function I(){return oe(M,arguments,z(this).constructor)}return I.prototype=Object.create(M.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}),q(I,M)},X(A)}function oe(A,D,P){return re()?oe=Reflect.construct.bind():oe=function(I,j,U){var K=[null];K.push.apply(K,j);var G=Function.bind.apply(I,K),ee=new G;return U&&q(ee,U.prototype),ee},oe.apply(null,arguments)}function re(){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 ae(A){return Function.toString.call(A).indexOf("[native code]")!==-1}function q(A,D){return q=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(M,I){return M.__proto__=I,M},q(A,D)}function z(A){return z=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(P){return P.__proto__||Object.getPrototypeOf(P)},z(A)}function Q(A){return new le(A,0)}function Ie(A){return function(){return new Y(A.apply(this,arguments))}}function Y(A){var D,P;function M(j,U){try{var K=A[j](U),G=K.value,ee=G instanceof le;Promise.resolve(ee?G.v:G).then(function(se){if(ee){var Ce=j==="return"?"return":"next";if(!G.k||se.done)return M(Ce,se);se=A[Ce](se).value}I(K.done?"return":"normal",se)},function(se){M("throw",se)})}catch(se){I("throw",se)}}function I(j,U){switch(j){case"return":D.resolve({value:U,done:!0});break;case"throw":D.reject(U);break;default:D.resolve({value:U,done:!1})}(D=D.next)?M(D.key,D.arg):P=null}this._invoke=function(j,U){return new Promise(function(K,G){var ee={key:j,arg:U,resolve:K,reject:G,next:null};P?P=P.next=ee:(D=P=ee,M(j,U))})},typeof A.return!="function"&&(this.return=void 0)}Y.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Y.prototype.next=function(A){return this._invoke("next",A)},Y.prototype.throw=function(A){return this._invoke("throw",A)},Y.prototype.return=function(A){return this._invoke("return",A)};function le(A,D){this.v=A,this.k=D}var B=function(A){F(P,A);var D=H(P);function P(M,I){var j;return N(this,P),j=D.call(this,M),j.data=I,j}return T(P)}(X(Error));ia.WidgetApiResponseError=B,B.prototype.name=B.name;var W=function(A){F(P,A);var D=H(P);function P(){var M,I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,j=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(N(this,P),M=D.call(this),k($(M),"transport",void 0),k($(M),"capabilitiesFinished",!1),k($(M),"supportsMSC2974Renegotiate",!1),k($(M),"requestedCapabilities",[]),k($(M),"approvedCapabilities",void 0),k($(M),"cachedClientVersions",void 0),k($(M),"turnServerWatchers",0),!globalThis.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");return M.transport=new i.PostmessageTransport(t.WidgetApiDirection.FromWidget,I,globalThis.parent,globalThis),M.transport.targetOrigin=j,M.transport.on("message",M.handleMessage.bind($(M))),M}return T(P,[{key:"hasCapability",value:function(I){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(I):this.requestedCapabilities.includes(I)}},{key:"requestCapability",value:function(I){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(I)}},{key:"requestCapabilities",value:function(I){var j=g(I),U;try{for(j.s();!(U=j.n()).done;){var K=U.value;this.requestCapability(K)}}catch(G){j.e(G)}finally{j.f()}}},{key:"requestCapabilityForRoomTimeline",value:function(I){this.requestCapability("org.matrix.msc2762.timeline:".concat(I))}},{key:"requestCapabilityToSendState",value:function(I,j){this.requestCapability(c.WidgetEventCapability.forStateEvent(c.EventDirection.Send,I,j).raw)}},{key:"requestCapabilityToReceiveState",value:function(I,j){this.requestCapability(c.WidgetEventCapability.forStateEvent(c.EventDirection.Receive,I,j).raw)}},{key:"requestCapabilityToSendToDevice",value:function(I){this.requestCapability(c.WidgetEventCapability.forToDeviceEvent(c.EventDirection.Send,I).raw)}},{key:"requestCapabilityToReceiveToDevice",value:function(I){this.requestCapability(c.WidgetEventCapability.forToDeviceEvent(c.EventDirection.Receive,I).raw)}},{key:"requestCapabilityToSendEvent",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomEvent(c.EventDirection.Send,I).raw)}},{key:"requestCapabilityToReceiveEvent",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomEvent(c.EventDirection.Receive,I).raw)}},{key:"requestCapabilityToSendMessage",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomMessageEvent(c.EventDirection.Send,I).raw)}},{key:"requestCapabilityToReceiveMessage",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomMessageEvent(c.EventDirection.Receive,I).raw)}},{key:"requestCapabilityToReceiveRoomAccountData",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomAccountData(c.EventDirection.Receive,I).raw)}},{key:"requestOpenIDConnectToken",value:function(){var I=this;return new Promise(function(j,U){I.transport.sendComplete(o.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then(function(K){var G=K.response;if(G.state===s.OpenIDRequestState.Allowed)j(G);else if(G.state===s.OpenIDRequestState.Blocked)U(new Error("User declined to verify their identity"));else if(G.state===s.OpenIDRequestState.PendingUserConfirmation){var ee=function se(Ce){Ce.preventDefault();var Re=Ce.detail;Re.data.original_request_id===K.requestId&&(Re.data.state===s.OpenIDRequestState.Allowed?(j(Re.data),I.transport.reply(Re,{})):Re.data.state===s.OpenIDRequestState.Blocked?(U(new Error("User declined to verify their identity")),I.transport.reply(Re,{})):(U(new Error("Invalid state on reply: "+G.state)),I.transport.reply(Re,{error:{message:"Invalid state"}})),I.off("action:".concat(o.WidgetApiToWidgetAction.OpenIDCredentials),se))};I.on("action:".concat(o.WidgetApiToWidgetAction.OpenIDCredentials),ee)}else U(new Error("Invalid state: "+G.state))}).catch(U)})}},{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(I){return this.transport.send(o.WidgetApiFromWidgetAction.SendSticker,I).then()}},{key:"setAlwaysOnScreen",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:I}).then(function(j){return j.success})}},{key:"openModalWidget",value:function(I,j){var U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],K=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},G=arguments.length>4&&arguments[4]!==void 0?arguments[4]:a.MatrixWidgetType.Custom;return this.transport.send(o.WidgetApiFromWidgetAction.OpenModalWidget,{type:G,url:I,name:j,buttons:U,data:K}).then()}},{key:"closeModalWidget",value:function(){var I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.transport.send(o.WidgetApiFromWidgetAction.CloseModalWidget,I).then()}},{key:"sendRoomEvent",value:function(I,j,U,K,G,ee){return this.sendEvent(I,void 0,j,U,K,G,ee)}},{key:"sendStateEvent",value:function(I,j,U,K,G,ee){return this.sendEvent(I,j,U,K,G,ee)}},{key:"sendEvent",value:function(I,j,U,K,G,ee,se){return this.transport.send(o.WidgetApiFromWidgetAction.SendEvent,w(w(w(w(w({type:I,content:U},j!==void 0&&{state_key:j}),K!==void 0&&{room_id:K}),G!==void 0&&{delay:G}),ee!==void 0&&{parent_delay_id:ee}),se!==void 0&&{sticky_duration_ms:se}))}},{key:"cancelScheduledDelayedEvent",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:I,action:d.UpdateDelayedEventAction.Cancel})}},{key:"restartScheduledDelayedEvent",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:I,action:d.UpdateDelayedEventAction.Restart})}},{key:"sendScheduledDelayedEvent",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:I,action:d.UpdateDelayedEventAction.Send})}},{key:"sendToDevice",value:function(I,j,U){return this.transport.send(o.WidgetApiFromWidgetAction.SendToDevice,{type:I,encrypted:j,messages:U})}},{key:"readRoomAccountData",value:function(I,j){var U={type:I};return j&&(j.includes(u.Symbols.AnyRoom)?U.room_ids=u.Symbols.AnyRoom:U.room_ids=j),this.transport.send(o.WidgetApiFromWidgetAction.BeeperReadRoomAccountData,U).then(function(K){return K.events})}},{key:"readRoomEvents",value:function(I,j,U,K,G){var ee={type:I,msgtype:U};return j!==void 0&&(ee.limit=j),K&&(K.includes(u.Symbols.AnyRoom)?ee.room_ids=u.Symbols.AnyRoom:ee.room_ids=K),G&&(ee.since=G),this.transport.send(o.WidgetApiFromWidgetAction.MSC2876ReadEvents,ee).then(function(se){return se.events})}},{key:"readEventRelations",value:function(){var M=h(f().mark(function j(U,K,G,ee,se,Ce,Re,ge){var He,Qe;return f().wrap(function(ve){for(;;)switch(ve.prev=ve.next){case 0:return ve.next=2,this.getClientVersions();case 2:if(He=ve.sent,He.includes(n.UnstableApiVersion.MSC3869)){ve.next=5;break}throw new Error("The read_relations action is not supported by the client.");case 5:return Qe={event_id:U,rel_type:G,event_type:ee,room_id:K,to:Re,from:Ce,limit:se,direction:ge},ve.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC3869ReadRelations,Qe));case 7:case"end":return ve.stop()}},j,this)}));function I(j,U,K,G,ee,se,Ce,Re){return M.apply(this,arguments)}return I}()},{key:"readStateEvents",value:function(I,j,U,K){var G={type:I,state_key:U===void 0?!0:U};return j!==void 0&&(G.limit=j),K&&(K.includes(u.Symbols.AnyRoom)?G.room_ids=u.Symbols.AnyRoom:G.room_ids=K),this.transport.send(o.WidgetApiFromWidgetAction.MSC2876ReadEvents,G).then(function(ee){return ee.events})}},{key:"setModalButtonEnabled",value:function(I,j){if(I===l.BuiltInModalButtonID.Close)throw new Error("The close button cannot be disabled");return this.transport.send(o.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:I,enabled:j}).then()}},{key:"navigateTo",value:function(I){if(!I||!I.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(o.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:I}).then()}},{key:"getTurnServers",value:function(){var I=this;return Ie(f().mark(function j(){var U,K;return f().wrap(function(ee){for(;;)switch(ee.prev=ee.next){case 0:if(K=function(){var se=h(f().mark(function Ce(Re){return f().wrap(function(He){for(;;)switch(He.prev=He.next){case 0:Re.preventDefault(),U(Re.detail.data),I.transport.reply(Re.detail,{});case 3:case"end":return He.stop()}},Ce)}));return function(Re){return se.apply(this,arguments)}}(),I.on("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),K),I.turnServerWatchers!==0){ee.next=12;break}return ee.prev=3,ee.next=6,Q(I.transport.send(o.WidgetApiFromWidgetAction.WatchTurnServers,{}));case 6:ee.next=12;break;case 8:throw ee.prev=8,ee.t0=ee.catch(3),I.off("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),K),ee.t0;case 12:I.turnServerWatchers++,ee.prev=13;case 14:return ee.next=17,Q(new Promise(function(se){return U=se}));case 17:return ee.next=19,ee.sent;case 19:ee.next=14;break;case 21:if(ee.prev=21,I.off("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),K),I.turnServerWatchers--,I.turnServerWatchers!==0){ee.next=27;break}return ee.next=27,Q(I.transport.send(o.WidgetApiFromWidgetAction.UnwatchTurnServers,{}));case 27:return ee.finish(21);case 28:case"end":return ee.stop()}},j,null,[[3,8],[13,,21,28]])}))()}},{key:"searchUserDirectory",value:function(){var M=h(f().mark(function j(U,K){var G,ee;return f().wrap(function(Ce){for(;;)switch(Ce.prev=Ce.next){case 0:return Ce.next=2,this.getClientVersions();case 2:if(G=Ce.sent,G.includes(n.UnstableApiVersion.MSC3973)){Ce.next=5;break}throw new Error("The user_directory_search action is not supported by the client.");case 5:return ee={search_term:U,limit:K},Ce.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch,ee));case 7:case"end":return Ce.stop()}},j,this)}));function I(j,U){return M.apply(this,arguments)}return I}()},{key:"getMediaConfig",value:function(){var M=h(f().mark(function j(){var U,K;return f().wrap(function(ee){for(;;)switch(ee.prev=ee.next){case 0:return ee.next=2,this.getClientVersions();case 2:if(U=ee.sent,U.includes(n.UnstableApiVersion.MSC4039)){ee.next=5;break}throw new Error("The get_media_config action is not supported by the client.");case 5:return K={},ee.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC4039GetMediaConfigAction,K));case 7:case"end":return ee.stop()}},j,this)}));function I(){return M.apply(this,arguments)}return I}()},{key:"uploadFile",value:function(){var M=h(f().mark(function j(U){var K,G;return f().wrap(function(se){for(;;)switch(se.prev=se.next){case 0:return se.next=2,this.getClientVersions();case 2:if(K=se.sent,K.includes(n.UnstableApiVersion.MSC4039)){se.next=5;break}throw new Error("The upload_file action is not supported by the client.");case 5:return G={file:U},se.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC4039UploadFileAction,G));case 7:case"end":return se.stop()}},j,this)}));function I(j){return M.apply(this,arguments)}return I}()},{key:"downloadFile",value:function(){var M=h(f().mark(function j(U){var K,G;return f().wrap(function(se){for(;;)switch(se.prev=se.next){case 0:return se.next=2,this.getClientVersions();case 2:if(K=se.sent,K.includes(n.UnstableApiVersion.MSC4039)){se.next=5;break}throw new Error("The download_file action is not supported by the client.");case 5:return G={content_uri:U},se.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC4039DownloadFileAction,G));case 7:case"end":return se.stop()}},j,this)}));function I(j){return M.apply(this,arguments)}return I}()},{key:"start",value:function(){var I=this;this.transport.start(),this.getClientVersions().then(function(j){j.includes(n.UnstableApiVersion.MSC2974)&&(I.supportsMSC2974Renegotiate=!0)})}},{key:"handleMessage",value:function(I){var j=new CustomEvent("action:".concat(I.detail.action),{detail:I.detail,cancelable:!0});if(this.emit("action:".concat(I.detail.action),j),!j.defaultPrevented)switch(I.detail.action){case o.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(I.detail);case o.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(I.detail);case o.WidgetApiToWidgetAction.UpdateVisibility:return this.transport.reply(I.detail,{});case o.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(I.detail,{});default:return this.transport.reply(I.detail,{error:{message:"Unknown or unsupported to-widget action: "+I.detail.action}})}}},{key:"replyVersions",value:function(I){this.transport.reply(I,{supported_versions:n.CurrentApiVersions})}},{key:"getClientVersions",value:function(){var I=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(o.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then(function(j){return I.cachedClientVersions=j.supported_versions,j.supported_versions}).catch(function(j){return console.warn("non-fatal error getting supported client versions: ",j),[]})}},{key:"handleCapabilities",value:function(I){var j=this;return this.capabilitiesFinished?this.transport.reply(I,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then(function(U){return U.includes(n.UnstableApiVersion.MSC2871)?j.once("action:".concat(o.WidgetApiToWidgetAction.NotifyCapabilities),function(K){j.approvedCapabilities=K.detail.data.approved,j.emit("ready")}):j.emit("ready"),j.capabilitiesFinished=!0,j.transport.reply(I,{capabilities:j.requestedCapabilities})})}}]),P}(e.EventEmitter);return ia.WidgetApi=W,ia}var Su={},Jn={};Object.defineProperty(Jn,"__esModule",{value:!0});Jn.VideoConferenceCapabilities=Jn.StickerpickerCapabilities=Jn.MatrixCapabilities=void 0;Jn.getTimelineRoomIDFromCapability=S7;Jn.isTimelineCapability=g7;Jn.isTimelineCapabilityFor=y7;var Nw=function(r){return r.Screenshots="m.capability.screenshot",r.StickerSending="m.sticker",r.AlwaysOnScreen="m.always_on_screen",r.RequiresClient="io.element.requires_client",r.MSC2931Navigate="org.matrix.msc2931.navigate",r.MSC3846TurnServers="town.robin.msc3846.turn_servers",r.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",r.MSC4039UploadFile="org.matrix.msc4039.upload_file",r.MSC4039DownloadFile="org.matrix.msc4039.download_file",r.MSC4157SendDelayedEvent="org.matrix.msc4157.send.delayed_event",r.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",r.MSC4407SendStickyEvent="org.matrix.msc4407.send.sticky_event",r.MSC4407ReceiveStickyEvent="org.matrix.msc4407.receive.sticky_event",r}({});Jn.MatrixCapabilities=Nw;var v7=[Nw.StickerSending];Jn.StickerpickerCapabilities=v7;var m7=[Nw.AlwaysOnScreen];Jn.VideoConferenceCapabilities=m7;function g7(r){return r==null?void 0:r.startsWith("org.matrix.msc2762.timeline:")}function y7(r,e){return r==="org.matrix.msc2762.timeline:".concat(e)}function S7(r){return r.substring(r.indexOf(":")+1)}var Cf={};Object.defineProperty(Cf,"__esModule",{value:!0});Cf.SimpleObservable=void 0;function Hd(r){"@babel/helpers - typeof";return Hd=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Hd(r)}function b7(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_7(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
287
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function _7(r,e){if(r){if(typeof r=="string")return Bk(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Bk(r,e)}}function Bk(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function E7(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function w7(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,ON(n.key),n)}}function T7(r,e,t){return e&&w7(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}function R7(r,e,t){return e=ON(e),e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ON(r){var e=C7(r,"string");return Hd(e)==="symbol"?e:String(e)}function C7(r,e){if(Hd(r)!=="object"||r===null)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(Hd(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}var k7=function(){function r(e){E7(this,r),R7(this,"listeners",[]),e&&this.listeners.push(e)}return T7(r,[{key:"onUpdate",value:function(t){this.listeners.push(t)}},{key:"update",value:function(t){var n=b7(this.listeners),i;try{for(n.s();!(i=n.n()).done;){var o=i.value;o(t)}}catch(s){n.e(s)}finally{n.f()}}},{key:"close",value:function(){this.listeners=[]}}]),r}();Cf.SimpleObservable=k7;var Kk;function I7(){if(Kk)return Su;Kk=1,Object.defineProperty(Su,"__esModule",{value:!0}),Su.ClientWidgetApi=void 0;var r=fm,e=Dw(),t=Xa,n=Ls,i=Jn,o=Qi,s=Zi,a=Wc,l=Cf,c=qc,u=Gc;function d(B){"@babel/helpers - typeof";return d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(W){return typeof W}:function(W){return W&&typeof Symbol=="function"&&W.constructor===Symbol&&W!==Symbol.prototype?"symbol":typeof W},d(B)}function f(B,W){var A=Object.keys(B);if(Object.getOwnPropertySymbols){var D=Object.getOwnPropertySymbols(B);W&&(D=D.filter(function(P){return Object.getOwnPropertyDescriptor(B,P).enumerable})),A.push.apply(A,D)}return A}function p(B){for(var W=1;W<arguments.length;W++){var A=arguments[W]!=null?arguments[W]:{};W%2?f(Object(A),!0).forEach(function(D){q(B,D,A[D])}):Object.getOwnPropertyDescriptors?Object.defineProperties(B,Object.getOwnPropertyDescriptors(A)):f(Object(A)).forEach(function(D){Object.defineProperty(B,D,Object.getOwnPropertyDescriptor(A,D))})}return B}function h(B,W){var A=typeof Symbol<"u"&&B[Symbol.iterator]||B["@@iterator"];if(!A){if(Array.isArray(B)||(A=g(B))||W){A&&(B=A);var D=0,P=function(){};return{s:P,n:function(){return D>=B.length?{done:!0}:{done:!1,value:B[D++]}},e:function(K){throw K},f:P}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
288
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var M=!0,I=!1,j;return{s:function(){A=A.call(B)},n:function(){var K=A.next();return M=K.done,K},e:function(K){I=!0,j=K},f:function(){try{!M&&A.return!=null&&A.return()}finally{if(I)throw j}}}}function m(B){return R(B)||b(B)||g(B)||w()}function w(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
289
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function g(B,W){if(B){if(typeof B=="string")return k(B,W);var A=Object.prototype.toString.call(B).slice(8,-1);if(A==="Object"&&B.constructor&&(A=B.constructor.name),A==="Map"||A==="Set")return Array.from(B);if(A==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A))return k(B,W)}}function b(B){if(typeof Symbol<"u"&&B[Symbol.iterator]!=null||B["@@iterator"]!=null)return Array.from(B)}function R(B){if(Array.isArray(B))return k(B)}function k(B,W){(W==null||W>B.length)&&(W=B.length);for(var A=0,D=new Array(W);A<W;A++)D[A]=B[A];return D}function O(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */O=function(){return B};var B={},W=Object.prototype,A=W.hasOwnProperty,D=Object.defineProperty||function(ye,de,J){ye[de]=J.value},P=typeof Symbol=="function"?Symbol:{},M=P.iterator||"@@iterator",I=P.asyncIterator||"@@asyncIterator",j=P.toStringTag||"@@toStringTag";function U(ye,de,J){return Object.defineProperty(ye,de,{value:J,enumerable:!0,configurable:!0,writable:!0}),ye[de]}try{U({},"")}catch{U=function(J,te,ne){return J[te]=ne}}function K(ye,de,J,te){var ne=de&&de.prototype instanceof se?de:se,ue=Object.create(ne.prototype),_e=new mr(te||[]);return D(ue,"_invoke",{value:un(ye,J,_e)}),ue}function G(ye,de,J){try{return{type:"normal",arg:ye.call(de,J)}}catch(te){return{type:"throw",arg:te}}}B.wrap=K;var ee={};function se(){}function Ce(){}function Re(){}var ge={};U(ge,M,function(){return this});var He=Object.getPrototypeOf,Qe=He&&He(He(Rt([])));Qe&&Qe!==W&&A.call(Qe,M)&&(ge=Qe);var $e=Re.prototype=se.prototype=Object.create(ge);function ve(ye){["next","throw","return"].forEach(function(de){U(ye,de,function(J){return this._invoke(de,J)})})}function We(ye,de){function J(ne,ue,_e,we){var ze=G(ye[ne],ye,ue);if(ze.type!=="throw"){var dt=ze.arg,ht=dt.value;return ht&&d(ht)=="object"&&A.call(ht,"__await")?de.resolve(ht.__await).then(function(Bt){J("next",Bt,_e,we)},function(Bt){J("throw",Bt,_e,we)}):de.resolve(ht).then(function(Bt){dt.value=Bt,_e(dt)},function(Bt){return J("throw",Bt,_e,we)})}we(ze.arg)}var te;D(this,"_invoke",{value:function(ue,_e){function we(){return new de(function(ze,dt){J(ue,_e,ze,dt)})}return te=te?te.then(we,we):we()}})}function un(ye,de,J){var te="suspendedStart";return function(ne,ue){if(te==="executing")throw new Error("Generator is already running");if(te==="completed"){if(ne==="throw")throw ue;return Rn()}for(J.method=ne,J.arg=ue;;){var _e=J.delegate;if(_e){var we=Rr(_e,J);if(we){if(we===ee)continue;return we}}if(J.method==="next")J.sent=J._sent=J.arg;else if(J.method==="throw"){if(te==="suspendedStart")throw te="completed",J.arg;J.dispatchException(J.arg)}else J.method==="return"&&J.abrupt("return",J.arg);te="executing";var ze=G(ye,de,J);if(ze.type==="normal"){if(te=J.done?"completed":"suspendedYield",ze.arg===ee)continue;return{value:ze.arg,done:J.done}}ze.type==="throw"&&(te="completed",J.method="throw",J.arg=ze.arg)}}}function Rr(ye,de){var J=de.method,te=ye.iterator[J];if(te===void 0)return de.delegate=null,J==="throw"&&ye.iterator.return&&(de.method="return",de.arg=void 0,Rr(ye,de),de.method==="throw")||J!=="return"&&(de.method="throw",de.arg=new TypeError("The iterator does not provide a '"+J+"' method")),ee;var ne=G(te,ye.iterator,de.arg);if(ne.type==="throw")return de.method="throw",de.arg=ne.arg,de.delegate=null,ee;var ue=ne.arg;return ue?ue.done?(de[ye.resultName]=ue.value,de.next=ye.nextLoc,de.method!=="return"&&(de.method="next",de.arg=void 0),de.delegate=null,ee):ue:(de.method="throw",de.arg=new TypeError("iterator result is not an object"),de.delegate=null,ee)}function gt(ye){var de={tryLoc:ye[0]};1 in ye&&(de.catchLoc=ye[1]),2 in ye&&(de.finallyLoc=ye[2],de.afterLoc=ye[3]),this.tryEntries.push(de)}function vr(ye){var de=ye.completion||{};de.type="normal",delete de.arg,ye.completion=de}function mr(ye){this.tryEntries=[{tryLoc:"root"}],ye.forEach(gt,this),this.reset(!0)}function Rt(ye){if(ye){var de=ye[M];if(de)return de.call(ye);if(typeof ye.next=="function")return ye;if(!isNaN(ye.length)){var J=-1,te=function ne(){for(;++J<ye.length;)if(A.call(ye,J))return ne.value=ye[J],ne.done=!1,ne;return ne.value=void 0,ne.done=!0,ne};return te.next=te}}return{next:Rn}}function Rn(){return{value:void 0,done:!0}}return Ce.prototype=Re,D($e,"constructor",{value:Re,configurable:!0}),D(Re,"constructor",{value:Ce,configurable:!0}),Ce.displayName=U(Re,j,"GeneratorFunction"),B.isGeneratorFunction=function(ye){var de=typeof ye=="function"&&ye.constructor;return!!de&&(de===Ce||(de.displayName||de.name)==="GeneratorFunction")},B.mark=function(ye){return Object.setPrototypeOf?Object.setPrototypeOf(ye,Re):(ye.__proto__=Re,U(ye,j,"GeneratorFunction")),ye.prototype=Object.create($e),ye},B.awrap=function(ye){return{__await:ye}},ve(We.prototype),U(We.prototype,I,function(){return this}),B.AsyncIterator=We,B.async=function(ye,de,J,te,ne){ne===void 0&&(ne=Promise);var ue=new We(K(ye,de,J,te),ne);return B.isGeneratorFunction(de)?ue:ue.next().then(function(_e){return _e.done?_e.value:ue.next()})},ve($e),U($e,j,"Generator"),U($e,M,function(){return this}),U($e,"toString",function(){return"[object Generator]"}),B.keys=function(ye){var de=Object(ye),J=[];for(var te in de)J.push(te);return J.reverse(),function ne(){for(;J.length;){var ue=J.pop();if(ue in de)return ne.value=ue,ne.done=!1,ne}return ne.done=!0,ne}},B.values=Rt,mr.prototype={constructor:mr,reset:function(de){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(vr),!de)for(var J in this)J.charAt(0)==="t"&&A.call(this,J)&&!isNaN(+J.slice(1))&&(this[J]=void 0)},stop:function(){this.done=!0;var de=this.tryEntries[0].completion;if(de.type==="throw")throw de.arg;return this.rval},dispatchException:function(de){if(this.done)throw de;var J=this;function te(dt,ht){return _e.type="throw",_e.arg=de,J.next=dt,ht&&(J.method="next",J.arg=void 0),!!ht}for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ue=this.tryEntries[ne],_e=ue.completion;if(ue.tryLoc==="root")return te("end");if(ue.tryLoc<=this.prev){var we=A.call(ue,"catchLoc"),ze=A.call(ue,"finallyLoc");if(we&&ze){if(this.prev<ue.catchLoc)return te(ue.catchLoc,!0);if(this.prev<ue.finallyLoc)return te(ue.finallyLoc)}else if(we){if(this.prev<ue.catchLoc)return te(ue.catchLoc,!0)}else{if(!ze)throw new Error("try statement without catch or finally");if(this.prev<ue.finallyLoc)return te(ue.finallyLoc)}}}},abrupt:function(de,J){for(var te=this.tryEntries.length-1;te>=0;--te){var ne=this.tryEntries[te];if(ne.tryLoc<=this.prev&&A.call(ne,"finallyLoc")&&this.prev<ne.finallyLoc){var ue=ne;break}}ue&&(de==="break"||de==="continue")&&ue.tryLoc<=J&&J<=ue.finallyLoc&&(ue=null);var _e=ue?ue.completion:{};return _e.type=de,_e.arg=J,ue?(this.method="next",this.next=ue.finallyLoc,ee):this.complete(_e)},complete:function(de,J){if(de.type==="throw")throw de.arg;return de.type==="break"||de.type==="continue"?this.next=de.arg:de.type==="return"?(this.rval=this.arg=de.arg,this.method="return",this.next="end"):de.type==="normal"&&J&&(this.next=J),ee},finish:function(de){for(var J=this.tryEntries.length-1;J>=0;--J){var te=this.tryEntries[J];if(te.finallyLoc===de)return this.complete(te.completion,te.afterLoc),vr(te),ee}},catch:function(de){for(var J=this.tryEntries.length-1;J>=0;--J){var te=this.tryEntries[J];if(te.tryLoc===de){var ne=te.completion;if(ne.type==="throw"){var ue=ne.arg;vr(te)}return ue}}throw new Error("illegal catch attempt")},delegateYield:function(de,J,te){return this.delegate={iterator:Rt(de),resultName:J,nextLoc:te},this.method==="next"&&(this.arg=void 0),ee}},B}function T(B,W,A,D,P,M,I){try{var j=B[M](I),U=j.value}catch(K){A(K);return}j.done?W(U):Promise.resolve(U).then(D,P)}function x(B){return function(){var W=this,A=arguments;return new Promise(function(D,P){var M=B.apply(W,A);function I(U){T(M,D,P,I,j,"next",U)}function j(U){T(M,D,P,I,j,"throw",U)}I(void 0)})}}function C(B,W){if(!(B instanceof W))throw new TypeError("Cannot call a class as a function")}function N(B,W){for(var A=0;A<W.length;A++){var D=W[A];D.enumerable=D.enumerable||!1,D.configurable=!0,"value"in D&&(D.writable=!0),Object.defineProperty(B,z(D.key),D)}}function F(B,W,A){return W&&N(B.prototype,W),Object.defineProperty(B,"prototype",{writable:!1}),B}function H(B,W){if(typeof W!="function"&&W!==null)throw new TypeError("Super expression must either be null or a function");B.prototype=Object.create(W&&W.prototype,{constructor:{value:B,writable:!0,configurable:!0}}),Object.defineProperty(B,"prototype",{writable:!1}),W&&ie(B,W)}function ie(B,W){return ie=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(D,P){return D.__proto__=P,D},ie(B,W)}function $(B){var W=re();return function(){var D=ae(B),P;if(W){var M=ae(this).constructor;P=Reflect.construct(D,arguments,M)}else P=D.apply(this,arguments);return X(this,P)}}function X(B,W){if(W&&(d(W)==="object"||typeof W=="function"))return W;if(W!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return oe(B)}function oe(B){if(B===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return B}function re(){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 ae(B){return ae=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(A){return A.__proto__||Object.getPrototypeOf(A)},ae(B)}function q(B,W,A){return W=z(W),W in B?Object.defineProperty(B,W,{value:A,enumerable:!0,configurable:!0,writable:!0}):B[W]=A,B}function z(B){var W=Q(B,"string");return d(W)==="symbol"?W:String(W)}function Q(B,W){if(d(B)!=="object"||B===null)return B;var A=B[Symbol.toPrimitive];if(A!==void 0){var D=A.call(B,W);if(d(D)!=="object")return D;throw new TypeError("@@toPrimitive must return a primitive value.")}return(W==="string"?String:Number)(B)}function Ie(B){var W,A,D,P=2;for(typeof Symbol<"u"&&(A=Symbol.asyncIterator,D=Symbol.iterator);P--;){if(A&&(W=B[A])!=null)return W.call(B);if(D&&(W=B[D])!=null)return new Y(W.call(B));A="@@asyncIterator",D="@@iterator"}throw new TypeError("Object is not async iterable")}function Y(B){function W(A){if(Object(A)!==A)return Promise.reject(new TypeError(A+" is not an object."));var D=A.done;return Promise.resolve(A.value).then(function(P){return{value:P,done:D}})}return Y=function(D){this.s=D,this.n=D.next},Y.prototype={s:null,n:null,next:function(){return W(this.n.apply(this.s,arguments))},return:function(D){var P=this.s.return;return P===void 0?Promise.resolve({value:D,done:!0}):W(P.apply(this.s,arguments))},throw:function(D){var P=this.s.return;return P===void 0?Promise.reject(D):W(P.apply(this.s,arguments))}},new Y(B)}var le=function(B){H(A,B);var W=$(A);function A(D,P,M){var I;if(C(this,A),I=W.call(this),I.widget=D,I.driver=M,q(oe(I),"transport",void 0),q(oe(I),"cachedWidgetVersions",null),q(oe(I),"contentLoadedActionSent",!1),q(oe(I),"allowedCapabilities",new Set),q(oe(I),"allowedEvents",[]),q(oe(I),"isStopped",!1),q(oe(I),"turnServers",null),q(oe(I),"contentLoadedWaitTimer",void 0),q(oe(I),"pushRoomStateTasks",new Set),q(oe(I),"pushRoomStateResult",new Map),q(oe(I),"flushRoomStateTask",null),q(oe(I),"viewedRoomId",null),!(P!=null&&P.contentWindow))throw new Error("No iframe supplied");if(!D)throw new Error("Invalid widget");if(!M)throw new Error("Invalid driver");return I.transport=new e.PostmessageTransport(t.WidgetApiDirection.ToWidget,D.id,P.contentWindow,globalThis),I.transport.targetOrigin=D.origin,I.transport.on("message",I.handleMessage.bind(oe(I))),P.addEventListener("load",I.onIframeLoad.bind(oe(I))),I.transport.start(),I}return F(A,[{key:"hasCapability",value:function(P){return this.allowedCapabilities.has(P)}},{key:"canUseRoomTimeline",value:function(P){return this.hasCapability("org.matrix.msc2762.timeline:".concat(c.Symbols.AnyRoom))||this.hasCapability("org.matrix.msc2762.timeline:".concat(P))}},{key:"canSendRoomEvent",value:function(P){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(I){return I.matchesAsRoomEvent(s.EventDirection.Send,P,M)})}},{key:"canSendStateEvent",value:function(P,M){return this.allowedEvents.some(function(I){return I.matchesAsStateEvent(s.EventDirection.Send,P,M)})}},{key:"canSendToDeviceEvent",value:function(P){return this.allowedEvents.some(function(M){return M.matchesAsToDeviceEvent(s.EventDirection.Send,P)})}},{key:"canReceiveRoomEvent",value:function(P){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(I){return I.matchesAsRoomEvent(s.EventDirection.Receive,P,M)})}},{key:"canReceiveStateEvent",value:function(P,M){return this.allowedEvents.some(function(I){return I.matchesAsStateEvent(s.EventDirection.Receive,P,M)})}},{key:"canReceiveToDeviceEvent",value:function(P){return this.allowedEvents.some(function(M){return M.matchesAsToDeviceEvent(s.EventDirection.Receive,P)})}},{key:"canReceiveRoomAccountData",value:function(P){return this.allowedEvents.some(function(M){return M.matchesAsRoomAccountData(s.EventDirection.Receive,P)})}},{key:"stop",value:function(){this.isStopped=!0,this.transport.stop()}},{key:"getWidgetVersions",value:function(){var D=x(O().mark(function M(){var I;return O().wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(!Array.isArray(this.cachedWidgetVersions)){U.next=2;break}return U.abrupt("return",this.cachedWidgetVersions);case 2:return U.prev=2,U.next=5,this.transport.send(n.WidgetApiToWidgetAction.SupportedApiVersions,{});case 5:return I=U.sent,this.cachedWidgetVersions=I.supported_versions,U.abrupt("return",I.supported_versions);case 10:return U.prev=10,U.t0=U.catch(2),console.warn("non-fatal error getting supported widget versions: ",U.t0),U.abrupt("return",[]);case 14:case"end":return U.stop()}},M,this,[[2,10]])}));function P(){return D.apply(this,arguments)}return P}()},{key:"beginCapabilities",value:function(){var P=this;this.emit("preparing");var M;this.transport.send(n.WidgetApiToWidgetAction.Capabilities,{}).then(function(I){return M=I.capabilities,P.driver.validateCapabilities(new Set(I.capabilities))}).then(function(I){P.allowCapabilities(m(I),M),P.emit("ready")}).catch(function(I){P.emit("error:preparing",I)})}},{key:"allowCapabilities",value:function(P,M){var I,j=this;console.log("Widget ".concat(this.widget.id," is allowed capabilities:"),P);var U=h(P),K;try{for(U.s();!(K=U.n()).done;){var G=K.value;this.allowedCapabilities.add(G)}}catch(gt){U.e(gt)}finally{U.f()}var ee=s.WidgetEventCapability.findEventCapabilities(P);(I=this.allowedEvents).push.apply(I,m(ee)),this.transport.send(n.WidgetApiToWidgetAction.NotifyCapabilities,{requested:M,approved:Array.from(this.allowedCapabilities)}).catch(function(gt){console.warn("non-fatal error notifying widget of approved capabilities:",gt)}).then(function(){j.emit("capabilitiesNotified")});var se=h(P),Ce;try{for(se.s();!(Ce=se.n()).done;){var Re=Ce.value;if((0,i.isTimelineCapability)(Re)){var ge=(0,i.getTimelineRoomIDFromCapability)(Re);if(ge===c.Symbols.AnyRoom){var He=h(this.driver.getKnownRooms()),Qe;try{for(He.s();!(Qe=He.n()).done;){var $e=Qe.value;this.pushRoomState($e)}}catch(gt){He.e(gt)}finally{He.f()}}else this.pushRoomState(ge)}}}catch(gt){se.e(gt)}finally{se.f()}if(P.includes(i.MatrixCapabilities.MSC4407ReceiveStickyEvent)){console.debug("Widget ".concat(this.widget.id," is allowed to receive sticky events, check current sticky state."));var ve=P.filter(function(gt){return(0,i.isTimelineCapability)(gt)}).map(function(gt){return(0,i.getTimelineRoomIDFromCapability)(gt)}).flatMap(function(gt){return gt===c.Symbols.AnyRoom?j.driver.getKnownRooms():gt});console.debug("Widget ".concat(this.widget.id," is allowed to receive sticky events in rooms:"),ve);var We=h(ve),un;try{var Rr=function(){var vr=un.value;j.pushStickyState(vr).catch(function(mr){console.error("Failed to push sticky events to widget ".concat(j.widget.id," for room ").concat(vr,":"),mr)})};for(We.s();!(un=We.n()).done;)Rr()}catch(gt){We.e(gt)}finally{We.f()}}ee.length>0&&this.viewedRoomId!==null&&!this.canUseRoomTimeline(this.viewedRoomId)&&this.pushRoomState(this.viewedRoomId)}},{key:"onIframeLoad",value:function(P){this.widget.waitForIframeLoad?this.beginCapabilities():(console.log("waitForIframeLoad is false: waiting for widget to send contentLoaded"),this.contentLoadedWaitTimer=setTimeout(function(){console.error("Widget specified waitForIframeLoad=false but timed out waiting for contentLoaded event!")},1e4),this.contentLoadedActionSent=!1)}},{key:"handleContentLoadedAction",value:function(P){if(this.contentLoadedWaitTimer!==void 0&&(clearTimeout(this.contentLoadedWaitTimer),this.contentLoadedWaitTimer=void 0),this.contentLoadedActionSent)throw new Error("Improper sequence: ContentLoaded Action can only be sent 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 waitForIframeLoad is true (default=true)"}}):(this.transport.reply(P,{}),this.beginCapabilities()),this.contentLoadedActionSent=!0}},{key:"replyVersions",value:function(P){this.transport.reply(P,{supported_versions:o.CurrentApiVersions})}},{key:"supportsUpdateState",value:function(){var D=x(O().mark(function M(){return O().wrap(function(j){for(;;)switch(j.prev=j.next){case 0:return j.next=2,this.getWidgetVersions();case 2:return j.abrupt("return",j.sent.includes(o.UnstableApiVersion.MSC2762_UPDATE_STATE));case 3:case"end":return j.stop()}},M,this)}));function P(){return D.apply(this,arguments)}return P}()},{key:"handleCapabilitiesRenegotiate",value:function(P){var M,I=this;this.transport.reply(P,{});var j=((M=P.data)===null||M===void 0?void 0:M.capabilities)||[],U=new Set(j.filter(function(K){return!I.hasCapability(K)}));U.size===0&&this.allowCapabilities([],[]),this.driver.validateCapabilities(U).then(function(K){return I.allowCapabilities(m(K),m(U))})}},{key:"handleNavigate",value:function(P){var M,I=this;if(!this.hasCapability(i.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(P,{error:{message:"Missing capability"}});if(!((M=P.data)!==null&&M!==void 0&&M.uri.startsWith("https://matrix.to/#")))return this.transport.reply(P,{error:{message:"Invalid matrix.to URI"}});var j=function(K){console.error("[ClientWidgetApi] Failed to handle navigation: ",K),I.handleDriverError(K,P,"Error handling navigation")};try{this.driver.navigate(P.data.uri.toString()).catch(function(U){return j(U)}).then(function(){return I.transport.reply(P,{})})}catch(U){return j(U)}}},{key:"handleOIDC",value:function(P){var M=this,I=1,j=function(ee,se){return se=se||{},I>1?M.transport.send(n.WidgetApiToWidgetAction.OpenIDCredentials,p({state:ee,original_request_id:P.requestId},se)):M.transport.reply(P,p({state:ee},se))},U=function(ee){return console.error("[ClientWidgetApi] Failed to handle OIDC: ",ee),I>1?j(a.OpenIDRequestState.Blocked):M.transport.reply(P,{error:{message:ee}})},K=new l.SimpleObservable(function(G){if(G.state===a.OpenIDRequestState.PendingUserConfirmation&&I>1)return K.close(),U("client provided out-of-phase response to OIDC flow");if(G.state===a.OpenIDRequestState.PendingUserConfirmation){j(G.state),I++;return}return G.state===a.OpenIDRequestState.Allowed&&!G.token?U("client provided invalid OIDC token for an allowed request"):(G.state===a.OpenIDRequestState.Blocked&&(G.token=void 0),K.close(),j(G.state,G.token))});this.driver.askOpenID(K)}},{key:"handleReadRoomAccountData",value:function(P){var M=this,I=this.driver.readRoomAccountData(P.data.type);return this.canReceiveRoomAccountData(P.data.type)?I.then(function(j){M.transport.reply(P,{events:j})}):this.transport.reply(P,{error:{message:"Cannot read room account data of this type"}})}},{key:"handleReadEvents",value:function(){var D=x(O().mark(function M(I){var j=this,U,K,G,ee,se,Ce,Re,ge,He,Qe;return O().wrap(function(ve){for(;;)switch(ve.prev=ve.next){case 0:if(I.data.type){ve.next=2;break}return ve.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - missing event type"}}));case 2:if(!(I.data.limit!==void 0&&(!I.data.limit||I.data.limit<0))){ve.next=4;break}return ve.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - limit out of range"}}));case 4:if(I.data.room_ids!==void 0){ve.next=8;break}U=this.viewedRoomId===null?[]:[this.viewedRoomId],ve.next=30;break;case 8:if(I.data.room_ids!==c.Symbols.AnyRoom){ve.next=12;break}U=this.driver.getKnownRooms().filter(function(We){return j.canUseRoomTimeline(We)}),ve.next=30;break;case 12:U=I.data.room_ids,K=h(U),ve.prev=14,K.s();case 16:if((G=K.n()).done){ve.next=22;break}if(ee=G.value,this.canUseRoomTimeline(ee)){ve.next=20;break}return ve.abrupt("return",this.transport.reply(I,{error:{message:"Unable to access room timeline: ".concat(ee)}}));case 20:ve.next=16;break;case 22:ve.next=27;break;case 24:ve.prev=24,ve.t0=ve.catch(14),K.e(ve.t0);case 27:return ve.prev=27,K.f(),ve.finish(27);case 30:if(se=I.data.limit||0,Ce=I.data.since,Re=void 0,ge=void 0,I.data.state_key===void 0){ve.next=40;break}if(Re=I.data.state_key===!0?void 0:I.data.state_key.toString(),this.canReceiveStateEvent(I.data.type,(He=Re)!==null&&He!==void 0?He:null)){ve.next=38;break}return ve.abrupt("return",this.transport.reply(I,{error:{message:"Cannot read state events of this type"}}));case 38:ve.next=43;break;case 40:if(ge=I.data.msgtype,this.canReceiveRoomEvent(I.data.type,ge)){ve.next=43;break}return ve.abrupt("return",this.transport.reply(I,{error:{message:"Cannot read room events of this type"}}));case 43:if(!(I.data.room_ids===void 0&&U.length===0)){ve.next=50;break}return console.warn("The widgetDriver uses deprecated behaviour:\n It does not set the viewedRoomId using `setViewedRoomId`"),ve.next=47,I.data.state_key===void 0?this.driver.readRoomEvents(I.data.type,ge,se,null,Ce):this.driver.readStateEvents(I.data.type,Re,se,null);case 47:Qe=ve.sent,ve.next=68;break;case 50:return ve.next=52,this.supportsUpdateState();case 52:if(!ve.sent){ve.next=58;break}return ve.next=55,Promise.all(U.map(function(We){return j.driver.readRoomTimeline(We,I.data.type,ge,Re,se,Ce)}));case 55:Qe=ve.sent.flat(1),ve.next=68;break;case 58:if(I.data.state_key!==void 0){ve.next=64;break}return ve.next=61,Promise.all(U.map(function(We){return j.driver.readRoomTimeline(We,I.data.type,ge,Re,se,Ce)}));case 61:ve.t1=ve.sent,ve.next=67;break;case 64:return ve.next=66,Promise.all(U.map(function(We){return j.driver.readRoomState(We,I.data.type,Re)}));case 66:ve.t1=ve.sent;case 67:Qe=ve.t1.flat(1);case 68:this.transport.reply(I,{events:Qe});case 69:case"end":return ve.stop()}},M,this,[[14,24,27,30]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleSendEvent",value:function(P){var M=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 I=P.data.delay!==void 0||P.data.parent_delay_id!==void 0;if(I&&!this.hasCapability(i.MatrixCapabilities.MSC4157SendDelayedEvent))return this.transport.reply(P,{error:{message:"Missing capability for ".concat(i.MatrixCapabilities.MSC4157SendDelayedEvent)}});var j=P.data.sticky_duration_ms!==void 0;if(j&&!this.hasCapability(i.MatrixCapabilities.MSC4407SendStickyEvent))return this.transport.reply(P,{error:{message:"Missing capability for ".concat(i.MatrixCapabilities.MSC4407SendStickyEvent)}});var U;if(P.data.state_key!==void 0){if(!this.canSendStateEvent(P.data.type,P.data.state_key))return this.transport.reply(P,{error:{message:"Cannot send state events of this type"}});if(j)return this.transport.reply(P,{error:{message:"Cannot send a state event with a sticky duration"}});if(I){var K,G;U=this.driver.sendDelayedEvent((K=P.data.delay)!==null&&K!==void 0?K:null,(G=P.data.parent_delay_id)!==null&&G!==void 0?G:null,P.data.type,P.data.content||{},P.data.state_key,P.data.room_id)}else U=this.driver.sendEvent(P.data.type,P.data.content||{},P.data.state_key,P.data.room_id)}else{var ee=P.data.content||{},se=ee.msgtype;if(!this.canSendRoomEvent(P.data.type,se))return this.transport.reply(P,{error:{message:"Cannot send room events of this type"}});var Ce=[P.data.type,ee,null,P.data.room_id];if(I&&P.data.sticky_duration_ms){var Re,ge;U=this.driver.sendDelayedStickyEvent((Re=P.data.delay)!==null&&Re!==void 0?Re:null,(ge=P.data.parent_delay_id)!==null&&ge!==void 0?ge:null,P.data.sticky_duration_ms,P.data.type,ee,P.data.room_id)}else if(I){var He,Qe,$e;U=(He=this.driver).sendDelayedEvent.apply(He,[(Qe=P.data.delay)!==null&&Qe!==void 0?Qe:null,($e=P.data.parent_delay_id)!==null&&$e!==void 0?$e:null].concat(Ce))}else if(P.data.sticky_duration_ms)U=this.driver.sendStickyEvent(P.data.sticky_duration_ms,P.data.type,ee,P.data.room_id);else{var ve;U=(ve=this.driver).sendEvent.apply(ve,Ce)}}U.then(function(We){return M.transport.reply(P,p({room_id:We.roomId},"eventId"in We?{event_id:We.eventId}:{delay_id:We.delayId}))}).catch(function(We){console.error("error sending event: ",We),M.handleDriverError(We,P,"Error sending event")})}},{key:"handleUpdateDelayedEvent",value:function(P){var M=this;if(!P.data.delay_id)return this.transport.reply(P,{error:{message:"Invalid request - missing delay_id"}});if(!this.hasCapability(i.MatrixCapabilities.MSC4157UpdateDelayedEvent))return this.transport.reply(P,{error:{message:"Missing capability"}});var I;switch(P.data.action){case u.UpdateDelayedEventAction.Cancel:I=this.driver.cancelScheduledDelayedEvent;break;case u.UpdateDelayedEventAction.Restart:I=this.driver.restartScheduledDelayedEvent;break;case u.UpdateDelayedEventAction.Send:I=this.driver.sendScheduledDelayedEvent;break;default:return this.transport.reply(P,{error:{message:"Invalid request - unsupported action"}})}I.call(this.driver,P.data.delay_id).then(function(){return M.transport.reply(P,{})}).catch(function(j){console.error("error updating delayed event: ",j),M.handleDriverError(j,P,"Error updating delayed event")})}},{key:"handleSendToDevice",value:function(){var D=x(O().mark(function M(I){return O().wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(I.data.type){U.next=4;break}this.transport.reply(I,{error:{message:"Invalid request - missing event type"}}),U.next=26;break;case 4:if(I.data.messages){U.next=8;break}this.transport.reply(I,{error:{message:"Invalid request - missing event contents"}}),U.next=26;break;case 8:if(typeof I.data.encrypted=="boolean"){U.next=12;break}this.transport.reply(I,{error:{message:"Invalid request - missing encryption flag"}}),U.next=26;break;case 12:if(this.canSendToDeviceEvent(I.data.type)){U.next=16;break}this.transport.reply(I,{error:{message:"Cannot send to-device events of this type"}}),U.next=26;break;case 16:return U.prev=16,U.next=19,this.driver.sendToDevice(I.data.type,I.data.encrypted,I.data.messages);case 19:this.transport.reply(I,{}),U.next=26;break;case 22:U.prev=22,U.t0=U.catch(16),console.error("error sending to-device event",U.t0),this.handleDriverError(U.t0,I,"Error sending event");case 26:case"end":return U.stop()}},M,this,[[16,22]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"pollTurnServers",value:function(){var D=x(O().mark(function M(I,j){var U,K,G,ee,se,Ce;return O().wrap(function(ge){for(;;)switch(ge.prev=ge.next){case 0:return ge.prev=0,ge.next=3,this.transport.send(n.WidgetApiToWidgetAction.UpdateTurnServers,j);case 3:U=!1,K=!1,ge.prev=5,ee=Ie(I);case 7:return ge.next=9,ee.next();case 9:if(!(U=!(se=ge.sent).done)){ge.next=16;break}return Ce=se.value,ge.next=13,this.transport.send(n.WidgetApiToWidgetAction.UpdateTurnServers,Ce);case 13:U=!1,ge.next=7;break;case 16:ge.next=22;break;case 18:ge.prev=18,ge.t0=ge.catch(5),K=!0,G=ge.t0;case 22:if(ge.prev=22,ge.prev=23,!(U&&ee.return!=null)){ge.next=27;break}return ge.next=27,ee.return();case 27:if(ge.prev=27,!K){ge.next=30;break}throw G;case 30:return ge.finish(27);case 31:return ge.finish(22);case 32:ge.next=37;break;case 34:ge.prev=34,ge.t1=ge.catch(0),console.error("error polling for TURN servers",ge.t1);case 37:case"end":return ge.stop()}},M,this,[[0,34],[5,18,22,32],[23,,27,31]])}));function P(M,I){return D.apply(this,arguments)}return P}()},{key:"handleWatchTurnServers",value:function(){var D=x(O().mark(function M(I){var j,U,K,G;return O().wrap(function(se){for(;;)switch(se.prev=se.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC3846TurnServers)){se.next=4;break}this.transport.reply(I,{error:{message:"Missing capability"}}),se.next=26;break;case 4:if(!this.turnServers){se.next=8;break}this.transport.reply(I,{}),se.next=26;break;case 8:return se.prev=8,j=this.driver.getTurnServers(),se.next=12,j.next();case 12:if(U=se.sent,K=U.done,G=U.value,!K){se.next=17;break}throw new Error("Client refuses to provide any TURN servers");case 17:this.transport.reply(I,{}),this.pollTurnServers(j,G),this.turnServers=j,se.next=26;break;case 22:se.prev=22,se.t0=se.catch(8),console.error("error getting first TURN server results",se.t0),this.transport.reply(I,{error:{message:"TURN servers not available"}});case 26:case"end":return se.stop()}},M,this,[[8,22]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleUnwatchTurnServers",value:function(){var D=x(O().mark(function M(I){return O().wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC3846TurnServers)){U.next=4;break}this.transport.reply(I,{error:{message:"Missing capability"}}),U.next=12;break;case 4:if(this.turnServers){U.next=8;break}this.transport.reply(I,{}),U.next=12;break;case 8:return U.next=10,this.turnServers.return(void 0);case 10:this.turnServers=null,this.transport.reply(I,{});case 12:case"end":return U.stop()}},M,this)}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleReadRelations",value:function(){var D=x(O().mark(function M(I){var j=this,U,K;return O().wrap(function(ee){for(;;)switch(ee.prev=ee.next){case 0:if(I.data.event_id){ee.next=2;break}return ee.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - missing event ID"}}));case 2:if(!(I.data.limit!==void 0&&I.data.limit<0)){ee.next=4;break}return ee.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - limit out of range"}}));case 4:if(!(I.data.room_id!==void 0&&!this.canUseRoomTimeline(I.data.room_id))){ee.next=6;break}return ee.abrupt("return",this.transport.reply(I,{error:{message:"Unable to access room timeline: ".concat(I.data.room_id)}}));case 6:return ee.prev=6,ee.next=9,this.driver.readEventRelations(I.data.event_id,I.data.room_id,I.data.rel_type,I.data.event_type,I.data.from,I.data.to,I.data.limit,I.data.direction);case 9:return U=ee.sent,K=U.chunk.filter(function(se){return se.state_key!==void 0?j.canReceiveStateEvent(se.type,se.state_key):j.canReceiveRoomEvent(se.type,se.content.msgtype)}),ee.abrupt("return",this.transport.reply(I,{chunk:K,prev_batch:U.prevBatch,next_batch:U.nextBatch}));case 14:ee.prev=14,ee.t0=ee.catch(6),console.error("error getting the relations",ee.t0),this.handleDriverError(ee.t0,I,"Unexpected error while reading relations");case 18:case"end":return ee.stop()}},M,this,[[6,14]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleUserDirectorySearch",value:function(){var D=x(O().mark(function M(I){var j;return O().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC3973UserDirectorySearch)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:if(typeof I.data.search_term=="string"){K.next=4;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - missing search term"}}));case 4:if(!(I.data.limit!==void 0&&I.data.limit<0)){K.next=6;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - limit out of range"}}));case 6:return K.prev=6,K.next=9,this.driver.searchUserDirectory(I.data.search_term,I.data.limit);case 9:return j=K.sent,K.abrupt("return",this.transport.reply(I,{limited:j.limited,results:j.results.map(function(G){return{user_id:G.userId,display_name:G.displayName,avatar_url:G.avatarUrl}})}));case 13:K.prev=13,K.t0=K.catch(6),console.error("error searching in the user directory",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while searching in the user directory");case 17:case"end":return K.stop()}},M,this,[[6,13]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleGetMediaConfig",value:function(){var D=x(O().mark(function M(I){var j;return O().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC4039UploadFile)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:return K.prev=2,K.next=5,this.driver.getMediaConfig();case 5:return j=K.sent,K.abrupt("return",this.transport.reply(I,j));case 9:K.prev=9,K.t0=K.catch(2),console.error("error while getting the media configuration",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while getting the media configuration");case 13:case"end":return K.stop()}},M,this,[[2,9]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleUploadFile",value:function(){var D=x(O().mark(function M(I){var j;return O().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC4039UploadFile)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:return K.prev=2,K.next=5,this.driver.uploadFile(I.data.file);case 5:return j=K.sent,K.abrupt("return",this.transport.reply(I,{content_uri:j.contentUri}));case 9:K.prev=9,K.t0=K.catch(2),console.error("error while uploading a file",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while uploading a file");case 13:case"end":return K.stop()}},M,this,[[2,9]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleDownloadFile",value:function(){var D=x(O().mark(function M(I){var j;return O().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC4039DownloadFile)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:return K.prev=2,K.next=5,this.driver.downloadFile(I.data.content_uri);case 5:return j=K.sent,K.abrupt("return",this.transport.reply(I,{file:j.file}));case 9:K.prev=9,K.t0=K.catch(2),console.error("error while downloading a file",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while downloading a file");case 13:case"end":return K.stop()}},M,this,[[2,9]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleDriverError",value:function(P,M,I){var j=this.driver.processError(P);this.transport.reply(M,{error:p({message:I},j)})}},{key:"handleMessage",value:function(P){if(!this.isStopped){var M=new CustomEvent("action:".concat(P.detail.action),{detail:P.detail,cancelable:!0});if(this.emit("action:".concat(P.detail.action),M),!M.defaultPrevented)switch(P.detail.action){case n.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(P.detail);case n.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(P.detail);case n.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(P.detail);case n.WidgetApiFromWidgetAction.SendToDevice:return this.handleSendToDevice(P.detail);case n.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(P.detail);case n.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(P.detail);case n.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(P.detail);case n.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(P.detail);case n.WidgetApiFromWidgetAction.WatchTurnServers:return this.handleWatchTurnServers(P.detail);case n.WidgetApiFromWidgetAction.UnwatchTurnServers:return this.handleUnwatchTurnServers(P.detail);case n.WidgetApiFromWidgetAction.MSC3869ReadRelations:return this.handleReadRelations(P.detail);case n.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch:return this.handleUserDirectorySearch(P.detail);case n.WidgetApiFromWidgetAction.BeeperReadRoomAccountData:return this.handleReadRoomAccountData(P.detail);case n.WidgetApiFromWidgetAction.MSC4039GetMediaConfigAction:return this.handleGetMediaConfig(P.detail);case n.WidgetApiFromWidgetAction.MSC4039UploadFileAction:return this.handleUploadFile(P.detail);case n.WidgetApiFromWidgetAction.MSC4039DownloadFileAction:return this.handleDownloadFile(P.detail);case n.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent:return this.handleUpdateDelayedEvent(P.detail);default:return this.transport.reply(P.detail,{error:{message:"Unknown or unsupported from-widget action: "+P.detail.action}})}}}},{key:"updateTheme",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.ThemeChange,P)}},{key:"updateLanguage",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.LanguageChange,{lang:P})}},{key:"takeScreenshot",value:function(){return this.transport.send(n.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:"updateVisibility",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.UpdateVisibility,{visible:P})}},{key:"sendWidgetConfig",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.WidgetConfig,P).then()}},{key:"notifyModalWidgetButtonClicked",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.ButtonClicked,{id:P}).then()}},{key:"notifyModalWidgetClose",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.CloseModalWidget,P).then()}},{key:"feedEvent",value:function(){var D=x(O().mark(function M(I,j){var U;return O().wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(j!==void 0&&this.setViewedRoomId(j),!(I.room_id!==this.viewedRoomId&&!this.canUseRoomTimeline(I.room_id))){G.next=3;break}return G.abrupt("return");case 3:if(!(I.state_key!==void 0&&I.state_key!==null)){G.next=8;break}if(this.canReceiveStateEvent(I.type,I.state_key)){G.next=6;break}return G.abrupt("return");case 6:G.next=10;break;case 8:if(this.canReceiveRoomEvent(I.type,(U=I.content)===null||U===void 0?void 0:U.msgtype)){G.next=10;break}return G.abrupt("return");case 10:return G.next=12,this.transport.send(n.WidgetApiToWidgetAction.SendEvent,I);case 12:case"end":return G.stop()}},M,this)}));function P(M,I){return D.apply(this,arguments)}return P}()},{key:"feedToDevice",value:function(){var D=x(O().mark(function M(I,j){return O().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(!this.canReceiveToDeviceEvent(I.type)){K.next=3;break}return K.next=3,this.transport.send(n.WidgetApiToWidgetAction.SendToDevice,p(p({},I),{},{encrypted:j}));case 3:case"end":return K.stop()}},M,this)}));function P(M,I){return D.apply(this,arguments)}return P}()},{key:"setViewedRoomId",value:function(P){this.viewedRoomId=P,P!==null&&!this.canUseRoomTimeline(P)&&this.pushRoomState(P)}},{key:"flushRoomState",value:function(){var D=x(O().mark(function M(){var I,j,U,K,G,ee,se;return O().wrap(function(Re){for(;;)switch(Re.prev=Re.next){case 0:Re.prev=0;case 1:return Re.next=3,Promise.all(this.pushRoomStateTasks);case 3:if(this.pushRoomStateTasks.size>0){Re.next=1;break}case 4:I=[],j=h(this.pushRoomStateResult.values());try{for(j.s();!(U=j.n()).done;){K=U.value,G=h(K.values());try{for(G.s();!(ee=G.n()).done;)se=ee.value,I.push.apply(I,m(se.values()))}catch(ge){G.e(ge)}finally{G.f()}}}catch(ge){j.e(ge)}finally{j.f()}return Re.next=9,this.getWidgetVersions();case 9:if(!Re.sent.includes(o.UnstableApiVersion.MSC2762_UPDATE_STATE)){Re.next=12;break}return Re.next=12,this.transport.send(n.WidgetApiToWidgetAction.UpdateState,{state:I});case 12:return Re.prev=12,this.flushRoomStateTask=null,Re.finish(12);case 15:case"end":return Re.stop()}},M,this,[[0,,12,15]])}));function P(){return D.apply(this,arguments)}return P}()},{key:"pushStickyState",value:function(){var D=x(O().mark(function M(I){var j=this;return O().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:return console.debug("Pushing sticky state to widget for room",I),K.abrupt("return",this.driver.readStickyEvents(I).then(function(G){var ee=G.filter(function(se){var Ce;return j.canReceiveRoomEvent(se.type,typeof((Ce=se.content)===null||Ce===void 0?void 0:Ce.msgtype)=="string"?se.content.msgtype:null)});return{roomId:I,stickyEvents:ee}}).then(function(){var G=x(O().mark(function ee(se){var Ce,Re,ge;return O().wrap(function(Qe){for(;;)switch(Qe.prev=Qe.next){case 0:return Ce=se.roomId,Re=se.stickyEvents,console.debug("Pushing",Re.length,"sticky events to widget for room",Ce),ge=Re.map(function($e){return j.transport.send(n.WidgetApiToWidgetAction.SendEvent,$e)}),Qe.next=5,Promise.all(ge);case 5:case"end":return Qe.stop()}},ee)}));return function(ee){return G.apply(this,arguments)}}()));case 2:case"end":return K.stop()}},M,this)}));function P(M){return D.apply(this,arguments)}return P}()},{key:"pushRoomState",value:function(P){var M=this,I=h(this.allowedEvents),j;try{var U=function(){var G=j.value;if(G.kind===s.EventKind.State&&G.direction===s.EventDirection.Receive){var ee,se,Ce=M.driver.readRoomState(P,G.eventType,(ee=G.keyStr)!==null&&ee!==void 0?ee:void 0),Re=Ce.then(function(ge){var He=h(ge),Qe;try{for(He.s();!(Qe=He.n()).done;){var $e=Qe.value,ve=M.pushRoomStateResult.get(P);ve===void 0&&(ve=new Map,M.pushRoomStateResult.set(P,ve));var We=ve.get(G.eventType);We===void 0&&(We=new Map,ve.set(G.eventType,We)),We.has($e.state_key)||We.set($e.state_key,$e)}}catch(un){He.e(un)}finally{He.f()}},function(ge){return console.error("Failed to read room state for ".concat(P," (").concat(G.eventType,", ").concat(G.keyStr,")"),ge)}).then(function(){M.pushRoomStateTasks.delete(Re)});M.pushRoomStateTasks.add(Re),(se=M.flushRoomStateTask)!==null&&se!==void 0||(M.flushRoomStateTask=M.flushRoomState()),M.flushRoomStateTask.catch(function(ge){return console.error("Failed to push room state",ge)})}};for(I.s();!(j=I.n()).done;)U()}catch(K){I.e(K)}finally{I.f()}}},{key:"feedStateUpdate",value:function(){var D=x(O().mark(function M(I){var j,U;return O().wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(I.state_key!==void 0){G.next=2;break}throw new Error("Not a state event");case 2:if(!((I.room_id===this.viewedRoomId||this.canUseRoomTimeline(I.room_id))&&this.canReceiveStateEvent(I.type,I.state_key))){G.next=21;break}if(this.pushRoomStateTasks.size!==0){G.next=11;break}return G.next=6,this.getWidgetVersions();case 6:if(!G.sent.includes(o.UnstableApiVersion.MSC2762_UPDATE_STATE)){G.next=9;break}return G.next=9,this.transport.send(n.WidgetApiToWidgetAction.UpdateState,{state:[I]});case 9:G.next=21;break;case 11:j=this.pushRoomStateResult.get(I.room_id),j===void 0&&(j=new Map,this.pushRoomStateResult.set(I.room_id,j)),U=j.get(I.type),U===void 0&&(U=new Map,j.set(I.type,U)),U.has(I.type)||U.set(I.state_key,I);case 16:return G.next=18,Promise.all(this.pushRoomStateTasks);case 18:if(this.pushRoomStateTasks.size>0){G.next=16;break}case 19:return G.next=21,this.flushRoomStateTask;case 21:case"end":return G.stop()}},M,this)}));function P(M){return D.apply(this,arguments)}return P}()}]),A}(r.EventEmitter);return Su.ClientWidgetApi=le,Su}var Lw={};Object.defineProperty(Lw,"__esModule",{value:!0});Lw.isErrorResponse=x7;function o_(r){"@babel/helpers - typeof";return o_=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o_(r)}function x7(r){var e=r.error;return o_(e)==="object"&&e!==null&&"message"in e&&typeof e.message=="string"}var wm={};Object.defineProperty(wm,"__esModule",{value:!0});wm.WidgetKind=void 0;var O7=function(r){return r.Room="room",r.Account="account",r.Modal="modal",r}({});wm.WidgetKind=O7;var Tm={};Object.defineProperty(Tm,"__esModule",{value:!0});Tm.ModalButtonKind=void 0;var P7=function(r){return r.Primary="m.primary",r.Secondary="m.secondary",r.Warning="m.warning",r.Danger="m.danger",r.Link="m.link",r}({});Tm.ModalButtonKind=P7;var Rm={};Object.defineProperty(Rm,"__esModule",{value:!0});Rm.isValidUrl=M7;function M7(r){if(!r)return!1;try{var e=new URL(r);return!(e.protocol!=="http"&&e.protocol!=="https")}catch(t){if(t instanceof TypeError)return!1;throw t}}var Cm={};Object.defineProperty(Cm,"__esModule",{value:!0});Cm.assertPresent=A7;function A7(r,e){if(!r[e])throw new Error("".concat(String(e)," is required"))}var bu={},Vk;function PN(){if(Vk)return bu;Vk=1,Object.defineProperty(bu,"__esModule",{value:!0}),bu.Widget=void 0;var r=Im(),e=Cm;function t(c){"@babel/helpers - typeof";return t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(u){return typeof u}:function(u){return u&&typeof Symbol=="function"&&u.constructor===Symbol&&u!==Symbol.prototype?"symbol":typeof u},t(c)}function n(c,u){if(!(c instanceof u))throw new TypeError("Cannot call a class as a function")}function i(c,u){for(var d=0;d<u.length;d++){var f=u[d];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(c,s(f.key),f)}}function o(c,u,d){return u&&i(c.prototype,u),Object.defineProperty(c,"prototype",{writable:!1}),c}function s(c){var u=a(c,"string");return t(u)==="symbol"?u:String(u)}function a(c,u){if(t(c)!=="object"||c===null)return c;var d=c[Symbol.toPrimitive];if(d!==void 0){var f=d.call(c,u);if(t(f)!=="object")return f;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(c)}var l=function(){function c(u){if(n(this,c),this.definition=u,!this.definition)throw new Error("Definition is required");(0,e.assertPresent)(u,"id"),(0,e.assertPresent)(u,"creatorUserId"),(0,e.assertPresent)(u,"type"),(0,e.assertPresent)(u,"url")}return o(c,[{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(d){return(0,r.runTemplate)(this.templateUrl,this.definition,d)}}]),c}();return bu.Widget=l,bu}var _u={},$k;function D7(){if($k)return _u;$k=1,Object.defineProperty(_u,"__esModule",{value:!0}),_u.WidgetParser=void 0;var r=PN(),e=Rm;function t(f){"@babel/helpers - typeof";return t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p},t(f)}function n(f,p){var h=typeof Symbol<"u"&&f[Symbol.iterator]||f["@@iterator"];if(!h){if(Array.isArray(f)||(h=i(f))||p){h&&(f=h);var m=0,w=function(){};return{s:w,n:function(){return m>=f.length?{done:!0}:{done:!1,value:f[m++]}},e:function(O){throw O},f:w}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
290
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var g=!0,b=!1,R;return{s:function(){h=h.call(f)},n:function(){var O=h.next();return g=O.done,O},e:function(O){b=!0,R=O},f:function(){try{!g&&h.return!=null&&h.return()}finally{if(b)throw R}}}}function i(f,p){if(f){if(typeof f=="string")return o(f,p);var h=Object.prototype.toString.call(f).slice(8,-1);if(h==="Object"&&f.constructor&&(h=f.constructor.name),h==="Map"||h==="Set")return Array.from(f);if(h==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(h))return o(f,p)}}function o(f,p){(p==null||p>f.length)&&(p=f.length);for(var h=0,m=new Array(p);h<p;h++)m[h]=f[h];return m}function s(f,p){if(!(f instanceof p))throw new TypeError("Cannot call a class as a function")}function a(f,p){for(var h=0;h<p.length;h++){var m=p[h];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(f,c(m.key),m)}}function l(f,p,h){return h&&a(f,h),Object.defineProperty(f,"prototype",{writable:!1}),f}function c(f){var p=u(f,"string");return t(p)==="symbol"?p:String(p)}function u(f,p){if(t(f)!=="object"||f===null)return f;var h=f[Symbol.toPrimitive];if(h!==void 0){var m=h.call(f,p);if(t(m)!=="object")return m;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(f)}var d=function(){function f(){s(this,f)}return l(f,null,[{key:"parseAccountData",value:function(h){if(!h)return[];for(var m=[],w=0,g=Object.keys(h);w<g.length;w++){var b=g[w],R=h[b];if(R&&!(R.type!=="m.widget"&&R.type!=="im.vector.modular.widgets")&&R.sender){var k=R.state_key||R.id;if(k===b){var O={content:R.content,sender:R.sender,type:"m.widget",state_key:b,event_id:"$example",room_id:"!example",origin_server_ts:1},T=f.parseRoomWidget(O);T&&m.push(T)}}}return m}},{key:"parseWidgetsFromRoomState",value:function(h){if(!h)return[];var m=[],w=n(h),g;try{for(w.s();!(g=w.n()).done;){var b=g.value,R=f.parseRoomWidget(b);R&&m.push(R)}}catch(k){w.e(k)}finally{w.f()}return m}},{key:"parseRoomWidget",value:function(h){if(!h||h.type!=="m.widget"&&h.type!=="im.vector.modular.widgets")return null;var m=h.content||{},w={id:h.state_key,creatorUserId:m.creatorUserId||h.sender,name:m.name,type:m.type,url:m.url,waitForIframeLoad:m.waitForIframeLoad,data:m.data};return f.processEstimatedWidget(w)}},{key:"processEstimatedWidget",value:function(h){return!h.id||!h.creatorUserId||!h.type||!(0,e.isValidUrl)(h.url)?null:new r.Widget(h)}}]),f}();return _u.WidgetParser=d,_u}var km={};Object.defineProperty(km,"__esModule",{value:!0});km.runTemplate=N7;km.toString=MN;function N7(r,e,t){for(var n=Object.assign({},e.data,{matrix_room_id:t.widgetRoomId||"",matrix_user_id:t.currentUserId,matrix_display_name:t.userDisplayName||t.currentUserId,matrix_avatar_url:t.userHttpAvatarUrl||"",matrix_widget_id:e.id,"org.matrix.msc2873.client_id":t.clientId||"","org.matrix.msc2873.client_theme":t.clientTheme||"","org.matrix.msc2873.client_language":t.clientLanguage||"","org.matrix.msc3819.matrix_device_id":t.deviceId||"","org.matrix.msc4039.matrix_base_url":t.baseUrl||""}),i=r,o=0,s=Object.keys(n);o<s.length;o++){var a=s[o],l="$".concat(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(l,"g");i=i.replace(c,encodeURIComponent(MN(n[a])))}return i}function MN(r){return r==null?"".concat(r):String(r)}var Eu={},Wk;function L7(){if(Wk)return Eu;Wk=1,Object.defineProperty(Eu,"__esModule",{value:!0}),Eu.WidgetDriver=void 0;var r=Im();function e(l){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c},e(l)}function t(l,c){if(!(l instanceof c))throw new TypeError("Cannot call a class as a function")}function n(l,c){for(var u=0;u<c.length;u++){var d=c[u];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(l,o(d.key),d)}}function i(l,c,u){return c&&n(l.prototype,c),Object.defineProperty(l,"prototype",{writable:!1}),l}function o(l){var c=s(l,"string");return e(c)==="symbol"?c:String(c)}function s(l,c){if(e(l)!=="object"||l===null)return l;var u=l[Symbol.toPrimitive];if(u!==void 0){var d=u.call(l,c);if(e(d)!=="object")return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(l)}var a=function(){function l(){t(this,l)}return i(l,[{key:"validateCapabilities",value:function(u){return Promise.resolve(new Set)}},{key:"sendEvent",value:function(u,d){return Promise.reject(new Error("Failed to override function"))}},{key:"sendStickyEvent",value:function(u,d,f){throw new Error("Method not implemented.")}},{key:"sendDelayedEvent",value:function(u,d,f,p){return Promise.reject(new Error("Failed to override function"))}},{key:"sendDelayedStickyEvent",value:function(u,d,f,p,h){throw new Error("Method not implemented.")}},{key:"cancelScheduledDelayedEvent",value:function(u){return Promise.reject(new Error("Failed to override function"))}},{key:"restartScheduledDelayedEvent",value:function(u){return Promise.reject(new Error("Failed to override function"))}},{key:"sendScheduledDelayedEvent",value:function(u){return Promise.reject(new Error("Failed to override function"))}},{key:"sendToDevice",value:function(u,d,f){return Promise.reject(new Error("Failed to override function"))}},{key:"readRoomAccountData",value:function(u){return Promise.resolve([])}},{key:"readRoomEvents",value:function(u,d,f){return Promise.resolve([])}},{key:"readStateEvents",value:function(u,d,f){return Promise.resolve([])}},{key:"readStickyEvents",value:function(u){throw new Error("readStickyEvents is not implemented")}},{key:"readRoomTimeline",value:function(u,d,f,p,h,m){return p===void 0?this.readRoomEvents(d,f,h,[u],m):this.readStateEvents(d,p,h,[u])}},{key:"readRoomState",value:function(u,d,f){return this.readStateEvents(d,f,Number.MAX_SAFE_INTEGER,[u])}},{key:"readEventRelations",value:function(u,d,f,p,h,m,w,g){return Promise.resolve({chunk:[]})}},{key:"askOpenID",value:function(u){u.update({state:r.OpenIDRequestState.Blocked})}},{key:"navigate",value:function(u){throw new Error("Navigation is not implemented")}},{key:"getTurnServers",value:function(){throw new Error("TURN server support is not implemented")}},{key:"searchUserDirectory",value:function(u,d){return Promise.resolve({limited:!1,results:[]})}},{key:"getMediaConfig",value:function(){throw new Error("Get media config is not implemented")}},{key:"uploadFile",value:function(u){throw new Error("Upload file is not implemented")}},{key:"downloadFile",value:function(u){throw new Error("Download file is not implemented")}},{key:"getKnownRooms",value:function(){throw new Error("Querying known rooms is not implemented")}},{key:"processError",value:function(u){}}]),l}();return Eu.WidgetDriver=a,Eu}var qk;function Im(){return qk||(qk=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});var e=p7();Object.keys(e).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===e[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return e[C]}})});var t=I7();Object.keys(t).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===t[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return t[C]}})});var n=qc;Object.keys(n).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===n[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return n[C]}})});var i=Dw();Object.keys(i).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===i[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return i[C]}})});var o=Tf;Object.keys(o).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===o[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return o[C]}})});var s=Lw;Object.keys(s).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===s[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return s[C]}})});var a=Ls;Object.keys(a).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===a[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return a[C]}})});var l=Xa;Object.keys(l).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===l[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return l[C]}})});var c=Qi;Object.keys(c).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===c[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return c[C]}})});var u=Jn;Object.keys(u).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===u[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return u[C]}})});var d=Wc;Object.keys(d).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===d[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return d[C]}})});var f=wm;Object.keys(f).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===f[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return f[C]}})});var p=Tm;Object.keys(p).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===p[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return p[C]}})});var h=Rf;Object.keys(h).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===h[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return h[C]}})});var m=Gc;Object.keys(m).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===m[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return m[C]}})});var w=Zi;Object.keys(w).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===w[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return w[C]}})});var g=Rm;Object.keys(g).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===g[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return g[C]}})});var b=Cm;Object.keys(b).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===b[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return b[C]}})});var R=PN();Object.keys(R).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===R[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return R[C]}})});var k=D7();Object.keys(k).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===k[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return k[C]}})});var O=km;Object.keys(O).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===O[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return O[C]}})});var T=Cf;Object.keys(T).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===T[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return T[C]}})});var x=L7();Object.keys(x).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===x[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return x[C]}})})}(sy)),sy}var os=Im();function Gk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function gh(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Gk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Gk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function U7(r){var e,t,n,i=2;for(typeof Symbol<"u"&&(t=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(t&&(e=r[t])!=null)return e.call(r);if(n&&(e=r[n])!=null)return new Zh(e.call(r));t="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function Zh(r){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var n=t.done;return Promise.resolve(t.value).then(function(i){return{value:i,done:n}})}return Zh=function(n){this.s=n,this.n=n.next},Zh.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(n){var i=this.s.return;return i===void 0?Promise.resolve({value:n,done:!0}):e(i.apply(this.s,arguments))},throw:function(n){var i=this.s.return;return i===void 0?Promise.reject(n):e(i.apply(this.s,arguments))}},new Zh(r)}var ep=function(r){return r.PendingEventsChanged="PendingEvent.pendingEventsChanged",r}({});class AN extends $c{constructor(e,t,n,i,o){var s,a,l,c,u,d,f,p,h,m,w,g,b;super(i),s=this,this.widgetApi=e,this.capabilities=t,this.roomId=n,v(this,"room",void 0),v(this,"widgetApiReady",void 0),v(this,"lifecycle",void 0),v(this,"syncState",null),v(this,"pendingSendingEventsTxId",[]),v(this,"eventEmitter",new Tt),v(this,"updateTxId",function(){var O=_(function*(T){if(T.getSender()===s.getUserId()&&s.pendingSendingEventsTxId.some(F=>T.getType()===F.type)){for(var x,C=(x=s.pendingSendingEventsTxId.find(F=>F.id===T.getId()))===null||x===void 0?void 0:x.txId;!C&&s.pendingSendingEventsTxId.length>0;){var N;yield new Promise(F=>s.eventEmitter.once(ep.PendingEventsChanged,()=>F())),C=(N=s.pendingSendingEventsTxId.find(F=>F.id===T.getId()))===null||N===void 0?void 0:N.txId}C&&(T.setTxnId(C),T.setUnsigned(gh(gh({},T.getUnsigned()),{},{transaction_id:C}))),s.pendingSendingEventsTxId=s.pendingSendingEventsTxId.filter(F=>F.id!==T.getId()),s.pendingSendingEventsTxId.length===0&&s.eventEmitter.emit(ep.PendingEventsChanged)}});return function(T){return O.apply(this,arguments)}}()),v(this,"onEvent",function(){var O=_(function*(T){if(T.preventDefault(),T.detail.data.room_id===s.roomId){var x=new pr(T.detail.data);yield s.updateTxId(x),yield s.syncApi.injectRoomEvents(s.room,[],[x]),s.emit(Te.Event,x),s.setSyncState(ct.Syncing),S.info("Received event ".concat(x.getId()," ").concat(x.getType()," ").concat(x.getStateKey()))}else{var{event_id:C,room_id:N}=T.detail.data;S.info("Received event ".concat(C," for a different room ").concat(N,"; discarding"))}yield s.ack(T)});return function(T){return O.apply(this,arguments)}}()),v(this,"onToDevice",function(){var O=_(function*(T){T.preventDefault();var x=new pr({type:T.detail.data.type,sender:T.detail.data.sender,content:T.detail.data.content});T.detail.data.encrypted&&x.makeEncrypted(V.RoomMessageEncrypted,{},"",""),s.emit(Te.ToDeviceEvent,x),s.setSyncState(ct.Syncing),yield s.ack(T)});return function(T){return O.apply(this,arguments)}}());var R=this.widgetApi.transport.send.bind(this.widgetApi.transport);this.widgetApi.transport.send=function(){var O=_(function*(T,x){try{return yield R(T,x)}catch(C){Hk(C)}});return function(T,x){return O.apply(this,arguments)}}();var k=this.widgetApi.transport.sendComplete.bind(this.widgetApi.transport);this.widgetApi.transport.sendComplete=function(){var O=_(function*(T,x){try{return yield k(T,x)}catch(C){Hk(C)}});return function(T,x){return O.apply(this,arguments)}}(),this.widgetApiReady=new Promise(O=>this.widgetApi.once("ready",O)),((a=t.sendEvent)!==null&&a!==void 0&&a.length||(l=t.receiveEvent)!==null&&l!==void 0&&l.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||t.receiveMessage===!0||Array.isArray(t.receiveMessage)&&t.receiveMessage.length||(c=t.sendState)!==null&&c!==void 0&&c.length||(u=t.receiveState)!==null&&u!==void 0&&u.length)&&e.requestCapabilityForRoomTimeline(n),(d=t.sendEvent)===null||d===void 0||d.forEach(O=>e.requestCapabilityToSendEvent(O)),(f=t.receiveEvent)===null||f===void 0||f.forEach(O=>e.requestCapabilityToReceiveEvent(O)),t.sendMessage===!0?e.requestCapabilityToSendMessage():Array.isArray(t.sendMessage)&&t.sendMessage.forEach(O=>e.requestCapabilityToSendMessage(O)),t.receiveMessage===!0?e.requestCapabilityToReceiveMessage():Array.isArray(t.receiveMessage)&&t.receiveMessage.forEach(O=>e.requestCapabilityToReceiveMessage(O)),(p=t.sendState)===null||p===void 0||p.forEach(O=>{var{eventType:T,stateKey:x}=O;return e.requestCapabilityToSendState(T,x)}),(h=t.receiveState)===null||h===void 0||h.forEach(O=>{var{eventType:T,stateKey:x}=O;return e.requestCapabilityToReceiveState(T,x)}),(m=t.sendToDevice)===null||m===void 0||m.forEach(O=>e.requestCapabilityToSendToDevice(O)),(w=t.receiveToDevice)===null||w===void 0||w.forEach(O=>e.requestCapabilityToReceiveToDevice(O)),t.sendDelayedEvents&&((g=t.sendEvent)!==null&&g!==void 0&&g.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||(b=t.sendState)!==null&&b!==void 0&&b.length)&&e.requestCapability(os.MatrixCapabilities.MSC4157SendDelayedEvent),t.updateDelayedEvents&&e.requestCapability(os.MatrixCapabilities.MSC4157UpdateDelayedEvent),t.turnServers&&e.requestCapability(os.MatrixCapabilities.MSC3846TurnServers),e.on("action:".concat(os.WidgetApiToWidgetAction.SendEvent),this.onEvent),e.on("action:".concat(os.WidgetApiToWidgetAction.SendToDevice),this.onToDevice),e.start(),o&&e.sendContentLoaded()}startClient(){var e=arguments,t=this;return _(function*(){var n,i,o=e.length>0&&e[0]!==void 0?e[0]:{};t.lifecycle=new AbortController;var s=t.getUserId();s&&t.store.storeUser(new Co(s)),o.slidingSync?t.syncApi=new bN(o.slidingSync,t,o,t.buildSyncApiOptions()):t.syncApi=new Mu(t,o,t.buildSyncApiOptions()),t.room=t.syncApi.createRoom(t.roomId),t.store.storeRoom(t.room),yield t.widgetApiReady,yield Promise.all((n=(i=t.capabilities.receiveState)===null||i===void 0?void 0:i.map(function(){var a=_(function*(l){var{eventType:c,stateKey:u}=l,d=yield t.widgetApi.readStateEvents(c,void 0,u,[t.roomId]),f=d.map(p=>new pr(p));yield t.syncApi.injectRoomEvents(t.room,[],f),f.forEach(p=>{t.emit(Te.Event,p),S.info("Backfilled event ".concat(p.getId()," ").concat(p.getType()," ").concat(p.getStateKey()))})});return function(l){return a.apply(this,arguments)}}()))!==null&&n!==void 0?n:[]),o.clientWellKnownPollPeriod!==void 0&&(t.clientWellKnownIntervalID=setInterval(()=>{t.fetchClientWellKnown()},1e3*o.clientWellKnownPollPeriod),t.fetchClientWellKnown()),t.setSyncState(ct.Syncing),S.info("Finished backfilling events"),t.matrixRTC.start(),t.capabilities.turnServers&&t.watchTurnServers()})()}stopClient(){this.widgetApi.off("action:".concat(os.WidgetApiToWidgetAction.SendEvent),this.onEvent),this.widgetApi.off("action:".concat(os.WidgetApiToWidgetAction.SendToDevice),this.onToDevice),super.stopClient(),this.lifecycle.abort()}joinRoom(e){var t=this;return _(function*(){if(e===t.roomId)return t.room;throw new Error("Unknown room: ".concat(e))})()}encryptAndSendEvent(e,t,n){var i=this;return _(function*(){var o=t.event.redacts?gh(gh({},t.getContent()),{},{redacts:t.event.redacts}):t.getContent();if(n){var s=yield i.widgetApi.sendRoomEvent(t.getType(),o,e.roomId,"delay"in n?n.delay:void 0,"parent_delay_id"in n?n.parent_delay_id:void 0);return i.validateSendDelayedEventResponse(s)}var a=t.getTxnId();a&&i.pendingSendingEventsTxId.push({type:t.getType(),id:void 0,txId:a});var l;try{l=yield i.widgetApi.sendRoomEvent(t.getType(),o,e.roomId)}catch(c){throw i.updatePendingEventStatus(e,t,je.NOT_SENT),c}return e.updatePendingEvent(t,je.SENT,l.event_id),i.pendingSendingEventsTxId.forEach(c=>{c.txId===a&&(c.id=l.event_id)}),i.eventEmitter.emit(ep.PendingEventsChanged),{event_id:l.event_id}})()}sendStateEvent(e,t,n){var i=arguments,o=this;return _(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:"",a=yield o.widgetApi.sendStateEvent(t,s,n,e);if(a.event_id===void 0)throw new Error("'event_id' absent from response to an event request");return{event_id:a.event_id}})()}_unstable_sendDelayedStateEvent(e,t,n,i){var o=arguments,s=this;return _(function*(){var a=o.length>4&&o[4]!==void 0?o[4]:"";if(!(yield s.doesServerSupportUnstableFeature($i)))throw Error("Server does not support the delayed events API");var l=yield s.widgetApi.sendStateEvent(n,a,i,e,"delay"in t?t.delay:void 0,"parent_delay_id"in t?t.parent_delay_id:void 0);return s.validateSendDelayedEventResponse(l)})()}validateSendDelayedEventResponse(e){if(e.delay_id===void 0)throw new Error("'delay_id' absent from response to a delayed event request");return{delay_id:e.delay_id}}_unstable_updateDelayedEvent(e,t){var n=this;return _(function*(){if(!(yield n.doesServerSupportUnstableFeature($i)))throw Error("Server does not support the delayed events API");return yield n.widgetApi.updateDelayedEvent(e,t)})()}sendToDevice(e,t){var n=this;return _(function*(){return yield n.widgetApi.sendToDevice(e,!1,ms(t)),{}})()}getOpenIdToken(){var e=this;return _(function*(){var t=yield e.widgetApi.requestOpenIDConnectToken();return{access_token:t.access_token,expires_in:t.expires_in,matrix_server_name:t.matrix_server_name,token_type:t.token_type}})()}queueToDevice(e){var t=this;return _(function*(){var{eventType:n,batch:i}=e,o=new qt(()=>new Map);for(var{userId:s,deviceId:a,payload:l}of i)o.getOrCreate(s).set(a,l);yield t.widgetApi.sendToDevice(n,!1,ms(o))})()}encryptAndSendToDevices(e,t){var n=this;return _(function*(){var i=new qt(()=>new Map);for(var{userId:o,deviceInfo:{deviceId:s}}of e)i.getOrCreate(o).set(s,t);yield n.widgetApi.sendToDevice(t.type,!0,ms(i))})()}sendToDeviceViaWidgetApi(e,t,n){var i=this;return _(function*(){yield i.widgetApi.sendToDevice(e,t,ms(n))})()}checkTurnServers(){var e=this;return _(function*(){return e.turnServers.length>0})()}getSyncState(){return this.syncState}setSyncState(e){var t=this.syncState;this.syncState=e,this.emit(Te.Sync,e,t)}ack(e){var t=this;return _(function*(){yield t.widgetApi.transport.reply(e.detail,{})})()}watchTurnServers(){var e=this;return _(function*(){var t=e.widgetApi.getTurnServers(),n=()=>{t.return(void 0)};e.lifecycle.signal.addEventListener("abort",n);try{var i=!1,o=!1,s;try{for(var a=U7(t),l;i=!(l=yield a.next()).done;i=!1){var c=l.value;e.turnServers=[{urls:c.uris,username:c.username,credential:c.password}],e.emit(Te.TurnServers,e.turnServers),S.log("Received TURN server: ".concat(c.uris))}}catch(u){o=!0,s=u}finally{try{i&&a.return!=null&&(yield a.return())}finally{if(o)throw s}}}catch(u){S.warn("Error watching TURN servers",u)}finally{e.lifecycle.signal.removeEventListener("abort",n)}})()}}function Hk(r){throw r instanceof os.WidgetApiResponseError&&r.data.matrix_api_error?hr.fromWidgetApiErrorData(r.data.matrix_api_error):r}class j7{constructor(){v(this,"unthreadedReadReceipts",new Map),v(this,"threadedReadReceipts",new qt(()=>new Map))}setUnthreaded(e,t){this.unthreadedReadReceipts.set(e,t)}setThreaded(e,t,n){this.threadedReadReceipts.getOrCreate(e).set(t,n)}allUnthreaded(){return this.unthreadedReadReceipts.entries()}*allThreaded(){for(var e of this.threadedReadReceipts.values())for(var t of e.entries())yield t}consumeEphemeralEvents(e){e==null||e.forEach(t=>{t.type!==V.Receipt||!t.content||Object.keys(t.content).forEach(n=>{Object.entries(t.content[n]).forEach(i=>{var[o,s]=i;if(uw(o))for(var a of Object.keys(s)){var l=t.content[n][o][a],c={data:t.content[n][o][a],type:o,eventId:n};l.thread_id?this.setThreaded(l.thread_id,a,c):this.setUnthreaded(a,c)}})})})}buildAccumulatedReceiptEvent(e){var t={type:V.Receipt,room_id:e,content:{}},n=new qt(()=>new qt(()=>new Map));for(var[i,o]of this.allUnthreaded())n.getOrCreate(o.eventId).getOrCreate(o.type).set(i,o.data);for(var[s,a]of this.allThreaded())n.getOrCreate(a.eventId).getOrCreate(a.type).set(s,a.data);return t.content=ms(n),n.size>0?t:null}}var ho=function(r){return r.Invite="invite",r.Leave="leave",r.Join="join",r.Knock="knock",r}({});function F7(r){return"_localTs"in r&&r._localTs!==void 0}class DN{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.opts=e,v(this,"accountData",{}),v(this,"inviteRooms",{}),v(this,"knockRooms",{}),v(this,"joinRooms",{}),v(this,"nextBatch",null),this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.accumulateRooms(e,t),this.accumulateAccountData(e),this.nextBatch=e.next_batch}accumulateAccountData(e){!e.account_data||!e.account_data.events||e.account_data.events.forEach(t=>{this.accountData[t.type]=t})}accumulateRooms(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach(n=>{this.accumulateRoom(n,ho.Invite,e.rooms.invite[n],t)}),e.rooms.join&&Object.keys(e.rooms.join).forEach(n=>{this.accumulateRoom(n,ho.Join,e.rooms.join[n],t)}),e.rooms.leave&&Object.keys(e.rooms.leave).forEach(n=>{this.accumulateRoom(n,ho.Leave,e.rooms.leave[n],t)}),e.rooms.knock&&Object.keys(e.rooms.knock).forEach(n=>{this.accumulateRoom(n,ho.Knock,e.rooms.knock[n],t)}))}accumulateRoom(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;switch(t){case ho.Invite:this.knockRooms[e]&&delete this.knockRooms[e],this.accumulateInviteState(e,n);break;case ho.Knock:this.accumulateKnockState(e,n);break;case ho.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,n,i);break;case ho.Leave:this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:S.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!(!t.invite_state||!t.invite_state.events)){if(!this.inviteRooms[e]){this.inviteRooms[e]={invite_state:t.invite_state};return}var n=this.inviteRooms[e];t.invite_state.events.forEach(i=>{for(var o=!1,s=0;s<n.invite_state.events.length;s++){var a=n.invite_state.events[s];a.type===i.type&&a.state_key==i.state_key&&(n.invite_state.events[s]=i,o=!0)}o||n.invite_state.events.push(i)})}}accumulateKnockState(e,t){if(!(!t.knock_state||!t.knock_state.events)){if(!this.knockRooms[e]){this.knockRooms[e]={knock_state:t.knock_state};return}var n=this.knockRooms[e];t.knock_state.events.forEach(i=>{for(var o=!1,s=0;s<n.knock_state.events.length;s++){var a=n.knock_state.events[s];a.type===i.type&&a.state_key==i.state_key&&(n.knock_state.events[s]=i,o=!0)}o||n.knock_state.events.push(i)})}}accumulateJoinState(e,t){var n,i,o,s,a,l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;this.joinRooms[e]||(this.joinRooms[e]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_unreadThreadNotifications:{},_summary:{},_receipts:new j7});var c=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach(k=>{c._accountData[k.type]=k}),t.unread_notifications&&(c._unreadNotifications=t.unread_notifications),c._unreadThreadNotifications=(n=(i=t[Fd.stable])!==null&&i!==void 0?i:t[Fd.unstable])!==null&&n!==void 0?n:void 0,t.summary){var u,d,f,p="m.heroes",h="m.invited_member_count",m="m.joined_member_count",w=c._summary,g=t.summary;w[p]=(u=g[p])!==null&&u!==void 0?u:w[p],w[m]=(d=g[m])!==null&&d!==void 0?d:w[m],w[h]=(f=g[h])!==null&&f!==void 0?f:w[h]}if(c._receipts.consumeEphemeralEvents((o=t.ephemeral)===null||o===void 0?void 0:o.events),t.timeline&&t.timeline.limited&&(c._timeline=[]),(s=t.state)===null||s===void 0||(s=s.events)===null||s===void 0||s.forEach(k=>{ay(c._currentState,k)}),(a=t.timeline)===null||a===void 0||(a=a.events)===null||a===void 0||a.forEach((k,O)=>{var T;ay(c._currentState,k);var x;if(l)x=k;else{var C;x=Object.assign({},k),x.unsigned!==void 0&&(x.unsigned=Object.assign({},x.unsigned));var N=(C=k.unsigned)===null||C===void 0?void 0:C.age;N!==void 0&&(x._localTs=Date.now()-N)}c._timeline.push({event:x,token:O===0&&(T=t.timeline.prev_batch)!==null&&T!==void 0?T:null})}),c._timeline.length>this.opts.maxTimelineEntries){for(var b=c._timeline.length-this.opts.maxTimelineEntries,R=b;R<c._timeline.length;R++)if(c._timeline[R].token){c._timeline=c._timeline.slice(R,c._timeline.length);break}}}getJSON(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t={join:{},invite:{},knock:{},leave:{}};Object.keys(this.inviteRooms).forEach(i=>{t.invite[i]=this.inviteRooms[i]}),Object.keys(this.knockRooms).forEach(i=>{t.knock[i]=this.knockRooms[i]}),Object.keys(this.joinRooms).forEach(i=>{var o=this.joinRooms[i],s={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(f=>{s.account_data.events.push(o._accountData[f])});var a=o._receipts.buildAccumulatedReceiptEvent(i);a&&s.ephemeral.events.push(a),o._timeline.forEach(f=>{if(!s.timeline.prev_batch){if(!f.token)return;s.timeline.prev_batch=f.token}var p;!e&&F7(f.event)?(p=Object.assign({},f.event),p.unsigned!==void 0&&(p.unsigned=Object.assign({},p.unsigned)),delete p._localTs,p.unsigned=p.unsigned||{},p.unsigned.age=Date.now()-f.event._localTs):p=f.event,s.timeline.events.push(p)});for(var l=Object.create(null),c=s.timeline.events.length-1;c>=0;c--){var u=s.timeline.events[c];if(!(u.state_key===null||u.state_key===void 0)){var d=lm(u);d.unsigned&&(d.unsigned.prev_content&&(d.content=d.unsigned.prev_content),d.unsigned.prev_sender&&(d.sender=d.unsigned.prev_sender)),ay(l,d)}}Object.keys(o._currentState).forEach(f=>{Object.keys(o._currentState[f]).forEach(p=>{var h=o._currentState[f][p];l[f]&&l[f][p]&&(h=l[f][p]),s.state.events.push(h)})}),t.join[i]=s});var n=[];return Object.keys(this.accountData).forEach(i=>{n.push(this.accountData[i])}),{nextBatch:this.nextBatch,roomsData:t,accountData:n}}getNextBatchToken(){return this.nextBatch}}function ay(r,e){e.state_key===null||e.state_key===void 0||!e.type||(r[e.type]||(r[e.type]=Object.create(null)),r[e.type][e.state_key]=e)}class Lu extends Error{}Lu.prototype.name="InvalidTokenError";function B7(r){return decodeURIComponent(atob(r).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}function K7(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return B7(e)}catch{return atob(e)}}function NN(r,e){if(typeof r!="string")throw new Lu("Invalid token specified: must be a string");e||(e={});const t=e.header===!0?0:1,n=r.split(".")[t];if(typeof n!="string")throw new Lu(`Invalid token specified: missing part #${t+1}`);let i;try{i=K7(n)}catch(o){throw new Lu(`Invalid token specified: invalid base64 for part #${t+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new Lu(`Invalid token specified: invalid json for part #${t+1} (${o.message})`)}}var V7={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Bi,Ki,zd=(r=>(r[r.NONE=0]="NONE",r[r.ERROR=1]="ERROR",r[r.WARN=2]="WARN",r[r.INFO=3]="INFO",r[r.DEBUG=4]="DEBUG",r))(zd||{});(r=>{function e(){Bi=3,Ki=V7}r.reset=e;function t(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");Bi=i}r.setLevel=t;function n(i){Ki=i}r.setLogger=n})(zd||(zd={}));var Qt=class Ui{constructor(e){this._name=e}debug(...e){Bi>=4&&Ki.debug(Ui._format(this._name,this._method),...e)}info(...e){Bi>=3&&Ki.info(Ui._format(this._name,this._method),...e)}warn(...e){Bi>=2&&Ki.warn(Ui._format(this._name,this._method),...e)}error(...e){Bi>=1&&Ki.error(Ui._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const n=new Ui(`${e}.${t}`);return n.debug("begin"),n}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(e,...t){Bi>=4&&Ki.debug(Ui._format(e),...t)}static info(e,...t){Bi>=3&&Ki.info(Ui._format(e),...t)}static warn(e,...t){Bi>=2&&Ki.warn(Ui._format(e),...t)}static error(e,...t){Bi>=1&&Ki.error(Ui._format(e),...t)}};zd.reset();var Yd=class{static decode(r){try{return NN(r)}catch(e){throw Qt.error("JwtUtils.decode",e),e}}static async generateSignedJwt(r,e,t){const n=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(r))),i=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),o=`${n}.${i}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,new TextEncoder().encode(o)),a=Or.encodeBase64Url(new Uint8Array(s));return`${o}.${a}`}static async generateSignedJwtWithHmac(r,e,t){const n=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(r))),i=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),o=`${n}.${i}`,s=await window.crypto.subtle.sign("HMAC",t,new TextEncoder().encode(o)),a=Or.encodeBase64Url(new Uint8Array(s));return`${o}.${a}`}},$7="10000000-1000-4000-8000-100000000000",s_=r=>btoa([...new Uint8Array(r)].map(e=>String.fromCharCode(e)).join("")),LN=class ci{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return $7.replace(/[018]/g,t=>(+t^ci._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return ci.generateUUIDv4()+ci.generateUUIDv4()+ci.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const n=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",n);return s_(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw Qt.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const i=new TextEncoder().encode([e,t].join(":"));return s_(i)}static async hash(e,t){const n=new TextEncoder().encode(t),i=await crypto.subtle.digest(e,n);return new Uint8Array(i)}static async customCalculateJwkThumbprint(e){let t;switch(e.kty){case"RSA":t={e:e.e,kty:e.kty,n:e.n};break;case"EC":t={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":t={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":t={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const n=await ci.hash("SHA-256",JSON.stringify(t));return ci.encodeBase64Url(n)}static async generateDPoPProof({url:e,accessToken:t,httpMethod:n,keyPair:i,nonce:o}){let s,a;const l={jti:window.crypto.randomUUID(),htm:n??"GET",htu:e,iat:Math.floor(Date.now()/1e3)};t&&(s=await ci.hash("SHA-256",t),a=ci.encodeBase64Url(s),l.ath=a),o&&(l.nonce=o);try{const c=await crypto.subtle.exportKey("jwk",i.publicKey),u={alg:"ES256",typ:"dpop+jwt",jwk:{crv:c.crv,kty:c.kty,x:c.x,y:c.y}};return await Yd.generateSignedJwt(u,l,i.privateKey)}catch(c){throw c instanceof TypeError?new Error(`Error exporting dpop public key: ${c.message}`):c}}static async generateDPoPJkt(e){try{const t=await crypto.subtle.exportKey("jwk",e.publicKey);return await ci.customCalculateJwkThumbprint(t)}catch(t){throw t instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${t.message}`):t}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(e,t,n,i="HS256"){const o=Math.floor(Date.now()/1e3),s={alg:i,typ:"JWT"},a={iss:e,sub:e,aud:n,jti:ci.generateUUIDv4(),exp:o+300,iat:o},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[i];if(!c)throw new Error(`Unsupported algorithm: ${i}. Supported algorithms are: HS256, HS384, HS512`);const u=new TextEncoder,d=await crypto.subtle.importKey("raw",u.encode(t),{name:"HMAC",hash:c},!1,["sign"]);return await Yd.generateSignedJwtWithHmac(s,a,d)}};LN.encodeBase64Url=r=>s_(r).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Or=LN,W7=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Qt(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},lv=class tp extends W7{constructor(){super(...arguments),this._logger=new Qt(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-tp.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=tp.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const n=tp.getEpochTime()+e;if(this.expiration===n&&this._timerHandle){t.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),t.debug("using duration",e),this._expiration=n;const i=Math.min(e,5);this._timerHandle=setInterval(this._callback,i*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},zk=class{static readParams(r,e="query"){if(!r)throw new TypeError("Invalid URL");const n=new URL(r,"http://127.0.0.1")[e==="fragment"?"hash":"search"];return new URLSearchParams(n.slice(1))}},Rc=";",Jd=class extends Error{constructor(r,e){var t,n,i;if(super(r.error_description||r.error||""),this.form=e,this.name="ErrorResponse",!r.error)throw Qt.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=r.error,this.error_description=(t=r.error_description)!=null?t:null,this.error_uri=(n=r.error_uri)!=null?n:null,this.state=r.userState,this.session_state=(i=r.session_state)!=null?i:null,this.url_state=r.url_state}},q7=class extends Error{constructor(r){super(r),this.name="ErrorTimeout"}},G7=class{constructor(){this._logger=new Qt("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(r){return this._logger.create(`getItem('${r}')`),this._data[r]}setItem(r,e){this._logger.create(`setItem('${r}')`),this._data[r]=e}removeItem(r){this._logger.create(`removeItem('${r}')`),delete this._data[r]}get length(){return Object.getOwnPropertyNames(this._data).length}key(r){return Object.getOwnPropertyNames(this._data)[r]}},a_=class extends Error{constructor(r,e){super(e),this.name="ErrorDPoPNonce",this.nonce=r}},Uw=class{constructor(r=[],e=null,t={}){this._jwtHandler=e,this._extraHeaders=t,this._logger=new Qt("JsonService"),this._contentTypes=[],this._contentTypes.push(...r,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(r,e={}){const{timeoutInSeconds:t,...n}=e;if(!t)return await fetch(r,n);const i=new AbortController,o=setTimeout(()=>i.abort(),t*1e3);try{return await fetch(r,{...e,signal:i.signal})}catch(s){throw s instanceof DOMException&&s.name==="AbortError"?new q7("Network timed out"):s}finally{clearTimeout(o)}}async getJson(r,{token:e,credentials:t,timeoutInSeconds:n}={}){const i=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};e&&(i.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+e),this._appendExtraHeaders(o);let s;try{i.debug("url:",r),s=await this.fetchWithTimeout(r,{method:"GET",headers:o,timeoutInSeconds:n,credentials:t})}catch(c){throw i.error("Network Error"),c}i.debug("HTTP response received, status",s.status);const a=s.headers.get("Content-Type");if(a&&!this._contentTypes.find(c=>a.startsWith(c))&&i.throw(new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${r}`)),s.ok&&this._jwtHandler&&(a!=null&&a.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let l;try{l=await s.json()}catch(c){throw i.error("Error parsing JSON response",c),s.ok?c:new Error(`${s.statusText} (${s.status})`)}if(!s.ok)throw i.error("Error from server:",l),l.error?new Jd(l):new Error(`${s.statusText} (${s.status}): ${JSON.stringify(l)}`);return l}async postForm(r,{body:e,basicAuth:t,timeoutInSeconds:n,initCredentials:i,extraHeaders:o}){const s=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...o};t!==void 0&&(a.Authorization="Basic "+t),this._appendExtraHeaders(a);let l;try{s.debug("url:",r),l=await this.fetchWithTimeout(r,{method:"POST",headers:a,body:e,timeoutInSeconds:n,credentials:i})}catch(f){throw s.error("Network error"),f}s.debug("HTTP response received, status",l.status);const c=l.headers.get("Content-Type");if(c&&!this._contentTypes.find(f=>c.startsWith(f)))throw new Error(`Invalid response Content-Type: ${c??"undefined"}, from URL: ${r}`);const u=await l.text();let d={};if(u)try{d=JSON.parse(u)}catch(f){throw s.error("Error parsing JSON response",f),l.ok?f:new Error(`${l.statusText} (${l.status})`)}if(!l.ok){if(s.error("Error from server:",d),l.headers.has("dpop-nonce")){const f=l.headers.get("dpop-nonce");throw new a_(f,`${JSON.stringify(d)}`)}throw d.error?new Jd(d,e):new Error(`${l.statusText} (${l.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(r){const e=this._logger.create("appendExtraHeaders"),t=Object.keys(this._extraHeaders),n=["accept","content-type"],i=["authorization"];t.length!==0&&t.forEach(o=>{if(n.includes(o.toLocaleLowerCase())){e.warn("Protected header could not be set",o,n);return}if(i.includes(o.toLocaleLowerCase())&&Object.keys(r).includes(o)){e.warn("Header could not be overridden",o,i);return}const s=typeof this._extraHeaders[o]=="function"?this._extraHeaders[o]():this._extraHeaders[o];s&&s!==""&&(r[o]=s)})}},UN=class{constructor(r){this._settings=r,this._logger=new Qt("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Uw(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const r=this._logger.create("getMetadata");if(this._metadata)return r.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw r.throw(new Error("No authority or metadataUrl configured on settings")),null;r.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return r.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},e,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(r=!0){return this._getMetadataProperty("token_endpoint",r)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(r=!0){return this._getMetadataProperty("revocation_endpoint",r)}getKeysEndpoint(r=!0){return this._getMetadataProperty("jwks_uri",r)}async _getMetadataProperty(r,e=!1){const t=this._logger.create(`_getMetadataProperty('${r}')`),n=await this.getMetadata();if(t.debug("resolved"),n[r]===void 0){if(e===!0){t.warn("Metadata does not contain optional property");return}t.throw(new Error("Metadata does not contain property "+r))}return n[r]}async getSigningKeys(){const r=this._logger.create("getSigningKeys");if(this._signingKeys)return r.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);r.debug("got jwks_uri",e);const t=await this._jsonService.getJson(e,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(r.debug("got key set",t),!Array.isArray(t.keys))throw r.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=t.keys,this._signingKeys}},xm=class{constructor({prefix:r="oidc.",store:e=localStorage}={}){this._logger=new Qt("WebStorageStateStore"),this._store=e,this._prefix=r}async set(r,e){this._logger.create(`set('${r}')`),r=this._prefix+r,await this._store.setItem(r,e)}async get(r){return this._logger.create(`get('${r}')`),r=this._prefix+r,await this._store.getItem(r)}async remove(r){this._logger.create(`remove('${r}')`),r=this._prefix+r;const e=await this._store.getItem(r);return await this._store.removeItem(r),e}async getAllKeys(){this._logger.create("getAllKeys");const r=await this._store.length,e=[];for(let t=0;t<r;t++){const n=await this._store.key(t);n&&n.indexOf(this._prefix)===0&&e.push(n.substr(this._prefix.length))}return e}},H7="code",z7="openid",Y7="client_secret_post",J7=60*15,l_=class{constructor({authority:r,metadataUrl:e,metadata:t,signingKeys:n,metadataSeed:i,client_id:o,client_secret:s,response_type:a=H7,scope:l=z7,redirect_uri:c,post_logout_redirect_uri:u,client_authentication:d=Y7,token_endpoint_auth_signing_alg:f="HS256",prompt:p,display:h,max_age:m,ui_locales:w,acr_values:g,resource:b,response_mode:R,filterProtocolClaims:k=!0,loadUserInfo:O=!1,requestTimeoutInSeconds:T,staleStateAgeInSeconds:x=J7,mergeClaimsStrategy:C={array:"replace"},disablePKCE:N=!1,stateStore:F,revokeTokenAdditionalContentTypes:H,fetchRequestCredentials:ie,refreshTokenAllowedScope:$,extraQueryParams:X={},extraTokenParams:oe={},extraHeaders:re={},dpop:ae,omitScopeWhenRequesting:q=!1}){var z;if(this.authority=r,e?this.metadataUrl=e:(this.metadataUrl=r,r&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=t,this.metadataSeed=i,this.signingKeys=n,this.client_id=o,this.client_secret=s,this.response_type=a,this.scope=l,this.redirect_uri=c,this.post_logout_redirect_uri=u,this.client_authentication=d,this.token_endpoint_auth_signing_alg=f,this.prompt=p,this.display=h,this.max_age=m,this.ui_locales=w,this.acr_values=g,this.resource=b,this.response_mode=R,this.filterProtocolClaims=k??!0,this.loadUserInfo=!!O,this.staleStateAgeInSeconds=x,this.mergeClaimsStrategy=C,this.omitScopeWhenRequesting=q,this.disablePKCE=!!N,this.revokeTokenAdditionalContentTypes=H,this.fetchRequestCredentials=ie||"same-origin",this.requestTimeoutInSeconds=T,F)this.stateStore=F;else{const Q=typeof window<"u"?window.localStorage:new G7;this.stateStore=new xm({store:Q})}if(this.refreshTokenAllowedScope=$,this.extraQueryParams=X,this.extraTokenParams=oe,this.extraHeaders=re,this.dpop=ae,this.dpop&&!((z=this.dpop)!=null&&z.store))throw new Error("A DPoPStore is required when dpop is enabled")}},X7=class{constructor(r,e){this._settings=r,this._metadataService=e,this._logger=new Qt("UserInfoService"),this._getClaimsFromJwt=async t=>{const n=this._logger.create("_getClaimsFromJwt");try{const i=Yd.decode(t);return n.debug("JWT decoding successful"),i}catch(i){throw n.error("Error parsing JWT response"),i}},this._jsonService=new Uw(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(r){const e=this._logger.create("getClaims");r||this._logger.throw(new Error("No token passed"));const t=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",t);const n=await this._jsonService.getJson(t,{token:r,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("got claims",n),n}},jN=class{constructor(r,e){this._settings=r,this._metadataService=e,this._logger=new Qt("TokenClient"),this._jsonService=new Uw(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:r="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:i,...o}){const s=this._logger.create("exchangeCode");t||s.throw(new Error("A client_id is required")),e||s.throw(new Error("A redirect_uri is required")),o.code||s.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:r,redirect_uri:e});for(const[d,f]of Object.entries(o))f!=null&&a.set(d,f);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&n==null)throw s.throw(new Error("A client_secret is required")),null;let l;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":l=Or.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n);break;case"client_secret_jwt":{const d=await Or.generateClientAssertionJwt(t,n,c,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",d);break}}s.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return s.debug("got response"),u}async exchangeCredentials({grant_type:r="password",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,scope:n=this._settings.scope,...i}){const o=this._logger.create("exchangeCredentials");e||o.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:r});this._settings.omitScopeWhenRequesting||s.set("scope",n);for(const[u,d]of Object.entries(i))d!=null&&s.set(u,d);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&t==null)throw o.throw(new Error("A client_secret is required")),null;let a;const l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=Or.generateBasicAuth(e,t);break;case"client_secret_post":s.append("client_id",e),t&&s.append("client_secret",t);break;case"client_secret_jwt":{const u=await Or.generateClientAssertionJwt(e,t,l,this._settings.token_endpoint_auth_signing_alg);s.append("client_id",e),s.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),s.append("client_assertion",u);break}}o.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return o.debug("got response"),c}async exchangeRefreshToken({grant_type:r="refresh_token",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:i,...o}){const s=this._logger.create("exchangeRefreshToken");e||s.throw(new Error("A client_id is required")),o.refresh_token||s.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:r});for(const[d,f]of Object.entries(o))Array.isArray(f)?f.forEach(p=>a.append(d,p)):f!=null&&a.set(d,f);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&t==null)throw s.throw(new Error("A client_secret is required")),null;let l;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":l=Or.generateBasicAuth(e,t);break;case"client_secret_post":a.append("client_id",e),t&&a.append("client_secret",t);break;case"client_secret_jwt":{const d=await Or.generateClientAssertionJwt(e,t,c,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",e),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",d);break}}s.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return s.debug("got response"),u}async revoke(r){var e;const t=this._logger.create("revoke");r.token||t.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${(e=r.token_type_hint)!=null?e:"default token type"}`);const i=new URLSearchParams;for(const[o,s]of Object.entries(r))s!=null&&i.set(o,s);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),t.debug("got response")}},Q7=class{constructor(r,e,t){this._settings=r,this._metadataService=e,this._claimsService=t,this._logger=new Qt("ResponseValidator"),this._userInfoService=new X7(this._settings,this._metadataService),this._tokenClient=new jN(this._settings,this._metadataService)}async validateSigninResponse(r,e,t){const n=this._logger.create("validateSigninResponse");this._processSigninState(r,e),n.debug("state processed"),await this._processCode(r,e,t),n.debug("code processed"),r.isOpenId&&this._validateIdTokenAttributes(r,"",e.nonce),n.debug("tokens validated"),await this._processClaims(r,e==null?void 0:e.skipUserInfo,r.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(r,e){const t=this._logger.create("validateCredentialsResponse"),n=r.isOpenId&&!!r.id_token;n&&this._validateIdTokenAttributes(r),t.debug("tokens validated"),await this._processClaims(r,e,n),t.debug("claims processed")}async validateRefreshResponse(r,e){var t,n;const i=this._logger.create("validateRefreshResponse");r.userState=e.data,(t=r.session_state)!=null||(r.session_state=e.session_state),(n=r.scope)!=null||(r.scope=e.scope),r.isOpenId&&r.id_token&&(this._validateIdTokenAttributes(r,e.id_token),i.debug("ID Token validated")),r.id_token||(r.id_token=e.id_token,r.profile=e.profile);const o=r.isOpenId&&!!r.id_token;await this._processClaims(r,!1,o),i.debug("claims processed")}validateSignoutResponse(r,e){const t=this._logger.create("validateSignoutResponse");if(e.id!==r.state&&t.throw(new Error("State does not match")),t.debug("state validated"),r.userState=e.data,r.error)throw t.warn("Response was error",r.error),new Jd(r)}_processSigninState(r,e){var t;const n=this._logger.create("_processSigninState");if(e.id!==r.state&&n.throw(new Error("State does not match")),e.client_id||n.throw(new Error("No client_id on state")),e.authority||n.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),r.userState=e.data,r.url_state=e.url_state,(t=r.scope)!=null||(r.scope=e.scope),r.error)throw n.warn("Response was error",r.error),new Jd(r);e.code_verifier&&!r.code&&n.throw(new Error("Expected code in response"))}async _processClaims(r,e=!1,t=!0){const n=this._logger.create("_processClaims");if(r.profile=this._claimsService.filterProtocolClaims(r.profile),e||!this._settings.loadUserInfo||!r.access_token){n.debug("not loading user info");return}n.debug("loading user info");const i=await this._userInfoService.getClaims(r.access_token);n.debug("user info claims received from user info endpoint"),t&&i.sub!==r.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),r.profile=this._claimsService.mergeClaims(r.profile,this._claimsService.filterProtocolClaims(i)),n.debug("user info claims received, updated profile:",r.profile)}async _processCode(r,e,t){const n=this._logger.create("_processCode");if(r.code){n.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:r.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,extraHeaders:t,...e.extraTokenParams});Object.assign(r,i)}else n.debug("No code to process")}_validateIdTokenAttributes(r,e,t){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const o=Yd.decode((n=r.id_token)!=null?n:"");if(o.sub||i.throw(new Error("ID Token is missing a subject claim")),t&&o.nonce!==t&&i.throw(new Error("nonce in id_token does not match nonce in client storage")),e){const s=Yd.decode(e);o.sub!==s.sub&&i.throw(new Error("sub in id_token does not match current sub")),o.auth_time&&o.auth_time!==s.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),o.azp&&o.azp!==s.azp&&i.throw(new Error("azp in id_token does not match original azp")),!o.azp&&s.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}r.profile=o}},cv=class c_{constructor(e){this.id=e.id||Or.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=lv.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Qt("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return Qt.createStatic("State","fromStorageString"),Promise.resolve(new c_(JSON.parse(e)))}static async clearStaleState(e,t){const n=Qt.createStatic("State","clearStaleState"),i=lv.getEpochTime()-t,o=await e.getAllKeys();n.debug("got keys",o);for(let s=0;s<o.length;s++){const a=o[s],l=await e.get(a);let c=!1;if(l)try{const u=await c_.fromStorageString(l);n.debug("got item from key:",a,u.created),u.created<=i&&(c=!0)}catch(u){n.error("Error parsing state for key:",a,u),c=!0}else n.debug("no item in storage for key:",a),c=!0;c&&(n.debug("removed item for key:",a),e.remove(a))}}},jw=class u_ extends cv{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo,this.nonce=e.nonce}static async create(e){const t=e.code_verifier===!0?Or.generateCodeVerifier():e.code_verifier||void 0,n=t?await Or.generateCodeChallenge(t):void 0;return new u_({...e,code_verifier:t,code_challenge:n})}toStorageString(){return new Qt("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo,nonce:this.nonce})}static fromStorageString(e){Qt.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return u_.create(t)}},FN=class BN{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:n,redirect_uri:i,response_type:o,scope:s,state_data:a,response_mode:l,request_type:c,client_secret:u,nonce:d,url_state:f,resource:p,skipUserInfo:h,extraQueryParams:m,extraTokenParams:w,disablePKCE:g,dpopJkt:b,omitScopeWhenRequesting:R,...k}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!o)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!s)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");const O=await jw.create({data:a,request_type:c,url_state:f,code_verifier:!g,client_id:n,authority:t,redirect_uri:i,response_mode:l,client_secret:u,scope:s,extraTokenParams:w,skipUserInfo:h,nonce:d}),T=new URL(e);T.searchParams.append("client_id",n),T.searchParams.append("redirect_uri",i),T.searchParams.append("response_type",o),R||T.searchParams.append("scope",s),d&&T.searchParams.append("nonce",d),b&&T.searchParams.append("dpop_jkt",b);let x=O.id;f&&(x=`${x}${Rc}${f}`),T.searchParams.append("state",x),O.code_challenge&&(T.searchParams.append("code_challenge",O.code_challenge),T.searchParams.append("code_challenge_method","S256")),p&&(Array.isArray(p)?p:[p]).forEach(N=>T.searchParams.append("resource",N));for(const[C,N]of Object.entries({response_mode:l,...k,...m}))N!=null&&T.searchParams.append(C,N.toString());return new BN({url:T.href,state:O})}};FN._logger=new Qt("SigninRequest");var Z7=FN,eY="openid",rp=class{constructor(r){if(this.access_token="",this.token_type="",this.profile={},this.state=r.get("state"),this.session_state=r.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(Rc);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Rc))}this.error=r.get("error"),this.error_description=r.get("error_description"),this.error_uri=r.get("error_uri"),this.code=r.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-lv.getEpochTime()}set expires_in(r){typeof r=="string"&&(r=Number(r)),r!==void 0&&r>=0&&(this.expires_at=Math.floor(r)+lv.getEpochTime())}get isOpenId(){var r;return((r=this.scope)==null?void 0:r.split(" ").includes(eY))||!!this.id_token}},tY=class{constructor({url:r,state_data:e,id_token_hint:t,post_logout_redirect_uri:n,extraQueryParams:i,request_type:o,client_id:s,url_state:a}){if(this._logger=new Qt("SignoutRequest"),!r)throw this._logger.error("ctor: No url passed"),new Error("url");const l=new URL(r);if(t&&l.searchParams.append("id_token_hint",t),s&&l.searchParams.append("client_id",s),n&&(l.searchParams.append("post_logout_redirect_uri",n),e||a)){this.state=new cv({data:e,request_type:o,url_state:a});let c=this.state.id;a&&(c=`${c}${Rc}${a}`),l.searchParams.append("state",c)}for(const[c,u]of Object.entries({...i}))u!=null&&l.searchParams.append(c,u.toString());this.url=l.href}},rY=class{constructor(r){if(this.state=r.get("state"),this.state){const e=decodeURIComponent(this.state).split(Rc);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Rc))}this.error=r.get("error"),this.error_description=r.get("error_description"),this.error_uri=r.get("error_uri")}},nY=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],iY=["sub","iss","aud","exp","iat"],oY=class{constructor(r){this._settings=r,this._logger=new Qt("ClaimsService")}filterProtocolClaims(r){const e={...r};if(this._settings.filterProtocolClaims){let t;Array.isArray(this._settings.filterProtocolClaims)?t=this._settings.filterProtocolClaims:t=nY;for(const n of t)iY.includes(n)||delete e[n]}return e}mergeClaims(r,e){const t={...r};for(const[n,i]of Object.entries(e))if(t[n]!==i)if(Array.isArray(t[n])||Array.isArray(i))if(this._settings.mergeClaimsStrategy.array=="replace")t[n]=i;else{const o=Array.isArray(t[n])?t[n]:[t[n]];for(const s of Array.isArray(i)?i:[i])o.includes(s)||o.push(s);t[n]=o}else typeof t[n]=="object"&&typeof i=="object"?t[n]=this.mergeClaims(t[n],i):t[n]=i;return t}},sY=class{constructor(r,e){this.keys=r,this.nonce=e}},Fw=class{constructor(r,e){this._logger=new Qt("OidcClient"),this.settings=r instanceof l_?r:new l_(r),this.metadataService=e??new UN(this.settings),this._claimsService=new oY(this.settings),this._validator=new Q7(this.settings,this.metadataService,this._claimsService),this._tokenClient=new jN(this.settings,this.metadataService)}async createSigninRequest({state:r,request:e,request_uri:t,request_type:n,id_token_hint:i,login_hint:o,skipUserInfo:s,nonce:a,url_state:l,response_type:c=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:f=this.settings.prompt,display:p=this.settings.display,max_age:h=this.settings.max_age,ui_locales:m=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:g=this.settings.resource,response_mode:b=this.settings.response_mode,extraQueryParams:R=this.settings.extraQueryParams,extraTokenParams:k=this.settings.extraTokenParams,dpopJkt:O,omitScopeWhenRequesting:T=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if(c!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const C=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",C);const N=await Z7.create({url:C,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:c,scope:u,state_data:r,url_state:l,prompt:f,display:p,max_age:h,ui_locales:m,id_token_hint:i,login_hint:o,acr_values:w,dpopJkt:O,resource:g,request:e,request_uri:t,extraQueryParams:R,extraTokenParams:k,request_type:n,response_mode:b,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:T});await this.clearStaleState();const F=N.state;return await this.settings.stateStore.set(F.id,F.toStorageString()),N}async readSigninResponseState(r,e=!1){const t=this._logger.create("readSigninResponseState"),n=new rp(zk.readParams(r,this.settings.response_mode));if(!n.state)throw t.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](n.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await jw.fromStorageString(i),response:n}}async processSigninResponse(r,e,t=!0){const n=this._logger.create("processSigninResponse"),{state:i,response:o}=await this.readSigninResponseState(r,t);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const s=await this.getDpopProof(this.settings.dpop.store);e={...e,DPoP:s}}try{await this._validator.validateSigninResponse(o,i,e)}catch(s){if(s instanceof a_&&this.settings.dpop){const a=await this.getDpopProof(this.settings.dpop.store,s.nonce);e.DPoP=a,await this._validator.validateSigninResponse(o,i,e)}else throw s}return o}async getDpopProof(r,e){let t,n;return(await r.getAllKeys()).includes(this.settings.client_id)?(n=await r.get(this.settings.client_id),n.nonce!==e&&e&&(n.nonce=e,await r.set(this.settings.client_id,n))):(t=await Or.generateDPoPKeys(),n=new sY(t,e),await r.set(this.settings.client_id,n)),await Or.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:r,password:e,skipUserInfo:t=!1,extraTokenParams:n={}}){const i=await this._tokenClient.exchangeCredentials({username:r,password:e,...n}),o=new rp(new URLSearchParams);return Object.assign(o,i),await this._validator.validateCredentialsResponse(o,t),o}async useRefreshToken({state:r,redirect_uri:e,resource:t,timeoutInSeconds:n,extraHeaders:i,extraTokenParams:o}){var s;const a=this._logger.create("useRefreshToken");let l;if(this.settings.refreshTokenAllowedScope===void 0)l=r.scope;else{const d=this.settings.refreshTokenAllowedScope.split(" ");l=(((s=r.scope)==null?void 0:s.split(" "))||[]).filter(p=>d.includes(p)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const d=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:d}}let c;try{c=await this._tokenClient.exchangeRefreshToken({refresh_token:r.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:n,extraHeaders:i,...o})}catch(d){if(d instanceof a_&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),c=await this._tokenClient.exchangeRefreshToken({refresh_token:r.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:n,extraHeaders:i,...o});else throw d}const u=new rp(new URLSearchParams);return Object.assign(u,c),a.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...r,scope:l}),u}async createSignoutRequest({state:r,id_token_hint:e,client_id:t,request_type:n,url_state:i,post_logout_redirect_uri:o=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),l=await this.metadataService.getEndSessionEndpoint();if(!l)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",l),!t&&o&&!e&&(t=this.settings.client_id);const c=new tY({url:l,id_token_hint:e,client_id:t,post_logout_redirect_uri:o,state_data:r,extraQueryParams:s,request_type:n,url_state:i});await this.clearStaleState();const u=c.state;return u&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),c}async readSignoutResponseState(r,e=!1){const t=this._logger.create("readSignoutResponseState"),n=new rY(zk.readParams(r,this.settings.response_mode));if(!n.state){if(t.debug("No state in response"),n.error)throw t.warn("Response was error:",n.error),new Jd(n);return{state:void 0,response:n}}const i=await this.settings.stateStore[e?"remove":"get"](n.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await cv.fromStorageString(i),response:n}}async processSignoutResponse(r){const e=this._logger.create("processSignoutResponse"),{state:t,response:n}=await this.readSignoutResponseState(r,!0);return t?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,t)):e.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),cv.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(r,e){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:r,token_type_hint:e})}},Wr=function(r){return r.NotSupported="OIDC authentication not supported",r.Misconfigured="OIDC is misconfigured",r.General="Something went wrong with OIDC discovery",r.OpSupport="Configured OIDC OP does not support required functions",r.DynamicRegistrationNotSupported="Dynamic registration not supported",r.DynamicRegistrationFailed="Dynamic registration failed",r.DynamicRegistrationInvalid="Dynamic registration invalid response",r.CodeExchangeFailed="Failed to exchange code for token",r.InvalidBearerTokenResponse="Invalid bearer token response",r.InvalidIdToken="Invalid ID token",r.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",r}({}),Bw=r=>!!r&&typeof r=="object"&&!Array.isArray(r),Is=(r,e)=>!r[e]||!ad(r,e)?(S.error("Missing or invalid property: ".concat(e)),!1):!0,ad=(r,e)=>r[e]&&typeof r[e]!="string"?(S.error("Invalid property: ".concat(e)),!1):!0,aY=(r,e)=>r[e]&&(!Array.isArray(r[e])||!r[e].every(t=>typeof t=="string"))?(S.error("Invalid property: ".concat(e)),!1):!0,ly=(r,e,t)=>{var n=r[e];return!n||!Array.isArray(n)||!n.includes(t)?(S.error("Invalid property: ".concat(e,". ").concat(t," is required.")),!1):!0},Kw=r=>{if(!Bw(r))throw S.error("Issuer configuration not found or malformed"),new Error(Wr.OpSupport);var e=[Is(r,"authorization_endpoint"),Is(r,"token_endpoint"),Is(r,"revocation_endpoint"),ad(r,"registration_endpoint"),ad(r,"account_management_uri"),ad(r,"device_authorization_endpoint"),aY(r,"account_management_actions_supported"),ly(r,"response_types_supported","code"),ly(r,"grant_types_supported","authorization_code"),ly(r,"code_challenge_methods_supported","S256")].some(t=>!t);if(!e)return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint,registrationEndpoint:r.registration_endpoint,accountManagementEndpoint:r.account_management_uri,accountManagementActionsSupported:r.account_management_actions_supported};throw S.error("Issuer configuration not valid"),new Error(Wr.OpSupport)};function KN(r){Kw(r)}var VN=r=>{try{return NN(r)}catch(e){throw S.error("Could not decode id_token",e),e}},$N=(r,e,t,n)=>{try{if(!r)throw new Error("No ID token");var i=VN(r);if(i.iss!==e)throw new Error("Invalid issuer");if(i.aud!==t)throw new Error("Invalid audience");if(n!==void 0&&i.nonce!==n)throw new Error("Invalid nonce");if(!i.exp||Date.now()>i.exp*1e3)throw new Error("Invalid expiry")}catch(o){throw S.error("Invalid ID token",o),new Error(Wr.InvalidIdToken)}};function WN(r){if(!Bw(r))throw S.error("Stored user state not found"),new Error(Wr.MissingOrInvalidStoredState);var e=[Is(r,"homeserverUrl"),Is(r,"nonce"),ad(r,"identityServerUrl")].some(t=>!t);if(e)throw new Error(Wr.MissingOrInvalidStoredState)}var lY=r=>Bw(r)&&Is(r,"token_type")&&r.token_type.toLowerCase()==="bearer"&&Is(r,"access_token")&&Is(r,"refresh_token")&&(!("expires_in"in r)||typeof r.expires_in=="number");function qN(r){if(!lY(r))throw new Error(Wr.InvalidBearerTokenResponse)}function Yk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function uv(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Yk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Yk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Om=r=>{var e=r??Ei(10);return"openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:".concat(e)},cY=function(){var r=_(function*(e){if(!globalThis.crypto.subtle)return S.warn("A secure context is required to generate code challenge. Using plain text code challenge"),e;var t=yield wN(e);return mm(t)});return function(t){return r.apply(this,arguments)}}(),uY=r=>{var{redirectUri:e}=r;return{scope:Om(),redirectUri:e,state:Ei(8),nonce:Ei(8),codeVerifier:Ei(64)}},dY=function(){var r=_(function*(e,t,n){var{scope:i,redirectUri:o,state:s,nonce:a,codeVerifier:l}=n,c=new URL(e);return c.searchParams.append("response_mode","query"),c.searchParams.append("response_type","code"),c.searchParams.append("redirect_uri",o),c.searchParams.append("client_id",t),c.searchParams.append("state",s),c.searchParams.append("scope",i),c.searchParams.append("nonce",a),c.searchParams.append("code_challenge_method","S256"),c.searchParams.append("code_challenge",yield cY(l)),c.toString()});return function(t,n,i){return r.apply(this,arguments)}}(),fY=function(){var r=_(function*(e){var{metadata:t,redirectUri:n,clientId:i,homeserverUrl:o,identityServerUrl:s,nonce:a,prompt:l,urlState:c}=e,u=Om(),d=new Fw(uv(uv({},t),{},{client_id:i,redirect_uri:n,authority:t.issuer,response_mode:"query",response_type:"code",scope:u,stateStore:new xm({prefix:"mx_oidc_",store:window.sessionStorage})})),f={homeserverUrl:o,nonce:a,identityServerUrl:s},p=yield d.createSigninRequest({state:f,nonce:a,prompt:l,url_state:c});return p.url});return function(t){return r.apply(this,arguments)}}(),hY=r=>({id_token:r.id_token,scope:r.scope,expires_at:r.expires_at,refresh_token:r.refresh_token,access_token:r.access_token,token_type:"Bearer"}),pY=function(){var r=_(function*(e,t){var n=new URL(window.location.origin);n.searchParams.append("code",e),n.searchParams.append("state",t),zd.setLogger(S);try{var i=new rp(n.searchParams),o=new xm({prefix:"mx_oidc_",store:window.sessionStorage}),s=yield o.get(i.state);if(!s)throw new Error(Wr.MissingOrInvalidStoredState);var a=yield jw.fromStorageString(s),l=new Fw(uv(uv({},a),{},{stateStore:o})),c=yield l.processSigninResponse(n.href),u=c.userState;WN(u),qN(c),$N(c.id_token,l.settings.authority,l.settings.client_id,u.nonce);var d=hY(c);return{oidcClientSettings:{clientId:l.settings.client_id,issuer:l.settings.authority},tokenResponse:d,homeserverUrl:u.homeserverUrl,identityServerUrl:u.identityServerUrl,idTokenClaims:c.profile}}catch(p){S.error("Oidc login failed",p);var f=p.message;throw Object.values(Wr).includes(f)?p:new Error(Wr.CodeExchangeFailed)}});return function(t,n){return r.apply(this,arguments)}}();function Jk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Xk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Jk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Jk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var GN=function(){var r=_(function*(e){var t,n=new URL(".well-known/openid-configuration",e),i=yield fetch(n,{method:Z.Get,signal:hm(5e3)}),o=yield i.json(),s=Kw(o),a=new l_({authority:e,redirect_uri:"",client_id:""}),l=new UN(a),c=yield l.getMetadata(),u=(t=yield l.getSigningKeys())!==null&&t!==void 0?t:void 0;return KN(c),Xk(Xk({},s),{},{metadata:c,signingKeys:u})});return function(t){return r.apply(this,arguments)}}(),vY="urn:ietf:params:oauth:grant-type:device_code",mY=function(){var r=_(function*(e,t){if(!e.registrationEndpoint)throw new Error(Wr.DynamicRegistrationNotSupported);var n=["authorization_code","refresh_token"];if(n.some(c=>!e.metadata.grant_types_supported.includes(c)))throw new Error(Wr.DynamicRegistrationNotSupported);var i={client_name:t.clientName,client_uri:t.clientUri,response_types:["code"],grant_types:n,redirect_uris:t.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:t.applicationType,logo_uri:t.logoUri,contacts:t.contacts,policy_uri:t.policyUri,tos_uri:t.tosUri},o={Accept:"application/json","Content-Type":"application/json"};try{var s=yield fetch(e.registrationEndpoint,{method:Z.Post,headers:o,body:JSON.stringify(i)});if(s.status>=400)throw new Error(Wr.DynamicRegistrationFailed);var a=yield s.json(),l=a.client_id;if(!l||typeof l!="string")throw new Error(Wr.DynamicRegistrationInvalid);return l}catch(c){throw Object.values(Wr).includes(c.message)?c:(S.error("Dynamic registration request failed",c),new Error(Wr.DynamicRegistrationFailed))}});return function(t,n){return r.apply(this,arguments)}}();function Qk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Zk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Qk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Qk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class gY{constructor(e,t,n,i,o){this.idTokenClaims=o,v(this,"oidcClientReady",void 0),v(this,"oidcClient",void 0),v(this,"inflightRefreshRequest",void 0),this.oidcClientReady=this.initialiseOidcClient(e,t,i,n)}initialiseOidcClient(e,t,n,i){var o=this;return _(function*(){try{var s=yield GN(e),a=Om(n);o.oidcClient=new Fw(Zk(Zk({},s.metadata),{},{client_id:t,scope:a,redirect_uri:i,authority:s.metadata.issuer,stateStore:new xm({prefix:"mx_oidc_",store:window.sessionStorage})}))}catch(l){throw S.error("Failed to initialise OIDC client.",l),new Error("Failed to initialise OIDC client.")}})()}doRefreshAccessToken(e){var t=this;return _(function*(){t.inflightRefreshRequest||(t.inflightRefreshRequest=t.getNewTokens(e));try{var n=yield t.inflightRefreshRequest;return n}finally{t.inflightRefreshRequest=void 0}})()}persistTokens(e){return _(function*(){})()}getNewTokens(e){var t=this;return _(function*(){if(!t.oidcClient)throw new Error("Cannot get new token before OIDC client is initialised.");var n={refresh_token:e,session_state:"test",data:void 0,profile:t.idTokenClaims},i=yield t.oidcClient.useRefreshToken({state:n,timeoutInSeconds:300}),o={accessToken:i.access_token,refreshToken:i.refresh_token};return yield t.persistTokens(o),o})()}}var eI=function(){},yY=10;class SY{constructor(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.client=e,this.timelineSet=t,v(this,"windowLimit",void 0),v(this,"start",void 0),v(this,"end",void 0),v(this,"eventCount",0),this.windowLimit=i.windowLimit||1e3,(n=t.room)===null||n===void 0||n.on(fe.Timeline,this.onTimelineEvent.bind(this))}load(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20,n=i=>{if(!i)throw new Error("No timeline given to initFields");var o,s=i.getEvents();if(!e)o=s.length;else if(o=s.findIndex(c=>c.getId()===e),o<0)throw new Error("getEventTimeline result didn't include requested event");var a=Math.min(s.length,o+Math.ceil(t/2)),l=Math.max(0,a-t);this.start=new d_(i,l-i.getBaseIndex()),this.end=new d_(i,a-i.getBaseIndex()),this.eventCount=a-l};return this.timelineSet.getTimelineForEvent(e)?(n(this.timelineSet.getTimelineForEvent(e)),Promise.resolve()):e?this.client.getEventTimeline(this.timelineSet,e).then(n):(n(this.timelineSet.getLiveTimeline()),Promise.resolve())}getTimelineIndex(e){if(e==Ee.BACKWARDS){var t;return(t=this.start)!==null&&t!==void 0?t:null}else if(e==Ee.FORWARDS){var n;return(n=this.end)!==null&&n!==void 0?n:null}else throw new Error("Invalid direction '"+e+"'")}extend(e,t){var n=this.getTimelineIndex(e);if(!n)return!1;var i=e==Ee.BACKWARDS?n.retreat(t):n.advance(t);if(i){this.eventCount+=i,eI("TimelineWindow: increased cap by "+i+" (now "+this.eventCount+")");var o=this.eventCount-this.windowLimit;return o>0&&this.unpaginate(o,e!=Ee.BACKWARDS),!0}return!1}onTimelineEvent(e,t,n,i){i&&this.onEventRemoved()}onEventRemoved(){var e=this.getEvents();e.length>0&&e[e.length-1]===void 0&&this.end&&this.end.index--}canPaginate(e){var t=this.getTimelineIndex(e);if(!t)return!1;if(e==Ee.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;var n=t.timeline.getNeighbouringTimeline(e),i=t.timeline.getPaginationToken(e);return!!n||!!i}paginate(e,t){var n=arguments,i=this;return _(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!0,s=n.length>3&&n[3]!==void 0?n[3]:yY,a=i.getTimelineIndex(e);if(!a)return!1;if(a.pendingPaginate)return a.pendingPaginate;if(i.extend(e,t))return!0;if(!o||s===0)return!1;var l=a.timeline.getPaginationToken(e);if(!l)return!1;var c=i.client.paginateEventTimeline(a.timeline,{backwards:e==Ee.BACKWARDS,limit:t}).finally(function(){a.pendingPaginate=void 0}).then(u=>u?i.paginate(e,t,!0,s-1):i.paginate(e,t,!1,0));return a.pendingPaginate=c,c})()}unpaginate(e,t){var n=t?this.start:this.end;if(!n)throw new Error("Attempting to unpaginate startOfTimeline=".concat(t," but don't have this direction"));if(e>this.eventCount||e<0)throw new Error("Attemting to unpaginate ".concat(e," events, but only have ").concat(this.eventCount," in the timeline"));for(;e>0;){var i=t?n.advance(e):n.retreat(e);if(i<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=i,this.eventCount-=i,eI("TimelineWindow.unpaginate: dropped "+i+" (now "+this.eventCount+")")}}getEvents(){if(!this.start)return[];for(var e=[],t=this.start.timeline;t;){var n,i,o=t.getEvents(),s=0,a=o.length;t===this.start.timeline&&(s=this.start.index+t.getBaseIndex()),t===((n=this.end)===null||n===void 0?void 0:n.timeline)&&(a=this.end.index+t.getBaseIndex());for(var l=s;l<a;l++)e.push(o[l]);if(t===((i=this.end)===null||i===void 0?void 0:i.timeline))break;t=t.getNeighbouringTimeline(Ee.FORWARDS)}return e}}class d_{constructor(e,t){this.timeline=e,this.index=t,v(this,"pendingPaginate",void 0)}minIndex(){return this.timeline.getBaseIndex()*-1}maxIndex(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()}advance(e){if(!e)return 0;var t;if(e<0){if(t=Math.max(e,this.minIndex()-this.index),t<0)return this.index+=t,t}else if(t=Math.min(e,this.maxIndex()-this.index),t>0)return this.index+=t,t;var n=this.timeline.getNeighbouringTimeline(e<0?Ee.BACKWARDS:Ee.FORWARDS);return n?(this.timeline=n,e<0?this.index=this.maxIndex():this.index=this.minIndex(),this.advance(e)):0}retreat(e){return this.advance(e*-1)*-1}}var wu="m.login.email.identity",tI="m.login.msisdn",f_=function(r){return r.Password="m.login.password",r.Recaptcha="m.login.recaptcha",r.Terms="m.login.terms",r.Email="m.login.email.identity",r.Msisdn="m.login.msisdn",r.Sso="m.login.sso",r.SsoUnstable="org.matrix.login.sso",r.Dummy="m.login.dummy",r.RegistrationToken="m.login.registration_token",r.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token",r}({});class HN extends Error{constructor(e,t,n){super(e),this.required_stages=t,this.flows=n,v(this,"name","NoAuthFlowFoundError")}}class bY{constructor(e){var t=this;v(this,"matrixClient",void 0),v(this,"inputs",void 0),v(this,"clientSecret",void 0),v(this,"requestCallback",void 0),v(this,"busyChangedCallback",void 0),v(this,"stateUpdatedCallback",void 0),v(this,"requestEmailTokenCallback",void 0),v(this,"supportedStages",void 0),v(this,"data",void 0),v(this,"emailSid",void 0),v(this,"requestingEmailToken",!1),v(this,"attemptAuthDeferred",null),v(this,"chosenFlow",null),v(this,"currentStage",null),v(this,"emailAttempt",1),v(this,"submitPromise",null),v(this,"requestEmailToken",_(function*(){if(t.requestingEmailToken)S.warn("Could not request email token: Already requesting");else{S.trace("Requesting email token. Attempt: "+t.emailAttempt),t.requestingEmailToken=!0;try{var n=yield t.requestEmailTokenCallback(t.inputs.emailAddress,t.clientSecret,t.emailAttempt++,t.data.session);t.emailSid=n.sid,S.trace("Email token request succeeded")}finally{t.requestingEmailToken=!1}}})),this.matrixClient=e.matrixClient,this.data=e.authData||{flows:[]},this.requestCallback=e.doRequest,this.busyChangedCallback=e.busyChanged,this.stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this.requestEmailTokenCallback=e.requestEmailToken,this.inputs=e.inputs||{},e.sessionId&&(this.data.session=e.sessionId),this.clientSecret=e.clientSecret||this.matrixClient.generateClientSecret(),this.emailSid=e.emailSid,e.supportedStages!==void 0&&(this.supportedStages=new Set(e.supportedStages))}attemptAuth(){var e=this;return _(function*(){var t;e.attemptAuthDeferred=Gs();var n=e.attemptAuthDeferred.promise;if((t=e.data)!==null&&t!==void 0&&(t=t.flows)!==null&&t!==void 0&&t.length)e.startNextAuthStage();else{var i;(i=e.busyChangedCallback)===null||i===void 0||i.call(e,!0);var o=e.data.session?{session:e.data.session}:null;e.doRequest(o).finally(()=>{var s;(s=e.busyChangedCallback)===null||s===void 0||s.call(e,!1)})}return n})()}poll(){var e=this;return _(function*(){if(e.data.session&&e.attemptAuthDeferred&&!e.submitPromise){var t={};if(e.currentStage==wu&&e.emailSid){var n={sid:e.emailSid,client_secret:e.clientSecret},i=e.matrixClient.getIdentityServerUrl();i&&(n.id_server=new URL(i).host),t={type:wu,threepid_creds:n}}e.submitAuthDict(t,!0)}})()}getSessionId(){var e;return(e=this.data)===null||e===void 0?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var t;return(t=this.data)===null||t===void 0||(t=t.params)===null||t===void 0?void 0:t[e]}getChosenFlow(){return this.chosenFlow}submitAuthDict(e){var t=arguments,n=this;return _(function*(){var i,o=t.length>1&&t[1]!==void 0?t[1]:!1;if(!n.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");if(!o){var s;(s=n.busyChangedCallback)===null||s===void 0||s.call(n,!0)}for(;n.submitPromise;)try{yield n.submitPromise}catch{}var a;(i=n.data)!==null&&i!==void 0&&i.session?(a={session:n.data.session},Object.assign(a,e)):a=e;try{n.submitPromise=n.doRequest(a,o),yield n.submitPromise}finally{if(n.submitPromise=null,!o){var l;(l=n.busyChangedCallback)===null||l===void 0||l.call(n,!1)}}})()}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}doRequest(e){var t=arguments,n=this;return _(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;try{var o=yield n.requestCallback(e,i);n.attemptAuthDeferred.resolve(o),n.attemptAuthDeferred=null}catch(h){var s,a,l,c,u=h instanceof hr?h:null,d=(s=u==null||(a=u.data)===null||a===void 0?void 0:a.flows)!==null&&s!==void 0?s:null,f=((l=n.data)===null||l===void 0?void 0:l.flows)||!!d;if(!u||u.httpStatus!==401||!u.data||!f)if(i)S.log("Background poll request failed doing UI auth: ignoring",h);else{var p;(p=n.attemptAuthDeferred)===null||p===void 0||p.reject(h)}u&&!u.data&&(u.data={}),u&&!u.data.flows&&!u.data.completed&&!u.data.session&&(u.data.flows=n.data.flows,u.data.completed=n.data.completed,u.data.session=n.data.session),u&&(n.data=u.data);try{n.startNextAuthStage()}catch(m){n.attemptAuthDeferred.reject(m),n.attemptAuthDeferred=null;return}if(!n.emailSid&&(c=n.chosenFlow)!==null&&c!==void 0&&c.stages.includes(f_.Email))try{yield n.requestEmailToken()}catch(m){n.attemptAuthDeferred.reject(m),n.attemptAuthDeferred=null}}})()}startNextAuthStage(){var e,t,n=this.chooseStage();if(!n)throw new Error("No incomplete flows from the server");if(this.currentStage=n,n===f_.Dummy){this.submitAuthDict({type:"m.login.dummy"});return}if((e=this.data)!==null&&e!==void 0&&e.errcode||(t=this.data)!==null&&t!==void 0&&t.error){var i,o;this.stateUpdatedCallback(n,{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(n,n===wu?{emailSid:this.emailSid}:{})}chooseStage(){this.chosenFlow===null&&(this.chosenFlow=this.chooseFlow()),S.log("Active flow => %s",JSON.stringify(this.chosenFlow));var e=this.firstUncompletedStage(this.chosenFlow);return S.log("Next stage: %s",e),e}scoreFlow(e){var t=e.stages.length;return this.supportedStages!==void 0&&(t+=e.stages.filter(n=>!this.supportedStages.has(n)).length*10),t}chooseFlow(){var e,t=((e=this.data)===null||e===void 0?void 0:e.flows)||[],n=!!this.inputs.emailAddress||!!this.emailSid,i=!!this.inputs.phoneCountry&&!!this.inputs.phoneNumber;t.sort((u,d)=>this.scoreFlow(u)-this.scoreFlow(d));for(var o of t){var s=!1,a=!1;for(var l of o.stages)l===wu?s=!0:l==tI&&(a=!0);if(s==n&&a==i)return o}var c=[];throw n&&c.push(wu),i&&c.push(tI),new HN("No appropriate authentication flow found",c,t)}firstUncompletedStage(e){var t,n=((t=this.data)===null||t===void 0?void 0:t.completed)||[];return e.stages.find(i=>!n.includes(i))}}var zN=[r=>{r.createObjectStore("users",{keyPath:["userId"]}),r.createObjectStore("accountData",{keyPath:["type"]}),r.createObjectStore("sync",{keyPath:["clobber"]})},r=>{var e=r.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]});e.createIndex("room","room_id")},r=>{r.createObjectStore("client_options",{keyPath:["clobber"]})},r=>{r.createObjectStore("to_device_queue",{autoIncrement:!0})}],_Y=zN.length;function yh(r,e,t){var n=r.openCursor(e);return new Promise((i,o)=>{var s=[];n.onerror=()=>{o(new Error("Query failed: "+n.error))},n.onsuccess=()=>{var a=n.result;if(!a){i(s);return}s.push(t(a)),a.continue()}})}function oa(r){return new Promise((e,t)=>{r.oncomplete=function(n){e(n)},r.onerror=function(){t(r.error)}})}function YN(r){return new Promise((e,t)=>{r.onsuccess=function(n){e(n)},r.onerror=function(){t(r.error)}})}function EY(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r),r.onerror=n=>t(n)})}function cy(r){return YN(r).then(e=>r.result)}class rI{static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),nN(e,t)}constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"default";this.indexedDB=e,v(this,"dbName",void 0),v(this,"syncAccumulator",void 0),v(this,"db",void 0),v(this,"disconnected",!0),v(this,"_isNewlyCreated",!1),v(this,"syncToDatabasePromise",void 0),v(this,"pendingUserPresenceData",[]),this.dbName="matrix-js-sdk:"+t,this.syncAccumulator=new DN}connect(e){var t=this;if(!this.disconnected)return S.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,S.log("LocalIndexedDBStoreBackend.connect: connecting...");var n=this.indexedDB.open(this.dbName,_Y);return n.onupgradeneeded=i=>{var o=n.result,s=i.oldVersion;S.log("LocalIndexedDBStoreBackend.connect: upgrading from ".concat(s)),s<1&&(this._isNewlyCreated=!0),zN.forEach((a,l)=>{s<=l&&a(o)})},n.onblocked=()=>{S.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},S.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),YN(n).then(_(function*(){S.log("LocalIndexedDBStoreBackend.connect: connected"),t.db=n.result,t.db.onversionchange=()=>{var i;(i=t.db)===null||i===void 0||i.close(),t.disconnected=!0,t.db=void 0},t.db.onclose=()=>{t.disconnected=!0,t.db=void 0,e==null||e()},yield t.init()}))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then(e=>{var[t,n]=e;S.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:n.nextBatch,rooms:n.roomsData,account_data:{events:t}},!0)})}getOutOfBandMembers(e){return new Promise((t,n)=>{var i=this.db.transaction(["oob_membership_events"],"readonly"),o=i.objectStore("oob_membership_events"),s=o.index("room"),a=IDBKeyRange.only(e),l=s.openCursor(a),c=[],u=!1;l.onsuccess=()=>{var d=l.result;if(!d)return!c.length&&!u?t(null):t(c);var f=d.value;f.oob_written?u=!0:c.push(f),d.continue()},l.onerror=d=>{n(d)}}).then(t=>(S.log("LL: got ".concat(t==null?void 0:t.length," membershipEvents from storage for room ").concat(e," ...")),t))}setOutOfBandMembers(e,t){var n=this;return _(function*(){S.log("LL: backend about to store ".concat(t.length)+" members for ".concat(e));var i=n.db.transaction(["oob_membership_events"],"readwrite"),o=i.objectStore("oob_membership_events");t.forEach(a=>{o.put(a)});var s={room_id:e,oob_written:!0,state_key:0};o.put(s),yield oa(i),S.log("LL: backend done storing for ".concat(e,"!"))})()}clearOutOfBandMembers(e){var t=this;return _(function*(){var n=t.db.transaction(["oob_membership_events"],"readonly"),i=n.objectStore("oob_membership_events"),o=i.index("room"),s=IDBKeyRange.only(e),a=cy(o.openKeyCursor(s,"next")).then(h=>(h==null?void 0:h.primaryKey)[1]),l=cy(o.openKeyCursor(s,"prev")).then(h=>(h==null?void 0:h.primaryKey)[1]),[c,u]=yield Promise.all([a,l]),d=t.db.transaction(["oob_membership_events"],"readwrite"),f=d.objectStore("oob_membership_events"),p=IDBKeyRange.bound([e,c],[e,u]);S.log("LL: Deleting all users + marker in storage for room ".concat(e,", with key range:"),[e,c],[e,u]),yield EY(f.delete(p))})()}clearDatabase(){return new Promise(e=>{var t;S.log("Removing indexeddb instance: ".concat(this.dbName)),(t=this.db)===null||t===void 0||t.close();var n=this.indexedDB.deleteDatabase(this.dbName);n.onblocked=()=>{S.log("can't yet delete indexeddb ".concat(this.dbName," because it is open elsewhere"))},n.onerror=()=>{S.warn("unable to delete js-sdk store indexeddb: ".concat(n.error)),e()},n.onsuccess=()=>{S.log("Removed indexeddb instance: ".concat(this.dbName)),e()}})}getSavedSync(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(lm(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then(()=>{this.syncAccumulator.accumulate(e)})}syncToDatabase(e){var t=this;return _(function*(){return t.syncToDatabasePromise?(S.warn("Skipping syncToDatabase() as persist already in flight"),t.pendingUserPresenceData.push(...e),t.syncToDatabasePromise):(e.unshift(...t.pendingUserPresenceData),t.syncToDatabasePromise=t.doSyncToDatabase(e),t.syncToDatabasePromise)})()}doSyncToDatabase(e){var t=this;return _(function*(){try{var n=t.syncAccumulator.getJSON(!0);yield Promise.all([t.persistUserPresenceEvents(e),t.persistAccountData(n.accountData),t.persistSyncData(n.nextBatch,n.roomsData)])}finally{t.syncToDatabasePromise=void 0}})()}persistSyncData(e,t){return S.log("Persisting sync data up to",e),ca(()=>{var n=this.db.transaction(["sync"],"readwrite"),i=n.objectStore("sync");return i.put({clobber:"-",nextBatch:e,roomsData:t}),oa(n).then(()=>{S.log("Persisted sync data up to",e)})})}persistAccountData(e){return ca(()=>{var t=this.db.transaction(["accountData"],"readwrite"),n=t.objectStore("accountData");for(var i of e)n.put(i);return oa(t).then()})}persistUserPresenceEvents(e){return ca(()=>{var t=this.db.transaction(["users"],"readwrite"),n=t.objectStore("users");for(var i of e)n.put({userId:i[0],event:i[1]});return oa(t).then()})}getUserPresenceEvents(){return ca(()=>{var e=this.db.transaction(["users"],"readonly"),t=e.objectStore("users");return yh(t,void 0,n=>[n.value.userId,n.value.event])})}loadAccountData(){return S.log("LocalIndexedDBStoreBackend: loading account data..."),ca(()=>{var e=this.db.transaction(["accountData"],"readonly"),t=e.objectStore("accountData");return yh(t,void 0,n=>n.value).then(n=>(S.log("LocalIndexedDBStoreBackend: loaded account data"),n))})}loadSyncData(){return S.log("LocalIndexedDBStoreBackend: loading sync data..."),ca(()=>{var e=this.db.transaction(["sync"],"readonly"),t=e.objectStore("sync");return yh(t,void 0,n=>n.value).then(n=>(S.log("LocalIndexedDBStoreBackend: loaded sync data"),n.length>1&&S.warn("loadSyncData: More than 1 sync row found."),n.length>0?n[0]:{}))})}getClientOptions(){return Promise.resolve().then(()=>{var e=this.db.transaction(["client_options"],"readonly"),t=e.objectStore("client_options");return yh(t,void 0,n=>{var i;return(i=n.value)===null||i===void 0?void 0:i.options}).then(n=>n[0])})}storeClientOptions(e){var t=this;return _(function*(){var n=t.db.transaction(["client_options"],"readwrite"),i=n.objectStore("client_options");i.put({clobber:"-",options:e}),yield oa(n)})()}saveToDeviceBatches(e){var t=this;return _(function*(){var n=t.db.transaction(["to_device_queue"],"readwrite"),i=n.objectStore("to_device_queue");for(var o of e)i.add(o);yield oa(n)})()}getOldestToDeviceBatch(){var e=this;return _(function*(){var t=e.db.transaction(["to_device_queue"],"readonly"),n=t.objectStore("to_device_queue"),i=yield cy(n.openCursor());if(!i)return null;var o=i.value;return{id:i.key,txnId:o.txnId,eventType:o.eventType,batch:o.batch}})()}removeToDeviceBatch(e){var t=this;return _(function*(){var n=t.db.transaction(["to_device_queue"],"readwrite"),i=n.objectStore("to_device_queue");i.delete(e),yield oa(n)})()}destroy(){var e=this;return _(function*(){var t;(t=e.db)===null||t===void 0||t.close()})()}}class wY{constructor(e,t){this.workerFactory=e,this.dbName=t,v(this,"worker",void 0),v(this,"nextSeq",0),v(this,"inFlight",{}),v(this,"startPromise",void 0),v(this,"onWorkerMessage",n=>{var i=n.data;if(i.command=="closed"){var o;(o=this.onClose)===null||o===void 0||o.call(this)}else if(i.command=="cmd_success"||i.command=="cmd_fail"){if(i.seq===void 0){S.error("Got reply from worker with no seq");return}var s=this.inFlight[i.seq];if(s===void 0){S.error("Got reply for unknown seq "+i.seq);return}if(delete this.inFlight[i.seq],i.command=="cmd_success")s.resolve(i.result);else{var a=new Error(i.error.message);a.name=i.error.name,s.reject(a)}}else S.warn("Unrecognised message from worker: ",i)})}connect(e){return this.onClose=e,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(e){return this.doCmd("setSyncData",[e])}syncToDatabase(e){return this.doCmd("syncToDatabase",[e])}getOutOfBandMembers(e){return this.doCmd("getOutOfBandMembers",[e])}setOutOfBandMembers(e,t){return this.doCmd("setOutOfBandMembers",[e,t])}clearOutOfBandMembers(e){return this.doCmd("clearOutOfBandMembers",[e])}getClientOptions(){return this.doCmd("getClientOptions")}storeClientOptions(e){return this.doCmd("storeClientOptions",[e])}getUserPresenceEvents(){return this.doCmd("getUserPresenceEvents")}saveToDeviceBatches(e){var t=this;return _(function*(){return t.doCmd("saveToDeviceBatches",[e])})()}getOldestToDeviceBatch(){var e=this;return _(function*(){return e.doCmd("getOldestToDeviceBatch")})()}removeToDeviceBatch(e){var t=this;return _(function*(){return t.doCmd("removeToDeviceBatch",[e])})()}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then(()=>{S.log("IndexedDB worker is ready")})),this.startPromise}doCmd(e,t){return Promise.resolve().then(()=>{var n,i=this.nextSeq++,o=Gs();return this.inFlight[i]=o,(n=this.worker)===null||n===void 0||n.postMessage({command:e,seq:i,args:t}),o.promise})}destroy(){var e=this;return _(function*(){var t;(t=e.worker)===null||t===void 0||t.terminate()})()}}var TY=1e3*60*5;class RY extends Em{static exists(e,t){return rI.exists(e,t)}constructor(e){if(super(e),v(this,"backend",void 0),v(this,"startedUp",!1),v(this,"syncTs",0),v(this,"userModifiedMap",{}),v(this,"emitter",new Tt),v(this,"onClose",()=>{this.emitter.emit("closed")}),v(this,"getSavedSync",this.degradable(()=>this.backend.getSavedSync(),"getSavedSync")),v(this,"isNewlyCreated",this.degradable(()=>this.backend.isNewlyCreated(),"isNewlyCreated")),v(this,"getSavedSyncToken",this.degradable(()=>this.backend.getNextBatchToken(),"getSavedSyncToken")),v(this,"deleteAllData",this.degradable(()=>(super.deleteAllData(),this.backend.clearDatabase().then(()=>{S.log("Deleted indexeddb data.")},t=>{throw S.error("Failed to delete indexeddb data: ".concat(t)),t})),null)),v(this,"reallySave",this.degradable(()=>{this.syncTs=Date.now();var t=[];for(var n of this.getUsers())this.userModifiedMap[n.userId]!==n.getLastModifiedTime()&&n.events.presence&&(t.push([n.userId,n.events.presence.event]),this.userModifiedMap[n.userId]=n.getLastModifiedTime());return this.backend.syncToDatabase(t)},null)),v(this,"setSyncData",this.degradable(t=>this.backend.setSyncData(t),"setSyncData")),v(this,"getOutOfBandMembers",this.degradable(t=>this.backend.getOutOfBandMembers(t),"getOutOfBandMembers")),v(this,"setOutOfBandMembers",this.degradable((t,n)=>(super.setOutOfBandMembers(t,n),this.backend.setOutOfBandMembers(t,n)),"setOutOfBandMembers")),v(this,"clearOutOfBandMembers",this.degradable(t=>(super.clearOutOfBandMembers(t),this.backend.clearOutOfBandMembers(t)),"clearOutOfBandMembers")),v(this,"getClientOptions",this.degradable(()=>this.backend.getClientOptions(),"getClientOptions")),v(this,"storeClientOptions",this.degradable(t=>(super.storeClientOptions(t),this.backend.storeClientOptions(t)),"storeClientOptions")),!e.indexedDB)throw new Error("Missing required option: indexedDB");e.workerFactory?this.backend=new wY(e.workerFactory,e.dbName):this.backend=new rI(e.indexedDB,e.dbName)}on(e,t){this.emitter.on(e,t)}startup(){return this.startedUp?(S.log("IndexedDBStore.startup: already started"),Promise.resolve()):(S.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect(this.onClose).then(()=>(S.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents())).then(e=>{S.log("IndexedDBStore.startup: processing presence events"),e.forEach(t=>{var[n,i]=t;if(!this.createUser)throw new Error("`IndexedDBStore.startup` must be called after assigning it to the client, not before!");var o=this.createUser(n);i&&o.setPresenceEvent(new pr(i)),this.userModifiedMap[o.userId]=o.getLastModifiedTime(),this.storeUser(o)}),this.startedUp=!0}))}destroy(){return this.backend.destroy()}wantsSave(){var e=Date.now();return e-this.syncTs>TY}save(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){var n=this,i=t?super[t]:null;return _(function*(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];try{return yield e.call(n,...s)}catch(l){S.error("IndexedDBStore failure, degrading to MemoryStore",l),n.emitter.emit("degraded",l);try{S.log("IndexedDBStore trying to delete degraded data"),yield n.backend.clearDatabase(),S.log("IndexedDBStore delete after degrading succeeded")}catch(c){S.warn("IndexedDBStore delete after degrading failed",c)}if(i)return i.call(n,...s)}})}getPendingEvents(e){var t=()=>super.getPendingEvents,n=this;return _(function*(){if(!n.localStorage)return t().call(n,e);var i=n.localStorage.getItem(uy(e));if(i)try{return JSON.parse(i)}catch(o){S.error("Could not parse persisted pending events",o)}return[]})()}setPendingEvents(e,t){var n=()=>super.setPendingEvents,i=this;return _(function*(){if(!i.localStorage)return n().call(i,e,t);t.length>0?i.localStorage.setItem(uy(e),JSON.stringify(t)):i.localStorage.removeItem(uy(e))})()}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function uy(r){return"mx_pending_events_".concat(r)}var CY=function(r){return r.Email="email",r.Phone="msisdn",r}({}),kY=new Ft("delegated_oidc_compatibility","org.matrix.msc3824.delegated_oidc_compatibility"),IY=function(r){return r.Gitlab="gitlab",r.Github="github",r.Apple="apple",r.Google="google",r.Facebook="facebook",r.Twitter="twitter",r}({}),xY=function(r){return r.LOGIN="login",r.REGISTER="register",r}({}),OY=function(r){return r.Global="Global",r.SetItemError="setItem",r.GetItemError="getItem",r.RemoveItemError="removeItem",r.ClearError="clear",r.QuotaExceededError="QuotaExceededError",r}({});class PY extends Tt{}new PY;var JN=()=>new cm;function XN(r){JN=r}function QN(r){var e,t,n;return r.store=(e=r.store)!==null&&e!==void 0?e:new Em({localStorage:globalThis.localStorage}),r.scheduler=(t=r.scheduler)!==null&&t!==void 0?t:new Ec,r.cryptoStore=(n=r.cryptoStore)!==null&&n!==void 0?n:JN(),r}function ZN(r){return new $c(QN(r))}function MY(r,e,t,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;return new AN(r,e,t,QN(n),i)}const AY=Object.freeze(Object.defineProperty({__proto__:null,AuthType:f_,AutoDiscovery:Ke,AutoDiscoveryAction:Dn,AutoDiscoveryError:ni,Beacon:kD,BeaconEvent:kt,CRYPTO_ENABLED:G9,CallEvent:Ye,CallFeedEvent:Li,Category:ho,ClientEvent:Te,ClientPrefix:Ot,ClientStoppedError:r8,ConditionKind:rr,ConditionOperator:Uz,ConnectionError:_f,ContentHelpers:vH,Crypto:l8,CryptoEvent:et,DELEGATED_OIDC_COMPATIBILITY:kY,DEVICE_CODE_SCOPE:vY,DMMemberCountCondition:jz,Device:YD,DeviceVerification:wo,Direction:Ge,DuplicateStrategy:ed,EVENT_VISIBILITY_CHANGE_TYPE:Ea,EventEmitterEvents:aD,EventStatus:je,EventTimeline:Ee,EventTimelineSet:Ul,EventType:V,FILTER_RELATED_BY_REL_TYPES:rc,FILTER_RELATED_BY_SENDERS:tc,FeatureSupport:Vr,Filter:gn,GET_LOGIN_TOKEN_CAPABILITY:z9,GroupCall:Sw,GroupCallEvent:yt,GroupCallIntent:XD,GroupCallState:Mt,GroupCallStatsReportEvent:Au,GroupCallType:gm,GuestAccess:av,HTTPError:yc,HistoryVisibility:Aw,HttpApiEvent:Tb,IdentityPrefix:fo,IdentityProviderBrand:IY,IndexedDBCryptoStore:be,IndexedDBStore:RY,InteractiveAuth:bY,InvalidCryptoStoreError:Rw,InvalidCryptoStoreState:Tw,JoinRule:yN,KNOWN_SAFE_ROOM_VERSION:BD,KeySignatureUploadError:Du,KnownMembership:Be,LOCAL_NOTIFICATION_SETTINGS_PREFIX:dD,LocalStorageCryptoStore:Sm,LocalStorageErrors:OY,LocationAssetType:vc,MAIN_ROOM_TIMELINE:bf,MSC3912_RELATION_BASED_REDACTIONS_PROP:Sb,M_ASSET:yf,M_BEACON:vb,M_BEACON_INFO:fw,M_HTML:P6,M_LOCATION:Sf,M_MESSAGE:O6,M_POLL_END:Jp,M_POLL_KIND_DISCLOSED:J6,M_POLL_KIND_UNDISCLOSED:X6,M_POLL_RESPONSE:jd,M_POLL_START:Q6,M_TEXT:cw,M_TIMESTAMP:qs,M_TOPIC:pw,MatrixClient:$c,MatrixError:hr,MatrixEvent:pr,MatrixEventEvent:ot,MatrixHttpApi:UD,MatrixScheduler:Ec,MediaHandlerEvent:ha,MediaPrefix:Jl,MemoryCryptoStore:cm,MemoryStore:Em,Method:Z,MsgType:xi,NoAuthFlowFoundError:HN,NotificationCountType:it,OidcError:Wr,OidcTokenRefresher:gY,PUSHER_DEVICE_ID:Z6,PUSHER_ENABLED:bb,PendingEventOrdering:wc,Poll:OD,PollEvent:cs,Preset:Mw,PushRuleActionName:ks,PushRuleKind:Er,REFERENCE_RELATION:G1,ReceiptType:Jr,RelationType:At,Relations:hw,RelationsEvent:Gh,RestrictedAllowType:C9,Room:pm,RoomCreateTypeField:Xp,RoomEvent:fe,RoomMember:Zp,RoomMemberEvent:Ar,RoomNameType:Ni,RoomState:qd,RoomStateEvent:Ne,RoomSummary:vD,RoomType:Yl,RoomVersionStability:jD,RoomWidgetClient:AN,RoomWidgetClientEvent:ep,RuleId:br,SERVICE_TYPES:jb,SSOAction:xY,SearchOrderBy:SN,SearchResult:_m,SecretStorage:N8,ServerCapabilities:FD,SetPresence:KD,SlidingSyncEvent:t_,StatsReport:To,SyncAccumulator:DN,SyncState:ct,THREAD_RELATION_TYPE:vt,Thread:Et,ThreadEvent:Xr,ThreadFilterType:di,ThreepidMedium:CY,TimelineIndex:d_,TimelineWindow:SY,ToDeviceMessageId:en,TweakName:bw,TypedEventEmitter:Tt,UNSIGNED_MEMBERSHIP_FIELD:fD,UNSIGNED_THREAD_ID_FIELD:Qp,UNSTABLE_ELEMENT_FUNCTIONAL_USERS:uD,UNSTABLE_MSC2666_MUTUAL_ROOMS:RN,UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS:CN,UNSTABLE_MSC2666_SHARED_ROOMS:TN,UNSTABLE_MSC2716_MARKER:cD,UNSTABLE_MSC3088_ENABLED:gb,UNSTABLE_MSC3088_PURPOSE:mb,UNSTABLE_MSC3089_BRANCH:yo,UNSTABLE_MSC3089_LEAF:lD,UNSTABLE_MSC3089_TREE_SUBTYPE:yb,UNSTABLE_MSC3852_LAST_SEEN_UA:H9,UNSTABLE_MSC4133_EXTENDED_PROFILES:kN,UNSTABLE_MSC4140_DELAYED_EVENTS:$i,UpdateDelayedEventAction:Jh,User:Co,UserEvent:ar,Visibility:R9,anySignal:DD,calculateRetryBackoff:LD,completeAuthorizationCodeGrant:pY,createClient:ZN,createNewMatrixCall:Bd,createRoomWidgetClient:MY,decodeBase64:Dr,decodeIdToken:VN,determineFeatureSupport:Qh,discoverAndValidateOIDCIssuerWellKnown:GN,encodeBase64:Qr,encodeUnpaddedBase64:vm,encodeUnpaddedBase64Url:mm,fixNotificationCountOnDecryption:IN,generateAuthorizationParams:uY,generateAuthorizationUrl:dY,generateOidcAuthorizationUrl:fY,generateScope:Om,getBeaconInfoIdentifier:ev,getHttpUriForMxc:um,inMainTimelineForReceipt:Wd,isDmMemberCountCondition:Fz,isEventTypeSame:M6,isPollEvent:PD,isTimestampInDuration:Eb,isValidatedIssuerMetadata:KN,parseErrorResponse:gw,registerOidcClient:mY,retryNetworkOperation:ND,safeGetRetryAfterMs:mw,setCryptoStoreFactory:XN,threadFilterTypeToFilter:xN,threadIdForReceipt:Tc,timeoutSignal:hm,validateBearerTokenResponse:qN,validateIdToken:$N,validateOIDCIssuerWellKnown:Kw,validateStoredUserState:WN},Symbol.toStringTag,{value:"Module"}));if(globalThis.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");globalThis.__js_sdk_entrypoint=!0;var h_;try{h_=globalThis.indexedDB}catch{}h_&&XN(()=>new be(h_,"matrix-js-sdk:crypto"));globalThis.matrixcs=AY;class DY{constructor(e){this.namespace=e}k(e){return`${this.namespace}:${e}`}get(e){return localStorage.getItem(this.k(e))}set(e,t){localStorage.setItem(this.k(e),t)}remove(e){localStorage.removeItem(this.k(e))}getJSON(e){const t=this.get(e);if(t===null)return null;try{return JSON.parse(t)}catch{return null}}setJSON(e,t){this.set(e,JSON.stringify(t))}}const dy=new DY("zoon");class NY{constructor(){De(this,"client",null);De(this,"listeners",new Set)}safeGet(){return this.client}get(){if(!this.client)throw new Error("MatrixClientPeg: not logged in");return this.client}set(e){return this.client&&this.client.stopClient(),this.client=ZN({baseUrl:e.homeserverUrl,accessToken:e.accessToken,userId:e.userId,deviceId:e.deviceId,store:new Em({localStorage:globalThis.localStorage})}),dy.setJSON("session",e),this.emit(),this.client}reset(){if(this.client)try{this.client.stopClient()}catch{}this.client=null,dy.remove("session"),this.emit()}injectClientForTest(e){if(this.client)try{this.client.stopClient()}catch{}this.client=e,this.emit()}restoreFromStorage(){const e=dy.getJSON("session");return e?(this.set(e),e):null}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(){for(const e of this.listeners)e()}}const me=new NY,nI=r=>typeof r=="boolean"?`${r}`:r===0?"0":r,iI=d1,Vw=(r,e)=>t=>{var n;if((e==null?void 0:e.variants)==null)return iI(r,t==null?void 0:t.class,t==null?void 0:t.className);const{variants:i,defaultVariants:o}=e,s=Object.keys(i).map(c=>{const u=t==null?void 0:t[c],d=o==null?void 0:o[c];if(u===null)return null;const f=nI(u)||nI(d);return i[c][f]}),a=t&&Object.entries(t).reduce((c,u)=>{let[d,f]=u;return f===void 0||(c[d]=f),c},{}),l=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((c,u)=>{let{class:d,className:f,...p}=u;return Object.entries(p).every(h=>{let[m,w]=h;return Array.isArray(w)?w.includes({...o,...a}[m]):{...o,...a}[m]===w})?[...c,d,f]:c},[]);return iI(r,s,l,t==null?void 0:t.class,t==null?void 0:t.className)};function LY({className:r,...e}){return y.jsx("div",{"data-slot":"empty",className:Ue("flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance",r),...e})}function UY({className:r,...e}){return y.jsx("div",{"data-slot":"empty-header",className:Ue("flex max-w-sm flex-col items-center gap-2",r),...e})}const jY=Vw("mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",icon:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4"}},defaultVariants:{variant:"default"}});function FY({className:r,variant:e="default",...t}){return y.jsx("div",{"data-slot":"empty-icon","data-variant":e,className:Ue(jY({variant:e,className:r})),...t})}function BY({className:r,...e}){return y.jsx("div",{"data-slot":"empty-description",className:Ue("text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",r),...e})}function KY({className:r,...e}){return y.jsx(Lv,{role:"status","aria-label":"Loading",className:Ue("size-4 animate-spin",r),...e})}async function VY(r){const e=await fetch(`${r}/_matrix/client/v3/login`);if(!e.ok)throw await $w(e);return(await e.json()).flows}async function $Y(r,e,t){const n=await fetch(`${r}/_matrix/client/v3/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"m.login.password",identifier:{type:"m.id.user",user:e},password:t,initial_device_display_name:"Zoon Web"})});if(!n.ok)throw await $w(n);return eL(r,await n.json())}async function WY(r,e){const t=await fetch(`${r}/_matrix/client/v3/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"m.login.token",token:e,initial_device_display_name:"Zoon Web"})});if(!t.ok)throw await $w(t);return eL(r,await t.json())}function qY(r,e,t){const n=t?`/_matrix/client/v3/login/sso/redirect/${encodeURIComponent(t)}`:"/_matrix/client/v3/login/sso/redirect";return`${r}${n}?redirectUrl=${encodeURIComponent(e)}`}function eL(r,e){const t=e;return{homeserverUrl:r,accessToken:t.access_token,userId:t.user_id,deviceId:t.device_id}}async function $w(r){try{const e=await r.json();return new Error(e.error??e.errcode??`HTTP ${r.status}`)}catch{return new Error(`HTTP ${r.status}`)}}function GY({homeserverUrl:r}){const[e]=DP(),t=e.get("loginToken"),[n,i]=E.useState(null),[o,s]=E.useState(!1);return E.useEffect(()=>{t&&WY(r,t).then(a=>{me.set(a),s(!0)}).catch(a=>i(a instanceof Error?a.message:String(a)))},[r,t]),t?n?y.jsx("div",{role:"alert",children:n}):o?y.jsx(Mp,{to:"/",replace:!0}):y.jsx(LY,{className:"min-h-screen",role:"status",children:y.jsxs(UY,{children:[y.jsx(FY,{children:y.jsx(KY,{"aria-label":"Completing sign-in"})}),y.jsx(BY,{children:"Completing sign-in…"})]})}):y.jsx(Mp,{to:"/login",replace:!0})}const HY=Vw("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",outline:"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",ghost:"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",xs:"h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",lg:"h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",icon:"size-8","icon-xs":"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg","icon-lg":"size-9"}},defaultVariants:{variant:"default",size:"default"}}),Gt=E.forwardRef(function({className:e,variant:t="default",size:n="default",asChild:i=!1,...o},s){const a=i?yK:"button";return y.jsx(a,{ref:s,"data-slot":"button","data-variant":t,"data-size":n,className:Ue(HY({variant:t,size:n,className:e})),...o})});function p_({className:r,size:e="default",...t}){return y.jsx("div",{"data-slot":"card","data-size":e,className:Ue("group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",r),...t})}function v_({className:r,...e}){return y.jsx("div",{"data-slot":"card-header",className:Ue("group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",r),...e})}function m_({className:r,...e}){return y.jsx("div",{"data-slot":"card-title",className:Ue("font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",r),...e})}function oI({className:r,...e}){return y.jsx("div",{"data-slot":"card-description",className:Ue("text-sm text-muted-foreground",r),...e})}function np({className:r,...e}){return y.jsx("div",{"data-slot":"card-content",className:Ue("px-4 group-data-[size=sm]/card:px-3",r),...e})}function zY({className:r,...e}){return y.jsx("div",{"data-slot":"card-footer",className:Ue("flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",r),...e})}function Xd({className:r,type:e,...t}){return y.jsx("input",{type:e,"data-slot":"input",className:Ue("h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",r),...t})}function Qd({className:r,...e}){return y.jsx(i$,{"data-slot":"label",className:Ue("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",r),...e})}function tL({className:r,orientation:e="horizontal",decorative:t=!0,...n}){return y.jsx(U$,{"data-slot":"separator",decorative:t,orientation:e,className:Ue("shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",r),...n})}function YY({homeserverUrl:r,defaultIdpLabel:e}){const[t,n]=E.useState(null),[i,o]=E.useState(null),[s,a]=E.useState(!1);if(E.useEffect(()=>{VY(r).then(n).catch(p=>o(String(p.message??p)))},[r]),!t)return y.jsx("div",{role:"status",children:"Loading login options…"});const l=t.find(p=>p.type==="m.login.password"),c=t.find(p=>p.type==="m.login.sso"),u=async p=>{p.preventDefault(),o(null),a(!0);const h=new FormData(p.currentTarget);try{const m=await $Y(r,String(h.get("username")??""),String(h.get("password")??""));me.set(m)}catch(m){o(m instanceof Error?m.message:String(m))}finally{a(!1)}},d=p=>{const h=`${window.location.origin}/auth/callback`;window.location.assign(qY(r,h,p))},f=(c==null?void 0:c.identity_providers)??(c?[{id:"",name:e??"SSO"}]:[]);return y.jsx("div",{className:"flex min-h-screen items-center justify-center p-6",children:y.jsxs(p_,{className:"w-full max-w-sm",children:[y.jsx(v_,{children:y.jsx(m_,{children:"Sign in"})}),y.jsxs(np,{className:"flex flex-col gap-4",children:[i&&y.jsx("div",{role:"alert",className:"text-destructive text-sm",children:i}),l&&y.jsxs("form",{onSubmit:u,className:"flex flex-col gap-3",children:[y.jsxs("div",{className:"flex flex-col gap-1.5",children:[y.jsx(Qd,{htmlFor:"login-username",children:"Username"}),y.jsx(Xd,{id:"login-username",name:"username",autoComplete:"username",required:!0})]}),y.jsxs("div",{className:"flex flex-col gap-1.5",children:[y.jsx(Qd,{htmlFor:"login-password",children:"Password"}),y.jsx(Xd,{id:"login-password",name:"password",type:"password",autoComplete:"current-password",required:!0})]}),y.jsx(Gt,{type:"submit",disabled:s,children:"Sign in"})]}),l&&c&&y.jsx(tL,{}),f.map(p=>y.jsxs(Gt,{type:"button",variant:"outline",onClick:()=>d(p.id||void 0),children:["Sign in with ",p.name]},p.id||"default-sso"))]})]})})}const fy=768;function JY(){const[r,e]=E.useState(void 0);return E.useEffect(()=>{const t=window.matchMedia(`(max-width: ${fy-1}px)`),n=()=>{e(window.innerWidth<fy)};return t.addEventListener("change",n),e(window.innerWidth<fy),()=>t.removeEventListener("change",n)},[]),!!r}function XY({...r}){return y.jsx(ME,{"data-slot":"sheet",...r})}function QY({...r}){return y.jsx(AE,{"data-slot":"sheet-portal",...r})}function ZY({className:r,...e}){return y.jsx(DE,{"data-slot":"sheet-overlay",className:Ue("fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",r),...e})}function eJ({className:r,children:e,side:t="right",showCloseButton:n=!0,...i}){return y.jsxs(QY,{children:[y.jsx(ZY,{}),y.jsxs(NE,{"data-slot":"sheet-content","data-side":t,className:Ue("fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10",r),...i,children:[e,n&&y.jsx(LE,{"data-slot":"sheet-close",asChild:!0,children:y.jsxs(Gt,{variant:"ghost",className:"absolute top-3 right-3",size:"icon-sm",children:[y.jsx(RE,{}),y.jsx("span",{className:"sr-only",children:"Close"})]})})]})]})}function tJ({className:r,...e}){return y.jsx("div",{"data-slot":"sheet-header",className:Ue("flex flex-col gap-0.5 p-4",r),...e})}function rJ({className:r,...e}){return y.jsx(yM,{"data-slot":"sheet-title",className:Ue("font-heading text-base font-medium text-foreground",r),...e})}function nJ({className:r,...e}){return y.jsx(SM,{"data-slot":"sheet-description",className:Ue("text-sm text-muted-foreground",r),...e})}const iJ="sidebar_state",oJ=60*60*24*7,sJ="16rem",aJ="18rem",lJ="3rem",cJ="b",rL=E.createContext(null);function Ww(){const r=E.useContext(rL);if(!r)throw new Error("useSidebar must be used within a SidebarProvider.");return r}function uJ({defaultOpen:r=!0,open:e,onOpenChange:t,className:n,style:i,children:o,...s}){const a=JY(),[l,c]=E.useState(!1),[u,d]=E.useState(r),f=e??u,p=E.useCallback(g=>{const b=typeof g=="function"?g(f):g;t?t(b):d(b),document.cookie=`${iJ}=${b}; path=/; max-age=${oJ}`},[t,f]),h=E.useCallback(()=>a?c(g=>!g):p(g=>!g),[a,p,c]);E.useEffect(()=>{const g=b=>{b.key===cJ&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),h())};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[h]);const m=f?"expanded":"collapsed",w=E.useMemo(()=>({state:m,open:f,setOpen:p,isMobile:a,openMobile:l,setOpenMobile:c,toggleSidebar:h}),[m,f,p,a,l,c,h]);return y.jsx(rL.Provider,{value:w,children:y.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":sJ,"--sidebar-width-icon":lJ,...i},className:Ue("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",n),...s,children:o})})}function dJ({side:r="left",variant:e="sidebar",collapsible:t="offcanvas",className:n,children:i,dir:o,...s}){const{isMobile:a,state:l,openMobile:c,setOpenMobile:u}=Ww();return t==="none"?y.jsx("div",{"data-slot":"sidebar",className:Ue("flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",n),...s,children:i}):a?y.jsx(XY,{open:c,onOpenChange:u,...s,children:y.jsxs(eJ,{dir:o,"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":aJ},side:r,children:[y.jsxs(tJ,{className:"sr-only",children:[y.jsx(rJ,{children:"Sidebar"}),y.jsx(nJ,{children:"Displays the mobile sidebar."})]}),y.jsx("div",{className:"flex h-full w-full flex-col",children:i})]})}):y.jsxs("div",{className:"group peer hidden text-sidebar-foreground md:block","data-state":l,"data-collapsible":l==="collapsed"?t:"","data-variant":e,"data-side":r,"data-slot":"sidebar",children:[y.jsx("div",{"data-slot":"sidebar-gap",className:Ue("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",e==="floating"||e==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),y.jsx("div",{"data-slot":"sidebar-container","data-side":r,className:Ue("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",e==="floating"||e==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...s,children:y.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:"flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border",children:i})})]})}function fJ({className:r,onClick:e,...t}){const{toggleSidebar:n}=Ww();return y.jsxs(Gt,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon-sm",className:Ue(r),onClick:i=>{e==null||e(i),n()},...t,children:[y.jsx(BP,{}),y.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function hJ({className:r,...e}){return y.jsx("main",{"data-slot":"sidebar-inset",className:Ue("relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",r),...e})}function pJ({className:r,...e}){return y.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:Ue("flex flex-col gap-2 p-2",r),...e})}function vJ({className:r,...e}){return y.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:Ue("no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",r),...e})}function mJ(){const{isMobile:r,setOpenMobile:e}=Ww();return y.jsx("div",{className:"flex h-full items-center justify-center p-6 sm:p-10",children:y.jsxs("div",{className:"flex max-w-sm flex-col items-center text-center",children:[y.jsx("div",{className:"mb-5 flex h-14 w-14 items-center justify-center rounded-2xl bg-accent text-accent-foreground",children:y.jsx(FP,{className:"h-7 w-7","aria-hidden":!0})}),y.jsx("h2",{className:"text-xl font-semibold tracking-tight text-foreground",children:"Pick a room to get started"}),y.jsx("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:r?"Open the room list to choose a conversation, or start a new one.":"Choose a room from the sidebar to view its conversation, or start a new one."}),r?y.jsxs("button",{type:"button",onClick:()=>e(!0),className:"mt-6 inline-flex items-center gap-2 rounded-md border border-border bg-background px-3 py-2 text-sm font-medium shadow-sm hover:bg-muted",children:[y.jsx(BP,{className:"h-4 w-4","aria-hidden":!0}),"Open room list"]}):null]})})}function Gi(r){return r.replace(/&/g,"&amp;").replace(/'/g,"&apos;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gJ(r){var e,t,n,i,o,s,a;const l=(e=r.meta)===null||e===void 0?void 0:e.title,c=(t=r.meta)===null||t===void 0?void 0:t.creator,u=(n=r.meta)===null||n===void 0?void 0:n.source,d=(o=(i=r.meta)===null||i===void 0?void 0:i.license)===null||o===void 0?void 0:o.url,f=yJ(r);return!l&&!c&&!u&&!d&&!f?"":'<metadata xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/"><rdf:RDF><rdf:Description>'+(l?`<dc:title>${Gi(l)}</dc:title>`:"")+(c?`<dc:creator>${Gi(c)}</dc:creator>`:"")+(u?`<dc:source xsi:type="dcterms:URI">${Gi((a=(s=r.meta)===null||s===void 0?void 0:s.source)!==null&&a!==void 0?a:"")}</dc:source>`:"")+(d?`<dcterms:license xsi:type="dcterms:URI">${Gi(d)}</dcterms:license>`:"")+(f?`<dc:rights>${Gi(f)}</dc:rights>`:"")+"</rdf:Description></rdf:RDF></metadata>"}function yJ(r){var e,t,n,i,o,s,a,l,c,u,d,f,p,h,m;let w=!((e=r.meta)===null||e===void 0)&&e.title?`„${(t=r.meta)===null||t===void 0?void 0:t.title}”`:"Design",g=`„${(i=(n=r.meta)===null||n===void 0?void 0:n.creator)!==null&&i!==void 0?i:"Unknown"}”`;!((o=r.meta)===null||o===void 0)&&o.source&&(w+=` (${r.meta.source})`);let b="";return((a=(s=r.meta)===null||s===void 0?void 0:s.license)===null||a===void 0?void 0:a.name)!=="MIT"&&((l=r.meta)===null||l===void 0?void 0:l.creator)!=="DiceBear"&&(!((c=r.meta)===null||c===void 0)&&c.title)&&(b+="Remix of "),b+=`${w} by ${g}`,!((d=(u=r.meta)===null||u===void 0?void 0:u.license)===null||d===void 0)&&d.name&&(b+=`, licensed under „${(p=(f=r.meta)===null||f===void 0?void 0:f.license)===null||p===void 0?void 0:p.name}”`,!((m=(h=r.meta)===null||h===void 0?void 0:h.license)===null||m===void 0)&&m.url&&(b+=` (${r.meta.license.url})`)),b}const sI=-2147483648,SJ=2147483647,bJ=1024;function nL(r){return r^=r<<13,r^=r>>17,r^=r<<5,r}function _J(r){let e=0;for(let t=0;t<r.length;t++)e=(e<<5)-e+r.charCodeAt(t)|0,e=nL(e);return e}function dv(r=""){r=r.toString().slice(0,bJ);let e=_J(r)||1;const t=()=>e=nL(e),n=(i,o)=>Math.floor((t()-sI)/(SJ-sI)*(o+1-i)+i);return{seed:r,next:t,bool(i=50){return n(1,100)<=i},integer(i,o){return n(i,o)},pick(i,o){var s;return i.length===0?(t(),o):(s=i[n(0,i.length-1)])!==null&&s!==void 0?s:o},shuffle(i){const o=dv(t().toString()),s=[...i];for(let a=s.length-1;a>0;a--){const l=o.integer(0,a);[s[a],s[l]]=[s[l],s[a]]}return s},string(i,o="abcdefghijklmnopqrstuvwxyz1234567890"){const s=dv(t().toString());let a="";for(let l=0;l<i;l++)a+=o[s.integer(0,o.length-1)];return a}}}function Hc(r){let e=r.attributes.viewBox.split(" "),t=parseInt(e[0]),n=parseInt(e[1]),i=parseInt(e[2]),o=parseInt(e[3]);return{x:t,y:n,width:i,height:o}}function EJ(r,e,t,n,i){let{width:o,height:s,x:a,y:l}=Hc(r);const c=`<rect fill="${Gi(e)}" width="${o}" height="${s}" x="${a}" y="${l}" />`;switch(n){case"solid":return c+r.body;case"gradientLinear":return`<rect fill="url(#backgroundLinear)" width="${o}" height="${s}" x="${a}" y="${l}" /><defs><linearGradient id="backgroundLinear" gradientTransform="rotate(${i} 0.5 0.5)"><stop stop-color="${Gi(e)}"/><stop offset="1" stop-color="${Gi(t)}"/></linearGradient></defs>`+r.body}}function wJ(r,e){let{width:t,height:n,x:i,y:o}=Hc(r),s=e?(e-100)/100:0,a=(t/2+i)*s*-1,l=(n/2+o)*s*-1;return`<g transform="translate(${a} ${l}) scale(${e/100})">${r.body}</g>`}function TJ(r,e,t){let n=Hc(r),i=(n.width+n.x*2)*((e??0)/100),o=(n.height+n.y*2)*((t??0)/100);return`<g transform="translate(${i} ${o})">${r.body}</g>`}function RJ(r,e){let{width:t,height:n,x:i,y:o}=Hc(r);return`<g transform="rotate(${e}, ${t/2+i}, ${n/2+o})">${r.body}</g>`}function CJ(r){let{width:e,x:t}=Hc(r);return`<g transform="scale(-1 1) translate(${e*-1-t*2} 0)">${r.body}</g>`}function kJ(r,e){let{width:t,height:n,x:i,y:o}=Hc(r),s=e?t*e/100:0,a=e?n*e/100:0;return`<mask id="viewboxMask"><rect width="${t}" height="${n}" rx="${s}" ry="${a}" x="${i}" y="${o}" fill="#fff" /></mask><g mask="url(#viewboxMask)">${r.body}</g>`}function IJ(r){const e={xmlns:"http://www.w3.org/2000/svg",...r.attributes};return Object.keys(e).map(t=>`${Gi(t)}="${Gi(e[t])}"`).join(" ")}function xJ(r){const e=dv(Math.random().toString()),t={};return r.body.replace(/(id="|url\(#)([a-z0-9-_]+)([")])/gi,(n,i,o,s)=>(t[o]=t[o]||e.string(8),`${i}${t[o]}${s}`))}const OJ={properties:{seed:{type:"string"},flip:{type:"boolean",default:!1},rotate:{type:"integer",minimum:0,maximum:360,default:0},scale:{type:"integer",minimum:0,maximum:200,default:100},radius:{type:"integer",minimum:0,maximum:50,default:0},size:{type:"integer",minimum:1},backgroundColor:{type:"array",items:{type:"string",pattern:"^(transparent|[a-fA-F0-9]{6})$"}},backgroundType:{type:"array",items:{type:"string",enum:["solid","gradientLinear"]},default:["solid"]},backgroundRotation:{type:"array",items:{type:"integer",minimum:-360,maximum:360},default:[0,360]},translateX:{type:"integer",minimum:-100,maximum:100,default:0},translateY:{type:"integer",minimum:-100,maximum:100,default:0},clip:{type:"boolean",default:!0},randomizeIds:{type:"boolean",default:!1}}};function aI(r){var e;let t={},n=(e=r.properties)!==null&&e!==void 0?e:{};return Object.keys(n).forEach(i=>{let o=n[i];typeof o=="object"&&o.default!==void 0&&(Array.isArray(o.default)?t[i]=[...o.default]:typeof o.default=="object"?t[i]={...o.default}:t[i]=o.default)}),t}function PJ(r,e){var t;let n={...aI(OJ),...aI((t=r.schema)!==null&&t!==void 0?t:{}),...e};return JSON.parse(JSON.stringify(n))}function lI(r){return r==="transparent"?r:`#${r}`}function MJ(r,e,t){var n;let i=r.shuffle(e);i.length<=1||e.length==2&&t=="gradientLinear"?(i=e,r.next()):i=r.shuffle(e),i.length===0&&(i=["transparent"]);const o=i[0],s=(n=i[1])!==null&&n!==void 0?n:i[0];return{primary:lI(o),secondary:lI(s)}}function AJ(r,e={}){var t,n,i,o,s;e=PJ(r,e);const a=dv(e.seed),l=r.create({prng:a,options:e}),c=a.pick((t=e.backgroundType)!==null&&t!==void 0?t:[],"solid"),{primary:u,secondary:d}=MJ(a,(n=e.backgroundColor)!==null&&n!==void 0?n:[],c),f=a.integer(!((i=e.backgroundRotation)===null||i===void 0)&&i.length?Math.min(...e.backgroundRotation):0,!((o=e.backgroundRotation)===null||o===void 0)&&o.length?Math.max(...e.backgroundRotation):0);e.size&&(l.attributes.width=e.size.toString(),l.attributes.height=e.size.toString()),e.scale!==void 0&&e.scale!==100&&(l.body=wJ(l,e.scale)),e.flip&&(l.body=CJ(l)),e.rotate&&(l.body=RJ(l,e.rotate)),(e.translateX||e.translateY)&&(l.body=TJ(l,e.translateX,e.translateY)),u!=="transparent"&&d!=="transparent"&&(l.body=EJ(l,u,d,c,f)),(e.radius||e.clip)&&(l.body=kJ(l,(s=e.radius)!==null&&s!==void 0?s:0)),e.randomizeIds&&(l.body=xJ(l));const p=IJ(l),h=gJ(r),m=`<svg ${p}>${h}${l.body}</svg>`;return{toString:()=>m,toJson:()=>{var w;return{svg:m,extra:{primaryBackgroundColor:u,secondaryBackgroundColor:d,backgroundType:c,backgroundRotation:f,...(w=l.extra)===null||w===void 0?void 0:w.call(l)}}},toDataUri:()=>`data:image/svg+xml;utf8,${encodeURIComponent(m)}`}}const DJ={g:(r,e)=>'<path d="M101.6 51.2a20 20 0 0 0-14.7-14.5q-3.9-1-8.5-1-10 0-17 4.7A30 30 0 0 0 50.9 54q-3.6 9-3.6 21.6 0 12.8 3.5 21.8 3.4 9 10.3 14a29 29 0 0 0 17.2 4.8q9 0 15-2.6 6-2.7 9-7.5t3-11.4l6.8.7H78.7v-28h64.5v20q0 20-8.4 34.1a56 56 0 0 1-23.2 21.6Q97 150.7 78 150.7q-21.3 0-37.3-9t-25-25.8q-9-16.5-9-39.7a87 87 0 0 1 5.4-32 67 67 0 0 1 38-38q12.9-5 27.6-5 12.9 0 24 3.7 11.1 3.6 19.7 10.4a50 50 0 0 1 20.2 36z" fill="white"/>',r:(r,e)=>'<path d="M17.6 148.7V3.2h62.8q16.2 0 28.3 6 12 5.8 18.9 16.9a50 50 0 0 1 6.7 26.6q0 15.6-7 26.3A43 43 0 0 1 108 95.2q-12.5 5.5-29 5.5H41.3V70H71q7 0 11.8-1.7a15 15 0 0 0 7.6-5.6 17 17 0 0 0 2.7-10q0-6.3-2.7-10.2a15 15 0 0 0-7.6-5.8q-4.9-2-11.8-2H57v114zm85.2-66.8 36.4 66.8h-43L60.9 81.9z" fill="white"/>',a:(r,e)=>'<path d="M42.6 148.7H0L48 3.2h54l48 145.5h-42.7L75.5 43.3h-1.1zm-8-57.4h80.1v29.5h-80z" fill="white"/>',d:(r,e)=>'<path d="M67 148.7H11V3.2h55.4q22.5 0 38.8 8.8a60 60 0 0 1 25.3 25q9 16.2 9 39 0 22.6-9 39a61 61 0 0 1-25 25 81 81 0 0 1-38.5 8.7m-16.5-33.5h15a44 44 0 0 0 18.5-3.5q7.6-3.5 11.6-12t4-23.8q0-15-4-23.7a24 24 0 0 0-12-12 47 47 0 0 0-19.2-3.5H50.5z" fill="white"/>',i:(r,e)=>'<path d="M94.8 3.2v145.5H55.3V3.2z" fill="white"/>',e:(r,e)=>'<path d="M22.2 148.7V3.2H127V35H61.7v25h59.9v32h-60v25h65.1v31.8z" fill="white"/>',n:(r,e)=>'<path d="M138 3.2v145.5h-33L52.5 72.3h-1v76.4H12.2V3.2h33.5l51.7 76.2h1.2V3.2z" fill="white"/>',t:(r,e)=>'<path d="M11.7 35V3.2h126.5V35H94.4v113.7h-39V35z" fill="white"/>'},NJ={g:(r,e)=>'<path d="M101.6 51.1a20 20 0 0 0-14.7-14.5q-3.9-1-8.5-1.1-10 0-17 4.8A30 30 0 0 0 50.9 54q-3.6 9-3.6 21.6 0 12.8 3.5 21.8 3.4 9 10.3 14a29 29 0 0 0 17.2 4.8q9 0 15-2.6 6-2.7 9-7.5t3-11.4l6.8.7H78.7v-28h64.5v20q0 20-8.4 34.1a56 56 0 0 1-23.2 21.6Q97 150.6 78 150.6q-21.3 0-37.3-9t-25-25.8-9-39.7a87 87 0 0 1 5.4-32 67 67 0 0 1 38-38Q63 1 77.6 1q12.9 0 24 3.7 11.1 3.6 19.7 10.4a50 50 0 0 1 20.2 36z" fill="white"/>',r:(r,e)=>'<path d="M17.6 148.6V3h62.8q16.2 0 28.3 6 12 5.8 18.9 16.9a50 50 0 0 1 6.7 26.5q0 15.7-7 26.4A43 43 0 0 1 108 95q-12.5 5.5-29 5.5H41.3V69.9H71q7 0 11.8-1.7a15 15 0 0 0 7.6-5.6 17 17 0 0 0 2.7-10q0-6.3-2.7-10.2a15 15 0 0 0-7.6-5.8q-4.9-2-11.8-2H57v114zm85.2-66.8 36.4 66.8h-43L60.9 81.8z" fill="white"/>',a:(r,e)=>'<path d="M42.6 148.6H0L48 3h54l48 145.5h-42.7L75.5 43.2h-1.1zm-8-57.4h80.1v29.5h-80z" fill="white"/>',d:(r,e)=>'<path d="M67 148.6H11V3h55.4q22.5 0 38.8 8.7a60 60 0 0 1 25.3 25q9 16.4 9 39 0 22.8-9 39.1a61 61 0 0 1-25 25 81 81 0 0 1-38.5 8.7M50.5 115h15a44 44 0 0 0 18.5-3.4q7.6-3.6 11.6-12t4-23.8q0-15-4-23.7a24 24 0 0 0-12-12 47 47 0 0 0-19.2-3.5H50.5z" fill="white"/>',i:(r,e)=>'<path d="M94.8 3.1v145.5H55.3V3z" fill="white"/>',e:(r,e)=>'<path d="M22.2 148.6V3H127v32H61.7v25h59.9v31.8h-60v25h65.1v31.9z" fill="white"/>',n:(r,e)=>'<path d="M138 3.1v145.5h-33L52.5 72h-1v76.5H12.2V3h33.5l51.7 76.1h1.2v-76z" fill="white"/>',t:(r,e)=>'<path d="M11.7 35V3h126.5v32H94.4v113.7h-39V34.9z" fill="white"/>'},LJ=Object.freeze(Object.defineProperty({__proto__:null,shape1:NJ,shape2:DJ},Symbol.toStringTag,{value:"Module"}));function cI({prng:r,group:e,width:t,height:n,values:i=[],rotation:o,offsetX:s,offsetY:a}){const l=LJ,c=r.pick(i),u=r.integer(Math.min(...o),Math.max(...o)),d=r.integer(Math.min(...s),Math.max(...s)),f=r.integer(Math.min(...a),Math.max(...a));if(c&&l[e][c])return{name:c,value(p,h){var m,w,g;let b=l[e][c](p,h);return(this.rotation||this.offsetX||this.offsetY)&&(b=`<g transform="translate(${(m=this.offsetX)!==null&&m!==void 0?m:0}, ${(w=this.offsetY)!==null&&w!==void 0?w:0}) rotate(${(g=this.rotation)!==null&&g!==void 0?g:0} ${t/2} ${n/2})">${b}</g>`),b},rotation:u,offsetX:d,offsetY:f}}function UJ({prng:r,options:e}){var t,n,i,o,s,a;const l=cI({prng:r,group:"shape2",values:e.shape2,width:150,height:150,rotation:!((t=e.shape2Rotation)===null||t===void 0)&&t.length?e.shape2Rotation:[0],offsetX:!((n=e.shape2OffsetX)===null||n===void 0)&&n.length?e.shape2OffsetX:[0],offsetY:!((i=e.shape2OffsetY)===null||i===void 0)&&i.length?e.shape2OffsetY:[0]}),c=cI({prng:r,group:"shape1",values:e.shape1,width:150,height:150,rotation:!((o=e.shape1Rotation)===null||o===void 0)&&o.length?e.shape1Rotation:[0],offsetX:!((s=e.shape1OffsetX)===null||s===void 0)&&s.length?e.shape1OffsetX:[0],offsetY:!((a=e.shape1OffsetY)===null||a===void 0)&&a.length?e.shape1OffsetY:[0]});return{shape2:l,shape1:c}}function jJ({prng:r,options:e}){return{}}const FJ={$schema:"http://json-schema.org/draft-07/schema#",properties:{backgroundColor:{type:"array",items:{type:"string",pattern:"^(transparent|[a-fA-F0-9]{6})$"},default:["eb4747","eb6247","eb7e47","eb9947","ebb447","ebd047","ebeb47","d0eb47","b4eb47","99eb47","7eeb47","62eb47","47eb47","47eb62","47eb7e","47eb99","47ebb4","47ebd0","47ebeb","47d0eb","47b4eb","4799eb","477eeb","4762eb","4747eb","6247eb","7e47eb","9947eb","b447eb","d047eb","eb47eb","eb47d0","eb4799","eb477e","eb4762"]},shape1:{type:"array",items:{type:"string",enum:["g","r","a","d","i","e","n","t"]},default:["g","r","a","d","i","e","n","t"]},shape1OffsetX:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape1OffsetY:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape1Rotation:{type:"array",items:{type:"integer",minimum:-180,maximum:180},maxItems:2,default:[-180,180]},shape2:{type:"array",items:{type:"string",enum:["g","r","a","d","i","e","n","t"]},default:["g","r","a","d","i","e","n","t"]},shape2OffsetX:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape2OffsetY:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape2Rotation:{type:"array",items:{type:"integer",minimum:-160,maximum:160},maxItems:2,default:[-160,160]}}},BJ={title:"Glass",creator:"DiceBear",source:"https://www.dicebear.com",homepage:"https://www.dicebear.com",license:{name:"CC0 1.0",url:"https://creativecommons.org/publicdomain/zero/1.0/"}},KJ=({prng:r,options:e})=>{var t,n,i,o;const s=UJ({prng:r,options:e}),a=jJ({prng:r,options:e});return{attributes:{viewBox:"0 0 100 100",fill:"none","shape-rendering":"auto"},body:`<g style="mix-blend-mode:screen" opacity="0.6" filter="url(#dicebearGlass-a)"><g transform="translate(-25 -25)">${(n=(t=s.shape2)===null||t===void 0?void 0:t.value(s,a))!==null&&n!==void 0?n:""}</g></g><g style="mix-blend-mode:screen" opacity="0.6" filter="url(#dicebearGlass-b)"><g transform="translate(-25 -25)">${(o=(i=s.shape1)===null||i===void 0?void 0:i.value(s,a))!==null&&o!==void 0?o:""}</g></g><defs><filter id="dicebearGlass-a" x="-57" y="-57" width="214" height="214" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="16" result="effect1_foregroundBlur_25_7"/></filter><filter id="dicebearGlass-b" x="-57" y="-57" width="214" height="214" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="16" result="effect1_foregroundBlur_25_7"/></filter></defs>`,extra:()=>({...Object.entries(s).reduce((l,[c,u])=>(l[c]=u==null?void 0:u.name,l),{}),...Object.entries(a).reduce((l,[c,u])=>(l[`${c}Color`]=u,l),{})})}},VJ=Object.freeze(Object.defineProperty({__proto__:null,create:KJ,meta:BJ,schema:FJ},Symbol.toStringTag,{value:"Module"}));function iL({className:r,size:e="default",...t}){return y.jsx(f3,{"data-slot":"avatar","data-size":e,className:Ue("group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",r),...t})}function $J({className:r,...e}){return y.jsx(h3,{"data-slot":"avatar-fallback",className:Ue("flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",r),...e})}function WJ({className:r,...e}){return y.jsx("span",{"data-slot":"avatar-badge",className:Ue("absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none","group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden","group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2","group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",r),...e})}function qJ(r){const e=r.indexOf(":");if(e>0){const t=r.slice(1,e);return`${r.slice(e+1)}+${t}`}return r}const uI={online:"bg-green-400",unavailable:"bg-yellow-400",offline:"bg-zinc-500"};function qw({userId:r,size:e="default",presence:t,className:n}){const i=AJ(VJ,{seed:qJ(r)}).toDataUri();return y.jsxs(iL,{size:e,className:Ue(n),children:[y.jsx("img",{src:i,alt:r,className:"aspect-square size-full rounded-full object-cover"}),t!==void 0&&y.jsx(WJ,{"data-presence":t,className:Ue(uI[t]??uI.offline)})]})}function Gw({...r}){return y.jsx(X4,{"data-slot":"dropdown-menu",...r})}function Hw({...r}){return y.jsx(Q4,{"data-slot":"dropdown-menu-trigger",...r})}function zw({className:r,align:e="start",sideOffset:t=4,...n}){return y.jsx(Z4,{children:y.jsx(e$,{"data-slot":"dropdown-menu-content",sideOffset:t,align:e,className:Ue("z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",r),...n})})}function ld({className:r,inset:e,variant:t="default",...n}){return y.jsx(t$,{"data-slot":"dropdown-menu-item","data-inset":e,"data-variant":t,className:Ue("group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",r),...n})}function GJ({className:r,...e}){return y.jsx(r$,{"data-slot":"dropdown-menu-separator",className:Ue("-mx-1 my-1 h-px bg-border",r),...e})}function HJ(r,e){const[t,n]=E.useState({ready:!1,spaceId:null});return E.useEffect(()=>{let i=!1;return(async()=>{const o=me.safeGet();if(!o)return;const s=`#${r}:${e}`;try{const a=await o.getRoomIdForAlias(s);if(i)return;if(!a){n({ready:!0,spaceId:null});return}const l=a.room_id;o.getRoom(l)||await o.joinRoom(s),i||n({ready:!0,spaceId:l})}catch{i||n({ready:!0,spaceId:null})}})(),()=>{i=!0}},[r,e]),t}function oL(){const r=E.useSyncExternalStore(e=>me.subscribe(e),()=>me.safeGet(),()=>null);if(!r)throw new Error("useMatrixClient called when not logged in");return r}function zJ(r){var t;if(!r)return null;const e=(t=me.safeGet())==null?void 0:t.getRoom(r);return(e==null?void 0:e.name)??null}function YJ(r){return E.useSyncExternalStore(e=>{const t=me.safeGet();if(!t||!r)return me.subscribe(e);let n=null;const i=()=>{if(n)return;const a=t.getRoom(r);if(!a)return;const l=()=>e();a.on(fe.Name,l),n=()=>a.off(fe.Name,l)};i();const o=()=>{i(),e()};t.on(Te.Room,o);const s=me.subscribe(e);return()=>{t.off(Te.Room,o),n&&n(),s()}},()=>zJ(r),()=>null)}function Cc(r){const e=/^@([^:]+):/.exec(r);return e?e[1]:r}function sL(r){return r.name||Cc(r.userId)}function zc(r){let e=0;for(let n=0;n<r.length;n++)e=e*31+r.charCodeAt(n)|0;return`hsl(${(e%360+360)%360} 70% 72%)`}const aL=/(@[A-Za-z0-9._\-=/+]+:[A-Za-z0-9.\-]+)/g,JJ=/^@[A-Za-z0-9._\-=/+]+:[A-Za-z0-9.\-]+$/;function XJ(r,e){const t=new Map;for(const s of e){const a=Cc(s.userId);a!==s.userId&&!t.has(a)&&t.set(a,s.userId)}const n=new Set;for(const s of r.match(aL)??[])n.add(s);const i=/(^|\s)@([A-Za-z0-9._\-=/+]+)(?!:[A-Za-z0-9.\-])/g;return{body:r.replace(i,(s,a,l)=>{const c=t.get(l);return c?(n.add(c),`${a}${c}`):s}),userIds:Array.from(n)}}function lL(r){return r.split(aL).map(t=>JJ.test(t)?{text:t,userId:t}:{text:t,userId:null})}function QJ(r,e){const t=me.safeGet();if(!t)return Cc(r);if(e){const i=t.getRoom(e),o=i==null?void 0:i.getMember(r);if(o)return sL(o)}const n=t.getUser(r);return n!=null&&n.displayName?n.displayName:Cc(r)}function Vo(r,e){return E.useSyncExternalStore(t=>{const n=me.subscribe(t),i=me.safeGet();if(!i)return n;const o=e?i.getRoom(e)??null:null,s=()=>t();o==null||o.currentState.on(Ne.Members,s);const a=i.getUser(r),l=()=>t();return a==null||a.on(ar.DisplayName,l),()=>{o==null||o.currentState.off(Ne.Members,s),a==null||a.off(ar.DisplayName,l),n()}},()=>QJ(r,e),()=>Cc(r))}const jl=[];let li=jl;function ZJ(){const r=me.safeGet();if(!r)return li!==jl&&(li=jl),li;const e=r.getAccountData("m.direct");if(!e)return li!==jl&&(li=jl),li;const t=e.getContent(),n=new Set;for(const o of Object.values(t))for(const s of o??[])n.add(s);const i=Array.from(n).map(o=>r.getRoom(o)).filter(o=>!!o);return li.length===i.length&&li.every((o,s)=>o===i[s])||(li=i),li}function eX(){return E.useSyncExternalStore(r=>{const e=me.safeGet();if(!e)return me.subscribe(r);const t=()=>r();e.on(Te.AccountData,t);const n=me.subscribe(r);return()=>{e.off(Te.AccountData,t),n()}},ZJ,()=>jl)}const fv=[];let Xo=fv;function tX(){const r=me.safeGet();if(!r)return Xo!==fv&&(Xo=fv),Xo;const e=r.getRooms().filter(t=>{var n;return!!((n=t.tags)!=null&&n["m.favourite"])});return Xo.length===e.length&&Xo.every((t,n)=>t===e[n])||(Xo=e),Xo}function rX(){return E.useSyncExternalStore(r=>{const e=me.safeGet();if(!e)return me.subscribe(r);const t=()=>r();for(const i of e.getRooms())i.on(fe.Tags,t);const n=me.subscribe(r);return()=>{for(const i of e.getRooms())i.off(fe.Tags,t);n()}},tX,()=>fv)}const cL={level:0,canSendEvent:()=>!1,canSendStateEvent:()=>!1},dI=new Map;function nX(r){var d;const e=me.safeGet(),t=e==null?void 0:e.getRoom(r),n=e==null?void 0:e.getUserId();if(!t||!n)return cL;const i=t.currentState.getStateEvents(V.RoomPowerLevels,"")??null,o=dI.get(r);if(o&&o.plEvent===i)return o.result;const s=(i==null?void 0:i.getContent())??{},a=((d=s.users)==null?void 0:d[n])??s.users_default??0,l=s.events_default??0,c=s.state_default??50,u={level:a,canSendEvent:f=>{var p;return a>=(((p=s.events)==null?void 0:p[f])??l)},canSendStateEvent:f=>{var p;return a>=(((p=s.events)==null?void 0:p[f])??c)}};return dI.set(r,{plEvent:i,result:u}),u}function Yw(r){return E.useSyncExternalStore(e=>{const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return me.subscribe(e);const i=()=>e();n.currentState.on(Ne.Events,i);const o=me.subscribe(e);return()=>{n.currentState.off(Ne.Events,i),o()}},()=>nX(r),()=>cL)}const hy={total:0,highlight:0};function iX(r){let e=0,t=0;for(const n of r)e+=n.getUnreadNotificationCount(it.Total),t+=n.getUnreadNotificationCount(it.Highlight);return{total:e,highlight:t}}function py(r){const e=E.useRef(hy);return E.useSyncExternalStore(t=>{const n=()=>t();for(const o of r)o.on(fe.UnreadNotifications,n);const i=me.subscribe(t);return()=>{for(const o of r)o.off(fe.UnreadNotifications,n);i()}},()=>{const t=iX(r),n=e.current;if(n.total===t.total&&n.highlight===t.highlight)return n;const i=t.total===0&&t.highlight===0?hy:t;return e.current=i,i},()=>hy)}const Uu=[],vy=new Map;function oX(r){const e=me.safeGet(),t=e==null?void 0:e.getRoom(r),n=vy.get(r)??Uu;if(!e||!t)return n!==Uu&&vy.set(r,Uu),Uu;const o=t.currentState.getStateEvents("m.space.child").map(s=>s.getStateKey()).filter(s=>!!s).map(s=>e.getRoom(s)).filter(s=>!!s);return n.length===o.length&&n.every((s,a)=>s===o[a])?n:(vy.set(r,o),o)}function sX(r){return E.useSyncExternalStore(e=>{const t=me.safeGet();if(!t)return me.subscribe(e);let n=null;const i=()=>{if(n)return;const a=t.getRoom(r);if(!a)return;const l=()=>e();a.currentState.on(Ne.Events,l),n=()=>a.currentState.off(Ne.Events,l)};i();const o=()=>{i(),e()};t.on(Te.Room,o);const s=me.subscribe(e);return()=>{t.off(Te.Room,o),n&&n(),s()}},()=>oX(r),()=>Uu)}function aX({className:r,children:e,...t}){return y.jsxs(P$,{"data-slot":"scroll-area",className:Ue("relative",r),...t,children:[y.jsx(M$,{"data-slot":"scroll-area-viewport",className:"size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1",children:e}),y.jsx(lX,{}),y.jsx(A$,{})]})}function lX({className:r,orientation:e="vertical",...t}){return y.jsx(zA,{"data-slot":"scroll-area-scrollbar","data-orientation":e,orientation:e,className:Ue("flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",r),...t,children:y.jsx(QA,{"data-slot":"scroll-area-thumb",className:"relative flex-1 rounded-full bg-border"})})}var fI=1,cX=.9,uX=.8,dX=.17,my=.1,gy=.999,fX=.9999,hX=.99,pX=/[\\\/_+.#"@\[\(\{&]/,vX=/[\\\/_+.#"@\[\(\{&]/g,mX=/[\s-]/,uL=/[\s-]/g;function g_(r,e,t,n,i,o,s){if(o===e.length)return i===r.length?fI:hX;var a=`${i},${o}`;if(s[a]!==void 0)return s[a];for(var l=n.charAt(o),c=t.indexOf(l,i),u=0,d,f,p,h;c>=0;)d=g_(r,e,t,n,c+1,o+1,s),d>u&&(c===i?d*=fI:pX.test(r.charAt(c-1))?(d*=uX,p=r.slice(i,c-1).match(vX),p&&i>0&&(d*=Math.pow(gy,p.length))):mX.test(r.charAt(c-1))?(d*=cX,h=r.slice(i,c-1).match(uL),h&&i>0&&(d*=Math.pow(gy,h.length))):(d*=dX,i>0&&(d*=Math.pow(gy,c-i))),r.charAt(c)!==e.charAt(o)&&(d*=fX)),(d<my&&t.charAt(c-1)===n.charAt(o+1)||n.charAt(o+1)===n.charAt(o)&&t.charAt(c-1)!==n.charAt(o))&&(f=g_(r,e,t,n,c+1,o+2,s),f*my>d&&(d=f*my)),d>u&&(u=d),c=t.indexOf(l,c+1);return s[a]=u,u}function hI(r){return r.toLowerCase().replace(uL," ")}function gX(r,e,t){return r=t&&t.length>0?`${r+" "+t.join(" ")}`:r,g_(r,e,hI(r),hI(e),0,0,{})}var Tu='[cmdk-group=""]',yy='[cmdk-group-items=""]',yX='[cmdk-group-heading=""]',dL='[cmdk-item=""]',pI=`${dL}:not([aria-disabled="true"])`,y_="cmdk-item-select",_l="data-value",SX=(r,e,t)=>gX(r,e,t),fL=E.createContext(void 0),kf=()=>E.useContext(fL),hL=E.createContext(void 0),Jw=()=>E.useContext(hL),pL=E.createContext(void 0),vL=E.forwardRef((r,e)=>{let t=El(()=>{var Y,le;return{search:"",value:(le=(Y=r.value)!=null?Y:r.defaultValue)!=null?le:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=El(()=>new Set),i=El(()=>new Map),o=El(()=>new Map),s=El(()=>new Set),a=mL(r),{label:l,children:c,value:u,onValueChange:d,filter:f,shouldFilter:p,loop:h,disablePointerSelection:m=!1,vimBindings:w=!0,...g}=r,b=jn(),R=jn(),k=jn(),O=E.useRef(null),T=OX();Ba(()=>{if(u!==void 0){let Y=u.trim();t.current.value=Y,x.emit()}},[u]),Ba(()=>{T(6,$)},[]);let x=E.useMemo(()=>({subscribe:Y=>(s.current.add(Y),()=>s.current.delete(Y)),snapshot:()=>t.current,setState:(Y,le,B)=>{var W,A,D,P;if(!Object.is(t.current[Y],le)){if(t.current[Y]=le,Y==="search")ie(),F(),T(1,H);else if(Y==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let M=document.getElementById(k);M?M.focus():(W=document.getElementById(b))==null||W.focus()}if(T(7,()=>{var M;t.current.selectedItemId=(M=X())==null?void 0:M.id,x.emit()}),B||T(5,$),((A=a.current)==null?void 0:A.value)!==void 0){let M=le??"";(P=(D=a.current).onValueChange)==null||P.call(D,M);return}}x.emit()}},emit:()=>{s.current.forEach(Y=>Y())}}),[]),C=E.useMemo(()=>({value:(Y,le,B)=>{var W;le!==((W=o.current.get(Y))==null?void 0:W.value)&&(o.current.set(Y,{value:le,keywords:B}),t.current.filtered.items.set(Y,N(le,B)),T(2,()=>{F(),x.emit()}))},item:(Y,le)=>(n.current.add(Y),le&&(i.current.has(le)?i.current.get(le).add(Y):i.current.set(le,new Set([Y]))),T(3,()=>{ie(),F(),t.current.value||H(),x.emit()}),()=>{o.current.delete(Y),n.current.delete(Y),t.current.filtered.items.delete(Y);let B=X();T(4,()=>{ie(),(B==null?void 0:B.getAttribute("id"))===Y&&H(),x.emit()})}),group:Y=>(i.current.has(Y)||i.current.set(Y,new Set),()=>{o.current.delete(Y),i.current.delete(Y)}),filter:()=>a.current.shouldFilter,label:l||r["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:b,inputId:k,labelId:R,listInnerRef:O}),[]);function N(Y,le){var B,W;let A=(W=(B=a.current)==null?void 0:B.filter)!=null?W:SX;return Y?A(Y,t.current.search,le):0}function F(){if(!t.current.search||a.current.shouldFilter===!1)return;let Y=t.current.filtered.items,le=[];t.current.filtered.groups.forEach(W=>{let A=i.current.get(W),D=0;A.forEach(P=>{let M=Y.get(P);D=Math.max(M,D)}),le.push([W,D])});let B=O.current;oe().sort((W,A)=>{var D,P;let M=W.getAttribute("id"),I=A.getAttribute("id");return((D=Y.get(I))!=null?D:0)-((P=Y.get(M))!=null?P:0)}).forEach(W=>{let A=W.closest(yy);A?A.appendChild(W.parentElement===A?W:W.closest(`${yy} > *`)):B.appendChild(W.parentElement===B?W:W.closest(`${yy} > *`))}),le.sort((W,A)=>A[1]-W[1]).forEach(W=>{var A;let D=(A=O.current)==null?void 0:A.querySelector(`${Tu}[${_l}="${encodeURIComponent(W[0])}"]`);D==null||D.parentElement.appendChild(D)})}function H(){let Y=oe().find(B=>B.getAttribute("aria-disabled")!=="true"),le=Y==null?void 0:Y.getAttribute(_l);x.setState("value",le||void 0)}function ie(){var Y,le,B,W;if(!t.current.search||a.current.shouldFilter===!1){t.current.filtered.count=n.current.size;return}t.current.filtered.groups=new Set;let A=0;for(let D of n.current){let P=(le=(Y=o.current.get(D))==null?void 0:Y.value)!=null?le:"",M=(W=(B=o.current.get(D))==null?void 0:B.keywords)!=null?W:[],I=N(P,M);t.current.filtered.items.set(D,I),I>0&&A++}for(let[D,P]of i.current)for(let M of P)if(t.current.filtered.items.get(M)>0){t.current.filtered.groups.add(D);break}t.current.filtered.count=A}function $(){var Y,le,B;let W=X();W&&(((Y=W.parentElement)==null?void 0:Y.firstChild)===W&&((B=(le=W.closest(Tu))==null?void 0:le.querySelector(yX))==null||B.scrollIntoView({block:"nearest"})),W.scrollIntoView({block:"nearest"}))}function X(){var Y;return(Y=O.current)==null?void 0:Y.querySelector(`${dL}[aria-selected="true"]`)}function oe(){var Y;return Array.from(((Y=O.current)==null?void 0:Y.querySelectorAll(pI))||[])}function re(Y){let le=oe()[Y];le&&x.setState("value",le.getAttribute(_l))}function ae(Y){var le;let B=X(),W=oe(),A=W.findIndex(P=>P===B),D=W[A+Y];(le=a.current)!=null&&le.loop&&(D=A+Y<0?W[W.length-1]:A+Y===W.length?W[0]:W[A+Y]),D&&x.setState("value",D.getAttribute(_l))}function q(Y){let le=X(),B=le==null?void 0:le.closest(Tu),W;for(;B&&!W;)B=Y>0?IX(B,Tu):xX(B,Tu),W=B==null?void 0:B.querySelector(pI);W?x.setState("value",W.getAttribute(_l)):ae(Y)}let z=()=>re(oe().length-1),Q=Y=>{Y.preventDefault(),Y.metaKey?z():Y.altKey?q(1):ae(1)},Ie=Y=>{Y.preventDefault(),Y.metaKey?re(0):Y.altKey?q(-1):ae(-1)};return E.createElement(Je.div,{ref:e,tabIndex:-1,...g,"cmdk-root":"",onKeyDown:Y=>{var le;(le=g.onKeyDown)==null||le.call(g,Y);let B=Y.nativeEvent.isComposing||Y.keyCode===229;if(!(Y.defaultPrevented||B))switch(Y.key){case"n":case"j":{w&&Y.ctrlKey&&Q(Y);break}case"ArrowDown":{Q(Y);break}case"p":case"k":{w&&Y.ctrlKey&&Ie(Y);break}case"ArrowUp":{Ie(Y);break}case"Home":{Y.preventDefault(),re(0);break}case"End":{Y.preventDefault(),z();break}case"Enter":{Y.preventDefault();let W=X();if(W){let A=new Event(y_);W.dispatchEvent(A)}}}}},E.createElement("label",{"cmdk-label":"",htmlFor:C.inputId,id:C.labelId,style:MX},l),Pm(r,Y=>E.createElement(hL.Provider,{value:x},E.createElement(fL.Provider,{value:C},Y))))}),bX=E.forwardRef((r,e)=>{var t,n;let i=jn(),o=E.useRef(null),s=E.useContext(pL),a=kf(),l=mL(r),c=(n=(t=l.current)==null?void 0:t.forceMount)!=null?n:s==null?void 0:s.forceMount;Ba(()=>{if(!c)return a.item(i,s==null?void 0:s.id)},[c]);let u=gL(i,o,[r.value,r.children,o],r.keywords),d=Jw(),f=Us(T=>T.value&&T.value===u.current),p=Us(T=>c||a.filter()===!1?!0:T.search?T.filtered.items.get(i)>0:!0);E.useEffect(()=>{let T=o.current;if(!(!T||r.disabled))return T.addEventListener(y_,h),()=>T.removeEventListener(y_,h)},[p,r.onSelect,r.disabled]);function h(){var T,x;m(),(x=(T=l.current).onSelect)==null||x.call(T,u.current)}function m(){d.setState("value",u.current,!0)}if(!p)return null;let{disabled:w,value:g,onSelect:b,forceMount:R,keywords:k,...O}=r;return E.createElement(Je.div,{ref:Ao(o,e),...O,id:i,"cmdk-item":"",role:"option","aria-disabled":!!w,"aria-selected":!!f,"data-disabled":!!w,"data-selected":!!f,onPointerMove:w||a.getDisablePointerSelection()?void 0:m,onClick:w?void 0:h},r.children)}),_X=E.forwardRef((r,e)=>{let{heading:t,children:n,forceMount:i,...o}=r,s=jn(),a=E.useRef(null),l=E.useRef(null),c=jn(),u=kf(),d=Us(p=>i||u.filter()===!1?!0:p.search?p.filtered.groups.has(s):!0);Ba(()=>u.group(s),[]),gL(s,a,[r.value,r.heading,l]);let f=E.useMemo(()=>({id:s,forceMount:i}),[i]);return E.createElement(Je.div,{ref:Ao(a,e),...o,"cmdk-group":"",role:"presentation",hidden:d?void 0:!0},t&&E.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:c},t),Pm(r,p=>E.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":t?c:void 0},E.createElement(pL.Provider,{value:f},p))))}),EX=E.forwardRef((r,e)=>{let{alwaysRender:t,...n}=r,i=E.useRef(null),o=Us(s=>!s.search);return!t&&!o?null:E.createElement(Je.div,{ref:Ao(i,e),...n,"cmdk-separator":"",role:"separator"})}),wX=E.forwardRef((r,e)=>{let{onValueChange:t,...n}=r,i=r.value!=null,o=Jw(),s=Us(c=>c.search),a=Us(c=>c.selectedItemId),l=kf();return E.useEffect(()=>{r.value!=null&&o.setState("search",r.value)},[r.value]),E.createElement(Je.input,{ref:e,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:i?r.value:s,onChange:c=>{i||o.setState("search",c.target.value),t==null||t(c.target.value)}})}),TX=E.forwardRef((r,e)=>{let{children:t,label:n="Suggestions",...i}=r,o=E.useRef(null),s=E.useRef(null),a=Us(c=>c.selectedItemId),l=kf();return E.useEffect(()=>{if(s.current&&o.current){let c=s.current,u=o.current,d,f=new ResizeObserver(()=>{d=requestAnimationFrame(()=>{let p=c.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return f.observe(c),()=>{cancelAnimationFrame(d),f.unobserve(c)}}},[]),E.createElement(Je.div,{ref:Ao(o,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":n,id:l.listId},Pm(r,c=>E.createElement("div",{ref:Ao(s,l.listInnerRef),"cmdk-list-sizer":""},c)))}),RX=E.forwardRef((r,e)=>{let{open:t,onOpenChange:n,overlayClassName:i,contentClassName:o,container:s,...a}=r;return E.createElement(ME,{open:t,onOpenChange:n},E.createElement(AE,{container:s},E.createElement(DE,{"cmdk-overlay":"",className:i}),E.createElement(NE,{"aria-label":r.label,"cmdk-dialog":"",className:o},E.createElement(vL,{ref:e,...a}))))}),CX=E.forwardRef((r,e)=>Us(t=>t.filtered.count===0)?E.createElement(Je.div,{ref:e,...r,"cmdk-empty":"",role:"presentation"}):null),kX=E.forwardRef((r,e)=>{let{progress:t,children:n,label:i="Loading...",...o}=r;return E.createElement(Je.div,{ref:e,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Pm(r,s=>E.createElement("div",{"aria-hidden":!0},s)))}),Yc=Object.assign(vL,{List:TX,Item:bX,Input:wX,Group:_X,Separator:EX,Dialog:RX,Empty:CX,Loading:kX});function IX(r,e){let t=r.nextElementSibling;for(;t;){if(t.matches(e))return t;t=t.nextElementSibling}}function xX(r,e){let t=r.previousElementSibling;for(;t;){if(t.matches(e))return t;t=t.previousElementSibling}}function mL(r){let e=E.useRef(r);return Ba(()=>{e.current=r}),e}var Ba=typeof window>"u"?E.useEffect:E.useLayoutEffect;function El(r){let e=E.useRef();return e.current===void 0&&(e.current=r()),e}function Us(r){let e=Jw(),t=()=>r(e.snapshot());return E.useSyncExternalStore(e.subscribe,t,t)}function gL(r,e,t,n=[]){let i=E.useRef(),o=kf();return Ba(()=>{var s;let a=(()=>{var c;for(let u of t){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(c=u.current.textContent)==null?void 0:c.trim():i.current}})(),l=n.map(c=>c.trim());o.value(r,a,l),(s=e.current)==null||s.setAttribute(_l,a),i.current=a}),i}var OX=()=>{let[r,e]=E.useState(),t=El(()=>new Map);return Ba(()=>{t.current.forEach(n=>n()),t.current=new Map},[r]),(n,i)=>{t.current.set(n,i),e({})}};function PX(r){let e=r.type;return typeof e=="function"?e(r.props):"render"in e?e.render(r.props):r}function Pm({asChild:r,children:e},t){return r&&E.isValidElement(e)?E.cloneElement(PX(e),{ref:e.ref},t(e.props.children)):t(e)}var MX={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function Mm({...r}){return y.jsx(ME,{"data-slot":"dialog",...r})}function AX({...r}){return y.jsx(AE,{"data-slot":"dialog-portal",...r})}function DX({className:r,...e}){return y.jsx(DE,{"data-slot":"dialog-overlay",className:Ue("fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",r),...e})}function Am({className:r,children:e,showCloseButton:t=!0,...n}){return y.jsxs(AX,{children:[y.jsx(DX,{}),y.jsxs(NE,{"data-slot":"dialog-content",className:Ue("fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",r),...n,children:[e,t&&y.jsx(LE,{"data-slot":"dialog-close",asChild:!0,children:y.jsxs(Gt,{variant:"ghost",className:"absolute top-2 right-2",size:"icon-sm",children:[y.jsx(RE,{}),y.jsx("span",{className:"sr-only",children:"Close"})]})})]})]})}function Dm({className:r,...e}){return y.jsx("div",{"data-slot":"dialog-header",className:Ue("flex flex-col gap-2",r),...e})}function Nm({className:r,showCloseButton:e=!1,children:t,...n}){return y.jsxs("div",{"data-slot":"dialog-footer",className:Ue("-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",r),...n,children:[t,e&&y.jsx(LE,{asChild:!0,children:y.jsx(Gt,{variant:"outline",children:"Close"})})]})}function Lm({className:r,...e}){return y.jsx(yM,{"data-slot":"dialog-title",className:Ue("font-heading text-base leading-none font-medium",r),...e})}function Xw({className:r,...e}){return y.jsx(SM,{"data-slot":"dialog-description",className:Ue("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",r),...e})}function NX({className:r,...e}){return y.jsx("div",{"data-slot":"input-group",role:"group",className:Ue("group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",r),...e})}const LX=Vw("flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",{variants:{align:{"inline-start":"order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]","inline-end":"order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]","block-start":"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2","block-end":"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2"}},defaultVariants:{align:"inline-start"}});function UX({className:r,align:e="inline-start",...t}){return y.jsx("div",{role:"group","data-slot":"input-group-addon","data-align":e,className:Ue(LX({align:e}),r),onClick:n=>{var i,o;n.target.closest("button")||(o=(i=n.currentTarget.parentElement)==null?void 0:i.querySelector("input"))==null||o.focus()},...t})}function yL({className:r,...e}){return y.jsx(Yc,{"data-slot":"command",className:Ue("flex size-full flex-col overflow-hidden rounded-xl! bg-popover p-1 text-popover-foreground",r),...e})}function SL({className:r,...e}){return y.jsx("div",{"data-slot":"command-input-wrapper",className:"p-1 pb-0",children:y.jsxs(NX,{className:"h-8! rounded-lg! border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!",children:[y.jsx(Yc.Input,{"data-slot":"command-input",className:Ue("w-full text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",r),...e}),y.jsx(UX,{children:y.jsx(lK,{className:"size-4 shrink-0 opacity-50"})})]})})}function bL({className:r,...e}){return y.jsx(Yc.List,{"data-slot":"command-list",className:Ue("no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none",r),...e})}function _L({className:r,...e}){return y.jsx(Yc.Empty,{"data-slot":"command-empty",className:Ue("py-6 text-center text-sm",r),...e})}function EL({className:r,...e}){return y.jsx(Yc.Group,{"data-slot":"command-group",className:Ue("overflow-hidden p-1 text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground",r),...e})}function wL({className:r,children:e,...t}){return y.jsxs(Yc.Item,{"data-slot":"command-item",className:Ue("group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-lg! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",r),...t,children:[e,y.jsx(LP,{className:"ml-auto opacity-0 group-has-data-[slot=command-shortcut]/command-item:hidden group-data-[checked=true]/command-item:opacity-100"})]})}const ip=[],vI=new Map;function jX(r){var i;if(!r)return ip;const e=(i=me.safeGet())==null?void 0:i.getRoom(r);if(!e)return ip;const t=vI.get(r)??ip,n=e.getJoinedMembers();return t.length===n.length&&t.every((o,s)=>o===n[s])?t:(vI.set(r,n),n)}function FX(r){return E.useSyncExternalStore(e=>{const t=me.safeGet(),n=r?t==null?void 0:t.getRoom(r):null;if(!n)return me.subscribe(e);const i=()=>e();n.currentState.on(Ne.Members,i);const o=me.subscribe(e);return()=>{n.currentState.off(Ne.Members,i),o()}},()=>jX(r),()=>ip)}function BX(r){if(!r||typeof r!="object")return null;const e=r;if(e.version!==1||!Array.isArray(e.agents))return null;const t=[];for(const n of e.agents)n.user_id&&t.push({userId:n.user_id,name:n.name??n.user_id,role:n.role,avatarUrl:n.avatar_url,rooms:Array.isArray(n.rooms)?n.rooms:[]});return t}function KX(r){return new Set(r.map(e=>e.userId))}const TL={ready:!1,agents:[],isAgent:()=>!1},Sy=new WeakMap;function VX(r){var l;const e=(l=me.safeGet())==null?void 0:l.getRoom(r);if(!e)return TL;const t=Sy.get(e),n=e.currentState.getStateEvents("eco.zoon.workforce",""),i=(n==null?void 0:n.getContent())??null,o=BX(i);if(!o){if(t&&!t.ready)return t;const c={ready:!1,agents:[],isAgent:()=>!1};return Sy.set(e,c),c}if(t!=null&&t.ready&&t.agents.length===o.length&&t.agents.every((c,u)=>c.userId===o[u].userId))return t;const s=KX(o),a={ready:!0,agents:o,isAgent:c=>s.has(c)};return Sy.set(e,a),a}function RL(r){return E.useSyncExternalStore(e=>{const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return me.subscribe(e);const i=()=>e();n.currentState.on(Ne.Events,i);const o=me.subscribe(e);return()=>{n.currentState.off(Ne.Events,i),o()}},()=>VX(r),()=>TL)}function $X({open:r,spaceId:e,onOpenChange:t}){var m;const n=FX(e),{ready:i,isAgent:o}=RL(e),[s,a]=E.useState([]),[l,c]=E.useState(!1),u=Pc(),d=(m=me.safeGet())==null?void 0:m.getUserId(),f=E.useMemo(()=>n.filter(w=>w.userId!==d).filter(w=>!i||!o(w.userId)),[n,d,i,o]),p=w=>{a(g=>g.includes(w)?g.filter(b=>b!==w):[...g,w])},h=async()=>{var g;if(!s.length)return;const w=me.safeGet();if(w){c(!0);try{const b=await w.createRoom({is_direct:!0,preset:"trusted_private_chat",invite:s}),R=((g=w.getAccountData("m.direct"))==null?void 0:g.getContent())??{},k={...R},O=s[0];k[O]=[...R[O]??[],b.room_id],await w.setAccountData("m.direct",k),t(!1),a([]),u(`/room/${b.room_id}`)}finally{c(!1)}}};return y.jsx(Mm,{open:r,onOpenChange:t,children:y.jsxs(Am,{children:[y.jsxs(Dm,{children:[y.jsx(Lm,{children:"Start a DM"}),y.jsxs(Xw,{children:["DMs are private to the people you invite. Agents are managed via ",y.jsx("code",{children:"zooid.yaml"}),"."]})]}),!i&&y.jsx("p",{className:"rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:"Agent list unavailable — the picker may include agents until the workforce roster publishes."}),y.jsxs(yL,{children:[y.jsx(SL,{placeholder:"Search humans…"}),y.jsxs(bL,{children:[y.jsx(_L,{children:"No humans found."}),y.jsx(EL,{children:f.map(w=>y.jsxs(wL,{value:`${w.name??w.userId} ${w.userId}`,onSelect:()=>p(w.userId),"data-selected":s.includes(w.userId)||void 0,children:[y.jsx("span",{className:"flex-1 truncate",children:w.name??w.userId}),y.jsx("span",{className:"text-xs text-muted-foreground",children:w.userId})]},w.userId))})]})]}),y.jsxs(Nm,{children:[y.jsx(Gt,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),y.jsx(Gt,{disabled:!s.length||l,onClick:h,children:"Start DM"})]})]})})}function WX({open:r,spaceId:e,onOpenChange:t}){const[n,i]=E.useState(""),[o,s]=E.useState(""),[a,l]=E.useState("public"),[c,u]=E.useState(!1),d=Pc(),f=()=>{i(""),s(""),l("public"),u(!1)},p=async h=>{var g;h.preventDefault();const m=me.safeGet();if(!m)return;const w=n.trim();if(w){u(!0);try{const b=((g=m.getUserId())==null?void 0:g.split(":")[1])??"",k=(await m.createRoom({name:w,topic:o.trim()||void 0,preset:a==="public"?"public_chat":"private_chat",initial_state:[{type:"m.space.parent",state_key:e,content:{via:[b],canonical:!0}}]})).room_id;await m.sendStateEvent(e,"m.space.child",{via:[b]},k),t(!1),f(),d(`/room/${k}`)}finally{u(!1)}}};return y.jsx(Mm,{open:r,onOpenChange:h=>{t(h),h||f()},children:y.jsx(Am,{children:y.jsxs("form",{onSubmit:p,children:[y.jsxs(Dm,{children:[y.jsx(Lm,{children:"Create channel"}),y.jsx(Xw,{children:"Channels are public to the workforce by default."})]}),y.jsxs("div",{className:"flex flex-col gap-3 py-2",children:[y.jsxs("div",{className:"flex flex-col gap-1.5",children:[y.jsx(Qd,{htmlFor:"room-name",children:"Name"}),y.jsx(Xd,{id:"room-name",value:n,onChange:h=>i(h.target.value),autoFocus:!0,placeholder:"design"})]}),y.jsxs("div",{className:"flex flex-col gap-1.5",children:[y.jsx(Qd,{htmlFor:"room-topic",children:"Topic"}),y.jsx(Xd,{id:"room-topic",value:o,onChange:h=>s(h.target.value),placeholder:"What is this channel about?"})]}),y.jsxs("fieldset",{className:"flex flex-col gap-2",children:[y.jsx("legend",{className:"text-sm font-medium",children:"Privacy"}),y.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[y.jsx("input",{type:"radio",name:"privacy",value:"public",checked:a==="public",onChange:()=>l("public")}),"Public — anyone in the workforce"]}),y.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[y.jsx("input",{type:"radio",name:"privacy",value:"private",checked:a==="private",onChange:()=>l("private")}),"Private — invite only"]})]})]}),y.jsxs(Nm,{children:[y.jsx(Gt,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),y.jsx(Gt,{type:"submit",disabled:!n.trim()||c,children:"Create channel"})]})]})})})}function qX(r){var t,n;if(!r)return!1;const e=(t=me.safeGet())==null?void 0:t.getRoom(r);return!!((n=e==null?void 0:e.tags)!=null&&n["m.favourite"])}function CL(r){const e=E.useSyncExternalStore(n=>{const i=me.safeGet();if(!i||!r)return me.subscribe(n);let o=null;const s=()=>{if(o)return;const c=i.getRoom(r);if(!c)return;const u=()=>n();c.on(fe.Tags,u),o=()=>c.off(fe.Tags,u)};s();const a=()=>{s(),n()};i.on(Te.Room,a);const l=me.subscribe(n);return()=>{i.off(Te.Room,a),o&&o(),l()}},()=>qX(r),()=>!1),t=E.useCallback(async()=>{if(!r)return;const n=me.safeGet();n&&(e?await n.deleteRoomTag(r,"m.favourite"):await n.setRoomTag(r,"m.favourite",{order:.5}))},[r,e]);return{isFavorite:e,toggle:t}}const ju={total:0,highlight:0},by=new Map;function GX(r){var i;const e=(i=me.safeGet())==null?void 0:i.getRoom(r),t=by.get(r)??ju;if(!e)return t!==ju&&by.set(r,ju),ju;const n={total:e.getUnreadNotificationCount(it.Total),highlight:e.getUnreadNotificationCount(it.Highlight)};return t.total===n.total&&t.highlight===n.highlight?t:(by.set(r,n),n)}function HX(r){return E.useSyncExternalStore(e=>{const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return me.subscribe(e);const i=()=>e();n.on(fe.UnreadNotifications,i);const o=me.subscribe(e);return()=>{n.off(fe.UnreadNotifications,i),o()}},()=>GX(r),()=>ju)}function op({total:r,highlight:e}){if(r<=0)return null;const t=r>99?"99+":String(r),n=e>0?"bg-destructive text-destructive-foreground":"bg-muted text-muted-foreground";return y.jsx("span",{"aria-label":`${r} unread`,className:`inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] font-medium tabular-nums ${n}`,children:t})}function _y({room:r}){const{isFavorite:e,toggle:t}=CL(r.roomId),{total:n,highlight:i}=HX(r.roomId),o=n>0;return y.jsxs("div",{className:"group/row flex items-center gap-1 px-2 py-1.5 text-sm hover:bg-sidebar-accent",children:[y.jsxs(XF,{to:`/room/${r.roomId}`,className:"flex flex-1 items-center gap-2 truncate",children:[y.jsx(iL,{className:"size-6",children:y.jsx($J,{children:(r.name??r.roomId).slice(0,2).toUpperCase()})}),y.jsx("span",{className:`truncate ${o?"font-semibold":""}`,children:r.name||r.roomId})]}),y.jsxs("div",{className:"relative h-5 min-w-5",children:[y.jsx("div",{className:"group-hover/row:invisible group-focus-within/row:invisible",children:y.jsx(op,{total:n,highlight:i})}),y.jsxs(Gw,{children:[y.jsx(Hw,{asChild:!0,children:y.jsx("button",{type:"button","aria-label":"room actions",className:"absolute right-0 top-0 inline-flex h-5 w-5 items-center justify-center rounded-full text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground focus:opacity-100 group-hover/row:opacity-100 group-focus-within/row:opacity-100",children:y.jsx(WB,{className:"size-3"})})}),y.jsx(zw,{children:y.jsx(ld,{onClick:t,children:e?"Remove from favorites":"Add to favorites"})})]})]})]})}function Ey({title:r,action:e,children:t,defaultExpanded:n=!0}){const[i,o]=E.useState(n);return y.jsxs("section",{role:"region","aria-label":r,className:"flex flex-col",children:[y.jsxs("header",{className:"flex items-center gap-1 px-2 py-1 text-xs uppercase text-muted-foreground",children:[y.jsxs("button",{type:"button","aria-label":`toggle ${r} section`,onClick:()=>o(s=>!s),className:"flex items-center gap-1",children:[i?y.jsx(UP,{className:"size-3"}):y.jsx(jP,{className:"size-3"}),y.jsx("h3",{className:"font-semibold",children:r})]}),y.jsx("div",{className:"ml-auto",children:e})]}),i&&y.jsx("div",{children:t})]})}const mI="inline-flex h-5 w-5 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground";function zX({spaceId:r}){const e=rX(),t=eX(),n=sX(r),o=Yw(r).canSendStateEvent("m.space.child"),[s,a]=E.useState(!1),[l,c]=E.useState(!1),u=new Set,d=b=>{const R=[];for(const k of b)u.has(k.roomId)||(u.add(k.roomId),R.push(k));return R},f=d(e),p=d(t),h=d(n),m=py(f),w=py(p),g=py(h);return y.jsxs(aX,{className:"h-full",children:[y.jsxs("div",{className:"flex flex-col gap-2 p-2",children:[y.jsx(Ey,{title:"Favorites",action:y.jsx(op,{total:m.total,highlight:m.highlight}),children:f.map(b=>y.jsx(_y,{room:b},b.roomId))}),y.jsx(Ey,{title:"Rooms",action:y.jsxs("div",{className:"flex items-center gap-1",children:[y.jsx(op,{total:g.total,highlight:g.highlight}),o?y.jsx("button",{type:"button","aria-label":"add channel",onClick:()=>a(!0),className:mI,children:y.jsx(GT,{className:"size-3"})}):null]}),children:h.map(b=>y.jsx(_y,{room:b},b.roomId))}),y.jsx(Ey,{title:"DMs",defaultExpanded:!1,action:y.jsxs("div",{className:"flex items-center gap-1",children:[y.jsx(op,{total:w.total,highlight:w.highlight}),y.jsx("button",{type:"button","aria-label":"start dm",onClick:()=>c(!0),className:mI,children:y.jsx(GT,{className:"size-3"})})]}),children:p.map(b=>y.jsx(_y,{room:b},b.roomId))})]}),y.jsx(WX,{open:s,spaceId:r,onOpenChange:a}),y.jsx($X,{open:l,spaceId:r,onOpenChange:c})]})}function YX({spaceId:r}){return r?y.jsx(zX,{spaceId:r}):y.jsx("nav",{"aria-label":"Rooms",className:"h-full p-4 text-xs text-muted-foreground",children:"Workforce unavailable."})}function kL({...r}){return y.jsx(m$,{"data-slot":"popover",...r})}function IL({...r}){return y.jsx(g$,{"data-slot":"popover-trigger",...r})}function xL({className:r,align:e="center",sideOffset:t=4,...n}){return y.jsx(y$,{children:y.jsx(S$,{"data-slot":"popover-content",align:e,sideOffset:t,className:Ue("z-50 w-72 rounded-md border border-border bg-popover p-3 text-popover-foreground shadow-md outline-none","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",r),...n})})}const OL=[],gI=new WeakMap;function JX(r){var i;const e=(i=me.safeGet())==null?void 0:i.getRoom(r);if(!e)return OL;const t=e.getJoinedMembers(),n=gI.get(e);return n&&n.length===t.length&&n.every((o,s)=>o===t[s])?n:(gI.set(e,t),t)}function PL(r){return E.useSyncExternalStore(e=>{const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return me.subscribe(e);const i=()=>e();n.currentState.on(Ne.Members,i);const o=me.subscribe(e);return()=>{n.currentState.off(Ne.Members,i),o()}},()=>JX(r),()=>OL)}const XX={presence:"offline",statusMsg:null};function yI(r){var t;const e=(t=me.safeGet())==null?void 0:t.getUser(r);return e?{presence:e.presence??"offline",statusMsg:e.presenceStatusMsg??null}:XX}function ML(r){const[e,t]=E.useState(()=>yI(r));return E.useEffect(()=>{const n=me.safeGet();if(!n)return;const i=()=>t(yI(r)),o=n.getUser(r);o&&o.on(ar.Presence,i);const s=(a,l)=>{l.userId===r&&i()};return n.on(ar.Presence,s),()=>{o==null||o.off(ar.Presence,i),n.off(ar.Presence,s)}},[r]),e}function QX(r,e){const[t,n]=E.useState(r);return E.useEffect(()=>{const i=setTimeout(()=>n(r),e);return()=>clearTimeout(i)},[r,e]),t}const SI={results:[],loading:!1};function ZX(r){const e=QX(r.trim(),300),[t,n]=E.useState(SI);return E.useEffect(()=>{const i=me.safeGet();if(!i||!e){n(SI);return}let o=!1;return n(s=>({...s,loading:!0})),i.searchUserDirectory({term:e,limit:10}).then(s=>{if(o)return;const a=i.getUserId(),l=s.results.filter(c=>c.user_id!==a).map(c=>({userId:c.user_id,displayName:c.display_name,avatarUrl:c.avatar_url}));n({results:l,loading:!1})}).catch(()=>{o||n({results:[],loading:!1})}),()=>{o=!0}},[e]),t}function eQ({open:r,roomId:e,spaceId:t,onOpenChange:n}){const[i,o]=E.useState(""),[s,a]=E.useState(null),[l,c]=E.useState(!1),{ready:u,isAgent:d}=RL(t),{results:f}=ZX(i),p=E.useMemo(()=>u?f.filter(w=>!d(w.userId)):f,[f,u,d]),h=()=>{o(""),a(null),c(!1)},m=async()=>{if(!s)return;const w=me.safeGet();if(w){c(!0);try{await w.invite(e,s),n(!1),h()}finally{c(!1)}}};return y.jsx(Mm,{open:r,onOpenChange:w=>{n(w),w||h()},children:y.jsxs(Am,{children:[y.jsxs(Dm,{children:[y.jsx(Lm,{children:"Invite to room"}),y.jsxs(Xw,{children:["Agent room membership is managed via ",y.jsx("code",{children:"zooid.yaml"}),"."]})]}),!u&&y.jsx("p",{className:"rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:"Agent list unavailable — search may include agents until the workforce roster publishes."}),y.jsxs(yL,{shouldFilter:!1,children:[y.jsx(SL,{placeholder:"Search users…",value:i,onValueChange:o,autoFocus:!0}),y.jsxs(bL,{children:[y.jsx(_L,{children:i.trim()?"No users found.":"Type to search."}),y.jsx(EL,{children:p.map(w=>y.jsxs(wL,{value:`${w.displayName??w.userId} ${w.userId}`,onSelect:()=>a(w.userId),"data-selected":s===w.userId||void 0,children:[y.jsx("span",{className:"flex-1 truncate",children:w.displayName??w.userId}),y.jsx("span",{className:"text-xs text-muted-foreground",children:w.userId})]},w.userId))})]})]}),y.jsxs(Nm,{children:[y.jsx(Gt,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),y.jsx(Gt,{onClick:m,disabled:!s||l,children:"Invite"})]})]})})}function tQ({open:r,roomId:e,currentName:t,onOpenChange:n}){const[i,o]=E.useState(t),[s,a]=E.useState(!1),[l,c]=E.useState(null);E.useEffect(()=>{r&&(o(t),c(null),a(!1))},[r,t]);const u=i.trim(),d=u.length>0&&u!==t&&!s,f=async()=>{const p=me.safeGet();if(p){a(!0),c(null);try{await p.setRoomName(e,u),n(!1)}catch(h){c(h instanceof Error?h.message:String(h)),a(!1)}}};return y.jsx(Mm,{open:r,onOpenChange:n,children:y.jsxs(Am,{className:"sm:max-w-md",children:[y.jsx(Dm,{children:y.jsx(Lm,{children:"Rename room"})}),y.jsxs("div",{className:"space-y-2",children:[y.jsx(Qd,{htmlFor:"room-name",children:"Room name"}),y.jsx(Xd,{id:"room-name",value:i,onChange:p=>o(p.target.value),maxLength:256,autoFocus:!0}),l&&y.jsx("div",{role:"alert",className:"text-sm text-destructive",children:l})]}),y.jsxs(Nm,{children:[y.jsx(Gt,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),y.jsx(Gt,{onClick:()=>void f(),disabled:!d,children:"Save"})]})]})})}function rQ({spaceId:r}){var g,b;const e=SF("/room/:roomId"),t=e==null?void 0:e.params.roomId,n=E.useSyncExternalStore(R=>me.subscribe(R),()=>me.safeGet(),()=>null),i=PL(t??""),o=Yw(t??""),{isFavorite:s,toggle:a}=CL(t??""),[l,c]=E.useState(!1),[u,d]=E.useState(!1);if(!t||!n)return null;const f=n.getRoom(t),p=(f==null?void 0:f.name)??t,h=((b=(g=f==null?void 0:f.currentState.getStateEvents("m.room.power_levels",""))==null?void 0:g.getContent())==null?void 0:b.invite)??50,m=o.level>=h,w=o.canSendStateEvent("m.room.name");return y.jsxs(y.Fragment,{children:[y.jsx(tL,{orientation:"vertical",className:"h-4"}),w?y.jsxs(Gw,{children:[y.jsx(Hw,{asChild:!0,children:y.jsxs(Gt,{variant:"ghost",size:"sm","aria-label":"Room actions",className:"h-7 max-w-48 gap-1 truncate px-1.5 text-sm font-medium",children:[y.jsx("span",{className:"truncate",children:p}),y.jsx(UP,{className:"size-3.5 text-muted-foreground"})]})}),y.jsx(zw,{align:"start",children:y.jsx(ld,{onSelect:()=>d(!0),children:"Rename room"})})]}):y.jsx("span",{className:"text-sm font-medium truncate max-w-48",children:p}),y.jsx(Gt,{variant:"ghost",size:"icon","aria-label":s?"Remove from favorites":"Add to favorites",onClick:()=>void a(),className:"size-6 text-muted-foreground hover:text-foreground",children:y.jsx(pK,{className:`size-3.5 ${s?"fill-current text-amber-500":""}`})}),i.length>0&&y.jsxs(kL,{children:[y.jsx(IL,{asChild:!0,children:y.jsxs(Gt,{variant:"ghost",size:"sm",className:"h-6 px-1.5 text-xs text-muted-foreground",children:[i.length," member",i.length!==1?"s":""]})}),y.jsxs(xL,{align:"start",className:"w-56 p-2",children:[m&&r&&y.jsx(Gt,{variant:"outline",size:"sm",className:"mb-2 w-full",onClick:()=>c(!0),children:"Invite"}),y.jsx("ul",{className:"space-y-1",children:i.map(R=>y.jsx("li",{className:"flex items-center gap-2 py-0.5",children:y.jsx(nQ,{roomId:t,userId:R.userId})},R.userId))})]})]}),r&&y.jsx(eQ,{open:l,roomId:t,spaceId:r,onOpenChange:c}),y.jsx(tQ,{open:u,roomId:t,currentName:p,onOpenChange:d})]})}function nQ({roomId:r,userId:e}){const{presence:t}=ML(e),n=Vo(e,r);return y.jsxs(y.Fragment,{children:[y.jsx(qw,{userId:e,size:"sm",presence:t}),y.jsx("span",{className:"text-sm truncate",children:n})]})}function iQ(){const r=oL(),e=r.getUserId()??"",t=Vo(e),n=e.split(":")[1]??e,i="dev",{spaceId:o}=HJ(i,n),a=YJ(o)??i;return E.useEffect(()=>{r.startClient({initialSyncLimit:10}).catch(()=>{})},[r]),y.jsxs(uJ,{className:"h-svh overflow-hidden",children:[y.jsxs(dJ,{collapsible:"icon",children:[y.jsx(pJ,{className:"h-12 flex-row items-center border-b border-sidebar-border px-4",children:y.jsx("span",{className:"text-sm font-medium truncate",children:a})}),y.jsx(vJ,{children:y.jsx(YX,{spaceId:o})})]}),y.jsxs(hJ,{"data-testid":"logged-in-view",children:[y.jsxs("header",{className:"flex items-center justify-between border-b border-border px-4 h-12",children:[y.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[y.jsx(fJ,{"aria-label":"Toggle sidebar"}),y.jsx(rQ,{spaceId:o})]}),y.jsxs(Gw,{children:[y.jsx(Hw,{asChild:!0,children:y.jsx(Gt,{variant:"ghost",size:"icon","aria-label":"User menu",className:"shrink-0",children:y.jsx(qw,{userId:e,size:"sm"})})}),y.jsxs(zw,{align:"end",className:"w-48",children:[y.jsx(ld,{disabled:!0,className:"font-medium",children:t}),y.jsx(ld,{disabled:!0,className:"text-xs text-muted-foreground",children:e}),y.jsx(GJ,{}),y.jsx(ld,{onSelect:()=>me.reset(),children:"Log out"})]})]})]}),y.jsx("main",{className:"flex-1 min-h-0 overflow-hidden",children:y.jsx(FF,{})})]})]})}const AL=[{names:["clear","new"],description:"Reset the agent's memory of this thread",threadScopedOnly:!0,build:()=>({eventType:"eco.zoon.session_reset",content:{}})},{names:["interrupt","stop"],description:"Stop the agent's current turn in this thread",threadScopedOnly:!0,build:r=>({eventType:"eco.zoon.interrupt",content:r?{reason:r}:{}})}];function oQ(r,e={threadScoped:!1}){if(!r.startsWith("/"))return null;const t=r.indexOf(" "),n=(t===-1?r.slice(1):r.slice(1,t)).toLowerCase(),i=t===-1?"":r.slice(t+1).trim();for(const o of AL)if(o.names.includes(n))return o.threadScopedOnly&&!e.threadScoped?null:o.build(i);return null}function sQ(r={threadScoped:!1}){return AL.flatMap(e=>e.threadScopedOnly&&!r.threadScoped?[]:e.names.map(t=>({name:t,description:e.description})))}const DL={events:[],pendingRootIds:[]},NL={events:[],totalCount:0},LL={root:void 0,rootPending:!1,events:[],totalCount:0},bI=new WeakMap,_I=new Map,EI=new Map,Zd=new Map,wy=new Set,wI=new Set,S_=new Set;function aQ(){for(const r of S_)r()}function UL(r,e,t){const n=`${e}:${t}`;Zd.has(t)||wy.has(n)||wI.has(n)||(wy.add(n),r.fetchRoomEvent(e,t).then(i=>{Zd.set(t,new pr(i)),aQ()}).catch(i=>{console.warn(`[useTimeline] fetchRoomEvent(${e}, ${t}) failed:`,i),wI.add(n)}).finally(()=>{wy.delete(n)}))}function If(r){const e=r.getUnfilteredTimelineSet(),t=new Set,n=[];for(const i of e.getTimelines())for(const o of i.getEvents()){const s=o.getId()??`${o.getType()}-${o.getTs()}`;t.has(s)||(t.add(s),n.push(o))}return n.sort((i,o)=>i.getTs()-o.getTs()),n}function lQ(r){var u;const e=me.safeGet(),t=e==null?void 0:e.getRoom(r);if(!e||!t)return DL;const n=If(t),i=new Set,o=new Set,s=[];for(const d of n){const f=d.getId();f&&i.add(f);const p=(u=d.getContent())==null?void 0:u["m.relates_to"];(p==null?void 0:p.rel_type)==="m.thread"?p.event_id&&o.add(p.event_id):s.push(d)}const a=[];for(const d of o){if(i.has(d))continue;const f=Zd.get(d);if(f){s.push(f);continue}const p=t.findEventById(d);if(p){s.push(p);continue}UL(e,r,d),a.push(d)}s.sort((d,f)=>d.getTs()-f.getTs());const l=bI.get(t);if(l&&l.events.length===s.length&&l.events[s.length-1]===s[s.length-1]&&l.pendingRootIds.length===a.length&&l.pendingRootIds.every((d,f)=>d===a[f]))return l;const c={events:s,pendingRootIds:a};return bI.set(t,c),c}function cQ(r,e){var p,h;const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return NL;const i=If(n),o=i.find(m=>m.getId()===e)??Zd.get(e)??n.findEventById(e),s=o==null?void 0:o.getUnsigned(),a=((h=(p=s==null?void 0:s["m.relations"])==null?void 0:p["m.thread"])==null?void 0:h.count)??0,l=i.filter(m=>{var g;const w=(g=m.getContent())==null?void 0:g["m.relates_to"];return(w==null?void 0:w.rel_type)==="m.thread"&&w.event_id===e}),c=Math.max(a,l.length),u=`${r}:${e}`,d=_I.get(u);if(d&&d.replyCount===l.length&&d.totalCount===c)return d.state;const f={events:l.slice(-3),totalCount:c};return _I.set(u,{replyCount:l.length,totalCount:c,state:f}),f}function uQ(r,e){var h,m;const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!t||!n)return LL;const i=If(n),o=i.find(w=>w.getId()===e)??Zd.get(e)??n.findEventById(e);let s=!1;o||(UL(t,r,e),s=!0);const a=o==null?void 0:o.getUnsigned(),l=((m=(h=a==null?void 0:a["m.relations"])==null?void 0:h["m.thread"])==null?void 0:m.count)??0,c=i.filter(w=>{var b;const g=(b=w.getContent())==null?void 0:b["m.relates_to"];return(g==null?void 0:g.rel_type)==="m.thread"&&g.event_id===e}),u=Math.max(l,c.length),d=`${r}:${e}`,f=EI.get(d);if(f&&f.replyCount===c.length&&f.totalCount===u&&f.root===o&&f.rootPending===s)return f.state;const p={root:o,rootPending:s,events:c,totalCount:u};return EI.set(d,{replyCount:c.length,totalCount:u,root:o,rootPending:s,state:p}),p}function xf(r){return e=>{const t=me.safeGet();if(!t)return me.subscribe(e);const n=(a,l)=>{(l==null?void 0:l.roomId)===r&&e()},i=a=>{a.roomId===r&&e()};t.on(fe.Timeline,n),t.on(Te.Room,i);const o=t.getRoom(r);o==null||o.on(fe.Timeline,n),S_.add(e);const s=me.subscribe(e);return()=>{t.off(fe.Timeline,n),t.off(Te.Room,i),o==null||o.off(fe.Timeline,n),S_.delete(e),s()}}}function jL(r){return E.useSyncExternalStore(xf(r),()=>lQ(r),()=>DL)}function FL(r,e){return E.useSyncExternalStore(xf(r),()=>cQ(r,e),()=>NL)}function dQ(r,e){return E.useSyncExternalStore(xf(r),()=>uQ(r,e),()=>LL)}const BL={status:null,content:null,rawInput:null,latestUpdateTs:0},TI=new Map;function fQ(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function hQ(r,e){const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return BL;const i=If(n);let o=-1,s=null,a=null,l=null;const c=[];for(const h of i){const m=h.getType();m!=="eco.zoon.tool_call"&&m!=="eco.zoon.tool_call_update"||h.getContent().tool_call_id!==e||c.push({ts:h.getTs(),ev:h})}c.sort((h,m)=>h.ts-m.ts);for(const{ts:h,ev:m}of c){const w=m.getType(),g=m.getContent();fQ(g.raw_input)&&(l={...l??{},...g.raw_input}),w==="eco.zoon.tool_call_update"&&typeof g.status=="string"&&h>=o&&(o=h,s=g.status,a=typeof g.content=="string"?g.content:null)}const u=l?JSON.stringify(l):"",d=`${r}:${e}`,f=TI.get(d);if(f&&f.ts===o&&f.status===s&&f.rawInputKey===u)return f.result;const p={status:s,content:a,rawInput:l,latestUpdateTs:o>0?o:0};return TI.set(d,{ts:o,status:s,rawInputKey:u,result:p}),p}function pQ(r,e){return E.useSyncExternalStore(xf(r),()=>hQ(r,e),()=>BL)}const sp={toolInput:null,toolKind:null,toolTitle:null},Ty=new Map;function vQ(r,e){const t=me.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return sp;const i=If(n);let o;for(const d of i){if(d.getType()!=="eco.zoon.approval_request")continue;if(d.getContent().tool_call_id===e){o=d;break}}const s=`${r}:${e}`,a=Ty.get(s),l=o==null?void 0:o.getId();if(a&&a.eventId===l)return a.result;if(!o)return Ty.set(s,{eventId:void 0,result:sp}),sp;const c=o.getContent(),u={toolInput:c.tool_input&&typeof c.tool_input=="object"&&!Array.isArray(c.tool_input)?c.tool_input:null,toolKind:typeof c.tool_kind=="string"?c.tool_kind:null,toolTitle:typeof c.tool_title=="string"?c.tool_title:null};return Ty.set(s,{eventId:l,result:u}),u}function mQ(r,e){return E.useSyncExternalStore(xf(r),()=>vQ(r,e),()=>sp)}const gQ="field-sizing-content min-h-9 flex-1 bg-transparent px-2.5 py-2 text-base outline-none placeholder:text-muted-foreground resize-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",yQ="flex items-center rounded-lg border border-input bg-transparent transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30 pr-1.5";function SQ(r,e){const t=r.replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"…":t}function bQ({roomId:r,threadRootEventId:e,onExitThread:t}){const n=oL(),[i,o]=E.useState(""),[s,a]=E.useState(null),[l,c]=E.useState(null),[u,d]=E.useState(0),f=E.useRef(null),p=!!e,h=e??null,w=FL(r,e??"").events.at(-1),g=E.useMemo(()=>{var oe;if(w)return w.getContent().body??"";if(!e)return"";const $=n==null?void 0:n.getRoom(r),X=$==null?void 0:$.getLiveTimeline().getEvents().find(re=>re.getId()===e);return((oe=X==null?void 0:X.getContent())==null?void 0:oe.body)??""},[w,e,n,r]),b=PL(r),R=E.useMemo(()=>b.map($=>({userId:$.userId,name:sL($)})),[b]),k=E.useMemo(()=>sQ({threadScoped:p}),[p]),O=E.useMemo(()=>{if(!l||l.mode!=="mention")return[];const $=l.query.toLowerCase();return R.filter(X=>X.userId.toLowerCase().includes($)||X.name.toLowerCase().includes($)).slice(0,8)},[l,R]),T=E.useMemo(()=>{if(!l||l.mode!=="slash")return[];const $=l.query.toLowerCase();return $?k.filter(X=>X.name.startsWith($)||X.description.toLowerCase().includes($)):k},[l,k]),x=(l==null?void 0:l.mode)==="slash"?T:O;function C($,X){if($.startsWith("/")&&X>0&&!$.includes(" ")){const re=$.slice(1,X);c(ae=>(ae==null?void 0:ae.mode)==="slash"&&ae.query===re?ae:(((ae==null?void 0:ae.mode)!=="slash"||ae.query!==re)&&d(0),{mode:"slash",start:0,query:re}));return}let oe=X-1;for(;oe>=0;){const re=$[oe];if(re==="@"){if(oe===0||/\s/.test($[oe-1])){const ae=$.slice(oe+1,X);if(!/\s/.test(ae)&&!ae.includes(":")){c(q=>(q==null?void 0:q.mode)==="mention"&&q.start===oe&&q.query===ae?q:(d(0),{mode:"mention",start:oe,query:ae}));return}}break}if(/\s/.test(re))break;oe--}c(null)}function N($){if(!l)return;const X=i.slice(0,l.start),oe=i.slice(l.start+1+l.query.length),re=`@${Cc($.userId)} `,ae=X+re+oe;o(ae),c(null),requestAnimationFrame(()=>{const q=f.current;if(!q)return;const z=X.length+re.length;q.focus(),q.setSelectionRange(z,z)})}function F($){const X=`/${$.name} `;o(X),c(null),requestAnimationFrame(()=>{const oe=f.current;oe&&(oe.focus(),oe.setSelectionRange(X.length,X.length))})}async function H(){const $=i.trim();if($){a(null);try{const X=oQ($,{threadScoped:p});if(X){const q=h?{...X.content,"m.relates_to":{rel_type:"m.thread",event_id:h}}:X.content;await n.sendEvent.call(n,r,h,X.eventType,q),o("");return}const{body:oe,userIds:re}=XJ($,R),ae={msgtype:"m.text",body:oe};re.length>0&&(ae["m.mentions"]={user_ids:re}),await n.sendEvent.call(n,r,h,"m.room.message",ae),o("")}catch(X){a(X instanceof Error?X.message:String(X))}}}const ie=async $=>{if(l&&x.length>0){if($.key==="ArrowDown"){$.preventDefault(),d(X=>(X+1)%x.length);return}if($.key==="ArrowUp"){$.preventDefault(),d(X=>(X-1+x.length)%x.length);return}if($.key==="Enter"||$.key==="Tab"){if($.preventDefault(),l.mode==="slash"){const X=T[u];X&&$.key==="Enter"&&i.trim()===`/${X.name}`?(c(null),await H()):F(X)}else N(O[u]);return}if($.key==="Escape"){$.preventDefault(),c(null);return}}$.key!=="Enter"||$.shiftKey||($.preventDefault(),await H())};return y.jsxs("div",{className:"relative shrink-0 border-t border-border p-3",children:[s&&y.jsx("div",{role:"alert",className:"mb-2 text-sm text-destructive",children:s}),e&&y.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-2 min-w-0",children:[g?y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"shrink-0",children:"Replying to"}),y.jsxs("span",{className:"truncate italic text-foreground/70",children:['"',SQ(g,60),'"']})]}):y.jsx("span",{className:"shrink-0",children:"Replying in current thread"}),y.jsx("button",{type:"button","aria-label":"Exit thread",onClick:()=>t==null?void 0:t(),className:"ml-auto shrink-0 rounded px-2 py-1 hover:bg-muted",children:"Cancel"})]}),l&&x.length>0&&y.jsx("ul",{role:"listbox","aria-label":l.mode==="slash"?"Command suggestions":"Mention suggestions",className:"absolute bottom-full left-3 right-3 mb-1 max-h-56 overflow-auto rounded-md border border-border bg-popover p-1 shadow-lg",children:l.mode==="slash"?T.map(($,X)=>y.jsxs("li",{role:"option","aria-selected":X===u,onMouseDown:oe=>{oe.preventDefault(),F($)},onMouseEnter:()=>d(X),className:"flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 text-sm "+(X===u?"bg-accent text-accent-foreground":""),children:[y.jsxs("span",{className:"font-mono font-semibold text-primary",children:["/",$.name]}),y.jsx("span",{className:"text-xs text-muted-foreground",children:$.description})]},$.name)):O.map(($,X)=>y.jsxs("li",{role:"option","aria-selected":X===u,onMouseDown:oe=>{oe.preventDefault(),N($)},onMouseEnter:()=>d(X),className:"flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 text-sm "+(X===u?"bg-accent text-accent-foreground":""),children:[y.jsx("span",{className:"font-semibold",style:{color:zc($.userId)},children:$.name}),y.jsx("span",{className:"text-xs text-muted-foreground",children:$.userId})]},$.userId))}),y.jsxs("div",{className:yQ,children:[y.jsx("textarea",{ref:f,"data-slot":"textarea","aria-label":"Message",placeholder:"Send a message…",value:i,onChange:$=>{o($.target.value),C($.target.value,$.target.selectionStart)},onKeyUp:$=>{if(!(l&&($.key==="ArrowDown"||$.key==="ArrowUp"))&&($.key.startsWith("Arrow")||$.key==="Home"||$.key==="End")){const X=$.currentTarget;C(X.value,X.selectionStart)}},onClick:$=>{const X=$.currentTarget;C(X.value,X.selectionStart)},onBlur:()=>c(null),onKeyDown:ie,rows:1,className:Ue(gQ)}),y.jsx("button",{type:"button",onClick:()=>void H(),disabled:!i.trim(),"aria-label":"Send message",className:"shrink-0 self-center rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40",children:y.jsx(uK,{className:"h-4 w-4"})})]})]})}function _Q({userId:r,roomId:e}){return y.jsx("span",{style:{color:zc(r)},children:Vo(r,e)})}function EQ({typingUserIds:r,roomId:e}){if(r.length===0)return y.jsx("div",{className:"h-5","aria-hidden":!0});const t=2,n=r.slice(0,t),i=r.length-t;let o;i>0?o=` and ${i} other${i>1?"s":""} are typing…`:r.length===1?o=" is typing…":o=" are typing…";const s=[];return n.forEach((a,l)=>{l>0&&s.push(", "),s.push(y.jsx(_Q,{userId:a,roomId:e},a))}),y.jsxs("div",{className:"h-5 px-3 text-xs text-muted-foreground leading-5",children:[s,o]})}function wQ(r,e,t=50){const[n,i]=E.useState(!1);return{loadMore:E.useCallback(async()=>{if(n)return;const s=me.safeGet(),a=s==null?void 0:s.getRoom(r),l=(a==null?void 0:a.getThread(e))??null;if(!(!s||!l)){i(!0);try{await s.paginateEventTimeline(l.liveTimeline,{backwards:!0,limit:t})}catch(c){console.warn(`[useLoadMoreThread] paginate(${r}, ${e}) failed:`,c)}finally{i(!1)}}},[r,e,t,n]),loading:n}}const kc={Request:"eco.zoon.approval_request",Response:"eco.zoon.approval_response"};function KL(r){if(r.getType()!==kc.Request)return null;const e=r.getContent();if(typeof e.approval_id!="string"||typeof e.session_id!="string"||typeof e.tool_call_id!="string")return null;const n=(Array.isArray(e.options)?e.options:[]).map(i=>{if(!i||typeof i!="object")return null;const o=i,s=typeof o.optionId=="string"?o.optionId:typeof o.id=="string"?o.id:null,a=typeof o.name=="string"?o.name:typeof o.label=="string"?o.label:null,l=typeof o.kind=="string"?o.kind:"";return!s||!a?null:{optionId:s,name:a,kind:l}}).filter(i=>i!==null);return{approvalId:e.approval_id,sessionId:e.session_id,toolCallId:e.tool_call_id,toolKind:typeof e.tool_kind=="string"?e.tool_kind:void 0,toolTitle:typeof e.tool_title=="string"?e.tool_title:void 0,toolInput:e.tool_input,options:n}}function TQ(r){if(r.getType()!==kc.Response)return null;const e=r.getContent();return typeof e.approval_id!="string"||e.decision!=="allow"&&e.decision!=="cancel"?null:{approvalId:e.approval_id,decision:e.decision,optionId:typeof e.option_id=="string"?e.option_id:void 0,respondedBy:r.getSender()??"?"}}function RQ(r,e){for(const t of r){const n=TQ(t);if(n&&n.approvalId===e)return n}return null}const ss={SessionStart:"eco.zoon.session.start",TurnStart:"eco.zoon.turn.start",AgentMessageChunk:"eco.zoon.agent_message_chunk",ToolCall:"eco.zoon.tool_call",ToolCallUpdate:"eco.zoon.tool_call_update",Plan:"eco.zoon.plan",TurnEnd:"eco.zoon.turn.end"},CQ=new Set(Object.values(ss));function kQ(r){return CQ.has(r.getType())}function IQ(r){const e=r.getContent(),t=typeof e.session_id=="string"?e.session_id:null;if(!t)return null;switch(r.getType()){case ss.SessionStart:return{kind:"session.start",sessionId:t};case ss.TurnStart:return{kind:"turn.start",sessionId:t};case ss.AgentMessageChunk:return typeof e.content!="string"?null:{kind:"agent_message_chunk",sessionId:t,content:e.content};case ss.ToolCall:{const n=typeof e.tool_call_id=="string"?e.tool_call_id:null,i=typeof e.title=="string"?e.title:null,o=typeof e.kind=="string"?e.kind:null;return!n||!i||!o?null:{kind:"tool_call",sessionId:t,toolCallId:n,title:i,toolKind:o,rawInput:RI(e.raw_input),locations:CI(e.locations)}}case ss.ToolCallUpdate:{const n=typeof e.tool_call_id=="string"?e.tool_call_id:null,i=typeof e.status=="string"?e.status:null;return!n||!i?null:{kind:"tool_call_update",sessionId:t,toolCallId:n,status:i,content:xQ(e.content),rawInput:RI(e.raw_input),locations:CI(e.locations)}}case ss.Plan:{if(!Array.isArray(e.entries))return null;const n=e.entries.map(i=>{if(!i||typeof i!="object")return null;const o=i;return typeof o.id!="string"||typeof o.title!="string"||typeof o.status!="string"?null:{id:o.id,title:o.title,status:o.status}}).filter(i=>i!==null);return{kind:"plan",sessionId:t,entries:n}}case ss.TurnEnd:return{kind:"turn.end",sessionId:t,stopReason:typeof e.stop_reason=="string"?e.stop_reason:void 0};default:return null}}function RI(r){if(r&&typeof r=="object"&&!Array.isArray(r))return r}function CI(r){if(!Array.isArray(r)||r.length===0)return;const e=[];for(const t of r)if(t&&typeof t=="object"){const n=t;typeof n.path=="string"&&e.push({path:n.path,line:typeof n.line=="number"?n.line:void 0})}return e.length>0?e:void 0}function xQ(r){if(typeof r=="string")return r;if(!Array.isArray(r)||r.length===0)return;const e=[];for(const t of r){if(!t||typeof t!="object")continue;const n=t;if(n.type==="content"&&n.content&&typeof n.content=="object"){const i=n.content;i.type==="text"&&typeof i.text=="string"&&e.push(i.text)}}return e.length>0?e.join(`
291
+ `):void 0}function OQ(r){const e=KL(r),t=r.getRoomId()??"",{events:n}=jL(t),i=e?RQ(n,e.approvalId):null,[o,s]=E.useState({sending:!1,error:null}),a=E.useRef(!1),l=E.useCallback(async(u,d)=>{if(e&&!i&&!a.current){a.current=!0,s({sending:!0,error:null});try{const f=me.get(),p={approval_id:e.approvalId,session_id:e.sessionId,decision:u};d&&(p.option_id=d),await f.sendEvent(t,kc.Response,p),s({sending:!1,error:null})}catch(f){s({sending:!1,error:f instanceof Error?f.message:String(f)}),a.current=!1}}},[e,i,t]);let c="pending";return i?c="resolved":o.error?c="error":o.sending&&(c="sending"),{state:c,resolution:i,error:o.error,send:l}}function PQ({event:r}){const e=KL(r),t=r.getRoomId()??"",n=Yw(t),{state:i,resolution:o,error:s,send:a}=OQ(r),[l,c]=E.useState(!1);if(!e)return null;const u=n.canSendEvent(kc.Response),d=MQ(e.toolKind,e.toolTitle,e.toolInput);return i==="resolved"&&o?y.jsx(p_,{"data-testid":"approval-card",className:"my-2 max-w-xl",children:y.jsxs(v_,{children:[y.jsx(m_,{className:"text-base",children:d.title}),y.jsxs(oI,{children:[d.subtitle&&y.jsx("span",{className:"block",children:d.subtitle}),o.decision==="allow"?"Approved":"Cancelled"," by"," ",y.jsx("span",{children:o.respondedBy})]})]})}):y.jsxs(p_,{"data-testid":"approval-card",className:"my-2 max-w-xl",children:[y.jsxs(v_,{children:[y.jsx(m_,{className:"text-base",children:d.title}),d.subtitle&&y.jsx(oI,{className:"font-mono text-xs break-all",children:d.subtitle})]}),e.toolInput!==void 0&&y.jsxs(np,{className:"pt-0",children:[y.jsx("button",{type:"button",onClick:()=>c(f=>!f),className:"text-xs text-muted-foreground hover:text-foreground","aria-expanded":l,children:l?"Hide details ▾":"Show details ▸"}),l&&y.jsx("pre",{className:"mt-2 max-h-64 overflow-auto rounded-md bg-muted/50 p-2 text-xs",children:AQ(e.toolInput)})]}),s&&y.jsx(np,{children:y.jsx("div",{role:"alert",className:"text-destructive text-sm",children:s})}),u?y.jsx(zY,{className:"gap-2",children:e.options.length===0?y.jsxs(y.Fragment,{children:[y.jsx(Gt,{type:"button",disabled:i==="sending",onClick:()=>a("allow"),children:"Allow"}),y.jsx(Gt,{type:"button",variant:"outline",disabled:i==="sending",onClick:()=>a("cancel"),children:"Cancel"})]}):e.options.map(f=>{const p=f.kind.startsWith("reject"),h=p?"cancel":"allow";return y.jsx(Gt,{type:"button",variant:p?"outline":"default",disabled:i==="sending",onClick:()=>a(h,f.optionId),children:f.name},f.optionId)})}):y.jsx(np,{children:y.jsx("p",{className:"text-muted-foreground text-sm",children:"You have insufficient permission to respond to this approval."})})]})}function MQ(r,e,t){const n=e??r??"Tool call",i=t&&typeof t=="object"?t:null;if(r==="edit"&&i&&typeof i.filepath=="string")return{title:`Edit ${kI(i.filepath)}`,subtitle:i.filepath};if(r==="fetch"&&i&&typeof i.url=="string")return{title:"Fetch",subtitle:i.url};if(r==="execute"&&i&&typeof i.command=="string")return{title:"Run command",subtitle:i.command};if(r==="read"&&i&&typeof i.filepath=="string")return{title:`Read ${kI(i.filepath)}`,subtitle:i.filepath};if(i){const o=Object.entries(i).find(([s,a])=>typeof a=="string"&&s!=="diff"&&a.length<200);if(o)return{title:n,subtitle:String(o[1])}}return{title:n}}function kI(r){const e=r.split("/");return e[e.length-1]||r}function AQ(r){try{return JSON.stringify(r,null,2)}catch{return String(r)}}function DQ({decoded:r,sender:e,roomId:t,ts:n}){const i=Vo(e,t);switch(r.kind){case"session.start":return y.jsx(II,{text:`${i} started session`});case"turn.start":return null;case"turn.end":return y.jsx(II,{text:`turn ended${r.stopReason?` (${r.stopReason})`:""}`});case"agent_message_chunk":return y.jsxs("div",{className:"py-1 text-sm text-foreground/80",children:[y.jsx("span",{className:"font-mono text-muted-foreground mr-2",children:i}),r.content]});case"tool_call":return y.jsx(BQ,{decoded:r,sender:e,roomId:t,ts:n});case"tool_call_update":return null;case"plan":return y.jsx($Q,{decoded:r})}}function II({text:r}){return y.jsxs("div",{className:"flex items-center gap-2 py-2 text-xs uppercase tracking-wider text-muted-foreground",children:[y.jsx("div",{className:"h-px flex-1 bg-border"}),y.jsx("span",{children:r}),y.jsx("div",{className:"h-px flex-1 bg-border"})]})}function NQ(r){switch(r){case"edit":return GB;case"read":return zB;case"fetch":return JB;case"execute":return HT;default:return HT}}function LQ({status:r}){return r?r==="completed"?y.jsx(LP,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):r==="failed"?y.jsx(RE,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}):r==="stalled"?y.jsx(KP,{className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400","aria-label":"stalled"}):r==="in_progress"||r==="pending"?y.jsx(Lv,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):null:null}const UQ=5*60*1e3,jQ=30*1e3;function FQ(r){const[,e]=E.useState(0);E.useEffect(()=>{if(!r)return;const t=setInterval(()=>e(n=>n+1),jQ);return()=>clearInterval(t)},[r])}function BQ({decoded:r,sender:e,roomId:t,ts:n}){const[i,o]=E.useState(!1),{status:s,content:a,rawInput:l,latestUpdateTs:c}=pQ(t,r.toolCallId),u=mQ(t,r.toolCallId),d=Vo(e,t),f=NQ(r.toolKind),p=r.title??r.toolKind??"Tool call",h=s===null||s==="pending"||s==="in_progress";FQ(h);const m=Math.max(n,c),w=h&&m>0&&Date.now()-m>UQ,g=w?"stalled":s??(h?"in_progress":null),b=(l&&Object.keys(l).length>0?l:u.toolInput)??void 0,R=KQ(r.toolKind,b,r.locations);return y.jsxs("div",{className:"my-1 rounded-md border border-border bg-muted/30",children:[y.jsxs("button",{type:"button",onClick:()=>o(k=>!k),"aria-expanded":i,className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-sm hover:bg-muted/50",children:[y.jsx(jP,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${i?"rotate-90":""}`}),y.jsx(f,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),y.jsx("span",{className:"font-medium",children:p}),R&&y.jsx("span",{className:"text-xs text-muted-foreground font-mono truncate",children:R}),y.jsx("span",{className:"ml-auto flex items-center gap-1.5",children:y.jsx(LQ,{status:g})})]}),i&&y.jsxs("div",{className:"border-t border-border px-2.5 py-2 text-xs text-muted-foreground space-y-1",children:[w&&y.jsxs("div",{className:"rounded-sm bg-amber-500/10 px-2 py-1 text-amber-700 dark:text-amber-400",children:["No updates for over 5 minutes — the tool may be stuck. Try",y.jsx("code",{className:"font-mono",children:" /interrupt"})," to cancel."]}),y.jsxs("div",{children:[y.jsx("span",{className:"text-foreground/70",children:"by"})," ",d]}),y.jsxs("div",{className:"font-mono break-all",children:["id: ",r.toolCallId]}),r.locations&&r.locations.length>0&&y.jsxs("div",{children:[y.jsx("span",{className:"text-foreground/70",children:"files: "}),r.locations.map((k,O)=>y.jsxs("span",{className:"font-mono break-all",children:[k.path,k.line!==void 0?`:${k.line}`:"",O<r.locations.length-1?", ":""]},O))]}),b&&Object.keys(b).length>0&&y.jsx("pre",{className:"mt-1 max-h-64 overflow-auto rounded-md bg-background/50 p-2 text-xs",children:VQ(b)}),a&&y.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words text-foreground/80",children:[y.jsx("span",{className:"text-foreground/70 block mb-0.5",children:"output:"}),a]})]})]})}function Ry(r){const e=r.split("/");return e[e.length-1]||r}function KQ(r,e,t){if(e){if(r==="edit"&&typeof e.filepath=="string"||r==="read"&&typeof e.filepath=="string")return Ry(e.filepath);if(r==="fetch"&&typeof e.url=="string")return e.url;if(r==="execute"&&typeof e.command=="string")return e.command;for(const[n,i]of Object.entries(e))if(n!=="diff"&&typeof i=="string"&&i.length<120)return i}return t&&t.length>0?Ry(t[0].path):null}function VQ(r){try{return JSON.stringify(r,null,2)}catch{return String(r)}}function $Q({decoded:r}){return y.jsxs("div",{className:"my-1 rounded-md border border-border bg-muted/30 px-2.5 py-2",children:[y.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[y.jsx(eK,{className:"h-3.5 w-3.5"}),"Plan"]}),y.jsx("ul",{className:"space-y-0.5 text-sm",children:r.entries.map(e=>y.jsxs("li",{className:"flex items-start gap-2",children:[y.jsx("span",{className:WQ(e.status),"aria-label":e.status}),y.jsx("span",{className:e.status==="completed"?"line-through text-muted-foreground":"text-foreground",children:e.title})]},e.id))})]})}function WQ(r){const e="mt-1.5 inline-block h-2 w-2 shrink-0 rounded-full ";switch(r){case"completed":return e+"bg-emerald-500";case"in_progress":return e+"bg-amber-500 animate-pulse";case"failed":return e+"bg-destructive";default:return e+"bg-muted-foreground/40"}}const Fu=new Map,Cy=new Map;function qQ(r,e){return`${r} ${e}`}function GQ(r,e){if(r.size!==e.size)return!1;for(const[t,n]of r){const i=e.get(t);if(!i||i.count!==n.count||i.mine!==n.mine||i.myEventId!==n.myEventId)return!1}return!0}function HQ(r,e){var c;const t=qQ(r,e),n=Cy.get(t)??Fu,i=me.safeGet(),o=i==null?void 0:i.getRoom(r);if(!i||!o)return n!==Fu&&Cy.set(t,Fu),Fu;const s=i.getSafeUserId(),a=new Map,l=o.getLiveTimeline().getEvents();for(const u of l){if(u.getType()!=="m.reaction"||(c=u.isRedacted)!=null&&c.call(u))continue;const f=u.getContent()["m.relates_to"];if((f==null?void 0:f.rel_type)!=="m.annotation"||f.event_id!==e)continue;const p=f.key??"";if(!p)continue;const h=u.getSender(),m=a.get(p)??{count:0,mine:!1,myEventId:void 0};m.count+=1,h===s&&(m.mine=!0,m.myEventId=u.getId()??m.myEventId),a.set(p,m)}return GQ(n,a)?n:(Cy.set(t,a),a)}function zQ(r,e){return E.useSyncExternalStore(t=>{const n=me.safeGet(),i=n==null?void 0:n.getRoom(r);if(!i)return me.subscribe(t);const o=()=>t();i.on(fe.Timeline,o),i.on(fe.Redaction,o);const s=me.subscribe(t);return()=>{i.off(fe.Timeline,o),i.off(fe.Redaction,o),s()}},()=>HQ(r,e),()=>Fu)}/*! @license DOMPurify 3.4.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.5/LICENSE */function xI(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function YQ(r){if(Array.isArray(r))return r}function JQ(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,o,s,a=[],l=!0,c=!1;try{if(o=(t=t.call(r)).next,e!==0)for(;!(l=(n=o.call(t)).done)&&(a.push(n.value),a.length!==e);l=!0);}catch(u){c=!0,i=u}finally{try{if(!l&&t.return!=null&&(s=t.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function XQ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
292
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function QQ(r,e){return YQ(r)||JQ(r,e)||ZQ(r,e)||XQ()}function ZQ(r,e){if(r){if(typeof r=="string")return xI(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?xI(r,e):void 0}}const VL=Object.entries,OI=Object.setPrototypeOf,eZ=Object.isFrozen,tZ=Object.getPrototypeOf,rZ=Object.getOwnPropertyDescriptor;let rn=Object.freeze,ti=Object.seal,wl=Object.create,$L=typeof Reflect<"u"&&Reflect,b_=$L.apply,__=$L.construct;rn||(rn=function(e){return e});ti||(ti=function(e){return e});b_||(b_=function(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;o<n;o++)i[o-2]=arguments[o];return e.apply(t,i)});__||(__=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return new e(...n)});const dl=ir(Array.prototype.forEach),nZ=ir(Array.prototype.lastIndexOf),PI=ir(Array.prototype.pop),fl=ir(Array.prototype.push),iZ=ir(Array.prototype.splice),zr=Array.isArray,Bu=ir(String.prototype.toLowerCase),ky=ir(String.prototype.toString),MI=ir(String.prototype.match),hl=ir(String.prototype.replace),AI=ir(String.prototype.indexOf),oZ=ir(String.prototype.trim),sZ=ir(Number.prototype.toString),aZ=ir(Boolean.prototype.toString),DI=typeof BigInt>"u"?null:ir(BigInt.prototype.toString),NI=typeof Symbol>"u"?null:ir(Symbol.prototype.toString),$t=ir(Object.prototype.hasOwnProperty),Ru=ir(Object.prototype.toString),Ir=ir(RegExp.prototype.test),Sh=lZ(TypeError);function ir(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return b_(r,e,n)}}function lZ(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return __(r,t)}}function Xe(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Bu;if(OI&&OI(r,null),!zr(e))return r;let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const o=t(i);o!==i&&(eZ(e)||(e[n]=o),i=o)}r[i]=!0}return r}function cZ(r){for(let e=0;e<r.length;e++)$t(r,e)||(r[e]=null);return r}function pn(r){const e=wl(null);for(const n of VL(r)){var t=QQ(n,2);const i=t[0],o=t[1];$t(r,i)&&(zr(o)?e[i]=cZ(o):o&&typeof o=="object"&&o.constructor===Object?e[i]=pn(o):e[i]=o)}return e}function uZ(r){switch(typeof r){case"string":return r;case"number":return sZ(r);case"boolean":return aZ(r);case"bigint":return DI?DI(r):"0";case"symbol":return NI?NI(r):"Symbol()";case"undefined":return Ru(r);case"function":case"object":{if(r===null)return Ru(r);const e=r,t=pa(e,"toString");if(typeof t=="function"){const n=t(e);return typeof n=="string"?n:Ru(n)}return Ru(r)}default:return Ru(r)}}function pa(r,e){for(;r!==null;){const n=rZ(r,e);if(n){if(n.get)return ir(n.get);if(typeof n.value=="function")return ir(n.value)}r=tZ(r)}function t(){return null}return t}function dZ(r){try{return Ir(r,""),!0}catch{return!1}}const LI=rn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Iy=rn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),xy=rn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),fZ=rn(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Oy=rn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),hZ=rn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),UI=rn(["#text"]),jI=rn(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Py=rn(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),FI=rn(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),bh=rn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),pZ=ti(/{{[\w\W]*|^[\w\W]*}}/g),vZ=ti(/<%[\w\W]*|^[\w\W]*%>/g),mZ=ti(/\${[\w\W]*/g),gZ=ti(/^data-[\-\w.\u00B7-\uFFFF]+$/),yZ=ti(/^aria-[\-\w]+$/),BI=ti(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),SZ=ti(/^(?:\w+script|data):/i),bZ=ti(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),_Z=ti(/^html$/i),EZ=ti(/^[a-z][.\w]*(-[.\w]+)+$/i),pl={element:1,text:3,progressingInstruction:7,comment:8,document:9},wZ=function(){return typeof window>"u"?null:window},TZ=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},KI=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function WL(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:wZ();const e=Ae=>WL(Ae);if(e.version="3.4.5",e.removed=[],!r||!r.document||r.document.nodeType!==pl.document||!r.Element)return e.isSupported=!1,e;let t=r.document;const n=t,i=n.currentScript,o=r.DocumentFragment,s=r.HTMLTemplateElement,a=r.Node,l=r.Element,c=r.NodeFilter,u=r.NamedNodeMap,d=u===void 0?r.NamedNodeMap||r.MozNamedAttrMap:u,f=r.HTMLFormElement,p=r.DOMParser,h=r.trustedTypes,m=l.prototype,w=pa(m,"cloneNode"),g=pa(m,"remove"),b=pa(m,"nextSibling"),R=pa(m,"childNodes"),k=pa(m,"parentNode"),O=a&&a.prototype?pa(a.prototype,"nodeType"):null;if(typeof s=="function"){const Ae=t.createElement("template");Ae.content&&Ae.content.ownerDocument&&(t=Ae.content.ownerDocument)}let T,x="";const C=t,N=C.implementation,F=C.createNodeIterator,H=C.createDocumentFragment,ie=C.getElementsByTagName,$=n.importNode;let X=KI();e.isSupported=typeof VL=="function"&&typeof k=="function"&&N&&N.createHTMLDocument!==void 0;const oe=pZ,re=vZ,ae=mZ,q=gZ,z=yZ,Q=SZ,Ie=bZ,Y=EZ;let le=BI,B=null;const W=Xe({},[...LI,...Iy,...xy,...Oy,...UI]);let A=null;const D=Xe({},[...jI,...Py,...FI,...bh]);let P=Object.seal(wl(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),M=null,I=null;const j=Object.seal(wl(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let U=!0,K=!0,G=!1,ee=!0,se=!1,Ce=!0,Re=!1,ge=!1,He=!1,Qe=!1,$e=!1,ve=!1,We=!0,un=!1;const Rr="user-content-";let gt=!0,vr=!1,mr={},Rt=null;const Rn=Xe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ye=null;const de=Xe({},["audio","video","img","source","image","track"]);let J=null;const te=Xe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ne="http://www.w3.org/1998/Math/MathML",ue="http://www.w3.org/2000/svg",_e="http://www.w3.org/1999/xhtml";let we=_e,ze=!1,dt=null;const ht=Xe({},[ne,ue,_e],ky);let Bt=Xe({},["mi","mo","mn","ms","mtext"]),Le=Xe({},["annotation-xml"]);const pt=Xe({},["title","style","font","a","script"]);let Kt=null;const Gr=["application/xhtml+xml","text/html"],Qa="text/html";let tt=null,or=null;const Za=t.createElement("form"),dn=function(L){return L instanceof RegExp||L instanceof Function},Hr=function(){let L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(or&&or===L)return;(!L||typeof L!="object")&&(L={}),L=pn(L),Kt=Gr.indexOf(L.PARSER_MEDIA_TYPE)===-1?Qa:L.PARSER_MEDIA_TYPE,tt=Kt==="application/xhtml+xml"?ky:Bu,B=$t(L,"ALLOWED_TAGS")&&zr(L.ALLOWED_TAGS)?Xe({},L.ALLOWED_TAGS,tt):W,A=$t(L,"ALLOWED_ATTR")&&zr(L.ALLOWED_ATTR)?Xe({},L.ALLOWED_ATTR,tt):D,dt=$t(L,"ALLOWED_NAMESPACES")&&zr(L.ALLOWED_NAMESPACES)?Xe({},L.ALLOWED_NAMESPACES,ky):ht,J=$t(L,"ADD_URI_SAFE_ATTR")&&zr(L.ADD_URI_SAFE_ATTR)?Xe(pn(te),L.ADD_URI_SAFE_ATTR,tt):te,ye=$t(L,"ADD_DATA_URI_TAGS")&&zr(L.ADD_DATA_URI_TAGS)?Xe(pn(de),L.ADD_DATA_URI_TAGS,tt):de,Rt=$t(L,"FORBID_CONTENTS")&&zr(L.FORBID_CONTENTS)?Xe({},L.FORBID_CONTENTS,tt):Rn,M=$t(L,"FORBID_TAGS")&&zr(L.FORBID_TAGS)?Xe({},L.FORBID_TAGS,tt):pn({}),I=$t(L,"FORBID_ATTR")&&zr(L.FORBID_ATTR)?Xe({},L.FORBID_ATTR,tt):pn({}),mr=$t(L,"USE_PROFILES")?L.USE_PROFILES&&typeof L.USE_PROFILES=="object"?pn(L.USE_PROFILES):L.USE_PROFILES:!1,U=L.ALLOW_ARIA_ATTR!==!1,K=L.ALLOW_DATA_ATTR!==!1,G=L.ALLOW_UNKNOWN_PROTOCOLS||!1,ee=L.ALLOW_SELF_CLOSE_IN_ATTR!==!1,se=L.SAFE_FOR_TEMPLATES||!1,Ce=L.SAFE_FOR_XML!==!1,Re=L.WHOLE_DOCUMENT||!1,Qe=L.RETURN_DOM||!1,$e=L.RETURN_DOM_FRAGMENT||!1,ve=L.RETURN_TRUSTED_TYPE||!1,He=L.FORCE_BODY||!1,We=L.SANITIZE_DOM!==!1,un=L.SANITIZE_NAMED_PROPS||!1,gt=L.KEEP_CONTENT!==!1,vr=L.IN_PLACE||!1,le=dZ(L.ALLOWED_URI_REGEXP)?L.ALLOWED_URI_REGEXP:BI,we=typeof L.NAMESPACE=="string"?L.NAMESPACE:_e,Bt=$t(L,"MATHML_TEXT_INTEGRATION_POINTS")&&L.MATHML_TEXT_INTEGRATION_POINTS&&typeof L.MATHML_TEXT_INTEGRATION_POINTS=="object"?pn(L.MATHML_TEXT_INTEGRATION_POINTS):Xe({},["mi","mo","mn","ms","mtext"]),Le=$t(L,"HTML_INTEGRATION_POINTS")&&L.HTML_INTEGRATION_POINTS&&typeof L.HTML_INTEGRATION_POINTS=="object"?pn(L.HTML_INTEGRATION_POINTS):Xe({},["annotation-xml"]);const ce=$t(L,"CUSTOM_ELEMENT_HANDLING")&&L.CUSTOM_ELEMENT_HANDLING&&typeof L.CUSTOM_ELEMENT_HANDLING=="object"?pn(L.CUSTOM_ELEMENT_HANDLING):wl(null);if(P=wl(null),$t(ce,"tagNameCheck")&&dn(ce.tagNameCheck)&&(P.tagNameCheck=ce.tagNameCheck),$t(ce,"attributeNameCheck")&&dn(ce.attributeNameCheck)&&(P.attributeNameCheck=ce.attributeNameCheck),$t(ce,"allowCustomizedBuiltInElements")&&typeof ce.allowCustomizedBuiltInElements=="boolean"&&(P.allowCustomizedBuiltInElements=ce.allowCustomizedBuiltInElements),se&&(K=!1),$e&&(Qe=!0),mr&&(B=Xe({},UI),A=wl(null),mr.html===!0&&(Xe(B,LI),Xe(A,jI)),mr.svg===!0&&(Xe(B,Iy),Xe(A,Py),Xe(A,bh)),mr.svgFilters===!0&&(Xe(B,xy),Xe(A,Py),Xe(A,bh)),mr.mathMl===!0&&(Xe(B,Oy),Xe(A,FI),Xe(A,bh))),j.tagCheck=null,j.attributeCheck=null,$t(L,"ADD_TAGS")&&(typeof L.ADD_TAGS=="function"?j.tagCheck=L.ADD_TAGS:zr(L.ADD_TAGS)&&(B===W&&(B=pn(B)),Xe(B,L.ADD_TAGS,tt))),$t(L,"ADD_ATTR")&&(typeof L.ADD_ATTR=="function"?j.attributeCheck=L.ADD_ATTR:zr(L.ADD_ATTR)&&(A===D&&(A=pn(A)),Xe(A,L.ADD_ATTR,tt))),$t(L,"ADD_URI_SAFE_ATTR")&&zr(L.ADD_URI_SAFE_ATTR)&&Xe(J,L.ADD_URI_SAFE_ATTR,tt),$t(L,"FORBID_CONTENTS")&&zr(L.FORBID_CONTENTS)&&(Rt===Rn&&(Rt=pn(Rt)),Xe(Rt,L.FORBID_CONTENTS,tt)),$t(L,"ADD_FORBID_CONTENTS")&&zr(L.ADD_FORBID_CONTENTS)&&(Rt===Rn&&(Rt=pn(Rt)),Xe(Rt,L.ADD_FORBID_CONTENTS,tt)),gt&&(B["#text"]=!0),Re&&Xe(B,["html","head","body"]),B.table&&(Xe(B,["tbody"]),delete M.tbody),L.TRUSTED_TYPES_POLICY){if(typeof L.TRUSTED_TYPES_POLICY.createHTML!="function")throw Sh('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof L.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Sh('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=L.TRUSTED_TYPES_POLICY,x=T.createHTML("")}else T===void 0&&(T=TZ(h,i)),T!==null&&typeof x=="string"&&(x=T.createHTML(""));rn&&rn(L),or=L},Jc=Xe({},[...Iy,...xy,...fZ]),Pi=Xe({},[...Oy,...hZ]),p0=function(L){let ce=k(L);(!ce||!ce.tagName)&&(ce={namespaceURI:we,tagName:"template"});const ke=Bu(L.tagName),rt=Bu(ce.tagName);return dt[L.namespaceURI]?L.namespaceURI===ue?ce.namespaceURI===_e?ke==="svg":ce.namespaceURI===ne?ke==="svg"&&(rt==="annotation-xml"||Bt[rt]):!!Jc[ke]:L.namespaceURI===ne?ce.namespaceURI===_e?ke==="math":ce.namespaceURI===ue?ke==="math"&&Le[rt]:!!Pi[ke]:L.namespaceURI===_e?ce.namespaceURI===ue&&!Le[rt]||ce.namespaceURI===ne&&!Bt[rt]?!1:!Pi[ke]&&(pt[ke]||!Jc[ke]):!!(Kt==="application/xhtml+xml"&&dt[L.namespaceURI]):!1},ii=function(L){fl(e.removed,{element:L});try{k(L).removeChild(L)}catch{g(L)}},Ys=function(L,ce){try{fl(e.removed,{attribute:ce.getAttributeNode(L),from:ce})}catch{fl(e.removed,{attribute:null,from:ce})}if(ce.removeAttribute(L),L==="is")if(Qe||$e)try{ii(ce)}catch{}else try{ce.setAttribute(L,"")}catch{}},v0=function(L){let ce=null,ke=null;if(He)L="<remove></remove>"+L;else{const er=MI(L,/^[\r\n\t ]+/);ke=er&&er[0]}Kt==="application/xhtml+xml"&&we===_e&&(L='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+L+"</body></html>");const rt=T?T.createHTML(L):L;if(we===_e)try{ce=new p().parseFromString(rt,Kt)}catch{}if(!ce||!ce.documentElement){ce=N.createDocument(we,"template",null);try{ce.documentElement.innerHTML=ze?x:rt}catch{}}const Zt=ce.body||ce.documentElement;return L&&ke&&Zt.insertBefore(t.createTextNode(ke),Zt.childNodes[0]||null),we===_e?ie.call(ce,Re?"html":"body")[0]:Re?ce.documentElement:Zt},m0=function(L){return F.call(L.ownerDocument||L,L,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},g0=function(L){L.normalize();const ce=F.call(L.ownerDocument||L,L,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let ke=ce.nextNode();for(;ke;){let rt=ke.data;dl([oe,re,ae],Zt=>{rt=hl(rt,Zt," ")}),ke.data=rt,ke=ce.nextNode()}},Wm=function(L){return L instanceof f&&(typeof L.nodeName!="string"||typeof L.textContent!="string"||typeof L.removeChild!="function"||!(L.attributes instanceof d)||typeof L.removeAttribute!="function"||typeof L.setAttribute!="function"||typeof L.namespaceURI!="string"||typeof L.insertBefore!="function"||typeof L.hasChildNodes!="function")},Of=function(L){if(!O||typeof L!="object"||L===null)return!1;try{return typeof O(L)=="number"}catch{return!1}};function oo(Ae,L,ce){dl(Ae,ke=>{ke.call(e,L,ce,or)})}const y0=function(L){let ce=null;if(oo(X.beforeSanitizeElements,L,null),Wm(L))return ii(L),!0;const ke=tt(L.nodeName);if(oo(X.uponSanitizeElement,L,{tagName:ke,allowedTags:B}),Ce&&L.hasChildNodes()&&!Of(L.firstElementChild)&&Ir(/<[/\w!]/g,L.innerHTML)&&Ir(/<[/\w!]/g,L.textContent)||Ce&&L.namespaceURI===_e&&ke==="style"&&Of(L.firstElementChild)||L.nodeType===pl.progressingInstruction||Ce&&L.nodeType===pl.comment&&Ir(/<[/\w]/g,L.data))return ii(L),!0;if(M[ke]||!(j.tagCheck instanceof Function&&j.tagCheck(ke))&&!B[ke]){if(!M[ke]&&b0(ke)&&(P.tagNameCheck instanceof RegExp&&Ir(P.tagNameCheck,ke)||P.tagNameCheck instanceof Function&&P.tagNameCheck(ke)))return!1;if(gt&&!Rt[ke]){const rt=k(L)||L.parentNode,Zt=R(L)||L.childNodes;if(Zt&&rt){const er=Zt.length;for(let fn=er-1;fn>=0;--fn){const $o=w(Zt[fn],!0);rt.insertBefore($o,b(L))}}}return ii(L),!0}return L instanceof l&&!p0(L)||(ke==="noscript"||ke==="noembed"||ke==="noframes")&&Ir(/<\/no(script|embed|frames)/i,L.innerHTML)?(ii(L),!0):(se&&L.nodeType===pl.text&&(ce=L.textContent,dl([oe,re,ae],rt=>{ce=hl(ce,rt," ")}),L.textContent!==ce&&(fl(e.removed,{element:L.cloneNode()}),L.textContent=ce)),oo(X.afterSanitizeElements,L,null),!1)},S0=function(L,ce,ke){if(I[ce]||We&&(ce==="id"||ce==="name")&&(ke in t||ke in Za))return!1;const rt=A[ce]||j.attributeCheck instanceof Function&&j.attributeCheck(ce,L);if(!(K&&!I[ce]&&Ir(q,ce))){if(!(U&&Ir(z,ce))){if(!rt||I[ce]){if(!(b0(L)&&(P.tagNameCheck instanceof RegExp&&Ir(P.tagNameCheck,L)||P.tagNameCheck instanceof Function&&P.tagNameCheck(L))&&(P.attributeNameCheck instanceof RegExp&&Ir(P.attributeNameCheck,ce)||P.attributeNameCheck instanceof Function&&P.attributeNameCheck(ce,L))||ce==="is"&&P.allowCustomizedBuiltInElements&&(P.tagNameCheck instanceof RegExp&&Ir(P.tagNameCheck,ke)||P.tagNameCheck instanceof Function&&P.tagNameCheck(ke))))return!1}else if(!J[ce]){if(!Ir(le,hl(ke,Ie,""))){if(!((ce==="src"||ce==="xlink:href"||ce==="href")&&L!=="script"&&AI(ke,"data:")===0&&ye[L])){if(!(G&&!Ir(Q,hl(ke,Ie,"")))){if(ke)return!1}}}}}}return!0},vU=Xe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),b0=function(L){return!vU[Bu(L)]&&Ir(Y,L)},_0=function(L){oo(X.beforeSanitizeAttributes,L,null);const ce=L.attributes;if(!ce||Wm(L))return;const ke={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:A,forceKeepAttr:void 0};let rt=ce.length;for(;rt--;){const Zt=ce[rt],er=Zt.name,fn=Zt.namespaceURI,$o=Zt.value,so=tt(er),Gm=$o;let gr=er==="value"?Gm:oZ(Gm);if(ke.attrName=so,ke.attrValue=gr,ke.keepAttr=!0,ke.forceKeepAttr=void 0,oo(X.uponSanitizeAttribute,L,ke),gr=ke.attrValue,un&&(so==="id"||so==="name")&&AI(gr,Rr)!==0&&(Ys(er,L),gr=Rr+gr),Ce&&Ir(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,gr)){Ys(er,L);continue}if(so==="attributename"&&MI(gr,"href")){Ys(er,L);continue}if(ke.forceKeepAttr)continue;if(!ke.keepAttr){Ys(er,L);continue}if(!ee&&Ir(/\/>/i,gr)){Ys(er,L);continue}se&&dl([oe,re,ae],w0=>{gr=hl(gr,w0," ")});const E0=tt(L.nodeName);if(!S0(E0,so,gr)){Ys(er,L);continue}if(T&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!fn)switch(h.getAttributeType(E0,so)){case"TrustedHTML":{gr=T.createHTML(gr);break}case"TrustedScriptURL":{gr=T.createScriptURL(gr);break}}if(gr!==Gm)try{fn?L.setAttributeNS(fn,er,gr):L.setAttribute(er,gr),Wm(L)?ii(L):PI(e.removed)}catch{Ys(er,L)}}oo(X.afterSanitizeAttributes,L,null)},qm=function(L){let ce=null;const ke=m0(L);for(oo(X.beforeSanitizeShadowDOM,L,null);ce=ke.nextNode();)oo(X.uponSanitizeShadowNode,ce,null),y0(ce),_0(ce),ce.content instanceof o&&qm(ce.content);oo(X.afterSanitizeShadowDOM,L,null)},Pf=function(L){if(L.nodeType===pl.element&&L.shadowRoot instanceof o){const rt=L.shadowRoot;Pf(rt),qm(rt)}const ce=L.childNodes;if(!ce)return;const ke=[];dl(ce,rt=>{fl(ke,rt)});for(const rt of ke)Pf(rt)};return e.sanitize=function(Ae){let L=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ce=null,ke=null,rt=null,Zt=null;if(ze=!Ae,ze&&(Ae="<!-->"),typeof Ae!="string"&&!Of(Ae)&&(Ae=uZ(Ae),typeof Ae!="string"))throw Sh("dirty is not a string, aborting");if(!e.isSupported)return Ae;if(ge||Hr(L),e.removed=[],typeof Ae=="string"&&(vr=!1),vr){const $o=Ae.nodeName;if(typeof $o=="string"){const so=tt($o);if(!B[so]||M[so])throw Sh("root node is forbidden and cannot be sanitized in-place")}Pf(Ae)}else if(Of(Ae))ce=v0("<!---->"),ke=ce.ownerDocument.importNode(Ae,!0),ke.nodeType===pl.element&&ke.nodeName==="BODY"||ke.nodeName==="HTML"?ce=ke:ce.appendChild(ke),Pf(ke);else{if(!Qe&&!se&&!Re&&Ae.indexOf("<")===-1)return T&&ve?T.createHTML(Ae):Ae;if(ce=v0(Ae),!ce)return Qe?null:ve?x:""}ce&&He&&ii(ce.firstChild);const er=m0(vr?Ae:ce);for(;rt=er.nextNode();)y0(rt),_0(rt),rt.content instanceof o&&qm(rt.content);if(vr)return se&&g0(Ae),Ae;if(Qe){if(se&&g0(ce),$e)for(Zt=H.call(ce.ownerDocument);ce.firstChild;)Zt.appendChild(ce.firstChild);else Zt=ce;return(A.shadowroot||A.shadowrootmode)&&(Zt=$.call(n,Zt,!0)),Zt}let fn=Re?ce.outerHTML:ce.innerHTML;return Re&&B["!doctype"]&&ce.ownerDocument&&ce.ownerDocument.doctype&&ce.ownerDocument.doctype.name&&Ir(_Z,ce.ownerDocument.doctype.name)&&(fn="<!DOCTYPE "+ce.ownerDocument.doctype.name+`>
293
+ `+fn),se&&dl([oe,re,ae],$o=>{fn=hl(fn,$o," ")}),T&&ve?T.createHTML(fn):fn},e.setConfig=function(){let Ae=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Hr(Ae),ge=!0},e.clearConfig=function(){or=null,ge=!1},e.isValidAttribute=function(Ae,L,ce){or||Hr({});const ke=tt(Ae),rt=tt(L);return S0(ke,rt,ce)},e.addHook=function(Ae,L){typeof L=="function"&&fl(X[Ae],L)},e.removeHook=function(Ae,L){if(L!==void 0){const ce=nZ(X[Ae],L);return ce===-1?void 0:iZ(X[Ae],ce,1)[0]}return PI(X[Ae])},e.removeHooks=function(Ae){X[Ae]=[]},e.removeAllHooks=function(){X=KI()},e}var RZ=WL(),Qw={},Zw={};Object.defineProperty(Zw,"__esModule",{value:!0});var bt;(function(r){r.Root="root",r.Text="text",r.Directive="directive",r.Comment="comment",r.Script="script",r.Style="style",r.Tag="tag",r.CDATA="cdata",r.Doctype="doctype"})(bt||(bt={}));function CZ(r){return r.type===bt.Tag||r.type===bt.Script||r.type===bt.Style}bt.Root;bt.Text;bt.Directive;bt.Comment;bt.Script;bt.Style;bt.Tag;bt.CDATA;bt.Doctype;let qL=class{constructor(){De(this,"parent",null);De(this,"prev",null);De(this,"next",null);De(this,"startIndex",null);De(this,"endIndex",null)}get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return JL(this,e)}},e0=class extends qL{constructor(t){super();De(this,"data");this.data=t}get nodeValue(){return this.data}set nodeValue(t){this.data=t}},GL=class extends e0{constructor(){super(...arguments);De(this,"type",bt.Text)}get nodeType(){return 3}},HL=class extends e0{constructor(){super(...arguments);De(this,"type",bt.Comment)}get nodeType(){return 8}},zL=class extends e0{constructor(t,n){super(n);De(this,"type",bt.Directive);De(this,"name");De(this,"x-name");De(this,"x-publicId");De(this,"x-systemId");this.name=t}get nodeType(){return 1}},t0=class extends qL{constructor(t){super();De(this,"children");this.children=t}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(t){this.children=t}},kZ=class extends t0{constructor(){super(...arguments);De(this,"type",bt.CDATA)}get nodeType(){return 4}},IZ=class extends t0{constructor(){super(...arguments);De(this,"type",bt.Root)}get nodeType(){return 9}},YL=class extends t0{constructor(t,n,i=[],o=t==="script"?bt.Script:t==="style"?bt.Style:bt.Tag){super(i);De(this,"name");De(this,"attribs");De(this,"type");De(this,"namespace");De(this,"x-attribsNamespace");De(this,"x-attribsPrefix");this.name=t,this.attribs=n,this.type=o}get nodeType(){return 1}get tagName(){return this.name}set tagName(t){this.name=t}get attributes(){return Object.keys(this.attribs).map(t=>{var n,i;return{name:t,value:this.attribs[t],namespace:(n=this["x-attribsNamespace"])==null?void 0:n[t],prefix:(i=this["x-attribsPrefix"])==null?void 0:i[t]}})}};function xZ(r){return CZ(r)}function OZ(r){return r.type===bt.CDATA}function PZ(r){return r.type===bt.Text}function MZ(r){return r.type===bt.Comment}function AZ(r){return r.type===bt.Directive}function DZ(r){return r.type===bt.Root}function JL(r,e=!1){let t;if(PZ(r))t=new GL(r.data);else if(MZ(r))t=new HL(r.data);else if(xZ(r)){const n=e?My(r.children):[],i=new YL(r.name,{...r.attribs},n);for(const o of n)o.parent=i;r.namespace!=null&&(i.namespace=r.namespace),r["x-attribsNamespace"]&&(i["x-attribsNamespace"]={...r["x-attribsNamespace"]}),r["x-attribsPrefix"]&&(i["x-attribsPrefix"]={...r["x-attribsPrefix"]}),t=i}else if(OZ(r)){const n=e?My(r.children):[],i=new kZ(n);for(const o of n)o.parent=i;t=i}else if(DZ(r)){const n=e?My(r.children):[],i=new IZ(n);for(const o of n)o.parent=i;r["x-mode"]&&(i["x-mode"]=r["x-mode"]),t=i}else if(AZ(r)){const n=new zL(r.name,r.data);r["x-name"]!=null&&(n["x-name"]=r["x-name"],n["x-publicId"]=r["x-publicId"],n["x-systemId"]=r["x-systemId"]),t=n}else throw new Error(`Not implemented yet: ${r.type}`);return t.startIndex=r.startIndex,t.endIndex=r.endIndex,r.sourceCodeLocation!=null&&(t.sourceCodeLocation=r.sourceCodeLocation),t}function My(r){const e=r.map(t=>JL(t,!0));for(let t=1;t<e.length;t++)e[t].prev=e[t-1],e[t-1].next=e[t];return e}var NZ=["animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","linearGradient","radialGradient","textPath"],LZ=NZ.reduce(function(r,e){return r[e.toLowerCase()]=e,r},{}),XL="\r",UZ=new RegExp(XL,"g"),QL="__HTML_DOM_PARSER_CARRIAGE_RETURN_PLACEHOLDER_".concat(Date.now().toString(),"__"),jZ=new RegExp(QL,"g");function FZ(r){return LZ[r]}function BZ(r){for(var e={},t=0,n=r.length;t<n;t++){var i=r[t];e[i.name]=i.value}return e}function KZ(r){r=r.toLowerCase();var e=FZ(r);return e||r}function _h(r,e){var t="<"+e,n=r.toLowerCase().indexOf(t);if(n===-1)return!1;var i=r[n+t.length];return i===">"||i===" "||i===" "||i===`
294
+ `||i==="\r"||i==="/"}function VZ(r){return r.replace(UZ,QL)}function $Z(r){return r.replace(jZ,XL)}function ZL(r,e,t){var n,i,o,s;e===void 0&&(e=null);for(var a=[],l,c=0,u=r.length;c<u;c++){var d=r[c];switch(d.nodeType){case 1:{var f=KZ(d.nodeName);l=new YL(f,BZ(d.attributes)),l.children=ZL(f==="template"?d.content.childNodes:d.childNodes,l);break}case 3:l=new GL($Z((n=d.nodeValue)!==null&&n!==void 0?n:""));break;case 8:l=new HL((i=d.nodeValue)!==null&&i!==void 0?i:"");break;default:continue}var p=(o=a[c-1])!==null&&o!==void 0?o:null;p&&(p.next=l),l.parent=e,l.prev=p,l.next=null,a.push(l)}return t&&(l=new zL(t.substring(0,t.indexOf(" ")).toLowerCase(),t),l.next=(s=a[0])!==null&&s!==void 0?s:null,l.parent=e,a.unshift(l),a[1]&&(a[1].prev=a[0])),a}var VI="html",Eh="head",vl="body",WZ=/<([a-zA-Z]+[0-9]?)/;function E_(r,e){return e?e.createHTML(r):r}var hv=function(r,e,t){throw new Error("This browser does not support `document.implementation.createHTMLDocument`")},w_=function(r,e,t){throw new Error("This browser does not support `DOMParser.prototype.parseFromString`")},$I=typeof window=="object"&&window.DOMParser;if(typeof $I=="function"){var qZ=new $I,GZ="text/html";w_=function(r,e,t){return e&&(r="<".concat(e,">").concat(r,"</").concat(e,">")),qZ.parseFromString(r,GZ)},hv=w_}if(typeof document=="object"&&document.implementation){var wh=document.implementation.createHTMLDocument();hv=function(r,e,t){if(e){var n=wh.documentElement.querySelector(e);return n&&(n.innerHTML=E_(r,t)),wh}return wh.documentElement.innerHTML=E_(r,t),wh}}var Th=typeof document=="object"&&document.createElement("template"),T_;Th&&Th.content&&(T_=function(r,e){return Th.innerHTML=E_(r,e),Th.content.childNodes});var WI=function(){return document.createDocumentFragment().childNodes};function HZ(r,e){var t,n,i,o,s,a;r=VZ(r);var l=WZ.exec(r),c=(t=l==null?void 0:l[1])===null||t===void 0?void 0:t.toLowerCase();switch(c){case VI:{var u=w_(r);if(!_h(r,Eh)){var d=u.querySelector(Eh);(n=d==null?void 0:d.parentNode)===null||n===void 0||n.removeChild(d)}if(!_h(r,vl)){var d=u.querySelector(vl);(i=d==null?void 0:d.parentNode)===null||i===void 0||i.removeChild(d)}return u.querySelectorAll(VI)}case Eh:case vl:{var f=hv(r,void 0,e).querySelectorAll(c);return _h(r,vl)&&_h(r,Eh)?(s=(o=f[0].parentNode)===null||o===void 0?void 0:o.childNodes)!==null&&s!==void 0?s:WI():f}default:{if(T_)return T_(r,e);var d=hv(r,vl,e).querySelector(vl);return(a=d==null?void 0:d.childNodes)!==null&&a!==void 0?a:WI()}}}var zZ=/<(![a-zA-Z\s]+)>/;function YZ(r,e){if(typeof r!="string")throw new TypeError("First argument must be a string");if(!r)return[];var t=zZ.exec(r),n=t?t[1]:void 0;return ZL(HZ(r,e==null?void 0:e.trustedTypePolicy),null,n)}Zw.default=YZ;var Um={},Oi={},jm={},JZ=0;jm.SAME=JZ;var XZ=1;jm.CAMELCASE=XZ;jm.possibleStandardNames={accept:0,acceptCharset:1,"accept-charset":"acceptCharset",accessKey:1,action:0,allowFullScreen:1,alt:0,as:0,async:0,autoCapitalize:1,autoComplete:1,autoCorrect:1,autoFocus:1,autoPlay:1,autoSave:1,capture:0,cellPadding:1,cellSpacing:1,challenge:0,charSet:1,checked:0,children:0,cite:0,class:"className",classID:1,className:1,cols:0,colSpan:1,content:0,contentEditable:1,contextMenu:1,controls:0,controlsList:1,coords:0,crossOrigin:1,dangerouslySetInnerHTML:1,data:0,dateTime:1,default:0,defaultChecked:1,defaultValue:1,defer:0,dir:0,disabled:0,disablePictureInPicture:1,disableRemotePlayback:1,download:0,draggable:0,encType:1,enterKeyHint:1,for:"htmlFor",form:0,formMethod:1,formAction:1,formEncType:1,formNoValidate:1,formTarget:1,frameBorder:1,headers:0,height:0,hidden:0,high:0,href:0,hrefLang:1,htmlFor:1,httpEquiv:1,"http-equiv":"httpEquiv",icon:0,id:0,innerHTML:1,inputMode:1,integrity:0,is:0,itemID:1,itemProp:1,itemRef:1,itemScope:1,itemType:1,keyParams:1,keyType:1,kind:0,label:0,lang:0,list:0,loop:0,low:0,manifest:0,marginWidth:1,marginHeight:1,max:0,maxLength:1,media:0,mediaGroup:1,method:0,min:0,minLength:1,multiple:0,muted:0,name:0,noModule:1,nonce:0,noValidate:1,open:0,optimum:0,pattern:0,placeholder:0,playsInline:1,poster:0,preload:0,profile:0,radioGroup:1,readOnly:1,referrerPolicy:1,rel:0,required:0,reversed:0,role:0,rows:0,rowSpan:1,sandbox:0,scope:0,scoped:0,scrolling:0,seamless:0,selected:0,shape:0,size:0,sizes:0,span:0,spellCheck:1,src:0,srcDoc:1,srcLang:1,srcSet:1,start:0,step:0,style:0,summary:0,tabIndex:1,target:0,title:0,type:0,useMap:1,value:0,width:0,wmode:0,wrap:0,about:0,accentHeight:1,"accent-height":"accentHeight",accumulate:0,additive:0,alignmentBaseline:1,"alignment-baseline":"alignmentBaseline",allowReorder:1,alphabetic:0,amplitude:0,arabicForm:1,"arabic-form":"arabicForm",ascent:0,attributeName:1,attributeType:1,autoReverse:1,azimuth:0,baseFrequency:1,baselineShift:1,"baseline-shift":"baselineShift",baseProfile:1,bbox:0,begin:0,bias:0,by:0,calcMode:1,capHeight:1,"cap-height":"capHeight",clip:0,clipPath:1,"clip-path":"clipPath",clipPathUnits:1,clipRule:1,"clip-rule":"clipRule",color:0,colorInterpolation:1,"color-interpolation":"colorInterpolation",colorInterpolationFilters:1,"color-interpolation-filters":"colorInterpolationFilters",colorProfile:1,"color-profile":"colorProfile",colorRendering:1,"color-rendering":"colorRendering",contentScriptType:1,contentStyleType:1,cursor:0,cx:0,cy:0,d:0,datatype:0,decelerate:0,descent:0,diffuseConstant:1,direction:0,display:0,divisor:0,dominantBaseline:1,"dominant-baseline":"dominantBaseline",dur:0,dx:0,dy:0,edgeMode:1,elevation:0,enableBackground:1,"enable-background":"enableBackground",end:0,exponent:0,externalResourcesRequired:1,fill:0,fillOpacity:1,"fill-opacity":"fillOpacity",fillRule:1,"fill-rule":"fillRule",filter:0,filterRes:1,filterUnits:1,floodOpacity:1,"flood-opacity":"floodOpacity",floodColor:1,"flood-color":"floodColor",focusable:0,fontFamily:1,"font-family":"fontFamily",fontSize:1,"font-size":"fontSize",fontSizeAdjust:1,"font-size-adjust":"fontSizeAdjust",fontStretch:1,"font-stretch":"fontStretch",fontStyle:1,"font-style":"fontStyle",fontVariant:1,"font-variant":"fontVariant",fontWeight:1,"font-weight":"fontWeight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:1,"glyph-name":"glyphName",glyphOrientationHorizontal:1,"glyph-orientation-horizontal":"glyphOrientationHorizontal",glyphOrientationVertical:1,"glyph-orientation-vertical":"glyphOrientationVertical",glyphRef:1,gradientTransform:1,gradientUnits:1,hanging:0,horizAdvX:1,"horiz-adv-x":"horizAdvX",horizOriginX:1,"horiz-origin-x":"horizOriginX",ideographic:0,imageRendering:1,"image-rendering":"imageRendering",in2:0,in:0,inlist:0,intercept:0,k1:0,k2:0,k3:0,k4:0,k:0,kernelMatrix:1,kernelUnitLength:1,kerning:0,keyPoints:1,keySplines:1,keyTimes:1,lengthAdjust:1,letterSpacing:1,"letter-spacing":"letterSpacing",lightingColor:1,"lighting-color":"lightingColor",limitingConeAngle:1,local:0,markerEnd:1,"marker-end":"markerEnd",markerHeight:1,markerMid:1,"marker-mid":"markerMid",markerStart:1,"marker-start":"markerStart",markerUnits:1,markerWidth:1,mask:0,maskContentUnits:1,maskUnits:1,mathematical:0,mode:0,numOctaves:1,offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:1,"overline-position":"overlinePosition",overlineThickness:1,"overline-thickness":"overlineThickness",paintOrder:1,"paint-order":"paintOrder",panose1:0,"panose-1":"panose1",pathLength:1,patternContentUnits:1,patternTransform:1,patternUnits:1,pointerEvents:1,"pointer-events":"pointerEvents",points:0,pointsAtX:1,pointsAtY:1,pointsAtZ:1,prefix:0,preserveAlpha:1,preserveAspectRatio:1,primitiveUnits:1,property:0,r:0,radius:0,refX:1,refY:1,renderingIntent:1,"rendering-intent":"renderingIntent",repeatCount:1,repeatDur:1,requiredExtensions:1,requiredFeatures:1,resource:0,restart:0,result:0,results:0,rotate:0,rx:0,ry:0,scale:0,security:0,seed:0,shapeRendering:1,"shape-rendering":"shapeRendering",slope:0,spacing:0,specularConstant:1,specularExponent:1,speed:0,spreadMethod:1,startOffset:1,stdDeviation:1,stemh:0,stemv:0,stitchTiles:1,stopColor:1,"stop-color":"stopColor",stopOpacity:1,"stop-opacity":"stopOpacity",strikethroughPosition:1,"strikethrough-position":"strikethroughPosition",strikethroughThickness:1,"strikethrough-thickness":"strikethroughThickness",string:0,stroke:0,strokeDasharray:1,"stroke-dasharray":"strokeDasharray",strokeDashoffset:1,"stroke-dashoffset":"strokeDashoffset",strokeLinecap:1,"stroke-linecap":"strokeLinecap",strokeLinejoin:1,"stroke-linejoin":"strokeLinejoin",strokeMiterlimit:1,"stroke-miterlimit":"strokeMiterlimit",strokeWidth:1,"stroke-width":"strokeWidth",strokeOpacity:1,"stroke-opacity":"strokeOpacity",suppressContentEditableWarning:1,suppressHydrationWarning:1,surfaceScale:1,systemLanguage:1,tableValues:1,targetX:1,targetY:1,textAnchor:1,"text-anchor":"textAnchor",textDecoration:1,"text-decoration":"textDecoration",textLength:1,textRendering:1,"text-rendering":"textRendering",to:0,transform:0,typeof:0,u1:0,u2:0,underlinePosition:1,"underline-position":"underlinePosition",underlineThickness:1,"underline-thickness":"underlineThickness",unicode:0,unicodeBidi:1,"unicode-bidi":"unicodeBidi",unicodeRange:1,"unicode-range":"unicodeRange",unitsPerEm:1,"units-per-em":"unitsPerEm",unselectable:0,vAlphabetic:1,"v-alphabetic":"vAlphabetic",values:0,vectorEffect:1,"vector-effect":"vectorEffect",version:0,vertAdvY:1,"vert-adv-y":"vertAdvY",vertOriginX:1,"vert-origin-x":"vertOriginX",vertOriginY:1,"vert-origin-y":"vertOriginY",vHanging:1,"v-hanging":"vHanging",vIdeographic:1,"v-ideographic":"vIdeographic",viewBox:1,viewTarget:1,visibility:0,vMathematical:1,"v-mathematical":"vMathematical",vocab:0,widths:0,wordSpacing:1,"word-spacing":"wordSpacing",writingMode:1,"writing-mode":"writingMode",x1:0,x2:0,x:0,xChannelSelector:1,xHeight:1,"x-height":"xHeight",xlinkActuate:1,"xlink:actuate":"xlinkActuate",xlinkArcrole:1,"xlink:arcrole":"xlinkArcrole",xlinkHref:1,"xlink:href":"xlinkHref",xlinkRole:1,"xlink:role":"xlinkRole",xlinkShow:1,"xlink:show":"xlinkShow",xlinkTitle:1,"xlink:title":"xlinkTitle",xlinkType:1,"xlink:type":"xlinkType",xmlBase:1,"xml:base":"xmlBase",xmlLang:1,"xml:lang":"xmlLang",xmlns:0,"xml:space":"xmlSpace",xmlnsXlink:1,"xmlns:xlink":"xmlnsXlink",xmlSpace:1,y1:0,y2:0,y:0,yChannelSelector:1,z:0,zoomAndPan:1};const eU=0,zs=1,Fm=2,Bm=3,r0=4,tU=5,rU=6;function QZ(r){return Ur.hasOwnProperty(r)?Ur[r]:null}function cn(r,e,t,n,i,o,s){this.acceptsBooleans=e===Fm||e===Bm||e===r0,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=t,this.propertyName=r,this.type=e,this.sanitizeURL=o,this.removeEmptyString=s}const Ur={},ZZ=["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"];ZZ.forEach(r=>{Ur[r]=new cn(r,eU,!1,r,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(([r,e])=>{Ur[r]=new cn(r,zs,!1,e,null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(r=>{Ur[r]=new cn(r,Fm,!1,r.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(r=>{Ur[r]=new cn(r,Fm,!1,r,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"].forEach(r=>{Ur[r]=new cn(r,Bm,!1,r.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(r=>{Ur[r]=new cn(r,Bm,!0,r,null,!1,!1)});["capture","download"].forEach(r=>{Ur[r]=new cn(r,r0,!1,r,null,!1,!1)});["cols","rows","size","span"].forEach(r=>{Ur[r]=new cn(r,rU,!1,r,null,!1,!1)});["rowSpan","start"].forEach(r=>{Ur[r]=new cn(r,tU,!1,r.toLowerCase(),null,!1,!1)});const n0=/[\-\:]([a-z])/g,i0=r=>r[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"].forEach(r=>{const e=r.replace(n0,i0);Ur[e]=new cn(e,zs,!1,r,null,!1,!1)});["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(r=>{const e=r.replace(n0,i0);Ur[e]=new cn(e,zs,!1,r,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(r=>{const e=r.replace(n0,i0);Ur[e]=new cn(e,zs,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(r=>{Ur[r]=new cn(r,zs,!1,r.toLowerCase(),null,!1,!1)});const eee="xlinkHref";Ur[eee]=new cn("xlinkHref",zs,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(r=>{Ur[r]=new cn(r,zs,!1,r.toLowerCase(),null,!0,!0)});const{CAMELCASE:tee,SAME:ree,possibleStandardNames:qI}=jm,nee=":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",iee=nee+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",oee=RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+iee+"]*$")),see=Object.keys(qI).reduce((r,e)=>{const t=qI[e];return t===ree?r[e]=e:t===tee?r[e.toLowerCase()]=e:r[e]=t,r},{});Oi.BOOLEAN=Bm;Oi.BOOLEANISH_STRING=Fm;Oi.NUMERIC=tU;Oi.OVERLOADED_BOOLEAN=r0;Oi.POSITIVE_NUMERIC=rU;Oi.RESERVED=eU;Oi.STRING=zs;Oi.getPropertyInfo=QZ;Oi.isCustomAttribute=oee;Oi.possibleStandardNames=see;var o0={},s0={},GI=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,aee=/\n/g,lee=/^\s*/,cee=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,uee=/^:\s*/,dee=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,fee=/^[;\s]*/,hee=/^\s+|\s+$/g,pee=`
295
+ `,HI="/",zI="*",ya="",vee="comment",mee="declaration";function gee(r,e){if(typeof r!="string")throw new TypeError("First argument must be a string");if(!r)return[];e=e||{};var t=1,n=1;function i(h){var m=h.match(aee);m&&(t+=m.length);var w=h.lastIndexOf(pee);n=~w?h.length-w:n+h.length}function o(){var h={line:t,column:n};return function(m){return m.position=new s(h),c(),m}}function s(h){this.start=h,this.end={line:t,column:n},this.source=e.source}s.prototype.content=r;function a(h){var m=new Error(e.source+":"+t+":"+n+": "+h);if(m.reason=h,m.filename=e.source,m.line=t,m.column=n,m.source=r,!e.silent)throw m}function l(h){var m=h.exec(r);if(m){var w=m[0];return i(w),r=r.slice(w.length),m}}function c(){l(lee)}function u(h){var m;for(h=h||[];m=d();)m!==!1&&h.push(m);return h}function d(){var h=o();if(!(HI!=r.charAt(0)||zI!=r.charAt(1))){for(var m=2;ya!=r.charAt(m)&&(zI!=r.charAt(m)||HI!=r.charAt(m+1));)++m;if(m+=2,ya===r.charAt(m-1))return a("End of comment missing");var w=r.slice(2,m-2);return n+=2,i(w),r=r.slice(m),n+=2,h({type:vee,comment:w})}}function f(){var h=o(),m=l(cee);if(m){if(d(),!l(uee))return a("property missing ':'");var w=l(dee),g=h({type:mee,property:YI(m[0].replace(GI,ya)),value:w?YI(w[0].replace(GI,ya)):ya});return l(fee),g}}function p(){var h=[];u(h);for(var m;m=f();)m!==!1&&(h.push(m),u(h));return h}return c(),p()}function YI(r){return r?r.replace(hee,ya):ya}var yee=gee,See=wi&&wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(s0,"__esModule",{value:!0});s0.default=_ee;const bee=See(yee);function _ee(r,e){let t=null;if(!r||typeof r!="string")return t;const n=(0,bee.default)(r),i=typeof e=="function";return n.forEach(o=>{if(o.type!=="declaration")return;const{property:s,value:a}=o;i?e(s,a,o):a&&(t=t||{},t[s]=a)}),t}var Km={};Object.defineProperty(Km,"__esModule",{value:!0});Km.camelCase=void 0;var Eee=/^--[a-zA-Z0-9_-]+$/,wee=/-([a-z])/g,Tee=/^[^-]+$/,Ree=/^-(webkit|moz|ms|o|khtml)-/,Cee=/^-(ms)-/,kee=function(r){return!r||Tee.test(r)||Eee.test(r)},Iee=function(r,e){return e.toUpperCase()},JI=function(r,e){return"".concat(e,"-")},xee=function(r,e){return e===void 0&&(e={}),kee(r)?r:(r=r.toLowerCase(),e.reactCompat?r=r.replace(Cee,JI):r=r.replace(Ree,JI),r.replace(wee,Iee))};Km.camelCase=xee;var Oee=wi&&wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},Pee=Oee(s0),Mee=Km;function R_(r,e){var t={};return!r||typeof r!="string"||(0,Pee.default)(r,function(n,i){n&&i&&(t[(0,Mee.camelCase)(n,e)]=i)}),t}R_.default=R_;var Aee=R_;(function(r){var e=wi&&wi.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(r,"__esModule",{value:!0}),r.returnFirstArg=r.canTextBeChildOfNode=r.ELEMENTS_WITH_NO_TEXT_CHILDREN=r.PRESERVE_CUSTOM_ATTRIBUTES=void 0,r.isCustomComponent=o,r.setStyleProp=a;const t=E,n=e(Aee),i=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function o(u,d){return u.includes("-")?!i.has(u):!!(d&&typeof d.is=="string")}const s={reactCompat:!0};function a(u,d){if(typeof u=="string"){if(!u.trim()){d.style={};return}try{d.style=(0,n.default)(u,s)}catch{d.style={}}}}r.PRESERVE_CUSTOM_ATTRIBUTES=Number(t.version.split(".")[0])>=16,r.ELEMENTS_WITH_NO_TEXT_CHILDREN=new Set(["tr","tbody","thead","tfoot","colgroup","table","head","html","frameset"]);const l=u=>!r.ELEMENTS_WITH_NO_TEXT_CHILDREN.has(u.name);r.canTextBeChildOfNode=l;const c=u=>u;r.returnFirstArg=c})(o0);Object.defineProperty(Um,"__esModule",{value:!0});Um.default=Uee;const Ku=Oi,XI=o0,Dee=["checked","value"],Nee=["input","select","textarea"],Lee={reset:!0,submit:!0};function Uee(r={},e){const t={},n=!!(r.type&&Lee[r.type]);for(const i in r){const o=r[i];if((0,Ku.isCustomAttribute)(i)){t[i]=o;continue}const s=i.toLowerCase();let a=QI(s);if(a){const l=(0,Ku.getPropertyInfo)(a);switch(Dee.includes(a)&&Nee.includes(e)&&!n&&(a=QI("default"+s)),t[a]=o,l==null?void 0:l.type){case Ku.BOOLEAN:t[a]=!0;break;case Ku.OVERLOADED_BOOLEAN:o===""&&(t[a]=!0);break}continue}XI.PRESERVE_CUSTOM_ATTRIBUTES&&(t[i]=o)}return(0,XI.setStyleProp)(r.style,t),t}function QI(r){return Ku.possibleStandardNames[r]}var a0={},ut;(function(r){r.Root="root",r.Text="text",r.Directive="directive",r.Comment="comment",r.Script="script",r.Style="style",r.Tag="tag",r.CDATA="cdata",r.Doctype="doctype"})(ut||(ut={}));function jee(r){return r.type===ut.Tag||r.type===ut.Script||r.type===ut.Style}ut.Root;ut.Text;ut.Directive;ut.Comment;ut.Script;ut.Style;ut.Tag;ut.CDATA;ut.Doctype;let l0=class{constructor(){De(this,"parent",null);De(this,"prev",null);De(this,"next",null);De(this,"startIndex",null);De(this,"endIndex",null)}get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return h0(this,e)}};class Vm extends l0{constructor(t){super();De(this,"data");this.data=t}get nodeValue(){return this.data}set nodeValue(t){this.data=t}}class pv extends Vm{constructor(){super(...arguments);De(this,"type",ut.Text)}get nodeType(){return 3}}class c0 extends Vm{constructor(){super(...arguments);De(this,"type",ut.Comment)}get nodeType(){return 8}}class u0 extends Vm{constructor(t,n){super(n);De(this,"type",ut.Directive);De(this,"name");De(this,"x-name");De(this,"x-publicId");De(this,"x-systemId");this.name=t}get nodeType(){return 1}}class $m extends l0{constructor(t){super();De(this,"children");this.children=t}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(t){this.children=t}}class d0 extends $m{constructor(){super(...arguments);De(this,"type",ut.CDATA)}get nodeType(){return 4}}class vv extends $m{constructor(){super(...arguments);De(this,"type",ut.Root)}get nodeType(){return 9}}let f0=class extends $m{constructor(t,n,i=[],o=t==="script"?ut.Script:t==="style"?ut.Style:ut.Tag){super(i);De(this,"name");De(this,"attribs");De(this,"type");De(this,"namespace");De(this,"x-attribsNamespace");De(this,"x-attribsPrefix");this.name=t,this.attribs=n,this.type=o}get nodeType(){return 1}get tagName(){return this.name}set tagName(t){this.name=t}get attributes(){return Object.keys(this.attribs).map(t=>{var n,i;return{name:t,value:this.attribs[t],namespace:(n=this["x-attribsNamespace"])==null?void 0:n[t],prefix:(i=this["x-attribsPrefix"])==null?void 0:i[t]}})}};function nU(r){return jee(r)}function iU(r){return r.type===ut.CDATA}function oU(r){return r.type===ut.Text}function sU(r){return r.type===ut.Comment}function aU(r){return r.type===ut.Directive}function lU(r){return r.type===ut.Root}function Fee(r){return Object.hasOwn(r,"children")}function h0(r,e=!1){let t;if(oU(r))t=new pv(r.data);else if(sU(r))t=new c0(r.data);else if(nU(r)){const n=e?Ay(r.children):[],i=new f0(r.name,{...r.attribs},n);for(const o of n)o.parent=i;r.namespace!=null&&(i.namespace=r.namespace),r["x-attribsNamespace"]&&(i["x-attribsNamespace"]={...r["x-attribsNamespace"]}),r["x-attribsPrefix"]&&(i["x-attribsPrefix"]={...r["x-attribsPrefix"]}),t=i}else if(iU(r)){const n=e?Ay(r.children):[],i=new d0(n);for(const o of n)o.parent=i;t=i}else if(lU(r)){const n=e?Ay(r.children):[],i=new vv(n);for(const o of n)o.parent=i;r["x-mode"]&&(i["x-mode"]=r["x-mode"]),t=i}else if(aU(r)){const n=new u0(r.name,r.data);r["x-name"]!=null&&(n["x-name"]=r["x-name"],n["x-publicId"]=r["x-publicId"],n["x-systemId"]=r["x-systemId"]),t=n}else throw new Error(`Not implemented yet: ${r.type}`);return t.startIndex=r.startIndex,t.endIndex=r.endIndex,r.sourceCodeLocation!=null&&(t.sourceCodeLocation=r.sourceCodeLocation),t}function Ay(r){const e=r.map(t=>h0(t,!0));for(let t=1;t<e.length;t++)e[t].prev=e[t-1],e[t-1].next=e[t];return e}const ZI={withStartIndices:!1,withEndIndices:!1,xmlMode:!1};class ex{constructor(e,t,n){De(this,"dom",[]);De(this,"root",new vv(this.dom));De(this,"callback");De(this,"options");De(this,"elementCB");De(this,"done",!1);De(this,"tagStack",[this.root]);De(this,"lastNode",null);De(this,"parser",null);typeof t=="function"&&(n=t,t=ZI),typeof e=="object"&&(t=e,e=void 0),this.callback=e??null,this.options=t??ZI,this.elementCB=n??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new vv(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;const e=this.tagStack.pop();this.options.withEndIndices&&this.parser&&(e.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(e)}onopentag(e,t){const n=this.options.xmlMode?ut.Tag:void 0,i=new f0(e,t,void 0,n);this.addNode(i),this.tagStack.push(i)}ontext(e){const{lastNode:t}=this;if(t&&t.type===ut.Text)t.data+=e,this.options.withEndIndices&&this.parser&&(t.endIndex=this.parser.endIndex);else{const n=new pv(e);this.addNode(n),this.lastNode=n}}oncomment(e){if(this.lastNode&&this.lastNode.type===ut.Comment){this.lastNode.data+=e;return}const t=new c0(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){const e=new pv(""),t=new d0([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){const n=new u0(e,t);this.addNode(n)}handleCallback(e){if(typeof this.callback=="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){const t=this.tagStack[this.tagStack.length-1],n=t.children[t.children.length-1];this.options.withStartIndices&&this.parser&&(e.startIndex=this.parser.startIndex),this.options.withEndIndices&&this.parser&&(e.endIndex=this.parser.endIndex),t.children.push(e),n&&(e.prev=n,n.next=e),e.parent=t,this.lastNode=null}}const Bee=Object.freeze(Object.defineProperty({__proto__:null,CDATA:d0,Comment:c0,DataNode:Vm,Document:vv,DomHandler:ex,Element:f0,Node:l0,NodeWithChildren:$m,ProcessingInstruction:u0,Text:pv,cloneNode:h0,default:ex,hasChildren:Fee,isCDATA:iU,isComment:sU,isDirective:aU,isDocument:lU,isTag:nU,isText:oU},Symbol.toStringTag,{value:"Module"})),cU=SU(Bee);var Kee=wi&&wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(a0,"__esModule",{value:!0});a0.default=uU;const Vee=cU,Dy=E,$ee=Kee(Um),cd=o0,Wee={cloneElement:Dy.cloneElement,createElement:Dy.createElement,isValidElement:Dy.isValidElement};function uU(r,e={}){var t,n,i,o,s;const a=[],l=typeof e.replace=="function",c=(t=e.transform)!==null&&t!==void 0?t:cd.returnFirstArg,{cloneElement:u,createElement:d,isValidElement:f}=(n=e.library)!==null&&n!==void 0?n:Wee,p=r.length;dU(r);for(let h=0;h<p;h++){const m=r[h];if(l){let R=(i=e.replace)===null||i===void 0?void 0:i.call(e,m,h);if(f(R)){p>1&&(R=u(R,{key:(o=R.key)!==null&&o!==void 0?o:h})),a.push(c(R,m,h));continue}}if(m.type==="text"){const R=!m.data.trim().length;if(R&&m.parent&&!(0,cd.canTextBeChildOfNode)(m.parent)||e.trim&&R)continue;a.push(c(m.data,m,h));continue}const w=m;let g={};qee(w)?((0,cd.setStyleProp)(w.attribs.style,w.attribs),g=w.attribs):w.attribs&&(g=(0,$ee.default)(w.attribs,w.name));let b;switch(m.type){case"script":case"style":m.children[0]&&(g.dangerouslySetInnerHTML={__html:m.children[0].data});break;case"tag":m.name==="textarea"&&m.children[0]?g.defaultValue=m.children[0].data:!((s=m.children)===null||s===void 0)&&s.length&&(b=uU(m.children,e));break;default:continue}p>1&&(g.key=h),a.push(c(d(m.name,g,b),m,h))}return a.length===1?a[0]:a}function dU(r){for(const e of r)(e.type==="tag"||e.type==="script"||e.type==="style")&&(Object.setPrototypeOf(e,Vee.Element.prototype),dU(e.children))}function qee(r){return cd.PRESERVE_CUSTOM_ATTRIBUTES&&r.type==="tag"&&(0,cd.isCustomComponent)(r.name,r.attribs)}(function(r){var e=wi&&wi.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(r,"__esModule",{value:!0}),r.htmlToDOM=r.domToReact=r.attributesToProps=r.Text=r.ProcessingInstruction=r.Element=r.Comment=void 0,r.default=a;const t=e(Zw);r.htmlToDOM=t.default;const n=e(Um);r.attributesToProps=n.default;const i=e(a0);r.domToReact=i.default;var o=cU;Object.defineProperty(r,"Comment",{enumerable:!0,get:function(){return o.Comment}}),Object.defineProperty(r,"Element",{enumerable:!0,get:function(){return o.Element}}),Object.defineProperty(r,"ProcessingInstruction",{enumerable:!0,get:function(){return o.ProcessingInstruction}}),Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return o.Text}});const s={lowerCaseAttributeNames:!1};function a(l,c){var u;if(typeof l!="string")throw new TypeError("First argument must be a string");if(!l)return[];const d=Object.assign(Object.assign({},(u=c==null?void 0:c.htmlparser2)!==null&&u!==void 0?u:s),{trustedTypePolicy:c==null?void 0:c.trustedTypePolicy});return(0,i.default)((0,t.default)(l,d),c)}})(Qw);const tx=Ka(Qw),Gee=tx.default||tx,Hee=["del","h1","h2","h3","h4","h5","h6","blockquote","p","a","ul","ol","sup","sub","li","b","i","u","strong","em","s","code","hr","br","div","table","thead","tbody","tr","th","td","caption","pre","span","img","details","summary"],zee=["href","name","target","width","height","alt","title","src","start","class","data-mx-color","data-mx-bg-color","data-mx-spoiler"];function Yee({userId:r,roomId:e}){const t=Vo(r,e);return y.jsxs("span",{className:"rounded-sm bg-primary/15 px-1 font-medium",style:{color:zc(r)},title:r,children:["@",t]})}function Jee(r,e){return lL(r).map((t,n)=>t.userId?y.jsx(Yee,{userId:t.userId,roomId:e},n):y.jsx(E.Fragment,{children:t.text},n))}function fU({html:r,roomId:e}){const t=RZ.sanitize(r,{ALLOWED_TAGS:Hee,ALLOWED_ATTR:zee,ALLOWED_URI_REGEXP:/^(?:(?:https?|ftp|mailto|magnet|matrix):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i}),n={replace:i=>{var o;if(i.type==="tag"&&i.name==="a"){const s=((o=i.attribs)==null?void 0:o.href)??"",a=i.children??[];return y.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer ugc",className:"text-primary underline",children:Qw.domToReact(a,n)})}if(i.type==="text"){const s=i.data;return s.includes(":")?y.jsx(E.Fragment,{children:Jee(s,e)}):void 0}}};return y.jsx("div",{className:["prose prose-sm dark:prose-invert max-w-none min-w-0 break-words","prose-p:my-1 prose-headings:mt-3 prose-headings:mb-1","prose-pre:my-2 prose-pre:bg-muted prose-pre:text-foreground prose-pre:border prose-pre:border-border","prose-code:bg-muted prose-code:text-foreground prose-code:rounded-sm prose-code:px-1 prose-code:py-px prose-code:font-normal","prose-code:before:content-none prose-code:after:content-none","prose-a:text-primary prose-a:underline prose-a:underline-offset-2","prose-blockquote:border-muted-foreground/40 prose-blockquote:text-muted-foreground prose-blockquote:not-italic","prose-hr:border-border","prose-strong:text-foreground prose-headings:text-foreground"].join(" "),children:Gee(t,n)})}const Xee=E.lazy(()=>hD(()=>import("./reaction-picker-emoji-Kh7emgFa.js"),[]));function hU({roomId:r,eventId:e}){const[t,n]=E.useState(!1),i=me.safeGet(),o=async s=>{n(!1),i&&await i.sendEvent(r,"m.reaction",{"m.relates_to":{rel_type:"m.annotation",event_id:e,key:s}})};return y.jsxs(kL,{open:t,onOpenChange:n,children:[y.jsx(IL,{asChild:!0,children:y.jsx("button",{type:"button","aria-label":"add reaction",className:"inline-flex items-center rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:y.jsx(fK,{className:"size-4"})})}),y.jsx(xL,{align:"start",className:"w-auto p-0",children:y.jsx(E.Suspense,{fallback:y.jsx("div",{className:"p-3 text-xs",children:"Loading…"}),children:t&&y.jsx(Xee,{onPick:o})})})]})}function Qee({roomId:r,eventId:e,reactions:t}){const n=me.safeGet();if(t.size===0)return null;const i=async(o,s)=>{if(n){if(s.mine&&s.myEventId){await n.redactEvent(r,s.myEventId);return}await n.sendEvent(r,"m.reaction",{"m.relates_to":{rel_type:"m.annotation",event_id:e,key:o}})}};return y.jsxs("div",{"data-testid":"reactions-row",className:"mt-1 flex flex-wrap items-center gap-1",children:[Array.from(t.entries()).map(([o,s])=>y.jsxs("button",{type:"button","aria-label":`${o} ${s.count}`,onClick:()=>void i(o,s),className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs ${s.mine?"border-primary/60 bg-primary/10 text-primary":"border-border bg-muted/40 text-foreground hover:bg-muted"}`,children:[y.jsx("span",{children:o}),y.jsx("span",{className:"tabular-nums",children:s.count})]},o)),y.jsx("span",{className:"inline-flex items-center rounded-full border border-border bg-muted/40 px-1.5 py-0.5 hover:bg-muted",children:y.jsx(hU,{roomId:r,eventId:e})})]})}function Zee({userId:r}){const{presence:e}=ML(r);return y.jsx(qw,{userId:r,size:"sm",presence:e})}function ete({userId:r,roomId:e}){const t=Vo(r,e);return y.jsxs("span",{className:"rounded-sm bg-primary/15 px-1 font-medium",style:{color:zc(r)},title:r,children:["@",t]})}function tte({event:r}){const e=r.getContent(),t=r.getSender()??"?",n=r.getRoomId()??"",i=Vo(t,n),o=e.format==="org.matrix.custom.html"&&typeof e.formatted_body=="string"&&e.formatted_body.length>0;return e.msgtype!=="m.text"&&e.msgtype!=="m.notice"?null:y.jsxs("div",{className:"flex items-baseline gap-1.5 text-sm leading-5",children:[y.jsx("span",{className:"shrink-0 font-semibold",style:{color:zc(t)},children:i}),o?y.jsx("div",{className:"line-clamp-2 min-w-0 flex-1 text-foreground/80",children:y.jsx(fU,{html:e.formatted_body,roomId:n})}):y.jsx("span",{className:"line-clamp-2 min-w-0 flex-1 text-foreground/80",children:e.body??""})]})}function rte({event:r,onReplyInThread:e,onViewThread:t,disableThreadAffordances:n}){const i=r.getContent(),o=r.getSender()??"?",s=i.body??"",a=r.getId()??"",l=r.getRoomId()??"",c=Vo(o,l),u=i.format==="org.matrix.custom.html"&&typeof i.formatted_body=="string"&&i.formatted_body.length>0,{events:d,totalCount:f}=FL(l,n?"":a),p=zQ(l,a);return i.msgtype!=="m.text"&&i.msgtype!=="m.notice"?null:y.jsxs("div",{className:"group relative flex gap-2 py-1.5 hover:bg-muted/30",children:[y.jsx("div",{className:"mt-0.5 shrink-0",children:y.jsx(Zee,{userId:o})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("span",{className:"font-semibold text-sm leading-6",style:{color:zc(o)},title:o,children:c}),u?y.jsx(fU,{html:i.formatted_body,roomId:l}):y.jsx("p",{className:"min-w-0 whitespace-pre-wrap break-words leading-6 text-foreground text-sm",children:lL(s).map((h,m)=>h.userId?y.jsx(ete,{userId:h.userId,roomId:l},m):y.jsx("span",{children:h.text},m))}),y.jsx(Qee,{roomId:l,eventId:a,reactions:p}),!n&&f>0&&y.jsxs("div",{className:"mt-2 pl-3 border-l-2 border-muted-foreground/25 space-y-1",children:[f>3&&y.jsxs("button",{type:"button",onClick:()=>t==null?void 0:t(a),className:"text-xs text-primary hover:underline block",children:["View thread (",f," events)"]}),d.map(h=>y.jsx(tte,{event:h},h.getId()))]}),!n&&y.jsx("button",{type:"button","aria-label":"Reply in thread",onClick:()=>e==null?void 0:e(a),className:"mt-1 text-xs text-muted-foreground hover:text-foreground hover:underline",children:"Reply in thread"})]}),y.jsx("div",{className:"pointer-events-none absolute -top-3 right-2 z-10 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100",children:y.jsxs("div",{className:"flex items-center gap-1.5 rounded-md border border-border bg-background px-1.5 py-1 shadow-sm",children:[y.jsx(hU,{roomId:l,eventId:a}),!n&&y.jsx("button",{type:"button","aria-label":"Reply",onClick:()=>e==null?void 0:e(a),className:"inline-flex items-center rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:y.jsx(FP,{className:"size-4"})})]})})]})}function C_({event:r,onReplyInThread:e,onViewThread:t,disableThreadAffordances:n}){if(r.getType()==="m.room.message")return y.jsx(rte,{event:r,onReplyInThread:e,onViewThread:t,disableThreadAffordances:n});if(r.getType()===kc.Request)return y.jsx(PQ,{event:r});if(r.getType()===kc.Response)return null;if(r.getType()==="eco.zoon.session_reset")return y.jsxs("div",{className:"flex items-center gap-2 py-3 text-xs uppercase tracking-wider text-muted-foreground",children:[y.jsx("div",{className:"h-px flex-1 bg-border"}),y.jsx("span",{children:"new session"}),y.jsx("div",{className:"h-px flex-1 bg-border"})]});if(kQ(r)){const i=IQ(r);return i?y.jsx(DQ,{decoded:i,sender:r.getSender()??"?",roomId:r.getRoomId()??"",ts:r.getTs()}):null}return null}function pU({loading:r,hasMore:e,onClick:t}){return!e&&!r?null:y.jsx("div",{className:"flex justify-center py-2",children:y.jsxs("button",{type:"button",onClick:t,disabled:r||!e,className:"flex items-center gap-1.5 rounded-md px-3 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[r&&y.jsx(Lv,{className:"h-3 w-3 animate-spin"}),r?"Loading…":"Load more"]})})}const rx=5;function nte(){return y.jsxs("div",{className:"flex gap-2 py-1.5","aria-busy":"true","aria-label":"Loading thread parent",children:[y.jsx("div",{className:"mt-0.5 h-7 w-7 shrink-0 rounded-full bg-muted animate-pulse"}),y.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[y.jsx("div",{className:"h-3 w-24 rounded bg-muted animate-pulse"}),y.jsx("div",{className:"h-3 w-3/4 rounded bg-muted animate-pulse"})]})]})}function ite({roomId:r,rootEventId:e,onBack:t}){const{root:n,rootPending:i,events:o,totalCount:s}=dQ(r,e),{loadMore:a,loading:l}=wQ(r,e),c=o.length<s,u=E.useRef(null),d=E.useRef(!0),f=E.useRef(null);function p(){const h=u.current;h&&(d.current=h.scrollHeight-h.scrollTop-h.clientHeight<50)}return E.useEffect(()=>{const h=u.current;!h||!d.current||(h.scrollTop=h.scrollHeight)},[o]),E.useEffect(()=>{const h=`${r}:${e}`;f.current!==h&&(o.length===0&&i||(c&&o.length<rx?(f.current=h,a()):(!c||o.length>=rx)&&(f.current=h)))},[r,e,c,o.length,i,a]),y.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[y.jsxs("header",{className:"flex items-center gap-2 border-b border-border px-3 py-2 shrink-0",children:[y.jsxs("button",{type:"button",onClick:t,"aria-label":"Back to room",className:"flex items-center gap-1 rounded px-2 py-1 text-sm text-muted-foreground hover:bg-muted hover:text-foreground",children:[y.jsx(UB,{className:"h-4 w-4"}),"Back"]}),y.jsxs("span",{className:"text-sm font-medium",children:["Thread ",s>0?`(${s} ${s===1?"event":"events"})`:""]})]}),y.jsxs("div",{ref:u,onScroll:p,className:"flex-1 min-h-0 overflow-y-auto",children:[o.length>0&&y.jsx(pU,{loading:l,hasMore:c,onClick:a}),y.jsxs("ol",{className:"flex flex-col gap-0.5 px-4 py-3",children:[y.jsx("li",{children:n?y.jsx(C_,{event:n,disableThreadAffordances:!0}):i?y.jsx(nte,{}):y.jsx("div",{className:"text-sm text-muted-foreground italic py-2",children:"Thread root unavailable."})}),o.map(h=>y.jsx("li",{children:y.jsx(C_,{event:h,disableThreadAffordances:!0})},h.getId()??`${h.getType()}-${h.getTs()}`))]})]})]})}function Ny(r){const e=me.safeGet(),t=e==null?void 0:e.getRoom(r);return t?t.getLiveTimeline().getPaginationToken(Ge.Backward)!==null:!1}function ote(r,e=50){const[t,n]=E.useState(()=>({loading:!1,hasMore:Ny(r)}));return E.useEffect(()=>{n(l=>({...l,hasMore:Ny(r)}));const o=me.safeGet(),s=o==null?void 0:o.getRoom(r);if(!o||!s)return;const a=()=>{n(l=>{const c=Ny(r);return c===l.hasMore?l:{...l,hasMore:c}})};return s.on(fe.Timeline,a),()=>{s.off(fe.Timeline,a)}},[r]),{loadMore:E.useCallback(async()=>{if(t.loading||!t.hasMore)return;const o=me.safeGet(),s=o==null?void 0:o.getRoom(r);if(!(!o||!s)){n(a=>({...a,loading:!0}));try{const a=s.getLiveTimeline(),l=await o.paginateEventTimeline(a,{backwards:!0,limit:e});n({loading:!1,hasMore:l})}catch(a){console.warn(`[useLoadMoreHistory] paginate(${r}) failed:`,a),n({loading:!1,hasMore:!1})}}},[r,e,t.loading,t.hasMore]),loading:t.loading,hasMore:t.hasMore}}function ste(){return y.jsxs("div",{className:"flex gap-2 py-1.5","aria-busy":"true","aria-label":"Loading thread parent",children:[y.jsx("div",{className:"mt-0.5 h-7 w-7 shrink-0 rounded-full bg-muted animate-pulse"}),y.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[y.jsx("div",{className:"h-3 w-24 rounded bg-muted animate-pulse"}),y.jsx("div",{className:"h-3 w-3/4 rounded bg-muted animate-pulse"})]})]})}function ate({events:r,pendingRootIds:e,onReplyInThread:t,onViewThread:n}){return y.jsxs("ol",{className:"flex flex-col gap-0.5 px-4 py-3",children:[e==null?void 0:e.map(i=>y.jsx("li",{children:y.jsx(ste,{})},`skeleton-${i}`)),r.map(i=>y.jsx("li",{children:y.jsx(C_,{event:i,onReplyInThread:t,onViewThread:n})},i.getId()??`${i.getType()}-${i.getTs()}`))]})}const nx=5;function lte({roomId:r,onReplyInThread:e,onViewThread:t}){const{events:n,pendingRootIds:i}=jL(r),{loadMore:o,loading:s,hasMore:a}=ote(r),l=E.useRef(null),c=E.useRef(!0),u=E.useRef(null);function d(){const f=l.current;f&&(c.current=f.scrollHeight-f.scrollTop-f.clientHeight<50)}return E.useEffect(()=>{const f=l.current;!f||!c.current||(f.scrollTop=f.scrollHeight)},[n]),E.useEffect(()=>{u.current!==r&&(a&&n.length<nx?(u.current=r,o()):(!a||n.length>=nx)&&(u.current=r))},[r,a,n.length,o]),y.jsxs("div",{ref:l,onScroll:d,className:"h-full overflow-y-auto",children:[n.length>0&&y.jsx(pU,{loading:s,hasMore:a,onClick:o}),y.jsx(ate,{events:n,pendingRootIds:i,onReplyInThread:e,onViewThread:t})]})}function cte(r){const t=r.getLiveTimeline().getEvents();for(let n=t.length-1;n>=0;n--){const i=t[n];if(i.getType()==="m.room.message")return i}return t[t.length-1]??null}function ute(r){E.useEffect(()=>{const e=me.safeGet(),t=e==null?void 0:e.getRoom(r);if(!e||!t)return;let n=null;const i=()=>{const s=cte(t);if(!s)return;const a=s.getId()??null;a!==null&&a===n||(n=a,e.sendReadReceipt(s).catch(()=>{}))};i();const o=()=>i();return t.on(fe.Timeline,o),()=>{t.off(fe.Timeline,o)}},[r])}const Ly=[];function ix(r){const e=me.safeGet();if(!e)return Ly;const t=e.getUserId()??"",n=e.getRoom(r);if(!n)return Ly;const i=n.currentState.getMembers().filter(o=>o.typing&&o.userId!==t).map(o=>o.userId);return i.length===0?Ly:i}function dte(r){const[e,t]=E.useState(()=>ix(r));return E.useEffect(()=>{const n=me.safeGet();if(!n)return;const i=()=>t(ix(r));return n.on(Ar.Typing,i),()=>{n.off(Ar.Typing,i)}},[r]),e}function fte(){const{roomId:r}=wF(),[e,t]=DP(),n=e.get("thread"),i=dte(r??"");ute(r??"");function o(a){t({thread:a})}function s(){t({})}return r?y.jsxs("article",{className:"flex h-full min-h-0 flex-col",children:[y.jsx("div",{className:"min-h-0 flex-1",children:n?y.jsx(ite,{roomId:r,rootEventId:n,onBack:s}):y.jsx(lte,{roomId:r,onReplyInThread:o,onViewThread:o})}),y.jsx(EQ,{typingUserIds:i,roomId:r}),y.jsx(bQ,{roomId:r,threadRootEventId:n,onExitThread:s})]}):y.jsx("div",{children:"No room selected"})}function hte(){return E.useSyncExternalStore(r=>me.subscribe(r),()=>me.safeGet()?"logged-in":"logged-out",()=>"logged-out")}function pte({config:r,initialRoute:e}){const[t,n]=E.useState(!1);return E.useEffect(()=>{if(!me.restoreFromStorage()){n(!0);return}let o=!1;return(async()=>{var s;try{await me.get().whoami()}catch(a){const l=a,c=l.errcode??((s=l.data)==null?void 0:s.errcode);(c==="M_UNKNOWN_TOKEN"||c==="M_MISSING_TOKEN"||c==="M_FORBIDDEN"||l.httpStatus===401)&&me.reset()}o||n(!0)})(),()=>{o=!0}},[]),t?e?y.jsxs(OR,{children:[y.jsx(jF,{initialEntries:[e],children:y.jsx(ox,{config:r})}),y.jsx(zT,{})]}):y.jsxs(OR,{children:[y.jsx(zF,{children:y.jsx(ox,{config:r})}),y.jsx(zT,{})]}):y.jsx("div",{role:"status",children:"Loading…"})}function ox({config:r}){const e=hte(),t=Pc();return E.useEffect(()=>{e==="logged-out"&&window.location.pathname!=="/auth/callback"&&t("/login",{replace:!0})},[e,t]),y.jsxs(BF,{children:[y.jsxs(ml,{path:"/",element:e==="logged-in"?y.jsx(iQ,{}):y.jsx(Mp,{to:"/login",replace:!0}),children:[y.jsx(ml,{index:!0,element:y.jsx(mJ,{})}),y.jsx(ml,{path:"room/:roomId",element:y.jsx(fte,{})})]}),y.jsx(ml,{path:"/login",element:e==="logged-in"?y.jsx(Mp,{to:"/",replace:!0}):y.jsx(YY,{homeserverUrl:r.homeserverUrl,defaultIdpLabel:r.defaultIdpLabel??null})}),y.jsx(ml,{path:"/auth/callback",element:y.jsx(GY,{homeserverUrl:r.homeserverUrl})})]})}const vte=E.createContext({theme:"system",setTheme:()=>null}),sx="zoon-ui-theme";function mte({children:r,defaultTheme:e="system"}){const[t,n]=E.useState(()=>localStorage.getItem(sx)??e);E.useEffect(()=>{const o=window.document.documentElement;if(o.classList.remove("light","dark"),t==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(s)}else o.classList.add(t)},[t]);const i=o=>{localStorage.setItem(sx,o),n(o)};return y.jsx(vte.Provider,{value:{theme:t,setTheme:i},children:r})}async function gte(r){var e;if((e=r.runtimeConfig)!=null&&e.homeserver_url)return r.runtimeConfig.homeserver_url;if(r.buildtimeUrl)return r.buildtimeUrl;throw new Error("No homeserver URL could be resolved")}async function yte(){try{const r=await fetch("/config.json",{cache:"no-store"});if(!r.ok)return null;const e=await r.json(),t={};return typeof e.homeserver_url=="string"&&(t.homeserver_url=e.homeserver_url),typeof e.default_idp_label=="string"&&(t.default_idp_label=e.default_idp_label),t}catch{return null}}const Ste=null;async function bte(){const r=await yte(),t={homeserverUrl:await gte({runtimeConfig:r,buildtimeUrl:Ste}),defaultIdpLabel:(r==null?void 0:r.default_idp_label)??null};bP(document.getElementById("root")).render(y.jsx(E.StrictMode,{children:y.jsx(mte,{defaultTheme:"system",children:y.jsx(pte,{config:t})})}))}bte().catch(r=>{console.error("Bootstrap failed:",r),document.body.innerHTML=`<pre>Bootstrap failed: ${String((r==null?void 0:r.message)??r)}</pre>`});export{pe as $,s8 as A,nv as B,Yt as C,kw as D,V as E,ko as F,ak as G,Aw as H,ot as I,qt as J,Be as K,Cte as L,Z as M,cr as N,Dt as O,rs as P,bl as Q,be as R,Vi as S,en as T,od as U,fa as V,mc as W,Ef as X,E as Y,y as Z,v as _,_ as a,xte as b,wi as c,Dr as d,vm as e,Se as f,LD as g,wo as h,YD as i,Tt as j,Bc as k,S as l,Hs as m,Ow as n,xi as o,bm as p,Gs as q,hr as r,As as s,Ot as t,r8 as u,Qr as v,sN as w,Iw as x,Ei as y,Cw as z};