Room
Defined in: src/models/room.ts:338
Extends
Section titled “Extends”ReadReceipt<RoomEmittedEvents,RoomEventHandlerMap>
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new Room(
roomId,client,myUserId,opts?):Room
Defined in: src/models/room.ts:483
Construct a new Room.
For a room, we store an ordered sequence of timelines, which may or may not be continuous. Each timeline lists a series of events, as well as tracking the room state at the start and the end of the timeline. It also tracks forward and backward pagination tokens, as well as containing links to the next timeline in the sequence.
There is one special timeline - the 'live' timeline, which represents the timeline to which events are being added in real-time as they are received from the /sync API. Note that you should not retain references to this timeline - even if it is the current timeline right now, it may not remain so if the server gives us a timeline gap in /sync.
In order that we can find events from their ids later, we also maintain a map from event_id to timeline and index.
Parameters
Section titled “Parameters”roomId
Section titled “roomId”string
Required. The ID of this room.
client
Section titled “client”Required. The client, used to lazy load members.
myUserId
Section titled “myUserId”string
Required. The ID of the syncing user.
IOpts = {}
Configuration options
Returns
Section titled “Returns”Room
Overrides
Section titled “Overrides”ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap>.constructor
Properties
Section titled “Properties”accountData
Section titled “accountData”accountData:
Map<string,DigitalWorldEvent>
Defined in: src/models/room.ts:401
accountData Dict of per-room account_data events; the keys are the event type and the values are the events.
cachedThreadReadReceipts
Section titled “cachedThreadReadReceipts”
readonlycachedThreadReadReceipts:Map<string,CachedReceiptStructure[]>
Defined in: src/models/room.ts:344
client
Section titled “client”
readonlyclient:DigitalWorldClient
Defined in: src/models/room.ts:485
Required. The client, used to lazy load members.
currentState
Section titled “currentState”currentState:
RoomState
Defined in: src/models/room.ts:419
currentState The state of the room at the time of the newest event in the timeline.
myUserId
Section titled “myUserId”
readonlymyUserId:string
Defined in: src/models/room.ts:486
Required. The ID of the syncing user.
name:
string
Defined in: src/models/room.ts:387
The human-readable display name for this room.
normalizedName
Section titled “normalizedName”normalizedName:
string
Defined in: src/models/room.ts:391
The un-homoglyphed name for this room.
oldState
Section titled “oldState”oldState:
RoomState
Defined in: src/models/room.ts:412
oldState The state of the room at the time of the oldest event in the live timeline.
readonlypolls:Map<string,Poll>
Defined in: src/models/room.ts:353
reEmitter
Section titled “reEmitter”
readonlyreEmitter:TypedReEmitter<RoomEmittedEvents,RoomEventHandlerMap>
Defined in: src/models/room.ts:339
relations
Section titled “relations”
readonlyrelations:RelationsContainer
Defined in: src/models/room.ts:421
roomId
Section titled “roomId”
readonlyroomId:string
Defined in: src/models/room.ts:484
Required. The ID of this room.
summary
Section titled “summary”summary:
RoomSummary|null=null
Defined in: src/models/room.ts:405
The room summary.
tags:
Record<string,Record<string,any>> ={}
Defined in: src/models/room.ts:396
Dict of room tags; the keys are the tag name and the values
are any metadata associated with the tag - e.g. { "fav" : { order: 1 } }
threadsTimelineSets
Section titled “threadsTimelineSets”
readonlythreadsTimelineSets: [] | [EventTimelineSet,EventTimelineSet] =[]
Defined in: src/models/room.ts:360
Empty array if the timeline sets have not been initialised. After initialisation: 0: All threads 1: Threads the current user has participated in
captureRejections
Section titled “captureRejections”
staticcaptureRejections:boolean
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:425
Value: boolean
Change the default captureRejections option on all new EventEmitter objects.
v13.4.0, v12.16.0
Inherited from
Section titled “Inherited from”ReadReceipt.captureRejections
captureRejectionSymbol
Section titled “captureRejectionSymbol”
readonlystaticcaptureRejectionSymbol: typeofcaptureRejectionSymbol
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:418
Value: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler.
v13.4.0, v12.16.0
Inherited from
Section titled “Inherited from”ReadReceipt.captureRejectionSymbol
defaultMaxListeners
Section titled “defaultMaxListeners”
staticdefaultMaxListeners:number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:464
By default, a maximum of 10 listeners can be registered for any single
event. This limit can be changed for individual EventEmitter instances
using the emitter.setMaxListeners(n) method. To change the default
for allEventEmitter instances, the events.defaultMaxListeners property
can be used. If this value is not a positive number, a RangeError is thrown.
Take caution when setting the events.defaultMaxListeners because the
change affects all EventEmitter instances, including those created before
the change is made. However, calling emitter.setMaxListeners(n) still has
precedence over events.defaultMaxListeners.
This is not a hard limit. The EventEmitter instance will allow
more listeners to be added but will output a trace warning to stderr indicating
that a “possible EventEmitter memory leak” has been detected. For any single
EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners() methods can be used to
temporarily avoid this warning:
import { EventEmitter } from 'node:events';const emitter = new EventEmitter();emitter.setMaxListeners(emitter.getMaxListeners() + 1);emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));});The --trace-warnings command-line flag can be used to display the
stack trace for such warnings.
The emitted warning can be inspected with process.on('warning') and will
have the additional emitter, type, and count properties, referring to
the event emitter instance, the event’s name and the number of attached
listeners, respectively.
Its name property is set to 'MaxListenersExceededWarning'.
v0.11.2
Inherited from
Section titled “Inherited from”ReadReceipt.defaultMaxListeners
errorMonitor
Section titled “errorMonitor”
readonlystaticerrorMonitor: typeoferrorMonitor
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:411
This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error' event is emitted. Therefore, the process will still crash if no
regular 'error' listener is installed.
v13.6.0, v12.17.0
Inherited from
Section titled “Inherited from”ReadReceipt.errorMonitor
Accessors
Section titled “Accessors”threadsAggregateNotificationType
Section titled “threadsAggregateNotificationType”Get Signature
Section titled “Get Signature”get threadsAggregateNotificationType():
NotificationCountType|null
Defined in: src/models/room.ts:1612
Returns
Section titled “Returns”NotificationCountType | null
the notification count type for all the threads in the room
timeline
Section titled “timeline”Get Signature
Section titled “Get Signature”get timeline():
DigitalWorldEvent[]
Defined in: src/models/room.ts:807
The live event timeline for this room, with the oldest event at index 0.
Returns
Section titled “Returns”Overrides
Section titled “Overrides”ReadReceipt.timeline
Methods
Section titled “Methods”_unstable_getKeyedStickyEvent()
Section titled “_unstable_getKeyedStickyEvent()”_unstable_getKeyedStickyEvent(
sender,type,stickyKey):StickyDigitalWorldEvent|undefined
Defined in: src/models/room.ts:3460
Get a sticky event that match the given type, sender, and stickyKey
Parameters
Section titled “Parameters”sender
Section titled “sender”string
The sender of the sticky event.
string
The event type.
stickyKey
Section titled “stickyKey”string
The sticky key used by the event.
Returns
Section titled “Returns”StickyDigitalWorldEvent | undefined
A matching active sticky event, or undefined.
_unstable_getStickyEvents()
Section titled “_unstable_getStickyEvents()”_unstable_getStickyEvents():
Iterable<StickyDigitalWorldEvent>
Defined in: src/models/room.ts:3448
Get an iterator of currently active sticky events.
Returns
Section titled “Returns”Iterable<StickyDigitalWorldEvent>
_unstable_getUnkeyedStickyEvent()
Section titled “_unstable_getUnkeyedStickyEvent()”_unstable_getUnkeyedStickyEvent(
sender,type):StickyDigitalWorldEvent[]
Defined in: src/models/room.ts:3475
Get active sticky events without a sticky key that match the given type and sender.
Parameters
Section titled “Parameters”sender
Section titled “sender”string
The sender of the sticky event.
string
The event type.
Returns
Section titled “Returns”An array of matching sticky events.
[captureRejectionSymbol]()?
Section titled “[captureRejectionSymbol]()?”
optional[captureRejectionSymbol]<K>(error,event, …args):void
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:103
Type Parameters
Section titled “Type Parameters”K
Parameters
Section titled “Parameters”Error
string | symbol
…AnyRest
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ReadReceipt.[captureRejectionSymbol]
addAccountData()
Section titled “addAccountData()”addAccountData(
events):void
Defined in: src/models/room.ts:3423
Update the account_data events for this room, overwriting events of the same type.
Parameters
Section titled “Parameters”events
Section titled “events”an array of account_data events to add
Returns
Section titled “Returns”void
addEphemeralEvents()
Section titled “addEphemeralEvents()”addEphemeralEvents(
events):void
Defined in: src/models/room.ts:3308
Adds/handles ephemeral events such as typing notifications and read receipts.
Parameters
Section titled “Parameters”events
Section titled “events”A list of events to process
Returns
Section titled “Returns”void
addEventsToTimeline()
Section titled “addEventsToTimeline()”addEventsToTimeline(
events,toStartOfTimeline,addToState,timeline,paginationToken?):void
Defined in: src/models/room.ts:1864
Add events to a timeline
Will fire "Room.timeline" for each event added.
Parameters
Section titled “Parameters”events
Section titled “events”A list of events to add.
toStartOfTimeline
Section titled “toStartOfTimeline”boolean
True to add these events to the start (oldest) instead of the end (newest) of the timeline. If true, the oldest event will be the last element of ‘events’.
addToState
Section titled “addToState”boolean
timeline
Section titled “timeline”timeline to add events to.
paginationToken?
Section titled “paginationToken?”string
token for the next batch of events
Returns
Section titled “Returns”void
Remarks
Section titled “Remarks”Fires RoomEvent.Timeline
addListener()
Section titled “addListener()”addListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:70
Alias for on.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | RoomEmittedEvents
Parameters
Section titled “Parameters”T
listener
Section titled “listener”Listener<RoomEmittedEvents, RoomEventHandlerMap, T>
Returns
Section titled “Returns”this
Inherited from
Section titled “Inherited from”ReadReceipt.addListener
addLiveEvents()
Section titled “addLiveEvents()”addLiveEvents(
events,addLiveEventOptions):Promise<void>
Defined in: src/models/room.ts:3087
Add some events to this room. This can include state events, message events and typing notifications. These events are treated as “live” so they will go to the end of the timeline.
Parameters
Section titled “Parameters”events
Section titled “events”A list of events to add.
addLiveEventOptions
Section titled “addLiveEventOptions”addLiveEvent options
Returns
Section titled “Returns”Promise<void>
Throws
Section titled “Throws”If duplicateStrategy is not falsey, ‘replace’ or ‘ignore’.
addLocalEchoReceipt()
Section titled “addLocalEchoReceipt()”addLocalEchoReceipt(
userId,e,receiptType,unthreaded?):void
Defined in: src/models/read-receipt.ts:383
Add a temporary local-echo receipt to the room to reflect in the client the fact that we’ve sent one.
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The user ID if the receipt sender
The event that is to be acknowledged
receiptType
Section titled “receiptType”The type of receipt
unthreaded?
Section titled “unthreaded?”boolean = false
the receipt is unthreaded
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ReadReceipt.addLocalEchoReceipt
addPendingEvent()
Section titled “addPendingEvent()”addPendingEvent(
event,txnId):void
Defined in: src/models/room.ts:2784
Add a pending outgoing event to this room.
The event is added to either the pendingEventList, or the live timeline, depending on the setting of opts.pendingEventOrdering.
This is an internal method, intended for use by DigitalWorldClient.
Parameters
Section titled “Parameters”The event to add.
string
Transaction id for this outgoing event
Returns
Section titled “Returns”void
Throws
Section titled “Throws”if the event doesn’t have status SENDING, or we aren’t given a unique transaction id.
Remarks
Section titled “Remarks”Fires RoomEvent.LocalEchoUpdated
addReceipt()
Section titled “addReceipt()”addReceipt(
event,synthetic?):void
Defined in: src/models/room.ts:3230
Add a receipt event to the room.
Parameters
Section titled “Parameters”The m.receipt event.
synthetic?
Section titled “synthetic?”boolean = false
True if this event is implicit.
Returns
Section titled “Returns”void
Overrides
Section titled “Overrides”ReadReceipt.addReceipt
addReceiptToStructure()
Section titled “addReceiptToStructure()”addReceiptToStructure(
eventId,receiptType,userId,receipt,synthetic):void
Defined in: src/models/read-receipt.ts:242
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
receiptType
Section titled “receiptType”userId
Section titled “userId”string
receipt
Section titled “receipt”synthetic
Section titled “synthetic”boolean
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”ReadReceipt.addReceiptToStructure
addTags()
Section titled “addTags()”addTags(
event):void
Defined in: src/models/room.ts:3402
Update the room-tag event for the room. The previous one is overwritten.
Parameters
Section titled “Parameters”the m.tag event
Returns
Section titled “Returns”void
addTimeline()
Section titled “addTimeline()”addTimeline():
EventTimeline
Defined in: src/models/room.ts:1485
Add a new timeline to this room’s unfiltered timeline set
Returns
Section titled “Returns”newly-created timeline
canInvite()
Section titled “canInvite()”canInvite(
userId):boolean
Defined in: src/models/room.ts:3515
Returns whether the given user has permissions to issue an invite for this room.
Parameters
Section titled “Parameters”userId
Section titled “userId”string
the ID of the user to check permissions for
Returns
Section titled “Returns”boolean
true if the user should be permitted to issue invites for this room.
clearLoadedMembersIfNeeded()
Section titled “clearLoadedMembersIfNeeded()”clearLoadedMembersIfNeeded():
Promise<void>
Defined in: src/models/room.ts:1157
Removes the lazily loaded members from storage if needed
Returns
Section titled “Returns”Promise<void>
compareEventOrdering()
Section titled “compareEventOrdering()”compareEventOrdering(
leftEventId,rightEventId):number|null
Defined in: src/models/room.ts:4011
Determine the order of two events in this room.
In principle this should use the same order as the server, but in practice this is difficult for events that were not received over the Sync API. See MSC4033 for details.
This implementation leans on the order of events within their timelines, and falls back to comparing event timestamps when they are in different timelines.
This is a known limitation; see the project’s issue tracker for status.
Parameters
Section titled “Parameters”leftEventId
Section titled “leftEventId”string
the id of the first event
rightEventId
Section titled “rightEventId”string
the id of the second event
Returns
Section titled “Returns”number | null
-1 if left < right, 1 if left > right, 0 if left == right, null if we can’t tell (because we can’t find the events).
createThread()
Section titled “createThread()”createThread(
threadId,rootEvent,events?,toStartOfTimeline):Thread
Defined in: src/models/room.ts:2528
Parameters
Section titled “Parameters”threadId
Section titled “threadId”string
rootEvent
Section titled “rootEvent”DigitalWorldEvent | undefined
events?
Section titled “events?”DigitalWorldEvent[] = []
toStartOfTimeline
Section titled “toStartOfTimeline”boolean
Returns
Section titled “Returns”createThreadsTimelineSets()
Section titled “createThreadsTimelineSets()”createThreadsTimelineSets():
Promise<[EventTimelineSet,EventTimelineSet] |null>
Defined in: src/models/room.ts:542
Returns
Section titled “Returns”Promise<[EventTimelineSet, EventTimelineSet] | null>
decryptAllEvents()
Section titled “decryptAllEvents()”decryptAllEvents():
Promise<void>
Defined in: src/models/room.ts:598
Bulk decrypt events in a room
Returns
Section titled “Returns”Promise<void>
Signals when all events have been decrypted
decryptCriticalEvents()
Section titled “decryptCriticalEvents()”decryptCriticalEvents():
Promise<void>
Defined in: src/models/room.ts:576
Bulk decrypt critical events in a room
Critical events represents the minimal set of events to decrypt for a typical UI to function properly
- Last event of every room (to generate likely message preview)
- All events up to the read receipt (to calculate an accurate notification count)
Returns
Section titled “Returns”Promise<void>
Signals when all events have been decrypted
emit()
Section titled “emit()”Call Signature
Section titled “Call Signature”emit<
T>(event, …args):boolean
Defined in: src/models/typed-event-emitter.ts:86
Synchronously calls each of the listeners registered for the event named
event, in the order they were registered, passing the supplied arguments
to each.
Type Parameters
Section titled “Type Parameters”T extends RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<RoomEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”boolean
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”ReadReceipt.emit
Call Signature
Section titled “Call Signature”emit<
T>(event, …args):boolean
Defined in: src/models/typed-event-emitter.ts:87
Synchronously calls each of the listeners registered for the event named
event, in the order they were registered, passing the supplied arguments
to each.
Type Parameters
Section titled “Type Parameters”T extends RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<RoomEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”boolean
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”ReadReceipt.emit
emitPromised()
Section titled “emitPromised()”Call Signature
Section titled “Call Signature”emitPromised<
T>(event, …args):Promise<boolean>
Defined in: src/models/typed-event-emitter.ts:98
Similar to emit but calls all listeners within a Promise.all and returns the promise chain
Type Parameters
Section titled “Type Parameters”T extends RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<RoomEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”Promise<boolean>
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”ReadReceipt.emitPromised
Call Signature
Section titled “Call Signature”emitPromised<
T>(event, …args):Promise<boolean>
Defined in: src/models/typed-event-emitter.ts:102
Similar to emit but calls all listeners within a Promise.all and returns the promise chain
Type Parameters
Section titled “Type Parameters”T extends RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<RoomEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”Promise<boolean>
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”ReadReceipt.emitPromised
eventNames()
Section titled “eventNames()”eventNames(): (
string|symbol)[]
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:967
Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or Symbols.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();myEE.on('foo', () => {});myEE.on('bar', () => {});
const sym = Symbol('symbol');myEE.on(sym, () => {});
console.log(myEE.eventNames());// Prints: [ 'foo', 'bar', Symbol(symbol) ]Returns
Section titled “Returns”(string | symbol)[]
v6.0.0
Inherited from
Section titled “Inherited from”ReadReceipt.eventNames
eventShouldLiveIn()
Section titled “eventShouldLiveIn()”eventShouldLiveIn(
event,events?,roots?):object
Defined in: src/models/room.ts:2379
Determine which timeline(s) a given event should live in Thread roots live in both the main timeline and their corresponding thread timeline Relations, redactions, replies to thread relation events live only in the thread timeline Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless. Otherwise, the event lives in the main timeline only.
Note: when a redaction is applied, the redacted event, events relating to it, and the redaction event itself, will all move to the main thread. This method classifies them as inside the thread of the redacted event. They are moved later as part of makeRedacted. This will change if MSC3389 is merged.
Parameters
Section titled “Parameters”events?
Section titled “events?”roots?
Section titled “roots?”Set<string>
Returns
Section titled “Returns”object
shouldLiveInRoom
Section titled “shouldLiveInRoom”shouldLiveInRoom:
boolean
shouldLiveInThread
Section titled “shouldLiveInThread”shouldLiveInThread:
boolean
threadId?
Section titled “threadId?”
optionalthreadId?:string
fetchRoomThreads()
Section titled “fetchRoomThreads()”fetchRoomThreads():
Promise<void>
Defined in: src/models/room.ts:2154
Fetch the bare minimum of room threads required for the thread list to work reliably. With server support that means fetching one page. Without server support that means fetching as much at once as the server allows us to.
Returns
Section titled “Returns”Promise<void>
findEventById()
Section titled “findEventById()”findEventById(
eventId):DigitalWorldEvent|undefined
Defined in: src/models/room.ts:1513
Get an event which is stored in our unfiltered timeline set, or in a thread
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
event ID to look for
Returns
Section titled “Returns”DigitalWorldEvent | undefined
the given event, or undefined if unknown
Overrides
Section titled “Overrides”ReadReceipt.findEventById
findPredecessor()
Section titled “findPredecessor()”findPredecessor(
msc3946ProcessDynamicPredecessor?): {eventId?:string;roomId:string;viaServers?:string[]; } |null
Defined in: src/models/room.ts:3608
Find the predecessor of this room.
Parameters
Section titled “Parameters”msc3946ProcessDynamicPredecessor?
Section titled “msc3946ProcessDynamicPredecessor?”boolean = false
if true, look for an m.room.predecessor state event and use it if found (MSC3946).
Returns
Section titled “Returns”{ eventId?: string; roomId: string; viaServers?: string[]; } | null
null if this room has no predecessor. Otherwise, returns the roomId, last eventId and viaServers of the predecessor room.
If msc3946ProcessDynamicPredecessor is true, use m.predecessor events as well as m.room.create events to find predecessors.
Note: if an m.predecessor event is used, eventId may be undefined since last_known_event_id is optional.
Note: viaServers may be undefined, and will definitely be undefined if this predecessor comes from a RoomCreate event (rather than a RoomPredecessor, which has the optional via_servers property).
findThreadForEvent()
Section titled “findThreadForEvent()”findThreadForEvent(
event?):Thread|null
Defined in: src/models/room.ts:2454
Parameters
Section titled “Parameters”event?
Section titled “event?”Returns
Section titled “Returns”Thread | null
fixupNotifications()
Section titled “fixupNotifications()”fixupNotifications(
userId):void
Defined in: src/models/room.ts:3980
This issue should also be addressed on synapse’s side and is tracked as part of https://github.com/matrix-org/synapse/issues/14837
We consider a room fully read if the current user has sent the last event in the live timeline of that context and if the read receipt we have on record matches. This also detects all unread threads and applies the same logic to those contexts
Parameters
Section titled “Parameters”userId
Section titled “userId”string
Returns
Section titled “Returns”void
Overrides
Section titled “Overrides”ReadReceipt.fixupNotifications
getAccountData()
Section titled “getAccountData()”getAccountData(
type):DigitalWorldEvent|undefined
Defined in: src/models/room.ts:3440
Access account_data event of given event type for this room
Parameters
Section titled “Parameters”string
the type of account_data event to be accessed
Returns
Section titled “Returns”DigitalWorldEvent | undefined
the account_data event in question
getAltAliases()
Section titled “getAltAliases()”getAltAliases():
string[]
Defined in: src/models/room.ts:1837
Get this room’s alternative aliases
Returns
Section titled “Returns”string[]
The room’s alternative aliases, or an empty array
getAvatarFallbackMember()
Section titled “getAvatarFallbackMember()”getAvatarFallbackMember():
RoomMember|undefined
Defined in: src/models/room.ts:945
Returns
Section titled “Returns”RoomMember | undefined
getAvatarUrl()
Section titled “getAvatarUrl()”getAvatarUrl(
baseUrl,width,height,resizeMethod,allowDefault?,useAuthentication?):string|null
Defined in: src/models/room.ts:1784
Get the avatar URL for a room if one was set.
Parameters
Section titled “Parameters”baseUrl
Section titled “baseUrl”string
The hub base URL. See DigitalWorldClient#getHubUrl.
number
The desired width of the thumbnail.
height
Section titled “height”number
The desired height of the thumbnail.
resizeMethod
Section titled “resizeMethod”The thumbnail resize method to use, either “crop” or “scale”.
allowDefault?
Section titled “allowDefault?”boolean = true
True to allow an identicon for this room if an avatar URL wasn’t explicitly set. Default: true. (Deprecated)
useAuthentication?
Section titled “useAuthentication?”boolean = false
(optional) If true, the caller supports authenticated media and wants an authentication-required URL. Note that server support for authenticated media will not be checked - it is the caller’s responsibility to do so before calling this function. Note also that useAuthentication implies allowRedirects. Defaults to false (unauthenticated endpoints).
Returns
Section titled “Returns”string | null
the avatar URL or null.
getBlacklistUnverifiedDevices()
Section titled “getBlacklistUnverifiedDevices()”getBlacklistUnverifiedDevices():
boolean|null
Defined in: src/models/room.ts:1762
Whether to send encrypted messages to devices within this room.
Returns
Section titled “Returns”boolean | null
true if blacklisting unverified devices, null if the global value should be used for this room.
getBumpStamp()
Section titled “getBumpStamp()”getBumpStamp():
number|undefined
Defined in: src/models/room.ts:1667
Get the bump stamp for this room. This can be used for sorting rooms when the timeline entries are unknown. Used in MSC4186: Simplified Sliding Sync.
Returns
Section titled “Returns”number | undefined
The bump stamp for the room, if it exists.
getCanonicalAlias()
Section titled “getCanonicalAlias()”getCanonicalAlias():
string|null
Defined in: src/models/room.ts:1828
Get this room’s canonical alias The alias returned by this function may not necessarily still point to this room.
Returns
Section titled “Returns”string | null
The room’s canonical alias, or null if there is none
getCreator()
Section titled “getCreator()”getCreator():
string|null
Defined in: src/models/room.ts:615
Gets the creator of the room
Returns
Section titled “Returns”string | null
The creator of the room, or null if it could not be determined
getDefaultRoomName()
Section titled “getDefaultRoomName()”getDefaultRoomName(
userId):string
Defined in: src/models/room.ts:1986
Get the default room name (i.e. what a given user would see if the room had no m.room.name)
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The userId from whose perspective we want to calculate the default name
Returns
Section titled “Returns”string
The default room name
getDMInviter()
Section titled “getDMInviter()”getDMInviter():
string|undefined
Defined in: src/models/room.ts:887
If this room is a DM we’re invited to, try to find out who invited us
Returns
Section titled “Returns”string | undefined
user id of the inviter
getEncryptionTargetMembers()
Section titled “getEncryptionTargetMembers()”getEncryptionTargetMembers():
Promise<RoomMember[]>
Defined in: src/models/room.ts:1961
Get a list of members we should be encrypting for in this room
Returns
Section titled “Returns”Promise<RoomMember[]>
A list of members who we should encrypt messages for in this room.
getEventForTxnId()
Section titled “getEventForTxnId()”getEventForTxnId(
txnId):DigitalWorldEvent|undefined
Defined in: src/models/room.ts:2892
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”DigitalWorldEvent | undefined
getEventReadUpTo()
Section titled “getEventReadUpTo()”getEventReadUpTo(
userId,ignoreSynthesized?):string|null
Defined in: src/models/read-receipt.ts:127
Get the ID of the event that a given user has read up to, or null if:
- we have received no read receipts for them, or
- the receipt we have points at an event we don’t have, or
- the thread ID in the receipt does not match the thread root of the referenced event.
(The event might not exist if it is not loaded, and the thread ID might not match if the event has moved thread because it was redacted.)
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The user ID to get read receipt event ID for
ignoreSynthesized?
Section titled “ignoreSynthesized?”boolean = false
If true, return only receipts that have been sent by the server, not implicit ones generated by the JS SDK.
Returns
Section titled “Returns”string | null
ID of the latest existing event that the given user has read, or null.
Inherited from
Section titled “Inherited from”ReadReceipt.getEventReadUpTo
getGuestAccess()
Section titled “getGuestAccess()”getGuestAccess():
GuestAccess
Defined in: src/models/room.ts:3546
Returns the history visibility based on the m.room.history_visibility state event, defaulting to shared.
Returns
Section titled “Returns”the history_visibility applied to this room
getHistoryVisibility()
Section titled “getHistoryVisibility()”getHistoryVisibility():
HistoryVisibility
Defined in: src/models/room.ts:3538
Returns the history visibility based on the m.room.history_visibility state event, defaulting to shared.
Returns
Section titled “Returns”the history_visibility applied to this room
getInvitedAndJoinedMemberCount()
Section titled “getInvitedAndJoinedMemberCount()”getInvitedAndJoinedMemberCount():
number
Defined in: src/models/room.ts:1941
Returns the number of invited + joined members in this room
Returns
Section titled “Returns”number
The number of members in this room whose membership is ‘invite’ or ‘join’
getInvitedMemberCount()
Section titled “getInvitedMemberCount()”getInvitedMemberCount():
number
Defined in: src/models/room.ts:1933
Returns the number of invited members in this room
Returns
Section titled “Returns”number
The number of members in this room whose membership is ‘invite’
getJoinedMemberCount()
Section titled “getJoinedMemberCount()”getJoinedMemberCount():
number
Defined in: src/models/room.ts:1925
Returns the number of joined members in this room This method caches the result. This is a wrapper around the method of the same name in roomState, returning its result for the room’s current state.
Returns
Section titled “Returns”number
The number of members in this room whose membership is ‘join’
getJoinedMembers()
Section titled “getJoinedMembers()”getJoinedMembers():
RoomMember[]
Defined in: src/models/room.ts:1914
Get a list of members whose membership state is “join”.
Returns
Section titled “Returns”A list of currently joined members.
getJoinRule()
Section titled “getJoinRule()”getJoinRule():
JoinRule
Defined in: src/models/room.ts:3530
Returns the join rule based on the m.room.join_rule state event, defaulting to invite.
Returns
Section titled “Returns”the join_rule applied to this room
getLastActiveTimestamp()
Section titled “getLastActiveTimestamp()”getLastActiveTimestamp():
number
Defined in: src/models/room.ts:816
Get the timestamp of the last message in the room
Returns
Section titled “Returns”number
the timestamp of the last message in the room
getLastLiveEvent()
Section titled “getLastLiveEvent()”getLastLiveEvent():
DigitalWorldEvent|undefined
Defined in: src/models/room.ts:837
Returns the last live event of this room. “last” means latest timestamp. Instead of using timestamps, it would be better to do the comparison based on the order of the hub DAG. Unfortunately, this information is currently not available in the client. This is a known limitation; see the project’s issue tracker for status. “live of this room” means from all live timelines: the room and the threads.
Returns
Section titled “Returns”DigitalWorldEvent | undefined
DigitalWorldEvent if there is a last event; else undefined.
getLastThread()
Section titled “getLastThread()”getLastThread():
Thread|undefined
Defined in: src/models/room.ts:858
Returns the last thread of this room. “last” means latest timestamp of the last thread event. Instead of using timestamps, it would be better to do the comparison based on the order of the hub DAG. Unfortunately, this information is currently not available in the client. This is a known limitation; see the project’s issue tracker for status.
Returns
Section titled “Returns”Thread | undefined
the thread with the most recent event in its live time line. undefined if there is no thread.
getLastUnthreadedReceiptFor()
Section titled “getLastUnthreadedReceiptFor()”getLastUnthreadedReceiptFor(
userId):Receipt|undefined
Defined in: src/models/room.ts:3965
Returns the most recent unthreaded receipt for a given user
Parameters
Section titled “Parameters”userId
Section titled “userId”string
the MxID of the User
Returns
Section titled “Returns”Receipt | undefined
an unthreaded Receipt. Can be undefined if receipts have been disabled or a user chooses to use private read receipts (or we have simply not received a receipt from this user yet).
Overrides
Section titled “Overrides”ReadReceipt.getLastUnthreadedReceiptFor
getLiveTimeline()
Section titled “getLiveTimeline()”getLiveTimeline():
EventTimeline
Defined in: src/models/room.ts:797
Get the live unfiltered timeline for this room.
Returns
Section titled “Returns”live timeline
getMaxListeners()
Section titled “getMaxListeners()”getMaxListeners():
number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:819
Returns the current max listener value for the EventEmitter which is either
set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.
Returns
Section titled “Returns”number
v1.0.0
Inherited from
Section titled “Inherited from”ReadReceipt.getMaxListeners
getMember()
Section titled “getMember()”getMember(
userId):RoomMember|null
Defined in: src/models/room.ts:1897
Get a member from the current room state.
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The user ID of the member.
Returns
Section titled “Returns”RoomMember | null
The member or null.
getMembers()
Section titled “getMembers()”getMembers():
RoomMember[]
Defined in: src/models/room.ts:1906
Get all currently loaded members from the current room state.
Returns
Section titled “Returns”Room members
getMembersWithMembership()
Section titled “getMembersWithMembership()”getMembersWithMembership(
membership):RoomMember[]
Defined in: src/models/room.ts:1950
Get a list of members with given membership state.
Parameters
Section titled “Parameters”membership
Section titled “membership”string
The membership state.
Returns
Section titled “Returns”A list of members with the given membership state.
getMxcAvatarUrl()
Section titled “getMxcAvatarUrl()”getMxcAvatarUrl():
string|null
Defined in: src/models/room.ts:1817
Get the mxc avatar url for the room, if one was set.
Returns
Section titled “Returns”string | null
the mxc avatar url or falsy
getMyMembership()
Section titled “getMyMembership()”getMyMembership():
string
Defined in: src/models/room.ts:878
Returns
Section titled “Returns”string
the membership type (join | leave | invite | knock) for the logged in user
getOldestThreadedReceiptTs()
Section titled “getOldestThreadedReceiptTs()”getOldestThreadedReceiptTs():
number
Defined in: src/models/room.ts:3941
Find when a client has gained thread capabilities by inspecting the oldest threaded receipt
Returns
Section titled “Returns”number
the timestamp of the oldest threaded receipt
getOrCreateFilteredTimelineSet()
Section titled “getOrCreateFilteredTimelineSet()”getOrCreateFilteredTimelineSet(
filter,opts?):EventTimelineSet
Defined in: src/models/room.ts:2010
Add a timelineSet for this room with the given filter
Parameters
Section titled “Parameters”filter
Section titled “filter”The filter to be applied to this timelineSet
ICreateFilterOpts = {}
Configuration options
Returns
Section titled “Returns”The timelineSet
getPendingEvent()
Section titled “getPendingEvent()”getPendingEvent(
eventId):DigitalWorldEvent|null
Defined in: src/models/room.ts:788
Get a specific event from the pending event list, if configured, null otherwise.
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
The event ID to check for.
Returns
Section titled “Returns”DigitalWorldEvent | null
getPendingEvents()
Section titled “getPendingEvents()”getPendingEvents():
DigitalWorldEvent[]
Defined in: src/models/room.ts:738
Get the list of pending sent events for this room
Returns
Section titled “Returns”A list of the sent events waiting for remote echo.
Throws
Section titled “Throws”If opts.pendingEventOrdering was not ‘detached’
getReadReceiptForUserId()
Section titled “getReadReceiptForUserId()”getReadReceiptForUserId(
userId,ignoreSynthesized?,receiptType?):WrappedReceipt|null
Defined in: src/models/read-receipt.ts:91
Gets the latest receipt for a given user in the room
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The id of the user for which we want the receipt
ignoreSynthesized?
Section titled “ignoreSynthesized?”boolean = false
Whether to ignore synthesized receipts or not
receiptType?
Section titled “receiptType?”ReceiptType = ReceiptType.Read
Optional. The type of the receipt we want to get
Returns
Section titled “Returns”WrappedReceipt | null
the latest receipts of the chosen type for the chosen user
Inherited from
Section titled “Inherited from”ReadReceipt.getReadReceiptForUserId
getReceiptsForEvent()
Section titled “getReceiptsForEvent()”getReceiptsForEvent(
event):CachedReceipt[]
Defined in: src/models/read-receipt.ts:339
Get a list of receipts for the given event.
Parameters
Section titled “Parameters”the event to get receipts for
Returns
Section titled “Returns”A list of receipts with a userId, type and data keys or an empty list.
Inherited from
Section titled “Inherited from”ReadReceipt.getReceiptsForEvent
getRecommendedVersion()
Section titled “getRecommendedVersion()”getRecommendedVersion():
Promise<IRecommendedVersion>
Defined in: src/models/room.ts:639
Determines the recommended room version for the room. This returns an
object with 3 properties: version as the new version the
room should be upgraded to (may be the same as the current version);
needsUpgrade to indicate if the room actually can be
upgraded (ie: does the current version not match?); and urgent
to indicate if the new version patches a vulnerability in a previous
version.
Returns
Section titled “Returns”Promise<IRecommendedVersion>
Resolves to the version the room should be upgraded to.
getRoomUnreadNotificationCount()
Section titled “getRoomUnreadNotificationCount()”getRoomUnreadNotificationCount(
type?):number
Defined in: src/models/room.ts:1563
Get one of the notification counts for this room
Parameters
Section titled “Parameters”NotificationCountType = NotificationCountType.Total
The type of notification count to get. default: ‘total’
Returns
Section titled “Returns”number
The notification count, or undefined if there is no count for this type.
getThread()
Section titled “getThread()”getThread(
eventId):Thread|null
Defined in: src/models/room.ts:1881
Get the instance of the thread associated with the current event
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
the ID of the current event
Returns
Section titled “Returns”Thread | null
a thread instance if known
getThreads()
Section titled “getThreads()”getThreads():
Thread[]
Defined in: src/models/room.ts:1888
Get all the known threads in the room
Returns
Section titled “Returns”Thread[]
getThreadUnreadNotificationCount()
Section titled “getThreadUnreadNotificationCount()”getThreadUnreadNotificationCount(
threadId,type?):number
Defined in: src/models/room.ts:1574
Get one of the notification counts for a thread
Parameters
Section titled “Parameters”threadId
Section titled “threadId”string
the root event ID
NotificationCountType = NotificationCountType.Total
The type of notification count to get. default: ‘total’
Returns
Section titled “Returns”number
The notification count, or undefined if there is no count for this type.
getTimelineForEvent()
Section titled “getTimelineForEvent()”getTimelineForEvent(
eventId):EventTimeline|null
Defined in: src/models/room.ts:1470
Get the timeline which contains the given event from the unfiltered set, if any
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
event ID to look for
Returns
Section titled “Returns”EventTimeline | null
timeline containing the given event, or null if unknown
getTimelineNeedsRefresh()
Section titled “getTimelineNeedsRefresh()”getTimelineNeedsRefresh():
boolean
Defined in: src/models/room.ts:1503
Whether the timeline needs to be refreshed in order to pull in new historical messages that were imported.
Returns
Section titled “Returns”boolean
.
getTimelineSets()
Section titled “getTimelineSets()”getTimelineSets():
EventTimelineSet[]
Defined in: src/models/room.ts:1451
Return the timeline sets for this room.
Returns
Section titled “Returns”array of timeline sets for this room
getType()
Section titled “getType()”getType():
string|undefined
Defined in: src/models/room.ts:3554
Returns the type of the room from the m.room.create event content or undefined if none is set
Returns
Section titled “Returns”string | undefined
the type of the room.
getUnfilteredTimelineSet()
Section titled “getUnfilteredTimelineSet()”getUnfilteredTimelineSet():
EventTimelineSet
Defined in: src/models/room.ts:1459
Helper to return the main unfiltered timeline set for this room
Returns
Section titled “Returns”room’s unfiltered timeline set
Overrides
Section titled “Overrides”ReadReceipt.getUnfilteredTimelineSet
getUnreadCountForEventContext()
Section titled “getUnreadCountForEventContext()”getUnreadCountForEventContext(
type?,event):number
Defined in: src/models/room.ts:1547
Get the notification for the event context (room or thread timeline)
Parameters
Section titled “Parameters”NotificationCountType = NotificationCountType.Total
Returns
Section titled “Returns”number
getUnreadNotificationCount()
Section titled “getUnreadNotificationCount()”getUnreadNotificationCount(
type?):number
Defined in: src/models/room.ts:1536
Get one of the notification counts for this room
Parameters
Section titled “Parameters”NotificationCountType = NotificationCountType.Total
The type of notification count to get. default: ‘total’
Returns
Section titled “Returns”number
The notification count, or undefined if there is no count for this type.
getUsersReadUpTo()
Section titled “getUsersReadUpTo()”getUsersReadUpTo(
event):string[]
Defined in: src/models/read-receipt.ts:392
Get a list of user IDs who have read up to the given event.
Parameters
Section titled “Parameters”the event to get read receipts for.
Returns
Section titled “Returns”string[]
A list of user IDs.
Inherited from
Section titled “Inherited from”ReadReceipt.getUsersReadUpTo
getVersion()
Section titled “getVersion()”getVersion():
string
Defined in: src/models/room.ts:624
Gets the version of the room
Returns
Section titled “Returns”string
The version of the room
guessDMUserId()
Section titled “guessDMUserId()”guessDMUserId():
string
Defined in: src/models/room.ts:906
Assuming this room is a DM room, tries to guess with which user.
Returns
Section titled “Returns”string
user id of the other member (could be syncing user)
hasEncryptionStateEvent()
Section titled “hasEncryptionStateEvent()”hasEncryptionStateEvent():
boolean
Defined in: src/models/room.ts:4021
Return true if this room has an m.room.encryption state event.
If this returns true, events sent to this room should be encrypted (and DigitalWorldClient.sendEvent and friends
will encrypt outgoing events).
Returns
Section titled “Returns”boolean
hasMembershipState()
Section titled “hasMembershipState()”hasMembershipState(
userId,membership):boolean
Defined in: src/models/room.ts:1996
Check if the given user_id has the given membership state.
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The user ID to check.
membership
Section titled “membership”string
The membership e.g. 'join'
Returns
Section titled “Returns”boolean
True if this user_id has the given membership state.
hasPendingEvent()
Section titled “hasPendingEvent()”hasPendingEvent(
eventId):boolean
Defined in: src/models/room.ts:779
Check whether the pending event list contains a given event by ID. If pending event ordering is not “detached” then this returns false.
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
The event ID to check for.
Returns
Section titled “Returns”boolean
hasThreadUnreadNotification()
Section titled “hasThreadUnreadNotification()”hasThreadUnreadNotification():
boolean
Defined in: src/models/room.ts:1582
Checks if the current room has unread thread notifications
Returns
Section titled “Returns”boolean
hasUserReadEvent()
Section titled “hasUserReadEvent()”hasUserReadEvent(
userId,eventId):boolean
Defined in: src/models/room.ts:3954
Determines if the given user has read a particular event ID with the known history of the room. This is not a definitive check as it relies only on what is available to the room at the time of execution.
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The user ID to check the read state of.
eventId
Section titled “eventId”string
The event ID to check if the user read.
Returns
Section titled “Returns”boolean
true if the user has read the event, false otherwise.
Overrides
Section titled “Overrides”ReadReceipt.hasUserReadEvent
isCallRoom()
Section titled “isCallRoom()”isCallRoom():
boolean
Defined in: src/models/room.ts:3578
Returns whether the room is a call-room as defined by MSC3417.
Returns
Section titled “Returns”boolean
true if the room’s type is RoomType.UnstableCall
isElementVideoRoom()
Section titled “isElementVideoRoom()”isElementVideoRoom():
boolean
Defined in: src/models/room.ts:3586
Returns whether the room is a video room.
Returns
Section titled “Returns”boolean
true if the room’s type is RoomType.ElementVideo
isSpaceRoom()
Section titled “isSpaceRoom()”isSpaceRoom():
boolean
Defined in: src/models/room.ts:3570
Returns whether the room is a space-room as defined by MSC1772.
Returns
Section titled “Returns”boolean
true if the room’s type is RoomType.Space
listenerCount()
Section titled “listenerCount()”listenerCount(
event):number
Defined in: src/models/typed-event-emitter.ts:115
Returns the number of listeners listening to the event named event.
Parameters
Section titled “Parameters”EventEmitterEvents | RoomEmittedEvents
The name of the event being listened for
Returns
Section titled “Returns”number
Inherited from
Section titled “Inherited from”ReadReceipt.listenerCount
listeners()
Section titled “listeners()”listeners(
event):Function[]
Defined in: src/models/typed-event-emitter.ts:122
Returns a copy of the array of listeners for the event named event.
Parameters
Section titled “Parameters”EventEmitterEvents | RoomEmittedEvents
Returns
Section titled “Returns”Function[]
Inherited from
Section titled “Inherited from”ReadReceipt.listeners
loadMembersIfNeeded()
Section titled “loadMembersIfNeeded()”loadMembersIfNeeded():
Promise<boolean>
Defined in: src/models/room.ts:1099
Preloads the member list in case lazy loading of memberships is in use. Can be called multiple times, it will only preload once.
Returns
Section titled “Returns”Promise<boolean>
when preloading is done and accessing the members on the room will take all members in the room into account
maySendMessage()
Section titled “maySendMessage()”maySendMessage():
boolean
Defined in: src/models/room.ts:3501
Returns whether the syncing user has permission to send a message in the room
Returns
Section titled “Returns”boolean
true if the user should be permitted to send message events into the room.
membersLoaded()
Section titled “membersLoaded()”membersLoaded():
boolean
Defined in: src/models/room.ts:1083
Check if loading of out-of-band-members has completed
Returns
Section titled “Returns”boolean
true if the full membership list of this room has been loaded (including if lazy-loading is disabled). False if the load is not started or is in progress.
off<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:129
Alias for removeListener
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | RoomEmittedEvents
Parameters
Section titled “Parameters”T
listener
Section titled “listener”Listener<RoomEmittedEvents, RoomEventHandlerMap, T>
Returns
Section titled “Returns”this
Inherited from
Section titled “Inherited from”ReadReceipt.off
on<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:150
Adds the listener function to the end of the listeners array for the
event named event.
No checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added, and called, multiple times.
By default, event listeners are invoked in the order they are added. The prependListener method can be used as an alternative to add the event listener to the beginning of the listeners array.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<RoomEmittedEvents, RoomEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”ReadReceipt.on
once()
Section titled “once()”once<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:169
Adds a one-time listener function for the event named event. The
next time event is triggered, this listener is removed and then invoked.
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The prependOnceListener method can be used as an alternative to add the event listener to the beginning of the listeners array.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<RoomEmittedEvents, RoomEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”ReadReceipt.once
partitionThreadedEvents()
Section titled “partitionThreadedEvents()”partitionThreadedEvents(
events): [DigitalWorldEvent[],DigitalWorldEvent[],DigitalWorldEvent[]]
Defined in: src/models/room.ts:3171
Parameters
Section titled “Parameters”events
Section titled “events”Returns
Section titled “Returns”[DigitalWorldEvent[], DigitalWorldEvent[], DigitalWorldEvent[]]
prependListener()
Section titled “prependListener()”prependListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:186
Adds the listener function to the beginning of the listeners array for the
event named event.
No checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added, and called, multiple times.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<RoomEmittedEvents, RoomEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”ReadReceipt.prependListener
prependOnceListener()
Section titled “prependOnceListener()”prependOnceListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:202
Adds a one-timelistener function for the event named event to the beginning of the listeners array.
The next time event is triggered, this listener is removed, and then invoked.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | RoomEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<RoomEmittedEvents, RoomEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”ReadReceipt.prependOnceListener
processPollEvents()
Section titled “processPollEvents()”processPollEvents(
events):Promise<void>
Defined in: src/models/room.ts:2233
Process a list of poll events.
Parameters
Section titled “Parameters”events
Section titled “events”List of events
Returns
Section titled “Returns”Promise<void>
processThreadedEvents()
Section titled “processThreadedEvents()”processThreadedEvents(
events,toStartOfTimeline):void
Defined in: src/models/room.ts:2474
Adds events to a thread’s timeline. Will fire “Thread.update”
Parameters
Section titled “Parameters”events
Section titled “events”toStartOfTimeline
Section titled “toStartOfTimeline”boolean
Returns
Section titled “Returns”void
processThreadRoots()
Section titled “processThreadRoots()”processThreadRoots(
events,toStartOfTimeline):void
Defined in: src/models/room.ts:2139
Takes the given thread root events and creates threads for them.
Parameters
Section titled “Parameters”events
Section titled “events”toStartOfTimeline
Section titled “toStartOfTimeline”boolean
Returns
Section titled “Returns”void
rawListeners()
Section titled “rawListeners()”rawListeners(
event):Function[]
Defined in: src/models/typed-event-emitter.ts:243
Returns a copy of the array of listeners for the event named eventName,
including any wrappers (such as those created by .once()).
Parameters
Section titled “Parameters”EventEmitterEvents | RoomEmittedEvents
Returns
Section titled “Returns”Function[]
Inherited from
Section titled “Inherited from”ReadReceipt.rawListeners
recalculate()
Section titled “recalculate()”recalculate():
void
Defined in: src/models/room.ts:3357
Recalculate various aspects of the room, including the room name and room summary. Call this any time the room’s current state is modified. May fire “Room.name” if the room name is updated.
Returns
Section titled “Returns”void
Remarks
Section titled “Remarks”Fires RoomEvent.Name
refreshLiveTimeline()
Section titled “refreshLiveTimeline()”refreshLiveTimeline():
Promise<void>
Defined in: src/models/room.ts:1190
Empty out the current live timeline and re-request it. This is used when
historical messages are imported into the room via MSC2716 /batch_send
because the client may already have that section of the timeline loaded.
We need to force the client to throw away their current timeline so that
when they back paginate over the area again with the historical messages
in between, it grabs the newly imported messages. We can listen for
UNSTABLE_MSC2716_MARKER, in order to tell when historical messages are ready
to be discovered in the room and the timeline needs a refresh. The SDK
emits a RoomEvent.HistoryImportedWithinTimeline event when we detect a
valid marker and can check the needs refresh status via
room.getTimelineNeedsRefresh().
Returns
Section titled “Returns”Promise<void>
removeAllListeners()
Section titled “removeAllListeners()”removeAllListeners(
event?):this
Defined in: src/models/typed-event-emitter.ts:219
Removes all listeners, or those of the specified event.
It is bad practice to remove listeners added elsewhere in the code,
particularly when the EventEmitter instance was created by some other
component or module (e.g. sockets or file streams).
Parameters
Section titled “Parameters”event?
Section titled “event?”EventEmitterEvents | RoomEmittedEvents
The name of the event. If undefined, all listeners everywhere are removed.
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”ReadReceipt.removeAllListeners
removeEvent()
Section titled “removeEvent()”removeEvent(
eventId):boolean
Defined in: src/models/room.ts:3335
Removes a single event from this room.
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
The id of the event to remove
Returns
Section titled “Returns”boolean
true if the event was removed from any of the room’s timeline sets
removeEvents()
Section titled “removeEvents()”removeEvents(
eventIds):void
Defined in: src/models/room.ts:3322
Removes events from this room.
Parameters
Section titled “Parameters”eventIds
Section titled “eventIds”string[]
A list of eventIds to remove.
Returns
Section titled “Returns”void
removeFilteredTimelineSet()
Section titled “removeFilteredTimelineSet()”removeFilteredTimelineSet(
filter):void
Defined in: src/models/room.ts:2356
Forget the timelineSet for this room with the given filter
Parameters
Section titled “Parameters”filter
Section titled “filter”the filter whose timelineSet is to be forgotten
Returns
Section titled “Returns”void
removeListener()
Section titled “removeListener()”removeListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:232
Removes the specified listener from the listener array for the event named event.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | RoomEmittedEvents
Parameters
Section titled “Parameters”T
listener
Section titled “listener”Listener<RoomEmittedEvents, RoomEventHandlerMap, T>
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”ReadReceipt.removeListener
removePendingEvent()
Section titled “removePendingEvent()”removePendingEvent(
eventId):boolean
Defined in: src/models/room.ts:753
Removes a pending event for this room
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
Returns
Section titled “Returns”boolean
True if an element was removed.
resetLiveTimeline()
Section titled “resetLiveTimeline()”resetLiveTimeline(
backPaginationToken?,forwardPaginationToken?):void
Defined in: src/models/room.ts:1291
Reset the live timeline of all timelineSets, and start new ones.
This is used when /sync returns a 'limited' timeline.
Parameters
Section titled “Parameters”backPaginationToken?
Section titled “backPaginationToken?”string | null
token for back-paginating the new timeline
forwardPaginationToken?
Section titled “forwardPaginationToken?”string | null
token for forward-paginating the old live timeline, if absent or null, all timelines are reset, removing old ones (including the previous live timeline which would otherwise be unable to paginate forwards without this token). Removing just the old live timeline whilst preserving previous ones is not supported.
Returns
Section titled “Returns”void
resetThreadUnreadNotificationCountFromSync()
Section titled “resetThreadUnreadNotificationCountFromSync()”resetThreadUnreadNotificationCountFromSync(
exceptThreadIds?):void
Defined in: src/models/room.ts:1638
Resets the total thread notifications for all threads in this room to zero,
excluding any threads whose IDs are given in exceptThreadIds.
If the room is not encrypted, also resets the highlight notification count to zero for the same set of threads.
This is intended for use from the sync code since we calculate highlight notification counts locally from decrypted messages. We want to partially trust the total from the server such that we clear notifications when read receipts arrive. The weird name is intended to reflect this. You probably do not want to use this.
Parameters
Section titled “Parameters”exceptThreadIds?
Section titled “exceptThreadIds?”string[] = []
The thread IDs to exclude from the reset.
Returns
Section titled “Returns”void
setBlacklistUnverifiedDevices()
Section titled “setBlacklistUnverifiedDevices()”setBlacklistUnverifiedDevices(
value):void
Defined in: src/models/room.ts:1753
Whether to send encrypted messages to devices within this room.
Parameters
Section titled “Parameters”boolean
true to blacklist unverified devices, null to use the global value for this room.
Returns
Section titled “Returns”void
setBumpStamp()
Section titled “setBumpStamp()”setBumpStamp(
bumpStamp):void
Defined in: src/models/room.ts:1658
Set the bump stamp for this room. This can be used for sorting rooms when the timeline entries are unknown. Used in MSC4186: Simplified Sliding Sync.
Parameters
Section titled “Parameters”bumpStamp
Section titled “bumpStamp”number
The bump_stamp value from the server
Returns
Section titled “Returns”void
setMaxListeners()
Section titled “setMaxListeners()”setMaxListeners(
n):this
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:813
By default EventEmitters will print a warning if more than 10 listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. The emitter.setMaxListeners() method allows the limit to be
modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
Parameters
Section titled “Parameters”number
Returns
Section titled “Returns”this
v0.3.5
Inherited from
Section titled “Inherited from”ReadReceipt.setMaxListeners
setMSC4186SummaryData()
Section titled “setMSC4186SummaryData()”setMSC4186SummaryData(
heroes,joinedCount,invitedCount):void
Defined in: src/models/room.ts:1717
Takes information from the MSC4186 room summary and updates the room with it.
Parameters
Section titled “Parameters”heroes
Section titled “heroes”MSC4186Hero[] | undefined
The room’s hero members
joinedCount
Section titled “joinedCount”number | undefined
The number of joined members
invitedCount
Section titled “invitedCount”number | undefined
The number of invited members
Returns
Section titled “Returns”void
setSummary()
Section titled “setSummary()”setSummary(
summary):void
Defined in: src/models/room.ts:1690
Takes a legacy room summary (/v3/sync as opposed to MSC4186) and updates the room with it.
Parameters
Section titled “Parameters”summary
Section titled “summary”The room summary to update the room with
Returns
Section titled “Returns”void
setThreadUnreadNotificationCount()
Section titled “setThreadUnreadNotificationCount()”setThreadUnreadNotificationCount(
threadId,type,count):void
Defined in: src/models/room.ts:1597
Swet one of the notification count for a thread
Parameters
Section titled “Parameters”threadId
Section titled “threadId”string
the root event ID
The type of notification count to get. default: ‘total’
number
Returns
Section titled “Returns”void
setTimelineNeedsRefresh()
Section titled “setTimelineNeedsRefresh()”setTimelineNeedsRefresh(
value):void
Defined in: src/models/room.ts:1494
Whether the timeline needs to be refreshed in order to pull in new historical messages that were imported.
Parameters
Section titled “Parameters”boolean
The value to set
Returns
Section titled “Returns”void
setUnread()
Section titled “setUnread()”setUnread(
type,count):void
Defined in: src/models/room.ts:1681
Parameters
Section titled “Parameters”number
Returns
Section titled “Returns”void
Overrides
Section titled “Overrides”ReadReceipt.setUnread
setUnreadNotificationCount()
Section titled “setUnreadNotificationCount()”setUnreadNotificationCount(
type,count):void
Defined in: src/models/room.ts:1676
Set one of the notification counts for this room
Parameters
Section titled “Parameters”The type of notification count to set.
number
The new count
Returns
Section titled “Returns”void
shouldEncryptForInvitedMembers()
Section titled “shouldEncryptForInvitedMembers()”shouldEncryptForInvitedMembers():
boolean
Defined in: src/models/room.ts:1974
Determine whether we should encrypt messages for invited users in this room
Returns
Section titled “Returns”boolean
if we should encrypt messages for invited users
tryApplyRedaction()
Section titled “tryApplyRedaction()”
readonlytryApplyRedaction(event):void
Defined in: src/models/room.ts:2631
Parameters
Section titled “Parameters”Returns
Section titled “Returns”void
updateMyMembership()
Section titled “updateMyMembership()”updateMyMembership(
membership):void
Defined in: src/models/room.ts:1037
Sets the membership this room was received as during sync
Parameters
Section titled “Parameters”membership
Section titled “membership”string
join | leave | invite
Returns
Section titled “Returns”void
updatePendingEvent()
Section titled “updatePendingEvent()”updatePendingEvent(
event,newStatus,newEventId?):void
Defined in: src/models/room.ts:2959
Update the status / event id on a pending event, to reflect its transmission progress.
This is an internal method.
Parameters
Section titled “Parameters”local echo event
newStatus
Section titled “newStatus”status to assign
newEventId?
Section titled “newEventId?”string
new event id to assign. Ignored unless newStatus == EventStatus.SENT.
Returns
Section titled “Returns”void
Remarks
Section titled “Remarks”Fires RoomEvent.LocalEchoUpdated
userMayUpgradeRoom()
Section titled “userMayUpgradeRoom()”userMayUpgradeRoom(
userId):boolean
Defined in: src/models/room.ts:726
Determines whether the given user is permitted to perform a room upgrade
Parameters
Section titled “Parameters”userId
Section titled “userId”string
The ID of the user to test against
Returns
Section titled “Returns”boolean
True if the given user is permitted to upgrade the room
addAbortListener()
Section titled “addAbortListener()”
staticaddAbortListener(signal,resource):Disposable
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:403
Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
lead to resource leaks since another third party with the signal can
call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
this since it would violate the web standard. Additionally, the original
API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
two issues by listening to the event such that stopImmediatePropagation does
not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
import { addAbortListener } from 'node:events';
function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); }}Parameters
Section titled “Parameters”signal
Section titled “signal”AbortSignal
resource
Section titled “resource”(event) => void
Returns
Section titled “Returns”Disposable
Disposable that removes the abort listener.
v20.5.0
Inherited from
Section titled “Inherited from”ReadReceipt.addAbortListener
getEventListeners()
Section titled “getEventListeners()”
staticgetEventListeners(emitter,name):Function[]
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:325
Returns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
the emitter.
For EventTargets this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{ const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]}{ const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]}Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter<DefaultEventMap> | EventTarget
string | symbol
Returns
Section titled “Returns”Function[]
v15.2.0, v14.17.0
Inherited from
Section titled “Inherited from”ReadReceipt.getEventListeners
getMaxListeners()
Section titled “getMaxListeners()”
staticgetMaxListeners(emitter):number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:354
Returns the currently set max amount of listeners.
For EventEmitters this behaves exactly the same as calling .getMaxListeners on
the emitter.
For EventTargets this is the only way to get the max event listeners for the
event target. If the number of event handlers on a single EventTarget exceeds
the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{ const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11}{ const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11}Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter<DefaultEventMap> | EventTarget
Returns
Section titled “Returns”number
v19.9.0
Inherited from
Section titled “Inherited from”ReadReceipt.getMaxListeners
listenerCount()
Section titled “listenerCount()”
staticlistenerCount(emitter,eventName):number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:297
A class method that returns the number of listeners for the given eventName registered on the given emitter.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();myEmitter.on('event', () => {});myEmitter.on('event', () => {});console.log(listenerCount(myEmitter, 'event'));// Prints: 2Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter
The emitter to query
eventName
Section titled “eventName”string | symbol
The event name
Returns
Section titled “Returns”number
v0.9.12
Inherited from
Section titled “Inherited from”ReadReceipt.listenerCount
Call Signature
Section titled “Call Signature”
staticon(emitter,eventName,options?):AsyncIterator<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:270
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42);});
for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42]}// Unreachable hereReturns an AsyncIterator that iterates eventName events. It will throw
if the EventEmitter emits 'error'. It removes all listeners when
exiting the loop. The value returned by each iteration is an array
composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ac = new AbortController();
(async () => { const ee = new EventEmitter();
// Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); });
for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here})();
process.nextTick(() => ac.abort());Use the close option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close');});
for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42]}// the loop will exit after 'close' is emittedconsole.log('done'); // prints 'done'Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter
eventName
Section titled “eventName”string | symbol
options?
Section titled “options?”StaticEventEmitterIteratorOptions
Returns
Section titled “Returns”AsyncIterator<any[]>
An AsyncIterator that iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
Inherited from
Section titled “Inherited from”ReadReceipt.on
Call Signature
Section titled “Call Signature”
staticon(emitter,eventName,options?):AsyncIterator<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:275
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42);});
for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42]}// Unreachable hereReturns an AsyncIterator that iterates eventName events. It will throw
if the EventEmitter emits 'error'. It removes all listeners when
exiting the loop. The value returned by each iteration is an array
composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ac = new AbortController();
(async () => { const ee = new EventEmitter();
// Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); });
for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here})();
process.nextTick(() => ac.abort());Use the close option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close');});
for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42]}// the loop will exit after 'close' is emittedconsole.log('done'); // prints 'done'Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventTarget
eventName
Section titled “eventName”string
options?
Section titled “options?”StaticEventEmitterIteratorOptions
Returns
Section titled “Returns”AsyncIterator<any[]>
An AsyncIterator that iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
Inherited from
Section titled “Inherited from”ReadReceipt.on
once()
Section titled “once()”Call Signature
Section titled “Call Signature”
staticonce(emitter,eventName,options?):Promise<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:184
Creates a Promise that is fulfilled when the EventEmitter emits the given
event or that is rejected if the EventEmitter emits 'error' while waiting.
The Promise will resolve with an array of all the arguments emitted to the
given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
semantics and does not listen to the 'error' event.
import { once, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => { ee.emit('myevent', 42);});
const [value] = await once(ee, 'myevent');console.log(value);
const err = new Error('kaboom');process.nextTick(() => { ee.emit('error', err);});
try { await once(ee, 'myevent');} catch (err) { console.error('error happened', err);}The special handling of the 'error' event is only used when events.once() is used to wait for another event. If events.once() is used to wait for the
’error' event itself, then it is treated as any other kind of event without
special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boomAn AbortSignal can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();const ac = new AbortController();
async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } }}
foo(ee, 'foo', ac.signal);ac.abort(); // Abort waiting for the eventee.emit('foo'); // Prints: Waiting for the event was canceled!Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter
eventName
Section titled “eventName”string | symbol
options?
Section titled “options?”StaticEventEmitterOptions
Returns
Section titled “Returns”Promise<any[]>
v11.13.0, v10.16.0
Inherited from
Section titled “Inherited from”ReadReceipt.once
Call Signature
Section titled “Call Signature”
staticonce(emitter,eventName,options?):Promise<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:189
Creates a Promise that is fulfilled when the EventEmitter emits the given
event or that is rejected if the EventEmitter emits 'error' while waiting.
The Promise will resolve with an array of all the arguments emitted to the
given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
semantics and does not listen to the 'error' event.
import { once, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => { ee.emit('myevent', 42);});
const [value] = await once(ee, 'myevent');console.log(value);
const err = new Error('kaboom');process.nextTick(() => { ee.emit('error', err);});
try { await once(ee, 'myevent');} catch (err) { console.error('error happened', err);}The special handling of the 'error' event is only used when events.once() is used to wait for another event. If events.once() is used to wait for the
’error' event itself, then it is treated as any other kind of event without
special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boomAn AbortSignal can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();const ac = new AbortController();
async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } }}
foo(ee, 'foo', ac.signal);ac.abort(); // Abort waiting for the eventee.emit('foo'); // Prints: Waiting for the event was canceled!Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventTarget
eventName
Section titled “eventName”string
options?
Section titled “options?”StaticEventEmitterOptions
Returns
Section titled “Returns”Promise<any[]>
v11.13.0, v10.16.0
Inherited from
Section titled “Inherited from”ReadReceipt.once
setMaxListeners()
Section titled “setMaxListeners()”
staticsetMaxListeners(n?, …eventTargets):void
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:369
import { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);Parameters
Section titled “Parameters”number
A non-negative number. The maximum number of listeners per EventTarget event.
eventTargets
Section titled “eventTargets”…(EventEmitter<DefaultEventMap> | EventTarget)[]
Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, n is set as the default max for all newly created {EventTarget} and {EventEmitter}
objects.
Returns
Section titled “Returns”void
v15.4.0
Inherited from
Section titled “Inherited from”ReadReceipt.setMaxListeners