# JavaScript API Reference

Every member of the Glint SDK: Glint.init(), lifecycle, meter, demo, system and master mute, player, saves, achievements, leaderboards, multiplayer rooms, binary frames, host migration and local gamepads.

This is the reference for the browser SDK in `@joinfoundry/glint-sdk`, protocol version 1. Signatures are copied from the TypeScript declarations that ship with the package (`dist/index.d.ts`). If anything here differs, the declarations are correct.

## Load the SDK

The SDK has no runtime dependencies and is under 7 KB with Brotli. Use whichever fits your build.

```ts tab="npm"
// npm install @joinfoundry/glint-sdk
import { Glint } from "@joinfoundry/glint-sdk";
// Also available: import Glint from "@joinfoundry/glint-sdk";
// and: import { init } from "@joinfoundry/glint-sdk";

const sdk = await Glint.init();
```

```html tab="Script tag"
<!-- glint.js sits next to index.html and defines window.Glint -->
<script src="./glint.js"></script>
<script type="module">
  const sdk = await window.Glint.init();
</script>
```

`glint init` copies `glint.js` into every starter. It's also in the package at `dist/glint.js` (importable as `@joinfoundry/glint-sdk/browser`), and you can download it from `https://glint.joinfoundry.xyz/sdk/glint.js`. Ship the file inside your build: games can't load scripts from other hosts.

All types (`GlintSdk`, `MultiplayerRoom`, `SaveSlotMeta` and the rest) are exported from the package for TypeScript.

## Glint.init()

```ts
function init(opts?: { timeoutMs?: number }): Promise<GlintSdk>;
const Glint: { init: typeof init };
```

Call it once at startup to connect to the Glint host page and resolve the SDK instance. Later calls return the same promise, so calling it from multiple modules is safe.

| Option | Type | Default | Meaning |
| --- | --- | --- | --- |
| `timeoutMs` | number | `1500` | How long to wait for Glint to answer before falling back to standalone mode. |

The resolved object also has two read-only fields:

| Field | Type | Value |
| --- | --- | --- |
| `sdk.protocol` | `1` | The bridge protocol version. |
| `sdk.slug` | string | The game's address on Glint. `"local-preview"` in the Local Emulator, `"standalone"` outside Glint. |

### Standalone Mode

When the page isn't inside a frame, or nothing answers within `timeoutMs`, `init()` resolves with a standalone SDK so the same build runs on its own:

- `lifecycle` calls do nothing; `onPause` and `onResume` follow the tab's visibility.
- `meter.getState()` returns `{ kind: "preview", remainingSeconds: null }` and `demo.isDemo()` returns `false`.
- `system.getHints()` reads the browser, with `environment: "standalone"` and `muted: false`.
- `player.get()` returns `{ isSignedIn: false, id: "fp_standalone", displayName: "Player", avatarUrl: null }`.
- Saves go to `localStorage` under keys starting with `glint:standalone:save:`.
- Achievements unlock in memory, `leaderboards.submit()` returns `{ accepted: true, rank: 1 }`, `getTop()` returns `[]` and `getPlayerRank()` returns `null`.
- `demo.openPurchaseModal()` returns `{ purchased: false }`.
- `multiplayer.getPendingInviteCode()` reads `?room=` from the page's address. Creating or joining a room rejects with `Standalone mode: host bridge unavailable.`

## Lifecycle

```ts
type PauseReason = "tab_hidden" | "host_overlay" | "demo" | "free-hours";
type Unsubscribe = () => void;

sdk.lifecycle.loadingProgress(progress: number): void;
sdk.lifecycle.ready(): void;
sdk.lifecycle.gameplayStart(): void;
sdk.lifecycle.gameplayStop(): void;
sdk.lifecycle.onPause(cb: (reason: PauseReason) => void): Unsubscribe;
sdk.lifecycle.onResume(cb: () => void): Unsubscribe;
```

| Member | What it does |
| --- | --- |
| `loadingProgress(progress)` | Reports loading from `0` to `1`. Values outside that range are clamped. Glint shows it on its loading bar. |
| `ready()` | Says the first screen is interactive. Glint hides its loader and shows the game. Call it within 15 seconds; after that, Glint shows the game anyway. |
| `gameplayStart()` | Tells Glint that active gameplay started, for example when a level begins. |
| `gameplayStop()` | Tells Glint that active gameplay stopped, for example on a menu or game over screen. |
| `onPause(cb)` | Runs `cb` when Glint pauses the game. Stop your loop, physics and audio at once. |
| `onResume(cb)` | Runs `cb` when the game may continue. |

Pause reasons:

| Reason | When |
| --- | --- |
| `tab_hidden` | The player switched tabs or hid the browser. `onResume` fires when the tab is visible again. |
| `host_overlay` | The player closed the game in Glint's player. |
| `demo` | The demo's 15 minutes ran out, or the game called `sdk.demo.triggerDemoEnd()`. |
| `free-hours` | The player's free hours for the month ran out. |

On every pause, the SDK flushes pending saves for you. After `demo` and `free-hours`, Glint removes the game about 1.2 seconds later.

```js
let paused = false;
let rafId = 0;

sdk.lifecycle.onPause(() => {
  paused = true;
  cancelAnimationFrame(rafId);
  void sdk.saves.flush();
});
sdk.lifecycle.onResume(() => {
  if (!paused) return;
  paused = false;
  rafId = requestAnimationFrame(tick);
});

await loadAssets(p => sdk.lifecycle.loadingProgress(p));
sdk.lifecycle.ready();
sdk.lifecycle.gameplayStart();
```

## Meter

```ts
type MeterKind = "free" | "demo" | "owned" | "pass" | "preview";

interface MeterState {
  kind: MeterKind;
  remainingSeconds: number | null;
}

sdk.meter.getState(): MeterState;
sdk.meter.onUpdate(cb: (state: MeterState) => void): Unsubscribe;
```

| Kind | Meaning | `remainingSeconds` |
| --- | --- | --- |
| `free` | A free game, using the player's monthly free hours. | Seconds left this month |
| `demo` | A paid game's demo. | Seconds left of the 15 minutes |
| `owned` | The player owns the game. | `null` |
| `pass` | The player has Glint Pass. | `null` |
| `preview` | The game's creator or staff previewing, or standalone mode. | `null` |

Glint sends updates while time is counting. Use them to warn the player before time runs out.

## Demo

```ts
sdk.demo.isDemo(): boolean;
sdk.demo.getRemainingSeconds(): number | null;
sdk.demo.triggerDemoEnd(): void;
sdk.demo.openPurchaseModal(): Promise<{ purchased: boolean }>;
```

| Member | What it does |
| --- | --- |
| `isDemo()` | `true` when the running build is the game's demo. |
| `getRemainingSeconds()` | Seconds left in the demo when the meter kind is `demo`, otherwise `null`. |
| `triggerDemoEnd()` | Ends the demo now, for example at the end of the demo's content. Glint pauses the game with reason `demo` and shows the demo's end screen, which offers the full game. |
| `openPurchaseModal()` | Opens Glint's purchase flow for the game. It resolves right away with `{ purchased: false }`; the purchase itself happens on Glint's page. |

```js
if (sdk.demo.isDemo() && levelCompleted === 1) {
  sdk.lifecycle.gameplayStop();
  sdk.demo.triggerDemoEnd();
}
```

## System and Master Mute

```ts
interface SystemHints {
  device: "desktop" | "mobile" | "tablet";
  inputs: { touch: boolean; mouse: boolean; keyboard: boolean; gamepad: boolean };
  reducedMotion: boolean;
  maxDpr: number;
  locale: string;
  environment: "production" | "local_emulator" | "standalone";
  muted: boolean;
}

sdk.system.getHints(): SystemHints;
sdk.system.isMuted(): boolean;
sdk.system.onMuteChange(cb: (muted: boolean) => void): Unsubscribe;
```

| Hint | Meaning |
| --- | --- |
| `device` | The kind of device, from the browser's user agent. |
| `inputs` | Which inputs the device likely has. |
| `reducedMotion` | The player asked their system for reduced motion. Tone down shaking and flashing. |
| `maxDpr` | The highest canvas pixel ratio to use: 2 on phones, otherwise the screen's ratio up to 2. |
| `locale` | The browser's language, such as `en-US`. |
| `environment` | `production` on Glint, `local_emulator` in `glint preview`, `standalone` elsewhere. |
| `muted` | Glint's master mute at the time of the call. |

Glint's player bar has a mute button that applies to every game. Read `isMuted()` at startup and follow `onMuteChange()`:

```js
const hints = sdk.system.getHints();
const dpr = Math.min(2, hints.maxDpr);
canvas.width = Math.floor(canvas.clientWidth * dpr);
canvas.height = Math.floor(canvas.clientHeight * dpr);

masterGain.gain.value = sdk.system.isMuted() ? 0 : 1;
sdk.system.onMuteChange(muted => {
  masterGain.gain.value = muted ? 0 : 1;
});
```

## Player

```ts
interface PlayerIdentity {
  isSignedIn: boolean;
  id: string;
  displayName: string;
  avatarUrl: string | null;
}

sdk.player.get(): PlayerIdentity;
```

`id` is an opaque ID that starts with `fp_` and is different for every game, so games can't follow a player across Glint. It is never the player's Foundry account ID. Signed-out players get an ID tied to Glint's visitor cookie and the display name `Guest`. `avatarUrl` is the player's profile photo, or `null`.

## Saves

```ts
interface SaveSlotMeta {
  slot: string;
  bytes: number;
  updatedAt: number;
}

sdk.saves.list(): Promise<SaveSlotMeta[]>;
sdk.saves.load<T = unknown>(slot: string): Promise<{ data: T; updatedAt: number; bytes: number } | null>;
sdk.saves.save<T = unknown>(slot: string, data: T, opts?: { immediate?: boolean }): Promise<{ ok: boolean; bytesUsed: number }>;
sdk.saves.delete(slot: string): Promise<void>;
sdk.saves.flush(): Promise<void>;
```

Saves are stored per player and per game on Glint's servers, so they follow the player to any device and no other game can read them.

| Rule | Limit |
| --- | --- |
| Slots | Up to 4 per player per game |
| Slot names | 1 to 32 letters, digits, hyphens or underscores, such as `main` or `slot-2` |
| Size | 1 MB in total across all slots, measured as UTF-8 JSON |
| Data | Anything JSON can represent |

| Member | What it does |
| --- | --- |
| `list()` | The player's slots with their size in bytes and last update time (milliseconds since 1970). |
| `load(slot)` | The slot's data, update time and size, or `null` if the slot is empty. |
| `save(slot, data, opts)` | Writes the slot. The SDK writes each slot at most once every 2 seconds; quicker saves wait and only the latest data is written. Pass `{ immediate: true }` to write at once. Resolves with `bytesUsed`, the total across all slots. |
| `delete(slot)` | Removes the slot and cancels any waiting write to it. |
| `flush()` | Writes every waiting save now. The SDK also does this on every pause. |

A save that would need a fifth slot, or take the total over 1 MB, rejects with an error. When a signed-out player signs in, their guest saves move to their account; for each slot, the newer copy wins.

```ts
type Progress = { level: number; coins: number };

const saved = await sdk.saves.load<Progress>("main");
const progress = saved?.data ?? { level: 1, coins: 0 };

progress.level += 1;
await sdk.saves.save("main", progress);
```

## Achievements

```ts
sdk.achievements.listUnlocked(): Promise<string[]>;
sdk.achievements.unlock(key: string): Promise<{ newlyUnlocked: boolean }>;
```

Define achievements in Glint Studio first, up to 100 per game. See [Achievements and Leaderboards](https://joinfoundry.xyz/help/glint/achievements-and-leaderboards). Keys use lowercase letters, digits, hyphens and underscores; the SDK trims and lowercases the key you pass.

| Member | What it does |
| --- | --- |
| `listUnlocked()` | The keys the player has unlocked in this game. |
| `unlock(key)` | Unlocks the achievement. `newlyUnlocked` is `true` the first time; repeat calls return `false` without contacting Glint again. A key that isn't defined in Glint Studio rejects with an error. |

When an achievement is newly unlocked, Glint shows its own "Achievement unlocked" toast with the name and description from Glint Studio, so you don't need your own. Guest unlocks move to the player's account when they sign in.

```js
const { newlyUnlocked } = await sdk.achievements.unlock("first_win");
```

## Leaderboards

```ts
type LeaderboardScope = "all" | "weekly" | "daily";

interface LeaderboardEntry {
  rank: number;
  entryId?: string;
  playerId: string;
  displayName: string;
  score: number;
  metadata: Record<string, string | number> | null;
  submittedAt: string;
}

sdk.leaderboards.submit(
  boardKey: string,
  score: number,
  metadata?: Record<string, string | number>,
): Promise<{ accepted: boolean; rank?: number }>;
sdk.leaderboards.getTop(boardKey: string, opts?: { scope?: LeaderboardScope; limit?: number }): Promise<LeaderboardEntry[]>;
sdk.leaderboards.getPlayerRank(boardKey: string, opts?: { scope?: LeaderboardScope }): Promise<LeaderboardEntry | null>;
```

Define each board in Glint Studio first, up to 20 per game, with its sort order, lowest and highest allowed score, submissions per minute and minimum play time. See [Achievements and Leaderboards](https://joinfoundry.xyz/help/glint/achievements-and-leaderboards).

| Member | What it does |
| --- | --- |
| `submit(boardKey, score, metadata)` | Submits a score. Glint keeps each player's best score for all time, the current week (from Monday, UTC) and the current day (UTC). `accepted` is `false` when the score is outside the board's range or the player hasn't played for the board's minimum time. `rank` is the all-time rank of this score. |
| `getTop(boardKey, opts)` | The top entries for a scope. `scope` defaults to `"all"`; `limit` is 1 to 100 and defaults to 10. Ties go to the earlier submission. |
| `getPlayerRank(boardKey, opts)` | The player's own entry and rank for a scope, or `null` if they have none. `entryId` is only set on `getTop()` entries. |

`metadata` keys can be up to 40 characters, and values are numbers or strings of up to 80 characters. A board that isn't defined in Glint Studio, or too many submissions in a minute, rejects with an error.

```js
const { accepted, rank } = await sdk.leaderboards.submit("high_score", score, { level: 3 });
const weekly = await sdk.leaderboards.getTop("high_score", { scope: "weekly", limit: 10 });
const me = await sdk.leaderboards.getPlayerRank("high_score", { scope: "weekly" });
```

## Multiplayer Rooms

Online multiplayer runs through rooms that Glint relays for you. Your game doesn't open a connection itself. Glint's page holds the connection and passes messages to and from your frame, and players never see each other's IP addresses. Set `multiplayer.online.enabled` to `true` in `glint.json` (see the [Manifest Reference](https://joinfoundry.xyz/help/developers/glint-sdk-manifest#multiplayeronline)).

```ts
sdk.multiplayer.getPendingInviteCode(): string | null;
sdk.multiplayer.createRoom(opts?: RoomCreateOptions): Promise<MultiplayerRoom>;
sdk.multiplayer.joinRoom(code: string, opts?: { asSpectator?: boolean }): Promise<MultiplayerRoom>;
sdk.multiplayer.quickJoin(opts?: QuickJoinOptions): Promise<MultiplayerRoom>;
sdk.multiplayer.openInviteDialog(): Promise<{ code: string; url: string }>;
sdk.multiplayer.local: LocalMultiplayerHelper;
```

A player is in one room at a time. Creating or joining a room closes the connection to the previous one; call `leave()` on the old room object first so its listeners stop too.

### Create, Join and Quick Join

```ts
interface RoomCreateOptions {
  mode?: string;
  bucket?: string;
  maxPlayers?: number;
  visibility?: "public" | "invite_only" | "invite";
  locked?: boolean;
  allowSpectators?: boolean;
  allowJoinInProgress?: boolean;
  initialState?: Record<string, unknown>;
  metadata?: Record<string, string | number | boolean>;
}

interface QuickJoinOptions {
  mode?: string;
  bucket?: string;
  maxPlayers?: number;
  createIfNone?: boolean;
}
```

`createRoom(opts)` makes a room and joins it as its first player and host.

| Option | Default | Meaning |
| --- | --- | --- |
| `mode` | `"default"` | A name for the kind of match, up to 40 characters. Quick join matches rooms with the same name. |
| `bucket` | Same as `mode` | Used instead of `mode` for matching when both are set. |
| `maxPlayers` | `multiplayer.online.maxPlayers`, or 8 | 2 to 16 active players. Spectators don't count. |
| `visibility` | `"invite_only"` | `"public"` rooms can be found by quick join. `"invite"` is the same as `"invite_only"`. |
| `locked` | `false` | A locked room refuses new players. |
| `allowSpectators` | `multiplayer.online.allowSpectators`, or `true` | Whether others can join to watch. |
| `allowJoinInProgress` | `multiplayer.online.allowJoinInProgress`, or `true` | Stored with the room. Glint doesn't enforce it yet; to stop players joining a match in progress, lock the room. |
| `initialState` | `{}` | The room's starting shared state, up to 64 KB. |
| `metadata` | None | Accepted, but Glint doesn't store it yet. |

`joinRoom(code, opts)` joins a room by its code. Codes are 4 characters and not case-sensitive. Pass `{ asSpectator: true }` to watch instead of play. Joining again with the same player while still in the room reconnects to the same seat.

`quickJoin(opts)` joins the first public, unlocked room with the same `bucket` (or `mode`) that has a free seat. If none exists, it creates a public room with those options, unless `createIfNone` is `false`, in which case it rejects.

These calls reject with an error whose message says why, for example `That room was not found or has closed.`, `This room is full.`, `This match has already started.` (the room is locked), `This room does not allow spectators.`, `This room's spectator slots are full.` or `No open room is available right now.`

```js
const invite = sdk.multiplayer.getPendingInviteCode();
const room = invite
  ? await sdk.multiplayer.joinRoom(invite)
  : await sdk.multiplayer.quickJoin({ mode: "arena", maxPlayers: 8, createIfNone: true });
```

### Invites

`openInviteDialog()` opens Glint's "Invite players" dialog for the current room. It shows the room code and a Copy invite link button, and resolves with the code and the link. The link is the game's page with `?room=CODE` added. It rejects if the player isn't in a room.

When someone opens an invite link and starts the game, `getPendingInviteCode()` returns the code. Check it once at startup and join that room, as in the example above.

### The Room Object

```ts
interface MultiplayerPlayer {
  id: string;
  displayName: string;
  avatarUrl: string | null;
  isHost: boolean;
  role: "player" | "spectator";
  seat: number | null;
  status: "active" | "away" | "reconnecting";
  state: Record<string, unknown>;
}

interface MultiplayerRoom {
  readonly id: string;
  readonly code: string;
  readonly mode: string;
  readonly maxPlayers: number;
  readonly locked: boolean;
  readonly selfId: string;
  readonly hostId: string;
  readonly isHost: boolean;
  readonly players: ReadonlyArray<MultiplayerPlayer>;
  readonly spectators: ReadonlyArray<MultiplayerPlayer>;
  readonly state: Readonly<Record<string, unknown>>;
  serverNow(): number;
  setRoomState(patch: Record<string, unknown>): void;
  setPlayerState(patch: Record<string, unknown>): void;
  setLocked(locked: boolean): void;
  send(
    target: "all" | "host" | "others" | string,
    type: string,
    payload: unknown | Uint8Array,
    opts?: { reliable?: boolean },
  ): boolean;
  onStateChange(cb: (state: Record<string, unknown>, patch?: Record<string, unknown>) => void): Unsubscribe;
  onPlayerState(cb: (playerId: string, state: Record<string, unknown>) => void): Unsubscribe;
  onMessage(cb: (fromGlinterId: string, type: string, payload: unknown, binary: boolean) => void): Unsubscribe;
  onPlayerJoin(cb: (player: MultiplayerPlayer) => void): Unsubscribe;
  onPlayerLeave(cb: (playerId: string, reason: string) => void): Unsubscribe;
  onPlayerStatus(cb: (playerId: string, status: "active" | "away" | "reconnecting") => void): Unsubscribe;
  onHostChange(cb: (newHostId: string, isSelfHost: boolean) => void): Unsubscribe;
  onError(cb: (err: { code: string; message: string }) => void): Unsubscribe;
  onClose(cb: () => void): Unsubscribe;
  leave(): Promise<void>;
}
```

| Member | Meaning |
| --- | --- |
| `id`, `code` | The room's ID and its 4-character join code. |
| `mode` | The room's matching name (its `bucket`, or `mode`). |
| `maxPlayers` | Active player seats. |
| `locked` | Whether the room refuses new players. |
| `selfId` | This player's ID, the same as `sdk.player.get().id`. |
| `hostId`, `isHost` | The current host, and whether that's this player. |
| `players` | Active players, kept up to date as players join, leave and change state. `seat` is a 0-based seat number. |
| `spectators` | Spectators in the room when this player joined. Glint doesn't announce spectators joining or leaving. |
| `state` | The room's shared state. |
| `serverNow()` | The relay's clock in milliseconds, using the offset measured when you joined. Use it to schedule events at the same moment for everyone. |
| `leave()` | Leaves the room and removes this room's listeners. Other players get `onPlayerLeave` with reason `"left"`. |
| `onClose(cb)` | The room connection closed. |

### Room State and Player State

- `setRoomState(patch)` merges `patch` into the room's shared state. Only the host can change it; calls from other players are ignored. The whole state can be up to 64 KB.
- `setPlayerState(patch)` merges `patch` into this player's own state, up to 8 KB. Spectators can't set player state.
- `setLocked(locked)` locks or unlocks the room. Only the host can. A locked room refuses new players (spectators can still join) and quick join skips it.

Changes reach every member of the room, including the one who made them, through `onStateChange(state, patch)` and `onPlayerState(playerId, state)`. Patches are shallow: each top-level key you send replaces the old value.

```js
if (room.isHost) room.setRoomState({ phase: "playing", round: 1 });
room.setPlayerState({ ready: true });

room.onStateChange((state, patch) => {
  if (patch?.phase === "playing") startRound(state.round);
});
room.onPlayerState((playerId, state) => markReady(playerId, state.ready));
```

### Messages

`send(target, type, payload, opts)` sends a message and returns `true`, or returns `false` without sending when the message is over 4 KB or you've sent 20 messages in the last second.

| `target` | Who receives it |
| --- | --- |
| `"all"` | Every other member of the room |
| `"others"` | Every other member of the room |
| `"host"` | The host |
| A player ID | That player |

The sender doesn't receive its own messages. `type` is your own label, up to 64 characters. `payload` is anything JSON can represent, or a `Uint8Array` for [binary frames](#binary-frames). Receivers get `onMessage(fromGlinterId, type, payload, binary)`.

```js
room.onMessage((from, type, payload) => {
  if (room.isHost && type === "input") applyInput(from, payload);
});
room.send("host", "input", { left: true, jump: false });
```

Render at full frame rate locally and send compact updates 10 to 20 times a second, interpolating between them.

### Binary Frames

Pass a `Uint8Array` as the payload to send raw bytes. The bytes go to the receivers without JSON encoding, and receivers get a `Uint8Array` with `binary` set to `true`. Use them for frequent snapshots such as positions.

```js
// Sender: 8 bytes, two 32-bit floats, about 15 times a second
const packet = new Uint8Array(8);
const view = new DataView(packet.buffer);
view.setFloat32(0, x, true);
view.setFloat32(4, y, true);
room.send("others", "pos", packet, { reliable: false });

// Receiver
room.onMessage((from, type, payload, binary) => {
  if (type !== "pos" || !binary || payload.byteLength < 8) return;
  const v = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
  movePeer(from, v.getFloat32(0, true), v.getFloat32(4, true));
});
```

- A frame can carry up to 4 KB (4,096 bytes).
- When the array covers its whole buffer, the SDK hands that buffer to Glint without copying it, and the buffer is then detached: you can't read or reuse it. Create a new array for each send, as above, or send a `subarray()`, which the SDK copies.
- `reliable: false` marks a frame that can be dropped. Today every message travels over the same ordered connection either way; JSON messages ignore the option.

### Host Migration

The host is the player who runs the authoritative game logic. Glint picks a new host when:

- the host's connection drops: the earliest-joined active player becomes host right away;
- the host's tab stays hidden for 10 seconds: the host moves to another active player;
- the host leaves the room.

Always handle `onHostChange`. The validator warns when an online game has no `onHostChange` handler ([GL014](https://joinfoundry.xyz/help/developers/glint-sdk-cli#gl014)).

```js
room.onHostChange((newHostId, isSelfHost) => {
  if (isSelfHost) {
    // Continue the match from the shared state the old host kept up to date.
    simulation.resumeFrom(room.state);
    room.setRoomState({ migratedAt: room.serverNow() });
  }
});
```

Keep anything the next host needs in `setRoomState()`, so the match survives a host change.

### Presence and Reconnects

| Event | When |
| --- | --- |
| `onPlayerJoin(player)` | A new player joined. Spectators aren't announced. |
| `onPlayerStatus(playerId, "away")` | That player's tab is hidden. Glint sends this for them when it pauses their game. |
| `onPlayerStatus(playerId, "active")` | They're back, or they reconnected. |
| `onPlayerStatus(playerId, "reconnecting")` | Their connection dropped. They keep their seat for 30 seconds. |
| `onPlayerLeave(playerId, reason)` | They left (`"left"`) or didn't reconnect within 30 seconds (`"timeout"`). |

While your game is paused in an online room, stop sending inputs and mute audio, but keep handling messages and state from others.

A room closes 60 seconds after its last member leaves or times out.

### Errors and Limits

| Limit | Value |
| --- | --- |
| Active players | 2 to 16 |
| Spectators | Up to 32 |
| Messages | 20 per second per member, counting state changes as well as `send()` |
| Message size | 4 KB |
| Room state | 64 KB |
| Player state | 8 KB per player |
| Reconnect grace | 30 seconds |
| Host away before migration | 10 seconds |

`onError(cb)` reports problems in the room as `{ code, message }`. When a member goes over the message rate, or a message or state change is too large, Glint drops it and reports the code `FP013_MP_LIMIT_EXCEEDED`. This is a room error, separate from the validator's GL013 code.

## Controller Input and Remapping

`sdk.input` gives you synchronous, remappable input from USB and Bluetooth controllers (Xbox, PlayStation, Nintendo Switch, 8BitDo and generic pads). Players can remap buttons and sticks for each controller, rebind your game's actions from the controller button in the player or the **Controller** section of Glint Account, and set the deadzone and invert-Y. Signed-in players' settings follow them across devices.

```ts
type GamepadButtonId =
  | "south" | "east" | "west" | "north"
  | "lb" | "rb" | "lt" | "rt"
  | "select" | "start" | "l3" | "r3"
  | "dpad_up" | "dpad_down" | "dpad_left" | "dpad_right";

type GamepadBindingTarget = GamepadButtonId | "left_stick" | "right_stick" | "dpad";

interface GamepadActionDef {
  id: string;
  label: string;
  kind?: "button" | "trigger" | "axis2d";
  default: GamepadBindingTarget;
  description?: string;
}

sdk.input.defineActions(actions: GamepadActionDef[]): void;
sdk.input.getActions(): GamepadActionDef[];
sdk.input.getConnected(): Array<{ index: number; id: string; glyphStyle: "xbox" | "playstation" | "nintendo" | "generic" }>;
sdk.input.poll(slot?: number): GamepadSnapshot;
sdk.input.getBinding(actionId: string): GamepadBinding | null;
sdk.input.getActionLabel(actionId: string, slot?: number): string;
sdk.input.getButtonLabel(target: GamepadBindingTarget, slot?: number): string;
sdk.input.rumble(slot?: number, opts?: { durationMs?: number; strong?: number; weak?: number }): boolean;
sdk.input.openRemapper(): void;
sdk.input.onConfigChange(cb: () => void): Unsubscribe;
sdk.input.onGamepadChange(cb: (pads) => void): Unsubscribe;
```

Declare actions in `glint.json` under `inputs.gamepad.actions` (or call `sdk.input.defineActions` at startup), then poll once per frame:

```ts
sdk.input.defineActions([
  { id: "move", label: "Move", kind: "axis2d", default: "left_stick" },
  { id: "jump", label: "Jump", kind: "button", default: "south" },
  { id: "boost", label: "Boost", kind: "trigger", default: "rt" },
]);

function update() {
  const pad = sdk.input.poll(0); // Player 1 (use 0..3 for local multiplayer)
  if (pad.connected) {
    const move = pad.actionAxis("move"); // Radial deadzone & invert-Y applied
    if (pad.justPressed("jump")) player.jump();
    player.setBoost(pad.actionValue("boost")); // 0..1 analog trigger
  }
}

// Show button prompts matching the player's actual controller and rebinds (e.g. "A", "Cross", "B")
jumpHint.textContent = `Press ${sdk.input.getActionLabel("jump")} to jump`;
```

Call `sdk.input.openRemapper()` from your own settings menu to open Glint's controller remapper. Subscribe to `sdk.input.onConfigChange(...)` to update on-screen button prompts when the player changes a binding.

## Local Gamepads

```ts
interface LocalMultiplayerHelper {
  getConnectedGamepads(): Gamepad[];
  onGamepadChange(cb: (pads: Gamepad[]) => void): Unsubscribe;
}
```

For players sharing one device, `sdk.multiplayer.local` wraps the browser's Gamepad API. `getConnectedGamepads()` returns the connected pads, and `onGamepadChange(cb)` calls `cb` with the current list whenever a pad connects or disconnects. Glint's frame allows gamepad access. Declare local play in `multiplayer.local` in `glint.json`.

```js
const seats = new Map();
const assign = pads => {
  seats.clear();
  pads.forEach((pad, i) => seats.set(pad.index, i));
};
assign(sdk.multiplayer.local.getConnectedGamepads());
sdk.multiplayer.local.onGamepadChange(assign);
```

## Type Reference

```ts
interface GlintSdk {
  readonly protocol: 1;
  readonly slug: string;
  readonly lifecycle: {
    loadingProgress(progress: number): void;
    ready(): void;
    gameplayStart(): void;
    gameplayStop(): void;
    onPause(cb: (reason: PauseReason) => void): Unsubscribe;
    onResume(cb: () => void): Unsubscribe;
  };
  readonly meter: {
    getState(): MeterState;
    onUpdate(cb: (state: MeterState) => void): Unsubscribe;
  };
  readonly demo: {
    isDemo(): boolean;
    getRemainingSeconds(): number | null;
    triggerDemoEnd(): void;
    openPurchaseModal(): Promise<{ purchased: boolean }>;
  };
  readonly system: {
    getHints(): SystemHints;
    isMuted(): boolean;
    onMuteChange(cb: (muted: boolean) => void): Unsubscribe;
  };
  readonly player: {
    get(): PlayerIdentity;
  };
  readonly saves: {
    list(): Promise<SaveSlotMeta[]>;
    load<T = unknown>(slot: string): Promise<{ data: T; updatedAt: number; bytes: number } | null>;
    save<T = unknown>(slot: string, data: T, opts?: { immediate?: boolean }): Promise<{ ok: boolean; bytesUsed: number }>;
    delete(slot: string): Promise<void>;
    flush(): Promise<void>;
  };
  readonly achievements: {
    listUnlocked(): Promise<string[]>;
    unlock(key: string): Promise<{ newlyUnlocked: boolean }>;
  };
  readonly leaderboards: {
    submit(
      boardKey: string,
      score: number,
      metadata?: Record<string, string | number>,
    ): Promise<{ accepted: boolean; rank?: number }>;
    getTop(boardKey: string, opts?: { scope?: LeaderboardScope; limit?: number }): Promise<LeaderboardEntry[]>;
    getPlayerRank(boardKey: string, opts?: { scope?: LeaderboardScope }): Promise<LeaderboardEntry | null>;
  };
  readonly multiplayer: {
    getPendingInviteCode(): string | null;
    createRoom(opts?: RoomCreateOptions): Promise<MultiplayerRoom>;
    joinRoom(code: string, opts?: { asSpectator?: boolean }): Promise<MultiplayerRoom>;
    quickJoin(opts?: QuickJoinOptions): Promise<MultiplayerRoom>;
    openInviteDialog(): Promise<{ code: string; url: string }>;
    readonly local: LocalMultiplayerHelper;
  };
  readonly input: InputModule;
}
```
