@diffenderfer-games/hub 2.0.0-next.0 → 2.0.0-next.2

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 (154) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +21 -21
  3. package/README.md +206 -139
  4. package/dist/auto.d.ts +6 -6
  5. package/dist/auto.js +2 -2
  6. package/dist/doctor/cli.mjs +62 -25
  7. package/dist/doctor/cli.mjs.map +1 -1
  8. package/dist/index.d.ts +6 -6
  9. package/dist/index.js +2 -2
  10. package/dist/mp.d.ts +3 -3
  11. package/dist/race.d.ts +1 -1
  12. package/dist/rooms.d.ts +3 -3
  13. package/dist/shared/bridge.js +9 -3
  14. package/dist/shared/bridge.js.map +1 -1
  15. package/dist/shared/client-version.gen.js +1 -1
  16. package/dist/shared/daily.d.ts +10 -4
  17. package/dist/shared/daily.d.ts.map +1 -1
  18. package/dist/shared/daily.js +12 -2
  19. package/dist/shared/daily.js.map +1 -1
  20. package/dist/shared/globals.js +8 -3
  21. package/dist/shared/globals.js.map +1 -1
  22. package/dist/shared/index.d.ts +314 -35
  23. package/dist/shared/index.d.ts.map +1 -1
  24. package/dist/shared/input.js +7 -2
  25. package/dist/shared/input.js.map +1 -1
  26. package/dist/shared/latest-state.js +1 -1
  27. package/dist/shared/mp.js +10 -2
  28. package/dist/shared/mp.js.map +1 -1
  29. package/dist/shared/multiplayer-types.d.ts +15 -2
  30. package/dist/shared/multiplayer-types.d.ts.map +1 -1
  31. package/dist/shared/race-types.d.ts +1 -1
  32. package/dist/shared/race.js +1 -1
  33. package/dist/shared/room-types.d.ts +28 -3
  34. package/dist/shared/room-types.d.ts.map +1 -1
  35. package/dist/shared/rooms.d.ts.map +1 -1
  36. package/dist/shared/rooms.js +10 -2
  37. package/dist/shared/rooms.js.map +1 -1
  38. package/dist/shared/runtime-opener.js +1 -1
  39. package/dist/shared/social.d.ts +23 -8
  40. package/dist/shared/social.d.ts.map +1 -1
  41. package/dist/shared/social.js +6 -1
  42. package/dist/shared/social.js.map +1 -1
  43. package/dist/shared/src.js +1588 -388
  44. package/dist/shared/src.js.map +1 -1
  45. package/dist/shared/wire-types.d.ts +6 -2
  46. package/dist/shared/wire-types.d.ts.map +1 -1
  47. package/dist/social.d.ts +5 -5
  48. package/dist/social.js +1 -1
  49. package/package.json +89 -89
  50. package/src/auto.ts +39 -39
  51. package/src/core/connection.ts +394 -299
  52. package/src/core/errors.ts +147 -147
  53. package/src/core/game-data.ts +40 -38
  54. package/src/core/hub-economy.ts +216 -179
  55. package/src/core/hub-progress.ts +202 -205
  56. package/src/core/hub.ts +133 -131
  57. package/src/core/menu-control.ts +61 -61
  58. package/src/core/offline/events.ts +50 -50
  59. package/src/core/offline/favorites.ts +21 -21
  60. package/src/core/offline/hub-kinds/daily-kind.ts +68 -0
  61. package/src/core/offline/hub-kinds/economy-kinds.ts +86 -0
  62. package/src/core/offline/hub-kinds/game-fields.ts +2 -0
  63. package/src/core/offline/hub-kinds/index.ts +35 -0
  64. package/src/core/offline/hub-kinds/legacy-ops.ts +37 -0
  65. package/src/core/offline/hub-kinds/progress-kinds.ts +148 -0
  66. package/src/core/offline/kind-adapters.ts +48 -0
  67. package/src/core/offline/local-inventory.ts +64 -0
  68. package/src/core/offline/local-store.ts +259 -261
  69. package/src/core/offline/offline-api.ts +65 -0
  70. package/src/core/offline/outbox-entry.ts +59 -0
  71. package/src/core/offline/outbox-kinds.ts +78 -0
  72. package/src/core/offline/outbox-merge.ts +39 -0
  73. package/src/core/offline/outbox-replayer.ts +141 -0
  74. package/src/core/offline/outbox-store.ts +85 -0
  75. package/src/core/offline/outbox.ts +232 -0
  76. package/src/core/offline/queue.ts +126 -171
  77. package/src/core/offline/replay-lease.ts +87 -0
  78. package/src/core/offline/replay-policy.ts +52 -0
  79. package/src/core/page.ts +74 -74
  80. package/src/core/rest/endpoint-types.ts +22 -22
  81. package/src/core/rest/rest-client.ts +163 -152
  82. package/src/core/rest/routes.gen.ts +108 -87
  83. package/src/core/storage/json-guards.ts +80 -74
  84. package/src/core/storage/key-value.ts +66 -66
  85. package/src/core/ticket.ts +43 -43
  86. package/src/core/types.ts +134 -134
  87. package/src/core/version/client-version.gen.ts +1 -1
  88. package/src/core/version/hub-version.ts +62 -62
  89. package/src/core/version/semver.ts +97 -97
  90. package/src/daily/daily-system.ts +168 -161
  91. package/src/daily/page-daily.ts +36 -36
  92. package/src/daily/types.ts +68 -67
  93. package/src/daily.ts +10 -10
  94. package/src/doctor/checks.ts +86 -76
  95. package/src/doctor/cli.ts +98 -106
  96. package/src/doctor/hub-version-fetch.ts +43 -0
  97. package/src/doctor/tsconfig.json +12 -12
  98. package/src/globals.ts +115 -110
  99. package/src/index.ts +55 -50
  100. package/src/input/device-state.ts +146 -146
  101. package/src/input/edges.ts +55 -55
  102. package/src/input/gamepad.ts +61 -61
  103. package/src/input/input-events.ts +32 -32
  104. package/src/input/input-registry.ts +171 -164
  105. package/src/input/input-system.ts +393 -393
  106. package/src/input/legacy-controls.ts +64 -64
  107. package/src/input/nav-state.ts +191 -191
  108. package/src/input/navigator.ts +171 -171
  109. package/src/input/on-screen-controls.ts +101 -101
  110. package/src/input/page-control.ts +43 -43
  111. package/src/input/page-input.ts +193 -193
  112. package/src/input/player-remaps.ts +77 -77
  113. package/src/input/source-values.ts +116 -116
  114. package/src/input/spatial.ts +47 -47
  115. package/src/input/types.ts +331 -331
  116. package/src/input/zero-config.ts +177 -177
  117. package/src/input.ts +22 -22
  118. package/src/mp.ts +10 -10
  119. package/src/overlay/controls-panel.ts +163 -163
  120. package/src/overlay/dom.ts +46 -46
  121. package/src/overlay/layout-clusters.ts +162 -162
  122. package/src/overlay/layout-geometry.ts +136 -136
  123. package/src/overlay/layout.ts +203 -203
  124. package/src/overlay/listener-scope.ts +23 -23
  125. package/src/overlay/on-screen-keyboard.ts +137 -137
  126. package/src/overlay/overlay.ts +208 -208
  127. package/src/overlay/styles.ts +9 -9
  128. package/src/overlay/virtual-controls.ts +262 -262
  129. package/src/race.ts +10 -10
  130. package/src/realtime/bridge.ts +126 -121
  131. package/src/realtime/cross-bundle.ts +29 -29
  132. package/src/realtime/fallback-notice.ts +48 -48
  133. package/src/realtime/hub-link.ts +65 -65
  134. package/src/realtime/latest-state.ts +33 -33
  135. package/src/realtime/multiplayer-forwarder.ts +40 -28
  136. package/src/realtime/multiplayer-types.ts +66 -52
  137. package/src/realtime/page-runtime.ts +60 -60
  138. package/src/realtime/race-forwarder.ts +59 -59
  139. package/src/realtime/race-types.ts +132 -132
  140. package/src/realtime/room-types.ts +151 -125
  141. package/src/realtime/rooms-forwarder.ts +91 -79
  142. package/src/realtime/runtime-api.ts +60 -49
  143. package/src/realtime/runtime-opener.ts +61 -61
  144. package/src/realtime/social-forwarder.ts +77 -72
  145. package/src/realtime/social-types.ts +86 -78
  146. package/src/realtime/types.ts +53 -53
  147. package/src/realtime/wire-types.ts +79 -72
  148. package/src/rooms.ts +10 -10
  149. package/src/social.ts +18 -18
  150. package/src/types.ts +13 -13
  151. package/src/uistack/page-stack.ts +45 -45
  152. package/src/uistack/play-suspension.ts +82 -82
  153. package/src/uistack/types.ts +76 -76
  154. package/src/uistack/ui-stack.ts +144 -144
@@ -1,299 +1,394 @@
1
- /**
2
- * The machinery under every `Hub` call: reaching the REST API, falling back
3
- * to the offline cache, queueing writes made offline and replaying them,
4
- * buffering analytics, warming the cache for every game, and reporting
5
- * online/offline/sync status (to `onStatus` listeners and as `hub:*` window
6
- * events, which the injected menu listens for).
7
- */
8
- import { HubError } from './errors';
9
- import { LocalStore } from './offline/local-store';
10
- import type { QueueOp, QueueOpInput } from './offline/queue';
11
- import { absoluteApiBase, detectApiBase, detectSlug, emitWindowEvent, isBrowserPage } from './page';
12
- import { createRestClient, type RestClient } from './rest/rest-client';
13
- import type { HubOptions, HubStatus, SnapshotResponse } from './types';
14
-
15
- /** How long `prefetchAll()` waits between snapshots unless forced. */
16
- const PREFETCH_INTERVAL_MS = 30_000;
17
-
18
- /** A queued write the hub refused during a sync: dropped, with the hub's message. */
19
- export interface SyncConflict {
20
- /** The refused op. */
21
- readonly op: QueueOp;
22
- /** The hub's message. */
23
- readonly error?: string;
24
- }
25
-
26
- /** What one `sync()` did. */
27
- export interface SyncResult {
28
- /** Queued writes the hub accepted. */
29
- readonly flushed: number;
30
- /** Queued writes the hub refused (and that were dropped). */
31
- readonly conflicts: SyncConflict[];
32
- }
33
-
34
- /** Whether a failure means "the hub can't be reached" (rather than a refusal). */
35
- // eslint-disable-next-line no-restricted-syntax -- trust boundary: whatever a call threw
36
- function isTransportFailure(failure: unknown): boolean {
37
- return failure instanceof HubError && failure.isOffline;
38
- }
39
-
40
- /** The game slug's path field, or a {@link HubError} when the slug is unknown. */
41
- export interface GameFields {
42
- /** The game's slug. */
43
- readonly slug: string;
44
- }
45
-
46
- /** The connection, offline cache and sync machinery shared by every `Hub` method. */
47
- export class HubConnection {
48
- /** This client's game slug (`null` when it could not be determined). */
49
- readonly slug: string | null;
50
- /** The absolute API base, e.g. `https://diffenderfer.games/_api`. */
51
- readonly apiBase: string;
52
- /** Typed REST calls to {@link apiBase}. */
53
- protected readonly rest: RestClient;
54
- /** This game's offline cache, queue and event buffer. */
55
- protected readonly store: LocalStore;
56
- private readonly offlineMode: NonNullable<HubOptions['offline']>;
57
- private isReachable = true;
58
- private isSyncing = false;
59
- private lastPrefetchAt = 0;
60
- private readonly statusListeners = new Set<(status: HubStatus) => void>();
61
-
62
- /** A connection for `options` (slug and API base default to the page's). */
63
- constructor(options: HubOptions = {}) {
64
- this.slug = options.slug ?? detectSlug();
65
- this.apiBase = options.apiBase === undefined ? detectApiBase() : absoluteApiBase(options.apiBase);
66
- this.offlineMode = options.offline ?? 'auto';
67
- this.rest = createRestClient({
68
- apiBase: this.apiBase,
69
- fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
70
- onReachable: () => {
71
- this.setReachable(true);
72
- },
73
- });
74
- this.store = new LocalStore(this.slug ?? 'app');
75
- if (typeof navigator !== 'undefined' && 'onLine' in navigator) {
76
- this.isReachable = navigator.onLine;
77
- }
78
- if (isBrowserPage()) {
79
- window.addEventListener('online', () => {
80
- this.setReachable(true);
81
- });
82
- window.addEventListener('offline', () => {
83
- this.setReachable(false);
84
- });
85
- }
86
- }
87
-
88
- /** `true` when calls are being served from the offline cache rather than the hub. */
89
- get isOffline(): boolean {
90
- return this.offlineMode === 'always' || (this.offlineMode === 'auto' && !this.isReachable);
91
- }
92
-
93
- /** `true` while the hub is reachable. */
94
- get isOnline(): boolean {
95
- return this.isReachable;
96
- }
97
-
98
- /** Queued writes plus buffered analytics events waiting to sync. */
99
- pending(): number {
100
- return this.store.queueLength() + this.store.getEvents().length;
101
- }
102
-
103
- /** Subscribe to connection and sync status changes; returns the unsubscribe function. */
104
- onStatus(listener: (status: HubStatus) => void): () => void {
105
- this.statusListeners.add(listener);
106
- return () => {
107
- this.statusListeners.delete(listener);
108
- };
109
- }
110
-
111
- /** Tell `onStatus` listeners and the page (`hub:status`) the current status. */
112
- protected notifyStatus(): void {
113
- const status: HubStatus = { online: this.isReachable, offline: this.isOffline, pending: this.pending() };
114
- for (const listener of this.statusListeners) {
115
- try {
116
- listener(status);
117
- } catch {
118
- // A listener's failure must not stop the others.
119
- }
120
- }
121
- emitWindowEvent('hub:status', status);
122
- }
123
-
124
- /** Record reachability; coming back online syncs the queue and re-warms the cache. */
125
- protected setReachable(isReachableNow: boolean): void {
126
- if (isReachableNow === this.isReachable) {
127
- return;
128
- }
129
- this.isReachable = isReachableNow;
130
- emitWindowEvent(isReachableNow ? 'hub:online' : 'hub:offline', { pending: this.pending() });
131
- this.notifyStatus();
132
- if (isReachableNow) {
133
- void this.sync();
134
- void this.prefetchAll().catch(() => undefined);
135
- }
136
- }
137
-
138
- /** `{ slug }` for this game's endpoints; throws when the slug is unknown. */
139
- protected gameFields(): GameFields {
140
- if (this.slug === null) {
141
- throw new HubError('Hub: could not determine the game slug.');
142
- }
143
- return { slug: this.slug };
144
- }
145
-
146
- /**
147
- * Run the network call, falling back to the offline answer when the hub
148
- * can't be reached (per the offline mode). Real API errors (with an HTTP
149
- * status) always reach the caller.
150
- */
151
- protected async withFallback<Reply>(networkCall: () => Promise<Reply>, offlineAnswer: () => Reply): Promise<Reply> {
152
- if (this.isOffline) {
153
- return offlineAnswer();
154
- }
155
- try {
156
- return await networkCall();
157
- } catch (failure) {
158
- if (!isTransportFailure(failure) || this.offlineMode === 'never') {
159
- throw failure;
160
- }
161
- this.setReachable(false);
162
- return offlineAnswer();
163
- }
164
- }
165
-
166
- /** Send one queued write. */
167
- private async sendOp(op: QueueOpInput): Promise<void> {
168
- const game = this.gameFields();
169
- switch (op.kind) {
170
- case 'putSave':
171
- await this.rest.call('writeSave', { ...game, slot: op.slot, data: op.data, label: op.label });
172
- return;
173
- case 'deleteSave':
174
- await this.rest.call('deleteSave', { ...game, slot: op.slot });
175
- return;
176
- case 'setStat':
177
- await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.value, mode: 'set' });
178
- return;
179
- case 'maxStat':
180
- await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.value, mode: 'max' });
181
- return;
182
- case 'incrStat':
183
- await this.rest.call('updateGameStat', { ...game, key: op.key, value: op.amount, mode: 'incr' });
184
- return;
185
- case 'submitScore':
186
- await this.rest.call('submitScore', { ...game, key: op.key, score: op.score, ...op.opts });
187
- return;
188
- case 'setProfile':
189
- await this.rest.call('setGameProfile', { ...game, ...op.patch });
190
- return;
191
- }
192
- }
193
-
194
- /**
195
- * Apply a write to the offline cache at once, then send it now (online
196
- * with an empty queue) or queue it behind the others. Resolves with the
197
- * local answer; a real API error on the direct path reaches the caller and
198
- * is not queued.
199
- */
200
- protected async mutateQueued<Reply>(input: QueueOpInput, localAnswer: () => Reply): Promise<Reply> {
201
- const answer = localAnswer();
202
- if (this.isOffline || this.store.queueLength() > 0) {
203
- this.store.enqueue(input);
204
- this.notifyStatus();
205
- if (!this.isOffline) {
206
- void this.sync();
207
- }
208
- return answer;
209
- }
210
- try {
211
- await this.sendOp(input);
212
- return answer;
213
- } catch (failure) {
214
- if (!isTransportFailure(failure)) {
215
- throw failure;
216
- }
217
- this.setReachable(false);
218
- this.store.enqueue(input);
219
- this.notifyStatus();
220
- return answer;
221
- }
222
- }
223
-
224
- /**
225
- * Replay the queue, then the buffered events, in order. Stops at the first
226
- * transport failure (offline again: the rest stays queued); a write the hub
227
- * refuses is dropped and reported as a conflict.
228
- */
229
- async sync(): Promise<SyncResult> {
230
- if (this.isSyncing || this.isOffline || this.slug === null) {
231
- return { flushed: 0, conflicts: [] };
232
- }
233
- this.isSyncing = true;
234
- let flushed = 0;
235
- const conflicts: SyncConflict[] = [];
236
- try {
237
- let queue = this.store.getQueue();
238
- for (let op = queue[0]; op !== undefined; op = queue[0]) {
239
- try {
240
- await this.sendOp(op);
241
- flushed += 1;
242
- } catch (failure) {
243
- if (isTransportFailure(failure)) {
244
- break;
245
- }
246
- conflicts.push({ op, error: failure instanceof Error ? failure.message : String(failure) });
247
- }
248
- queue = queue.slice(1);
249
- this.store.setQueue(queue);
250
- }
251
- await this.flushEvents();
252
- } finally {
253
- this.isSyncing = false;
254
- }
255
- emitWindowEvent('hub:sync', { pending: this.pending(), flushed, conflicts });
256
- this.notifyStatus();
257
- return { flushed, conflicts };
258
- }
259
-
260
- /** Send the buffered analytics events; a refused one is dropped (telemetry never blocks). */
261
- private async flushEvents(): Promise<void> {
262
- let events = this.store.getEvents();
263
- for (let event = events[0]; event !== undefined; event = events[0]) {
264
- try {
265
- await this.rest.call('recordGameEvent', { ...this.gameFields(), type: event.type });
266
- } catch (failure) {
267
- if (isTransportFailure(failure)) {
268
- return;
269
- }
270
- }
271
- events = events.slice(1);
272
- this.store.setEvents(events);
273
- }
274
- }
275
-
276
- /**
277
- * Warm the offline cache for every game the player has touched, in one
278
- * request, so going offline later still shows complete progress.
279
- * Throttled to once per 30 s unless `isForced`; `null` when offline or throttled.
280
- */
281
- async prefetchAll(isForced = false): Promise<SnapshotResponse | null> {
282
- if (this.isOffline || (!isForced && Date.now() - this.lastPrefetchAt < PREFETCH_INTERVAL_MS)) {
283
- return null;
284
- }
285
- let snapshot: SnapshotResponse;
286
- try {
287
- snapshot = await this.rest.call('getMyOfflineSnapshot');
288
- } catch (failure) {
289
- if (isTransportFailure(failure)) {
290
- return null;
291
- }
292
- throw failure;
293
- }
294
- this.lastPrefetchAt = Date.now();
295
- this.store.hydrate(snapshot);
296
- emitWindowEvent('hub:prefetch', { games: Object.keys(snapshot.games).length });
297
- return snapshot;
298
- }
299
- }
1
+ /**
2
+ * The machinery under every `Hub` call: reaching the REST API, falling back
3
+ * to the offline cache, queueing writes made offline in the outbox and
4
+ * replaying them, buffering analytics, warming the cache for every game, and
5
+ * reporting online/offline/sync status (to `onStatus` listeners and as
6
+ * `hub:*` window events, which the injected menu listens for).
7
+ */
8
+ import type { Json } from '@diffenderfer-games/hub-contract';
9
+ import { HubError } from './errors';
10
+ import { registerHubKinds, legacyOperation } from './offline/hub-kinds';
11
+ import { LocalStore } from './offline/local-store';
12
+ import { OfflineApi } from './offline/offline-api';
13
+ import { Outbox, type OfflineOp } from './offline/outbox';
14
+ import { absoluteApiBase, detectApiBase, detectSlug, emitWindowEvent, isBrowserPage } from './page';
15
+ import { createRestClient, type RestClient } from './rest/rest-client';
16
+ import { createPageStore } from './storage/key-value';
17
+ import type { HubOptions, HubStatus, SnapshotResponse } from './types';
18
+
19
+ /** How long `prefetchAll()` waits between snapshots unless forced. */
20
+ const PREFETCH_INTERVAL_MS = 30_000;
21
+
22
+ /** A queued op the hub refused during a sync (or that kept failing): dropped, with the reason. */
23
+ export interface SyncConflict {
24
+ /** The dropped op. */
25
+ readonly op: OfflineOp;
26
+ /** The hub's (or the handler's) message. */
27
+ readonly error?: string;
28
+ }
29
+
30
+ /** What one `sync()` did. */
31
+ export interface SyncResult {
32
+ /** Queued ops that landed. */
33
+ readonly flushed: number;
34
+ /** Queued ops that were dropped. */
35
+ readonly conflicts: SyncConflict[];
36
+ }
37
+
38
+ /** A sync that did nothing. */
39
+ const NOTHING_SYNCED: SyncResult = { flushed: 0, conflicts: [] };
40
+
41
+ /** Whether a failure means "the hub can't be reached" (rather than a refusal). */
42
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: whatever a call threw
43
+ function isTransportFailure(failure: unknown): boolean {
44
+ return failure instanceof HubError && failure.isOffline;
45
+ }
46
+
47
+ /** The game slug's path field, or a {@link HubError} when the slug is unknown. */
48
+ export interface GameFields {
49
+ /** The game's slug. */
50
+ readonly slug: string;
51
+ }
52
+
53
+ /** The connection, offline cache and sync machinery shared by every `Hub` method. */
54
+ export class HubConnection {
55
+ /** This client's game slug (`null` when it could not be determined). */
56
+ readonly slug: string | null;
57
+ /** The absolute API base, e.g. `https://diffenderfer.games/_api`. */
58
+ readonly apiBase: string;
59
+ /** Typed REST calls to {@link apiBase}. */
60
+ protected readonly rest: RestClient;
61
+ /** This game's offline cache and event buffer. */
62
+ protected readonly store: LocalStore;
63
+ /** This game's queued operations. */
64
+ protected readonly outbox: Outbox;
65
+ private readonly offlineMode: NonNullable<HubOptions['offline']>;
66
+ private isReachable = true;
67
+ private runningSync: Promise<SyncResult> | null = null;
68
+ private followingSync: Promise<SyncResult> | null = null;
69
+ private isFollowingEager = false;
70
+ private directSend: Promise<Json | undefined> | null = null;
71
+ private lastPrefetchAt = 0;
72
+ private offlineApi: OfflineApi | undefined;
73
+ private readonly statusListeners = new Set<(status: HubStatus) => void>();
74
+
75
+ /** A connection for `options` (slug and API base default to the page's). */
76
+ constructor(options: HubOptions = {}) {
77
+ this.slug = options.slug ?? detectSlug();
78
+ this.apiBase = options.apiBase === undefined ? detectApiBase() : absoluteApiBase(options.apiBase);
79
+ this.offlineMode = options.offline ?? 'auto';
80
+ this.rest = createRestClient({
81
+ apiBase: this.apiBase,
82
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
83
+ onReachable: () => {
84
+ this.setReachable(true);
85
+ },
86
+ });
87
+ const pageStore = createPageStore();
88
+ this.store = new LocalStore(this.slug ?? 'app', pageStore);
89
+ this.outbox = new Outbox({
90
+ slug: this.slug ?? 'app',
91
+ store: pageStore,
92
+ rest: this.rest,
93
+ emit: emitWindowEvent,
94
+ onUnreachable: () => {
95
+ this.setReachable(false);
96
+ },
97
+ onChange: () => {
98
+ this.notifyStatus();
99
+ },
100
+ onRetryDue: () => {
101
+ void this.retrySync();
102
+ },
103
+ });
104
+ registerHubKinds(this.outbox, {
105
+ game: () => this.gameFields(),
106
+ onDailyComplete: (payload, completion) => {
107
+ emitWindowEvent('hub:daily-complete', { day: payload.day, count: completion.count, rank: completion.rank, meta: payload.meta });
108
+ },
109
+ });
110
+ this.importLegacyQueue();
111
+ if (typeof navigator !== 'undefined' && 'onLine' in navigator) {
112
+ this.isReachable = navigator.onLine;
113
+ }
114
+ if (isBrowserPage()) {
115
+ this.listenToPage();
116
+ }
117
+ }
118
+
119
+ /** `true` when calls are being served from the offline cache rather than the hub. */
120
+ get isOffline(): boolean {
121
+ return this.offlineMode === 'always' || (this.offlineMode === 'auto' && !this.isReachable);
122
+ }
123
+
124
+ /** `true` while the hub is reachable. */
125
+ get isOnline(): boolean {
126
+ return this.isReachable;
127
+ }
128
+
129
+ /**
130
+ * The offline outbox: define your own kinds of operation, queue them, and
131
+ * hear how they replay (`hub.offline.define`, `enqueue`, `pending`, `on`).
132
+ */
133
+ get offline(): OfflineApi {
134
+ this.offlineApi ??= new OfflineApi({
135
+ outbox: this.outbox,
136
+ requestSync: () => {
137
+ if (!this.isOffline) {
138
+ void this.sync();
139
+ }
140
+ },
141
+ });
142
+ return this.offlineApi;
143
+ }
144
+
145
+ /** Queued operations plus buffered analytics events waiting to sync. */
146
+ pending(): number {
147
+ return this.outbox.count() + this.store.getEvents().length;
148
+ }
149
+
150
+ /** Subscribe to connection and sync status changes; returns the unsubscribe function. */
151
+ onStatus(listener: (status: HubStatus) => void): () => void {
152
+ this.statusListeners.add(listener);
153
+ return () => {
154
+ this.statusListeners.delete(listener);
155
+ };
156
+ }
157
+
158
+ /** Tell `onStatus` listeners and the page (`hub:status`) the current status. */
159
+ protected notifyStatus(): void {
160
+ const status: HubStatus = { online: this.isReachable, offline: this.isOffline, pending: this.pending() };
161
+ for (const listener of this.statusListeners) {
162
+ try {
163
+ listener(status);
164
+ } catch {
165
+ // A listener's failure must not stop the others.
166
+ }
167
+ }
168
+ emitWindowEvent('hub:status', status);
169
+ }
170
+
171
+ /** Record reachability; coming back online replays the outbox and re-warms the cache. */
172
+ protected setReachable(isReachableNow: boolean): void {
173
+ if (isReachableNow === this.isReachable) {
174
+ return;
175
+ }
176
+ this.isReachable = isReachableNow;
177
+ emitWindowEvent(isReachableNow ? 'hub:online' : 'hub:offline', { pending: this.pending() });
178
+ this.notifyStatus();
179
+ if (isReachableNow) {
180
+ // Replay first, so the snapshot that re-warms the cache already has the queued changes.
181
+ void this.replayAll(true).then(() => this.prefetchAll()).catch(() => undefined);
182
+ }
183
+ }
184
+
185
+ /** `{ slug }` for this game's endpoints; throws when the slug is unknown. */
186
+ protected gameFields(): GameFields {
187
+ if (this.slug === null) {
188
+ throw new HubError('Hub: could not determine the game slug.');
189
+ }
190
+ return { slug: this.slug };
191
+ }
192
+
193
+ /**
194
+ * Run the network call, falling back to the offline answer when the hub
195
+ * can't be reached (per the offline mode). Real API errors (with an HTTP
196
+ * status) always reach the caller.
197
+ */
198
+ protected async withFallback<Reply>(networkCall: () => Promise<Reply>, offlineAnswer: () => Reply): Promise<Reply> {
199
+ if (this.isOffline) {
200
+ return offlineAnswer();
201
+ }
202
+ try {
203
+ return await networkCall();
204
+ } catch (failure) {
205
+ if (!isTransportFailure(failure) || this.offlineMode === 'never') {
206
+ throw failure;
207
+ }
208
+ this.setReachable(false);
209
+ return offlineAnswer();
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Apply a write to the offline cache at once, then perform it as an op of
215
+ * `kind`: sent now when online with nothing waiting, else queued behind
216
+ * the others. Resolves with the local answer (or, sent now, with
217
+ * `replyAnswer`'s reading of the hub's reply). A real API error on the
218
+ * direct path reaches the caller and is not queued; a transport failure
219
+ * queues the op under the same id, so if the request did land, its replay
220
+ * is recognised by the hub and not applied twice.
221
+ */
222
+ protected async mutateOffline<Reply>(kind: string, payload: Json, localAnswer: () => Reply, replyAnswer?: (result: Json | undefined) => Reply | undefined): Promise<Reply> {
223
+ const answer = localAnswer();
224
+ const op = this.outbox.stamp(kind, payload);
225
+ if (this.isOffline || this.outbox.count() > 0 || this.runningSync !== null || this.directSend !== null) {
226
+ this.outbox.add(op);
227
+ if (!this.isOffline) {
228
+ void this.sync();
229
+ }
230
+ return answer;
231
+ }
232
+ const sending = this.outbox.runNow(op);
233
+ this.directSend = sending;
234
+ try {
235
+ const result = await sending;
236
+ return replyAnswer?.(result) ?? answer;
237
+ } catch (failure) {
238
+ if (!isTransportFailure(failure)) {
239
+ throw failure;
240
+ }
241
+ this.setReachable(false);
242
+ this.outbox.add({ ...op, attempts: 1 });
243
+ return answer;
244
+ } finally {
245
+ if (this.directSend === sending) {
246
+ this.directSend = null;
247
+ }
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Replay the outbox, then the buffered events, in order. Stops at the
253
+ * first transport failure (offline again: the rest stays queued); an op
254
+ * the hub refuses is dropped and reported as a conflict.
255
+ */
256
+ sync(): Promise<SyncResult> {
257
+ return this.isOffline ? Promise.resolve(NOTHING_SYNCED) : this.replayAll(false);
258
+ }
259
+
260
+ /** A retry came due: try again even when the hub was last unreachable (the try is the probe), unless the browser itself is offline. */
261
+ private retrySync(): Promise<SyncResult> {
262
+ const isBrowserOffline = typeof navigator !== 'undefined' && 'onLine' in navigator && !navigator.onLine;
263
+ return this.offlineMode === 'always' || isBrowserOffline ? Promise.resolve(NOTHING_SYNCED) : this.replayAll(false);
264
+ }
265
+
266
+ /**
267
+ * One replay at a time per client. A call during one queues a single
268
+ * follow-up replay (eager if any caller asked for that), so an op queued
269
+ * or a reconnect that happens mid-replay is never missed.
270
+ */
271
+ private replayAll(isEager: boolean): Promise<SyncResult> {
272
+ if (this.slug === null || this.offlineMode === 'always') {
273
+ return Promise.resolve(NOTHING_SYNCED);
274
+ }
275
+ const running = this.runningSync;
276
+ if (running === null) {
277
+ return this.startReplay(isEager);
278
+ }
279
+ this.isFollowingEager ||= isEager;
280
+ this.followingSync ??= running.catch(() => NOTHING_SYNCED).then(() => {
281
+ const isFollowUpEager = this.isFollowingEager;
282
+ this.isFollowingEager = false;
283
+ this.followingSync = null;
284
+ return this.startReplay(isFollowUpEager);
285
+ });
286
+ return this.followingSync;
287
+ }
288
+
289
+ private startReplay(isEager: boolean): Promise<SyncResult> {
290
+ const run = this.runReplay(isEager).finally(() => {
291
+ if (this.runningSync === run) {
292
+ this.runningSync = null;
293
+ }
294
+ });
295
+ this.runningSync = run;
296
+ return run;
297
+ }
298
+
299
+ private async runReplay(isEager: boolean): Promise<SyncResult> {
300
+ if (this.directSend !== null) {
301
+ await this.directSend.catch(() => undefined);
302
+ }
303
+ const report = await this.outbox.replay(isEager);
304
+ const conflicts = report.failed.map((failure) => ({ op: failure.entry, error: failure.error }));
305
+ if (report.stoppedBy !== 'connection') {
306
+ await this.flushEvents();
307
+ }
308
+ const result: SyncResult = { flushed: report.replayed.length, conflicts };
309
+ emitWindowEvent('hub:sync', { pending: this.pending(), ...result });
310
+ this.notifyStatus();
311
+ return result;
312
+ }
313
+
314
+ /** Send the buffered analytics events; a refused one is dropped (telemetry never blocks). */
315
+ private async flushEvents(): Promise<void> {
316
+ let events = this.store.getEvents();
317
+ for (let event = events[0]; event !== undefined; event = events[0]) {
318
+ try {
319
+ await this.rest.call('recordGameEvent', { ...this.gameFields(), type: event.type });
320
+ } catch (failure) {
321
+ if (isTransportFailure(failure)) {
322
+ return;
323
+ }
324
+ }
325
+ events = events.slice(1);
326
+ this.store.setEvents(events);
327
+ }
328
+ }
329
+
330
+ /** Move a v1 copy's queued writes into the outbox, in their order. */
331
+ private importLegacyQueue(): void {
332
+ if (this.slug === null) {
333
+ return;
334
+ }
335
+ try {
336
+ for (const legacy of this.store.takeLegacyQueue()) {
337
+ const operation = legacyOperation(legacy);
338
+ if (operation !== undefined) {
339
+ this.outbox.add(this.outbox.stamp(operation.kind, operation.payload));
340
+ }
341
+ }
342
+ } catch {
343
+ // A full outbox keeps what fitted; the client must still start.
344
+ }
345
+ }
346
+
347
+ /** Follow the browser's connection, other tabs' outbox changes, and replay what an earlier page left queued. */
348
+ private listenToPage(): void {
349
+ window.addEventListener('online', () => {
350
+ this.setReachable(true);
351
+ });
352
+ window.addEventListener('offline', () => {
353
+ this.setReachable(false);
354
+ });
355
+ window.addEventListener('storage', (event) => {
356
+ if (event instanceof StorageEvent && this.outbox.entries.owns(event.key)) {
357
+ this.notifyStatus();
358
+ }
359
+ });
360
+ if (this.outbox.count() > 0) {
361
+ setTimeout(() => {
362
+ void this.sync();
363
+ }, 0);
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Warm the offline cache for every game the player has touched, in one
369
+ * request, so going offline later still shows complete progress.
370
+ * Throttled to once per 30 s unless `isForced`; `null` when offline or throttled.
371
+ */
372
+ async prefetchAll(isForced = false): Promise<SnapshotResponse | null> {
373
+ if (this.isOffline || (!isForced && Date.now() - this.lastPrefetchAt < PREFETCH_INTERVAL_MS)) {
374
+ return null;
375
+ }
376
+ let snapshot: SnapshotResponse;
377
+ try {
378
+ snapshot = await this.rest.call('getMyOfflineSnapshot');
379
+ } catch (failure) {
380
+ if (isTransportFailure(failure)) {
381
+ return null;
382
+ }
383
+ throw failure;
384
+ }
385
+ this.lastPrefetchAt = Date.now();
386
+ if (this.outbox.count() > 0) {
387
+ // Changes are still waiting to sync: the cache already holds them, and the snapshot doesn't yet.
388
+ return snapshot;
389
+ }
390
+ this.store.hydrate(snapshot);
391
+ emitWindowEvent('hub:prefetch', { games: Object.keys(snapshot.games).length });
392
+ return snapshot;
393
+ }
394
+ }