@unwanted/matrix-sdk-mini 34.12.0-4 → 34.12.0-5

Sign up to get free protection for your applications and to get access to all the features.
package/lib/client.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["SyncApi","SyncState","EventStatus","MatrixEvent","MatrixEventEvent","StubStore","Filter","utils","noUnsafeEventProps","replaceParam","sleep","Direction","EventTimeline","PushProcessor","AutoDiscovery","encodeUnpaddedBase64Url","TypedReEmitter","logger","SERVICE_TYPES","ClientPrefix","IdentityPrefix","MatrixError","MatrixHttpApi","MediaPrefix","Method","retryNetworkOperation","User","UserEvent","getHttpUriForMxc","SearchResult","ContentHelpers","NotificationCountType","EventType","LOCAL_NOTIFICATION_SETTINGS_PREFIX","MSC3912_RELATION_BASED_REDACTIONS_PROP","MsgType","PUSHER_ENABLED","RelationType","RoomCreateTypeField","RoomType","UNSTABLE_MSC3088_ENABLED","UNSTABLE_MSC3088_PURPOSE","UNSTABLE_MSC3089_TREE_SUBTYPE","GuestAccess","HistoryVisibility","Preset","eventMapperFor","randomString","DEFAULT_TREE_POWER_LEVELS_TEMPLATE","MSC3089TreeSpace","SearchOrderBy","PushRuleActionName","PushRuleKind","TypedEventEmitter","MAIN_ROOM_TIMELINE","ReceiptType","SlidingSyncSdk","determineFeatureSupport","FeatureSupport","Thread","THREAD_RELATION_TYPE","ThreadFilterType","threadFilterTypeToFilter","M_BEACON_INFO","NamespacedValue","UnstableValue","ToDeviceMessageQueue","IgnoredInvites","buildFeatureSupportMap","Feature","ServerSupport","getRelationsThreadFilter","KnownMembership","ServerCapabilities","sha256","SCROLLBACK_DELAY_MS","UNSTABLE_MSC3852_LAST_SEEN_UA","PendingEventOrdering","GET_LOGIN_TOKEN_CAPABILITY","UNSTABLE_MSC2666_SHARED_ROOMS","UNSTABLE_MSC2666_MUTUAL_ROOMS","UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS","UNSTABLE_MSC4140_DELAYED_EVENTS","UNSTABLE_MSC4133_EXTENDED_PROFILES","EVENT_ID_PREFIX","ClientEvent","SSO_ACTION_PARAM","MatrixClient","constructor","opts","_opts$logger","_opts$usingExternalCr","_this","this","_defineProperty","Map","Set","isInitialSyncComplete","_this$getRooms","unreadRooms","getRooms","filter","room","getUnreadNotificationCount","Total","currentUserId","getSafeUserId","fixupNotifications","off","Sync","fixupRoomNotifications","baseUrl","ensureNoTrailingSlash","idBaseUrl","identityServer","usingExternalCrypto","store","deviceId","sessionId","userId","credentials","http","fetchFn","accessToken","refreshToken","tokenRefreshFunction","prefix","V3","onlyData","extraParams","queryParams","localTimeoutMs","useAuthorizationHeader","deviceToImport","warn","pickleKey","useLivekitForGroupCalls","Boolean","scheduler","setProcessFunction","_ref","_asyncToGenerator","eventToSend","getRoom","getRoomId","status","SENDING","updatePendingEventStatus","res","sendEventHttpRequest","updatePendingEvent","SENT","event_id","_x","apply","arguments","serverCapabilitiesService","on","timelineSupport","verificationMethods","iceCandidatePoolSize","undefined","fallbackICEServerAllowed","isVoipWithNoMediaAllowed","livekitServiceURL","roomNameGenerator","toDeviceMessageQueue","ignoredInvites","setMaxListeners","newStore","_store","setUserCreator","createUser","startClient","_this2","clientRunning","getUserId","storeUser","syncApi","error","stop","getVersions","threads","list","fwdPagination","doesServerSupportThread","setServerSideSupport","setServerSideListSupport","setServerSideFwdPaginationSupport","e","clientOpts","slidingSync","buildSyncApiOptions","sync","catch","info","clientWellKnownPollPeriod","clientWellKnownIntervalID","setInterval","fetchClientWellKnown","start","canResetEntireTimeline","roomId","canResetTimelineCallback","stopClient","_this$syncApi","_this$peekSync","debug","peekSync","stopPeeking","globalThis","clearInterval","clearStores","Error","promises","push","deleteAllData","Promise","all","then","getDomain","replace","getUserIdLocalpart","split","substring","getDeviceId","getSessionId","getLivekitServiceURL","setLivekitServiceURL","newURL","getSyncState","_this$syncApi$getSync","_this$syncApi2","getSyncStateData","state","Prepared","Syncing","isGuest","isGuestAccount","setGuest","guest","getScheduler","retryImmediately","_this$syncApi$retryIm","_this$syncApi3","sendQueue","getNotifTimelineSet","notifTimelineSet","setNotifTimelineSet","set","getCapabilities","_this3","caps","getCachedCapabilities","fetchCapabilities","uploadKeys","_this4","getMediaConfig","authedRequest","Get","getVisibleRooms","msc3946ProcessDynamicPredecessor","length","allRooms","replacedRooms","r","_r$findPredecessor","predecessor","findPredecessor","add","tombstone","currentState","getStateEvents","RoomTombstone","has","getUser","getUsers","setAccountData","eventType","content","path","encodeUri","$userId","$type","Put","getAccountData","getAccountDataFromServer","_this5","event","getContent","_data","data","errcode","deleteAccountData","_this6","msc3391DeleteAccountDataServerSupport","canSupport","get","AccountDataDeletion","Unsupported","options","Unstable","Delete","getIgnoredUsers","Object","keys","setIgnoredUsers","userIds","ignored_users","forEach","u","isUserIgnored","includes","joinRoom","roomIdOrAlias","_arguments","_this7","syncRoom","hasMembershipState","Join","signPromise","resolve","inviteSignUrl","url","URL","searchParams","requestOtherUrl","Post","viaServers","server_name","via","signedInviteObj","third_party_signed","$roomid","room_id","resolvedRoom","createRoom","knockRoom","Knock","$roomIdOrAlias","body","reason","resendEvent","encryptAndSendEvent","cancelPendingEvent","QUEUED","NOT_SENT","ENCRYPTING","eventsBeingEncrypted","delete","getId","removeEventFromQueue","CANCELLED","setRoomName","name","sendStateEvent","RoomName","setRoomTopic","topic","htmlTopic","makeTopicContent","RoomTopic","getRoomTags","$roomId","setRoomTag","tagName","metadata","$tag","deleteRoomTag","setRoomAccountData","setPowerLevel","powerLevel","_this8","_content","_this8$getRoom","RoomPowerLevels","getStateEvent","deepCopy","users","Array","isArray","user","unstable_createLiveBeacon","beaconInfoContent","_this9","unstable_setLiveBeacon","_this10","sendEvent","threadIdOrEventType","eventTypeOrContent","contentOrTxnId","txnIdOrVoid","threadId","txnId","startsWith","addThreadRelationIfNeeded","sendCompleteEvent","type","_content$mRelates_to","rel_type","_content$mRelates_to2","_this$getRoom","isReply","_objectSpread","is_falling_back","thread","getThread","_thread$lastReply$get","_thread$lastReply","lastReply","ev","isRelation","eventObject","delayOptsOrTxnId","delayOpts","makeTxnId","localEvent","assign","user_id","sender","origin_server_ts","Date","getTime","setThread","reEmitter","reEmit","Replaced","VisibilityChange","BeforeRedaction","targetId","getAssociatedId","target","getPendingEvents","find","once","LocalEventIdReplaced","updateAssociatedId","getType","concat","setTxnId","setStatus","addPendingEvent","reject","_this11","promise","queueEvent","getQueueForEvent","err","getEncryptedIfNeededEventType","_this$getRoom2","Reaction","hasEncryptionStateEvent","RoomMessageEncrypted","newStatus","getTxnId","pathParams","$eventType","getWireType","$stateKey","getStateKey","$txnId","isState","pathTemplate","isRedaction","redacts","$redactsEventId","getWireContent","getUnstableDelayQueryOpts","redactEvent","eventId","_eventId","_opts","_opts2","with_rel_types","RelationBasedRedactions","withRelTypesPropName","Stable","stable","unstable","RoomRedaction","sendMessage","RoomMessage","sendContent","sendTextMessage","_threadId","makeTextMessage","sendNotice","_threadId2","makeNotice","sendEmoteMessage","_threadId3","makeEmoteMessage","sendImageMessage","_threadId4","text","msgtype","Image","sendStickerMessage","_threadId5","Sticker","sendHtmlMessage","htmlBody","_threadId6","makeHtmlMessage","sendHtmlNotice","_threadId7","makeHtmlNotice","sendHtmlEmote","_threadId8","makeHtmlEmote","_unstable_sendDelayedEvent","_this12","doesServerSupportUnstableFeature","_unstable_sendDelayedStateEvent","_arguments2","_this13","stateKey","_unstable_getDelayedEvents","fromToken","_this14","queryDict","from","_unstable_updateDelayedEvent","delayId","action","_this15","$delayId","sendReceipt","receiptType","_arguments3","_this16","unthreaded","$receiptType","$eventId","shouldAddThreadId","supportsThreads","fullBody","thread_id","threadIdForReceipt","addLocalEchoReceipt","sendReadReceipt","_arguments4","_this17","Read","hasPendingEvent","setRoomReadMarkers","rmEventId","rrEvent","rpEvent","_this18","rrEventId","rpEventId","ReadPrivate","setRoomReadMarkersHttpRequest","getUrlPreview","ts","Math","floor","parsed","hash","toString","key","urlPreviewCache","resp","priority","sendTyping","isTyping","timeoutMs","typing","timeout","getRoomUpgradeHistory","verifyLinks","currentRoom","before","findPredecessorRooms","after","findSuccessorRooms","_room$findPredecessor","ret","seenRoomIDs","predecessorRoomId","_room$findPredecessor2","predecessorRoom","splice","tombstoneEvent","successorRoom","_successorRoom$findPr","roomIds","map","ref","size","slice","invite","membershipChange","Invite","inviteByEmail","email","inviteByThreePid","medium","address","_this19","_this19$identityServe","identityServerUrl","getIdentityServerUrl","params","id_server","getAccessToken","identityAccessToken","leave","Leave","leaveRoomChain","includeFuture","upgradeHistory","eligibleToLeave","populationResults","doLeave","ban","Ban","forget","_arguments5","_this20","deleteRoom","$room_id","response","removeRoom","emit","DeleteRoom","unban","kick","membership","$membership","getPushActionsForEvent","forceRecalculate","getPushActions","actions","rule","pushProcessor","actionsAndRuleForEvent","setPushDetails","getPushDetailsForEvent","getPushDetails","setProfileInfo","$info","setDisplayName","_this21","prom","displayname","displayName","DisplayName","events","presence","setAvatarUrl","_this22","avatar_url","avatarUrl","AvatarUrl","mxcUrlToHttp","mxcUrl","width","height","resizeMethod","allowDirectLinks","allowRedirects","useAuthentication","setSyncPresence","_this23","_this23$syncApi","setPresence","_this24","validStates","indexOf","getPresence","scrollback","limit","timeToWaitMs","ongoingScrollbacks","errorTs","timeWaitedMs","now","max","oldState","paginationToken","numAdded","createMessagesRequest","Backward","_res$end","_res$end2","matrixEvents","chunk","getEventMapper","stateEvents","setUnknownStateEvents","timelineEvents","threadedEvents","unknownRelations","partitionThreadedEvents","processAggregatedTimelineEvents","addEventsToTimeline","getLiveTimeline","processThreadEvents","relations","aggregateChildEvent","end","storeEvents","getEventTimeline","timelineSet","_this25","_this25$clientOpts","_ref2","_timelineSet$getTimel","_timelineSet$room$fin","getTimelineForEvent","getThreadTimeline","lazyLoadMembers","JSON","stringify","LAZY_LOADING_MESSAGES_FILTER","mapper","events_after","reverse","events_before","timeline","getState","BACKWARDS","addTimeline","initialiseState","FORWARDS","findThreadForEvent","liveTimeline","_this26","_this26$clientOpts","canContain","recurse","RelationsRecursion","hasServerSideSupport","hasServerSideFwdPaginationSupport","_resOlder$next_batch","_resNewer$next_batch","_timelineSet$getTimel2","resOlder","fetchRelations","id","dir","resNewer","Forward","_timelineSet$thread","processEvent","next_batch","originalEvent","fetchRoomEvent","setPaginationToken","_resOlder$next_batch2","eventsNewer","nextBatch","_resNewer$next_batch2","_timelineSet$thread2","getLatestTimeline","_this27","threadListType","_res$chunk","createThreadListMessagesRequest","getFilter","_res$chunk2","_this27$clientOpts","_res2$chunk","messagesPath","_this$clientOpts","timelineFilter","_timelineFilter$getRo","getRoomTimelineFilterComponent","toJSON","_this$clientOpts2","All","include","_timelineFilter$getRo2","hasServerSideListSupport","V1","_res$chunk3","prev_batch","paginateEventTimeline","eventTimeline","_this28","isNotifTimeline","getTimelineSet","backwards","token","getPaginationToken","pendingRequest","paginationRequests","_opts$limit","only","_ref3","next_token","notifications","i","notification","_x2","finally","roomState","processThreadRoots","_eventTimeline$getRoo","_eventTimeline$getRoo2","_ref4","getSender","getEventReadUpTo","newToken","_thread$rootEvent","_eventTimeline$getRoo3","rootEvent","_x3","it","getServerAggregatedRelation","atEnd","resetNotifTimelineSet","resetLiveTimeline","peekInRoom","_this$peekSync2","peek","setGuestAccess","writePromise","RoomGuestAccess","guest_access","allowJoin","CanJoin","Forbidden","readPromise","allowRead","RoomHistoryVisibility","history_visibility","WorldReadable","requestRegisterEmailToken","clientSecret","sendAttempt","nextLink","requestTokenFromEndpoint","client_secret","send_attempt","next_link","requestRegisterMsisdnToken","phoneCountry","phoneNumber","country","phone_number","requestAdd3pidEmailToken","requestAdd3pidMsisdnToken","requestPasswordEmailToken","requestPasswordMsisdnToken","endpoint","_this29","postParams","request","getRoomPushRule","scope","pushRules","_this$pushRules$scope","rule_id","setRoomMutePushRule","mute","hasDontNotifyRule","roomPushRule","DontNotify","deletePushRule","RoomSpecific","addPushRule","deferred","defer","getPushRules","result","err2","searchMessageText","roomEvents","search_term","query","search","search_categories","room_events","searchRoomEvents","term","order_by","Recent","event_context","before_limit","after_limit","include_profile","searchResults","_query","results","highlights","processRoomEventsSearch","backPaginateRoomEventsSearch","searchOpts","abortSignal","_roomEvents$results$l","_roomEvents$results","count","hl","resultsLength","sr","fromJson","context","getEvent","getTimeline","getMember","syncLeftRooms","syncedLeftRooms","syncLeftRoomsPromise","createFilter","filter_id","storeFilter","filterId","allowCached","$filterId","getOrCreateFilter","filterName","_this30","getFilterIdByName","existingId","existingFilter","oldDef","getDefinition","newDef","deepCompare","setFilterIdByName","createdFilter","getOpenIdToken","setFallbackICEServerAllowed","allow","isFallbackICEServerAllowed","isSynapseAdministrator","admin","whoisSynapseUser","deactivateSynapseUser","_this31","_this31$getDomain","clientWellKnownPromise","getRawClientConfig","clientWellKnown","ClientWellKnown","getClientWellKnown","waitForClientWellKnown","storeClientOptions","primTypes","serializableOpts","entries","_ref5","value","reduce","obj","_ref6","_unstable_getSharedRooms","_this32","sharedRoomsSupport","mutualRoomsSupport","queryMutualRoomsSupport","rooms","tokenQuery","joined","next_batch_token","_this33","serverVersionsPromise","serverVersions","isVersionSupported","version","_this34","versions","feature","_this35","unstableFeatures","doesServerForceEncryptionForPreset","presetName","_this36","versionsPresetName","_this37","threadUnstable","threadStable","listUnstable","listStable","fwdPaginationUnstable","fwdPaginationStable","_unused","None","hasLazyLoadMembersEnabled","_this$clientOpts3","setCanResetTimelineCallback","cb","getCanResetTimelineCallback","relationType","_arguments6","_this38","_result$next_batch","_result$prev_batch","fetchedEventType","eventResult","Replace","prevBatch","generateClientSecret","decryptEventIfNeeded","termsUrlForService","serviceType","IS","getUrl","V2","IM","getHomeserverUrl","_this$idBaseUrl","_this$idBaseUrl2","stripProto","setIdentityServerUrl","setIdBaseUrl","getRefreshToken","_this$http$opts$refre","setAccessToken","isLoggedIn","txnCtr","isUsernameAvailable","username","available","register","password","auth","bindThreepids","guestAccessToken","inhibitLogin","session","refresh_token","guest_access_token","inhibit_login","registerRequest","registerGuest","kind","performRefreshRequestWithPrefix","inhibitLogoutEmit","loginFlows","login","loginType","access_token","loginWithPassword","getCasLoginUrl","redirectUrl","getSsoLoginUrl","idpId","href","loginWithToken","logout","_arguments7","_this39","abort","deactivateAccount","erase","requestLoginToken","_this40","getFallbackAuthUrl","authSessionId","$loginType","_this41","_this41$identityServe","invitesNeedingToken","invite_3pid","id_access_token","Experimental","queryString","encodeParams","templatedUrl","$relationType","members","includeMembership","excludeMembership","atEventId","not_membership","at","upgradeRoom","newVersion","new_version","roomInitialSync","_limit$toString","_this42","FullyRead","getJoinedRooms","getJoinedRoomMembers","publicRooms","_ref7","server","since","_objectWithoutProperties","_excluded","createAlias","alias","$alias","deleteAlias","getLocalAliases","getRoomIdForAlias","getRoomDirectoryVisibility","setRoomDirectoryVisibility","visibility","searchUserDirectory","_ref8","uploadContent","file","cancelUpload","upload","getCurrentUploads","getProfileInfo","doesServerSupportExtendedProfiles","_this43","getExtendedProfileRequestPrefix","_this44","getExtendedProfile","_this45","getExtendedProfileProperty","_this46","profile","$key","setExtendedProfileProperty","_this47","deleteExtendedProfileProperty","_this48","patchExtendedProfile","_this49","Patch","setExtendedProfile","_this50","getThreePids","addThreePidOnly","_this51","bindThreePid","_this52","unbindThreePid","_this53","deleteThreePid","setPassword","authDict","newPassword","logoutDevices","new_password","logout_devices","getDevices","getDevice","$device_id","setDeviceDetails","deleteDevice","deleteMultipleDevices","devices","getPushers","_this54","pushers","pusher","hasOwnProperty","setPusher","removePusher","pushKey","appId","pushkey","app_id","setLocalNotificationSettings","notificationSettings","rules","setPushRules","rewriteDefaultRules","updateCachedPushRuleKeys","ruleId","$kind","$ruleId","setPushRuleEnabled","enabled","setPushRuleActions","_ref9","getKeyChanges","oldToken","qps","to","registerWithIdentityServer","hsOpenIdToken","uri","requestEmailToken","idServerRequest","requestMsisdnToken","submitMsisdnToken","sid","msisdnToken","submitMsisdnTokenOtherUrl","getIdentityHashDetails","identityHashedLookup","addressPairs","_this55","hashes","localMapping","_ref10","p","addr","toLowerCase","med","hashBuffer","hashed","_x4","unhashed","foundAddresses","mxid","plainAddress","lookupThreePid","_this56","mapping","bulkLookupThreePids","_this57","v1results","_loop","originalQuery","threepids","getIdentityAccount","sendToDevice","contentMap","messages","recursiveMapToObject","targets","deviceMessages","queueToDevice","batch","queueBatch","getThirdpartyProtocols","getThirdpartyLocation","protocol","$protocol","getThirdpartyUser","getTerms","agreeToTerms","termsUrls","headers","Authorization","user_accepts","reportEvent","score","getRoomHierarchy","maxDepth","suggestedOnly","suggested_only","String","max_depth","unstableCreateFileTree","_this58","preset","PrivateChat","power_level_content_override","creation_content","Space","initial_state","state_key","unstableGetFileTreeSpace","_purposeEvent$getCont","_createEvent$getConte","getMyMembership","createEvent","RoomCreate","purposeEvent","req","proxyBaseUrl","pos","clientTimeout","_this$clientOpts4","threadSupport","supportsIntentionalMentions","IntentionalMentions","getRoomSummary","_this59","paramOpts","toStartOfTimeline","processThreadedEvents","processBeaconEvents","processPollEvents","whoami","_this60","timestampToEvent","timestamp","_this61","httpStatus","getAuthIssuer","_this62","fromEntries","_ref11","k","v","inMainTimelineForReceipt","threadRootId","isThreadRoot","isRelatedToRoot","relationEventId"],"sources":["../src/client.ts"],"sourcesContent":["/*\nCopyright 2015-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport { ISyncStateData, SetPresence, SyncApi, SyncApiOptions, SyncState } from \"./sync.ts\";\nimport {\n EventStatus,\n IContent,\n IDecryptOptions,\n IEvent,\n MatrixEvent,\n MatrixEventEvent,\n MatrixEventHandlerMap,\n PushDetails,\n} from \"./models/event.ts\";\nimport { StubStore } from \"./store/stub.ts\";\nimport { Filter, IFilterDefinition, IRoomEventFilter } from \"./filter.ts\";\nimport * as utils from \"./utils.ts\";\nimport { noUnsafeEventProps, QueryDict, replaceParam, sleep } from \"./utils.ts\";\nimport { Direction, EventTimeline } from \"./models/event-timeline.ts\";\nimport { IActionsObject, PushProcessor } from \"./pushprocessor.ts\";\nimport { AutoDiscovery, AutoDiscoveryAction } from \"./autodiscovery.ts\";\nimport { encodeUnpaddedBase64Url } from \"./base64.ts\";\nimport { TypedReEmitter } from \"./ReEmitter.ts\";\nimport { logger, Logger } from \"./logger.ts\";\nimport { SERVICE_TYPES } from \"./service-types.ts\";\nimport {\n Body,\n ClientPrefix,\n FileType,\n HttpApiEvent,\n HttpApiEventHandlerMap,\n IdentityPrefix,\n IHttpOpts,\n IRequestOpts,\n MatrixError,\n MatrixHttpApi,\n MediaPrefix,\n Method,\n retryNetworkOperation,\n TokenRefreshFunction,\n Upload,\n UploadOpts,\n UploadResponse,\n} from \"./http-api/index.ts\";\nimport { User, UserEvent, UserEventHandlerMap } from \"./models/user.ts\";\nimport { getHttpUriForMxc } from \"./content-repo.ts\";\nimport { SearchResult } from \"./models/search-result.ts\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./models/beacon.ts\";\nimport { AuthDict } from \"./interactive-auth.ts\";\nimport { IMinimalEvent, IRoomEvent, IStateEvent } from \"./sync-accumulator.ts\";\nimport { EventTimelineSet } from \"./models/event-timeline-set.ts\";\nimport * as ContentHelpers from \"./content-helpers.ts\";\nimport { NotificationCountType, Room, RoomEvent, RoomEventHandlerMap, RoomNameState } from \"./models/room.ts\";\nimport { RoomMemberEvent, RoomMemberEventHandlerMap } from \"./models/room-member.ts\";\nimport { IPowerLevelsContent, RoomStateEvent, RoomStateEventHandlerMap } from \"./models/room-state.ts\";\nimport {\n DelayedEventInfo,\n IAddThreePidOnlyBody,\n IBindThreePidBody,\n IContextResponse,\n ICreateRoomOpts,\n IEventSearchOpts,\n IFilterResponse,\n IGuestAccessOpts,\n IJoinRoomOpts,\n INotificationsResponse,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRelationsRequestOpts,\n IRelationsResponse,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n IStatusResponse,\n ITagsResponse,\n KnockRoomOpts,\n SendDelayedEventRequestOpts,\n SendDelayedEventResponse,\n UpdateDelayedEventAction,\n} from \"./@types/requests.ts\";\nimport {\n EventType,\n LOCAL_NOTIFICATION_SETTINGS_PREFIX,\n MSC3912_RELATION_BASED_REDACTIONS_PROP,\n MsgType,\n PUSHER_ENABLED,\n RelationType,\n RoomCreateTypeField,\n RoomType,\n StateEvents,\n TimelineEvents,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n} from \"./@types/event.ts\";\nimport {\n GuestAccess,\n HistoryVisibility,\n IdServerUnbindResult,\n JoinRule,\n Preset,\n Visibility,\n} from \"./@types/partials.ts\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper.ts\";\nimport { randomString } from \"./randomstring.ts\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace.ts\";\nimport { ISignatures } from \"./@types/signed.ts\";\nimport { IStore } from \"./store/index.ts\";\nimport {\n IEventWithRoomId,\n ISearchRequestBody,\n ISearchResponse,\n ISearchResults,\n IStateEventWithRoomId,\n SearchOrderBy,\n} from \"./@types/search.ts\";\nimport { ISynapseAdminDeactivateResponse, ISynapseAdminWhoisResponse } from \"./@types/synapse.ts\";\nimport { IHierarchyRoom } from \"./@types/spaces.ts\";\nimport {\n IPusher,\n IPusherRequest,\n IPushRule,\n IPushRules,\n PushRuleAction,\n PushRuleActionName,\n PushRuleKind,\n RuleId,\n} from \"./@types/PushRules.ts\";\nimport { IThreepid } from \"./@types/threepids.ts\";\nimport {\n ILoginFlowsResponse,\n IRefreshTokenResponse,\n LoginRequest,\n LoginResponse,\n LoginTokenPostResponse,\n SSOAction,\n} from \"./@types/auth.ts\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"./@types/read_receipts.ts\";\nimport { MSC3575SlidingSyncRequest, MSC3575SlidingSyncResponse, SlidingSync } from \"./sliding-sync.ts\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk.ts\";\nimport {\n determineFeatureSupport,\n FeatureSupport,\n Thread,\n THREAD_RELATION_TYPE,\n ThreadFilterType,\n threadFilterTypeToFilter,\n} from \"./models/thread.ts\";\nimport { M_BEACON_INFO, MBeaconInfoEventContent } from \"./@types/beacon.ts\";\nimport { NamespacedValue, UnstableValue } from \"./NamespacedValue.ts\";\nimport { ToDeviceMessageQueue } from \"./ToDeviceMessageQueue.ts\";\nimport { ToDeviceBatch } from \"./models/ToDeviceMessage.ts\";\nimport { IgnoredInvites } from \"./models/invites-ignorer.ts\";\nimport { UIARequest, UIAResponse } from \"./@types/uia.ts\";\nimport { LocalNotificationSettings } from \"./@types/local_notifications.ts\";\nimport { buildFeatureSupportMap, Feature, ServerSupport } from \"./feature.ts\";\nimport { RegisterRequest, RegisterResponse } from \"./@types/registration.ts\";\nimport { getRelationsThreadFilter } from \"./thread-utils.ts\";\nimport { KnownMembership, Membership } from \"./@types/membership.ts\";\nimport { RoomMessageEventContent, StickerEventContent } from \"./@types/events.ts\";\nimport { ImageInfo } from \"./@types/media.ts\";\nimport { Capabilities, ServerCapabilities } from \"./serverCapabilities.ts\";\nimport { sha256 } from \"./digest.ts\";\n\nexport type Store = IStore;\n\nexport type ResetTimelineCallback = (roomId: string) => boolean;\n\nconst SCROLLBACK_DELAY_MS = 3000;\n\nexport const UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue(\n \"last_seen_user_agent\",\n \"org.matrix.msc3852.last_seen_user_agent\",\n);\n\ninterface IExportedDevice {\n userId: string;\n deviceId: string;\n}\n\nexport interface ICreateClientOpts {\n baseUrl: string;\n\n idBaseUrl?: string;\n\n /**\n * The data store used for sync data from the homeserver. If not specified,\n * this client will not store any HTTP responses. The `createClient` helper\n * will create a default store if needed.\n */\n store?: Store;\n\n /**\n * The scheduler to use. If not\n * specified, this client will not retry requests on failure. This client\n * will supply its own processing function to\n * {@link MatrixScheduler#setProcessFunction}.\n */\n scheduler?: MatrixScheduler;\n\n /**\n * The function to invoke for HTTP requests.\n * Most supported environments have a global `fetch` registered to which this will fall back.\n */\n fetchFn?: typeof globalThis.fetch;\n\n userId?: string;\n\n /**\n * A unique identifier for this device; used for tracking things like crypto\n * keys and access tokens. If not specified, end-to-end encryption will be\n * disabled.\n */\n deviceId?: string;\n\n accessToken?: string;\n refreshToken?: string;\n\n /**\n * Function used to attempt refreshing access and refresh tokens\n * Called by http-api when a possibly expired token is encountered\n * and a refreshToken is found\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Identity server provider to retrieve the user's access token when accessing\n * the identity server. See also https://github.com/vector-im/element-web/issues/10615\n * which seeks to replace the previous approach of manual access tokens params\n * with this callback throughout the SDK.\n */\n identityServer?: IIdentityServerProvider;\n\n /**\n * The default maximum amount of\n * time to wait before timing out HTTP requests. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n\n /**\n * Set to false to send the access token to the server via a query parameter rather\n * than the Authorization HTTP header.\n *\n * Note that as of v1.11 of the Matrix spec, sending the access token via a query\n * is deprecated.\n *\n * Default true.\n */\n useAuthorizationHeader?: boolean;\n\n /**\n * Set to true to enable\n * improved timeline support, see {@link MatrixClient#getEventTimeline}.\n * It is disabled by default for compatibility with older clients - in particular to\n * maintain support for back-paginating the live timeline after a '/sync'\n * result with a gap.\n */\n timelineSupport?: boolean;\n\n /**\n * Extra query parameters to append\n * to all requests with this client. Useful for application services which require\n * `?user_id=`.\n */\n queryParams?: Record<string, string>;\n\n /**\n * Device data exported with\n * \"exportDevice\" method that must be imported to recreate this device.\n * Should only be useful for devices with end-to-end crypto enabled.\n * If provided, deviceId and userId should **NOT** be provided at the top\n * level (they are present in the exported data).\n */\n deviceToImport?: IExportedDevice;\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in {@link ICreateClientOpts#cryptoStore}.\n *\n * This must be set to the same value every time the client is initialised for the same device.\n *\n * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),\n * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device\n * previously used legacy crypto (so must be migrated), then this must still be provided, so that the\n * data can be migrated from the legacy store.\n */\n pickleKey?: string;\n\n /**\n * Verification methods we should offer to the other side when performing an interactive verification.\n * If unset, we will offer all known methods. Currently these are: showing a QR code, scanning a QR code, and SAS\n * (aka \"emojis\").\n *\n * See {@link types.VerificationMethod} for a set of useful constants for this parameter.\n */\n verificationMethods?: Array<string>;\n\n /**\n * Up to this many ICE candidates will be gathered when an incoming call arrives.\n * Gathering does not send data to the caller, but will communicate with the configured TURN\n * server. Default 0.\n */\n iceCandidatePoolSize?: number;\n\n /**\n * Whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.\n */\n fallbackICEServerAllowed?: boolean;\n\n livekitServiceURL?: string;\n\n /**\n * Method to generate room names for empty rooms and rooms names based on membership.\n * Defaults to a built-in English handler with basic pluralisation.\n */\n roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null;\n\n /**\n * If true, participant can join group call without video and audio this has to be allowed. By default, a local\n * media stream is needed to establish a group call.\n * Default: false.\n */\n isVoipWithNoMediaAllowed?: boolean;\n\n /**\n * If true, group calls will not establish media connectivity and only create the signaling events,\n * so that livekit media can be used in the application layert (js-sdk contains no livekit code).\n */\n useLivekitForGroupCalls?: boolean;\n\n /**\n * A logger to associate with this MatrixClient.\n * Defaults to the built-in global logger.\n */\n logger?: Logger;\n}\n\nexport interface IMatrixClientCreateOpts extends ICreateClientOpts {\n /**\n * Whether to allow sending messages to encrypted rooms when encryption\n * is not available internally within this SDK. This is useful if you are using an external\n * E2E proxy, for example. Defaults to false.\n */\n usingExternalCrypto?: boolean;\n}\n\nexport enum PendingEventOrdering {\n Chronological = \"chronological\",\n Detached = \"detached\",\n}\n\nexport interface IStartClientOpts {\n /**\n * The event `limit=` to apply to initial sync. Default: 8.\n */\n initialSyncLimit?: number;\n\n /**\n * True to put `archived=true</code> on the <code>/initialSync` request. Default: false.\n */\n includeArchivedRooms?: boolean;\n\n /**\n * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false.\n */\n resolveInvitesToProfiles?: boolean;\n\n /**\n * Controls where pending messages appear in a room's timeline. If \"<b>chronological</b>\", messages will\n * appear in the timeline when the call to `sendEvent` was made. If \"<b>detached</b>\",\n * pending messages will appear in a separate list, accessbile via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n\n /**\n * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds).\n */\n pollTimeout?: number;\n\n /**\n * The filter to apply to /sync calls.\n */\n filter?: Filter;\n\n /**\n * True to perform syncing without automatically updating presence.\n */\n disablePresence?: boolean;\n\n /**\n * True to not load all membership events during initial sync but fetch them when needed by calling\n * `loadOutOfBandMembers` This will override the filter option at this moment.\n */\n lazyLoadMembers?: boolean;\n\n /**\n * The number of seconds between polls to /.well-known/matrix/client, undefined to disable.\n * This should be in the order of hours. Default: undefined.\n */\n clientWellKnownPollPeriod?: number;\n\n /**\n * Will organises events in threaded conversations when\n * a thread relation is encountered\n */\n threadSupport?: boolean;\n\n /**\n * @experimental\n */\n slidingSync?: SlidingSync;\n}\n\nexport interface IStoredClientOpts extends IStartClientOpts { }\n\nexport const GET_LOGIN_TOKEN_CAPABILITY = new NamespacedValue(\n \"m.get_login_token\",\n \"org.matrix.msc3882.get_login_token\",\n);\n\nexport const UNSTABLE_MSC2666_SHARED_ROOMS = \"uk.half-shot.msc2666\";\nexport const UNSTABLE_MSC2666_MUTUAL_ROOMS = \"uk.half-shot.msc2666.mutual_rooms\";\nexport const UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS = \"uk.half-shot.msc2666.query_mutual_rooms\";\n\nexport const UNSTABLE_MSC4140_DELAYED_EVENTS = \"org.matrix.msc4140\";\n\nexport const UNSTABLE_MSC4133_EXTENDED_PROFILES = \"uk.tcpip.msc4133\";\n\nexport type SendToDeviceContentMap = Map<string, Map<string, Record<string, any>>>;\n\nexport interface ISignedKey {\n keys: Record<string, string>;\n signatures: ISignatures;\n user_id: string;\n algorithms: string[];\n device_id: string;\n}\n\nexport interface IUploadKeySignaturesResponse {\n failures: Record<\n string,\n Record<\n string,\n {\n errcode: string;\n error: string;\n }\n >\n >;\n}\n\nexport interface IPreviewUrlResponse {\n [key: string]: undefined | string | number;\n \"og:title\": string;\n \"og:type\": string;\n \"og:url\": string;\n \"og:image\"?: string;\n \"og:image:type\"?: string;\n \"og:image:height\"?: number;\n \"og:image:width\"?: number;\n \"og:description\"?: string;\n \"matrix:image:size\"?: number;\n}\n\nexport interface ITurnServerResponse {\n uris: string[];\n username: string;\n password: string;\n ttl: number;\n}\n\nexport interface ITurnServer {\n urls: string[];\n username: string;\n credential: string;\n}\n\nexport interface IServerVersions {\n versions: string[];\n unstable_features: Record<string, boolean>;\n}\n\nexport interface IClientWellKnown {\n [key: string]: any;\n \"m.homeserver\"?: IWellKnownConfig;\n \"m.identity_server\"?: IWellKnownConfig;\n}\n\nexport interface IWellKnownConfig<T = IClientWellKnown> {\n raw?: T;\n action?: AutoDiscoveryAction;\n reason?: string;\n error?: Error | string;\n // eslint-disable-next-line\n base_url?: string | null;\n // XXX: this is undocumented\n server_name?: string;\n}\n\ninterface IMediaConfig {\n [key: string]: any; // extensible\n \"m.upload.size\"?: number;\n}\n\ninterface IThirdPartySigned {\n sender: string;\n mxid: string;\n token: string;\n signatures: ISignatures;\n}\n\ninterface IJoinRequestBody {\n third_party_signed?: IThirdPartySigned;\n}\n\ninterface ITagMetadata {\n [key: string]: any;\n order?: number;\n}\n\ninterface IMessagesResponse {\n start?: string;\n end?: string;\n chunk: IRoomEvent[];\n state?: IStateEvent[];\n}\n\ninterface IThreadedMessagesResponse {\n prev_batch: string;\n next_batch: string;\n chunk: IRoomEvent[];\n state: IStateEvent[];\n}\n\nexport interface IRequestTokenResponse {\n sid: string;\n submit_url?: string;\n}\n\nexport interface IRequestMsisdnTokenResponse extends IRequestTokenResponse {\n msisdn: string;\n success: boolean;\n intl_fmt: string;\n}\n\nexport interface IQueryKeysRequest {\n device_keys: { [userId: string]: string[] };\n timeout?: number;\n token?: string;\n}\n\nexport interface IClaimKeysRequest {\n one_time_keys: { [userId: string]: { [deviceId: string]: string } };\n timeout?: number;\n}\n\nexport interface IOpenIDToken {\n access_token: string;\n token_type: \"Bearer\" | string;\n matrix_server_name: string;\n expires_in: number;\n}\n\ninterface IRoomInitialSyncResponse {\n room_id: string;\n membership: Membership;\n messages?: {\n start?: string;\n end?: string;\n chunk: IEventWithRoomId[];\n };\n state?: IStateEventWithRoomId[];\n visibility: Visibility;\n account_data?: IMinimalEvent[];\n presence: Partial<IEvent>; // legacy and undocumented, api is deprecated so this won't get attention\n}\n\ninterface IJoinedRoomsResponse {\n joined_rooms: string[];\n}\n\ninterface IJoinedMembersResponse {\n joined: {\n [userId: string]: {\n display_name: string;\n avatar_url: string;\n };\n };\n}\n\n// Re-export for backwards compatibility\nexport type IRegisterRequestParams = RegisterRequest;\n\nexport interface IPublicRoomsChunkRoom {\n room_id: string;\n name?: string;\n avatar_url?: string;\n topic?: string;\n canonical_alias?: string;\n aliases?: string[];\n world_readable: boolean;\n guest_can_join: boolean;\n num_joined_members: number;\n room_type?: RoomType | string; // Added by MSC3827\n join_rule?: JoinRule.Knock | JoinRule.Public; // Added by MSC2403\n}\n\ninterface IPublicRoomsResponse {\n chunk: IPublicRoomsChunkRoom[];\n next_batch?: string;\n prev_batch?: string;\n total_room_count_estimate?: number;\n}\n\ninterface IUserDirectoryResponse {\n results: {\n user_id: string;\n display_name?: string;\n avatar_url?: string;\n }[];\n limited: boolean;\n}\n\nexport interface IMyDevice {\n \"device_id\": string;\n \"display_name\"?: string;\n \"last_seen_ip\"?: string;\n \"last_seen_ts\"?: number;\n // UNSTABLE_MSC3852_LAST_SEEN_UA\n \"last_seen_user_agent\"?: string;\n \"org.matrix.msc3852.last_seen_user_agent\"?: string;\n}\n\nexport interface Keys {\n keys: { [keyId: string]: string };\n usage: string[];\n user_id: string;\n}\n\nexport interface IClaimOTKsResult {\n failures: { [serverName: string]: object };\n one_time_keys: {\n [userId: string]: {\n [deviceId: string]: {\n [keyId: string]: {\n key: string;\n signatures: ISignatures;\n };\n };\n };\n };\n}\n\nexport interface IFieldType {\n regexp: string;\n placeholder: string;\n}\n\nexport interface IInstance {\n desc: string;\n icon?: string;\n fields: object;\n network_id: string;\n // XXX: this is undocumented but we rely on it: https://github.com/matrix-org/matrix-doc/issues/3203\n instance_id: string;\n}\n\nexport interface IProtocol {\n user_fields: string[];\n location_fields: string[];\n icon: string;\n field_types: Record<string, IFieldType>;\n instances: IInstance[];\n}\n\ninterface IThirdPartyLocation {\n alias: string;\n protocol: string;\n fields: object;\n}\n\ninterface IThirdPartyUser {\n userid: string;\n protocol: string;\n fields: object;\n}\n\n/**\n * The summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n */\nexport interface RoomSummary extends Omit<IPublicRoomsChunkRoom, \"canonical_alias\" | \"aliases\"> {\n /**\n * The current membership of this user in the room.\n * Usually \"leave\" if the room is fetched over federation.\n */\n \"membership\"?: Membership;\n /**\n * Version of the room.\n */\n \"im.nheko.summary.room_version\"?: string;\n /**\n * The encryption algorithm used for this room, if the room is encrypted.\n */\n \"im.nheko.summary.encryption\"?: string;\n}\n\ninterface IRoomHierarchy {\n rooms: IHierarchyRoom[];\n next_batch?: string;\n}\n\nexport interface TimestampToEventResponse {\n event_id: string;\n origin_server_ts: number;\n}\n\ninterface IWhoamiResponse {\n user_id: string;\n device_id?: string;\n is_guest?: boolean;\n}\n/* eslint-enable camelcase */\n\n// We're using this constant for methods overloading and inspect whether a variable\n// contains an eventId or not. This was required to ensure backwards compatibility\n// of methods for threads\n// Probably not the most graceful solution but does a good enough job for now\nconst EVENT_ID_PREFIX = \"$\";\n\nexport enum ClientEvent {\n Sync = \"sync\",\n Event = \"event\",\n ToDeviceEvent = \"toDeviceEvent\",\n AccountData = \"accountData\",\n Room = \"Room\",\n DeleteRoom = \"deleteRoom\",\n SyncUnexpectedError = \"sync.unexpectedError\",\n ClientWellKnown = \"WellKnown.client\",\n ReceivedVoipEvent = \"received_voip_event\",\n UndecryptableToDeviceEvent = \"toDeviceEvent.undecryptable\",\n TurnServers = \"turnServers\",\n TurnServersError = \"turnServers.error\",\n}\n\ntype RoomEvents =\n | RoomEvent.Name\n | RoomEvent.Redaction\n | RoomEvent.RedactionCancelled\n | RoomEvent.Receipt\n | RoomEvent.Tags\n | RoomEvent.LocalEchoUpdated\n | RoomEvent.HistoryImportedWithinTimeline\n | RoomEvent.AccountData\n | RoomEvent.MyMembership\n | RoomEvent.Timeline\n | RoomEvent.TimelineReset;\n\ntype RoomStateEvents =\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker;\n\ntype MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange;\n\ntype RoomMemberEvents =\n | RoomMemberEvent.Name\n | RoomMemberEvent.Typing\n | RoomMemberEvent.PowerLevel\n | RoomMemberEvent.Membership;\n\ntype UserEvents =\n | UserEvent.AvatarUrl\n | UserEvent.DisplayName\n | UserEvent.Presence\n | UserEvent.CurrentlyActive\n | UserEvent.LastPresenceTs;\n\nexport type EmittedEvents =\n | ClientEvent\n | RoomEvents\n | RoomStateEvents\n | MatrixEventEvents\n | RoomMemberEvents\n | UserEvents\n | HttpApiEvent.SessionLoggedOut\n | HttpApiEvent.NoConsent\n | BeaconEvent;\n\nexport type ClientEventHandlerMap = {\n /**\n * Fires whenever the SDK's syncing state is updated. The state can be one of:\n * <ul>\n *\n * <li>PREPARED: The client has synced with the server at least once and is\n * ready for methods to be called on it. This will be immediately followed by\n * a state of SYNCING. <i>This is the equivalent of \"syncComplete\" in the\n * previous API.</i></li>\n *\n * <li>CATCHUP: The client has detected the connection to the server might be\n * available again and will now try to do a sync again. As this sync might take\n * a long time (depending how long ago was last synced, and general server\n * performance) the client is put in this mode so the UI can reflect trying\n * to catch up with the server after losing connection.</li>\n *\n * <li>SYNCING : The client is currently polling for new events from the server.\n * This will be called <i>after</i> processing latest events from a sync.</li>\n *\n * <li>ERROR : The client has had a problem syncing with the server. If this is\n * called <i>before</i> PREPARED then there was a problem performing the initial\n * sync. If this is called <i>after</i> PREPARED then there was a problem polling\n * the server for updates. This may be called multiple times even if the state is\n * already ERROR. <i>This is the equivalent of \"syncError\" in the previous\n * API.</i></li>\n *\n * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that\n * should be considered erroneous.\n * </li>\n *\n * <li>STOPPED: The client has stopped syncing with server due to stopClient\n * being called.\n * </li>\n * </ul>\n * State transition diagram:\n * ```\n * +---->STOPPED\n * |\n * +----->PREPARED -------> SYNCING <--+\n * | ^ | ^ |\n * | CATCHUP ----------+ | | |\n * | ^ V | |\n * null ------+ | +------- RECONNECTING |\n * | V V |\n * +------->ERROR ---------------------+\n *\n * NB: 'null' will never be emitted by this event.\n *\n * ```\n * Transitions:\n * <ul>\n *\n * <li>`null -> PREPARED` : Occurs when the initial sync is completed\n * first time. This involves setting up filters and obtaining push rules.\n *\n * <li>`null -> ERROR` : Occurs when the initial sync failed first time.\n *\n * <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds\n * after previously failing.\n *\n * <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning\n * to PREPARED. Starts listening for live updates rather than catching up.\n *\n * <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails.\n *\n * <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls\n * continue to fail, but the keepalive calls (to /versions) succeed.\n *\n * <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails\n *\n * <li>`ERROR -> SYNCING` : Occurs when the client has performed a\n * live update after having previously failed.\n *\n * <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive\n * for a second time or more.</li>\n *\n * <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live\n * update. This is called <i>after</i> processing.</li>\n *\n * <li>`* -> STOPPED` : Occurs once the client has stopped syncing or\n * trying to sync after stopClient has been called.</li>\n * </ul>\n *\n * @param state - An enum representing the syncing state. One of \"PREPARED\",\n * \"SYNCING\", \"ERROR\", \"STOPPED\".\n *\n * @param prevState - An enum representing the previous syncing state.\n * One of \"PREPARED\", \"SYNCING\", \"ERROR\", \"STOPPED\" <b>or null</b>.\n *\n * @param data - Data about this transition.\n *\n * @example\n * ```\n * matrixClient.on(\"sync\", function(state, prevState, data) {\n * switch (state) {\n * case \"ERROR\":\n * // update UI to say \"Connection Lost\"\n * break;\n * case \"SYNCING\":\n * // update UI to remove any \"Connection Lost\" message\n * break;\n * case \"PREPARED\":\n * // the client instance is ready to be queried.\n * var rooms = matrixClient.getRooms();\n * break;\n * }\n * });\n * ```\n */\n [ClientEvent.Sync]: (state: SyncState, prevState: SyncState | null, data?: ISyncStateData) => void;\n /**\n * Fires whenever the SDK receives a new event.\n * <p>\n * This is only fired for live events received via /sync - it is not fired for\n * events received over context, search, or pagination APIs.\n *\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"event\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.Event]: (event: MatrixEvent) => void;\n /**\n * Fires whenever the SDK receives a new to-device event.\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"toDeviceEvent\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.ToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires if a to-device event is received that cannot be decrypted.\n * Encrypted to-device events will (generally) use plain Olm encryption,\n * in which case decryption failures are fatal: the event will never be\n * decryptable, unlike Megolm encrypted events where the key may simply\n * arrive later.\n *\n * An undecryptable to-device event is therefore likley to indicate problems.\n *\n * @param event - The undecyptable to-device event\n */\n [ClientEvent.UndecryptableToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires whenever new user-scoped account_data is added.\n * @param event - The event describing the account_data just added\n * @param event - The previous account data, if known.\n * @example\n * ```\n * matrixClient.on(\"accountData\", function(event, oldEvent){\n * myAccountData[event.type] = event.content;\n * });\n * ```\n */\n [ClientEvent.AccountData]: (event: MatrixEvent, lastEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a new Room is added. This will fire when you are invited to a\n * room, as well as when you join a room. <strong>This event is experimental and\n * may change.</strong>\n * @param room - The newly created, fully populated room.\n * @example\n * ```\n * matrixClient.on(\"Room\", function(room){\n * var roomId = room.roomId;\n * });\n * ```\n */\n [ClientEvent.Room]: (room: Room) => void;\n /**\n * Fires whenever a Room is removed. This will fire when you forget a room.\n * <strong>This event is experimental and may change.</strong>\n * @param roomId - The deleted room ID.\n * @example\n * ```\n * matrixClient.on(\"deleteRoom\", function(roomId){\n * // update UI from getRooms()\n * });\n * ```\n */\n [ClientEvent.DeleteRoom]: (roomId: string) => void;\n [ClientEvent.SyncUnexpectedError]: (error: Error) => void;\n /**\n * Fires when the client .well-known info is fetched.\n *\n * @param data - The JSON object returned by the server\n */\n [ClientEvent.ClientWellKnown]: (data: IClientWellKnown) => void;\n [ClientEvent.ReceivedVoipEvent]: (event: MatrixEvent) => void;\n [ClientEvent.TurnServers]: (servers: ITurnServer[]) => void;\n [ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void;\n} & RoomEventHandlerMap &\n RoomStateEventHandlerMap &\n MatrixEventHandlerMap &\n RoomMemberEventHandlerMap &\n UserEventHandlerMap &\n HttpApiEventHandlerMap &\n BeaconEventHandlerMap;\n\nconst SSO_ACTION_PARAM = new UnstableValue(\"action\", \"org.matrix.msc3824.action\");\n\n/**\n * Represents a Matrix Client. Only directly construct this if you want to use\n * custom modules. Normally, {@link createClient} should be used\n * as it specifies 'sensible' defaults for these modules.\n */\nexport class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHandlerMap> {\n public static readonly RESTORE_BACKUP_ERROR_BAD_KEY = \"RESTORE_BACKUP_ERROR_BAD_KEY\";\n\n private readonly logger: Logger;\n\n public reEmitter = new TypedReEmitter<EmittedEvents, ClientEventHandlerMap>(this);\n public olmVersion: [number, number, number] | null = null; // populated after initCrypto\n public usingExternalCrypto = false;\n private _store!: Store;\n public deviceId: string | null;\n public credentials: { userId: string | null };\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.\n *\n * As supplied in the constructor via {@link IMatrixClientCreateOpts#pickleKey}.\n *\n * If unset, either a hardcoded key or no encryption at all is used, depending on the Crypto implementation.\n *\n * @deprecated this should be a private property.\n */\n public pickleKey?: string;\n\n public scheduler?: MatrixScheduler;\n public clientRunning = false;\n public timelineSupport = false;\n public urlPreviewCache: { [key: string]: Promise<IPreviewUrlResponse> } = {};\n public identityServer?: IIdentityServerProvider;\n public http: MatrixHttpApi<IHttpOpts & { onlyData: true }>; // XXX: Intended private, used in code.\n\n public iceCandidatePoolSize = 0; // XXX: Intended private, used in code.\n public idBaseUrl?: string;\n public baseUrl: string;\n public readonly isVoipWithNoMediaAllowed;\n\n public useLivekitForGroupCalls: boolean;\n\n // Note: these are all `protected` to let downstream consumers make mistakes if they want to.\n // We don't technically support this usage, but have reasons to do this.\n\n protected peekSync: SyncApi | null = null;\n protected isGuestAccount = false;\n protected ongoingScrollbacks: { [roomId: string]: { promise?: Promise<Room>; errorTs?: number } } = {};\n protected notifTimelineSet: EventTimelineSet | null = null;\n /* @deprecated */\n protected verificationMethods?: string[];\n protected fallbackICEServerAllowed = false;\n protected syncApi?: SlidingSyncSdk | SyncApi;\n public roomNameGenerator?: ICreateClientOpts[\"roomNameGenerator\"];\n public pushRules?: IPushRules;\n protected syncLeftRoomsPromise?: Promise<Room[]>;\n protected syncedLeftRooms = false;\n protected clientOpts?: IStoredClientOpts;\n protected clientWellKnownIntervalID?: ReturnType<typeof setInterval>;\n protected canResetTimelineCallback?: ResetTimelineCallback;\n\n public canSupport = new Map<Feature, ServerSupport>();\n\n // The pushprocessor caches useful things, so keep one and re-use it\n protected pushProcessor = new PushProcessor(this);\n\n // Promise to a response of the server's /versions response\n // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020\n protected serverVersionsPromise?: Promise<IServerVersions>;\n\n protected clientWellKnown?: IClientWellKnown;\n protected clientWellKnownPromise?: Promise<IClientWellKnown>;\n protected txnCtr = 0;\n protected sessionId: string;\n\n /** IDs of events which are currently being encrypted.\n *\n * This is part of the cancellation mechanism: if the event is no longer listed here when encryption completes,\n * that tells us that it has been cancelled, and we should not send it.\n */\n private eventsBeingEncrypted = new Set<string>();\n\n private toDeviceMessageQueue: ToDeviceMessageQueue;\n public livekitServiceURL?: string;\n\n // A manager for determining which invites should be ignored.\n public readonly ignoredInvites: IgnoredInvites;\n\n private serverCapabilitiesService: ServerCapabilities;\n\n public constructor(opts: IMatrixClientCreateOpts) {\n super();\n\n // If a custom logger is provided, use it. Otherwise, default to the global\n // one in logger.ts.\n this.logger = opts.logger ?? logger;\n\n opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);\n opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);\n\n this.baseUrl = opts.baseUrl;\n this.idBaseUrl = opts.idBaseUrl;\n this.identityServer = opts.identityServer;\n\n this.usingExternalCrypto = opts.usingExternalCrypto ?? false;\n this.store = opts.store || new StubStore();\n this.deviceId = opts.deviceId || null;\n this.sessionId = randomString(10);\n\n const userId = opts.userId || null;\n this.credentials = { userId };\n\n this.http = new MatrixHttpApi(this as ConstructorParameters<typeof MatrixHttpApi>[0], {\n fetchFn: opts.fetchFn,\n baseUrl: opts.baseUrl,\n idBaseUrl: opts.idBaseUrl,\n accessToken: opts.accessToken,\n refreshToken: opts.refreshToken,\n tokenRefreshFunction: opts.tokenRefreshFunction,\n prefix: ClientPrefix.V3,\n onlyData: true,\n extraParams: opts.queryParams,\n localTimeoutMs: opts.localTimeoutMs,\n useAuthorizationHeader: opts.useAuthorizationHeader,\n logger: this.logger,\n });\n\n if (opts.deviceToImport) {\n if (this.deviceId) {\n this.logger.warn(\n \"not importing device because device ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (this.credentials.userId) {\n this.logger.warn(\n \"not importing device because user ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (!opts.deviceToImport.deviceId) {\n this.logger.warn(\"not importing device because no device ID in exported data\");\n } else {\n this.deviceId = opts.deviceToImport.deviceId;\n this.credentials.userId = opts.deviceToImport.userId;\n }\n } else if (opts.pickleKey) {\n this.pickleKey = opts.pickleKey;\n }\n\n this.useLivekitForGroupCalls = Boolean(opts.useLivekitForGroupCalls);\n\n this.scheduler = opts.scheduler;\n if (this.scheduler) {\n this.scheduler.setProcessFunction(async (eventToSend: MatrixEvent) => {\n const room = this.getRoom(eventToSend.getRoomId());\n if (eventToSend.status !== EventStatus.SENDING) {\n this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);\n }\n const res = await this.sendEventHttpRequest(eventToSend);\n if (room) {\n // ensure we update pending event before the next scheduler run so that any listeners to event id\n // updates on the synchronous event emitter get a chance to run first.\n room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);\n }\n return res;\n });\n }\n\n this.serverCapabilitiesService = new ServerCapabilities(this.http);\n\n this.on(ClientEvent.Sync, this.fixupRoomNotifications);\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n\n this.verificationMethods = opts.verificationMethods;\n\n this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;\n this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;\n this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false;\n\n this.livekitServiceURL = opts.livekitServiceURL;\n\n this.roomNameGenerator = opts.roomNameGenerator;\n\n this.toDeviceMessageQueue = new ToDeviceMessageQueue(this);\n\n this.ignoredInvites = new IgnoredInvites(this);\n\n // having lots of event listeners is not unusual. 0 means \"unlimited\".\n this.setMaxListeners(0);\n }\n\n public set store(newStore: Store) {\n this._store = newStore;\n this._store.setUserCreator((userId) => User.createUser(userId, this));\n }\n\n public get store(): Store {\n return this._store;\n }\n\n /**\n * High level helper method to begin syncing and poll for new events. To listen for these\n * events, add a listener for {@link ClientEvent.Event}\n * via {@link MatrixClient#on}. Alternatively, listen for specific\n * state change events.\n * @param opts - Options to apply when syncing.\n */\n public async startClient(opts?: IStartClientOpts): Promise<void> {\n if (this.clientRunning) {\n // client is already running.\n return;\n }\n this.clientRunning = true;\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n if (this.syncApi) {\n // This shouldn't happen since we thought the client was not running\n this.logger.error(\"Still have sync object whilst not running: stopping old one\");\n this.syncApi.stop();\n }\n\n try {\n await this.getVersions();\n\n // This should be done with `canSupport`\n // TODO: https://github.com/vector-im/element-web/issues/23643\n const { threads, list, fwdPagination } = await this.doesServerSupportThread();\n Thread.setServerSideSupport(threads);\n Thread.setServerSideListSupport(list);\n Thread.setServerSideFwdPaginationSupport(fwdPagination);\n } catch (e) {\n this.logger.error(\n \"Can't fetch server versions, continuing to initialise sync, this will be retried later\",\n e,\n );\n }\n\n this.clientOpts = opts ?? {};\n if (this.clientOpts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(\n this.clientOpts.slidingSync,\n this,\n this.clientOpts,\n );\n } else {\n this.syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n }\n\n this.syncApi.sync().catch((e) => this.logger.info(\"Sync startup aborted with an error:\", e));\n\n if (this.clientOpts.clientWellKnownPollPeriod !== undefined) {\n this.clientWellKnownIntervalID = setInterval(() => {\n this.fetchClientWellKnown();\n }, 1000 * this.clientOpts.clientWellKnownPollPeriod);\n this.fetchClientWellKnown();\n }\n\n this.toDeviceMessageQueue.start();\n this.serverCapabilitiesService.start();\n }\n\n /**\n * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor\n */\n protected buildSyncApiOptions(): SyncApiOptions {\n return {\n canResetEntireTimeline: (roomId: string): boolean => {\n if (!this.canResetTimelineCallback) {\n return false;\n }\n return this.canResetTimelineCallback(roomId);\n },\n };\n }\n\n /**\n * High level helper method to stop the client from polling and allow a\n * clean shutdown.\n */\n public stopClient(): void {\n if (!this.clientRunning) return; // already stopped\n\n this.logger.debug(\"stopping MatrixClient\");\n\n this.clientRunning = false;\n\n this.syncApi?.stop();\n this.syncApi = undefined;\n\n this.peekSync?.stopPeeking();\n\n if (this.clientWellKnownIntervalID !== undefined) {\n globalThis.clearInterval(this.clientWellKnownIntervalID);\n }\n\n this.toDeviceMessageQueue.stop();\n\n this.serverCapabilitiesService.stop();\n }\n\n /**\n * Clear any data out of the persistent stores used by the client.\n *\n * @returns Promise which resolves when the stores have been cleared.\n */\n public clearStores(): Promise<void> {\n if (this.clientRunning) {\n throw new Error(\"Cannot clear stores while client is running\");\n }\n\n const promises: Promise<void>[] = [];\n\n promises.push(this.store.deleteAllData());\n\n return Promise.all(promises).then(); // .then to fix types\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user, or null if not logged in\n */\n public getUserId(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId;\n }\n return null;\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user\n * @throws Error if not logged in\n */\n public getSafeUserId(): string {\n const userId = this.getUserId();\n if (!userId) {\n throw new Error(\"Expected logged in user but found none.\");\n }\n return userId;\n }\n\n /**\n * Get the domain for this client's MXID\n * @returns Domain of this MXID\n */\n public getDomain(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.replace(/^.*?:/, \"\");\n }\n return null;\n }\n\n /**\n * Get the local part of the current user ID e.g. \"foo\" in \"\\@foo:bar\".\n * @returns The user ID localpart or null.\n */\n public getUserIdLocalpart(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.split(\":\")[0].substring(1);\n }\n return null;\n }\n\n /**\n * Get the device ID of this client\n * @returns device ID\n */\n public getDeviceId(): string | null {\n return this.deviceId;\n }\n\n /**\n * Get the session ID of this client\n * @returns session ID\n */\n public getSessionId(): string {\n return this.sessionId;\n }\n\n public getLivekitServiceURL(): string | undefined {\n return this.livekitServiceURL;\n }\n\n // This shouldn't need to exist, but the widget API has startup ordering problems that\n // mean it doesn't know the livekit URL fast enough: remove this once this is fixed.\n public setLivekitServiceURL(newURL: string): void {\n this.livekitServiceURL = newURL;\n }\n\n /**\n * Get the current sync state.\n * @returns the sync state, which may be null.\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncApi?.getSyncState() ?? null;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n if (!this.syncApi) {\n return null;\n }\n return this.syncApi.getSyncStateData();\n }\n\n /**\n * Whether the initial sync has completed.\n * @returns True if at least one sync has happened.\n */\n public isInitialSyncComplete(): boolean {\n const state = this.getSyncState();\n if (!state) {\n return false;\n }\n return state === SyncState.Prepared || state === SyncState.Syncing;\n }\n\n /**\n * Return whether the client is configured for a guest account.\n * @returns True if this is a guest access_token (or no token is supplied).\n */\n public isGuest(): boolean {\n return this.isGuestAccount;\n }\n\n /**\n * Set whether this client is a guest account. <b>This method is experimental\n * and may change without warning.</b>\n * @param guest - True if this is a guest account.\n * @experimental if the token is a macaroon, it should be encoded in it that it is a 'guest'\n * access token, which means that the SDK can determine this entirely without\n * the dev manually flipping this flag.\n */\n public setGuest(guest: boolean): void {\n this.isGuestAccount = guest;\n }\n\n /**\n * Return the provided scheduler, if any.\n * @returns The scheduler or undefined\n */\n public getScheduler(): MatrixScheduler | undefined {\n return this.scheduler;\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * Will also retry any outbound to-device messages currently in the queue to be sent\n * (retries of regular outgoing events are handled separately, per-event).\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n // don't await for this promise: we just want to kick it off\n this.toDeviceMessageQueue.sendQueue();\n return this.syncApi?.retryImmediately() ?? false;\n }\n\n /**\n * Return the global notification EventTimelineSet, if any\n *\n * @returns the globl notification EventTimelineSet\n */\n public getNotifTimelineSet(): EventTimelineSet | null {\n return this.notifTimelineSet;\n }\n\n /**\n * Set the global notification EventTimelineSet\n *\n */\n public setNotifTimelineSet(set: EventTimelineSet): void {\n this.notifTimelineSet = set;\n }\n\n /**\n * Gets the cached capabilities of the homeserver, returning cached ones if available.\n * If there are no cached capabilities and none can be fetched, throw an exception.\n *\n * @returns Promise resolving with The capabilities of the homeserver\n */\n public async getCapabilities(): Promise<Capabilities> {\n const caps = this.serverCapabilitiesService.getCachedCapabilities();\n if (caps) return caps;\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * Gets the cached capabilities of the homeserver. If none have been fetched yet,\n * return undefined.\n *\n * @returns The capabilities of the homeserver\n */\n public getCachedCapabilities(): Capabilities | undefined {\n return this.serverCapabilitiesService.getCachedCapabilities();\n }\n\n /**\n * Fetches the latest capabilities from the homeserver, ignoring any cached\n * versions. The newly returned version is cached.\n *\n * @returns A promise which resolves to the capabilities of the homeserver\n */\n public fetchCapabilities(): Promise<Capabilities> {\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * @deprecated Does nothing.\n */\n public async uploadKeys(): Promise<void> {\n this.logger.warn(\"MatrixClient.uploadKeys is deprecated\");\n }\n\n /**\n * Get the config for the media repository.\n * @returns Promise which resolves with an object containing the config.\n */\n public getMediaConfig(): Promise<IMediaConfig> {\n return this.http.authedRequest(Method.Get, \"/config\", undefined, undefined, {\n prefix: MediaPrefix.V3,\n });\n }\n\n /**\n * Get the room for the given room ID.\n * This function will return a valid room for any room for which a Room event\n * has been emitted. Note in particular that other events, eg. RoomState.members\n * will be emitted for a room before this function will return the given room.\n * @param roomId - The room ID\n * @returns The Room or null if it doesn't exist or there is no data store.\n */\n public getRoom(roomId: string | undefined): Room | null {\n if (!roomId) {\n return null;\n }\n return this.store.getRoom(roomId);\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getRooms(): Room[] {\n return this.store.getRooms();\n }\n\n /**\n * Retrieve all rooms that should be displayed to the user\n * This is essentially getRooms() with some rooms filtered out, eg. old versions\n * of rooms that have been replaced or (in future) other rooms that have been\n * marked at the protocol level as not to be displayed to the user.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and\n * use it if found (MSC3946).\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getVisibleRooms(msc3946ProcessDynamicPredecessor = false): Room[] {\n const allRooms = this.store.getRooms();\n\n const replacedRooms = new Set();\n for (const r of allRooms) {\n const predecessor = r.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (predecessor) {\n replacedRooms.add(predecessor);\n }\n }\n\n return allRooms.filter((r) => {\n const tombstone = r.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (tombstone && replacedRooms.has(r.roomId)) {\n return false;\n }\n return true;\n });\n }\n\n /**\n * Retrieve a user.\n * @param userId - The user ID to retrieve.\n * @returns A user or null if there is no data store or the user does\n * not exist.\n */\n public getUser(userId: string): User | null {\n return this.store.getUser(userId);\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, or an empty list if there is no data store.\n */\n public getUsers(): User[] {\n return this.store.getUsers();\n }\n\n /**\n * Set account data event for the current user.\n * It will retry the request up to 5 times.\n * @param eventType - The event type\n * @param content - the contents object for the event\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setAccountData(eventType: EventType | string, content: IContent): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n return retryNetworkOperation(5, () => {\n return this.http.authedRequest(Method.Put, path, undefined, content);\n });\n }\n\n /**\n * Get account data event of given type for the current user.\n * @param eventType - The event type\n * @returns The contents of the given account data event\n */\n public getAccountData(eventType: string): MatrixEvent | undefined {\n return this.store.getAccountData(eventType);\n }\n\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n * @param eventType - The event type\n * @returns Promise which resolves: The contents of the given account data event.\n * @returns Rejects: with an error response.\n */\n public async getAccountDataFromServer<T extends { [k: string]: any }>(eventType: string): Promise<T | null> {\n if (this.isInitialSyncComplete()) {\n const event = this.store.getAccountData(eventType);\n if (!event) {\n return null;\n }\n // The network version below returns just the content, so this branch\n // does the same to match.\n return event.getContent<T>();\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n try {\n return await this.http.authedRequest(Method.Get, path);\n } catch (e) {\n if ((<MatrixError>e).data?.errcode === \"M_NOT_FOUND\") {\n return null;\n }\n throw e;\n }\n }\n\n public async deleteAccountData(eventType: string): Promise<void> {\n const msc3391DeleteAccountDataServerSupport = this.canSupport.get(Feature.AccountDataDeletion);\n // if deletion is not supported overwrite with empty content\n if (msc3391DeleteAccountDataServerSupport === ServerSupport.Unsupported) {\n await this.setAccountData(eventType, {});\n return;\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.getSafeUserId(),\n $type: eventType,\n });\n const options =\n msc3391DeleteAccountDataServerSupport === ServerSupport.Unstable\n ? { prefix: \"/_matrix/client/unstable/org.matrix.msc3391\" }\n : undefined;\n return await this.http.authedRequest(Method.Delete, path, undefined, undefined, options);\n }\n\n /**\n * Gets the users that are ignored by this client\n * @returns The array of users that are ignored (empty if none)\n */\n public getIgnoredUsers(): string[] {\n const event = this.getAccountData(\"m.ignored_user_list\");\n if (!event || !event.getContent() || !event.getContent()[\"ignored_users\"]) return [];\n return Object.keys(event.getContent()[\"ignored_users\"]);\n }\n\n /**\n * Sets the users that the current user should ignore.\n * @param userIds - the user IDs to ignore\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setIgnoredUsers(userIds: string[]): Promise<{}> {\n const content = { ignored_users: {} as Record<string, object> };\n userIds.forEach((u) => {\n content.ignored_users[u] = {};\n });\n return this.setAccountData(\"m.ignored_user_list\", content);\n }\n\n /**\n * Gets whether or not a specific user is being ignored by this client.\n * @param userId - the user ID to check\n * @returns true if the user is ignored, false otherwise\n */\n public isUserIgnored(userId: string): boolean {\n return this.getIgnoredUsers().includes(userId);\n }\n\n /**\n * Join a room. If you have already joined the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to join.\n * @param opts - Options when joining the room.\n * @returns Promise which resolves: Room object.\n * @returns Rejects: with an error response.\n */\n public async joinRoom(roomIdOrAlias: string, opts: IJoinRoomOpts = {}): Promise<Room> {\n if (opts.syncRoom === undefined) {\n opts.syncRoom = true;\n }\n\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return room;\n\n let signPromise: Promise<IThirdPartySigned | void> = Promise.resolve();\n\n if (opts.inviteSignUrl) {\n const url = new URL(opts.inviteSignUrl);\n url.searchParams.set(\"mxid\", this.credentials.userId!);\n signPromise = this.http.requestOtherUrl<IThirdPartySigned>(Method.Post, url);\n }\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const data: IJoinRequestBody = {};\n const signedInviteObj = await signPromise;\n if (signedInviteObj) {\n data.third_party_signed = signedInviteObj;\n }\n\n const path = utils.encodeUri(\"/join/$roomid\", { $roomid: roomIdOrAlias });\n const res = await this.http.authedRequest<{ room_id: string }>(Method.Post, path, queryParams, data);\n\n const roomId = res.room_id;\n // In case we were originally given an alias, check the room cache again\n // with the resolved ID - this method is supposed to no-op if we already\n // were in the room, after all.\n const resolvedRoom = this.getRoom(roomId);\n if (resolvedRoom?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return resolvedRoom;\n\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n const syncRoom = syncApi.createRoom(roomId);\n if (opts.syncRoom) {\n // v2 will do this for us\n // return syncApi.syncRoom(room);\n }\n return syncRoom;\n }\n\n /**\n * Knock a room. If you have already knocked the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to knock.\n * @param opts - Options when knocking the room.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public knockRoom(roomIdOrAlias: string, opts: KnockRoomOpts = {}): Promise<{ room_id: string }> {\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Knock)) {\n return Promise.resolve({ room_id: room.roomId });\n }\n\n const path = utils.encodeUri(\"/knock/$roomIdOrAlias\", { $roomIdOrAlias: roomIdOrAlias });\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const body: Record<string, string> = {};\n if (opts.reason) {\n body.reason = opts.reason;\n }\n\n return this.http.authedRequest(Method.Post, path, queryParams, body);\n }\n\n /**\n * Resend an event. Will also retry any to-device messages waiting to be sent.\n * @param event - The event to resend.\n * @param room - Optional. The room the event is in. Will update the\n * timeline entry if provided.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public resendEvent(event: MatrixEvent, room: Room): Promise<ISendEventResponse> {\n // also kick the to-device queue to retry\n this.toDeviceMessageQueue.sendQueue();\n\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n return this.encryptAndSendEvent(room, event);\n }\n\n /**\n * Cancel a queued or unsent event.\n *\n * @param event - Event to cancel\n * @throws Error if the event is not in QUEUED, NOT_SENT or ENCRYPTING state\n */\n public cancelPendingEvent(event: MatrixEvent): void {\n if (![EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.ENCRYPTING].includes(event.status!)) {\n throw new Error(\"cannot cancel an event with status \" + event.status);\n }\n\n // If the event is currently being encrypted then remove it from the pending list, to indicate that it should\n // not be sent.\n if (event.status === EventStatus.ENCRYPTING) {\n this.eventsBeingEncrypted.delete(event.getId()!);\n } else if (this.scheduler && event.status === EventStatus.QUEUED) {\n // tell the scheduler to forget about it, if it's queued\n this.scheduler.removeEventFromQueue(event);\n }\n\n // then tell the room about the change of state, which will remove it\n // from the room's list of pending events.\n const room = this.getRoom(event.getRoomId());\n this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomName(roomId: string, name: string): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, EventType.RoomName, { name: name });\n }\n\n /**\n * @param htmlTopic - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomTopic(roomId: string, topic: string, htmlTopic?: string): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeTopicContent(topic, htmlTopic);\n return this.sendStateEvent(roomId, EventType.RoomTopic, content);\n }\n\n /**\n * @returns Promise which resolves: to an object keyed by tagId with objects containing a numeric order field.\n * @returns Rejects: with an error response.\n */\n public getRoomTags(roomId: string): Promise<ITagsResponse> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param tagName - name of room tag to be set\n * @param metadata - associated with that tag to be stored\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public setRoomTag(roomId: string, tagName: string, metadata: ITagMetadata = {}): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Put, path, undefined, metadata);\n }\n\n /**\n * @param tagName - name of room tag to be removed\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public deleteRoomTag(roomId: string, tagName: string): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * @param eventType - event type to be set\n * @param content - event content\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomAccountData(roomId: string, eventType: string, content: Record<string, any>): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $type: eventType,\n });\n return this.http.authedRequest(Method.Put, path, undefined, content);\n }\n\n /**\n * Set a power level to one or multiple users.\n * Will apply changes atop of current power level event from local state if running & synced, falling back\n * to fetching latest from the `/state/` API.\n * @param roomId - the room to update power levels in\n * @param userId - the ID of the user or users to update power levels of\n * @param powerLevel - the numeric power level to update given users to\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public async setPowerLevel(\n roomId: string,\n userId: string | string[],\n powerLevel: number | undefined,\n ): Promise<ISendEventResponse> {\n let content: IPowerLevelsContent | undefined;\n if (this.clientRunning && this.isInitialSyncComplete()) {\n content = this.getRoom(roomId)?.currentState?.getStateEvents(EventType.RoomPowerLevels, \"\")?.getContent();\n }\n if (!content) {\n try {\n content = await this.getStateEvent(roomId, EventType.RoomPowerLevels, \"\");\n } catch (e) {\n // It is possible for a Matrix room to not have a power levels event\n if (e instanceof MatrixError && e.errcode === \"M_NOT_FOUND\") {\n content = {};\n } else {\n throw e;\n }\n }\n }\n\n // take a copy of the content to ensure we don't corrupt\n // existing client state with a failed power level change\n content = utils.deepCopy(content);\n\n if (!content?.users) {\n content.users = {};\n }\n const users = Array.isArray(userId) ? userId : [userId];\n for (const user of users) {\n if (powerLevel == null) {\n delete content.users[user];\n } else {\n content.users[user] = powerLevel;\n }\n }\n\n return this.sendStateEvent(roomId, EventType.RoomPowerLevels, content, \"\");\n }\n\n /**\n * Create an m.beacon_info event\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_createLiveBeacon(\n roomId: Room[\"roomId\"],\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.unstable_setLiveBeacon(roomId, beaconInfoContent);\n }\n\n /**\n * Upsert a live beacon event\n * using a specific m.beacon_info.* event variable type\n * @param roomId - string\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_setLiveBeacon(\n roomId: string,\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, M_BEACON_INFO.name, beaconInfoContent, this.getUserId()!);\n }\n\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent(\n roomId: string,\n threadIdOrEventType: string | null,\n eventTypeOrContent: string | IContent,\n contentOrTxnId?: IContent | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse> {\n let threadId: string | null;\n let eventType: string;\n let content: IContent;\n let txnId: string | undefined;\n if (!threadIdOrEventType?.startsWith(EVENT_ID_PREFIX) && threadIdOrEventType !== null) {\n txnId = contentOrTxnId as string;\n content = eventTypeOrContent as IContent;\n eventType = threadIdOrEventType;\n threadId = null;\n } else {\n txnId = txnIdOrVoid;\n content = contentOrTxnId as IContent;\n eventType = eventTypeOrContent as string;\n threadId = threadIdOrEventType;\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, txnId);\n }\n\n /**\n * If we expect that an event is part of a thread but is missing the relation\n * we need to add it manually, as well as the reply fallback\n */\n private addThreadRelationIfNeeded(content: IContent, threadId: string | null, roomId: string): void {\n if (threadId && !content[\"m.relates_to\"]?.rel_type) {\n const isReply = !!content[\"m.relates_to\"]?.[\"m.in_reply_to\"];\n content[\"m.relates_to\"] = {\n ...content[\"m.relates_to\"],\n rel_type: THREAD_RELATION_TYPE.name,\n event_id: threadId,\n // Set is_falling_back to true unless this is actually intended to be a reply\n is_falling_back: !isReply,\n };\n const thread = this.getRoom(roomId)?.getThread(threadId);\n if (thread && !isReply) {\n content[\"m.relates_to\"][\"m.in_reply_to\"] = {\n event_id:\n thread\n .lastReply((ev: MatrixEvent) => {\n return ev.isRelation(THREAD_RELATION_TYPE.name) && !ev.status;\n })\n ?.getId() ?? threadId,\n };\n }\n }\n }\n\n /**\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n /**\n * Sends a delayed event (MSC4140).\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param delayOpts - Properties of the delay for this event.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOpts: SendDelayedEventRequestOpts,\n txnId?: string,\n ): Promise<SendDelayedEventResponse>;\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOptsOrTxnId?: SendDelayedEventRequestOpts | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let delayOpts: SendDelayedEventRequestOpts | undefined;\n let txnId: string | undefined;\n if (typeof delayOptsOrTxnId === \"string\") {\n txnId = delayOptsOrTxnId;\n } else {\n delayOpts = delayOptsOrTxnId;\n txnId = txnIdOrVoid;\n }\n\n if (!txnId) {\n txnId = this.makeTxnId();\n }\n\n // We always construct a MatrixEvent when sending because the store and scheduler use them.\n // We'll extract the params back out if it turns out the client has no scheduler or store.\n const localEvent = new MatrixEvent(\n Object.assign(eventObject, {\n event_id: \"~\" + roomId + \":\" + txnId,\n user_id: this.credentials.userId,\n sender: this.credentials.userId,\n room_id: roomId,\n origin_server_ts: new Date().getTime(),\n }),\n );\n\n const room = this.getRoom(roomId);\n const thread = threadId ? room?.getThread(threadId) : undefined;\n if (thread) {\n localEvent.setThread(thread);\n }\n\n if (!delayOpts) {\n // set up re-emitter for this new event - this is normally the job of EventMapper but we don't use it here\n this.reEmitter.reEmit(localEvent, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n room?.reEmitter.reEmit(localEvent, [MatrixEventEvent.BeforeRedaction]);\n }\n\n // if this is a relation or redaction of an event\n // that hasn't been sent yet (e.g. with a local id starting with a ~)\n // then listen for the remote echo of that event so that by the time\n // this event does get sent, we have the correct event_id\n const targetId = localEvent.getAssociatedId();\n if (targetId?.startsWith(\"~\")) {\n const target = room?.getPendingEvents().find((e) => e.getId() === targetId);\n target?.once(MatrixEventEvent.LocalEventIdReplaced, () => {\n localEvent.updateAssociatedId(target.getId()!);\n });\n }\n\n const type = localEvent.getType();\n this.logger.debug(\n `sendEvent of type ${type} in ${roomId} with txnId ${txnId}${delayOpts ? \" (delayed event)\" : \"\"}`,\n );\n\n localEvent.setTxnId(txnId);\n localEvent.setStatus(EventStatus.SENDING);\n\n // TODO: separate store for delayed events?\n if (!delayOpts) {\n // add this event immediately to the local store as 'sending'.\n room?.addPendingEvent(localEvent, txnId);\n\n // addPendingEvent can change the state to NOT_SENT if it believes\n // that there's other events that have failed. We won't bother to\n // try sending the event if the state has changed as such.\n if (localEvent.status === EventStatus.NOT_SENT) {\n return Promise.reject(new Error(\"Event blocked by other events not yet sent\"));\n }\n\n return this.encryptAndSendEvent(room, localEvent);\n } else {\n return this.encryptAndSendEvent(room, localEvent, delayOpts);\n }\n }\n\n /**\n * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent\n * @returns returns a promise which resolves with the result of the send request\n */\n protected async encryptAndSendEvent(room: Room | null, event: MatrixEvent): Promise<ISendEventResponse>;\n /**\n * Simply sends a delayed event without encrypting it.\n * TODO: Allow encrypted delayed events, and encrypt them properly\n * @param delayOpts - Properties of the delay for this event.\n * @returns returns a promise which resolves with the result of the delayed send request\n */\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n if (delayOpts) {\n return this.sendEventHttpRequest(event, delayOpts);\n }\n\n try {\n this.eventsBeingEncrypted.add(event.getId()!);\n\n // encryptEventIfNeeded may have updated the status from SENDING to ENCRYPTING. If so, we need\n // to put it back.\n if (event.status === EventStatus.ENCRYPTING) {\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n }\n\n let promise: Promise<ISendEventResponse> | null = null;\n if (this.scheduler) {\n // if this returns a promise then the scheduler has control now and will\n // resolve/reject when it is done. Internally, the scheduler will invoke\n // processFn which is set to this._sendEventHttpRequest so the same code\n // path is executed regardless.\n promise = this.scheduler.queueEvent(event);\n if (promise && this.scheduler.getQueueForEvent(event)!.length > 1) {\n // event is processed FIFO so if the length is 2 or more we know\n // this event is stuck behind an earlier event.\n this.updatePendingEventStatus(room, event, EventStatus.QUEUED);\n }\n }\n\n if (!promise) {\n promise = this.sendEventHttpRequest(event);\n if (room) {\n promise = promise.then((res) => {\n room.updatePendingEvent(event, EventStatus.SENT, res[\"event_id\"]);\n return res;\n });\n }\n }\n\n return await promise;\n } catch (err) {\n this.logger.error(\"Error sending event\", err);\n try {\n // set the error on the event before we update the status:\n // updating the status emits the event, so the state should be\n // consistent at that point.\n event.error = <MatrixError>err;\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n } catch (e) {\n this.logger.error(\"Exception in error handler!\", e);\n }\n if (err instanceof MatrixError) {\n err.event = event;\n }\n throw err;\n }\n }\n\n /**\n * Returns the eventType that should be used taking encryption into account\n * for a given eventType.\n * @param roomId - the room for the events `eventType` relates to\n * @param eventType - the event type\n * @returns the event type taking encryption into account\n */\n private getEncryptedIfNeededEventType(\n roomId: string,\n eventType?: EventType | string | null,\n ): EventType | string | null | undefined {\n if (eventType === EventType.Reaction) return eventType;\n return this.getRoom(roomId)?.hasEncryptionStateEvent() ? EventType.RoomMessageEncrypted : eventType;\n }\n\n protected updatePendingEventStatus(room: Room | null, event: MatrixEvent, newStatus: EventStatus): void {\n if (room) {\n room.updatePendingEvent(event, newStatus);\n } else {\n event.setStatus(newStatus);\n }\n }\n\n private sendEventHttpRequest(event: MatrixEvent): Promise<ISendEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let txnId = event.getTxnId();\n if (!txnId) {\n txnId = this.makeTxnId();\n event.setTxnId(txnId);\n }\n\n const pathParams = {\n $roomId: event.getRoomId()!,\n $eventType: event.getWireType(),\n $stateKey: event.getStateKey()!,\n $txnId: txnId,\n };\n\n let path: string;\n\n if (event.isState()) {\n let pathTemplate = \"/rooms/$roomId/state/$eventType\";\n if (event.getStateKey() && event.getStateKey()!.length > 0) {\n pathTemplate = \"/rooms/$roomId/state/$eventType/$stateKey\";\n }\n path = utils.encodeUri(pathTemplate, pathParams);\n } else if (event.isRedaction() && event.event.redacts) {\n const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`;\n path = utils.encodeUri(pathTemplate, {\n $redactsEventId: event.event.redacts,\n ...pathParams,\n });\n } else {\n path = utils.encodeUri(\"/rooms/$roomId/send/$eventType/$txnId\", pathParams);\n }\n\n const content = event.getWireContent();\n if (!delayOpts) {\n return this.http.authedRequest<ISendEventResponse>(Method.Put, path, undefined, content).then((res) => {\n this.logger.debug(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`);\n return res;\n });\n } else {\n return this.http.authedRequest<SendDelayedEventResponse>(\n Method.Put,\n path,\n getUnstableDelayQueryOpts(delayOpts),\n content,\n );\n }\n }\n\n /**\n * @param txnId - transaction id. One will be made up if not supplied.\n * @param opts - Redact options\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if called with `with_rel_types` (MSC3912) but the server does not support it.\n * Callers should check whether the server supports MSC3912 via `MatrixClient.canSupport`.\n */\n public redactEvent(\n roomId: string,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId?: string,\n txnId?: string | IRedactOpts,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse> {\n if (!eventId?.startsWith(EVENT_ID_PREFIX)) {\n opts = txnId as IRedactOpts;\n txnId = eventId;\n eventId = threadId!;\n threadId = null;\n }\n const reason = opts?.reason;\n const content: IContent = { reason };\n\n if (opts?.with_rel_types !== undefined) {\n if (this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Unsupported) {\n throw new Error(\n \"Server does not support relation based redactions \" +\n `roomId ${roomId} eventId ${eventId} txnId: ${txnId} threadId ${threadId}`,\n );\n }\n\n const withRelTypesPropName =\n this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Stable\n ? MSC3912_RELATION_BASED_REDACTIONS_PROP.stable!\n : MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable!;\n\n content[withRelTypesPropName] = opts.with_rel_types;\n }\n\n return this.sendCompleteEvent(\n roomId,\n threadId,\n {\n type: EventType.RoomRedaction,\n content,\n redacts: eventId,\n },\n txnId as string,\n );\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendMessage(roomId: string, content: RoomMessageEventContent, txnId?: string): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null,\n content: RoomMessageEventContent,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null | RoomMessageEventContent,\n content?: RoomMessageEventContent | string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (typeof threadId !== \"string\" && threadId !== null) {\n txnId = content as string;\n content = threadId as RoomMessageEventContent;\n threadId = null;\n }\n\n const eventType = EventType.RoomMessage;\n const sendContent = content as RoomMessageEventContent;\n\n return this.sendEvent(roomId, threadId as string | null, eventType, sendContent, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns\n * @returns Rejects: with an error response.\n */\n public sendTextMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeTextMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendNotice(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeNotice(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendEmoteMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeEmoteMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendImageMessage(roomId: string, url: string, info?: ImageInfo, text?: string): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Image\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Image\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n msgtype: MsgType.Image,\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies RoomMessageEventContent;\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendStickerMessage(\n roomId: string,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Sticker\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Sticker\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies StickerEventContent;\n\n return this.sendEvent(roomId, threadId, EventType.Sticker, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlMessage(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlMessage(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlNotice(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlNotice(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlEmote(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlEmote(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * Send a delayed timeline event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedEvent<K extends keyof TimelineEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, delayOpts, txnId);\n }\n\n /**\n * Send a delayed state event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedStateEvent<K extends keyof StateEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, getUnstableDelayQueryOpts(delayOpts), content as Body, opts);\n }\n\n /**\n * Get all pending delayed events for the calling user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_getDelayedEvents(fromToken?: string): Promise<DelayedEventInfo> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const queryDict = fromToken ? { from: fromToken } : undefined;\n return await this.http.authedRequest(Method.Get, \"/delayed_events\", queryDict, undefined, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Manage a delayed event associated with the given delay_id.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_updateDelayedEvent(delayId: string, action: UpdateDelayedEventAction): Promise<{}> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const path = utils.encodeUri(\"/delayed_events/$delayId\", {\n $delayId: delayId,\n });\n const data = {\n action,\n };\n return await this.http.authedRequest(Method.Post, path, undefined, data, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Send a receipt.\n * @param event - The event being acknowledged\n * @param receiptType - The kind of receipt e.g. \"m.read\". Other than\n * ReceiptType.Read are experimental!\n * @param body - Additional content to send alongside the receipt.\n * @param unthreaded - An unthreaded receipt will clear room+thread notifications\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReceipt(\n event: MatrixEvent,\n receiptType: ReceiptType,\n body?: Record<string, any>,\n unthreaded = false,\n ): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send receipts so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/receipt/$receiptType/$eventId\", {\n $roomId: event.getRoomId()!,\n $receiptType: receiptType,\n $eventId: event.getId()!,\n });\n\n // Unless we're explicitly making an unthreaded receipt or we don't\n // support threads, include the `thread_id` property in the body.\n const shouldAddThreadId = !unthreaded && this.supportsThreads();\n const fullBody = shouldAddThreadId ? { ...body, thread_id: threadIdForReceipt(event) } : body;\n\n const promise = this.http.authedRequest<{}>(Method.Post, path, undefined, fullBody || {});\n\n const room = this.getRoom(event.getRoomId());\n if (room && this.credentials.userId) {\n room.addLocalEchoReceipt(this.credentials.userId, event, receiptType, unthreaded);\n }\n return promise;\n }\n\n /**\n * Send a read receipt.\n * @param event - The event that has been read.\n * @param receiptType - other than ReceiptType.Read are experimental! Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReadReceipt(\n event: MatrixEvent | null,\n receiptType = ReceiptType.Read,\n unthreaded = false,\n ): Promise<{} | undefined> {\n if (!event) return;\n const eventId = event.getId()!;\n const room = this.getRoom(event.getRoomId());\n if (room?.hasPendingEvent(eventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${eventId})`);\n }\n\n return this.sendReceipt(event, receiptType, {}, unthreaded);\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEvent - the event tracked by the read receipt. This is here for\n * convenience because the RR and the RM are commonly updated at the same time as each\n * other. The local echo of this receipt will be done if set. Optional.\n * @param rpEvent - the m.read.private read receipt event for when we don't\n * want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkers(\n roomId: string,\n rmEventId: string,\n rrEvent?: MatrixEvent,\n rpEvent?: MatrixEvent,\n ): Promise<{}> {\n const room = this.getRoom(roomId);\n if (room?.hasPendingEvent(rmEventId)) {\n throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);\n }\n\n // Add the optional RR update, do local echo like `sendReceipt`\n let rrEventId: string | undefined;\n if (rrEvent) {\n rrEventId = rrEvent.getId()!;\n if (room?.hasPendingEvent(rrEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rrEvent, ReceiptType.Read);\n }\n\n // Add the optional private RR update, do local echo like `sendReceipt`\n let rpEventId: string | undefined;\n if (rpEvent) {\n rpEventId = rpEvent.getId()!;\n if (room?.hasPendingEvent(rpEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rpEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rpEvent, ReceiptType.ReadPrivate);\n }\n\n return await this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId);\n }\n\n /**\n * Get a preview of the given URL as of (roughly) the given point in time,\n * described as an object with OpenGraph keys and associated values.\n * Attributes may be synthesized where actual OG metadata is lacking.\n * Caches results to prevent hammering the server.\n * @param url - The URL to get preview data for\n * @param ts - The preferred point in time that the preview should\n * describe (ms since epoch). The preview returned will either be the most\n * recent one preceding this timestamp if available, or failing that the next\n * most recent available preview.\n * @returns Promise which resolves: Object of OG metadata.\n * @returns Rejects: with an error response.\n * May return synthesized attributes if the URL lacked OG meta.\n */\n public getUrlPreview(url: string, ts: number): Promise<IPreviewUrlResponse> {\n // bucket the timestamp to the nearest minute to prevent excessive spam to the server\n // Surely 60-second accuracy is enough for anyone.\n ts = Math.floor(ts / 60000) * 60000;\n\n const parsed = new URL(url);\n parsed.hash = \"\"; // strip the hash as it won't affect the preview\n url = parsed.toString();\n\n const key = ts + \"_\" + url;\n\n // If there's already a request in flight (or we've handled it), return that instead.\n if (key in this.urlPreviewCache) {\n return this.urlPreviewCache[key];\n }\n\n const resp = this.http.authedRequest<IPreviewUrlResponse>(\n Method.Get,\n \"/preview_url\",\n {\n url,\n ts: ts.toString(),\n },\n undefined,\n {\n prefix: MediaPrefix.V3,\n priority: \"low\",\n },\n );\n // TODO: Expire the URL preview cache sometimes\n this.urlPreviewCache[key] = resp;\n return resp;\n }\n\n /**\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public sendTyping(roomId: string, isTyping: boolean, timeoutMs: number): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send typing notifications so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/typing/$userId\", {\n $roomId: roomId,\n $userId: this.getUserId()!,\n });\n const data: QueryDict = {\n typing: isTyping,\n };\n if (isTyping) {\n data.timeout = timeoutMs ? timeoutMs : 20000;\n }\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Determines the history of room upgrades for a given room, as far as the\n * client can see. Returns an array of Rooms where the first entry is the\n * oldest and the last entry is the newest (likely current) room. If the\n * provided room is not found, this returns an empty list. This works in\n * both directions, looking for older and newer rooms of the given room.\n * @param roomId - The room ID to search from\n * @param verifyLinks - If true, the function will only return rooms\n * which can be proven to be linked. For example, rooms which have a create\n * event pointing to an old room which the client is not aware of or doesn't\n * have a matching tombstone would not be returned.\n * @param msc3946ProcessDynamicPredecessor - if true, look for\n * m.room.predecessor state events as well as create events, and prefer\n * predecessor events where they exist (MSC3946).\n * @returns An array of rooms representing the upgrade\n * history.\n */\n public getRoomUpgradeHistory(\n roomId: string,\n verifyLinks = false,\n msc3946ProcessDynamicPredecessor = false,\n ): Room[] {\n const currentRoom = this.getRoom(roomId);\n if (!currentRoom) return [];\n\n const before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n const after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n\n return [...before, currentRoom, ...after];\n }\n\n private findPredecessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n const seenRoomIDs = new Set<string>([room.roomId]);\n\n // Work backwards from newer to older rooms\n let predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n while (predecessorRoomId !== null) {\n if (predecessorRoomId) {\n if (seenRoomIDs.has(predecessorRoomId)) break;\n seenRoomIDs.add(predecessorRoomId);\n }\n const predecessorRoom = this.getRoom(predecessorRoomId);\n if (predecessorRoom === null) {\n break;\n }\n if (verifyLinks) {\n const tombstone = predecessorRoom.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (!tombstone || tombstone.getContent()[\"replacement_room\"] !== room.roomId) {\n break;\n }\n }\n\n // Insert at the front because we're working backwards from the currentRoom\n ret.splice(0, 0, predecessorRoom);\n\n room = predecessorRoom;\n predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n }\n return ret;\n }\n\n private findSuccessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n\n // Work forwards, looking at tombstone events\n let tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n while (tombstoneEvent) {\n const successorRoom = this.getRoom(tombstoneEvent.getContent()[\"replacement_room\"]);\n if (!successorRoom) break; // end of the chain\n if (successorRoom.roomId === room.roomId) break; // Tombstone is referencing its own room\n\n if (verifyLinks) {\n const predecessorRoomId = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (!predecessorRoomId || predecessorRoomId !== room.roomId) {\n break;\n }\n }\n\n // Push to the end because we're looking forwards\n ret.push(successorRoom);\n const roomIds = new Set(ret.map((ref) => ref.roomId));\n if (roomIds.size < ret.length) {\n // The last room added to the list introduced a previous roomId\n // To avoid recursion, return the last rooms - 1\n return ret.slice(0, ret.length - 1);\n }\n\n // Set the current room to the reference room so we know where we're at\n room = successorRoom;\n tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n }\n return ret;\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public invite(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Invite, reason);\n }\n\n /**\n * Invite a user to a room based on their email address.\n * @param roomId - The room to invite the user to.\n * @param email - The email address to invite.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public inviteByEmail(roomId: string, email: string): Promise<{}> {\n return this.inviteByThreePid(roomId, \"email\", email);\n }\n\n /**\n * Invite a user to a room based on a third-party identifier.\n * @param roomId - The room to invite the user to.\n * @param medium - The medium to invite the user e.g. \"email\".\n * @param address - The address for the specified medium.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async inviteByThreePid(roomId: string, medium: string, address: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/invite\", { $roomId: roomId });\n\n const identityServerUrl = this.getIdentityServerUrl(true);\n if (!identityServerUrl) {\n return Promise.reject(\n new MatrixError({\n error: \"No supplied identity server URL\",\n errcode: \"ORG.MATRIX.JSSDK_MISSING_PARAM\",\n }),\n );\n }\n const params: Record<string, string> = {\n id_server: identityServerUrl,\n medium: medium,\n address: address,\n };\n\n if (this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n params[\"id_access_token\"] = identityAccessToken;\n }\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, params);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public leave(roomId: string): Promise<{}> {\n return this.membershipChange(roomId, undefined, KnownMembership.Leave);\n }\n\n /**\n * Leaves all rooms in the chain of room upgrades based on the given room. By\n * default, this will leave all the previous and upgraded rooms, including the\n * given room. To only leave the given room and any previous rooms, keeping the\n * upgraded (modern) rooms untouched supply `false` to `includeFuture`.\n * @param roomId - The room ID to start leaving at\n * @param includeFuture - If true, the whole chain (past and future) of\n * upgraded rooms will be left.\n * @returns Promise which resolves when completed with an object keyed\n * by room ID and value of the error encountered when leaving or null.\n */\n public leaveRoomChain(\n roomId: string,\n includeFuture = true,\n ): Promise<{ [roomId: string]: Error | MatrixError | null }> {\n const upgradeHistory = this.getRoomUpgradeHistory(roomId);\n\n let eligibleToLeave = upgradeHistory;\n if (!includeFuture) {\n eligibleToLeave = [];\n for (const room of upgradeHistory) {\n eligibleToLeave.push(room);\n if (room.roomId === roomId) {\n break;\n }\n }\n }\n\n const populationResults: { [roomId: string]: Error } = {};\n const promises: Promise<unknown>[] = [];\n\n const doLeave = (roomId: string): Promise<void> => {\n return this.leave(roomId)\n .then(() => {\n delete populationResults[roomId];\n })\n .catch((err) => {\n // suppress error\n populationResults[roomId] = err;\n });\n };\n\n for (const room of eligibleToLeave) {\n promises.push(doLeave(room.roomId));\n }\n\n return Promise.all(promises).then(() => populationResults);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public ban(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Ban, reason);\n }\n\n /**\n * @param deleteRoom - True to delete the room from the store on success.\n * Default: true.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async forget(roomId: string, deleteRoom = true): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/forget\", {\n $room_id: roomId,\n });\n const response = await this.http.authedRequest<{}>(Method.Post, path);\n if (deleteRoom) {\n this.store.removeRoom(roomId);\n this.emit(ClientEvent.DeleteRoom, roomId);\n }\n return response;\n }\n\n /**\n * @returns Promise which resolves: Object (currently empty)\n * @returns Rejects: with an error response.\n */\n public unban(roomId: string, userId: string): Promise<{}> {\n // unbanning != set their state to leave: this used to be\n // the case, but was then changed so that leaving was always\n // a revoking of privilege, otherwise two people racing to\n // kick / ban someone could end up banning and then un-banning\n // them.\n const path = utils.encodeUri(\"/rooms/$roomId/unban\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public kick(roomId: string, userId: string, reason?: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/kick\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n reason: reason,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n private membershipChange(\n roomId: string,\n userId: string | undefined,\n membership: Membership,\n reason?: string,\n ): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/$membership\", {\n $room_id: roomId,\n $membership: membership,\n });\n return this.http.authedRequest(Method.Post, path, undefined, {\n user_id: userId, // may be undefined e.g. on leave\n reason: reason,\n });\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushActionsForEvent(event: MatrixEvent, forceRecalculate = false): IActionsObject | null {\n if (!event.getPushActions() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushActions();\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushDetailsForEvent(event: MatrixEvent, forceRecalculate = false): PushDetails | null {\n if (!event.getPushDetails() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushDetails();\n }\n\n /**\n * @param info - The kind of info to set (e.g. 'avatar_url')\n * @param data - The JSON object to set.\n * @returns\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setProfileInfo(info: \"avatar_url\", data: { avatar_url: string }): Promise<{}>;\n public setProfileInfo(info: \"displayname\", data: { displayname: string }): Promise<{}>;\n public setProfileInfo(info: \"avatar_url\" | \"displayname\", data: object): Promise<{}> {\n const path = utils.encodeUri(\"/profile/$userId/$info\", {\n $userId: this.credentials.userId!,\n $info: info,\n });\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setDisplayName(name: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"displayname\", { displayname: name });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.displayName = name;\n user.emit(UserEvent.DisplayName, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setAvatarUrl(url: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"avatar_url\", { avatar_url: url });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.avatarUrl = url;\n user.emit(UserEvent.AvatarUrl, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * Turn an MXC URL into an HTTP one. <strong>This method is experimental and\n * may change.</strong>\n * @param mxcUrl - The MXC URL\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return null for such URLs.\n * @param allowRedirects - If true, the caller supports the URL being 307 or\n * 308 redirected to another resource upon request. If false, redirects\n * are not expected. Implied `true` when `useAuthentication` is `true`.\n * @param useAuthentication - If true, the caller supports authenticated\n * media and wants an authentication-required URL. Note that server support\n * for authenticated media will *not* be checked - it is the caller's responsibility\n * to do so before calling this function. Note also that `useAuthentication`\n * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n * @returns the avatar URL or null.\n */\n public mxcUrlToHttp(\n mxcUrl: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks?: boolean,\n allowRedirects?: boolean,\n useAuthentication?: boolean,\n ): string | null {\n return getHttpUriForMxc(\n this.baseUrl,\n mxcUrl,\n width,\n height,\n resizeMethod,\n allowDirectLinks,\n allowRedirects,\n useAuthentication,\n );\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * This has an advantage over calls to the PUT /presence API in that it\n * doesn't clobber status_msg set by other devices.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public async setSyncPresence(presence?: SetPresence): Promise<void> {\n this.syncApi?.setPresence(presence);\n }\n\n /**\n * @param opts - Options to apply\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n * @throws If 'presence' isn't a valid presence enum value.\n */\n public async setPresence(opts: IPresenceOpts): Promise<void> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: this.credentials.userId!,\n });\n\n const validStates = [\"offline\", \"online\", \"unavailable\"];\n if (validStates.indexOf(opts.presence) === -1) {\n throw new Error(\"Bad presence value: \" + opts.presence);\n }\n await this.http.authedRequest(Method.Put, path, undefined, opts);\n }\n\n /**\n * @param userId - The user to get presence for\n * @returns Promise which resolves: The presence state for this user.\n * @returns Rejects: with an error response.\n */\n public getPresence(userId: string): Promise<IStatusResponse> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: userId,\n });\n\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve older messages from the given room and put them in the timeline.\n *\n * If this is called multiple times whilst a request is ongoing, the <i>same</i>\n * Promise will be returned. If there was a problem requesting scrollback, there\n * will be a small delay before another request can be made (to prevent tight-looping\n * when there is no connection).\n *\n * @param room - The room to get older messages in.\n * @param limit - Optional. The maximum number of previous events to\n * pull in. Default: 30.\n * @returns Promise which resolves: Room. If you are at the beginning\n * of the timeline, `Room.oldState.paginationToken` will be\n * `null`.\n * @returns Rejects: with an error response.\n */\n public scrollback(room: Room, limit = 30): Promise<Room> {\n let timeToWaitMs = 0;\n\n let info = this.ongoingScrollbacks[room.roomId] || {};\n if (info.promise) {\n return info.promise;\n } else if (info.errorTs) {\n const timeWaitedMs = Date.now() - info.errorTs;\n timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);\n }\n\n if (room.oldState.paginationToken === null) {\n return Promise.resolve(room); // already at the start.\n }\n // attempt to grab more events from the store first\n const numAdded = this.store.scrollback(room, limit).length;\n if (numAdded === limit) {\n // store contained everything we needed.\n return Promise.resolve(room);\n }\n // reduce the required number of events appropriately\n limit = limit - numAdded;\n\n const promise = new Promise<Room>((resolve, reject) => {\n // wait for a time before doing this request\n // (which may be 0 in order not to special case the code paths)\n sleep(timeToWaitMs)\n .then(() => {\n return this.createMessagesRequest(\n room.roomId,\n room.oldState.paginationToken,\n limit,\n Direction.Backward,\n );\n })\n .then((res: IMessagesResponse) => {\n const matrixEvents = res.chunk.map(this.getEventMapper());\n if (res.state) {\n const stateEvents = res.state.map(this.getEventMapper());\n room.currentState.setUnknownStateEvents(stateEvents);\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] =\n room.partitionThreadedEvents(matrixEvents);\n\n this.processAggregatedTimelineEvents(room, timelineEvents);\n room.addEventsToTimeline(timelineEvents, true, room.getLiveTimeline());\n this.processThreadEvents(room, threadedEvents, true);\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n room.oldState.paginationToken = res.end ?? null;\n if (res.chunk.length === 0) {\n room.oldState.paginationToken = null;\n }\n this.store.storeEvents(room, matrixEvents, res.end ?? null, true);\n delete this.ongoingScrollbacks[room.roomId];\n resolve(room);\n })\n .catch((err) => {\n this.ongoingScrollbacks[room.roomId] = {\n errorTs: Date.now(),\n };\n reject(err);\n });\n });\n\n info = { promise };\n\n this.ongoingScrollbacks[room.roomId] = info;\n return promise;\n }\n\n public getEventMapper(options?: MapperOpts): EventMapper {\n return eventMapperFor(this, options || {});\n }\n\n /**\n * Get an EventTimeline for the given event\n *\n * <p>If the EventTimelineSet object already has the given event in its store, the\n * corresponding timeline will be returned. Otherwise, a /context request is\n * made, and used to construct an EventTimeline.\n * If the event does not belong to this EventTimelineSet then undefined will be returned.\n *\n * @param timelineSet - The timelineSet to look for the event in, must be bound to a room\n * @param eventId - The ID of the event to look for\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} including the given event\n */\n public async getEventTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet?.room) {\n throw new Error(\"getEventTimeline only supports room timelines\");\n }\n\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n if (timelineSet.thread && this.supportsThreads()) {\n return this.getThreadTimeline(timelineSet, eventId);\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n let params: Record<string, string | string[]> | undefined = undefined;\n if (this.clientOpts?.lazyLoadMembers) {\n params = { filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER) };\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n if (!res.event) {\n throw new Error(\"'event' not in '/context' result - homeserver too old?\");\n }\n\n // by the time the request completes, the event might have ended up in the timeline.\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.logger.warn(\"Tried loading a regular timeline at the position of a thread event\");\n return undefined;\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...res.events_after.reverse().map(mapper),\n event,\n ...res.events_before.map(mapper),\n ];\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(events[0].getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n timeline.getState(EventTimeline.FORWARDS)!.paginationToken = res.end;\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] = timelineSet.room.partitionThreadedEvents(events);\n timelineSet.addEventsToTimeline(timelineEvents, true, timeline, res.start);\n // The target event is not in a thread but process the contextual events, so we can show any threads around it.\n this.processThreadEvents(timelineSet.room, threadedEvents, true);\n this.processAggregatedTimelineEvents(timelineSet.room, timelineEvents);\n unknownRelations.forEach((event) => timelineSet.relations.aggregateChildEvent(event));\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return (\n timelineSet.getTimelineForEvent(eventId) ??\n timelineSet.room.findThreadForEvent(event)?.liveTimeline ?? // for Threads degraded support\n timeline\n );\n }\n\n public async getThreadTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<EventTimeline | undefined> {\n if (!this.supportsThreads()) {\n throw new Error(\"could not get thread timeline: no client support\");\n }\n\n if (!timelineSet.room) {\n throw new Error(\"could not get thread timeline: not a room timeline\");\n }\n\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n const params: Record<string, string | string[]> = {\n limit: \"0\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n\n if (!timelineSet.canContain(event)) {\n return undefined;\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n if (Thread.hasServerSideSupport) {\n if (Thread.hasServerSideFwdPaginationSupport) {\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const thread = timelineSet.thread;\n const resOlder: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Forward, from: res.end, recurse: recurse || undefined },\n );\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...resNewer.chunk.reverse().filter(getRelationsThreadFilter(thread.id)).map(mapper),\n event,\n ...resOlder.chunk.filter(getRelationsThreadFilter(thread.id)).map(mapper),\n ];\n\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(event.getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n }\n\n timelineSet.addEventsToTimeline(events, true, timeline, resNewer.next_batch);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(resNewer.next_batch ?? null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return timelineSet.getTimelineForEvent(eventId) ?? timeline;\n } else {\n // Where the event is a thread reply (not a root) and running in MSC-enabled mode the Thread timeline only\n // functions contiguously, so we have to jump through some hoops to get our target event in it.\n // XXX: workaround for https://github.com/vector-im/element-meta/issues/150\n\n const thread = timelineSet.thread;\n\n const resOlder = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const eventsNewer: IEvent[] = [];\n let nextBatch: Optional<string> = res.end;\n while (nextBatch) {\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Forward, from: nextBatch, recurse: recurse || undefined },\n );\n nextBatch = resNewer.next_batch ?? null;\n eventsNewer.push(...resNewer.chunk);\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...eventsNewer.reverse().map(mapper),\n event,\n ...resOlder.chunk.map(mapper),\n ];\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread\n // summaries.\n const timeline = timelineSet.getLiveTimeline();\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n\n timelineSet.addEventsToTimeline(events, true, timeline, null);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n return timeline;\n }\n }\n }\n\n /**\n * Get an EventTimeline for the latest events in the room. This will just\n * call `/messages` to get the latest message in the room, then use\n * `client.getEventTimeline(...)` to construct a new timeline from it.\n *\n * @param timelineSet - The timelineSet to find or add the timeline to\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} timeline with the latest events in the room\n */\n public async getLatestTimeline(timelineSet: EventTimelineSet): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet.room) {\n throw new Error(\"getLatestTimeline only supports room timelines\");\n }\n\n let event: IRoomEvent | undefined;\n if (timelineSet.threadListType !== null) {\n const res = await this.createThreadListMessagesRequest(\n timelineSet.room.roomId,\n null,\n 1,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n event = res.chunk?.[0];\n } else if (timelineSet.thread && Thread.hasServerSideSupport) {\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n const res = await this.fetchRelations(\n timelineSet.room.roomId,\n timelineSet.thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, limit: 1, recurse: recurse || undefined },\n );\n event = res.chunk?.[0];\n } else {\n const messagesPath = utils.encodeUri(\"/rooms/$roomId/messages\", {\n $roomId: timelineSet.room.roomId,\n });\n\n const params: Record<string, string | string[]> = {\n dir: \"b\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n const res = await this.http.authedRequest<IMessagesResponse>(Method.Get, messagesPath, params);\n event = res.chunk?.[0];\n }\n if (!event) {\n throw new Error(\"No message returned when trying to construct getLatestTimeline\");\n }\n\n return this.getEventTimeline(timelineSet, event.event_id);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used in code.\n public createMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir: Direction,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/messages\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter | null = null;\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = filter || {};\n Object.assign(filter, timelineFilter.getRoomTimelineFilterComponent()?.toJSON());\n }\n if (filter) {\n params.filter = JSON.stringify(filter);\n }\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used by room.fetchRoomThreads\n public createThreadListMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir = Direction.Backward,\n threadListType: ThreadFilterType | null = ThreadFilterType.All,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/threads\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n include: threadFilterTypeToFilter(threadListType),\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter = {};\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = {\n ...Filter.LAZY_LOADING_MESSAGES_FILTER,\n };\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = {\n ...filter,\n ...timelineFilter.getRoomTimelineFilterComponent()?.toJSON(),\n };\n }\n if (Object.keys(filter).length) {\n params.filter = JSON.stringify(filter);\n }\n\n const opts = {\n prefix:\n Thread.hasServerSideListSupport === FeatureSupport.Stable\n ? ClientPrefix.V1\n : \"/_matrix/client/unstable/org.matrix.msc3856\",\n };\n\n return this.http\n .authedRequest<IThreadedMessagesResponse>(Method.Get, path, params, undefined, opts)\n .then((res) => ({\n ...res,\n chunk: res.chunk?.reverse(),\n start: res.prev_batch,\n end: res.next_batch,\n }));\n }\n\n /**\n * Take an EventTimeline, and back/forward-fill results.\n *\n * @param eventTimeline - timeline object to be updated\n *\n * @returns Promise which resolves to a boolean: false if there are no\n * events and we reached either end of the timeline; else true.\n */\n public paginateEventTimeline(eventTimeline: EventTimeline, opts: IPaginateOpts): Promise<boolean> {\n const isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet;\n const room = this.getRoom(eventTimeline.getRoomId()!);\n const threadListType = eventTimeline.getTimelineSet().threadListType;\n const thread = eventTimeline.getTimelineSet().thread;\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n opts = opts || {};\n const backwards = opts.backwards || false;\n\n if (isNotifTimeline) {\n if (!backwards) {\n throw new Error(\"paginateNotifTimeline can only paginate backwards\");\n }\n }\n\n const dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n\n const token = eventTimeline.getPaginationToken(dir);\n const pendingRequest = eventTimeline.paginationRequests[dir];\n\n if (pendingRequest) {\n // already a request in progress - return the existing promise\n return pendingRequest;\n }\n\n let path: string;\n let params: Record<string, string>;\n let promise: Promise<boolean>;\n\n if (isNotifTimeline) {\n path = \"/notifications\";\n params = {\n limit: (opts.limit ?? 30).toString(),\n only: \"highlight\",\n };\n\n if (token && token !== \"end\") {\n params.from = token;\n }\n\n promise = this.http\n .authedRequest<INotificationsResponse>(Method.Get, path, params)\n .then(async (res) => {\n const token = res.next_token;\n const matrixEvents: MatrixEvent[] = [];\n\n res.notifications = res.notifications.filter(noUnsafeEventProps);\n\n for (let i = 0; i < res.notifications.length; i++) {\n const notification = res.notifications[i];\n const event = this.getEventMapper()(notification.event);\n\n // @TODO(kerrya) reprocessing every notification is ugly\n // remove if we get server MSC3994 support\n this.getPushDetailsForEvent(event, true);\n\n event.event.room_id = notification.room_id; // XXX: gutwrenching\n matrixEvents[i] = event;\n }\n\n // No need to partition events for threads here, everything lives\n // in the notification timeline set\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !res.next_token) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(res.next_token);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (threadListType !== null) {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n if (!Thread.hasServerSideFwdPaginationSupport && dir === Direction.Forward) {\n throw new Error(\"Cannot paginate threads forwards without server-side support for MSC 3715\");\n }\n\n promise = this.createThreadListMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n threadListType,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, matrixEvents);\n this.processThreadRoots(room, matrixEvents, backwards);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && res.end == res.start) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return res.end !== res.start;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (thread) {\n const room = this.getRoom(eventTimeline.getRoomId() ?? undefined);\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n promise = this.fetchRelations(eventTimeline.getRoomId() ?? \"\", thread.id, null, null, {\n dir,\n limit: opts.limit,\n from: token ?? undefined,\n recurse: recurse || undefined,\n })\n .then(async (res) => {\n const mapper = this.getEventMapper();\n const matrixEvents = res.chunk\n .filter(noUnsafeEventProps)\n .filter(getRelationsThreadFilter(thread.id))\n .map(mapper);\n\n // Process latest events first\n for (const event of matrixEvents.slice().reverse()) {\n await thread?.processEvent(event);\n const sender = event.getSender()!;\n if (!backwards || thread?.getEventReadUpTo(sender) === null) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n }\n\n const newToken = res.next_batch;\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, newToken ?? null);\n if (!newToken && backwards) {\n const originalEvent =\n thread.rootEvent ??\n mapper(await this.fetchRoomEvent(eventTimeline.getRoomId() ?? \"\", thread.id));\n timelineSet.addEventsToTimeline([originalEvent], true, eventTimeline, null);\n }\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !newToken) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(newToken);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n promise = this.createMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n const [timelineEvents, , unknownRelations] = room.partitionThreadedEvents(matrixEvents);\n timelineSet.addEventsToTimeline(timelineEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, timelineEvents);\n this.processThreadRoots(\n room,\n timelineEvents.filter((it) => it.getServerAggregatedRelation(THREAD_RELATION_TYPE.name)),\n false,\n );\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n const atEnd = res.end === undefined || res.end === res.start;\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && atEnd) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return !atEnd;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n }\n\n return promise;\n }\n\n /**\n * Reset the notifTimelineSet entirely, paginating in some historical notifs as\n * a starting point for subsequent pagination.\n */\n public resetNotifTimelineSet(): void {\n if (!this.notifTimelineSet) {\n return;\n }\n\n // FIXME: This thing is a total hack, and results in duplicate events being\n // added to the timeline both from /sync and /notifications, and lots of\n // slow and wasteful processing and pagination. The correct solution is to\n // extend /messages or /search or something to filter on notifications.\n\n // use the fictitious token 'end'. in practice we would ideally give it\n // the oldest backwards pagination token from /sync, but /sync doesn't\n // know about /notifications, so we have no choice but to start paginating\n // from the current point in time. This may well overlap with historical\n // notifs which are then inserted into the timeline by /sync responses.\n this.notifTimelineSet.resetLiveTimeline(\"end\");\n\n // we could try to paginate a single event at this point in order to get\n // a more valid pagination token, but it just ends up with an out of order\n // timeline. given what a mess this is and given we're going to have duplicate\n // events anyway, just leave it with the dummy token for now.\n /*\n this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {\n backwards: true,\n limit: 1\n });\n */\n }\n\n /**\n * Peek into a room and receive updates about the room. This only works if the\n * history visibility for the room is world_readable.\n * @param roomId - The room to attempt to peek into.\n * @param limit - The number of timeline events to initially retrieve.\n * @returns Promise which resolves: Room object\n * @returns Rejects: with an error response.\n */\n public peekInRoom(roomId: string, limit: number = 20): Promise<Room> {\n this.peekSync?.stopPeeking();\n this.peekSync = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n return this.peekSync.peek(roomId, limit);\n }\n\n /**\n * Stop any ongoing room peeking.\n */\n public stopPeeking(): void {\n if (this.peekSync) {\n this.peekSync.stopPeeking();\n this.peekSync = null;\n }\n }\n\n /**\n * Set r/w flags for guest access in a room.\n * @param roomId - The room to configure guest access in.\n * @param opts - Options\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n */\n public setGuestAccess(roomId: string, opts: IGuestAccessOpts): Promise<void> {\n const writePromise = this.sendStateEvent(\n roomId,\n EventType.RoomGuestAccess,\n {\n guest_access: opts.allowJoin ? GuestAccess.CanJoin : GuestAccess.Forbidden,\n },\n \"\",\n );\n\n let readPromise: Promise<unknown> = Promise.resolve();\n if (opts.allowRead) {\n readPromise = this.sendStateEvent(\n roomId,\n EventType.RoomHistoryVisibility,\n {\n history_visibility: HistoryVisibility.WorldReadable,\n },\n \"\",\n );\n }\n\n return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract\n }\n\n /**\n * Requests an email verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * Parameters and return value are as for requestEmailToken\n\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in which\n * phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international format\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of adding a\n * third party identifier to an account.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n * If an account with the given email address already exists and is\n * associated with an account other than the one the user is authed as,\n * it will either send an email to the address informing them of this\n * or return M_THREEPID_IN_USE (which one is up to the homeserver).\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of adding a\n * third party identifier to an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the addition of phone numbers to an\n * account, as requestAdd3pidEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting. Specifically,\n * if no account with the given email address exists, it may either\n * return M_THREEPID_NOT_FOUND or send an email\n * to the address informing them of this (which one is up to the homeserver).\n *\n * requestEmailToken calls the equivalent API directly on the identity server,\n * therefore bypassing the password reset specific logic.\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting, as requestPasswordEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Internal utility function for requesting validation tokens from usage-specific\n * requestToken endpoints.\n *\n * @param endpoint - The endpoint to send the request to\n * @param params - Parameters for the POST request\n * @returns Promise which resolves: As requestEmailToken\n */\n private async requestTokenFromEndpoint<T extends IRequestTokenResponse>(\n endpoint: string,\n params: QueryDict,\n ): Promise<T> {\n const postParams = Object.assign({}, params);\n\n return this.http.request(Method.Post, endpoint, undefined, postParams);\n }\n\n /**\n * Get the room-kind push rule associated with a room.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @returns the rule or undefined.\n */\n public getRoomPushRule(scope: \"global\" | \"device\", roomId: string): IPushRule | undefined {\n // There can be only room-kind push rule per room\n // and its id is the room id.\n if (this.pushRules) {\n return this.pushRules[scope]?.room?.find((rule) => rule.rule_id === roomId);\n } else {\n throw new Error(\"SyncApi.sync() must be done before accessing to push rules.\");\n }\n }\n\n /**\n * Set a room-kind muting push rule in a room.\n * The operation also updates MatrixClient.pushRules at the end.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @param mute - the mute state.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public setRoomMutePushRule(scope: \"global\" | \"device\", roomId: string, mute: boolean): Promise<void> | undefined {\n let promise: Promise<unknown> | undefined;\n let hasDontNotifyRule = false;\n\n // Get the existing room-kind push rule if any\n const roomPushRule = this.getRoomPushRule(scope, roomId);\n if (roomPushRule?.actions.includes(PushRuleActionName.DontNotify)) {\n hasDontNotifyRule = true;\n }\n\n if (!mute) {\n // Remove the rule only if it is a muting rule\n if (hasDontNotifyRule) {\n promise = this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule!.rule_id);\n }\n } else {\n if (!roomPushRule) {\n promise = this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n });\n } else if (!hasDontNotifyRule) {\n // Remove the existing one before setting the mute push rule\n // This is a workaround to SYN-590 (Push rule update fails)\n const deferred = utils.defer();\n this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id)\n .then(() => {\n this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n })\n .then(() => {\n deferred.resolve();\n })\n .catch((err) => {\n deferred.reject(err);\n });\n })\n .catch((err) => {\n deferred.reject(err);\n });\n\n promise = deferred.promise;\n }\n }\n\n if (promise) {\n return new Promise<void>((resolve, reject) => {\n // Update this.pushRules when the operation completes\n promise!\n .then(() => {\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n resolve();\n })\n .catch((err) => {\n reject(err);\n });\n })\n .catch((err: Error) => {\n // Update it even if the previous operation fails. This can help the\n // app to recover when push settings has been modified from another client\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n reject(err);\n })\n .catch((err2) => {\n reject(err);\n });\n });\n });\n }\n }\n\n public searchMessageText(opts: ISearchOpts): Promise<ISearchResponse> {\n const roomEvents: ISearchRequestBody[\"search_categories\"][\"room_events\"] = {\n search_term: opts.query,\n };\n\n if (\"keys\" in opts) {\n roomEvents.keys = opts.keys;\n }\n\n return this.search({\n body: {\n search_categories: {\n room_events: roomEvents,\n },\n },\n });\n }\n\n /**\n * Perform a server-side search for room events.\n *\n * The returned promise resolves to an object containing the fields:\n *\n * * count: estimate of the number of results\n * * next_batch: token for back-pagination; if undefined, there are no more results\n * * highlights: a list of words to highlight from the stemming algorithm\n * * results: a list of results\n *\n * Each entry in the results list is a SearchResult.\n *\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public searchRoomEvents(opts: IEventSearchOpts): Promise<ISearchResults> {\n // TODO: support search groups\n\n const body = {\n search_categories: {\n room_events: {\n search_term: opts.term,\n filter: opts.filter,\n order_by: SearchOrderBy.Recent,\n event_context: {\n before_limit: 1,\n after_limit: 1,\n include_profile: true,\n },\n },\n },\n };\n\n const searchResults: ISearchResults = {\n _query: body,\n results: [],\n highlights: [],\n };\n\n return this.search({ body: body }).then((res) => this.processRoomEventsSearch(searchResults, res));\n }\n\n /**\n * Take a result from an earlier searchRoomEvents call, and backfill results.\n *\n * @param searchResults - the results object to be updated\n * @returns Promise which resolves: updated result object\n * @returns Rejects: with an error response.\n */\n public backPaginateRoomEventsSearch<T extends ISearchResults>(searchResults: T): Promise<T> {\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n\n if (!searchResults.next_batch) {\n return Promise.reject(new Error(\"Cannot backpaginate event search any further\"));\n }\n\n if (searchResults.pendingRequest) {\n // already a request in progress - return the existing promise\n return searchResults.pendingRequest as Promise<T>;\n }\n\n const searchOpts = {\n body: searchResults._query!,\n next_batch: searchResults.next_batch,\n };\n\n const promise = this.search(searchOpts, searchResults.abortSignal)\n .then((res) => this.processRoomEventsSearch(searchResults, res))\n .finally(() => {\n searchResults.pendingRequest = undefined;\n });\n searchResults.pendingRequest = promise;\n\n return promise;\n }\n\n /**\n * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the\n * response from the API call and updates the searchResults\n *\n * @returns searchResults\n * @internal\n */\n // XXX: Intended private, used in code\n public processRoomEventsSearch<T extends ISearchResults>(searchResults: T, response: ISearchResponse): T {\n const roomEvents = response.search_categories.room_events;\n\n searchResults.count = roomEvents.count;\n searchResults.next_batch = roomEvents.next_batch;\n\n // combine the highlight list with our existing list;\n const highlights = new Set<string>(roomEvents.highlights);\n searchResults.highlights.forEach((hl) => {\n highlights.add(hl);\n });\n\n // turn it back into a list.\n searchResults.highlights = Array.from(highlights);\n\n const mapper = this.getEventMapper();\n\n // append the new results to our existing results\n const resultsLength = roomEvents.results?.length ?? 0;\n for (let i = 0; i < resultsLength; i++) {\n const sr = SearchResult.fromJson(roomEvents.results![i], mapper);\n const room = this.getRoom(sr.context.getEvent().getRoomId());\n if (room) {\n // Copy over a known event sender if we can\n for (const ev of sr.context.getTimeline()) {\n const sender = room.getMember(ev.getSender()!);\n if (!ev.sender && sender) ev.sender = sender;\n }\n }\n searchResults.results.push(sr);\n }\n return searchResults;\n }\n\n /**\n * Populate the store with rooms the user has left.\n * @returns Promise which resolves: TODO - Resolved when the rooms have\n * been added to the data store.\n * @returns Rejects: with an error response.\n */\n public syncLeftRooms(): Promise<Room[]> {\n // Guard against multiple calls whilst ongoing and multiple calls post success\n if (this.syncedLeftRooms) {\n return Promise.resolve([]); // don't call syncRooms again if it succeeded.\n }\n if (this.syncLeftRoomsPromise) {\n return this.syncLeftRoomsPromise; // return the ongoing request\n }\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n this.syncLeftRoomsPromise = syncApi.syncLeftRooms();\n\n // cleanup locks\n this.syncLeftRoomsPromise\n .then(() => {\n this.logger.debug(\"Marking success of sync left room request\");\n this.syncedLeftRooms = true; // flip the bit on success\n })\n .finally(() => {\n this.syncLeftRoomsPromise = undefined; // cleanup ongoing request state\n });\n\n return this.syncLeftRoomsPromise;\n }\n\n /**\n * Create a new filter.\n * @param content - The HTTP body for the request\n * @returns Promise which resolves to a Filter object.\n * @returns Rejects: with an error response.\n */\n public createFilter(content: IFilterDefinition): Promise<Filter> {\n const path = utils.encodeUri(\"/user/$userId/filter\", {\n $userId: this.credentials.userId!,\n });\n return this.http.authedRequest<IFilterResponse>(Method.Post, path, undefined, content).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(this.credentials.userId, response.filter_id, content);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * Retrieve a filter.\n * @param userId - The user ID of the filter owner\n * @param filterId - The filter ID to retrieve\n * @param allowCached - True to allow cached filters to be returned.\n * Default: True.\n * @returns Promise which resolves: a Filter object\n * @returns Rejects: with an error response.\n */\n public getFilter(userId: string, filterId: string, allowCached: boolean): Promise<Filter> {\n if (allowCached) {\n const filter = this.store.getFilter(userId, filterId);\n if (filter) {\n return Promise.resolve(filter);\n }\n }\n\n const path = utils.encodeUri(\"/user/$userId/filter/$filterId\", {\n $userId: userId,\n $filterId: filterId,\n });\n\n return this.http.authedRequest<IFilterDefinition>(Method.Get, path).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(userId, filterId, response);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * @returns Filter ID\n */\n public async getOrCreateFilter(filterName: string, filter: Filter): Promise<string> {\n const filterId = this.store.getFilterIdByName(filterName);\n let existingId: string | undefined;\n\n if (filterId) {\n // check that the existing filter matches our expectations\n try {\n const existingFilter = await this.getFilter(this.credentials.userId!, filterId, true);\n if (existingFilter) {\n const oldDef = existingFilter.getDefinition();\n const newDef = filter.getDefinition();\n\n if (utils.deepCompare(oldDef, newDef)) {\n // super, just use that.\n // debuglog(\"Using existing filter ID %s: %s\", filterId,\n // JSON.stringify(oldDef));\n existingId = filterId;\n }\n }\n } catch (error) {\n // Synapse currently returns the following when the filter cannot be found:\n // {\n // errcode: \"M_UNKNOWN\",\n // name: \"M_UNKNOWN\",\n // message: \"No row found\",\n // }\n if ((<MatrixError>error).errcode !== \"M_UNKNOWN\" && (<MatrixError>error).errcode !== \"M_NOT_FOUND\") {\n throw error;\n }\n }\n // if the filter doesn't exist anymore on the server, remove from store\n if (!existingId) {\n this.store.setFilterIdByName(filterName, undefined);\n }\n }\n\n if (existingId) {\n return existingId;\n }\n\n // create a new filter\n const createdFilter = await this.createFilter(filter.getDefinition());\n\n this.store.setFilterIdByName(filterName, createdFilter.filterId);\n return createdFilter.filterId!;\n }\n\n /**\n * Gets a bearer token from the homeserver that the user can\n * present to a third party in order to prove their ownership\n * of the Matrix account they are logged into.\n * @returns Promise which resolves: Token object\n * @returns Rejects: with an error response.\n */\n public getOpenIdToken(): Promise<IOpenIDToken> {\n const path = utils.encodeUri(\"/user/$userId/openid/request_token\", {\n $userId: this.credentials.userId!,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, {});\n }\n\n /**\n * Once the client has been initialised, we want to clear notifications we\n * know for a fact should be here.\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * We consider a room or a thread as fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n */\n private fixupRoomNotifications = (): void => {\n if (this.isInitialSyncComplete()) {\n const unreadRooms = (this.getRooms() ?? []).filter((room) => {\n return room.getUnreadNotificationCount(NotificationCountType.Total) > 0;\n });\n\n for (const room of unreadRooms) {\n const currentUserId = this.getSafeUserId();\n room.fixupNotifications(currentUserId);\n }\n\n this.off(ClientEvent.Sync, this.fixupRoomNotifications);\n }\n };\n\n /**\n * Set whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n */\n public setFallbackICEServerAllowed(allow: boolean): void {\n this.fallbackICEServerAllowed = allow;\n }\n\n /**\n * Get whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n * @returns\n */\n public isFallbackICEServerAllowed(): boolean {\n return this.fallbackICEServerAllowed;\n }\n\n /**\n * Determines if the current user is an administrator of the Synapse homeserver.\n * Returns false if untrue or the homeserver does not appear to be a Synapse\n * homeserver. <strong>This function is implementation specific and may change\n * as a result.</strong>\n * @returns true if the user appears to be a Synapse administrator.\n */\n public isSynapseAdministrator(): Promise<boolean> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/users/$userId/admin\", { $userId: this.getUserId()! });\n return this.http\n .authedRequest<{ admin: boolean }>(Method.Get, path, undefined, undefined, { prefix: \"\" })\n .then((r) => r.admin); // pull out the specific boolean we want\n }\n\n /**\n * Performs a whois lookup on a user using Synapse's administrator API.\n * <strong>This function is implementation specific and may change as a\n * result.</strong>\n * @param userId - the User ID to look up.\n * @returns the whois response - see Synapse docs for information.\n */\n public whoisSynapseUser(userId: string): Promise<ISynapseAdminWhoisResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/whois/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix: \"\" });\n }\n\n /**\n * Deactivates a user using Synapse's administrator API. <strong>This\n * function is implementation specific and may change as a result.</strong>\n * @param userId - the User ID to deactivate.\n * @returns the deactivate response - see Synapse docs for information.\n */\n public deactivateSynapseUser(userId: string): Promise<ISynapseAdminDeactivateResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/deactivate/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Post, path, undefined, undefined, { prefix: \"\" });\n }\n\n protected async fetchClientWellKnown(): Promise<void> {\n // `getRawClientConfig` does not throw or reject on network errors, instead\n // it absorbs errors and returns `{}`.\n this.clientWellKnownPromise = AutoDiscovery.getRawClientConfig(this.getDomain() ?? undefined);\n this.clientWellKnown = await this.clientWellKnownPromise;\n this.emit(ClientEvent.ClientWellKnown, this.clientWellKnown);\n }\n\n public getClientWellKnown(): IClientWellKnown | undefined {\n return this.clientWellKnown;\n }\n\n public waitForClientWellKnown(): Promise<IClientWellKnown> {\n if (!this.clientRunning) {\n throw new Error(\"Client is not running\");\n }\n return this.clientWellKnownPromise!;\n }\n\n /**\n * store client options with boolean/string/numeric values\n * to know in the next session what flags the sync data was\n * created with (e.g. lazy loading)\n * @returns for store operation\n */\n public storeClientOptions(): Promise<void> {\n // XXX: Intended private, used in code\n const primTypes = [\"boolean\", \"string\", \"number\"];\n const serializableOpts = Object.entries(this.clientOpts!)\n .filter(([key, value]) => {\n return primTypes.includes(typeof value);\n })\n .reduce<Record<string, any>>((obj, [key, value]) => {\n obj[key] = value;\n return obj;\n }, {});\n return this.store.storeClientOptions(serializableOpts);\n }\n\n /**\n * Gets a set of room IDs in common with another user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) for more details.\n *\n * @param userId - The userId to check.\n * @returns Promise which resolves to an array of rooms\n * @returns Rejects: with an error response.\n */\n // TODO: on spec release, rename this to getMutualRooms\n // eslint-disable-next-line\n public async _unstable_getSharedRooms(userId: string): Promise<string[]> {\n // Initial variant of the MSC\n const sharedRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_SHARED_ROOMS);\n\n // Newer variant that renamed shared rooms to mutual rooms\n const mutualRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_MUTUAL_ROOMS);\n\n // Latest variant that changed from path elements to query elements\n const queryMutualRoomsSupport = await this.doesServerSupportUnstableFeature(\n UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS,\n );\n\n if (!sharedRoomsSupport && !mutualRoomsSupport && !queryMutualRoomsSupport) {\n throw Error(\"Server does not support the Mutual Rooms API\");\n }\n\n let path;\n let query;\n\n // Cascading unstable support switching.\n if (queryMutualRoomsSupport) {\n path = \"/uk.half-shot.msc2666/user/mutual_rooms\";\n query = { user_id: userId };\n } else {\n path = utils.encodeUri(\n `/uk.half-shot.msc2666/user/${mutualRoomsSupport ? \"mutual_rooms\" : \"shared_rooms\"}/$userId`,\n { $userId: userId },\n );\n query = {};\n }\n\n // Accumulated rooms\n const rooms: string[] = [];\n let token = null;\n\n do {\n const tokenQuery: Record<string, string> = {};\n if (token != null && queryMutualRoomsSupport) {\n tokenQuery[\"batch_token\"] = token;\n }\n\n const res = await this.http.authedRequest<{\n joined: string[];\n next_batch_token?: string;\n }>(Method.Get, path, { ...query, ...tokenQuery }, undefined, {\n prefix: ClientPrefix.Unstable,\n });\n\n rooms.push(...res.joined);\n\n if (res.next_batch_token !== undefined) {\n token = res.next_batch_token;\n } else {\n token = null;\n }\n } while (token != null);\n\n return rooms;\n }\n\n /**\n * Get the API versions supported by the server, along with any\n * unstable APIs it supports\n * @returns The server /versions response\n */\n public async getVersions(): Promise<IServerVersions> {\n if (this.serverVersionsPromise) {\n return this.serverVersionsPromise;\n }\n\n // We send an authenticated request as of MSC4026\n this.serverVersionsPromise = this.http\n .authedRequest<IServerVersions>(Method.Get, \"/_matrix/client/versions\", undefined, undefined, {\n prefix: \"\",\n })\n .catch((e) => {\n // Need to unset this if it fails, otherwise we'll never retry\n this.serverVersionsPromise = undefined;\n // but rethrow the exception to anything that was waiting\n throw e;\n });\n\n const serverVersions = await this.serverVersionsPromise;\n this.canSupport = await buildFeatureSupportMap(serverVersions);\n\n return this.serverVersionsPromise;\n }\n\n /**\n * Check if a particular spec version is supported by the server.\n * @param version - The spec version (such as \"r0.5.0\") to check for.\n * @returns Whether it is supported\n */\n public async isVersionSupported(version: string): Promise<boolean> {\n const { versions } = await this.getVersions();\n return versions && versions.includes(version);\n }\n\n /**\n * Query the server to see if it lists support for an unstable feature\n * in the /versions response\n * @param feature - the feature name\n * @returns true if the feature is supported\n */\n public async doesServerSupportUnstableFeature(feature: string): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n return unstableFeatures && !!unstableFeatures[feature];\n }\n\n /**\n * Query the server to see if it is forcing encryption to be enabled for\n * a given room preset, based on the /versions response.\n * @param presetName - The name of the preset to check.\n * @returns true if the server is forcing encryption\n * for the preset.\n */\n public async doesServerForceEncryptionForPreset(presetName: Preset): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n\n // The preset name in the versions response will be without the _chat suffix.\n const versionsPresetName = presetName.includes(\"_chat\")\n ? presetName.substring(0, presetName.indexOf(\"_chat\"))\n : presetName;\n\n return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`];\n }\n\n public async doesServerSupportThread(): Promise<{\n threads: FeatureSupport;\n list: FeatureSupport;\n fwdPagination: FeatureSupport;\n }> {\n if (await this.isVersionSupported(\"v1.4\")) {\n return {\n threads: FeatureSupport.Stable,\n list: FeatureSupport.Stable,\n fwdPagination: FeatureSupport.Stable,\n };\n }\n\n try {\n const [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] =\n await Promise.all([\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715.stable\"),\n ]);\n\n return {\n threads: determineFeatureSupport(threadStable, threadUnstable),\n list: determineFeatureSupport(listStable, listUnstable),\n fwdPagination: determineFeatureSupport(fwdPaginationStable, fwdPaginationUnstable),\n };\n } catch {\n return {\n threads: FeatureSupport.None,\n list: FeatureSupport.None,\n fwdPagination: FeatureSupport.None,\n };\n }\n }\n\n /**\n * Get if lazy loading members is being used.\n * @returns Whether or not members are lazy loaded by this client\n */\n public hasLazyLoadMembersEnabled(): boolean {\n return !!this.clientOpts?.lazyLoadMembers;\n }\n\n /**\n * Set a function which is called when /sync returns a 'limited' response.\n * It is called with a room ID and returns a boolean. It should return 'true' if the SDK\n * can SAFELY remove events from this room. It may not be safe to remove events if there\n * are other references to the timelines for this room, e.g because the client is\n * actively viewing events in this room.\n * Default: returns false.\n * @param cb - The callback which will be invoked.\n */\n public setCanResetTimelineCallback(cb: ResetTimelineCallback): void {\n this.canResetTimelineCallback = cb;\n }\n\n /**\n * Get the callback set via `setCanResetTimelineCallback`.\n * @returns The callback or null\n */\n public getCanResetTimelineCallback(): ResetTimelineCallback | undefined {\n return this.canResetTimelineCallback;\n }\n\n /**\n * Returns relations for a given event. Handles encryption transparently,\n * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.\n * When the returned promise resolves, all messages should have finished trying to decrypt.\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.\n */\n public async relations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<{\n originalEvent?: MatrixEvent | null;\n events: MatrixEvent[];\n nextBatch?: string | null;\n prevBatch?: string | null;\n }> {\n const fetchedEventType = eventType ? this.getEncryptedIfNeededEventType(roomId, eventType) : null;\n const [eventResult, result] = await Promise.all([\n this.fetchRoomEvent(roomId, eventId),\n this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts),\n ]);\n const mapper = this.getEventMapper();\n\n const originalEvent = eventResult ? mapper(eventResult) : undefined;\n let events = result.chunk.map(mapper);\n\n if (fetchedEventType === EventType.RoomMessageEncrypted) {\n if (eventType !== null) {\n events = events.filter((e) => e.getType() === eventType);\n }\n }\n\n if (originalEvent && relationType === RelationType.Replace) {\n events = events.filter((e) => e.getSender() === originalEvent.getSender());\n }\n return {\n originalEvent: originalEvent ?? null,\n events,\n nextBatch: result.next_batch ?? null,\n prevBatch: result.prev_batch ?? null,\n };\n }\n\n /**\n * Generates a random string suitable for use as a client secret. <strong>This\n * method is experimental and may change.</strong>\n * @returns A new client secret\n */\n public generateClientSecret(): string {\n return randomString(32);\n }\n\n /**\n * Attempts to decrypt an event\n * @param event - The event to decrypt\n * @returns A decryption promise\n */\n public decryptEventIfNeeded(event: MatrixEvent, options?: IDecryptOptions): Promise<void> {\n return Promise.resolve();\n }\n\n private termsUrlForService(serviceType: SERVICE_TYPES, baseUrl: string): URL {\n switch (serviceType) {\n case SERVICE_TYPES.IS:\n return this.http.getUrl(\"/terms\", undefined, IdentityPrefix.V2, baseUrl);\n case SERVICE_TYPES.IM:\n return this.http.getUrl(\"/terms\", undefined, \"/_matrix/integrations/v1\", baseUrl);\n default:\n throw new Error(\"Unsupported service type\");\n }\n }\n\n /**\n * Get the Homeserver URL of this client\n * @returns Homeserver URL of this client\n */\n public getHomeserverUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get the identity server URL of this client\n * @param stripProto - whether or not to strip the protocol from the URL\n * @returns Identity server URL of this client\n */\n public getIdentityServerUrl(stripProto = false): string | undefined {\n if (stripProto && (this.idBaseUrl?.startsWith(\"http://\") || this.idBaseUrl?.startsWith(\"https://\"))) {\n return this.idBaseUrl.split(\"://\")[1];\n }\n return this.idBaseUrl;\n }\n\n /**\n * Set the identity server URL of this client\n * @param url - New identity server URL\n */\n public setIdentityServerUrl(url?: string): void {\n this.idBaseUrl = utils.ensureNoTrailingSlash(url);\n this.http.setIdBaseUrl(this.idBaseUrl);\n }\n\n /**\n * Get the access token associated with this account.\n * @returns The access_token or null\n */\n public getAccessToken(): string | null {\n return this.http.opts.accessToken || null;\n }\n\n /**\n * Get the refresh token associated with this account.\n * @returns The refresh_token or null\n */\n public getRefreshToken(): string | null {\n return this.http.opts.refreshToken ?? null;\n }\n\n /**\n * Set the access token associated with this account.\n * @param token - The new access token.\n */\n public setAccessToken(token: string): void {\n this.http.opts.accessToken = token;\n // The /versions response can vary for different users so clear the cache\n this.serverVersionsPromise = undefined;\n }\n\n /**\n * @returns true if there is a valid access_token for this client.\n */\n public isLoggedIn(): boolean {\n return this.http.opts.accessToken !== undefined;\n }\n\n /**\n * Make up a new transaction id\n *\n * @returns a new, unique, transaction id\n */\n public makeTxnId(): string {\n return \"m\" + new Date().getTime() + \".\" + this.txnCtr++;\n }\n\n /**\n * Check whether a username is available prior to registration. An error response\n * indicates an invalid/unavailable username.\n * @param username - The username to check the availability of.\n * @returns Promise which resolves: to boolean of whether the username is available.\n */\n public isUsernameAvailable(username: string): Promise<boolean> {\n return this.http\n .authedRequest<{ available: true }>(Method.Get, \"/register/available\", { username })\n .then((response) => {\n return response.available;\n })\n .catch((response) => {\n if (response.errcode === \"M_USER_IN_USE\") {\n return false;\n }\n return Promise.reject(response);\n });\n }\n\n /**\n * @param bindThreepids - Set key 'email' to true to bind any email\n * threepid uses during registration in the identity server. Set 'msisdn' to\n * true to bind msisdn.\n * @returns Promise which resolves to a RegisterResponse object\n * @returns Rejects: with an error response.\n */\n public register(\n username: string,\n password: string,\n sessionId: string | null,\n auth: { session?: string; type: string },\n bindThreepids?: { email?: boolean; msisdn?: boolean },\n guestAccessToken?: string,\n inhibitLogin?: boolean,\n ): Promise<RegisterResponse> {\n if (sessionId) {\n auth.session = sessionId;\n }\n\n const params: RegisterRequest = {\n auth: auth,\n refresh_token: true, // always ask for a refresh token - does nothing if unsupported\n };\n if (username !== undefined && username !== null) {\n params.username = username;\n }\n if (password !== undefined && password !== null) {\n params.password = password;\n }\n if (guestAccessToken !== undefined && guestAccessToken !== null) {\n params.guest_access_token = guestAccessToken;\n }\n if (inhibitLogin !== undefined && inhibitLogin !== null) {\n params.inhibit_login = inhibitLogin;\n }\n\n return this.registerRequest(params);\n }\n\n /**\n * Register a guest account.\n * This method returns the auth info needed to create a new authenticated client,\n * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:\n * ```javascript\n * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);\n * const { user_id, device_id, access_token } = tmpClient.registerGuest();\n * const client = createClient({\n * baseUrl: MATRIX_INSTANCE,\n * accessToken: access_token,\n * userId: user_id,\n * deviceId: device_id,\n * })\n * client.setGuest(true);\n * ```\n *\n * @param body - JSON HTTP body to provide.\n * @returns Promise which resolves: JSON object that contains:\n * `{ user_id, device_id, access_token, home_server }`\n * @returns Rejects: with an error response.\n */\n public registerGuest({ body }: { body?: RegisterRequest } = {}): Promise<RegisterResponse> {\n return this.registerRequest(body || {}, \"guest\");\n }\n\n /**\n * @param data - parameters for registration request\n * @param kind - type of user to register. may be \"guest\"\n * @returns Promise which resolves: to the /register response\n * @returns Rejects: with an error response.\n */\n public registerRequest(data: RegisterRequest, kind?: string): Promise<RegisterResponse> {\n const params: { kind?: string } = {};\n if (kind) {\n params.kind = kind;\n }\n\n return this.http.request(Method.Post, \"/register\", params, data);\n }\n\n /**\n * Refreshes an access token using a provided refresh token. The refresh token\n * must be valid for the current access token known to the client instance.\n *\n * Note that this function will not cause a logout if the token is deemed\n * unknown by the server - the caller is responsible for managing logout\n * actions on error.\n * @param refreshToken - The refresh token.\n * @returns Promise which resolves to the new token.\n * @returns Rejects with an error response.\n */\n public refreshToken(refreshToken: string): Promise<IRefreshTokenResponse> {\n const performRefreshRequestWithPrefix = (prefix: ClientPrefix): Promise<IRefreshTokenResponse> =>\n this.http.authedRequest(\n Method.Post,\n \"/refresh\",\n undefined,\n { refresh_token: refreshToken },\n {\n prefix,\n inhibitLogoutEmit: true, // we don't want to cause logout loops\n },\n );\n\n // First try with the (specced) /v3/ prefix.\n // However, before Synapse 1.72.0, Synapse incorrectly required a /v1/ prefix, so we fall\n // back to that if the request fails, for backwards compatibility.\n return performRefreshRequestWithPrefix(ClientPrefix.V3).catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n return performRefreshRequestWithPrefix(ClientPrefix.V1);\n }\n throw e;\n });\n }\n\n /**\n * @returns Promise which resolves to the available login flows\n * @returns Rejects: with an error response.\n */\n public loginFlows(): Promise<ILoginFlowsResponse> {\n return this.http.request(Method.Get, \"/login\");\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public login(loginType: LoginRequest[\"type\"], data: Omit<LoginRequest, \"type\">): Promise<LoginResponse> {\n return this.http\n .authedRequest<LoginResponse>(Method.Post, \"/login\", undefined, {\n ...data,\n type: loginType,\n })\n .then((response) => {\n if (response.access_token && response.user_id) {\n this.http.opts.accessToken = response.access_token;\n this.credentials = {\n userId: response.user_id,\n };\n }\n return response;\n });\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithPassword(user: string, password: string): Promise<LoginResponse> {\n return this.login(\"m.login.password\", {\n user: user,\n password: password,\n });\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with CAS.\n * @returns The HS URL to hit to begin the CAS login process.\n */\n public getCasLoginUrl(redirectUrl: string): string {\n return this.getSsoLoginUrl(redirectUrl, \"cas\");\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with the SSO.\n * @param loginType - The type of SSO login we are doing (sso or cas).\n * Defaults to 'sso'.\n * @param idpId - The ID of the Identity Provider being targeted, optional.\n * @param action - the SSO flow to indicate to the IdP, optional.\n * @returns The HS URL to hit to begin the SSO login process.\n */\n public getSsoLoginUrl(redirectUrl: string, loginType = \"sso\", idpId?: string, action?: SSOAction): string {\n let url = \"/login/\" + loginType + \"/redirect\";\n if (idpId) {\n url += \"/\" + idpId;\n }\n\n const params = {\n redirectUrl,\n [SSO_ACTION_PARAM.unstable!]: action,\n };\n\n return this.http.getUrl(url, params).href;\n }\n\n /**\n * @param token - Login token previously received from homeserver\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithToken(token: string): Promise<LoginResponse> {\n return this.login(\"m.login.token\", {\n token: token,\n });\n }\n\n /**\n * Logs out the current session.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param stopClient - whether to stop the client before calling /logout to prevent invalid token errors.\n * @returns Promise which resolves: On success, the empty object `{}`\n */\n public async logout(stopClient = false): Promise<{}> {\n if (stopClient) {\n this.stopClient();\n this.http.abort();\n }\n\n return this.http.authedRequest(Method.Post, \"/logout\");\n }\n\n /**\n * Deactivates the logged-in account.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @param erase - Optional. If set, send as `erase` attribute in the\n * JSON request body, indicating whether the account should be erased. Defaults\n * to false.\n * @returns Promise which resolves: On success, the empty object\n */\n public deactivateAccount(\n auth?: AuthDict,\n erase?: boolean,\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const body: Body = {};\n if (auth) {\n body.auth = auth;\n }\n if (erase !== undefined) {\n body.erase = erase;\n }\n\n return this.http.authedRequest(Method.Post, \"/account/deactivate\", undefined, body);\n }\n\n /**\n * Make a request for an `m.login.token` to be issued as per\n * https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv1loginget_token\n *\n * The server may require User-Interactive auth.\n *\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: On success, the token response\n * or UIA auth data.\n */\n public async requestLoginToken(auth?: AuthDict): Promise<UIAResponse<LoginTokenPostResponse>> {\n const body: UIARequest<{}> = { auth };\n return this.http.authedRequest<UIAResponse<LoginTokenPostResponse>>(\n Method.Post,\n \"/login/get_token\",\n undefined, // no query params\n body,\n { prefix: ClientPrefix.V1 },\n );\n }\n\n /**\n * Get the fallback URL to use for unknown interactive-auth stages.\n *\n * @param loginType - the type of stage being attempted\n * @param authSessionId - the auth session ID provided by the homeserver\n *\n * @returns HS URL to hit to for the fallback interface\n */\n public getFallbackAuthUrl(loginType: string, authSessionId: string): string {\n const path = utils.encodeUri(\"/auth/$loginType/fallback/web\", {\n $loginType: loginType,\n });\n\n return this.http.getUrl(path, {\n session: authSessionId,\n }).href;\n }\n\n /**\n * Create a new room.\n * @param options - a list of options to pass to the /createRoom API.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public async createRoom(options: ICreateRoomOpts): Promise<{ room_id: string }> {\n // eslint-disable-line camelcase\n // some valid options include: room_alias_name, visibility, invite\n\n // inject the id_access_token if inviting 3rd party addresses\n const invitesNeedingToken = (options.invite_3pid || []).filter((i) => !i.id_access_token);\n if (invitesNeedingToken.length > 0 && this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n for (const invite of invitesNeedingToken) {\n invite.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.authedRequest(Method.Post, \"/createRoom\", undefined, options);\n }\n\n /**\n * Fetches relations for a given event\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns the response, with chunk, prev_batch and, next_batch.\n */\n public fetchRelations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<IRelationsResponse> {\n let params = opts as QueryDict;\n if (Thread.hasServerSideFwdPaginationSupport === FeatureSupport.Experimental) {\n params = replaceParam(\"dir\", \"org.matrix.msc3715.dir\", params);\n }\n if (this.canSupport.get(Feature.RelationsRecursion) === ServerSupport.Unstable) {\n params = replaceParam(\"recurse\", \"org.matrix.msc3981.recurse\", params);\n }\n const queryString = utils.encodeParams(params);\n\n let templatedUrl = \"/rooms/$roomId/relations/$eventId\";\n if (relationType !== null) {\n templatedUrl += \"/$relationType\";\n if (eventType !== null) {\n templatedUrl += \"/$eventType\";\n }\n } else if (eventType !== null) {\n this.logger.warn(`eventType: ${eventType} ignored when fetching\n relations as relationType is null`);\n eventType = null;\n }\n\n const path = utils.encodeUri(templatedUrl + \"?\" + queryString, {\n $roomId: roomId,\n $eventId: eventId,\n $relationType: relationType!,\n $eventType: eventType!,\n });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n prefix: ClientPrefix.V1,\n });\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomState(roomId: string): Promise<IStateEventWithRoomId[]> {\n const path = utils.encodeUri(\"/rooms/$roomId/state\", { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get an event in a room by its event id.\n *\n * @returns Promise which resolves to an object containing the event.\n * @returns Rejects: with an error response.\n */\n public fetchRoomEvent(roomId: string, eventId: string): Promise<Partial<IEvent>> {\n const path = utils.encodeUri(\"/rooms/$roomId/event/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param includeMembership - the membership type to include in the response\n * @param excludeMembership - the membership type to exclude from the response\n * @param atEventId - the id of the event for which moment in the timeline the members should be returned for\n * @returns Promise which resolves: dictionary of userid to profile information\n * @returns Rejects: with an error response.\n */\n public members(\n roomId: string,\n includeMembership?: string,\n excludeMembership?: string,\n atEventId?: string,\n ): Promise<{ [userId: string]: IStateEventWithRoomId[] }> {\n const queryParams: Record<string, string> = {};\n if (includeMembership) {\n queryParams.membership = includeMembership;\n }\n if (excludeMembership) {\n queryParams.not_membership = excludeMembership;\n }\n if (atEventId) {\n queryParams.at = atEventId;\n }\n\n const queryString = utils.encodeParams(queryParams);\n\n const path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString, { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Upgrades a room to a new protocol version\n * @param newVersion - The target version to upgrade to\n * @returns Promise which resolves: Object with key 'replacement_room'\n * @returns Rejects: with an error response.\n */\n public upgradeRoom(roomId: string, newVersion: string): Promise<{ replacement_room: string }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/rooms/$roomId/upgrade\", { $roomId: roomId });\n return this.http.authedRequest(Method.Post, path, undefined, { new_version: newVersion });\n }\n\n /**\n * Retrieve a state event.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getStateEvent(roomId: string, eventType: string, stateKey: string): Promise<Record<string, any>> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Send a state event into a room\n * @param roomId - ID of the room to send the event into\n * @param eventType - type of the state event to send\n * @param content - content of the event to send\n * @param stateKey - the stateKey to send into the room\n * @param opts - Options for the request function.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public sendStateEvent<K extends keyof StateEvents>(\n roomId: string,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<ISendEventResponse> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, undefined, content as Body, opts);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomInitialSync(roomId: string, limit: number): Promise<IRoomInitialSyncResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/initialSync\", { $roomId: roomId });\n\n return this.http.authedRequest(Method.Get, path, { limit: limit?.toString() ?? \"30\" });\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEventId - ID of the event tracked by the read receipt. This is here\n * for convenience because the RR and the RM are commonly updated at the same time as\n * each other. Optional.\n * @param rpEventId - rpEvent the m.read.private read receipt event for when we\n * don't want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkersHttpRequest(\n roomId: string,\n rmEventId: string,\n rrEventId?: string,\n rpEventId?: string,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/read_markers\", {\n $roomId: roomId,\n });\n\n const content: IContent = {\n [ReceiptType.FullyRead]: rmEventId,\n [ReceiptType.Read]: rrEventId,\n };\n\n if (\n (await this.doesServerSupportUnstableFeature(\"org.matrix.msc2285.stable\")) ||\n (await this.isVersionSupported(\"v1.4\"))\n ) {\n content[ReceiptType.ReadPrivate] = rpEventId;\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * @returns Promise which resolves: A list of the user's current rooms\n * @returns Rejects: with an error response.\n */\n public getJoinedRooms(): Promise<IJoinedRoomsResponse> {\n const path = utils.encodeUri(\"/joined_rooms\", {});\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve membership info. for a room.\n * @param roomId - ID of the room to get membership for\n * @returns Promise which resolves: A list of currently joined users\n * and their profile data.\n * @returns Rejects: with an error response.\n */\n public getJoinedRoomMembers(roomId: string): Promise<IJoinedMembersResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/joined_members\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param params - Options for this request\n * @returns Promise which resolves: IPublicRoomsResponse\n * @returns Rejects: with an error response.\n */\n public publicRooms({\n server,\n limit,\n since,\n ...options\n }: IRoomDirectoryOptions = {}): Promise<IPublicRoomsResponse> {\n if (Object.keys(options).length === 0) {\n const queryParams: QueryDict = { server, limit, since };\n return this.http.authedRequest(Method.Get, \"/publicRooms\", queryParams);\n } else {\n const queryParams: QueryDict = { server };\n const body = {\n limit,\n since,\n ...options,\n };\n return this.http.authedRequest(Method.Post, \"/publicRooms\", queryParams, body);\n }\n }\n\n /**\n * Create an alias to room ID mapping.\n * @param alias - The room alias to create.\n * @param roomId - The room ID to link the alias to.\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public createAlias(alias: string, roomId: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n const data = {\n room_id: roomId,\n };\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Delete an alias to room ID mapping. This alias must be on your local server,\n * and you must have sufficient access to do this operation.\n * @param alias - The room alias to delete.\n * @returns Promise which resolves: an empty object `{}`.\n * @returns Rejects: with an error response.\n */\n public deleteAlias(alias: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Gets the local aliases for the room. Note: this includes all local aliases, unlike the\n * curated list from the m.room.canonical_alias state event.\n * @param roomId - The room ID to get local aliases for.\n * @returns Promise which resolves: an object with an `aliases` property, containing an array of local aliases\n * @returns Rejects: with an error response.\n */\n public getLocalAliases(roomId: string): Promise<{ aliases: string[] }> {\n const path = utils.encodeUri(\"/rooms/$roomId/aliases\", { $roomId: roomId });\n const prefix = ClientPrefix.V3;\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix });\n }\n\n /**\n * Get room info for the given alias.\n * @param alias - The room alias to resolve.\n * @returns Promise which resolves: Object with room_id and servers.\n * @returns Rejects: with an error response.\n */\n public getRoomIdForAlias(alias: string): Promise<{ room_id: string; servers: string[] }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get the visibility of a room in the current HS's room directory\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getRoomDirectoryVisibility(roomId: string): Promise<{ visibility: Visibility }> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Set the visibility of a room in the current HS's room directory\n * @param visibility - \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomDirectoryVisibility(roomId: string, visibility: Visibility): Promise<{}> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { visibility });\n }\n\n /**\n * Query the user directory with a term matching user IDs, display names and domains.\n * @param options\n * @param options.term - the term with which to search.\n * @param options.limit - the maximum number of results to return. The server will apply a limit if unspecified.\n * @returns Promise which resolves: an array of results.\n */\n public searchUserDirectory({ term, limit }: { term: string; limit?: number }): Promise<IUserDirectoryResponse> {\n const body: Body = {\n search_term: term,\n };\n\n if (limit !== undefined) {\n body.limit = limit;\n }\n\n return this.http.authedRequest(Method.Post, \"/user_directory/search\", undefined, body);\n }\n\n /**\n * Upload a file to the media repository on the homeserver.\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n public uploadContent(file: FileType, opts?: UploadOpts): Promise<UploadResponse> {\n return this.http.uploadContent(file, opts);\n }\n\n /**\n * Cancel a file upload in progress\n * @param upload - The object returned from uploadContent\n * @returns true if canceled, otherwise false\n */\n public cancelUpload(upload: Promise<UploadResponse>): boolean {\n return this.http.cancelUpload(upload);\n }\n\n /**\n * Get a list of all file uploads in progress\n * @returns Array of objects representing current uploads.\n * Currently in progress is element 0. Keys:\n * - promise: The promise associated with the upload\n * - loaded: Number of bytes uploaded\n * - total: Total number of bytes to upload\n */\n public getCurrentUploads(): Upload[] {\n return this.http.getCurrentUploads();\n }\n\n /**\n * @param info - The kind of info to retrieve (e.g. 'displayname',\n * 'avatar_url').\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getProfileInfo(\n userId: string,\n info?: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ avatar_url?: string; displayname?: string }> {\n const path = info\n ? utils.encodeUri(\"/profile/$userId/$info\", { $userId: userId, $info: info })\n : utils.encodeUri(\"/profile/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Determine if the server supports extended profiles, as described by MSC4133.\n *\n * @returns `true` if supported, otherwise `false`\n */\n public async doesServerSupportExtendedProfiles(): Promise<boolean> {\n return this.doesServerSupportUnstableFeature(UNSTABLE_MSC4133_EXTENDED_PROFILES);\n }\n\n /**\n * Get the prefix used for extended profile requests.\n *\n * @returns The prefix for use with `authedRequest`\n */\n private async getExtendedProfileRequestPrefix(): Promise<string> {\n if (await this.doesServerSupportUnstableFeature(\"uk.tcpip.msc4133.stable\")) {\n return ClientPrefix.V3;\n }\n return \"/_matrix/client/unstable/uk.tcpip.msc4133\";\n }\n\n /**\n * Fetch a user's *extended* profile, which may include additonal keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @returns A set of keys to property values.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the profile could not be found.\n */\n public async getExtendedProfile(userId: string): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n return this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Fetch a specific key from the user's *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @param key The key of the property to fetch.\n * @returns The property value.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the key was not set OR the profile could not be found.\n */\n public async getExtendedProfileProperty(userId: string, key: string): Promise<unknown> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const profile = (await this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n )) as Record<string, unknown>;\n return profile[key];\n }\n\n /**\n * Set a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to set.\n * @param value The value to set on the propety.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfileProperty(key: string, value: unknown): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n { [key]: value },\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Delete a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to delete.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async deleteExtendedProfileProperty(key: string): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Delete,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Update multiple properties on your *extended* profile. This will\n * merge with any existing keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to merge with the existing profile.\n * @returns The newly merged profile.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async patchExtendedProfile(profile: Record<string, unknown>): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n return this.http.authedRequest(\n Method.Patch,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Set multiple properties on your *extended* profile. This will completely\n * replace the existing profile, removing any unspecified keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to set.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfile(profile: Record<string, unknown>): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * @returns Promise which resolves to a list of the user's threepids.\n * @returns Rejects: with an error response.\n */\n public getThreePids(): Promise<{ threepids: IThreepid[] }> {\n return this.http.authedRequest(Method.Get, \"/account/3pid\");\n }\n\n /**\n * Add a 3PID to your homeserver account. This API does not use an identity\n * server, as the homeserver is expected to handle 3PID ownership validation.\n *\n * @param data - A object with 3PID validation data from having called\n * `account/3pid/<medium>/requestToken` on the homeserver.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async addThreePidOnly(data: IAddThreePidOnlyBody): Promise<{}> {\n const path = \"/account/3pid/add\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Bind a 3PID for discovery onto an identity server via the homeserver. The\n * identity server handles 3PID ownership validation and the homeserver records\n * the new binding to track where all 3PIDs for the account are bound.\n *\n * @param data - A object with 3PID validation data from having called\n * `validate/<medium>/requestToken` on the identity server. It should also\n * contain `id_server` and `id_access_token` fields as well.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async bindThreePid(data: IBindThreePidBody): Promise<{}> {\n const path = \"/account/3pid/bind\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Unbind a 3PID for discovery on an identity server via the homeserver. The\n * homeserver removes its record of the binding to keep an updated record of\n * where all 3PIDs for the account are bound.\n *\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: on success\n * @returns Rejects: with an error response.\n */\n public async unbindThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/unbind\";\n const data = {\n medium,\n address,\n id_server: this.getIdentityServerUrl(true),\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: The server response on success\n * (generally the empty JSON object)\n * @returns Rejects: with an error response.\n */\n public deleteThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/delete\";\n return this.http.authedRequest(Method.Post, path, undefined, { medium, address });\n }\n\n /**\n * Make a request to change your password.\n * @param newPassword - The new desired password.\n * @param logoutDevices - Should all sessions be logged out after the password change. Defaults to true.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPassword(authDict: AuthDict, newPassword: string, logoutDevices?: boolean): Promise<{}> {\n const path = \"/account/password\";\n const data = {\n auth: authDict,\n new_password: newPassword,\n logout_devices: logoutDevices,\n };\n\n return this.http.authedRequest<{}>(Method.Post, path, undefined, data);\n }\n\n /**\n * Gets all devices recorded for the logged-in user\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevices(): Promise<{ devices: IMyDevice[] }> {\n return this.http.authedRequest(Method.Get, \"/devices\");\n }\n\n /**\n * Gets specific device details for the logged-in user\n * @param deviceId - device to query\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevice(deviceId: string): Promise<IMyDevice> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Update the given device\n *\n * @param deviceId - device to update\n * @param body - body of request\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setDeviceDetails(deviceId: string, body: { display_name: string }): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Delete the given device\n *\n * @param deviceId - device to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteDevice(deviceId: string, auth?: AuthDict): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n const body: Body = {};\n\n if (auth) {\n body.auth = auth;\n }\n\n return this.http.authedRequest(Method.Delete, path, undefined, body);\n }\n\n /**\n * Delete multiple device\n *\n * @param devices - IDs of the devices to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteMultipleDevices(devices: string[], auth?: AuthDict): Promise<{}> {\n const body: Body = { devices };\n\n if (auth) {\n body.auth = auth;\n }\n\n const path = \"/delete_devices\";\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Gets all pushers registered for the logged-in user\n *\n * @returns Promise which resolves: Array of objects representing pushers\n * @returns Rejects: with an error response.\n */\n public async getPushers(): Promise<{ pushers: IPusher[] }> {\n const response = await this.http.authedRequest<{ pushers: IPusher[] }>(Method.Get, \"/pushers\");\n\n // Migration path for clients that connect to a homeserver that does not support\n // MSC3881 yet, see https://github.com/matrix-org/matrix-spec-proposals/blob/kerry/remote-push-toggle/proposals/3881-remote-push-notification-toggling.md#migration\n if (!(await this.doesServerSupportUnstableFeature(\"org.matrix.msc3881\"))) {\n response.pushers = response.pushers.map((pusher) => {\n if (!pusher.hasOwnProperty(PUSHER_ENABLED.name)) {\n pusher[PUSHER_ENABLED.name] = true;\n }\n return pusher;\n });\n }\n\n return response;\n }\n\n /**\n * Adds a new pusher or updates an existing pusher\n *\n * @param pusher - Object representing a pusher\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public setPusher(pusher: IPusherRequest): Promise<{}> {\n const path = \"/pushers/set\";\n return this.http.authedRequest(Method.Post, path, undefined, pusher);\n }\n\n /**\n * Removes an existing pusher\n * @param pushKey - pushkey of pusher to remove\n * @param appId - app_id of pusher to remove\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public removePusher(pushKey: string, appId: string): Promise<{}> {\n const path = \"/pushers/set\";\n const body = {\n pushkey: pushKey,\n app_id: appId,\n kind: null, // marks pusher for removal\n };\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Persists local notification settings\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setLocalNotificationSettings(\n deviceId: string,\n notificationSettings: LocalNotificationSettings,\n ): Promise<{}> {\n const key = `${LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${deviceId}`;\n return this.setAccountData(key, notificationSettings);\n }\n\n /**\n * Get the push rules for the account from the server.\n * @returns Promise which resolves to the push rules.\n * @returns Rejects: with an error response.\n */\n public getPushRules(): Promise<IPushRules> {\n return this.http.authedRequest<IPushRules>(Method.Get, \"/pushrules/\").then((rules: IPushRules) => {\n this.setPushRules(rules);\n return this.pushRules!;\n });\n }\n\n /**\n * Update the push rules for the account. This should be called whenever\n * updated push rules are available.\n */\n public setPushRules(rules: IPushRules): void {\n // Fix-up defaults, if applicable.\n this.pushRules = PushProcessor.rewriteDefaultRules(rules, this.getUserId()!);\n // Pre-calculate any necessary caches.\n this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public addPushRule(\n scope: string,\n kind: PushRuleKind,\n ruleId: Exclude<string, RuleId>,\n body: Pick<IPushRule, \"actions\" | \"conditions\" | \"pattern\">,\n ): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public deletePushRule(scope: string, kind: PushRuleKind, ruleId: Exclude<string, RuleId>): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Enable or disable a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleEnabled(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n enabled: boolean,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/enabled\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { enabled: enabled });\n }\n\n /**\n * Set the actions for a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleActions(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n actions: PushRuleAction[],\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/actions\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { actions: actions });\n }\n\n /**\n * Perform a server-side search.\n * @param params\n * @param params.next_batch - the batch token to pass in the query string\n * @param params.body - the JSON object to pass to the request body.\n * @param abortSignal - optional signal used to cancel the http request.\n * @returns Promise which resolves to the search response object.\n * @returns Rejects: with an error response.\n */\n public search(\n { body, next_batch: nextBatch }: { body: ISearchRequestBody; next_batch?: string },\n abortSignal?: AbortSignal,\n ): Promise<ISearchResponse> {\n const queryParams: QueryDict = {};\n if (nextBatch) {\n queryParams.next_batch = nextBatch;\n }\n return this.http.authedRequest(Method.Post, \"/search\", queryParams, body, { abortSignal });\n }\n\n /**\n * Ask the server for a list of users who have changed their device lists\n * between a pair of sync tokens\n *\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public getKeyChanges(oldToken: string, newToken: string): Promise<{ changed: string[]; left: string[] }> {\n const qps = {\n from: oldToken,\n to: newToken,\n };\n\n return this.http.authedRequest(Method.Get, \"/keys/changes\", qps);\n }\n\n /**\n * Register with an identity server using the OpenID token from the user's\n * Homeserver, which can be retrieved via\n * {@link MatrixClient#getOpenIdToken}.\n *\n * Note that the `/account/register` endpoint (as well as IS authentication in\n * general) was added as part of the v2 API version.\n *\n * @returns Promise which resolves: with object containing an Identity\n * Server access token.\n * @returns Rejects: with an error response.\n */\n public registerWithIdentityServer(hsOpenIdToken: IOpenIDToken): Promise<{\n access_token: string;\n token: string;\n }> {\n if (!this.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n const uri = this.http.getUrl(\"/account/register\", undefined, IdentityPrefix.V2, this.idBaseUrl);\n return this.http.requestOtherUrl(Method.Post, uri, hsOpenIdToken);\n }\n\n /**\n * Requests an email verification token directly from an identity server.\n *\n * This API is used as part of binding an email for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param email - The email address to request a token for\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another email.\n * To request another email to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the identity\n * server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n email: email,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestTokenResponse>(\n Method.Post,\n \"/validate/email/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Requests a MSISDN verification token directly from an identity server.\n *\n * This API is used as part of binding a MSISDN for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in\n * which phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international\n * format\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another SMS.\n * To request another SMS to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves to an object with a sid string\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n country: phoneCountry,\n phone_number: phoneNumber,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestMsisdnTokenResponse>(\n Method.Post,\n \"/validate/msisdn/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to the identity server\n *\n * This is used when submitting the code sent by SMS to a phone number.\n * The identity server has an equivalent API for email but the js-sdk does\n * not expose this, since email is normally validated by the user clicking\n * a link rather than entering a code.\n *\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n * Some legacy identity servers had no authentication here.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n * @throws Error if No identity server is set\n */\n public submitMsisdnToken(\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n identityAccessToken: string | null,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n\n return this.http.idServerRequest(\n Method.Post,\n \"/validate/msisdn/submitToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken ?? undefined,\n );\n }\n\n /**\n * Submits a MSISDN token to an arbitrary URL.\n *\n * This is used when submitting the code sent by SMS to a phone number in the\n * newer 3PID flow where the homeserver validates 3PID ownership (as part of\n * `requestAdd3pidMsisdnToken`). The homeserver response may include a\n * `submit_url` to specify where the token should be sent, and this helper can\n * be used to pass the token to this URL.\n *\n * @param url - The URL to submit the token to\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n */\n public submitMsisdnTokenOtherUrl(\n url: string,\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n return this.http.requestOtherUrl(Method.Post, url, params);\n }\n\n /**\n * Gets the V2 hashing information from the identity server. Primarily useful for\n * lookups.\n * @param identityAccessToken - The access token for the identity server.\n * @returns The hashing information for the identity server.\n */\n public getIdentityHashDetails(identityAccessToken: string): Promise<{\n /**\n * The algorithms the server supports. Must contain at least sha256.\n */\n algorithms: string[];\n /**\n * The pepper the client MUST use in hashing identifiers,\n * and MUST supply to the /lookup endpoint when performing lookups.\n */\n lookup_pepper: string;\n }> {\n return this.http.idServerRequest(\n Method.Get,\n \"/hash_details\",\n undefined,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Performs a hashed lookup of addresses against the identity server. This is\n * only supported on identity servers which have at least the version 2 API.\n * @param addressPairs - An array of 2 element arrays.\n * The first element of each pair is the address, the second is the 3PID medium.\n * Eg: `[\"email@example.org\", \"email\"]`\n * @param identityAccessToken - The access token for the identity server.\n * @returns A collection of address mappings to\n * found MXIDs. Results where no user could be found will not be listed.\n */\n public async identityHashedLookup(\n addressPairs: [string, string][],\n identityAccessToken: string,\n ): Promise<{ address: string; mxid: string }[]> {\n const params: Record<string, string | string[]> = {\n // addresses: [\"email@example.org\", \"10005550000\"],\n // algorithm: \"sha256\",\n // pepper: \"abc123\"\n };\n\n // Get hash information first before trying to do a lookup\n const hashes = await this.getIdentityHashDetails(identityAccessToken);\n if (!hashes || !hashes[\"lookup_pepper\"] || !hashes[\"algorithms\"]) {\n throw new Error(\"Unsupported identity server: bad response\");\n }\n\n params[\"pepper\"] = hashes[\"lookup_pepper\"];\n\n const localMapping: Record<string, string> = {\n // hashed identifier => plain text address\n // For use in this function's return format\n };\n\n // When picking an algorithm, we pick the hashed over no hashes\n if (hashes[\"algorithms\"].includes(\"sha256\")) {\n params[\"addresses\"] = await Promise.all(\n addressPairs.map(async (p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const hashBuffer = await sha256(`${addr} ${med} ${params[\"pepper\"]}`);\n const hashed = encodeUnpaddedBase64Url(hashBuffer);\n\n // Map the hash to a known (case-sensitive) address. We use the case\n // sensitive version because the caller might be expecting that.\n localMapping[hashed] = p[0];\n return hashed;\n }),\n );\n params[\"algorithm\"] = \"sha256\";\n } else if (hashes[\"algorithms\"].includes(\"none\")) {\n params[\"addresses\"] = addressPairs.map((p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const unhashed = `${addr} ${med}`;\n // Map the unhashed values to a known (case-sensitive) address. We use\n // the case-sensitive version because the caller might be expecting that.\n localMapping[unhashed] = p[0];\n return unhashed;\n });\n params[\"algorithm\"] = \"none\";\n } else {\n throw new Error(\"Unsupported identity server: unknown hash algorithm\");\n }\n\n const response = await this.http.idServerRequest<{\n mappings: { [address: string]: string };\n }>(Method.Post, \"/lookup\", params, IdentityPrefix.V2, identityAccessToken);\n\n if (!response?.[\"mappings\"]) return []; // no results\n\n const foundAddresses: { address: string; mxid: string }[] = [];\n for (const hashed of Object.keys(response[\"mappings\"])) {\n const mxid = response[\"mappings\"][hashed];\n const plainAddress = localMapping[hashed];\n if (!plainAddress) {\n throw new Error(\"Identity server returned more results than expected\");\n }\n\n foundAddresses.push({ address: plainAddress, mxid });\n }\n return foundAddresses;\n }\n\n /**\n * Looks up the public Matrix ID mapping for a given 3rd party\n * identifier from the identity server\n *\n * @param medium - The medium of the threepid, eg. 'email'\n * @param address - The textual address of the threepid\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: A threepid mapping\n * object or the empty object if no mapping\n * exists\n * @returns Rejects: with an error response.\n */\n public async lookupThreePid(\n medium: string,\n address: string,\n identityAccessToken: string,\n ): Promise<\n | {\n address: string;\n medium: string;\n mxid: string;\n }\n | {}\n > {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup([[address, medium]], identityAccessToken);\n const result = response.find((p) => p.address === address);\n if (!result) {\n return {};\n }\n\n const mapping = {\n address,\n medium,\n mxid: result.mxid,\n\n // We can't reasonably fill these parameters:\n // not_before\n // not_after\n // ts\n // signatures\n };\n\n return mapping;\n }\n\n /**\n * Looks up the public Matrix ID mappings for multiple 3PIDs.\n *\n * @param query - Array of arrays containing\n * [medium, address]\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: Lookup results from IS.\n * @returns Rejects: with an error response.\n */\n public async bulkLookupThreePids(\n query: [string, string][],\n identityAccessToken: string,\n ): Promise<{\n threepids: [medium: string, address: string, mxid: string][];\n }> {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup(\n // We have to reverse the query order to get [address, medium] pairs\n query.map((p) => [p[1], p[0]]),\n identityAccessToken,\n );\n\n const v1results: [medium: string, address: string, mxid: string][] = [];\n for (const mapping of response) {\n const originalQuery = query.find((p) => p[1] === mapping.address);\n if (!originalQuery) {\n throw new Error(\"Identity sever returned unexpected results\");\n }\n\n v1results.push([\n originalQuery[0], // medium\n mapping.address,\n mapping.mxid,\n ]);\n }\n\n return { threepids: v1results };\n }\n\n /**\n * Get account info from the identity server. This is useful as a neutral check\n * to verify that other APIs are likely to approve access by testing that the\n * token is valid, terms have been agreed, etc.\n *\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: an object with account info.\n * @returns Rejects: with an error response.\n */\n public getIdentityAccount(identityAccessToken: string): Promise<{ user_id: string }> {\n return this.http.idServerRequest(Method.Get, \"/account\", undefined, IdentityPrefix.V2, identityAccessToken);\n }\n\n /**\n * Send an event to a specific list of devices.\n * This is a low-level API that simply wraps the HTTP API\n * call to send to-device messages. We recommend using\n * queueToDevice() which is a higher level API.\n *\n * @param eventType - type of event to send\n * content to send. Map from user_id to device_id to content object.\n * @param txnId - transaction id. One will be made up if not\n * supplied.\n * @returns Promise which resolves: to an empty object `{}`\n */\n public sendToDevice(eventType: string, contentMap: SendToDeviceContentMap, txnId?: string): Promise<{}> {\n const path = utils.encodeUri(\"/sendToDevice/$eventType/$txnId\", {\n $eventType: eventType,\n $txnId: txnId ? txnId : this.makeTxnId(),\n });\n\n const body = {\n messages: utils.recursiveMapToObject(contentMap),\n };\n\n const targets = new Map<string, string[]>();\n\n for (const [userId, deviceMessages] of contentMap) {\n targets.set(userId, Array.from(deviceMessages.keys()));\n }\n\n this.logger.debug(`PUT ${path}`, targets);\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Sends events directly to specific devices using Matrix's to-device\n * messaging system. The batch will be split up into appropriately sized\n * batches for sending and stored in the store so they can be retried\n * later if they fail to send. Retries will happen automatically.\n * @param batch - The to-device messages to send\n */\n public queueToDevice(batch: ToDeviceBatch): Promise<void> {\n return this.toDeviceMessageQueue.queueBatch(batch);\n }\n\n /**\n * Get the third party protocols that can be reached using\n * this HS\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyProtocols(): Promise<{ [protocol: string]: IProtocol }> {\n return this.http\n .authedRequest<Record<string, IProtocol>>(Method.Get, \"/thirdparty/protocols\")\n .then((response) => {\n // sanity check\n if (!response || typeof response !== \"object\") {\n throw new Error(`/thirdparty/protocols did not return an object: ${response}`);\n }\n return response;\n });\n }\n\n /**\n * Get information on how a specific place on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyLocation(\n protocol: string,\n params: { searchFields?: string[] },\n ): Promise<IThirdPartyLocation[]> {\n const path = utils.encodeUri(\"/thirdparty/location/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Get information on how a specific user on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyUser(protocol: string, params?: QueryDict): Promise<IThirdPartyUser[]> {\n const path = utils.encodeUri(\"/thirdparty/user/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n public getTerms(serviceType: SERVICE_TYPES, baseUrl: string): Promise<any> {\n // TODO: Types\n const url = this.termsUrlForService(serviceType, baseUrl);\n return this.http.requestOtherUrl(Method.Get, url);\n }\n\n public agreeToTerms(\n serviceType: SERVICE_TYPES,\n baseUrl: string,\n accessToken: string,\n termsUrls: string[],\n ): Promise<{}> {\n const url = this.termsUrlForService(serviceType, baseUrl);\n const headers = {\n Authorization: \"Bearer \" + accessToken,\n };\n return this.http.requestOtherUrl(\n Method.Post,\n url,\n {\n user_accepts: termsUrls,\n },\n { headers },\n );\n }\n\n /**\n * Reports an event as inappropriate to the server, which may then notify the appropriate people.\n * @param roomId - The room in which the event being reported is located.\n * @param eventId - The event to report.\n * @param score - The score to rate this content as where -100 is most offensive and 0 is inoffensive.\n * @param reason - The reason the content is being reported. May be blank.\n * @returns Promise which resolves to an empty object if successful\n */\n public reportEvent(roomId: string, eventId: string, score: number, reason: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/report/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, { score, reason });\n }\n\n /**\n * Fetches or paginates a room hierarchy as defined by MSC2946.\n * Falls back gracefully to sourcing its data from `getSpaceSummary` if this API is not yet supported by the server.\n * @param roomId - The ID of the space-room to use as the root of the summary.\n * @param limit - The maximum number of rooms to return per page.\n * @param maxDepth - The maximum depth in the tree from the root room to return.\n * @param suggestedOnly - Whether to only return rooms with suggested=true.\n * @param fromToken - The opaque token to paginate a previous request.\n * @returns the response, with next_batch & rooms fields.\n */\n public getRoomHierarchy(\n roomId: string,\n limit?: number,\n maxDepth?: number,\n suggestedOnly = false,\n fromToken?: string,\n ): Promise<IRoomHierarchy> {\n const path = utils.encodeUri(\"/rooms/$roomId/hierarchy\", {\n $roomId: roomId,\n });\n\n const queryParams: QueryDict = {\n suggested_only: String(suggestedOnly),\n max_depth: maxDepth?.toString(),\n from: fromToken,\n limit: limit?.toString(),\n };\n\n return this.http\n .authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n })\n .catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n // fall back to the prefixed hierarchy API.\n return this.http.authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2946\",\n });\n }\n\n throw e;\n });\n }\n\n /**\n * Creates a new file tree space with the given name. The client will pick\n * defaults for how it expects to be able to support the remaining API offered\n * by the returned class.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param name - The name of the tree space.\n * @returns Promise which resolves to the created space.\n */\n public async unstableCreateFileTree(name: string): Promise<MSC3089TreeSpace> {\n const { room_id: roomId } = await this.createRoom({\n name: name,\n preset: Preset.PrivateChat,\n power_level_content_override: {\n ...DEFAULT_TREE_POWER_LEVELS_TEMPLATE,\n users: {\n [this.getUserId()!]: 100,\n },\n },\n creation_content: {\n [RoomCreateTypeField]: RoomType.Space,\n },\n initial_state: [\n {\n type: UNSTABLE_MSC3088_PURPOSE.name,\n state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n content: {\n [UNSTABLE_MSC3088_ENABLED.name]: true,\n },\n },\n ],\n });\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Gets a reference to a tree space, if the room ID given is a tree space. If the room\n * does not appear to be a tree space then null is returned.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param roomId - The room ID to get a tree space reference for.\n * @returns The tree space, or null if not a tree space.\n */\n public unstableGetFileTreeSpace(roomId: string): MSC3089TreeSpace | null {\n const room = this.getRoom(roomId);\n if (room?.getMyMembership() !== KnownMembership.Join) return null;\n\n const createEvent = room.currentState.getStateEvents(EventType.RoomCreate, \"\");\n const purposeEvent = room.currentState.getStateEvents(\n UNSTABLE_MSC3088_PURPOSE.name,\n UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n );\n\n if (!createEvent) throw new Error(\"Expected single room create event\");\n\n if (!purposeEvent?.getContent()?.[UNSTABLE_MSC3088_ENABLED.name]) return null;\n if (createEvent.getContent()?.[RoomCreateTypeField] !== RoomType.Space) return null;\n\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Perform a single MSC3575 sliding sync request.\n * @param req - The request to make.\n * @param proxyBaseUrl - The base URL for the sliding sync proxy.\n * @param abortSignal - Optional signal to abort request mid-flight.\n * @returns The sliding sync response, or a standard error.\n * @throws on non 2xx status codes with an object with a field \"httpStatus\":number.\n */\n public slidingSync(\n req: MSC3575SlidingSyncRequest,\n proxyBaseUrl?: string,\n abortSignal?: AbortSignal,\n ): Promise<MSC3575SlidingSyncResponse> {\n const qps: QueryDict = {};\n if (req.pos) {\n qps.pos = req.pos;\n delete req.pos;\n }\n if (req.timeout) {\n qps.timeout = req.timeout;\n delete req.timeout;\n }\n const clientTimeout = req.clientTimeout;\n delete req.clientTimeout;\n return this.http.authedRequest<MSC3575SlidingSyncResponse>(Method.Post, \"/sync\", qps, req, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3575\",\n baseUrl: proxyBaseUrl,\n localTimeoutMs: clientTimeout,\n abortSignal,\n });\n }\n\n /**\n * A helper to determine thread support\n * @returns a boolean to determine if threads are enabled\n */\n public supportsThreads(): boolean {\n return this.clientOpts?.threadSupport || false;\n }\n\n /**\n * A helper to determine intentional mentions support\n * @returns a boolean to determine if intentional mentions are enabled on the server\n * @experimental\n */\n public supportsIntentionalMentions(): boolean {\n return this.canSupport.get(Feature.IntentionalMentions) !== ServerSupport.Unsupported;\n }\n\n /**\n * Fetches the summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n * @param roomIdOrAlias - The ID or alias of the room to get the summary of.\n * @param via - The list of servers which know about the room if only an ID was provided.\n */\n public async getRoomSummary(roomIdOrAlias: string, via?: string[]): Promise<RoomSummary> {\n const paramOpts = {\n prefix: \"/_matrix/client/unstable/im.nheko.summary\",\n };\n try {\n const path = utils.encodeUri(\"/summary/$roomid\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } catch (e) {\n if (e instanceof MatrixError && e.errcode === \"M_UNRECOGNIZED\") {\n const path = utils.encodeUri(\"/rooms/$roomid/summary\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } else {\n throw e;\n }\n }\n }\n\n /**\n * Processes a list of threaded events and adds them to their respective timelines\n * @param room - the room the adds the threaded events\n * @param threadedEvents - an array of the threaded events\n * @param toStartOfTimeline - the direction in which we want to add the events\n */\n public processThreadEvents(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n room.processThreadedEvents(threadedEvents, toStartOfTimeline);\n }\n\n /**\n * Processes a list of thread roots and creates a thread model\n * @param room - the room to create the threads in\n * @param threadedEvents - an array of thread roots\n * @param toStartOfTimeline - the direction\n */\n public processThreadRoots(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n if (!this.supportsThreads()) return;\n room.processThreadRoots(threadedEvents, toStartOfTimeline);\n }\n\n public processBeaconEvents(room?: Room, events?: MatrixEvent[]): void {\n this.processAggregatedTimelineEvents(room, events);\n }\n\n /**\n * Calls aggregation functions for event types that are aggregated\n * Polls and location beacons\n * @param room - room the events belong to\n * @param events - timeline events to be processed\n * @returns\n */\n public processAggregatedTimelineEvents(room?: Room, events?: MatrixEvent[]): void {\n if (!events?.length) return;\n if (!room) return;\n\n room.currentState.processBeaconEvents(events, this);\n room.processPollEvents(events);\n }\n\n /**\n * Fetches information about the user for the configured access token.\n */\n public async whoami(): Promise<IWhoamiResponse> {\n return this.http.authedRequest(Method.Get, \"/account/whoami\");\n }\n\n /**\n * Find the event_id closest to the given timestamp in the given direction.\n * @returns Resolves: A promise of an object containing the event_id and\n * origin_server_ts of the closest event to the timestamp in the given direction\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n */\n public async timestampToEvent(\n roomId: string,\n timestamp: number,\n dir: Direction,\n ): Promise<TimestampToEventResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/timestamp_to_event\", {\n $roomId: roomId,\n });\n const queryParams = {\n ts: timestamp.toString(),\n dir: dir,\n };\n\n try {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n });\n } catch (err) {\n // Fallback to the prefixed unstable endpoint. Since the stable endpoint is\n // new, we should also try the unstable endpoint before giving up. We can\n // remove this fallback request in a year (remove after 2023-11-28).\n if (\n (<MatrixError>err).errcode === \"M_UNRECOGNIZED\" &&\n // XXX: The 400 status code check should be removed in the future\n // when Synapse is compliant with MSC3743.\n ((<MatrixError>err).httpStatus === 400 ||\n // This the correct standard status code for an unsupported\n // endpoint according to MSC3743. Not Found and Method Not Allowed\n // both indicate that this endpoint+verb combination is\n // not supported.\n (<MatrixError>err).httpStatus === 404 ||\n (<MatrixError>err).httpStatus === 405)\n ) {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3030\",\n });\n }\n\n throw err;\n }\n }\n\n /**\n * Get the OIDC issuer responsible for authentication on this server, if any\n * @returns Resolves: A promise of an object containing the OIDC issuer if configured\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n * @experimental - part of MSC2965\n */\n public async getAuthIssuer(): Promise<{\n issuer: string;\n }> {\n return this.http.request(Method.Get, \"/auth_issuer\", undefined, undefined, {\n prefix: ClientPrefix.Unstable + \"/org.matrix.msc2965\",\n });\n }\n}\n\nfunction getUnstableDelayQueryOpts(delayOpts: SendDelayedEventRequestOpts): QueryDict {\n return Object.fromEntries(\n Object.entries(delayOpts).map(([k, v]) => [`${UNSTABLE_MSC4140_DELAYED_EVENTS}.${k}`, v]),\n );\n}\n\n/**\n * Given an event, figure out the thread ID we should use for it in a receipt.\n *\n * This will either be \"main\", or event.threadRootId. For the thread root, or\n * e.g. reactions to the thread root, this will be main. For events inside the\n * thread, or e.g. reactions to them, this will be event.threadRootId.\n *\n * (Exported for test.)\n */\nexport function threadIdForReceipt(event: MatrixEvent): string {\n return inMainTimelineForReceipt(event) ? MAIN_ROOM_TIMELINE : event.threadRootId!;\n}\n\n/**\n * a) True for non-threaded messages, thread roots and non-thread relations to thread roots.\n * b) False for messages with thread relations to the thread root.\n * c) False for messages with any kind of relation to a message from case b.\n *\n * Note: true for redactions of messages that are in threads. Redacted messages\n * are not really in threads (because their relations are gone), so if they look\n * like they are in threads, that is a sign of a bug elsewhere. (At time of\n * writing, this bug definitely exists - messages are not moved to another\n * thread when they are redacted.)\n *\n * @returns true if this event is considered to be in the main timeline as far\n * as receipts are concerned.\n */\nexport function inMainTimelineForReceipt(event: MatrixEvent): boolean {\n if (!event.threadRootId) {\n // Not in a thread: then it is in the main timeline\n return true;\n }\n\n if (event.isThreadRoot) {\n // Thread roots are in the main timeline. Note: the spec is ambiguous (or\n // wrong) on this - see\n // https://github.com/matrix-org/matrix-spec-proposals/pull/4037\n return true;\n }\n\n if (!event.isRelation()) {\n // If it's not related to anything, it can't be related via a chain of\n // relations to a thread root.\n //\n // Note: this is a bug, because how does it have a threadRootId if it is\n // neither a thread root, nor related to one?\n logger.warn(`Event is not a relation or a thread root, but still has a threadRootId! id=${event.getId()}`);\n return true;\n }\n\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n // It's a message in a thread - definitely not in the main timeline.\n return false;\n }\n\n const isRelatedToRoot = event.relationEventId === event.threadRootId;\n\n // If it's related to the thread root (and we already know it's not a thread\n // relation) then it's in the main timeline. If it's related to something\n // else, then it's in the thread (because it has a thread ID).\n return isRelatedToRoot;\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAIA,SAAsCA,OAAO,EAAkBC,SAAS,QAAQ,WAAW;AAC3F,SACIC,WAAW,EAIXC,WAAW,EACXC,gBAAgB,QAGb,mBAAmB;AAC1B,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,MAAM,QAA6C,aAAa;AACzE,OAAO,KAAKC,KAAK,MAAM,YAAY;AACnC,SAASC,kBAAkB,EAAaC,YAAY,EAAEC,KAAK,QAAQ,YAAY;AAC/E,SAASC,SAAS,EAAEC,aAAa,QAAQ,4BAA4B;AACrE,SAAyBC,aAAa,QAAQ,oBAAoB;AAClE,SAASC,aAAa,QAA6B,oBAAoB;AACvE,SAASC,uBAAuB,QAAQ,aAAa;AACrD,SAASC,cAAc,QAAQ,gBAAgB;AAC/C,SAASC,MAAM,QAAgB,aAAa;AAC5C,SAASC,aAAa,QAAQ,oBAAoB;AAClD,SAEIC,YAAY,EAIZC,cAAc,EAGdC,WAAW,EACXC,aAAa,EACbC,WAAW,EACXC,MAAM,EACNC,qBAAqB,QAKlB,qBAAqB;AAC5B,SAASC,IAAI,EAAEC,SAAS,QAA6B,kBAAkB;AACvE,SAASC,gBAAgB,QAAQ,mBAAmB;AACpD,SAASC,YAAY,QAAQ,2BAA2B;AAOxD,OAAO,KAAKC,cAAc,MAAM,sBAAsB;AACtD,SAASC,qBAAqB,QAA6D,kBAAkB;AA6B7G,SACIC,SAAS,EACTC,kCAAkC,EAClCC,sCAAsC,EACtCC,OAAO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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASD,wBAAwBA,CAAC/9B,KAAkB,EAAW;EAClE,IAAI,CAACA,KAAK,CAACg+B,YAAY,EAAE;IACrB;IACA,OAAO,IAAI;EACf;EAEA,IAAIh+B,KAAK,CAACi+B,YAAY,EAAE;IACpB;IACA;IACA;IACA,OAAO,IAAI;EACf;EAEA,IAAI,CAACj+B,KAAK,CAAC2H,UAAU,CAAC,CAAC,EAAE;IACrB;IACA;IACA;IACA;IACA;IACA1Y,MAAM,CAACqH,IAAI,+EAAAgT,MAAA,CAA+EtJ,KAAK,CAAC8D,KAAK,CAAC,CAAC,CAAE,CAAC;IAC1G,OAAO,IAAI;EACf;EAEA,IAAI9D,KAAK,CAAC2H,UAAU,CAAC/V,oBAAoB,CAACsS,IAAI,CAAC,EAAE;IAC7C;IACA,OAAO,KAAK;EAChB;EAEA,IAAMg6B,eAAe,GAAGl+B,KAAK,CAACm+B,eAAe,KAAKn+B,KAAK,CAACg+B,YAAY;;EAEpE;EACA;EACA;EACA,OAAOE,eAAe;AAC1B","ignoreList":[]}
1
+ {"version":3,"file":"client.js","names":["SyncApi","SyncState","EventStatus","MatrixEvent","MatrixEventEvent","StubStore","Filter","utils","noUnsafeEventProps","replaceParam","sleep","Direction","EventTimeline","PushProcessor","AutoDiscovery","encodeUnpaddedBase64Url","TypedReEmitter","logger","SERVICE_TYPES","ClientPrefix","IdentityPrefix","MatrixError","MatrixHttpApi","MediaPrefix","Method","retryNetworkOperation","User","UserEvent","getHttpUriForMxc","SearchResult","ContentHelpers","NotificationCountType","EventType","LOCAL_NOTIFICATION_SETTINGS_PREFIX","MSC3912_RELATION_BASED_REDACTIONS_PROP","MsgType","PUSHER_ENABLED","RelationType","RoomCreateTypeField","RoomType","UNSTABLE_MSC3088_ENABLED","UNSTABLE_MSC3088_PURPOSE","UNSTABLE_MSC3089_TREE_SUBTYPE","GuestAccess","HistoryVisibility","Preset","eventMapperFor","randomString","DEFAULT_TREE_POWER_LEVELS_TEMPLATE","MSC3089TreeSpace","SearchOrderBy","PushRuleActionName","PushRuleKind","TypedEventEmitter","MAIN_ROOM_TIMELINE","ReceiptType","SlidingSyncSdk","determineFeatureSupport","FeatureSupport","Thread","THREAD_RELATION_TYPE","ThreadFilterType","threadFilterTypeToFilter","M_BEACON_INFO","NamespacedValue","UnstableValue","ToDeviceMessageQueue","IgnoredInvites","buildFeatureSupportMap","Feature","ServerSupport","getRelationsThreadFilter","KnownMembership","ServerCapabilities","sha256","SCROLLBACK_DELAY_MS","UNSTABLE_MSC3852_LAST_SEEN_UA","PendingEventOrdering","GET_LOGIN_TOKEN_CAPABILITY","UNSTABLE_MSC2666_SHARED_ROOMS","UNSTABLE_MSC2666_MUTUAL_ROOMS","UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS","UNSTABLE_MSC4140_DELAYED_EVENTS","UNSTABLE_MSC4133_EXTENDED_PROFILES","EVENT_ID_PREFIX","ClientEvent","SSO_ACTION_PARAM","MatrixClient","constructor","opts","_opts$logger","_opts$usingExternalCr","_this","this","_defineProperty","Map","Set","isInitialSyncComplete","_this$getRooms","unreadRooms","getRooms","filter","room","getUnreadNotificationCount","Total","currentUserId","getSafeUserId","fixupNotifications","off","Sync","fixupRoomNotifications","baseUrl","ensureNoTrailingSlash","idBaseUrl","identityServer","usingExternalCrypto","store","deviceId","sessionId","userId","credentials","http","fetchFn","accessToken","refreshToken","tokenRefreshFunction","prefix","V3","onlyData","extraParams","queryParams","localTimeoutMs","useAuthorizationHeader","deviceToImport","warn","pickleKey","useLivekitForGroupCalls","Boolean","scheduler","setProcessFunction","_ref","_asyncToGenerator","eventToSend","getRoom","getRoomId","status","SENDING","updatePendingEventStatus","res","sendEventHttpRequest","updatePendingEvent","SENT","event_id","_x","apply","arguments","serverCapabilitiesService","on","timelineSupport","verificationMethods","iceCandidatePoolSize","undefined","fallbackICEServerAllowed","isVoipWithNoMediaAllowed","livekitServiceURL","roomNameGenerator","toDeviceMessageQueue","ignoredInvites","setMaxListeners","newStore","_store","setUserCreator","createUser","startClient","_this2","clientRunning","getUserId","storeUser","syncApi","error","stop","getVersions","threads","list","fwdPagination","doesServerSupportThread","setServerSideSupport","setServerSideListSupport","setServerSideFwdPaginationSupport","e","clientOpts","slidingSync","buildSyncApiOptions","sync","catch","info","clientWellKnownPollPeriod","clientWellKnownIntervalID","setInterval","fetchClientWellKnown","start","canResetEntireTimeline","roomId","canResetTimelineCallback","stopClient","_this$syncApi","_this$peekSync","debug","peekSync","stopPeeking","globalThis","clearInterval","clearStores","Error","promises","push","deleteAllData","Promise","all","then","getDomain","replace","getUserIdLocalpart","split","substring","getDeviceId","getSessionId","getLivekitServiceURL","setLivekitServiceURL","newURL","getSyncState","_this$syncApi$getSync","_this$syncApi2","getSyncStateData","state","Prepared","Syncing","isGuest","isGuestAccount","setGuest","guest","getScheduler","retryImmediately","_this$syncApi$retryIm","_this$syncApi3","sendQueue","getNotifTimelineSet","notifTimelineSet","setNotifTimelineSet","set","getCapabilities","_this3","caps","getCachedCapabilities","fetchCapabilities","uploadKeys","_this4","getMediaConfig","authedRequest","Get","getVisibleRooms","msc3946ProcessDynamicPredecessor","length","allRooms","replacedRooms","r","_r$findPredecessor","predecessor","findPredecessor","add","tombstone","currentState","getStateEvents","RoomTombstone","has","getUser","getUsers","setAccountData","eventType","content","path","encodeUri","$userId","$type","Put","getAccountData","getAccountDataFromServer","_this5","event","getContent","_data","data","errcode","deleteAccountData","_this6","msc3391DeleteAccountDataServerSupport","canSupport","get","AccountDataDeletion","Unsupported","options","Unstable","Delete","getIgnoredUsers","Object","keys","setIgnoredUsers","userIds","ignored_users","forEach","u","isUserIgnored","includes","joinRoom","roomIdOrAlias","_arguments","_this7","syncRoom","hasMembershipState","Join","signPromise","resolve","inviteSignUrl","url","URL","searchParams","requestOtherUrl","Post","viaServers","server_name","via","signedInviteObj","third_party_signed","$roomid","room_id","resolvedRoom","createRoom","knockRoom","Knock","$roomIdOrAlias","body","reason","resendEvent","encryptAndSendEvent","cancelPendingEvent","QUEUED","NOT_SENT","ENCRYPTING","eventsBeingEncrypted","delete","getId","removeEventFromQueue","CANCELLED","setRoomName","name","sendStateEvent","RoomName","setRoomTopic","topic","htmlTopic","makeTopicContent","RoomTopic","getRoomTags","$roomId","setRoomTag","tagName","metadata","$tag","deleteRoomTag","setRoomAccountData","setPowerLevel","powerLevel","_this8","_content","_this8$getRoom","RoomPowerLevels","getStateEvent","deepCopy","users","Array","isArray","user","unstable_createLiveBeacon","beaconInfoContent","_this9","unstable_setLiveBeacon","_this10","sendEvent","threadIdOrEventType","eventTypeOrContent","contentOrTxnId","txnIdOrVoid","threadId","txnId","startsWith","addThreadRelationIfNeeded","sendCompleteEvent","type","_content$mRelates_to","rel_type","_content$mRelates_to2","_this$getRoom","isReply","_objectSpread","is_falling_back","thread","getThread","_thread$lastReply$get","_thread$lastReply","lastReply","ev","isRelation","eventObject","delayOptsOrTxnId","delayOpts","makeTxnId","localEvent","assign","user_id","sender","origin_server_ts","Date","getTime","setThread","reEmitter","reEmit","Replaced","VisibilityChange","BeforeRedaction","targetId","getAssociatedId","target","getPendingEvents","find","once","LocalEventIdReplaced","updateAssociatedId","getType","concat","setTxnId","setStatus","addPendingEvent","reject","_this11","promise","queueEvent","getQueueForEvent","err","getEncryptedIfNeededEventType","_this$getRoom2","Reaction","hasEncryptionStateEvent","RoomMessageEncrypted","newStatus","getTxnId","pathParams","$eventType","getWireType","$stateKey","getStateKey","$txnId","isState","pathTemplate","isRedaction","redacts","$redactsEventId","getWireContent","getUnstableDelayQueryOpts","redactEvent","eventId","_eventId","_opts","_opts2","with_rel_types","RelationBasedRedactions","withRelTypesPropName","Stable","stable","unstable","RoomRedaction","sendMessage","RoomMessage","sendContent","sendTextMessage","_threadId","makeTextMessage","sendNotice","_threadId2","makeNotice","sendEmoteMessage","_threadId3","makeEmoteMessage","sendImageMessage","_threadId4","text","msgtype","Image","sendStickerMessage","_threadId5","Sticker","sendHtmlMessage","htmlBody","_threadId6","makeHtmlMessage","sendHtmlNotice","_threadId7","makeHtmlNotice","sendHtmlEmote","_threadId8","makeHtmlEmote","_unstable_sendDelayedEvent","_this12","doesServerSupportUnstableFeature","_unstable_sendDelayedStateEvent","_arguments2","_this13","stateKey","_unstable_getDelayedEvents","fromToken","_this14","queryDict","from","_unstable_updateDelayedEvent","delayId","action","_this15","$delayId","sendReceipt","receiptType","_arguments3","_this16","unthreaded","$receiptType","$eventId","shouldAddThreadId","supportsThreads","fullBody","thread_id","threadIdForReceipt","addLocalEchoReceipt","sendReadReceipt","_arguments4","_this17","Read","hasPendingEvent","setRoomReadMarkers","rmEventId","rrEvent","rpEvent","_this18","rrEventId","rpEventId","ReadPrivate","setRoomReadMarkersHttpRequest","getUrlPreview","ts","Math","floor","parsed","hash","toString","key","urlPreviewCache","resp","priority","sendTyping","isTyping","timeoutMs","typing","timeout","getRoomUpgradeHistory","verifyLinks","currentRoom","before","findPredecessorRooms","after","findSuccessorRooms","_room$findPredecessor","ret","seenRoomIDs","predecessorRoomId","_room$findPredecessor2","predecessorRoom","splice","tombstoneEvent","successorRoom","_successorRoom$findPr","roomIds","map","ref","size","slice","invite","membershipChange","Invite","inviteByEmail","email","inviteByThreePid","medium","address","_this19","_this19$identityServe","identityServerUrl","getIdentityServerUrl","params","id_server","getAccessToken","identityAccessToken","leave","Leave","leaveRoomChain","includeFuture","upgradeHistory","eligibleToLeave","populationResults","doLeave","ban","Ban","forget","_arguments5","_this20","deleteRoom","$room_id","response","removeRoom","emit","DeleteRoom","unban","kick","membership","$membership","getPushActionsForEvent","forceRecalculate","getPushActions","actions","rule","pushProcessor","actionsAndRuleForEvent","setPushDetails","getPushDetailsForEvent","getPushDetails","setProfileInfo","$info","setDisplayName","_this21","prom","displayname","displayName","DisplayName","events","presence","setAvatarUrl","_this22","avatar_url","avatarUrl","AvatarUrl","mxcUrlToHttp","mxcUrl","width","height","resizeMethod","allowDirectLinks","allowRedirects","useAuthentication","setSyncPresence","_this23","_this23$syncApi","setPresence","_this24","validStates","indexOf","getPresence","scrollback","limit","timeToWaitMs","ongoingScrollbacks","errorTs","timeWaitedMs","now","max","oldState","paginationToken","numAdded","createMessagesRequest","Backward","_res$end","_res$end2","matrixEvents","chunk","getEventMapper","stateEvents","setUnknownStateEvents","timelineEvents","threadedEvents","unknownRelations","partitionThreadedEvents","processAggregatedTimelineEvents","addEventsToTimeline","getLiveTimeline","processThreadEvents","relations","aggregateChildEvent","end","storeEvents","getEventTimeline","timelineSet","_this25","_this25$clientOpts","_ref2","_timelineSet$getTimel","_timelineSet$room$fin","getTimelineForEvent","getThreadTimeline","lazyLoadMembers","JSON","stringify","LAZY_LOADING_MESSAGES_FILTER","mapper","events_after","reverse","events_before","timeline","getState","BACKWARDS","addTimeline","initialiseState","FORWARDS","findThreadForEvent","liveTimeline","_this26","_this26$clientOpts","canContain","recurse","RelationsRecursion","hasServerSideSupport","hasServerSideFwdPaginationSupport","_resOlder$next_batch","_resNewer$next_batch","_timelineSet$getTimel2","resOlder","fetchRelations","id","dir","resNewer","Forward","_timelineSet$thread","processEvent","next_batch","originalEvent","fetchRoomEvent","setPaginationToken","_resOlder$next_batch2","eventsNewer","nextBatch","_resNewer$next_batch2","_timelineSet$thread2","getLatestTimeline","_this27","threadListType","_res$chunk","createThreadListMessagesRequest","getFilter","_res$chunk2","_this27$clientOpts","_res2$chunk","messagesPath","_this$clientOpts","timelineFilter","_timelineFilter$getRo","getRoomTimelineFilterComponent","toJSON","_this$clientOpts2","All","include","_timelineFilter$getRo2","hasServerSideListSupport","V1","_res$chunk3","prev_batch","paginateEventTimeline","eventTimeline","_this28","isNotifTimeline","getTimelineSet","backwards","token","getPaginationToken","pendingRequest","paginationRequests","_opts$limit","only","_ref3","next_token","notifications","i","notification","_x2","finally","roomState","processThreadRoots","_eventTimeline$getRoo","_eventTimeline$getRoo2","_ref4","getSender","getEventReadUpTo","newToken","_thread$rootEvent","_eventTimeline$getRoo3","rootEvent","_x3","it","getServerAggregatedRelation","atEnd","resetNotifTimelineSet","resetLiveTimeline","peekInRoom","_this$peekSync2","peek","setGuestAccess","writePromise","RoomGuestAccess","guest_access","allowJoin","CanJoin","Forbidden","readPromise","allowRead","RoomHistoryVisibility","history_visibility","WorldReadable","requestRegisterEmailToken","clientSecret","sendAttempt","nextLink","requestTokenFromEndpoint","client_secret","send_attempt","next_link","requestRegisterMsisdnToken","phoneCountry","phoneNumber","country","phone_number","requestAdd3pidEmailToken","requestAdd3pidMsisdnToken","requestPasswordEmailToken","requestPasswordMsisdnToken","endpoint","_this29","postParams","request","getRoomPushRule","scope","pushRules","_this$pushRules$scope","rule_id","setRoomMutePushRule","mute","hasDontNotifyRule","roomPushRule","DontNotify","deletePushRule","RoomSpecific","addPushRule","deferred","defer","getPushRules","result","err2","searchMessageText","roomEvents","search_term","query","search","search_categories","room_events","searchRoomEvents","term","order_by","Recent","event_context","before_limit","after_limit","include_profile","searchResults","_query","results","highlights","processRoomEventsSearch","backPaginateRoomEventsSearch","searchOpts","abortSignal","_roomEvents$results$l","_roomEvents$results","count","hl","resultsLength","sr","fromJson","context","getEvent","getTimeline","getMember","syncLeftRooms","syncedLeftRooms","syncLeftRoomsPromise","createFilter","filter_id","storeFilter","filterId","allowCached","$filterId","getOrCreateFilter","filterName","_this30","getFilterIdByName","existingId","existingFilter","oldDef","getDefinition","newDef","deepCompare","setFilterIdByName","createdFilter","getOpenIdToken","setFallbackICEServerAllowed","allow","isFallbackICEServerAllowed","isSynapseAdministrator","admin","whoisSynapseUser","deactivateSynapseUser","_this31","_this31$getDomain","clientWellKnownPromise","getRawClientConfig","clientWellKnown","ClientWellKnown","getClientWellKnown","waitForClientWellKnown","storeClientOptions","primTypes","serializableOpts","entries","_ref5","value","reduce","obj","_ref6","_unstable_getSharedRooms","_this32","sharedRoomsSupport","mutualRoomsSupport","queryMutualRoomsSupport","rooms","tokenQuery","joined","next_batch_token","_this33","serverVersionsPromise","serverVersions","isVersionSupported","version","_this34","versions","feature","_this35","unstableFeatures","doesServerForceEncryptionForPreset","presetName","_this36","versionsPresetName","_this37","threadUnstable","threadStable","listUnstable","listStable","fwdPaginationUnstable","fwdPaginationStable","_unused","None","hasLazyLoadMembersEnabled","_this$clientOpts3","setCanResetTimelineCallback","cb","getCanResetTimelineCallback","relationType","_arguments6","_this38","_result$next_batch","_result$prev_batch","fetchedEventType","eventResult","Replace","prevBatch","generateClientSecret","decryptEventIfNeeded","termsUrlForService","serviceType","IS","getUrl","V2","IM","getHomeserverUrl","_this$idBaseUrl","_this$idBaseUrl2","stripProto","setIdentityServerUrl","setIdBaseUrl","getRefreshToken","_this$http$opts$refre","setAccessToken","isLoggedIn","txnCtr","isUsernameAvailable","username","available","register","password","auth","bindThreepids","guestAccessToken","inhibitLogin","session","refresh_token","guest_access_token","inhibit_login","registerRequest","registerGuest","kind","performRefreshRequestWithPrefix","inhibitLogoutEmit","loginFlows","login","loginType","access_token","loginWithPassword","getCasLoginUrl","redirectUrl","getSsoLoginUrl","idpId","href","loginWithToken","logout","_arguments7","_this39","abort","deactivateAccount","erase","requestLoginToken","_this40","getFallbackAuthUrl","authSessionId","$loginType","_this41","_this41$identityServe","invitesNeedingToken","invite_3pid","id_access_token","Experimental","queryString","encodeParams","templatedUrl","$relationType","members","includeMembership","excludeMembership","atEventId","not_membership","at","upgradeRoom","newVersion","new_version","roomInitialSync","_limit$toString","_this42","FullyRead","getJoinedRooms","getJoinedRoomMembers","publicRooms","_ref7","server","since","_objectWithoutProperties","_excluded","createAlias","alias","$alias","deleteAlias","getLocalAliases","getRoomIdForAlias","getRoomDirectoryVisibility","setRoomDirectoryVisibility","visibility","searchUserDirectory","_ref8","uploadContent","file","cancelUpload","upload","getCurrentUploads","getProfileInfo","doesServerSupportExtendedProfiles","_this43","getExtendedProfileRequestPrefix","_this44","getExtendedProfile","_this45","getExtendedProfileProperty","_this46","profile","$key","setExtendedProfileProperty","_this47","deleteExtendedProfileProperty","_this48","patchExtendedProfile","_this49","Patch","setExtendedProfile","_this50","getThreePids","addThreePidOnly","_this51","bindThreePid","_this52","unbindThreePid","_this53","deleteThreePid","setPassword","authDict","newPassword","logoutDevices","new_password","logout_devices","getDevices","getDevice","$device_id","setDeviceDetails","deleteDevice","deleteMultipleDevices","devices","getPushers","_this54","pushers","pusher","hasOwnProperty","setPusher","removePusher","pushKey","appId","pushkey","app_id","setLocalNotificationSettings","notificationSettings","rules","setPushRules","rewriteDefaultRules","updateCachedPushRuleKeys","ruleId","$kind","$ruleId","setPushRuleEnabled","enabled","setPushRuleActions","_ref9","getKeyChanges","oldToken","qps","to","registerWithIdentityServer","hsOpenIdToken","uri","requestEmailToken","idServerRequest","requestMsisdnToken","submitMsisdnToken","sid","msisdnToken","submitMsisdnTokenOtherUrl","getIdentityHashDetails","identityHashedLookup","addressPairs","_this55","hashes","localMapping","_ref10","p","addr","toLowerCase","med","hashBuffer","hashed","_x4","unhashed","foundAddresses","mxid","plainAddress","lookupThreePid","_this56","mapping","bulkLookupThreePids","_this57","v1results","_loop","originalQuery","threepids","getIdentityAccount","sendToDevice","contentMap","messages","recursiveMapToObject","targets","deviceMessages","queueToDevice","batch","queueBatch","getThirdpartyProtocols","getThirdpartyLocation","protocol","$protocol","getThirdpartyUser","getTerms","agreeToTerms","termsUrls","headers","Authorization","user_accepts","reportEvent","score","getRoomHierarchy","maxDepth","suggestedOnly","suggested_only","String","max_depth","unstableCreateFileTree","_this58","preset","PrivateChat","power_level_content_override","creation_content","Space","initial_state","state_key","unstableGetFileTreeSpace","_purposeEvent$getCont","_createEvent$getConte","getMyMembership","createEvent","RoomCreate","purposeEvent","req","proxyBaseUrl","pos","clientTimeout","_this$clientOpts4","threadSupport","supportsIntentionalMentions","IntentionalMentions","getRoomSummary","_this59","paramOpts","toStartOfTimeline","processThreadedEvents","processBeaconEvents","processPollEvents","whoami","_this60","timestampToEvent","timestamp","_this61","httpStatus","getAuthIssuer","_this62","fromEntries","_ref11","k","v","inMainTimelineForReceipt","threadRootId","isThreadRoot","isRelatedToRoot","relationEventId"],"sources":["../src/client.ts"],"sourcesContent":["/*\nCopyright 2015-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport { ISyncStateData, SetPresence, SyncApi, SyncApiOptions, SyncState } from \"./sync.ts\";\nimport {\n EventStatus,\n IContent,\n IDecryptOptions,\n IEvent,\n MatrixEvent,\n MatrixEventEvent,\n MatrixEventHandlerMap,\n PushDetails,\n} from \"./models/event.ts\";\nimport { StubStore } from \"./store/stub.ts\";\nimport { Filter, IFilterDefinition, IRoomEventFilter } from \"./filter.ts\";\nimport * as utils from \"./utils.ts\";\nimport { noUnsafeEventProps, QueryDict, replaceParam, sleep } from \"./utils.ts\";\nimport { Direction, EventTimeline } from \"./models/event-timeline.ts\";\nimport { IActionsObject, PushProcessor } from \"./pushprocessor.ts\";\nimport { AutoDiscovery, AutoDiscoveryAction } from \"./autodiscovery.ts\";\nimport { encodeUnpaddedBase64Url } from \"./base64.ts\";\nimport { TypedReEmitter } from \"./ReEmitter.ts\";\nimport { logger, Logger } from \"./logger.ts\";\nimport { SERVICE_TYPES } from \"./service-types.ts\";\nimport {\n Body,\n ClientPrefix,\n FileType,\n HttpApiEvent,\n HttpApiEventHandlerMap,\n IdentityPrefix,\n IHttpOpts,\n IRequestOpts,\n MatrixError,\n MatrixHttpApi,\n MediaPrefix,\n Method,\n retryNetworkOperation,\n TokenRefreshFunction,\n Upload,\n UploadOpts,\n UploadResponse,\n} from \"./http-api/index.ts\";\nimport { User, UserEvent, UserEventHandlerMap } from \"./models/user.ts\";\nimport { getHttpUriForMxc } from \"./content-repo.ts\";\nimport { SearchResult } from \"./models/search-result.ts\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider.ts\";\nimport { MatrixScheduler } from \"./scheduler.ts\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./models/beacon.ts\";\nimport { AuthDict } from \"./interactive-auth.ts\";\nimport { IMinimalEvent, IRoomEvent, IStateEvent } from \"./sync-accumulator.ts\";\nimport { EventTimelineSet } from \"./models/event-timeline-set.ts\";\nimport * as ContentHelpers from \"./content-helpers.ts\";\nimport { NotificationCountType, Room, RoomEvent, RoomEventHandlerMap, RoomNameState } from \"./models/room.ts\";\nimport { RoomMemberEvent, RoomMemberEventHandlerMap } from \"./models/room-member.ts\";\nimport { IPowerLevelsContent, RoomStateEvent, RoomStateEventHandlerMap } from \"./models/room-state.ts\";\nimport {\n DelayedEventInfo,\n IAddThreePidOnlyBody,\n IBindThreePidBody,\n IContextResponse,\n ICreateRoomOpts,\n IEventSearchOpts,\n IFilterResponse,\n IGuestAccessOpts,\n IJoinRoomOpts,\n INotificationsResponse,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRelationsRequestOpts,\n IRelationsResponse,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n IStatusResponse,\n ITagsResponse,\n KnockRoomOpts,\n SendDelayedEventRequestOpts,\n SendDelayedEventResponse,\n UpdateDelayedEventAction,\n} from \"./@types/requests.ts\";\nimport {\n EventType,\n LOCAL_NOTIFICATION_SETTINGS_PREFIX,\n MSC3912_RELATION_BASED_REDACTIONS_PROP,\n MsgType,\n PUSHER_ENABLED,\n RelationType,\n RoomCreateTypeField,\n RoomType,\n StateEvents,\n TimelineEvents,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n} from \"./@types/event.ts\";\nimport {\n GuestAccess,\n HistoryVisibility,\n IdServerUnbindResult,\n JoinRule,\n Preset,\n Visibility,\n} from \"./@types/partials.ts\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper.ts\";\nimport { randomString } from \"./randomstring.ts\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace.ts\";\nimport { ISignatures } from \"./@types/signed.ts\";\nimport { IStore } from \"./store/index.ts\";\nimport {\n IEventWithRoomId,\n ISearchRequestBody,\n ISearchResponse,\n ISearchResults,\n IStateEventWithRoomId,\n SearchOrderBy,\n} from \"./@types/search.ts\";\nimport { ISynapseAdminDeactivateResponse, ISynapseAdminWhoisResponse } from \"./@types/synapse.ts\";\nimport { IHierarchyRoom } from \"./@types/spaces.ts\";\nimport {\n IPusher,\n IPusherRequest,\n IPushRule,\n IPushRules,\n PushRuleAction,\n PushRuleActionName,\n PushRuleKind,\n RuleId,\n} from \"./@types/PushRules.ts\";\nimport { IThreepid } from \"./@types/threepids.ts\";\nimport {\n ILoginFlowsResponse,\n IRefreshTokenResponse,\n LoginRequest,\n LoginResponse,\n LoginTokenPostResponse,\n SSOAction,\n} from \"./@types/auth.ts\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter.ts\";\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"./@types/read_receipts.ts\";\nimport { MSC3575SlidingSyncRequest, MSC3575SlidingSyncResponse, SlidingSync } from \"./sliding-sync.ts\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk.ts\";\nimport {\n determineFeatureSupport,\n FeatureSupport,\n Thread,\n THREAD_RELATION_TYPE,\n ThreadFilterType,\n threadFilterTypeToFilter,\n} from \"./models/thread.ts\";\nimport { M_BEACON_INFO, MBeaconInfoEventContent } from \"./@types/beacon.ts\";\nimport { NamespacedValue, UnstableValue } from \"./NamespacedValue.ts\";\nimport { ToDeviceMessageQueue } from \"./ToDeviceMessageQueue.ts\";\nimport { ToDeviceBatch } from \"./models/ToDeviceMessage.ts\";\nimport { IgnoredInvites } from \"./models/invites-ignorer.ts\";\nimport { UIARequest, UIAResponse } from \"./@types/uia.ts\";\nimport { LocalNotificationSettings } from \"./@types/local_notifications.ts\";\nimport { buildFeatureSupportMap, Feature, ServerSupport } from \"./feature.ts\";\nimport { RegisterRequest, RegisterResponse } from \"./@types/registration.ts\";\nimport { getRelationsThreadFilter } from \"./thread-utils.ts\";\nimport { KnownMembership, Membership } from \"./@types/membership.ts\";\nimport { RoomMessageEventContent, StickerEventContent } from \"./@types/events.ts\";\nimport { ImageInfo } from \"./@types/media.ts\";\nimport { Capabilities, ServerCapabilities } from \"./serverCapabilities.ts\";\nimport { sha256 } from \"./digest.ts\";\n\nexport type Store = IStore;\n\nexport type ResetTimelineCallback = (roomId: string) => boolean;\n\nconst SCROLLBACK_DELAY_MS = 3000;\n\nexport const UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue(\n \"last_seen_user_agent\",\n \"org.matrix.msc3852.last_seen_user_agent\",\n);\n\ninterface IExportedDevice {\n userId: string;\n deviceId: string;\n}\n\nexport interface ICreateClientOpts {\n baseUrl: string;\n\n idBaseUrl?: string;\n\n /**\n * The data store used for sync data from the homeserver. If not specified,\n * this client will not store any HTTP responses. The `createClient` helper\n * will create a default store if needed.\n */\n store?: Store;\n\n /**\n * The scheduler to use. If not\n * specified, this client will not retry requests on failure. This client\n * will supply its own processing function to\n * {@link MatrixScheduler#setProcessFunction}.\n */\n scheduler?: MatrixScheduler;\n\n /**\n * The function to invoke for HTTP requests.\n * Most supported environments have a global `fetch` registered to which this will fall back.\n */\n fetchFn?: typeof globalThis.fetch;\n\n userId?: string;\n\n /**\n * A unique identifier for this device; used for tracking things like crypto\n * keys and access tokens. If not specified, end-to-end encryption will be\n * disabled.\n */\n deviceId?: string;\n\n accessToken?: string;\n refreshToken?: string;\n\n /**\n * Function used to attempt refreshing access and refresh tokens\n * Called by http-api when a possibly expired token is encountered\n * and a refreshToken is found\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Identity server provider to retrieve the user's access token when accessing\n * the identity server. See also https://github.com/vector-im/element-web/issues/10615\n * which seeks to replace the previous approach of manual access tokens params\n * with this callback throughout the SDK.\n */\n identityServer?: IIdentityServerProvider;\n\n /**\n * The default maximum amount of\n * time to wait before timing out HTTP requests. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n\n /**\n * Set to false to send the access token to the server via a query parameter rather\n * than the Authorization HTTP header.\n *\n * Note that as of v1.11 of the Matrix spec, sending the access token via a query\n * is deprecated.\n *\n * Default true.\n */\n useAuthorizationHeader?: boolean;\n\n /**\n * Set to true to enable\n * improved timeline support, see {@link MatrixClient#getEventTimeline}.\n * It is disabled by default for compatibility with older clients - in particular to\n * maintain support for back-paginating the live timeline after a '/sync'\n * result with a gap.\n */\n timelineSupport?: boolean;\n\n /**\n * Extra query parameters to append\n * to all requests with this client. Useful for application services which require\n * `?user_id=`.\n */\n queryParams?: Record<string, string>;\n\n /**\n * Device data exported with\n * \"exportDevice\" method that must be imported to recreate this device.\n * Should only be useful for devices with end-to-end crypto enabled.\n * If provided, deviceId and userId should **NOT** be provided at the top\n * level (they are present in the exported data).\n */\n deviceToImport?: IExportedDevice;\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in {@link ICreateClientOpts#cryptoStore}.\n *\n * This must be set to the same value every time the client is initialised for the same device.\n *\n * This is only used for the legacy crypto implementation (as used by {@link MatrixClient#initCrypto}),\n * but if you use the rust crypto implementation ({@link MatrixClient#initRustCrypto}) and the device\n * previously used legacy crypto (so must be migrated), then this must still be provided, so that the\n * data can be migrated from the legacy store.\n */\n pickleKey?: string;\n\n /**\n * Verification methods we should offer to the other side when performing an interactive verification.\n * If unset, we will offer all known methods. Currently these are: showing a QR code, scanning a QR code, and SAS\n * (aka \"emojis\").\n *\n * See {@link types.VerificationMethod} for a set of useful constants for this parameter.\n */\n verificationMethods?: Array<string>;\n\n /**\n * Up to this many ICE candidates will be gathered when an incoming call arrives.\n * Gathering does not send data to the caller, but will communicate with the configured TURN\n * server. Default 0.\n */\n iceCandidatePoolSize?: number;\n\n /**\n * Whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.\n */\n fallbackICEServerAllowed?: boolean;\n\n livekitServiceURL?: string;\n\n /**\n * Method to generate room names for empty rooms and rooms names based on membership.\n * Defaults to a built-in English handler with basic pluralisation.\n */\n roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null;\n\n /**\n * If true, participant can join group call without video and audio this has to be allowed. By default, a local\n * media stream is needed to establish a group call.\n * Default: false.\n */\n isVoipWithNoMediaAllowed?: boolean;\n\n /**\n * If true, group calls will not establish media connectivity and only create the signaling events,\n * so that livekit media can be used in the application layert (js-sdk contains no livekit code).\n */\n useLivekitForGroupCalls?: boolean;\n\n /**\n * A logger to associate with this MatrixClient.\n * Defaults to the built-in global logger.\n */\n logger?: Logger;\n}\n\nexport interface IMatrixClientCreateOpts extends ICreateClientOpts {\n /**\n * Whether to allow sending messages to encrypted rooms when encryption\n * is not available internally within this SDK. This is useful if you are using an external\n * E2E proxy, for example. Defaults to false.\n */\n usingExternalCrypto?: boolean;\n}\n\nexport enum PendingEventOrdering {\n Chronological = \"chronological\",\n Detached = \"detached\",\n}\n\nexport interface IStartClientOpts {\n /**\n * The event `limit=` to apply to initial sync. Default: 8.\n */\n initialSyncLimit?: number;\n\n /**\n * True to put `archived=true</code> on the <code>/initialSync` request. Default: false.\n */\n includeArchivedRooms?: boolean;\n\n /**\n * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false.\n */\n resolveInvitesToProfiles?: boolean;\n\n /**\n * Controls where pending messages appear in a room's timeline. If \"<b>chronological</b>\", messages will\n * appear in the timeline when the call to `sendEvent` was made. If \"<b>detached</b>\",\n * pending messages will appear in a separate list, accessbile via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n\n /**\n * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds).\n */\n pollTimeout?: number;\n\n /**\n * The filter to apply to /sync calls.\n */\n filter?: Filter;\n\n /**\n * True to perform syncing without automatically updating presence.\n */\n disablePresence?: boolean;\n\n /**\n * True to not load all membership events during initial sync but fetch them when needed by calling\n * `loadOutOfBandMembers` This will override the filter option at this moment.\n */\n lazyLoadMembers?: boolean;\n\n /**\n * The number of seconds between polls to /.well-known/matrix/client, undefined to disable.\n * This should be in the order of hours. Default: undefined.\n */\n clientWellKnownPollPeriod?: number;\n\n /**\n * Will organises events in threaded conversations when\n * a thread relation is encountered\n */\n threadSupport?: boolean;\n\n /**\n * @experimental\n */\n slidingSync?: SlidingSync;\n}\n\nexport interface IStoredClientOpts extends IStartClientOpts { }\n\nexport const GET_LOGIN_TOKEN_CAPABILITY = new NamespacedValue(\n \"m.get_login_token\",\n \"org.matrix.msc3882.get_login_token\",\n);\n\nexport const UNSTABLE_MSC2666_SHARED_ROOMS = \"uk.half-shot.msc2666\";\nexport const UNSTABLE_MSC2666_MUTUAL_ROOMS = \"uk.half-shot.msc2666.mutual_rooms\";\nexport const UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS = \"uk.half-shot.msc2666.query_mutual_rooms\";\n\nexport const UNSTABLE_MSC4140_DELAYED_EVENTS = \"org.matrix.msc4140\";\n\nexport const UNSTABLE_MSC4133_EXTENDED_PROFILES = \"uk.tcpip.msc4133\";\n\nexport type SendToDeviceContentMap = Map<string, Map<string, Record<string, any>>>;\n\nexport interface IUploadKeySignaturesResponse {\n failures: Record<\n string,\n Record<\n string,\n {\n errcode: string;\n error: string;\n }\n >\n >;\n}\n\nexport interface IPreviewUrlResponse {\n [key: string]: undefined | string | number;\n \"og:title\": string;\n \"og:type\": string;\n \"og:url\": string;\n \"og:image\"?: string;\n \"og:image:type\"?: string;\n \"og:image:height\"?: number;\n \"og:image:width\"?: number;\n \"og:description\"?: string;\n \"matrix:image:size\"?: number;\n}\n\nexport interface ITurnServerResponse {\n uris: string[];\n username: string;\n password: string;\n ttl: number;\n}\n\nexport interface ITurnServer {\n urls: string[];\n username: string;\n credential: string;\n}\n\nexport interface IServerVersions {\n versions: string[];\n unstable_features: Record<string, boolean>;\n}\n\nexport interface IClientWellKnown {\n [key: string]: any;\n \"m.homeserver\"?: IWellKnownConfig;\n \"m.identity_server\"?: IWellKnownConfig;\n}\n\nexport interface IWellKnownConfig<T = IClientWellKnown> {\n raw?: T;\n action?: AutoDiscoveryAction;\n reason?: string;\n error?: Error | string;\n // eslint-disable-next-line\n base_url?: string | null;\n // XXX: this is undocumented\n server_name?: string;\n}\n\ninterface IMediaConfig {\n [key: string]: any; // extensible\n \"m.upload.size\"?: number;\n}\n\ninterface IThirdPartySigned {\n sender: string;\n mxid: string;\n token: string;\n signatures: ISignatures;\n}\n\ninterface IJoinRequestBody {\n third_party_signed?: IThirdPartySigned;\n}\n\ninterface ITagMetadata {\n [key: string]: any;\n order?: number;\n}\n\ninterface IMessagesResponse {\n start?: string;\n end?: string;\n chunk: IRoomEvent[];\n state?: IStateEvent[];\n}\n\ninterface IThreadedMessagesResponse {\n prev_batch: string;\n next_batch: string;\n chunk: IRoomEvent[];\n state: IStateEvent[];\n}\n\nexport interface IRequestTokenResponse {\n sid: string;\n submit_url?: string;\n}\n\nexport interface IRequestMsisdnTokenResponse extends IRequestTokenResponse {\n msisdn: string;\n success: boolean;\n intl_fmt: string;\n}\n\nexport interface IQueryKeysRequest {\n device_keys: { [userId: string]: string[] };\n timeout?: number;\n token?: string;\n}\n\nexport interface IClaimKeysRequest {\n one_time_keys: { [userId: string]: { [deviceId: string]: string } };\n timeout?: number;\n}\n\nexport interface IOpenIDToken {\n access_token: string;\n token_type: \"Bearer\" | string;\n matrix_server_name: string;\n expires_in: number;\n}\n\ninterface IRoomInitialSyncResponse {\n room_id: string;\n membership: Membership;\n messages?: {\n start?: string;\n end?: string;\n chunk: IEventWithRoomId[];\n };\n state?: IStateEventWithRoomId[];\n visibility: Visibility;\n account_data?: IMinimalEvent[];\n presence: Partial<IEvent>; // legacy and undocumented, api is deprecated so this won't get attention\n}\n\ninterface IJoinedRoomsResponse {\n joined_rooms: string[];\n}\n\ninterface IJoinedMembersResponse {\n joined: {\n [userId: string]: {\n display_name: string;\n avatar_url: string;\n };\n };\n}\n\n// Re-export for backwards compatibility\nexport type IRegisterRequestParams = RegisterRequest;\n\nexport interface IPublicRoomsChunkRoom {\n room_id: string;\n name?: string;\n avatar_url?: string;\n topic?: string;\n canonical_alias?: string;\n aliases?: string[];\n world_readable: boolean;\n guest_can_join: boolean;\n num_joined_members: number;\n room_type?: RoomType | string; // Added by MSC3827\n join_rule?: JoinRule.Knock | JoinRule.Public; // Added by MSC2403\n}\n\ninterface IPublicRoomsResponse {\n chunk: IPublicRoomsChunkRoom[];\n next_batch?: string;\n prev_batch?: string;\n total_room_count_estimate?: number;\n}\n\ninterface IUserDirectoryResponse {\n results: {\n user_id: string;\n display_name?: string;\n avatar_url?: string;\n }[];\n limited: boolean;\n}\n\nexport interface IMyDevice {\n \"device_id\": string;\n \"display_name\"?: string;\n \"last_seen_ip\"?: string;\n \"last_seen_ts\"?: number;\n // UNSTABLE_MSC3852_LAST_SEEN_UA\n \"last_seen_user_agent\"?: string;\n \"org.matrix.msc3852.last_seen_user_agent\"?: string;\n}\n\nexport interface Keys {\n keys: { [keyId: string]: string };\n usage: string[];\n user_id: string;\n}\n\nexport interface IClaimOTKsResult {\n failures: { [serverName: string]: object };\n one_time_keys: {\n [userId: string]: {\n [deviceId: string]: {\n [keyId: string]: {\n key: string;\n signatures: ISignatures;\n };\n };\n };\n };\n}\n\nexport interface IFieldType {\n regexp: string;\n placeholder: string;\n}\n\nexport interface IInstance {\n desc: string;\n icon?: string;\n fields: object;\n network_id: string;\n // XXX: this is undocumented but we rely on it: https://github.com/matrix-org/matrix-doc/issues/3203\n instance_id: string;\n}\n\nexport interface IProtocol {\n user_fields: string[];\n location_fields: string[];\n icon: string;\n field_types: Record<string, IFieldType>;\n instances: IInstance[];\n}\n\ninterface IThirdPartyLocation {\n alias: string;\n protocol: string;\n fields: object;\n}\n\ninterface IThirdPartyUser {\n userid: string;\n protocol: string;\n fields: object;\n}\n\n/**\n * The summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n */\nexport interface RoomSummary extends Omit<IPublicRoomsChunkRoom, \"canonical_alias\" | \"aliases\"> {\n /**\n * The current membership of this user in the room.\n * Usually \"leave\" if the room is fetched over federation.\n */\n \"membership\"?: Membership;\n /**\n * Version of the room.\n */\n \"im.nheko.summary.room_version\"?: string;\n /**\n * The encryption algorithm used for this room, if the room is encrypted.\n */\n \"im.nheko.summary.encryption\"?: string;\n}\n\ninterface IRoomHierarchy {\n rooms: IHierarchyRoom[];\n next_batch?: string;\n}\n\nexport interface TimestampToEventResponse {\n event_id: string;\n origin_server_ts: number;\n}\n\ninterface IWhoamiResponse {\n user_id: string;\n device_id?: string;\n is_guest?: boolean;\n}\n/* eslint-enable camelcase */\n\n// We're using this constant for methods overloading and inspect whether a variable\n// contains an eventId or not. This was required to ensure backwards compatibility\n// of methods for threads\n// Probably not the most graceful solution but does a good enough job for now\nconst EVENT_ID_PREFIX = \"$\";\n\nexport enum ClientEvent {\n Sync = \"sync\",\n Event = \"event\",\n ToDeviceEvent = \"toDeviceEvent\",\n AccountData = \"accountData\",\n Room = \"Room\",\n DeleteRoom = \"deleteRoom\",\n SyncUnexpectedError = \"sync.unexpectedError\",\n ClientWellKnown = \"WellKnown.client\",\n ReceivedVoipEvent = \"received_voip_event\",\n UndecryptableToDeviceEvent = \"toDeviceEvent.undecryptable\",\n TurnServers = \"turnServers\",\n TurnServersError = \"turnServers.error\",\n}\n\ntype RoomEvents =\n | RoomEvent.Name\n | RoomEvent.Redaction\n | RoomEvent.RedactionCancelled\n | RoomEvent.Receipt\n | RoomEvent.Tags\n | RoomEvent.LocalEchoUpdated\n | RoomEvent.HistoryImportedWithinTimeline\n | RoomEvent.AccountData\n | RoomEvent.MyMembership\n | RoomEvent.Timeline\n | RoomEvent.TimelineReset;\n\ntype RoomStateEvents =\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker;\n\ntype MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange;\n\ntype RoomMemberEvents =\n | RoomMemberEvent.Name\n | RoomMemberEvent.Typing\n | RoomMemberEvent.PowerLevel\n | RoomMemberEvent.Membership;\n\ntype UserEvents =\n | UserEvent.AvatarUrl\n | UserEvent.DisplayName\n | UserEvent.Presence\n | UserEvent.CurrentlyActive\n | UserEvent.LastPresenceTs;\n\nexport type EmittedEvents =\n | ClientEvent\n | RoomEvents\n | RoomStateEvents\n | MatrixEventEvents\n | RoomMemberEvents\n | UserEvents\n | HttpApiEvent.SessionLoggedOut\n | HttpApiEvent.NoConsent\n | BeaconEvent;\n\nexport type ClientEventHandlerMap = {\n /**\n * Fires whenever the SDK's syncing state is updated. The state can be one of:\n * <ul>\n *\n * <li>PREPARED: The client has synced with the server at least once and is\n * ready for methods to be called on it. This will be immediately followed by\n * a state of SYNCING. <i>This is the equivalent of \"syncComplete\" in the\n * previous API.</i></li>\n *\n * <li>CATCHUP: The client has detected the connection to the server might be\n * available again and will now try to do a sync again. As this sync might take\n * a long time (depending how long ago was last synced, and general server\n * performance) the client is put in this mode so the UI can reflect trying\n * to catch up with the server after losing connection.</li>\n *\n * <li>SYNCING : The client is currently polling for new events from the server.\n * This will be called <i>after</i> processing latest events from a sync.</li>\n *\n * <li>ERROR : The client has had a problem syncing with the server. If this is\n * called <i>before</i> PREPARED then there was a problem performing the initial\n * sync. If this is called <i>after</i> PREPARED then there was a problem polling\n * the server for updates. This may be called multiple times even if the state is\n * already ERROR. <i>This is the equivalent of \"syncError\" in the previous\n * API.</i></li>\n *\n * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that\n * should be considered erroneous.\n * </li>\n *\n * <li>STOPPED: The client has stopped syncing with server due to stopClient\n * being called.\n * </li>\n * </ul>\n * State transition diagram:\n * ```\n * +---->STOPPED\n * |\n * +----->PREPARED -------> SYNCING <--+\n * | ^ | ^ |\n * | CATCHUP ----------+ | | |\n * | ^ V | |\n * null ------+ | +------- RECONNECTING |\n * | V V |\n * +------->ERROR ---------------------+\n *\n * NB: 'null' will never be emitted by this event.\n *\n * ```\n * Transitions:\n * <ul>\n *\n * <li>`null -> PREPARED` : Occurs when the initial sync is completed\n * first time. This involves setting up filters and obtaining push rules.\n *\n * <li>`null -> ERROR` : Occurs when the initial sync failed first time.\n *\n * <li>`ERROR -> PREPARED` : Occurs when the initial sync succeeds\n * after previously failing.\n *\n * <li>`PREPARED -> SYNCING` : Occurs immediately after transitioning\n * to PREPARED. Starts listening for live updates rather than catching up.\n *\n * <li>`SYNCING -> RECONNECTING` : Occurs when the live update fails.\n *\n * <li>`RECONNECTING -> RECONNECTING` : Can occur if the update calls\n * continue to fail, but the keepalive calls (to /versions) succeed.\n *\n * <li>`RECONNECTING -> ERROR` : Occurs when the keepalive call also fails\n *\n * <li>`ERROR -> SYNCING` : Occurs when the client has performed a\n * live update after having previously failed.\n *\n * <li>`ERROR -> ERROR` : Occurs when the client has failed to keepalive\n * for a second time or more.</li>\n *\n * <li>`SYNCING -> SYNCING` : Occurs when the client has performed a live\n * update. This is called <i>after</i> processing.</li>\n *\n * <li>`* -> STOPPED` : Occurs once the client has stopped syncing or\n * trying to sync after stopClient has been called.</li>\n * </ul>\n *\n * @param state - An enum representing the syncing state. One of \"PREPARED\",\n * \"SYNCING\", \"ERROR\", \"STOPPED\".\n *\n * @param prevState - An enum representing the previous syncing state.\n * One of \"PREPARED\", \"SYNCING\", \"ERROR\", \"STOPPED\" <b>or null</b>.\n *\n * @param data - Data about this transition.\n *\n * @example\n * ```\n * matrixClient.on(\"sync\", function(state, prevState, data) {\n * switch (state) {\n * case \"ERROR\":\n * // update UI to say \"Connection Lost\"\n * break;\n * case \"SYNCING\":\n * // update UI to remove any \"Connection Lost\" message\n * break;\n * case \"PREPARED\":\n * // the client instance is ready to be queried.\n * var rooms = matrixClient.getRooms();\n * break;\n * }\n * });\n * ```\n */\n [ClientEvent.Sync]: (state: SyncState, prevState: SyncState | null, data?: ISyncStateData) => void;\n /**\n * Fires whenever the SDK receives a new event.\n * <p>\n * This is only fired for live events received via /sync - it is not fired for\n * events received over context, search, or pagination APIs.\n *\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"event\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.Event]: (event: MatrixEvent) => void;\n /**\n * Fires whenever the SDK receives a new to-device event.\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"toDeviceEvent\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.ToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires if a to-device event is received that cannot be decrypted.\n * Encrypted to-device events will (generally) use plain Olm encryption,\n * in which case decryption failures are fatal: the event will never be\n * decryptable, unlike Megolm encrypted events where the key may simply\n * arrive later.\n *\n * An undecryptable to-device event is therefore likley to indicate problems.\n *\n * @param event - The undecyptable to-device event\n */\n [ClientEvent.UndecryptableToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires whenever new user-scoped account_data is added.\n * @param event - The event describing the account_data just added\n * @param event - The previous account data, if known.\n * @example\n * ```\n * matrixClient.on(\"accountData\", function(event, oldEvent){\n * myAccountData[event.type] = event.content;\n * });\n * ```\n */\n [ClientEvent.AccountData]: (event: MatrixEvent, lastEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a new Room is added. This will fire when you are invited to a\n * room, as well as when you join a room. <strong>This event is experimental and\n * may change.</strong>\n * @param room - The newly created, fully populated room.\n * @example\n * ```\n * matrixClient.on(\"Room\", function(room){\n * var roomId = room.roomId;\n * });\n * ```\n */\n [ClientEvent.Room]: (room: Room) => void;\n /**\n * Fires whenever a Room is removed. This will fire when you forget a room.\n * <strong>This event is experimental and may change.</strong>\n * @param roomId - The deleted room ID.\n * @example\n * ```\n * matrixClient.on(\"deleteRoom\", function(roomId){\n * // update UI from getRooms()\n * });\n * ```\n */\n [ClientEvent.DeleteRoom]: (roomId: string) => void;\n [ClientEvent.SyncUnexpectedError]: (error: Error) => void;\n /**\n * Fires when the client .well-known info is fetched.\n *\n * @param data - The JSON object returned by the server\n */\n [ClientEvent.ClientWellKnown]: (data: IClientWellKnown) => void;\n [ClientEvent.ReceivedVoipEvent]: (event: MatrixEvent) => void;\n [ClientEvent.TurnServers]: (servers: ITurnServer[]) => void;\n [ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void;\n} & RoomEventHandlerMap &\n RoomStateEventHandlerMap &\n MatrixEventHandlerMap &\n RoomMemberEventHandlerMap &\n UserEventHandlerMap &\n HttpApiEventHandlerMap &\n BeaconEventHandlerMap;\n\nconst SSO_ACTION_PARAM = new UnstableValue(\"action\", \"org.matrix.msc3824.action\");\n\n/**\n * Represents a Matrix Client. Only directly construct this if you want to use\n * custom modules. Normally, {@link createClient} should be used\n * as it specifies 'sensible' defaults for these modules.\n */\nexport class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHandlerMap> {\n public static readonly RESTORE_BACKUP_ERROR_BAD_KEY = \"RESTORE_BACKUP_ERROR_BAD_KEY\";\n\n private readonly logger: Logger;\n\n public reEmitter = new TypedReEmitter<EmittedEvents, ClientEventHandlerMap>(this);\n public olmVersion: [number, number, number] | null = null; // populated after initCrypto\n public usingExternalCrypto = false;\n private _store!: Store;\n public deviceId: string | null;\n public credentials: { userId: string | null };\n\n /**\n * Encryption key used for encrypting sensitive data (such as e2ee keys) in storage.\n *\n * As supplied in the constructor via {@link IMatrixClientCreateOpts#pickleKey}.\n *\n * If unset, either a hardcoded key or no encryption at all is used, depending on the Crypto implementation.\n *\n * @deprecated this should be a private property.\n */\n public pickleKey?: string;\n\n public scheduler?: MatrixScheduler;\n public clientRunning = false;\n public timelineSupport = false;\n public urlPreviewCache: { [key: string]: Promise<IPreviewUrlResponse> } = {};\n public identityServer?: IIdentityServerProvider;\n public http: MatrixHttpApi<IHttpOpts & { onlyData: true }>; // XXX: Intended private, used in code.\n\n public iceCandidatePoolSize = 0; // XXX: Intended private, used in code.\n public idBaseUrl?: string;\n public baseUrl: string;\n public readonly isVoipWithNoMediaAllowed;\n\n public useLivekitForGroupCalls: boolean;\n\n // Note: these are all `protected` to let downstream consumers make mistakes if they want to.\n // We don't technically support this usage, but have reasons to do this.\n\n protected peekSync: SyncApi | null = null;\n protected isGuestAccount = false;\n protected ongoingScrollbacks: { [roomId: string]: { promise?: Promise<Room>; errorTs?: number } } = {};\n protected notifTimelineSet: EventTimelineSet | null = null;\n /* @deprecated */\n protected verificationMethods?: string[];\n protected fallbackICEServerAllowed = false;\n protected syncApi?: SlidingSyncSdk | SyncApi;\n public roomNameGenerator?: ICreateClientOpts[\"roomNameGenerator\"];\n public pushRules?: IPushRules;\n protected syncLeftRoomsPromise?: Promise<Room[]>;\n protected syncedLeftRooms = false;\n protected clientOpts?: IStoredClientOpts;\n protected clientWellKnownIntervalID?: ReturnType<typeof setInterval>;\n protected canResetTimelineCallback?: ResetTimelineCallback;\n\n public canSupport = new Map<Feature, ServerSupport>();\n\n // The pushprocessor caches useful things, so keep one and re-use it\n protected pushProcessor = new PushProcessor(this);\n\n // Promise to a response of the server's /versions response\n // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020\n protected serverVersionsPromise?: Promise<IServerVersions>;\n\n protected clientWellKnown?: IClientWellKnown;\n protected clientWellKnownPromise?: Promise<IClientWellKnown>;\n protected txnCtr = 0;\n protected sessionId: string;\n\n /** IDs of events which are currently being encrypted.\n *\n * This is part of the cancellation mechanism: if the event is no longer listed here when encryption completes,\n * that tells us that it has been cancelled, and we should not send it.\n */\n private eventsBeingEncrypted = new Set<string>();\n\n private toDeviceMessageQueue: ToDeviceMessageQueue;\n public livekitServiceURL?: string;\n\n // A manager for determining which invites should be ignored.\n public readonly ignoredInvites: IgnoredInvites;\n\n private serverCapabilitiesService: ServerCapabilities;\n\n public constructor(opts: IMatrixClientCreateOpts) {\n super();\n\n // If a custom logger is provided, use it. Otherwise, default to the global\n // one in logger.ts.\n this.logger = opts.logger ?? logger;\n\n opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);\n opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);\n\n this.baseUrl = opts.baseUrl;\n this.idBaseUrl = opts.idBaseUrl;\n this.identityServer = opts.identityServer;\n\n this.usingExternalCrypto = opts.usingExternalCrypto ?? false;\n this.store = opts.store || new StubStore();\n this.deviceId = opts.deviceId || null;\n this.sessionId = randomString(10);\n\n const userId = opts.userId || null;\n this.credentials = { userId };\n\n this.http = new MatrixHttpApi(this as ConstructorParameters<typeof MatrixHttpApi>[0], {\n fetchFn: opts.fetchFn,\n baseUrl: opts.baseUrl,\n idBaseUrl: opts.idBaseUrl,\n accessToken: opts.accessToken,\n refreshToken: opts.refreshToken,\n tokenRefreshFunction: opts.tokenRefreshFunction,\n prefix: ClientPrefix.V3,\n onlyData: true,\n extraParams: opts.queryParams,\n localTimeoutMs: opts.localTimeoutMs,\n useAuthorizationHeader: opts.useAuthorizationHeader,\n logger: this.logger,\n });\n\n if (opts.deviceToImport) {\n if (this.deviceId) {\n this.logger.warn(\n \"not importing device because device ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (this.credentials.userId) {\n this.logger.warn(\n \"not importing device because user ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (!opts.deviceToImport.deviceId) {\n this.logger.warn(\"not importing device because no device ID in exported data\");\n } else {\n this.deviceId = opts.deviceToImport.deviceId;\n this.credentials.userId = opts.deviceToImport.userId;\n }\n } else if (opts.pickleKey) {\n this.pickleKey = opts.pickleKey;\n }\n\n this.useLivekitForGroupCalls = Boolean(opts.useLivekitForGroupCalls);\n\n this.scheduler = opts.scheduler;\n if (this.scheduler) {\n this.scheduler.setProcessFunction(async (eventToSend: MatrixEvent) => {\n const room = this.getRoom(eventToSend.getRoomId());\n if (eventToSend.status !== EventStatus.SENDING) {\n this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);\n }\n const res = await this.sendEventHttpRequest(eventToSend);\n if (room) {\n // ensure we update pending event before the next scheduler run so that any listeners to event id\n // updates on the synchronous event emitter get a chance to run first.\n room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);\n }\n return res;\n });\n }\n\n this.serverCapabilitiesService = new ServerCapabilities(this.http);\n\n this.on(ClientEvent.Sync, this.fixupRoomNotifications);\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n\n this.verificationMethods = opts.verificationMethods;\n\n this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;\n this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;\n this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false;\n\n this.livekitServiceURL = opts.livekitServiceURL;\n\n this.roomNameGenerator = opts.roomNameGenerator;\n\n this.toDeviceMessageQueue = new ToDeviceMessageQueue(this);\n\n this.ignoredInvites = new IgnoredInvites(this);\n\n // having lots of event listeners is not unusual. 0 means \"unlimited\".\n this.setMaxListeners(0);\n }\n\n public set store(newStore: Store) {\n this._store = newStore;\n this._store.setUserCreator((userId) => User.createUser(userId, this));\n }\n\n public get store(): Store {\n return this._store;\n }\n\n /**\n * High level helper method to begin syncing and poll for new events. To listen for these\n * events, add a listener for {@link ClientEvent.Event}\n * via {@link MatrixClient#on}. Alternatively, listen for specific\n * state change events.\n * @param opts - Options to apply when syncing.\n */\n public async startClient(opts?: IStartClientOpts): Promise<void> {\n if (this.clientRunning) {\n // client is already running.\n return;\n }\n this.clientRunning = true;\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n if (this.syncApi) {\n // This shouldn't happen since we thought the client was not running\n this.logger.error(\"Still have sync object whilst not running: stopping old one\");\n this.syncApi.stop();\n }\n\n try {\n await this.getVersions();\n\n // This should be done with `canSupport`\n // TODO: https://github.com/vector-im/element-web/issues/23643\n const { threads, list, fwdPagination } = await this.doesServerSupportThread();\n Thread.setServerSideSupport(threads);\n Thread.setServerSideListSupport(list);\n Thread.setServerSideFwdPaginationSupport(fwdPagination);\n } catch (e) {\n this.logger.error(\n \"Can't fetch server versions, continuing to initialise sync, this will be retried later\",\n e,\n );\n }\n\n this.clientOpts = opts ?? {};\n if (this.clientOpts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(\n this.clientOpts.slidingSync,\n this,\n this.clientOpts,\n );\n } else {\n this.syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n }\n\n this.syncApi.sync().catch((e) => this.logger.info(\"Sync startup aborted with an error:\", e));\n\n if (this.clientOpts.clientWellKnownPollPeriod !== undefined) {\n this.clientWellKnownIntervalID = setInterval(() => {\n this.fetchClientWellKnown();\n }, 1000 * this.clientOpts.clientWellKnownPollPeriod);\n this.fetchClientWellKnown();\n }\n\n this.toDeviceMessageQueue.start();\n this.serverCapabilitiesService.start();\n }\n\n /**\n * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor\n */\n protected buildSyncApiOptions(): SyncApiOptions {\n return {\n canResetEntireTimeline: (roomId: string): boolean => {\n if (!this.canResetTimelineCallback) {\n return false;\n }\n return this.canResetTimelineCallback(roomId);\n },\n };\n }\n\n /**\n * High level helper method to stop the client from polling and allow a\n * clean shutdown.\n */\n public stopClient(): void {\n if (!this.clientRunning) return; // already stopped\n\n this.logger.debug(\"stopping MatrixClient\");\n\n this.clientRunning = false;\n\n this.syncApi?.stop();\n this.syncApi = undefined;\n\n this.peekSync?.stopPeeking();\n\n if (this.clientWellKnownIntervalID !== undefined) {\n globalThis.clearInterval(this.clientWellKnownIntervalID);\n }\n\n this.toDeviceMessageQueue.stop();\n\n this.serverCapabilitiesService.stop();\n }\n\n /**\n * Clear any data out of the persistent stores used by the client.\n *\n * @returns Promise which resolves when the stores have been cleared.\n */\n public clearStores(): Promise<void> {\n if (this.clientRunning) {\n throw new Error(\"Cannot clear stores while client is running\");\n }\n\n const promises: Promise<void>[] = [];\n\n promises.push(this.store.deleteAllData());\n\n return Promise.all(promises).then(); // .then to fix types\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user, or null if not logged in\n */\n public getUserId(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId;\n }\n return null;\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user\n * @throws Error if not logged in\n */\n public getSafeUserId(): string {\n const userId = this.getUserId();\n if (!userId) {\n throw new Error(\"Expected logged in user but found none.\");\n }\n return userId;\n }\n\n /**\n * Get the domain for this client's MXID\n * @returns Domain of this MXID\n */\n public getDomain(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.replace(/^.*?:/, \"\");\n }\n return null;\n }\n\n /**\n * Get the local part of the current user ID e.g. \"foo\" in \"\\@foo:bar\".\n * @returns The user ID localpart or null.\n */\n public getUserIdLocalpart(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.split(\":\")[0].substring(1);\n }\n return null;\n }\n\n /**\n * Get the device ID of this client\n * @returns device ID\n */\n public getDeviceId(): string | null {\n return this.deviceId;\n }\n\n /**\n * Get the session ID of this client\n * @returns session ID\n */\n public getSessionId(): string {\n return this.sessionId;\n }\n\n public getLivekitServiceURL(): string | undefined {\n return this.livekitServiceURL;\n }\n\n // This shouldn't need to exist, but the widget API has startup ordering problems that\n // mean it doesn't know the livekit URL fast enough: remove this once this is fixed.\n public setLivekitServiceURL(newURL: string): void {\n this.livekitServiceURL = newURL;\n }\n\n /**\n * Get the current sync state.\n * @returns the sync state, which may be null.\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncApi?.getSyncState() ?? null;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n if (!this.syncApi) {\n return null;\n }\n return this.syncApi.getSyncStateData();\n }\n\n /**\n * Whether the initial sync has completed.\n * @returns True if at least one sync has happened.\n */\n public isInitialSyncComplete(): boolean {\n const state = this.getSyncState();\n if (!state) {\n return false;\n }\n return state === SyncState.Prepared || state === SyncState.Syncing;\n }\n\n /**\n * Return whether the client is configured for a guest account.\n * @returns True if this is a guest access_token (or no token is supplied).\n */\n public isGuest(): boolean {\n return this.isGuestAccount;\n }\n\n /**\n * Set whether this client is a guest account. <b>This method is experimental\n * and may change without warning.</b>\n * @param guest - True if this is a guest account.\n * @experimental if the token is a macaroon, it should be encoded in it that it is a 'guest'\n * access token, which means that the SDK can determine this entirely without\n * the dev manually flipping this flag.\n */\n public setGuest(guest: boolean): void {\n this.isGuestAccount = guest;\n }\n\n /**\n * Return the provided scheduler, if any.\n * @returns The scheduler or undefined\n */\n public getScheduler(): MatrixScheduler | undefined {\n return this.scheduler;\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * Will also retry any outbound to-device messages currently in the queue to be sent\n * (retries of regular outgoing events are handled separately, per-event).\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n // don't await for this promise: we just want to kick it off\n this.toDeviceMessageQueue.sendQueue();\n return this.syncApi?.retryImmediately() ?? false;\n }\n\n /**\n * Return the global notification EventTimelineSet, if any\n *\n * @returns the globl notification EventTimelineSet\n */\n public getNotifTimelineSet(): EventTimelineSet | null {\n return this.notifTimelineSet;\n }\n\n /**\n * Set the global notification EventTimelineSet\n *\n */\n public setNotifTimelineSet(set: EventTimelineSet): void {\n this.notifTimelineSet = set;\n }\n\n /**\n * Gets the cached capabilities of the homeserver, returning cached ones if available.\n * If there are no cached capabilities and none can be fetched, throw an exception.\n *\n * @returns Promise resolving with The capabilities of the homeserver\n */\n public async getCapabilities(): Promise<Capabilities> {\n const caps = this.serverCapabilitiesService.getCachedCapabilities();\n if (caps) return caps;\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * Gets the cached capabilities of the homeserver. If none have been fetched yet,\n * return undefined.\n *\n * @returns The capabilities of the homeserver\n */\n public getCachedCapabilities(): Capabilities | undefined {\n return this.serverCapabilitiesService.getCachedCapabilities();\n }\n\n /**\n * Fetches the latest capabilities from the homeserver, ignoring any cached\n * versions. The newly returned version is cached.\n *\n * @returns A promise which resolves to the capabilities of the homeserver\n */\n public fetchCapabilities(): Promise<Capabilities> {\n return this.serverCapabilitiesService.fetchCapabilities();\n }\n\n /**\n * @deprecated Does nothing.\n */\n public async uploadKeys(): Promise<void> {\n this.logger.warn(\"MatrixClient.uploadKeys is deprecated\");\n }\n\n /**\n * Get the config for the media repository.\n * @returns Promise which resolves with an object containing the config.\n */\n public getMediaConfig(): Promise<IMediaConfig> {\n return this.http.authedRequest(Method.Get, \"/config\", undefined, undefined, {\n prefix: MediaPrefix.V3,\n });\n }\n\n /**\n * Get the room for the given room ID.\n * This function will return a valid room for any room for which a Room event\n * has been emitted. Note in particular that other events, eg. RoomState.members\n * will be emitted for a room before this function will return the given room.\n * @param roomId - The room ID\n * @returns The Room or null if it doesn't exist or there is no data store.\n */\n public getRoom(roomId: string | undefined): Room | null {\n if (!roomId) {\n return null;\n }\n return this.store.getRoom(roomId);\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getRooms(): Room[] {\n return this.store.getRooms();\n }\n\n /**\n * Retrieve all rooms that should be displayed to the user\n * This is essentially getRooms() with some rooms filtered out, eg. old versions\n * of rooms that have been replaced or (in future) other rooms that have been\n * marked at the protocol level as not to be displayed to the user.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and\n * use it if found (MSC3946).\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getVisibleRooms(msc3946ProcessDynamicPredecessor = false): Room[] {\n const allRooms = this.store.getRooms();\n\n const replacedRooms = new Set();\n for (const r of allRooms) {\n const predecessor = r.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (predecessor) {\n replacedRooms.add(predecessor);\n }\n }\n\n return allRooms.filter((r) => {\n const tombstone = r.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (tombstone && replacedRooms.has(r.roomId)) {\n return false;\n }\n return true;\n });\n }\n\n /**\n * Retrieve a user.\n * @param userId - The user ID to retrieve.\n * @returns A user or null if there is no data store or the user does\n * not exist.\n */\n public getUser(userId: string): User | null {\n return this.store.getUser(userId);\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, or an empty list if there is no data store.\n */\n public getUsers(): User[] {\n return this.store.getUsers();\n }\n\n /**\n * Set account data event for the current user.\n * It will retry the request up to 5 times.\n * @param eventType - The event type\n * @param content - the contents object for the event\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setAccountData(eventType: EventType | string, content: IContent): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n return retryNetworkOperation(5, () => {\n return this.http.authedRequest(Method.Put, path, undefined, content);\n });\n }\n\n /**\n * Get account data event of given type for the current user.\n * @param eventType - The event type\n * @returns The contents of the given account data event\n */\n public getAccountData(eventType: string): MatrixEvent | undefined {\n return this.store.getAccountData(eventType);\n }\n\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n * @param eventType - The event type\n * @returns Promise which resolves: The contents of the given account data event.\n * @returns Rejects: with an error response.\n */\n public async getAccountDataFromServer<T extends { [k: string]: any }>(eventType: string): Promise<T | null> {\n if (this.isInitialSyncComplete()) {\n const event = this.store.getAccountData(eventType);\n if (!event) {\n return null;\n }\n // The network version below returns just the content, so this branch\n // does the same to match.\n return event.getContent<T>();\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n try {\n return await this.http.authedRequest(Method.Get, path);\n } catch (e) {\n if ((<MatrixError>e).data?.errcode === \"M_NOT_FOUND\") {\n return null;\n }\n throw e;\n }\n }\n\n public async deleteAccountData(eventType: string): Promise<void> {\n const msc3391DeleteAccountDataServerSupport = this.canSupport.get(Feature.AccountDataDeletion);\n // if deletion is not supported overwrite with empty content\n if (msc3391DeleteAccountDataServerSupport === ServerSupport.Unsupported) {\n await this.setAccountData(eventType, {});\n return;\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.getSafeUserId(),\n $type: eventType,\n });\n const options =\n msc3391DeleteAccountDataServerSupport === ServerSupport.Unstable\n ? { prefix: \"/_matrix/client/unstable/org.matrix.msc3391\" }\n : undefined;\n return await this.http.authedRequest(Method.Delete, path, undefined, undefined, options);\n }\n\n /**\n * Gets the users that are ignored by this client\n * @returns The array of users that are ignored (empty if none)\n */\n public getIgnoredUsers(): string[] {\n const event = this.getAccountData(\"m.ignored_user_list\");\n if (!event || !event.getContent() || !event.getContent()[\"ignored_users\"]) return [];\n return Object.keys(event.getContent()[\"ignored_users\"]);\n }\n\n /**\n * Sets the users that the current user should ignore.\n * @param userIds - the user IDs to ignore\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setIgnoredUsers(userIds: string[]): Promise<{}> {\n const content = { ignored_users: {} as Record<string, object> };\n userIds.forEach((u) => {\n content.ignored_users[u] = {};\n });\n return this.setAccountData(\"m.ignored_user_list\", content);\n }\n\n /**\n * Gets whether or not a specific user is being ignored by this client.\n * @param userId - the user ID to check\n * @returns true if the user is ignored, false otherwise\n */\n public isUserIgnored(userId: string): boolean {\n return this.getIgnoredUsers().includes(userId);\n }\n\n /**\n * Join a room. If you have already joined the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to join.\n * @param opts - Options when joining the room.\n * @returns Promise which resolves: Room object.\n * @returns Rejects: with an error response.\n */\n public async joinRoom(roomIdOrAlias: string, opts: IJoinRoomOpts = {}): Promise<Room> {\n if (opts.syncRoom === undefined) {\n opts.syncRoom = true;\n }\n\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return room;\n\n let signPromise: Promise<IThirdPartySigned | void> = Promise.resolve();\n\n if (opts.inviteSignUrl) {\n const url = new URL(opts.inviteSignUrl);\n url.searchParams.set(\"mxid\", this.credentials.userId!);\n signPromise = this.http.requestOtherUrl<IThirdPartySigned>(Method.Post, url);\n }\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const data: IJoinRequestBody = {};\n const signedInviteObj = await signPromise;\n if (signedInviteObj) {\n data.third_party_signed = signedInviteObj;\n }\n\n const path = utils.encodeUri(\"/join/$roomid\", { $roomid: roomIdOrAlias });\n const res = await this.http.authedRequest<{ room_id: string }>(Method.Post, path, queryParams, data);\n\n const roomId = res.room_id;\n // In case we were originally given an alias, check the room cache again\n // with the resolved ID - this method is supposed to no-op if we already\n // were in the room, after all.\n const resolvedRoom = this.getRoom(roomId);\n if (resolvedRoom?.hasMembershipState(this.credentials.userId!, KnownMembership.Join)) return resolvedRoom;\n\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n const syncRoom = syncApi.createRoom(roomId);\n if (opts.syncRoom) {\n // v2 will do this for us\n // return syncApi.syncRoom(room);\n }\n return syncRoom;\n }\n\n /**\n * Knock a room. If you have already knocked the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to knock.\n * @param opts - Options when knocking the room.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public knockRoom(roomIdOrAlias: string, opts: KnockRoomOpts = {}): Promise<{ room_id: string }> {\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, KnownMembership.Knock)) {\n return Promise.resolve({ room_id: room.roomId });\n }\n\n const path = utils.encodeUri(\"/knock/$roomIdOrAlias\", { $roomIdOrAlias: roomIdOrAlias });\n\n const queryParams: QueryDict = {};\n if (opts.viaServers) {\n // server_name has been deprecated in favour of via with Matrix >1.11 (MSC4156)\n queryParams.server_name = opts.viaServers;\n queryParams.via = opts.viaServers;\n }\n\n const body: Record<string, string> = {};\n if (opts.reason) {\n body.reason = opts.reason;\n }\n\n return this.http.authedRequest(Method.Post, path, queryParams, body);\n }\n\n /**\n * Resend an event. Will also retry any to-device messages waiting to be sent.\n * @param event - The event to resend.\n * @param room - Optional. The room the event is in. Will update the\n * timeline entry if provided.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public resendEvent(event: MatrixEvent, room: Room): Promise<ISendEventResponse> {\n // also kick the to-device queue to retry\n this.toDeviceMessageQueue.sendQueue();\n\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n return this.encryptAndSendEvent(room, event);\n }\n\n /**\n * Cancel a queued or unsent event.\n *\n * @param event - Event to cancel\n * @throws Error if the event is not in QUEUED, NOT_SENT or ENCRYPTING state\n */\n public cancelPendingEvent(event: MatrixEvent): void {\n if (![EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.ENCRYPTING].includes(event.status!)) {\n throw new Error(\"cannot cancel an event with status \" + event.status);\n }\n\n // If the event is currently being encrypted then remove it from the pending list, to indicate that it should\n // not be sent.\n if (event.status === EventStatus.ENCRYPTING) {\n this.eventsBeingEncrypted.delete(event.getId()!);\n } else if (this.scheduler && event.status === EventStatus.QUEUED) {\n // tell the scheduler to forget about it, if it's queued\n this.scheduler.removeEventFromQueue(event);\n }\n\n // then tell the room about the change of state, which will remove it\n // from the room's list of pending events.\n const room = this.getRoom(event.getRoomId());\n this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomName(roomId: string, name: string): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, EventType.RoomName, { name: name });\n }\n\n /**\n * @param htmlTopic - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomTopic(roomId: string, topic: string, htmlTopic?: string): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeTopicContent(topic, htmlTopic);\n return this.sendStateEvent(roomId, EventType.RoomTopic, content);\n }\n\n /**\n * @returns Promise which resolves: to an object keyed by tagId with objects containing a numeric order field.\n * @returns Rejects: with an error response.\n */\n public getRoomTags(roomId: string): Promise<ITagsResponse> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param tagName - name of room tag to be set\n * @param metadata - associated with that tag to be stored\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public setRoomTag(roomId: string, tagName: string, metadata: ITagMetadata = {}): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Put, path, undefined, metadata);\n }\n\n /**\n * @param tagName - name of room tag to be removed\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public deleteRoomTag(roomId: string, tagName: string): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * @param eventType - event type to be set\n * @param content - event content\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomAccountData(roomId: string, eventType: string, content: Record<string, any>): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $type: eventType,\n });\n return this.http.authedRequest(Method.Put, path, undefined, content);\n }\n\n /**\n * Set a power level to one or multiple users.\n * Will apply changes atop of current power level event from local state if running & synced, falling back\n * to fetching latest from the `/state/` API.\n * @param roomId - the room to update power levels in\n * @param userId - the ID of the user or users to update power levels of\n * @param powerLevel - the numeric power level to update given users to\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public async setPowerLevel(\n roomId: string,\n userId: string | string[],\n powerLevel: number | undefined,\n ): Promise<ISendEventResponse> {\n let content: IPowerLevelsContent | undefined;\n if (this.clientRunning && this.isInitialSyncComplete()) {\n content = this.getRoom(roomId)?.currentState?.getStateEvents(EventType.RoomPowerLevels, \"\")?.getContent();\n }\n if (!content) {\n try {\n content = await this.getStateEvent(roomId, EventType.RoomPowerLevels, \"\");\n } catch (e) {\n // It is possible for a Matrix room to not have a power levels event\n if (e instanceof MatrixError && e.errcode === \"M_NOT_FOUND\") {\n content = {};\n } else {\n throw e;\n }\n }\n }\n\n // take a copy of the content to ensure we don't corrupt\n // existing client state with a failed power level change\n content = utils.deepCopy(content);\n\n if (!content?.users) {\n content.users = {};\n }\n const users = Array.isArray(userId) ? userId : [userId];\n for (const user of users) {\n if (powerLevel == null) {\n delete content.users[user];\n } else {\n content.users[user] = powerLevel;\n }\n }\n\n return this.sendStateEvent(roomId, EventType.RoomPowerLevels, content, \"\");\n }\n\n /**\n * Create an m.beacon_info event\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_createLiveBeacon(\n roomId: Room[\"roomId\"],\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.unstable_setLiveBeacon(roomId, beaconInfoContent);\n }\n\n /**\n * Upsert a live beacon event\n * using a specific m.beacon_info.* event variable type\n * @param roomId - string\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_setLiveBeacon(\n roomId: string,\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise<ISendEventResponse> {\n return this.sendStateEvent(roomId, M_BEACON_INFO.name, beaconInfoContent, this.getUserId()!);\n }\n\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent<K extends keyof TimelineEvents>(\n roomId: string,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEvent(\n roomId: string,\n threadIdOrEventType: string | null,\n eventTypeOrContent: string | IContent,\n contentOrTxnId?: IContent | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse> {\n let threadId: string | null;\n let eventType: string;\n let content: IContent;\n let txnId: string | undefined;\n if (!threadIdOrEventType?.startsWith(EVENT_ID_PREFIX) && threadIdOrEventType !== null) {\n txnId = contentOrTxnId as string;\n content = eventTypeOrContent as IContent;\n eventType = threadIdOrEventType;\n threadId = null;\n } else {\n txnId = txnIdOrVoid;\n content = contentOrTxnId as IContent;\n eventType = eventTypeOrContent as string;\n threadId = threadIdOrEventType;\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, txnId);\n }\n\n /**\n * If we expect that an event is part of a thread but is missing the relation\n * we need to add it manually, as well as the reply fallback\n */\n private addThreadRelationIfNeeded(content: IContent, threadId: string | null, roomId: string): void {\n if (threadId && !content[\"m.relates_to\"]?.rel_type) {\n const isReply = !!content[\"m.relates_to\"]?.[\"m.in_reply_to\"];\n content[\"m.relates_to\"] = {\n ...content[\"m.relates_to\"],\n rel_type: THREAD_RELATION_TYPE.name,\n event_id: threadId,\n // Set is_falling_back to true unless this is actually intended to be a reply\n is_falling_back: !isReply,\n };\n const thread = this.getRoom(roomId)?.getThread(threadId);\n if (thread && !isReply) {\n content[\"m.relates_to\"][\"m.in_reply_to\"] = {\n event_id:\n thread\n .lastReply((ev: MatrixEvent) => {\n return ev.isRelation(THREAD_RELATION_TYPE.name) && !ev.status;\n })\n ?.getId() ?? threadId,\n };\n }\n }\n }\n\n /**\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n /**\n * Sends a delayed event (MSC4140).\n * @param eventObject - An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added.\n * @param delayOpts - Properties of the delay for this event.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOpts: SendDelayedEventRequestOpts,\n txnId?: string,\n ): Promise<SendDelayedEventResponse>;\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: Partial<IEvent>,\n delayOptsOrTxnId?: SendDelayedEventRequestOpts | string,\n txnIdOrVoid?: string,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let delayOpts: SendDelayedEventRequestOpts | undefined;\n let txnId: string | undefined;\n if (typeof delayOptsOrTxnId === \"string\") {\n txnId = delayOptsOrTxnId;\n } else {\n delayOpts = delayOptsOrTxnId;\n txnId = txnIdOrVoid;\n }\n\n if (!txnId) {\n txnId = this.makeTxnId();\n }\n\n // We always construct a MatrixEvent when sending because the store and scheduler use them.\n // We'll extract the params back out if it turns out the client has no scheduler or store.\n const localEvent = new MatrixEvent(\n Object.assign(eventObject, {\n event_id: \"~\" + roomId + \":\" + txnId,\n user_id: this.credentials.userId,\n sender: this.credentials.userId,\n room_id: roomId,\n origin_server_ts: new Date().getTime(),\n }),\n );\n\n const room = this.getRoom(roomId);\n const thread = threadId ? room?.getThread(threadId) : undefined;\n if (thread) {\n localEvent.setThread(thread);\n }\n\n if (!delayOpts) {\n // set up re-emitter for this new event - this is normally the job of EventMapper but we don't use it here\n this.reEmitter.reEmit(localEvent, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n room?.reEmitter.reEmit(localEvent, [MatrixEventEvent.BeforeRedaction]);\n }\n\n // if this is a relation or redaction of an event\n // that hasn't been sent yet (e.g. with a local id starting with a ~)\n // then listen for the remote echo of that event so that by the time\n // this event does get sent, we have the correct event_id\n const targetId = localEvent.getAssociatedId();\n if (targetId?.startsWith(\"~\")) {\n const target = room?.getPendingEvents().find((e) => e.getId() === targetId);\n target?.once(MatrixEventEvent.LocalEventIdReplaced, () => {\n localEvent.updateAssociatedId(target.getId()!);\n });\n }\n\n const type = localEvent.getType();\n this.logger.debug(\n `sendEvent of type ${type} in ${roomId} with txnId ${txnId}${delayOpts ? \" (delayed event)\" : \"\"}`,\n );\n\n localEvent.setTxnId(txnId);\n localEvent.setStatus(EventStatus.SENDING);\n\n // TODO: separate store for delayed events?\n if (!delayOpts) {\n // add this event immediately to the local store as 'sending'.\n room?.addPendingEvent(localEvent, txnId);\n\n // addPendingEvent can change the state to NOT_SENT if it believes\n // that there's other events that have failed. We won't bother to\n // try sending the event if the state has changed as such.\n if (localEvent.status === EventStatus.NOT_SENT) {\n return Promise.reject(new Error(\"Event blocked by other events not yet sent\"));\n }\n\n return this.encryptAndSendEvent(room, localEvent);\n } else {\n return this.encryptAndSendEvent(room, localEvent, delayOpts);\n }\n }\n\n /**\n * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent\n * @returns returns a promise which resolves with the result of the send request\n */\n protected async encryptAndSendEvent(room: Room | null, event: MatrixEvent): Promise<ISendEventResponse>;\n /**\n * Simply sends a delayed event without encrypting it.\n * TODO: Allow encrypted delayed events, and encrypt them properly\n * @param delayOpts - Properties of the delay for this event.\n * @returns returns a promise which resolves with the result of the delayed send request\n */\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n protected async encryptAndSendEvent(\n room: Room | null,\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n if (delayOpts) {\n return this.sendEventHttpRequest(event, delayOpts);\n }\n\n try {\n this.eventsBeingEncrypted.add(event.getId()!);\n\n // encryptEventIfNeeded may have updated the status from SENDING to ENCRYPTING. If so, we need\n // to put it back.\n if (event.status === EventStatus.ENCRYPTING) {\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n }\n\n let promise: Promise<ISendEventResponse> | null = null;\n if (this.scheduler) {\n // if this returns a promise then the scheduler has control now and will\n // resolve/reject when it is done. Internally, the scheduler will invoke\n // processFn which is set to this._sendEventHttpRequest so the same code\n // path is executed regardless.\n promise = this.scheduler.queueEvent(event);\n if (promise && this.scheduler.getQueueForEvent(event)!.length > 1) {\n // event is processed FIFO so if the length is 2 or more we know\n // this event is stuck behind an earlier event.\n this.updatePendingEventStatus(room, event, EventStatus.QUEUED);\n }\n }\n\n if (!promise) {\n promise = this.sendEventHttpRequest(event);\n if (room) {\n promise = promise.then((res) => {\n room.updatePendingEvent(event, EventStatus.SENT, res[\"event_id\"]);\n return res;\n });\n }\n }\n\n return await promise;\n } catch (err) {\n this.logger.error(\"Error sending event\", err);\n try {\n // set the error on the event before we update the status:\n // updating the status emits the event, so the state should be\n // consistent at that point.\n event.error = <MatrixError>err;\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n } catch (e) {\n this.logger.error(\"Exception in error handler!\", e);\n }\n if (err instanceof MatrixError) {\n err.event = event;\n }\n throw err;\n }\n }\n\n /**\n * Returns the eventType that should be used taking encryption into account\n * for a given eventType.\n * @param roomId - the room for the events `eventType` relates to\n * @param eventType - the event type\n * @returns the event type taking encryption into account\n */\n private getEncryptedIfNeededEventType(\n roomId: string,\n eventType?: EventType | string | null,\n ): EventType | string | null | undefined {\n if (eventType === EventType.Reaction) return eventType;\n return this.getRoom(roomId)?.hasEncryptionStateEvent() ? EventType.RoomMessageEncrypted : eventType;\n }\n\n protected updatePendingEventStatus(room: Room | null, event: MatrixEvent, newStatus: EventStatus): void {\n if (room) {\n room.updatePendingEvent(event, newStatus);\n } else {\n event.setStatus(newStatus);\n }\n }\n\n private sendEventHttpRequest(event: MatrixEvent): Promise<ISendEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts: SendDelayedEventRequestOpts,\n ): Promise<SendDelayedEventResponse>;\n private sendEventHttpRequest(\n event: MatrixEvent,\n delayOpts?: SendDelayedEventRequestOpts,\n ): Promise<ISendEventResponse | SendDelayedEventResponse> {\n let txnId = event.getTxnId();\n if (!txnId) {\n txnId = this.makeTxnId();\n event.setTxnId(txnId);\n }\n\n const pathParams = {\n $roomId: event.getRoomId()!,\n $eventType: event.getWireType(),\n $stateKey: event.getStateKey()!,\n $txnId: txnId,\n };\n\n let path: string;\n\n if (event.isState()) {\n let pathTemplate = \"/rooms/$roomId/state/$eventType\";\n if (event.getStateKey() && event.getStateKey()!.length > 0) {\n pathTemplate = \"/rooms/$roomId/state/$eventType/$stateKey\";\n }\n path = utils.encodeUri(pathTemplate, pathParams);\n } else if (event.isRedaction() && event.event.redacts) {\n const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`;\n path = utils.encodeUri(pathTemplate, {\n $redactsEventId: event.event.redacts,\n ...pathParams,\n });\n } else {\n path = utils.encodeUri(\"/rooms/$roomId/send/$eventType/$txnId\", pathParams);\n }\n\n const content = event.getWireContent();\n if (!delayOpts) {\n return this.http.authedRequest<ISendEventResponse>(Method.Put, path, undefined, content).then((res) => {\n this.logger.debug(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`);\n return res;\n });\n } else {\n return this.http.authedRequest<SendDelayedEventResponse>(\n Method.Put,\n path,\n getUnstableDelayQueryOpts(delayOpts),\n content,\n );\n }\n }\n\n /**\n * @param txnId - transaction id. One will be made up if not supplied.\n * @param opts - Redact options\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if called with `with_rel_types` (MSC3912) but the server does not support it.\n * Callers should check whether the server supports MSC3912 via `MatrixClient.canSupport`.\n */\n public redactEvent(\n roomId: string,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse>;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId?: string,\n txnId?: string | IRedactOpts,\n opts?: IRedactOpts,\n ): Promise<ISendEventResponse> {\n if (!eventId?.startsWith(EVENT_ID_PREFIX)) {\n opts = txnId as IRedactOpts;\n txnId = eventId;\n eventId = threadId!;\n threadId = null;\n }\n const reason = opts?.reason;\n const content: IContent = { reason };\n\n if (opts?.with_rel_types !== undefined) {\n if (this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Unsupported) {\n throw new Error(\n \"Server does not support relation based redactions \" +\n `roomId ${roomId} eventId ${eventId} txnId: ${txnId} threadId ${threadId}`,\n );\n }\n\n const withRelTypesPropName =\n this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Stable\n ? MSC3912_RELATION_BASED_REDACTIONS_PROP.stable!\n : MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable!;\n\n content[withRelTypesPropName] = opts.with_rel_types;\n }\n\n return this.sendCompleteEvent(\n roomId,\n threadId,\n {\n type: EventType.RoomRedaction,\n content,\n redacts: eventId,\n },\n txnId as string,\n );\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendMessage(roomId: string, content: RoomMessageEventContent, txnId?: string): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null,\n content: RoomMessageEventContent,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendMessage(\n roomId: string,\n threadId: string | null | RoomMessageEventContent,\n content?: RoomMessageEventContent | string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (typeof threadId !== \"string\" && threadId !== null) {\n txnId = content as string;\n content = threadId as RoomMessageEventContent;\n threadId = null;\n }\n\n const eventType = EventType.RoomMessage;\n const sendContent = content as RoomMessageEventContent;\n\n return this.sendEvent(roomId, threadId as string | null, eventType, sendContent, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns\n * @returns Rejects: with an error response.\n */\n public sendTextMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeTextMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendNotice(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeNotice(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendEmoteMessage(roomId: string, body: string, txnId?: string): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse>;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeEmoteMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendImageMessage(roomId: string, url: string, info?: ImageInfo, text?: string): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Image\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Image\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n msgtype: MsgType.Image,\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies RoomMessageEventContent;\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendStickerMessage(\n roomId: string,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: ImageInfo,\n text?: string,\n ): Promise<ISendEventResponse>;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url?: string | ImageInfo,\n info?: ImageInfo | string,\n text = \"Sticker\",\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Sticker\";\n info = url as ImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n url: url as string,\n info: info as ImageInfo,\n body: text,\n } satisfies StickerEventContent;\n\n return this.sendEvent(roomId, threadId, EventType.Sticker, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlMessage(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlMessage(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlNotice(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlNotice(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlEmote(roomId: string, body: string, htmlBody: string): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise<ISendEventResponse>;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise<ISendEventResponse> {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlEmote(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * Send a delayed timeline event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedEvent<K extends keyof TimelineEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n threadId: string | null,\n eventType: K,\n content: TimelineEvents[K],\n txnId?: string,\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n this.addThreadRelationIfNeeded(content, threadId, roomId);\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, delayOpts, txnId);\n }\n\n /**\n * Send a delayed state event.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_sendDelayedStateEvent<K extends keyof StateEvents>(\n roomId: string,\n delayOpts: SendDelayedEventRequestOpts,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<SendDelayedEventResponse> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, getUnstableDelayQueryOpts(delayOpts), content as Body, opts);\n }\n\n /**\n * Get all pending delayed events for the calling user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_getDelayedEvents(fromToken?: string): Promise<DelayedEventInfo> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const queryDict = fromToken ? { from: fromToken } : undefined;\n return await this.http.authedRequest(Method.Get, \"/delayed_events\", queryDict, undefined, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Manage a delayed event associated with the given delay_id.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) for more details.\n */\n // eslint-disable-next-line\n public async _unstable_updateDelayedEvent(delayId: string, action: UpdateDelayedEventAction): Promise<{}> {\n if (!(await this.doesServerSupportUnstableFeature(UNSTABLE_MSC4140_DELAYED_EVENTS))) {\n throw Error(\"Server does not support the delayed events API\");\n }\n\n const path = utils.encodeUri(\"/delayed_events/$delayId\", {\n $delayId: delayId,\n });\n const data = {\n action,\n };\n return await this.http.authedRequest(Method.Post, path, undefined, data, {\n prefix: `${ClientPrefix.Unstable}/${UNSTABLE_MSC4140_DELAYED_EVENTS}`,\n });\n }\n\n /**\n * Send a receipt.\n * @param event - The event being acknowledged\n * @param receiptType - The kind of receipt e.g. \"m.read\". Other than\n * ReceiptType.Read are experimental!\n * @param body - Additional content to send alongside the receipt.\n * @param unthreaded - An unthreaded receipt will clear room+thread notifications\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReceipt(\n event: MatrixEvent,\n receiptType: ReceiptType,\n body?: Record<string, any>,\n unthreaded = false,\n ): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send receipts so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/receipt/$receiptType/$eventId\", {\n $roomId: event.getRoomId()!,\n $receiptType: receiptType,\n $eventId: event.getId()!,\n });\n\n // Unless we're explicitly making an unthreaded receipt or we don't\n // support threads, include the `thread_id` property in the body.\n const shouldAddThreadId = !unthreaded && this.supportsThreads();\n const fullBody = shouldAddThreadId ? { ...body, thread_id: threadIdForReceipt(event) } : body;\n\n const promise = this.http.authedRequest<{}>(Method.Post, path, undefined, fullBody || {});\n\n const room = this.getRoom(event.getRoomId());\n if (room && this.credentials.userId) {\n room.addLocalEchoReceipt(this.credentials.userId, event, receiptType, unthreaded);\n }\n return promise;\n }\n\n /**\n * Send a read receipt.\n * @param event - The event that has been read.\n * @param receiptType - other than ReceiptType.Read are experimental! Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReadReceipt(\n event: MatrixEvent | null,\n receiptType = ReceiptType.Read,\n unthreaded = false,\n ): Promise<{} | undefined> {\n if (!event) return;\n const eventId = event.getId()!;\n const room = this.getRoom(event.getRoomId());\n if (room?.hasPendingEvent(eventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${eventId})`);\n }\n\n return this.sendReceipt(event, receiptType, {}, unthreaded);\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEvent - the event tracked by the read receipt. This is here for\n * convenience because the RR and the RM are commonly updated at the same time as each\n * other. The local echo of this receipt will be done if set. Optional.\n * @param rpEvent - the m.read.private read receipt event for when we don't\n * want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkers(\n roomId: string,\n rmEventId: string,\n rrEvent?: MatrixEvent,\n rpEvent?: MatrixEvent,\n ): Promise<{}> {\n const room = this.getRoom(roomId);\n if (room?.hasPendingEvent(rmEventId)) {\n throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);\n }\n\n // Add the optional RR update, do local echo like `sendReceipt`\n let rrEventId: string | undefined;\n if (rrEvent) {\n rrEventId = rrEvent.getId()!;\n if (room?.hasPendingEvent(rrEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rrEvent, ReceiptType.Read);\n }\n\n // Add the optional private RR update, do local echo like `sendReceipt`\n let rpEventId: string | undefined;\n if (rpEvent) {\n rpEventId = rpEvent.getId()!;\n if (room?.hasPendingEvent(rpEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rpEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rpEvent, ReceiptType.ReadPrivate);\n }\n\n return await this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId);\n }\n\n /**\n * Get a preview of the given URL as of (roughly) the given point in time,\n * described as an object with OpenGraph keys and associated values.\n * Attributes may be synthesized where actual OG metadata is lacking.\n * Caches results to prevent hammering the server.\n * @param url - The URL to get preview data for\n * @param ts - The preferred point in time that the preview should\n * describe (ms since epoch). The preview returned will either be the most\n * recent one preceding this timestamp if available, or failing that the next\n * most recent available preview.\n * @returns Promise which resolves: Object of OG metadata.\n * @returns Rejects: with an error response.\n * May return synthesized attributes if the URL lacked OG meta.\n */\n public getUrlPreview(url: string, ts: number): Promise<IPreviewUrlResponse> {\n // bucket the timestamp to the nearest minute to prevent excessive spam to the server\n // Surely 60-second accuracy is enough for anyone.\n ts = Math.floor(ts / 60000) * 60000;\n\n const parsed = new URL(url);\n parsed.hash = \"\"; // strip the hash as it won't affect the preview\n url = parsed.toString();\n\n const key = ts + \"_\" + url;\n\n // If there's already a request in flight (or we've handled it), return that instead.\n if (key in this.urlPreviewCache) {\n return this.urlPreviewCache[key];\n }\n\n const resp = this.http.authedRequest<IPreviewUrlResponse>(\n Method.Get,\n \"/preview_url\",\n {\n url,\n ts: ts.toString(),\n },\n undefined,\n {\n prefix: MediaPrefix.V3,\n priority: \"low\",\n },\n );\n // TODO: Expire the URL preview cache sometimes\n this.urlPreviewCache[key] = resp;\n return resp;\n }\n\n /**\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public sendTyping(roomId: string, isTyping: boolean, timeoutMs: number): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send typing notifications so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/typing/$userId\", {\n $roomId: roomId,\n $userId: this.getUserId()!,\n });\n const data: QueryDict = {\n typing: isTyping,\n };\n if (isTyping) {\n data.timeout = timeoutMs ? timeoutMs : 20000;\n }\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Determines the history of room upgrades for a given room, as far as the\n * client can see. Returns an array of Rooms where the first entry is the\n * oldest and the last entry is the newest (likely current) room. If the\n * provided room is not found, this returns an empty list. This works in\n * both directions, looking for older and newer rooms of the given room.\n * @param roomId - The room ID to search from\n * @param verifyLinks - If true, the function will only return rooms\n * which can be proven to be linked. For example, rooms which have a create\n * event pointing to an old room which the client is not aware of or doesn't\n * have a matching tombstone would not be returned.\n * @param msc3946ProcessDynamicPredecessor - if true, look for\n * m.room.predecessor state events as well as create events, and prefer\n * predecessor events where they exist (MSC3946).\n * @returns An array of rooms representing the upgrade\n * history.\n */\n public getRoomUpgradeHistory(\n roomId: string,\n verifyLinks = false,\n msc3946ProcessDynamicPredecessor = false,\n ): Room[] {\n const currentRoom = this.getRoom(roomId);\n if (!currentRoom) return [];\n\n const before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n const after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n\n return [...before, currentRoom, ...after];\n }\n\n private findPredecessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n const seenRoomIDs = new Set<string>([room.roomId]);\n\n // Work backwards from newer to older rooms\n let predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n while (predecessorRoomId !== null) {\n if (predecessorRoomId) {\n if (seenRoomIDs.has(predecessorRoomId)) break;\n seenRoomIDs.add(predecessorRoomId);\n }\n const predecessorRoom = this.getRoom(predecessorRoomId);\n if (predecessorRoom === null) {\n break;\n }\n if (verifyLinks) {\n const tombstone = predecessorRoom.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (!tombstone || tombstone.getContent()[\"replacement_room\"] !== room.roomId) {\n break;\n }\n }\n\n // Insert at the front because we're working backwards from the currentRoom\n ret.splice(0, 0, predecessorRoom);\n\n room = predecessorRoom;\n predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n }\n return ret;\n }\n\n private findSuccessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n\n // Work forwards, looking at tombstone events\n let tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n while (tombstoneEvent) {\n const successorRoom = this.getRoom(tombstoneEvent.getContent()[\"replacement_room\"]);\n if (!successorRoom) break; // end of the chain\n if (successorRoom.roomId === room.roomId) break; // Tombstone is referencing its own room\n\n if (verifyLinks) {\n const predecessorRoomId = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (!predecessorRoomId || predecessorRoomId !== room.roomId) {\n break;\n }\n }\n\n // Push to the end because we're looking forwards\n ret.push(successorRoom);\n const roomIds = new Set(ret.map((ref) => ref.roomId));\n if (roomIds.size < ret.length) {\n // The last room added to the list introduced a previous roomId\n // To avoid recursion, return the last rooms - 1\n return ret.slice(0, ret.length - 1);\n }\n\n // Set the current room to the reference room so we know where we're at\n room = successorRoom;\n tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n }\n return ret;\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public invite(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Invite, reason);\n }\n\n /**\n * Invite a user to a room based on their email address.\n * @param roomId - The room to invite the user to.\n * @param email - The email address to invite.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public inviteByEmail(roomId: string, email: string): Promise<{}> {\n return this.inviteByThreePid(roomId, \"email\", email);\n }\n\n /**\n * Invite a user to a room based on a third-party identifier.\n * @param roomId - The room to invite the user to.\n * @param medium - The medium to invite the user e.g. \"email\".\n * @param address - The address for the specified medium.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async inviteByThreePid(roomId: string, medium: string, address: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/invite\", { $roomId: roomId });\n\n const identityServerUrl = this.getIdentityServerUrl(true);\n if (!identityServerUrl) {\n return Promise.reject(\n new MatrixError({\n error: \"No supplied identity server URL\",\n errcode: \"ORG.MATRIX.JSSDK_MISSING_PARAM\",\n }),\n );\n }\n const params: Record<string, string> = {\n id_server: identityServerUrl,\n medium: medium,\n address: address,\n };\n\n if (this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n params[\"id_access_token\"] = identityAccessToken;\n }\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, params);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public leave(roomId: string): Promise<{}> {\n return this.membershipChange(roomId, undefined, KnownMembership.Leave);\n }\n\n /**\n * Leaves all rooms in the chain of room upgrades based on the given room. By\n * default, this will leave all the previous and upgraded rooms, including the\n * given room. To only leave the given room and any previous rooms, keeping the\n * upgraded (modern) rooms untouched supply `false` to `includeFuture`.\n * @param roomId - The room ID to start leaving at\n * @param includeFuture - If true, the whole chain (past and future) of\n * upgraded rooms will be left.\n * @returns Promise which resolves when completed with an object keyed\n * by room ID and value of the error encountered when leaving or null.\n */\n public leaveRoomChain(\n roomId: string,\n includeFuture = true,\n ): Promise<{ [roomId: string]: Error | MatrixError | null }> {\n const upgradeHistory = this.getRoomUpgradeHistory(roomId);\n\n let eligibleToLeave = upgradeHistory;\n if (!includeFuture) {\n eligibleToLeave = [];\n for (const room of upgradeHistory) {\n eligibleToLeave.push(room);\n if (room.roomId === roomId) {\n break;\n }\n }\n }\n\n const populationResults: { [roomId: string]: Error } = {};\n const promises: Promise<unknown>[] = [];\n\n const doLeave = (roomId: string): Promise<void> => {\n return this.leave(roomId)\n .then(() => {\n delete populationResults[roomId];\n })\n .catch((err) => {\n // suppress error\n populationResults[roomId] = err;\n });\n };\n\n for (const room of eligibleToLeave) {\n promises.push(doLeave(room.roomId));\n }\n\n return Promise.all(promises).then(() => populationResults);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public ban(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, KnownMembership.Ban, reason);\n }\n\n /**\n * @param deleteRoom - True to delete the room from the store on success.\n * Default: true.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async forget(roomId: string, deleteRoom = true): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/forget\", {\n $room_id: roomId,\n });\n const response = await this.http.authedRequest<{}>(Method.Post, path);\n if (deleteRoom) {\n this.store.removeRoom(roomId);\n this.emit(ClientEvent.DeleteRoom, roomId);\n }\n return response;\n }\n\n /**\n * @returns Promise which resolves: Object (currently empty)\n * @returns Rejects: with an error response.\n */\n public unban(roomId: string, userId: string): Promise<{}> {\n // unbanning != set their state to leave: this used to be\n // the case, but was then changed so that leaving was always\n // a revoking of privilege, otherwise two people racing to\n // kick / ban someone could end up banning and then un-banning\n // them.\n const path = utils.encodeUri(\"/rooms/$roomId/unban\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public kick(roomId: string, userId: string, reason?: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/kick\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n reason: reason,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n private membershipChange(\n roomId: string,\n userId: string | undefined,\n membership: Membership,\n reason?: string,\n ): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/$membership\", {\n $room_id: roomId,\n $membership: membership,\n });\n return this.http.authedRequest(Method.Post, path, undefined, {\n user_id: userId, // may be undefined e.g. on leave\n reason: reason,\n });\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushActionsForEvent(event: MatrixEvent, forceRecalculate = false): IActionsObject | null {\n if (!event.getPushActions() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushActions();\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushDetailsForEvent(event: MatrixEvent, forceRecalculate = false): PushDetails | null {\n if (!event.getPushDetails() || forceRecalculate) {\n const { actions, rule } = this.pushProcessor.actionsAndRuleForEvent(event);\n event.setPushDetails(actions, rule);\n }\n return event.getPushDetails();\n }\n\n /**\n * @param info - The kind of info to set (e.g. 'avatar_url')\n * @param data - The JSON object to set.\n * @returns\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setProfileInfo(info: \"avatar_url\", data: { avatar_url: string }): Promise<{}>;\n public setProfileInfo(info: \"displayname\", data: { displayname: string }): Promise<{}>;\n public setProfileInfo(info: \"avatar_url\" | \"displayname\", data: object): Promise<{}> {\n const path = utils.encodeUri(\"/profile/$userId/$info\", {\n $userId: this.credentials.userId!,\n $info: info,\n });\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setDisplayName(name: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"displayname\", { displayname: name });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.displayName = name;\n user.emit(UserEvent.DisplayName, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setAvatarUrl(url: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"avatar_url\", { avatar_url: url });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.avatarUrl = url;\n user.emit(UserEvent.AvatarUrl, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * Turn an MXC URL into an HTTP one. <strong>This method is experimental and\n * may change.</strong>\n * @param mxcUrl - The MXC URL\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return null for such URLs.\n * @param allowRedirects - If true, the caller supports the URL being 307 or\n * 308 redirected to another resource upon request. If false, redirects\n * are not expected. Implied `true` when `useAuthentication` is `true`.\n * @param useAuthentication - If true, the caller supports authenticated\n * media and wants an authentication-required URL. Note that server support\n * for authenticated media will *not* be checked - it is the caller's responsibility\n * to do so before calling this function. Note also that `useAuthentication`\n * implies `allowRedirects`. Defaults to false (unauthenticated endpoints).\n * @returns the avatar URL or null.\n */\n public mxcUrlToHttp(\n mxcUrl: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks?: boolean,\n allowRedirects?: boolean,\n useAuthentication?: boolean,\n ): string | null {\n return getHttpUriForMxc(\n this.baseUrl,\n mxcUrl,\n width,\n height,\n resizeMethod,\n allowDirectLinks,\n allowRedirects,\n useAuthentication,\n );\n }\n\n /**\n * Specify the set_presence value to be used for subsequent calls to the Sync API.\n * This has an advantage over calls to the PUT /presence API in that it\n * doesn't clobber status_msg set by other devices.\n * @param presence - the presence to specify to set_presence of sync calls\n */\n public async setSyncPresence(presence?: SetPresence): Promise<void> {\n this.syncApi?.setPresence(presence);\n }\n\n /**\n * @param opts - Options to apply\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n * @throws If 'presence' isn't a valid presence enum value.\n */\n public async setPresence(opts: IPresenceOpts): Promise<void> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: this.credentials.userId!,\n });\n\n const validStates = [\"offline\", \"online\", \"unavailable\"];\n if (validStates.indexOf(opts.presence) === -1) {\n throw new Error(\"Bad presence value: \" + opts.presence);\n }\n await this.http.authedRequest(Method.Put, path, undefined, opts);\n }\n\n /**\n * @param userId - The user to get presence for\n * @returns Promise which resolves: The presence state for this user.\n * @returns Rejects: with an error response.\n */\n public getPresence(userId: string): Promise<IStatusResponse> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: userId,\n });\n\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve older messages from the given room and put them in the timeline.\n *\n * If this is called multiple times whilst a request is ongoing, the <i>same</i>\n * Promise will be returned. If there was a problem requesting scrollback, there\n * will be a small delay before another request can be made (to prevent tight-looping\n * when there is no connection).\n *\n * @param room - The room to get older messages in.\n * @param limit - Optional. The maximum number of previous events to\n * pull in. Default: 30.\n * @returns Promise which resolves: Room. If you are at the beginning\n * of the timeline, `Room.oldState.paginationToken` will be\n * `null`.\n * @returns Rejects: with an error response.\n */\n public scrollback(room: Room, limit = 30): Promise<Room> {\n let timeToWaitMs = 0;\n\n let info = this.ongoingScrollbacks[room.roomId] || {};\n if (info.promise) {\n return info.promise;\n } else if (info.errorTs) {\n const timeWaitedMs = Date.now() - info.errorTs;\n timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);\n }\n\n if (room.oldState.paginationToken === null) {\n return Promise.resolve(room); // already at the start.\n }\n // attempt to grab more events from the store first\n const numAdded = this.store.scrollback(room, limit).length;\n if (numAdded === limit) {\n // store contained everything we needed.\n return Promise.resolve(room);\n }\n // reduce the required number of events appropriately\n limit = limit - numAdded;\n\n const promise = new Promise<Room>((resolve, reject) => {\n // wait for a time before doing this request\n // (which may be 0 in order not to special case the code paths)\n sleep(timeToWaitMs)\n .then(() => {\n return this.createMessagesRequest(\n room.roomId,\n room.oldState.paginationToken,\n limit,\n Direction.Backward,\n );\n })\n .then((res: IMessagesResponse) => {\n const matrixEvents = res.chunk.map(this.getEventMapper());\n if (res.state) {\n const stateEvents = res.state.map(this.getEventMapper());\n room.currentState.setUnknownStateEvents(stateEvents);\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] =\n room.partitionThreadedEvents(matrixEvents);\n\n this.processAggregatedTimelineEvents(room, timelineEvents);\n room.addEventsToTimeline(timelineEvents, true, room.getLiveTimeline());\n this.processThreadEvents(room, threadedEvents, true);\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n room.oldState.paginationToken = res.end ?? null;\n if (res.chunk.length === 0) {\n room.oldState.paginationToken = null;\n }\n this.store.storeEvents(room, matrixEvents, res.end ?? null, true);\n delete this.ongoingScrollbacks[room.roomId];\n resolve(room);\n })\n .catch((err) => {\n this.ongoingScrollbacks[room.roomId] = {\n errorTs: Date.now(),\n };\n reject(err);\n });\n });\n\n info = { promise };\n\n this.ongoingScrollbacks[room.roomId] = info;\n return promise;\n }\n\n public getEventMapper(options?: MapperOpts): EventMapper {\n return eventMapperFor(this, options || {});\n }\n\n /**\n * Get an EventTimeline for the given event\n *\n * <p>If the EventTimelineSet object already has the given event in its store, the\n * corresponding timeline will be returned. Otherwise, a /context request is\n * made, and used to construct an EventTimeline.\n * If the event does not belong to this EventTimelineSet then undefined will be returned.\n *\n * @param timelineSet - The timelineSet to look for the event in, must be bound to a room\n * @param eventId - The ID of the event to look for\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} including the given event\n */\n public async getEventTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet?.room) {\n throw new Error(\"getEventTimeline only supports room timelines\");\n }\n\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n if (timelineSet.thread && this.supportsThreads()) {\n return this.getThreadTimeline(timelineSet, eventId);\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n let params: Record<string, string | string[]> | undefined = undefined;\n if (this.clientOpts?.lazyLoadMembers) {\n params = { filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER) };\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n if (!res.event) {\n throw new Error(\"'event' not in '/context' result - homeserver too old?\");\n }\n\n // by the time the request completes, the event might have ended up in the timeline.\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.logger.warn(\"Tried loading a regular timeline at the position of a thread event\");\n return undefined;\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...res.events_after.reverse().map(mapper),\n event,\n ...res.events_before.map(mapper),\n ];\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(events[0].getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n timeline.getState(EventTimeline.FORWARDS)!.paginationToken = res.end;\n }\n\n const [timelineEvents, threadedEvents, unknownRelations] = timelineSet.room.partitionThreadedEvents(events);\n timelineSet.addEventsToTimeline(timelineEvents, true, timeline, res.start);\n // The target event is not in a thread but process the contextual events, so we can show any threads around it.\n this.processThreadEvents(timelineSet.room, threadedEvents, true);\n this.processAggregatedTimelineEvents(timelineSet.room, timelineEvents);\n unknownRelations.forEach((event) => timelineSet.relations.aggregateChildEvent(event));\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return (\n timelineSet.getTimelineForEvent(eventId) ??\n timelineSet.room.findThreadForEvent(event)?.liveTimeline ?? // for Threads degraded support\n timeline\n );\n }\n\n public async getThreadTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<EventTimeline | undefined> {\n if (!this.supportsThreads()) {\n throw new Error(\"could not get thread timeline: no client support\");\n }\n\n if (!timelineSet.room) {\n throw new Error(\"could not get thread timeline: not a room timeline\");\n }\n\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n const params: Record<string, string | string[]> = {\n limit: \"0\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest<IContextResponse>(Method.Get, path, params);\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n\n if (!timelineSet.canContain(event)) {\n return undefined;\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n if (Thread.hasServerSideSupport) {\n if (Thread.hasServerSideFwdPaginationSupport) {\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const thread = timelineSet.thread;\n const resOlder: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n null,\n null,\n { dir: Direction.Forward, from: res.end, recurse: recurse || undefined },\n );\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...resNewer.chunk.reverse().filter(getRelationsThreadFilter(thread.id)).map(mapper),\n event,\n ...resOlder.chunk.filter(getRelationsThreadFilter(thread.id)).map(mapper),\n ];\n\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(event.getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n }\n\n timelineSet.addEventsToTimeline(events, true, timeline, resNewer.next_batch);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(resNewer.next_batch ?? null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return timelineSet.getTimelineForEvent(eventId) ?? timeline;\n } else {\n // Where the event is a thread reply (not a root) and running in MSC-enabled mode the Thread timeline only\n // functions contiguously, so we have to jump through some hoops to get our target event in it.\n // XXX: workaround for https://github.com/vector-im/element-meta/issues/150\n\n const thread = timelineSet.thread;\n\n const resOlder = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, from: res.start, recurse: recurse || undefined },\n );\n const eventsNewer: IEvent[] = [];\n let nextBatch: Optional<string> = res.end;\n while (nextBatch) {\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Forward, from: nextBatch, recurse: recurse || undefined },\n );\n nextBatch = resNewer.next_batch ?? null;\n eventsNewer.push(...resNewer.chunk);\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...eventsNewer.reverse().map(mapper),\n event,\n ...resOlder.chunk.map(mapper),\n ];\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread\n // summaries.\n const timeline = timelineSet.getLiveTimeline();\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n\n timelineSet.addEventsToTimeline(events, true, timeline, null);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n return timeline;\n }\n }\n }\n\n /**\n * Get an EventTimeline for the latest events in the room. This will just\n * call `/messages` to get the latest message in the room, then use\n * `client.getEventTimeline(...)` to construct a new timeline from it.\n *\n * @param timelineSet - The timelineSet to find or add the timeline to\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} timeline with the latest events in the room\n */\n public async getLatestTimeline(timelineSet: EventTimelineSet): Promise<Optional<EventTimeline>> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet.room) {\n throw new Error(\"getLatestTimeline only supports room timelines\");\n }\n\n let event: IRoomEvent | undefined;\n if (timelineSet.threadListType !== null) {\n const res = await this.createThreadListMessagesRequest(\n timelineSet.room.roomId,\n null,\n 1,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n event = res.chunk?.[0];\n } else if (timelineSet.thread && Thread.hasServerSideSupport) {\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n const res = await this.fetchRelations(\n timelineSet.room.roomId,\n timelineSet.thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, limit: 1, recurse: recurse || undefined },\n );\n event = res.chunk?.[0];\n } else {\n const messagesPath = utils.encodeUri(\"/rooms/$roomId/messages\", {\n $roomId: timelineSet.room.roomId,\n });\n\n const params: Record<string, string | string[]> = {\n dir: \"b\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n const res = await this.http.authedRequest<IMessagesResponse>(Method.Get, messagesPath, params);\n event = res.chunk?.[0];\n }\n if (!event) {\n throw new Error(\"No message returned when trying to construct getLatestTimeline\");\n }\n\n return this.getEventTimeline(timelineSet, event.event_id);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used in code.\n public createMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir: Direction,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/messages\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter | null = null;\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = filter || {};\n Object.assign(filter, timelineFilter.getRoomTimelineFilterComponent()?.toJSON());\n }\n if (filter) {\n params.filter = JSON.stringify(filter);\n }\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used by room.fetchRoomThreads\n public createThreadListMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir = Direction.Backward,\n threadListType: ThreadFilterType | null = ThreadFilterType.All,\n timelineFilter?: Filter,\n ): Promise<IMessagesResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/threads\", { $roomId: roomId });\n\n const params: Record<string, string> = {\n limit: limit.toString(),\n dir: dir,\n include: threadFilterTypeToFilter(threadListType),\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter = {};\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = {\n ...Filter.LAZY_LOADING_MESSAGES_FILTER,\n };\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = {\n ...filter,\n ...timelineFilter.getRoomTimelineFilterComponent()?.toJSON(),\n };\n }\n if (Object.keys(filter).length) {\n params.filter = JSON.stringify(filter);\n }\n\n const opts = {\n prefix:\n Thread.hasServerSideListSupport === FeatureSupport.Stable\n ? ClientPrefix.V1\n : \"/_matrix/client/unstable/org.matrix.msc3856\",\n };\n\n return this.http\n .authedRequest<IThreadedMessagesResponse>(Method.Get, path, params, undefined, opts)\n .then((res) => ({\n ...res,\n chunk: res.chunk?.reverse(),\n start: res.prev_batch,\n end: res.next_batch,\n }));\n }\n\n /**\n * Take an EventTimeline, and back/forward-fill results.\n *\n * @param eventTimeline - timeline object to be updated\n *\n * @returns Promise which resolves to a boolean: false if there are no\n * events and we reached either end of the timeline; else true.\n */\n public paginateEventTimeline(eventTimeline: EventTimeline, opts: IPaginateOpts): Promise<boolean> {\n const isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet;\n const room = this.getRoom(eventTimeline.getRoomId()!);\n const threadListType = eventTimeline.getTimelineSet().threadListType;\n const thread = eventTimeline.getTimelineSet().thread;\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n opts = opts || {};\n const backwards = opts.backwards || false;\n\n if (isNotifTimeline) {\n if (!backwards) {\n throw new Error(\"paginateNotifTimeline can only paginate backwards\");\n }\n }\n\n const dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n\n const token = eventTimeline.getPaginationToken(dir);\n const pendingRequest = eventTimeline.paginationRequests[dir];\n\n if (pendingRequest) {\n // already a request in progress - return the existing promise\n return pendingRequest;\n }\n\n let path: string;\n let params: Record<string, string>;\n let promise: Promise<boolean>;\n\n if (isNotifTimeline) {\n path = \"/notifications\";\n params = {\n limit: (opts.limit ?? 30).toString(),\n only: \"highlight\",\n };\n\n if (token && token !== \"end\") {\n params.from = token;\n }\n\n promise = this.http\n .authedRequest<INotificationsResponse>(Method.Get, path, params)\n .then(async (res) => {\n const token = res.next_token;\n const matrixEvents: MatrixEvent[] = [];\n\n res.notifications = res.notifications.filter(noUnsafeEventProps);\n\n for (let i = 0; i < res.notifications.length; i++) {\n const notification = res.notifications[i];\n const event = this.getEventMapper()(notification.event);\n\n // @TODO(kerrya) reprocessing every notification is ugly\n // remove if we get server MSC3994 support\n this.getPushDetailsForEvent(event, true);\n\n event.event.room_id = notification.room_id; // XXX: gutwrenching\n matrixEvents[i] = event;\n }\n\n // No need to partition events for threads here, everything lives\n // in the notification timeline set\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !res.next_token) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(res.next_token);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (threadListType !== null) {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n if (!Thread.hasServerSideFwdPaginationSupport && dir === Direction.Forward) {\n throw new Error(\"Cannot paginate threads forwards without server-side support for MSC 3715\");\n }\n\n promise = this.createThreadListMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n threadListType,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, matrixEvents);\n this.processThreadRoots(room, matrixEvents, backwards);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && res.end == res.start) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return res.end !== res.start;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (thread) {\n const room = this.getRoom(eventTimeline.getRoomId() ?? undefined);\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n const recurse = this.canSupport.get(Feature.RelationsRecursion) !== ServerSupport.Unsupported;\n promise = this.fetchRelations(eventTimeline.getRoomId() ?? \"\", thread.id, null, null, {\n dir,\n limit: opts.limit,\n from: token ?? undefined,\n recurse: recurse || undefined,\n })\n .then(async (res) => {\n const mapper = this.getEventMapper();\n const matrixEvents = res.chunk\n .filter(noUnsafeEventProps)\n .filter(getRelationsThreadFilter(thread.id))\n .map(mapper);\n\n // Process latest events first\n for (const event of matrixEvents.slice().reverse()) {\n await thread?.processEvent(event);\n const sender = event.getSender()!;\n if (!backwards || thread?.getEventReadUpTo(sender) === null) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n }\n\n const newToken = res.next_batch;\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, newToken ?? null);\n if (!newToken && backwards) {\n const originalEvent =\n thread.rootEvent ??\n mapper(await this.fetchRoomEvent(eventTimeline.getRoomId() ?? \"\", thread.id));\n timelineSet.addEventsToTimeline([originalEvent], true, eventTimeline, null);\n }\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !newToken) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(newToken);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n promise = this.createMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n const [timelineEvents, , unknownRelations] = room.partitionThreadedEvents(matrixEvents);\n timelineSet.addEventsToTimeline(timelineEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, timelineEvents);\n this.processThreadRoots(\n room,\n timelineEvents.filter((it) => it.getServerAggregatedRelation(THREAD_RELATION_TYPE.name)),\n false,\n );\n unknownRelations.forEach((event) => room.relations.aggregateChildEvent(event));\n\n const atEnd = res.end === undefined || res.end === res.start;\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && atEnd) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return !atEnd;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n }\n\n return promise;\n }\n\n /**\n * Reset the notifTimelineSet entirely, paginating in some historical notifs as\n * a starting point for subsequent pagination.\n */\n public resetNotifTimelineSet(): void {\n if (!this.notifTimelineSet) {\n return;\n }\n\n // FIXME: This thing is a total hack, and results in duplicate events being\n // added to the timeline both from /sync and /notifications, and lots of\n // slow and wasteful processing and pagination. The correct solution is to\n // extend /messages or /search or something to filter on notifications.\n\n // use the fictitious token 'end'. in practice we would ideally give it\n // the oldest backwards pagination token from /sync, but /sync doesn't\n // know about /notifications, so we have no choice but to start paginating\n // from the current point in time. This may well overlap with historical\n // notifs which are then inserted into the timeline by /sync responses.\n this.notifTimelineSet.resetLiveTimeline(\"end\");\n\n // we could try to paginate a single event at this point in order to get\n // a more valid pagination token, but it just ends up with an out of order\n // timeline. given what a mess this is and given we're going to have duplicate\n // events anyway, just leave it with the dummy token for now.\n /*\n this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {\n backwards: true,\n limit: 1\n });\n */\n }\n\n /**\n * Peek into a room and receive updates about the room. This only works if the\n * history visibility for the room is world_readable.\n * @param roomId - The room to attempt to peek into.\n * @param limit - The number of timeline events to initially retrieve.\n * @returns Promise which resolves: Room object\n * @returns Rejects: with an error response.\n */\n public peekInRoom(roomId: string, limit: number = 20): Promise<Room> {\n this.peekSync?.stopPeeking();\n this.peekSync = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n return this.peekSync.peek(roomId, limit);\n }\n\n /**\n * Stop any ongoing room peeking.\n */\n public stopPeeking(): void {\n if (this.peekSync) {\n this.peekSync.stopPeeking();\n this.peekSync = null;\n }\n }\n\n /**\n * Set r/w flags for guest access in a room.\n * @param roomId - The room to configure guest access in.\n * @param opts - Options\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n */\n public setGuestAccess(roomId: string, opts: IGuestAccessOpts): Promise<void> {\n const writePromise = this.sendStateEvent(\n roomId,\n EventType.RoomGuestAccess,\n {\n guest_access: opts.allowJoin ? GuestAccess.CanJoin : GuestAccess.Forbidden,\n },\n \"\",\n );\n\n let readPromise: Promise<unknown> = Promise.resolve();\n if (opts.allowRead) {\n readPromise = this.sendStateEvent(\n roomId,\n EventType.RoomHistoryVisibility,\n {\n history_visibility: HistoryVisibility.WorldReadable,\n },\n \"\",\n );\n }\n\n return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract\n }\n\n /**\n * Requests an email verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * Parameters and return value are as for requestEmailToken\n\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in which\n * phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international format\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/register/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of adding a\n * third party identifier to an account.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n * If an account with the given email address already exists and is\n * associated with an account other than the one the user is authed as,\n * it will either send an email to the address informing them of this\n * or return M_THREEPID_IN_USE (which one is up to the homeserver).\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of adding a\n * third party identifier to an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the addition of phone numbers to an\n * account, as requestAdd3pidEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/3pid/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting. Specifically,\n * if no account with the given email address exists, it may either\n * return M_THREEPID_NOT_FOUND or send an email\n * to the address informing them of this (which one is up to the homeserver).\n *\n * requestEmailToken calls the equivalent API directly on the identity server,\n * therefore bypassing the password reset specific logic.\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<IRequestTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting, as requestPasswordEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n return this.requestTokenFromEndpoint(\"/account/password/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Internal utility function for requesting validation tokens from usage-specific\n * requestToken endpoints.\n *\n * @param endpoint - The endpoint to send the request to\n * @param params - Parameters for the POST request\n * @returns Promise which resolves: As requestEmailToken\n */\n private async requestTokenFromEndpoint<T extends IRequestTokenResponse>(\n endpoint: string,\n params: QueryDict,\n ): Promise<T> {\n const postParams = Object.assign({}, params);\n\n return this.http.request(Method.Post, endpoint, undefined, postParams);\n }\n\n /**\n * Get the room-kind push rule associated with a room.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @returns the rule or undefined.\n */\n public getRoomPushRule(scope: \"global\" | \"device\", roomId: string): IPushRule | undefined {\n // There can be only room-kind push rule per room\n // and its id is the room id.\n if (this.pushRules) {\n return this.pushRules[scope]?.room?.find((rule) => rule.rule_id === roomId);\n } else {\n throw new Error(\"SyncApi.sync() must be done before accessing to push rules.\");\n }\n }\n\n /**\n * Set a room-kind muting push rule in a room.\n * The operation also updates MatrixClient.pushRules at the end.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @param mute - the mute state.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public setRoomMutePushRule(scope: \"global\" | \"device\", roomId: string, mute: boolean): Promise<void> | undefined {\n let promise: Promise<unknown> | undefined;\n let hasDontNotifyRule = false;\n\n // Get the existing room-kind push rule if any\n const roomPushRule = this.getRoomPushRule(scope, roomId);\n if (roomPushRule?.actions.includes(PushRuleActionName.DontNotify)) {\n hasDontNotifyRule = true;\n }\n\n if (!mute) {\n // Remove the rule only if it is a muting rule\n if (hasDontNotifyRule) {\n promise = this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule!.rule_id);\n }\n } else {\n if (!roomPushRule) {\n promise = this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n });\n } else if (!hasDontNotifyRule) {\n // Remove the existing one before setting the mute push rule\n // This is a workaround to SYN-590 (Push rule update fails)\n const deferred = utils.defer();\n this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id)\n .then(() => {\n this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n })\n .then(() => {\n deferred.resolve();\n })\n .catch((err) => {\n deferred.reject(err);\n });\n })\n .catch((err) => {\n deferred.reject(err);\n });\n\n promise = deferred.promise;\n }\n }\n\n if (promise) {\n return new Promise<void>((resolve, reject) => {\n // Update this.pushRules when the operation completes\n promise!\n .then(() => {\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n resolve();\n })\n .catch((err) => {\n reject(err);\n });\n })\n .catch((err: Error) => {\n // Update it even if the previous operation fails. This can help the\n // app to recover when push settings has been modified from another client\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n reject(err);\n })\n .catch((err2) => {\n reject(err);\n });\n });\n });\n }\n }\n\n public searchMessageText(opts: ISearchOpts): Promise<ISearchResponse> {\n const roomEvents: ISearchRequestBody[\"search_categories\"][\"room_events\"] = {\n search_term: opts.query,\n };\n\n if (\"keys\" in opts) {\n roomEvents.keys = opts.keys;\n }\n\n return this.search({\n body: {\n search_categories: {\n room_events: roomEvents,\n },\n },\n });\n }\n\n /**\n * Perform a server-side search for room events.\n *\n * The returned promise resolves to an object containing the fields:\n *\n * * count: estimate of the number of results\n * * next_batch: token for back-pagination; if undefined, there are no more results\n * * highlights: a list of words to highlight from the stemming algorithm\n * * results: a list of results\n *\n * Each entry in the results list is a SearchResult.\n *\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public searchRoomEvents(opts: IEventSearchOpts): Promise<ISearchResults> {\n // TODO: support search groups\n\n const body = {\n search_categories: {\n room_events: {\n search_term: opts.term,\n filter: opts.filter,\n order_by: SearchOrderBy.Recent,\n event_context: {\n before_limit: 1,\n after_limit: 1,\n include_profile: true,\n },\n },\n },\n };\n\n const searchResults: ISearchResults = {\n _query: body,\n results: [],\n highlights: [],\n };\n\n return this.search({ body: body }).then((res) => this.processRoomEventsSearch(searchResults, res));\n }\n\n /**\n * Take a result from an earlier searchRoomEvents call, and backfill results.\n *\n * @param searchResults - the results object to be updated\n * @returns Promise which resolves: updated result object\n * @returns Rejects: with an error response.\n */\n public backPaginateRoomEventsSearch<T extends ISearchResults>(searchResults: T): Promise<T> {\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n\n if (!searchResults.next_batch) {\n return Promise.reject(new Error(\"Cannot backpaginate event search any further\"));\n }\n\n if (searchResults.pendingRequest) {\n // already a request in progress - return the existing promise\n return searchResults.pendingRequest as Promise<T>;\n }\n\n const searchOpts = {\n body: searchResults._query!,\n next_batch: searchResults.next_batch,\n };\n\n const promise = this.search(searchOpts, searchResults.abortSignal)\n .then((res) => this.processRoomEventsSearch(searchResults, res))\n .finally(() => {\n searchResults.pendingRequest = undefined;\n });\n searchResults.pendingRequest = promise;\n\n return promise;\n }\n\n /**\n * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the\n * response from the API call and updates the searchResults\n *\n * @returns searchResults\n * @internal\n */\n // XXX: Intended private, used in code\n public processRoomEventsSearch<T extends ISearchResults>(searchResults: T, response: ISearchResponse): T {\n const roomEvents = response.search_categories.room_events;\n\n searchResults.count = roomEvents.count;\n searchResults.next_batch = roomEvents.next_batch;\n\n // combine the highlight list with our existing list;\n const highlights = new Set<string>(roomEvents.highlights);\n searchResults.highlights.forEach((hl) => {\n highlights.add(hl);\n });\n\n // turn it back into a list.\n searchResults.highlights = Array.from(highlights);\n\n const mapper = this.getEventMapper();\n\n // append the new results to our existing results\n const resultsLength = roomEvents.results?.length ?? 0;\n for (let i = 0; i < resultsLength; i++) {\n const sr = SearchResult.fromJson(roomEvents.results![i], mapper);\n const room = this.getRoom(sr.context.getEvent().getRoomId());\n if (room) {\n // Copy over a known event sender if we can\n for (const ev of sr.context.getTimeline()) {\n const sender = room.getMember(ev.getSender()!);\n if (!ev.sender && sender) ev.sender = sender;\n }\n }\n searchResults.results.push(sr);\n }\n return searchResults;\n }\n\n /**\n * Populate the store with rooms the user has left.\n * @returns Promise which resolves: TODO - Resolved when the rooms have\n * been added to the data store.\n * @returns Rejects: with an error response.\n */\n public syncLeftRooms(): Promise<Room[]> {\n // Guard against multiple calls whilst ongoing and multiple calls post success\n if (this.syncedLeftRooms) {\n return Promise.resolve([]); // don't call syncRooms again if it succeeded.\n }\n if (this.syncLeftRoomsPromise) {\n return this.syncLeftRoomsPromise; // return the ongoing request\n }\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n this.syncLeftRoomsPromise = syncApi.syncLeftRooms();\n\n // cleanup locks\n this.syncLeftRoomsPromise\n .then(() => {\n this.logger.debug(\"Marking success of sync left room request\");\n this.syncedLeftRooms = true; // flip the bit on success\n })\n .finally(() => {\n this.syncLeftRoomsPromise = undefined; // cleanup ongoing request state\n });\n\n return this.syncLeftRoomsPromise;\n }\n\n /**\n * Create a new filter.\n * @param content - The HTTP body for the request\n * @returns Promise which resolves to a Filter object.\n * @returns Rejects: with an error response.\n */\n public createFilter(content: IFilterDefinition): Promise<Filter> {\n const path = utils.encodeUri(\"/user/$userId/filter\", {\n $userId: this.credentials.userId!,\n });\n return this.http.authedRequest<IFilterResponse>(Method.Post, path, undefined, content).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(this.credentials.userId, response.filter_id, content);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * Retrieve a filter.\n * @param userId - The user ID of the filter owner\n * @param filterId - The filter ID to retrieve\n * @param allowCached - True to allow cached filters to be returned.\n * Default: True.\n * @returns Promise which resolves: a Filter object\n * @returns Rejects: with an error response.\n */\n public getFilter(userId: string, filterId: string, allowCached: boolean): Promise<Filter> {\n if (allowCached) {\n const filter = this.store.getFilter(userId, filterId);\n if (filter) {\n return Promise.resolve(filter);\n }\n }\n\n const path = utils.encodeUri(\"/user/$userId/filter/$filterId\", {\n $userId: userId,\n $filterId: filterId,\n });\n\n return this.http.authedRequest<IFilterDefinition>(Method.Get, path).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(userId, filterId, response);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * @returns Filter ID\n */\n public async getOrCreateFilter(filterName: string, filter: Filter): Promise<string> {\n const filterId = this.store.getFilterIdByName(filterName);\n let existingId: string | undefined;\n\n if (filterId) {\n // check that the existing filter matches our expectations\n try {\n const existingFilter = await this.getFilter(this.credentials.userId!, filterId, true);\n if (existingFilter) {\n const oldDef = existingFilter.getDefinition();\n const newDef = filter.getDefinition();\n\n if (utils.deepCompare(oldDef, newDef)) {\n // super, just use that.\n // debuglog(\"Using existing filter ID %s: %s\", filterId,\n // JSON.stringify(oldDef));\n existingId = filterId;\n }\n }\n } catch (error) {\n // Synapse currently returns the following when the filter cannot be found:\n // {\n // errcode: \"M_UNKNOWN\",\n // name: \"M_UNKNOWN\",\n // message: \"No row found\",\n // }\n if ((<MatrixError>error).errcode !== \"M_UNKNOWN\" && (<MatrixError>error).errcode !== \"M_NOT_FOUND\") {\n throw error;\n }\n }\n // if the filter doesn't exist anymore on the server, remove from store\n if (!existingId) {\n this.store.setFilterIdByName(filterName, undefined);\n }\n }\n\n if (existingId) {\n return existingId;\n }\n\n // create a new filter\n const createdFilter = await this.createFilter(filter.getDefinition());\n\n this.store.setFilterIdByName(filterName, createdFilter.filterId);\n return createdFilter.filterId!;\n }\n\n /**\n * Gets a bearer token from the homeserver that the user can\n * present to a third party in order to prove their ownership\n * of the Matrix account they are logged into.\n * @returns Promise which resolves: Token object\n * @returns Rejects: with an error response.\n */\n public getOpenIdToken(): Promise<IOpenIDToken> {\n const path = utils.encodeUri(\"/user/$userId/openid/request_token\", {\n $userId: this.credentials.userId!,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, {});\n }\n\n /**\n * Once the client has been initialised, we want to clear notifications we\n * know for a fact should be here.\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * We consider a room or a thread as fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n */\n private fixupRoomNotifications = (): void => {\n if (this.isInitialSyncComplete()) {\n const unreadRooms = (this.getRooms() ?? []).filter((room) => {\n return room.getUnreadNotificationCount(NotificationCountType.Total) > 0;\n });\n\n for (const room of unreadRooms) {\n const currentUserId = this.getSafeUserId();\n room.fixupNotifications(currentUserId);\n }\n\n this.off(ClientEvent.Sync, this.fixupRoomNotifications);\n }\n };\n\n /**\n * Set whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n */\n public setFallbackICEServerAllowed(allow: boolean): void {\n this.fallbackICEServerAllowed = allow;\n }\n\n /**\n * Get whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n * @returns\n */\n public isFallbackICEServerAllowed(): boolean {\n return this.fallbackICEServerAllowed;\n }\n\n /**\n * Determines if the current user is an administrator of the Synapse homeserver.\n * Returns false if untrue or the homeserver does not appear to be a Synapse\n * homeserver. <strong>This function is implementation specific and may change\n * as a result.</strong>\n * @returns true if the user appears to be a Synapse administrator.\n */\n public isSynapseAdministrator(): Promise<boolean> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/users/$userId/admin\", { $userId: this.getUserId()! });\n return this.http\n .authedRequest<{ admin: boolean }>(Method.Get, path, undefined, undefined, { prefix: \"\" })\n .then((r) => r.admin); // pull out the specific boolean we want\n }\n\n /**\n * Performs a whois lookup on a user using Synapse's administrator API.\n * <strong>This function is implementation specific and may change as a\n * result.</strong>\n * @param userId - the User ID to look up.\n * @returns the whois response - see Synapse docs for information.\n */\n public whoisSynapseUser(userId: string): Promise<ISynapseAdminWhoisResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/whois/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix: \"\" });\n }\n\n /**\n * Deactivates a user using Synapse's administrator API. <strong>This\n * function is implementation specific and may change as a result.</strong>\n * @param userId - the User ID to deactivate.\n * @returns the deactivate response - see Synapse docs for information.\n */\n public deactivateSynapseUser(userId: string): Promise<ISynapseAdminDeactivateResponse> {\n const path = utils.encodeUri(\"/_synapse/admin/v1/deactivate/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Post, path, undefined, undefined, { prefix: \"\" });\n }\n\n protected async fetchClientWellKnown(): Promise<void> {\n // `getRawClientConfig` does not throw or reject on network errors, instead\n // it absorbs errors and returns `{}`.\n this.clientWellKnownPromise = AutoDiscovery.getRawClientConfig(this.getDomain() ?? undefined);\n this.clientWellKnown = await this.clientWellKnownPromise;\n this.emit(ClientEvent.ClientWellKnown, this.clientWellKnown);\n }\n\n public getClientWellKnown(): IClientWellKnown | undefined {\n return this.clientWellKnown;\n }\n\n public waitForClientWellKnown(): Promise<IClientWellKnown> {\n if (!this.clientRunning) {\n throw new Error(\"Client is not running\");\n }\n return this.clientWellKnownPromise!;\n }\n\n /**\n * store client options with boolean/string/numeric values\n * to know in the next session what flags the sync data was\n * created with (e.g. lazy loading)\n * @returns for store operation\n */\n public storeClientOptions(): Promise<void> {\n // XXX: Intended private, used in code\n const primTypes = [\"boolean\", \"string\", \"number\"];\n const serializableOpts = Object.entries(this.clientOpts!)\n .filter(([key, value]) => {\n return primTypes.includes(typeof value);\n })\n .reduce<Record<string, any>>((obj, [key, value]) => {\n obj[key] = value;\n return obj;\n }, {});\n return this.store.storeClientOptions(serializableOpts);\n }\n\n /**\n * Gets a set of room IDs in common with another user.\n *\n * Note: This endpoint is unstable, and can throw an `Error`.\n * Check progress on [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) for more details.\n *\n * @param userId - The userId to check.\n * @returns Promise which resolves to an array of rooms\n * @returns Rejects: with an error response.\n */\n // TODO: on spec release, rename this to getMutualRooms\n // eslint-disable-next-line\n public async _unstable_getSharedRooms(userId: string): Promise<string[]> {\n // Initial variant of the MSC\n const sharedRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_SHARED_ROOMS);\n\n // Newer variant that renamed shared rooms to mutual rooms\n const mutualRoomsSupport = await this.doesServerSupportUnstableFeature(UNSTABLE_MSC2666_MUTUAL_ROOMS);\n\n // Latest variant that changed from path elements to query elements\n const queryMutualRoomsSupport = await this.doesServerSupportUnstableFeature(\n UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS,\n );\n\n if (!sharedRoomsSupport && !mutualRoomsSupport && !queryMutualRoomsSupport) {\n throw Error(\"Server does not support the Mutual Rooms API\");\n }\n\n let path;\n let query;\n\n // Cascading unstable support switching.\n if (queryMutualRoomsSupport) {\n path = \"/uk.half-shot.msc2666/user/mutual_rooms\";\n query = { user_id: userId };\n } else {\n path = utils.encodeUri(\n `/uk.half-shot.msc2666/user/${mutualRoomsSupport ? \"mutual_rooms\" : \"shared_rooms\"}/$userId`,\n { $userId: userId },\n );\n query = {};\n }\n\n // Accumulated rooms\n const rooms: string[] = [];\n let token = null;\n\n do {\n const tokenQuery: Record<string, string> = {};\n if (token != null && queryMutualRoomsSupport) {\n tokenQuery[\"batch_token\"] = token;\n }\n\n const res = await this.http.authedRequest<{\n joined: string[];\n next_batch_token?: string;\n }>(Method.Get, path, { ...query, ...tokenQuery }, undefined, {\n prefix: ClientPrefix.Unstable,\n });\n\n rooms.push(...res.joined);\n\n if (res.next_batch_token !== undefined) {\n token = res.next_batch_token;\n } else {\n token = null;\n }\n } while (token != null);\n\n return rooms;\n }\n\n /**\n * Get the API versions supported by the server, along with any\n * unstable APIs it supports\n * @returns The server /versions response\n */\n public async getVersions(): Promise<IServerVersions> {\n if (this.serverVersionsPromise) {\n return this.serverVersionsPromise;\n }\n\n // We send an authenticated request as of MSC4026\n this.serverVersionsPromise = this.http\n .authedRequest<IServerVersions>(Method.Get, \"/_matrix/client/versions\", undefined, undefined, {\n prefix: \"\",\n })\n .catch((e) => {\n // Need to unset this if it fails, otherwise we'll never retry\n this.serverVersionsPromise = undefined;\n // but rethrow the exception to anything that was waiting\n throw e;\n });\n\n const serverVersions = await this.serverVersionsPromise;\n this.canSupport = await buildFeatureSupportMap(serverVersions);\n\n return this.serverVersionsPromise;\n }\n\n /**\n * Check if a particular spec version is supported by the server.\n * @param version - The spec version (such as \"r0.5.0\") to check for.\n * @returns Whether it is supported\n */\n public async isVersionSupported(version: string): Promise<boolean> {\n const { versions } = await this.getVersions();\n return versions && versions.includes(version);\n }\n\n /**\n * Query the server to see if it lists support for an unstable feature\n * in the /versions response\n * @param feature - the feature name\n * @returns true if the feature is supported\n */\n public async doesServerSupportUnstableFeature(feature: string): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n return unstableFeatures && !!unstableFeatures[feature];\n }\n\n /**\n * Query the server to see if it is forcing encryption to be enabled for\n * a given room preset, based on the /versions response.\n * @param presetName - The name of the preset to check.\n * @returns true if the server is forcing encryption\n * for the preset.\n */\n public async doesServerForceEncryptionForPreset(presetName: Preset): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n\n // The preset name in the versions response will be without the _chat suffix.\n const versionsPresetName = presetName.includes(\"_chat\")\n ? presetName.substring(0, presetName.indexOf(\"_chat\"))\n : presetName;\n\n return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`];\n }\n\n public async doesServerSupportThread(): Promise<{\n threads: FeatureSupport;\n list: FeatureSupport;\n fwdPagination: FeatureSupport;\n }> {\n if (await this.isVersionSupported(\"v1.4\")) {\n return {\n threads: FeatureSupport.Stable,\n list: FeatureSupport.Stable,\n fwdPagination: FeatureSupport.Stable,\n };\n }\n\n try {\n const [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] =\n await Promise.all([\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715.stable\"),\n ]);\n\n return {\n threads: determineFeatureSupport(threadStable, threadUnstable),\n list: determineFeatureSupport(listStable, listUnstable),\n fwdPagination: determineFeatureSupport(fwdPaginationStable, fwdPaginationUnstable),\n };\n } catch {\n return {\n threads: FeatureSupport.None,\n list: FeatureSupport.None,\n fwdPagination: FeatureSupport.None,\n };\n }\n }\n\n /**\n * Get if lazy loading members is being used.\n * @returns Whether or not members are lazy loaded by this client\n */\n public hasLazyLoadMembersEnabled(): boolean {\n return !!this.clientOpts?.lazyLoadMembers;\n }\n\n /**\n * Set a function which is called when /sync returns a 'limited' response.\n * It is called with a room ID and returns a boolean. It should return 'true' if the SDK\n * can SAFELY remove events from this room. It may not be safe to remove events if there\n * are other references to the timelines for this room, e.g because the client is\n * actively viewing events in this room.\n * Default: returns false.\n * @param cb - The callback which will be invoked.\n */\n public setCanResetTimelineCallback(cb: ResetTimelineCallback): void {\n this.canResetTimelineCallback = cb;\n }\n\n /**\n * Get the callback set via `setCanResetTimelineCallback`.\n * @returns The callback or null\n */\n public getCanResetTimelineCallback(): ResetTimelineCallback | undefined {\n return this.canResetTimelineCallback;\n }\n\n /**\n * Returns relations for a given event. Handles encryption transparently,\n * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.\n * When the returned promise resolves, all messages should have finished trying to decrypt.\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.\n */\n public async relations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<{\n originalEvent?: MatrixEvent | null;\n events: MatrixEvent[];\n nextBatch?: string | null;\n prevBatch?: string | null;\n }> {\n const fetchedEventType = eventType ? this.getEncryptedIfNeededEventType(roomId, eventType) : null;\n const [eventResult, result] = await Promise.all([\n this.fetchRoomEvent(roomId, eventId),\n this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts),\n ]);\n const mapper = this.getEventMapper();\n\n const originalEvent = eventResult ? mapper(eventResult) : undefined;\n let events = result.chunk.map(mapper);\n\n if (fetchedEventType === EventType.RoomMessageEncrypted) {\n if (eventType !== null) {\n events = events.filter((e) => e.getType() === eventType);\n }\n }\n\n if (originalEvent && relationType === RelationType.Replace) {\n events = events.filter((e) => e.getSender() === originalEvent.getSender());\n }\n return {\n originalEvent: originalEvent ?? null,\n events,\n nextBatch: result.next_batch ?? null,\n prevBatch: result.prev_batch ?? null,\n };\n }\n\n /**\n * Generates a random string suitable for use as a client secret. <strong>This\n * method is experimental and may change.</strong>\n * @returns A new client secret\n */\n public generateClientSecret(): string {\n return randomString(32);\n }\n\n /**\n * Attempts to decrypt an event\n * @param event - The event to decrypt\n * @returns A decryption promise\n */\n public decryptEventIfNeeded(event: MatrixEvent, options?: IDecryptOptions): Promise<void> {\n return Promise.resolve();\n }\n\n private termsUrlForService(serviceType: SERVICE_TYPES, baseUrl: string): URL {\n switch (serviceType) {\n case SERVICE_TYPES.IS:\n return this.http.getUrl(\"/terms\", undefined, IdentityPrefix.V2, baseUrl);\n case SERVICE_TYPES.IM:\n return this.http.getUrl(\"/terms\", undefined, \"/_matrix/integrations/v1\", baseUrl);\n default:\n throw new Error(\"Unsupported service type\");\n }\n }\n\n /**\n * Get the Homeserver URL of this client\n * @returns Homeserver URL of this client\n */\n public getHomeserverUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get the identity server URL of this client\n * @param stripProto - whether or not to strip the protocol from the URL\n * @returns Identity server URL of this client\n */\n public getIdentityServerUrl(stripProto = false): string | undefined {\n if (stripProto && (this.idBaseUrl?.startsWith(\"http://\") || this.idBaseUrl?.startsWith(\"https://\"))) {\n return this.idBaseUrl.split(\"://\")[1];\n }\n return this.idBaseUrl;\n }\n\n /**\n * Set the identity server URL of this client\n * @param url - New identity server URL\n */\n public setIdentityServerUrl(url?: string): void {\n this.idBaseUrl = utils.ensureNoTrailingSlash(url);\n this.http.setIdBaseUrl(this.idBaseUrl);\n }\n\n /**\n * Get the access token associated with this account.\n * @returns The access_token or null\n */\n public getAccessToken(): string | null {\n return this.http.opts.accessToken || null;\n }\n\n /**\n * Get the refresh token associated with this account.\n * @returns The refresh_token or null\n */\n public getRefreshToken(): string | null {\n return this.http.opts.refreshToken ?? null;\n }\n\n /**\n * Set the access token associated with this account.\n * @param token - The new access token.\n */\n public setAccessToken(token: string): void {\n this.http.opts.accessToken = token;\n // The /versions response can vary for different users so clear the cache\n this.serverVersionsPromise = undefined;\n }\n\n /**\n * @returns true if there is a valid access_token for this client.\n */\n public isLoggedIn(): boolean {\n return this.http.opts.accessToken !== undefined;\n }\n\n /**\n * Make up a new transaction id\n *\n * @returns a new, unique, transaction id\n */\n public makeTxnId(): string {\n return \"m\" + new Date().getTime() + \".\" + this.txnCtr++;\n }\n\n /**\n * Check whether a username is available prior to registration. An error response\n * indicates an invalid/unavailable username.\n * @param username - The username to check the availability of.\n * @returns Promise which resolves: to boolean of whether the username is available.\n */\n public isUsernameAvailable(username: string): Promise<boolean> {\n return this.http\n .authedRequest<{ available: true }>(Method.Get, \"/register/available\", { username })\n .then((response) => {\n return response.available;\n })\n .catch((response) => {\n if (response.errcode === \"M_USER_IN_USE\") {\n return false;\n }\n return Promise.reject(response);\n });\n }\n\n /**\n * @param bindThreepids - Set key 'email' to true to bind any email\n * threepid uses during registration in the identity server. Set 'msisdn' to\n * true to bind msisdn.\n * @returns Promise which resolves to a RegisterResponse object\n * @returns Rejects: with an error response.\n */\n public register(\n username: string,\n password: string,\n sessionId: string | null,\n auth: { session?: string; type: string },\n bindThreepids?: { email?: boolean; msisdn?: boolean },\n guestAccessToken?: string,\n inhibitLogin?: boolean,\n ): Promise<RegisterResponse> {\n if (sessionId) {\n auth.session = sessionId;\n }\n\n const params: RegisterRequest = {\n auth: auth,\n refresh_token: true, // always ask for a refresh token - does nothing if unsupported\n };\n if (username !== undefined && username !== null) {\n params.username = username;\n }\n if (password !== undefined && password !== null) {\n params.password = password;\n }\n if (guestAccessToken !== undefined && guestAccessToken !== null) {\n params.guest_access_token = guestAccessToken;\n }\n if (inhibitLogin !== undefined && inhibitLogin !== null) {\n params.inhibit_login = inhibitLogin;\n }\n\n return this.registerRequest(params);\n }\n\n /**\n * Register a guest account.\n * This method returns the auth info needed to create a new authenticated client,\n * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:\n * ```javascript\n * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);\n * const { user_id, device_id, access_token } = tmpClient.registerGuest();\n * const client = createClient({\n * baseUrl: MATRIX_INSTANCE,\n * accessToken: access_token,\n * userId: user_id,\n * deviceId: device_id,\n * })\n * client.setGuest(true);\n * ```\n *\n * @param body - JSON HTTP body to provide.\n * @returns Promise which resolves: JSON object that contains:\n * `{ user_id, device_id, access_token, home_server }`\n * @returns Rejects: with an error response.\n */\n public registerGuest({ body }: { body?: RegisterRequest } = {}): Promise<RegisterResponse> {\n return this.registerRequest(body || {}, \"guest\");\n }\n\n /**\n * @param data - parameters for registration request\n * @param kind - type of user to register. may be \"guest\"\n * @returns Promise which resolves: to the /register response\n * @returns Rejects: with an error response.\n */\n public registerRequest(data: RegisterRequest, kind?: string): Promise<RegisterResponse> {\n const params: { kind?: string } = {};\n if (kind) {\n params.kind = kind;\n }\n\n return this.http.request(Method.Post, \"/register\", params, data);\n }\n\n /**\n * Refreshes an access token using a provided refresh token. The refresh token\n * must be valid for the current access token known to the client instance.\n *\n * Note that this function will not cause a logout if the token is deemed\n * unknown by the server - the caller is responsible for managing logout\n * actions on error.\n * @param refreshToken - The refresh token.\n * @returns Promise which resolves to the new token.\n * @returns Rejects with an error response.\n */\n public refreshToken(refreshToken: string): Promise<IRefreshTokenResponse> {\n const performRefreshRequestWithPrefix = (prefix: ClientPrefix): Promise<IRefreshTokenResponse> =>\n this.http.authedRequest(\n Method.Post,\n \"/refresh\",\n undefined,\n { refresh_token: refreshToken },\n {\n prefix,\n inhibitLogoutEmit: true, // we don't want to cause logout loops\n },\n );\n\n // First try with the (specced) /v3/ prefix.\n // However, before Synapse 1.72.0, Synapse incorrectly required a /v1/ prefix, so we fall\n // back to that if the request fails, for backwards compatibility.\n return performRefreshRequestWithPrefix(ClientPrefix.V3).catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n return performRefreshRequestWithPrefix(ClientPrefix.V1);\n }\n throw e;\n });\n }\n\n /**\n * @returns Promise which resolves to the available login flows\n * @returns Rejects: with an error response.\n */\n public loginFlows(): Promise<ILoginFlowsResponse> {\n return this.http.request(Method.Get, \"/login\");\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public login(loginType: LoginRequest[\"type\"], data: Omit<LoginRequest, \"type\">): Promise<LoginResponse> {\n return this.http\n .authedRequest<LoginResponse>(Method.Post, \"/login\", undefined, {\n ...data,\n type: loginType,\n })\n .then((response) => {\n if (response.access_token && response.user_id) {\n this.http.opts.accessToken = response.access_token;\n this.credentials = {\n userId: response.user_id,\n };\n }\n return response;\n });\n }\n\n /**\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithPassword(user: string, password: string): Promise<LoginResponse> {\n return this.login(\"m.login.password\", {\n user: user,\n password: password,\n });\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with CAS.\n * @returns The HS URL to hit to begin the CAS login process.\n */\n public getCasLoginUrl(redirectUrl: string): string {\n return this.getSsoLoginUrl(redirectUrl, \"cas\");\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with the SSO.\n * @param loginType - The type of SSO login we are doing (sso or cas).\n * Defaults to 'sso'.\n * @param idpId - The ID of the Identity Provider being targeted, optional.\n * @param action - the SSO flow to indicate to the IdP, optional.\n * @returns The HS URL to hit to begin the SSO login process.\n */\n public getSsoLoginUrl(redirectUrl: string, loginType = \"sso\", idpId?: string, action?: SSOAction): string {\n let url = \"/login/\" + loginType + \"/redirect\";\n if (idpId) {\n url += \"/\" + idpId;\n }\n\n const params = {\n redirectUrl,\n [SSO_ACTION_PARAM.unstable!]: action,\n };\n\n return this.http.getUrl(url, params).href;\n }\n\n /**\n * @param token - Login token previously received from homeserver\n * @returns Promise which resolves to a LoginResponse object\n * @returns Rejects: with an error response.\n */\n public loginWithToken(token: string): Promise<LoginResponse> {\n return this.login(\"m.login.token\", {\n token: token,\n });\n }\n\n /**\n * Logs out the current session.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param stopClient - whether to stop the client before calling /logout to prevent invalid token errors.\n * @returns Promise which resolves: On success, the empty object `{}`\n */\n public async logout(stopClient = false): Promise<{}> {\n if (stopClient) {\n this.stopClient();\n this.http.abort();\n }\n\n return this.http.authedRequest(Method.Post, \"/logout\");\n }\n\n /**\n * Deactivates the logged-in account.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @param erase - Optional. If set, send as `erase` attribute in the\n * JSON request body, indicating whether the account should be erased. Defaults\n * to false.\n * @returns Promise which resolves: On success, the empty object\n */\n public deactivateAccount(\n auth?: AuthDict,\n erase?: boolean,\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const body: Body = {};\n if (auth) {\n body.auth = auth;\n }\n if (erase !== undefined) {\n body.erase = erase;\n }\n\n return this.http.authedRequest(Method.Post, \"/account/deactivate\", undefined, body);\n }\n\n /**\n * Make a request for an `m.login.token` to be issued as per\n * https://spec.matrix.org/v1.7/client-server-api/#post_matrixclientv1loginget_token\n *\n * The server may require User-Interactive auth.\n *\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: On success, the token response\n * or UIA auth data.\n */\n public async requestLoginToken(auth?: AuthDict): Promise<UIAResponse<LoginTokenPostResponse>> {\n const body: UIARequest<{}> = { auth };\n return this.http.authedRequest<UIAResponse<LoginTokenPostResponse>>(\n Method.Post,\n \"/login/get_token\",\n undefined, // no query params\n body,\n { prefix: ClientPrefix.V1 },\n );\n }\n\n /**\n * Get the fallback URL to use for unknown interactive-auth stages.\n *\n * @param loginType - the type of stage being attempted\n * @param authSessionId - the auth session ID provided by the homeserver\n *\n * @returns HS URL to hit to for the fallback interface\n */\n public getFallbackAuthUrl(loginType: string, authSessionId: string): string {\n const path = utils.encodeUri(\"/auth/$loginType/fallback/web\", {\n $loginType: loginType,\n });\n\n return this.http.getUrl(path, {\n session: authSessionId,\n }).href;\n }\n\n /**\n * Create a new room.\n * @param options - a list of options to pass to the /createRoom API.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public async createRoom(options: ICreateRoomOpts): Promise<{ room_id: string }> {\n // eslint-disable-line camelcase\n // some valid options include: room_alias_name, visibility, invite\n\n // inject the id_access_token if inviting 3rd party addresses\n const invitesNeedingToken = (options.invite_3pid || []).filter((i) => !i.id_access_token);\n if (invitesNeedingToken.length > 0 && this.identityServer?.getAccessToken) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n for (const invite of invitesNeedingToken) {\n invite.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.authedRequest(Method.Post, \"/createRoom\", undefined, options);\n }\n\n /**\n * Fetches relations for a given event\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns the response, with chunk, prev_batch and, next_batch.\n */\n public fetchRelations(\n roomId: string,\n eventId: string,\n relationType: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<IRelationsResponse> {\n let params = opts as QueryDict;\n if (Thread.hasServerSideFwdPaginationSupport === FeatureSupport.Experimental) {\n params = replaceParam(\"dir\", \"org.matrix.msc3715.dir\", params);\n }\n if (this.canSupport.get(Feature.RelationsRecursion) === ServerSupport.Unstable) {\n params = replaceParam(\"recurse\", \"org.matrix.msc3981.recurse\", params);\n }\n const queryString = utils.encodeParams(params);\n\n let templatedUrl = \"/rooms/$roomId/relations/$eventId\";\n if (relationType !== null) {\n templatedUrl += \"/$relationType\";\n if (eventType !== null) {\n templatedUrl += \"/$eventType\";\n }\n } else if (eventType !== null) {\n this.logger.warn(`eventType: ${eventType} ignored when fetching\n relations as relationType is null`);\n eventType = null;\n }\n\n const path = utils.encodeUri(templatedUrl + \"?\" + queryString, {\n $roomId: roomId,\n $eventId: eventId,\n $relationType: relationType!,\n $eventType: eventType!,\n });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n prefix: ClientPrefix.V1,\n });\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomState(roomId: string): Promise<IStateEventWithRoomId[]> {\n const path = utils.encodeUri(\"/rooms/$roomId/state\", { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get an event in a room by its event id.\n *\n * @returns Promise which resolves to an object containing the event.\n * @returns Rejects: with an error response.\n */\n public fetchRoomEvent(roomId: string, eventId: string): Promise<Partial<IEvent>> {\n const path = utils.encodeUri(\"/rooms/$roomId/event/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param includeMembership - the membership type to include in the response\n * @param excludeMembership - the membership type to exclude from the response\n * @param atEventId - the id of the event for which moment in the timeline the members should be returned for\n * @returns Promise which resolves: dictionary of userid to profile information\n * @returns Rejects: with an error response.\n */\n public members(\n roomId: string,\n includeMembership?: string,\n excludeMembership?: string,\n atEventId?: string,\n ): Promise<{ [userId: string]: IStateEventWithRoomId[] }> {\n const queryParams: Record<string, string> = {};\n if (includeMembership) {\n queryParams.membership = includeMembership;\n }\n if (excludeMembership) {\n queryParams.not_membership = excludeMembership;\n }\n if (atEventId) {\n queryParams.at = atEventId;\n }\n\n const queryString = utils.encodeParams(queryParams);\n\n const path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString, { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Upgrades a room to a new protocol version\n * @param newVersion - The target version to upgrade to\n * @returns Promise which resolves: Object with key 'replacement_room'\n * @returns Rejects: with an error response.\n */\n public upgradeRoom(roomId: string, newVersion: string): Promise<{ replacement_room: string }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/rooms/$roomId/upgrade\", { $roomId: roomId });\n return this.http.authedRequest(Method.Post, path, undefined, { new_version: newVersion });\n }\n\n /**\n * Retrieve a state event.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getStateEvent(roomId: string, eventType: string, stateKey: string): Promise<Record<string, any>> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Send a state event into a room\n * @param roomId - ID of the room to send the event into\n * @param eventType - type of the state event to send\n * @param content - content of the event to send\n * @param stateKey - the stateKey to send into the room\n * @param opts - Options for the request function.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public sendStateEvent<K extends keyof StateEvents>(\n roomId: string,\n eventType: K,\n content: StateEvents[K],\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise<ISendEventResponse> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, undefined, content as Body, opts);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomInitialSync(roomId: string, limit: number): Promise<IRoomInitialSyncResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/initialSync\", { $roomId: roomId });\n\n return this.http.authedRequest(Method.Get, path, { limit: limit?.toString() ?? \"30\" });\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEventId - ID of the event tracked by the read receipt. This is here\n * for convenience because the RR and the RM are commonly updated at the same time as\n * each other. Optional.\n * @param rpEventId - rpEvent the m.read.private read receipt event for when we\n * don't want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkersHttpRequest(\n roomId: string,\n rmEventId: string,\n rrEventId?: string,\n rpEventId?: string,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/read_markers\", {\n $roomId: roomId,\n });\n\n const content: IContent = {\n [ReceiptType.FullyRead]: rmEventId,\n [ReceiptType.Read]: rrEventId,\n };\n\n if (\n (await this.doesServerSupportUnstableFeature(\"org.matrix.msc2285.stable\")) ||\n (await this.isVersionSupported(\"v1.4\"))\n ) {\n content[ReceiptType.ReadPrivate] = rpEventId;\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * @returns Promise which resolves: A list of the user's current rooms\n * @returns Rejects: with an error response.\n */\n public getJoinedRooms(): Promise<IJoinedRoomsResponse> {\n const path = utils.encodeUri(\"/joined_rooms\", {});\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve membership info. for a room.\n * @param roomId - ID of the room to get membership for\n * @returns Promise which resolves: A list of currently joined users\n * and their profile data.\n * @returns Rejects: with an error response.\n */\n public getJoinedRoomMembers(roomId: string): Promise<IJoinedMembersResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/joined_members\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param params - Options for this request\n * @returns Promise which resolves: IPublicRoomsResponse\n * @returns Rejects: with an error response.\n */\n public publicRooms({\n server,\n limit,\n since,\n ...options\n }: IRoomDirectoryOptions = {}): Promise<IPublicRoomsResponse> {\n if (Object.keys(options).length === 0) {\n const queryParams: QueryDict = { server, limit, since };\n return this.http.authedRequest(Method.Get, \"/publicRooms\", queryParams);\n } else {\n const queryParams: QueryDict = { server };\n const body = {\n limit,\n since,\n ...options,\n };\n return this.http.authedRequest(Method.Post, \"/publicRooms\", queryParams, body);\n }\n }\n\n /**\n * Create an alias to room ID mapping.\n * @param alias - The room alias to create.\n * @param roomId - The room ID to link the alias to.\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public createAlias(alias: string, roomId: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n const data = {\n room_id: roomId,\n };\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Delete an alias to room ID mapping. This alias must be on your local server,\n * and you must have sufficient access to do this operation.\n * @param alias - The room alias to delete.\n * @returns Promise which resolves: an empty object `{}`.\n * @returns Rejects: with an error response.\n */\n public deleteAlias(alias: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Gets the local aliases for the room. Note: this includes all local aliases, unlike the\n * curated list from the m.room.canonical_alias state event.\n * @param roomId - The room ID to get local aliases for.\n * @returns Promise which resolves: an object with an `aliases` property, containing an array of local aliases\n * @returns Rejects: with an error response.\n */\n public getLocalAliases(roomId: string): Promise<{ aliases: string[] }> {\n const path = utils.encodeUri(\"/rooms/$roomId/aliases\", { $roomId: roomId });\n const prefix = ClientPrefix.V3;\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix });\n }\n\n /**\n * Get room info for the given alias.\n * @param alias - The room alias to resolve.\n * @returns Promise which resolves: Object with room_id and servers.\n * @returns Rejects: with an error response.\n */\n public getRoomIdForAlias(alias: string): Promise<{ room_id: string; servers: string[] }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get the visibility of a room in the current HS's room directory\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getRoomDirectoryVisibility(roomId: string): Promise<{ visibility: Visibility }> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Set the visibility of a room in the current HS's room directory\n * @param visibility - \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomDirectoryVisibility(roomId: string, visibility: Visibility): Promise<{}> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { visibility });\n }\n\n /**\n * Query the user directory with a term matching user IDs, display names and domains.\n * @param options\n * @param options.term - the term with which to search.\n * @param options.limit - the maximum number of results to return. The server will apply a limit if unspecified.\n * @returns Promise which resolves: an array of results.\n */\n public searchUserDirectory({ term, limit }: { term: string; limit?: number }): Promise<IUserDirectoryResponse> {\n const body: Body = {\n search_term: term,\n };\n\n if (limit !== undefined) {\n body.limit = limit;\n }\n\n return this.http.authedRequest(Method.Post, \"/user_directory/search\", undefined, body);\n }\n\n /**\n * Upload a file to the media repository on the homeserver.\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n public uploadContent(file: FileType, opts?: UploadOpts): Promise<UploadResponse> {\n return this.http.uploadContent(file, opts);\n }\n\n /**\n * Cancel a file upload in progress\n * @param upload - The object returned from uploadContent\n * @returns true if canceled, otherwise false\n */\n public cancelUpload(upload: Promise<UploadResponse>): boolean {\n return this.http.cancelUpload(upload);\n }\n\n /**\n * Get a list of all file uploads in progress\n * @returns Array of objects representing current uploads.\n * Currently in progress is element 0. Keys:\n * - promise: The promise associated with the upload\n * - loaded: Number of bytes uploaded\n * - total: Total number of bytes to upload\n */\n public getCurrentUploads(): Upload[] {\n return this.http.getCurrentUploads();\n }\n\n /**\n * @param info - The kind of info to retrieve (e.g. 'displayname',\n * 'avatar_url').\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getProfileInfo(\n userId: string,\n info?: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ avatar_url?: string; displayname?: string }> {\n const path = info\n ? utils.encodeUri(\"/profile/$userId/$info\", { $userId: userId, $info: info })\n : utils.encodeUri(\"/profile/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Determine if the server supports extended profiles, as described by MSC4133.\n *\n * @returns `true` if supported, otherwise `false`\n */\n public async doesServerSupportExtendedProfiles(): Promise<boolean> {\n return this.doesServerSupportUnstableFeature(UNSTABLE_MSC4133_EXTENDED_PROFILES);\n }\n\n /**\n * Get the prefix used for extended profile requests.\n *\n * @returns The prefix for use with `authedRequest`\n */\n private async getExtendedProfileRequestPrefix(): Promise<string> {\n if (await this.doesServerSupportUnstableFeature(\"uk.tcpip.msc4133.stable\")) {\n return ClientPrefix.V3;\n }\n return \"/_matrix/client/unstable/uk.tcpip.msc4133\";\n }\n\n /**\n * Fetch a user's *extended* profile, which may include additonal keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @returns A set of keys to property values.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the profile could not be found.\n */\n public async getExtendedProfile(userId: string): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n return this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Fetch a specific key from the user's *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param userId The user ID to fetch the profile of.\n * @param key The key of the property to fetch.\n * @returns The property value.\n *\n * @throws An error if the server does not support MSC4133.\n * @throws A M_NOT_FOUND error if the key was not set OR the profile could not be found.\n */\n public async getExtendedProfileProperty(userId: string, key: string): Promise<unknown> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const profile = (await this.http.authedRequest(\n Method.Get,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n )) as Record<string, unknown>;\n return profile[key];\n }\n\n /**\n * Set a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to set.\n * @param value The value to set on the propety.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfileProperty(key: string, value: unknown): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n { [key]: value },\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Delete a property on your *extended* profile.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param key The key of the property to delete.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async deleteExtendedProfileProperty(key: string): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Delete,\n utils.encodeUri(\"/profile/$userId/$key\", { $userId: userId, $key: key }),\n undefined,\n undefined,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Update multiple properties on your *extended* profile. This will\n * merge with any existing keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to merge with the existing profile.\n * @returns The newly merged profile.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async patchExtendedProfile(profile: Record<string, unknown>): Promise<Record<string, unknown>> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n return this.http.authedRequest(\n Method.Patch,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * Set multiple properties on your *extended* profile. This will completely\n * replace the existing profile, removing any unspecified keys.\n *\n * @see https://github.com/tcpipuk/matrix-spec-proposals/blob/main/proposals/4133-extended-profiles.md\n * @param profile The profile object to set.\n *\n * @throws An error if the server does not support MSC4133 OR the server disallows editing the user profile.\n */\n public async setExtendedProfile(profile: Record<string, unknown>): Promise<void> {\n if (!(await this.doesServerSupportExtendedProfiles())) {\n throw new Error(\"Server does not support extended profiles\");\n }\n const userId = this.getUserId();\n\n await this.http.authedRequest(\n Method.Put,\n utils.encodeUri(\"/profile/$userId\", { $userId: userId }),\n {},\n profile,\n {\n prefix: await this.getExtendedProfileRequestPrefix(),\n },\n );\n }\n\n /**\n * @returns Promise which resolves to a list of the user's threepids.\n * @returns Rejects: with an error response.\n */\n public getThreePids(): Promise<{ threepids: IThreepid[] }> {\n return this.http.authedRequest(Method.Get, \"/account/3pid\");\n }\n\n /**\n * Add a 3PID to your homeserver account. This API does not use an identity\n * server, as the homeserver is expected to handle 3PID ownership validation.\n *\n * @param data - A object with 3PID validation data from having called\n * `account/3pid/<medium>/requestToken` on the homeserver.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async addThreePidOnly(data: IAddThreePidOnlyBody): Promise<{}> {\n const path = \"/account/3pid/add\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Bind a 3PID for discovery onto an identity server via the homeserver. The\n * identity server handles 3PID ownership validation and the homeserver records\n * the new binding to track where all 3PIDs for the account are bound.\n *\n * @param data - A object with 3PID validation data from having called\n * `validate/<medium>/requestToken` on the identity server. It should also\n * contain `id_server` and `id_access_token` fields as well.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async bindThreePid(data: IBindThreePidBody): Promise<{}> {\n const path = \"/account/3pid/bind\";\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Unbind a 3PID for discovery on an identity server via the homeserver. The\n * homeserver removes its record of the binding to keep an updated record of\n * where all 3PIDs for the account are bound.\n *\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: on success\n * @returns Rejects: with an error response.\n */\n public async unbindThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/unbind\";\n const data = {\n medium,\n address,\n id_server: this.getIdentityServerUrl(true),\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: The server response on success\n * (generally the empty JSON object)\n * @returns Rejects: with an error response.\n */\n public deleteThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/delete\";\n return this.http.authedRequest(Method.Post, path, undefined, { medium, address });\n }\n\n /**\n * Make a request to change your password.\n * @param newPassword - The new desired password.\n * @param logoutDevices - Should all sessions be logged out after the password change. Defaults to true.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPassword(authDict: AuthDict, newPassword: string, logoutDevices?: boolean): Promise<{}> {\n const path = \"/account/password\";\n const data = {\n auth: authDict,\n new_password: newPassword,\n logout_devices: logoutDevices,\n };\n\n return this.http.authedRequest<{}>(Method.Post, path, undefined, data);\n }\n\n /**\n * Gets all devices recorded for the logged-in user\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevices(): Promise<{ devices: IMyDevice[] }> {\n return this.http.authedRequest(Method.Get, \"/devices\");\n }\n\n /**\n * Gets specific device details for the logged-in user\n * @param deviceId - device to query\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevice(deviceId: string): Promise<IMyDevice> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Update the given device\n *\n * @param deviceId - device to update\n * @param body - body of request\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setDeviceDetails(deviceId: string, body: { display_name: string }): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Delete the given device\n *\n * @param deviceId - device to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteDevice(deviceId: string, auth?: AuthDict): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n const body: Body = {};\n\n if (auth) {\n body.auth = auth;\n }\n\n return this.http.authedRequest(Method.Delete, path, undefined, body);\n }\n\n /**\n * Delete multiple device\n *\n * @param devices - IDs of the devices to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteMultipleDevices(devices: string[], auth?: AuthDict): Promise<{}> {\n const body: Body = { devices };\n\n if (auth) {\n body.auth = auth;\n }\n\n const path = \"/delete_devices\";\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Gets all pushers registered for the logged-in user\n *\n * @returns Promise which resolves: Array of objects representing pushers\n * @returns Rejects: with an error response.\n */\n public async getPushers(): Promise<{ pushers: IPusher[] }> {\n const response = await this.http.authedRequest<{ pushers: IPusher[] }>(Method.Get, \"/pushers\");\n\n // Migration path for clients that connect to a homeserver that does not support\n // MSC3881 yet, see https://github.com/matrix-org/matrix-spec-proposals/blob/kerry/remote-push-toggle/proposals/3881-remote-push-notification-toggling.md#migration\n if (!(await this.doesServerSupportUnstableFeature(\"org.matrix.msc3881\"))) {\n response.pushers = response.pushers.map((pusher) => {\n if (!pusher.hasOwnProperty(PUSHER_ENABLED.name)) {\n pusher[PUSHER_ENABLED.name] = true;\n }\n return pusher;\n });\n }\n\n return response;\n }\n\n /**\n * Adds a new pusher or updates an existing pusher\n *\n * @param pusher - Object representing a pusher\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public setPusher(pusher: IPusherRequest): Promise<{}> {\n const path = \"/pushers/set\";\n return this.http.authedRequest(Method.Post, path, undefined, pusher);\n }\n\n /**\n * Removes an existing pusher\n * @param pushKey - pushkey of pusher to remove\n * @param appId - app_id of pusher to remove\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public removePusher(pushKey: string, appId: string): Promise<{}> {\n const path = \"/pushers/set\";\n const body = {\n pushkey: pushKey,\n app_id: appId,\n kind: null, // marks pusher for removal\n };\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Persists local notification settings\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setLocalNotificationSettings(\n deviceId: string,\n notificationSettings: LocalNotificationSettings,\n ): Promise<{}> {\n const key = `${LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${deviceId}`;\n return this.setAccountData(key, notificationSettings);\n }\n\n /**\n * Get the push rules for the account from the server.\n * @returns Promise which resolves to the push rules.\n * @returns Rejects: with an error response.\n */\n public getPushRules(): Promise<IPushRules> {\n return this.http.authedRequest<IPushRules>(Method.Get, \"/pushrules/\").then((rules: IPushRules) => {\n this.setPushRules(rules);\n return this.pushRules!;\n });\n }\n\n /**\n * Update the push rules for the account. This should be called whenever\n * updated push rules are available.\n */\n public setPushRules(rules: IPushRules): void {\n // Fix-up defaults, if applicable.\n this.pushRules = PushProcessor.rewriteDefaultRules(rules, this.getUserId()!);\n // Pre-calculate any necessary caches.\n this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public addPushRule(\n scope: string,\n kind: PushRuleKind,\n ruleId: Exclude<string, RuleId>,\n body: Pick<IPushRule, \"actions\" | \"conditions\" | \"pattern\">,\n ): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public deletePushRule(scope: string, kind: PushRuleKind, ruleId: Exclude<string, RuleId>): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Enable or disable a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleEnabled(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n enabled: boolean,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/enabled\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { enabled: enabled });\n }\n\n /**\n * Set the actions for a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleActions(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n actions: PushRuleAction[],\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/actions\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { actions: actions });\n }\n\n /**\n * Perform a server-side search.\n * @param params\n * @param params.next_batch - the batch token to pass in the query string\n * @param params.body - the JSON object to pass to the request body.\n * @param abortSignal - optional signal used to cancel the http request.\n * @returns Promise which resolves to the search response object.\n * @returns Rejects: with an error response.\n */\n public search(\n { body, next_batch: nextBatch }: { body: ISearchRequestBody; next_batch?: string },\n abortSignal?: AbortSignal,\n ): Promise<ISearchResponse> {\n const queryParams: QueryDict = {};\n if (nextBatch) {\n queryParams.next_batch = nextBatch;\n }\n return this.http.authedRequest(Method.Post, \"/search\", queryParams, body, { abortSignal });\n }\n\n /**\n * Ask the server for a list of users who have changed their device lists\n * between a pair of sync tokens\n *\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public getKeyChanges(oldToken: string, newToken: string): Promise<{ changed: string[]; left: string[] }> {\n const qps = {\n from: oldToken,\n to: newToken,\n };\n\n return this.http.authedRequest(Method.Get, \"/keys/changes\", qps);\n }\n\n /**\n * Register with an identity server using the OpenID token from the user's\n * Homeserver, which can be retrieved via\n * {@link MatrixClient#getOpenIdToken}.\n *\n * Note that the `/account/register` endpoint (as well as IS authentication in\n * general) was added as part of the v2 API version.\n *\n * @returns Promise which resolves: with object containing an Identity\n * Server access token.\n * @returns Rejects: with an error response.\n */\n public registerWithIdentityServer(hsOpenIdToken: IOpenIDToken): Promise<{\n access_token: string;\n token: string;\n }> {\n if (!this.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n const uri = this.http.getUrl(\"/account/register\", undefined, IdentityPrefix.V2, this.idBaseUrl);\n return this.http.requestOtherUrl(Method.Post, uri, hsOpenIdToken);\n }\n\n /**\n * Requests an email verification token directly from an identity server.\n *\n * This API is used as part of binding an email for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param email - The email address to request a token for\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another email.\n * To request another email to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the identity\n * server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n email: email,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestTokenResponse>(\n Method.Post,\n \"/validate/email/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Requests a MSISDN verification token directly from an identity server.\n *\n * This API is used as part of binding a MSISDN for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in\n * which phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international\n * format\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another SMS.\n * To request another SMS to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves to an object with a sid string\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise<IRequestMsisdnTokenResponse> {\n const params: Record<string, string> = {\n client_secret: clientSecret,\n country: phoneCountry,\n phone_number: phoneNumber,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest<IRequestMsisdnTokenResponse>(\n Method.Post,\n \"/validate/msisdn/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to the identity server\n *\n * This is used when submitting the code sent by SMS to a phone number.\n * The identity server has an equivalent API for email but the js-sdk does\n * not expose this, since email is normally validated by the user clicking\n * a link rather than entering a code.\n *\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n * Some legacy identity servers had no authentication here.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n * @throws Error if No identity server is set\n */\n public submitMsisdnToken(\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n identityAccessToken: string | null,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n\n return this.http.idServerRequest(\n Method.Post,\n \"/validate/msisdn/submitToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken ?? undefined,\n );\n }\n\n /**\n * Submits a MSISDN token to an arbitrary URL.\n *\n * This is used when submitting the code sent by SMS to a phone number in the\n * newer 3PID flow where the homeserver validates 3PID ownership (as part of\n * `requestAdd3pidMsisdnToken`). The homeserver response may include a\n * `submit_url` to specify where the token should be sent, and this helper can\n * be used to pass the token to this URL.\n *\n * @param url - The URL to submit the token to\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n *\n * @returns Promise which resolves: Object, containing success boolean.\n * @returns Rejects: with an error response.\n */\n public submitMsisdnTokenOtherUrl(\n url: string,\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n ): Promise<{ success: boolean }> {\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n return this.http.requestOtherUrl(Method.Post, url, params);\n }\n\n /**\n * Gets the V2 hashing information from the identity server. Primarily useful for\n * lookups.\n * @param identityAccessToken - The access token for the identity server.\n * @returns The hashing information for the identity server.\n */\n public getIdentityHashDetails(identityAccessToken: string): Promise<{\n /**\n * The algorithms the server supports. Must contain at least sha256.\n */\n algorithms: string[];\n /**\n * The pepper the client MUST use in hashing identifiers,\n * and MUST supply to the /lookup endpoint when performing lookups.\n */\n lookup_pepper: string;\n }> {\n return this.http.idServerRequest(\n Method.Get,\n \"/hash_details\",\n undefined,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Performs a hashed lookup of addresses against the identity server. This is\n * only supported on identity servers which have at least the version 2 API.\n * @param addressPairs - An array of 2 element arrays.\n * The first element of each pair is the address, the second is the 3PID medium.\n * Eg: `[\"email@example.org\", \"email\"]`\n * @param identityAccessToken - The access token for the identity server.\n * @returns A collection of address mappings to\n * found MXIDs. Results where no user could be found will not be listed.\n */\n public async identityHashedLookup(\n addressPairs: [string, string][],\n identityAccessToken: string,\n ): Promise<{ address: string; mxid: string }[]> {\n const params: Record<string, string | string[]> = {\n // addresses: [\"email@example.org\", \"10005550000\"],\n // algorithm: \"sha256\",\n // pepper: \"abc123\"\n };\n\n // Get hash information first before trying to do a lookup\n const hashes = await this.getIdentityHashDetails(identityAccessToken);\n if (!hashes || !hashes[\"lookup_pepper\"] || !hashes[\"algorithms\"]) {\n throw new Error(\"Unsupported identity server: bad response\");\n }\n\n params[\"pepper\"] = hashes[\"lookup_pepper\"];\n\n const localMapping: Record<string, string> = {\n // hashed identifier => plain text address\n // For use in this function's return format\n };\n\n // When picking an algorithm, we pick the hashed over no hashes\n if (hashes[\"algorithms\"].includes(\"sha256\")) {\n params[\"addresses\"] = await Promise.all(\n addressPairs.map(async (p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const hashBuffer = await sha256(`${addr} ${med} ${params[\"pepper\"]}`);\n const hashed = encodeUnpaddedBase64Url(hashBuffer);\n\n // Map the hash to a known (case-sensitive) address. We use the case\n // sensitive version because the caller might be expecting that.\n localMapping[hashed] = p[0];\n return hashed;\n }),\n );\n params[\"algorithm\"] = \"sha256\";\n } else if (hashes[\"algorithms\"].includes(\"none\")) {\n params[\"addresses\"] = addressPairs.map((p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const unhashed = `${addr} ${med}`;\n // Map the unhashed values to a known (case-sensitive) address. We use\n // the case-sensitive version because the caller might be expecting that.\n localMapping[unhashed] = p[0];\n return unhashed;\n });\n params[\"algorithm\"] = \"none\";\n } else {\n throw new Error(\"Unsupported identity server: unknown hash algorithm\");\n }\n\n const response = await this.http.idServerRequest<{\n mappings: { [address: string]: string };\n }>(Method.Post, \"/lookup\", params, IdentityPrefix.V2, identityAccessToken);\n\n if (!response?.[\"mappings\"]) return []; // no results\n\n const foundAddresses: { address: string; mxid: string }[] = [];\n for (const hashed of Object.keys(response[\"mappings\"])) {\n const mxid = response[\"mappings\"][hashed];\n const plainAddress = localMapping[hashed];\n if (!plainAddress) {\n throw new Error(\"Identity server returned more results than expected\");\n }\n\n foundAddresses.push({ address: plainAddress, mxid });\n }\n return foundAddresses;\n }\n\n /**\n * Looks up the public Matrix ID mapping for a given 3rd party\n * identifier from the identity server\n *\n * @param medium - The medium of the threepid, eg. 'email'\n * @param address - The textual address of the threepid\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: A threepid mapping\n * object or the empty object if no mapping\n * exists\n * @returns Rejects: with an error response.\n */\n public async lookupThreePid(\n medium: string,\n address: string,\n identityAccessToken: string,\n ): Promise<\n | {\n address: string;\n medium: string;\n mxid: string;\n }\n | {}\n > {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup([[address, medium]], identityAccessToken);\n const result = response.find((p) => p.address === address);\n if (!result) {\n return {};\n }\n\n const mapping = {\n address,\n medium,\n mxid: result.mxid,\n\n // We can't reasonably fill these parameters:\n // not_before\n // not_after\n // ts\n // signatures\n };\n\n return mapping;\n }\n\n /**\n * Looks up the public Matrix ID mappings for multiple 3PIDs.\n *\n * @param query - Array of arrays containing\n * [medium, address]\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: Lookup results from IS.\n * @returns Rejects: with an error response.\n */\n public async bulkLookupThreePids(\n query: [string, string][],\n identityAccessToken: string,\n ): Promise<{\n threepids: [medium: string, address: string, mxid: string][];\n }> {\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup(\n // We have to reverse the query order to get [address, medium] pairs\n query.map((p) => [p[1], p[0]]),\n identityAccessToken,\n );\n\n const v1results: [medium: string, address: string, mxid: string][] = [];\n for (const mapping of response) {\n const originalQuery = query.find((p) => p[1] === mapping.address);\n if (!originalQuery) {\n throw new Error(\"Identity sever returned unexpected results\");\n }\n\n v1results.push([\n originalQuery[0], // medium\n mapping.address,\n mapping.mxid,\n ]);\n }\n\n return { threepids: v1results };\n }\n\n /**\n * Get account info from the identity server. This is useful as a neutral check\n * to verify that other APIs are likely to approve access by testing that the\n * token is valid, terms have been agreed, etc.\n *\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: an object with account info.\n * @returns Rejects: with an error response.\n */\n public getIdentityAccount(identityAccessToken: string): Promise<{ user_id: string }> {\n return this.http.idServerRequest(Method.Get, \"/account\", undefined, IdentityPrefix.V2, identityAccessToken);\n }\n\n /**\n * Send an event to a specific list of devices.\n * This is a low-level API that simply wraps the HTTP API\n * call to send to-device messages. We recommend using\n * queueToDevice() which is a higher level API.\n *\n * @param eventType - type of event to send\n * content to send. Map from user_id to device_id to content object.\n * @param txnId - transaction id. One will be made up if not\n * supplied.\n * @returns Promise which resolves: to an empty object `{}`\n */\n public sendToDevice(eventType: string, contentMap: SendToDeviceContentMap, txnId?: string): Promise<{}> {\n const path = utils.encodeUri(\"/sendToDevice/$eventType/$txnId\", {\n $eventType: eventType,\n $txnId: txnId ? txnId : this.makeTxnId(),\n });\n\n const body = {\n messages: utils.recursiveMapToObject(contentMap),\n };\n\n const targets = new Map<string, string[]>();\n\n for (const [userId, deviceMessages] of contentMap) {\n targets.set(userId, Array.from(deviceMessages.keys()));\n }\n\n this.logger.debug(`PUT ${path}`, targets);\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Sends events directly to specific devices using Matrix's to-device\n * messaging system. The batch will be split up into appropriately sized\n * batches for sending and stored in the store so they can be retried\n * later if they fail to send. Retries will happen automatically.\n * @param batch - The to-device messages to send\n */\n public queueToDevice(batch: ToDeviceBatch): Promise<void> {\n return this.toDeviceMessageQueue.queueBatch(batch);\n }\n\n /**\n * Get the third party protocols that can be reached using\n * this HS\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyProtocols(): Promise<{ [protocol: string]: IProtocol }> {\n return this.http\n .authedRequest<Record<string, IProtocol>>(Method.Get, \"/thirdparty/protocols\")\n .then((response) => {\n // sanity check\n if (!response || typeof response !== \"object\") {\n throw new Error(`/thirdparty/protocols did not return an object: ${response}`);\n }\n return response;\n });\n }\n\n /**\n * Get information on how a specific place on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyLocation(\n protocol: string,\n params: { searchFields?: string[] },\n ): Promise<IThirdPartyLocation[]> {\n const path = utils.encodeUri(\"/thirdparty/location/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Get information on how a specific user on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyUser(protocol: string, params?: QueryDict): Promise<IThirdPartyUser[]> {\n const path = utils.encodeUri(\"/thirdparty/user/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n public getTerms(serviceType: SERVICE_TYPES, baseUrl: string): Promise<any> {\n // TODO: Types\n const url = this.termsUrlForService(serviceType, baseUrl);\n return this.http.requestOtherUrl(Method.Get, url);\n }\n\n public agreeToTerms(\n serviceType: SERVICE_TYPES,\n baseUrl: string,\n accessToken: string,\n termsUrls: string[],\n ): Promise<{}> {\n const url = this.termsUrlForService(serviceType, baseUrl);\n const headers = {\n Authorization: \"Bearer \" + accessToken,\n };\n return this.http.requestOtherUrl(\n Method.Post,\n url,\n {\n user_accepts: termsUrls,\n },\n { headers },\n );\n }\n\n /**\n * Reports an event as inappropriate to the server, which may then notify the appropriate people.\n * @param roomId - The room in which the event being reported is located.\n * @param eventId - The event to report.\n * @param score - The score to rate this content as where -100 is most offensive and 0 is inoffensive.\n * @param reason - The reason the content is being reported. May be blank.\n * @returns Promise which resolves to an empty object if successful\n */\n public reportEvent(roomId: string, eventId: string, score: number, reason: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/report/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, { score, reason });\n }\n\n /**\n * Fetches or paginates a room hierarchy as defined by MSC2946.\n * Falls back gracefully to sourcing its data from `getSpaceSummary` if this API is not yet supported by the server.\n * @param roomId - The ID of the space-room to use as the root of the summary.\n * @param limit - The maximum number of rooms to return per page.\n * @param maxDepth - The maximum depth in the tree from the root room to return.\n * @param suggestedOnly - Whether to only return rooms with suggested=true.\n * @param fromToken - The opaque token to paginate a previous request.\n * @returns the response, with next_batch & rooms fields.\n */\n public getRoomHierarchy(\n roomId: string,\n limit?: number,\n maxDepth?: number,\n suggestedOnly = false,\n fromToken?: string,\n ): Promise<IRoomHierarchy> {\n const path = utils.encodeUri(\"/rooms/$roomId/hierarchy\", {\n $roomId: roomId,\n });\n\n const queryParams: QueryDict = {\n suggested_only: String(suggestedOnly),\n max_depth: maxDepth?.toString(),\n from: fromToken,\n limit: limit?.toString(),\n };\n\n return this.http\n .authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n })\n .catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n // fall back to the prefixed hierarchy API.\n return this.http.authedRequest<IRoomHierarchy>(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2946\",\n });\n }\n\n throw e;\n });\n }\n\n /**\n * Creates a new file tree space with the given name. The client will pick\n * defaults for how it expects to be able to support the remaining API offered\n * by the returned class.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param name - The name of the tree space.\n * @returns Promise which resolves to the created space.\n */\n public async unstableCreateFileTree(name: string): Promise<MSC3089TreeSpace> {\n const { room_id: roomId } = await this.createRoom({\n name: name,\n preset: Preset.PrivateChat,\n power_level_content_override: {\n ...DEFAULT_TREE_POWER_LEVELS_TEMPLATE,\n users: {\n [this.getUserId()!]: 100,\n },\n },\n creation_content: {\n [RoomCreateTypeField]: RoomType.Space,\n },\n initial_state: [\n {\n type: UNSTABLE_MSC3088_PURPOSE.name,\n state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n content: {\n [UNSTABLE_MSC3088_ENABLED.name]: true,\n },\n },\n ],\n });\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Gets a reference to a tree space, if the room ID given is a tree space. If the room\n * does not appear to be a tree space then null is returned.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param roomId - The room ID to get a tree space reference for.\n * @returns The tree space, or null if not a tree space.\n */\n public unstableGetFileTreeSpace(roomId: string): MSC3089TreeSpace | null {\n const room = this.getRoom(roomId);\n if (room?.getMyMembership() !== KnownMembership.Join) return null;\n\n const createEvent = room.currentState.getStateEvents(EventType.RoomCreate, \"\");\n const purposeEvent = room.currentState.getStateEvents(\n UNSTABLE_MSC3088_PURPOSE.name,\n UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n );\n\n if (!createEvent) throw new Error(\"Expected single room create event\");\n\n if (!purposeEvent?.getContent()?.[UNSTABLE_MSC3088_ENABLED.name]) return null;\n if (createEvent.getContent()?.[RoomCreateTypeField] !== RoomType.Space) return null;\n\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Perform a single MSC3575 sliding sync request.\n * @param req - The request to make.\n * @param proxyBaseUrl - The base URL for the sliding sync proxy.\n * @param abortSignal - Optional signal to abort request mid-flight.\n * @returns The sliding sync response, or a standard error.\n * @throws on non 2xx status codes with an object with a field \"httpStatus\":number.\n */\n public slidingSync(\n req: MSC3575SlidingSyncRequest,\n proxyBaseUrl?: string,\n abortSignal?: AbortSignal,\n ): Promise<MSC3575SlidingSyncResponse> {\n const qps: QueryDict = {};\n if (req.pos) {\n qps.pos = req.pos;\n delete req.pos;\n }\n if (req.timeout) {\n qps.timeout = req.timeout;\n delete req.timeout;\n }\n const clientTimeout = req.clientTimeout;\n delete req.clientTimeout;\n return this.http.authedRequest<MSC3575SlidingSyncResponse>(Method.Post, \"/sync\", qps, req, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3575\",\n baseUrl: proxyBaseUrl,\n localTimeoutMs: clientTimeout,\n abortSignal,\n });\n }\n\n /**\n * A helper to determine thread support\n * @returns a boolean to determine if threads are enabled\n */\n public supportsThreads(): boolean {\n return this.clientOpts?.threadSupport || false;\n }\n\n /**\n * A helper to determine intentional mentions support\n * @returns a boolean to determine if intentional mentions are enabled on the server\n * @experimental\n */\n public supportsIntentionalMentions(): boolean {\n return this.canSupport.get(Feature.IntentionalMentions) !== ServerSupport.Unsupported;\n }\n\n /**\n * Fetches the summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n * @param roomIdOrAlias - The ID or alias of the room to get the summary of.\n * @param via - The list of servers which know about the room if only an ID was provided.\n */\n public async getRoomSummary(roomIdOrAlias: string, via?: string[]): Promise<RoomSummary> {\n const paramOpts = {\n prefix: \"/_matrix/client/unstable/im.nheko.summary\",\n };\n try {\n const path = utils.encodeUri(\"/summary/$roomid\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } catch (e) {\n if (e instanceof MatrixError && e.errcode === \"M_UNRECOGNIZED\") {\n const path = utils.encodeUri(\"/rooms/$roomid/summary\", { $roomid: roomIdOrAlias });\n return await this.http.authedRequest(Method.Get, path, { via }, undefined, paramOpts);\n } else {\n throw e;\n }\n }\n }\n\n /**\n * Processes a list of threaded events and adds them to their respective timelines\n * @param room - the room the adds the threaded events\n * @param threadedEvents - an array of the threaded events\n * @param toStartOfTimeline - the direction in which we want to add the events\n */\n public processThreadEvents(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n room.processThreadedEvents(threadedEvents, toStartOfTimeline);\n }\n\n /**\n * Processes a list of thread roots and creates a thread model\n * @param room - the room to create the threads in\n * @param threadedEvents - an array of thread roots\n * @param toStartOfTimeline - the direction\n */\n public processThreadRoots(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n if (!this.supportsThreads()) return;\n room.processThreadRoots(threadedEvents, toStartOfTimeline);\n }\n\n public processBeaconEvents(room?: Room, events?: MatrixEvent[]): void {\n this.processAggregatedTimelineEvents(room, events);\n }\n\n /**\n * Calls aggregation functions for event types that are aggregated\n * Polls and location beacons\n * @param room - room the events belong to\n * @param events - timeline events to be processed\n * @returns\n */\n public processAggregatedTimelineEvents(room?: Room, events?: MatrixEvent[]): void {\n if (!events?.length) return;\n if (!room) return;\n\n room.currentState.processBeaconEvents(events, this);\n room.processPollEvents(events);\n }\n\n /**\n * Fetches information about the user for the configured access token.\n */\n public async whoami(): Promise<IWhoamiResponse> {\n return this.http.authedRequest(Method.Get, \"/account/whoami\");\n }\n\n /**\n * Find the event_id closest to the given timestamp in the given direction.\n * @returns Resolves: A promise of an object containing the event_id and\n * origin_server_ts of the closest event to the timestamp in the given direction\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n */\n public async timestampToEvent(\n roomId: string,\n timestamp: number,\n dir: Direction,\n ): Promise<TimestampToEventResponse> {\n const path = utils.encodeUri(\"/rooms/$roomId/timestamp_to_event\", {\n $roomId: roomId,\n });\n const queryParams = {\n ts: timestamp.toString(),\n dir: dir,\n };\n\n try {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n });\n } catch (err) {\n // Fallback to the prefixed unstable endpoint. Since the stable endpoint is\n // new, we should also try the unstable endpoint before giving up. We can\n // remove this fallback request in a year (remove after 2023-11-28).\n if (\n (<MatrixError>err).errcode === \"M_UNRECOGNIZED\" &&\n // XXX: The 400 status code check should be removed in the future\n // when Synapse is compliant with MSC3743.\n ((<MatrixError>err).httpStatus === 400 ||\n // This the correct standard status code for an unsupported\n // endpoint according to MSC3743. Not Found and Method Not Allowed\n // both indicate that this endpoint+verb combination is\n // not supported.\n (<MatrixError>err).httpStatus === 404 ||\n (<MatrixError>err).httpStatus === 405)\n ) {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3030\",\n });\n }\n\n throw err;\n }\n }\n\n /**\n * Get the OIDC issuer responsible for authentication on this server, if any\n * @returns Resolves: A promise of an object containing the OIDC issuer if configured\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n * @experimental - part of MSC2965\n */\n public async getAuthIssuer(): Promise<{\n issuer: string;\n }> {\n return this.http.request(Method.Get, \"/auth_issuer\", undefined, undefined, {\n prefix: ClientPrefix.Unstable + \"/org.matrix.msc2965\",\n });\n }\n}\n\nfunction getUnstableDelayQueryOpts(delayOpts: SendDelayedEventRequestOpts): QueryDict {\n return Object.fromEntries(\n Object.entries(delayOpts).map(([k, v]) => [`${UNSTABLE_MSC4140_DELAYED_EVENTS}.${k}`, v]),\n );\n}\n\n/**\n * Given an event, figure out the thread ID we should use for it in a receipt.\n *\n * This will either be \"main\", or event.threadRootId. For the thread root, or\n * e.g. reactions to the thread root, this will be main. For events inside the\n * thread, or e.g. reactions to them, this will be event.threadRootId.\n *\n * (Exported for test.)\n */\nexport function threadIdForReceipt(event: MatrixEvent): string {\n return inMainTimelineForReceipt(event) ? MAIN_ROOM_TIMELINE : event.threadRootId!;\n}\n\n/**\n * a) True for non-threaded messages, thread roots and non-thread relations to thread roots.\n * b) False for messages with thread relations to the thread root.\n * c) False for messages with any kind of relation to a message from case b.\n *\n * Note: true for redactions of messages that are in threads. Redacted messages\n * are not really in threads (because their relations are gone), so if they look\n * like they are in threads, that is a sign of a bug elsewhere. (At time of\n * writing, this bug definitely exists - messages are not moved to another\n * thread when they are redacted.)\n *\n * @returns true if this event is considered to be in the main timeline as far\n * as receipts are concerned.\n */\nexport function inMainTimelineForReceipt(event: MatrixEvent): boolean {\n if (!event.threadRootId) {\n // Not in a thread: then it is in the main timeline\n return true;\n }\n\n if (event.isThreadRoot) {\n // Thread roots are in the main timeline. Note: the spec is ambiguous (or\n // wrong) on this - see\n // https://github.com/matrix-org/matrix-spec-proposals/pull/4037\n return true;\n }\n\n if (!event.isRelation()) {\n // If it's not related to anything, it can't be related via a chain of\n // relations to a thread root.\n //\n // Note: this is a bug, because how does it have a threadRootId if it is\n // neither a thread root, nor related to one?\n logger.warn(`Event is not a relation or a thread root, but still has a threadRootId! id=${event.getId()}`);\n return true;\n }\n\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n // It's a message in a thread - definitely not in the main timeline.\n return false;\n }\n\n const isRelatedToRoot = event.relationEventId === event.threadRootId;\n\n // If it's related to the thread root (and we already know it's not a thread\n // relation) then it's in the main timeline. If it's related to something\n // else, then it's in the thread (because it has a thread ID).\n return isRelatedToRoot;\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAIA,SAAsCA,OAAO,EAAkBC,SAAS,QAAQ,WAAW;AAC3F,SACIC,WAAW,EAIXC,WAAW,EACXC,gBAAgB,QAGb,mBAAmB;AAC1B,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,MAAM,QAA6C,aAAa;AACzE,OAAO,KAAKC,KAAK,MAAM,YAAY;AACnC,SAASC,kBAAkB,EAAaC,YAAY,EAAEC,KAAK,QAAQ,YAAY;AAC/E,SAASC,SAAS,EAAEC,aAAa,QAAQ,4BAA4B;AACrE,SAAyBC,aAAa,QAAQ,oBAAoB;AAClE,SAAS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