@ksaa-nlp/gamehub-sdk 0.9.0 → 3.6.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 +158 -373
- package/SPEC.md +869 -0
- package/dist/gamehub-sdk.js +168 -1191
- package/dist/gamehub-sdk.js.map +3 -3
- package/dist/src/api-client.d.ts +15 -5
- package/dist/src/api-client.d.ts.map +1 -1
- package/dist/src/api-client.js +21 -5
- package/dist/src/api-client.js.map +1 -1
- package/dist/src/bridge.d.ts +31 -14
- package/dist/src/bridge.d.ts.map +1 -1
- package/dist/src/bridge.js +148 -159
- package/dist/src/bridge.js.map +1 -1
- package/dist/src/constants.d.ts +8 -6
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +8 -6
- package/dist/src/constants.js.map +1 -1
- package/dist/src/init.d.ts +18 -12
- package/dist/src/init.d.ts.map +1 -1
- package/dist/src/init.js +23 -156
- package/dist/src/init.js.map +1 -1
- package/dist/src/main.d.ts +45 -85
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js +33 -52
- package/dist/src/main.js.map +1 -1
- package/dist/src/match-context.d.ts.map +1 -1
- package/dist/src/match-context.js +0 -14
- package/dist/src/match-context.js.map +1 -1
- package/dist/src/server-dev-harness.d.ts +85 -0
- package/dist/src/server-dev-harness.d.ts.map +1 -0
- package/dist/src/server-dev-harness.js +233 -0
- package/dist/src/server-dev-harness.js.map +1 -0
- package/dist/src/server-entry.d.ts +127 -0
- package/dist/src/server-entry.d.ts.map +1 -0
- package/dist/src/server-entry.js +26 -0
- package/dist/src/server-entry.js.map +1 -0
- package/dist/src/session.d.ts +16 -9
- package/dist/src/session.d.ts.map +1 -1
- package/dist/src/session.js +38 -27
- package/dist/src/session.js.map +1 -1
- package/dist/src/state.d.ts +17 -55
- package/dist/src/state.d.ts.map +1 -1
- package/dist/src/state.js +13 -32
- package/dist/src/state.js.map +1 -1
- package/dist/src/utils.d.ts +3 -14
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/src/utils.js +3 -31
- package/dist/src/utils.js.map +1 -1
- package/dist/types/bootstrap.d.ts +56 -36
- package/dist/types/bootstrap.d.ts.map +1 -1
- package/dist/types/question.d.ts +36 -0
- package/dist/types/question.d.ts.map +1 -0
- package/dist/types/question.js +21 -0
- package/dist/types/question.js.map +1 -0
- package/dist/types/session.d.ts +46 -20
- package/dist/types/session.d.ts.map +1 -1
- package/package.json +14 -4
- package/CHANGELOG.md +0 -545
- package/MIGRATION.md +0 -322
- package/dist/src/multiplayer-match.d.ts +0 -42
- package/dist/src/multiplayer-match.d.ts.map +0 -1
- package/dist/src/multiplayer-match.js +0 -551
- package/dist/src/multiplayer-match.js.map +0 -1
- package/dist/src/multiplayer.d.ts +0 -96
- package/dist/src/multiplayer.d.ts.map +0 -1
- package/dist/src/multiplayer.js +0 -536
- package/dist/src/multiplayer.js.map +0 -1
- package/dist/types/multiplayer-match.d.ts +0 -204
- package/dist/types/multiplayer-match.d.ts.map +0 -1
- package/dist/types/multiplayer-match.js +0 -15
- package/dist/types/multiplayer-match.js.map +0 -1
- package/dist/types/multiplayer.d.ts +0 -194
- package/dist/types/multiplayer.d.ts.map +0 -1
- package/dist/types/multiplayer.js +0 -2
- package/dist/types/multiplayer.js.map +0 -1
package/dist/gamehub-sdk.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
(() => {
|
|
3
3
|
// src/constants.ts
|
|
4
|
-
var SDK_VERSION = "
|
|
4
|
+
var SDK_VERSION = "3.6.0";
|
|
5
5
|
var MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
6
6
|
var PARENT_REQUEST_TIMEOUT_MS = 2e3;
|
|
7
|
-
var
|
|
8
|
-
var MP_MAX_RECONNECT_DELAY_MS = 1e4;
|
|
7
|
+
var HOST_API_TIMEOUT_MS = 15e3;
|
|
9
8
|
var QUESTIONS_LIMIT_CAP = 100;
|
|
10
9
|
|
|
11
10
|
// src/state.ts
|
|
@@ -20,20 +19,13 @@
|
|
|
20
19
|
leagueId: null,
|
|
21
20
|
gameId: null,
|
|
22
21
|
matchId: null,
|
|
23
|
-
|
|
24
|
-
participant2Id: null,
|
|
25
|
-
participant1MemberIds: [],
|
|
26
|
-
participant2MemberIds: [],
|
|
27
|
-
matchContext: null,
|
|
28
|
-
matchContextPromise: null,
|
|
29
|
-
bootstrapShareId: null,
|
|
30
|
-
bootstrapRoomCode: null,
|
|
31
|
-
bootstrapRoomRole: null,
|
|
32
|
-
bootstrapRoomToken: null,
|
|
33
|
-
bootstrapWsUrl: null,
|
|
22
|
+
bootstrapMode: null,
|
|
34
23
|
bootstrapPlayerName: null,
|
|
35
|
-
|
|
36
|
-
|
|
24
|
+
bootstrapPlayerCount: null,
|
|
25
|
+
bootstrapTeamOneName: null,
|
|
26
|
+
bootstrapTeamTwoName: null,
|
|
27
|
+
bootstrapProfileId: null,
|
|
28
|
+
bootstrapMultiplayer: null,
|
|
37
29
|
bootstrapReceived: false,
|
|
38
30
|
isInitialized: false,
|
|
39
31
|
isAutoInitializing: false,
|
|
@@ -41,20 +33,8 @@
|
|
|
41
33
|
bootstrapRequestPromise: null,
|
|
42
34
|
parentOrigin: null,
|
|
43
35
|
sessionStartPromise: null,
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
mpSocket: null,
|
|
47
|
-
mpReconnectTimer: null,
|
|
48
|
-
mpReconnectAttempts: 0,
|
|
49
|
-
mpExpectedClose: false,
|
|
50
|
-
mpRoom: null,
|
|
51
|
-
mpLastJoinRequest: null,
|
|
52
|
-
mpPeers: /* @__PURE__ */ new Map(),
|
|
53
|
-
mpHandlers: /* @__PURE__ */ new Map(),
|
|
54
|
-
mpLastSeqByPeer: /* @__PURE__ */ new Map(),
|
|
55
|
-
mpViewerOverride: false,
|
|
56
|
-
mpServerOffsetMs: 0,
|
|
57
|
-
mpServerOffsetSamples: 0
|
|
36
|
+
matchContext: null,
|
|
37
|
+
matchContextPromise: null
|
|
58
38
|
};
|
|
59
39
|
|
|
60
40
|
// src/utils.ts
|
|
@@ -72,16 +52,6 @@
|
|
|
72
52
|
if (result.success && result.data) return result.data;
|
|
73
53
|
return result;
|
|
74
54
|
}
|
|
75
|
-
function extractShareIdFromLink(link) {
|
|
76
|
-
try {
|
|
77
|
-
const parsed = new URL(link, window.location.origin);
|
|
78
|
-
const mp = parsed.searchParams.get("mp");
|
|
79
|
-
if (mp) return mp;
|
|
80
|
-
return parsed.pathname.split("/").pop() || null;
|
|
81
|
-
} catch {
|
|
82
|
-
return null;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
55
|
function readQueryParam(name) {
|
|
86
56
|
try {
|
|
87
57
|
const params = new URLSearchParams(window.location.search);
|
|
@@ -93,130 +63,76 @@
|
|
|
93
63
|
return match ? decodeURIComponent(match[1]) : null;
|
|
94
64
|
}
|
|
95
65
|
}
|
|
96
|
-
function readCsvQueryParam(name) {
|
|
97
|
-
const raw = readQueryParam(name) || "";
|
|
98
|
-
return raw.split(",").map((value) => value.trim()).filter(Boolean);
|
|
99
|
-
}
|
|
100
66
|
|
|
101
67
|
// src/bridge.ts
|
|
68
|
+
function trimToNullable(value) {
|
|
69
|
+
if (value === null) return null;
|
|
70
|
+
if (typeof value !== "string") return void 0;
|
|
71
|
+
const trimmed = value.trim();
|
|
72
|
+
return trimmed ? trimmed : null;
|
|
73
|
+
}
|
|
74
|
+
function parseMultiplayer(value) {
|
|
75
|
+
if (value === null) return null;
|
|
76
|
+
if (!value || typeof value !== "object") return void 0;
|
|
77
|
+
const { reservation, wsEndpoint } = value;
|
|
78
|
+
if (!reservation || typeof reservation !== "object" || typeof reservation.name !== "string" || typeof reservation.sessionId !== "string" || typeof reservation.roomId !== "string" || typeof wsEndpoint !== "string") {
|
|
79
|
+
return void 0;
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
reservation,
|
|
83
|
+
wsEndpoint: wsEndpoint.trim()
|
|
84
|
+
};
|
|
85
|
+
}
|
|
102
86
|
function mergeBootstrapConfig(config = {}) {
|
|
103
87
|
if (!config || typeof config !== "object") return;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
state.
|
|
134
|
-
|
|
135
|
-
state.
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
state.
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
state.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
} else if (config.playerName === null) {
|
|
146
|
-
state.bootstrapPlayerName = null;
|
|
147
|
-
}
|
|
148
|
-
if (typeof config.peerId === "string" && config.peerId.trim()) {
|
|
149
|
-
state.bootstrapPeerId = config.peerId.trim();
|
|
150
|
-
} else if (config.peerId === null) {
|
|
151
|
-
state.bootstrapPeerId = null;
|
|
152
|
-
}
|
|
153
|
-
if (config.room && typeof config.room === "object") {
|
|
154
|
-
const room = config.room;
|
|
155
|
-
if (typeof room.roomCode === "string" && room.roomCode.trim()) {
|
|
156
|
-
state.bootstrapRoomCode = room.roomCode.trim().toUpperCase();
|
|
157
|
-
} else if (room.roomCode === null) {
|
|
158
|
-
state.bootstrapRoomCode = null;
|
|
159
|
-
}
|
|
160
|
-
if (typeof room.shareId === "string" && room.shareId.trim()) {
|
|
161
|
-
state.bootstrapShareId = room.shareId.trim();
|
|
162
|
-
} else if (room.shareId === null) {
|
|
163
|
-
state.bootstrapShareId = null;
|
|
164
|
-
}
|
|
165
|
-
if (typeof room.maxPlayers === "number" && Number.isFinite(room.maxPlayers)) {
|
|
166
|
-
state.bootstrapMaxPlayers = room.maxPlayers;
|
|
167
|
-
} else if (room.maxPlayers === null) {
|
|
168
|
-
state.bootstrapMaxPlayers = null;
|
|
169
|
-
}
|
|
170
|
-
if (typeof room.role === "string" && room.role.trim()) {
|
|
171
|
-
state.bootstrapRoomRole = room.role.trim();
|
|
172
|
-
} else if (room.role === null) {
|
|
173
|
-
state.bootstrapRoomRole = null;
|
|
174
|
-
}
|
|
175
|
-
if (typeof room.roomToken === "string" && room.roomToken.trim()) {
|
|
176
|
-
state.bootstrapRoomToken = room.roomToken.trim();
|
|
177
|
-
} else if (room.roomToken === null) {
|
|
178
|
-
state.bootstrapRoomToken = null;
|
|
179
|
-
}
|
|
180
|
-
if (typeof room.wsUrl === "string" && room.wsUrl.trim()) {
|
|
181
|
-
state.bootstrapWsUrl = room.wsUrl.trim();
|
|
182
|
-
} else if (room.wsUrl === null) {
|
|
183
|
-
state.bootstrapWsUrl = null;
|
|
184
|
-
}
|
|
185
|
-
} else if (config.room === null) {
|
|
186
|
-
state.bootstrapRoomCode = null;
|
|
187
|
-
state.bootstrapShareId = null;
|
|
188
|
-
state.bootstrapMaxPlayers = null;
|
|
189
|
-
state.bootstrapRoomRole = null;
|
|
190
|
-
state.bootstrapRoomToken = null;
|
|
191
|
-
state.bootstrapWsUrl = null;
|
|
192
|
-
}
|
|
88
|
+
const apply = (key, raw) => {
|
|
89
|
+
const next = trimToNullable(raw);
|
|
90
|
+
if (next === void 0) return;
|
|
91
|
+
state[key] = next;
|
|
92
|
+
};
|
|
93
|
+
apply("gameSlug", config.gameSlug);
|
|
94
|
+
apply("authToken", config.authToken);
|
|
95
|
+
apply("leagueId", config.leagueId);
|
|
96
|
+
apply("gameId", config.gameId);
|
|
97
|
+
apply("matchId", config.matchId);
|
|
98
|
+
const applyBootstrap = (key, raw) => {
|
|
99
|
+
const next = trimToNullable(raw);
|
|
100
|
+
if (next === void 0) return;
|
|
101
|
+
state[key] = next;
|
|
102
|
+
};
|
|
103
|
+
applyBootstrap("bootstrapMode", config.mode);
|
|
104
|
+
applyBootstrap("bootstrapPlayerName", config.playerName);
|
|
105
|
+
applyBootstrap("bootstrapPlayerCount", config.playerCount);
|
|
106
|
+
applyBootstrap("bootstrapTeamOneName", config.teamOneName);
|
|
107
|
+
applyBootstrap("bootstrapTeamTwoName", config.teamTwoName);
|
|
108
|
+
applyBootstrap("bootstrapProfileId", config.profileId);
|
|
109
|
+
const mp = parseMultiplayer(config.multiplayer);
|
|
110
|
+
if (mp !== void 0) {
|
|
111
|
+
state.bootstrapMultiplayer = mp;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function snapshotBootstrap() {
|
|
115
|
+
return {
|
|
116
|
+
gameSlug: state.gameSlug,
|
|
117
|
+
authToken: state.authToken,
|
|
118
|
+
leagueId: state.leagueId,
|
|
119
|
+
gameId: state.gameId,
|
|
120
|
+
matchId: state.matchId,
|
|
121
|
+
mode: state.bootstrapMode,
|
|
122
|
+
playerName: state.bootstrapPlayerName,
|
|
123
|
+
playerCount: state.bootstrapPlayerCount,
|
|
124
|
+
teamOneName: state.bootstrapTeamOneName,
|
|
125
|
+
teamTwoName: state.bootstrapTeamTwoName,
|
|
126
|
+
profileId: state.bootstrapProfileId,
|
|
127
|
+
multiplayer: state.bootstrapMultiplayer
|
|
128
|
+
};
|
|
193
129
|
}
|
|
194
130
|
function requestBootstrapFromParent() {
|
|
195
131
|
if (!isBrowser() || window.parent === window) {
|
|
196
132
|
return Promise.resolve(null);
|
|
197
133
|
}
|
|
198
134
|
if (state.bootstrapReceived) {
|
|
199
|
-
return Promise.resolve(
|
|
200
|
-
gameSlug: state.gameSlug,
|
|
201
|
-
authToken: state.authToken,
|
|
202
|
-
leagueId: state.leagueId,
|
|
203
|
-
gameId: state.gameId,
|
|
204
|
-
matchId: state.matchId,
|
|
205
|
-
participant1Id: state.participant1Id,
|
|
206
|
-
participant2Id: state.participant2Id,
|
|
207
|
-
participant1MemberIds: state.participant1MemberIds,
|
|
208
|
-
participant2MemberIds: state.participant2MemberIds,
|
|
209
|
-
playerName: state.bootstrapPlayerName,
|
|
210
|
-
peerId: state.bootstrapPeerId,
|
|
211
|
-
room: state.bootstrapRoomCode ? {
|
|
212
|
-
roomCode: state.bootstrapRoomCode,
|
|
213
|
-
shareId: state.bootstrapShareId,
|
|
214
|
-
maxPlayers: state.bootstrapMaxPlayers,
|
|
215
|
-
role: state.bootstrapRoomRole,
|
|
216
|
-
roomToken: state.bootstrapRoomToken,
|
|
217
|
-
wsUrl: state.bootstrapWsUrl
|
|
218
|
-
} : null
|
|
219
|
-
});
|
|
135
|
+
return Promise.resolve(snapshotBootstrap());
|
|
220
136
|
}
|
|
221
137
|
if (state.bootstrapRequestPromise) {
|
|
222
138
|
return state.bootstrapRequestPromise;
|
|
@@ -280,14 +196,6 @@
|
|
|
280
196
|
if (event.data.leagueId) state.leagueId = event.data.leagueId;
|
|
281
197
|
if (event.data.gameId) state.gameId = event.data.gameId;
|
|
282
198
|
if (event.data.matchId) state.matchId = event.data.matchId;
|
|
283
|
-
if (event.data.participant1Id)
|
|
284
|
-
state.participant1Id = event.data.participant1Id;
|
|
285
|
-
if (event.data.participant2Id)
|
|
286
|
-
state.participant2Id = event.data.participant2Id;
|
|
287
|
-
if (Array.isArray(event.data.participant1MemberIds))
|
|
288
|
-
state.participant1MemberIds = event.data.participant1MemberIds.filter(Boolean);
|
|
289
|
-
if (Array.isArray(event.data.participant2MemberIds))
|
|
290
|
-
state.participant2MemberIds = event.data.participant2MemberIds.filter(Boolean);
|
|
291
199
|
resolve(event.data.token || null);
|
|
292
200
|
}
|
|
293
201
|
};
|
|
@@ -304,6 +212,50 @@
|
|
|
304
212
|
}, PARENT_REQUEST_TIMEOUT_MS);
|
|
305
213
|
});
|
|
306
214
|
}
|
|
215
|
+
var apiRequestSeq = 0;
|
|
216
|
+
function requestApiFromParent(endpoint, options = {}) {
|
|
217
|
+
return new Promise((resolve, reject) => {
|
|
218
|
+
if (!isBrowser() || window.parent === window) {
|
|
219
|
+
reject(new Error("Host bridge unavailable: not running in an iframe"));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const messageId = "api_" + Date.now().toString() + "_" + ++apiRequestSeq;
|
|
223
|
+
let settled = false;
|
|
224
|
+
let timeoutId = null;
|
|
225
|
+
const handler = (event) => {
|
|
226
|
+
if (!event.data || event.data.type !== MESSAGE_PREFIX + "_API_RESPONSE" || event.data.messageId !== messageId) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (settled) return;
|
|
230
|
+
settled = true;
|
|
231
|
+
window.removeEventListener("message", handler);
|
|
232
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
233
|
+
state.parentOrigin = event.origin;
|
|
234
|
+
if (event.data.ok) {
|
|
235
|
+
resolve(event.data.result ?? {});
|
|
236
|
+
} else {
|
|
237
|
+
reject(new Error(event.data.error || "Host API request failed"));
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
window.addEventListener("message", handler);
|
|
241
|
+
window.parent.postMessage(
|
|
242
|
+
{
|
|
243
|
+
type: MESSAGE_PREFIX + "_API_REQUEST",
|
|
244
|
+
messageId,
|
|
245
|
+
endpoint,
|
|
246
|
+
method: options.method || "GET",
|
|
247
|
+
body: options.body ?? null
|
|
248
|
+
},
|
|
249
|
+
state.parentOrigin || "*"
|
|
250
|
+
);
|
|
251
|
+
timeoutId = setTimeout(() => {
|
|
252
|
+
if (settled) return;
|
|
253
|
+
settled = true;
|
|
254
|
+
window.removeEventListener("message", handler);
|
|
255
|
+
reject(new Error("Host API request timed out"));
|
|
256
|
+
}, HOST_API_TIMEOUT_MS);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
307
259
|
function sendToParent(type, data) {
|
|
308
260
|
if (!isBrowser() || window.parent === window) return;
|
|
309
261
|
window.parent.postMessage(
|
|
@@ -318,6 +270,9 @@
|
|
|
318
270
|
|
|
319
271
|
// src/api-client.ts
|
|
320
272
|
async function apiRequest(endpoint, options = {}) {
|
|
273
|
+
if (isBrowser() && window.parent !== window) {
|
|
274
|
+
return requestApiFromParent(endpoint, options);
|
|
275
|
+
}
|
|
321
276
|
const url = state.apiBase + endpoint;
|
|
322
277
|
const headers = {
|
|
323
278
|
"Content-Type": "application/json",
|
|
@@ -335,432 +290,6 @@
|
|
|
335
290
|
return response.json();
|
|
336
291
|
}
|
|
337
292
|
|
|
338
|
-
// src/multiplayer.ts
|
|
339
|
-
function emit(eventName, payload) {
|
|
340
|
-
const handlers = state.mpHandlers.get(eventName);
|
|
341
|
-
if (handlers) {
|
|
342
|
-
handlers.forEach((handler) => {
|
|
343
|
-
try {
|
|
344
|
-
handler(payload);
|
|
345
|
-
} catch (err) {
|
|
346
|
-
error("Multiplayer handler error:", err);
|
|
347
|
-
}
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
const allHandlers = state.mpHandlers.get("*");
|
|
351
|
-
if (allHandlers) {
|
|
352
|
-
allHandlers.forEach((handler) => {
|
|
353
|
-
try {
|
|
354
|
-
handler({ eventName, payload });
|
|
355
|
-
} catch (err) {
|
|
356
|
-
error("Multiplayer * handler error:", err);
|
|
357
|
-
}
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
function clearSocket() {
|
|
362
|
-
if (state.mpReconnectTimer) {
|
|
363
|
-
clearTimeout(state.mpReconnectTimer);
|
|
364
|
-
state.mpReconnectTimer = null;
|
|
365
|
-
}
|
|
366
|
-
if (state.mpSocket) {
|
|
367
|
-
try {
|
|
368
|
-
state.mpSocket.onopen = null;
|
|
369
|
-
state.mpSocket.onclose = null;
|
|
370
|
-
state.mpSocket.onmessage = null;
|
|
371
|
-
state.mpSocket.onerror = null;
|
|
372
|
-
state.mpSocket.close();
|
|
373
|
-
} catch {
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
state.mpSocket = null;
|
|
377
|
-
}
|
|
378
|
-
function connect(joinInfo) {
|
|
379
|
-
clearSocket();
|
|
380
|
-
const wsBase = joinInfo.wsUrl.replace(/\/+$/, "");
|
|
381
|
-
const wsUrl = wsBase + "?roomToken=" + encodeURIComponent(joinInfo.roomToken) + "&gameSlug=" + encodeURIComponent(joinInfo.gameSlug) + "&sdk=2.x";
|
|
382
|
-
state.mpExpectedClose = false;
|
|
383
|
-
state.mpSocket = new WebSocket(wsUrl);
|
|
384
|
-
state.mpSocket.onopen = () => {
|
|
385
|
-
state.mpReconnectAttempts = 0;
|
|
386
|
-
emit("connected", {
|
|
387
|
-
roomCode: joinInfo.roomCode,
|
|
388
|
-
peerId: joinInfo.peerId
|
|
389
|
-
});
|
|
390
|
-
};
|
|
391
|
-
state.mpSocket.onmessage = (event) => {
|
|
392
|
-
let message = null;
|
|
393
|
-
try {
|
|
394
|
-
message = JSON.parse(event.data);
|
|
395
|
-
} catch {
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
if (!message || !message.type) return;
|
|
399
|
-
if (typeof message.sentAt === "number" && message.retained !== true) {
|
|
400
|
-
const sample = message.sentAt - Date.now();
|
|
401
|
-
if (state.mpServerOffsetSamples === 0) {
|
|
402
|
-
state.mpServerOffsetMs = sample;
|
|
403
|
-
} else {
|
|
404
|
-
state.mpServerOffsetMs = 0.85 * state.mpServerOffsetMs + 0.15 * sample;
|
|
405
|
-
}
|
|
406
|
-
state.mpServerOffsetSamples += 1;
|
|
407
|
-
}
|
|
408
|
-
if (message.type === "system") {
|
|
409
|
-
if (message.eventName === "room_joined") {
|
|
410
|
-
state.mpPeers.clear();
|
|
411
|
-
const peers = message.payload?.peers || [];
|
|
412
|
-
peers.forEach((peer) => {
|
|
413
|
-
if (peer && peer.peerId) state.mpPeers.set(peer.peerId, peer);
|
|
414
|
-
});
|
|
415
|
-
}
|
|
416
|
-
if (message.eventName === "peer_joined" && message.payload?.peerId) {
|
|
417
|
-
state.mpPeers.set(message.payload.peerId, message.payload);
|
|
418
|
-
}
|
|
419
|
-
if (message.eventName === "peer_left" && message.payload?.peerId) {
|
|
420
|
-
state.mpPeers.delete(message.payload.peerId);
|
|
421
|
-
}
|
|
422
|
-
if (message.eventName === "room_closed") {
|
|
423
|
-
emit("room_left", { reason: "room_closed" });
|
|
424
|
-
clearSocket();
|
|
425
|
-
}
|
|
426
|
-
if (message.eventName === "host_changed" && message.payload?.newHostPeerId && state.mpRoom) {
|
|
427
|
-
const newHostPeerId = message.payload.newHostPeerId;
|
|
428
|
-
const previousHostPeerId = message.payload.previousHostPeerId;
|
|
429
|
-
if (state.mpRoom.peerId === newHostPeerId) {
|
|
430
|
-
state.mpRoom.role = "host";
|
|
431
|
-
} else if (previousHostPeerId && state.mpRoom.peerId === previousHostPeerId) {
|
|
432
|
-
state.mpRoom.role = "player";
|
|
433
|
-
}
|
|
434
|
-
const promoted = state.mpPeers.get(newHostPeerId);
|
|
435
|
-
if (promoted) {
|
|
436
|
-
state.mpPeers.set(newHostPeerId, { ...promoted, role: "host" });
|
|
437
|
-
}
|
|
438
|
-
if (previousHostPeerId) {
|
|
439
|
-
const prev = state.mpPeers.get(previousHostPeerId);
|
|
440
|
-
if (prev) {
|
|
441
|
-
state.mpPeers.set(previousHostPeerId, {
|
|
442
|
-
...prev,
|
|
443
|
-
role: "player"
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
emit(message.eventName, message.payload || {});
|
|
449
|
-
return;
|
|
450
|
-
}
|
|
451
|
-
if (message.type === "game_event") {
|
|
452
|
-
const isRetained = message.retained === true;
|
|
453
|
-
if (!isRetained && typeof message.seq === "number" && typeof message.fromPeerId === "string") {
|
|
454
|
-
const last = state.mpLastSeqByPeer.get(message.fromPeerId) || 0;
|
|
455
|
-
if (message.seq <= last) return;
|
|
456
|
-
state.mpLastSeqByPeer.set(message.fromPeerId, message.seq);
|
|
457
|
-
}
|
|
458
|
-
emit("message", {
|
|
459
|
-
roomCode: message.roomCode,
|
|
460
|
-
fromPeerId: message.fromPeerId,
|
|
461
|
-
eventName: message.eventName,
|
|
462
|
-
payload: message.payload,
|
|
463
|
-
seq: message.seq,
|
|
464
|
-
sentAt: message.sentAt,
|
|
465
|
-
retained: isRetained
|
|
466
|
-
});
|
|
467
|
-
emit(message.eventName, {
|
|
468
|
-
roomCode: message.roomCode,
|
|
469
|
-
fromPeerId: message.fromPeerId,
|
|
470
|
-
payload: message.payload,
|
|
471
|
-
seq: message.seq,
|
|
472
|
-
sentAt: message.sentAt,
|
|
473
|
-
retained: isRetained
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
};
|
|
477
|
-
state.mpSocket.onclose = () => {
|
|
478
|
-
emit("disconnected", { roomCode: joinInfo.roomCode });
|
|
479
|
-
if (state.mpExpectedClose || !state.mpLastJoinRequest) return;
|
|
480
|
-
if (state.mpReconnectAttempts >= MP_MAX_RECONNECT_ATTEMPTS) return;
|
|
481
|
-
state.mpReconnectAttempts += 1;
|
|
482
|
-
const delay = Math.min(
|
|
483
|
-
1e3 * Math.pow(2, state.mpReconnectAttempts - 1),
|
|
484
|
-
MP_MAX_RECONNECT_DELAY_MS
|
|
485
|
-
);
|
|
486
|
-
emit("reconnecting", {
|
|
487
|
-
attempts: state.mpReconnectAttempts,
|
|
488
|
-
delayMs: delay
|
|
489
|
-
});
|
|
490
|
-
state.mpReconnectTimer = setTimeout(() => {
|
|
491
|
-
if (!state.mpLastJoinRequest) return;
|
|
492
|
-
connect(state.mpLastJoinRequest);
|
|
493
|
-
}, delay);
|
|
494
|
-
};
|
|
495
|
-
state.mpSocket.onerror = () => {
|
|
496
|
-
};
|
|
497
|
-
}
|
|
498
|
-
async function createRoom(options = {}) {
|
|
499
|
-
await ensureInitialized();
|
|
500
|
-
if (!state.gameSlug) {
|
|
501
|
-
return { success: false, error: "Game slug is required" };
|
|
502
|
-
}
|
|
503
|
-
const result = await apiRequest("/multiplayer/rooms/create", {
|
|
504
|
-
method: "POST",
|
|
505
|
-
body: {
|
|
506
|
-
gameSlug: state.gameSlug,
|
|
507
|
-
maxPlayers: options.maxPlayers,
|
|
508
|
-
passcode: options.passcode,
|
|
509
|
-
rateBurst: options.rateBurst,
|
|
510
|
-
rateWindowMs: options.rateWindowMs,
|
|
511
|
-
autoMigrateHost: options.autoMigrateHost
|
|
512
|
-
}
|
|
513
|
-
});
|
|
514
|
-
const data = unwrapResult(result);
|
|
515
|
-
if (!result.success || !data?.roomToken) {
|
|
516
|
-
return {
|
|
517
|
-
success: false,
|
|
518
|
-
error: result.error?.message || "Failed to create room"
|
|
519
|
-
};
|
|
520
|
-
}
|
|
521
|
-
state.mpRoom = {
|
|
522
|
-
roomCode: data.roomCode,
|
|
523
|
-
shareId: data.shareId,
|
|
524
|
-
shareUrl: data.shareUrl,
|
|
525
|
-
peerId: data.peerId,
|
|
526
|
-
role: data.role,
|
|
527
|
-
gameSlug: data.gameSlug,
|
|
528
|
-
roomToken: data.roomToken,
|
|
529
|
-
wsUrl: data.wsUrl
|
|
530
|
-
};
|
|
531
|
-
state.mpLastJoinRequest = {
|
|
532
|
-
roomCode: data.roomCode,
|
|
533
|
-
roomToken: data.roomToken,
|
|
534
|
-
wsUrl: data.wsUrl,
|
|
535
|
-
gameSlug: data.gameSlug,
|
|
536
|
-
peerId: data.peerId
|
|
537
|
-
};
|
|
538
|
-
connect(state.mpLastJoinRequest);
|
|
539
|
-
return {
|
|
540
|
-
success: true,
|
|
541
|
-
roomCode: data.roomCode,
|
|
542
|
-
shareId: data.shareId,
|
|
543
|
-
shareUrl: data.shareUrl,
|
|
544
|
-
peerId: data.peerId,
|
|
545
|
-
roomToken: data.roomToken
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
async function joinRoom(roomCode, options = {}) {
|
|
549
|
-
await ensureInitialized();
|
|
550
|
-
if (!state.gameSlug) {
|
|
551
|
-
return { success: false, error: "Game slug is required" };
|
|
552
|
-
}
|
|
553
|
-
const result = await apiRequest("/multiplayer/rooms/join-token", {
|
|
554
|
-
method: "POST",
|
|
555
|
-
body: {
|
|
556
|
-
gameSlug: state.gameSlug,
|
|
557
|
-
roomCode,
|
|
558
|
-
passcode: options.passcode,
|
|
559
|
-
displayName: options.displayName
|
|
560
|
-
}
|
|
561
|
-
});
|
|
562
|
-
const data = unwrapResult(result);
|
|
563
|
-
if (!result.success || !data?.roomToken) {
|
|
564
|
-
return {
|
|
565
|
-
success: false,
|
|
566
|
-
error: result.error?.message || "Failed to join room"
|
|
567
|
-
};
|
|
568
|
-
}
|
|
569
|
-
const resolvedRole = options.asViewer && data.role !== "host" ? "viewer" : data.role;
|
|
570
|
-
state.mpViewerOverride = resolvedRole === "viewer";
|
|
571
|
-
state.mpRoom = {
|
|
572
|
-
roomCode: data.roomCode,
|
|
573
|
-
shareId: data.shareId,
|
|
574
|
-
peerId: data.peerId,
|
|
575
|
-
role: resolvedRole,
|
|
576
|
-
gameSlug: data.gameSlug,
|
|
577
|
-
roomToken: data.roomToken,
|
|
578
|
-
wsUrl: data.wsUrl
|
|
579
|
-
};
|
|
580
|
-
state.mpLastJoinRequest = {
|
|
581
|
-
roomCode: data.roomCode,
|
|
582
|
-
roomToken: data.roomToken,
|
|
583
|
-
wsUrl: data.wsUrl,
|
|
584
|
-
gameSlug: data.gameSlug,
|
|
585
|
-
peerId: data.peerId
|
|
586
|
-
};
|
|
587
|
-
connect(state.mpLastJoinRequest);
|
|
588
|
-
return {
|
|
589
|
-
success: true,
|
|
590
|
-
roomCode: data.roomCode,
|
|
591
|
-
shareId: data.shareId,
|
|
592
|
-
peerId: data.peerId,
|
|
593
|
-
roomToken: data.roomToken
|
|
594
|
-
};
|
|
595
|
-
}
|
|
596
|
-
async function joinRoomByLink(link, options = {}) {
|
|
597
|
-
await ensureInitialized();
|
|
598
|
-
if (!state.gameSlug) {
|
|
599
|
-
return { success: false, error: "Game slug is required" };
|
|
600
|
-
}
|
|
601
|
-
const shareId = extractShareIdFromLink(link);
|
|
602
|
-
if (!shareId) {
|
|
603
|
-
return { success: false, error: "Invalid multiplayer link" };
|
|
604
|
-
}
|
|
605
|
-
const result = await apiRequest("/multiplayer/rooms/join-token", {
|
|
606
|
-
method: "POST",
|
|
607
|
-
body: {
|
|
608
|
-
gameSlug: state.gameSlug,
|
|
609
|
-
shareId,
|
|
610
|
-
passcode: options.passcode,
|
|
611
|
-
displayName: options.displayName
|
|
612
|
-
}
|
|
613
|
-
});
|
|
614
|
-
const data = unwrapResult(result);
|
|
615
|
-
if (!result.success || !data?.roomToken) {
|
|
616
|
-
return {
|
|
617
|
-
success: false,
|
|
618
|
-
error: result.error?.message || "Failed to join room by link"
|
|
619
|
-
};
|
|
620
|
-
}
|
|
621
|
-
const resolvedRole = options.asViewer && data.role !== "host" ? "viewer" : data.role;
|
|
622
|
-
state.mpViewerOverride = resolvedRole === "viewer";
|
|
623
|
-
state.mpRoom = {
|
|
624
|
-
roomCode: data.roomCode,
|
|
625
|
-
shareId: data.shareId,
|
|
626
|
-
peerId: data.peerId,
|
|
627
|
-
role: resolvedRole,
|
|
628
|
-
gameSlug: data.gameSlug,
|
|
629
|
-
roomToken: data.roomToken,
|
|
630
|
-
wsUrl: data.wsUrl
|
|
631
|
-
};
|
|
632
|
-
state.mpLastJoinRequest = {
|
|
633
|
-
roomCode: data.roomCode,
|
|
634
|
-
roomToken: data.roomToken,
|
|
635
|
-
wsUrl: data.wsUrl,
|
|
636
|
-
gameSlug: data.gameSlug,
|
|
637
|
-
peerId: data.peerId
|
|
638
|
-
};
|
|
639
|
-
connect(state.mpLastJoinRequest);
|
|
640
|
-
return {
|
|
641
|
-
success: true,
|
|
642
|
-
roomCode: data.roomCode,
|
|
643
|
-
shareId: data.shareId,
|
|
644
|
-
peerId: data.peerId,
|
|
645
|
-
roomToken: data.roomToken
|
|
646
|
-
};
|
|
647
|
-
}
|
|
648
|
-
async function leaveRoom(reason = "left") {
|
|
649
|
-
if (state.mpRoom && state.mpRoom.role === "host" && state.mpRoom.roomToken) {
|
|
650
|
-
try {
|
|
651
|
-
await apiRequest(
|
|
652
|
-
"/multiplayer/rooms/" + encodeURIComponent(state.mpRoom.roomCode) + "/close",
|
|
653
|
-
{
|
|
654
|
-
method: "POST",
|
|
655
|
-
body: { roomToken: state.mpRoom.roomToken }
|
|
656
|
-
}
|
|
657
|
-
);
|
|
658
|
-
} catch {
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
state.mpExpectedClose = true;
|
|
662
|
-
clearSocket();
|
|
663
|
-
state.mpRoom = null;
|
|
664
|
-
state.mpLastJoinRequest = null;
|
|
665
|
-
state.mpPeers.clear();
|
|
666
|
-
state.mpLastSeqByPeer.clear();
|
|
667
|
-
state.mpViewerOverride = false;
|
|
668
|
-
emit("room_left", { reason });
|
|
669
|
-
}
|
|
670
|
-
function send(eventName, payload = {}, options = {}) {
|
|
671
|
-
if (state.mpViewerOverride) {
|
|
672
|
-
warn("multiplayer.send ignored: peer is a viewer");
|
|
673
|
-
return false;
|
|
674
|
-
}
|
|
675
|
-
const socket = state.mpSocket;
|
|
676
|
-
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
677
|
-
return false;
|
|
678
|
-
}
|
|
679
|
-
const frame = { eventName, payload };
|
|
680
|
-
if (options.retain) {
|
|
681
|
-
frame.retain = true;
|
|
682
|
-
if (options.retainKey) frame.retainKey = options.retainKey;
|
|
683
|
-
}
|
|
684
|
-
if (options.to !== void 0) {
|
|
685
|
-
frame.to = options.to;
|
|
686
|
-
}
|
|
687
|
-
if (options.hostOnly === true) {
|
|
688
|
-
frame.hostOnly = true;
|
|
689
|
-
}
|
|
690
|
-
socket.send(JSON.stringify(frame));
|
|
691
|
-
return true;
|
|
692
|
-
}
|
|
693
|
-
function broadcast(eventName, payload = {}, options = {}) {
|
|
694
|
-
if (!isHost()) {
|
|
695
|
-
warn("multiplayer.broadcast ignored: peer is not the host");
|
|
696
|
-
return false;
|
|
697
|
-
}
|
|
698
|
-
return send(eventName, payload, { ...options, hostOnly: true });
|
|
699
|
-
}
|
|
700
|
-
function getRole() {
|
|
701
|
-
return state.mpRoom ? state.mpRoom.role : null;
|
|
702
|
-
}
|
|
703
|
-
function isHost() {
|
|
704
|
-
return state.mpRoom?.role === "host";
|
|
705
|
-
}
|
|
706
|
-
function isViewer() {
|
|
707
|
-
return state.mpViewerOverride === true;
|
|
708
|
-
}
|
|
709
|
-
function selfId() {
|
|
710
|
-
return state.mpRoom ? state.mpRoom.peerId : null;
|
|
711
|
-
}
|
|
712
|
-
function on(eventName, handler) {
|
|
713
|
-
const handlers = state.mpHandlers;
|
|
714
|
-
if (!handlers.has(eventName)) {
|
|
715
|
-
handlers.set(eventName, /* @__PURE__ */ new Set());
|
|
716
|
-
}
|
|
717
|
-
handlers.get(eventName).add(handler);
|
|
718
|
-
return () => {
|
|
719
|
-
const set = handlers.get(eventName);
|
|
720
|
-
if (!set) return;
|
|
721
|
-
set.delete(handler);
|
|
722
|
-
if (set.size === 0) handlers.delete(eventName);
|
|
723
|
-
};
|
|
724
|
-
}
|
|
725
|
-
function getRoom() {
|
|
726
|
-
return state.mpRoom ? { ...state.mpRoom } : null;
|
|
727
|
-
}
|
|
728
|
-
function getPeers() {
|
|
729
|
-
return Array.from(state.mpPeers.values());
|
|
730
|
-
}
|
|
731
|
-
function isConnected() {
|
|
732
|
-
const s = state.mpSocket;
|
|
733
|
-
return Boolean(s && s.readyState === WebSocket.OPEN);
|
|
734
|
-
}
|
|
735
|
-
function serverNow() {
|
|
736
|
-
return Date.now() + state.mpServerOffsetMs;
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
// src/match-context.ts
|
|
740
|
-
async function fetchMatchContext() {
|
|
741
|
-
if (!state.leagueId || !state.matchId) return null;
|
|
742
|
-
if (state.matchContext) return state.matchContext;
|
|
743
|
-
if (state.matchContextPromise) return await state.matchContextPromise;
|
|
744
|
-
state.matchContextPromise = apiRequest(
|
|
745
|
-
"/leagues/" + encodeURIComponent(state.leagueId) + "/matches/" + encodeURIComponent(state.matchId),
|
|
746
|
-
{ method: "GET" }
|
|
747
|
-
).then((result) => {
|
|
748
|
-
const data = unwrapResult(result);
|
|
749
|
-
if (result?.success && data) {
|
|
750
|
-
state.matchContext = data;
|
|
751
|
-
state.participant1Id = data.participant1?.participantId || state.participant1Id;
|
|
752
|
-
state.participant2Id = data.participant2?.participantId || state.participant2Id;
|
|
753
|
-
state.participant1MemberIds = Array.isArray(data.participant1?.members) ? data.participant1.members.map((member) => member?.leaguePlayerId).filter(Boolean) : state.participant1MemberIds;
|
|
754
|
-
state.participant2MemberIds = Array.isArray(data.participant2?.members) ? data.participant2.members.map((member) => member?.leaguePlayerId).filter(Boolean) : state.participant2MemberIds;
|
|
755
|
-
return state.matchContext;
|
|
756
|
-
}
|
|
757
|
-
return null;
|
|
758
|
-
}).catch(() => null).finally(() => {
|
|
759
|
-
state.matchContextPromise = null;
|
|
760
|
-
});
|
|
761
|
-
return await state.matchContextPromise;
|
|
762
|
-
}
|
|
763
|
-
|
|
764
293
|
// src/session.ts
|
|
765
294
|
async function startSession() {
|
|
766
295
|
if (!state.gameSlug) return { success: false, error: "Game slug not set" };
|
|
@@ -807,10 +336,6 @@
|
|
|
807
336
|
error: "SDK could not initialize. Is game slug set?"
|
|
808
337
|
};
|
|
809
338
|
}
|
|
810
|
-
if (state.mpRoom && state.mpRoom.role !== "host") {
|
|
811
|
-
warn("submitScore skipped: only the multiplayer host may submit scores");
|
|
812
|
-
return { success: true, skipped: true };
|
|
813
|
-
}
|
|
814
339
|
if (!state.sessionToken) {
|
|
815
340
|
if (state.sessionStartPromise) {
|
|
816
341
|
await state.sessionStartPromise;
|
|
@@ -894,26 +419,34 @@
|
|
|
894
419
|
if (limit !== void 0 && (typeof limit !== "number" || limit < 1)) {
|
|
895
420
|
return [];
|
|
896
421
|
}
|
|
422
|
+
const profileId = options.profileId || state.bootstrapProfileId || "";
|
|
897
423
|
try {
|
|
898
424
|
const params = new URLSearchParams({
|
|
899
|
-
limit: String(
|
|
425
|
+
limit: String(
|
|
426
|
+
Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)
|
|
427
|
+
),
|
|
900
428
|
random: "true"
|
|
901
429
|
});
|
|
902
430
|
if (state.gameId) params.set("gameId", state.gameId);
|
|
903
431
|
if (difficulty) params.set("difficulty", difficulty);
|
|
904
432
|
if (category) params.set("category", String(category));
|
|
433
|
+
if (profileId) params.set("profileId", profileId);
|
|
905
434
|
const result = await apiRequest(
|
|
906
435
|
"/games/" + encodeURIComponent(gameIdentifier) + "/questions?" + params.toString(),
|
|
907
436
|
{ method: "GET" }
|
|
908
437
|
);
|
|
909
438
|
const data = unwrapResult(result);
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
return data.questions;
|
|
439
|
+
const raw = Array.isArray(data) ? data : Array.isArray(data?.questions) ? data.questions : [];
|
|
440
|
+
return raw.map(normalizeQuestion);
|
|
913
441
|
} catch {
|
|
914
442
|
return [];
|
|
915
443
|
}
|
|
916
444
|
}
|
|
445
|
+
function normalizeQuestion(raw) {
|
|
446
|
+
const q = raw;
|
|
447
|
+
const answer = typeof q.answer === "number" ? String(q.answer) : q.answer;
|
|
448
|
+
return { ...q, answer };
|
|
449
|
+
}
|
|
917
450
|
|
|
918
451
|
// src/init.ts
|
|
919
452
|
var environmentDetected = false;
|
|
@@ -933,10 +466,6 @@
|
|
|
933
466
|
state.leagueId = readQueryParam("leagueId");
|
|
934
467
|
state.gameId = readQueryParam("gameId");
|
|
935
468
|
state.matchId = readQueryParam("matchId");
|
|
936
|
-
state.participant1Id = readQueryParam("participant1Id");
|
|
937
|
-
state.participant2Id = readQueryParam("participant2Id");
|
|
938
|
-
state.participant1MemberIds = readCsvQueryParam("participant1MemberIds");
|
|
939
|
-
state.participant2MemberIds = readCsvQueryParam("participant2MemberIds");
|
|
940
469
|
const scripts = document.getElementsByTagName("script");
|
|
941
470
|
for (let i = 0; i < scripts.length; i++) {
|
|
942
471
|
const src = scripts[i].src;
|
|
@@ -968,111 +497,17 @@
|
|
|
968
497
|
state.apiBase = state.sdkOrigin + effectiveBasePath + "/api";
|
|
969
498
|
state.gameSlug = detectedSlug;
|
|
970
499
|
}
|
|
971
|
-
function getPendingShareId() {
|
|
972
|
-
if (state.bootstrapShareId) return state.bootstrapShareId;
|
|
973
|
-
return readQueryParam("mp");
|
|
974
|
-
}
|
|
975
|
-
function getPendingRoomCode() {
|
|
976
|
-
if (state.bootstrapRoomCode) return state.bootstrapRoomCode;
|
|
977
|
-
const roomCode = readQueryParam("roomCode");
|
|
978
|
-
return roomCode ? roomCode.trim().toUpperCase() : null;
|
|
979
|
-
}
|
|
980
|
-
function getPendingRoomRole() {
|
|
981
|
-
if (state.bootstrapRoomRole) return state.bootstrapRoomRole;
|
|
982
|
-
const role = readQueryParam("roomRole");
|
|
983
|
-
return role ? role.trim() : null;
|
|
984
|
-
}
|
|
985
|
-
function getPendingRoomToken() {
|
|
986
|
-
if (state.bootstrapRoomToken) return state.bootstrapRoomToken;
|
|
987
|
-
const roomToken = readQueryParam("roomToken");
|
|
988
|
-
return roomToken ? roomToken.trim() : null;
|
|
989
|
-
}
|
|
990
|
-
function getPendingWsUrl() {
|
|
991
|
-
if (state.bootstrapWsUrl) return state.bootstrapWsUrl;
|
|
992
|
-
const wsUrl = readQueryParam("wsUrl");
|
|
993
|
-
return wsUrl ? wsUrl.trim() : null;
|
|
994
|
-
}
|
|
995
|
-
function getPendingPlayerName() {
|
|
996
|
-
if (state.bootstrapPlayerName) return state.bootstrapPlayerName;
|
|
997
|
-
const playerName = readQueryParam("playerName");
|
|
998
|
-
return playerName ? playerName.trim() : void 0;
|
|
999
|
-
}
|
|
1000
|
-
function seedPeerIdFromUrl() {
|
|
1001
|
-
if (state.bootstrapPeerId) return;
|
|
1002
|
-
const fromUrl = readQueryParam("peerId");
|
|
1003
|
-
if (fromUrl) state.bootstrapPeerId = fromUrl.trim();
|
|
1004
|
-
}
|
|
1005
|
-
function resumePendingRoomFromBootstrap() {
|
|
1006
|
-
const roomCode = getPendingRoomCode();
|
|
1007
|
-
const roomToken = getPendingRoomToken();
|
|
1008
|
-
const wsUrl = getPendingWsUrl();
|
|
1009
|
-
const peerId = state.bootstrapPeerId || readQueryParam("peerId")?.trim() || null;
|
|
1010
|
-
if (!state.gameSlug || !roomCode || !roomToken || !wsUrl || !peerId) {
|
|
1011
|
-
return false;
|
|
1012
|
-
}
|
|
1013
|
-
const role = getPendingRoomRole() || "player";
|
|
1014
|
-
state.mpViewerOverride = role === "viewer";
|
|
1015
|
-
state.mpRoom = {
|
|
1016
|
-
roomCode,
|
|
1017
|
-
shareId: state.bootstrapShareId || "",
|
|
1018
|
-
peerId,
|
|
1019
|
-
role,
|
|
1020
|
-
gameSlug: state.gameSlug,
|
|
1021
|
-
roomToken,
|
|
1022
|
-
wsUrl
|
|
1023
|
-
};
|
|
1024
|
-
state.mpLastJoinRequest = {
|
|
1025
|
-
roomCode,
|
|
1026
|
-
roomToken,
|
|
1027
|
-
wsUrl,
|
|
1028
|
-
gameSlug: state.gameSlug,
|
|
1029
|
-
peerId
|
|
1030
|
-
};
|
|
1031
|
-
connect(state.mpLastJoinRequest);
|
|
1032
|
-
return true;
|
|
1033
|
-
}
|
|
1034
|
-
async function autoJoinPendingShare() {
|
|
1035
|
-
const shareId = getPendingShareId();
|
|
1036
|
-
if (!shareId) return;
|
|
1037
|
-
if (state.lastAutoJoinShareId === shareId) return;
|
|
1038
|
-
try {
|
|
1039
|
-
state.lastAutoJoinShareId = shareId;
|
|
1040
|
-
await joinRoomByLink(shareId, {
|
|
1041
|
-
displayName: getPendingPlayerName()
|
|
1042
|
-
});
|
|
1043
|
-
} catch (err) {
|
|
1044
|
-
state.lastAutoJoinShareId = null;
|
|
1045
|
-
warn("Auto join by link failed: " + (err?.message || err));
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
async function autoJoinPendingRoomCode() {
|
|
1049
|
-
const roomCode = getPendingRoomCode();
|
|
1050
|
-
if (!roomCode) return;
|
|
1051
|
-
if (state.lastAutoJoinRoomCode === roomCode) return;
|
|
1052
|
-
try {
|
|
1053
|
-
state.lastAutoJoinRoomCode = roomCode;
|
|
1054
|
-
if (resumePendingRoomFromBootstrap()) {
|
|
1055
|
-
return;
|
|
1056
|
-
}
|
|
1057
|
-
await joinRoom(roomCode, {
|
|
1058
|
-
displayName: getPendingPlayerName()
|
|
1059
|
-
});
|
|
1060
|
-
} catch (err) {
|
|
1061
|
-
state.lastAutoJoinRoomCode = null;
|
|
1062
|
-
warn("Auto join by room code failed: " + (err?.message || err));
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
500
|
async function autoInit() {
|
|
1066
501
|
if (!isBrowser()) return false;
|
|
1067
|
-
if (state.isInitialized || state.isAutoInitializing)
|
|
502
|
+
if (state.isInitialized || state.isAutoInitializing) {
|
|
1068
503
|
return state.autoInitPromise;
|
|
504
|
+
}
|
|
1069
505
|
detectEnvironment();
|
|
1070
506
|
installHostMessageListener();
|
|
1071
507
|
state.isAutoInitializing = true;
|
|
1072
508
|
state.autoInitPromise = (async () => {
|
|
1073
509
|
try {
|
|
1074
510
|
await requestBootstrapFromParent();
|
|
1075
|
-
seedPeerIdFromUrl();
|
|
1076
511
|
if (!state.gameSlug) {
|
|
1077
512
|
warn(
|
|
1078
513
|
"Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}."
|
|
@@ -1089,12 +524,9 @@
|
|
|
1089
524
|
slug: state.gameSlug,
|
|
1090
525
|
auto: true
|
|
1091
526
|
});
|
|
1092
|
-
await fetchMatchContext();
|
|
1093
527
|
if (state.authToken || state.leagueId && state.gameId && state.matchId) {
|
|
1094
528
|
state.sessionStartPromise = startSession();
|
|
1095
529
|
}
|
|
1096
|
-
await autoJoinPendingShare();
|
|
1097
|
-
await autoJoinPendingRoomCode();
|
|
1098
530
|
return true;
|
|
1099
531
|
} catch (err) {
|
|
1100
532
|
error("Auto-init failed:", err);
|
|
@@ -1120,9 +552,6 @@
|
|
|
1120
552
|
state.parentOrigin = event.origin;
|
|
1121
553
|
state.bootstrapReceived = true;
|
|
1122
554
|
mergeBootstrapConfig(event.data.payload);
|
|
1123
|
-
if (state.isInitialized && state.bootstrapShareId && !state.mpRoom) {
|
|
1124
|
-
autoJoinPendingShare();
|
|
1125
|
-
}
|
|
1126
555
|
}
|
|
1127
556
|
if (type === MESSAGE_PREFIX + "_SET_AUTH") {
|
|
1128
557
|
state.authToken = event.data.token;
|
|
@@ -1143,457 +572,25 @@
|
|
|
1143
572
|
});
|
|
1144
573
|
}
|
|
1145
574
|
|
|
1146
|
-
// src/
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
throw new Error(
|
|
1160
|
-
"multiplayer.match: an existing match is still active. Call destroy() first."
|
|
1161
|
-
);
|
|
1162
|
-
}
|
|
1163
|
-
if (!state.mpRoom) {
|
|
1164
|
-
throw new Error(
|
|
1165
|
-
"multiplayer.match: not in a room. Call createRoom/joinRoom first."
|
|
1166
|
-
);
|
|
1167
|
-
}
|
|
1168
|
-
const expectedPeers = options.expectedPeers ?? 2;
|
|
1169
|
-
const autoReady = options.autoReady !== false;
|
|
1170
|
-
const startEventName = options.startEventName ?? START_EVENT_DEFAULT;
|
|
1171
|
-
const readyEventName = options.readyEventName ?? READY_EVENT_DEFAULT;
|
|
1172
|
-
const startRetainKey = options.startRetainKey ?? START_RETAIN_KEY_DEFAULT;
|
|
1173
|
-
let matchState = "waiting";
|
|
1174
|
-
let matchId = null;
|
|
1175
|
-
let starting = false;
|
|
1176
|
-
let destroyed = false;
|
|
1177
|
-
let wantReady = autoReady;
|
|
1178
|
-
const readyPeerIds = /* @__PURE__ */ new Set();
|
|
1179
|
-
const appliedIdKeys = /* @__PURE__ */ new Set();
|
|
1180
|
-
const stateChangeHandlers = /* @__PURE__ */ new Set();
|
|
1181
|
-
const offHandlers = [];
|
|
1182
|
-
function setState(next) {
|
|
1183
|
-
if (matchState === next) return;
|
|
1184
|
-
matchState = next;
|
|
1185
|
-
for (const handler of stateChangeHandlers) {
|
|
1186
|
-
try {
|
|
1187
|
-
handler(next);
|
|
1188
|
-
} catch (err) {
|
|
1189
|
-
error("multiplayer.match onStateChange handler error:", err);
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
function localSelfId() {
|
|
1194
|
-
return selfId();
|
|
1195
|
-
}
|
|
1196
|
-
function localIsHost() {
|
|
1197
|
-
return isHost();
|
|
1198
|
-
}
|
|
1199
|
-
function localPeers() {
|
|
1200
|
-
return getPeers();
|
|
1201
|
-
}
|
|
1202
|
-
function makeCtx(retained = false) {
|
|
1203
|
-
return {
|
|
1204
|
-
get matchId() {
|
|
1205
|
-
return matchId ?? "";
|
|
1206
|
-
},
|
|
1207
|
-
get isHost() {
|
|
1208
|
-
return localIsHost();
|
|
1209
|
-
},
|
|
1210
|
-
get selfId() {
|
|
1211
|
-
return localSelfId() ?? "";
|
|
1212
|
-
},
|
|
1213
|
-
get peers() {
|
|
1214
|
-
return localPeers();
|
|
1215
|
-
},
|
|
1216
|
-
retained,
|
|
1217
|
-
peer(peerId) {
|
|
1218
|
-
return localPeers().find((p) => p.peerId === peerId) ?? null;
|
|
1219
|
-
},
|
|
1220
|
-
intent: apiIntent,
|
|
1221
|
-
broadcast: apiBroadcast
|
|
1222
|
-
};
|
|
1223
|
-
}
|
|
1224
|
-
function eventDefFor(name) {
|
|
1225
|
-
return options.events[name];
|
|
1226
|
-
}
|
|
1227
|
-
function idKeyFor(eventName, def, payload, seq) {
|
|
1228
|
-
if (def?.idKey) {
|
|
1229
|
-
try {
|
|
1230
|
-
return def.idKey(payload);
|
|
1231
|
-
} catch (err) {
|
|
1232
|
-
error(
|
|
1233
|
-
`multiplayer.match idKey('${eventName}') threw \u2014 falling back to seq:`,
|
|
1234
|
-
err
|
|
1235
|
-
);
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
return `${eventName}:${payload.matchId}:${seq ?? "local"}`;
|
|
1239
|
-
}
|
|
1240
|
-
function maybeApply(eventName, def, payload, fromPeerId, seq, retained) {
|
|
1241
|
-
if (!def?.apply) return;
|
|
1242
|
-
const key = idKeyFor(eventName, def, payload, seq);
|
|
1243
|
-
if (appliedIdKeys.has(key)) return;
|
|
1244
|
-
appliedIdKeys.add(key);
|
|
1245
|
-
try {
|
|
1246
|
-
def.apply(makeCtx(retained), payload, fromPeerId);
|
|
1247
|
-
} catch (err) {
|
|
1248
|
-
error(`multiplayer.match apply('${eventName}') threw:`, err);
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
function apiIntent(name, payloadIn) {
|
|
1252
|
-
if (destroyed || matchState === "aborted" || matchState === "ended") {
|
|
1253
|
-
warn(
|
|
1254
|
-
`multiplayer.match.intent('${String(name)}'): match is ${matchState}`
|
|
1255
|
-
);
|
|
1256
|
-
return false;
|
|
1257
|
-
}
|
|
1258
|
-
if (matchId == null) {
|
|
1259
|
-
warn(
|
|
1260
|
-
`multiplayer.match.intent('${String(name)}'): match has not started yet`
|
|
1261
|
-
);
|
|
1262
|
-
return false;
|
|
1263
|
-
}
|
|
1264
|
-
const payload = { ...payloadIn, matchId };
|
|
1265
|
-
const def = eventDefFor(String(name));
|
|
1266
|
-
if (localIsHost() && def?.hostHandle) {
|
|
1267
|
-
const me = localSelfId();
|
|
1268
|
-
if (!me) return false;
|
|
1269
|
-
try {
|
|
1270
|
-
Promise.resolve(
|
|
1271
|
-
def.hostHandle(makeCtx(), payload, me)
|
|
1272
|
-
).catch(
|
|
1273
|
-
(err) => error(`multiplayer.match hostHandle('${String(name)}') threw:`, err)
|
|
1274
|
-
);
|
|
1275
|
-
} catch (err) {
|
|
1276
|
-
error(`multiplayer.match hostHandle('${String(name)}') threw:`, err);
|
|
1277
|
-
}
|
|
1278
|
-
return true;
|
|
1279
|
-
}
|
|
1280
|
-
return send(String(name), payload);
|
|
1281
|
-
}
|
|
1282
|
-
function apiBroadcast(name, payloadIn, callerOptions = {}) {
|
|
1283
|
-
if (destroyed || matchState === "aborted" || matchState === "ended") {
|
|
1284
|
-
warn(
|
|
1285
|
-
`multiplayer.match.broadcast('${String(name)}'): match is ${matchState}`
|
|
1286
|
-
);
|
|
1287
|
-
return false;
|
|
1288
|
-
}
|
|
1289
|
-
if (matchId == null) {
|
|
1290
|
-
warn(
|
|
1291
|
-
`multiplayer.match.broadcast('${String(name)}'): match has not started yet`
|
|
1292
|
-
);
|
|
1293
|
-
return false;
|
|
1294
|
-
}
|
|
1295
|
-
if (!localIsHost()) {
|
|
1296
|
-
warn(
|
|
1297
|
-
`multiplayer.match.broadcast('${String(name)}'): peer is not the host`
|
|
1298
|
-
);
|
|
1299
|
-
return false;
|
|
1300
|
-
}
|
|
1301
|
-
const payload = { ...payloadIn, matchId };
|
|
1302
|
-
const def = eventDefFor(String(name));
|
|
1303
|
-
const targeted = callerOptions.to !== void 0;
|
|
1304
|
-
if (!targeted) {
|
|
1305
|
-
const me = localSelfId() ?? "";
|
|
1306
|
-
maybeApply(String(name), def, payload, me, void 0, false);
|
|
1307
|
-
}
|
|
1308
|
-
const retain = !targeted && (callerOptions.retain ?? def?.retain ?? false);
|
|
1309
|
-
let retainKey;
|
|
1310
|
-
if (retain) {
|
|
1311
|
-
if (callerOptions.retainKey) {
|
|
1312
|
-
retainKey = callerOptions.retainKey;
|
|
1313
|
-
} else if (def?.retainKey) {
|
|
1314
|
-
try {
|
|
1315
|
-
retainKey = def.retainKey(payload);
|
|
1316
|
-
} catch (err) {
|
|
1317
|
-
error(
|
|
1318
|
-
`multiplayer.match retainKey('${String(name)}') threw \u2014 using event name:`,
|
|
1319
|
-
err
|
|
1320
|
-
);
|
|
1321
|
-
retainKey = String(name);
|
|
1322
|
-
}
|
|
1323
|
-
} else {
|
|
1324
|
-
retainKey = String(name);
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
const sendOptions = {};
|
|
1328
|
-
if (retain) {
|
|
1329
|
-
sendOptions.retain = true;
|
|
1330
|
-
sendOptions.retainKey = retainKey;
|
|
1331
|
-
}
|
|
1332
|
-
if (targeted) {
|
|
1333
|
-
sendOptions.to = callerOptions.to;
|
|
1334
|
-
}
|
|
1335
|
-
return broadcast(
|
|
1336
|
-
String(name),
|
|
1337
|
-
payload,
|
|
1338
|
-
Object.keys(sendOptions).length ? sendOptions : void 0
|
|
1339
|
-
);
|
|
1340
|
-
}
|
|
1341
|
-
function refreshWaiting() {
|
|
1342
|
-
if (matchId != null) return;
|
|
1343
|
-
const present = localPeers().length;
|
|
1344
|
-
const waiting = present < expectedPeers;
|
|
1345
|
-
options.onWaitingForPeers?.(waiting, present, expectedPeers);
|
|
1346
|
-
}
|
|
1347
|
-
function announceReadyIfWanted() {
|
|
1348
|
-
if (!wantReady) return;
|
|
1349
|
-
if (matchId != null) return;
|
|
1350
|
-
const me = localSelfId();
|
|
1351
|
-
if (!me) return;
|
|
1352
|
-
readyPeerIds.add(me);
|
|
1353
|
-
send(readyEventName, { readyAtMs: Date.now() });
|
|
1354
|
-
if (localIsHost()) void maybeStart();
|
|
1355
|
-
}
|
|
1356
|
-
async function maybeStart() {
|
|
1357
|
-
if (matchId != null || starting) return;
|
|
1358
|
-
if (!localIsHost()) return;
|
|
1359
|
-
const peers = localPeers();
|
|
1360
|
-
if (peers.length < expectedPeers) return;
|
|
1361
|
-
if (!peers.every((p) => readyPeerIds.has(p.peerId))) return;
|
|
1362
|
-
starting = true;
|
|
1363
|
-
setState("starting");
|
|
1364
|
-
try {
|
|
1365
|
-
const built = await options.buildStart(peers);
|
|
1366
|
-
const newMatchId = generateMatchId();
|
|
1367
|
-
const fullPayload = { ...built, matchId: newMatchId };
|
|
1368
|
-
broadcast(startEventName, fullPayload, {
|
|
1369
|
-
retain: true,
|
|
1370
|
-
retainKey: startRetainKey
|
|
1371
|
-
});
|
|
1372
|
-
matchId = newMatchId;
|
|
1373
|
-
setState("active");
|
|
1374
|
-
try {
|
|
1375
|
-
options.onStart(makeCtx(), fullPayload);
|
|
1376
|
-
} catch (err) {
|
|
1377
|
-
error("multiplayer.match onStart threw:", err);
|
|
1378
|
-
}
|
|
1379
|
-
} catch (err) {
|
|
1380
|
-
error("multiplayer.match buildStart threw:", err);
|
|
1381
|
-
setState("waiting");
|
|
1382
|
-
} finally {
|
|
1383
|
-
starting = false;
|
|
1384
|
-
}
|
|
1385
|
-
}
|
|
1386
|
-
function handleStartFrame(msg) {
|
|
1387
|
-
if (destroyed) return;
|
|
1388
|
-
const payload = msg?.payload ?? msg;
|
|
1389
|
-
if (!payload || typeof payload !== "object") return;
|
|
1390
|
-
if (typeof payload.matchId !== "string" || !payload.matchId) return;
|
|
1391
|
-
if (matchId === payload.matchId) return;
|
|
1392
|
-
matchId = payload.matchId;
|
|
1393
|
-
appliedIdKeys.clear();
|
|
1394
|
-
setState("active");
|
|
1395
|
-
const retained = msg?.retained === true;
|
|
1396
|
-
try {
|
|
1397
|
-
options.onStart(makeCtx(retained), payload);
|
|
1398
|
-
} catch (err) {
|
|
1399
|
-
error("multiplayer.match onStart threw:", err);
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1402
|
-
function handleReadyFrame(msg) {
|
|
1403
|
-
const fromPeerId = msg?.fromPeerId;
|
|
1404
|
-
if (typeof fromPeerId === "string" && fromPeerId) {
|
|
1405
|
-
readyPeerIds.add(fromPeerId);
|
|
1406
|
-
}
|
|
1407
|
-
if (localIsHost()) void maybeStart();
|
|
1408
|
-
}
|
|
1409
|
-
function handleUserEvent(eventName, msg) {
|
|
1410
|
-
if (destroyed) return;
|
|
1411
|
-
const payload = msg?.payload;
|
|
1412
|
-
if (!payload || typeof payload !== "object") return;
|
|
1413
|
-
if (matchId == null) return;
|
|
1414
|
-
if (typeof payload.matchId !== "string" || payload.matchId !== matchId) {
|
|
1415
|
-
return;
|
|
1416
|
-
}
|
|
1417
|
-
const def = eventDefFor(eventName);
|
|
1418
|
-
const fromPeerId = msg?.fromPeerId ?? "";
|
|
1419
|
-
const seq = msg?.seq;
|
|
1420
|
-
const retained = msg?.retained === true;
|
|
1421
|
-
if (def?.hostHandle && localIsHost() && fromPeerId !== localSelfId() && !retained) {
|
|
1422
|
-
try {
|
|
1423
|
-
Promise.resolve(
|
|
1424
|
-
def.hostHandle(makeCtx(false), payload, fromPeerId)
|
|
1425
|
-
).catch(
|
|
1426
|
-
(err) => error(
|
|
1427
|
-
`multiplayer.match hostHandle('${eventName}') threw:`,
|
|
1428
|
-
err
|
|
1429
|
-
)
|
|
1430
|
-
);
|
|
1431
|
-
} catch (err) {
|
|
1432
|
-
error(`multiplayer.match hostHandle('${eventName}') threw:`, err);
|
|
1433
|
-
}
|
|
1434
|
-
return;
|
|
1435
|
-
}
|
|
1436
|
-
maybeApply(eventName, def, payload, fromPeerId, seq, retained);
|
|
1437
|
-
}
|
|
1438
|
-
offHandlers.push(
|
|
1439
|
-
on("peer_joined", () => {
|
|
1440
|
-
refreshWaiting();
|
|
1441
|
-
if (localIsHost()) void maybeStart();
|
|
1442
|
-
})
|
|
1443
|
-
);
|
|
1444
|
-
offHandlers.push(
|
|
1445
|
-
on("connected", () => {
|
|
1446
|
-
announceReadyIfWanted();
|
|
1447
|
-
})
|
|
1448
|
-
);
|
|
1449
|
-
offHandlers.push(
|
|
1450
|
-
on("room_joined", () => {
|
|
1451
|
-
refreshWaiting();
|
|
1452
|
-
announceReadyIfWanted();
|
|
1453
|
-
if (localIsHost()) void maybeStart();
|
|
1454
|
-
})
|
|
1455
|
-
);
|
|
1456
|
-
offHandlers.push(
|
|
1457
|
-
on("peer_left", (msg) => {
|
|
1458
|
-
const leftId = msg?.peerId;
|
|
1459
|
-
if (typeof leftId === "string") readyPeerIds.delete(leftId);
|
|
1460
|
-
refreshWaiting();
|
|
1461
|
-
if (matchState === "active" && options.onPeerLeft && leftId) {
|
|
1462
|
-
try {
|
|
1463
|
-
options.onPeerLeft(makeCtx(), leftId);
|
|
1464
|
-
} catch (err) {
|
|
1465
|
-
error("multiplayer.match onPeerLeft threw:", err);
|
|
1466
|
-
}
|
|
1467
|
-
}
|
|
1468
|
-
if (matchId == null && localIsHost()) void maybeStart();
|
|
1469
|
-
})
|
|
1470
|
-
);
|
|
1471
|
-
offHandlers.push(
|
|
1472
|
-
on("disconnected", () => {
|
|
1473
|
-
if (matchState === "active" || matchState === "starting") {
|
|
1474
|
-
abort("disconnected");
|
|
1475
|
-
}
|
|
1476
|
-
})
|
|
1477
|
-
);
|
|
1478
|
-
offHandlers.push(
|
|
1479
|
-
on("room_closed", () => {
|
|
1480
|
-
abort("room_closed");
|
|
1481
|
-
})
|
|
1482
|
-
);
|
|
1483
|
-
offHandlers.push(on(readyEventName, handleReadyFrame));
|
|
1484
|
-
offHandlers.push(on(startEventName, handleStartFrame));
|
|
1485
|
-
for (const eventName of Object.keys(options.events)) {
|
|
1486
|
-
if (eventName === startEventName || eventName === readyEventName) {
|
|
1487
|
-
continue;
|
|
1488
|
-
}
|
|
1489
|
-
offHandlers.push(
|
|
1490
|
-
on(eventName, (msg) => handleUserEvent(eventName, msg))
|
|
1491
|
-
);
|
|
1492
|
-
}
|
|
1493
|
-
function abort(reason) {
|
|
1494
|
-
if (matchState === "aborted" || matchState === "ended") return;
|
|
1495
|
-
setState("aborted");
|
|
1496
|
-
try {
|
|
1497
|
-
options.onAborted?.(reason, { matchId });
|
|
1498
|
-
} catch (err) {
|
|
1499
|
-
error("multiplayer.match onAborted threw:", err);
|
|
1500
|
-
}
|
|
1501
|
-
}
|
|
1502
|
-
refreshWaiting();
|
|
1503
|
-
announceReadyIfWanted();
|
|
1504
|
-
const match = {
|
|
1505
|
-
get state() {
|
|
1506
|
-
return matchState;
|
|
1507
|
-
},
|
|
1508
|
-
get matchId() {
|
|
1509
|
-
return matchId;
|
|
1510
|
-
},
|
|
1511
|
-
intent: apiIntent,
|
|
1512
|
-
broadcast: apiBroadcast,
|
|
1513
|
-
markReady() {
|
|
1514
|
-
wantReady = true;
|
|
1515
|
-
announceReadyIfWanted();
|
|
1516
|
-
},
|
|
1517
|
-
onStateChange(handler) {
|
|
1518
|
-
stateChangeHandlers.add(handler);
|
|
1519
|
-
return () => {
|
|
1520
|
-
stateChangeHandlers.delete(handler);
|
|
1521
|
-
};
|
|
1522
|
-
},
|
|
1523
|
-
async destroy(opts) {
|
|
1524
|
-
if (destroyed) return;
|
|
1525
|
-
destroyed = true;
|
|
1526
|
-
for (const off of offHandlers) {
|
|
1527
|
-
try {
|
|
1528
|
-
off();
|
|
1529
|
-
} catch {
|
|
1530
|
-
}
|
|
1531
|
-
}
|
|
1532
|
-
offHandlers.length = 0;
|
|
1533
|
-
stateChangeHandlers.clear();
|
|
1534
|
-
readyPeerIds.clear();
|
|
1535
|
-
appliedIdKeys.clear();
|
|
1536
|
-
activeMatch = null;
|
|
1537
|
-
setState("ended");
|
|
1538
|
-
if (opts?.leaveRoom) {
|
|
1539
|
-
await leaveRoom("match_ended");
|
|
1540
|
-
}
|
|
1541
|
-
}
|
|
1542
|
-
};
|
|
1543
|
-
activeMatch = match;
|
|
1544
|
-
return match;
|
|
1545
|
-
}
|
|
1546
|
-
function assignSeats(peers, seatNames, hostPeerId) {
|
|
1547
|
-
const peerIds = peers.map((p) => p.peerId).filter(Boolean);
|
|
1548
|
-
const ordered = [];
|
|
1549
|
-
if (hostPeerId && peerIds.includes(hostPeerId)) {
|
|
1550
|
-
ordered.push(hostPeerId);
|
|
1551
|
-
}
|
|
1552
|
-
for (const id of [...peerIds].sort()) {
|
|
1553
|
-
if (id !== hostPeerId) ordered.push(id);
|
|
1554
|
-
}
|
|
1555
|
-
const bySeat = {};
|
|
1556
|
-
const byPeer = {};
|
|
1557
|
-
for (let i = 0; i < ordered.length; i++) {
|
|
1558
|
-
const seat = i < seatNames.length ? seatNames[i] : null;
|
|
1559
|
-
if (seat != null) bySeat[seat] = ordered[i];
|
|
1560
|
-
byPeer[ordered[i]] = seat;
|
|
1561
|
-
}
|
|
1562
|
-
return { bySeat, byPeer };
|
|
1563
|
-
}
|
|
1564
|
-
function waitForPeers(n, timeoutMs) {
|
|
1565
|
-
return new Promise((resolve, reject) => {
|
|
1566
|
-
let done = false;
|
|
1567
|
-
let timer = null;
|
|
1568
|
-
let offJoined = null;
|
|
1569
|
-
let offJoinedSystem = null;
|
|
1570
|
-
function cleanup() {
|
|
1571
|
-
done = true;
|
|
1572
|
-
if (timer != null) clearTimeout(timer);
|
|
1573
|
-
offJoined?.();
|
|
1574
|
-
offJoinedSystem?.();
|
|
1575
|
-
}
|
|
1576
|
-
function check() {
|
|
1577
|
-
if (done) return true;
|
|
1578
|
-
const peers = getPeers();
|
|
1579
|
-
if (peers.length >= n) {
|
|
1580
|
-
cleanup();
|
|
1581
|
-
resolve(peers);
|
|
1582
|
-
return true;
|
|
1583
|
-
}
|
|
1584
|
-
return false;
|
|
1585
|
-
}
|
|
1586
|
-
if (check()) return;
|
|
1587
|
-
offJoined = on("peer_joined", () => check());
|
|
1588
|
-
offJoinedSystem = on("room_joined", () => check());
|
|
1589
|
-
if (timeoutMs && timeoutMs > 0) {
|
|
1590
|
-
timer = setTimeout(() => {
|
|
1591
|
-
if (done) return;
|
|
1592
|
-
cleanup();
|
|
1593
|
-
reject(new Error("waitForPeers: timeout"));
|
|
1594
|
-
}, timeoutMs);
|
|
575
|
+
// src/match-context.ts
|
|
576
|
+
async function fetchMatchContext() {
|
|
577
|
+
if (!state.leagueId || !state.matchId) return null;
|
|
578
|
+
if (state.matchContext) return state.matchContext;
|
|
579
|
+
if (state.matchContextPromise) return await state.matchContextPromise;
|
|
580
|
+
state.matchContextPromise = apiRequest(
|
|
581
|
+
"/leagues/" + encodeURIComponent(state.leagueId) + "/matches/" + encodeURIComponent(state.matchId),
|
|
582
|
+
{ method: "GET" }
|
|
583
|
+
).then((result) => {
|
|
584
|
+
const data = unwrapResult(result);
|
|
585
|
+
if (result?.success && data) {
|
|
586
|
+
state.matchContext = data;
|
|
587
|
+
return state.matchContext;
|
|
1595
588
|
}
|
|
589
|
+
return null;
|
|
590
|
+
}).catch(() => null).finally(() => {
|
|
591
|
+
state.matchContextPromise = null;
|
|
1596
592
|
});
|
|
593
|
+
return await state.matchContextPromise;
|
|
1597
594
|
}
|
|
1598
595
|
|
|
1599
596
|
// src/main.ts
|
|
@@ -1623,8 +620,9 @@
|
|
|
1623
620
|
submitMatchResult(result = {}) {
|
|
1624
621
|
return submitMatchResult(result);
|
|
1625
622
|
},
|
|
1626
|
-
async
|
|
1627
|
-
|
|
623
|
+
async getMatchContext() {
|
|
624
|
+
await ensureInitialized();
|
|
625
|
+
return await fetchMatchContext();
|
|
1628
626
|
},
|
|
1629
627
|
notifyComplete(data = {}) {
|
|
1630
628
|
sendToParent("GAME_COMPLETE", data);
|
|
@@ -1632,6 +630,17 @@
|
|
|
1632
630
|
requestClose() {
|
|
1633
631
|
sendToParent("REQUEST_CLOSE", {});
|
|
1634
632
|
},
|
|
633
|
+
reportQuestion(data) {
|
|
634
|
+
sendToParent("QUESTION_REPORT", {
|
|
635
|
+
questionId: data.questionId,
|
|
636
|
+
prompt: data.prompt,
|
|
637
|
+
message: data.message,
|
|
638
|
+
questions: Array.isArray(data.questions) ? data.questions.map((q) => ({
|
|
639
|
+
questionId: q.questionId,
|
|
640
|
+
prompt: q.prompt
|
|
641
|
+
})) : void 0
|
|
642
|
+
});
|
|
643
|
+
},
|
|
1635
644
|
logEvent(eventName, eventData = {}) {
|
|
1636
645
|
sendToParent("LOG_EVENT", {
|
|
1637
646
|
event: eventName,
|
|
@@ -1654,50 +663,18 @@
|
|
|
1654
663
|
leagueId: state.leagueId,
|
|
1655
664
|
gameId: state.gameId,
|
|
1656
665
|
matchId: state.matchId,
|
|
1657
|
-
|
|
1658
|
-
participant1Id: state.participant1Id,
|
|
1659
|
-
participant2Id: state.participant2Id,
|
|
1660
|
-
participant1MemberIds: state.participant1MemberIds,
|
|
1661
|
-
participant2MemberIds: state.participant2MemberIds,
|
|
666
|
+
mode: state.bootstrapMode,
|
|
1662
667
|
playerName: state.bootstrapPlayerName,
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
role: state.bootstrapRoomRole,
|
|
1669
|
-
roomToken: state.bootstrapRoomToken,
|
|
1670
|
-
wsUrl: state.bootstrapWsUrl
|
|
1671
|
-
} : null,
|
|
668
|
+
playerCount: state.bootstrapPlayerCount,
|
|
669
|
+
teamOneName: state.bootstrapTeamOneName,
|
|
670
|
+
teamTwoName: state.bootstrapTeamTwoName,
|
|
671
|
+
profileId: state.bootstrapProfileId,
|
|
672
|
+
multiplayer: state.bootstrapMultiplayer,
|
|
1672
673
|
isBootstrapped: state.bootstrapReceived
|
|
1673
674
|
};
|
|
1674
675
|
},
|
|
1675
|
-
async getMatchContext() {
|
|
1676
|
-
await ensureInitialized();
|
|
1677
|
-
return await fetchMatchContext();
|
|
1678
|
-
},
|
|
1679
676
|
getQuestions(options = {}) {
|
|
1680
677
|
return getQuestions(options);
|
|
1681
|
-
},
|
|
1682
|
-
multiplayer: {
|
|
1683
|
-
createRoom,
|
|
1684
|
-
joinRoom,
|
|
1685
|
-
joinRoomByLink,
|
|
1686
|
-
leaveRoom,
|
|
1687
|
-
send,
|
|
1688
|
-
broadcast,
|
|
1689
|
-
on,
|
|
1690
|
-
getRoom,
|
|
1691
|
-
getPeers,
|
|
1692
|
-
isConnected,
|
|
1693
|
-
getRole,
|
|
1694
|
-
isHost,
|
|
1695
|
-
isViewer,
|
|
1696
|
-
selfId,
|
|
1697
|
-
serverNow,
|
|
1698
|
-
match: createMatch,
|
|
1699
|
-
assignSeats,
|
|
1700
|
-
waitForPeers
|
|
1701
678
|
}
|
|
1702
679
|
};
|
|
1703
680
|
}
|