@element-hq/element-call-embedded 0.9.0-release-test.8 → 0.9.0-release-test.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{index-DXFW22xn.js → index-BEBk3_8N.js} +2 -2
- package/dist/assets/{index-DXFW22xn.js.map → index-BEBk3_8N.js.map} +1 -1
- package/dist/assets/{index-CZZJETQc.js → index-CdFYKKU5.js} +3 -3
- package/dist/assets/{index-CZZJETQc.js.map → index-CdFYKKU5.js.map} +1 -1
- package/dist/assets/{index-DdfFhWLD.js → index-OfDiWbJe.js} +6 -6
- package/dist/assets/{index-DdfFhWLD.js.map → index-OfDiWbJe.js.map} +1 -1
- package/dist/assets/{matrix-sdk-crypto-wasm-DGXDpLaN.js → matrix-sdk-crypto-wasm-D9e1T4vy.js} +3 -3
- package/dist/assets/{matrix-sdk-crypto-wasm-DGXDpLaN.js.map → matrix-sdk-crypto-wasm-D9e1T4vy.js.map} +1 -1
- package/dist/assets/pako.esm-Bt8vjcgE.js +2 -0
- package/dist/assets/{pako.esm-BMdhWMX1.js.map → pako.esm-Bt8vjcgE.js.map} +1 -1
- package/dist/assets/polyfill-force-Baj25WyX.js +2 -0
- package/dist/assets/{polyfill-force-CajV37WF.js.map → polyfill-force-Baj25WyX.js.map} +1 -1
- package/dist/assets/polyfill-force-Dn71dwtm.js +2 -0
- package/dist/assets/{polyfill-force-DQyUIgBV.js.map → polyfill-force-Dn71dwtm.js.map} +1 -1
- package/dist/assets/spa-CCVn2ay1.js +2 -0
- package/dist/assets/{spa-DFPpa8E_.js.map → spa-CCVn2ay1.js.map} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/pako.esm-BMdhWMX1.js +0 -2
- package/dist/assets/polyfill-force-CajV37WF.js +0 -2
- package/dist/assets/polyfill-force-DQyUIgBV.js +0 -2
- package/dist/assets/spa-DFPpa8E_.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-
|
|
2
|
-
function Qne(n,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in n)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(n,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"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();var HGe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Wo(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function VGe(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function r(){return this instanceof r?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(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var _T={exports:{}},Em={},bT={exports:{}},_t={};/**
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-CdFYKKU5.js","./matrix-sdk-crypto-wasm-D9e1T4vy.js","./polyfill-force-Baj25WyX.js","./index-BEBk3_8N.js","./polyfill-force-Dn71dwtm.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
try{let n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new n.Error().stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="1b5a8c91-94d5-4739-99e7-61516c70424d",n._sentryDebugIdIdentifier="sentry-dbid-1b5a8c91-94d5-4739-99e7-61516c70424d")}catch{}function Qne(n,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in n)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}{let n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};n.SENTRY_RELEASE={id:"embedded-v0.9.0-release-test.9"}}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();var HGe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Wo(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function VGe(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function r(){return this instanceof r?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(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var _T={exports:{}},Em={},bT={exports:{}},_t={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
5
5
|
*
|
|
@@ -30,7 +30,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
30
30
|
`)+`\r
|
|
31
31
|
`},NT}var S5;function hse(){if(S5)return yo;S5=1;var n=use(),e=dse(),t=_P();return yo.grammar=t,yo.write=e,yo.parse=n.parse,yo.parseParams=n.parseParams,yo.parseFmtpConfig=n.parseFmtpConfig,yo.parsePayloads=n.parsePayloads,yo.parseRemoteCandidates=n.parseRemoteCandidates,yo.parseImageAttributes=n.parseImageAttributes,yo.parseSimulcastStreamList=n.parseSimulcastStreamList,yo}var YR=hse();function bP(n,e){if(typeof n.toBase64=="function")return n.toBase64(e);let t=btoa(n.reduce((r,i)=>r+String.fromCharCode(i),""));return e.omitPadding&&(t=t.replace(/={1,2}$/,"")),e.alphabet==="base64url"&&(t=t.replace(/\+/g,"-").replace(/\//g,"_")),t}function y_(n){return bP(n,{alphabet:"base64",omitPadding:!1})}function R$(n){return bP(n,{alphabet:"base64",omitPadding:!0})}function fw(n){return bP(n,{alphabet:"base64url",omitPadding:!0})}function fse(n,e){return typeof Uint8Array.fromBase64=="function"?Uint8Array.fromBase64(n,e):Uint8Array.from(atob(n),t=>t.charCodeAt(0))}function _f(n){return fse(n.replace(/-/g,"+").replace(/_/g,"/"),{alphabet:"base64",lastChunkHandling:"loose"})}const pse="abcdefghijklmnopqrstuvwxyz",mse="ABCDEFGHIJKLMNOPQRSTUVWXYZ",gse="0123456789";function k$(n){const e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),fw(e)}function Es(n){return vse(n,mse+pse+gse)}function vse(n,e){if(e.length<2||e.length>256)throw new Error("Character set must be between 2 and 256 characters long");if(n<1||n>32768)throw new Error("Requested random string length must be between 1 and 32768");const t=256-256%e.length,r=new Uint8Array(Math.floor(n*1.3));let i=r.length;const s=[];for(;s.length<n;){i===r.length&&(globalThis.crypto.getRandomValues(r),i=0);const o=r[i++];o<t&&s.push(e[o%e.length])}return s.join("")}const pl="org.matrix.msc3077.sdp_stream_metadata";var Qt=(n=>(n.Usermedia="m.usermedia",n.Screenshare="m.screenshare",n))(Qt||{});let id=null,XR=0;const yse=()=>(id===null&&(id=new AudioContext),XR++,id),_se=()=>{XR--,XR===0&&(id==null||id.close(),id=null)},bse=200,JR=-60,Sse=8;var x$=(n=>(n.NewStream="new_stream",n.MuteStateChanged="mute_state_changed",n.LocalVolumeChanged="local_volume_changed",n.VolumeChanged="volume_changed",n.ConnectedChanged="connected_changed",n.Speaking="speaking",n.Disposed="disposed",n))(x$||{});class hc extends Yn{constructor(e){super(),this.localVolume=1,this.measuringVolumeActivity=!1,this.speakingThreshold=JR,this.speaking=!1,this._disposed=!1,this._connected=!1,this.onAddTrack=()=>{this.emit("new_stream",this.stream)},this.onCallState=t=>{t===_s.Connected?this.connected=!0:t===_s.Connecting&&(this.connected=!1)},this.volumeLooper=()=>{if(!this.analyser||!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let t=-1/0;for(const i of this.frequencyBinCount)i>t&&(t=i);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(t),this.emit("volume_changed",t);let r=!1;for(const i of this.speakingVolumeSamples)if(i>this.speakingThreshold){r=!0;break}this.speaking!==r&&(this.speaking=r,this.emit("speaking",this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,bse)},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(Sse).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(Bi.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit("connected_changed",this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){if(t===e)return;const r=this.measuringVolumeActivity;e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?(this.initVolumeMeasuring(),r&&this.measureVolumeActivity(!0)):this.measureVolumeActivity(!1),this.emit("new_stream",this.stream)}initVolumeMeasuring(){if(!this.hasAudioTrack)return;this.audioContext||(this.audioContext=yse()),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1,this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}getMember(){const e=this.client.getRoom(this.roomId);return(e==null?void 0:e.getMember(this.userId))??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("mute_state_changed",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("volume_changed",-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){const e=this.client.getMediaHandler(),t=this.stream.clone();return M.log(`CallFeed clone() cloning stream (originalStreamId=${this.stream.id}, newStreamId${t.id})`),this.purpose===Qt.Usermedia?e.userMediaStreams.push(t):e.screensharingStreams.push(t),new hc({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.removeEventListener("addtrack",this.onAddTrack),(t=this.call)==null||t.removeListener(Bi.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,_se()),this._disposed=!0,this.emit("disposed")}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit("local_volume_changed",e)}}const wse=3e3;var ZR=(n=>(n.Incoming="Call.incoming",n))(ZR||{});class Ese{constructor(e){this.nextSeqByCall=new Map,this.toDeviceEventBuffers=new Map,this.onSync=()=>{const t=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then(()=>this.evaluateEventBuffer(t)):this.eventBufferPromiseChain=this.evaluateEventBuffer(t)},this.onRoomTimeline=t=>{this.callEventBuffer.push(t)},this.onToDeviceEvent=t=>{const r=t.getContent();if(!r.call_id){this.callEventBuffer.push(t);return}if(this.nextSeqByCall.has(r.call_id)||this.nextSeqByCall.set(r.call_id,0),r.seq===void 0){this.callEventBuffer.push(t);return}const i=this.nextSeqByCall.get(r.call_id)||0;if(r.seq!==i){this.toDeviceEventBuffers.has(r.call_id)||this.toDeviceEventBuffers.set(r.call_id,[]);const s=this.toDeviceEventBuffers.get(r.call_id),o=s.findIndex(a=>a.getContent().seq>r.seq);o===-1?s.push(t):s.splice(o,0,t)}else{const s=r.call_id;this.callEventBuffer.push(t),this.nextSeqByCall.set(s,r.seq+1);const o=this.toDeviceEventBuffers.get(s);let a=o&&o.shift();for(;a&&a.getContent().seq===this.nextSeqByCall.get(s);)this.callEventBuffer.push(a),this.nextSeqByCall.set(s,a.getContent().seq+1),a=o.shift()}},this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(Ge.Sync,this.onSync),this.client.on(Xe.Timeline,this.onRoomTimeline),this.client.on(Ge.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(Ge.Sync,this.onSync),this.client.removeListener(Xe.Timeline,this.onRoomTimeline),this.client.removeListener(Ge.ToDeviceEvent,this.onToDeviceEvent)}async evaluateEventBuffer(e){await Promise.all(e.map(i=>this.client.decryptEventIfNeeded(i)));const t=e.filter(i=>{const s=i.getType();return s.startsWith("m.call.")||s.startsWith("org.matrix.call.")}),r=new Set;for(const i of t){const s=i.getType();(s===ie.CallAnswer||s===ie.CallHangup)&&r.add(i.getContent().call_id)}for(const i of t){const s=i.getType(),o=i.getContent().call_id;if(!(s===ie.CallInvite&&r.has(o)))try{await this.handleCallEvent(i)}catch(a){M.error("CallEventHandler evaluateEventBuffer() caught exception handling call event",a)}}}async handleCallEvent(e){var h,p,m;this.client.emit(Ge.ReceivedVoipEvent,e);const t=e.getContent(),r=e.getRoomId()||((p=(h=this.client.groupCallEventHandler.getGroupCallById(t.conf_id))==null?void 0:h.room)==null?void 0:p.roomId),i=t.conf_id,s=e.getType(),o=e.getSender();let a=t.call_id?this.calls.get(t.call_id):void 0,c,l;if(i){if(l=this.client.groupCallEventHandler.getGroupCallById(i),!l){M.warn(`CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=${i}, type=${s})`);return}if(c=t.device_id,!c){M.warn(`CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=${o})`),l.emit(Ob.Error,new O$(o));return}if(t.dest_session_id!==this.client.getSessionId()){M.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring");return}}const u=o===this.client.credentials.userId&&(c===void 0||c===this.client.getDeviceId());if(r){if(s===ie.CallInvite){if(u||e.getLocalAge()>t.lifetime-wse||a&&a.state===_s.Ended||(a&&M.warn(`CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=${t.call_id})`),t.invitee&&t.invitee!==this.client.getUserId()))return;const v=(this.client.getTurnServersExpiry()??0)-Date.now();if(M.info("CallEventHandler handleCallEvent() current turn creds expire in "+v+" ms"),a=av(this.client,r,{forceTURN:this.client.forceTURN,opponentDeviceId:c,groupCallId:i,opponentSessionId:t.sender_session_id})??void 0,!a){M.log(`CallEventHandler handleCallEvent() this client does not support WebRTC (callId=${t.call_id})`);return}a.callId=t.call_id;const g=l==null?void 0:l.getGroupCallStats();g&&a.initStats(g);try{await a.initWithInvite(e)}catch(b){b instanceof rc&&(b.code===A$.UnknownDevice?l==null||l.emit(Ob.Error,b):M.error(b))}if(this.calls.set(a.callId,a),this.candidateEventsByCall.get(a.callId))for(const b of this.candidateEventsByCall.get(a.callId))a.onRemoteIceCandidatesReceived(b);let S;for(const b of this.calls.values()){const R=[_s.WaitLocalMedia,_s.CreateOffer,_s.InviteSent].includes(b.state);if(a.roomId===b.roomId&&b.direction===M$.Outbound&&((m=a.getOpponentMember())==null?void 0:m.userId)===b.invitee&&R){S=b;break}}S?S.callId>a.callId?(M.log(`CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=${a.callId}, outgoingId=${S.callId})`),S.replacedBy(a)):(M.log(`CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=${a.callId}, outgoingId=${S.callId})`),a.hangup(nc.Replaced,!0)):this.client.emit("Call.incoming",a);return}else if(s===ie.CallCandidates){if(u)return;a?a.onRemoteIceCandidatesReceived(e):(this.candidateEventsByCall.has(t.call_id)||this.candidateEventsByCall.set(t.call_id,[]),this.candidateEventsByCall.get(t.call_id).push(e));return}else if([ie.CallHangup,ie.CallReject].includes(s)){a?a.state!==_s.Ended&&(s===ie.CallHangup?a.onHangupReceived(t):a.onRejectReceived(t),a.state===_s.Ended&&this.calls.delete(t.call_id)):(a=av(this.client,r,{opponentDeviceId:c,opponentSessionId:t.sender_session_id})??void 0,a&&(a.callId=t.call_id,a.initWithHangup(e),this.calls.set(t.call_id,a)));return}if(!a||!a.hasPeerConnection){M.info(`CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=${s})`);return}if(e.getContent().party_id!==a.ourPartyId)switch(s){case ie.CallAnswer:u?a.state===_s.Ringing&&a.onAnsweredElsewhere(t):a.onAnswerReceived(e);break;case ie.CallSelectAnswer:a.onSelectAnswerReceived(e);break;case ie.CallNegotiate:a.onNegotiateReceived(e);break;case ie.CallAssertedIdentity:case ie.CallAssertedIdentityPrefix:a.onAssertedIdentityReceived(e);break;case ie.CallSDPStreamMetadataChanged:case ie.CallSDPStreamMetadataChangedPrefix:a.onSDPStreamMetadataChangedReceived(e);break}}}}var QR=(n=>(n.Incoming="GroupCall.incoming",n.Outgoing="GroupCall.outgoing",n.Ended="GroupCall.ended",n.Participants="GroupCall.participants",n))(QR||{});class Cse{constructor(e){this.client=e,this.groupCalls=new Map,this.roomDeferreds=new Map,this.onRoomsChanged=t=>{this.createGroupCallForRoom(t)},this.onRoomStateChanged=(t,r)=>{if(t.getType()===ie.GroupCallPrefix){const s=t.getStateKey(),o=t.getContent(),a=this.groupCalls.get(r.roomId);!a&&!o["m.terminated"]&&!t.isRedacted()?this.createGroupCallFromRoomStateEvent(t):a&&a.groupCallId===s?o["m.terminated"]||t.isRedacted()?a.terminate(!1):o["m.type"]!==a.type&&M.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=${r.roomId})`):a&&a.groupCallId!==s&&M.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=${r.roomId})`)}}}async start(){this.client.getSyncState()!==Pr.Syncing&&(M.debug("GroupCallEventHandler start() waiting for client to start syncing"),await new Promise(t=>{const r=()=>{if(this.client.getSyncState()===Pr.Syncing)return this.client.off(Ge.Sync,r),t()};this.client.on(Ge.Sync,r)}));const e=this.client.getRooms();for(const t of e)this.createGroupCallForRoom(t);this.client.on(Ge.Room,this.onRoomsChanged),this.client.on(It.Events,this.onRoomStateChanged)}stop(){this.client.removeListener(Ge.Room,this.onRoomsChanged),this.client.removeListener(It.Events,this.onRoomStateChanged)}getRoomDeferred(e){let t=this.roomDeferreds.get(e);if(t===void 0){let r;t={prom:new Promise(i=>{r=i})},t.resolve=r,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){const t=e.currentState.getStateEvents(ie.GroupCallPrefix),r=t.sort((i,s)=>s.getTs()-i.getTs());for(const i of r)if(!(i.getContent()["m.terminated"]||i.isRedacted())){M.debug(`GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=${i.getStateKey()}, ts=${i.getTs()}, roomId=${e.roomId}, numOfPossibleCalls=${t.length})`),this.createGroupCallFromRoomStateEvent(i);break}this.getRoomDeferred(e.roomId).resolve()}createGroupCallFromRoomStateEvent(e){const t=e.getRoomId(),r=e.getContent(),i=this.client.getRoom(t);if(!i){M.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=${t})`);return}const s=e.getStateKey(),o=r["m.type"];if(!Object.values(pw).includes(o)){M.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=${o}, roomId=${t})`);return}const a=r["m.intent"];if(!Object.values(SP).includes(a)){M.warn(`Received invalid group call intent (type=${o}, roomId=${t})`);return}const c=!!r["io.element.ptt"];let l;if(r!=null&&r.dataChannelsEnabled&&(r!=null&&r.dataChannelOptions)){const{ordered:h,maxPacketLifeTime:p,maxRetransmits:m,protocol:v}=r.dataChannelOptions;l={ordered:h,maxPacketLifeTime:p,maxRetransmits:m,protocol:v}}const u=new EP(this.client,i,o,c,a,s,(r==null?void 0:r.dataChannelsEnabled)||this.client.isVoipWithNoMediaAllowed,l,this.client.isVoipWithNoMediaAllowed,this.client.useLivekitForGroupCalls,r["io.element.livekit_service_url"]);return this.groupCalls.set(i.roomId,u),this.client.emit("GroupCall.incoming",u),u}}class Tse{constructor(){this.bandwidth={},this.bitrate={},this.packetLoss={},this.transport=[]}}class Ise{static buildBandwidthReport(e){const t=e.availableIncomingBitrate,r=e.availableOutgoingBitrate;return{download:t?Math.round(t/1e3):0,upload:r?Math.round(r/1e3):0}}}class Rse{static buildReport(e,t,r,i){const s=e==null?void 0:e.get(t.localCandidateId),o=e==null?void 0:e.get(t.remoteCandidateId);if(o&&s){const a=o.ip!==void 0?o.ip:o.address,c=o.port,l=`${a}:${c}`,u=s.ip!==void 0?s.ip:s.address,h=s.port,p=`${u}:${h}`,m=o.protocol;r.some(v=>v.ip===l&&v.type===m&&v.localIp===p)||r.push({ip:l,type:m,localIp:p,isFocus:i,localCandidateType:s.candidateType,remoteCandidateType:o.candidateType,networkType:s.networkType,rtt:t.currentRoundTripTime?t.currentRoundTripTime*1e3:NaN})}return r}}class kse{constructor(){this.ssrcToMid={local:new Map,remote:new Map}}findMidBySsrc(e,t){let r;return this.ssrcToMid[t].forEach((i,s)=>{if(i.find(o=>o==e)){r=s;return}}),r}parse(e,t){const r=YR.parse(e),i=new Map;r.media.forEach(s=>{var o;if(s.mid&&s.type==="video"||s.type==="audio"){const a=[];(o=s.ssrcs)==null||o.forEach(c=>{c.attribute==="cname"&&a.push(`${c.id}`)}),i.set(`${s.mid}`,a)}}),this.ssrcToMid[t]=i}getSsrcToMidMap(e){return this.ssrcToMid[e]}}class xse{constructor(e){this.pc=e}getLocalTracks(e){const t=r=>r!==null&&r.kind===e;return this.pc.getTransceivers().filter(r=>r.currentDirection==="sendonly"||r.currentDirection==="sendrecv").filter(r=>r.sender!==null).map(r=>r.sender).map(r=>r.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 r,i;const t=this.pc.getTransceivers().find(s=>s.mid===e);return(i=(r=t==null?void 0:t.sender)==null?void 0:r.track)==null?void 0:i.id}getRemoteTrackIdByMid(e){var r,i;const t=this.pc.getTransceivers().find(s=>s.mid===e);return(i=(r=t==null?void 0:t.receiver)==null?void 0:r.track)==null?void 0:i.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 Pse{constructor(e,t,r){this.trackId=e,this.type=t,this.kind=r,this.loss={packetsTotal:0,packetsLost:0,isDownloadStream:!1},this.bitrate={download:0,upload:0},this.resolution={width:-1,height:-1},this.audioConcealment={concealedAudio:0,totalAudioDuration:0},this.framerate=0,this.jitter=0,this.codec="",this.isAlive=!0,this.isMuted=!1,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 Lse{constructor(e,t){this.mediaSsrcHandler=e,this.mediaTrackHandler=t,this.track2stats=new Map}findTrack2Stats(e,t){let r;if(e.trackIdentifier)r=e.trackIdentifier;else if(e.mid)r=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid);else if(e.ssrc){if(!this.mediaSsrcHandler.findMidBySsrc(e.ssrc,t))return;r=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid)}if(!r)return;let i=this.track2stats.get(r);if(!i){const s=this.mediaTrackHandler.getTackById(r);if(s!==void 0){const o=s.kind==="audio"?s.kind:"video";i=new Pse(r,t,o),this.track2stats.set(r,i)}else return}return i}findLocalVideoTrackStats(e){if(this.mediaTrackHandler.getLocalTracks("video").length!==0)return this.findTrack2Stats(e,"local")}getTrack2stats(){return this.track2stats}findTransceiverByTrackId(e){return this.mediaTrackHandler.getTransceiverByTrackId(e)}}class Wu{static getNonNegativeValue(e){let t=e;return typeof t!="number"&&(t=Number(t)),isNaN(t)?0:Math.max(0,t)}}class ms{static buildFramerateResolution(e,t){const r={height:t.frameHeight,width:t.frameWidth},i=t.framesPerSecond;r.height&&r.width&&e.setResolution(r),e.setFramerate(Math.round(i||0))}static calculateSimulcastFramerate(e,t,r,i){let s=e.getFramerate();if(!s){if(r){const o=t.timestamp-r.timestamp;o>0&&t.framesSent&&(s=(t.framesSent-r.framesSent)/o*1e3)}if(!s)return}s=i?Math.round(s/i):0,e.setFramerate(s)}static buildCodec(e,t,r){const i=e==null?void 0:e.get(r.codecId);if(i){const s=i.mimeType.split("/")[1];s&&t.setCodec(s)}}static buildBitrateReceived(e,t,r){e.setBitrate({download:ms.calculateBitrate(t.bytesReceived,r.bytesReceived,t.timestamp,r.timestamp),upload:0})}static buildBitrateSend(e,t,r){e.setBitrate({download:0,upload:this.calculateBitrate(t.bytesSent,r.bytesSent,t.timestamp,r.timestamp)})}static buildPacketsLost(e,t,r){const i=t.type==="outbound-rtp"?"packetsSent":"packetsReceived";let s=t[i];(!s||s<0)&&(s=0);const o=Wu.getNonNegativeValue(r[i]),a=Math.max(0,s-o),c=Wu.getNonNegativeValue(t.packetsLost),l=Wu.getNonNegativeValue(r.packetsLost),u=Math.max(0,c-l);e.setLoss({packetsTotal:a+u,packetsLost:u,isDownloadStream:t.type!=="outbound-rtp"})}static calculateBitrate(e,t,r,i){const s=Wu.getNonNegativeValue(e),o=Wu.getNonNegativeValue(t),a=Math.max(0,s-o),c=r-i;let l=0;return c>0&&(l=Math.round(a*8/c)),l}static setTrackStatsState(e,t){var i;if(t===void 0){e.alive=!1;return}const r=e.getType()==="remote"?t.receiver.track:(i=t==null?void 0:t.sender)==null?void 0:i.track;if(r==null){e.alive=!1;return}if(r.readyState==="ended"){e.alive=!1;return}e.muted=r.muted,e.enabled=r.enabled,e.alive=!0}static buildTrackSummary(e){const t={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},r={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},i=e.filter(o=>o.getType()==="remote"),s=i.filter(o=>o.kind==="audio");return i.forEach(o=>{var c,l;const a=o.kind==="video"?t:r;a.count++,o.alive&&o.muted&&a.muted++,a.maxJitter<o.getJitter()&&(a.maxJitter=o.getJitter()),a.maxPacketLoss<o.getLoss().packetsLost&&(a.maxPacketLoss=o.getLoss().packetsLost),s.length>0&&(a.concealedAudio+=(c=o.getAudioConcealment())==null?void 0:c.concealedAudio,a.totalAudio+=(l=o.getAudioConcealment())==null?void 0:l.totalAudioDuration)}),{audioTrackSummary:r,videoTrackSummary:t}}static buildJitter(e,t){if(t.type!=="inbound-rtp")return;const r=t==null?void 0:t.jitter;if(r!==void 0){const i=Wu.getNonNegativeValue(r);e.setJitter(Math.round(i*1e3))}else e.setJitter(-1)}static buildAudioConcealment(e,t){if(t.type!=="inbound-rtp")return;const i=1e3*(t==null?void 0:t.totalSamplesDuration)/(t==null?void 0:t.totalSamplesReceived)*(t==null?void 0:t.concealedSamples),s=1e3*(t==null?void 0:t.totalSamplesDuration);e.setAudioConcealment(i,s)}}class Rg{static build(e){const t={},r={download:0,upload:0},i={download:0,upload:0};let s=0,o=0;const a={local:new Map,remote:new Map},c={local:new Map,remote:new Map},l={local:new Map,remote:new Map},u=new Map,h=new Map;let p=0,m=0,v=0,g=0,S=0,b=0;for(const[R,k]of e){const I=k.getLoss(),T=I.isDownloadStream?"download":"upload";if(r[T]+=I.packetsTotal,i[T]+=I.packetsLost,s+=k.getBitrate().download,o+=k.getBitrate().upload,k.kind==="audio"){const C=k.getAudioConcealment();S+=C.concealedAudio,b+=C.totalAudioDuration,p+=k.getBitrate().download,m+=k.getBitrate().upload}else v+=k.getBitrate().download,g+=k.getBitrate().upload;a[k.getType()].set(R,k.getResolution()),c[k.getType()].set(R,k.getFramerate()),l[k.getType()].set(R,k.getCodec()),k.getType()==="remote"&&(u.set(R,k.getJitter()),k.kind==="audio"&&h.set(R,k.getAudioConcealment())),k.resetBitrate()}return t.bitrate={upload:o,download:s},t.bitrate.audio={upload:m,download:p},t.bitrate.video={upload:g,download:v},t.packetLoss={total:Rg.calculatePacketLoss(i.download+i.upload,r.download+r.upload),download:Rg.calculatePacketLoss(i.download,r.download),upload:Rg.calculatePacketLoss(i.upload,r.upload)},t.audioConcealment=h,t.totalAudioConcealment={concealedAudio:S,totalAudioDuration:b},t.framerate=c,t.resolution=a,t.codec=l,t.jitter=u,t}static calculatePacketLoss(e,t){return!t||t<=0||!e||e<=0?0:Math.round(e/t*100)}}class Ml{static buildCallFeedReport(e,t,r){const i=r.getTransceivers(),s=[],o=[];return i.forEach(a=>{var u;const c=(u=a.sender)!=null&&u.track?Ml.buildTrackStats(a.sender.track,"sender"):null,l=Ml.buildTrackStats(a.receiver.track,"receiver");s.push({mid:a.mid==null?"null":a.mid,direction:a.direction,currentDirection:a.currentDirection==null?"null":a.currentDirection,sender:c,receiver:l})}),{callId:e,opponentMemberId:t,transceiver:s,callFeeds:o}}static buildTrackStats(e,t="--"){var s,o;const r=(s=e.getSettings())==null?void 0:s.deviceId,i=(o=e.getConstraints())==null?void 0:o.deviceId;return{id:e.id,kind:e.kind,settingDeviceId:r??"unknown",constrainDeviceId:i??"unknown",muted:e.muted,enabled:e.enabled,readyState:e.readyState,label:t}}static expandCallFeedReport(e,t,r="unknown"){return t.forEach(i=>{const s=i.stream.getAudioTracks(),o=i.stream.getVideoTracks(),a=s.length>0?Ml.buildTrackStats(i.stream.getAudioTracks()[0],i.purpose):null,c=o.length>0?Ml.buildTrackStats(i.stream.getVideoTracks()[0],i.purpose):null,l={stream:i.stream.id,type:i.isLocal()?"local":"remote",audio:a,video:c,purpose:i.purpose,prefix:r,isVideoMuted:i.isVideoMuted(),isAudioMuted:i.isAudioMuted()};e.callFeeds.push(l)}),e}}class Ase{constructor(e,t,r,i,s=!0){this.callId=e,this.opponentMemberId=t,this.pc=r,this.emitter=i,this.isFocus=s,this.isActive=!0,this.connectionStats=new Tse,r.addEventListener("signalingstatechange",this.onSignalStateChange.bind(this)),this.trackStats=new Lse(new kse,new xse(r))}async processStats(e,t){const r={isFirstCollection:this.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(this.isActive){const i=this.pc.getStats();if(typeof(i==null?void 0:i.then)=="function")return i.then(s=>{var a,c;this.currentStatsReport=typeof(s==null?void 0:s.result)=="function"?s.result():s;try{this.processStatsReport(e,t)}catch(l){return this.handleError(l),r}this.previousStatsReport=this.currentStatsReport,r.receivedMedia=this.connectionStats.bitrate.download,r.receivedAudioMedia=((a=this.connectionStats.bitrate.audio)==null?void 0:a.download)||0,r.receivedVideoMedia=((c=this.connectionStats.bitrate.video)==null?void 0:c.download)||0;const o=ms.buildTrackSummary(Array.from(this.trackStats.getTrack2stats().values()));return{...r,audioTrackSummary:o.audioTrackSummary,videoTrackSummary:o.videoTrackSummary}}).catch(s=>(this.handleError(s),r));this.isActive=!1}return Promise.resolve(r)}processStatsReport(e,t){var i;const r=new Map;r.callId=this.callId,r.opponentMemberId=this.opponentMemberId,(i=this.currentStatsReport)==null||i.forEach(s=>{const o=this.previousStatsReport?this.previousStatsReport.get(s.id):null;if(s.type==="candidate-pair"&&s.nominated&&s.state==="succeeded")this.connectionStats.bandwidth=Ise.buildBandwidthReport(s),this.connectionStats.transport=Rse.buildReport(this.currentStatsReport,s,this.connectionStats.transport,this.isFocus);else if(s.type==="inbound-rtp"||s.type==="outbound-rtp"){const a=this.trackStats.findTrack2Stats(s,s.type==="inbound-rtp"?"remote":"local");if(!a)return;if(o&&ms.buildPacketsLost(a,s,o),s.type==="inbound-rtp"){ms.buildFramerateResolution(a,s),o&&ms.buildBitrateReceived(a,s,o);const c=this.trackStats.findTransceiverByTrackId(a.trackId);ms.setTrackStatsState(a,c),ms.buildJitter(a,s),ms.buildAudioConcealment(a,s)}else o&&(r.set(a.trackId,Wu.getNonNegativeValue(s.bytesSent)),ms.buildBitrateSend(a,s,o));ms.buildCodec(this.currentStatsReport,a,s)}else if(s.type==="track"&&s.kind==="video"&&!s.remoteSource){const a=this.trackStats.findLocalVideoTrackStats(s);if(!a)return;ms.buildFramerateResolution(a,s),ms.calculateSimulcastFramerate(a,s,o,this.trackStats.mediaTrackHandler.getActiveSimulcastStreams())}}),this.emitter.emitByteSendReport(r),this.emitter.emitCallFeedReport(Ml.buildCallFeedReport(this.callId,this.opponentMemberId,this.pc)),this.processAndEmitConnectionStatsReport()}setActive(e){this.isActive=e}getActive(){return this.isActive}handleError(e){this.isActive=!1,M.warn(`CallStatsReportGatherer ${this.callId} processStatsReport fails and set to inactive ${e}`)}processAndEmitConnectionStatsReport(){const e=Rg.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({...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 wa=(n=>(n.CONNECTION_STATS="StatsReport.connection_stats",n.CALL_FEED_REPORT="StatsReport.call_feed_report",n.BYTE_SENT_STATS="StatsReport.byte_sent_stats",n.SUMMARY_STATS="StatsReport.summary_stats",n))(wa||{});class Ose extends Yn{emitByteSendReport(e){this.emit(wa.BYTE_SENT_STATS,e)}emitConnectionStatsReport(e){this.emit(wa.CONNECTION_STATS,e)}emitCallFeedReport(e){this.emit(wa.CALL_FEED_REPORT,e)}emitSummaryStatsReport(e){this.emit(wa.SUMMARY_STATS,e)}}class P${constructor(e){this.emitter=e}build(e){const t=e.filter(u=>!u.isFirstCollection),r=t.length,i=e.length;if(r===0)return;const s={receivedAudio:0,receivedVideo:0,receivedMedia:0,concealedAudio:0,totalAudio:0};let o=0,a=0;t.forEach(u=>{this.countTrackListReceivedMedia(s,u),this.countConcealedAudio(s,u),o=this.buildMaxJitter(o,u),a=this.buildMaxPacketLoss(a,u)});const c=5,l={percentageReceivedMedia:Number((s.receivedMedia/r).toFixed(c)),percentageReceivedVideoMedia:Number((s.receivedVideo/r).toFixed(c)),percentageReceivedAudioMedia:Number((s.receivedAudio/r).toFixed(c)),maxJitter:o,maxPacketLoss:a,percentageConcealedAudio:Number(s.totalAudio>0?(s.concealedAudio/s.totalAudio).toFixed(c):0),peerConnections:i};this.emitter.emitSummaryStatsReport(l)}static extendSummaryReport(e,t){const r=[],i=[];for(const s of t){i.push(s);for(const o of s[1])r.push(o)}e.opponentDevicesInCall=Math.max(0,r.length-1),e.opponentUsersInCall=Math.max(0,i.length-1),e.diffDevicesToPeerConnections=Math.max(0,r.length-1)-e.peerConnections,e.ratioPeerConnectionToDevices=Math.max(0,r.length-1)==0?0:e.peerConnections/(r.length-1)}countTrackListReceivedMedia(e,t){let r=!1,i=!1;(t.receivedAudioMedia>0||t.audioTrackSummary.count===0)&&(e.receivedAudio++,r=!0),(t.receivedVideoMedia>0||t.videoTrackSummary.count===0||t.videoTrackSummary.muted>0&&t.videoTrackSummary.muted===t.videoTrackSummary.count)&&(e.receivedVideo++,i=!0),i&&r&&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 Mse{constructor(e,t,r=1e4){this.groupCallId=e,this.userId=t,this.interval=r,this.gatherers=new Map,this.reports=new Ose,this.summaryStatsReportGatherer=new P$(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,r){return this.hasStatsReportGatherer(e)?!1:(this.gatherers.set(e,new Ase(e,t,r,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 r;(r=this.getStatsReportGatherer(e))==null||r.setOpponentMemberId(t)}processStats(){const e=[];this.gatherers.forEach(t=>{e.push(t.processStats(this.groupCallId,this.userId))}),Promise.all(e).then(t=>this.summaryStatsReportGatherer.build(t)).catch(t=>{M.error("Could not build summary stats report",t)})}setInterval(e){this.interval=e}}var SP=(n=>(n.Ring="m.ring",n.Prompt="m.prompt",n.Room="m.room",n))(SP||{}),pw=(n=>(n.Video="m.video",n.Voice="m.voice",n))(pw||{}),Ob=(n=>(n.GroupCallStateChanged="group_call_state_changed",n.ActiveSpeakerChanged="active_speaker_changed",n.CallsChanged="calls_changed",n.UserMediaFeedsChanged="user_media_feeds_changed",n.ScreenshareFeedsChanged="screenshare_feeds_changed",n.LocalScreenshareStateChanged="local_screenshare_state_changed",n.LocalMuteStateChanged="local_mute_state_changed",n.ParticipantsChanged="participants_changed",n.Error="group_call_error",n))(Ob||{}),L$=(n=>(n.ConnectionStats="GroupCall.connection_stats",n.ByteSentStats="GroupCall.byte_sent_stats",n.SummaryStats="GroupCall.summary_stats",n.CallFeedStats="GroupCall.call_feed_stats",n))(L$||{}),A$=(n=>(n.NoUserMedia="no_user_media",n.UnknownDevice="unknown_device",n.PlaceCallFailed="place_call_failed",n))(A$||{});class ek extends Error{constructor(e,t,r){r?super(t+": "+r):super(t),this.code=e}}class O$ extends ek{constructor(e){super("unknown_device","No device found for "+e),this.userId=e}}var wP=(n=>(n.LocalCallFeedUninitialized="local_call_feed_uninitialized",n.InitializingLocalCallFeed="initializing_local_call_feed",n.LocalCallFeedInitialized="local_call_feed_initialized",n.Entered="entered",n.Ended="ended",n))(wP||{});const w5=1e3*60*60;function n1(n){var e;return((e=n.getOpponentMember())==null?void 0:e.userId)||n.invitee||null}class EP extends Yn{constructor(e,t,r,i,s,o,a,c,l,u=!1,h){var p;super(),this.client=e,this.room=t,this.type=r,this.isPtt=i,this.intent=s,this.dataChannelsEnabled=a,this.dataChannelOptions=c,this.useLivekit=u,this.activeSpeakerInterval=1e3,this.retryCallInterval=5e3,this.participantTimeout=1e3*15,this.pttMaxTransmitTime=1e3*20,this.userMediaFeeds=[],this.screenshareFeeds=[],this.calls=new Map,this.callHandlers=new Map,this.retryCallCounts=new Map,this.transmitTimer=null,this.participantsExpirationTimer=null,this.resendMemberStateTimer=null,this.initWithAudioMuted=!1,this.initWithVideoMuted=!1,this.statsCollectIntervalTime=0,this.onConnectionStats=m=>{this.emit("GroupCall.connection_stats",{report:m})},this.onByteSentStats=m=>{this.emit("GroupCall.byte_sent_stats",{report:m})},this.onSummaryStats=m=>{P$.extendSummaryReport(m,this.participants),this.emit("GroupCall.summary_stats",{report:m})},this.onCallFeedReport=m=>{this.localCallFeed&&(m=Ml.expandCallFeedReport(m,[this.localCallFeed],"from-local-feed"));const v=[];this.forEachCall(g=>{g.callId===m.callId&&g.getFeeds().forEach(S=>v.push(S))}),m=Ml.expandCallFeedReport(m,v,"from-call-feed"),this.emit("GroupCall.call_feed_stats",{report:m})},this._state="local_call_feed_uninitialized",this._participants=new Map,this._creationTs=null,this._enteredViaAnotherSession=!1,this.onIncomingCall=m=>{var R;if(m.roomId!==this.room.roomId)return;if(m.state!==_s.Ringing){M.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call no longer in ringing state - ignoring`);return}if(!m.groupCallId||m.groupCallId!==this.groupCallId){M.log(`GroupCall ${this.groupCallId} onIncomingCall() ignored because it doesn't match the current group call`),m.reject();return}const v=(R=m.getOpponentMember())==null?void 0:R.userId;if(v===void 0){M.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call with no member - ignoring`);return}if(this.useLivekit){M.info("Received incoming call whilst in signaling-only mode! Ignoring.");return}const g=this.calls.get(v)??new Map,S=g.get(m.getOpponentDeviceId());if((S==null?void 0:S.callId)===m.callId)return;M.log(`GroupCall ${this.groupCallId} onIncomingCall() incoming call (userId=${v}, callId=${m.callId})`),S&&S.hangup(nc.Replaced,!1),g.set(m.getOpponentDeviceId(),m),this.calls.set(v,g),this.initCall(m);const b=this.getLocalFeeds().map(k=>k.clone());if(!this.callExpected(m))for(const k of b)er(k.stream.getAudioTracks(),!1),er(k.stream.getVideoTracks(),!1);m.answerWithCallFeeds(b),this.emit("calls_changed",this.calls)},this.onRetryCallLoop=()=>{let m=!1;for(const[{userId:v},g]of this.participants){const S=this.calls.get(v);let b=this.retryCallCounts.get(v);for(const[R,k]of g){const I=S==null?void 0:S.get(R),T=(b==null?void 0:b.get(R))??0;(I==null?void 0:I.getOpponentSessionId())!==k.sessionId&&this.wantsOutgoingCall(v,R)&&T<3&&(b===void 0&&(b=new Map,this.retryCallCounts.set(v,b)),b.set(R,T+1),m=!0)}}m&&this.placeOutgoingCalls()},this.onCallFeedsChanged=m=>{const v=n1(m),g=m.getOpponentDeviceId();if(!v)throw new Error("Cannot change call feeds without user id");const S=this.getUserMediaFeed(v,g),b=m.remoteUsermediaFeed,R=b!==S,k=this.calls.get(v),I=k==null?void 0:k.get(g);if((I==null?void 0:I.callId)!==m.callId)return;R&&(!S&&b?this.addUserMediaFeed(b):S&&b?this.replaceUserMediaFeed(S,b):S&&!b&&this.removeUserMediaFeed(S));const T=this.getScreenshareFeed(v,g),C=m.remoteScreensharingFeed;C!==T&&(!T&&C?this.addScreenshareFeed(C):T&&C?this.replaceScreenshareFeed(T,C):T&&!C&&this.removeScreenshareFeed(T))},this.onCallStateChanged=(m,v,g)=>{var k;if(v===_s.Ended)return;const S=this.localCallFeed.isAudioMuted();m.localUsermediaStream&&m.isMicrophoneMuted()!==S&&m.setMicrophoneMuted(S);const b=this.localCallFeed.isVideoMuted();m.localUsermediaStream&&m.isLocalVideoMuted()!==b&&m.setLocalVideoMuted(b);const R=(k=m.getOpponentMember())==null?void 0:k.userId;if(v===_s.Connected&&R){const I=this.retryCallCounts.get(R);I==null||I.delete(m.getOpponentDeviceId()),(I==null?void 0:I.size)===0&&this.retryCallCounts.delete(R)}},this.onCallHangup=m=>{var S;if(m.hangupReason===nc.Replaced)return;const v=((S=m.getOpponentMember())==null?void 0:S.userId)??this.room.getMember(m.invitee).userId,g=this.calls.get(v);(g==null?void 0:g.get(m.getOpponentDeviceId()))===m&&(this.disposeCall(m,m.hangupReason),g.delete(m.getOpponentDeviceId()),g.size===0&&this.calls.delete(v),this.emit("calls_changed",this.calls))},this.onCallReplaced=(m,v)=>{const g=m.getOpponentMember().userId;let S=this.calls.get(g);S===void 0&&(S=new Map,this.calls.set(g,S)),m.hangup(nc.Replaced,!1),this.initCall(v),S.set(m.getOpponentDeviceId(),v),this.emit("calls_changed",this.calls)},this.onActiveSpeakerLoop=()=>{let m,v;for(const g of this.userMediaFeeds){if(g.isLocal()&&this.userMediaFeeds.length>1)continue;const b=g.speakingVolumeSamples.reduce((R,k)=>R+Math.max(k,JR))/g.speakingVolumeSamples.length;(!m||b>m)&&(m=b,v=g)}v&&this.activeSpeaker!==v&&m&&m>JR&&(this.activeSpeaker=v,this.emit("active_speaker_changed",this.activeSpeaker))},this.onRoomState=()=>this.updateParticipants(),this.onParticipantsChanged=()=>{this.forEachCall(m=>{const v=this.callExpected(m);for(const g of m.getLocalFeeds())er(g.stream.getAudioTracks(),!g.isAudioMuted()&&v),er(g.stream.getVideoTracks(),!g.isVideoMuted()&&v)}),this.state==="entered"&&!this.useLivekit&&this.placeOutgoingCalls()},this.onStateChanged=(m,v)=>{(m==="entered"||v==="entered"||m==="ended")&&(this.updateParticipants(),this.updateMemberState().catch(g=>M.error(`GroupCall ${this.groupCallId} onStateChanged() failed to update member state devices"`,g)))},this.onLocalFeedsChanged=()=>{this.state==="entered"&&this.updateMemberState().catch(m=>M.error(`GroupCall ${this.groupCallId} onLocalFeedsChanged() failed to update member state feeds`,m))},this.reEmitter=new jj(this),this.groupCallId=o??zu(),this._livekitServiceURL=h,this.creationTs=((p=t.currentState.getStateEvents(ie.GroupCallPrefix,this.groupCallId))==null?void 0:p.getTs())??null,this.updateParticipants(),t.on(It.Update,this.onRoomState),this.on("participants_changed",this.onParticipantsChanged),this.on("group_call_state_changed",this.onStateChanged),this.on("local_screenshare_state_changed",this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!l}async create(){return this.creationTs=Date.now(),this.client.groupCallEventHandler.groupCalls.set(this.room.roomId,this),this.client.emit(QR.Outgoing,this),await this.sendCallStateEvent(),this}async sendCallStateEvent(){const e={"m.intent":this.intent,"m.type":this.type,"io.element.ptt":this.isPtt,dataChannelsEnabled:this.dataChannelsEnabled,dataChannelOptions:this.dataChannelsEnabled?this.dataChannelOptions:void 0};this.livekitServiceURL&&(e["io.element.livekit_service_url"]=this.livekitServiceURL),await this.client.sendStateEvent(this.room.roomId,ie.GroupCallPrefix,e,this.groupCallId)}get livekitServiceURL(){return this._livekitServiceURL}updateLivekitServiceURL(e){return this._livekitServiceURL=e,this.sendCallStateEvent()}get state(){return this._state}set state(e){const t=this._state;e!==t&&(this._state=e,this.emit("group_call_state_changed",e,t))}get participants(){return this._participants}set participants(e){const t=this._participants,r=(s,o)=>s.sessionId===o.sessionId&&s.screensharing===o.screensharing;NM(e,t,(s,o)=>NM(s,o,r))||(this._participants=e,this.emit("participants_changed",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(const t of this.calls.values())for(const r of t.values())e(r)}getLocalFeeds(){const e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e;return((e=this.participants.get(this.room.getMember(this.client.getUserId())))==null?void 0:e.has(this.client.getDeviceId()))??!1}callExpected(e){var s;const t=n1(e),r=t===null?null:this.room.getMember(t),i=e.getOpponentDeviceId();return r!==null&&i!==void 0&&((s=this.participants.get(r))==null?void 0:s.get(i))!==void 0}async initLocalCallFeed(){if(this.useLivekit){M.info("Livekit group call: not starting local call feed.");return}if(this.state!=="local_call_feed_uninitialized")throw new Error(`Cannot initialize local call feed in the "${this.state}" state.`);if(this.state="initializing_local_call_feed",this.initCallFeedPromise)return this.initCallFeedPromise;try{this.initCallFeedPromise=this.initLocalCallFeedInternal(),await this.initCallFeedPromise}finally{this.initCallFeedPromise=void 0}}async initLocalCallFeedInternal(){M.log(`GroupCall ${this.groupCallId} initLocalCallFeedInternal() running`);let e;try{e=await this.client.getMediaHandler().getUserMediaStream(!0,this.type==="m.video")}catch(r){if(this.allowCallWithoutVideoAndAudio)e=new MediaStream;else throw this.state="local_call_feed_uninitialized",r}if(this._state!=="initializing_local_call_feed")throw this.client.getMediaHandler().stopUserMediaStream(e),new Error("Group call disposed while gathering media stream");const t=new hc({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:e,purpose:Qt.Usermedia,audioMuted:this.initWithAudioMuted||e.getAudioTracks().length===0||this.isPtt,videoMuted:this.initWithVideoMuted||e.getVideoTracks().length===0});er(e.getAudioTracks(),!t.isAudioMuted()),er(e.getVideoTracks(),!t.isVideoMuted()),this.localCallFeed=t,this.addUserMediaFeed(t),this.state="local_call_feed_initialized"}async updateLocalUsermediaStream(e){if(this.localCallFeed){const t=this.localCallFeed.stream;this.localCallFeed.setNewStream(e);const r=this.localCallFeed.isAudioMuted(),i=this.localCallFeed.isVideoMuted();M.log(`GroupCall ${this.groupCallId} updateLocalUsermediaStream() (oldStreamId=${t.id}, newStreamId=${e.id}, micShouldBeMuted=${r}, vidShouldBeMuted=${i})`),er(e.getAudioTracks(),!r),er(e.getVideoTracks(),!i),this.client.getMediaHandler().stopUserMediaStream(t)}}async enter(){if(this.state==="local_call_feed_uninitialized")await this.initLocalCallFeed();else if(this.state!=="local_call_feed_initialized")throw new Error(`Cannot enter call in the "${this.state}" state`);M.log(`GroupCall ${this.groupCallId} enter() running`),this.state="entered",this.client.on(ZR.Incoming,this.onIncomingCall);for(const e of this.client.callEventHandler.calls.values())this.onIncomingCall(e);this.useLivekit||(this.retryCallLoopInterval=setInterval(this.onRetryCallLoop,this.retryCallInterval),this.activeSpeaker=void 0,this.onActiveSpeakerLoop(),this.activeSpeakerLoopInterval=setInterval(this.onActiveSpeakerLoop,this.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==="entered"&&(this.forEachCall(t=>t.hangup(nc.UserHangup,!1)),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(ZR.Incoming,this.onIncomingCall),(e=this.stats)==null||e.stop())}leave(){this.dispose(),this.state="local_call_feed_uninitialized"}async terminate(e=!0){if(this.dispose(),this.room.off(It.Update,this.onRoomState),this.client.groupCallEventHandler.groupCalls.delete(this.room.roomId),this.client.emit(QR.Ended,this),this.state="ended",e){const t=this.room.currentState.getStateEvents(ie.GroupCallPrefix,this.groupCallId);await this.client.sendStateEvent(this.room.roomId,ie.GroupCallPrefix,{...t.getContent(),"m.terminated":"call_ended"},this.groupCallId)}}isLocalVideoMuted(){return this.localCallFeed?this.localCallFeed.isVideoMuted():!0}isMicrophoneMuted(){return this.localCallFeed?this.localCallFeed.isAudioMuted():!0}async setMicrophoneMuted(e){if(!e&&!await this.client.getMediaHandler().hasAudioDevice())return!1;const t=!e&&this.isPtt;this.isPtt&&(!e&&this.isMicrophoneMuted()?this.transmitTimer=setTimeout(()=>{this.setMicrophoneMuted(!0)},this.pttMaxTransmitTime):e&&!this.isMicrophoneMuted()&&(this.transmitTimer!==null&&clearTimeout(this.transmitTimer),this.transmitTimer=null)),this.forEachCall(i=>{var s;return(s=i.localUsermediaFeed)==null?void 0:s.setAudioVideoMuted(e,null)});const r=async()=>{const i=[];this.forEachCall(s=>i.push(s.sendMetadataUpdate())),await Promise.all(i).catch(s=>M.info(`GroupCall ${this.groupCallId} setMicrophoneMuted() failed to send some metadata updates`,s))};if(t&&await r(),this.localCallFeed){if(M.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() (streamId=${this.localCallFeed.stream.id}, muted=${e})`),!await this.checkAudioPermissionIfNecessary(e))return!1;this.localCallFeed.setAudioVideoMuted(e,null),er(this.localCallFeed.stream.getAudioTracks(),!e)}else M.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no stream muted (muted=${e})`),this.initWithAudioMuted=e;return this.forEachCall(i=>er(i.localUsermediaFeed.stream.getAudioTracks(),!e&&this.callExpected(i))),this.emit("local_mute_state_changed",e,this.isLocalVideoMuted()),t||await r(),!0}async checkAudioPermissionIfNecessary(e){try{if(!e&&this.localCallFeed&&!this.localCallFeed.hasAudioTrack){const t=await this.client.getMediaHandler().getUserMediaStream(!0,!this.localCallFeed.isVideoMuted());if((t==null?void 0:t.getTracks().length)===0)return M.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device to receive local stream, muted=${e}`),!1}}catch{return M.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device or permission to receive local stream, muted=${e}`),!1}return!0}async setLocalVideoMuted(e){if(!e&&!await this.client.getMediaHandler().hasVideoDevice())return!1;if(this.localCallFeed){M.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() (stream=${this.localCallFeed.stream.id}, muted=${e})`);try{const r=await this.client.getMediaHandler().getUserMediaStream(!0,!e);await this.updateLocalUsermediaStream(r),this.localCallFeed.setAudioVideoMuted(null,e),er(this.localCallFeed.stream.getVideoTracks(),!e)}catch{return M.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no device or permission to receive local stream, muted=${e}`),!1}}else M.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no stream muted (muted=${e})`),this.initWithVideoMuted=e;const t=[];return this.forEachCall(r=>t.push(r.setLocalVideoMuted(e))),await Promise.all(t),this.forEachCall(r=>er(r.localUsermediaFeed.stream.getVideoTracks(),!e&&this.callExpected(r))),this.emit("local_mute_state_changed",this.isMicrophoneMuted(),e),!0}async setScreensharingEnabled(e,t={}){if(e===this.isScreensharing())return e;if(e)try{M.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() is asking for screensharing permissions`);const r=await this.client.getMediaHandler().getScreensharingStream(t);for(const i of r.getTracks()){const s=()=>{this.setScreensharingEnabled(!1),i.removeEventListener("ended",s)};i.addEventListener("ended",s)}return M.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls`),this.localDesktopCapturerSourceId=t.desktopCapturerSourceId,this.localScreenshareFeed=new hc({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:r,purpose:Qt.Screenshare,audioMuted:!1,videoMuted:!1}),this.addScreenshareFeed(this.localScreenshareFeed),this.emit("local_screenshare_state_changed",!0,this.localScreenshareFeed,this.localDesktopCapturerSourceId),this.forEachCall(i=>i.pushLocalFeed(this.localScreenshareFeed.clone())),!0}catch(r){if(t.throwOnFail)throw r;return M.error(`GroupCall ${this.groupCallId} setScreensharingEnabled() enabling screensharing error`,r),this.emit("group_call_error",new ek("no_user_media","Failed to get screen-sharing stream: ",r)),!1}else return this.forEachCall(r=>{r.localScreensharingFeed&&r.removeLocalFeed(r.localScreensharingFeed)}),this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0,this.emit("local_screenshare_state_changed",!1,void 0,void 0),!1}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,t){const r=this.client.getUserId(),i=this.client.getDeviceId();return e>=r&&(e!==r||t>i)}placeOutgoingCalls(){let e=!1;for(const[{userId:t},r]of this.participants){const i=this.calls.get(t)??new Map;for(const[s,o]of r){const a=i.get(s);if((a==null?void 0:a.getOpponentSessionId())!==o.sessionId&&this.wantsOutgoingCall(t,s)){e=!0,a!==void 0&&(M.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() replacing call (userId=${t}, deviceId=${s}, callId=${a.callId})`),a.hangup(nc.NewSession,!1));const c=av(this.client,this.room.roomId,{invitee:t,opponentDeviceId:s,opponentSessionId:o.sessionId,groupCallId:this.groupCallId});c===null?(M.error(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to create call (userId=${t}, device=${s})`),i.delete(s)):(this.initCall(c),i.set(s,c),M.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() placing call (userId=${t}, deviceId=${s}, sessionId=${o.sessionId})`),c.placeCallWithCallFeeds(this.getLocalFeeds().map(l=>l.clone()),o.screensharing).then(()=>{this.dataChannelsEnabled&&c.createDataChannel("datachannel",this.dataChannelOptions)}).catch(l=>{M.warn(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to place call (userId=${t})`,l),l instanceof rc&&l.code==="unknown_device"?this.emit("group_call_error",l):this.emit("group_call_error",new ek("place_call_failed",`Failed to place call to ${t}`)),c.hangup(nc.SignallingFailed,!1),i.get(s)===c&&i.delete(s)}))}}i.size>0?this.calls.set(t,i):this.calls.delete(t)}e&&this.emit("calls_changed",this.calls)}getMemberStateEvents(e){return e===void 0?this.room.currentState.getStateEvents(ie.GroupCallMemberPrefix):this.room.currentState.getStateEvents(ie.GroupCallMemberPrefix,e)}initCall(e){const t=n1(e);if(!t)throw new Error("Cannot init call without user id");const r=()=>this.onCallFeedsChanged(e),i=(c,l)=>this.onCallStateChanged(e,c,l),s=this.onCallHangup,o=c=>this.onCallReplaced(e,c);let a=this.callHandlers.get(t);a===void 0&&(a=new Map,this.callHandlers.set(t,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:r,onCallStateChanged:i,onCallHangup:s,onCallReplaced:o}),e.on(Bi.FeedsChanged,r),e.on(Bi.State,i),e.on(Bi.Hangup,s),e.on(Bi.Replaced,o),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(Bi)),e.initStats(this.getGroupCallStats()),r()}disposeCall(e,t){const r=n1(e),i=e.getOpponentDeviceId();if(!r)throw new Error("Cannot dispose call without user id");const s=this.callHandlers.get(r),{onCallFeedsChanged:o,onCallStateChanged:a,onCallHangup:c,onCallReplaced:l}=s.get(i);if(e.removeListener(Bi.FeedsChanged,o),e.removeListener(Bi.State,a),e.removeListener(Bi.Hangup,c),e.removeListener(Bi.Replaced,l),s.delete(r),s.size===0&&this.callHandlers.delete(r),e.hangupReason===nc.Replaced)return;const u=this.getUserMediaFeed(r,i);u&&this.removeUserMediaFeed(u);const h=this.getScreenshareFeed(r,i);h&&this.removeScreenshareFeed(h)}getUserMediaFeed(e,t){return this.userMediaFeeds.find(r=>r.userId===e&&r.deviceId===t)}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit("user_media_feeds_changed",this.userMediaFeeds)}replaceUserMediaFeed(e,t){const r=this.userMediaFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(r===-1)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(r,1,t),e.dispose(),t.measureVolumeActivity(!0),this.emit("user_media_feeds_changed",this.userMediaFeeds)}removeUserMediaFeed(e){const t=this.userMediaFeeds.findIndex(r=>r.userId===e.userId&&r.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("user_media_feeds_changed",this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit("active_speaker_changed",this.activeSpeaker))}getScreenshareFeed(e,t){return this.screenshareFeeds.find(r=>r.userId===e&&r.deviceId===t)}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit("screenshare_feeds_changed",this.screenshareFeeds)}replaceScreenshareFeed(e,t){const r=this.screenshareFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(r===-1)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(r,1,t),e.dispose(),this.emit("screenshare_feeds_changed",this.screenshareFeeds)}removeScreenshareFeed(e){const t=this.screenshareFeeds.findIndex(r=>r.userId===e.userId&&r.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("screenshare_feeds_changed",this.screenshareFeeds)}updateParticipants(){const e=this.room.getMember(this.client.getSafeUserId());if(!e){M.warn(`GroupCall ${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==="ended"){this.participants=new Map;return}const t=new Map,r=Date.now(),i=this.state==="entered"||this.enteredViaAnotherSession;let s=1/0;for(const o of this.getMemberStateEvents()){const a=this.room.getMember(o.getStateKey()),c=o.getContent(),u=(Array.isArray(c["m.calls"])?c["m.calls"]:[]).find(m=>m["m.call_id"]===this.groupCallId);let p=(Array.isArray(u==null?void 0:u["m.devices"])?u["m.devices"]:[]).filter(m=>typeof m.device_id=="string"&&typeof m.session_id=="string"&&typeof m.expires_ts=="number"&&m.expires_ts>r&&Array.isArray(m.feeds));if(!i&&(a==null?void 0:a.userId)===this.client.getUserId()&&(p=p.filter(m=>m.device_id!==this.client.getDeviceId())),p.length>0&&(a==null?void 0:a.membership)===We.Join){const m=new Map;t.set(a,m);for(const v of p)m.set(v.device_id,{sessionId:v.session_id,screensharing:v.feeds.some(g=>g.purpose===Qt.Screenshare)}),v.expires_ts<s&&(s=v.expires_ts)}}if(i){let o=t.get(e);o===void 0&&(o=new Map,t.set(e,o)),o.has(this.client.getDeviceId())||o.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some(a=>a.purpose===Qt.Screenshare)})}this.participants=t,s<1/0&&(this.participantsExpirationTimer=setTimeout(()=>this.updateParticipants(),s-r))}async updateDevices(e,t=!1){const r=Date.now(),i=this.client.getUserId(),s=this.getMemberStateEvents(i),o=(s==null?void 0:s.getContent())??{},a=Array.isArray(o["m.calls"])?o["m.calls"]:[];let c=null;const l=[];for(const g of a)g["m.call_id"]===this.groupCallId?c=g:l.push(g);c===null&&(c={});const h=(Array.isArray(c["m.devices"])?c["m.devices"]:[]).filter(g=>typeof g.device_id=="string"&&typeof g.session_id=="string"&&typeof g.expires_ts=="number"&&g.expires_ts>r&&Array.isArray(g.feeds)),p=e(h);if(p===null)return;const m=[...l];p.length>0&&m.push({...c,"m.call_id":this.groupCallId,"m.devices":p});const v={"m.calls":m};await this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,v,i,{keepAlive:t})}async addDeviceToMemberState(){await this.updateDevices(e=>[...e.filter(t=>t.device_id!==this.client.getDeviceId()),{device_id:this.client.getDeviceId(),session_id:this.client.getSessionId(),expires_ts:Date.now()+w5,feeds:this.getLocalFeeds().map(t=>({purpose:t.purpose}))}])}async updateMemberState(){this.resendMemberStateTimer!==null&&(clearInterval(this.resendMemberStateTimer),this.resendMemberStateTimer=null),this.state==="entered"?(await this.addDeviceToMemberState(),this.resendMemberStateTimer=setInterval(async()=>{M.log(`GroupCall ${this.groupCallId} updateMemberState() resending call member state"`);try{await this.addDeviceToMemberState()}catch(e){M.error(`GroupCall ${this.groupCallId} updateMemberState() failed to resend call member state`,e)}},w5*3/4)):await this.updateDevices(e=>e.filter(t=>t.device_id!==this.client.getDeviceId()),!0)}async cleanMemberState(){const{devices:e}=await this.client.getDevices(),t=new Map(e.map(r=>[r.device_id,r]));await this.updateDevices(r=>{const i=r.filter(s=>{const o=t.get(s.device_id);return(o==null?void 0:o.last_seen_ts)!==void 0&&!(s.device_id===this.client.getDeviceId()&&this.state!=="entered"&&!this.enteredViaAnotherSession)});return i.length===r.length?null:i})}getGroupCallStats(){if(this.stats===void 0){const e=this.client.getUserId()||"unknown";this.stats=new Mse(this.groupCallId,e,this.statsCollectIntervalTime),this.stats.reports.on(wa.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(wa.BYTE_SENT_STATS,this.onByteSentStats),this.stats.reports.on(wa.SUMMARY_STATS,this.onSummaryStats),this.stats.reports.on(wa.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())}}var _s=(n=>(n.Fledgling="fledgling",n.InviteSent="invite_sent",n.WaitLocalMedia="wait_local_media",n.CreateOffer="create_offer",n.CreateAnswer="create_answer",n.Connecting="connecting",n.Connected="connected",n.Ringing="ringing",n.Ended="ended",n))(_s||{}),M$=(n=>(n.Inbound="inbound",n.Outbound="outbound",n))(M$||{}),Bi=(n=>(n.Hangup="hangup",n.State="state",n.Error="error",n.Replaced="replaced",n.LocalHoldUnhold="local_hold_unhold",n.RemoteHoldUnhold="remote_hold_unhold",n.HoldUnhold="hold_unhold",n.FeedsChanged="feeds_changed",n.AssertedIdentityChanged="asserted_identity_changed",n.LengthChanged="length_changed",n.DataChannel="datachannel",n.SendVoipEvent="send_voip_event",n.PeerConnectionCreated="peer_connection_created",n))(Bi||{}),nc=(n=>(n.UserHangup="user_hangup",n.LocalOfferFailed="local_offer_failed",n.NoUserMedia="no_user_media",n.UnknownDevices="unknown_devices",n.SendInvite="send_invite",n.CreateAnswer="create_answer",n.CreateOffer="create_offer",n.SendAnswer="send_answer",n.SetRemoteDescription="set_remote_description",n.SetLocalDescription="set_local_description",n.AnsweredElsewhere="answered_elsewhere",n.IceFailed="ice_failed",n.InviteTimeout="invite_timeout",n.Replaced="replaced",n.SignallingFailed="signalling_timeout",n.UserBusy="user_busy",n.Transferred="transferred",n.NewSession="new_session",n))(nc||{});const Nse="1",Dse="stun:turn.matrix.org",DT=60*1e3,Fse=1e3,Use=30*1e3,jse=2*1e3;class rc extends Error{constructor(e,t,r){super(t+": "+r),this.code=e}}function zu(){return Date.now().toString()+Es(16)}function E5(n){return[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:n?12e3:void 0}]}function _o(n,e){return n+":"+e}class $se extends Yn{constructor(e){if(super(),this.toDeviceSeq=0,this.isPtt=!1,this._state="fledgling",this.candidateSendQueue=[],this.candidateSendTries=0,this.candidatesEnded=!1,this.feeds=[],this.transceivers=new Map,this.inviteOrAnswerSent=!1,this.waitForLocalAVStream=!1,this.removeTrackListeners=new Map,this.remoteOnHold=!1,this.makingOffer=!1,this.ignoreOffer=!1,this.isSettingRemoteAnswerPending=!1,this.remoteCandidateBuffer=new Map,this.gotLocalIceCandidate=t=>{if(t.candidate){if(this.candidatesEnded&&M.warn(`Call ${this.callId} gotLocalIceCandidate() got candidate after candidates have ended!`),M.debug(`Call ${this.callId} got local ICE ${t.candidate.sdpMid} ${t.candidate.candidate}`),this.callHasEnded())return;t.candidate.candidate===""?this.queueCandidate(null):this.queueCandidate(t.candidate)}},this.onIceGatheringStateChange=t=>{var r;M.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state changed to ${this.peerConn.iceGatheringState}`),((r=this.peerConn)==null?void 0:r.iceGatheringState)==="complete"&&(this.queueCandidate(null),M.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state complete, set candidates have ended`))},this.getLocalOfferFailed=t=>{M.error(`Call ${this.callId} getLocalOfferFailed() running`,t),this.emit("error",new rc("local_offer_failed","Failed to get local offer!",t),this),this.terminate("local","local_offer_failed",!1)},this.getUserMediaFailed=t=>{if(this.successor){this.successor.getUserMediaFailed(t);return}M.warn(`Call ${this.callId} getUserMediaFailed() failed to get user media - ending call`,t),this.emit("error",new rc("no_user_media","Couldn't start capturing media! Is your microphone set up and does this app have permission?",t),this),this.terminate("local","no_user_media",!1)},this.placeCallFailed=t=>{if(this.successor){this.successor.placeCallFailed(t);return}M.warn(`Call ${this.callId} placeCallWithCallFeeds() failed - ending call`,t),this.emit("error",new rc("ice_failed","Couldn't start call! Invalid ICE server configuration.",t),this),this.terminate("local","ice_failed",!1)},this.onIceConnectionStateChanged=()=>{var t,r,i,s,o,a,c;if(!this.callHasEnded()&&(M.debug(`Call ${this.callId} onIceConnectionStateChanged() running (state=${(t=this.peerConn)==null?void 0:t.iceConnectionState}, conn=${(r=this.peerConn)==null?void 0:r.connectionState})`),["connected","completed"].includes(((i=this.peerConn)==null?void 0:i.iceConnectionState)??"")?(clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.iceReconnectionTimeOut&&clearTimeout(this.iceReconnectionTimeOut),this.state="connected",!this.callLengthInterval&&!this.callStartTime&&(this.callStartTime=Date.now(),this.callLengthInterval=setInterval(()=>{this.emit("length_changed",Math.round((Date.now()-this.callStartTime)/1e3),this)},Fse))):((s=this.peerConn)==null?void 0:s.iceConnectionState)=="failed"?(this.candidatesEnded=!1,(o=this.peerConn)!=null&&o.restartIce?(this.candidatesEnded=!1,M.debug(`Call ${this.callId} onIceConnectionStateChanged() ice restart (state=${(a=this.peerConn)==null?void 0:a.iceConnectionState})`),this.peerConn.restartIce()):(M.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)`),this.hangup("ice_failed",!1))):((c=this.peerConn)==null?void 0:c.iceConnectionState)=="disconnected"&&(this.candidatesEnded=!1,this.iceReconnectionTimeOut=setTimeout(()=>{var l,u,h;M.info(`Call ${this.callId} onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=${(l=this.peerConn)==null?void 0:l.iceConnectionState}, conn=${(u=this.peerConn)==null?void 0:u.connectionState})`),(h=this.peerConn)!=null&&h.restartIce&&(this.candidatesEnded=!1,this.peerConn.restartIce()),this.iceReconnectionTimeOut=void 0},jse),this.iceDisconnectedTimeout=setTimeout(()=>{M.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)`),this.hangup("ice_failed",!1)},Use),this.state="connecting"),this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState)))for(const l of this.getRemoteFeeds())l.setAudioVideoMuted(!0,!0)},this.onSignallingStateChanged=()=>{var t;M.debug(`Call ${this.callId} onSignallingStateChanged() running (state=${(t=this.peerConn)==null?void 0:t.signalingState})`)},this.onTrack=t=>{if(t.streams.length===0){M.warn(`Call ${this.callId} onTrack() called with streamless track streamless (kind=${t.track.kind})`);return}const r=t.streams[0];if(this.pushRemoteFeed(r),!this.removeTrackListeners.has(r)){const i=()=>{r.getTracks().length===0&&(M.info(`Call ${this.callId} onTrack() removing track (streamId=${r.id})`),this.deleteFeedByStream(r),r.removeEventListener("removetrack",i),this.removeTrackListeners.delete(r))};r.addEventListener("removetrack",i),this.removeTrackListeners.set(r,i)}},this.onDataChannel=t=>{this.emit("datachannel",t.channel,this)},this.onNegotiationNeeded=async()=>{if(M.info(`Call ${this.callId} onNegotiationNeeded() negotiation is needed!`),this.state!=="create_offer"&&this.opponentVersion===0){M.info(`Call ${this.callId} onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event`);return}this.queueGotLocalOffer()},this.onHangupReceived=t=>{M.debug(`Call ${this.callId} onHangupReceived() running`),this.partyIdMatches(t)||this.state==="ringing"?this.terminate("remote",t.reason||"user_hangup",!0):M.info(`Call ${this.callId} onHangupReceived() ignoring message from party ID ${t.party_id}: our partner is ${this.opponentPartyId}`)},this.onRejectReceived=t=>{M.debug(`Call ${this.callId} onRejectReceived() running`),["invite_sent","ringing"].includes(this.state)||this.state==="fledgling"&&this.direction==="inbound"?this.terminate("remote",t.reason||"user_hangup",!0):M.debug(`Call ${this.callId} onRejectReceived() called in wrong state (state=${this.state})`)},this.onAnsweredElsewhere=t=>{M.debug(`Call ${this.callId} onAnsweredElsewhere() running`),this.terminate("remote","answered_elsewhere",!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=e.forceTURN??!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:[Dse]});for(const t of this.turnServers)gj(t,["urls"]);this.callId=zu(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}async placeVoiceCall(){await this.placeCall(!0,!1)}async placeVideoCall(){await this.placeCall(!0,!0)}createDataChannel(e,t){const r=this.peerConn.createDataChannel(e,t);return this.emit("datachannel",r,this),r}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){const t=this._state;this._state=e,this.emit("state",e,t,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?"video":"voice"}get hasLocalUserMediaVideoTrack(){var e;return!!((e=this.localUsermediaStream)!=null&&e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===Qt.Usermedia&&((t=e.stream)==null?void 0:t.getVideoTracks().length)})}get hasLocalUserMediaAudioTrack(){var e;return!!((e=this.localUsermediaStream)!=null&&e.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===Qt.Usermedia&&!!((t=e.stream)!=null&&t.getAudioTracks().length)})}get hasUserMediaAudioSender(){var e;return!!((e=this.transceivers.get(_o(Qt.Usermedia,"audio")))!=null&&e.sender)}get hasUserMediaVideoSender(){var e;return!!((e=this.transceivers.get(_o(Qt.Usermedia,"video")))!=null&&e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find(e=>e.purpose===Qt.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(e=>e.purpose===Qt.Screenshare)}get localUsermediaStream(){var e;return(e=this.localUsermediaFeed)==null?void 0:e.stream}get localScreensharingStream(){var e;return(e=this.localScreensharingFeed)==null?void 0:e.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find(e=>e.purpose===Qt.Usermedia)}get remoteScreensharingFeed(){return this.getRemoteFeeds().find(e=>e.purpose===Qt.Screenshare)}get remoteUsermediaStream(){var e;return(e=this.remoteUsermediaFeed)==null?void 0:e.stream}get remoteScreensharingStream(){var e;return(e=this.remoteScreensharingFeed)==null?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())}async initOpponentCrypto(){var t;if(!this.opponentDeviceId||!this.client.getUseE2eForGroupCall())return;if(!this.client.getCrypto()){this.hasOpponentDeviceInfo=!0;return}const e=this.invitee||((t=this.getOpponentMember())==null?void 0:t.userId);throw e?(this.hasOpponentDeviceInfo=!1,new O$(e)):new Error("Couldn't find opponent user ID to init crypto")}getLocalSDPStreamMetadata(e=!1){const t={};for(const r of this.getLocalFeeds())e&&(r.sdpMetadataStreamId=r.stream.id),t[r.sdpMetadataStreamId]={purpose:r.purpose,audio_muted:r.isAudioMuted(),video_muted:r.isVideoMuted()};return t}noIncomingFeeds(){return!this.feeds.some(e=>!e.isLocal())}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata()){this.pushRemoteFeedWithoutMetadata(e);return}const t=this.getOpponentMember().userId,r=this.remoteSDPStreamMetadata[e.id].purpose,i=this.remoteSDPStreamMetadata[e.id].audio_muted,s=this.remoteSDPStreamMetadata[e.id].video_muted;if(!r){M.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=${e.id})`);return}if(this.getFeedByStreamId(e.id)){M.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`);return}this.feeds.push(new hc({client:this.client,call:this,roomId:this.roomId,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:r,audioMuted:i,videoMuted:s})),this.emit("feeds_changed",this.feeds,this),M.info(`Call ${this.callId} pushRemoteFeed() pushed stream (streamId=${e.id}, active=${e.active}, purpose=${r})`)}pushRemoteFeedWithoutMetadata(e){var s;const t=this.getOpponentMember().userId,r=Qt.Usermedia,i=(s=this.feeds.find(o=>!o.isLocal()))==null?void 0:s.stream;if(i&&e.id!==i.id){M.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=${e.id})`);return}if(this.getFeedByStreamId(e.id)){M.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=${e.id})`);return}this.feeds.push(new hc({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:r})),this.emit("feeds_changed",this.feeds,this),M.info(`Call ${this.callId} pushRemoteFeedWithoutMetadata() pushed stream (streamId=${e.id}, active=${e.active})`)}pushNewLocalFeed(e,t,r=!0){const i=this.client.getUserId();if(er(e.getAudioTracks(),!0),er(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)){M.warn(`Call ${this.callId} pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`);return}this.pushLocalFeed(new hc({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:t}),r)}pushLocalFeed(e,t=!0){if(this.feeds.some(r=>e.stream.id===r.stream.id)){M.info(`Call ${this.callId} pushLocalFeed() ignoring duplicate local stream (streamId=${e.stream.id})`);return}if(this.feeds.push(e),t)for(const r of e.stream.getTracks()){M.info(`Call ${this.callId} pushLocalFeed() adding track to peer connection (id=${r.id}, kind=${r.kind}, streamId=${e.stream.id}, streamPurpose=${e.purpose}, enabled=${r.enabled})`);const i=_o(e.purpose,r.kind);if(this.transceivers.has(i)){const s=this.transceivers.get(i);s.sender.replaceTrack(r),s.direction=s.direction==="inactive"?"sendonly":"sendrecv"}else{const s=this.peerConn.addTrack(r,e.stream),o=this.peerConn.getTransceivers().find(a=>a.sender===s);o?this.transceivers.set(i,o):M.warn(`Call ${this.callId} pushLocalFeed() didn't find a matching transceiver after adding track!`)}}M.info(`Call ${this.callId} pushLocalFeed() pushed stream (id=${e.stream.id}, active=${e.stream.active}, purpose=${e.purpose})`),this.emit("feeds_changed",this.feeds,this)}removeLocalFeed(e){const t=_o(e.purpose,"audio"),r=_o(e.purpose,"video");for(const i of[t,r])if(this.transceivers.has(i)){const s=this.transceivers.get(i);s.sender&&this.peerConn.removeTrack(s.sender)}e.purpose===Qt.Screenshare&&this.client.getMediaHandler().stopScreensharingStream(e.stream),this.deleteFeed(e)}deleteAllFeeds(){for(const e of this.feeds)(!e.isLocal()||!this.groupCallId)&&e.dispose();this.feeds=[],this.emit("feeds_changed",this.feeds,this)}deleteFeedByStream(e){const t=this.getFeedByStreamId(e.id);if(!t){M.warn(`Call ${this.callId} deleteFeedByStream() didn't find the feed to delete (streamId=${e.id})`);return}this.deleteFeed(t)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit("feeds_changed",this.feeds,this)}async getCurrentCallStats(){return this.callHasEnded()?this.callStatsAtEnd:this.collectCallStats()}async collectCallStats(){if(!this.peerConn)return;const e=await this.peerConn.getStats(),t=[];return e.forEach(r=>{t.push(r)}),t}async initWithInvite(e){var o;const t=e.getContent();this.direction="inbound",await this.client.checkTurnServers()||M.warn(`Call ${this.callId} initWithInvite() failed to get TURN credentials! Proceeding with call anyway...`);const i=t[pl];i?this.updateRemoteSDPStreamMetadata(i):M.debug(`Call ${this.callId} initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams`),this.peerConn=this.createPeerConnection(),this.emit("peer_connection_created",this.peerConn,this),this.chooseOpponent(e),await this.initOpponentCrypto();try{await this.peerConn.setRemoteDescription(t.offer),M.debug(`Call ${this.callId} initWithInvite() set remote description: ${t.offer.type}`),await this.addBufferedIceCandidates()}catch(a){M.debug(`Call ${this.callId} initWithInvite() failed to set remote description`,a),this.terminate("local","set_remote_description",!1);return}const s=(o=this.feeds.find(a=>!a.isLocal()))==null?void 0:o.stream;if(!this.isOnlyDataChannelAllowed&&(!s||s.getTracks().length===0)){M.error(`Call ${this.callId} initWithInvite() no remote stream or no tracks after setting remote description!`),this.terminate("local","set_remote_description",!1);return}if(this.state="ringing",e.getLocalAge()){const a=setTimeout(()=>{var l;this.state=="ringing"&&(M.debug(`Call ${this.callId} initWithInvite() invite has expired. Hanging up.`),this.hangupParty="remote",this.state="ended",this.stopAllMedia(),this.peerConn.signalingState!="closed"&&this.peerConn.close(),(l=this.stats)==null||l.removeStatsReportGatherer(this.callId),this.emit("hangup",this))},t.lifetime-e.getLocalAge()),c=l=>{l!=="ringing"&&(clearTimeout(a),this.off("state",c))};this.on("state",c)}}initWithHangup(e){this.state="ended"}shouldAnswerWithMediaType(e,t,r){return e&&!t?(M.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${r} because the other side isn't sending it either.`),!1):!_j(e)&&e!==t&&!this.opponentSupportsSDPStreamMetadata()?(M.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${r}=${e} because the other side doesn't support it. Answering with ${r}=${t}.`),t):e??t}async answer(e,t){if(!this.inviteOrAnswerSent){if(e===!1&&t===!1)throw new Error("You CANNOT answer a call without media");if(!this.localUsermediaStream&&!this.waitForLocalAVStream){const r=this.state,i=this.shouldAnswerWithMediaType(e,this.hasRemoteUserMediaAudioTrack,"audio"),s=this.shouldAnswerWithMediaType(t,this.hasRemoteUserMediaVideoTrack,"video");this.state="wait_local_media",this.waitForLocalAVStream=!0;try{const o=await this.client.getMediaHandler().getUserMediaStream(i,s);this.waitForLocalAVStream=!1;const c=[new hc({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId()??void 0,stream:o,purpose:Qt.Usermedia,audioMuted:!1,videoMuted:!1})];this.localScreensharingFeed&&c.push(this.localScreensharingFeed),this.answerWithCallFeeds(c)}catch(o){if(s)M.warn(`Call ${this.callId} answer() failed to getUserMedia(), trying to getUserMedia() without video`),this.state=r,this.waitForLocalAVStream=!1,await this.answer(i,!1);else{this.getUserMediaFailed(o);return}}}else this.waitForLocalAVStream&&(this.state="wait_local_media")}}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){M.debug(`Call ${this.callId} replacedBy() running (newCallId=${e.callId})`),this.state==="wait_local_media"?(M.debug(`Call ${this.callId} replacedBy() telling new call to wait for local media (newCallId=${e.callId})`),e.waitForLocalAVStream=!0):["create_offer","invite_sent"].includes(this.state)&&(e.direction==="outbound"?e.queueGotCallFeedsForAnswer([]):(M.debug(`Call ${this.callId} replacedBy() handing local stream to new call(newCallId=${e.callId})`),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(t=>t.clone())))),this.successor=e,this.emit("replaced",e,this),this.hangup("replaced",!0)}hangup(e,t){if(this.callHasEnded()||(M.debug(`Call ${this.callId} hangup() ending call (reason=${e})`),this.terminate("local",e,!t),["fledgling","wait_local_media"].includes(this.state)))return;const r={};(this.opponentVersion&&this.opponentVersion!==0||e!=="user_hangup")&&(r.reason=e),this.sendVoipEvent(ie.CallHangup,r)}reject(){if(this.state!=="ringing")throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion===0){M.info(`Call ${this.callId} reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=${this.opponentVersion})`),this.hangup("user_hangup",!0);return}M.debug("Rejecting call: "+this.callId),this.terminate("local","user_hangup",!0),this.sendVoipEvent(ie.CallReject,{})}async upgradeCall(e,t){if(!(!e&&!t)&&this.opponentSupportsSDPStreamMetadata())try{M.debug(`Call ${this.callId} upgradeCall() upgrading call (audio=${e}, video=${t})`);const r=e||this.hasLocalUserMediaAudioTrack,i=t||this.hasLocalUserMediaVideoTrack,s=await this.client.getMediaHandler().getUserMediaStream(r,i,!1);await this.updateLocalUsermediaStream(s,e,t)}catch(r){M.error(`Call ${this.callId} upgradeCall() failed to upgrade the call`,r),this.emit("error",new rc("no_user_media","Failed to get camera access: ",r),this)}}opponentSupportsSDPStreamMetadata(){return!!this.remoteSDPStreamMetadata}isScreensharing(){return!!this.localScreensharingStream}async setScreensharingEnabled(e,t){if(e&&this.isScreensharing())return M.warn(`Call ${this.callId} setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!`),!0;if(!e&&!this.isScreensharing())return M.warn(`Call ${this.callId} setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!`),!1;if(!this.opponentSupportsSDPStreamMetadata())return this.setScreensharingEnabledWithoutMetadataSupport(e,t);if(M.debug(`Call ${this.callId} setScreensharingEnabled() running (enabled=${e})`),e)try{const r=await this.client.getMediaHandler().getScreensharingStream(t);return r?(this.pushNewLocalFeed(r,Qt.Screenshare),!0):!1}catch(r){return M.error(`Call ${this.callId} setScreensharingEnabled() failed to get screen-sharing stream:`,r),!1}else{const r=this.transceivers.get(_o(Qt.Screenshare,"audio")),i=this.transceivers.get(_o(Qt.Screenshare,"video"));for(const s of[r,i])s&&s.sender&&this.peerConn.removeTrack(s.sender);return this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}}async setScreensharingEnabledWithoutMetadataSupport(e,t){var r,i,s;if(M.debug(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() running (enabled=${e})`),e)try{const o=await this.client.getMediaHandler().getScreensharingStream(t);if(!o)return!1;const a=o.getTracks().find(l=>l.kind==="video"),c=(r=this.transceivers.get(_o(Qt.Usermedia,"video")))==null?void 0:r.sender;return c==null||c.replaceTrack(a??null),this.pushNewLocalFeed(o,Qt.Screenshare,!1),!0}catch(o){return M.error(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:`,o),!1}else{const o=(i=this.localUsermediaStream)==null?void 0:i.getTracks().find(c=>c.kind==="video"),a=(s=this.transceivers.get(_o(Qt.Usermedia,"video")))==null?void 0:s.sender;return a==null||a.replaceTrack(o??null),this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}}async updateLocalUsermediaStream(e,t=!1,r=!1){const i=this.localUsermediaFeed,s=t||!i.isAudioMuted()&&!this.remoteOnHold,o=r||!i.isVideoMuted()&&!this.remoteOnHold;M.log(`Call ${this.callId} updateLocalUsermediaStream() running (streamId=${e.id}, audio=${s}, video=${o})`),er(e.getAudioTracks(),s),er(e.getVideoTracks(),o);for(const a of this.localUsermediaStream.getTracks())this.localUsermediaStream.removeTrack(a),a.stop();for(const a of e.getTracks())this.localUsermediaStream.addTrack(a);for(const a of e.getTracks()){const c=_o(Qt.Usermedia,a.kind),l=this.transceivers.get(c),u=l==null?void 0:l.sender;let h=!1;if(u)try{M.info(`Call ${this.callId} updateLocalUsermediaStream() replacing track (id=${a.id}, kind=${a.kind}, streamId=${e.id}, streamPurpose=${i.purpose})`),await u.replaceTrack(a),l.direction=l.direction==="inactive"?"sendonly":"sendrecv",h=!0}catch(p){M.warn(`Call ${this.callId} updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead`,p)}if(!h){M.info(`Call ${this.callId} updateLocalUsermediaStream() adding track to peer connection (id=${a.id}, kind=${a.kind}, streamId=${e.id}, streamPurpose=${i.purpose})`);const p=this.peerConn.addTrack(a,this.localUsermediaStream),m=this.peerConn.getTransceivers().find(v=>v.sender===p);m?this.transceivers.set(c,m):M.warn(`Call ${this.callId} updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!`)}}}async setLocalVideoMuted(e){var t,r;if(M.log(`Call ${this.callId} setLocalVideoMuted() running ${e}`),!e&&this.stopVideoTrackTimer!==void 0&&(clearTimeout(this.stopVideoTrackTimer),this.stopVideoTrackTimer=void 0),!await this.client.getMediaHandler().hasVideoDevice())return this.isLocalVideoMuted();if(!this.hasUserMediaVideoSender&&!e)return(t=this.localUsermediaFeed)==null||t.setAudioVideoMuted(null,e),await this.upgradeCall(!1,!0),this.isLocalVideoMuted();if(!e&&this.localUsermediaStream.getVideoTracks().length===0){const i=await this.client.getMediaHandler().getUserMediaStream(!0,!0);await this.updateLocalUsermediaStream(i)}return(r=this.localUsermediaFeed)==null||r.setAudioVideoMuted(null,e),this.updateMuteStatus(),await this.sendMetadataUpdate(),e&&(this.stopVideoTrackTimer=setTimeout(()=>{for(const i of this.localUsermediaStream.getVideoTracks())i.stop(),this.localUsermediaStream.removeTrack(i)},120)),this.isLocalVideoMuted()}isLocalVideoMuted(){var e;return((e=this.localUsermediaFeed)==null?void 0:e.isVideoMuted())??!1}async setMicrophoneMuted(e){var t;return M.log(`Call ${this.callId} setMicrophoneMuted() running ${e}`),await this.client.getMediaHandler().hasAudioDevice()?!e&&(!this.hasUserMediaAudioSender||!this.hasLocalUserMediaAudioTrack)?(await this.upgradeCall(!0,!1),this.isMicrophoneMuted()):((t=this.localUsermediaFeed)==null||t.setAudioVideoMuted(e,null),this.updateMuteStatus(),await this.sendMetadataUpdate(),this.isMicrophoneMuted()):this.isMicrophoneMuted()}isMicrophoneMuted(){var e;return((e=this.localUsermediaFeed)==null?void 0:e.isAudioMuted())??!1}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(const t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit("remote_hold_unhold",this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!=="connected")return!1;let e=!0;for(const t of this.peerConn.getTransceivers())["inactive","recvonly"].includes(t.currentDirection)||(e=!1);return e}sendDtmfDigit(e){var t;for(const r of this.peerConn.getSenders())if(((t=r.track)==null?void 0:t.kind)==="audio"&&r.dtmf){r.dtmf.insertDTMF(e);return}throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){const e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;M.log(`Call ${this.callId} updateMuteStatus stream ${this.localUsermediaStream.id} micShouldBeMuted ${e} vidShouldBeMuted ${t}`),er(this.localUsermediaStream.getAudioTracks(),!e),er(this.localUsermediaStream.getVideoTracks(),!t)}async sendMetadataUpdate(){await this.sendVoipEvent(ie.CallSDPStreamMetadataChangedPrefix,{[pl]:this.getLocalSDPStreamMetadata()})}gotCallFeedsForInvite(e,t=!1){if(this.successor){this.successor.queueGotCallFeedsForAnswer(e);return}if(this.callHasEnded()){this.stopAllMedia();return}for(const r of e)this.pushLocalFeed(r);t&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state="create_offer",M.debug(`Call ${this.callId} gotUserMediaForInvite() run`)}async sendAnswer(){const e={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[pl]:this.getLocalSDPStreamMetadata(!0)};e.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1};const t=this.discardDuplicateCandidates();M.info(`Call ${this.callId} sendAnswer() discarding ${t} candidates that will be sent in answer`);try{await this.sendVoipEvent(ie.CallAnswer,e),this.inviteOrAnswerSent=!0}catch(r){this.state="ringing",r instanceof mn&&r.event&&this.client.cancelPendingEvent(r.event);let i="send_answer",s="Failed to send answer";throw r.name=="UnknownDeviceError"&&(i="unknown_devices",s="Unknown devices present in the room"),this.emit("error",new rc(i,s,r),this),r}this.sendCandidateQueue()}queueGotCallFeedsForAnswer(e){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.gotCallFeedsForAnswer(e)):this.responsePromiseChain=this.gotCallFeedsForAnswer(e)}mungeSdp(e,t){const r=YR.parse(e.sdp);r.media.forEach(i=>{const s=new Map,o=new Map;for(const a of i.rtp)s.set(a.payload,a.codec),o.set(a.codec,a.payload);for(const a of t){if(a.mediaType!==i.type)continue;if(!o.has(a.codec)){M.info(`Call ${this.callId} mungeSdp() ignoring SDP modifications for ${a.codec} as it's not present.`);continue}const c=[];a.enableDtx!==void 0&&c.push(`usedtx=${a.enableDtx?"1":"0"}`),a.maxAverageBitrate!==void 0&&c.push(`maxaveragebitrate=${a.maxAverageBitrate}`);let l=!1;for(const u of i.fmtp)s.get(u.payload)===a.codec&&(l=!0,u.config+=";"+c.join(";"));l||i.fmtp.push({payload:o.get(a.codec),config:c.join(";")})}}),e.sdp=YR.write(r)}async createOffer(){const e=await this.peerConn.createOffer();return this.mungeSdp(e,E5(this.isPtt)),e}async createAnswer(){const e=await this.peerConn.createAnswer();return this.mungeSdp(e,E5(this.isPtt)),e}async gotCallFeedsForAnswer(e){if(this.callHasEnded())return;this.waitForLocalAVStream=!1;for(const r of e)this.pushLocalFeed(r);this.state="create_answer";let t;try{this.getRidOfRTXCodecs(),t=await this.createAnswer()}catch(r){M.debug(`Call ${this.callId} gotCallFeedsForAnswer() failed to create answer: `,r),this.terminate("local","create_answer",!0);return}try{if(await this.peerConn.setLocalDescription(t),this.callHasEnded()||(this.state="connecting",await new Promise(r=>{setTimeout(r,200)}),this.callHasEnded()))return;this.sendAnswer()}catch(r){M.debug(`Call ${this.callId} gotCallFeedsForAnswer() error setting local description!`,r),this.terminate("local","set_local_description",!0);return}}async onRemoteIceCandidatesReceived(e){if(this.callHasEnded())return;const t=e.getContent(),r=t.candidates;if(!r){M.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!`);return}const i=t.version===0?null:t.party_id||null;if(this.opponentPartyId===void 0){if(i){M.info(`Call ${this.callId} onRemoteIceCandidatesReceived() buffering ${r.length} candidates until we pick an opponent`);const s=this.remoteCandidateBuffer.get(i)||[];s.push(...r),this.remoteCandidateBuffer.set(i,s)}return}if(!this.partyIdMatches(t)){M.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates from party ID ${t.party_id}: we have chosen party ID ${this.opponentPartyId}`);return}await this.addIceCandidates(r)}async onAnswerReceived(e){const t=e.getContent();if(M.debug(`Call ${this.callId} onAnswerReceived() running (hangupParty=${t.party_id})`),this.callHasEnded()){M.debug(`Call ${this.callId} onAnswerReceived() ignoring answer because call has ended`);return}if(this.opponentPartyId!==void 0){M.info(`Call ${this.callId} onAnswerReceived() ignoring answer from party ID ${t.party_id}: we already have an answer/reject from ${this.opponentPartyId}`);return}this.chooseOpponent(e),await this.addBufferedIceCandidates(),this.state="connecting";const r=t[pl];r?this.updateRemoteSDPStreamMetadata(r):M.warn(`Call ${this.callId} onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams`);try{this.isSettingRemoteAnswerPending=!0,await this.peerConn.setRemoteDescription(t.answer),this.isSettingRemoteAnswerPending=!1,M.debug(`Call ${this.callId} onAnswerReceived() set remote description: ${t.answer.type}`)}catch(i){this.isSettingRemoteAnswerPending=!1,M.debug(`Call ${this.callId} onAnswerReceived() failed to set remote description`,i),this.terminate("local","set_remote_description",!1);return}if(this.opponentPartyId!==null)try{await this.sendVoipEvent(ie.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(i){M.warn(`Call ${this.callId} onAnswerReceived() failed to send select_answer event`,i)}}async onSelectAnswerReceived(e){if(this.direction!=="inbound"){M.warn(`Call ${this.callId} onSelectAnswerReceived() got select_answer for an outbound call: ignoring`);return}const t=e.getContent().selected_party_id;if(t==null){M.warn(`Call ${this.callId} onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring`);return}t!==this.ourPartyId&&(M.info(`Call ${this.callId} onSelectAnswerReceived() got select_answer for party ID ${t}: we are party ID ${this.ourPartyId}.`),await this.terminate("remote","answered_elsewhere",!0))}async onNegotiateReceived(e){var u;const t=e.getContent(),r=t.description;if(!r||!r.sdp||!r.type){M.info(`Call ${this.callId} onNegotiateReceived() ignoring invalid m.call.negotiate event`);return}const i=this.direction==="inbound",s=!this.makingOffer&&(this.peerConn.signalingState==="stable"||this.isSettingRemoteAnswerPending),o=r.type==="offer"&&!s;if(this.ignoreOffer=!i&&o,this.ignoreOffer){M.info(`Call ${this.callId} onNegotiateReceived() ignoring colliding negotiate event because we're impolite`);return}const a=this.isLocalOnHold(),c=t[pl];c?this.updateRemoteSDPStreamMetadata(c):M.warn(`Call ${this.callId} onNegotiateReceived() received negotiation event without SDPStreamMetadata!`);try{if(this.isSettingRemoteAnswerPending=r.type=="answer",await this.peerConn.setRemoteDescription(r),this.isSettingRemoteAnswerPending=!1,M.debug(`Call ${this.callId} onNegotiateReceived() set remote description: ${r.type}`),r.type==="offer"){let h;try{this.getRidOfRTXCodecs(),h=await this.createAnswer()}catch(p){M.debug(`Call ${this.callId} onNegotiateReceived() failed to create answer: `,p),this.terminate("local","create_answer",!0);return}await this.peerConn.setLocalDescription(h),M.debug(`Call ${this.callId} onNegotiateReceived() create an answer`),this.sendVoipEvent(ie.CallNegotiate,{lifetime:DT,description:(u=this.peerConn.localDescription)==null?void 0:u.toJSON(),[pl]:this.getLocalSDPStreamMetadata(!0)})}}catch(h){this.isSettingRemoteAnswerPending=!1,M.warn(`Call ${this.callId} onNegotiateReceived() failed to complete negotiation`,h)}const l=this.isLocalOnHold();a!==l&&(this.emit("local_hold_unhold",l,this),this.emit("hold_unhold",l))}updateRemoteSDPStreamMetadata(e){var t;this.remoteSDPStreamMetadata=bj(this.remoteSDPStreamMetadata||{},e,!0);for(const r of this.getRemoteFeeds()){const i=r.stream.id,s=this.remoteSDPStreamMetadata[i];r.setAudioVideoMuted(s==null?void 0:s.audio_muted,s==null?void 0:s.video_muted),r.purpose=(t=this.remoteSDPStreamMetadata[i])==null?void 0:t.purpose}}onSDPStreamMetadataChangedReceived(e){const r=e.getContent()[pl];this.updateRemoteSDPStreamMetadata(r)}async onAssertedIdentityReceived(e){const t=e.getContent();t.asserted_identity&&(this.remoteAssertedIdentity={id:t.asserted_identity.id,displayName:t.asserted_identity.display_name},this.emit("asserted_identity_changed",this))}callHasEnded(){return this.state==="ended"}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.wrappedGotLocalOffer()):this.responsePromiseChain=this.wrappedGotLocalOffer()}async wrappedGotLocalOffer(){this.makingOffer=!0;try{await this.gotLocalOffer()}catch(e){this.getLocalOfferFailed(e);return}finally{this.makingOffer=!1}}async gotLocalOffer(){var s,o;if(M.debug(`Call ${this.callId} gotLocalOffer() running`),this.callHasEnded()){M.debug(`Call ${this.callId} gotLocalOffer() ignoring newly created offer because the call has ended"`);return}let e;try{this.getRidOfRTXCodecs(),e=await this.createOffer()}catch(a){M.debug(`Call ${this.callId} gotLocalOffer() failed to create offer: `,a),this.terminate("local","create_offer",!0);return}try{await this.peerConn.setLocalDescription(e)}catch(a){M.debug(`Call ${this.callId} gotLocalOffer() error setting local description!`,a),this.terminate("local","set_local_description",!0);return}if(this.peerConn.iceGatheringState==="gathering"&&await new Promise(a=>{setTimeout(a,200)}),this.callHasEnded())return;const t=this.state==="create_offer"?ie.CallInvite:ie.CallNegotiate,r={lifetime:DT};t===ie.CallInvite&&this.invitee&&(r.invitee=this.invitee),this.state==="create_offer"?r.offer=(s=this.peerConn.localDescription)==null?void 0:s.toJSON():r.description=(o=this.peerConn.localDescription)==null?void 0:o.toJSON(),r.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},r[pl]=this.getLocalSDPStreamMetadata(!0);const i=this.discardDuplicateCandidates();M.info(`Call ${this.callId} gotLocalOffer() discarding ${i} candidates that will be sent in offer`);try{await this.sendVoipEvent(t,r)}catch(a){M.error(`Call ${this.callId} gotLocalOffer() failed to send invite`,a),a instanceof mn&&a.event&&this.client.cancelPendingEvent(a.event);let c="signalling_timeout",l="Signalling failed";this.state==="create_offer"&&(c="send_invite",l="Failed to send invite"),a.name=="UnknownDeviceError"&&(c="unknown_devices",l="Unknown devices present in the room"),this.emit("error",new rc(c,l,a),this),this.terminate("local",c,!1);return}this.sendCandidateQueue(),this.state==="create_offer"&&(this.inviteOrAnswerSent=!0,this.state="invite_sent",this.inviteTimeout=setTimeout(()=>{this.inviteTimeout=void 0,this.state==="invite_sent"&&this.hangup("invite_timeout",!1)},DT))}getRidOfRTXCodecs(){if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const e=this.transceivers.get(_o(Qt.Screenshare,"video"));if(!e||!e.setCodecPreferences)return;const t=RTCRtpReceiver.getCapabilities("video").codecs,r=RTCRtpSender.getCapabilities("video").codecs,i=[];for(const s of[...t,...r])if(s.mimeType!=="video/rtx"){i.push(s);try{e.setCodecPreferences(i)}catch(o){M.info("Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences",s,o),i.pop()}}}async sendVoipEvent(e,t){var i,s;const r={...t,version:Nse,call_id:this.callId,party_id:this.ourPartyId,conf_id:this.groupCallId};if(this.opponentDeviceId){const o=this.toDeviceSeq++,a={...r,device_id:this.client.deviceId,sender_session_id:this.client.getSessionId(),dest_session_id:this.opponentSessionId,seq:o,[cw]:lse()};this.emit("send_voip_event",{type:"toDevice",eventType:e,userId:this.invitee||((i=this.getOpponentMember())==null?void 0:i.userId),opponentDeviceId:this.opponentDeviceId,content:a},this);const c=this.invitee||this.getOpponentMember().userId;if(this.client.getUseE2eForGroupCall()){if(!this.hasOpponentDeviceInfo){M.warn(`Call ${this.callId} sendVoipEvent() failed: we do not have opponentDeviceInfo`);return}throw new Error("Unimplemented")}else await this.client.sendToDevice(e,new Map([[c,new Map([[this.opponentDeviceId,a]])]]))}else this.emit("send_voip_event",{type:"sendEvent",eventType:e,roomId:this.roomId,content:r,userId:this.invitee||((s=this.getOpponentMember())==null?void 0:s.userId)},this),await this.client.sendEvent(this.roomId,e,r)}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,this.state==="ringing"||!this.inviteOrAnswerSent)return;const t=this.direction==="inbound"?500:2e3;this.candidateSendTries===0&&setTimeout(()=>{this.sendCandidateQueue()},t)}discardDuplicateCandidates(){let e=0;const t=[];for(let r=0;r<this.candidateSendQueue.length;r++){const i=this.candidateSendQueue[r];i.candidate===""?t.push(i):e++}return this.candidateSendQueue=t,e}async transfer(e){const t=await this.client.getProfileInfo(e),r=zu(),i={replacement_id:zu(),target_user:{id:e,display_name:t.displayname,avatar_url:t.avatar_url},create_call:r};await this.sendVoipEvent(ie.CallReplaces,i),await this.terminate("local","transferred",!0)}async transferToCall(e){var l,u;const t=(l=e.getOpponentMember())==null?void 0:l.userId,r=t?await this.client.getProfileInfo(t):void 0,i=(u=this.getOpponentMember())==null?void 0:u.userId,s=i?await this.client.getProfileInfo(i):void 0,o=zu(),a={replacement_id:zu(),target_user:{id:i,display_name:s==null?void 0:s.displayname,avatar_url:s==null?void 0:s.avatar_url},await_call:o};await e.sendVoipEvent(ie.CallReplaces,a);const c={replacement_id:zu(),target_user:{id:t,display_name:r==null?void 0:r.displayname,avatar_url:r==null?void 0:r.avatar_url},create_call:o};await this.sendVoipEvent(ie.CallReplaces,c),await this.terminate("local","transferred",!0),await e.terminate("local","transferred",!0)}async terminate(e,t,r){var i;if(!this.callHasEnded()){this.hangupParty=e,this.hangupReason=t,this.state="ended",this.inviteTimeout&&(clearTimeout(this.inviteTimeout),this.inviteTimeout=void 0),this.iceDisconnectedTimeout!==void 0&&(clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0),this.callLengthInterval&&(clearInterval(this.callLengthInterval),this.callLengthInterval=void 0),this.stopVideoTrackTimer!==void 0&&(clearTimeout(this.stopVideoTrackTimer),this.stopVideoTrackTimer=void 0);for(const[s,o]of this.removeTrackListeners)s.removeEventListener("removetrack",o);this.removeTrackListeners.clear(),this.callStatsAtEnd=await this.collectCallStats(),this.stopAllMedia(),this.deleteAllFeeds(),this.peerConn&&this.peerConn.signalingState!=="closed"&&this.peerConn.close(),(i=this.stats)==null||i.removeStatsReportGatherer(this.callId),r&&this.emit("hangup",this),this.client.callEventHandler.calls.delete(this.callId)}}stopAllMedia(){M.debug(`Call ${this.callId} stopAllMedia() running`);for(const e of this.feeds)if(e.isLocal()&&e.purpose===Qt.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===Qt.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else if(!e.isLocal()){M.debug(`Call ${this.callId} stopAllMedia() stopping stream (streamId=${e.stream.id})`);for(const t of e.stream.getTracks())t.stop()}}checkForErrorListener(){if(this.listeners(nP.Error).length===0)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}async sendCandidateQueue(){if(this.candidateSendQueue.length===0||this.callHasEnded())return;const e=this.candidateSendQueue;this.candidateSendQueue=[],++this.candidateSendTries;const t={candidates:e.map(r=>r.toJSON())};this.candidatesEnded&&t.candidates.push({candidate:""}),M.debug(`Call ${this.callId} sendCandidateQueue() attempting to send ${e.length} candidates`);try{await this.sendVoipEvent(ie.CallCandidates,t),this.candidateSendTries=0,this.sendCandidateQueue()}catch(r){if(r instanceof mn&&r.event&&this.client.cancelPendingEvent(r.event),this.candidateSendQueue.push(...e),this.candidateSendTries>5){M.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates on attempt ${this.candidateSendTries}. Giving up on this call.`,r);const s="signalling_timeout",o="Signalling failed";this.emit("error",new rc(s,o,r),this),this.hangup(s,!1);return}const i=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,M.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates. Retrying in ${i}ms`,r),setTimeout(()=>{this.sendCandidateQueue()},i)}}async placeCall(e,t){if(!e)throw new Error("You CANNOT start a call without audio");this.state="wait_local_media";let r;try{const i=await this.client.getMediaHandler().getUserMediaStream(e,t);er(i.getAudioTracks(),!0),er(i.getVideoTracks(),!0),r=new hc({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId()??void 0,stream:i,purpose:Qt.Usermedia,audioMuted:!1,videoMuted:!1})}catch(i){this.getUserMediaFailed(i);return}try{await this.placeCallWithCallFeeds([r])}catch(i){this.placeCallFailed(i);return}}async placeCallWithCallFeeds(e,t=!1){this.checkForErrorListener(),this.direction="outbound",await this.initOpponentCrypto(),this.client.callEventHandler.calls.set(this.callId,this),await this.client.checkTurnServers()||M.warn(`Call ${this.callId} placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...`),this.peerConn=this.createPeerConnection(),this.emit("peer_connection_created",this.peerConn,this),this.gotCallFeedsForInvite(e,t)}createPeerConnection(){var i;const e=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers.length?this.turnServers:void 0,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});e.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),e.addEventListener("signalingstatechange",this.onSignallingStateChanged),e.addEventListener("icecandidate",this.gotLocalIceCandidate),e.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),e.addEventListener("track",this.onTrack),e.addEventListener("negotiationneeded",this.onNegotiationNeeded),e.addEventListener("datachannel",this.onDataChannel);const t=this.getOpponentMember(),r=t?t.userId:"unknown";return(i=this.stats)==null||i.addStatsReportGatherer(this.callId,r,e),e}partyIdMatches(e){return(e.version===0?null:e.party_id||null)===this.opponentPartyId}chooseOpponent(e){var r;const t=e.getContent();M.debug(`Call ${this.callId} chooseOpponent() running (partyId=${t.party_id})`),this.opponentVersion=t.version,this.opponentVersion===0?this.opponentPartyId=null:this.opponentPartyId=t.party_id||null,this.opponentCaps=t.capabilities||{},this.opponentMember=this.client.getRoom(this.roomId).getMember(e.getSender())??void 0,this.opponentMember&&((r=this.stats)==null||r.updateOpponentMember(this.callId,this.opponentMember.userId))}async addBufferedIceCandidates(){const e=this.remoteCandidateBuffer.get(this.opponentPartyId);e&&(M.info(`Call ${this.callId} addBufferedIceCandidates() adding ${e.length} buffered candidates for opponent ${this.opponentPartyId}`),await this.addIceCandidates(e)),this.remoteCandidateBuffer.clear()}async addIceCandidates(e){for(const t of e){(t.sdpMid===null||t.sdpMid===void 0)&&(t.sdpMLineIndex===null||t.sdpMLineIndex===void 0)?M.debug(`Call ${this.callId} addIceCandidates() got remote ICE end-of-candidates`):M.debug(`Call ${this.callId} addIceCandidates() got remote ICE candidate (sdpMid=${t.sdpMid}, candidate=${t.candidate})`);try{await this.peerConn.addIceCandidate(t)}catch(r){this.ignoreOffer?M.debug(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate because ignoring offer`,r):M.info(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate`,r)}}}get hasPeerConnection(){return!!this.peerConn}initStats(e,t="unknown"){this.stats=e,this.stats.start()}}function er(n,e){for(const t of n)t.enabled=e}function tk(){if(typeof window>"u"||typeof document>"u")return!1;try{if(!!!(window.RTCPeerConnection??window.RTCSessionDescription??window.RTCIceCandidate??navigator.mediaDevices))return M.error("WebRTC is not supported in this browser / environment"),!1}catch(n){return M.error("Exception thrown when trying to access WebRTC",n),!1}return!0}function av(n,e,t){if(!tk())return null;const r=t?t.forceTURN:!1,i={client:n,roomId:e,invitee:t==null?void 0:t.invitee,turnServers:n.getTurnServers(),forceTURN:n.forceTURN||r,opponentDeviceId:t==null?void 0:t.opponentDeviceId,opponentSessionId:t==null?void 0:t.opponentSessionId,groupCallId:t==null?void 0:t.groupCallId},s=new $se(i);return n.reEmitter.reEmit(s,Object.values(Bi)),s}var Sc=(n=>(n.DontNotify="dont_notify",n.Notify="notify",n.Coalesce="coalesce",n))(Sc||{}),mw=(n=>(n.Highlight="highlight",n.Sound="sound",n))(mw||{}),N$=(n=>(n.ExactEquals="==",n.LessThan="<",n.GreaterThan=">",n.GreaterThanOrEqual=">=",n.LessThanOrEqual="<=",n))(N$||{});const Bse="2";function Hse(n){return n==="==2"||n==="2"}var Hn=(n=>(n.EventMatch="event_match",n.EventPropertyIs="event_property_is",n.EventPropertyContains="event_property_contains",n.ContainsDisplayName="contains_display_name",n.RoomMemberCount="room_member_count",n.SenderNotificationPermission="sender_notification_permission",n.CallStarted="call_started",n.CallStartedPrefix="org.matrix.msc3914.call_started",n))(Hn||{}),pr=(n=>(n.Override="override",n.ContentSpecific="content",n.RoomSpecific="room",n.SenderSpecific="sender",n.Underride="underride",n))(pr||{}),fr=(n=>(n.Master=".m.rule.master",n.IsUserMention=".m.rule.is_user_mention",n.IsRoomMention=".m.rule.is_room_mention",n.ContainsDisplayName=".m.rule.contains_display_name",n.ContainsUserName=".m.rule.contains_user_name",n.AtRoomNotification=".m.rule.roomnotif",n.DM=".m.rule.room_one_to_one",n.EncryptedDM=".m.rule.encrypted_room_one_to_one",n.Message=".m.rule.message",n.EncryptedMessage=".m.rule.encrypted",n.InviteToSelf=".m.rule.invite_for_me",n.MemberEvent=".m.rule.member_event",n.IncomingCall=".m.rule.call",n.SuppressNotices=".m.rule.suppress_notices",n.Tombstone=".m.rule.tombstone",n.PollStart=".m.rule.poll_start",n.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",n.PollEnd=".m.rule.poll_end",n.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",n.PollStartOneToOne=".m.rule.poll_start_one_to_one",n.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",n.PollEndOneToOne=".m.rule.poll_end_one_to_one",n.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one",n))(fr||{});const C5=[pr.Override,pr.ContentSpecific,pr.RoomSpecific,pr.SenderSpecific,pr.Underride],Vse={".m.rule.is_room_mention":{rule_id:".m.rule.is_room_mention",default:!0,enabled:!0,conditions:[{kind:Hn.EventPropertyIs,key:"content.m\\.mentions.room",value:!0},{kind:Hn.SenderNotificationPermission,key:"room"}],actions:[Sc.Notify,{set_tweak:mw.Highlight}]},".m.rule.reaction":{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:Hn.EventMatch,key:"type",pattern:"m.reaction"}],actions:[Sc.DontNotify]},".org.matrix.msc3786.rule.room.server_acl":{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:Hn.EventMatch,key:"type",pattern:ie.RoomServerAcl},{kind:Hn.EventMatch,key:"state_key",pattern:""}],actions:[]}},CP=Symbol("UserDefinedRules"),Gse=[fr.Master,CP,fr.SuppressNotices,fr.InviteToSelf,fr.MemberEvent,fr.IsUserMention,fr.ContainsDisplayName,fr.IsRoomMention,fr.AtRoomNotification,fr.Tombstone,".m.rule.reaction",".m.rule.room.server_acl",".org.matrix.msc3786.rule.room.server_acl",".m.rule.suppress_edits"],qse={".org.matrix.msc3914.rule.room.call":{rule_id:".org.matrix.msc3914.rule.room.call",default:!0,enabled:!0,conditions:[{kind:Hn.EventMatch,key:"type",pattern:"org.matrix.msc3401.call"},{kind:Hn.CallStarted}],actions:[Sc.Notify,{set_tweak:mw.Sound,value:"default"}]}},Kse=[CP,fr.IncomingCall,".org.matrix.msc3914.rule.room.call",fr.EncryptedDM,fr.DM,fr.Message,fr.EncryptedMessage];function T5(n,e,t,r){const i=e.filter(l=>l.default),s=e.filter(l=>!l.default);function o(l){l===CP?c.push(...s):l in t?(M.warn(`Adding default global ${n} push rule ${l}`),c.push(t[l])):M.warn(`Missing default global ${n} push rule ${l}`)}let a=0;const c=[];for(const l of i){const u=r.indexOf(l.rule_id);if(u===-1){c.push(l);continue}for(;u>a;){const h=r[a];o(h),a+=1}c.push(l),a+=1}for(const l of r.slice(a))o(l);return c}const fa=class fa{constructor(e){this.client=e,this.parsedKeys=new Map}static actionListToActionsObject(e){const t={notify:!1,tweaks:{}};for(const r of e)r===Sc.Notify?t.notify=!0:typeof r=="object"&&(r.value===void 0&&(r.value=!0),t.tweaks[r.set_tweak]=r.value);return t}static rewriteDefaultRules(e,t=void 0){let r=JSON.parse(JSON.stringify(e));return r||(r={}),r.global||(r.global={}),r.global.override||(r.global.override=[]),r.global.underride||(r.global.underride=[]),r.global.override=T5(pr.Override,r.global.override,Vse,Gse),r.global.underride=T5(pr.Underride,r.global.underride,qse,Kse),r}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=[]);const t=new Set(this.parsedKeys.keys());for(const r of[e.global.override,e.global.room,e.global.sender,e.global.underride])for(const i of r)if(i.conditions)for(const s of i.conditions)s.kind===Hn.EventMatch&&(t.delete(s.key),this.parsedKeys.set(s.key,fa.partsForDottedKey(s.key)));t.forEach(r=>this.parsedKeys.delete(r))}matchingRuleFromKindSet(e,t){for(const r of C5){const i=t[r];if(i)for(const s of i){if(!s.enabled)continue;const o=this.templateRuleToRaw(r,s);if(o&&this.ruleMatchesEvent(o,e))return{...s,kind:r}}}return null}templateRuleToRaw(e,t){const r={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case pr.Underride:case pr.Override:r.conditions=t.conditions;break;case pr.RoomSpecific:if(!t.rule_id)return null;r.conditions.push({kind:Hn.EventMatch,key:"room_id",value:t.rule_id});break;case pr.SenderSpecific:if(!t.rule_id)return null;r.conditions.push({kind:Hn.EventMatch,key:"user_id",value:t.rule_id});break;case pr.ContentSpecific:if(!t.pattern)return null;r.conditions.push({kind:Hn.EventMatch,key:"content.body",pattern:t.pattern});break}return r}eventFulfillsCondition(e,t){switch(e.kind){case Hn.EventMatch:return this.eventFulfillsEventMatchCondition(e,t);case Hn.EventPropertyIs:return this.eventFulfillsEventPropertyIsCondition(e,t);case Hn.EventPropertyContains:return this.eventFulfillsEventPropertyContains(e,t);case Hn.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,t);case Hn.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,t);case Hn.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,t);case Hn.CallStarted:case Hn.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(e,t)}return!1}eventFulfillsSenderNotifPermCondition(e,t){const r=e.key;if(!r)return!1;const i=this.client.getRoom(t.getRoomId());return i!=null&&i.currentState?i.currentState.mayTriggerNotifOfType(r,t.getSender()):!1}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;const r=this.client.getRoom(t.getRoomId());if(!r||!r.currentState||!r.currentState.members)return!1;const i=r.currentState.getJoinedMemberCount(),s=e.is.match(/^([=<>]*)(\d*)$/);if(!s)return!1;const o=s[1],a=parseInt(s[2]);if(isNaN(a))return!1;switch(o){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 c;let r=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(r=t.getClearContent()),!r||!r.body||typeof r.body!="string")return!1;const i=this.client.getRoom(t.getRoomId()),s=(c=i==null?void 0:i.currentState)==null?void 0:c.getMember(this.client.credentials.userId);if(!s)return!1;const o=s.name,a=new RegExp("(^|\\W)"+vj(o)+"(\\W|$)","i");return r.body.search(a)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;const r=this.valueForDottedKey(e.key,t);if(typeof r!="string")return!1;if(e.value)return e.value===r;if(typeof e.pattern!="string")return!1;const i=e.key==="content.body"?this.createCachedRegex("(^|\\W)",e.pattern,"(\\W|$)"):this.createCachedRegex("^",e.pattern,"$");return!!r.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;const r=this.valueForDottedKey(e.key,t);return Array.isArray(r)?r.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"]||Cd(t.getPrevContent(),{}))}createCachedRegex(e,t,r){return fa.cachedGlobToRegex[t]||(fa.cachedGlobToRegex[t]=new RegExp(e+yj(t)+r,"i")),fa.cachedGlobToRegex[t]}static partsForDottedKey(e){const t=[];let r="",i=!1;for(const s of e){if(i){s==="\\"||s==="."?r+=s:r+="\\"+s,i=!1;continue}s=="."?(t.push(r),r=""):s=="\\"?i=!0:r+=s}return i&&(r+="\\"),t.push(r),t}valueForDottedKey(e,t){let r=this.parsedKeys.get(e);r===void 0&&(r=fa.partsForDottedKey(e),this.parsedKeys.set(e,r));let i;const s=r[0];let o=0;for(s==="content"?(i=t.getContent(),++o):s==="type"?(i=t.getType(),++o):i=t.event;o<r.length;++o){if(_j(i))return;const a=r[o];i=i[a]}return i}matchingRuleForEventWithRulesets(e,t){return!t||e.getSender()===this.client.getSafeUserId()?null:this.matchingRuleFromKindSet(e,t.global)}pushActionsForEventAndRulesets(e,t){const r=this.matchingRuleForEventWithRulesets(e,t);if(!r)return{};const i=fa.actionListToActionsObject(r.actions);return i.tweaks.highlight===void 0&&(i.tweaks.highlight=r.kind==pr.ContentSpecific),{actions:i,rule:r}}ruleMatchesEvent(e,t){var r;return this.client.supportsIntentionalMentions()&&t.getContent()["m.mentions"]!==void 0&&(e.rule_id===fr.ContainsUserName||e.rule_id===fr.ContainsDisplayName||e.rule_id===fr.AtRoomNotification)?!1:!((r=e.conditions)!=null&&r.some(i=>!this.eventFulfillsCondition(i,t)))}actionsForEvent(e){const{actions:t}=this.pushActionsForEventAndRulesets(e,this.client.pushRules);return t||{}}actionsAndRuleForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){const t=this.getPushRuleAndKindById(e);return(t==null?void 0:t.rule)??null}getPushRuleAndKindById(e){var t;for(const r of["global"])if(((t=this.client.pushRules)==null?void 0:t[r])!==void 0){for(const i of C5)if(this.client.pushRules[r][i]!==void 0){for(const s of this.client.pushRules[r][i])if(s.rule_id===e)return{rule:s,kind:i}}}return null}};fa.cachedGlobToRegex={};let Mb=fa;const cv=["v1.1","v1.2","v1.3","v1.4","v1.5","v1.6","v1.7","v1.8","v1.9"],Wse=cv[0],zse=cv[cv.length-1];var D$=(n=>(n.SUCCESS="SUCCESS",n.IGNORE="IGNORE",n.PROMPT="PROMPT",n.FAIL_PROMPT="FAIL_PROMPT",n.FAIL_ERROR="FAIL_ERROR",n))(D$||{}),TP=(n=>(n.Invalid="Invalid homeserver discovery response",n.GenericFailure="Failed to get autodiscovery configuration from server",n.InvalidHsBaseUrl="Invalid base_url for m.homeserver",n.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",n.InvalidIsBaseUrl="Invalid base_url for m.identity_server",n.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",n.InvalidIs="Invalid identity server discovery response",n.MissingWellknown="No .well-known JSON file found",n.InvalidJson="Invalid JSON",n.UnsupportedHomeserverSpecVersion="The homeserver does not meet the version requirements",n))(TP||{});const lt=class lt{static async fromDiscoveryConfig(e){var c;const t={"m.homeserver":{state:lt.FAIL_ERROR,error:lt.ERROR_INVALID,base_url:null},"m.identity_server":{state:lt.PROMPT,error:null,base_url:null}};if(!(e!=null&&e["m.homeserver"]))return M.error("No m.homeserver key in config"),t["m.homeserver"].state=lt.FAIL_PROMPT,t["m.homeserver"].error=lt.ERROR_INVALID,Promise.resolve(t);if(!e["m.homeserver"].base_url)return M.error("No m.homeserver base_url in config"),t["m.homeserver"].state=lt.FAIL_PROMPT,t["m.homeserver"].error=lt.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const r=this.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!r)return M.error("Invalid base_url for m.homeserver"),t["m.homeserver"].error=lt.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const i=await this.fetchWellKnownObject(`${r}/_matrix/client/versions`);if(!i||!Array.isArray((c=i.raw)==null?void 0:c.versions))return M.error("Invalid /versions response"),t["m.homeserver"].error=lt.ERROR_INVALID_HOMESERVER,t["m.homeserver"].base_url=r,Promise.resolve(t);const s=new Set(i.raw.versions);let o=!1;for(const l of cv)if(s.has(l)){o=!0;break}if(!o)return M.error("Homeserver does not meet version requirements"),t["m.homeserver"].error=lt.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION,t["m.homeserver"].base_url=r,Promise.resolve(t);t["m.homeserver"]={state:lt.SUCCESS,error:null,base_url:r};let a="";if(e["m.identity_server"]){const l={"m.homeserver":t["m.homeserver"],"m.identity_server":{state:lt.FAIL_PROMPT,error:lt.ERROR_INVALID_IS,base_url:null}};if(a=this.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!a)return M.error("Invalid base_url for m.identity_server"),l["m.identity_server"].error=lt.ERROR_INVALID_IS_BASE_URL,Promise.resolve(l);const u=await this.fetchWellKnownObject(`${a}/_matrix/identity/v2`);if(!(u!=null&&u.raw)||u.action!=="SUCCESS")return M.error("Invalid /v2 response"),l["m.identity_server"].error=lt.ERROR_INVALID_IDENTITY_SERVER,l["m.identity_server"].base_url=a,Promise.resolve(l)}return a&&a.toString().length>0&&(t["m.identity_server"]={state:lt.SUCCESS,error:null,base_url:a}),Object.keys(e).forEach(l=>{if(l==="m.homeserver"||l==="m.identity_server"){const u=["error","state","base_url"];for(const h of Object.keys(e[l]))u.includes(h)||(t[l][h]=e[l][h])}else t[l]=e[l]}),Promise.resolve(t)}static async findClientConfig(e){if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");const t={"m.homeserver":{state:lt.FAIL_ERROR,error:lt.ERROR_INVALID,base_url:null},"m.identity_server":{state:lt.PROMPT,error:null,base_url:null}},r=e.includes("://")?e:`https://${e}`,i=await this.fetchWellKnownObject(`${r}/.well-known/matrix/client`);return!i||i.action!=="SUCCESS"?(M.error("No response or error when parsing .well-known"),i.reason&&M.error(i.reason),i.action==="IGNORE"?t["m.homeserver"]={state:lt.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=lt.FAIL_PROMPT,t["m.homeserver"].error=lt.ERROR_INVALID),Promise.resolve(t)):lt.fromDiscoveryConfig(i.raw)}static async getRawClientConfig(e){if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");const t=await this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return t?t.raw??{}:{}}static sanitizeWellKnownUrl(e){if(!e)return!1;try{let t;try{t=new URL(e)}catch(o){M.error("Could not parse url",o)}if(!(t!=null&&t.hostname)||t.protocol!=="http:"&&t.protocol!=="https:")return!1;const r=t.port?`:${t.port}`:"",i=t.pathname?t.pathname:"";let s=`${t.protocol}//${t.hostname}${r}${i}`;return s.endsWith("/")&&(s=s.substring(0,s.length-1)),s}catch(t){return M.error(t),!1}}static fetch(e,t){return this.fetchFn?this.fetchFn(e,t):globalThis.fetch(e,t)}static setFetchFn(e){lt.fetchFn=e}static async fetchWellKnownObject(e){let t;try{if(t=await lt.fetch(e,{method:de.Get,signal:uw(5e3)}),t.status===404)return{raw:{},action:"IGNORE",reason:lt.ERROR_MISSING_WELLKNOWN};if(!t.ok)return{raw:{},action:"FAIL_PROMPT",reason:"General failure"}}catch(r){const i=r;let s="";return typeof i=="object"&&(s=i==null?void 0:i.message),{error:i,raw:{},action:"FAIL_PROMPT",reason:s||"General failure"}}try{return{raw:await t.json(),action:"SUCCESS"}}catch(r){const i=r;return{error:i,raw:{},action:"FAIL_PROMPT",reason:(i==null?void 0:i.name)==="SyntaxError"?lt.ERROR_INVALID_JSON:lt.ERROR_INVALID}}}};lt.ERROR_INVALID="Invalid homeserver discovery response",lt.ERROR_GENERIC_FAILURE="Failed to get autodiscovery configuration from server",lt.ERROR_INVALID_HS_BASE_URL="Invalid base_url for m.homeserver",lt.ERROR_INVALID_HOMESERVER="Homeserver URL does not appear to be a valid Matrix homeserver",lt.ERROR_INVALID_IS_BASE_URL="Invalid base_url for m.identity_server",lt.ERROR_INVALID_IDENTITY_SERVER="Identity server URL does not appear to be a valid identity server",lt.ERROR_INVALID_IS="Invalid identity server discovery response",lt.ERROR_MISSING_WELLKNOWN="No .well-known JSON file found",lt.ERROR_INVALID_JSON="Invalid JSON",lt.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION="The homeserver does not meet the version requirements",lt.ALL_ERRORS=Object.keys(TP),lt.FAIL_ERROR="FAIL_ERROR",lt.FAIL_PROMPT="FAIL_PROMPT",lt.PROMPT="PROMPT",lt.SUCCESS="SUCCESS";let lv=lt;var Nb=(n=>(n.IS="SERVICE_TYPE_IS",n.IM="SERVICE_TYPE_IM",n))(Nb||{});class Yse{constructor(e){this.ourEvent=e,this.ourEventIndex=0,this.paginateTokens={[bt.Backward]:null,[bt.Forward]:null},this.timeline=[e]}getEvent(){return this.timeline[this.ourEventIndex]}getTimeline(){return this.timeline}getOurEventIndex(){return this.ourEventIndex}getPaginateToken(e=!1){return this.paginateTokens[e?bt.Backward:bt.Forward]}setPaginateToken(e,t=!1){this.paginateTokens[t?bt.Backward:bt.Forward]=e??null}addEvents(e,t=!1){t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}class gw{constructor(e,t){this.rank=e,this.context=t}static fromJson(e,t){const r=e.context||{};let i=(r.events_before||[]).map(t),s=(r.events_after||[]).map(t);const o=new Yse(t(e.result)),a=o.ourEvent.threadRootId;return i=i.filter(c=>c.threadRootId===a),s=s.filter(c=>c.threadRootId===a),o.setPaginateToken(r.start,!0),o.addEvents(i,!0),o.addEvents(s,!1),o.setPaginateToken(r.end,!1),new gw(e.rank,o)}}var IP=(n=>(n.Public="public",n.Private="private",n))(IP||{}),ay=(n=>(n.PrivateChat="private_chat",n.TrustedPrivateChat="trusted_private_chat",n.PublicChat="public_chat",n))(ay||{}),wc=(n=>(n.Public="public",n.Invite="invite",n.Private="private",n.Knock="knock",n.Restricted="restricted",n))(wc||{}),F$=(n=>(n.RoomMembership="m.room_membership",n))(F$||{}),uv=(n=>(n.CanJoin="can_join",n.Forbidden="forbidden",n))(uv||{}),vw=(n=>(n.Invited="invited",n.Joined="joined",n.Shared="shared",n.WorldReadable="world_readable",n))(vw||{});function Xse(n,e){let t=!!e.preventReEmit;const r=e.decrypt!==!1;function i(s){const o=n.getRoom(s.room_id);let a;o&&s.state_key===void 0&&(a=o.findEventById(s.event_id)),!a||a.status?a=new Ji(s):(a.setUnsigned({...a.getUnsigned(),...s.unsigned}),t=!0);const c=a.getServerAggregatedRelation(sn.Replace);if(c!=null&&c.content){const u=i(c);a.makeReplaced(u)}const l=o==null?void 0:o.findThreadForEvent(a);return l&&a.setThread(l),a.isEncrypted()&&(t||n.reEmitter.reEmit(a,[pn.Decrypted]),r&&n.decryptEventIfNeeded(a)),t||(n.reEmitter.reEmit(a,[pn.Replaced,pn.VisibilityChange]),o==null||o.reEmitter.reEmit(a,[pn.BeforeRedaction])),a}return i}class I5{constructor(e,t,r){this.client=e,this.indexEvent=t,this.directory=r}get id(){const 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(){return this.indexEvent.getContent().version??1}get roomId(){return this.indexEvent.getRoomId()}async delete(){await this.client.sendStateEvent(this.roomId,dc.name,{},this.id),await this.client.redactEvent(this.roomId,this.id);const e=(await this.getVersionHistory())[1];e&&await e.delete()}getName(){return this.indexEvent.getContent().name||"Unnamed File"}async setName(e){await this.client.sendStateEvent(this.roomId,dc.name,{...this.indexEvent.getContent(),name:e},this.id)}isLocked(){return this.indexEvent.getContent().locked||!1}async setLocked(e){await this.client.sendStateEvent(this.roomId,dc.name,{...this.indexEvent.getContent(),locked:e},this.id)}async getFileInfo(){const t=(await this.getFileEvent()).getOriginalContent().file,r=this.client.mxcUrlToHttp(t.url);if(!r)throw new Error(`No HTTP URL available for ${t.url}`);return{info:t,httpUrl:r}}async getFileEvent(){const e=this.client.getRoom(this.roomId);if(!e)throw new Error("Unknown room");let t=e.getUnfilteredTimelineSet().findEventById(this.id);for(;!t&&e.getLiveTimeline().getState(Be.BACKWARDS).paginationToken;)await this.client.scrollback(e,100),t=e.getUnfilteredTimelineSet().findEventById(this.id);if(!t)throw new Error("Failed to find event");return await this.client.decryptEventIfNeeded(t),t}async createNewVersion(e,t,r,i){const s=await this.directory.createFile(e,t,r,{...i??{},"m.new_content":!0,"m.relates_to":{rel_type:sn.Replace,event_id:this.id}});return await this.client.sendStateEvent(this.roomId,dc.name,{active:!0,name:e,version:this.version+1},s.event_id),await this.client.sendStateEvent(this.roomId,dc.name,{...this.indexEvent.getContent(),active:!1},this.id),s}async getVersionHistory(){const e=[];e.push(this);const t=this.client.getRoom(this.roomId);if(!t)throw new Error("Invalid or unknown room");const r=[...t.getLiveTimeline().getEvents()].reverse();let i,s=await this.getFileEvent();do if(i=r.find(o=>o.replacingEventId()===s.getId()),i){const o=this.directory.getFile(i.getId());if(o)e.push(o),s=i;else break}while(i);return e}}const Jse={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[ie.RoomPowerLevels]:100,[ie.RoomHistoryVisibility]:100,[ie.RoomTombstone]:100,[ie.RoomEncryption]:100,[ie.RoomName]:50,[ie.RoomMessage]:50,[ie.RoomMessageEncrypted]:50,[ie.Sticker]:50},users:{}};class R5{constructor(e,t){if(this.client=e,this.roomId=t,this.room=this.client.getRoom(this.roomId),!this.room)throw new Error("Unknown room")}get id(){return this.roomId}get isTopLevel(){const e=this.room.currentState.getStateEvents(ie.SpaceParent);return e!=null&&e.length?e.every(t=>{var r;return!((r=t.getContent())!=null&&r.via)}):!0}async setName(e){await this.client.sendStateEvent(this.roomId,ie.RoomName,{name:e},"")}async invite(e,t=!0){const r=[this.retryInvite(e)];t&&r.push(...this.getDirectories().map(i=>i.invite(e,t))),await Promise.all(r)}retryInvite(e){return vre(async()=>{await this.client.invite(this.roomId,e).catch(t=>{throw(t==null?void 0:t.errcode)==="M_FORBIDDEN"?new mj.AbortError(t):t})})}async setPermissions(e,t){var l;const r=this.room.currentState.getStateEvents(ie.RoomPowerLevels,"");if(Array.isArray(r))throw new Error("Unexpected return type for power levels");const i=(r==null?void 0:r.getContent())||{},s=i.users_default||0,o=i.events_default||50,a=((l=i.events)==null?void 0:l[ie.RoomPowerLevels])||100,c=i.users||{};switch(t){case"viewer":c[e]=s;break;case"editor":c[e]=o;break;case"owner":c[e]=a;break;default:throw new Error("Invalid role: "+t)}i.users=c,await this.client.sendStateEvent(this.roomId,ie.RoomPowerLevels,i,"")}getPermissions(e){var c,l;const t=this.room.currentState.getStateEvents(ie.RoomPowerLevels,"");if(Array.isArray(t))throw new Error("Unexpected return type for power levels");const r=(t==null?void 0:t.getContent())||{},i=r.users_default||0,s=r.events_default||50,o=((c=r.events)==null?void 0:c[ie.RoomPowerLevels])||100,a=((l=r.users)==null?void 0:l[e])||i;return a>=o?"owner":a>=s?"editor":"viewer"}async createDirectory(e){const t=await this.client.unstableCreateFileTree(e);return await this.client.sendStateEvent(this.roomId,ie.SpaceChild,{via:[this.client.getDomain()]},t.roomId),await this.client.sendStateEvent(t.roomId,ie.SpaceParent,{via:[this.client.getDomain()]},this.roomId),t}getDirectories(){const e=[],t=this.room.currentState.getStateEvents(ie.SpaceChild);for(const r of t)try{const i=r.getStateKey();if(i){const s=this.client.unstableGetFileTreeSpace(i);s&&e.push(s)}}catch(i){M.warn("Unable to create tree space instance for listing. Are we joined?",i)}return e}getDirectory(e){return this.getDirectories().find(t=>t.roomId===e)}async delete(){const e=this.getDirectories();for(const i of e)await i.delete();const t=[We.Invite,We.Knock,We.Join],r=this.room.currentState.getStateEvents(ie.RoomMember);for(const i of r)if(i.getStateKey()!==this.client.getUserId()&&t.includes(i.getContent().membership)){const o=i.getStateKey();if(!o)throw new Error("State key not found for branch");await this.client.kick(this.roomId,o,"Room deleted")}await this.client.leave(this.roomId)}getOrderedChildren(e){const t=e.map(r=>({roomId:r.getStateKey(),order:r.getContent().order})).filter(r=>r.roomId);return t.sort((r,i)=>{var s,o;if(r.order&&!i.order)return-1;if(!r.order&&i.order)return 1;if(!r.order&&!i.order){const a=this.client.getRoom(r.roomId),c=this.client.getRoom(i.roomId);if(!a||!c)return p_(r.roomId,i.roomId);const l=((s=a.currentState.getStateEvents(ie.RoomCreate,""))==null?void 0:s.getTs())??0,u=((o=c.currentState.getStateEvents(ie.RoomCreate,""))==null?void 0:o.getTs())??0;return l===u?p_(r.roomId,i.roomId):l-u}else return p_(r.order,i.order)}),t}getParentRoom(){const t=this.room.currentState.getStateEvents(ie.SpaceParent)[0];if(!t)throw new Error("Expected to have a parent in a non-top level space");const r=t.getStateKey();if(!r)throw new Error("No state key found for parent");const i=this.client.getRoom(r);if(!i)throw new Error("Unable to locate room for parent");return i}getOrder(){if(this.isTopLevel)return-1;const t=this.getParentRoom().currentState.getStateEvents(ie.SpaceChild);return this.getOrderedChildren(t).findIndex(i=>i.roomId===this.roomId)}async setOrder(e){if(this.isTopLevel)throw new Error("Cannot set order of top level spaces currently");const t=this.getParentRoom(),r=t.currentState.getStateEvents(ie.SpaceChild),i=this.getOrderedChildren(r);e=Math.max(Math.min(e,i.length-1),0);const o=this.getOrder()<e;o&&e===i.length-1?e--:!o&&e===0&&e++;const a=i[o?e:e-1],c=i[o?e+1:e];let l=Ql[0],u=!1;if(!a)c!=null&&c.order&&(l=OM(c.order));else if(e===i.length-1)c!=null&&c.order&&(l=Tm(c.order));else{const m=a==null?void 0:a.order,v=c==null?void 0:c.order;m&&v?m===v?l=Tm(m):l=yre(m,v):m?l=Tm(m):v?l=OM(v):u=!0}if(u){let m;for(let v=0;v<=e;v++){const g=i[v];if(v===0&&(m=g.order),g.order)m=g.order;else{m=m?Tm(m):Ql[0];const S=t.currentState.getStateEvents(ie.SpaceChild,g.roomId),b=(S==null?void 0:S.getContent())??{via:[this.client.getDomain()]};await this.client.sendStateEvent(t.roomId,ie.SpaceChild,{...b,order:m},g.roomId)}}m&&(l=Tm(m))}const h=t.currentState.getStateEvents(ie.SpaceChild,this.roomId),p=(h==null?void 0:h.getContent())??{via:[this.client.getDomain()]};await this.client.sendStateEvent(t.roomId,ie.SpaceChild,{...p,order:l},this.roomId)}async createFile(e,t,r,i){const{content_uri:s}=await this.client.uploadContent(t,{includeFilename:!1});r.url=s;const o={msgtype:zo.File,body:e,url:s,file:r};i=i??{},i["m.new_content"]&&(i["m.new_content"]=o);const a=await this.client.sendMessage(this.roomId,{...i,...o,[Ej.name]:{}});return await this.client.sendStateEvent(this.roomId,dc.name,{active:!0,name:e},a.event_id),a}getFile(e){const t=this.room.currentState.getStateEvents(dc.name,e);return t?new I5(this.client,t,this):null}listFiles(){return this.listAllFiles().filter(e=>e.isActive)}listAllFiles(){return(this.room.currentState.getStateEvents(dc.name)??[]).map(t=>new I5(this.client,t,this))}}var RP=(n=>(n.Recent="recent",n.Rank="rank",n))(RP||{}),U$=(n=>(n.LocalStreamsChanged="local_streams_changed",n))(U$||{});class Zse extends Yn{constructor(e){super(),this.client=e,this.userMediaStreams=[],this.screensharingStreams=[]}restoreMediaSettings(e,t){this.audioInput=e,this.videoInput=t}async setAudioInput(e){M.info(`MediaHandler setAudioInput() running (deviceId=${e})`),this.audioInput!==e&&(this.audioInput=e,await this.updateLocalUsermediaStreams())}async setAudioSettings(e){M.info(`MediaHandler setAudioSettings() running (opts=${JSON.stringify(e)})`),this.audioSettings=Object.assign({},e),await this.updateLocalUsermediaStreams()}async setVideoInput(e){M.info(`MediaHandler setVideoInput() running (deviceId=${e})`),this.videoInput!==e&&(this.videoInput=e,await this.updateLocalUsermediaStreams())}async setMediaInputs(e,t){M.log(`MediaHandler setMediaInputs() running (audioInput: ${e} videoInput: ${t})`),this.audioInput=e,this.videoInput=t,await this.updateLocalUsermediaStreams()}async updateLocalUsermediaStreams(){if(this.userMediaStreams.length===0)return;const e=new Map;for(const t of this.client.callEventHandler.calls.values())e.set(t.callId,{audio:t.hasLocalUserMediaAudioTrack,video:t.hasLocalUserMediaVideoTrack});for(const t of this.userMediaStreams){M.log(`MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=${t.id})`);for(const r of t.getTracks())r.stop()}this.userMediaStreams=[],this.localUserMediaStream=void 0;for(const t of this.client.callEventHandler.calls.values()){if(t.callHasEnded()||!e.has(t.callId))continue;const{audio:r,video:i}=e.get(t.callId);M.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=${t.callId})`);const s=await this.getUserMediaStream(r,i);t.callHasEnded()||await t.updateLocalUsermediaStream(s)}for(const t of this.client.groupCallEventHandler.groupCalls.values()){if(!t.localCallFeed)continue;M.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=${t.groupCallId})`);const r=await this.getUserMediaStream(!0,t.type===pw.Video);t.state!==wP.Ended&&await t.updateLocalUsermediaStream(r)}this.emit("local_streams_changed")}async hasAudioDevice(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="audioinput").length>0}catch(e){return M.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}async hasVideoDevice(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(t=>t.kind==="videoinput").length>0}catch(e){return M.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}async getUserMediaStream(e,t,r=!0){return this.getMediaStreamPromise?this.getMediaStreamPromise=this.getMediaStreamPromise.then(()=>this.getUserMediaStreamInternal(e,t,r)):this.getMediaStreamPromise=this.getUserMediaStreamInternal(e,t,r),this.getMediaStreamPromise}async getUserMediaStreamInternal(e,t,r){var c,l,u,h,p;const i=e&&await this.hasAudioDevice(),s=t&&await this.hasVideoDevice();let o,a=!0;if(this.localUserMediaStream?(i!==this.localUserMediaStream.getAudioTracks().length>0&&(a=!1),s!==this.localUserMediaStream.getVideoTracks().length>0&&(a=!1),i&&((l=(c=this.localUserMediaStream.getAudioTracks()[0])==null?void 0:c.getSettings())==null?void 0:l.deviceId)!==this.audioInput&&(a=!1),s&&((h=(u=this.localUserMediaStream.getVideoTracks()[0])==null?void 0:u.getSettings())==null?void 0:h.deviceId)!==this.videoInput&&(a=!1)):a=!1,a){if(o=this.localUserMediaStream.clone(),M.log(`MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=${(p=this.localUserMediaStream)==null?void 0:p.id} newStreamId=${o.id} shouldRequestAudio=${i} shouldRequestVideo=${s})`),!i)for(const m of o.getAudioTracks())o.removeTrack(m);if(!s)for(const m of o.getVideoTracks())o.removeTrack(m)}else{const m=this.getUserMediaContraints(i,s);o=await navigator.mediaDevices.getUserMedia(m),M.log(`MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=${o.id}, shouldRequestAudio=${i}, shouldRequestVideo=${s}, constraints=${JSON.stringify(m)})`);for(const v of o.getTracks()){const g=v.getSettings();v.kind==="audio"?this.audioInput=g.deviceId:v.kind==="video"&&(this.videoInput=g.deviceId)}r&&(this.localUserMediaStream=o)}return r&&this.userMediaStreams.push(o),this.emit("local_streams_changed"),o}stopUserMediaStream(e){var r;M.log(`MediaHandler stopUserMediaStream() stopping (streamId=${e.id})`);for(const i of e.getTracks())i.stop();const t=this.userMediaStreams.indexOf(e);if(t!==-1&&(M.debug(`MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=${e.id})`,e.id),this.userMediaStreams.splice(t,1)),this.emit("local_streams_changed"),this.localUserMediaStream===e)this.localUserMediaStream=void 0;else for(const i of e.getTracks())if((r=this.localUserMediaStream)!=null&&r.getTrackById(i.id)){this.stopUserMediaStream(this.localUserMediaStream);break}}async getScreensharingStream(e={},t=!0){let r;if(this.screensharingStreams.length===0){const i=this.getScreenshareContraints(e);e.desktopCapturerSourceId?(M.debug(`MediaHandler getScreensharingStream() calling getUserMedia() (opts=${JSON.stringify(e)})`),r=await navigator.mediaDevices.getUserMedia(i)):(M.debug(`MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=${JSON.stringify(e)})`),r=await navigator.mediaDevices.getDisplayMedia(i))}else{const i=this.screensharingStreams[this.screensharingStreams.length-1];M.log(`MediaHandler getScreensharingStream() cloning (streamId=${i.id})`),r=i.clone()}return t&&this.screensharingStreams.push(r),this.emit("local_streams_changed"),r}stopScreensharingStream(e){M.debug(`MediaHandler stopScreensharingStream() stopping stream (streamId=${e.id})`);for(const r of e.getTracks())r.stop();const t=this.screensharingStreams.indexOf(e);t!==-1&&(M.debug(`MediaHandler stopScreensharingStream() splicing stream out (streamId=${e.id})`),this.screensharingStreams.splice(t,1)),this.emit("local_streams_changed")}stopAllStreams(){for(const e of this.userMediaStreams){M.log(`MediaHandler stopAllStreams() stopping (streamId=${e.id})`);for(const t of e.getTracks())t.stop()}for(const e of this.screensharingStreams)for(const t of e.getTracks())t.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0,this.emit("local_streams_changed")}getUserMediaContraints(e,t){const r=!!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:r?{exact:640}:{ideal:640},height:r?{exact:360}:{ideal:360}}:!1}}getScreenshareContraints(e){const{desktopCapturerSourceId:t,audio:r}=e;return t?{audio:r??!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t}}}:{audio:r??!1,video:!0}}}var nk=(n=>(n.RequestFinished="FINISHED",n.Complete="COMPLETE",n))(nk||{}),gp=(n=>(n.PreProcess="ExtState.PreProcess",n.PostProcess="ExtState.PostProcess",n))(gp||{}),Db=(n=>(n.RoomData="SlidingSync.RoomData",n.Lifecycle="SlidingSync.Lifecycle",n.List="SlidingSync.List",n))(Db||{});const Qse=3;class eoe{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return gp.PreProcess}onRequest(e){if(e)return{enabled:!0}}async onResponse(e){e.device_lists&&await this.crypto.processDeviceLists(e.device_lists),await this.crypto.processKeyCounts(e.device_one_time_keys_count,e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]),this.crypto.onSyncCompleted({})}}class toe{constructor(e,t){this.client=e,this.cryptoCallbacks=t,this.nextBatch=null}name(){return"to_device"}when(){return gp.PreProcess}onRequest(e){const t={since:this.nextBatch!==null?this.nextBatch:void 0};return e&&(t.limit=100,t.enabled=!0),t}async onResponse(e){const t=[];let r=e.events||[];r.length>0&&this.cryptoCallbacks&&(r=await this.cryptoCallbacks.preprocessToDeviceMessages(r)),r.map(I$).map(i=>{if(i.getType()==="m.key.verification.cancel"){const s=i.getContent().transaction_id;s&&t.push(s)}return i}).forEach(i=>{const s=i.getContent();if(i.getType()=="m.room.message"&&s.msgtype=="m.bad.encrypted"){M.log("Ignoring undecryptable to-device event from "+i.getSender());return}if(i.getType()==="m.key.verification.start"||i.getType()==="m.key.verification.request"){const o=s.transaction_id;t.includes(o)&&i.flagCancelled()}this.client.emit(Ge.ToDeviceEvent,i)}),this.nextBatch=e.next_batch}}class noe{constructor(e){this.client=e}name(){return"account_data"}when(){return gp.PostProcess}onRequest(e){if(e)return{enabled:!0}}async onResponse(e){e.global&&e.global.length>0&&this.processGlobalAccountData(e.global);for(const t in e.rooms){const r=bf(this.client,t,e.rooms[t]),i=this.client.getRoom(t);if(!i){M.warn("got account data for room but room doesn't exist on client:",t);continue}i.addAccountData(r),r.forEach(s=>{this.client.emit(Ge.Event,s)})}}processGlobalAccountData(e){const t=bf(this.client,void 0,e),r=t.reduce((i,s)=>(i[s.getType()]=this.client.store.getAccountData(s.getType()),i),{});this.client.store.storeAccountDataEvents(t),t.forEach(i=>{if(i.getType()===ie.PushRules){const o=i.getContent();this.client.setPushRules(o)}const s=r[i.getType()];return this.client.emit(Ge.AccountData,i,s),i})}}class roe{constructor(e){this.client=e}name(){return"typing"}when(){return gp.PostProcess}onRequest(e){if(e)return{enabled:!0}}async onResponse(e){if(e!=null&&e.rooms)for(const t in e.rooms)$$(this.client,t,[e.rooms[t]])}}class ioe{constructor(e){this.client=e}name(){return"receipts"}when(){return gp.PostProcess}onRequest(e){if(e)return{enabled:!0}}async onResponse(e){if(e!=null&&e.rooms)for(const t in e.rooms)$$(this.client,t,[e.rooms[t]])}}class j${constructor(e,t,r,i){this.slidingSync=e,this.client=t,this.syncState=null,this.lastPos=null,this.failCount=0,this.notifEvents=[],this.opts=E$(r),this.syncOpts=C$(i),t.getNotifTimelineSet()&&t.reEmitter.reEmit(t.getNotifTimelineSet(),[Xe.Timeline,Xe.TimelineReset]),this.slidingSync.on(Db.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(Db.RoomData,this.onRoomData.bind(this));const s=[new toe(this.client,this.syncOpts.cryptoCallbacks),new noe(this.client),new roe(this.client),new ioe(this.client)];this.syncOpts.cryptoCallbacks&&s.push(new eoe(this.syncOpts.cryptoCallbacks)),s.forEach(o=>{this.slidingSync.registerExtension(o)})}async onRoomData(e,t){let r=this.client.store.getRoom(e);if(!r){if(!t.initial){M.debug("initial flag not set but no stored room exists for room ",e,t);return}r=T$(this.client,e,this.opts)}await this.processRoomData(this.client,r,t)}onLifecycle(e,t,r){switch(r&&M.debug("onLifecycle",e,r),e){case nk.Complete:if(this.purgeNotifications(),!t)break;this.lastPos||this.updateSyncState(Pr.Prepared,{oldSyncToken:void 0,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(Pr.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.lastPos=t.pos;break;case nk.RequestFinished:if(r){if(this.failCount+=1,this.updateSyncState(this.failCount>Qse?Pr.Error:Pr.Reconnecting,{error:new mn(r)}),this.shouldAbortSync(new mn(r)))return}else this.failCount=0;break}}async syncLeftRooms(){return[]}async peek(e){return null}stopPeeking(){}setPresence(e){}getSyncState(){return this.syncState}getSyncStateData(){return this.syncStateData??null}createRoom(e){const{timelineSupport:t}=this.client,r=new hw(e,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t});return this.client.reEmitter.reEmit(r,[Xe.Name,Xe.Redaction,Xe.RedactionCancelled,Xe.Receipt,Xe.Tags,Xe.LocalEchoUpdated,Xe.AccountData,Xe.MyMembership,Xe.Timeline,Xe.TimelineReset]),this.registerStateListeners(r),r}registerStateListeners(e){this.client.reEmitter.reEmit(e.currentState,[It.Events,It.Members,It.NewMember,It.Update]),e.currentState.on(It.NewMember,(t,r,i)=>{i.user=this.client.getUser(i.userId)??void 0,this.client.reEmitter.reEmit(i,[Fo.Name,Fo.Typing,Fo.PowerLevel,Fo.Membership])})}shouldAbortSync(e){return e.errcode==="M_UNKNOWN_TOKEN"?(M.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(Pr.Error,{error:e}),!0):!1}async processRoomData(e,t,r){r=soe(e,t.roomId,r);const i=bf(this.client,t.roomId,r.required_state);let s=bf(this.client,t.roomId,r.timeline,!1);const o=[];if(r.initial){const l=new Set;t.getLiveTimeline().getEvents().forEach(m=>{l.add(m.getId())});const u=[],h=[];let p=!1;for(let m=s.length-1;m>=0;m--){const v=s[m];if(l.has(v.getId())){p=!0;continue}p?u.push(v):h.unshift(v)}s=h,u.length>0&&t.addEventsToTimeline(u,!0,!1,t.getLiveTimeline(),r.prev_batch)}const a=t.hasEncryptionStateEvent();if(r.notification_count!=null&&t.setUnreadNotificationCount(rr.Total,r.notification_count),r.highlight_count!=null&&(!a||a&&t.getUnreadNotificationCount(rr.Highlight)<=0)&&t.setUnreadNotificationCount(rr.Highlight,r.highlight_count),Number.isInteger(r.invited_count)&&t.currentState.setInvitedMemberCount(r.invited_count),Number.isInteger(r.joined_count)&&t.currentState.setJoinedMemberCount(r.joined_count),r.invite_state){const l=bf(this.client,t.roomId,r.invite_state);await this.injectRoomEvents(t,l),r.initial&&(t.recalculate(),this.client.store.storeRoom(t),this.client.emit(Ge.Room,t)),l.forEach(u=>{this.client.emit(Ge.Event,u)}),t.updateMyMembership(We.Invite);return}r.initial&&t.getLiveTimeline().setPaginationToken(r.prev_batch??null,Be.BACKWARDS),await this.injectRoomEvents(t,i,s,r.num_live),t.addEphemeralEvents(o),t.updateMyMembership(We.Join),t.recalculate(),r.initial&&(e.store.storeRoom(t),e.emit(Ge.Room,t)),this.addNotifications(s);const c=async l=>{e.emit(Ge.Event,l),l.isState()&&l.getType()==ie.RoomEncryption&&this.syncOpts.cryptoCallbacks&&await this.syncOpts.cryptoCallbacks.onCryptoEvent(t,l)};await af(i,c),await af(s,c),o.forEach(function(l){e.emit(Ge.Event,l)}),t.decryptCriticalEvents()}async injectRoomEvents(e,t,r=[],i=0){const s=e.getLiveTimeline(),o=s.getEvents().length==0;if(o){for(const c of t)this.client.getPushActionsForEvent(c);s.initialiseState(t)}o||(e.oldState.setStateEvents(t),e.currentState.setStateEvents(t));let a=[];i>0&&(a=r.slice(-1*i),r=r.slice(0,-1*a.length)),await e.addLiveEvents(r,{fromCache:!0,addToState:!1}),a.length>0&&await e.addLiveEvents(a,{fromCache:!1,addToState:!1}),e.recalculate(),this.resolveInvites(e)}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership(We.Invite).forEach(function(r){if(r.requestedProfileInfo)return;r.requestedProfileInfo=!0;const i=t.getUser(r.userId);let s;i?s=Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):s=t.getProfileInfo(r.userId),s.then(function(o){const a=r.events.member;a.getContent().membership===We.Invite&&(a.getContent().avatar_url=o.avatar_url,a.getContent().displayname=o.displayname,r.setMembershipEvent(a,e.currentState))},function(o){})})}retryImmediately(){return!0}async sync(){for(M.debug("Sliding sync init loop");!this.client.isGuest();)try{M.debug("Getting push rules...");const e=await this.client.getPushRules();M.debug("Got push rules"),this.client.pushRules=e;break}catch(e){if(M.error("Getting push rules failed",e),this.shouldAbortSync(e))return}await this.slidingSync.start()}stop(){M.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,t){const r=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(Ge.Sync,this.syncState,r,t)}addNotifications(e){if(this.client.getNotifTimelineSet())for(const t of e){const r=this.client.getPushActionsForEvent(t);r&&r.notify&&r.tweaks&&r.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.addLiveEvent(e,{addToState:!1})}),this.notifEvents=[]}}function soe(n,e,t){if(!t.name)return t;for(const r of t.required_state)if(r.type===ie.RoomName&&r.state_key==="")return r.content={name:t.name},t;return t.required_state.push({event_id:"$fake-sliding-sync-name-event-"+e,state_key:"",type:ie.RoomName,content:{name:t.name},sender:n.getUserId(),origin_server_ts:new Date().getTime()}),t}function bf(n,e,t,r=!0){const i=n.getEventMapper({decrypt:r});return t.map(function(s){return s.room_id=e,i(s)})}function $$(n,e,t){const r=bf(n,e,t),i=n.getRoom(e);if(!i){M.warn("got ephemeral events for room but room doesn't exist on client:",e);return}i.addEphemeralEvents(r),r.forEach(s=>{n.emit(Ge.Event,s)})}const kP=new Fn("m.beacon_info","org.matrix.msc3672.beacon_info"),rk=new Fn("m.beacon","org.matrix.msc3672.beacon");class qf{constructor(e=qf.RETRY_BACKOFF_RATELIMIT,t=qf.QUEUE_MESSAGES){this.retryAlgorithm=e,this.queueAlgorithm=t,this.queues={},this.activeQueues=[],this.procFn=null,this.processQueue=r=>{const i=this.peekNextEvent(r);if(!i){this.disableQueue(r);return}r1("Queue '%s' has %s pending events",r,this.queues[r].length),Promise.resolve().then(()=>this.procFn(i.event)).then(s=>{this.removeNextEvent(r),r1("Queue '%s' sent event %s",r,i.event.getId()),i.defer.resolve(s),this.processQueue(r)},s=>{i.attempts+=1;const o=this.retryAlgorithm(i.event,i.attempts,s);r1("retry(%s) err=%s event_id=%s waitTime=%s",i.attempts,s,i.event.getId(),o),o===-1?(M.info("Queue '%s' giving up on event %s",r,i.event.getId()),this.clearQueue(r,s)):setTimeout(this.processQueue,o,r)})}}static RETRY_BACKOFF_RATELIMIT(e,t,r){return h$(r,t,!1)}static QUEUE_MESSAGES(e){return e.getType()===ie.RoomMessage||e.hasAssociation()?"message":null}getQueueForEvent(e){const t=this.queueAlgorithm(e);return!t||!this.queues[t]?null:this.queues[t].map(function(r){return r.event})}removeEventFromQueue(e){const t=this.queueAlgorithm(e);if(!t||!this.queues[t])return!1;let r=!1;return _b(this.queues[t],i=>i.event.getId()===e.getId()?(r=!0,!0):!1),r}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){const t=this.queueAlgorithm(e);if(!t)return null;this.queues[t]||(this.queues[t]=[]);const r=Zl();return this.queues[t].push({event:e,defer:r,attempts:0}),r1("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),this.startProcessingQueues(),r.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){const t=this.activeQueues.indexOf(e);t>=0&&this.activeQueues.splice(t,1),M.info("Stopping queue '%s' as it is now empty",e)}clearQueue(e,t){M.info("clearing queue '%s'",e);let r;for(;r=this.removeNextEvent(e);)r.defer.reject(t);this.disableQueue(e)}peekNextEvent(e){const t=this.queues[e];if(Array.isArray(t))return t[0]}removeNextEvent(e){const t=this.queues[e];if(Array.isArray(t))return t.shift()}}function r1(...n){}const k5=20;class ooe{constructor(e){this.client=e,this.sending=!1,this.running=!0,this.retryTimeout=null,this.retryAttempts=0,this.sendQueue=async()=>{if(this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.sending||!this.running)return;M.debug("Attempting to send queued to-device messages"),this.sending=!0;let t;try{for(;this.running&&(t=await this.client.store.getOldestToDeviceBatch(),t!==null);)await this.sendBatch(t),await this.client.store.removeToDeviceBatch(t.id),this.retryAttempts=0;if(!this.running)return;M.debug("All queued to-device messages sent")}catch(r){++this.retryAttempts;const i=qf.RETRY_BACKOFF_RATELIMIT(null,this.retryAttempts,r);if(i===-1){Math.floor(r.httpStatus/100)===4?(M.error("Fatal error when sending to-device message - dropping to-device batch!",r),await this.client.store.removeToDeviceBatch(t.id)):M.info("Automatic retry limit reached for to-device messages.");return}M.info(`Failed to send batch of to-device messages. Will retry in ${i}ms`,r),this.retryTimeout=setTimeout(this.sendQueue,i)}finally{this.sending=!1}},this.onResumedSync=(t,r)=>{t===Pr.Syncing&&r!==Pr.Syncing&&(M.info("Resuming queue after resumed sync"),this.sendQueue())}}start(){this.running=!0,this.sendQueue(),this.client.on(Ge.Sync,this.onResumedSync)}stop(){this.running=!1,this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.client.removeListener(Ge.Sync,this.onResumedSync)}async queueBatch(e){const t=[];for(let r=0;r<e.batch.length;r+=k5){const i={eventType:e.eventType,batch:e.batch.slice(r,r+k5),txnId:this.client.makeTxnId()};t.push(i);const s=i.batch.map(o=>`${o.userId}/${o.deviceId} (msgid ${o.payload[cw]})`);M.info(`Enqueuing batch of to-device messages. type=${e.eventType} txnid=${i.txnId}`,s)}await this.client.store.saveToDeviceBatches(t),this.sendQueue()}async sendBatch(e){const t=new _c(()=>new Map);for(const r of e.batch)t.getOrCreate(r.userId).set(r.deviceId,r.payload);M.info(`Sending batch of ${e.batch.length} to-device messages with ID ${e.id} and txnId ${e.txnId}`),await this.client.sendToDevice(e.eventType,t,e.txnId)}}const FT=new ss.UnstableValue("m.policies","org.matrix.msc3847.policies"),i1=new ss.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites");var ik=(n=>(n.Ban="m.ban",n))(ik||{}),dd=(n=>(n.User="m.policy.user",n.Room="m.policy.room",n.Server="m.policy.server",n))(dd||{});const x5={[dd.User]:ie.PolicyRuleUser,[dd.Room]:ie.PolicyRuleRoom,[dd.Server]:ie.PolicyRuleServer};class aoe{constructor(e){this.client=e}async addRule(e,t,r){const i=await this.getOrCreateTargetRoom();return(await this.client.sendStateEvent(i.roomId,x5[e],{entity:t,reason:r,recommendation:ik.Ban})).event_id}async removeRule(e){await this.client.redactEvent(e.getRoomId(),e.getId())}async addSource(e){await this.client.joinRoom(e);const t=(await this.getOrCreateSourceRooms()).map(r=>r.roomId);return t.includes(e)?!1:(t.push(e),await this.withIgnoreInvitesPolicies(r=>{r.sources=t}),!0)}async getRuleForInvite({sender:e,roomId:t}){const r=await this.getOrCreateSourceRooms(),i=e.split(":")[1],s=t.split(":")[1];for(const o of r){const a=o.getUnfilteredTimelineSet().getLiveTimeline().getState(Be.FORWARDS);for(const{scope:c,entities:l}of[{scope:dd.Room,entities:[t]},{scope:dd.User,entities:[e]},{scope:dd.Server,entities:[i,s]}]){const u=a.getStateEvents(x5[c]);for(const h of u){const p=h.getContent();if((p==null?void 0:p.recommendation)!=ik.Ban)continue;const m=p==null?void 0:p.entity;if(!m)continue;let v;try{v=new RegExp(yj(m))}catch{continue}for(const g of l)if(g&&v.test(g))return h}}}return null}async getOrCreateTargetRoom(){let t=this.getIgnoreInvitesPolicies().target;if(typeof t!="string"&&(t=null),t){const r=this.client.getRoom(t);if(r)return r;t=null}return t=(await this.client.createRoom({name:"Individual Policy Room",preset:ay.PrivateChat})).room_id,await this.withIgnoreInvitesPolicies(r=>{r.target=t}),this.client.getRoom(t)}async getOrCreateSourceRooms(){let t=this.getIgnoreInvitesPolicies().sources,r=!1;Array.isArray(t)||(r=!0,t=[]);let i=t.filter(s=>typeof s=="string").map(s=>this.client.getRoom(s)).filter(s=>!!s);if(i.length!=t.length&&(r=!0),i.length==0){const s=await this.getOrCreateTargetRoom();r=!0,i=[s]}return r&&await this.withIgnoreInvitesPolicies(s=>{s.sources=t}),i}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}async withIgnoreInvitesPolicies(e){const{policies:t,ignoreInvitesPolicies:r}=this.getPoliciesAndIgnoreInvitesPolicies();e(r),t[i1.name]=r,await this.client.setAccountData(FT.name,t)}getPoliciesAndIgnoreInvitesPolicies(){var i;let e={};for(const s of[FT.name,FT.altName]){if(!s)continue;const o=(i=this.client.getAccountData(s))==null?void 0:i.getContent();if(o){e=o;break}}let t={},r=!1;for(const s of[i1.name,i1.altName]){if(!s)continue;const o=e[s];if(o&&typeof o=="object"){t=o,r=!0;break}}return r||(e[i1.name]=t),{policies:e,ignoreInvitesPolicies:t}}}const UT="matrix-js-sdk";function coe(n){if(n.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<n.length;l++){const u=n.charAt(l),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=l}const t=n.length,r=n.charAt(0),i=Math.log(t)/Math.log(256),s=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,h=0,p=0;const m=l.length;for(;p!==m&&l[p]===0;)p++,u++;const v=(m-p)*s+1>>>0,g=new Uint8Array(v);for(;p!==m;){let R=l[p],k=0;for(let I=v-1;(R!==0||k<h)&&I!==-1;I--,k++)R+=256*g[I]>>>0,g[I]=R%t>>>0,R=R/t>>>0;if(R!==0)throw new Error("Non-zero carry");h=k,p++}let S=v-h;for(;S!==v&&g[S]===0;)S++;let b=r.repeat(u);for(;S<v;++S)b+=n.charAt(g[S]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,h=0,p=0;for(;l[u]===r;)h++,u++;const m=(l.length-u)*i+1>>>0,v=new Uint8Array(m);for(;l[u];){let R=e[l.charCodeAt(u)];if(R===255)return;let k=0;for(let I=m-1;(R!==0||k<p)&&I!==-1;I--,k++)R+=t*v[I]>>>0,v[I]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");p=k,u++}let g=m-p;for(;g!==m&&v[g]===0;)g++;const S=new Uint8Array(h+(m-g));let b=h;for(;g!==m;)S[b++]=v[g++];return S}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var loe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const XGe=coe(loe);var cr=(n=>(n.UserTrustStatusChanged="userTrustStatusChanged",n.KeyBackupStatus="crypto.keyBackupStatus",n.KeyBackupFailed="crypto.keyBackupFailed",n.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",n.KeyBackupDecryptionKeyCached="crypto.keyBackupDecryptionKeyCached",n.VerificationRequestReceived="crypto.verificationRequestReceived",n.WillUpdateDevices="crypto.willUpdateDevices",n.DevicesUpdated="crypto.devicesUpdated",n.KeysChanged="crossSigning.keysChanged",n.LegacyCryptoStoreMigrationProgress="crypto.legacyCryptoStoreMigrationProgress",n.DehydratedDeviceCreated="dehydration.DehydratedDeviceCreated",n.DehydratedDeviceUploaded="dehydration.DehydratedDeviceUploaded",n.RehydrationStarted="dehydration.RehydrationStarted",n.RehydrationProgress="dehydration.RehydrationProgress",n.RehydrationCompleted="dehydration.RehydrationCompleted",n.RehydrationError="dehydration.RehydrationError",n.DehydrationKeyCached="dehydration.DehydrationKeyCached",n.DehydratedDeviceRotationError="dehydration.DehydratedDeviceRotationError",n))(cr||{}),sk=(n=>(n.MEGOLM_UNKNOWN_INBOUND_SESSION_ID="MEGOLM_UNKNOWN_INBOUND_SESSION_ID",n.MEGOLM_KEY_WITHHELD="MEGOLM_KEY_WITHHELD",n.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE="MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE",n.OLM_UNKNOWN_MESSAGE_INDEX="OLM_UNKNOWN_MESSAGE_INDEX",n.HISTORICAL_MESSAGE_NO_KEY_BACKUP="HISTORICAL_MESSAGE_NO_KEY_BACKUP",n.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED="HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED",n.HISTORICAL_MESSAGE_WORKING_BACKUP="HISTORICAL_MESSAGE_WORKING_BACKUP",n.HISTORICAL_MESSAGE_USER_NOT_JOINED="HISTORICAL_MESSAGE_USER_NOT_JOINED",n.SENDER_IDENTITY_PREVIOUSLY_VERIFIED="SENDER_IDENTITY_PREVIOUSLY_VERIFIED",n.UNSIGNED_SENDER_DEVICE="UNSIGNED_SENDER_DEVICE",n.UNKNOWN_SENDER_DEVICE="UNKNOWN_SENDER_DEVICE",n.UNKNOWN_ERROR="UNKNOWN_ERROR",n.MEGOLM_BAD_ROOM="MEGOLM_BAD_ROOM",n.MEGOLM_MISSING_FIELDS="MEGOLM_MISSING_FIELDS",n.OLM_DECRYPT_GROUP_MESSAGE_ERROR="OLM_DECRYPT_GROUP_MESSAGE_ERROR",n.OLM_BAD_ENCRYPTED_MESSAGE="OLM_BAD_ENCRYPTED_MESSAGE",n.OLM_BAD_RECIPIENT="OLM_BAD_RECIPIENT",n.OLM_BAD_RECIPIENT_KEY="OLM_BAD_RECIPIENT_KEY",n.OLM_BAD_ROOM="OLM_BAD_ROOM",n.OLM_BAD_SENDER_CHECK_FAILED="OLM_BAD_SENDER_CHECK_FAILED",n.OLM_BAD_SENDER="OLM_BAD_SENDER",n.OLM_FORWARDED_MESSAGE="OLM_FORWARDED_MESSAGE",n.OLM_MISSING_CIPHERTEXT="OLM_MISSING_CIPHERTEXT",n.OLM_NOT_INCLUDED_IN_RECIPIENTS="OLM_NOT_INCLUDED_IN_RECIPIENTS",n.UNKNOWN_ENCRYPTION_ALGORITHM="UNKNOWN_ENCRYPTION_ALGORITHM",n))(sk||{}),uoe=(n=>(n[n.AllDevicesIsolationMode=0]="AllDevicesIsolationMode",n[n.OnlySignedDevicesIsolationMode=1]="OnlySignedDevicesIsolationMode",n))(uoe||{});class JGe{constructor(e){this.errorOnVerifiedUserProblems=e,this.kind=0}}class ZGe{constructor(e,t,r,i=!1){this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=r,this.needsUserApproval=i}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}class QGe{constructor(e){this.signedByOwner=e.signedByOwner??!1,this.crossSigningVerified=e.crossSigningVerified??!1,this.tofu=e.tofu??!1,this.localVerified=e.localVerified??!1,this.trustCrossSignedDevices=e.trustCrossSignedDevices??!1}isVerified(){return this.localVerified||this.trustCrossSignedDevices&&this.crossSigningVerified}}var doe=(n=>(n.Fetch="fetch",n.LoadKeys="load_keys",n))(doe||{}),hoe=(n=>(n.Master="master",n.SelfSigning="self_signing",n.UserSigning="user_signing",n))(hoe||{}),foe=(n=>(n[n.NONE=0]="NONE",n[n.GREY=1]="GREY",n[n.RED=2]="RED",n))(foe||{}),poe=(n=>(n[n.UNKNOWN=0]="UNKNOWN",n[n.UNVERIFIED_IDENTITY=1]="UNVERIFIED_IDENTITY",n[n.UNSIGNED_DEVICE=2]="UNSIGNED_DEVICE",n[n.UNKNOWN_DEVICE=3]="UNKNOWN_DEVICE",n[n.AUTHENTICITY_NOT_GUARANTEED=4]="AUTHENTICITY_NOT_GUARANTEED",n[n.MISMATCHED_SENDER_KEY=5]="MISMATCHED_SENDER_KEY",n[n.SENT_IN_CLEAR=6]="SENT_IN_CLEAR",n[n.VERIFICATION_VIOLATION=7]="VERIFICATION_VIOLATION",n))(poe||{});const moe=new Uint8Array(8);async function B$(n,e){const t=await globalThis.crypto.subtle.importKey("raw",n,{name:"HKDF"},!1,["deriveBits"]),r=await globalThis.crypto.subtle.deriveBits({name:"HKDF",salt:moe,info:new TextEncoder().encode(e),hash:"SHA-256"},t,512),i=r.slice(0,32),s=r.slice(32),o=globalThis.crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["encrypt","decrypt"]),a=globalThis.crypto.subtle.importKey("raw",s,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([o,a])}async function H$(n,e,t,r){let i;r?i=_f(r):(i=new Uint8Array(16),globalThis.crypto.getRandomValues(i),i[8]&=127);const[s,o]=await B$(e,t),a=new TextEncoder().encode(n),c=await globalThis.crypto.subtle.encrypt({name:"AES-CTR",counter:i,length:64},s,a),l=await globalThis.crypto.subtle.sign({name:"HMAC"},o,c);return{iv:y_(i),ciphertext:y_(new Uint8Array(c)),mac:y_(new Uint8Array(l))}}async function goe(n,e,t){const[r,i]=await B$(e,t),s=_f(n.ciphertext);if(!await globalThis.crypto.subtle.verify({name:"HMAC"},i,_f(n.mac),s))throw new Error(`Error decrypting secret ${t}: bad MAC`);const o=await globalThis.crypto.subtle.decrypt({name:"AES-CTR",counter:_f(n.iv),length:64},r,s);return new TextDecoder().decode(new Uint8Array(o))}const Yu="m.secret_storage.v1.aes-hmac-sha2";class V${constructor(e,t){this.accountDataAdapter=e,this.callbacks=t}async getDefaultKeyId(){const e=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return e?e.key??null:null}setDefaultKeyId(e){return new Promise((t,r)=>{const i=o=>{if(o.getType()!=="m.secret_storage.default_key")return;const a=o.getContent();(e===null?Object.keys(a).length===0:a.key===e)&&(this.accountDataAdapter.removeListener(Ge.AccountData,i),t())};this.accountDataAdapter.on(Ge.AccountData,i);const s=e===null?{}:{key:e};this.accountDataAdapter.setAccountData("m.secret_storage.default_key",s).catch(o=>{this.accountDataAdapter.removeListener(Ge.AccountData,i),r(o)})})}async addKey(e,t,r){if(e!==Yu)throw new Error(`Unknown key algorithm ${e}`);const i={algorithm:e};t.name&&(i.name=t.name),t.passphrase&&(i.passphrase=t.passphrase);const{iv:s,mac:o}=await ak(t.key);if(i.iv=s,i.mac=o,!r)do r=Es(32);while(await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${r}`));return await this.accountDataAdapter.setAccountData(`m.secret_storage.key.${r}`,i),{keyId:r,keyInfo:i}}async getKey(e){if(e||(e=await this.getDefaultKeyId()),!e)return null;const t=await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${e}`);return t?[e,t]:null}async hasKey(e){return!!await this.getKey(e)}async checkKey(e,t){if(t.algorithm===Yu)if(t.mac){const{mac:r}=await ak(e,t.iv);return ok(t.mac)===ok(r)}else return!0;else throw new Error("Unknown algorithm")}async store(e,t,r){if(t===null){await this.accountDataAdapter.setAccountData(e,{});return}const i={};if(!r){const s=await this.getDefaultKeyId();if(!s)throw new Error("No keys specified and no default key present");r=[s]}if(r.length===0)throw new Error("Zero keys given to encrypt with!");for(const s of r){const o=await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${s}`);if(!o)throw new Error("Unknown key: "+s);if(o.algorithm===Yu){const a={[s]:o},[,c]=await this.getSecretStorageKey(a,e);i[s]=await c.encrypt(t)}else M.warn("unknown algorithm for secret storage key "+s+": "+o.algorithm)}await this.accountDataAdapter.setAccountData(e,{encrypted:i})}async get(e){const t=await this.accountDataAdapter.getAccountDataFromServer(e);if(!t)return;if(!t.encrypted)throw new Error("Content is not encrypted!");const r={};for(const a of Object.keys(t.encrypted)){const c=await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${a}`),l=t.encrypted[a];(c==null?void 0:c.algorithm)===Yu&&l.iv&&l.ciphertext&&l.mac&&(r[a]=c)}if(Object.keys(r).length===0)throw new Error(`Could not decrypt ${e} because none of the keys it is encrypted with are for a supported algorithm`);const[i,s]=await this.getSecretStorageKey(r,e),o=t.encrypted[i];return s.decrypt(o)}async isStored(e){const t=await this.accountDataAdapter.getAccountDataFromServer(e);if(!(t!=null&&t.encrypted))return null;const r={};for(const i of Object.keys(t.encrypted)){const s=await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${i}`);if(!s)continue;const o=t.encrypted[i];s.algorithm===Yu&&o.iv&&o.ciphertext&&o.mac&&(r[i]=s)}return Object.keys(r).length?r:null}async getSecretStorageKey(e,t){if(!this.callbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");const r=await this.callbacks.getSecretStorageKey({keys:e},t);if(!r)throw new Error("getSecretStorageKey callback returned falsey");if(r.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[i,s]=r;if(!e[i])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[i].algorithm===Yu)return[i,{encrypt:function(a){return H$(a,s,t)},decrypt:function(a){return goe(a,s,t)}}];throw new Error("Unknown key type: "+e[i].algorithm)}}function ok(n){let e=n.length;for(;e>=1&&n.charCodeAt(e-1)==61;)e--;return e<n.length?n.substring(0,e):n}const voe="\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 ak(n,e){return H$(voe,n,"",e)}const yoe=Object.freeze(Object.defineProperty({__proto__:null,SECRET_STORAGE_ALGORITHM_V1_AES:Yu,ServerSideSecretStorageImpl:V$,calculateKeyCheck:ak,trimTrailingEquals:ok},Symbol.toStringTag,{value:"Module"})),G$=n=>n.type==="livekit"&&"livekit_service_url"in n,ck=n=>G$(n)&&"livekit_alias"in n,xP=n=>n.type==="livekit"&&"focus_selection"in n,PP=1e3*60*60*4,_oe=(n,e)=>{var r;const t="Malformed session membership event: ";return typeof n.device_id!="string"&&e.push(t+"device_id must be string"),typeof n.call_id!="string"&&e.push(t+"call_id must be string"),typeof n.application!="string"&&e.push(t+"application must be a string"),typeof((r=n.focus_active)==null?void 0:r.type)!="string"&&e.push(t+"focus_active.type must be a string"),Array.isArray(n.foci_preferred)||e.push(t+"foci_preferred must be an array"),n.created_ts&&typeof n.created_ts!="number"&&e.push(t+"created_ts must be number"),n.scope&&typeof n.scope!="string"&&e.push(t+"scope must be string"),e.length===0};class P5{constructor(e,t){this.parentEvent=e;const r=[];if(_oe(t,r))this.membershipData=t;else throw Error(`unknown CallMembership data. Does not match MSC4143 call.member (${r.join(" & ")}) events this could be a legacy membership event: (${t})`)}static equal(e,t){return Cd(e.membershipData,t.membershipData)}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 this.createdTs().toString()}createdTs(){return this.membershipData.created_ts??this.parentEvent.getTs()}getAbsoluteExpiry(){return this.createdTs()+(this.membershipData.expires??PP)}getMsUntilExpiry(){return this.getAbsoluteExpiry()-Date.now()}isExpired(){return this.getMsUntilExpiry()<=0}getPreferredFoci(){return this.membershipData.foci_preferred}getFocusSelection(){const e=this.membershipData.focus_active;if(xP(e))return e.focus_selection}}var Vl=(n=>(n.Cancel="cancel",n.Restart="restart",n.Send="send",n))(Vl||{}),LP=(n=>(n.TooNew="TOO_NEW",n))(LP||{});const H4=class H4 extends Error{constructor(e){const t=`Crypto store is invalid because ${e}, please stop the client, delete all data and start the client again`;super(t),this.reason=e,this.name="InvalidCryptoStoreError"}};H4.TOO_NEW="TOO_NEW";let Fb=H4;class boe extends Error{constructor(e,t){super(e),this.value=t}}class Soe extends Error{constructor(){super("MatrixClient has been stopped")}}class Nl extends Error{constructor(e,t){super(e),this.clientEndpoint=t,this.name="UnsupportedDelayedEventsEndpointError"}}const s1=M.getChild("MatrixRTCSession");class woe{constructor(e){this.membershipLoopHandler=e,this.running=!1,this.wakeup=t=>{s1.error("Cannot call wakeup before calling `startWithJoin()`")},this._actions=[]}get actions(){return this._actions}async startWithJoin(){if(this.running){s1.error("Cannot call startWithJoin() on NewMembershipActionScheduler while already running");return}this.running=!0,this._actions=[{ts:Date.now(),type:__.SendFirstDelayedEvent}];try{for(;this._actions.length>0;){this._actions.sort((o,a)=>o.ts-a.ts);const e=this._actions[0];let t;const r=new Promise(o=>{this.wakeup=a=>{t=a,o()}});e.ts>Date.now()&&await Promise.race([r,Td(e.ts-Date.now())]);let i={};if(!t){s1.debug(`Current MembershipManager processing: ${e.type}
|
|
32
32
|
Queue:`,this._actions,`
|
|
33
|
-
Date.now: "${Date.now()}`);try{i=await this.membershipLoopHandler(e.type)}catch(o){throw Error(`The MembershipManager shut down because of the end condition: ${o}`)}}this._actions.splice(0,1);const s=t??i;"replace"in s?this._actions=s.replace:"insert"in s&&this._actions.push(...s.insert)}}finally{this.running=!1}s1.debug("Leave MembershipManager ActionScheduler loop (no more actions)")}initiateJoin(){var e;(e=this.wakeup)==null||e.call(this,{replace:[{ts:Date.now(),type:__.SendFirstDelayedEvent}]})}initiateLeave(){var e;(e=this.wakeup)==null||e.call(this,{replace:[{ts:Date.now(),type:__.SendScheduledDelayedLeaveEvent}]})}}const ar=M.getChild("MatrixRTCSession");var __=(n=>(n.SendFirstDelayedEvent="SendFirstDelayedEvent",n.SendJoinEvent="SendJoinEvent",n.RestartDelayedEvent="RestartDelayedEvent",n.UpdateExpiry="UpdateExpiry",n.SendMainDelayedEvent="SendMainDelayedEvent",n.SendScheduledDelayedLeaveEvent="SendScheduledDelayedLeaveEvent",n.SendLeaveEvent="SendLeaveEvent",n))(__||{});class Ub{constructor(e,t,r,i){this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,this.activated=!1,this.scheduler=new woe(a=>(this.oldStatus&&ar.debug(`MembershipManager applied action changes. Status: ${this.oldStatus} -> ${this.status}`),this.oldStatus=this.status,ar.debug(`MembershipManager before processing action. status=${this.oldStatus}`),this.membershipLoopHandler(a)));const[s,o]=[this.client.getUserId(),this.client.getDeviceId()];if(s===null)throw Error("Missing userId in client");if(o===null)throw Error("Missing deviceId in client");this.deviceId=o,this.stateKey=this.makeMembershipStateKey(s,o),this.state=Ub.defaultState}isJoined(){return this.activated}join(e,t,r){if(this.scheduler.running){ar.error("MembershipManager is already running. Ignoring join request.");return}this.fociPreferred=e,this.focusActive=t,this.leavePromiseDefer=void 0,this.activated=!0,this.state=Ub.defaultState,this.scheduler.startWithJoin().then(()=>{var i;this.scheduler.running||((i=this.leavePromiseDefer)==null||i.resolve(!0),this.leavePromiseDefer=void 0)}).catch(i=>{ar.error("MembershipManager stopped because: ",i),r==null||r(i)}).finally(()=>this.activated=!1)}leave(e){return this.scheduler.running?(this.leavePromiseDefer||(this.leavePromiseDefer=Zl(),this.activated=!1,this.scheduler.initiateLeave(),e&&setTimeout(()=>{var t;return(t=this.leavePromiseDefer)==null?void 0:t.resolve(!1)},e)),this.leavePromiseDefer.promise):(ar.warn("Called MembershipManager.leave() even though the MembershipManager is not running"),Promise.resolve(!0))}async onRTCSessionMemberUpdate(e){const t=r=>r.sender===this.client.getUserId()&&r.deviceId===this.client.getDeviceId();if(this.isJoined()&&!e.some(t)){const r=["SendFirstDelayedEvent","SendJoinEvent"];ar.warn("Missing own membership: force re-join"),this.scheduler.actions.find(i=>r.includes(i.type))?ar.error("NewMembershipManger tried adding another `SendFirstDelayedEvent` actions even though we already have one in the Queue\nActionQueueOnMemberUpdate:",this.scheduler.actions):(this.state.hasMemberStateEvent=!1,this.scheduler.initiateJoin())}return Promise.resolve()}getActiveFocus(){if(this.focusActive)if(xP(this.focusActive)){if(this.focusActive.focus_selection==="oldest_membership"){const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else ar.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}static get defaultState(){return{hasMemberStateEvent:!1,delayId:void 0,startTime:0,rateLimitRetries:new Map,networkErrorRetries:new Map,expireUpdateIterations:1}}get callMemberEventRetryDelayMinimum(){var e;return((e=this.joinConfig)==null?void 0:e.callMemberEventRetryDelayMinimum)??3e3}get membershipEventExpiryTimeout(){var e;return((e=this.joinConfig)==null?void 0:e.membershipExpiryTimeout)??PP}get membershipEventExpiryTimeoutHeadroom(){var e;return((e=this.joinConfig)==null?void 0:e.membershipExpiryTimeoutHeadroom)??5e3}computeNextExpiryActionTs(e){return this.state.startTime+this.membershipEventExpiryTimeout*e-this.membershipEventExpiryTimeoutHeadroom}get membershipServerSideExpiryTimeout(){var e;return this.membershipServerSideExpiryTimeoutOverride??((e=this.joinConfig)==null?void 0:e.membershipServerSideExpiryTimeout)??8e3}get membershipKeepAlivePeriod(){var e;return((e=this.joinConfig)==null?void 0:e.membershipKeepAlivePeriod)??5e3}get maximumRateLimitRetryCount(){var e;return((e=this.joinConfig)==null?void 0:e.maximumRateLimitRetryCount)??10}get maximumNetworkErrorRetryCount(){var e;return((e=this.joinConfig)==null?void 0:e.maximumNetworkErrorRetryCount)??10}async membershipLoopHandler(e){switch(this.oldStatus=this.status,e){case"SendFirstDelayedEvent":return this.state.delayId?this.cancelKnownDelayIdBeforeSendFirstDelayedEvent(this.state.delayId):this.sendFirstDelayedLeaveEvent();case"RestartDelayedEvent":return this.state.delayId?this.restartDelayedEvent(this.state.delayId):fs(this.state.hasMemberStateEvent?"SendMainDelayedEvent":"SendFirstDelayedEvent");case"SendMainDelayedEvent":return this.sendMainDelayedEvent();case"SendScheduledDelayedLeaveEvent":return this.state.hasMemberStateEvent?this.state.delayId?this.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(this.state.delayId):fs("SendLeaveEvent"):{replace:[]};case"SendJoinEvent":return this.sendJoinEvent();case"UpdateExpiry":return this.updateExpiryOnJoinedEvent();case"SendLeaveEvent":return this.state.hasMemberStateEvent?this.sendFallbackLeaveEvent():{replace:[]}}}async sendFirstDelayedLeaveEvent(){return await this.client._unstable_sendDelayedStateEvent(this.room.roomId,{delay:this.membershipServerSideExpiryTimeout},ie.GroupCallMemberPrefix,{},this.stateKey).then(e=>(this.state.rateLimitRetries.set("SendFirstDelayedEvent",0),this.state.networkErrorRetries.set("SendFirstDelayedEvent",0),this.state.delayId=e.delay_id,fs("SendJoinEvent"))).catch(e=>{const t="SendFirstDelayedEvent";if(this.manageMaxDelayExceededSituation(e))return fs(t);const r=this.actionUpdateFromErrors(e,t,"sendDelayedStateEvent");return r||(this.isUnsupportedDelayedEndpoint(e)?ar.info("Not using delayed event because the endpoint is not supported"):ar.info("Not using delayed event because: "+e),fs("SendJoinEvent"))})}async cancelKnownDelayIdBeforeSendFirstDelayedEvent(e){return await this.client._unstable_updateDelayedEvent(e,Vl.Cancel).then(()=>(this.state.delayId=void 0,this.resetRateLimitCounter("SendFirstDelayedEvent"),jT("SendFirstDelayedEvent"))).catch(t=>{const r="SendFirstDelayedEvent",i=this.actionUpdateFromErrors(t,r,"updateDelayedEvent");if(i)return i;if(this.isNotFoundError(t))return this.state.delayId=void 0,jT(r);if(this.isUnsupportedDelayedEndpoint(t))return jT("SendJoinEvent");throw Error("We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle")})}async restartDelayedEvent(e){return await this.client._unstable_updateDelayedEvent(e,Vl.Restart).then(()=>(this.resetRateLimitCounter("RestartDelayedEvent"),fs("RestartDelayedEvent",this.membershipKeepAlivePeriod))).catch(t=>{const r="RestartDelayedEvent";if(this.isNotFoundError(t))return this.state.delayId=void 0,fs("SendMainDelayedEvent");if(this.isUnsupportedDelayedEndpoint(t))return{};const i=this.actionUpdateFromErrors(t,r,"updateDelayedEvent");if(i)return i;throw Error("Could not restart delayed event, even though delayed events are supported. "+t)})}async sendMainDelayedEvent(){return await this.client._unstable_sendDelayedStateEvent(this.room.roomId,{delay:this.membershipServerSideExpiryTimeout},ie.GroupCallMemberPrefix,{},this.stateKey).then(e=>(this.state.delayId=e.delay_id,this.resetRateLimitCounter("SendMainDelayedEvent"),fs("RestartDelayedEvent",this.membershipKeepAlivePeriod))).catch(e=>{const t="SendMainDelayedEvent";if(this.isUnsupportedDelayedEndpoint(e))return{};if(this.manageMaxDelayExceededSituation(e))return fs(t);const r=this.actionUpdateFromErrors(e,t,"updateDelayedEvent");if(r)return r;throw Error("Could not send delayed event, even though delayed events are supported. "+e)})}async sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(e){return await this.client._unstable_updateDelayedEvent(e,Vl.Send).then(()=>(this.state.hasMemberStateEvent=!1,this.resetRateLimitCounter("SendScheduledDelayedLeaveEvent"),{replace:[]})).catch(t=>{const r="SendLeaveEvent";if(this.isUnsupportedDelayedEndpoint(t))return{};if(this.isNotFoundError(t))return this.state.delayId=void 0,fs(r);const i=this.actionUpdateFromErrors(t,r,"updateDelayedEvent");return i||(ar.warn("Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent",t),fs(r))})}async sendJoinEvent(){return await this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,this.makeMyMembership(this.membershipEventExpiryTimeout),this.stateKey).then(()=>(this.state.startTime=Date.now(),this.state.expireUpdateIterations=1,this.state.hasMemberStateEvent=!0,this.resetRateLimitCounter("SendJoinEvent"),{insert:[{ts:Date.now(),type:"RestartDelayedEvent"},{ts:this.computeNextExpiryActionTs(this.state.expireUpdateIterations),type:"UpdateExpiry"}]})).catch(e=>{const t=this.actionUpdateFromErrors(e,"SendJoinEvent","sendStateEvent");if(t)return t;throw e})}async updateExpiryOnJoinedEvent(){const e=this.state.expireUpdateIterations+1;return await this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,this.makeMyMembership(this.membershipEventExpiryTimeout*e),this.stateKey).then(()=>(this.resetRateLimitCounter("UpdateExpiry"),this.state.expireUpdateIterations=e,{insert:[{ts:this.computeNextExpiryActionTs(e),type:"UpdateExpiry"}]})).catch(t=>{const r=this.actionUpdateFromErrors(t,"UpdateExpiry","sendStateEvent");if(r)return r;throw t})}async sendFallbackLeaveEvent(){return await this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,{},this.stateKey).then(()=>(this.resetRateLimitCounter("SendLeaveEvent"),this.state.hasMemberStateEvent=!1,{replace:[]})).catch(e=>{const t=this.actionUpdateFromErrors(e,"SendLeaveEvent","sendStateEvent");if(t)return t;throw e})}makeMembershipStateKey(e,t){const r=`${e}_${t}`;return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:`_${r}`}makeMyMembership(e){return{call_id:"",scope:"m.room",application:"m.call",device_id:this.deviceId,expires:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:this.fociPreferred??[]}}isNotFoundError(e){return e instanceof mn&&e.errcode==="M_NOT_FOUND"}manageMaxDelayExceededSituation(e){if(e instanceof mn&&e.errcode==="M_UNKNOWN"&&e.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){const t=e.data["org.matrix.msc4140.max_delay"];return typeof t=="number"&&this.membershipServerSideExpiryTimeout>t&&(this.membershipServerSideExpiryTimeoutOverride=t),ar.warn("Retry sending delayed disconnection event due to server timeout limitations:",e),!0}return!1}actionUpdateFromErrors(e,t,r){const i=this.actionUpdateFromRateLimitError(e,r,t);if(i)return i;const s=this.actionUpdateFromNetworkErrorRetry(e,t);if(s)return s}actionUpdateFromRateLimitError(e,t,r){if(!((e instanceof eu||e instanceof mn)&&e.isRateLimitError()))return;const i=this.state.rateLimitRetries.get(r)??0;if(i<this.maximumRateLimitRetryCount){let s;try{s=e.getRetryAfterMs()??5e3,ar.info(`Rate limited by server, retrying in ${s}ms`)}catch(a){ar.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of 5000",a),s=5e3}return this.state.rateLimitRetries.set(r,i+1),fs(r,s)}throw Error("Exceeded maximum retries for "+r+" attempts (client."+t+"): "+e)}actionUpdateFromNetworkErrorRetry(e,t){const r=this.state.networkErrorRetries.get(t)??0,i=this.callMemberEventRetryDelayMinimum/1e3+"s",s="("+r+"/"+this.maximumNetworkErrorRetryCount+")";if(e instanceof Error&&e.name==="AbortError")ar.warn("Network local timeout error while sending event, retrying in "+i+" "+s,e);else if(e instanceof Error&&e.message.includes("updating delayed event"))ar.warn("delayed event update timeout error, retrying in "+i+" "+s,e);else if(e instanceof Vd)ar.warn("Network connection error while sending event, retrying in "+i+" "+s,e);else if((e instanceof eu||e instanceof mn)&&typeof e.httpStatus=="number"&&e.httpStatus>=500&&e.httpStatus<600)ar.warn("Server error while sending event, retrying in "+i+" "+s,e);else return;if(r<this.maximumNetworkErrorRetryCount)return this.state.networkErrorRetries.set(t,r+1),fs(t,this.callMemberEventRetryDelayMinimum);throw Error("Reached maximum ("+this.maximumNetworkErrorRetryCount+") retries cause by: "+e)}isUnsupportedDelayedEndpoint(e){return e instanceof Nl}resetRateLimitCounter(e){this.state.rateLimitRetries.set(e,0),this.state.networkErrorRetries.set(e,0)}get status(){const e=this.scheduler.actions;if(e.length===1){const{type:t}=e[0];switch(t){case"SendFirstDelayedEvent":case"SendJoinEvent":case"SendMainDelayedEvent":return"Connecting";case"UpdateExpiry":return"Connected";case"SendScheduledDelayedLeaveEvent":case"SendLeaveEvent":return"Disconnecting"}}else if(e.length===2){const t=e.map(r=>r.type);if((t.includes("RestartDelayedEvent")||t.includes("SendMainDelayedEvent"))&&t.includes("UpdateExpiry"))return"Connected"}else if(e.length===3){const t=e.map(r=>r.type);if(t.filter(r=>r==="RestartDelayedEvent").length===2&&t.includes("UpdateExpiry"))return"Connected"}return this.scheduler.running?(ar.error("MembershipManager has an unknown state. Actions: ",e),"Unknown"):"Disconnected"}}function fs(n,e){return{insert:[{ts:Date.now()+(e??0),type:n}]}}function jT(n,e){return{replace:[{ts:Date.now()+0,type:n}]}}const Bn=M.getChild("MatrixRTCSession");class Eoe{constructor(e,t,r,i){this.client=e,this.room=t,this.getMemberships=r,this.onEncryptionKeysChanged=i,this.manageMediaKeys=!1,this.setNewKeyTimeouts=new Set,this.encryptionKeys=new Map,this.currentEncryptionKeyIndex=-1,this.statistics={counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}},this.joined=!1,this.isMyMembership=s=>s.sender===this.client.getUserId()&&s.deviceId===this.client.getDeviceId(),this.sendEncryptionKeysEvent=async s=>{if(this.keysEventUpdateTimeout!==void 0&&(clearTimeout(this.keysEventUpdateTimeout),this.keysEventUpdateTimeout=void 0),this.lastEncryptionKeyUpdateRequest=Date.now(),!this.joined)return;Bn.info(`Sending encryption keys event. indexToSend=${s}`);const o=this.client.getUserId(),a=this.client.getDeviceId();if(!o)throw new Error("No userId");if(!a)throw new Error("No deviceId");const c=this.getKeysForParticipant(o,a);if(!c){Bn.warn("Tried to send encryption keys event but no keys found!");return}if(typeof s!="number"&&this.currentEncryptionKeyIndex===-1){Bn.warn("Tried to send encryption keys event but no current key index found!");return}const l=s??this.currentEncryptionKeyIndex,u=c[l];try{const h={keys:[{index:l,key:R$(u)}],device_id:a,call_id:"",sent_ts:Date.now()};this.statistics.counters.roomEventEncryptionKeysSent+=1,await this.client.sendEvent(this.room.roomId,ie.CallEncryptionKeysPrefix,h),Bn.debug(`Embedded-E2EE-LOG updateEncryptionKeyEvent participantId=${o}:${a} numKeys=${c.length} currentKeyIndex=${this.currentEncryptionKeyIndex} keyIndexToSend=${l}`,this.encryptionKeys)}catch(h){const p=h;if(p.event&&this.client.cancelPendingEvent(p.event),this.keysEventUpdateTimeout===void 0){const m=pP(p,5e3);Bn.warn(`Failed to send m.call.encryption_key, retrying in ${m}`,h),this.keysEventUpdateTimeout=setTimeout(()=>void this.sendEncryptionKeysEvent(),m)}else Bn.info("Not scheduling key resend as another re-send is already pending")}},this.onCallEncryptionEventReceived=s=>{const o=s.getSender(),a=s.getContent(),c=a.device_id,l=a.call_id;if(!o){Bn.warn(`Received m.call.encryption_keys with no userId: callId=${l}`);return}if(l!==""){Bn.warn(`Received m.call.encryption_keys with unsupported callId: userId=${o}, deviceId=${c}, callId=${l}`);return}if(!Array.isArray(a.keys)){Bn.warn(`Received m.call.encryption_keys where keys wasn't an array: callId=${l}`);return}if(o===this.client.getUserId()&&c===this.client.getDeviceId()){Bn.info("Ignoring our own keys event");return}this.statistics.counters.roomEventEncryptionKeysReceived+=1;const u=Date.now()-(typeof a.sent_ts=="number"?a.sent_ts:s.getTs());this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=u;for(const h of a.keys){if(!h){Bn.info("Ignoring false-y key in keys event");continue}const p=h.key,m=h.index;!p||m===void 0||m===null||l===void 0||l===null||typeof c!="string"||typeof l!="string"||typeof p!="string"||typeof m!="number"?Bn.warn(`Malformed call encryption_key: userId=${o}, deviceId=${c}, encryptionKeyIndex=${m} callId=${l}`):(Bn.debug(`Embedded-E2EE-LOG onCallEncryption userId=${o}:${c} encryptionKeyIndex=${m} age=${u}ms`,this.encryptionKeys),this.setEncryptionKey(o,c,m,p,s.getTs()))}},this.onRotateKeyTimeout=()=>{if(!this.manageMediaKeys)return;this.makeNewKeyTimeout=void 0,Bn.info("Making new sender key for key rotation");const s=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(s)}}get updateEncryptionKeyThrottle(){var e;return((e=this.joinConfig)==null?void 0:e.updateEncryptionKeyThrottle)??3e3}get makeKeyDelay(){var e;return((e=this.joinConfig)==null?void 0:e.makeKeyDelay)??3e3}get useKeyDelay(){var e;return((e=this.joinConfig)==null?void 0:e.useKeyDelay)??5e3}getEncryptionKeys(){return this.encryptionKeys}join(e){var t,r;this.joinConfig=e,this.joined=!0,this.manageMediaKeys=((t=this.joinConfig)==null?void 0:t.manageMediaKeys)??this.manageMediaKeys,(r=this.joinConfig)!=null&&r.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey())}leave(){const e=this.client.getUserId(),t=this.client.getDeviceId();if(!e)throw new Error("No userId");if(!t)throw new Error("No deviceId");this.encryptionKeys.set(b_(e,t),[]),this.makeNewKeyTimeout!==void 0&&(clearTimeout(this.makeNewKeyTimeout),this.makeNewKeyTimeout=void 0);for(const r of this.setNewKeyTimeouts)clearTimeout(r);this.setNewKeyTimeouts.clear(),this.manageMediaKeys=!1,this.joined=!1}onMembershipsUpdate(e){if(this.manageMediaKeys&&this.joined){const t=new Set(e.filter(a=>!this.isMyMembership(a)).map($T)),r=new Set(this.getMemberships().filter(a=>!this.isMyMembership(a)).map($T)),i=Array.from(t).some(a=>!r.has(a)),s=Array.from(r).some(a=>!t.has(a)),o=this.lastMembershipFingerprints;if(this.storeLastMembershipFingerprints(),i)this.makeNewKeyTimeout||(Bn.debug("Member(s) have left: queueing sender key rotation"),this.makeNewKeyTimeout=setTimeout(this.onRotateKeyTimeout,this.makeKeyDelay));else if(s)Bn.debug("New member(s) have joined: re-sending keys"),this.requestSendCurrentKey();else if(o){const a=this.lastMembershipFingerprints;(Array.from(o).some(l=>!a.has(l))||Array.from(a).some(l=>!o.has(l)))&&(Bn.debug("Member(s) have updated/reconnected: re-sending keys to everyone"),this.requestSendCurrentKey())}}}makeNewSenderKey(e=!1){const t=this.client.getUserId(),r=this.client.getDeviceId();if(!t)throw new Error("No userId");if(!r)throw new Error("No deviceId");const i=k$(16),s=this.getNewEncryptionKeyIndex();return Bn.info("Generated new key at index "+s),this.setEncryptionKey(t,r,s,i,Date.now(),e),s}requestSendCurrentKey(){if(this.manageMediaKeys){if(this.lastEncryptionKeyUpdateRequest&&this.lastEncryptionKeyUpdateRequest+this.updateEncryptionKeyThrottle>Date.now()){Bn.info("Last encryption key event sent too recently: postponing"),this.keysEventUpdateTimeout===void 0&&(this.keysEventUpdateTimeout=setTimeout(()=>void this.sendEncryptionKeysEvent(),this.updateEncryptionKeyThrottle));return}this.sendEncryptionKeysEvent()}}getKeysForParticipant(e,t){var r;return(r=this.encryptionKeys.get(b_(e,t)))==null?void 0:r.map(i=>i.key)}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.getMemberships().filter(e=>!this.isMyMembership(e)).map(e=>`${$T(e)}:${e.createdTs()}`))}getNewEncryptionKeyIndex(){return this.currentEncryptionKeyIndex===-1?0:(this.currentEncryptionKeyIndex+1)%256}setEncryptionKey(e,t,r,i,s,o=!1){const a=_f(i),c=b_(e,t);this.encryptionKeys.has(c)||this.encryptionKeys.set(c,[]);const l=this.encryptionKeys.get(c),u=l[r];if(u){if(u.timestamp>s){Bn.info(`Ignoring new key at index ${r} for ${c} as it is older than existing known key`);return}if(Coe(u.key,a)){u.timestamp=s;return}}if(l[r]={key:a,timestamp:s},o){const h=setTimeout(()=>{this.setNewKeyTimeouts.delete(h),Bn.info(`Delayed-emitting key changed event for ${c} idx ${r}`),e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=r),this.onEncryptionKeysChanged(a,r,c)},this.useKeyDelay);this.setNewKeyTimeouts.add(h)}else e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=r),this.onEncryptionKeysChanged(a,r,c)}}const b_=(n,e)=>`${n}:${e}`;function Coe(n,e){return n===e?!0:!!n&&!!e&&n.length===e.length&&n.every((t,r)=>t===e[r])}const $T=n=>b_(n.sender,n.deviceId);class Toe{constructor(e,t,r,i){this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,this.updateCallMembershipRunning=!1,this.needCallMembershipUpdate=!1,this.triggerCallMembershipEventUpdate=async()=>{if(this.updateCallMembershipRunning){this.needCallMembershipUpdate=!0;return}this.updateCallMembershipRunning=!0;try{do this.needCallMembershipUpdate=!1,await this.updateCallMembershipEvent();while(this.needCallMembershipUpdate)}finally{this.updateCallMembershipRunning=!1}},this.delayDisconnection=async()=>{try{const s=this.disconnectDelayId;await Ah(()=>this.client._unstable_updateDelayedEvent(s,Vl.Restart)),this.scheduleDelayDisconnection()}catch(s){M.error("Failed to delay our disconnection event:",s)}}}get callMemberEventRetryDelayMinimum(){var e;return((e=this.joinConfig)==null?void 0:e.callMemberEventRetryDelayMinimum)??3e3}get membershipExpiryTimeout(){var e;return((e=this.joinConfig)==null?void 0:e.membershipExpiryTimeout)??PP}get membershipServerSideExpiryTimeout(){var e;return this.membershipServerSideExpiryTimeoutOverride??((e=this.joinConfig)==null?void 0:e.membershipServerSideExpiryTimeout)??8e3}get membershipKeepAlivePeriod(){var e;return((e=this.joinConfig)==null?void 0:e.membershipKeepAlivePeriod)??5e3}get callMemberEventRetryJitter(){var e;return((e=this.joinConfig)==null?void 0:e.callMemberEventRetryJitter)??2e3}isJoined(){return this.relativeExpiry!==void 0}join(e,t){this.ownFocusActive=t,this.ownFociPreferred=e,this.relativeExpiry=this.membershipExpiryTimeout,this.triggerCallMembershipEventUpdate()}async leave(e=void 0){return this.relativeExpiry=void 0,this.ownFocusActive=void 0,this.memberEventTimeout&&(clearTimeout(this.memberEventTimeout),this.memberEventTimeout=void 0),e?await Promise.race([this.triggerCallMembershipEventUpdate(),Td(e,"timeout")])!=="timeout":(await this.triggerCallMembershipEventUpdate(),!0)}async onRTCSessionMemberUpdate(e){const t=r=>r.sender===this.client.getUserId()&&r.deviceId===this.client.getDeviceId();if(this.isJoined()&&!e.some(t))return M.warn("Missing own membership: force re-join"),this.triggerCallMembershipEventUpdate()}getActiveFocus(){if(this.ownFocusActive)if(xP(this.ownFocusActive)){if(this.ownFocusActive.focus_selection==="oldest_membership"){const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else M.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}makeNewMembership(e){return this.isJoined()?this.makeMyMembership(e):{}}makeMyMembership(e){return{call_id:"",scope:"m.room",application:"m.call",device_id:e,expires:this.relativeExpiry,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:this.ownFociPreferred??[]}}async updateCallMembershipEvent(){if(this.memberEventTimeout&&(clearTimeout(this.memberEventTimeout),this.memberEventTimeout=void 0),!this.room.getLiveTimeline().getState(Be.FORWARDS))throw new Error("Couldn't get room state for room "+this.room.roomId);const t=this.client.getUserId(),r=this.client.getDeviceId();if(!t||!r)throw new Error("User ID or device ID was null!");let i={};i=this.makeNewMembership(r);try{if(this.isJoined()){const s=this.makeMembershipStateKey(t,r),o=async()=>{try{const a=await Ah(()=>this.client._unstable_sendDelayedStateEvent(this.room.roomId,{delay:this.membershipServerSideExpiryTimeout},ie.GroupCallMemberPrefix,{},s));this.disconnectDelayId=a.delay_id}catch(a){if(a instanceof mn&&a.errcode==="M_UNKNOWN"&&a.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){const c=a.data["org.matrix.msc4140.max_delay"];if(typeof c=="number"&&this.membershipServerSideExpiryTimeout>c)return this.membershipServerSideExpiryTimeoutOverride=c,o()}M.error("Failed to prepare delayed disconnection event:",a)}};if(await o(),await Ah(()=>this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,i,s)),this.disconnectDelayId!==void 0)try{const a=this.disconnectDelayId;await Ah(()=>this.client._unstable_updateDelayedEvent(a,Vl.Restart))}catch(a){a instanceof mn&&a.errcode==="M_NOT_FOUND"&&(M.warn("Failed to update delayed disconnection event, prepare it again:",a),this.disconnectDelayId=void 0,await o())}this.disconnectDelayId!==void 0&&this.scheduleDelayDisconnection()}else{let s=!1;if(this.disconnectDelayId!==void 0){try{const o=this.disconnectDelayId;await Ah(()=>this.client._unstable_updateDelayedEvent(o,Vl.Send)),s=!0}catch(o){M.error("Failed to send our delayed disconnection event:",o)}this.disconnectDelayId=void 0}s||await Ah(()=>this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,{},this.makeMembershipStateKey(t,r)))}M.info("Sent updated call member event.")}catch(s){const o=this.callMemberEventRetryDelayMinimum+Math.random()*this.callMemberEventRetryJitter;M.warn(`Failed to send call member event (retrying in ${o}): ${s}`),await Td(o),await this.triggerCallMembershipEventUpdate()}}scheduleDelayDisconnection(){this.memberEventTimeout=setTimeout(()=>void this.delayDisconnection(),this.membershipKeepAlivePeriod)}makeMembershipStateKey(e,t){const r=`${e}_${t}`;return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:`_${r}`}}async function Ah(n,e=1){for(;;)try{return await n()}catch(t){if(e>0&&t instanceof eu&&t.isRateLimitError()){e--;let r;const i=5e3;try{r=t.getRetryAfterMs()??i,M.info(`Rate limited by server, retrying in ${r}ms`)}catch(s){M.warn(`Error while retrieving a rate-limit retry delay, retrying after default delay of ${i}`,s),r=i}await Td(r)}else throw t}}const ps=M.getChild("MatrixRTCSession");var ts=(n=>(n.MembershipsChanged="memberships_changed",n.JoinStateChanged="join_state_changed",n.EncryptionKeyChanged="encryption_key_changed",n.MembershipManagerError="membership_manager_error",n))(ts||{});class Sf extends Yn{constructor(e,t,r){var s;super(),this.client=e,this.roomSubset=t,this.memberships=r,this.onCallEncryption=o=>{this.encryptionManager.onCallEncryptionEventReceived(o)},this.onMembershipUpdate=()=>{this.recalculateSessionMembers()},this.onRoomMemberUpdate=()=>{this.recalculateSessionMembers()},this.onRTCSessionMemberUpdate=()=>{this.recalculateSessionMembers()},this.recalculateSessionMembers=()=>{var c,l;const o=this.memberships;this.memberships=Sf.callMembershipsForRoom(this.room),this._callId=this._callId??((c=this.memberships[0])==null?void 0:c.callId),(o.length!=this.memberships.length||o.some((u,h)=>!P5.equal(u,this.memberships[h])))&&(ps.info(`Memberships for call in room ${this.roomSubset.roomId} have changed: emitting`),gre(ps,"emit MatrixRTCSessionEvent.MembershipsChanged",()=>{this.emit("memberships_changed",o,this.memberships)}),(l=this.membershipManager)==null||l.onRTCSessionMemberUpdate(this.memberships)),this.encryptionManager.onMembershipsUpdate(o),this.setExpiryTimer()},this._callId=(s=r[0])==null?void 0:s.callId;const i=this.roomSubset.getLiveTimeline().getState(Be.FORWARDS);i==null||i.on(It.Members,this.onRoomMemberUpdate),this.setExpiryTimer(),this.encryptionManager=new Eoe(this.client,this.roomSubset,()=>this.memberships,(o,a,c)=>{this.emit("encryption_key_changed",o,a,c)})}get statistics(){return this.encryptionManager.statistics}get callId(){return this._callId}static callMembershipsForRoom(e){const t=e.getLiveTimeline().getState(Be.FORWARDS);if(!t)throw ps.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);const r=t.getStateEvents(ie.GroupCallMemberPrefix),i=[];for(const s of r){const o=s.getContent(),a=Object.keys(o).length;if(a===0)continue;const c=[];if(a>1&&"focus_active"in o?c.push(o):a===1&&"memberships"in o&&ps.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session"),c.length!==0)for(const l of c)try{const u=new P5(s,l);if(u.callId!==""||u.scope!=="m.room"){ps.info("Ignoring user-scoped call");continue}if(u.isExpired()){ps.info(`Ignoring expired device membership ${u.sender}/${u.deviceId}`);continue}if(!e.hasMembershipState(u.sender??"",We.Join)){ps.info(`Ignoring membership of user ${u.sender} who is not in the room.`);continue}i.push(u)}catch(u){ps.warn("Couldn't construct call membership: ",u)}}return i.sort((s,o)=>s.createdTs()-o.createdTs()),i.length>1&&ps.debug(`Call memberships in room ${e.roomId}, in order: `,i.map(s=>[s.createdTs(),s.sender])),i}static roomSessionForRoom(e,t){const r=Sf.callMembershipsForRoom(t);return new Sf(e,t,r)}get room(){return this.roomSubset}isJoined(){var e;return((e=this.membershipManager)==null?void 0:e.isJoined())??!1}async stop(){var t;await((t=this.membershipManager)==null?void 0:t.leave(1e3)),this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);const e=this.roomSubset.getLiveTimeline().getState(Be.FORWARDS);e==null||e.off(It.Members,this.onRoomMemberUpdate)}joinRoomSession(e,t,r){if(this.isJoined()){ps.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`);return}else(r==null?void 0:r.useNewMembershipManager)??!1?this.membershipManager=new Ub(r,this.roomSubset,this.client,()=>this.getOldestMembership()):this.membershipManager=new Toe(r,this.roomSubset,this.client,()=>this.getOldestMembership());this.membershipManager.join(e,t,i=>{ps.error("MembershipManager encountered an unrecoverable error: ",i),this.emit("membership_manager_error",i),this.emit("join_state_changed",this.isJoined())}),this.encryptionManager.join(r),this.emit("join_state_changed",!0)}async leaveRoomSession(e=void 0){if(!this.isJoined())return ps.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`),!1;ps.info(`Leaving call session in room ${this.roomSubset.roomId}`),this.encryptionManager.leave();const t=this.membershipManager.leave(e);return this.emit("join_state_changed",!1),await t}getActiveFocus(){var e;return(e=this.membershipManager)==null?void 0:e.getActiveFocus()}getOldestMembership(){return this.memberships[0]}getFocusInUse(){const e=this.getOldestMembership();if((e==null?void 0:e.getFocusSelection())==="oldest_membership")return e.getPreferredFoci()[0]}reemitEncryptionKeys(){this.encryptionManager.getEncryptionKeys().forEach((e,t)=>{e.forEach((r,i)=>{this.emit("encryption_key_changed",r.key,i,t)})})}getEncryptionKeys(){const e=this.encryptionManager.getEncryptionKeys()??new Map;return Array.from(e.entries()).map(([t,r])=>[t,r.map(i=>i.key)]).values()}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);let e;for(const t of this.memberships){const r=t.getMsUntilExpiry();r!==void 0&&(e===void 0||r<e)&&(e=r)}e!=null&&(this.expiryTimeout=setTimeout(this.onRTCSessionMemberUpdate,e))}}const Fm=M.getChild("MatrixRTCSessionManager");var lk=(n=>(n.SessionStarted="session_started",n.SessionEnded="session_ended",n))(lk||{});class Ioe extends Yn{constructor(e){super(),this.client=e,this.roomSessions=new Map,this.onTimeline=t=>{this.consumeCallEncryptionEvent(t)},this.onRoom=t=>{this.refreshRoom(t)},this.onRoomState=(t,r)=>{const i=this.client.getRoom(t.getRoomId());if(!i){Fm.error(`Got room state event for unknown room ${t.getRoomId()}!`);return}t.getType()==ie.GroupCallMemberPrefix&&this.refreshRoom(i)}}start(){for(const e of this.client.getRooms()??[]){const t=Sf.roomSessionForRoom(this.client,e);t.memberships.length>0&&this.roomSessions.set(e.roomId,t)}this.client.on(Ge.Room,this.onRoom),this.client.on(Xe.Timeline,this.onTimeline),this.client.on(It.Events,this.onRoomState)}stop(){for(const e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(Ge.Room,this.onRoom),this.client.off(Xe.Timeline,this.onTimeline),this.client.off(It.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,Sf.roomSessionForRoom(this.client,e)),this.roomSessions.get(e.roomId)}async consumeCallEncryptionEvent(e,t=!1){if(await this.client.decryptEventIfNeeded(e),e.isDecryptionFailure()){t?Fm.warn(`Decryption failed for event ${e.getId()}: ${e.decryptionFailureReason}`):(Fm.warn(`Decryption failed for event ${e.getId()}: ${e.decryptionFailureReason} will retry once only`),setTimeout(()=>void this.consumeCallEncryptionEvent(e,!0),1e3));return}else t&&Fm.info(`Decryption succeeded for event ${e.getId()} after retry`);if(e.getType()!==ie.CallEncryptionKeysPrefix)return Promise.resolve();const r=this.client.getRoom(e.getRoomId());if(!r)return Fm.error(`Got room state event for unknown room ${e.getRoomId()}!`),Promise.resolve();this.getRoomSession(r).onCallEncryption(e)}refreshRoom(e){const t=!this.roomSessions.has(e.roomId),r=this.getRoomSession(e),i=r.memberships.length>0&&!t;r.onRTCSessionMemberUpdate();const s=r.memberships.length>0;i&&!s?this.emit("session_ended",e.roomId,this.roomSessions.get(e.roomId)):!i&&s&&this.emit("session_started",e.roomId,this.roomSessions.get(e.roomId))}}function BT(n){return e=>{var t,r,i,s;return((r=(t=e.content)==null?void 0:t["m.relates_to"])==null?void 0:r.event_id)!==n||((s=(i=e.content)==null?void 0:i["m.relates_to"])==null?void 0:s.rel_type)===en.name}}async function q$(n){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");const e=new TextEncoder().encode(n),t=await globalThis.crypto.subtle.digest("SHA-256",e);return new Uint8Array(t)}var Kr=(n=>(n.NotSupported="OIDC authentication not supported",n.Misconfigured="OIDC is misconfigured",n.General="Something went wrong with OIDC discovery",n.OpSupport="Configured OIDC OP does not support required functions",n.DynamicRegistrationNotSupported="Dynamic registration not supported",n.DynamicRegistrationFailed="Dynamic registration failed",n.DynamicRegistrationInvalid="Dynamic registration invalid response",n.CodeExchangeFailed="Failed to exchange code for token",n.InvalidBearerTokenResponse="Invalid bearer token response",n.InvalidIdToken="Invalid ID token",n.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",n))(Kr||{});const AP=n=>!!n&&typeof n=="object"&&!Array.isArray(n),yc=(n,e)=>!n[e]||!kg(n,e)?(M.error(`Missing or invalid property: ${e}`),!1):!0,kg=(n,e)=>n[e]&&typeof n[e]!="string"?(M.error(`Invalid property: ${e}`),!1):!0,L5=(n,e)=>n[e]&&(!Array.isArray(n[e])||!n[e].every(t=>typeof t=="string"))?(M.error(`Invalid property: ${e}`),!1):!0,HT=(n,e,t)=>{const r=n[e];return!r||!Array.isArray(r)||!r.includes(t)?(M.error(`Invalid property: ${e}. ${t} is required.`),!1):!0},K$=n=>{if(!AP(n))throw M.error("Issuer configuration not found or malformed"),new Error(Kr.OpSupport);if(![yc(n,"issuer"),yc(n,"authorization_endpoint"),yc(n,"token_endpoint"),yc(n,"revocation_endpoint"),kg(n,"registration_endpoint"),kg(n,"account_management_uri"),kg(n,"device_authorization_endpoint"),L5(n,"account_management_actions_supported"),HT(n,"response_types_supported","code"),HT(n,"grant_types_supported","authorization_code"),HT(n,"code_challenge_methods_supported","S256"),L5(n,"prompt_values_supported")].some(t=>!t))return n;throw M.error("Issuer configuration not valid"),new Error(Kr.OpSupport)},W$=n=>{try{return i$(n)}catch(e){throw M.error("Could not decode id_token",e),e}},z$=(n,e,t,r)=>{try{if(!n)throw new Error("No ID token");const i=W$(n);if(i.iss!==e)throw new Error("Invalid issuer");if(!(typeof i.aud=="string"?[i.aud]:i.aud).includes(t))throw new Error("Invalid audience");if(r!==void 0&&i.nonce!==r)throw new Error("Invalid nonce");if(!i.exp||Date.now()>i.exp*1e3)throw new Error("Invalid expiry")}catch(i){throw M.error("Invalid ID token",i),new Error(Kr.InvalidIdToken)}};function Y$(n){if(!AP(n))throw M.error("Stored user state not found"),new Error(Kr.MissingOrInvalidStoredState);if([yc(n,"homeserverUrl"),yc(n,"nonce"),kg(n,"identityServerUrl")].some(t=>!t))throw new Error(Kr.MissingOrInvalidStoredState)}const Roe=n=>AP(n)&&yc(n,"token_type")&&n.token_type.toLowerCase()==="bearer"&&yc(n,"access_token")&&yc(n,"refresh_token")&&(!("expires_in"in n)||typeof n.expires_in=="number");function X$(n){if(!Roe(n))throw new Error(Kr.InvalidBearerTokenResponse)}const yw=n=>`openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${n??Es(10)}`,koe=async n=>{if(!globalThis.crypto.subtle)return M.warn("A secure context is required to generate code challenge. Using plain text code challenge"),n;const e=await q$(n);return fw(e)},xoe=({redirectUri:n})=>({scope:yw(),redirectUri:n,state:Es(8),nonce:Es(8),codeVerifier:Es(64)}),Poe=async(n,e,{scope:t,redirectUri:r,state:i,nonce:s,codeVerifier:o})=>{const a=new URL(n);return a.searchParams.append("response_mode","query"),a.searchParams.append("response_type","code"),a.searchParams.append("redirect_uri",r),a.searchParams.append("client_id",e),a.searchParams.append("state",i),a.searchParams.append("scope",t),a.searchParams.append("nonce",s),a.searchParams.append("code_challenge_method","S256"),a.searchParams.append("code_challenge",await koe(o)),a.toString()},Loe=async({metadata:n,redirectUri:e,clientId:t,homeserverUrl:r,identityServerUrl:i,nonce:s,prompt:o,urlState:a})=>{const c=yw(),l=new fP({...n,client_id:t,redirect_uri:e,authority:n.issuer,response_mode:"query",response_type:"code",scope:c,stateStore:new lw({prefix:"mx_oidc_",store:window.sessionStorage})}),u={homeserverUrl:r,nonce:s,identityServerUrl:i};return(await l.createSigninRequest({state:u,nonce:s,prompt:o,url_state:a})).url},Aoe=n=>({id_token:n.id_token,scope:n.scope,expires_at:n.expires_at,refresh_token:n.refresh_token,access_token:n.access_token,token_type:"Bearer"}),Ooe=async(n,e)=>{const t=new URL(window.location.origin);t.searchParams.append("code",n),t.searchParams.append("state",e),ov.setLogger(M);try{const r=new v_(t.searchParams),i=new lw({prefix:"mx_oidc_",store:window.sessionStorage}),s=await i.get(r.state);if(!s)throw new Error(Kr.MissingOrInvalidStoredState);const o=await hP.fromStorageString(s),a=new fP({...o,stateStore:i}),c=await a.processSigninResponse(t.href),l=c.userState;Y$(l),X$(c),z$(c.id_token,a.settings.authority,a.settings.client_id,l.nonce);const u=Aoe(c);return{oidcClientSettings:{clientId:a.settings.client_id,issuer:a.settings.authority},tokenResponse:u,homeserverUrl:l.homeserverUrl,identityServerUrl:l.identityServerUrl,idTokenClaims:c.profile}}catch(r){M.error("Oidc login failed",r);const i=r.message;throw Object.values(Kr).includes(i)?r:new Error(Kr.CodeExchangeFailed)}},OP=async n=>{const e=new URL(".well-known/openid-configuration",n),r=await(await fetch(e,{method:de.Get,signal:uw(5e3)})).json();return MP(r)},MP=async n=>{const e=K$(n),t=new qR({authority:e.issuer,metadata:e,redirect_uri:"",client_id:""}),r=new o$(t);return{...e,signingKeys:await r.getSigningKeys()}},Moe="urn:ietf:params:oauth:grant-type:device_code",VT=(n,e)=>{if(!e)return!1;const t=new URL(e);return!(t.protocol!==n.protocol||t.host!==n.host&&!t.host.endsWith(`.${n.host}`))},Noe=async(n,e)=>{if(!n.registration_endpoint)throw new Error(Kr.DynamicRegistrationNotSupported);const t=["authorization_code","refresh_token"];if(t.some(o=>!n.grant_types_supported.includes(o)))throw new Error(Kr.DynamicRegistrationNotSupported);const r=new URL(e.clientUri),i={client_name:e.clientName,client_uri:e.clientUri,response_types:["code"],grant_types:t,redirect_uris:e.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:e.applicationType,contacts:e.contacts,logo_uri:VT(r,e.logoUri)?e.logoUri:void 0,policy_uri:VT(r,e.policyUri)?e.policyUri:void 0,tos_uri:VT(r,e.tosUri)?e.tosUri:void 0},s={Accept:"application/json","Content-Type":"application/json"};try{const o=await fetch(n.registration_endpoint,{method:de.Post,headers:s,body:JSON.stringify(i)});if(o.status>=400)throw new Error(Kr.DynamicRegistrationFailed);const c=(await o.json()).client_id;if(!c||typeof c!="string")throw new Error(Kr.DynamicRegistrationInvalid);return c}catch(o){throw Object.values(Kr).includes(o.message)?o:(M.error("Dynamic registration request failed",o),new Error(Kr.DynamicRegistrationFailed))}};class Doe{constructor(e,t,r,i,s){this.idTokenClaims=s,this.oidcClientReady=this.initialiseOidcClient(e,t,i,r)}async initialiseOidcClient(e,t,r,i){try{const s=await OP(e),o=yw(r);this.oidcClient=new fP({metadata:s,signingKeys:s.signingKeys??void 0,client_id:t,scope:o,redirect_uri:i,authority:s.issuer,stateStore:new lw({prefix:"mx_oidc_",store:window.sessionStorage})})}catch(s){throw M.error("Failed to initialise OIDC client.",s),new Error("Failed to initialise OIDC client.")}}async doRefreshAccessToken(e){this.inflightRefreshRequest||(this.inflightRefreshRequest=this.getNewTokens(e));try{return await this.inflightRefreshRequest}finally{this.inflightRefreshRequest=void 0}}async persistTokens(e){}async getNewTokens(e){if(!this.oidcClient)throw new Error("Cannot get new token before OIDC client is initialised.");const t={refresh_token:e,session_state:"test",data:void 0,profile:this.idTokenClaims},r=await this.oidcClient.useRefreshToken({state:t,timeoutInSeconds:300}),i={accessToken:r.access_token,refreshToken:r.refresh_token};return await this.persistTokens(i),i}}const Foe=3e3,A5=10*60*1e3,Uoe=new Fn("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent");var Rd=(n=>(n.Chronological="chronological",n.Detached="detached",n))(Rd||{});const joe=new nw("m.get_login_token","org.matrix.msc3882.get_login_token"),J$="uk.half-shot.msc2666",Z$="uk.half-shot.msc2666.mutual_rooms",Q$="uk.half-shot.msc2666.query_mutual_rooms",ga="org.matrix.msc4140",eB="uk.tcpip.msc4133",ta="$";var Ge=(n=>(n.Sync="sync",n.Event="event",n.ToDeviceEvent="toDeviceEvent",n.AccountData="accountData",n.Room="Room",n.DeleteRoom="deleteRoom",n.SyncUnexpectedError="sync.unexpectedError",n.ClientWellKnown="WellKnown.client",n.ReceivedVoipEvent="received_voip_event",n.UndecryptableToDeviceEvent="toDeviceEvent.undecryptable",n.TurnServers="turnServers",n.TurnServersError="turnServers.error",n))(Ge||{});const $oe=new Fn("action","org.matrix.msc3824.action"),V4=class V4 extends Yn{constructor(e){super(),this.reEmitter=new oy(this),this.olmVersion=null,this.usingExternalCrypto=!1,this.clientRunning=!1,this.timelineSupport=!1,this.urlPreviewCache={},this.supportsCallTransfer=!1,this.forceTURN=!1,this.iceCandidatePoolSize=0,this.canSupportVoip=!1,this.peekSync=null,this.isGuestAccount=!1,this.ongoingScrollbacks={},this.notifTimelineSet=null,this.fallbackICEServerAllowed=!1,this.syncedLeftRooms=!1,this.canSupport=new Map,this.pushProcessor=new Mb(this),this.turnServers=[],this.turnServersExpiry=0,this.txnCtr=0,this.mediaHandler=new Zse(this),this.eventsBeingEncrypted=new Set,this.useE2eForGroupCall=!0,this.startCallEventHandler=()=>{this.isInitialSyncComplete()&&(tk()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off("sync",this.startCallEventHandler))},this.startMatrixRTC=()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off("sync",this.startMatrixRTC))},this.fixupRoomNotifications=()=>{if(this.isInitialSyncComplete()){const r=(this.getRooms()??[]).filter(i=>i.getUnreadNotificationCount(rr.Total)>0);for(const i of r){const s=this.getSafeUserId();i.fixupNotifications(s)}this.off("sync",this.fixupRoomNotifications)}},this.logger=e.logger??M,e.baseUrl=RT(e.baseUrl),e.idBaseUrl=RT(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=e.usingExternalCrypto??!1,this.store=e.store||new ise,this.deviceId=e.deviceId||null,this.sessionId=Es(10);const t=e.userId||null;this.credentials={userId:t},this.http=new y$(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:lr.V3,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader,logger:this.logger}),e.pickleKey&&(this.legacyPickleKey=e.pickleKey),this.useLivekitForGroupCalls=!!e.useLivekitForGroupCalls,this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(async r=>{const i=this.getRoom(r.getRoomId());r.status!==rt.SENDING&&this.updatePendingEventStatus(i,r,rt.SENDING);const s=await this.sendEventHttpRequest(r);return i&&i.updatePendingEvent(r,rt.SENT,s.event_id),s}),tk()&&(this.callEventHandler=new Ese(this),this.groupCallEventHandler=new Cse(this),this.canSupportVoip=!0,this.on("sync",this.startCallEventHandler)),this.matrixRTC=new Ioe(this),this.serverCapabilitiesService=new _$(this.http),this.on("sync",this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.legacyCryptoStore=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 ooe(this),this.on(pn.Decrypted,r=>{tB(this,r)}),this.ignoredInvites=new aoe(this),this._secretStorage=new V$(this,e.cryptoCallbacks??{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(t=>bc.createUser(t,this))}get store(){return this._store}async startClient(e){if(this.clientRunning)return;this.clientRunning=!0,this.on("sync",this.startMatrixRTC);const t=this.getUserId();t&&this.store.storeUser(new bc(t)),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval(()=>{this.checkTurnServers()},A5),this.checkTurnServers()),this.syncApi&&(this.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{await this.getVersions();const{threads:r,list:i,fwdPagination:s}=await this.doesServerSupportThread();Gr.setServerSideSupport(r),Gr.setServerSideListSupport(i),Gr.setServerSideFwdPaginationSupport(s)}catch(r){this.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",r)}this.clientOpts=e??{},this.clientOpts.slidingSync?this.syncApi=new j$(this.clientOpts.slidingSync,this,this.clientOpts,this.buildSyncApiOptions()):this.syncApi=new rd(this,this.clientOpts,this.buildSyncApiOptions()),this.syncApi.sync().catch(r=>this.logger.info("Sync startup aborted with an error:",r)),this.clientOpts.clientWellKnownPollPeriod!==void 0&&(this.clientWellKnownIntervalID=setInterval(()=>{this.fetchClientWellKnown()},1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.toDeviceMessageQueue.start(),this.serverCapabilitiesService.start()}buildSyncApiOptions(){return{cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1}}stopClient(){var e,t,r,i,s;(e=this.cryptoBackend)==null||e.stop(),this.off("sync",this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(t=this.syncApi)==null||t.stop(),this.syncApi=void 0,(r=this.peekSync)==null||r.stopPeeking(),(i=this.callEventHandler)==null||i.stop(),(s=this.groupCallEventHandler)==null||s.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())}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const e=[];e.push(this.store.deleteAllData()),this.legacyCryptoStore&&e.push(this.legacyCryptoStore.deleteAllData());const t=async()=>{let r;try{if(r=globalThis.indexedDB,!r)return}catch{return}for(const i of[`${UT}::matrix-sdk-crypto`,`${UT}::matrix-sdk-crypto-meta`])await new Promise((o,a)=>{this.logger.info(`Removing IndexedDB instance ${i}`);const c=r.deleteDatabase(i);c.onsuccess=l=>{this.logger.info(`Removed IndexedDB instance ${i}`),o(0)},c.onerror=l=>{this.logger.warn(`Failed to remove IndexedDB instance ${i}:`,l),o(0)},c.onblocked=l=>{this.logger.info(`cannot yet remove IndexedDB instance ${i}`)}})};return e.push(t()),Promise.all(e).then()}getUserId(){var e;return((e=this.credentials)==null?void 0:e.userId)??null}getSafeUserId(){const e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){var e;return(e=this.credentials)!=null&&e.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){var e,t;return((t=(e=this.credentials)==null?void 0:e.userId)==null?void 0:t.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 av(this,e)}async createGroupCall(e,t,r,i,s,o){if(this.getGroupCallForRoom(e))throw new Error(`${e} already has an existing group call`);const a=this.getRoom(e);if(!a)throw new Error(`Cannot find room ${e}`);return new EP(this,a,t,r,i,void 0,s||this.isVoipWithNoMediaAllowed,o,this.isVoipWithNoMediaAllowed,this.useLivekitForGroupCalls,this.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;return((e=this.syncApi)==null?void 0:e.getSyncState())??null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return e?e===Pr.Prepared||e===Pr.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e;return this.toDeviceMessageQueue.sendQueue(),((e=this.syncApi)==null?void 0:e.retryImmediately())??!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}async getCapabilities(){const e=this.serverCapabilitiesService.getCachedCapabilities();return e||this.serverCapabilitiesService.fetchCapabilities()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}async initRustCrypto(e={}){if(this.cryptoBackend){this.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}const t=this.getUserId();if(t===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");const r=this.getDeviceId();if(r===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");this.logger.debug("Downloading Rust crypto library");const s=await(await rv(()=>import("./index-CZZJETQc.js"),__vite__mapDeps([0,1]),import.meta.url)).initRustCrypto({logger:this.logger,http:this.http,userId:t,deviceId:r,secretStorage:this.secretStorage,cryptoCallbacks:this.cryptoCallbacks,storePrefix:e.useIndexedDB===!1?null:UT,storeKey:e.storageKey,storePassphrase:e.storagePassword,legacyCryptoStore:this.legacyCryptoStore,legacyPickleKey:this.legacyPickleKey??"DEFAULT_KEY",legacyMigrationProgressListener:(o,a)=>{this.emit(cr.LegacyCryptoStoreMigrationProgress,o,a)}});s.setSupportedVerificationMethods(this.verificationMethods),this.cryptoBackend=s,this.on(Fo.Membership,s.onRoomMembership.bind(s)),this.on("event",o=>{s.onLiveEventFromSync(o)}),this.reEmitter.reEmit(s,[cr.VerificationRequestReceived,cr.UserTrustStatusChanged,cr.KeyBackupStatus,cr.KeyBackupSessionsRemaining,cr.KeyBackupFailed,cr.KeyBackupDecryptionKeyCached,cr.KeysChanged,cr.DevicesUpdated,cr.WillUpdateDevices,cr.DehydratedDeviceCreated,cr.DehydratedDeviceUploaded,cr.RehydrationStarted,cr.RehydrationProgress,cr.RehydrationCompleted,cr.RehydrationError,cr.DehydrationKeyCached,cr.DehydratedDeviceRotationError])}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isRoomEncrypted(e){const t=this.getRoom(e);return t?t.hasEncryptionStateEvent():!1}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}makeKeyBackupPath(e,t,r){let i;return t!==void 0?i=Le("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):e!==void 0?i=Le("/room_keys/keys/$roomId",{$roomId:e}):i="/room_keys/keys",{path:i,queryData:r===void 0?void 0:{version:r}}}async deleteKeysFromBackup(e,t,r){const i=this.makeKeyBackupPath(e,t,r);await this.http.authedRequest(de.Delete,i.path,i.queryData,void 0,{prefix:lr.V3})}getMediaConfig(){return this.http.authedRequest(de.Get,"/config",void 0,void 0,{prefix:ud.V3})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(e=!1){var i;const t=this.store.getRooms(),r=new Set;for(const s of t){const o=(i=s.findPredecessor(e))==null?void 0:i.roomId;o&&r.add(o)}return t.filter(s=>!(s.currentState.getStateEvents(ie.RoomTombstone,"")&&r.has(s.roomId)))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}async setAccountData(e,t){if(!this.clientRunning)return M.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results."),await zR(5,()=>this.setAccountDataRaw(e,t));const r=this.store.getAccountData(e);if(r&&Cd(r.event.content,t))return{};const i=Zl();function s(o){o.getType()===e&&i.resolve()}this.addListener("accountData",s);try{const o=await zR(5,()=>this.setAccountDataRaw(e,t));return await i.promise,o}finally{this.removeListener("accountData",s)}}setAccountDataRaw(e,t){const r=Le("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this.http.authedRequest(de.Put,r,void 0,t)}getAccountData(e){return this.store.getAccountData(e)}async getAccountDataFromServer(e){var r;if(this.isInitialSyncComplete()){const i=this.store.getAccountData(e);return i?i.getContent():null}const t=Le("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return await this.http.authedRequest(de.Get,t)}catch(i){if(((r=i.data)==null?void 0:r.errcode)==="M_NOT_FOUND")return null;throw i}}async deleteAccountData(e){const t=this.canSupport.get(vs.AccountDataDeletion);if(t===Vr.Unsupported){await this.setAccountData(e,{});return}const r=Le("/user/$userId/account_data/$type",{$userId:this.getSafeUserId(),$type:e}),i=t===Vr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return await this.http.authedRequest(de.Delete,r,void 0,void 0,i)}getIgnoredUsers(){const e=this.getAccountData(ie.IgnoredUserList);return e!=null&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){const t={ignored_users:{}};return e.forEach(r=>{t.ignored_users[r]={}}),this.setAccountData(ie.IgnoredUserList,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}async joinRoom(e,t={}){t.syncRoom===void 0&&(t.syncRoom=!0);const r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,We.Join))return r;let i=Promise.resolve();if(t.inviteSignUrl){const v=new URL(t.inviteSignUrl);v.searchParams.set("mxid",this.credentials.userId),i=this.http.requestOtherUrl(de.Post,v)}const s={};t.viaServers&&(s.server_name=t.viaServers,s.via=t.viaServers);const o={},a=await i;a&&(o.third_party_signed=a);const c=Le("/join/$roomid",{$roomid:e}),u=(await this.http.authedRequest(de.Post,c,s,o)).room_id,h=this.getRoom(u);if(h!=null&&h.hasMembershipState(this.credentials.userId,We.Join))return h;const m=new rd(this,this.clientOpts,this.buildSyncApiOptions()).createRoom(u);return t.syncRoom,m}knockRoom(e,t={}){const r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,We.Knock))return Promise.resolve({room_id:r.roomId});const i=Le("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),s={};t.viaServers&&(s.server_name=t.viaServers,s.via=t.viaServers);const o={};return t.reason&&(o.reason=t.reason),this.http.authedRequest(de.Post,i,s,o)}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,rt.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![rt.QUEUED,rt.NOT_SENT,rt.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===rt.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===rt.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,rt.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,ie.RoomName,{name:t})}setRoomTopic(e,t,r){const i=Yj(t,r);return this.sendStateEvent(e,ie.RoomTopic,i)}getRoomTags(e){const t=Le("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(de.Get,t)}setRoomTag(e,t,r={}){const i=Le("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(de.Put,i,void 0,r)}deleteRoomTag(e,t){const r=Le("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(de.Delete,r)}setRoomAccountData(e,t,r){const i=Le("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(de.Put,i,void 0,r)}async setPowerLevel(e,t,r){var o,a,c;let i;if(this.clientRunning&&this.isInitialSyncComplete()&&(i=(c=(a=(o=this.getRoom(e))==null?void 0:o.currentState)==null?void 0:a.getStateEvents(ie.RoomPowerLevels,""))==null?void 0:c.getContent()),!i)try{i=await this.getStateEvent(e,ie.RoomPowerLevels,"")}catch(l){if(l instanceof mn&&l.errcode==="M_NOT_FOUND")i={};else throw l}i=iw(i),i!=null&&i.users||(i.users={});const s=Array.isArray(t)?t:[t];for(const l of s)r==null?delete i.users[l]:i.users[l]=r;return this.sendStateEvent(e,ie.RoomPowerLevels,i,"")}async unstable_createLiveBeacon(e,t){return this.unstable_setLiveBeacon(e,t)}async unstable_setLiveBeacon(e,t){return this.sendStateEvent(e,kP.name,t,this.getUserId())}sendEvent(e,t,r,i,s){let o,a,c,l;return!(t!=null&&t.startsWith(ta))&&t!==null?(l=i,c=r,a=t,o=null):(l=s,c=i,a=r,o=t),this.addThreadRelationIfNeeded(c,o,e),this.sendCompleteEvent(e,o,{type:a,content:c},l)}addThreadRelationIfNeeded(e,t,r){var i,s,o,a;if(t&&!((i=e["m.relates_to"])!=null&&i.rel_type)){const c=!!((s=e["m.relates_to"])!=null&&s["m.in_reply_to"]);e["m.relates_to"]={...e["m.relates_to"],rel_type:en.name,event_id:t,is_falling_back:!c};const l=(o=this.getRoom(r))==null?void 0:o.getThread(t);l&&!c&&(e["m.relates_to"]["m.in_reply_to"]={event_id:((a=l.lastReply(u=>u.isRelation(en.name)&&!u.status))==null?void 0:a.getId())??t})}}sendCompleteEvent(e,t,r,i,s){let o,a;typeof i=="string"?a=i:(o=i,a=s),a||(a=this.makeTxnId());const c=new Ji(Object.assign(r,{event_id:"~"+e+":"+a,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:new Date().getTime()})),l=this.getRoom(e),u=t?l==null?void 0:l.getThread(t):void 0;u&&c.setThread(u),o||(this.reEmitter.reEmit(c,[pn.Replaced,pn.VisibilityChange]),l==null||l.reEmitter.reEmit(c,[pn.BeforeRedaction]));const h=c.getAssociatedId();if(h!=null&&h.startsWith("~")){const m=l==null?void 0:l.getPendingEvents().find(v=>v.getId()===h);m==null||m.once(pn.LocalEventIdReplaced,()=>{c.updateAssociatedId(m.getId())})}const p=c.getType();return this.logger.debug(`sendEvent of type ${p} in ${e} with txnId ${a}${o?" (delayed event)":""}`),c.setTxnId(a),c.setStatus(rt.SENDING),o?this.encryptAndSendEvent(l,c,o):(l==null||l.addPendingEvent(c,a),c.status===rt.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(l,c))}async encryptAndSendEvent(e,t,r){if(r)return this.sendEventHttpRequest(t,r);try{let i;this.eventsBeingEncrypted.add(t.getId());try{await this.encryptEventIfNeeded(t,e??void 0)}finally{i=!this.eventsBeingEncrypted.delete(t.getId())}if(i)return{};t.status===rt.ENCRYPTING&&this.updatePendingEventStatus(e,t,rt.SENDING);let s=null;return this.scheduler&&(s=this.scheduler.queueEvent(t),s&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,rt.QUEUED)),s||(s=this.sendEventHttpRequest(t),e&&(s=s.then(o=>(e.updatePendingEvent(t,rt.SENT,o.event_id),o)))),await s}catch(i){this.logger.error("Error sending event",i);try{t.error=i,this.updatePendingEventStatus(e,t,rt.NOT_SENT)}catch(s){this.logger.error("Exception in error handler!",s)}throw i instanceof mn&&(i.event=t),i}}async encryptEventIfNeeded(e,t){if(t&&await this.shouldEncryptEventForRoom(e,t)&&!(!this.cryptoBackend&&this.usingExternalCrypto)){if(!this.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");this.updatePendingEventStatus(t,e,rt.ENCRYPTING),await this.cryptoBackend.encryptEvent(e,t)}}async shouldEncryptEventForRoom(e,t){var r;return e.isEncrypted()||e.getType()===ie.Reaction||e.isRedaction()?!1:!!(t.hasEncryptionStateEvent()||await((r=this.cryptoBackend)==null?void 0:r.isEncryptionEnabledInRoom(t.roomId)))}getEncryptedIfNeededEventType(e,t){var r;return t===ie.Reaction?t:(r=this.getRoom(e))!=null&&r.hasEncryptionStateEvent()?ie.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,r){e?e.updatePendingEvent(t,r):t.setStatus(r)}sendEventHttpRequest(e,t){let r=e.getTxnId();r||(r=this.makeTxnId(),e.setTxnId(r));const i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:r};let s;if(e.isState()){let a="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(a="/rooms/$roomId/state/$eventType/$stateKey"),s=Le(a,i)}else e.isRedaction()&&e.event.redacts?s=Le("/rooms/$roomId/redact/$redactsEventId/$txnId",{$redactsEventId:e.event.redacts,...i}):s=Le("/rooms/$roomId/send/$eventType/$txnId",i);const o=e.getWireContent();return t?this.http.authedRequest(de.Put,s,O5(t),o):this.http.authedRequest(de.Put,s,void 0,o).then(a=>(this.logger.debug(`Event sent to ${e.getRoomId()} with event id ${a.event_id}`),a))}redactEvent(e,t,r,i,s){r!=null&&r.startsWith(ta)||(s=i,i=r,r=t,t=null);const a={reason:s==null?void 0:s.reason};if((s==null?void 0:s.with_rel_types)!==void 0){if(this.canSupport.get(vs.RelationBasedRedactions)===Vr.Unsupported)throw new Error(`Server does not support relation based redactions roomId ${e} eventId ${r} txnId: ${i} threadId ${t}`);const c=this.canSupport.get(vs.RelationBasedRedactions)===Vr.Stable?FR.stable:FR.unstable;a[c]=s.with_rel_types}return this.sendCompleteEvent(e,t,{type:ie.RoomRedaction,content:a,redacts:r},i)}sendMessage(e,t,r,i){typeof t!="string"&&t!==null&&(i=r,r=t,t=null);const s=ie.RoomMessage,o=r;return this.sendEvent(e,t,s,o,i)}sendTextMessage(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Gj(r);return this.sendMessage(e,t,s,i)}sendNotice(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=qj(r);return this.sendMessage(e,t,s,i)}sendEmoteMessage(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Kj(r);return this.sendMessage(e,t,s,i)}sendImageMessage(e,t,r,i,s="Image"){!(t!=null&&t.startsWith(ta))&&t!==null&&(s=i||"Image",i=r,r=t,t=null);const o={msgtype:zo.Image,url:r,info:i,body:s};return this.sendMessage(e,t,o)}sendStickerMessage(e,t,r,i,s="Sticker"){!(t!=null&&t.startsWith(ta))&&t!==null&&(s=i||"Sticker",i=r,r=t,t=null);const o={url:r,info:i,body:s};return this.sendEvent(e,t,ie.Sticker,o)}sendHtmlMessage(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Bj(r,i);return this.sendMessage(e,t,s)}sendHtmlNotice(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Hj(r,i);return this.sendMessage(e,t,s)}sendHtmlEmote(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Vj(r,i);return this.sendMessage(e,t,s)}async _unstable_sendDelayedEvent(e,t,r,i,s,o){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","sendDelayedEvent");return this.addThreadRelationIfNeeded(s,r,e),this.sendCompleteEvent(e,r,{type:i,content:s},t,o)}async _unstable_sendDelayedStateEvent(e,t,r,i,s="",o={}){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","sendDelayedStateEvent");const a={$roomId:e,$eventType:r,$stateKey:s};let c=Le("/rooms/$roomId/state/$eventType",a);return s!==void 0&&(c=Le(c+"/$stateKey",a)),this.http.authedRequest(de.Put,c,O5(t),i,o)}async _unstable_getDelayedEvents(e){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","getDelayedEvents");const t=e?{from:e}:void 0;return await this.http.authedRequest(de.Get,"/delayed_events",t,void 0,{prefix:`${lr.Unstable}/${ga}`})}async _unstable_updateDelayedEvent(e,t,r={}){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","updateDelayedEvent");const i=Le("/delayed_events/$delayId",{$delayId:e}),s={action:t};return await this.http.authedRequest(de.Post,i,void 0,s,{...r,prefix:`${lr.Unstable}/${ga}`})}async sendReceipt(e,t,r,i=!1){if(this.isGuest())return Promise.resolve({});const s=Le("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),a=!i&&this.supportsThreads()?{...r,thread_id:Kf(e)}:r,c=this.http.authedRequest(de.Post,s,void 0,a||{}),l=this.getRoom(e.getRoomId());return l&&this.credentials.userId&&l.addLocalEchoReceipt(this.credentials.userId,e,t,i),c}async sendReadReceipt(e,t=ci.Read,r=!1){if(!e)return;const i=e.getId(),s=this.getRoom(e.getRoomId());if(s!=null&&s.hasPendingEvent(i))throw new Error(`Cannot set read receipt to a pending event (${i})`);return this.sendReceipt(e,t,{},r)}async setRoomReadMarkers(e,t,r,i){const s=this.getRoom(e);if(s!=null&&s.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let o;if(r){if(o=r.getId(),s!=null&&s.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);s==null||s.addLocalEchoReceipt(this.credentials.userId,r,ci.Read)}let a;if(i){if(a=i.getId(),s!=null&&s.hasPendingEvent(a))throw new Error(`Cannot set read receipt to a pending event (${a})`);s==null||s.addLocalEchoReceipt(this.credentials.userId,i,ci.ReadPrivate)}return await this.setRoomReadMarkersHttpRequest(e,t,o,a)}getUrlPreview(e,t){t=Math.floor(t/6e4)*6e4;const r=new URL(e);r.hash="",e=r.toString();const i=t+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];const s=this.http.authedRequest(de.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:ud.V3,priority:"low"});return this.urlPreviewCache[i]=s,s}sendTyping(e,t,r){if(this.isGuest())return Promise.resolve({});const i=Le("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),s={typing:t};return t&&(s.timeout=r||2e4),this.http.authedRequest(de.Put,i,void 0,s)}getRoomUpgradeHistory(e,t=!1,r=!1){const i=this.getRoom(e);if(!i)return[];const s=this.findPredecessorRooms(i,t,r),o=this.findSuccessorRooms(i,t,r);return[...s,i,...o]}findPredecessorRooms(e,t,r){var a,c;const i=[],s=new Set([e.roomId]);let o=(a=e.findPredecessor(r))==null?void 0:a.roomId;for(;o!==null;){if(o){if(s.has(o))break;s.add(o)}const l=this.getRoom(o);if(l===null)break;if(t){const u=l.currentState.getStateEvents(ie.RoomTombstone,"");if(!u||u.getContent().replacement_room!==e.roomId)break}i.splice(0,0,l),e=l,o=(c=e.findPredecessor(r))==null?void 0:c.roomId}return i}findSuccessorRooms(e,t,r){var o;const i=[];let s=e.currentState.getStateEvents(ie.RoomTombstone,"");for(;s;){const a=this.getRoom(s.getContent().replacement_room);if(!a||a.roomId===e.roomId)break;if(t){const l=(o=a.findPredecessor(r))==null?void 0:o.roomId;if(!l||l!==e.roomId)break}if(i.push(a),new Set(i.map(l=>l.roomId)).size<i.length)return i.slice(0,i.length-1);e=a,s=e.currentState.getStateEvents(ie.RoomTombstone,"")}return i}invite(e,t,r){return this.membershipChange(e,t,We.Invite,r)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}async inviteByThreePid(e,t,r){var a;const i=Le("/rooms/$roomId/invite",{$roomId:e}),s=this.getIdentityServerUrl(!0);if(!s)return Promise.reject(new mn({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));const o={id_server:s,medium:t,address:r};if((a=this.identityServer)!=null&&a.getAccessToken){const c=await this.identityServer.getAccessToken();c&&(o.id_access_token=c)}return this.http.authedRequest(de.Post,i,void 0,o)}leave(e){return this.membershipChange(e,void 0,We.Leave)}leaveRoomChain(e,t=!0){const r=this.getRoomUpgradeHistory(e);let i=r;if(!t){i=[];for(const c of r)if(i.push(c),c.roomId===e)break}const s={},o=[],a=c=>this.leave(c).then(()=>{delete s[c]}).catch(l=>{s[c]=l});for(const c of i)o.push(a(c.roomId));return Promise.all(o).then(()=>s)}ban(e,t,r){return this.membershipChange(e,t,We.Ban,r)}async forget(e,t=!0){const r=Le("/rooms/$room_id/forget",{$room_id:e}),i=await this.http.authedRequest(de.Post,r);return t&&(this.store.removeRoom(e),this.emit("deleteRoom",e)),i}unban(e,t){const r=Le("/rooms/$roomId/unban",{$roomId:e}),i={user_id:t};return this.http.authedRequest(de.Post,r,void 0,i)}kick(e,t,r){const i=Le("/rooms/$roomId/kick",{$roomId:e}),s={user_id:t,reason:r};return this.http.authedRequest(de.Post,i,void 0,s)}membershipChange(e,t,r,i){const s=Le("/rooms/$room_id/$membership",{$room_id:e,$membership:r});return this.http.authedRequest(de.Post,s,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e,t=!1){if(!e.getPushActions()||t){const{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushActions()}getPushDetailsForEvent(e,t=!1){if(!e.getPushDetails()||t){const{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushDetails()}setProfileInfo(e,t){const r=Le("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(de.Put,r,void 0,t)}async setDisplayName(e){const t=await this.setProfileInfo("displayname",{displayname:e}),r=this.getUser(this.getUserId());return r&&(r.displayName=e,r.emit(Ol.DisplayName,r.events.presence,r)),t}async setAvatarUrl(e){const t=await this.setProfileInfo("avatar_url",{avatar_url:e}),r=this.getUser(this.getUserId());return r&&(r.avatarUrl=e,r.emit(Ol.AvatarUrl,r.events.presence,r)),t}mxcUrlToHttp(e,t,r,i,s,o,a){return ow(this.baseUrl,e,t,r,i,s,o,a)}async setSyncPresence(e){var t;(t=this.syncApi)==null||t.setPresence(e)}async setPresence(e){const t=Le("/presence/$userId/status",{$userId:this.credentials.userId});if(["offline","online","unavailable"].indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);await this.http.authedRequest(de.Put,t,void 0,e)}getPresence(e){const t=Le("/presence/$userId/status",{$userId:e});return this.http.authedRequest(de.Get,t)}scrollback(e,t=30){let r=0,i=this.ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){const a=Date.now()-i.errorTs;r=Math.max(Foe-a,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);const s=this.store.scrollback(e,t).length;if(s===t)return Promise.resolve(e);t=t-s;const o=new Promise((a,c)=>{Td(r).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,bt.Backward)).then(l=>{const u=l.chunk.map(this.getEventMapper());if(l.state){const v=l.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(v)}const[h,p,m]=e.partitionThreadedEvents(u);this.processAggregatedTimelineEvents(e,h),e.addEventsToTimeline(h,!0,!0,e.getLiveTimeline()),this.processThreadEvents(e,p,!0),m.forEach(v=>e.relations.aggregateChildEvent(v)),e.oldState.paginationToken=l.end??null,l.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,u,l.end??null,!0),delete this.ongoingScrollbacks[e.roomId],a(e)}).catch(l=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},c(l)})});return i={promise:o},this.ongoingScrollbacks[e.roomId]=i,o}getEventMapper(e){return Xse(this,e||{})}async getEventTimeline(e,t){var m,v;if(!this.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&&this.supportsThreads())return this.getThreadTimeline(e,t);const r=Le("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let i;(m=this.clientOpts)!=null&&m.lazyLoadMembers&&(i={filter:JSON.stringify(ys.LAZY_LOADING_MESSAGES_FILTER)});const s=await this.http.authedRequest(de.Get,r,i);if(!s.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const o=this.getEventMapper(),a=o(s.event);if(a.isRelation(en.name)){this.logger.warn("Tried loading a regular timeline at the position of a thread event");return}const c=[...s.events_after.reverse().map(o),a,...s.events_before.map(o)];let l=e.getTimelineForEvent(c[0].getId());l?l.getState(Be.BACKWARDS).setUnknownStateEvents(s.state.map(o)):(l=e.addTimeline(),l.initialiseState(s.state.map(o)),l.getState(Be.FORWARDS).paginationToken=s.end);const[u,h,p]=e.room.partitionThreadedEvents(c);return e.addEventsToTimeline(u,!0,!1,l,s.start),this.processThreadEvents(e.room,h,!0),this.processAggregatedTimelineEvents(e.room,u),p.forEach(g=>e.relations.aggregateChildEvent(g)),e.getTimelineForEvent(t)??((v=e.room.findThreadForEvent(a))==null?void 0:v.liveTimeline)??l}async getThreadTimeline(e,t){var l,u,h;if(!this.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");const r=Le("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),i={limit:"0"};(l=this.clientOpts)!=null&&l.lazyLoadMembers&&(i.filter=JSON.stringify(ys.LAZY_LOADING_MESSAGES_FILTER));const s=await this.http.authedRequest(de.Get,r,i),o=this.getEventMapper(),a=o(s.event);if(!e.canContain(a))return;const c=this.canSupport.get(vs.RelationsRecursion)!==Vr.Unsupported;if(Gr.hasServerSideSupport)if(Gr.hasServerSideFwdPaginationSupport){if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const p=e.thread,m=await this.fetchRelations(e.room.roomId,p.id,null,null,{dir:bt.Backward,from:s.start,recurse:c||void 0}),v=await this.fetchRelations(e.room.roomId,p.id,null,null,{dir:bt.Forward,from:s.end,recurse:c||void 0}),g=[...v.chunk.reverse().filter(BT(p.id)).map(o),a,...m.chunk.filter(BT(p.id)).map(o)];for(const b of g)await((u=e.thread)==null?void 0:u.processEvent(b));let S=e.getTimelineForEvent(a.getId());if(S?S.getState(Be.BACKWARDS).setUnknownStateEvents(s.state.map(o)):(S=e.addTimeline(),S.initialiseState(s.state.map(o))),e.addEventsToTimeline(g,!0,!1,S,v.next_batch),!m.next_batch){const b=await this.fetchRoomEvent(e.room.roomId,p.id);e.addEventsToTimeline([o(b)],!0,!1,S,null)}return S.setPaginationToken(m.next_batch??null,bt.Backward),S.setPaginationToken(v.next_batch??null,bt.Forward),this.processAggregatedTimelineEvents(e.room,g),e.getTimelineForEvent(t)??S}else{const p=e.thread,m=await this.fetchRelations(e.room.roomId,p.id,en.name,null,{dir:bt.Backward,from:s.start,recurse:c||void 0}),v=[];let g=s.end;for(;g;){const R=await this.fetchRelations(e.room.roomId,p.id,en.name,null,{dir:bt.Forward,from:g,recurse:c||void 0});g=R.next_batch??null,v.push(...R.chunk)}const S=[...v.reverse().map(o),a,...m.chunk.map(o)];for(const R of S)await((h=e.thread)==null?void 0:h.processEvent(R));const b=e.getLiveTimeline();if(b.getState(Be.BACKWARDS).setUnknownStateEvents(s.state.map(o)),e.addEventsToTimeline(S,!0,!1,b,null),!m.next_batch){const R=await this.fetchRoomEvent(e.room.roomId,p.id);e.addEventsToTimeline([o(R)],!0,!1,b,null)}return b.setPaginationToken(m.next_batch??null,bt.Backward),b.setPaginationToken(null,bt.Forward),this.processAggregatedTimelineEvents(e.room,S),b}}async getLatestTimeline(e){var r,i,s,o;if(!this.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");let t;if(e.threadListType!==null)t=(r=(await this.createThreadListMessagesRequest(e.room.roomId,null,1,bt.Backward,e.threadListType,e.getFilter())).chunk)==null?void 0:r[0];else if(e.thread&&Gr.hasServerSideSupport){const a=this.canSupport.get(vs.RelationsRecursion)!==Vr.Unsupported;t=(i=(await this.fetchRelations(e.room.roomId,e.thread.id,en.name,null,{dir:bt.Backward,limit:1,recurse:a||void 0})).chunk)==null?void 0:i[0]}else{const a=Le("/rooms/$roomId/messages",{$roomId:e.room.roomId}),c={dir:"b"};(s=this.clientOpts)!=null&&s.lazyLoadMembers&&(c.filter=JSON.stringify(ys.LAZY_LOADING_MESSAGES_FILTER)),t=(o=(await this.http.authedRequest(de.Get,a,c)).chunk)==null?void 0:o[0]}if(!t)throw new Error("No message returned when trying to construct getLatestTimeline");return this.getEventTimeline(e,t.event_id)}createMessagesRequest(e,t,r=30,i,s){var l,u;const o=Le("/rooms/$roomId/messages",{$roomId:e}),a={limit:r.toString(),dir:i};t&&(a.from=t);let c=null;return(l=this.clientOpts)!=null&&l.lazyLoadMembers&&(c=Object.assign({},ys.LAZY_LOADING_MESSAGES_FILTER)),s&&(c=c||{},Object.assign(c,(u=s.getRoomTimelineFilterComponent())==null?void 0:u.toJSON())),c&&(a.filter=JSON.stringify(c)),this.http.authedRequest(de.Get,o,a)}createThreadListMessagesRequest(e,t,r=30,i=bt.Backward,s=To.All,o){var h,p;const a=Le("/rooms/$roomId/threads",{$roomId:e}),c={limit:r.toString(),dir:i,include:nB(s)};t&&(c.from=t);let l={};(h=this.clientOpts)!=null&&h.lazyLoadMembers&&(l={...ys.LAZY_LOADING_MESSAGES_FILTER}),o&&(l={...l,...(p=o.getRoomTimelineFilterComponent())==null?void 0:p.toJSON()}),Object.keys(l).length&&(c.filter=JSON.stringify(l));const u={prefix:Gr.hasServerSideListSupport===ha.Stable?lr.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(de.Get,a,c,void 0,u).then(m=>{var v;return{...m,chunk:(v=m.chunk)==null?void 0:v.reverse(),start:m.prev_batch,end:m.next_batch}})}paginateEventTimeline(e,t){const r=e.getTimelineSet()===this.notifTimelineSet,i=this.getRoom(e.getRoomId()),s=e.getTimelineSet().threadListType,o=e.getTimelineSet().thread;t=t||{};const a=t.backwards||!1;if(r&&!a)throw new Error("paginateNotifTimeline can only paginate backwards");const c=a?Be.BACKWARDS:Be.FORWARDS,l=e.getPaginationToken(c),u=e.paginationRequests[c];if(u)return u;let h,p,m;if(r)h="/notifications",p={limit:(t.limit??30).toString(),only:"highlight"},l&&l!=="end"&&(p.from=l),m=this.http.authedRequest(de.Get,h,p).then(async v=>{const g=v.next_token,S=[];v.notifications=v.notifications.filter(Po);for(let R=0;R<v.notifications.length;R++){const k=v.notifications[R],I=this.getEventMapper()(k.event);this.getPushDetailsForEvent(I,!0),I.event.room_id=k.room_id,S[R]=I}const b=e.getTimelineSet();return b.addEventsToTimeline(S,a,!1,e,g),this.processAggregatedTimelineEvents(b.room,S),a&&!v.next_token&&e.setPaginationToken(null,c),!!v.next_token}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m;else if(s!==null){if(!i)throw new Error("Unknown room "+e.getRoomId());if(!Gr.hasServerSideFwdPaginationSupport&&c===bt.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");m=this.createThreadListMessagesRequest(e.getRoomId(),l,t.limit,c,s,e.getFilter()).then(v=>{if(v.state){const R=e.getState(c),k=v.state.filter(Po).map(this.getEventMapper());R.setUnknownStateEvents(k)}const g=v.end,S=v.chunk.filter(Po).map(this.getEventMapper());return e.getTimelineSet().addEventsToTimeline(S,a,!1,e,g),this.processAggregatedTimelineEvents(i,S),this.processThreadRoots(i,S,a),a&&v.end==v.start&&e.setPaginationToken(null,c),v.end!==v.start}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m}else if(o){const v=this.getRoom(e.getRoomId()??void 0);if(!v)throw new Error("Unknown room "+e.getRoomId());const g=this.canSupport.get(vs.RelationsRecursion)!==Vr.Unsupported;m=this.fetchRelations(e.getRoomId()??"",o.id,null,null,{dir:c,limit:t.limit,from:l??void 0,recurse:g||void 0}).then(async S=>{const b=this.getEventMapper(),R=S.chunk.filter(Po).filter(BT(o.id)).map(b);for(const T of R.slice().reverse()){await(o==null?void 0:o.processEvent(T));const C=T.getSender();(!a||(o==null?void 0:o.getEventReadUpTo(C))===null)&&v.addLocalEchoReceipt(C,T,ci.Read)}const k=S.next_batch,I=e.getTimelineSet();if(I.addEventsToTimeline(R,a,!1,e,k??null),!k&&a){const T=o.rootEvent??b(await this.fetchRoomEvent(e.getRoomId()??"",o.id));I.addEventsToTimeline([T],!0,!1,e,null)}return this.processAggregatedTimelineEvents(I.room,R),a&&!k&&e.setPaginationToken(null,c),!!k}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m}else{if(!i)throw new Error("Unknown room "+e.getRoomId());m=this.createMessagesRequest(e.getRoomId(),l,t.limit,c,e.getFilter()).then(v=>{if(v.state){const T=e.getState(c),C=v.state.filter(Po).map(this.getEventMapper());T.setUnknownStateEvents(C)}const g=v.end,S=v.chunk.filter(Po).map(this.getEventMapper()),b=e.getTimelineSet(),[R,,k]=i.partitionThreadedEvents(S);b.addEventsToTimeline(R,a,!1,e,g),this.processAggregatedTimelineEvents(i,R),this.processThreadRoots(i,R.filter(T=>T.getServerAggregatedRelation(en.name)),!1),k.forEach(T=>i.relations.aggregateChildEvent(T));const I=v.end===void 0||v.end===v.start;return a&&I&&e.setPaginationToken(null,c),!I}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m}return m}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e,t=20){var r;return(r=this.peekSync)==null||r.stopPeeking(),this.peekSync=new rd(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,t)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const r=this.sendStateEvent(e,ie.RoomGuestAccess,{guest_access:t.allowJoin?uv.CanJoin:uv.Forbidden},"");let i=Promise.resolve();return t.allowRead&&(i=this.sendStateEvent(e,ie.RoomHistoryVisibility,{history_visibility:vw.WorldReadable},"")),Promise.all([i,r]).then()}requestRegisterEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestRegisterMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestAdd3pidEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestAdd3pidMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestPasswordEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestPasswordMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}async requestTokenFromEndpoint(e,t){const r=Object.assign({},t);return this.http.request(de.Post,e,void 0,r)}getRoomPushRule(e,t){var r,i;if(this.pushRules)return(i=(r=this.pushRules[e])==null?void 0:r.room)==null?void 0:i.find(s=>s.rule_id===t);throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,r){let i,s=!1;const o=this.getRoomPushRule(e,t);if(o!=null&&o.actions.includes(Sc.DontNotify)&&(s=!0),!r)s&&(i=this.deletePushRule(e,pr.RoomSpecific,o.rule_id));else if(!o)i=this.addPushRule(e,pr.RoomSpecific,t,{actions:[Sc.DontNotify]});else if(!s){const a=Zl();this.deletePushRule(e,pr.RoomSpecific,o.rule_id).then(()=>{this.addPushRule(e,pr.RoomSpecific,t,{actions:[Sc.DontNotify]}).then(()=>{a.resolve()}).catch(c=>{a.reject(c)})}).catch(c=>{a.reject(c)}),i=a.promise}if(i)return new Promise((a,c)=>{i.then(()=>{this.getPushRules().then(l=>{this.pushRules=l,a()}).catch(l=>{c(l)})}).catch(l=>{this.getPushRules().then(u=>{this.pushRules=u,c(l)}).catch(u=>{c(l)})})})}searchMessageText(e){const t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:RP.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},r={_query:t,results:[],highlights:[]};return this.search({body:t}).then(i=>this.processRoomEventsSearch(r,i))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;const t={body:e._query,next_batch:e.next_batch},r=this.search(t,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=r,r}processRoomEventsSearch(e,t){var a;const r=t.search_categories.room_events;e.count=r.count,e.next_batch=r.next_batch;const i=new Set(r.highlights);e.highlights.forEach(c=>{i.add(c)}),e.highlights=Array.from(i);const s=this.getEventMapper(),o=((a=r.results)==null?void 0:a.length)??0;for(let c=0;c<o;c++){const l=gw.fromJson(r.results[c],s),u=this.getRoom(l.context.getEvent().getRoomId());if(u)for(const h of l.context.getTimeline())h.setMetadata(u.currentState,!1);e.results.push(l)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const e=new rd(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){const t=Le("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,t,void 0,e).then(r=>{const i=ys.fromJson(this.credentials.userId,r.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,t,r){if(r){const s=this.store.getFilter(e,t);if(s)return Promise.resolve(s)}const i=Le("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(de.Get,i).then(s=>{const o=ys.fromJson(e,t,s);return this.store.storeFilter(o),o})}async getOrCreateFilter(e,t){const r=this.store.getFilterIdByName(e);let i;if(r){try{const o=await this.getFilter(this.credentials.userId,r,!0);if(o){const a=o.getDefinition(),c=t.getDefinition();Cd(a,c)&&(i=r)}}catch(o){if(o.errcode!=="M_UNKNOWN"&&o.errcode!=="M_NOT_FOUND")throw o}i||this.store.setFilterIdByName(e,void 0)}if(i)return i;const s=await this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,s.filterId),s.filterId}getOpenIdToken(){const e=Le("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(de.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}async checkTurnServers(){if(!this.canSupportVoip)return;let e=!1;const t=this.turnServersExpiry-Date.now();if(t>A5)this.logger.debug("TURN creds are valid for another "+t+" ms: not fetching new ones."),e=!0;else{this.logger.debug("Fetching new TURN credentials");try{const r=await this.turnServer();if(r.uris){this.logger.debug("Got TURN URIs: "+r.uris+" refresh in "+r.ttl+" secs");const i={urls:r.uris,username:r.username,credential:r.password};this.turnServers=[i],this.turnServersExpiry=Date.now()+r.ttl*1e3,e=!0,this.emit("turnServers",this.turnServers)}}catch(r){this.logger.error("Failed to get TURN URIs",r),r.httpStatus===403?(this.logger.info("TURN access unavailable for this account: stopping credentials checks"),this.checkTurnServersIntervalID!==null&&globalThis.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.emit("turnServers.error",r,!0)):this.emit("turnServers.error",r,!1)}}return e}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=Le("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(de.Get,e,void 0,void 0,{prefix:""}).then(t=>t.admin)}whoisSynapseUser(e){const t=Le("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(de.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=Le("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(de.Post,t,void 0,void 0,{prefix:""})}async fetchClientWellKnown(){this.clientWellKnownPromise=lv.getRawClientConfig(this.getDomain()??void 0),this.clientWellKnown=await this.clientWellKnownPromise,this.emit("WellKnown.client",this.clientWellKnown)}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter(([r,i])=>e.includes(typeof i)).reduce((r,[i,s])=>(r[i]=s,r),{});return this.store.storeClientOptions(t)}async _unstable_getSharedRooms(e){const t=await this.doesServerSupportUnstableFeature(J$),r=await this.doesServerSupportUnstableFeature(Z$),i=await this.doesServerSupportUnstableFeature(Q$);if(!t&&!r&&!i)throw Error("Server does not support the Mutual Rooms API");let s,o;i?(s="/uk.half-shot.msc2666/user/mutual_rooms",o={user_id:e}):(s=Le(`/uk.half-shot.msc2666/user/${r?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e}),o={});const a=[];let c=null;do{const l={};c!=null&&i&&(l.batch_token=c);const u=await this.http.authedRequest(de.Get,s,{...o,...l},void 0,{prefix:lr.Unstable});a.push(...u.joined),u.next_batch_token!==void 0?c=u.next_batch_token:c=null}while(c!=null);return a}async getVersions(){if(this.serverVersionsPromise)return this.serverVersionsPromise;this.serverVersionsPromise=this.http.authedRequest(de.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(t=>{throw this.serverVersionsPromise=void 0,t});const e=await this.serverVersionsPromise;return this.canSupport=await tse(e),this.serverVersionsPromise}async isVersionSupported(e){const{versions:t}=await this.getVersions();return t&&t.includes(e)}async doesServerSupportUnstableFeature(e){const t=await this.getVersions();if(!t)return!1;const r=t.unstable_features;return r&&!!r[e]}async doesServerForceEncryptionForPreset(e){const t=await this.getVersions();if(!t)return!1;const r=t.unstable_features,i=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return r&&!!r[`io.element.e2ee_forced.${i}`]}async doesServerSupportThread(){if(await this.isVersionSupported("v1.4"))return{threads:ha.Stable,list:ha.Stable,fwdPagination:ha.Stable};try{const[e,t,r,i,s,o]=await Promise.all([this.doesServerSupportUnstableFeature("org.matrix.msc3440"),this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3856"),this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3715"),this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:S_(t,e),list:S_(i,r),fwdPagination:S_(o,s)}}catch{return{threads:ha.None,list:ha.None,fwdPagination:ha.None}}}hasLazyLoadMembersEnabled(){var e;return!!((e=this.clientOpts)!=null&&e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}async relations(e,t,r,i,s={dir:bt.Backward}){const o=i?this.getEncryptedIfNeededEventType(e,i):null,[a,c]=await Promise.all([this.fetchRoomEvent(e,t),this.fetchRelations(e,t,r,o,s)]),l=this.getEventMapper(),u=a?l(a):void 0;let h=c.chunk.map(l);if(o===ie.RoomMessageEncrypted){const p=u?h.concat(u):h;await Promise.all(p.map(m=>this.decryptEventIfNeeded(m))),i!==null&&(h=h.filter(m=>m.getType()===i))}return u&&r===sn.Replace&&(h=h.filter(p=>p.getSender()===u.getSender())),{originalEvent:u??null,events:h,nextBatch:c.next_batch??null,prevBatch:c.prev_batch??null}}generateClientSecret(){return Es(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.getCrypto()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case Nb.IS:return this.http.getUrl("/terms",void 0,da.V2,t);case Nb.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(e=!1){var t,r;return e&&((t=this.idBaseUrl)!=null&&t.startsWith("http://")||(r=this.idBaseUrl)!=null&&r.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=RT(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}getRefreshToken(){return this.http.opts.refreshToken??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(de.Get,"/register/available",{username:e}).then(t=>t.available).catch(t=>t.errcode==="M_USER_IN_USE"?!1:Promise.reject(t))}register(e,t,r,i,s,o,a){r&&(i.session=r);const c={auth:i,refresh_token:!0};return e!=null&&(c.username=e),t!=null&&(c.password=t),o!=null&&(c.guest_access_token=o),a!=null&&(c.inhibit_login=a),this.registerRequest(c)}registerGuest({body:e}={}){return this.registerRequest(e||{},"guest")}registerRequest(e,t){const r={};return t&&(r.kind=t),this.http.request(de.Post,"/register",r,e)}refreshToken(e){const t=r=>this.http.authedRequest(de.Post,"/refresh",void 0,{refresh_token:e},{prefix:r,inhibitLogoutEmit:!0});return t(lr.V3).catch(r=>{if(r.errcode==="M_UNRECOGNIZED")return t(lr.V1);throw r})}loginFlows(){return this.http.request(de.Get,"/login")}login(e,t){return this.loginRequest({...t,type:e}).then(r=>(r.access_token&&r.user_id&&(this.http.opts.accessToken=r.access_token,this.credentials={userId:r.user_id}),r))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",r,i){let s="/login/"+t+"/redirect";r&&(s+="/"+r);const o={redirectUrl:e,[$oe.unstable]:i};return this.http.getUrl(s,o).href}loginWithToken(e){return this.login("m.login.token",{token:e})}async loginRequest(e){return await this.http.authedRequest(de.Post,"/login",void 0,e)}async logout(e=!1){return e&&(this.stopClient(),this.http.abort()),this.http.authedRequest(de.Post,"/logout")}deactivateAccount(e,t){const r={};return e&&(r.auth=e),t!==void 0&&(r.erase=t),this.http.authedRequest(de.Post,"/account/deactivate",void 0,r)}async requestLoginToken(e){const t={auth:e};return this.http.authedRequest(de.Post,"/login/get_token",void 0,t,{prefix:lr.V1})}getFallbackAuthUrl(e,t){const r=Le("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(r,{session:t}).href}async createRoom(e){var r;const t=(e.invite_3pid||[]).filter(i=>!i.id_access_token);if(t.length>0&&((r=this.identityServer)!=null&&r.getAccessToken)){const i=await this.identityServer.getAccessToken();if(i)for(const s of t)s.id_access_token=i}return this.http.authedRequest(de.Post,"/createRoom",void 0,e)}fetchRelations(e,t,r,i,s={dir:bt.Backward}){let o=s;Gr.hasServerSideFwdPaginationSupport===ha.Experimental&&(o=PM("dir","org.matrix.msc3715.dir",o)),this.canSupport.get(vs.RelationsRecursion)===Vr.Unstable&&(o=PM("recurse","org.matrix.msc3981.recurse",o));const a=PR(o);let c="/rooms/$roomId/relations/$eventId";r!==null?(c+="/$relationType",i!==null&&(c+="/$eventType")):i!==null&&(this.logger.warn(`eventType: ${i} ignored when fetching
|
|
33
|
+
Date.now: "${Date.now()}`);try{i=await this.membershipLoopHandler(e.type)}catch(o){throw Error(`The MembershipManager shut down because of the end condition: ${o}`)}}this._actions.splice(0,1);const s=t??i;"replace"in s?this._actions=s.replace:"insert"in s&&this._actions.push(...s.insert)}}finally{this.running=!1}s1.debug("Leave MembershipManager ActionScheduler loop (no more actions)")}initiateJoin(){var e;(e=this.wakeup)==null||e.call(this,{replace:[{ts:Date.now(),type:__.SendFirstDelayedEvent}]})}initiateLeave(){var e;(e=this.wakeup)==null||e.call(this,{replace:[{ts:Date.now(),type:__.SendScheduledDelayedLeaveEvent}]})}}const ar=M.getChild("MatrixRTCSession");var __=(n=>(n.SendFirstDelayedEvent="SendFirstDelayedEvent",n.SendJoinEvent="SendJoinEvent",n.RestartDelayedEvent="RestartDelayedEvent",n.UpdateExpiry="UpdateExpiry",n.SendMainDelayedEvent="SendMainDelayedEvent",n.SendScheduledDelayedLeaveEvent="SendScheduledDelayedLeaveEvent",n.SendLeaveEvent="SendLeaveEvent",n))(__||{});class Ub{constructor(e,t,r,i){this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,this.activated=!1,this.scheduler=new woe(a=>(this.oldStatus&&ar.debug(`MembershipManager applied action changes. Status: ${this.oldStatus} -> ${this.status}`),this.oldStatus=this.status,ar.debug(`MembershipManager before processing action. status=${this.oldStatus}`),this.membershipLoopHandler(a)));const[s,o]=[this.client.getUserId(),this.client.getDeviceId()];if(s===null)throw Error("Missing userId in client");if(o===null)throw Error("Missing deviceId in client");this.deviceId=o,this.stateKey=this.makeMembershipStateKey(s,o),this.state=Ub.defaultState}isJoined(){return this.activated}join(e,t,r){if(this.scheduler.running){ar.error("MembershipManager is already running. Ignoring join request.");return}this.fociPreferred=e,this.focusActive=t,this.leavePromiseDefer=void 0,this.activated=!0,this.state=Ub.defaultState,this.scheduler.startWithJoin().then(()=>{var i;this.scheduler.running||((i=this.leavePromiseDefer)==null||i.resolve(!0),this.leavePromiseDefer=void 0)}).catch(i=>{ar.error("MembershipManager stopped because: ",i),r==null||r(i)}).finally(()=>this.activated=!1)}leave(e){return this.scheduler.running?(this.leavePromiseDefer||(this.leavePromiseDefer=Zl(),this.activated=!1,this.scheduler.initiateLeave(),e&&setTimeout(()=>{var t;return(t=this.leavePromiseDefer)==null?void 0:t.resolve(!1)},e)),this.leavePromiseDefer.promise):(ar.warn("Called MembershipManager.leave() even though the MembershipManager is not running"),Promise.resolve(!0))}async onRTCSessionMemberUpdate(e){const t=r=>r.sender===this.client.getUserId()&&r.deviceId===this.client.getDeviceId();if(this.isJoined()&&!e.some(t)){const r=["SendFirstDelayedEvent","SendJoinEvent"];ar.warn("Missing own membership: force re-join"),this.scheduler.actions.find(i=>r.includes(i.type))?ar.error("NewMembershipManger tried adding another `SendFirstDelayedEvent` actions even though we already have one in the Queue\nActionQueueOnMemberUpdate:",this.scheduler.actions):(this.state.hasMemberStateEvent=!1,this.scheduler.initiateJoin())}return Promise.resolve()}getActiveFocus(){if(this.focusActive)if(xP(this.focusActive)){if(this.focusActive.focus_selection==="oldest_membership"){const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else ar.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}static get defaultState(){return{hasMemberStateEvent:!1,delayId:void 0,startTime:0,rateLimitRetries:new Map,networkErrorRetries:new Map,expireUpdateIterations:1}}get callMemberEventRetryDelayMinimum(){var e;return((e=this.joinConfig)==null?void 0:e.callMemberEventRetryDelayMinimum)??3e3}get membershipEventExpiryTimeout(){var e;return((e=this.joinConfig)==null?void 0:e.membershipExpiryTimeout)??PP}get membershipEventExpiryTimeoutHeadroom(){var e;return((e=this.joinConfig)==null?void 0:e.membershipExpiryTimeoutHeadroom)??5e3}computeNextExpiryActionTs(e){return this.state.startTime+this.membershipEventExpiryTimeout*e-this.membershipEventExpiryTimeoutHeadroom}get membershipServerSideExpiryTimeout(){var e;return this.membershipServerSideExpiryTimeoutOverride??((e=this.joinConfig)==null?void 0:e.membershipServerSideExpiryTimeout)??8e3}get membershipKeepAlivePeriod(){var e;return((e=this.joinConfig)==null?void 0:e.membershipKeepAlivePeriod)??5e3}get maximumRateLimitRetryCount(){var e;return((e=this.joinConfig)==null?void 0:e.maximumRateLimitRetryCount)??10}get maximumNetworkErrorRetryCount(){var e;return((e=this.joinConfig)==null?void 0:e.maximumNetworkErrorRetryCount)??10}async membershipLoopHandler(e){switch(this.oldStatus=this.status,e){case"SendFirstDelayedEvent":return this.state.delayId?this.cancelKnownDelayIdBeforeSendFirstDelayedEvent(this.state.delayId):this.sendFirstDelayedLeaveEvent();case"RestartDelayedEvent":return this.state.delayId?this.restartDelayedEvent(this.state.delayId):fs(this.state.hasMemberStateEvent?"SendMainDelayedEvent":"SendFirstDelayedEvent");case"SendMainDelayedEvent":return this.sendMainDelayedEvent();case"SendScheduledDelayedLeaveEvent":return this.state.hasMemberStateEvent?this.state.delayId?this.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(this.state.delayId):fs("SendLeaveEvent"):{replace:[]};case"SendJoinEvent":return this.sendJoinEvent();case"UpdateExpiry":return this.updateExpiryOnJoinedEvent();case"SendLeaveEvent":return this.state.hasMemberStateEvent?this.sendFallbackLeaveEvent():{replace:[]}}}async sendFirstDelayedLeaveEvent(){return await this.client._unstable_sendDelayedStateEvent(this.room.roomId,{delay:this.membershipServerSideExpiryTimeout},ie.GroupCallMemberPrefix,{},this.stateKey).then(e=>(this.state.rateLimitRetries.set("SendFirstDelayedEvent",0),this.state.networkErrorRetries.set("SendFirstDelayedEvent",0),this.state.delayId=e.delay_id,fs("SendJoinEvent"))).catch(e=>{const t="SendFirstDelayedEvent";if(this.manageMaxDelayExceededSituation(e))return fs(t);const r=this.actionUpdateFromErrors(e,t,"sendDelayedStateEvent");return r||(this.isUnsupportedDelayedEndpoint(e)?ar.info("Not using delayed event because the endpoint is not supported"):ar.info("Not using delayed event because: "+e),fs("SendJoinEvent"))})}async cancelKnownDelayIdBeforeSendFirstDelayedEvent(e){return await this.client._unstable_updateDelayedEvent(e,Vl.Cancel).then(()=>(this.state.delayId=void 0,this.resetRateLimitCounter("SendFirstDelayedEvent"),jT("SendFirstDelayedEvent"))).catch(t=>{const r="SendFirstDelayedEvent",i=this.actionUpdateFromErrors(t,r,"updateDelayedEvent");if(i)return i;if(this.isNotFoundError(t))return this.state.delayId=void 0,jT(r);if(this.isUnsupportedDelayedEndpoint(t))return jT("SendJoinEvent");throw Error("We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle")})}async restartDelayedEvent(e){return await this.client._unstable_updateDelayedEvent(e,Vl.Restart).then(()=>(this.resetRateLimitCounter("RestartDelayedEvent"),fs("RestartDelayedEvent",this.membershipKeepAlivePeriod))).catch(t=>{const r="RestartDelayedEvent";if(this.isNotFoundError(t))return this.state.delayId=void 0,fs("SendMainDelayedEvent");if(this.isUnsupportedDelayedEndpoint(t))return{};const i=this.actionUpdateFromErrors(t,r,"updateDelayedEvent");if(i)return i;throw Error("Could not restart delayed event, even though delayed events are supported. "+t)})}async sendMainDelayedEvent(){return await this.client._unstable_sendDelayedStateEvent(this.room.roomId,{delay:this.membershipServerSideExpiryTimeout},ie.GroupCallMemberPrefix,{},this.stateKey).then(e=>(this.state.delayId=e.delay_id,this.resetRateLimitCounter("SendMainDelayedEvent"),fs("RestartDelayedEvent",this.membershipKeepAlivePeriod))).catch(e=>{const t="SendMainDelayedEvent";if(this.isUnsupportedDelayedEndpoint(e))return{};if(this.manageMaxDelayExceededSituation(e))return fs(t);const r=this.actionUpdateFromErrors(e,t,"updateDelayedEvent");if(r)return r;throw Error("Could not send delayed event, even though delayed events are supported. "+e)})}async sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(e){return await this.client._unstable_updateDelayedEvent(e,Vl.Send).then(()=>(this.state.hasMemberStateEvent=!1,this.resetRateLimitCounter("SendScheduledDelayedLeaveEvent"),{replace:[]})).catch(t=>{const r="SendLeaveEvent";if(this.isUnsupportedDelayedEndpoint(t))return{};if(this.isNotFoundError(t))return this.state.delayId=void 0,fs(r);const i=this.actionUpdateFromErrors(t,r,"updateDelayedEvent");return i||(ar.warn("Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent",t),fs(r))})}async sendJoinEvent(){return await this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,this.makeMyMembership(this.membershipEventExpiryTimeout),this.stateKey).then(()=>(this.state.startTime=Date.now(),this.state.expireUpdateIterations=1,this.state.hasMemberStateEvent=!0,this.resetRateLimitCounter("SendJoinEvent"),{insert:[{ts:Date.now(),type:"RestartDelayedEvent"},{ts:this.computeNextExpiryActionTs(this.state.expireUpdateIterations),type:"UpdateExpiry"}]})).catch(e=>{const t=this.actionUpdateFromErrors(e,"SendJoinEvent","sendStateEvent");if(t)return t;throw e})}async updateExpiryOnJoinedEvent(){const e=this.state.expireUpdateIterations+1;return await this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,this.makeMyMembership(this.membershipEventExpiryTimeout*e),this.stateKey).then(()=>(this.resetRateLimitCounter("UpdateExpiry"),this.state.expireUpdateIterations=e,{insert:[{ts:this.computeNextExpiryActionTs(e),type:"UpdateExpiry"}]})).catch(t=>{const r=this.actionUpdateFromErrors(t,"UpdateExpiry","sendStateEvent");if(r)return r;throw t})}async sendFallbackLeaveEvent(){return await this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,{},this.stateKey).then(()=>(this.resetRateLimitCounter("SendLeaveEvent"),this.state.hasMemberStateEvent=!1,{replace:[]})).catch(e=>{const t=this.actionUpdateFromErrors(e,"SendLeaveEvent","sendStateEvent");if(t)return t;throw e})}makeMembershipStateKey(e,t){const r=`${e}_${t}`;return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:`_${r}`}makeMyMembership(e){return{call_id:"",scope:"m.room",application:"m.call",device_id:this.deviceId,expires:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:this.fociPreferred??[]}}isNotFoundError(e){return e instanceof mn&&e.errcode==="M_NOT_FOUND"}manageMaxDelayExceededSituation(e){if(e instanceof mn&&e.errcode==="M_UNKNOWN"&&e.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){const t=e.data["org.matrix.msc4140.max_delay"];return typeof t=="number"&&this.membershipServerSideExpiryTimeout>t&&(this.membershipServerSideExpiryTimeoutOverride=t),ar.warn("Retry sending delayed disconnection event due to server timeout limitations:",e),!0}return!1}actionUpdateFromErrors(e,t,r){const i=this.actionUpdateFromRateLimitError(e,r,t);if(i)return i;const s=this.actionUpdateFromNetworkErrorRetry(e,t);if(s)return s}actionUpdateFromRateLimitError(e,t,r){if(!((e instanceof eu||e instanceof mn)&&e.isRateLimitError()))return;const i=this.state.rateLimitRetries.get(r)??0;if(i<this.maximumRateLimitRetryCount){let s;try{s=e.getRetryAfterMs()??5e3,ar.info(`Rate limited by server, retrying in ${s}ms`)}catch(a){ar.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of 5000",a),s=5e3}return this.state.rateLimitRetries.set(r,i+1),fs(r,s)}throw Error("Exceeded maximum retries for "+r+" attempts (client."+t+"): "+e)}actionUpdateFromNetworkErrorRetry(e,t){const r=this.state.networkErrorRetries.get(t)??0,i=this.callMemberEventRetryDelayMinimum/1e3+"s",s="("+r+"/"+this.maximumNetworkErrorRetryCount+")";if(e instanceof Error&&e.name==="AbortError")ar.warn("Network local timeout error while sending event, retrying in "+i+" "+s,e);else if(e instanceof Error&&e.message.includes("updating delayed event"))ar.warn("delayed event update timeout error, retrying in "+i+" "+s,e);else if(e instanceof Vd)ar.warn("Network connection error while sending event, retrying in "+i+" "+s,e);else if((e instanceof eu||e instanceof mn)&&typeof e.httpStatus=="number"&&e.httpStatus>=500&&e.httpStatus<600)ar.warn("Server error while sending event, retrying in "+i+" "+s,e);else return;if(r<this.maximumNetworkErrorRetryCount)return this.state.networkErrorRetries.set(t,r+1),fs(t,this.callMemberEventRetryDelayMinimum);throw Error("Reached maximum ("+this.maximumNetworkErrorRetryCount+") retries cause by: "+e)}isUnsupportedDelayedEndpoint(e){return e instanceof Nl}resetRateLimitCounter(e){this.state.rateLimitRetries.set(e,0),this.state.networkErrorRetries.set(e,0)}get status(){const e=this.scheduler.actions;if(e.length===1){const{type:t}=e[0];switch(t){case"SendFirstDelayedEvent":case"SendJoinEvent":case"SendMainDelayedEvent":return"Connecting";case"UpdateExpiry":return"Connected";case"SendScheduledDelayedLeaveEvent":case"SendLeaveEvent":return"Disconnecting"}}else if(e.length===2){const t=e.map(r=>r.type);if((t.includes("RestartDelayedEvent")||t.includes("SendMainDelayedEvent"))&&t.includes("UpdateExpiry"))return"Connected"}else if(e.length===3){const t=e.map(r=>r.type);if(t.filter(r=>r==="RestartDelayedEvent").length===2&&t.includes("UpdateExpiry"))return"Connected"}return this.scheduler.running?(ar.error("MembershipManager has an unknown state. Actions: ",e),"Unknown"):"Disconnected"}}function fs(n,e){return{insert:[{ts:Date.now()+(e??0),type:n}]}}function jT(n,e){return{replace:[{ts:Date.now()+0,type:n}]}}const Bn=M.getChild("MatrixRTCSession");class Eoe{constructor(e,t,r,i){this.client=e,this.room=t,this.getMemberships=r,this.onEncryptionKeysChanged=i,this.manageMediaKeys=!1,this.setNewKeyTimeouts=new Set,this.encryptionKeys=new Map,this.currentEncryptionKeyIndex=-1,this.statistics={counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}},this.joined=!1,this.isMyMembership=s=>s.sender===this.client.getUserId()&&s.deviceId===this.client.getDeviceId(),this.sendEncryptionKeysEvent=async s=>{if(this.keysEventUpdateTimeout!==void 0&&(clearTimeout(this.keysEventUpdateTimeout),this.keysEventUpdateTimeout=void 0),this.lastEncryptionKeyUpdateRequest=Date.now(),!this.joined)return;Bn.info(`Sending encryption keys event. indexToSend=${s}`);const o=this.client.getUserId(),a=this.client.getDeviceId();if(!o)throw new Error("No userId");if(!a)throw new Error("No deviceId");const c=this.getKeysForParticipant(o,a);if(!c){Bn.warn("Tried to send encryption keys event but no keys found!");return}if(typeof s!="number"&&this.currentEncryptionKeyIndex===-1){Bn.warn("Tried to send encryption keys event but no current key index found!");return}const l=s??this.currentEncryptionKeyIndex,u=c[l];try{const h={keys:[{index:l,key:R$(u)}],device_id:a,call_id:"",sent_ts:Date.now()};this.statistics.counters.roomEventEncryptionKeysSent+=1,await this.client.sendEvent(this.room.roomId,ie.CallEncryptionKeysPrefix,h),Bn.debug(`Embedded-E2EE-LOG updateEncryptionKeyEvent participantId=${o}:${a} numKeys=${c.length} currentKeyIndex=${this.currentEncryptionKeyIndex} keyIndexToSend=${l}`,this.encryptionKeys)}catch(h){const p=h;if(p.event&&this.client.cancelPendingEvent(p.event),this.keysEventUpdateTimeout===void 0){const m=pP(p,5e3);Bn.warn(`Failed to send m.call.encryption_key, retrying in ${m}`,h),this.keysEventUpdateTimeout=setTimeout(()=>void this.sendEncryptionKeysEvent(),m)}else Bn.info("Not scheduling key resend as another re-send is already pending")}},this.onCallEncryptionEventReceived=s=>{const o=s.getSender(),a=s.getContent(),c=a.device_id,l=a.call_id;if(!o){Bn.warn(`Received m.call.encryption_keys with no userId: callId=${l}`);return}if(l!==""){Bn.warn(`Received m.call.encryption_keys with unsupported callId: userId=${o}, deviceId=${c}, callId=${l}`);return}if(!Array.isArray(a.keys)){Bn.warn(`Received m.call.encryption_keys where keys wasn't an array: callId=${l}`);return}if(o===this.client.getUserId()&&c===this.client.getDeviceId()){Bn.info("Ignoring our own keys event");return}this.statistics.counters.roomEventEncryptionKeysReceived+=1;const u=Date.now()-(typeof a.sent_ts=="number"?a.sent_ts:s.getTs());this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=u;for(const h of a.keys){if(!h){Bn.info("Ignoring false-y key in keys event");continue}const p=h.key,m=h.index;!p||m===void 0||m===null||l===void 0||l===null||typeof c!="string"||typeof l!="string"||typeof p!="string"||typeof m!="number"?Bn.warn(`Malformed call encryption_key: userId=${o}, deviceId=${c}, encryptionKeyIndex=${m} callId=${l}`):(Bn.debug(`Embedded-E2EE-LOG onCallEncryption userId=${o}:${c} encryptionKeyIndex=${m} age=${u}ms`,this.encryptionKeys),this.setEncryptionKey(o,c,m,p,s.getTs()))}},this.onRotateKeyTimeout=()=>{if(!this.manageMediaKeys)return;this.makeNewKeyTimeout=void 0,Bn.info("Making new sender key for key rotation");const s=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(s)}}get updateEncryptionKeyThrottle(){var e;return((e=this.joinConfig)==null?void 0:e.updateEncryptionKeyThrottle)??3e3}get makeKeyDelay(){var e;return((e=this.joinConfig)==null?void 0:e.makeKeyDelay)??3e3}get useKeyDelay(){var e;return((e=this.joinConfig)==null?void 0:e.useKeyDelay)??5e3}getEncryptionKeys(){return this.encryptionKeys}join(e){var t,r;this.joinConfig=e,this.joined=!0,this.manageMediaKeys=((t=this.joinConfig)==null?void 0:t.manageMediaKeys)??this.manageMediaKeys,(r=this.joinConfig)!=null&&r.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey())}leave(){const e=this.client.getUserId(),t=this.client.getDeviceId();if(!e)throw new Error("No userId");if(!t)throw new Error("No deviceId");this.encryptionKeys.set(b_(e,t),[]),this.makeNewKeyTimeout!==void 0&&(clearTimeout(this.makeNewKeyTimeout),this.makeNewKeyTimeout=void 0);for(const r of this.setNewKeyTimeouts)clearTimeout(r);this.setNewKeyTimeouts.clear(),this.manageMediaKeys=!1,this.joined=!1}onMembershipsUpdate(e){if(this.manageMediaKeys&&this.joined){const t=new Set(e.filter(a=>!this.isMyMembership(a)).map($T)),r=new Set(this.getMemberships().filter(a=>!this.isMyMembership(a)).map($T)),i=Array.from(t).some(a=>!r.has(a)),s=Array.from(r).some(a=>!t.has(a)),o=this.lastMembershipFingerprints;if(this.storeLastMembershipFingerprints(),i)this.makeNewKeyTimeout||(Bn.debug("Member(s) have left: queueing sender key rotation"),this.makeNewKeyTimeout=setTimeout(this.onRotateKeyTimeout,this.makeKeyDelay));else if(s)Bn.debug("New member(s) have joined: re-sending keys"),this.requestSendCurrentKey();else if(o){const a=this.lastMembershipFingerprints;(Array.from(o).some(l=>!a.has(l))||Array.from(a).some(l=>!o.has(l)))&&(Bn.debug("Member(s) have updated/reconnected: re-sending keys to everyone"),this.requestSendCurrentKey())}}}makeNewSenderKey(e=!1){const t=this.client.getUserId(),r=this.client.getDeviceId();if(!t)throw new Error("No userId");if(!r)throw new Error("No deviceId");const i=k$(16),s=this.getNewEncryptionKeyIndex();return Bn.info("Generated new key at index "+s),this.setEncryptionKey(t,r,s,i,Date.now(),e),s}requestSendCurrentKey(){if(this.manageMediaKeys){if(this.lastEncryptionKeyUpdateRequest&&this.lastEncryptionKeyUpdateRequest+this.updateEncryptionKeyThrottle>Date.now()){Bn.info("Last encryption key event sent too recently: postponing"),this.keysEventUpdateTimeout===void 0&&(this.keysEventUpdateTimeout=setTimeout(()=>void this.sendEncryptionKeysEvent(),this.updateEncryptionKeyThrottle));return}this.sendEncryptionKeysEvent()}}getKeysForParticipant(e,t){var r;return(r=this.encryptionKeys.get(b_(e,t)))==null?void 0:r.map(i=>i.key)}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.getMemberships().filter(e=>!this.isMyMembership(e)).map(e=>`${$T(e)}:${e.createdTs()}`))}getNewEncryptionKeyIndex(){return this.currentEncryptionKeyIndex===-1?0:(this.currentEncryptionKeyIndex+1)%256}setEncryptionKey(e,t,r,i,s,o=!1){const a=_f(i),c=b_(e,t);this.encryptionKeys.has(c)||this.encryptionKeys.set(c,[]);const l=this.encryptionKeys.get(c),u=l[r];if(u){if(u.timestamp>s){Bn.info(`Ignoring new key at index ${r} for ${c} as it is older than existing known key`);return}if(Coe(u.key,a)){u.timestamp=s;return}}if(l[r]={key:a,timestamp:s},o){const h=setTimeout(()=>{this.setNewKeyTimeouts.delete(h),Bn.info(`Delayed-emitting key changed event for ${c} idx ${r}`),e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=r),this.onEncryptionKeysChanged(a,r,c)},this.useKeyDelay);this.setNewKeyTimeouts.add(h)}else e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=r),this.onEncryptionKeysChanged(a,r,c)}}const b_=(n,e)=>`${n}:${e}`;function Coe(n,e){return n===e?!0:!!n&&!!e&&n.length===e.length&&n.every((t,r)=>t===e[r])}const $T=n=>b_(n.sender,n.deviceId);class Toe{constructor(e,t,r,i){this.joinConfig=e,this.room=t,this.client=r,this.getOldestMembership=i,this.updateCallMembershipRunning=!1,this.needCallMembershipUpdate=!1,this.triggerCallMembershipEventUpdate=async()=>{if(this.updateCallMembershipRunning){this.needCallMembershipUpdate=!0;return}this.updateCallMembershipRunning=!0;try{do this.needCallMembershipUpdate=!1,await this.updateCallMembershipEvent();while(this.needCallMembershipUpdate)}finally{this.updateCallMembershipRunning=!1}},this.delayDisconnection=async()=>{try{const s=this.disconnectDelayId;await Ah(()=>this.client._unstable_updateDelayedEvent(s,Vl.Restart)),this.scheduleDelayDisconnection()}catch(s){M.error("Failed to delay our disconnection event:",s)}}}get callMemberEventRetryDelayMinimum(){var e;return((e=this.joinConfig)==null?void 0:e.callMemberEventRetryDelayMinimum)??3e3}get membershipExpiryTimeout(){var e;return((e=this.joinConfig)==null?void 0:e.membershipExpiryTimeout)??PP}get membershipServerSideExpiryTimeout(){var e;return this.membershipServerSideExpiryTimeoutOverride??((e=this.joinConfig)==null?void 0:e.membershipServerSideExpiryTimeout)??8e3}get membershipKeepAlivePeriod(){var e;return((e=this.joinConfig)==null?void 0:e.membershipKeepAlivePeriod)??5e3}get callMemberEventRetryJitter(){var e;return((e=this.joinConfig)==null?void 0:e.callMemberEventRetryJitter)??2e3}isJoined(){return this.relativeExpiry!==void 0}join(e,t){this.ownFocusActive=t,this.ownFociPreferred=e,this.relativeExpiry=this.membershipExpiryTimeout,this.triggerCallMembershipEventUpdate()}async leave(e=void 0){return this.relativeExpiry=void 0,this.ownFocusActive=void 0,this.memberEventTimeout&&(clearTimeout(this.memberEventTimeout),this.memberEventTimeout=void 0),e?await Promise.race([this.triggerCallMembershipEventUpdate(),Td(e,"timeout")])!=="timeout":(await this.triggerCallMembershipEventUpdate(),!0)}async onRTCSessionMemberUpdate(e){const t=r=>r.sender===this.client.getUserId()&&r.deviceId===this.client.getDeviceId();if(this.isJoined()&&!e.some(t))return M.warn("Missing own membership: force re-join"),this.triggerCallMembershipEventUpdate()}getActiveFocus(){if(this.ownFocusActive)if(xP(this.ownFocusActive)){if(this.ownFocusActive.focus_selection==="oldest_membership"){const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}else M.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{const e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}}makeNewMembership(e){return this.isJoined()?this.makeMyMembership(e):{}}makeMyMembership(e){return{call_id:"",scope:"m.room",application:"m.call",device_id:e,expires:this.relativeExpiry,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:this.ownFociPreferred??[]}}async updateCallMembershipEvent(){if(this.memberEventTimeout&&(clearTimeout(this.memberEventTimeout),this.memberEventTimeout=void 0),!this.room.getLiveTimeline().getState(Be.FORWARDS))throw new Error("Couldn't get room state for room "+this.room.roomId);const t=this.client.getUserId(),r=this.client.getDeviceId();if(!t||!r)throw new Error("User ID or device ID was null!");let i={};i=this.makeNewMembership(r);try{if(this.isJoined()){const s=this.makeMembershipStateKey(t,r),o=async()=>{try{const a=await Ah(()=>this.client._unstable_sendDelayedStateEvent(this.room.roomId,{delay:this.membershipServerSideExpiryTimeout},ie.GroupCallMemberPrefix,{},s));this.disconnectDelayId=a.delay_id}catch(a){if(a instanceof mn&&a.errcode==="M_UNKNOWN"&&a.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){const c=a.data["org.matrix.msc4140.max_delay"];if(typeof c=="number"&&this.membershipServerSideExpiryTimeout>c)return this.membershipServerSideExpiryTimeoutOverride=c,o()}M.error("Failed to prepare delayed disconnection event:",a)}};if(await o(),await Ah(()=>this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,i,s)),this.disconnectDelayId!==void 0)try{const a=this.disconnectDelayId;await Ah(()=>this.client._unstable_updateDelayedEvent(a,Vl.Restart))}catch(a){a instanceof mn&&a.errcode==="M_NOT_FOUND"&&(M.warn("Failed to update delayed disconnection event, prepare it again:",a),this.disconnectDelayId=void 0,await o())}this.disconnectDelayId!==void 0&&this.scheduleDelayDisconnection()}else{let s=!1;if(this.disconnectDelayId!==void 0){try{const o=this.disconnectDelayId;await Ah(()=>this.client._unstable_updateDelayedEvent(o,Vl.Send)),s=!0}catch(o){M.error("Failed to send our delayed disconnection event:",o)}this.disconnectDelayId=void 0}s||await Ah(()=>this.client.sendStateEvent(this.room.roomId,ie.GroupCallMemberPrefix,{},this.makeMembershipStateKey(t,r)))}M.info("Sent updated call member event.")}catch(s){const o=this.callMemberEventRetryDelayMinimum+Math.random()*this.callMemberEventRetryJitter;M.warn(`Failed to send call member event (retrying in ${o}): ${s}`),await Td(o),await this.triggerCallMembershipEventUpdate()}}scheduleDelayDisconnection(){this.memberEventTimeout=setTimeout(()=>void this.delayDisconnection(),this.membershipKeepAlivePeriod)}makeMembershipStateKey(e,t){const r=`${e}_${t}`;return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:`_${r}`}}async function Ah(n,e=1){for(;;)try{return await n()}catch(t){if(e>0&&t instanceof eu&&t.isRateLimitError()){e--;let r;const i=5e3;try{r=t.getRetryAfterMs()??i,M.info(`Rate limited by server, retrying in ${r}ms`)}catch(s){M.warn(`Error while retrieving a rate-limit retry delay, retrying after default delay of ${i}`,s),r=i}await Td(r)}else throw t}}const ps=M.getChild("MatrixRTCSession");var ts=(n=>(n.MembershipsChanged="memberships_changed",n.JoinStateChanged="join_state_changed",n.EncryptionKeyChanged="encryption_key_changed",n.MembershipManagerError="membership_manager_error",n))(ts||{});class Sf extends Yn{constructor(e,t,r){var s;super(),this.client=e,this.roomSubset=t,this.memberships=r,this.onCallEncryption=o=>{this.encryptionManager.onCallEncryptionEventReceived(o)},this.onMembershipUpdate=()=>{this.recalculateSessionMembers()},this.onRoomMemberUpdate=()=>{this.recalculateSessionMembers()},this.onRTCSessionMemberUpdate=()=>{this.recalculateSessionMembers()},this.recalculateSessionMembers=()=>{var c,l;const o=this.memberships;this.memberships=Sf.callMembershipsForRoom(this.room),this._callId=this._callId??((c=this.memberships[0])==null?void 0:c.callId),(o.length!=this.memberships.length||o.some((u,h)=>!P5.equal(u,this.memberships[h])))&&(ps.info(`Memberships for call in room ${this.roomSubset.roomId} have changed: emitting`),gre(ps,"emit MatrixRTCSessionEvent.MembershipsChanged",()=>{this.emit("memberships_changed",o,this.memberships)}),(l=this.membershipManager)==null||l.onRTCSessionMemberUpdate(this.memberships)),this.encryptionManager.onMembershipsUpdate(o),this.setExpiryTimer()},this._callId=(s=r[0])==null?void 0:s.callId;const i=this.roomSubset.getLiveTimeline().getState(Be.FORWARDS);i==null||i.on(It.Members,this.onRoomMemberUpdate),this.setExpiryTimer(),this.encryptionManager=new Eoe(this.client,this.roomSubset,()=>this.memberships,(o,a,c)=>{this.emit("encryption_key_changed",o,a,c)})}get statistics(){return this.encryptionManager.statistics}get callId(){return this._callId}static callMembershipsForRoom(e){const t=e.getLiveTimeline().getState(Be.FORWARDS);if(!t)throw ps.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);const r=t.getStateEvents(ie.GroupCallMemberPrefix),i=[];for(const s of r){const o=s.getContent(),a=Object.keys(o).length;if(a===0)continue;const c=[];if(a>1&&"focus_active"in o?c.push(o):a===1&&"memberships"in o&&ps.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session"),c.length!==0)for(const l of c)try{const u=new P5(s,l);if(u.callId!==""||u.scope!=="m.room"){ps.info("Ignoring user-scoped call");continue}if(u.isExpired()){ps.info(`Ignoring expired device membership ${u.sender}/${u.deviceId}`);continue}if(!e.hasMembershipState(u.sender??"",We.Join)){ps.info(`Ignoring membership of user ${u.sender} who is not in the room.`);continue}i.push(u)}catch(u){ps.warn("Couldn't construct call membership: ",u)}}return i.sort((s,o)=>s.createdTs()-o.createdTs()),i.length>1&&ps.debug(`Call memberships in room ${e.roomId}, in order: `,i.map(s=>[s.createdTs(),s.sender])),i}static roomSessionForRoom(e,t){const r=Sf.callMembershipsForRoom(t);return new Sf(e,t,r)}get room(){return this.roomSubset}isJoined(){var e;return((e=this.membershipManager)==null?void 0:e.isJoined())??!1}async stop(){var t;await((t=this.membershipManager)==null?void 0:t.leave(1e3)),this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);const e=this.roomSubset.getLiveTimeline().getState(Be.FORWARDS);e==null||e.off(It.Members,this.onRoomMemberUpdate)}joinRoomSession(e,t,r){if(this.isJoined()){ps.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`);return}else(r==null?void 0:r.useNewMembershipManager)??!1?this.membershipManager=new Ub(r,this.roomSubset,this.client,()=>this.getOldestMembership()):this.membershipManager=new Toe(r,this.roomSubset,this.client,()=>this.getOldestMembership());this.membershipManager.join(e,t,i=>{ps.error("MembershipManager encountered an unrecoverable error: ",i),this.emit("membership_manager_error",i),this.emit("join_state_changed",this.isJoined())}),this.encryptionManager.join(r),this.emit("join_state_changed",!0)}async leaveRoomSession(e=void 0){if(!this.isJoined())return ps.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`),!1;ps.info(`Leaving call session in room ${this.roomSubset.roomId}`),this.encryptionManager.leave();const t=this.membershipManager.leave(e);return this.emit("join_state_changed",!1),await t}getActiveFocus(){var e;return(e=this.membershipManager)==null?void 0:e.getActiveFocus()}getOldestMembership(){return this.memberships[0]}getFocusInUse(){const e=this.getOldestMembership();if((e==null?void 0:e.getFocusSelection())==="oldest_membership")return e.getPreferredFoci()[0]}reemitEncryptionKeys(){this.encryptionManager.getEncryptionKeys().forEach((e,t)=>{e.forEach((r,i)=>{this.emit("encryption_key_changed",r.key,i,t)})})}getEncryptionKeys(){const e=this.encryptionManager.getEncryptionKeys()??new Map;return Array.from(e.entries()).map(([t,r])=>[t,r.map(i=>i.key)]).values()}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);let e;for(const t of this.memberships){const r=t.getMsUntilExpiry();r!==void 0&&(e===void 0||r<e)&&(e=r)}e!=null&&(this.expiryTimeout=setTimeout(this.onRTCSessionMemberUpdate,e))}}const Fm=M.getChild("MatrixRTCSessionManager");var lk=(n=>(n.SessionStarted="session_started",n.SessionEnded="session_ended",n))(lk||{});class Ioe extends Yn{constructor(e){super(),this.client=e,this.roomSessions=new Map,this.onTimeline=t=>{this.consumeCallEncryptionEvent(t)},this.onRoom=t=>{this.refreshRoom(t)},this.onRoomState=(t,r)=>{const i=this.client.getRoom(t.getRoomId());if(!i){Fm.error(`Got room state event for unknown room ${t.getRoomId()}!`);return}t.getType()==ie.GroupCallMemberPrefix&&this.refreshRoom(i)}}start(){for(const e of this.client.getRooms()??[]){const t=Sf.roomSessionForRoom(this.client,e);t.memberships.length>0&&this.roomSessions.set(e.roomId,t)}this.client.on(Ge.Room,this.onRoom),this.client.on(Xe.Timeline,this.onTimeline),this.client.on(It.Events,this.onRoomState)}stop(){for(const e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(Ge.Room,this.onRoom),this.client.off(Xe.Timeline,this.onTimeline),this.client.off(It.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,Sf.roomSessionForRoom(this.client,e)),this.roomSessions.get(e.roomId)}async consumeCallEncryptionEvent(e,t=!1){if(await this.client.decryptEventIfNeeded(e),e.isDecryptionFailure()){t?Fm.warn(`Decryption failed for event ${e.getId()}: ${e.decryptionFailureReason}`):(Fm.warn(`Decryption failed for event ${e.getId()}: ${e.decryptionFailureReason} will retry once only`),setTimeout(()=>void this.consumeCallEncryptionEvent(e,!0),1e3));return}else t&&Fm.info(`Decryption succeeded for event ${e.getId()} after retry`);if(e.getType()!==ie.CallEncryptionKeysPrefix)return Promise.resolve();const r=this.client.getRoom(e.getRoomId());if(!r)return Fm.error(`Got room state event for unknown room ${e.getRoomId()}!`),Promise.resolve();this.getRoomSession(r).onCallEncryption(e)}refreshRoom(e){const t=!this.roomSessions.has(e.roomId),r=this.getRoomSession(e),i=r.memberships.length>0&&!t;r.onRTCSessionMemberUpdate();const s=r.memberships.length>0;i&&!s?this.emit("session_ended",e.roomId,this.roomSessions.get(e.roomId)):!i&&s&&this.emit("session_started",e.roomId,this.roomSessions.get(e.roomId))}}function BT(n){return e=>{var t,r,i,s;return((r=(t=e.content)==null?void 0:t["m.relates_to"])==null?void 0:r.event_id)!==n||((s=(i=e.content)==null?void 0:i["m.relates_to"])==null?void 0:s.rel_type)===en.name}}async function q$(n){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");const e=new TextEncoder().encode(n),t=await globalThis.crypto.subtle.digest("SHA-256",e);return new Uint8Array(t)}var Kr=(n=>(n.NotSupported="OIDC authentication not supported",n.Misconfigured="OIDC is misconfigured",n.General="Something went wrong with OIDC discovery",n.OpSupport="Configured OIDC OP does not support required functions",n.DynamicRegistrationNotSupported="Dynamic registration not supported",n.DynamicRegistrationFailed="Dynamic registration failed",n.DynamicRegistrationInvalid="Dynamic registration invalid response",n.CodeExchangeFailed="Failed to exchange code for token",n.InvalidBearerTokenResponse="Invalid bearer token response",n.InvalidIdToken="Invalid ID token",n.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",n))(Kr||{});const AP=n=>!!n&&typeof n=="object"&&!Array.isArray(n),yc=(n,e)=>!n[e]||!kg(n,e)?(M.error(`Missing or invalid property: ${e}`),!1):!0,kg=(n,e)=>n[e]&&typeof n[e]!="string"?(M.error(`Invalid property: ${e}`),!1):!0,L5=(n,e)=>n[e]&&(!Array.isArray(n[e])||!n[e].every(t=>typeof t=="string"))?(M.error(`Invalid property: ${e}`),!1):!0,HT=(n,e,t)=>{const r=n[e];return!r||!Array.isArray(r)||!r.includes(t)?(M.error(`Invalid property: ${e}. ${t} is required.`),!1):!0},K$=n=>{if(!AP(n))throw M.error("Issuer configuration not found or malformed"),new Error(Kr.OpSupport);if(![yc(n,"issuer"),yc(n,"authorization_endpoint"),yc(n,"token_endpoint"),yc(n,"revocation_endpoint"),kg(n,"registration_endpoint"),kg(n,"account_management_uri"),kg(n,"device_authorization_endpoint"),L5(n,"account_management_actions_supported"),HT(n,"response_types_supported","code"),HT(n,"grant_types_supported","authorization_code"),HT(n,"code_challenge_methods_supported","S256"),L5(n,"prompt_values_supported")].some(t=>!t))return n;throw M.error("Issuer configuration not valid"),new Error(Kr.OpSupport)},W$=n=>{try{return i$(n)}catch(e){throw M.error("Could not decode id_token",e),e}},z$=(n,e,t,r)=>{try{if(!n)throw new Error("No ID token");const i=W$(n);if(i.iss!==e)throw new Error("Invalid issuer");if(!(typeof i.aud=="string"?[i.aud]:i.aud).includes(t))throw new Error("Invalid audience");if(r!==void 0&&i.nonce!==r)throw new Error("Invalid nonce");if(!i.exp||Date.now()>i.exp*1e3)throw new Error("Invalid expiry")}catch(i){throw M.error("Invalid ID token",i),new Error(Kr.InvalidIdToken)}};function Y$(n){if(!AP(n))throw M.error("Stored user state not found"),new Error(Kr.MissingOrInvalidStoredState);if([yc(n,"homeserverUrl"),yc(n,"nonce"),kg(n,"identityServerUrl")].some(t=>!t))throw new Error(Kr.MissingOrInvalidStoredState)}const Roe=n=>AP(n)&&yc(n,"token_type")&&n.token_type.toLowerCase()==="bearer"&&yc(n,"access_token")&&yc(n,"refresh_token")&&(!("expires_in"in n)||typeof n.expires_in=="number");function X$(n){if(!Roe(n))throw new Error(Kr.InvalidBearerTokenResponse)}const yw=n=>`openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:${n??Es(10)}`,koe=async n=>{if(!globalThis.crypto.subtle)return M.warn("A secure context is required to generate code challenge. Using plain text code challenge"),n;const e=await q$(n);return fw(e)},xoe=({redirectUri:n})=>({scope:yw(),redirectUri:n,state:Es(8),nonce:Es(8),codeVerifier:Es(64)}),Poe=async(n,e,{scope:t,redirectUri:r,state:i,nonce:s,codeVerifier:o})=>{const a=new URL(n);return a.searchParams.append("response_mode","query"),a.searchParams.append("response_type","code"),a.searchParams.append("redirect_uri",r),a.searchParams.append("client_id",e),a.searchParams.append("state",i),a.searchParams.append("scope",t),a.searchParams.append("nonce",s),a.searchParams.append("code_challenge_method","S256"),a.searchParams.append("code_challenge",await koe(o)),a.toString()},Loe=async({metadata:n,redirectUri:e,clientId:t,homeserverUrl:r,identityServerUrl:i,nonce:s,prompt:o,urlState:a})=>{const c=yw(),l=new fP({...n,client_id:t,redirect_uri:e,authority:n.issuer,response_mode:"query",response_type:"code",scope:c,stateStore:new lw({prefix:"mx_oidc_",store:window.sessionStorage})}),u={homeserverUrl:r,nonce:s,identityServerUrl:i};return(await l.createSigninRequest({state:u,nonce:s,prompt:o,url_state:a})).url},Aoe=n=>({id_token:n.id_token,scope:n.scope,expires_at:n.expires_at,refresh_token:n.refresh_token,access_token:n.access_token,token_type:"Bearer"}),Ooe=async(n,e)=>{const t=new URL(window.location.origin);t.searchParams.append("code",n),t.searchParams.append("state",e),ov.setLogger(M);try{const r=new v_(t.searchParams),i=new lw({prefix:"mx_oidc_",store:window.sessionStorage}),s=await i.get(r.state);if(!s)throw new Error(Kr.MissingOrInvalidStoredState);const o=await hP.fromStorageString(s),a=new fP({...o,stateStore:i}),c=await a.processSigninResponse(t.href),l=c.userState;Y$(l),X$(c),z$(c.id_token,a.settings.authority,a.settings.client_id,l.nonce);const u=Aoe(c);return{oidcClientSettings:{clientId:a.settings.client_id,issuer:a.settings.authority},tokenResponse:u,homeserverUrl:l.homeserverUrl,identityServerUrl:l.identityServerUrl,idTokenClaims:c.profile}}catch(r){M.error("Oidc login failed",r);const i=r.message;throw Object.values(Kr).includes(i)?r:new Error(Kr.CodeExchangeFailed)}},OP=async n=>{const e=new URL(".well-known/openid-configuration",n),r=await(await fetch(e,{method:de.Get,signal:uw(5e3)})).json();return MP(r)},MP=async n=>{const e=K$(n),t=new qR({authority:e.issuer,metadata:e,redirect_uri:"",client_id:""}),r=new o$(t);return{...e,signingKeys:await r.getSigningKeys()}},Moe="urn:ietf:params:oauth:grant-type:device_code",VT=(n,e)=>{if(!e)return!1;const t=new URL(e);return!(t.protocol!==n.protocol||t.host!==n.host&&!t.host.endsWith(`.${n.host}`))},Noe=async(n,e)=>{if(!n.registration_endpoint)throw new Error(Kr.DynamicRegistrationNotSupported);const t=["authorization_code","refresh_token"];if(t.some(o=>!n.grant_types_supported.includes(o)))throw new Error(Kr.DynamicRegistrationNotSupported);const r=new URL(e.clientUri),i={client_name:e.clientName,client_uri:e.clientUri,response_types:["code"],grant_types:t,redirect_uris:e.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:e.applicationType,contacts:e.contacts,logo_uri:VT(r,e.logoUri)?e.logoUri:void 0,policy_uri:VT(r,e.policyUri)?e.policyUri:void 0,tos_uri:VT(r,e.tosUri)?e.tosUri:void 0},s={Accept:"application/json","Content-Type":"application/json"};try{const o=await fetch(n.registration_endpoint,{method:de.Post,headers:s,body:JSON.stringify(i)});if(o.status>=400)throw new Error(Kr.DynamicRegistrationFailed);const c=(await o.json()).client_id;if(!c||typeof c!="string")throw new Error(Kr.DynamicRegistrationInvalid);return c}catch(o){throw Object.values(Kr).includes(o.message)?o:(M.error("Dynamic registration request failed",o),new Error(Kr.DynamicRegistrationFailed))}};class Doe{constructor(e,t,r,i,s){this.idTokenClaims=s,this.oidcClientReady=this.initialiseOidcClient(e,t,i,r)}async initialiseOidcClient(e,t,r,i){try{const s=await OP(e),o=yw(r);this.oidcClient=new fP({metadata:s,signingKeys:s.signingKeys??void 0,client_id:t,scope:o,redirect_uri:i,authority:s.issuer,stateStore:new lw({prefix:"mx_oidc_",store:window.sessionStorage})})}catch(s){throw M.error("Failed to initialise OIDC client.",s),new Error("Failed to initialise OIDC client.")}}async doRefreshAccessToken(e){this.inflightRefreshRequest||(this.inflightRefreshRequest=this.getNewTokens(e));try{return await this.inflightRefreshRequest}finally{this.inflightRefreshRequest=void 0}}async persistTokens(e){}async getNewTokens(e){if(!this.oidcClient)throw new Error("Cannot get new token before OIDC client is initialised.");const t={refresh_token:e,session_state:"test",data:void 0,profile:this.idTokenClaims},r=await this.oidcClient.useRefreshToken({state:t,timeoutInSeconds:300}),i={accessToken:r.access_token,refreshToken:r.refresh_token};return await this.persistTokens(i),i}}const Foe=3e3,A5=10*60*1e3,Uoe=new Fn("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent");var Rd=(n=>(n.Chronological="chronological",n.Detached="detached",n))(Rd||{});const joe=new nw("m.get_login_token","org.matrix.msc3882.get_login_token"),J$="uk.half-shot.msc2666",Z$="uk.half-shot.msc2666.mutual_rooms",Q$="uk.half-shot.msc2666.query_mutual_rooms",ga="org.matrix.msc4140",eB="uk.tcpip.msc4133",ta="$";var Ge=(n=>(n.Sync="sync",n.Event="event",n.ToDeviceEvent="toDeviceEvent",n.AccountData="accountData",n.Room="Room",n.DeleteRoom="deleteRoom",n.SyncUnexpectedError="sync.unexpectedError",n.ClientWellKnown="WellKnown.client",n.ReceivedVoipEvent="received_voip_event",n.UndecryptableToDeviceEvent="toDeviceEvent.undecryptable",n.TurnServers="turnServers",n.TurnServersError="turnServers.error",n))(Ge||{});const $oe=new Fn("action","org.matrix.msc3824.action"),V4=class V4 extends Yn{constructor(e){super(),this.reEmitter=new oy(this),this.olmVersion=null,this.usingExternalCrypto=!1,this.clientRunning=!1,this.timelineSupport=!1,this.urlPreviewCache={},this.supportsCallTransfer=!1,this.forceTURN=!1,this.iceCandidatePoolSize=0,this.canSupportVoip=!1,this.peekSync=null,this.isGuestAccount=!1,this.ongoingScrollbacks={},this.notifTimelineSet=null,this.fallbackICEServerAllowed=!1,this.syncedLeftRooms=!1,this.canSupport=new Map,this.pushProcessor=new Mb(this),this.turnServers=[],this.turnServersExpiry=0,this.txnCtr=0,this.mediaHandler=new Zse(this),this.eventsBeingEncrypted=new Set,this.useE2eForGroupCall=!0,this.startCallEventHandler=()=>{this.isInitialSyncComplete()&&(tk()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off("sync",this.startCallEventHandler))},this.startMatrixRTC=()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off("sync",this.startMatrixRTC))},this.fixupRoomNotifications=()=>{if(this.isInitialSyncComplete()){const r=(this.getRooms()??[]).filter(i=>i.getUnreadNotificationCount(rr.Total)>0);for(const i of r){const s=this.getSafeUserId();i.fixupNotifications(s)}this.off("sync",this.fixupRoomNotifications)}},this.logger=e.logger??M,e.baseUrl=RT(e.baseUrl),e.idBaseUrl=RT(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=e.usingExternalCrypto??!1,this.store=e.store||new ise,this.deviceId=e.deviceId||null,this.sessionId=Es(10);const t=e.userId||null;this.credentials={userId:t},this.http=new y$(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:lr.V3,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader,logger:this.logger}),e.pickleKey&&(this.legacyPickleKey=e.pickleKey),this.useLivekitForGroupCalls=!!e.useLivekitForGroupCalls,this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(async r=>{const i=this.getRoom(r.getRoomId());r.status!==rt.SENDING&&this.updatePendingEventStatus(i,r,rt.SENDING);const s=await this.sendEventHttpRequest(r);return i&&i.updatePendingEvent(r,rt.SENT,s.event_id),s}),tk()&&(this.callEventHandler=new Ese(this),this.groupCallEventHandler=new Cse(this),this.canSupportVoip=!0,this.on("sync",this.startCallEventHandler)),this.matrixRTC=new Ioe(this),this.serverCapabilitiesService=new _$(this.http),this.on("sync",this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.legacyCryptoStore=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 ooe(this),this.on(pn.Decrypted,r=>{tB(this,r)}),this.ignoredInvites=new aoe(this),this._secretStorage=new V$(this,e.cryptoCallbacks??{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(t=>bc.createUser(t,this))}get store(){return this._store}async startClient(e){if(this.clientRunning)return;this.clientRunning=!0,this.on("sync",this.startMatrixRTC);const t=this.getUserId();t&&this.store.storeUser(new bc(t)),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval(()=>{this.checkTurnServers()},A5),this.checkTurnServers()),this.syncApi&&(this.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{await this.getVersions();const{threads:r,list:i,fwdPagination:s}=await this.doesServerSupportThread();Gr.setServerSideSupport(r),Gr.setServerSideListSupport(i),Gr.setServerSideFwdPaginationSupport(s)}catch(r){this.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",r)}this.clientOpts=e??{},this.clientOpts.slidingSync?this.syncApi=new j$(this.clientOpts.slidingSync,this,this.clientOpts,this.buildSyncApiOptions()):this.syncApi=new rd(this,this.clientOpts,this.buildSyncApiOptions()),this.syncApi.sync().catch(r=>this.logger.info("Sync startup aborted with an error:",r)),this.clientOpts.clientWellKnownPollPeriod!==void 0&&(this.clientWellKnownIntervalID=setInterval(()=>{this.fetchClientWellKnown()},1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.toDeviceMessageQueue.start(),this.serverCapabilitiesService.start()}buildSyncApiOptions(){return{cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1}}stopClient(){var e,t,r,i,s;(e=this.cryptoBackend)==null||e.stop(),this.off("sync",this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(t=this.syncApi)==null||t.stop(),this.syncApi=void 0,(r=this.peekSync)==null||r.stopPeeking(),(i=this.callEventHandler)==null||i.stop(),(s=this.groupCallEventHandler)==null||s.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())}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const e=[];e.push(this.store.deleteAllData()),this.legacyCryptoStore&&e.push(this.legacyCryptoStore.deleteAllData());const t=async()=>{let r;try{if(r=globalThis.indexedDB,!r)return}catch{return}for(const i of[`${UT}::matrix-sdk-crypto`,`${UT}::matrix-sdk-crypto-meta`])await new Promise((o,a)=>{this.logger.info(`Removing IndexedDB instance ${i}`);const c=r.deleteDatabase(i);c.onsuccess=l=>{this.logger.info(`Removed IndexedDB instance ${i}`),o(0)},c.onerror=l=>{this.logger.warn(`Failed to remove IndexedDB instance ${i}:`,l),o(0)},c.onblocked=l=>{this.logger.info(`cannot yet remove IndexedDB instance ${i}`)}})};return e.push(t()),Promise.all(e).then()}getUserId(){var e;return((e=this.credentials)==null?void 0:e.userId)??null}getSafeUserId(){const e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){var e;return(e=this.credentials)!=null&&e.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){var e,t;return((t=(e=this.credentials)==null?void 0:e.userId)==null?void 0:t.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 av(this,e)}async createGroupCall(e,t,r,i,s,o){if(this.getGroupCallForRoom(e))throw new Error(`${e} already has an existing group call`);const a=this.getRoom(e);if(!a)throw new Error(`Cannot find room ${e}`);return new EP(this,a,t,r,i,void 0,s||this.isVoipWithNoMediaAllowed,o,this.isVoipWithNoMediaAllowed,this.useLivekitForGroupCalls,this.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;return((e=this.syncApi)==null?void 0:e.getSyncState())??null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return e?e===Pr.Prepared||e===Pr.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e;return this.toDeviceMessageQueue.sendQueue(),((e=this.syncApi)==null?void 0:e.retryImmediately())??!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}async getCapabilities(){const e=this.serverCapabilitiesService.getCachedCapabilities();return e||this.serverCapabilitiesService.fetchCapabilities()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}async initRustCrypto(e={}){if(this.cryptoBackend){this.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}const t=this.getUserId();if(t===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");const r=this.getDeviceId();if(r===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");this.logger.debug("Downloading Rust crypto library");const s=await(await rv(()=>import("./index-CdFYKKU5.js"),__vite__mapDeps([0,1]),import.meta.url)).initRustCrypto({logger:this.logger,http:this.http,userId:t,deviceId:r,secretStorage:this.secretStorage,cryptoCallbacks:this.cryptoCallbacks,storePrefix:e.useIndexedDB===!1?null:UT,storeKey:e.storageKey,storePassphrase:e.storagePassword,legacyCryptoStore:this.legacyCryptoStore,legacyPickleKey:this.legacyPickleKey??"DEFAULT_KEY",legacyMigrationProgressListener:(o,a)=>{this.emit(cr.LegacyCryptoStoreMigrationProgress,o,a)}});s.setSupportedVerificationMethods(this.verificationMethods),this.cryptoBackend=s,this.on(Fo.Membership,s.onRoomMembership.bind(s)),this.on("event",o=>{s.onLiveEventFromSync(o)}),this.reEmitter.reEmit(s,[cr.VerificationRequestReceived,cr.UserTrustStatusChanged,cr.KeyBackupStatus,cr.KeyBackupSessionsRemaining,cr.KeyBackupFailed,cr.KeyBackupDecryptionKeyCached,cr.KeysChanged,cr.DevicesUpdated,cr.WillUpdateDevices,cr.DehydratedDeviceCreated,cr.DehydratedDeviceUploaded,cr.RehydrationStarted,cr.RehydrationProgress,cr.RehydrationCompleted,cr.RehydrationError,cr.DehydrationKeyCached,cr.DehydratedDeviceRotationError])}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isRoomEncrypted(e){const t=this.getRoom(e);return t?t.hasEncryptionStateEvent():!1}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}makeKeyBackupPath(e,t,r){let i;return t!==void 0?i=Le("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):e!==void 0?i=Le("/room_keys/keys/$roomId",{$roomId:e}):i="/room_keys/keys",{path:i,queryData:r===void 0?void 0:{version:r}}}async deleteKeysFromBackup(e,t,r){const i=this.makeKeyBackupPath(e,t,r);await this.http.authedRequest(de.Delete,i.path,i.queryData,void 0,{prefix:lr.V3})}getMediaConfig(){return this.http.authedRequest(de.Get,"/config",void 0,void 0,{prefix:ud.V3})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(e=!1){var i;const t=this.store.getRooms(),r=new Set;for(const s of t){const o=(i=s.findPredecessor(e))==null?void 0:i.roomId;o&&r.add(o)}return t.filter(s=>!(s.currentState.getStateEvents(ie.RoomTombstone,"")&&r.has(s.roomId)))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}async setAccountData(e,t){if(!this.clientRunning)return M.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results."),await zR(5,()=>this.setAccountDataRaw(e,t));const r=this.store.getAccountData(e);if(r&&Cd(r.event.content,t))return{};const i=Zl();function s(o){o.getType()===e&&i.resolve()}this.addListener("accountData",s);try{const o=await zR(5,()=>this.setAccountDataRaw(e,t));return await i.promise,o}finally{this.removeListener("accountData",s)}}setAccountDataRaw(e,t){const r=Le("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this.http.authedRequest(de.Put,r,void 0,t)}getAccountData(e){return this.store.getAccountData(e)}async getAccountDataFromServer(e){var r;if(this.isInitialSyncComplete()){const i=this.store.getAccountData(e);return i?i.getContent():null}const t=Le("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return await this.http.authedRequest(de.Get,t)}catch(i){if(((r=i.data)==null?void 0:r.errcode)==="M_NOT_FOUND")return null;throw i}}async deleteAccountData(e){const t=this.canSupport.get(vs.AccountDataDeletion);if(t===Vr.Unsupported){await this.setAccountData(e,{});return}const r=Le("/user/$userId/account_data/$type",{$userId:this.getSafeUserId(),$type:e}),i=t===Vr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return await this.http.authedRequest(de.Delete,r,void 0,void 0,i)}getIgnoredUsers(){const e=this.getAccountData(ie.IgnoredUserList);return e!=null&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){const t={ignored_users:{}};return e.forEach(r=>{t.ignored_users[r]={}}),this.setAccountData(ie.IgnoredUserList,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}async joinRoom(e,t={}){t.syncRoom===void 0&&(t.syncRoom=!0);const r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,We.Join))return r;let i=Promise.resolve();if(t.inviteSignUrl){const v=new URL(t.inviteSignUrl);v.searchParams.set("mxid",this.credentials.userId),i=this.http.requestOtherUrl(de.Post,v)}const s={};t.viaServers&&(s.server_name=t.viaServers,s.via=t.viaServers);const o={},a=await i;a&&(o.third_party_signed=a);const c=Le("/join/$roomid",{$roomid:e}),u=(await this.http.authedRequest(de.Post,c,s,o)).room_id,h=this.getRoom(u);if(h!=null&&h.hasMembershipState(this.credentials.userId,We.Join))return h;const m=new rd(this,this.clientOpts,this.buildSyncApiOptions()).createRoom(u);return t.syncRoom,m}knockRoom(e,t={}){const r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,We.Knock))return Promise.resolve({room_id:r.roomId});const i=Le("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),s={};t.viaServers&&(s.server_name=t.viaServers,s.via=t.viaServers);const o={};return t.reason&&(o.reason=t.reason),this.http.authedRequest(de.Post,i,s,o)}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,rt.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![rt.QUEUED,rt.NOT_SENT,rt.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===rt.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===rt.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,rt.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,ie.RoomName,{name:t})}setRoomTopic(e,t,r){const i=Yj(t,r);return this.sendStateEvent(e,ie.RoomTopic,i)}getRoomTags(e){const t=Le("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(de.Get,t)}setRoomTag(e,t,r={}){const i=Le("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(de.Put,i,void 0,r)}deleteRoomTag(e,t){const r=Le("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(de.Delete,r)}setRoomAccountData(e,t,r){const i=Le("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(de.Put,i,void 0,r)}async setPowerLevel(e,t,r){var o,a,c;let i;if(this.clientRunning&&this.isInitialSyncComplete()&&(i=(c=(a=(o=this.getRoom(e))==null?void 0:o.currentState)==null?void 0:a.getStateEvents(ie.RoomPowerLevels,""))==null?void 0:c.getContent()),!i)try{i=await this.getStateEvent(e,ie.RoomPowerLevels,"")}catch(l){if(l instanceof mn&&l.errcode==="M_NOT_FOUND")i={};else throw l}i=iw(i),i!=null&&i.users||(i.users={});const s=Array.isArray(t)?t:[t];for(const l of s)r==null?delete i.users[l]:i.users[l]=r;return this.sendStateEvent(e,ie.RoomPowerLevels,i,"")}async unstable_createLiveBeacon(e,t){return this.unstable_setLiveBeacon(e,t)}async unstable_setLiveBeacon(e,t){return this.sendStateEvent(e,kP.name,t,this.getUserId())}sendEvent(e,t,r,i,s){let o,a,c,l;return!(t!=null&&t.startsWith(ta))&&t!==null?(l=i,c=r,a=t,o=null):(l=s,c=i,a=r,o=t),this.addThreadRelationIfNeeded(c,o,e),this.sendCompleteEvent(e,o,{type:a,content:c},l)}addThreadRelationIfNeeded(e,t,r){var i,s,o,a;if(t&&!((i=e["m.relates_to"])!=null&&i.rel_type)){const c=!!((s=e["m.relates_to"])!=null&&s["m.in_reply_to"]);e["m.relates_to"]={...e["m.relates_to"],rel_type:en.name,event_id:t,is_falling_back:!c};const l=(o=this.getRoom(r))==null?void 0:o.getThread(t);l&&!c&&(e["m.relates_to"]["m.in_reply_to"]={event_id:((a=l.lastReply(u=>u.isRelation(en.name)&&!u.status))==null?void 0:a.getId())??t})}}sendCompleteEvent(e,t,r,i,s){let o,a;typeof i=="string"?a=i:(o=i,a=s),a||(a=this.makeTxnId());const c=new Ji(Object.assign(r,{event_id:"~"+e+":"+a,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:new Date().getTime()})),l=this.getRoom(e),u=t?l==null?void 0:l.getThread(t):void 0;u&&c.setThread(u),o||(this.reEmitter.reEmit(c,[pn.Replaced,pn.VisibilityChange]),l==null||l.reEmitter.reEmit(c,[pn.BeforeRedaction]));const h=c.getAssociatedId();if(h!=null&&h.startsWith("~")){const m=l==null?void 0:l.getPendingEvents().find(v=>v.getId()===h);m==null||m.once(pn.LocalEventIdReplaced,()=>{c.updateAssociatedId(m.getId())})}const p=c.getType();return this.logger.debug(`sendEvent of type ${p} in ${e} with txnId ${a}${o?" (delayed event)":""}`),c.setTxnId(a),c.setStatus(rt.SENDING),o?this.encryptAndSendEvent(l,c,o):(l==null||l.addPendingEvent(c,a),c.status===rt.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(l,c))}async encryptAndSendEvent(e,t,r){if(r)return this.sendEventHttpRequest(t,r);try{let i;this.eventsBeingEncrypted.add(t.getId());try{await this.encryptEventIfNeeded(t,e??void 0)}finally{i=!this.eventsBeingEncrypted.delete(t.getId())}if(i)return{};t.status===rt.ENCRYPTING&&this.updatePendingEventStatus(e,t,rt.SENDING);let s=null;return this.scheduler&&(s=this.scheduler.queueEvent(t),s&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,rt.QUEUED)),s||(s=this.sendEventHttpRequest(t),e&&(s=s.then(o=>(e.updatePendingEvent(t,rt.SENT,o.event_id),o)))),await s}catch(i){this.logger.error("Error sending event",i);try{t.error=i,this.updatePendingEventStatus(e,t,rt.NOT_SENT)}catch(s){this.logger.error("Exception in error handler!",s)}throw i instanceof mn&&(i.event=t),i}}async encryptEventIfNeeded(e,t){if(t&&await this.shouldEncryptEventForRoom(e,t)&&!(!this.cryptoBackend&&this.usingExternalCrypto)){if(!this.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");this.updatePendingEventStatus(t,e,rt.ENCRYPTING),await this.cryptoBackend.encryptEvent(e,t)}}async shouldEncryptEventForRoom(e,t){var r;return e.isEncrypted()||e.getType()===ie.Reaction||e.isRedaction()?!1:!!(t.hasEncryptionStateEvent()||await((r=this.cryptoBackend)==null?void 0:r.isEncryptionEnabledInRoom(t.roomId)))}getEncryptedIfNeededEventType(e,t){var r;return t===ie.Reaction?t:(r=this.getRoom(e))!=null&&r.hasEncryptionStateEvent()?ie.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,r){e?e.updatePendingEvent(t,r):t.setStatus(r)}sendEventHttpRequest(e,t){let r=e.getTxnId();r||(r=this.makeTxnId(),e.setTxnId(r));const i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:r};let s;if(e.isState()){let a="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(a="/rooms/$roomId/state/$eventType/$stateKey"),s=Le(a,i)}else e.isRedaction()&&e.event.redacts?s=Le("/rooms/$roomId/redact/$redactsEventId/$txnId",{$redactsEventId:e.event.redacts,...i}):s=Le("/rooms/$roomId/send/$eventType/$txnId",i);const o=e.getWireContent();return t?this.http.authedRequest(de.Put,s,O5(t),o):this.http.authedRequest(de.Put,s,void 0,o).then(a=>(this.logger.debug(`Event sent to ${e.getRoomId()} with event id ${a.event_id}`),a))}redactEvent(e,t,r,i,s){r!=null&&r.startsWith(ta)||(s=i,i=r,r=t,t=null);const a={reason:s==null?void 0:s.reason};if((s==null?void 0:s.with_rel_types)!==void 0){if(this.canSupport.get(vs.RelationBasedRedactions)===Vr.Unsupported)throw new Error(`Server does not support relation based redactions roomId ${e} eventId ${r} txnId: ${i} threadId ${t}`);const c=this.canSupport.get(vs.RelationBasedRedactions)===Vr.Stable?FR.stable:FR.unstable;a[c]=s.with_rel_types}return this.sendCompleteEvent(e,t,{type:ie.RoomRedaction,content:a,redacts:r},i)}sendMessage(e,t,r,i){typeof t!="string"&&t!==null&&(i=r,r=t,t=null);const s=ie.RoomMessage,o=r;return this.sendEvent(e,t,s,o,i)}sendTextMessage(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Gj(r);return this.sendMessage(e,t,s,i)}sendNotice(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=qj(r);return this.sendMessage(e,t,s,i)}sendEmoteMessage(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Kj(r);return this.sendMessage(e,t,s,i)}sendImageMessage(e,t,r,i,s="Image"){!(t!=null&&t.startsWith(ta))&&t!==null&&(s=i||"Image",i=r,r=t,t=null);const o={msgtype:zo.Image,url:r,info:i,body:s};return this.sendMessage(e,t,o)}sendStickerMessage(e,t,r,i,s="Sticker"){!(t!=null&&t.startsWith(ta))&&t!==null&&(s=i||"Sticker",i=r,r=t,t=null);const o={url:r,info:i,body:s};return this.sendEvent(e,t,ie.Sticker,o)}sendHtmlMessage(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Bj(r,i);return this.sendMessage(e,t,s)}sendHtmlNotice(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Hj(r,i);return this.sendMessage(e,t,s)}sendHtmlEmote(e,t,r,i){!(t!=null&&t.startsWith(ta))&&t!==null&&(i=r,r=t,t=null);const s=Vj(r,i);return this.sendMessage(e,t,s)}async _unstable_sendDelayedEvent(e,t,r,i,s,o){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","sendDelayedEvent");return this.addThreadRelationIfNeeded(s,r,e),this.sendCompleteEvent(e,r,{type:i,content:s},t,o)}async _unstable_sendDelayedStateEvent(e,t,r,i,s="",o={}){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","sendDelayedStateEvent");const a={$roomId:e,$eventType:r,$stateKey:s};let c=Le("/rooms/$roomId/state/$eventType",a);return s!==void 0&&(c=Le(c+"/$stateKey",a)),this.http.authedRequest(de.Put,c,O5(t),i,o)}async _unstable_getDelayedEvents(e){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","getDelayedEvents");const t=e?{from:e}:void 0;return await this.http.authedRequest(de.Get,"/delayed_events",t,void 0,{prefix:`${lr.Unstable}/${ga}`})}async _unstable_updateDelayedEvent(e,t,r={}){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","updateDelayedEvent");const i=Le("/delayed_events/$delayId",{$delayId:e}),s={action:t};return await this.http.authedRequest(de.Post,i,void 0,s,{...r,prefix:`${lr.Unstable}/${ga}`})}async sendReceipt(e,t,r,i=!1){if(this.isGuest())return Promise.resolve({});const s=Le("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),a=!i&&this.supportsThreads()?{...r,thread_id:Kf(e)}:r,c=this.http.authedRequest(de.Post,s,void 0,a||{}),l=this.getRoom(e.getRoomId());return l&&this.credentials.userId&&l.addLocalEchoReceipt(this.credentials.userId,e,t,i),c}async sendReadReceipt(e,t=ci.Read,r=!1){if(!e)return;const i=e.getId(),s=this.getRoom(e.getRoomId());if(s!=null&&s.hasPendingEvent(i))throw new Error(`Cannot set read receipt to a pending event (${i})`);return this.sendReceipt(e,t,{},r)}async setRoomReadMarkers(e,t,r,i){const s=this.getRoom(e);if(s!=null&&s.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let o;if(r){if(o=r.getId(),s!=null&&s.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);s==null||s.addLocalEchoReceipt(this.credentials.userId,r,ci.Read)}let a;if(i){if(a=i.getId(),s!=null&&s.hasPendingEvent(a))throw new Error(`Cannot set read receipt to a pending event (${a})`);s==null||s.addLocalEchoReceipt(this.credentials.userId,i,ci.ReadPrivate)}return await this.setRoomReadMarkersHttpRequest(e,t,o,a)}getUrlPreview(e,t){t=Math.floor(t/6e4)*6e4;const r=new URL(e);r.hash="",e=r.toString();const i=t+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];const s=this.http.authedRequest(de.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:ud.V3,priority:"low"});return this.urlPreviewCache[i]=s,s}sendTyping(e,t,r){if(this.isGuest())return Promise.resolve({});const i=Le("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),s={typing:t};return t&&(s.timeout=r||2e4),this.http.authedRequest(de.Put,i,void 0,s)}getRoomUpgradeHistory(e,t=!1,r=!1){const i=this.getRoom(e);if(!i)return[];const s=this.findPredecessorRooms(i,t,r),o=this.findSuccessorRooms(i,t,r);return[...s,i,...o]}findPredecessorRooms(e,t,r){var a,c;const i=[],s=new Set([e.roomId]);let o=(a=e.findPredecessor(r))==null?void 0:a.roomId;for(;o!==null;){if(o){if(s.has(o))break;s.add(o)}const l=this.getRoom(o);if(l===null)break;if(t){const u=l.currentState.getStateEvents(ie.RoomTombstone,"");if(!u||u.getContent().replacement_room!==e.roomId)break}i.splice(0,0,l),e=l,o=(c=e.findPredecessor(r))==null?void 0:c.roomId}return i}findSuccessorRooms(e,t,r){var o;const i=[];let s=e.currentState.getStateEvents(ie.RoomTombstone,"");for(;s;){const a=this.getRoom(s.getContent().replacement_room);if(!a||a.roomId===e.roomId)break;if(t){const l=(o=a.findPredecessor(r))==null?void 0:o.roomId;if(!l||l!==e.roomId)break}if(i.push(a),new Set(i.map(l=>l.roomId)).size<i.length)return i.slice(0,i.length-1);e=a,s=e.currentState.getStateEvents(ie.RoomTombstone,"")}return i}invite(e,t,r){return this.membershipChange(e,t,We.Invite,r)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}async inviteByThreePid(e,t,r){var a;const i=Le("/rooms/$roomId/invite",{$roomId:e}),s=this.getIdentityServerUrl(!0);if(!s)return Promise.reject(new mn({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));const o={id_server:s,medium:t,address:r};if((a=this.identityServer)!=null&&a.getAccessToken){const c=await this.identityServer.getAccessToken();c&&(o.id_access_token=c)}return this.http.authedRequest(de.Post,i,void 0,o)}leave(e){return this.membershipChange(e,void 0,We.Leave)}leaveRoomChain(e,t=!0){const r=this.getRoomUpgradeHistory(e);let i=r;if(!t){i=[];for(const c of r)if(i.push(c),c.roomId===e)break}const s={},o=[],a=c=>this.leave(c).then(()=>{delete s[c]}).catch(l=>{s[c]=l});for(const c of i)o.push(a(c.roomId));return Promise.all(o).then(()=>s)}ban(e,t,r){return this.membershipChange(e,t,We.Ban,r)}async forget(e,t=!0){const r=Le("/rooms/$room_id/forget",{$room_id:e}),i=await this.http.authedRequest(de.Post,r);return t&&(this.store.removeRoom(e),this.emit("deleteRoom",e)),i}unban(e,t){const r=Le("/rooms/$roomId/unban",{$roomId:e}),i={user_id:t};return this.http.authedRequest(de.Post,r,void 0,i)}kick(e,t,r){const i=Le("/rooms/$roomId/kick",{$roomId:e}),s={user_id:t,reason:r};return this.http.authedRequest(de.Post,i,void 0,s)}membershipChange(e,t,r,i){const s=Le("/rooms/$room_id/$membership",{$room_id:e,$membership:r});return this.http.authedRequest(de.Post,s,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e,t=!1){if(!e.getPushActions()||t){const{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushActions()}getPushDetailsForEvent(e,t=!1){if(!e.getPushDetails()||t){const{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushDetails()}setProfileInfo(e,t){const r=Le("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(de.Put,r,void 0,t)}async setDisplayName(e){const t=await this.setProfileInfo("displayname",{displayname:e}),r=this.getUser(this.getUserId());return r&&(r.displayName=e,r.emit(Ol.DisplayName,r.events.presence,r)),t}async setAvatarUrl(e){const t=await this.setProfileInfo("avatar_url",{avatar_url:e}),r=this.getUser(this.getUserId());return r&&(r.avatarUrl=e,r.emit(Ol.AvatarUrl,r.events.presence,r)),t}mxcUrlToHttp(e,t,r,i,s,o,a){return ow(this.baseUrl,e,t,r,i,s,o,a)}async setSyncPresence(e){var t;(t=this.syncApi)==null||t.setPresence(e)}async setPresence(e){const t=Le("/presence/$userId/status",{$userId:this.credentials.userId});if(["offline","online","unavailable"].indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);await this.http.authedRequest(de.Put,t,void 0,e)}getPresence(e){const t=Le("/presence/$userId/status",{$userId:e});return this.http.authedRequest(de.Get,t)}scrollback(e,t=30){let r=0,i=this.ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){const a=Date.now()-i.errorTs;r=Math.max(Foe-a,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);const s=this.store.scrollback(e,t).length;if(s===t)return Promise.resolve(e);t=t-s;const o=new Promise((a,c)=>{Td(r).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,bt.Backward)).then(l=>{const u=l.chunk.map(this.getEventMapper());if(l.state){const v=l.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(v)}const[h,p,m]=e.partitionThreadedEvents(u);this.processAggregatedTimelineEvents(e,h),e.addEventsToTimeline(h,!0,!0,e.getLiveTimeline()),this.processThreadEvents(e,p,!0),m.forEach(v=>e.relations.aggregateChildEvent(v)),e.oldState.paginationToken=l.end??null,l.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,u,l.end??null,!0),delete this.ongoingScrollbacks[e.roomId],a(e)}).catch(l=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},c(l)})});return i={promise:o},this.ongoingScrollbacks[e.roomId]=i,o}getEventMapper(e){return Xse(this,e||{})}async getEventTimeline(e,t){var m,v;if(!this.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&&this.supportsThreads())return this.getThreadTimeline(e,t);const r=Le("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let i;(m=this.clientOpts)!=null&&m.lazyLoadMembers&&(i={filter:JSON.stringify(ys.LAZY_LOADING_MESSAGES_FILTER)});const s=await this.http.authedRequest(de.Get,r,i);if(!s.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const o=this.getEventMapper(),a=o(s.event);if(a.isRelation(en.name)){this.logger.warn("Tried loading a regular timeline at the position of a thread event");return}const c=[...s.events_after.reverse().map(o),a,...s.events_before.map(o)];let l=e.getTimelineForEvent(c[0].getId());l?l.getState(Be.BACKWARDS).setUnknownStateEvents(s.state.map(o)):(l=e.addTimeline(),l.initialiseState(s.state.map(o)),l.getState(Be.FORWARDS).paginationToken=s.end);const[u,h,p]=e.room.partitionThreadedEvents(c);return e.addEventsToTimeline(u,!0,!1,l,s.start),this.processThreadEvents(e.room,h,!0),this.processAggregatedTimelineEvents(e.room,u),p.forEach(g=>e.relations.aggregateChildEvent(g)),e.getTimelineForEvent(t)??((v=e.room.findThreadForEvent(a))==null?void 0:v.liveTimeline)??l}async getThreadTimeline(e,t){var l,u,h;if(!this.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");const r=Le("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),i={limit:"0"};(l=this.clientOpts)!=null&&l.lazyLoadMembers&&(i.filter=JSON.stringify(ys.LAZY_LOADING_MESSAGES_FILTER));const s=await this.http.authedRequest(de.Get,r,i),o=this.getEventMapper(),a=o(s.event);if(!e.canContain(a))return;const c=this.canSupport.get(vs.RelationsRecursion)!==Vr.Unsupported;if(Gr.hasServerSideSupport)if(Gr.hasServerSideFwdPaginationSupport){if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const p=e.thread,m=await this.fetchRelations(e.room.roomId,p.id,null,null,{dir:bt.Backward,from:s.start,recurse:c||void 0}),v=await this.fetchRelations(e.room.roomId,p.id,null,null,{dir:bt.Forward,from:s.end,recurse:c||void 0}),g=[...v.chunk.reverse().filter(BT(p.id)).map(o),a,...m.chunk.filter(BT(p.id)).map(o)];for(const b of g)await((u=e.thread)==null?void 0:u.processEvent(b));let S=e.getTimelineForEvent(a.getId());if(S?S.getState(Be.BACKWARDS).setUnknownStateEvents(s.state.map(o)):(S=e.addTimeline(),S.initialiseState(s.state.map(o))),e.addEventsToTimeline(g,!0,!1,S,v.next_batch),!m.next_batch){const b=await this.fetchRoomEvent(e.room.roomId,p.id);e.addEventsToTimeline([o(b)],!0,!1,S,null)}return S.setPaginationToken(m.next_batch??null,bt.Backward),S.setPaginationToken(v.next_batch??null,bt.Forward),this.processAggregatedTimelineEvents(e.room,g),e.getTimelineForEvent(t)??S}else{const p=e.thread,m=await this.fetchRelations(e.room.roomId,p.id,en.name,null,{dir:bt.Backward,from:s.start,recurse:c||void 0}),v=[];let g=s.end;for(;g;){const R=await this.fetchRelations(e.room.roomId,p.id,en.name,null,{dir:bt.Forward,from:g,recurse:c||void 0});g=R.next_batch??null,v.push(...R.chunk)}const S=[...v.reverse().map(o),a,...m.chunk.map(o)];for(const R of S)await((h=e.thread)==null?void 0:h.processEvent(R));const b=e.getLiveTimeline();if(b.getState(Be.BACKWARDS).setUnknownStateEvents(s.state.map(o)),e.addEventsToTimeline(S,!0,!1,b,null),!m.next_batch){const R=await this.fetchRoomEvent(e.room.roomId,p.id);e.addEventsToTimeline([o(R)],!0,!1,b,null)}return b.setPaginationToken(m.next_batch??null,bt.Backward),b.setPaginationToken(null,bt.Forward),this.processAggregatedTimelineEvents(e.room,S),b}}async getLatestTimeline(e){var r,i,s,o;if(!this.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");let t;if(e.threadListType!==null)t=(r=(await this.createThreadListMessagesRequest(e.room.roomId,null,1,bt.Backward,e.threadListType,e.getFilter())).chunk)==null?void 0:r[0];else if(e.thread&&Gr.hasServerSideSupport){const a=this.canSupport.get(vs.RelationsRecursion)!==Vr.Unsupported;t=(i=(await this.fetchRelations(e.room.roomId,e.thread.id,en.name,null,{dir:bt.Backward,limit:1,recurse:a||void 0})).chunk)==null?void 0:i[0]}else{const a=Le("/rooms/$roomId/messages",{$roomId:e.room.roomId}),c={dir:"b"};(s=this.clientOpts)!=null&&s.lazyLoadMembers&&(c.filter=JSON.stringify(ys.LAZY_LOADING_MESSAGES_FILTER)),t=(o=(await this.http.authedRequest(de.Get,a,c)).chunk)==null?void 0:o[0]}if(!t)throw new Error("No message returned when trying to construct getLatestTimeline");return this.getEventTimeline(e,t.event_id)}createMessagesRequest(e,t,r=30,i,s){var l,u;const o=Le("/rooms/$roomId/messages",{$roomId:e}),a={limit:r.toString(),dir:i};t&&(a.from=t);let c=null;return(l=this.clientOpts)!=null&&l.lazyLoadMembers&&(c=Object.assign({},ys.LAZY_LOADING_MESSAGES_FILTER)),s&&(c=c||{},Object.assign(c,(u=s.getRoomTimelineFilterComponent())==null?void 0:u.toJSON())),c&&(a.filter=JSON.stringify(c)),this.http.authedRequest(de.Get,o,a)}createThreadListMessagesRequest(e,t,r=30,i=bt.Backward,s=To.All,o){var h,p;const a=Le("/rooms/$roomId/threads",{$roomId:e}),c={limit:r.toString(),dir:i,include:nB(s)};t&&(c.from=t);let l={};(h=this.clientOpts)!=null&&h.lazyLoadMembers&&(l={...ys.LAZY_LOADING_MESSAGES_FILTER}),o&&(l={...l,...(p=o.getRoomTimelineFilterComponent())==null?void 0:p.toJSON()}),Object.keys(l).length&&(c.filter=JSON.stringify(l));const u={prefix:Gr.hasServerSideListSupport===ha.Stable?lr.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(de.Get,a,c,void 0,u).then(m=>{var v;return{...m,chunk:(v=m.chunk)==null?void 0:v.reverse(),start:m.prev_batch,end:m.next_batch}})}paginateEventTimeline(e,t){const r=e.getTimelineSet()===this.notifTimelineSet,i=this.getRoom(e.getRoomId()),s=e.getTimelineSet().threadListType,o=e.getTimelineSet().thread;t=t||{};const a=t.backwards||!1;if(r&&!a)throw new Error("paginateNotifTimeline can only paginate backwards");const c=a?Be.BACKWARDS:Be.FORWARDS,l=e.getPaginationToken(c),u=e.paginationRequests[c];if(u)return u;let h,p,m;if(r)h="/notifications",p={limit:(t.limit??30).toString(),only:"highlight"},l&&l!=="end"&&(p.from=l),m=this.http.authedRequest(de.Get,h,p).then(async v=>{const g=v.next_token,S=[];v.notifications=v.notifications.filter(Po);for(let R=0;R<v.notifications.length;R++){const k=v.notifications[R],I=this.getEventMapper()(k.event);this.getPushDetailsForEvent(I,!0),I.event.room_id=k.room_id,S[R]=I}const b=e.getTimelineSet();return b.addEventsToTimeline(S,a,!1,e,g),this.processAggregatedTimelineEvents(b.room,S),a&&!v.next_token&&e.setPaginationToken(null,c),!!v.next_token}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m;else if(s!==null){if(!i)throw new Error("Unknown room "+e.getRoomId());if(!Gr.hasServerSideFwdPaginationSupport&&c===bt.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");m=this.createThreadListMessagesRequest(e.getRoomId(),l,t.limit,c,s,e.getFilter()).then(v=>{if(v.state){const R=e.getState(c),k=v.state.filter(Po).map(this.getEventMapper());R.setUnknownStateEvents(k)}const g=v.end,S=v.chunk.filter(Po).map(this.getEventMapper());return e.getTimelineSet().addEventsToTimeline(S,a,!1,e,g),this.processAggregatedTimelineEvents(i,S),this.processThreadRoots(i,S,a),a&&v.end==v.start&&e.setPaginationToken(null,c),v.end!==v.start}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m}else if(o){const v=this.getRoom(e.getRoomId()??void 0);if(!v)throw new Error("Unknown room "+e.getRoomId());const g=this.canSupport.get(vs.RelationsRecursion)!==Vr.Unsupported;m=this.fetchRelations(e.getRoomId()??"",o.id,null,null,{dir:c,limit:t.limit,from:l??void 0,recurse:g||void 0}).then(async S=>{const b=this.getEventMapper(),R=S.chunk.filter(Po).filter(BT(o.id)).map(b);for(const T of R.slice().reverse()){await(o==null?void 0:o.processEvent(T));const C=T.getSender();(!a||(o==null?void 0:o.getEventReadUpTo(C))===null)&&v.addLocalEchoReceipt(C,T,ci.Read)}const k=S.next_batch,I=e.getTimelineSet();if(I.addEventsToTimeline(R,a,!1,e,k??null),!k&&a){const T=o.rootEvent??b(await this.fetchRoomEvent(e.getRoomId()??"",o.id));I.addEventsToTimeline([T],!0,!1,e,null)}return this.processAggregatedTimelineEvents(I.room,R),a&&!k&&e.setPaginationToken(null,c),!!k}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m}else{if(!i)throw new Error("Unknown room "+e.getRoomId());m=this.createMessagesRequest(e.getRoomId(),l,t.limit,c,e.getFilter()).then(v=>{if(v.state){const T=e.getState(c),C=v.state.filter(Po).map(this.getEventMapper());T.setUnknownStateEvents(C)}const g=v.end,S=v.chunk.filter(Po).map(this.getEventMapper()),b=e.getTimelineSet(),[R,,k]=i.partitionThreadedEvents(S);b.addEventsToTimeline(R,a,!1,e,g),this.processAggregatedTimelineEvents(i,R),this.processThreadRoots(i,R.filter(T=>T.getServerAggregatedRelation(en.name)),!1),k.forEach(T=>i.relations.aggregateChildEvent(T));const I=v.end===void 0||v.end===v.start;return a&&I&&e.setPaginationToken(null,c),!I}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=m}return m}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e,t=20){var r;return(r=this.peekSync)==null||r.stopPeeking(),this.peekSync=new rd(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,t)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const r=this.sendStateEvent(e,ie.RoomGuestAccess,{guest_access:t.allowJoin?uv.CanJoin:uv.Forbidden},"");let i=Promise.resolve();return t.allowRead&&(i=this.sendStateEvent(e,ie.RoomHistoryVisibility,{history_visibility:vw.WorldReadable},"")),Promise.all([i,r]).then()}requestRegisterEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestRegisterMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestAdd3pidEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestAdd3pidMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}requestPasswordEmailToken(e,t,r,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:r,next_link:i})}requestPasswordMsisdnToken(e,t,r,i,s){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:r,send_attempt:i,next_link:s})}async requestTokenFromEndpoint(e,t){const r=Object.assign({},t);return this.http.request(de.Post,e,void 0,r)}getRoomPushRule(e,t){var r,i;if(this.pushRules)return(i=(r=this.pushRules[e])==null?void 0:r.room)==null?void 0:i.find(s=>s.rule_id===t);throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,r){let i,s=!1;const o=this.getRoomPushRule(e,t);if(o!=null&&o.actions.includes(Sc.DontNotify)&&(s=!0),!r)s&&(i=this.deletePushRule(e,pr.RoomSpecific,o.rule_id));else if(!o)i=this.addPushRule(e,pr.RoomSpecific,t,{actions:[Sc.DontNotify]});else if(!s){const a=Zl();this.deletePushRule(e,pr.RoomSpecific,o.rule_id).then(()=>{this.addPushRule(e,pr.RoomSpecific,t,{actions:[Sc.DontNotify]}).then(()=>{a.resolve()}).catch(c=>{a.reject(c)})}).catch(c=>{a.reject(c)}),i=a.promise}if(i)return new Promise((a,c)=>{i.then(()=>{this.getPushRules().then(l=>{this.pushRules=l,a()}).catch(l=>{c(l)})}).catch(l=>{this.getPushRules().then(u=>{this.pushRules=u,c(l)}).catch(u=>{c(l)})})})}searchMessageText(e){const t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:RP.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},r={_query:t,results:[],highlights:[]};return this.search({body:t}).then(i=>this.processRoomEventsSearch(r,i))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;const t={body:e._query,next_batch:e.next_batch},r=this.search(t,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=r,r}processRoomEventsSearch(e,t){var a;const r=t.search_categories.room_events;e.count=r.count,e.next_batch=r.next_batch;const i=new Set(r.highlights);e.highlights.forEach(c=>{i.add(c)}),e.highlights=Array.from(i);const s=this.getEventMapper(),o=((a=r.results)==null?void 0:a.length)??0;for(let c=0;c<o;c++){const l=gw.fromJson(r.results[c],s),u=this.getRoom(l.context.getEvent().getRoomId());if(u)for(const h of l.context.getTimeline())h.setMetadata(u.currentState,!1);e.results.push(l)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const e=new rd(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){const t=Le("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,t,void 0,e).then(r=>{const i=ys.fromJson(this.credentials.userId,r.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,t,r){if(r){const s=this.store.getFilter(e,t);if(s)return Promise.resolve(s)}const i=Le("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(de.Get,i).then(s=>{const o=ys.fromJson(e,t,s);return this.store.storeFilter(o),o})}async getOrCreateFilter(e,t){const r=this.store.getFilterIdByName(e);let i;if(r){try{const o=await this.getFilter(this.credentials.userId,r,!0);if(o){const a=o.getDefinition(),c=t.getDefinition();Cd(a,c)&&(i=r)}}catch(o){if(o.errcode!=="M_UNKNOWN"&&o.errcode!=="M_NOT_FOUND")throw o}i||this.store.setFilterIdByName(e,void 0)}if(i)return i;const s=await this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,s.filterId),s.filterId}getOpenIdToken(){const e=Le("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(de.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}async checkTurnServers(){if(!this.canSupportVoip)return;let e=!1;const t=this.turnServersExpiry-Date.now();if(t>A5)this.logger.debug("TURN creds are valid for another "+t+" ms: not fetching new ones."),e=!0;else{this.logger.debug("Fetching new TURN credentials");try{const r=await this.turnServer();if(r.uris){this.logger.debug("Got TURN URIs: "+r.uris+" refresh in "+r.ttl+" secs");const i={urls:r.uris,username:r.username,credential:r.password};this.turnServers=[i],this.turnServersExpiry=Date.now()+r.ttl*1e3,e=!0,this.emit("turnServers",this.turnServers)}}catch(r){this.logger.error("Failed to get TURN URIs",r),r.httpStatus===403?(this.logger.info("TURN access unavailable for this account: stopping credentials checks"),this.checkTurnServersIntervalID!==null&&globalThis.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.emit("turnServers.error",r,!0)):this.emit("turnServers.error",r,!1)}}return e}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=Le("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(de.Get,e,void 0,void 0,{prefix:""}).then(t=>t.admin)}whoisSynapseUser(e){const t=Le("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(de.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=Le("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(de.Post,t,void 0,void 0,{prefix:""})}async fetchClientWellKnown(){this.clientWellKnownPromise=lv.getRawClientConfig(this.getDomain()??void 0),this.clientWellKnown=await this.clientWellKnownPromise,this.emit("WellKnown.client",this.clientWellKnown)}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter(([r,i])=>e.includes(typeof i)).reduce((r,[i,s])=>(r[i]=s,r),{});return this.store.storeClientOptions(t)}async _unstable_getSharedRooms(e){const t=await this.doesServerSupportUnstableFeature(J$),r=await this.doesServerSupportUnstableFeature(Z$),i=await this.doesServerSupportUnstableFeature(Q$);if(!t&&!r&&!i)throw Error("Server does not support the Mutual Rooms API");let s,o;i?(s="/uk.half-shot.msc2666/user/mutual_rooms",o={user_id:e}):(s=Le(`/uk.half-shot.msc2666/user/${r?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e}),o={});const a=[];let c=null;do{const l={};c!=null&&i&&(l.batch_token=c);const u=await this.http.authedRequest(de.Get,s,{...o,...l},void 0,{prefix:lr.Unstable});a.push(...u.joined),u.next_batch_token!==void 0?c=u.next_batch_token:c=null}while(c!=null);return a}async getVersions(){if(this.serverVersionsPromise)return this.serverVersionsPromise;this.serverVersionsPromise=this.http.authedRequest(de.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(t=>{throw this.serverVersionsPromise=void 0,t});const e=await this.serverVersionsPromise;return this.canSupport=await tse(e),this.serverVersionsPromise}async isVersionSupported(e){const{versions:t}=await this.getVersions();return t&&t.includes(e)}async doesServerSupportUnstableFeature(e){const t=await this.getVersions();if(!t)return!1;const r=t.unstable_features;return r&&!!r[e]}async doesServerForceEncryptionForPreset(e){const t=await this.getVersions();if(!t)return!1;const r=t.unstable_features,i=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return r&&!!r[`io.element.e2ee_forced.${i}`]}async doesServerSupportThread(){if(await this.isVersionSupported("v1.4"))return{threads:ha.Stable,list:ha.Stable,fwdPagination:ha.Stable};try{const[e,t,r,i,s,o]=await Promise.all([this.doesServerSupportUnstableFeature("org.matrix.msc3440"),this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3856"),this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3715"),this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:S_(t,e),list:S_(i,r),fwdPagination:S_(o,s)}}catch{return{threads:ha.None,list:ha.None,fwdPagination:ha.None}}}hasLazyLoadMembersEnabled(){var e;return!!((e=this.clientOpts)!=null&&e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}async relations(e,t,r,i,s={dir:bt.Backward}){const o=i?this.getEncryptedIfNeededEventType(e,i):null,[a,c]=await Promise.all([this.fetchRoomEvent(e,t),this.fetchRelations(e,t,r,o,s)]),l=this.getEventMapper(),u=a?l(a):void 0;let h=c.chunk.map(l);if(o===ie.RoomMessageEncrypted){const p=u?h.concat(u):h;await Promise.all(p.map(m=>this.decryptEventIfNeeded(m))),i!==null&&(h=h.filter(m=>m.getType()===i))}return u&&r===sn.Replace&&(h=h.filter(p=>p.getSender()===u.getSender())),{originalEvent:u??null,events:h,nextBatch:c.next_batch??null,prevBatch:c.prev_batch??null}}generateClientSecret(){return Es(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.getCrypto()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case Nb.IS:return this.http.getUrl("/terms",void 0,da.V2,t);case Nb.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(e=!1){var t,r;return e&&((t=this.idBaseUrl)!=null&&t.startsWith("http://")||(r=this.idBaseUrl)!=null&&r.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=RT(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}getRefreshToken(){return this.http.opts.refreshToken??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(de.Get,"/register/available",{username:e}).then(t=>t.available).catch(t=>t.errcode==="M_USER_IN_USE"?!1:Promise.reject(t))}register(e,t,r,i,s,o,a){r&&(i.session=r);const c={auth:i,refresh_token:!0};return e!=null&&(c.username=e),t!=null&&(c.password=t),o!=null&&(c.guest_access_token=o),a!=null&&(c.inhibit_login=a),this.registerRequest(c)}registerGuest({body:e}={}){return this.registerRequest(e||{},"guest")}registerRequest(e,t){const r={};return t&&(r.kind=t),this.http.request(de.Post,"/register",r,e)}refreshToken(e){const t=r=>this.http.authedRequest(de.Post,"/refresh",void 0,{refresh_token:e},{prefix:r,inhibitLogoutEmit:!0});return t(lr.V3).catch(r=>{if(r.errcode==="M_UNRECOGNIZED")return t(lr.V1);throw r})}loginFlows(){return this.http.request(de.Get,"/login")}login(e,t){return this.loginRequest({...t,type:e}).then(r=>(r.access_token&&r.user_id&&(this.http.opts.accessToken=r.access_token,this.credentials={userId:r.user_id}),r))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",r,i){let s="/login/"+t+"/redirect";r&&(s+="/"+r);const o={redirectUrl:e,[$oe.unstable]:i};return this.http.getUrl(s,o).href}loginWithToken(e){return this.login("m.login.token",{token:e})}async loginRequest(e){return await this.http.authedRequest(de.Post,"/login",void 0,e)}async logout(e=!1){return e&&(this.stopClient(),this.http.abort()),this.http.authedRequest(de.Post,"/logout")}deactivateAccount(e,t){const r={};return e&&(r.auth=e),t!==void 0&&(r.erase=t),this.http.authedRequest(de.Post,"/account/deactivate",void 0,r)}async requestLoginToken(e){const t={auth:e};return this.http.authedRequest(de.Post,"/login/get_token",void 0,t,{prefix:lr.V1})}getFallbackAuthUrl(e,t){const r=Le("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(r,{session:t}).href}async createRoom(e){var r;const t=(e.invite_3pid||[]).filter(i=>!i.id_access_token);if(t.length>0&&((r=this.identityServer)!=null&&r.getAccessToken)){const i=await this.identityServer.getAccessToken();if(i)for(const s of t)s.id_access_token=i}return this.http.authedRequest(de.Post,"/createRoom",void 0,e)}fetchRelations(e,t,r,i,s={dir:bt.Backward}){let o=s;Gr.hasServerSideFwdPaginationSupport===ha.Experimental&&(o=PM("dir","org.matrix.msc3715.dir",o)),this.canSupport.get(vs.RelationsRecursion)===Vr.Unstable&&(o=PM("recurse","org.matrix.msc3981.recurse",o));const a=PR(o);let c="/rooms/$roomId/relations/$eventId";r!==null?(c+="/$relationType",i!==null&&(c+="/$eventType")):i!==null&&(this.logger.warn(`eventType: ${i} ignored when fetching
|
|
34
34
|
relations as relationType is null`),i=null);const l=Le(c+"?"+a,{$roomId:e,$eventId:t,$relationType:r,$eventType:i});return this.http.authedRequest(de.Get,l,void 0,void 0,{prefix:lr.V1})}roomState(e){const t=Le("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(de.Get,t)}fetchRoomEvent(e,t){const r=Le("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(de.Get,r)}members(e,t,r,i){const s={};t&&(s.membership=t),r&&(s.not_membership=r),i&&(s.at=i);const o=PR(s),a=Le("/rooms/$roomId/members?"+o,{$roomId:e});return this.http.authedRequest(de.Get,a)}upgradeRoom(e,t){const r=Le("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(de.Post,r,void 0,{new_version:t})}getStateEvent(e,t,r){const i={$roomId:e,$eventType:t,$stateKey:r};let s=Le("/rooms/$roomId/state/$eventType",i);return r!==void 0&&(s=Le(s+"/$stateKey",i)),this.http.authedRequest(de.Get,s)}sendStateEvent(e,t,r,i="",s={}){const o={$roomId:e,$eventType:t,$stateKey:i};let a=Le("/rooms/$roomId/state/$eventType",o);return i!==void 0&&(a=Le(a+"/$stateKey",o)),this.http.authedRequest(de.Put,a,void 0,r,s)}roomInitialSync(e,t){const r=Le("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(de.Get,r,{limit:(t==null?void 0:t.toString())??"30"})}async setRoomReadMarkersHttpRequest(e,t,r,i){const s=Le("/rooms/$roomId/read_markers",{$roomId:e}),o={[ci.FullyRead]:t,[ci.Read]:r};return(await this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")||await this.isVersionSupported("v1.4"))&&(o[ci.ReadPrivate]=i),this.http.authedRequest(de.Post,s,void 0,o)}getJoinedRooms(){const e=Le("/joined_rooms",{});return this.http.authedRequest(de.Get,e)}getJoinedRoomMembers(e){const t=Le("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(de.Get,t)}publicRooms({server:e,limit:t,since:r,...i}={}){if(Object.keys(i).length===0){const s={server:e,limit:t,since:r};return this.http.authedRequest(de.Get,"/publicRooms",s)}else{const s={server:e},o={limit:t,since:r,...i};return this.http.authedRequest(de.Post,"/publicRooms",s,o)}}createAlias(e,t){const r=Le("/directory/room/$alias",{$alias:e}),i={room_id:t};return this.http.authedRequest(de.Put,r,void 0,i)}deleteAlias(e){const t=Le("/directory/room/$alias",{$alias:e});return this.http.authedRequest(de.Delete,t)}getLocalAliases(e){const t=Le("/rooms/$roomId/aliases",{$roomId:e}),r=lr.V3;return this.http.authedRequest(de.Get,t,void 0,void 0,{prefix:r})}getRoomIdForAlias(e){const t=Le("/directory/room/$alias",{$alias:e});return this.http.authedRequest(de.Get,t)}getRoomDirectoryVisibility(e){const t=Le("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(de.Get,t)}setRoomDirectoryVisibility(e,t){const r=Le("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(de.Put,r,void 0,{visibility:t})}searchUserDirectory({term:e,limit:t}){const r={search_term:e};return t!==void 0&&(r.limit=t),this.http.authedRequest(de.Post,"/user_directory/search",void 0,r)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){const r=t?Le("/profile/$userId/$info",{$userId:e,$info:t}):Le("/profile/$userId",{$userId:e});return this.http.authedRequest(de.Get,r)}async doesServerSupportExtendedProfiles(){return this.doesServerSupportUnstableFeature(eB)}async getExtendedProfileRequestPrefix(){return await this.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable")?lr.V3:"/_matrix/client/unstable/uk.tcpip.msc4133"}async getExtendedProfile(e){if(!await this.doesServerSupportExtendedProfiles())throw new Error("Server does not support extended profiles");return this.http.authedRequest(de.Get,Le("/profile/$userId",{$userId:e}),void 0,void 0,{prefix:await this.getExtendedProfileRequestPrefix()})}async getExtendedProfileProperty(e,t){if(!await this.doesServerSupportExtendedProfiles())throw new Error("Server does not support extended profiles");return(await this.http.authedRequest(de.Get,Le("/profile/$userId/$key",{$userId:e,$key:t}),void 0,void 0,{prefix:await this.getExtendedProfileRequestPrefix()}))[t]}async setExtendedProfileProperty(e,t){if(!await this.doesServerSupportExtendedProfiles())throw new Error("Server does not support extended profiles");const r=this.getUserId();await this.http.authedRequest(de.Put,Le("/profile/$userId/$key",{$userId:r,$key:e}),void 0,{[e]:t},{prefix:await this.getExtendedProfileRequestPrefix()})}async deleteExtendedProfileProperty(e){if(!await this.doesServerSupportExtendedProfiles())throw new Error("Server does not support extended profiles");const t=this.getUserId();await this.http.authedRequest(de.Delete,Le("/profile/$userId/$key",{$userId:t,$key:e}),void 0,void 0,{prefix:await this.getExtendedProfileRequestPrefix()})}async patchExtendedProfile(e){if(!await this.doesServerSupportExtendedProfiles())throw new Error("Server does not support extended profiles");const t=this.getUserId();return this.http.authedRequest(de.Patch,Le("/profile/$userId",{$userId:t}),{},e,{prefix:await this.getExtendedProfileRequestPrefix()})}async setExtendedProfile(e){if(!await this.doesServerSupportExtendedProfiles())throw new Error("Server does not support extended profiles");const t=this.getUserId();await this.http.authedRequest(de.Put,Le("/profile/$userId",{$userId:t}),{},e,{prefix:await this.getExtendedProfileRequestPrefix()})}getThreePids(){return this.http.authedRequest(de.Get,"/account/3pid")}async addThreePidOnly(e){return this.http.authedRequest(de.Post,"/account/3pid/add",void 0,e)}async bindThreePid(e){return this.http.authedRequest(de.Post,"/account/3pid/bind",void 0,e)}async unbindThreePid(e,t){const r="/account/3pid/unbind",i={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)};return this.http.authedRequest(de.Post,r,void 0,i)}deleteThreePid(e,t){return this.http.authedRequest(de.Post,"/account/3pid/delete",void 0,{medium:e,address:t})}setPassword(e,t,r){const i="/account/password",s={auth:e,new_password:t,logout_devices:r};return this.http.authedRequest(de.Post,i,void 0,s)}getDevices(){return this.http.authedRequest(de.Get,"/devices")}getDevice(e){const t=Le("/devices/$device_id",{$device_id:e});return this.http.authedRequest(de.Get,t)}setDeviceDetails(e,t){const r=Le("/devices/$device_id",{$device_id:e});return this.http.authedRequest(de.Put,r,void 0,t)}deleteDevice(e,t){const r=Le("/devices/$device_id",{$device_id:e}),i={};return t&&(i.auth=t),this.http.authedRequest(de.Delete,r,void 0,i)}deleteMultipleDevices(e,t){const r={devices:e};return t&&(r.auth=t),this.http.authedRequest(de.Post,"/delete_devices",void 0,r)}async getPushers(){const e=await this.http.authedRequest(de.Get,"/pushers");return await this.doesServerSupportUnstableFeature("org.matrix.msc3881")||(e.pushers=e.pushers.map(t=>(t.hasOwnProperty(UR.name)||(t[UR.name]=!0),t))),e}setPusher(e){return this.http.authedRequest(de.Post,"/pushers/set",void 0,e)}removePusher(e,t){const r="/pushers/set",i={pushkey:e,app_id:t,kind:null};return this.http.authedRequest(de.Post,r,void 0,i)}setLocalNotificationSettings(e,t){const r=`${Ij.name}.${e}`;return this.setAccountData(r,t)}getPushRules(){return this.http.authedRequest(de.Get,"/pushrules/").then(e=>(this.setPushRules(e),this.pushRules))}setPushRules(e){this.pushRules=Mb.rewriteDefaultRules(e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,r,i){const s=Le("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:r});return this.http.authedRequest(de.Put,s,void 0,i)}deletePushRule(e,t,r){const i=Le("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:r});return this.http.authedRequest(de.Delete,i)}setPushRuleEnabled(e,t,r,i){const s=Le("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:r});return this.http.authedRequest(de.Put,s,void 0,{enabled:i})}setPushRuleActions(e,t,r,i){const s=Le("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:r});return this.http.authedRequest(de.Put,s,void 0,{actions:i})}search({body:e,next_batch:t},r){const i={};return t&&(i.next_batch=t),this.http.authedRequest(de.Post,"/search",i,e,{abortSignal:r})}uploadKeysRequest(e,t){return this.http.authedRequest(de.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(de.Post,"/keys/signatures/upload",void 0,e)}downloadKeysForUsers(e,{token:t}={}){const r={device_keys:{}};return t!==void 0&&(r.token=t),e.forEach(i=>{r.device_keys[i]=[]}),this.http.authedRequest(de.Post,"/keys/query",void 0,r)}claimOneTimeKeys(e,t="signed_curve25519",r){const i={};t===void 0&&(t="signed_curve25519");for(const[a,c]of e){const l=i[a]||{};wb(i,a,l),wb(l,c,t)}const s={one_time_keys:i};return r&&(s.timeout=r),this.http.authedRequest(de.Post,"/keys/claim",void 0,s)}getKeyChanges(e,t){const r={from:e,to:t};return this.http.authedRequest(de.Get,"/keys/changes",r)}uploadDeviceSigningKeys(e,t){const r=Object.assign({},t);return e&&Object.assign(r,{auth:e}),this.http.authedRequest(de.Post,"/keys/device_signing/upload",void 0,r,{prefix:lr.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const t=this.http.getUrl("/account/register",void 0,da.V2,this.idBaseUrl);return this.http.requestOtherUrl(de.Post,t,e)}requestEmailToken(e,t,r,i,s){const o={client_secret:t,email:e,send_attempt:r==null?void 0:r.toString()};return i&&(o.next_link=i),this.http.idServerRequest(de.Post,"/validate/email/requestToken",o,da.V2,s)}requestMsisdnToken(e,t,r,i,s,o){const a={client_secret:r,country:e,phone_number:t,send_attempt:i==null?void 0:i.toString()};return s&&(a.next_link=s),this.http.idServerRequest(de.Post,"/validate/msisdn/requestToken",a,da.V2,o)}submitMsisdnToken(e,t,r,i){const s={sid:e,client_secret:t,token:r};return this.http.idServerRequest(de.Post,"/validate/msisdn/submitToken",s,da.V2,i??void 0)}submitMsisdnTokenOtherUrl(e,t,r,i){const s={sid:t,client_secret:r,token:i};return this.http.requestOtherUrl(de.Post,e,s)}getIdentityHashDetails(e){return this.http.idServerRequest(de.Get,"/hash_details",void 0,da.V2,e)}async identityHashedLookup(e,t){const r={},i=await this.getIdentityHashDetails(t);if(!i||!i.lookup_pepper||!i.algorithms)throw new Error("Unsupported identity server: bad response");r.pepper=i.lookup_pepper;const s={};if(i.algorithms.includes("sha256"))r.addresses=await Promise.all(e.map(async c=>{const l=c[0].toLowerCase(),u=c[1].toLowerCase(),h=await q$(`${l} ${u} ${r.pepper}`),p=fw(h);return s[p]=c[0],p})),r.algorithm="sha256";else if(i.algorithms.includes("none"))r.addresses=e.map(c=>{const l=c[0].toLowerCase(),u=c[1].toLowerCase(),h=`${l} ${u}`;return s[h]=c[0],h}),r.algorithm="none";else throw new Error("Unsupported identity server: unknown hash algorithm");const o=await this.http.idServerRequest(de.Post,"/lookup",r,da.V2,t);if(!(o!=null&&o.mappings))return[];const a=[];for(const c of Object.keys(o.mappings)){const l=o.mappings[c],u=s[c];if(!u)throw new Error("Identity server returned more results than expected");a.push({address:u,mxid:l})}return a}async lookupThreePid(e,t,r){const s=(await this.identityHashedLookup([[t,e]],r)).find(a=>a.address===t);return s?{address:t,medium:e,mxid:s.mxid}:{}}async bulkLookupThreePids(e,t){const r=await this.identityHashedLookup(e.map(s=>[s[1],s[0]]),t),i=[];for(const s of r){const o=e.find(a=>a[1]===s.address);if(!o)throw new Error("Identity sever returned unexpected results");i.push([o[0],s.address,s.mxid])}return{threepids:i}}getIdentityAccount(e){return this.http.idServerRequest(de.Get,"/account",void 0,da.V2,e)}sendToDevice(e,t,r){const i=Le("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:r||this.makeTxnId()}),s={messages:td(t)},o=new Map;for(const[a,c]of t)o.set(a,Array.from(c.keys()));return this.logger.debug(`PUT ${i}`,o),this.http.authedRequest(de.Put,i,void 0,s)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(de.Get,"/thirdparty/protocols").then(e=>{if(!e||typeof e!="object")throw new Error(`/thirdparty/protocols did not return an object: ${e}`);return e})}getThirdpartyLocation(e,t){const r=Le("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(de.Get,r,t)}getThirdpartyUser(e,t){const r=Le("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(de.Get,r,t)}getTerms(e,t){const r=this.termsUrlForService(e,t);return this.http.requestOtherUrl(de.Get,r)}agreeToTerms(e,t,r,i){const s=this.termsUrlForService(e,t),o={Authorization:"Bearer "+r};return this.http.requestOtherUrl(de.Post,s,{user_accepts:i},{headers:o})}reportEvent(e,t,r,i){const s=Le("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(de.Post,s,void 0,{score:r,reason:i})}getRoomHierarchy(e,t,r,i=!1,s){const o=Le("/rooms/$roomId/hierarchy",{$roomId:e}),a={suggested_only:String(i),max_depth:r==null?void 0:r.toString(),from:s,limit:t==null?void 0:t.toString()};return this.http.authedRequest(de.Get,o,a,void 0,{prefix:lr.V1}).catch(c=>{if(c.errcode==="M_UNRECOGNIZED")return this.http.authedRequest(de.Get,o,a,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw c})}async unstableCreateFileTree(e){const{room_id:t}=await this.createRoom({name:e,preset:ay.PrivateChat,power_level_content_override:{...Jse,users:{[this.getUserId()]:100}},creation_content:{[Eb]:ld.Space},initial_state:[{type:MR.name,state_key:DR.name,content:{[NR.name]:!0}},{type:ie.RoomEncryption,state_key:"",content:{algorithm:"m.megolm.v1.aes-sha2"}}]});return new R5(this,t)}unstableGetFileTreeSpace(e){var s,o;const t=this.getRoom(e);if((t==null?void 0:t.getMyMembership())!==We.Join)return null;const r=t.currentState.getStateEvents(ie.RoomCreate,""),i=t.currentState.getStateEvents(MR.name,DR.name);if(!r)throw new Error("Expected single room create event");return!((s=i==null?void 0:i.getContent())!=null&&s[NR.name])||((o=r.getContent())==null?void 0:o[Eb])!==ld.Space?null:new R5(this,e)}slidingSync(e,t,r){const i={};e.pos&&(i.pos=e.pos,delete e.pos),e.timeout&&(i.timeout=e.timeout,delete e.timeout);const s=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(de.Post,"/sync",i,e,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:t,localTimeoutMs:s,abortSignal:r})}supportsThreads(){var e;return((e=this.clientOpts)==null?void 0:e.threadSupport)||!1}supportsIntentionalMentions(){return this.canSupport.get(vs.IntentionalMentions)!==Vr.Unsupported}async getRoomSummary(e,t){const r={prefix:"/_matrix/client/unstable/im.nheko.summary"};try{const i=Le("/summary/$roomid",{$roomid:e});return await this.http.authedRequest(de.Get,i,{via:t},void 0,r)}catch(i){if(i instanceof mn&&i.errcode==="M_UNRECOGNIZED"){const s=Le("/rooms/$roomid/summary",{$roomid:e});return await this.http.authedRequest(de.Get,s,{via:t},void 0,r)}else throw i}}processThreadEvents(e,t,r){e.processThreadedEvents(t,r)}processThreadRoots(e,t,r){this.supportsThreads()&&e.processThreadRoots(t,r)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){t!=null&&t.length&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}async whoami(){return this.http.authedRequest(de.Get,"/account/whoami")}async timestampToEvent(e,t,r){const i=Le("/rooms/$roomId/timestamp_to_event",{$roomId:e}),s={ts:t.toString(),dir:r};try{return await this.http.authedRequest(de.Get,i,s,void 0,{prefix:lr.V1})}catch(o){if(o.errcode==="M_UNRECOGNIZED"&&(o.httpStatus===400||o.httpStatus===404||o.httpStatus===405))return await this.http.authedRequest(de.Get,i,s,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw o}}async getAuthIssuer(){return this.http.request(de.Get,"/auth_issuer",void 0,void 0,{prefix:lr.Unstable+"/org.matrix.msc2965"})}async getAuthMetadata(){let e;try{e=await this.http.request(de.Get,"/auth_metadata",void 0,void 0,{prefix:lr.Unstable+"/org.matrix.msc2965"})}catch(t){if(t instanceof mn&&t.errcode==="M_UNRECOGNIZED"){const{issuer:r}=await this.getAuthIssuer();return OP(r)}throw t}return MP(e)}};V4.RESTORE_BACKUP_ERROR_BAD_KEY="RESTORE_BACKUP_ERROR_BAD_KEY";let dv=V4;function O5(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>[`${ga}.${e}`,t]))}function tB(n,e){var u;const t=n.getUserId(),r=e.getId(),i=n.getRoom(e.getRoomId());if(!i||!t||!r)return;if(!i.findEventById(r)){M.info(`Decrypted event ${e.getId()} is not in room ${i.roomId}: ignoring`);return}const s=!!e.threadRootId&&!e.isThreadRoot;let o;if(s){const h=i.getThread(e.threadRootId);o=h?h.hasUserReadEvent(t,r):!0}else o=i.hasUserReadEvent(t,r);if(o)return;const a=n.getPushActionsForEvent(e,!0);if(!!((u=a==null?void 0:a.tweaks)!=null&&u.highlight)){const h=i.getUnreadCountForEventContext(rr.Highlight,e)+1;s?i.setThreadUnreadNotificationCount(e.threadRootId,rr.Highlight,h):i.setUnreadNotificationCount(rr.Highlight,h)}if(!!(a!=null&&a.notify)){const h=i.getUnreadCountForEventContext(rr.Total,e)+1;s?i.setThreadUnreadNotificationCount(e.threadRootId,rr.Total,h):i.setUnreadNotificationCount(rr.Total,h)}}function Kf(n){return hv(n)?iy:n.threadRootId}function hv(n){return!n.threadRootId||n.isThreadRoot?!0:n.isRelation()?n.isRelation(en.name)?!1:n.relationEventId===n.threadRootId:(M.warn(`Event is not a relation or a thread root, but still has a threadRootId! id=${n.getId()}`),!0)}var Ro=(n=>(n.New="Thread.new",n.Update="Thread.update",n.NewReply="Thread.newReply",n.ViewThread="Thread.viewThread",n.Delete="Thread.delete",n))(Ro||{}),ha=(n=>(n[n.None=0]="None",n[n.Experimental=1]="Experimental",n[n.Stable=2]="Stable",n))(ha||{});function S_(n,e){return n?2:e?1:0}const Fs=class Fs extends Qj{constructor(e,t,r){if(super(),this.id=e,this.rootEvent=t,this._currentUserParticipated=!1,this.replyCount=0,this.pendingReplyCount=0,this.initialEventsFetched=!Fs.hasServerSideSupport,this.replayEvents=[],this.onTimelineReset=async()=>{await this.processRootEventPromise,this.processRootEventPromise=void 0},this.onBeforeRedaction=(i,s)=>{i!=null&&i.isRelation(en.name)&&this.room.eventShouldLiveIn(i).threadId===this.id&&i.getId()!==this.id&&!s.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit("Thread.update",this))},this.onRedaction=async(i,s,o)=>{var a;if(o===this.id)if(this.replyCount<=0){for(const c of this.timeline)this.clearEventMetadata(c);this.lastEvent=this.rootEvent,this._currentUserParticipated=!1,this.emit("Thread.delete",this)}else((a=this.lastEvent)==null?void 0:a.getId())===i.getAssociatedId()&&(await this.processRootEventPromise,this.processRootEventPromise=void 0),await this.updateThreadMetadata()},this.onTimelineEvent=(i,s,o)=>{if(!o){const a=i.getSender();a&&s&&this.shouldSendLocalEchoReceipt(a,i)&&s.addLocalEchoReceipt(a,i,ci.Read),i.getId()!==this.id&&i.isRelation(en.name)&&this.replyCount++}this.onEcho(i,o??!1)},this.onLocalEcho=i=>{this.onEcho(i,!1)},this.onEcho=async(i,s)=>{i.threadRootId===this.id&&this.lastEvent!==i&&(await this.updateThreadMetadata(),i.isRelation(en.name)&&(s||(this.lastEvent=void 0,this.emit("Thread.newReply",this,i))))},this.setMaxListeners(1e3),!(r!=null&&r.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=r.room,this.client=r.client,this.pendingEventOrdering=r.pendingEventOrdering??Rd.Chronological,this.timelineSet=new cf(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new oy(this),this.reEmitter.reEmit(this.timelineSet,[Xe.Timeline,Xe.TimelineReset]),this.room.on(pn.BeforeRedaction,this.onBeforeRedaction),this.room.on(Xe.Redaction,this.onRedaction),this.room.on(Xe.LocalEchoUpdated,this.onLocalEcho),this.room.on(Xe.TimelineReset,this.onTimelineReset),this.timelineSet.on(Xe.Timeline,this.onTimelineEvent),this.processReceipts(r.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}async fetchRootEvent(){try{const e=await this.client.fetchRoomEvent(this.roomId,this.id),t=this.client.getEventMapper();this.rootEvent=t(e)}catch(e){M.error("Failed to fetch thread root to construct thread with",e)}await this.processEvent(this.rootEvent)}static setServerSideSupport(e){Fs.hasServerSideSupport=e,e!==2&&(wf.setPreferUnstable(!0),Ef.setPreferUnstable(!0),en.setPreferUnstable(!0))}static setServerSideListSupport(e){Fs.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){Fs.hasServerSideFwdPaginationSupport=e}shouldSendLocalEchoReceipt(e,t){var i;if((this.client.canSupport.get(vs.RelationsRecursion)??Vr.Unsupported)===Vr.Unsupported){const s=(i=this.getReadReceiptForUserId(e))==null?void 0:i.eventId;if(s){const o=this.findEventById(s);if(o&&o.getTs()>t.getTs())return!1}}return!0}get roomState(){return this.room.getLiveTimeline().getState(Be.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState,addToState:!1})}insertEventIntoTimeline(e){const t=e.getId();t&&(this.findEventById(t)||this.timelineSet.insertEventIntoTimeline(e,this.liveTimeline,this.roomState,!1))}addEvents(e,t){e.forEach(r=>this.addEvent(r,t,!1)),this.updateThreadMetadata()}addEvent(e,t,r=!0){this.setEventMetadata(e);const i=this.lastReply(),s=!i||e.localTimestamp>=i.localTimestamp;if(!Fs.hasServerSideSupport)this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e);else if(e.isRelation(sn.Annotation)||e.isRelation(sn.Replace)){this.addRelatedThreadEvent(e,t);return}else!t&&s?(this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e)):t?this.addEventToTimeline(e,t):this.insertEventIntoTimeline(e);e.getId()!==this.id&&e.isRelation(en.name)&&!t&&s&&(this.lastEvent=void 0),r&&(this.emit("Thread.newReply",this,e),this.updateThreadMetadata())}addRelatedThreadEvent(e,t){var r,i,s;this.initialEventsFetched?(this.client.canSupport.get(vs.RelationsRecursion)??Vr.Unsupported)===Vr.Unsupported?this.insertEventIntoTimeline(e):this.addEventToTimeline(e,t):(r=this.replayEvents)==null||r.push(e),(i=this.timelineSet.relations)==null||i.aggregateParentEvent(e),(s=this.timelineSet.relations)==null||s.aggregateChildEvent(e,this.timelineSet)}async processEvent(e){e&&(this.setEventMetadata(e),await this.fetchEditsWhereNeeded(e))}processReceipts(e=[]){for(const{eventId:t,receiptType:r,userId:i,receipt:s,synthetic:o}of e)this.addReceiptToStructure(t,r,i,s,o)}getRootEventBundledRelationship(e=this.rootEvent){return e==null?void 0:e.getServerAggregatedRelation(en.name)}async processRootEvent(){const e=this.getRootEventBundledRelationship();if(Fs.hasServerSideSupport&&e){this.replyCount=e.count,this._currentUserParticipated=!!e.current_user_participated;const t=this.client.getEventMapper();this.lastEvent=t({...e.latest_event,room_id:this.roomId}),this.updatePendingReplyCount(),await this.processEvent(this.lastEvent)}}updatePendingReplyCount(){const t=(this.pendingEventOrdering===Rd.Detached?this.room.getPendingEvents():this.events).filter(r=>{var i;return r.threadRootId===this.id&&r.isRelation(en.name)&&r.status!==null&&r.getId()!==((i=this.lastEvent)==null?void 0:i.getId())});this.lastPendingEvent=t.length?t[t.length-1]:void 0,this.pendingReplyCount=t.length}async resetLiveTimeline(e,t){const r=this.liveTimeline;this.timelineSet.resetLiveTimeline(e??void 0,t??void 0);const i=this.liveTimeline;let s,o;e&&(s=(await this.client.createMessagesRequest(this.roomId,e,1,bt.Forward)).end),t&&(o=(await this.client.createMessagesRequest(this.roomId,t,1,bt.Backward)).start),t&&r.getPaginationToken(bt.Forward)===t&&r.setPaginationToken(o??null,bt.Forward),e&&i.getPaginationToken(bt.Backward)===e&&i.setPaginationToken(s??null,bt.Backward)}async updateThreadFromRootEvent(){Fs.hasServerSideSupport&&(!this.initialEventsFetched&&!this.lastEvent&&await this.processRootEvent(),await this.fetchRootEvent()),await this.processRootEvent()}async updateThreadMetadata(){if(this.updatePendingReplyCount(),this.processRootEventPromise||(this.processRootEventPromise=this.updateThreadFromRootEvent()),await this.processRootEventPromise,!this.initialEventsFetched)if(this.initalEventFetchProm)await this.initalEventFetchProm;else try{this.timelineSet.resetLiveTimeline(),this.replyCount===0&&this.rootEvent?(this.timelineSet.addEventsToTimeline([this.rootEvent],!0,!1,this.liveTimeline,null),this.liveTimeline.setPaginationToken(null,bt.Backward)):(this.initalEventFetchProm=this.client.paginateEventTimeline(this.liveTimeline,{backwards:!0}),await this.initalEventFetchProm),this.initialEventsFetched=!0;for(const e of this.replayEvents)this.addEvent(e,!1);this.replayEvents=null,this.emit(Xe.TimelineReset,this.room,this.timelineSet,!0)}catch(e){M.error("Failed to load start of newly created thread: ",e),this.initialEventsFetched=!1}this.emit("Thread.update",this)}async fetchEditsWhereNeeded(...e){if((this.client.canSupport.get(vs.RelationsRecursion)??Vr.Unsupported)===Vr.Unsupported)return Promise.all(e.filter(Boe).map(async r=>{try{const i=await this.client.relations(this.roomId,r.getId(),sn.Replace,r.getType(),{limit:1});if(i.events.length){const s=i.events[0];r.makeReplaced(s),this.insertEventIntoTimeline(s)}}catch(i){M.error("Failed to load edits for encrypted thread event",i)}}))}setEventMetadata(e){e&&(Be.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){var t,r,i;e&&(e.setThread(void 0),(i=(r=(t=e.event)==null?void 0:t.unsigned)==null?void 0:r["m.relations"])==null||delete i[en.name])}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(e=t=>t.isRelation(en.name)){for(let t=this.timeline.length-1;t>=0;t--){const r=this.timeline[t];if(e(r))return r}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){return this.lastPendingEvent??this.lastEvent??this.lastReply()}get timeline(){return this.events}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof Ji}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 o;const r=e===this.client.getUserId(),i=this.timeline[this.timeline.length-1];if(r&&i){const a=i.getTs()<this.room.getOldestThreadedReceiptTs(),c=i.getId();if(a&&c)return c}const s=super.getEventReadUpTo(e,t);if(i){const a=this.room.getLastUnthreadedReceiptFor(e);if(!a)return s;for(let c=((o=this.timeline)==null?void 0:o.length)-1;c>=0;--c){const l=this.timeline[c];if(l.getId()===s)return s;if(l.getTs()<a.ts)return l.getId()??s}}return s}hasUserReadEvent(e,t){var r,i,s;if(e===this.client.getUserId()){const o=(((r=this.lastReply())==null?void 0:r.getTs())??0)<this.room.getOldestThreadedReceiptTs(),a=((i=this.room.getLastUnthreadedReceiptFor(e))==null?void 0:i.ts)??0,c=(((s=this==null?void 0:this.lastReply())==null?void 0:s.getTs())??0)<a;if(o||c)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)}};Fs.hasServerSideSupport=0,Fs.hasServerSideListSupport=0,Fs.hasServerSideFwdPaginationSupport=0;let Gr=Fs;function Boe(n){return n.isEncrypted()&&(n.isRelation(en.name)||n.isThreadRoot)}const wf=new rw("related_by_senders","io.element.relation_senders"),Ef=new rw("related_by_rel_types","io.element.relation_types"),en=new rw("m.thread","io.element.thread");var To=(n=>(n[n.My=0]="My",n[n.All=1]="All",n))(To||{});function nB(n){switch(n){case 0:return"participated";default:return"all"}}class M5 extends Error{constructor(e,t,r){super(t),this.code=e,this.name="DecryptionError",this.detailedString=Hoe(this,r)}}function Hoe(n,e){let t=n.name+"[msg: "+n.message;return e&&(t+=", "+Object.keys(e).map(r=>r+": "+e[r]).join(", ")),t+="]",t}const N5=Object.freeze({visible:!0});var pn=(n=>(n.Decrypted="Event.decrypted",n.BeforeRedaction="Event.beforeRedaction",n.VisibilityChange="Event.visibilityChange",n.LocalEventIdReplaced="Event.localEventIdReplaced",n.Status="Event.status",n.Replaced="Event.replaced",n.RelationsCreated="Event.relationsCreated",n.SentinelUpdated="Event.sentinelUpdated",n))(pn||{});class Ji extends Yn{constructor(e={}){super(),this.event=e,this.pushDetails={},this._replacingEvent=null,this._localRedactionEvent=null,this._isCancelled=!1,this.visibility=N5,this._hasCachedExtEv=!1,this._cachedExtEv=void 0,this._decryptionFailureReason=null,this.senderCurve25519Key=null,this.claimedEd25519Key=null,this.forwardingCurve25519KeyChain=[],this.untrusted=null,this.decryptionPromise=null,this.retryDecryption=!1,this.sender=null,this.target=null,this.status=null,this.error=null,this.forwardLooking=!0,["state_key","type","sender","room_id","membership"].forEach(r=>{typeof e[r]=="string"&&(e[r]=IT(e[r]))}),["membership","avatar_url","displayname"].forEach(r=>{var i;typeof((i=e.content)==null?void 0:i[r])=="string"&&(e.content[r]=IT(e.content[r]))}),["rel_type"].forEach(r=>{var i,s;typeof((s=(i=e.content)==null?void 0:i["m.relates_to"])==null?void 0:s[r])=="string"&&(e.content["m.relates_to"][r]=IT(e.content["m.relates_to"][r]))}),this.txnId=e.txn_id;const t=this.getAge();this.localTimestamp=t!==void 0?Date.now()-t:this.getTs()??Date.now(),this.reEmitter=new oy(this)}setMetadata(e,t){var s,o,a,c;const r=this.isState()&&this.getType()===ie.RoomMember&&this.getSender()===this.getStateKey();let i=!1;if(r||!((o=(s=this.sender)==null?void 0:s.events)!=null&&o.member)){const l=e.getSentinelMember(this.getSender());l!==this.sender&&(i=!0),this.sender=l}if(r||!((c=(a=this.target)==null?void 0:a.events)!=null&&c.member)&&this.getType()===ie.RoomMember){const l=e.getSentinelMember(this.getStateKey());l!==this.target&&(i=!0),this.target=l}this.isState()&&t&&(this.forwardLooking=!1),i&&this.emit("Event.sentinelUpdated")}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=ss.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){const e=Object.assign({},this.getContent());if(this.getWireType()===ie.RoomMessageEncrypted)for(const[t,r]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||e[t]===void 0&&(e[t]=r);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 t;const e=this.getRoomId();return e?`id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()} room=${e} ts=${(t=this.getDate())==null?void 0:t.toISOString()}`:`msgid=${this.getContent()[cw]} type=${this.getWireType()} sender=${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 r;if(this.isState())return;const e=(r=this.getWireContent())==null?void 0:r["m.relates_to"];if((e==null?void 0:e.rel_type)===en.name)return e.event_id;if(this.thread)return this.thread.id;if(this.threadId!==void 0)return this.threadId;const t=this.getUnsigned();if(typeof t[Cb.name]=="string")return t[Cb.name]}get isThreadRoot(){return this.isState()?!1:!!this.getServerAggregatedRelation(en.name)||this.threadRootId===this.getId()}get replyEventId(){var e,t;return(t=(e=this.getWireContent()["m.relates_to"])==null?void 0:e["m.in_reply_to"])==null?void 0:t.event_id}get relationEventId(){var e,t;return(t=(e=this.getWireContent())==null?void 0:e["m.relates_to"])==null?void 0:t.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(){const e=this.getUnsigned();return Rj.findIn(e)}makeEncrypted(e,t,r,i){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=r,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===sk.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE}shouldAttemptDecryption(){return!(this.isRedacted()||this.isBeingDecrypted()||this.clearEvent||!this.isEncrypted())}async attemptDecryption(e,t={}){if(!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");const r=this.clearEvent&&!this.isDecryptionFailure(),i=t.forceRedecryptIfUntrusted&&this.isKeySourceUntrusted();if(r&&!i)throw new Error("Attempt to decrypt event which has already been decrypted");return this.decryptionPromise?(M.log(`Event ${this.getId()} already being decrypted; queueing a retry`),this.retryDecryption=!0,this.decryptionPromise):(this.decryptionPromise=this.decryptionLoop(e,t),this.decryptionPromise)}getKeyRequestRecipients(e){return[{userId:e,deviceId:"*"}]}async decryptionLoop(e,t={}){for(await Promise.resolve();;){this.retryDecryption=!1;let r;try{const i=await e.decryptEvent(this);t.isRetry===!0&&M.info(`Decrypted event on retry (${this.getDetails()})`),this.setClearData(i),this._decryptionFailureReason=null}catch(i){const s=i instanceof M5?i.detailedString:String(i);if(r=i,this.retryDecryption){M.log(`Error decrypting event (${this.getDetails()}), but retrying: ${s}`);continue}M.warn(`Error decrypting event (${this.getDetails()}): ${s}`),this.setClearDataForDecryptionFailure(String(i)),this._decryptionFailureReason=i instanceof M5?i.code:sk.UNKNOWN_ERROR}this.decryptionPromise=null,this.retryDecryption=!1,this.setPushDetails(),t.emit!==!1&&this.emit("Event.decrypted",this,r);return}}setClearData(e){this.clearEvent=e.clearEvent,this.senderCurve25519Key=e.senderCurve25519Key??null,this.claimedEd25519Key=e.claimedEd25519Key??null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.invalidateExtensibleEvent()}setClearDataForDecryptionFailure(e){this.clearEvent={type:ie.RoomMessage,content:{msgtype:"m.bad.encrypted",body:`** Unable to decrypt: ${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===ie.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(){const e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=void 0),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit("Event.beforeRedaction",this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){const t=(e==null?void 0:e.visible)??!0,r=(e==null?void 0:e.reason)??null;let i=!1;(this.visibility.visible!==t||!this.visibility.visible&&this.visibility.reason!==r)&&(i=!0),i&&(t?this.visibility=N5:this.visibility=Object.freeze({visible:!1,reason:r}),this.emit("Event.visibilityChange",this,t))}messageVisibility(){return this.visibility}makeRedacted(e,t){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit("Event.beforeRedaction",this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(const s in this.event)this.event.hasOwnProperty(s)&&!Voe.has(s)&&delete this.event[s];this.isEncrypted()&&(this.clearEvent=void 0);const r=this.getType()in D5?D5[this.getType()]:{},i=this.getContent();for(const s in i)i.hasOwnProperty(s)&&!r[s]&&delete i[s];!this.isThreadRoot&&this.threadRootId&&this.threadRootId!==this.getId()&&(this.moveAllRelatedToMainTimeline(t),e.moveToMainTimeline(t)),this.invalidateExtensibleEvent()}moveAllRelatedToMainTimeline(e){var r;const t=this.thread;if(this.moveToMainTimeline(e),t)for(const i of t.events)((r=i.getRelation())==null?void 0:r.event_id)===this.getId()&&i.moveAllRelatedToMainTimeline(e)}moveToMainTimeline(e){var r;(r=this.thread)==null||r.timelineSet.removeEvent(this.getId()),this.setThread(void 0);const t=e.getLiveTimeline();t.getTimelineSet().insertEventIntoTimeline(this,t,t.getState(Be.FORWARDS),!1)}isRedacted(){return!!this.getUnsigned().redacted_because}isRedaction(){return this.getType()===ie.RoomRedaction}asVisibilityChange(){if(!nd.matches(this.getType()))return null;const e=this.getRelation();if(!e||e.rel_type!="m.reference")return null;const t=e.event_id;if(!t)return null;const r=this.getWireContent(),i=!!r.visible,s=r.reason;return s&&typeof s!="string"?null:{visible:i,reason:s,eventId:t}}isVisibilityEvent(){return nd.matches(this.getType())}getRedactionEvent(){var e,t,r;return this.isRedacted()?(e=this.clearEvent)!=null&&e.unsigned?((t=this.clearEvent)==null?void 0:t.unsigned.redacted_because)??null:(r=this.event.unsigned)!=null&&r.redacted_because?this.event.unsigned.redacted_because:{}:null}getPushActions(){return this.pushDetails.actions||null}getPushDetails(){return this.pushDetails}setPushDetails(e,t){this.pushDetails={actions:e,rule:t}}handleRemoteEcho(e){const t=this.getUnsigned(),r=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()!==r&&this.emit("Event.localEventIdReplaced",this),this.localTimestamp=Date.now()-(this.getAge()??0)}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit("Event.status",this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit("Event.localEventIdReplaced",this)}isRelation(e){var r;const t=(r=this.getWireContent())==null?void 0:r["m.relates_to"];return this.isState()&&(t!=null&&t.rel_type)&&[sn.Replace,sn.Thread].includes(t.rel_type)?!1:!!(t!=null&&t.rel_type&&t.event_id&&(!e||t.rel_type===e))}getRelation(){return this.isRelation()?this.getWireContent()["m.relates_to"]??null:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=e??null,this.emit("Event.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?void 0:t[e]}replacingEventId(){const e=this.getServerAggregatedRelation(sn.Replace);if(e)return e.event_id;if(this._replacingEvent)return this._replacingEvent.getId()}replacingEvent(){return this._replacingEvent}replacingEventDate(){const e=this.getServerAggregatedRelation(sn.Replace);if(e){const t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent)return this._replacingEvent.getDate()??void 0}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const 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){const t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(e=!0){this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){const e=new Ji(JSON.parse(JSON.stringify(this.event)));for(const[t,r]of Object.entries(this))t!=="event"&&(e[t]=r);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;const t=LR(this.event),r=LR(e.event);return JSON.stringify(t)===JSON.stringify(r)}toJSON(){const e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}setThread(e){this.isState()||(this.thread&&this.reEmitter.stopReEmitting(this.thread,[Ro.Update]),this.thread=e,this.setThreadId(e==null?void 0:e.id),e&&this.reEmitter.reEmit(e,[Ro.Update]))}getThread(){return this.thread}setThreadId(e){this.threadId=e}}const Voe=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),D5={[ie.RoomMember]:{membership:1},[ie.RoomJoinRules]:{join_rule:1},[ie.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}};var It=(n=>(n.Events="RoomState.events",n.Members="RoomState.members",n.NewMember="RoomState.newMember",n.Update="RoomState.update",n.BeaconLiveness="RoomState.BeaconLiveness",n.Marker="RoomState.Marker",n))(It||{});class fv extends Yn{constructor(e,t={status:0}){super(),this.roomId=e,this.oobMemberFlags=t,this.reEmitter=new oy(this),this.sentinels={},this.displayNameToUserIds=new Map,this.userIdsToDisplayNames={},this.tokenToInvite={},this.joinedMemberCount=null,this.summaryJoinedMemberCount=null,this.invitedMemberCount=null,this.summaryInvitedMemberCount=null,this.modified=-1,this.members={},this.events=new Map,this.paginationToken=null,this.beacons=new Map,this._liveBeaconIds=[],this.updateModifiedTime()}getJoinedMemberCount(){return this.summaryJoinedMemberCount!==null?this.summaryJoinedMemberCount:(this.joinedMemberCount===null&&(this.joinedMemberCount=this.getMembers().reduce((e,t)=>t.membership===We.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===We.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;let t=this.sentinels[e];if(t===void 0){t=new Tb(this.roomId,e);const r=this.members[e];r!=null&&r.events.member&&t.setMembershipEvent(r.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());const r=this.events.get(e).get(t);return r||null}get hasLiveBeacons(){var e;return!!((e=this.liveBeaconIds)!=null&&e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){const e=new fv(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=0,Array.from(this.events.values()).forEach(r=>{e.setStateEvents(Array.from(r.values()))}),this.oobMemberFlags.status=t,this.summaryInvitedMemberCount!==null&&e.setInvitedMemberCount(this.getInvitedMemberCount()),this.summaryJoinedMemberCount!==null&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==2&&this.getMembers().forEach(r=>{var i;r.isOutOfBand()&&((i=e.getMember(r.userId))==null||i.markOutOfBand())}),e}setUnknownStateEvents(e){const t=e.filter(r=>!this.events.has(r.getType())||!this.events.get(r.getType()).has(r.getStateKey()));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach(r=>{if(r.getRoomId()!==this.roomId||!r.isState())return;kP.matches(r.getType())&&this.setBeacon(r);const i=this.getStateEventMatching(r);this.setStateEvent(r),r.getType()===ie.RoomMember&&(this.updateDisplayNameCache(r.getStateKey(),r.getContent().displayname??""),this.updateThirdPartyTokenCache(r)),this.emit("RoomState.events",r,this,i)}),this.onBeaconLivenessChange(),e.forEach(r=>{if(!(r.getRoomId()!==this.roomId||!r.isState()))if(r.getType()===ie.RoomMember){const i=r.getStateKey();(r.getContent().membership===We.Leave||r.getContent().membership===We.Ban)&&(r.getContent().avatar_url=r.getContent().avatar_url||r.getPrevContent().avatar_url,r.getContent().displayname=r.getContent().displayname||r.getPrevContent().displayname);const s=this.getOrCreateMember(i,r);s.setMembershipEvent(r,this),this.updateMember(s),this.emit("RoomState.members",r,this,s)}else if(r.getType()===ie.RoomPowerLevels){if(r.getStateKey()!=="")return;Object.values(this.members).forEach(s=>{const o=s.getLastModifiedTime();s.setPowerLevelEvent(r),o!==s.getLastModifiedTime()&&this.emit("RoomState.members",r,this,s)}),this.sentinels={}}else Cj.matches(r.getType())&&this.emit("RoomState.Marker",r,t)}),this.emit("RoomState.update",this)}async processBeaconEvents(e,t){var s;if(!e.length||!this.beacons.size)return;const r=[...this.beacons.values()].reduce((o,a)=>(o[a.beaconInfoId]=a,o),{}),i=(o,a)=>{if(!rk.matches(a.getType()))return;const c=r[o];c&&c.addLocations([a])};for(const o of e){const a=(s=o.getRelation())==null?void 0:s.event_id;if(!a||!r[a]||!rk.matches(o.getType())&&!o.isEncrypted())return;try{await t.decryptEventIfNeeded(o),i(a,o)}catch{o.isDecryptionFailure()&&o.once(pn.Decrypted,async()=>{i(a,o)})}}}getOrCreateMember(e,t){let r=this.members[e];return r||(r=new Tb(this.roomId,e),this.members[e]=r,this.emit("RoomState.newMember",t,this,r)),r}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 i;const t=Rb(e);if(this.beacons.has(t)){const s=this.beacons.get(t);if(e.isRedacted()){s.beaconInfoId===((i=e.getRedactionEvent())==null?void 0:i.redacts)&&(s.destroy(),this.beacons.delete(t));return}return s.update(e)}if(e.isRedacted())return;const r=new Jj(e);this.reEmitter.reEmit(r,[Gn.New,Gn.Update,Gn.Destroy,Gn.LivenessChange]),this.emit(Gn.New,e,r),r.on(Gn.LivenessChange,this.onBeaconLivenessChange.bind(this)),r.on(Gn.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(r.identifier,r)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter(e=>e.isLive).map(e=>e.identifier),this.emit("RoomState.BeaconLiveness",this,this.hasLiveBeacons)}getStateEventMatching(e){var t;return((t=this.events.get(e.getType()))==null?void 0:t.get(e.getStateKey()))??null}updateMember(e){const t=this.getStateEvents(ie.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===0}outOfBandMembersReady(){return this.oobMemberFlags.status===2}markOutOfBandMembersStarted(){this.oobMemberFlags.status===0&&(this.oobMemberFlags.status=1)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===1&&(this.oobMemberFlags.status=0)}clearOutOfBandMembers(){let e=0;Object.keys(this.members).forEach(t=>{this.members[t].isOutOfBand()&&(++e,delete this.members[t])}),M.log(`LL: RoomState removed ${e} members...`),this.oobMemberFlags.status=0}setOutOfBandMembers(e){M.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===1&&(M.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=2,e.forEach(t=>this.setOutOfBandMember(t)),this.emit("RoomState.update",this))}setOutOfBandMember(e){if(e.getType()!==ie.RoomMember)return;const t=e.getStateKey(),r=this.getMember(t);if(r&&!r.isOutOfBand())return;const 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("RoomState.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){return this.displayNameToUserIds.get(Hl(e))??[]}maySendRedactionForEvent(e,t){const r=this.getMember(t);return!r||r.membership===We.Leave||e.status||e.isRedacted()||!this.maySendEvent(ie.RoomRedaction,t)?!1:e.getSender()===t?!0:this.hasSufficientPowerLevelFor("redact",r.powerLevel)}hasSufficientPowerLevelFor(e,t){const r=this.getStateEvents(ie.RoomPowerLevels,"");let i={};r&&(i=r.getContent());let s=50;return LM(i[e])&&(s=i[e]),t>=s}maySendMessage(e){return this.maySendEventOfType(ie.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,r){const i=this.getStateEvents(ie.RoomPowerLevels,"");let s,o={},a=0,c=0,l=0;if(i){s=i.getContent(),o=s.events||{},Number.isSafeInteger(s.state_default)?a=s.state_default:a=50;const h=s.users&&s.users[t];Number.isSafeInteger(h)?l=h:Number.isSafeInteger(s.users_default)&&(l=s.users_default),Number.isSafeInteger(s.events_default)&&(c=s.events_default)}let u=r?a:c;return Number.isSafeInteger(o[e])&&(u=o[e]),l>=u}mayTriggerNotifOfType(e,t){const r=this.getMember(t);if(!r)return!1;const i=this.getStateEvents(ie.RoomPowerLevels,"");let s=50;return i&&i.getContent()&&i.getContent().notifications&&LM(i.getContent().notifications[e])&&(s=i.getContent().notifications[e]),r.powerLevel>=s}getJoinRule(){const e=this.getStateEvents(ie.RoomJoinRules,"");return((e==null?void 0:e.getContent())??{}).join_rule||wc.Invite}getHistoryVisibility(){const e=this.getStateEvents(ie.RoomHistoryVisibility,"");return((e==null?void 0:e.getContent())??{}).history_visibility||vw.Shared}getGuestAccess(){const e=this.getStateEvents(ie.RoomGuestAccess,"");return((e==null?void 0:e.getContent())??{}).guest_access||uv.Forbidden}findPredecessor(e=!1){if(e){const r=this.getStateEvents(ie.RoomPredecessor,"");if(r){const i=r.getContent(),s=i.predecessor_room_id;let o=i.last_known_event_id;typeof o!="string"&&(o=void 0);let a=i.via_servers;if(Array.isArray(a)||(a=void 0),typeof s=="string")return{roomId:s,eventId:o,viaServers:a}}}const t=this.getStateEvents(ie.RoomCreate,"");if(t){const r=t.getContent().predecessor;if(r){const i=r.room_id;if(typeof i=="string"){let s=r.event_id;return(typeof s!="string"||s==="")&&(s=void 0),{roomId:i,eventId:s}}}}return null}updateThirdPartyTokenCache(e){if(!e.getContent().third_party_invite)return;const t=(e.getContent().third_party_invite.signed||{}).token;!t||!this.getStateEvents(ie.RoomThirdPartyInvite,t)||(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){const r=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],r){const s=Hl(r),o=this.displayNameToUserIds.get(s);if(o){const a=o.filter(c=>c!==e);this.displayNameToUserIds.set(s,a)}}this.userIdsToDisplayNames[e]=t;const i=t&&Hl(t);if(i){const s=this.displayNameToUserIds.get(i)??[];s.push(e),this.displayNameToUserIds.set(i,s)}}}function F5(n){return typeof n=="string"&&!!n&&n!=="undefined"&&n!=="null"||typeof n=="number"}class pv{constructor(e={}){this.rooms={},this.users={},this.syncToken=null,this.filters=new _c(()=>new Map),this.accountData=new Map,this.oobMembers=new Map,this.pendingEvents={},this.pendingToDeviceBatches=[],this.nextToDeviceBatchId=0,this.onRoomMember=(t,r,i)=>{var o;if(i.membership===We.Invite)return;const s=this.users[i.userId]||((o=this.createUser)==null?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(It.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(It.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,r,i){}storeFilter(e){!(e!=null&&e.userId)||!(e!=null&&e.filterId)||this.filters.getOrCreate(e.userId).set(e.filterId,e)}getFilter(e,t){var r;return((r=this.filters.get(e))==null?void 0:r.get(t))||null}getFilterIdByName(e){if(!this.localStorage)return null;const t="mxjssdk_memory_filter_"+e;try{const r=this.localStorage.getItem(t);if(F5(r))return r}catch{}return null}setFilterIdByName(e,t){if(!this.localStorage)return;const r="mxjssdk_memory_filter_"+e;try{F5(t)?this.localStorage.setItem(r,t):this.localStorage.removeItem(r)}catch{}}storeAccountDataEvents(e){e.forEach(t=>{!Object.keys(t.getContent()).length?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 _c(()=>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()}async getPendingEvents(e){return this.pendingEvents[e]??[]}async setPendingEvents(e,t){this.pendingEvents[e]=t}saveToDeviceBatches(e){for(const t of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:t.eventType,txnId:t.txnId,batch:t.batch});return Promise.resolve()}async getOldestToDeviceBatch(){return this.pendingToDeviceBatches.length===0?null:this.pendingToDeviceBatches[0]}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter(t=>t.id!==e),Promise.resolve()}async destroy(){}}var rB=(n=>(n.ToWidget="toWidget",n.FromWidget="fromWidget",n))(rB||{});function Goe(n){if(n==="toWidget")return"fromWidget";if(n==="fromWidget")return"toWidget";throw new Error("Invalid direction")}var wl=(n=>(n.MSC2762="org.matrix.msc2762",n.MSC2871="org.matrix.msc2871",n.MSC2873="org.matrix.msc2873",n.MSC2931="org.matrix.msc2931",n.MSC2974="org.matrix.msc2974",n.MSC2876="org.matrix.msc2876",n.MSC3819="org.matrix.msc3819",n.MSC3846="town.robin.msc3846",n.MSC3869="org.matrix.msc3869",n.MSC3973="org.matrix.msc3973",n.MSC4039="org.matrix.msc4039",n))(wl||{});const qoe=["0.0.1","0.0.2","org.matrix.msc2762","org.matrix.msc2871","org.matrix.msc2873","org.matrix.msc2931","org.matrix.msc2974","org.matrix.msc2876","org.matrix.msc3819","town.robin.msc3846","org.matrix.msc3869","org.matrix.msc3973","org.matrix.msc4039"];class Koe extends aw.EventEmitter{constructor(e,t,r,i){super(),this.sendDirection=e,this.initialWidgetId=t,this.transportWindow=r,this.inboundWindow=i,this.strictOriginCheck=!1,this.targetOrigin="*",this.timeoutSeconds=10,this._ready=!1,this._widgetId=null,this.outboundRequests=new Map,this.stopController=new AbortController,this._widgetId=t}get ready(){return this._ready}get widgetId(){return this._widgetId||null}get nextRequestId(){const e=`widgetapi-${Date.now()}`;let t=0,r=e;for(;this.outboundRequests.has(r);)r=`${e}-${t++}`;return this.outboundRequests.set(r,null),r}sendInternal(e){console.log(`[PostmessageTransport] Sending object to ${this.targetOrigin}: `,e),this.transportWindow.postMessage(e,this.targetOrigin)}reply(e,t){return this.sendInternal({...e,response:t})}send(e,t){return this.sendComplete(e,t).then(r=>r.response)}sendComplete(e,t){if(!this.ready||!this.widgetId)return Promise.reject(new Error("Not ready or unknown widget ID"));const r={api:this.sendDirection,widgetId:this.widgetId,requestId:this.nextRequestId,action:e,data:t};return e===hr.UpdateVisibility&&(r.visible=t.visible),new Promise((i,s)=>{const o=h=>{u(),i(h)},a=h=>{u(),s(h)},c=setTimeout(()=>a(new Error("Request timed out")),(this.timeoutSeconds||1)*1e3),l=()=>a(new Error("Transport stopped"));this.stopController.signal.addEventListener("abort",l);const u=()=>{this.outboundRequests.delete(r.requestId),clearTimeout(c),this.stopController.signal.removeEventListener("abort",l)};this.outboundRequests.set(r.requestId,{request:r,resolve:o,reject:a}),this.sendInternal(r)})}start(){this.inboundWindow.addEventListener("message",e=>{this.handleMessage(e)}),this._ready=!0}stop(){this._ready=!1,this.stopController.abort()}handleMessage(e){if(this.stopController.signal.aborted||!e.data||this.strictOriginCheck&&e.origin!==window.origin)return;const t=e.data;if(!(!t.action||!t.requestId||!t.widgetId))if(t.response){if(t.api!==this.sendDirection)return;this.handleResponse(t)}else{const r=t;if(r.api!==Goe(this.sendDirection))return;this.handleRequest(r)}}handleRequest(e){if(this.widgetId){if(this.widgetId!==e.widgetId)return}else this._widgetId=e.widgetId;this.emit("message",new CustomEvent("message",{detail:e}))}handleResponse(e){if(e.widgetId!==this.widgetId)return;const t=this.outboundRequests.get(e.requestId);if(t)if(zoe(e.response)){const{message:r,...i}=e.response.error;t.reject(new jb(r,i))}else t.resolve(e)}}var hr=(n=>(n.SupportedApiVersions="supported_api_versions",n.Capabilities="capabilities",n.NotifyCapabilities="notify_capabilities",n.ThemeChange="theme_change",n.LanguageChange="language_change",n.TakeScreenshot="screenshot",n.UpdateVisibility="visibility",n.OpenIDCredentials="openid_credentials",n.WidgetConfig="widget_config",n.CloseModalWidget="close_modal",n.ButtonClicked="button_clicked",n.SendEvent="send_event",n.SendToDevice="send_to_device",n.UpdateTurnServers="update_turn_servers",n))(hr||{}),Sn=(n=>(n.SupportedApiVersions="supported_api_versions",n.ContentLoaded="content_loaded",n.SendSticker="m.sticker",n.UpdateAlwaysOnScreen="set_always_on_screen",n.GetOpenIDCredentials="get_openid",n.CloseModalWidget="close_modal",n.OpenModalWidget="open_modal",n.SetModalButtonEnabled="set_button_enabled",n.SendEvent="send_event",n.SendToDevice="send_to_device",n.WatchTurnServers="watch_turn_servers",n.UnwatchTurnServers="unwatch_turn_servers",n.BeeperReadRoomAccountData="com.beeper.read_room_account_data",n.MSC2876ReadEvents="org.matrix.msc2876.read_events",n.MSC2931Navigate="org.matrix.msc2931.navigate",n.MSC2974RenegotiateCapabilities="org.matrix.msc2974.request_capabilities",n.MSC3869ReadRelations="org.matrix.msc3869.read_relations",n.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",n.MSC4039GetMediaConfigAction="org.matrix.msc4039.get_media_config",n.MSC4039UploadFileAction="org.matrix.msc4039.upload_file",n.MSC4039DownloadFileAction="org.matrix.msc4039.download_file",n.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",n))(Sn||{}),ef=(n=>(n.Allowed="allowed",n.Blocked="blocked",n.PendingUserConfirmation="request",n))(ef||{}),iB=(n=>(n.Custom="m.custom",n.JitsiMeet="m.jitsi",n.Stickerpicker="m.stickerpicker",n))(iB||{}),sB=(n=>(n.Close="m.close",n))(sB||{}),aa=(n=>(n.Send="send",n.Receive="receive",n))(aa||{});class ai{constructor(e,t,r,i,s){this.direction=e,this.eventType=t,this.kind=r,this.keyStr=i,this.raw=s}matchesAsStateEvent(e,t,r){return this.kind!=="state_event"||this.direction!==e||this.eventType!==t?!1:this.keyStr===null||this.keyStr===r}matchesAsToDeviceEvent(e,t){return!(this.kind!=="to_device"||this.direction!==e||this.eventType!==t)}matchesAsRoomEvent(e,t,r=null){if(this.kind!=="event"||this.direction!==e||this.eventType!==t)return!1;if(this.eventType==="m.room.message"){if(this.keyStr===null||this.keyStr===r)return!0}else return!0;return!1}matchesAsRoomAccountData(e,t){return!(this.kind!=="room_account"||this.direction!==e||this.eventType!==t)}static forStateEvent(e,t,r){t=t.replace(/#/g,"\\#"),r=r!=null?`#${r}`:"";const i=`org.matrix.msc2762.${e}.state_event:${t}${r}`;return ai.findEventCapabilities([i])[0]}static forToDeviceEvent(e,t){const r=`org.matrix.msc3819.${e}.to_device:${t}`;return ai.findEventCapabilities([r])[0]}static forRoomEvent(e,t){const r=`org.matrix.msc2762.${e}.event:${t}`;return ai.findEventCapabilities([r])[0]}static forRoomMessageEvent(e,t){t=t??"";const r=`org.matrix.msc2762.${e}.event:m.room.message#${t}`;return ai.findEventCapabilities([r])[0]}static forRoomAccountData(e,t){const r=`com.beeper.capabilities.${e}.room_account_data:${t}`;return ai.findEventCapabilities([r])[0]}static findEventCapabilities(e){const t=[];for(const r of e){let i=null,s,o=null;if(r.startsWith("org.matrix.msc2762.send.event:")?(i="send",o="event",s=r.substring(30)):r.startsWith("org.matrix.msc2762.send.state_event:")?(i="send",o="state_event",s=r.substring(36)):r.startsWith("org.matrix.msc3819.send.to_device:")?(i="send",o="to_device",s=r.substring(34)):r.startsWith("org.matrix.msc2762.receive.event:")?(i="receive",o="event",s=r.substring(33)):r.startsWith("org.matrix.msc2762.receive.state_event:")?(i="receive",o="state_event",s=r.substring(39)):r.startsWith("org.matrix.msc3819.receive.to_device:")?(i="receive",o="to_device",s=r.substring(37)):r.startsWith("com.beeper.capabilities.receive.room_account_data:")&&(i="receive",o="room_account",s=r.substring(50)),i===null||o===null||s===void 0)continue;const a=s.startsWith("m.room.message#")||o==="state_event";let c=null;if(s.includes("#")&&a){const l=s.split("#"),u=l.findIndex(h=>!h.endsWith("\\"));s=l.slice(0,u+1).map(h=>h.endsWith("\\")?h.substring(0,h.length-1):h).join("#"),c=l.slice(u+1).join("#")}t.push(new ai(i,s,o,c,r))}return t}}var Xu=(n=>(n.AnyRoom="*",n))(Xu||{});const tw=class tw extends Error{constructor(e,t){super(e),this.data=t}};tw.prototype.name=tw.name;let jb=tw;class Woe extends aw.EventEmitter{constructor(e=null,t=null){if(super(),this.clientOrigin=t,this.capabilitiesFinished=!1,this.supportsMSC2974Renegotiate=!1,this.requestedCapabilities=[],this.turnServerWatchers=0,!window.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");this.transport=new Koe(rB.FromWidget,e,window.parent,window),this.transport.targetOrigin=t,this.transport.on("message",this.handleMessage.bind(this))}hasCapability(e){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(e):this.requestedCapabilities.includes(e)}requestCapability(e){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(e)}requestCapabilities(e){e.forEach(t=>this.requestCapability(t))}requestCapabilityForRoomTimeline(e){this.requestCapability(`org.matrix.msc2762.timeline:${e}`)}requestCapabilityToSendState(e,t){this.requestCapability(ai.forStateEvent(aa.Send,e,t).raw)}requestCapabilityToReceiveState(e,t){this.requestCapability(ai.forStateEvent(aa.Receive,e,t).raw)}requestCapabilityToSendToDevice(e){this.requestCapability(ai.forToDeviceEvent(aa.Send,e).raw)}requestCapabilityToReceiveToDevice(e){this.requestCapability(ai.forToDeviceEvent(aa.Receive,e).raw)}requestCapabilityToSendEvent(e){this.requestCapability(ai.forRoomEvent(aa.Send,e).raw)}requestCapabilityToReceiveEvent(e){this.requestCapability(ai.forRoomEvent(aa.Receive,e).raw)}requestCapabilityToSendMessage(e){this.requestCapability(ai.forRoomMessageEvent(aa.Send,e).raw)}requestCapabilityToReceiveMessage(e){this.requestCapability(ai.forRoomMessageEvent(aa.Receive,e).raw)}requestCapabilityToReceiveRoomAccountData(e){this.requestCapability(ai.forRoomAccountData(aa.Receive,e).raw)}requestOpenIDConnectToken(){return new Promise((e,t)=>{this.transport.sendComplete(Sn.GetOpenIDCredentials,{}).then(r=>{const i=r.response;if(i.state===ef.Allowed)e(i);else if(i.state===ef.Blocked)t(new Error("User declined to verify their identity"));else if(i.state===ef.PendingUserConfirmation){const s=o=>{o.preventDefault();const a=o.detail;a.data.original_request_id===r.requestId&&(a.data.state===ef.Allowed?(e(a.data),this.transport.reply(a,{})):a.data.state===ef.Blocked?(t(new Error("User declined to verify their identity")),this.transport.reply(a,{})):(t(new Error("Invalid state on reply: "+i.state)),this.transport.reply(a,{error:{message:"Invalid state"}})),this.off(`action:${hr.OpenIDCredentials}`,s))};this.on(`action:${hr.OpenIDCredentials}`,s)}else t(new Error("Invalid state: "+i.state))}).catch(t)})}updateRequestedCapabilities(){return this.transport.send(Sn.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}sendContentLoaded(){return this.transport.send(Sn.ContentLoaded,{}).then()}sendSticker(e){return this.transport.send(Sn.SendSticker,e).then()}setAlwaysOnScreen(e){return this.transport.send(Sn.UpdateAlwaysOnScreen,{value:e}).then(t=>t.success)}openModalWidget(e,t,r=[],i={},s=iB.Custom){return this.transport.send(Sn.OpenModalWidget,{type:s,url:e,name:t,buttons:r,data:i}).then()}closeModalWidget(e={}){return this.transport.send(Sn.CloseModalWidget,e).then()}sendRoomEvent(e,t,r,i,s){return this.sendEvent(e,void 0,t,r,i,s)}sendStateEvent(e,t,r,i,s,o){return this.sendEvent(e,t,r,i,s,o)}sendEvent(e,t,r,i,s,o){return this.transport.send(Sn.SendEvent,{type:e,content:r,...t!==void 0&&{state_key:t},...i!==void 0&&{room_id:i},...s!==void 0&&{delay:s},...o!==void 0&&{parent_delay_id:o}})}updateDelayedEvent(e,t){return this.transport.send(Sn.MSC4157UpdateDelayedEvent,{delay_id:e,action:t})}sendToDevice(e,t,r){return this.transport.send(Sn.SendToDevice,{type:e,encrypted:t,messages:r})}readRoomAccountData(e,t){const r={type:e};return t&&(t.includes(Xu.AnyRoom)?r.room_ids=Xu.AnyRoom:r.room_ids=t),this.transport.send(Sn.BeeperReadRoomAccountData,r).then(i=>i.events)}readRoomEvents(e,t,r,i,s){const o={type:e,msgtype:r};return t!==void 0&&(o.limit=t),i&&(i.includes(Xu.AnyRoom)?o.room_ids=Xu.AnyRoom:o.room_ids=i),s&&(o.since=s),this.transport.send(Sn.MSC2876ReadEvents,o).then(a=>a.events)}async readEventRelations(e,t,r,i,s,o,a,c){if(!(await this.getClientVersions()).includes(wl.MSC3869))throw new Error("The read_relations action is not supported by the client.");const u={event_id:e,rel_type:r,event_type:i,room_id:t,to:a,from:o,limit:s,direction:c};return this.transport.send(Sn.MSC3869ReadRelations,u)}readStateEvents(e,t,r,i){const s={type:e,state_key:r===void 0?!0:r};return t!==void 0&&(s.limit=t),i&&(i.includes(Xu.AnyRoom)?s.room_ids=Xu.AnyRoom:s.room_ids=i),this.transport.send(Sn.MSC2876ReadEvents,s).then(o=>o.events)}setModalButtonEnabled(e,t){if(e===sB.Close)throw new Error("The close button cannot be disabled");return this.transport.send(Sn.SetModalButtonEnabled,{button:e,enabled:t}).then()}navigateTo(e){if(!e||!e.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(Sn.MSC2931Navigate,{uri:e}).then()}async*getTurnServers(){let e;const t=async r=>{r.preventDefault(),e(r.detail.data),await this.transport.reply(r.detail,{})};if(this.on(`action:${hr.UpdateTurnServers}`,t),this.turnServerWatchers===0)try{await this.transport.send(Sn.WatchTurnServers,{})}catch(r){throw this.off(`action:${hr.UpdateTurnServers}`,t),r}this.turnServerWatchers++;try{for(;;)yield await new Promise(r=>e=r)}finally{this.off(`action:${hr.UpdateTurnServers}`,t),this.turnServerWatchers--,this.turnServerWatchers===0&&await this.transport.send(Sn.UnwatchTurnServers,{})}}async searchUserDirectory(e,t){if(!(await this.getClientVersions()).includes(wl.MSC3973))throw new Error("The user_directory_search action is not supported by the client.");const i={search_term:e,limit:t};return this.transport.send(Sn.MSC3973UserDirectorySearch,i)}async getMediaConfig(){if(!(await this.getClientVersions()).includes(wl.MSC4039))throw new Error("The get_media_config action is not supported by the client.");const t={};return this.transport.send(Sn.MSC4039GetMediaConfigAction,t)}async uploadFile(e){if(!(await this.getClientVersions()).includes(wl.MSC4039))throw new Error("The upload_file action is not supported by the client.");const r={file:e};return this.transport.send(Sn.MSC4039UploadFileAction,r)}async downloadFile(e){if(!(await this.getClientVersions()).includes(wl.MSC4039))throw new Error("The download_file action is not supported by the client.");const r={content_uri:e};return this.transport.send(Sn.MSC4039DownloadFileAction,r)}start(){this.transport.start(),this.getClientVersions().then(e=>{e.includes(wl.MSC2974)&&(this.supportsMSC2974Renegotiate=!0)})}handleMessage(e){const t=new CustomEvent(`action:${e.detail.action}`,{detail:e.detail,cancelable:!0});if(this.emit(`action:${e.detail.action}`,t),!t.defaultPrevented)switch(e.detail.action){case hr.SupportedApiVersions:return this.replyVersions(e.detail);case hr.Capabilities:return this.handleCapabilities(e.detail);case hr.UpdateVisibility:return this.transport.reply(e.detail,{});case hr.NotifyCapabilities:return this.transport.reply(e.detail,{});default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}replyVersions(e){this.transport.reply(e,{supported_versions:qoe})}getClientVersions(){return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(Sn.SupportedApiVersions,{}).then(e=>(this.cachedClientVersions=e.supported_versions,e.supported_versions)).catch(e=>(console.warn("non-fatal error getting supported client versions: ",e),[]))}handleCapabilities(e){return this.capabilitiesFinished?this.transport.reply(e,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then(t=>(t.includes(wl.MSC2871)?this.once(`action:${hr.NotifyCapabilities}`,r=>{this.approvedCapabilities=r.detail.data.approved,this.emit("ready")}):this.emit("ready"),this.capabilitiesFinished=!0,this.transport.reply(e,{capabilities:this.requestedCapabilities})))}}var xg=(n=>(n.Screenshots="m.capability.screenshot",n.StickerSending="m.sticker",n.AlwaysOnScreen="m.always_on_screen",n.RequiresClient="io.element.requires_client",n.MSC2931Navigate="org.matrix.msc2931.navigate",n.MSC3846TurnServers="town.robin.msc3846.turn_servers",n.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",n.MSC4039UploadFile="org.matrix.msc4039.upload_file",n.MSC4039DownloadFile="org.matrix.msc4039.download_file",n.MSC4157SendDelayedEvent="org.matrix.msc4157.send.delayed_event",n.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",n))(xg||{});function zoe(n){const e=n.error;return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}var oB=(n=>(n.PendingEventsChanged="PendingEvent.pendingEventsChanged",n))(oB||{});class aB extends dv{constructor(e,t,r,i,s){var c,l,u,h,p,m,v,g,S,b,R,k;super(i),this.widgetApi=e,this.capabilities=t,this.roomId=r,this.syncState=null,this.pendingSendingEventsTxId=[],this.eventEmitter=new Yn,this.updateTxId=async I=>{var T,C;if(I.getSender()===this.getUserId()&&this.pendingSendingEventsTxId.some(P=>I.getType()===P.type)){let P=(T=this.pendingSendingEventsTxId.find(O=>O.id===I.getId()))==null?void 0:T.txId;for(;!P&&this.pendingSendingEventsTxId.length>0;)await new Promise(O=>this.eventEmitter.once("PendingEvent.pendingEventsChanged",()=>O())),P=(C=this.pendingSendingEventsTxId.find(O=>O.id===I.getId()))==null?void 0:C.txId;P&&(I.setTxnId(P),I.setUnsigned({...I.getUnsigned(),transaction_id:P})),this.pendingSendingEventsTxId=this.pendingSendingEventsTxId.filter(O=>O.id!==I.getId()),this.pendingSendingEventsTxId.length===0&&this.eventEmitter.emit("PendingEvent.pendingEventsChanged")}},this.onEvent=async I=>{if(I.preventDefault(),I.detail.data.room_id===this.roomId){const T=new Ji(I.detail.data);await this.updateTxId(T),this.syncApi instanceof rd?await this.syncApi.injectRoomEvents(this.room,[],void 0,[T]):await this.syncApi.injectRoomEvents(this.room,[],[T]),this.emit(Ge.Event,T),this.setSyncState(Pr.Syncing),M.info(`Received event ${T.getId()} ${T.getType()} ${T.getStateKey()}`)}else{const{event_id:T,room_id:C}=I.detail.data;M.info(`Received event ${T} for a different room ${C}; discarding`)}await this.ack(I)},this.onToDevice=async I=>{I.preventDefault();const T=new Ji({type:I.detail.data.type,sender:I.detail.data.sender,content:I.detail.data.content});I.detail.data.encrypted&&T.makeEncrypted(ie.RoomMessageEncrypted,{},"",""),this.emit(Ge.ToDeviceEvent,T),this.setSyncState(Pr.Syncing),await this.ack(I)};const o=this.widgetApi.transport.send.bind(this.widgetApi.transport);this.widgetApi.transport.send=async(I,T)=>{try{return await o(I,T)}catch(C){U5(C)}};const a=this.widgetApi.transport.sendComplete.bind(this.widgetApi.transport);this.widgetApi.transport.sendComplete=async(I,T)=>{try{return await a(I,T)}catch(C){U5(C)}},this.widgetApiReady=new Promise(I=>this.widgetApi.once("ready",I)),((c=t.sendEvent)!=null&&c.length||(l=t.receiveEvent)!=null&&l.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||t.receiveMessage===!0||Array.isArray(t.receiveMessage)&&t.receiveMessage.length||(u=t.sendState)!=null&&u.length||(h=t.receiveState)!=null&&h.length)&&e.requestCapabilityForRoomTimeline(r),(p=t.sendEvent)==null||p.forEach(I=>e.requestCapabilityToSendEvent(I)),(m=t.receiveEvent)==null||m.forEach(I=>e.requestCapabilityToReceiveEvent(I)),t.sendMessage===!0?e.requestCapabilityToSendMessage():Array.isArray(t.sendMessage)&&t.sendMessage.forEach(I=>e.requestCapabilityToSendMessage(I)),t.receiveMessage===!0?e.requestCapabilityToReceiveMessage():Array.isArray(t.receiveMessage)&&t.receiveMessage.forEach(I=>e.requestCapabilityToReceiveMessage(I)),(v=t.sendState)==null||v.forEach(({eventType:I,stateKey:T})=>e.requestCapabilityToSendState(I,T)),(g=t.receiveState)==null||g.forEach(({eventType:I,stateKey:T})=>e.requestCapabilityToReceiveState(I,T)),(S=t.sendToDevice)==null||S.forEach(I=>e.requestCapabilityToSendToDevice(I)),(b=t.receiveToDevice)==null||b.forEach(I=>e.requestCapabilityToReceiveToDevice(I)),t.sendDelayedEvents&&((R=t.sendEvent)!=null&&R.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||(k=t.sendState)!=null&&k.length)&&e.requestCapability(xg.MSC4157SendDelayedEvent),t.updateDelayedEvents&&e.requestCapability(xg.MSC4157UpdateDelayedEvent),t.turnServers&&e.requestCapability(xg.MSC3846TurnServers),e.on(`action:${hr.SendEvent}`,this.onEvent),e.on(`action:${hr.SendToDevice}`,this.onToDevice),e.start(),s&&e.sendContentLoaded()}async startClient(e={}){var r;this.lifecycle=new AbortController;const t=this.getUserId();t&&this.store.storeUser(new bc(t)),e.slidingSync?this.syncApi=new j$(e.slidingSync,this,e,this.buildSyncApiOptions()):this.syncApi=new rd(this,e,this.buildSyncApiOptions()),this.room=this.syncApi.createRoom(this.roomId),this.store.storeRoom(this.room),await this.widgetApiReady,await Promise.all(((r=this.capabilities.receiveState)==null?void 0:r.map(async({eventType:i,stateKey:s})=>{const a=(await this.widgetApi.readStateEvents(i,void 0,s,[this.roomId])).map(c=>new Ji(c));this.syncApi instanceof rd?await this.syncApi.injectRoomEvents(this.room,void 0,a):await this.syncApi.injectRoomEvents(this.room,a),a.forEach(c=>{this.emit(Ge.Event,c),M.info(`Backfilled event ${c.getId()} ${c.getType()} ${c.getStateKey()}`)})}))??[]),e.clientWellKnownPollPeriod!==void 0&&(this.clientWellKnownIntervalID=setInterval(()=>{this.fetchClientWellKnown()},1e3*e.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.setSyncState(Pr.Syncing),M.info("Finished backfilling events"),this.matrixRTC.start(),this.capabilities.turnServers&&this.watchTurnServers()}stopClient(){this.widgetApi.off(`action:${hr.SendEvent}`,this.onEvent),this.widgetApi.off(`action:${hr.SendToDevice}`,this.onToDevice),super.stopClient(),this.lifecycle.abort()}async joinRoom(e){if(e===this.roomId)return this.room;throw new Error(`Unknown room: ${e}`)}async encryptAndSendEvent(e,t,r){const i=t.event.redacts?{...t.getContent(),redacts:t.event.redacts}:t.getContent();if(r){const a=await this.widgetApi.sendRoomEvent(t.getType(),i,e.roomId,"delay"in r?r.delay:void 0,"parent_delay_id"in r?r.parent_delay_id:void 0).catch(na);return this.validateSendDelayedEventResponse(a)}const s=t.getTxnId();s&&this.pendingSendingEventsTxId.push({type:t.getType(),id:void 0,txId:s});let o;try{o=await this.widgetApi.sendRoomEvent(t.getType(),i,e.roomId).catch(na)}catch(a){throw this.updatePendingEventStatus(e,t,rt.NOT_SENT),a}return e.updatePendingEvent(t,rt.SENT,o.event_id),this.pendingSendingEventsTxId.forEach(a=>{a.txId===s&&(a.id=o.event_id)}),this.eventEmitter.emit("PendingEvent.pendingEventsChanged"),{event_id:o.event_id}}async sendStateEvent(e,t,r,i=""){const s=await this.widgetApi.sendStateEvent(t,i,r,e).catch(na);if(s.event_id===void 0)throw new Error("'event_id' absent from response to an event request");return{event_id:s.event_id}}async _unstable_sendDelayedStateEvent(e,t,r,i,s=""){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","sendDelayedStateEvent");const o=await this.widgetApi.sendStateEvent(r,s,i,e,"delay"in t?t.delay:void 0,"parent_delay_id"in t?t.parent_delay_id:void 0).catch(na);return this.validateSendDelayedEventResponse(o)}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}}async _unstable_updateDelayedEvent(e,t){if(!await this.doesServerSupportUnstableFeature(ga))throw new Nl("Server does not support the delayed events API","updateDelayedEvent");return await this.widgetApi.updateDelayedEvent(e,t).catch(na),{}}async sendToDevice(e,t){return await this.widgetApi.sendToDevice(e,!1,td(t)).catch(na),{}}async getOpenIdToken(){const e=await this.widgetApi.requestOpenIDConnectToken().catch(na);return{access_token:e.access_token,expires_in:e.expires_in,matrix_server_name:e.matrix_server_name,token_type:e.token_type}}async queueToDevice({eventType:e,batch:t}){const r=new _c(()=>new Map);for(const{userId:i,deviceId:s,payload:o}of t)r.getOrCreate(i).set(s,o);await this.widgetApi.sendToDevice(e,!1,td(r)).catch(na)}async encryptAndSendToDevices(e,t){const r=new _c(()=>new Map);for(const{userId:i,deviceId:s}of e)r.getOrCreate(i).set(s,t);await this.widgetApi.sendToDevice(t.type,!0,td(r)).catch(na)}async sendToDeviceViaWidgetApi(e,t,r){await this.widgetApi.sendToDevice(e,t,td(r)).catch(na)}async checkTurnServers(){return this.turnServers.length>0}getSyncState(){return this.syncState}setSyncState(e){const t=this.syncState;this.syncState=e,this.emit(Ge.Sync,e,t)}async ack(e){await this.widgetApi.transport.reply(e.detail,{})}async watchTurnServers(){const e=this.widgetApi.getTurnServers(),t=()=>{e.return(void 0)};this.lifecycle.signal.addEventListener("abort",t);try{for await(const r of e)this.turnServers=[{urls:r.uris,username:r.username,credential:r.password}],this.emit(Ge.TurnServers,this.turnServers),M.log(`Received TURN server: ${r.uris}`)}catch(r){M.warn("Error watching TURN servers",r)}finally{this.lifecycle.signal.removeEventListener("abort",t)}}}function U5(n){throw n instanceof jb&&n.data.matrix_api_error?mn.fromWidgetApiErrorData(n.data.matrix_api_error):n}function na(n){throw n instanceof Error&&n.message==="Request timed out"?new Vd("widget api timeout"):n}class Yoe{constructor(){this.unthreadedReadReceipts=new Map,this.threadedReadReceipts=new _c(()=>new Map)}setUnthreaded(e,t){this.unthreadedReadReceipts.set(e,t)}setThreaded(e,t,r){this.threadedReadReceipts.getOrCreate(e).set(t,r)}allUnthreaded(){return this.unthreadedReadReceipts.entries()}*allThreaded(){for(const e of this.threadedReadReceipts.values())for(const t of e.entries())yield t}consumeEphemeralEvents(e){e==null||e.forEach(t=>{t.type!==ie.Receipt||!t.content||Object.keys(t.content).forEach(r=>{Object.entries(t.content[r]).forEach(([i,s])=>{if(eP(i))for(const o of Object.keys(s)){const a=t.content[r][i][o],c={data:t.content[r][i][o],type:i,eventId:r};a.thread_id?this.setThreaded(a.thread_id,o,c):this.setUnthreaded(o,c)}})})})}buildAccumulatedReceiptEvent(e){const t={type:ie.Receipt,room_id:e,content:{}},r=new _c(()=>new _c(()=>new Map));for(const[i,s]of this.allUnthreaded())r.getOrCreate(s.eventId).getOrCreate(s.type).set(i,s.data);for(const[i,s]of this.allThreaded())r.getOrCreate(s.eventId).getOrCreate(s.type).set(i,s.data);return t.content=td(r),r.size>0?t:null}}var cB=(n=>(n.Invite="invite",n.Leave="leave",n.Join="join",n.Knock="knock",n))(cB||{});function Xoe(n){return"_localTs"in n&&n._localTs!==void 0}class lB{constructor(e={}){this.opts=e,this.accountData={},this.inviteRooms={},this.knockRooms={},this.joinRooms={},this.nextBatch=null,this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e,t=!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,t=!1){e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach(r=>{this.accumulateRoom(r,"invite",e.rooms.invite[r],t)}),e.rooms.join&&Object.keys(e.rooms.join).forEach(r=>{this.accumulateRoom(r,"join",e.rooms.join[r],t)}),e.rooms.leave&&Object.keys(e.rooms.leave).forEach(r=>{this.accumulateRoom(r,"leave",e.rooms.leave[r],t)}),e.rooms.knock&&Object.keys(e.rooms.knock).forEach(r=>{this.accumulateRoom(r,"knock",e.rooms.knock[r],t)}))}accumulateRoom(e,t,r,i=!1){switch(t){case"invite":this.knockRooms[e]&&delete this.knockRooms[e],this.accumulateInviteState(e,r);break;case"knock":this.accumulateKnockState(e,r);break;case"join":this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,r,i);break;case"leave":this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:M.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!t.invite_state||!t.invite_state.events)return;if(!this.inviteRooms[e]){this.inviteRooms[e]={invite_state:t.invite_state};return}const r=this.inviteRooms[e];t.invite_state.events.forEach(i=>{let s=!1;for(let o=0;o<r.invite_state.events.length;o++){const a=r.invite_state.events[o];a.type===i.type&&a.state_key==i.state_key&&(r.invite_state.events[o]=i,s=!0)}s||r.invite_state.events.push(i)})}accumulateKnockState(e,t){if(!t.knock_state||!t.knock_state.events)return;if(!this.knockRooms[e]){this.knockRooms[e]={knock_state:t.knock_state};return}const r=this.knockRooms[e];t.knock_state.events.forEach(i=>{let s=!1;for(let o=0;o<r.knock_state.events.length;o++){const a=r.knock_state.events[o];a.type===i.type&&a.state_key==i.state_key&&(r.knock_state.events[o]=i,s=!0)}s||r.knock_state.events.push(i)})}accumulateJoinState(e,t,r=!1){var s,o,a,c,l,u,h;this.joinRooms[e]||(this.joinRooms[e]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_unreadThreadNotifications:{},_summary:{},_receipts:new Yoe});const i=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach(p=>{i._accountData[p.type]=p}),t.unread_notifications&&(i._unreadNotifications=t.unread_notifications),i._unreadThreadNotifications=t[iv.stable]??t[iv.unstable]??void 0,t.summary){const p="m.heroes",m="m.invited_member_count",v="m.joined_member_count",g=i._summary,S=t.summary;g[p]=S[p]??g[p],g[v]=S[v]??g[v],g[m]=S[m]??g[m]}if(i._receipts.consumeEphemeralEvents((s=t.ephemeral)==null?void 0:s.events),t.timeline&&t.timeline.limited&&(i._timeline=[]),(a=(o=t.state)==null?void 0:o.events)==null||a.forEach(p=>{o1(i._currentState,p)}),(l=(c=t["org.matrix.msc4222.state_after"])==null?void 0:c.events)==null||l.forEach(p=>{o1(i._currentState,p)}),(h=(u=t.timeline)==null?void 0:u.events)==null||h.forEach((p,m)=>{var g;t["org.matrix.msc4222.state_after"]||o1(i._currentState,p);let v;if(r)v=p;else{v=Object.assign({},p),v.unsigned!==void 0&&(v.unsigned=Object.assign({},v.unsigned));const S=(g=p.unsigned)==null?void 0:g.age;S!==void 0&&(v._localTs=Date.now()-S)}i._timeline.push({event:v,token:m===0?t.timeline.prev_batch??null:null})}),i._timeline.length>this.opts.maxTimelineEntries){const p=i._timeline.length-this.opts.maxTimelineEntries;for(let m=p;m<i._timeline.length;m++)if(i._timeline[m].token){i._timeline=i._timeline.slice(m,i._timeline.length);break}}}getJSON(e=!1){const 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=>{const s=this.joinRooms[i],o={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},"org.matrix.msc4222.state_after":{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:s._unreadNotifications,unread_thread_notifications:s._unreadThreadNotifications,summary:s._summary};Object.keys(s._accountData).forEach(l=>{o.account_data.events.push(s._accountData[l])});const a=s._receipts.buildAccumulatedReceiptEvent(i);a&&o.ephemeral.events.push(a),s._timeline.forEach(l=>{if(!o.timeline.prev_batch){if(!l.token)return;o.timeline.prev_batch=l.token}let u;!e&&Xoe(l.event)?(u=Object.assign({},l.event),u.unsigned!==void 0&&(u.unsigned=Object.assign({},u.unsigned)),delete u._localTs,u.unsigned=u.unsigned||{},u.unsigned.age=Date.now()-l.event._localTs):u=l.event,o.timeline.events.push(u)});const c=Object.create(null);for(let l=o.timeline.events.length-1;l>=0;l--){const u=o.timeline.events[l];if(u.state_key===null||u.state_key===void 0)continue;const h=iw(u);h.unsigned&&(h.unsigned.prev_content&&(h.content=h.unsigned.prev_content),h.unsigned.prev_sender&&(h.sender=h.unsigned.prev_sender)),o1(c,h)}Object.keys(s._currentState).forEach(l=>{Object.keys(s._currentState[l]).forEach(u=>{let h=s._currentState[l][u];o["org.matrix.msc4222.state_after"].events.push(h),c[l]&&c[l][u]&&(h=c[l][u]),o.state.events.push(h)})}),t.join[i]=o});const r=[];return Object.keys(this.accountData).forEach(i=>{r.push(this.accountData[i])}),{nextBatch:this.nextBatch,roomsData:t,accountData:r}}getNextBatchToken(){return this.nextBatch}}function o1(n,e){e.state_key===null||e.state_key===void 0||!e.type||(n[e.type]||(n[e.type]=Object.create(null)),n[e.type][e.state_key]=e)}var uB=(n=>(n[n.Blocked=-1]="Blocked",n[n.Unverified=0]="Unverified",n[n.Verified=1]="Verified",n))(uB||{});class Joe{constructor(e){this.dehydrated=!1,this.deviceId=e.deviceId,this.userId=e.userId,this.algorithms=e.algorithms,this.keys=e.keys,this.verified=e.verified||0,this.signatures=e.signatures||new Map,this.displayName=e.displayName,this.dehydrated=!!e.dehydrated}getFingerprint(){return this.keys.get(`ed25519:${this.deviceId}`)}getIdentityKey(){return this.keys.get(`curve25519:${this.deviceId}`)}}const j5=function(){},Zoe=10;class Qoe{constructor(e,t,r={}){var i;this.client=e,this.timelineSet=t,this.eventCount=0,this.windowLimit=r.windowLimit||1e3,(i=t.room)==null||i.on(Xe.Timeline,this.onTimelineEvent.bind(this))}load(e,t=20){const r=i=>{if(!i)throw new Error("No timeline given to initFields");let s;const o=i.getEvents();if(!e)s=o.length;else if(s=o.findIndex(l=>l.getId()===e),s<0)throw new Error("getEventTimeline result didn't include requested event");const a=Math.min(o.length,s+Math.ceil(t/2)),c=Math.max(0,a-t);this.start=new uk(i,c-i.getBaseIndex()),this.end=new uk(i,a-i.getBaseIndex()),this.eventCount=a-c};return this.timelineSet.getTimelineForEvent(e)?(r(this.timelineSet.getTimelineForEvent(e)),Promise.resolve()):e?this.client.getEventTimeline(this.timelineSet,e).then(r):(r(this.timelineSet.getLiveTimeline()),Promise.resolve())}getTimelineIndex(e){if(e==Be.BACKWARDS)return this.start??null;if(e==Be.FORWARDS)return this.end??null;throw new Error("Invalid direction '"+e+"'")}extend(e,t){const r=this.getTimelineIndex(e);if(!r)return!1;const i=e==Be.BACKWARDS?r.retreat(t):r.advance(t);if(i){this.eventCount+=i,j5("TimelineWindow: increased cap by "+i+" (now "+this.eventCount+")");const s=this.eventCount-this.windowLimit;return s>0&&this.unpaginate(s,e!=Be.BACKWARDS),!0}return!1}onTimelineEvent(e,t,r,i){i&&this.onEventRemoved()}onEventRemoved(){const e=this.getEvents();e.length>0&&e[e.length-1]===void 0&&this.end&&this.end.index--}canPaginate(e){const t=this.getTimelineIndex(e);if(!t)return!1;if(e==Be.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;const r=t.timeline.getNeighbouringTimeline(e),i=t.timeline.getPaginationToken(e);return!!r||!!i}async paginate(e,t,r=!0,i=Zoe){const s=this.getTimelineIndex(e);if(!s)return!1;if(s.pendingPaginate)return s.pendingPaginate;if(this.extend(e,t))return!0;if(!r||i===0||!s.timeline.getPaginationToken(e))return!1;const a=this.client.paginateEventTimeline(s.timeline,{backwards:e==Be.BACKWARDS,limit:t}).finally(function(){s.pendingPaginate=void 0}).then(c=>c?this.paginate(e,t,!0,i-1):this.paginate(e,t,!1,0));return s.pendingPaginate=a,a}unpaginate(e,t){const r=t?this.start:this.end;if(!r)throw new Error(`Attempting to unpaginate startOfTimeline=${t} but don't have this direction`);if(e>this.eventCount||e<0)throw new Error(`Attemting to unpaginate ${e} events, but only have ${this.eventCount} in the timeline`);for(;e>0;){const i=t?r.advance(e):r.retreat(e);if(i<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=i,this.eventCount-=i,j5("TimelineWindow.unpaginate: dropped "+i+" (now "+this.eventCount+")")}}getEvents(){var r,i;if(!this.start)return[];const e=[];let t=this.start.timeline;for(;t;){const s=t.getEvents();let o=0,a=s.length;t===this.start.timeline&&(o=this.start.index+t.getBaseIndex()),t===((r=this.end)==null?void 0:r.timeline)&&(a=this.end.index+t.getBaseIndex());for(let c=o;c<a;c++)e.push(s[c]);if(t===((i=this.end)==null?void 0:i.timeline))break;t=t.getNeighbouringTimeline(Be.FORWARDS)}return e}}class uk{constructor(e,t){this.timeline=e,this.index=t}minIndex(){return this.timeline.getBaseIndex()*-1}maxIndex(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()}advance(e){if(!e)return 0;let 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;const r=this.timeline.getNeighbouringTimeline(e<0?Be.BACKWARDS:Be.FORWARDS);return r?(this.timeline=r,e<0?this.index=this.maxIndex():this.index=this.minIndex(),this.advance(e)):0}retreat(e){return this.advance(e*-1)*-1}}const Um="m.login.email.identity",$5="m.login.msisdn";var dB=(n=>(n.Password="m.login.password",n.Recaptcha="m.login.recaptcha",n.Terms="m.login.terms",n.Email="m.login.email.identity",n.Msisdn="m.login.msisdn",n.Sso="m.login.sso",n.SsoUnstable="org.matrix.login.sso",n.Dummy="m.login.dummy",n.RegistrationToken="m.login.registration_token",n.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token",n))(dB||{});class hB extends Error{constructor(e,t,r){super(e),this.required_stages=t,this.flows=r,this.name="NoAuthFlowFoundError"}}class NP{constructor(e){this.requestingEmailToken=!1,this.attemptAuthDeferred=null,this.chosenFlow=null,this.currentStage=null,this.emailAttempt=1,this.submitPromise=null,this.requestEmailToken=async()=>{if(this.requestingEmailToken)M.warn("Could not request email token: Already requesting");else{M.trace("Requesting email token. Attempt: "+this.emailAttempt),this.requestingEmailToken=!0;try{const t=await this.requestEmailTokenCallback(this.inputs.emailAddress,this.clientSecret,this.emailAttempt++,this.data.session);this.emailSid=t.sid,M.trace("Email token request succeeded")}finally{this.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))}async attemptAuth(){var t,r,i;this.attemptAuthDeferred=Zl();const e=this.attemptAuthDeferred.promise;if((r=(t=this.data)==null?void 0:t.flows)!=null&&r.length)this.startNextAuthStage();else{(i=this.busyChangedCallback)==null||i.call(this,!0);const s=this.data.session?{session:this.data.session}:null;this.doRequest(s).finally(()=>{var o;(o=this.busyChangedCallback)==null||o.call(this,!1)})}return e}async poll(){if(!this.data.session||!this.attemptAuthDeferred||this.submitPromise)return;let e={};if(this.currentStage==Um&&this.emailSid){const t={sid:this.emailSid,client_secret:this.clientSecret},r=this.matrixClient.getIdentityServerUrl();r&&(t.id_server=new URL(r).host),e={type:Um,threepid_creds:t}}this.submitAuthDict(e,!0)}getSessionId(){var e;return(e=this.data)==null?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var t,r;return(r=(t=this.data)==null?void 0:t.params)==null?void 0:r[e]}getChosenFlow(){return this.chosenFlow}async submitAuthDict(e,t=!1){var i,s,o;if(!this.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");for(t||(i=this.busyChangedCallback)==null||i.call(this,!0);this.submitPromise;)try{await this.submitPromise}catch{}let r;(s=this.data)!=null&&s.session?r=Object.assign({session:this.data.session},e):r=e;try{this.submitPromise=this.doRequest(r,t),await this.submitPromise}finally{this.submitPromise=null,t||(o=this.busyChangedCallback)==null||o.call(this,!1)}}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}async doRequest(e,t=!1){var r,i,s,o;try{const a=await this.requestCallback(e,t);this.attemptAuthDeferred.resolve(a),this.attemptAuthDeferred=null}catch(a){const c=a instanceof mn?a:null,l=((r=c==null?void 0:c.data)==null?void 0:r.flows)??null,u=((i=this.data)==null?void 0:i.flows)||!!l;(!c||c.httpStatus!==401||!c.data||!u)&&(t?M.log("Background poll request failed doing UI auth: ignoring",a):(s=this.attemptAuthDeferred)==null||s.reject(a)),c&&!c.data&&(c.data={}),c&&!c.data.flows&&!c.data.completed&&!c.data.session&&(c.data.flows=this.data.flows,c.data.completed=this.data.completed,c.data.session=this.data.session),c&&(this.data=c.data);try{this.startNextAuthStage()}catch(h){this.attemptAuthDeferred.reject(h),this.attemptAuthDeferred=null;return}if(!this.emailSid&&((o=this.chosenFlow)!=null&&o.stages.includes("m.login.email.identity")))try{await this.requestEmailToken()}catch(h){this.attemptAuthDeferred.reject(h),this.attemptAuthDeferred=null}}}startNextAuthStage(){var t,r,i,s;const e=this.chooseStage();if(!e)throw new Error("No incomplete flows from the server");if(this.currentStage=e,e==="m.login.dummy"){this.submitAuthDict({type:"m.login.dummy"});return}if((t=this.data)!=null&&t.errcode||(r=this.data)!=null&&r.error){this.stateUpdatedCallback(e,{errcode:((i=this.data)==null?void 0:i.errcode)||"",error:((s=this.data)==null?void 0:s.error)||""});return}this.stateUpdatedCallback(e,e===Um?{emailSid:this.emailSid}:{})}chooseStage(){this.chosenFlow===null&&(this.chosenFlow=this.chooseFlow()),M.log("Active flow => %s",JSON.stringify(this.chosenFlow));const e=this.firstUncompletedStage(this.chosenFlow);return M.log("Next stage: %s",e),e}scoreFlow(e){let t=e.stages.length;return this.supportedStages!==void 0&&(t+=e.stages.filter(r=>!this.supportedStages.has(r)).length*10),t}chooseFlow(){var s;const e=((s=this.data)==null?void 0:s.flows)||[],t=!!this.inputs.emailAddress||!!this.emailSid,r=!!this.inputs.phoneCountry&&!!this.inputs.phoneNumber;e.sort((o,a)=>this.scoreFlow(o)-this.scoreFlow(a));for(const o of e){let a=!1,c=!1;for(const l of o.stages)l===Um?a=!0:l==$5&&(c=!0);if(a==t&&c==r)return o}const i=[];throw t&&i.push(Um),r&&i.push($5),new hB("No appropriate authentication flow found",i,e)}firstUncompletedStage(e){var r;const t=((r=this.data)==null?void 0:r.completed)||[];return e.stages.find(i=>!t.includes(i))}}function fB(n,e){return new Promise((t,r)=>{let i=!0;const s=n.open(e);s.onupgradeneeded=()=>{i=!1},s.onblocked=()=>r(s.error),s.onsuccess=()=>{s.result.close(),i||n.deleteDatabase(e),t(i)},s.onerror=()=>r(s.error)})}const pB=[n=>{n.createObjectStore("users",{keyPath:["userId"]}),n.createObjectStore("accountData",{keyPath:["type"]}),n.createObjectStore("sync",{keyPath:["clobber"]})},n=>{n.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")},n=>{n.createObjectStore("client_options",{keyPath:["clobber"]})},n=>{n.createObjectStore("to_device_queue",{autoIncrement:!0})}],eae=pB.length;function a1(n,e,t){const r=n.openCursor(e);return new Promise((i,s)=>{const o=[];r.onerror=()=>{var a;s(new Error("Query failed: "+((a=r.error)==null?void 0:a.name)))},r.onsuccess=()=>{const a=r.result;if(!a){i(o);return}o.push(t(a)),a.continue()}})}function Bu(n){return new Promise((e,t)=>{n.oncomplete=function(r){e(r)},n.onerror=function(){t(n.error)}})}function mB(n){return new Promise((e,t)=>{n.onsuccess=function(r){e(r)},n.onerror=function(){t(n.error)}})}function tae(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n),n.onerror=r=>t(r)})}function GT(n){return mB(n).then(e=>n.result)}class B5{constructor(e,t="default"){this.indexedDB=e,this.disconnected=!0,this._isNewlyCreated=!1,this.pendingUserPresenceData=[],this.dbName="matrix-js-sdk:"+t,this.syncAccumulator=new lB}static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),fB(e,t)}connect(e){if(!this.disconnected)return M.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,M.log("LocalIndexedDBStoreBackend.connect: connecting...");const t=this.indexedDB.open(this.dbName,eae);return t.onupgradeneeded=r=>{const i=t.result,s=r.oldVersion;M.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${s}`),s<1&&(this._isNewlyCreated=!0),pB.forEach((o,a)=>{s<=a&&o(i)})},t.onblocked=()=>{M.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},M.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),mB(t).then(async()=>{M.log("LocalIndexedDBStoreBackend.connect: connected"),this.db=t.result,this.db.onversionchange=()=>{var r;(r=this.db)==null||r.close(),this.disconnected=!0,this.db=void 0},this.db.onclose=()=>{this.disconnected=!0,this.db=void 0,e==null||e()},await this.init()})}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then(([e,t])=>{M.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:t.nextBatch,rooms:t.roomsData,account_data:{events:e}},!0)})}getOutOfBandMembers(e){return new Promise((t,r)=>{const o=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),a=IDBKeyRange.only(e),c=o.openCursor(a),l=[];let u=!1;c.onsuccess=()=>{const h=c.result;if(!h)return!l.length&&!u?t(null):t(l);const p=h.value;p.oob_written?u=!0:l.push(p),h.continue()},c.onerror=h=>{r(h)}}).then(t=>(M.log(`LL: got ${t==null?void 0:t.length} membershipEvents from storage for room ${e} ...`),t))}async setOutOfBandMembers(e,t){M.log(`LL: backend about to store ${t.length} members for ${e}`);const r=this.db.transaction(["oob_membership_events"],"readwrite"),i=r.objectStore("oob_membership_events");t.forEach(o=>{i.put(o)});const s={room_id:e,oob_written:!0,state_key:0};i.put(s),await Bu(r),M.log(`LL: backend done storing for ${e}!`)}async clearOutOfBandMembers(e){const i=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),s=IDBKeyRange.only(e),o=GT(i.openKeyCursor(s,"next")).then(m=>(m==null?void 0:m.primaryKey)[1]),a=GT(i.openKeyCursor(s,"prev")).then(m=>(m==null?void 0:m.primaryKey)[1]),[c,l]=await Promise.all([o,a]),h=this.db.transaction(["oob_membership_events"],"readwrite").objectStore("oob_membership_events"),p=IDBKeyRange.bound([e,c],[e,l]);M.log(`LL: Deleting all users + marker in storage for room ${e}, with key range:`,[e,c],[e,l]),await tae(h.delete(p))}clearDatabase(){return new Promise(e=>{var r;M.log(`Removing indexeddb instance: ${this.dbName}`),(r=this.db)==null||r.close();const t=this.indexedDB.deleteDatabase(this.dbName);t.onblocked=()=>{M.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`)},t.onerror=()=>{var i;M.warn(`unable to delete js-sdk store indexeddb: ${(i=t.error)==null?void 0:i.name}`),e()},t.onsuccess=()=>{M.log(`Removed indexeddb instance: ${this.dbName}`),e()}})}getSavedSync(e=!0){const t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(iw(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then(()=>{this.syncAccumulator.accumulate(e)})}async syncToDatabase(e){return this.syncToDatabasePromise?(M.warn("Skipping syncToDatabase() as persist already in flight"),this.pendingUserPresenceData.push(...e),this.syncToDatabasePromise):(e.unshift(...this.pendingUserPresenceData),this.syncToDatabasePromise=this.doSyncToDatabase(e),this.syncToDatabasePromise)}async doSyncToDatabase(e){try{const t=this.syncAccumulator.getJSON(!0);await Promise.all([this.persistUserPresenceEvents(e),this.persistAccountData(t.accountData),this.persistSyncData(t.nextBatch,t.roomsData)])}finally{this.syncToDatabasePromise=void 0}}persistSyncData(e,t){return M.log("Persisting sync data up to",e),kh(()=>{const r=this.db.transaction(["sync"],"readwrite");return r.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t}),Bu(r).then(()=>{M.log("Persisted sync data up to",e)})})}persistAccountData(e){return kh(()=>{const t=this.db.transaction(["accountData"],"readwrite"),r=t.objectStore("accountData");for(const i of e)r.put(i);return Bu(t).then()})}persistUserPresenceEvents(e){return kh(()=>{const t=this.db.transaction(["users"],"readwrite"),r=t.objectStore("users");for(const i of e)r.put({userId:i[0],event:i[1]});return Bu(t).then()})}getUserPresenceEvents(){return kh(()=>{const t=this.db.transaction(["users"],"readonly").objectStore("users");return a1(t,void 0,r=>[r.value.userId,r.value.event])})}loadAccountData(){return M.log("LocalIndexedDBStoreBackend: loading account data..."),kh(()=>{const t=this.db.transaction(["accountData"],"readonly").objectStore("accountData");return a1(t,void 0,r=>r.value).then(r=>(M.log("LocalIndexedDBStoreBackend: loaded account data"),r))})}loadSyncData(){return M.log("LocalIndexedDBStoreBackend: loading sync data..."),kh(()=>{const t=this.db.transaction(["sync"],"readonly").objectStore("sync");return a1(t,void 0,r=>r.value).then(r=>(M.log("LocalIndexedDBStoreBackend: loaded sync data"),r.length>1&&M.warn("loadSyncData: More than 1 sync row found."),r.length>0?r[0]:{}))})}getClientOptions(){return Promise.resolve().then(()=>{const t=this.db.transaction(["client_options"],"readonly").objectStore("client_options");return a1(t,void 0,r=>{var i;return(i=r.value)==null?void 0:i.options}).then(r=>r[0])})}async storeClientOptions(e){const t=this.db.transaction(["client_options"],"readwrite");t.objectStore("client_options").put({clobber:"-",options:e}),await Bu(t)}async saveToDeviceBatches(e){const t=this.db.transaction(["to_device_queue"],"readwrite"),r=t.objectStore("to_device_queue");for(const i of e)r.add(i);await Bu(t)}async getOldestToDeviceBatch(){const t=this.db.transaction(["to_device_queue"],"readonly").objectStore("to_device_queue"),r=await GT(t.openCursor());if(!r)return null;const i=r.value;return{id:r.key,txnId:i.txnId,eventType:i.eventType,batch:i.batch}}async removeToDeviceBatch(e){const t=this.db.transaction(["to_device_queue"],"readwrite");t.objectStore("to_device_queue").delete(e),await Bu(t)}async destroy(){var e;(e=this.db)==null||e.close()}}class nae{constructor(e,t){this.workerFactory=e,this.dbName=t,this.nextSeq=0,this.inFlight={},this.onWorkerMessage=r=>{var s;const i=r.data;if(i.command=="closed")(s=this.onClose)==null||s.call(this);else if(i.command=="cmd_success"||i.command=="cmd_fail"){if(i.seq===void 0){M.error("Got reply from worker with no seq");return}const o=this.inFlight[i.seq];if(o===void 0){M.error("Got reply for unknown seq "+i.seq);return}if(delete this.inFlight[i.seq],i.command=="cmd_success")o.resolve(i.result);else{const a=new Error(i.error.message);a.name=i.error.name,o.reject(a)}}else M.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")}async saveToDeviceBatches(e){return this.doCmd("saveToDeviceBatches",[e])}async getOldestToDeviceBatch(){return this.doCmd("getOldestToDeviceBatch")}async removeToDeviceBatch(e){return this.doCmd("removeToDeviceBatch",[e])}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then(()=>{M.log("IndexedDB worker is ready")})),this.startPromise}doCmd(e,t){return Promise.resolve().then(()=>{var s;const r=this.nextSeq++,i=Zl();return this.inFlight[r]=i,(s=this.worker)==null||s.postMessage({command:e,seq:r,args:t}),i.promise})}async destroy(){var e;(e=this.worker)==null||e.terminate()}}const rae=1e3*60*5;class gB extends pv{constructor(e){if(super(e),this.startedUp=!1,this.syncTs=0,this.userModifiedMap={},this.emitter=new Yn,this.onClose=()=>{this.emitter.emit("closed")},this.getSavedSync=this.degradable(()=>this.backend.getSavedSync(),"getSavedSync"),this.isNewlyCreated=this.degradable(()=>this.backend.isNewlyCreated(),"isNewlyCreated"),this.getSavedSyncToken=this.degradable(()=>this.backend.getNextBatchToken(),"getSavedSyncToken"),this.deleteAllData=this.degradable(()=>(super.deleteAllData(),this.backend.clearDatabase().then(()=>{M.log("Deleted indexeddb data.")},t=>{throw M.error(`Failed to delete indexeddb data: ${t}`),t})),null),this.reallySave=this.degradable(()=>{this.syncTs=Date.now();const t=[];for(const r of this.getUsers())this.userModifiedMap[r.userId]!==r.getLastModifiedTime()&&r.events.presence&&(t.push([r.userId,r.events.presence.event]),this.userModifiedMap[r.userId]=r.getLastModifiedTime());return this.backend.syncToDatabase(t)},null),this.setSyncData=this.degradable(t=>this.backend.setSyncData(t),"setSyncData"),this.getOutOfBandMembers=this.degradable(t=>this.backend.getOutOfBandMembers(t),"getOutOfBandMembers"),this.setOutOfBandMembers=this.degradable((t,r)=>(super.setOutOfBandMembers(t,r),this.backend.setOutOfBandMembers(t,r)),"setOutOfBandMembers"),this.clearOutOfBandMembers=this.degradable(t=>(super.clearOutOfBandMembers(t),this.backend.clearOutOfBandMembers(t)),"clearOutOfBandMembers"),this.getClientOptions=this.degradable(()=>this.backend.getClientOptions(),"getClientOptions"),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 nae(e.workerFactory,e.dbName):this.backend=new B5(e.indexedDB,e.dbName)}static exists(e,t){return B5.exists(e,t)}on(e,t){this.emitter.on(e,t)}startup(){return this.startedUp?(M.log("IndexedDBStore.startup: already started"),Promise.resolve()):(M.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect(this.onClose).then(()=>(M.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents())).then(e=>{M.log("IndexedDBStore.startup: processing presence events"),e.forEach(([t,r])=>{if(!this.createUser)throw new Error("`IndexedDBStore.startup` must be called after assigning it to the client, not before!");const i=this.createUser(t);r&&i.setPresenceEvent(new Ji(r)),this.userModifiedMap[i.userId]=i.getLastModifiedTime(),this.storeUser(i)}),this.startedUp=!0}))}destroy(){return this.backend.destroy()}wantsSave(){return Date.now()-this.syncTs>rae}save(e=!1){return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){const r=t?super[t]:null;return async(...i)=>{try{return await e.call(this,...i)}catch(s){M.error("IndexedDBStore failure, degrading to MemoryStore",s),this.emitter.emit("degraded",s);try{M.log("IndexedDBStore trying to delete degraded data"),await this.backend.clearDatabase(),M.log("IndexedDBStore delete after degrading succeeded")}catch(o){M.warn("IndexedDBStore delete after degrading failed",o)}if(r)return r.call(this,...i)}}}async getPendingEvents(e){if(!this.localStorage)return super.getPendingEvents(e);const t=this.localStorage.getItem(qT(e));if(t)try{return JSON.parse(t)}catch(r){M.error("Could not parse persisted pending events",r)}return[]}async setPendingEvents(e,t){if(!this.localStorage)return super.setPendingEvents(e,t);t.length>0?this.localStorage.setItem(qT(e),JSON.stringify(t)):this.localStorage.removeItem(qT(e))}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function qT(n){return`mx_pending_events_${n}`}const Ho="crypto.",H5=Ho+"migration",KT=Ho+"account",iae=Ho+"cross_signing_keys",w_=Ho+"inboundgroupsessions/",sae=Ho+"inboundgroupsessions.withheld/",oae=Ho+"rooms/",WT=Ho+"sessionsneedingbackup";function Oh(n){return Ho+"sessions/"+n}function zT(n,e){return w_+n+"/"+e}function aae(n,e){return sae+n+"/"+e}function cae(n){return oae+n}class _w extends sw{constructor(e){super(),this.store=e}static exists(e){var r;const t=e.length;for(let i=0;i<t;i++)if((r=e.key(i))!=null&&r.startsWith(Ho))return!0;return!1}async containsData(){return _w.exists(this.store)}async getMigrationState(){return Ns(this.store,H5)??Id.NOT_STARTED}async setMigrationState(e){Hu(this.store,H5,e)}countEndToEndSessions(e,t){let r=0;for(let i=0;i<this.store.length;++i){const s=this.store.key(i);if(s!=null&&s.startsWith(Oh(""))){const o=Ns(this.store,s);r+=Object.keys(o??{}).length}}t(r)}_getEndToEndSessions(e){const t=Ns(this.store,Oh(e)),r={};for(const[i,s]of Object.entries(t||{}))typeof s=="string"?r[i]={session:s}:r[i]=s;return r}getEndToEndSession(e,t,r,i){const s=this._getEndToEndSessions(e);i(s[t]??{})}getEndToEndSessions(e,t,r){r(this._getEndToEndSessions(e)??{})}storeEndToEndSession(e,t,r,i){const s=this._getEndToEndSessions(e)||{};s[t]=r,Hu(this.store,Oh(e),s)}async getEndToEndSessionsBatch(){var t;const e=[];for(let r=0;r<this.store.length;++r)if((t=this.store.key(r))!=null&&t.startsWith(Oh(""))){const i=this.store.key(r).split("/")[1];for(const s of Object.values(this._getEndToEndSessions(i)))if(e.push(s),e.length>=Vf)return e}return e.length===0?null:e}async deleteEndToEndSessionsBatch(e){for(const{deviceKey:t,sessionId:r}of e){const i=this._getEndToEndSessions(t)||{};delete i[r],Object.keys(i).length===0?this.store.removeItem(Oh(t)):Hu(this.store,Oh(t),i)}}getEndToEndInboundGroupSession(e,t,r,i){i(Ns(this.store,zT(e,t)),Ns(this.store,aae(e,t)))}storeEndToEndInboundGroupSession(e,t,r,i){Hu(this.store,zT(e,t),r)}async countEndToEndInboundGroupSessions(){let e=0;for(let t=0;t<this.store.length;++t){const r=this.store.key(t);r!=null&&r.startsWith(w_)&&(e+=1)}return e}async getEndToEndInboundGroupSessionsBatch(){const e=Ns(this.store,WT)||{},t=[];for(let r=0;r<this.store.length;++r){const i=this.store.key(r);if(i!=null&&i.startsWith(w_)){const s=i.slice(w_.length);if(t.push({senderKey:s.slice(0,43),sessionId:s.slice(44),sessionData:Ns(this.store,i),needsBackup:s in e}),t.length>=Vf)return t}}return t.length===0?null:t}async deleteEndToEndInboundGroupSessionsBatch(e){for(const{senderKey:t,sessionId:r}of e){const i=zT(t,r);this.store.removeItem(i)}}getEndToEndRooms(e,t){const r={},i=cae("");for(let s=0;s<this.store.length;++s){const o=this.store.key(s);if(o!=null&&o.startsWith(i)){const a=o.slice(i.length);r[a]=Ns(this.store,o)}}t(r)}markSessionsNeedingBackup(e){const t=Ns(this.store,WT)||{};for(const r of e)t[r.senderKey+"/"+r.sessionId]=!0;return Hu(this.store,WT,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(KT),Promise.resolve()}getAccount(e,t){const r=Ns(this.store,KT);t(r)}storeAccount(e,t){Hu(this.store,KT,t)}getCrossSigningKeys(e,t){const r=Ns(this.store,iae);t(r)}getSecretStorePrivateKey(e,t,r){const i=Ns(this.store,Ho+`ssss_cache.${r}`);t(i)}storeSecretStorePrivateKey(e,t,r){Hu(this.store,Ho+`ssss_cache.${t}`,r)}doTxn(e,t,r){return Promise.resolve(r(null))}}function Ns(n,e){try{return JSON.parse(n.getItem(e))}catch(t){M.log("Error: Failed to get key %s: %s",e,t.message),M.log(t.stack)}return null}function Hu(n,e,t){n.setItem(e,JSON.stringify(t))}let lae=class{constructor(e){this.db=e,this.nextTxnId=0,e.onversionchange=()=>{M.log(`versionchange for indexeddb ${this.db.name}: closing`),e.close()}}async containsData(){throw Error("Not implemented for Backend")}async startup(){return this}async deleteAllData(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")}async getMigrationState(){let e=Id.NOT_STARTED;return await this.doTxn("readonly",[Qn.STORE_ACCOUNT],t=>{const i=t.objectStore(Qn.STORE_ACCOUNT).get(AR);i.onsuccess=()=>{e=i.result??Id.NOT_STARTED}}),e}async setMigrationState(e){await this.doTxn("readwrite",[Qn.STORE_ACCOUNT],t=>{t.objectStore(Qn.STORE_ACCOUNT).put(e,AR)})}getAccount(e,t){const i=e.objectStore("account").get("-");i.onsuccess=function(){try{t(i.result||null)}catch(s){Di(e,s)}}}storeAccount(e,t){e.objectStore("account").put(t,"-")}getCrossSigningKeys(e,t){const i=e.objectStore("account").get("crossSigningKeys");i.onsuccess=function(){try{t(i.result||null)}catch(s){Di(e,s)}}}getSecretStorePrivateKey(e,t,r){const s=e.objectStore("account").get(`ssss_cache:${r}`);s.onsuccess=function(){try{t(s.result||null)}catch(o){Di(e,o)}}}storeSecretStorePrivateKey(e,t,r){e.objectStore("account").put(r,`ssss_cache:${t}`)}countEndToEndSessions(e,t){const i=e.objectStore("sessions").count();i.onsuccess=function(){try{t(i.result)}catch(s){Di(e,s)}}}getEndToEndSessions(e,t,r){const o=t.objectStore("sessions").index("deviceKey").openCursor(e),a={};o.onsuccess=function(){const c=o.result;if(c)a[c.value.sessionId]={session:c.value.session,lastReceivedMessageTs:c.value.lastReceivedMessageTs},c.continue();else try{r(a)}catch(l){Di(t,l)}}}getEndToEndSession(e,t,r,i){const o=r.objectStore("sessions").get([e,t]);o.onsuccess=function(){try{o.result?i({session:o.result.session,lastReceivedMessageTs:o.result.lastReceivedMessageTs}):i(null)}catch(a){Di(r,a)}}}storeEndToEndSession(e,t,r,i){i.objectStore("sessions").put({deviceKey:e,sessionId:t,session:r.session,lastReceivedMessageTs:r.lastReceivedMessageTs})}async getEndToEndSessionsBatch(){const e=[];return await this.doTxn("readonly",[Qn.STORE_SESSIONS],t=>{const i=t.objectStore(Qn.STORE_SESSIONS).openCursor();i.onsuccess=function(){try{const s=i.result;s&&(e.push(s.value),e.length<Vf&&s.continue())}catch(s){Di(t,s)}}}),e.length===0?null:e}async deleteEndToEndSessionsBatch(e){await this.doTxn("readwrite",[Qn.STORE_SESSIONS],async t=>{try{const r=t.objectStore(Qn.STORE_SESSIONS);for(const{deviceKey:i,sessionId:s}of e){const o=r.delete([i,s]);await new Promise(a=>{o.onsuccess=a})}}catch(r){Di(t,r)}})}getEndToEndInboundGroupSession(e,t,r,i){let s=!1,o=!1;const c=r.objectStore("inbound_group_sessions").get([e,t]);c.onsuccess=function(){try{c.result?s=c.result.session:s=null,o!==!1&&i(s,o)}catch(h){Di(r,h)}};const u=r.objectStore("inbound_group_sessions_withheld").get([e,t]);u.onsuccess=function(){try{u.result?o=u.result.session:o=null,s!==!1&&i(s,o)}catch(h){Di(r,h)}}}storeEndToEndInboundGroupSession(e,t,r,i){i.objectStore("inbound_group_sessions").put({senderCurve25519Key:e,sessionId:t,session:r})}async countEndToEndInboundGroupSessions(){let e=0;return await this.doTxn("readonly",[Qn.STORE_INBOUND_GROUP_SESSIONS],t=>{const i=t.objectStore(Qn.STORE_INBOUND_GROUP_SESSIONS).count();i.onsuccess=()=>{e=i.result}}),e}async getEndToEndInboundGroupSessionsBatch(){const e=[];return await this.doTxn("readonly",[Qn.STORE_INBOUND_GROUP_SESSIONS,Qn.STORE_BACKUP],t=>{const r=t.objectStore(Qn.STORE_INBOUND_GROUP_SESSIONS),i=t.objectStore(Qn.STORE_BACKUP),s=r.openCursor();s.onsuccess=function(){try{const o=s.result;if(o){const a=i.get(o.key);a.onsuccess=()=>{e.push({senderKey:o.value.senderCurve25519Key,sessionId:o.value.sessionId,sessionData:o.value.session,needsBackup:a.result!==void 0}),e.length<Vf&&o.continue()}}}catch(o){Di(t,o)}}}),e.length===0?null:e}async deleteEndToEndInboundGroupSessionsBatch(e){await this.doTxn("readwrite",[Qn.STORE_INBOUND_GROUP_SESSIONS],async t=>{try{const r=t.objectStore(Qn.STORE_INBOUND_GROUP_SESSIONS);for(const{senderKey:i,sessionId:s}of e){const o=r.delete([i,s]);await new Promise(a=>{o.onsuccess=a})}}catch(r){Di(t,r)}})}getEndToEndDeviceData(e,t){const i=e.objectStore("device_data").get("-");i.onsuccess=function(){try{t(i.result||null)}catch(s){Di(e,s)}}}getEndToEndRooms(e,t){const r={},s=e.objectStore("rooms").openCursor();s.onsuccess=function(){const o=s.result;if(o)r[o.key]=o.value,o.continue();else try{t(r)}catch(a){Di(e,a)}}}async markSessionsNeedingBackup(e,t){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const r=t.objectStore("sessions_needing_backup");await Promise.all(e.map(i=>new Promise((s,o)=>{const a=r.put({senderCurve25519Key:i.senderKey,sessionId:i.sessionId});a.onsuccess=s,a.onerror=o})))}doTxn(e,t,r,i=M){const s=this.db.transaction(t,e),o=hae(s),a=r(s);return o.then(()=>a)}};const vB=[n=>{dae(n)},n=>{n.createObjectStore("account")},n=>{n.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]}).createIndex("deviceKey","deviceKey")},n=>{n.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},n=>{n.createObjectStore("device_data")},n=>{n.createObjectStore("rooms")},n=>{n.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},n=>{n.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},n=>{n.createObjectStore("session_problems",{keyPath:["deviceKey","time"]}).createIndex("deviceKey","deviceKey"),n.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},n=>{n.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},n=>{n.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}],yB=vB.length;function uae(n,e){M.log(`Upgrading IndexedDBCryptoStore from version ${e} to ${yB}`),vB.forEach((t,r)=>{e<=r&&t(n)})}function dae(n){const e=n.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});e.createIndex("session",["requestBody.room_id","requestBody.session_id"]),e.createIndex("state","state")}function Di(n,e){n._mx_abortexception=e;try{n.abort()}catch{}}function hae(n){return new Promise((e,t)=>{n.oncomplete=()=>{n._mx_abortexception!==void 0&&t(n._mx_abortexception),e(null)},n.onerror=r=>{n._mx_abortexception!==void 0?t(n._mx_abortexception):(M.log("Error performing indexeddb txn",r),t(n.error))},n.onabort=r=>{n._mx_abortexception!==void 0?t(n._mx_abortexception):(M.log("Error performing indexeddb txn",r),t(n.error))}})}const oi=class oi{constructor(e,t){this.indexedDB=e,this.dbName=t}static exists(e,t){return fB(e,t)}static existsAndIsNotMigrated(e,t){return new Promise((r,i)=>{let s=!0;const o=e.open(t);o.onupgradeneeded=()=>{s=!1},o.onblocked=()=>i(o.error),o.onsuccess=()=>{const a=o.result;if(!s)a.close(),e.deleteDatabase(t),r(!1);else{const u=a.transaction([oi.STORE_ACCOUNT],"readonly").objectStore(oi.STORE_ACCOUNT).get(AR);u.onsuccess=()=>{const h=u.result??Id.NOT_STARTED;r(h===Id.NOT_STARTED)},u.onerror=()=>{i(u.error)},a.close()}},o.onerror=()=>i(o.error)})}async containsData(){return oi.exists(this.indexedDB,this.dbName)}startup(){return this.backendPromise?this.backendPromise:(this.backendPromise=new Promise((e,t)=>{if(!this.indexedDB){t(new Error("no indexeddb support available"));return}M.log(`connecting to indexeddb ${this.dbName}`);const r=this.indexedDB.open(this.dbName,yB);r.onupgradeneeded=i=>{const s=r.result,o=i.oldVersion;uae(s,o)},r.onblocked=()=>{M.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{M.log("Error connecting to indexeddb",i),t(r.error)},r.onsuccess=()=>{const i=r.result;M.log(`connected to indexeddb ${this.dbName}`),e(new lae(i))}}).then(e=>e.doTxn("readonly",[oi.STORE_INBOUND_GROUP_SESSIONS,oi.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],t=>{e.getEndToEndInboundGroupSession("","",t,()=>{})}).then(()=>e)).catch(e=>{if(e.name==="VersionError")throw M.warn("Crypto DB is too new for us to use!",e),new Fb(LP.TooNew);M.warn(`unable to connect to indexeddb ${this.dbName}: falling back to localStorage store: ${e}`);try{return new _w(globalThis.localStorage)}catch(t){return M.warn(`unable to open localStorage: falling back to in-memory store: ${t}`),new sw}}).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}M.log(`Removing indexeddb instance: ${this.dbName}`);const r=this.indexedDB.deleteDatabase(this.dbName);r.onblocked=()=>{M.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{M.log("Error deleting data from indexeddb",i),t(r.error)},r.onsuccess=()=>{M.log(`Removed indexeddb instance: ${this.dbName}`),e()}}).catch(e=>{M.warn(`unable to delete IndexedDBCryptoStore: ${e}`)})}getMigrationState(){return this.backend.getMigrationState()}setMigrationState(e){return this.backend.setMigrationState(e)}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,r){this.backend.getSecretStorePrivateKey(e,t,r)}storeSecretStorePrivateKey(e,t,r){this.backend.storeSecretStorePrivateKey(e,t,r)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,r,i){this.backend.getEndToEndSession(e,t,r,i)}getEndToEndSessions(e,t,r){this.backend.getEndToEndSessions(e,t,r)}storeEndToEndSession(e,t,r,i){this.backend.storeEndToEndSession(e,t,r,i)}countEndToEndInboundGroupSessions(){return this.backend.countEndToEndInboundGroupSessions()}getEndToEndSessionsBatch(){return this.backend.getEndToEndSessionsBatch()}deleteEndToEndSessionsBatch(e){return this.backend.deleteEndToEndSessionsBatch(e)}getEndToEndInboundGroupSession(e,t,r,i){this.backend.getEndToEndInboundGroupSession(e,t,r,i)}storeEndToEndInboundGroupSession(e,t,r,i){this.backend.storeEndToEndInboundGroupSession(e,t,r,i)}getEndToEndInboundGroupSessionsBatch(){return this.backend.getEndToEndInboundGroupSessionsBatch()}deleteEndToEndInboundGroupSessionsBatch(e){return this.backend.deleteEndToEndInboundGroupSessionsBatch(e)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}doTxn(e,t,r,i){return this.backend.doTxn(e,t,r,i)}};oi.STORE_ACCOUNT="account",oi.STORE_SESSIONS="sessions",oi.STORE_INBOUND_GROUP_SESSIONS="inbound_group_sessions",oi.STORE_INBOUND_GROUP_SESSIONS_WITHHELD="inbound_group_sessions_withheld",oi.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS="shared_history_inbound_group_sessions",oi.STORE_PARKED_SHARED_HISTORY="parked_shared_history",oi.STORE_DEVICE_DATA="device_data",oi.STORE_ROOMS="rooms",oi.STORE_BACKUP="sessions_needing_backup";let Qn=oi;var _B=(n=>(n.Email="email",n.Phone="msisdn",n))(_B||{});const fae=new Fn("delegated_oidc_compatibility","org.matrix.msc3824.delegated_oidc_compatibility");var bB=(n=>(n.Gitlab="gitlab",n.Github="github",n.Apple="apple",n.Google="google",n.Facebook="facebook",n.Twitter="twitter",n))(bB||{}),SB=(n=>(n.LOGIN="login",n.REGISTER="register",n))(SB||{});const pae="us.cloke.msc4175.tz";class mae{constructor(e){this.relations=e.filter(t=>!!t)}getRelations(){return this.relations.reduce((e,t)=>[...e,...t.getRelations()],[])}on(e,t){this.relations.forEach(r=>r.on(e,t))}off(e,t){this.relations.forEach(r=>r.off(e,t))}}var wB=(n=>(n.Global="Global",n.SetItemError="setItem",n.GetItemError="getItem",n.RemoveItemError="removeItem",n.ClearError="clear",n.QuotaExceededError="QuotaExceededError",n))(wB||{});class gae extends Yn{}const vae=new gae;let EB=()=>new sw;function CB(n){EB=n}function TB(n){return n.store=n.store??new pv({localStorage:globalThis.localStorage}),n.scheduler=n.scheduler??new qf,n.cryptoStore=n.cryptoStore??EB(),n}function bw(n){return new dv(TB(n))}function IB(n,e,t,r,i=!0){return new aB(n,e,t,TB(r),i)}const yae=Object.freeze(Object.defineProperty({__proto__:null,AuthType:dB,AutoDiscovery:lv,AutoDiscoveryAction:D$,AutoDiscoveryError:TP,Beacon:Jj,BeaconEvent:Gn,CallEvent:Bi,CallFeedEvent:x$,Category:cB,ClientEvent:Ge,ClientPrefix:lr,ClientStoppedError:Soe,ConditionKind:Hn,ConditionOperator:N$,ConnectionError:Vd,ContentHelpers:Xre,DELEGATED_OIDC_COMPATIBILITY:fae,DEVICE_CODE_SCOPE:Moe,DMMemberCountCondition:Bse,Device:Joe,DeviceVerification:uB,Direction:bt,DuplicateStrategy:Ig,EVENT_VISIBILITY_CHANGE_TYPE:nd,EventEmitterEvents:nP,EventStatus:rt,EventTimeline:Be,EventTimelineSet:cf,EventType:ie,FILTER_RELATED_BY_REL_TYPES:Ef,FILTER_RELATED_BY_SENDERS:wf,FeatureSupport:ha,Filter:ys,GET_LOGIN_TOKEN_CAPABILITY:joe,GroupCall:EP,GroupCallEvent:Ob,GroupCallIntent:SP,GroupCallState:wP,GroupCallStatsReportEvent:L$,GroupCallType:pw,GuestAccess:uv,HTTPError:eu,HistoryVisibility:vw,HttpApiEvent:Ab,IdentityPrefix:da,IdentityProviderBrand:bB,IndexedDBCryptoStore:Qn,IndexedDBStore:gB,InteractiveAuth:NP,InvalidCryptoStoreError:Fb,InvalidCryptoStoreState:LP,JoinRule:wc,KNOWN_SAFE_ROOM_VERSION:b$,KeySignatureUploadError:boe,KnownMembership:We,LOCAL_NOTIFICATION_SETTINGS_PREFIX:Ij,LocalStorageCryptoStore:_w,LocalStorageErrors:wB,LocationAssetType:Ed,MAIN_ROOM_TIMELINE:iy,MAXIMUM_MATRIX_VERSION:zse,MINIMUM_MATRIX_VERSION:Wse,MSC3912_RELATION_BASED_REDACTIONS_PROP:FR,M_ASSET:ny,M_BEACON:rk,M_BEACON_INFO:kP,M_HTML:Gre,M_LOCATION:ry,M_MESSAGE:Vre,M_POLL_END:kb,M_POLL_KIND_DISCLOSED:Jre,M_POLL_KIND_UNDISCLOSED:Zre,M_POLL_RESPONSE:sv,M_POLL_START:Qre,M_TEXT:aP,M_TIMESTAMP:pu,M_TOPIC:cP,MatrixClient:dv,MatrixError:mn,MatrixEvent:Ji,MatrixEventEvent:pn,MatrixHttpApi:y$,MatrixScheduler:qf,MediaHandlerEvent:U$,MediaPrefix:ud,MemoryCryptoStore:sw,MemoryStore:pv,Method:de,MsgType:zo,NoAuthFlowFoundError:hB,NotificationCountType:rr,OidcError:Kr,OidcTokenRefresher:Doe,PUSHER_DEVICE_ID:Pre,PUSHER_ENABLED:UR,PendingEventOrdering:Rd,Poll:e$,PollEvent:lP,Preset:ay,ProfileKeyMSC4175Timezone:pae,PushRuleActionName:Sc,PushRuleKind:pr,REFERENCE_RELATION:$j,ReceiptType:ci,RelatedRelations:mae,RelationType:sn,Relations:oP,RelationsEvent:Dj,RestrictedAllowType:F$,Room:hw,RoomCreateTypeField:Eb,RoomEvent:Xe,RoomMember:Tb,RoomMemberEvent:Fo,RoomNameType:S$,RoomState:fv,RoomStateEvent:It,RoomSummary:Uj,RoomType:ld,RoomVersionStability:yP,RoomWidgetClient:aB,RoomWidgetClientEvent:oB,RuleId:fr,SERVICE_TYPES:Nb,SSOAction:SB,SUPPORTED_MATRIX_VERSIONS:cv,SearchOrderBy:RP,SearchResult:gw,SecretStorage:yoe,ServerCapabilities:_$,SetPresence:w$,SlidingSyncEvent:Db,StatsReport:wa,SyncAccumulator:lB,SyncState:Pr,THREAD_RELATION_TYPE:en,Thread:Gr,ThreadEvent:Ro,ThreadFilterType:To,ThreepidMedium:_B,TimelineIndex:uk,TimelineWindow:Qoe,ToDeviceMessageId:cw,TokenRefreshError:u$,TweakName:mw,TypedEventEmitter:Yn,UNSIGNED_MEMBERSHIP_FIELD:Rj,UNSIGNED_THREAD_ID_FIELD:Cb,UNSTABLE_ELEMENT_FUNCTIONAL_USERS:Tj,UNSTABLE_MSC2666_MUTUAL_ROOMS:Z$,UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS:Q$,UNSTABLE_MSC2666_SHARED_ROOMS:J$,UNSTABLE_MSC2716_MARKER:Cj,UNSTABLE_MSC3088_ENABLED:NR,UNSTABLE_MSC3088_PURPOSE:MR,UNSTABLE_MSC3089_BRANCH:dc,UNSTABLE_MSC3089_LEAF:Ej,UNSTABLE_MSC3089_TREE_SUBTYPE:DR,UNSTABLE_MSC3852_LAST_SEEN_UA:Uoe,UNSTABLE_MSC4133_EXTENDED_PROFILES:eB,UNSTABLE_MSC4140_DELAYED_EVENTS:ga,UnsupportedDelayedEventsEndpointError:Nl,UpdateDelayedEventAction:Vl,User:bc,UserEvent:Ol,Visibility:IP,anySignal:d$,calculateRetryBackoff:h$,completeAuthorizationCodeGrant:Ooe,createClient:bw,createNewMatrixCall:av,createRoomWidgetClient:IB,decodeBase64:_f,decodeIdToken:W$,determineFeatureSupport:S_,discoverAndValidateOIDCIssuerWellKnown:OP,encodeBase64:y_,encodeUnpaddedBase64:R$,encodeUnpaddedBase64Url:fw,fixNotificationCountOnDecryption:tB,generateAuthorizationParams:xoe,generateAuthorizationUrl:Poe,generateOidcAuthorizationUrl:Loe,generateScope:yw,getBeaconInfoIdentifier:Rb,getHttpUriForMxc:ow,inMainTimelineForReceipt:hv,isDmMemberCountCondition:Hse,isEventTypeSame:qre,isPollEvent:t$,isTimestampInDuration:$R,localStorageErrorsEventsEmitter:vae,parseErrorResponse:mP,registerOidcClient:Noe,retryNetworkOperation:zR,safeGetRetryAfterMs:pP,setCryptoStoreFactory:CB,threadFilterTypeToFilter:nB,threadIdForReceipt:Kf,timeoutSignal:uw,validateAuthMetadata:K$,validateAuthMetadataAndKeys:MP,validateBearerTokenResponse:X$,validateIdToken:z$,validateStoredUserState:Y$},Symbol.toStringTag,{value:"Module"}));if(globalThis.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");globalThis.__js_sdk_entrypoint=!0;let dk;try{dk=globalThis.indexedDB}catch{}dk&&CB(()=>new Qn(dk,"matrix-js-sdk:crypto"));globalThis.matrixcs=yae;var _=Qx();const Re=Wo(_),RB=Qne({__proto__:null,default:Re},[_]);var c1={},YT={exports:{}},Fi={},XT={exports:{}},JT={};/**
|
|
35
35
|
* @license React
|
|
36
36
|
* scheduler.production.min.js
|
|
@@ -204,7 +204,7 @@ total: ${r}ms
|
|
|
204
204
|
peerConnection: ${i}ms
|
|
205
205
|
websocket: ${s}ms`)}}function Wt(n){return typeof n=="function"}function jJ(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var U2=jJ(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
206
206
|
`+t.map(function(r,i){return i+1+") "+r.toString()}).join(`
|
|
207
|
-
`):"",this.name="UnsubscriptionError",this.errors=t}});function OS(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Ry=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=du(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(g){e={error:g}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(Wt(u))try{u()}catch(g){s=g instanceof U2?g.errors:[g]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var p=du(h),m=p.next();!m.done;m=p.next()){var v=m.value;try{HD(v)}catch(g){s=s??[],g instanceof U2?s=io(io([],ro(s)),ro(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{m&&!m.done&&(i=p.return)&&i.call(p)}finally{if(r)throw r.error}}}if(s)throw new U2(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)HD(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&OS(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&OS(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),$J=Ry.EMPTY;function BJ(n){return n instanceof Ry||n&&"closed"in n&&Wt(n.remove)&&Wt(n.add)&&Wt(n.unsubscribe)}function HD(n){Wt(n)?n():n.unsubscribe()}var jOe={Promise:void 0},$Oe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,io([n,e],ro(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function HJ(n){$Oe.setTimeout(function(){throw n})}function MS(){}function lb(n){n()}var WL=function(n){oo(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,BJ(t)&&t.add(r)):r.destination=VOe,r}return e.create=function(t,r,i){return new $v(t,r,i)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Ry),BOe=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){z1(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){z1(r)}else z1(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){z1(t)}},n}(),$v=function(n){oo(e,n);function e(t,r,i){var s=n.call(this)||this,o;return Wt(t)||!t?o={next:t??void 0,error:r??void 0,complete:i??void 0}:o=t,s.destination=new BOe(o),s}return e}(WL);function z1(n){HJ(n)}function HOe(n){throw n}var VOe={closed:!0,next:MS,error:HOe,complete:MS},zL=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Eu(n){return n}function GOe(n){return n.length===0?Eu:n.length===1?n[0]:function(t){return n.reduce(function(r,i){return i(r)},t)}}var Ln=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var i=this,s=KOe(e)?e:new $v(e,t,r);return lb(function(){var o=i,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?i._subscribe(s):i._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=VD(t),new t(function(i,s){var o=new $v({next:function(a){try{e(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[zL]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return GOe(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=VD(e),new e(function(r,i){var s;t.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function VD(n){var e;return(e=n??jOe.Promise)!==null&&e!==void 0?e:Promise}function qOe(n){return n&&Wt(n.next)&&Wt(n.error)&&Wt(n.complete)}function KOe(n){return n&&n instanceof WL||qOe(n)&&BJ(n)}function WOe(n){return Wt(n==null?void 0:n.lift)}function Mr(n){return function(e){if(WOe(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function zn(n,e,t,r,i){return new zOe(n,e,t,r,i)}var zOe=function(n){oo(e,n);function e(t,r,i,s,o,a){var c=n.call(this,t)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(l){try{r(l)}catch(u){t.error(u)}}:n.prototype._next,c._error=s?function(l){try{s(l)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=i?function(){try{i()}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._complete,c}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(WL),YOe=jJ(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Rr=function(n){oo(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new GD(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new YOe},e.prototype.next=function(t){var r=this;lb(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=du(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(t)}}catch(l){i={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(t){var r=this;lb(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var i=r.observers;i.length;)i.shift().error(t)}})},e.prototype.complete=function(){var t=this;lb(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?$J:(this.currentObservers=null,a.push(t),new Ry(function(){r.currentObservers=null,OS(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new Ln;return t.source=this,t},e.create=function(t,r){return new GD(t,r)},e}(Ln),GD=function(n){oo(e,n);function e(t,r){var i=n.call(this)||this;return i.destination=t,i.source=r,i}return e.prototype.next=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,t)},e.prototype.error=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&i!==void 0?i:$J},e}(Rr),is=function(n){oo(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,i=t.thrownError,s=t._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e}(Rr),YL={now:function(){return(YL.delegate||Date).now()},delegate:void 0},XOe=function(n){oo(e,n);function e(t,r,i){t===void 0&&(t=1/0),r===void 0&&(r=1/0),i===void 0&&(i=YL);var s=n.call(this)||this;return s._bufferSize=t,s._windowTime=r,s._timestampProvider=i,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,t),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(t){var r=this,i=r.isStopped,s=r._buffer,o=r._infiniteTimeWindow,a=r._timestampProvider,c=r._windowTime;i||(s.push(t),!o&&s.push(a.now()+c)),this._trimBuffer(),n.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(t),i=this,s=i._infiniteTimeWindow,o=i._buffer,a=o.slice(),c=0;c<a.length&&!t.closed;c+=s?1:2)t.next(a[c]);return this._checkFinalizedStatuses(t),r},e.prototype._trimBuffer=function(){var t=this,r=t._bufferSize,i=t._timestampProvider,s=t._buffer,o=t._infiniteTimeWindow,a=(o?1:2)*r;if(r<1/0&&a<s.length&&s.splice(0,s.length-a),!o){for(var c=i.now(),l=0,u=1;u<s.length&&s[u]<=c;u+=2)l=u;l&&s.splice(0,l+1)}},e}(Rr),JOe=function(n){oo(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(Ry),qD={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,io([n,e],ro(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},ZOe=function(n){oo(e,n);function e(t,r){var i=n.call(this,t,r)||this;return i.scheduler=t,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(t,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,r)),this.pending=!0,this.delay=r,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(o,this.id,r),this},e.prototype.requestAsyncId=function(t,r,i){return i===void 0&&(i=0),qD.setInterval(t.flush.bind(t,this),i)},e.prototype.recycleAsyncId=function(t,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&qD.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var i=!1,s;try{this.work(t)}catch(o){i=!0,s=o||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,i=t.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,OS(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(JOe),KD=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=YL.now,n}(),QOe=function(n){oo(e,n);function e(t,r){r===void 0&&(r=KD.now);var i=n.call(this,t,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,i){for(;t=r.shift();)t.unsubscribe();throw i}},e}(KD),mE=new QOe(ZOe),eMe=mE,NS=new Ln(function(n){return n.complete()});function VJ(n){return n&&Wt(n.schedule)}function XL(n){return n[n.length-1]}function JL(n){return Wt(XL(n))?n.pop():void 0}function ky(n){return VJ(XL(n))?n.pop():void 0}function tMe(n,e){return typeof XL(n)=="number"?n.pop():e}var ZL=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function GJ(n){return Wt(n==null?void 0:n.then)}function qJ(n){return Wt(n[zL])}function KJ(n){return Symbol.asyncIterator&&Wt(n==null?void 0:n[Symbol.asyncIterator])}function WJ(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function nMe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var zJ=nMe();function YJ(n){return Wt(n==null?void 0:n[zJ])}function XJ(n){return j6(this,arguments,function(){var t,r,i,s;return Jw(this,function(o){switch(o.label){case 0:t=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Rc(t.read())];case 3:return r=o.sent(),i=r.value,s=r.done,s?[4,Rc(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Rc(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function JJ(n){return Wt(n==null?void 0:n.getReader)}function yr(n){if(n instanceof Ln)return n;if(n!=null){if(qJ(n))return rMe(n);if(ZL(n))return iMe(n);if(GJ(n))return sMe(n);if(KJ(n))return ZJ(n);if(YJ(n))return oMe(n);if(JJ(n))return aMe(n)}throw WJ(n)}function rMe(n){return new Ln(function(e){var t=n[zL]();if(Wt(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function iMe(n){return new Ln(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function sMe(n){return new Ln(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,HJ)})}function oMe(n){return new Ln(function(e){var t,r;try{for(var i=du(n),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e.complete()})}function ZJ(n){return new Ln(function(e){cMe(n,e).catch(function(t){return e.error(t)})})}function aMe(n){return ZJ(XJ(n))}function cMe(n,e){var t,r,i,s;return U6(this,void 0,void 0,function(){var o,a;return Jw(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),t=$6(n),c.label=1;case 1:return[4,t.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),i={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Xl(n,e,t,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function QJ(n,e){return e===void 0&&(e=0),Mr(function(t,r){t.subscribe(zn(r,function(i){return Xl(r,n,function(){return r.next(i)},e)},function(){return Xl(r,n,function(){return r.complete()},e)},function(i){return Xl(r,n,function(){return r.error(i)},e)}))})}function eZ(n,e){return e===void 0&&(e=0),Mr(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function lMe(n,e){return yr(n).pipe(eZ(e),QJ(e))}function uMe(n,e){return yr(n).pipe(eZ(e),QJ(e))}function dMe(n,e){return new Ln(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function hMe(n,e){return new Ln(function(t){var r;return Xl(t,e,function(){r=n[zJ](),Xl(t,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){t.error(a);return}o?t.complete():t.next(s)},0,!0)}),function(){return Wt(r==null?void 0:r.return)&&r.return()}})}function tZ(n,e){if(!n)throw new Error("Iterable cannot be null");return new Ln(function(t){Xl(t,e,function(){var r=n[Symbol.asyncIterator]();Xl(t,e,function(){r.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}function fMe(n,e){return tZ(XJ(n),e)}function pMe(n,e){if(n!=null){if(qJ(n))return lMe(n,e);if(ZL(n))return dMe(n,e);if(GJ(n))return uMe(n,e);if(KJ(n))return tZ(n,e);if(YJ(n))return hMe(n,e);if(JJ(n))return fMe(n,e)}throw WJ(n)}function xy(n,e){return e?pMe(n,e):yr(n)}function Ct(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n);return xy(n,t)}function mMe(n){return!!n&&(n instanceof Ln||Wt(n.lift)&&Wt(n.subscribe))}function gMe(n){return n instanceof Date&&!isNaN(n)}function Fe(n,e){return Mr(function(t,r){var i=0;t.subscribe(zn(r,function(s){r.next(n.call(e,s,i++))}))})}var vMe=Array.isArray;function yMe(n,e){return vMe(e)?n.apply(void 0,io([],ro(e))):n(e)}function QL(n){return Fe(function(e){return yMe(n,e)})}var _Me=Array.isArray,bMe=Object.getPrototypeOf,SMe=Object.prototype,wMe=Object.keys;function nZ(n){if(n.length===1){var e=n[0];if(_Me(e))return{args:e,keys:null};if(EMe(e)){var t=wMe(e);return{args:t.map(function(r){return e[r]}),keys:t}}}return{args:n,keys:null}}function EMe(n){return n&&typeof n=="object"&&bMe(n)===SMe}function rZ(n,e){return n.reduce(function(t,r,i){return t[r]=e[i],t},{})}function On(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n),r=JL(n),i=nZ(n),s=i.args,o=i.keys;if(s.length===0)return xy([],t);var a=new Ln(CMe(s,t,o?function(c){return rZ(o,c)}:Eu));return r?a.pipe(QL(r)):a}function CMe(n,e,t){return t===void 0&&(t=Eu),function(r){WD(e,function(){for(var i=n.length,s=new Array(i),o=i,a=i,c=function(u){WD(e,function(){var h=xy(n[u],e),p=!1;h.subscribe(zn(r,function(m){s[u]=m,p||(p=!0,a--),a||r.next(t(s.slice()))},function(){--o||r.complete()}))},r)},l=0;l<i;l++)c(l)},r)}}function WD(n,e,t){n?Xl(t,n,e):e()}function TMe(n,e,t,r,i,s,o,a){var c=[],l=0,u=0,h=!1,p=function(){h&&!c.length&&!l&&e.complete()},m=function(g){return l<r?v(g):c.push(g)},v=function(g){l++;var S=!1;yr(t(g,u++)).subscribe(zn(e,function(b){e.next(b)},function(){S=!0},void 0,function(){if(S)try{l--;for(var b=function(){var R=c.shift();o||v(R)};c.length&&l<r;)b();p()}catch(R){e.error(R)}}))};return n.subscribe(zn(e,m,function(){h=!0,p()})),function(){}}function Py(n,e,t){return t===void 0&&(t=1/0),Wt(e)?Py(function(r,i){return Fe(function(s,o){return e(r,s,i,o)})(yr(n(r,i)))},t):(typeof e=="number"&&(t=e),Mr(function(r,i){return TMe(r,i,n,t)}))}function iZ(n){return n===void 0&&(n=1/0),Py(Eu,n)}function IMe(){return iZ(1)}function DS(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return IMe()(xy(n,ky(n)))}function RMe(n){return new Ln(function(e){yr(n()).subscribe(e)})}function kMe(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=JL(n),r=nZ(n),i=r.args,s=r.keys,o=new Ln(function(a){var c=i.length;if(!c){a.complete();return}for(var l=new Array(c),u=c,h=c,p=function(v){var g=!1;yr(i[v]).subscribe(zn(a,function(S){g||(g=!0,h--),l[v]=S},function(){return u--},void 0,function(){(!u||!g)&&(h||a.next(s?rZ(s,l):l),a.complete())}))},m=0;m<c;m++)p(m)});return t?o.pipe(QL(t)):o}var xMe=["addListener","removeListener"],PMe=["addEventListener","removeEventListener"],LMe=["on","off"];function Ta(n,e,t,r){if(Wt(t)&&(r=t,t=void 0),r)return Ta(n,e,t).pipe(QL(r));var i=ro(MMe(n)?PMe.map(function(a){return function(c){return n[a](e,c,t)}}):AMe(n)?xMe.map(zD(n,e)):OMe(n)?LMe.map(zD(n,e)):[],2),s=i[0],o=i[1];if(!s&&ZL(n))return Py(function(a){return Ta(a,e,t)})(yr(n));if(!s)throw new TypeError("Invalid event target");return new Ln(function(a){var c=function(){for(var l=[],u=0;u<arguments.length;u++)l[u]=arguments[u];return a.next(1<l.length?l:l[0])};return s(c),function(){return o(c)}})}function zD(n,e){return function(t){return function(r){return n[t](e,r)}}}function AMe(n){return Wt(n.addListener)&&Wt(n.removeListener)}function OMe(n){return Wt(n.on)&&Wt(n.off)}function MMe(n){return Wt(n.addEventListener)&&Wt(n.removeEventListener)}function jl(n,e,t){n===void 0&&(n=0),t===void 0&&(t=eMe);var r=-1;return e!=null&&(VJ(e)?t=e:r=e),new Ln(function(i){var s=gMe(n)?+n-t.now():n;s<0&&(s=0);var o=0;return t.schedule(function(){i.closed||(i.next(o++),0<=r?this.schedule(void 0,r):i.complete())},s)})}function Ex(n,e){return n===void 0&&(n=0),e===void 0&&(e=mE),n<0&&(n=0),jl(n,n,e)}function Bv(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n),r=tMe(n,1/0),i=n;return i.length?i.length===1?yr(i[0]):iZ(r)(xy(i,t)):NS}var NMe=Array.isArray;function DMe(n){return n.length===1&&NMe(n[0])?n[0]:n}function Vo(n,e){return Mr(function(t,r){var i=0;t.subscribe(zn(r,function(s){return n.call(e,s,i++)&&r.next(s)}))})}function FMe(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return n=DMe(n),n.length===1?yr(n[0]):new Ln(UMe(n))}function UMe(n){return function(e){for(var t=[],r=function(s){t.push(yr(n[s]).subscribe(zn(e,function(o){if(t){for(var a=0;a<t.length;a++)a!==s&&t[a].unsubscribe();t=null}e.next(o)})))},i=0;t&&!e.closed&&i<n.length;i++)r(i)}}function jMe(n){return Mr(function(e,t){var r=!1,i=null,s=null,o=!1,a=function(){if(s==null||s.unsubscribe(),s=null,r){r=!1;var l=i;i=null,t.next(l)}o&&t.complete()},c=function(){s=null,o&&t.complete()};e.subscribe(zn(t,function(l){r=!0,i=l,s||yr(n(l)).subscribe(s=zn(t,a,c))},function(){o=!0,(!r||!s||s.closed)&&t.complete()}))})}function $Me(n,e,t,r,i){return function(s,o){var a=t,c=e,l=0;s.subscribe(zn(o,function(u){var h=l++;c=a?n(c,u,h):(a=!0,u),o.next(c)},i))}}function Cx(n){return n<=0?function(){return NS}:Mr(function(e,t){var r=0;e.subscribe(zn(t,function(i){++r<=n&&(t.next(i),n<=r&&t.complete())}))})}function BMe(n){return Fe(function(){return n})}function HMe(n,e){return Py(function(t,r){return yr(n(t,r)).pipe(Cx(1),BMe(t))})}function VMe(n,e){e===void 0&&(e=mE);var t=jl(n,e);return HMe(function(){return t})}function ba(n,e){return e===void 0&&(e=Eu),n=n??GMe,Mr(function(t,r){var i,s=!0;t.subscribe(zn(r,function(o){var a=e(o);(s||!n(i,a))&&(s=!1,i=a,r.next(o))}))})}function GMe(n,e){return n===e}function qMe(n,e){return ba(function(t,r){return t[n]===r[n]})}function sZ(n){return Mr(function(e,t){try{e.subscribe(t)}finally{t.add(n)}})}function tc(n,e){return Mr($Me(n,e,arguments.length>=2,!0))}function KMe(n){n===void 0&&(n={});var e=n.connector,t=e===void 0?function(){return new Rr}:e,r=n.resetOnError,i=r===void 0?!0:r,s=n.resetOnComplete,o=s===void 0?!0:s,a=n.resetOnRefCountZero,c=a===void 0?!0:a;return function(l){var u,h,p,m=0,v=!1,g=!1,S=function(){h==null||h.unsubscribe(),h=void 0},b=function(){S(),u=p=void 0,v=g=!1},R=function(){var k=u;b(),k==null||k.unsubscribe()};return Mr(function(k,I){m++,!g&&!v&&S();var T=p=p??t();I.add(function(){m--,m===0&&!g&&!v&&(h=j2(R,c))}),T.subscribe(I),!u&&m>0&&(u=new $v({next:function(C){return T.next(C)},error:function(C){g=!0,S(),h=j2(b,i,C),T.error(C)},complete:function(){v=!0,S(),h=j2(b,o),T.complete()}}),yr(k).subscribe(u))})(l)}}function j2(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];if(e===!0){n();return}if(e!==!1){var i=new $v({next:function(){i.unsubscribe(),n()}});return yr(e.apply(void 0,io([],ro(t)))).subscribe(i)}}function WMe(n,e,t){var r,i,s,o,a=!1;return n&&typeof n=="object"?(r=n.bufferSize,o=r===void 0?1/0:r,i=n.windowTime,e=i===void 0?1/0:i,s=n.refCount,a=s===void 0?!1:s,t=n.scheduler):o=n??1/0,KMe({connector:function(){return new XOe(o,e,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:a})}function zMe(n){return Vo(function(e,t){return n<=t})}function ln(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n);return Mr(function(r,i){(t?DS(n,r,t):DS(n,r)).subscribe(i)})}function At(n,e){return Mr(function(t,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};t.subscribe(zn(r,function(c){i==null||i.unsubscribe();var l=0,u=s++;yr(n(c,u)).subscribe(i=zn(r,function(h){return r.next(e?e(c,h,u,l++):h)},function(){i=null,a()}))},function(){o=!0,a()}))})}function YMe(){return At(Eu)}function XMe(n,e){return Mr(function(t,r){var i=e;return At(function(s,o){return n(i,s,o)},function(s,o){return i=o,o})(t).subscribe(r),function(){i=null}})}function JMe(n){return Mr(function(e,t){yr(n).subscribe(zn(t,function(){return t.complete()},MS)),!t.closed&&e.subscribe(t)})}function ZMe(n,e,t){var r=Wt(n)||e||t?{next:n,error:e,complete:t}:n;return r?Mr(function(i,s){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var a=!0;i.subscribe(zn(s,function(c){var l;(l=r.next)===null||l===void 0||l.call(r,c),s.next(c)},function(){var c;a=!1,(c=r.complete)===null||c===void 0||c.call(r),s.complete()},function(c){var l;a=!1,(l=r.error)===null||l===void 0||l.call(r,c),s.error(c)},function(){var c,l;a&&((c=r.unsubscribe)===null||c===void 0||c.call(r)),(l=r.finalize)===null||l===void 0||l.call(r)}))}):Eu}function Tx(n,e){return Mr(function(t,r){var i=e??{},s=i.leading,o=s===void 0?!0:s,a=i.trailing,c=a===void 0?!1:a,l=!1,u=null,h=null,p=!1,m=function(){h==null||h.unsubscribe(),h=null,c&&(S(),p&&r.complete())},v=function(){h=null,p&&r.complete()},g=function(b){return h=yr(n(b)).subscribe(zn(r,m,v))},S=function(){if(l){l=!1;var b=u;u=null,r.next(b),!p&&g(b)}};t.subscribe(zn(r,function(b){l=!0,u=b,!(h&&!h.closed)&&(o?S():g(b))},function(){p=!0,!(c&&l&&h&&!h.closed)&&r.complete()}))})}function QMe(n,e,t){e===void 0&&(e=mE);var r=jl(n,e);return Tx(function(){return r},t)}function e5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=JL(n);return Mr(function(r,i){for(var s=n.length,o=new Array(s),a=n.map(function(){return!1}),c=!1,l=function(h){yr(n[h]).subscribe(zn(i,function(p){o[h]=p,!c&&!a[h]&&(a[h]=!0,(c=a.every(Eu))&&(a=null))},MS))},u=0;u<s;u++)l(u);r.subscribe(zn(i,function(h){if(c){var p=io([h],ro(o));i.next(t?t.apply(void 0,io([],ro(p))):p)}}))})}function t5e(n,e,t){if(!t)return _.useState(e)[0];const[r]=_.useState(()=>new is(t)),[i]=_.useState(()=>e(r)),s=_.useRef(!0);return n(()=>{if(s.current){s.current=!1;return}r.next(t)},t),i}function Hv(n,e){return t5e(_.useEffect,n,e)}var n5e=()=>new Rr,r5e=n=>n+1|0,i5e=()=>{const n=_.useState(0)[1];return _.useRef(()=>n(r5e)).current},oZ=typeof window>"u"?_.useEffect:_.useLayoutEffect,YD=n=>{var e;return(e=n[1])!=null&&e.next?n[1]:{next:n[1],error:n[2],complete:n[3]}};function s5e(n,e){const t=_.useRef(e),r=_.useRef(),i=_.useRef();return oZ(()=>{t.current=e,r.current=YD(e)}),n(()=>{const s=t.current[0];r.current||(r.current=YD(t.current));const o=s.subscribe({next:a=>{var c,l;s===t.current[0]&&((l=(c=r.current).next)==null||l.call(c,a))},error:a=>{s===t.current[0]&&(r.current.error?r.current.error(a):console.error(a))},complete:()=>{var a,c;s===t.current[0]&&((c=(a=r.current).complete)==null||c.call(a))}});return i.current=o,()=>{o.unsubscribe()}},[e[0]]),i}function o5e(n,e,t,r){return s5e(_.useEffect,[n,e,t,r])}function a5e(n,e,t){if(mMe(e)){const r=e,[i,s]=_.useState(()=>r instanceof is||r.value!==void 0?r.value:t);return n(r,s),_.useDebugValue(i),i}else{const r=e,[i,s]=_.useState(t),[o]=_.useState(n5e),[a]=_.useState(()=>r(o,i)),c=_.useRef(l=>o.next(l)).current;return n(a,s),_.useDebugValue(i),[i,c]}}function Vv(n,e){return a5e(o5e,n,e)}function ot(n){const e=i5e(),t=_.useRef(n),r=_.useRef(),i=_.useRef(!1),s=_.useRef(!1),[o,a]=_.useState(()=>{let c;return n.subscribe({next:l=>{s.current=!0,c=l},error:l=>{r.current=l}}).unsubscribe(),c});if(oZ(()=>{t.current=n}),_.useEffect(()=>{r.current=null;const c=t.current;let l=o;const u=c.subscribe({next:h=>{c===t.current&&(i.current?a(()=>h):l=h)},error:h=>{c===t.current&&(r.current=h,e())}});return i.current||l!==o&&a(()=>l),i.current=!0,()=>{u.unsubscribe()}},[n]),r.current)throw r.current;if(s.current)return _.useDebugValue(o),o;throw new Error("Observable did not synchronously emit a value.")}function c5e(n){const[e]=_.useState(()=>new is(n)),[t]=_.useState(()=>({get current(){return e.value},set current(r){e.next(r)}}));return[t,e]}class Ri{constructor(e,t){this.defaultValue=t,this.setValue=s=>{this._value$.next(s),localStorage.setItem(this.key,JSON.stringify(s))},this.key=`matrix-setting-${e}`;const r=localStorage.getItem(this.key);let i=t;if(r!==null)try{i=JSON.parse(r)}catch(s){M.warn(`Invalid value stored for setting ${e}: ${r}.`,s)}this._value$=new is(i),this.value$=this._value$}}function Ar(n){return[ot(n.value$),n.setValue]}const Ix=new Ri("opt-in-analytics",null),gE=()=>{const n=Ar(Ix);return jt.instance.isEnabled()?n:[!1,null]},aZ=new Ri("developer-settings-tab",!1),cZ=new Ri("duplicate-tiles",0),lZ=new Ri("show-non-member-tiles",!1),e4=new Ri("debug-tile-layout",!1),Gv=new Ri("show-connection-stats",!1),l5e=new Ri("audio-input",void 0),u5e=new Ri("audio-output",void 0),d5e=new Ri("video-input",void 0),uZ=new Ri("hand-raised-show-timer",!1),dZ=new Ri("reactions-show",!0),t4=new Ri("reactions-play-sound",!0),hZ=new Ri("sound-effect-volume",.5),fZ=new Ri("new-membership-manager",!0),XD=new Ri("always-show-self",!0);var vE=(n=>(n[n.Guest=0]="Guest",n[n.Registered=1]="Registered",n))(vE||{});const Co=class Co{constructor(e){var r,i;this.posthog=e,this.enabled=!1,this.anonymity=0,this.platformSuperProperties={},this.registrationType=0,this.sanitizeProperties=(s,o)=>(this.anonymity==1&&(s.$referrer=null,s.$referring_domain=null,s.$initial_referrer=null,s.$initial_referring_domain=null,s.$device_id=null),s.$current_url=s.$current_url.split("/").slice(0,3).join(""),s),this.eventCallEnded=new xOe,this.eventSignup=new LOe,this.eventCallStarted=new POe,this.eventLogin=new AOe,this.eventMuteMicrophone=new OOe,this.eventMuteCamera=new MOe,this.eventUndecryptableToDevice=new NOe,this.eventQualitySurvey=new DOe,this.eventCallDisconnected=new FOe,this.eventCallConnectDuration=new UOe;const t={project_api_key:(r=gt.get().posthog)==null?void 0:r.api_key,api_host:(i=gt.get().posthog)==null?void 0:i.api_host};if(t.project_api_key&&t.api_host){if(Co.getPlatformProperties().matrixBackend==="embedded"){const{analyticsID:s}=Rs();Ix.setValue(!!s)}this.posthog.init(t.project_api_key,{api_host:t.api_host,autocapture:!1,mask_all_text:!0,mask_all_element_attributes:!0,capture_pageview:!1,sanitize_properties:this.sanitizeProperties,respect_dnt:!0,advanced_disable_decide:!0}),this.enabled=!0}else M.info("Posthog is not enabled because there is no api key or no host given in the config"),this.enabled=!1;this.startListeningToSettingsChanges()}static hasInstance(){return!!this.internalInstance}static get instance(){return this.internalInstance||(this.internalInstance=new Co(rOe)),this.internalInstance}registerSuperProperties(e){this.enabled&&this.posthog.register(e)}static getPlatformProperties(){var t,r;return{appVersion:"embedded-v0.9.0-release-test.8",matrixBackend:Je?"embedded":"jssdk",callBackend:"livekit",cryptoVersion:Je||(r=(t=window.matrixclient)==null?void 0:t.getCrypto())==null?void 0:r.getVersion()}}capture(e,t,r){this.enabled&&this.posthog.capture(e,{...t},r)}isEnabled(){return this.enabled}setAnonymity(e){this.enabled&&(e==0||e==1)&&(this.posthog.reset(),this.updateSuperProperties()),this.anonymity=e}static getRandomAnalyticsId(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16)).join("")}async identifyUser(e){if(this.anonymity==2&&this.enabled){let t=await this.getAnalyticsId();try{if(!t&&!Je){const r=e();await this.setAccountAnalyticsId(r),t=await this.hashedEcAnalyticsId(r)}}catch(r){M.log("Unable to identify user for tracking"+(r==null?void 0:r.toString()))}t?this.posthog.identify(t):M.info("No analyticsID is available. Should not try to setup posthog")}}async getAnalyticsId(){const e=window.matrixclient;let t;if(Je)t=Rs().analyticsID;else{const r=await e.getAccountDataFromServer(Co.ANALYTICS_EVENT_TYPE);t=(r==null?void 0:r.id)??null}return t?await this.hashedEcAnalyticsId(t):null}async hashedEcAnalyticsId(e){const t=window.matrixclient,r="ec"+e+t.getUserId(),i=await crypto.subtle.digest("sha-256",aOe.Buffer.from(r,"utf-8")),s=new Int32Array(i);return Array.from(s).map(o=>Math.abs(o).toString(16).padStart(2,"0")).join("")}async setAccountAnalyticsId(e){if(!Je){const t=window.matrixclient,r=await t.getAccountDataFromServer(Co.ANALYTICS_EVENT_TYPE);await t.setAccountData(Co.ANALYTICS_EVENT_TYPE,Object.assign({id:e},r))}}getAnonymity(){return this.anonymity}logout(){this.enabled&&this.posthog.reset(),this.setAnonymity(0)}onLoginStatusChanged(){this.maybeIdentifyUser().catch(()=>M.log("Could not identify user on login status change"))}updateSuperProperties(){this.platformSuperProperties=Co.getPlatformProperties(),this.registerSuperProperties({...this.platformSuperProperties,registrationType:this.registrationType==0?"Guest":"Registered"})}userRegisteredInThisSession(){return this.eventSignup.getSignupEndTime()>new Date(0)}async maybeIdentifyUser(){window.matrixclient&&(this.anonymity===2&&(this.setRegistrationType(window.matrixclient.isGuest()||window.passwordlessUser?0:1),this.identificationPromise=this.identifyUser(Co.getRandomAnalyticsId),await this.identificationPromise,this.userRegisteredInThisSession()&&this.eventSignup.track()),this.anonymity!==0&&this.updateSuperProperties())}trackEvent({eventName:e,...t},r){const i=()=>{this.anonymity==0||this.anonymity==1||this.capture(e,t,r)};this.identificationPromise?this.identificationPromise.then(i,s=>{M.error("Failed to identify user for tracking",s)}):i()}startListeningToSettingsChanges(){Ix.value$.subscribe(e=>{this.setAnonymity(e?2:0),this.maybeIdentifyUser().catch(()=>M.log("Could not identify user"))})}setRegistrationType(e){this.registrationType=e,!(this.anonymity==0||this.anonymity==1)&&this.updateSuperProperties()}};Co.ANALYTICS_EVENT_TYPE="im.vector.analytics",Co.internalInstance=null;let jt=Co;const h5e=2*60*1e3;class f5e{async forceFlush(){}onStart(e){try{switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipStart(e);return;case"matrix.groupCallMembership.summaryReport":this.onSummaryReportStart(e);return}}catch(t){M.debug(t)}}onEnd(e){switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipEnd(e);return}}get prevCall(){const e=localStorage.getItem("matrix-prev-call");if(e===null)return null;try{return JSON.parse(e)}catch(t){return M.warn("Invalid prev call data",e,"error:",t),null}}set prevCall(e){localStorage.setItem("matrix-prev-call",JSON.stringify(e))}onGroupCallMembershipStart(e){const t=this.prevCall,r=e.attributes["matrix.confId"];if(t!==null&&r===t.callId){const i=I7(e.startTime)-t.hangupTs;i<=h5e&&jt.instance.trackEvent({eventName:"Rejoin",callId:t.callId,rejoinDuration:i})}}onGroupCallMembershipEnd(e){this.prevCall={callId:e.attributes["matrix.confId"],hangupTs:I7(e.endTime)}}onSummaryReportStart(e){const t=e.events.find(r=>r.name==="matrix.stats.summary");if(t!==void 0){const r=t.attributes;if(r){const i=`${r["matrix.stats.summary.percentageReceivedMedia"]}`,s=`${r["matrix.stats.summary.percentageReceivedVideoMedia"]}`,o=`${r["matrix.stats.summary.percentageReceivedAudioMedia"]}`,a=`${r["matrix.stats.summary.maxJitter"]}`,c=`${r["matrix.stats.summary.maxPacketLoss"]}`,l=`${r["matrix.stats.summary.peerConnections"]}`,u=`${r["matrix.stats.summary.percentageConcealedAudio"]}`,h=`${r["matrix.stats.summary.opponentUsersInCall"]}`,p=`${r["matrix.stats.summary.opponentDevicesInCall"]}`,m=`${r["matrix.stats.summary.diffDevicesToPeerConnections"]}`,v=`${r["matrix.stats.summary.ratioPeerConnectionToDevices"]}`;jt.instance.trackEvent({eventName:"MediaReceived",callId:e.attributes["matrix.confId"],mediaReceived:i,audioReceived:o,videoReceived:s,maxJitter:a,maxPacketLoss:c,peerConnections:l,percentageConcealedAudio:u,opponentUsersInCall:h,opponentDevicesInCall:p,diffDevicesToPeerConnections:m,ratioPeerConnectionToDevices:v},{send_instantly:!0})}}}async shutdown(){return Promise.resolve()}}const JD=n=>Object.entries(n).map(([e,t])=>({key:e,type:typeof t,value:t}));class p5e{constructor(){this.spans=[]}async forceFlush(){}onStart(e){this.spans.push(e)}onEnd(){}dump(){const e=Date.now()*1e3,t=new Map;for(const s of this.spans){const o=s.spanContext().traceId;let a=t.get(o);a===void 0&&(a=[],t.set(o,a)),a.push(s)}const r="p1",i={[r]:{serviceName:"element-call",tags:[]},warnings:null};return JSON.stringify({total:0,limit:0,offset:0,errors:null,data:[...t.entries()].map(([s,o])=>({traceID:s,warnings:null,processes:i,spans:o.map(a=>{const c=a.spanContext(),l=S2(a.startTime),u=a.duration[0]===-1?e-l:S2(a.duration);return{traceID:s,spanID:c.spanId,operationName:a.name,processID:r,warnings:null,startTime:l,duration:u,references:a.parentSpanId===void 0?[]:[{refType:"CHILD_OF",traceID:s,spanID:a.parentSpanId}],tags:JD(a.attributes),logs:a.events.map(h=>({timestamp:S2(h.time),fields:[...JD(h.attributes??{}),{key:"event",type:"string",value:h.name}]}))}})}))})}async shutdown(){}}const m5e="element-call";let Ku;class yE{static globalInit(){var r,i,s;const e=gt.get(),t=!!((r=e.opentelemetry)!=null&&r.collector_url);(!Ku||Ku.isOtlpEnabled!==t)&&(M.info("(Re)starting OpenTelemetry debug reporting"),Ku==null||Ku.dispose(),Ku=new yE((i=e.opentelemetry)==null?void 0:i.collector_url,(s=e.rageshake)==null?void 0:s.submit_url))}static get instance(){return Ku}constructor(e,t){const r={resource:new z3({[I4e.SERVICE_NAME]:m5e})};this._provider=new J6e(r),e?(M.info("Enabling OTLP collector with URL "+e),this.otlpExporter=new K6e({url:e}),this._provider.addSpanProcessor(new $Pe(this.otlpExporter))):M.info("OTLP collector disabled"),t&&(this.rageshakeProcessor=new p5e,this._provider.addSpanProcessor(this.rageshakeProcessor)),this._provider.addSpanProcessor(new f5e),y2.trace.setGlobalTracerProvider(this._provider),this._tracer=y2.trace.getTracer("my-element-call-otl-tracer")}dispose(){var e;y2.trace.disable(),(e=this._provider)==null||e.shutdown().catch(t=>{M.error("Failed to shutdown OpenTelemetry",t)})}get isOtlpEnabled(){return!!this.otlpExporter}get tracer(){return this._tracer}get provider(){return this._provider}}const ZD=async n=>{const{gzip:e}=await rv(async()=>{const{gzip:r}=await import("./pako.esm-BMdhWMX1.js");return{gzip:r}},[],import.meta.url),t=new TextEncoder().encode(n);return new Blob([e(t)])};async function g5e(n,e){e.append("crypto_version",n.getVersion());const t=await n.getOwnDeviceKeys(),r=[`curve25519:${t.curve25519}`,`ed25519:${t.ed25519}`];e.append("device_keys",r.join(", "));const i=await n.getCrossSigningStatus();e.append("cross_signing_ready",String(await n.isCrossSigningReady())),e.append("cross_signing_key",await n.getCrossSigningKeyId()??"n/a"),e.append("cross_signing_privkey_in_secret_storage",String(i.privateKeysInSecretStorage)),e.append("cross_signing_master_privkey_cached",String(i.privateKeysCachedLocally.masterKey)),e.append("cross_signing_self_signing_privkey_cached",String(i.privateKeysCachedLocally.selfSigningKey)),e.append("cross_signing_user_signing_privkey_cached",String(i.privateKeysCachedLocally.userSigningKey))}async function v5e(n,e,t){const r=n.secretStorage;t.append("secret_storage_ready",String(await e.isSecretStorageReady())),t.append("secret_storage_key_in_account",String(await r.hasKey())),t.append("session_backup_key_in_secret_storage",String(!!await n.isKeyBackupKeyStored()));const i=await e.getSessionBackupPrivateKey();t.append("session_backup_key_cached",String(!!i)),t.append("session_backup_key_well_formed",String(i instanceof Uint8Array))}function n4(){const{client:n}=nh(),[{sending:e,sent:t,error:r},i]=_.useState({sending:!1,sent:!1,error:void 0});return{submitRageshake:_.useCallback(async o=>{var a;if(!((a=gt.get().rageshake)!=null&&a.submit_url))throw new Error("No rageshake URL is configured");if(!e)try{i({sending:!0,sent:!1,error:void 0});let c="UNKNOWN";window.navigator&&window.navigator.userAgent&&(c=window.navigator.userAgent);let l="UNKNOWN";try{l=String(window.matchMedia("(pointer: coarse)").matches)}catch(m){M.warn("Could not get coarse pointer for rageshake submit.",m)}let u=o.rageshakeRequestId?`Rageshake ${o.rageshakeRequestId}`:"";o.description&&(u+=`: ${o.description}`);const h=new FormData;if(h.append("text",u??"User did not supply any additional text."),h.append("app","matrix-video-chat"),h.append("version","embedded-v0.9.0-release-test.8"),h.append("user_agent",c),h.append("installed_pwa","false"),h.append("touch_input",l),h.append("call_backend","livekit"),h.append("hostname",window.location.hostname),n){const m=n.getUserId(),v=n.getUser(m);h.append("display_name",(v==null?void 0:v.displayName)??""),h.append("user_id",n.credentials.userId??""),h.append("device_id",n.deviceId??""),o.roomId&&h.append("room_id",o.roomId);const g=n.getCrypto();g&&(await g5e(g,h),await v5e(n,g,h))}if(o.label&&h.append("label",o.label),navigator.storage&&navigator.storage.persisted)try{h.append("storageManager_persisted",String(await navigator.storage.persisted()))}catch(m){M.warn("coulr not get navigator peristed storage",m)}else if(document.hasStorageAccess)try{h.append("storageManager_persisted",String(await document.hasStorageAccess()))}catch(m){M.warn("could not get storage access",m)}if(navigator.storage&&navigator.storage.estimate)try{const m=await navigator.storage.estimate();h.append("storageManager_quota",String(m.quota)),h.append("storageManager_usage",String(m.usage)),m.usageDetails&&Object.keys(m.usageDetails).forEach(v=>{h.append(`storageManager_usage_${v}`,String(m.usageDetails[v]))})}catch(m){M.warn("could not obatain storage estimate",m)}if(o.sendLogs){const m=await Nke();for(const v of m)h.append("compressed-log",await ZD(v.lines),v.id);h.append("file",await ZD(yE.instance.rageshakeProcessor.dump()),"traces.json.gz")}o.rageshakeRequestId&&h.append("group_call_rageshake_request_id",o.rageshakeRequestId);const p=await fetch(gt.get().rageshake.submit_url,{method:"POST",body:h});if(p.status!==200)throw new Error(`Failed to submit feedback: receive HTTP ${p.status} ${p.statusText}`);i({sending:!1,sent:!0,error:void 0})}catch(c){i({sending:!1,sent:!1,error:c}),M.error(c)}},[n,e]),sending:e,sent:t,error:r}}function y5e(){const{client:n}=nh();return _.useCallback((t,r)=>{n.sendEvent(t,"org.matrix.rageshake_request",{request_id:r}).catch(i=>{M.error("Failed to send org.matrix.rageshake_request event",i)})},[n])}function _5e(n){const[e,t]=_.useState(!1),r=_.useCallback(()=>t(!1),[t]),{client:i}=nh(),[s,o]=_.useState();return _.useEffect(()=>{if(!i)return;const a=c=>{c.getType()==="org.matrix.rageshake_request"&&n===c.getRoomId()&&i.getUserId()!==c.getSender()&&(o(c.getContent().request_id),t(!0))};return i.on(Ge.Event,a),()=>{i.removeListener(Ge.Event,a)}},[t,n,i]),{rageshakeRequestId:s??"",roomId:n,open:e,onDismiss:r}}const b5e=({description:n})=>{var c;const{submitRageshake:e,sending:t,sent:r,error:i}=n4(),{t:s}=Qe(),o=_.useCallback(()=>{e({description:n,sendLogs:!0}).catch(l=>{M.error("Failed to send rageshake",l)})},[e,n]);if(!((c=gt.get().rageshake)!=null&&c.submit_url))return null;let a=null;if(t)a=w.jsx("span",{children:s("rageshake_sending")});else if(r)a=w.jsx("div",{children:s("rageshake_sent")});else{let l=s("rageshake_send_logs");i&&(l=s("rageshake_button_error_caption")),a=w.jsx(Mt,{onClick:o,className:b7.wideButton,disabled:t,children:l})}return w.jsx("div",{className:b7.rageshakeControl,children:a})},S5e="_error_19mk1_1",w5e="_icon_19mk1_9",Y1={error:S5e,icon:w5e},E5e="_endCall_bwclo_8",C5e={endCall:E5e},pZ=({muted:n,...e})=>{const{t}=Qe(),r=n?IY:wL,i=t(n?"unmute_microphone_button_label":"mute_microphone_button_label");return w.jsx(ui,{label:i,children:w.jsx(Mt,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},mZ=({muted:n,...e})=>{const{t}=Qe(),r=n?cIe:WY,i=t(n?"start_video_button_label":"stop_video_button_label");return w.jsx(ui,{label:i,children:w.jsx(Mt,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},gZ=n=>{const{t:e}=Qe();return w.jsx(ui,{label:e("switch_camera"),children:w.jsx(Mt,{iconOnly:!0,Icon:sIe,kind:"secondary",...n})})},T5e=({enabled:n,...e})=>{const{t}=Qe(),r=t(n?"stop_screenshare_button_label":"screenshare_button_label");return w.jsx(ui,{label:r,children:w.jsx(Mt,{iconOnly:!0,Icon:nIe,kind:n?"primary":"secondary",...e})})},vZ=({className:n,...e})=>{const{t}=Qe();return w.jsx(ui,{label:t("hangup_button_label"),children:w.jsx(Mt,{className:De(n,C5e.endCall),iconOnly:!0,Icon:vY,destructive:!0,...e})})},yZ=n=>{const{t:e}=Qe();return w.jsx(ui,{label:e("common.settings"),children:w.jsx(Mt,{iconOnly:!0,Icon:tIe,kind:"secondary",...n})})},I5e="_external_jhjdf_8",R5e={external:I5e};function _Z(n,e){const t=TV(n),r=NV(n,{state:e});return[t,r]}const Aa=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=_Z(e,t);return w.jsx(MEe,{ref:i,...r,href:s,onClick:o})}),bd=_.forwardRef(function({className:e,children:t,...r},i){return w.jsx("a",{ref:i,className:De(e,R5e.external),target:"_blank",rel:"noreferrer noopener",...r,children:t})}),r4=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=_Z(e,t);return w.jsx(Mt,{as:"a",ref:i,...r,href:s,onClick:o})});function bZ(n){const[e,t]=_.useState(n.memberships),r=_.useCallback(()=>{M.info(`Memberships changed for call in room ${n.room.roomId} (${n.memberships.length} members)`),t(n.memberships)},[n]);return _.useEffect(()=>(n.on(ts.MembershipsChanged,r),()=>{n.off(ts.MembershipsChanged,r)}),[n,r]),e}const SZ=_.createContext(void 0),i4=()=>{const n=_.useContext(SZ);if(!n)throw new Error("useReactions must be used within a ReactionsProvider");return n},k5e=({children:n,rtcSession:e,vm:t})=>{const r=bZ(e),i=jp(),s=(i==null?void 0:i.state)==="valid"&&i.supportedFeatures.reactions,o=e.room,a=o.client.getUserId(),c=o.client.getDeviceId(),l=`${a}:${c}`,u=_.useMemo(()=>{var b;return(b=r.find(R=>R.sender===a&&R.deviceId===c))==null?void 0:b.eventId},[r,a,c]),h=ot(t.reactions$),p=_.useMemo(()=>l!==void 0?h[l]:void 0,[l,h]),m=ot(t.handsRaised$),v=_.useMemo(()=>l!==void 0?m[l]:void 0,[l,m]),g=_.useCallback(async()=>{if(!l)return;const b=v==null?void 0:v.reactionEventId;if(b)try{await o.client.redactEvent(e.room.roomId,b),M.debug("Redacted raise hand event")}catch(R){throw M.error("Failed to redact reaction event",b,R),R}else try{if(!u)throw new Error("Cannot find own membership event");const R=await o.client.sendEvent(e.room.roomId,ie.Reaction,{"m.relates_to":{rel_type:sn.Annotation,event_id:u,key:"🖐️"}});M.debug("Sent raise hand event",R.event_id)}catch(R){M.error("Failed to send raised hand",R)}},[u,l,v,e,o]),S=_.useCallback(async b=>{if(!(!l||p)){if(!u)throw new Error("Cannot find own membership event");await o.client.sendEvent(e.room.roomId,KL,{"m.relates_to":{rel_type:sn.Reference,event_id:u},emoji:b.emoji,name:b.name})}},[u,p,o,l,e]);return w.jsx(SZ.Provider,{value:{supportsReactions:s,toggleRaisedHand:g,sendReaction:S},children:n})},x5e="_raisedButton_unw54_1",P5e="_reactionPopupMenu_unw54_5",L5e="_reactionPopupMenuRoot_unw54_21",A5e="_reactionPopupMenuModal_unw54_21",O5e="_reactionsMenuSection_unw54_47",M5e="_reactionsMenu_unw54_47",N5e="_reactionButton_unw54_81",D5e="_verticalSeperator_unw54_91",F5e="_alert_unw54_99",Io={raisedButton:x5e,reactionPopupMenu:P5e,reactionPopupMenuRoot:L5e,reactionPopupMenuModal:A5e,reactionsMenuSection:O5e,reactionsMenu:M5e,reactionButton:N5e,verticalSeperator:D5e,alert:F5e};var wZ=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(j5e);if(s){const o=s.props.children,a=i.map(c=>c===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:c);return w.jsx(Rx,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return w.jsx(Rx,{...r,ref:e,children:t})});wZ.displayName="Slot";var Rx=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=B5e(t),s=$5e(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Va(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});Rx.displayName="SlotClone";var U5e=({children:n})=>w.jsx(w.Fragment,{children:n});function j5e(n){return _.isValidElement(n)&&n.type===U5e}function $5e(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function B5e(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var H5e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],V5e=H5e.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?wZ:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),w.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{}),G5e="VisuallyHidden",kx=_.forwardRef((n,e)=>w.jsx(V5e.span,{...n,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...n.style}}));kx.displayName=G5e;const q5e="_modal_lmgdq_8",K5e="_dialog_lmgdq_14",W5e="_content_lmgdq_21",z5e="_drawer_lmgdq_32",Y5e="_close_lmgdq_59",X5e="_header_lmgdq_84",J5e="_body_lmgdq_114",Z5e="_tabbed_lmgdq_129",Q5e="_handle_lmgdq_133",Ui={modal:q5e,dialog:K5e,content:W5e,drawer:z5e,close:Y5e,header:X5e,body:J5e,tabbed:Z5e,handle:Q5e},eNe="_bg_197ap_8",tNe="_animate_197ap_23",nNe="_overlay_197ap_40",_a={bg:eNe,animate:tNe,overlay:nNe},th=({title:n,hideHeader:e,children:t,className:r,classNameDrawer:i,classNameModal:s,open:o,onDismiss:a,tabbed:c,...l})=>{const{t:u}=Qe(),h=iE("(hover: none) or (pointer: coarse)"),p=_.useCallback(m=>{m||a==null||a()},[a]);if(h)return w.jsx(Ki.Root,{open:o,onOpenChange:p,dismissible:a!==void 0,children:w.jsxs(Ki.Portal,{children:[w.jsx(Ki.Overlay,{className:De(_a.bg)}),w.jsx(Ki.Content,{className:De(r,i,_a.overlay,Ui.modal,Ui.drawer,{[Ui.tabbed]:c}),role:"dialog","aria-describedby":void 0,...l,children:w.jsxs("div",{className:Ui.content,children:[w.jsxs("div",{className:Ui.header,children:[w.jsx("div",{className:Ui.handle}),w.jsx(kx,{asChild:!0,children:w.jsx(Ki.Title,{children:n})})]}),w.jsx("div",{className:Ui.body,children:t})]})})]})});{const m=w.jsx(oL,{asChild:!0,children:w.jsx(Su,{as:"h2",weight:"semibold",size:"md",children:n})}),v=w.jsxs("div",{className:Ui.header,children:[m,a!==void 0&&w.jsx(gz,{className:Ui.close,"data-testid":"modal_close","aria-label":u("action.close"),children:w.jsx(Gw,{width:20,height:20})})]});return w.jsx(nL,{open:o,onOpenChange:p,children:w.jsxs(rL,{children:[w.jsx(iL,{className:De(_a.bg,_a.animate)}),w.jsx(sL,{asChild:!0,"aria-describedby":void 0,role:"dialog",...l,children:w.jsx(kz,{className:De(r,s,_a.overlay,_a.animate,Ui.modal,Ui.dialog,{[Ui.tabbed]:c}),children:w.jsxs("div",{className:Ui.content,children:[e?null:v,e?w.jsx(kx,{asChild:!0,children:m}):null,w.jsx("div",{className:Ui.body,children:t})]})})})]})})}},rNe=({raised:n,open:e,...t})=>{const{t:r}=Qe();return w.jsx(ui,{label:r("common.reactions"),children:w.jsx(Mt,{className:De(n&&Io.raisedButton),"aria-expanded":e,"aria-haspopup":!0,kind:n||e?"primary":"secondary",iconOnly:!0,Icon:n?MY:eIe,...t})})};function iNe({sendReaction:n,toggleRaisedHand:e,isHandRaised:t,canReact:r,errorText:i}){const{t:s}=Qe(),[o,a]=_.useState(!1),c=_.useMemo(()=>o?jv:jv.slice(0,5),[o]),l=s(t?"action.lower_hand":"action.raise_hand");return w.jsxs(w.Fragment,{children:[i&&w.jsx(Q1e,{className:Io.alert,type:"critical",title:s("error.generic"),children:i}),w.jsxs("div",{className:Io.reactionPopupMenu,children:[w.jsx("section",{className:Io.handRaiseSection,children:w.jsx(ui,{label:l,caption:"H",children:w.jsx(Mt,{kind:t?"primary":"secondary","aria-keyshortcuts":"H","aria-pressed":t,"aria-label":l,onClick:()=>e(),iconOnly:!0,Icon:MY})})}),w.jsx("div",{className:Io.verticalSeperator}),w.jsx("section",{className:Io.reactionsMenuSection,children:w.jsx("menu",{className:De(o&&Io.reactionsMenuExpanded,Io.reactionsMenu),children:c.map((u,h)=>w.jsx("li",{children:w.jsx(ui,{label:u.name,caption:h<wx?(h+1).toString():void 0,children:w.jsx(Mt,{kind:"secondary",className:Io.reactionButton,disabled:!r,onClick:()=>n(u),"aria-keyshortcuts":h<wx?(h+1).toString():void 0,children:u.emoji})})},u.name))})}),w.jsx("section",{style:{marginLeft:"var(--cpd-separator-spacing)"},children:w.jsx(ui,{label:s(o?"action.show_less":"action.show_more"),children:w.jsx(Mt,{iconOnly:!0,"aria-label":s(o?"action.show_less":"action.show_more"),Icon:o?VTe:pTe,kind:"tertiary",onClick:()=>a(!o)})})})]})]})}function sNe({identifier:n,vm:e,...t}){const{t:r}=Qe(),{toggleRaisedHand:i,sendReaction:s}=i4(),[o,a]=_.useState(!1),[c,l]=_.useState(!1),[u,h]=_.useState(),p=Vv(e.handsRaised$.pipe(Fe(S=>!!S[n]))),m=Vv(e.reactions$.pipe(Fe(S=>!S[n])));_.useEffect(()=>{h(void 0)},[c]);const v=_.useCallback(async S=>{try{a(!0),await s(S),h(void 0),l(!1)}catch(b){h(b instanceof Error?b.message:"Unknown error"),M.error("Failed to send reaction",b)}finally{a(!1)}},[s]),g=_.useCallback(()=>{(async()=>{try{a(!0),await i(),l(!1)}catch(b){h(b instanceof Error?b.message:"Unknown error"),M.error("Failed to raise/lower hand",b)}finally{a(!1)}})()},[i]);return w.jsxs(w.Fragment,{children:[w.jsx(rNe,{disabled:o,onClick:()=>l(S=>!S),raised:!!p,open:c,...t}),w.jsx(th,{open:c,title:r("action.pick_reaction"),hideHeader:!0,classNameModal:Io.reactionPopupMenuModal,className:Io.reactionPopupMenuRoot,onDismiss:()=>l(!1),children:w.jsx(iNe,{errorText:u,isHandRaised:!!p,canReact:!o&&!!m,sendReaction:S=>void v(S),toggleRaisedHand:g})})]})}const qv=({Icon:n,title:e,rageshake:t,fatal:r,children:i,widget:s})=>{const{t:o}=Qe(),{confineToRoom:a}=eh(),c=_.useCallback(()=>{window.location.href="/"},[]),l=({widget:h})=>{const p=()=>{h.api.transport.send(xr.Close,{}).catch(m=>{M.error("Failed to send close action",m)}).finally(()=>{h.api.transport.stop()})};return w.jsx(Mt,{kind:"primary",onClick:p,children:o("action.close")})},u=()=>r||location.pathname==="/"?w.jsx(Mt,{kind:"tertiary",className:Y1.homeLink,onClick:c,children:o("return_home_button")}):w.jsx(r4,{kind:"tertiary",className:Y1.homeLink,to:"/",children:o("return_home_button")});return w.jsxs("div",{className:Y1.error,children:[w.jsx(cTe,{className:Y1.icon,children:w.jsx(n,{})}),w.jsx(Su,{as:"h1",weight:"semibold",size:"md",children:e}),i,t&&w.jsx(b5e,{description:`***Error View***: ${e}`}),s?w.jsx(l,{widget:s}):!a&&w.jsx(u,{})]})};class EZ extends Error{constructor(e,t){super(e),this.richMessage=t}}const oNe=()=>{const{t:n}=Qe();return w.jsx(qv,{widget:Je,Icon:AY,title:n("error.open_elsewhere"),children:w.jsx("p",{children:n("error.open_elsewhere_description",{brand:"Element Call"})})})};class aNe extends EZ{constructor(){super("App opened in another tab",w.jsx(oNe,{}))}}const Uf=({className:n,children:e})=>{const{hideHeader:t}=eh();return w.jsxs("div",{className:De(u2.page,n),children:[!t&&w.jsxs(wu,{children:[w.jsx(Jd,{children:w.jsx(Dd,{})}),w.jsx(Zd,{})]}),w.jsx("div",{className:u2.container,children:w.jsx("div",{className:u2.content,children:e})})]})},Kv=({error:n,widget:e})=>{const{t}=Qe();return _.useEffect(()=>{M.error(n),jw(n)},[n]),w.jsx(Uf,{children:n instanceof EZ?n.richMessage:w.jsx(qv,{widget:e,Icon:Vw,title:t("error.generic"),rageshake:!0,fatal:!0,children:w.jsx("p",{children:t("error.generic_description")})})})},_E=()=>{const{t:n}=Qe();return w.jsx(Uf,{children:w.jsx("h1",{children:n("common.loading")})})},s4=_.createContext(void 0);s4.Provider;const jp=()=>_.useContext(s4);function nh(){var r;let n,e;const t=jp();return(t==null?void 0:t.state)==="valid"&&(n=(r=t.authenticated)==null?void 0:r.client,e=t.setClient),{client:n,setClient:e}}function o4(){var c,l,u;const n=jp();let e,t,r=!1,i=!0,s,o=!1,a;return(n==null?void 0:n.state)==="valid"?(e=(c=n.authenticated)==null?void 0:c.client,t=n.setClient,r=((l=n.authenticated)==null?void 0:l.isPasswordlessUser)??!1,i=!1,o=e!==void 0,a=(u=n.authenticated)==null?void 0:u.logout):(n==null?void 0:n.state)==="error"&&(s=n.error,i=!1),{client:e,setClient:t,passwordlessUser:r,loading:i,authenticated:o,logout:a,error:s}}const X1="BroadcastChannel"in window?new BroadcastChannel("load"):null,cNe=({children:n})=>{const e=ja(),[t,r]=_.useState(void 0),i=_.useRef(!1);_.useEffect(()=>{i.current||(i.current=!0,lNe().then(r).catch(R=>M.error(R)).finally(()=>i.current=!1))},[]);const s=_.useCallback(async R=>{const k=CZ();!(t!=null&&t.client)||!k||(await t.client.setPassword({type:"m.login.password",identifier:{type:"m.id.user",user:k.user_id},user:k.user_id,password:k.tempPassword},R),QD({...k,passwordlessUser:!1}),r({...t,passwordlessUser:!1}))},[t]),o=_.useCallback(R=>{const k=t==null?void 0:t.client,I=R==null?void 0:R.client;k&&k!==I&&k.stopClient(),R?(QD(R.session),r({widgetApi:null,client:R.client,passwordlessUser:R.session.passwordlessUser})):(xx(),r(null))},[t==null?void 0:t.client]),a=_.useCallback(async()=>{const R=t==null?void 0:t.client;R&&(await R.logout(!0),await R.clearStores(),xx(),r(null),await e("/"),jt.instance.setRegistrationType(vE.Guest))},[e,t==null?void 0:t.client]);_.useEffect(()=>{Je||X1==null||X1.postMessage({})},[]);const[c,l]=_.useState(void 0);Bg(X1,"message",_.useCallback(()=>{t==null||t.client.stopClient(),l(new aNe)},[t==null?void 0:t.client,l]));const[u,h]=_.useState(!1),[p,m]=_.useState(!1),[v,g]=_.useState(!1),S=_.useMemo(()=>c?{state:"error",error:c}:t===void 0?void 0:{state:"valid",authenticated:t===null?void 0:{client:t.client,isPasswordlessUser:t.passwordlessUser,changePassword:s,logout:a},setClient:o,disconnected:u,supportedFeatures:{reactions:p,thumbnails:v}},[c,s,t,a,o,u,p,v]),b=_.useCallback((R,k,I)=>{h(uNe(R,I))},[]);return _.useEffect(()=>{if(t){if(window.matrixclient=t.client,window.passwordlessUser=t.passwordlessUser,jt.hasInstance()&&jt.instance.onLoginStatusChanged(),t.client&&t.client.on(Ge.Sync,b),t.widgetApi){g(!1);const R=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.reaction"),k=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.room.redaction"),I=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.reaction"),T=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.room.redaction");!R||!I||!k||!T?(M.warn("Widget does not support reactions"),m(!1)):m(!0)}else m(!0),g(!0);return()=>{t.client&&t.client.removeListener(Ge.Sync,b)}}},[t,b]),c?w.jsx(Kv,{widget:Je,error:c}):w.jsx(s4.Provider,{value:S,children:n})};async function lNe(){if(Je){M.log("Using a matryoshka client");const n=await Je.client;return{widgetApi:Je.api,client:n,passwordlessUser:!1}}else{const{initSPA:n}=await rv(async()=>{const{initSPA:e}=await import("./spa-DFPpa8E_.js");return{initSPA:e}},[],import.meta.url);return n(CZ,xx)}}const xx=()=>localStorage.removeItem("matrix-auth-store"),QD=n=>localStorage.setItem("matrix-auth-store",JSON.stringify(n)),CZ=()=>{const n=localStorage.getItem("matrix-auth-store");if(n)return JSON.parse(n)},uNe=(n,e)=>{var t;return n==="ERROR"&&((t=e==null?void 0:e.error)==null?void 0:t.name)==="ConnectionError"};function Ly(n){const[{success:e,loading:t,displayName:r,avatarUrl:i,error:s},o]=_.useState(()=>{let c;return n&&(c=n.getUser(n.getUserId())??void 0),{success:!1,loading:!1,displayName:c==null?void 0:c.rawDisplayName,avatarUrl:c==null?void 0:c.avatarUrl,error:void 0}});_.useEffect(()=>{const c=(u,{displayName:h,avatarUrl:p})=>{o({success:!1,loading:!1,displayName:h,avatarUrl:p,error:void 0})};let l;if(n){const u=n.getUserId();l=n.getUser(u),l==null||l.on(Ol.DisplayName,c),l==null||l.on(Ol.AvatarUrl,c)}return()=>{l&&(l.removeListener(Ol.DisplayName,c),l.removeListener(Ol.AvatarUrl,c))}},[n]);const a=_.useCallback(async({displayName:c,avatar:l,removeAvatar:u})=>{if(n){o(h=>({...h,loading:!0,error:void 0,success:!1}));try{await n.setDisplayName(c);let h;u?await n.setAvatarUrl(""):l&&({content_uri:h}=await n.uploadContent(l),await n.setAvatarUrl(h)),o(p=>({...p,displayName:c,avatarUrl:u?void 0:h??p.avatarUrl,loading:!1,success:!0}))}catch(h){o(p=>({...p,loading:!1,error:h instanceof Error?h:Error(h),success:!1}))}}else M.error("Client not initialized before calling saveProfile")},[n]);return{loading:t,error:s,displayName:r,avatarUrl:i,saveProfile:a,success:e}}const dNe="_settingsModal_1dkeq_8",hNe="_volumeSlider_1dkeq_20",eF={settingsModal:dNe,volumeSlider:hNe},fNe="_tabContainer_1nnp9_8",pNe="_tabList_1nnp9_14",tF={tabContainer:fNe,tabList:pNe};function mNe({label:n,tab:e,onTabChange:t,tabs:r}){const i=_.useId();return w.jsxs("div",{className:tF.tabContainer,children:[w.jsx(lTe,{role:"tablist","aria-label":n,className:tF.tabList,children:r.map(({key:s,name:o})=>w.jsx(fTe,{"aria-controls":`${i}[${s}]`,onClick:()=>t(s),active:s===e,children:o}))}),r.map(({key:s,content:o})=>w.jsx("div",{id:`${i}[${s}]`,style:{display:s===e?void 0:"none"},children:o}))]})}const gNe="_fieldRow_iwncy_8",vNe="_field_iwncy_8",yNe="_rightAlign_iwncy_21",_Ne="_inputField_iwncy_33",bNe="_disabled_iwncy_52",SNe="_prefix_iwncy_110",wNe="_checkboxField_iwncy_131",ENe="_checkbox_iwncy_131",CNe="_description_iwncy_168",TNe="_errorMessage_iwncy_197",INe="_noLabel_iwncy_210",js={fieldRow:gNe,field:vNe,rightAlign:yNe,inputField:_Ne,disabled:bNe,prefix:SNe,checkboxField:wNe,checkbox:ENe,description:CNe,errorMessage:TNe,noLabel:INe},RNe=(n,e)=>_.createElement("svg",{fill:"none",height:24,stroke:"#000",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,viewBox:"0 0 24 24",width:24,xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{d:"m20 6-11 11-5-5"})),kNe=_.forwardRef(RNe);class TZ extends Error{constructor(e,t){super(t(e,{lng:"en"})),this.translatedMessage=t(e)}}class xNe extends TZ{}const nF=(n,e)=>new xNe(n,e);function yt({children:n,rightAlign:e,className:t}){return w.jsx("div",{className:De(js.fieldRow,{[js.rightAlign]:e},t),children:n})}function PNe({children:n,className:e}){return w.jsx("div",{className:De(js.field,e),children:n})}const vn=_.forwardRef(({id:n,label:e,className:t,type:r,checked:i,prefix:s,suffix:o,description:a,disabled:c,min:l,...u},h)=>{const p=_.useId();return w.jsxs(PNe,{className:De(r==="checkbox"?js.checkboxField:js.inputField,{[js.prefix]:!!s,[js.disabled]:c},t),children:[s&&w.jsx("span",{children:s}),r==="textarea"?w.jsx("textarea",{id:n,ref:h,disabled:c,"aria-describedby":p,...u}):w.jsx("input",{id:n,ref:h,type:r,checked:i,disabled:c,"aria-describedby":p,min:l,...u}),w.jsxs("label",{htmlFor:n,children:[r==="checkbox"&&w.jsx("div",{className:js.checkbox,children:w.jsx(kNe,{})}),e]}),o&&w.jsx("span",{children:o}),a&&w.jsx("p",{id:p,className:e?js.description:De(js.description,js.noLabel),children:a})]})});vn.displayName="InputField";const Cu=({error:n})=>w.jsx("p",{className:js.errorMessage,children:n instanceof TZ?n.translatedMessage:n.message}),LNe="_avatarInputField_1ep5q_8",ANe="_avatar_1ep5q_8",ONe="_fileInput_1ep5q_17",MNe="_edit_1ep5q_21",J1={avatarInputField:LNe,avatar:ANe,fileInput:ONe,edit:MNe},IZ=({id:n,label:e,className:t,avatarUrl:r,userId:i,displayName:s,onRemoveAvatar:o,...a})=>{const{t:c}=Qe(),[l,u]=_.useState(!1),[h,p]=_.useState(void 0),[m,v]=_.useState(!1),g=_.useRef(null);_.useEffect(()=>{const R=g.current,k=I=>{const T=I;T.target.files&&T.target.files.length>0?(p(URL.createObjectURL(T.target.files[0])),u(!1)):p(void 0)};return R.addEventListener("change",k),()=>{R==null||R.removeEventListener("change",k)}});const S=_.useCallback(()=>{g.current.click()},[g]),b=_.useCallback(()=>{u(!0),o()},[o]);return w.jsxs("div",{className:De(J1.avatarInputField,t),children:[w.jsx(Np,{id:i,className:J1.avatar,name:s,size:Mp.XL,src:l?void 0:h||r}),w.jsx("input",{id:n,accept:"image/*",ref:g,type:"file",className:J1.fileInput,role:"button","aria-label":e,...a}),w.jsx("div",{className:J1.edit,children:(r||h)&&!l?w.jsxs(hL,{title:c("action.edit"),showTitle:!1,open:m,onOpenChange:v,trigger:w.jsx(Mt,{iconOnly:!0,Icon:s7,kind:"tertiary",size:"sm","aria-label":c("action.edit")}),children:[w.jsx(ip,{Icon:rIe,label:c("action.upload_file"),onSelect:S}),w.jsx(ip,{Icon:qTe,label:c("action.remove"),kind:"critical",onSelect:b})]}):w.jsx(Mt,{type:"button",iconOnly:!0,Icon:s7,kind:"tertiary",size:"sm","aria-label":c("action.edit"),onClick:S})})]})};IZ.displayName="AvatarInputField";const NNe="_content_gj715_8",DNe="_avatarFieldRow_gj715_15",rF={content:NNe,avatarFieldRow:DNe},FNe=({client:n})=>{const{t:e}=Qe(),{error:t,displayName:r,avatarUrl:i,saveProfile:s}=Ly(n),o=_.useMemo(()=>n.getUserId(),[n]),a=_.useRef(null),c=_.useRef(!1),l=_.useCallback(()=>{c.current=!0},[]),u=_.useRef(!1),h=_.useCallback(()=>{u.current=!0,c.current=!0},[]);return _.useEffect(()=>{const p=a.current;return()=>{if(c.current){const m=new FormData(p),v=m.get("displayName"),g=m.get("avatar"),S=typeof g=="string"?g.length:(g==null?void 0:g.size)??0,b=typeof v=="string"?v:(v==null?void 0:v.name)??null;if(!b)return;s({displayName:b,avatar:g&&S>0?g:void 0,removeAvatar:u.current&&(!g||S===0)}).catch(R=>{M.error("Failed to save profile",R)})}}},[s]),w.jsxs("form",{onChange:l,ref:a,className:rF.content,children:[w.jsx(yt,{className:rF.avatarFieldRow,children:o&&r&&w.jsx(IZ,{id:"avatar",name:"avatar",label:e("common.avatar"),avatarUrl:i,userId:o,displayName:r,onRemoveAvatar:h})}),w.jsx(yt,{children:w.jsx(vn,{id:"userId",name:"userId",label:e("common.username"),type:"text",disabled:!0,value:n.getUserId()})}),w.jsx(yt,{children:w.jsx(vn,{id:"displayName",name:"displayName",label:e("common.display_name"),type:"text",required:!0,autoComplete:"off",placeholder:e("common.display_name"),defaultValue:r,"data-testid":"profile_displayname"})}),t&&w.jsx(yt,{children:w.jsx(Cu,{error:t})})]})},UNe="_feedback_19yh9_8",RZ={feedback:UNe},a4=()=>w.jsxs(Ci,{i18nKey:"analytics_notice",children:["By participating in this beta, you consent to the collection of anonymous data, which we use to improve the product. You can find more information about which data we track in our"," ",w.jsx(bd,{href:"https://element.io/privacy",children:"Privacy Policy"})," ","and our"," ",w.jsx(bd,{href:"https://element.io/cookie-policy",children:"Cookie Policy"}),"."]}),jNe=({roomId:n})=>{const{t:e}=Qe(),{submitRageshake:t,sending:r,sent:i,error:s}=n4(),o=y5e(),a=_.useCallback(h=>{h.preventDefault();const p=new FormData(h.target),m=p.get("description"),v=typeof m=="string"?m:"",g=!!p.get("sendLogs"),S=Es(16);t({description:v,sendLogs:g,rageshakeRequestId:S,roomId:n}).catch(b=>{M.error("Failed to send feedback rageshake",b)}),n&&g&&o(n,S)},[t,n,o]),[c,l]=gE(),u=w.jsx(Xt,{size:"sm",children:w.jsxs(Ci,{i18nKey:"settings.opt_in_description",children:[w.jsx(a4,{}),w.jsx("br",{}),"You may withdraw consent by unchecking this box. If you are currently in a call, this setting will take effect at the end of the call."]})});return w.jsxs("div",{children:[w.jsx("h4",{children:e("common.analytics")}),w.jsx(yt,{children:w.jsx(vn,{id:"optInAnalytics",type:"checkbox",checked:c??void 0,description:u,onChange:h=>{l==null||l(h.target.checked)}})}),w.jsx("h4",{children:e("settings.feedback_tab_h4")}),w.jsx(Xt,{children:e("settings.feedback_tab_body")}),w.jsxs("form",{onSubmit:a,children:[w.jsx(yt,{children:w.jsx(vn,{className:RZ.feedback,id:"description",name:"description",label:e("settings.feedback_tab_description_label"),placeholder:e("settings.feedback_tab_description_label"),type:"textarea",disabled:r||i})}),!i&&w.jsxs(yt,{children:[w.jsx(vn,{id:"sendLogs",name:"sendLogs",label:e("settings.feedback_tab_send_logs_label"),type:"checkbox",defaultChecked:!0}),w.jsx(Mt,{type:"submit",disabled:r,children:e(r?"submitting":"action.submit")})]}),w.jsxs(yt,{children:[s&&w.jsx(Cu,{error:s}),i&&w.jsx(Xt,{children:e("settings.feedback_tab_thank_you")})]})]})]})};var ub={exports:{}},$Ne=ub.exports,iF;function BNe(){return iF||(iF=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})($Ne,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(g,S){var b=g[S];if(typeof b.bind=="function")return b.bind(g);try{return Function.prototype.bind.call(b,g)}catch{return function(){return Function.prototype.apply.apply(b,[g,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&r?c:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function u(){for(var g=this.getLevel(),S=0;S<i.length;S++){var b=i[S];this[b]=S<g?e:this.methodFactory(b,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function h(g){return function(){typeof console!==t&&(u.call(this),this[g].apply(this,arguments))}}function p(g,S,b){return l(g)||h.apply(this,arguments)}function m(g,S){var b=this,R,k,I,T="loglevel";typeof g=="string"?T+=":"+g:typeof g=="symbol"&&(T=void 0);function C(U){var B=(i[U]||"silent").toUpperCase();if(!(typeof window===t||!T)){try{window.localStorage[T]=B;return}catch{}try{window.document.cookie=encodeURIComponent(T)+"="+B+";"}catch{}}}function P(){var U;if(!(typeof window===t||!T)){try{U=window.localStorage[T]}catch{}if(typeof U===t)try{var B=window.document.cookie,V=encodeURIComponent(T),z=B.indexOf(V+"=");z!==-1&&(U=/^([^;]+)/.exec(B.slice(z+V.length+1))[1])}catch{}return b.levels[U]===void 0&&(U=void 0),U}}function O(){if(!(typeof window===t||!T)){try{window.localStorage.removeItem(T)}catch{}try{window.document.cookie=encodeURIComponent(T)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function D(U){var B=U;if(typeof B=="string"&&b.levels[B.toUpperCase()]!==void 0&&(B=b.levels[B.toUpperCase()]),typeof B=="number"&&B>=0&&B<=b.levels.SILENT)return B;throw new TypeError("log.setLevel() called with invalid level: "+U)}b.name=g,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||p,b.getLevel=function(){return I??k??R},b.setLevel=function(U,B){return I=D(U),B!==!1&&C(I),u.call(b)},b.setDefaultLevel=function(U){k=D(U),P()||b.setLevel(U,!1)},b.resetLevel=function(){I=null,O(),u.call(b)},b.enableAll=function(U){b.setLevel(b.levels.TRACE,U)},b.disableAll=function(U){b.setLevel(b.levels.SILENT,U)},b.rebuild=function(){if(o!==b&&(R=D(o.getLevel())),u.call(b),o===b)for(var U in s)s[U].rebuild()},R=D(o?o.getLevel():"WARN");var F=P();F!=null&&(I=D(F)),u.call(b)}o=new m,o.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[S];return b||(b=s[S]=new m(S,o.methodFactory)),b};var v=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})}(ub)),ub.exports}var HNe=BNe();const VNe=Wo(HNe);var GNe=(n,e,t)=>new Promise((r,i)=>{var s=c=>{try{a(t.next(c))}catch(l){i(l)}},o=c=>{try{a(t.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);a((t=t.apply(n,e)).next())}),qNe=[he.ConnectionStateChanged,he.RoomMetadataChanged,he.ActiveSpeakersChanged,he.ConnectionQualityChanged,he.ParticipantConnected,he.ParticipantDisconnected,he.ParticipantPermissionsChanged,he.ParticipantMetadataChanged,he.ParticipantNameChanged,he.ParticipantAttributesChanged,he.TrackMuted,he.TrackUnmuted,he.TrackPublished,he.TrackUnpublished,he.TrackStreamStateChanged,he.TrackSubscriptionFailed,he.TrackSubscriptionPermissionChanged,he.TrackSubscriptionStatusChanged],KNe=[...qNe,he.LocalTrackPublished,he.LocalTrackUnpublished];ue.TrackPublished,ue.TrackUnpublished,ue.TrackMuted,ue.TrackUnmuted,ue.TrackStreamStateChanged,ue.TrackSubscribed,ue.TrackUnsubscribed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionFailed,ue.LocalTrackPublished,ue.LocalTrackUnpublished;var WNe=[ue.ConnectionQualityChanged,ue.IsSpeakingChanged,ue.ParticipantMetadataChanged,ue.ParticipantPermissionsChanged,ue.TrackMuted,ue.TrackUnmuted,ue.TrackPublished,ue.TrackUnpublished,ue.TrackStreamStateChanged,ue.TrackSubscriptionFailed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionStatusChanged];[...WNe,ue.LocalTrackPublished,ue.LocalTrackUnpublished];var zNe=VNe.getLogger("lk-components-js");zNe.setDefaultLevel("WARN");function YNe(n,...e){return new Ln(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(ln(n))}function XNe(n,e){return new Ln(r=>{const i=(...o)=>{r.next(o)};return n.on(e,i),()=>{n.off(e,i)}})}function JNe(n,e,t=!0){var r;const i=()=>GNe(this,null,function*(){try{const a=yield Mc.getLocalDevices(n,t);s.next(a)}catch(a){e==null||e(a)}}),s=new Rr,o=s.pipe(sZ(()=>{var a;(a=navigator==null?void 0:navigator.mediaDevices)==null||a.removeEventListener("devicechange",i)}));if(typeof window<"u"){if(!window.isSecureContext)throw new Error("Accessing media devices is available only in secure contexts (HTTPS and localhost), in some or all supporting browsers. See: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mediaDevices");(r=navigator==null?void 0:navigator.mediaDevices)==null||r.addEventListener("devicechange",i)}return DS(Mc.getLocalDevices(n,t).catch(a=>(e==null||e(a),[])),o)}function c4(n,...e){return new Ln(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(ln(n))}function l4(n){return c4(n,ue.TrackMuted,ue.TrackUnmuted,ue.ParticipantPermissionsChanged,ue.TrackPublished,ue.TrackUnpublished,ue.LocalTrackPublished,ue.LocalTrackUnpublished,ue.MediaDevicesError,ue.TrackSubscriptionStatusChanged).pipe(Fe(t=>{const{isMicrophoneEnabled:r,isCameraEnabled:i,isScreenShareEnabled:s}=t,o=t.getTrackPublication(pe.Source.Microphone),a=t.getTrackPublication(pe.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:r,isScreenShareEnabled:s,cameraTrack:a,microphoneTrack:o,participant:t}}))}function ZNe(n,e={}){var t;let r;const i=new Ln(c=>(r=c,()=>a.unsubscribe())).pipe(ln(Array.from(n.remoteParticipants.values()))),s=(t=e.additionalRoomEvents)!=null?t:KNe,o=Array.from(new Set([he.ParticipantConnected,he.ParticipantDisconnected,he.ConnectionStateChanged,...s])),a=YNe(n,...o).subscribe(c=>r==null?void 0:r.next(Array.from(c.remoteParticipants.values())));return n.remoteParticipants.size>0&&(r==null||r.next(Array.from(n.remoteParticipants.values()))),i}new TextEncoder;new TextDecoder;function $2(n,e,t){const r=_.useRef(!1),i=t||r.current;r.current||(r.current=t);const s=_.useMemo(()=>JNe(n,()=>M.error("Error creating MediaDeviceObserver"),i).pipe(ln([])),[n,i]),o=ot(_.useMemo(()=>s.pipe(Fe(h=>{var m;let p=new Map(h.map((v,g)=>[v.deviceId,v.label?{type:"name",name:v.label}:{type:"number",number:g+1}]));return n==="audiooutput"&&p.size&&!p.has("")&&!p.has("default")&&(p=new Map([["",{type:"default",name:((m=h[0])==null?void 0:m.label)||null}],...p])),p})),[n,s])),[a,c]=Ar(e),l=_.useMemo(()=>{if(o.size)return a!==void 0&&o.has(a)||o.size===1&&o.has("")?a:o.keys().next().value},[o,a]),u=ot(_.useMemo(()=>s.pipe(Fe(h=>{var p;return(p=h.find(m=>m.deviceId===l))==null?void 0:p.groupId})),[s,l]));return _.useMemo(()=>({available:o,selectedId:l,selectedGroupId:u,select:c}),[o,l,u,c])}const B2={available:new Map,selectedId:void 0,selectedGroupId:void 0,select:()=>{}},QNe={audioInput:B2,audioOutput:B2,videoInput:B2,startUsingDeviceNames:()=>{},stopUsingDeviceNames:()=>{}},kZ=_.createContext(QNe),e8e=({children:n})=>{const[e,t]=_.useState(0),r=e>0,i=$2("audioinput",l5e,r),s=$2("audiooutput",u5e,r),o=$2("videoinput",d5e,r),a=_.useCallback(()=>t(u=>u+1),[t]),c=_.useCallback(()=>t(u=>u-1),[t]),l=_.useMemo(()=>({audioInput:i,audioOutput:s,videoInput:o,startUsingDeviceNames:a,stopUsingDeviceNames:c}),[i,s,o,a,c]);return w.jsx(kZ.Provider,{value:l,children:n})},rh=()=>_.useContext(kZ),t8e=(n,e=!0)=>_.useEffect(()=>{if(e)return n.startUsingDeviceNames(),n.stopUsingDeviceNames},[n,e]),n8e=()=>{const{t:n}=Qe(),[e,t]=Ar(uZ),[r,i]=Ar(dZ),[s,o]=Ar(t4),a=(u,h)=>{h(u.target.checked)},[c,l]=Ar(aZ);return w.jsxs("div",{children:[w.jsx(Xt,{children:n("settings.preferences_tab.introduction")}),w.jsx(yt,{children:w.jsx(vn,{id:"showHandRaisedTimer",label:n("settings.preferences_tab.show_hand_raised_timer_label"),description:n("settings.preferences_tab.show_hand_raised_timer_description"),type:"checkbox",checked:e,onChange:u=>a(u,t)})}),w.jsx(yt,{children:w.jsx(vn,{id:"showReactions",label:n("settings.preferences_tab.reactions_show_label"),description:n("settings.preferences_tab.reactions_show_description"),type:"checkbox",checked:r,onChange:u=>a(u,i)})}),w.jsx(yt,{children:w.jsx(vn,{id:"playReactionSound",label:n("settings.preferences_tab.reactions_play_sound_label"),description:n("settings.preferences_tab.reactions_play_sound_description"),type:"checkbox",checked:s,onChange:u=>a(u,o)})}),w.jsx(yt,{children:w.jsx(vn,{id:"developerSettingsTab",type:"checkbox",checked:c,label:n("settings.preferences_tab.developer_mode_label"),description:n("settings.preferences_tab.developer_mode_label_description"),onChange:u=>l(u.target.checked)})})]})};function xZ(n,[e,t]){return Math.min(t,Math.max(e,n))}function r8e(n){const e=_.useRef({value:n,previous:n});return _.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}var FS=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(s8e);if(s){const o=s.props.children,a=i.map(c=>c===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:c);return w.jsx(Px,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return w.jsx(Px,{...r,ref:e,children:t})});FS.displayName="Slot";var Px=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=a8e(t),s=o8e(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Va(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});Px.displayName="SlotClone";var i8e=({children:n})=>w.jsx(w.Fragment,{children:n});function s8e(n){return _.isValidElement(n)&&n.type===i8e}function o8e(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function a8e(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var c8e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],bE=c8e.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?FS:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),w.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{});function l8e(n){const e=n+"CollectionProvider",[t,r]=Ha(e),[i,s]=t(e,{collectionRef:{current:null},itemMap:new Map}),o=m=>{const{scope:v,children:g}=m,S=Re.useRef(null),b=Re.useRef(new Map).current;return w.jsx(i,{scope:v,itemMap:b,collectionRef:S,children:g})};o.displayName=e;const a=n+"CollectionSlot",c=Re.forwardRef((m,v)=>{const{scope:g,children:S}=m,b=s(a,g),R=rn(v,b.collectionRef);return w.jsx(FS,{ref:R,children:S})});c.displayName=a;const l=n+"CollectionItemSlot",u="data-radix-collection-item",h=Re.forwardRef((m,v)=>{const{scope:g,children:S,...b}=m,R=Re.useRef(null),k=rn(v,R),I=s(l,g);return Re.useEffect(()=>(I.itemMap.set(R,{ref:R,...b}),()=>void I.itemMap.delete(R))),w.jsx(FS,{[u]:"",ref:k,children:S})});h.displayName=l;function p(m){const v=s(n+"CollectionConsumer",m);return Re.useCallback(()=>{const S=v.collectionRef.current;if(!S)return[];const b=Array.from(S.querySelectorAll(`[${u}]`));return Array.from(v.itemMap.values()).sort((I,T)=>b.indexOf(I.ref.current)-b.indexOf(T.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:o,Slot:c,ItemSlot:h},p,r]}var PZ=["PageUp","PageDown"],LZ=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],AZ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},$p="Slider",[Lx,u8e,d8e]=l8e($p),[OZ,dqe]=Ha($p,[d8e]),[h8e,SE]=OZ($p),MZ=_.forwardRef((n,e)=>{const{name:t,min:r=0,max:i=100,step:s=1,orientation:o="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:l=[r],value:u,onValueChange:h=()=>{},onValueCommit:p=()=>{},inverted:m=!1,form:v,...g}=n,S=_.useRef(new Set),b=_.useRef(0),k=o==="horizontal"?f8e:p8e,[I=[],T]=Yw({prop:u,defaultProp:l,onChange:U=>{var V;(V=[...S.current][b.current])==null||V.focus(),h(U)}}),C=_.useRef(I);function P(U){const B=_8e(I,U);F(U,B)}function O(U){F(U,b.current)}function D(){const U=C.current[b.current];I[b.current]!==U&&p(I)}function F(U,B,{commit:V}={commit:!1}){const z=E8e(s),H=C8e(Math.round((U-r)/s)*s+r,z),J=xZ(H,[r,i]);T((Y=[])=>{const G=v8e(Y,J,B);if(w8e(G,c*s)){b.current=G.indexOf(J);const K=String(G)!==String(Y);return K&&V&&p(G),K?G:Y}else return Y})}return w.jsx(h8e,{scope:n.__scopeSlider,name:t,disabled:a,min:r,max:i,valueIndexToChangeRef:b,thumbs:S.current,values:I,orientation:o,form:v,children:w.jsx(Lx.Provider,{scope:n.__scopeSlider,children:w.jsx(Lx.Slot,{scope:n.__scopeSlider,children:w.jsx(k,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:e,onPointerDown:Ze(g.onPointerDown,()=>{a||(C.current=I)}),min:r,max:i,inverted:m,onSlideStart:a?void 0:P,onSlideMove:a?void 0:O,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&F(r,0,{commit:!0}),onEndKeyDown:()=>!a&&F(i,I.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:B})=>{if(!a){const H=PZ.includes(U.key)||U.shiftKey&&LZ.includes(U.key)?10:1,J=b.current,Y=I[J],G=s*H*B;F(Y+G,J,{commit:!0})}}})})})})});MZ.displayName=$p;var[NZ,DZ]=OZ($p,{startEdge:"left",endEdge:"right",size:"width",direction:1}),f8e=_.forwardRef((n,e)=>{const{min:t,max:r,dir:i,inverted:s,onSlideStart:o,onSlideMove:a,onSlideEnd:c,onStepKeyDown:l,...u}=n,[h,p]=_.useState(null),m=rn(e,k=>p(k)),v=_.useRef(void 0),g=M6(i),S=g==="ltr",b=S&&!s||!S&&s;function R(k){const I=v.current||h.getBoundingClientRect(),T=[0,I.width],P=u4(T,b?[t,r]:[r,t]);return v.current=I,P(k-I.left)}return w.jsx(NZ,{scope:n.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:w.jsx(FZ,{dir:g,"data-orientation":"horizontal",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:k=>{const I=R(k.clientX);o==null||o(I)},onSlideMove:k=>{const I=R(k.clientX);a==null||a(I)},onSlideEnd:()=>{v.current=void 0,c==null||c()},onStepKeyDown:k=>{const T=AZ[b?"from-left":"from-right"].includes(k.key);l==null||l({event:k,direction:T?-1:1})}})})}),p8e=_.forwardRef((n,e)=>{const{min:t,max:r,inverted:i,onSlideStart:s,onSlideMove:o,onSlideEnd:a,onStepKeyDown:c,...l}=n,u=_.useRef(null),h=rn(e,u),p=_.useRef(void 0),m=!i;function v(g){const S=p.current||u.current.getBoundingClientRect(),b=[0,S.height],k=u4(b,m?[r,t]:[t,r]);return p.current=S,k(g-S.top)}return w.jsx(NZ,{scope:n.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:w.jsx(FZ,{"data-orientation":"vertical",...l,ref:h,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const S=v(g.clientY);s==null||s(S)},onSlideMove:g=>{const S=v(g.clientY);o==null||o(S)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=AZ[m?"from-bottom":"from-top"].includes(g.key);c==null||c({event:g,direction:b?-1:1})}})})}),FZ=_.forwardRef((n,e)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:i,onSlideEnd:s,onHomeKeyDown:o,onEndKeyDown:a,onStepKeyDown:c,...l}=n,u=SE($p,t);return w.jsx(bE.span,{...l,ref:e,onKeyDown:Ze(n.onKeyDown,h=>{h.key==="Home"?(o(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):PZ.concat(LZ).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:Ze(n.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:Ze(n.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&i(h)}),onPointerUp:Ze(n.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),s(h))})})}),UZ="SliderTrack",jZ=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=SE(UZ,t);return w.jsx(bE.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...r,ref:e})});jZ.displayName=UZ;var Ax="SliderRange",$Z=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=SE(Ax,t),s=DZ(Ax,t),o=_.useRef(null),a=rn(e,o),c=i.values.length,l=i.values.map(p=>HZ(p,i.min,i.max)),u=c>1?Math.min(...l):0,h=100-Math.max(...l);return w.jsx(bE.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...r,ref:a,style:{...n.style,[s.startEdge]:u+"%",[s.endEdge]:h+"%"}})});$Z.displayName=Ax;var Ox="SliderThumb",BZ=_.forwardRef((n,e)=>{const t=u8e(n.__scopeSlider),[r,i]=_.useState(null),s=rn(e,a=>i(a)),o=_.useMemo(()=>r?t().findIndex(a=>a.ref.current===r):-1,[t,r]);return w.jsx(m8e,{...n,ref:s,index:o})}),m8e=_.forwardRef((n,e)=>{const{__scopeSlider:t,index:r,name:i,...s}=n,o=SE(Ox,t),a=DZ(Ox,t),[c,l]=_.useState(null),u=rn(e,R=>l(R)),h=c?o.form||!!c.closest("form"):!0,p=rK(c),m=o.values[r],v=m===void 0?0:HZ(m,o.min,o.max),g=y8e(r,o.values.length),S=p==null?void 0:p[a.size],b=S?b8e(S,v,a.direction):0;return _.useEffect(()=>{if(c)return o.thumbs.add(c),()=>{o.thumbs.delete(c)}},[c,o.thumbs]),w.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${v}% + ${b}px)`},children:[w.jsx(Lx.ItemSlot,{scope:n.__scopeSlider,children:w.jsx(bE.span,{role:"slider","aria-label":n["aria-label"]||g,"aria-valuemin":o.min,"aria-valuenow":m,"aria-valuemax":o.max,"aria-orientation":o.orientation,"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,tabIndex:o.disabled?void 0:0,...s,ref:u,style:m===void 0?{display:"none"}:n.style,onFocus:Ze(n.onFocus,()=>{o.valueIndexToChangeRef.current=r})})}),h&&w.jsx(g8e,{name:i??(o.name?o.name+(o.values.length>1?"[]":""):void 0),form:o.form,value:m},r)]})});BZ.displayName=Ox;var g8e=n=>{const{value:e,...t}=n,r=_.useRef(null),i=r8e(e);return _.useEffect(()=>{const s=r.current,o=window.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(o,"value").set;if(i!==e&&c){const l=new Event("input",{bubbles:!0});c.call(s,e),s.dispatchEvent(l)}},[i,e]),w.jsx("input",{style:{display:"none"},...t,ref:r,defaultValue:e})};function v8e(n=[],e,t){const r=[...n];return r[t]=e,r.sort((i,s)=>i-s)}function HZ(n,e,t){const s=100/(t-e)*(n-e);return xZ(s,[0,100])}function y8e(n,e){return e>2?`Value ${n+1} of ${e}`:e===2?["Minimum","Maximum"][n]:void 0}function _8e(n,e){if(n.length===1)return 0;const t=n.map(i=>Math.abs(i-e)),r=Math.min(...t);return t.indexOf(r)}function b8e(n,e,t){const r=n/2,s=u4([0,50],[0,r]);return(r-s(e)*t)*t}function S8e(n){return n.slice(0,-1).map((e,t)=>n[t+1]-e)}function w8e(n,e){if(e>0){const t=S8e(n);return Math.min(...t)>=e}return!0}function u4(n,e){return t=>{if(n[0]===n[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(n[1]-n[0]);return e[0]+r*(t-n[0])}}function E8e(n){return(String(n).split(".")[1]||"").length}function C8e(n,e){const t=Math.pow(10,e);return Math.round(n*t)/t}var T8e=MZ,I8e=jZ,R8e=$Z,k8e=BZ;const x8e="_slider_15go1_8",P8e="_track_15go1_14",L8e="_highlight_15go1_31",A8e="_handle_15go1_43",Z1={slider:x8e,track:P8e,highlight:L8e,handle:A8e},VZ=({className:n,label:e,value:t,onValueChange:r,onValueCommit:i,min:s,max:o,step:a,disabled:c})=>{const l=_.useCallback(([h])=>r(h),[r]),u=_.useCallback(([h])=>i==null?void 0:i(h),[i]);return w.jsxs(T8e,{className:De(n,Z1.slider),value:[t],onValueChange:l,onValueCommit:u,min:s,max:o,step:a,disabled:c,children:[w.jsx(I8e,{className:Z1.track,children:w.jsx(R8e,{className:Z1.highlight})}),w.jsx(ui,{placement:"top",label:Math.round(t*100).toString()+"%",children:w.jsx(k8e,{className:Z1.handle,"aria-label":e})})]})},O8e="_selection_1akwb_1",M8e="_title_1akwb_5",N8e="_separator_1akwb_10",D8e="_options_1akwb_14",F8e="_secondary_1akwb_20",rg={selection:O8e,title:M8e,separator:N8e,options:D8e,secondary:F8e},H2=({devices:n,title:e,numberedLabel:t})=>{const{t:r}=Qe(),i=_.useId(),s=_.useCallback(o=>{n.select(o.target.value)},[n]);return n.available.size==0?null:w.jsxs("div",{className:rg.selection,children:[w.jsx(Su,{type:"body",weight:"semibold",size:"sm",as:"h4",className:rg.title,children:e}),w.jsx(Yz,{className:rg.separator}),w.jsx("div",{className:rg.options,children:[...n.available].map(([o,a])=>{let c;switch(a.type){case"name":c=a.name;break;case"number":c=t(a.number);break;case"default":c=a.name===null?r("settings.devices.default"):w.jsxs(Ci,{i18nKey:"settings.devices.default_named",name:a.name,children:["Default"," ",w.jsxs("span",{className:rg.secondary,children:["(",{name:a.name},")"]})]});break}return w.jsx(KCe,{name:i,control:w.jsx(iTe,{checked:o===n.selectedId,onChange:s,value:o}),children:w.jsx(DCe,{children:c})},o)})})]})},U8e={},j8e=({client:n,livekitRoom:e})=>{var v;const{t}=Qe(),[r,i]=Ar(cZ),[s,o]=Ar(e4),[a,c]=Ar(lZ),[l,u]=Ar(Gv),[h,p]=Ar(fZ),m=_.useMemo(()=>{var g;if((g=e==null?void 0:e.engine.client.ws)!=null&&g.url){const S=new URL(e.engine.client.ws.url);return S.search="",S}return null},[e]);return w.jsxs(w.Fragment,{children:[w.jsx("p",{children:t("developer_mode.hostname",{hostname:window.location.hostname||"unknown"})}),w.jsx("p",{children:t("version",{productName:"Element Call",version:"embedded-v0.9.0-release-test.8"})}),w.jsx("p",{children:t("developer_mode.crypto_version",{version:((v=n.getCrypto())==null?void 0:v.getVersion())||"unknown"})}),w.jsx("p",{children:t("developer_mode.matrix_id",{id:n.getUserId()||"unknown"})}),w.jsx("p",{children:t("developer_mode.device_id",{id:n.getDeviceId()||"unknown"})}),w.jsx(yt,{children:w.jsx(vn,{id:"duplicateTiles",type:"number",label:t("developer_mode.duplicate_tiles_label"),value:r.toString(),min:0,onChange:_.useCallback(g=>{const S=g.target.valueAsNumber;S<0||i(Number.isNaN(S)?0:S)},[i])})}),w.jsx(yt,{children:w.jsx(vn,{id:"debugTileLayout",type:"checkbox",checked:s,label:t("developer_mode.debug_tile_layout_label"),onChange:g=>o(g.target.checked)})}),w.jsx(yt,{children:w.jsx(vn,{id:"showNonMemberTiles",type:"checkbox",label:t("developer_mode.show_non_member_tiles"),checked:!!a,onChange:_.useCallback(g=>{c(g.target.checked)},[c])})}),w.jsx(yt,{children:w.jsx(vn,{id:"showConnectionStats",type:"checkbox",label:t("developer_mode.show_connection_stats"),checked:!!l,onChange:_.useCallback(g=>{u(g.target.checked)},[u])})}),w.jsx(yt,{children:w.jsx(vn,{id:"useNewMembershipManager",type:"checkbox",label:t("developer_mode.use_new_membership_manager"),checked:!!h,onChange:_.useCallback(g=>{p(g.target.checked)},[p])})}),e?w.jsxs(w.Fragment,{children:[w.jsx("p",{children:t("developer_mode.livekit_sfu",{url:(m==null?void 0:m.href)||"unknown"})}),w.jsx("p",{children:t("developer_mode.livekit_server_info")}),w.jsxs("pre",{className:U8e.pre,children:[e.serverInfo?JSON.stringify(e.serverInfo,null,2):"undefined",e.metadata]})]}):null]})},d4="audio",h4=({open:n,onDismiss:e,tab:t,onTabChange:r,client:i,roomId:s,livekitRoom:o})=>{const{t:a}=Qe(),c=rh();t8e(c,n);const[l,u]=Ar(hZ),[h,p]=_.useState(l),[m]=Ar(aZ),v={key:"audio",name:a("common.audio"),content:w.jsx(w.Fragment,{children:w.jsxs(e7,{children:[w.jsx(H2,{devices:c.audioInput,title:a("settings.devices.microphone"),numberedLabel:T=>a("settings.devices.microphone_numbered",{n:T})}),w.jsx(H2,{devices:c.audioOutput,title:a("settings.devices.speaker"),numberedLabel:T=>a("settings.devices.speaker_numbered",{n:T})}),w.jsxs("div",{className:eF.volumeSlider,children:[w.jsx("label",{children:a("settings.audio_tab.effect_volume_label")}),w.jsx("p",{children:a("settings.audio_tab.effect_volume_description")}),w.jsx(VZ,{label:a("video_tile.volume"),value:h,onValueChange:p,onValueCommit:u,min:0,max:1,step:.01})]})]})})},g={key:"video",name:a("common.video"),content:w.jsx(e7,{children:w.jsx(H2,{devices:c.videoInput,title:a("settings.devices.camera"),numberedLabel:T=>a("settings.devices.camera_numbered",{n:T})})})},S={key:"preferences",name:a("common.preferences"),content:w.jsx(n8e,{})},b={key:"profile",name:a("common.profile"),content:w.jsx(FNe,{client:i})},R={key:"feedback",name:a("settings.feedback_tab_title"),content:w.jsx(jNe,{roomId:s})},k={key:"developer",name:a("settings.developer_tab_title"),content:w.jsx(j8e,{client:i,livekitRoom:o})},I=[v,g];return Je===null&&I.push(b),I.push(S,R),m&&I.push(k),w.jsx(th,{title:a("common.settings"),className:eF.settingsModal,open:n,onDismiss:e,tabbed:!0,children:w.jsx(mNe,{label:a("common.settings"),tab:t,onTabChange:r,tabs:I})})},$8e=(n,e)=>_.createElement("svg",{width:22,height:22,viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("mask",{id:"path-1-inside-1_898_2641",fill:"white"},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z"})),_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z",fill:"white"}),_.createElement("path",{d:"M17.1502 20.1214L17.9339 21.2814L17.1502 20.1214ZM4.4 19.8008L3.55919 20.9202H3.55919L4.4 19.8008ZM17.1197 17.3237L18.0934 18.3296L18.7717 17.6731L18.4173 16.7981L17.1197 17.3237ZM4.88028 17.3237L3.58268 16.7981L3.22829 17.6731L3.90659 18.3296L4.88028 17.3237ZM11 23.4C13.5662 23.4 15.9541 22.619 17.9339 21.2814L16.3665 18.9613C14.835 19.9959 12.9902 20.6 11 20.6V23.4ZM3.55919 20.9202C5.63176 22.477 8.21011 23.4 11 23.4V20.6C8.83723 20.6 6.84514 19.8865 5.24081 18.6814L3.55919 20.9202ZM-1.4 11C-1.4 15.0577 0.55052 18.6603 3.55919 20.9202L5.24081 18.6814C2.90591 16.9276 1.4 14.1399 1.4 11H-1.4ZM11 -1.4C4.15167 -1.4 -1.4 4.15167 -1.4 11H1.4C1.4 5.69807 5.69807 1.4 11 1.4V-1.4ZM23.4 11C23.4 4.15167 17.8483 -1.4 11 -1.4V1.4C16.3019 1.4 20.6 5.69807 20.6 11H23.4ZM17.9339 21.2814C21.2288 19.0554 23.4 15.2815 23.4 11H20.6C20.6 14.3124 18.9236 17.2337 16.3665 18.9613L17.9339 21.2814ZM12.9 7.975C12.9 9.28384 11.9459 10.15 11 10.15V12.95C13.6991 12.95 15.7 10.615 15.7 7.975H12.9ZM11 5.8C11.9459 5.8 12.9 6.66616 12.9 7.975H15.7C15.7 5.335 13.6991 3 11 3V5.8ZM9.1 7.975C9.1 6.66616 10.0541 5.8 11 5.8V3C8.30086 3 6.3 5.335 6.3 7.975H9.1ZM11 10.15C10.0541 10.15 9.1 9.28384 9.1 7.975H6.3C6.3 10.615 8.30086 12.95 11 12.95V10.15ZM16.146 16.3178C14.8129 17.6081 13.0004 18.4 11 18.4V21.2C13.756 21.2 16.2591 20.1051 18.0934 18.3296L16.146 16.3178ZM11 14.6C13.1797 14.6 15.0494 15.9415 15.8221 17.8493L18.4173 16.7981C17.2312 13.8697 14.359 11.8 11 11.8V14.6ZM6.17788 17.8493C6.95058 15.9415 8.8203 14.6 11 14.6V11.8C7.64102 11.8 4.7688 13.8697 3.58268 16.7981L6.17788 17.8493ZM11 18.4C8.99963 18.4 7.18709 17.6081 5.85397 16.3178L3.90659 18.3296C5.74088 20.1051 8.24402 21.2 11 21.2V18.4Z",fill:"white",mask:"url(#path-1-inside-1_898_2641)"})),sF=_.forwardRef($8e),B8e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M20.0988 9.01625C20.3188 9.59375 20.8825 9.97875 21.5013 9.97875C22.3263 9.97875 23 10.6525 23 11.4775V12.5225C23 13.3475 22.3263 14.0213 21.5013 14.0213C20.8825 14.0213 20.3188 14.4062 20.0988 14.9838C20.0806 15.0292 20.0624 15.0753 20.0441 15.1218C19.9792 15.2863 19.9125 15.4555 19.8375 15.6163C19.5763 16.18 19.7 16.84 20.14 17.28C20.7313 17.8575 20.7313 18.8062 20.14 19.3975L19.3975 20.14C18.82 20.7313 17.8713 20.7313 17.28 20.14C16.8538 19.7 16.18 19.5763 15.6163 19.8375C15.41 19.9338 15.2037 20.0163 14.9838 20.0988C14.4062 20.3188 14.0213 20.8825 14.0213 21.5013C14.0213 22.3263 13.3475 23 12.5225 23H11.4775C10.6525 23 9.97875 22.3263 9.97875 21.5013C9.97875 20.8825 9.59375 20.3188 9.01625 20.0988C8.97079 20.0806 8.92466 20.0624 8.87815 20.044C8.71368 19.9792 8.54454 19.9125 8.38375 19.8375C7.82 19.5763 7.16 19.7 6.72 20.14C6.1425 20.7313 5.19375 20.7313 4.6025 20.14L3.86 19.3975C3.26875 18.82 3.26875 17.8713 3.86 17.28C4.3 16.8538 4.42375 16.18 4.1625 15.6163C4.06625 15.41 3.98375 15.2037 3.90125 14.9838C3.68125 14.4062 3.1175 14.0213 2.49875 14.0213C1.67375 14.0213 1 13.3475 1 12.5225V11.4775C1 10.6525 1.67375 9.97875 2.49875 9.97875C3.1175 9.97875 3.68125 9.59375 3.90125 9.01625C3.94464 8.87742 3.99897 8.74406 4.0539 8.60926C4.086 8.53046 4.11831 8.45117 4.14875 8.37C4.41 7.80625 4.28625 7.14625 3.84625 6.70625C3.255 6.12875 3.255 5.18 3.84625 4.58875L4.6025 3.86C5.18 3.26875 6.12875 3.26875 6.72 3.86C7.14625 4.3 7.82 4.42375 8.38375 4.1625C8.59 4.06625 8.79625 3.97 9.01625 3.90125C9.59375 3.68125 9.97875 3.1175 9.97875 2.49875C9.97875 1.67375 10.6525 1 11.4775 1H12.5225C13.3475 1 14.0213 1.67375 14.0213 2.49875C14.0213 3.13125 14.4062 3.68125 14.9838 3.90125C15.0292 3.91943 15.0753 3.93762 15.1218 3.95595C15.2863 4.02079 15.4555 4.08746 15.6163 4.1625C16.18 4.42375 16.84 4.3 17.28 3.86C17.8575 3.26875 18.8062 3.26875 19.3975 3.86L20.14 4.6025C20.7313 5.18 20.7313 6.12875 20.14 6.72C19.7 7.14625 19.5763 7.82 19.8375 8.38375C19.9338 8.59 20.0163 8.79625 20.0988 9.01625ZM12 17.5C8.96125 17.5 6.5 15.0387 6.5 12C6.5 8.96125 8.96125 6.5 12 6.5C15.0387 6.5 17.5 8.96125 17.5 12C17.5 15.0387 15.0387 17.5 12 17.5Z",fill:"#ffffff"})),H8e=_.forwardRef(B8e),V8e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.49966 2.38889C7.49966 1.89797 7.89763 1.5 8.38855 1.5H20.1108C20.6017 1.5 20.9997 1.89797 20.9997 2.38889V21.6111C20.9997 22.102 20.6017 22.5 20.1108 22.5H8.38855C7.89763 22.5 7.49966 22.102 7.49966 21.6111V12.6667H7.49089H7.4821H7.47331H7.46452H7.45573H7.44694H7.43815H7.42936H7.42057H7.41178H7.403H7.39421H7.38542H7.37663H7.36784H7.35905H7.35026H7.34147H7.33268H7.32389H7.3151H7.30632H7.29753H7.28874H7.27995H7.27116H7.26237H7.25358H7.24479H7.236H7.22721H7.21842H7.20964H7.20085H7.19206H7.18327H7.17448H7.16569H7.1569H7.14811H7.13932H7.13053H7.12175H7.11296H7.10417H7.09538H7.08659H7.0778H7.06901H7.06022H7.05143H7.04264H7.03385H7.02507H7.01628H7.00749H6.9987H6.98991H6.98112H6.97233H6.96354H6.95475H6.94596H6.93717H6.92839H6.9196H6.91081H6.90202H6.89323H6.88444H6.87565H6.86686H6.85807H6.84928H6.8405H6.83171H6.82292H6.81413H6.80534H6.79655H6.78776H6.77897H6.77018H6.76139H6.7526H6.74382H6.73503H6.72624H6.71745H6.70866H6.69987H6.69108H6.68229H6.6735H6.66471H6.65592H6.64714H6.63835H6.62956H6.62077H6.61198H6.60319H6.5944H6.58561H6.57682H6.56803H6.55925H6.55046H6.54167H6.53288H6.52409H6.5153H6.50651H6.49772H6.48893H6.48014H6.47135H6.46257H6.45378H6.44499H6.4362H6.42741H6.41862H6.40983H6.40104H6.39225H6.38346H6.37467H6.36589H6.3571H6.34831H6.33952H6.33073H6.32194H6.31315H6.30436H6.29557H6.28678H6.27799H6.26921H6.26042H6.25163H6.24284H6.23405H6.22526H6.21647H6.20768H6.19889H6.1901H6.18132H6.17253H6.16374H6.15495H6.14616H6.13737H6.12858H6.11979H6.111H6.10221H6.09342H6.08464H6.07585H6.06706H6.05827H6.04948H6.04069H6.0319H6.02311H6.01432H6.00553H5.99674H5.98796H5.97917H5.97038H5.96159H5.9528H5.94401H5.93522H5.92643H5.91764H5.90885H5.90007H5.89128H5.88249H5.8737H5.86491H5.85612H5.84733H5.83854H5.82975H5.82096H5.81217H5.80339H5.7946H5.78581H5.77702H5.76823H5.75944H5.75065H5.74186H5.73307H5.72428H5.71549H5.70671H5.69792H5.68913H5.68034H5.67155H5.66276H5.65397H5.64518H5.63639H5.6276H5.61882H5.61003H5.60124H5.59245H5.58366H5.57487H5.56608H5.55729H5.5485H5.53971H5.53092H5.52214H5.51335H5.50456H5.49577H5.48698H5.47819H5.4694H5.46061H5.45182H5.44303H5.43424H5.42546H5.41667H5.40788H5.39909H5.3903H5.38151H5.37272H5.36393H5.35514H5.34635H5.33757H5.32878H5.31999H5.3112H5.30241H5.29362H5.28483H5.27604H5.26725H5.25846H5.24967H5.24089H5.2321H5.22331H5.21452H5.20573H5.19694H5.18815H5.17936H5.17057H5.16178H5.15299H5.14421H5.13542H5.12663H5.11784H5.10905H5.10026H5.09147H5.08268H5.07389H5.0651H5.05632H5.04753H5.03874H5.02995H5.02116H5.01237H5.00358H4.99479H4.986H4.97721H4.96842H4.95964H4.95085H4.94206H4.93327H4.92448H4.91569H4.9069H4.89811H4.88932H4.88053H4.87174H4.86296H4.85417H4.84538H4.83659H4.8278H4.81901H4.81022H4.80143H4.79264H4.78385H4.77507H4.76628H4.75749H4.7487H4.73991H4.73112H4.72233H4.71354H4.70475H4.69596H4.68717H4.67839H4.6696H4.66081H4.65202H4.64323H4.63444H4.62565H4.61686H4.60807H4.59928H4.59049H4.58171H4.57292H4.56413H4.55534H4.54655H4.53776H4.52897H4.52018H4.51139H4.5026H4.49382H4.48503H4.47624H4.46745H4.45866H4.44987H4.44108H4.43229H4.4235H4.41471H4.40592H4.39714H4.38835H4.37956H4.37077H4.36198H4.35319H4.3444H4.33561H4.32682H4.31803H4.30924H4.30046H4.29167H4.28288H4.27409H4.2653H4.25651H4.24772H4.23893H4.23014H4.22135H4.21257H4.20378H4.19499H4.1862H4.17741H4.16862H4.15983H4.15104H4.14225H4.13346H4.12467H4.11589H4.1071H4.09831H4.08952H4.08073H4.07194H4.06315H4.05436H4.04557H4.03678H4.02799H4.01921H4.01042H4.00163H3.99284H3.98405H3.97526H3.96647H3.95768H3.94889H3.9401H3.93132H3.92253H3.91374H3.90495H3.89616H3.88737H3.87858H3.86979H3.861H3.85221H3.84342H3.83464H3.82585H3.81706H3.80827H3.79948H3.79069H3.7819H3.77311H3.76432H3.75553H3.74674H3.73796H3.72917H3.72038H3.71159H3.7028H3.69401H3.68522H3.67643H3.66764H3.65885H3.65007H3.64128H3.63249H3.6237H3.61491H3.60612H3.59733H3.58854H3.57975H3.57096H3.56217H3.55339H3.5446H3.53581H3.52702H3.51823H3.50944H3.50065H3.49186H3.48307H3.47428H3.46549H3.45671H3.44792H3.43913H3.43034H3.42155H3.41276H3.40397H3.39518H3.38639H3.3776H3.36882H3.36003H3.35124H3.34245H3.33366H3.32487H3.31608H3.30729H3.2985H3.28971H3.28092H3.27214H3.26335H3.25456H3.24577H3.23698H3.22819H3.2194H3.21061H3.20182H3.19303H3.18424H3.17546H3.16667H3.15788H3.14909H3.1403H3.13151H3.12272H3.11393H3.10514H3.09635H3.08757H3.07878H3.06999H3.0612H3.05241H3.04362H3.03483H3.02604H3.01725H3.00846H2.99967C2.63148 12.6667 2.33301 12.3682 2.33301 12C2.33301 11.6318 2.63148 11.3333 2.99967 11.3333H3.00846H3.01725H3.02604H3.03483H3.04362H3.05241H3.0612H3.06999H3.07878H3.08757H3.09635H3.10514H3.11393H3.12272H3.13151H3.1403H3.14909H3.15788H3.16667H3.17546H3.18424H3.19303H3.20182H3.21061H3.2194H3.22819H3.23698H3.24577H3.25456H3.26335H3.27214H3.28092H3.28971H3.2985H3.30729H3.31608H3.32487H3.33366H3.34245H3.35124H3.36003H3.36882H3.3776H3.38639H3.39518H3.40397H3.41276H3.42155H3.43034H3.43913H3.44792H3.45671H3.46549H3.47428H3.48307H3.49186H3.50065H3.50944H3.51823H3.52702H3.53581H3.5446H3.55339H3.56217H3.57096H3.57975H3.58854H3.59733H3.60612H3.61491H3.6237H3.63249H3.64128H3.65007H3.65885H3.66764H3.67643H3.68522H3.69401H3.7028H3.71159H3.72038H3.72917H3.73796H3.74674H3.75553H3.76432H3.77311H3.7819H3.79069H3.79948H3.80827H3.81706H3.82585H3.83464H3.84342H3.85221H3.861H3.86979H3.87858H3.88737H3.89616H3.90495H3.91374H3.92253H3.93132H3.9401H3.94889H3.95768H3.96647H3.97526H3.98405H3.99284H4.00163H4.01042H4.01921H4.02799H4.03678H4.04557H4.05436H4.06315H4.07194H4.08073H4.08952H4.09831H4.1071H4.11589H4.12467H4.13346H4.14225H4.15104H4.15983H4.16862H4.17741H4.1862H4.19499H4.20378H4.21257H4.22135H4.23014H4.23893H4.24772H4.25651H4.2653H4.27409H4.28288H4.29167H4.30046H4.30924H4.31803H4.32682H4.33561H4.3444H4.35319H4.36198H4.37077H4.37956H4.38835H4.39714H4.40592H4.41471H4.4235H4.43229H4.44108H4.44987H4.45866H4.46745H4.47624H4.48503H4.49382H4.5026H4.51139H4.52018H4.52897H4.53776H4.54655H4.55534H4.56413H4.57292H4.58171H4.59049H4.59928H4.60807H4.61686H4.62565H4.63444H4.64323H4.65202H4.66081H4.6696H4.67839H4.68717H4.69596H4.70475H4.71354H4.72233H4.73112H4.73991H4.7487H4.75749H4.76628H4.77507H4.78385H4.79264H4.80143H4.81022H4.81901H4.8278H4.83659H4.84538H4.85417H4.86296H4.87174H4.88053H4.88932H4.89811H4.9069H4.91569H4.92448H4.93327H4.94206H4.95085H4.95964H4.96842H4.97721H4.986H4.99479H5.00358H5.01237H5.02116H5.02995H5.03874H5.04753H5.05631H5.0651H5.07389H5.08268H5.09147H5.10026H5.10905H5.11784H5.12663H5.13542H5.14421H5.15299H5.16178H5.17057H5.17936H5.18815H5.19694H5.20573H5.21452H5.22331H5.2321H5.24089H5.24967H5.25846H5.26725H5.27604H5.28483H5.29362H5.30241H5.3112H5.31999H5.32878H5.33757H5.34635H5.35514H5.36393H5.37272H5.38151H5.3903H5.39909H5.40788H5.41667H5.42546H5.43424H5.44303H5.45182H5.46061H5.4694H5.47819H5.48698H5.49577H5.50456H5.51335H5.52214H5.53092H5.53971H5.5485H5.55729H5.56608H5.57487H5.58366H5.59245H5.60124H5.61003H5.61882H5.6276H5.63639H5.64518H5.65397H5.66276H5.67155H5.68034H5.68913H5.69792H5.70671H5.71549H5.72428H5.73307H5.74186H5.75065H5.75944H5.76823H5.77702H5.78581H5.7946H5.80339H5.81217H5.82096H5.82975H5.83854H5.84733H5.85612H5.86491H5.8737H5.88249H5.89128H5.90007H5.90885H5.91764H5.92643H5.93522H5.94401H5.9528H5.96159H5.97038H5.97917H5.98796H5.99674H6.00553H6.01432H6.02311H6.0319H6.04069H6.04948H6.05827H6.06706H6.07585H6.08464H6.09342H6.10221H6.111H6.11979H6.12858H6.13737H6.14616H6.15495H6.16374H6.17253H6.18132H6.1901H6.19889H6.20768H6.21647H6.22526H6.23405H6.24284H6.25163H6.26042H6.26921H6.27799H6.28678H6.29557H6.30436H6.31315H6.32194H6.33073H6.33952H6.34831H6.3571H6.36589H6.37467H6.38346H6.39225H6.40104H6.40983H6.41862H6.42741H6.4362H6.44499H6.45378H6.46257H6.47135H6.48014H6.48893H6.49772H6.50651H6.5153H6.52409H6.53288H6.54167H6.55046H6.55925H6.56803H6.57682H6.58561H6.5944H6.60319H6.61198H6.62077H6.62956H6.63835H6.64714H6.65592H6.66471H6.6735H6.68229H6.69108H6.69987H6.70866H6.71745H6.72624H6.73503H6.74382H6.7526H6.76139H6.77018H6.77897H6.78776H6.79655H6.80534H6.81413H6.82292H6.83171H6.8405H6.84928H6.85807H6.86686H6.87565H6.88444H6.89323H6.90202H6.91081H6.9196H6.92839H6.93717H6.94596H6.95475H6.96354H6.97233H6.98112H6.98991H6.9987H7.00749H7.01628H7.02507H7.03385H7.04264H7.05143H7.06022H7.06901H7.0778H7.08659H7.09538H7.10417H7.11296H7.12175H7.13053H7.13932H7.14811H7.1569H7.16569H7.17448H7.18327H7.19206H7.20085H7.20964H7.21842H7.22721H7.236H7.24479H7.25358H7.26237H7.27116H7.27995H7.28874H7.29753H7.30632H7.3151H7.32389H7.33268H7.34147H7.35026H7.35905H7.36784H7.37663H7.38542H7.39421H7.403H7.41178H7.42057H7.42936H7.43815H7.44694H7.45573H7.46452H7.47331H7.4821H7.49089H7.49966V2.38889ZM13.3687 6.24853C13.1172 5.9796 12.7095 5.9796 12.458 6.24853C12.2065 6.51747 12.2065 6.9535 12.458 7.22243L16.3022 11.3336L16.2894 11.3336L16.2726 11.3336L16.2558 11.3336L16.239 11.3335L16.2223 11.3335L16.2055 11.3335L16.1887 11.3335L16.1719 11.3335L16.1552 11.3334L16.1384 11.3334L16.1216 11.3334L16.1048 11.3334L16.088 11.3334L16.0713 11.3333L16.0545 11.3333L16.0377 11.3333L16.0209 11.3333L16.0041 11.3333L15.9874 11.3332L15.9706 11.3332L15.9538 11.3332L15.937 11.3332L15.9202 11.3332L15.9035 11.3331L15.8867 11.3331L15.8699 11.3331L15.8531 11.3331L15.8364 11.3331L15.8196 11.333L15.8028 11.333L15.786 11.333L15.7692 11.333L15.7525 11.333L15.7357 11.3329L15.7189 11.3329L15.7021 11.3329L15.6853 11.3329L15.6686 11.3329L15.6518 11.3328L15.635 11.3328L15.6182 11.3328L15.6014 11.3328L15.5847 11.3328L15.5679 11.3327L15.5511 11.3327L15.5343 11.3327L15.5175 11.3327L15.5008 11.3327L15.484 11.3326L15.4672 11.3326L15.4504 11.3326L15.4337 11.3326L15.4169 11.3326L15.4001 11.3325L15.3833 11.3325L15.3665 11.3325L15.3498 11.3325L15.333 11.3324L15.3162 11.3324L15.2994 11.3324L15.2826 11.3324L15.2659 11.3324L15.2491 11.3323L15.2323 11.3323L15.2155 11.3323L15.1987 11.3323L15.182 11.3323L15.1652 11.3322L15.1484 11.3322L15.1316 11.3322L15.1148 11.3322L15.0981 11.3322L15.0813 11.3321L15.0645 11.3321L15.0477 11.3321L15.031 11.3321L15.0142 11.3321L14.9974 11.332L14.9806 11.332L14.9638 11.332L14.9471 11.332L14.9303 11.332L14.9135 11.3319L14.8967 11.3319L14.8799 11.3319L14.8632 11.3319L14.8464 11.3319L14.8296 11.3318L14.8128 11.3318L14.796 11.3318L14.7793 11.3318L14.7625 11.3318L14.7457 11.3317L14.7289 11.3317L14.7122 11.3317L14.6954 11.3317L14.6786 11.3317L14.6618 11.3316L14.645 11.3316L14.6283 11.3316L14.6115 11.3316L14.5947 11.3316L14.5779 11.3315L14.5611 11.3315L14.5444 11.3315L14.5276 11.3315L14.5108 11.3315L14.494 11.3314L14.4772 11.3314L14.4605 11.3314L14.4437 11.3314L14.4269 11.3314L14.4101 11.3313L14.3933 11.3313L14.3766 11.3313L14.3598 11.3313L14.343 11.3313L14.3262 11.3312L14.3095 11.3312L14.2927 11.3312L14.2759 11.3312L14.2591 11.3312L14.2423 11.3311L14.2256 11.3311L14.2088 11.3311L14.192 11.3311L14.1752 11.3311L14.1584 11.331L14.1417 11.331L14.1249 11.331L14.1081 11.331L14.0913 11.331L14.0745 11.3309L14.0578 11.3309L14.041 11.3309L14.0242 11.3309L14.0074 11.3309L13.9906 11.3308L13.9739 11.3308L13.9571 11.3308L13.9403 11.3308L13.9235 11.3308L13.9068 11.3307L13.89 11.3307L13.8732 11.3307L13.8564 11.3307L13.8396 11.3307L13.8229 11.3306L13.8061 11.3306L13.7893 11.3306L13.7725 11.3306L13.7557 11.3306L13.739 11.3305L13.7222 11.3305L13.7054 11.3305L13.6886 11.3305L13.6718 11.3305L13.6551 11.3304L13.6383 11.3304L13.6215 11.3304L13.6047 11.3304L13.5879 11.3304L13.5712 11.3303L13.5544 11.3303L13.5376 11.3303L13.5208 11.3303L13.5041 11.3303L13.4873 11.3302L13.4705 11.3302L13.4537 11.3302L13.4369 11.3302L13.4202 11.3302L13.4034 11.3301L13.3866 11.3301L13.3698 11.3301L13.353 11.3301L13.3363 11.33L13.3195 11.33L13.3027 11.33L13.2859 11.33L13.2691 11.33L13.2524 11.3299L13.2356 11.3299L13.2188 11.3299L13.202 11.3299L13.1853 11.3299L13.1685 11.3298L13.1517 11.3298L13.1349 11.3298L13.1181 11.3298L13.1014 11.3298L13.0846 11.3297L13.0678 11.3297L13.051 11.3297L13.0342 11.3297L13.0175 11.3297L13.0007 11.3296L12.9839 11.3296L12.9671 11.3296L12.9503 11.3296L12.9336 11.3296L12.9168 11.3295L12.9 11.3295L12.8832 11.3295L12.8664 11.3295L12.8497 11.3295L12.8329 11.3294L12.8161 11.3294L12.7993 11.3294L12.7826 11.3294L12.7658 11.3294L12.749 11.3293L12.7322 11.3293L12.7154 11.3293L12.6987 11.3293L12.6819 11.3293L12.6651 11.3292L12.6483 11.3292L12.6315 11.3292L12.6148 11.3292L12.598 11.3292L12.5812 11.3291L12.5644 11.3291L12.5476 11.3291L12.5309 11.3291L12.5141 11.3291L12.4973 11.329L12.4805 11.329L12.4637 11.329L12.447 11.329L12.4302 11.329L12.4134 11.3289L12.3966 11.3289L12.3799 11.3289L12.3631 11.3289L12.3463 11.3289L12.3295 11.3288L12.3127 11.3288L12.296 11.3288L12.2792 11.3288L12.2624 11.3288L12.2456 11.3287L12.2288 11.3287L12.2121 11.3287L12.1953 11.3287L12.1785 11.3287L12.1617 11.3286L12.1449 11.3286L12.1282 11.3286L12.1114 11.3286L12.0946 11.3286L12.0778 11.3285L12.0611 11.3285L12.0443 11.3285L12.0275 11.3285L12.0107 11.3285L11.9939 11.3284L11.9772 11.3284L11.9604 11.3284L11.9436 11.3284L11.9268 11.3284L11.91 11.3283L11.8933 11.3283L11.8765 11.3283L11.8597 11.3283L11.8429 11.3283L11.8261 11.3282L11.8094 11.3282L11.7926 11.3282L11.7758 11.3282L11.759 11.3282L11.7422 11.3281L11.7255 11.3281L11.7087 11.3281L11.6919 11.3281L11.6751 11.3281L11.6583 11.328L11.6416 11.328L11.6248 11.328L11.608 11.328L11.5912 11.328L11.5745 11.3279L11.5577 11.3279L11.5409 11.3279L11.5241 11.3279L11.5073 11.3279L11.4906 11.3278L11.4738 11.3278L11.457 11.3278L11.4402 11.3278L11.4234 11.3278L11.4067 11.3277L11.3899 11.3277L11.3731 11.3277L11.3563 11.3277L11.3395 11.3277L11.3228 11.3276L11.306 11.3276L11.2892 11.3276L11.2724 11.3276L11.2557 11.3275L11.2389 11.3275L11.2221 11.3275L11.2053 11.3275L11.1885 11.3275L11.1718 11.3274L11.155 11.3274L11.1382 11.3274L11.1214 11.3274L11.1046 11.3274L11.0879 11.3273L11.0711 11.3273L11.0543 11.3273L11.0375 11.3273L11.0207 11.3273L11.004 11.3272L10.9872 11.3272L10.9704 11.3272L10.9536 11.3272L10.9368 11.3272L10.9201 11.3271L10.9033 11.3271L10.8865 11.3271L10.8697 11.3271L10.853 11.3271L10.8362 11.327L10.8194 11.327L10.8026 11.327L10.7858 11.327L10.7691 11.327L10.7523 11.3269L10.7355 11.3269L10.7187 11.3269L10.7019 11.3269L10.6852 11.3269L10.6684 11.3268L10.6516 11.3268L10.6348 11.3268L10.618 11.3268L10.6013 11.3268L10.5845 11.3267L10.5677 11.3267L10.5509 11.3267L10.5341 11.3267L10.5174 11.3267L10.5006 11.3266L10.4838 11.3266L10.467 11.3266L10.4503 11.3266L10.4335 11.3266L10.4167 11.3265L10.3999 11.3265L10.3831 11.3265L10.3664 11.3265L10.3496 11.3265L10.3328 11.3264L10.316 11.3264L10.2992 11.3264L10.2825 11.3264L10.2657 11.3264L10.2489 11.3263L10.2321 11.3263L10.2153 11.3263L10.1986 11.3263L10.1818 11.3263L10.165 11.3262L10.1482 11.3262L10.1315 11.3262L10.1147 11.3262L10.0979 11.3262L10.0811 11.3261L10.0643 11.3261L10.0476 11.3261L10.0308 11.3261L10.014 11.3261L9.99722 11.326L9.98044 11.326L9.96366 11.326L9.94688 11.326L9.9301 11.326L9.91332 11.3259L9.89654 11.3259L9.87977 11.3259L9.86299 11.3259L9.84621 11.3259L9.82943 11.3258L9.81265 11.3258L9.79587 11.3258L9.77909 11.3258L9.76231 11.3258L9.74553 11.3257L9.72875 11.3257L9.71197 11.3257L9.69519 11.3257L9.67841 11.3257L9.66163 11.3256L9.64486 11.3256L9.62808 11.3256L9.6113 11.3256L9.59452 11.3256L9.57774 11.3255L9.56096 11.3255L9.54418 11.3255L9.5274 11.3255L9.51062 11.3255L9.49384 11.3254L9.47706 11.3254L9.46029 11.3254L9.44351 11.3254L9.42673 11.3254L9.40995 11.3253L9.39317 11.3253L9.37639 11.3253L9.35961 11.3253L9.34283 11.3253L9.32605 11.3252L9.30927 11.3252L9.29249 11.3252L9.27572 11.3252L9.25894 11.3252L9.24216 11.3251L9.22538 11.3251L9.2086 11.3251L9.19182 11.3251L9.17504 11.325L9.15826 11.325L9.14148 11.325L9.1247 11.325L9.10792 11.325L9.09115 11.3249L9.07437 11.3249L9.05759 11.3249L9.04081 11.3249L9.02403 11.3249L9.00725 11.3248L8.99047 11.3248L8.97369 11.3248L8.95691 11.3248L8.94013 11.3248L8.92335 11.3247L8.90658 11.3247L8.8898 11.3247L8.87302 11.3247L8.85624 11.3247L8.83946 11.3246L8.82268 11.3246L8.8059 11.3246L8.78912 11.3246L8.77234 11.3246L8.75556 11.3245L8.73878 11.3245L8.722 11.3245L8.70523 11.3245L8.68845 11.3245L8.67167 11.3244L8.65489 11.3244L8.63811 11.3244L8.62133 11.3244L8.60455 11.3244L8.58777 11.3243L8.57099 11.3243L8.55421 11.3243L8.53743 11.3243L8.52066 11.3243L8.50388 11.3242L8.4871 11.3242L8.47032 11.3242L8.45354 11.3242L8.43676 11.3242L8.41998 11.3241L8.4032 11.3241L8.38642 11.3241L8.36964 11.3241L8.35286 11.3241L8.33608 11.324L8.31931 11.324L8.30253 11.324L8.28575 11.324L8.26897 11.324L8.25219 11.3239L8.23541 11.3239L8.21863 11.3239L8.20185 11.3239L8.18507 11.3239L8.16829 11.3238L8.15151 11.3238L8.13474 11.3238L8.11796 11.3238L8.10118 11.3238L8.0844 11.3237L8.06762 11.3237L8.05084 11.3237L8.03406 11.3237L8.01728 11.3237L8.0005 11.3236L7.99885 12.657L8.01563 12.657L8.03241 12.657L8.04919 12.657L8.06597 12.6571L8.08274 12.6571L8.09952 12.6571L8.1163 12.6571L8.13308 12.6571L8.14986 12.6572L8.16664 12.6572L8.18342 12.6572L8.2002 12.6572L8.21698 12.6572L8.23376 12.6573L8.25054 12.6573L8.26731 12.6573L8.28409 12.6573L8.30087 12.6573L8.31765 12.6574L8.33443 12.6574L8.35121 12.6574L8.36799 12.6574L8.38477 12.6574L8.40155 12.6575L8.41833 12.6575L8.43511 12.6575L8.45189 12.6575L8.46866 12.6575L8.48544 12.6576L8.50222 12.6576L8.519 12.6576L8.53578 12.6576L8.55256 12.6576L8.56934 12.6577L8.58612 12.6577L8.6029 12.6577L8.61968 12.6577L8.63646 12.6577L8.65323 12.6578L8.67001 12.6578L8.68679 12.6578L8.70357 12.6578L8.72035 12.6578L8.73713 12.6579L8.75391 12.6579L8.77069 12.6579L8.78747 12.6579L8.80425 12.6579L8.82103 12.658L8.83781 12.658L8.85458 12.658L8.87136 12.658L8.88814 12.658L8.90492 12.6581L8.9217 12.6581L8.93848 12.6581L8.95526 12.6581L8.97204 12.6581L8.98882 12.6582L9.0056 12.6582L9.02238 12.6582L9.03915 12.6582L9.05593 12.6582L9.07271 12.6583L9.08949 12.6583L9.10627 12.6583L9.12305 12.6583L9.13983 12.6583L9.15661 12.6584L9.17339 12.6584L9.19017 12.6584L9.20695 12.6584L9.22373 12.6584L9.2405 12.6585L9.25728 12.6585L9.27406 12.6585L9.29084 12.6585L9.30762 12.6585L9.3244 12.6586L9.34118 12.6586L9.35796 12.6586L9.37474 12.6586L9.39152 12.6586L9.4083 12.6587L9.42507 12.6587L9.44185 12.6587L9.45863 12.6587L9.47541 12.6587L9.49219 12.6588L9.50897 12.6588L9.52575 12.6588L9.54253 12.6588L9.55931 12.6588L9.57609 12.6589L9.59287 12.6589L9.60964 12.6589L9.62642 12.6589L9.6432 12.6589L9.65998 12.659L9.67676 12.659L9.69354 12.659L9.71032 12.659L9.7271 12.659L9.74388 12.6591L9.76066 12.6591L9.77744 12.6591L9.79421 12.6591L9.81099 12.6591L9.82777 12.6592L9.84455 12.6592L9.86133 12.6592L9.87811 12.6592L9.89489 12.6592L9.91167 12.6593L9.92845 12.6593L9.94523 12.6593L9.96201 12.6593L9.97879 12.6594L9.99556 12.6594L10.0123 12.6594L10.0291 12.6594L10.0459 12.6594L10.0627 12.6595L10.0795 12.6595L10.0962 12.6595L10.113 12.6595L10.1298 12.6595L10.1466 12.6596L10.1634 12.6596L10.1801 12.6596L10.1969 12.6596L10.2137 12.6596L10.2305 12.6597L10.2473 12.6597L10.264 12.6597L10.2808 12.6597L10.2976 12.6597L10.3144 12.6598L10.3311 12.6598L10.3479 12.6598L10.3647 12.6598L10.3815 12.6598L10.3983 12.6599L10.415 12.6599L10.4318 12.6599L10.4486 12.6599L10.4654 12.6599L10.4822 12.66L10.4989 12.66L10.5157 12.66L10.5325 12.66L10.5493 12.66L10.5661 12.6601L10.5828 12.6601L10.5996 12.6601L10.6164 12.6601L10.6332 12.6601L10.65 12.6602L10.6667 12.6602L10.6835 12.6602L10.7003 12.6602L10.7171 12.6602L10.7338 12.6603L10.7506 12.6603L10.7674 12.6603L10.7842 12.6603L10.801 12.6603L10.8177 12.6604L10.8345 12.6604L10.8513 12.6604L10.8681 12.6604L10.8849 12.6604L10.9016 12.6605L10.9184 12.6605L10.9352 12.6605L10.952 12.6605L10.9688 12.6605L10.9855 12.6606L11.0023 12.6606L11.0191 12.6606L11.0359 12.6606L11.0526 12.6606L11.0694 12.6607L11.0862 12.6607L11.103 12.6607L11.1198 12.6607L11.1365 12.6607L11.1533 12.6608L11.1701 12.6608L11.1869 12.6608L11.2037 12.6608L11.2204 12.6608L11.2372 12.6609L11.254 12.6609L11.2708 12.6609L11.2876 12.6609L11.3043 12.6609L11.3211 12.661L11.3379 12.661L11.3547 12.661L11.3715 12.661L11.3882 12.661L11.405 12.6611L11.4218 12.6611L11.4386 12.6611L11.4553 12.6611L11.4721 12.6611L11.4889 12.6612L11.5057 12.6612L11.5225 12.6612L11.5392 12.6612L11.556 12.6612L11.5728 12.6613L11.5896 12.6613L11.6064 12.6613L11.6231 12.6613L11.6399 12.6613L11.6567 12.6614L11.6735 12.6614L11.6903 12.6614L11.707 12.6614L11.7238 12.6614L11.7406 12.6615L11.7574 12.6615L11.7742 12.6615L11.7909 12.6615L11.8077 12.6615L11.8245 12.6616L11.8413 12.6616L11.858 12.6616L11.8748 12.6616L11.8916 12.6616L11.9084 12.6617L11.9252 12.6617L11.9419 12.6617L11.9587 12.6617L11.9755 12.6617L11.9923 12.6618L12.0091 12.6618L12.0258 12.6618L12.0426 12.6618L12.0594 12.6618L12.0762 12.6619L12.093 12.6619L12.1097 12.6619L12.1265 12.6619L12.1433 12.662L12.1601 12.662L12.1768 12.662L12.1936 12.662L12.2104 12.662L12.2272 12.6621L12.244 12.6621L12.2607 12.6621L12.2775 12.6621L12.2943 12.6621L12.3111 12.6622L12.3279 12.6622L12.3446 12.6622L12.3614 12.6622L12.3782 12.6622L12.395 12.6623L12.4118 12.6623L12.4285 12.6623L12.4453 12.6623L12.4621 12.6623L12.4789 12.6624L12.4957 12.6624L12.5124 12.6624L12.5292 12.6624L12.546 12.6624L12.5628 12.6625L12.5795 12.6625L12.5963 12.6625L12.6131 12.6625L12.6299 12.6625L12.6467 12.6626L12.6634 12.6626L12.6802 12.6626L12.697 12.6626L12.7138 12.6626L12.7306 12.6627L12.7473 12.6627L12.7641 12.6627L12.7809 12.6627L12.7977 12.6627L12.8145 12.6628L12.8312 12.6628L12.848 12.6628L12.8648 12.6628L12.8816 12.6628L12.8984 12.6629L12.9151 12.6629L12.9319 12.6629L12.9487 12.6629L12.9655 12.6629L12.9822 12.663L12.999 12.663L13.0158 12.663L13.0326 12.663L13.0494 12.663L13.0661 12.6631L13.0829 12.6631L13.0997 12.6631L13.1165 12.6631L13.1333 12.6631L13.15 12.6632L13.1668 12.6632L13.1836 12.6632L13.2004 12.6632L13.2172 12.6632L13.2339 12.6633L13.2507 12.6633L13.2675 12.6633L13.2843 12.6633L13.3011 12.6633L13.3178 12.6634L13.3346 12.6634L13.3514 12.6634L13.3682 12.6634L13.3849 12.6634L13.4017 12.6635L13.4185 12.6635L13.4353 12.6635L13.4521 12.6635L13.4688 12.6635L13.4856 12.6636L13.5024 12.6636L13.5192 12.6636L13.536 12.6636L13.5527 12.6636L13.5695 12.6637L13.5863 12.6637L13.6031 12.6637L13.6199 12.6637L13.6366 12.6637L13.6534 12.6638L13.6702 12.6638L13.687 12.6638L13.7038 12.6638L13.7205 12.6638L13.7373 12.6639L13.7541 12.6639L13.7709 12.6639L13.7876 12.6639L13.8044 12.6639L13.8212 12.664L13.838 12.664L13.8548 12.664L13.8715 12.664L13.8883 12.664L13.9051 12.6641L13.9219 12.6641L13.9387 12.6641L13.9554 12.6641L13.9722 12.6641L13.989 12.6642L14.0058 12.6642L14.0226 12.6642L14.0393 12.6642L14.0561 12.6642L14.0729 12.6643L14.0897 12.6643L14.1064 12.6643L14.1232 12.6643L14.14 12.6644L14.1568 12.6644L14.1736 12.6644L14.1903 12.6644L14.2071 12.6644L14.2239 12.6645L14.2407 12.6645L14.2575 12.6645L14.2742 12.6645L14.291 12.6645L14.3078 12.6646L14.3246 12.6646L14.3414 12.6646L14.3581 12.6646L14.3749 12.6646L14.3917 12.6647L14.4085 12.6647L14.4253 12.6647L14.442 12.6647L14.4588 12.6647L14.4756 12.6648L14.4924 12.6648L14.5091 12.6648L14.5259 12.6648L14.5427 12.6648L14.5595 12.6649L14.5763 12.6649L14.593 12.6649L14.6098 12.6649L14.6266 12.6649L14.6434 12.665L14.6602 12.665L14.6769 12.665L14.6937 12.665L14.7105 12.665L14.7273 12.6651L14.7441 12.6651L14.7608 12.6651L14.7776 12.6651L14.7944 12.6651L14.8112 12.6652L14.828 12.6652L14.8447 12.6652L14.8615 12.6652L14.8783 12.6652L14.8951 12.6653L14.9118 12.6653L14.9286 12.6653L14.9454 12.6653L14.9622 12.6653L14.979 12.6654L14.9957 12.6654L15.0125 12.6654L15.0293 12.6654L15.0461 12.6654L15.0629 12.6655L15.0796 12.6655L15.0964 12.6655L15.1132 12.6655L15.13 12.6655L15.1468 12.6656L15.1635 12.6656L15.1803 12.6656L15.1971 12.6656L15.2139 12.6656L15.2306 12.6657L15.2474 12.6657L15.2642 12.6657L15.281 12.6657L15.2978 12.6657L15.3145 12.6658L15.3313 12.6658L15.3481 12.6658L15.3649 12.6658L15.3817 12.6658L15.3984 12.6659L15.4152 12.6659L15.432 12.6659L15.4488 12.6659L15.4656 12.6659L15.4823 12.666L15.4991 12.666L15.5159 12.666L15.5327 12.666L15.5495 12.666L15.5662 12.6661L15.583 12.6661L15.5998 12.6661L15.6166 12.6661L15.6333 12.6661L15.6501 12.6662L15.6669 12.6662L15.6837 12.6662L15.7005 12.6662L15.7172 12.6662L15.734 12.6663L15.7508 12.6663L15.7676 12.6663L15.7844 12.6663L15.8011 12.6663L15.8179 12.6664L15.8347 12.6664L15.8515 12.6664L15.8683 12.6664L15.885 12.6664L15.9018 12.6665L15.9186 12.6665L15.9354 12.6665L15.9522 12.6665L15.9689 12.6665L15.9857 12.6666L16.0025 12.6666L16.0193 12.6666L16.036 12.6666L16.0528 12.6666L16.0696 12.6667L16.0864 12.6667L16.1032 12.6667L16.1199 12.6667L16.1367 12.6667L16.1535 12.6668L16.1703 12.6668L16.1871 12.6668L16.2038 12.6668L16.2206 12.6669L16.2374 12.6669L16.2542 12.6669L16.271 12.6669L16.2836 12.6669L12.458 16.7581C12.2065 17.0271 12.2065 17.4631 12.458 17.732C12.7095 18.001 13.1172 18.001 13.3687 17.732L18.2822 12.4772C18.5337 12.2083 18.5337 11.7723 18.2822 11.5033L13.3687 6.24853Z",fill:"white"})),G8e=_.forwardRef(V8e),q8e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M18.2139 2.44646L12 3.99992H5.4375C4.64359 3.99992 4 4.64352 4 5.43742V18.5624C4 19.3563 4.64359 19.9999 5.4375 19.9999H12L18.2139 21.5534C19.1211 21.7802 20 21.094 20 20.1588V3.84104C20 2.90584 19.1211 2.21964 18.2139 2.44646ZM12 17.9999V5.99992H6V17.9999H12Z",fill:"white"})),K8e=_.forwardRef(q8e),W8e="_userButton_t5z8t_15",z8e={userButton:W8e},Y8e=({preventNavigation:n,isAuthenticated:e,isPasswordlessUser:t,userId:r,displayName:i,avatarUrl:s,onAction:o})=>{const{t:a}=Qe(),c=di(),l=_.useMemo(()=>{const p=[];return e&&(p.push({key:"user",icon:sF,label:i,dataTestid:"usermenu_user"}),p.push({key:"settings",icon:H8e,label:a("common.settings")}),t&&!n&&p.push({key:"login",label:a("action.sign_in"),icon:G8e,dataTestid:"usermenu_login"}),!t&&!n&&p.push({key:"logout",label:a("action.sign_out"),icon:K8e,dataTestid:"usermenu_logout"})),p},[e,t,i,n,a]),[u,h]=_.useState(!1);return e?w.jsx(hL,{title:a("a11y.user_menu"),showTitle:!1,align:"end",open:u,onOpenChange:h,trigger:w.jsx("button",{"aria-label":a("common.profile"),className:z8e.userButton,"data-testid":"usermenu_open",children:e&&(!t||s)?w.jsx(Np,{id:r,name:i,size:Mp.SM,src:s}):w.jsx(sF,{})}),children:l.map(({key:p,icon:m,label:v,dataTestid:g})=>w.jsx(ip,{Icon:m,label:v,"data-test-id":g,onSelect:()=>o(p)},p))}):w.jsx(r4,{to:{pathname:"/login"},state:{from:c},children:a("log_in")})},f4=({preventNavigation:n=!1})=>{const e=di(),t=ja(),{client:r,logout:i,authenticated:s,passwordlessUser:o}=o4(),{displayName:a,avatarUrl:c}=Ly(r),[l,u]=_.useState(!1),h=_.useCallback(()=>u(!1),[u]),[p,m]=_.useState(d4),v=_.useCallback(S=>{var b;switch(S){case"user":m("profile"),u(!0);break;case"settings":m("audio"),u(!0);break;case"logout":i==null||i();break;case"login":(b=t("/login",{state:{from:e}}))==null||b.catch(R=>M.error("Failed to navigate to login",R));break}},[t,e,i,u]),g=(r==null?void 0:r.getUserIdLocalpart())??"";return w.jsxs(w.Fragment,{children:[w.jsx(Y8e,{preventNavigation:n,isAuthenticated:s,isPasswordlessUser:o,avatarUrl:c,onAction:v,userId:(r==null?void 0:r.getUserId())??"",displayName:a||(g?g.replace("@",""):"")}),r&&w.jsx(h4,{client:r,open:l,onDismiss:h,tab:p,onTabChange:m})]})};function X8e(n){return new Worker(""+new URL("IndexedDBWorker-DunQAoUH.js",import.meta.url).href,{name:n==null?void 0:n.name})}const db=new tP,J8e=n=>{const[e,t]=_.useState(()=>localStorage.getItem(n));return _.useEffect(()=>(db.on(n,t),()=>{db.off(n,t)}),[n,t]),[e,_.useCallback(r=>{t(r),localStorage.setItem(n,r),db.emit(n,r)},[n,t])]},Z8e=(n,e)=>{localStorage.setItem(n,e),db.emit(n,e)};function GZ(n,e){Z8e(p4(n),e)}const p4=n=>`room-shared-key-${n}`,Q8e=n=>{const e=p4(n);return J8e(e)[0]};function e9e(n){qZ(Rs());const e=p4(n);return localStorage.getItem(e)}function qZ(n){!n.password||!n.roomId||GZ(n.roomId,n.password)}const t9e=()=>{const n=eh();return _.useEffect(()=>qZ(n),[n]),n.roomId&&n.password?[n.roomId,n.password]:[void 0,void 0]};function wE(n){const{client:e}=nh(),[t,r]=t9e(),i=Q8e(n),s=e==null?void 0:e.getRoom(n);return _.useMemo(()=>s?i?{kind:Vt.SHARED_KEY,secret:i}:t===n?{kind:Vt.SHARED_KEY,secret:r}:s.hasEncryptionStateEvent()?{kind:Vt.PER_PARTICIPANT}:{kind:Vt.NONE}:{kind:Vt.NONE},[r,s,n,i,t])}const oF=!1,n9e="element-call-sync";async function r9e(n){let e=!!await n.store.getSavedSyncToken();return new Promise((t,r)=>{const i=(s,o,a)=>{s==="PREPARED"?e?e=!1:(n.removeListener(Ge.Sync,i),t()):s==="ERROR"&&(n.removeListener(Ge.Sync,i),r(a==null?void 0:a.error))};n.on(Ge.Sync,i)})}async function KZ(n,e){var a;let t;try{t=window.indexedDB}catch(c){M.warn("Could not get indexDB from window.",c)}const r={fallbackICEServerAllowed:oF,isVoipWithNoMediaAllowed:(a=gt.get().features)==null?void 0:a.feature_group_calls_without_video_and_audio};t&&localStorage?r.store=new gB({indexedDB:window.indexedDB,localStorage,dbName:n9e,workerFactory:()=>new X8e}):localStorage&&(r.store=new pv({localStorage}));const{e2eEnabled:i}=Rs();i||M.info("Disabling E2E: group call signalling will NOT be encrypted.");const s=bw({...r,...n,useAuthorizationHeader:!0,localTimeoutMs:5e3,useE2eForGroupCall:i,fallbackICEServerAllowed:oF});e||await s.clearStores();try{await s.store.startup()}catch(c){M.error("Error starting matrix client indexDB store. Falling back to memory store.",c),s.store=new pv({localStorage}),await s.store.startup()}try{await s.initRustCrypto()}catch(c){M.warn(c,"Make sure to clear client stores before initializing the rust crypto.")}const o=r9e(s);return await s.startClient({clientWellKnownPollPeriod:60*10}),await o,s}function Ay(n){return n.trim().replace(/\s/g,"-").replace(/[^\w-]/g,"").toLowerCase()}function i9e(n,e){return`#${Ay(n)}:${e.getDomain()}`}function WZ(n){const e=n.split(":",2);if(e.length===2&&e[0][0]==="#"){if(e[1]===gt.defaultServerName())return e[0];throw new Error("Unsupported remote room alias")}return n}async function zZ(n,e,t){M.log("Creating room for group call");const r=n.createRoom({visibility:IP.Private,preset:ay.PublicChat,name:e,room_alias_name:t?void 0:Ay(e),power_level_content_override:{invite:100,kick:100,ban:100,redact:50,state_default:0,events_default:0,users_default:0,events:{"m.room.power_levels":100,"m.room.history_visibility":100,"m.room.tombstone":100,"m.room.encryption":100,"m.room.name":50,"m.room.message":0,"m.room.encrypted":50,"m.sticker":50,"org.matrix.msc3401.call.member":0},users:{[n.getUserId()]:100}}}),i=await new Promise((o,a)=>{r.catch(u=>{a(u),l()});const c=u=>{r.then(h=>{u.roomId===h.room_id&&(o(u.roomId),l())},h=>{M.error("Failed to wait for the room to arrive",h)})},l=()=>{n.off(Ge.Room,c)};n.on(Ge.Room,c)});let s;return t==Vt.SHARED_KEY&&(s=k$(16),GZ(i,s)),{roomId:i,alias:t?void 0:i9e(e,n),password:s}}function YZ(n,e,t,r){return`${window.location.protocol}//${window.location.host}${EE(n,e,t)}`}function EE(n,e,t,r){return`/room/#${t?"/"+Ay(t):""}?${Ike(n,e).toString()}`}const m4=n=>{const[e,t]=_.useState(void 0),[r,i]=_.useState(void 0),s=_.useRef(void 0);s.current||(s.current=bw({baseUrl:gt.defaultHomeserverUrl()})),_.useEffect(()=>{Je||s.current.registerRequest({}).catch(a=>{var c,l,u,h,p,m,v;t((p=(h=(u=(l=(c=a.data)==null?void 0:c.params["m.login.terms"])==null?void 0:l.policies)==null?void 0:u.privacy_policy)==null?void 0:h.en)==null?void 0:p.url),i((v=(m=a.data)==null?void 0:m.params["m.login.recaptcha"])==null?void 0:v.public_key)})},[]);const o=_.useCallback(async(a,c,l,u,h)=>{const p=new NP({matrixClient:s.current,doRequest:async k=>s.current.registerRequest({username:a,password:c,auth:k||void 0}),stateUpdated:(k,I)=>{if(I.error)throw new Error(I.error);k==="m.login.terms"?p.submitAuthDict({type:"m.login.terms"}).catch(T=>{M.error(T)}):k==="m.login.recaptcha"&&p.submitAuthDict({type:"m.login.recaptcha",response:u}).catch(T=>{M.error(T)})},requestEmailToken:async()=>Promise.resolve({sid:"dummy"})}),{user_id:m,access_token:v,device_id:g}=await p.attemptAuth();await(n==null?void 0:n.logout(!0));const S=await KZ({baseUrl:gt.defaultHomeserverUrl(),accessToken:v,userId:m,deviceId:g},!1);await S.setDisplayName(l);const b={user_id:m,device_id:g,access_token:v,passwordlessUser:h};h&&(b.tempPassword=c);const R=S.getUser(S.getUserId());return R.setRawDisplayName(l),R.setDisplayName(l),[S,b]},[n]);return{privacyPolicyUrl:e,recaptchaKey:r,register:o}},s9e="_buttons_1arp2_8",o9e={buttons:s9e},XZ=({onJoin:n,open:e,onDismiss:t})=>{const{t:r}=Qe();return w.jsxs(th,{title:r("join_existing_call_modal.title"),open:e,onDismiss:t,children:[w.jsx("p",{children:r("join_existing_call_modal.text")}),w.jsxs(yt,{rightAlign:!0,className:o9e.buttons,children:[w.jsx(Mt,{onClick:t,children:r("action.no")}),w.jsx(Mt,{onClick:n,"data-testid":"home_joinExistingRoom",children:r("join_existing_call_modal.join_button")})]})]})},aF="https://www.recaptcha.net/recaptcha/api.js?onload=mxOnRecaptchaLoaded&render=explicit";function g4(n){const{t:e}=Qe(),[t]=_.useState(()=>Es(16)),r=_.useRef(void 0);_.useEffect(()=>{var a;if(!n)return;const o=()=>{document.getElementById(t)&&window.grecaptcha.render(t,{sitekey:n,size:"invisible",callback:c=>{var l;return(l=r.current)==null?void 0:l.resolve(c)},"error-callback":()=>{var c;return(c=r.current)==null?void 0:c.reject(new Error)}})};if(typeof((a=window.grecaptcha)==null?void 0:a.render)=="function")o();else if(window.mxOnRecaptchaLoaded=o,!document.querySelector(`script[src="${aF}"]`)){const c=document.createElement("script");c.src=aF,c.async=!0,document.body.appendChild(c)}},[t,n]);const i=_.useCallback(async()=>n?window.grecaptcha?new Promise((o,a)=>{var u,h;const c=new MutationObserver(p=>{var m,v;for(const g of p)if(((v=(m=g.target)==null?void 0:m.style)==null?void 0:v.visibility)!=="visible"){a(nF("recaptcha_dismissed",e)),c.disconnect();return}});r.current={resolve:p=>{o(p),c.disconnect()},reject:p=>{a(p),c.disconnect()}},window.grecaptcha.execute().then(()=>{},p=>{M.error("Recaptcha execution failed",p)});const l=document.querySelector('iframe[src*="recaptcha/api2/bframe"]');(u=l==null?void 0:l.parentNode)!=null&&u.parentNode&&c.observe((h=l==null?void 0:l.parentNode)==null?void 0:h.parentNode,{attributes:!0})}):(M.log("Recaptcha not loaded"),Promise.reject(nF("recaptcha_not_loaded",e))):Promise.resolve(""),[n,e]),s=_.useCallback(()=>{var o;(o=window.grecaptcha)==null||o.reset()},[]);return{execute:i,reset:s,recaptchaId:t}}const a9e="_form_jcuzc_8",c9e={form:a9e},CE=_.forwardRef(({children:n,className:e,onSubmit:t},r)=>w.jsx("form",{onSubmit:t,className:De(c9e.form,e),ref:r,children:n}));CE.displayName="Form";const l9e="_footer_106jg_8",u9e="_mobileLoginLink_106jg_19",d9e="_form_106jg_24",h9e="_notice_106jg_40",ig={footer:l9e,mobileLoginLink:u9e,form:d9e,notice:h9e},f9e="_container_dwllg_8",p9e="_main_dwllg_15",m9e="_logo_dwllg_23",jf={container:f9e,main:p9e,logo:m9e},cF=n=>{n=1831565813+(n|=0)|0;let e=Math.imul(n^n>>>15,1|n);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};class g9e{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:t,separator:r,dictionaries:i,style:s,seed:o}=e;this.dictionaries=i,this.separator=r,this.length=t,this.style=s,this.seed=o}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
|
|
207
|
+
`):"",this.name="UnsubscriptionError",this.errors=t}});function OS(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Ry=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=du(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(g){e={error:g}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(Wt(u))try{u()}catch(g){s=g instanceof U2?g.errors:[g]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var p=du(h),m=p.next();!m.done;m=p.next()){var v=m.value;try{HD(v)}catch(g){s=s??[],g instanceof U2?s=io(io([],ro(s)),ro(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{m&&!m.done&&(i=p.return)&&i.call(p)}finally{if(r)throw r.error}}}if(s)throw new U2(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)HD(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&OS(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&OS(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),$J=Ry.EMPTY;function BJ(n){return n instanceof Ry||n&&"closed"in n&&Wt(n.remove)&&Wt(n.add)&&Wt(n.unsubscribe)}function HD(n){Wt(n)?n():n.unsubscribe()}var jOe={Promise:void 0},$Oe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,io([n,e],ro(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function HJ(n){$Oe.setTimeout(function(){throw n})}function MS(){}function lb(n){n()}var WL=function(n){oo(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,BJ(t)&&t.add(r)):r.destination=VOe,r}return e.create=function(t,r,i){return new $v(t,r,i)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Ry),BOe=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){z1(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){z1(r)}else z1(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){z1(t)}},n}(),$v=function(n){oo(e,n);function e(t,r,i){var s=n.call(this)||this,o;return Wt(t)||!t?o={next:t??void 0,error:r??void 0,complete:i??void 0}:o=t,s.destination=new BOe(o),s}return e}(WL);function z1(n){HJ(n)}function HOe(n){throw n}var VOe={closed:!0,next:MS,error:HOe,complete:MS},zL=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Eu(n){return n}function GOe(n){return n.length===0?Eu:n.length===1?n[0]:function(t){return n.reduce(function(r,i){return i(r)},t)}}var Ln=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var i=this,s=KOe(e)?e:new $v(e,t,r);return lb(function(){var o=i,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?i._subscribe(s):i._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=VD(t),new t(function(i,s){var o=new $v({next:function(a){try{e(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[zL]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return GOe(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=VD(e),new e(function(r,i){var s;t.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function VD(n){var e;return(e=n??jOe.Promise)!==null&&e!==void 0?e:Promise}function qOe(n){return n&&Wt(n.next)&&Wt(n.error)&&Wt(n.complete)}function KOe(n){return n&&n instanceof WL||qOe(n)&&BJ(n)}function WOe(n){return Wt(n==null?void 0:n.lift)}function Mr(n){return function(e){if(WOe(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function zn(n,e,t,r,i){return new zOe(n,e,t,r,i)}var zOe=function(n){oo(e,n);function e(t,r,i,s,o,a){var c=n.call(this,t)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(l){try{r(l)}catch(u){t.error(u)}}:n.prototype._next,c._error=s?function(l){try{s(l)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=i?function(){try{i()}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._complete,c}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(WL),YOe=jJ(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Rr=function(n){oo(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new GD(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new YOe},e.prototype.next=function(t){var r=this;lb(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=du(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(t)}}catch(l){i={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(t){var r=this;lb(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var i=r.observers;i.length;)i.shift().error(t)}})},e.prototype.complete=function(){var t=this;lb(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?$J:(this.currentObservers=null,a.push(t),new Ry(function(){r.currentObservers=null,OS(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new Ln;return t.source=this,t},e.create=function(t,r){return new GD(t,r)},e}(Ln),GD=function(n){oo(e,n);function e(t,r){var i=n.call(this)||this;return i.destination=t,i.source=r,i}return e.prototype.next=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,t)},e.prototype.error=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&i!==void 0?i:$J},e}(Rr),is=function(n){oo(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,i=t.thrownError,s=t._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e}(Rr),YL={now:function(){return(YL.delegate||Date).now()},delegate:void 0},XOe=function(n){oo(e,n);function e(t,r,i){t===void 0&&(t=1/0),r===void 0&&(r=1/0),i===void 0&&(i=YL);var s=n.call(this)||this;return s._bufferSize=t,s._windowTime=r,s._timestampProvider=i,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,t),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(t){var r=this,i=r.isStopped,s=r._buffer,o=r._infiniteTimeWindow,a=r._timestampProvider,c=r._windowTime;i||(s.push(t),!o&&s.push(a.now()+c)),this._trimBuffer(),n.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(t),i=this,s=i._infiniteTimeWindow,o=i._buffer,a=o.slice(),c=0;c<a.length&&!t.closed;c+=s?1:2)t.next(a[c]);return this._checkFinalizedStatuses(t),r},e.prototype._trimBuffer=function(){var t=this,r=t._bufferSize,i=t._timestampProvider,s=t._buffer,o=t._infiniteTimeWindow,a=(o?1:2)*r;if(r<1/0&&a<s.length&&s.splice(0,s.length-a),!o){for(var c=i.now(),l=0,u=1;u<s.length&&s[u]<=c;u+=2)l=u;l&&s.splice(0,l+1)}},e}(Rr),JOe=function(n){oo(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(Ry),qD={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,io([n,e],ro(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},ZOe=function(n){oo(e,n);function e(t,r){var i=n.call(this,t,r)||this;return i.scheduler=t,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(t,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,r)),this.pending=!0,this.delay=r,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(o,this.id,r),this},e.prototype.requestAsyncId=function(t,r,i){return i===void 0&&(i=0),qD.setInterval(t.flush.bind(t,this),i)},e.prototype.recycleAsyncId=function(t,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&qD.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var i=!1,s;try{this.work(t)}catch(o){i=!0,s=o||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,i=t.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,OS(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(JOe),KD=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=YL.now,n}(),QOe=function(n){oo(e,n);function e(t,r){r===void 0&&(r=KD.now);var i=n.call(this,t,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,i){for(;t=r.shift();)t.unsubscribe();throw i}},e}(KD),mE=new QOe(ZOe),eMe=mE,NS=new Ln(function(n){return n.complete()});function VJ(n){return n&&Wt(n.schedule)}function XL(n){return n[n.length-1]}function JL(n){return Wt(XL(n))?n.pop():void 0}function ky(n){return VJ(XL(n))?n.pop():void 0}function tMe(n,e){return typeof XL(n)=="number"?n.pop():e}var ZL=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function GJ(n){return Wt(n==null?void 0:n.then)}function qJ(n){return Wt(n[zL])}function KJ(n){return Symbol.asyncIterator&&Wt(n==null?void 0:n[Symbol.asyncIterator])}function WJ(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function nMe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var zJ=nMe();function YJ(n){return Wt(n==null?void 0:n[zJ])}function XJ(n){return j6(this,arguments,function(){var t,r,i,s;return Jw(this,function(o){switch(o.label){case 0:t=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Rc(t.read())];case 3:return r=o.sent(),i=r.value,s=r.done,s?[4,Rc(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Rc(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function JJ(n){return Wt(n==null?void 0:n.getReader)}function yr(n){if(n instanceof Ln)return n;if(n!=null){if(qJ(n))return rMe(n);if(ZL(n))return iMe(n);if(GJ(n))return sMe(n);if(KJ(n))return ZJ(n);if(YJ(n))return oMe(n);if(JJ(n))return aMe(n)}throw WJ(n)}function rMe(n){return new Ln(function(e){var t=n[zL]();if(Wt(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function iMe(n){return new Ln(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function sMe(n){return new Ln(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,HJ)})}function oMe(n){return new Ln(function(e){var t,r;try{for(var i=du(n),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e.complete()})}function ZJ(n){return new Ln(function(e){cMe(n,e).catch(function(t){return e.error(t)})})}function aMe(n){return ZJ(XJ(n))}function cMe(n,e){var t,r,i,s;return U6(this,void 0,void 0,function(){var o,a;return Jw(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),t=$6(n),c.label=1;case 1:return[4,t.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),i={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Xl(n,e,t,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function QJ(n,e){return e===void 0&&(e=0),Mr(function(t,r){t.subscribe(zn(r,function(i){return Xl(r,n,function(){return r.next(i)},e)},function(){return Xl(r,n,function(){return r.complete()},e)},function(i){return Xl(r,n,function(){return r.error(i)},e)}))})}function eZ(n,e){return e===void 0&&(e=0),Mr(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function lMe(n,e){return yr(n).pipe(eZ(e),QJ(e))}function uMe(n,e){return yr(n).pipe(eZ(e),QJ(e))}function dMe(n,e){return new Ln(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function hMe(n,e){return new Ln(function(t){var r;return Xl(t,e,function(){r=n[zJ](),Xl(t,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){t.error(a);return}o?t.complete():t.next(s)},0,!0)}),function(){return Wt(r==null?void 0:r.return)&&r.return()}})}function tZ(n,e){if(!n)throw new Error("Iterable cannot be null");return new Ln(function(t){Xl(t,e,function(){var r=n[Symbol.asyncIterator]();Xl(t,e,function(){r.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}function fMe(n,e){return tZ(XJ(n),e)}function pMe(n,e){if(n!=null){if(qJ(n))return lMe(n,e);if(ZL(n))return dMe(n,e);if(GJ(n))return uMe(n,e);if(KJ(n))return tZ(n,e);if(YJ(n))return hMe(n,e);if(JJ(n))return fMe(n,e)}throw WJ(n)}function xy(n,e){return e?pMe(n,e):yr(n)}function Ct(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n);return xy(n,t)}function mMe(n){return!!n&&(n instanceof Ln||Wt(n.lift)&&Wt(n.subscribe))}function gMe(n){return n instanceof Date&&!isNaN(n)}function Fe(n,e){return Mr(function(t,r){var i=0;t.subscribe(zn(r,function(s){r.next(n.call(e,s,i++))}))})}var vMe=Array.isArray;function yMe(n,e){return vMe(e)?n.apply(void 0,io([],ro(e))):n(e)}function QL(n){return Fe(function(e){return yMe(n,e)})}var _Me=Array.isArray,bMe=Object.getPrototypeOf,SMe=Object.prototype,wMe=Object.keys;function nZ(n){if(n.length===1){var e=n[0];if(_Me(e))return{args:e,keys:null};if(EMe(e)){var t=wMe(e);return{args:t.map(function(r){return e[r]}),keys:t}}}return{args:n,keys:null}}function EMe(n){return n&&typeof n=="object"&&bMe(n)===SMe}function rZ(n,e){return n.reduce(function(t,r,i){return t[r]=e[i],t},{})}function On(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n),r=JL(n),i=nZ(n),s=i.args,o=i.keys;if(s.length===0)return xy([],t);var a=new Ln(CMe(s,t,o?function(c){return rZ(o,c)}:Eu));return r?a.pipe(QL(r)):a}function CMe(n,e,t){return t===void 0&&(t=Eu),function(r){WD(e,function(){for(var i=n.length,s=new Array(i),o=i,a=i,c=function(u){WD(e,function(){var h=xy(n[u],e),p=!1;h.subscribe(zn(r,function(m){s[u]=m,p||(p=!0,a--),a||r.next(t(s.slice()))},function(){--o||r.complete()}))},r)},l=0;l<i;l++)c(l)},r)}}function WD(n,e,t){n?Xl(t,n,e):e()}function TMe(n,e,t,r,i,s,o,a){var c=[],l=0,u=0,h=!1,p=function(){h&&!c.length&&!l&&e.complete()},m=function(g){return l<r?v(g):c.push(g)},v=function(g){l++;var S=!1;yr(t(g,u++)).subscribe(zn(e,function(b){e.next(b)},function(){S=!0},void 0,function(){if(S)try{l--;for(var b=function(){var R=c.shift();o||v(R)};c.length&&l<r;)b();p()}catch(R){e.error(R)}}))};return n.subscribe(zn(e,m,function(){h=!0,p()})),function(){}}function Py(n,e,t){return t===void 0&&(t=1/0),Wt(e)?Py(function(r,i){return Fe(function(s,o){return e(r,s,i,o)})(yr(n(r,i)))},t):(typeof e=="number"&&(t=e),Mr(function(r,i){return TMe(r,i,n,t)}))}function iZ(n){return n===void 0&&(n=1/0),Py(Eu,n)}function IMe(){return iZ(1)}function DS(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return IMe()(xy(n,ky(n)))}function RMe(n){return new Ln(function(e){yr(n()).subscribe(e)})}function kMe(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=JL(n),r=nZ(n),i=r.args,s=r.keys,o=new Ln(function(a){var c=i.length;if(!c){a.complete();return}for(var l=new Array(c),u=c,h=c,p=function(v){var g=!1;yr(i[v]).subscribe(zn(a,function(S){g||(g=!0,h--),l[v]=S},function(){return u--},void 0,function(){(!u||!g)&&(h||a.next(s?rZ(s,l):l),a.complete())}))},m=0;m<c;m++)p(m)});return t?o.pipe(QL(t)):o}var xMe=["addListener","removeListener"],PMe=["addEventListener","removeEventListener"],LMe=["on","off"];function Ta(n,e,t,r){if(Wt(t)&&(r=t,t=void 0),r)return Ta(n,e,t).pipe(QL(r));var i=ro(MMe(n)?PMe.map(function(a){return function(c){return n[a](e,c,t)}}):AMe(n)?xMe.map(zD(n,e)):OMe(n)?LMe.map(zD(n,e)):[],2),s=i[0],o=i[1];if(!s&&ZL(n))return Py(function(a){return Ta(a,e,t)})(yr(n));if(!s)throw new TypeError("Invalid event target");return new Ln(function(a){var c=function(){for(var l=[],u=0;u<arguments.length;u++)l[u]=arguments[u];return a.next(1<l.length?l:l[0])};return s(c),function(){return o(c)}})}function zD(n,e){return function(t){return function(r){return n[t](e,r)}}}function AMe(n){return Wt(n.addListener)&&Wt(n.removeListener)}function OMe(n){return Wt(n.on)&&Wt(n.off)}function MMe(n){return Wt(n.addEventListener)&&Wt(n.removeEventListener)}function jl(n,e,t){n===void 0&&(n=0),t===void 0&&(t=eMe);var r=-1;return e!=null&&(VJ(e)?t=e:r=e),new Ln(function(i){var s=gMe(n)?+n-t.now():n;s<0&&(s=0);var o=0;return t.schedule(function(){i.closed||(i.next(o++),0<=r?this.schedule(void 0,r):i.complete())},s)})}function Ex(n,e){return n===void 0&&(n=0),e===void 0&&(e=mE),n<0&&(n=0),jl(n,n,e)}function Bv(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n),r=tMe(n,1/0),i=n;return i.length?i.length===1?yr(i[0]):iZ(r)(xy(i,t)):NS}var NMe=Array.isArray;function DMe(n){return n.length===1&&NMe(n[0])?n[0]:n}function Vo(n,e){return Mr(function(t,r){var i=0;t.subscribe(zn(r,function(s){return n.call(e,s,i++)&&r.next(s)}))})}function FMe(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return n=DMe(n),n.length===1?yr(n[0]):new Ln(UMe(n))}function UMe(n){return function(e){for(var t=[],r=function(s){t.push(yr(n[s]).subscribe(zn(e,function(o){if(t){for(var a=0;a<t.length;a++)a!==s&&t[a].unsubscribe();t=null}e.next(o)})))},i=0;t&&!e.closed&&i<n.length;i++)r(i)}}function jMe(n){return Mr(function(e,t){var r=!1,i=null,s=null,o=!1,a=function(){if(s==null||s.unsubscribe(),s=null,r){r=!1;var l=i;i=null,t.next(l)}o&&t.complete()},c=function(){s=null,o&&t.complete()};e.subscribe(zn(t,function(l){r=!0,i=l,s||yr(n(l)).subscribe(s=zn(t,a,c))},function(){o=!0,(!r||!s||s.closed)&&t.complete()}))})}function $Me(n,e,t,r,i){return function(s,o){var a=t,c=e,l=0;s.subscribe(zn(o,function(u){var h=l++;c=a?n(c,u,h):(a=!0,u),o.next(c)},i))}}function Cx(n){return n<=0?function(){return NS}:Mr(function(e,t){var r=0;e.subscribe(zn(t,function(i){++r<=n&&(t.next(i),n<=r&&t.complete())}))})}function BMe(n){return Fe(function(){return n})}function HMe(n,e){return Py(function(t,r){return yr(n(t,r)).pipe(Cx(1),BMe(t))})}function VMe(n,e){e===void 0&&(e=mE);var t=jl(n,e);return HMe(function(){return t})}function ba(n,e){return e===void 0&&(e=Eu),n=n??GMe,Mr(function(t,r){var i,s=!0;t.subscribe(zn(r,function(o){var a=e(o);(s||!n(i,a))&&(s=!1,i=a,r.next(o))}))})}function GMe(n,e){return n===e}function qMe(n,e){return ba(function(t,r){return t[n]===r[n]})}function sZ(n){return Mr(function(e,t){try{e.subscribe(t)}finally{t.add(n)}})}function tc(n,e){return Mr($Me(n,e,arguments.length>=2,!0))}function KMe(n){n===void 0&&(n={});var e=n.connector,t=e===void 0?function(){return new Rr}:e,r=n.resetOnError,i=r===void 0?!0:r,s=n.resetOnComplete,o=s===void 0?!0:s,a=n.resetOnRefCountZero,c=a===void 0?!0:a;return function(l){var u,h,p,m=0,v=!1,g=!1,S=function(){h==null||h.unsubscribe(),h=void 0},b=function(){S(),u=p=void 0,v=g=!1},R=function(){var k=u;b(),k==null||k.unsubscribe()};return Mr(function(k,I){m++,!g&&!v&&S();var T=p=p??t();I.add(function(){m--,m===0&&!g&&!v&&(h=j2(R,c))}),T.subscribe(I),!u&&m>0&&(u=new $v({next:function(C){return T.next(C)},error:function(C){g=!0,S(),h=j2(b,i,C),T.error(C)},complete:function(){v=!0,S(),h=j2(b,o),T.complete()}}),yr(k).subscribe(u))})(l)}}function j2(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];if(e===!0){n();return}if(e!==!1){var i=new $v({next:function(){i.unsubscribe(),n()}});return yr(e.apply(void 0,io([],ro(t)))).subscribe(i)}}function WMe(n,e,t){var r,i,s,o,a=!1;return n&&typeof n=="object"?(r=n.bufferSize,o=r===void 0?1/0:r,i=n.windowTime,e=i===void 0?1/0:i,s=n.refCount,a=s===void 0?!1:s,t=n.scheduler):o=n??1/0,KMe({connector:function(){return new XOe(o,e,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:a})}function zMe(n){return Vo(function(e,t){return n<=t})}function ln(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=ky(n);return Mr(function(r,i){(t?DS(n,r,t):DS(n,r)).subscribe(i)})}function At(n,e){return Mr(function(t,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};t.subscribe(zn(r,function(c){i==null||i.unsubscribe();var l=0,u=s++;yr(n(c,u)).subscribe(i=zn(r,function(h){return r.next(e?e(c,h,u,l++):h)},function(){i=null,a()}))},function(){o=!0,a()}))})}function YMe(){return At(Eu)}function XMe(n,e){return Mr(function(t,r){var i=e;return At(function(s,o){return n(i,s,o)},function(s,o){return i=o,o})(t).subscribe(r),function(){i=null}})}function JMe(n){return Mr(function(e,t){yr(n).subscribe(zn(t,function(){return t.complete()},MS)),!t.closed&&e.subscribe(t)})}function ZMe(n,e,t){var r=Wt(n)||e||t?{next:n,error:e,complete:t}:n;return r?Mr(function(i,s){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var a=!0;i.subscribe(zn(s,function(c){var l;(l=r.next)===null||l===void 0||l.call(r,c),s.next(c)},function(){var c;a=!1,(c=r.complete)===null||c===void 0||c.call(r),s.complete()},function(c){var l;a=!1,(l=r.error)===null||l===void 0||l.call(r,c),s.error(c)},function(){var c,l;a&&((c=r.unsubscribe)===null||c===void 0||c.call(r)),(l=r.finalize)===null||l===void 0||l.call(r)}))}):Eu}function Tx(n,e){return Mr(function(t,r){var i=e??{},s=i.leading,o=s===void 0?!0:s,a=i.trailing,c=a===void 0?!1:a,l=!1,u=null,h=null,p=!1,m=function(){h==null||h.unsubscribe(),h=null,c&&(S(),p&&r.complete())},v=function(){h=null,p&&r.complete()},g=function(b){return h=yr(n(b)).subscribe(zn(r,m,v))},S=function(){if(l){l=!1;var b=u;u=null,r.next(b),!p&&g(b)}};t.subscribe(zn(r,function(b){l=!0,u=b,!(h&&!h.closed)&&(o?S():g(b))},function(){p=!0,!(c&&l&&h&&!h.closed)&&r.complete()}))})}function QMe(n,e,t){e===void 0&&(e=mE);var r=jl(n,e);return Tx(function(){return r},t)}function e5e(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=JL(n);return Mr(function(r,i){for(var s=n.length,o=new Array(s),a=n.map(function(){return!1}),c=!1,l=function(h){yr(n[h]).subscribe(zn(i,function(p){o[h]=p,!c&&!a[h]&&(a[h]=!0,(c=a.every(Eu))&&(a=null))},MS))},u=0;u<s;u++)l(u);r.subscribe(zn(i,function(h){if(c){var p=io([h],ro(o));i.next(t?t.apply(void 0,io([],ro(p))):p)}}))})}function t5e(n,e,t){if(!t)return _.useState(e)[0];const[r]=_.useState(()=>new is(t)),[i]=_.useState(()=>e(r)),s=_.useRef(!0);return n(()=>{if(s.current){s.current=!1;return}r.next(t)},t),i}function Hv(n,e){return t5e(_.useEffect,n,e)}var n5e=()=>new Rr,r5e=n=>n+1|0,i5e=()=>{const n=_.useState(0)[1];return _.useRef(()=>n(r5e)).current},oZ=typeof window>"u"?_.useEffect:_.useLayoutEffect,YD=n=>{var e;return(e=n[1])!=null&&e.next?n[1]:{next:n[1],error:n[2],complete:n[3]}};function s5e(n,e){const t=_.useRef(e),r=_.useRef(),i=_.useRef();return oZ(()=>{t.current=e,r.current=YD(e)}),n(()=>{const s=t.current[0];r.current||(r.current=YD(t.current));const o=s.subscribe({next:a=>{var c,l;s===t.current[0]&&((l=(c=r.current).next)==null||l.call(c,a))},error:a=>{s===t.current[0]&&(r.current.error?r.current.error(a):console.error(a))},complete:()=>{var a,c;s===t.current[0]&&((c=(a=r.current).complete)==null||c.call(a))}});return i.current=o,()=>{o.unsubscribe()}},[e[0]]),i}function o5e(n,e,t,r){return s5e(_.useEffect,[n,e,t,r])}function a5e(n,e,t){if(mMe(e)){const r=e,[i,s]=_.useState(()=>r instanceof is||r.value!==void 0?r.value:t);return n(r,s),_.useDebugValue(i),i}else{const r=e,[i,s]=_.useState(t),[o]=_.useState(n5e),[a]=_.useState(()=>r(o,i)),c=_.useRef(l=>o.next(l)).current;return n(a,s),_.useDebugValue(i),[i,c]}}function Vv(n,e){return a5e(o5e,n,e)}function ot(n){const e=i5e(),t=_.useRef(n),r=_.useRef(),i=_.useRef(!1),s=_.useRef(!1),[o,a]=_.useState(()=>{let c;return n.subscribe({next:l=>{s.current=!0,c=l},error:l=>{r.current=l}}).unsubscribe(),c});if(oZ(()=>{t.current=n}),_.useEffect(()=>{r.current=null;const c=t.current;let l=o;const u=c.subscribe({next:h=>{c===t.current&&(i.current?a(()=>h):l=h)},error:h=>{c===t.current&&(r.current=h,e())}});return i.current||l!==o&&a(()=>l),i.current=!0,()=>{u.unsubscribe()}},[n]),r.current)throw r.current;if(s.current)return _.useDebugValue(o),o;throw new Error("Observable did not synchronously emit a value.")}function c5e(n){const[e]=_.useState(()=>new is(n)),[t]=_.useState(()=>({get current(){return e.value},set current(r){e.next(r)}}));return[t,e]}class Ri{constructor(e,t){this.defaultValue=t,this.setValue=s=>{this._value$.next(s),localStorage.setItem(this.key,JSON.stringify(s))},this.key=`matrix-setting-${e}`;const r=localStorage.getItem(this.key);let i=t;if(r!==null)try{i=JSON.parse(r)}catch(s){M.warn(`Invalid value stored for setting ${e}: ${r}.`,s)}this._value$=new is(i),this.value$=this._value$}}function Ar(n){return[ot(n.value$),n.setValue]}const Ix=new Ri("opt-in-analytics",null),gE=()=>{const n=Ar(Ix);return jt.instance.isEnabled()?n:[!1,null]},aZ=new Ri("developer-settings-tab",!1),cZ=new Ri("duplicate-tiles",0),lZ=new Ri("show-non-member-tiles",!1),e4=new Ri("debug-tile-layout",!1),Gv=new Ri("show-connection-stats",!1),l5e=new Ri("audio-input",void 0),u5e=new Ri("audio-output",void 0),d5e=new Ri("video-input",void 0),uZ=new Ri("hand-raised-show-timer",!1),dZ=new Ri("reactions-show",!0),t4=new Ri("reactions-play-sound",!0),hZ=new Ri("sound-effect-volume",.5),fZ=new Ri("new-membership-manager",!0),XD=new Ri("always-show-self",!0);var vE=(n=>(n[n.Guest=0]="Guest",n[n.Registered=1]="Registered",n))(vE||{});const Co=class Co{constructor(e){var r,i;this.posthog=e,this.enabled=!1,this.anonymity=0,this.platformSuperProperties={},this.registrationType=0,this.sanitizeProperties=(s,o)=>(this.anonymity==1&&(s.$referrer=null,s.$referring_domain=null,s.$initial_referrer=null,s.$initial_referring_domain=null,s.$device_id=null),s.$current_url=s.$current_url.split("/").slice(0,3).join(""),s),this.eventCallEnded=new xOe,this.eventSignup=new LOe,this.eventCallStarted=new POe,this.eventLogin=new AOe,this.eventMuteMicrophone=new OOe,this.eventMuteCamera=new MOe,this.eventUndecryptableToDevice=new NOe,this.eventQualitySurvey=new DOe,this.eventCallDisconnected=new FOe,this.eventCallConnectDuration=new UOe;const t={project_api_key:(r=gt.get().posthog)==null?void 0:r.api_key,api_host:(i=gt.get().posthog)==null?void 0:i.api_host};if(t.project_api_key&&t.api_host){if(Co.getPlatformProperties().matrixBackend==="embedded"){const{analyticsID:s}=Rs();Ix.setValue(!!s)}this.posthog.init(t.project_api_key,{api_host:t.api_host,autocapture:!1,mask_all_text:!0,mask_all_element_attributes:!0,capture_pageview:!1,sanitize_properties:this.sanitizeProperties,respect_dnt:!0,advanced_disable_decide:!0}),this.enabled=!0}else M.info("Posthog is not enabled because there is no api key or no host given in the config"),this.enabled=!1;this.startListeningToSettingsChanges()}static hasInstance(){return!!this.internalInstance}static get instance(){return this.internalInstance||(this.internalInstance=new Co(rOe)),this.internalInstance}registerSuperProperties(e){this.enabled&&this.posthog.register(e)}static getPlatformProperties(){var t,r;return{appVersion:"embedded-v0.9.0-release-test.9",matrixBackend:Je?"embedded":"jssdk",callBackend:"livekit",cryptoVersion:Je||(r=(t=window.matrixclient)==null?void 0:t.getCrypto())==null?void 0:r.getVersion()}}capture(e,t,r){this.enabled&&this.posthog.capture(e,{...t},r)}isEnabled(){return this.enabled}setAnonymity(e){this.enabled&&(e==0||e==1)&&(this.posthog.reset(),this.updateSuperProperties()),this.anonymity=e}static getRandomAnalyticsId(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16)).join("")}async identifyUser(e){if(this.anonymity==2&&this.enabled){let t=await this.getAnalyticsId();try{if(!t&&!Je){const r=e();await this.setAccountAnalyticsId(r),t=await this.hashedEcAnalyticsId(r)}}catch(r){M.log("Unable to identify user for tracking"+(r==null?void 0:r.toString()))}t?this.posthog.identify(t):M.info("No analyticsID is available. Should not try to setup posthog")}}async getAnalyticsId(){const e=window.matrixclient;let t;if(Je)t=Rs().analyticsID;else{const r=await e.getAccountDataFromServer(Co.ANALYTICS_EVENT_TYPE);t=(r==null?void 0:r.id)??null}return t?await this.hashedEcAnalyticsId(t):null}async hashedEcAnalyticsId(e){const t=window.matrixclient,r="ec"+e+t.getUserId(),i=await crypto.subtle.digest("sha-256",aOe.Buffer.from(r,"utf-8")),s=new Int32Array(i);return Array.from(s).map(o=>Math.abs(o).toString(16).padStart(2,"0")).join("")}async setAccountAnalyticsId(e){if(!Je){const t=window.matrixclient,r=await t.getAccountDataFromServer(Co.ANALYTICS_EVENT_TYPE);await t.setAccountData(Co.ANALYTICS_EVENT_TYPE,Object.assign({id:e},r))}}getAnonymity(){return this.anonymity}logout(){this.enabled&&this.posthog.reset(),this.setAnonymity(0)}onLoginStatusChanged(){this.maybeIdentifyUser().catch(()=>M.log("Could not identify user on login status change"))}updateSuperProperties(){this.platformSuperProperties=Co.getPlatformProperties(),this.registerSuperProperties({...this.platformSuperProperties,registrationType:this.registrationType==0?"Guest":"Registered"})}userRegisteredInThisSession(){return this.eventSignup.getSignupEndTime()>new Date(0)}async maybeIdentifyUser(){window.matrixclient&&(this.anonymity===2&&(this.setRegistrationType(window.matrixclient.isGuest()||window.passwordlessUser?0:1),this.identificationPromise=this.identifyUser(Co.getRandomAnalyticsId),await this.identificationPromise,this.userRegisteredInThisSession()&&this.eventSignup.track()),this.anonymity!==0&&this.updateSuperProperties())}trackEvent({eventName:e,...t},r){const i=()=>{this.anonymity==0||this.anonymity==1||this.capture(e,t,r)};this.identificationPromise?this.identificationPromise.then(i,s=>{M.error("Failed to identify user for tracking",s)}):i()}startListeningToSettingsChanges(){Ix.value$.subscribe(e=>{this.setAnonymity(e?2:0),this.maybeIdentifyUser().catch(()=>M.log("Could not identify user"))})}setRegistrationType(e){this.registrationType=e,!(this.anonymity==0||this.anonymity==1)&&this.updateSuperProperties()}};Co.ANALYTICS_EVENT_TYPE="im.vector.analytics",Co.internalInstance=null;let jt=Co;const h5e=2*60*1e3;class f5e{async forceFlush(){}onStart(e){try{switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipStart(e);return;case"matrix.groupCallMembership.summaryReport":this.onSummaryReportStart(e);return}}catch(t){M.debug(t)}}onEnd(e){switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipEnd(e);return}}get prevCall(){const e=localStorage.getItem("matrix-prev-call");if(e===null)return null;try{return JSON.parse(e)}catch(t){return M.warn("Invalid prev call data",e,"error:",t),null}}set prevCall(e){localStorage.setItem("matrix-prev-call",JSON.stringify(e))}onGroupCallMembershipStart(e){const t=this.prevCall,r=e.attributes["matrix.confId"];if(t!==null&&r===t.callId){const i=I7(e.startTime)-t.hangupTs;i<=h5e&&jt.instance.trackEvent({eventName:"Rejoin",callId:t.callId,rejoinDuration:i})}}onGroupCallMembershipEnd(e){this.prevCall={callId:e.attributes["matrix.confId"],hangupTs:I7(e.endTime)}}onSummaryReportStart(e){const t=e.events.find(r=>r.name==="matrix.stats.summary");if(t!==void 0){const r=t.attributes;if(r){const i=`${r["matrix.stats.summary.percentageReceivedMedia"]}`,s=`${r["matrix.stats.summary.percentageReceivedVideoMedia"]}`,o=`${r["matrix.stats.summary.percentageReceivedAudioMedia"]}`,a=`${r["matrix.stats.summary.maxJitter"]}`,c=`${r["matrix.stats.summary.maxPacketLoss"]}`,l=`${r["matrix.stats.summary.peerConnections"]}`,u=`${r["matrix.stats.summary.percentageConcealedAudio"]}`,h=`${r["matrix.stats.summary.opponentUsersInCall"]}`,p=`${r["matrix.stats.summary.opponentDevicesInCall"]}`,m=`${r["matrix.stats.summary.diffDevicesToPeerConnections"]}`,v=`${r["matrix.stats.summary.ratioPeerConnectionToDevices"]}`;jt.instance.trackEvent({eventName:"MediaReceived",callId:e.attributes["matrix.confId"],mediaReceived:i,audioReceived:o,videoReceived:s,maxJitter:a,maxPacketLoss:c,peerConnections:l,percentageConcealedAudio:u,opponentUsersInCall:h,opponentDevicesInCall:p,diffDevicesToPeerConnections:m,ratioPeerConnectionToDevices:v},{send_instantly:!0})}}}async shutdown(){return Promise.resolve()}}const JD=n=>Object.entries(n).map(([e,t])=>({key:e,type:typeof t,value:t}));class p5e{constructor(){this.spans=[]}async forceFlush(){}onStart(e){this.spans.push(e)}onEnd(){}dump(){const e=Date.now()*1e3,t=new Map;for(const s of this.spans){const o=s.spanContext().traceId;let a=t.get(o);a===void 0&&(a=[],t.set(o,a)),a.push(s)}const r="p1",i={[r]:{serviceName:"element-call",tags:[]},warnings:null};return JSON.stringify({total:0,limit:0,offset:0,errors:null,data:[...t.entries()].map(([s,o])=>({traceID:s,warnings:null,processes:i,spans:o.map(a=>{const c=a.spanContext(),l=S2(a.startTime),u=a.duration[0]===-1?e-l:S2(a.duration);return{traceID:s,spanID:c.spanId,operationName:a.name,processID:r,warnings:null,startTime:l,duration:u,references:a.parentSpanId===void 0?[]:[{refType:"CHILD_OF",traceID:s,spanID:a.parentSpanId}],tags:JD(a.attributes),logs:a.events.map(h=>({timestamp:S2(h.time),fields:[...JD(h.attributes??{}),{key:"event",type:"string",value:h.name}]}))}})}))})}async shutdown(){}}const m5e="element-call";let Ku;class yE{static globalInit(){var r,i,s;const e=gt.get(),t=!!((r=e.opentelemetry)!=null&&r.collector_url);(!Ku||Ku.isOtlpEnabled!==t)&&(M.info("(Re)starting OpenTelemetry debug reporting"),Ku==null||Ku.dispose(),Ku=new yE((i=e.opentelemetry)==null?void 0:i.collector_url,(s=e.rageshake)==null?void 0:s.submit_url))}static get instance(){return Ku}constructor(e,t){const r={resource:new z3({[I4e.SERVICE_NAME]:m5e})};this._provider=new J6e(r),e?(M.info("Enabling OTLP collector with URL "+e),this.otlpExporter=new K6e({url:e}),this._provider.addSpanProcessor(new $Pe(this.otlpExporter))):M.info("OTLP collector disabled"),t&&(this.rageshakeProcessor=new p5e,this._provider.addSpanProcessor(this.rageshakeProcessor)),this._provider.addSpanProcessor(new f5e),y2.trace.setGlobalTracerProvider(this._provider),this._tracer=y2.trace.getTracer("my-element-call-otl-tracer")}dispose(){var e;y2.trace.disable(),(e=this._provider)==null||e.shutdown().catch(t=>{M.error("Failed to shutdown OpenTelemetry",t)})}get isOtlpEnabled(){return!!this.otlpExporter}get tracer(){return this._tracer}get provider(){return this._provider}}const ZD=async n=>{const{gzip:e}=await rv(async()=>{const{gzip:r}=await import("./pako.esm-Bt8vjcgE.js");return{gzip:r}},[],import.meta.url),t=new TextEncoder().encode(n);return new Blob([e(t)])};async function g5e(n,e){e.append("crypto_version",n.getVersion());const t=await n.getOwnDeviceKeys(),r=[`curve25519:${t.curve25519}`,`ed25519:${t.ed25519}`];e.append("device_keys",r.join(", "));const i=await n.getCrossSigningStatus();e.append("cross_signing_ready",String(await n.isCrossSigningReady())),e.append("cross_signing_key",await n.getCrossSigningKeyId()??"n/a"),e.append("cross_signing_privkey_in_secret_storage",String(i.privateKeysInSecretStorage)),e.append("cross_signing_master_privkey_cached",String(i.privateKeysCachedLocally.masterKey)),e.append("cross_signing_self_signing_privkey_cached",String(i.privateKeysCachedLocally.selfSigningKey)),e.append("cross_signing_user_signing_privkey_cached",String(i.privateKeysCachedLocally.userSigningKey))}async function v5e(n,e,t){const r=n.secretStorage;t.append("secret_storage_ready",String(await e.isSecretStorageReady())),t.append("secret_storage_key_in_account",String(await r.hasKey())),t.append("session_backup_key_in_secret_storage",String(!!await n.isKeyBackupKeyStored()));const i=await e.getSessionBackupPrivateKey();t.append("session_backup_key_cached",String(!!i)),t.append("session_backup_key_well_formed",String(i instanceof Uint8Array))}function n4(){const{client:n}=nh(),[{sending:e,sent:t,error:r},i]=_.useState({sending:!1,sent:!1,error:void 0});return{submitRageshake:_.useCallback(async o=>{var a;if(!((a=gt.get().rageshake)!=null&&a.submit_url))throw new Error("No rageshake URL is configured");if(!e)try{i({sending:!0,sent:!1,error:void 0});let c="UNKNOWN";window.navigator&&window.navigator.userAgent&&(c=window.navigator.userAgent);let l="UNKNOWN";try{l=String(window.matchMedia("(pointer: coarse)").matches)}catch(m){M.warn("Could not get coarse pointer for rageshake submit.",m)}let u=o.rageshakeRequestId?`Rageshake ${o.rageshakeRequestId}`:"";o.description&&(u+=`: ${o.description}`);const h=new FormData;if(h.append("text",u??"User did not supply any additional text."),h.append("app","matrix-video-chat"),h.append("version","embedded-v0.9.0-release-test.9"),h.append("user_agent",c),h.append("installed_pwa","false"),h.append("touch_input",l),h.append("call_backend","livekit"),h.append("hostname",window.location.hostname),n){const m=n.getUserId(),v=n.getUser(m);h.append("display_name",(v==null?void 0:v.displayName)??""),h.append("user_id",n.credentials.userId??""),h.append("device_id",n.deviceId??""),o.roomId&&h.append("room_id",o.roomId);const g=n.getCrypto();g&&(await g5e(g,h),await v5e(n,g,h))}if(o.label&&h.append("label",o.label),navigator.storage&&navigator.storage.persisted)try{h.append("storageManager_persisted",String(await navigator.storage.persisted()))}catch(m){M.warn("coulr not get navigator peristed storage",m)}else if(document.hasStorageAccess)try{h.append("storageManager_persisted",String(await document.hasStorageAccess()))}catch(m){M.warn("could not get storage access",m)}if(navigator.storage&&navigator.storage.estimate)try{const m=await navigator.storage.estimate();h.append("storageManager_quota",String(m.quota)),h.append("storageManager_usage",String(m.usage)),m.usageDetails&&Object.keys(m.usageDetails).forEach(v=>{h.append(`storageManager_usage_${v}`,String(m.usageDetails[v]))})}catch(m){M.warn("could not obatain storage estimate",m)}if(o.sendLogs){const m=await Nke();for(const v of m)h.append("compressed-log",await ZD(v.lines),v.id);h.append("file",await ZD(yE.instance.rageshakeProcessor.dump()),"traces.json.gz")}o.rageshakeRequestId&&h.append("group_call_rageshake_request_id",o.rageshakeRequestId);const p=await fetch(gt.get().rageshake.submit_url,{method:"POST",body:h});if(p.status!==200)throw new Error(`Failed to submit feedback: receive HTTP ${p.status} ${p.statusText}`);i({sending:!1,sent:!0,error:void 0})}catch(c){i({sending:!1,sent:!1,error:c}),M.error(c)}},[n,e]),sending:e,sent:t,error:r}}function y5e(){const{client:n}=nh();return _.useCallback((t,r)=>{n.sendEvent(t,"org.matrix.rageshake_request",{request_id:r}).catch(i=>{M.error("Failed to send org.matrix.rageshake_request event",i)})},[n])}function _5e(n){const[e,t]=_.useState(!1),r=_.useCallback(()=>t(!1),[t]),{client:i}=nh(),[s,o]=_.useState();return _.useEffect(()=>{if(!i)return;const a=c=>{c.getType()==="org.matrix.rageshake_request"&&n===c.getRoomId()&&i.getUserId()!==c.getSender()&&(o(c.getContent().request_id),t(!0))};return i.on(Ge.Event,a),()=>{i.removeListener(Ge.Event,a)}},[t,n,i]),{rageshakeRequestId:s??"",roomId:n,open:e,onDismiss:r}}const b5e=({description:n})=>{var c;const{submitRageshake:e,sending:t,sent:r,error:i}=n4(),{t:s}=Qe(),o=_.useCallback(()=>{e({description:n,sendLogs:!0}).catch(l=>{M.error("Failed to send rageshake",l)})},[e,n]);if(!((c=gt.get().rageshake)!=null&&c.submit_url))return null;let a=null;if(t)a=w.jsx("span",{children:s("rageshake_sending")});else if(r)a=w.jsx("div",{children:s("rageshake_sent")});else{let l=s("rageshake_send_logs");i&&(l=s("rageshake_button_error_caption")),a=w.jsx(Mt,{onClick:o,className:b7.wideButton,disabled:t,children:l})}return w.jsx("div",{className:b7.rageshakeControl,children:a})},S5e="_error_19mk1_1",w5e="_icon_19mk1_9",Y1={error:S5e,icon:w5e},E5e="_endCall_bwclo_8",C5e={endCall:E5e},pZ=({muted:n,...e})=>{const{t}=Qe(),r=n?IY:wL,i=t(n?"unmute_microphone_button_label":"mute_microphone_button_label");return w.jsx(ui,{label:i,children:w.jsx(Mt,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},mZ=({muted:n,...e})=>{const{t}=Qe(),r=n?cIe:WY,i=t(n?"start_video_button_label":"stop_video_button_label");return w.jsx(ui,{label:i,children:w.jsx(Mt,{iconOnly:!0,Icon:r,kind:n?"primary":"secondary",...e})})},gZ=n=>{const{t:e}=Qe();return w.jsx(ui,{label:e("switch_camera"),children:w.jsx(Mt,{iconOnly:!0,Icon:sIe,kind:"secondary",...n})})},T5e=({enabled:n,...e})=>{const{t}=Qe(),r=t(n?"stop_screenshare_button_label":"screenshare_button_label");return w.jsx(ui,{label:r,children:w.jsx(Mt,{iconOnly:!0,Icon:nIe,kind:n?"primary":"secondary",...e})})},vZ=({className:n,...e})=>{const{t}=Qe();return w.jsx(ui,{label:t("hangup_button_label"),children:w.jsx(Mt,{className:De(n,C5e.endCall),iconOnly:!0,Icon:vY,destructive:!0,...e})})},yZ=n=>{const{t:e}=Qe();return w.jsx(ui,{label:e("common.settings"),children:w.jsx(Mt,{iconOnly:!0,Icon:tIe,kind:"secondary",...n})})},I5e="_external_jhjdf_8",R5e={external:I5e};function _Z(n,e){const t=TV(n),r=NV(n,{state:e});return[t,r]}const Aa=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=_Z(e,t);return w.jsx(MEe,{ref:i,...r,href:s,onClick:o})}),bd=_.forwardRef(function({className:e,children:t,...r},i){return w.jsx("a",{ref:i,className:De(e,R5e.external),target:"_blank",rel:"noreferrer noopener",...r,children:t})}),r4=_.forwardRef(function({to:e,state:t,...r},i){const[s,o]=_Z(e,t);return w.jsx(Mt,{as:"a",ref:i,...r,href:s,onClick:o})});function bZ(n){const[e,t]=_.useState(n.memberships),r=_.useCallback(()=>{M.info(`Memberships changed for call in room ${n.room.roomId} (${n.memberships.length} members)`),t(n.memberships)},[n]);return _.useEffect(()=>(n.on(ts.MembershipsChanged,r),()=>{n.off(ts.MembershipsChanged,r)}),[n,r]),e}const SZ=_.createContext(void 0),i4=()=>{const n=_.useContext(SZ);if(!n)throw new Error("useReactions must be used within a ReactionsProvider");return n},k5e=({children:n,rtcSession:e,vm:t})=>{const r=bZ(e),i=jp(),s=(i==null?void 0:i.state)==="valid"&&i.supportedFeatures.reactions,o=e.room,a=o.client.getUserId(),c=o.client.getDeviceId(),l=`${a}:${c}`,u=_.useMemo(()=>{var b;return(b=r.find(R=>R.sender===a&&R.deviceId===c))==null?void 0:b.eventId},[r,a,c]),h=ot(t.reactions$),p=_.useMemo(()=>l!==void 0?h[l]:void 0,[l,h]),m=ot(t.handsRaised$),v=_.useMemo(()=>l!==void 0?m[l]:void 0,[l,m]),g=_.useCallback(async()=>{if(!l)return;const b=v==null?void 0:v.reactionEventId;if(b)try{await o.client.redactEvent(e.room.roomId,b),M.debug("Redacted raise hand event")}catch(R){throw M.error("Failed to redact reaction event",b,R),R}else try{if(!u)throw new Error("Cannot find own membership event");const R=await o.client.sendEvent(e.room.roomId,ie.Reaction,{"m.relates_to":{rel_type:sn.Annotation,event_id:u,key:"🖐️"}});M.debug("Sent raise hand event",R.event_id)}catch(R){M.error("Failed to send raised hand",R)}},[u,l,v,e,o]),S=_.useCallback(async b=>{if(!(!l||p)){if(!u)throw new Error("Cannot find own membership event");await o.client.sendEvent(e.room.roomId,KL,{"m.relates_to":{rel_type:sn.Reference,event_id:u},emoji:b.emoji,name:b.name})}},[u,p,o,l,e]);return w.jsx(SZ.Provider,{value:{supportsReactions:s,toggleRaisedHand:g,sendReaction:S},children:n})},x5e="_raisedButton_unw54_1",P5e="_reactionPopupMenu_unw54_5",L5e="_reactionPopupMenuRoot_unw54_21",A5e="_reactionPopupMenuModal_unw54_21",O5e="_reactionsMenuSection_unw54_47",M5e="_reactionsMenu_unw54_47",N5e="_reactionButton_unw54_81",D5e="_verticalSeperator_unw54_91",F5e="_alert_unw54_99",Io={raisedButton:x5e,reactionPopupMenu:P5e,reactionPopupMenuRoot:L5e,reactionPopupMenuModal:A5e,reactionsMenuSection:O5e,reactionsMenu:M5e,reactionButton:N5e,verticalSeperator:D5e,alert:F5e};var wZ=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(j5e);if(s){const o=s.props.children,a=i.map(c=>c===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:c);return w.jsx(Rx,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return w.jsx(Rx,{...r,ref:e,children:t})});wZ.displayName="Slot";var Rx=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=B5e(t),s=$5e(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Va(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});Rx.displayName="SlotClone";var U5e=({children:n})=>w.jsx(w.Fragment,{children:n});function j5e(n){return _.isValidElement(n)&&n.type===U5e}function $5e(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function B5e(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var H5e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],V5e=H5e.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?wZ:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),w.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{}),G5e="VisuallyHidden",kx=_.forwardRef((n,e)=>w.jsx(V5e.span,{...n,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...n.style}}));kx.displayName=G5e;const q5e="_modal_lmgdq_8",K5e="_dialog_lmgdq_14",W5e="_content_lmgdq_21",z5e="_drawer_lmgdq_32",Y5e="_close_lmgdq_59",X5e="_header_lmgdq_84",J5e="_body_lmgdq_114",Z5e="_tabbed_lmgdq_129",Q5e="_handle_lmgdq_133",Ui={modal:q5e,dialog:K5e,content:W5e,drawer:z5e,close:Y5e,header:X5e,body:J5e,tabbed:Z5e,handle:Q5e},eNe="_bg_197ap_8",tNe="_animate_197ap_23",nNe="_overlay_197ap_40",_a={bg:eNe,animate:tNe,overlay:nNe},th=({title:n,hideHeader:e,children:t,className:r,classNameDrawer:i,classNameModal:s,open:o,onDismiss:a,tabbed:c,...l})=>{const{t:u}=Qe(),h=iE("(hover: none) or (pointer: coarse)"),p=_.useCallback(m=>{m||a==null||a()},[a]);if(h)return w.jsx(Ki.Root,{open:o,onOpenChange:p,dismissible:a!==void 0,children:w.jsxs(Ki.Portal,{children:[w.jsx(Ki.Overlay,{className:De(_a.bg)}),w.jsx(Ki.Content,{className:De(r,i,_a.overlay,Ui.modal,Ui.drawer,{[Ui.tabbed]:c}),role:"dialog","aria-describedby":void 0,...l,children:w.jsxs("div",{className:Ui.content,children:[w.jsxs("div",{className:Ui.header,children:[w.jsx("div",{className:Ui.handle}),w.jsx(kx,{asChild:!0,children:w.jsx(Ki.Title,{children:n})})]}),w.jsx("div",{className:Ui.body,children:t})]})})]})});{const m=w.jsx(oL,{asChild:!0,children:w.jsx(Su,{as:"h2",weight:"semibold",size:"md",children:n})}),v=w.jsxs("div",{className:Ui.header,children:[m,a!==void 0&&w.jsx(gz,{className:Ui.close,"data-testid":"modal_close","aria-label":u("action.close"),children:w.jsx(Gw,{width:20,height:20})})]});return w.jsx(nL,{open:o,onOpenChange:p,children:w.jsxs(rL,{children:[w.jsx(iL,{className:De(_a.bg,_a.animate)}),w.jsx(sL,{asChild:!0,"aria-describedby":void 0,role:"dialog",...l,children:w.jsx(kz,{className:De(r,s,_a.overlay,_a.animate,Ui.modal,Ui.dialog,{[Ui.tabbed]:c}),children:w.jsxs("div",{className:Ui.content,children:[e?null:v,e?w.jsx(kx,{asChild:!0,children:m}):null,w.jsx("div",{className:Ui.body,children:t})]})})})]})})}},rNe=({raised:n,open:e,...t})=>{const{t:r}=Qe();return w.jsx(ui,{label:r("common.reactions"),children:w.jsx(Mt,{className:De(n&&Io.raisedButton),"aria-expanded":e,"aria-haspopup":!0,kind:n||e?"primary":"secondary",iconOnly:!0,Icon:n?MY:eIe,...t})})};function iNe({sendReaction:n,toggleRaisedHand:e,isHandRaised:t,canReact:r,errorText:i}){const{t:s}=Qe(),[o,a]=_.useState(!1),c=_.useMemo(()=>o?jv:jv.slice(0,5),[o]),l=s(t?"action.lower_hand":"action.raise_hand");return w.jsxs(w.Fragment,{children:[i&&w.jsx(Q1e,{className:Io.alert,type:"critical",title:s("error.generic"),children:i}),w.jsxs("div",{className:Io.reactionPopupMenu,children:[w.jsx("section",{className:Io.handRaiseSection,children:w.jsx(ui,{label:l,caption:"H",children:w.jsx(Mt,{kind:t?"primary":"secondary","aria-keyshortcuts":"H","aria-pressed":t,"aria-label":l,onClick:()=>e(),iconOnly:!0,Icon:MY})})}),w.jsx("div",{className:Io.verticalSeperator}),w.jsx("section",{className:Io.reactionsMenuSection,children:w.jsx("menu",{className:De(o&&Io.reactionsMenuExpanded,Io.reactionsMenu),children:c.map((u,h)=>w.jsx("li",{children:w.jsx(ui,{label:u.name,caption:h<wx?(h+1).toString():void 0,children:w.jsx(Mt,{kind:"secondary",className:Io.reactionButton,disabled:!r,onClick:()=>n(u),"aria-keyshortcuts":h<wx?(h+1).toString():void 0,children:u.emoji})})},u.name))})}),w.jsx("section",{style:{marginLeft:"var(--cpd-separator-spacing)"},children:w.jsx(ui,{label:s(o?"action.show_less":"action.show_more"),children:w.jsx(Mt,{iconOnly:!0,"aria-label":s(o?"action.show_less":"action.show_more"),Icon:o?VTe:pTe,kind:"tertiary",onClick:()=>a(!o)})})})]})]})}function sNe({identifier:n,vm:e,...t}){const{t:r}=Qe(),{toggleRaisedHand:i,sendReaction:s}=i4(),[o,a]=_.useState(!1),[c,l]=_.useState(!1),[u,h]=_.useState(),p=Vv(e.handsRaised$.pipe(Fe(S=>!!S[n]))),m=Vv(e.reactions$.pipe(Fe(S=>!S[n])));_.useEffect(()=>{h(void 0)},[c]);const v=_.useCallback(async S=>{try{a(!0),await s(S),h(void 0),l(!1)}catch(b){h(b instanceof Error?b.message:"Unknown error"),M.error("Failed to send reaction",b)}finally{a(!1)}},[s]),g=_.useCallback(()=>{(async()=>{try{a(!0),await i(),l(!1)}catch(b){h(b instanceof Error?b.message:"Unknown error"),M.error("Failed to raise/lower hand",b)}finally{a(!1)}})()},[i]);return w.jsxs(w.Fragment,{children:[w.jsx(rNe,{disabled:o,onClick:()=>l(S=>!S),raised:!!p,open:c,...t}),w.jsx(th,{open:c,title:r("action.pick_reaction"),hideHeader:!0,classNameModal:Io.reactionPopupMenuModal,className:Io.reactionPopupMenuRoot,onDismiss:()=>l(!1),children:w.jsx(iNe,{errorText:u,isHandRaised:!!p,canReact:!o&&!!m,sendReaction:S=>void v(S),toggleRaisedHand:g})})]})}const qv=({Icon:n,title:e,rageshake:t,fatal:r,children:i,widget:s})=>{const{t:o}=Qe(),{confineToRoom:a}=eh(),c=_.useCallback(()=>{window.location.href="/"},[]),l=({widget:h})=>{const p=()=>{h.api.transport.send(xr.Close,{}).catch(m=>{M.error("Failed to send close action",m)}).finally(()=>{h.api.transport.stop()})};return w.jsx(Mt,{kind:"primary",onClick:p,children:o("action.close")})},u=()=>r||location.pathname==="/"?w.jsx(Mt,{kind:"tertiary",className:Y1.homeLink,onClick:c,children:o("return_home_button")}):w.jsx(r4,{kind:"tertiary",className:Y1.homeLink,to:"/",children:o("return_home_button")});return w.jsxs("div",{className:Y1.error,children:[w.jsx(cTe,{className:Y1.icon,children:w.jsx(n,{})}),w.jsx(Su,{as:"h1",weight:"semibold",size:"md",children:e}),i,t&&w.jsx(b5e,{description:`***Error View***: ${e}`}),s?w.jsx(l,{widget:s}):!a&&w.jsx(u,{})]})};class EZ extends Error{constructor(e,t){super(e),this.richMessage=t}}const oNe=()=>{const{t:n}=Qe();return w.jsx(qv,{widget:Je,Icon:AY,title:n("error.open_elsewhere"),children:w.jsx("p",{children:n("error.open_elsewhere_description",{brand:"Element Call"})})})};class aNe extends EZ{constructor(){super("App opened in another tab",w.jsx(oNe,{}))}}const Uf=({className:n,children:e})=>{const{hideHeader:t}=eh();return w.jsxs("div",{className:De(u2.page,n),children:[!t&&w.jsxs(wu,{children:[w.jsx(Jd,{children:w.jsx(Dd,{})}),w.jsx(Zd,{})]}),w.jsx("div",{className:u2.container,children:w.jsx("div",{className:u2.content,children:e})})]})},Kv=({error:n,widget:e})=>{const{t}=Qe();return _.useEffect(()=>{M.error(n),jw(n)},[n]),w.jsx(Uf,{children:n instanceof EZ?n.richMessage:w.jsx(qv,{widget:e,Icon:Vw,title:t("error.generic"),rageshake:!0,fatal:!0,children:w.jsx("p",{children:t("error.generic_description")})})})},_E=()=>{const{t:n}=Qe();return w.jsx(Uf,{children:w.jsx("h1",{children:n("common.loading")})})},s4=_.createContext(void 0);s4.Provider;const jp=()=>_.useContext(s4);function nh(){var r;let n,e;const t=jp();return(t==null?void 0:t.state)==="valid"&&(n=(r=t.authenticated)==null?void 0:r.client,e=t.setClient),{client:n,setClient:e}}function o4(){var c,l,u;const n=jp();let e,t,r=!1,i=!0,s,o=!1,a;return(n==null?void 0:n.state)==="valid"?(e=(c=n.authenticated)==null?void 0:c.client,t=n.setClient,r=((l=n.authenticated)==null?void 0:l.isPasswordlessUser)??!1,i=!1,o=e!==void 0,a=(u=n.authenticated)==null?void 0:u.logout):(n==null?void 0:n.state)==="error"&&(s=n.error,i=!1),{client:e,setClient:t,passwordlessUser:r,loading:i,authenticated:o,logout:a,error:s}}const X1="BroadcastChannel"in window?new BroadcastChannel("load"):null,cNe=({children:n})=>{const e=ja(),[t,r]=_.useState(void 0),i=_.useRef(!1);_.useEffect(()=>{i.current||(i.current=!0,lNe().then(r).catch(R=>M.error(R)).finally(()=>i.current=!1))},[]);const s=_.useCallback(async R=>{const k=CZ();!(t!=null&&t.client)||!k||(await t.client.setPassword({type:"m.login.password",identifier:{type:"m.id.user",user:k.user_id},user:k.user_id,password:k.tempPassword},R),QD({...k,passwordlessUser:!1}),r({...t,passwordlessUser:!1}))},[t]),o=_.useCallback(R=>{const k=t==null?void 0:t.client,I=R==null?void 0:R.client;k&&k!==I&&k.stopClient(),R?(QD(R.session),r({widgetApi:null,client:R.client,passwordlessUser:R.session.passwordlessUser})):(xx(),r(null))},[t==null?void 0:t.client]),a=_.useCallback(async()=>{const R=t==null?void 0:t.client;R&&(await R.logout(!0),await R.clearStores(),xx(),r(null),await e("/"),jt.instance.setRegistrationType(vE.Guest))},[e,t==null?void 0:t.client]);_.useEffect(()=>{Je||X1==null||X1.postMessage({})},[]);const[c,l]=_.useState(void 0);Bg(X1,"message",_.useCallback(()=>{t==null||t.client.stopClient(),l(new aNe)},[t==null?void 0:t.client,l]));const[u,h]=_.useState(!1),[p,m]=_.useState(!1),[v,g]=_.useState(!1),S=_.useMemo(()=>c?{state:"error",error:c}:t===void 0?void 0:{state:"valid",authenticated:t===null?void 0:{client:t.client,isPasswordlessUser:t.passwordlessUser,changePassword:s,logout:a},setClient:o,disconnected:u,supportedFeatures:{reactions:p,thumbnails:v}},[c,s,t,a,o,u,p,v]),b=_.useCallback((R,k,I)=>{h(uNe(R,I))},[]);return _.useEffect(()=>{if(t){if(window.matrixclient=t.client,window.passwordlessUser=t.passwordlessUser,jt.hasInstance()&&jt.instance.onLoginStatusChanged(),t.client&&t.client.on(Ge.Sync,b),t.widgetApi){g(!1);const R=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.reaction"),k=t.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.room.redaction"),I=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.reaction"),T=t.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.room.redaction");!R||!I||!k||!T?(M.warn("Widget does not support reactions"),m(!1)):m(!0)}else m(!0),g(!0);return()=>{t.client&&t.client.removeListener(Ge.Sync,b)}}},[t,b]),c?w.jsx(Kv,{widget:Je,error:c}):w.jsx(s4.Provider,{value:S,children:n})};async function lNe(){if(Je){M.log("Using a matryoshka client");const n=await Je.client;return{widgetApi:Je.api,client:n,passwordlessUser:!1}}else{const{initSPA:n}=await rv(async()=>{const{initSPA:e}=await import("./spa-CCVn2ay1.js");return{initSPA:e}},[],import.meta.url);return n(CZ,xx)}}const xx=()=>localStorage.removeItem("matrix-auth-store"),QD=n=>localStorage.setItem("matrix-auth-store",JSON.stringify(n)),CZ=()=>{const n=localStorage.getItem("matrix-auth-store");if(n)return JSON.parse(n)},uNe=(n,e)=>{var t;return n==="ERROR"&&((t=e==null?void 0:e.error)==null?void 0:t.name)==="ConnectionError"};function Ly(n){const[{success:e,loading:t,displayName:r,avatarUrl:i,error:s},o]=_.useState(()=>{let c;return n&&(c=n.getUser(n.getUserId())??void 0),{success:!1,loading:!1,displayName:c==null?void 0:c.rawDisplayName,avatarUrl:c==null?void 0:c.avatarUrl,error:void 0}});_.useEffect(()=>{const c=(u,{displayName:h,avatarUrl:p})=>{o({success:!1,loading:!1,displayName:h,avatarUrl:p,error:void 0})};let l;if(n){const u=n.getUserId();l=n.getUser(u),l==null||l.on(Ol.DisplayName,c),l==null||l.on(Ol.AvatarUrl,c)}return()=>{l&&(l.removeListener(Ol.DisplayName,c),l.removeListener(Ol.AvatarUrl,c))}},[n]);const a=_.useCallback(async({displayName:c,avatar:l,removeAvatar:u})=>{if(n){o(h=>({...h,loading:!0,error:void 0,success:!1}));try{await n.setDisplayName(c);let h;u?await n.setAvatarUrl(""):l&&({content_uri:h}=await n.uploadContent(l),await n.setAvatarUrl(h)),o(p=>({...p,displayName:c,avatarUrl:u?void 0:h??p.avatarUrl,loading:!1,success:!0}))}catch(h){o(p=>({...p,loading:!1,error:h instanceof Error?h:Error(h),success:!1}))}}else M.error("Client not initialized before calling saveProfile")},[n]);return{loading:t,error:s,displayName:r,avatarUrl:i,saveProfile:a,success:e}}const dNe="_settingsModal_1dkeq_8",hNe="_volumeSlider_1dkeq_20",eF={settingsModal:dNe,volumeSlider:hNe},fNe="_tabContainer_1nnp9_8",pNe="_tabList_1nnp9_14",tF={tabContainer:fNe,tabList:pNe};function mNe({label:n,tab:e,onTabChange:t,tabs:r}){const i=_.useId();return w.jsxs("div",{className:tF.tabContainer,children:[w.jsx(lTe,{role:"tablist","aria-label":n,className:tF.tabList,children:r.map(({key:s,name:o})=>w.jsx(fTe,{"aria-controls":`${i}[${s}]`,onClick:()=>t(s),active:s===e,children:o}))}),r.map(({key:s,content:o})=>w.jsx("div",{id:`${i}[${s}]`,style:{display:s===e?void 0:"none"},children:o}))]})}const gNe="_fieldRow_iwncy_8",vNe="_field_iwncy_8",yNe="_rightAlign_iwncy_21",_Ne="_inputField_iwncy_33",bNe="_disabled_iwncy_52",SNe="_prefix_iwncy_110",wNe="_checkboxField_iwncy_131",ENe="_checkbox_iwncy_131",CNe="_description_iwncy_168",TNe="_errorMessage_iwncy_197",INe="_noLabel_iwncy_210",js={fieldRow:gNe,field:vNe,rightAlign:yNe,inputField:_Ne,disabled:bNe,prefix:SNe,checkboxField:wNe,checkbox:ENe,description:CNe,errorMessage:TNe,noLabel:INe},RNe=(n,e)=>_.createElement("svg",{fill:"none",height:24,stroke:"#000",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,viewBox:"0 0 24 24",width:24,xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{d:"m20 6-11 11-5-5"})),kNe=_.forwardRef(RNe);class TZ extends Error{constructor(e,t){super(t(e,{lng:"en"})),this.translatedMessage=t(e)}}class xNe extends TZ{}const nF=(n,e)=>new xNe(n,e);function yt({children:n,rightAlign:e,className:t}){return w.jsx("div",{className:De(js.fieldRow,{[js.rightAlign]:e},t),children:n})}function PNe({children:n,className:e}){return w.jsx("div",{className:De(js.field,e),children:n})}const vn=_.forwardRef(({id:n,label:e,className:t,type:r,checked:i,prefix:s,suffix:o,description:a,disabled:c,min:l,...u},h)=>{const p=_.useId();return w.jsxs(PNe,{className:De(r==="checkbox"?js.checkboxField:js.inputField,{[js.prefix]:!!s,[js.disabled]:c},t),children:[s&&w.jsx("span",{children:s}),r==="textarea"?w.jsx("textarea",{id:n,ref:h,disabled:c,"aria-describedby":p,...u}):w.jsx("input",{id:n,ref:h,type:r,checked:i,disabled:c,"aria-describedby":p,min:l,...u}),w.jsxs("label",{htmlFor:n,children:[r==="checkbox"&&w.jsx("div",{className:js.checkbox,children:w.jsx(kNe,{})}),e]}),o&&w.jsx("span",{children:o}),a&&w.jsx("p",{id:p,className:e?js.description:De(js.description,js.noLabel),children:a})]})});vn.displayName="InputField";const Cu=({error:n})=>w.jsx("p",{className:js.errorMessage,children:n instanceof TZ?n.translatedMessage:n.message}),LNe="_avatarInputField_1ep5q_8",ANe="_avatar_1ep5q_8",ONe="_fileInput_1ep5q_17",MNe="_edit_1ep5q_21",J1={avatarInputField:LNe,avatar:ANe,fileInput:ONe,edit:MNe},IZ=({id:n,label:e,className:t,avatarUrl:r,userId:i,displayName:s,onRemoveAvatar:o,...a})=>{const{t:c}=Qe(),[l,u]=_.useState(!1),[h,p]=_.useState(void 0),[m,v]=_.useState(!1),g=_.useRef(null);_.useEffect(()=>{const R=g.current,k=I=>{const T=I;T.target.files&&T.target.files.length>0?(p(URL.createObjectURL(T.target.files[0])),u(!1)):p(void 0)};return R.addEventListener("change",k),()=>{R==null||R.removeEventListener("change",k)}});const S=_.useCallback(()=>{g.current.click()},[g]),b=_.useCallback(()=>{u(!0),o()},[o]);return w.jsxs("div",{className:De(J1.avatarInputField,t),children:[w.jsx(Np,{id:i,className:J1.avatar,name:s,size:Mp.XL,src:l?void 0:h||r}),w.jsx("input",{id:n,accept:"image/*",ref:g,type:"file",className:J1.fileInput,role:"button","aria-label":e,...a}),w.jsx("div",{className:J1.edit,children:(r||h)&&!l?w.jsxs(hL,{title:c("action.edit"),showTitle:!1,open:m,onOpenChange:v,trigger:w.jsx(Mt,{iconOnly:!0,Icon:s7,kind:"tertiary",size:"sm","aria-label":c("action.edit")}),children:[w.jsx(ip,{Icon:rIe,label:c("action.upload_file"),onSelect:S}),w.jsx(ip,{Icon:qTe,label:c("action.remove"),kind:"critical",onSelect:b})]}):w.jsx(Mt,{type:"button",iconOnly:!0,Icon:s7,kind:"tertiary",size:"sm","aria-label":c("action.edit"),onClick:S})})]})};IZ.displayName="AvatarInputField";const NNe="_content_gj715_8",DNe="_avatarFieldRow_gj715_15",rF={content:NNe,avatarFieldRow:DNe},FNe=({client:n})=>{const{t:e}=Qe(),{error:t,displayName:r,avatarUrl:i,saveProfile:s}=Ly(n),o=_.useMemo(()=>n.getUserId(),[n]),a=_.useRef(null),c=_.useRef(!1),l=_.useCallback(()=>{c.current=!0},[]),u=_.useRef(!1),h=_.useCallback(()=>{u.current=!0,c.current=!0},[]);return _.useEffect(()=>{const p=a.current;return()=>{if(c.current){const m=new FormData(p),v=m.get("displayName"),g=m.get("avatar"),S=typeof g=="string"?g.length:(g==null?void 0:g.size)??0,b=typeof v=="string"?v:(v==null?void 0:v.name)??null;if(!b)return;s({displayName:b,avatar:g&&S>0?g:void 0,removeAvatar:u.current&&(!g||S===0)}).catch(R=>{M.error("Failed to save profile",R)})}}},[s]),w.jsxs("form",{onChange:l,ref:a,className:rF.content,children:[w.jsx(yt,{className:rF.avatarFieldRow,children:o&&r&&w.jsx(IZ,{id:"avatar",name:"avatar",label:e("common.avatar"),avatarUrl:i,userId:o,displayName:r,onRemoveAvatar:h})}),w.jsx(yt,{children:w.jsx(vn,{id:"userId",name:"userId",label:e("common.username"),type:"text",disabled:!0,value:n.getUserId()})}),w.jsx(yt,{children:w.jsx(vn,{id:"displayName",name:"displayName",label:e("common.display_name"),type:"text",required:!0,autoComplete:"off",placeholder:e("common.display_name"),defaultValue:r,"data-testid":"profile_displayname"})}),t&&w.jsx(yt,{children:w.jsx(Cu,{error:t})})]})},UNe="_feedback_19yh9_8",RZ={feedback:UNe},a4=()=>w.jsxs(Ci,{i18nKey:"analytics_notice",children:["By participating in this beta, you consent to the collection of anonymous data, which we use to improve the product. You can find more information about which data we track in our"," ",w.jsx(bd,{href:"https://element.io/privacy",children:"Privacy Policy"})," ","and our"," ",w.jsx(bd,{href:"https://element.io/cookie-policy",children:"Cookie Policy"}),"."]}),jNe=({roomId:n})=>{const{t:e}=Qe(),{submitRageshake:t,sending:r,sent:i,error:s}=n4(),o=y5e(),a=_.useCallback(h=>{h.preventDefault();const p=new FormData(h.target),m=p.get("description"),v=typeof m=="string"?m:"",g=!!p.get("sendLogs"),S=Es(16);t({description:v,sendLogs:g,rageshakeRequestId:S,roomId:n}).catch(b=>{M.error("Failed to send feedback rageshake",b)}),n&&g&&o(n,S)},[t,n,o]),[c,l]=gE(),u=w.jsx(Xt,{size:"sm",children:w.jsxs(Ci,{i18nKey:"settings.opt_in_description",children:[w.jsx(a4,{}),w.jsx("br",{}),"You may withdraw consent by unchecking this box. If you are currently in a call, this setting will take effect at the end of the call."]})});return w.jsxs("div",{children:[w.jsx("h4",{children:e("common.analytics")}),w.jsx(yt,{children:w.jsx(vn,{id:"optInAnalytics",type:"checkbox",checked:c??void 0,description:u,onChange:h=>{l==null||l(h.target.checked)}})}),w.jsx("h4",{children:e("settings.feedback_tab_h4")}),w.jsx(Xt,{children:e("settings.feedback_tab_body")}),w.jsxs("form",{onSubmit:a,children:[w.jsx(yt,{children:w.jsx(vn,{className:RZ.feedback,id:"description",name:"description",label:e("settings.feedback_tab_description_label"),placeholder:e("settings.feedback_tab_description_label"),type:"textarea",disabled:r||i})}),!i&&w.jsxs(yt,{children:[w.jsx(vn,{id:"sendLogs",name:"sendLogs",label:e("settings.feedback_tab_send_logs_label"),type:"checkbox",defaultChecked:!0}),w.jsx(Mt,{type:"submit",disabled:r,children:e(r?"submitting":"action.submit")})]}),w.jsxs(yt,{children:[s&&w.jsx(Cu,{error:s}),i&&w.jsx(Xt,{children:e("settings.feedback_tab_thank_you")})]})]})]})};var ub={exports:{}},$Ne=ub.exports,iF;function BNe(){return iF||(iF=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})($Ne,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(g,S){var b=g[S];if(typeof b.bind=="function")return b.bind(g);try{return Function.prototype.bind.call(b,g)}catch{return function(){return Function.prototype.apply.apply(b,[g,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&r?c:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function u(){for(var g=this.getLevel(),S=0;S<i.length;S++){var b=i[S];this[b]=S<g?e:this.methodFactory(b,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function h(g){return function(){typeof console!==t&&(u.call(this),this[g].apply(this,arguments))}}function p(g,S,b){return l(g)||h.apply(this,arguments)}function m(g,S){var b=this,R,k,I,T="loglevel";typeof g=="string"?T+=":"+g:typeof g=="symbol"&&(T=void 0);function C(U){var B=(i[U]||"silent").toUpperCase();if(!(typeof window===t||!T)){try{window.localStorage[T]=B;return}catch{}try{window.document.cookie=encodeURIComponent(T)+"="+B+";"}catch{}}}function P(){var U;if(!(typeof window===t||!T)){try{U=window.localStorage[T]}catch{}if(typeof U===t)try{var B=window.document.cookie,V=encodeURIComponent(T),z=B.indexOf(V+"=");z!==-1&&(U=/^([^;]+)/.exec(B.slice(z+V.length+1))[1])}catch{}return b.levels[U]===void 0&&(U=void 0),U}}function O(){if(!(typeof window===t||!T)){try{window.localStorage.removeItem(T)}catch{}try{window.document.cookie=encodeURIComponent(T)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function D(U){var B=U;if(typeof B=="string"&&b.levels[B.toUpperCase()]!==void 0&&(B=b.levels[B.toUpperCase()]),typeof B=="number"&&B>=0&&B<=b.levels.SILENT)return B;throw new TypeError("log.setLevel() called with invalid level: "+U)}b.name=g,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||p,b.getLevel=function(){return I??k??R},b.setLevel=function(U,B){return I=D(U),B!==!1&&C(I),u.call(b)},b.setDefaultLevel=function(U){k=D(U),P()||b.setLevel(U,!1)},b.resetLevel=function(){I=null,O(),u.call(b)},b.enableAll=function(U){b.setLevel(b.levels.TRACE,U)},b.disableAll=function(U){b.setLevel(b.levels.SILENT,U)},b.rebuild=function(){if(o!==b&&(R=D(o.getLevel())),u.call(b),o===b)for(var U in s)s[U].rebuild()},R=D(o?o.getLevel():"WARN");var F=P();F!=null&&(I=D(F)),u.call(b)}o=new m,o.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[S];return b||(b=s[S]=new m(S,o.methodFactory)),b};var v=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})}(ub)),ub.exports}var HNe=BNe();const VNe=Wo(HNe);var GNe=(n,e,t)=>new Promise((r,i)=>{var s=c=>{try{a(t.next(c))}catch(l){i(l)}},o=c=>{try{a(t.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);a((t=t.apply(n,e)).next())}),qNe=[he.ConnectionStateChanged,he.RoomMetadataChanged,he.ActiveSpeakersChanged,he.ConnectionQualityChanged,he.ParticipantConnected,he.ParticipantDisconnected,he.ParticipantPermissionsChanged,he.ParticipantMetadataChanged,he.ParticipantNameChanged,he.ParticipantAttributesChanged,he.TrackMuted,he.TrackUnmuted,he.TrackPublished,he.TrackUnpublished,he.TrackStreamStateChanged,he.TrackSubscriptionFailed,he.TrackSubscriptionPermissionChanged,he.TrackSubscriptionStatusChanged],KNe=[...qNe,he.LocalTrackPublished,he.LocalTrackUnpublished];ue.TrackPublished,ue.TrackUnpublished,ue.TrackMuted,ue.TrackUnmuted,ue.TrackStreamStateChanged,ue.TrackSubscribed,ue.TrackUnsubscribed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionFailed,ue.LocalTrackPublished,ue.LocalTrackUnpublished;var WNe=[ue.ConnectionQualityChanged,ue.IsSpeakingChanged,ue.ParticipantMetadataChanged,ue.ParticipantPermissionsChanged,ue.TrackMuted,ue.TrackUnmuted,ue.TrackPublished,ue.TrackUnpublished,ue.TrackStreamStateChanged,ue.TrackSubscriptionFailed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionStatusChanged];[...WNe,ue.LocalTrackPublished,ue.LocalTrackUnpublished];var zNe=VNe.getLogger("lk-components-js");zNe.setDefaultLevel("WARN");function YNe(n,...e){return new Ln(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(ln(n))}function XNe(n,e){return new Ln(r=>{const i=(...o)=>{r.next(o)};return n.on(e,i),()=>{n.off(e,i)}})}function JNe(n,e,t=!0){var r;const i=()=>GNe(this,null,function*(){try{const a=yield Mc.getLocalDevices(n,t);s.next(a)}catch(a){e==null||e(a)}}),s=new Rr,o=s.pipe(sZ(()=>{var a;(a=navigator==null?void 0:navigator.mediaDevices)==null||a.removeEventListener("devicechange",i)}));if(typeof window<"u"){if(!window.isSecureContext)throw new Error("Accessing media devices is available only in secure contexts (HTTPS and localhost), in some or all supporting browsers. See: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mediaDevices");(r=navigator==null?void 0:navigator.mediaDevices)==null||r.addEventListener("devicechange",i)}return DS(Mc.getLocalDevices(n,t).catch(a=>(e==null||e(a),[])),o)}function c4(n,...e){return new Ln(r=>{const i=()=>{r.next(n)};return e.forEach(o=>{n.on(o,i)}),()=>{e.forEach(o=>{n.off(o,i)})}}).pipe(ln(n))}function l4(n){return c4(n,ue.TrackMuted,ue.TrackUnmuted,ue.ParticipantPermissionsChanged,ue.TrackPublished,ue.TrackUnpublished,ue.LocalTrackPublished,ue.LocalTrackUnpublished,ue.MediaDevicesError,ue.TrackSubscriptionStatusChanged).pipe(Fe(t=>{const{isMicrophoneEnabled:r,isCameraEnabled:i,isScreenShareEnabled:s}=t,o=t.getTrackPublication(pe.Source.Microphone),a=t.getTrackPublication(pe.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:r,isScreenShareEnabled:s,cameraTrack:a,microphoneTrack:o,participant:t}}))}function ZNe(n,e={}){var t;let r;const i=new Ln(c=>(r=c,()=>a.unsubscribe())).pipe(ln(Array.from(n.remoteParticipants.values()))),s=(t=e.additionalRoomEvents)!=null?t:KNe,o=Array.from(new Set([he.ParticipantConnected,he.ParticipantDisconnected,he.ConnectionStateChanged,...s])),a=YNe(n,...o).subscribe(c=>r==null?void 0:r.next(Array.from(c.remoteParticipants.values())));return n.remoteParticipants.size>0&&(r==null||r.next(Array.from(n.remoteParticipants.values()))),i}new TextEncoder;new TextDecoder;function $2(n,e,t){const r=_.useRef(!1),i=t||r.current;r.current||(r.current=t);const s=_.useMemo(()=>JNe(n,()=>M.error("Error creating MediaDeviceObserver"),i).pipe(ln([])),[n,i]),o=ot(_.useMemo(()=>s.pipe(Fe(h=>{var m;let p=new Map(h.map((v,g)=>[v.deviceId,v.label?{type:"name",name:v.label}:{type:"number",number:g+1}]));return n==="audiooutput"&&p.size&&!p.has("")&&!p.has("default")&&(p=new Map([["",{type:"default",name:((m=h[0])==null?void 0:m.label)||null}],...p])),p})),[n,s])),[a,c]=Ar(e),l=_.useMemo(()=>{if(o.size)return a!==void 0&&o.has(a)||o.size===1&&o.has("")?a:o.keys().next().value},[o,a]),u=ot(_.useMemo(()=>s.pipe(Fe(h=>{var p;return(p=h.find(m=>m.deviceId===l))==null?void 0:p.groupId})),[s,l]));return _.useMemo(()=>({available:o,selectedId:l,selectedGroupId:u,select:c}),[o,l,u,c])}const B2={available:new Map,selectedId:void 0,selectedGroupId:void 0,select:()=>{}},QNe={audioInput:B2,audioOutput:B2,videoInput:B2,startUsingDeviceNames:()=>{},stopUsingDeviceNames:()=>{}},kZ=_.createContext(QNe),e8e=({children:n})=>{const[e,t]=_.useState(0),r=e>0,i=$2("audioinput",l5e,r),s=$2("audiooutput",u5e,r),o=$2("videoinput",d5e,r),a=_.useCallback(()=>t(u=>u+1),[t]),c=_.useCallback(()=>t(u=>u-1),[t]),l=_.useMemo(()=>({audioInput:i,audioOutput:s,videoInput:o,startUsingDeviceNames:a,stopUsingDeviceNames:c}),[i,s,o,a,c]);return w.jsx(kZ.Provider,{value:l,children:n})},rh=()=>_.useContext(kZ),t8e=(n,e=!0)=>_.useEffect(()=>{if(e)return n.startUsingDeviceNames(),n.stopUsingDeviceNames},[n,e]),n8e=()=>{const{t:n}=Qe(),[e,t]=Ar(uZ),[r,i]=Ar(dZ),[s,o]=Ar(t4),a=(u,h)=>{h(u.target.checked)},[c,l]=Ar(aZ);return w.jsxs("div",{children:[w.jsx(Xt,{children:n("settings.preferences_tab.introduction")}),w.jsx(yt,{children:w.jsx(vn,{id:"showHandRaisedTimer",label:n("settings.preferences_tab.show_hand_raised_timer_label"),description:n("settings.preferences_tab.show_hand_raised_timer_description"),type:"checkbox",checked:e,onChange:u=>a(u,t)})}),w.jsx(yt,{children:w.jsx(vn,{id:"showReactions",label:n("settings.preferences_tab.reactions_show_label"),description:n("settings.preferences_tab.reactions_show_description"),type:"checkbox",checked:r,onChange:u=>a(u,i)})}),w.jsx(yt,{children:w.jsx(vn,{id:"playReactionSound",label:n("settings.preferences_tab.reactions_play_sound_label"),description:n("settings.preferences_tab.reactions_play_sound_description"),type:"checkbox",checked:s,onChange:u=>a(u,o)})}),w.jsx(yt,{children:w.jsx(vn,{id:"developerSettingsTab",type:"checkbox",checked:c,label:n("settings.preferences_tab.developer_mode_label"),description:n("settings.preferences_tab.developer_mode_label_description"),onChange:u=>l(u.target.checked)})})]})};function xZ(n,[e,t]){return Math.min(t,Math.max(e,n))}function r8e(n){const e=_.useRef({value:n,previous:n});return _.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}var FS=_.forwardRef((n,e)=>{const{children:t,...r}=n,i=_.Children.toArray(t),s=i.find(s8e);if(s){const o=s.props.children,a=i.map(c=>c===s?_.Children.count(o)>1?_.Children.only(null):_.isValidElement(o)?o.props.children:null:c);return w.jsx(Px,{...r,ref:e,children:_.isValidElement(o)?_.cloneElement(o,void 0,a):null})}return w.jsx(Px,{...r,ref:e,children:t})});FS.displayName="Slot";var Px=_.forwardRef((n,e)=>{const{children:t,...r}=n;if(_.isValidElement(t)){const i=a8e(t),s=o8e(r,t.props);return t.type!==_.Fragment&&(s.ref=e?Va(e,i):i),_.cloneElement(t,s)}return _.Children.count(t)>1?_.Children.only(null):null});Px.displayName="SlotClone";var i8e=({children:n})=>w.jsx(w.Fragment,{children:n});function s8e(n){return _.isValidElement(n)&&n.type===i8e}function o8e(n,e){const t={...e};for(const r in e){const i=n[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?t[r]=(...a)=>{s(...a),i(...a)}:i&&(t[r]=i):r==="style"?t[r]={...i,...s}:r==="className"&&(t[r]=[i,s].filter(Boolean).join(" "))}return{...n,...t}}function a8e(n){var r,i;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(i=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var c8e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],bE=c8e.reduce((n,e)=>{const t=_.forwardRef((r,i)=>{const{asChild:s,...o}=r,a=s?FS:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),w.jsx(a,{...o,ref:i})});return t.displayName=`Primitive.${e}`,{...n,[e]:t}},{});function l8e(n){const e=n+"CollectionProvider",[t,r]=Ha(e),[i,s]=t(e,{collectionRef:{current:null},itemMap:new Map}),o=m=>{const{scope:v,children:g}=m,S=Re.useRef(null),b=Re.useRef(new Map).current;return w.jsx(i,{scope:v,itemMap:b,collectionRef:S,children:g})};o.displayName=e;const a=n+"CollectionSlot",c=Re.forwardRef((m,v)=>{const{scope:g,children:S}=m,b=s(a,g),R=rn(v,b.collectionRef);return w.jsx(FS,{ref:R,children:S})});c.displayName=a;const l=n+"CollectionItemSlot",u="data-radix-collection-item",h=Re.forwardRef((m,v)=>{const{scope:g,children:S,...b}=m,R=Re.useRef(null),k=rn(v,R),I=s(l,g);return Re.useEffect(()=>(I.itemMap.set(R,{ref:R,...b}),()=>void I.itemMap.delete(R))),w.jsx(FS,{[u]:"",ref:k,children:S})});h.displayName=l;function p(m){const v=s(n+"CollectionConsumer",m);return Re.useCallback(()=>{const S=v.collectionRef.current;if(!S)return[];const b=Array.from(S.querySelectorAll(`[${u}]`));return Array.from(v.itemMap.values()).sort((I,T)=>b.indexOf(I.ref.current)-b.indexOf(T.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:o,Slot:c,ItemSlot:h},p,r]}var PZ=["PageUp","PageDown"],LZ=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],AZ={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},$p="Slider",[Lx,u8e,d8e]=l8e($p),[OZ,dqe]=Ha($p,[d8e]),[h8e,SE]=OZ($p),MZ=_.forwardRef((n,e)=>{const{name:t,min:r=0,max:i=100,step:s=1,orientation:o="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:l=[r],value:u,onValueChange:h=()=>{},onValueCommit:p=()=>{},inverted:m=!1,form:v,...g}=n,S=_.useRef(new Set),b=_.useRef(0),k=o==="horizontal"?f8e:p8e,[I=[],T]=Yw({prop:u,defaultProp:l,onChange:U=>{var V;(V=[...S.current][b.current])==null||V.focus(),h(U)}}),C=_.useRef(I);function P(U){const B=_8e(I,U);F(U,B)}function O(U){F(U,b.current)}function D(){const U=C.current[b.current];I[b.current]!==U&&p(I)}function F(U,B,{commit:V}={commit:!1}){const z=E8e(s),H=C8e(Math.round((U-r)/s)*s+r,z),J=xZ(H,[r,i]);T((Y=[])=>{const G=v8e(Y,J,B);if(w8e(G,c*s)){b.current=G.indexOf(J);const K=String(G)!==String(Y);return K&&V&&p(G),K?G:Y}else return Y})}return w.jsx(h8e,{scope:n.__scopeSlider,name:t,disabled:a,min:r,max:i,valueIndexToChangeRef:b,thumbs:S.current,values:I,orientation:o,form:v,children:w.jsx(Lx.Provider,{scope:n.__scopeSlider,children:w.jsx(Lx.Slot,{scope:n.__scopeSlider,children:w.jsx(k,{"aria-disabled":a,"data-disabled":a?"":void 0,...g,ref:e,onPointerDown:Ze(g.onPointerDown,()=>{a||(C.current=I)}),min:r,max:i,inverted:m,onSlideStart:a?void 0:P,onSlideMove:a?void 0:O,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&F(r,0,{commit:!0}),onEndKeyDown:()=>!a&&F(i,I.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:B})=>{if(!a){const H=PZ.includes(U.key)||U.shiftKey&&LZ.includes(U.key)?10:1,J=b.current,Y=I[J],G=s*H*B;F(Y+G,J,{commit:!0})}}})})})})});MZ.displayName=$p;var[NZ,DZ]=OZ($p,{startEdge:"left",endEdge:"right",size:"width",direction:1}),f8e=_.forwardRef((n,e)=>{const{min:t,max:r,dir:i,inverted:s,onSlideStart:o,onSlideMove:a,onSlideEnd:c,onStepKeyDown:l,...u}=n,[h,p]=_.useState(null),m=rn(e,k=>p(k)),v=_.useRef(void 0),g=M6(i),S=g==="ltr",b=S&&!s||!S&&s;function R(k){const I=v.current||h.getBoundingClientRect(),T=[0,I.width],P=u4(T,b?[t,r]:[r,t]);return v.current=I,P(k-I.left)}return w.jsx(NZ,{scope:n.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:w.jsx(FZ,{dir:g,"data-orientation":"horizontal",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:k=>{const I=R(k.clientX);o==null||o(I)},onSlideMove:k=>{const I=R(k.clientX);a==null||a(I)},onSlideEnd:()=>{v.current=void 0,c==null||c()},onStepKeyDown:k=>{const T=AZ[b?"from-left":"from-right"].includes(k.key);l==null||l({event:k,direction:T?-1:1})}})})}),p8e=_.forwardRef((n,e)=>{const{min:t,max:r,inverted:i,onSlideStart:s,onSlideMove:o,onSlideEnd:a,onStepKeyDown:c,...l}=n,u=_.useRef(null),h=rn(e,u),p=_.useRef(void 0),m=!i;function v(g){const S=p.current||u.current.getBoundingClientRect(),b=[0,S.height],k=u4(b,m?[r,t]:[t,r]);return p.current=S,k(g-S.top)}return w.jsx(NZ,{scope:n.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:w.jsx(FZ,{"data-orientation":"vertical",...l,ref:h,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const S=v(g.clientY);s==null||s(S)},onSlideMove:g=>{const S=v(g.clientY);o==null||o(S)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:g=>{const b=AZ[m?"from-bottom":"from-top"].includes(g.key);c==null||c({event:g,direction:b?-1:1})}})})}),FZ=_.forwardRef((n,e)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:i,onSlideEnd:s,onHomeKeyDown:o,onEndKeyDown:a,onStepKeyDown:c,...l}=n,u=SE($p,t);return w.jsx(bE.span,{...l,ref:e,onKeyDown:Ze(n.onKeyDown,h=>{h.key==="Home"?(o(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):PZ.concat(LZ).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:Ze(n.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:Ze(n.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&i(h)}),onPointerUp:Ze(n.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),s(h))})})}),UZ="SliderTrack",jZ=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=SE(UZ,t);return w.jsx(bE.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...r,ref:e})});jZ.displayName=UZ;var Ax="SliderRange",$Z=_.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,i=SE(Ax,t),s=DZ(Ax,t),o=_.useRef(null),a=rn(e,o),c=i.values.length,l=i.values.map(p=>HZ(p,i.min,i.max)),u=c>1?Math.min(...l):0,h=100-Math.max(...l);return w.jsx(bE.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...r,ref:a,style:{...n.style,[s.startEdge]:u+"%",[s.endEdge]:h+"%"}})});$Z.displayName=Ax;var Ox="SliderThumb",BZ=_.forwardRef((n,e)=>{const t=u8e(n.__scopeSlider),[r,i]=_.useState(null),s=rn(e,a=>i(a)),o=_.useMemo(()=>r?t().findIndex(a=>a.ref.current===r):-1,[t,r]);return w.jsx(m8e,{...n,ref:s,index:o})}),m8e=_.forwardRef((n,e)=>{const{__scopeSlider:t,index:r,name:i,...s}=n,o=SE(Ox,t),a=DZ(Ox,t),[c,l]=_.useState(null),u=rn(e,R=>l(R)),h=c?o.form||!!c.closest("form"):!0,p=rK(c),m=o.values[r],v=m===void 0?0:HZ(m,o.min,o.max),g=y8e(r,o.values.length),S=p==null?void 0:p[a.size],b=S?b8e(S,v,a.direction):0;return _.useEffect(()=>{if(c)return o.thumbs.add(c),()=>{o.thumbs.delete(c)}},[c,o.thumbs]),w.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${v}% + ${b}px)`},children:[w.jsx(Lx.ItemSlot,{scope:n.__scopeSlider,children:w.jsx(bE.span,{role:"slider","aria-label":n["aria-label"]||g,"aria-valuemin":o.min,"aria-valuenow":m,"aria-valuemax":o.max,"aria-orientation":o.orientation,"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,tabIndex:o.disabled?void 0:0,...s,ref:u,style:m===void 0?{display:"none"}:n.style,onFocus:Ze(n.onFocus,()=>{o.valueIndexToChangeRef.current=r})})}),h&&w.jsx(g8e,{name:i??(o.name?o.name+(o.values.length>1?"[]":""):void 0),form:o.form,value:m},r)]})});BZ.displayName=Ox;var g8e=n=>{const{value:e,...t}=n,r=_.useRef(null),i=r8e(e);return _.useEffect(()=>{const s=r.current,o=window.HTMLInputElement.prototype,c=Object.getOwnPropertyDescriptor(o,"value").set;if(i!==e&&c){const l=new Event("input",{bubbles:!0});c.call(s,e),s.dispatchEvent(l)}},[i,e]),w.jsx("input",{style:{display:"none"},...t,ref:r,defaultValue:e})};function v8e(n=[],e,t){const r=[...n];return r[t]=e,r.sort((i,s)=>i-s)}function HZ(n,e,t){const s=100/(t-e)*(n-e);return xZ(s,[0,100])}function y8e(n,e){return e>2?`Value ${n+1} of ${e}`:e===2?["Minimum","Maximum"][n]:void 0}function _8e(n,e){if(n.length===1)return 0;const t=n.map(i=>Math.abs(i-e)),r=Math.min(...t);return t.indexOf(r)}function b8e(n,e,t){const r=n/2,s=u4([0,50],[0,r]);return(r-s(e)*t)*t}function S8e(n){return n.slice(0,-1).map((e,t)=>n[t+1]-e)}function w8e(n,e){if(e>0){const t=S8e(n);return Math.min(...t)>=e}return!0}function u4(n,e){return t=>{if(n[0]===n[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(n[1]-n[0]);return e[0]+r*(t-n[0])}}function E8e(n){return(String(n).split(".")[1]||"").length}function C8e(n,e){const t=Math.pow(10,e);return Math.round(n*t)/t}var T8e=MZ,I8e=jZ,R8e=$Z,k8e=BZ;const x8e="_slider_15go1_8",P8e="_track_15go1_14",L8e="_highlight_15go1_31",A8e="_handle_15go1_43",Z1={slider:x8e,track:P8e,highlight:L8e,handle:A8e},VZ=({className:n,label:e,value:t,onValueChange:r,onValueCommit:i,min:s,max:o,step:a,disabled:c})=>{const l=_.useCallback(([h])=>r(h),[r]),u=_.useCallback(([h])=>i==null?void 0:i(h),[i]);return w.jsxs(T8e,{className:De(n,Z1.slider),value:[t],onValueChange:l,onValueCommit:u,min:s,max:o,step:a,disabled:c,children:[w.jsx(I8e,{className:Z1.track,children:w.jsx(R8e,{className:Z1.highlight})}),w.jsx(ui,{placement:"top",label:Math.round(t*100).toString()+"%",children:w.jsx(k8e,{className:Z1.handle,"aria-label":e})})]})},O8e="_selection_1akwb_1",M8e="_title_1akwb_5",N8e="_separator_1akwb_10",D8e="_options_1akwb_14",F8e="_secondary_1akwb_20",rg={selection:O8e,title:M8e,separator:N8e,options:D8e,secondary:F8e},H2=({devices:n,title:e,numberedLabel:t})=>{const{t:r}=Qe(),i=_.useId(),s=_.useCallback(o=>{n.select(o.target.value)},[n]);return n.available.size==0?null:w.jsxs("div",{className:rg.selection,children:[w.jsx(Su,{type:"body",weight:"semibold",size:"sm",as:"h4",className:rg.title,children:e}),w.jsx(Yz,{className:rg.separator}),w.jsx("div",{className:rg.options,children:[...n.available].map(([o,a])=>{let c;switch(a.type){case"name":c=a.name;break;case"number":c=t(a.number);break;case"default":c=a.name===null?r("settings.devices.default"):w.jsxs(Ci,{i18nKey:"settings.devices.default_named",name:a.name,children:["Default"," ",w.jsxs("span",{className:rg.secondary,children:["(",{name:a.name},")"]})]});break}return w.jsx(KCe,{name:i,control:w.jsx(iTe,{checked:o===n.selectedId,onChange:s,value:o}),children:w.jsx(DCe,{children:c})},o)})})]})},U8e={},j8e=({client:n,livekitRoom:e})=>{var v;const{t}=Qe(),[r,i]=Ar(cZ),[s,o]=Ar(e4),[a,c]=Ar(lZ),[l,u]=Ar(Gv),[h,p]=Ar(fZ),m=_.useMemo(()=>{var g;if((g=e==null?void 0:e.engine.client.ws)!=null&&g.url){const S=new URL(e.engine.client.ws.url);return S.search="",S}return null},[e]);return w.jsxs(w.Fragment,{children:[w.jsx("p",{children:t("developer_mode.hostname",{hostname:window.location.hostname||"unknown"})}),w.jsx("p",{children:t("version",{productName:"Element Call",version:"embedded-v0.9.0-release-test.9"})}),w.jsx("p",{children:t("developer_mode.crypto_version",{version:((v=n.getCrypto())==null?void 0:v.getVersion())||"unknown"})}),w.jsx("p",{children:t("developer_mode.matrix_id",{id:n.getUserId()||"unknown"})}),w.jsx("p",{children:t("developer_mode.device_id",{id:n.getDeviceId()||"unknown"})}),w.jsx(yt,{children:w.jsx(vn,{id:"duplicateTiles",type:"number",label:t("developer_mode.duplicate_tiles_label"),value:r.toString(),min:0,onChange:_.useCallback(g=>{const S=g.target.valueAsNumber;S<0||i(Number.isNaN(S)?0:S)},[i])})}),w.jsx(yt,{children:w.jsx(vn,{id:"debugTileLayout",type:"checkbox",checked:s,label:t("developer_mode.debug_tile_layout_label"),onChange:g=>o(g.target.checked)})}),w.jsx(yt,{children:w.jsx(vn,{id:"showNonMemberTiles",type:"checkbox",label:t("developer_mode.show_non_member_tiles"),checked:!!a,onChange:_.useCallback(g=>{c(g.target.checked)},[c])})}),w.jsx(yt,{children:w.jsx(vn,{id:"showConnectionStats",type:"checkbox",label:t("developer_mode.show_connection_stats"),checked:!!l,onChange:_.useCallback(g=>{u(g.target.checked)},[u])})}),w.jsx(yt,{children:w.jsx(vn,{id:"useNewMembershipManager",type:"checkbox",label:t("developer_mode.use_new_membership_manager"),checked:!!h,onChange:_.useCallback(g=>{p(g.target.checked)},[p])})}),e?w.jsxs(w.Fragment,{children:[w.jsx("p",{children:t("developer_mode.livekit_sfu",{url:(m==null?void 0:m.href)||"unknown"})}),w.jsx("p",{children:t("developer_mode.livekit_server_info")}),w.jsxs("pre",{className:U8e.pre,children:[e.serverInfo?JSON.stringify(e.serverInfo,null,2):"undefined",e.metadata]})]}):null]})},d4="audio",h4=({open:n,onDismiss:e,tab:t,onTabChange:r,client:i,roomId:s,livekitRoom:o})=>{const{t:a}=Qe(),c=rh();t8e(c,n);const[l,u]=Ar(hZ),[h,p]=_.useState(l),[m]=Ar(aZ),v={key:"audio",name:a("common.audio"),content:w.jsx(w.Fragment,{children:w.jsxs(e7,{children:[w.jsx(H2,{devices:c.audioInput,title:a("settings.devices.microphone"),numberedLabel:T=>a("settings.devices.microphone_numbered",{n:T})}),w.jsx(H2,{devices:c.audioOutput,title:a("settings.devices.speaker"),numberedLabel:T=>a("settings.devices.speaker_numbered",{n:T})}),w.jsxs("div",{className:eF.volumeSlider,children:[w.jsx("label",{children:a("settings.audio_tab.effect_volume_label")}),w.jsx("p",{children:a("settings.audio_tab.effect_volume_description")}),w.jsx(VZ,{label:a("video_tile.volume"),value:h,onValueChange:p,onValueCommit:u,min:0,max:1,step:.01})]})]})})},g={key:"video",name:a("common.video"),content:w.jsx(e7,{children:w.jsx(H2,{devices:c.videoInput,title:a("settings.devices.camera"),numberedLabel:T=>a("settings.devices.camera_numbered",{n:T})})})},S={key:"preferences",name:a("common.preferences"),content:w.jsx(n8e,{})},b={key:"profile",name:a("common.profile"),content:w.jsx(FNe,{client:i})},R={key:"feedback",name:a("settings.feedback_tab_title"),content:w.jsx(jNe,{roomId:s})},k={key:"developer",name:a("settings.developer_tab_title"),content:w.jsx(j8e,{client:i,livekitRoom:o})},I=[v,g];return Je===null&&I.push(b),I.push(S,R),m&&I.push(k),w.jsx(th,{title:a("common.settings"),className:eF.settingsModal,open:n,onDismiss:e,tabbed:!0,children:w.jsx(mNe,{label:a("common.settings"),tab:t,onTabChange:r,tabs:I})})},$8e=(n,e)=>_.createElement("svg",{width:22,height:22,viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("mask",{id:"path-1-inside-1_898_2641",fill:"white"},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z"})),_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M17.1502 20.1214C15.3946 21.3074 13.2782 22 11 22C8.52367 22 6.23845 21.1817 4.4 19.8008C1.72821 17.794 0 14.5988 0 11C0 4.92487 4.92487 0 11 0C17.0751 0 22 4.92487 22 11C22 14.797 20.0762 18.1446 17.1502 20.1214ZM11 11.55C12.8225 11.55 14.3 9.94942 14.3 7.975C14.3 6.00058 12.8225 4.4 11 4.4C9.17746 4.4 7.7 6.00058 7.7 7.975C7.7 9.94942 9.17746 11.55 11 11.55ZM11 19.8C13.3782 19.8 15.536 18.8566 17.1197 17.3237C16.1403 14.9056 13.7693 13.2 11 13.2C8.23066 13.2 5.85969 14.9056 4.88028 17.3237C6.46399 18.8566 8.62183 19.8 11 19.8Z",fill:"white"}),_.createElement("path",{d:"M17.1502 20.1214L17.9339 21.2814L17.1502 20.1214ZM4.4 19.8008L3.55919 20.9202H3.55919L4.4 19.8008ZM17.1197 17.3237L18.0934 18.3296L18.7717 17.6731L18.4173 16.7981L17.1197 17.3237ZM4.88028 17.3237L3.58268 16.7981L3.22829 17.6731L3.90659 18.3296L4.88028 17.3237ZM11 23.4C13.5662 23.4 15.9541 22.619 17.9339 21.2814L16.3665 18.9613C14.835 19.9959 12.9902 20.6 11 20.6V23.4ZM3.55919 20.9202C5.63176 22.477 8.21011 23.4 11 23.4V20.6C8.83723 20.6 6.84514 19.8865 5.24081 18.6814L3.55919 20.9202ZM-1.4 11C-1.4 15.0577 0.55052 18.6603 3.55919 20.9202L5.24081 18.6814C2.90591 16.9276 1.4 14.1399 1.4 11H-1.4ZM11 -1.4C4.15167 -1.4 -1.4 4.15167 -1.4 11H1.4C1.4 5.69807 5.69807 1.4 11 1.4V-1.4ZM23.4 11C23.4 4.15167 17.8483 -1.4 11 -1.4V1.4C16.3019 1.4 20.6 5.69807 20.6 11H23.4ZM17.9339 21.2814C21.2288 19.0554 23.4 15.2815 23.4 11H20.6C20.6 14.3124 18.9236 17.2337 16.3665 18.9613L17.9339 21.2814ZM12.9 7.975C12.9 9.28384 11.9459 10.15 11 10.15V12.95C13.6991 12.95 15.7 10.615 15.7 7.975H12.9ZM11 5.8C11.9459 5.8 12.9 6.66616 12.9 7.975H15.7C15.7 5.335 13.6991 3 11 3V5.8ZM9.1 7.975C9.1 6.66616 10.0541 5.8 11 5.8V3C8.30086 3 6.3 5.335 6.3 7.975H9.1ZM11 10.15C10.0541 10.15 9.1 9.28384 9.1 7.975H6.3C6.3 10.615 8.30086 12.95 11 12.95V10.15ZM16.146 16.3178C14.8129 17.6081 13.0004 18.4 11 18.4V21.2C13.756 21.2 16.2591 20.1051 18.0934 18.3296L16.146 16.3178ZM11 14.6C13.1797 14.6 15.0494 15.9415 15.8221 17.8493L18.4173 16.7981C17.2312 13.8697 14.359 11.8 11 11.8V14.6ZM6.17788 17.8493C6.95058 15.9415 8.8203 14.6 11 14.6V11.8C7.64102 11.8 4.7688 13.8697 3.58268 16.7981L6.17788 17.8493ZM11 18.4C8.99963 18.4 7.18709 17.6081 5.85397 16.3178L3.90659 18.3296C5.74088 20.1051 8.24402 21.2 11 21.2V18.4Z",fill:"white",mask:"url(#path-1-inside-1_898_2641)"})),sF=_.forwardRef($8e),B8e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M20.0988 9.01625C20.3188 9.59375 20.8825 9.97875 21.5013 9.97875C22.3263 9.97875 23 10.6525 23 11.4775V12.5225C23 13.3475 22.3263 14.0213 21.5013 14.0213C20.8825 14.0213 20.3188 14.4062 20.0988 14.9838C20.0806 15.0292 20.0624 15.0753 20.0441 15.1218C19.9792 15.2863 19.9125 15.4555 19.8375 15.6163C19.5763 16.18 19.7 16.84 20.14 17.28C20.7313 17.8575 20.7313 18.8062 20.14 19.3975L19.3975 20.14C18.82 20.7313 17.8713 20.7313 17.28 20.14C16.8538 19.7 16.18 19.5763 15.6163 19.8375C15.41 19.9338 15.2037 20.0163 14.9838 20.0988C14.4062 20.3188 14.0213 20.8825 14.0213 21.5013C14.0213 22.3263 13.3475 23 12.5225 23H11.4775C10.6525 23 9.97875 22.3263 9.97875 21.5013C9.97875 20.8825 9.59375 20.3188 9.01625 20.0988C8.97079 20.0806 8.92466 20.0624 8.87815 20.044C8.71368 19.9792 8.54454 19.9125 8.38375 19.8375C7.82 19.5763 7.16 19.7 6.72 20.14C6.1425 20.7313 5.19375 20.7313 4.6025 20.14L3.86 19.3975C3.26875 18.82 3.26875 17.8713 3.86 17.28C4.3 16.8538 4.42375 16.18 4.1625 15.6163C4.06625 15.41 3.98375 15.2037 3.90125 14.9838C3.68125 14.4062 3.1175 14.0213 2.49875 14.0213C1.67375 14.0213 1 13.3475 1 12.5225V11.4775C1 10.6525 1.67375 9.97875 2.49875 9.97875C3.1175 9.97875 3.68125 9.59375 3.90125 9.01625C3.94464 8.87742 3.99897 8.74406 4.0539 8.60926C4.086 8.53046 4.11831 8.45117 4.14875 8.37C4.41 7.80625 4.28625 7.14625 3.84625 6.70625C3.255 6.12875 3.255 5.18 3.84625 4.58875L4.6025 3.86C5.18 3.26875 6.12875 3.26875 6.72 3.86C7.14625 4.3 7.82 4.42375 8.38375 4.1625C8.59 4.06625 8.79625 3.97 9.01625 3.90125C9.59375 3.68125 9.97875 3.1175 9.97875 2.49875C9.97875 1.67375 10.6525 1 11.4775 1H12.5225C13.3475 1 14.0213 1.67375 14.0213 2.49875C14.0213 3.13125 14.4062 3.68125 14.9838 3.90125C15.0292 3.91943 15.0753 3.93762 15.1218 3.95595C15.2863 4.02079 15.4555 4.08746 15.6163 4.1625C16.18 4.42375 16.84 4.3 17.28 3.86C17.8575 3.26875 18.8062 3.26875 19.3975 3.86L20.14 4.6025C20.7313 5.18 20.7313 6.12875 20.14 6.72C19.7 7.14625 19.5763 7.82 19.8375 8.38375C19.9338 8.59 20.0163 8.79625 20.0988 9.01625ZM12 17.5C8.96125 17.5 6.5 15.0387 6.5 12C6.5 8.96125 8.96125 6.5 12 6.5C15.0387 6.5 17.5 8.96125 17.5 12C17.5 15.0387 15.0387 17.5 12 17.5Z",fill:"#ffffff"})),H8e=_.forwardRef(B8e),V8e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.49966 2.38889C7.49966 1.89797 7.89763 1.5 8.38855 1.5H20.1108C20.6017 1.5 20.9997 1.89797 20.9997 2.38889V21.6111C20.9997 22.102 20.6017 22.5 20.1108 22.5H8.38855C7.89763 22.5 7.49966 22.102 7.49966 21.6111V12.6667H7.49089H7.4821H7.47331H7.46452H7.45573H7.44694H7.43815H7.42936H7.42057H7.41178H7.403H7.39421H7.38542H7.37663H7.36784H7.35905H7.35026H7.34147H7.33268H7.32389H7.3151H7.30632H7.29753H7.28874H7.27995H7.27116H7.26237H7.25358H7.24479H7.236H7.22721H7.21842H7.20964H7.20085H7.19206H7.18327H7.17448H7.16569H7.1569H7.14811H7.13932H7.13053H7.12175H7.11296H7.10417H7.09538H7.08659H7.0778H7.06901H7.06022H7.05143H7.04264H7.03385H7.02507H7.01628H7.00749H6.9987H6.98991H6.98112H6.97233H6.96354H6.95475H6.94596H6.93717H6.92839H6.9196H6.91081H6.90202H6.89323H6.88444H6.87565H6.86686H6.85807H6.84928H6.8405H6.83171H6.82292H6.81413H6.80534H6.79655H6.78776H6.77897H6.77018H6.76139H6.7526H6.74382H6.73503H6.72624H6.71745H6.70866H6.69987H6.69108H6.68229H6.6735H6.66471H6.65592H6.64714H6.63835H6.62956H6.62077H6.61198H6.60319H6.5944H6.58561H6.57682H6.56803H6.55925H6.55046H6.54167H6.53288H6.52409H6.5153H6.50651H6.49772H6.48893H6.48014H6.47135H6.46257H6.45378H6.44499H6.4362H6.42741H6.41862H6.40983H6.40104H6.39225H6.38346H6.37467H6.36589H6.3571H6.34831H6.33952H6.33073H6.32194H6.31315H6.30436H6.29557H6.28678H6.27799H6.26921H6.26042H6.25163H6.24284H6.23405H6.22526H6.21647H6.20768H6.19889H6.1901H6.18132H6.17253H6.16374H6.15495H6.14616H6.13737H6.12858H6.11979H6.111H6.10221H6.09342H6.08464H6.07585H6.06706H6.05827H6.04948H6.04069H6.0319H6.02311H6.01432H6.00553H5.99674H5.98796H5.97917H5.97038H5.96159H5.9528H5.94401H5.93522H5.92643H5.91764H5.90885H5.90007H5.89128H5.88249H5.8737H5.86491H5.85612H5.84733H5.83854H5.82975H5.82096H5.81217H5.80339H5.7946H5.78581H5.77702H5.76823H5.75944H5.75065H5.74186H5.73307H5.72428H5.71549H5.70671H5.69792H5.68913H5.68034H5.67155H5.66276H5.65397H5.64518H5.63639H5.6276H5.61882H5.61003H5.60124H5.59245H5.58366H5.57487H5.56608H5.55729H5.5485H5.53971H5.53092H5.52214H5.51335H5.50456H5.49577H5.48698H5.47819H5.4694H5.46061H5.45182H5.44303H5.43424H5.42546H5.41667H5.40788H5.39909H5.3903H5.38151H5.37272H5.36393H5.35514H5.34635H5.33757H5.32878H5.31999H5.3112H5.30241H5.29362H5.28483H5.27604H5.26725H5.25846H5.24967H5.24089H5.2321H5.22331H5.21452H5.20573H5.19694H5.18815H5.17936H5.17057H5.16178H5.15299H5.14421H5.13542H5.12663H5.11784H5.10905H5.10026H5.09147H5.08268H5.07389H5.0651H5.05632H5.04753H5.03874H5.02995H5.02116H5.01237H5.00358H4.99479H4.986H4.97721H4.96842H4.95964H4.95085H4.94206H4.93327H4.92448H4.91569H4.9069H4.89811H4.88932H4.88053H4.87174H4.86296H4.85417H4.84538H4.83659H4.8278H4.81901H4.81022H4.80143H4.79264H4.78385H4.77507H4.76628H4.75749H4.7487H4.73991H4.73112H4.72233H4.71354H4.70475H4.69596H4.68717H4.67839H4.6696H4.66081H4.65202H4.64323H4.63444H4.62565H4.61686H4.60807H4.59928H4.59049H4.58171H4.57292H4.56413H4.55534H4.54655H4.53776H4.52897H4.52018H4.51139H4.5026H4.49382H4.48503H4.47624H4.46745H4.45866H4.44987H4.44108H4.43229H4.4235H4.41471H4.40592H4.39714H4.38835H4.37956H4.37077H4.36198H4.35319H4.3444H4.33561H4.32682H4.31803H4.30924H4.30046H4.29167H4.28288H4.27409H4.2653H4.25651H4.24772H4.23893H4.23014H4.22135H4.21257H4.20378H4.19499H4.1862H4.17741H4.16862H4.15983H4.15104H4.14225H4.13346H4.12467H4.11589H4.1071H4.09831H4.08952H4.08073H4.07194H4.06315H4.05436H4.04557H4.03678H4.02799H4.01921H4.01042H4.00163H3.99284H3.98405H3.97526H3.96647H3.95768H3.94889H3.9401H3.93132H3.92253H3.91374H3.90495H3.89616H3.88737H3.87858H3.86979H3.861H3.85221H3.84342H3.83464H3.82585H3.81706H3.80827H3.79948H3.79069H3.7819H3.77311H3.76432H3.75553H3.74674H3.73796H3.72917H3.72038H3.71159H3.7028H3.69401H3.68522H3.67643H3.66764H3.65885H3.65007H3.64128H3.63249H3.6237H3.61491H3.60612H3.59733H3.58854H3.57975H3.57096H3.56217H3.55339H3.5446H3.53581H3.52702H3.51823H3.50944H3.50065H3.49186H3.48307H3.47428H3.46549H3.45671H3.44792H3.43913H3.43034H3.42155H3.41276H3.40397H3.39518H3.38639H3.3776H3.36882H3.36003H3.35124H3.34245H3.33366H3.32487H3.31608H3.30729H3.2985H3.28971H3.28092H3.27214H3.26335H3.25456H3.24577H3.23698H3.22819H3.2194H3.21061H3.20182H3.19303H3.18424H3.17546H3.16667H3.15788H3.14909H3.1403H3.13151H3.12272H3.11393H3.10514H3.09635H3.08757H3.07878H3.06999H3.0612H3.05241H3.04362H3.03483H3.02604H3.01725H3.00846H2.99967C2.63148 12.6667 2.33301 12.3682 2.33301 12C2.33301 11.6318 2.63148 11.3333 2.99967 11.3333H3.00846H3.01725H3.02604H3.03483H3.04362H3.05241H3.0612H3.06999H3.07878H3.08757H3.09635H3.10514H3.11393H3.12272H3.13151H3.1403H3.14909H3.15788H3.16667H3.17546H3.18424H3.19303H3.20182H3.21061H3.2194H3.22819H3.23698H3.24577H3.25456H3.26335H3.27214H3.28092H3.28971H3.2985H3.30729H3.31608H3.32487H3.33366H3.34245H3.35124H3.36003H3.36882H3.3776H3.38639H3.39518H3.40397H3.41276H3.42155H3.43034H3.43913H3.44792H3.45671H3.46549H3.47428H3.48307H3.49186H3.50065H3.50944H3.51823H3.52702H3.53581H3.5446H3.55339H3.56217H3.57096H3.57975H3.58854H3.59733H3.60612H3.61491H3.6237H3.63249H3.64128H3.65007H3.65885H3.66764H3.67643H3.68522H3.69401H3.7028H3.71159H3.72038H3.72917H3.73796H3.74674H3.75553H3.76432H3.77311H3.7819H3.79069H3.79948H3.80827H3.81706H3.82585H3.83464H3.84342H3.85221H3.861H3.86979H3.87858H3.88737H3.89616H3.90495H3.91374H3.92253H3.93132H3.9401H3.94889H3.95768H3.96647H3.97526H3.98405H3.99284H4.00163H4.01042H4.01921H4.02799H4.03678H4.04557H4.05436H4.06315H4.07194H4.08073H4.08952H4.09831H4.1071H4.11589H4.12467H4.13346H4.14225H4.15104H4.15983H4.16862H4.17741H4.1862H4.19499H4.20378H4.21257H4.22135H4.23014H4.23893H4.24772H4.25651H4.2653H4.27409H4.28288H4.29167H4.30046H4.30924H4.31803H4.32682H4.33561H4.3444H4.35319H4.36198H4.37077H4.37956H4.38835H4.39714H4.40592H4.41471H4.4235H4.43229H4.44108H4.44987H4.45866H4.46745H4.47624H4.48503H4.49382H4.5026H4.51139H4.52018H4.52897H4.53776H4.54655H4.55534H4.56413H4.57292H4.58171H4.59049H4.59928H4.60807H4.61686H4.62565H4.63444H4.64323H4.65202H4.66081H4.6696H4.67839H4.68717H4.69596H4.70475H4.71354H4.72233H4.73112H4.73991H4.7487H4.75749H4.76628H4.77507H4.78385H4.79264H4.80143H4.81022H4.81901H4.8278H4.83659H4.84538H4.85417H4.86296H4.87174H4.88053H4.88932H4.89811H4.9069H4.91569H4.92448H4.93327H4.94206H4.95085H4.95964H4.96842H4.97721H4.986H4.99479H5.00358H5.01237H5.02116H5.02995H5.03874H5.04753H5.05631H5.0651H5.07389H5.08268H5.09147H5.10026H5.10905H5.11784H5.12663H5.13542H5.14421H5.15299H5.16178H5.17057H5.17936H5.18815H5.19694H5.20573H5.21452H5.22331H5.2321H5.24089H5.24967H5.25846H5.26725H5.27604H5.28483H5.29362H5.30241H5.3112H5.31999H5.32878H5.33757H5.34635H5.35514H5.36393H5.37272H5.38151H5.3903H5.39909H5.40788H5.41667H5.42546H5.43424H5.44303H5.45182H5.46061H5.4694H5.47819H5.48698H5.49577H5.50456H5.51335H5.52214H5.53092H5.53971H5.5485H5.55729H5.56608H5.57487H5.58366H5.59245H5.60124H5.61003H5.61882H5.6276H5.63639H5.64518H5.65397H5.66276H5.67155H5.68034H5.68913H5.69792H5.70671H5.71549H5.72428H5.73307H5.74186H5.75065H5.75944H5.76823H5.77702H5.78581H5.7946H5.80339H5.81217H5.82096H5.82975H5.83854H5.84733H5.85612H5.86491H5.8737H5.88249H5.89128H5.90007H5.90885H5.91764H5.92643H5.93522H5.94401H5.9528H5.96159H5.97038H5.97917H5.98796H5.99674H6.00553H6.01432H6.02311H6.0319H6.04069H6.04948H6.05827H6.06706H6.07585H6.08464H6.09342H6.10221H6.111H6.11979H6.12858H6.13737H6.14616H6.15495H6.16374H6.17253H6.18132H6.1901H6.19889H6.20768H6.21647H6.22526H6.23405H6.24284H6.25163H6.26042H6.26921H6.27799H6.28678H6.29557H6.30436H6.31315H6.32194H6.33073H6.33952H6.34831H6.3571H6.36589H6.37467H6.38346H6.39225H6.40104H6.40983H6.41862H6.42741H6.4362H6.44499H6.45378H6.46257H6.47135H6.48014H6.48893H6.49772H6.50651H6.5153H6.52409H6.53288H6.54167H6.55046H6.55925H6.56803H6.57682H6.58561H6.5944H6.60319H6.61198H6.62077H6.62956H6.63835H6.64714H6.65592H6.66471H6.6735H6.68229H6.69108H6.69987H6.70866H6.71745H6.72624H6.73503H6.74382H6.7526H6.76139H6.77018H6.77897H6.78776H6.79655H6.80534H6.81413H6.82292H6.83171H6.8405H6.84928H6.85807H6.86686H6.87565H6.88444H6.89323H6.90202H6.91081H6.9196H6.92839H6.93717H6.94596H6.95475H6.96354H6.97233H6.98112H6.98991H6.9987H7.00749H7.01628H7.02507H7.03385H7.04264H7.05143H7.06022H7.06901H7.0778H7.08659H7.09538H7.10417H7.11296H7.12175H7.13053H7.13932H7.14811H7.1569H7.16569H7.17448H7.18327H7.19206H7.20085H7.20964H7.21842H7.22721H7.236H7.24479H7.25358H7.26237H7.27116H7.27995H7.28874H7.29753H7.30632H7.3151H7.32389H7.33268H7.34147H7.35026H7.35905H7.36784H7.37663H7.38542H7.39421H7.403H7.41178H7.42057H7.42936H7.43815H7.44694H7.45573H7.46452H7.47331H7.4821H7.49089H7.49966V2.38889ZM13.3687 6.24853C13.1172 5.9796 12.7095 5.9796 12.458 6.24853C12.2065 6.51747 12.2065 6.9535 12.458 7.22243L16.3022 11.3336L16.2894 11.3336L16.2726 11.3336L16.2558 11.3336L16.239 11.3335L16.2223 11.3335L16.2055 11.3335L16.1887 11.3335L16.1719 11.3335L16.1552 11.3334L16.1384 11.3334L16.1216 11.3334L16.1048 11.3334L16.088 11.3334L16.0713 11.3333L16.0545 11.3333L16.0377 11.3333L16.0209 11.3333L16.0041 11.3333L15.9874 11.3332L15.9706 11.3332L15.9538 11.3332L15.937 11.3332L15.9202 11.3332L15.9035 11.3331L15.8867 11.3331L15.8699 11.3331L15.8531 11.3331L15.8364 11.3331L15.8196 11.333L15.8028 11.333L15.786 11.333L15.7692 11.333L15.7525 11.333L15.7357 11.3329L15.7189 11.3329L15.7021 11.3329L15.6853 11.3329L15.6686 11.3329L15.6518 11.3328L15.635 11.3328L15.6182 11.3328L15.6014 11.3328L15.5847 11.3328L15.5679 11.3327L15.5511 11.3327L15.5343 11.3327L15.5175 11.3327L15.5008 11.3327L15.484 11.3326L15.4672 11.3326L15.4504 11.3326L15.4337 11.3326L15.4169 11.3326L15.4001 11.3325L15.3833 11.3325L15.3665 11.3325L15.3498 11.3325L15.333 11.3324L15.3162 11.3324L15.2994 11.3324L15.2826 11.3324L15.2659 11.3324L15.2491 11.3323L15.2323 11.3323L15.2155 11.3323L15.1987 11.3323L15.182 11.3323L15.1652 11.3322L15.1484 11.3322L15.1316 11.3322L15.1148 11.3322L15.0981 11.3322L15.0813 11.3321L15.0645 11.3321L15.0477 11.3321L15.031 11.3321L15.0142 11.3321L14.9974 11.332L14.9806 11.332L14.9638 11.332L14.9471 11.332L14.9303 11.332L14.9135 11.3319L14.8967 11.3319L14.8799 11.3319L14.8632 11.3319L14.8464 11.3319L14.8296 11.3318L14.8128 11.3318L14.796 11.3318L14.7793 11.3318L14.7625 11.3318L14.7457 11.3317L14.7289 11.3317L14.7122 11.3317L14.6954 11.3317L14.6786 11.3317L14.6618 11.3316L14.645 11.3316L14.6283 11.3316L14.6115 11.3316L14.5947 11.3316L14.5779 11.3315L14.5611 11.3315L14.5444 11.3315L14.5276 11.3315L14.5108 11.3315L14.494 11.3314L14.4772 11.3314L14.4605 11.3314L14.4437 11.3314L14.4269 11.3314L14.4101 11.3313L14.3933 11.3313L14.3766 11.3313L14.3598 11.3313L14.343 11.3313L14.3262 11.3312L14.3095 11.3312L14.2927 11.3312L14.2759 11.3312L14.2591 11.3312L14.2423 11.3311L14.2256 11.3311L14.2088 11.3311L14.192 11.3311L14.1752 11.3311L14.1584 11.331L14.1417 11.331L14.1249 11.331L14.1081 11.331L14.0913 11.331L14.0745 11.3309L14.0578 11.3309L14.041 11.3309L14.0242 11.3309L14.0074 11.3309L13.9906 11.3308L13.9739 11.3308L13.9571 11.3308L13.9403 11.3308L13.9235 11.3308L13.9068 11.3307L13.89 11.3307L13.8732 11.3307L13.8564 11.3307L13.8396 11.3307L13.8229 11.3306L13.8061 11.3306L13.7893 11.3306L13.7725 11.3306L13.7557 11.3306L13.739 11.3305L13.7222 11.3305L13.7054 11.3305L13.6886 11.3305L13.6718 11.3305L13.6551 11.3304L13.6383 11.3304L13.6215 11.3304L13.6047 11.3304L13.5879 11.3304L13.5712 11.3303L13.5544 11.3303L13.5376 11.3303L13.5208 11.3303L13.5041 11.3303L13.4873 11.3302L13.4705 11.3302L13.4537 11.3302L13.4369 11.3302L13.4202 11.3302L13.4034 11.3301L13.3866 11.3301L13.3698 11.3301L13.353 11.3301L13.3363 11.33L13.3195 11.33L13.3027 11.33L13.2859 11.33L13.2691 11.33L13.2524 11.3299L13.2356 11.3299L13.2188 11.3299L13.202 11.3299L13.1853 11.3299L13.1685 11.3298L13.1517 11.3298L13.1349 11.3298L13.1181 11.3298L13.1014 11.3298L13.0846 11.3297L13.0678 11.3297L13.051 11.3297L13.0342 11.3297L13.0175 11.3297L13.0007 11.3296L12.9839 11.3296L12.9671 11.3296L12.9503 11.3296L12.9336 11.3296L12.9168 11.3295L12.9 11.3295L12.8832 11.3295L12.8664 11.3295L12.8497 11.3295L12.8329 11.3294L12.8161 11.3294L12.7993 11.3294L12.7826 11.3294L12.7658 11.3294L12.749 11.3293L12.7322 11.3293L12.7154 11.3293L12.6987 11.3293L12.6819 11.3293L12.6651 11.3292L12.6483 11.3292L12.6315 11.3292L12.6148 11.3292L12.598 11.3292L12.5812 11.3291L12.5644 11.3291L12.5476 11.3291L12.5309 11.3291L12.5141 11.3291L12.4973 11.329L12.4805 11.329L12.4637 11.329L12.447 11.329L12.4302 11.329L12.4134 11.3289L12.3966 11.3289L12.3799 11.3289L12.3631 11.3289L12.3463 11.3289L12.3295 11.3288L12.3127 11.3288L12.296 11.3288L12.2792 11.3288L12.2624 11.3288L12.2456 11.3287L12.2288 11.3287L12.2121 11.3287L12.1953 11.3287L12.1785 11.3287L12.1617 11.3286L12.1449 11.3286L12.1282 11.3286L12.1114 11.3286L12.0946 11.3286L12.0778 11.3285L12.0611 11.3285L12.0443 11.3285L12.0275 11.3285L12.0107 11.3285L11.9939 11.3284L11.9772 11.3284L11.9604 11.3284L11.9436 11.3284L11.9268 11.3284L11.91 11.3283L11.8933 11.3283L11.8765 11.3283L11.8597 11.3283L11.8429 11.3283L11.8261 11.3282L11.8094 11.3282L11.7926 11.3282L11.7758 11.3282L11.759 11.3282L11.7422 11.3281L11.7255 11.3281L11.7087 11.3281L11.6919 11.3281L11.6751 11.3281L11.6583 11.328L11.6416 11.328L11.6248 11.328L11.608 11.328L11.5912 11.328L11.5745 11.3279L11.5577 11.3279L11.5409 11.3279L11.5241 11.3279L11.5073 11.3279L11.4906 11.3278L11.4738 11.3278L11.457 11.3278L11.4402 11.3278L11.4234 11.3278L11.4067 11.3277L11.3899 11.3277L11.3731 11.3277L11.3563 11.3277L11.3395 11.3277L11.3228 11.3276L11.306 11.3276L11.2892 11.3276L11.2724 11.3276L11.2557 11.3275L11.2389 11.3275L11.2221 11.3275L11.2053 11.3275L11.1885 11.3275L11.1718 11.3274L11.155 11.3274L11.1382 11.3274L11.1214 11.3274L11.1046 11.3274L11.0879 11.3273L11.0711 11.3273L11.0543 11.3273L11.0375 11.3273L11.0207 11.3273L11.004 11.3272L10.9872 11.3272L10.9704 11.3272L10.9536 11.3272L10.9368 11.3272L10.9201 11.3271L10.9033 11.3271L10.8865 11.3271L10.8697 11.3271L10.853 11.3271L10.8362 11.327L10.8194 11.327L10.8026 11.327L10.7858 11.327L10.7691 11.327L10.7523 11.3269L10.7355 11.3269L10.7187 11.3269L10.7019 11.3269L10.6852 11.3269L10.6684 11.3268L10.6516 11.3268L10.6348 11.3268L10.618 11.3268L10.6013 11.3268L10.5845 11.3267L10.5677 11.3267L10.5509 11.3267L10.5341 11.3267L10.5174 11.3267L10.5006 11.3266L10.4838 11.3266L10.467 11.3266L10.4503 11.3266L10.4335 11.3266L10.4167 11.3265L10.3999 11.3265L10.3831 11.3265L10.3664 11.3265L10.3496 11.3265L10.3328 11.3264L10.316 11.3264L10.2992 11.3264L10.2825 11.3264L10.2657 11.3264L10.2489 11.3263L10.2321 11.3263L10.2153 11.3263L10.1986 11.3263L10.1818 11.3263L10.165 11.3262L10.1482 11.3262L10.1315 11.3262L10.1147 11.3262L10.0979 11.3262L10.0811 11.3261L10.0643 11.3261L10.0476 11.3261L10.0308 11.3261L10.014 11.3261L9.99722 11.326L9.98044 11.326L9.96366 11.326L9.94688 11.326L9.9301 11.326L9.91332 11.3259L9.89654 11.3259L9.87977 11.3259L9.86299 11.3259L9.84621 11.3259L9.82943 11.3258L9.81265 11.3258L9.79587 11.3258L9.77909 11.3258L9.76231 11.3258L9.74553 11.3257L9.72875 11.3257L9.71197 11.3257L9.69519 11.3257L9.67841 11.3257L9.66163 11.3256L9.64486 11.3256L9.62808 11.3256L9.6113 11.3256L9.59452 11.3256L9.57774 11.3255L9.56096 11.3255L9.54418 11.3255L9.5274 11.3255L9.51062 11.3255L9.49384 11.3254L9.47706 11.3254L9.46029 11.3254L9.44351 11.3254L9.42673 11.3254L9.40995 11.3253L9.39317 11.3253L9.37639 11.3253L9.35961 11.3253L9.34283 11.3253L9.32605 11.3252L9.30927 11.3252L9.29249 11.3252L9.27572 11.3252L9.25894 11.3252L9.24216 11.3251L9.22538 11.3251L9.2086 11.3251L9.19182 11.3251L9.17504 11.325L9.15826 11.325L9.14148 11.325L9.1247 11.325L9.10792 11.325L9.09115 11.3249L9.07437 11.3249L9.05759 11.3249L9.04081 11.3249L9.02403 11.3249L9.00725 11.3248L8.99047 11.3248L8.97369 11.3248L8.95691 11.3248L8.94013 11.3248L8.92335 11.3247L8.90658 11.3247L8.8898 11.3247L8.87302 11.3247L8.85624 11.3247L8.83946 11.3246L8.82268 11.3246L8.8059 11.3246L8.78912 11.3246L8.77234 11.3246L8.75556 11.3245L8.73878 11.3245L8.722 11.3245L8.70523 11.3245L8.68845 11.3245L8.67167 11.3244L8.65489 11.3244L8.63811 11.3244L8.62133 11.3244L8.60455 11.3244L8.58777 11.3243L8.57099 11.3243L8.55421 11.3243L8.53743 11.3243L8.52066 11.3243L8.50388 11.3242L8.4871 11.3242L8.47032 11.3242L8.45354 11.3242L8.43676 11.3242L8.41998 11.3241L8.4032 11.3241L8.38642 11.3241L8.36964 11.3241L8.35286 11.3241L8.33608 11.324L8.31931 11.324L8.30253 11.324L8.28575 11.324L8.26897 11.324L8.25219 11.3239L8.23541 11.3239L8.21863 11.3239L8.20185 11.3239L8.18507 11.3239L8.16829 11.3238L8.15151 11.3238L8.13474 11.3238L8.11796 11.3238L8.10118 11.3238L8.0844 11.3237L8.06762 11.3237L8.05084 11.3237L8.03406 11.3237L8.01728 11.3237L8.0005 11.3236L7.99885 12.657L8.01563 12.657L8.03241 12.657L8.04919 12.657L8.06597 12.6571L8.08274 12.6571L8.09952 12.6571L8.1163 12.6571L8.13308 12.6571L8.14986 12.6572L8.16664 12.6572L8.18342 12.6572L8.2002 12.6572L8.21698 12.6572L8.23376 12.6573L8.25054 12.6573L8.26731 12.6573L8.28409 12.6573L8.30087 12.6573L8.31765 12.6574L8.33443 12.6574L8.35121 12.6574L8.36799 12.6574L8.38477 12.6574L8.40155 12.6575L8.41833 12.6575L8.43511 12.6575L8.45189 12.6575L8.46866 12.6575L8.48544 12.6576L8.50222 12.6576L8.519 12.6576L8.53578 12.6576L8.55256 12.6576L8.56934 12.6577L8.58612 12.6577L8.6029 12.6577L8.61968 12.6577L8.63646 12.6577L8.65323 12.6578L8.67001 12.6578L8.68679 12.6578L8.70357 12.6578L8.72035 12.6578L8.73713 12.6579L8.75391 12.6579L8.77069 12.6579L8.78747 12.6579L8.80425 12.6579L8.82103 12.658L8.83781 12.658L8.85458 12.658L8.87136 12.658L8.88814 12.658L8.90492 12.6581L8.9217 12.6581L8.93848 12.6581L8.95526 12.6581L8.97204 12.6581L8.98882 12.6582L9.0056 12.6582L9.02238 12.6582L9.03915 12.6582L9.05593 12.6582L9.07271 12.6583L9.08949 12.6583L9.10627 12.6583L9.12305 12.6583L9.13983 12.6583L9.15661 12.6584L9.17339 12.6584L9.19017 12.6584L9.20695 12.6584L9.22373 12.6584L9.2405 12.6585L9.25728 12.6585L9.27406 12.6585L9.29084 12.6585L9.30762 12.6585L9.3244 12.6586L9.34118 12.6586L9.35796 12.6586L9.37474 12.6586L9.39152 12.6586L9.4083 12.6587L9.42507 12.6587L9.44185 12.6587L9.45863 12.6587L9.47541 12.6587L9.49219 12.6588L9.50897 12.6588L9.52575 12.6588L9.54253 12.6588L9.55931 12.6588L9.57609 12.6589L9.59287 12.6589L9.60964 12.6589L9.62642 12.6589L9.6432 12.6589L9.65998 12.659L9.67676 12.659L9.69354 12.659L9.71032 12.659L9.7271 12.659L9.74388 12.6591L9.76066 12.6591L9.77744 12.6591L9.79421 12.6591L9.81099 12.6591L9.82777 12.6592L9.84455 12.6592L9.86133 12.6592L9.87811 12.6592L9.89489 12.6592L9.91167 12.6593L9.92845 12.6593L9.94523 12.6593L9.96201 12.6593L9.97879 12.6594L9.99556 12.6594L10.0123 12.6594L10.0291 12.6594L10.0459 12.6594L10.0627 12.6595L10.0795 12.6595L10.0962 12.6595L10.113 12.6595L10.1298 12.6595L10.1466 12.6596L10.1634 12.6596L10.1801 12.6596L10.1969 12.6596L10.2137 12.6596L10.2305 12.6597L10.2473 12.6597L10.264 12.6597L10.2808 12.6597L10.2976 12.6597L10.3144 12.6598L10.3311 12.6598L10.3479 12.6598L10.3647 12.6598L10.3815 12.6598L10.3983 12.6599L10.415 12.6599L10.4318 12.6599L10.4486 12.6599L10.4654 12.6599L10.4822 12.66L10.4989 12.66L10.5157 12.66L10.5325 12.66L10.5493 12.66L10.5661 12.6601L10.5828 12.6601L10.5996 12.6601L10.6164 12.6601L10.6332 12.6601L10.65 12.6602L10.6667 12.6602L10.6835 12.6602L10.7003 12.6602L10.7171 12.6602L10.7338 12.6603L10.7506 12.6603L10.7674 12.6603L10.7842 12.6603L10.801 12.6603L10.8177 12.6604L10.8345 12.6604L10.8513 12.6604L10.8681 12.6604L10.8849 12.6604L10.9016 12.6605L10.9184 12.6605L10.9352 12.6605L10.952 12.6605L10.9688 12.6605L10.9855 12.6606L11.0023 12.6606L11.0191 12.6606L11.0359 12.6606L11.0526 12.6606L11.0694 12.6607L11.0862 12.6607L11.103 12.6607L11.1198 12.6607L11.1365 12.6607L11.1533 12.6608L11.1701 12.6608L11.1869 12.6608L11.2037 12.6608L11.2204 12.6608L11.2372 12.6609L11.254 12.6609L11.2708 12.6609L11.2876 12.6609L11.3043 12.6609L11.3211 12.661L11.3379 12.661L11.3547 12.661L11.3715 12.661L11.3882 12.661L11.405 12.6611L11.4218 12.6611L11.4386 12.6611L11.4553 12.6611L11.4721 12.6611L11.4889 12.6612L11.5057 12.6612L11.5225 12.6612L11.5392 12.6612L11.556 12.6612L11.5728 12.6613L11.5896 12.6613L11.6064 12.6613L11.6231 12.6613L11.6399 12.6613L11.6567 12.6614L11.6735 12.6614L11.6903 12.6614L11.707 12.6614L11.7238 12.6614L11.7406 12.6615L11.7574 12.6615L11.7742 12.6615L11.7909 12.6615L11.8077 12.6615L11.8245 12.6616L11.8413 12.6616L11.858 12.6616L11.8748 12.6616L11.8916 12.6616L11.9084 12.6617L11.9252 12.6617L11.9419 12.6617L11.9587 12.6617L11.9755 12.6617L11.9923 12.6618L12.0091 12.6618L12.0258 12.6618L12.0426 12.6618L12.0594 12.6618L12.0762 12.6619L12.093 12.6619L12.1097 12.6619L12.1265 12.6619L12.1433 12.662L12.1601 12.662L12.1768 12.662L12.1936 12.662L12.2104 12.662L12.2272 12.6621L12.244 12.6621L12.2607 12.6621L12.2775 12.6621L12.2943 12.6621L12.3111 12.6622L12.3279 12.6622L12.3446 12.6622L12.3614 12.6622L12.3782 12.6622L12.395 12.6623L12.4118 12.6623L12.4285 12.6623L12.4453 12.6623L12.4621 12.6623L12.4789 12.6624L12.4957 12.6624L12.5124 12.6624L12.5292 12.6624L12.546 12.6624L12.5628 12.6625L12.5795 12.6625L12.5963 12.6625L12.6131 12.6625L12.6299 12.6625L12.6467 12.6626L12.6634 12.6626L12.6802 12.6626L12.697 12.6626L12.7138 12.6626L12.7306 12.6627L12.7473 12.6627L12.7641 12.6627L12.7809 12.6627L12.7977 12.6627L12.8145 12.6628L12.8312 12.6628L12.848 12.6628L12.8648 12.6628L12.8816 12.6628L12.8984 12.6629L12.9151 12.6629L12.9319 12.6629L12.9487 12.6629L12.9655 12.6629L12.9822 12.663L12.999 12.663L13.0158 12.663L13.0326 12.663L13.0494 12.663L13.0661 12.6631L13.0829 12.6631L13.0997 12.6631L13.1165 12.6631L13.1333 12.6631L13.15 12.6632L13.1668 12.6632L13.1836 12.6632L13.2004 12.6632L13.2172 12.6632L13.2339 12.6633L13.2507 12.6633L13.2675 12.6633L13.2843 12.6633L13.3011 12.6633L13.3178 12.6634L13.3346 12.6634L13.3514 12.6634L13.3682 12.6634L13.3849 12.6634L13.4017 12.6635L13.4185 12.6635L13.4353 12.6635L13.4521 12.6635L13.4688 12.6635L13.4856 12.6636L13.5024 12.6636L13.5192 12.6636L13.536 12.6636L13.5527 12.6636L13.5695 12.6637L13.5863 12.6637L13.6031 12.6637L13.6199 12.6637L13.6366 12.6637L13.6534 12.6638L13.6702 12.6638L13.687 12.6638L13.7038 12.6638L13.7205 12.6638L13.7373 12.6639L13.7541 12.6639L13.7709 12.6639L13.7876 12.6639L13.8044 12.6639L13.8212 12.664L13.838 12.664L13.8548 12.664L13.8715 12.664L13.8883 12.664L13.9051 12.6641L13.9219 12.6641L13.9387 12.6641L13.9554 12.6641L13.9722 12.6641L13.989 12.6642L14.0058 12.6642L14.0226 12.6642L14.0393 12.6642L14.0561 12.6642L14.0729 12.6643L14.0897 12.6643L14.1064 12.6643L14.1232 12.6643L14.14 12.6644L14.1568 12.6644L14.1736 12.6644L14.1903 12.6644L14.2071 12.6644L14.2239 12.6645L14.2407 12.6645L14.2575 12.6645L14.2742 12.6645L14.291 12.6645L14.3078 12.6646L14.3246 12.6646L14.3414 12.6646L14.3581 12.6646L14.3749 12.6646L14.3917 12.6647L14.4085 12.6647L14.4253 12.6647L14.442 12.6647L14.4588 12.6647L14.4756 12.6648L14.4924 12.6648L14.5091 12.6648L14.5259 12.6648L14.5427 12.6648L14.5595 12.6649L14.5763 12.6649L14.593 12.6649L14.6098 12.6649L14.6266 12.6649L14.6434 12.665L14.6602 12.665L14.6769 12.665L14.6937 12.665L14.7105 12.665L14.7273 12.6651L14.7441 12.6651L14.7608 12.6651L14.7776 12.6651L14.7944 12.6651L14.8112 12.6652L14.828 12.6652L14.8447 12.6652L14.8615 12.6652L14.8783 12.6652L14.8951 12.6653L14.9118 12.6653L14.9286 12.6653L14.9454 12.6653L14.9622 12.6653L14.979 12.6654L14.9957 12.6654L15.0125 12.6654L15.0293 12.6654L15.0461 12.6654L15.0629 12.6655L15.0796 12.6655L15.0964 12.6655L15.1132 12.6655L15.13 12.6655L15.1468 12.6656L15.1635 12.6656L15.1803 12.6656L15.1971 12.6656L15.2139 12.6656L15.2306 12.6657L15.2474 12.6657L15.2642 12.6657L15.281 12.6657L15.2978 12.6657L15.3145 12.6658L15.3313 12.6658L15.3481 12.6658L15.3649 12.6658L15.3817 12.6658L15.3984 12.6659L15.4152 12.6659L15.432 12.6659L15.4488 12.6659L15.4656 12.6659L15.4823 12.666L15.4991 12.666L15.5159 12.666L15.5327 12.666L15.5495 12.666L15.5662 12.6661L15.583 12.6661L15.5998 12.6661L15.6166 12.6661L15.6333 12.6661L15.6501 12.6662L15.6669 12.6662L15.6837 12.6662L15.7005 12.6662L15.7172 12.6662L15.734 12.6663L15.7508 12.6663L15.7676 12.6663L15.7844 12.6663L15.8011 12.6663L15.8179 12.6664L15.8347 12.6664L15.8515 12.6664L15.8683 12.6664L15.885 12.6664L15.9018 12.6665L15.9186 12.6665L15.9354 12.6665L15.9522 12.6665L15.9689 12.6665L15.9857 12.6666L16.0025 12.6666L16.0193 12.6666L16.036 12.6666L16.0528 12.6666L16.0696 12.6667L16.0864 12.6667L16.1032 12.6667L16.1199 12.6667L16.1367 12.6667L16.1535 12.6668L16.1703 12.6668L16.1871 12.6668L16.2038 12.6668L16.2206 12.6669L16.2374 12.6669L16.2542 12.6669L16.271 12.6669L16.2836 12.6669L12.458 16.7581C12.2065 17.0271 12.2065 17.4631 12.458 17.732C12.7095 18.001 13.1172 18.001 13.3687 17.732L18.2822 12.4772C18.5337 12.2083 18.5337 11.7723 18.2822 11.5033L13.3687 6.24853Z",fill:"white"})),G8e=_.forwardRef(V8e),q8e=(n,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M18.2139 2.44646L12 3.99992H5.4375C4.64359 3.99992 4 4.64352 4 5.43742V18.5624C4 19.3563 4.64359 19.9999 5.4375 19.9999H12L18.2139 21.5534C19.1211 21.7802 20 21.094 20 20.1588V3.84104C20 2.90584 19.1211 2.21964 18.2139 2.44646ZM12 17.9999V5.99992H6V17.9999H12Z",fill:"white"})),K8e=_.forwardRef(q8e),W8e="_userButton_t5z8t_15",z8e={userButton:W8e},Y8e=({preventNavigation:n,isAuthenticated:e,isPasswordlessUser:t,userId:r,displayName:i,avatarUrl:s,onAction:o})=>{const{t:a}=Qe(),c=di(),l=_.useMemo(()=>{const p=[];return e&&(p.push({key:"user",icon:sF,label:i,dataTestid:"usermenu_user"}),p.push({key:"settings",icon:H8e,label:a("common.settings")}),t&&!n&&p.push({key:"login",label:a("action.sign_in"),icon:G8e,dataTestid:"usermenu_login"}),!t&&!n&&p.push({key:"logout",label:a("action.sign_out"),icon:K8e,dataTestid:"usermenu_logout"})),p},[e,t,i,n,a]),[u,h]=_.useState(!1);return e?w.jsx(hL,{title:a("a11y.user_menu"),showTitle:!1,align:"end",open:u,onOpenChange:h,trigger:w.jsx("button",{"aria-label":a("common.profile"),className:z8e.userButton,"data-testid":"usermenu_open",children:e&&(!t||s)?w.jsx(Np,{id:r,name:i,size:Mp.SM,src:s}):w.jsx(sF,{})}),children:l.map(({key:p,icon:m,label:v,dataTestid:g})=>w.jsx(ip,{Icon:m,label:v,"data-test-id":g,onSelect:()=>o(p)},p))}):w.jsx(r4,{to:{pathname:"/login"},state:{from:c},children:a("log_in")})},f4=({preventNavigation:n=!1})=>{const e=di(),t=ja(),{client:r,logout:i,authenticated:s,passwordlessUser:o}=o4(),{displayName:a,avatarUrl:c}=Ly(r),[l,u]=_.useState(!1),h=_.useCallback(()=>u(!1),[u]),[p,m]=_.useState(d4),v=_.useCallback(S=>{var b;switch(S){case"user":m("profile"),u(!0);break;case"settings":m("audio"),u(!0);break;case"logout":i==null||i();break;case"login":(b=t("/login",{state:{from:e}}))==null||b.catch(R=>M.error("Failed to navigate to login",R));break}},[t,e,i,u]),g=(r==null?void 0:r.getUserIdLocalpart())??"";return w.jsxs(w.Fragment,{children:[w.jsx(Y8e,{preventNavigation:n,isAuthenticated:s,isPasswordlessUser:o,avatarUrl:c,onAction:v,userId:(r==null?void 0:r.getUserId())??"",displayName:a||(g?g.replace("@",""):"")}),r&&w.jsx(h4,{client:r,open:l,onDismiss:h,tab:p,onTabChange:m})]})};function X8e(n){return new Worker(""+new URL("IndexedDBWorker-DunQAoUH.js",import.meta.url).href,{name:n==null?void 0:n.name})}const db=new tP,J8e=n=>{const[e,t]=_.useState(()=>localStorage.getItem(n));return _.useEffect(()=>(db.on(n,t),()=>{db.off(n,t)}),[n,t]),[e,_.useCallback(r=>{t(r),localStorage.setItem(n,r),db.emit(n,r)},[n,t])]},Z8e=(n,e)=>{localStorage.setItem(n,e),db.emit(n,e)};function GZ(n,e){Z8e(p4(n),e)}const p4=n=>`room-shared-key-${n}`,Q8e=n=>{const e=p4(n);return J8e(e)[0]};function e9e(n){qZ(Rs());const e=p4(n);return localStorage.getItem(e)}function qZ(n){!n.password||!n.roomId||GZ(n.roomId,n.password)}const t9e=()=>{const n=eh();return _.useEffect(()=>qZ(n),[n]),n.roomId&&n.password?[n.roomId,n.password]:[void 0,void 0]};function wE(n){const{client:e}=nh(),[t,r]=t9e(),i=Q8e(n),s=e==null?void 0:e.getRoom(n);return _.useMemo(()=>s?i?{kind:Vt.SHARED_KEY,secret:i}:t===n?{kind:Vt.SHARED_KEY,secret:r}:s.hasEncryptionStateEvent()?{kind:Vt.PER_PARTICIPANT}:{kind:Vt.NONE}:{kind:Vt.NONE},[r,s,n,i,t])}const oF=!1,n9e="element-call-sync";async function r9e(n){let e=!!await n.store.getSavedSyncToken();return new Promise((t,r)=>{const i=(s,o,a)=>{s==="PREPARED"?e?e=!1:(n.removeListener(Ge.Sync,i),t()):s==="ERROR"&&(n.removeListener(Ge.Sync,i),r(a==null?void 0:a.error))};n.on(Ge.Sync,i)})}async function KZ(n,e){var a;let t;try{t=window.indexedDB}catch(c){M.warn("Could not get indexDB from window.",c)}const r={fallbackICEServerAllowed:oF,isVoipWithNoMediaAllowed:(a=gt.get().features)==null?void 0:a.feature_group_calls_without_video_and_audio};t&&localStorage?r.store=new gB({indexedDB:window.indexedDB,localStorage,dbName:n9e,workerFactory:()=>new X8e}):localStorage&&(r.store=new pv({localStorage}));const{e2eEnabled:i}=Rs();i||M.info("Disabling E2E: group call signalling will NOT be encrypted.");const s=bw({...r,...n,useAuthorizationHeader:!0,localTimeoutMs:5e3,useE2eForGroupCall:i,fallbackICEServerAllowed:oF});e||await s.clearStores();try{await s.store.startup()}catch(c){M.error("Error starting matrix client indexDB store. Falling back to memory store.",c),s.store=new pv({localStorage}),await s.store.startup()}try{await s.initRustCrypto()}catch(c){M.warn(c,"Make sure to clear client stores before initializing the rust crypto.")}const o=r9e(s);return await s.startClient({clientWellKnownPollPeriod:60*10}),await o,s}function Ay(n){return n.trim().replace(/\s/g,"-").replace(/[^\w-]/g,"").toLowerCase()}function i9e(n,e){return`#${Ay(n)}:${e.getDomain()}`}function WZ(n){const e=n.split(":",2);if(e.length===2&&e[0][0]==="#"){if(e[1]===gt.defaultServerName())return e[0];throw new Error("Unsupported remote room alias")}return n}async function zZ(n,e,t){M.log("Creating room for group call");const r=n.createRoom({visibility:IP.Private,preset:ay.PublicChat,name:e,room_alias_name:t?void 0:Ay(e),power_level_content_override:{invite:100,kick:100,ban:100,redact:50,state_default:0,events_default:0,users_default:0,events:{"m.room.power_levels":100,"m.room.history_visibility":100,"m.room.tombstone":100,"m.room.encryption":100,"m.room.name":50,"m.room.message":0,"m.room.encrypted":50,"m.sticker":50,"org.matrix.msc3401.call.member":0},users:{[n.getUserId()]:100}}}),i=await new Promise((o,a)=>{r.catch(u=>{a(u),l()});const c=u=>{r.then(h=>{u.roomId===h.room_id&&(o(u.roomId),l())},h=>{M.error("Failed to wait for the room to arrive",h)})},l=()=>{n.off(Ge.Room,c)};n.on(Ge.Room,c)});let s;return t==Vt.SHARED_KEY&&(s=k$(16),GZ(i,s)),{roomId:i,alias:t?void 0:i9e(e,n),password:s}}function YZ(n,e,t,r){return`${window.location.protocol}//${window.location.host}${EE(n,e,t)}`}function EE(n,e,t,r){return`/room/#${t?"/"+Ay(t):""}?${Ike(n,e).toString()}`}const m4=n=>{const[e,t]=_.useState(void 0),[r,i]=_.useState(void 0),s=_.useRef(void 0);s.current||(s.current=bw({baseUrl:gt.defaultHomeserverUrl()})),_.useEffect(()=>{Je||s.current.registerRequest({}).catch(a=>{var c,l,u,h,p,m,v;t((p=(h=(u=(l=(c=a.data)==null?void 0:c.params["m.login.terms"])==null?void 0:l.policies)==null?void 0:u.privacy_policy)==null?void 0:h.en)==null?void 0:p.url),i((v=(m=a.data)==null?void 0:m.params["m.login.recaptcha"])==null?void 0:v.public_key)})},[]);const o=_.useCallback(async(a,c,l,u,h)=>{const p=new NP({matrixClient:s.current,doRequest:async k=>s.current.registerRequest({username:a,password:c,auth:k||void 0}),stateUpdated:(k,I)=>{if(I.error)throw new Error(I.error);k==="m.login.terms"?p.submitAuthDict({type:"m.login.terms"}).catch(T=>{M.error(T)}):k==="m.login.recaptcha"&&p.submitAuthDict({type:"m.login.recaptcha",response:u}).catch(T=>{M.error(T)})},requestEmailToken:async()=>Promise.resolve({sid:"dummy"})}),{user_id:m,access_token:v,device_id:g}=await p.attemptAuth();await(n==null?void 0:n.logout(!0));const S=await KZ({baseUrl:gt.defaultHomeserverUrl(),accessToken:v,userId:m,deviceId:g},!1);await S.setDisplayName(l);const b={user_id:m,device_id:g,access_token:v,passwordlessUser:h};h&&(b.tempPassword=c);const R=S.getUser(S.getUserId());return R.setRawDisplayName(l),R.setDisplayName(l),[S,b]},[n]);return{privacyPolicyUrl:e,recaptchaKey:r,register:o}},s9e="_buttons_1arp2_8",o9e={buttons:s9e},XZ=({onJoin:n,open:e,onDismiss:t})=>{const{t:r}=Qe();return w.jsxs(th,{title:r("join_existing_call_modal.title"),open:e,onDismiss:t,children:[w.jsx("p",{children:r("join_existing_call_modal.text")}),w.jsxs(yt,{rightAlign:!0,className:o9e.buttons,children:[w.jsx(Mt,{onClick:t,children:r("action.no")}),w.jsx(Mt,{onClick:n,"data-testid":"home_joinExistingRoom",children:r("join_existing_call_modal.join_button")})]})]})},aF="https://www.recaptcha.net/recaptcha/api.js?onload=mxOnRecaptchaLoaded&render=explicit";function g4(n){const{t:e}=Qe(),[t]=_.useState(()=>Es(16)),r=_.useRef(void 0);_.useEffect(()=>{var a;if(!n)return;const o=()=>{document.getElementById(t)&&window.grecaptcha.render(t,{sitekey:n,size:"invisible",callback:c=>{var l;return(l=r.current)==null?void 0:l.resolve(c)},"error-callback":()=>{var c;return(c=r.current)==null?void 0:c.reject(new Error)}})};if(typeof((a=window.grecaptcha)==null?void 0:a.render)=="function")o();else if(window.mxOnRecaptchaLoaded=o,!document.querySelector(`script[src="${aF}"]`)){const c=document.createElement("script");c.src=aF,c.async=!0,document.body.appendChild(c)}},[t,n]);const i=_.useCallback(async()=>n?window.grecaptcha?new Promise((o,a)=>{var u,h;const c=new MutationObserver(p=>{var m,v;for(const g of p)if(((v=(m=g.target)==null?void 0:m.style)==null?void 0:v.visibility)!=="visible"){a(nF("recaptcha_dismissed",e)),c.disconnect();return}});r.current={resolve:p=>{o(p),c.disconnect()},reject:p=>{a(p),c.disconnect()}},window.grecaptcha.execute().then(()=>{},p=>{M.error("Recaptcha execution failed",p)});const l=document.querySelector('iframe[src*="recaptcha/api2/bframe"]');(u=l==null?void 0:l.parentNode)!=null&&u.parentNode&&c.observe((h=l==null?void 0:l.parentNode)==null?void 0:h.parentNode,{attributes:!0})}):(M.log("Recaptcha not loaded"),Promise.reject(nF("recaptcha_not_loaded",e))):Promise.resolve(""),[n,e]),s=_.useCallback(()=>{var o;(o=window.grecaptcha)==null||o.reset()},[]);return{execute:i,reset:s,recaptchaId:t}}const a9e="_form_jcuzc_8",c9e={form:a9e},CE=_.forwardRef(({children:n,className:e,onSubmit:t},r)=>w.jsx("form",{onSubmit:t,className:De(c9e.form,e),ref:r,children:n}));CE.displayName="Form";const l9e="_footer_106jg_8",u9e="_mobileLoginLink_106jg_19",d9e="_form_106jg_24",h9e="_notice_106jg_40",ig={footer:l9e,mobileLoginLink:u9e,form:d9e,notice:h9e},f9e="_container_dwllg_8",p9e="_main_dwllg_15",m9e="_logo_dwllg_23",jf={container:f9e,main:p9e,logo:m9e},cF=n=>{n=1831565813+(n|=0)|0;let e=Math.imul(n^n>>>15,1|n);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};class g9e{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:t,separator:r,dictionaries:i,style:s,seed:o}=e;this.dictionaries=i,this.separator=r,this.length=t,this.style=s,this.seed=o}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries.
|
|
208
208
|
Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((t,r)=>{let i;e?(i=(o=>{if(typeof o=="string"){const a=o.split("").map(l=>l.charCodeAt(0)).reduce((l,u)=>l+u,1),c=Math.floor(Number(a));return cF(c)}return cF(o)})(e),e=4294967296*i):i=Math.random();let s=r[Math.floor(i*r.length)]||"";if(this.style==="lowerCase")s=s.toLowerCase();else if(this.style==="capital"){const[o,...a]=s.split("");s=o.toUpperCase()+a.join("")}else this.style==="upperCase"&&(s=s.toUpperCase());return t?`${t}${this.separator}${s}`:`${s}`},"")}}const lF={separator:"_",dictionaries:[]},v9e=n=>{const e=[...n&&n.dictionaries||lF.dictionaries],t={...lF,...n,length:n&&n.length||e.length,dictionaries:e};if(!n||!n.dictionaries||!n.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new g9e(t).generate()};var y9e=["able","above","absent","absolute","abstract","abundant","academic","acceptable","accepted","accessible","accurate","accused","active","actual","acute","added","additional","adequate","adjacent","administrative","adorable","advanced","adverse","advisory","aesthetic","afraid","aggregate","aggressive","agreeable","agreed","agricultural","alert","alive","alleged","allied","alone","alright","alternative","amateur","amazing","ambitious","amused","ancient","angry","annoyed","annual","anonymous","anxious","appalling","apparent","applicable","appropriate","arbitrary","architectural","armed","arrogant","artificial","artistic","ashamed","asleep","assistant","associated","atomic","attractive","automatic","autonomous","available","average","awake","aware","awful","awkward","back","bad","balanced","bare","basic","beautiful","beneficial","better","bewildered","big","binding","biological","bitter","bizarre","blank","blind","blonde","bloody","blushing","boiling","bold","bored","boring","bottom","brainy","brave","breakable","breezy","brief","bright","brilliant","broad","broken","bumpy","burning","busy","calm","capable","capitalist","careful","casual","causal","cautious","central","certain","changing","characteristic","charming","cheap","cheerful","chemical","chief","chilly","chosen","christian","chronic","chubby","circular","civic","civil","civilian","classic","classical","clean","clear","clever","clinical","close","closed","cloudy","clumsy","coastal","cognitive","coherent","cold","collective","colonial","colorful","colossal","coloured","colourful","combative","combined","comfortable","coming","commercial","common","communist","compact","comparable","comparative","compatible","competent","competitive","complete","complex","complicated","comprehensive","compulsory","conceptual","concerned","concrete","condemned","confident","confidential","confused","conscious","conservation","conservative","considerable","consistent","constant","constitutional","contemporary","content","continental","continued","continuing","continuous","controlled","controversial","convenient","conventional","convinced","convincing","cooing","cool","cooperative","corporate","correct","corresponding","costly","courageous","crazy","creative","creepy","criminal","critical","crooked","crowded","crucial","crude","cruel","cuddly","cultural","curious","curly","current","curved","cute","daily","damaged","damp","dangerous","dark","dead","deaf","deafening","dear","decent","decisive","deep","defeated","defensive","defiant","definite","deliberate","delicate","delicious","delighted","delightful","democratic","dependent","depressed","desirable","desperate","detailed","determined","developed","developing","devoted","different","difficult","digital","diplomatic","direct","dirty","disabled","disappointed","disastrous","disciplinary","disgusted","distant","distinct","distinctive","distinguished","disturbed","disturbing","diverse","divine","dizzy","domestic","dominant","double","doubtful","drab","dramatic","dreadful","driving","drunk","dry","dual","due","dull","dusty","dutch","dying","dynamic","eager","early","eastern","easy","economic","educational","eerie","effective","efficient","elaborate","elated","elderly","eldest","electoral","electric","electrical","electronic","elegant","eligible","embarrassed","embarrassing","emotional","empirical","empty","enchanting","encouraging","endless","energetic","enormous","enthusiastic","entire","entitled","envious","environmental","equal","equivalent","essential","established","estimated","ethical","ethnic","eventual","everyday","evident","evil","evolutionary","exact","excellent","exceptional","excess","excessive","excited","exciting","exclusive","existing","exotic","expected","expensive","experienced","experimental","explicit","extended","extensive","external","extra","extraordinary","extreme","exuberant","faint","fair","faithful","familiar","famous","fancy","fantastic","far","fascinating","fashionable","fast","fat","fatal","favourable","favourite","federal","fellow","female","feminist","few","fierce","filthy","final","financial","fine","firm","fiscal","fit","fixed","flaky","flat","flexible","fluffy","fluttering","flying","following","fond","foolish","foreign","formal","formidable","forthcoming","fortunate","forward","fragile","frail","frantic","free","frequent","fresh","friendly","frightened","front","frozen","full","fun","functional","fundamental","funny","furious","future","fuzzy","gastric","gay","general","generous","genetic","gentle","genuine","geographical","giant","gigantic","given","glad","glamorous","gleaming","global","glorious","golden","good","gorgeous","gothic","governing","graceful","gradual","grand","grateful","greasy","great","grieving","grim","gross","grotesque","growing","grubby","grumpy","guilty","handicapped","handsome","happy","hard","harsh","head","healthy","heavy","helpful","helpless","hidden","high","hilarious","hissing","historic","historical","hollow","holy","homeless","homely","hon","honest","horizontal","horrible","hostile","hot","huge","human","hungry","hurt","hushed","husky","icy","ideal","identical","ideological","ill","illegal","imaginative","immediate","immense","imperial","implicit","important","impossible","impressed","impressive","improved","inadequate","inappropriate","inc","inclined","increased","increasing","incredible","independent","indirect","individual","industrial","inevitable","influential","informal","inherent","initial","injured","inland","inner","innocent","innovative","inquisitive","instant","institutional","insufficient","intact","integral","integrated","intellectual","intelligent","intense","intensive","interested","interesting","interim","interior","intermediate","internal","international","intimate","invisible","involved","irrelevant","isolated","itchy","jealous","jittery","joint","jolly","joyous","judicial","juicy","junior","just","keen","key","kind","known","labour","large","late","latin","lazy","leading","left","legal","legislative","legitimate","lengthy","lesser","level","lexical","liable","liberal","light","like","likely","limited","linear","linguistic","liquid","literary","little","live","lively","living","local","logical","lonely","long","loose","lost","loud","lovely","low","loyal","ltd","lucky","mad","magic","magnetic","magnificent","main","major","male","mammoth","managerial","managing","manual","many","marginal","marine","marked","married","marvellous","marxist","mass","massive","mathematical","mature","maximum","mean","meaningful","mechanical","medical","medieval","melodic","melted","mental","mere","metropolitan","mid","middle","mighty","mild","military","miniature","minimal","minimum","ministerial","minor","miserable","misleading","missing","misty","mixed","moaning","mobile","moderate","modern","modest","molecular","monetary","monthly","moral","motionless","muddy","multiple","mushy","musical","mute","mutual","mysterious","naked","narrow","nasty","national","native","natural","naughty","naval","near","nearby","neat","necessary","negative","neighbouring","nervous","net","neutral","new","nice","noble","noisy","normal","northern","nosy","notable","novel","nuclear","numerous","nursing","nutritious","nutty","obedient","objective","obliged","obnoxious","obvious","occasional","occupational","odd","official","ok","okay","old","olympic","only","open","operational","opposite","optimistic","oral","ordinary","organic","organisational","original","orthodox","other","outdoor","outer","outrageous","outside","outstanding","overall","overseas","overwhelming","painful","pale","panicky","parallel","parental","parliamentary","partial","particular","passing","passive","past","patient","payable","peaceful","peculiar","perfect","permanent","persistent","personal","petite","philosophical","physical","plain","planned","plastic","pleasant","pleased","poised","polite","political","poor","popular","positive","possible","potential","powerful","practical","precious","precise","preferred","pregnant","preliminary","premier","prepared","present","presidential","pretty","previous","prickly","primary","prime","primitive","principal","printed","prior","private","probable","productive","professional","profitable","profound","progressive","prominent","promising","proper","proposed","prospective","protective","protestant","proud","provincial","psychiatric","psychological","public","puny","pure","purring","puzzled","quaint","qualified","quarrelsome","querulous","quick","quickest","quiet","quintessential","quixotic","racial","radical","rainy","random","rapid","rare","raspy","rational","ratty","raw","ready","real","realistic","rear","reasonable","recent","reduced","redundant","regional","registered","regular","regulatory","related","relative","relaxed","relevant","reliable","relieved","religious","reluctant","remaining","remarkable","remote","renewed","representative","repulsive","required","resident","residential","resonant","respectable","respective","responsible","resulting","retail","retired","revolutionary","rich","ridiculous","right","rigid","ripe","rising","rival","roasted","robust","rolling","romantic","rotten","rough","round","royal","rubber","rude","ruling","running","rural","sacred","sad","safe","salty","satisfactory","satisfied","scared","scary","scattered","scientific","scornful","scrawny","screeching","secondary","secret","secure","select","selected","selective","selfish","semantic","senior","sensible","sensitive","separate","serious","severe","sexual","shaggy","shaky","shallow","shared","sharp","sheer","shiny","shivering","shocked","short","shrill","shy","sick","significant","silent","silky","silly","similar","simple","single","skilled","skinny","sleepy","slight","slim","slimy","slippery","slow","small","smart","smiling","smoggy","smooth","social","socialist","soft","solar","sole","solid","sophisticated","sore","sorry","sound","sour","southern","soviet","spare","sparkling","spatial","special","specific","specified","spectacular","spicy","spiritual","splendid","spontaneous","sporting","spotless","spotty","square","squealing","stable","stale","standard","static","statistical","statutory","steady","steep","sticky","stiff","still","stingy","stormy","straight","straightforward","strange","strategic","strict","striking","striped","strong","structural","stuck","stupid","subjective","subsequent","substantial","subtle","successful","successive","sudden","sufficient","suitable","sunny","super","superb","superior","supporting","supposed","supreme","sure","surprised","surprising","surrounding","surviving","suspicious","sweet","swift","symbolic","sympathetic","systematic","tall","tame","tart","tasteless","tasty","technical","technological","teenage","temporary","tender","tense","terrible","territorial","testy","then","theoretical","thick","thin","thirsty","thorough","thoughtful","thoughtless","thundering","tight","tiny","tired","top","tory","total","tough","toxic","traditional","tragic","tremendous","tricky","tropical","troubled","typical","ugliest","ugly","ultimate","unable","unacceptable","unaware","uncertain","unchanged","uncomfortable","unconscious","underground","underlying","unemployed","uneven","unexpected","unfair","unfortunate","unhappy","uniform","uninterested","unique","united","universal","unknown","unlikely","unnecessary","unpleasant","unsightly","unusual","unwilling","upper","upset","uptight","urban","urgent","used","useful","useless","usual","vague","valid","valuable","variable","varied","various","varying","vast","verbal","vertical","very","vicarious","vicious","victorious","violent","visible","visiting","visual","vital","vitreous","vivacious","vivid","vocal","vocational","voiceless","voluminous","voluntary","vulnerable","wandering","warm","wasteful","watery","weak","wealthy","weary","wee","weekly","weird","welcome","well","western","wet","whispering","whole","wicked","wide","widespread","wild","wilful","willing","willowy","wily","wise","wispy","wittering","witty","wonderful","wooden","working","worldwide","worried","worrying","worthwhile","worthy","written","wrong","xenacious","xenial","xenogeneic","xenophobic","xeric","xerothermic","yabbering","yammering","yappiest","yappy","yawning","yearling","yearning","yeasty","yelling","yelping","yielding","yodelling","young","youngest","youthful","ytterbic","yucky","yummy","zany","zealous","zeroth","zestful","zesty","zippy","zonal","zoophagous","zygomorphic","zygotic"],_9e=["aardvark","aardwolf","albatross","alligator","alpaca","amphibian","anaconda","angelfish","anglerfish","ant","anteater","antelope","antlion","ape","aphid","armadillo","asp","baboon","badger","bandicoot","barnacle","barracuda","basilisk","bass","bat","bear","beaver","bedbug","bee","beetle","bird","bison","blackbird","boa","boar","bobcat","bobolink","bonobo","booby","bovid","bug","butterfly","buzzard","camel","canid","canidae","capybara","cardinal","caribou","carp","cat","caterpillar","catfish","catshark","cattle","centipede","cephalopod","chameleon","cheetah","chickadee","chicken","chimpanzee","chinchilla","chipmunk","cicada","clam","clownfish","cobra","cockroach","cod","condor","constrictor","coral","cougar","cow","coyote","crab","crane","crawdad","crayfish","cricket","crocodile","crow","cuckoo","damselfly","deer","dingo","dinosaur","dog","dolphin","donkey","dormouse","dove","dragon","dragonfly","duck","eagle","earthworm","earwig","echidna","eel","egret","elephant","elk","emu","ermine","falcon","felidae","ferret","finch","firefly","fish","flamingo","flea","fly","flyingfish","fowl","fox","frog","galliform","gamefowl","gayal","gazelle","gecko","gerbil","gibbon","giraffe","goat","goldfish","goose","gopher","gorilla","grasshopper","grouse","guan","guanaco","guineafowl","gull","guppy","haddock","halibut","hamster","hare","harrier","hawk","hedgehog","heron","herring","hippopotamus","hookworm","hornet","horse","hoverfly","hummingbird","hyena","iguana","impala","jackal","jaguar","jay","jellyfish","junglefowl","kangaroo","kingfisher","kite","kiwi","koala","koi","krill","ladybug","lamprey","landfowl","lark","leech","lemming","lemur","leopard","leopon","limpet","lion","lizard","llama","lobster","locust","loon","louse","lungfish","lynx","macaw","mackerel","magpie","mammal","manatee","mandrill","marlin","marmoset","marmot","marsupial","marten","mastodon","meadowlark","meerkat","mink","minnow","mite","mockingbird","mole","mollusk","mongoose","monkey","moose","mosquito","moth","mouse","mule","muskox","narwhal","newt","nightingale","ocelot","octopus","opossum","orangutan","orca","ostrich","otter","owl","ox","panda","panther","parakeet","parrot","parrotfish","partridge","peacock","peafowl","pelican","penguin","perch","pheasant","pig","pigeon","pike","pinniped","piranha","planarian","platypus","pony","porcupine","porpoise","possum","prawn","primate","ptarmigan","puffin","puma","python","quail","quelea","quokka","rabbit","raccoon","rat","rattlesnake","raven","reindeer","reptile","rhinoceros","roadrunner","rodent","rook","rooster","roundworm","sailfish","salamander","salmon","sawfish","scallop","scorpion","seahorse","shark","sheep","shrew","shrimp","silkworm","silverfish","skink","skunk","sloth","slug","smelt","snail","snake","snipe","sole","sparrow","spider","spoonbill","squid","squirrel","starfish","stingray","stoat","stork","sturgeon","swallow","swan","swift","swordfish","swordtail","tahr","takin","tapir","tarantula","tarsier","termite","tern","thrush","tick","tiger","tiglon","toad","tortoise","toucan","trout","tuna","turkey","turtle","tyrannosaurus","unicorn","urial","vicuna","viper","vole","vulture","wallaby","walrus","warbler","wasp","weasel","whale","whippet","whitefish","wildcat","wildebeest","wildfowl","wolf","wolverine","wombat","woodpecker","worm","wren","xerinae","yak","zebra"],b9e=["amaranth","amber","amethyst","apricot","aqua","aquamarine","azure","beige","black","blue","blush","bronze","brown","chocolate","coffee","copper","coral","crimson","cyan","emerald","fuchsia","gold","gray","green","harlequin","indigo","ivory","jade","lavender","lime","magenta","maroon","moccasin","olive","orange","peach","pink","plum","purple","red","rose","salmon","sapphire","scarlet","silver","tan","teal","tomato","turquoise","violet","white","yellow"];const S9e=["hydrogen","helium","lithium","beryllium","boron","carbon","nitrogen","oxygen","fluorine","neon","sodium","magnesium","aluminum","silicon","phosphorus","sulfur","chlorine","argon","potassium","calcium","scandium","titanium","vanadium","chromium","manganese","iron","cobalt","nickel","copper","zinc","gallium","germanium","arsenic","selenium","bromine","krypton","rubidium","strontium","yttrium","zirconium","niobium","molybdenum","technetium","ruthenium","rhodium","palladium","silver","cadmium","indium","tin","antimony","tellurium","iodine","xenon","cesium","barium","lanthanum","cerium","praseodymium","neodymium","promethium","samarium","europium","gadolinium","terbium","dysprosium","holmium","erbium","thulium","ytterbium","lutetium","hafnium","tantalum","wolfram","rhenium","osmium","iridium","platinum","gold","mercury","thallium","lead","bismuth","polonium","astatine","radon","francium","radium","actinium","thorium","protactinium","uranium","neptunium","plutonium","americium","curium","berkelium","californium","einsteinium","fermium","mendelevium","nobelium","lawrencium","rutherfordium","dubnium","seaborgium","bohrium","hassium","meitnerium","darmstadtium","roentgenium","copernicium","nihonium","flerovium","moscovium","livermorium","tennessine","oganesson"];function JZ(){return v9e({dictionaries:[b9e,y9e,_9e,S9e],style:"lowerCase",length:3,separator:"-"})}const w9e=()=>{const{setClient:n}=nh(),[e,t]=_.useState(!1),[r,i]=_.useState(),[s]=gE(),{recaptchaKey:o,register:a}=m4(),{execute:c,reset:l,recaptchaId:u}=g4(o),[h,p]=_.useState(!1),m=_.useCallback(()=>p(!1),[p]),[v,g]=_.useState(),S=ja(),{t:b}=Qe(),R=_.useCallback(k=>{k.preventDefault();const I=new FormData(k.target),T=WZ(I.get("callName")),C=I.get("displayName");async function P(){i(void 0),t(!0);const O=await c(),D=JZ(),[F,U]=await a(D,Es(16),C,O,!0);let B;try{B=await zZ(F,T,Vt.SHARED_KEY)}catch(V){if(!n)throw V;if(V.errcode==="M_ROOM_IN_USE"){g(()=>{var H;n({client:F,session:U});const z=Ay(T);(H=S(`/${z}`))==null||H.catch(J=>{M.error("Failed to navigate to alias localpart",J)})}),t(!1),p(!0);return}else throw V}if(!n)throw new Error("setClient is undefined");if(!B.password)throw new Error("Failed to create room with shared secret");n({client:F,session:U}),await S(EE(B.roomId,{kind:Vt.SHARED_KEY,secret:B.password},T))}P().catch(O=>{M.error(O),t(!1),i(O),l()})},[a,l,c,S,p,n]);return w.jsxs(w.Fragment,{children:[w.jsxs("div",{className:jf.container,children:[w.jsxs(wu,{children:[w.jsx(Jd,{children:w.jsx(Dd,{})}),w.jsx(Zd,{hideMobile:!0,children:w.jsx(f4,{})})]}),w.jsxs("main",{className:jf.main,children:[w.jsx(Dd,{className:jf.logo}),w.jsx(Su,{size:"lg",weight:"semibold",children:b("start_new_call")}),w.jsxs(CE,{className:ig.form,onSubmit:R,children:[w.jsx(yt,{children:w.jsx(vn,{id:"callName",name:"callName",label:b("call_name"),placeholder:b("call_name"),type:"text",required:!0,autoComplete:"off","data-testid":"home_callName"})}),w.jsx(yt,{children:w.jsx(vn,{id:"displayName",name:"displayName",label:b("common.display_name"),placeholder:b("common.display_name"),type:"text",required:!0,"data-testid":"home_displayName",autoComplete:"off"})}),s===null&&w.jsx(Xt,{size:"sm",className:ig.notice,children:w.jsx(a4,{})}),w.jsx(Xt,{size:"sm",className:ig.notice,children:w.jsxs(Ci,{i18nKey:"unauthenticated_view_eula_caption",children:['By clicking "Go", you agree to our'," ",w.jsx(bd,{href:gt.get().eula,children:"End User Licensing Agreement (EULA)"})]})}),r&&w.jsx(yt,{children:w.jsx(Cu,{error:r})}),w.jsx(Mt,{type:"submit",size:"lg",disabled:e,"data-testid":"home_go",children:b(e?"common.loading":"action.go")}),w.jsx("div",{id:u})]})]}),w.jsxs("footer",{className:ig.footer,children:[w.jsx(Xt,{className:ig.mobileLoginLink,children:w.jsx(Aa,{to:"/login","data-testid":"home_login",children:b("unauthenticated_view_login_button")})}),w.jsx(Xt,{children:w.jsxs(Ci,{i18nKey:"unauthenticated_view_body",children:["Not registered yet?"," ",w.jsx(Aa,{to:"/register","data-testid":"home_register",children:"Create an account"})]})})]})]}),v&&w.jsx(XZ,{onJoin:v,open:h,onDismiss:m})]})},qh={};function uF(n,e){if(qh[e.roomId])return qh[e.roomId];if(!e||!e.timeline){const i=Number.MAX_SAFE_INTEGER;return qh[e.roomId]=i,i}const t=n.getUserId();if(e.getMyMembership()!==We.Join){const i=e.currentState.getStateEvents("m.room.member",t);if(i&&!Array.isArray(i)){const s=i.getTs();return qh[e.roomId]=s,s}}for(let i=e.timeline.length-1;i>=0;--i){const o=e.timeline[i].getTs();if(o)return qh[e.roomId]=o,o}const r=Number.MAX_SAFE_INTEGER;return qh[e.roomId]=r,r}function E9e(n,e){return e.sort((t,r)=>uF(n,r)-uF(n,t))}const C9e=n=>{var e,t;if(!n.hasEncryptionStateEvent()&&!e9e(n.roomId))return!1;switch(n.getJoinRule()){case wc.Public:return!0;case wc.Knock:switch(n.getMyMembership()){case We.Join:case We.Knock:return!0;case We.Invite:return((t=(e=n.getLiveTimeline().getState(Be.FORWARDS))==null?void 0:e.getStateEvents(ie.RoomMember,n.myUserId))==null?void 0:t.getPrevContent().membership)===wc.Knock;default:return!1}default:return n.getMyMembership()===We.Join}},T9e=n=>{var e,t;switch(n.getMyMembership()){case We.Join:return!!((t=(e=n.getLiveTimeline().getState(Be.FORWARDS))==null?void 0:e.events)!=null&&t.get(ie.GroupCallMemberPrefix));case We.Knock:return!0;default:return!1}};function I9e(n){const[e,t]=_.useState([]);return _.useEffect(()=>{function r(){const i=n.getRooms().filter(T9e).filter(C9e),o=E9e(n,i).map(a=>{const c=n.matrixRTC.getRoomSession(a);return{roomAlias:a.getCanonicalAlias()??void 0,roomName:a.name,avatarUrl:a.getMxcAvatarUrl(),room:a,session:c,participants:c.memberships.filter(l=>l.sender).map(l=>a.getMember(l.sender)).filter(l=>l)}});t(o)}return r(),n.matrixRTC.on(lk.SessionStarted,r),n.on(Xe.MyMembership,r),()=>{n.matrixRTC.off(lk.SessionStarted,r),n.off(Xe.MyMembership,r)}},[n]),e}const R9e="_form_1vjc2_8",k9e="_fieldRow_1vjc2_16",x9e="_button_1vjc2_24",P9e="_notice_1vjc2_32",sg={form:R9e,fieldRow:k9e,button:x9e,notice:P9e},L9e="_callTileSpacer_l4ywf_8",A9e="_callTile_l4ywf_8",O9e="_callTileLink_l4ywf_28",M9e="_callInfo_l4ywf_40",N9e="_callName_l4ywf_53",D9e="_callList_l4ywf_63",F9e="_disabled_l4ywf_74",uc={callTileSpacer:L9e,callTile:A9e,callTileLink:O9e,callInfo:M9e,callName:N9e,callList:D9e,disabled:F9e},U9e=({rooms:n,client:e})=>w.jsx(w.Fragment,{children:w.jsxs("div",{className:uc.callList,children:[n.map(({room:t,roomName:r,avatarUrl:i,participants:s})=>w.jsx(j9e,{client:e,name:r,avatarUrl:i,room:t,participants:s},t.roomId)),n.length>3&&w.jsxs(w.Fragment,{children:[w.jsx("div",{className:uc.callTileSpacer}),w.jsx("div",{className:uc.callTileSpacer})]})]})}),j9e=({name:n,avatarUrl:e,room:t,client:r})=>{const{t:i}=Qe(),s=wE(t.roomId),[o,a]=_.useState(!1),c=_.useCallback(u=>{u.stopPropagation(),u.preventDefault(),a(!0),r.leave(t.roomId).catch(()=>a(!1))},[t,r]),l=w.jsxs(w.Fragment,{children:[w.jsx(Np,{id:t.roomId,name:n,size:Mp.LG,src:e}),w.jsx("div",{className:uc.callInfo,children:w.jsx(Xt,{weight:"semibold",className:uc.callName,children:n})}),w.jsx(Wq,{onClick:c,disabled:o,"aria-label":i("action.remove"),children:w.jsx(Gw,{})})]});return w.jsx("div",{className:uc.callTile,children:o?w.jsx("span",{className:De(uc.callTileLink,uc.disabled),children:l}):w.jsx(Pw,{to:EE(t.roomId,s,t.name),className:uc.callTileLink,children:l})})},$9e=({client:n})=>{const[e,t]=_.useState(!1),[r,i]=_.useState(),[s]=gE(),o=ja(),{t:a}=Qe(),[c,l]=_.useState(!1),u=_.useCallback(()=>l(!1),[l]),h=_.useCallback(S=>{S.preventDefault();const R=new FormData(S.target).get("callName"),k=typeof R=="string"?WZ(R):"";async function I(){i(void 0),t(!0);const T=await zZ(n,k,Vt.SHARED_KEY);if(!T.password)throw new Error("Failed to create room with shared secret");await o(EE(T.roomId,{kind:Vt.SHARED_KEY,secret:T.password},k))}I().catch(T=>{T.errcode==="M_ROOM_IN_USE"?(v(Ay(k)),t(!1),i(void 0),l(!0)):(M.error(T),t(!1),i(T))})},[n,o,l]),p=I9e(n),[m,v]=_.useState(),g=_.useCallback(()=>{var S;(S=o(`/${m}`))==null||S.catch(b=>{M.error("Failed to navigate to existing alias",b)})},[o,m]);return w.jsxs(w.Fragment,{children:[w.jsxs("div",{className:jf.container,children:[w.jsxs(wu,{children:[w.jsx(Jd,{children:w.jsx(Dd,{})}),w.jsx(Zd,{children:w.jsx(f4,{})})]}),w.jsxs("main",{className:jf.main,children:[w.jsx(Dd,{className:jf.logo}),w.jsx(Su,{size:"lg",weight:"semibold",children:a("start_new_call")}),w.jsxs(CE,{className:sg.form,onSubmit:h,children:[w.jsxs(yt,{className:sg.fieldRow,children:[w.jsx(vn,{id:"callName",name:"callName",label:a("call_name"),placeholder:a("call_name"),type:"text",required:!0,autoComplete:"off","data-testid":"home_callName"}),w.jsx(Mt,{type:"submit",size:"lg",className:sg.button,disabled:e,"data-testid":"home_go",children:a(e?"common.loading":"action.go")})]}),s===null&&w.jsx(Xt,{size:"sm",className:sg.notice,children:w.jsx(a4,{})}),r&&w.jsx(yt,{className:sg.fieldRow,children:w.jsx(Cu,{error:r})})]}),p.length>0&&w.jsx(U9e,{rooms:p,client:n})]})]}),w.jsx(XZ,{onJoin:g,open:c,onDismiss:u})]})};function Oy(n){_.useEffect(()=>{const e="Element Call";document.title=n?`${e} | ${n}`:e},[n])}const ZZ=()=>{const{t:n}=Qe();Oy(n("common.home"));const e=jp();return e?e.state==="error"?w.jsx(Kv,{widget:Je,error:e.error}):e.authenticated?w.jsx($9e,{client:e.authenticated.client}):w.jsx(w9e,{}):w.jsx(_E,{})},B9e=(n,e)=>_.createElement("svg",{width:300,height:66,viewBox:"0 0 300 66",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("circle",{cx:32.6901,cy:32.6904,r:23.496,fill:"white"}),_.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32.6137 65.2274C50.6257 65.2274 65.2274 50.6257 65.2274 32.6137C65.2274 14.6016 50.6257 0 32.6137 0C14.6016 0 0 14.6016 0 32.6137C0 50.6257 14.6016 65.2274 32.6137 65.2274ZM26.6511 15.1961C26.6511 13.8796 27.7205 12.8124 29.0397 12.8124C37.9808 12.8124 45.2291 20.0456 45.2291 28.9681C45.2291 30.2846 44.1596 31.3518 42.8405 31.3518C41.5213 31.3518 40.4519 30.2846 40.4519 28.9681C40.4519 22.6785 35.3425 17.5797 29.0397 17.5797C27.7205 17.5797 26.6511 16.5125 26.6511 15.1961ZM52.4139 28.9683C52.4139 27.6518 51.3445 26.5846 50.0253 26.5846C48.7061 26.5846 47.6367 27.6518 47.6367 28.9683C47.6367 35.2579 42.5274 40.3567 36.2246 40.3567C34.9054 40.3567 33.836 41.4239 33.836 42.7404C33.836 44.0568 34.9054 45.124 36.2246 45.124C45.1657 45.124 52.4139 37.8909 52.4139 28.9683ZM38.6134 50.031C38.6134 51.3475 37.544 52.4146 36.2248 52.4146C27.2837 52.4146 20.0355 45.1815 20.0355 36.2589C20.0355 34.9425 21.1049 33.8753 22.4241 33.8753C23.7432 33.8753 24.8127 34.9425 24.8127 36.2589C24.8127 42.5486 29.922 47.6474 36.2248 47.6474C37.544 47.6474 38.6134 48.7146 38.6134 50.031ZM12.8113 36.2589C12.8113 37.5754 13.8808 38.6426 15.1999 38.6426C16.5191 38.6426 17.5885 37.5754 17.5885 36.2589C17.5885 29.9693 22.6979 24.8705 29.0007 24.8705C30.3198 24.8705 31.3893 23.8033 31.3893 22.4869C31.3893 21.1704 30.3198 20.1032 29.0007 20.1032C20.0595 20.1032 12.8113 27.3364 12.8113 36.2589Z",fill:"#0DBD8B"}),_.createElement("path",{d:"M114.73 36.9816H91.7256C91.9974 39.3888 92.871 41.3107 94.3464 42.7472C95.8217 44.1449 97.763 44.8438 100.17 44.8438C101.762 44.8438 103.199 44.4555 104.48 43.679C105.761 42.9025 106.674 41.8542 107.217 40.5341H114.206C113.274 43.6014 111.527 46.0862 108.964 47.9887C106.441 49.8523 103.451 50.7842 99.9955 50.7842C95.4917 50.7842 91.8421 49.2894 89.0466 46.2998C86.29 43.3102 84.9117 39.5247 84.9117 34.9432C84.9117 30.4783 86.3094 26.7316 89.1049 23.7032C91.9003 20.6747 95.5111 19.1605 99.9373 19.1605C104.363 19.1605 107.935 20.6553 110.653 23.6449C113.41 26.5957 114.788 30.323 114.788 34.8267L114.73 36.9816ZM99.9373 24.8097C97.763 24.8097 95.9576 25.4503 94.5211 26.7316C93.0845 28.0128 92.1915 29.7212 91.8421 31.8566H107.916C107.605 29.7212 106.751 28.0128 105.353 26.7316C103.956 25.4503 102.15 24.8097 99.9373 24.8097Z",fill:"white"}),_.createElement("path",{d:"M119.557 41.0583V6.40625H126.488V41.1748C126.488 42.7278 127.342 43.5043 129.05 43.5043L130.273 43.4461V50.0271C129.613 50.1435 128.914 50.2018 128.177 50.2018C125.187 50.2018 122.993 49.4447 121.596 47.9305C120.237 46.4163 119.557 44.1255 119.557 41.0583Z",fill:"white"}),_.createElement("path",{d:"M162.549 36.9816H139.545C139.817 39.3888 140.69 41.3107 142.166 42.7472C143.641 44.1449 145.582 44.8438 147.99 44.8438C149.582 44.8438 151.018 44.4555 152.299 43.679C153.581 42.9025 154.493 41.8542 155.037 40.5341H162.025C161.093 43.6014 159.346 46.0862 156.784 47.9887C154.26 49.8523 151.27 50.7842 147.815 50.7842C143.311 50.7842 139.662 49.2894 136.866 46.2998C134.109 43.3102 132.731 39.5247 132.731 34.9432C132.731 30.4783 134.129 26.7316 136.924 23.7032C139.72 20.6747 143.331 19.1605 147.757 19.1605C152.183 19.1605 155.755 20.6553 158.473 23.6449C161.229 26.5957 162.608 30.323 162.608 34.8267L162.549 36.9816ZM147.757 24.8097C145.582 24.8097 143.777 25.4503 142.341 26.7316C140.904 28.0128 140.011 29.7212 139.662 31.8566H155.735C155.425 29.7212 154.571 28.0128 153.173 26.7316C151.775 25.4503 149.97 24.8097 147.757 24.8097Z",fill:"white"}),_.createElement("path",{d:"M193.817 32.7302V50.0853H186.887V31.973C186.887 27.3916 184.984 25.1009 181.179 25.1009C179.122 25.1009 177.471 25.7609 176.229 27.081C175.025 28.4011 174.424 30.2065 174.424 32.4972V50.0853H167.493V19.8594H173.9V23.8779C174.637 22.519 175.763 21.393 177.277 20.5C178.792 19.607 180.675 19.1605 182.927 19.1605C187.12 19.1605 190.148 20.7524 192.012 23.9361C194.574 20.7524 197.991 19.1605 202.262 19.1605C205.795 19.1605 208.513 20.2671 210.415 22.4801C212.318 24.6544 213.269 27.5275 213.269 31.0995V50.0853H206.338V31.973C206.338 27.3916 204.436 25.1009 200.631 25.1009C198.535 25.1009 196.865 25.7803 195.623 27.1392C194.419 28.4593 193.817 30.323 193.817 32.7302Z",fill:"white"}),_.createElement("path",{d:"M247.735 36.9816H224.731C225.002 39.3888 225.876 41.3107 227.351 42.7472C228.827 44.1449 230.768 44.8438 233.175 44.8438C234.767 44.8438 236.204 44.4555 237.485 43.679C238.766 42.9025 239.678 41.8542 240.222 40.5341H247.211C246.279 43.6014 244.532 46.0862 241.969 47.9887C239.446 49.8523 236.456 50.7842 233 50.7842C228.497 50.7842 224.847 49.2894 222.052 46.2998C219.295 43.3102 217.917 39.5247 217.917 34.9432C217.917 30.4783 219.314 26.7316 222.11 23.7032C224.905 20.6747 228.516 19.1605 232.942 19.1605C237.368 19.1605 240.94 20.6553 243.658 23.6449C246.415 26.5957 247.793 30.323 247.793 34.8267L247.735 36.9816ZM232.942 24.8097C230.768 24.8097 228.963 25.4503 227.526 26.7316C226.089 28.0128 225.196 29.7212 224.847 31.8566H240.921C240.61 29.7212 239.756 28.0128 238.358 26.7316C236.961 25.4503 235.155 24.8097 232.942 24.8097Z",fill:"white"}),_.createElement("path",{d:"M259.085 19.8594V23.8779C259.784 22.5578 260.929 21.4513 262.521 20.5583C264.152 19.6264 266.113 19.1605 268.403 19.1605C271.975 19.1605 274.732 20.2477 276.673 22.4219C278.653 24.5961 279.643 27.4887 279.643 31.0995V50.0853H272.713V31.973C272.713 29.8376 272.208 28.1681 271.199 26.9645C270.228 25.7221 268.733 25.1009 266.714 25.1009C264.501 25.1009 262.754 25.7609 261.473 27.081C260.23 28.4011 259.609 30.2259 259.609 32.5554V50.0853H252.679V19.8594H259.085Z",fill:"white"}),_.createElement("path",{d:"M299.884 43.912V49.9106C299.029 50.1435 297.826 50.26 296.273 50.26C290.371 50.26 287.42 47.2898 287.42 41.3495V25.3921H282.82V19.8594H287.42V11.9972H294.351V19.8594H300V25.3921H294.351V40.6506C294.351 43.019 295.477 44.2032 297.729 44.2032L299.884 43.912Z",fill:"white"})),QZ=_.forwardRef(B9e),H9e="_logo_1gx2r_8",V9e="_container_1gx2r_14",G9e="_content_1gx2r_22",q9e="_formContainer_1gx2r_30",K9e="_authLinks_1gx2r_62",Sa={logo:H9e,container:V9e,content:G9e,formContainer:q9e,authLinks:K9e};function W9e(n){return _.useCallback(async(e,t,r)=>{const i=bw({baseUrl:e}),s=new NP({matrixClient:i,doRequest:async()=>i.login("m.login.password",{identifier:{type:"m.id.user",user:t},password:r}),stateUpdated:()=>{},requestEmailToken:async()=>Promise.resolve({sid:""})}),{user_id:o,access_token:a,device_id:c}=await s.attemptAuth(),l={user_id:o,access_token:a,device_id:c,passwordlessUser:!1};return await(n==null?void 0:n.logout(!0)),[await KZ({baseUrl:e,accessToken:a,userId:o,deviceId:c},!1),l]},[n])}const z9e=()=>{var g,S;const{t:n}=Qe();Oy(n("login_title"));const{client:e,setClient:t}=nh(),r=W9e(e),i=gt.defaultHomeserverUrl(),s=_.useRef(null),o=_.useRef(null),a=ja(),c=di(),[l,u]=_.useState(!1),[h,p]=_.useState(),m=_.useCallback(b=>{if(b.preventDefault(),u(!0),!i||!s.current||!o.current){p(Error("Login parameters are undefined")),u(!1);return}r(i,s.current.value,o.current.value).then(async([R,k])=>{if(!t)return;t({client:R,session:k});const I=c.state;I&&I.from?await a(I.from):await a("/"),jt.instance.eventLogin.track()}).catch(R=>{p(R),u(!1)})},[r,c,a,i,t]);let v=(g=gt.defaultServerName())==null?void 0:g.slice(0,25);return v=(v==null?void 0:v.length)!==((S=gt.defaultServerName())==null?void 0:S.length)?v+"...":v,w.jsx(w.Fragment,{children:w.jsx("div",{className:Sa.container,children:w.jsxs("div",{className:Sa.content,children:[w.jsxs("div",{className:Sa.formContainer,children:[w.jsx(QZ,{width:"auto",height:"auto",className:Sa.logo}),w.jsx("h2",{children:n("log_in")}),w.jsx("h4",{children:n("login_subheading")}),w.jsxs("form",{onSubmit:m,children:[w.jsx(yt,{children:w.jsx(vn,{type:"text",ref:s,placeholder:n("common.username"),label:n("common.username"),autoCorrect:"off",autoCapitalize:"none",prefix:"@",suffix:`:${v}`,"data-testid":"login_username"})}),w.jsx(yt,{children:w.jsx(vn,{type:"password",ref:o,placeholder:n("common.password"),label:n("common.password"),"data-testid":"login_password"})}),h&&w.jsx(yt,{children:w.jsx(Cu,{error:h})}),w.jsx(yt,{children:w.jsx(Mt,{type:"submit",disabled:l,"data-testid":"login_login",children:n(l?"logging_in":"login_title")})})]})]}),w.jsxs("div",{className:Sa.authLinks,children:[w.jsx("p",{children:n("login_auth_links_prompt")}),w.jsx("p",{children:w.jsxs(Ci,{i18nKey:"login_auth_links",children:[w.jsx(Aa,{to:"/register",children:"Create an account"})," Or ",w.jsx(Aa,{to:"/",children:"Access as a guest"})]})})]})]})})})},Y9e=()=>{const{t:n}=Qe();Oy(n("action.register"));const{loading:e,authenticated:t,passwordlessUser:r,client:i,setClient:s}=o4(),o=_.useRef(null),a=ja(),c=di(),[l,u]=_.useState(!1),[h,p]=_.useState(),[m,v]=_.useState(""),[g,S]=_.useState(""),{recaptchaKey:b,register:R}=m4(i),{execute:k,reset:I,recaptchaId:T}=g4(b),C=_.useCallback(P=>{P.preventDefault();const O=new FormData(P.target),D=O.get("userName"),F=O.get("password"),U=O.get("passwordConfirmation");if(F!==U)return;(async()=>{u(!0);const V=await k(),[z,H]=await R(D,F,D,V,r);if(i&&(i!=null&&i.groupCallEventHandler)&&r)for(const J of i.groupCallEventHandler.groupCalls.values()){const Y=J.room.roomId;try{await z.joinRoom(Y)}catch(G){G.errcode==="M_LIMIT_EXCEEDED"?(await Td(G.data.retry_after_ms),await z.joinRoom(Y)):(jw(G),M.error(`Couldn't join room ${Y}`,G))}}s==null||s({client:z,session:H}),jt.instance.eventSignup.cacheSignupEnd(new Date)})().then(async()=>{var V,z;(V=c.state)!=null&&V.from?await a((z=c.state)==null?void 0:z.from):await a("/")}).catch(V=>{p(V),u(!1),I()})},[R,c,a,r,I,k,i,s]);return _.useEffect(()=>{var P,O;m&&g&&m!==g?(P=o.current)==null||P.setCustomValidity(n("register.passwords_must_match")):(O=o.current)==null||O.setCustomValidity("")},[m,g,n]),_.useEffect(()=>{var P;!e&&t&&!r&&!l&&((P=a("/"))==null||P.catch(O=>{M.error("Failed to navigate to /",O)}))},[e,a,t,r,l]),e?w.jsx(_E,{}):(jt.instance.eventSignup.cacheSignupStart(new Date),w.jsx(w.Fragment,{children:w.jsx("div",{className:Sa.container,children:w.jsxs("div",{className:Sa.content,children:[w.jsxs("div",{className:Sa.formContainer,children:[w.jsx(QZ,{width:"auto",height:"auto",className:Sa.logo}),w.jsx("h2",{children:n("register_heading")}),w.jsxs("form",{onSubmit:C,children:[w.jsx(yt,{children:w.jsx(vn,{type:"text",name:"userName",placeholder:n("common.username"),label:n("common.username"),autoCorrect:"off",autoCapitalize:"none",prefix:"@",suffix:`:${gt.defaultServerName()}`,"data-testid":"register_username"})}),w.jsx(yt,{children:w.jsx(vn,{required:!0,name:"password",type:"password",onChange:P=>v(P.target.value),value:m,placeholder:n("common.password"),label:n("common.password"),"data-testid":"register_password"})}),w.jsx(yt,{children:w.jsx(vn,{required:!0,type:"password",name:"passwordConfirmation",onChange:P=>S(P.target.value),value:g,placeholder:n("register_confirm_password_label"),label:n("register_confirm_password_label"),ref:o,"data-testid":"register_confirm_password"})}),w.jsx(Xt,{size:"sm",children:w.jsxs(Ci,{i18nKey:"recaptcha_caption",children:["This site is protected by ReCAPTCHA and the Google"," ",w.jsx(bd,{href:"https://www.google.com/policies/privacy/",children:"Privacy Policy"})," ","and"," ",w.jsx(bd,{href:"https://policies.google.com/terms",children:"Terms of Service"})," ","apply.",w.jsx("br",{}),'By clicking "Register", you agree to our'," ",w.jsx(bd,{href:gt.get().eula,children:"End User Licensing Agreement (EULA)"})]})}),h&&w.jsx(yt,{children:w.jsx(Cu,{error:h})}),w.jsx(yt,{children:w.jsx(Mt,{type:"submit",disabled:l,"data-testid":"register_register",children:n(l?"register.registering":"action.register")})}),w.jsx("div",{id:T})]})]}),w.jsx("div",{className:Sa.authLinks,children:w.jsxs(Ci,{i18nKey:"register_auth_links",children:[w.jsx("p",{children:"Already have an account?"}),w.jsxs("p",{children:[w.jsx(Aa,{to:"/login",children:"Log in"})," Or ",w.jsx(Aa,{to:"/",children:"Access as a guest"})]})]})})]})})}))},X9e="_form_1wfyo_8",J9e="_headline_1wfyo_18",Z9e="_container_1wfyo_37",Q9e="_main_1wfyo_45",e7e="_footer_1wfyo_62",og={form:X9e,headline:J9e,container:Z9e,main:Q9e,footer:e7e};function eQ(){const{setClient:n}=nh(),{privacyPolicyUrl:e,recaptchaKey:t,register:r}=m4(),{execute:i,reset:s,recaptchaId:o}=g4(t),a=_.useCallback(async c=>{if(!n)throw new Error("No client context");if(Je)throw new Error("Registration was skipped: We should never try to register password-less user in embedded mode.");try{const l=await i(),u=JZ(),[h,p]=await r(u,Es(16),c,l,!0);n({client:h,session:p})}catch(l){throw s(),l}},[i,s,r,n]);return{privacyPolicyUrl:e,registerPasswordlessUser:a,recaptchaId:o}}const t7e=()=>{const[n,e]=_.useState(!1),[t,r]=_.useState(),{registerPasswordlessUser:i,recaptchaId:s}=eQ(),o=_.useCallback(l=>{l.preventDefault(),e(!0);const h=new FormData(l.target).get("displayName");i(typeof h=="string"?h:"").catch(m=>{M.error("Failed to register passwordless user",l),e(!1),r(m)})},[i]),{t:a}=Qe(),c=di();return w.jsxs(w.Fragment,{children:[w.jsxs(wu,{children:[w.jsx(Jd,{children:w.jsx(Dd,{})}),w.jsx(Zd,{children:w.jsx(f4,{preventNavigation:!0})})]}),w.jsxs("div",{className:og.container,children:[w.jsxs("main",{className:og.main,children:[w.jsx(Su,{size:"xl",weight:"semibold",className:og.headline,children:a("lobby.join_as_guest")}),w.jsxs(CE,{className:og.form,onSubmit:o,children:[w.jsx(yt,{children:w.jsx(vn,{id:"displayName",name:"displayName",label:a("common.display_name"),placeholder:a("common.display_name"),"data-testid":"joincall_displayName",type:"text",required:!0,autoComplete:"off"})}),w.jsx(Xt,{size:"sm",children:w.jsxs(Ci,{i18nKey:"room_auth_view_eula_caption",children:['By clicking "Join call now", you agree to our'," ",w.jsx(bd,{href:gt.get().eula,children:"End User Licensing Agreement (EULA)"})]})}),t&&w.jsx(yt,{children:w.jsx(Cu,{error:t})}),w.jsx(Mt,{type:"submit",size:"lg",disabled:n,"data-testid":"joincall_joincall",children:a(n?"common.loading":"room_auth_view_continue_button")}),w.jsx("div",{id:s})]})]}),w.jsx(Xt,{className:og.footer,children:w.jsxs(Ci,{i18nKey:"unauthenticated_view_body",children:["Not registered yet?"," ",w.jsx(Aa,{to:"/register",state:{from:c},children:"Create an account"})]})})]})]})};var wg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function tQ(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var nQ={exports:{}};(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(wg,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(g,S){var b=g[S];if(typeof b.bind=="function")return b.bind(g);try{return Function.prototype.bind.call(b,g)}catch{return function(){return Function.prototype.apply.apply(b,[g,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&r?c:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function u(){for(var g=this.getLevel(),S=0;S<i.length;S++){var b=i[S];this[b]=S<g?e:this.methodFactory(b,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function h(g){return function(){typeof console!==t&&(u.call(this),this[g].apply(this,arguments))}}function p(g,S,b){return l(g)||h.apply(this,arguments)}function m(g,S){var b=this,R,k,I,T="loglevel";typeof g=="string"?T+=":"+g:typeof g=="symbol"&&(T=void 0);function C(U){var B=(i[U]||"silent").toUpperCase();if(!(typeof window===t||!T)){try{window.localStorage[T]=B;return}catch{}try{window.document.cookie=encodeURIComponent(T)+"="+B+";"}catch{}}}function P(){var U;if(!(typeof window===t||!T)){try{U=window.localStorage[T]}catch{}if(typeof U===t)try{var B=window.document.cookie,V=encodeURIComponent(T),z=B.indexOf(V+"=");z!==-1&&(U=/^([^;]+)/.exec(B.slice(z+V.length+1))[1])}catch{}return b.levels[U]===void 0&&(U=void 0),U}}function O(){if(!(typeof window===t||!T)){try{window.localStorage.removeItem(T)}catch{}try{window.document.cookie=encodeURIComponent(T)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function D(U){var B=U;if(typeof B=="string"&&b.levels[B.toUpperCase()]!==void 0&&(B=b.levels[B.toUpperCase()]),typeof B=="number"&&B>=0&&B<=b.levels.SILENT)return B;throw new TypeError("log.setLevel() called with invalid level: "+U)}b.name=g,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||p,b.getLevel=function(){return I??k??R},b.setLevel=function(U,B){return I=D(U),B!==!1&&C(I),u.call(b)},b.setDefaultLevel=function(U){k=D(U),P()||b.setLevel(U,!1)},b.resetLevel=function(){I=null,O(),u.call(b)},b.enableAll=function(U){b.setLevel(b.levels.TRACE,U)},b.disableAll=function(U){b.setLevel(b.levels.SILENT,U)},b.rebuild=function(){if(o!==b&&(R=D(o.getLevel())),u.call(b),o===b)for(var U in s)s[U].rebuild()},R=D(o?o.getLevel():"WARN");var F=P();F!=null&&(I=D(F)),u.call(b)}o=new m,o.getLogger=function(g){if(typeof g!="symbol"&&typeof g!="string"||g==="")throw new TypeError("You must supply a name when creating a logger.");var S=s[g];return S||(S=s[g]=new m(g,o.methodFactory)),S};var v=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})})(nQ);var n7e=nQ.exports;const r7e=tQ(n7e);var Mx=function(n,e){return Mx=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])},Mx(n,e)};function qc(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Mx(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function i7e(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((r=r.apply(n,[])).next())})}function rQ(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(r=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],i=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function lp(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function US(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return s}function jS(n,e,t){if(arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function $f(n){return this instanceof $f?(this.v=n,this):new $f(n)}function s7e(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),i,s=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),i[Symbol.asyncIterator]=function(){return this},i;function o(m){return function(v){return Promise.resolve(v).then(m,h)}}function a(m,v){r[m]&&(i[m]=function(g){return new Promise(function(S,b){s.push([m,g,S,b])>1||c(m,g)})},v&&(i[m]=v(i[m])))}function c(m,v){try{l(r[m](v))}catch(g){p(s[0][3],g)}}function l(m){m.value instanceof $f?Promise.resolve(m.value.v).then(u,h):p(s[0][2],m)}function u(m){c("next",m)}function h(m){c("throw",m)}function p(m,v){m(v),s.shift(),s.length&&c(s[0][0],s[0][1])}}function o7e(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof lp=="function"?lp(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(o){return new Promise(function(a,c){o=n[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function vr(n){return typeof n=="function"}function v4(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var V2=v4(function(n){return function(e){n(this),this.message=e?e.length+` errors occurred during unsubscription:
|
|
209
209
|
`+e.map(function(t,r){return r+1+") "+t.toString()}).join(`
|
|
210
210
|
`):"",this.name="UnsubscriptionError",this.errors=e}});function $S(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var My=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=lp(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(g){e={error:g}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else o.remove(this);var u=this.initialTeardown;if(vr(u))try{u()}catch(g){s=g instanceof V2?g.errors:[g]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var p=lp(h),m=p.next();!m.done;m=p.next()){var v=m.value;try{dF(v)}catch(g){s=s??[],g instanceof V2?s=jS(jS([],US(s)),US(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{m&&!m.done&&(i=p.return)&&i.call(p)}finally{if(r)throw r.error}}}if(s)throw new V2(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)dF(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&$S(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&$S(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),iQ=My.EMPTY;function sQ(n){return n instanceof My||n&&"closed"in n&&vr(n.remove)&&vr(n.add)&&vr(n.unsubscribe)}function dF(n){vr(n)?n():n.unsubscribe()}var a7e={Promise:void 0},c7e={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,jS([n,e],US(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function oQ(n){c7e.setTimeout(function(){throw n})}function hF(){}function hb(n){n()}var y4=function(n){qc(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,sQ(t)&&t.add(r)):r.destination=d7e,r}return e.create=function(t,r,i){return new Nx(t,r,i)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(My),l7e=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Q1(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Q1(r)}else Q1(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Q1(t)}},n}(),Nx=function(n){qc(e,n);function e(t,r,i){var s=n.call(this)||this,o;return vr(t)||!t?o={next:t??void 0,error:r??void 0,complete:i??void 0}:o=t,s.destination=new l7e(o),s}return e}(y4);function Q1(n){oQ(n)}function u7e(n){throw n}var d7e={closed:!0,next:hF,error:u7e,complete:hF},_4=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function aQ(n){return n}function h7e(n){return n.length===0?aQ:n.length===1?n[0]:function(e){return n.reduce(function(t,r){return r(t)},e)}}var ks=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var i=this,s=p7e(e)?e:new Nx(e,t,r);return hb(function(){var o=i,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?i._subscribe(s):i._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=fF(t),new t(function(i,s){var o=new Nx({next:function(a){try{e(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[_4]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return h7e(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=fF(e),new e(function(r,i){var s;t.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function fF(n){var e;return(e=n??a7e.Promise)!==null&&e!==void 0?e:Promise}function f7e(n){return n&&vr(n.next)&&vr(n.error)&&vr(n.complete)}function p7e(n){return n&&n instanceof y4||f7e(n)&&sQ(n)}function m7e(n){return vr(n==null?void 0:n.lift)}function Ny(n){return function(e){if(m7e(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function BS(n,e,t,r,i){return new g7e(n,e,t,r,i)}var g7e=function(n){qc(e,n);function e(t,r,i,s,o,a){var c=n.call(this,t)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(l){try{r(l)}catch(u){t.error(u)}}:n.prototype._next,c._error=s?function(l){try{s(l)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=i?function(){try{i()}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._complete,c}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(y4),v7e=v4(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),cQ=function(n){qc(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new pF(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new v7e},e.prototype.next=function(t){var r=this;hb(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=lp(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(t)}}catch(l){i={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(t){var r=this;hb(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var i=r.observers;i.length;)i.shift().error(t)}})},e.prototype.complete=function(){var t=this;hb(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?iQ:(this.currentObservers=null,a.push(t),new My(function(){r.currentObservers=null,$S(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new ks;return t.source=this,t},e.create=function(t,r){return new pF(t,r)},e}(ks),pF=function(n){qc(e,n);function e(t,r){var i=n.call(this)||this;return i.destination=t,i.source=r,i}return e.prototype.next=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,t)},e.prototype.error=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&i!==void 0?i:iQ},e}(cQ);(function(n){qc(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,i=t.thrownError,s=t._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e})(cQ);var y7e={now:function(){return Date.now()}},_7e=function(n){qc(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(My),mF={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setInterval.apply(void 0,jS([n,e],US(t)))},clearInterval:function(n){return clearInterval(n)},delegate:void 0},b7e=function(n){qc(e,n);function e(t,r){var i=n.call(this,t,r)||this;return i.scheduler=t,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(t,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,r)),this.pending=!0,this.delay=r,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(o,this.id,r),this},e.prototype.requestAsyncId=function(t,r,i){return i===void 0&&(i=0),mF.setInterval(t.flush.bind(t,this),i)},e.prototype.recycleAsyncId=function(t,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&mF.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var i=!1,s;try{this.work(t)}catch(o){i=!0,s=o||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,i=t.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,$S(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(_7e),gF=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=y7e.now,n}(),S7e=function(n){qc(e,n);function e(t,r){r===void 0&&(r=gF.now);var i=n.call(this,t,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,i){for(;t=r.shift();)t.unsubscribe();throw i}},e}(gF);new S7e(b7e);function w7e(n){return n&&vr(n.schedule)}function E7e(n){return n[n.length-1]}function lQ(n){return w7e(E7e(n))?n.pop():void 0}var uQ=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function dQ(n){return vr(n==null?void 0:n.then)}function hQ(n){return vr(n[_4])}function fQ(n){return Symbol.asyncIterator&&vr(n==null?void 0:n[Symbol.asyncIterator])}function pQ(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function C7e(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var mQ=C7e();function gQ(n){return vr(n==null?void 0:n[mQ])}function vQ(n){return s7e(this,arguments,function(){var e,t,r,i;return rQ(this,function(s){switch(s.label){case 0:e=n.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,$f(e.read())];case 3:return t=s.sent(),r=t.value,i=t.done,i?[4,$f(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,$f(r)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return e.releaseLock(),[7];case 10:return[2]}})})}function yQ(n){return vr(n==null?void 0:n.getReader)}function Dy(n){if(n instanceof ks)return n;if(n!=null){if(hQ(n))return T7e(n);if(uQ(n))return I7e(n);if(dQ(n))return R7e(n);if(fQ(n))return _Q(n);if(gQ(n))return k7e(n);if(yQ(n))return x7e(n)}throw pQ(n)}function T7e(n){return new ks(function(e){var t=n[_4]();if(vr(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function I7e(n){return new ks(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function R7e(n){return new ks(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,oQ)})}function k7e(n){return new ks(function(e){var t,r;try{for(var i=lp(n),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){t={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e.complete()})}function _Q(n){return new ks(function(e){P7e(n,e).catch(function(t){return e.error(t)})})}function x7e(n){return _Q(vQ(n))}function P7e(n,e){var t,r,i,s;return i7e(this,void 0,void 0,function(){var o,a;return rQ(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),t=o7e(n),c.label=1;case 1:return[4,t.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),i={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Sd(n,e,t,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function bQ(n,e){return e===void 0&&(e=0),Ny(function(t,r){t.subscribe(BS(r,function(i){return Sd(r,n,function(){return r.next(i)},e)},function(){return Sd(r,n,function(){return r.complete()},e)},function(i){return Sd(r,n,function(){return r.error(i)},e)}))})}function SQ(n,e){return e===void 0&&(e=0),Ny(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function L7e(n,e){return Dy(n).pipe(SQ(e),bQ(e))}function A7e(n,e){return Dy(n).pipe(SQ(e),bQ(e))}function O7e(n,e){return new ks(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function M7e(n,e){return new ks(function(t){var r;return Sd(t,e,function(){r=n[mQ](),Sd(t,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){t.error(a);return}o?t.complete():t.next(s)},0,!0)}),function(){return vr(r==null?void 0:r.return)&&r.return()}})}function wQ(n,e){if(!n)throw new Error("Iterable cannot be null");return new ks(function(t){Sd(t,e,function(){var r=n[Symbol.asyncIterator]();Sd(t,e,function(){r.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}function N7e(n,e){return wQ(vQ(n),e)}function D7e(n,e){if(n!=null){if(hQ(n))return L7e(n,e);if(uQ(n))return O7e(n,e);if(dQ(n))return A7e(n,e);if(fQ(n))return wQ(n,e);if(gQ(n))return M7e(n,e);if(yQ(n))return N7e(n,e)}throw pQ(n)}function F7e(n,e){return e?D7e(n,e):Dy(n)}v4(function(n){return function(e){e===void 0&&(e=null),n(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=e}});function TE(n,e){return Ny(function(t,r){var i=0;t.subscribe(BS(r,function(s){r.next(n.call(e,s,i++))}))})}function U7e(n,e,t,r,i,s,o,a){var c=[],l=0,u=0,h=!1,p=function(){h&&!c.length&&!l&&e.complete()},m=function(g){return l<r?v(g):c.push(g)},v=function(g){l++;var S=!1;Dy(t(g,u++)).subscribe(BS(e,function(b){e.next(b)},function(){S=!0},void 0,function(){if(S)try{l--;for(var b=function(){var R=c.shift();o||v(R)};c.length&&l<r;)b();p()}catch(R){e.error(R)}}))};return n.subscribe(BS(e,m,function(){h=!0,p()})),function(){}}function EQ(n,e,t){return t===void 0&&(t=1/0),vr(e)?EQ(function(r,i){return TE(function(s,o){return e(r,s,i,o)})(Dy(n(r,i)))},t):(typeof e=="number"&&(t=e),Ny(function(r,i){return U7e(r,i,n,t)}))}function j7e(n){return EQ(aQ,n)}function $7e(){return j7e(1)}function vF(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return $7e()(F7e(n,lQ(n)))}function IE(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=lQ(n);return Ny(function(r,i){(t?vF(n,r,t):vF(n,r)).subscribe(i)})}var B7e="lk";function b4(n){return typeof n>"u"?!1:H7e(n)||V7e(n)}function H7e(n){var e;return n?n.hasOwnProperty("participant")&&n.hasOwnProperty("source")&&n.hasOwnProperty("track")&&typeof((e=n.publication)==null?void 0:e.track)<"u":!1}function V7e(n){return n?n.hasOwnProperty("participant")&&n.hasOwnProperty("source")&&n.hasOwnProperty("publication")&&typeof n.publication<"u":!1}function G7e(n){return n?n.hasOwnProperty("participant")&&n.hasOwnProperty("source")&&typeof n.publication>"u":!1}function q7e(n){if(typeof n=="string"||typeof n=="number")return`${n}`;if(G7e(n))return`${n.participant.identity}_${n.source}_placeholder`;if(b4(n))return`${n.participant.identity}_${n.publication.source}_${n.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${n}`)}var K7e=[he.ConnectionStateChanged,he.RoomMetadataChanged,he.ActiveSpeakersChanged,he.ConnectionQualityChanged,he.ParticipantConnected,he.ParticipantDisconnected,he.ParticipantPermissionsChanged,he.ParticipantMetadataChanged,he.ParticipantNameChanged,he.ParticipantAttributesChanged,he.TrackMuted,he.TrackUnmuted,he.TrackPublished,he.TrackUnpublished,he.TrackStreamStateChanged,he.TrackSubscriptionFailed,he.TrackSubscriptionPermissionChanged,he.TrackSubscriptionStatusChanged],W7e=[...K7e,he.LocalTrackPublished,he.LocalTrackUnpublished];ue.TrackPublished,ue.TrackUnpublished,ue.TrackMuted,ue.TrackUnmuted,ue.TrackStreamStateChanged,ue.TrackSubscribed,ue.TrackUnsubscribed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionFailed,ue.LocalTrackPublished,ue.LocalTrackUnpublished;var z7e=[ue.ConnectionQualityChanged,ue.IsSpeakingChanged,ue.ParticipantMetadataChanged,ue.ParticipantPermissionsChanged,ue.TrackMuted,ue.TrackUnmuted,ue.TrackPublished,ue.TrackUnpublished,ue.TrackStreamStateChanged,ue.TrackSubscriptionFailed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionStatusChanged];[...z7e,ue.LocalTrackPublished,ue.LocalTrackUnpublished];var fu=r7e.getLogger("lk-components-js");fu.setDefaultLevel("WARN");function CQ(n){return typeof n=="object"}function TQ(n){return Array.isArray(n)&&n.filter(CQ).length>0}function Y7e(n){return`${B7e}-${n}`}function X7e(n){const e=Dx(n),t=IQ(n.participant).pipe(TE(()=>Dx(n)),IE(e));return{className:Y7e(n.source===pe.Source.Camera||n.source===pe.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:t}}function Dx(n){if(b4(n))return n.publication;{const{source:e,name:t,participant:r}=n;if(e&&t)return r.getTrackPublications().find(i=>i.source===e&&i.trackName===t);if(t)return r.getTrackPublicationByName(t);if(e)return r.getTrackPublication(e);throw new Error("At least one of source and name needs to be defined")}}function J7e(n,...e){return new ks(t=>{const r=()=>{t.next(n)};return e.forEach(i=>{n.on(i,r)}),()=>{e.forEach(i=>{n.off(i,r)})}}).pipe(IE(n))}function Z7e(n,...e){return new ks(t=>{const r=()=>{t.next(n)};return e.forEach(i=>{n.on(i,r)}),()=>{e.forEach(i=>{n.off(i,r)})}}).pipe(IE(n))}function IQ(n){return Z7e(n,ue.TrackMuted,ue.TrackUnmuted,ue.ParticipantPermissionsChanged,ue.TrackPublished,ue.TrackUnpublished,ue.LocalTrackPublished,ue.LocalTrackUnpublished,ue.MediaDevicesError,ue.TrackSubscriptionStatusChanged).pipe(TE(e=>{const{isMicrophoneEnabled:t,isCameraEnabled:r,isScreenShareEnabled:i}=e,s=e.getTrackPublication(pe.Source.Microphone),o=e.getTrackPublication(pe.Source.Camera);return{isCameraEnabled:r,isMicrophoneEnabled:t,isScreenShareEnabled:i,cameraTrack:o,microphoneTrack:s,participant:e}}))}new TextEncoder;new TextDecoder;function yF(n,e,t=!0){const r=[n.localParticipant,...Array.from(n.remoteParticipants.values())],i=[];return r.forEach(s=>{e.forEach(o=>{const a=Array.from(s.trackPublications.values()).filter(c=>c.source===o&&(!t||c.track)).map(c=>({participant:s,publication:c,source:c.source}));i.push(...a)})}),{trackReferences:i,participants:r}}function Q7e(n,e,t){var r,i;const s=(r=t.additionalRoomEvents)!=null?r:W7e,o=(i=t.onlySubscribed)!=null?i:!0,a=Array.from(new Set([he.ParticipantConnected,he.ParticipantDisconnected,he.ConnectionStateChanged,he.LocalTrackPublished,he.LocalTrackUnpublished,he.TrackPublished,he.TrackUnpublished,he.TrackSubscriptionStatusChanged,...s]).values());return J7e(n,...a).pipe(TE(c=>{const l=yF(c,e,o);return fu.debug(`TrackReference[] was updated. (length ${l.trackReferences.length})`,l),l}),IE(yF(n,e,o)))}_.createContext(void 0);const eDe=_.createContext(void 0);function tDe(){return _.useContext(eDe)}function RQ(n){const e=tDe(),t=n??e;if(!t)throw new Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return t}_.createContext(void 0);const kQ=_.createContext(void 0);function nDe(){return _.useContext(kQ)}function xQ(n){const e=nDe(),t=n??e;if(!t)throw new Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return t}_.createContext(void 0);function PQ(n){var e,t,r="";if(typeof n=="string"||typeof n=="number")r+=n;else if(typeof n=="object")if(Array.isArray(n)){var i=n.length;for(e=0;e<i;e++)n[e]&&(t=PQ(n[e]))&&(r&&(r+=" "),r+=t)}else for(t in n)n[t]&&(r&&(r+=" "),r+=t);return r}function rDe(){for(var n,e,t=0,r="",i=arguments.length;t<i;t++)(n=arguments[t])&&(e=PQ(n))&&(r&&(r+=" "),r+=e);return r}function iDe(...n){return(...e)=>{for(const t of n)if(typeof t=="function")try{t(...e)}catch(r){console.error(r)}}}function sDe(...n){const e={...n[0]};for(let t=1;t<n.length;t++){const r=n[t];for(const i in r){const s=e[i],o=r[i];typeof s=="function"&&typeof o=="function"&&i[0]==="o"&&i[1]==="n"&&i.charCodeAt(2)>=65&&i.charCodeAt(2)<=90?e[i]=iDe(s,o):(i==="className"||i==="UNSAFE_className")&&typeof s=="string"&&typeof o=="string"?e[i]=rDe(s,o):e[i]=o!==void 0?o:s}}return e}function oDe(n){return n!==void 0}function aDe(...n){return sDe(...n.filter(oDe))}function cDe(n,e){return n==="processor"&&e&&typeof e=="object"&&"name"in e?e.name:n==="e2ee"&&e?"e2ee-enabled":e}function lDe(n={}){const e=xQ(n.room),[t,r]=_.useState(e.localParticipant),[i,s]=_.useState(t.isMicrophoneEnabled),[o,a]=_.useState(t.isMicrophoneEnabled),[c,l]=_.useState(t.lastMicrophoneError),[u,h]=_.useState(t.lastCameraError),[p,m]=_.useState(t.isMicrophoneEnabled),[v,g]=_.useState(void 0),[S,b]=_.useState(void 0),R=k=>{a(k.isCameraEnabled),s(k.isMicrophoneEnabled),m(k.isScreenShareEnabled),b(k.cameraTrack),g(k.microphoneTrack),l(k.participant.lastMicrophoneError),h(k.participant.lastCameraError),r(k.participant)};return _.useEffect(()=>{const k=IQ(e.localParticipant).subscribe(R);return()=>k.unsubscribe()},[e]),{isMicrophoneEnabled:i,isScreenShareEnabled:p,isCameraEnabled:o,microphoneTrack:v,cameraTrack:S,lastMicrophoneError:c,lastCameraError:u,localParticipant:t}}function uDe(n=[pe.Source.Camera,pe.Source.Microphone,pe.Source.ScreenShare,pe.Source.ScreenShareAudio,pe.Source.Unknown],e={}){const t=xQ(e.room),[r,i]=_.useState([]),[s,o]=_.useState([]),a=_.useMemo(()=>n.map(c=>CQ(c)?c.source:c),[JSON.stringify(n)]);return _.useEffect(()=>{const c=Q7e(t,a,{additionalRoomEvents:e.updateOnlyOn,onlySubscribed:e.onlySubscribed}).subscribe(({trackReferences:l,participants:u})=>{fu.debug("setting track bundles",l,u),i(l),o(u)});return()=>c.unsubscribe()},[t,JSON.stringify(e.onlySubscribed),JSON.stringify(e.updateOnlyOn),JSON.stringify(n)]),_.useMemo(()=>{if(TQ(n)){const c=hDe(n,s),l=Array.from(r);return s.forEach(u=>{c.has(u.identity)&&(c.get(u.identity)??[]).forEach(h=>{if(r.find(({participant:m,publication:v})=>u.identity===m.identity&&v.source===h))return;fu.debug(`Add ${h} placeholder for participant ${u.identity}.`);const p={participant:u,source:h};l.push(p)})}),l}else return r},[r,s,n])}function dDe(n,e){const t=new Set(n);for(const r of e)t.delete(r);return t}function hDe(n,e){const t=new Map;if(TQ(n)){const r=n.filter(i=>i.withPlaceholder).map(i=>i.source);e.forEach(i=>{const s=i.getTrackPublications().map(a=>{var c;return(c=a.track)==null?void 0:c.source}).filter(a=>a!==void 0),o=Array.from(dDe(new Set(r),new Set(s)));o.length>0&&t.set(i.identity,o)})}return t}function LQ(n,e={}){const[t,r]=_.useState(Dx(n)),[i,s]=_.useState(t==null?void 0:t.isMuted),[o,a]=_.useState(t==null?void 0:t.isSubscribed),[c,l]=_.useState(t==null?void 0:t.track),[u,h]=_.useState("landscape"),p=_.useRef(),{className:m,trackObserver:v}=_.useMemo(()=>X7e(n),[n.participant.sid??n.participant.identity,n.source,b4(n)&&n.publication.trackSid]);return _.useEffect(()=>{const g=v.subscribe(S=>{fu.debug("update track",S),r(S),s(S==null?void 0:S.isMuted),a(S==null?void 0:S.isSubscribed),l(S==null?void 0:S.track)});return()=>g==null?void 0:g.unsubscribe()},[v]),_.useEffect(()=>{var g,S;return c&&(p.current&&c.detach(p.current),(g=e.element)!=null&&g.current&&!(n.participant.isLocal&&(c==null?void 0:c.kind)==="audio")&&c.attach(e.element.current)),p.current=(S=e.element)==null?void 0:S.current,()=>{p.current&&(c==null||c.detach(p.current))}},[c,e.element]),_.useEffect(()=>{var g,S;if(typeof((g=t==null?void 0:t.dimensions)==null?void 0:g.width)=="number"&&typeof((S=t==null?void 0:t.dimensions)==null?void 0:S.height)=="number"){const b=t.dimensions.width>t.dimensions.height?"landscape":"portrait";h(b)}},[t]),{publication:t,isMuted:i,isSubscribed:o,track:c,elementProps:aDe(e.props,{className:m,"data-lk-local-participant":n.participant.isLocal,"data-lk-source":t==null?void 0:t.source,...(t==null?void 0:t.kind)==="video"&&{"data-lk-orientation":u}})}}var fDe="Expected a function",_F=NaN,pDe="[object Symbol]",mDe=/^\s+|\s+$/g,gDe=/^[-+]0x[0-9a-f]+$/i,vDe=/^0b[01]+$/i,yDe=/^0o[0-7]+$/i,_De=parseInt,bDe=typeof wg=="object"&&wg&&wg.Object===Object&&wg,SDe=typeof self=="object"&&self&&self.Object===Object&&self,wDe=bDe||SDe||Function("return this")(),EDe=Object.prototype,CDe=EDe.toString,TDe=Math.max,IDe=Math.min,G2=function(){return wDe.Date.now()};function RDe(n,e,t){var r,i,s,o,a,c,l=0,u=!1,h=!1,p=!0;if(typeof n!="function")throw new TypeError(fDe);e=bF(e)||0,Fx(t)&&(u=!!t.leading,h="maxWait"in t,s=h?TDe(bF(t.maxWait)||0,e):s,p="trailing"in t?!!t.trailing:p);function m(C){var P=r,O=i;return r=i=void 0,l=C,o=n.apply(O,P),o}function v(C){return l=C,a=setTimeout(b,e),u?m(C):o}function g(C){var P=C-c,O=C-l,D=e-P;return h?IDe(D,s-O):D}function S(C){var P=C-c,O=C-l;return c===void 0||P>=e||P<0||h&&O>=s}function b(){var C=G2();if(S(C))return R(C);a=setTimeout(b,g(C))}function R(C){return a=void 0,p&&r?m(C):(r=i=void 0,o)}function k(){a!==void 0&&clearTimeout(a),l=0,r=c=i=a=void 0}function I(){return a===void 0?o:R(G2())}function T(){var C=G2(),P=S(C);if(r=arguments,i=this,c=C,P){if(a===void 0)return v(c);if(h)return a=setTimeout(b,e),m(c)}return a===void 0&&(a=setTimeout(b,e)),o}return T.cancel=k,T.flush=I,T}function Fx(n){var e=typeof n;return!!n&&(e=="object"||e=="function")}function kDe(n){return!!n&&typeof n=="object"}function xDe(n){return typeof n=="symbol"||kDe(n)&&CDe.call(n)==pDe}function bF(n){if(typeof n=="number")return n;if(xDe(n))return _F;if(Fx(n)){var e=typeof n.valueOf=="function"?n.valueOf():n;n=Fx(e)?e+"":e}if(typeof n!="string")return n===0?n:+n;n=n.replace(mDe,"");var t=vDe.test(n);return t||yDe.test(n)?_De(n.slice(2),t?2:8):gDe.test(n)?_F:+n}var PDe=RDe;const SF=tQ(PDe);function LDe(n){const e=_.useRef(n);e.current=n,_.useEffect(()=>()=>{e.current()},[])}function ADe(n,e=500,t){const r=_.useRef();LDe(()=>{r.current&&r.current.cancel()});const i=_.useMemo(()=>{const s=SF(n,e,t),o=(...a)=>s(...a);return o.cancel=()=>{s.cancel()},o.isPending=()=>!!r.current,o.flush=()=>s.flush(),o},[n,e,t]);return _.useEffect(()=>{r.current=SF(n,e,t)},[n,e,t]),i}function ODe(n,e,t){const r=(l,u)=>l===u,i=n instanceof Function?n():n,[s,o]=_.useState(i),a=_.useRef(i),c=ADe(o,e,t);return r(a.current,i)||(c(i),a.current=i),[s,c]}function MDe({threshold:n=0,root:e=null,rootMargin:t="0%",freezeOnceVisible:r=!1,initialIsIntersecting:i=!1,onChange:s}={}){var o;const[a,c]=_.useState(null),[l,u]=_.useState(()=>({isIntersecting:i,entry:void 0})),h=_.useRef();h.current=s;const p=((o=l.entry)==null?void 0:o.isIntersecting)&&r;_.useEffect(()=>{if(!a||!("IntersectionObserver"in window)||p)return;const g=new IntersectionObserver(S=>{const b=Array.isArray(g.thresholds)?g.thresholds:[g.thresholds];S.forEach(R=>{const k=R.isIntersecting&&b.some(I=>R.intersectionRatio>=I);u({isIntersecting:k,entry:R}),h.current&&h.current(k,R)})},{threshold:n,root:e,rootMargin:t});return g.observe(a),()=>{g.disconnect()}},[a,JSON.stringify(n),e,t,p,r]);const m=_.useRef(null);_.useEffect(()=>{var g;!a&&(g=l.entry)!=null&&g.target&&!r&&!p&&m.current!==l.entry.target&&(m.current=l.entry.target,u({isIntersecting:i,entry:void 0}))},[a,l.entry,r,p,i]);const v=[c,!!l.isIntersecting,l.entry];return v.ref=v[0],v.isIntersecting=v[1],v.entry=v[2],v}const NDe=_.forwardRef(function({onTrackClick:n,onClick:e,onSubscriptionStatusChanged:t,trackRef:r,manageSubscription:i,...s},o){const a=RQ(r),c=_.useRef(null);_.useImperativeHandle(o,()=>c.current);const l=MDe({root:c.current}),[u]=ODe(l,3e3);_.useEffect(()=>{i&&a.publication instanceof zb&&(u==null?void 0:u.isIntersecting)===!1&&(l==null?void 0:l.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[u,a,i]),_.useEffect(()=>{i&&a.publication instanceof zb&&(l==null?void 0:l.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[l,a,i]);const{elementProps:h,publication:p,isSubscribed:m}=LQ(a,{element:c,props:s});_.useEffect(()=>{t==null||t(!!m)},[m,t]);const v=g=>{e==null||e(g),n==null||n({participant:a==null?void 0:a.participant,track:p})};return _.createElement("video",{ref:c,...h,muted:!0,onClick:v})}),DDe=_.forwardRef(function({trackRef:n,onSubscriptionStatusChanged:e,volume:t,...r},i){const s=RQ(n),o=_.useRef(null);_.useImperativeHandle(i,()=>o.current);const{elementProps:a,isSubscribed:c,track:l,publication:u}=LQ(s,{element:o,props:r});return _.useEffect(()=>{e==null||e(!!c)},[c,e]),_.useEffect(()=>{l===void 0||t===void 0||(l instanceof gV?l.setVolume(t):fu.warn("Volume can only be set on remote audio tracks."))},[t,l]),_.useEffect(()=>{u===void 0||r.muted===void 0||(u instanceof zb?u.setEnabled(!r.muted):fu.warn("Can only call setEnabled on remote track publications."))},[r.muted,u,l]),_.createElement("audio",{ref:o,...a})});function FDe({volume:n,muted:e}){const t=uDe([pe.Source.Microphone,pe.Source.ScreenShareAudio,pe.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0}).filter(r=>!r.participant.isLocal&&r.publication.kind===pe.Kind.Audio);return _.createElement("div",{style:{display:"none"}},t.map(r=>_.createElement(DDe,{key:q7e(r),trackRef:r,volume:n,muted:e})))}function UDe(n,e){const[t,r]=_.useState(),i=_.useMemo(()=>new Wi,[]);return _.useEffect(()=>{let s=!1,o=[];return i.lock().then(async a=>{try{(n.audio||n.video)&&(o=await t6(n),s?o.forEach(c=>c.stop()):r(o))}catch(c){e&&c instanceof Error?e(c):fu.error(c)}finally{a()}}),()=>{s=!0,o.forEach(a=>{a.stop()})}},[JSON.stringify(n,cDe),e,i]),t}const jDe="_inRoom_1a6xo_8",$De="_header_1a6xo_17",BDe="_filler_1a6xo_29",HDe="_footer_1a6xo_34",VDe="_hidden_1a6xo_53",GDe="_overlay_1a6xo_57",qDe="_logo_1a6xo_75",KDe="_buttons_1a6xo_84",WDe="_layout_1a6xo_91",zDe="_raiseHand_1a6xo_111",YDe="_invite_1a6xo_117",XDe="_switchCamera_1a6xo_118",JDe="_shareScreen_1a6xo_119",ZDe="_fixedGrid_1a6xo_148",QDe="_scrollingGrid_1a6xo_154",eFe="_tile_1a6xo_173",tFe="_maximised_1a6xo_178",Rn={inRoom:jDe,header:$De,filler:BDe,footer:HDe,hidden:VDe,overlay:GDe,logo:qDe,buttons:KDe,layout:WDe,raiseHand:zDe,invite:YDe,switchCamera:XDe,shareScreen:JDe,fixedGrid:ZDe,scrollingGrid:QDe,tile:eFe,maximised:tFe},nFe="_content_1cy0f_8",rFe="_wait_1cy0f_19",iFe="_join_1cy0f_32",ag={content:nFe,wait:rFe,join:iFe};function wF(n,e){let t;return(...r)=>{window.clearTimeout(t),t=window.setTimeout(()=>n(...r),e)}}function Yg({debounce:n,scroll:e,polyfill:t,offsetSize:r}={debounce:0,scroll:!1,offsetSize:!1}){const i=t||(typeof window>"u"?class{}:window.ResizeObserver);if(!i)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");const[s,o]=_.useState({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),a=_.useRef({element:null,scrollContainers:null,resizeObserver:null,lastBounds:s,orientationHandler:null}),c=n?typeof n=="number"?n:n.scroll:null,l=n?typeof n=="number"?n:n.resize:null,u=_.useRef(!1);_.useEffect(()=>(u.current=!0,()=>void(u.current=!1)));const[h,p,m]=_.useMemo(()=>{const b=()=>{if(!a.current.element)return;const{left:R,top:k,width:I,height:T,bottom:C,right:P,x:O,y:D}=a.current.element.getBoundingClientRect(),F={left:R,top:k,width:I,height:T,bottom:C,right:P,x:O,y:D};a.current.element instanceof HTMLElement&&r&&(F.height=a.current.element.offsetHeight,F.width=a.current.element.offsetWidth),Object.freeze(F),u.current&&!cFe(a.current.lastBounds,F)&&o(a.current.lastBounds=F)};return[b,l?wF(b,l):b,c?wF(b,c):b]},[o,r,c,l]);function v(){a.current.scrollContainers&&(a.current.scrollContainers.forEach(b=>b.removeEventListener("scroll",m,!0)),a.current.scrollContainers=null),a.current.resizeObserver&&(a.current.resizeObserver.disconnect(),a.current.resizeObserver=null),a.current.orientationHandler&&("orientation"in screen&&"removeEventListener"in screen.orientation?screen.orientation.removeEventListener("change",a.current.orientationHandler):"onorientationchange"in window&&window.removeEventListener("orientationchange",a.current.orientationHandler))}function g(){a.current.element&&(a.current.resizeObserver=new i(m),a.current.resizeObserver.observe(a.current.element),e&&a.current.scrollContainers&&a.current.scrollContainers.forEach(b=>b.addEventListener("scroll",m,{capture:!0,passive:!0})),a.current.orientationHandler=()=>{m()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",a.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",a.current.orientationHandler))}const S=b=>{!b||b===a.current.element||(v(),a.current.element=b,a.current.scrollContainers=AQ(b),g())};return oFe(m,!!e),sFe(p),_.useEffect(()=>{v(),g()},[e,m,p]),_.useEffect(()=>v,[]),[S,s,h]}function sFe(n){_.useEffect(()=>{const e=n;return window.addEventListener("resize",e),()=>void window.removeEventListener("resize",e)},[n])}function oFe(n,e){_.useEffect(()=>{if(e){const t=n;return window.addEventListener("scroll",t,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",t,!0)}},[n,e])}function AQ(n){const e=[];if(!n||n===document.body)return e;const{overflow:t,overflowX:r,overflowY:i}=window.getComputedStyle(n);return[t,r,i].some(s=>s==="auto"||s==="scroll")&&e.push(n),[...e,...AQ(n.parentElement)]}const aFe=["x","y","top","bottom","left","right","width","height"],cFe=(n,e)=>aFe.every(t=>n[t]===e[t]),lFe="_loading_14w06_8",uFe={loading:lFe},dFe=({size:n,loading:e,...t})=>w.jsxs("div",{children:[e&&w.jsx("div",{className:uFe.loading,children:w.jsx(XCe,{size:n/3})}),w.jsx(Np,{size:n,...t})]}),hFe="_preview_1jjvr_8",fFe="_mirror_1jjvr_24",pFe="_cameraStarting_1jjvr_28",mFe="_avatarContainer_1jjvr_39",gFe="_buttonBar_1jjvr_51",cg={preview:hFe,mirror:fFe,cameraStarting:pFe,avatarContainer:mFe,buttonBar:gFe},vFe=({matrixInfo:n,muteStates:e,videoTrack:t,children:r})=>{const{t:i}=Qe(),[s,o]=Yg(),a=_.useRef(null);_.useEffect(()=>(a.current&&(t==null||t.attach(a.current)),()=>{t==null||t.detach()}),[t]);const c=_.useMemo(()=>e.video.enabled&&!t,[e.video.enabled,t]);return w.jsxs("div",{className:De(cg.preview),ref:s,children:[w.jsx("video",{className:t&&n6(t).facingMode==="user"?cg.mirror:void 0,ref:a,muted:!0,playsInline:!0,tabIndex:-1,disablePictureInPicture:!0}),(!e.video.enabled||c)&&w.jsx(w.Fragment,{children:w.jsxs("div",{className:cg.avatarContainer,children:[c&&w.jsx("div",{className:cg.cameraStarting,role:"status",children:i("video_tile.camera_starting")}),w.jsx(dFe,{id:n.userId,name:n.displayName,size:Math.min(o.width,o.height)/2,src:n.avatarUrl,loading:c})]})}),w.jsx("div",{className:cg.buttonBar,children:r})]})},OQ=n=>{const{t:e}=Qe();return w.jsx(Mt,{kind:"secondary",size:"sm",Icon:aIe,...n,children:e("action.invite")})};function up(n){const e=_.useRef(void 0);return e.current??(e.current={value:n()}),e.current.value}let wd;/android/i.test(navigator.userAgent)?wd="android":/iPad|iPhone|iPod|Mac/.test(navigator.userAgent)&&"ontouchend"in document?wd="ios":wd="desktop";const yFe=()=>{const{userAgent:n}=navigator;return n.includes("Firefox")};function Lc(n){const e=_.useRef(n);return e.current=n,e}function MQ(n){const e=rh(),t=Lc(e.videoInput.select),r=Hv(s=>s.pipe(At(([o])=>o),At(o=>o===null?Ct(null):Bv(Ta(o,Pe.Restarted).pipe(ln(null),Fe(()=>o)),Ta(o,Pe.Muted).pipe(Fe(()=>null))))),[n]),i=Hv(s=>wd==="desktop"?Ct(null):s.pipe(At(([o])=>o),Fe(o=>{if(o===null)return null;const a=n6(o).facingMode;return a!=="user"&&a!=="environment"?null:()=>void o.restartTrack({facingMode:a==="user"?"environment":"user"}).then(()=>{const c=o.mediaStreamTrack.getSettings().deviceId;c!==void 0&&t.current(c)}).catch(c=>M.error("Failed to switch camera",a,c))})),[r]);return ot(i)}const NQ=({client:n,matrixInfo:e,muteStates:t,onEnter:r,enterLabel:i,confineToRoom:s,hideHeader:o,participantCount:a,onShareClick:c,waitingForInvite:l})=>{const{t:u}=Qe();Oy(e.roomName);const h=_.useCallback(()=>{var z,H;return(H=(z=t.audio).setEnabled)==null?void 0:H.call(z,J=>!J)},[t]),p=_.useCallback(()=>{var z,H;return(H=(z=t.video).setEnabled)==null?void 0:H.call(z,J=>!J)},[t]),[m,v]=_.useState(!1),[g,S]=_.useState(d4),b=_.useCallback(()=>v(!0),[v]),R=_.useCallback(()=>v(!1),[v]),k=ja(),I=_.useCallback(()=>{var z;(z=k("/"))==null||z.catch(H=>{M.error("Failed to navigate to /",H)})},[k]),T=iE("(max-height: 500px)"),C=!s&&w.jsx(Aa,{className:ag.recents,to:"/",children:u("lobby.leave_button")}),P=rh(),O=up(()=>t.audio.enabled&&{deviceId:P.audioInput.selectedId}),D=_.useMemo(()=>({audio:Object.assign({},O),video:t.video.enabled&&{deviceId:P.videoInput.selectedId}}),[O,P.videoInput.selectedId,t.video.enabled]),F=_.useCallback(z=>{var H,J,Y,G;M.error("Error while creating preview Tracks:",z),(J=(H=t.audio).setEnabled)==null||J.call(H,!1),(G=(Y=t.video).setEnabled)==null||G.call(Y,!1)},[t.audio,t.video]),U=UDe(D,F),B=_.useMemo(()=>(U==null?void 0:U.find(z=>z.kind===pe.Kind.Video))??null,[U]),V=MQ(Hv(z=>z.pipe(Fe(([H])=>H)),[B]));return w.jsxs(w.Fragment,{children:[w.jsxs("div",{className:De(ag.room,Rn.inRoom),children:[!o&&w.jsxs(wu,{children:[w.jsx(Jd,{children:w.jsx(ZY,{id:e.roomId,name:e.roomName,avatarUrl:e.roomAvatar,encrypted:e.e2eeSystem.kind!==Vt.NONE,participantCount:a})}),w.jsx(Zd,{children:c!==null&&w.jsx(OQ,{onClick:c})})]}),w.jsxs("div",{className:ag.content,children:[w.jsx(vFe,{matrixInfo:e,muteStates:t,videoTrack:B,children:w.jsx(Mt,{className:De(ag.join,{[ag.wait]:l}),size:l?"sm":"lg",onClick:()=>{l||r()},"data-testid":"lobby_joinCall",children:i??u("lobby.join_button")})}),!T&&C]}),w.jsxs("div",{className:Rn.footer,children:[T&&C,w.jsxs("div",{className:Rn.buttons,children:[w.jsx(pZ,{muted:!t.audio.enabled,onClick:h,disabled:t.audio.setEnabled===null}),w.jsx(mZ,{muted:!t.video.enabled,onClick:p,disabled:t.video.setEnabled===null}),V&&w.jsx(gZ,{onClick:V}),w.jsx(yZ,{onClick:b}),!s&&w.jsx(vZ,{onClick:I})]})]})]}),n&&w.jsx(h4,{client:n,open:m,onDismiss:R,tab:g,onTabChange:S})]})},_Fe="_headline_1em2y_8",bFe="_callEndedContent_1em2y_15",SFe="_callEndedButton_1em2y_35",wFe="_submitButton_1em2y_40",EFe="_container_1em2y_47",CFe="_main_1em2y_55",TFe="_footer_1em2y_72",yl={headline:_Fe,callEndedContent:bFe,callEndedButton:SFe,submitButton:wFe,container:EFe,main:CFe,footer:TFe},IFe="_starIcon_1m09w_8",RFe="_starRating_1m09w_12",kFe="_inputContainer_1m09w_18",xFe="_hideElement_1m09w_22",lg={starIcon:IFe,starRating:RFe,inputContainer:kFe,hideElement:xFe},PFe=(n,e)=>_.createElement("svg",{width:28,height:26,viewBox:"0 0 28 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{d:"M14 21.0267L22.24 26.0001L20.0533 16.6267L27.3333 10.3201L17.7466 9.50675L14 0.666748L10.2533 9.50675L0.666626 10.3201L7.94663 16.6267L5.75996 26.0001L14 21.0267Z",fill:"white"})),LFe=_.forwardRef(PFe),AFe=(n,e)=>_.createElement("svg",{width:28,height:26,viewBox:"0 0 28 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...n},_.createElement("path",{id:"Vector",d:"M14 7.50675L15.2933 10.5601L15.92 12.0401L17.52 12.1734L20.8133 12.4534L18.3066 14.6267L17.0933 15.6801L17.4533 17.2534L18.2 20.4667L15.3733 18.7601L14 17.9067L12.6266 18.7334L9.79996 20.4401L10.5466 17.2267L10.9066 15.6534L9.69329 14.6001L7.18663 12.4267L10.48 12.1467L12.08 12.0134L12.7066 10.5334L14 7.50675M14 0.666748L10.2533 9.50675L0.666626 10.3201L7.94663 16.6267L5.75996 26.0001L14 21.0267L22.24 26.0001L20.0533 16.6267L27.3333 10.3201L17.7466 9.50675L14 0.666748Z",fill:"white"})),OFe=_.forwardRef(AFe);function MFe({starCount:n,onChange:e,required:t}){const[r,i]=_.useState(0),[s,o]=_.useState(0),{t:a}=Qe();return w.jsx("div",{className:lg.starRating,children:[...Array(n)].map((c,l)=>(l+=1,w.jsxs("div",{className:lg.inputContainer,onMouseEnter:()=>o(l),onMouseLeave:()=>o(r),children:[w.jsx("input",{className:lg.hideElement,type:"radio",id:"starInput"+String(l),value:String(l)+"Star",name:"star rating",onChange:u=>{i(l),e(l)},required:!0}),w.jsx("label",{className:lg.hideElement,id:"starInvisibleLabel"+String(l),htmlFor:"starInput"+String(l),children:a("star_rating_input_label",{count:l})}),w.jsx("label",{className:lg.starIcon,id:"starIcon"+String(l),htmlFor:"starInput"+String(l),children:l<=(s||r)?w.jsx(LFe,{}):w.jsx(OFe,{})})]},l)))})}const NFe=({client:n,isPasswordlessUser:e,confineToRoom:t,endedCallId:r})=>{const{t:i}=Qe(),s=ja(),{displayName:o}=Ly(n),[a,c]=_.useState(!1),[l,u]=_.useState(0),[h,p]=_.useState(!1),[m,v]=_.useState(!1),g=_.useCallback(R=>{R.preventDefault();const I=new FormData(R.target).get("feedbackText");jt.instance.eventQualitySurvey.track(r,I,l),p(!0),setTimeout(()=>{v(!0),setTimeout(()=>{var T;e?c(!0):t||(T=s("/"))==null||T.catch(C=>{M.error("Failed to navigate to /",C)})},1e3)},1e3)},[r,s,e,t,l]),S=e&&w.jsxs("div",{className:yl.callEndedContent,children:[w.jsxs(Ci,{i18nKey:"call_ended_view.create_account_prompt",children:[w.jsx("p",{children:"Why not finish by setting up a password to keep your account?"}),w.jsx("p",{children:"You'll be able to keep your name and set an avatar for use on future calls"})]}),w.jsx(r4,{className:yl.callEndedButton,to:"/register",children:i("call_ended_view.create_account_button")})]}),b=w.jsxs("div",{className:yl.callEndedContent,children:[w.jsx(Ci,{i18nKey:"call_ended_view.feedback_prompt",children:w.jsx("p",{children:"We'd love to hear your feedback so we can improve your experience."})}),w.jsxs("form",{onSubmit:g,children:[w.jsx(yt,{children:w.jsx(MFe,{starCount:5,onChange:u,required:!0})}),w.jsx(yt,{children:w.jsx(vn,{className:RZ.feedback,id:"feedbackText",name:"feedbackText",label:i("settings.feedback_tab_description_label"),placeholder:i("settings.feedback_tab_description_label"),type:"textarea"})})," ",w.jsx(yt,{children:m?w.jsx(Ci,{i18nKey:"call_ended_view.feedback_done",children:w.jsx("p",{children:"Thanks for your feedback!"})}):w.jsx(Mt,{type:"submit",className:yl.submitButton,"data-testid":"home_go",children:i(h?"submitting":"action.submit")})})]})]});return w.jsxs(w.Fragment,{children:[w.jsxs(wu,{children:[w.jsx(Jd,{children:!t&&w.jsx(Dd,{})}),w.jsx(Zd,{})]}),w.jsxs("div",{className:yl.container,children:[w.jsxs("main",{className:yl.main,children:[w.jsx(Su,{size:"xl",weight:"semibold",className:yl.headline,children:a?i("call_ended_view.headline",{displayName:o}):i("call_ended_view.headline",{displayName:o})+`
|
|
@@ -216,6 +216,6 @@ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},TR=t,T
|
|
|
216
216
|
The chosen QR Code version cannot contain this amount of data.
|
|
217
217
|
Minimum version required to store current data is: `+U+`.
|
|
218
218
|
`);const B=k(P,O,F),V=n.getSymbolSize(P),z=new r(V);return m(z,P),v(z),g(z,P),b(z,O,0),P>=7&&S(z,P),R(z,B),isNaN(D)&&(D=o.getBestMask(z,b.bind(null,z,O))),o.applyMask(D,z),b(z,O,D),{modules:z,version:P,errorCorrectionLevel:O,maskPattern:D,segments:F}}return cR.create=function(P,O){if(typeof P>"u"||P==="")throw new Error("No input text");let D=e.M,F,U;return typeof O<"u"&&(D=e.from(O.errorCorrectionLevel,e.M),F=l.from(O.version),U=o.from(O.maskPattern),O.toSJISFunc&&n.setToSJISFunction(O.toSJISFunc)),T(P,F,D,U)},cR}var RR={},kR={},sj;function Qee(){return sj||(sj=1,function(n){function e(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let r=t.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+t);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const i=parseInt(r.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+r.slice(0,6).join("")}}n.getOptions=function(r){r||(r={}),r.color||(r.color={});const i=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,o=r.scale||4;return{width:s,scale:s?4:o,margin:i,color:{dark:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},n.getScale=function(r,i){return i.width&&i.width>=r+i.margin*2?i.width/(r+i.margin*2):i.scale},n.getImageWidth=function(r,i){const s=n.getScale(r,i);return Math.floor((r+i.margin*2)*s)},n.qrToImageData=function(r,i,s){const o=i.modules.size,a=i.modules.data,c=n.getScale(o,s),l=Math.floor((o+s.margin*2)*c),u=s.margin*c,h=[s.color.light,s.color.dark];for(let p=0;p<l;p++)for(let m=0;m<l;m++){let v=(p*l+m)*4,g=s.color.light;if(p>=u&&m>=u&&p<l-u&&m<l-u){const S=Math.floor((p-u)/c),b=Math.floor((m-u)/c);g=h[a[S*o+b]?1:0]}r[v++]=g.r,r[v++]=g.g,r[v++]=g.b,r[v]=g.a}}}(kR)),kR}var oj;function IVe(){return oj||(oj=1,function(n){const e=Qee();function t(i,s,o){i.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}n.render=function(s,o,a){let c=a,l=o;typeof c>"u"&&(!o||!o.getContext)&&(c=o,o=void 0),o||(l=r()),c=e.getOptions(c);const u=e.getImageWidth(s.modules.size,c),h=l.getContext("2d"),p=h.createImageData(u,u);return e.qrToImageData(p.data,s,c),t(h,l,u),h.putImageData(p,0,0),l},n.renderToDataURL=function(s,o,a){let c=a;typeof c>"u"&&(!o||!o.getContext)&&(c=o,o=void 0),c||(c={});const l=n.render(s,o,c),u=c.type||"image/png",h=c.rendererOpts||{};return l.toDataURL(u,h.quality)}}(RR)),RR}var xR={},aj;function RVe(){if(aj)return xR;aj=1;const n=Qee();function e(i,s){const o=i.a/255,a=s+'="'+i.hex+'"';return o<1?a+" "+s+'-opacity="'+o.toFixed(2).slice(1)+'"':a}function t(i,s,o){let a=i+s;return typeof o<"u"&&(a+=" "+o),a}function r(i,s,o){let a="",c=0,l=!1,u=0;for(let h=0;h<i.length;h++){const p=Math.floor(h%s),m=Math.floor(h/s);!p&&!l&&(l=!0),i[h]?(u++,h>0&&p>0&&i[h-1]||(a+=l?t("M",p+o,.5+m+o):t("m",c,0),c=0,l=!1),p+1<s&&i[h+1]||(a+=t("h",u),u=0)):c++}return a}return xR.render=function(s,o,a){const c=n.getOptions(o),l=s.modules.size,u=s.modules.data,h=l+c.margin*2,p=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",m="<path "+e(c.color.dark,"stroke")+' d="'+r(u,l,c.margin)+'"/>',v='viewBox="0 0 '+h+" "+h+'"',S='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+v+' shape-rendering="crispEdges">'+p+m+`</svg>
|
|
219
|
-
`;return typeof a=="function"&&a(null,S),S},xR}var cj;function kVe(){if(cj)return Xh;cj=1;const n=cVe(),e=TVe(),t=IVe(),r=RVe();function i(s,o,a,c,l){const u=[].slice.call(arguments,1),h=u.length,p=typeof u[h-1]=="function";if(!p&&!n())throw new Error("Callback required as last argument");if(p){if(h<2)throw new Error("Too few arguments provided");h===2?(l=a,a=o,o=c=void 0):h===3&&(o.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=o,o=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=o,o=c=void 0):h===2&&!o.getContext&&(c=a,a=o,o=void 0),new Promise(function(m,v){try{const g=e.create(a,c);m(s(g,o,c))}catch(g){v(g)}})}try{const m=e.create(a,c);l(null,s(m,o,c))}catch(m){l(m)}}return Xh.create=e.create,Xh.toCanvas=i.bind(null,t.render),Xh.toDataURL=i.bind(null,t.renderToDataURL),Xh.toString=i.bind(null,function(s,o,a){return r.render(s,a)}),Xh}var xVe=kVe();const PVe="_qrCode_h54ia_8",LVe={qrCode:PVe},AVe=({data:n,className:e})=>{const[t,r]=_.useState(null);return _.useEffect(()=>{let i=!1;return xVe.toDataURL(n,{errorCorrectionLevel:"L"}).then(s=>{i||r(s)}).catch(s=>{i||r(null)}),()=>{i=!0}},[n]),w.jsx("div",{className:De(LVe.qrCode,e),children:t&&w.jsx("img",{src:t,alt:Ma("qr_code")})})},OVe=({room:n,open:e,onDismiss:t})=>{const{t:r}=Qe(),i=wE(n.roomId),s=_.useMemo(()=>YZ(n.roomId,i,n.name),[i,n.name,n.roomId]),[,o]=tVe(s),[a,c]=_.useState(!1),l=_.useCallback(()=>c(!1),[c]),u=_.useCallback(h=>{h.stopPropagation(),o(),t(),c(!0)},[o,t]);return w.jsxs(w.Fragment,{children:[w.jsxs(th,{title:r("invite_modal.title"),open:e,onDismiss:t,children:[w.jsx(AVe,{className:oR.qrCode,data:s}),w.jsx(Xt,{className:oR.url,size:"sm",weight:"semibold",children:s}),w.jsx(Mt,{className:oR.button,Icon:zTe,onClick:u,"data-testid":"modal_inviteLink",children:r("action.copy_link")})]}),w.jsx(aVe,{open:a,onDismiss:l,autoDismiss:2e3,Icon:eY,children:r("invite_modal.link_copied_toast")})]})},MVe=({error:n,recoveryActionHandler:e,widget:t})=>{const{t:r}=Qe();let i;switch(n.category){case mb.CONFIGURATION_ISSUE:i=WTe;break;case mb.NETWORK_CONNECTIVITY:i=ZTe;break;case mb.CLIENT_CONFIGURATION:i=hIe;break;default:i=Vw}const s=[];return n instanceof Tee&&s.push({label:r("call_ended_view.reconnect_button"),onClick:()=>e("reconnect")}),w.jsx(Uf,{children:w.jsxs(qv,{Icon:i,title:n.localisedTitle,rageshake:n.code==D4.UNKNOWN_ERROR,widget:t,children:[w.jsx("p",{children:n.localisedMessage??w.jsx(Ci,{i18nKey:"error.unexpected_ec_error",components:[w.jsx("b",{}),w.jsx("code",{})],values:{errorCode:n.code}})}),s&&s.map((o,a)=>w.jsx("button",{onClick:o.onClick,children:o.label},`action${a}`))]})})},NVe=({recoveryActionHandler:n,onError:e,children:t,widget:r})=>{const i=_.useCallback(({error:s,resetError:o})=>{const a=s instanceof Kc?s:new F4(s instanceof Error?s:new Error);return w.jsx(MVe,{widget:r??null,error:a,resetError:o,recoveryActionHandler:c=>{o(),n(c)}})},[n,r]);return w.jsx(Hw,{fallback:i,onError:s=>e==null?void 0:e(s),children:t})},DVe=({client:n,isPasswordlessUser:e,confineToRoom:t,preload:r,skipLobby:i,hideHeader:s,rtcSession:o,isJoined:a,muteStates:c,widget:l})=>{const u=bZ(o),h=Lc($4({sounds:zee,latencyHint:"interactive"}));_.useEffect(()=>{var ye,Se;u.length>=$He&&((Se=(ye=c.audio).setEnabled)==null||Se.call(ye,!1))},[]),_.useEffect(()=>(window.rtcSession=o,()=>{delete window.rtcSession}),[o]),EL(o,ts.MembershipManagerError,ye=>{z(new c$e(D4.MEMBERSHIP_MANAGER_UNRECOVERABLE,ye.message??ye))}),_.useEffect(()=>{n.getRoom(o.room.roomId)!==o.room&&M.warn(`We've ended up with multiple rooms for the same ID (${o.room.roomId}). This indicates a bug in the group call loading code, and may lead to incomplete room state.`)},[n,o.room]);const p=o.room,{displayName:m,avatarUrl:v}=Ly(n),g=YHe(p),S=zHe(p),{perParticipantE2EE:b,returnToLobby:R}=eh(),k=wE(p.roomId),[I]=Ar(fZ);Oy(g);const T=_.useMemo(()=>({userId:n.getUserId(),displayName:m,avatarUrl:v,roomId:p.roomId,roomName:g,roomAlias:p.getCanonicalAlias(),roomAvatar:S,e2eeSystem:k}),[n,m,v,g,p,S,k]),C=_.useMemo(()=>new Set(u.map(ye=>ye.sender)).size,[u]),P=rh(),O=Lc(P),D=Lc(c),F=async(ye,Se,xe)=>{try{await KHe(ye,Se,xe)}catch(Oe){if(Oe instanceof Kc)z(Oe);else{M.error("Unknown Error while entering RTC session",Oe);const Ye=new F4(Oe instanceof Error?Oe:new Error("Unknown error",{cause:Oe}));z(Ye)}}};_.useEffect(()=>{const ye=async({audioInput:Se,videoInput:xe})=>{var Ye,Ht,Un,Nt;const Oe=await Mc.getLocalDevices(void 0,!0);if(Se){const je=EF(Se,"audioinput",Oe);je?(M.debug(`Found audio input ID ${je} for name ${Se}`),O.current.audioInput.select(je)):(M.warn("Unknown audio input: "+Se),(Ht=(Ye=D.current.audio).setEnabled)==null||Ht.call(Ye,!1))}if(xe){const je=EF(xe,"videoinput",Oe);je?(M.debug(`Found video input ID ${je} for name ${xe}`),O.current.videoInput.select(je)):(M.warn("Unknown video input: "+xe),(Nt=(Un=D.current.video).setEnabled)==null||Nt.call(Un,!1))}};if(i)if(l)if(r){const Se=xe=>{(async()=>{await ye(xe.detail.data),await F(o,b,I),l.api.transport.reply(xe.detail,{})})().catch(Oe=>{M.error("Error joining RTC session",Oe)})};return l.lazyActions.on(xr.JoinCall,Se),()=>{l.lazyActions.off(xr.JoinCall,Se)}}else(async()=>{await F(o,b,I)})().catch(Se=>{M.error("Error joining RTC session",Se)});else F(o,b,I)},[l,o,r,i,b,O,D,I]);const[U,B]=_.useState(!1),[V,z]=_.useState(null),H=ja(),J=_.useCallback((ye="user")=>{var Ye;const Se=(Ye=h.current)==null?void 0:Ye.playSound("left"),xe=!!l;B(!0);const Oe=new Promise(Ht=>{jt.instance.eventCallEnded.track(p.roomId,o.memberships.length,xe,o),window.setTimeout(Ht,10)});AU(o,ye,Promise.all([Se,Oe])).then(async()=>{!e&&!t&&!jt.instance.isEnabled()&&await H("/")}).catch(Ht=>{M.error("Error leaving RTC session",Ht)})},[h,l,o,p.roomId,e,t,H]);_.useEffect(()=>{if(l&&a){l.api.setAlwaysOnScreen(!0).catch(Se=>{M.error("Error calling setAlwaysOnScreen(true)",Se)});const ye=Se=>{l.api.transport.reply(Se.detail,{}),AU(o,"user").catch(xe=>{M.error("Failed to leave RTC session",xe)})};return l.lazyActions.once(xr.HangupCall,ye),()=>{l.lazyActions.off(xr.HangupCall,ye)}}},[l,a,o]);const Y=XHe(p),[G,K]=_.useState(!1),ee=_.useCallback(()=>K(!1),[K]),q=_.useCallback(()=>K(!0),[K]),Q=Y===wc.Public?q:null;if(!QH()&&k.kind!==Vt.NONE)throw new l$e;const Ce=w.jsx(OVe,{room:p,open:G,onDismiss:ee}),Te=w.jsxs(w.Fragment,{children:[Ce,w.jsx(NQ,{client:n,matrixInfo:T,muteStates:c,onEnter:()=>void F(o,b,I),confineToRoom:t,hideHeader:s,participantCount:C,onShareClick:Q})]});let Ae;if(V){const ye=()=>{throw V};Ae=w.jsx(ye,{})}else a?Ae=w.jsxs(w.Fragment,{children:[Ce,w.jsx(UHe,{client:n,matrixInfo:T,rtcSession:o,participantCount:C,onLeave:J,hideHeader:s,muteStates:c,e2eeSystem:k,onShareClick:Q})]}):U&&l===null?e||jt.instance.isEnabled()&&l===null?Ae=w.jsx(NFe,{endedCallId:o.room.roomId,client:n,isPasswordlessUser:e,confineToRoom:t}):Ae=null:U&&l!==null?Ae=R?Te:null:r||i?Ae=null:Ae=Te;return w.jsx(NVe,{widget:l,recoveryActionHandler:ye=>{ye=="reconnect"&&(B(!1),F(o,b,I).catch(Se=>{M.error("Error re-entering RTC session",Se)}))},onError:()=>{o.isJoined()&&J("error")},children:Ae})},FVe="_modal_1tnec_8",UVe={modal:FVe},jVe=({roomId:n})=>{const{t:e}=Qe(),[t,r]=_.useState(!0),i=_.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[r]),s=wE(n);s.kind===Vt.NONE&&M.error("Generating app redirect URL for encrypted room but don't have key available!");const o=_.useMemo(()=>{const a=new URL(n===null?window.location.href:YZ(n,s));a.hash=Eke(a.hash,l=>(l.set("appPrompt","false"),l.set("confineToRoom","true"),l));const c=new URL("io.element.call:/");return c.searchParams.set("url",a.toString()),c.toString()},[s,n]);return w.jsxs(th,{className:UVe.modal,title:e("app_selection_modal.title"),open:t,children:[w.jsx(Xt,{size:"md",weight:"semibold",children:e("app_selection_modal.text")}),w.jsx(Mt,{kind:"secondary",onClick:i,children:e("app_selection_modal.continue_in_browser")}),w.jsx(Mt,{as:"a",href:o,Icon:AY,children:e("app_selection_modal.open_in_app")})]})},$Ve=3,BVe=3e3;async function ete(n,e=0,...t){try{return await n.joinRoom(...t)}catch(r){if(r instanceof mn&&r.errcode==="M_FORBIDDEN"&&e<$Ve)return await new Promise(i=>setTimeout(i,BVe)),ete(n,e+1,...t);throw r}}class yb extends Error{constructor(e,t,r,i){super(t),this.icon=e,this.messageBody=r,this.reason=i}}const HVe=(n,e,t)=>{const[r,i]=_.useState({kind:"loading"}),s=_.useRef(void 0),{t:o}=Qe(),a=_.useCallback(()=>new yb(HTe,o("group_call_loader.banned_heading"),o("group_call_loader.banned_body"),u()),[o]),c=_.useCallback(()=>new yb(Gw,o("group_call_loader.knock_reject_heading"),o("group_call_loader.knock_reject_body"),u()),[o]),l=_.useCallback(()=>new yb(vY,o("group_call_loader.call_ended_heading"),o("group_call_loader.call_ended_body"),u()),[o]),u=()=>{var h,p,m;return(m=(p=s.current)==null?void 0:p.currentState.getStateEvents(ie.RoomMember,(h=s.current)==null?void 0:h.myUserId))==null?void 0:m.getContent().reason};return _.useEffect(()=>{if(!n||!e)return;const h=async b=>{let R=null;const k=await n.getRoomIdForAlias(b.toLowerCase());return M.info(`${b} resolved to ${k.room_id}`),R=n.getRoom(k.room_id),R?M.info(`Already in room ${k.room_id}, not rejoining.`):(M.info(`Room ${k.room_id} not found, joining.`),R=await n.joinRoom(k.room_id,{viaServers:k.servers})),R},p=async(b,R,k)=>(await n.knockRoom(b,{viaServers:R}),k(),await new Promise((I,T)=>{n.on(Xe.MyMembership,(C,P,O)=>{b===C.roomId&&(s.current=C,P===We.Invite&&O===We.Knock&&ete(n,0,C.roomId,{viaServers:R}).then(D=>{M.log("Auto-joined %s",D.roomId),I(D)},T),P===We.Ban&&T(a()),P===We.Leave&&T(c()))})})),m=async()=>{let b=null;if(e[0]==="#")b=await h(e),s.current=b;else{const R=e;b=n.getRoom(R),s.current=b??void 0;const k=b==null?void 0:b.getMyMembership();if(k===We.Join)return b;if(Je)throw new Error("Room not found. The widget-api did not pass over the relevant room events/information.");if(k===We.Ban)throw a();if(k===We.Invite)b=await n.joinRoom(R,{viaServers:t});else{let I;try{I=await n.getRoomSummary(R,t)}catch(T){M.warn("Could not load room summary to decide whether we want to join or knock.\n EC will fallback to join as if this would be a public room.\n Reach out to your homeserver admin to ask them about supporting the `/summary` endpoint (im.nheko.summary):",T)}if(I===void 0||I.join_rule===wc.Public)b=await n.joinRoom(R,{viaServers:t});else if(I.join_rule===wc.Knock){const T=I;let C=()=>{};const P=new Promise(O=>{T.membership!==We.Knock?C=O:O()});i({kind:"canKnock",roomSummary:T,knock:C}),await P,b=await p(I.room_id,t,()=>i({kind:"waitForInvite",roomSummary:T}))}else throw new Error(`Room ${I.room_id} is not joinable. This likely means, that the conference owner has changed the room settings to private.`)}}return M.info(`Joined ${e}, waiting room to be ready for group calls`),await n.waitUntilRoomReadyForGroupCalls(b.roomId),M.info(`${e}, is ready for group calls`),b},v=async()=>{const b=await m();return s.current=b,M.debug(`Fetched / joined room ${e}`),n.matrixRTC.getRoomSession(b)},g=async()=>{n.getSyncState()!==Pr.Syncing&&(M.debug("useLoadGroupCall: waiting for client to start syncing..."),await new Promise(b=>{const R=()=>{if(n.getSyncState()===Pr.Syncing)return n.off(Ge.Sync,R),b()};n.on(Ge.Sync,R)}),M.debug("useLoadGroupCall: client is now syncing."))},S=async()=>{await new Promise((b,R)=>{n.on(Xe.MyMembership,(k,I)=>{I===We.Leave&&R(l()),I===We.Ban&&R(a())})})};r.kind==="loading"&&(M.log("Start loading group call"),g().then(v).then(b=>i({kind:"loaded",rtcSession:b})).then(S).catch(b=>i({kind:"failed",error:b})))},[a,n,c,l,e,r,o,t]),r};function VVe(n){const[,e]=_.useState(0);return _.useEffect(()=>{if(n!==void 0){const t=r=>{M.info(`Session in room ${n.room.roomId} changed to ${r?"joined":"left"}`),e(i=>i+1)};return n.on(ts.JoinStateChanged,t),()=>{n.off(ts.JoinStateChanged,t)}}},[n]),(n==null?void 0:n.isJoined())??!1}const GVe=()=>{const{confineToRoom:n,appPrompt:e,preload:t,hideHeader:r,displayName:i,skipLobby:s}=eh(),{t:o}=Qe(),{roomAlias:a,roomId:c,viaServers:l}=Tke(),u=c??a;u||M.error("No room specified");const{registerPasswordlessUser:h}=eQ(),[p,m]=_.useState(!1),{loading:v,authenticated:g,client:S,error:b,passwordlessUser:R}=o4(),{avatarUrl:k,displayName:I}=Ly(S),T=HVe(S,u,l),C=VVe(T.kind==="loaded"?T.rtcSession:void 0),P=HHe(C);_.useEffect(()=>{!v&&!g&&i&&!Je&&(m(!0),h(i).catch(V=>{M.error("Failed to register passwordless user",V)}).finally(()=>{m(!1)}))},[v,g,i,m,h]);const[O,D]=gE();_.useEffect(()=>{O===null&&D&&D(!0)},[O,D]);const F=_.useRef(!1);_.useEffect(()=>{T.kind==="loaded"&&F.current&&M.log("Play join sound 'Not yet implemented'")},[T.kind]);const U=()=>{switch(T.kind){case"loaded":return w.jsx(DVe,{widget:Je,client:S,rtcSession:T.rtcSession,isJoined:C,isPasswordlessUser:R,confineToRoom:n,preload:t,skipLobby:s||F.current,hideHeader:r,muteStates:P});case"waitForInvite":case"canKnock":{F.current=F.current||T.kind==="waitForInvite";const V=T.kind==="canKnock"?T.knock:null,z=T.kind==="canKnock"?o("lobby.ask_to_join"):w.jsxs(w.Fragment,{children:[o("lobby.waiting_for_invite"),w.jsx(eY,{})]});return w.jsx(NQ,{client:S,matrixInfo:{userId:S.getUserId()??"",displayName:I??"",avatarUrl:k??"",roomAlias:null,roomId:T.roomSummary.room_id,roomName:T.roomSummary.name??"",roomAvatar:T.roomSummary.avatar_url??null,e2eeSystem:{kind:T.roomSummary["im.nheko.summary.encryption"]?Vt.PER_PARTICIPANT:Vt.NONE}},onEnter:()=>V==null?void 0:V(),enterLabel:z,waitingForInvite:T.kind==="waitForInvite",confineToRoom:n,hideHeader:r,participantCount:null,muteStates:P,onShareClick:null})}case"loading":return w.jsx(Uf,{children:w.jsx("h1",{children:o("common.loading")})});case"failed":return F.current=!1,T.error.errcode==="M_NOT_FOUND"?w.jsx(Uf,{children:w.jsx(qv,{Icon:oIe,title:o("error.call_not_found"),widget:Je,children:w.jsx(Ci,{i18nKey:"error.call_not_found_description",children:w.jsxs("p",{children:["That link doesn't appear to belong to any existing call. Check that you have the right link, or"," ",w.jsx(Aa,{to:"/",children:"create a new one"}),"."]})})})}):T.error instanceof yb?w.jsx(Uf,{children:w.jsxs(qv,{Icon:T.error.icon,title:T.error.message,widget:Je,children:[w.jsx("p",{children:T.error.messageBody}),T.error.reason&&w.jsx("p",{children:o("group_call_loader.reason",{reason:T.error.reason})})]})}):w.jsx(Kv,{widget:Je,error:T.error});default:return w.jsx(w.Fragment,{children:" "})}};let B;return v||p?B=w.jsx(_E,{}):b?B=w.jsx(Kv,{widget:Je,error:b}):S?u?B=U():B=w.jsx(ZZ,{}):B=w.jsx(t7e,{}),w.jsxs(w.Fragment,{children:[B,e&>.get().app_prompt&&(wd==="android"||wd==="ios")&&c&&w.jsx(jVe,{roomId:c})]})},qVe="_banner_sye6n_8",KVe={banner:qVe},WVe=({children:n,className:e,...t})=>{const{t:r}=Qe(),i=jp();let s=!1;return(i==null?void 0:i.state)==="valid"&&(s=i.disconnected),w.jsx(w.Fragment,{children:s&&w.jsxs("div",{className:De(KVe.banner,e),...t,children:[n,r("disconnected_banner")]})})},zVe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLQn9C+0YLRgNC10LHQuNGC0LXQu9GB0LrQviDQvNC10L3RjiIKICB9LAogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAi0JfQsNGC0LLQvtGA0LgiLAogICAgImdvIjogItCd0LDQv9GA0LXQtCIsCiAgICAibm8iOiAi0J3QtSIsCiAgICAicmVnaXN0ZXIiOiAi0KDQtdCz0LjRgdGC0YDQsNGG0LjRjyIsCiAgICAicmVtb3ZlIjogItCf0YDQtdC80LDRhdC90LgiLAogICAgInNpZ25faW4iOiAi0JLQu9C10LciLAogICAgInNpZ25fb3V0IjogItCY0LfQu9C10LciCiAgfSwKICAiY2FsbF9lbmRlZF92aWV3IjogewogICAgImNyZWF0ZV9hY2NvdW50X2J1dHRvbiI6ICLQodGK0LfQtNCw0Lkg0LDQutCw0YPQvdGCIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+0JfQsNGJ0L4g0L3QtSDQvdCw0YHRgtGA0L7QudGC0LUg0L/QsNGA0L7Qu9CwINC30LAg0LTQsCDQt9Cw0L/QsNC30LjRgtC1INCw0LrQsNGD0L3RgtCwINGB0Lg/PC8wPjwxPtCp0LUg0LzQvtC20LXRgtC1INC00LAg0LfQsNC/0LDQt9C40YLQtSDQuNC80LXRgtC+INC4INCw0LLQsNGC0LDRgNCwINGB0Lgg0LfQsCDQsdGK0LTQtdGJ0Lgg0YDQsNC30LPQvtCy0L7RgNC4PC8xPiIsCiAgICAibm90X25vd19idXR0b24iOiAi0J3QtSDRgdC10LPQsCwg0LLRitGA0L3QuCDRgdC1INC90LAg0L3QsNGH0LDQu9C90LjRjyDQtdC60YDQsNC9IgogIH0sCiAgImNvbW1vbiI6IHsKICAgICJhdWRpbyI6ICLQl9Cy0YPQuiIsCiAgICAiYXZhdGFyIjogItCQ0LLQsNGC0LDRgCIsCiAgICAiZGlzcGxheV9uYW1lIjogItCY0LzQtS/Qv9GB0LXQstC00L7QvdC40LwiLAogICAgImhvbWUiOiAi0J3QsNGH0LDQu9C+IiwKICAgICJsb2FkaW5nIjogItCX0LDRgNC10LbQtNCw0L3QteKApiIsCiAgICAicGFzc3dvcmQiOiAi0J/QsNGA0L7Qu9CwIiwKICAgICJwcm9maWxlIjogItCf0YDQvtGE0LjQuyIsCiAgICAic2V0dGluZ3MiOiAi0J3QsNGB0YLRgNC+0LnQutC4IiwKICAgICJ1c2VybmFtZSI6ICLQn9C+0YLRgNC10LHQuNGC0LXQu9GB0LrQviDQuNC80LUiLAogICAgInZpZGVvIjogItCS0LjQtNC10L4iCiAgfSwKICAiam9pbl9leGlzdGluZ19jYWxsX21vZGFsIjogewogICAgImpvaW5fYnV0dG9uIjogItCU0LAsINC/0YDQuNGB0YrQtdC00LjQvdC4INGB0LUiLAogICAgInRleHQiOiAi0KLQvtC30Lgg0YDQsNC30LPQvtCy0L7RgCDQstC10YfQtSDRgdGK0YnQtdGB0YLQstGD0LLQsCwg0LjRgdC60LDRgtC1INC70Lgg0LTQsCDRgdC1INC/0YDQuNGB0YrQtdC00LjQvdC40YLQtT8iLAogICAgInRpdGxlIjogItCf0YDQuNGB0YrQtdC00LjQvdGP0LLQsNC90LUg0LrRitC8INGB0YrRidC10YHRgtCy0YPQstCw0Ykg0YDQsNC30LPQvtCy0L7RgD8iCiAgfSwKICAibGF5b3V0X3Nwb3RsaWdodF9sYWJlbCI6ICLQn9GA0L7QttC10LrRgtC+0YAiLAogICJsb2JieSI6IHsKICAgICJqb2luX2J1dHRvbiI6ICLQktC70LXQtyDQsiDRgNCw0LfQs9C+0LLQvtGA0LAiCiAgfSwKICAibG9nZ2luZ19pbiI6ICLQktC70LjQt9Cw0L3QteKApiIsCiAgImxvZ2luX2F1dGhfbGlua3MiOiAiPDA+0KHRitC30LTQsNC50YLQtSDQsNC60LDRg9C90YI8LzA+INC40LvQuCA8Mj7QktC70LXQt9GC0LUg0LrQsNGC0L4g0LPQvtGB0YI8LzI+IiwKICAibG9naW5fdGl0bGUiOiAi0JLQu9C10LciLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogItCU0YDRg9CzINC/0L7RgtGA0LXQsdC40YLQtdC7INCyINGC0L7Qt9C4INGA0LDQt9Cz0L7QstC+0YAg0LjQvNCwINC/0YDQvtCx0LvQtdC8LiDQl9CwINC00LAg0LTQuNCw0LPQvdC+0YHRgtC40YbQuNGA0LDQvNC1INGC0L7Qt9C4INC/0YDQvtCx0LvQtdC8INC/0L4t0LTQvtCx0YDQtSDQvdC4INGB0LUg0LjRgdC60LAg0LTQsCDRgdGK0LHQtdGA0LXQvCBkZWJ1ZyDQu9C+0LPQvtCy0LUuIiwKICAgICJ0aXRsZSI6ICLQl9Cw0Y/QstC60LAg0LfQsCBkZWJ1ZyDQu9C+0LPQvtCy0LUiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICLQmNC30L/RgNCw0YLQtdGC0LUgZGVidWcg0LvQvtCz0L7QstC1IiwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAi0JjQt9C/0YDQsNGJ0LDQvdC14oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICJSZWNhcHRjaGEg0L7RgtGF0LLRitGA0LvQtdC90LAiLAogICJyZWNhcHRjaGFfbm90X2xvYWRlZCI6ICJSZWNhcHRjaGEg0L3QtSDQtSDQt9Cw0YDQtdC00LXQvdCwIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi0J/QsNGA0L7Qu9C40YLQtSDQvdC1INGB0YrQstC/0LDQtNCw0YIiLAogICAgInJlZ2lzdGVyaW5nIjogItCg0LXQs9C40YHRgtGA0LjRgNCw0L3QteKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPtCS0LXRh9C1INC40LzQsNGC0LUg0LDQutCw0YPQvdGCPzwvMD48MT48MD7QktC70LXQt9GC0LUg0YEg0L3QtdCz0L48LzA+INC40LvQuCA8Mj7QktC70LXQt9GC0LUg0LrQsNGC0L4g0LPQvtGB0YI8LzI+PC8xPiIsCiAgInJlZ2lzdGVyX2NvbmZpcm1fcGFzc3dvcmRfbGFiZWwiOiAi0J/QvtGC0LLRitGA0LTQuCDQv9Cw0YDQvtC70LDRgtCwIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogItCS0YDRitGJ0LDQvdC1INC90LAg0L3QsNGH0LDQu9C90LjRjyDQtdC60YDQsNC9IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogItCh0L/QvtC00LXQu9C4INC10LrRgNCw0L3QsCIsCiAgInNldHRpbmdzIjogewogICAgImRldmVsb3Blcl90YWJfdGl0bGUiOiAi0KDQsNC30YDQsNCx0L7RgtGH0LjQuiIsCiAgICAiZmVlZGJhY2tfdGFiX2g0IjogItCY0LfQv9GA0LDRgtC4INC+0LHRgNCw0YLQvdCwINCy0YDRitC30LrQsCIsCiAgICAiZmVlZGJhY2tfdGFiX3NlbmRfbG9nc19sYWJlbCI6ICLQktC60LvRjtGH0LggZGVidWcg0LvQvtCz0L7QstC1IgogIH0sCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2JvZHkiOiAi0JLRgdC1INC+0YnQtSDQvdC1INGB0YLQtSDRgNC10LPQuNGB0YLRgNC40YDQsNC90Lg/IDwyPtCh0YrQt9C00LDQudGC0LUg0LDQutCw0YPQvdGCPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLQktC70LXQt9GC0LUg0LIg0LDQutCw0YPQvdGC0LAg0YHQuCIsCiAgInZlcnNpb24iOiAi0JLQtdGA0YHQuNGPOiB7e3ZlcnNpb259fSIKfQo=",YVe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICJVxb5pdmF0ZWxza8OpIG1lbnUiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogIlphdsWZw610IiwKICAgICJnbyI6ICJQb2tyYcSNb3ZhdCIsCiAgICAibm8iOiAiTmUiLAogICAgInJlZ2lzdGVyIjogIlJlZ2lzdHJhY2UiLAogICAgInJlbW92ZSI6ICJPZHN0cmFuaXQiLAogICAgInNpZ25faW4iOiAiUMWZaWhsw6FzaXQgc2UiLAogICAgInNpZ25fb3V0IjogIk9kaGzDoXNpdCBzZSIKICB9LAogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiY3JlYXRlX2FjY291bnRfYnV0dG9uIjogIlZ5dHZvxZlpdCDDusSNZXQiLAogICAgImNyZWF0ZV9hY2NvdW50X3Byb21wdCI6ICI8MD5Qcm/EjSBuZXNrb27EjWl0IG5hc3RhdmVuw61tIGhlc2xhLCBhYnlzdGUgbW9obGkgw7rEjWV0IHBvdcW+w610IHpub3Z1PzwvMD48MT5CdWRldGUgc2kgbW9jaSBuZWNoYXQgc3bDqSBqbcOpbm8gYSBuYXN0YXZpdCBzaSBhdmF0YXIgcHJvIGJ1ZG91Y8OtIGhvdm9yeSA8LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICJUZcSPIG5lLCB2csOhdGl0IHNlIG5hIGRvbW92c2tvdSBvYnJhem92a3UiCiAgfSwKICAiY29tbW9uIjogewogICAgImRpc3BsYXlfbmFtZSI6ICJab2JyYXpvdmFuw6kgam3DqW5vIiwKICAgICJob21lIjogIkRvbW92IiwKICAgICJsb2FkaW5nIjogIk5hxI3DrXTDoW7DreKApiIsCiAgICAicGFzc3dvcmQiOiAiSGVzbG8iLAogICAgInByb2ZpbGUiOiAiUHJvZmlsIiwKICAgICJzZXR0aW5ncyI6ICJOYXN0YXZlbsOtIiwKICAgICJ1c2VybmFtZSI6ICJVxb5pdmF0ZWxza8OpIGptw6lubyIKICB9LAogICJoZWFkZXJfbGFiZWwiOiAiRG9tb3YgRWxlbWVudCBDYWxsIiwKICAiam9pbl9leGlzdGluZ19jYWxsX21vZGFsIjogewogICAgImpvaW5fYnV0dG9uIjogIkFubywgcMWZaXBvaml0IHNlIiwKICAgICJ0ZXh0IjogIlRlbnRvIGhvdm9yIGppxb4gZXhpc3R1amUsIGNoY2V0ZSBzZSBwxZlpcG9qaXQ/IiwKICAgICJ0aXRsZSI6ICJQxZlpcG9qaXQgc2UgayBleGlzdHVqw61jaW11IGhvdm9ydT8iCiAgfSwKICAibGF5b3V0X3Nwb3RsaWdodF9sYWJlbCI6ICJTb3VzdMWZZWTEm27DvSBtw7NkIiwKICAibG9iYnkiOiB7CiAgICAiam9pbl9idXR0b24iOiAiUMWZaXBvaml0IHNlIGsgaG92b3J1IgogIH0sCiAgImxvZ2dpbmdfaW4iOiAiUMWZaWhsYcWhb3bDoW7DrSBzZeKApiIsCiAgImxvZ2luX2F1dGhfbGlua3MiOiAiPDA+Vnl0dm/FmWl0IMO6xI1ldDwvMD4gT3IgPDI+SmFrbyBob3N0PC8yPiIsCiAgImxvZ2luX3RpdGxlIjogIlDFmWlobMOhxaFlbsOtIiwKICAicmFnZXNoYWtlX3JlcXVlc3RfbW9kYWwiOiB7CiAgICAiYm9keSI6ICJKaW7DvSB1xb5pdmF0ZWwgdiB0b210byBob3ZvcnUgbcOhIHByb2Jsw6lteS4gQWJ5Y2hvbSBtb2hsaSBkaWFnbm9zdGlrb3ZhdCBwcm9ibMOpbSwgcsOhZGkgYnljaG9tIHNocm9tw6HFvmRpbGkgcHJvdG9rb2x5IGxhZMSbbsOtLiIsCiAgICAidGl0bGUiOiAixb3DoWRvc3QgbyBwcm90b2tvbHkgbGFkxJtuw60iCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICJQb3NsYXQgbGFkw61jw60gesOhem5hbSIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogIlBvc8OtbMOhbsOt4oCmIiwKICAicmFnZXNoYWtlX3NlbmRpbmdfbG9ncyI6ICJQb3PDrWzDoW7DrSBsYWTDrWPDrWhvIHrDoXpuYW114oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICJSZWNhcHRjaGEgYnlsYSB6YW3DrXRudXRhIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAiUmVjYXB0Y2hhIHNlIG5lbmHEjWV0bGEiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICJIZXNsYSBzZSBtdXPDrSBzaG9kb3ZhdCIsCiAgICAicmVnaXN0ZXJpbmciOiAiUmVnaXN0cm92w6Fuw63igKYiCiAgfSwKICAicmVnaXN0ZXJfYXV0aF9saW5rcyI6ICI8MD5Vxb4gbcOhdGUgw7rEjWV0PzwvMD48MT48MD5QxZlpaGzDoXNpdCBzZTwvMD4gT3IgPDI+SmFrbyBob3N0PC8yPjwvMT4iLAogICJyZWdpc3Rlcl9jb25maXJtX3Bhc3N3b3JkX2xhYmVsIjogIlBvdHZyZGl0IGhlc2xvIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogIlZyw6F0aXQgc2UgbmEgZG9tw6Fjw60gb2JyYXpvdmt1IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIlNkw61sZXQgb2JyYXpvdmt1IiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICJWw712b2rDocWZIiwKICAgICJmZWVkYmFja190YWJfaDQiOiAiRMOhdCBmZWVkYmFjayIsCiAgICAiZmVlZGJhY2tfdGFiX3NlbmRfbG9nc19sYWJlbCI6ICJaYWhybm91dCBsYWTDrWPDrSB6w6F6bmFteSIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogIk5lanN0ZSByZWdpc3Ryb3ZhbsOtPyA8Mj5WeXR2b8WZaXQgw7rEjWV0PC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICJQxZlpaGzDoXNpdCBzZSBrZSBzdsOpbXUgw7rEjXR1IiwKICAidmVyc2lvbiI6ICJWZXJ6ZToge3t2ZXJzaW9ufX0iCn0K",XVe=""+new URL("de-app-BVrY_LcE.json",import.meta.url).href,JVe=""+new URL("el-app-Bgiig2Nz.json",import.meta.url).href,ZVe=""+new URL("en-app-CaNSxxxY.json",import.meta.url).href,QVe=""+new URL("es-app-k4RDObng.json",import.meta.url).href,eGe=""+new URL("et-app-lXLRqT0e.json",import.meta.url).href,tGe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLZgdmH2LHYs9iqINqp2KfYsdio2LEiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogItio2LPYqtmGIiwKICAgICJnbyI6ICLYsdmB2KrZhiIsCiAgICAibm8iOiAi2K7bjNixIiwKICAgICJyZWdpc3RlciI6ICLYq9io2KrigIzZhtin2YUiLAogICAgInJlbW92ZSI6ICLYrdiw2YEiLAogICAgInNpZ25faW4iOiAi2YjYsdmI2K8iLAogICAgInNpZ25fb3V0IjogItiu2LHZiNisIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAi2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+2obYsdinINuM2qkg2LHZhdiyINi52KjZiNixINio2LHYp9uMINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2KrZhti424zZhSDZhtmF24zigIzaqdmG24zYr9ifPC8wPjwxPti02YXYpyDZhduM4oCM2KrZiNin2YbbjNivINmG2KfZhSDYrtmI2K8g2LHYpyDYrdmB2Lgg2qnZhtuM2K8g2Ygg24zaqSDYotmI2KfYqtin2LEg2KjYsdin24wg2KrZhdin2LPigIzZh9in24wg2KLbjNmG2K/ZhyDYqNiz2KfYstuM2K88LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLYp9mE2KfZhiDZhtmH2Iwg2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCDYqNix2q/Ysdiv24zYryIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAi2LXYr9inIiwKICAgICJhdmF0YXIiOiAi2KLZiNin2KrYp9ixIiwKICAgICJkaXNwbGF5X25hbWUiOiAi2YbYp9mFINmG2YXYp9uM2LTbjCIsCiAgICAiaG9tZSI6ICLYrtin2YbZhyIsCiAgICAibG9hZGluZyI6ICLYqNin2LHar9iy2KfYsduM4oCmIiwKICAgICJwYXNzd29yZCI6ICLYsdmF2LIg2LnYqNmI2LEiLAogICAgInByb2ZpbGUiOiAi2b7YsdmI2YHYp9uM2YQiLAogICAgInNldHRpbmdzIjogItiq2YbYuNuM2YXYp9iqIiwKICAgICJ1c2VybmFtZSI6ICLZhtin2YUg2qnYp9ix2KjYsduMIiwKICAgICJ2aWRlbyI6ICLZiNuM2K/bjNmIIgogIH0sCiAgImhlYWRlcl9sYWJlbCI6ICLYrtin2YbZh9mUINiq2YXYp9izINin2YTZhdmG2KoiLAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi2KjZhNmH2Iwg2KjZhyDYqtmF2KfYsyDYqNm+24zZiNmG2K/bjNivIiwKICAgICJ0ZXh0IjogItin24zZhiDYqtmF2KfYsyDYp9iyINmC2KjZhCDZiNis2YjYryDYr9in2LHYr9iMINmF24zigIzYrtmI2KfZh9uM2K8g2KjZvtuM2YjZhtiv24zYr9ifIiwKICAgICJ0aXRsZSI6ICLZvtuM2YjYs9iqINio2Ycg2KrZhdin2LPYnyIKICB9LAogICJsYXlvdXRfc3BvdGxpZ2h0X2xhYmVsIjogItmG2YjYsSDYp9mB2qnZhiIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogItm+24zZiNiz2KrZhiDYqNmHINiq2YXYp9izIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAi2YjYsdmI2K/igKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPtiz2KfYrtiqINit2LPYp9ioINqp2KfYsdio2LHbjDwvMD4gT3IgPDI+2K/Ys9iq2LHYs9uMINio2Ycg2LnZhtmI2KfZhiDZhduM2YfZhdin2YY8LzI+IiwKICAibG9naW5fdGl0bGUiOiAi2YjYsdmI2K8iLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogItqp2KfYsdio2LEg2K/bjNqv2LHbjCDYr9ixINin24zZhiDYqtmF2KfYsyDZhdi02qnZhNuMINiv2KfYsdivLiDYqNix2KfbjCDYqti02K7bjNi1INio2YfYqtixINmF2LTaqdmE2Iwg2KjZh9iq2LEg2KfYs9iqINmF2Kcg2YTYp9qvINi524zYqOKAjNuM2KfYqNuMINix2Kcg2KzZhdi54oCM2KLZiNix24wg2qnZhtuM2YUuIiwKICAgICJ0aXRsZSI6ICLYr9ix2K7ZiNin2LPYqiDZhNin2q8g2LnbjNio4oCM24zYp9io24wiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICLYp9ix2LPYp9mEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YTigKYiLAogICJyYWdlc2hha2Vfc2VuZGluZ19sb2dzIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YQg2KjYp9qv4oCM2YfYp9uMINi524zYqOKAjNuM2KfYqNuM4oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICLYsduM2qnZvtqG2Kcg2LHYryDYtNivIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAi2qnZvtqG2Kcg2KjYp9ix2q/bjNix24wg2YbYtNivIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi2LHZhdiyINi52KjZiNixINio2KfbjNivINmH2YXYrtmI2KfZhtuMINiv2KfYtNiq2Ycg2KjYp9i02K8iLAogICAgInJlZ2lzdGVyaW5nIjogItir2KjYquKAjNmG2KfZheKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPtin2LIg2YLYqNmEINit2LPYp9ioINqp2KfYsdio2LHbjCDYr9in2LHbjNiv2J88LzA+PDE+PDA+2YjYsdmI2K88LzA+IE9yIDwyPtio2Ycg2LnZhtmI2KfZhiDbjNqpINmF24zZh9mF2KfZhiDZiNin2LHYryDYtNmI24zYrzwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLYqtin24zbjNivINix2YXYsti52KjZiNixIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogItio2LHar9i02Kog2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCIsCiAgInNjcmVlbnNoYXJlX2J1dHRvbl9sYWJlbCI6ICLYp9i02KrYsdin2qkg2q/YsNin2LHbjCDYtdmB2K3ZhyDZhtmF2KfbjNi0IiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICLYqtmI2LPYudmHINiv2YfZhtiv2YciLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICLYqNin2LLYrtmI2LHYryDYp9ix2KfYptmHINiv2YfbjNivIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIti02KfZhdmEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogItmH2YbZiNiyINir2KjYquKAjNmG2KfZhSDZhtqp2LHYr9mH4oCM2KfbjNiv2J8gPDI+2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLYqNmHINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2YjYp9ix2K8g2LTZiNuM2K8iLAogICJ2ZXJzaW9uIjogItmG2LPYrtmHOiB7e9mG2LPYrtmHfX0iCn0K",nGe=""+new URL("fr-app-DbyWYFAw.json",import.meta.url).href,rGe=""+new URL("id-app-C7u2K42_.json",import.meta.url).href,iGe=""+new URL("it-app-Brq71wxA.json",import.meta.url).href,sGe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLjg6bjg7zjgrbjg7zjg6Hjg4vjg6Xjg7wiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogIumWieOBmOOCiyIsCiAgICAiZ28iOiAi57aa6KGMIiwKICAgICJubyI6ICLjgYTjgYTjgYgiLAogICAgInJlZ2lzdGVyIjogIueZu+mMsiIsCiAgICAicmVtb3ZlIjogIuWJiumZpCIsCiAgICAic2lnbl9pbiI6ICLjgrXjgqTjg7PjgqTjg7MiLAogICAgInNpZ25fb3V0IjogIuOCteOCpOODs+OCouOCpuODiCIKICB9LAogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiY3JlYXRlX2FjY291bnRfYnV0dG9uIjogIuOCouOCq+OCpuODs+ODiOOCkuS9nOaIkCIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAi6Z+z5aOwIiwKICAgICJhdmF0YXIiOiAi44Ki44OQ44K/44O8IiwKICAgICJkaXNwbGF5X25hbWUiOiAi6KGo56S65ZCNIiwKICAgICJob21lIjogIuODm+ODvOODoCIsCiAgICAibG9hZGluZyI6ICLoqq3jgb/ovrzjgpPjgafjgYTjgb7jgZnigKYiLAogICAgInBhc3N3b3JkIjogIuODkeOCueODr+ODvOODiSIsCiAgICAicHJvZmlsZSI6ICLjg5fjg63jg5XjgqPjg7zjg6siLAogICAgInNldHRpbmdzIjogIuioreWumiIsCiAgICAidXNlcm5hbWUiOiAi44Om44O844K244O85ZCNIiwKICAgICJ2aWRlbyI6ICLjg5Pjg4fjgqoiCiAgfSwKICAiaGVhZGVyX2xhYmVsIjogIkVsZW1lbnQgQ2FsbCDjg5vjg7zjg6AiLAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi44Gv44GE44CB6YCa6Kmx44Gr5Y+C5YqgIiwKICAgICJ0ZXh0IjogIuOBk+OBrumAmuipseOBr+aXouOBq+WtmOWcqOOBl+OBvuOBmeOAguWPguWKoOOBl+OBvuOBmeOBi++8nyIsCiAgICAidGl0bGUiOiAi5pei5a2Y44Gu6YCa6Kmx44Gr5Y+C5Yqg44GX44G+44GZ44GL77yfIgogIH0sCiAgImxheW91dF9zcG90bGlnaHRfbGFiZWwiOiAi44K544Od44OD44OI44Op44Kk44OIIiwKICAibG9iYnkiOiB7CiAgICAiam9pbl9idXR0b24iOiAi6YCa6Kmx44Gr5Y+C5YqgIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAi44Ot44Kw44Kk44Oz44GX44Gm44GE44G+44GZ4oCmIiwKICAibG9naW5fYXV0aF9saW5rcyI6ICI8MD7jgqLjgqvjgqbjg7Pjg4jjgpLkvZzmiJA8LzA+44G+44Gf44GvPDI+44Ky44K544OI44Go44GX44Gm44Ki44Kv44K744K5PC8yPiIsCiAgImxvZ2luX3RpdGxlIjogIuODreOCsOOCpOODsyIsCiAgInJhZ2VzaGFrZV9yZXF1ZXN0X21vZGFsIjogewogICAgInRpdGxlIjogIuODh+ODkOODg+OCsOODreOCsOOCkuimgeaxgiIKICB9LAogICJyYWdlc2hha2Vfc2VuZF9sb2dzIjogIuODh+ODkOODg+OCsOODreOCsOOCkumAgeS/oSIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogIumAgeS/oeOBl+OBpuOBhOOBvuOBmeKApiIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nX2xvZ3MiOiAi44OH44OQ44OD44Kw44Ot44Kw44KS6YCB5L+h44GX44Gm44GE44G+44GZ4oCmIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi44OR44K544Ov44O844OJ44GM5LiA6Ie044GZ44KL5b+F6KaB44GM44GC44KK44G+44GZIiwKICAgICJyZWdpc3RlcmluZyI6ICLnmbvpjLLjgZfjgabjgYTjgb7jgZnigKYiCiAgfSwKICAicmVnaXN0ZXJfYXV0aF9saW5rcyI6ICI8MD7ml6LjgavjgqLjgqvjgqbjg7Pjg4jjgpLjgYrmjIHjgaHjgafjgZnjgYvvvJ88LzA+PDE+PDA+44Ot44Kw44Kk44OzPC8wPuOBvuOBn+OBrzwyPuOCsuOCueODiOOBqOOBl+OBpuOCouOCr+OCu+OCuTwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLjg5Hjgrnjg6/jg7zjg4njgpLnorroqo0iLAogICJyZXR1cm5faG9tZV9idXR0b24iOiAi44Ob44O844Og55S76Z2i44Gr5oi744KLIiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIueUu+mdouWFseaciSIsCiAgInNldHRpbmdzIjogewogICAgImRldmVsb3Blcl90YWJfdGl0bGUiOiAi6ZaL55m66ICFIiwKICAgICJmZWVkYmFja190YWJfaDQiOiAi44OV44Kj44O844OJ44OQ44OD44Kv44KS6YCB5L+hIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIuODh+ODkOODg+OCsOODreOCsOOCkuWQq+OCgeOCiyIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogIuOCouOCq+OCpuODs+ODiOOBjOOBguOCiuOBvuOBm+OCk+OBi++8nyA8Mj7jgqLjgqvjgqbjg7Pjg4jjgpLkvZzmiJA8LzI+IiwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfbG9naW5fYnV0dG9uIjogIuOCouOCq+OCpuODs+ODiOOBq+ODreOCsOOCpOODsyIsCiAgInZlcnNpb24iOiAi44OQ44O844K444On44Oz77yae3t2ZXJzaW9ufX0iCn0K",oGe=""+new URL("lv-app--dkl5K2p.json",import.meta.url).href,aGe=""+new URL("pl-app-DGeQk6oM.json",import.meta.url).href,cGe=""+new URL("ro-app-C7W3EjXp.json",import.meta.url).href,lGe=""+new URL("ru-app-B-FtZqJU.json",import.meta.url).href,uGe=""+new URL("sk-app-C-Uhf1j4.json",import.meta.url).href,dGe="data:application/json;base64,ewogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiaGVhZGxpbmUiOiAie3tkaXNwbGF5TmFtZX19LCBkaXR0IHNhbXRhbCBoYXIgYXZzbHV0YXRzLiIKICB9LAogICJzdGFyX3JhdGluZ19pbnB1dF9sYWJlbF9vbmUiOiAie3tjb3VudH19IHN0asOkcm5hIiwKICAic3Rhcl9yYXRpbmdfaW5wdXRfbGFiZWxfb3RoZXIiOiAie3tjb3VudH19IHN0asOkcm5vciIKfQo=",hGe="data:application/json;base64,ewogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAiS2FwYXQiLAogICAgImdvIjogIkdpdCIsCiAgICAibm8iOiAiSGF5xLFyIiwKICAgICJyZWdpc3RlciI6ICJLYXlkb2wiLAogICAgInJlbW92ZSI6ICLDh8Sxa2FyIiwKICAgICJzaWduX2luIjogIkdpciIsCiAgICAic2lnbl9vdXQiOiAiw4fEsWsiCiAgfSwKICAiY2FsbF9lbmRlZF92aWV3IjogewogICAgImNyZWF0ZV9hY2NvdW50X2J1dHRvbiI6ICJIZXNhcCBhw6ciLAogICAgImNyZWF0ZV9hY2NvdW50X3Byb21wdCI6ICI8MD5IZXNhYsSxbsSxesSxIHR1dG1hayBpw6dpbiBuaXllIGJpciBwYXJvbGEgYcOnbcSxeW9yc3VudXo/PC8wPjwxPkLDtnlsZWNlIGlsZXJpa2kgYXJhbWFsYXJkYSBhZMSxbsSxesSxIHZlIGF2YXRhcsSxbsSxesSxIGt1bGxhbmFiaWxlY2Vrc2luaXo8LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLFnmltZGkgZGXEn2lsLCBldiBla3JhbsSxbmEgZMO2biIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAiU2VzIiwKICAgICJkaXNwbGF5X25hbWUiOiAiRWtyYW4gYWTEsSIsCiAgICAiaG9tZSI6ICJFdiIsCiAgICAibG9hZGluZyI6ICJZw7xrbGVuaXlvcuKApiIsCiAgICAicGFzc3dvcmQiOiAiUGFyb2xhIiwKICAgICJzZXR0aW5ncyI6ICJBeWFybGFyIgogIH0sCiAgImpvaW5fZXhpc3RpbmdfY2FsbF9tb2RhbCI6IHsKICAgICJ0ZXh0IjogIkJ1IGFyYW1hIHphdGVuIHZhciwga2F0xLFsbWFrIGlzdGVyIG1pc2luaXo/IiwKICAgICJ0aXRsZSI6ICJNZXZjdXQgYXJhbWF5YSBrYXTEsWw/IgogIH0sCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogIkFyYW1heWEga2F0xLFsIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAiR2lyaWxpeW9y4oCmIiwKICAibG9naW5fYXV0aF9saW5rcyI6ICI8MD5IZXNhcCBvbHXFn3R1cjwvMD4geWFodXQgPDI+S29udWsgb2xhcmFrIGdpcjwvMj4iLAogICJsb2dpbl90aXRsZSI6ICJHaXIiLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogIkJ1IGFyYW1hZGFraSBiYcWfa2EgYmlyIGt1bGxhbsSxY8SxIHNvcnVuIHlhxZ/EsXlvci4gU29ydW51IGRhaGEgaXlpIMOnw7Z6ZWJpbG1lbWl6IGnDp2luIGhhdGEgYXnEsWtsYW1hIGvDvHTDvMSfw7xuw7wgYWxtYWsgaXN0ZXJpei4iLAogICAgInRpdGxlIjogIkhhdGEgYXnEsWtsYW1hIGvDvHTDvGsgaXN0ZW1pIgogIH0sCiAgInJhZ2VzaGFrZV9zZW5kX2xvZ3MiOiAiSGF0YSBhecSxa2xhbWEga8O8dMO8xJ/DvG7DvCBnw7ZuZGVyIiwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAiR8O2bmRlcmlsaXlvcuKApiIsCiAgInJlY2FwdGNoYV9kaXNtaXNzZWQiOiAicmVDQVBUQ0hBIGF0bGFuZMSxIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAicmVDQVBUQ0hBIHnDvGtsZW5tZWRpIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAiUGFyb2xhbGFyIGF5bsSxIG9sbWFsxLEiLAogICAgInJlZ2lzdGVyaW5nIjogIktheWRlZGl5b3LigKYiCiAgfSwKICAicmVnaXN0ZXJfYXV0aF9saW5rcyI6ICI8MD5NZXZjdXQgaGVzYWLEsW7EsXogbcSxIHZhcj88LzA+PDE+PDA+R2lyPC8wPiB5YWh1dCA8Mj5Lb251ayBnaXJpxZ9pPC8yPjwvMT4iLAogICJyZWdpc3Rlcl9jb25maXJtX3Bhc3N3b3JkX2xhYmVsIjogIlBhcm9sYXnEsSB0ZWtyYXIgZWRpbiIsCiAgInJldHVybl9ob21lX2J1dHRvbiI6ICJFdiBla3JhbsSxbmEgZ2VyaSBkw7ZuIiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIkVrcmFuIHBheWxhxZ8iLAogICJzZXR0aW5ncyI6IHsKICAgICJkZXZlbG9wZXJfdGFiX3RpdGxlIjogIkdlbGnFn3RpcmljaSIsCiAgICAiZmVlZGJhY2tfdGFiX2g0IjogIkdlcmkgYmlsZGlyaW0gdmVyIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIkhhdGEgYXnEsWtsYW1hIGvDvHTDvMSfw7xuw7wgZGFoaWwgZXQiCiAgfSwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfYm9keSI6ICJLYXlkb2xtYWTEsW7EsXogbcSxPyA8Mj5IZXNhcCBhw6fEsW48LzI+IiwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfbG9naW5fYnV0dG9uIjogIkhlc2FixLFuxLF6YSBnaXJpbiIKfQo=",fGe=""+new URL("uk-app-BxyP4dDT.json",import.meta.url).href,pGe="data:application/json;base64,ewogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAixJDDs25nIiwKICAgICJubyI6ICJLaMO0bmciLAogICAgInJlZ2lzdGVyIjogIsSQxINuZyBrw70iLAogICAgInNpZ25faW4iOiAixJDEg25nIG5o4bqtcCIsCiAgICAic2lnbl9vdXQiOiAixJDEg25nIHh14bqldCIsCiAgICAic3VibWl0IjogIkfhu61pIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAiVOG6oW8gdMOgaSBraG/huqNuIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+VOG6oWkgc2FvIGzhuqFpIGtow7RuZyBob8OgbiB0aGnhu4duIGLhurFuZyBjw6FjaCDEkeG6t3QgbeG6rXQga2jhuql1IMSR4buDIGdp4buvIHTDoGkga2hv4bqjbiBj4bunYSBi4bqhbj88LzA+PDE+QuG6oW4gc+G6vSBjw7MgdGjhu4MgZ2nhu68gdMOqbiB2w6AgxJHhurd0IOG6o25oIMSR4bqhaSBkaeG7h24gY2hvIG5o4buvbmcgY3Xhu5ljIGfhu41pIHRp4bq/cCB0aGVvLjwvMT4iLAogICAgImZlZWRiYWNrX2RvbmUiOiAiPDA+Q+G6o20gaMahbiB2w6wgxJHDoyBwaOG6o24gaOG7k2khPC8wPiIsCiAgICAiZmVlZGJhY2tfcHJvbXB0IjogIjwwPkNow7puZyB0w7RpIG114buRbiBuZ2hlIHBo4bqjbiBo4buTaSBj4bunYSBi4bqhbiDEkeG7gyBjw7JuIGPhuqNpIHRoaeG7h24gdHLhuqNpIG5naGnhu4dtIGNobyBi4bqhbi48LzA+IiwKICAgICJoZWFkbGluZSI6ICJ7e2Rpc3BsYXlOYW1lfX0sIGN14buZYyBn4buNaSDEkcOjIGvhur90IHRow7pjLiIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAiw4JtIHRoYW5oIiwKICAgICJhdmF0YXIiOiAi4bqibmggxJHhuqFpIGRp4buHbiIsCiAgICAiZGlzcGxheV9uYW1lIjogIlTDqm4gaGnhu4NuIHRo4buLIiwKICAgICJsb2FkaW5nIjogIsSQYW5nIHThuqNp4oCmIiwKICAgICJwYXNzd29yZCI6ICJN4bqtdCBraOG6qXUiLAogICAgInByb2ZpbGUiOiAiSOG7kyBzxqEiLAogICAgInNldHRpbmdzIjogIkPDoGkgxJHhurd0IiwKICAgICJ1c2VybmFtZSI6ICJUw6puIG5nxrDhu51pIGTDuW5nIiwKICAgICJ2aWRlbyI6ICJUcnV54buBbiBow6xuaCIKICB9LAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAiVsOibmcsIHRoYW0gZ2lhIGN14buZYyBn4buNaSIsCiAgICAidGV4dCI6ICJDdeG7mWMgZ+G7jWkgxJHDoyB04buTbiB04bqhaSwgYuG6oW4gY8OzIG114buRbiB0aGFtIGdpYSBraMO0bmc/IiwKICAgICJ0aXRsZSI6ICJUaGFtIGdpYSBjdeG7mWMgZ+G7jWk/IgogIH0sCiAgImxheW91dF9zcG90bGlnaHRfbGFiZWwiOiAiVGnDqnUgxJFp4buDbSIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogIlRoYW0gZ2lhIGN14buZYyBn4buNaSIKICB9LAogICJsb2dnaW5nX2luIjogIsSQYW5nIMSRxINuZyBuaOG6rXDigKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPlThuqFvIHTDoGkga2hv4bqjbjwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBraMOhYzwvMj4iLAogICJsb2dpbl90aXRsZSI6ICLEkMSDbmcgbmjhuq1wIiwKICAicmFnZXNoYWtlX3JlcXVlc3RfbW9kYWwiOiB7CiAgICAiYm9keSI6ICJN4buZdCBuZ8aw4budaSBkw7luZyBraMOhYyB0cm9uZyBjdeG7mWMgZ+G7jWkgxJFhbmcgZ+G6t3AgduG6pW4gxJHhu4EuIMSQ4buDIGPDsyB0aOG7gyBjaOG6qW4gxJFvw6FuIHThu5F0IGjGoW4gY2jDum5nIHTDtGkgbXXhu5FuIHRodSB0aOG6rXAgbmjhuq10IGvDvSBn4buhIGzhu5dpLiIsCiAgICAidGl0bGUiOiAiWcOqdSBj4bqndSBuaOG6rXQga8O9IGfhu6EgbOG7l2kiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAixJBhbmcgZ+G7rWnigKYiLAogICJyZWNhcHRjaGFfbm90X2xvYWRlZCI6ICJDaMawYSB04bqjaSDEkcaw4bujYyBSZWNhcHRjaGEiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICJN4bqtdCBraOG6qXUgcGjhuqNpIGto4bubcCIsCiAgICAicmVnaXN0ZXJpbmciOiAixJBhbmcgxJHEg25nIGvDveKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPsSQw6MgY8OzIHTDoGkga2hv4bqjbj88LzA+PDE+PDA+xJDEg25nIG5o4bqtcDwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBLaMOhY2g8LzI+PC8xPiIsCiAgInJlZ2lzdGVyX2NvbmZpcm1fcGFzc3dvcmRfbGFiZWwiOiAiWMOhYyBuaOG6rW4gbeG6rXQga2jhuql1IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIkNoaWEgc+G6uyBtw6BuIGjDrG5oIiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICJOaMOgIHBow6F0IHRyaeG7g24iLAogICAgImZlZWRiYWNrX3RhYl9kZXNjcmlwdGlvbl9sYWJlbCI6ICJQaOG6o24gaOG7k2kgY+G7p2EgYuG6oW4iLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICJH4butaSBwaOG6o24gaOG7k2kiLAogICAgImZlZWRiYWNrX3RhYl9zZW5kX2xvZ3NfbGFiZWwiOiAiS8OobSB0aGVvIG5o4bqtdCBrw70gZ+G7oSBs4buXaSIsCiAgICAiZmVlZGJhY2tfdGFiX3RoYW5rX3lvdSI6ICJD4bqjbSDGoW4sIGNow7puZyB0w7RpIMSRw6Mgbmjhuq1uIMSRxrDhu6NjIHBo4bqjbiBo4buTaSEiLAogICAgImZlZWRiYWNrX3RhYl90aXRsZSI6ICJQaOG6o24gaOG7k2kiCiAgfSwKICAic3VibWl0dGluZyI6ICLEkGFuZyBn4butaeKApiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2JvZHkiOiAiQ2jGsGEgxJHEg25nIGvDvT8gPDI+VOG6oW8gdMOgaSBraG/huqNuPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLEkMSDbmcgbmjhuq1wIHbDoG8gdMOgaSBraG/huqNuIGPhu6dhIGLhuqFuIiwKICAidmVyc2lvbiI6ICJQaGnDqm4gYuG6o246IHt7dmVyc2lvbn19Igp9Cg==",mGe=""+new URL("zh-Hans-app-CCvn5Yaa.json",import.meta.url).href,gGe=""+new URL("zh-Hant-app-bsZKL_R6.json",import.meta.url).href,{slice:vGe,forEach:yGe}=[];function _Ge(n){return yGe.call(vGe.call(arguments,1),e=>{if(e)for(const t in e)n[t]===void 0&&(n[t]=e[t])}),n}const lj=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,bGe=function(n,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${n}=${i}`;if(r.maxAge>0){const o=r.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(r.domain){if(!lj.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!lj.test(r.path))throw new TypeError("option path is invalid");s+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s},uj={create(n,e,t,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+t*60*1e3)),r&&(i.domain=r),document.cookie=bGe(n,encodeURIComponent(e),i)},read(n){const e=`${n}=`,t=document.cookie.split(";");for(let r=0;r<t.length;r++){let i=t[r];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null},remove(n){this.create(n,"",-1)}};var SGe={name:"cookie",lookup(n){let{lookupCookie:e}=n;if(e&&typeof document<"u")return uj.read(e)||void 0},cacheUserLanguage(n,e){let{lookupCookie:t,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;t&&typeof document<"u"&&uj.create(t,n,r,i,s)}},wGe={name:"querystring",lookup(n){var r;let{lookupQuerystring:e}=n,t;if(typeof window<"u"){let{search:i}=window.location;!window.location.search&&((r=window.location.hash)==null?void 0:r.indexOf("?"))>-1&&(i=window.location.hash.substring(window.location.hash.indexOf("?")));const o=i.substring(1).split("&");for(let a=0;a<o.length;a++){const c=o[a].indexOf("=");c>0&&o[a].substring(0,c)===e&&(t=o[a].substring(c+1))}}return t}};let Jh=null;const dj=()=>{if(Jh!==null)return Jh;try{if(Jh=typeof window<"u"&&window.localStorage!==null,!Jh)return!1;const n="i18next.translate.boo";window.localStorage.setItem(n,"foo"),window.localStorage.removeItem(n)}catch{Jh=!1}return Jh};var EGe={name:"localStorage",lookup(n){let{lookupLocalStorage:e}=n;if(e&&dj())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupLocalStorage:t}=e;t&&dj()&&window.localStorage.setItem(t,n)}};let Zh=null;const hj=()=>{if(Zh!==null)return Zh;try{if(Zh=typeof window<"u"&&window.sessionStorage!==null,!Zh)return!1;const n="i18next.translate.boo";window.sessionStorage.setItem(n,"foo"),window.sessionStorage.removeItem(n)}catch{Zh=!1}return Zh};var CGe={name:"sessionStorage",lookup(n){let{lookupSessionStorage:e}=n;if(e&&hj())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupSessionStorage:t}=e;t&&hj()&&window.sessionStorage.setItem(t,n)}},TGe={name:"navigator",lookup(n){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:r,language:i}=navigator;if(t)for(let s=0;s<t.length;s++)e.push(t[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},IGe={name:"htmlTag",lookup(n){let{htmlTag:e}=n,t;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(t=r.getAttribute("lang")),t}},RGe={name:"path",lookup(n){var i;let{lookupFromPathIndex:e}=n;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(i=t[typeof e=="number"?e:0])==null?void 0:i.replace("/",""):void 0}},kGe={name:"subdomain",lookup(n){var i,s;let{lookupFromSubdomainIndex:e}=n;const t=typeof e=="number"?e+1:1,r=typeof window<"u"&&((s=(i=window.location)==null?void 0:i.hostname)==null?void 0:s.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(r)return r[t]}};let tte=!1;try{document.cookie,tte=!0}catch{}const nte=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];tte||nte.splice(1,1);const xGe=()=>({order:nte,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:n=>n});class rte{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=_Ge(t,this.options||{},xGe()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(SGe),this.addDetector(wGe),this.addDetector(EGe),this.addDetector(CGe),this.addDetector(TGe),this.addDetector(IGe),this.addDetector(RGe),this.addDetector(kGe)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(t=t.concat(i))}}),t=t.map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}rte.type="languageDetector";var d_={},fj;function PGe(){if(fj)return d_;fj=1,Object.defineProperty(d_,"__esModule",{value:!0}),d_.shouldPolyfill=n;function n(){return!Intl.Segmenter}return d_}var LGe=PGe(),h_={},pj;function AGe(){if(pj)return h_;pj=1,Object.defineProperty(h_,"__esModule",{value:!0}),h_.shouldPolyfill=n;function n(){return typeof Intl>"u"||!("DurationFormat"in Intl)}return h_}var OGe=AGe();const ite=Object.assign({"../locales/bg/app.json":zVe,"../locales/cs/app.json":YVe,"../locales/de/app.json":XVe,"../locales/el/app.json":JVe,"../locales/en/app.json":ZVe,"../locales/es/app.json":QVe,"../locales/et/app.json":eGe,"../locales/fa/app.json":tGe,"../locales/fr/app.json":nGe,"../locales/id/app.json":rGe,"../locales/it/app.json":iGe,"../locales/ja/app.json":sGe,"../locales/lv/app.json":oGe,"../locales/pl/app.json":aGe,"../locales/ro/app.json":cGe,"../locales/ru/app.json":lGe,"../locales/sk/app.json":uGe,"../locales/sv/app.json":dGe,"../locales/tr/app.json":hGe,"../locales/uk/app.json":fGe,"../locales/vi/app.json":pGe,"../locales/zh-Hans/app.json":mGe,"../locales/zh-Hant/app.json":gGe}),MGe=(n,e)=>ite[`../locales/${n}/${e}.json`],NGe=[...new Set(Object.keys(ite).map(n=>{var t;const e=(t=n.match(/\/([^/]+)\/[^/]+\.json$/))==null?void 0:t[1];if(!e)throw new Error(`Could not parse locale URL ${n}`);return e}))],DGe={type:"backend",init(){},read(n,e,t){(async()=>{const r=MGe(n,e);if(!r)throw new Error(`Namespace ${e} for locale ${n} not found`);const i=await fetch(r,{credentials:"omit",headers:{Accept:"application/json"}});if(kL(i))throw Error(`Failed to fetch ${r}`);return await i.json()})().then(r=>t(null,r),r=>t(r,null))}};class FGe{constructor(){this.config=0,this.sentry=0,this.openTelemetry=0}allDepsAreLoaded(){return!Object.values(this).some(e=>e!==2)}}class Us{constructor(){this.isInitialized=!1,this.loadStates=new FGe}static isInitialized(){var e;return(e=Us.internalInstance)==null?void 0:e.isInitialized}static async initBeforeReact(){const e=[];LGe.shouldPolyfill()&&e.push(rv(()=>import("./polyfill-force-CajV37WF.js").then(s=>s.p),__vite__mapDeps([2,3]),import.meta.url)),OGe.shouldPolyfill()&&e.push(rv(()=>import("./polyfill-force-DQyUIgBV.js").then(s=>s.p),__vite__mapDeps([4,3]),import.meta.url)),await Promise.all(e);const t=new rte;t.addDetector({name:"urlFragment",lookup:()=>Rs().lang??void 0}),await hi.use(DGe).use(t).use(UTe).init({fallbackLng:"en",defaultNS:"app",keySeparator:".",nsSeparator:!1,pluralSeparator:"_",contextSeparator:"|",supportedLngs:NGe,interpolation:{escapeValue:!1},detection:{order:["urlFragment","navigator"],caches:[]}});const{fonts:r,fontScale:i}=Rs();i!==null&&document.documentElement.style.setProperty("--font-scale",i.toString()),r.length>0&&document.documentElement.style.setProperty("--font-family",r.map(s=>`"${s}"`).join(", ")),document.body.setAttribute("data-platform",wd)}static init(){var e;return(e=Us==null?void 0:Us.internalInstance)!=null&&e.initPromise?null:(Us.internalInstance=new Us,Us.internalInstance.initPromise=new Promise(t=>{Us.internalInstance.initStep(t)}),Us.internalInstance.initPromise)}initStep(e){var t,r,i,s;this.loadStates.config===0&&(this.loadStates.config=1,gt.init().then(()=>{this.loadStates.config=2,this.initStep(e)},o=>{M.error("Failed to load config",o)})),this.loadStates.sentry===0&&this.loadStates.config===2&&((t=gt.get().sentry)!=null&&t.DSN&&((r=gt.get().sentry)!=null&&r.environment)&&_ye({dsn:(i=gt.get().sentry)==null?void 0:i.DSN,environment:(s=gt.get().sentry)==null?void 0:s.environment,integrations:[Uye({useEffect:Re.useEffect,useLocation:di,useNavigationType:Rde,createRoutesFromChildren:Jb,matchRoutes:r6})],tracesSampleRate:1}),this.loadStates.sentry=2),this.loadStates.openTelemetry===0&&this.loadStates.config===2&&(yE.globalInit(),this.loadStates.openTelemetry=2),this.loadStates.allDepsAreLoaded()&&(e(),this.isInitialized=!0)}}const UGe=()=>{const[n,e]=_.useState(()=>Rs().theme),t=_.useRef(document.body.classList.item(0));_.useEffect(()=>{if(Je){const r=i=>{i.preventDefault(),"name"in i.detail.data&&typeof i.detail.data.name=="string"&&e(i.detail.data.name),Je.api.transport.reply(i.detail,{})};return Je.lazyActions.on(hr.ThemeChange,r),()=>{Je.lazyActions.off(hr.ThemeChange,r)}}},[]),_.useLayoutEffect(()=>{const r=n!=null&&n.includes("light")?"light":"dark",i=n!=null&&n.includes("high-contrast")?"-hc":"",s="cpd-theme-"+r+i;s!==t.current&&(document.body.classList.remove("cpd-theme-light","cpd-theme-dark","cpd-theme-light-hc","cpd-theme-dark-hc"),document.body.classList.add(s),t.current=s),document.body.classList.remove("no-theme")},[t,n])},f_=jye(PV),jGe=({children:n})=>{const{pathname:e}=di();return _.useEffect(()=>{let t="";!["/login","/register"].includes(e)&&!Je&&(t="var(--background-gradient)"),document.getElementsByTagName("body")[0].style.backgroundImage=t},[e]),w.jsx(w.Fragment,{children:n})},$Ge=({children:n})=>(UGe(),n),BGe=()=>{const[n,e]=_.useState(!1);return _.useEffect(()=>{var t;(t=Us.init())==null||t.then(async()=>{n||(e(!0),await(Je==null?void 0:Je.api.sendContentLoaded()))}).catch(M.error)}),w.jsx(fhe,{children:w.jsx(jGe,{children:w.jsx($Ge,{children:w.jsx(Kq,{children:n?w.jsx(_.Suspense,{fallback:null,children:w.jsx(cNe,{children:w.jsx(e8e,{children:w.jsxs(Hw,{fallback:t=>w.jsx(Kv,{error:t,widget:Je}),children:[w.jsx(WVe,{}),w.jsxs(Vde,{children:[w.jsx(f_,{path:"/",element:w.jsx(ZZ,{})}),w.jsx(f_,{path:"/login",element:w.jsx(z9e,{})}),w.jsx(f_,{path:"/register",element:w.jsx(Y9e,{})}),w.jsx(f_,{path:"*",element:w.jsx(GVe,{})})]})]})})})}):w.jsx(_E,{})})})})})};window.setLKLogLevel=_H;Oke().catch(n=>{M.error("Failed to initialize rageshake",n)});_H("warn");ele((n,e,t)=>{global.mx_rage_logger.log(n,"livekit",e,t)});M.info("Element Call embedded-v0.9.0-release-test.8");const Zx=Eae.createRoot(document.getElementById("root"));let tv=null;window.isSecureContext?navigator.mediaDevices||(tv=new Error("Your browser does not support WebRTC.")):tv=new Error(`This app cannot run in an insecure context. To fix this, access the app via a local loopback address, or serve it over HTTPS.
|
|
219
|
+
`;return typeof a=="function"&&a(null,S),S},xR}var cj;function kVe(){if(cj)return Xh;cj=1;const n=cVe(),e=TVe(),t=IVe(),r=RVe();function i(s,o,a,c,l){const u=[].slice.call(arguments,1),h=u.length,p=typeof u[h-1]=="function";if(!p&&!n())throw new Error("Callback required as last argument");if(p){if(h<2)throw new Error("Too few arguments provided");h===2?(l=a,a=o,o=c=void 0):h===3&&(o.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=o,o=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=o,o=c=void 0):h===2&&!o.getContext&&(c=a,a=o,o=void 0),new Promise(function(m,v){try{const g=e.create(a,c);m(s(g,o,c))}catch(g){v(g)}})}try{const m=e.create(a,c);l(null,s(m,o,c))}catch(m){l(m)}}return Xh.create=e.create,Xh.toCanvas=i.bind(null,t.render),Xh.toDataURL=i.bind(null,t.renderToDataURL),Xh.toString=i.bind(null,function(s,o,a){return r.render(s,a)}),Xh}var xVe=kVe();const PVe="_qrCode_h54ia_8",LVe={qrCode:PVe},AVe=({data:n,className:e})=>{const[t,r]=_.useState(null);return _.useEffect(()=>{let i=!1;return xVe.toDataURL(n,{errorCorrectionLevel:"L"}).then(s=>{i||r(s)}).catch(s=>{i||r(null)}),()=>{i=!0}},[n]),w.jsx("div",{className:De(LVe.qrCode,e),children:t&&w.jsx("img",{src:t,alt:Ma("qr_code")})})},OVe=({room:n,open:e,onDismiss:t})=>{const{t:r}=Qe(),i=wE(n.roomId),s=_.useMemo(()=>YZ(n.roomId,i,n.name),[i,n.name,n.roomId]),[,o]=tVe(s),[a,c]=_.useState(!1),l=_.useCallback(()=>c(!1),[c]),u=_.useCallback(h=>{h.stopPropagation(),o(),t(),c(!0)},[o,t]);return w.jsxs(w.Fragment,{children:[w.jsxs(th,{title:r("invite_modal.title"),open:e,onDismiss:t,children:[w.jsx(AVe,{className:oR.qrCode,data:s}),w.jsx(Xt,{className:oR.url,size:"sm",weight:"semibold",children:s}),w.jsx(Mt,{className:oR.button,Icon:zTe,onClick:u,"data-testid":"modal_inviteLink",children:r("action.copy_link")})]}),w.jsx(aVe,{open:a,onDismiss:l,autoDismiss:2e3,Icon:eY,children:r("invite_modal.link_copied_toast")})]})},MVe=({error:n,recoveryActionHandler:e,widget:t})=>{const{t:r}=Qe();let i;switch(n.category){case mb.CONFIGURATION_ISSUE:i=WTe;break;case mb.NETWORK_CONNECTIVITY:i=ZTe;break;case mb.CLIENT_CONFIGURATION:i=hIe;break;default:i=Vw}const s=[];return n instanceof Tee&&s.push({label:r("call_ended_view.reconnect_button"),onClick:()=>e("reconnect")}),w.jsx(Uf,{children:w.jsxs(qv,{Icon:i,title:n.localisedTitle,rageshake:n.code==D4.UNKNOWN_ERROR,widget:t,children:[w.jsx("p",{children:n.localisedMessage??w.jsx(Ci,{i18nKey:"error.unexpected_ec_error",components:[w.jsx("b",{}),w.jsx("code",{})],values:{errorCode:n.code}})}),s&&s.map((o,a)=>w.jsx("button",{onClick:o.onClick,children:o.label},`action${a}`))]})})},NVe=({recoveryActionHandler:n,onError:e,children:t,widget:r})=>{const i=_.useCallback(({error:s,resetError:o})=>{const a=s instanceof Kc?s:new F4(s instanceof Error?s:new Error);return w.jsx(MVe,{widget:r??null,error:a,resetError:o,recoveryActionHandler:c=>{o(),n(c)}})},[n,r]);return w.jsx(Hw,{fallback:i,onError:s=>e==null?void 0:e(s),children:t})},DVe=({client:n,isPasswordlessUser:e,confineToRoom:t,preload:r,skipLobby:i,hideHeader:s,rtcSession:o,isJoined:a,muteStates:c,widget:l})=>{const u=bZ(o),h=Lc($4({sounds:zee,latencyHint:"interactive"}));_.useEffect(()=>{var ye,Se;u.length>=$He&&((Se=(ye=c.audio).setEnabled)==null||Se.call(ye,!1))},[]),_.useEffect(()=>(window.rtcSession=o,()=>{delete window.rtcSession}),[o]),EL(o,ts.MembershipManagerError,ye=>{z(new c$e(D4.MEMBERSHIP_MANAGER_UNRECOVERABLE,ye.message??ye))}),_.useEffect(()=>{n.getRoom(o.room.roomId)!==o.room&&M.warn(`We've ended up with multiple rooms for the same ID (${o.room.roomId}). This indicates a bug in the group call loading code, and may lead to incomplete room state.`)},[n,o.room]);const p=o.room,{displayName:m,avatarUrl:v}=Ly(n),g=YHe(p),S=zHe(p),{perParticipantE2EE:b,returnToLobby:R}=eh(),k=wE(p.roomId),[I]=Ar(fZ);Oy(g);const T=_.useMemo(()=>({userId:n.getUserId(),displayName:m,avatarUrl:v,roomId:p.roomId,roomName:g,roomAlias:p.getCanonicalAlias(),roomAvatar:S,e2eeSystem:k}),[n,m,v,g,p,S,k]),C=_.useMemo(()=>new Set(u.map(ye=>ye.sender)).size,[u]),P=rh(),O=Lc(P),D=Lc(c),F=async(ye,Se,xe)=>{try{await KHe(ye,Se,xe)}catch(Oe){if(Oe instanceof Kc)z(Oe);else{M.error("Unknown Error while entering RTC session",Oe);const Ye=new F4(Oe instanceof Error?Oe:new Error("Unknown error",{cause:Oe}));z(Ye)}}};_.useEffect(()=>{const ye=async({audioInput:Se,videoInput:xe})=>{var Ye,Ht,Un,Nt;const Oe=await Mc.getLocalDevices(void 0,!0);if(Se){const je=EF(Se,"audioinput",Oe);je?(M.debug(`Found audio input ID ${je} for name ${Se}`),O.current.audioInput.select(je)):(M.warn("Unknown audio input: "+Se),(Ht=(Ye=D.current.audio).setEnabled)==null||Ht.call(Ye,!1))}if(xe){const je=EF(xe,"videoinput",Oe);je?(M.debug(`Found video input ID ${je} for name ${xe}`),O.current.videoInput.select(je)):(M.warn("Unknown video input: "+xe),(Nt=(Un=D.current.video).setEnabled)==null||Nt.call(Un,!1))}};if(i)if(l)if(r){const Se=xe=>{(async()=>{await ye(xe.detail.data),await F(o,b,I),l.api.transport.reply(xe.detail,{})})().catch(Oe=>{M.error("Error joining RTC session",Oe)})};return l.lazyActions.on(xr.JoinCall,Se),()=>{l.lazyActions.off(xr.JoinCall,Se)}}else(async()=>{await F(o,b,I)})().catch(Se=>{M.error("Error joining RTC session",Se)});else F(o,b,I)},[l,o,r,i,b,O,D,I]);const[U,B]=_.useState(!1),[V,z]=_.useState(null),H=ja(),J=_.useCallback((ye="user")=>{var Ye;const Se=(Ye=h.current)==null?void 0:Ye.playSound("left"),xe=!!l;B(!0);const Oe=new Promise(Ht=>{jt.instance.eventCallEnded.track(p.roomId,o.memberships.length,xe,o),window.setTimeout(Ht,10)});AU(o,ye,Promise.all([Se,Oe])).then(async()=>{!e&&!t&&!jt.instance.isEnabled()&&await H("/")}).catch(Ht=>{M.error("Error leaving RTC session",Ht)})},[h,l,o,p.roomId,e,t,H]);_.useEffect(()=>{if(l&&a){l.api.setAlwaysOnScreen(!0).catch(Se=>{M.error("Error calling setAlwaysOnScreen(true)",Se)});const ye=Se=>{l.api.transport.reply(Se.detail,{}),AU(o,"user").catch(xe=>{M.error("Failed to leave RTC session",xe)})};return l.lazyActions.once(xr.HangupCall,ye),()=>{l.lazyActions.off(xr.HangupCall,ye)}}},[l,a,o]);const Y=XHe(p),[G,K]=_.useState(!1),ee=_.useCallback(()=>K(!1),[K]),q=_.useCallback(()=>K(!0),[K]),Q=Y===wc.Public?q:null;if(!QH()&&k.kind!==Vt.NONE)throw new l$e;const Ce=w.jsx(OVe,{room:p,open:G,onDismiss:ee}),Te=w.jsxs(w.Fragment,{children:[Ce,w.jsx(NQ,{client:n,matrixInfo:T,muteStates:c,onEnter:()=>void F(o,b,I),confineToRoom:t,hideHeader:s,participantCount:C,onShareClick:Q})]});let Ae;if(V){const ye=()=>{throw V};Ae=w.jsx(ye,{})}else a?Ae=w.jsxs(w.Fragment,{children:[Ce,w.jsx(UHe,{client:n,matrixInfo:T,rtcSession:o,participantCount:C,onLeave:J,hideHeader:s,muteStates:c,e2eeSystem:k,onShareClick:Q})]}):U&&l===null?e||jt.instance.isEnabled()&&l===null?Ae=w.jsx(NFe,{endedCallId:o.room.roomId,client:n,isPasswordlessUser:e,confineToRoom:t}):Ae=null:U&&l!==null?Ae=R?Te:null:r||i?Ae=null:Ae=Te;return w.jsx(NVe,{widget:l,recoveryActionHandler:ye=>{ye=="reconnect"&&(B(!1),F(o,b,I).catch(Se=>{M.error("Error re-entering RTC session",Se)}))},onError:()=>{o.isJoined()&&J("error")},children:Ae})},FVe="_modal_1tnec_8",UVe={modal:FVe},jVe=({roomId:n})=>{const{t:e}=Qe(),[t,r]=_.useState(!0),i=_.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[r]),s=wE(n);s.kind===Vt.NONE&&M.error("Generating app redirect URL for encrypted room but don't have key available!");const o=_.useMemo(()=>{const a=new URL(n===null?window.location.href:YZ(n,s));a.hash=Eke(a.hash,l=>(l.set("appPrompt","false"),l.set("confineToRoom","true"),l));const c=new URL("io.element.call:/");return c.searchParams.set("url",a.toString()),c.toString()},[s,n]);return w.jsxs(th,{className:UVe.modal,title:e("app_selection_modal.title"),open:t,children:[w.jsx(Xt,{size:"md",weight:"semibold",children:e("app_selection_modal.text")}),w.jsx(Mt,{kind:"secondary",onClick:i,children:e("app_selection_modal.continue_in_browser")}),w.jsx(Mt,{as:"a",href:o,Icon:AY,children:e("app_selection_modal.open_in_app")})]})},$Ve=3,BVe=3e3;async function ete(n,e=0,...t){try{return await n.joinRoom(...t)}catch(r){if(r instanceof mn&&r.errcode==="M_FORBIDDEN"&&e<$Ve)return await new Promise(i=>setTimeout(i,BVe)),ete(n,e+1,...t);throw r}}class yb extends Error{constructor(e,t,r,i){super(t),this.icon=e,this.messageBody=r,this.reason=i}}const HVe=(n,e,t)=>{const[r,i]=_.useState({kind:"loading"}),s=_.useRef(void 0),{t:o}=Qe(),a=_.useCallback(()=>new yb(HTe,o("group_call_loader.banned_heading"),o("group_call_loader.banned_body"),u()),[o]),c=_.useCallback(()=>new yb(Gw,o("group_call_loader.knock_reject_heading"),o("group_call_loader.knock_reject_body"),u()),[o]),l=_.useCallback(()=>new yb(vY,o("group_call_loader.call_ended_heading"),o("group_call_loader.call_ended_body"),u()),[o]),u=()=>{var h,p,m;return(m=(p=s.current)==null?void 0:p.currentState.getStateEvents(ie.RoomMember,(h=s.current)==null?void 0:h.myUserId))==null?void 0:m.getContent().reason};return _.useEffect(()=>{if(!n||!e)return;const h=async b=>{let R=null;const k=await n.getRoomIdForAlias(b.toLowerCase());return M.info(`${b} resolved to ${k.room_id}`),R=n.getRoom(k.room_id),R?M.info(`Already in room ${k.room_id}, not rejoining.`):(M.info(`Room ${k.room_id} not found, joining.`),R=await n.joinRoom(k.room_id,{viaServers:k.servers})),R},p=async(b,R,k)=>(await n.knockRoom(b,{viaServers:R}),k(),await new Promise((I,T)=>{n.on(Xe.MyMembership,(C,P,O)=>{b===C.roomId&&(s.current=C,P===We.Invite&&O===We.Knock&&ete(n,0,C.roomId,{viaServers:R}).then(D=>{M.log("Auto-joined %s",D.roomId),I(D)},T),P===We.Ban&&T(a()),P===We.Leave&&T(c()))})})),m=async()=>{let b=null;if(e[0]==="#")b=await h(e),s.current=b;else{const R=e;b=n.getRoom(R),s.current=b??void 0;const k=b==null?void 0:b.getMyMembership();if(k===We.Join)return b;if(Je)throw new Error("Room not found. The widget-api did not pass over the relevant room events/information.");if(k===We.Ban)throw a();if(k===We.Invite)b=await n.joinRoom(R,{viaServers:t});else{let I;try{I=await n.getRoomSummary(R,t)}catch(T){M.warn("Could not load room summary to decide whether we want to join or knock.\n EC will fallback to join as if this would be a public room.\n Reach out to your homeserver admin to ask them about supporting the `/summary` endpoint (im.nheko.summary):",T)}if(I===void 0||I.join_rule===wc.Public)b=await n.joinRoom(R,{viaServers:t});else if(I.join_rule===wc.Knock){const T=I;let C=()=>{};const P=new Promise(O=>{T.membership!==We.Knock?C=O:O()});i({kind:"canKnock",roomSummary:T,knock:C}),await P,b=await p(I.room_id,t,()=>i({kind:"waitForInvite",roomSummary:T}))}else throw new Error(`Room ${I.room_id} is not joinable. This likely means, that the conference owner has changed the room settings to private.`)}}return M.info(`Joined ${e}, waiting room to be ready for group calls`),await n.waitUntilRoomReadyForGroupCalls(b.roomId),M.info(`${e}, is ready for group calls`),b},v=async()=>{const b=await m();return s.current=b,M.debug(`Fetched / joined room ${e}`),n.matrixRTC.getRoomSession(b)},g=async()=>{n.getSyncState()!==Pr.Syncing&&(M.debug("useLoadGroupCall: waiting for client to start syncing..."),await new Promise(b=>{const R=()=>{if(n.getSyncState()===Pr.Syncing)return n.off(Ge.Sync,R),b()};n.on(Ge.Sync,R)}),M.debug("useLoadGroupCall: client is now syncing."))},S=async()=>{await new Promise((b,R)=>{n.on(Xe.MyMembership,(k,I)=>{I===We.Leave&&R(l()),I===We.Ban&&R(a())})})};r.kind==="loading"&&(M.log("Start loading group call"),g().then(v).then(b=>i({kind:"loaded",rtcSession:b})).then(S).catch(b=>i({kind:"failed",error:b})))},[a,n,c,l,e,r,o,t]),r};function VVe(n){const[,e]=_.useState(0);return _.useEffect(()=>{if(n!==void 0){const t=r=>{M.info(`Session in room ${n.room.roomId} changed to ${r?"joined":"left"}`),e(i=>i+1)};return n.on(ts.JoinStateChanged,t),()=>{n.off(ts.JoinStateChanged,t)}}},[n]),(n==null?void 0:n.isJoined())??!1}const GVe=()=>{const{confineToRoom:n,appPrompt:e,preload:t,hideHeader:r,displayName:i,skipLobby:s}=eh(),{t:o}=Qe(),{roomAlias:a,roomId:c,viaServers:l}=Tke(),u=c??a;u||M.error("No room specified");const{registerPasswordlessUser:h}=eQ(),[p,m]=_.useState(!1),{loading:v,authenticated:g,client:S,error:b,passwordlessUser:R}=o4(),{avatarUrl:k,displayName:I}=Ly(S),T=HVe(S,u,l),C=VVe(T.kind==="loaded"?T.rtcSession:void 0),P=HHe(C);_.useEffect(()=>{!v&&!g&&i&&!Je&&(m(!0),h(i).catch(V=>{M.error("Failed to register passwordless user",V)}).finally(()=>{m(!1)}))},[v,g,i,m,h]);const[O,D]=gE();_.useEffect(()=>{O===null&&D&&D(!0)},[O,D]);const F=_.useRef(!1);_.useEffect(()=>{T.kind==="loaded"&&F.current&&M.log("Play join sound 'Not yet implemented'")},[T.kind]);const U=()=>{switch(T.kind){case"loaded":return w.jsx(DVe,{widget:Je,client:S,rtcSession:T.rtcSession,isJoined:C,isPasswordlessUser:R,confineToRoom:n,preload:t,skipLobby:s||F.current,hideHeader:r,muteStates:P});case"waitForInvite":case"canKnock":{F.current=F.current||T.kind==="waitForInvite";const V=T.kind==="canKnock"?T.knock:null,z=T.kind==="canKnock"?o("lobby.ask_to_join"):w.jsxs(w.Fragment,{children:[o("lobby.waiting_for_invite"),w.jsx(eY,{})]});return w.jsx(NQ,{client:S,matrixInfo:{userId:S.getUserId()??"",displayName:I??"",avatarUrl:k??"",roomAlias:null,roomId:T.roomSummary.room_id,roomName:T.roomSummary.name??"",roomAvatar:T.roomSummary.avatar_url??null,e2eeSystem:{kind:T.roomSummary["im.nheko.summary.encryption"]?Vt.PER_PARTICIPANT:Vt.NONE}},onEnter:()=>V==null?void 0:V(),enterLabel:z,waitingForInvite:T.kind==="waitForInvite",confineToRoom:n,hideHeader:r,participantCount:null,muteStates:P,onShareClick:null})}case"loading":return w.jsx(Uf,{children:w.jsx("h1",{children:o("common.loading")})});case"failed":return F.current=!1,T.error.errcode==="M_NOT_FOUND"?w.jsx(Uf,{children:w.jsx(qv,{Icon:oIe,title:o("error.call_not_found"),widget:Je,children:w.jsx(Ci,{i18nKey:"error.call_not_found_description",children:w.jsxs("p",{children:["That link doesn't appear to belong to any existing call. Check that you have the right link, or"," ",w.jsx(Aa,{to:"/",children:"create a new one"}),"."]})})})}):T.error instanceof yb?w.jsx(Uf,{children:w.jsxs(qv,{Icon:T.error.icon,title:T.error.message,widget:Je,children:[w.jsx("p",{children:T.error.messageBody}),T.error.reason&&w.jsx("p",{children:o("group_call_loader.reason",{reason:T.error.reason})})]})}):w.jsx(Kv,{widget:Je,error:T.error});default:return w.jsx(w.Fragment,{children:" "})}};let B;return v||p?B=w.jsx(_E,{}):b?B=w.jsx(Kv,{widget:Je,error:b}):S?u?B=U():B=w.jsx(ZZ,{}):B=w.jsx(t7e,{}),w.jsxs(w.Fragment,{children:[B,e&>.get().app_prompt&&(wd==="android"||wd==="ios")&&c&&w.jsx(jVe,{roomId:c})]})},qVe="_banner_sye6n_8",KVe={banner:qVe},WVe=({children:n,className:e,...t})=>{const{t:r}=Qe(),i=jp();let s=!1;return(i==null?void 0:i.state)==="valid"&&(s=i.disconnected),w.jsx(w.Fragment,{children:s&&w.jsxs("div",{className:De(KVe.banner,e),...t,children:[n,r("disconnected_banner")]})})},zVe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLQn9C+0YLRgNC10LHQuNGC0LXQu9GB0LrQviDQvNC10L3RjiIKICB9LAogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAi0JfQsNGC0LLQvtGA0LgiLAogICAgImdvIjogItCd0LDQv9GA0LXQtCIsCiAgICAibm8iOiAi0J3QtSIsCiAgICAicmVnaXN0ZXIiOiAi0KDQtdCz0LjRgdGC0YDQsNGG0LjRjyIsCiAgICAicmVtb3ZlIjogItCf0YDQtdC80LDRhdC90LgiLAogICAgInNpZ25faW4iOiAi0JLQu9C10LciLAogICAgInNpZ25fb3V0IjogItCY0LfQu9C10LciCiAgfSwKICAiY2FsbF9lbmRlZF92aWV3IjogewogICAgImNyZWF0ZV9hY2NvdW50X2J1dHRvbiI6ICLQodGK0LfQtNCw0Lkg0LDQutCw0YPQvdGCIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+0JfQsNGJ0L4g0L3QtSDQvdCw0YHRgtGA0L7QudGC0LUg0L/QsNGA0L7Qu9CwINC30LAg0LTQsCDQt9Cw0L/QsNC30LjRgtC1INCw0LrQsNGD0L3RgtCwINGB0Lg/PC8wPjwxPtCp0LUg0LzQvtC20LXRgtC1INC00LAg0LfQsNC/0LDQt9C40YLQtSDQuNC80LXRgtC+INC4INCw0LLQsNGC0LDRgNCwINGB0Lgg0LfQsCDQsdGK0LTQtdGJ0Lgg0YDQsNC30LPQvtCy0L7RgNC4PC8xPiIsCiAgICAibm90X25vd19idXR0b24iOiAi0J3QtSDRgdC10LPQsCwg0LLRitGA0L3QuCDRgdC1INC90LAg0L3QsNGH0LDQu9C90LjRjyDQtdC60YDQsNC9IgogIH0sCiAgImNvbW1vbiI6IHsKICAgICJhdWRpbyI6ICLQl9Cy0YPQuiIsCiAgICAiYXZhdGFyIjogItCQ0LLQsNGC0LDRgCIsCiAgICAiZGlzcGxheV9uYW1lIjogItCY0LzQtS/Qv9GB0LXQstC00L7QvdC40LwiLAogICAgImhvbWUiOiAi0J3QsNGH0LDQu9C+IiwKICAgICJsb2FkaW5nIjogItCX0LDRgNC10LbQtNCw0L3QteKApiIsCiAgICAicGFzc3dvcmQiOiAi0J/QsNGA0L7Qu9CwIiwKICAgICJwcm9maWxlIjogItCf0YDQvtGE0LjQuyIsCiAgICAic2V0dGluZ3MiOiAi0J3QsNGB0YLRgNC+0LnQutC4IiwKICAgICJ1c2VybmFtZSI6ICLQn9C+0YLRgNC10LHQuNGC0LXQu9GB0LrQviDQuNC80LUiLAogICAgInZpZGVvIjogItCS0LjQtNC10L4iCiAgfSwKICAiam9pbl9leGlzdGluZ19jYWxsX21vZGFsIjogewogICAgImpvaW5fYnV0dG9uIjogItCU0LAsINC/0YDQuNGB0YrQtdC00LjQvdC4INGB0LUiLAogICAgInRleHQiOiAi0KLQvtC30Lgg0YDQsNC30LPQvtCy0L7RgCDQstC10YfQtSDRgdGK0YnQtdGB0YLQstGD0LLQsCwg0LjRgdC60LDRgtC1INC70Lgg0LTQsCDRgdC1INC/0YDQuNGB0YrQtdC00LjQvdC40YLQtT8iLAogICAgInRpdGxlIjogItCf0YDQuNGB0YrQtdC00LjQvdGP0LLQsNC90LUg0LrRitC8INGB0YrRidC10YHRgtCy0YPQstCw0Ykg0YDQsNC30LPQvtCy0L7RgD8iCiAgfSwKICAibGF5b3V0X3Nwb3RsaWdodF9sYWJlbCI6ICLQn9GA0L7QttC10LrRgtC+0YAiLAogICJsb2JieSI6IHsKICAgICJqb2luX2J1dHRvbiI6ICLQktC70LXQtyDQsiDRgNCw0LfQs9C+0LLQvtGA0LAiCiAgfSwKICAibG9nZ2luZ19pbiI6ICLQktC70LjQt9Cw0L3QteKApiIsCiAgImxvZ2luX2F1dGhfbGlua3MiOiAiPDA+0KHRitC30LTQsNC50YLQtSDQsNC60LDRg9C90YI8LzA+INC40LvQuCA8Mj7QktC70LXQt9GC0LUg0LrQsNGC0L4g0LPQvtGB0YI8LzI+IiwKICAibG9naW5fdGl0bGUiOiAi0JLQu9C10LciLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogItCU0YDRg9CzINC/0L7RgtGA0LXQsdC40YLQtdC7INCyINGC0L7Qt9C4INGA0LDQt9Cz0L7QstC+0YAg0LjQvNCwINC/0YDQvtCx0LvQtdC8LiDQl9CwINC00LAg0LTQuNCw0LPQvdC+0YHRgtC40YbQuNGA0LDQvNC1INGC0L7Qt9C4INC/0YDQvtCx0LvQtdC8INC/0L4t0LTQvtCx0YDQtSDQvdC4INGB0LUg0LjRgdC60LAg0LTQsCDRgdGK0LHQtdGA0LXQvCBkZWJ1ZyDQu9C+0LPQvtCy0LUuIiwKICAgICJ0aXRsZSI6ICLQl9Cw0Y/QstC60LAg0LfQsCBkZWJ1ZyDQu9C+0LPQvtCy0LUiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICLQmNC30L/RgNCw0YLQtdGC0LUgZGVidWcg0LvQvtCz0L7QstC1IiwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAi0JjQt9C/0YDQsNGJ0LDQvdC14oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICJSZWNhcHRjaGEg0L7RgtGF0LLRitGA0LvQtdC90LAiLAogICJyZWNhcHRjaGFfbm90X2xvYWRlZCI6ICJSZWNhcHRjaGEg0L3QtSDQtSDQt9Cw0YDQtdC00LXQvdCwIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi0J/QsNGA0L7Qu9C40YLQtSDQvdC1INGB0YrQstC/0LDQtNCw0YIiLAogICAgInJlZ2lzdGVyaW5nIjogItCg0LXQs9C40YHRgtGA0LjRgNCw0L3QteKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPtCS0LXRh9C1INC40LzQsNGC0LUg0LDQutCw0YPQvdGCPzwvMD48MT48MD7QktC70LXQt9GC0LUg0YEg0L3QtdCz0L48LzA+INC40LvQuCA8Mj7QktC70LXQt9GC0LUg0LrQsNGC0L4g0LPQvtGB0YI8LzI+PC8xPiIsCiAgInJlZ2lzdGVyX2NvbmZpcm1fcGFzc3dvcmRfbGFiZWwiOiAi0J/QvtGC0LLRitGA0LTQuCDQv9Cw0YDQvtC70LDRgtCwIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogItCS0YDRitGJ0LDQvdC1INC90LAg0L3QsNGH0LDQu9C90LjRjyDQtdC60YDQsNC9IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogItCh0L/QvtC00LXQu9C4INC10LrRgNCw0L3QsCIsCiAgInNldHRpbmdzIjogewogICAgImRldmVsb3Blcl90YWJfdGl0bGUiOiAi0KDQsNC30YDQsNCx0L7RgtGH0LjQuiIsCiAgICAiZmVlZGJhY2tfdGFiX2g0IjogItCY0LfQv9GA0LDRgtC4INC+0LHRgNCw0YLQvdCwINCy0YDRitC30LrQsCIsCiAgICAiZmVlZGJhY2tfdGFiX3NlbmRfbG9nc19sYWJlbCI6ICLQktC60LvRjtGH0LggZGVidWcg0LvQvtCz0L7QstC1IgogIH0sCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2JvZHkiOiAi0JLRgdC1INC+0YnQtSDQvdC1INGB0YLQtSDRgNC10LPQuNGB0YLRgNC40YDQsNC90Lg/IDwyPtCh0YrQt9C00LDQudGC0LUg0LDQutCw0YPQvdGCPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLQktC70LXQt9GC0LUg0LIg0LDQutCw0YPQvdGC0LAg0YHQuCIsCiAgInZlcnNpb24iOiAi0JLQtdGA0YHQuNGPOiB7e3ZlcnNpb259fSIKfQo=",YVe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICJVxb5pdmF0ZWxza8OpIG1lbnUiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogIlphdsWZw610IiwKICAgICJnbyI6ICJQb2tyYcSNb3ZhdCIsCiAgICAibm8iOiAiTmUiLAogICAgInJlZ2lzdGVyIjogIlJlZ2lzdHJhY2UiLAogICAgInJlbW92ZSI6ICJPZHN0cmFuaXQiLAogICAgInNpZ25faW4iOiAiUMWZaWhsw6FzaXQgc2UiLAogICAgInNpZ25fb3V0IjogIk9kaGzDoXNpdCBzZSIKICB9LAogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiY3JlYXRlX2FjY291bnRfYnV0dG9uIjogIlZ5dHZvxZlpdCDDusSNZXQiLAogICAgImNyZWF0ZV9hY2NvdW50X3Byb21wdCI6ICI8MD5Qcm/EjSBuZXNrb27EjWl0IG5hc3RhdmVuw61tIGhlc2xhLCBhYnlzdGUgbW9obGkgw7rEjWV0IHBvdcW+w610IHpub3Z1PzwvMD48MT5CdWRldGUgc2kgbW9jaSBuZWNoYXQgc3bDqSBqbcOpbm8gYSBuYXN0YXZpdCBzaSBhdmF0YXIgcHJvIGJ1ZG91Y8OtIGhvdm9yeSA8LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICJUZcSPIG5lLCB2csOhdGl0IHNlIG5hIGRvbW92c2tvdSBvYnJhem92a3UiCiAgfSwKICAiY29tbW9uIjogewogICAgImRpc3BsYXlfbmFtZSI6ICJab2JyYXpvdmFuw6kgam3DqW5vIiwKICAgICJob21lIjogIkRvbW92IiwKICAgICJsb2FkaW5nIjogIk5hxI3DrXTDoW7DreKApiIsCiAgICAicGFzc3dvcmQiOiAiSGVzbG8iLAogICAgInByb2ZpbGUiOiAiUHJvZmlsIiwKICAgICJzZXR0aW5ncyI6ICJOYXN0YXZlbsOtIiwKICAgICJ1c2VybmFtZSI6ICJVxb5pdmF0ZWxza8OpIGptw6lubyIKICB9LAogICJoZWFkZXJfbGFiZWwiOiAiRG9tb3YgRWxlbWVudCBDYWxsIiwKICAiam9pbl9leGlzdGluZ19jYWxsX21vZGFsIjogewogICAgImpvaW5fYnV0dG9uIjogIkFubywgcMWZaXBvaml0IHNlIiwKICAgICJ0ZXh0IjogIlRlbnRvIGhvdm9yIGppxb4gZXhpc3R1amUsIGNoY2V0ZSBzZSBwxZlpcG9qaXQ/IiwKICAgICJ0aXRsZSI6ICJQxZlpcG9qaXQgc2UgayBleGlzdHVqw61jaW11IGhvdm9ydT8iCiAgfSwKICAibGF5b3V0X3Nwb3RsaWdodF9sYWJlbCI6ICJTb3VzdMWZZWTEm27DvSBtw7NkIiwKICAibG9iYnkiOiB7CiAgICAiam9pbl9idXR0b24iOiAiUMWZaXBvaml0IHNlIGsgaG92b3J1IgogIH0sCiAgImxvZ2dpbmdfaW4iOiAiUMWZaWhsYcWhb3bDoW7DrSBzZeKApiIsCiAgImxvZ2luX2F1dGhfbGlua3MiOiAiPDA+Vnl0dm/FmWl0IMO6xI1ldDwvMD4gT3IgPDI+SmFrbyBob3N0PC8yPiIsCiAgImxvZ2luX3RpdGxlIjogIlDFmWlobMOhxaFlbsOtIiwKICAicmFnZXNoYWtlX3JlcXVlc3RfbW9kYWwiOiB7CiAgICAiYm9keSI6ICJKaW7DvSB1xb5pdmF0ZWwgdiB0b210byBob3ZvcnUgbcOhIHByb2Jsw6lteS4gQWJ5Y2hvbSBtb2hsaSBkaWFnbm9zdGlrb3ZhdCBwcm9ibMOpbSwgcsOhZGkgYnljaG9tIHNocm9tw6HFvmRpbGkgcHJvdG9rb2x5IGxhZMSbbsOtLiIsCiAgICAidGl0bGUiOiAixb3DoWRvc3QgbyBwcm90b2tvbHkgbGFkxJtuw60iCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICJQb3NsYXQgbGFkw61jw60gesOhem5hbSIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogIlBvc8OtbMOhbsOt4oCmIiwKICAicmFnZXNoYWtlX3NlbmRpbmdfbG9ncyI6ICJQb3PDrWzDoW7DrSBsYWTDrWPDrWhvIHrDoXpuYW114oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICJSZWNhcHRjaGEgYnlsYSB6YW3DrXRudXRhIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAiUmVjYXB0Y2hhIHNlIG5lbmHEjWV0bGEiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICJIZXNsYSBzZSBtdXPDrSBzaG9kb3ZhdCIsCiAgICAicmVnaXN0ZXJpbmciOiAiUmVnaXN0cm92w6Fuw63igKYiCiAgfSwKICAicmVnaXN0ZXJfYXV0aF9saW5rcyI6ICI8MD5Vxb4gbcOhdGUgw7rEjWV0PzwvMD48MT48MD5QxZlpaGzDoXNpdCBzZTwvMD4gT3IgPDI+SmFrbyBob3N0PC8yPjwvMT4iLAogICJyZWdpc3Rlcl9jb25maXJtX3Bhc3N3b3JkX2xhYmVsIjogIlBvdHZyZGl0IGhlc2xvIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogIlZyw6F0aXQgc2UgbmEgZG9tw6Fjw60gb2JyYXpvdmt1IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIlNkw61sZXQgb2JyYXpvdmt1IiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICJWw712b2rDocWZIiwKICAgICJmZWVkYmFja190YWJfaDQiOiAiRMOhdCBmZWVkYmFjayIsCiAgICAiZmVlZGJhY2tfdGFiX3NlbmRfbG9nc19sYWJlbCI6ICJaYWhybm91dCBsYWTDrWPDrSB6w6F6bmFteSIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogIk5lanN0ZSByZWdpc3Ryb3ZhbsOtPyA8Mj5WeXR2b8WZaXQgw7rEjWV0PC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICJQxZlpaGzDoXNpdCBzZSBrZSBzdsOpbXUgw7rEjXR1IiwKICAidmVyc2lvbiI6ICJWZXJ6ZToge3t2ZXJzaW9ufX0iCn0K",XVe=""+new URL("de-app-BVrY_LcE.json",import.meta.url).href,JVe=""+new URL("el-app-Bgiig2Nz.json",import.meta.url).href,ZVe=""+new URL("en-app-CaNSxxxY.json",import.meta.url).href,QVe=""+new URL("es-app-k4RDObng.json",import.meta.url).href,eGe=""+new URL("et-app-lXLRqT0e.json",import.meta.url).href,tGe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLZgdmH2LHYs9iqINqp2KfYsdio2LEiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogItio2LPYqtmGIiwKICAgICJnbyI6ICLYsdmB2KrZhiIsCiAgICAibm8iOiAi2K7bjNixIiwKICAgICJyZWdpc3RlciI6ICLYq9io2KrigIzZhtin2YUiLAogICAgInJlbW92ZSI6ICLYrdiw2YEiLAogICAgInNpZ25faW4iOiAi2YjYsdmI2K8iLAogICAgInNpZ25fb3V0IjogItiu2LHZiNisIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAi2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+2obYsdinINuM2qkg2LHZhdiyINi52KjZiNixINio2LHYp9uMINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2KrZhti424zZhSDZhtmF24zigIzaqdmG24zYr9ifPC8wPjwxPti02YXYpyDZhduM4oCM2KrZiNin2YbbjNivINmG2KfZhSDYrtmI2K8g2LHYpyDYrdmB2Lgg2qnZhtuM2K8g2Ygg24zaqSDYotmI2KfYqtin2LEg2KjYsdin24wg2KrZhdin2LPigIzZh9in24wg2KLbjNmG2K/ZhyDYqNiz2KfYstuM2K88LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLYp9mE2KfZhiDZhtmH2Iwg2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCDYqNix2q/Ysdiv24zYryIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAi2LXYr9inIiwKICAgICJhdmF0YXIiOiAi2KLZiNin2KrYp9ixIiwKICAgICJkaXNwbGF5X25hbWUiOiAi2YbYp9mFINmG2YXYp9uM2LTbjCIsCiAgICAiaG9tZSI6ICLYrtin2YbZhyIsCiAgICAibG9hZGluZyI6ICLYqNin2LHar9iy2KfYsduM4oCmIiwKICAgICJwYXNzd29yZCI6ICLYsdmF2LIg2LnYqNmI2LEiLAogICAgInByb2ZpbGUiOiAi2b7YsdmI2YHYp9uM2YQiLAogICAgInNldHRpbmdzIjogItiq2YbYuNuM2YXYp9iqIiwKICAgICJ1c2VybmFtZSI6ICLZhtin2YUg2qnYp9ix2KjYsduMIiwKICAgICJ2aWRlbyI6ICLZiNuM2K/bjNmIIgogIH0sCiAgImhlYWRlcl9sYWJlbCI6ICLYrtin2YbZh9mUINiq2YXYp9izINin2YTZhdmG2KoiLAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi2KjZhNmH2Iwg2KjZhyDYqtmF2KfYsyDYqNm+24zZiNmG2K/bjNivIiwKICAgICJ0ZXh0IjogItin24zZhiDYqtmF2KfYsyDYp9iyINmC2KjZhCDZiNis2YjYryDYr9in2LHYr9iMINmF24zigIzYrtmI2KfZh9uM2K8g2KjZvtuM2YjZhtiv24zYr9ifIiwKICAgICJ0aXRsZSI6ICLZvtuM2YjYs9iqINio2Ycg2KrZhdin2LPYnyIKICB9LAogICJsYXlvdXRfc3BvdGxpZ2h0X2xhYmVsIjogItmG2YjYsSDYp9mB2qnZhiIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogItm+24zZiNiz2KrZhiDYqNmHINiq2YXYp9izIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAi2YjYsdmI2K/igKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPtiz2KfYrtiqINit2LPYp9ioINqp2KfYsdio2LHbjDwvMD4gT3IgPDI+2K/Ys9iq2LHYs9uMINio2Ycg2LnZhtmI2KfZhiDZhduM2YfZhdin2YY8LzI+IiwKICAibG9naW5fdGl0bGUiOiAi2YjYsdmI2K8iLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogItqp2KfYsdio2LEg2K/bjNqv2LHbjCDYr9ixINin24zZhiDYqtmF2KfYsyDZhdi02qnZhNuMINiv2KfYsdivLiDYqNix2KfbjCDYqti02K7bjNi1INio2YfYqtixINmF2LTaqdmE2Iwg2KjZh9iq2LEg2KfYs9iqINmF2Kcg2YTYp9qvINi524zYqOKAjNuM2KfYqNuMINix2Kcg2KzZhdi54oCM2KLZiNix24wg2qnZhtuM2YUuIiwKICAgICJ0aXRsZSI6ICLYr9ix2K7ZiNin2LPYqiDZhNin2q8g2LnbjNio4oCM24zYp9io24wiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRfbG9ncyI6ICLYp9ix2LPYp9mEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YTigKYiLAogICJyYWdlc2hha2Vfc2VuZGluZ19sb2dzIjogItiv2LEg2K3Yp9mEINin2LHYs9in2YQg2KjYp9qv4oCM2YfYp9uMINi524zYqOKAjNuM2KfYqNuM4oCmIiwKICAicmVjYXB0Y2hhX2Rpc21pc3NlZCI6ICLYsduM2qnZvtqG2Kcg2LHYryDYtNivIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAi2qnZvtqG2Kcg2KjYp9ix2q/bjNix24wg2YbYtNivIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi2LHZhdiyINi52KjZiNixINio2KfbjNivINmH2YXYrtmI2KfZhtuMINiv2KfYtNiq2Ycg2KjYp9i02K8iLAogICAgInJlZ2lzdGVyaW5nIjogItir2KjYquKAjNmG2KfZheKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPtin2LIg2YLYqNmEINit2LPYp9ioINqp2KfYsdio2LHbjCDYr9in2LHbjNiv2J88LzA+PDE+PDA+2YjYsdmI2K88LzA+IE9yIDwyPtio2Ycg2LnZhtmI2KfZhiDbjNqpINmF24zZh9mF2KfZhiDZiNin2LHYryDYtNmI24zYrzwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLYqtin24zbjNivINix2YXYsti52KjZiNixIiwKICAicmV0dXJuX2hvbWVfYnV0dG9uIjogItio2LHar9i02Kog2KjZhyDYtdmB2K3ZhyDYp9i12YTbjCIsCiAgInNjcmVlbnNoYXJlX2J1dHRvbl9sYWJlbCI6ICLYp9i02KrYsdin2qkg2q/YsNin2LHbjCDYtdmB2K3ZhyDZhtmF2KfbjNi0IiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICLYqtmI2LPYudmHINiv2YfZhtiv2YciLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICLYqNin2LLYrtmI2LHYryDYp9ix2KfYptmHINiv2YfbjNivIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIti02KfZhdmEINmE2Kfar+KAjNmH2KfbjCDYuduM2KjigIzbjNin2KjbjCIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogItmH2YbZiNiyINir2KjYquKAjNmG2KfZhSDZhtqp2LHYr9mH4oCM2KfbjNiv2J8gPDI+2LPYp9iu2Kog2K3Ys9in2Kgg2qnYp9ix2KjYsduMPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLYqNmHINit2LPYp9ioINqp2KfYsdio2LHbjCDYrtmI2K8g2YjYp9ix2K8g2LTZiNuM2K8iLAogICJ2ZXJzaW9uIjogItmG2LPYrtmHOiB7e9mG2LPYrtmHfX0iCn0K",nGe=""+new URL("fr-app-DbyWYFAw.json",import.meta.url).href,rGe=""+new URL("id-app-C7u2K42_.json",import.meta.url).href,iGe=""+new URL("it-app-Brq71wxA.json",import.meta.url).href,sGe="data:application/json;base64,ewogICJhMTF5IjogewogICAgInVzZXJfbWVudSI6ICLjg6bjg7zjgrbjg7zjg6Hjg4vjg6Xjg7wiCiAgfSwKICAiYWN0aW9uIjogewogICAgImNsb3NlIjogIumWieOBmOOCiyIsCiAgICAiZ28iOiAi57aa6KGMIiwKICAgICJubyI6ICLjgYTjgYTjgYgiLAogICAgInJlZ2lzdGVyIjogIueZu+mMsiIsCiAgICAicmVtb3ZlIjogIuWJiumZpCIsCiAgICAic2lnbl9pbiI6ICLjgrXjgqTjg7PjgqTjg7MiLAogICAgInNpZ25fb3V0IjogIuOCteOCpOODs+OCouOCpuODiCIKICB9LAogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiY3JlYXRlX2FjY291bnRfYnV0dG9uIjogIuOCouOCq+OCpuODs+ODiOOCkuS9nOaIkCIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAi6Z+z5aOwIiwKICAgICJhdmF0YXIiOiAi44Ki44OQ44K/44O8IiwKICAgICJkaXNwbGF5X25hbWUiOiAi6KGo56S65ZCNIiwKICAgICJob21lIjogIuODm+ODvOODoCIsCiAgICAibG9hZGluZyI6ICLoqq3jgb/ovrzjgpPjgafjgYTjgb7jgZnigKYiLAogICAgInBhc3N3b3JkIjogIuODkeOCueODr+ODvOODiSIsCiAgICAicHJvZmlsZSI6ICLjg5fjg63jg5XjgqPjg7zjg6siLAogICAgInNldHRpbmdzIjogIuioreWumiIsCiAgICAidXNlcm5hbWUiOiAi44Om44O844K244O85ZCNIiwKICAgICJ2aWRlbyI6ICLjg5Pjg4fjgqoiCiAgfSwKICAiaGVhZGVyX2xhYmVsIjogIkVsZW1lbnQgQ2FsbCDjg5vjg7zjg6AiLAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAi44Gv44GE44CB6YCa6Kmx44Gr5Y+C5YqgIiwKICAgICJ0ZXh0IjogIuOBk+OBrumAmuipseOBr+aXouOBq+WtmOWcqOOBl+OBvuOBmeOAguWPguWKoOOBl+OBvuOBmeOBi++8nyIsCiAgICAidGl0bGUiOiAi5pei5a2Y44Gu6YCa6Kmx44Gr5Y+C5Yqg44GX44G+44GZ44GL77yfIgogIH0sCiAgImxheW91dF9zcG90bGlnaHRfbGFiZWwiOiAi44K544Od44OD44OI44Op44Kk44OIIiwKICAibG9iYnkiOiB7CiAgICAiam9pbl9idXR0b24iOiAi6YCa6Kmx44Gr5Y+C5YqgIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAi44Ot44Kw44Kk44Oz44GX44Gm44GE44G+44GZ4oCmIiwKICAibG9naW5fYXV0aF9saW5rcyI6ICI8MD7jgqLjgqvjgqbjg7Pjg4jjgpLkvZzmiJA8LzA+44G+44Gf44GvPDI+44Ky44K544OI44Go44GX44Gm44Ki44Kv44K744K5PC8yPiIsCiAgImxvZ2luX3RpdGxlIjogIuODreOCsOOCpOODsyIsCiAgInJhZ2VzaGFrZV9yZXF1ZXN0X21vZGFsIjogewogICAgInRpdGxlIjogIuODh+ODkOODg+OCsOODreOCsOOCkuimgeaxgiIKICB9LAogICJyYWdlc2hha2Vfc2VuZF9sb2dzIjogIuODh+ODkOODg+OCsOODreOCsOOCkumAgeS/oSIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nIjogIumAgeS/oeOBl+OBpuOBhOOBvuOBmeKApiIsCiAgInJhZ2VzaGFrZV9zZW5kaW5nX2xvZ3MiOiAi44OH44OQ44OD44Kw44Ot44Kw44KS6YCB5L+h44GX44Gm44GE44G+44GZ4oCmIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAi44OR44K544Ov44O844OJ44GM5LiA6Ie044GZ44KL5b+F6KaB44GM44GC44KK44G+44GZIiwKICAgICJyZWdpc3RlcmluZyI6ICLnmbvpjLLjgZfjgabjgYTjgb7jgZnigKYiCiAgfSwKICAicmVnaXN0ZXJfYXV0aF9saW5rcyI6ICI8MD7ml6LjgavjgqLjgqvjgqbjg7Pjg4jjgpLjgYrmjIHjgaHjgafjgZnjgYvvvJ88LzA+PDE+PDA+44Ot44Kw44Kk44OzPC8wPuOBvuOBn+OBrzwyPuOCsuOCueODiOOBqOOBl+OBpuOCouOCr+OCu+OCuTwvMj48LzE+IiwKICAicmVnaXN0ZXJfY29uZmlybV9wYXNzd29yZF9sYWJlbCI6ICLjg5Hjgrnjg6/jg7zjg4njgpLnorroqo0iLAogICJyZXR1cm5faG9tZV9idXR0b24iOiAi44Ob44O844Og55S76Z2i44Gr5oi744KLIiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIueUu+mdouWFseaciSIsCiAgInNldHRpbmdzIjogewogICAgImRldmVsb3Blcl90YWJfdGl0bGUiOiAi6ZaL55m66ICFIiwKICAgICJmZWVkYmFja190YWJfaDQiOiAi44OV44Kj44O844OJ44OQ44OD44Kv44KS6YCB5L+hIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIuODh+ODkOODg+OCsOODreOCsOOCkuWQq+OCgeOCiyIKICB9LAogICJ1bmF1dGhlbnRpY2F0ZWRfdmlld19ib2R5IjogIuOCouOCq+OCpuODs+ODiOOBjOOBguOCiuOBvuOBm+OCk+OBi++8nyA8Mj7jgqLjgqvjgqbjg7Pjg4jjgpLkvZzmiJA8LzI+IiwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfbG9naW5fYnV0dG9uIjogIuOCouOCq+OCpuODs+ODiOOBq+ODreOCsOOCpOODsyIsCiAgInZlcnNpb24iOiAi44OQ44O844K444On44Oz77yae3t2ZXJzaW9ufX0iCn0K",oGe=""+new URL("lv-app--dkl5K2p.json",import.meta.url).href,aGe=""+new URL("pl-app-DGeQk6oM.json",import.meta.url).href,cGe=""+new URL("ro-app-C7W3EjXp.json",import.meta.url).href,lGe=""+new URL("ru-app-B-FtZqJU.json",import.meta.url).href,uGe=""+new URL("sk-app-C-Uhf1j4.json",import.meta.url).href,dGe="data:application/json;base64,ewogICJjYWxsX2VuZGVkX3ZpZXciOiB7CiAgICAiaGVhZGxpbmUiOiAie3tkaXNwbGF5TmFtZX19LCBkaXR0IHNhbXRhbCBoYXIgYXZzbHV0YXRzLiIKICB9LAogICJzdGFyX3JhdGluZ19pbnB1dF9sYWJlbF9vbmUiOiAie3tjb3VudH19IHN0asOkcm5hIiwKICAic3Rhcl9yYXRpbmdfaW5wdXRfbGFiZWxfb3RoZXIiOiAie3tjb3VudH19IHN0asOkcm5vciIKfQo=",hGe="data:application/json;base64,ewogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAiS2FwYXQiLAogICAgImdvIjogIkdpdCIsCiAgICAibm8iOiAiSGF5xLFyIiwKICAgICJyZWdpc3RlciI6ICJLYXlkb2wiLAogICAgInJlbW92ZSI6ICLDh8Sxa2FyIiwKICAgICJzaWduX2luIjogIkdpciIsCiAgICAic2lnbl9vdXQiOiAiw4fEsWsiCiAgfSwKICAiY2FsbF9lbmRlZF92aWV3IjogewogICAgImNyZWF0ZV9hY2NvdW50X2J1dHRvbiI6ICJIZXNhcCBhw6ciLAogICAgImNyZWF0ZV9hY2NvdW50X3Byb21wdCI6ICI8MD5IZXNhYsSxbsSxesSxIHR1dG1hayBpw6dpbiBuaXllIGJpciBwYXJvbGEgYcOnbcSxeW9yc3VudXo/PC8wPjwxPkLDtnlsZWNlIGlsZXJpa2kgYXJhbWFsYXJkYSBhZMSxbsSxesSxIHZlIGF2YXRhcsSxbsSxesSxIGt1bGxhbmFiaWxlY2Vrc2luaXo8LzE+IiwKICAgICJub3Rfbm93X2J1dHRvbiI6ICLFnmltZGkgZGXEn2lsLCBldiBla3JhbsSxbmEgZMO2biIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAiU2VzIiwKICAgICJkaXNwbGF5X25hbWUiOiAiRWtyYW4gYWTEsSIsCiAgICAiaG9tZSI6ICJFdiIsCiAgICAibG9hZGluZyI6ICJZw7xrbGVuaXlvcuKApiIsCiAgICAicGFzc3dvcmQiOiAiUGFyb2xhIiwKICAgICJzZXR0aW5ncyI6ICJBeWFybGFyIgogIH0sCiAgImpvaW5fZXhpc3RpbmdfY2FsbF9tb2RhbCI6IHsKICAgICJ0ZXh0IjogIkJ1IGFyYW1hIHphdGVuIHZhciwga2F0xLFsbWFrIGlzdGVyIG1pc2luaXo/IiwKICAgICJ0aXRsZSI6ICJNZXZjdXQgYXJhbWF5YSBrYXTEsWw/IgogIH0sCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogIkFyYW1heWEga2F0xLFsIgogIH0sCiAgImxvZ2dpbmdfaW4iOiAiR2lyaWxpeW9y4oCmIiwKICAibG9naW5fYXV0aF9saW5rcyI6ICI8MD5IZXNhcCBvbHXFn3R1cjwvMD4geWFodXQgPDI+S29udWsgb2xhcmFrIGdpcjwvMj4iLAogICJsb2dpbl90aXRsZSI6ICJHaXIiLAogICJyYWdlc2hha2VfcmVxdWVzdF9tb2RhbCI6IHsKICAgICJib2R5IjogIkJ1IGFyYW1hZGFraSBiYcWfa2EgYmlyIGt1bGxhbsSxY8SxIHNvcnVuIHlhxZ/EsXlvci4gU29ydW51IGRhaGEgaXlpIMOnw7Z6ZWJpbG1lbWl6IGnDp2luIGhhdGEgYXnEsWtsYW1hIGvDvHTDvMSfw7xuw7wgYWxtYWsgaXN0ZXJpei4iLAogICAgInRpdGxlIjogIkhhdGEgYXnEsWtsYW1hIGvDvHTDvGsgaXN0ZW1pIgogIH0sCiAgInJhZ2VzaGFrZV9zZW5kX2xvZ3MiOiAiSGF0YSBhecSxa2xhbWEga8O8dMO8xJ/DvG7DvCBnw7ZuZGVyIiwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAiR8O2bmRlcmlsaXlvcuKApiIsCiAgInJlY2FwdGNoYV9kaXNtaXNzZWQiOiAicmVDQVBUQ0hBIGF0bGFuZMSxIiwKICAicmVjYXB0Y2hhX25vdF9sb2FkZWQiOiAicmVDQVBUQ0hBIHnDvGtsZW5tZWRpIiwKICAicmVnaXN0ZXIiOiB7CiAgICAicGFzc3dvcmRzX211c3RfbWF0Y2giOiAiUGFyb2xhbGFyIGF5bsSxIG9sbWFsxLEiLAogICAgInJlZ2lzdGVyaW5nIjogIktheWRlZGl5b3LigKYiCiAgfSwKICAicmVnaXN0ZXJfYXV0aF9saW5rcyI6ICI8MD5NZXZjdXQgaGVzYWLEsW7EsXogbcSxIHZhcj88LzA+PDE+PDA+R2lyPC8wPiB5YWh1dCA8Mj5Lb251ayBnaXJpxZ9pPC8yPjwvMT4iLAogICJyZWdpc3Rlcl9jb25maXJtX3Bhc3N3b3JkX2xhYmVsIjogIlBhcm9sYXnEsSB0ZWtyYXIgZWRpbiIsCiAgInJldHVybl9ob21lX2J1dHRvbiI6ICJFdiBla3JhbsSxbmEgZ2VyaSBkw7ZuIiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIkVrcmFuIHBheWxhxZ8iLAogICJzZXR0aW5ncyI6IHsKICAgICJkZXZlbG9wZXJfdGFiX3RpdGxlIjogIkdlbGnFn3RpcmljaSIsCiAgICAiZmVlZGJhY2tfdGFiX2g0IjogIkdlcmkgYmlsZGlyaW0gdmVyIiwKICAgICJmZWVkYmFja190YWJfc2VuZF9sb2dzX2xhYmVsIjogIkhhdGEgYXnEsWtsYW1hIGvDvHTDvMSfw7xuw7wgZGFoaWwgZXQiCiAgfSwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfYm9keSI6ICJLYXlkb2xtYWTEsW7EsXogbcSxPyA8Mj5IZXNhcCBhw6fEsW48LzI+IiwKICAidW5hdXRoZW50aWNhdGVkX3ZpZXdfbG9naW5fYnV0dG9uIjogIkhlc2FixLFuxLF6YSBnaXJpbiIKfQo=",fGe=""+new URL("uk-app-BxyP4dDT.json",import.meta.url).href,pGe="data:application/json;base64,ewogICJhY3Rpb24iOiB7CiAgICAiY2xvc2UiOiAixJDDs25nIiwKICAgICJubyI6ICJLaMO0bmciLAogICAgInJlZ2lzdGVyIjogIsSQxINuZyBrw70iLAogICAgInNpZ25faW4iOiAixJDEg25nIG5o4bqtcCIsCiAgICAic2lnbl9vdXQiOiAixJDEg25nIHh14bqldCIsCiAgICAic3VibWl0IjogIkfhu61pIgogIH0sCiAgImNhbGxfZW5kZWRfdmlldyI6IHsKICAgICJjcmVhdGVfYWNjb3VudF9idXR0b24iOiAiVOG6oW8gdMOgaSBraG/huqNuIiwKICAgICJjcmVhdGVfYWNjb3VudF9wcm9tcHQiOiAiPDA+VOG6oWkgc2FvIGzhuqFpIGtow7RuZyBob8OgbiB0aGnhu4duIGLhurFuZyBjw6FjaCDEkeG6t3QgbeG6rXQga2jhuql1IMSR4buDIGdp4buvIHTDoGkga2hv4bqjbiBj4bunYSBi4bqhbj88LzA+PDE+QuG6oW4gc+G6vSBjw7MgdGjhu4MgZ2nhu68gdMOqbiB2w6AgxJHhurd0IOG6o25oIMSR4bqhaSBkaeG7h24gY2hvIG5o4buvbmcgY3Xhu5ljIGfhu41pIHRp4bq/cCB0aGVvLjwvMT4iLAogICAgImZlZWRiYWNrX2RvbmUiOiAiPDA+Q+G6o20gaMahbiB2w6wgxJHDoyBwaOG6o24gaOG7k2khPC8wPiIsCiAgICAiZmVlZGJhY2tfcHJvbXB0IjogIjwwPkNow7puZyB0w7RpIG114buRbiBuZ2hlIHBo4bqjbiBo4buTaSBj4bunYSBi4bqhbiDEkeG7gyBjw7JuIGPhuqNpIHRoaeG7h24gdHLhuqNpIG5naGnhu4dtIGNobyBi4bqhbi48LzA+IiwKICAgICJoZWFkbGluZSI6ICJ7e2Rpc3BsYXlOYW1lfX0sIGN14buZYyBn4buNaSDEkcOjIGvhur90IHRow7pjLiIKICB9LAogICJjb21tb24iOiB7CiAgICAiYXVkaW8iOiAiw4JtIHRoYW5oIiwKICAgICJhdmF0YXIiOiAi4bqibmggxJHhuqFpIGRp4buHbiIsCiAgICAiZGlzcGxheV9uYW1lIjogIlTDqm4gaGnhu4NuIHRo4buLIiwKICAgICJsb2FkaW5nIjogIsSQYW5nIHThuqNp4oCmIiwKICAgICJwYXNzd29yZCI6ICJN4bqtdCBraOG6qXUiLAogICAgInByb2ZpbGUiOiAiSOG7kyBzxqEiLAogICAgInNldHRpbmdzIjogIkPDoGkgxJHhurd0IiwKICAgICJ1c2VybmFtZSI6ICJUw6puIG5nxrDhu51pIGTDuW5nIiwKICAgICJ2aWRlbyI6ICJUcnV54buBbiBow6xuaCIKICB9LAogICJqb2luX2V4aXN0aW5nX2NhbGxfbW9kYWwiOiB7CiAgICAiam9pbl9idXR0b24iOiAiVsOibmcsIHRoYW0gZ2lhIGN14buZYyBn4buNaSIsCiAgICAidGV4dCI6ICJDdeG7mWMgZ+G7jWkgxJHDoyB04buTbiB04bqhaSwgYuG6oW4gY8OzIG114buRbiB0aGFtIGdpYSBraMO0bmc/IiwKICAgICJ0aXRsZSI6ICJUaGFtIGdpYSBjdeG7mWMgZ+G7jWk/IgogIH0sCiAgImxheW91dF9zcG90bGlnaHRfbGFiZWwiOiAiVGnDqnUgxJFp4buDbSIsCiAgImxvYmJ5IjogewogICAgImpvaW5fYnV0dG9uIjogIlRoYW0gZ2lhIGN14buZYyBn4buNaSIKICB9LAogICJsb2dnaW5nX2luIjogIsSQYW5nIMSRxINuZyBuaOG6rXDigKYiLAogICJsb2dpbl9hdXRoX2xpbmtzIjogIjwwPlThuqFvIHTDoGkga2hv4bqjbjwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBraMOhYzwvMj4iLAogICJsb2dpbl90aXRsZSI6ICLEkMSDbmcgbmjhuq1wIiwKICAicmFnZXNoYWtlX3JlcXVlc3RfbW9kYWwiOiB7CiAgICAiYm9keSI6ICJN4buZdCBuZ8aw4budaSBkw7luZyBraMOhYyB0cm9uZyBjdeG7mWMgZ+G7jWkgxJFhbmcgZ+G6t3AgduG6pW4gxJHhu4EuIMSQ4buDIGPDsyB0aOG7gyBjaOG6qW4gxJFvw6FuIHThu5F0IGjGoW4gY2jDum5nIHTDtGkgbXXhu5FuIHRodSB0aOG6rXAgbmjhuq10IGvDvSBn4buhIGzhu5dpLiIsCiAgICAidGl0bGUiOiAiWcOqdSBj4bqndSBuaOG6rXQga8O9IGfhu6EgbOG7l2kiCiAgfSwKICAicmFnZXNoYWtlX3NlbmRpbmciOiAixJBhbmcgZ+G7rWnigKYiLAogICJyZWNhcHRjaGFfbm90X2xvYWRlZCI6ICJDaMawYSB04bqjaSDEkcaw4bujYyBSZWNhcHRjaGEiLAogICJyZWdpc3RlciI6IHsKICAgICJwYXNzd29yZHNfbXVzdF9tYXRjaCI6ICJN4bqtdCBraOG6qXUgcGjhuqNpIGto4bubcCIsCiAgICAicmVnaXN0ZXJpbmciOiAixJBhbmcgxJHEg25nIGvDveKApiIKICB9LAogICJyZWdpc3Rlcl9hdXRoX2xpbmtzIjogIjwwPsSQw6MgY8OzIHTDoGkga2hv4bqjbj88LzA+PDE+PDA+xJDEg25nIG5o4bqtcDwvMD4gSGF5IDwyPlRoYW0gZ2lhIGTGsOG7m2kgdMOqbiBLaMOhY2g8LzI+PC8xPiIsCiAgInJlZ2lzdGVyX2NvbmZpcm1fcGFzc3dvcmRfbGFiZWwiOiAiWMOhYyBuaOG6rW4gbeG6rXQga2jhuql1IiwKICAic2NyZWVuc2hhcmVfYnV0dG9uX2xhYmVsIjogIkNoaWEgc+G6uyBtw6BuIGjDrG5oIiwKICAic2V0dGluZ3MiOiB7CiAgICAiZGV2ZWxvcGVyX3RhYl90aXRsZSI6ICJOaMOgIHBow6F0IHRyaeG7g24iLAogICAgImZlZWRiYWNrX3RhYl9kZXNjcmlwdGlvbl9sYWJlbCI6ICJQaOG6o24gaOG7k2kgY+G7p2EgYuG6oW4iLAogICAgImZlZWRiYWNrX3RhYl9oNCI6ICJH4butaSBwaOG6o24gaOG7k2kiLAogICAgImZlZWRiYWNrX3RhYl9zZW5kX2xvZ3NfbGFiZWwiOiAiS8OobSB0aGVvIG5o4bqtdCBrw70gZ+G7oSBs4buXaSIsCiAgICAiZmVlZGJhY2tfdGFiX3RoYW5rX3lvdSI6ICJD4bqjbSDGoW4sIGNow7puZyB0w7RpIMSRw6Mgbmjhuq1uIMSRxrDhu6NjIHBo4bqjbiBo4buTaSEiLAogICAgImZlZWRiYWNrX3RhYl90aXRsZSI6ICJQaOG6o24gaOG7k2kiCiAgfSwKICAic3VibWl0dGluZyI6ICLEkGFuZyBn4butaeKApiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2JvZHkiOiAiQ2jGsGEgxJHEg25nIGvDvT8gPDI+VOG6oW8gdMOgaSBraG/huqNuPC8yPiIsCiAgInVuYXV0aGVudGljYXRlZF92aWV3X2xvZ2luX2J1dHRvbiI6ICLEkMSDbmcgbmjhuq1wIHbDoG8gdMOgaSBraG/huqNuIGPhu6dhIGLhuqFuIiwKICAidmVyc2lvbiI6ICJQaGnDqm4gYuG6o246IHt7dmVyc2lvbn19Igp9Cg==",mGe=""+new URL("zh-Hans-app-CCvn5Yaa.json",import.meta.url).href,gGe=""+new URL("zh-Hant-app-bsZKL_R6.json",import.meta.url).href,{slice:vGe,forEach:yGe}=[];function _Ge(n){return yGe.call(vGe.call(arguments,1),e=>{if(e)for(const t in e)n[t]===void 0&&(n[t]=e[t])}),n}const lj=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,bGe=function(n,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${n}=${i}`;if(r.maxAge>0){const o=r.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(r.domain){if(!lj.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!lj.test(r.path))throw new TypeError("option path is invalid");s+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return s},uj={create(n,e,t,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+t*60*1e3)),r&&(i.domain=r),document.cookie=bGe(n,encodeURIComponent(e),i)},read(n){const e=`${n}=`,t=document.cookie.split(";");for(let r=0;r<t.length;r++){let i=t[r];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null},remove(n){this.create(n,"",-1)}};var SGe={name:"cookie",lookup(n){let{lookupCookie:e}=n;if(e&&typeof document<"u")return uj.read(e)||void 0},cacheUserLanguage(n,e){let{lookupCookie:t,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;t&&typeof document<"u"&&uj.create(t,n,r,i,s)}},wGe={name:"querystring",lookup(n){var r;let{lookupQuerystring:e}=n,t;if(typeof window<"u"){let{search:i}=window.location;!window.location.search&&((r=window.location.hash)==null?void 0:r.indexOf("?"))>-1&&(i=window.location.hash.substring(window.location.hash.indexOf("?")));const o=i.substring(1).split("&");for(let a=0;a<o.length;a++){const c=o[a].indexOf("=");c>0&&o[a].substring(0,c)===e&&(t=o[a].substring(c+1))}}return t}};let Jh=null;const dj=()=>{if(Jh!==null)return Jh;try{if(Jh=typeof window<"u"&&window.localStorage!==null,!Jh)return!1;const n="i18next.translate.boo";window.localStorage.setItem(n,"foo"),window.localStorage.removeItem(n)}catch{Jh=!1}return Jh};var EGe={name:"localStorage",lookup(n){let{lookupLocalStorage:e}=n;if(e&&dj())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupLocalStorage:t}=e;t&&dj()&&window.localStorage.setItem(t,n)}};let Zh=null;const hj=()=>{if(Zh!==null)return Zh;try{if(Zh=typeof window<"u"&&window.sessionStorage!==null,!Zh)return!1;const n="i18next.translate.boo";window.sessionStorage.setItem(n,"foo"),window.sessionStorage.removeItem(n)}catch{Zh=!1}return Zh};var CGe={name:"sessionStorage",lookup(n){let{lookupSessionStorage:e}=n;if(e&&hj())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(n,e){let{lookupSessionStorage:t}=e;t&&hj()&&window.sessionStorage.setItem(t,n)}},TGe={name:"navigator",lookup(n){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:r,language:i}=navigator;if(t)for(let s=0;s<t.length;s++)e.push(t[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},IGe={name:"htmlTag",lookup(n){let{htmlTag:e}=n,t;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(t=r.getAttribute("lang")),t}},RGe={name:"path",lookup(n){var i;let{lookupFromPathIndex:e}=n;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(i=t[typeof e=="number"?e:0])==null?void 0:i.replace("/",""):void 0}},kGe={name:"subdomain",lookup(n){var i,s;let{lookupFromSubdomainIndex:e}=n;const t=typeof e=="number"?e+1:1,r=typeof window<"u"&&((s=(i=window.location)==null?void 0:i.hostname)==null?void 0:s.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(r)return r[t]}};let tte=!1;try{document.cookie,tte=!0}catch{}const nte=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];tte||nte.splice(1,1);const xGe=()=>({order:nte,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:n=>n});class rte{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=_Ge(t,this.options||{},xGe()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(SGe),this.addDetector(wGe),this.addDetector(EGe),this.addDetector(CGe),this.addDetector(TGe),this.addDetector(IGe),this.addDetector(RGe),this.addDetector(kGe)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(t=t.concat(i))}}),t=t.map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}rte.type="languageDetector";var d_={},fj;function PGe(){if(fj)return d_;fj=1,Object.defineProperty(d_,"__esModule",{value:!0}),d_.shouldPolyfill=n;function n(){return!Intl.Segmenter}return d_}var LGe=PGe(),h_={},pj;function AGe(){if(pj)return h_;pj=1,Object.defineProperty(h_,"__esModule",{value:!0}),h_.shouldPolyfill=n;function n(){return typeof Intl>"u"||!("DurationFormat"in Intl)}return h_}var OGe=AGe();const ite=Object.assign({"../locales/bg/app.json":zVe,"../locales/cs/app.json":YVe,"../locales/de/app.json":XVe,"../locales/el/app.json":JVe,"../locales/en/app.json":ZVe,"../locales/es/app.json":QVe,"../locales/et/app.json":eGe,"../locales/fa/app.json":tGe,"../locales/fr/app.json":nGe,"../locales/id/app.json":rGe,"../locales/it/app.json":iGe,"../locales/ja/app.json":sGe,"../locales/lv/app.json":oGe,"../locales/pl/app.json":aGe,"../locales/ro/app.json":cGe,"../locales/ru/app.json":lGe,"../locales/sk/app.json":uGe,"../locales/sv/app.json":dGe,"../locales/tr/app.json":hGe,"../locales/uk/app.json":fGe,"../locales/vi/app.json":pGe,"../locales/zh-Hans/app.json":mGe,"../locales/zh-Hant/app.json":gGe}),MGe=(n,e)=>ite[`../locales/${n}/${e}.json`],NGe=[...new Set(Object.keys(ite).map(n=>{var t;const e=(t=n.match(/\/([^/]+)\/[^/]+\.json$/))==null?void 0:t[1];if(!e)throw new Error(`Could not parse locale URL ${n}`);return e}))],DGe={type:"backend",init(){},read(n,e,t){(async()=>{const r=MGe(n,e);if(!r)throw new Error(`Namespace ${e} for locale ${n} not found`);const i=await fetch(r,{credentials:"omit",headers:{Accept:"application/json"}});if(kL(i))throw Error(`Failed to fetch ${r}`);return await i.json()})().then(r=>t(null,r),r=>t(r,null))}};class FGe{constructor(){this.config=0,this.sentry=0,this.openTelemetry=0}allDepsAreLoaded(){return!Object.values(this).some(e=>e!==2)}}class Us{constructor(){this.isInitialized=!1,this.loadStates=new FGe}static isInitialized(){var e;return(e=Us.internalInstance)==null?void 0:e.isInitialized}static async initBeforeReact(){const e=[];LGe.shouldPolyfill()&&e.push(rv(()=>import("./polyfill-force-Baj25WyX.js").then(s=>s.p),__vite__mapDeps([2,3]),import.meta.url)),OGe.shouldPolyfill()&&e.push(rv(()=>import("./polyfill-force-Dn71dwtm.js").then(s=>s.p),__vite__mapDeps([4,3]),import.meta.url)),await Promise.all(e);const t=new rte;t.addDetector({name:"urlFragment",lookup:()=>Rs().lang??void 0}),await hi.use(DGe).use(t).use(UTe).init({fallbackLng:"en",defaultNS:"app",keySeparator:".",nsSeparator:!1,pluralSeparator:"_",contextSeparator:"|",supportedLngs:NGe,interpolation:{escapeValue:!1},detection:{order:["urlFragment","navigator"],caches:[]}});const{fonts:r,fontScale:i}=Rs();i!==null&&document.documentElement.style.setProperty("--font-scale",i.toString()),r.length>0&&document.documentElement.style.setProperty("--font-family",r.map(s=>`"${s}"`).join(", ")),document.body.setAttribute("data-platform",wd)}static init(){var e;return(e=Us==null?void 0:Us.internalInstance)!=null&&e.initPromise?null:(Us.internalInstance=new Us,Us.internalInstance.initPromise=new Promise(t=>{Us.internalInstance.initStep(t)}),Us.internalInstance.initPromise)}initStep(e){var t,r,i,s;this.loadStates.config===0&&(this.loadStates.config=1,gt.init().then(()=>{this.loadStates.config=2,this.initStep(e)},o=>{M.error("Failed to load config",o)})),this.loadStates.sentry===0&&this.loadStates.config===2&&((t=gt.get().sentry)!=null&&t.DSN&&((r=gt.get().sentry)!=null&&r.environment)&&_ye({dsn:(i=gt.get().sentry)==null?void 0:i.DSN,environment:(s=gt.get().sentry)==null?void 0:s.environment,integrations:[Uye({useEffect:Re.useEffect,useLocation:di,useNavigationType:Rde,createRoutesFromChildren:Jb,matchRoutes:r6})],tracesSampleRate:1}),this.loadStates.sentry=2),this.loadStates.openTelemetry===0&&this.loadStates.config===2&&(yE.globalInit(),this.loadStates.openTelemetry=2),this.loadStates.allDepsAreLoaded()&&(e(),this.isInitialized=!0)}}const UGe=()=>{const[n,e]=_.useState(()=>Rs().theme),t=_.useRef(document.body.classList.item(0));_.useEffect(()=>{if(Je){const r=i=>{i.preventDefault(),"name"in i.detail.data&&typeof i.detail.data.name=="string"&&e(i.detail.data.name),Je.api.transport.reply(i.detail,{})};return Je.lazyActions.on(hr.ThemeChange,r),()=>{Je.lazyActions.off(hr.ThemeChange,r)}}},[]),_.useLayoutEffect(()=>{const r=n!=null&&n.includes("light")?"light":"dark",i=n!=null&&n.includes("high-contrast")?"-hc":"",s="cpd-theme-"+r+i;s!==t.current&&(document.body.classList.remove("cpd-theme-light","cpd-theme-dark","cpd-theme-light-hc","cpd-theme-dark-hc"),document.body.classList.add(s),t.current=s),document.body.classList.remove("no-theme")},[t,n])},f_=jye(PV),jGe=({children:n})=>{const{pathname:e}=di();return _.useEffect(()=>{let t="";!["/login","/register"].includes(e)&&!Je&&(t="var(--background-gradient)"),document.getElementsByTagName("body")[0].style.backgroundImage=t},[e]),w.jsx(w.Fragment,{children:n})},$Ge=({children:n})=>(UGe(),n),BGe=()=>{const[n,e]=_.useState(!1);return _.useEffect(()=>{var t;(t=Us.init())==null||t.then(async()=>{n||(e(!0),await(Je==null?void 0:Je.api.sendContentLoaded()))}).catch(M.error)}),w.jsx(fhe,{children:w.jsx(jGe,{children:w.jsx($Ge,{children:w.jsx(Kq,{children:n?w.jsx(_.Suspense,{fallback:null,children:w.jsx(cNe,{children:w.jsx(e8e,{children:w.jsxs(Hw,{fallback:t=>w.jsx(Kv,{error:t,widget:Je}),children:[w.jsx(WVe,{}),w.jsxs(Vde,{children:[w.jsx(f_,{path:"/",element:w.jsx(ZZ,{})}),w.jsx(f_,{path:"/login",element:w.jsx(z9e,{})}),w.jsx(f_,{path:"/register",element:w.jsx(Y9e,{})}),w.jsx(f_,{path:"*",element:w.jsx(GVe,{})})]})]})})})}):w.jsx(_E,{})})})})})};window.setLKLogLevel=_H;Oke().catch(n=>{M.error("Failed to initialize rageshake",n)});_H("warn");ele((n,e,t)=>{global.mx_rage_logger.log(n,"livekit",e,t)});M.info("Element Call embedded-v0.9.0-release-test.9");const Zx=Eae.createRoot(document.getElementById("root"));let tv=null;window.isSecureContext?navigator.mediaDevices||(tv=new Error("Your browser does not support WebRTC.")):tv=new Error(`This app cannot run in an insecure context. To fix this, access the app via a local loopback address, or serve it over HTTPS.
|
|
220
220
|
https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts`);if(tv!==null)throw Zx.render(tv.message),tv;Us.initBeforeReact().then(()=>{Zx.render(w.jsx(_.StrictMode,{children:w.jsx(BGe,{})}))}).catch(n=>{M.error("Failed to initialize app",n),Zx.render(n.message)});export{JGe as A,hoe as B,gt as C,uoe as D,ie as E,Es as F,pn as G,vw as H,doe as I,_c as J,We as K,KGe as L,mn as M,M5 as N,sk as O,foe as P,poe as Q,Qn as R,Yu as S,Yn as T,ZGe as U,Id as V,goe as W,io as _,VGe as a,oo as b,HGe as c,XGe as d,qGe as e,oF as f,Wo as g,cr as h,KZ as i,de as j,_f as k,M as l,Le as m,cw as n,h$ as o,uB as p,Joe as q,oy as r,Td as s,rqe as t,zo as u,Zl as v,lr as w,Soe as x,y_ as y,QGe as z};
|
|
221
|
-
//# sourceMappingURL=index-
|
|
221
|
+
//# sourceMappingURL=index-OfDiWbJe.js.map
|