@ksaa-nlp/gamehub-react-native-sdk 0.0.0-stage → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +315 -2
- package/SPEC.md +294 -0
- package/dist/src/answers.d.ts +5 -0
- package/dist/src/answers.d.ts.map +1 -0
- package/dist/src/answers.js +32 -0
- package/dist/src/answers.js.map +1 -0
- package/dist/src/api-client.d.ts +7 -0
- package/dist/src/api-client.d.ts.map +1 -0
- package/dist/src/api-client.js +123 -0
- package/dist/src/api-client.js.map +1 -0
- package/dist/src/config.d.ts +15 -0
- package/dist/src/config.d.ts.map +1 -0
- package/dist/src/config.js +45 -0
- package/dist/src/config.js.map +1 -0
- package/dist/src/constants.d.ts +6 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/constants.js +6 -0
- package/dist/src/constants.js.map +1 -0
- package/dist/src/content.d.ts +7 -0
- package/dist/src/content.d.ts.map +1 -0
- package/dist/src/content.js +70 -0
- package/dist/src/content.js.map +1 -0
- package/dist/src/host-events.d.ts +7 -0
- package/dist/src/host-events.d.ts.map +1 -0
- package/dist/src/host-events.js +20 -0
- package/dist/src/host-events.js.map +1 -0
- package/dist/src/identity.d.ts +10 -0
- package/dist/src/identity.d.ts.map +1 -0
- package/dist/src/identity.js +27 -0
- package/dist/src/identity.js.map +1 -0
- package/dist/src/index.d.ts +6 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +75 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/launch.d.ts +16 -0
- package/dist/src/launch.d.ts.map +1 -0
- package/dist/src/launch.js +115 -0
- package/dist/src/launch.js.map +1 -0
- package/dist/src/loading.d.ts +8 -0
- package/dist/src/loading.d.ts.map +1 -0
- package/dist/src/loading.js +96 -0
- package/dist/src/loading.js.map +1 -0
- package/dist/src/lobby-request.d.ts +4 -0
- package/dist/src/lobby-request.d.ts.map +1 -0
- package/dist/src/lobby-request.js +46 -0
- package/dist/src/lobby-request.js.map +1 -0
- package/dist/src/lobby.d.ts +34 -0
- package/dist/src/lobby.d.ts.map +1 -0
- package/dist/src/lobby.js +311 -0
- package/dist/src/lobby.js.map +1 -0
- package/dist/src/match-context.d.ts +10 -0
- package/dist/src/match-context.d.ts.map +1 -0
- package/dist/src/match-context.js +41 -0
- package/dist/src/match-context.js.map +1 -0
- package/dist/src/multiplayer-client.d.ts +27 -0
- package/dist/src/multiplayer-client.d.ts.map +1 -0
- package/dist/src/multiplayer-client.js +163 -0
- package/dist/src/multiplayer-client.js.map +1 -0
- package/dist/src/multiplayer-react.d.ts +4 -0
- package/dist/src/multiplayer-react.d.ts.map +1 -0
- package/dist/src/multiplayer-react.js +8 -0
- package/dist/src/multiplayer-react.js.map +1 -0
- package/dist/src/multiplayer-storage.d.ts +22 -0
- package/dist/src/multiplayer-storage.d.ts.map +1 -0
- package/dist/src/multiplayer-storage.js +65 -0
- package/dist/src/multiplayer-storage.js.map +1 -0
- package/dist/src/multiplayer-types.d.ts +56 -0
- package/dist/src/multiplayer-types.d.ts.map +1 -0
- package/dist/src/multiplayer-types.js +2 -0
- package/dist/src/multiplayer-types.js.map +1 -0
- package/dist/src/multiplayer.d.ts +5 -0
- package/dist/src/multiplayer.d.ts.map +1 -0
- package/dist/src/multiplayer.js +4 -0
- package/dist/src/multiplayer.js.map +1 -0
- package/dist/src/react.d.ts +12 -0
- package/dist/src/react.d.ts.map +1 -0
- package/dist/src/react.js +24 -0
- package/dist/src/react.js.map +1 -0
- package/dist/src/score.d.ts +9 -0
- package/dist/src/score.d.ts.map +1 -0
- package/dist/src/score.js +168 -0
- package/dist/src/score.js.map +1 -0
- package/dist/src/session-view.d.ts +4 -0
- package/dist/src/session-view.d.ts.map +1 -0
- package/dist/src/session-view.js +276 -0
- package/dist/src/session-view.js.map +1 -0
- package/dist/src/session.d.ts +10 -0
- package/dist/src/session.d.ts.map +1 -0
- package/dist/src/session.js +221 -0
- package/dist/src/session.js.map +1 -0
- package/dist/src/settings.d.ts +4 -0
- package/dist/src/settings.d.ts.map +1 -0
- package/dist/src/settings.js +40 -0
- package/dist/src/settings.js.map +1 -0
- package/dist/src/types.d.ts +137 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +2 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/utils.d.ts +5 -0
- package/dist/src/utils.d.ts.map +1 -0
- package/dist/src/utils.js +16 -0
- package/dist/src/utils.js.map +1 -0
- package/dist/vendor/colyseus-schemas/clock.d.ts +15 -0
- package/dist/vendor/colyseus-schemas/clock.js +67 -0
- package/dist/vendor/colyseus-schemas/common.d.ts +35 -0
- package/dist/vendor/colyseus-schemas/common.js +15 -0
- package/dist/vendor/colyseus-schemas/multiplayer.d.ts +8 -0
- package/dist/vendor/colyseus-schemas/multiplayer.js +26 -0
- package/dist/vendor/colyseus-schemas/ugc.d.ts +53 -0
- package/dist/vendor/colyseus-schemas/ugc.js +124 -0
- package/dist/vendor/gamehub-multiplayer-contracts/index.d.ts +200 -0
- package/dist/vendor/gamehub-multiplayer-contracts/index.js +289 -0
- package/dist/vendor/loading.d.ts +6 -0
- package/dist/vendor/loading.d.ts.map +1 -0
- package/dist/vendor/loading.js +2 -0
- package/dist/vendor/loading.js.map +1 -0
- package/dist/vendor/match.d.ts +37 -0
- package/dist/vendor/match.d.ts.map +1 -0
- package/dist/vendor/match.js +2 -0
- package/dist/vendor/match.js.map +1 -0
- package/dist/vendor/multiplayer-client.d.ts +52 -0
- package/dist/vendor/multiplayer-client.d.ts.map +1 -0
- package/dist/vendor/multiplayer-client.js +286 -0
- package/dist/vendor/multiplayer-client.js.map +1 -0
- package/dist/vendor/multiplayer-session.d.ts +82 -0
- package/dist/vendor/multiplayer-session.d.ts.map +1 -0
- package/dist/vendor/multiplayer-session.js +2 -0
- package/dist/vendor/multiplayer-session.js.map +1 -0
- package/dist/vendor/question.d.ts +35 -0
- package/dist/vendor/question.d.ts.map +1 -0
- package/dist/vendor/question.js +20 -0
- package/dist/vendor/question.js.map +1 -0
- package/dist/vendor/session.d.ts +174 -0
- package/dist/vendor/session.d.ts.map +1 -0
- package/dist/vendor/session.js +2 -0
- package/dist/vendor/session.js.map +1 -0
- package/dist/vendor/word.d.ts +147 -0
- package/dist/vendor/word.d.ts.map +1 -0
- package/dist/vendor/word.js +15 -0
- package/dist/vendor/word.js.map +1 -0
- package/package.json +90 -4
package/README.md
CHANGED
|
@@ -1,3 +1,316 @@
|
|
|
1
|
-
#
|
|
1
|
+
# GameHub SDK for React Native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
GameHub sessions, scores, questions, words and league matches for **native React
|
|
4
|
+
Native games**. Supports Expo and bare React Native without native modules.
|
|
5
|
+
This is separate from the browser SDK and the GameHub Expo host application.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @ksaa-nlp/gamehub-react-native-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Inside this monorepo, add `"@ksaa-nlp/gamehub-react-native-sdk": "*"` to the
|
|
12
|
+
consumer workspace dependencies and install from the repository root.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { createSdk } from '@ksaa-nlp/gamehub-react-native-sdk';
|
|
16
|
+
|
|
17
|
+
// Read these values from your app's environment and authentication state.
|
|
18
|
+
const sdk = createSdk({
|
|
19
|
+
apiBaseUrl: config.gameHubApiUrl, // e.g. https://your-gamehub.example/api
|
|
20
|
+
gameSlug: 'my-native-game',
|
|
21
|
+
authToken: accountToken,
|
|
22
|
+
profileId: selectedProfileId, // optional question/word profile
|
|
23
|
+
onHostEvent(event) {
|
|
24
|
+
if (event.type === 'REQUEST_CLOSE') navigation.goBack();
|
|
25
|
+
if (event.type === 'GAME_COMPLETE') showResults(event.payload);
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const questions = await sdk.getQuestions({ difficulty: 'easy', limit: 10 });
|
|
30
|
+
const words = await sdk.getWords({ limit: 10 });
|
|
31
|
+
|
|
32
|
+
// Start when play begins, so server-measured duration includes gameplay.
|
|
33
|
+
const session = await sdk.startSession();
|
|
34
|
+
if (!session.success) showSessionError(session.error);
|
|
35
|
+
|
|
36
|
+
const outcome = await sdk.submitScore(100, { attempts: 3 });
|
|
37
|
+
if (outcome.success) showAcceptedScore(outcome);
|
|
38
|
+
else if (!outcome.terminal) showRetryOrError(outcome);
|
|
39
|
+
|
|
40
|
+
// Call on logout, account change, or token replacement.
|
|
41
|
+
sdk.setAuthToken(nextAccountToken ?? null);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Create one stable SDK instance per game context. It owns in-memory session state;
|
|
45
|
+
recreating it discards retries. `submitScore` can start a session automatically,
|
|
46
|
+
but explicitly starting when gameplay begins records a useful server duration.
|
|
47
|
+
An accepted or terminally rejected score clears the session for the next round.
|
|
48
|
+
Unknown or retriable results keep the original payload: retry with the same score
|
|
49
|
+
and metadata. There is no automatic retry and changed submissions are refused.
|
|
50
|
+
|
|
51
|
+
React integration is optional:
|
|
52
|
+
|
|
53
|
+
```tsx
|
|
54
|
+
import { GameHubProvider, useGameHubSdk, useGameHubSettings }
|
|
55
|
+
from '@ksaa-nlp/gamehub-react-native-sdk/react';
|
|
56
|
+
|
|
57
|
+
function NativeGame() {
|
|
58
|
+
const sdk = useGameHubSdk();
|
|
59
|
+
const { musicEnabled } = useGameHubSettings();
|
|
60
|
+
// Apply musicEnabled to your own audio engine.
|
|
61
|
+
return <GameScreen onExit={() => sdk.requestClose()} musicEnabled={musicEnabled} />;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function GameRoot() {
|
|
65
|
+
return <GameHubProvider sdk={sdk}><NativeGame /></GameHubProvider>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Synchronize this from the account preferences managed by your application.
|
|
69
|
+
sdk.setSettings({ musicEnabled: currentUser.gamePreferences.musicEnabled });
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`getSettings()` returns a stable immutable snapshot; music defaults off.
|
|
73
|
+
`onSettingsChange` emits immediately and returns an unsubscribe function.
|
|
74
|
+
The provider requires an existing SDK instance and does not start requests.
|
|
75
|
+
React 18.2 or 19 is required only for the `/react` entry. Core imports do not
|
|
76
|
+
load React, React Native, Expo, a WebView, or any realtime transport.
|
|
77
|
+
|
|
78
|
+
Answer recording is available in 1.3.0. Report each answered question; the
|
|
79
|
+
SDK batches answers and sends them before the score:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
sdk.recordAnswer({ questionId: q.id, correct, choice, timeMs, level });
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Platform-owned loading is available in 1.2.0:
|
|
86
|
+
|
|
87
|
+
```tsx
|
|
88
|
+
import { useGameHubLoading } from '@ksaa-nlp/gamehub-react-native-sdk/react';
|
|
89
|
+
|
|
90
|
+
function HostedGame() {
|
|
91
|
+
const loading = useGameHubLoading();
|
|
92
|
+
return <GameContainer loading={loading} />;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
sdk.setLoading('loading');
|
|
96
|
+
try {
|
|
97
|
+
await loadGameAssets();
|
|
98
|
+
sdk.setLoading(null); // Reveal the interactive tutorial/game.
|
|
99
|
+
} catch {
|
|
100
|
+
sdk.setLoading('failed');
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The host should keep the game mounted, block game input while busy, retain close
|
|
105
|
+
controls, and offer retry on failure or a bounded wait. `getLoading()` and
|
|
106
|
+
`onLoadingChange(listener)` expose the same effective state outside React.
|
|
107
|
+
Subscriptions emit immediately; `onHostEvent` also receives `LOADING_STATE` with
|
|
108
|
+
`payload.state` on transitions. States are `loading`, `waiting-for-players`,
|
|
109
|
+
`reconnecting`, `failed` and `null`. `ready()` signals SDK configuration, not asset
|
|
110
|
+
readiness. Asset loading must be cleared before an interactive tutorial.
|
|
111
|
+
|
|
112
|
+
`MultiplayerClient` reports its connection/wait/recovery states automatically
|
|
113
|
+
through optional `setLoading(state, launch)`. Games normally omit `launch`:
|
|
114
|
+
the connection and asset channels cannot clear one another. Failed and recovery
|
|
115
|
+
states take precedence, then asset loading, then player waiting. The SDK rejects
|
|
116
|
+
stale launch identities and clears connection state on round replacement or a
|
|
117
|
+
terminal lobby update; authentication changes, completion and close clear both
|
|
118
|
+
channels. Loading subscriptions do not start network requests or lobby polling.
|
|
119
|
+
Existing custom launch hosts without `setLoading` remain supported.
|
|
120
|
+
|
|
121
|
+
League games configure `leagueId`, `gameId` and optionally `matchId` on creation.
|
|
122
|
+
Use `getMatchContext()`, `submitMatchScore(score, meta)` or
|
|
123
|
+
`submitMatchResult(result)` as appropriate; server admission rules still apply.
|
|
124
|
+
Sessions and content use the same HTTP contracts as the browser SDK. Shared
|
|
125
|
+
contract types (`Question`, `Word`, `ScoreMetadata`, `SubmitScoreResult`,
|
|
126
|
+
`MatchContext`, etc.) are exported from this package.
|
|
127
|
+
|
|
128
|
+
The API URL is required and includes `/api` and any deployment prefix. HTTPS is
|
|
129
|
+
required; HTTP loopback URLs are permitted for local development. On a physical
|
|
130
|
+
device, use a reachable HTTPS development server. Auth tokens are kept in memory;
|
|
131
|
+
your app owns login and secure persistence. Requests time out after 15 seconds
|
|
132
|
+
by default (`requestTimeoutMs` overrides this). A custom `fetch` can be injected.
|
|
133
|
+
Auth changes invalidate pending results, sessions, and cached league context.
|
|
134
|
+
|
|
135
|
+
`notifyComplete`, `requestClose`, `reportQuestion`, `reportWord` and `logEvent`
|
|
136
|
+
send typed events to `onHostEvent`. Your application supplies navigation, result
|
|
137
|
+
screens, report forms and analytics handlers. These methods do nothing without
|
|
138
|
+
that callback. They do not open platform UI or send reports by themselves.
|
|
139
|
+
|
|
140
|
+
Existing web games inside a native WebView continue to use
|
|
141
|
+
`@ksaa-nlp/gamehub-sdk`. Version 1.1 adds optional native multiplayer below.
|
|
142
|
+
The [SPEC](./SPEC.md) defines precise behavior and usage-report boundaries.
|
|
143
|
+
|
|
144
|
+
From the monorepo root:
|
|
145
|
+
|
|
146
|
+
```sh
|
|
147
|
+
npm run build:sdk:native
|
|
148
|
+
npm run test:sdk:native
|
|
149
|
+
npm run test:sdk:native:metro # Expo 54 iOS/Android export and React resolution smoke
|
|
150
|
+
npm -w @ksaa-nlp/gamehub-react-native-sdk run typecheck
|
|
151
|
+
npm -w @ksaa-nlp/gamehub-react-native-sdk run typecheck:consumer
|
|
152
|
+
npm -w @ksaa-nlp/gamehub-react-native-sdk pack --dry-run
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The root `npm run build` builds deployed services. Build and test this SDK
|
|
156
|
+
separately with the native commands above.
|
|
157
|
+
|
|
158
|
+
Builds copy the canonical HTTP type files from `packages/gamehub-sdk/types/`
|
|
159
|
+
unchanged, then compile them locally. Generated `vendor/` and `dist/` files must
|
|
160
|
+
not be edited. Published consumers need no sibling workspace packages.
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
## Native multiplayer
|
|
164
|
+
|
|
165
|
+
Install the realtime peers only when the game uses multiplayer:
|
|
166
|
+
|
|
167
|
+
```sh
|
|
168
|
+
npm install @colyseus/sdk @colyseus/schema
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
For Expo 54/Metro, select the browser fallback for `ws` in your existing
|
|
172
|
+
`metro.config.js`. React Native supplies `globalThis.WebSocket`; the Node `ws`
|
|
173
|
+
implementation must stay out of the mobile bundle. Keep your existing Expo
|
|
174
|
+
configuration and add this before exporting it:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
const previousResolver = config.resolver.resolveRequest;
|
|
178
|
+
config.resolver.resolveRequest = (context, moduleName, platform) => {
|
|
179
|
+
if (moduleName === 'ws' && (platform === 'ios' || platform === 'android')) {
|
|
180
|
+
return context.resolveRequest({
|
|
181
|
+
...context,
|
|
182
|
+
unstable_enablePackageExports: false,
|
|
183
|
+
mainFields: ['react-native', 'browser', 'main'],
|
|
184
|
+
}, moduleName, platform);
|
|
185
|
+
}
|
|
186
|
+
return previousResolver
|
|
187
|
+
? previousResolver(context, moduleName, platform)
|
|
188
|
+
: context.resolveRequest(context, moduleName, platform);
|
|
189
|
+
};
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
This uses Metro's [per-package resolver configuration](https://metrobundler.dev/docs/package-exports/#example-custom-resolver).
|
|
193
|
+
The iOS/Android smoke check exercises this setup and checks for one React and
|
|
194
|
+
one schema runtime. In monorepos, keep Expo's
|
|
195
|
+
`experiments.autolinkingModuleResolution` enabled so hooks resolve to the app's
|
|
196
|
+
React. Native multiplayer type consumers also include `ES2021.WeakRef` for
|
|
197
|
+
the canonical schema declarations, alongside React Native globals.
|
|
198
|
+
|
|
199
|
+
Configure the SDK with a stable host identity and a secure ID generator from
|
|
200
|
+
your app. Keep one SDK instance per game and identity context.
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { createSdk } from '@ksaa-nlp/gamehub-react-native-sdk';
|
|
204
|
+
import { MultiplayerClient } from '@ksaa-nlp/gamehub-react-native-sdk/multiplayer';
|
|
205
|
+
import { AppState } from 'react-native';
|
|
206
|
+
|
|
207
|
+
const sdk = createSdk({
|
|
208
|
+
apiBaseUrl: config.gameHubApiUrl,
|
|
209
|
+
gameSlug: 'my-native-game',
|
|
210
|
+
authToken: accountToken,
|
|
211
|
+
multiplayer: {
|
|
212
|
+
hostInstanceId: persistedHostId,
|
|
213
|
+
createId: () => secureRandomUuid(), // supplied by your app
|
|
214
|
+
// sessionId: persistedSessionId, // restore with an explicit read
|
|
215
|
+
// resumeToken: secureGuestCredential, // existing guest join policy only
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
const unsubscribe = sdk.onMultiplayerSessionChange(({ session, error }) => {
|
|
220
|
+
renderLobby(session, error);
|
|
221
|
+
});
|
|
222
|
+
const created = await sdk.requestMultiplayerSession({ operation: 'create', type: 'player' });
|
|
223
|
+
// Or join: { operation: 'join', roomCode: '123456', displayName: 'Player', type: 'player' }
|
|
224
|
+
if (created.success) {
|
|
225
|
+
await sdk.requestMultiplayerSession({ operation: 'ready', ready: true });
|
|
226
|
+
// The host starts when the required players are ready.
|
|
227
|
+
await sdk.requestMultiplayerSession({ operation: 'start' });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const launch = sdk.getMultiplayerLaunch();
|
|
231
|
+
if (launch) {
|
|
232
|
+
const client = new MultiplayerClient(sdk, launch, {
|
|
233
|
+
appState: AppState,
|
|
234
|
+
storage: reconnectStorage, // optional sync/async getItem/setItem/removeItem
|
|
235
|
+
});
|
|
236
|
+
const stop = client.subscribe((snapshot) => {
|
|
237
|
+
const counter = snapshot.state?.game.get('counter');
|
|
238
|
+
if (counter) renderCounter(JSON.parse(counter.json));
|
|
239
|
+
renderConnection(snapshot.status, snapshot.error);
|
|
240
|
+
});
|
|
241
|
+
await client.connect();
|
|
242
|
+
client.send('increment', { amount: 1 }); // your approved UGC action protocol
|
|
243
|
+
// On exit: stop(); await client.leave();
|
|
244
|
+
}
|
|
245
|
+
// On leaving the lobby: await sdk.requestMultiplayerSession({ operation: 'leave' });
|
|
246
|
+
// On unmount: unsubscribe();
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Applications own lobby UI, secure identity/credential persistence and login.
|
|
250
|
+
Account tokens are sent as Bearer credentials; guest resume tokens only enable
|
|
251
|
+
the backend's existing join/resume flow. Store the session ID if the app needs
|
|
252
|
+
to restore a lobby after restart, then request `{operation:'read'}`. No guest
|
|
253
|
+
creation permission is granted. Server code remains authored through the browser
|
|
254
|
+
SDK's `/server` and `/server/dev` entries and runs only on the server.
|
|
255
|
+
|
|
256
|
+
`requestMultiplayerLaunch()` exposes reserved, recoverable and terminal outcomes;
|
|
257
|
+
the client consumes reservations automatically. The SDK validates game, host,
|
|
258
|
+
seat and round binding. Solo/league scoring is blocked while multiplayer owns
|
|
259
|
+
the context. Since 1.1.1, a failed initial create/join with no bound session
|
|
260
|
+
releases that ownership, so your app can explicitly start solo/league play
|
|
261
|
+
without calling `leave`. Create retries keep their idempotency key. Failed
|
|
262
|
+
operations on a bound session or pending restoration keep ownership.
|
|
263
|
+
Only a server-acknowledged `ctx.endMatch` completes multiplayer.
|
|
264
|
+
Native and browser clients use the same schema/actions/results and approved
|
|
265
|
+
UGC server package. Their installed game protocol must match; the SDK does not
|
|
266
|
+
perform automatic version negotiation or native OTA updates.
|
|
267
|
+
|
|
268
|
+
`./react` exports `useGameHubMultiplayerSession()` for lobby UI inside
|
|
269
|
+
`GameHubProvider`. The optional `./multiplayer/react` entry exports
|
|
270
|
+
`useMultiplayerSnapshot(client)` for an existing round client. Hooks unsubscribe
|
|
271
|
+
on unmount; create a new round client after rematch. Returning to an active app
|
|
272
|
+
resumes the core connection without leaving on background. Recovery remains
|
|
273
|
+
bounded by the backend's grace window. Async storage failures allow memory-only
|
|
274
|
+
play and are visible as `storageAvailable:false`.
|
|
275
|
+
|
|
276
|
+
Main and `./react` imports remain free of realtime transports. The published
|
|
277
|
+
package includes build-time copies of the unchanged browser core and shared
|
|
278
|
+
contracts/schemas; it does not depend on the browser SDK at runtime.
|
|
279
|
+
|
|
280
|
+
## Source responsibilities and browser SDK comparison
|
|
281
|
+
|
|
282
|
+
The native SDK implements the browser SDK's game-facing HTTP, settings, lobby,
|
|
283
|
+
launch and realtime capabilities. Its app supplies configuration and account
|
|
284
|
+
tokens explicitly; host events call `onHostEvent`. These callbacks require app
|
|
285
|
+
handlers to show UI, submit reports or record analytics. Native settings are
|
|
286
|
+
synchronized by the app. Browser-only bootstrap and server tools are not native
|
|
287
|
+
client responsibilities.
|
|
288
|
+
|
|
289
|
+
Every file in `packages/gamehub-sdk/src/` maps as follows:
|
|
290
|
+
|
|
291
|
+
| Browser source | Native implementation or platform difference |
|
|
292
|
+
| --- | --- |
|
|
293
|
+
| `main.ts` | `index.ts` composes an isolated client; native contracts live in `types.ts`. Native adds token/settings setters and direct lobby/launch getters. |
|
|
294
|
+
| `api-client.ts` | `api-client.ts` calls HTTP directly with Bearer/resume headers, timeouts and response validation. |
|
|
295
|
+
| `session.ts` | `session.ts` owns sessions/submissions; `score.ts` validates/normalizes scores; `content.ts` fetches questions/words. |
|
|
296
|
+
| `match-context.ts` | `match-context.ts` owns cached league-match reads. |
|
|
297
|
+
| `settings.ts` | `settings.ts` owns immutable preferences and subscriptions; the app calls `setSettings`. |
|
|
298
|
+
| `state.ts` | State is owned by individual native factories/classes; `identity.ts` owns token generations. No shared singleton. |
|
|
299
|
+
| `constants.ts` | `constants.ts` owns native version/defaults/limits. Browser message prefixes/timeouts are unnecessary. |
|
|
300
|
+
| `utils.ts` | `utils.ts` provides native JSON helpers. Browser detection, URL query discovery and browser logging helpers are not carried over. |
|
|
301
|
+
| `init.ts` | `config.ts` validates explicit app configuration; `identity.ts` supports token changes. No automatic bootstrap/session start or browser pause/resume globals. |
|
|
302
|
+
| `bridge.ts` | HTTP goes through `api-client.ts`; one-way host signals go through `host-events.ts`. No browser handshake, bootstrap snapshot or correlated host API proxy. |
|
|
303
|
+
| `transport.ts` | Direct native fetch and app callbacks replace iframe postMessage/WebView transport. The native SDK does not wrap a WebView. |
|
|
304
|
+
| `browser-entry.ts` | Intentionally absent: native apps import the factory; there is no script-tag/global singleton or `isInIframe` API. |
|
|
305
|
+
| `multiplayer-session.ts` | `lobby.ts` performs native HTTP session operations/polling; `lobby-request.ts` validates inputs and `session-view.ts` validates responses. Native returns the shared HTTP `SessionView`, rather than the browser host's lobby projection. |
|
|
306
|
+
| `multiplayer.ts` | `launch.ts` performs bound HTTP reservations with stale-context fencing. Native `multiplayer.ts` is the optional realtime package entry. |
|
|
307
|
+
| `multiplayer-client.ts` | Copied unchanged at build time into generated `vendor/`; native `multiplayer-client.ts` adapts app lifecycle and `multiplayer-storage.ts` adapts async storage. `multiplayer-types.ts` owns native interfaces. |
|
|
308
|
+
| `multiplayer-entry.ts` | Native `multiplayer.ts` exports the adapter and shared wire contracts; realtime peers remain optional. |
|
|
309
|
+
| `server-entry.ts` | Intentionally stays in the browser SDK's `/server` entry for authoring UGC server code. |
|
|
310
|
+
| `server-dev-harness.ts` | Intentionally stays in the browser SDK's `/server/dev` entry for local server tests. |
|
|
311
|
+
| `bot-driver.ts` | Intentionally stays in the server authoring SDK. Native clients can manage bot seats and receive their state; bot moves execute on the server. |
|
|
312
|
+
|
|
313
|
+
`react.ts` additionally owns the native provider and SDK/settings/lobby hooks;
|
|
314
|
+
`multiplayer-react.ts` owns the realtime snapshot hook. Neither duplicates the
|
|
315
|
+
realtime core. The complete native file ownership contract is in
|
|
316
|
+
[SPEC.md — Source ownership](./SPEC.md#source-ownership).
|
package/SPEC.md
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
# GameHub React Native SDK
|
|
2
|
+
|
|
3
|
+
Version: 1.3.0. Status: authoritative.
|
|
4
|
+
|
|
5
|
+
## Purpose and boundaries
|
|
6
|
+
|
|
7
|
+
`@ksaa-nlp/gamehub-react-native-sdk` is a sibling npm workspace for games
|
|
8
|
+
implemented directly in React Native. It uses the existing GameHub HTTP APIs;
|
|
9
|
+
it is independent of the browser SDK singleton and of the Expo application.
|
|
10
|
+
It does not wrap a WebView, implement login/navigation, or grant guest
|
|
11
|
+
admission. Optional native multiplayer uses the existing HTTP admission and
|
|
12
|
+
Colyseus round protocol; server authoring remains in the browser SDK server
|
|
13
|
+
entries. The main and `./react` entries stay transport-agnostic. Existing web games keep using
|
|
14
|
+
`@ksaa-nlp/gamehub-sdk`, including its native WebView bridge.
|
|
15
|
+
|
|
16
|
+
## Configuration and public API
|
|
17
|
+
|
|
18
|
+
`createSdk(options): NativeSdk` constructs an isolated client without starting
|
|
19
|
+
network activity. Required options are `apiBaseUrl` (absolute HTTP(S) API root,
|
|
20
|
+
including `/api`, with an optional deployment prefix) and nonempty `gameSlug`.
|
|
21
|
+
No production origin is embedded. URLs containing credentials, query or hash
|
|
22
|
+
are rejected. HTTPS is required except HTTP loopback development hosts.
|
|
23
|
+
Optional options: `authToken`, `gameId`, `leagueId`, `matchId`, `profileId`,
|
|
24
|
+
`settings: {musicEnabled:boolean}`, `fetch` (injectable Fetch-compatible
|
|
25
|
+
transport), `requestTimeoutMs` (positive finite, default 15000), and `onHostEvent`.
|
|
26
|
+
`gameId` is required with `leagueId`; `leagueId` is required with `matchId`.
|
|
27
|
+
|
|
28
|
+
Public methods:
|
|
29
|
+
|
|
30
|
+
- `version`, `getGameSlug()`, `isInitialized()`, `isAuthenticated()`,
|
|
31
|
+
`hasActiveSession()`, `ready(): Promise<boolean>` (configuration is synchronous).
|
|
32
|
+
- `setAuthToken(token: string | null)` clears sessions and cached match context
|
|
33
|
+
when changed. In-flight work captures its identity epoch and cannot publish
|
|
34
|
+
state, events, or successful results into a newer identity. Apps call this
|
|
35
|
+
on logout, login, or token replacement; tokens remain in memory only.
|
|
36
|
+
- `startSession()`, `submitScore(score, meta?)`, `submitMatchScore(score, meta?)`,
|
|
37
|
+
`submitMatchResult(result?)`, `getMatchContext()` follow the browser SDK's
|
|
38
|
+
HTTP result types and endpoint selection. Each path segment is encoded.
|
|
39
|
+
- `recordAnswer(answer)` (1.3.0) follows the browser SDK 5.5.0 contract: same
|
|
40
|
+
validation, only a signed-in standalone session with a 24-hex token (no
|
|
41
|
+
league, no multiplayer ownership), per-session `seq` 0–499, batches of at most
|
|
42
|
+
50 posted to `/sessions/answers` at ten queued answers, three seconds after
|
|
43
|
+
the last one, and before `submitScore` sends a score. Failed batches are
|
|
44
|
+
dropped; an identity change stops pending batches.
|
|
45
|
+
- `getQuestions(options?)` and `getWords(options?)` use explicit profile options,
|
|
46
|
+
then configured profile. Limits default/cap at 100 questions and 50 words, must be finite positive
|
|
47
|
+
integers; invalid options/errors return `[]`. Questions normalize numeric
|
|
48
|
+
answers to strings. Failed match-context reads return `null`.
|
|
49
|
+
- `getSettings()`, `setSettings(settings)`, `onSettingsChange(listener)` manage
|
|
50
|
+
immutable in-memory snapshots. Subscriptions emit immediately and return an
|
|
51
|
+
unsubscribe function. Music defaults off. The caller synchronizes account
|
|
52
|
+
preferences; this package does not persist or fetch them automatically.
|
|
53
|
+
- `setLoading(state, launch?)`, `getLoading()` and `onLoadingChange(listener)`
|
|
54
|
+
provide platform-owned presentation state. States are `loading`,
|
|
55
|
+
`waiting-for-players`, `reconnecting`, `failed` or `null`. The stable snapshot
|
|
56
|
+
is that primitive state; subscriptions emit immediately and unsubscribe
|
|
57
|
+
independently. Optional `LOADING_STATE` host events carry `{state}` only when
|
|
58
|
+
effective state changes. Asset and multiplayer channels clear independently;
|
|
59
|
+
precedence is failed, reconnecting, loading, waiting, then null. Invalid states
|
|
60
|
+
and malformed or stale five-field launch identities are ignored. The optional
|
|
61
|
+
launch identifies the connection channel and must match the current active
|
|
62
|
+
launch; a game omits it for asset work. Round/terminal lobby changes clear stale
|
|
63
|
+
connection state without subscribing or starting polling. Authentication
|
|
64
|
+
changes, completion and close clear both channels; delayed connection updates
|
|
65
|
+
for that completed/closed launch are ignored. Loading is presentation only:
|
|
66
|
+
it never changes readiness, scoring, gameplay or server authority. SDK `ready()`
|
|
67
|
+
does not imply assets are ready.
|
|
68
|
+
- `notifyComplete(data?)`, `requestClose()`, `reportQuestion(data)`,
|
|
69
|
+
`reportWord(data)`, `logEvent(name, data?)` invoke optional `onHostEvent` with
|
|
70
|
+
`{type,payload}`. Types are `GAME_COMPLETE`, `REQUEST_CLOSE`, `QUESTION_REPORT`,
|
|
71
|
+
`WORD_REPORT`, `EVENT`, `SESSION_STARTED`, `SCORE_SUBMITTED`, `LOADING_STATE`. No callback means
|
|
72
|
+
no-op. Callback/listener exceptions cannot change an HTTP operation's result.
|
|
73
|
+
|
|
74
|
+
The `./react` subpath exports `GameHubProvider` (`sdk` and `children` props),
|
|
75
|
+
`useGameHubSdk()`, `useGameHubSettings()` and `useGameHubLoading()`. Hooks require the provider and
|
|
76
|
+
throw a clear error otherwise. The provider accepts an existing stable SDK
|
|
77
|
+
instance; it does not own its authentication or issue requests. Settings use
|
|
78
|
+
React's external-store subscription mechanism and unsubscribe on unmount.
|
|
79
|
+
React is an optional peer, required for React hook subpaths; the main entry does
|
|
80
|
+
not import React or React Native. No native modules/config plugins are needed.
|
|
81
|
+
|
|
82
|
+
## HTTP and session lifecycle
|
|
83
|
+
|
|
84
|
+
All requests attach the current account Bearer token if supplied, parse the
|
|
85
|
+
GameHub envelope, and have a bounded timeout. Non-JSON, malformed success or
|
|
86
|
+
transport failures must never be treated as accepted scores. HTTP failure
|
|
87
|
+
status overrides an inconsistent `success:true` envelope. Auth errors are
|
|
88
|
+
returned to the caller; the app owns login/revocation handling.
|
|
89
|
+
|
|
90
|
+
Standalone session start requires an account token. League session paths use
|
|
91
|
+
configured IDs and rely on backend admission. Concurrent starts are deduplicated.
|
|
92
|
+
Score validation follows browser bounds: finite 0..10,000,000 score (floored),
|
|
93
|
+
JSON object metadata, depth <=5, <=200 keys, <=100 characters per key, <=2048
|
|
94
|
+
characters per string, <=100 entries per array, <=32 KiB UTF-8, no prototype
|
|
95
|
+
keys or non-JSON values. Attempts normalize/cap at 1,000,000. Client timing is
|
|
96
|
+
never authoritative. Validation works without `TextEncoder` or Node globals.
|
|
97
|
+
|
|
98
|
+
Submissions are bound to the session plus normalized score/attempts/client
|
|
99
|
+
metadata. Concurrent equivalent submissions share a request; changed payloads
|
|
100
|
+
are rejected. Unknown/retriable outcomes retain the exact original request
|
|
101
|
+
for retry and never automatically retry. Accepted and terminal rejected
|
|
102
|
+
outcomes clear the session, permitting sequential rounds. Successful account
|
|
103
|
+
submissions require `status:accepted`, `terminal:true`, a session ID, and finite
|
|
104
|
+
server timing; legacy league `accepted:true,timeTaken` is also supported.
|
|
105
|
+
Results reuse the existing SDK discriminated union, including retry-after
|
|
106
|
+
details. Explicit identity changes invalidate all previous work.
|
|
107
|
+
|
|
108
|
+
## Source ownership
|
|
109
|
+
|
|
110
|
+
`src/index.ts` composes per-instance feature owners and exports the existing
|
|
111
|
+
public factory, version and types. It contains no HTTP, scoring, content,
|
|
112
|
+
settings or persistence implementation. Internal modules are not new package
|
|
113
|
+
subpaths or public APIs. The responsibility refactor preserves the 1.1.0
|
|
114
|
+
behavior and API; it does not add browser bootstrap or server-authoring APIs.
|
|
115
|
+
|
|
116
|
+
| Source | Responsibility |
|
|
117
|
+
| --- | --- |
|
|
118
|
+
| `config.ts` | Validate the fixed API URL, game/league/profile context and HTTP options. |
|
|
119
|
+
| `constants.ts` | Package version, request timeout and content limits. |
|
|
120
|
+
| `identity.ts` | In-memory account token and generation used to fence stale work. |
|
|
121
|
+
| `api-client.ts` | Fetch, auth/resume headers, bounded timeout, envelope parsing and identity fencing. |
|
|
122
|
+
| `session.ts` | Solo/league session lifecycle, submissions, deduplication, exact retries and terminal cleanup. |
|
|
123
|
+
| `score.ts` | Pure score/metadata validation, canonical payloads and result normalization. |
|
|
124
|
+
| `match-context.ts` | Cached, deduplicated league-match context reads and invalidation. |
|
|
125
|
+
| `content.ts` | Question/word queries, profiles, limits and answer normalization. |
|
|
126
|
+
| `settings.ts` | Immutable preference snapshots and subscriptions. |
|
|
127
|
+
| `loading.ts` | Independent asset/connection channels, effective loading snapshots and lifecycle fencing. |
|
|
128
|
+
| `host-events.ts` | Isolated callbacks for completion, close, reports, analytics and session/score events. |
|
|
129
|
+
| `lobby.ts` | Multiplayer session operations, ownership, revisions, immutable snapshots and polling. |
|
|
130
|
+
| `lobby-request.ts` | Validate allowed lobby operations and caller input fields. |
|
|
131
|
+
| `session-view.ts` | Validate and project server session, roster, round and result views. |
|
|
132
|
+
| `launch.ts` | Deduplicate and validate reservations against the current launch/generation. |
|
|
133
|
+
| `multiplayer.ts` | Optional realtime public entry and re-exports. |
|
|
134
|
+
| `multiplayer-client.ts` | Native round/lifecycle adapter around the unchanged generated realtime core. |
|
|
135
|
+
| `multiplayer-storage.ts` | Async token hydration, synchronous core cache, serialized persistence and disposal fencing. |
|
|
136
|
+
| `multiplayer-types.ts` | Native realtime, storage and lifecycle interfaces. |
|
|
137
|
+
| `react.ts` | Optional provider and SDK/settings/lobby hooks. |
|
|
138
|
+
| `multiplayer-react.ts` | Optional realtime snapshot hook. |
|
|
139
|
+
| `types.ts` | Native main-entry contracts and canonical HTTP type re-exports. |
|
|
140
|
+
| `utils.ts` | Internal JSON-object, nonnegative-integer and recursive-freeze helpers. |
|
|
141
|
+
|
|
142
|
+
Each feature owns its mutable state inside its factory or instance. The
|
|
143
|
+
composition root resets session and match state on identity changes or lobby
|
|
144
|
+
ownership; lobby changes invalidate bound realtime adapters. The browser core
|
|
145
|
+
continues to own sockets, schema synchronization, clock and reconnect behavior.
|
|
146
|
+
|
|
147
|
+
## Distribution and shared contracts
|
|
148
|
+
|
|
149
|
+
ESM JavaScript plus declarations under `dist/`, with `react-native` conditions
|
|
150
|
+
and ordinary import/default exports. Node test tooling is development-only.
|
|
151
|
+
`build:types` copies the unchanged `session`, `question`, `word`, and
|
|
152
|
+
`match`, `multiplayer-session` and `loading` TypeScript contract files from the browser SDK into generated `vendor/`;
|
|
153
|
+
the build compiles them into the package. Never hand-edit generated copies.
|
|
154
|
+
There is no runtime dependency on the browser SDK, private workspaces, Node,
|
|
155
|
+
DOM, or Expo. The optional realtime entries require the external peers
|
|
156
|
+
`@colyseus/sdk` and `@colyseus/schema`; React remains external. One root lockfile is used.
|
|
157
|
+
The native HTTP envelope exports `ApiResponse` (`data:unknown`), `ApiError`, and
|
|
158
|
+
`ApiErrorDetails`. Browser-only `ApiRequestOptions` is not exported. Declarations
|
|
159
|
+
must typecheck in a React Native consumer using ES2020 and React Native globals,
|
|
160
|
+
without DOM or `skipLibCheck`. The optional multiplayer entry additionally uses
|
|
161
|
+
`ES2021.WeakRef`, required by the canonical schema declarations.
|
|
162
|
+
|
|
163
|
+
SDK Usage Intelligence currently scans uploaded HTML/JavaScript game artifacts.
|
|
164
|
+
This package adds no public API to the browser SDK and no native artifact
|
|
165
|
+
ingestion to that report. Existing HTTP-backed feature IDs are observed by the
|
|
166
|
+
backend unchanged; native configuration, native lobby/realtime adapters, React hooks, and local host events
|
|
167
|
+
are outside that report's static inventory. No native usage coverage is claimed.
|
|
168
|
+
|
|
169
|
+
## Acceptance requirements
|
|
170
|
+
|
|
171
|
+
- REQ-001: New workspace builds, exposes main and React entries with declarations,
|
|
172
|
+
packs independently, and resolves in an Expo 54/Metro consumer. Main imports
|
|
173
|
+
without DOM, React, Node runtime modules, or browser singleton dependencies.
|
|
174
|
+
- REQ-002: Explicit validated configuration, isolated clients, bounded HTTP,
|
|
175
|
+
Bearer auth, token changes and stale-request suppression are covered by tests.
|
|
176
|
+
- REQ-003: Session deduplication, valid score results, terminal cleanup, exact
|
|
177
|
+
retries/conflicts, invalid metadata, and sequential rounds have executable tests.
|
|
178
|
+
- REQ-004: Content/profile and league endpoint selection, numeric answers,
|
|
179
|
+
settings snapshots/subscriptions, host events, and React provider/hooks have tests.
|
|
180
|
+
- REQ-005: README examples, package specification, workspace/build/lockfile wiring
|
|
181
|
+
and report coverage boundaries are documented; existing SDK tests still pass.
|
|
182
|
+
|
|
183
|
+
## Implementation plan
|
|
184
|
+
|
|
185
|
+
1. Add workspace metadata, native client, and generated shared type build.
|
|
186
|
+
2. Add optional React provider/hooks and package usage documentation.
|
|
187
|
+
3. Wire root builds and lockfile; document native/report boundaries.
|
|
188
|
+
4. Run native SDK and existing SDK tests, typecheck, pack inspection and Metro
|
|
189
|
+
consumer bundling; obtain independent code/security review and fix findings.
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
## Native multiplayer (1.1.0)
|
|
193
|
+
|
|
194
|
+
The acceptance contract and implementation plan for this extension are in
|
|
195
|
+
[React Native SDK UGC multiplayer](../../specs/react-native-sdk-multiplayer.md).
|
|
196
|
+
The shared backend protocol is [multiplayer v2](../../specs/multiplayer.md).
|
|
197
|
+
|
|
198
|
+
Optional `multiplayer` options contain `hostInstanceId` (1..160 base64url-style
|
|
199
|
+
ID characters), `createId():string` (app-supplied secure ID generation), optional
|
|
200
|
+
`resumeToken` (43..128 base64url characters), optional `sessionId` for restoring
|
|
201
|
+
an existing context with `read`, and `pollIntervalMs` (1000..60000, default 2500).
|
|
202
|
+
The SDK never generates weak credentials. Configuration performs no network
|
|
203
|
+
activity. Account Bearer and guest `x-gamehub-resume` credentials use existing
|
|
204
|
+
backend authorization; guest creation does not bypass account-only policy.
|
|
205
|
+
Apps persist their identity, session ID and credentials.
|
|
206
|
+
|
|
207
|
+
Main entry APIs:
|
|
208
|
+
|
|
209
|
+
- `requestMultiplayerSession(request)` accepts create, join, ready, read, start,
|
|
210
|
+
leave, rematch, add-bot and remove-bot operations. It returns
|
|
211
|
+
`NativeMultiplayerSessionResult`. SDK supplies game, host, profile, create key,
|
|
212
|
+
revision and round bindings; callers cannot override them.
|
|
213
|
+
- `getMultiplayerSession()` returns a stable immutable
|
|
214
|
+
`NativeMultiplayerSessionState` containing `{session:SessionView|null,busy,error,
|
|
215
|
+
disconnected}`. `onMultiplayerSessionChange(listener)` immediately emits that
|
|
216
|
+
snapshot, isolates callback errors and returns an unsubscribe function.
|
|
217
|
+
- `getMultiplayerLaunch()` returns the current validated `LaunchReference` or
|
|
218
|
+
null. `requestMultiplayerLaunch()` returns the shared `LaunchOutcome` union,
|
|
219
|
+
including reserved, recoverable and terminal variants.
|
|
220
|
+
- `./react` adds `useGameHubMultiplayerSession()`, using the existing provider
|
|
221
|
+
and React external-store subscription mechanism.
|
|
222
|
+
|
|
223
|
+
Omitted multiplayer configuration returns `PROTOCOL_UNSUPPORTED` without a
|
|
224
|
+
request. Equivalent concurrent operations deduplicate; conflicting work returns
|
|
225
|
+
`BUSY`. Create retries retain their idempotency key; successful leave rotates it.
|
|
226
|
+
While the first create/join is pending, multiplayer owns the context. If that
|
|
227
|
+
request fails without binding a session (including malformed responses,
|
|
228
|
+
transport errors or timeouts), ownership is released before the idle snapshot
|
|
229
|
+
is published. Callers can explicitly start solo/league play without calling
|
|
230
|
+
leave; create retries still retain their key. A bound session or pending
|
|
231
|
+
restoration keeps ownership after failed reads, mutations or leave requests.
|
|
232
|
+
Stale requests cannot release a newer identity's ownership.
|
|
233
|
+
New create/join operations are refused while a session is active or restoration
|
|
234
|
+
is pending. Session views validate version, game, roster, IDs, revisions and
|
|
235
|
+
bound round/seat/host launch references. Responses cannot regress either session
|
|
236
|
+
or round revision. Only successful `{left:true}` acknowledges leave.
|
|
237
|
+
|
|
238
|
+
All operations POST to the existing `/multiplayer/sessions`, `/join` or
|
|
239
|
+
`/:sessionId/:operation` routes beneath `apiBaseUrl`. Polling reads run only
|
|
240
|
+
while subscribed and bound to a session, with no overlapping reads. Last
|
|
241
|
+
unsubscribe, leave and authentication changes stop polling. Explicit reads work
|
|
242
|
+
without subscriptions. Malformed responses and HTTP/transport/timeout failures
|
|
243
|
+
remain typed failures. SDK identity changes fence pending lobby, reservation,
|
|
244
|
+
solo-session and score responses and clear lobby/launch state. Multiplayer
|
|
245
|
+
ownership blocks ordinary solo and league score submissions, including cached
|
|
246
|
+
solo tokens; multiplayer completion requires server-acknowledged `ctx.endMatch`.
|
|
247
|
+
|
|
248
|
+
`./multiplayer` exports `MultiplayerClient`, `MultiplayerSnapshot`,
|
|
249
|
+
`ConnectionStatus`, `LaunchHost`, `MultiplayerClientOptions`, `TokenStorage`,
|
|
250
|
+
`AppStateSource` and the shared wire contracts. Constructor:
|
|
251
|
+
`new MultiplayerClient(host, launch, {storage?, appState?, clientFactory?})`.
|
|
252
|
+
The native SDK is a compatible launch host. The client exposes `connect()`,
|
|
253
|
+
`subscribe(listener)`, `getSnapshot()`, `send(type,payload)`, `serverNow()` and
|
|
254
|
+
`leave()`. Each client belongs to one round; create another after rematch.
|
|
255
|
+
Host changes invalidate old clients and remove reconnect credentials. The
|
|
256
|
+
unchanged browser core owns reservation consumption, synchronization, clock and
|
|
257
|
+
bounded reconnect behavior. Game state uses canonical schema values:
|
|
258
|
+
`state.game.get(key)?.json` contains a JSON string.
|
|
259
|
+
|
|
260
|
+
The shared core calls the host's optional `setLoading(state, launch?)` during
|
|
261
|
+
connection, player waiting, recovery, failure and completion. The native SDK
|
|
262
|
+
implements it; custom launch hosts may omit it without changing connection
|
|
263
|
+
behavior. The host app renders loading UI via `useGameHubLoading`, a subscription
|
|
264
|
+
or `LOADING_STATE` events. It keeps gameplay mounted, blocks input while busy,
|
|
265
|
+
retains close controls and supplies its own recovery action/time limit.
|
|
266
|
+
|
|
267
|
+
Storage supplies synchronous or asynchronous `getItem`, `setItem`, and
|
|
268
|
+
`removeItem`. Hydration precedes connection and persistence is serialized so
|
|
269
|
+
leave/logout removal wins over queued writes. Storage errors allow memory-only
|
|
270
|
+
play and set `storageAvailable:false`. Explicit leave removes credentials and
|
|
271
|
+
closes late sockets. `appState` structurally accepts React Native `AppState`:
|
|
272
|
+
`addEventListener('change', listener):{remove():void}`. Returning to `active`
|
|
273
|
+
calls the core's connect method; backgrounding does not leave a seat or add
|
|
274
|
+
another retry loop. Leave/context invalidation removes lifecycle listeners.
|
|
275
|
+
Recovery is limited by the server grace window.
|
|
276
|
+
|
|
277
|
+
`./multiplayer/react` exports `useMultiplayerSnapshot(client)`, with stable
|
|
278
|
+
snapshots and unmount cleanup. Consumers own lobby/game UI and secure storage.
|
|
279
|
+
The native action/state protocol must match the selected approved UGC package;
|
|
280
|
+
automatic version negotiation, arbitrary custom server messages and native OTA
|
|
281
|
+
updates are outside this change.
|
|
282
|
+
|
|
283
|
+
Builds generate an unchanged source copy of browser `multiplayer-client.ts`,
|
|
284
|
+
copy HTTP/lobby types and exact compiled contracts/schema modules. Generated
|
|
285
|
+
`vendor/` and `dist/` are never hand-edited. Only realtime entries import
|
|
286
|
+
Colyseus. Published packages contain all copies and require no private sibling
|
|
287
|
+
workspace at runtime. Expo 54 iOS/Android Metro smoke covers lobby and realtime
|
|
288
|
+
hooks with one React runtime and one schema runtime.
|
|
289
|
+
For the installed Colyseus peer, consumers configure Metro's `ws` resolution
|
|
290
|
+
to use legacy browser/main fields on iOS/Android, as shown in the README. Native
|
|
291
|
+
WebSocket handles transport; Node's `ws/lib` modules must not enter the bundle.
|
|
292
|
+
The smoke check uses a generated standalone Expo consumer, extends the mobile
|
|
293
|
+
workspace's Metro configuration and enables Expo autolinking, without changing
|
|
294
|
+
the mobile application's configuration or release identity.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { RecordAnswerData } from '../vendor/session.js';
|
|
2
|
+
/** Same rules as the browser SDK and the platform's answer contract; null
|
|
3
|
+
* when any field is invalid, so the answer is dropped. */
|
|
4
|
+
export declare function normalizeAnswer(answer: RecordAnswerData): Record<string, unknown> | null;
|
|
5
|
+
//# sourceMappingURL=answers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"answers.d.ts","sourceRoot":"","sources":["../../src/answers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAS7D;2DAC2D;AAC3D,wBAAgB,eAAe,CAC7B,MAAM,EAAE,gBAAgB,GACvB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAsBhC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const QUESTION_ID = /^[A-Za-z0-9_:.-]{1,64}$/;
|
|
2
|
+
const isInt = (value, min, max) => typeof value === 'number' &&
|
|
3
|
+
Number.isInteger(value) &&
|
|
4
|
+
value >= min &&
|
|
5
|
+
value <= max;
|
|
6
|
+
/** Same rules as the browser SDK and the platform's answer contract; null
|
|
7
|
+
* when any field is invalid, so the answer is dropped. */
|
|
8
|
+
export function normalizeAnswer(answer) {
|
|
9
|
+
if (!answer || typeof answer !== 'object')
|
|
10
|
+
return null;
|
|
11
|
+
const { questionId, correct, choice, timeMs, level } = answer;
|
|
12
|
+
if (typeof questionId !== 'string' || !QUESTION_ID.test(questionId))
|
|
13
|
+
return null;
|
|
14
|
+
if (typeof correct !== 'boolean')
|
|
15
|
+
return null;
|
|
16
|
+
if (choice !== undefined &&
|
|
17
|
+
!(typeof choice === 'string' && choice.length <= 100) &&
|
|
18
|
+
!isInt(choice, -1000000, 1000000))
|
|
19
|
+
return null;
|
|
20
|
+
if (timeMs !== undefined && !isInt(Math.round(timeMs), 0, 600000))
|
|
21
|
+
return null;
|
|
22
|
+
if (level !== undefined && !isInt(level, 0, 1000))
|
|
23
|
+
return null;
|
|
24
|
+
return {
|
|
25
|
+
questionId,
|
|
26
|
+
correct,
|
|
27
|
+
...(choice !== undefined ? { choice } : {}),
|
|
28
|
+
...(timeMs !== undefined ? { timeMs: Math.round(timeMs) } : {}),
|
|
29
|
+
...(level !== undefined ? { level } : {}),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=answers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"answers.js","sourceRoot":"","sources":["../../src/answers.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAC9C,MAAM,KAAK,GAAG,CAAC,KAAc,EAAE,GAAW,EAAE,GAAW,EAAE,EAAE,CACzD,OAAO,KAAK,KAAK,QAAQ;IACzB,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC;IACvB,KAAK,IAAI,GAAG;IACZ,KAAK,IAAI,GAAG,CAAC;AAEf;2DAC2D;AAC3D,MAAM,UAAU,eAAe,CAC7B,MAAwB;IAExB,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACvD,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,CAAC;IAC9D,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC;QACjE,OAAO,IAAI,CAAC;IACd,IAAI,OAAO,OAAO,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IAC9C,IACE,MAAM,KAAK,SAAS;QACpB,CAAC,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC;QACrD,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,OAAS,EAAE,OAAS,CAAC;QAErC,OAAO,IAAI,CAAC;IACd,IAAI,MAAM,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,MAAO,CAAC;QAChE,OAAO,IAAI,CAAC;IACd,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAC/D,OAAO;QACL,UAAU;QACV,OAAO;QACP,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3C,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC/D,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC1C,CAAC;AACJ,CAAC"}
|