@ksaa-nlp/gamehub-sdk 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,111 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.1 — 2026-04-30
4
+
5
+ Three small, additive fixes that surfaced while porting link-game to the `multiplayer.match` API.
6
+
7
+ - **`MatchCtx.retained: boolean`.** Added a `retained` flag on the context passed into `apply` and `onStart` handlers. It's `true` only when the handler is running for a server-replayed retained frame (a peer reconnecting / joining late catching up on past state) and `false` for live broadcasts and host-initiated calls. Game code uses this to suppress one-shot side effects — sounds, confetti, win animations, draw dialogs on a delay — that would otherwise re-fire for state the peer didn't see live. Also: retained replays no longer trigger a host's `hostHandle` (the host already authored that frame; re-validating against its own snapshot is at best wasteful, at worst incorrect).
8
+
9
+ - **`Peer` identity fields.** The wire payload from the realtime server (`displayName`, `avatar`, `userId`, `guestId`) was already populated from JWT claims, but the public `Peer` type only exposed `peerId`/`role`/`metadata`. Adding the rest as optional fields lets games access player-name and avatar info without an `as any` cast. Optional because anonymous / passcode-joined peers may not carry all four.
10
+
11
+ - **`MatchEventMap` constraint relaxed to a self-mapped form.** `match<TMap, TStart>(...)` previously required `TMap extends Record<string, MatchScopedPayload>`, which TypeScript silently rejects for an `interface LinkMatchMap { ... }` declaration because interfaces with concrete keys don't have an index signature. Switched the constraint everywhere (the `match()` factory, `MatchOptions`, the `Sdk['multiplayer'].match` signature) to the self-mapped pattern `<TMap extends { [K in keyof TMap]: MatchScopedPayload }>`, which accepts both interface-shaped and type-alias-shaped event maps while still enforcing per-key payload safety. The `MatchEventMap` alias is retained as documentation; its docstring now explains why the actual generics use the self-mapped form.
12
+
13
+ ### Why these are 0.6.1 rather than 0.6.0
14
+
15
+ These shipped together with the original `multiplayer.match` API (0.6.0) but emerged only when a real game tried to consume it. Bumping a patch version makes the relationship explicit: 0.6.0 is the API as designed; 0.6.1 is the API as a real game actually uses it.
16
+
17
+ ### Verified
18
+
19
+ - SDK type-check + build clean (53.3 KB IIFE).
20
+ - link-game (Angular, `@ksaa-nlp/gamehub-sdk@0.6.x` consumer) builds clean against the new types.
21
+ - 18/18 realtime tests still green.
22
+
23
+ ### Unchanged
24
+
25
+ - Wire protocol with the realtime server.
26
+ - `Sdk` interface beyond the new `MatchCtx.retained` / `Peer.{userId,guestId,displayName,avatar}` fields and the loosened `match<>` constraint (purely a relaxation, no existing code breaks).
27
+ - `BootstrapData`, `MpMessage`, `multiplayer.send` / `broadcast` / `on` semantics.
28
+
29
+ ---
30
+
31
+ ## 0.6.0 — 2026-04-30
32
+
33
+ Adds **`multiplayer.match()`** — a host-authoritative match coordinator that owns the lifecycle every multiplayer game otherwise reinvents: peer-ready handshake, host-elected match start, intent → resolve routing, matchId scoping, and idempotent reapply of broadcasts (live and retained replay alike). Plus two helpers (`assignSeats`, `waitForPeers`) that complete the picture.
34
+
35
+ ### Why
36
+
37
+ Surveying the in-tree multiplayer game (link-game) showed that ~700 lines of its component file were transport plumbing, not gameplay: a `readyPeerIds` set, a `currentMatchId`, an `appliedEventKeys` set, manual `if (!this.isHostPeer()) return;` guards on every intent path, manual `if (p.matchId !== this.currentMatchId) return;` filters on every applier, and an ad-hoc switch dispatcher fanning the SDK's `'message'` channel into per-event handlers.
38
+
39
+ All of that is generic — every host-authoritative game needs the same machinery — so it belongs in the SDK.
40
+
41
+ ### What changed
42
+
43
+ - **`Sdk.multiplayer.match<TMap, TStart>(options)`**. Build a Match by declaring (a) a typed event map, (b) per-event `hostHandle` / `apply` pairs, and (c) a host-only `buildStart`. Everything else lives in the reducer.
44
+
45
+ ```ts
46
+ const match = sdk.multiplayer.match<LinkMap, MatchStartPayload>({
47
+ expectedPeers: 2,
48
+ buildStart: async (peers) => ({
49
+ greenPeerId: seats.bySeat.green,
50
+ navyPeerId: seats.bySeat.navy,
51
+ cellAssignments: makeGrid(),
52
+ startedAtMs: Date.now(),
53
+ }),
54
+ onStart: (ctx, p) => applyMatchStart(p),
55
+ events: {
56
+ 'link:cell_click_request': {
57
+ hostHandle: (ctx, p, from) => ctx.broadcast('link:cell_opened', resolve(p, from)),
58
+ },
59
+ 'link:cell_opened': {
60
+ apply: (ctx, p) => applyCellOpened(p),
61
+ idKey: (p) => `cell:${p.cellId}`,
62
+ retain: true,
63
+ retainKey: (p) => `cell:${p.cellId}`,
64
+ },
65
+ },
66
+ onWaitingForPeers: (waiting) => /* show overlay */,
67
+ onPeerLeft: (ctx, peerId) => /* show disconnect dialog */,
68
+ onAborted: (reason) => /* show retry/back */,
69
+ });
70
+ ```
71
+
72
+ What the SDK enforces, so games stop writing it:
73
+ - `peer_ready` handshake fires automatically (or on an explicit `match.markReady()` when `autoReady: false`).
74
+ - Host elects start once `expectedPeers` are present and ready, calls `buildStart`, broadcasts the result with `retain: true` so reconnecting peers receive it.
75
+ - **`matchId` auto-injection on send + auto-verification on receive.** Frames from a previous match are dropped before user code runs.
76
+ - **`idKey` dedupe** — same logical event applied at most once per match. Defaults to `${event}:${matchId}:${seq}`; override per-event when retained replays need to dedupe against live frames the peer already saw (e.g. `cell:${cellId}`).
77
+ - **Host short-circuit** — `match.intent(...)` from the host runs `hostHandle` directly without a WS roundtrip.
78
+ - **`hostOnly` guarding** — `ctx.broadcast` no-ops on guests with a warning.
79
+ - **Lifecycle states** — `waiting | starting | active | aborted | ended`. Subscribe via `match.onStateChange(handler)`.
80
+ - **Reconnect resilience** — re-announces ready on every `connected`/`room_joined`, replays retained match-start + per-event snapshots automatically, idKey dedupe catches the overlap.
81
+
82
+ - **`Sdk.multiplayer.assignSeats(peers, seatNames, hostPeerId)`** — generalises link-game's `assignColors` to N seats and N peers. Sorts as `host first, then lex-asc by peerId`, returns both `bySeat` and `byPeer` maps.
83
+
84
+ - **`Sdk.multiplayer.waitForPeers(n, timeoutMs?)`** — promise-based barrier for "don't render until everyone's here".
85
+
86
+ - The match-start broadcast is **always retained** under `match:start`. Per-event retain is opt-in via `MatchEventDef.retain` / `retainKey`. The `retain` defaults are baked into the reducer so games that follow the standard pattern get transparent reconnect for free.
87
+
88
+ - New exported types: [`Match`, `MatchOptions`, `MatchCtx`, `MatchHostCtx`, `MatchEventDef`, `MatchEventMap`, `MatchScopedPayload`, `MatchBroadcastOptions`, `MatchState`, `MatchAbortReason`](./types/multiplayer-match.ts).
89
+
90
+ ### Migration
91
+
92
+ The match API is purely additive — existing `multiplayer.send` / `broadcast` / `on` paths are unchanged. Games can adopt it incrementally; mixing match-managed events with raw `multiplayer.on` listeners is fine.
93
+
94
+ A typical port (link-game): the per-event switch in [link.component.ts:491](https://github.com/...) becomes the `events` map, `readyPeerIds` / `appliedEventKeys` / `currentMatchId` are deleted, every `if (p.matchId !== this.currentMatchId)` and `if (this.isHostPeer())` guard is deleted. Estimated 60–70% reduction in multiplayer-related code.
95
+
96
+ ### What's verified
97
+
98
+ - TypeScript: full type-check passes; a smoke test exercises the public generics end-to-end against a realistic game-shaped event map (typed `hostHandle`, `apply`, `idKey`, `retainKey`, `assignSeats` literal-tuple inference, `match.intent`/`match.broadcast`).
99
+ - Build: `npm run build` ships a 53.1 KB IIFE (up from 39.8 KB at 0.5).
100
+
101
+ ### Unchanged
102
+
103
+ - Wire protocol with the realtime server (the match reducer just uses the existing `send`/`broadcast` + retained-events transport from 0.5).
104
+ - Public `Sdk` interface beyond the three new methods.
105
+ - `BootstrapData` shape, `MpMessage` shape, all other multiplayer methods.
106
+
107
+ ---
108
+
3
109
  ## 0.5.0 — 2026-04-30
4
110
 
5
111
  Adds **retained ("sticky") multiplayer events** so peers that join or reconnect mid-match automatically receive the latest authoritative state before any live traffic — without games having to write a custom resync intent.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // src/constants.ts
4
- var SDK_VERSION = "0.5.0";
4
+ var SDK_VERSION = "0.6.1";
5
5
  var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
6
  var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
7
  var MP_MAX_RECONNECT_ATTEMPTS = 5;
@@ -645,6 +645,9 @@
645
645
  frame.retain = true;
646
646
  if (options.retainKey) frame.retainKey = options.retainKey;
647
647
  }
648
+ if (options.to !== void 0) {
649
+ frame.to = options.to;
650
+ }
648
651
  socket.send(JSON.stringify(frame));
649
652
  return true;
650
653
  }
@@ -1098,6 +1101,449 @@
1098
1101
  });
1099
1102
  }
1100
1103
 
1104
+ // src/multiplayer-match.ts
1105
+ var READY_EVENT_DEFAULT = "match:peer_ready";
1106
+ var START_EVENT_DEFAULT = "match:start";
1107
+ var START_RETAIN_KEY_DEFAULT = "match:start";
1108
+ var activeMatch = null;
1109
+ function generateMatchId() {
1110
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
1111
+ return crypto.randomUUID();
1112
+ }
1113
+ return `match-${Date.now()}-${Math.random().toString(36).slice(2)}`;
1114
+ }
1115
+ function createMatch(options) {
1116
+ if (activeMatch) {
1117
+ throw new Error(
1118
+ "multiplayer.match: an existing match is still active. Call destroy() first."
1119
+ );
1120
+ }
1121
+ if (!state.mpRoom) {
1122
+ throw new Error(
1123
+ "multiplayer.match: not in a room. Call createRoom/joinRoom first."
1124
+ );
1125
+ }
1126
+ const expectedPeers = options.expectedPeers ?? 2;
1127
+ const autoReady = options.autoReady !== false;
1128
+ const startEventName = options.startEventName ?? START_EVENT_DEFAULT;
1129
+ const readyEventName = options.readyEventName ?? READY_EVENT_DEFAULT;
1130
+ const startRetainKey = options.startRetainKey ?? START_RETAIN_KEY_DEFAULT;
1131
+ let matchState = "waiting";
1132
+ let matchId = null;
1133
+ let starting = false;
1134
+ let destroyed = false;
1135
+ let wantReady = autoReady;
1136
+ const readyPeerIds = /* @__PURE__ */ new Set();
1137
+ const appliedIdKeys = /* @__PURE__ */ new Set();
1138
+ const stateChangeHandlers = /* @__PURE__ */ new Set();
1139
+ const offHandlers = [];
1140
+ function setState(next) {
1141
+ if (matchState === next) return;
1142
+ matchState = next;
1143
+ for (const handler of stateChangeHandlers) {
1144
+ try {
1145
+ handler(next);
1146
+ } catch (err) {
1147
+ error("multiplayer.match onStateChange handler error:", err);
1148
+ }
1149
+ }
1150
+ }
1151
+ function localSelfId() {
1152
+ return selfId();
1153
+ }
1154
+ function localIsHost() {
1155
+ return isHost();
1156
+ }
1157
+ function localPeers() {
1158
+ return getPeers();
1159
+ }
1160
+ function makeCtx(retained = false) {
1161
+ return {
1162
+ get matchId() {
1163
+ return matchId ?? "";
1164
+ },
1165
+ get isHost() {
1166
+ return localIsHost();
1167
+ },
1168
+ get selfId() {
1169
+ return localSelfId() ?? "";
1170
+ },
1171
+ get peers() {
1172
+ return localPeers();
1173
+ },
1174
+ retained,
1175
+ peer(peerId) {
1176
+ return localPeers().find((p) => p.peerId === peerId) ?? null;
1177
+ },
1178
+ intent: apiIntent,
1179
+ broadcast: apiBroadcast
1180
+ };
1181
+ }
1182
+ function eventDefFor(name) {
1183
+ return options.events[name];
1184
+ }
1185
+ function idKeyFor(eventName, def, payload, seq) {
1186
+ if (def?.idKey) {
1187
+ try {
1188
+ return def.idKey(payload);
1189
+ } catch (err) {
1190
+ error(
1191
+ `multiplayer.match idKey('${eventName}') threw \u2014 falling back to seq:`,
1192
+ err
1193
+ );
1194
+ }
1195
+ }
1196
+ return `${eventName}:${payload.matchId}:${seq ?? "local"}`;
1197
+ }
1198
+ function maybeApply(eventName, def, payload, fromPeerId, seq, retained) {
1199
+ if (!def?.apply) return;
1200
+ const key = idKeyFor(eventName, def, payload, seq);
1201
+ if (appliedIdKeys.has(key)) return;
1202
+ appliedIdKeys.add(key);
1203
+ try {
1204
+ def.apply(makeCtx(retained), payload, fromPeerId);
1205
+ } catch (err) {
1206
+ error(`multiplayer.match apply('${eventName}') threw:`, err);
1207
+ }
1208
+ }
1209
+ function apiIntent(name, payloadIn) {
1210
+ if (destroyed || matchState === "aborted" || matchState === "ended") {
1211
+ warn(
1212
+ `multiplayer.match.intent('${String(name)}'): match is ${matchState}`
1213
+ );
1214
+ return false;
1215
+ }
1216
+ if (matchId == null) {
1217
+ warn(
1218
+ `multiplayer.match.intent('${String(name)}'): match has not started yet`
1219
+ );
1220
+ return false;
1221
+ }
1222
+ const payload = { ...payloadIn, matchId };
1223
+ const def = eventDefFor(String(name));
1224
+ if (localIsHost() && def?.hostHandle) {
1225
+ const me = localSelfId();
1226
+ if (!me) return false;
1227
+ try {
1228
+ Promise.resolve(
1229
+ def.hostHandle(makeCtx(), payload, me)
1230
+ ).catch(
1231
+ (err) => error(`multiplayer.match hostHandle('${String(name)}') threw:`, err)
1232
+ );
1233
+ } catch (err) {
1234
+ error(`multiplayer.match hostHandle('${String(name)}') threw:`, err);
1235
+ }
1236
+ return true;
1237
+ }
1238
+ return send(String(name), payload);
1239
+ }
1240
+ function apiBroadcast(name, payloadIn, callerOptions = {}) {
1241
+ if (destroyed || matchState === "aborted" || matchState === "ended") {
1242
+ warn(
1243
+ `multiplayer.match.broadcast('${String(name)}'): match is ${matchState}`
1244
+ );
1245
+ return false;
1246
+ }
1247
+ if (matchId == null) {
1248
+ warn(
1249
+ `multiplayer.match.broadcast('${String(name)}'): match has not started yet`
1250
+ );
1251
+ return false;
1252
+ }
1253
+ if (!localIsHost()) {
1254
+ warn(
1255
+ `multiplayer.match.broadcast('${String(name)}'): peer is not the host`
1256
+ );
1257
+ return false;
1258
+ }
1259
+ const payload = { ...payloadIn, matchId };
1260
+ const def = eventDefFor(String(name));
1261
+ const me = localSelfId() ?? "";
1262
+ maybeApply(String(name), def, payload, me, void 0, false);
1263
+ const retain = callerOptions.retain ?? def?.retain ?? false;
1264
+ let retainKey;
1265
+ if (retain) {
1266
+ if (callerOptions.retainKey) {
1267
+ retainKey = callerOptions.retainKey;
1268
+ } else if (def?.retainKey) {
1269
+ try {
1270
+ retainKey = def.retainKey(payload);
1271
+ } catch (err) {
1272
+ error(
1273
+ `multiplayer.match retainKey('${String(name)}') threw \u2014 using event name:`,
1274
+ err
1275
+ );
1276
+ retainKey = String(name);
1277
+ }
1278
+ } else {
1279
+ retainKey = String(name);
1280
+ }
1281
+ }
1282
+ const sendOptions = retain ? { retain: true, retainKey } : void 0;
1283
+ return broadcast(
1284
+ String(name),
1285
+ payload,
1286
+ sendOptions
1287
+ );
1288
+ }
1289
+ function refreshWaiting() {
1290
+ if (matchId != null) return;
1291
+ const present = localPeers().length;
1292
+ const waiting = present < expectedPeers;
1293
+ options.onWaitingForPeers?.(waiting, present, expectedPeers);
1294
+ }
1295
+ function announceReadyIfWanted() {
1296
+ if (!wantReady) return;
1297
+ if (matchId != null) return;
1298
+ const me = localSelfId();
1299
+ if (!me) return;
1300
+ readyPeerIds.add(me);
1301
+ send(readyEventName, { readyAtMs: Date.now() });
1302
+ if (localIsHost()) void maybeStart();
1303
+ }
1304
+ async function maybeStart() {
1305
+ if (matchId != null || starting) return;
1306
+ if (!localIsHost()) return;
1307
+ const peers = localPeers();
1308
+ if (peers.length < expectedPeers) return;
1309
+ if (!peers.every((p) => readyPeerIds.has(p.peerId))) return;
1310
+ starting = true;
1311
+ setState("starting");
1312
+ try {
1313
+ const built = await options.buildStart(peers);
1314
+ const newMatchId = generateMatchId();
1315
+ const fullPayload = { ...built, matchId: newMatchId };
1316
+ broadcast(startEventName, fullPayload, {
1317
+ retain: true,
1318
+ retainKey: startRetainKey
1319
+ });
1320
+ matchId = newMatchId;
1321
+ setState("active");
1322
+ try {
1323
+ options.onStart(makeCtx(), fullPayload);
1324
+ } catch (err) {
1325
+ error("multiplayer.match onStart threw:", err);
1326
+ }
1327
+ } catch (err) {
1328
+ error("multiplayer.match buildStart threw:", err);
1329
+ setState("waiting");
1330
+ } finally {
1331
+ starting = false;
1332
+ }
1333
+ }
1334
+ function handleStartFrame(msg) {
1335
+ if (destroyed) return;
1336
+ const payload = msg?.payload ?? msg;
1337
+ if (!payload || typeof payload !== "object") return;
1338
+ if (typeof payload.matchId !== "string" || !payload.matchId) return;
1339
+ if (matchId === payload.matchId) return;
1340
+ matchId = payload.matchId;
1341
+ appliedIdKeys.clear();
1342
+ setState("active");
1343
+ const retained = msg?.retained === true;
1344
+ try {
1345
+ options.onStart(makeCtx(retained), payload);
1346
+ } catch (err) {
1347
+ error("multiplayer.match onStart threw:", err);
1348
+ }
1349
+ }
1350
+ function handleReadyFrame(msg) {
1351
+ const fromPeerId = msg?.fromPeerId;
1352
+ if (typeof fromPeerId === "string" && fromPeerId) {
1353
+ readyPeerIds.add(fromPeerId);
1354
+ }
1355
+ if (localIsHost()) void maybeStart();
1356
+ }
1357
+ function handleUserEvent(eventName, msg) {
1358
+ if (destroyed) return;
1359
+ const payload = msg?.payload;
1360
+ if (!payload || typeof payload !== "object") return;
1361
+ if (matchId == null) return;
1362
+ if (typeof payload.matchId !== "string" || payload.matchId !== matchId) {
1363
+ return;
1364
+ }
1365
+ const def = eventDefFor(eventName);
1366
+ const fromPeerId = msg?.fromPeerId ?? "";
1367
+ const seq = msg?.seq;
1368
+ const retained = msg?.retained === true;
1369
+ if (def?.hostHandle && localIsHost() && fromPeerId !== localSelfId() && !retained) {
1370
+ try {
1371
+ Promise.resolve(
1372
+ def.hostHandle(makeCtx(false), payload, fromPeerId)
1373
+ ).catch(
1374
+ (err) => error(
1375
+ `multiplayer.match hostHandle('${eventName}') threw:`,
1376
+ err
1377
+ )
1378
+ );
1379
+ } catch (err) {
1380
+ error(`multiplayer.match hostHandle('${eventName}') threw:`, err);
1381
+ }
1382
+ return;
1383
+ }
1384
+ maybeApply(eventName, def, payload, fromPeerId, seq, retained);
1385
+ }
1386
+ offHandlers.push(
1387
+ on("peer_joined", () => {
1388
+ refreshWaiting();
1389
+ if (localIsHost()) void maybeStart();
1390
+ })
1391
+ );
1392
+ offHandlers.push(
1393
+ on("connected", () => {
1394
+ announceReadyIfWanted();
1395
+ })
1396
+ );
1397
+ offHandlers.push(
1398
+ on("room_joined", () => {
1399
+ refreshWaiting();
1400
+ announceReadyIfWanted();
1401
+ if (localIsHost()) void maybeStart();
1402
+ })
1403
+ );
1404
+ offHandlers.push(
1405
+ on("peer_left", (msg) => {
1406
+ const leftId = msg?.peerId;
1407
+ if (typeof leftId === "string") readyPeerIds.delete(leftId);
1408
+ refreshWaiting();
1409
+ if (matchState === "active" && options.onPeerLeft && leftId) {
1410
+ try {
1411
+ options.onPeerLeft(makeCtx(), leftId);
1412
+ } catch (err) {
1413
+ error("multiplayer.match onPeerLeft threw:", err);
1414
+ }
1415
+ }
1416
+ if (matchId == null && localIsHost()) void maybeStart();
1417
+ })
1418
+ );
1419
+ offHandlers.push(
1420
+ on("disconnected", () => {
1421
+ if (matchState === "active" || matchState === "starting") {
1422
+ abort("disconnected");
1423
+ }
1424
+ })
1425
+ );
1426
+ offHandlers.push(
1427
+ on("room_closed", () => {
1428
+ abort("room_closed");
1429
+ })
1430
+ );
1431
+ offHandlers.push(on(readyEventName, handleReadyFrame));
1432
+ offHandlers.push(on(startEventName, handleStartFrame));
1433
+ for (const eventName of Object.keys(options.events)) {
1434
+ if (eventName === startEventName || eventName === readyEventName) {
1435
+ continue;
1436
+ }
1437
+ offHandlers.push(
1438
+ on(eventName, (msg) => handleUserEvent(eventName, msg))
1439
+ );
1440
+ }
1441
+ function abort(reason) {
1442
+ if (matchState === "aborted" || matchState === "ended") return;
1443
+ setState("aborted");
1444
+ try {
1445
+ options.onAborted?.(reason, { matchId });
1446
+ } catch (err) {
1447
+ error("multiplayer.match onAborted threw:", err);
1448
+ }
1449
+ }
1450
+ refreshWaiting();
1451
+ announceReadyIfWanted();
1452
+ const match = {
1453
+ get state() {
1454
+ return matchState;
1455
+ },
1456
+ get matchId() {
1457
+ return matchId;
1458
+ },
1459
+ intent: apiIntent,
1460
+ broadcast: apiBroadcast,
1461
+ markReady() {
1462
+ wantReady = true;
1463
+ announceReadyIfWanted();
1464
+ },
1465
+ onStateChange(handler) {
1466
+ stateChangeHandlers.add(handler);
1467
+ return () => {
1468
+ stateChangeHandlers.delete(handler);
1469
+ };
1470
+ },
1471
+ async destroy(opts) {
1472
+ if (destroyed) return;
1473
+ destroyed = true;
1474
+ for (const off of offHandlers) {
1475
+ try {
1476
+ off();
1477
+ } catch {
1478
+ }
1479
+ }
1480
+ offHandlers.length = 0;
1481
+ stateChangeHandlers.clear();
1482
+ readyPeerIds.clear();
1483
+ appliedIdKeys.clear();
1484
+ activeMatch = null;
1485
+ setState("ended");
1486
+ if (opts?.leaveRoom) {
1487
+ await leaveRoom("match_ended");
1488
+ }
1489
+ }
1490
+ };
1491
+ activeMatch = match;
1492
+ return match;
1493
+ }
1494
+ function assignSeats(peers, seatNames, hostPeerId) {
1495
+ const peerIds = peers.map((p) => p.peerId).filter(Boolean);
1496
+ const ordered = [];
1497
+ if (hostPeerId && peerIds.includes(hostPeerId)) {
1498
+ ordered.push(hostPeerId);
1499
+ }
1500
+ for (const id of [...peerIds].sort()) {
1501
+ if (id !== hostPeerId) ordered.push(id);
1502
+ }
1503
+ const bySeat = {};
1504
+ const byPeer = {};
1505
+ for (let i = 0; i < ordered.length; i++) {
1506
+ const seat = i < seatNames.length ? seatNames[i] : null;
1507
+ if (seat != null) bySeat[seat] = ordered[i];
1508
+ byPeer[ordered[i]] = seat;
1509
+ }
1510
+ return { bySeat, byPeer };
1511
+ }
1512
+ function waitForPeers(n, timeoutMs) {
1513
+ return new Promise((resolve, reject) => {
1514
+ let done = false;
1515
+ let timer = null;
1516
+ let offJoined = null;
1517
+ let offJoinedSystem = null;
1518
+ function cleanup() {
1519
+ done = true;
1520
+ if (timer != null) clearTimeout(timer);
1521
+ offJoined?.();
1522
+ offJoinedSystem?.();
1523
+ }
1524
+ function check() {
1525
+ if (done) return true;
1526
+ const peers = getPeers();
1527
+ if (peers.length >= n) {
1528
+ cleanup();
1529
+ resolve(peers);
1530
+ return true;
1531
+ }
1532
+ return false;
1533
+ }
1534
+ if (check()) return;
1535
+ offJoined = on("peer_joined", () => check());
1536
+ offJoinedSystem = on("room_joined", () => check());
1537
+ if (timeoutMs && timeoutMs > 0) {
1538
+ timer = setTimeout(() => {
1539
+ if (done) return;
1540
+ cleanup();
1541
+ reject(new Error("waitForPeers: timeout"));
1542
+ }, timeoutMs);
1543
+ }
1544
+ });
1545
+ }
1546
+
1101
1547
  // src/main.ts
1102
1548
  function createSdk() {
1103
1549
  return {
@@ -1195,7 +1641,10 @@
1195
1641
  getRole,
1196
1642
  isHost,
1197
1643
  isViewer,
1198
- selfId
1644
+ selfId,
1645
+ match: createMatch,
1646
+ assignSeats,
1647
+ waitForPeers
1199
1648
  }
1200
1649
  };
1201
1650
  }