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

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