@ksaa-nlp/gamehub-sdk 0.6.1 → 0.7.0

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,72 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0 — 2026-04-30
4
+
5
+ Three Tier-1 transport features completing the multiplayer roadmap: targeted send, per-peer seq continuity across reconnect, and a server-clock helper. All three are additive — existing `multiplayer.send` / `broadcast` / `match` calls keep their current semantics.
6
+
7
+ ### Targeted send (`SendOptions.to`)
8
+
9
+ `multiplayer.send(name, payload, { to: peerId | peerId[] })` and the matching `MatchBroadcastOptions.to` route a frame to a specific subset of peers in the room instead of fanning out. Use cases: a private host→guest hint, per-player power-up effects that shouldn't leak to a spectator, host correcting one guest's view.
10
+
11
+ ```ts
12
+ sdk.multiplayer.send('private_hint', payload, { to: guestPeerId });
13
+ ctx.broadcast('reveal_for_winner', payload, { to: [winnerId] });
14
+ ```
15
+
16
+ Server-side semantics:
17
+ - The sender does NOT receive their own frame as an echo unless their id is explicitly in the `to` list.
18
+ - Unknown peerIds are silently skipped (no error frame).
19
+ - `to` and `retain` are mutually exclusive — a targeted frame is per-definition not a room-wide snapshot, so the server drops `retain` when `to` is set. The match-API mirrors this client-side and also skips the local `apply` step on targeted broadcasts (targeting means "send state to specific peers", not "this is the new authoritative state").
20
+
21
+ ### Per-peer seq continuity across reconnect
22
+
23
+ A peer's outbound `seq` counter now survives a disconnect+reconnect within `RECONNECT_GRACE_MS` (30s). Previously the counter reset to 0 on every new socket because it lived in `wsMeta` (a `WeakMap` keyed by socket); a reconnecting peer's first new message would have `seq=1`, which the SDK's `mpLastSeqByPeer` dedupe at the receiver would compare against the last value seen pre-disconnect (e.g. `seq=12`) and silently drop.
24
+
25
+ Server changes that fix this:
26
+ - The `multiplayer_peers` collection now stores `seq` per peer doc.
27
+ - `storePeer()` (called on every connect) reads the existing seq and seeds `wsMeta.state.seq` from it before any message is processed.
28
+ - The message handler captures `state.seq` into a local immediately after incrementing, then awaits `touchPeer(peerId, seq)` (persists seq + lastSeenAt) BEFORE publishing — so a crash between persist and publish leaves the DB at-least-as-recent as what receivers observed.
29
+ - The `ws.on('close')` handler no longer deletes the peer doc; it sets `lastSeenAt: 0` so `getPeers` immediately filters the peer out, but the `seq` value stays around for a reconnect to pick up.
30
+
31
+ Race fix as part of this: previously, three concurrent message handlers on the same socket could yield on `await touchPeer` interleaved, all read `state.seq` at the end, and emit identical seqs. The seq is now snapshotted into a local before any `await`.
32
+
33
+ ### Server clock helper (`multiplayer.serverNow()`)
34
+
35
+ `sdk.multiplayer.serverNow()` returns a server-anchored timestamp in milliseconds. Use it — not `Date.now()` — for any timer math compared across peers (countdowns, deadlines, replay times). Peer device clocks routinely drift seconds apart; without this, two peers running the same `maxTimeSec - (Date.now() - serverStartMs)/1000` countdown can show different remaining times.
36
+
37
+ Implementation: every incoming frame's `sentAt - Date.now()` becomes a sample. The first sample sets the offset wholesale; subsequent samples blend via a 0.85 / 0.15 EMA so a single high-latency packet doesn't yank the clock around. Retained replays are excluded from offset updates (their `sentAt` is when the host originally pinned them, not the current network).
38
+
39
+ ```ts
40
+ // Old: brittle across clock skew
41
+ const remaining = maxTimeSec - (Date.now() - serverStartMs) / 1000;
42
+
43
+ // New: stable
44
+ const remaining = maxTimeSec - (sdk.multiplayer.serverNow() - serverStartMs) / 1000;
45
+ ```
46
+
47
+ Returns `Date.now()` exactly until the first frame arrives, so games can call it during boot without special-casing.
48
+
49
+ ### Verified
50
+
51
+ - 23/23 realtime tests green (14 unit + 9 integration). New tests cover: targeted single-peer delivery, targeted multi-peer delivery, targeted-strips-retain, seq continuity across reconnect, peer-doc preserved on disconnect.
52
+ - SDK type-check + build clean.
53
+
54
+ ### Wire format
55
+
56
+ Strictly additive on the wire. Inbound (client → server):
57
+ - `to?: string | string[]` — targeted recipients.
58
+
59
+ Server → client: unchanged. The server-stamped `sentAt` was already on every frame; v0.7 just consumes it on the SDK side.
60
+
61
+ ### Unchanged
62
+
63
+ - `Sdk` interface beyond the new `multiplayer.serverNow()` method and the new `to` field on `SendOptions` / `MatchBroadcastOptions` (both optional).
64
+ - `BootstrapData`, `MpMessage`.
65
+ - All other multiplayer methods.
66
+ - The match API — adding retain/seq features here doesn't touch its semantics.
67
+
68
+ ---
69
+
3
70
  ## 0.6.1 — 2026-04-30
4
71
 
5
72
  Three small, additive fixes that surfaced while porting link-game to the `multiplayer.match` API.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // src/constants.ts
4
- var SDK_VERSION = "0.6.1";
4
+ var SDK_VERSION = "0.7.0";
5
5
  var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
6
  var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
7
  var MP_MAX_RECONNECT_ATTEMPTS = 5;
@@ -52,7 +52,9 @@
52
52
  mpPeers: /* @__PURE__ */ new Map(),
53
53
  mpHandlers: /* @__PURE__ */ new Map(),
54
54
  mpLastSeqByPeer: /* @__PURE__ */ new Map(),
55
- mpViewerOverride: false
55
+ mpViewerOverride: false,
56
+ mpServerOffsetMs: 0,
57
+ mpServerOffsetSamples: 0
56
58
  };
57
59
 
58
60
  // src/utils.ts
@@ -394,6 +396,15 @@
394
396
  return;
395
397
  }
396
398
  if (!message || !message.type) return;
399
+ if (typeof message.sentAt === "number" && message.retained !== true) {
400
+ const sample = message.sentAt - Date.now();
401
+ if (state.mpServerOffsetSamples === 0) {
402
+ state.mpServerOffsetMs = sample;
403
+ } else {
404
+ state.mpServerOffsetMs = 0.85 * state.mpServerOffsetMs + 0.15 * sample;
405
+ }
406
+ state.mpServerOffsetSamples += 1;
407
+ }
397
408
  if (message.type === "system") {
398
409
  if (message.eventName === "room_joined") {
399
410
  state.mpPeers.clear();
@@ -693,6 +704,9 @@
693
704
  const s = state.mpSocket;
694
705
  return Boolean(s && s.readyState === WebSocket.OPEN);
695
706
  }
707
+ function serverNow() {
708
+ return Date.now() + state.mpServerOffsetMs;
709
+ }
696
710
 
697
711
  // src/match-context.ts
698
712
  async function fetchMatchContext() {
@@ -1258,9 +1272,12 @@
1258
1272
  }
1259
1273
  const payload = { ...payloadIn, matchId };
1260
1274
  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;
1275
+ const targeted = callerOptions.to !== void 0;
1276
+ if (!targeted) {
1277
+ const me = localSelfId() ?? "";
1278
+ maybeApply(String(name), def, payload, me, void 0, false);
1279
+ }
1280
+ const retain = !targeted && (callerOptions.retain ?? def?.retain ?? false);
1264
1281
  let retainKey;
1265
1282
  if (retain) {
1266
1283
  if (callerOptions.retainKey) {
@@ -1279,11 +1296,18 @@
1279
1296
  retainKey = String(name);
1280
1297
  }
1281
1298
  }
1282
- const sendOptions = retain ? { retain: true, retainKey } : void 0;
1299
+ const sendOptions = {};
1300
+ if (retain) {
1301
+ sendOptions.retain = true;
1302
+ sendOptions.retainKey = retainKey;
1303
+ }
1304
+ if (targeted) {
1305
+ sendOptions.to = callerOptions.to;
1306
+ }
1283
1307
  return broadcast(
1284
1308
  String(name),
1285
1309
  payload,
1286
- sendOptions
1310
+ Object.keys(sendOptions).length ? sendOptions : void 0
1287
1311
  );
1288
1312
  }
1289
1313
  function refreshWaiting() {
@@ -1642,6 +1666,7 @@
1642
1666
  isHost,
1643
1667
  isViewer,
1644
1668
  selfId,
1669
+ serverNow,
1645
1670
  match: createMatch,
1646
1671
  assignSeats,
1647
1672
  waitForPeers