2 lines
404 KiB
JavaScript
2 lines
404 KiB
JavaScript
(self.webpackChunkelement_web=self.webpackChunkelement_web||[]).push([[4387],{"./node_modules/@babel/runtime/helpers/esm/defineProperty.js":(e,t,i)=>{"use strict";i.d(t,{A:()=>n});var s=i("./node_modules/@babel/runtime/helpers/esm/toPropertyKey.js");function n(e,t,i){return(t=(0,s.A)(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}},"./node_modules/@babel/runtime/helpers/esm/toPrimitive.js":(e,t,i)=>{"use strict";i.d(t,{A:()=>n});var s=i("./node_modules/@babel/runtime/helpers/esm/typeof.js");function n(e,t){if("object"!=(0,s.A)(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=(0,s.A)(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}},"./node_modules/@babel/runtime/helpers/esm/toPropertyKey.js":(e,t,i)=>{"use strict";i.d(t,{A:()=>r});var s=i("./node_modules/@babel/runtime/helpers/esm/typeof.js"),n=i("./node_modules/@babel/runtime/helpers/esm/toPrimitive.js");function r(e){var t=(0,n.A)(e,"string");return"symbol"==(0,s.A)(t)?t:t+""}},"./node_modules/@babel/runtime/helpers/esm/typeof.js":(e,t,i)=>{"use strict";function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}i.d(t,{A:()=>s})},"./node_modules/loglevel/lib/loglevel.js":function(e,t,i){var s,n;!function(){"use strict";s=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],n={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(s){return"debug"===s&&(s="log"),typeof console!==t&&("trace"===s&&i?a:void 0!==console[s]?o(console,s):void 0!==console.log?o(console,"log"):e)}function l(){for(var i=this.getLevel(),n=0;n<s.length;n++){var r=s[n];this[r]=n<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function c(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function h(e,t,i){return d(e)||c.apply(this,arguments)}function u(e,i){var o,a,d,c=this,u="loglevel";function m(e){var i=(s[e]||"silent").toUpperCase();if(typeof window!==t&&u){try{return void(window.localStorage[u]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"="+i+";"}catch(e){}}}function v(){var e;if(typeof window!==t&&u){try{e=window.localStorage[u]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,s=encodeURIComponent(u),n=i.indexOf(s+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n+s.length+1))[1])}catch(e){}return void 0===c.levels[e]&&(e=void 0),e}}function p(){if(typeof window!==t&&u){try{window.localStorage.removeItem(u)}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}function g(e){var t=e;if("string"==typeof t&&void 0!==c.levels[t.toUpperCase()]&&(t=c.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=c.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?u+=":"+e:"symbol"==typeof e&&(u=void 0),c.name=e,c.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},c.methodFactory=i||h,c.getLevel=function(){return null!=d?d:null!=a?a:o},c.setLevel=function(e,t){return d=g(e),!1!==t&&m(d),l.call(c)},c.setDefaultLevel=function(e){a=g(e),v()||c.setLevel(e,!1)},c.resetLevel=function(){d=null,p(),l.call(c)},c.enableAll=function(e){c.setLevel(c.levels.TRACE,e)},c.disableAll=function(e){c.setLevel(c.levels.SILENT,e)},c.rebuild=function(){if(r!==c&&(o=g(r.getLevel())),l.call(c),r===c)for(var e in n)n[e].rebuild()},o=g(r?r.getLevel():"WARN");var f=v();null!=f&&(d=g(f)),l.call(c)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=n[e];return t||(t=n[e]=new u(e,r.methodFactory)),t};var m=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return n},r.default=r,r},void 0===(n="function"==typeof s?s.call(t,i,t,e):s)||(e.exports=n)}()},"./node_modules/matrix-js-sdk/src/@types/PushRules.ts":(e,t,i)=>{"use strict";i.d(t,{Ji:()=>o,QN:()=>n,YU:()=>s,kq:()=>a,wp:()=>r});let s=function(e){return e.DontNotify="dont_notify",e.Notify="notify",e.Coalesce="coalesce",e}({}),n=function(e){return e.Highlight="highlight",e.Sound="sound",e}({});let r=function(e){return e.EventMatch="event_match",e.EventPropertyIs="event_property_is",e.EventPropertyContains="event_property_contains",e.ContainsDisplayName="contains_display_name",e.RoomMemberCount="room_member_count",e.SenderNotificationPermission="sender_notification_permission",e.CallStarted="call_started",e.CallStartedPrefix="org.matrix.msc3914.call_started",e}({}),o=function(e){return e.Override="override",e.ContentSpecific="content",e.RoomSpecific="room",e.SenderSpecific="sender",e.Underride="underride",e}({}),a=function(e){return e.Master=".m.rule.master",e.IsUserMention=".m.rule.is_user_mention",e.IsRoomMention=".m.rule.is_room_mention",e.ContainsDisplayName=".m.rule.contains_display_name",e.ContainsUserName=".m.rule.contains_user_name",e.AtRoomNotification=".m.rule.roomnotif",e.DM=".m.rule.room_one_to_one",e.EncryptedDM=".m.rule.encrypted_room_one_to_one",e.Message=".m.rule.message",e.EncryptedMessage=".m.rule.encrypted",e.InviteToSelf=".m.rule.invite_for_me",e.MemberEvent=".m.rule.member_event",e.IncomingCall=".m.rule.call",e.SuppressNotices=".m.rule.suppress_notices",e.Tombstone=".m.rule.tombstone",e.PollStart=".m.rule.poll_start",e.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",e.PollEnd=".m.rule.poll_end",e.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",e.PollStartOneToOne=".m.rule.poll_start_one_to_one",e.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",e.PollEndOneToOne=".m.rule.poll_end_one_to_one",e.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one",e}({})},"./node_modules/matrix-js-sdk/src/@types/beacon.ts":(e,t,i)=>{"use strict";i.d(t,{E:()=>n,z:()=>r});var s=i("./node_modules/matrix-js-sdk/src/NamespacedValue.ts");const n=new s.qr("m.beacon_info","org.matrix.msc3672.beacon_info"),r=new s.qr("m.beacon","org.matrix.msc3672.beacon")},"./node_modules/matrix-js-sdk/src/@types/event.ts":(e,t,i)=>{"use strict";i.d(t,{Bx:()=>n,CJ:()=>d,Ct:()=>a,D7:()=>c,ID:()=>m,Ng:()=>f,SY:()=>R,Sr:()=>E,Wr:()=>o,Xs:()=>I,Yg:()=>y,Z3:()=>g,cr:()=>S,ge:()=>p,iK:()=>v,nN:()=>u,ud:()=>h,wt:()=>l,zZ:()=>r});var s=i("./node_modules/matrix-js-sdk/src/NamespacedValue.ts");let n=function(e){return e.RoomCanonicalAlias="m.room.canonical_alias",e.RoomCreate="m.room.create",e.RoomJoinRules="m.room.join_rules",e.RoomMember="m.room.member",e.RoomThirdPartyInvite="m.room.third_party_invite",e.RoomPowerLevels="m.room.power_levels",e.RoomName="m.room.name",e.RoomTopic="m.room.topic",e.RoomAvatar="m.room.avatar",e.RoomPinnedEvents="m.room.pinned_events",e.RoomEncryption="m.room.encryption",e.RoomHistoryVisibility="m.room.history_visibility",e.RoomGuestAccess="m.room.guest_access",e.RoomServerAcl="m.room.server_acl",e.RoomTombstone="m.room.tombstone",e.RoomPredecessor="org.matrix.msc3946.room_predecessor",e.PolicyRuleUser="m.policy.rule.user",e.PolicyRuleRoom="m.policy.rule.room",e.PolicyRuleServer="m.policy.rule.server",e.SpaceChild="m.space.child",e.SpaceParent="m.space.parent",e.RoomRedaction="m.room.redaction",e.RoomMessage="m.room.message",e.RoomMessageEncrypted="m.room.encrypted",e.Sticker="m.sticker",e.CallInvite="m.call.invite",e.CallCandidates="m.call.candidates",e.CallAnswer="m.call.answer",e.CallHangup="m.call.hangup",e.CallReject="m.call.reject",e.CallSelectAnswer="m.call.select_answer",e.CallNegotiate="m.call.negotiate",e.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",e.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",e.CallReplaces="m.call.replaces",e.CallAssertedIdentity="m.call.asserted_identity",e.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",e.CallEncryptionKeysPrefix="io.element.call.encryption_keys",e.KeyVerificationRequest="m.key.verification.request",e.KeyVerificationStart="m.key.verification.start",e.KeyVerificationCancel="m.key.verification.cancel",e.KeyVerificationMac="m.key.verification.mac",e.KeyVerificationDone="m.key.verification.done",e.KeyVerificationKey="m.key.verification.key",e.KeyVerificationAccept="m.key.verification.accept",e.KeyVerificationReady="m.key.verification.ready",e.RoomMessageFeedback="m.room.message.feedback",e.Reaction="m.reaction",e.PollStart="org.matrix.msc3381.poll.start",e.Typing="m.typing",e.Receipt="m.receipt",e.Presence="m.presence",e.FullyRead="m.fully_read",e.Tag="m.tag",e.SpaceOrder="org.matrix.msc3230.space_order",e.PushRules="m.push_rules",e.Direct="m.direct",e.IgnoredUserList="m.ignored_user_list",e.RoomKey="m.room_key",e.RoomKeyRequest="m.room_key_request",e.ForwardedRoomKey="m.forwarded_room_key",e.Dummy="m.dummy",e.SecretRequest="m.secret.request",e.SecretSend="m.secret.send",e.GroupCallPrefix="org.matrix.msc3401.call",e.GroupCallMemberPrefix="org.matrix.msc3401.call.member",e.RTCMembership="org.matrix.msc4143.rtc.member",e.CallNotify="org.matrix.msc4075.call.notify",e.RTCNotification="org.matrix.msc4075.rtc.notification",e.RTCDecline="org.matrix.msc4310.rtc.decline",e}({}),r=function(e){return e.Annotation="m.annotation",e.Replace="m.replace",e.Reference="m.reference",e.Thread="m.thread",e}({}),o=function(e){return e.Text="m.text",e.Emote="m.emote",e.Notice="m.notice",e.Image="m.image",e.File="m.file",e.Audio="m.audio",e.Location="m.location",e.Video="m.video",e.KeyVerificationRequest="m.key.verification.request",e}({});const a="type";let d=function(e){return e.Space="m.space",e.UnstableCall="org.matrix.msc3417.call",e.ElementVideo="io.element.video",e}({});const l="org.matrix.msgid",c=new s.qr("m.room.purpose","org.matrix.msc3088.purpose"),h=new s.qr("m.enabled","org.matrix.msc3088.enabled"),u=new s.qr("m.data_tree","org.matrix.msc3089.data_tree"),m=new s.qr("m.leaf","org.matrix.msc3089.leaf"),v=new s.qr("m.branch","org.matrix.msc3089.branch"),p=new s.qr("m.room.marker","org.matrix.msc2716.marker"),g=new s.qr("with_rel_types","org.matrix.msc3912.with_relations"),f=new s.qr("io.element.functional_members","io.element.functional_members"),y=new s.qr("m.visibility","org.matrix.msc3531.visibility"),S=new s.qr("enabled","org.matrix.msc3881.enabled"),I=(new s.qr("device_id","org.matrix.msc3881.device_id"),new s.qr("m.local_notification_settings","org.matrix.msc3890.local_notification_settings")),E=new s.qr("thread_id","org.matrix.msc4023.thread_id"),R=new s.xu("membership","io.element.msc4115.membership")},"./node_modules/matrix-js-sdk/src/@types/extensible_events.ts":(e,t,i)=>{"use strict";var s=i("./node_modules/matrix-events-sdk/lib/index.js");new s.UnstableValue("m.message","org.matrix.msc1767.message"),new s.UnstableValue("m.text","org.matrix.msc1767.text"),new s.UnstableValue("m.html","org.matrix.msc1767.html"),new s.NamespacedValue("m.reference")},"./node_modules/matrix-js-sdk/src/@types/location.ts":(e,t,i)=>{"use strict";i.d(t,{J1:()=>n,M6:()=>o,vo:()=>r});var s=i("./node_modules/matrix-js-sdk/src/NamespacedValue.ts");const n=new s.qr("m.asset","org.matrix.msc3488.asset"),r=new s.qr("m.ts","org.matrix.msc3488.ts"),o=new s.qr("m.location","org.matrix.msc3488.location")},"./node_modules/matrix-js-sdk/src/@types/partials.ts":(e,t,i)=>{"use strict";i.d(t,{Jv:()=>o,dx:()=>n,k:()=>s,rF:()=>r});let s=function(e){return e.PrivateChat="private_chat",e.TrustedPrivateChat="trusted_private_chat",e.PublicChat="public_chat",e}({}),n=function(e){return e.Public="public",e.Invite="invite",e.Private="private",e.Knock="knock",e.Restricted="restricted",e}({}),r=function(e){return e.CanJoin="can_join",e.Forbidden="forbidden",e}({}),o=function(e){return e.Invited="invited",e.Joined="joined",e.Shared="shared",e.WorldReadable="world_readable",e}({})},"./node_modules/matrix-js-sdk/src/@types/polls.ts":(e,t,i)=>{"use strict";i.d(t,{cI:()=>r,qN:()=>n});var s=i("./node_modules/matrix-events-sdk/lib/index.js");new s.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed"),new s.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed"),new s.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");const n=new s.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response"),r=new s.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end")},"./node_modules/matrix-js-sdk/src/@types/read_receipts.ts":(e,t,i)=>{"use strict";i.d(t,{L:()=>s,S:()=>n});let s=function(e){return e.Read="m.read",e.FullyRead="m.fully_read",e.ReadPrivate="m.read.private",e}({});const n="main"},"./node_modules/matrix-js-sdk/src/@types/requests.ts":(e,t,i)=>{"use strict";function s(e){return(!("parent_delay_id"in e)||"string"==typeof e.parent_delay_id)&&("delay"in e&&"number"!=typeof e.delay||("delay"in e||"parent_delay_id"in e))}i.d(t,{U:()=>s,e:()=>n});let n=function(e){return e.Cancel="cancel",e.Restart="restart",e.Send="send",e}({})},"./node_modules/matrix-js-sdk/src/@types/search.ts":(e,t,i)=>{"use strict";i.d(t,{g:()=>s});let s=function(e){return e.Recent="recent",e.Rank="rank",e}({})},"./node_modules/matrix-js-sdk/src/@types/sync.ts":(e,t,i)=>{"use strict";i.d(t,{a:()=>s});const s=new(i("./node_modules/matrix-js-sdk/src/NamespacedValue.ts").M6)("unread_thread_notifications","org.matrix.msc3773.unread_thread_notifications")},"./node_modules/matrix-js-sdk/src/@types/topic.ts":(e,t,i)=>{"use strict";i.d(t,{s:()=>s});const s=new(i("./node_modules/matrix-js-sdk/src/NamespacedValue.ts").xu)("m.topic")},"./node_modules/matrix-js-sdk/src/NamespacedValue.ts":(e,t,i)=>{"use strict";i.d(t,{M6:()=>r,qr:()=>o,xu:()=>n});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js");class n{constructor(e,t){if(this.stable=e,this.unstable=t,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}get name(){return this.stable?this.stable:this.unstable}get altName(){return this.stable?this.unstable:null}get names(){const e=[this.name],t=this.altName;return t&&e.push(t),e}matches(e){return this.name===e||this.altName===e}findIn(e){let t;return this.name&&(t=null==e?void 0:e[this.name]),!t&&this.altName&&(t=null==e?void 0:e[this.altName]),t}includedIn(e){let t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}}class r extends n{constructor(...e){super(...e),(0,s.A)(this,"preferUnstable",!1)}setPreferUnstable(e){this.preferUnstable=e}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}}class o extends n{constructor(e,t){if(super(e,t),!this.unstable)throw new Error("Unstable value must be supplied")}get name(){return this.unstable}get altName(){return this.stable}}},"./node_modules/matrix-js-sdk/src/autodiscovery.ts":(e,t,i)=>{"use strict";i.d(t,{MN:()=>l});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/logger.ts"),r=i("./node_modules/matrix-js-sdk/src/http-api/index.ts"),o=i("./node_modules/matrix-js-sdk/src/version-support.ts");let a=function(e){return e.SUCCESS="SUCCESS",e.IGNORE="IGNORE",e.PROMPT="PROMPT",e.FAIL_PROMPT="FAIL_PROMPT",e.FAIL_ERROR="FAIL_ERROR",e}({}),d=function(e){return e.Invalid="Invalid homeserver discovery response",e.GenericFailure="Failed to get autodiscovery configuration from server",e.InvalidHsBaseUrl="Invalid base_url for m.homeserver",e.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",e.InvalidIsBaseUrl="Invalid base_url for m.identity_server",e.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",e.InvalidIs="Invalid identity server discovery response",e.MissingWellknown="No .well-known JSON file found",e.InvalidJson="Invalid JSON",e.UnsupportedHomeserverSpecVersion="The homeserver does not meet the version requirements",e}({});class l{static async fromDiscoveryConfig(e){var t;const i={"m.homeserver":{state:l.FAIL_ERROR,error:l.ERROR_INVALID,base_url:null},"m.identity_server":{state:l.PROMPT,error:null,base_url:null}};if(null==e||!e["m.homeserver"])return n.vF.error("No m.homeserver key in config"),i["m.homeserver"].state=l.FAIL_PROMPT,i["m.homeserver"].error=l.ERROR_INVALID,Promise.resolve(i);if(!e["m.homeserver"].base_url)return n.vF.error("No m.homeserver base_url in config"),i["m.homeserver"].state=l.FAIL_PROMPT,i["m.homeserver"].error=l.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);const s=this.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!s)return n.vF.error("Invalid base_url for m.homeserver"),i["m.homeserver"].error=l.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);const r=await this.fetchWellKnownObject(`${s}/_matrix/client/versions`);if(!r||!Array.isArray(null===(t=r.raw)||void 0===t?void 0:t.versions))return n.vF.error("Invalid /versions response"),i["m.homeserver"].error=l.ERROR_INVALID_HOMESERVER,i["m.homeserver"].base_url=s,Promise.resolve(i);const d=new Set(r.raw.versions);let c=!1;for(const e of o.Hr)if(d.has(e)){c=!0;break}if(!c)return n.vF.error("Homeserver does not meet version requirements"),i["m.homeserver"].error=l.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION,i["m.homeserver"].base_url=s,Promise.resolve(i);i["m.homeserver"]={state:l.SUCCESS,error:null,base_url:s};let h="";if(e["m.identity_server"]){const t={"m.homeserver":i["m.homeserver"],"m.identity_server":{state:l.FAIL_PROMPT,error:l.ERROR_INVALID_IS,base_url:null}};if(h=this.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!h)return n.vF.error("Invalid base_url for m.identity_server"),t["m.identity_server"].error=l.ERROR_INVALID_IS_BASE_URL,Promise.resolve(t);const s=await this.fetchWellKnownObject(`${h}/_matrix/identity/v2`);if(null==s||!s.raw||s.action!==a.SUCCESS)return n.vF.error("Invalid /v2 response"),t["m.identity_server"].error=l.ERROR_INVALID_IDENTITY_SERVER,t["m.identity_server"].base_url=h,Promise.resolve(t)}return h&&h.toString().length>0&&(i["m.identity_server"]={state:l.SUCCESS,error:null,base_url:h}),Object.keys(e).forEach(t=>{if("m.homeserver"===t||"m.identity_server"===t){const s=["error","state","base_url"];for(const n of Object.keys(e[t]))s.includes(n)||(i[t][n]=e[t][n])}else i[t]=e[t]}),Promise.resolve(i)}static async findClientConfig(e){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t={"m.homeserver":{state:l.FAIL_ERROR,error:l.ERROR_INVALID,base_url:null},"m.identity_server":{state:l.PROMPT,error:null,base_url:null}},i=e.includes("://")?e:`https://${e}`,s=await this.fetchWellKnownObject(`${i}/.well-known/matrix/client`);return s&&s.action===a.SUCCESS?l.fromDiscoveryConfig(s.raw):(n.vF.error("No response or error when parsing .well-known"),s.reason&&n.vF.error(s.reason),s.action===a.IGNORE?t["m.homeserver"]={state:l.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=l.FAIL_PROMPT,t["m.homeserver"].error=l.ERROR_INVALID),Promise.resolve(t))}static async getRawClientConfig(e){var t;if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const i=await this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return i&&null!==(t=i.raw)&&void 0!==t?t:{}}static sanitizeWellKnownUrl(e){if(!e)return!1;try{var t;let i;try{i=new URL(e)}catch(e){n.vF.error("Could not parse url",e)}if(null===(t=i)||void 0===t||!t.hostname)return!1;if("http:"!==i.protocol&&"https:"!==i.protocol)return!1;const s=i.port?`:${i.port}`:"",r=i.pathname?i.pathname:"";let o=`${i.protocol}//${i.hostname}${s}${r}`;return o.endsWith("/")&&(o=o.substring(0,o.length-1)),o}catch(e){return n.vF.error(e),!1}}static fetch(e,t){return this.fetchFn?this.fetchFn(e,t):globalThis.fetch(e,t)}static setFetchFn(e){l.fetchFn=e}static async fetchWellKnownObject(e){let t;try{if(t=await l.fetch(e,{method:r.IT.Get,signal:(0,r._)(5e3)}),404===t.status)return{raw:{},action:a.IGNORE,reason:l.ERROR_MISSING_WELLKNOWN};if(200!==t.status)return{raw:{},action:a.FAIL_PROMPT,reason:"General failure"}}catch(e){const t=e;let i="";return"object"==typeof t&&(i=null==t?void 0:t.message),{error:t,raw:{},action:a.FAIL_PROMPT,reason:i||"General failure"}}try{return{raw:await t.json(),action:a.SUCCESS}}catch(e){const t=e;return{error:t,raw:{},action:a.FAIL_PROMPT,reason:"SyntaxError"===(null==t?void 0:t.name)?l.ERROR_INVALID_JSON:l.ERROR_INVALID}}}}(0,s.A)(l,"ERROR_INVALID",d.Invalid),(0,s.A)(l,"ERROR_GENERIC_FAILURE",d.GenericFailure),(0,s.A)(l,"ERROR_INVALID_HS_BASE_URL",d.InvalidHsBaseUrl),(0,s.A)(l,"ERROR_INVALID_HOMESERVER",d.InvalidHomeserver),(0,s.A)(l,"ERROR_INVALID_IS_BASE_URL",d.InvalidIsBaseUrl),(0,s.A)(l,"ERROR_INVALID_IDENTITY_SERVER",d.InvalidIdentityServer),(0,s.A)(l,"ERROR_INVALID_IS",d.InvalidIs),(0,s.A)(l,"ERROR_MISSING_WELLKNOWN",d.MissingWellknown),(0,s.A)(l,"ERROR_INVALID_JSON",d.InvalidJson),(0,s.A)(l,"ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION",d.UnsupportedHomeserverSpecVersion),(0,s.A)(l,"ALL_ERRORS",Object.keys(d)),(0,s.A)(l,"FAIL_ERROR",a.FAIL_ERROR),(0,s.A)(l,"FAIL_PROMPT",a.FAIL_PROMPT),(0,s.A)(l,"PROMPT",a.PROMPT),(0,s.A)(l,"SUCCESS",a.SUCCESS),(0,s.A)(l,"fetchFn",void 0)},"./node_modules/matrix-js-sdk/src/client.ts":(e,t,i)=>{"use strict";i.d(t,{AU:()=>ce,Xb:()=>ve,eO:()=>oe,fN:()=>pe});var s=i("./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js"),n=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),r=i("./node_modules/matrix-js-sdk/src/sync.ts"),o=i("./node_modules/matrix-js-sdk/src/models/event.ts"),a=i("./node_modules/matrix-js-sdk/src/store/stub.ts"),d=i("./node_modules/matrix-js-sdk/src/webrtc/call.ts"),l=i("./node_modules/matrix-js-sdk/src/filter.ts"),c=i("./node_modules/matrix-js-sdk/src/webrtc/callEventHandler.ts"),h=i("./node_modules/matrix-js-sdk/src/webrtc/groupCallEventHandler.ts"),u=i("./node_modules/matrix-js-sdk/src/utils.ts"),m=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),v=i("./node_modules/matrix-js-sdk/src/pushprocessor.ts"),p=i("./node_modules/matrix-js-sdk/src/autodiscovery.ts"),g=i("./node_modules/matrix-js-sdk/src/base64.ts"),f=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),y=i("./node_modules/matrix-js-sdk/src/logger.ts"),S=i("./node_modules/matrix-js-sdk/src/service-types.ts"),I=i("./node_modules/matrix-js-sdk/src/http-api/index.ts"),E=i("./node_modules/matrix-js-sdk/src/models/user.ts"),R=i("./node_modules/matrix-js-sdk/src/content-repo.ts"),b=i("./node_modules/matrix-js-sdk/src/models/search-result.ts"),T=i("./node_modules/matrix-js-sdk/src/content-helpers.ts"),_=i("./node_modules/matrix-js-sdk/src/models/room.ts"),w=i("./node_modules/matrix-js-sdk/src/models/room-member.ts"),C=i("./node_modules/matrix-js-sdk/src/@types/requests.ts"),k=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),A=i("./node_modules/matrix-js-sdk/src/@types/partials.ts"),M=i("./node_modules/matrix-js-sdk/src/event-mapper.ts"),x=i("./node_modules/matrix-js-sdk/src/randomstring.ts"),F=i("./node_modules/matrix-js-sdk/src/models/MSC3089TreeSpace.ts"),O=i("./node_modules/matrix-js-sdk/src/@types/search.ts"),P=i("./node_modules/matrix-js-sdk/src/@types/PushRules.ts"),D=i("./node_modules/matrix-js-sdk/src/webrtc/groupCall.ts"),U=i("./node_modules/matrix-js-sdk/src/webrtc/mediaHandler.ts"),L=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),N=i("./node_modules/matrix-js-sdk/src/@types/read_receipts.ts"),j=i("./node_modules/matrix-js-sdk/src/sliding-sync-sdk.ts"),$=i("./node_modules/matrix-js-sdk/src/models/thread.ts"),B=i("./node_modules/matrix-js-sdk/src/@types/beacon.ts"),q=i("./node_modules/matrix-js-sdk/src/NamespacedValue.ts"),V=i("./node_modules/matrix-js-sdk/src/ToDeviceMessageQueue.ts"),G=i("./node_modules/matrix-js-sdk/src/models/invites-ignorer.ts"),H=i("./node_modules/matrix-js-sdk/src/feature.ts"),K=i("./node_modules/matrix-js-sdk/src/rust-crypto/constants.ts"),W=i("./node_modules/matrix-js-sdk/src/crypto-api/index.ts"),J=i("./node_modules/matrix-js-sdk/src/secret-storage.ts"),z=i("./node_modules/matrix-js-sdk/src/matrixrtc/MatrixRTCSessionManager.ts"),Y=i("./node_modules/matrix-js-sdk/src/thread-utils.ts"),Q=i("./node_modules/matrix-js-sdk/src/@types/membership.ts"),X=i("./node_modules/matrix-js-sdk/src/serverCapabilities.ts"),Z=i("./node_modules/matrix-js-sdk/src/digest.ts"),ee=i("./node_modules/matrix-js-sdk/src/oidc/index.ts"),te=i("./node_modules/matrix-js-sdk/src/errors.ts");const ie=["server","limit","since"];function se(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function ne(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?se(Object(i),!0).forEach(function(t){(0,n.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):se(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}const re=6e5;new q.qr("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent");let oe=function(e){return e.Chronological="chronological",e.Detached="detached",e}({});new q.xu("m.get_login_token","org.matrix.msc3882.get_login_token");const ae="org.matrix.msc4140",de="org.matrix.msc4354";const le="$";let ce=function(e){return e.Sync="sync",e.Event="event",e.ToDeviceEvent="toDeviceEvent",e.ReceivedToDeviceMessage="receivedToDeviceMessage",e.AccountData="accountData",e.Room="Room",e.DeleteRoom="deleteRoom",e.SyncUnexpectedError="sync.unexpectedError",e.ClientWellKnown="WellKnown.client",e.ReceivedVoipEvent="received_voip_event",e.TurnServers="turnServers",e.TurnServersError="turnServers.error",e}({});const he=new q.qr("action","org.matrix.msc3824.action");class ue extends L.X{constructor(e){var t,i,s,r,l;super(),(0,n.A)(this,"logger",void 0),(0,n.A)(this,"reEmitter",new f.Q(this)),(0,n.A)(this,"olmVersion",null),(0,n.A)(this,"usingExternalCrypto",!1),(0,n.A)(this,"_store",void 0),(0,n.A)(this,"deviceId",void 0),(0,n.A)(this,"credentials",void 0),(0,n.A)(this,"legacyPickleKey",void 0),(0,n.A)(this,"scheduler",void 0),(0,n.A)(this,"clientRunning",!1),(0,n.A)(this,"timelineSupport",!1),(0,n.A)(this,"urlPreviewCache",{}),(0,n.A)(this,"identityServer",void 0),(0,n.A)(this,"http",void 0),(0,n.A)(this,"cryptoBackend",void 0),(0,n.A)(this,"enableEncryptedStateEvents",void 0),(0,n.A)(this,"cryptoCallbacks",void 0),(0,n.A)(this,"callEventHandler",void 0),(0,n.A)(this,"groupCallEventHandler",void 0),(0,n.A)(this,"supportsCallTransfer",!1),(0,n.A)(this,"forceTURN",!1),(0,n.A)(this,"iceCandidatePoolSize",0),(0,n.A)(this,"idBaseUrl",void 0),(0,n.A)(this,"baseUrl",void 0),(0,n.A)(this,"isVoipWithNoMediaAllowed",void 0),(0,n.A)(this,"disableVoip",void 0),(0,n.A)(this,"useLivekitForGroupCalls",void 0),(0,n.A)(this,"canSupportVoip",!1),(0,n.A)(this,"peekSync",null),(0,n.A)(this,"isGuestAccount",!1),(0,n.A)(this,"ongoingScrollbacks",{}),(0,n.A)(this,"notifTimelineSet",null),(0,n.A)(this,"legacyCryptoStore",void 0),(0,n.A)(this,"verificationMethods",void 0),(0,n.A)(this,"fallbackICEServerAllowed",!1),(0,n.A)(this,"syncApi",void 0),(0,n.A)(this,"roomNameGenerator",void 0),(0,n.A)(this,"pushRules",void 0),(0,n.A)(this,"syncLeftRoomsPromise",void 0),(0,n.A)(this,"syncedLeftRooms",!1),(0,n.A)(this,"clientOpts",void 0),(0,n.A)(this,"clientWellKnownIntervalID",void 0),(0,n.A)(this,"canResetTimelineCallback",void 0),(0,n.A)(this,"canSupport",new Map),(0,n.A)(this,"pushProcessor",new v.j(this)),(0,n.A)(this,"serverVersionsPromise",void 0),(0,n.A)(this,"clientWellKnown",void 0),(0,n.A)(this,"clientWellKnownPromise",void 0),(0,n.A)(this,"turnServers",[]),(0,n.A)(this,"turnServersExpiry",0),(0,n.A)(this,"checkTurnServersIntervalID",void 0),(0,n.A)(this,"txnCtr",0),(0,n.A)(this,"mediaHandler",new U.L(this)),(0,n.A)(this,"sessionId",void 0),(0,n.A)(this,"eventsBeingEncrypted",new Set),(0,n.A)(this,"useE2eForGroupCall",!0),(0,n.A)(this,"toDeviceMessageQueue",void 0),(0,n.A)(this,"livekitServiceURL",void 0),(0,n.A)(this,"_secretStorage",void 0),(0,n.A)(this,"ignoredInvites",void 0),(0,n.A)(this,"matrixRTC",void 0),(0,n.A)(this,"serverCapabilitiesService",void 0),(0,n.A)(this,"startCallEventHandler",()=>{this.isInitialSyncComplete()&&((0,d.sj)()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off(ce.Sync,this.startCallEventHandler))}),(0,n.A)(this,"startMatrixRTC",()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off(ce.Sync,this.startMatrixRTC))}),(0,n.A)(this,"fixupRoomNotifications",()=>{if(this.isInitialSyncComplete()){var e;const t=(null!==(e=this.getRooms())&&void 0!==e?e:[]).filter(e=>e.getUnreadNotificationCount(_.X5.Total)>0);for(const e of t){const t=this.getSafeUserId();e.fixupNotifications(t)}this.off(ce.Sync,this.fixupRoomNotifications)}}),this.logger=null!==(t=e.logger)&&void 0!==t?t:y.vF,e.baseUrl=u.hc(e.baseUrl),e.idBaseUrl=u.hc(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=null!==(i=e.usingExternalCrypto)&&void 0!==i&&i,this.store=e.store||new a.E,this.deviceId=e.deviceId||null,this.sessionId=(0,x.US)(10);const m=e.userId||null;this.credentials={userId:m},this.http=new I.ED(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:I.iD.V3,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader,logger:this.logger}),e.pickleKey&&(this.legacyPickleKey=e.pickleKey),this.useLivekitForGroupCalls=Boolean(e.useLivekitForGroupCalls),this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(async e=>{const t=this.getRoom(e.getRoomId());e.status!==o.fb.SENDING&&this.updatePendingEventStatus(t,e,o.fb.SENDING);const i=await this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,o.fb.SENT,i.event_id),i}),this.disableVoip=null!==(s=e.disableVoip)&&void 0!==s&&s,!this.disableVoip&&(0,d.sj)()&&(this.callEventHandler=new c.N(this),this.groupCallEventHandler=new h.e(this),this.canSupportVoip=!0,this.on(ce.Sync,this.startCallEventHandler)),this.matrixRTC=new z.I(this.logger,this),this.serverCapabilitiesService=new X.K(this.logger,this.http),this.on(ce.Sync,this.fixupRoomNotifications),this.timelineSupport=Boolean(e.timelineSupport),this.legacyCryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.enableEncryptedStateEvents=null!==(r=e.enableEncryptedStateEvents)&&void 0!==r&&r,this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=void 0===e.iceCandidatePoolSize?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,void 0!==e.useE2eForGroupCall&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.livekitServiceURL=e.livekitServiceURL,this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new V.k(this,this.logger),this.on(o.OQ.Decrypted,e=>{!function(e,t){var i;const s=e.getUserId(),n=t.getId(),r=e.getRoom(t.getRoomId());if(!r||!s||!n)return;if(!r.findEventById(n))return void y.vF.info(`Decrypted event ${t.getId()} is not in room ${r.roomId}: ignoring`);const o=!!t.threadRootId&&!t.isThreadRoot;let a;if(o){const e=r.getThread(t.threadRootId);a=!e||e.hasUserReadEvent(s,n)}else a=r.hasUserReadEvent(s,n);if(a)return;const d=e.getPushActionsForEvent(t,!0);if(null!=d&&null!==(i=d.tweaks)&&void 0!==i&&i.highlight){const e=r.getUnreadCountForEventContext(_.X5.Highlight,t)+1;o?r.setThreadUnreadNotificationCount(t.threadRootId,_.X5.Highlight,e):r.setUnreadNotificationCount(_.X5.Highlight,e)}if(null!=d&&d.notify){const e=r.getUnreadCountForEventContext(_.X5.Total,t)+1;o?r.setThreadUnreadNotificationCount(t.threadRootId,_.X5.Total,e):r.setUnreadNotificationCount(_.X5.Total,e)}}(this,e)}),this.ignoredInvites=new G.bp(this),this._secretStorage=new J.ServerSideSecretStorageImpl(this,null!==(l=e.cryptoCallbacks)&&void 0!==l?l:{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(e=>E.K.createUser(e,this))}get store(){return this._store}async startClient(e){if(this.clientRunning)return;this.clientRunning=!0,this.on(ce.Sync,this.startMatrixRTC);const t=this.getUserId();t&&this.store.storeUser(new E.K(t)),this.supportsVoip()&&(this.checkTurnServersIntervalID=setInterval(()=>{this.checkTurnServers()},re),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:e,list:t,fwdPagination:i}=await this.doesServerSupportThread();$.jV.setServerSideSupport(e),$.jV.setServerSideListSupport(t),$.jV.setServerSideFwdPaginationSupport(i)}catch(e){this.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",e)}this.clientOpts=null!=e?e:{},this.clientOpts.slidingSync?this.syncApi=new j.m(this.clientOpts.slidingSync,this,this.clientOpts,this.buildSyncApiOptions()):this.syncApi=new r.w_(this,this.clientOpts,this.buildSyncApiOptions()),this.syncApi.sync().catch(e=>this.logger.info("Sync startup aborted with an error:",e)),void 0!==this.clientOpts.clientWellKnownPollPeriod&&(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),logger:this.logger.getChild("sync")}}stopClient(){var e,t,i,s,n;null===(e=this.cryptoBackend)||void 0===e||e.stop(),this.off(ce.Sync,this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,null===(t=this.syncApi)||void 0===t||t.stop(),this.syncApi=void 0,null===(i=this.peekSync)||void 0===i||i.stopPeeking(),null===(s=this.callEventHandler)||void 0===s||s.stop(),null===(n=this.groupCallEventHandler)||void 0===n||n.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,globalThis.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,void 0!==this.clientWellKnownIntervalID&&globalThis.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop(),this.matrixRTC.stop(),this.serverCapabilitiesService.stop())}clearStores(e={}){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const t=[];t.push(this.store.deleteAllData()),this.legacyCryptoStore&&t.push(this.legacyCryptoStore.deleteAllData());return t.push((async()=>{let t;try{if(t=globalThis.indexedDB,!t)return}catch{return}for(const n of[`${null!==(i=e.cryptoDatabasePrefix)&&void 0!==i?i:K.J}::matrix-sdk-crypto`,`${null!==(s=e.cryptoDatabasePrefix)&&void 0!==s?s:K.J}::matrix-sdk-crypto-meta`]){var i,s;const e=new Promise((e,i)=>{this.logger.info(`Removing IndexedDB instance ${n}`);const s=t.deleteDatabase(n);s.onsuccess=t=>{this.logger.info(`Removed IndexedDB instance ${n}`),e(0)},s.onerror=t=>{this.logger.warn(`Failed to remove IndexedDB instance ${n}:`,t),e(0)},s.onblocked=e=>{this.logger.info(`cannot yet remove IndexedDB instance ${n}`)}});await e}})()),Promise.all(t).then()}getUserId(){var e,t;return null!==(e=null===(t=this.credentials)||void 0===t?void 0:t.userId)&&void 0!==e?e:null}getSafeUserId(){const e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){var e;return null!==(e=this.credentials)&&void 0!==e&&e.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){var e,t;return null!==(e=null===(t=this.credentials)||void 0===t||null===(t=t.userId)||void 0===t?void 0:t.split(":")[0].substring(1))&&void 0!==e?e:null}getDeviceId(){return this.deviceId}getSessionId(){return this.sessionId}supportsVoip(){return!this.disableVoip&&this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(e){return(0,d.sv)(this,e)}async createGroupCall(e,t,i,s,n,r){if(this.getGroupCallForRoom(e))throw new Error(`${e} already has an existing group call`);const o=this.getRoom(e);if(!o)throw new Error(`Cannot find room ${e}`);return new D.eO(this,o,t,i,s,void 0,n||this.isVoipWithNoMediaAllowed,r,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,t;return null!==(e=null===(t=this.syncApi)||void 0===t?void 0:t.getSyncState())&&void 0!==e?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return!!e&&(e===r.Lm.Prepared||e===r.Lm.Syncing)}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),null!==(e=null===(t=this.syncApi)||void 0===t?void 0:t.retryImmediately())&&void 0!==e&&e}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={}){var t,s;if(this.cryptoBackend)return void this.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");const n=this.getUserId();if(null===n)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");const r=this.getDeviceId();if(null===r)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 o=await Promise.all([i.e(3380),i.e(485),i.e(1787)]).then(i.bind(i,"./node_modules/matrix-js-sdk/src/rust-crypto/index.ts")),a=await o.initRustCrypto({logger:this.logger,http:this.http,userId:n,deviceId:r,secretStorage:this.secretStorage,cryptoCallbacks:this.cryptoCallbacks,storePrefix:!1===e.useIndexedDB?null:null!==(t=e.cryptoDatabasePrefix)&&void 0!==t?t:K.J,storeKey:e.storageKey,storePassphrase:e.storagePassword,legacyCryptoStore:this.legacyCryptoStore,legacyPickleKey:null!==(s=this.legacyPickleKey)&&void 0!==s?s:"DEFAULT_KEY",legacyMigrationProgressListener:(e,t)=>{this.emit(W.cr.LegacyCryptoStoreMigrationProgress,e,t)},enableEncryptedStateEvents:this.enableEncryptedStateEvents});a.setSupportedVerificationMethods(this.verificationMethods),this.cryptoBackend=a,this.on(w.o5.Membership,a.onRoomMembership.bind(a)),this.on(ce.Event,e=>{a.onLiveEventFromSync(e)}),this.reEmitter.reEmit(a,[W.cr.VerificationRequestReceived,W.cr.UserTrustStatusChanged,W.cr.KeyBackupStatus,W.cr.KeyBackupSessionsRemaining,W.cr.KeyBackupFailed,W.cr.KeyBackupDecryptionKeyCached,W.cr.KeysChanged,W.cr.DevicesUpdated,W.cr.WillUpdateDevices,W.cr.DehydratedDeviceCreated,W.cr.DehydratedDeviceUploaded,W.cr.RehydrationStarted,W.cr.RehydrationProgress,W.cr.RehydrationCompleted,W.cr.RehydrationError,W.cr.DehydrationKeyCached,W.cr.DehydratedDeviceRotationError])}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isRoomEncrypted(e){const t=this.getRoom(e);return!!t&&t.hasEncryptionStateEvent()}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}makeKeyBackupPath(e,t,i){let s;s=void 0!==t?u.RR("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):void 0!==e?u.RR("/room_keys/keys/$roomId",{$roomId:e}):"/room_keys/keys";return{path:s,queryData:void 0===i?void 0:{version:i}}}async deleteKeysFromBackup(e,t,i){const s=this.makeKeyBackupPath(e,t,i);await this.http.authedRequest(I.IT.Delete,s.path,s.queryData,void 0,{prefix:I.iD.V3})}getMediaConfig(e=!1){const t=e?"/media/config":"/config";return this.http.authedRequest(I.IT.Get,t,void 0,void 0,{prefix:e?I.iD.V1:I.zs.V3})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(e=!1){const t=this.store.getRooms(),i=new Set(t);for(const t of i){const s=this.findPredecessorRooms(t,!0,e);for(const e of s)i.delete(e)}return Array.from(i)}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}async setAccountData(e,t){if(!this.clientRunning)return this.logger.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results."),await(0,I.Y6)(5,()=>this.setAccountDataRaw(e,t));const i=this.store.getAccountData(e);if(i&&(0,u.ky)(i.event.content,t))return{};const s=Promise.withResolvers();function n(t){t.getType()===e&&s.resolve()}this.addListener(ce.AccountData,n);try{const i=await(0,I.Y6)(5,()=>this.setAccountDataRaw(e,t));return await s.promise,i}finally{this.removeListener(ce.AccountData,n)}}setAccountDataRaw(e,t){const i=u.RR("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this.http.authedRequest(I.IT.Put,i,void 0,t)}getAccountData(e){return this.store.getAccountData(e)}async getAccountDataFromServer(e){if(this.isInitialSyncComplete()){const t=this.store.getAccountData(e);return t?t.getContent():null}const t=u.RR("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return await this.http.authedRequest(I.IT.Get,t)}catch(e){var i;if("M_NOT_FOUND"===(null===(i=e.data)||void 0===i?void 0:i.errcode))return null;throw e}}async deleteAccountData(e){const t=this.canSupport.get(H.Xj.AccountDataDeletion);if(t===H.Tj.Unsupported)return void await this.setAccountData(e,{});const i=u.RR("/user/$userId/account_data/$type",{$userId:this.getSafeUserId(),$type:e}),s=t===H.Tj.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return await this.http.authedRequest(I.IT.Delete,i,void 0,void 0,s)}getIgnoredUsers(){const e=this.getAccountData(k.Bx.IgnoredUserList);return null!=e&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){const t={ignored_users:{}};return e.forEach(e=>{t.ignored_users[e]={}}),this.setAccountData(k.Bx.IgnoredUserList,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}async joinRoom(e,t={}){var i,s;const n=this.getRoom(e),o=null==n?void 0:n.getMember(this.getSafeUserId()),a=null==o?void 0:o.membership,d=a==Q.O.Invite&&null!==(i=null==o||null===(s=o.events.member)||void 0===s?void 0:s.getSender())&&void 0!==i?i:null;if(this.logger.debug(`joinRoom[${e}]: preJoinMembership=${a}, inviter=${d}, opts=${JSON.stringify(t)}`),a==Q.O.Join)return n;let l=Promise.resolve();if(t.inviteSignUrl){const e=new URL(t.inviteSignUrl);e.searchParams.set("mxid",this.credentials.userId),l=this.http.requestOtherUrl(I.IT.Post,e)}const c={};t.viaServers&&(c.via=c.server_name=t.viaServers.slice(0,3));const h={},m=await l;m&&(h.third_party_signed=m);const v=u.RR("/join/$roomid",{$roomid:e}),p=(await this.http.authedRequest(I.IT.Post,v,c,h)).room_id;t.acceptSharedHistory&&d&&this.cryptoBackend&&await this.cryptoBackend.maybeAcceptKeyBundle(p,d);const g=this.getRoom(p);if(null!=g&&g.hasMembershipState(this.credentials.userId,Q.O.Join))return g;return new r.w_(this,this.clientOpts,this.buildSyncApiOptions()).createRoom(p)}knockRoom(e,t={}){const i=this.getRoom(e);if(null!=i&&i.hasMembershipState(this.credentials.userId,Q.O.Knock))return Promise.resolve({room_id:i.roomId});const s=u.RR("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),n={};if(t.viaServers){const e=Array.isArray(t.viaServers)?t.viaServers.slice(0,3):[t.viaServers];n.server_name=e,n.via=e}const r={};return t.reason&&(r.reason=t.reason),this.http.authedRequest(I.IT.Post,s,n,r)}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,o.fb.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![o.fb.QUEUED,o.fb.NOT_SENT,o.fb.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===o.fb.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===o.fb.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,o.fb.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,k.Bx.RoomName,{name:t})}setRoomTopic(e,t,i){const s=T.makeTopicContent(t,i);return this.sendStateEvent(e,k.Bx.RoomTopic,s)}getRoomTags(e){const t=u.RR("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(I.IT.Get,t)}setRoomTag(e,t,i={}){const s=u.RR("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(I.IT.Put,s,void 0,i)}deleteRoomTag(e,t){const i=u.RR("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(I.IT.Delete,i)}setRoomAccountData(e,t,i){const s=u.RR("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(I.IT.Put,s,void 0,i)}async setPowerLevel(e,t,i){var s;let n;var r;this.clientRunning&&this.isInitialSyncComplete()&&(n=null===(r=this.getRoom(e))||void 0===r||null===(r=r.currentState)||void 0===r||null===(r=r.getStateEvents(k.Bx.RoomPowerLevels,""))||void 0===r?void 0:r.getContent());if(!n)try{n=await this.getStateEvent(e,k.Bx.RoomPowerLevels,"")}catch(e){if(!(e instanceof I.up&&"M_NOT_FOUND"===e.errcode))throw e;n={}}n=u.A4(n),null!==(s=n)&&void 0!==s&&s.users||(n.users={});const o=Array.isArray(t)?t:[t];for(const e of o)null==i?delete n.users[e]:n.users[e]=i;return this.sendStateEvent(e,k.Bx.RoomPowerLevels,n,"")}async unstable_createLiveBeacon(e,t){return this.unstable_setLiveBeacon(e,t)}async unstable_setLiveBeacon(e,t){return this.sendStateEvent(e,B.E.name,t,this.getUserId())}sendEvent(e,t,i,s,n){let r,o,a,d;return null!=t&&t.startsWith(le)||null===t?(d=n,a=s,o=i,r=t):(d=s,a=i,o=t,r=null),this.addThreadRelationIfNeeded(a,r,e),this.sendCompleteEvent({roomId:e,threadId:r,eventObject:{type:o,content:a},txnId:d})}addThreadRelationIfNeeded(e,t,i){var s;if(t&&(null===(s=e["m.relates_to"])||void 0===s||!s.rel_type)){var n,r;const s=!(null===(n=e["m.relates_to"])||void 0===n||!n["m.in_reply_to"]);e["m.relates_to"]=ne(ne({},e["m.relates_to"]),{},{rel_type:$.RN.name,event_id:t,is_falling_back:!s});const d=null===(r=this.getRoom(i))||void 0===r?void 0:r.getThread(t);var o,a;if(d&&!s)e["m.relates_to"]["m.in_reply_to"]={event_id:null!==(o=null===(a=d.lastReply(e=>e.isRelation($.RN.name)&&!e.status))||void 0===a?void 0:a.getId())&&void 0!==o?o:t}}}sendCompleteEvent({roomId:e,threadId:t,eventObject:i,delayOpts:s,queryDict:n,txnId:r}){r||(r=this.makeTxnId());const a=new o.kl(Object.assign(i,{event_id:"~"+e+":"+r,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),d=this.getRoom(e),l=t?null==d?void 0:d.getThread(t):void 0;l&&a.setThread(l),s||(this.reEmitter.reEmit(a,[o.OQ.Replaced,o.OQ.VisibilityChange]),null==d||d.reEmitter.reEmit(a,[o.OQ.BeforeRedaction]));const c=a.getAssociatedId();if(null!=c&&c.startsWith("~")){const e=null==d?void 0:d.getPendingEvents().find(e=>e.getId()===c);null==e||e.once(o.OQ.LocalEventIdReplaced,()=>{a.updateAssociatedId(e.getId())})}const h=a.getType();return this.logger.debug(`sendEvent of type ${h} in ${e} with txnId ${r}${s?" (delayed event)":""}${n?" query params: "+JSON.stringify(n):""}`),a.setTxnId(r),a.setStatus(o.fb.SENDING),s?this.encryptAndSendEvent(d,a,s,n):(null==d||d.addPendingEvent(a,r),a.status===o.fb.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(d,a,n))}async encryptAndSendEvent(e,t,i,s){let n=s;if(i&&(0,C.U)(i))return this.sendEventHttpRequest(t,i,n);n||(n=i);try{let i;this.eventsBeingEncrypted.add(t.getId());try{await this.encryptEventIfNeeded(t,null!=e?e:void 0)}finally{i=!this.eventsBeingEncrypted.delete(t.getId())}if(i)return{};t.status===o.fb.ENCRYPTING&&this.updatePendingEventStatus(e,t,o.fb.SENDING);let s=null;return this.scheduler&&(s=this.scheduler.queueEvent(t),s&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,o.fb.QUEUED)),s||(s=this.sendEventHttpRequest(t,n),e&&(s=s.then(i=>(e.updatePendingEvent(t,o.fb.SENT,i.event_id),i)))),await s}catch(i){this.logger.error("Error sending event",i);try{t.error=i,this.updatePendingEventStatus(e,t,o.fb.NOT_SENT)}catch(e){this.logger.error("Exception in error handler!",e)}throw i instanceof I.up&&(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,o.fb.ENCRYPTING),await this.cryptoBackend.encryptEvent(e,t)}}async shouldEncryptEventForRoom(e,t){var i;return!e.isEncrypted()&&(e.getType()!==k.Bx.Reaction&&(!e.isRedaction()&&(!!t.hasEncryptionStateEvent()||!!await(null===(i=this.cryptoBackend)||void 0===i?void 0:i.isEncryptionEnabledInRoom(t.roomId)))))}getEncryptedIfNeededEventType(e,t){var i;return t===k.Bx.Reaction?t:null!==(i=this.getRoom(e))&&void 0!==i&&i.hasEncryptionStateEvent()?k.Bx.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,i){e?e.updatePendingEvent(t,i):t.setStatus(i)}sendEventHttpRequest(e,t,i){let s=e.getTxnId();s||(s=this.makeTxnId(),e.setTxnId(s));const n={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:s};let r;if(e.isState()){let t="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(t="/rooms/$roomId/state/$eventType/$stateKey"),r=u.RR(t,n)}else if(e.isRedaction()&&e.event.redacts){const t="/rooms/$roomId/redact/$redactsEventId/$txnId";r=u.RR(t,ne({$redactsEventId:e.event.redacts},n))}else r=u.RR("/rooms/$roomId/send/$eventType/$txnId",n);const o=t&&(0,C.U)(t)?t:void 0,a=o?i:t,d=e.getWireContent();return o?this.http.authedRequest(I.IT.Put,r,ne(ne({},me(o)),a),d):this.http.authedRequest(I.IT.Put,r,a,d).then(t=>(this.logger.debug(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t))}redactEvent(e,t,i,s,n){var r,o,a;null!==(r=i)&&void 0!==r&&r.startsWith(le)||(n=s,s=i,i=t,t=null);const d={reason:null===(o=n)||void 0===o?void 0:o.reason};if(void 0!==(null===(a=n)||void 0===a?void 0:a.with_rel_types)){if(this.canSupport.get(H.Xj.RelationBasedRedactions)===H.Tj.Unsupported)throw new Error(`Server does not support relation based redactions roomId ${e} eventId ${i} txnId: ${s} threadId ${t}`);d[this.canSupport.get(H.Xj.RelationBasedRedactions)===H.Tj.Stable?k.Z3.stable:k.Z3.unstable]=n.with_rel_types}return this.sendCompleteEvent({roomId:e,threadId:t,eventObject:{type:k.Bx.RoomRedaction,content:d,redacts:i},txnId:s})}sendMessage(e,t,i,s){"string"!=typeof t&&null!==t&&(s=i,i=t,t=null);const n=k.Bx.RoomMessage,r=i;return this.sendEvent(e,t,n,r,s)}sendTextMessage(e,t,i,s){var n;null!==(n=t)&&void 0!==n&&n.startsWith(le)||null===t||(s=i,i=t,t=null);const r=T.makeTextMessage(i);return this.sendMessage(e,t,r,s)}sendNotice(e,t,i,s){var n;null!==(n=t)&&void 0!==n&&n.startsWith(le)||null===t||(s=i,i=t,t=null);const r=T.makeNotice(i);return this.sendMessage(e,t,r,s)}sendEmoteMessage(e,t,i,s){var n;null!==(n=t)&&void 0!==n&&n.startsWith(le)||null===t||(s=i,i=t,t=null);const r=T.makeEmoteMessage(i);return this.sendMessage(e,t,r,s)}sendImageMessage(e,t,i,s,n="Image"){var r;null!==(r=t)&&void 0!==r&&r.startsWith(le)||null===t||(n=s||"Image",s=i,i=t,t=null);const o={msgtype:k.Wr.Image,url:i,info:s,body:n};return this.sendMessage(e,t,o)}sendStickerMessage(e,t,i,s,n="Sticker"){var r;null!==(r=t)&&void 0!==r&&r.startsWith(le)||null===t||(n=s||"Sticker",s=i,i=t,t=null);const o={url:i,info:s,body:n};return this.sendEvent(e,t,k.Bx.Sticker,o)}sendHtmlMessage(e,t,i,s){var n;null!==(n=t)&&void 0!==n&&n.startsWith(le)||null===t||(s=i,i=t,t=null);const r=T.makeHtmlMessage(i,s);return this.sendMessage(e,t,r)}sendHtmlNotice(e,t,i,s){var n;null!==(n=t)&&void 0!==n&&n.startsWith(le)||null===t||(s=i,i=t,t=null);const r=T.makeHtmlNotice(i,s);return this.sendMessage(e,t,r)}sendHtmlEmote(e,t,i,s){var n;null!==(n=t)&&void 0!==n&&n.startsWith(le)||null===t||(s=i,i=t,t=null);const r=T.makeHtmlEmote(i,s);return this.sendMessage(e,t,r)}async _unstable_sendDelayedEvent(e,t,i,s,n,r){if(!await this.doesServerSupportUnstableFeature(ae))throw new te.qK("Server does not support the delayed events API","sendDelayedEvent");return this.addThreadRelationIfNeeded(n,i,e),this.sendCompleteEvent({roomId:e,threadId:i,eventObject:{type:s,content:n},delayOpts:t,txnId:r})}async _unstable_sendStickyDelayedEvent(e,t,i,s,n,r,o){if(!await this.doesServerSupportUnstableFeature(ae))throw new te.qK("Server does not support the delayed events API","getDelayedEvents");if(!await this.doesServerSupportUnstableFeature(de))throw new te.xp("Server does not support the sticky events","sendStickyEvent");return this.addThreadRelationIfNeeded(r,s,e),this.sendCompleteEvent({roomId:e,threadId:s,eventObject:{type:n,content:r},queryDict:{"org.matrix.msc4354.sticky_duration_ms":t},delayOpts:i,txnId:o})}async _unstable_sendDelayedStateEvent(e,t,i,s,n="",r={}){if(!await this.doesServerSupportUnstableFeature(ae))throw new te.qK("Server does not support the delayed events API","sendDelayedStateEvent");const o={$roomId:e,$eventType:i,$stateKey:n};let a=u.RR("/rooms/$roomId/state/$eventType",o);return void 0!==n&&(a=u.RR(a+"/$stateKey",o)),this.http.authedRequest(I.IT.Put,a,me(t),s,r)}async _unstable_sendStickyEvent(e,t,i,s,n,r){if(!await this.doesServerSupportUnstableFeature(de))throw new te.xp("Server does not support the sticky events","sendStickyEvent");return this.addThreadRelationIfNeeded(n,i,e),this.sendCompleteEvent({roomId:e,threadId:i,eventObject:{type:s,content:n},queryDict:{"org.matrix.msc4354.sticky_duration_ms":t},txnId:r})}async _unstable_getDelayedEvents(e){if(!await this.doesServerSupportUnstableFeature(ae))throw new te.qK("Server does not support the delayed events API","getDelayedEvents");const t=e?{from:e}:void 0;return await this.http.authedRequest(I.IT.Get,"/delayed_events",t,void 0,{prefix:`${I.iD.Unstable}/${ae}`})}async _unstable_updateDelayedEvent(e,t,i={}){if(!await this.doesServerSupportUnstableFeature(ae))throw new te.qK("Server does not support the delayed events API","updateDelayedEvent");const s=u.RR("/delayed_events/$delayId",{$delayId:e}),n={action:t};return await this.http.authedRequest(I.IT.Post,s,void 0,n,ne(ne({},i),{},{prefix:`${I.iD.Unstable}/${ae}`}))}async sendReceipt(e,t,i,s=!1){if(this.isGuest())return Promise.resolve({});const n=u.RR("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),r=!s&&this.supportsThreads()?ne(ne({},i),{},{thread_id:ve(e)}):i,o=this.http.authedRequest(I.IT.Post,n,void 0,r||{}),a=this.getRoom(e.getRoomId());return a&&this.credentials.userId&&a.addLocalEchoReceipt(this.credentials.userId,e,t,s),o}async sendReadReceipt(e,t=N.L.Read,i=!1){if(!e)return;const s=e.getId(),n=this.getRoom(e.getRoomId());if(null!=n&&n.hasPendingEvent(s))throw new Error(`Cannot set read receipt to a pending event (${s})`);return this.sendReceipt(e,t,{},i)}async setRoomReadMarkers(e,t,i,s){const n=this.getRoom(e);if(null!=n&&n.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let r,o;if(i){if(r=i.getId(),null!=n&&n.hasPendingEvent(r))throw new Error(`Cannot set read receipt to a pending event (${r})`);null==n||n.addLocalEchoReceipt(this.credentials.userId,i,N.L.Read)}if(s){if(o=s.getId(),null!=n&&n.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);null==n||n.addLocalEchoReceipt(this.credentials.userId,s,N.L.ReadPrivate)}return await this.setRoomReadMarkersHttpRequest(e,t,r,o)}sendRtcDecline(e,t){return this.sendEvent(e,k.Bx.RTCDecline,{"m.relates_to":{event_id:t,rel_type:k.zZ.Reference}})}getUrlPreview(e,t){t=6e4*Math.floor(t/6e4);const i=new URL(e);i.hash="";const s=t+"_"+(e=i.toString());if(s in this.urlPreviewCache)return this.urlPreviewCache[s];const n=this.http.authedRequest(I.IT.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:I.zs.V3,priority:"low"});return this.urlPreviewCache[s]=n,n}sendTyping(e,t,i){if(this.isGuest())return Promise.resolve({});const s=u.RR("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),n={typing:t};return t&&(n.timeout=i||2e4),this.http.authedRequest(I.IT.Put,s,void 0,n)}getRoomUpgradeHistory(e,t=!1,i=!1){const s=this.getRoom(e);if(!s)return[];return[...this.findPredecessorRooms(s,t,i),s,...this.findSuccessorRooms(s,t,i)]}findPredecessorRooms(e,t,i){var s;const n=[],r=new Set([e.roomId]);let o=null===(s=e.findPredecessor(i))||void 0===s?void 0:s.roomId;for(;null!==o;){var a;if(o){if(r.has(o))break;r.add(o)}const s=this.getRoom(o);if(null===s)break;if(t){const t=s.currentState.getStateEvents(k.Bx.RoomTombstone,"");if(!t||t.getContent().replacement_room!==e.roomId)break}n.splice(0,0,s),o=null===(a=(e=s).findPredecessor(i))||void 0===a?void 0:a.roomId}return n}findSuccessorRooms(e,t,i){const s=[];let n=e.currentState.getStateEvents(k.Bx.RoomTombstone,"");for(;n;){const o=this.getRoom(n.getContent().replacement_room);if(!o)break;if(o.roomId===e.roomId)break;if(t){var r;const t=null===(r=o.findPredecessor(i))||void 0===r?void 0:r.roomId;if(!t||t!==e.roomId)break}s.push(o);if(new Set(s.map(e=>e.roomId)).size<s.length)return s.slice(0,s.length-1);n=(e=o).currentState.getStateEvents(k.Bx.RoomTombstone,"")}return s}async invite(e,t,i={}){var s;("object"!=typeof i&&(i={reason:i}),i.shareEncryptedHistory)&&await(null===(s=this.cryptoBackend)||void 0===s?void 0:s.shareRoomHistoryWithUser(e,t));return await this.membershipChange(e,t,Q.O.Invite,i.reason)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}async inviteByThreePid(e,t,i){var s;const n=u.RR("/rooms/$roomId/invite",{$roomId:e}),r=this.getIdentityServerUrl(!0);if(!r)return Promise.reject(new I.up({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));const o={id_server:r,medium:t,address:i};if(null!==(s=this.identityServer)&&void 0!==s&&s.getAccessToken){const e=await this.identityServer.getAccessToken();e&&(o.id_access_token=e)}return this.http.authedRequest(I.IT.Post,n,void 0,o)}leave(e){return this.membershipChange(e,void 0,Q.O.Leave)}leaveRoomChain(e,t=!0){const i=this.getRoomUpgradeHistory(e,!0);let s=i;if(!t){s=[];for(const t of i)if(s.push(t),t.roomId===e)break}const n={},r=[],o=e=>this.leave(e).then(()=>{delete n[e]}).catch(t=>{n[e]=t});for(const e of s)r.push(o(e.roomId));return Promise.all(r).then(()=>n)}ban(e,t,i){return this.membershipChange(e,t,Q.O.Ban,i)}async forget(e,t=!0){const i=u.RR("/rooms/$room_id/forget",{$room_id:e}),s=await this.http.authedRequest(I.IT.Post,i);return t&&(this.store.removeRoom(e),this.emit(ce.DeleteRoom,e)),s}unban(e,t){const i=u.RR("/rooms/$roomId/unban",{$roomId:e}),s={user_id:t};return this.http.authedRequest(I.IT.Post,i,void 0,s)}kick(e,t,i){const s=u.RR("/rooms/$roomId/kick",{$roomId:e}),n={user_id:t,reason:i};return this.http.authedRequest(I.IT.Post,s,void 0,n)}membershipChange(e,t,i,s){const n=u.RR("/rooms/$room_id/$membership",{$room_id:e,$membership:i});return this.http.authedRequest(I.IT.Post,n,void 0,{user_id:t,reason:s})}getPushActionsForEvent(e,t=!1){if(!e.getPushActions()||t){const{actions:t,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(t,i)}return e.getPushActions()}getPushDetailsForEvent(e,t=!1){if(!e.getPushDetails()||t){const{actions:t,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(t,i)}return e.getPushDetails()}setProfileInfo(e,t){const i=u.RR("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(I.IT.Put,i,void 0,t)}async setDisplayName(e){const t=await this.setProfileInfo("displayname",{displayname:e}),i=this.getUser(this.getUserId());return i&&(i.displayName=e,i.emit(E.U.DisplayName,i.events.presence,i)),t}async setAvatarUrl(e){const t=await this.setProfileInfo("avatar_url",{avatar_url:e}),i=this.getUser(this.getUserId());return i&&(i.avatarUrl=e,i.emit(E.U.AvatarUrl,i.events.presence,i)),t}mxcUrlToHttp(e,t,i,s,n,r,o){return(0,R.y)(this.baseUrl,e,t,i,s,n,r,o)}async setSyncPresence(e){var t;null===(t=this.syncApi)||void 0===t||t.setPresence(e)}async setPresence(e){const t=u.RR("/presence/$userId/status",{$userId:this.credentials.userId});if(-1===["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);await this.http.authedRequest(I.IT.Put,t,void 0,e)}getPresence(e){const t=u.RR("/presence/$userId/status",{$userId:e});return this.http.authedRequest(I.IT.Get,t)}scrollback(e,t=30){let i=0,s=this.ongoingScrollbacks[e.roomId]||{};if(s.promise)return s.promise;if(s.errorTs){const e=Date.now()-s.errorTs;i=Math.max(3e3-e,0)}if(null===e.oldState.paginationToken)return Promise.resolve(e);const n=this.store.scrollback(e,t).length;if(n===t)return Promise.resolve(e);t-=n;const r=new Promise((s,n)=>{(0,u.yy)(i).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,m.O.Backward)).then(t=>{var i,n;const r=t.chunk.map(this.getEventMapper());if(t.state){const i=t.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(i)}const[o,a,d]=e.partitionThreadedEvents(r);this.processAggregatedTimelineEvents(e,o),e.addEventsToTimeline(o,!0,!0,e.getLiveTimeline()),this.processThreadEvents(e,a,!0),d.forEach(t=>e.relations.aggregateChildEvent(t)),e.oldState.paginationToken=null!==(i=t.end)&&void 0!==i?i:null,0===t.chunk.length&&(e.oldState.paginationToken=null),this.store.storeEvents(e,r,null!==(n=t.end)&&void 0!==n?n:null,!0),delete this.ongoingScrollbacks[e.roomId],s(e)}).catch(t=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},n(t)})});return s={promise:r},this.ongoingScrollbacks[e.roomId]=s,r}getEventMapper(e){return(0,M.t)(this,e||{})}async getEventTimeline(e,t){var i,s,n,r;if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(null==e||!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 o=u.RR("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let a;null!==(i=this.clientOpts)&&void 0!==i&&i.lazyLoadMembers&&(a={filter:JSON.stringify(l.d.LAZY_LOADING_MESSAGES_FILTER)});const d=await this.http.authedRequest(I.IT.Get,o,a);if(!d.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const c=this.getEventMapper(),h=c(d.event);if(h.isRelation($.RN.name))return void this.logger.warn("Tried loading a regular timeline at the position of a thread event");const v=[...d.events_after.reverse().map(c),h,...d.events_before.map(c)];let p=e.getTimelineForEvent(v[0].getId());p?p.getState(m.q.BACKWARDS).setUnknownStateEvents(d.state.map(c)):(p=e.addTimeline(),p.initialiseState(d.state.map(c)),p.getState(m.q.FORWARDS).paginationToken=d.end);const[g,f,y]=e.room.partitionThreadedEvents(v);return e.addEventsToTimeline(g,!0,!1,p,d.start),this.processThreadEvents(e.room,f,!0),this.processAggregatedTimelineEvents(e.room,g),y.forEach(t=>e.relations.aggregateChildEvent(t)),null!==(s=null!==(n=e.getTimelineForEvent(t))&&void 0!==n?n:null===(r=e.room.findThreadForEvent(h))||void 0===r?void 0:r.liveTimeline)&&void 0!==s?s:p}async getThreadTimeline(e,t){var i;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 s=u.RR("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),n={limit:"0"};null!==(i=this.clientOpts)&&void 0!==i&&i.lazyLoadMembers&&(n.filter=JSON.stringify(l.d.LAZY_LOADING_MESSAGES_FILTER));const r=await this.http.authedRequest(I.IT.Get,s,n),o=this.getEventMapper(),a=o(r.event);if(!e.canContain(a))return;const d=this.canSupport.get(H.Xj.RelationsRecursion)!==H.Tj.Unsupported;if($.jV.hasServerSideSupport){if($.jV.hasServerSideFwdPaginationSupport){var c,h,v;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const i=e.thread,s=await this.fetchRelations(e.room.roomId,i.id,null,null,{dir:m.O.Backward,from:r.start,recurse:d||void 0}),n=await this.fetchRelations(e.room.roomId,i.id,null,null,{dir:m.O.Forward,from:r.end,recurse:d||void 0}),l=[...n.chunk.reverse().filter((0,Y.q)(i.id)).map(o),a,...s.chunk.filter((0,Y.q)(i.id)).map(o)];for(const t of l){var p;await(null===(p=e.thread)||void 0===p?void 0:p.processEvent(t))}let u=e.getTimelineForEvent(a.getId());if(u?u.getState(m.q.BACKWARDS).setUnknownStateEvents(r.state.map(o)):(u=e.addTimeline(),u.initialiseState(r.state.map(o))),e.addEventsToTimeline(l,!0,!1,u,n.next_batch),!s.next_batch){const t=await this.fetchRoomEvent(e.room.roomId,i.id);e.addEventsToTimeline([o(t)],!0,!1,u,null)}return u.setPaginationToken(null!==(c=s.next_batch)&&void 0!==c?c:null,m.O.Backward),u.setPaginationToken(null!==(h=n.next_batch)&&void 0!==h?h:null,m.O.Forward),this.processAggregatedTimelineEvents(e.room,l),null!==(v=e.getTimelineForEvent(t))&&void 0!==v?v:u}{var g;const t=e.thread,i=await this.fetchRelations(e.room.roomId,t.id,$.RN.name,null,{dir:m.O.Backward,from:r.start,recurse:d||void 0}),s=[];let n=r.end;for(;n;){var f;const i=await this.fetchRelations(e.room.roomId,t.id,$.RN.name,null,{dir:m.O.Forward,from:n,recurse:d||void 0});n=null!==(f=i.next_batch)&&void 0!==f?f:null,s.push(...i.chunk)}const l=[...s.reverse().map(o),a,...i.chunk.map(o)];for(const t of l){var y;await(null===(y=e.thread)||void 0===y?void 0:y.processEvent(t))}const c=e.getLiveTimeline();if(c.getState(m.q.BACKWARDS).setUnknownStateEvents(r.state.map(o)),e.addEventsToTimeline(l,!0,!1,c,null),!i.next_batch){const i=await this.fetchRoomEvent(e.room.roomId,t.id);e.addEventsToTimeline([o(i)],!0,!1,c,null)}return c.setPaginationToken(null!==(g=i.next_batch)&&void 0!==g?g:null,m.O.Backward),c.setPaginationToken(null,m.O.Forward),this.processAggregatedTimelineEvents(e.room,l),c}}}async getLatestTimeline(e){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(null!==e.threadListType){var i;t=null===(i=(await this.createThreadListMessagesRequest(e.room.roomId,null,1,m.O.Backward,e.threadListType,e.getFilter())).chunk)||void 0===i?void 0:i[0]}else if(e.thread&&$.jV.hasServerSideSupport){var s;const i=this.canSupport.get(H.Xj.RelationsRecursion)!==H.Tj.Unsupported;t=null===(s=(await this.fetchRelations(e.room.roomId,e.thread.id,$.RN.name,null,{dir:m.O.Backward,limit:1,recurse:i||void 0})).chunk)||void 0===s?void 0:s[0]}else{var n,r;const i=u.RR("/rooms/$roomId/messages",{$roomId:e.room.roomId}),s={dir:"b"};null!==(n=this.clientOpts)&&void 0!==n&&n.lazyLoadMembers&&(s.filter=JSON.stringify(l.d.LAZY_LOADING_MESSAGES_FILTER));t=null===(r=(await this.http.authedRequest(I.IT.Get,i,s)).chunk)||void 0===r?void 0:r[0]}if(!t)throw new Error("No message returned when trying to construct getLatestTimeline");return this.getEventTimeline(e,t.event_id)}createMessagesRequest(e,t,i=30,s,n){var r;const o=u.RR("/rooms/$roomId/messages",{$roomId:e}),a={limit:i.toString(),dir:s};t&&(a.from=t);let d=null;var c;(null!==(r=this.clientOpts)&&void 0!==r&&r.lazyLoadMembers&&(d=Object.assign({},l.d.LAZY_LOADING_MESSAGES_FILTER)),n)&&(d=d||{},Object.assign(d,null===(c=n.getRoomTimelineFilterComponent())||void 0===c?void 0:c.toJSON()));return d&&(a.filter=JSON.stringify(d)),this.http.authedRequest(I.IT.Get,o,a)}createThreadListMessagesRequest(e,t,i=30,s=m.O.Backward,n=$.x3.All,r){var o;const a=u.RR("/rooms/$roomId/threads",{$roomId:e}),d={limit:i.toString(),dir:s,include:(0,$.UR)(n)};t&&(d.from=t);let c={};var h;(null!==(o=this.clientOpts)&&void 0!==o&&o.lazyLoadMembers&&(c=ne({},l.d.LAZY_LOADING_MESSAGES_FILTER)),r)&&(c=ne(ne({},c),null===(h=r.getRoomTimelineFilterComponent())||void 0===h?void 0:h.toJSON()));Object.keys(c).length&&(d.filter=JSON.stringify(c));const v={prefix:$.jV.hasServerSideListSupport===$.c1.Stable?I.iD.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(I.IT.Get,a,d,void 0,v).then(e=>{var t;return ne(ne({},e),{},{chunk:null===(t=e.chunk)||void 0===t?void 0:t.reverse(),start:e.prev_batch,end:e.next_batch})})}paginateEventTimeline(e,t){const i=e.getTimelineSet()===this.notifTimelineSet,s=this.getRoom(e.getRoomId()),n=e.getTimelineSet().threadListType,r=e.getTimelineSet().thread,o=(t=t||{}).backwards||!1;if(i&&!o)throw new Error("paginateNotifTimeline can only paginate backwards");const a=o?m.q.BACKWARDS:m.q.FORWARDS,d=e.getPaginationToken(a),l=e.paginationRequests[a];if(l)return l;let c,h,v;var p;if(i)c="/notifications",h={limit:(null!==(p=t.limit)&&void 0!==p?p:30).toString(),only:"highlight"},d&&"end"!==d&&(h.from=d),v=this.http.authedRequest(I.IT.Get,"/notifications",h).then(async t=>{const i=t.next_token,s=[];t.notifications=t.notifications.filter(u.O5);for(let e=0;e<t.notifications.length;e++){const i=t.notifications[e],n=this.getEventMapper()(i.event);this.getPushDetailsForEvent(n,!0),n.event.room_id=i.room_id,s[e]=n}const n=e.getTimelineSet();return n.addEventsToTimeline(s,o,!1,e,i),this.processAggregatedTimelineEvents(n.room,s),o&&!t.next_token&&e.setPaginationToken(null,a),Boolean(t.next_token)}).finally(()=>{e.paginationRequests[a]=null}),e.paginationRequests[a]=v;else if(null!==n){if(!s)throw new Error("Unknown room "+e.getRoomId());if(!$.jV.hasServerSideFwdPaginationSupport&&a===m.O.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");v=this.createThreadListMessagesRequest(e.getRoomId(),d,t.limit,a,n,e.getFilter()).then(t=>{if(t.state){const i=e.getState(a),s=t.state.filter(u.O5).map(this.getEventMapper());i.setUnknownStateEvents(s)}const i=t.end,n=t.chunk.filter(u.O5).map(this.getEventMapper());return e.getTimelineSet().addEventsToTimeline(n,o,!1,e,i),this.processAggregatedTimelineEvents(s,n),this.processThreadRoots(s,n,o),o&&t.end==t.start&&e.setPaginationToken(null,a),t.end!==t.start}).finally(()=>{e.paginationRequests[a]=null}),e.paginationRequests[a]=v}else if(r){var g,f;const i=this.getRoom(null!==(g=e.getRoomId())&&void 0!==g?g:void 0);if(!i)throw new Error("Unknown room "+e.getRoomId());const s=this.canSupport.get(H.Xj.RelationsRecursion)!==H.Tj.Unsupported;v=this.fetchRelations(null!==(f=e.getRoomId())&&void 0!==f?f:"",r.id,null,null,{dir:a,limit:t.limit,from:null!=d?d:void 0,recurse:s||void 0}).then(async t=>{const s=this.getEventMapper(),n=t.chunk.filter(u.O5).filter((0,Y.q)(r.id)).map(s);for(const e of n.slice().reverse()){await(null==r?void 0:r.processEvent(e));const t=e.getSender();o&&null!==(null==r?void 0:r.getEventReadUpTo(t))||i.addLocalEchoReceipt(t,e,N.L.Read)}const d=t.next_batch,l=e.getTimelineSet();if(l.addEventsToTimeline(n,o,!1,e,null!=d?d:null),!d&&o){var c,h;const t=null!==(c=r.rootEvent)&&void 0!==c?c:s(await this.fetchRoomEvent(null!==(h=e.getRoomId())&&void 0!==h?h:"",r.id));l.addEventsToTimeline([t],!0,!1,e,null)}return this.processAggregatedTimelineEvents(l.room,n),o&&!d&&e.setPaginationToken(null,a),Boolean(d)}).finally(()=>{e.paginationRequests[a]=null}),e.paginationRequests[a]=v}else{if(!s)throw new Error("Unknown room "+e.getRoomId());v=this.createMessagesRequest(e.getRoomId(),d,t.limit,a,e.getFilter()).then(t=>{if(t.state){const i=e.getState(a),s=t.state.filter(u.O5).map(this.getEventMapper());i.setUnknownStateEvents(s)}const i=t.end,n=t.chunk.filter(u.O5).map(this.getEventMapper()),r=e.getTimelineSet(),[d,,l]=s.partitionThreadedEvents(n);r.addEventsToTimeline(d,o,!1,e,i),this.processAggregatedTimelineEvents(s,d),this.processThreadRoots(s,d.filter(e=>e.getServerAggregatedRelation($.RN.name)),!1),l.forEach(e=>s.relations.aggregateChildEvent(e));const c=void 0===t.end||t.end===t.start;return o&&c&&e.setPaginationToken(null,a),!c}).finally(()=>{e.paginationRequests[a]=null}),e.paginationRequests[a]=v}return v}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e,t=20){var i;return null===(i=this.peekSync)||void 0===i||i.stopPeeking(),this.peekSync=new r.w_(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,t)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const i=this.sendStateEvent(e,k.Bx.RoomGuestAccess,{guest_access:t.allowJoin?A.rF.CanJoin:A.rF.Forbidden},"");let s=Promise.resolve();return t.allowRead&&(s=this.sendStateEvent(e,k.Bx.RoomHistoryVisibility,{history_visibility:A.Jv.WorldReadable},"")),Promise.all([s,i]).then()}requestRegisterEmailToken(e,t,i,s){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:s})}requestRegisterMsisdnToken(e,t,i,s,n){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:s,next_link:n})}requestAdd3pidEmailToken(e,t,i,s){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:s})}requestAdd3pidMsisdnToken(e,t,i,s,n){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:s,next_link:n})}requestPasswordEmailToken(e,t,i,s){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:s})}requestPasswordMsisdnToken(e,t,i,s,n){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:s,next_link:n})}async requestTokenFromEndpoint(e,t){const i=Object.assign({},t);return this.http.request(I.IT.Post,e,void 0,i)}getRoomPushRule(e,t){var i;if(this.pushRules)return null===(i=this.pushRules[e])||void 0===i||null===(i=i.room)||void 0===i?void 0:i.find(e=>e.rule_id===t);throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,i){let s,n=!1;const r=this.getRoomPushRule(e,t);if(null!=r&&r.actions.includes(P.YU.DontNotify)&&(n=!0),i)if(r){if(!n){const i=Promise.withResolvers();this.deletePushRule(e,P.Ji.RoomSpecific,r.rule_id).then(()=>{this.addPushRule(e,P.Ji.RoomSpecific,t,{actions:[P.YU.DontNotify]}).then(()=>{i.resolve()}).catch(e=>{i.reject(e)})}).catch(e=>{i.reject(e)}),s=i.promise}}else s=this.addPushRule(e,P.Ji.RoomSpecific,t,{actions:[P.YU.DontNotify]});else n&&(s=this.deletePushRule(e,P.Ji.RoomSpecific,r.rule_id));if(s)return new Promise((e,t)=>{s.then(()=>{this.getPushRules().then(t=>{this.pushRules=t,e()}).catch(e=>{t(e)})}).catch(e=>{this.getPushRules().then(i=>{this.pushRules=i,t(e)}).catch(i=>{t(e)})})})}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:O.g.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},i={_query:t,results:[],highlights:[]};return this.search({body:t}).then(e=>this.processRoomEventsSearch(i,e))}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},i=this.search(t,e.abortSignal).then(t=>this.processRoomEventsSearch(e,t)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=i,i}processRoomEventsSearch(e,t){var i,s;const n=t.search_categories.room_events;e.count=n.count,e.next_batch=n.next_batch;const r=new Set(n.highlights);e.highlights.forEach(e=>{r.add(e)}),e.highlights=Array.from(r);const o=this.getEventMapper(),a=null!==(i=null===(s=n.results)||void 0===s?void 0:s.length)&&void 0!==i?i:0;for(let t=0;t<a;t++){const i=b.q.fromJson(n.results[t],o),s=this.getRoom(i.context.getEvent().getRoomId());if(s)for(const e of i.context.getTimeline())e.setMetadata(s.currentState,!1);e.results.push(i)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const e=new r.w_(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=u.RR("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(I.IT.Post,t,void 0,e).then(t=>{const i=l.d.fromJson(this.credentials.userId,t.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,t,i){if(i){const i=this.store.getFilter(e,t);if(i)return Promise.resolve(i)}const s=u.RR("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(I.IT.Get,s).then(i=>{const s=l.d.fromJson(e,t,i);return this.store.storeFilter(s),s})}async getOrCreateFilter(e,t){const i=this.store.getFilterIdByName(e);let s;if(i){try{const e=await this.getFilter(this.credentials.userId,i,!0);if(e){const n=e.getDefinition(),r=t.getDefinition();u.ky(n,r)&&(s=i)}}catch(e){if("M_UNKNOWN"!==e.errcode&&"M_NOT_FOUND"!==e.errcode)throw e}s||this.store.setFilterIdByName(e,void 0)}if(s)return s;const n=await this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,n.filterId),n.filterId}getOpenIdToken(){const e=u.RR("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(I.IT.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(I.IT.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return void 0!==this.checkTurnServersIntervalID}async checkTurnServers(){if(!this.supportsVoip())return;let e=!1;const t=this.turnServersExpiry-Date.now();if(t>re)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 t=await this.turnServer();if(t.uris){this.logger.debug("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");const i={urls:t.uris,username:t.username,credential:t.password};this.turnServers=[i],this.turnServersExpiry=Date.now()+1e3*t.ttl,e=!0,this.emit(ce.TurnServers,this.turnServers)}}catch(e){this.logger.error("Failed to get TURN URIs",e),403===e.httpStatus?(this.logger.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&globalThis.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.emit(ce.TurnServersError,e,!0)):this.emit(ce.TurnServersError,e,!1)}}return e}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=u.RR("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(I.IT.Get,e,void 0,void 0,{prefix:""}).then(e=>e.admin)}whoisSynapseUser(e){const t=u.RR("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(I.IT.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=u.RR("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(I.IT.Post,t,void 0,void 0,{prefix:""})}async fetchClientWellKnown(){var e;this.clientWellKnownPromise=p.MN.getRawClientConfig(null!==(e=this.getDomain())&&void 0!==e?e:void 0),this.clientWellKnown=await this.clientWellKnownPromise,this.emit(ce.ClientWellKnown,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(([t,i])=>e.includes(typeof i)).reduce((e,[t,i])=>(e[t]=i,e),{});return this.store.storeClientOptions(t)}async _unstable_getSharedRooms(e){const t=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"),i=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms"),s=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.query_mutual_rooms");if(!t&&!i&&!s)throw Error("Server does not support the Mutual Rooms API");let n,r;s?(n="/uk.half-shot.msc2666/user/mutual_rooms",r={user_id:e}):(n=u.RR(`/uk.half-shot.msc2666/user/${i?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e}),r={});const o=[];let a=null;do{const e={};null!=a&&s&&(e.batch_token=a);const t=await this.http.authedRequest(I.IT.Get,n,ne(ne({},r),e),void 0,{prefix:I.iD.Unstable});o.push(...t.joined),a=void 0!==t.next_batch_token?t.next_batch_token:null}while(null!=a);return o}async getVersions(){if(this.serverVersionsPromise)return this.serverVersionsPromise;this.serverVersionsPromise=this.http.authedRequest(I.IT.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(e=>{throw this.serverVersionsPromise=void 0,e});const e=await this.serverVersionsPromise;return this.canSupport=await(0,H.yk)(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 i=t.unstable_features;return i&&!!i[e]}async doesServerForceEncryptionForPreset(e){const t=await this.getVersions();if(!t)return!1;const i=t.unstable_features,s=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return i&&!!i[`io.element.e2ee_forced.${s}`]}async doesServerSupportThread(){if(await this.isVersionSupported("v1.4"))return{threads:$.c1.Stable,list:$.c1.Stable,fwdPagination:$.c1.Stable};try{const[e,t,i,s,n,r]=await Promise.all([this.doesServerSupportUnstableFeature("org.matrix.msc3440"),this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3856"),this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3715"),this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:(0,$.FD)(t,e),list:(0,$.FD)(s,i),fwdPagination:(0,$.FD)(r,n)}}catch{return{threads:$.c1.None,list:$.c1.None,fwdPagination:$.c1.None}}}hasLazyLoadMembersEnabled(){var e;return!(null===(e=this.clientOpts)||void 0===e||!e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}async relations(e,t,i,s,n={dir:m.O.Backward}){var r,o;const a=s?this.getEncryptedIfNeededEventType(e,s):null,[d,l]=await Promise.all([this.fetchRoomEvent(e,t),this.fetchRelations(e,t,i,a,n)]),c=this.getEventMapper(),h=d?c(d):void 0;let u=l.chunk.map(c);if(a===k.Bx.RoomMessageEncrypted){const e=h?u.concat(h):u;await Promise.all(e.map(e=>this.decryptEventIfNeeded(e))),null!==s&&(u=u.filter(e=>e.getType()===s))}return h&&i===k.zZ.Replace&&(u=u.filter(e=>e.getSender()===h.getSender())),{originalEvent:null!=h?h:null,events:u,nextBatch:null!==(r=l.next_batch)&&void 0!==r?r:null,prevBatch:null!==(o=l.prev_batch)&&void 0!==o?o:null}}generateClientSecret(){return(0,x.US)(32)}decryptEventIfNeeded(e,t){return e.isState()&&!this.enableEncryptedStateEvents?Promise.resolve():(e.shouldAttemptDecryption()&&this.getCrypto()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve())}termsUrlForService(e,t){switch(e){case S.S.IS:return this.http.getUrl("/terms",void 0,I.Pw.V2,t);case S.S.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,i;return e&&(null!==(t=this.idBaseUrl)&&void 0!==t&&t.startsWith("http://")||null!==(i=this.idBaseUrl)&&void 0!==i&&i.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=u.hc(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}getRefreshToken(){var e;return null!==(e=this.http.opts.refreshToken)&&void 0!==e?e:null}setAccessToken(e){this.http.opts.accessToken=e,this.serverVersionsPromise=void 0}isLoggedIn(){return void 0!==this.http.opts.accessToken}makeTxnId(){return"m"+(new Date).getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(I.IT.Get,"/register/available",{username:e}).then(e=>e.available).catch(e=>"M_USER_IN_USE"!==e.errcode&&Promise.reject(e))}register(e,t,i,s,n,r,o){i&&(s.session=i);const a={auth:s,refresh_token:!0};return null!=e&&(a.username=e),null!=t&&(a.password=t),null!=r&&(a.guest_access_token=r),null!=o&&(a.inhibit_login=o),this.registerRequest(a)}registerGuest({body:e}={}){return this.registerRequest(e||{},"guest")}registerRequest(e,t){const i={};return t&&(i.kind=t),this.http.request(I.IT.Post,"/register",i,e)}refreshToken(e){const t=t=>this.http.authedRequest(I.IT.Post,"/refresh",void 0,{refresh_token:e},{prefix:t,inhibitLogoutEmit:!0});return t(I.iD.V3).catch(e=>{if("M_UNRECOGNIZED"===e.errcode)return t(I.iD.V1);throw e})}loginFlows(){return this.http.request(I.IT.Get,"/login")}login(e,t){return this.loginRequest(ne(ne({},t),{},{type:e})).then(e=>(e.access_token&&e.user_id&&(this.http.opts.accessToken=e.access_token,this.credentials={userId:e.user_id}),e))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",i,s){let n="/login/"+t+"/redirect";i&&(n+="/"+i);const r={redirectUrl:e,[he.unstable]:s};return this.http.getUrl(n,r).href}loginWithToken(e){return this.login("m.login.token",{token:e})}async loginRequest(e){return await this.http.authedRequest(I.IT.Post,"/login",void 0,e)}async logout(e=!1){return e&&(this.stopClient(),this.http.abort()),this.http.authedRequest(I.IT.Post,"/logout")}deactivateAccount(e,t){const i={};return e&&(i.auth=e),void 0!==t&&(i.erase=t),this.http.authedRequest(I.IT.Post,"/account/deactivate",void 0,i)}async requestLoginToken(e){const t={auth:e};return this.http.authedRequest(I.IT.Post,"/login/get_token",void 0,t,{prefix:I.iD.V1})}getFallbackAuthUrl(e,t){const i=u.RR("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(i,{session:t}).href}async createRoom(e){var t;const i=(e.invite_3pid||[]).filter(e=>!e.id_access_token);if(i.length>0&&null!==(t=this.identityServer)&&void 0!==t&&t.getAccessToken){const e=await this.identityServer.getAccessToken();if(e)for(const t of i)t.id_access_token=e}return this.http.authedRequest(I.IT.Post,"/createRoom",void 0,e)}fetchRelations(e,t,i,s,n={dir:m.O.Backward}){let r=n;$.jV.hasServerSideFwdPaginationSupport===$.c1.Experimental&&(r=(0,u.Ab)("dir","org.matrix.msc3715.dir",r)),this.canSupport.get(H.Xj.RelationsRecursion)===H.Tj.Unstable&&(r=(0,u.Ab)("recurse","org.matrix.msc3981.recurse",r));const o=u.hm(r);let a="/rooms/$roomId/relations/$eventId";null!==i?(a+="/$relationType",null!==s&&(a+="/$eventType")):null!==s&&(this.logger.warn(`eventType: ${s} ignored when fetching\n relations as relationType is null`),s=null);const d=u.RR(a+"?"+o,{$roomId:e,$eventId:t,$relationType:i,$eventType:s});return this.http.authedRequest(I.IT.Get,d,void 0,void 0,{prefix:I.iD.V1})}roomState(e){const t=u.RR("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(I.IT.Get,t)}fetchRoomEvent(e,t){const i=u.RR("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(I.IT.Get,i)}members(e,t,i,s){const n={};t&&(n.membership=t),i&&(n.not_membership=i),s&&(n.at=s);const r=u.hm(n),o=u.RR("/rooms/$roomId/members?"+r,{$roomId:e});return this.http.authedRequest(I.IT.Get,o)}upgradeRoom(e,t){const i=u.RR("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(I.IT.Post,i,void 0,{new_version:t})}getStateEvent(e,t,i){const s={$roomId:e,$eventType:t,$stateKey:i};let n=u.RR("/rooms/$roomId/state/$eventType",s);return void 0!==i&&(n=u.RR(n+"/$stateKey",s)),this.http.authedRequest(I.IT.Get,n)}async sendStateEvent(e,t,i,s="",n={}){const r=this.getRoom(e),a=new o.kl({room_id:e,type:t,state_key:s,content:i});await this.encryptStateEventIfNeeded(a,null!=r?r:void 0);const d={$roomId:e,$eventType:a.getWireType(),$stateKey:a.getWireStateKey()};let l=u.RR("/rooms/$roomId/state/$eventType",d);return void 0!==s&&(l=u.RR(l+"/$stateKey",d)),this.http.authedRequest(I.IT.Put,l,void 0,a.getWireContent(),n)}async encryptStateEventIfNeeded(e,t){if(this.enableEncryptedStateEvents&&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.");await this.shouldEncryptEventForRoom(e,t)&&await this.cryptoBackend.isStateEncryptionEnabledInRoom(t.roomId)&&(["m.room.create","m.room.member","m.room.join_rules","m.room.power_levels","m.room.third_party_invite","m.room.history_visibility","m.room.guest_access","m.room.encryption"].includes(e.getType())||await this.cryptoBackend.encryptEvent(e,t))}}roomInitialSync(e,t){var i;const s=u.RR("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(I.IT.Get,s,{limit:null!==(i=null==t?void 0:t.toString())&&void 0!==i?i:"30"})}async setRoomReadMarkersHttpRequest(e,t,i,s){const n=u.RR("/rooms/$roomId/read_markers",{$roomId:e}),r={[N.L.FullyRead]:t,[N.L.Read]:i};return(await this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")||await this.isVersionSupported("v1.4"))&&(r[N.L.ReadPrivate]=s),this.http.authedRequest(I.IT.Post,n,void 0,r)}getJoinedRooms(){const e=u.RR("/joined_rooms",{});return this.http.authedRequest(I.IT.Get,e)}getJoinedRoomMembers(e){const t=u.RR("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(I.IT.Get,t)}publicRooms(e={}){let{server:t,limit:i,since:n}=e,r=(0,s.A)(e,ie);if(0===Object.keys(r).length){const e={server:t,limit:i,since:n};return this.http.authedRequest(I.IT.Get,"/publicRooms",e)}{const e={server:t},s=ne({limit:i,since:n},r);return this.http.authedRequest(I.IT.Post,"/publicRooms",e,s)}}createAlias(e,t){const i=u.RR("/directory/room/$alias",{$alias:e}),s={room_id:t};return this.http.authedRequest(I.IT.Put,i,void 0,s)}deleteAlias(e){const t=u.RR("/directory/room/$alias",{$alias:e});return this.http.authedRequest(I.IT.Delete,t)}getLocalAliases(e){const t=u.RR("/rooms/$roomId/aliases",{$roomId:e}),i=I.iD.V3;return this.http.authedRequest(I.IT.Get,t,void 0,void 0,{prefix:i})}getRoomIdForAlias(e){const t=u.RR("/directory/room/$alias",{$alias:e});return this.http.authedRequest(I.IT.Get,t)}getRoomDirectoryVisibility(e){const t=u.RR("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(I.IT.Get,t)}setRoomDirectoryVisibility(e,t){const i=u.RR("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(I.IT.Put,i,void 0,{visibility:t})}searchUserDirectory({term:e,limit:t}){const i={search_term:e};return void 0!==t&&(i.limit=t),this.http.authedRequest(I.IT.Post,"/user_directory/search",void 0,i)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){const i=t?u.RR("/profile/$userId/$info",{$userId:e,$info:t}):u.RR("/profile/$userId",{$userId:e});return this.http.authedRequest(I.IT.Get,i)}async doesServerSupportExtendedProfiles(){return await this.isVersionSupported("v1.16")||await this.doesServerSupportUnstableFeature("uk.tcpip.msc4133")||await this.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable")}async getExtendedProfileRequestPrefix(){return await this.isVersionSupported("v1.16")||await this.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable")?I.iD.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(I.IT.Get,u.RR("/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(I.IT.Get,u.RR("/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 i=this.getUserId();await this.http.authedRequest(I.IT.Put,u.RR("/profile/$userId/$key",{$userId:i,$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(I.IT.Delete,u.RR("/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(I.IT.Patch,u.RR("/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(I.IT.Put,u.RR("/profile/$userId",{$userId:t}),{},e,{prefix:await this.getExtendedProfileRequestPrefix()})}getThreePids(){return this.http.authedRequest(I.IT.Get,"/account/3pid")}async addThreePidOnly(e){return this.http.authedRequest(I.IT.Post,"/account/3pid/add",void 0,e)}async bindThreePid(e){return this.http.authedRequest(I.IT.Post,"/account/3pid/bind",void 0,e)}async unbindThreePid(e,t){const i={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)};return this.http.authedRequest(I.IT.Post,"/account/3pid/unbind",void 0,i)}deleteThreePid(e,t){return this.http.authedRequest(I.IT.Post,"/account/3pid/delete",void 0,{medium:e,address:t})}setPassword(e,t,i){const s={auth:e,new_password:t,logout_devices:i};return this.http.authedRequest(I.IT.Post,"/account/password",void 0,s)}getDevices(){return this.http.authedRequest(I.IT.Get,"/devices")}getDevice(e){const t=u.RR("/devices/$device_id",{$device_id:e});return this.http.authedRequest(I.IT.Get,t)}setDeviceDetails(e,t){const i=u.RR("/devices/$device_id",{$device_id:e});return this.http.authedRequest(I.IT.Put,i,void 0,t)}deleteDevice(e,t){const i=u.RR("/devices/$device_id",{$device_id:e}),s={};return t&&(s.auth=t),this.http.authedRequest(I.IT.Delete,i,void 0,s)}deleteMultipleDevices(e,t){const i={devices:e};t&&(i.auth=t);return this.http.authedRequest(I.IT.Post,"/delete_devices",void 0,i)}async getPushers(){const e=await this.http.authedRequest(I.IT.Get,"/pushers");return await this.doesServerSupportUnstableFeature("org.matrix.msc3881")||(e.pushers=e.pushers.map(e=>(e.hasOwnProperty(k.cr.name)||(e[k.cr.name]=!0),e))),e}setPusher(e){return this.http.authedRequest(I.IT.Post,"/pushers/set",void 0,e)}removePusher(e,t){const i={pushkey:e,app_id:t,kind:null};return this.http.authedRequest(I.IT.Post,"/pushers/set",void 0,i)}setLocalNotificationSettings(e,t){const i=`${k.Xs.name}.${e}`;return this.setAccountData(i,t)}getPushRules(){return this.http.authedRequest(I.IT.Get,"/pushrules/").then(e=>(this.setPushRules(e),this.pushRules))}setPushRules(e){this.pushRules=v.j.rewriteDefaultRules(this.logger,e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,i,s){const n=u.RR("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:i});return this.http.authedRequest(I.IT.Put,n,void 0,s)}deletePushRule(e,t,i){const s=u.RR("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:i});return this.http.authedRequest(I.IT.Delete,s)}setPushRuleEnabled(e,t,i,s){const n=u.RR("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:i});return this.http.authedRequest(I.IT.Put,n,void 0,{enabled:s})}setPushRuleActions(e,t,i,s){const n=u.RR("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:i});return this.http.authedRequest(I.IT.Put,n,void 0,{actions:s})}search({body:e,next_batch:t},i){const s={};return t&&(s.next_batch=t),this.http.authedRequest(I.IT.Post,"/search",s,e,{abortSignal:i})}uploadKeysRequest(e,t){return this.http.authedRequest(I.IT.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(I.IT.Post,"/keys/signatures/upload",void 0,e)}downloadKeysForUsers(e,{token:t}={}){const i={device_keys:{}};return void 0!==t&&(i.token=t),e.forEach(e=>{i.device_keys[e]=[]}),this.http.authedRequest(I.IT.Post,"/keys/query",void 0,i)}claimOneTimeKeys(e,t="signed_curve25519",i){const s={};void 0===t&&(t="signed_curve25519");for(const[i,n]of e){const e=s[i]||{};(0,u.C6)(s,i,e),(0,u.C6)(e,n,t)}const n={one_time_keys:s};i&&(n.timeout=i);return this.http.authedRequest(I.IT.Post,"/keys/claim",void 0,n)}getKeyChanges(e,t){const i={from:e,to:t};return this.http.authedRequest(I.IT.Get,"/keys/changes",i)}uploadDeviceSigningKeys(e,t){const i=Object.assign({},t);return e&&Object.assign(i,{auth:e}),this.http.authedRequest(I.IT.Post,"/keys/device_signing/upload",void 0,i,{prefix:I.iD.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const t=this.http.getUrl("/account/register",void 0,I.Pw.V2,this.idBaseUrl);return this.http.requestOtherUrl(I.IT.Post,t,e)}requestEmailToken(e,t,i,s,n){const r={client_secret:t,email:e,send_attempt:null==i?void 0:i.toString()};return s&&(r.next_link=s),this.http.idServerRequest(I.IT.Post,"/validate/email/requestToken",r,I.Pw.V2,n)}requestMsisdnToken(e,t,i,s,n,r){const o={client_secret:i,country:e,phone_number:t,send_attempt:null==s?void 0:s.toString()};return n&&(o.next_link=n),this.http.idServerRequest(I.IT.Post,"/validate/msisdn/requestToken",o,I.Pw.V2,r)}submitMsisdnToken(e,t,i,s){const n={sid:e,client_secret:t,token:i};return this.http.idServerRequest(I.IT.Post,"/validate/msisdn/submitToken",n,I.Pw.V2,null!=s?s:void 0)}submitMsisdnTokenOtherUrl(e,t,i,s){const n={sid:t,client_secret:i,token:s};return this.http.requestOtherUrl(I.IT.Post,e,n)}getIdentityHashDetails(e){return this.http.idServerRequest(I.IT.Get,"/hash_details",void 0,I.Pw.V2,e)}async identityHashedLookup(e,t){const i={},s=await this.getIdentityHashDetails(t);if(!s||!s.lookup_pepper||!s.algorithms)throw new Error("Unsupported identity server: bad response");i.pepper=s.lookup_pepper;const n={};if(s.algorithms.includes("sha256"))i.addresses=await Promise.all(e.map(async e=>{const t=e[0].toLowerCase(),s=e[1].toLowerCase(),r=await(0,Z.s)(`${t} ${s} ${i.pepper}`),o=(0,g.A4)(r);return n[o]=e[0],o})),i.algorithm="sha256";else{if(!s.algorithms.includes("none"))throw new Error("Unsupported identity server: unknown hash algorithm");i.addresses=e.map(e=>{const t=`${e[0].toLowerCase()} ${e[1].toLowerCase()}`;return n[t]=e[0],t}),i.algorithm="none"}const r=await this.http.idServerRequest(I.IT.Post,"/lookup",i,I.Pw.V2,t);if(null==r||!r.mappings)return[];const o=[];for(const e of Object.keys(r.mappings)){const t=r.mappings[e],i=n[e];if(!i)throw new Error("Identity server returned more results than expected");o.push({address:i,mxid:t})}return o}async lookupThreePid(e,t,i){const s=(await this.identityHashedLookup([[t,e]],i)).find(e=>e.address===t);if(!s)return{};return{address:t,medium:e,mxid:s.mxid}}async bulkLookupThreePids(e,t){const i=await this.identityHashedLookup(e.map(e=>[e[1],e[0]]),t),s=[];for(const t of i){const i=e.find(e=>e[1]===t.address);if(!i)throw new Error("Identity sever returned unexpected results");s.push([i[0],t.address,t.mxid])}return{threepids:s}}getIdentityAccount(e){return this.http.idServerRequest(I.IT.Get,"/account",void 0,I.Pw.V2,e)}sendToDevice(e,t,i){const s=u.RR("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:i||this.makeTxnId()}),n={messages:u.HF(t)},r=new Map;for(const[e,i]of t)r.set(e,Array.from(i.keys()));return this.logger.debug(`PUT ${s}`,r),this.http.authedRequest(I.IT.Put,s,void 0,n)}async encryptAndSendToDevice(e,t,i){if(!this.cryptoBackend)throw new Error("Cannot encrypt to device event, your client does not support encryption.");const s=await this.cryptoBackend.encryptToDeviceMessages(e,t,i);await this.queueToDevice(s)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(I.IT.Get,"/thirdparty/protocols").then(e=>{if(!e||"object"!=typeof e)throw new Error(`/thirdparty/protocols did not return an object: ${e}`);return e})}getThirdpartyLocation(e,t){const i=u.RR("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(I.IT.Get,i,t)}getThirdpartyUser(e,t){const i=u.RR("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(I.IT.Get,i,t)}getTerms(e,t){const i=this.termsUrlForService(e,t);return this.http.requestOtherUrl(I.IT.Get,i)}agreeToTerms(e,t,i,s){const n=this.termsUrlForService(e,t),r={Authorization:"Bearer "+i};return this.http.requestOtherUrl(I.IT.Post,n,{user_accepts:s},{headers:r})}reportEvent(e,t,i,s){const n=u.RR("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(I.IT.Post,n,void 0,{score:i,reason:s})}reportRoom(e,t){const i=u.RR("/rooms/$roomId/report",{$roomId:e});return this.http.authedRequest(I.IT.Post,i,void 0,{reason:t})}getRoomHierarchy(e,t,i,s=!1,n){const r=u.RR("/rooms/$roomId/hierarchy",{$roomId:e}),o={suggested_only:String(s),max_depth:null==i?void 0:i.toString(),from:n,limit:null==t?void 0:t.toString()};return this.http.authedRequest(I.IT.Get,r,o,void 0,{prefix:I.iD.V1}).catch(e=>{if("M_UNRECOGNIZED"===e.errcode)return this.http.authedRequest(I.IT.Get,r,o,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw e})}async unstableCreateFileTree(e){const{room_id:t}=await this.createRoom({name:e,preset:A.k.PrivateChat,power_level_content_override:ne(ne({},F.mG),{},{users:{[this.getUserId()]:100}}),creation_content:{[k.Ct]:k.CJ.Space},initial_state:[{type:k.D7.name,state_key:k.nN.name,content:{[k.ud.name]:!0}},{type:k.Bx.RoomEncryption,state_key:"",content:{algorithm:"m.megolm.v1.aes-sha2"}}]});return new F.wZ(this,t)}unstableGetFileTreeSpace(e){var t,i;const s=this.getRoom(e);if((null==s?void 0:s.getMyMembership())!==Q.O.Join)return null;const n=s.currentState.getStateEvents(k.Bx.RoomCreate,""),r=s.currentState.getStateEvents(k.D7.name,k.nN.name);if(!n)throw new Error("Expected single room create event");return null!=r&&null!==(t=r.getContent())&&void 0!==t&&t[k.ud.name]?(null===(i=n.getContent())||void 0===i?void 0:i[k.Ct])!==k.CJ.Space?null:new F.wZ(this,e):null}slidingSync(e,t,i){const s={};e.pos&&(s.pos=e.pos,delete e.pos),e.timeout&&(s.timeout=e.timeout,delete e.timeout);const n=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(I.IT.Post,"/sync",s,e,{prefix:"/_matrix/client/unstable/org.matrix.simplified_msc3575",baseUrl:t,localTimeoutMs:n,abortSignal:i})}supportsThreads(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.threadSupport)||!1}supportsIntentionalMentions(){return this.canSupport.get(H.Xj.IntentionalMentions)!==H.Tj.Unsupported}async getRoomSummary(e,t){const i={prefix:"/_matrix/client/unstable/im.nheko.summary"};try{const s=u.RR("/summary/$roomid",{$roomid:e});return await this.http.authedRequest(I.IT.Get,s,{via:t},void 0,i)}catch(s){if(s instanceof I.up&&"M_UNRECOGNIZED"===s.errcode){const s=u.RR("/rooms/$roomid/summary",{$roomid:e});return await this.http.authedRequest(I.IT.Get,s,{via:t},void 0,i)}throw s}}processThreadEvents(e,t,i){e.processThreadedEvents(t,i)}processThreadRoots(e,t,i){this.supportsThreads()&&e.processThreadRoots(t,i)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){null!=t&&t.length&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}async whoami(){return this.http.authedRequest(I.IT.Get,"/account/whoami")}async timestampToEvent(e,t,i){const s=u.RR("/rooms/$roomId/timestamp_to_event",{$roomId:e}),n={ts:t.toString(),dir:i};try{return await this.http.authedRequest(I.IT.Get,s,n,void 0,{prefix:I.iD.V1})}catch(e){if("M_UNRECOGNIZED"===e.errcode&&(400===e.httpStatus||404===e.httpStatus||405===e.httpStatus))return await this.http.authedRequest(I.IT.Get,s,n,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw e}}async getAuthMetadata(){let e;try{e=await this.http.request(I.IT.Get,"/auth_metadata",void 0,void 0,{prefix:I.iD.Unstable+"/org.matrix.msc2965"})}catch(e){if(e instanceof I.up&&"M_UNRECOGNIZED"===e.errcode){const{issuer:e}=await this.http.request(I.IT.Get,"/auth_issuer",void 0,void 0,{prefix:I.iD.Unstable+"/org.matrix.msc2965"});return(0,ee.k8)(e)}throw e}return(0,ee.Pl)(e)}}function me(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[`${ae}.${e}`,t]))}function ve(e){return pe(e)?N.S:e.threadRootId}function pe(e){if(!e.threadRootId)return!0;if(e.isThreadRoot)return!0;if(!e.isRelation())return y.vF.warn(`Event is not a relation or a thread root, but still has a threadRootId! id=${e.getId()}`),!0;if(e.isRelation($.RN.name))return!1;return e.relationEventId===e.threadRootId}(0,n.A)(ue,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY")},"./node_modules/matrix-js-sdk/src/content-helpers.ts":(e,t,i)=>{"use strict";i.d(t,{makeEmoteMessage:()=>u,makeHtmlEmote:()=>l,makeHtmlMessage:()=>a,makeHtmlNotice:()=>d,makeNotice:()=>h,makeTextMessage:()=>c,makeTopicContent:()=>m,parseBeaconContent:()=>p,parseBeaconInfoContent:()=>v});var s=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),n=(i("./node_modules/matrix-js-sdk/src/@types/extensible_events.ts"),i("./node_modules/matrix-js-sdk/src/extensible_events_v1/utilities.ts")),r=i("./node_modules/matrix-js-sdk/src/@types/location.ts"),o=i("./node_modules/matrix-js-sdk/src/@types/topic.ts");function a(e,t){return{msgtype:s.Wr.Text,format:"org.matrix.custom.html",body:e,formatted_body:t}}function d(e,t){return{msgtype:s.Wr.Notice,format:"org.matrix.custom.html",body:e,formatted_body:t}}function l(e,t){return{msgtype:s.Wr.Emote,format:"org.matrix.custom.html",body:e,formatted_body:t}}function c(e){return{msgtype:s.Wr.Text,body:e}}function h(e){return{msgtype:s.Wr.Notice,body:e}}function u(e){return{msgtype:s.Wr.Emote,body:e}}const m=(e,t)=>{const i=[];return(0,n.c)(t)&&i.push({body:t,mimetype:"text/html"}),(0,n.c)(e)&&i.push({body:e,mimetype:"text/plain"}),{topic:e,[o.s.name]:{"m.text":i}}},v=e=>{var t;const{description:i,timeout:s,live:n}=e,o=null!==(t=r.vo.findIn(e))&&void 0!==t?t:void 0,a=r.J1.findIn(e);return{description:i,timeout:s,live:n,assetType:null==a?void 0:a.type,timestamp:o}},p=e=>{var t;const i=r.M6.findIn(e),s=null!==(t=r.vo.findIn(e))&&void 0!==t?t:void 0;return{description:null==i?void 0:i.description,uri:null==i?void 0:i.uri,timestamp:s}}},"./node_modules/matrix-js-sdk/src/crypto-api/index.ts":(e,t,i)=>{"use strict";i.d(t,{ux:()=>h,nX:()=>p,cr:()=>d,RT:()=>l,YH:()=>c,wc:()=>m,so:()=>g,uV:()=>f,wF:()=>v,L0:()=>u,wn:()=>a.w,jS:()=>o});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js");i("./node_modules/matrix-js-sdk/src/crypto-api/verification.ts");const n=(0,i("./node_modules/base-x/src/esm/index.js").A)("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r=[139,1];function o(e){var t;const i=new Uint8Array(r.length+e.length+1);i.set(r,0),i.set(e,r.length);let s=0;for(let e=0;e<i.length-1;++e)s^=i[e];i[i.length-1]=s;return null===(t=n.encode(i).match(/.{1,4}/g))||void 0===t?void 0:t.join(" ")}var a=i("./node_modules/matrix-js-sdk/src/crypto-api/key-passphrase.ts");let d=function(e){return e.UserTrustStatusChanged="userTrustStatusChanged",e.KeyBackupStatus="crypto.keyBackupStatus",e.KeyBackupFailed="crypto.keyBackupFailed",e.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",e.KeyBackupDecryptionKeyCached="crypto.keyBackupDecryptionKeyCached",e.VerificationRequestReceived="crypto.verificationRequestReceived",e.WillUpdateDevices="crypto.willUpdateDevices",e.DevicesUpdated="crypto.devicesUpdated",e.KeysChanged="crossSigning.keysChanged",e.LegacyCryptoStoreMigrationProgress="crypto.legacyCryptoStoreMigrationProgress",e.DehydratedDeviceCreated="dehydration.DehydratedDeviceCreated",e.DehydratedDeviceUploaded="dehydration.DehydratedDeviceUploaded",e.RehydrationStarted="dehydration.RehydrationStarted",e.RehydrationProgress="dehydration.RehydrationProgress",e.RehydrationCompleted="dehydration.RehydrationCompleted",e.RehydrationError="dehydration.RehydrationError",e.DehydrationKeyCached="dehydration.DehydrationKeyCached",e.DehydratedDeviceRotationError="dehydration.DehydratedDeviceRotationError",e}({}),l=function(e){return e.MEGOLM_UNKNOWN_INBOUND_SESSION_ID="MEGOLM_UNKNOWN_INBOUND_SESSION_ID",e.MEGOLM_KEY_WITHHELD="MEGOLM_KEY_WITHHELD",e.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE="MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE",e.OLM_UNKNOWN_MESSAGE_INDEX="OLM_UNKNOWN_MESSAGE_INDEX",e.HISTORICAL_MESSAGE_NO_KEY_BACKUP="HISTORICAL_MESSAGE_NO_KEY_BACKUP",e.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED="HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED",e.HISTORICAL_MESSAGE_WORKING_BACKUP="HISTORICAL_MESSAGE_WORKING_BACKUP",e.HISTORICAL_MESSAGE_USER_NOT_JOINED="HISTORICAL_MESSAGE_USER_NOT_JOINED",e.SENDER_IDENTITY_PREVIOUSLY_VERIFIED="SENDER_IDENTITY_PREVIOUSLY_VERIFIED",e.UNSIGNED_SENDER_DEVICE="UNSIGNED_SENDER_DEVICE",e.UNKNOWN_SENDER_DEVICE="UNKNOWN_SENDER_DEVICE",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e}({}),c=function(e){return e[e.AllDevicesIsolationMode=0]="AllDevicesIsolationMode",e[e.OnlySignedDevicesIsolationMode=1]="OnlySignedDevicesIsolationMode",e}({});class h{constructor(e){(0,s.A)(this,"kind",c.AllDevicesIsolationMode),this.errorOnVerifiedUserProblems=e}}class u{constructor(e,t,i,n=!1){(0,s.A)(this,"needsUserApproval",void 0),this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=i,this.needsUserApproval=n}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}class m{constructor(e){var t,i,n,r,o;(0,s.A)(this,"signedByOwner",void 0),(0,s.A)(this,"crossSigningVerified",void 0),(0,s.A)(this,"tofu",void 0),(0,s.A)(this,"localVerified",void 0),(0,s.A)(this,"trustCrossSignedDevices",void 0),this.signedByOwner=null!==(t=e.signedByOwner)&&void 0!==t&&t,this.crossSigningVerified=null!==(i=e.crossSigningVerified)&&void 0!==i&&i,this.tofu=null!==(n=e.tofu)&&void 0!==n&&n,this.localVerified=null!==(r=e.localVerified)&&void 0!==r&&r,this.trustCrossSignedDevices=null!==(o=e.trustCrossSignedDevices)&&void 0!==o&&o}isVerified(){return this.localVerified||this.trustCrossSignedDevices&&this.crossSigningVerified}}let v=function(e){return e.Fetch="fetch",e.LoadKeys="load_keys",e}({}),p=function(e){return e.Master="master",e.SelfSigning="self_signing",e.UserSigning="user_signing",e}({}),g=function(e){return e[e.NONE=0]="NONE",e[e.GREY=1]="GREY",e[e.RED=2]="RED",e}({}),f=function(e){return e[e.UNKNOWN=0]="UNKNOWN",e[e.UNVERIFIED_IDENTITY=1]="UNVERIFIED_IDENTITY",e[e.UNSIGNED_DEVICE=2]="UNSIGNED_DEVICE",e[e.UNKNOWN_DEVICE=3]="UNKNOWN_DEVICE",e[e.AUTHENTICITY_NOT_GUARANTEED=4]="AUTHENTICITY_NOT_GUARANTEED",e[e.MISMATCHED_SENDER_KEY=5]="MISMATCHED_SENDER_KEY",e[e.SENT_IN_CLEAR=6]="SENT_IN_CLEAR",e[e.VERIFICATION_VIOLATION=7]="VERIFICATION_VIOLATION",e[e.MISMATCHED_SENDER=8]="MISMATCHED_SENDER",e}({})},"./node_modules/matrix-js-sdk/src/crypto-api/verification.ts":(e,t,i)=>{"use strict";i.d(t,{FM:()=>s,Ji:()=>r,X9:()=>n});let s=function(e){return e.Change="change",e}({}),n=function(e){return e[e.Unsent=1]="Unsent",e[e.Requested=2]="Requested",e[e.Ready=3]="Ready",e[e.Started=4]="Started",e[e.Cancelled=5]="Cancelled",e[e.Done=6]="Done",e}({}),r=function(e){return e.Cancel="cancel",e.ShowSas="show_sas",e.ShowReciprocateQr="show_reciprocate_qr",e}({})},"./node_modules/matrix-js-sdk/src/errors.ts":(e,t,i)=>{"use strict";i.d(t,{E5:()=>r,LA:()=>o,hP:()=>n,qK:()=>a,xp:()=>d});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js");let n=function(e){return e.TooNew="TOO_NEW",e}({});class r extends Error{constructor(e){super(`Crypto store is invalid because ${e}, please stop the client, delete all data and start the client again`),this.reason=e,this.name="InvalidCryptoStoreError"}}(0,s.A)(r,"TOO_NEW",n.TooNew);Error;class o extends Error{constructor(){super("MatrixClient has been stopped")}}class a extends Error{constructor(e,t){super(e),this.clientEndpoint=t,this.name="UnsupportedDelayedEventsEndpointError"}}class d extends Error{constructor(e,t){super(e),this.clientEndpoint=t,this.name="UnsupportedStickyEventsEndpointError"}}},"./node_modules/matrix-js-sdk/src/extensible_events_v1/utilities.ts":(e,t,i)=>{"use strict";function s(e){return null!=e}i.d(t,{c:()=>s})},"./node_modules/matrix-js-sdk/src/filter.ts":(e,t,i)=>{"use strict";i.d(t,{d:()=>l});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/@types/sync.ts"),r=i("./node_modules/matrix-js-sdk/src/filter-component.ts");function o(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function a(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?o(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):o(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function d(e,t,i){const s=t.split(".");let n=e;for(let e=0;e<s.length-1;e++)n[s[e]]||(n[s[e]]={}),n=n[s[e]];n[s[s.length-1]]=i}class l{static fromJson(e,t,i){const s=new l(e,t);return s.setDefinition(i),s}constructor(e,t){(0,s.A)(this,"definition",{}),(0,s.A)(this,"roomFilter",void 0),(0,s.A)(this,"roomTimelineFilter",void 0),this.userId=e,this.filterId=t}getFilterId(){return this.filterId}getDefinition(){return this.definition}setDefinition(e){this.definition=e;const t=e.room,i={};t&&(t.rooms&&(i.rooms=t.rooms),t.rooms&&(i.not_rooms=t.not_rooms)),this.roomFilter=new r.i(i,this.userId),this.roomTimelineFilter=new r.i((null==t?void 0:t.timeline)||{},this.userId)}getRoomTimelineFilterComponent(){return this.roomTimelineFilter}filterRoomTimeline(e){return this.roomFilter&&(e=this.roomFilter.filter(e)),this.roomTimelineFilter&&(e=this.roomTimelineFilter.filter(e)),e}setTimelineLimit(e){d(this.definition,"room.timeline.limit",e)}setUnreadThreadNotifications(e){var t,i;this.definition=a(a({},this.definition),{},{room:a(a({},null===(t=this.definition)||void 0===t?void 0:t.room),{},{timeline:a(a({},null===(i=this.definition)||void 0===i||null===(i=i.room)||void 0===i?void 0:i.timeline),{},{[n.a.name]:e})})})}setLazyLoadMembers(e){d(this.definition,"room.state.lazy_load_members",e)}setIncludeLeaveRooms(e){d(this.definition,"room.include_leave",e)}}(0,s.A)(l,"LAZY_LOADING_MESSAGES_FILTER",{lazy_load_members:!0})},"./node_modules/matrix-js-sdk/src/http-api/index.ts":(e,t,i)=>{"use strict";i.d(t,{ED:()=>h,IT:()=>d.I,Pw:()=>r.Pw,Y6:()=>c.Y6,_:()=>c._,fZ:()=>c.fZ,iD:()=>r.iD,up:()=>l.up,zs:()=>r.zs});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/http-api/fetch.ts"),r=i("./node_modules/matrix-js-sdk/src/http-api/prefix.ts"),o=i("./node_modules/matrix-js-sdk/src/utils.ts"),a=i("./node_modules/matrix-js-sdk/src/realtime-callbacks.ts"),d=i("./node_modules/matrix-js-sdk/src/http-api/method.ts"),l=i("./node_modules/matrix-js-sdk/src/http-api/errors.ts"),c=i("./node_modules/matrix-js-sdk/src/http-api/utils.ts");i("./node_modules/matrix-js-sdk/src/http-api/interface.ts");class h extends n.H{constructor(...e){super(...e),(0,s.A)(this,"uploads",[])}uploadContent(e,t={}){var i,s,n,h;const u=null===(i=t.includeFilename)||void 0===i||i,m=null!==(s=t.abortController)&&void 0!==s?s:new AbortController,v=(null!==(n=t.type)&&void 0!==n?n:e.type)||"application/octet-stream",p=null!==(h=t.name)&&void 0!==h?h:e.name,g={loaded:0,total:0,abortController:m},f=Promise.withResolvers();if(globalThis.XMLHttpRequest){const i=new globalThis.XMLHttpRequest,s=function(){i.abort(),f.reject(new Error("Timeout"))};let n=a.w(s,3e4);i.onreadystatechange=function(){if(i.readyState===globalThis.XMLHttpRequest.DONE){a.D(n);try{if(0===i.status)throw new DOMException(i.statusText,"AbortError");if(!i.responseText)throw new Error("No response body.");i.status>=400?f.reject((0,c.xy)(i,i.responseText)):f.resolve(JSON.parse(i.responseText))}catch(e){if("AbortError"===e.name)return void f.reject(e);f.reject(new l.Rc("request failed",e))}}},i.upload.onprogress=e=>{var i;a.D(n),g.loaded=e.loaded,g.total=e.total,n=a.w(s,3e4),null===(i=t.progressHandler)||void 0===i||i.call(t,{loaded:e.loaded,total:e.total})};const o=this.getUrl("/upload",void 0,r.zs.V3);u&&p&&o.searchParams.set("filename",encodeURIComponent(p)),!this.opts.useAuthorizationHeader&&this.opts.accessToken&&o.searchParams.set("access_token",encodeURIComponent(this.opts.accessToken)),i.open(d.I.Post,o.href),this.opts.useAuthorizationHeader&&this.opts.accessToken&&i.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),i.setRequestHeader("Content-Type",v),i.send(e),m.signal.addEventListener("abort",()=>{i.abort()})}else{const t={};u&&p&&(t.filename=p);const i={"Content-Type":v};this.authedRequest(d.I.Post,"/upload",t,e,{prefix:r.zs.V3,headers:i,abortSignal:m.signal}).then(f.resolve,f.reject)}return g.promise=f.promise.finally(()=>{(0,o.Nz)(this.uploads,e=>e===g)}),m.signal.addEventListener("abort",()=>{(0,o.Nz)(this.uploads,e=>e===g),f.reject(new DOMException("Aborted","AbortError"))}),this.uploads.push(g),g.promise}cancelUpload(e){const t=this.uploads.find(t=>t.promise===e);return!!t&&(t.abortController.abort(),!0)}getCurrentUploads(){return this.uploads}getContentUri(){return{base:this.opts.baseUrl,path:r.zs.V3+"/upload",params:{access_token:this.opts.accessToken}}}}},"./node_modules/matrix-js-sdk/src/indexeddb-worker.ts":(e,t,i)=>{"use strict";i.d(t,{h:()=>o});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/store/indexeddb-local-backend.ts"),r=i("./node_modules/matrix-js-sdk/src/logger.ts");class o{constructor(e){(0,s.A)(this,"backend",void 0),(0,s.A)(this,"onClose",()=>{this.postMessage.call(null,{command:"closed"})}),(0,s.A)(this,"onMessage",e=>{var t,i,s,o,a,d,l,c,h,u,m,v,p,g,f,y;const S=e.data;let I;switch(S.command){case"setupWorker":this.backend=new n.k(indexedDB,S.args[0]),I=Promise.resolve();break;case"connect":I=null===(t=this.backend)||void 0===t?void 0:t.connect(this.onClose);break;case"isNewlyCreated":I=null===(i=this.backend)||void 0===i?void 0:i.isNewlyCreated();break;case"clearDatabase":I=null===(s=this.backend)||void 0===s?void 0:s.clearDatabase();break;case"getSavedSync":I=null===(o=this.backend)||void 0===o?void 0:o.getSavedSync(!1);break;case"setSyncData":I=null===(a=this.backend)||void 0===a?void 0:a.setSyncData(S.args[0]);break;case"syncToDatabase":I=null===(d=this.backend)||void 0===d?void 0:d.syncToDatabase(S.args[0]);break;case"getUserPresenceEvents":I=null===(l=this.backend)||void 0===l?void 0:l.getUserPresenceEvents();break;case"getNextBatchToken":I=null===(c=this.backend)||void 0===c?void 0:c.getNextBatchToken();break;case"getOutOfBandMembers":I=null===(h=this.backend)||void 0===h?void 0:h.getOutOfBandMembers(S.args[0]);break;case"clearOutOfBandMembers":I=null===(u=this.backend)||void 0===u?void 0:u.clearOutOfBandMembers(S.args[0]);break;case"setOutOfBandMembers":I=null===(m=this.backend)||void 0===m?void 0:m.setOutOfBandMembers(S.args[0],S.args[1]);break;case"getClientOptions":I=null===(v=this.backend)||void 0===v?void 0:v.getClientOptions();break;case"storeClientOptions":I=null===(p=this.backend)||void 0===p?void 0:p.storeClientOptions(S.args[0]);break;case"saveToDeviceBatches":I=null===(g=this.backend)||void 0===g?void 0:g.saveToDeviceBatches(S.args[0]);break;case"getOldestToDeviceBatch":I=null===(f=this.backend)||void 0===f?void 0:f.getOldestToDeviceBatch();break;case"removeToDeviceBatch":I=null===(y=this.backend)||void 0===y?void 0:y.removeToDeviceBatch(S.args[0])}void 0!==I?I.then(e=>{this.postMessage.call(null,{command:"cmd_success",seq:S.seq,result:e})},e=>{r.vF.error("Error running command: "+S.command,e),this.postMessage.call(null,{command:"cmd_fail",seq:S.seq,error:{message:e.message,name:e.name}})}):this.postMessage({command:"cmd_fail",seq:S.seq,error:"Unrecognised command"})}),this.postMessage=e}}},"./node_modules/matrix-js-sdk/src/logger.ts":(e,t,i)=>{"use strict";i.d(t,{Tl:()=>a,vF:()=>o});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/loglevel/lib/loglevel.js"),r=i.n(n);r().methodFactory=function(e,t,i){return function(...t){this.prefix&&t.unshift(this.prefix);return"error"===e||"warn"===e||"trace"===e||"info"===e||"debug"===e?console[e](...t):console.log(...t)}};const o=function e(t){const i="matrix"+(void 0===t?"":`-${t}`),s=r().getLogger(i);return void 0===s.getChild&&(s.prefix=t,s.getChild=i=>{const n=e((null!=t?t:"")+i);return n.methodFactory=s.methodFactory,n.rebuild(),n},s.setLevel(r().levels.DEBUG,!1)),s}();class a{constructor(e,t){(0,s.A)(this,"name",void 0),this.parent=e,this.name=t+":"}trace(...e){this.parent.trace(this.name,...e)}debug(...e){this.parent.debug(this.name,...e)}info(...e){this.parent.info(this.name,...e)}warn(...e){this.parent.warn(this.name,...e)}error(...e){this.parent.error(this.name,...e)}}},"./node_modules/matrix-js-sdk/src/matrixrtc/CallMembership.ts":(e,t,i)=>{"use strict";i.d(t,{F:()=>d,p:()=>l});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/room-member.ts"),r=i("./node_modules/matrix-js-sdk/src/utils.ts"),o=i("./node_modules/matrix-js-sdk/src/matrixrtc/MatrixRTCSession.ts"),a=i("./node_modules/matrix-js-sdk/src/logger.ts");const d=144e5;class l{static equal(e,t){return(0,r.ky)(null==e?void 0:e.membershipData,null==t?void 0:t.membershipData)}constructor(e,t){(0,s.A)(this,"membershipData",void 0),(0,s.A)(this,"matrixEventData",void 0),this.matrixEvent=e;const i=e.getId(),r=e.getSender();if(void 0===i)throw new Error("parentEvent is missing eventId field");if(void 0===r)throw new Error("parentEvent is missing sender field");const o=[],a=[];if(((e,t)=>{var i;const s=" - ";return"string"!=typeof e.device_id&&t.push(s+"device_id must be string"),"string"!=typeof e.call_id&&t.push(s+"call_id must be string"),"string"!=typeof e.application&&t.push(s+"application must be a string"),"string"!=typeof(null===(i=e.focus_active)||void 0===i?void 0:i.type)&&t.push(s+"focus_active.type must be a string"),void 0===e.focus_active&&t.push(s+"focus_active has an invalid type"),void 0===e.foci_preferred||Array.isArray(e.foci_preferred)&&e.foci_preferred.every(e=>"object"==typeof e&&null!==e&&"string"==typeof e.type)||t.push(s+"foci_preferred must be an array of transport objects"),void 0!==e.created_ts&&"number"!=typeof e.created_ts&&t.push(s+"created_ts must be number"),void 0!==e.scope&&"string"!=typeof e.scope&&t.push(s+"scope must be string"),void 0!==e["m.call.intent"]&&"string"!=typeof e["m.call.intent"]&&t.push(s+"m.call.intent must be a string"),0===t.length})(t,o))this.membershipData={kind:"session",data:t};else{if(!((e,t,i)=>{var s;const r=" - ";if("string"!=typeof e.slot_id?t.push(r+"slot_id must be string"):2!==e.slot_id.split("#").length&&t.push(r+'slot_id must include exactly one "#"'),"object"!=typeof e.member||null===e.member?t.push(r+"member must be an object"):("string"!=typeof e.member.user_id?t.push(r+"member.user_id must be string"):n.sh.test(e.member.user_id)?e.member.user_id!==i&&t.push(r+"member.user_id must match the sender"):t.push(r+"member.user_id must be a valid mxid"),"string"!=typeof e.member.device_id&&t.push(r+"member.device_id must be string"),"string"!=typeof e.member.id&&t.push(r+"member.id must be string")),"object"!=typeof e.application||null===e.application?t.push(r+"application must be an object"):"string"!=typeof e.application.type?t.push(r+"application.type must be a string"):e.application.type.includes("#")&&t.push(r+'application.type must not include "#"'),void 0!==e.rtc_transports&&Array.isArray(e.rtc_transports)){for(const i of e.rtc_transports)if("object"!=typeof i||null===i||"string"!=typeof i.type){t.push(r+"rtc_transports entries must be objects with a string type");break}}else t.push(r+"rtc_transports must be an array");if(void 0!==e.versions&&Array.isArray(e.versions)?e.versions.every(e=>"string"==typeof e)||t.push(r+"versions must be an array of strings"):t.push(r+"versions must be an array"),void 0===(null!==(s=e.sticky_key)&&void 0!==s?s:e.msc4354_sticky_key)&&t.push(r+"sticky_key or msc4354_sticky_key must be a defined"),void 0!==e.sticky_key&&"string"!=typeof e.sticky_key&&t.push(r+"sticky_key must be a string"),void 0!==e.msc4354_sticky_key&&"string"!=typeof e.msc4354_sticky_key&&t.push(r+"msc4354_sticky_key must be a string"),void 0!==e.sticky_key&&void 0!==e.msc4354_sticky_key&&e.sticky_key!==e.msc4354_sticky_key&&t.push(r+"sticky_key and msc4354_sticky_key must be equal if both are defined"),void 0!==e["m.relates_to"]){const i=e["m.relates_to"];"object"!=typeof i||null===i?t.push(r+"m.relates_to must be an object if provided"):("string"!=typeof i.event_id&&t.push(r+"m.relates_to.event_id must be a string"),"m.reference"!==i.rel_type&&t.push(r+"m.relates_to.rel_type must be m.reference"))}return 0===t.length})(t,a,r)){const e=o.length<a.length?`Does not match MSC4143 m.call.member:\n${o.join("\n")}\n\n`:`Does not match MSC4143 m.rtc.member:\n${a.join("\n")}\n\n`,i="\nevent:\n"+JSON.stringify(t).replaceAll('"',"'");throw Error("unknown CallMembership data.\n"+e+i)}this.membershipData={kind:"rtc",data:t}}this.matrixEventData={eventId:i,sender:r}}get sender(){return this.userId}get userId(){const{kind:e,data:t}=this.membershipData;return"rtc"===e?t.member.user_id:this.matrixEventData.sender}get eventId(){return this.matrixEventData.eventId}get slotId(){const{kind:e,data:t}=this.membershipData;return"rtc"===e?t.slot_id:(0,o.D1)({application:this.application,id:t.call_id})}get deviceId(){const{kind:e,data:t}=this.membershipData;return"rtc"===e?t.member.device_id:t.device_id}get callIntent(){const{kind:e,data:t}=this.membershipData;if("rtc"===e){const e=t.application["m.call.intent"];return"string"==typeof e?e:void a.vF.warn("RTC membership has invalid m.call.intent")}return t["m.call.intent"]}get slotDescription(){return(0,o.nr)(this.slotId)}get application(){const{kind:e,data:t}=this.membershipData;return"rtc"===e?t.application.type:t.application}get applicationData(){const{kind:e,data:t}=this.membershipData;return"rtc"===e?t.application:{type:t.application,"m.call.intent":t["m.call.intent"]}}get scope(){const{kind:e,data:t}=this.membershipData;if("rtc"!==e)return t.scope}get membershipID(){var e;const{kind:t,data:i}=this.membershipData;return"rtc"===t?i.member.id:(null!==(e=this.createdTs())&&void 0!==e?e:"").toString()}createdTs(){var e;const{kind:t,data:i}=this.membershipData;return"rtc"===t?this.matrixEvent.getTs():null!==(e=i.created_ts)&&void 0!==e?e:this.matrixEvent.getTs()}getAbsoluteExpiry(){var e;const{kind:t,data:i}=this.membershipData;if("rtc"!==t)return this.createdTs()+(null!==(e=i.expires)&&void 0!==e?e:d)}getMsUntilExpiry(){const{kind:e}=this.membershipData;if("rtc"!==e)return this.getAbsoluteExpiry()-Date.now()}isExpired(){const{kind:e}=this.membershipData;return"rtc"!==e&&this.getMsUntilExpiry()<=0}getTransport(e){const{kind:t,data:i}=this.membershipData;switch(t){case"rtc":return i.rtc_transports[0];case"session":switch(i.focus_active.focus_selection){case"multi_sfu":return i.foci_preferred[0];case"oldest_membership":if(l.equal(this,e))return i.foci_preferred[0];if(void 0!==e)return e.getTransport(e)}}}getFocusActive(){const{kind:e,data:t}=this.membershipData;if("session"===e)return t.focus_active}get transports(){const{kind:e,data:t}=this.membershipData;return"rtc"===e?t.rtc_transports:t.foci_preferred}}},"./node_modules/matrix-js-sdk/src/matrixrtc/IMembershipManager.ts":(e,t,i)=>{"use strict";i.d(t,{e:()=>s});let s=function(e){return e.StatusChanged="StatusChanged",e.ProbablyLeft="ProbablyLeft",e}({})},"./node_modules/matrix-js-sdk/src/matrixrtc/MatrixRTCSession.ts":(e,t,i)=>{"use strict";i.d(t,{D1:()=>T,nl:()=>_,nr:()=>b});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/logger.ts"),r=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),o=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),a=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),d=i("./node_modules/matrix-js-sdk/src/@types/membership.ts"),l=i("./node_modules/matrix-js-sdk/src/matrixrtc/CallMembership.ts"),c=i("./node_modules/matrix-js-sdk/src/models/room-state.ts"),h=i("./node_modules/matrix-js-sdk/src/matrixrtc/MembershipManager.ts"),u=i("./node_modules/matrix-js-sdk/src/matrixrtc/EncryptionManager.ts"),m=i("./node_modules/matrix-js-sdk/src/utils.ts"),v=i("./node_modules/matrix-js-sdk/src/matrixrtc/RoomKeyTransport.ts"),p=i("./node_modules/matrix-js-sdk/src/matrixrtc/IMembershipManager.ts"),g=i("./node_modules/matrix-js-sdk/src/matrixrtc/RTCEncryptionManager.ts"),f=i("./node_modules/matrix-js-sdk/src/matrixrtc/RoomAndToDeviceKeyTransport.ts"),y=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),S=i("./node_modules/matrix-js-sdk/src/matrixrtc/ToDeviceKeyTransport.ts");function I(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function E(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?I(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):I(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let R=function(e){return e.MembershipsChanged="memberships_changed",e.JoinStateChanged="join_state_changed",e.EncryptionKeyChanged="encryption_key_changed",e.MembershipManagerError="membership_manager_error",e.DidSendCallNotification="did_send_call_notification",e}({});function b(e){const[t,i]=e.split("#");return{application:t,id:i}}function T(e){return`${e.application}#${e.id}`}class _ extends r.X{get membershipStatus(){var e;return null===(e=this.membershipManager)||void 0===e?void 0:e.status}get probablyLeft(){var e;return null===(e=this.membershipManager)||void 0===e?void 0:e.probablyLeft}get callId(){var e;return null===(e=this.slotDescription)||void 0===e?void 0:e.id}get slotId(){return T(this.slotDescription)}static callMembershipsForRoom(e){return _.sessionMembershipsForSlot(e,{id:"",application:"m.call"})}static sessionMembershipsForRoom(e,t){return this.sessionMembershipsForSlot(e,t)}static sessionMembershipsForSlot(e,t){const i=n.vF.getChild(`[MatrixRTCSession ${e.roomId}]`),s=e.getLiveTimeline().getState(o.q.FORWARDS);if(!s)throw i.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);const r=s.getStateEvents(a.Bx.GroupCallMemberPrefix),c=[];for(const s of r){const n=s.getContent(),r=Object.keys(n).length;if(0===r)continue;const o=[];if(r>1&&"focus_active"in n?o.push(n):1===r&&"memberships"in n&&i.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session"),0!==o.length)for(const n of o)if("application"in n)try{var h;const r=new l.p(s,n);if(!(0,m.ky)(r.slotDescription,t)){i.info(`Ignoring membership of user ${r.sender} for a different slot: ${JSON.stringify(r.slotDescription)}`);continue}if(r.isExpired()){i.info(`Ignoring expired device membership ${r.sender}/${r.deviceId}`);continue}if(!e.hasMembershipState(null!==(h=r.sender)&&void 0!==h?h:"",d.O.Join)){i.info(`Ignoring membership of user ${r.sender} who is not in the room.`);continue}c.push(r)}catch(e){i.warn("Couldn't construct call membership: ",e)}}return c.sort((e,t)=>e.createdTs()-t.createdTs()),c.length>1&&i.debug(`Call memberships in room ${e.roomId}, in order: `,c.map(e=>[e.createdTs(),e.sender])),c}static roomSessionForRoom(e,t){const i=_.sessionMembershipsForSlot(t,{id:"",application:"m.call"});return new _(e,t,i,{id:"",application:"m.call"})}static sessionForRoom(e,t,i){return this.sessionForSlot(e,t,i)}static sessionForSlot(e,t,i){const s=_.sessionMembershipsForSlot(t,i);return new _(e,t,s,i)}get room(){return this.roomSubset}constructor(e,t,i,r){super(),(0,s.A)(this,"membershipManager",void 0),(0,s.A)(this,"encryptionManager",void 0),(0,s.A)(this,"joinConfig",void 0),(0,s.A)(this,"logger",void 0),(0,s.A)(this,"pendingNotificationToSend",void 0),(0,s.A)(this,"expiryTimeout",void 0),(0,s.A)(this,"statistics",{counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}}),(0,s.A)(this,"reEmitter",new y.Q(this)),(0,s.A)(this,"onRoomMemberUpdate",()=>{this.recalculateSessionMembers()}),(0,s.A)(this,"onRTCSessionMemberUpdate",()=>{this.recalculateSessionMembers()}),(0,s.A)(this,"recalculateSessionMembers",()=>{var e;const t=this.memberships;this.memberships=_.sessionMembershipsForSlot(this.room,this.slotDescription);if(t.length!=this.memberships.length||t.some((e,t)=>!l.p.equal(e,this.memberships[t]))){var i,s;this.logger.info(`Memberships for call in room ${this.roomSubset.roomId} have changed: emitting (${this.memberships.length} members)`),(0,m.G$)(this.logger,"emit MatrixRTCSessionEvent.MembershipsChanged",()=>{this.emit(R.MembershipsChanged,t,this.memberships)}),null===(i=this.membershipManager)||void 0===i||i.onRTCSessionMemberUpdate(this.memberships);const e=null===(s=this.membershipManager)||void 0===s?void 0:s.ownMembership;var n;if(this.pendingNotificationToSend&&e&&0===t.length)e.eventId&&null!==(n=this.joinConfig)&&void 0!==n&&n.notificationType?this.sendCallNotify(e.eventId,this.joinConfig.notificationType,e.callIntent):this.logger.warn("Own membership eventId is undefined, cannot send call notification");this.memberships.length>0&&(this.pendingNotificationToSend=void 0)}null===(e=this.encryptionManager)||void 0===e||e.onMembershipsUpdate(t),this.setExpiryTimer()}),this.client=e,this.roomSubset=t,this.memberships=i,this.slotDescription=r,this.logger=n.vF.getChild(`[MatrixRTCSession ${t.roomId}]`);const a=this.roomSubset.getLiveTimeline().getState(o.q.FORWARDS);null==a||a.on(c.f.Members,this.onRoomMemberUpdate),this.setExpiryTimer()}isJoined(){var e,t;return null!==(e=null===(t=this.membershipManager)||void 0===t?void 0:t.isJoined())&&void 0!==e&&e}async stop(){var e;await(null===(e=this.membershipManager)||void 0===e?void 0:e.leave(1e3)),this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);const t=this.roomSubset.getLiveTimeline().getState(o.q.FORWARDS);null==t||t.off(c.f.Members,this.onRoomMemberUpdate)}joinRoomSession(e,t,i){var s;if(this.isJoined())this.logger.info(`Already joined to session in room ${this.roomSubset.roomId}: ignoring join call`);else{{let e;if(this.membershipManager=new h.W(i,this.roomSubset,this.client,this.slotDescription,this.logger),this.reEmitter.reEmit(this.membershipManager,[p.e.ProbablyLeft,p.e.StatusChanged]),null!=i&&i.useExperimentalToDeviceTransport){this.logger.info("Using experimental to-device transport for encryption keys"),this.logger.info("Using to-device with room fallback transport for encryption keys");const[t,i]=[this.client.getUserId(),this.client.getDeviceId()],[s,n,r]=[this.roomSubset,this.client,this.statistics],o=new v.a(s,n,r),a=new S.i(t,i,s.roomId,n,r);e=new f.t(a,o,this.logger),this.reEmitter.reEmit(e,[f.V.EnabledTransportsChanged]),this.encryptionManager=new g.a(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,e,this.statistics,(e,t,i)=>{this.emit(R.EncryptionKeyChanged,e,t,i)},this.logger)}else e=new v.a(this.roomSubset,this.client,this.statistics),this.encryptionManager=new u.p(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,e,this.statistics,(e,t,i)=>{this.emit(R.EncryptionKeyChanged,e,t,i)})}this.joinConfig=i,this.pendingNotificationToSend=null===(s=this.joinConfig)||void 0===s?void 0:s.notificationType,this.membershipManager.join(e,t,e=>{this.logger.error("MembershipManager encountered an unrecoverable error: ",e),this.emit(R.MembershipManagerError,e),this.emit(R.JoinStateChanged,this.isJoined())}),this.encryptionManager.join(i),this.emit(R.JoinStateChanged,!0)}}async leaveRoomSession(e=void 0){if(!this.isJoined())return this.logger.info(`Not joined to session in room ${this.roomSubset.roomId}: ignoring leave call`),!1;this.logger.info(`Leaving call session in room ${this.roomSubset.roomId}`),this.encryptionManager.leave();const t=this.membershipManager.leave(e);return this.emit(R.JoinStateChanged,!1),await t}getFocusInUse(){const e=this.getOldestMembership();return null==e?void 0:e.getTransport(e)}getActiveFocus(){var e;return null===(e=this.getOldestMembership())||void 0===e?void 0:e.getFocusActive()}getOldestMembership(){return this.memberships[0]}getConsensusCallIntent(){var e;const t=null===(e=this.memberships.find(e=>!!e.callIntent))||void 0===e?void 0:e.callIntent;if(t)return this.memberships.every(e=>!e.callIntent||e.callIntent===t)?t:void 0}async updateCallIntent(e){var t,i;if(!(null===(t=this.membershipManager)||void 0===t?void 0:t.ownMembership))throw Error("Not connected yet");await(null===(i=this.membershipManager)||void 0===i?void 0:i.updateCallIntent(e))}reemitEncryptionKeys(){var e;null===(e=this.encryptionManager)||void 0===e||e.getEncryptionKeys().forEach((e,t)=>{e.forEach(e=>{this.emit(R.EncryptionKeyChanged,e.key,e.keyIndex,t)})})}setExpiryTimer(){let e;this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);for(const t of this.memberships){const i=t.getMsUntilExpiry();void 0!==i&&(void 0===e||i<e)&&(e=i)}null!=e&&(this.expiryTimeout=setTimeout(this.onRTCSessionMemberUpdate,e))}sendCallNotify(e,t,i){Promise.all([(async()=>{const e={application:"m.call","m.mentions":{user_ids:[],room:!0},notify_type:"notification"===t?"notify":t,call_id:this.callId};return{response:await this.client.sendEvent(this.roomSubset.roomId,a.Bx.CallNotify,e),content:e}})(),(async()=>{const s={"m.mentions":{user_ids:[],room:!0},notification_type:t,"m.relates_to":{event_id:e,rel_type:a.zZ.Reference},sender_ts:Date.now(),lifetime:3e4};i&&(s["m.call.intent"]=i);return{response:await this.client.sendEvent(this.roomSubset.roomId,a.Bx.RTCNotification,s),content:s}})()]).then(([e,t])=>{const i=E(E({},e.response),e.content),s=E(E({},t.response),t.content);this.emit(R.DidSendCallNotification,s,i)}).catch(([e,t])=>this.logger.error("Failed to send call notification",e,t))}}},"./node_modules/matrix-js-sdk/src/matrixrtc/MatrixRTCSessionManager.ts":(e,t,i)=>{"use strict";i.d(t,{I:()=>c});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/client.ts"),r=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),o=i("./node_modules/matrix-js-sdk/src/models/room-state.ts"),a=i("./node_modules/matrix-js-sdk/src/matrixrtc/MatrixRTCSession.ts"),d=i("./node_modules/matrix-js-sdk/src/@types/event.ts");let l=function(e){return e.SessionStarted="session_started",e.SessionEnded="session_ended",e}({});class c extends r.X{constructor(e,t,i={application:"m.call",id:""}){super(),(0,s.A)(this,"roomSessions",new Map),(0,s.A)(this,"logger",void 0),(0,s.A)(this,"onRoom",e=>{this.refreshRoom(e)}),(0,s.A)(this,"onRoomState",(e,t)=>{const i=this.client.getRoom(e.getRoomId());i?e.getType()==d.Bx.GroupCallMemberPrefix&&this.refreshRoom(i):this.logger.error(`Got room state event for unknown room ${e.getRoomId()}!`)}),this.client=t,this.slotDescription=i,this.logger=e.getChild("[MatrixRTCSessionManager]")}start(){for(const t of null!==(e=this.client.getRooms())&&void 0!==e?e:[]){var e;const i=a.nl.sessionForRoom(this.client,t,this.slotDescription);i.memberships.length>0&&this.roomSessions.set(t.roomId,i)}this.client.on(n.AU.Room,this.onRoom),this.client.on(o.f.Events,this.onRoomState)}stop(){for(const e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(n.AU.Room,this.onRoom),this.client.off(o.f.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,a.nl.sessionForRoom(this.client,e,this.slotDescription)),this.roomSessions.get(e.roomId)}refreshRoom(e){const t=!this.roomSessions.has(e.roomId),i=this.getRoomSession(e),s=i.memberships.length>0&&!t;i.onRTCSessionMemberUpdate();const n=i.memberships.length>0;s&&!n?(this.logger.trace(`Session ended for ${e.roomId} (${i.memberships.length} members)`),this.emit(l.SessionEnded,e.roomId,this.roomSessions.get(e.roomId))):!s&&n&&(this.logger.trace(`Session started for ${e.roomId} (${i.memberships.length} members)`),this.emit(l.SessionStarted,e.roomId,this.roomSessions.get(e.roomId)))}}},"./node_modules/matrix-js-sdk/src/matrixrtc/types.ts":(e,t,i)=>{"use strict";i.d(t,{n:()=>s,t:()=>n});let s=function(e){return e.Disconnected="Disconnected",e.Connecting="Connecting",e.ConnectingFailed="ConnectingFailed",e.Connected="Connected",e.Reconnecting="Reconnecting",e.Disconnecting="Disconnecting",e.Stuck="Stuck",e.Unknown="Unknown",e}({});const n=(e,t,i)=>e.sender===t&&e.deviceId===i},"./node_modules/matrix-js-sdk/src/models/beacon.ts":(e,t,i)=>{"use strict";i.d(t,{HF:()=>c,JH:()=>a,M9:()=>l});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/content-helpers.ts"),r=i("./node_modules/matrix-js-sdk/src/utils.ts"),o=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts");let a=function(e){return e.New="Beacon.new",e.Update="Beacon.update",e.LivenessChange="Beacon.LivenessChange",e.Destroy="Beacon.Destroy",e.LocationUpdate="Beacon.LocationUpdate",e}({});const d=(e,t,i)=>i>=e&&e+t>=i,l=e=>`${e.getRoomId()}_${e.getStateKey()}`;class c extends o.X{constructor(e){super(),(0,s.A)(this,"roomId",void 0),(0,s.A)(this,"_beaconInfo",void 0),(0,s.A)(this,"_isLive",void 0),(0,s.A)(this,"livenessWatchTimeout",void 0),(0,s.A)(this,"_latestLocationEvent",void 0),(0,s.A)(this,"clearLatestLocation",()=>{this._latestLocationEvent=void 0,this.emit(a.LocationUpdate,this.latestLocationState)}),this.rootEvent=e,this.roomId=this.rootEvent.getRoomId(),this.setBeaconInfo(this.rootEvent)}get isLive(){return!!this._isLive}get identifier(){return l(this.rootEvent)}get beaconInfoId(){return this.rootEvent.getId()}get beaconInfoOwner(){return this.rootEvent.getStateKey()}get beaconInfoEventType(){return this.rootEvent.getType()}get beaconInfo(){return this._beaconInfo}get latestLocationState(){return this._latestLocationEvent&&(0,n.parseBeaconContent)(this._latestLocationEvent.getContent())}get latestLocationEvent(){return this._latestLocationEvent}update(e){if(l(e)!==this.identifier)throw new Error("Invalid updating event");e.getTs()<this.rootEvent.getTs()||(this.rootEvent=e,this.setBeaconInfo(this.rootEvent),this.emit(a.Update,e,this),this.clearLatestLocation())}destroy(){this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this._isLive=!1,this.emit(a.Destroy,this.identifier)}monitorLiveness(){if(this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this.checkLiveness(),this.beaconInfo)if(this.isLive){const e=this.beaconInfo.timestamp+this.beaconInfo.timeout-Date.now();e>1&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},e))}else this.beaconInfo.timestamp>Date.now()&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},this.beaconInfo.timestamp-Date.now()))}addLocations(e){var t;if(!this.isLive)return;const i=null===(t=e.filter(e=>{const t=e.getContent(),i=(0,n.parseBeaconContent)(t);if(!i.uri||!i.timestamp)return!1;const{timestamp:s}=i;return this._beaconInfo.timestamp&&d(this._beaconInfo.timestamp,this._beaconInfo.timeout,s)&&(!this.latestLocationState||s>this.latestLocationState.timestamp)}).sort(r.Fq))||void 0===t?void 0:t[0];i&&(this._latestLocationEvent=i,this.emit(a.LocationUpdate,this.latestLocationState))}setBeaconInfo(e){this._beaconInfo=(0,n.parseBeaconInfoContent)(e.getContent()),this.checkLiveness()}checkLiveness(){const e=this.isLive;if(!this.beaconInfo)return;const t=this.beaconInfo.timestamp>Date.now()?this.beaconInfo.timestamp-36e4:this.beaconInfo.timestamp;this._isLive=!!this._beaconInfo.live&&!!t&&d(t,this._beaconInfo.timeout,Date.now()),e!==this.isLive&&this.emit(a.LivenessChange,this.isLive,this)}}},"./node_modules/matrix-js-sdk/src/models/event-timeline-set.ts":(e,t,i)=>{"use strict";i.d(t,{m:()=>h,x:()=>c});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),r=i("./node_modules/matrix-js-sdk/src/logger.ts"),o=i("./node_modules/matrix-js-sdk/src/models/room.ts"),a=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),d=i("./node_modules/matrix-js-sdk/src/models/relations-container.ts");let l;l=r.vF.log.bind(r.vF);let c=function(e){return e.Ignore="ignore",e.Replace="replace",e}({});class h extends a.X{constructor(e,t={},i,r,o=null){var a,l,c;super(),(0,s.A)(this,"relations",void 0),(0,s.A)(this,"timelineSupport",void 0),(0,s.A)(this,"displayPendingEvents",void 0),(0,s.A)(this,"liveTimeline",void 0),(0,s.A)(this,"timelines",void 0),(0,s.A)(this,"_eventIdToTimeline",new Map),(0,s.A)(this,"filter",void 0),this.room=e,this.thread=r,this.threadListType=o,this.timelineSupport=Boolean(t.timelineSupport),this.liveTimeline=new n.q(this),this.displayPendingEvents=!1!==t.pendingEvents,this.timelines=[this.liveTimeline],this._eventIdToTimeline=new Map,this.filter=t.filter,this.relations=null!==(a=null===(l=this.room)||void 0===l?void 0:l.relations)&&void 0!==a?a:new d.t(null!==(c=null==e?void 0:e.client)&&void 0!==c?c:i)}getTimelines(){return this.timelines}getFilter(){return this.filter}setFilter(e){this.filter=e}getPendingEvents(){return this.room&&this.displayPendingEvents?this.room.getPendingEvents():[]}getLiveTimeline(){return this.liveTimeline}setLiveTimeline(e){this.liveTimeline=e}eventIdToTimeline(e){return this._eventIdToTimeline.get(e)}replaceEventId(e,t){const i=this._eventIdToTimeline.get(e);i&&(this._eventIdToTimeline.delete(e),this._eventIdToTimeline.set(t,i))}resetLiveTimeline(e,t){const i=!this.timelineSupport||!t,s=this.liveTimeline,r=i?s.forkLive(n.q.FORWARDS):s.fork(n.q.FORWARDS);i?(this.timelines=[r],this._eventIdToTimeline=new Map):this.timelines.push(r),t&&s.setPaginationToken(t,n.q.FORWARDS),r.setPaginationToken(null!=e?e:null,n.q.BACKWARDS),this.liveTimeline=r,this.emit(o.u9.TimelineReset,this.room,this,i)}getTimelineForEvent(e){if(null==e)return null;const t=this._eventIdToTimeline.get(e);return void 0===t?null:t}findEventById(e){const t=this.getTimelineForEvent(e);if(t)return t.getEvents().find(function(t){return t.getId()==e})}addTimeline(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");const e=new n.q(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,i,s,o){if(!s)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&s==this.liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(this.filter&&!(e=this.filter.filterRoomTimeline(e)).length)return;const a=t?n.q.BACKWARDS:n.q.FORWARDS,d=t?n.q.FORWARDS:n.q.BACKWARDS;let c=!1,h=!1;for(const o of e){const e=o.getId(),u=this._eventIdToTimeline.get(e);if(!u){this.addEventToTimeline(o,s,{toStartOfTimeline:t,addToState:i}),h=!0,c=!0;continue}if(h=!1,u==s){l("Event "+e+" already in timeline "+s);continue}const m=s.getNeighbouringTimeline(a);if(m){l(u==m?"Event "+e+" in neighbouring timeline - switching to "+u:"Event "+e+" already in a different timeline "+u),s=u;continue}r.vF.info("Already have timeline for "+e+" - joining timeline "+s+" to "+u);const v=u===this.liveTimeline,p=s===this.liveTimeline,g=a===n.q.BACKWARDS&&v,f=a===n.q.FORWARDS&&p;g||f?(g&&r.vF.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+u+")"),f&&r.vF.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+s+")")):(s.setNeighbouringTimeline(u,a),u.setNeighbouringTimeline(s,d),s=u,c=!0)}if(h||!c){if(a===n.q.FORWARDS&&s===this.liveTimeline)return r.vF.warn({lastEventWasNew:h,didUpdate:c}),void r.vF.warn(`Refusing to set forwards pagination token of live timeline ${s} to ${o}`);s.setPaginationToken(null!=o?o:null,a)}}addLiveEvent(e,{duplicateStrategy:t,fromCache:i,roomState:s,timelineWasEmpty:r,addToState:o}){if(this.filter){if(!this.filter.filterRoomTimeline([e]).length)return}const a=this._eventIdToTimeline.get(e.getId());if(a)if(t===c.Replace){l("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());const t=a.getEvents();for(let i=0;i<t.length;i++)if(t[i].getId()===e.getId()){s||(s=a.getState(n.q.FORWARDS)),n.q.setEventMetadata(e,s,!1),t[i]=e;break}}else l("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());else this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1,fromCache:i,roomState:s,timelineWasEmpty:r,addToState:o})}addEventToTimeline(e,t,{toStartOfTimeline:i,fromCache:s=!1,roomState:n,timelineWasEmpty:a,addToState:d}){var l;if(t.getTimelineSet()!==this)throw new Error(`EventTimelineSet.addEventToTimeline: Timeline=${t.toString()} does not belong " +\n "in timelineSet(threadId=${null===(l=this.thread)||void 0===l?void 0:l.id})`);const c=e.getId();if(this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this),this.room&&!this.canContain(e)){var h;let i=`event=${c}`;return e.threadRootId&&(i+=`(belongs to thread=${e.threadRootId})`),void r.vF.warn(`EventTimelineSet.addEventToTimeline: Ignoring ${i} that does not belong in timeline=${t.toString()} timelineSet(threadId=${null===(h=this.thread)||void 0===h?void 0:h.id})`)}t.addEvent(e,{toStartOfTimeline:i,roomState:n,timelineWasEmpty:a,addToState:d}),this._eventIdToTimeline.set(c,t);const u={timeline:t,liveEvent:!i&&t==this.liveTimeline&&!s};this.emit(o.u9.Timeline,e,this.room,Boolean(i),!1,u)}insertEventIntoTimeline(e,t,i,s){var n;if(t.getTimelineSet()!==this)throw new Error(`EventTimelineSet.insertEventIntoTimeline: Timeline=${t.toString()} does not belong " +\n "in timelineSet(threadId=${null===(n=this.thread)||void 0===n?void 0:n.id})`);const a=e.getId();if(this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this),this.room&&!this.canContain(e)){var d;let i=`event=${a}`;return e.threadRootId&&(i+=`(belongs to thread=${e.threadRootId})`),void r.vF.warn(`EventTimelineSet.insertEventIntoTimeline: Ignoring ${i} that does not belong in timeline=${t.toString()} timelineSet(threadId=${null===(d=this.thread)||void 0===d?void 0:d.id})`)}const l=e.relationEventId;if(!l)return void this.addEventToTimeline(e,t,{toStartOfTimeline:!1,fromCache:!1,timelineWasEmpty:!1,roomState:i,addToState:s});const c=this.findEventById(l),h=t.getEvents();let u=void 0!==c?h.indexOf(c):0;for(;u<h.length;u++){if(h[u].getTs()>e.getTs())break}t.insertEvent(e,u,i,s),this._eventIdToTimeline.set(a,t);const m={timeline:t,liveEvent:!1};this.emit(o.u9.Timeline,e,this.room,!1,!1,m)}handleRemoteEcho(e,t,i){const s=this._eventIdToTimeline.get(t);s?(this._eventIdToTimeline.delete(t),this._eventIdToTimeline.set(i,s)):this.filter&&!this.filter.filterRoomTimeline([e]).length||this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1,addToState:!1})}removeEvent(e){const t=this._eventIdToTimeline.get(e);if(!t)return null;const i=t.removeEvent(e);if(i){this._eventIdToTimeline.delete(e);const s={timeline:t};this.emit(o.u9.Timeline,i,this.room,void 0,!0,s)}return i}compareEventOrdering(e,t){if(e==t)return 0;const i=this._eventIdToTimeline.get(e),s=this._eventIdToTimeline.get(t);if(void 0===i)return null;if(void 0===s)return null;if(i===s){let s,n;const r=i.getEvents();for(let i=0;i<r.length&&(void 0===s||void 0===n);i++){const o=r[i].getId();o==e&&(s=i),o==t&&(n=i)}const o=s-n;return o<0?-1:o>0?1:0}let r=i;for(;r;){if(r===s)return-1;r=r.getNeighbouringTimeline(n.q.FORWARDS)}for(r=i;r;){if(r===s)return 1;r=r.getNeighbouringTimeline(n.q.BACKWARDS)}return null}canContain(e){if(!this.room)throw new Error("Cannot call `EventTimelineSet::canContain without a `room` set. Set the room when creating the EventTimelineSet to call this method.");const{threadId:t,shouldLiveInRoom:i,shouldLiveInThread:s}=this.room.eventShouldLiveIn(e);if(this.thread)return this.thread.id===t;var n;i||s||r.vF.warn(`EventTimelineSet:canContain event encountered which cannot be added to any timeline roomId=${null===(n=this.room)||void 0===n?void 0:n.roomId} eventId=${e.getId()} threadId=${e.threadRootId}`);return i}}},"./node_modules/matrix-js-sdk/src/models/event-timeline.ts":(e,t,i)=>{"use strict";i.d(t,{O:()=>o,q:()=>a});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/room-state.ts"),r=i("./node_modules/matrix-js-sdk/src/@types/event.ts");let o=function(e){return e.Backward="b",e.Forward="f",e}({});class a{static setEventMetadata(e,t,i){e.setMetadata(t,i)}constructor(e){var t,i;(0,s.A)(this,"roomId",void 0),(0,s.A)(this,"name",void 0),(0,s.A)(this,"events",[]),(0,s.A)(this,"baseIndex",0),(0,s.A)(this,"startState",void 0),(0,s.A)(this,"endState",void 0),(0,s.A)(this,"startToken",null),(0,s.A)(this,"endToken",null),(0,s.A)(this,"prevTimeline",null),(0,s.A)(this,"nextTimeline",null),(0,s.A)(this,"paginationRequests",{[o.Backward]:null,[o.Forward]:null}),this.eventTimelineSet=e,this.roomId=null!==(t=null===(i=e.room)||void 0===i?void 0:i.roomId)&&void 0!==t?t:null,this.roomId&&(this.startState=new n.H(this.roomId),this.endState=new n.H(this.roomId)),this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+(new Date).toISOString()}initialiseState(e,{timelineWasEmpty:t}={}){var i,s;if(this.events.length>0)throw new Error("Cannot initialise state after events are added");null===(i=this.startState)||void 0===i||i.setStateEvents(e,{timelineWasEmpty:t}),null===(s=this.endState)||void 0===s||s.setStateEvents(e,{timelineWasEmpty:t})}forkLive(e){const t=this.getState(e),i=new a(this.eventTimelineSet);return i.startState=null==t?void 0:t.clone(),i.endState=t,this.endState=null==t?void 0:t.clone(),i}fork(e){const t=this.getState(e),i=new a(this.eventTimelineSet);return i.startState=null==t?void 0:t.clone(),i.endState=null==t?void 0:t.clone(),i}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(e){if(e==a.BACKWARDS)return this.startState;if(e==a.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.roomId?this.getState(e).paginationToken:e===o.Backward?this.startToken:this.endToken}setPaginationToken(e,t){this.roomId?this.getState(t).paginationToken=e:t===o.Backward?this.startToken=e:this.endToken=e}getNeighbouringTimeline(e){if(e==a.BACKWARDS)return this.prevTimeline;if(e==a.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+e+"'")}setNeighbouringTimeline(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+t+")");if(t==a.BACKWARDS)this.prevTimeline=e;else{if(t!=a.FORWARDS)throw new Error("Invalid direction '"+t+"'");this.nextTimeline=e}this.setPaginationToken(null,t)}addEvent(e,{toStartOfTimeline:t,roomState:i,timelineWasEmpty:s,addToState:n}){i||(i=t?this.startState:this.endState);const o=this.getTimelineSet();var d;o.room&&(a.setEventMetadata(e,i,t),n&&e.isState()&&o.room.getUnfilteredTimelineSet()===o&&(null===(d=i)||void 0===d||d.setStateEvents([e],{timelineWasEmpty:s}),e.sender&&(e.getType()!==r.Bx.RoomMember||t)||a.setEventMetadata(e,i,t)));let l;l=t?0:this.events.length,this.events.splice(l,0,e),t&&this.baseIndex++}insertEvent(e,t,i,s){const n=this.getTimelineSet();n.room&&(a.setEventMetadata(e,i,!1),s&&e.isState()&&n.room.getUnfilteredTimelineSet()===n&&(i.setStateEvents([e],{}),e.sender&&e.getType()!==r.Bx.RoomMember||a.setEventMetadata(e,i,!1))),this.events.splice(t,0,e)}removeEvent(e){for(let t=this.events.length-1;t>=0;t--){const i=this.events[t];if(i.getId()==e)return this.events.splice(t,1),t<this.baseIndex&&this.baseIndex--,i}return null}toString(){return this.name}}(0,s.A)(a,"BACKWARDS",o.Backward),(0,s.A)(a,"FORWARDS",o.Forward)},"./node_modules/matrix-js-sdk/src/models/event.ts":(e,t,i)=>{"use strict";i.d(t,{OQ:()=>f,P0:()=>g,fb:()=>v.f,kl:()=>y});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-events-sdk/lib/index.js"),r=i("./node_modules/matrix-js-sdk/src/logger.ts"),o=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),a=i("./node_modules/matrix-js-sdk/src/utils.ts"),d=i("./node_modules/matrix-js-sdk/src/models/thread.ts"),l=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),c=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),h=i("./node_modules/matrix-js-sdk/src/common-crypto/CryptoBackend.ts"),u=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),m=i("./node_modules/matrix-js-sdk/src/crypto-api/index.ts"),v=i("./node_modules/matrix-js-sdk/src/models/event-status.ts");const p=Object.freeze({visible:!0}),g=36e5;let f=function(e){return e.Decrypted="Event.decrypted",e.BeforeRedaction="Event.beforeRedaction",e.VisibilityChange="Event.visibilityChange",e.LocalEventIdReplaced="Event.localEventIdReplaced",e.Status="Event.status",e.Replaced="Event.replaced",e.RelationsCreated="Event.relationsCreated",e.SentinelUpdated="Event.sentinelUpdated",e}({});class y extends c.X{setMetadata(e,t){var i,s;const n=this.isState()&&this.getType()===o.Bx.RoomMember&&this.getSender()===this.getStateKey();let r=!1;if(n||null===(i=this.sender)||void 0===i||null===(i=i.events)||void 0===i||!i.member){const t=e.getSentinelMember(this.getSender());t!==this.sender&&(r=!0),this.sender=t}if(n||(null===(s=this.target)||void 0===s||null===(s=s.events)||void 0===s||!s.member)&&this.getType()===o.Bx.RoomMember){const t=e.getSentinelMember(this.getStateKey());t!==this.target&&(r=!0),this.target=t}this.isState()&&t&&(this.forwardLooking=!1),r&&this.emit(f.SentinelUpdated)}constructor(e={}){var t;super(),(0,s.A)(this,"pushDetails",{}),(0,s.A)(this,"_replacingEvent",null),(0,s.A)(this,"_localRedactionEvent",null),(0,s.A)(this,"_isCancelled",!1),(0,s.A)(this,"clearEvent",void 0),(0,s.A)(this,"visibility",p),(0,s.A)(this,"_hasCachedExtEv",!1),(0,s.A)(this,"_cachedExtEv",void 0),(0,s.A)(this,"_decryptionFailureReason",null),(0,s.A)(this,"senderCurve25519Key",null),(0,s.A)(this,"claimedEd25519Key",null),(0,s.A)(this,"forwardingCurve25519KeyChain",[]),(0,s.A)(this,"untrusted",null),(0,s.A)(this,"decryptionPromise",null),(0,s.A)(this,"retryDecryption",!1),(0,s.A)(this,"txnId",void 0),(0,s.A)(this,"thread",void 0),(0,s.A)(this,"threadId",void 0),(0,s.A)(this,"localTimestamp",void 0),(0,s.A)(this,"sender",null),(0,s.A)(this,"target",null),(0,s.A)(this,"status",null),(0,s.A)(this,"error",null),(0,s.A)(this,"forwardLooking",!0),(0,s.A)(this,"reEmitter",void 0),(0,s.A)(this,"unstableStickyExpiresAt",void 0),this.event=e,["state_key","type","sender","room_id","membership"].forEach(t=>{"string"==typeof e[t]&&(e[t]=(0,a.yD)(e[t]))}),["membership","avatar_url","displayname"].forEach(t=>{var i;"string"==typeof(null===(i=e.content)||void 0===i?void 0:i[t])&&(e.content[t]=(0,a.yD)(e.content[t]))}),["rel_type"].forEach(t=>{var i;"string"==typeof(null===(i=e.content)||void 0===i||null===(i=i["m.relates_to"])||void 0===i?void 0:i[t])&&(e.content["m.relates_to"][t]=(0,a.yD)(e.content["m.relates_to"][t]))}),this.txnId=e.txn_id;const i=this.getAge(),n=Date.now();this.localTimestamp=void 0!==i?n-i:null!==(t=this.getTs())&&void 0!==t?t:n,this.reEmitter=new l.Q(this),this.unstableStickyInfo&&(this.unstableStickyInfo.duration_ttl_ms?this.unstableStickyExpiresAt=n+this.unstableStickyInfo.duration_ttl_ms:this.unstableStickyExpiresAt=Math.min(n,this.getTs())+this.unstableStickyInfo.duration_ms)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=n.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){const e=Object.assign({},this.getContent());if(this.getWireType()===o.Bx.RoomMessageEncrypted)for(const[t,i]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||void 0===e[t]&&(e[t]=i);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(){const e=this.getRoomId();var t;if(e)return`id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()} room=${e} ts=${null===(t=this.getDate())||void 0===t?void 0:t.toISOString()}`;return`msgid=${this.getContent()[o.wt]} type=${this.getWireType()} sender=${this.getSender()}`}getOriginalContent(){var e,t;return this._localRedactionEvent?{}:this.clearEvent?null!==(t=this.clearEvent.content)&&void 0!==t?t:{}:null!==(e=this.event.content)&&void 0!==e?e:{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?null!==(e=this._replacingEvent.getContent()["m.new_content"])&&void 0!==e?e:{}:this.getOriginalContent();var e}getWireContent(){return this.event.content||{}}get threadRootId(){var e;if(this.isState())return;const t=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"];if((null==t?void 0:t.rel_type)===d.RN.name)return t.event_id;if(this.thread)return this.thread.id;if(void 0!==this.threadId)return this.threadId;const i=this.getUnsigned();return"string"==typeof i[o.Sr.name]?i[o.Sr.name]:void 0}get isThreadRoot(){if(this.isState())return!1;return!!this.getServerAggregatedRelation(d.RN.name)||this.threadRootId===this.getId()}get replyEventId(){var e;return null===(e=this.getWireContent()["m.relates_to"])||void 0===e||null===(e=e["m.in_reply_to"])||void 0===e?void 0:e.event_id}get relationEventId(){var e;return null===(e=this.getWireContent())||void 0===e||null===(e=e["m.relates_to"])||void 0===e?void 0:e.event_id}getPrevContent(){return this.getUnsigned().prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.clearEvent?this.clearEvent.state_key:this.event.state_key}getWireStateKey(){return this.event.state_key}isState(){return void 0!==this.event.state_key}getMembershipAtEvent(){const e=this.getUnsigned();return o.SY.findIn(e)}makeEncrypted(e,t,i,s){this.clearEvent={type:this.event.type,content:this.event.content,state_key:this.event.state_key},this.event.type=e,this.event.content=t,this.senderCurve25519Key=i,this.claimedEd25519Key=s,this.isState()&&(this.event.state_key=`${this.clearEvent.type}:${this.clearEvent.state_key}`)}isBeingDecrypted(){return null!=this.decryptionPromise}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){return null!==this._decryptionFailureReason}get decryptionFailureReason(){return this._decryptionFailureReason}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 i=this.clearEvent&&!this.isDecryptionFailure(),s=t.forceRedecryptIfUntrusted&&this.isKeySourceUntrusted();if(i&&!s)throw new Error("Attempt to decrypt event which has already been decrypted");return this.decryptionPromise?(r.vF.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();;){let i;this.retryDecryption=!1;try{const i=await e.decryptEvent(this);!0===t.isRetry&&r.vF.info(`Decrypted event on retry (${this.getDetails()})`),this.setClearData(i),this._decryptionFailureReason=null}catch(e){const t=e instanceof h.O?e.detailedString:String(e);if(i=e,this.retryDecryption){r.vF.log(`Error decrypting event (${this.getDetails()}), but retrying: ${t}`);continue}r.vF.warn(`Error decrypting event (${this.getDetails()}): ${t}`),this.setClearDataForDecryptionFailure(String(e)),this._decryptionFailureReason=e instanceof h.O?e.code:m.RT.UNKNOWN_ERROR}return this.decryptionPromise=null,this.retryDecryption=!1,this.setPushDetails(),void(!1!==t.emit&&this.emit(f.Decrypted,this,i))}}setClearData(e){var t,i;this.clearEvent=e.clearEvent,this.senderCurve25519Key=null!==(t=e.senderCurve25519Key)&&void 0!==t?t:null,this.claimedEd25519Key=null!==(i=e.claimedEd25519Key)&&void 0!==i?i:null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.invalidateExtensibleEvent()}setClearDataForDecryptionFailure(e){this.clearEvent={type:o.Bx.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.event.type===o.Bx.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(f.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var t,i;const s=null===(t=null==e?void 0:e.visible)||void 0===t||t,n=null!==(i=null==e?void 0:e.reason)&&void 0!==i?i:null;let r=!1;this.visibility.visible!==s?r=!0:this.visibility.visible||this.visibility.reason===n||(r=!0),r&&(this.visibility=s?p:Object.freeze({visible:!1,reason:n}),this.emit(f.VisibilityChange,this,s))}messageVisibility(){return this.visibility}makeRedacted(e,t){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(f.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(const e in this.event)this.event.hasOwnProperty(e)&&!S.has(e)&&delete this.event[e];this.isEncrypted()&&(this.clearEvent=void 0);const i=this.getType()in I?I[this.getType()]:{},s=this.getContent();for(const e in s)s.hasOwnProperty(e)&&!i[e]&&delete s[e];!this.isThreadRoot&&this.threadRootId&&this.threadRootId!==this.getId()&&(this.moveAllRelatedToMainTimeline(t),e.moveToMainTimeline(t)),this.invalidateExtensibleEvent()}moveAllRelatedToMainTimeline(e){const t=this.thread;if(this.moveToMainTimeline(e),t)for(const s of t.events){var i;(null===(i=s.getRelation())||void 0===i?void 0:i.event_id)===this.getId()&&s.moveAllRelatedToMainTimeline(e)}}moveToMainTimeline(e){var t;null===(t=this.thread)||void 0===t||t.timelineSet.removeEvent(this.getId()),this.setThread(void 0);const i=e.getLiveTimeline();i.getTimelineSet().insertEventIntoTimeline(this,i,i.getState(u.q.FORWARDS),!1)}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return this.getType()===o.Bx.RoomRedaction}asVisibilityChange(){if(!o.Yg.matches(this.getType()))return null;const e=this.getRelation();if(!e||"m.reference"!=e.rel_type)return null;const t=e.event_id;if(!t)return null;const i=this.getWireContent(),s=!!i.visible,n=i.reason;return n&&"string"!=typeof n?null:{visible:s,reason:n,eventId:t}}isVisibilityEvent(){return o.Yg.matches(this.getType())}getRedactionEvent(){var e,t,i,s;return this.isRedacted()?null!==(e=this.clearEvent)&&void 0!==e&&e.unsigned?null!==(i=null===(s=this.clearEvent)||void 0===s?void 0:s.unsigned.redacted_because)&&void 0!==i?i:null:null!==(t=this.event.unsigned)&&void 0!==t&&t.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){var t;const i=this.getUnsigned(),s=this.getId();this.event=e,i.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=i.redacted_because),this.setStatus(null),this.getId()!==s&&this.emit(f.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-(null!==(t=this.getAge())&&void 0!==t?t:0)}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(f.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(f.LocalEventIdReplaced,this)}isRelation(e){var t;const i=null===(t=this.getWireContent())||void 0===t?void 0:t["m.relates_to"];return!(this.isState()&&null!=i&&i.rel_type&&[o.zZ.Replace,o.zZ.Thread].includes(i.rel_type))&&!(null==i||!i.rel_type||!i.event_id||e&&i.rel_type!==e)}getRelation(){var e;return this.isRelation()&&null!==(e=this.getWireContent()["m.relates_to"])&&void 0!==e?e:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=null!=e?e:null,this.emit(f.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return null===(t=this.getUnsigned()["m.relations"])||void 0===t?void 0:t[e]}replacingEventId(){const e=this.getServerAggregatedRelation(o.zZ.Replace);return e?e.event_id:this._replacingEvent?this._replacingEvent.getId():void 0}replacingEvent(){return this._replacingEvent}replacingEventDate(){const e=this.getServerAggregatedRelation(o.zZ.Replace);if(e){const t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent){var t;return null!==(t=this._replacingEvent.getDate())&&void 0!==t?t:void 0}}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const e=this.getRelation();return this.replyEventId?this.replyEventId:e?e.event_id:this.isRedaction()?this.event.redacts:void 0}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 y(JSON.parse(JSON.stringify(this.event)));for(const[t,i]of Object.entries(this))"event"!==t&&(e[t]=i);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;const t=(0,a.hl)(this.event),i=(0,a.hl)(e.event);return JSON.stringify(t)===JSON.stringify(i)}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,[d.ju.Update]),this.thread=e,this.setThreadId(null==e?void 0:e.id),e&&this.reEmitter.reEmit(e,[d.ju.Update]))}getThread(){return this.thread}setThreadId(e){this.threadId=e}get unstableStickyInfo(){var e,t;if(null!==(e=this.event.msc4354_sticky)&&void 0!==e&&e.duration_ms)return{duration_ms:Math.min(g,this.event.msc4354_sticky.duration_ms),duration_ttl_ms:null===(t=this.event.unsigned)||void 0===t?void 0:t.msc4354_sticky_duration_ttl_ms}}}const S=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),I={[o.Bx.RoomMember]:{membership:1},[o.Bx.RoomJoinRules]:{join_rule:1},[o.Bx.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}}},"./node_modules/matrix-js-sdk/src/models/invites-ignorer.ts":(e,t,i)=>{"use strict";i.d(t,{bp:()=>l});var s=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),n=i("./node_modules/matrix-js-sdk/src/@types/partials.ts"),r=i("./node_modules/matrix-js-sdk/src/utils.ts"),o=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),a=i("./node_modules/matrix-js-sdk/src/models/invites-ignorer-types.ts");const d={[a.Jo.User]:o.Bx.PolicyRuleUser,[a.Jo.Room]:o.Bx.PolicyRuleRoom,[a.Jo.Server]:o.Bx.PolicyRuleServer};class l{constructor(e){this.client=e}async addRule(e,t,i){const s=await this.getOrCreateTargetRoom();return(await this.client.sendStateEvent(s.roomId,d[e],{entity:t,reason:i,recommendation:a.Q5.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(e=>e.roomId);return!t.includes(e)&&(t.push(e),await this.withIgnoreInvitesPolicies(e=>{e.sources=t}),!0)}async getRuleForInvite({sender:e,roomId:t}){const i=await this.getOrCreateSourceRooms(),n=e.split(":")[1],o=t.split(":")[1];for(const l of i){const i=l.getUnfilteredTimelineSet().getLiveTimeline().getState(s.q.FORWARDS);for(const{scope:s,entities:l}of[{scope:a.Jo.Room,entities:[t]},{scope:a.Jo.User,entities:[e]},{scope:a.Jo.Server,entities:[n,o]}]){const e=i.getStateEvents(d[s]);for(const t of e){const e=t.getContent();if((null==e?void 0:e.recommendation)!=a.Q5.Ban)continue;const i=null==e?void 0:e.entity;if(!i)continue;let s;try{s=new RegExp((0,r.dn)(i))}catch{continue}for(const e of l)if(e&&s.test(e))return t}}}return null}async getOrCreateTargetRoom(){let e=this.getIgnoreInvitesPolicies().target;if("string"!=typeof e&&(e=null),e){const t=this.client.getRoom(e);if(t)return t;e=null}return e=(await this.client.createRoom({name:"Individual Policy Room",preset:n.k.PrivateChat})).room_id,await this.withIgnoreInvitesPolicies(t=>{t.target=e}),this.client.getRoom(e)}async getOrCreateSourceRooms(){let e=this.getIgnoreInvitesPolicies().sources,t=!1;Array.isArray(e)||(t=!0,e=[]);let i=e.filter(e=>"string"==typeof e).map(e=>this.client.getRoom(e)).filter(e=>!!e);if(i.length!=e.length&&(t=!0),0==i.length){t=!0,i=[await this.getOrCreateTargetRoom()]}return t&&await this.withIgnoreInvitesPolicies(t=>{t.sources=e}),i}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}async withIgnoreInvitesPolicies(e){const{policies:t,ignoreInvitesPolicies:i}=this.getPoliciesAndIgnoreInvitesPolicies();e(i),t[a.NG.name]=i,await this.client.setAccountData(a.fx.name,t)}getPoliciesAndIgnoreInvitesPolicies(){let e={};for(const i of[a.fx.name,a.fx.altName]){var t;if(!i)continue;const s=null===(t=this.client.getAccountData(i))||void 0===t?void 0:t.getContent();if(s){e=s;break}}let i={},s=!1;for(const t of[a.NG.name,a.NG.altName]){if(!t)continue;const n=e[t];if(n&&"object"==typeof n){i=n,s=!0;break}}return s||(e[a.NG.name]=i),{policies:e,ignoreInvitesPolicies:i}}}},"./node_modules/matrix-js-sdk/src/models/poll.ts":(e,t,i)=>{"use strict";i.d(t,{Wi:()=>h,sP:()=>c,sn:()=>d});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-events-sdk/lib/index.js"),r=i("./node_modules/matrix-js-sdk/src/@types/polls.ts"),o=i("./node_modules/matrix-js-sdk/src/models/relations.ts"),a=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts");let d=function(e){return e.New="Poll.new",e.End="Poll.end",e.Update="Poll.update",e.Responses="Poll.Responses",e.Destroy="Poll.Destroy",e.UndecryptableRelations="Poll.UndecryptableRelations",e}({});const l=(e,t)=>({responseEvents:e.filter(e=>{if(!e.isDecryptionFailure())return r.qN.matches(e.getType())&&e.getTs()<=t})});class c extends a.X{constructor(e,t,i){if(super(),(0,s.A)(this,"roomId",void 0),(0,s.A)(this,"pollEvent",void 0),(0,s.A)(this,"_isFetchingResponses",!1),(0,s.A)(this,"relationsNextBatch",void 0),(0,s.A)(this,"responses",null),(0,s.A)(this,"endEvent",void 0),(0,s.A)(this,"undecryptableRelationEventIds",new Set),(0,s.A)(this,"countUndecryptableEvents",e=>{const t=e.filter(e=>e.isDecryptionFailure()).map(e=>e.getId()),i=this.undecryptableRelationsCount;this.undecryptableRelationEventIds=new Set([...this.undecryptableRelationEventIds,...t]),this.undecryptableRelationsCount!==i&&this.emit(d.UndecryptableRelations,this.undecryptableRelationsCount)}),this.rootEvent=e,this.matrixClient=t,this.room=i,!this.rootEvent.getRoomId()||!this.rootEvent.getId())throw new Error("Invalid poll start event.");this.roomId=this.rootEvent.getRoomId(),this.pollEvent=this.rootEvent.unstableExtensibleEvent}get pollId(){return this.rootEvent.getId()}get endEventId(){var e;return null===(e=this.endEvent)||void 0===e?void 0:e.getId()}get isEnded(){return!!this.endEvent}get isFetchingResponses(){return this._isFetchingResponses}get undecryptableRelationsCount(){return this.undecryptableRelationEventIds.size}async getResponses(){return this.responses||this.isFetchingResponses||await this.fetchResponses(),this.responses}onNewRelation(e){var t;if(r.cI.matches(e.getType())&&this.validateEndEvent(e)&&(this.endEvent=e,this.refilterResponsesOnEnd(),this.emit(d.End)),!this.responses)return;const i=(null===(t=this.endEvent)||void 0===t?void 0:t.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:s}=l([e],i);this.countUndecryptableEvents([e]),s.length&&(s.forEach(e=>{this.responses.addEvent(e)}),this.emit(d.Responses,this.responses))}async fetchResponses(){var e,t;this._isFetchingResponses=!0;const i=await this.matrixClient.relations(this.roomId,this.rootEvent.getId(),"m.reference",void 0,{from:this.relationsNextBatch||void 0});await Promise.all(i.events.map(e=>this.matrixClient.decryptEventIfNeeded(e)));const s=this.responses||new o.s("m.reference",r.qN.name,this.matrixClient,[r.qN.altName]),n=i.events.find(e=>r.cI.matches(e.getType()));this.validateEndEvent(n)&&(this.endEvent=n,this.refilterResponsesOnEnd(),this.emit(d.End));const a=(null===(e=this.endEvent)||void 0===e?void 0:e.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:c}=l(i.events,a);c.forEach(e=>{s.addEvent(e)}),this.relationsNextBatch=null!==(t=i.nextBatch)&&void 0!==t?t:void 0,this.responses=s,this.countUndecryptableEvents(i.events),this.relationsNextBatch?this.fetchResponses():this._isFetchingResponses=!1,this.emit(d.Responses,this.responses)}refilterResponsesOnEnd(){var e;if(!this.responses)return;const t=(null===(e=this.endEvent)||void 0===e?void 0:e.getTs())||Number.MAX_SAFE_INTEGER;this.responses.getRelations().forEach(e=>{var i;e.getTs()>t&&(null===(i=this.responses)||void 0===i||i.removeEvent(e))}),this.emit(d.Responses,this.responses)}validateEndEvent(e){if(!e)return!1;if(this.endEvent&&this.endEvent.getTs()<e.getTs())return!1;const t=this.room.currentState,i=e.getSender();return!!i&&(i===this.rootEvent.getSender()||t.maySendRedactionForEvent(this.rootEvent,i))}}const h=e=>{const t=e.getType();return n.M_POLL_START.matches(t)||r.qN.matches(t)||r.cI.matches(t)}},"./node_modules/matrix-js-sdk/src/models/relations.ts":(e,t,i)=>{"use strict";i.d(t,{s:()=>c});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/event.ts"),r=i("./node_modules/matrix-js-sdk/src/logger.ts"),o=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),a=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),d=i("./node_modules/matrix-js-sdk/src/models/room.ts");let l=function(e){return e.Add="Relations.add",e.Remove="Relations.remove",e.Redaction="Relations.redaction",e}({});class c extends a.X{constructor(e,t,i,r){super(),(0,s.A)(this,"relationEventIds",new Set),(0,s.A)(this,"relations",new Set),(0,s.A)(this,"annotationsByKey",{}),(0,s.A)(this,"annotationsBySender",{}),(0,s.A)(this,"sortedAnnotationsByKey",[]),(0,s.A)(this,"targetEvent",null),(0,s.A)(this,"creationEmitted",!1),(0,s.A)(this,"client",void 0),(0,s.A)(this,"onEventStatus",(e,t)=>{e.isSending()?t===n.fb.CANCELLED&&(e.removeListener(n.OQ.Status,this.onEventStatus),this.removeEvent(e)):e.removeListener(n.OQ.Status,this.onEventStatus)}),(0,s.A)(this,"onBeforeRedaction",async e=>{if(this.relations.has(e)){if(this.relations.delete(e),this.relationType===o.zZ.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===o.zZ.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=await this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.removeListener(n.OQ.BeforeRedaction,this.onBeforeRedaction),this.emit(l.Redaction,e)}}),this.relationType=e,this.eventType=t,this.altEventTypes=r,this.client=i instanceof d.Wv?i.client:i}async addEvent(e){if(this.relationEventIds.has(e.getId()))return;const t=e.getRelation();if(!t)return void r.vF.error("Event must have relation info");const i=t.rel_type,s=e.getType();if(this.relationType===i&&((e,t,i=[])=>[t,...i].includes(e))(s,this.eventType,this.altEventTypes)){if(e.isSending()&&e.on(n.OQ.Status,this.onEventStatus),this.relations.add(e),this.relationEventIds.add(e.getId()),this.relationType===o.zZ.Annotation)this.addAnnotationToAggregation(e);else if(this.relationType===o.zZ.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=await this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.on(n.OQ.BeforeRedaction,this.onBeforeRedaction),this.emit(l.Add,e),this.maybeEmitCreated()}else r.vF.error("Event relation info doesn't match this container")}async removeEvent(e){if(this.relations.has(e)){if(this.relations.delete(e),this.relationType===o.zZ.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===o.zZ.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=await this.getLastReplacement();this.targetEvent.makeReplaced(e)}this.emit(l.Remove,e)}}getRelations(){return[...this.relations]}addAnnotationToAggregation(e){var t;const{key:i}=null!==(t=e.getRelation())&&void 0!==t?t:{};if(!i)return;let s=this.annotationsByKey[i];s||(s=this.annotationsByKey[i]=new Set,this.sortedAnnotationsByKey.push([i,s])),s.add(e),this.sortedAnnotationsByKey.sort((e,t)=>{const i=e[1];return t[1].size-i.size});const n=e.getSender();let r=this.annotationsBySender[n];r||(r=this.annotationsBySender[n]=new Set),r.add(e)}removeAnnotationFromAggregation(e){var t;const{key:i}=null!==(t=e.getRelation())&&void 0!==t?t:{};if(!i)return;const s=this.annotationsByKey[i];s&&(s.delete(e),this.sortedAnnotationsByKey.sort((e,t)=>{const i=e[1];return t[1].size-i.size}));const n=e.getSender(),r=this.annotationsBySender[n];r&&r.delete(e)}getSortedAnnotationsByKey(){return this.relationType!==o.zZ.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==o.zZ.Annotation?null:this.annotationsBySender}async getLastReplacement(){if(this.relationType!==o.zZ.Replace)return null;if(!this.targetEvent)return null;const e=this.targetEvent.getServerAggregatedRelation(o.zZ.Replace),t=null==e?void 0:e.origin_server_ts,i=this.getRelations().reduce((e,i)=>i.getSender()!==this.targetEvent.getSender()||t&&t>i.getTs()||e&&e.getTs()>i.getTs()?e:i,null);return null!=i&&i.shouldAttemptDecryption()&&this.client.getCrypto()?await i.attemptDecryption(this.client.getCrypto()):null!=i&&i.isBeingDecrypted()&&await i.getDecryptionPromise(),i}async setTargetEvent(e){if(!this.targetEvent){if(this.targetEvent=e,this.relationType===o.zZ.Replace&&!this.targetEvent.isState()){const e=await this.getLastReplacement();e&&this.targetEvent.makeReplaced(e)}this.maybeEmitCreated()}}maybeEmitCreated(){this.creationEmitted||this.targetEvent&&this.relations.size&&(this.creationEmitted=!0,this.targetEvent.emit(n.OQ.RelationsCreated,this.relationType,this.eventType))}}},"./node_modules/matrix-js-sdk/src/models/room-member.ts":(e,t,i)=>{"use strict";i.d(t,{Yx:()=>h,o5:()=>c,sh:()=>u});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/content-repo.ts"),r=i("./node_modules/matrix-js-sdk/src/utils.ts"),o=i("./node_modules/matrix-js-sdk/src/logger.ts"),a=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),d=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),l=i("./node_modules/matrix-js-sdk/src/@types/membership.ts");let c=function(e){return e.Membership="RoomMember.membership",e.Name="RoomMember.name",e.PowerLevel="RoomMember.powerLevel",e.Typing="RoomMember.typing",e}({});class h extends a.X{constructor(e,t){super(),(0,s.A)(this,"_isOutOfBand",!1),(0,s.A)(this,"modified",-1),(0,s.A)(this,"requestedProfileInfo",!1),(0,s.A)(this,"typing",!1),(0,s.A)(this,"name",void 0),(0,s.A)(this,"rawDisplayName",void 0),(0,s.A)(this,"powerLevel",0),(0,s.A)(this,"user",void 0),(0,s.A)(this,"membership",void 0),(0,s.A)(this,"disambiguate",!1),(0,s.A)(this,"events",{}),this.roomId=e,this.userId=t,this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){var i,s;const n=null!==(i=e.getDirectionalContent().displayname)&&void 0!==i?i:"";if(e.getType()!==d.Bx.RoomMember)return;this._isOutOfBand=!1,this.events.member=e;const a=this.membership;this.membership=e.getDirectionalContent().membership,void 0===this.membership&&o.vF.trace(`membership event with membership undefined (forwardLooking: ${e.forwardLooking})!`,e.getContent(),"prevcontent is ",e.getPrevContent()),this.disambiguate=function(e,t,i){if(!t||t===e)return!1;if(!i)return!1;const s=(0,r.Gp)(t);if(!s)return!1;if(u.test(s))return!0;if(m.test(t))return!0;const n=i.getUserIdsWithDisplayName(t);return!!n.some(t=>t!==e)}(this.userId,n,t);const l=this.name;this.name=function(e,t,i){return t&&t!==e?i?(0,r.d7)(t)+" ("+e+")":(0,r.Gp)(t)?(0,r.d7)(t):e:e}(this.userId,n,this.disambiguate),this.rawDisplayName=(0,r.d7)(null!==(s=e.getDirectionalContent().displayname)&&void 0!==s?s:""),this.rawDisplayName&&(0,r.Gp)(this.rawDisplayName)||(this.rawDisplayName=this.userId),a!==this.membership&&(this.updateModifiedTime(),this.emit(c.Membership,e,this,a)),l!==this.name&&(this.updateModifiedTime(),this.emit(c.Name,e,this,l))}setPowerLevel(e,t){const i=this.powerLevel;this.powerLevel=e,i!==this.powerLevel&&(this.updateModifiedTime(),this.emit(c.PowerLevel,t,this))}setTypingEvent(e){if("m.typing"!==e.getType())return;const t=this.typing;this.typing=!1;const i=e.getContent().user_ids;Array.isArray(i)&&(-1!==i.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this.updateModifiedTime(),this.emit(c.Typing,e,this)))}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}isKicked(){return this.membership===l.O.Leave&&void 0!==this.events.member&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){const e=this.events.member;let t=e.getContent(),i=e.getSender();if(t.membership===l.O.Join&&(t=e.getPrevContent(),i=e.getUnsigned().prev_sender),t.membership===l.O.Invite&&t.is_direct)return i}}getAvatarUrl(e,t,i,s,r=!0,o,a=!1){const d=this.getMxcAvatarUrl();if(!d&&!r)return null;const l=(0,n.y)(e,d,t,i,s,o,void 0,a);return l||null}getMxcAvatarUrl(){return this.events.member?this.events.member.getDirectionalContent().avatar_url:this.user?this.user.avatarUrl:void 0}}const u=/@.+:.+/,m=/[\u200E\u200F\u202A-\u202F]/},"./node_modules/matrix-js-sdk/src/models/room-state.ts":(e,t,i)=>{"use strict";i.d(t,{H:()=>y,f:()=>f});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/room-member.ts"),r=i("./node_modules/matrix-js-sdk/src/logger.ts"),o=i("./node_modules/matrix-js-sdk/src/utils.ts"),a=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),d=i("./node_modules/matrix-js-sdk/src/models/event.ts"),l=i("./node_modules/matrix-js-sdk/src/@types/partials.ts"),c=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),h=i("./node_modules/matrix-js-sdk/src/models/beacon.ts"),u=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),m=i("./node_modules/matrix-js-sdk/src/@types/beacon.ts"),v=i("./node_modules/matrix-js-sdk/src/@types/membership.ts"),p=i("./node_modules/matrix-js-sdk/src/utils/roomVersion.ts"),g=function(e){return e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished",e}(g||{});let f=function(e){return e.Events="RoomState.events",e.Members="RoomState.members",e.NewMember="RoomState.newMember",e.Update="RoomState.update",e.BeaconLiveness="RoomState.BeaconLiveness",e.Marker="RoomState.Marker",e}({});class y extends c.X{constructor(e,t={status:g.NotStarted}){super(),(0,s.A)(this,"reEmitter",new u.Q(this)),(0,s.A)(this,"sentinels",{}),(0,s.A)(this,"displayNameToUserIds",new Map),(0,s.A)(this,"userIdsToDisplayNames",{}),(0,s.A)(this,"tokenToInvite",{}),(0,s.A)(this,"joinedMemberCount",null),(0,s.A)(this,"summaryJoinedMemberCount",null),(0,s.A)(this,"invitedMemberCount",null),(0,s.A)(this,"summaryInvitedMemberCount",null),(0,s.A)(this,"modified",-1),(0,s.A)(this,"members",{}),(0,s.A)(this,"events",new Map),(0,s.A)(this,"paginationToken",null),(0,s.A)(this,"beacons",new Map),(0,s.A)(this,"_liveBeaconIds",[]),(0,s.A)(this,"getVersionWarning",!1),this.roomId=e,this.oobMemberFlags=t,this.updateModifiedTime()}getRoomVersion(){var e;const t=this.getStateEvents(a.Bx.RoomCreate,"");return t?null!==(e=t.getContent().room_version)&&void 0!==e?e:"1":(this.getVersionWarning||(r.vF.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}getJoinedMemberCount(){return null!==this.summaryJoinedMemberCount?this.summaryJoinedMemberCount:(null===this.joinedMemberCount&&(this.joinedMemberCount=this.getMembers().reduce((e,t)=>t.membership===v.O.Join?e+1:e,0)),this.joinedMemberCount)}setJoinedMemberCount(e){this.summaryJoinedMemberCount=e}getInvitedMemberCount(){return null!==this.summaryInvitedMemberCount?this.summaryInvitedMemberCount:(null===this.invitedMemberCount&&(this.invitedMemberCount=this.getMembers().reduce((e,t)=>t.membership===v.O.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(void 0===t){t=new n.Yx(this.roomId,e);const i=this.members[e];null!=i&&i.events.member&&t.setMembershipEvent(i.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return void 0===t?[]:null;if(void 0===t)return Array.from(this.events.get(e).values());const i=this.events.get(e).get(t);return i||null}get hasLiveBeacons(){var e;return!(null===(e=this.liveBeaconIds)||void 0===e||!e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){const e=new y(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=g.NotStarted,Array.from(this.events.values()).forEach(t=>{e.setStateEvents(Array.from(t.values()))}),this.oobMemberFlags.status=t,null!==this.summaryInvitedMemberCount&&e.setInvitedMemberCount(this.getInvitedMemberCount()),null!==this.summaryJoinedMemberCount&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==g.Finished&&this.getMembers().forEach(t=>{var i;t.isOutOfBand()&&(null===(i=e.getMember(t.userId))||void 0===i||i.markOutOfBand())}),e}setUnknownStateEvents(e){const t=e.filter(e=>!this.events.has(e.getType())||!this.events.get(e.getType()).has(e.getStateKey()));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach(e=>{if(e.getRoomId()!==this.roomId||!e.isState())return;m.E.matches(e.getType())&&this.setBeacon(e);const t=this.getStateEventMatching(e);var i;(this.setStateEvent(e),e.getType()===a.Bx.RoomMember)&&(this.updateDisplayNameCache(e.getStateKey(),null!==(i=e.getContent().displayname)&&void 0!==i?i:""),this.updateThirdPartyTokenCache(e));this.emit(f.Events,e,this,t)}),this.onBeaconLivenessChange(),e.forEach(e=>{if(e.getRoomId()===this.roomId&&e.isState())if(e.getType()===a.Bx.RoomMember){const t=e.getStateKey();e.getContent().membership!==v.O.Leave&&e.getContent().membership!==v.O.Ban||(e.getContent().avatar_url=e.getContent().avatar_url||e.getPrevContent().avatar_url,e.getContent().displayname=e.getContent().displayname||e.getPrevContent().displayname);const i=this.getOrCreateMember(t,e);i.setMembershipEvent(e,this),this.updateMember(i),this.emit(f.Members,e,this,i)}else if(e.getType()===a.Bx.RoomPowerLevels){if(""!==e.getStateKey())return;const t=Object.values(this.members),i=this.getStateEvents(a.Bx.RoomCreate,""),s=S(this.getRoomVersion(),i);t.forEach(t=>{const n=t.getLastModifiedTime();if(i){const i=I(t.userId,e,s);t.setPowerLevel(i,e)}n!==t.getLastModifiedTime()&&this.emit(f.Members,e,this,t)}),this.sentinels={}}else a.ge.matches(e.getType())&&this.emit(f.Marker,e,t)}),this.emit(f.Update,this)}async processBeaconEvents(e,t){if(!e.length||!this.beacons.size)return;const i=[...this.beacons.values()].reduce((e,t)=>(e[t.beaconInfoId]=t,e),{}),s=(e,t)=>{if(!m.z.matches(t.getType()))return;const s=i[e];s&&s.addLocations([t])};for(const r of e){var n;const e=null===(n=r.getRelation())||void 0===n?void 0:n.event_id;if(!e||!i[e])return;if(!m.z.matches(r.getType())&&!r.isEncrypted())return;try{await t.decryptEventIfNeeded(r),s(e,r)}catch{r.isDecryptionFailure()&&r.once(d.OQ.Decrypted,async()=>{s(e,r)})}}}getOrCreateMember(e,t){let i=this.members[e];return i||(i=new n.Yx(this.roomId,e),this.members[e]=i,this.emit(f.NewMember,t,this,i)),i}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){const t=(0,h.M9)(e);if(this.beacons.has(t)){const s=this.beacons.get(t);var i;return e.isRedacted()?void(s.beaconInfoId===(null===(i=e.getRedactionEvent())||void 0===i?void 0:i.redacts)&&(s.destroy(),this.beacons.delete(t))):s.update(e)}if(e.isRedacted())return;const s=new h.HF(e);this.reEmitter.reEmit(s,[h.JH.New,h.JH.Update,h.JH.Destroy,h.JH.LivenessChange]),this.emit(h.JH.New,e,s),s.on(h.JH.LivenessChange,this.onBeaconLivenessChange.bind(this)),s.on(h.JH.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(s.identifier,s)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter(e=>e.isLive).map(e=>e.identifier),this.emit(f.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,i;return null!==(t=null===(i=this.events.get(e.getType()))||void 0===i?void 0:i.get(e.getStateKey()))&&void 0!==t?t:null}updateMember(e){const t=this.getStateEvents(a.Bx.RoomCreate,""),i=this.getStateEvents(a.Bx.RoomPowerLevels,"");if(i&&t){const s=I(e.userId,i,S(this.getRoomVersion(),t));e.setPowerLevel(s,i)}delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===g.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===g.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===g.NotStarted&&(this.oobMemberFlags.status=g.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===g.InProgress&&(this.oobMemberFlags.status=g.NotStarted)}clearOutOfBandMembers(){let e=0;Object.keys(this.members).forEach(t=>{this.members[t].isOutOfBand()&&(++e,delete this.members[t])}),r.vF.log(`LL: RoomState removed ${e} members...`),this.oobMemberFlags.status=g.NotStarted}setOutOfBandMembers(e){r.vF.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===g.InProgress&&(r.vF.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=g.Finished,e.forEach(e=>this.setOutOfBandMember(e)),this.emit(f.Update,this))}setOutOfBandMember(e){if(e.getType()!==a.Bx.RoomMember)return;const t=e.getStateKey(),i=this.getMember(t);if(i&&!i.isOutOfBand())return;const s=this.getOrCreateMember(t,e);s.setMembershipEvent(e,this),s.markOutOfBand(),this.updateDisplayNameCache(s.userId,s.name),this.setStateEvent(e),this.updateMember(s),this.emit(f.Members,e,this,s)}setTypingEvent(e){Object.values(this.members).forEach(function(t){t.setTypingEvent(e)})}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return null!==(t=this.displayNameToUserIds.get((0,o.Gp)(e)))&&void 0!==t?t:[]}maySendRedactionForEvent(e,t){const i=this.getMember(t);if(!i||i.membership===v.O.Leave)return!1;if(e.status||e.isRedacted())return!1;return!!this.maySendEvent(a.Bx.RoomRedaction,t)&&(e.getSender()===t||this.hasSufficientPowerLevelFor("redact",i.powerLevel))}hasSufficientPowerLevelFor(e,t){const i=this.getStateEvents(a.Bx.RoomPowerLevels,"");let s={};i&&(s=i.getContent());let n=50;return(0,o.Et)(s[e])&&(n=s[e]),t>=n}maySendMessage(e){return this.maySendEventOfType(a.Bx.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return!(t.isGuest()||!t.credentials.userId)&&this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,i){var s;const n=this.getStateEvents(a.Bx.RoomPowerLevels,"");let r,o={},d=0,l=0;n&&(r=n.getContent(),o=r.events||{},d=Number.isSafeInteger(r.state_default)?r.state_default:50,Number.isSafeInteger(r.events_default)&&(l=r.events_default));let c=i?d:l;Number.isSafeInteger(o[e])&&(c=o[e]);const h=this.getMember(t);return(null!==(s=null==h?void 0:h.powerLevel)&&void 0!==s?s:0)>=c}mayTriggerNotifOfType(e,t){const i=this.getMember(t);if(!i)return!1;const s=this.getStateEvents(a.Bx.RoomPowerLevels,"");let n=50;return s&&s.getContent()&&s.getContent().notifications&&(0,o.Et)(s.getContent().notifications[e])&&(n=s.getContent().notifications[e]),i.powerLevel>=n}getJoinRule(){var e;const t=this.getStateEvents(a.Bx.RoomJoinRules,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).join_rule||l.dx.Invite}getHistoryVisibility(){var e;const t=this.getStateEvents(a.Bx.RoomHistoryVisibility,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).history_visibility||l.Jv.Shared}getGuestAccess(){var e;const t=this.getStateEvents(a.Bx.RoomGuestAccess,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).guest_access||l.rF.Forbidden}findPredecessor(e=!1){if(e){const e=this.getStateEvents(a.Bx.RoomPredecessor,"");if(e){const t=e.getContent(),i=t.predecessor_room_id;let s=t.last_known_event_id;"string"!=typeof s&&(s=void 0);let n=t.via_servers;if(Array.isArray(n)||(n=void 0),"string"==typeof i)return{roomId:i,eventId:s,viaServers:n}}}const t=this.getStateEvents(a.Bx.RoomCreate,"");if(t){const e=t.getContent().predecessor;if(e){const t=e.room_id;if("string"==typeof t){let i=e.event_id;return"string"==typeof i&&""!==i||(i=void 0),{roomId:t,eventId:i}}}}return null}updateThirdPartyTokenCache(e){if(!e.getContent().third_party_invite)return;const t=(e.getContent().third_party_invite.signed||{}).token;if(!t)return;this.getStateEvents(a.Bx.RoomThirdPartyInvite,t)&&(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){const i=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],i){const t=(0,o.Gp)(i),s=this.displayNameToUserIds.get(t);if(s){const i=s.filter(t=>t!==e);this.displayNameToUserIds.set(t,i)}}this.userIdsToDisplayNames[e]=t;const s=t&&(0,o.Gp)(t);if(s){var n;const t=null!==(n=this.displayNameToUserIds.get(s))&&void 0!==n?n:[];t.push(e),this.displayNameToUserIds.set(s,t)}}}function S(e,t){const i=new Set;if((0,p.H)(e)&&t){const e=t.getSender();e&&i.add(e);const s=t.getDirectionalContent().additional_creators;Array.isArray(s)&&s.forEach(e=>i.add(e))}return i}function I(e,t,i){if(i.has(e))return 1/0;{const i=t.getDirectionalContent(),s=i.users||{};return void 0!==s[e]&&Number.isInteger(s[e])?s[e]:void 0!==i.users_default?i.users_default:0}}},"./node_modules/matrix-js-sdk/src/models/room.ts":(e,t,i)=>{"use strict";i.d(t,{Wv:()=>D,X5:()=>O,u9:()=>P});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-events-sdk/lib/index.js"),r=i("./node_modules/matrix-js-sdk/src/models/event-timeline-set.ts"),o=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),a=i("./node_modules/matrix-js-sdk/src/content-repo.ts"),d=i("./node_modules/matrix-js-sdk/src/utils.ts"),l=i("./node_modules/matrix-js-sdk/src/models/event.ts"),c=i("./node_modules/matrix-js-sdk/src/models/event-status.ts"),h=i("./node_modules/matrix-js-sdk/src/models/room-member.ts"),u=i("./node_modules/matrix-js-sdk/src/models/room-summary.ts"),m=i("./node_modules/matrix-js-sdk/src/logger.ts"),v=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),p=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),g=i("./node_modules/matrix-js-sdk/src/client.ts"),f=i("./node_modules/matrix-js-sdk/src/filter.ts"),y=i("./node_modules/matrix-js-sdk/src/models/room-state.ts"),S=i("./node_modules/matrix-js-sdk/src/models/beacon.ts"),I=i("./node_modules/matrix-js-sdk/src/models/thread.ts"),E=i("./node_modules/matrix-js-sdk/src/@types/read_receipts.ts"),R=i("./node_modules/matrix-js-sdk/src/models/relations-container.ts"),b=i("./node_modules/matrix-js-sdk/src/models/read-receipt.ts"),T=i("./node_modules/matrix-js-sdk/src/models/poll.ts"),_=i("./node_modules/matrix-js-sdk/src/models/room-receipts.ts"),w=i("./node_modules/matrix-js-sdk/src/models/compare-event-ordering.ts"),C=i("./node_modules/matrix-js-sdk/src/@types/membership.ts"),k=i("./node_modules/matrix-js-sdk/src/serverCapabilities.ts"),A=i("./node_modules/matrix-js-sdk/src/models/room-sticky-events.ts");function M(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function x(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?M(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):M(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}const F=["1","2","3","4","5","6","7","8","9","10"];let O=function(e){return e.Highlight="highlight",e.Total="total",e}({}),P=function(e){return e.MyMembership="Room.myMembership",e.Tags="Room.tags",e.AccountData="Room.accountData",e.Receipt="Room.receipt",e.Name="Room.name",e.Redaction="Room.redaction",e.RedactionCancelled="Room.redactionCancelled",e.LocalEchoUpdated="Room.localEchoUpdated",e.Timeline="Room.timeline",e.TimelineReset="Room.timelineReset",e.TimelineRefresh="Room.TimelineRefresh",e.OldStateUpdated="Room.OldStateUpdated",e.CurrentStateUpdated="Room.CurrentStateUpdated",e.HistoryImportedWithinTimeline="Room.historyImportedWithinTimeline",e.UnreadNotifications="Room.UnreadNotifications",e.Summary="Room.Summary",e}({});class D extends b.h{constructor(e,t,i,n={}){super(),(0,s.A)(this,"reEmitter",void 0),(0,s.A)(this,"txnToEvent",new Map),(0,s.A)(this,"notificationCounts",{}),(0,s.A)(this,"bumpStamp",void 0),(0,s.A)(this,"threadNotifications",new Map),(0,s.A)(this,"cachedThreadReadReceipts",new Map),(0,s.A)(this,"oldestThreadedReceiptTs",1/0),(0,s.A)(this,"unthreadedReceipts",new Map),(0,s.A)(this,"timelineSets",void 0),(0,s.A)(this,"polls",new Map),(0,s.A)(this,"threadsTimelineSets",[]),(0,s.A)(this,"filteredTimelineSets",{}),(0,s.A)(this,"timelineNeedsRefresh",!1),(0,s.A)(this,"pendingEventList",void 0),(0,s.A)(this,"blacklistUnverifiedDevices",void 0),(0,s.A)(this,"selfMembership",void 0),(0,s.A)(this,"heroes",null),(0,s.A)(this,"getTypeWarning",!1),(0,s.A)(this,"membersPromise",void 0),(0,s.A)(this,"name",void 0),(0,s.A)(this,"normalizedName",void 0),(0,s.A)(this,"tags",{}),(0,s.A)(this,"accountData",new Map),(0,s.A)(this,"summary",null),(0,s.A)(this,"oldState",void 0),(0,s.A)(this,"currentState",void 0),(0,s.A)(this,"relations",void 0),(0,s.A)(this,"threads",new Map),(0,s.A)(this,"visibilityEvents",new Map),(0,s.A)(this,"roomReceipts",new _.$(this)),(0,s.A)(this,"stickyEvents",new A.x),(0,s.A)(this,"threadTimelineSetsPromise",null),(0,s.A)(this,"threadsReady",!1),(0,s.A)(this,"updateThreadRootEvents",(e,t,i)=>{var s,n;e.length&&(this.updateThreadRootEvent(null===(s=this.threadsTimelineSets)||void 0===s?void 0:s[0],e,t,i),e.hasCurrentUserParticipated&&this.updateThreadRootEvent(null===(n=this.threadsTimelineSets)||void 0===n?void 0:n[1],e,t,i))}),(0,s.A)(this,"updateThreadRootEvent",(e,t,i,s)=>{e&&t.rootEvent&&(s&&e.removeEvent(t.id),I.jV.hasServerSideSupport?e.addLiveEvent(t.rootEvent,{duplicateStrategy:r.x.Replace,fromCache:!1,roomState:this.currentState,addToState:!1}):e.addEventToTimeline(t.rootEvent,e.getLiveTimeline(),{toStartOfTimeline:i,addToState:!1}))}),(0,s.A)(this,"tryApplyRedaction",e=>{if(e.isRedaction()){const t=e.event.redacts,i=t?this.findEventById(t):void 0;i&&this.applyEventAsRedaction(e,i)}else if(e.getType()===p.Bx.RoomMember){const t=e.getContent().membership;if(t!==C.O.Ban&&(t!==C.O.Leave||e.getStateKey()===e.getSender()))return;if(!0!==e.getContent()["org.matrix.msc4293.redact_events"])return;if(!this.getLiveTimeline().getState(o.O.Forward).maySendRedactionForEvent(e,e.getSender()))return;const i=this.getTimelineSets().map(e=>e.getTimelines()).reduce((e,t)=>(e.push(...t),e),[]).map(t=>t.getEvents().filter(t=>t.getSender()===e.getStateKey())).reduce((e,t)=>(e.push(...t),t),[]);for(const t of i)this.applyEventAsRedaction(e,t)}}),this.roomId=e,this.client=t,this.myUserId=i,this.opts=n,this.setMaxListeners(100),this.reEmitter=new v.Q(this),n.pendingEventOrdering=n.pendingEventOrdering||g.eO.Chronological,this.name=e,this.normalizedName=e,this.relations=new R.t(this.client,this),this.on(P.Receipt,this.onReceipt),this.reEmitter.reEmit(this.stickyEvents,[A.m.Update]),this.timelineSets=[new r.m(this,n)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[P.Timeline,P.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===g.eO.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then(e=>{const i=this.client.getEventMapper({decrypt:!1});e.forEach(async e=>{const s=i(e);await t.decryptEventIfNeeded(s),s.setStatus(c.f.NOT_SENT),this.addPendingEvent(s,s.getTxnId())})})),this.opts.lazyLoadMembers?this.membersPromise=void 0:this.membersPromise=Promise.resolve(!1)}async createThreadsTimelineSets(){var e;if(this.threadTimelineSetsPromise)return this.threadTimelineSetsPromise;if(null!==(e=this.client)&&void 0!==e&&e.supportsThreads())try{this.threadTimelineSetsPromise=Promise.all([this.createThreadTimelineSet(),this.createThreadTimelineSet(I.x3.My)]);const e=await this.threadTimelineSetsPromise;return this.threadsTimelineSets[0]=e[0],this.threadsTimelineSets[1]=e[1],e}catch{return this.threadTimelineSetsPromise=null,null}return null}async decryptCriticalEvents(){if(!this.client.getCrypto())return;const e=this.getEventReadUpTo(this.client.getUserId(),!0),t=this.getLiveTimeline().getEvents(),i=t.findIndex(t=>t.event.event_id===e),s=t.slice(i).reverse().map(e=>this.client.decryptEventIfNeeded(e));await Promise.allSettled(s)}async decryptAllEvents(){if(!this.client.getCrypto())return;const e=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0).reverse().map(e=>this.client.decryptEventIfNeeded(e));await Promise.allSettled(e)}getCreator(){var e;const t=this.currentState.getStateEvents(p.Bx.RoomCreate,"");return null!==(e=null==t?void 0:t.getSender())&&void 0!==e?e:null}getVersion(){return this.currentState.getRoomVersion()}async getRecommendedVersion(){let e={};try{e=await this.client.getCapabilities()}catch{}let t=e["m.room_versions"];if(!t){t={default:"10",available:{}};for(const e of F)t.available[e]=k.L.Stable}let i=this.checkVersionAgainstCapability(t);if(i.urgent&&i.needsUpgrade){m.vF.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");try{e=await this.client.fetchCapabilities()}catch(e){m.vF.warn("Failed to refresh room version capabilities",e)}if(t=e["m.room_versions"],!t)return m.vF.warn("No room version capability - assuming upgrade required."),i;i=this.checkVersionAgainstCapability(t)}return i}checkVersionAgainstCapability(e){const t=this.getVersion();m.vF.log(`[${this.roomId}] Current version: ${t}`),m.vF.log(`[${this.roomId}] Version capability: `,e);const i={version:t,needsUpgrade:!1,urgent:!1};if(t===e.default)return i;return Object.keys(e.available).filter(t=>"stable"===e.available[t]).includes(t)||(i.version=e.default,i.needsUpgrade=!0,i.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),i.urgent?m.vF.warn(`URGENT upgrade required on ${this.roomId}`):m.vF.warn(`Non-urgent upgrade required on ${this.roomId}`)),i}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(p.Bx.RoomTombstone,e)}getPendingEvents(){if(!this.pendingEventList)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(!this.pendingEventList)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=(0,d.Nz)(this.pendingEventList,function(t){return t.getId()==e},!1);return this.savePendingEvents(),t}hasPendingEvent(e){var t,i;return null!==(t=null===(i=this.pendingEventList)||void 0===i?void 0:i.some(t=>t.getId()===e))&&void 0!==t&&t}getPendingEvent(e){var t,i;return null!==(t=null===(i=this.pendingEventList)||void 0===i?void 0:i.find(t=>t.getId()===e))&&void 0!==t?t:null}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}get timeline(){return this.getLiveTimeline().getEvents()}getLastActiveTimestamp(){const e=this.getLiveTimeline().getEvents();if(e.length){return e[e.length-1].getTs()}return Number.MIN_SAFE_INTEGER}getLastLiveEvent(){var e,t;const i=this.getLiveTimeline().getEvents(),s=i[i.length-1],n=this.getLastThread();if(!n)return s;const r=n.events[n.events.length-1];return(null!==(e=null==s?void 0:s.getTs())&&void 0!==e?e:0)>(null!==(t=null==r?void 0:r.getTs())&&void 0!==t?t:0)?s:r}getLastThread(){return this.getThreads().reduce((e,t)=>{var i,s;if(!e)return t;const n=t.events[t.events.length-1],r=e.events[e.events.length-1];return(null!==(i=null==n?void 0:n.getTs())&&void 0!==i?i:0)>=(null!==(s=null==r?void 0:r.getTs())&&void 0!==s?s:0)?t:e},void 0)}getMyMembership(){var e;return null!==(e=this.selfMembership)&&void 0!==e?e:C.O.Leave}getDMInviter(){const e=this.getMember(this.myUserId);if(e)return e.getDMInviter();if(this.selfMembership===C.O.Invite){var t;if(2===this.getInvitedAndJoinedMemberCount())return null===(t=this.heroes)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.userId}}guessDMUserId(){const e=this.getMember(this.myUserId);if(e){const t=e.getDMInviter();if(t)return t}if(Array.isArray(this.heroes)&&this.heroes.length)return this.heroes[0].userId;const t=this.currentState.getMembers().find(e=>e.userId!==this.myUserId);return t?t.userId:this.myUserId}getFunctionalMembers(){const e=this.currentState.getStateEvents(p.Ng.name,"");return Array.isArray(null==e?void 0:e.getContent().service_members)?e.getContent().service_members:[]}getAvatarFallbackMember(){var e;const t=this.getFunctionalMembers();let i=0;if(this.getMembers().forEach(e=>{"join"!==e.membership&&"invite"!==e.membership||t.includes(e.userId)||i++}),i>2)return;const s=null===(e=this.heroes)||void 0===e?void 0:e.filter(e=>!t.includes(e.userId)),n=Array.isArray(s)&&s.length;if(n){for(const e of s){if(e.fromMSC4186){const t=new h.Yx(this.roomId,e.userId);return t.setMembershipEvent(new l.kl({event_id:"$"+this.roomId+e.userId+(new Date).getTime(),type:p.Bx.RoomMember,state_key:e.userId,content:{displayname:e.displayName,avatar_url:e.avatarUrl}})),t}{const t=this.getMember(e.userId);if(t)return t}}const e=s.map(e=>this.getMember(e.userId)).find(e=>!!e);if(e)return e}const r=this.getMembers(),o=null==r?void 0:r.filter(e=>!t.includes(e.userId));if(o.length<=2){const e=o.find(e=>e.userId!==this.myUserId);if(e)return e}if(n){const e=s.map(e=>this.client.getUser(e.userId)).find(e=>!!e);if(e){const t=new h.Yx(this.roomId,e.userId);return t.user=e,t}}}updateMyMembership(e){const t=this.selfMembership;this.selfMembership=e,t!==e&&(e===C.O.Leave&&this.cleanupAfterLeaving(),this.emit(P.MyMembership,this,e,t))}async loadMembersFromServer(){const e=this.client.store.getSyncToken();return(await this.client.members(this.roomId,void 0,C.O.Leave,null!=e?e:void 0)).chunk}async loadMembers(){let e=!1,t=await this.client.store.getOutOfBandMembers(this.roomId);(null===t||this.hasEncryptionStateEvent())&&(e=!0,t=await this.loadMembersFromServer(),m.vF.log(`LL: got ${t.length} members from server for room ${this.roomId}`));return{memberEvents:t.filter(d.O5).map(this.client.getEventMapper()),fromServer:e}}membersLoaded(){return!this.opts.lazyLoadMembers||this.currentState.outOfBandMembersReady()}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const e=this.loadMembers().then(e=>(this.currentState.setOutOfBandMembers(e.memberEvents),e.fromServer)).catch(e=>{throw this.membersPromise=void 0,this.currentState.markOutOfBandMembersFailed(),e});return e.then(e=>{if(e){const e=this.currentState.getMembers().filter(e=>e.isOutOfBand()).map(e=>{var t;return null===(t=e.events.member)||void 0===t?void 0:t.event});m.vF.log(`LL: telling store to write ${e.length} members for room ${this.roomId}`);return this.client.store.setOutOfBandMembers(this.roomId,e).catch(e=>{m.vF.log("LL: storing OOB room members failed, oh well",e)})}}).catch(e=>{m.vF.error(e)}),this.membersPromise=e,this.membersPromise}async clearLoadedMembersIfNeeded(){this.opts.lazyLoadMembers&&this.membersPromise&&(await this.loadMembersIfNeeded(),await this.client.store.clearOutOfBandMembers(this.roomId),this.currentState.clearOutOfBandMembers(),this.membersPromise=void 0)}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch(e=>{m.vF.error(`error after clearing loaded members from room ${this.roomId} after leaving`),m.vF.log(e)})}async refreshLiveTimeline(){const e=this.getLiveTimeline(),t=e.getPaginationToken(o.q.FORWARDS),i=e.getPaginationToken(o.q.BACKWARDS),s=e.getEvents(),n=s[s.length-1];m.vF.log(`[refreshLiveTimeline for ${this.roomId}] at mostRecentEventInTimeline=${n&&n.getId()} liveTimelineBefore=${e.toString()} forwardPaginationToken=${t} backwardPaginationToken=${i}`);const r=this.getUnfilteredTimelineSet();let a;n?(this.resetLiveTimeline(null,null),this.emit(P.TimelineRefresh,this,r),a=await this.client.getEventTimeline(r,n.getId())):a=await this.client.getLatestTimeline(r);const d=r.getLiveTimeline();!d||null===d.getPaginationToken(o.O.Forward)&&null===d.getPaginationToken(o.O.Backward)&&0===d.getEvents().length?(m.vF.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`),a.setPaginationToken(t,o.q.FORWARDS),r.setLiveTimeline(a),this.fixUpLegacyTimelineFields()):m.vF.log(`[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new live timeline after we reset it. We'll use that instead since any events in the scrollback from this timeline will include the history.`),this.setTimelineNeedsRefresh(!1),this.emit(P.TimelineRefresh,this,r)}resetLiveTimeline(e,t){for(const i of this.timelineSets)i.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);for(const i of this.threads.values())i.resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){const e=this.oldState,t=this.currentState;this.oldState=this.getLiveTimeline().getState(o.q.BACKWARDS),this.currentState=this.getLiveTimeline().getState(o.q.FORWARDS),e!==this.oldState&&this.emit(P.OldStateUpdated,this,e,this.oldState),t!==this.currentState&&(this.emit(P.CurrentStateUpdated,this,t,this.currentState),this.reEmitter.stopReEmitting(t,[y.f.Events,y.f.Members,y.f.NewMember,y.f.Update,y.f.Marker,S.JH.New,S.JH.Update,S.JH.Destroy,S.JH.LivenessChange]),this.reEmitter.reEmit(this.currentState,[y.f.Events,y.f.Members,y.f.NewMember,y.f.Update,y.f.Marker,S.JH.New,S.JH.Update,S.JH.Destroy,S.JH.LivenessChange]))}onReceipt(e){this.hasEncryptionStateEvent()&&this.clearNotificationsOnReceipt(e)}clearNotificationsOnReceipt(e){let t=[],i=!1;const s=e.getContent();for(const e of Object.values(s))for(const[s,n]of Object.entries(e))if(d.ll(s)&&n)for(const[e,s]of Object.entries(n)){if(!s||"object"!=typeof s)continue;const n=s;e===this.client.getUserId()&&(void 0===n.thread_id?i=!0:"string"==typeof n.thread_id&&t.push(n.thread_id))}i&&(t=this.getThreads().filter(e=>this.getThreadUnreadNotificationCount(e.id,O.Total)>0||this.getThreadUnreadNotificationCount(e.id,O.Highlight)>0).map(e=>e.id),t.push("main"));for(const e of t){var n;const t=20,i="main"===e?this.getLiveTimeline():null===(n=this.getThread(e))||void 0===n?void 0:n.liveTimeline;if(!i){m.vF.warn(`Couldn't find timeline for thread ID ${e} in room ${this.roomId}`);continue}const s=i.getEvents();let o=0;for(let e=s.length-1;e>=0;e--){var r;if(e===s.length-t)return;const i=s[e];if(this.hasUserReadEvent(this.client.getUserId(),i.getId()))break;const n=this.client.getPushActionsForEvent(i);o+=null!=n&&null!==(r=n.tweaks)&&void 0!==r&&r.highlight?1:0}"main"===e?this.setUnreadNotificationCount(O.Highlight,o):this.setThreadUnreadNotificationCount(e,O.Highlight,o)}}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){const t=this.findEventById(e),i=this.findThreadForEvent(t);return i?i.timelineSet.getTimelineForEvent(e):this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(e){this.timelineNeedsRefresh=e}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(e){let t=this.getUnfilteredTimelineSet().findEventById(e);if(!t){const i=this.getThreads();for(let s=0;s<i.length;s++){if(t=i[s].findEventById(e),t)return t}}return t}getUnreadNotificationCount(e=O.Total){let t=this.getRoomUnreadNotificationCount(e);for(const s of this.threadNotifications.values()){var i;t+=null!==(i=s[e])&&void 0!==i?i:0}return t}getUnreadCountForEventContext(e=O.Total,t){var i;return null!==(i=!!t.threadRootId&&!t.isThreadRoot?this.getThreadUnreadNotificationCount(t.threadRootId,e):this.getRoomUnreadNotificationCount(e))&&void 0!==i?i:0}getRoomUnreadNotificationCount(e=O.Total){var t;return null!==(t=this.notificationCounts[e])&&void 0!==t?t:0}getThreadUnreadNotificationCount(e,t=O.Total){var i,s;return null!==(i=null===(s=this.threadNotifications.get(e))||void 0===s?void 0:s[t])&&void 0!==i?i:0}hasThreadUnreadNotification(){for(const i of this.threadNotifications.values()){var e,t;if((null!==(e=i.highlight)&&void 0!==e?e:0)>0||(null!==(t=i.total)&&void 0!==t?t:0)>0)return!0}return!1}setThreadUnreadNotificationCount(e,t,i){var s,n;const r=x({highlight:null===(s=this.threadNotifications.get(e))||void 0===s?void 0:s.highlight,total:null===(n=this.threadNotifications.get(e))||void 0===n?void 0:n.total},{[t]:i});this.threadNotifications.set(e,r),this.emit(P.UnreadNotifications,r,e)}get threadsAggregateNotificationType(){let e=null;for(const s of this.threadNotifications.values()){var t,i;if((null!==(t=s.highlight)&&void 0!==t?t:0)>0)return O.Highlight;(null!==(i=s.total)&&void 0!==i?i:0)>0&&!e&&(e=O.Total)}return e}resetThreadUnreadNotificationCountFromSync(e=[]){const t=this.hasEncryptionStateEvent();for(const[i,s]of this.threadNotifications)e.includes(i)||(s.total=0,t||(s.highlight=0));this.emit(P.UnreadNotifications)}setBumpStamp(e){this.bumpStamp=e}getBumpStamp(){return this.bumpStamp}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t,this.emit(P.UnreadNotifications,this.notificationCounts)}setUnread(e,t){return this.setUnreadNotificationCount(e,t)}setSummary(e){var t;const i=null===(t=e["m.heroes"])||void 0===t?void 0:t.map(e=>({userId:e,fromMSC4186:!1})),s=e["m.joined_member_count"],n=e["m.invited_member_count"];Number.isInteger(s)&&this.currentState.setJoinedMemberCount(s),Number.isInteger(n)&&this.currentState.setInvitedMemberCount(n),Array.isArray(i)&&(this.heroes=i.filter(e=>e.userId!=this.myUserId)),this.emit(P.Summary,e)}setMSC4186SummaryData(e,t,i){e&&(this.heroes=e.filter(e=>e.user_id!==this.myUserId).map(e=>({userId:e.user_id,displayName:e.displayname,avatarUrl:e.avatar_url,fromMSC4186:!0}))),void 0!==t&&Number.isInteger(t)&&this.currentState.setJoinedMemberCount(t),void 0!==i&&Number.isInteger(i)&&this.currentState.setInvitedMemberCount(i),this.emit(P.Summary,{"m.heroes":this.heroes?this.heroes.map(e=>e.userId):[],"m.joined_member_count":t,"m.invited_member_count":i})}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return void 0===this.blacklistUnverifiedDevices?null:this.blacklistUnverifiedDevices}getAvatarUrl(e,t,i,s,n=!0,r=!1){const o=this.currentState.getStateEvents(p.Bx.RoomAvatar,"");if(!o&&!n)return null;const d=o?o.getContent().url:null;return d?(0,a.y)(e,d,t,i,s,void 0,void 0,r):null}getMxcAvatarUrl(){var e;return(null===(e=this.currentState.getStateEvents(p.Bx.RoomAvatar,""))||void 0===e||null===(e=e.getContent())||void 0===e?void 0:e.url)||null}getCanonicalAlias(){const e=this.currentState.getStateEvents(p.Bx.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(p.Bx.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,i,s,n){s.getTimelineSet().addEventsToTimeline(e,t,i,s,n)}getThread(e){var t;return null!==(t=this.threads.get(e))&&void 0!==t?t:null}getThreads(){return Array.from(this.threads.values())}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership(C.O.Join)}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter(function(t){return t.membership===e})}async getEncryptionTargetMembers(){await this.loadMembersIfNeeded();let e=this.getMembersWithMembership(C.O.Join);return this.shouldEncryptForInvitedMembers()&&(e=e.concat(this.getMembersWithMembership(C.O.Invite))),e}shouldEncryptForInvitedMembers(){var e;const t=this.currentState.getStateEvents(p.Bx.RoomHistoryVisibility,"");return"joined"!==(null==t||null===(e=t.getContent())||void 0===e?void 0:e.history_visibility)}getDefaultRoomName(e){return this.calculateRoomName(e,!0)}hasMembershipState(e,t){const i=this.getMember(e);return!!i&&i.membership===t}getOrCreateFilteredTimelineSet(e,{prepopulateTimeline:t=!0,useSyncEvents:i=!0,pendingEvents:s=!0}={}){if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const n=Object.assign({filter:e,pendingEvents:s},this.opts),a=new r.m(this,n);this.reEmitter.reEmit(a,[P.Timeline,P.TimelineReset]),i&&(this.filteredTimelineSets[e.filterId]=a,this.timelineSets.push(a));const d=this.getLiveTimeline();if(t){d.getEvents().forEach(function(e){a.addLiveEvent(e,{addToState:!1})});let e=d;for(;e.getNeighbouringTimeline(o.q.BACKWARDS);)e=e.getNeighbouringTimeline(o.q.BACKWARDS);a.getLiveTimeline().setPaginationToken(e.getPaginationToken(o.q.BACKWARDS),o.q.BACKWARDS)}else if(i){const e=d.getPaginationToken(o.O.Forward);a.getLiveTimeline().setPaginationToken(e,o.O.Backward)}return a}async getThreadListFilter(e=I.x3.All){const t=this.client.getUserId(),i=new f.d(t),s={room:{timeline:{[I.H.name]:[I.RN.name]}}};e===I.x3.My&&(s.room.timeline[I.o1.name]=[t]),i.setDefinition(s);const n=await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${e}`,i);return i.filterId=n,i}async createThreadTimelineSet(e){let t;if(I.jV.hasServerSideListSupport)t=new r.m(this,x(x({},this.opts),{},{pendingEvents:!1}),void 0,void 0,null!=e?e:I.x3.All),this.reEmitter.reEmit(t,[P.Timeline,P.TimelineReset]);else if(I.jV.hasServerSideSupport){const i=await this.getThreadListFilter(e);t=this.getOrCreateFilteredTimelineSet(i,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else t=new r.m(this,{pendingEvents:!1}),Array.from(this.threads).forEach(([,i])=>{if(0===i.length)return;const s=i.timeline.some(e=>e.getSender()===this.client.getUserId());(e!==I.x3.My||s)&&t.getLiveTimeline().addEvent(i.rootEvent,{toStartOfTimeline:!1,addToState:!1})});return t}processThreadRoots(e,t){if(this.client.supportsThreads())for(const i of e)o.q.setEventMetadata(i,this.currentState,t),this.getThread(i.getId())||this.createThread(i.getId(),i,[],t)}async fetchRoomThreads(){if(!this.threadsReady&&this.client.supportsThreads()){if(I.jV.hasServerSideListSupport)await Promise.all([this.fetchRoomThreadList(I.x3.All),this.fetchRoomThreadList(I.x3.My)]);else{const i=await this.getThreadListFilter(),{chunk:s}=await this.client.createMessagesRequest(this.roomId,"",Number.MAX_SAFE_INTEGER,o.O.Backward,i);if(!s.length)return;const n=s.map(this.client.getEventMapper()).sort((e,t)=>{const i=e.getServerAggregatedRelation(I.RN.name),s=t.getServerAggregatedRelation(I.RN.name);return i.latest_event.origin_server_ts-s.latest_event.origin_server_ts});let a;const d=this.getLiveTimeline().getState(o.q.FORWARDS);for(const i of n){var e;const s={duplicateStrategy:r.x.Ignore,fromCache:!1,addToState:!1,roomState:d};null===(e=this.threadsTimelineSets[0])||void 0===e||e.addLiveEvent(i,s);const n=i.getServerAggregatedRelation(I.RN.name);var t;if(null!=n&&n.current_user_participated)null===(t=this.threadsTimelineSets[1])||void 0===t||t.addLiveEvent(i,s),a=i}this.processThreadRoots(n,!0),this.client.decryptEventIfNeeded(n[n.length-1]),a&&this.client.decryptEventIfNeeded(a)}this.on(I.ju.NewReply,this.onThreadReply),this.on(I.ju.Update,this.onThreadUpdate),this.on(I.ju.Delete,this.onThreadDelete),this.threadsReady=!0}}async processPollEvents(e){for(const t of e)try{if(!t.isEncrypted()&&!(0,T.Wi)(t))continue;await this.client.decryptEventIfNeeded(t),this.processPollEvent(t)}catch(e){m.vF.warn("Error processing poll event",t.getId(),e)}}async processPollEvent(e){if(e.isDecryptionFailure())return void e.once(l.OQ.Decrypted,e=>{this.processPollEvent(e)});if(n.M_POLL_START.matches(e.getType())){try{const t=new T.sP(e,this.client,this);this.polls.set(e.getId(),t),this.emit(T.sn.New,t),e.once(l.OQ.BeforeRedaction,e=>{this.polls.delete(e.getId())})}catch{}return}const t=e.relationEventId;if(t&&this.polls.has(t)){const i=this.polls.get(t);null==i||i.onNewRelation(e)}}async fetchRoomThreadList(e){if(!this.client.supportsThreads())return;if(0===this.threadsTimelineSets.length)return;const t=e===I.x3.My?this.threadsTimelineSets[1]:this.threadsTimelineSets[0],{chunk:i,end:s}=await this.client.createThreadListMessagesRequest(this.roomId,null,void 0,o.O.Backward,t.threadListType,t.getFilter());if(t.getLiveTimeline().setPaginationToken(null!=s?s:null,o.O.Backward),!i.length)return;const n=i.map(this.client.getEventMapper());this.processThreadRoots(n,!0);const a=this.getLiveTimeline().getState(o.q.FORWARDS);for(const e of n)t.addLiveEvent(e,{duplicateStrategy:r.x.Replace,fromCache:!1,roomState:a,addToState:!1})}onThreadUpdate(e){this.updateThreadRootEvents(e,!1,!1)}onThreadReply(e){this.updateThreadRootEvents(e,!1,!0)}onThreadDelete(e){var t;this.threads.delete(e.id);const i=this.getTimelineForEvent(e.id),s=null==i||null===(t=i.getEvents())||void 0===t?void 0:t.find(t=>t.getId()===e.id);s?e.clearEventMetadata(s):m.vF.debug("onThreadDelete: Could not find root event in room timeline");for(const t of this.threadsTimelineSets)t.removeEvent(e.id)}removeFilteredTimelineSet(e){const t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];const i=this.timelineSets.indexOf(t);i>-1&&this.timelineSets.splice(i,1)}eventShouldLiveIn(e,t,i){var s;if(null===(s=this.client)||void 0===s||!s.supportsThreads())return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||null!=i&&i.has(e.getId()))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};const n=e.isRelation(I.RN.name),r=e.getAssociatedId(),o=e.threadRootId;if(r&&!n&&(o===r||null!=i&&i.has(r)))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};let a;var d;r&&(a=null!==(d=this.findEventById(r))&&void 0!==d?d:null==t?void 0:t.find(e=>e.getId()===r));return a&&!n?this.eventShouldLiveIn(a,t,i):null!=o?{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:o}:!r||e.replyEventId?{shouldLiveInRoom:!0,shouldLiveInThread:!1}:{shouldLiveInRoom:!1,shouldLiveInThread:!1}}findThreadForEvent(e){if(!e)return null;const{threadId:t}=this.eventShouldLiveIn(e);return t?this.getThread(t):null}addThreadedEvents(e,t,i=!1){const s=this.getThread(e);if(s)s.addEvents(t,i);else{var n;const s=null!==(n=this.findEventById(e))&&void 0!==n?n:t.find(t=>t.getId()===e);this.createThread(e,s,t,i)}}processThreadedEvents(e,t){e.forEach(this.tryApplyRedaction);const i={};for(const t of e){var s;const{threadId:e,shouldLiveInThread:n}=this.eventShouldLiveIn(t);n&&!i[e]&&(i[e]=[]),null===(s=i[e])||void 0===s||s.push(t)}Object.entries(i).map(([e,i])=>this.addThreadedEvents(e,i,t))}createThread(e,t,i=[],s){var n;if(this.threads.has(e))return this.threads.get(e);if(t){const e=this.relations.getAllChildEventsForEvent(t.getId());null!=e&&e.length&&(i=i.concat(e.filter(e=>!e.isRelation(p.zZ.Replace))))}const r=new I.jV(e,t,{room:this,client:this.client,pendingEventOrdering:this.opts.pendingEventOrdering,receipts:null!==(n=this.cachedThreadReadReceipts.get(e))&&void 0!==n?n:[]});return this.reEmitter.reEmit(r,[I.ju.Delete,I.ju.Update,I.ju.NewReply,P.Timeline,P.TimelineReset]),this.cachedThreadReadReceipts.delete(e),this.threads.set(r.id,r),r.addEvents(i,!1),this.threadsReady&&r.initialEventsFetched&&this.updateThreadRootEvents(r,s,!1),this.emit(I.ju.New,r,s),r}applyEventAsRedaction(e,t){const i=t.threadRootId;if(t.makeRedacted(e,this),t.isState()){const e=this.currentState.getStateEvents(t.getType(),t.getStateKey());(null==e?void 0:e.getId())===t.getId()&&this.currentState.setStateEvents([t])}this.emit(P.Redaction,e,this,i),this.visibilityEvents.delete(t.getId()),t.isVisibilityEvent()&&this.redactVisibilityChangeEvent(e)}processLiveEvent(e){this.tryApplyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e);if(!e.getUnsigned().transaction_id&&e.getSender()===this.myUserId)for(const[t,i]of this.txnToEvent)if(i.getId()===e.getId()){m.vF.debug("processLiveEvent: found sent event without txn ID: ",t,e.getId());const i=e.getUnsigned();i.transaction_id=t,e.setUnsigned(i);break}}addLiveEvent(e,t){const{duplicateStrategy:i,timelineWasEmpty:s,fromCache:n,addToState:r}=t;for(const t of this.timelineSets)t.addLiveEvent(e,{duplicateStrategy:i,fromCache:n,timelineWasEmpty:s,addToState:r});e.sender&&e.getType()!==p.Bx.RoomRedaction&&this.addReceipt((0,b.D)(e.sender.userId,e,E.L.Read),!0)}addPendingEvent(e,t){if(e.status!==c.f.SENDING&&e.status!==c.f.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent.get(t))throw new Error("addPendingEvent called on an event with known txnId "+t);if(o.q.setEventMetadata(e,this.getLiveTimeline().getState(o.q.FORWARDS),!1),this.txnToEvent.set(t,e),this.pendingEventList){if(this.pendingEventList.some(e=>e.status===c.f.NOT_SENT)&&(m.vF.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(c.f.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){const t=e.event.redacts;let i=this.pendingEventList.find(e=>e.getId()===t);!i&&t&&(i=this.findEventById(t)),i&&(i.markLocallyRedacted(e),this.emit(P.Redaction,e,this,i.threadRootId))}}else for(const t of this.timelineSets)t.getFilter()?t.getFilter().filterRoomTimeline([e]).length&&t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1,addToState:!1}):t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1,addToState:!1});this.emit(P.LocalEchoUpdated,e,this)}savePendingEvents(){if(this.pendingEventList){const e=this.pendingEventList.map(e=>x(x({},e.event),{},{txn_id:e.getTxnId()})).filter(e=>{const t=e.type===p.Bx.RoomMessageEncrypted,i=this.hasEncryptionStateEvent();return t||!i});this.client.store.setPendingEvents(this.roomId,e)}}aggregateNonLiveRelation(e){this.relations.aggregateChildEvent(e)}getEventForTxnId(e){return this.txnToEvent.get(e)}handleRemoteEcho(e,t){const i=t.getId(),s=e.getId(),n=t.status;m.vF.debug(`Got remote echo for event ${i} -> ${s} old status ${n}`),this.txnToEvent.delete(e.getUnsigned().transaction_id),this.pendingEventList&&this.removePendingEvent(i),t.handleRemoteEcho(e.event);const{shouldLiveInRoom:r,threadId:o}=this.eventShouldLiveIn(e),a=o?this.getThread(o):null;if(null==a||a.setEventMetadata(t),null==a||a.timelineSet.handleRemoteEcho(t,i,s),r)for(const e of this.timelineSets)e.handleRemoteEcho(t,i,s);this.emit(P.LocalEchoUpdated,t,this,i,n)}updatePendingEvent(e,t,i){if(m.vF.log(`setting pendingEvent status to ${t} in ${e.getRoomId()} event ID ${e.getId()} -> ${i}`),t==c.f.SENT&&!i)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==c.f.SENT){if(this.getTimelineForEvent(i)){const t=this.findEventById(i);if(!(null==t?void 0:t.getUnsigned().transaction_id)&&t){const i=t.getUnsigned();i.transaction_id=e.getTxnId(),t.setUnsigned(i),this.removeEvent(t.getId()),this.handleRemoteEcho(t,e)}return}}const s=e.status,n=e.getId();if(!s)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const r=U[s];if(null==r||!r.includes(t))throw new Error(`Invalid EventStatus transition ${s}->${t}`);if(e.setStatus(t),t==c.f.SENT){e.replaceLocalEventId(i);const{shouldLiveInRoom:t,threadId:s}=this.eventShouldLiveIn(e),r=s?this.getThread(s):void 0;if(null==r||r.setEventMetadata(e),null==r||r.timelineSet.replaceEventId(n,i),t)for(const e of this.timelineSets)e.replaceEventId(n,i)}else if(t==c.f.CANCELLED){if(this.pendingEventList){const e=this.getPendingEvent(n);this.removePendingEvent(n),null!=e&&e.isRedaction()&&this.revertRedactionLocalEcho(e)}this.removeEvent(n)}this.savePendingEvents(),this.emit(P.LocalEchoUpdated,e,this,n,s)}revertRedactionLocalEcho(e){const t=e.event.redacts;if(!t)return;const i=this.getUnfilteredTimelineSet().findEventById(t);i&&(i.unmarkLocallyRedacted(),this.emit(P.RedactionCancelled,e,this),i.isRelation()&&this.aggregateNonLiveRelation(i))}assertTimelineSetsAreLive(){for(let e=0;e<this.timelineSets.length;e++){const t=this.timelineSets[e].getLiveTimeline();if(t.getPaginationToken(o.q.FORWARDS))throw new Error("live timeline "+e+" is no longer live - it has a pagination token ("+t.getPaginationToken(o.q.FORWARDS)+")");if(t.getNeighbouringTimeline(o.q.FORWARDS))throw new Error(`live timeline ${e} is no longer live - it has a neighbouring timeline`)}}async addLiveEvents(e,t){const{duplicateStrategy:i,fromCache:s,timelineWasEmpty:n=!1,addToState:r}=t;if(i&&-1===["replace","ignore"].indexOf(i))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");this.assertTimelineSetsAreLive();const o=this.findThreadRoots(e),a={},d={duplicateStrategy:i,fromCache:s,timelineWasEmpty:n,addToState:r},c=[...e];for(const t of e){var h;if(this.processLiveEvent(t),t.getUnsigned().transaction_id){const e=this.txnToEvent.get(t.getUnsigned().transaction_id);if(e){this.handleRemoteEcho(t,e);continue}}let{shouldLiveInRoom:e,shouldLiveInThread:i,threadId:s=""}=this.eventShouldLiveIn(t,c,o);if(!i&&!e&&t.isRelation())try{const n=new l.kl(await this.client.fetchRoomEvent(this.roomId,t.relationEventId));if(c.push(n),n.threadRootId){o.add(n.threadRootId);const e=t.getUnsigned();e[p.Sr.name]=n.threadRootId,t.setUnsigned(e)}({shouldLiveInRoom:e,shouldLiveInThread:i,threadId:s=""}=this.eventShouldLiveIn(t,c,o))}catch(e){m.vF.error("Failed to load parent event of unhandled relation",e)}i&&!a[s]&&(a[s]=[]),null===(h=a[s])||void 0===h||h.push(t),e?this.addLiveEvent(t,d):!i&&t.isRelation()&&this.relations.aggregateChildEvent(t)}Object.entries(a).forEach(([e,t])=>{this.addThreadedEvents(e,t,!1)})}partitionThreadedEvents(e){if(this.client.supportsThreads()){const t=this.findThreadRoots(e);return e.reduce((i,s)=>{const{shouldLiveInRoom:n,shouldLiveInThread:r,threadId:o}=this.eventShouldLiveIn(s,e,t);return n&&i[0].push(s),r&&(s.setThreadId(null!=o?o:""),i[1].push(s)),r||n||i[2].push(s),i},[[],[],[]])}return[e,[],[]]}findThreadRoots(e){const t=new Set;for(const i of e){const e=i.threadRootId;null!=e&&t.add(e)}return t}addReceipt(e,t=!1){const i=e.getContent();this.roomReceipts.add(i,t),Object.keys(i).forEach(e=>{Object.keys(i[e]).forEach(s=>{Object.keys(i[e][s]).forEach(n=>{var r,o,a;const d=i[e][s][n],l=!d.thread_id||d.thread_id===E.S,c=l?this:this.threads.get(null!==(r=d.thread_id)&&void 0!==r?r:"");var h;if(c){if(c.addReceiptToStructure(e,s,n,d,t),!t&&this.client.isInitialSyncComplete()&&n===this.client.getUserId()){const t=c.timeline[c.timeline.length-1];t&&e===t.getId()&&n===t.getSender()&&(c.setUnread(O.Total,0),c.setUnread(O.Highlight,0))}}else this.cachedThreadReadReceipts.set(d.thread_id,[...null!==(h=this.cachedThreadReadReceipts.get(d.thread_id))&&void 0!==h?h:[],{eventId:e,receiptType:s,userId:n,receipt:d,synthetic:t}]);n===this.client.getUserId()&&!l&&d.ts<this.oldestThreadedReceiptTs&&(this.oldestThreadedReceiptTs=d.ts),!d.thread_id&&d.ts>(null!==(o=null===(a=this.unthreadedReceipts.get(n))||void 0===a?void 0:a.ts)&&void 0!==o?o:0)&&this.unthreadedReceipts.set(n,d)})})}),this.emit(P.Receipt,e,this)}addEphemeralEvents(e){for(const t of e)t.getType()===p.Bx.Typing?this.currentState.setTypingEvent(t):t.getType()===p.Bx.Receipt&&this.addReceipt(t)}removeEvents(e){for(const t of e)this.removeEvent(t)}removeEvent(e){let t=!1;for(const i of this.timelineSets){const s=i.removeEvent(e);s&&(s.isRedaction()&&this.revertRedactionLocalEcho(s),t=!0)}return t}recalculate(){const e=this.currentState.getStateEvents(p.Bx.RoomMember,this.myUserId);if(e){const t=e.getContent().membership;if(this.updateMyMembership(t),t===C.O.Invite){(e.getUnsigned().invite_room_state||[]).forEach(e=>{this.currentState.getStateEvents(e.type,e.state_key)||this.currentState.setStateEvents([new l.kl({type:e.type,state_key:e.state_key,content:e.content,event_id:"$fake"+Date.now(),room_id:this.roomId,sender:this.myUserId})])})}}const t=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=(0,d.S8)(this.name),this.summary=new u.c(this.roomId,{title:this.name}),t!==this.name&&this.emit(P.Name,this)}addTags(e){this.tags=e.getContent().tags||{},this.emit(P.Tags,e,this)}addAccountData(e){for(const t of e){"m.tag"===t.getType()&&this.addTags(t);const e=t.getType(),i=this.accountData.get(e);this.accountData.set(e,t),this.emit(P.AccountData,t,this,i)}}getAccountData(e){return this.accountData.get(e)}_unstable_getStickyEvents(){return this.stickyEvents.getStickyEvents()}_unstable_getKeyedStickyEvent(e,t,i){return this.stickyEvents.getKeyedStickyEvent(e,t,i)}_unstable_getUnkeyedStickyEvent(e,t){return this.stickyEvents.getUnkeyedStickyEvent(e,t)}_unstable_addStickyEvents(e){return this.stickyEvents.addStickyEvents(e)}maySendMessage(){return this.getMyMembership()===C.O.Join&&(this.hasEncryptionStateEvent()?this.currentState.maySendEvent(p.Bx.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(p.Bx.RoomMessage,this.myUserId))}canInvite(e){let t=this.getMyMembership()===C.O.Join;const i=this.currentState.getStateEvents(p.Bx.RoomPowerLevels,""),s=i&&i.getContent(),n=this.getMember(e);return s&&n&&s.invite>n.powerLevel&&(t=!1),t}getJoinRule(){return this.currentState.getJoinRule()}getHistoryVisibility(){return this.currentState.getHistoryVisibility()}getGuestAccess(){return this.currentState.getGuestAccess()}getType(){const e=this.currentState.getStateEvents(p.Bx.RoomCreate,"");if(e)return e.getContent()[p.Ct];this.getTypeWarning||(m.vF.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===p.CJ.Space}isCallRoom(){return this.getType()===p.CJ.UnstableCall}isElementVideoRoom(){return this.getType()===p.CJ.ElementVideo}findPredecessor(e=!1){const t=this.getLiveTimeline().getState(o.q.FORWARDS);return t?t.findPredecessor(e):null}roomNameGenerator(e){if(this.client.roomNameGenerator){const t=this.client.roomNameGenerator(this.roomId,e);if(null!==t)return t}switch(e.type){case L.Actual:return e.name;case L.Generated:return"Inviting"===e.subtype?`Inviting ${N(e.names,e.count)}`:N(e.names,e.count);case L.EmptyRoom:return e.oldName?`Empty room (was ${e.oldName})`:"Empty room"}}calculateRoomName(e,t=!1){if(!t){const e=this.currentState.getStateEvents(p.Bx.RoomName,"");if(null!=e&&e.getContent().name)return this.roomNameGenerator({type:L.Actual,name:e.getContent().name})}const i=this.getCanonicalAlias();if(i)return this.roomNameGenerator({type:L.Actual,name:i});let s=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1;const n=this.getFunctionalMembers();let r=[];if(this.heroes)this.heroes.forEach(e=>{if(n.includes(e.userId))s--;else if(e.displayName)r.push(e.displayName);else{const t=this.getMember(e.userId);r.push(t?t.name:e.userId)}});else{let t=this.currentState.getMembers().filter(t=>t.userId!==e&&(t.membership===C.O.Invite||t.membership===C.O.Join));t=t.filter(({userId:e})=>!n.includes(e)||(s--,!1));const i=new Intl.Collator;t.sort((e,t)=>i.compare(e.userId,t.userId)),t=t.slice(0,5),r=t.map(e=>e.name)}if(s)return this.roomNameGenerator({type:L.Generated,names:r,count:s});if(this.getMyMembership()==C.O.Join){const e=this.currentState.getStateEvents(p.Bx.RoomThirdPartyInvite);if(null!=e&&e.length){const t=e.map(e=>e.getContent().display_name);return this.roomNameGenerator({type:L.Generated,subtype:"Inviting",names:t,count:t.length+1})}}let o,a=r;return a.length||(a=this.currentState.getMembers().filter(t=>t.userId!==e&&t.membership!==C.O.Invite&&t.membership!==C.O.Join).map(e=>e.name)),a.length&&(o=this.roomNameGenerator({type:L.Generated,names:a,count:a.length+1})),this.roomNameGenerator({type:L.EmptyRoom,oldName:o})}applyNewVisibilityEvent(e){const t=e.asVisibilityChange();if(!t)return;const i=e.getSender();if(!i)return;if(!(p.Yg.name&&this.currentState.maySendStateEvent(p.Yg.name,i)||p.Yg.altName&&this.currentState.maySendStateEvent(p.Yg.altName,i)))return;const s=this.visibilityEvents.get(t.eventId);if(s){let t=s.length-1;const i=Math.max(0,s.length-30);for(;t>=i;--t){if(s[t].getTs()<e.getTs())break}-1===t?s.unshift(e):s.splice(t+1,0,e)}else this.visibilityEvents.set(t.eventId,[e]);const n=this.findEventById(t.eventId);n&&n.applyVisibilityEvent(t)}redactVisibilityChangeEvent(e){if(!e.isVisibilityEvent)throw new Error("expected a visibility change event");const t=e.getRelation(),i=null==t?void 0:t.event_id,s=this.visibilityEvents.get(i);if(!s)return;const n=s.findIndex(t=>t.getId()===e.getId());if(-1!==n&&(s.splice(n,1),n===s.length)){const e=this.findEventById(i);if(!e)return;if(0===n)this.visibilityEvents.delete(i),e.applyVisibilityEvent();else{const t=s[s.length-1].asVisibilityChange();if(!t)throw new Error("at this stage, visibility changes should be well-formed");e.applyVisibilityEvent(t)}}}applyPendingVisibilityEvents(e){const t=this.visibilityEvents.get(e.getId());if(!t||0==t.length)return;const i=t[t.length-1],s=i.asVisibilityChange();s&&(s.visible,i.getTs()<e.getTs()||e.applyVisibilityEvent(s))}getOldestThreadedReceiptTs(){return this.oldestThreadedReceiptTs}hasUserReadEvent(e,t){return this.roomReceipts.hasUserReadEvent(e,t)}getLastUnthreadedReceiptFor(e){return this.unthreadedReceipts.get(e)}fixupNotifications(e){super.fixupNotifications(e);const t=this.getThreads().filter(e=>this.getThreadUnreadNotificationCount(e.id,O.Total)>0);for(const i of t)i.fixupNotifications(e)}compareEventOrdering(e,t){return(0,w.s)(this,e,t)}hasEncryptionStateEvent(){var e;return Boolean(null===(e=this.getLiveTimeline().getState(o.q.FORWARDS))||void 0===e?void 0:e.getStateEvents(p.Bx.RoomEncryption,""))}}const U={[c.f.ENCRYPTING]:[c.f.SENDING,c.f.NOT_SENT,c.f.CANCELLED],[c.f.SENDING]:[c.f.ENCRYPTING,c.f.QUEUED,c.f.NOT_SENT,c.f.SENT],[c.f.QUEUED]:[c.f.SENDING,c.f.NOT_SENT,c.f.CANCELLED],[c.f.SENT]:[],[c.f.NOT_SENT]:[c.f.SENDING,c.f.QUEUED,c.f.CANCELLED],[c.f.CANCELLED]:[]};let L=function(e){return e[e.EmptyRoom=0]="EmptyRoom",e[e.Generated=1]="Generated",e[e.Actual=2]="Actual",e}({});function N(e,t){const i=t-1;if(e.length){if(1===e.length&&i<=1)return e[0];if(2===e.length&&i<=2)return`${e[0]} and ${e[1]}`;return i>1?`${e[0]} and ${i} others`:`${e[0]} and 1 other`}return"Empty room"}},"./node_modules/matrix-js-sdk/src/models/search-result.ts":(e,t,i)=>{"use strict";i.d(t,{q:()=>n});var s=i("./node_modules/matrix-js-sdk/src/models/event-context.ts");class n{static fromJson(e,t){const i=e.context||{};let r=(i.events_before||[]).map(t),o=(i.events_after||[]).map(t);const a=new s.y(t(e.result)),d=a.ourEvent.threadRootId;return r=r.filter(e=>e.threadRootId===d),o=o.filter(e=>e.threadRootId===d),a.setPaginateToken(i.start,!0),a.addEvents(r,!0),a.addEvents(o,!1),a.setPaginateToken(i.end,!1),new n(e.rank,a)}constructor(e,t){this.rank=e,this.context=t}}},"./node_modules/matrix-js-sdk/src/models/thread.ts":(e,t,i)=>{"use strict";i.d(t,{FD:()=>I,H:()=>T,RN:()=>_,UR:()=>C,c1:()=>S,jV:()=>E,ju:()=>y,o1:()=>b,x3:()=>w});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/client.ts"),r=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),o=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),a=i("./node_modules/matrix-js-sdk/src/models/event.ts"),d=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),l=i("./node_modules/matrix-js-sdk/src/models/event-timeline-set.ts"),c=i("./node_modules/matrix-js-sdk/src/models/room.ts"),h=i("./node_modules/matrix-js-sdk/src/NamespacedValue.ts"),u=i("./node_modules/matrix-js-sdk/src/logger.ts"),m=i("./node_modules/matrix-js-sdk/src/models/read-receipt.ts"),v=i("./node_modules/matrix-js-sdk/src/@types/read_receipts.ts"),p=i("./node_modules/matrix-js-sdk/src/feature.ts");function g(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function f(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?g(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):g(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let y=function(e){return e.New="Thread.new",e.Update="Thread.update",e.NewReply="Thread.newReply",e.ViewThread="Thread.viewThread",e.Delete="Thread.delete",e}({}),S=function(e){return e[e.None=0]="None",e[e.Experimental=1]="Experimental",e[e.Stable=2]="Stable",e}({});function I(e,t){return e?S.Stable:t?S.Experimental:S.None}class E extends m.h{constructor(e,t,i){var o;if(super(),(0,s.A)(this,"timelineSet",void 0),(0,s.A)(this,"_currentUserParticipated",!1),(0,s.A)(this,"reEmitter",void 0),(0,s.A)(this,"lastEvent",void 0),(0,s.A)(this,"replyCount",0),(0,s.A)(this,"lastPendingEvent",void 0),(0,s.A)(this,"pendingReplyCount",0),(0,s.A)(this,"room",void 0),(0,s.A)(this,"client",void 0),(0,s.A)(this,"pendingEventOrdering",void 0),(0,s.A)(this,"processRootEventPromise",void 0),(0,s.A)(this,"initialEventsFetched",!E.hasServerSideSupport),(0,s.A)(this,"initalEventFetchProm",void 0),(0,s.A)(this,"replayEvents",[]),(0,s.A)(this,"onTimelineReset",async()=>{await this.processRootEventPromise,this.processRootEventPromise=void 0}),(0,s.A)(this,"onBeforeRedaction",(e,t)=>{null!=e&&e.isRelation(_.name)&&this.room.eventShouldLiveIn(e).threadId===this.id&&e.getId()!==this.id&&!t.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(y.Update,this))}),(0,s.A)(this,"onRedaction",async(e,t,i)=>{if(i===this.id)if(this.replyCount<=0){for(const e of this.timeline)this.clearEventMetadata(e);this.lastEvent=this.rootEvent,this._currentUserParticipated=!1,this.emit(y.Delete,this)}else{var s;(null===(s=this.lastEvent)||void 0===s?void 0:s.getId())===e.getAssociatedId()&&(await this.processRootEventPromise,this.processRootEventPromise=void 0),await this.updateThreadMetadata()}}),(0,s.A)(this,"onTimelineEvent",(e,t,i)=>{if(!i){const i=e.getSender();i&&t&&this.shouldSendLocalEchoReceipt(i,e)&&t.addLocalEchoReceipt(i,e,v.L.Read),e.getId()!==this.id&&e.isRelation(_.name)&&this.replyCount++}this.onEcho(e,null!=i&&i)}),(0,s.A)(this,"onLocalEcho",e=>{this.onEcho(e,!1)}),(0,s.A)(this,"onEcho",async(e,t)=>{e.threadRootId===this.id&&this.lastEvent!==e&&(await this.updateThreadMetadata(),e.isRelation(_.name)&&(t||(this.lastEvent=void 0,this.emit(y.NewReply,this,e))))}),this.id=e,this.rootEvent=t,this.setMaxListeners(1e3),null==i||!i.room)throw new Error("element-web#22141: A thread requires a room in order to function");this.room=i.room,this.client=i.client,this.pendingEventOrdering=null!==(o=i.pendingEventOrdering)&&void 0!==o?o:n.eO.Chronological,this.timelineSet=new l.m(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new r.Q(this),this.reEmitter.reEmit(this.timelineSet,[c.u9.Timeline,c.u9.TimelineReset]),this.room.on(a.OQ.BeforeRedaction,this.onBeforeRedaction),this.room.on(c.u9.Redaction,this.onRedaction),this.room.on(c.u9.LocalEchoUpdated,this.onLocalEcho),this.room.on(c.u9.TimelineReset,this.onTimelineReset),this.timelineSet.on(c.u9.Timeline,this.onTimelineEvent),this.processReceipts(i.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){u.vF.error("Failed to fetch thread root to construct thread with",e)}await this.processEvent(this.rootEvent)}static setServerSideSupport(e){E.hasServerSideSupport=e,e!==S.Stable&&(b.setPreferUnstable(!0),T.setPreferUnstable(!0),_.setPreferUnstable(!0))}static setServerSideListSupport(e){E.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){E.hasServerSideFwdPaginationSupport=e}shouldSendLocalEchoReceipt(e,t){var i;if((null!==(i=this.client.canSupport.get(p.Xj.RelationsRecursion))&&void 0!==i?i:p.Tj.Unsupported)===p.Tj.Unsupported){var s;const i=null===(s=this.getReadReceiptForUserId(e))||void 0===s?void 0:s.eventId;if(i){const e=this.findEventById(i);if(e&&e.getTs()>t.getTs())return!1}}return!0}get roomState(){return this.room.getLiveTimeline().getState(d.q.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(e=>this.addEvent(e,t,!1)),this.updateThreadMetadata()}addEvent(e,t,i=!0){this.setEventMetadata(e);const s=this.lastReply(),n=!s||e.localTimestamp>=s.localTimestamp;if(E.hasServerSideSupport){if(e.isRelation(o.zZ.Annotation)||e.isRelation(o.zZ.Replace))return void this.addRelatedThreadEvent(e,t);!t&&n?(this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e)):t?this.addEventToTimeline(e,t):this.insertEventIntoTimeline(e)}else this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e);e.getId()!==this.id&&e.isRelation(_.name)&&!t&&n&&(this.lastEvent=void 0),i&&(this.emit(y.NewReply,this,e),this.updateThreadMetadata())}addRelatedThreadEvent(e,t){if(this.initialEventsFetched){var i;(null!==(i=this.client.canSupport.get(p.Xj.RelationsRecursion))&&void 0!==i?i:p.Tj.Unsupported)===p.Tj.Unsupported?this.insertEventIntoTimeline(e):this.addEventToTimeline(e,t)}else{var s,n;if(null===(s=this.replayEvents)||void 0===s||s.push(e),e.isRelation(o.zZ.Annotation))null===(n=this.timelineSet.relations)||void 0===n||n.aggregateChildEvent(e,this.timelineSet)}}async processEvent(e){e&&(this.setEventMetadata(e),await this.fetchEditsWhereNeeded(e))}processReceipts(e=[]){for(const{eventId:t,receiptType:i,userId:s,receipt:n,synthetic:r}of e)this.addReceiptToStructure(t,i,s,n,r)}getRootEventBundledRelationship(e=this.rootEvent){return null==e?void 0:e.getServerAggregatedRelation(_.name)}async processRootEvent(){const e=this.getRootEventBundledRelationship();if(E.hasServerSideSupport&&e){this.replyCount=e.count,this._currentUserParticipated=!!e.current_user_participated;const t=this.client.getEventMapper();this.lastEvent=t(f(f({},e.latest_event),{},{room_id:this.roomId})),this.updatePendingReplyCount(),await this.processEvent(this.lastEvent)}}updatePendingReplyCount(){const e=(this.pendingEventOrdering===n.eO.Detached?this.room.getPendingEvents():this.events).filter(e=>{var t;return e.threadRootId===this.id&&e.isRelation(_.name)&&null!==e.status&&e.getId()!==(null===(t=this.lastEvent)||void 0===t?void 0:t.getId())});this.lastPendingEvent=e.length?e[e.length-1]:void 0,this.pendingReplyCount=e.length}async resetLiveTimeline(e,t){const i=this.liveTimeline;this.timelineSet.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);const s=this.liveTimeline;let n,r;if(e){n=(await this.client.createMessagesRequest(this.roomId,e,1,d.O.Forward)).end}if(t){r=(await this.client.createMessagesRequest(this.roomId,t,1,d.O.Backward)).start}t&&i.getPaginationToken(d.O.Forward)===t&&i.setPaginationToken(null!=r?r:null,d.O.Forward),e&&s.getPaginationToken(d.O.Backward)===e&&s.setPaginationToken(null!=n?n:null,d.O.Backward)}async updateThreadFromRootEvent(){E.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(),0===this.replyCount&&this.rootEvent?(this.timelineSet.addEventsToTimeline([this.rootEvent],!0,!1,this.liveTimeline,null),this.liveTimeline.setPaginationToken(null,d.O.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(c.u9.TimelineReset,this.room,this.timelineSet,!0)}catch(e){u.vF.error("Failed to load start of newly created thread: ",e),this.initialEventsFetched=!1}this.emit(y.Update,this)}async fetchEditsWhereNeeded(...e){var t;if((null!==(t=this.client.canSupport.get(p.Xj.RelationsRecursion))&&void 0!==t?t:p.Tj.Unsupported)===p.Tj.Unsupported)return Promise.all(e.filter(R).map(async e=>{try{const t=await this.client.relations(this.roomId,e.getId(),o.zZ.Replace,e.getType(),{limit:1});if(t.events.length){const i=t.events[0];e.makeReplaced(i),this.insertEventIntoTimeline(i)}}catch(e){u.vF.error("Failed to load edits for encrypted thread event",e)}}))}setEventMetadata(e){e&&(d.q.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){var t;e&&(e.setThread(void 0),null===(t=e.event)||void 0===t||null===(t=t.unsigned)||void 0===t||null===(t=t["m.relations"])||void 0===t||delete t[_.name])}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(e=e=>e.isRelation(_.name)){for(let t=this.timeline.length-1;t>=0;t--){const i=this.timeline[t];if(e(i))return i}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,t;return null!==(e=null!==(t=this.lastPendingEvent)&&void 0!==t?t:this.lastEvent)&&void 0!==e?e:this.lastReply()}get timeline(){return this.events}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof a.kl}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){const i=e===this.client.getUserId(),s=this.timeline[this.timeline.length-1];if(i&&s){const e=s.getTs()<this.room.getOldestThreadedReceiptTs(),t=s.getId();if(e&&t)return t}const n=super.getEventReadUpTo(e,t);if(s){const t=this.room.getLastUnthreadedReceiptFor(e);if(!t)return n;for(let e=(null===(r=this.timeline)||void 0===r?void 0:r.length)-1;e>=0;--e){var r,o;const i=this.timeline[e];if(i.getId()===n)return n;if(i.getTs()<t.ts)return null!==(o=i.getId())&&void 0!==o?o:n}}return n}hasUserReadEvent(e,t){if(e===this.client.getUserId()){var i,s,n,r,o,a;const t=(null!==(i=null===(s=this.lastReply())||void 0===s?void 0:s.getTs())&&void 0!==i?i:0)<this.room.getOldestThreadedReceiptTs(),d=null!==(n=null===(r=this.room.getLastUnthreadedReceiptFor(e))||void 0===r?void 0:r.ts)&&void 0!==n?n:0,l=(null!==(o=null==this||null===(a=this.lastReply())||void 0===a?void 0:a.getTs())&&void 0!==o?o:0)<d;if(t||l)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)}}function R(e){return e.isEncrypted()&&(e.isRelation(_.name)||e.isThreadRoot)}(0,s.A)(E,"hasServerSideSupport",S.None),(0,s.A)(E,"hasServerSideListSupport",S.None),(0,s.A)(E,"hasServerSideFwdPaginationSupport",S.None);const b=new h.M6("related_by_senders","io.element.relation_senders"),T=new h.M6("related_by_rel_types","io.element.relation_types"),_=new h.M6("m.thread","io.element.thread");let w=function(e){return e[e.My=0]="My",e[e.All=1]="All",e}({});function C(e){return e===w.My?"participated":"all"}},"./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts":(e,t,i)=>{"use strict";i.d(t,{X:()=>r,u:()=>n});var s=i("./node_modules/events/events.js");let n=function(e){return e.NewListener="newListener",e.RemoveListener="removeListener",e.Error="error",e}({});class r extends s.EventEmitter{addListener(e,t){return super.addListener(e,t)}emit(e,...t){return super.emit(e,...t)}async emitPromised(e,...t){const i=this.listeners(e);return Promise.allSettled(i.map(e=>e(...t))).then(()=>i.length>0)}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}off(e,t){return super.off(e,t)}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}prependListener(e,t){return super.prependListener(e,t)}prependOnceListener(e,t){return super.prependOnceListener(e,t)}removeAllListeners(e){return void 0===e?super.removeAllListeners():super.removeAllListeners(e)}removeListener(e,t){return super.removeListener(e,t)}rawListeners(e){return super.rawListeners(e)}}},"./node_modules/matrix-js-sdk/src/models/user.ts":(e,t,i)=>{"use strict";i.d(t,{K:()=>o,U:()=>r});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts");let r=function(e){return e.DisplayName="User.displayName",e.AvatarUrl="User.avatarUrl",e.Presence="User.presence",e.CurrentlyActive="User.currentlyActive",e.LastPresenceTs="User.lastPresenceTs",e}({});class o extends n.X{constructor(e){super(),(0,s.A)(this,"modified",-1),(0,s.A)(this,"displayName",void 0),(0,s.A)(this,"rawDisplayName",void 0),(0,s.A)(this,"avatarUrl",void 0),(0,s.A)(this,"presenceStatusMsg",void 0),(0,s.A)(this,"presence","offline"),(0,s.A)(this,"lastActiveAgo",0),(0,s.A)(this,"lastPresenceTs",0),(0,s.A)(this,"currentlyActive",!1),(0,s.A)(this,"events",{}),this.userId=e,this.displayName=e,this.rawDisplayName=e,this.updateModifiedTime()}static createUser(e,t){const i=new o(e);return t.reEmitter.reEmit(i,[r.AvatarUrl,r.DisplayName,r.Presence,r.CurrentlyActive,r.LastPresenceTs]),i}setPresenceEvent(e){if("m.presence"!==e.getType())return;const t=null===this.events.presence;this.events.presence=e;const i=[];(e.getContent().presence!==this.presence||t)&&i.push(r.Presence),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&i.push(r.AvatarUrl),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&i.push(r.DisplayName),void 0!==e.getContent().currently_active&&e.getContent().currently_active!==this.currentlyActive&&i.push(r.CurrentlyActive),this.presence=e.getContent().presence,i.push(r.LastPresenceTs),e.getContent().status_msg&&(this.presenceStatusMsg=e.getContent().status_msg),e.getContent().displayname&&(this.displayName=e.getContent().displayname),e.getContent().avatar_url&&(this.avatarUrl=e.getContent().avatar_url),this.lastActiveAgo=e.getContent().last_active_ago,this.lastPresenceTs=Date.now(),this.currentlyActive=e.getContent().currently_active,this.updateModifiedTime();for(const t of i)this.emit(t,e,this)}setDisplayName(e){const t=this.displayName;this.displayName=e,e!==t&&this.updateModifiedTime()}setRawDisplayName(e){this.rawDisplayName=e}setAvatarUrl(e){const t=this.avatarUrl;this.avatarUrl=e,e!==t&&this.updateModifiedTime()}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getLastActiveTs(){return this.lastPresenceTs-this.lastActiveAgo}}},"./node_modules/matrix-js-sdk/src/oidc/authorize.ts":(e,t,i)=>{"use strict";i("./node_modules/oidc-client-ts/dist/umd/oidc-client-ts.js"),i("./node_modules/matrix-js-sdk/src/logger.ts"),i("./node_modules/matrix-js-sdk/src/oidc/error.ts"),i("./node_modules/matrix-js-sdk/src/oidc/validate.ts")},"./node_modules/matrix-js-sdk/src/oidc/index.ts":(e,t,i)=>{"use strict";i.d(t,{k8:()=>s.k,Pl:()=>s.P});i("./node_modules/matrix-js-sdk/src/oidc/authorize.ts");var s=i("./node_modules/matrix-js-sdk/src/oidc/discovery.ts");i("./node_modules/matrix-js-sdk/src/oidc/error.ts"),i("./node_modules/matrix-js-sdk/src/http-api/index.ts"),i("./node_modules/matrix-js-sdk/src/logger.ts");i("./node_modules/oidc-client-ts/dist/umd/oidc-client-ts.js");i("./node_modules/matrix-js-sdk/src/oidc/validate.ts")},"./node_modules/matrix-js-sdk/src/oidc/validate.ts":(e,t,i)=>{"use strict";i.d(t,{EZ:()=>h});class s extends Error{}s.prototype.name="InvalidTokenError";var n=i("./node_modules/matrix-js-sdk/src/logger.ts"),r=i("./node_modules/matrix-js-sdk/src/oidc/error.ts");const o=e=>!!e&&"object"==typeof e&&!Array.isArray(e),a=(e,t)=>!(!e[t]||!d(e,t))||(n.vF.error(`Missing or invalid property: ${t}`),!1),d=(e,t)=>!e[t]||"string"==typeof e[t]||(n.vF.error(`Invalid property: ${t}`),!1),l=(e,t)=>!!(!e[t]||Array.isArray(e[t])&&e[t].every(e=>"string"==typeof e))||(n.vF.error(`Invalid property: ${t}`),!1),c=(e,t,i)=>{const s=e[t];return!!(s&&Array.isArray(s)&&s.includes(i))||(n.vF.error(`Invalid property: ${t}. ${i} is required.`),!1)},h=e=>{if(!o(e))throw n.vF.error("Issuer configuration not found or malformed"),new Error(r.u.OpSupport);if(![a(e,"issuer"),a(e,"authorization_endpoint"),a(e,"token_endpoint"),a(e,"revocation_endpoint"),d(e,"registration_endpoint"),d(e,"account_management_uri"),d(e,"device_authorization_endpoint"),l(e,"account_management_actions_supported"),c(e,"response_types_supported","code"),c(e,"grant_types_supported","authorization_code"),c(e,"code_challenge_methods_supported","S256"),l(e,"prompt_values_supported")].some(e=>!e))return e;throw n.vF.error("Issuer configuration not valid"),new Error(r.u.OpSupport)}},"./node_modules/matrix-js-sdk/src/randomstring.ts":(e,t,i)=>{"use strict";i.d(t,{US:()=>d,rl:()=>a});var s=i("./node_modules/matrix-js-sdk/src/base64.ts");const n="abcdefghijklmnopqrstuvwxyz",r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",o="0123456789";function a(e){const t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),(0,s.A4)(t)}function d(e){return function(e,t){if(t.length<2||t.length>256)throw new Error("Character set must be between 2 and 256 characters long");if(e<1||e>32768)throw new Error("Requested random string length must be between 1 and 32768");const i=256-256%t.length,s=new Uint8Array(Math.floor(1.3*e));let n=s.length;const r=[];for(;r.length<e;){n===s.length&&(globalThis.crypto.getRandomValues(s),n=0);const e=s[n++];e<i&&r.push(t[e%t.length])}return r.join("")}(e,r+n+o)}},"./node_modules/matrix-js-sdk/src/secret-storage.ts":(e,t,i)=>{"use strict";i.d(t,{SECRET_STORAGE_ALGORITHM_V1_AES:()=>d,ServerSideSecretStorageImpl:()=>l});var s=i("./node_modules/matrix-js-sdk/src/client.ts"),n=i("./node_modules/matrix-js-sdk/src/randomstring.ts"),r=i("./node_modules/matrix-js-sdk/src/logger.ts"),o=i("./node_modules/matrix-js-sdk/src/utils/encryptAESSecretStorageItem.ts"),a=i("./node_modules/matrix-js-sdk/src/utils/decryptAESSecretStorageItem.ts");const d="m.secret_storage.v1.aes-hmac-sha2";class l{constructor(e,t){this.accountDataAdapter=e,this.callbacks=t}async getDefaultKeyId(){var e;const t=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return t&&null!==(e=t.key)&&void 0!==e?e:null}setDefaultKeyId(e){return new Promise((t,i)=>{const n=i=>{if("m.secret_storage.default_key"!==i.getType())return;const r=i.getContent();(null===e?0===Object.keys(r).length:r.key===e)&&(this.accountDataAdapter.removeListener(s.AU.AccountData,n),t())};this.accountDataAdapter.on(s.AU.AccountData,n);const r=null===e?{}:{key:e};this.accountDataAdapter.setAccountData("m.secret_storage.default_key",r).catch(e=>{this.accountDataAdapter.removeListener(s.AU.AccountData,n),i(e)})})}async addKey(e,t,i){if(e!==d)throw new Error(`Unknown key algorithm ${e}`);const s={algorithm:e};t.name&&(s.name=t.name),t.passphrase&&(s.passphrase=t.passphrase);const{iv:r,mac:o}=await u(t.key);if(s.iv=r,s.mac=o,!i)do{i=(0,n.US)(32)}while(await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${i}`));return await this.accountDataAdapter.setAccountData(`m.secret_storage.key.${i}`,s),{keyId:i,keyInfo:s}}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){const t=await this.getKey(e);return Boolean(t)}async checkKey(e,t){if(t.algorithm===d){if(t.mac){const{mac:i}=await u(e,t.iv);return c(t.mac)===c(i)}return!0}throw new Error("Unknown algorithm")}async store(e,t,i){if(null===t)return void await this.accountDataAdapter.setAccountData(e,{});const s={};if(!i){const e=await this.getDefaultKeyId();if(!e)throw new Error("No keys specified and no default key present");i=[e]}if(0===i.length)throw new Error("Zero keys given to encrypt with!");for(const n of i){const i=await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${n}`);if(!i)throw new Error("Unknown key: "+n);if(i.algorithm===d){const r={[n]:i},[,o]=await this.getSecretStorageKey(r,e);s[n]=await o.encrypt(t)}else r.vF.warn("unknown algorithm for secret storage key "+n+": "+i.algorithm)}await this.accountDataAdapter.setAccountData(e,{encrypted:s})}async get(e){const t=await this.accountDataAdapter.getAccountDataFromServer(e);if(!t)return;if(!t.encrypted)throw new Error("Content is not encrypted!");const i={};for(const e of Object.keys(t.encrypted)){const s=await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${e}`),n=t.encrypted[e];(null==s?void 0:s.algorithm)===d&&n.iv&&n.ciphertext&&n.mac&&(i[e]=s)}if(0===Object.keys(i).length)throw new Error(`Could not decrypt ${e} because none of the keys it is encrypted with are for a supported algorithm`);const[s,n]=await this.getSecretStorageKey(i,e),r=t.encrypted[s];return n.decrypt(r)}async isStored(e){const t=await this.accountDataAdapter.getAccountDataFromServer(e);if(null==t||!t.encrypted)return null;const i={};for(const e of Object.keys(t.encrypted)){const s=await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${e}`);if(!s)continue;const n=t.encrypted[e];s.algorithm===d&&n.iv&&n.ciphertext&&n.mac&&(i[e]=s)}return Object.keys(i).length?i:null}async getSecretStorageKey(e,t){if(!this.callbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");const i=await this.callbacks.getSecretStorageKey({keys:e},t);if(!i)throw new Error("getSecretStorageKey callback returned falsey");if(i.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[s,n]=i;if(!e[s])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[s].algorithm===d){return[s,{encrypt:function(e){return(0,o.A)(e,n,t)},decrypt:function(e){return(0,a.A)(e,n,t)}}]}throw new Error("Unknown key type: "+e[s].algorithm)}}function c(e){let t=e.length;for(;t>=1&&61==e.charCodeAt(t-1);)t--;return t<e.length?e.substring(0,t):e}const h="\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 u(e,t){return(0,o.A)(h,e,"",t)}},"./node_modules/matrix-js-sdk/src/serverCapabilities.ts":(e,t,i)=>{"use strict";i.d(t,{K:()=>o,L:()=>r});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/http-api/index.ts");let r=function(e){return e.Stable="stable",e.Unstable="unstable",e}({});class o{constructor(e,t){(0,s.A)(this,"capabilities",void 0),(0,s.A)(this,"retryTimeout",void 0),(0,s.A)(this,"refreshTimeout",void 0),(0,s.A)(this,"fetchCapabilities",async()=>{const e=await this.http.authedRequest(n.IT.Get,"/capabilities");return this.capabilities=e.capabilities,this.capabilities}),(0,s.A)(this,"poll",async()=>{try{await this.fetchCapabilities(),this.clearTimeouts(),this.refreshTimeout=setTimeout(this.poll,216e5),this.logger.debug("Fetched new server capabilities")}catch(e){this.clearTimeouts();const t=Math.floor(3e4+5e3*Math.random());this.retryTimeout=setTimeout(this.poll,t),this.logger.warn(`Failed to refresh capabilities: retrying in ${t}ms`,e)}}),this.logger=e,this.http=t}start(){this.poll().then()}stop(){this.clearTimeouts()}getCachedCapabilities(){return this.capabilities}clearTimeouts(){this.refreshTimeout&&(clearInterval(this.refreshTimeout),this.refreshTimeout=void 0),this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=void 0)}}},"./node_modules/matrix-js-sdk/src/service-types.ts":(e,t,i)=>{"use strict";i.d(t,{S:()=>s});let s=function(e){return e.IS="SERVICE_TYPE_IS",e.IM="SERVICE_TYPE_IM",e}({})},"./node_modules/matrix-js-sdk/src/sliding-sync.ts":(e,t,i)=>{"use strict";i.d(t,{HY:()=>r,cQ:()=>o,ns:()=>n});i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),i("./node_modules/matrix-js-sdk/src/logger.ts");var s=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts");i("./node_modules/matrix-js-sdk/src/utils.ts");let n=function(e){return e.RequestFinished="FINISHED",e.Complete="COMPLETE",e}({});let r=function(e){return e.PreProcess="ExtState.PreProcess",e.PostProcess="ExtState.PostProcess",e}({}),o=function(e){return e.RoomData="SlidingSync.RoomData",e.Lifecycle="SlidingSync.Lifecycle",e}({});s.X},"./node_modules/matrix-js-sdk/src/sync-accumulator.ts":(e,t,i)=>{"use strict";i.d(t,{w:()=>h});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/logger.ts"),r=i("./node_modules/matrix-js-sdk/src/utils.ts"),o=i("./node_modules/matrix-js-sdk/src/models/event.ts"),a=i("./node_modules/matrix-js-sdk/src/@types/sync.ts"),d=i("./node_modules/matrix-js-sdk/src/@types/event.ts");class l{constructor(){(0,s.A)(this,"unthreadedReadReceipts",new Map),(0,s.A)(this,"threadedReadReceipts",new r.kG(()=>new Map))}setUnthreaded(e,t){this.unthreadedReadReceipts.set(e,t)}setThreaded(e,t,i){this.threadedReadReceipts.getOrCreate(e).set(t,i)}allUnthreaded(){return this.unthreadedReadReceipts.entries()}*allThreaded(){for(const e of this.threadedReadReceipts.values())for(const t of e.entries())yield t}consumeEphemeralEvents(e){null==e||e.forEach(e=>{e.type===d.Bx.Receipt&&e.content&&Object.keys(e.content).forEach(t=>{Object.entries(e.content[t]).forEach(([i,s])=>{if((0,r.ll)(i))for(const n of Object.keys(s)){const s=e.content[t][i][n],r={data:e.content[t][i][n],type:i,eventId:t};s.thread_id?this.setThreaded(s.thread_id,n,r):this.setUnthreaded(n,r)}})})})}buildAccumulatedReceiptEvent(e){const t={type:d.Bx.Receipt,room_id:e,content:{}},i=new r.kG(()=>new r.kG(()=>new Map));for(const[e,t]of this.allUnthreaded())i.getOrCreate(t.eventId).getOrCreate(t.type).set(e,t.data);for(const[e,t]of this.allThreaded())i.getOrCreate(t.eventId).getOrCreate(t.type).set(e,t.data);return t.content=(0,r.HF)(i),i.size>0?t:null}}let c=function(e){return e.Invite="invite",e.Leave="leave",e.Join="join",e.Knock="knock",e}({});class h{constructor(e={}){(0,s.A)(this,"accountData",{}),(0,s.A)(this,"inviteRooms",{}),(0,s.A)(this,"knockRooms",{}),(0,s.A)(this,"joinRooms",{}),(0,s.A)(this,"nextBatch",null),this.opts=e,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(e=>{this.accountData[e.type]=e})}accumulateRooms(e,t=!1){e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach(i=>{this.accumulateRoom(i,c.Invite,e.rooms.invite[i],t)}),e.rooms.join&&Object.keys(e.rooms.join).forEach(i=>{this.accumulateRoom(i,c.Join,e.rooms.join[i],t)}),e.rooms.leave&&Object.keys(e.rooms.leave).forEach(i=>{this.accumulateRoom(i,c.Leave,e.rooms.leave[i],t)}),e.rooms.knock&&Object.keys(e.rooms.knock).forEach(i=>{this.accumulateRoom(i,c.Knock,e.rooms.knock[i],t)}))}accumulateRoom(e,t,i,s=!1){switch(t){case c.Invite:this.knockRooms[e]&&delete this.knockRooms[e],this.accumulateInviteState(e,i);break;case c.Knock:this.accumulateKnockState(e,i);break;case c.Join:this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,i,s);break;case c.Leave:this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:n.vF.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!t.invite_state||!t.invite_state.events)return;if(!this.inviteRooms[e])return void(this.inviteRooms[e]={invite_state:t.invite_state});const i=this.inviteRooms[e];t.invite_state.events.forEach(e=>{let t=!1;for(let s=0;s<i.invite_state.events.length;s++){const n=i.invite_state.events[s];n.type===e.type&&n.state_key==e.state_key&&(i.invite_state.events[s]=e,t=!0)}t||i.invite_state.events.push(e)})}accumulateKnockState(e,t){if(!t.knock_state||!t.knock_state.events)return;if(!this.knockRooms[e])return void(this.knockRooms[e]={knock_state:t.knock_state});const i=this.knockRooms[e];t.knock_state.events.forEach(e=>{let t=!1;for(let s=0;s<i.knock_state.events.length;s++){const n=i.knock_state.events[s];n.type===e.type&&n.state_key==e.state_key&&(i.knock_state.events[s]=e,t=!0)}t||i.knock_state.events.push(e)})}accumulateJoinState(e,t,i=!1){var s,n,r,d,c,h,m;const v=Date.now();this.joinRooms[e]||(this.joinRooms[e]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_unreadThreadNotifications:{},_summary:{},_receipts:new l,_stickyEvents:[]});const p=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach(e=>{p._accountData[e.type]=e}),t.unread_notifications&&(p._unreadNotifications=t.unread_notifications),p._unreadThreadNotifications=null!==(s=null!==(n=t[a.a.stable])&&void 0!==n?n:t[a.a.unstable])&&void 0!==s?s:void 0,t.summary){var g,f,y;const e="m.heroes",i="m.invited_member_count",s="m.joined_member_count",n=p._summary,r=t.summary;n[e]=null!==(g=r[e])&&void 0!==g?g:n[e],n[s]=null!==(f=r[s])&&void 0!==f?f:n[s],n[i]=null!==(y=r[i])&&void 0!==y?y:n[i]}if(p._receipts.consumeEphemeralEvents(null===(r=t.ephemeral)||void 0===r?void 0:r.events),t.timeline&&t.timeline.limited&&(p._timeline=[]),null===(d=t.state)||void 0===d||null===(d=d.events)||void 0===d||d.forEach(e=>{u(p._currentState,e)}),null===(c=t["org.matrix.msc4222.state_after"])||void 0===c||null===(c=c.events)||void 0===c||c.forEach(e=>{u(p._currentState,e)}),null===(h=t.timeline)||void 0===h||null===(h=h.events)||void 0===h||h.forEach((e,s)=>{var n;let r;if(t["org.matrix.msc4222.state_after"]||u(p._currentState,e),i)r=e;else{var o;r=Object.assign({},e),void 0!==r.unsigned&&(r.unsigned=Object.assign({},r.unsigned));const t=null===(o=e.unsigned)||void 0===o?void 0:o.age;void 0!==t&&(r._localTs=Date.now()-t)}p._timeline.push({event:r,token:0===s&&null!==(n=t.timeline.prev_batch)&&void 0!==n?n:null})}),p._stickyEvents=p._stickyEvents.filter(({expiresTs:e})=>e>v),null!==(m=t.msc4354_sticky)&&void 0!==m&&m.events&&(p._stickyEvents=p._stickyEvents.concat(t.msc4354_sticky.events.map(e=>({event:e,expiresTs:Math.min(e.msc4354_sticky.duration_ms,o.P0)+Math.min(e.origin_server_ts,v)})))),p._timeline.length>this.opts.maxTimelineEntries){for(let e=p._timeline.length-this.opts.maxTimelineEntries;e<p._timeline.length;e++)if(p._timeline[e].token){p._timeline=p._timeline.slice(e,p._timeline.length);break}}}getJSON(e=!1){const t={join:{},invite:{},knock:{},leave:{}};Object.keys(this.inviteRooms).forEach(e=>{t.invite[e]=this.inviteRooms[e]}),Object.keys(this.knockRooms).forEach(e=>{t.knock[e]=this.knockRooms[e]}),Object.keys(this.joinRooms).forEach(i=>{var s;const n=this.joinRooms[i],o={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},"org.matrix.msc4222.state_after":{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:n._unreadNotifications,unread_thread_notifications:n._unreadThreadNotifications,summary:n._summary,msc4354_sticky:null!==(s=n._stickyEvents)&&void 0!==s&&s.length?{events:n._stickyEvents.map(e=>e.event)}:void 0};Object.keys(n._accountData).forEach(e=>{o.account_data.events.push(n._accountData[e])});const a=n._receipts.buildAccumulatedReceiptEvent(i);a&&o.ephemeral.events.push(a),n._timeline.forEach(t=>{if(!o.timeline.prev_batch){if(!t.token)return;o.timeline.prev_batch=t.token}let i;var s;!e&&("_localTs"in(s=t.event)&&void 0!==s._localTs)?(i=Object.assign({},t.event),void 0!==i.unsigned&&(i.unsigned=Object.assign({},i.unsigned)),delete i._localTs,i.unsigned=i.unsigned||{},i.unsigned.age=Date.now()-t.event._localTs):i=t.event,o.timeline.events.push(i)});const d=Object.create(null);for(let e=o.timeline.events.length-1;e>=0;e--){const t=o.timeline.events[e];if(null===t.state_key||void 0===t.state_key)continue;const i=(0,r.A4)(t);i.unsigned&&(i.unsigned.prev_content&&(i.content=i.unsigned.prev_content),i.unsigned.prev_sender&&(i.sender=i.unsigned.prev_sender)),u(d,i)}Object.keys(n._currentState).forEach(e=>{Object.keys(n._currentState[e]).forEach(t=>{let i=n._currentState[e][t];o["org.matrix.msc4222.state_after"].events.push(i),d[e]&&d[e][t]&&(i=d[e][t]),o.state.events.push(i)})}),t.join[i]=o});const i=[];return Object.keys(this.accountData).forEach(e=>{i.push(this.accountData[e])}),{nextBatch:this.nextBatch,roomsData:t,accountData:i}}getNextBatchToken(){return this.nextBatch}}function u(e,t){null!==t.state_key&&void 0!==t.state_key&&t.type&&(e[t.type]||(e[t.type]=Object.create(null)),e[t.type][t.state_key]=t)}},"./node_modules/matrix-js-sdk/src/sync.ts":(e,t,i)=>{"use strict";i.d(t,{Bn:()=>_,Fe:()=>w,Lm:()=>E,M:()=>k,pq:()=>A,w_:()=>C});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/user.ts"),r=i("./node_modules/matrix-js-sdk/src/models/room.ts"),o=i("./node_modules/matrix-js-sdk/src/utils.ts"),a=i("./node_modules/matrix-js-sdk/src/filter.ts"),d=i("./node_modules/matrix-js-sdk/src/models/event-timeline.ts"),l=i("./node_modules/matrix-js-sdk/src/client.ts"),c=i("./node_modules/matrix-js-sdk/src/models/event.ts"),h=i("./node_modules/matrix-js-sdk/src/http-api/index.ts"),u=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),m=i("./node_modules/matrix-js-sdk/src/models/room-state.ts"),v=i("./node_modules/matrix-js-sdk/src/models/room-member.ts"),p=i("./node_modules/matrix-js-sdk/src/models/beacon.ts"),g=i("./node_modules/matrix-js-sdk/src/@types/sync.ts"),f=i("./node_modules/matrix-js-sdk/src/feature.ts"),y=i("./node_modules/matrix-js-sdk/src/@types/membership.ts");function S(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function I(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?S(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):S(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let E=function(e){return e.Error="ERROR",e.Prepared="PREPARED",e.Stopped="STOPPED",e.Syncing="SYNCING",e.Catchup="CATCHUP",e.Reconnecting="RECONNECTING",e}({});const R=["org.matrix.msc2716v3"];function b(e,t){return`FILTER_SYNC_${e}`+(t?"_"+t:"")}let T=function(e){return e.Offline="offline",e.Online="online",e.Unavailable="unavailable",e}({});function _(e){return I({initialSyncLimit:8,resolveInvitesToProfiles:!1,pollTimeout:3e4,pendingEventOrdering:l.eO.Chronological,threadSupport:!1},e)}function w(e){return I({canResetEntireTimeline:e=>!1},e)}class C{constructor(e,t,i){(0,s.A)(this,"opts",void 0),(0,s.A)(this,"syncOpts",void 0),(0,s.A)(this,"_peekRoom",null),(0,s.A)(this,"currentSyncRequest",void 0),(0,s.A)(this,"abortController",void 0),(0,s.A)(this,"syncState",null),(0,s.A)(this,"syncStateData",void 0),(0,s.A)(this,"catchingUp",!1),(0,s.A)(this,"running",!1),(0,s.A)(this,"keepAliveTimer",void 0),(0,s.A)(this,"connectionReturnedResolvers",void 0),(0,s.A)(this,"notifEvents",[]),(0,s.A)(this,"failedSyncCount",0),(0,s.A)(this,"storeIsInvalid",!1),(0,s.A)(this,"presence",void 0),(0,s.A)(this,"getPushRules",async()=>{try{this.syncOpts.logger.debug("Getting push rules...");const e=await this.client.getPushRules();this.syncOpts.logger.debug("Got push rules"),this.client.pushRules=e}catch(e){if(this.syncOpts.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return;return this.syncOpts.logger.debug("Waiting for saved sync before retrying push rules..."),await this.recoverFromSyncStartupError(this.savedSyncPromise,e),this.getPushRules()}}),(0,s.A)(this,"buildDefaultFilter",()=>{const e=new a.d(this.client.credentials.userId);return this.client.canSupport.get(f.Xj.ThreadUnreadNotifications)!==f.Tj.Unsupported&&e.setUnreadThreadNotifications(!0),e}),(0,s.A)(this,"prepareLazyLoadingForSync",async()=>{this.syncOpts.logger.debug("Prepare lazy loading for sync..."),this.client.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers&&(this.syncOpts.logger.debug("Enabling lazy load on sync filter..."),this.opts.filter||(this.opts.filter=this.buildDefaultFilter()),this.opts.filter.setLazyLoadMembers(!0))}),(0,s.A)(this,"storeClientOptions",async()=>{try{this.syncOpts.logger.debug("Storing client options..."),await this.client.storeClientOptions(),this.syncOpts.logger.debug("Stored client options")}catch(e){throw this.syncOpts.logger.error("Storing client options failed",e),e}}),(0,s.A)(this,"getFilter",async()=>{let e,t;this.syncOpts.logger.debug("Getting filter..."),e=this.opts.filter?this.opts.filter:this.buildDefaultFilter();try{t=await this.client.getOrCreateFilter(b(this.client.credentials.userId),e)}catch(e){return this.syncOpts.logger.error("Getting filter failed",e),this.shouldAbortSync(e)?{}:(this.syncOpts.logger.debug("Waiting for saved sync before retrying filter..."),await this.recoverFromSyncStartupError(this.savedSyncPromise,e),this.getFilter())}return{filter:e,filterId:t}}),(0,s.A)(this,"savedSyncPromise",void 0),(0,s.A)(this,"onOnline",()=>{this.syncOpts.logger.debug("Browser thinks we are back online"),this.startKeepAlives(0)}),this.client=e,this.opts=_(t),this.syncOpts=w(i),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),[r.u9.Timeline,r.u9.TimelineReset])}createRoom(e){const t=k(this.client,e,this.opts);return t.on(m.f.Marker,(e,i)=>{this.onMarkerStateEvent(t,e,i)}),t}onMarkerStateEvent(e,t,{timelineWasEmpty:i}={}){if(i)return void this.syncOpts.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because the timeline was empty before the marker arrived which means there is nothing to refresh.`);R.includes(e.getVersion())||t.getSender()===e.getCreator()?(this.syncOpts.logger.debug(`MarkerState: Timeline needs to be refreshed because a new markerEventId=${t.getId()} was sent in roomId=${e.roomId}`),e.setTimelineNeedsRefresh(!0),e.emit(r.u9.HistoryImportedWithinTimeline,t,e)):this.syncOpts.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.`)}async syncLeftRooms(){var e;const t=this.client,i=new a.d(this.client.credentials.userId);i.setTimelineLimit(1),i.setIncludeLeaveRooms(!0);const s=this.opts.pollTimeout+8e4,n={timeout:0,filter:await t.getOrCreateFilter(b(t.credentials.userId,"LEFT_ROOMS"),i),"org.matrix.msc4222.use_state_after":!0},r=await t.http.authedRequest(h.IT.Get,"/sync",n,void 0,{localTimeoutMs:s});let o=[];null!==(e=r.rooms)&&void 0!==e&&e.leave&&(o=this.mapSyncResponseToRoomArray(r.rooms.leave));return(await Promise.all(o.map(async e=>{const i=e.room;if(!e.isBrandNewRoom)return;e.timeline=e.timeline||{prev_batch:null,events:[]},i.getLiveTimeline().setPaginationToken(e.timeline.prev_batch,d.q.BACKWARDS);const{timelineEvents:s}=await this.mapAndInjectRoomEvents(e);return i.recalculate(),t.store.storeRoom(i),t.emit(l.AU.Room,i),this.processEventsForNotifs(i,s),i}))).filter(Boolean)}peek(e,t=20){var i;if((null===(i=this._peekRoom)||void 0===i?void 0:i.roomId)===e)return Promise.resolve(this._peekRoom);const s=this.client;return this._peekRoom=this.createRoom(e),this.client.roomInitialSync(e,t).then(t=>{var i;if((null===(i=this._peekRoom)||void 0===i?void 0:i.roomId)!==e)throw new Error("Peeking aborted");t.messages=t.messages||{chunk:[]},t.messages.chunk=t.messages.chunk||[],t.state=t.state||[];const r=(0,o.A4)(t.state).map(s.getEventMapper()),a=t.state.map(s.getEventMapper()),d=t.messages.chunk.map(s.getEventMapper());return Array.isArray(t.presence)&&t.presence.map(s.getEventMapper()).forEach(function(e){let t=s.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=n.K.createUser(e.getContent().user_id,s),t.setPresenceEvent(e),s.store.storeUser(t)),s.emit(l.AU.Event,e)}),t.messages.start&&(this._peekRoom.oldState.paginationToken=t.messages.start),this._peekRoom.oldState.setStateEvents(r),this._peekRoom.currentState.setStateEvents(a),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(d.reverse(),!0,!0,this._peekRoom.getLiveTimeline(),t.messages.start),s.store.storeRoom(this._peekRoom),s.emit(l.AU.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom})}stopPeeking(){this._peekRoom=null}peekPoll(e,t){var i;this._peekRoom===e?this.client.http.authedRequest(h.IT.Get,"/events",{room_id:e.roomId,timeout:String(3e4),from:t},void 0,{localTimeoutMs:5e4,abortSignal:null===(i=this.abortController)||void 0===i?void 0:i.signal}).then(async t=>{if(this._peekRoom!==e)return void this.syncOpts.logger.debug("Stopped peeking in room %s",e.roomId);t.chunk.filter(function(e){return"m.presence"===e.type}).map(this.client.getEventMapper()).forEach(e=>{let t=this.client.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=n.K.createUser(e.getContent().user_id,this.client),t.setPresenceEvent(e),this.client.store.storeUser(t)),this.client.emit(l.AU.Event,e)});const i=t.chunk.filter(function(t){return t.room_id===e.roomId&&t.event_id}).map(this.client.getEventMapper());await e.addLiveEvents(i,{addToState:!0}),this.peekPoll(e,t.end)},i=>{this.syncOpts.logger.error("[%s] Peek poll failed: %s",e.roomId,i),setTimeout(()=>{this.peekPoll(e,t)},3e4)}):this.syncOpts.logger.debug("Stopped peeking in room %s",e.roomId)}getSyncState(){return this.syncState}getSyncStateData(){var e;return null!==(e=this.syncStateData)&&void 0!==e?e:null}async recoverFromSyncStartupError(e,t){await e;const i=this.startKeepAlives();this.updateSyncState(E.Error,{error:t}),await i}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(this.syncOpts.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(E.Error,{error:e}),!0)}async sync(){var e,t;if(this.running=!0,this.abortController=new AbortController,null===(e=globalThis.window)||void 0===e||null===(t=e.addEventListener)||void 0===t||t.call(e,"online",this.onOnline,!1),this.client.isGuest())return this.doSync({});this.syncOpts.logger.debug("Getting saved sync token...");const i=this.client.store.getSavedSyncToken().then(e=>(this.syncOpts.logger.debug("Got saved sync token"),e));this.savedSyncPromise=this.client.store.getSavedSync().then(e=>{if(this.syncOpts.logger.debug(`Got reply from saved sync, exists? ${!!e}`),e)return this.syncFromCache(e)}).catch(e=>{this.syncOpts.logger.error("Getting saved sync failed",e)}),await this.getPushRules(),await this.prepareLazyLoadingForSync(),await this.storeClientOptions();const{filterId:s,filter:n}=await this.getFilter();if(n){if(this.client.resetNotifTimelineSet(),!this.currentSyncRequest){let e=s;const t=await i;if(t)this.syncOpts.logger.debug("Sending first sync request...");else{this.syncOpts.logger.debug("Sending initial sync request...");const t=this.buildDefaultFilter();t.setDefinition(n.getDefinition()),t.setTimelineLimit(this.opts.initialSyncLimit),e=JSON.stringify(t.getDefinition())}this.currentSyncRequest=this.doSyncRequest({filter:e},t)}return this.syncOpts.logger.debug("Waiting for saved sync before starting sync processing..."),await this.savedSyncPromise,this.doSync({filter:s})}}stop(){var e,t,i;this.syncOpts.logger.debug("SyncApi.stop"),null===(e=globalThis.window)||void 0===e||null===(t=e.removeEventListener)||void 0===t||t.call(e,"online",this.onOnline,!1),this.running=!1,null===(i=this.abortController)||void 0===i||i.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=void 0)}retryImmediately(){return!!this.connectionReturnedResolvers&&(this.startKeepAlives(0),!0)}async syncFromCache(e){this.syncOpts.logger.debug("sync(): not doing HTTP hit, instead returning stored /sync data");const t=e.nextBatch;this.client.store.setSyncToken(t);const i={nextSyncToken:t,catchingUp:!1,fromCache:!0},s={next_batch:t,rooms:e.roomsData,account_data:{events:e.accountData}};try{await this.processSyncResponse(i,s)}catch(e){this.syncOpts.logger.error("Error processing cached sync",e)}this.storeIsInvalid||this.updateSyncState(E.Prepared,i)}async doSync(e){for(;this.running;){const t=this.client.store.getSyncToken();let i;try{this.currentSyncRequest||(this.currentSyncRequest=this.doSyncRequest(e,t)),i=await this.currentSyncRequest}catch(e){if(await this.onSyncError(e))return;continue}finally{this.currentSyncRequest=void 0}this.client.store.setSyncToken(i.next_batch),this.failedSyncCount=0;const s={oldSyncToken:null!=t?t:void 0,nextSyncToken:i.next_batch,catchingUp:this.catchingUp};try{await this.processSyncResponse(s,i)}catch(e){this.syncOpts.logger.error("Caught /sync error",e),this.client.emit(l.AU.SyncUnexpectedError,e)}await this.client.store.setSyncData(i),s.catchingUp=this.catchingUp,e.hasSyncedBefore||(this.updateSyncState(E.Prepared,s),e.hasSyncedBefore=!0),this.syncOpts.cryptoCallbacks&&await this.syncOpts.cryptoCallbacks.onSyncCompleted(s),this.updateSyncState(E.Syncing,s),this.client.store.wantsSave()&&await this.client.store.save()}this.running||(this.syncOpts.logger.debug("Sync no longer running: exiting."),this.connectionReturnedResolvers&&(this.connectionReturnedResolvers.reject(),this.connectionReturnedResolvers=void 0),this.updateSyncState(E.Stopped))}doSyncRequest(e,t){var i;const s=this.getSyncParams(e,t);return this.client.http.authedRequest(h.IT.Get,"/sync",s,void 0,{localTimeoutMs:s.timeout+8e4,abortSignal:null===(i=this.abortController)||void 0===i?void 0:i.signal})}getSyncParams(e,t){let i=this.opts.pollTimeout;(this.getSyncState()!==E.Syncing||this.catchingUp)&&(this.catchingUp=!0,i=0);let s=e.filter;this.client.isGuest()&&!s&&(s=this.getGuestFilter());const n={filter:s,timeout:i,"org.matrix.msc4222.use_state_after":!0};return this.opts.disablePresence?n.set_presence=T.Offline:void 0!==this.presence&&(n.set_presence=this.presence),t?n.since=t:n._cacheBuster=Date.now(),[E.Reconnecting,E.Error].includes(this.getSyncState())&&(n.timeout=0),n}setPresence(e){this.presence=e}async onSyncError(e){if(!this.running)return this.syncOpts.logger.debug("Sync no longer running: exiting"),this.connectionReturnedResolvers&&(this.connectionReturnedResolvers.reject(),this.connectionReturnedResolvers=void 0),this.updateSyncState(E.Stopped),!0;if(this.syncOpts.logger.error("/sync error %s",e),this.shouldAbortSync(e))return!0;this.failedSyncCount++,this.syncOpts.logger.debug("Number of consecutive failed sync requests:",this.failedSyncCount),this.syncOpts.logger.debug("Starting keep-alive");const t=this.startKeepAlives();this.currentSyncRequest=void 0,this.updateSyncState(this.failedSyncCount>=3?E.Error:E.Reconnecting,{error:e});return await t&&this.getSyncState()===E.Error&&this.updateSyncState(E.Catchup,{catchingUp:!0}),!1}async processSyncResponse(e,t){var i,s,a,c;const h=this.client;if(Array.isArray(null===(i=t.presence)||void 0===i?void 0:i.events)&&t.presence.events.filter(o.O5).map(h.getEventMapper()).forEach(function(e){let t=h.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=n.K.createUser(e.getSender(),h),t.setPresenceEvent(e),h.store.storeUser(t)),h.emit(l.AU.Event,e)}),Array.isArray(null===(s=t.account_data)||void 0===s?void 0:s.events)){const e=t.account_data.events.filter(o.O5).map(h.getEventMapper()),i=e.reduce((e,t)=>(e[t.getType()]=h.store.getAccountData(t.getType()),e),{});h.store.storeAccountDataEvents(e),e.forEach(function(e){if(e.getType()===u.Bx.PushRules){const t=e.getContent();h.setPushRules(t)}const t=i[e.getType()];return h.emit(l.AU.AccountData,e,t),e})}if(t.to_device&&Array.isArray(t.to_device.events)&&t.to_device.events.length>0){const e=t.to_device.events.filter(o.O5);let i;i=this.syncOpts.cryptoCallbacks?await this.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(e):e.map(e=>({message:e,encryptionInfo:null})),A(i,h)}else this.catchingUp=!1;let m=[],v=[],p=[],f=[];t.rooms&&(t.rooms.invite&&(m=this.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(v=this.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(p=this.mapSyncResponseToRoomArray(t.rooms.leave)),t.rooms.knock&&(f=this.mapSyncResponseToRoomArray(t.rooms.knock))),this.notifEvents=[],await(0,o.d8)(m,async e=>{const t=e.room,i=this.mapSyncEventsFormat(e.invite_state,t);await this.injectRoomEvents(t,i,void 0),e.isBrandNewRoom?(t.recalculate(),h.store.storeRoom(t),h.emit(l.AU.Room,t)):t.recalculate(),i.forEach(function(e){h.emit(l.AU.Event,e)})}),await(0,o.d8)(v,async t=>{var i;const s=t.room,n=this.mapSyncEventsFormat(t.state,s),o=this.mapSyncEventsFormat(t["org.matrix.msc4222.state_after"],s),a=this.mapSyncEventsFormat(t.timeline,s,!1),c=this.mapSyncEventsFormat(t.ephemeral),m=this.mapSyncEventsFormat(t.account_data),v=this.mapSyncEventsFormat(t.msc4354_sticky),p=t["org.matrix.msc4222.state_after"]?o:n.concat(a),f=this.isRoomEncrypted(s,p);if(t.unread_notifications){var y,S;if(!f||0===t.unread_notifications.notification_count)s.setUnreadNotificationCount(r.X5.Total,null!==(y=t.unread_notifications.notification_count)&&void 0!==y?y:0);if(!f||s.getUnreadNotificationCount(r.X5.Highlight)<=0)s.setUnreadNotificationCount(r.X5.Highlight,null!==(S=t.unread_notifications.highlight_count)&&void 0!==S?S:0)}const I=null!==(i=t[g.a.name])&&void 0!==i?i:t[g.a.altName];if(I){s.resetThreadUnreadNotificationCountFromSync(Object.keys(I));for(const[e,t]of Object.entries(I)){var E;if(!f||0===t.notification_count)s.setThreadUnreadNotificationCount(e,r.X5.Total,null!==(E=t.notification_count)&&void 0!==E?E:0);const i=s.getThreadUnreadNotificationCount(e,r.X5.Highlight)<=0;var R;if(!f||f&&i)s.setThreadUnreadNotificationCount(e,r.X5.Highlight,null!==(R=t.highlight_count)&&void 0!==R?R:0)}}else s.resetThreadUnreadNotificationCountFromSync();if(t.timeline=t.timeline||{},t.isBrandNewRoom)null!==t.timeline.prev_batch&&s.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,d.q.BACKWARDS);else if(t.timeline.limited){let i=!0;for(let e=a.length-1;e>=0;e--){const t=a[e].getId();if(s.getTimelineForEvent(t)){this.syncOpts.logger.debug(`Already have event ${t} in limited sync - not resetting`),i=!1,a.splice(0,e);break}}var b;if(i)s.resetLiveTimeline(t.timeline.prev_batch,this.syncOpts.canResetEntireTimeline(s.roomId)?null:null!==(b=e.oldSyncToken)&&void 0!==b?b:null),h.resetNotifTimelineSet()}if(this.syncOpts.cryptoCallbacks)for(const e of p)e.isState()&&e.getType()===u.Bx.RoomEncryption&&""===e.getStateKey()&&await this.syncOpts.cryptoCallbacks.onCryptoEvent(s,e);for(const e of a.filter(e=>e.isState()))await this.client.decryptEventIfNeeded(e);try{"org.matrix.msc4222.state_after"in t?await this.injectRoomEvents(s,void 0,o,a,e.fromCache):await this.injectRoomEvents(s,n,void 0,a,e.fromCache)}catch(e){this.syncOpts.logger.error(`Failed to process events on room ${s.roomId}:`,e)}t.summary&&s.setSummary(t.summary),s.addEphemeralEvents(c),s.addAccountData(m);const T=v.concat(a.filter(e=>void 0!==e.unstableStickyInfo));s._unstable_addStickyEvents(T),s.recalculate(),t.isBrandNewRoom&&(h.store.storeRoom(s),h.emit(l.AU.Room,s)),this.processEventsForNotifs(s,a);const _=e=>h.emit(l.AU.Event,e);n.forEach(_),a.forEach(_),c.forEach(_),m.forEach(_),v.filter(e=>!a.some(t=>t.getId()===e.getId())).forEach(_),s.decryptCriticalEvents()}),await(0,o.d8)(p,async e=>{const t=e.room,{timelineEvents:i,stateEvents:s,stateAfterEvents:n}=await this.mapAndInjectRoomEvents(e),r=this.mapSyncEventsFormat(e.account_data);t.addAccountData(r),t.recalculate(),e.isBrandNewRoom&&(h.store.storeRoom(t),h.emit(l.AU.Room,t)),this.processEventsForNotifs(t,i),null==s||s.forEach(function(e){h.emit(l.AU.Event,e)}),null==n||n.forEach(function(e){h.emit(l.AU.Event,e)}),i.forEach(function(e){h.emit(l.AU.Event,e)}),r.forEach(function(e){h.emit(l.AU.Event,e)})}),await(0,o.d8)(f,async e=>{const t=e.room,i=this.mapSyncEventsFormat(e.knock_state,t);await this.injectRoomEvents(t,i,void 0),e.isBrandNewRoom?(t.recalculate(),h.store.storeRoom(t),h.emit(l.AU.Room,t)):t.recalculate(),i.forEach(function(e){h.emit(l.AU.Event,e)})}),e.oldSyncToken&&this.notifEvents.length&&(this.notifEvents.sort(function(e,t){return e.getTs()-t.getTs()}),this.notifEvents.forEach(function(e){var t;null===(t=h.getNotifTimelineSet())||void 0===t||t.addLiveEvent(e,{addToState:!0})})),t.device_lists&&this.syncOpts.cryptoCallbacks&&await this.syncOpts.cryptoCallbacks.processDeviceLists(t.device_lists),await(null===(a=this.syncOpts.cryptoCallbacks)||void 0===a?void 0:a.processKeyCounts(t.device_one_time_keys_count,null!==(c=t.device_unused_fallback_key_types)&&void 0!==c?c:t["org.matrix.msc2732.device_unused_fallback_key_types"]))}startKeepAlives(e){return void 0===e&&(e=2e3+Math.floor(5e3*Math.random())),null!==this.keepAliveTimer&&clearTimeout(this.keepAliveTimer),e>0?this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this),e):this.pokeKeepAlive(),this.connectionReturnedResolvers||(this.connectionReturnedResolvers=Promise.withResolvers()),this.connectionReturnedResolvers.promise}pokeKeepAlive(e=!1){var t;if(!this.running)return clearTimeout(this.keepAliveTimer),void(this.connectionReturnedResolvers&&(this.connectionReturnedResolvers.reject("SyncApi.stop() was called"),this.connectionReturnedResolvers=void 0));const i=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedResolvers&&(this.connectionReturnedResolvers.resolve(e),this.connectionReturnedResolvers=void 0)};this.client.http.request(h.IT.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3,abortSignal:null===(t=this.abortController)||void 0===t?void 0:t.signal}).then(()=>{i()},t=>{400==t.httpStatus||404==t.httpStatus?this.keepAliveTimer=setTimeout(i,2e3):(e=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,e),5e3+Math.floor(5e3*Math.random())),this.updateSyncState(E.Error,{error:t}))})}mapSyncResponseToRoomArray(e){const t=this.client;return Object.keys(e).filter(e=>!(0,o.YY)(e)).map(i=>{let s=t.store.getRoom(i),n=!1;return s||(s=this.createRoom(i),n=!0),I(I({},e[i]),{},{room:s,isBrandNewRoom:n})})}mapSyncEventsFormat(e,t,i=!0){if(!e||!Array.isArray(e.events))return[];const s=this.client.getEventMapper({decrypt:i});return e.events.filter(o.O5).map(function(e){return t&&(e.room_id=t.roomId),s(e)})}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership(y.O.Invite).forEach(function(i){if(i.requestedProfileInfo)return;i.requestedProfileInfo=!0;const s=t.getUser(i.userId);let n;n=s?Promise.resolve({avatar_url:s.avatarUrl,displayname:s.displayName}):t.getProfileInfo(i.userId),n.then(function(t){const s=i.events.member;(null==s?void 0:s.getContent().membership)===y.O.Invite&&(s.getContent().avatar_url=t.avatar_url,s.getContent().displayname=t.displayname,i.setMembershipEvent(s,e.currentState))},function(e){})})}findEncryptionEvent(e){return null==e?void 0:e.find(e=>e.getType()===u.Bx.RoomEncryption&&""===e.getStateKey())}isRoomEncrypted(e,t){return e.hasEncryptionStateEvent()||!!this.findEncryptionEvent(t)}async mapAndInjectRoomEvents(e){const t=this.mapSyncEventsFormat(e.state,e.room),i=this.mapSyncEventsFormat(e["org.matrix.msc4222.state_after"],e.room),s=this.mapSyncEventsFormat(e.timeline,e.room);return"org.matrix.msc4222.state_after"in e?await this.injectRoomEvents(e.room,void 0,i,s):await this.injectRoomEvents(e.room,t,void 0,s),{timelineEvents:s,stateEvents:t,stateAfterEvents:i}}async injectRoomEvents(e,t,i,s,n=!1){const r=null!=i?i:t,o=e.getLiveTimeline(),a=0==o.getEvents().length;if(a){for(const e of r)this.client.getPushActionsForEvent(e);o.initialiseState(r,{timelineWasEmpty:a})}this.resolveInvites(e),e.recalculate(),a||(e.oldState.setStateEvents(r),e.currentState.setStateEvents(r)),await e.addLiveEvents(s||[],{fromCache:n,timelineWasEmpty:a,addToState:void 0===i}),this.client.processBeaconEvents(e,s)}processEventsForNotifs(e,t){if(this.client.getNotifTimelineSet())for(const e of t){var i;const t=this.client.getPushActionsForEvent(e);null!=t&&t.notify&&null!==(i=t.tweaks)&&void 0!==i&&i.highlight&&this.notifEvents.push(e)}}getGuestFilter(){return"{}"}updateSyncState(e,t){const i=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(l.AU.Sync,this.syncState,i,t)}}function k(e,t,i){const{timelineSupport:s}=e,n=new r.Wv(t,e,e.getUserId(),{lazyLoadMembers:i.lazyLoadMembers,pendingEventOrdering:i.pendingEventOrdering,timelineSupport:s});return e.reEmitter.reEmit(n,[r.u9.Name,r.u9.Redaction,r.u9.RedactionCancelled,r.u9.Receipt,r.u9.Tags,r.u9.LocalEchoUpdated,r.u9.AccountData,r.u9.MyMembership,r.u9.Timeline,r.u9.TimelineReset,m.f.Events,m.f.Members,m.f.NewMember,m.f.Update,p.JH.New,p.JH.Update,p.JH.Destroy,p.JH.LivenessChange]),n.on(m.f.NewMember,(t,i,s)=>{var n;s.user=null!==(n=e.getUser(s.userId))&&void 0!==n?n:void 0,e.reEmitter.reEmit(s,[v.o5.Name,v.o5.Typing,v.o5.PowerLevel,v.o5.Membership])}),n}function A(e,t){const i=[];e.map(e=>{if("m.key.verification.cancel"===e.message.type){const t=e.message.content.transaction_id;t&&i.push(t)}return e}).forEach(function(e){{const s=e.message,n=s.content,r=new c.kl(Object.assign({},s));if("m.key.verification.start"===s.type||"m.key.verification.request"===s.type){const e=n.transaction_id;i.includes(e)&&r.flagCancelled()}e.encryptionInfo&&r.makeEncrypted(u.Bx.RoomMessageEncrypted,{ciphertext:""},e.encryptionInfo.senderCurve25519KeyBase64,""),t.emit(l.AU.ToDeviceEvent,r)}t.emit(l.AU.ReceivedToDeviceMessage,e)})}},"./node_modules/matrix-js-sdk/src/utils.ts":(e,t,i)=>{"use strict";i.d(t,{$9:()=>B,A4:()=>y,Ab:()=>v,Bi:()=>G,C6:()=>X,CC:()=>D,Et:()=>E,Fq:()=>K,G$:()=>x,Gp:()=>R,HF:()=>Y,Mf:()=>U,NQ:()=>M,Nt:()=>w,Nz:()=>g,O5:()=>Z,RR:()=>p,S8:()=>T,UB:()=>f,YY:()=>Q,aw:()=>V,d7:()=>b,d8:()=>O,dn:()=>C,hX:()=>F,hc:()=>k,hl:()=>I,hm:()=>m,j0:()=>P,kG:()=>ee,kg:()=>J,ky:()=>S,ll:()=>W,sy:()=>$,yD:()=>u,yy:()=>A,zR:()=>q});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/unhomoglyph/index.js"),r=i.n(n),o=i("./node_modules/p-retry/index.js"),a=i("./node_modules/matrix-js-sdk/src/@types/location.ts"),d=i("./node_modules/matrix-js-sdk/src/@types/read_receipts.ts");function l(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function c(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?l(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):l(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}const h=new Map;function u(e){return e instanceof String&&(e=e.toString()),h.has(e)||h.set(e,e),h.get(e)}function m(e,t){const i=null!=t?t:new URLSearchParams;for(const[t,s]of Object.entries(e))null!=s&&(Array.isArray(s)?s.forEach(e=>{i.append(t,String(e))}):i.append(t,String(s)));return i}function v(e,t,i){const s=c(c({},i),{},{[t]:i[e]});return delete s[e],s}function p(e,t){for(const i in t){if(!t.hasOwnProperty(i))continue;const s=t[i];null!=s&&(e=e.replace(i,encodeURIComponent(s)))}return e}function g(e,t,i){let s;if(i){for(s=e.length-1;s>=0;s--)if(t(e[s],s,e))return e.splice(s,1),!0}else for(s=0;s<e.length;s++)if(t(e[s],s,e))return e.splice(s,1),!0;return!1}function f(e,t){for(const i of t)if(!e.hasOwnProperty(i))throw new Error("Missing required key: "+i)}function y(e){return JSON.parse(JSON.stringify(e))}function S(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("number"==typeof e&&isNaN(e)&&isNaN(t))return!0;if(null===e||null===t)return e===t;if(!(e instanceof Object))return!1;if(e.constructor!==t.constructor||e.prototype!==t.prototype)return!1;if(e instanceof RegExp||e instanceof Date)return e.toString()===t.toString();if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!S(e[i],t[i]))return!1}else{for(const i in t)if(t.hasOwnProperty(i)!==e.hasOwnProperty(i))return!1;for(const i in e)if(t.hasOwnProperty(i)!==e.hasOwnProperty(i)||!S(e[i],t[i]))return!1}return!0}function I(e){if("object"!=typeof e)return e;if(null==e||Array.isArray(e))return e;const t=[];for(const[i,s]of Object.entries(e))t.push([i,I(s)]);return t.sort((e,t)=>V(e[0],t[0])),t}function E(e){return"number"==typeof e&&isFinite(e)}function R(e){return"string"==typeof e?r()(e.normalize("NFD").replace(_,"")):""}function b(e){return"string"==typeof e?e.replace(/[\u202d-\u202e]/g,""):""}function T(e){return R(e.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()}const _=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g;function w(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C(e){return w(e).replace(/\\\*/g,".*").replace(/\?/g,".")}function k(e){return null!=e&&e.endsWith("/")?e.slice(0,-1):e}function A(e,t){return new Promise(i=>{setTimeout(i,e,t)})}async function M(e,t,i){const s=Date.now();try{return await i()}finally{const i=Date.now();e.debug(`[Perf]: ${t} took ${i-s}ms`)}}function x(e,t,i){const s=Date.now();try{return i()}finally{const i=Date.now();e.debug(`[Perf]: ${t} took ${i-s}ms`)}}function F(e){return null==e}async function O(e,t){for(const i of e)await t(await i)}function P(e){return Promise.resolve(e())}function D(e,t){return(0,o.Ay)(t=>e(t),{retries:1/0,shouldRetry:t?({error:e})=>t(e):void 0,factor:2,minTimeout:3e3,maxTimeout:15e3})}const U=(()=>{let e="";for(let t=32;t<=126;t++)e+=String.fromCharCode(t);return e})();function L(e,t,i=U){return e.padEnd(t,i[0])}function N(e,t=U){const i=BigInt(t.length);var s;if(e<=i)return null!==(s=t[Number(e)-1])&&void 0!==s?s:"";let n=e/i,r=Number(e%i)-1;return r<0&&(n-=BigInt(Math.abs(r)),r=Number(i)-1),N(n,t)+t[r]}function j(e,t=U){const i=BigInt(t.length);let s=BigInt(0);for(let n=e.length-1,r=BigInt(0);n>=0;n--,r++){const o=e.charCodeAt(n)-t.charCodeAt(0);s+=BigInt(1+o)*i**r}return s}function $(e,t,i=U){const s=Math.max(e.length,t.length),n=j(L(e,s,i),i),r=j(L(t,s,i),i),o=(n+r)/BigInt(2);return o===n||o==r?N(o,i)+i[0]:N(o,i)}function B(e,t=U){return N(j(e,t)+BigInt(1),t)}function q(e,t=U){return N(j(e,t)-BigInt(1),t)}function V(e,t){return e<t?-1:e>t?1:0}function G(e,t,i=!1){for(const[s,n]of Object.entries(t))e[s]instanceof Object&&n?G(e[s],n):null==n&&i||X(e,s,n);return e}function H(e){var t;return null!==(t=a.vo.findIn(e.getContent()))&&void 0!==t?t:-1}function K(e,t){return H(t)-H(e)}function W(e){return[d.L.Read,d.L.ReadPrivate].includes(e)}function J(e,t,i=(e,t)=>e===t){if(e.size!==t.size)return!1;for(const[s,n]of e){const e=t.get(s);if(void 0===e||!i(n,e))return!1}return!0}function z(e){return e instanceof Map?Y(e):Array.isArray(e)?e.map(e=>z(e)):e}function Y(e){const t=new Map;for(const[i,s]of e)t.set(i,z(s));return Object.fromEntries(t.entries())}function Q(e){return"__proto__"===e||"prototype"===e||"constructor"===e}function X(e,t,i){if(Q(t))throw new Error("Trying to modify prototype or constructor");e[t]=i}function Z(e){return!(Q(e.room_id)||Q(e.sender)||Q(e.event_id))}class ee extends Map{constructor(e){super(),this.createDefault=e}getOrCreate(e){return this.has(e)||this.set(e,this.createDefault()),this.get(e)}}},"./node_modules/matrix-js-sdk/src/utils/decryptAESSecretStorageItem.ts":(e,t,i)=>{"use strict";i.d(t,{A:()=>r});var s=i("./node_modules/matrix-js-sdk/src/base64.ts"),n=i("./node_modules/matrix-js-sdk/src/utils/internal/deriveKeys.ts");async function r(e,t,i){const[r,o]=await(0,n.C)(t,i),a=(0,s.y4)(e.ciphertext);if(!await globalThis.crypto.subtle.verify({name:"HMAC"},o,(0,s.y4)(e.mac),a))throw new Error(`Error decrypting secret ${i}: bad MAC`);const d=await globalThis.crypto.subtle.decrypt({name:"AES-CTR",counter:(0,s.y4)(e.iv),length:64},r,a);return(new TextDecoder).decode(new Uint8Array(d))}},"./node_modules/matrix-js-sdk/src/version-support.ts":(e,t,i)=>{"use strict";i.d(t,{Hr:()=>s});const s=["v1.1","v1.2","v1.3","v1.4","v1.5","v1.6","v1.7","v1.8","v1.9"];s[0],s[s.length-1]},"./node_modules/matrix-js-sdk/src/webrtc/call.ts":(e,t,i)=>{"use strict";i.d(t,{$E:()=>E,Il:()=>R,QO:()=>S,RA:()=>T,WE:()=>_,iP:()=>f,ms:()=>A,sj:()=>M,sv:()=>x});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/uuid/dist/v4.js"),r=i("./node_modules/sdp-transform/lib/index.js"),o=i("./node_modules/matrix-js-sdk/src/logger.ts"),a=i("./node_modules/matrix-js-sdk/src/utils.ts"),d=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),l=i("./node_modules/matrix-js-sdk/src/randomstring.ts"),c=i("./node_modules/matrix-js-sdk/src/webrtc/callEventTypes.ts"),h=i("./node_modules/matrix-js-sdk/src/webrtc/callFeed.ts"),u=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),m=i("./node_modules/matrix-js-sdk/src/webrtc/groupCall.ts"),v=i("./node_modules/matrix-js-sdk/src/http-api/index.ts");function p(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function g(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?p(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):p(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let f=function(e){return e.Fledgling="fledgling",e.InviteSent="invite_sent",e.WaitLocalMedia="wait_local_media",e.CreateOffer="create_offer",e.CreateAnswer="create_answer",e.Connecting="connecting",e.Connected="connected",e.Ringing="ringing",e.Ended="ended",e}({}),y=function(e){return e.Voice="voice",e.Video="video",e}({}),S=function(e){return e.Inbound="inbound",e.Outbound="outbound",e}({}),I=function(e){return e.Local="local",e.Remote="remote",e}({}),E=function(e){return e.Hangup="hangup",e.State="state",e.Error="error",e.Replaced="replaced",e.LocalHoldUnhold="local_hold_unhold",e.RemoteHoldUnhold="remote_hold_unhold",e.HoldUnhold="hold_unhold",e.FeedsChanged="feeds_changed",e.AssertedIdentityChanged="asserted_identity_changed",e.LengthChanged="length_changed",e.DataChannel="datachannel",e.SendVoipEvent="send_voip_event",e.PeerConnectionCreated="peer_connection_created",e}({}),R=function(e){return e.UserHangup="user_hangup",e.LocalOfferFailed="local_offer_failed",e.NoUserMedia="no_user_media",e.UnknownDevices="unknown_devices",e.SendInvite="send_invite",e.CreateAnswer="create_answer",e.CreateOffer="create_offer",e.SendAnswer="send_answer",e.SetRemoteDescription="set_remote_description",e.SetLocalDescription="set_local_description",e.AnsweredElsewhere="answered_elsewhere",e.IceFailed="ice_failed",e.InviteTimeout="invite_timeout",e.Replaced="replaced",e.SignallingFailed="signalling_timeout",e.UserBusy="user_busy",e.Transferred="transferred",e.NewSession="new_session",e}({});const b=6e4;class T extends Error{constructor(e,t,i){super(t+": "+i),(0,s.A)(this,"code",void 0),this.code=e}}function _(){return Date.now().toString()+(0,l.US)(16)}function w(e){return[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:e?12e3:void 0}]}function C(e,t){return e+":"+t}class k extends u.X{constructor(e){var t;if(super(),(0,s.A)(this,"roomId",void 0),(0,s.A)(this,"callId",void 0),(0,s.A)(this,"invitee",void 0),(0,s.A)(this,"hangupParty",void 0),(0,s.A)(this,"hangupReason",void 0),(0,s.A)(this,"direction",void 0),(0,s.A)(this,"ourPartyId",void 0),(0,s.A)(this,"peerConn",void 0),(0,s.A)(this,"toDeviceSeq",0),(0,s.A)(this,"isPtt",!1),(0,s.A)(this,"_state",f.Fledgling),(0,s.A)(this,"client",void 0),(0,s.A)(this,"forceTURN",void 0),(0,s.A)(this,"turnServers",void 0),(0,s.A)(this,"candidateSendQueue",[]),(0,s.A)(this,"candidateSendTries",0),(0,s.A)(this,"candidatesEnded",!1),(0,s.A)(this,"feeds",[]),(0,s.A)(this,"transceivers",new Map),(0,s.A)(this,"inviteOrAnswerSent",!1),(0,s.A)(this,"waitForLocalAVStream",!1),(0,s.A)(this,"successor",void 0),(0,s.A)(this,"opponentMember",void 0),(0,s.A)(this,"opponentVersion",void 0),(0,s.A)(this,"opponentPartyId",void 0),(0,s.A)(this,"opponentCaps",void 0),(0,s.A)(this,"iceDisconnectedTimeout",void 0),(0,s.A)(this,"iceReconnectionTimeOut",void 0),(0,s.A)(this,"inviteTimeout",void 0),(0,s.A)(this,"removeTrackListeners",new Map),(0,s.A)(this,"remoteOnHold",!1),(0,s.A)(this,"callStatsAtEnd",void 0),(0,s.A)(this,"makingOffer",!1),(0,s.A)(this,"ignoreOffer",!1),(0,s.A)(this,"isSettingRemoteAnswerPending",!1),(0,s.A)(this,"responsePromiseChain",void 0),(0,s.A)(this,"remoteCandidateBuffer",new Map),(0,s.A)(this,"remoteAssertedIdentity",void 0),(0,s.A)(this,"remoteSDPStreamMetadata",void 0),(0,s.A)(this,"callLengthInterval",void 0),(0,s.A)(this,"callStartTime",void 0),(0,s.A)(this,"opponentDeviceId",void 0),(0,s.A)(this,"hasOpponentDeviceInfo",void 0),(0,s.A)(this,"opponentSessionId",void 0),(0,s.A)(this,"groupCallId",void 0),(0,s.A)(this,"stopVideoTrackTimer",void 0),(0,s.A)(this,"isOnlyDataChannelAllowed",void 0),(0,s.A)(this,"stats",void 0),(0,s.A)(this,"gotLocalIceCandidate",e=>{if(e.candidate){if(this.candidatesEnded&&o.vF.warn(`Call ${this.callId} gotLocalIceCandidate() got candidate after candidates have ended!`),o.vF.debug(`Call ${this.callId} got local ICE ${e.candidate.sdpMid} ${e.candidate.candidate}`),this.callHasEnded())return;""===e.candidate.candidate?this.queueCandidate(null):this.queueCandidate(e.candidate)}}),(0,s.A)(this,"onIceGatheringStateChange",e=>{var t;o.vF.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state changed to ${this.peerConn.iceGatheringState}`),"complete"===(null===(t=this.peerConn)||void 0===t?void 0:t.iceGatheringState)&&(this.queueCandidate(null),o.vF.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state complete, set candidates have ended`))}),(0,s.A)(this,"getLocalOfferFailed",e=>{o.vF.error(`Call ${this.callId} getLocalOfferFailed() running`,e),this.emit(E.Error,new T(R.LocalOfferFailed,"Failed to get local offer!",e),this),this.terminate(I.Local,R.LocalOfferFailed,!1)}),(0,s.A)(this,"getUserMediaFailed",e=>{this.successor?this.successor.getUserMediaFailed(e):(o.vF.warn(`Call ${this.callId} getUserMediaFailed() failed to get user media - ending call`,e),this.emit(E.Error,new T(R.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",e),this),this.terminate(I.Local,R.NoUserMedia,!1))}),(0,s.A)(this,"placeCallFailed",e=>{this.successor?this.successor.placeCallFailed(e):(o.vF.warn(`Call ${this.callId} placeCallWithCallFeeds() failed - ending call`,e),this.emit(E.Error,new T(R.IceFailed,"Couldn't start call! Invalid ICE server configuration.",e),this),this.terminate(I.Local,R.IceFailed,!1))}),(0,s.A)(this,"onIceConnectionStateChanged",()=>{var e,t,i,s,n,r;if(!this.callHasEnded()){if(o.vF.debug(`Call ${this.callId} onIceConnectionStateChanged() running (state=${null===(e=this.peerConn)||void 0===e?void 0:e.iceConnectionState}, conn=${null===(t=this.peerConn)||void 0===t?void 0:t.connectionState})`),["connected","completed"].includes(null!==(i=null===(s=this.peerConn)||void 0===s?void 0:s.iceConnectionState)&&void 0!==i?i:""))clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.iceReconnectionTimeOut&&clearTimeout(this.iceReconnectionTimeOut),this.state=f.Connected,this.callLengthInterval||this.callStartTime||(this.callStartTime=Date.now(),this.callLengthInterval=setInterval(()=>{this.emit(E.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3),this)},1e3));else if("failed"==(null===(n=this.peerConn)||void 0===n?void 0:n.iceConnectionState)){var a,d;if(this.candidatesEnded=!1,null!==(a=this.peerConn)&&void 0!==a&&a.restartIce)this.candidatesEnded=!1,o.vF.debug(`Call ${this.callId} onIceConnectionStateChanged() ice restart (state=${null===(d=this.peerConn)||void 0===d?void 0:d.iceConnectionState})`),this.peerConn.restartIce();else o.vF.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)`),this.hangup(R.IceFailed,!1)}else"disconnected"==(null===(r=this.peerConn)||void 0===r?void 0:r.iceConnectionState)&&(this.candidatesEnded=!1,this.iceReconnectionTimeOut=setTimeout(()=>{var e,t,i;o.vF.info(`Call ${this.callId} onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=${null===(e=this.peerConn)||void 0===e?void 0:e.iceConnectionState}, conn=${null===(t=this.peerConn)||void 0===t?void 0:t.connectionState})`),null!==(i=this.peerConn)&&void 0!==i&&i.restartIce&&(this.candidatesEnded=!1,this.peerConn.restartIce()),this.iceReconnectionTimeOut=void 0},2e3),this.iceDisconnectedTimeout=setTimeout(()=>{o.vF.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)`),this.hangup(R.IceFailed,!1)},3e4),this.state=f.Connecting);if(this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState))for(const e of this.getRemoteFeeds())e.setAudioVideoMuted(!0,!0)}}),(0,s.A)(this,"onSignallingStateChanged",()=>{var e;o.vF.debug(`Call ${this.callId} onSignallingStateChanged() running (state=${null===(e=this.peerConn)||void 0===e?void 0:e.signalingState})`)}),(0,s.A)(this,"onTrack",e=>{if(0===e.streams.length)return void o.vF.warn(`Call ${this.callId} onTrack() called with streamless track streamless (kind=${e.track.kind})`);const t=e.streams[0];if(this.pushRemoteFeed(t),!this.removeTrackListeners.has(t)){const e=()=>{0===t.getTracks().length&&(o.vF.info(`Call ${this.callId} onTrack() removing track (streamId=${t.id})`),this.deleteFeedByStream(t),t.removeEventListener("removetrack",e),this.removeTrackListeners.delete(t))};t.addEventListener("removetrack",e),this.removeTrackListeners.set(t,e)}}),(0,s.A)(this,"onDataChannel",e=>{this.emit(E.DataChannel,e.channel,this)}),(0,s.A)(this,"onNegotiationNeeded",async()=>{o.vF.info(`Call ${this.callId} onNegotiationNeeded() negotiation is needed!`),this.state===f.CreateOffer||0!==this.opponentVersion?this.queueGotLocalOffer():o.vF.info(`Call ${this.callId} onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event`)}),(0,s.A)(this,"onHangupReceived",e=>{o.vF.debug(`Call ${this.callId} onHangupReceived() running`),this.partyIdMatches(e)||this.state===f.Ringing?this.terminate(I.Remote,e.reason||R.UserHangup,!0):o.vF.info(`Call ${this.callId} onHangupReceived() ignoring message from party ID ${e.party_id}: our partner is ${this.opponentPartyId}`)}),(0,s.A)(this,"onRejectReceived",e=>{o.vF.debug(`Call ${this.callId} onRejectReceived() running`);[f.InviteSent,f.Ringing].includes(this.state)||this.state===f.Fledgling&&this.direction===S.Inbound?this.terminate(I.Remote,e.reason||R.UserHangup,!0):o.vF.debug(`Call ${this.callId} onRejectReceived() called in wrong state (state=${this.state})`)}),(0,s.A)(this,"onAnsweredElsewhere",e=>{o.vF.debug(`Call ${this.callId} onAnsweredElsewhere() running`),this.terminate(I.Remote,R.AnsweredElsewhere,!0)}),this.roomId=e.roomId,this.invitee=e.invitee,this.client=e.client,!this.client.deviceId)throw new Error("Client must have a device ID to start calls");this.forceTURN=null!==(t=e.forceTURN)&&void 0!==t&&t,this.ourPartyId=this.client.deviceId,this.opponentDeviceId=e.opponentDeviceId,this.opponentSessionId=e.opponentSessionId,this.groupCallId=e.groupCallId,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:["stun:turn.matrix.org"]});for(const e of this.turnServers)(0,a.UB)(e,["urls"]);this.callId=_(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}async placeVoiceCall(){await this.placeCall(!0,!1)}async placeVideoCall(){await this.placeCall(!0,!0)}createDataChannel(e,t){const i=this.peerConn.createDataChannel(e,t);return this.emit(E.DataChannel,i,this),i}getOpponentMember(){return this.opponentMember}getOpponentDeviceId(){return this.opponentDeviceId}getOpponentSessionId(){return this.opponentSessionId}opponentCanBeTransferred(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(E.State,e,t,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?y.Video:y.Voice}get hasLocalUserMediaVideoTrack(){var e;return!(null===(e=this.localUsermediaStream)||void 0===e||!e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===c.h.Usermedia&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoTracks().length)})}get hasLocalUserMediaAudioTrack(){var e;return!(null===(e=this.localUsermediaStream)||void 0===e||!e.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===c.h.Usermedia&&!(null===(t=e.stream)||void 0===t||!t.getAudioTracks().length)})}get hasUserMediaAudioSender(){var e;return Boolean(null===(e=this.transceivers.get(C(c.h.Usermedia,"audio")))||void 0===e?void 0:e.sender)}get hasUserMediaVideoSender(){var e;return Boolean(null===(e=this.transceivers.get(C(c.h.Usermedia,"video")))||void 0===e?void 0:e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find(e=>e.purpose===c.h.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(e=>e.purpose===c.h.Screenshare)}get localUsermediaStream(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.stream}get localScreensharingStream(){var e;return null===(e=this.localScreensharingFeed)||void 0===e?void 0:e.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find(e=>e.purpose===c.h.Usermedia)}get remoteScreensharingFeed(){return this.getRemoteFeeds().find(e=>e.purpose===c.h.Screenshare)}get remoteUsermediaStream(){var e;return null===(e=this.remoteUsermediaFeed)||void 0===e?void 0:e.stream}get remoteScreensharingStream(){var e;return null===(e=this.remoteScreensharingFeed)||void 0===e?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 e;if(!this.opponentDeviceId)return;if(!this.client.getUseE2eForGroupCall())return;if(!this.client.getCrypto())return void(this.hasOpponentDeviceInfo=!0);const t=this.invitee||(null===(e=this.getOpponentMember())||void 0===e?void 0:e.userId);if(!t)throw new Error("Couldn't find opponent user ID to init crypto");throw this.hasOpponentDeviceInfo=!1,new m.Iy(t)}getLocalSDPStreamMetadata(e=!1){const t={};for(const i of this.getLocalFeeds())e&&(i.sdpMetadataStreamId=i.stream.id),t[i.sdpMetadataStreamId]={purpose:i.purpose,audio_muted:i.isAudioMuted(),video_muted:i.isVideoMuted()};return t}noIncomingFeeds(){return!this.feeds.some(e=>!e.isLocal())}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata())return void this.pushRemoteFeedWithoutMetadata(e);const t=this.getOpponentMember().userId,i=this.remoteSDPStreamMetadata[e.id].purpose,s=this.remoteSDPStreamMetadata[e.id].audio_muted,n=this.remoteSDPStreamMetadata[e.id].video_muted;i?this.getFeedByStreamId(e.id)?o.vF.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`):(this.feeds.push(new h.Hh({client:this.client,call:this,roomId:this.roomId,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:i,audioMuted:s,videoMuted:n})),this.emit(E.FeedsChanged,this.feeds,this),o.vF.info(`Call ${this.callId} pushRemoteFeed() pushed stream (streamId=${e.id}, active=${e.active}, purpose=${i})`)):o.vF.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=${e.id})`)}pushRemoteFeedWithoutMetadata(e){var t;const i=this.getOpponentMember().userId,s=c.h.Usermedia,n=null===(t=this.feeds.find(e=>!e.isLocal()))||void 0===t?void 0:t.stream;n&&e.id!==n.id?o.vF.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=${e.id})`):this.getFeedByStreamId(e.id)?o.vF.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=${e.id})`):(this.feeds.push(new h.Hh({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:s})),this.emit(E.FeedsChanged,this.feeds,this),o.vF.info(`Call ${this.callId} pushRemoteFeedWithoutMetadata() pushed stream (streamId=${e.id}, active=${e.active})`))}pushNewLocalFeed(e,t,i=!0){const s=this.client.getUserId();A(e.getAudioTracks(),!0),A(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)?o.vF.warn(`Call ${this.callId} pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`):this.pushLocalFeed(new h.Hh({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:s,deviceId:this.getOpponentDeviceId(),stream:e,purpose:t}),i)}pushLocalFeed(e,t=!0){if(this.feeds.some(t=>e.stream.id===t.stream.id))o.vF.info(`Call ${this.callId} pushLocalFeed() ignoring duplicate local stream (streamId=${e.stream.id})`);else{if(this.feeds.push(e),t)for(const t of e.stream.getTracks()){o.vF.info(`Call ${this.callId} pushLocalFeed() adding track to peer connection (id=${t.id}, kind=${t.kind}, streamId=${e.stream.id}, streamPurpose=${e.purpose}, enabled=${t.enabled})`);const i=C(e.purpose,t.kind);if(this.transceivers.has(i)){const e=this.transceivers.get(i);e.sender.replaceTrack(t),e.direction="inactive"===e.direction?"sendonly":"sendrecv"}else{const s=this.peerConn.addTrack(t,e.stream),n=this.peerConn.getTransceivers().find(e=>e.sender===s);n?this.transceivers.set(i,n):o.vF.warn(`Call ${this.callId} pushLocalFeed() didn't find a matching transceiver after adding track!`)}}o.vF.info(`Call ${this.callId} pushLocalFeed() pushed stream (id=${e.stream.id}, active=${e.stream.active}, purpose=${e.purpose})`),this.emit(E.FeedsChanged,this.feeds,this)}}removeLocalFeed(e){const t=C(e.purpose,"audio"),i=C(e.purpose,"video");for(const e of[t,i])if(this.transceivers.has(e)){const t=this.transceivers.get(e);t.sender&&this.peerConn.removeTrack(t.sender)}e.purpose===c.h.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(E.FeedsChanged,this.feeds,this)}deleteFeedByStream(e){const t=this.getFeedByStreamId(e.id);t?this.deleteFeed(t):o.vF.warn(`Call ${this.callId} deleteFeedByStream() didn't find the feed to delete (streamId=${e.id})`)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit(E.FeedsChanged,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(e=>{t.push(e)}),t}async initWithInvite(e){var t;const i=e.getContent();this.direction=S.Inbound;await this.client.checkTurnServers()||o.vF.warn(`Call ${this.callId} initWithInvite() failed to get TURN credentials! Proceeding with call anyway...`);const s=i[c.A];s?this.updateRemoteSDPStreamMetadata(s):o.vF.debug(`Call ${this.callId} initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams`),this.peerConn=this.createPeerConnection(),this.emit(E.PeerConnectionCreated,this.peerConn,this),this.chooseOpponent(e),await this.initOpponentCrypto();try{await this.peerConn.setRemoteDescription(i.offer),o.vF.debug(`Call ${this.callId} initWithInvite() set remote description: ${i.offer.type}`),await this.addBufferedIceCandidates()}catch(e){return o.vF.debug(`Call ${this.callId} initWithInvite() failed to set remote description`,e),void this.terminate(I.Local,R.SetRemoteDescription,!1)}const n=null===(t=this.feeds.find(e=>!e.isLocal()))||void 0===t?void 0:t.stream;if(!(this.isOnlyDataChannelAllowed||n&&0!==n.getTracks().length))return o.vF.error(`Call ${this.callId} initWithInvite() no remote stream or no tracks after setting remote description!`),void this.terminate(I.Local,R.SetRemoteDescription,!1);if(this.state=f.Ringing,e.getLocalAge()){const t=setTimeout(()=>{var e;this.state==f.Ringing&&(o.vF.debug(`Call ${this.callId} initWithInvite() invite has expired. Hanging up.`),this.hangupParty=I.Remote,this.state=f.Ended,this.stopAllMedia(),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),null===(e=this.stats)||void 0===e||e.removeStatsReportGatherer(this.callId),this.emit(E.Hangup,this))},i.lifetime-e.getLocalAge()),s=e=>{e!==f.Ringing&&(clearTimeout(t),this.off(E.State,s))};this.on(E.State,s)}}initWithHangup(e){this.state=f.Ended}shouldAnswerWithMediaType(e,t,i){return e&&!t?(o.vF.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${i} because the other side isn't sending it either.`),!1):(0,a.hX)(e)||e===t||this.opponentSupportsSDPStreamMetadata()?null!=e?e:t:(o.vF.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${i}=${e} because the other side doesn't support it. Answering with ${i}=${t}.`),t)}async answer(e,t){if(!this.inviteOrAnswerSent){if(!1===e&&!1===t)throw new Error("You CANNOT answer a call without media");if(this.localUsermediaStream||this.waitForLocalAVStream)this.waitForLocalAVStream&&(this.state=f.WaitLocalMedia);else{const s=this.state,n=this.shouldAnswerWithMediaType(e,this.hasRemoteUserMediaAudioTrack,"audio"),r=this.shouldAnswerWithMediaType(t,this.hasRemoteUserMediaVideoTrack,"video");this.state=f.WaitLocalMedia,this.waitForLocalAVStream=!0;try{var i;const e=await this.client.getMediaHandler().getUserMediaStream(n,r);this.waitForLocalAVStream=!1;const t=[new h.Hh({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:null!==(i=this.client.getDeviceId())&&void 0!==i?i:void 0,stream:e,purpose:c.h.Usermedia,audioMuted:!1,videoMuted:!1})];this.localScreensharingFeed&&t.push(this.localScreensharingFeed),this.answerWithCallFeeds(t)}catch(e){if(!r)return void this.getUserMediaFailed(e);o.vF.warn(`Call ${this.callId} answer() failed to getUserMedia(), trying to getUserMedia() without video`),this.state=s,this.waitForLocalAVStream=!1,await this.answer(n,!1)}}}}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){o.vF.debug(`Call ${this.callId} replacedBy() running (newCallId=${e.callId})`),this.state===f.WaitLocalMedia?(o.vF.debug(`Call ${this.callId} replacedBy() telling new call to wait for local media (newCallId=${e.callId})`),e.waitForLocalAVStream=!0):[f.CreateOffer,f.InviteSent].includes(this.state)&&(e.direction===S.Outbound?e.queueGotCallFeedsForAnswer([]):(o.vF.debug(`Call ${this.callId} replacedBy() handing local stream to new call(newCallId=${e.callId})`),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(e=>e.clone())))),this.successor=e,this.emit(E.Replaced,e,this),this.hangup(R.Replaced,!0)}hangup(e,t){if(this.callHasEnded())return;if(o.vF.debug(`Call ${this.callId} hangup() ending call (reason=${e})`),this.terminate(I.Local,e,!t),[f.Fledgling,f.WaitLocalMedia].includes(this.state))return;const i={};(this.opponentVersion&&0!==this.opponentVersion||e!==R.UserHangup)&&(i.reason=e),this.sendVoipEvent(d.Bx.CallHangup,i)}reject(){if(this.state!==f.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(0===this.opponentVersion)return o.vF.info(`Call ${this.callId} reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=${this.opponentVersion})`),void this.hangup(R.UserHangup,!0);o.vF.debug("Rejecting call: "+this.callId),this.terminate(I.Local,R.UserHangup,!0),this.sendVoipEvent(d.Bx.CallReject,{})}async upgradeCall(e,t){if((e||t)&&this.opponentSupportsSDPStreamMetadata())try{o.vF.debug(`Call ${this.callId} upgradeCall() upgrading call (audio=${e}, video=${t})`);const i=e||this.hasLocalUserMediaAudioTrack,s=t||this.hasLocalUserMediaVideoTrack,n=await this.client.getMediaHandler().getUserMediaStream(i,s,!1);await this.updateLocalUsermediaStream(n,e,t)}catch(e){o.vF.error(`Call ${this.callId} upgradeCall() failed to upgrade the call`,e),this.emit(E.Error,new T(R.NoUserMedia,"Failed to get camera access: ",e),this)}}opponentSupportsSDPStreamMetadata(){return Boolean(this.remoteSDPStreamMetadata)}isScreensharing(){return Boolean(this.localScreensharingStream)}async setScreensharingEnabled(e,t){if(e&&this.isScreensharing())return o.vF.warn(`Call ${this.callId} setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!`),!0;if(!e&&!this.isScreensharing())return o.vF.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(o.vF.debug(`Call ${this.callId} setScreensharingEnabled() running (enabled=${e})`),!e){const e=this.transceivers.get(C(c.h.Screenshare,"audio")),t=this.transceivers.get(C(c.h.Screenshare,"video"));for(const i of[e,t])i&&i.sender&&this.peerConn.removeTrack(i.sender);return this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=await this.client.getMediaHandler().getScreensharingStream(t);return!!e&&(this.pushNewLocalFeed(e,c.h.Screenshare),!0)}catch(e){return o.vF.error(`Call ${this.callId} setScreensharingEnabled() failed to get screen-sharing stream:`,e),!1}}async setScreensharingEnabledWithoutMetadataSupport(e,t){if(o.vF.debug(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() running (enabled=${e})`),!e){var i,s;const e=null===(i=this.localUsermediaStream)||void 0===i?void 0:i.getTracks().find(e=>"video"===e.kind),t=null===(s=this.transceivers.get(C(c.h.Usermedia,"video")))||void 0===s?void 0:s.sender;return null==t||t.replaceTrack(null!=e?e:null),this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{var n;const e=await this.client.getMediaHandler().getScreensharingStream(t);if(!e)return!1;const i=e.getTracks().find(e=>"video"===e.kind),s=null===(n=this.transceivers.get(C(c.h.Usermedia,"video")))||void 0===n?void 0:n.sender;return null==s||s.replaceTrack(null!=i?i:null),this.pushNewLocalFeed(e,c.h.Screenshare,!1),!0}catch(e){return o.vF.error(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:`,e),!1}}async updateLocalUsermediaStream(e,t=!1,i=!1){const s=this.localUsermediaFeed,n=t||!s.isAudioMuted()&&!this.remoteOnHold,r=i||!s.isVideoMuted()&&!this.remoteOnHold;o.vF.log(`Call ${this.callId} updateLocalUsermediaStream() running (streamId=${e.id}, audio=${n}, video=${r})`),A(e.getAudioTracks(),n),A(e.getVideoTracks(),r);for(const e of this.localUsermediaStream.getTracks())this.localUsermediaStream.removeTrack(e),e.stop();for(const t of e.getTracks())this.localUsermediaStream.addTrack(t);for(const t of e.getTracks()){const i=C(c.h.Usermedia,t.kind),n=this.transceivers.get(i),r=null==n?void 0:n.sender;let a=!1;if(r)try{o.vF.info(`Call ${this.callId} updateLocalUsermediaStream() replacing track (id=${t.id}, kind=${t.kind}, streamId=${e.id}, streamPurpose=${s.purpose})`),await r.replaceTrack(t),n.direction="inactive"===n.direction?"sendonly":"sendrecv",a=!0}catch(e){o.vF.warn(`Call ${this.callId} updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead`,e)}if(!a){o.vF.info(`Call ${this.callId} updateLocalUsermediaStream() adding track to peer connection (id=${t.id}, kind=${t.kind}, streamId=${e.id}, streamPurpose=${s.purpose})`);const n=this.peerConn.addTrack(t,this.localUsermediaStream),r=this.peerConn.getTransceivers().find(e=>e.sender===n);r?this.transceivers.set(i,r):o.vF.warn(`Call ${this.callId} updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!`)}}}async setLocalVideoMuted(e){var t,i;if(o.vF.log(`Call ${this.callId} setLocalVideoMuted() running ${e}`),e||void 0===this.stopVideoTrackTimer||(clearTimeout(this.stopVideoTrackTimer),this.stopVideoTrackTimer=void 0),!await this.client.getMediaHandler().hasVideoDevice())return this.isLocalVideoMuted();if(!this.hasUserMediaVideoSender&&!e)return null===(i=this.localUsermediaFeed)||void 0===i||i.setAudioVideoMuted(null,e),await this.upgradeCall(!1,!0),this.isLocalVideoMuted();if(!e&&0===this.localUsermediaStream.getVideoTracks().length){const e=await this.client.getMediaHandler().getUserMediaStream(!0,!0);await this.updateLocalUsermediaStream(e)}return null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(null,e),this.updateMuteStatus(),await this.sendMetadataUpdate(),e&&(this.stopVideoTrackTimer=setTimeout(()=>{for(const e of this.localUsermediaStream.getVideoTracks())e.stop(),this.localUsermediaStream.removeTrack(e)},120)),this.isLocalVideoMuted()}isLocalVideoMuted(){var e,t;return null!==(e=null===(t=this.localUsermediaFeed)||void 0===t?void 0:t.isVideoMuted())&&void 0!==e&&e}async setMicrophoneMuted(e){var t;return o.vF.log(`Call ${this.callId} setMicrophoneMuted() running ${e}`),await this.client.getMediaHandler().hasAudioDevice()?e||this.hasUserMediaAudioSender&&this.hasLocalUserMediaAudioTrack?(null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(e,null),this.updateMuteStatus(),await this.sendMetadataUpdate(),this.isMicrophoneMuted()):(await this.upgradeCall(!0,!1),this.isMicrophoneMuted()):this.isMicrophoneMuted()}isMicrophoneMuted(){var e,t;return null!==(e=null===(t=this.localUsermediaFeed)||void 0===t?void 0:t.isAudioMuted())&&void 0!==e&&e}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(E.RemoteHoldUnhold,this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!==f.Connected)return!1;let e=!0;for(const t of this.peerConn.getTransceivers()){["inactive","recvonly"].includes(t.currentDirection)||(e=!1)}return e}sendDtmfDigit(e){for(const i of this.peerConn.getSenders()){var t;if("audio"===(null===(t=i.track)||void 0===t?void 0:t.kind)&&i.dtmf)return void i.dtmf.insertDTMF(e)}throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){const e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;o.vF.log(`Call ${this.callId} updateMuteStatus stream ${this.localUsermediaStream.id} micShouldBeMuted ${e} vidShouldBeMuted ${t}`),A(this.localUsermediaStream.getAudioTracks(),!e),A(this.localUsermediaStream.getVideoTracks(),!t)}async sendMetadataUpdate(){await this.sendVoipEvent(d.Bx.CallSDPStreamMetadataChangedPrefix,{[c.A]:this.getLocalSDPStreamMetadata()})}gotCallFeedsForInvite(e,t=!1){if(this.successor)this.successor.queueGotCallFeedsForAnswer(e);else if(this.callHasEnded())this.stopAllMedia();else{for(const t of e)this.pushLocalFeed(t);t&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=f.CreateOffer,o.vF.debug(`Call ${this.callId} gotUserMediaForInvite() run`)}}async sendAnswer(){const e={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[c.A]:this.getLocalSDPStreamMetadata(!0)};e.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1};const t=this.discardDuplicateCandidates();o.vF.info(`Call ${this.callId} sendAnswer() discarding ${t} candidates that will be sent in answer`);try{await this.sendVoipEvent(d.Bx.CallAnswer,e),this.inviteOrAnswerSent=!0}catch(e){this.state=f.Ringing,e instanceof v.up&&e.event&&this.client.cancelPendingEvent(e.event);let t=R.SendAnswer,i="Failed to send answer";throw"UnknownDeviceError"==e.name&&(t=R.UnknownDevices,i="Unknown devices present in the room"),this.emit(E.Error,new T(t,i,e),this),e}this.sendCandidateQueue()}queueGotCallFeedsForAnswer(e){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.gotCallFeedsForAnswer(e)):this.responsePromiseChain=this.gotCallFeedsForAnswer(e)}mungeSdp(e,t){const i=(0,r.qg)(e.sdp);i.media.forEach(e=>{const i=new Map,s=new Map;for(const t of e.rtp)i.set(t.payload,t.codec),s.set(t.codec,t.payload);for(const n of t){if(n.mediaType!==e.type)continue;if(!s.has(n.codec)){o.vF.info(`Call ${this.callId} mungeSdp() ignoring SDP modifications for ${n.codec} as it's not present.`);continue}const t=[];void 0!==n.enableDtx&&t.push("usedtx="+(n.enableDtx?"1":"0")),void 0!==n.maxAverageBitrate&&t.push(`maxaveragebitrate=${n.maxAverageBitrate}`);let r=!1;for(const s of e.fmtp)i.get(s.payload)===n.codec&&(r=!0,s.config+=";"+t.join(";"));r||e.fmtp.push({payload:s.get(n.codec),config:t.join(";")})}}),e.sdp=(0,r.M9)(i)}async createOffer(){const e=await this.peerConn.createOffer();return this.mungeSdp(e,w(this.isPtt)),e}async createAnswer(){const e=await this.peerConn.createAnswer();return this.mungeSdp(e,w(this.isPtt)),e}async gotCallFeedsForAnswer(e){if(this.callHasEnded())return;this.waitForLocalAVStream=!1;for(const t of e)this.pushLocalFeed(t);let t;this.state=f.CreateAnswer;try{this.getRidOfRTXCodecs(),t=await this.createAnswer()}catch(e){return o.vF.debug(`Call ${this.callId} gotCallFeedsForAnswer() failed to create answer: `,e),void this.terminate(I.Local,R.CreateAnswer,!0)}try{if(await this.peerConn.setLocalDescription(t),this.callHasEnded())return;if(this.state=f.Connecting,await new Promise(e=>{setTimeout(e,200)}),this.callHasEnded())return;this.sendAnswer()}catch(e){return o.vF.debug(`Call ${this.callId} gotCallFeedsForAnswer() error setting local description!`,e),void this.terminate(I.Local,R.SetLocalDescription,!0)}}async onRemoteIceCandidatesReceived(e){if(this.callHasEnded())return;const t=e.getContent(),i=t.candidates;if(!i)return void o.vF.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!`);const s=0===t.version?null:t.party_id||null;if(void 0!==this.opponentPartyId)this.partyIdMatches(t)?await this.addIceCandidates(i):o.vF.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates from party ID ${t.party_id}: we have chosen party ID ${this.opponentPartyId}`);else if(s){o.vF.info(`Call ${this.callId} onRemoteIceCandidatesReceived() buffering ${i.length} candidates until we pick an opponent`);const e=this.remoteCandidateBuffer.get(s)||[];e.push(...i),this.remoteCandidateBuffer.set(s,e)}}async onAnswerReceived(e){const t=e.getContent();if(o.vF.debug(`Call ${this.callId} onAnswerReceived() running (hangupParty=${t.party_id})`),this.callHasEnded())return void o.vF.debug(`Call ${this.callId} onAnswerReceived() ignoring answer because call has ended`);if(void 0!==this.opponentPartyId)return void o.vF.info(`Call ${this.callId} onAnswerReceived() ignoring answer from party ID ${t.party_id}: we already have an answer/reject from ${this.opponentPartyId}`);this.chooseOpponent(e),await this.addBufferedIceCandidates(),this.state=f.Connecting;const i=t[c.A];i?this.updateRemoteSDPStreamMetadata(i):o.vF.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,o.vF.debug(`Call ${this.callId} onAnswerReceived() set remote description: ${t.answer.type}`)}catch(e){return this.isSettingRemoteAnswerPending=!1,o.vF.debug(`Call ${this.callId} onAnswerReceived() failed to set remote description`,e),void this.terminate(I.Local,R.SetRemoteDescription,!1)}if(null!==this.opponentPartyId)try{await this.sendVoipEvent(d.Bx.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(e){o.vF.warn(`Call ${this.callId} onAnswerReceived() failed to send select_answer event`,e)}}async onSelectAnswerReceived(e){if(this.direction!==S.Inbound)return void o.vF.warn(`Call ${this.callId} onSelectAnswerReceived() got select_answer for an outbound call: ignoring`);const t=e.getContent().selected_party_id;null!=t?t!==this.ourPartyId&&(o.vF.info(`Call ${this.callId} onSelectAnswerReceived() got select_answer for party ID ${t}: we are party ID ${this.ourPartyId}.`),await this.terminate(I.Remote,R.AnsweredElsewhere,!0)):o.vF.warn(`Call ${this.callId} onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring`)}async onNegotiateReceived(e){const t=e.getContent(),i=t.description;if(!i||!i.sdp||!i.type)return void o.vF.info(`Call ${this.callId} onNegotiateReceived() ignoring invalid m.call.negotiate event`);const s=this.direction===S.Inbound,n=!this.makingOffer&&("stable"===this.peerConn.signalingState||this.isSettingRemoteAnswerPending),r="offer"===i.type&&!n;if(this.ignoreOffer=!s&&r,this.ignoreOffer)return void o.vF.info(`Call ${this.callId} onNegotiateReceived() ignoring colliding negotiate event because we're impolite`);const a=this.isLocalOnHold(),l=t[c.A];l?this.updateRemoteSDPStreamMetadata(l):o.vF.warn(`Call ${this.callId} onNegotiateReceived() received negotiation event without SDPStreamMetadata!`);try{if(this.isSettingRemoteAnswerPending="answer"==i.type,await this.peerConn.setRemoteDescription(i),this.isSettingRemoteAnswerPending=!1,o.vF.debug(`Call ${this.callId} onNegotiateReceived() set remote description: ${i.type}`),"offer"===i.type){var h;let e;try{this.getRidOfRTXCodecs(),e=await this.createAnswer()}catch(e){return o.vF.debug(`Call ${this.callId} onNegotiateReceived() failed to create answer: `,e),void this.terminate(I.Local,R.CreateAnswer,!0)}await this.peerConn.setLocalDescription(e),o.vF.debug(`Call ${this.callId} onNegotiateReceived() create an answer`),this.sendVoipEvent(d.Bx.CallNegotiate,{lifetime:b,description:null===(h=this.peerConn.localDescription)||void 0===h?void 0:h.toJSON(),[c.A]:this.getLocalSDPStreamMetadata(!0)})}}catch(e){this.isSettingRemoteAnswerPending=!1,o.vF.warn(`Call ${this.callId} onNegotiateReceived() failed to complete negotiation`,e)}const u=this.isLocalOnHold();a!==u&&(this.emit(E.LocalHoldUnhold,u,this),this.emit(E.HoldUnhold,u))}updateRemoteSDPStreamMetadata(e){this.remoteSDPStreamMetadata=(0,a.Bi)(this.remoteSDPStreamMetadata||{},e,!0);for(const e of this.getRemoteFeeds()){var t;const i=e.stream.id,s=this.remoteSDPStreamMetadata[i];e.setAudioVideoMuted(null==s?void 0:s.audio_muted,null==s?void 0:s.video_muted),e.purpose=null===(t=this.remoteSDPStreamMetadata[i])||void 0===t?void 0:t.purpose}}onSDPStreamMetadataChangedReceived(e){const t=e.getContent()[c.A];this.updateRemoteSDPStreamMetadata(t)}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(E.AssertedIdentityChanged,this))}callHasEnded(){return this.state===f.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){return void this.getLocalOfferFailed(e)}finally{this.makingOffer=!1}}async gotLocalOffer(){if(o.vF.debug(`Call ${this.callId} gotLocalOffer() running`),this.callHasEnded())return void o.vF.debug(`Call ${this.callId} gotLocalOffer() ignoring newly created offer because the call has ended"`);let e;try{this.getRidOfRTXCodecs(),e=await this.createOffer()}catch(e){return o.vF.debug(`Call ${this.callId} gotLocalOffer() failed to create offer: `,e),void this.terminate(I.Local,R.CreateOffer,!0)}try{await this.peerConn.setLocalDescription(e)}catch(e){return o.vF.debug(`Call ${this.callId} gotLocalOffer() error setting local description!`,e),void this.terminate(I.Local,R.SetLocalDescription,!0)}if("gathering"===this.peerConn.iceGatheringState&&await new Promise(e=>{setTimeout(e,200)}),this.callHasEnded())return;const t=this.state===f.CreateOffer?d.Bx.CallInvite:d.Bx.CallNegotiate,i={lifetime:b};var s,n;(t===d.Bx.CallInvite&&this.invitee&&(i.invitee=this.invitee),this.state===f.CreateOffer)?i.offer=null===(s=this.peerConn.localDescription)||void 0===s?void 0:s.toJSON():i.description=null===(n=this.peerConn.localDescription)||void 0===n?void 0:n.toJSON();i.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},i[c.A]=this.getLocalSDPStreamMetadata(!0);const r=this.discardDuplicateCandidates();o.vF.info(`Call ${this.callId} gotLocalOffer() discarding ${r} candidates that will be sent in offer`);try{await this.sendVoipEvent(t,i)}catch(e){o.vF.error(`Call ${this.callId} gotLocalOffer() failed to send invite`,e),e instanceof v.up&&e.event&&this.client.cancelPendingEvent(e.event);let t=R.SignallingFailed,i="Signalling failed";return this.state===f.CreateOffer&&(t=R.SendInvite,i="Failed to send invite"),"UnknownDeviceError"==e.name&&(t=R.UnknownDevices,i="Unknown devices present in the room"),this.emit(E.Error,new T(t,i,e),this),void this.terminate(I.Local,t,!1)}this.sendCandidateQueue(),this.state===f.CreateOffer&&(this.inviteOrAnswerSent=!0,this.state=f.InviteSent,this.inviteTimeout=setTimeout(()=>{this.inviteTimeout=void 0,this.state===f.InviteSent&&this.hangup(R.InviteTimeout,!1)},b))}getRidOfRTXCodecs(){if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const e=this.transceivers.get(C(c.h.Screenshare,"video"));if(!e||!e.setCodecPreferences)return;const t=RTCRtpReceiver.getCapabilities("video").codecs,i=RTCRtpSender.getCapabilities("video").codecs,s=[];for(const n of[...t,...i])if("video/rtx"!==n.mimeType){s.push(n);try{e.setCodecPreferences(s)}catch(e){o.vF.info("Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences",n,e),s.pop()}}}async sendVoipEvent(e,t){const i=g(g({},t),{},{version:"1",call_id:this.callId,party_id:this.ourPartyId,conf_id:this.groupCallId});if(this.opponentDeviceId){var s;const t=this.toDeviceSeq++,r=g(g({},i),{},{device_id:this.client.deviceId,sender_session_id:this.client.getSessionId(),dest_session_id:this.opponentSessionId,seq:t,[d.wt]:(0,n.A)()});this.emit(E.SendVoipEvent,{type:"toDevice",eventType:e,userId:this.invitee||(null===(s=this.getOpponentMember())||void 0===s?void 0:s.userId),opponentDeviceId:this.opponentDeviceId,content:r},this);const a=this.invitee||this.getOpponentMember().userId;if(this.client.getUseE2eForGroupCall()){if(!this.hasOpponentDeviceInfo)return void o.vF.warn(`Call ${this.callId} sendVoipEvent() failed: we do not have opponentDeviceInfo`);throw new Error("Unimplemented")}await this.client.sendToDevice(e,new Map([[a,new Map([[this.opponentDeviceId,r]])]]))}else{var r;this.emit(E.SendVoipEvent,{type:"sendEvent",eventType:e,roomId:this.roomId,content:i,userId:this.invitee||(null===(r=this.getOpponentMember())||void 0===r?void 0:r.userId)},this),await this.client.sendEvent(this.roomId,e,i)}}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,this.state===f.Ringing||!this.inviteOrAnswerSent)return;const t=this.direction===S.Inbound?500:2e3;0===this.candidateSendTries&&setTimeout(()=>{this.sendCandidateQueue()},t)}discardDuplicateCandidates(){let e=0;const t=[];for(let i=0;i<this.candidateSendQueue.length;i++){const s=this.candidateSendQueue[i];""===s.candidate?t.push(s):e++}return this.candidateSendQueue=t,e}async transfer(e){const t=await this.client.getProfileInfo(e),i=_(),s={replacement_id:_(),target_user:{id:e,display_name:t.displayname,avatar_url:t.avatar_url},create_call:i};await this.sendVoipEvent(d.Bx.CallReplaces,s),await this.terminate(I.Local,R.Transferred,!0)}async transferToCall(e){var t,i;const s=null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId,n=s?await this.client.getProfileInfo(s):void 0,r=null===(i=this.getOpponentMember())||void 0===i?void 0:i.userId,o=r?await this.client.getProfileInfo(r):void 0,a=_(),l={replacement_id:_(),target_user:{id:r,display_name:null==o?void 0:o.displayname,avatar_url:null==o?void 0:o.avatar_url},await_call:a};await e.sendVoipEvent(d.Bx.CallReplaces,l);const c={replacement_id:_(),target_user:{id:s,display_name:null==n?void 0:n.displayname,avatar_url:null==n?void 0:n.avatar_url},create_call:a};await this.sendVoipEvent(d.Bx.CallReplaces,c),await this.terminate(I.Local,R.Transferred,!0),await e.terminate(I.Local,R.Transferred,!0)}async terminate(e,t,i){var s;if(!this.callHasEnded()){this.hangupParty=e,this.hangupReason=t,this.state=f.Ended,this.inviteTimeout&&(clearTimeout(this.inviteTimeout),this.inviteTimeout=void 0),void 0!==this.iceDisconnectedTimeout&&(clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0),this.callLengthInterval&&(clearInterval(this.callLengthInterval),this.callLengthInterval=void 0),void 0!==this.stopVideoTrackTimer&&(clearTimeout(this.stopVideoTrackTimer),this.stopVideoTrackTimer=void 0);for(const[e,t]of this.removeTrackListeners)e.removeEventListener("removetrack",t);this.removeTrackListeners.clear(),this.callStatsAtEnd=await this.collectCallStats(),this.stopAllMedia(),this.deleteAllFeeds(),this.peerConn&&"closed"!==this.peerConn.signalingState&&this.peerConn.close(),null===(s=this.stats)||void 0===s||s.removeStatsReportGatherer(this.callId),i&&this.emit(E.Hangup,this),this.client.callEventHandler.calls.delete(this.callId)}}stopAllMedia(){o.vF.debug(`Call ${this.callId} stopAllMedia() running`);for(const e of this.feeds)if(e.isLocal()&&e.purpose===c.h.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===c.h.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else if(!e.isLocal()){o.vF.debug(`Call ${this.callId} stopAllMedia() stopping stream (streamId=${e.stream.id})`);for(const t of e.stream.getTracks())t.stop()}}checkForErrorListener(){if(0===this.listeners(u.u.Error).length)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}async sendCandidateQueue(){if(0===this.candidateSendQueue.length||this.callHasEnded())return;const e=this.candidateSendQueue;this.candidateSendQueue=[],++this.candidateSendTries;const t={candidates:e.map(e=>e.toJSON())};this.candidatesEnded&&t.candidates.push({candidate:""}),o.vF.debug(`Call ${this.callId} sendCandidateQueue() attempting to send ${e.length} candidates`);try{await this.sendVoipEvent(d.Bx.CallCandidates,t),this.candidateSendTries=0,this.sendCandidateQueue()}catch(t){if(t instanceof v.up&&t.event&&this.client.cancelPendingEvent(t.event),this.candidateSendQueue.push(...e),this.candidateSendTries>5){o.vF.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates on attempt ${this.candidateSendTries}. Giving up on this call.`,t);const e=R.SignallingFailed,i="Signalling failed";return this.emit(E.Error,new T(e,i,t),this),void this.hangup(e,!1)}const i=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,o.vF.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates. Retrying in ${i}ms`,t),setTimeout(()=>{this.sendCandidateQueue()},i)}}async placeCall(e,t){if(!e)throw new Error("You CANNOT start a call without audio");let i;this.state=f.WaitLocalMedia;try{var s;const n=await this.client.getMediaHandler().getUserMediaStream(e,t);A(n.getAudioTracks(),!0),A(n.getVideoTracks(),!0),i=new h.Hh({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:null!==(s=this.client.getDeviceId())&&void 0!==s?s:void 0,stream:n,purpose:c.h.Usermedia,audioMuted:!1,videoMuted:!1})}catch(e){return void this.getUserMediaFailed(e)}try{await this.placeCallWithCallFeeds([i])}catch(e){return void this.placeCallFailed(e)}}async placeCallWithCallFeeds(e,t=!1){this.checkForErrorListener(),this.direction=S.Outbound,await this.initOpponentCrypto(),this.client.callEventHandler.calls.set(this.callId,this);await this.client.checkTurnServers()||o.vF.warn(`Call ${this.callId} placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...`),this.peerConn=this.createPeerConnection(),this.emit(E.PeerConnectionCreated,this.peerConn,this),this.gotCallFeedsForInvite(e,t)}createPeerConnection(){var e;const t=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers.length?this.turnServers:void 0,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),t.addEventListener("signalingstatechange",this.onSignallingStateChanged),t.addEventListener("icecandidate",this.gotLocalIceCandidate),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t.addEventListener("track",this.onTrack),t.addEventListener("negotiationneeded",this.onNegotiationNeeded),t.addEventListener("datachannel",this.onDataChannel);const i=this.getOpponentMember(),s=i?i.userId:"unknown";return null===(e=this.stats)||void 0===e||e.addStatsReportGatherer(this.callId,s,t),t}partyIdMatches(e){return(0===e.version?null:e.party_id||null)===this.opponentPartyId}chooseOpponent(e){var t;const i=e.getContent();var s;(o.vF.debug(`Call ${this.callId} chooseOpponent() running (partyId=${i.party_id})`),this.opponentVersion=i.version,0===this.opponentVersion?this.opponentPartyId=null:this.opponentPartyId=i.party_id||null,this.opponentCaps=i.capabilities||{},this.opponentMember=null!==(t=this.client.getRoom(this.roomId).getMember(e.getSender()))&&void 0!==t?t:void 0,this.opponentMember)&&(null===(s=this.stats)||void 0===s||s.updateOpponentMember(this.callId,this.opponentMember.userId))}async addBufferedIceCandidates(){const e=this.remoteCandidateBuffer.get(this.opponentPartyId);e&&(o.vF.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){null!==t.sdpMid&&void 0!==t.sdpMid||null!==t.sdpMLineIndex&&void 0!==t.sdpMLineIndex?o.vF.debug(`Call ${this.callId} addIceCandidates() got remote ICE candidate (sdpMid=${t.sdpMid}, candidate=${t.candidate})`):o.vF.debug(`Call ${this.callId} addIceCandidates() got remote ICE end-of-candidates`);try{await this.peerConn.addIceCandidate(t)}catch(e){this.ignoreOffer?o.vF.debug(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate because ignoring offer`,e):o.vF.info(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate`,e)}}}get hasPeerConnection(){return Boolean(this.peerConn)}initStats(e,t="unknown"){this.stats=e,this.stats.start()}}function A(e,t){for(const i of e)i.enabled=t}function M(){if("undefined"==typeof window||"undefined"==typeof document)return!1;try{var e,t,i;if(!Boolean(null!==(e=null!==(t=null!==(i=window.RTCPeerConnection)&&void 0!==i?i:window.RTCSessionDescription)&&void 0!==t?t:window.RTCIceCandidate)&&void 0!==e?e:navigator.mediaDevices))return o.vF.error("WebRTC is not supported in this browser / environment"),!1}catch(e){return o.vF.error("Exception thrown when trying to access WebRTC",e),!1}return!0}function x(e,t,i){if(!M())return null;const s=!!i&&i.forceTURN,n={client:e,roomId:t,invitee:null==i?void 0:i.invitee,turnServers:e.getTurnServers(),forceTURN:e.forceTURN||s,opponentDeviceId:null==i?void 0:i.opponentDeviceId,opponentSessionId:null==i?void 0:i.opponentSessionId,groupCallId:null==i?void 0:i.groupCallId},r=new k(n);return e.reEmitter.reEmit(r,Object.values(E)),r}},"./node_modules/matrix-js-sdk/src/webrtc/callFeed.ts":(e,t,i)=>{"use strict";i.d(t,{Hh:()=>h,Tw:()=>l});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/webrtc/callEventTypes.ts"),r=i("./node_modules/matrix-js-sdk/src/webrtc/audioContext.ts"),o=i("./node_modules/matrix-js-sdk/src/logger.ts"),a=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),d=i("./node_modules/matrix-js-sdk/src/webrtc/call.ts");const l=-60;let c=function(e){return e.NewStream="new_stream",e.MuteStateChanged="mute_state_changed",e.LocalVolumeChanged="local_volume_changed",e.VolumeChanged="volume_changed",e.ConnectedChanged="connected_changed",e.Speaking="speaking",e.Disposed="disposed",e}({});class h extends a.X{constructor(e){super(),(0,s.A)(this,"stream",void 0),(0,s.A)(this,"sdpMetadataStreamId",void 0),(0,s.A)(this,"userId",void 0),(0,s.A)(this,"deviceId",void 0),(0,s.A)(this,"purpose",void 0),(0,s.A)(this,"speakingVolumeSamples",void 0),(0,s.A)(this,"client",void 0),(0,s.A)(this,"call",void 0),(0,s.A)(this,"roomId",void 0),(0,s.A)(this,"audioMuted",void 0),(0,s.A)(this,"videoMuted",void 0),(0,s.A)(this,"localVolume",1),(0,s.A)(this,"measuringVolumeActivity",!1),(0,s.A)(this,"audioContext",void 0),(0,s.A)(this,"analyser",void 0),(0,s.A)(this,"frequencyBinCount",void 0),(0,s.A)(this,"speakingThreshold",l),(0,s.A)(this,"speaking",!1),(0,s.A)(this,"volumeLooperTimeout",void 0),(0,s.A)(this,"_disposed",!1),(0,s.A)(this,"_connected",!1),(0,s.A)(this,"onAddTrack",()=>{this.emit(c.NewStream,this.stream)}),(0,s.A)(this,"onCallState",e=>{e===d.iP.Connected?this.connected=!0:e===d.iP.Connecting&&(this.connected=!1)}),(0,s.A)(this,"volumeLooper",()=>{if(!this.analyser)return;if(!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let e=-1/0;for(const t of this.frequencyBinCount)t>e&&(e=t);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(e),this.emit(c.VolumeChanged,e);let t=!1;for(const e of this.speakingVolumeSamples)if(e>this.speakingThreshold){t=!0;break}this.speaking!==t&&(this.speaking=t,this.emit(c.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,200)}),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(8).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(d.$E.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit(c.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){if(t===e)return;const i=this.measuringVolumeActivity;e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?(this.initVolumeMeasuring(),i&&this.measureVolumeActivity(!0)):this.measureVolumeActivity(!1),this.emit(c.NewStream,this.stream)}initVolumeMeasuring(){if(!this.hasAudioTrack)return;this.audioContext||(this.audioContext=(0,r.o)()),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1;this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}getMember(){var e;const t=this.client.getRoom(this.roomId);return null!==(e=null==t?void 0:t.getMember(this.userId))&&void 0!==e?e:null}isLocal(){return this.userId===this.client.getUserId()&&(void 0===this.deviceId||this.deviceId===this.client.getDeviceId())}isAudioMuted(){return 0===this.stream.getAudioTracks().length||this.audioMuted}isVideoMuted(){return 0===this.stream.getVideoTracks().length||this.videoMuted}isSpeaking(){return this.speaking}setNewStream(e){this.updateStream(this.stream,e)}setAudioVideoMuted(e,t){null!==e&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),null!==t&&(this.videoMuted=t),this.emit(c.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(e){if(e){if(!this.analyser||!this.frequencyBinCount||!this.hasAudioTrack)return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(c.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){const e=this.client.getMediaHandler(),t=this.stream.clone();return o.vF.log(`CallFeed clone() cloning stream (originalStreamId=${this.stream.id}, newStreamId${t.id})`),this.purpose===n.h.Usermedia?e.userMediaStreams.push(t):e.screensharingStreams.push(t),new h({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),null===(e=this.stream)||void 0===e||e.removeEventListener("addtrack",this.onAddTrack),null===(t=this.call)||void 0===t||t.removeListener(d.$E.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,(0,r.N)()),this._disposed=!0,this.emit(c.Disposed)}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit(c.LocalVolumeChanged,e)}}},"./node_modules/matrix-js-sdk/src/webrtc/groupCall.ts":(e,t,i)=>{"use strict";i.d(t,{AZ:()=>_,Ad:()=>b,BF:()=>C,F_:()=>M,Iy:()=>A,MC:()=>R,eO:()=>O});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),r=i("./node_modules/matrix-js-sdk/src/webrtc/callFeed.ts"),o=i("./node_modules/matrix-js-sdk/src/webrtc/call.ts"),a=i("./node_modules/matrix-js-sdk/src/models/room-state.ts"),d=i("./node_modules/matrix-js-sdk/src/logger.ts"),l=i("./node_modules/matrix-js-sdk/src/ReEmitter.ts"),c=i("./node_modules/matrix-js-sdk/src/webrtc/callEventTypes.ts"),h=i("./node_modules/matrix-js-sdk/src/@types/event.ts"),u=i("./node_modules/matrix-js-sdk/src/webrtc/callEventHandler.ts"),m=i("./node_modules/matrix-js-sdk/src/webrtc/groupCallEventHandler.ts"),v=i("./node_modules/matrix-js-sdk/src/utils.ts"),p=i("./node_modules/matrix-js-sdk/src/webrtc/stats/groupCallStats.ts"),g=i("./node_modules/matrix-js-sdk/src/webrtc/stats/statsReport.ts"),f=i("./node_modules/matrix-js-sdk/src/webrtc/stats/summaryStatsReportGatherer.ts"),y=i("./node_modules/matrix-js-sdk/src/webrtc/stats/callFeedStatsReporter.ts"),S=i("./node_modules/matrix-js-sdk/src/@types/membership.ts");function I(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function E(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?I(Object(i),!0).forEach(function(t){(0,s.A)(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):I(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let R=function(e){return e.Ring="m.ring",e.Prompt="m.prompt",e.Room="m.room",e}({}),b=function(e){return e.Video="m.video",e.Voice="m.voice",e}({}),T=function(e){return e.CallEnded="call_ended",e}({}),_=function(e){return e.GroupCallStateChanged="group_call_state_changed",e.ActiveSpeakerChanged="active_speaker_changed",e.CallsChanged="calls_changed",e.UserMediaFeedsChanged="user_media_feeds_changed",e.ScreenshareFeedsChanged="screenshare_feeds_changed",e.LocalScreenshareStateChanged="local_screenshare_state_changed",e.LocalMuteStateChanged="local_mute_state_changed",e.ParticipantsChanged="participants_changed",e.Error="group_call_error",e}({}),w=function(e){return e.ConnectionStats="GroupCall.connection_stats",e.ByteSentStats="GroupCall.byte_sent_stats",e.SummaryStats="GroupCall.summary_stats",e.CallFeedStats="GroupCall.call_feed_stats",e}({}),C=function(e){return e.NoUserMedia="no_user_media",e.UnknownDevice="unknown_device",e.PlaceCallFailed="place_call_failed",e}({});class k extends Error{constructor(e,t,i){i?(super(t+": "+i),(0,s.A)(this,"code",void 0)):(super(t),(0,s.A)(this,"code",void 0)),this.code=e}}class A extends k{constructor(e){super(C.UnknownDevice,"No device found for "+e),this.userId=e}}Error;let M=function(e){return e.LocalCallFeedUninitialized="local_call_feed_uninitialized",e.InitializingLocalCallFeed="initializing_local_call_feed",e.LocalCallFeedInitialized="local_call_feed_initialized",e.Entered="entered",e.Ended="ended",e}({});const x=36e5;function F(e){var t;return(null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId)||e.invitee||null}class O extends n.X{constructor(e,t,i,n,c,u,m,v,p,g=!1,S){var I,E;super(),(0,s.A)(this,"activeSpeakerInterval",1e3),(0,s.A)(this,"retryCallInterval",5e3),(0,s.A)(this,"participantTimeout",15e3),(0,s.A)(this,"pttMaxTransmitTime",2e4),(0,s.A)(this,"activeSpeaker",void 0),(0,s.A)(this,"localCallFeed",void 0),(0,s.A)(this,"localScreenshareFeed",void 0),(0,s.A)(this,"localDesktopCapturerSourceId",void 0),(0,s.A)(this,"userMediaFeeds",[]),(0,s.A)(this,"screenshareFeeds",[]),(0,s.A)(this,"groupCallId",void 0),(0,s.A)(this,"allowCallWithoutVideoAndAudio",void 0),(0,s.A)(this,"calls",new Map),(0,s.A)(this,"callHandlers",new Map),(0,s.A)(this,"activeSpeakerLoopInterval",void 0),(0,s.A)(this,"retryCallLoopInterval",void 0),(0,s.A)(this,"retryCallCounts",new Map),(0,s.A)(this,"reEmitter",void 0),(0,s.A)(this,"transmitTimer",null),(0,s.A)(this,"participantsExpirationTimer",null),(0,s.A)(this,"resendMemberStateTimer",null),(0,s.A)(this,"initWithAudioMuted",!1),(0,s.A)(this,"initWithVideoMuted",!1),(0,s.A)(this,"initCallFeedPromise",void 0),(0,s.A)(this,"_livekitServiceURL",void 0),(0,s.A)(this,"stats",void 0),(0,s.A)(this,"statsCollectIntervalTime",0),(0,s.A)(this,"onConnectionStats",e=>{this.emit(w.ConnectionStats,{report:e})}),(0,s.A)(this,"onByteSentStats",e=>{this.emit(w.ByteSentStats,{report:e})}),(0,s.A)(this,"onSummaryStats",e=>{f.Q.extendSummaryReport(e,this.participants),this.emit(w.SummaryStats,{report:e})}),(0,s.A)(this,"onCallFeedReport",e=>{this.localCallFeed&&(e=y.F.expandCallFeedReport(e,[this.localCallFeed],"from-local-feed"));const t=[];this.forEachCall(i=>{i.callId===e.callId&&i.getFeeds().forEach(e=>t.push(e))}),e=y.F.expandCallFeedReport(e,t,"from-call-feed"),this.emit(w.CallFeedStats,{report:e})}),(0,s.A)(this,"_state",M.LocalCallFeedUninitialized),(0,s.A)(this,"_participants",new Map),(0,s.A)(this,"_creationTs",null),(0,s.A)(this,"_enteredViaAnotherSession",!1),(0,s.A)(this,"onIncomingCall",e=>{var t,i;if(e.roomId!==this.room.roomId)return;if(e.state!==o.iP.Ringing)return void d.vF.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call no longer in ringing state - ignoring`);if(!e.groupCallId||e.groupCallId!==this.groupCallId)return d.vF.log(`GroupCall ${this.groupCallId} onIncomingCall() ignored because it doesn't match the current group call`),void e.reject();const s=null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId;if(void 0===s)return void d.vF.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call with no member - ignoring`);if(this.useLivekit)return void d.vF.info("Received incoming call whilst in signaling-only mode! Ignoring.");const n=null!==(i=this.calls.get(s))&&void 0!==i?i:new Map,r=n.get(e.getOpponentDeviceId());if((null==r?void 0:r.callId)===e.callId)return;d.vF.log(`GroupCall ${this.groupCallId} onIncomingCall() incoming call (userId=${s}, callId=${e.callId})`),r&&r.hangup(o.Il.Replaced,!1),n.set(e.getOpponentDeviceId(),e),this.calls.set(s,n),this.initCall(e);const a=this.getLocalFeeds().map(e=>e.clone());if(!this.callExpected(e))for(const e of a)(0,o.ms)(e.stream.getAudioTracks(),!1),(0,o.ms)(e.stream.getVideoTracks(),!1);e.answerWithCallFeeds(a),this.emit(_.CallsChanged,this.calls)}),(0,s.A)(this,"onRetryCallLoop",()=>{let e=!1;for(const[{userId:s},n]of this.participants){const r=this.calls.get(s);let o=this.retryCallCounts.get(s);for(const[a,d]of n){var t,i;const n=null==r?void 0:r.get(a),l=null!==(t=null===(i=o)||void 0===i?void 0:i.get(a))&&void 0!==t?t:0;(null==n?void 0:n.getOpponentSessionId())!==d.sessionId&&this.wantsOutgoingCall(s,a)&&l<3&&(void 0===o&&(o=new Map,this.retryCallCounts.set(s,o)),o.set(a,l+1),e=!0)}}e&&this.placeOutgoingCalls()}),(0,s.A)(this,"onCallFeedsChanged",e=>{const t=F(e),i=e.getOpponentDeviceId();if(!t)throw new Error("Cannot change call feeds without user id");const s=this.getUserMediaFeed(t,i),n=e.remoteUsermediaFeed,r=n!==s,o=this.calls.get(t),a=null==o?void 0:o.get(i);if((null==a?void 0:a.callId)!==e.callId)return;r&&(!s&&n?this.addUserMediaFeed(n):s&&n?this.replaceUserMediaFeed(s,n):s&&!n&&this.removeUserMediaFeed(s));const d=this.getScreenshareFeed(t,i),l=e.remoteScreensharingFeed;l!==d&&(!d&&l?this.addScreenshareFeed(l):d&&l?this.replaceScreenshareFeed(d,l):d&&!l&&this.removeScreenshareFeed(d))}),(0,s.A)(this,"onCallStateChanged",(e,t,i)=>{var s;if(t===o.iP.Ended)return;const n=this.localCallFeed.isAudioMuted();e.localUsermediaStream&&e.isMicrophoneMuted()!==n&&e.setMicrophoneMuted(n);const r=this.localCallFeed.isVideoMuted();e.localUsermediaStream&&e.isLocalVideoMuted()!==r&&e.setLocalVideoMuted(r);const a=null===(s=e.getOpponentMember())||void 0===s?void 0:s.userId;if(t===o.iP.Connected&&a){const t=this.retryCallCounts.get(a);null==t||t.delete(e.getOpponentDeviceId()),0===(null==t?void 0:t.size)&&this.retryCallCounts.delete(a)}}),(0,s.A)(this,"onCallHangup",e=>{var t,i;if(e.hangupReason===o.Il.Replaced)return;const s=null!==(t=null===(i=e.getOpponentMember())||void 0===i?void 0:i.userId)&&void 0!==t?t:this.room.getMember(e.invitee).userId,n=this.calls.get(s);(null==n?void 0:n.get(e.getOpponentDeviceId()))===e&&(this.disposeCall(e,e.hangupReason),n.delete(e.getOpponentDeviceId()),0===n.size&&this.calls.delete(s),this.emit(_.CallsChanged,this.calls))}),(0,s.A)(this,"onCallReplaced",(e,t)=>{const i=e.getOpponentMember().userId;let s=this.calls.get(i);void 0===s&&(s=new Map,this.calls.set(i,s)),e.hangup(o.Il.Replaced,!1),this.initCall(t),s.set(e.getOpponentDeviceId(),t),this.emit(_.CallsChanged,this.calls)}),(0,s.A)(this,"onActiveSpeakerLoop",()=>{let e,t;for(const i of this.userMediaFeeds){if(i.isLocal()&&this.userMediaFeeds.length>1)continue;const s=i.speakingVolumeSamples.reduce((e,t)=>e+Math.max(t,r.Tw))/i.speakingVolumeSamples.length;(!e||s>e)&&(e=s,t=i)}t&&this.activeSpeaker!==t&&e&&e>r.Tw&&(this.activeSpeaker=t,this.emit(_.ActiveSpeakerChanged,this.activeSpeaker))}),(0,s.A)(this,"onRoomState",()=>this.updateParticipants()),(0,s.A)(this,"onParticipantsChanged",()=>{this.forEachCall(e=>{const t=this.callExpected(e);for(const i of e.getLocalFeeds())(0,o.ms)(i.stream.getAudioTracks(),!i.isAudioMuted()&&t),(0,o.ms)(i.stream.getVideoTracks(),!i.isVideoMuted()&&t)}),this.state!==M.Entered||this.useLivekit||this.placeOutgoingCalls()}),(0,s.A)(this,"onStateChanged",(e,t)=>{e!==M.Entered&&t!==M.Entered&&e!==M.Ended||(this.updateParticipants(),this.updateMemberState().catch(e=>d.vF.error(`GroupCall ${this.groupCallId} onStateChanged() failed to update member state devices"`,e)))}),(0,s.A)(this,"onLocalFeedsChanged",()=>{this.state===M.Entered&&this.updateMemberState().catch(e=>d.vF.error(`GroupCall ${this.groupCallId} onLocalFeedsChanged() failed to update member state feeds`,e))}),this.client=e,this.room=t,this.type=i,this.isPtt=n,this.intent=c,this.dataChannelsEnabled=m,this.dataChannelOptions=v,this.useLivekit=g,this.reEmitter=new l.K(this),this.groupCallId=null!=u?u:(0,o.WE)(),this._livekitServiceURL=S,this.creationTs=null!==(I=null===(E=t.currentState.getStateEvents(h.Bx.GroupCallPrefix,this.groupCallId))||void 0===E?void 0:E.getTs())&&void 0!==I?I:null,this.updateParticipants(),t.on(a.f.Update,this.onRoomState),this.on(_.ParticipantsChanged,this.onParticipantsChanged),this.on(_.GroupCallStateChanged,this.onStateChanged),this.on(_.LocalScreenshareStateChanged,this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!p}async create(){return this.creationTs=Date.now(),this.client.groupCallEventHandler.groupCalls.set(this.room.roomId,this),this.client.emit(m.o.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,h.Bx.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(_.GroupCallStateChanged,e,t))}get participants(){return this._participants}set participants(e){const t=this._participants,i=(e,t)=>e.sessionId===t.sessionId&&e.screensharing===t.screensharing;(0,v.kg)(e,t,(e,t)=>(0,v.kg)(e,t,i))||(this._participants=e,this.emit(_.ParticipantsChanged,e))}get creationTs(){return this._creationTs}set creationTs(e){this._creationTs=e}get enteredViaAnotherSession(){return this._enteredViaAnotherSession}set enteredViaAnotherSession(e){this._enteredViaAnotherSession=e,this.updateParticipants()}forEachCall(e){for(const t of this.calls.values())for(const i of t.values())e(i)}getLocalFeeds(){const e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e,t;return null!==(e=null===(t=this.participants.get(this.room.getMember(this.client.getUserId())))||void 0===t?void 0:t.has(this.client.getDeviceId()))&&void 0!==e&&e}callExpected(e){var t;const i=F(e),s=null===i?null:this.room.getMember(i),n=e.getOpponentDeviceId();return null!==s&&void 0!==n&&void 0!==(null===(t=this.participants.get(s))||void 0===t?void 0:t.get(n))}async initLocalCallFeed(){if(this.useLivekit)d.vF.info("Livekit group call: not starting local call feed.");else{if(this.state!==M.LocalCallFeedUninitialized)throw new Error(`Cannot initialize local call feed in the "${this.state}" state.`);if(this.state=M.InitializingLocalCallFeed,this.initCallFeedPromise)return this.initCallFeedPromise;try{this.initCallFeedPromise=this.initLocalCallFeedInternal(),await this.initCallFeedPromise}finally{this.initCallFeedPromise=void 0}}}async initLocalCallFeedInternal(){let e;d.vF.log(`GroupCall ${this.groupCallId} initLocalCallFeedInternal() running`);try{e=await this.client.getMediaHandler().getUserMediaStream(!0,this.type===b.Video)}catch(t){if(!this.allowCallWithoutVideoAndAudio)throw this.state=M.LocalCallFeedUninitialized,t;e=new MediaStream}if(this._state!==M.InitializingLocalCallFeed)throw this.client.getMediaHandler().stopUserMediaStream(e),new Error("Group call disposed while gathering media stream");const t=new r.Hh({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:e,purpose:c.h.Usermedia,audioMuted:this.initWithAudioMuted||0===e.getAudioTracks().length||this.isPtt,videoMuted:this.initWithVideoMuted||0===e.getVideoTracks().length});(0,o.ms)(e.getAudioTracks(),!t.isAudioMuted()),(0,o.ms)(e.getVideoTracks(),!t.isVideoMuted()),this.localCallFeed=t,this.addUserMediaFeed(t),this.state=M.LocalCallFeedInitialized}async updateLocalUsermediaStream(e){if(this.localCallFeed){const t=this.localCallFeed.stream;this.localCallFeed.setNewStream(e);const i=this.localCallFeed.isAudioMuted(),s=this.localCallFeed.isVideoMuted();d.vF.log(`GroupCall ${this.groupCallId} updateLocalUsermediaStream() (oldStreamId=${t.id}, newStreamId=${e.id}, micShouldBeMuted=${i}, vidShouldBeMuted=${s})`),(0,o.ms)(e.getAudioTracks(),!i),(0,o.ms)(e.getVideoTracks(),!s),this.client.getMediaHandler().stopUserMediaStream(t)}}async enter(){if(this.state===M.LocalCallFeedUninitialized)await this.initLocalCallFeed();else if(this.state!==M.LocalCallFeedInitialized)throw new Error(`Cannot enter call in the "${this.state}" state`);d.vF.log(`GroupCall ${this.groupCallId} enter() running`),this.state=M.Entered,this.client.on(u.B.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(),null!==this.transmitTimer&&(clearTimeout(this.transmitTimer),this.transmitTimer=null),void 0!==this.retryCallLoopInterval&&(clearInterval(this.retryCallLoopInterval),this.retryCallLoopInterval=void 0),null!==this.participantsExpirationTimer&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===M.Entered&&(this.forEachCall(e=>e.hangup(o.Il.UserHangup,!1)),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(u.B.Incoming,this.onIncomingCall),null===(e=this.stats)||void 0===e||e.stop())}leave(){this.dispose(),this.state=M.LocalCallFeedUninitialized}async terminate(e=!0){if(this.dispose(),this.room.off(a.f.Update,this.onRoomState),this.client.groupCallEventHandler.groupCalls.delete(this.room.roomId),this.client.emit(m.o.Ended,this),this.state=M.Ended,e){const e=this.room.currentState.getStateEvents(h.Bx.GroupCallPrefix,this.groupCallId);await this.client.sendStateEvent(this.room.roomId,h.Bx.GroupCallPrefix,E(E({},e.getContent()),{},{"m.terminated":T.CallEnded}),this.groupCallId)}}isLocalVideoMuted(){return!this.localCallFeed||this.localCallFeed.isVideoMuted()}isMicrophoneMuted(){return!this.localCallFeed||this.localCallFeed.isAudioMuted()}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()&&(null!==this.transmitTimer&&clearTimeout(this.transmitTimer),this.transmitTimer=null)),this.forEachCall(t=>{var i;return null===(i=t.localUsermediaFeed)||void 0===i?void 0:i.setAudioVideoMuted(e,null)});const i=async()=>{const e=[];this.forEachCall(t=>e.push(t.sendMetadataUpdate())),await Promise.all(e).catch(e=>d.vF.info(`GroupCall ${this.groupCallId} setMicrophoneMuted() failed to send some metadata updates`,e))};if(t&&await i(),this.localCallFeed){d.vF.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() (streamId=${this.localCallFeed.stream.id}, muted=${e})`);if(!await this.checkAudioPermissionIfNecessary(e))return!1;this.localCallFeed.setAudioVideoMuted(e,null),(0,o.ms)(this.localCallFeed.stream.getAudioTracks(),!e)}else d.vF.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no stream muted (muted=${e})`),this.initWithAudioMuted=e;return this.forEachCall(t=>(0,o.ms)(t.localUsermediaFeed.stream.getAudioTracks(),!e&&this.callExpected(t))),this.emit(_.LocalMuteStateChanged,e,this.isLocalVideoMuted()),t||await i(),!0}async checkAudioPermissionIfNecessary(e){try{if(!e&&this.localCallFeed&&!this.localCallFeed.hasAudioTrack){const t=await this.client.getMediaHandler().getUserMediaStream(!0,!this.localCallFeed.isVideoMuted());if(0===(null==t?void 0:t.getTracks().length))return d.vF.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device to receive local stream, muted=${e}`),!1}}catch{return d.vF.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){d.vF.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() (stream=${this.localCallFeed.stream.id}, muted=${e})`);try{const t=await this.client.getMediaHandler().getUserMediaStream(!0,!e);await this.updateLocalUsermediaStream(t),this.localCallFeed.setAudioVideoMuted(null,e),(0,o.ms)(this.localCallFeed.stream.getVideoTracks(),!e)}catch{return d.vF.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no device or permission to receive local stream, muted=${e}`),!1}}else d.vF.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no stream muted (muted=${e})`),this.initWithVideoMuted=e;const t=[];return this.forEachCall(i=>t.push(i.setLocalVideoMuted(e))),await Promise.all(t),this.forEachCall(t=>(0,o.ms)(t.localUsermediaFeed.stream.getVideoTracks(),!e&&this.callExpected(t))),this.emit(_.LocalMuteStateChanged,this.isMicrophoneMuted(),e),!0}async setScreensharingEnabled(e,t={}){if(e===this.isScreensharing())return e;if(!e)return this.forEachCall(e=>{e.localScreensharingFeed&&e.removeLocalFeed(e.localScreensharingFeed)}),this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0,this.emit(_.LocalScreenshareStateChanged,!1,void 0,void 0),!1;try{d.vF.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() is asking for screensharing permissions`);const e=await this.client.getMediaHandler().getScreensharingStream(t);for(const t of e.getTracks()){const e=()=>{this.setScreensharingEnabled(!1),t.removeEventListener("ended",e)};t.addEventListener("ended",e)}return d.vF.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls`),this.localDesktopCapturerSourceId=t.desktopCapturerSourceId,this.localScreenshareFeed=new r.Hh({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:e,purpose:c.h.Screenshare,audioMuted:!1,videoMuted:!1}),this.addScreenshareFeed(this.localScreenshareFeed),this.emit(_.LocalScreenshareStateChanged,!0,this.localScreenshareFeed,this.localDesktopCapturerSourceId),this.forEachCall(e=>e.pushLocalFeed(this.localScreenshareFeed.clone())),!0}catch(e){if(t.throwOnFail)throw e;return d.vF.error(`GroupCall ${this.groupCallId} setScreensharingEnabled() enabling screensharing error`,e),this.emit(_.Error,new k(C.NoUserMedia,"Failed to get screen-sharing stream: ",e)),!1}}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,t){const i=this.client.getUserId(),s=this.client.getDeviceId();return e>=i&&(e!==i||t>s)}placeOutgoingCalls(){let e=!1;for(const[{userId:i},s]of this.participants){var t;const n=null!==(t=this.calls.get(i))&&void 0!==t?t:new Map;for(const[t,r]of s){const s=n.get(t);if((null==s?void 0:s.getOpponentSessionId())!==r.sessionId&&this.wantsOutgoingCall(i,t)){e=!0,void 0!==s&&(d.vF.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() replacing call (userId=${i}, deviceId=${t}, callId=${s.callId})`),s.hangup(o.Il.NewSession,!1));const a=(0,o.sv)(this.client,this.room.roomId,{invitee:i,opponentDeviceId:t,opponentSessionId:r.sessionId,groupCallId:this.groupCallId});null===a?(d.vF.error(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to create call (userId=${i}, device=${t})`),n.delete(t)):(this.initCall(a),n.set(t,a),d.vF.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() placing call (userId=${i}, deviceId=${t}, sessionId=${r.sessionId})`),a.placeCallWithCallFeeds(this.getLocalFeeds().map(e=>e.clone()),r.screensharing).then(()=>{this.dataChannelsEnabled&&a.createDataChannel("datachannel",this.dataChannelOptions)}).catch(e=>{d.vF.warn(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to place call (userId=${i})`,e),e instanceof o.RA&&e.code===C.UnknownDevice?this.emit(_.Error,e):this.emit(_.Error,new k(C.PlaceCallFailed,`Failed to place call to ${i}`)),a.hangup(o.Il.SignallingFailed,!1),n.get(t)===a&&n.delete(t)}))}}n.size>0?this.calls.set(i,n):this.calls.delete(i)}e&&this.emit(_.CallsChanged,this.calls)}getMemberStateEvents(e){return void 0===e?this.room.currentState.getStateEvents(h.Bx.GroupCallMemberPrefix):this.room.currentState.getStateEvents(h.Bx.GroupCallMemberPrefix,e)}initCall(e){const t=F(e);if(!t)throw new Error("Cannot init call without user id");const i=()=>this.onCallFeedsChanged(e),s=(t,i)=>this.onCallStateChanged(e,t,i),n=this.onCallHangup,r=t=>this.onCallReplaced(e,t);let a=this.callHandlers.get(t);void 0===a&&(a=new Map,this.callHandlers.set(t,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:i,onCallStateChanged:s,onCallHangup:n,onCallReplaced:r}),e.on(o.$E.FeedsChanged,i),e.on(o.$E.State,s),e.on(o.$E.Hangup,n),e.on(o.$E.Replaced,r),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(o.$E)),e.initStats(this.getGroupCallStats()),i()}disposeCall(e,t){const i=F(e),s=e.getOpponentDeviceId();if(!i)throw new Error("Cannot dispose call without user id");const n=this.callHandlers.get(i),{onCallFeedsChanged:r,onCallStateChanged:a,onCallHangup:d,onCallReplaced:l}=n.get(s);if(e.removeListener(o.$E.FeedsChanged,r),e.removeListener(o.$E.State,a),e.removeListener(o.$E.Hangup,d),e.removeListener(o.$E.Replaced,l),n.delete(i),0===n.size&&this.callHandlers.delete(i),e.hangupReason===o.Il.Replaced)return;const c=this.getUserMediaFeed(i,s);c&&this.removeUserMediaFeed(c);const h=this.getScreenshareFeed(i,s);h&&this.removeScreenshareFeed(h)}getUserMediaFeed(e,t){return this.userMediaFeeds.find(i=>i.userId===e&&i.deviceId===t)}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit(_.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(e,t){const i=this.userMediaFeeds.findIndex(t=>t.userId===e.userId&&t.deviceId===e.deviceId);if(-1===i)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(i,1,t),e.dispose(),t.measureVolumeActivity(!0),this.emit(_.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(e){const t=this.userMediaFeeds.findIndex(t=>t.userId===e.userId&&t.deviceId===e.deviceId);if(-1===t)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(t,1),e.dispose(),this.emit(_.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(_.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(e,t){return this.screenshareFeeds.find(i=>i.userId===e&&i.deviceId===t)}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit(_.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(e,t){const i=this.screenshareFeeds.findIndex(t=>t.userId===e.userId&&t.deviceId===e.deviceId);if(-1===i)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(i,1,t),e.dispose(),this.emit(_.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(e){const t=this.screenshareFeeds.findIndex(t=>t.userId===e.userId&&t.deviceId===e.deviceId);if(-1===t)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(t,1),e.dispose(),this.emit(_.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){const e=this.room.getMember(this.client.getSafeUserId());if(!e)return void d.vF.warn(`GroupCall ${this.groupCallId} updateParticipants() tried to update participants before local room member is available`);if(null!==this.participantsExpirationTimer&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===M.Ended)return void(this.participants=new Map);const t=new Map,i=Date.now(),s=this.state===M.Entered||this.enteredViaAnotherSession;let n=1/0;for(const e of this.getMemberStateEvents()){const r=this.room.getMember(e.getStateKey()),o=e.getContent(),a=(Array.isArray(o["m.calls"])?o["m.calls"]:[]).find(e=>e["m.call_id"]===this.groupCallId);let d=(Array.isArray(null==a?void 0:a["m.devices"])?a["m.devices"]:[]).filter(e=>"string"==typeof e.device_id&&"string"==typeof e.session_id&&"number"==typeof e.expires_ts&&e.expires_ts>i&&Array.isArray(e.feeds));if(s||(null==r?void 0:r.userId)!==this.client.getUserId()||(d=d.filter(e=>e.device_id!==this.client.getDeviceId())),d.length>0&&(null==r?void 0:r.membership)===S.O.Join){const e=new Map;t.set(r,e);for(const t of d)e.set(t.device_id,{sessionId:t.session_id,screensharing:t.feeds.some(e=>e.purpose===c.h.Screenshare)}),t.expires_ts<n&&(n=t.expires_ts)}}if(s){let i=t.get(e);void 0===i&&(i=new Map,t.set(e,i)),i.has(this.client.getDeviceId())||i.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some(e=>e.purpose===c.h.Screenshare)})}this.participants=t,n<1/0&&(this.participantsExpirationTimer=setTimeout(()=>this.updateParticipants(),n-i))}async updateDevices(e,t=!1){var i;const s=Date.now(),n=this.client.getUserId(),r=this.getMemberStateEvents(n),o=null!==(i=null==r?void 0:r.getContent())&&void 0!==i?i:{},a=Array.isArray(o["m.calls"])?o["m.calls"]:[];let d=null;const l=[];for(const e of a)e["m.call_id"]===this.groupCallId?d=e:l.push(e);null===d&&(d={});const c=e((Array.isArray(d["m.devices"])?d["m.devices"]:[]).filter(e=>"string"==typeof e.device_id&&"string"==typeof e.session_id&&"number"==typeof e.expires_ts&&e.expires_ts>s&&Array.isArray(e.feeds)));if(null===c)return;const u=[...l];c.length>0&&u.push(E(E({},d),{},{"m.call_id":this.groupCallId,"m.devices":c}));const m={"m.calls":u};await this.client.sendStateEvent(this.room.roomId,h.Bx.GroupCallMemberPrefix,m,n,{keepAlive:t})}async addDeviceToMemberState(){await this.updateDevices(e=>[...e.filter(e=>e.device_id!==this.client.getDeviceId()),{device_id:this.client.getDeviceId(),session_id:this.client.getSessionId(),expires_ts:Date.now()+x,feeds:this.getLocalFeeds().map(e=>({purpose:e.purpose}))}])}async updateMemberState(){null!==this.resendMemberStateTimer&&(clearInterval(this.resendMemberStateTimer),this.resendMemberStateTimer=null),this.state===M.Entered?(await this.addDeviceToMemberState(),this.resendMemberStateTimer=setInterval(async()=>{d.vF.log(`GroupCall ${this.groupCallId} updateMemberState() resending call member state"`);try{await this.addDeviceToMemberState()}catch(e){d.vF.error(`GroupCall ${this.groupCallId} updateMemberState() failed to resend call member state`,e)}},27e5)):await this.updateDevices(e=>e.filter(e=>e.device_id!==this.client.getDeviceId()),!0)}async cleanMemberState(){const{devices:e}=await this.client.getDevices(),t=new Map(e.map(e=>[e.device_id,e]));await this.updateDevices(e=>{const i=e.filter(e=>{const i=t.get(e.device_id);return void 0!==(null==i?void 0:i.last_seen_ts)&&!(e.device_id===this.client.getDeviceId()&&this.state!==M.Entered&&!this.enteredViaAnotherSession)});return i.length===e.length?null:i})}getGroupCallStats(){if(void 0===this.stats){const e=this.client.getUserId()||"unknown";this.stats=new p.r(this.groupCallId,e,this.statsCollectIntervalTime),this.stats.reports.on(g.I.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(g.I.BYTE_SENT_STATS,this.onByteSentStats),this.stats.reports.on(g.I.SUMMARY_STATS,this.onSummaryStats),this.stats.reports.on(g.I.CALL_FEED_REPORT,this.onCallFeedReport)}return this.stats}setGroupCallStatsInterval(e){this.statsCollectIntervalTime=e,void 0!==this.stats&&(this.stats.stop(),this.stats.setInterval(e),e>0&&this.stats.start())}}},"./node_modules/matrix-js-sdk/src/webrtc/mediaHandler.ts":(e,t,i)=>{"use strict";i.d(t,{L:()=>d});var s=i("./node_modules/@babel/runtime/helpers/esm/defineProperty.js"),n=i("./node_modules/matrix-js-sdk/src/models/typed-event-emitter.ts"),r=i("./node_modules/matrix-js-sdk/src/webrtc/groupCall.ts"),o=i("./node_modules/matrix-js-sdk/src/logger.ts");let a=function(e){return e.LocalStreamsChanged="local_streams_changed",e}({});class d extends n.X{constructor(e){super(),(0,s.A)(this,"audioInput",void 0),(0,s.A)(this,"audioSettings",void 0),(0,s.A)(this,"videoInput",void 0),(0,s.A)(this,"localUserMediaStream",void 0),(0,s.A)(this,"userMediaStreams",[]),(0,s.A)(this,"screensharingStreams",[]),(0,s.A)(this,"getMediaStreamPromise",void 0),this.client=e}restoreMediaSettings(e,t){this.audioInput=e,this.videoInput=t}async setAudioInput(e){o.vF.info(`MediaHandler setAudioInput() running (deviceId=${e})`),this.audioInput!==e&&(this.audioInput=e,await this.updateLocalUsermediaStreams())}async setAudioSettings(e){o.vF.info(`MediaHandler setAudioSettings() running (opts=${JSON.stringify(e)})`),this.audioSettings=Object.assign({},e),await this.updateLocalUsermediaStreams()}async setVideoInput(e){o.vF.info(`MediaHandler setVideoInput() running (deviceId=${e})`),this.videoInput!==e&&(this.videoInput=e,await this.updateLocalUsermediaStreams())}async setMediaInputs(e,t){o.vF.log(`MediaHandler setMediaInputs() running (audioInput: ${e} videoInput: ${t})`),this.audioInput=e,this.videoInput=t,await this.updateLocalUsermediaStreams()}async updateLocalUsermediaStreams(){if(0===this.userMediaStreams.length)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 e of this.userMediaStreams){o.vF.log(`MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=${e.id})`);for(const t of e.getTracks())t.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:i,video:s}=e.get(t.callId);o.vF.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=${t.callId})`);const n=await this.getUserMediaStream(i,s);t.callHasEnded()||await t.updateLocalUsermediaStream(n)}for(const e of this.client.groupCallEventHandler.groupCalls.values()){if(!e.localCallFeed)continue;o.vF.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=${e.groupCallId})`);const t=await this.getUserMediaStream(!0,e.type===r.Ad.Video);e.state!==r.F_.Ended&&await e.updateLocalUsermediaStream(t)}this.emit(a.LocalStreamsChanged)}async hasAudioDevice(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(e=>"audioinput"===e.kind).length>0}catch(e){return o.vF.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}async hasVideoDevice(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(e=>"videoinput"===e.kind).length>0}catch(e){return o.vF.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}async getUserMediaStream(e,t,i=!0){return this.getMediaStreamPromise?this.getMediaStreamPromise=this.getMediaStreamPromise.then(()=>this.getUserMediaStreamInternal(e,t,i)):this.getMediaStreamPromise=this.getUserMediaStreamInternal(e,t,i),this.getMediaStreamPromise}async getUserMediaStreamInternal(e,t,i){const s=e&&await this.hasAudioDevice(),n=t&&await this.hasVideoDevice();let r,d=!0;var l,c;this.localUserMediaStream?(s!==this.localUserMediaStream.getAudioTracks().length>0&&(d=!1),n!==this.localUserMediaStream.getVideoTracks().length>0&&(d=!1),s&&(null===(l=this.localUserMediaStream.getAudioTracks()[0])||void 0===l||null===(l=l.getSettings())||void 0===l?void 0:l.deviceId)!==this.audioInput&&(d=!1),n&&(null===(c=this.localUserMediaStream.getVideoTracks()[0])||void 0===c||null===(c=c.getSettings())||void 0===c?void 0:c.deviceId)!==this.videoInput&&(d=!1)):d=!1;if(d){var h;if(r=this.localUserMediaStream.clone(),o.vF.log(`MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=${null===(h=this.localUserMediaStream)||void 0===h?void 0:h.id} newStreamId=${r.id} shouldRequestAudio=${s} shouldRequestVideo=${n})`),!s)for(const e of r.getAudioTracks())r.removeTrack(e);if(!n)for(const e of r.getVideoTracks())r.removeTrack(e)}else{const e=this.getUserMediaContraints(s,n);r=await navigator.mediaDevices.getUserMedia(e),o.vF.log(`MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=${r.id}, shouldRequestAudio=${s}, shouldRequestVideo=${n}, constraints=${JSON.stringify(e)})`);for(const e of r.getTracks()){const t=e.getSettings();"audio"===e.kind?this.audioInput=t.deviceId:"video"===e.kind&&(this.videoInput=t.deviceId)}i&&(this.localUserMediaStream=r)}return i&&this.userMediaStreams.push(r),this.emit(a.LocalStreamsChanged),r}stopUserMediaStream(e){o.vF.log(`MediaHandler stopUserMediaStream() stopping (streamId=${e.id})`);for(const t of e.getTracks())t.stop();const t=this.userMediaStreams.indexOf(e);if(-1!==t&&(o.vF.debug(`MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=${e.id})`,e.id),this.userMediaStreams.splice(t,1)),this.emit(a.LocalStreamsChanged),this.localUserMediaStream===e)this.localUserMediaStream=void 0;else for(const t of e.getTracks()){var i;if(null!==(i=this.localUserMediaStream)&&void 0!==i&&i.getTrackById(t.id)){this.stopUserMediaStream(this.localUserMediaStream);break}}}async getScreensharingStream(e={},t=!0){let i;if(0===this.screensharingStreams.length){const t=this.getScreenshareContraints(e);e.desktopCapturerSourceId?(o.vF.debug(`MediaHandler getScreensharingStream() calling getUserMedia() (opts=${JSON.stringify(e)})`),i=await navigator.mediaDevices.getUserMedia(t)):(o.vF.debug(`MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=${JSON.stringify(e)})`),i=await navigator.mediaDevices.getDisplayMedia(t))}else{const e=this.screensharingStreams[this.screensharingStreams.length-1];o.vF.log(`MediaHandler getScreensharingStream() cloning (streamId=${e.id})`),i=e.clone()}return t&&this.screensharingStreams.push(i),this.emit(a.LocalStreamsChanged),i}stopScreensharingStream(e){o.vF.debug(`MediaHandler stopScreensharingStream() stopping stream (streamId=${e.id})`);for(const t of e.getTracks())t.stop();const t=this.screensharingStreams.indexOf(e);-1!==t&&(o.vF.debug(`MediaHandler stopScreensharingStream() splicing stream out (streamId=${e.id})`),this.screensharingStreams.splice(t,1)),this.emit(a.LocalStreamsChanged)}stopAllStreams(){for(const e of this.userMediaStreams){o.vF.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(a.LocalStreamsChanged)}getUserMediaContraints(e,t){const i=!!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},video:!!t&&{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:i?{exact:640}:{ideal:640},height:i?{exact:360}:{ideal:360}}}}getScreenshareContraints(e){const{desktopCapturerSourceId:t,audio:i}=e;return t?{audio:null!=i&&i,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t}}}:{audio:null!=i&&i,video:!0}}}},"./node_modules/matrix-js-sdk/src/webrtc/stats/statsReport.ts":(e,t,i)=>{"use strict";i.d(t,{I:()=>s});let s=function(e){return e.CONNECTION_STATS="StatsReport.connection_stats",e.CALL_FEED_REPORT="StatsReport.call_feed_report",e.BYTE_SENT_STATS="StatsReport.byte_sent_stats",e.SUMMARY_STATS="StatsReport.summary_stats",e}({})},"./node_modules/p-retry/index.js":(e,t,i)=>{"use strict";i.d(t,{lc:()=>a,Ay:()=>c});const s=Object.prototype.toString,n=e=>"[object Error]"===s.call(e),r=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function o(e,t,{min:i=0,allowInfinity:s=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${s?" or Infinity":""}.`);if(!s&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<i)throw new TypeError(`Expected \`${e}\` to be ≥ ${i}.`)}}class a extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const d=(e,t,i)=>{const s=i.retries-(t-1);return Object.freeze({error:e,attemptNumber:t,retriesLeft:s})};async function l(e,t,i,s,o){let l=e;if(l instanceof Error||(l=new TypeError(`Non-error was thrown: "${l}". You should only throw errors.`)),l instanceof a)throw l.originalError;if(l instanceof TypeError&&!function(e){if(!e||!n(e)||"TypeError"!==e.name||"string"!=typeof e.message)return!1;const{message:t,stack:i}=e;return"Load failed"===t?void 0===i||"__sentry_captured__"in e:!!t.startsWith("error sending request for url")||r.has(t)}(l))throw l;const c=d(l,t,i);await i.onFailedAttempt(c);const h=Date.now();if(h-s>=o||t>=i.retries+1||!await i.shouldRetry(c))throw l;const u=function(e,t){const i=t.randomize?Math.random()+1:1;let s=Math.round(i*Math.max(t.minTimeout,1)*t.factor**(e-1));return s=Math.min(s,t.maxTimeout),s}(t,i),m=o-(h-s);if(m<=0)throw l;const v=Math.min(u,m);v>0&&await new Promise((e,t)=>{const s=()=>{clearTimeout(n),i.signal?.removeEventListener("abort",s),t(i.signal.reason)},n=setTimeout(()=>{i.signal?.removeEventListener("abort",s),e()},v);i.unref&&n.unref?.(),i.signal?.addEventListener("abort",s,{once:!0})}),i.signal?.throwIfAborted()}async function c(e,t={}){if(function(e){if("number"==typeof e){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==e)throw new TypeError("Expected `retries` to be a number or Infinity.")}((t={...t}).retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,o("factor",t.factor,{min:0,allowInfinity:!1}),o("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),o("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0});const i=t.maxRetryTime??Number.POSITIVE_INFINITY;o("maxRetryTime",i,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let s=0;const n=Date.now(),r=i;for(;s<t.retries+1;){s++;try{t.signal?.throwIfAborted();const i=await e(s);return t.signal?.throwIfAborted(),i}catch(e){await l(e,s,t,n,r)}}throw new Error("Retry attempts exhausted without throwing an error.")}},"./node_modules/unhomoglyph/index.js":(e,t,i)=>{"use strict";var s=i("./node_modules/unhomoglyph/data.json");var n=RegExp(Object.keys(s).map(function(e){return e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}).join("|"),"g");function r(e){return s[e]}e.exports=function(e){return e.replace(n,r)}}}]);
|
|
//# sourceMappingURL=4387.js.map
|