# Client API on one page

> The whole Client API on one page, everything @irtio/client exports, for reading straight through.

This page is the whole [Client API](/docs/client) on one page, for
reading straight through. The Client API reference gives each interface,
member, event and function a page of its own, and the two always agree.

`@irtio/client` runs in browsers and in Node 24 or later. It connects over
WebTransport when the platform has it and falls back to WebSocket; Node
has no WebTransport, so it uses WebSocket. See [Node clients and bots](/docs/client/guides/node)
for running it from scripts. A page with no build step imports the same
module from `https://irt.io/client/5.js`; see [Start with a script
tag](/docs/guides/script-tag).

```ts
import {
  connect, RoomClient, type ReadyRoomClient, IrtError, CloseCode, defineSchema, defineCalls, call, defineStepper, entity, json,
  createRoom, joinByCode, listPublic, quickJoin, reloadForNewBuild, RoomOpenEvent, RoomMessageEvent, RoomCloseEvent, PresenceEvent,
  expose, isPlaytest,
  type ConnectInit, type ReadyState, type RoomClientEventMap, type ClientEntity, type Prediction, type Interpolator, type Reckoner, type WireStats,
} from "@irtio/client";
```

The package's entry points match the [script tag's
files](/docs/guides/script-tag): `@irtio/client`, `@irtio/client/ui`
(every UI kit element), `@irtio/client/voice`, `@irtio/client/replay` and
`@irtio/client/dev`, plus `@irtio/client/token` for signing player
tokens in your backend.

## Room URLs

Every room has a URL, `https://rooms.irt.io/<project>/<room ID>`, and
every project one, `https://rooms.irt.io/<project>/`, that room URLs
resolve against. A page declares its project URL in a meta tag, as it
declares a base URL:

```html
<meta name="irt-project" content="https://rooms.irt.io/my-game/">
```

`connect()`, the room-wide requests, `dataClient()` and the UI kit take room
URLs relative to it, resolved as `new URL(input, projectUrl)` resolves
them: `"main"` is `https://rooms.irt.io/my-game/main`. An IRT site and
`irt dev` add the tag to every HTML page, `irt dev`'s pointing at the
local server, so the same code connects locally and when deployed. A
page hosted elsewhere writes it; see [Hosting your page](/docs/hosting/pages).
Without a tag, as in Node, pass absolute URLs or a `project` option. A
relative URL with no project URL to resolve it against is a
`TypeError`, as `new URL` throws without a base, and so is a URL whose
path doesn't end in a project and a room ID: `new RoomClient()` and
`dataClient()` throw it, and `connect()` and the room-wide requests
reject with it. `ws:` and `wss:` URLs name the same rooms as `http:` and
`https:`, and a room URL's query and fragment are dropped.

A room URL is for connecting: opened in a browser, it's an error page,
not the game. Share the game's own page instead, with `?room=` or
`?code=`, as [`<irt-invite>`](/docs/client/ui-kit#irt-invite) builds it.

## `connect()`

```ts
function connect<S, P, C>(input: string | URL, init?: ConnectInit<S, P, C>): Promise<ReadyRoomClient<S, P, C>>;
// A RoomClient whose state and private are typed as set, since it has been ready
type ReadyRoomClient<S, P, C> = RoomClient<S, P, C> & { readonly state: ClientEntity<S>; readonly private: OwnedEntity<P> };

interface ConnectInit<S, P, C> {
  project?: string | URL; // the project URL a relative room URL resolves against; default the page's irt-project meta tag
  type?: string;          // the room type whose schema this is; default the build's type named default
  token?: string;         // a player token from your backend; without one, the client joins as a guest
  guest?: "browser" | "tab";  // where a guest's token is kept; default "tab", a player per tab
  schema?: Schema<S, P, C>;  // the same defineSchema module the room uses
  timeout?: number;       // ms the first connection may take to become ready, waking included; default 15000
  signal?: AbortSignal;   // aborts connecting, rejecting with an AbortError, or a TimeoutError for AbortSignal.timeout; once ready, close() the client instead
  targets?: Record<string, Schema>;  // schemas of the room types a handoff may take the player to, by type
}
```

`connect()` takes a room URL and an init object, as `fetch()` takes a URL
and a `RequestInit`. It resolves once the client holds the room's full
state, so `room.state` and `room.private` are set. It rejects with an
`IrtError`: a `NetworkError`, with code 0, when the room can't be
reached (after trying WebTransport and WebSocket), one named for the
close code when the router closes with a code the client doesn't retry,
a `TimeoutError` when `timeout` passes first, and an `AbortError` when
`signal` aborts, with the signal's reason as its `cause`, as `fetch()`
keeps it. A signal from `AbortSignal.timeout(ms)` rejects with a
`TimeoutError` instead. It rejects with a `TypeError` for a room URL it
can't resolve. A first dial that fails is final, but a connection that
opens and then drops before the client is ready is retried, as after
it. After it resolves, the client reconnects by itself. `timeout` counts
waking, which a caller can't see, so it stays beside `signal`. Without a
global `WebSocket`, as in Node before 24, it throws a `NotSupportedError`.

`type` is the [room type](/docs/guides/concepts#rooms) the client expects.
A room of another type, or a type the live build doesn't have, closes
the connection with 4015, which reloading doesn't fix; its reason names
the room's type. A connection that creates its room creates it of this
type. Pass it for every room that isn't of the `default` type, such as
one `createRoom({ type })` made or a match a lobby handed off to, when
you connect to it by URL: `connect(handoff.url, { type: "match" })`.
A handoff's own client already has it.

```ts
// connect.ts
import { CloseCode, connect, defineSchema, entity, IrtError, reloadForNewBuild } from "@irtio/client";

const Table = entity("table", { players: "u8" });
const schema = defineSchema({ state: Table });

try {
  const room = await connect("https://rooms.irt.io/my-game/main", { schema, signal: AbortSignal.timeout(20_000) });
  console.log(room.player, room.state.players);
  room.addEventListener("close", ({ error }) => {
    if (error?.code === CloseCode.RoomHibernated) console.log("offer a rejoin button");
  });
} catch (e) {
  if (e instanceof IrtError && e.name === "VersionError") reloadForNewBuild();
  else throw e;
}
```

**Waking.** `connect()` resolves after the room is running, so to show
that a room is starting, listen for `waking` before then: construct the
client with `new RoomClient(input, init)`, which connects as `connect()`
does without waiting, add listeners and await its `ready`:

```ts
// waking.ts
import { RoomClient } from "@irtio/client";

const client = new RoomClient("https://rooms.irt.io/my-game/main");
client.addEventListener("waking", () => console.log("starting the room"));
const room = await client.ready;
console.log(room.readyState); // "open"
```

`ready` resolves to the same client typed as `connect()` resolves it, with
`state` and `private` set. On the `RoomClient` before that they're typed
as possibly undefined.

**Transports.** WebTransport at the room URL itself, with one
bidirectional stream for reliable messages and datagrams for unreliable
ones; if it isn't available or doesn't connect within 3 seconds, the
client uses WebSocket at the room URL with `wss:` for `https:`. Once
WebTransport has failed and WebSocket connected, as on a network that
blocks UDP, every later connect in the page goes straight to WebSocket,
handoffs and reloads of the tab included: the page remembers it in
`sessionStorage`. To replace the transport, as to count or delay
traffic, see [Dev tools](/docs/tools/dev-tools#custom-transports).

**Guests.** Without a `token`, the router mints a guest token with a
player ID of `guest:<random>`. The client keeps it in `sessionStorage`
under `irt.guest.<project>`, `<project>` being the project's slug (in
memory where there's no `sessionStorage` or it's blocked), and sends it
on every connect, so each tab is its own guest: it keeps its player ID
across reconnects and reloads of that tab, and a new tab is a new
player. The token lasts 30 days and the router renews it on each
connect. See [Games without a backend](/docs/guides/no-backend#guests).

With `guest: "browser"`, the client keeps the token in `localStorage`
under the same key instead, so every tab of the browser is one guest,
across browser restarts too. Two tabs connecting at once share one
guest rather than each getting its own: where the browser has Web
Locks, the first holds a lock until the router has minted the guest,
and the others wait for it. One player in two tabs of a room is still
one player, so the newer tab's connection closes the older's with 4012.
A handoff's client and `room.playerData` use the same guest as the
connection. `guest` is unused with a `token`.

```ts
// one-guest-per-browser.ts
import { connect } from "@irtio/client";

const room = await connect("main", { guest: "browser" });
console.log(room.player); // the same guest:<random> in every tab of this browser
```

## RoomClient

```ts
class RoomClient<S, P, C> extends EventTarget {
  constructor(input: string | URL, init?: ConnectInit<S, P, C>);  // connects; await `ready` instead of connect()
  readonly ready: Promise<ReadyRoomClient<S, P, C>>;
  readonly schema: Schema<S, P, C>;
  readonly entities: EntityStore;
  readonly presence: PresenceList;           // who's in the room; see Presence
  readonly state: ClientEntity<S> | undefined;     // undefined until ready
  readonly private: OwnedEntity<P> | undefined;    // undefined until ready; the player owns its private state
  readonly calls: CallsOf<Schema<S, P, C>>;  // a typed async function per declared call; see Calls
  readonly readyState: ReadyState;           // "connecting" | "waking" | "open" | "reconnecting" | "closed"
  readonly asleep: boolean;                  // the room sleeps and the router holds the connection
  readonly connection: number;
  readonly player: string;
  readonly url: string;                      // the room URL, absolute, http: or https:, with no query or fragment
  readonly id: string;                       // the room ID, the URL's last segment, decoded
  readonly project: string;                  // the project URL the room URL resolves against
  readonly type: string;                     // the room type from ConnectInit, "default" when left out
  readonly generation: number;               // the room's generation; changes when it restarts or wakes
  readonly tickRate: number;                 // the room's; 0 for a room without ticks
  readonly tick: number;                     // tick of the last state update applied; stays put while nothing changes; 0 without ticks
  readonly update: number;                   // update number of the last state update applied
  readonly rtt: number;                      // smallest recent round trip, in ms
  readonly jitter: number;                   // mean deviation of the recent round trips, in ms
  readonly transportKind: "webtransport" | "websocket" | undefined;  // what carries the connection
  readonly joinTime: { ms: number; started: boolean } | undefined;   // how long joining took and whether the room started on the way
  readonly protocol: number;                 // the client protocol the connection speaks, from welcome
  readonly peers: { speakers: readonly string[]; listeners: readonly string[] };  // see Voice
  readonly voice: { url: string; token: string } | undefined;                     // set when the project uses voice
  readonly stats: WireStats;                 // messages and bytes in and out; see Wire statistics
  serverTick(): number;                      // the room's current tick, estimated, with a fraction; throws in a room without ticks
  serverTime(): number | undefined;          // the room's wall clock, room.now(), estimated, in ms

  send(message: unknown, opts?: { unreliable?: boolean; to?: readonly string[] }): void;
  flush(): void;                            // sends unsent owner writes now; send, calls and close do it first
  close(): void;                            // closes with 1000: the player's presence ends at once, with no grace
  lead(player: string): Promise<void>;      // native rooms: pass the leader role
  readonly lobby: LobbyState | undefined;   // a lobby's phase, who is ready and the countdown; see Lobbies
  setLobbyReady(ready: boolean): Promise<void>;  // lobbies: mark this player ready or not
  startCountdown(): Promise<void>;          // lobbies: the leader starts the countdown, under any start rule
  cancelCountdown(): Promise<void>;         // lobbies: the leader cancels it
  addEventListener<K extends keyof RoomClientEventMap>(type: K, listener: (this: RoomClient<S, P, C>, event: RoomClientEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
  removeEventListener<K extends keyof RoomClientEventMap>(type: K, listener: (this: RoomClient<S, P, C>, event: RoomClientEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
  predict<I, K>(stepper: Stepper<I>, opts: { find(room: RoomClient<S, P, C>): ClientEntity<K> | undefined; sample?(prediction: Prediction<I, K>): I; idle?(input: I): boolean; warnOnDivergence?: boolean }): Prediction<I, K>;
  readonly predictions: ReadonlySet<Prediction<any, any>>;   // every prediction predict() made, stopped ones included
  interpolate<K extends Kind, F extends keyof ValuesOf<K> & string>(kind: K, fields: readonly F[]): Interpolator<K, F>;
  readonly playerData: PlayerData;           // this player's data; see Player data, collections and leaderboards
  collection(name: string): Collection;
  leaderboard(name: string): ClientLeaderboard;
}
```

Its connection details, from `readyState` to `voice`, are read-only;
the client sets them as the connection changes.

Some members need more detail:

- **`readyState`** is `"open"` from the router's `welcome`, a moment
  before the full state arrives and `ready` resolves. A connection that
  drops before the first ready goes back to `"connecting"`, not
  `"reconnecting"`. Until the first `welcome`, `connection`, `tickRate`,
  `protocol` and the rest are 0 and `player` is `""`; after each
  reconnect and wake they're the new connection's.
- **`send()`** sends an `ArrayBuffer`, a typed array such as a
  `Uint8Array` or a `DataView` as a binary message, and anything else as
  JSON. It doesn't check the size: a message over 64 KB closes the
  connection with 4005, and the client reconnects after backoff. It throws an `IrtError` named
  `InvalidStateError` if called before the client was first ready, as
  `WebSocket.send()` throws while connecting, and a `TypeError` for a
  value JSON can't carry, rather than send something else: a `Map`, a
  `Set` or another object with no fields of its own, which would arrive
  as `{}`, a function, `NaN` or an infinity, an object that refers to
  itself, or bytes inside an object. `undefined` fields are left out, as
  `JSON.stringify()` leaves them. Call args are checked the same way. It
  doesn't check the size: a message over 64 KB closes the connection
  with 4005, and the client reconnects after backoff. In
  a native room, `to`, 1 to 16 player IDs, sends it only to those of
  them who are connected; it throws a `RangeError` for an empty list or
  more than 16, and any other room closes the connection with 4006 for
  it.
- **`send()` while reconnecting.** Reliable messages sent while
  `readyState` is `"reconnecting"` or `"waking"` wait in the client, up
  to 64, and go in the order they were sent once the client is open
  again, before the `open` event; past 64 they're dropped. If the
  client closes instead, they're dropped, as is anything sent after
  `close()`. Unreliable messages are
  dropped while reconnecting, as they'd be stale. The room handles the
  waiting messages after the player rejoins, so its `onJoin()` runs
  first.
- **`lead()`** passes the leader role of a native room to another
  connected player, with the native room's call `lead`, and resolves once
  the room took it. It rejects with an `IrtError` when this player
  isn't the leader or the other player isn't connected. See [Presence](#presence).
- **`close()`** closes the connection on purpose, with close code 1000;
  the room takes it as the player leaving, so their presence ends at
  once. The client doesn't reconnect, sets `readyState` to `"closed"`
  and fires `close` with `wasClean` true. Calls in flight reject with a
  `NetworkError`, and calling `close()` again does nothing. Called before
  the client is ready, it makes `ready` reject with an `AbortError`.
- **`state` and `private`** are undefined until `ready` resolves, and
  set from then on, through reconnects. `connect()` and `ready` resolve to
  a `ReadyRoomClient`, the same object typed with both set.
- **Listeners** are removed with `removeEventListener()`, or all at once
  by passing `{ signal }` and aborting it:
  `room.addEventListener("message", fn, { signal: controller.signal })`.
  `room.presence`, voice, replays and predictions are `EventTarget`s
  too. Entity callbacks, such as `room.entities.onEnter(kind, fn, {
  signal })`, take the same option, and also return a function that
  removes them; they stay callbacks, so each is typed by its kind.
- **`tickRate` and `tick`** are 0 in a room without ticks, and
  `serverTick()`, `predict()` and `interpolate()` throw an `IrtError`
  named `InvalidStateError` there, since they
  count time in the room's ticks; `serverTime()` is that room's clock.
  Before the first `welcome` the client can't tell, so they don't throw
  yet, and `serverTick()` returns 0. `predict()` also throws an `Error`
  while another prediction on the client hasn't been stopped.
- **`serverTick()` and `rtt`** come from pings. The client pings three
  times 100 ms apart after each `welcome`, then every 2 seconds. The
  room answers with its current tick, and the client takes the answer
  to be from the middle of that tick and half a round trip old.
  `serverTick()` and `rtt` use the sample with the smallest round trip
  of the last 8. Across a reconnect to the same generation the client
  keeps its estimate until a new pong arrives; after a restart or a
  wake it uses the first state update's tick until then.
- **`jitter`** is the mean deviation of the last 8 round trips from
  their mean. Each `welcome` starts the samples over: `jitter` goes back
  to 0, and `rtt` keeps its value until the next pong. **`transportKind`** comes from the dial; a custom `dial`
  can leave its `kind` out, and then it's undefined.
- **`joinTime`** is set when `ready` resolves: the milliseconds from
  `new RoomClient` to the first full state update, leaving out any
  `createRoom()` or `quickJoin()` before it, and `started`, whether the
  router sent `waking` on the way, which it does for a room that starts
  as well as one that wakes. After a reconnect it's the time from the
  drop to the resync. The [join loader](/docs/client/ui-kit#irt-join-loader)
  shows it.
- **How accurate `serverTick()` is.** The room only reports whole ticks,
  so on a symmetric link expect it to be off by up to half a tick: about
  25 ms at 20 Hz. Two clients in the same room can differ by up to a
  tick. It's good enough for what the SDK uses it for, sending inputs
  for the right tick and the render time of `interpolate()`, and for
  timing game events in ticks. It isn't a wall clock: a stalled room
  skips the ticks it couldn't run and ticks don't count time the room
  was hibernated or restarting.
- **`serverTime()`** is the room's wall clock, `room.now()`, in
  milliseconds, for timing in real time, such as music or judging a key
  press. Each pong carries the room's clock when it answered; the
  client takes the pong with the smallest round trip of the last 8,
  adds half its round trip and carries it on with its own clock. On a
  symmetric link it's off by about a millisecond. It's undefined before
  the first pong. It follows the test clock in `@irtio/testing`, as `room.now()` does.
  The client also reports its `rtt` in each ping, which the room shows
  as `conn.rtt`.
- **Asymmetric links.** Any clock estimated from round trips,
  `serverTick()`, `serverTime()` and one you build yourself, assumes half the round
  trip each way. When a link is slower one way, the clock is off by
  half the difference, and nothing in the round trip shows it: with
  150 ms up and 0 ms down, the client's clock is 75 ms behind the
  room's. To correct for it, and for audio output latency, let each
  player calibrate an offset, such as by tapping along to a beat.

**Messages before a listener.** A room's messages can reach the client
before `connect()` resolves, such as those it sends in `onJoin()`. The
client holds reliable messages that arrive before the first `message`
listener is added, up to 100, and gives them to the listeners once the
code that added the first one has run, so listeners added together all
get them. So `await connect(...)` then
`room.addEventListener("message", ...)` gets every message the room
sent on join. Messages keep the order the room
sent them in, held ones first; a held message is delivered after the
state updates that arrived with it are applied. Unreliable messages are
not held: before the first listener, they are dropped. After the first
`message` listener has been added, nothing is held, so a listener added
later gets only messages from then on.

`RoomClient` is an `EventTarget`, and its events are typed by
`RoomClientEventMap`, as `WebSocket`'s are in the DOM's types, so a
listener gets its event's type with no cast:

| Event | Type | When |
|---|---|---|
| `waking` | `Event` | The room isn't running and the connection is held while it starts. That's a wake of a hibernated room, but also the first start of a room this connection creates, and a restart after a crash: the router says it before it has looked up whether the room has room state. Show something neutral, such as "starting the room". It fires before `connect()` resolves; see [`connect()`](#connect) |
| `open` | `RoomOpenEvent` | The client holds the room's full state after having no connection: once before `connect()` resolves, with `reconnected` false, and after every reconnect, resumed or sent whole, with `reconnected` true. A listener added after `await connect(...)` so sees only reconnects |
| `reconnecting` | `RoomCloseEvent` | The connection dropped and the client is reconnecting; `code` and `reason` are what it dropped with. It fires once per drop, and also for a connection that drops before the first `open`, while `readyState` is `"connecting"` |
| `close` | `RoomCloseEvent` | The connection ended for good, or the first connection failed, with code 0 and a `NetworkError`, `TimeoutError` or `AbortError`. `error` is the `IrtError`, with the close code as its `code`, unless the client closed itself with `close()`, when `wasClean` is true; any other close, a kick included, has `wasClean` false |
| `message` | `RoomMessageEvent` | A message from the room arrived. A JSON message that doesn't parse is dropped |
| `update` | `CustomEvent<{ update: number; tick?: number }>` | A whole state update was applied, with its update number and, in a room with ticks, its tick. It fires after the update's entity and presence callbacks, and after `open` or `wake`. The room sends one only when something this client sees changed, so a room where nothing changes fires none; for the room's current tick, use `room.serverTick()` |
| `sleep` | `Event` | The room went to sleep and the router holds the connection; `room.asleep` is true. The connection stays open: messages, calls and writes sent meanwhile wake the room and reach it after, and unreliable messages and inputs are dropped. The client pings every 15 seconds instead of every 2 until the room wakes, and the router's answers don't change `rtt` or `serverTick()` |
| `wake` | `Event` | The room woke from sleep and the client holds its full state again. Calls made while it slept are answered, not failed; prediction starts over. It isn't an `open`, since the connection never dropped |
| `peers` | `CustomEvent<VoicePeers>` | `room.peers` changed: who this player hears or is heard by |
| `voice` | `CustomEvent<{ url: string; token: string }>` | The router granted voice for this connection; `room.voice` is set |
| `lobby` | `CustomEvent<LobbyState>` | A lobby's state changed; `room.lobby` is set |
| `handoff` | `CustomEvent<Handoff>` | A handoff connected the player to another room, or failed to; see [Lobbies](#lobbies) |

```ts
class RoomOpenEvent extends Event {
  readonly reconnected: boolean;    // false for the first open, true after each reconnect
}
class RoomMessageEvent extends Event {  // shaped like the web's MessageEvent
  readonly data: unknown;           // the message: JSON parsed, or a Uint8Array for bytes
  readonly unreliable: boolean;
  readonly from: string | undefined;  // the sender's player ID in a native room, "" from the server API, undefined from room code
}
class RoomCloseEvent extends Event {    // shaped like the web's CloseEvent
  readonly code: number;
  readonly reason: string;
  readonly wasClean: boolean;       // true when this client closed with close()
  readonly error?: IrtError;        // on close, what ended the connection, unless the client closed it
}
```

`from` is the sender's player ID in a native room, where messages come
from other players, and `""` for one sent through the server API. It's
undefined in a room with room code, whose messages come from the room.
Held messages keep it. The three event classes are IRT's own, with the
web's fields, rather than subclasses of `MessageEvent` and `CloseEvent`,
which not every runtime has.

```ts
// events.ts
import type { ReadyRoomClient } from "@irtio/client";

export function watch(room: ReadyRoomClient, log: (line: string) => void): () => void {
  const listening = new AbortController();
  const { signal } = listening;
  room.addEventListener("message", (e) => log(`${e.from ?? "room"}: ${JSON.stringify(e.data)}`), { signal });
  room.addEventListener("reconnecting", (e) => log(`dropped with ${e.code}, reconnecting`), { signal });
  room.addEventListener("open", (e) => e.reconnected && log("back"), { signal });
  room.addEventListener("update", (e) => log(`update ${e.detail.update}`), { signal });
  room.addEventListener("close", (e) => log(e.wasClean ? "left" : `closed: ${e.error?.message}`), { signal });
  return () => listening.abort();
}
```

### Lobbies

```ts
interface LobbyState {
  phase: "waiting" | "countdown" | "handing-off";
  ready: string[];          // ready people in join order, then every bot
  startsAt: number | null;  // when the countdown ends, in the room's wall-clock ms; compare with serverTime()
  min: number;              // the lobby's minPlayers and maxPlayers
  max: number;
  failed: "players" | "limit" | "spending" | "unavailable" | null;  // why the last handoff failed, until the next countdown
}

type Handoff =
  | { room: string; url: string; type: string; client: RoomClient<any, any, any> & { readonly state: any; readonly private: any };  // connected to the new room, holding its state
      as<S, P, C>(schema: Schema<S, P, C>): ReadyRoomClient<S, P, C> }
  | { room: string; url: string; type: string; error: IrtError;     // couldn't connect; this client stays where it was
      as(schema: Schema): never }                     // throws error
```

The `handoff` event's `detail` is a `Handoff`: the new room's ID, URL
and type, and its client. `client`'s kinds are `any`, since the room
type is known only at runtime. `h.as(schema)` returns the same client typed for `schema`, the
one `targets` names for `h.type`, so its state and calls are checked:
`const game = h.as(matchSchema)`. It throws an `Error`, not an
`IrtError`, when the room's schema hash isn't `schema`'s, and on a
failed handoff it throws `h.error`.

The lobby members and handoffs work like this:

- **`lobby`** is set from the lobby's state message, which a lobby sends
  after the first state update and whenever it changes, so it can still
  be undefined just after `connect()` resolves. It's undefined in every
  room that isn't a lobby.
- **`setLobbyReady()`, `startCountdown()` and `cancelCountdown()`** are
  the lobby's calls `ready`, `start` and `cancel`, and work from the
  moment the client is ready. They reject with an `IrtError` with the
  lobby's reason: `startCountdown()` and `cancelCountdown()` from anyone
  but the leader, `startCountdown()` outside waiting or with fewer than
  `minPlayers` people and bots, `cancelCountdown()` outside the
  countdown, and `setLobbyReady()` while the lobby hands off. In a room
  that isn't a lobby they reject as calls the room doesn't answer.
- **Handoffs.** When the router moves the player, the client connects
  to the new room with `targets[type]` as its schema, the empty schema
  for a type it doesn't name, and the same token or guest. Once the new
  client holds the room's state, this one closes, unless the
  handoff keeps it, as a party's does, then fires `handoff` with the new
  client, so its `close`, with `wasClean` true, comes first. Before
  closing, it waits up to 3 seconds for the replies to its
  calls in flight there. If the new client fails for good, `handoff`
  carries its error and this client stays connected. See
  [Lobbies and parties](/docs/room/guides/lobbies).

### Wire statistics

```ts
interface WireStats {
  messagesIn: number;
  bytesIn: number;
  messagesOut: number;
  bytesOut: number;
  readonly received: Record<string, { messages: number; bytes: number }>;  // by server message type
  readonly sent: Record<string, { messages: number; bytes: number }>;      // by client message type
  lastUpdate: { update: number; tick: number; parts: number; bytes: number; full: boolean } | undefined;
}
```

`room.stats` counts the client's traffic since it was created, across
reconnects. Sizes are of protocol messages as encoded, without the
transport's own framing, such as a WebSocket frame header. `received`
is keyed by type: `state` (state updates), `ack` (input acks), `pong`,
`message`, `unreliable`, `reply` and the rest; `sent` by `input` (or
`typedInput` with a schema's [input kind](/docs/client/guides/prediction#compact-inputs)),
`ping`, `write`, `message`, `unreliable`, `call`, `hello` and `resume`. So
`stats.received.state.bytes` is what state sync cost and
`stats.sent.input.bytes` what prediction inputs cost. `lastUpdate` is
the last whole state update applied: its update number and tick, the
messages it was split into, their size together on the wire, compressed
or not, and whether it was a full update, as on joining or on a
reconnect that couldn't resume. A flush that sent the client nothing
leaves it as it was. Sample the counters once a second to get rates:

```ts
// wire-rates.ts
import type { RoomClient } from "@irtio/client";

export function logRates(room: RoomClient): void {
  let last = { in: room.stats.bytesIn, out: room.stats.bytesOut };
  setInterval(() => {
    const now = { in: room.stats.bytesIn, out: room.stats.bytesOut };
    console.log(`in ${now.in - last.in} B/s, out ${now.out - last.out} B/s, last update ${room.stats.lastUpdate?.bytes ?? 0} B`);
    last = now;
  }, 1000);
}
```

### Calls

`room.calls` holds a typed async function for each call the schema
passed to `connect()` declares, with `defineCalls()` and `call(fields)`; see
[Calls](/docs/room/guides/calls). `room.calls.name(args, opts)`
runs the room's `calls.name` handler and resolves to what it returns,
JSON or bytes:

```ts
type CallsOf<typeof schema> = {
  buy(args: { item: string }, opts?: { timeout?: number; signal?: AbortSignal }): Promise<{ coins: number }>;
  balance(args?: undefined, opts?: { timeout?: number; signal?: AbortSignal }): Promise<number>;   // a call declared with no args
};
```

It rejects with an `IrtError`:

- **`OperationError`**, code 422, when the handler throws, with the
  handler's message as its `reason`; when the room rejects the args,
  because they don't match the call's fields or its `parse()` threw; when
  args don't match the fields of a call declared with `call(fields)`,
  which the client checks before sending, with nothing sent; and when
  the room has no such call.
- **`TimeoutError`** after `timeout` milliseconds, 10,000 by default.
- **`AbortError`** when `signal` aborts, with the signal's reason as its
  `cause`, or a **`TimeoutError`** for a signal from
  `AbortSignal.timeout()`. The room may still run it.
- **`NetworkError`** when the connection drops or the room restarts
  first, or when called while the client reconnects.
- **`InvalidStateError`** after the client closed. Called before the
  client was first ready, `room.calls.name()` throws it at once rather
  than rejecting, as `send()` does; `lead()`, `setLobbyReady()`,
  `startCountdown()` and `cancelCountdown()` reject with it.

A call made while the room sleeps waits for it to wake and is answered
then. A call that fails with no answer from the room may or may not have
run, and the SDK never retries it, so make calls that change state safe
to repeat, or check with another call. `CallsOf<typeof schema>` names
the type of `room.calls`, for passing it around.

### Reloading for a new build

`reloadForNewBuild()` reloads the page after a 4004 so the browser loads
the live build's site, and returns `true`. It reloads at most once until
a connection succeeds, and returns `false` instead of reloading again: a
room still running an older build refuses the new site's clients with
4004 until it hibernates, so reloading on every 4004 would loop. It also
returns `false` outside a browser or when storage is blocked.

## Close codes

| Code | Meaning | Client |
|---|---|---|
| 4000 | Protocol version not supported | Fails; update `@irtio/client` |
| 4001 | Token invalid or expired | Fails |
| 4002 | Room not found | Fails |
| 4003 | Room full | Fails |
| 4004 | The client's schema differs from the room build's | Fails; the message gives both hashes. Rebuild and redeploy the client and room together |
| 4005 | Rate or size limit exceeded | Reconnects after backoff |
| 4006 | Kicked by the room, or its `onJoin()` threw | Fails |
| 4007 | Room stopped | Fails |
| 4008 | Room moved or restarted | Reconnects at once |
| 4009 | Project over its spending limit | Fails |
| 4010 | Wake timed out | Reconnects after backoff |
| 4011 | The room hibernated by its own request | Fails; connect again to rejoin, which wakes it |
| 4012 | The same player connected to the room again elsewhere | Fails; the player is playing in another tab or device |
| 4013 | The player is [banned](/docs/hosting/moderation) from the project | Fails |
| 4014 | The room banned the player | Fails |
| 4015 | The room isn't of the client's `type`, or the live build has no such type | Fails; don't reload for it, since the new site has the same mistake |

Any other close reconnects with backoff: 250 ms doubling up to 10 s,
with jitter, and so does a reconnect that can't be dialled. A first
connection that can't be dialled at all fails at once with a
`NetworkError`. Since 4005 and 4010 always reconnect, no `IrtError`
carries them. [Errors and close
codes](/docs/client/errors) has each code's causes and the messages
`connect()` and calls reject with.

## Entities on the client

```ts
type ClientEntity<K> = Readonly<ValuesOf<K> & { id: number; kind: K }> & {
  toJSON(): ValuesOf<K> & { id: number; kind: string };   // a plain copy; kind is the kind's name
};
// An entity the local player owns: its writable fields can be set
type OwnedEntity<K> = ClientEntity<K> & { -readonly [N in WritableOf<K>]: ValuesOf<K>[N] };

class EntityStore {
  get(id: number): ClientEntity | undefined;
  get<K extends Kind>(kind: K, key: string): ClientEntity<K> | undefined;   // for a kind with a key
  all<K extends Kind>(kind: K): IterableIterator<Entity<K> & { toJSON(): ValuesOf<K> & { id: number; kind: string } }>;
  mine<K extends Kind>(kind: K): IterableIterator<OwnedEntity<K>>;
  ownerOf(e: ClientEntity): string | undefined;   // a player ID, or undefined for the room
  readonly count: number;
  onEnter<K extends Kind>(kind: K, fn: (e: ClientEntity<K>) => void, opts?: { signal?: AbortSignal }): () => void;
  onChange<K extends Kind>(kind: K, fn: (e: ClientEntity<K>, changed: (keyof ValuesOf<K>)[]) => void, opts?: { signal?: AbortSignal }): () => void;
  onCorrect<K extends Kind>(kind: K, fn: (e: OwnedEntity<K>, corrected: WritableOf<K>[]) => void, opts?: { signal?: AbortSignal }): () => void;
  onOwner<K extends Kind>(kind: K, fn: (e: ClientEntity<K>) => void, opts?: { signal?: AbortSignal }): () => void;
  onLeave<K extends Kind>(kind: K, fn: (e: ClientEntity<K>) => void, opts?: { signal?: AbortSignal }): () => void;
}
```

The store works like this:

- Entities are read-only, except the writable fields of entities the
  local player owns, including its private state; any other write throws
  a `TypeError`. A value of the wrong type throws a `TypeError` too, one
  out of its field's range a `RangeError`, and a write to an entity that
  has left the client's view an `Error`. See [Ownership](/docs/room/guides/ownership).
- The callbacks throw an `Error` for a kind the schema doesn't declare.
  An entity that enters already owned doesn't fire `onOwner()`. When the
  local player loses an entity, its unsent writes to it are dropped. The
  local player's own writes, `setStatus()` included, don't fire
  `onChange()`.
- Owner writes are sent at most once per room tick in a room with
  ticks, since the room applies them at the tick. In a room without
  ticks they go at the end of the task that made them, and a burst,
  such as a drag that writes on every pointer move, at most once per
  16 ms, the room applying each as it arrives. Either
  way they're also sent before each
  `send()` and call and before `close()`, so room code applies them
  before it handles the message, the call or the close. An unreliable
  message can overtake the writes sent before it on a real connection.
  `flush()` sends them at once. The room's
  corrections overwrite them, and `onCorrect()` runs after `onChange()` for
  the corrected fields.
- A state update is applied whole, then the callbacks run in order:
  leaves, enters and changes as they happened, then `update`.
- To copy an entity, call `toJSON()`: `{ id, kind, ...fields }` with
  `kind` as the kind's name, which `JSON.stringify()` also uses. Its fields
  are accessors on a shared prototype, so `{ ...entity }` copies only
  `id` and `kind`. The copy holds the values at that moment,
  and the entity object itself keeps changing with each state update.
- The shared state is entity 0 and the private state entity 1, of the
  schema's state and private kinds; `onChange(schema.state, ...)` works.
- `count` is every entity the client holds: the shared state, its
  private state, a presence entry for each player in the room, and the
  room's entities in its view. A seated player in a room of four, with
  one entity of its own in view, has a `count` of 7. Count one kind
  with `all(kind)`. The room's `entities.count` counts only the room's
  entities.
- Entities of a [hidden kind](/docs/room/guides/state-sync#hidden-entities)
  never arrive, so `all(kind)` of one is always empty.
- `get(kind, key)` finds an entity of a kind declared with a `key` by
  that field's value, while it's in the client's view; it's a map
  lookup, and it throws for a kind without a key. In a native room,
  which doesn't keep keys unique, two entities in view can share one:
  `get()` finds the one that entered last, and none once it leaves. See
  [Entity IDs and lookups](/docs/room/guides/state-sync#entity-ids-and-lookups).
- On a change of generation, or a reconnect the room can't resume, every
  entity leaves and the full state enters again as new objects. On a
  reconnect the room resumes, entities that didn't change keep their
  objects, and those that changed while the client was away, and every
  entity the player owns, leave and enter again as new ones. So owner
  writes not yet sent when the connection dropped are dropped, and the
  room's values come back.

## Presence

```ts
interface PresenceEntry {
  readonly player: string;
  readonly name: string;        // set by the room
  readonly status: unknown;     // JSON, at most 1 KB; null until set
  readonly connected: boolean;  // false for 10 s after the player's last connection closed
}

class PresenceList extends EventTarget {
  get(player: string): PresenceEntry | undefined;
  readonly me: PresenceEntry | undefined;   // the local player's entry
  readonly size: number;
  [Symbol.iterator](): IterableIterator<PresenceEntry>;
  setStatus(status: unknown): void;
  readonly leader: string | undefined;      // native rooms: the player who leads, or undefined for none
}

class PresenceEvent extends Event {          // join, change and leave
  readonly entry: PresenceEntry;
  readonly changed: readonly ("name" | "status" | "connected")[];   // on change, the fields that changed; empty otherwise
}
```

| Event | Type | When |
|---|---|---|
| `join` | `PresenceEvent` | A player joined the room |
| `change` | `PresenceEvent` | A player's name, status or connection changed; `changed` names the fields |
| `leave` | `PresenceEvent` | A player left the room |
| `leader` | `Event` | A native room's leader changed; read `presence.leader` |

```ts
// presence.ts
import type { ReadyRoomClient } from "@irtio/client";

export function listPlayers(room: ReadyRoomClient, show: (names: string[]) => void, signal: AbortSignal): void {
  const update = () => show([...room.presence].map((p) => (p.player === room.presence.leader ? `${p.name} (leads)` : p.name)));
  for (const type of ["join", "change", "leave", "leader"] as const) room.presence.addEventListener(type, update, { signal });
  room.presence.addEventListener("join", (e) => console.log(`${e.entry.name || e.entry.player} joined`), { signal });
  update();
}
```

The presence list works like this:

- `room.presence` lists every player in the room, whatever the room's
  interest, and is set once `ready` resolves. Its events fire after
  the entity callbacks of the same state update, before `update`.
- A resync doesn't fire `leave` and `join` for players who stayed;
  `change` fires for whatever changed while the client was away.
- `setStatus()` is an owner write: it changes `me.status` at once, without
  `change`. It throws a `TypeError` for a status that isn't
  JSON-serializable, a `RangeError` over 1 KB, and an `IrtError` named
  `InvalidStateError` before the client holds its own presence. A
  correction from the room fires `change`. See [Presence](/docs/room/guides/presence).
- **The leader.** A native room has a leader, set after the client's
  first state update and whenever it changes, when `leader` fires. The
  leader keeps the role while their presence lasts, so through a
  disconnect of up to 10 seconds, or until they pass it with
  `room.lead(player)`; then the earliest connected player leads, and
  the role doesn't go back to the old leader. A room with room code has
  no leader, and `leader` stays undefined.
- **In a native room** each player's status is at most 64 bytes of JSON;
  a longer one closes the connection with 4006, as does a
  `to` list of more than 16 players or a malformed message.

## Interpolation

```ts
class Interpolator<K, F extends string> {
  get(entity: ClientEntity<K>): Pick<ValuesOf<K>, F>;   // numbers, and a Quat for each quat field
}
interface Quat { readonly x: number; readonly y: number; readonly z: number; readonly w: number }
```

`room.interpolate(kind, fields)` records the listed numeric fields of
every entity of the kind as state updates arrive. `get(entity)` returns
them at the client's render time: the room's estimated tick minus two
ticks or 100 ms, whichever is longer, linearly between the two states
around it. Call it each frame. Use it for remote entities, and
[Client prediction](/docs/client/guides/prediction) for the local player. An `angle`
field goes the short way round where it wraps, and a `quat` field by
normalized lerp on the same side as the earlier state, so a rotation
whose sign flips between states doesn't spin. `fields` lists numeric,
`angle` and `quat` fields; any other is a type error, and
`interpolate()` throws a `TypeError` for it. For an entity it hasn't
recorded a state of yet, `get()` returns the entity's own values.

## Prediction

```ts
class Prediction<I, K> extends EventTarget {   // K is the kind `find` returns
  readonly entity: Entity<K> | undefined;   // has toJSON(), as client entities do
  render<F extends keyof ValuesOf<K>>(fields: readonly F[], opts?: { snapDistance?: number }): Pick<ValuesOf<K>, F>;   // numeric, angle and quat fields
  snap(): void;                   // drops the mispredictions render is smoothing
  readonly tick: number;          // room tick of the last input, which entity is stepped through; 0 before the first
  readonly pending: number;       // ticks ahead of the room's state: about 2 plus half the round trip while sampling, up to 64 in a quiet room
  readonly settled: boolean;      // entity agrees with the room's last state
  mispredictions: number;         // replays that found a field the stepper writes different
  onEvent<E extends Kind>(event: E, handlers: {   // an event kind of the schema's, emitted for the local player
    predict?(values: ValuesOf<E>, tick: number): void;            // the live step emitted it
    confirm?(predicted: ValuesOf<E>, room: ValuesOf<E>, tick: number): void;  // the room emitted it too
    reject?(values: ValuesOf<E>, tick: number): void;             // the room didn't, within the window
    unpredicted?(room: ValuesOf<E>, tick: number): void;          // the room did and the prediction didn't
    window?: number;              // ticks either side of the predicted tick that still confirm; default 2
  }): () => void;
  readonly drift: Drift;          // a summary of recent mispredictions
  reckon<RK extends Kind, F extends keyof ValuesOf<RK> & string>(kind: RK, fields: readonly F[]): Reckoner<RK, F>;
  push(input: I): void;
  stop(): void;
}

interface Drift {
  rate: number;                   // share of replays that mispredicted, about the last second, 0 to 1
  average: number;                // misprediction size, matched replays counting 0
  peak: number;                   // largest recent misprediction, falling to a tenth in a second
  last: number;                   // size of the last misprediction
  fields: readonly string[];      // fields of the last misprediction
  verdict: "matched" | "jitter" | "diverging";
}

class Reckoner<K, F extends string> {
  get(entity: ClientEntity<K>): Pick<ValuesOf<K>, F>;   // numbers, and a Quat for each quat field
}
```

A prediction fires `mispredict`, a `CustomEvent` whose `detail` is `{
tick, fields, delta }`, after each replay that found a field the stepper
writes different. `predict()` throws an `IrtError` named
`InvalidStateError` before the client is ready, and while another
prediction of the client runs.

`sample(prediction)` runs once per room tick, first at the next tick
after `predict()` returns, and receives the `Prediction`. Its `entity` is
set before each call whenever `find` finds the entity, so it's
undefined only while `find` finds nothing: before the entity is in the
client's view, while the room has deleted it and after a reconnect
until the full state arrives.

`push(input)` sends an input for the next room tick and steps the
prediction with it, and does nothing unless `readyState` is `"open"` and
the prediction is running. It throws a `TypeError` or a `RangeError` for
an input that doesn't fit the schema's input kind. `stop()` stops
sampling, makes `push()` do nothing and calls the stepper's `release()`.
A `sample` that throws stops the prediction.

`render(fields, { snapDistance })` drops the correction of those fields
instead of smoothing it when it's longer than `snapDistance`, measured
as a Euclidean distance over the numeric fields, as after a teleport,
and drops the listed `quat` fields' with them; `snap()` drops every
correction at once. An `angle` correction turns the short way round,
and a `quat` correction is a rotation smoothed back toward none. See
Client prediction for how inputs, acks and replay work, and the
[Drift](/docs/client/guides/prediction#drift) section of it for `drift` and
`warnOnDivergence`.

`prediction.reckon(kind, fields)` draws remote entities of a kind as
the stepper moves them on the prediction world. `get(entity)` returns
the listed fields as they are after the prediction's last step, at
`tick`, carried on at that step's velocity for the part of a tick
since, plus a share of any jump a replay made, which shrinks by 20% a
tick. A field no step wrote, and every field before the prediction
steps, is the entity's own. It takes the fields `interpolate()` takes and
throws for any other. See the
[Reckoning remote entities](/docs/client/guides/prediction#reckoning-remote-entities)
section of Client prediction.

## Room-wide requests for games without a backend

```ts
interface RoomsInit {
  project?: string | URL;  // the project URL; default the page's irt-project meta tag
  token?: string;          // a player token; guests leave it out
  signal?: AbortSignal;    // aborts the request, rejecting with an AbortError
}

function createRoom(init?: RoomsInit & { id?: string; type?: string; public?: boolean; joinCode?: boolean; meta?: unknown; maxPlayers?: number }): Promise<{ id: string; url: string; joinCode: string | null }>;
function joinByCode(code: string, init?: RoomsInit): Promise<string>;   // the room's URL
function listPublic(init?: RoomsInit & { type?: string }): Promise<{ id: string; url: string; type: string; players: number; maxPlayers: number; meta: unknown }[]>;
function quickJoin(init?: RoomsInit & { type?: string; meta?: Record<string, unknown>; maxPlayers?: number }): Promise<{ id: string; url: string; joinCode: string | null }>;
```

Each takes an init object, as `fetch()` does, and returns room URLs to
pass to `connect()`. A page with an `irt-project` tag passes no `project`;
without one, they reject with a `TypeError`.

Each is allowed or not by a project setting (`players.createRooms`,
`players.listPublic`, `players.quickJoin`). They reject with an `IrtError` whose `code` is the HTTP
status, such as 404 for an unknown join code, a `NotFoundError`; see
[Errors](/docs/client/errors#room-wide-requests). Join codes are 6
characters of `A-H`, `J-N`, `P-Z` and `2-9`. `joinByCode()` is case-insensitive
and ignores spaces around the code, so `"k7qx2m "` finds `K7QX2M`.

`maxPlayers` caps a room's connections below its room size's connection
limit (64 for `standard`), from 1 to that limit; a connection past it
closes with 4003, and a value out of range rejects with 400. With
`players.createRooms` on, connecting to a room that doesn't exist also
creates it, as a private room with no join code.

`type` is the [room type](/docs/guides/concepts#rooms): `createRoom()`
creates a room of it, `quickJoin()` picks or creates one, and `listPublic()`
lists only rooms of it. Without one, `createRoom()` and `quickJoin()` use the
type named `default` and reject with 400 naming the build's types when
it has none, and `listPublic()` lists every type, each room with its
`type`. A type's own `maxPlayers` and size apply to its new rooms.
`listPublic()` lists only active rooms, never hibernated ones.

`quickJoin()` returns a public room to connect to, for games that fill rooms
with whoever comes. It picks the active public room with the most players
that's under its connection limit and its own `maxPlayers`, among those
whose `meta` has every top-level key of `opts.meta` with an equal value.
Without one it picks such a hibernated room, and without that it creates
a public room with `opts.meta` as its `meta` and `opts.maxPlayers` as its
`maxPlayers`. It holds the room's slot for 10 seconds or until the client
connects, so players who quick join at once don't overfill a room or create
one each. `joinCode` is the room's join code, or `null`. A room whose code
called `room.setPublic(false)`, such as a game whose seats are taken, is
neither picked nor listed, active or hibernated, until it sets it back. The
setting is off by default; matchmaking by skill, parties or queues belongs in
your backend.

```ts
// rooms.ts
import { connect, createRoom, joinByCode, listPublic, quickJoin } from "@irtio/client";

export async function host() {
  const { url, joinCode } = await createRoom({ public: true, joinCode: true, meta: { mode: "duel" } });
  console.log("share", joinCode);
  return connect(url);
}

export async function join(code: string) {
  return connect(await joinByCode(code));
}

export async function browse() {
  for (const r of await listPublic()) console.log(r.id, r.players, r.meta);
}

export async function play(mode: string, signal?: AbortSignal) {
  const { url } = await quickJoin({ meta: { mode }, signal });
  return connect(url, { signal });
}
```

## Player data, collections and leaderboards

```ts
function dataClient(init?: { project?: string | URL; token?: string; guest?: "browser" | "tab"; signal?: AbortSignal }): DataClient;   // project: default the page's irt-project meta tag; signal aborts every request

class DataClient {
  readonly playerData: PlayerData;             // get, set, increment, delete, list, as in the room SDK, for this player
  collection(name: string): Collection;        // get, put, list, delete
  leaderboard(name: string): ClientLeaderboard;
  player(): Promise<string>;                   // the player ID calls are made as; mints a guest without a token
}

class ClientLeaderboard {
  readonly name: string;
  submit(score: number, opts?: { meta?: Record<string, string | number | boolean>; signal?: AbortSignal }): Promise<{ period: string; score: number }[]>;
  top(opts?: { period?: string; limit?: number; after?: string | null; signal?: AbortSignal }): Promise<{ entries: RankedEntry[]; next: string | null }>;
  around(opts?: { player?: string; period?: string; count?: number; signal?: AbortSignal }): Promise<{ rank: number; entries: RankedEntry[] } | undefined>;  // this player by default
}
```

Every call takes a `signal` in its last argument, such as
`data.playerData.get("save", { signal })` or `collection.put(entry, {
signal })`, beside the client's own `signal`, which aborts all of them.

The same calls as in the [Room API on one page](/docs/room/one-page#player-data-collections-and-leaderboards),
for the player the client is, over the router's `POST /v1/data/{project}`,
with no room connection needed. `RoomClient` has them too, as
`room.playerData`, `room.collection(name)` and `room.leaderboard(name)`,
made with the connection's token or guest, and they work before the
client is ready. `dataClient()` throws a `TypeError` when there's no
project URL. Getting a collection or a board makes no request. The
calls work like this:

- **Guests.** Without a `token`, the first call takes the guest token
  `connect()` keeps in `sessionStorage`, or gets one from `POST /v1/guest`
  and keeps it there, so a guest is one player in rooms and data calls.
  An expired guest token gets a new guest, as connecting does. With
  `guest: "browser"`, it's the browser's guest in `localStorage`, as
  `connect()` with `guest: "browser"` keeps it. With storage blocked, the token lives as long as the page. A board's `top()`,
  and `around()` with a `player`, go without a token until there is one:
  with the project's `players.readLeaderboardsWithoutToken` on they need
  no guest, and otherwise the router's `401` gets one first.
- **Rights.** A client reads its own player data and writes only the
  keys in `data.player.clientWrite`; reads entries and boards with
  `clientRead: true`, or only its own entries with `clientRead: "own"`,
  where a `get()` of another player's entry resolves with `undefined` and
  a `list()` with another `owner` is `E_FORBIDDEN`; and with `clientWrite: "own"` creates entries, changes
  and deletes its own, up to the collection's `maxOwn`, past which a
  create is `E_QUOTA`, and submits its own score. `owner` is always the
  client's player. A client's writes can't use `once`, which is
  `E_INVALID`. A score a client submits can be faked.
- **Nothing is cached** on the client; every call goes to the router, and
  `refresh()` has nothing to drop.
- **Errors.** Calls reject with `DataError` (also exported here) and a
  contract code: `E_UNAVAILABLE` when the router or data service can't be
  reached or answers 503, or a `signal` aborts, `E_LIMIT` over the router's 10 calls a second
  per address and per player or 30 guests a minute per address for each project,
  `E_FORBIDDEN` for a rejected token, or when the project doesn't allow
  guests. `player()` rejects the same way when it mints a guest. Its `name` is one of the web's
  error names for the code, as `IrtError`'s is: `NotAllowedError` for
  `E_FORBIDDEN`, `NotFoundError` for `E_UNKNOWN`, `VersionError` for
  `E_VERSION`, `QuotaExceededError` for `E_QUOTA`, `E_LIMIT` and
  `E_SPENDING`, `DataError` for `E_INVALID` and `E_TYPE`, and
  `NetworkError` for `E_UNAVAILABLE`, except `AbortError` when a signal
  aborted the call and `TimeoutError` when one from
  `AbortSignal.timeout()` did, with the signal's reason as `cause`. See
  [Player data, collections and leaderboards](/docs/room/guides/player-data).

```ts
// data.ts
import { DataError, dataClient } from "@irtio/client";

const data = dataClient({ project: "https://rooms.irt.io/my-game/" });

export async function saveSettings(volume: number) {
  try {
    await data.playerData.set("settings", { volume });
  } catch (e) {
    if (e instanceof DataError && e.code === "E_UNAVAILABLE") return false;
    throw e;
  }
  return true;
}

export async function weeklyTop() {
  const { entries } = await data.leaderboard("highscores").top({ period: "week", limit: 10 });
  return entries.map((e) => `${e.rank}. ${e.meta.name ?? e.player} ${e.score}`);
}
```

## Simulated network

```ts
import { simulateNetwork, type DevConnectInit, type NetworkConditions, type SimulateOptions } from "@irtio/client/dev";

function simulateNetwork(conditions: NetworkConditions, opts?: SimulateOptions): Dial;

interface DevConnectInit<S, P, C> extends ConnectInit<S, P, C> {
  dial?: Dial;            // opens the transport, as simulateNetwork() does
}

interface NetworkConditions {
  rttMs: number;      // added round trip, half each way
  jitterMs?: number;  // each one-way delay varies by up to this much either side of rttMs / 2
  loss?: number;      // fraction of unreliable messages dropped each way, 0 to 1
}

interface SimulateOptions {
  dial?: Dial;            // the transport to wrap; default WebTransport, then WebSocket
  clock?: Clock;          // timers, for tests
  random?: () => number;  // uniform in [0, 1), for tests
  allowRemote?: boolean;  // allow rooms on hosts other than localhost, *.localhost, 127.0.0.1 or ::1
}
```

Pass the result as the `dial` of a `DevConnectInit`, a `ConnectInit` with
development hooks, to `connect()`. Reliable messages are delayed and
stay in order; unreliable messages, inputs and pings can also be dropped
and reordered. Against a room that isn't local, without `allowRemote`,
`connect()` rejects with an `IrtError` of code 0 saying so.
`simulateNetwork()` throws a `RangeError` for a negative `rttMs` or
`jitterMs`, or a `loss` outside 0 to 1. It's a separate
entry, so it adds nothing to a bundle that doesn't import it. See
[Dev tools](/docs/tools/dev-tools#simulated-network-conditions).

## Voice

`room.peers` is `{ speakers, listeners }`, the player IDs this player
hears and is heard by, as the room last decided; the `peers` event fires
when it changes. `room.voice` is the router's `{ url, token }` when the
project uses voice, and the `voice` event fires when it's granted. On
each reconnect `room.voice` is undefined and `room.peers` empty, with a
`peers` event when they weren't, until the
router and the room send them again. `joinVoice(room, { position?, spatial?, range? })` from
`@irtio/client/voice` joins the voice server. The `Voice` it returns
has `participants`, the other players on the voice server, next to
`speaking`, `mutedPlayers` and the player's own controls. It's an
`EventTarget`: `participants`, `speaking` and `mutedPlayers` fire a
`CustomEvent` with the new set in `detail` when each changes, and
`micError` one with the `Error` when the microphone fails to start and
is turned off. See [Proximity voice](/docs/room/guides/voice#client).

## Replays

`loadReplay(bytes, { schema? })` from `@irtio/client/replay` plays a
replay or clip file into `replay.entities`, an `EntityStore` with the
usual events, with `replay.state` and `replay.presence`, whose `me` is
undefined, since a replay has no local player. It throws an `Error` for
bytes that aren't a replay or clip it can read, or that have no full
state to start from. `play()`, `pause()`, `speed`, `seek(tick)` and
`step()` move it between `firstTick` and `lastTick`; `tick` is the tick
shown, `playing` whether it plays and `tickRate` the room's. A `Replay`
is an `EventTarget`: `tick` fires as each tick is shown, `message` with
a `RoomMessageEvent` for each recorded broadcast played through, and
`ended` at the last tick. Stepping fires the tick's `message` events,
then its entity callbacks, then `tick`; `seek()` fires the callbacks for
everything that leaves and enters, then `tick`, and skips messages.
`loadClip({ room, project?, clip, token?, signal? }, { schema? })`
downloads a clip its room shared and loads it the same way; it tries a
404 again for up to about 4 seconds, since the clip may not be written
yet, then rejects with an `IrtError`: with the HTTP status, or code 0 as
a `NetworkError` when the router can't be reached and an `AbortError` or
`TimeoutError` when `signal` aborts. `kind(name)` returns a recorded kind that differs from the
schema's, and `privateOf(player)` a player's private state when it was
recorded, for the players `players` lists. `startedAt`, `recordedPrivate`
and `recordedMessages` describe the recording. It's a separate entry, so
it adds nothing to a bundle that doesn't import it. See
[Replays and clips](/docs/room/guides/replays).

## Playtests

`expose(name, value)` hands the [playtest module](/docs/tools/playtest#client-hooks)
something of the game's, such as its camera, as `ctx.exposed[name]`.
`isPlaytest()` returns `true` in a page a playtest opened, whose player
a coding agent plays. In any other page, `expose()` does nothing and
`isPlaytest()` returns `false`, so both are safe to ship. In a
playtest player's page, the SDK hands each connected `RoomClient` to
the playtest as `ctx.room`, with nothing from the game.

## Common mistakes

- **Not awaiting `connect()`.** `room.state` and `room.private` are set only
  once it resolves, and `send()` throws an `InvalidStateError` before then.
- **Reloading on every close.** Reload only on 4004, a `VersionError`.
  The client already reconnects on the codes that allow it.
- **Adding a `waking` listener after `await connect(...)`.** The room is
  running by then; use `new RoomClient` and `ready` to show it starting.
- **Naming a router or region.** Connect to room URLs, relative to the
  page's `irt-project` tag; there's no region in client code.
- **Reconnecting by hand after 4011.** That's the room asking to
  hibernate; offer the player a rejoin instead of looping.
- **Writing a client entity.** Send a message, or predict the local
  player.
- **Keeping references across a resync.** After a reconnect's `open`, entities
  the room sent again are new objects, every entity after a full update
  and, after a resume, those that changed and those the player owns; look them up again or rebuild
  from `onEnter()`.
- **Opening two clients as the same player.** The router closes the
  older one with 4012, and it doesn't reconnect. Two tabs of one browser
  are the same guest when both connect with `guest: "browser"`.
