@diffenderfer-games/hub 0.0.0-stage → 2.0.0-next.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.
Files changed (164) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +191 -3
  4. package/dist/auto.d.ts +36 -0
  5. package/dist/auto.d.ts.map +1 -0
  6. package/dist/auto.js +27 -0
  7. package/dist/auto.js.map +1 -0
  8. package/dist/daily.d.ts +2 -0
  9. package/dist/daily.js +1 -0
  10. package/dist/doctor/cli.mjs +268 -0
  11. package/dist/doctor/cli.mjs.map +1 -0
  12. package/dist/index.d.ts +12 -0
  13. package/dist/index.js +6 -0
  14. package/dist/input.d.ts +2 -0
  15. package/dist/input.js +3 -0
  16. package/dist/mp.d.ts +4 -0
  17. package/dist/mp.js +1 -0
  18. package/dist/race.d.ts +4 -0
  19. package/dist/race.js +1 -0
  20. package/dist/rooms.d.ts +4 -0
  21. package/dist/rooms.js +1 -0
  22. package/dist/shared/bridge.js +209 -0
  23. package/dist/shared/bridge.js.map +1 -0
  24. package/dist/shared/client-version.gen.js +7 -0
  25. package/dist/shared/client-version.gen.js.map +1 -0
  26. package/dist/shared/daily.d.ts +123 -0
  27. package/dist/shared/daily.d.ts.map +1 -0
  28. package/dist/shared/daily.js +191 -0
  29. package/dist/shared/daily.js.map +1 -0
  30. package/dist/shared/dom.js +48 -0
  31. package/dist/shared/dom.js.map +1 -0
  32. package/dist/shared/globals.js +102 -0
  33. package/dist/shared/globals.js.map +1 -0
  34. package/dist/shared/index.d.ts +706 -0
  35. package/dist/shared/index.d.ts.map +1 -0
  36. package/dist/shared/input.d.ts +730 -0
  37. package/dist/shared/input.d.ts.map +1 -0
  38. package/dist/shared/input.js +2718 -0
  39. package/dist/shared/input.js.map +1 -0
  40. package/dist/shared/latest-state.js +17 -0
  41. package/dist/shared/latest-state.js.map +1 -0
  42. package/dist/shared/mp.d.ts +9 -0
  43. package/dist/shared/mp.d.ts.map +1 -0
  44. package/dist/shared/mp.js +30 -0
  45. package/dist/shared/mp.js.map +1 -0
  46. package/dist/shared/multiplayer-types.d.ts +47 -0
  47. package/dist/shared/multiplayer-types.d.ts.map +1 -0
  48. package/dist/shared/page-stack.js +207 -0
  49. package/dist/shared/page-stack.js.map +1 -0
  50. package/dist/shared/race-types.d.ts +126 -0
  51. package/dist/shared/race-types.d.ts.map +1 -0
  52. package/dist/shared/race.d.ts +9 -0
  53. package/dist/shared/race.d.ts.map +1 -0
  54. package/dist/shared/race.js +53 -0
  55. package/dist/shared/race.js.map +1 -0
  56. package/dist/shared/room-types.d.ts +125 -0
  57. package/dist/shared/room-types.d.ts.map +1 -0
  58. package/dist/shared/rooms.d.ts +9 -0
  59. package/dist/shared/rooms.d.ts.map +1 -0
  60. package/dist/shared/rooms.js +62 -0
  61. package/dist/shared/rooms.js.map +1 -0
  62. package/dist/shared/runtime-opener.js +84 -0
  63. package/dist/shared/runtime-opener.js.map +1 -0
  64. package/dist/shared/social.d.ts +148 -0
  65. package/dist/shared/social.d.ts.map +1 -0
  66. package/dist/shared/social.js +73 -0
  67. package/dist/shared/social.js.map +1 -0
  68. package/dist/shared/src.js +2164 -0
  69. package/dist/shared/src.js.map +1 -0
  70. package/dist/shared/wire-types.d.ts +51 -0
  71. package/dist/shared/wire-types.d.ts.map +1 -0
  72. package/dist/social.d.ts +6 -0
  73. package/dist/social.js +3 -0
  74. package/dist/types.d.ts +1 -0
  75. package/dist/types.js +0 -0
  76. package/package.json +89 -6
  77. package/src/auto.ts +39 -0
  78. package/src/core/connection.ts +299 -0
  79. package/src/core/errors.ts +147 -0
  80. package/src/core/game-data.ts +38 -0
  81. package/src/core/hub-economy.ts +179 -0
  82. package/src/core/hub-progress.ts +205 -0
  83. package/src/core/hub.ts +131 -0
  84. package/src/core/menu-control.ts +61 -0
  85. package/src/core/offline/events.ts +50 -0
  86. package/src/core/offline/favorites.ts +21 -0
  87. package/src/core/offline/local-store.ts +261 -0
  88. package/src/core/offline/queue.ts +171 -0
  89. package/src/core/page.ts +74 -0
  90. package/src/core/rest/endpoint-types.ts +22 -0
  91. package/src/core/rest/rest-client.ts +152 -0
  92. package/src/core/rest/routes.gen.ts +90 -0
  93. package/src/core/storage/json-guards.ts +74 -0
  94. package/src/core/storage/key-value.ts +66 -0
  95. package/src/core/ticket.ts +43 -0
  96. package/src/core/types.ts +134 -0
  97. package/src/core/version/client-version.gen.ts +3 -0
  98. package/src/core/version/hub-version.ts +62 -0
  99. package/src/core/version/semver.ts +97 -0
  100. package/src/daily/daily-system.ts +161 -0
  101. package/src/daily/page-daily.ts +36 -0
  102. package/src/daily/types.ts +67 -0
  103. package/src/daily.ts +10 -0
  104. package/src/doctor/checks.ts +78 -0
  105. package/src/doctor/cli.ts +98 -0
  106. package/src/doctor/hub-version-fetch.ts +43 -0
  107. package/src/doctor/tsconfig.json +12 -0
  108. package/src/globals.ts +115 -0
  109. package/src/index.ts +50 -0
  110. package/src/input/device-state.ts +146 -0
  111. package/src/input/edges.ts +55 -0
  112. package/src/input/gamepad.ts +61 -0
  113. package/src/input/input-events.ts +32 -0
  114. package/src/input/input-registry.ts +164 -0
  115. package/src/input/input-system.ts +393 -0
  116. package/src/input/legacy-controls.ts +64 -0
  117. package/src/input/nav-state.ts +191 -0
  118. package/src/input/navigator.ts +171 -0
  119. package/src/input/on-screen-controls.ts +101 -0
  120. package/src/input/page-control.ts +43 -0
  121. package/src/input/page-input.ts +193 -0
  122. package/src/input/player-remaps.ts +77 -0
  123. package/src/input/source-values.ts +116 -0
  124. package/src/input/spatial.ts +47 -0
  125. package/src/input/types.ts +331 -0
  126. package/src/input/zero-config.ts +177 -0
  127. package/src/input.ts +22 -0
  128. package/src/mp.ts +10 -0
  129. package/src/overlay/controls-panel.ts +163 -0
  130. package/src/overlay/dom.ts +46 -0
  131. package/src/overlay/layout-clusters.ts +162 -0
  132. package/src/overlay/layout-geometry.ts +136 -0
  133. package/src/overlay/layout.ts +203 -0
  134. package/src/overlay/listener-scope.ts +23 -0
  135. package/src/overlay/on-screen-keyboard.ts +137 -0
  136. package/src/overlay/overlay.ts +208 -0
  137. package/src/overlay/styles.ts +54 -0
  138. package/src/overlay/virtual-controls.ts +262 -0
  139. package/src/race.ts +10 -0
  140. package/src/realtime/bridge.ts +121 -0
  141. package/src/realtime/cross-bundle.ts +29 -0
  142. package/src/realtime/fallback-notice.ts +48 -0
  143. package/src/realtime/hub-link.ts +65 -0
  144. package/src/realtime/latest-state.ts +33 -0
  145. package/src/realtime/multiplayer-forwarder.ts +28 -0
  146. package/src/realtime/multiplayer-types.ts +52 -0
  147. package/src/realtime/page-runtime.ts +60 -0
  148. package/src/realtime/race-forwarder.ts +59 -0
  149. package/src/realtime/race-types.ts +132 -0
  150. package/src/realtime/room-types.ts +125 -0
  151. package/src/realtime/rooms-forwarder.ts +79 -0
  152. package/src/realtime/runtime-api.ts +49 -0
  153. package/src/realtime/runtime-opener.ts +61 -0
  154. package/src/realtime/social-forwarder.ts +72 -0
  155. package/src/realtime/social-types.ts +78 -0
  156. package/src/realtime/types.ts +53 -0
  157. package/src/realtime/wire-types.ts +72 -0
  158. package/src/rooms.ts +10 -0
  159. package/src/social.ts +18 -0
  160. package/src/types.ts +13 -0
  161. package/src/uistack/page-stack.ts +45 -0
  162. package/src/uistack/play-suspension.ts +82 -0
  163. package/src/uistack/types.ts +76 -0
  164. package/src/uistack/ui-stack.ts +144 -0
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Finding the social runtime's realtime API on the page. The runtime owns the
3
+ * `rt` singleton (plan §4.4): it registers on `window.__DG__.rt`, and older
4
+ * runtimes only set the v1 name `window.__HUB_RT__`.
5
+ */
6
+ import { LEGACY_GLOBAL_NAMES } from '../globals';
7
+ import { hasMethods, isObject, readField } from './cross-bundle';
8
+ import type { RealtimeApi } from './runtime-api';
9
+ import { REALTIME_SINGLETON_API } from './runtime-api';
10
+
11
+ /** Whether `candidate` looks like a {@link RealtimeApi} (any bundle's). */
12
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: the runtime is another bundle
13
+ export function isRealtimeApi(candidate: unknown): candidate is RealtimeApi {
14
+ return typeof readField(candidate, 'version') === 'number'
15
+ && hasMethods(readField(candidate, 'presence'), ['set', 'clear'])
16
+ && hasMethods(readField(candidate, 'social'), ['openPlayer', 'friends', 'counts', 'chatMode', 'on'])
17
+ && hasMethods(readField(candidate, 'mp'), ['onLaunch', 'onJoinInfo', 'invite', 'setBusy', 'party'])
18
+ && hasMethods(readField(candidate, 'rooms'), ['create', 'join', 'list'])
19
+ && hasMethods(readField(candidate, 'notify'), ['setQuiet']);
20
+ }
21
+
22
+ let hasWarnedAboutApi = false;
23
+
24
+ /** Warn once when the runtime registered a different shape number than this client knows. */
25
+ function warnOnApiMismatch(registeredApi: number): void {
26
+ if (registeredApi === REALTIME_SINGLETON_API || hasWarnedAboutApi) {
27
+ return;
28
+ }
29
+ hasWarnedAboutApi = true;
30
+ // eslint-disable-next-line no-console -- the plan's one-time warning to the game developer, with the fix
31
+ console.warn(`[hub] this page's social runtime speaks realtime api ${String(registeredApi)}, this client api ${String(REALTIME_SINGLETON_API)}. Fix: npm update @diffenderfer-games/hub`);
32
+ }
33
+
34
+ /** The page's realtime API if the runtime has loaded, else `null`. */
35
+ export function findRealtimeApi(): RealtimeApi | null {
36
+ if (typeof window === 'undefined') {
37
+ return null;
38
+ }
39
+ const registered = window.__DG__?.rt;
40
+ if (registered !== undefined && isRealtimeApi(registered.instance)) {
41
+ warnOnApiMismatch(registered.api);
42
+ return registered.instance;
43
+ }
44
+ const legacy = window[LEGACY_GLOBAL_NAMES.rt];
45
+ return isRealtimeApi(legacy) ? legacy : null;
46
+ }
47
+
48
+ /** Whether the hub injected this page (`window.__HUB__`); without it the runtime can never arrive. */
49
+ export function isHubInjectedPage(): boolean {
50
+ return typeof window !== 'undefined' && isObject(readField(window, '__HUB__'));
51
+ }
52
+
53
+ /** Why the social runtime failed to load on this page (set by the menu), or `''`. */
54
+ export function readRuntimeFailure(): string {
55
+ if (typeof window === 'undefined') {
56
+ return '';
57
+ }
58
+ const failure = readField(window, '__HUB_RT_ERROR__');
59
+ return typeof failure === 'string' ? failure.slice(0, 120) : '';
60
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `hub.race`: races, forwarded to the social runtime. An old cached runtime
3
+ * (feature version 1) has no races, which reads as "not available" rather
4
+ * than a crash.
5
+ */
6
+ import { pageBridge } from './bridge';
7
+ import { hubLink } from './hub-link';
8
+ import type { HubRaceApi, RaceDefinition } from './race-types';
9
+ import type { RealtimeApi } from './runtime-api';
10
+ import { createRuntimeOpener } from './runtime-opener';
11
+
12
+ const openWithRuntime = createRuntimeOpener(pageBridge);
13
+
14
+ let raceDefinition: RaceDefinition | null = null;
15
+ pageBridge.onReady((realtime) => {
16
+ if (raceDefinition !== null) {
17
+ realtime.race?.define(raceDefinition);
18
+ }
19
+ });
20
+
21
+ /** The runtime's race section, or an `OfflineError` for a runtime too old to race. */
22
+ function requireRaces(realtime: RealtimeApi): HubRaceApi {
23
+ if (realtime.race === undefined) {
24
+ throw hubLink().createOfflineError('Races need the latest hub — reload the page.');
25
+ }
26
+ return realtime.race;
27
+ }
28
+
29
+ /** `hub.race`: races. */
30
+ export const raceForwarder: HubRaceApi = {
31
+ define(definition) {
32
+ raceDefinition = definition;
33
+ pageBridge.current()?.race?.define(definition);
34
+ },
35
+ create: (options) => pageBridge.call((realtime) => requireRaces(realtime).create(options)),
36
+ join: (code, options) => pageBridge.call((realtime) => requireRaces(realtime).join(code, options)),
37
+ list: () => pageBridge.call((realtime) => requireRaces(realtime).list()),
38
+ browse: () => {
39
+ openWithRuntime((realtime) => {
40
+ realtime.race?.browse();
41
+ });
42
+ },
43
+ openHistory: (options) => {
44
+ openWithRuntime((realtime) => {
45
+ realtime.race?.openHistory(options);
46
+ });
47
+ },
48
+ history: (query) => pageBridge.call((realtime) => requireRaces(realtime).history(query)),
49
+ status: (stats, progress) => {
50
+ pageBridge.current()?.race?.status(stats, progress);
51
+ },
52
+ finish: (stats) => pageBridge.call((realtime) => requireRaces(realtime).finish(stats)),
53
+ lose: (stats) => pageBridge.call((realtime) => requireRaces(realtime).lose(stats)),
54
+ forfeit: () => pageBridge.call((realtime) => requireRaces(realtime).forfeit()),
55
+ leave: () => pageBridge.call((realtime) => requireRaces(realtime).leave()),
56
+ rematch: (params) => pageBridge.call((realtime) => requireRaces(realtime).rematch(params)),
57
+ current: () => pageBridge.current()?.race?.current() ?? null,
58
+ on: (event, listener) => pageBridge.subscribe((realtime) => realtime.race?.on(event, listener) ?? (() => undefined)),
59
+ };
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Races as games see them through `hub.race` (docs/plans/race.md): a hub
3
+ * room with a referee. Everyone gets the same puzzle (shared seed and
4
+ * params), live status, and the first valid finish wins.
5
+ */
6
+ import type { RaceParams, RaceResult, RaceStats, RoomInfo } from '@diffenderfer-games/hub-contract';
7
+ import type { RaceHistory, RaceStatusEvent } from './wire-types';
8
+ import type { JoinOptions } from './room-types';
9
+
10
+ /** What a race game's `start` receives: build the puzzle from `seed` and `params`. */
11
+ export interface RaceStart {
12
+ /** The race room. */
13
+ roomId: string;
14
+ /** 1 for the first race in the room, +1 per rematch. */
15
+ round: number;
16
+ /** The shared seed, revealed at the countdown. */
17
+ seed: number;
18
+ /** The creator's choices. */
19
+ params: RaceParams;
20
+ /** The go, on THIS page's clock (`Date.now()` ms). The hub draws the 3-2-1. */
21
+ startAt: number;
22
+ /** Racer user ids. */
23
+ players: number[];
24
+ /** Watching: don't let a spectator play. */
25
+ spectator: boolean;
26
+ /** A re-join after a reload or reconnect (the race was already running). */
27
+ resumed: boolean;
28
+ }
29
+
30
+ /** Options for `hub.race.create`. */
31
+ export interface RaceCreateOptions {
32
+ /** The race params (defaults from the manifest). */
33
+ params?: RaceParams;
34
+ /** Public (default true): shows in Open races and can alert friends who follow the game. */
35
+ public?: boolean;
36
+ /** Seats (default the manifest's minimum). The race starts when they're all filled. */
37
+ maxPlayers?: number;
38
+ /** Race this party. */
39
+ partyId?: string;
40
+ }
41
+
42
+ /** Where the hub's race HUD sits. */
43
+ export type RaceHudPlace = 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
44
+
45
+ /** `hub.race.define`: how the hub drives a race game. */
46
+ export interface RaceDefinition {
47
+ /** The countdown began: build the puzzle from `seed` and `params` now and let the player move at `startAt`. */
48
+ start(race: RaceStart): void;
49
+ /** The race was decided (stop input; the hub shows the result card). */
50
+ end?(result: RaceResult): void;
51
+ /** The player left the race screen (Done, cancelled, the room closed): go back to your menu. */
52
+ exit?(): void;
53
+ /** The hub's live race HUD (default on, top). `false` if you draw your own from `hub.race.on('status')`. */
54
+ hud?: false | { place?: RaceHudPlace };
55
+ }
56
+
57
+ /** Events `hub.race.on` delivers, name → payload. */
58
+ export interface RaceEvents {
59
+ /** The race room changed (roster, phase, statuses folded in). */
60
+ room: RoomInfo;
61
+ /** The countdown began. */
62
+ start: RaceStart;
63
+ /** Another racer's live status. */
64
+ status: RaceStatusEvent;
65
+ /** The race was decided. */
66
+ result: RaceResult;
67
+ /** The race room is gone for this page (left, closed, kicked). */
68
+ closed: { reason: string };
69
+ }
70
+
71
+ /** Filters for the race history. */
72
+ export interface RaceHistoryQuery {
73
+ /** A game slug (default: every game). */
74
+ game?: string;
75
+ /** Only races with this player. */
76
+ with?: number;
77
+ /** Only races older than this race id (paging). */
78
+ before?: number;
79
+ /** Page size, 1 to 50. */
80
+ limit?: number;
81
+ }
82
+
83
+ /** Options for `hub.race.openHistory`. */
84
+ export interface RaceHistoryViewOptions {
85
+ /** This game (default), another slug, or `null` for every game. */
86
+ game?: string | null;
87
+ /** Only races with this player. */
88
+ with?: number;
89
+ }
90
+
91
+ /**
92
+ * `hub.race`: races (docs/multiplayer.md "Races"). Declare `game.race` in
93
+ * package.json, call `define` at boot, put a Race button on your menu that
94
+ * calls `create({ params })` (or `browse()`), and report `status`, `finish`
95
+ * and `lose`. The hub does the matching, the waiting card, invites, the
96
+ * countdown, the live HUD, the referee, the result card and the history.
97
+ */
98
+ export interface HubRaceApi {
99
+ /** Register how the hub starts and ends your race. Call once at boot (works before the runtime loads). */
100
+ define(definition: RaceDefinition): void;
101
+ /** Create a race (you're seated; the hub shows the waiting card). Rejects with `HubError` or `OfflineError`. */
102
+ create(options?: RaceCreateOptions): Promise<RoomInfo>;
103
+ /** Join a race by its 5-character code (or watch: `{ spectate: true }`). */
104
+ join(code: string, options?: JoinOptions): Promise<RoomInfo>;
105
+ /** Public races in this game waiting for racers. */
106
+ list(): Promise<RoomInfo[]>;
107
+ /** Open the hub's "Open races" sheet (join one, or type a code). */
108
+ browse(): void;
109
+ /** Open the hub's race history (this game by default). */
110
+ openHistory(options?: RaceHistoryViewOptions): void;
111
+ /** The signed-in player's races. */
112
+ history(query?: RaceHistoryQuery): Promise<RaceHistory>;
113
+ /** Live stats for the HUD (and optional 0..1 progress). Throttled and coalesced: call it on every change. */
114
+ status(stats: RaceStats, progress?: number): void;
115
+ /** I finished: resolves with the result if I won, `null` if someone was first. */
116
+ finish(stats?: RaceStats): Promise<RaceResult | null>;
117
+ /** I'm out (game over, no lives): the others race on, the last one in wins. */
118
+ lose(stats?: RaceStats): Promise<void>;
119
+ /** Give up. */
120
+ forfeit(): Promise<void>;
121
+ /** Leave the race room (a forfeit if it's running). */
122
+ leave(): Promise<void>;
123
+ /** Ask for another round after a race. */
124
+ rematch(params?: RaceParams): Promise<void>;
125
+ /** The race room this page is in (its `RoomInfo` has `race`), or `null`. */
126
+ current(): RoomInfo | null;
127
+ /** Subscribe to race events; works before the runtime loads. Returns the unsubscribe function. */
128
+ on<Name extends keyof RaceEvents>(event: Name, listener: (payload: RaceEvents[Name]) => void): () => void;
129
+ }
130
+
131
+ /** What the runtime's `race` section implements (the same surface `hub.race` forwards). */
132
+ export type RaceRuntimeApi = HubRaceApi;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Hub relay rooms as games see them through `hub.rooms`: realtime
3
+ * multiplayer for static games, relayed (never refereed) by the hub.
4
+ */
5
+ import type { Json, RoomInfo } from '@diffenderfer-games/hub-contract';
6
+ import type { RoomChatLine, RoomMessage } from './wire-types';
7
+
8
+ /** The shared room state (a JSON object, at most 32 KB). */
9
+ export type RoomState = Record<string, Json>;
10
+
11
+ /** Options for `hub.rooms.create`. `game` defaults to the current slug. */
12
+ export interface RoomCreateOptions {
13
+ /** The game slug (default: this page's game). */
14
+ game?: string;
15
+ /** The game mode. */
16
+ mode?: string;
17
+ /** Listed in `hub.rooms.list` (default false). */
18
+ public?: boolean;
19
+ /** Seats. */
20
+ maxPlayers?: number;
21
+ /** `host` (default): guests' unaddressed sends reach the host only. `relay`: everyone hears every send. */
22
+ model?: 'host' | 'relay';
23
+ /** Seat this party in the room. */
24
+ partyId?: string;
25
+ }
26
+
27
+ /** Options for joining a room or race. */
28
+ export interface JoinOptions {
29
+ /** Watch instead of taking a seat (if the game allows spectators). */
30
+ spectate?: boolean;
31
+ }
32
+
33
+ /** Events a {@link HubRoom} emits, name → payload. */
34
+ export interface RoomEvents {
35
+ /** The room changed: roster, ready flags, phase, host. */
36
+ room: RoomInfo;
37
+ /** A relayed game message. */
38
+ msg: RoomMessage;
39
+ /** The shared state after a change. */
40
+ state: RoomState;
41
+ /** A moderated chat line. */
42
+ chat: RoomChatLine;
43
+ /** The host removed me. */
44
+ kicked: { roomId: string };
45
+ /**
46
+ * The room is gone for this tab. `reason`: empty, ended, host_left,
47
+ * other_tab, moved, removed, or `gone` (client-side: the seat couldn't be
48
+ * reclaimed after a reconnect, e.g. the host restarted).
49
+ */
50
+ closed: { reason: string };
51
+ /** The host ended the match (phase → `ended`); `results` is what it passed to `end()`. Fires once. */
52
+ ended: { room: RoomInfo; results?: Json };
53
+ /** A player left mid-game (or their reconnect grace ran out). */
54
+ abandoned: { userId: number; reason?: string };
55
+ }
56
+
57
+ /** Who I am in a room. */
58
+ export interface RoomSelf {
59
+ /** My user id. */
60
+ userId: number;
61
+ /** I host the room. */
62
+ host: boolean;
63
+ /** I'm watching, not seated. */
64
+ spectator: boolean;
65
+ }
66
+
67
+ /** Options for {@link HubRoom.send}. */
68
+ export interface RoomSendOptions {
69
+ /** Send to this seat only. */
70
+ to?: number;
71
+ }
72
+
73
+ /** Options for {@link HubRoom.setState}. */
74
+ export interface RoomStateOptions {
75
+ /** Replace the whole state instead of shallow-merging the patch. */
76
+ replace?: boolean;
77
+ }
78
+
79
+ /** A live hub relay room, as games see it. */
80
+ export interface HubRoom {
81
+ /** The room as last reported. */
82
+ readonly info: RoomInfo;
83
+ /** The shared room state (at most 32 KB). */
84
+ readonly state: RoomState;
85
+ /** Who I am in this room. */
86
+ readonly me: RoomSelf;
87
+ /** Subscribe to a room event. Returns the unsubscribe function. */
88
+ on<Name extends keyof RoomEvents>(event: Name, listener: (payload: RoomEvents[Name]) => void): () => void;
89
+ /** Mark my seat ready (or not). */
90
+ ready(isReady: boolean): Promise<void>;
91
+ /** Set my seat's small game data (team, colour…), at most 2 KB. */
92
+ seat(seatData: Json): Promise<void>;
93
+ /** Host: start the match. */
94
+ start(): Promise<void>;
95
+ /** Relay a game message. */
96
+ send(message: Json, options?: RoomSendOptions): Promise<void>;
97
+ /** Change the shared state. */
98
+ setState(patch: RoomState, options?: RoomStateOptions): Promise<void>;
99
+ /** Free-text chat; resolves with the delivered (maybe softened) text, rejects with a content rejection. */
100
+ chat(text: string): Promise<string>;
101
+ /** Send a quick-chat phrase. */
102
+ quick(phraseId: string): Promise<void>;
103
+ /** Host: remove a player. */
104
+ kick(userId: number): Promise<void>;
105
+ /** Leave the room. */
106
+ leave(): Promise<void>;
107
+ /** Host: end the match, with optional results for everyone. */
108
+ end(results?: Json): Promise<void>;
109
+ }
110
+
111
+ /** Options for `hub.rooms.list`. */
112
+ export interface RoomListOptions {
113
+ /** Only rooms in this mode. */
114
+ mode?: string;
115
+ }
116
+
117
+ /** `hub.rooms`: hub relay rooms (static games, no server). */
118
+ export interface HubRoomsApi {
119
+ /** Create a room and take its first seat. */
120
+ create(options?: RoomCreateOptions): Promise<HubRoom>;
121
+ /** Join a room by its 5-character code or its id. */
122
+ join(codeOrId: string, options?: JoinOptions): Promise<HubRoom>;
123
+ /** Public rooms in the lobby phase for this game. */
124
+ list(options?: RoomListOptions): Promise<RoomInfo[]>;
125
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `hub.rooms`: hub relay rooms, forwarded to the social runtime. Each room is
3
+ * wrapped so its rejections use the core client's error classes.
4
+ */
5
+ import type { Json, RoomInfo } from '@diffenderfer-games/hub-contract';
6
+ import { pageBridge, rethrowAsHubError } from './bridge';
7
+ import type { HubRoom, HubRoomsApi, RoomEvents, RoomSelf, RoomSendOptions, RoomState, RoomStateOptions } from './room-types';
8
+
9
+ /** A runtime room whose rejections are re-created as the core client's errors. */
10
+ class ForwardedRoom implements HubRoom {
11
+ private readonly room: HubRoom;
12
+
13
+ constructor(room: HubRoom) {
14
+ this.room = room;
15
+ }
16
+
17
+ get info(): RoomInfo {
18
+ return this.room.info;
19
+ }
20
+
21
+ get state(): RoomState {
22
+ return this.room.state;
23
+ }
24
+
25
+ get me(): RoomSelf {
26
+ return this.room.me;
27
+ }
28
+
29
+ on<Name extends keyof RoomEvents>(event: Name, listener: (payload: RoomEvents[Name]) => void): () => void {
30
+ return this.room.on(event, listener);
31
+ }
32
+
33
+ ready(isReady: boolean): Promise<void> {
34
+ return rethrowAsHubError(this.room.ready(isReady));
35
+ }
36
+
37
+ seat(seatData: Json): Promise<void> {
38
+ return rethrowAsHubError(this.room.seat(seatData));
39
+ }
40
+
41
+ start(): Promise<void> {
42
+ return rethrowAsHubError(this.room.start());
43
+ }
44
+
45
+ send(message: Json, options?: RoomSendOptions): Promise<void> {
46
+ return rethrowAsHubError(this.room.send(message, options));
47
+ }
48
+
49
+ setState(patch: RoomState, options?: RoomStateOptions): Promise<void> {
50
+ return rethrowAsHubError(this.room.setState(patch, options));
51
+ }
52
+
53
+ chat(text: string): Promise<string> {
54
+ return rethrowAsHubError(this.room.chat(text));
55
+ }
56
+
57
+ quick(phraseId: string): Promise<void> {
58
+ return rethrowAsHubError(this.room.quick(phraseId));
59
+ }
60
+
61
+ kick(userId: number): Promise<void> {
62
+ return rethrowAsHubError(this.room.kick(userId));
63
+ }
64
+
65
+ leave(): Promise<void> {
66
+ return rethrowAsHubError(this.room.leave());
67
+ }
68
+
69
+ end(results?: Json): Promise<void> {
70
+ return rethrowAsHubError(this.room.end(results));
71
+ }
72
+ }
73
+
74
+ /** `hub.rooms`: hub relay rooms. */
75
+ export const roomsForwarder: HubRoomsApi = {
76
+ create: (options) => pageBridge.call(async (realtime) => new ForwardedRoom(await realtime.rooms.create(options))),
77
+ join: (codeOrId, options) => pageBridge.call(async (realtime) => new ForwardedRoom(await realtime.rooms.join(codeOrId, options))),
78
+ list: (options) => pageBridge.call((realtime) => realtime.rooms.list(options)),
79
+ };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The realtime API the hub's social runtime (`/_hub/social.js`) installs on
3
+ * the page, and that `hub.presence`, `hub.social`, `hub.mp`, `hub.rooms`,
4
+ * `hub.notify` and `hub.race` forward to.
5
+ */
6
+ import type { HubMpApi } from './multiplayer-types';
7
+ import type { HubRaceApi } from './race-types';
8
+ import type { HubRoomsApi } from './room-types';
9
+ import type { HubNotifyApi, HubPresenceApi, HubSocialApi } from './social-types';
10
+
11
+ /**
12
+ * The realtime feature version the runtime reports in {@link RealtimeApi.version}.
13
+ * 2 added races; a client feature-detects newer additions with it.
14
+ */
15
+ export const REALTIME_FEATURE_VERSION = 2;
16
+
17
+ /**
18
+ * The cross-bundle shape number of the `rt` page singleton (plan §4.4). The
19
+ * runtime registers with it through `claimSingleton`; bump it only when the
20
+ * shape of {@link RealtimeApi} changes incompatibly.
21
+ */
22
+ export const REALTIME_SINGLETON_API = 1;
23
+
24
+ /** The window event the runtime fires once it has installed itself. */
25
+ export const REALTIME_READY_EVENT = 'hub:rt-ready';
26
+
27
+ /** The window event the menu fires when the runtime failed to load (its reason is on `window.__HUB_RT_ERROR__`). */
28
+ export const REALTIME_FAILED_EVENT = 'hub:rt-failed';
29
+
30
+ /**
31
+ * Installed by the social runtime as the page's `rt` singleton (and the v1
32
+ * alias `window.__HUB_RT__`).
33
+ */
34
+ export interface RealtimeApi {
35
+ /** The runtime's feature version (see {@link REALTIME_FEATURE_VERSION}). */
36
+ readonly version: number;
37
+ /** Presence reporting. */
38
+ presence: HubPresenceApi;
39
+ /** Friends and the social dialogs. */
40
+ social: HubSocialApi;
41
+ /** Invites, launches, the leave guard and tickets. */
42
+ mp: HubMpApi;
43
+ /** Hub relay rooms. */
44
+ rooms: HubRoomsApi;
45
+ /** Toast behaviour. */
46
+ notify: HubNotifyApi;
47
+ /** Races (feature version 2 and later). */
48
+ race?: HubRaceApi;
49
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Opening the runtime's UI (a player card, the friends drawer, the race
3
+ * sheet) from a game button. A tap must never look dead: if the runtime isn't
4
+ * there within a moment the player is told it is loading, and if it never
5
+ * arrives, how to recover.
6
+ */
7
+ import type { RealtimeBridge } from './bridge';
8
+ import { hideFallbackNotice, showFallbackNotice } from './fallback-notice';
9
+ import { readRuntimeFailure } from './page-runtime';
10
+ import type { RealtimeApi } from './runtime-api';
11
+ import { REALTIME_FAILED_EVENT } from './runtime-api';
12
+
13
+ /** How long before "still loading" shows. */
14
+ const SLOW_NOTICE_MS = 1500;
15
+ /** How long the failure notice stays up. */
16
+ const FAILURE_NOTICE_MS = 8000;
17
+
18
+ /** Tell the player the social runtime failed, with the reason the menu recorded. */
19
+ function showRuntimeFailure(): void {
20
+ const reason = readRuntimeFailure();
21
+ showFallbackNotice(`Friends couldn't load${reason === '' ? '' : ` (${reason})`}. Reload the page to try again.`, FAILURE_NOTICE_MS);
22
+ }
23
+
24
+ /** Make an opener: runs a UI call on the runtime once it is up, with the loading and failure notices. */
25
+ export function createRuntimeOpener(bridge: RealtimeBridge): (openUi: (realtime: RealtimeApi) => void) => void {
26
+ return (openUi) => {
27
+ const loaded = bridge.current();
28
+ if (loaded !== null) {
29
+ openUi(loaded);
30
+ return;
31
+ }
32
+ // The menu already knows the runtime failed.
33
+ if (readRuntimeFailure() !== '') {
34
+ showRuntimeFailure();
35
+ return;
36
+ }
37
+ const slowTimer = setTimeout(() => {
38
+ showFallbackNotice('Friends are still loading…');
39
+ }, SLOW_NOTICE_MS);
40
+ let isSettled = false;
41
+ const onFailed = (): void => {
42
+ if (!isSettled) {
43
+ isSettled = true;
44
+ clearTimeout(slowTimer);
45
+ showRuntimeFailure();
46
+ }
47
+ };
48
+ if (typeof window !== 'undefined') {
49
+ window.addEventListener(REALTIME_FAILED_EVENT, onFailed, { once: true });
50
+ }
51
+ bridge.whenReady().then((realtime) => {
52
+ if (isSettled) {
53
+ return;
54
+ }
55
+ isSettled = true;
56
+ clearTimeout(slowTimer);
57
+ hideFallbackNotice();
58
+ openUi(realtime);
59
+ }, onFailed);
60
+ };
61
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * `hub.presence`, `hub.social` and `hub.notify`: thin forwarders to the
3
+ * social runtime. Presence and quiet mode are "latest state" calls,
4
+ * remembered and replayed when the runtime loads.
5
+ */
6
+ import { pageBridge } from './bridge';
7
+ import { latestState } from './latest-state';
8
+ import { createRuntimeOpener } from './runtime-opener';
9
+ import type { HubNotifyApi, HubPresenceApi, HubSocialApi, SocialCounts } from './social-types';
10
+
11
+ const openWithRuntime = createRuntimeOpener(pageBridge);
12
+
13
+ /** Counts before the runtime is up. */
14
+ const NO_COUNTS: SocialCounts = { online: 0, inGame: 0, friendsOnline: 0 };
15
+
16
+ /** `hub.presence`: what you're doing, shown to friends. */
17
+ export const presenceForwarder: HubPresenceApi = {
18
+ set(presence) {
19
+ latestState.presence = { ...presence };
20
+ pageBridge.current()?.presence.set(latestState.presence);
21
+ },
22
+ clear() {
23
+ latestState.presence = { kind: 'menu' };
24
+ pageBridge.current()?.presence.clear();
25
+ },
26
+ };
27
+
28
+ /** `hub.notify`: toast behaviour. */
29
+ export const notifyForwarder: HubNotifyApi = {
30
+ setQuiet(isQuiet) {
31
+ latestState.isQuiet = isQuiet;
32
+ pageBridge.current()?.notify.setQuiet(isQuiet);
33
+ },
34
+ };
35
+
36
+ /** `hub.social`: friends and the hub's social dialogs. */
37
+ export const socialForwarder: HubSocialApi = {
38
+ openPlayer: (ref) => {
39
+ openWithRuntime((realtime) => {
40
+ realtime.social.openPlayer(ref);
41
+ });
42
+ },
43
+ openFriends: () => {
44
+ openWithRuntime((realtime) => {
45
+ realtime.social.openFriends();
46
+ });
47
+ },
48
+ openChat: (userId) => {
49
+ openWithRuntime((realtime) => {
50
+ realtime.social.openChat(userId);
51
+ });
52
+ },
53
+ openInvite: (options) => {
54
+ openWithRuntime((realtime) => {
55
+ realtime.social.openInvite(options);
56
+ });
57
+ },
58
+ openSuggest: () => {
59
+ openWithRuntime((realtime) => {
60
+ realtime.social.openSuggest();
61
+ });
62
+ },
63
+ openNotify: (options) => {
64
+ openWithRuntime((realtime) => {
65
+ realtime.social.openNotify(options);
66
+ });
67
+ },
68
+ friends: () => pageBridge.call((realtime) => realtime.social.friends()),
69
+ counts: () => pageBridge.current()?.social.counts() ?? { ...NO_COUNTS },
70
+ chatMode: (userIds) => pageBridge.current()?.social.chatMode(userIds) ?? 'off',
71
+ on: (event, listener) => pageBridge.subscribe((realtime) => realtime.social.on(event, listener)),
72
+ };