TLSocketRoom

See source code
Table of contents
class TLSocketRoom<
  R extends UnknownRecord = UnknownRecord,
  SessionMeta = void,
> {}

Constructor

Constructs a new instance of the TLSocketRoom class

Parameters

NameDescription

opts

{
  clientTimeout?: number
  initialSnapshot?: RoomSnapshot | TLStoreSnapshot
  log?: TLSyncLog
  onAfterReceiveMessage?: (args: {
    message: TLSocketServerSentEvent<R>
    meta: SessionMeta
    sessionId: string
    stringified: string
  }) => void
  onBeforeSendMessage?: (args: {
    message: TLSocketServerSentEvent<R>
    meta: SessionMeta
    sessionId: string
    stringified: string
  }) => void
  onDataChange?: () => void
  onSessionRemoved?: (
    room: TLSocketRoom<R, SessionMeta>,
    args: {
      meta: SessionMeta
      numSessionsRemaining: number
      sessionId: string
    }
  ) => void
  schema?: StoreSchema<R, any>
}

Properties

log

readonlyoptional
readonly log?: TLSyncLog

opts

readonly
readonly opts: {
  clientTimeout?: number
  initialSnapshot?: RoomSnapshot | TLStoreSnapshot
  log?: TLSyncLog
  onAfterReceiveMessage?: (args: {
    message: TLSocketServerSentEvent<R>
    meta: SessionMeta
    sessionId: string
    stringified: string
  }) => void
  onBeforeSendMessage?: (args: {
    message: TLSocketServerSentEvent<R>
    meta: SessionMeta
    sessionId: string
    stringified: string
  }) => void
  onDataChange?: () => void
  onSessionRemoved?: (
    room: TLSocketRoom<R, SessionMeta>,
    args: {
      meta: SessionMeta
      numSessionsRemaining: number
      sessionId: string
    }
  ) => void
  schema?: StoreSchema<R, any>
}

Methods

close()

Close the room and disconnect all clients. Call this before discarding the room instance or shutting down the server.

close(): void

closeSession()

Immediately remove a session from the room, and close its socket if not already closed.

The client will attempt to reconnect unless you provide a fatalReason parameter.

The fatalReason parameter will be available in the return value of the useSync hook as useSync().error.reason.

closeSession(
  sessionId: string,
  fatalReason?: string | TLSyncErrorCloseEventReason
): void

Parameters

NameDescription

sessionId

string

The id of the session to remove

fatalReason

The reason message to use when calling .close on the underlying websocket

Returns

void

getCurrentDocumentClock()

Returns the current 'clock' of the document. The clock is an integer that increments every time the document changes. The clock is stored as part of the snapshot of the document for consistency purposes.

getCurrentDocumentClock(): number

getCurrentSnapshot()

Return a snapshot of the document state, including clock-related bookkeeping. You can store this and load it later on when initializing a TLSocketRoom. You can also pass a snapshot to if you need to revert to a previous state.

getCurrentSnapshot(): RoomSnapshot

getNumActiveSessions()

Returns the number of active sessions. Note that this is not the same as the number of connected sockets! Sessions time out a few moments after sockets close, to smooth over network hiccups.

getNumActiveSessions(): number

getRecord()

Returns a deeply cloned record from the store, if available.

getRecord(id: string): R

Parameters

NameDescription

id

string

The id of the record

Returns

R

the cloned record


getSessions()

Returns a list of the sessions in the room.

getSessions(): Array<{
  isConnected: boolean
  isReadonly: boolean
  meta: SessionMeta
  sessionId: string
}>

handleSocketClose()

If executing in a server environment where sockets do not have instance-level listeners, call this when a socket is closed.

handleSocketClose(sessionId: string): void

Parameters

NameDescription

sessionId

string

The id of the session. (should match the one used when calling handleSocketConnect)

Returns

void

handleSocketConnect()

Call this when a client establishes a new socket connection.

  • sessionId is a unique ID for a browser tab. This is passed as a query param by the useSync hook.
  • socket is a WebSocket-like object that the server uses to communicate with the client.
  • isReadonly is an optional boolean that can be set to true if the client should not be able to make changes to the document. They will still be able to send presence updates.
  • meta is an optional object that can be used to store additional information about the session.
handleSocketConnect(
  opts: {
    isReadonly?: boolean
    sessionId: string
    socket: WebSocketMinimal
  } & (SessionMeta extends void
    ? object
    : {
        meta: SessionMeta
      })
): void

Parameters

NameDescription

opts

{
  isReadonly?: boolean
  sessionId: string
  socket: WebSocketMinimal
} & (SessionMeta extends void
  ? object
  : {
      meta: SessionMeta
    })

The options object

Returns

void

handleSocketError()

If executing in a server environment where sockets do not have instance-level listeners, call this when a socket error occurs.

handleSocketError(sessionId: string): void

Parameters

NameDescription

sessionId

string

The id of the session. (should match the one used when calling handleSocketConnect)

Returns

void

handleSocketMessage()

If executing in a server environment where sockets do not have instance-level listeners (e.g. Bun.serve, Cloudflare Worker with WebSocket hibernation), you should call this method when messages are received. See our self-hosting example for Bun.serve for an example.

handleSocketMessage(
  sessionId: string,
  message: AllowSharedBufferSource | string
): void

Parameters

NameDescription

sessionId

string

The id of the session. (should match the one used when calling handleSocketConnect)

message

AllowSharedBufferSource | string

The message received from the client.

Returns

void

isClosed()

isClosed(): boolean

loadSnapshot()

Load a snapshot of the document state, overwriting the current state.

loadSnapshot(snapshot: RoomSnapshot | TLStoreSnapshot): void

Parameters

NameDescription

snapshot

The snapshot to load

Returns

void

updateStore()

Allow applying changes to the store inside of a transaction.

You can get values from the store by id with store.get(id). These values are safe to mutate, but to commit the changes you must call store.put(...) with the updated value. You can get all values in the store with store.getAll(). You can also delete values with store.delete(id).

updateStore(
  updater: (store: RoomStoreMethods<R>) => Promise<void> | void
): Promise<void>

Example

room.updateStore((store) => {
  const shape = store.get('shape:abc123')
  shape.meta.approved = true
  store.put(shape)
})

Changes to the store inside the callback are isolated from changes made by other clients until the transaction commits.

Parameters

NameDescription

updater

(
  store: RoomStoreMethods<R>
) => Promise<void> | void

A function that will be called with a store object that can be used to make changes.

Returns

Promise<void>

A promise that resolves when the transaction is complete.


Prev
TLRemoteSyncError
Next
ArrowBindingUtil