@ksaa-nlp/gamehub-sdk 0.1.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/src/session.ts ADDED
@@ -0,0 +1,240 @@
1
+ namespace GameHub.Session {
2
+ /**
3
+ * Starts a new game session and caches the returned session token. Safe to
4
+ * call multiple times — the cached token short-circuits subsequent calls.
5
+ *
6
+ * Endpoint is selected from the active context:
7
+ * - league + game + match → scoped match session
8
+ * - league + game → scoped league session
9
+ * - otherwise → standalone session (requires auth)
10
+ */
11
+ export async function startSession(): Promise<StartSessionResult> {
12
+ const S = GameHub.State;
13
+
14
+ if (!S.gameSlug) return { success: false, error: 'Game slug not set' };
15
+
16
+ const isLeagueMatchSession = Boolean(S.leagueId && S.gameId && S.matchId);
17
+ if (!S.authToken && !isLeagueMatchSession) {
18
+ return { success: false, error: 'User not authenticated' };
19
+ }
20
+ if (S.sessionToken) return { success: true, token: S.sessionToken };
21
+
22
+ try {
23
+ let endpoint = '/sessions/start';
24
+ let body: Record<string, any> = { gameSlug: S.gameSlug };
25
+
26
+ if (S.leagueId && S.gameId && S.matchId) {
27
+ endpoint =
28
+ '/leagues/' + S.leagueId + '/matches/' + S.matchId + '/session';
29
+ body = { gameId: S.gameId };
30
+ } else if (S.leagueId && S.gameId) {
31
+ endpoint = '/leagues/' + S.leagueId + '/sessions';
32
+ body = { gameId: S.gameId };
33
+ }
34
+
35
+ const result = await GameHub.Api.apiRequest(endpoint, {
36
+ method: 'POST',
37
+ body,
38
+ });
39
+
40
+ const data = GameHub.Utils.unwrapResult(result);
41
+ if (result.success || data?.token) {
42
+ S.sessionToken = data?.token || result?.token || null;
43
+ GameHub.Bridge.sendToParent('SESSION_STARTED', {
44
+ token: S.sessionToken,
45
+ });
46
+ return { success: true, token: S.sessionToken };
47
+ }
48
+
49
+ return {
50
+ success: false,
51
+ error: result.error?.message || 'Failed to start session',
52
+ };
53
+ } catch (err: any) {
54
+ return { success: false, error: err.message };
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Submit a score to the current session. If no session exists yet we try to
60
+ * open one (re-using any in-flight start attempt).
61
+ */
62
+ export async function submitScore(
63
+ score: number,
64
+ meta: ScoreMetadata = {}
65
+ ): Promise<SubmitScoreResult> {
66
+ const S = GameHub.State;
67
+
68
+ await GameHub.Init.ensureInitialized();
69
+
70
+ if (!S.isInitialized) {
71
+ return {
72
+ success: false,
73
+ error: 'SDK could not initialize. Is game slug set?',
74
+ };
75
+ }
76
+
77
+ // Online-mode gate: when the SDK is joined to a multiplayer room, only the
78
+ // host is allowed to submit. Guests and viewers short-circuit with
79
+ // `{ skipped: true }` so games can call `submitScore` from shared code
80
+ // without double-counting the match.
81
+ if (S.mpRoom && S.mpRoom.role !== 'host') {
82
+ GameHub.Utils.warn(
83
+ 'submitScore skipped: only the multiplayer host may submit scores'
84
+ );
85
+ return { success: true, skipped: true };
86
+ }
87
+
88
+ if (!S.sessionToken) {
89
+ if (S.sessionStartPromise) {
90
+ await S.sessionStartPromise;
91
+ } else {
92
+ const sessionResult = await startSession();
93
+ if (!sessionResult.success) {
94
+ return {
95
+ success: false,
96
+ error: sessionResult.error || 'Could not start session',
97
+ };
98
+ }
99
+ }
100
+ }
101
+
102
+ if (!S.sessionToken) {
103
+ return {
104
+ success: false,
105
+ error: 'No active session. User may not be authenticated.',
106
+ };
107
+ }
108
+
109
+ if (typeof score !== 'number' || score < 0) {
110
+ return { success: false, error: 'Score must be a non-negative number' };
111
+ }
112
+
113
+ try {
114
+ const result = await GameHub.Api.apiRequest('/sessions/submit', {
115
+ method: 'POST',
116
+ body: {
117
+ token: S.sessionToken,
118
+ score: Math.floor(score),
119
+ meta,
120
+ },
121
+ });
122
+
123
+ const data = GameHub.Utils.unwrapResult(result);
124
+
125
+ if (result.success || data?.accepted) {
126
+ GameHub.Bridge.sendToParent('SCORE_SUBMITTED', {
127
+ score,
128
+ accepted: data?.accepted,
129
+ timeTaken: data?.timeTaken,
130
+ });
131
+ return {
132
+ success: true,
133
+ accepted: data?.accepted,
134
+ timeTaken: data?.timeTaken,
135
+ };
136
+ }
137
+
138
+ return {
139
+ success: false,
140
+ error: result.error?.message || 'Score rejected',
141
+ };
142
+ } catch (err: any) {
143
+ return { success: false, error: err.message };
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Convenience wrapper that tags a score with the current league match
149
+ * context. Fails early if there's no matchId — a plain {@link submitScore}
150
+ * is the right call in that case.
151
+ */
152
+ export async function submitMatchScore(
153
+ score: number,
154
+ meta: ScoreMetadata = {}
155
+ ): Promise<SubmitScoreResult> {
156
+ const S = GameHub.State;
157
+ if (!S.matchId) {
158
+ return {
159
+ success: false,
160
+ error: 'No matchId found for this game session',
161
+ };
162
+ }
163
+
164
+ return await submitScore(score, {
165
+ ...(meta || {}),
166
+ matchId: S.matchId,
167
+ leagueId: S.leagueId || meta.leagueId,
168
+ gameId: S.gameId || meta.gameId,
169
+ });
170
+ }
171
+
172
+ /**
173
+ * Submit a match result (winner, scores, etc.) with a zero placeholder
174
+ * score — the server derives the real leaderboard entries from the result
175
+ * payload.
176
+ */
177
+ export async function submitMatchResult(
178
+ result: MatchResultPayload = {}
179
+ ): Promise<SubmitScoreResult> {
180
+ if (!result || typeof result !== 'object') {
181
+ return { success: false, error: 'match result payload is required' };
182
+ }
183
+
184
+ return await submitMatchScore(0, { matchResult: result });
185
+ }
186
+
187
+ /**
188
+ * Fetch questions for this game. Returns an empty array on any failure or
189
+ * invalid input — callers can treat "no questions" as the degraded state.
190
+ */
191
+ export async function getQuestions(
192
+ options: QuestionOptions = {}
193
+ ): Promise<Question[]> {
194
+ const S = GameHub.State;
195
+ await GameHub.Init.ensureInitialized();
196
+
197
+ const gameIdentifier = S.gameId || S.gameSlug;
198
+ if (!gameIdentifier) return [];
199
+
200
+ const { difficulty, category, limit } = options;
201
+
202
+ if (difficulty && !['easy', 'medium', 'hard'].includes(difficulty)) {
203
+ return [];
204
+ }
205
+
206
+ if (limit !== undefined && (typeof limit !== 'number' || limit < 1)) {
207
+ return [];
208
+ }
209
+
210
+ try {
211
+ const params = new URLSearchParams({
212
+ limit: String(
213
+ Math.min(
214
+ limit || GameHub.QUESTIONS_LIMIT_CAP,
215
+ GameHub.QUESTIONS_LIMIT_CAP
216
+ )
217
+ ),
218
+ random: 'true',
219
+ });
220
+ if (S.gameId) params.set('gameId', S.gameId);
221
+ if (difficulty) params.set('difficulty', difficulty);
222
+ if (category) params.set('category', String(category));
223
+
224
+ const result = await GameHub.Api.apiRequest(
225
+ '/games/' +
226
+ encodeURIComponent(gameIdentifier) +
227
+ '/questions?' +
228
+ params.toString(),
229
+ { method: 'GET' }
230
+ );
231
+
232
+ const data = GameHub.Utils.unwrapResult(result);
233
+ if (Array.isArray(data)) return data;
234
+ if (!data || !Array.isArray(data.questions)) return [];
235
+ return data.questions;
236
+ } catch {
237
+ return [];
238
+ }
239
+ }
240
+ }
package/src/state.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Centralised mutable state for the SDK singleton.
3
+ *
4
+ * Everything here is module-global by design — the SDK is a singleton per
5
+ * window and this is the single source of truth. Keeping it in one file makes
6
+ * lifetime and invalidation rules easier to audit than spreading `let`s across
7
+ * every feature module.
8
+ */
9
+ namespace GameHub.State {
10
+ // --- API endpoint resolution ---------------------------------------------
11
+ export let sdkOrigin: string = '';
12
+ export let sdkPathPrefix: string = '';
13
+ export let runtimeBasePath: string = '';
14
+ export let apiBase: string = '';
15
+
16
+ // --- Game / league context ------------------------------------------------
17
+ export let gameSlug: string | null = null;
18
+ export let sessionToken: string | null = null;
19
+ export let authToken: string | null = null;
20
+ export let leagueId: string | null = null;
21
+ export let gameId: string | null = null;
22
+ export let matchId: string | null = null;
23
+ export let participant1Id: string | null = null;
24
+ export let participant2Id: string | null = null;
25
+ export let participant1MemberIds: string[] = [];
26
+ export let participant2MemberIds: string[] = [];
27
+
28
+ // --- Match metadata (fetched lazily from the API) ------------------------
29
+ export let matchContext: MatchContext | null = null;
30
+ export let matchContextPromise: Promise<MatchContext | null> | null = null;
31
+
32
+ // --- Bootstrap payload from host -----------------------------------------
33
+ export let bootstrapShareId: string | null = null;
34
+ export let bootstrapRoomCode: string | null = null;
35
+ export let bootstrapRoomRole: string | null = null;
36
+ export let bootstrapRoomToken: string | null = null;
37
+ export let bootstrapWsUrl: string | null = null;
38
+ export let bootstrapPlayerName: string | null = null;
39
+ export let bootstrapPeerId: string | null = null;
40
+ export let bootstrapMaxPlayers: number | null = null;
41
+ export let bootstrapReceived = false;
42
+
43
+ // --- Initialisation lifecycle --------------------------------------------
44
+ export let isInitialized = false;
45
+ export let isAutoInitializing = false;
46
+ export let autoInitPromise: Promise<boolean> | null = null;
47
+ export let bootstrapRequestPromise: Promise<BootstrapConfig | null> | null =
48
+ null;
49
+ export let parentOrigin: string | null = null;
50
+ export let sessionStartPromise: Promise<StartSessionResult> | null = null;
51
+ export let lastAutoJoinShareId: string | null = null;
52
+ export let lastAutoJoinRoomCode: string | null = null;
53
+
54
+ // --- Multiplayer runtime --------------------------------------------------
55
+ export let mpSocket: WebSocket | null = null;
56
+ export let mpReconnectTimer: ReturnType<typeof setTimeout> | null = null;
57
+ export let mpReconnectAttempts = 0;
58
+ export let mpExpectedClose = false;
59
+ export let mpRoom: MpRoom | null = null;
60
+ export let mpLastJoinRequest: MpJoinRequest | null = null;
61
+ export const mpPeers: Map<string, Peer> = new Map();
62
+ export const mpHandlers: Map<string, Set<MpEventHandler>> = new Map();
63
+
64
+ /**
65
+ * Highest `seq` we've already delivered to game code, per sending peer.
66
+ * Used to drop late/duplicate `game_event` frames so a reconnect or a
67
+ * buffered message can't double-advance game state.
68
+ */
69
+ export const mpLastSeqByPeer: Map<string, number> = new Map();
70
+
71
+ /**
72
+ * Local override for view-only guests. The server doesn't know about
73
+ * viewers — this is a client-side flag the SDK flips when the game joins
74
+ * with `{ asViewer: true }`. It gates outbound `send`/`broadcast` and
75
+ * score submission.
76
+ */
77
+ export let mpViewerOverride = false;
78
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,68 @@
1
+ namespace GameHub.Utils {
2
+ /**
3
+ * Logs with a consistent `[GameHubSDK]` prefix so host-page developers can
4
+ * easily filter SDK messages in their console.
5
+ */
6
+ export function warn(message: string, ...rest: any[]): void {
7
+ console.warn('[GameHubSDK] ' + message, ...rest);
8
+ }
9
+
10
+ export function error(message: string, ...rest: any[]): void {
11
+ console.error('[GameHubSDK] ' + message, ...rest);
12
+ }
13
+
14
+ /**
15
+ * Flattens the standard `{ success, data }` envelope returned by our REST API
16
+ * down to the inner `data` payload, or returns the raw response if it isn't
17
+ * shaped that way.
18
+ */
19
+ export function unwrapResult(result: ApiResponse | null | undefined): any {
20
+ if (!result) return null;
21
+ if (result.success && result.data) return result.data;
22
+ return result;
23
+ }
24
+
25
+ /**
26
+ * Extracts a share ID from either:
27
+ * - a full multiplayer URL (`/join?mp=<shareId>`), or
28
+ * - a short path where the last segment is the share ID itself.
29
+ * Returns null if the link can't be parsed.
30
+ */
31
+ export function extractShareIdFromLink(link: string): string | null {
32
+ try {
33
+ const parsed = new URL(link, window.location.origin);
34
+ const mp = parsed.searchParams.get('mp');
35
+ if (mp) return mp;
36
+ return parsed.pathname.split('/').pop() || null;
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Safely read a query-string parameter, falling back to a regex scan when
44
+ * URLSearchParams is unavailable (very old browsers / odd runtimes).
45
+ */
46
+ export function readQueryParam(name: string): string | null {
47
+ try {
48
+ const params = new URLSearchParams(window.location.search);
49
+ return params.get(name);
50
+ } catch {
51
+ const match = window.location.search.match(
52
+ new RegExp('[?&]' + name + '=([^&]+)')
53
+ );
54
+ return match ? decodeURIComponent(match[1]) : null;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Reads a CSV query parameter and returns the trimmed, non-empty values.
60
+ */
61
+ export function readCsvQueryParam(name: string): string[] {
62
+ const raw = readQueryParam(name) || '';
63
+ return raw
64
+ .split(',')
65
+ .map((value) => value.trim())
66
+ .filter(Boolean);
67
+ }
68
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "none",
5
+ "lib": ["DOM", "DOM.Iterable", "ES2020"],
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "removeComments": false,
10
+ "declaration": true,
11
+ "outFile": "./dist/gamehub-sdk.js",
12
+ "skipLibCheck": true,
13
+ "types": []
14
+ },
15
+ "include": [
16
+ "types/api.ts",
17
+ "types/match.ts",
18
+ "types/bootstrap.ts",
19
+ "types/multiplayer.ts",
20
+ "types/session.ts",
21
+ "src/constants.ts",
22
+ "src/state.ts",
23
+ "src/utils.ts",
24
+ "src/api-client.ts",
25
+ "src/bridge.ts",
26
+ "src/match-context.ts",
27
+ "src/session.ts",
28
+ "src/multiplayer.ts",
29
+ "src/init.ts",
30
+ "src/main.ts"
31
+ ],
32
+ "exclude": ["node_modules", "dist"]
33
+ }
package/types/api.ts ADDED
@@ -0,0 +1,21 @@
1
+ namespace GameHub {
2
+ /**
3
+ * The envelope returned by the GameHub REST API.
4
+ */
5
+ export interface ApiResponse {
6
+ success: boolean;
7
+ data?: any;
8
+ token?: string;
9
+ error?: { message?: string };
10
+ }
11
+
12
+ /**
13
+ * Options accepted by {@link Api.apiRequest}.
14
+ */
15
+ export interface ApiRequestOptions {
16
+ method?: string;
17
+ headers?: Record<string, string>;
18
+ body?: any;
19
+ credentials?: RequestCredentials;
20
+ }
21
+ }
@@ -0,0 +1,65 @@
1
+ namespace GameHub {
2
+ /**
3
+ * Static room metadata supplied by the host during bootstrap.
4
+ *
5
+ * Peer counts and peer lists are deliberately excluded because they'd be
6
+ * stale by the time the game reads them. Use {@link Multiplayer.getPeers}
7
+ * and the `room_joined` / `peer_joined` / `peer_left` events for the
8
+ * live peer state.
9
+ */
10
+ export interface BootstrapRoom {
11
+ roomCode: string | null;
12
+ shareId: string | null;
13
+ maxPlayers: number | null;
14
+ role: string | null;
15
+ roomToken: string | null;
16
+ wsUrl: string | null;
17
+ }
18
+
19
+ /**
20
+ * The configuration the host sends via postMessage to seed SDK state.
21
+ */
22
+ export interface BootstrapConfig {
23
+ gameSlug?: string | null;
24
+ authToken?: string | null;
25
+ leagueId?: string | null;
26
+ gameId?: string | null;
27
+ matchId?: string | null;
28
+ participant1Id?: string | null;
29
+ participant2Id?: string | null;
30
+ participant1MemberIds?: string[];
31
+ participant2MemberIds?: string[];
32
+ playerName?: string | null;
33
+ /** The peerId the server assigned to this player. Use
34
+ * {@link Multiplayer.selfId} after join for the live value. */
35
+ peerId?: string | null;
36
+ room?: Partial<BootstrapRoom> | null;
37
+ }
38
+
39
+ /**
40
+ * Snapshot of the SDK's bootstrap-sourced state, returned by
41
+ * {@link GameHubSDK.getBootstrap}.
42
+ *
43
+ * This snapshot contains only static session metadata. For the live room
44
+ * and peer state, use {@link Multiplayer.getRoom}, {@link Multiplayer.getPeers},
45
+ * and the `room_joined` / `peer_joined` / `peer_left` events.
46
+ */
47
+ export interface BootstrapData {
48
+ gameSlug: string | null;
49
+ authToken: string | null;
50
+ leagueId: string | null;
51
+ gameId: string | null;
52
+ matchId: string | null;
53
+ match: MatchContext | null;
54
+ participant1Id: string | null;
55
+ participant2Id: string | null;
56
+ participant1MemberIds: string[];
57
+ participant2MemberIds: string[];
58
+ playerName: string | null;
59
+ /** The peerId the server assigned to this player. */
60
+ peerId: string | null;
61
+ /** Static room metadata. `null` for non-multiplayer sessions. */
62
+ room: BootstrapRoom | null;
63
+ isBootstrapped: boolean;
64
+ }
65
+ }
package/types/match.ts ADDED
@@ -0,0 +1,41 @@
1
+ namespace GameHub {
2
+ /**
3
+ * A single member belonging to a match participant (team player).
4
+ */
5
+ export interface MatchParticipantMember {
6
+ leaguePlayerId: string;
7
+ fullname?: string;
8
+ avatar?: string;
9
+ }
10
+
11
+ /**
12
+ * A participant (individual or team) in a league match.
13
+ */
14
+ export interface MatchParticipant {
15
+ participantId: string;
16
+ name?: string;
17
+ members?: MatchParticipantMember[];
18
+ }
19
+
20
+ /**
21
+ * The full context for a league match this game is being played in.
22
+ */
23
+ export interface MatchContext {
24
+ id: string;
25
+ leagueId: string;
26
+ gameId: string;
27
+ participant1: MatchParticipant;
28
+ participant2: MatchParticipant;
29
+ status: string;
30
+ }
31
+
32
+ /**
33
+ * Payload submitted via {@link Session.submitMatchResult}.
34
+ */
35
+ export interface MatchResultPayload {
36
+ winnerId?: string;
37
+ reason?: string;
38
+ scores?: Record<string, number>;
39
+ details?: Record<string, any>;
40
+ }
41
+ }
@@ -0,0 +1,118 @@
1
+ namespace GameHub {
2
+ /**
3
+ * Information needed to connect to a multiplayer room's WebSocket.
4
+ */
5
+ export interface JoinInfo {
6
+ wsUrl: string;
7
+ roomToken: string;
8
+ gameSlug: string;
9
+ roomCode: string;
10
+ peerId: string;
11
+ }
12
+
13
+ /**
14
+ * A peer in a multiplayer room.
15
+ */
16
+ export interface Peer {
17
+ peerId: string;
18
+ role?: string;
19
+ metadata?: Record<string, any>;
20
+ }
21
+
22
+ /**
23
+ * Public info about the current multiplayer room, returned by
24
+ * {@link Multiplayer.getRoom}.
25
+ */
26
+ export interface RoomInfo {
27
+ roomCode: string;
28
+ shareId: string;
29
+ shareUrl?: string;
30
+ peerId: string;
31
+ role: string;
32
+ gameSlug: string;
33
+ roomToken: string;
34
+ wsUrl: string;
35
+ }
36
+
37
+ /**
38
+ * Internal book-keeping for the currently-joined room.
39
+ */
40
+ export interface MpRoom {
41
+ roomCode: string;
42
+ shareId: string;
43
+ shareUrl?: string;
44
+ peerId: string;
45
+ role: string;
46
+ gameSlug: string;
47
+ roomToken: string;
48
+ wsUrl: string;
49
+ }
50
+
51
+ /**
52
+ * Parameters used by {@link Multiplayer.connect} to open / re-open a WS.
53
+ */
54
+ export interface MpJoinRequest {
55
+ roomCode: string;
56
+ roomToken: string;
57
+ wsUrl: string;
58
+ gameSlug: string;
59
+ peerId: string;
60
+ }
61
+
62
+ /**
63
+ * Listener for a single multiplayer event (or all events via `'*'`).
64
+ */
65
+ export type MpEventHandler = (payload: any) => void;
66
+
67
+ /** Options accepted when creating a room. */
68
+ export interface RoomOptions {
69
+ maxPlayers?: number;
70
+ passcode?: string;
71
+ }
72
+
73
+ /** Options accepted when joining a room. */
74
+ export interface JoinOptions {
75
+ passcode?: string;
76
+ displayName?: string;
77
+ /**
78
+ * When true, the SDK locally marks this peer as a view-only guest:
79
+ * {@link Multiplayer.send} and {@link Multiplayer.broadcast} become no-ops
80
+ * and score submission (`submitScore` / `submitMatchResult`) is blocked.
81
+ * The peer still receives every broadcast so it can mirror host state.
82
+ */
83
+ asViewer?: boolean;
84
+ }
85
+
86
+ /**
87
+ * Shape of the `message` event emitted for every peer-originated game event.
88
+ */
89
+ export interface MpMessage<T = any> {
90
+ roomCode: string;
91
+ fromPeerId: string;
92
+ eventName: string;
93
+ payload: T;
94
+ seq: number;
95
+ sentAt: number;
96
+ }
97
+
98
+ /** Result returned by `multiplayer.createRoom`. */
99
+ export interface CreateRoomResult {
100
+ success: boolean;
101
+ roomCode?: string;
102
+ shareId?: string;
103
+ shareUrl?: string;
104
+ peerId?: string;
105
+ roomToken?: string;
106
+ error?: string;
107
+ }
108
+
109
+ /** Result returned by `multiplayer.joinRoom` / `joinRoomByLink`. */
110
+ export interface JoinRoomResult {
111
+ success: boolean;
112
+ roomCode?: string;
113
+ shareId?: string;
114
+ peerId?: string;
115
+ roomToken?: string;
116
+ error?: string;
117
+ }
118
+ }