@hadoku/game-ui 0.1.253 → 0.1.255

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.
@@ -13,7 +13,7 @@
13
13
  *
14
14
  * So this component renders the one thing the app was not saying. It holds no
15
15
  * state and starts no timers: it takes a `ConnectionState` computed by
16
- * `draft/connection.ts` from facts the driver already tracks, which is why the
16
+ * `connectionState` (`./connection-state.ts`) from facts the driver already tracks, which is why the
17
17
  * banner can be tested without a socket and cannot drift from what the socket
18
18
  * is actually doing.
19
19
  *
@@ -14,7 +14,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
14
14
  *
15
15
  * So this component renders the one thing the app was not saying. It holds no
16
16
  * state and starts no timers: it takes a `ConnectionState` computed by
17
- * `draft/connection.ts` from facts the driver already tracks, which is why the
17
+ * `connectionState` (`./connection-state.ts`) from facts the driver already tracks, which is why the
18
18
  * banner can be tested without a socket and cannot drift from what the socket
19
19
  * is actually doing.
20
20
  *
@@ -1,3 +1,4 @@
1
+ import type { SeqVerdict } from '@wolffm/rooms-protocol';
1
2
  export type ConnectionPhase =
2
3
  /** No connection has ever been established. */
3
4
  'connecting'
@@ -32,3 +33,25 @@ export interface ConnectionState {
32
33
  }
33
34
  /** Whether the banner has anything worth showing. `live` is silence. */
34
35
  export declare function isWorthShowing(state: ConnectionState): boolean;
36
+ /** Everything a phase is decided from. All of it already exists on the driver. */
37
+ export interface ConnectionFacts {
38
+ connected: boolean;
39
+ /** Whether a connection has EVER been established. Distinguishes first-connect from a drop. */
40
+ everConnected: boolean;
41
+ /** The drop followed the server's own restart notice and is inside its quiet window. */
42
+ serverUpdating: boolean;
43
+ /** Join messages sent. `> 1` means at least one reconnect has happened. */
44
+ joins: number;
45
+ /** Payloads applied, in total. */
46
+ applied: number;
47
+ /** `applied` as it stood when the most recent RE-join went out. */
48
+ appliedAtLastJoin: number;
49
+ /** A resync request is outstanding and unanswered. */
50
+ resyncPending: boolean;
51
+ /** The seat this client holds, or null while spectating or unseated. */
52
+ seatId: number | null;
53
+ /** The verdict on the most recent envelope. Diagnostic only. */
54
+ lastVerdict: SeqVerdict | null;
55
+ }
56
+ /** What the connection is doing, and what to say about it. */
57
+ export declare function connectionState(facts: ConnectionFacts): ConnectionState;
@@ -1,5 +1,93 @@
1
- /* What a connection is doing, as `./ConnectionBanner.tsx` shows it; a game computes it from its socket (`../draft/connection.ts`). */
1
+ /*
2
+ * What a connection is doing, as `./ConnectionBanner.tsx` shows it: `connectionState` over facts a
3
+ * driver already tracks (`../track-connection.ts`), never a second copy of "are we connected".
4
+ *
5
+ * ## The one derived counter
6
+ *
7
+ * Telling "reconnected, waiting" from "reconnected, back in business" needs to
8
+ * know whether a payload has landed SINCE the re-join, which no single counter
9
+ * answers. `appliedAtLastJoin` is `stats.applied` sampled when the re-join goes
10
+ * out; the difference is the answer. It is one number in the driver rather than
11
+ * a timer in a component, because a timer makes the banner untestable and lies
12
+ * on a slow connection.
13
+ *
14
+ * `recovered` is deliberately BOUNDED to the first payload after the re-join.
15
+ * An unbounded one would leave "Reconnected" on screen for the remaining forty
16
+ * minutes of the draft, which is noise, and noise is what gets banners ignored.
17
+ */
2
18
  /** Whether the banner has anything worth showing. `live` is silence. */
3
19
  export function isWorthShowing(state) {
4
20
  return state.phase !== 'live';
5
21
  }
22
+ /** How many payloads after a re-join still count as "recovered". */
23
+ const RECOVERY_WINDOW = 1;
24
+ function seatPhrase(seatId) {
25
+ return seatId === null ? 'Your place' : `Seat ${seatId}`;
26
+ }
27
+ /** What the connection is doing, and what to say about it. */
28
+ export function connectionState(facts) {
29
+ const seated = facts.seatId !== null;
30
+ if (!facts.connected && !facts.everConnected) {
31
+ return {
32
+ phase: 'connecting',
33
+ seatHeld: false,
34
+ stalled: true,
35
+ label: 'Connecting',
36
+ detail: 'Joining…',
37
+ };
38
+ }
39
+ if (!facts.connected && facts.serverUpdating) {
40
+ return {
41
+ phase: 'updating',
42
+ seatHeld: seated,
43
+ stalled: true,
44
+ label: 'Updating…',
45
+ detail: seated ? 'Server updating — seat held.' : 'Server updating.',
46
+ };
47
+ }
48
+ if (!facts.connected) {
49
+ return {
50
+ phase: 'offline',
51
+ seatHeld: seated,
52
+ stalled: true,
53
+ label: seated ? `${seatPhrase(facts.seatId)} is held for you` : 'Disconnected',
54
+ detail: seated ? 'Connection dropped — seat held. Reconnecting.' : 'The connection dropped. Reconnecting.',
55
+ };
56
+ }
57
+ if (facts.resyncPending) {
58
+ return {
59
+ phase: 'resyncing',
60
+ seatHeld: false,
61
+ stalled: true,
62
+ label: 'Catching up',
63
+ detail: 'Resyncing.',
64
+ };
65
+ }
66
+ const sinceJoin = facts.applied - facts.appliedAtLastJoin;
67
+ const reconnected = facts.joins > 1;
68
+ if (reconnected && sinceJoin <= 0) {
69
+ return {
70
+ phase: 'reconnecting',
71
+ seatHeld: false,
72
+ stalled: true,
73
+ label: 'Reconnected — waiting for the table',
74
+ detail: 'Reconnected — resyncing.',
75
+ };
76
+ }
77
+ if (reconnected && sinceJoin <= RECOVERY_WINDOW) {
78
+ return {
79
+ phase: 'recovered',
80
+ seatHeld: false,
81
+ stalled: false,
82
+ label: seated ? `Back in ${seatPhrase(facts.seatId).toLowerCase()}` : 'Back',
83
+ detail: 'Recovered.',
84
+ };
85
+ }
86
+ return {
87
+ phase: 'live',
88
+ seatHeld: false,
89
+ stalled: false,
90
+ label: 'Live',
91
+ detail: 'Connected.',
92
+ };
93
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A board's trouble, live or replayed, told to the server log as a page event (`kind: 'trouble'`)
3
+ * over HTTP: the socket is what is in trouble, so it cannot carry it. The server keeps a page event's
4
+ * facts flat and short, so the facts are made so here: a long error arrives clipped, never refused.
5
+ */
6
+ import { type PageEvent } from '@wolffm/platform-wire/telemetry';
7
+ import { type Fetch } from './http.js';
8
+ export type TroublePage = Extract<PageEvent['page'], 'match' | 'replay'>;
9
+ /** Who reports: the match it is about, when there is one, and the page's own build. */
10
+ export type TroubleSource = {
11
+ matchId: string | null;
12
+ ui: string;
13
+ };
14
+ /**
15
+ * `what`, the match, the build and then `detail`'s facts, as a page event's `data`: at most its field
16
+ * count, names clipped, an absent fact left out. The first three go first so no detail crowds them out.
17
+ */
18
+ export declare function troubleData(what: string, detail: Record<string, unknown>, source: TroubleSource): PageEvent['data'];
19
+ /** Posts `what` and its facts to the page-event route; the page shows nothing either way. */
20
+ export declare function sendPageTrouble(page: TroublePage, what: string, detail: Record<string, unknown>, source: TroubleSource, fetchImpl?: Fetch): void;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A board's trouble, live or replayed, told to the server log as a page event (`kind: 'trouble'`)
3
+ * over HTTP: the socket is what is in trouble, so it cannot carry it. The server keeps a page event's
4
+ * facts flat and short, so the facts are made so here: a long error arrives clipped, never refused.
5
+ */
6
+ import { CLIENT_FIELDS_MAX, CLIENT_KEY_MAX, CLIENT_TEXT_MAX, PAGE_EVENT_PATH } from '@wolffm/platform-wire/telemetry';
7
+ import { apiUrl, pageFetch, sendJson } from "./http.js";
8
+ /** One fact as a page event holds it: a number or a flag as it is, anything else as its text, clipped. */
9
+ function scalar(value) {
10
+ if (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))
11
+ return value;
12
+ const text = typeof value === 'string' ? value : (JSON.stringify(value) ?? String(value));
13
+ return text.slice(0, CLIENT_TEXT_MAX);
14
+ }
15
+ /**
16
+ * `what`, the match, the build and then `detail`'s facts, as a page event's `data`: at most its field
17
+ * count, names clipped, an absent fact left out. The first three go first so no detail crowds them out.
18
+ */
19
+ export function troubleData(what, detail, source) {
20
+ const facts = [['what', what], ['matchId', source.matchId], ['ui', source.ui], ...Object.entries(detail)];
21
+ const data = new Map();
22
+ for (const [name, value] of facts) {
23
+ const key = name.slice(0, CLIENT_KEY_MAX);
24
+ if (data.size >= CLIENT_FIELDS_MAX)
25
+ break;
26
+ if (key === '' || data.has(key) || value === null || value === undefined)
27
+ continue;
28
+ data.set(key, scalar(value));
29
+ }
30
+ return Object.fromEntries(data);
31
+ }
32
+ /** Posts `what` and its facts to the page-event route; the page shows nothing either way. */
33
+ export function sendPageTrouble(page, what, detail, source, fetchImpl = pageFetch) {
34
+ const event = { page, kind: 'trouble', data: troubleData(what, detail, source) };
35
+ void sendJson(apiUrl(PAGE_EVENT_PATH), 'POST', event, fetchImpl, { keepalive: true }).catch((err) => console.warn(`[${page}] could not report`, what, err));
36
+ }
@@ -1,4 +1,5 @@
1
1
  import type { MatchChannel } from '@wolffm/rooms-protocol';
2
+ import type { ConnectionFacts } from '../components/connection-state.js';
2
3
  /**
3
4
  * A `MatchChannel` plus the host's own word that the match ended — the room's, never the
4
5
  * bundle's: `winners` are the seat numbers of the `{ t: 'over', winners }` that ended it (the
@@ -14,6 +15,8 @@ export interface RelayChannel extends MatchChannel {
14
15
  * match is under way (the first message this channel sends or hears after that).
15
16
  */
16
17
  onResult(handler: (winners: readonly number[] | null) => void): () => void;
18
+ /** What the connection is doing, told on every change: a drop, a planned restart, a rejoin and its answer. */
19
+ onConnection(handler: (facts: ConnectionFacts) => void): () => void;
17
20
  }
18
21
  export interface RelayChannelOptions {
19
22
  /** The server's origin, e.g. `http://localhost:9008`. Omitted: same origin (production). */
@@ -11,11 +11,12 @@
11
11
  *
12
12
  * Ordering and at-most-once delivery are `runtimes/relay.ts`'s `RelaySession`'s own guarantees;
13
13
  * this file adds nothing to either — it only opens the connection, joins, rejoins on every
14
- * reconnect and after every match's end, and relays `relay:message` both ways. A watcher's own `send` is a silent no-op from
14
+ * reconnect and after every match's end, relays `relay:message` both ways, and says what its connection is doing. A watcher's own `send` is a silent no-op from
15
15
  * out here too, but only because the SERVER drops it without an error — nothing here tracks
16
16
  * whether this socket holds a seat.
17
17
  */
18
18
  import { defaultSocketPath, openSocket, socketOptions } from "../room/socket-options.js";
19
+ import { trackConnection } from "../track-connection.js";
19
20
  /**
20
21
  * Mirrors `packages/game-server/src/play/relay-socket.ts`'s own `RELAY_EVENTS`. The client has no package
21
22
  * of the server's to import these from (the server is not a dependency of the UI bundle), so the
@@ -39,7 +40,9 @@ export function openRelayChannel(matchId, options = {}) {
39
40
  const handlers = new Set();
40
41
  const endedHandlers = new Set();
41
42
  const resultHandlers = new Set();
43
+ const connectionHandlers = new Set();
42
44
  let closed = false;
45
+ let rejoining = false;
43
46
  /** A result is shown: the next message sent or heard clears it. */
44
47
  let showing = false;
45
48
  const tellResult = (winners) => {
@@ -56,14 +59,35 @@ export function openRelayChannel(matchId, options = {}) {
56
59
  return;
57
60
  // A match that ended before this join answers with its result (`relay-socket.ts`'s ack).
58
61
  socket.emit(RELAY_EVENTS.join, { matchId }, (ack) => {
59
- if (closed || ack?.ok !== true || ack.ended === undefined)
62
+ if (closed || ack?.ok !== true)
60
63
  return;
61
- tellResult(winnersOf(ack.ended.winners));
64
+ const answered = rejoining;
65
+ rejoining = false;
66
+ if (answered)
67
+ tellConnection();
68
+ if (ack.ended !== undefined)
69
+ tellResult(winnersOf(ack.ended.winners));
62
70
  });
63
71
  };
64
- // A fresh connection joins once it opens; a later reconnect (a dropped network, a deploy) joins
65
- // again on the new one — `relay-socket.ts` treats that exactly like a brand new peer.
66
- socket.on('connect', join);
72
+ // The first join goes out at once (socket.io holds it until the connection opens); a reconnect (a
73
+ // dropped network, a deploy) joins again on the new one, as a brand new peer to `relay-socket.ts`.
74
+ const connection = trackConnection(socket, {
75
+ onRejoin: () => {
76
+ rejoining = true;
77
+ join();
78
+ },
79
+ });
80
+ // With no snapshot to wait for, a rejoin (`rejoining`: sent on a new connection, not yet answered) is
81
+ // the whole of coming back, so no "back" line stays over a quiet room. The seats are the room's to show.
82
+ const tellConnection = () => {
83
+ if (closed)
84
+ return;
85
+ const facts = { connected: connection.connected, everConnected: connection.everConnected, serverUpdating: connection.serverUpdating, joins: rejoining ? connection.joins : 1, applied: 0, appliedAtLastJoin: 0, resyncPending: false, seatId: null, lastVerdict: null };
86
+ for (const handler of [...connectionHandlers])
87
+ handler(facts);
88
+ };
89
+ connection.subscribe(tellConnection);
90
+ join();
67
91
  socket.on(RELAY_EVENTS.message, (msg) => {
68
92
  if (closed)
69
93
  return;
@@ -97,6 +121,12 @@ export function openRelayChannel(matchId, options = {}) {
97
121
  resultHandlers.add(handler);
98
122
  return () => resultHandlers.delete(handler);
99
123
  },
124
+ onConnection(handler) {
125
+ if (closed)
126
+ return () => { };
127
+ connectionHandlers.add(handler);
128
+ return () => connectionHandlers.delete(handler);
129
+ },
100
130
  send(msg) {
101
131
  if (closed)
102
132
  return;
@@ -116,6 +146,7 @@ export function openRelayChannel(matchId, options = {}) {
116
146
  handlers.clear();
117
147
  endedHandlers.clear();
118
148
  resultHandlers.clear();
149
+ connectionHandlers.clear();
119
150
  socket.disconnect();
120
151
  },
121
152
  };
@@ -0,0 +1,14 @@
1
+ import { watchRestart } from './restart-notice.js';
2
+ export type TrackedConnection = ReturnType<typeof trackConnection>;
3
+ export declare function trackConnection(transport: Parameters<typeof watchRestart>[0], { onRejoin }?: {
4
+ onRejoin?: () => void;
5
+ }): {
6
+ connected: boolean;
7
+ everConnected: boolean;
8
+ /** Dropped by a planned restart, inside its quiet window (`./restart-notice.ts`). */
9
+ serverUpdating: boolean;
10
+ /** 1 for the caller's first join, one more for each rejoin. */
11
+ joins: number;
12
+ /** Told after every change, the rejoin already sent. Returns the unsubscribe. */
13
+ subscribe(fn: () => void): () => void;
14
+ };
@@ -0,0 +1,41 @@
1
+ /* One socket's connection, as the facts a connection banner is drawn from (`./components/connection-state.ts`). The caller joins
2
+ * once at the start (socket.io holds an emit until the connection opens) and again in `onRejoin`, on every connect after the first. */
3
+ import { watchRestart } from "./restart-notice.js";
4
+ export function trackConnection(transport, { onRejoin } = {}) {
5
+ const listeners = new Set();
6
+ const tell = () => listeners.forEach((fn) => fn());
7
+ const state = {
8
+ connected: false,
9
+ everConnected: false,
10
+ /** Dropped by a planned restart, inside its quiet window (`./restart-notice.ts`). */
11
+ serverUpdating: false,
12
+ /** 1 for the caller's first join, one more for each rejoin. */
13
+ joins: 1,
14
+ /** Told after every change, the rejoin already sent. Returns the unsubscribe. */
15
+ subscribe(fn) {
16
+ listeners.add(fn);
17
+ return () => void listeners.delete(fn);
18
+ },
19
+ };
20
+ // Registered first, so a connect or a drop has settled `updating` before its own handler below
21
+ // tells anyone; only the quiet window running out is told from here.
22
+ watchRestart(transport, (updating, back) => {
23
+ state.serverUpdating = updating;
24
+ if (!state.connected && !back)
25
+ tell();
26
+ });
27
+ transport.on('connect', () => {
28
+ const rejoin = state.everConnected;
29
+ state.connected = state.everConnected = true;
30
+ if (rejoin) {
31
+ state.joins += 1;
32
+ onRejoin?.();
33
+ }
34
+ tell();
35
+ });
36
+ transport.on('disconnect', () => {
37
+ state.connected = false;
38
+ tell();
39
+ });
40
+ return state;
41
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-ui",
3
- "version": "0.1.253",
4
- "gitHead": "200c3dd1e6887b83b9d7572babb84ffbd8f38ec9",
3
+ "version": "0.1.255",
4
+ "gitHead": "e724376d6b5ef49938c93bc733dfb9e260f57d5f",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The browser parts any hosted game shares, above ui-shell: the room shell and session, seats and looks, the room route, the front page's generic pieces (gate, polls, gallery, patch notes), the bundle slot and relay channel a game's client mounts in, settings and trim screens, the HTTP and socket helpers, and the generic components (modal, popover, avatar, action button, radio cards). Knows no game; Magic's UI (games/magic/ui) plugs in, composed by the site (apps/ui). MIT; imports only react, react-dom, socket.io-client, @wolffm/* and the platform packages.",
@@ -53,8 +53,8 @@
53
53
  "react-dom": "^19.2.8"
54
54
  },
55
55
  "dependencies": {
56
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.257",
57
- "@wolffm/ui-shell": "npm:@hadoku/ui-shell@0.1.257",
56
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.259",
57
+ "@wolffm/ui-shell": "npm:@hadoku/ui-shell@0.1.259",
58
58
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.4",
59
59
  "@wolffm/rooms-client": "npm:@hadoku/rooms-client@^0.45.158",
60
60
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.158",