@playcademy/sdk 0.3.1 → 0.3.3
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/dist/index.d.ts +29 -30
- package/dist/index.js +343 -233
- package/dist/internal.d.ts +4356 -4027
- package/dist/internal.js +596 -477
- package/dist/server.d.ts +4 -11
- package/dist/server.js +50 -22
- package/dist/types.d.ts +3080 -3080
- package/package.json +10 -9
package/dist/index.js
CHANGED
|
@@ -32,15 +32,15 @@ class PlaycademyMessaging {
|
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
listen(type, handler) {
|
|
35
|
-
|
|
35
|
+
function postMessageListener(event) {
|
|
36
36
|
const messageEvent = event;
|
|
37
37
|
if (messageEvent.data?.type === type) {
|
|
38
38
|
handler(messageEvent.data.payload || messageEvent.data);
|
|
39
39
|
}
|
|
40
|
-
}
|
|
41
|
-
|
|
40
|
+
}
|
|
41
|
+
function customEventListener(event) {
|
|
42
42
|
handler(event.detail);
|
|
43
|
-
}
|
|
43
|
+
}
|
|
44
44
|
if (!this.listeners.has(type)) {
|
|
45
45
|
this.listeners.set(type, new Map);
|
|
46
46
|
}
|
|
@@ -50,7 +50,7 @@ class PlaycademyMessaging {
|
|
|
50
50
|
customEvent: customEventListener
|
|
51
51
|
});
|
|
52
52
|
window.addEventListener("message", postMessageListener);
|
|
53
|
-
|
|
53
|
+
globalThis.addEventListener(type, customEventListener);
|
|
54
54
|
}
|
|
55
55
|
unlisten(type, handler) {
|
|
56
56
|
const typeListeners = this.listeners.get(type);
|
|
@@ -59,14 +59,14 @@ class PlaycademyMessaging {
|
|
|
59
59
|
}
|
|
60
60
|
const listeners = typeListeners.get(handler);
|
|
61
61
|
window.removeEventListener("message", listeners.postMessage);
|
|
62
|
-
|
|
62
|
+
globalThis.removeEventListener(type, listeners.customEvent);
|
|
63
63
|
typeListeners.delete(handler);
|
|
64
64
|
if (typeListeners.size === 0) {
|
|
65
65
|
this.listeners.delete(type);
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
68
|
getMessagingContext(eventType) {
|
|
69
|
-
const isIframe = typeof window !== "undefined" &&
|
|
69
|
+
const isIframe = typeof globalThis.window !== "undefined" && globalThis.self !== window.top;
|
|
70
70
|
const iframeToParentEvents = [
|
|
71
71
|
"PLAYCADEMY_READY" /* READY */,
|
|
72
72
|
"PLAYCADEMY_EXIT" /* EXIT */,
|
|
@@ -89,18 +89,18 @@ class PlaycademyMessaging {
|
|
|
89
89
|
target.postMessage(messageData, origin);
|
|
90
90
|
}
|
|
91
91
|
sendViaCustomEvent(type, payload) {
|
|
92
|
-
|
|
92
|
+
globalThis.dispatchEvent(new CustomEvent(type, { detail: payload }));
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
var messaging = new PlaycademyMessaging;
|
|
96
96
|
|
|
97
97
|
// src/core/static/init.ts
|
|
98
98
|
async function getPlaycademyConfig(allowedParentOrigins) {
|
|
99
|
-
const preloaded =
|
|
99
|
+
const preloaded = globalThis.PLAYCADEMY;
|
|
100
100
|
if (preloaded?.token) {
|
|
101
101
|
return preloaded;
|
|
102
102
|
}
|
|
103
|
-
if (
|
|
103
|
+
if (globalThis.self !== window.top) {
|
|
104
104
|
return await waitForPlaycademyInit(allowedParentOrigins);
|
|
105
105
|
} else {
|
|
106
106
|
return createStandaloneConfig();
|
|
@@ -114,13 +114,14 @@ function getReferrerOrigin() {
|
|
|
114
114
|
}
|
|
115
115
|
}
|
|
116
116
|
function buildAllowedOrigins(explicit) {
|
|
117
|
-
if (Array.isArray(explicit) && explicit.length > 0)
|
|
117
|
+
if (Array.isArray(explicit) && explicit.length > 0) {
|
|
118
118
|
return explicit;
|
|
119
|
+
}
|
|
119
120
|
const ref = getReferrerOrigin();
|
|
120
121
|
return ref ? [ref] : [];
|
|
121
122
|
}
|
|
122
123
|
function isOriginAllowed(origin, allowlist) {
|
|
123
|
-
if (
|
|
124
|
+
if (globalThis.location.hostname === "localhost" || globalThis.location.hostname === "127.0.0.1") {
|
|
124
125
|
return true;
|
|
125
126
|
}
|
|
126
127
|
if (!allowlist || allowlist.length === 0) {
|
|
@@ -136,14 +137,16 @@ async function waitForPlaycademyInit(allowedParentOrigins) {
|
|
|
136
137
|
const allowlist = buildAllowedOrigins(allowedParentOrigins);
|
|
137
138
|
let hasWarnedAboutUntrustedOrigin = false;
|
|
138
139
|
function warnAboutUntrustedOrigin(origin) {
|
|
139
|
-
if (hasWarnedAboutUntrustedOrigin)
|
|
140
|
+
if (hasWarnedAboutUntrustedOrigin) {
|
|
140
141
|
return;
|
|
142
|
+
}
|
|
141
143
|
hasWarnedAboutUntrustedOrigin = true;
|
|
142
144
|
console.warn("[Playcademy SDK] Ignoring INIT from untrusted origin:", origin);
|
|
143
145
|
}
|
|
144
|
-
|
|
145
|
-
if (event.data?.type !== "PLAYCADEMY_INIT" /* INIT */)
|
|
146
|
+
function handleMessage(event) {
|
|
147
|
+
if (event.data?.type !== "PLAYCADEMY_INIT" /* INIT */) {
|
|
146
148
|
return;
|
|
149
|
+
}
|
|
147
150
|
if (!isOriginAllowed(event.origin, allowlist)) {
|
|
148
151
|
warnAboutUntrustedOrigin(event.origin);
|
|
149
152
|
return;
|
|
@@ -151,9 +154,9 @@ async function waitForPlaycademyInit(allowedParentOrigins) {
|
|
|
151
154
|
contextReceived = true;
|
|
152
155
|
window.removeEventListener("message", handleMessage);
|
|
153
156
|
clearTimeout(timeoutId);
|
|
154
|
-
|
|
157
|
+
globalThis.PLAYCADEMY = event.data.payload;
|
|
155
158
|
resolve(event.data.payload);
|
|
156
|
-
}
|
|
159
|
+
}
|
|
157
160
|
window.addEventListener("message", handleMessage);
|
|
158
161
|
const timeoutId = setTimeout(() => {
|
|
159
162
|
if (!contextReceived) {
|
|
@@ -167,16 +170,16 @@ function createStandaloneConfig() {
|
|
|
167
170
|
console.debug("[Playcademy SDK] Standalone mode detected, creating mock context for sandbox development");
|
|
168
171
|
const mockConfig = {
|
|
169
172
|
baseUrl: "http://localhost:4321",
|
|
170
|
-
gameUrl:
|
|
173
|
+
gameUrl: globalThis.location.origin,
|
|
171
174
|
token: "mock-game-token-for-local-dev",
|
|
172
175
|
gameId: "mock-game-id-from-template",
|
|
173
176
|
realtimeUrl: undefined
|
|
174
177
|
};
|
|
175
|
-
|
|
178
|
+
globalThis.PLAYCADEMY = mockConfig;
|
|
176
179
|
return mockConfig;
|
|
177
180
|
}
|
|
178
181
|
async function init(options) {
|
|
179
|
-
if (typeof window === "undefined") {
|
|
182
|
+
if (typeof globalThis.window === "undefined") {
|
|
180
183
|
throw new Error("Playcademy SDK must run in a browser context");
|
|
181
184
|
}
|
|
182
185
|
const config = await getPlaycademyConfig(options?.allowedParentOrigins);
|
|
@@ -188,7 +191,7 @@ async function init(options) {
|
|
|
188
191
|
gameUrl: config.gameUrl,
|
|
189
192
|
token: config.token,
|
|
190
193
|
gameId: config.gameId,
|
|
191
|
-
autoStartSession:
|
|
194
|
+
autoStartSession: globalThis.self !== window.top,
|
|
192
195
|
onDisconnect: options?.onDisconnect,
|
|
193
196
|
enableConnectionMonitoring: options?.enableConnectionMonitoring
|
|
194
197
|
});
|
|
@@ -198,23 +201,23 @@ async function init(options) {
|
|
|
198
201
|
return client;
|
|
199
202
|
}
|
|
200
203
|
// ../logger/src/index.ts
|
|
201
|
-
|
|
204
|
+
function isBrowser() {
|
|
202
205
|
const g = globalThis;
|
|
203
206
|
return typeof g.window !== "undefined" && typeof g.document !== "undefined";
|
|
204
|
-
}
|
|
205
|
-
|
|
207
|
+
}
|
|
208
|
+
function isProduction() {
|
|
206
209
|
return typeof process !== "undefined" && false;
|
|
207
|
-
}
|
|
208
|
-
|
|
210
|
+
}
|
|
211
|
+
function isDevelopment() {
|
|
209
212
|
return typeof process !== "undefined" && true;
|
|
210
|
-
}
|
|
211
|
-
|
|
213
|
+
}
|
|
214
|
+
function isInteractiveTTY() {
|
|
212
215
|
return typeof process !== "undefined" && Boolean(process.stdout && process.stdout.isTTY);
|
|
213
|
-
}
|
|
214
|
-
|
|
216
|
+
}
|
|
217
|
+
function isSilent() {
|
|
215
218
|
return typeof process !== "undefined" && process.env.LOG_SILENT === "true";
|
|
216
|
-
}
|
|
217
|
-
|
|
219
|
+
}
|
|
220
|
+
function detectOutputFormat() {
|
|
218
221
|
if (isBrowser()) {
|
|
219
222
|
return "browser";
|
|
220
223
|
}
|
|
@@ -238,7 +241,7 @@ var detectOutputFormat = () => {
|
|
|
238
241
|
return "color-tty";
|
|
239
242
|
}
|
|
240
243
|
return "json-single-line";
|
|
241
|
-
}
|
|
244
|
+
}
|
|
242
245
|
var colors = {
|
|
243
246
|
reset: "\x1B[0m",
|
|
244
247
|
bold: "\x1B[1m",
|
|
@@ -249,21 +252,26 @@ var colors = {
|
|
|
249
252
|
cyan: "\x1B[36m",
|
|
250
253
|
gray: "\x1B[90m"
|
|
251
254
|
};
|
|
252
|
-
|
|
255
|
+
function getLevelColor(level) {
|
|
253
256
|
switch (level) {
|
|
254
|
-
case "debug":
|
|
257
|
+
case "debug": {
|
|
255
258
|
return colors.blue;
|
|
256
|
-
|
|
259
|
+
}
|
|
260
|
+
case "info": {
|
|
257
261
|
return colors.cyan;
|
|
258
|
-
|
|
262
|
+
}
|
|
263
|
+
case "warn": {
|
|
259
264
|
return colors.yellow;
|
|
260
|
-
|
|
265
|
+
}
|
|
266
|
+
case "error": {
|
|
261
267
|
return colors.red;
|
|
262
|
-
|
|
268
|
+
}
|
|
269
|
+
default: {
|
|
263
270
|
return colors.reset;
|
|
271
|
+
}
|
|
264
272
|
}
|
|
265
|
-
}
|
|
266
|
-
|
|
273
|
+
}
|
|
274
|
+
function formatBrowserOutput(level, message, context, scope) {
|
|
267
275
|
const timestamp = new Date().toISOString();
|
|
268
276
|
const levelUpper = level.toUpperCase();
|
|
269
277
|
const consoleMethod = getConsoleMethod(level);
|
|
@@ -273,8 +281,8 @@ var formatBrowserOutput = (level, message, context, scope) => {
|
|
|
273
281
|
} else {
|
|
274
282
|
consoleMethod(`[${timestamp}] ${levelUpper}`, `${scopePrefix}${message}`);
|
|
275
283
|
}
|
|
276
|
-
}
|
|
277
|
-
|
|
284
|
+
}
|
|
285
|
+
function formatColorTTY(level, message, context, scope) {
|
|
278
286
|
const timestamp = new Date().toISOString();
|
|
279
287
|
const levelColor = getLevelColor(level);
|
|
280
288
|
const levelUpper = level.toUpperCase().padEnd(5);
|
|
@@ -286,8 +294,8 @@ var formatColorTTY = (level, message, context, scope) => {
|
|
|
286
294
|
} else {
|
|
287
295
|
consoleMethod(`${coloredPrefix} ${scopePrefix}${message}`);
|
|
288
296
|
}
|
|
289
|
-
}
|
|
290
|
-
|
|
297
|
+
}
|
|
298
|
+
function formatJSONSingleLine(level, message, context, scope) {
|
|
291
299
|
const timestamp = new Date().toISOString();
|
|
292
300
|
const logEntry = {
|
|
293
301
|
timestamp,
|
|
@@ -298,8 +306,8 @@ var formatJSONSingleLine = (level, message, context, scope) => {
|
|
|
298
306
|
};
|
|
299
307
|
const consoleMethod = getConsoleMethod(level);
|
|
300
308
|
consoleMethod(JSON.stringify(logEntry));
|
|
301
|
-
}
|
|
302
|
-
|
|
309
|
+
}
|
|
310
|
+
function formatJSONPretty(level, message, context, scope) {
|
|
303
311
|
const timestamp = new Date().toISOString();
|
|
304
312
|
const logEntry = {
|
|
305
313
|
timestamp,
|
|
@@ -310,65 +318,76 @@ var formatJSONPretty = (level, message, context, scope) => {
|
|
|
310
318
|
};
|
|
311
319
|
const consoleMethod = getConsoleMethod(level);
|
|
312
320
|
consoleMethod(JSON.stringify(logEntry, null, 2));
|
|
313
|
-
}
|
|
314
|
-
|
|
321
|
+
}
|
|
322
|
+
function getConsoleMethod(level) {
|
|
315
323
|
switch (level) {
|
|
316
|
-
case "debug":
|
|
324
|
+
case "debug": {
|
|
317
325
|
return console.debug;
|
|
318
|
-
|
|
326
|
+
}
|
|
327
|
+
case "info": {
|
|
319
328
|
return console.info;
|
|
320
|
-
|
|
329
|
+
}
|
|
330
|
+
case "warn": {
|
|
321
331
|
return console.warn;
|
|
322
|
-
|
|
332
|
+
}
|
|
333
|
+
case "error": {
|
|
323
334
|
return console.error;
|
|
324
|
-
|
|
335
|
+
}
|
|
336
|
+
default: {
|
|
325
337
|
return console.log;
|
|
338
|
+
}
|
|
326
339
|
}
|
|
327
|
-
}
|
|
340
|
+
}
|
|
328
341
|
var levelPriority = {
|
|
329
342
|
debug: 0,
|
|
330
343
|
info: 1,
|
|
331
344
|
warn: 2,
|
|
332
345
|
error: 3
|
|
333
346
|
};
|
|
334
|
-
|
|
347
|
+
function getMinimumLogLevel() {
|
|
335
348
|
const envLevel = typeof process !== "undefined" ? (process.env.LOG_LEVEL ?? "").toLowerCase() : "";
|
|
336
349
|
if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
|
|
337
350
|
return envLevel;
|
|
338
351
|
}
|
|
339
352
|
return isProduction() ? "info" : "debug";
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
if (isSilent())
|
|
353
|
+
}
|
|
354
|
+
function shouldLog(level) {
|
|
355
|
+
if (isSilent()) {
|
|
343
356
|
return false;
|
|
357
|
+
}
|
|
344
358
|
const minLevel = getMinimumLogLevel();
|
|
345
359
|
return levelPriority[level] >= levelPriority[minLevel];
|
|
346
|
-
}
|
|
360
|
+
}
|
|
347
361
|
var customHandler;
|
|
348
|
-
|
|
349
|
-
if (!shouldLog(level))
|
|
362
|
+
function performLog(level, message, context, scope) {
|
|
363
|
+
if (!shouldLog(level)) {
|
|
350
364
|
return;
|
|
365
|
+
}
|
|
351
366
|
if (customHandler) {
|
|
352
367
|
customHandler(level, message, context, scope);
|
|
353
368
|
return;
|
|
354
369
|
}
|
|
355
370
|
const outputFormat = detectOutputFormat();
|
|
356
371
|
switch (outputFormat) {
|
|
357
|
-
case "browser":
|
|
372
|
+
case "browser": {
|
|
358
373
|
formatBrowserOutput(level, message, context, scope);
|
|
359
374
|
break;
|
|
360
|
-
|
|
375
|
+
}
|
|
376
|
+
case "color-tty": {
|
|
361
377
|
formatColorTTY(level, message, context, scope);
|
|
362
378
|
break;
|
|
363
|
-
|
|
379
|
+
}
|
|
380
|
+
case "json-single-line": {
|
|
364
381
|
formatJSONSingleLine(level, message, context, scope);
|
|
365
382
|
break;
|
|
366
|
-
|
|
383
|
+
}
|
|
384
|
+
case "json-pretty": {
|
|
367
385
|
formatJSONPretty(level, message, context, scope);
|
|
368
386
|
break;
|
|
387
|
+
}
|
|
369
388
|
}
|
|
370
|
-
}
|
|
371
|
-
|
|
389
|
+
}
|
|
390
|
+
function createLogger(scopeName) {
|
|
372
391
|
return {
|
|
373
392
|
debug: (message, context) => performLog("debug", message, context, scopeName),
|
|
374
393
|
info: (message, context) => performLog("info", message, context, scopeName),
|
|
@@ -377,7 +396,7 @@ var createLogger = (scopeName) => {
|
|
|
377
396
|
log: (level, message, context) => performLog(level, message, context, scopeName),
|
|
378
397
|
scope: (name) => createLogger(scopeName ? `${scopeName}.${name}` : name)
|
|
379
398
|
};
|
|
380
|
-
}
|
|
399
|
+
}
|
|
381
400
|
var log = createLogger();
|
|
382
401
|
|
|
383
402
|
// src/core/errors.ts
|
|
@@ -388,15 +407,25 @@ class PlaycademyError extends Error {
|
|
|
388
407
|
}
|
|
389
408
|
}
|
|
390
409
|
|
|
410
|
+
class ManifestError extends PlaycademyError {
|
|
411
|
+
kind;
|
|
412
|
+
constructor(message, kind) {
|
|
413
|
+
super(message);
|
|
414
|
+
this.name = "ManifestError";
|
|
415
|
+
this.kind = kind;
|
|
416
|
+
Object.setPrototypeOf(this, ManifestError.prototype);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
391
420
|
class ApiError extends Error {
|
|
392
|
-
status;
|
|
393
421
|
code;
|
|
394
422
|
details;
|
|
395
423
|
rawBody;
|
|
424
|
+
status;
|
|
396
425
|
constructor(status, code, message, details, rawBody) {
|
|
397
426
|
super(message);
|
|
398
|
-
this.status = status;
|
|
399
427
|
this.name = "ApiError";
|
|
428
|
+
this.status = status;
|
|
400
429
|
this.code = code;
|
|
401
430
|
this.details = details;
|
|
402
431
|
this.rawBody = rawBody;
|
|
@@ -427,38 +456,54 @@ class ApiError extends Error {
|
|
|
427
456
|
}
|
|
428
457
|
function statusCodeToErrorCode(status) {
|
|
429
458
|
switch (status) {
|
|
430
|
-
case 400:
|
|
459
|
+
case 400: {
|
|
431
460
|
return "BAD_REQUEST";
|
|
432
|
-
|
|
461
|
+
}
|
|
462
|
+
case 401: {
|
|
433
463
|
return "UNAUTHORIZED";
|
|
434
|
-
|
|
464
|
+
}
|
|
465
|
+
case 403: {
|
|
435
466
|
return "FORBIDDEN";
|
|
436
|
-
|
|
467
|
+
}
|
|
468
|
+
case 404: {
|
|
437
469
|
return "NOT_FOUND";
|
|
438
|
-
|
|
470
|
+
}
|
|
471
|
+
case 405: {
|
|
439
472
|
return "METHOD_NOT_ALLOWED";
|
|
440
|
-
|
|
473
|
+
}
|
|
474
|
+
case 409: {
|
|
441
475
|
return "CONFLICT";
|
|
442
|
-
|
|
476
|
+
}
|
|
477
|
+
case 410: {
|
|
443
478
|
return "GONE";
|
|
444
|
-
|
|
479
|
+
}
|
|
480
|
+
case 412: {
|
|
445
481
|
return "PRECONDITION_FAILED";
|
|
446
|
-
|
|
482
|
+
}
|
|
483
|
+
case 413: {
|
|
447
484
|
return "PAYLOAD_TOO_LARGE";
|
|
448
|
-
|
|
485
|
+
}
|
|
486
|
+
case 422: {
|
|
449
487
|
return "VALIDATION_FAILED";
|
|
450
|
-
|
|
488
|
+
}
|
|
489
|
+
case 429: {
|
|
451
490
|
return "TOO_MANY_REQUESTS";
|
|
452
|
-
|
|
491
|
+
}
|
|
492
|
+
case 500: {
|
|
453
493
|
return "INTERNAL_ERROR";
|
|
454
|
-
|
|
494
|
+
}
|
|
495
|
+
case 501: {
|
|
455
496
|
return "NOT_IMPLEMENTED";
|
|
456
|
-
|
|
497
|
+
}
|
|
498
|
+
case 503: {
|
|
457
499
|
return "SERVICE_UNAVAILABLE";
|
|
458
|
-
|
|
500
|
+
}
|
|
501
|
+
case 504: {
|
|
459
502
|
return "TIMEOUT";
|
|
460
|
-
|
|
503
|
+
}
|
|
504
|
+
default: {
|
|
461
505
|
return status >= 500 ? "INTERNAL_ERROR" : "BAD_REQUEST";
|
|
506
|
+
}
|
|
462
507
|
}
|
|
463
508
|
}
|
|
464
509
|
function extractApiErrorInfo(error) {
|
|
@@ -476,10 +521,10 @@ function extractApiErrorInfo(error) {
|
|
|
476
521
|
// src/core/static/login.ts
|
|
477
522
|
async function login(baseUrl, email, password) {
|
|
478
523
|
let url = baseUrl;
|
|
479
|
-
if (baseUrl.startsWith("/") && typeof window !== "undefined") {
|
|
480
|
-
url =
|
|
524
|
+
if (baseUrl.startsWith("/") && typeof globalThis.window !== "undefined") {
|
|
525
|
+
url = globalThis.location.origin + baseUrl;
|
|
481
526
|
}
|
|
482
|
-
url
|
|
527
|
+
url += "/auth/login";
|
|
483
528
|
const response = await fetch(url, {
|
|
484
529
|
method: "POST",
|
|
485
530
|
headers: {
|
|
@@ -490,7 +535,7 @@ async function login(baseUrl, email, password) {
|
|
|
490
535
|
if (!response.ok) {
|
|
491
536
|
try {
|
|
492
537
|
const errorData = await response.json();
|
|
493
|
-
const errorMessage = errorData && errorData.message ? String(errorData.message) : response.statusText;
|
|
538
|
+
const errorMessage = errorData && errorData.message !== undefined ? String(errorData.message) : response.statusText;
|
|
494
539
|
throw new PlaycademyError(errorMessage);
|
|
495
540
|
} catch (error) {
|
|
496
541
|
log.error("[Playcademy SDK] Failed to parse error response JSON, using status text instead:", { error });
|
|
@@ -504,7 +549,7 @@ async function generateSecureRandomString(length) {
|
|
|
504
549
|
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
|
|
505
550
|
const randomValues = new Uint8Array(length);
|
|
506
551
|
globalThis.crypto.getRandomValues(randomValues);
|
|
507
|
-
return
|
|
552
|
+
return [...randomValues].map((byte) => charset[byte % charset.length]).join("");
|
|
508
553
|
}
|
|
509
554
|
|
|
510
555
|
// src/core/auth/oauth.ts
|
|
@@ -546,8 +591,9 @@ function parseOAuthState(state) {
|
|
|
546
591
|
}
|
|
547
592
|
function getOAuthConfig(provider) {
|
|
548
593
|
const configGetter = OAUTH_CONFIGS[provider];
|
|
549
|
-
if (!configGetter)
|
|
594
|
+
if (!configGetter) {
|
|
550
595
|
throw new Error(`Unsupported auth provider: ${provider}`);
|
|
596
|
+
}
|
|
551
597
|
return configGetter();
|
|
552
598
|
}
|
|
553
599
|
|
|
@@ -574,11 +620,11 @@ function openPopupWindow(url, name = "auth-popup", width = 500, height = 600) {
|
|
|
574
620
|
return window.open(url, name, features);
|
|
575
621
|
}
|
|
576
622
|
function isInIframe() {
|
|
577
|
-
if (typeof window === "undefined") {
|
|
623
|
+
if (typeof globalThis.window === "undefined") {
|
|
578
624
|
return false;
|
|
579
625
|
}
|
|
580
626
|
try {
|
|
581
|
-
return
|
|
627
|
+
return globalThis.self !== window.top;
|
|
582
628
|
} catch {
|
|
583
629
|
return true;
|
|
584
630
|
}
|
|
@@ -631,9 +677,10 @@ async function initiatePopupFlow(options) {
|
|
|
631
677
|
async function waitForServerMessage(popup, onStateChange) {
|
|
632
678
|
return new Promise((resolve) => {
|
|
633
679
|
let resolved = false;
|
|
634
|
-
|
|
635
|
-
if (event.origin !==
|
|
680
|
+
function handleMessage(event) {
|
|
681
|
+
if (event.origin !== globalThis.location.origin) {
|
|
636
682
|
return;
|
|
683
|
+
}
|
|
637
684
|
const data = event.data;
|
|
638
685
|
if (data?.type === "PLAYCADEMY_AUTH_STATE_CHANGE") {
|
|
639
686
|
resolved = true;
|
|
@@ -660,7 +707,7 @@ async function waitForServerMessage(popup, onStateChange) {
|
|
|
660
707
|
});
|
|
661
708
|
}
|
|
662
709
|
}
|
|
663
|
-
}
|
|
710
|
+
}
|
|
664
711
|
window.addEventListener("message", handleMessage);
|
|
665
712
|
const checkClosed = setInterval(() => {
|
|
666
713
|
if (popup.closed && !resolved) {
|
|
@@ -722,7 +769,7 @@ async function initiateRedirectFlow(options) {
|
|
|
722
769
|
params.set("scope", config.scope);
|
|
723
770
|
}
|
|
724
771
|
const authUrl = `${config.authorizationEndpoint}?${params.toString()}`;
|
|
725
|
-
|
|
772
|
+
globalThis.location.href = authUrl;
|
|
726
773
|
return new Promise(() => {});
|
|
727
774
|
} catch (error) {
|
|
728
775
|
const errorMessage = error instanceof Error ? error.message : "Authentication failed";
|
|
@@ -738,14 +785,22 @@ async function initiateRedirectFlow(options) {
|
|
|
738
785
|
// src/core/auth/flows/unified.ts
|
|
739
786
|
async function initiateUnifiedFlow(options) {
|
|
740
787
|
const { mode = "auto" } = options;
|
|
741
|
-
|
|
788
|
+
let effectiveMode;
|
|
789
|
+
if (mode === "auto") {
|
|
790
|
+
effectiveMode = isInIframe() ? "popup" : "redirect";
|
|
791
|
+
} else {
|
|
792
|
+
effectiveMode = mode;
|
|
793
|
+
}
|
|
742
794
|
switch (effectiveMode) {
|
|
743
|
-
case "popup":
|
|
795
|
+
case "popup": {
|
|
744
796
|
return initiatePopupFlow(options);
|
|
745
|
-
|
|
797
|
+
}
|
|
798
|
+
case "redirect": {
|
|
746
799
|
return initiateRedirectFlow(options);
|
|
747
|
-
|
|
800
|
+
}
|
|
801
|
+
default: {
|
|
748
802
|
throw new Error(`Unsupported authentication mode: ${effectiveMode}`);
|
|
803
|
+
}
|
|
749
804
|
}
|
|
750
805
|
}
|
|
751
806
|
|
|
@@ -767,7 +822,7 @@ async function login2(client, options) {
|
|
|
767
822
|
provider: options.provider,
|
|
768
823
|
mode: options.mode || "auto",
|
|
769
824
|
callbackUrl: options.callbackUrl,
|
|
770
|
-
hasStateData:
|
|
825
|
+
hasStateData: Boolean(stateData)
|
|
771
826
|
});
|
|
772
827
|
const optionsWithState = {
|
|
773
828
|
...options,
|
|
@@ -802,13 +857,13 @@ function createIdentityNamespace(client) {
|
|
|
802
857
|
// src/namespaces/game/runtime.ts
|
|
803
858
|
function createRuntimeNamespace(client) {
|
|
804
859
|
const eventListeners = new Map;
|
|
805
|
-
|
|
860
|
+
function trackListener(eventType, handler) {
|
|
806
861
|
if (!eventListeners.has(eventType)) {
|
|
807
862
|
eventListeners.set(eventType, new Set);
|
|
808
863
|
}
|
|
809
864
|
eventListeners.get(eventType).add(handler);
|
|
810
|
-
}
|
|
811
|
-
|
|
865
|
+
}
|
|
866
|
+
function untrackListener(eventType, handler) {
|
|
812
867
|
const listeners = eventListeners.get(eventType);
|
|
813
868
|
if (listeners) {
|
|
814
869
|
listeners.delete(handler);
|
|
@@ -816,12 +871,9 @@ function createRuntimeNamespace(client) {
|
|
|
816
871
|
eventListeners.delete(eventType);
|
|
817
872
|
}
|
|
818
873
|
}
|
|
819
|
-
}
|
|
820
|
-
if (typeof window !== "undefined" &&
|
|
821
|
-
|
|
822
|
-
const forwardKeys = Array.isArray(playcademyConfig?.forwardKeys) ? playcademyConfig.forwardKeys : ["Escape"];
|
|
823
|
-
const keySet = new Set(forwardKeys.map((k) => k.toLowerCase()));
|
|
824
|
-
const keyListener = (event) => {
|
|
874
|
+
}
|
|
875
|
+
if (typeof globalThis.window !== "undefined" && globalThis.self !== window.top) {
|
|
876
|
+
let keyListener = function(event) {
|
|
825
877
|
if (keySet.has(event.key?.toLowerCase() ?? "") || keySet.has(event.code?.toLowerCase() ?? "")) {
|
|
826
878
|
messaging.send("PLAYCADEMY_KEY_EVENT" /* KEY_EVENT */, {
|
|
827
879
|
key: event.key,
|
|
@@ -830,11 +882,14 @@ function createRuntimeNamespace(client) {
|
|
|
830
882
|
});
|
|
831
883
|
}
|
|
832
884
|
};
|
|
833
|
-
|
|
834
|
-
|
|
885
|
+
const playcademyConfig = globalThis.PLAYCADEMY;
|
|
886
|
+
const forwardKeys = Array.isArray(playcademyConfig?.forwardKeys) ? playcademyConfig.forwardKeys : ["Escape"];
|
|
887
|
+
const keySet = new Set(forwardKeys.map((k) => k.toLowerCase()));
|
|
888
|
+
globalThis.addEventListener("keydown", keyListener);
|
|
889
|
+
globalThis.addEventListener("keyup", keyListener);
|
|
835
890
|
trackListener("PLAYCADEMY_FORCE_EXIT" /* FORCE_EXIT */, () => {
|
|
836
|
-
|
|
837
|
-
|
|
891
|
+
globalThis.removeEventListener("keydown", keyListener);
|
|
892
|
+
globalThis.removeEventListener("keyup", keyListener);
|
|
838
893
|
});
|
|
839
894
|
}
|
|
840
895
|
return {
|
|
@@ -911,32 +966,30 @@ function createRuntimeNamespace(client) {
|
|
|
911
966
|
};
|
|
912
967
|
}
|
|
913
968
|
function createAssetsNamespace(client) {
|
|
914
|
-
|
|
969
|
+
async function fetchAsset(path, options) {
|
|
915
970
|
const gameUrl = client["initPayload"]?.gameUrl;
|
|
916
971
|
if (!gameUrl) {
|
|
917
|
-
const relativePath = path.startsWith("./") ? path :
|
|
972
|
+
const relativePath = path.startsWith("./") ? path : `./${path}`;
|
|
918
973
|
return fetch(relativePath, options);
|
|
919
974
|
}
|
|
920
975
|
const cleanPath = path.startsWith("./") ? path.slice(2) : path;
|
|
921
|
-
return fetch(gameUrl
|
|
922
|
-
}
|
|
976
|
+
return fetch(`${gameUrl}${cleanPath}`, options);
|
|
977
|
+
}
|
|
923
978
|
return {
|
|
924
979
|
url(pathOrStrings, ...values) {
|
|
925
980
|
const gameUrl = client["initPayload"]?.gameUrl;
|
|
926
981
|
let path;
|
|
927
982
|
if (Array.isArray(pathOrStrings) && "raw" in pathOrStrings) {
|
|
928
983
|
const strings = pathOrStrings;
|
|
929
|
-
path = strings.reduce((acc, str, i) =>
|
|
930
|
-
return acc + str + (values[i] != null ? String(values[i]) : "");
|
|
931
|
-
}, "");
|
|
984
|
+
path = strings.reduce((acc, str, i) => acc + str + (values[i] != null ? String(values[i]) : ""), "");
|
|
932
985
|
} else {
|
|
933
986
|
path = pathOrStrings;
|
|
934
987
|
}
|
|
935
988
|
if (!gameUrl) {
|
|
936
|
-
return path.startsWith("./") ? path :
|
|
989
|
+
return path.startsWith("./") ? path : `./${path}`;
|
|
937
990
|
}
|
|
938
991
|
const cleanPath = path.startsWith("./") ? path.slice(2) : path;
|
|
939
|
-
return gameUrl
|
|
992
|
+
return `${gameUrl}${cleanPath}`;
|
|
940
993
|
},
|
|
941
994
|
fetch: fetchAsset,
|
|
942
995
|
json: async (path) => {
|
|
@@ -958,10 +1011,10 @@ function createAssetsNamespace(client) {
|
|
|
958
1011
|
};
|
|
959
1012
|
}
|
|
960
1013
|
// src/namespaces/game/backend.ts
|
|
1014
|
+
function normalizePath(path) {
|
|
1015
|
+
return path.startsWith("/") ? path : `/${path}`;
|
|
1016
|
+
}
|
|
961
1017
|
function createBackendNamespace(client) {
|
|
962
|
-
function normalizePath(path) {
|
|
963
|
-
return path.startsWith("/") ? path : `/${path}`;
|
|
964
|
-
}
|
|
965
1018
|
return {
|
|
966
1019
|
async get(path, headers) {
|
|
967
1020
|
return client["requestGameBackend"](normalizePath(path), "GET", undefined, headers);
|
|
@@ -987,9 +1040,7 @@ function createBackendNamespace(client) {
|
|
|
987
1040
|
url(pathOrStrings, ...values) {
|
|
988
1041
|
if (Array.isArray(pathOrStrings) && "raw" in pathOrStrings) {
|
|
989
1042
|
const strings = pathOrStrings;
|
|
990
|
-
const path2 = strings.reduce((acc, str, i) =>
|
|
991
|
-
return acc + str + (values[i] != null ? String(values[i]) : "");
|
|
992
|
-
}, "");
|
|
1043
|
+
const path2 = strings.reduce((acc, str, i) => acc + str + (values[i] != null ? String(values[i]) : ""), "");
|
|
993
1044
|
return `${client.gameUrl}/api${path2.startsWith("/") ? path2 : `/${path2}`}`;
|
|
994
1045
|
}
|
|
995
1046
|
const path = pathOrStrings;
|
|
@@ -1003,8 +1054,9 @@ function createPermanentCache(keyPrefix) {
|
|
|
1003
1054
|
async function get(key, loader) {
|
|
1004
1055
|
const fullKey = keyPrefix ? `${keyPrefix}:${key}` : key;
|
|
1005
1056
|
const existing = cache.get(fullKey);
|
|
1006
|
-
if (existing)
|
|
1057
|
+
if (existing) {
|
|
1007
1058
|
return existing;
|
|
1059
|
+
}
|
|
1008
1060
|
const promise = loader().catch((error) => {
|
|
1009
1061
|
cache.delete(fullKey);
|
|
1010
1062
|
throw error;
|
|
@@ -1042,23 +1094,23 @@ function createPermanentCache(keyPrefix) {
|
|
|
1042
1094
|
function createUsersNamespace(client) {
|
|
1043
1095
|
const itemIdCache = createPermanentCache("items");
|
|
1044
1096
|
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1045
|
-
|
|
1046
|
-
if (UUID_REGEX.test(identifier))
|
|
1097
|
+
async function resolveItemId(identifier) {
|
|
1098
|
+
if (UUID_REGEX.test(identifier)) {
|
|
1047
1099
|
return identifier;
|
|
1100
|
+
}
|
|
1048
1101
|
const gameId = client["gameId"];
|
|
1049
1102
|
const cacheKey = gameId ? `${identifier}:${gameId}` : identifier;
|
|
1050
1103
|
return itemIdCache.get(cacheKey, async () => {
|
|
1051
1104
|
const queryParams = new URLSearchParams({ slug: identifier });
|
|
1052
|
-
if (gameId)
|
|
1105
|
+
if (gameId) {
|
|
1053
1106
|
queryParams.append("gameId", gameId);
|
|
1107
|
+
}
|
|
1054
1108
|
const item = await client["request"](`/items/resolve?${queryParams.toString()}`, "GET");
|
|
1055
1109
|
return item.id;
|
|
1056
1110
|
});
|
|
1057
|
-
}
|
|
1111
|
+
}
|
|
1058
1112
|
return {
|
|
1059
|
-
me: async () =>
|
|
1060
|
-
return client["request"]("/users/me", "GET");
|
|
1061
|
-
},
|
|
1113
|
+
me: async () => client["request"]("/users/me", "GET"),
|
|
1062
1114
|
inventory: {
|
|
1063
1115
|
get: async () => client["request"](`/inventory`, "GET"),
|
|
1064
1116
|
add: async (identifier, qty) => {
|
|
@@ -1185,8 +1237,15 @@ var ACHIEVEMENT_DEFINITIONS = [
|
|
|
1185
1237
|
}
|
|
1186
1238
|
];
|
|
1187
1239
|
// ../constants/src/typescript.ts
|
|
1188
|
-
var
|
|
1189
|
-
|
|
1240
|
+
var TypeScriptPackages = {
|
|
1241
|
+
tsc: "tsc",
|
|
1242
|
+
nativePreview: "@typescript/native-preview",
|
|
1243
|
+
nativePreviewPinned: "@typescript/native-preview@7.0.0-dev.20260221.1"
|
|
1244
|
+
};
|
|
1245
|
+
var TYPESCRIPT_RUNNER = {
|
|
1246
|
+
package: TypeScriptPackages.nativePreviewPinned,
|
|
1247
|
+
bin: "tsgo"
|
|
1248
|
+
};
|
|
1190
1249
|
// ../constants/src/overworld.ts
|
|
1191
1250
|
var ITEM_SLUGS = {
|
|
1192
1251
|
PLAYCADEMY_CREDITS: "PLAYCADEMY_CREDITS",
|
|
@@ -1241,7 +1300,7 @@ function createSingletonCache() {
|
|
|
1241
1300
|
// src/namespaces/game/credits.ts
|
|
1242
1301
|
function createCreditsNamespace(client) {
|
|
1243
1302
|
const creditsIdCache = createSingletonCache();
|
|
1244
|
-
|
|
1303
|
+
async function getCreditsItemId() {
|
|
1245
1304
|
return creditsIdCache.get(async () => {
|
|
1246
1305
|
const queryParams = new URLSearchParams({ slug: CURRENCIES.PRIMARY });
|
|
1247
1306
|
const creditsItem = await client["request"](`/items/resolve?${queryParams.toString()}`, "GET");
|
|
@@ -1250,7 +1309,7 @@ function createCreditsNamespace(client) {
|
|
|
1250
1309
|
}
|
|
1251
1310
|
return creditsItem.id;
|
|
1252
1311
|
});
|
|
1253
|
-
}
|
|
1312
|
+
}
|
|
1254
1313
|
return {
|
|
1255
1314
|
balance: async () => {
|
|
1256
1315
|
const inventory = await client["request"]("/inventory", "GET");
|
|
@@ -1298,14 +1357,12 @@ function createCreditsNamespace(client) {
|
|
|
1298
1357
|
// src/namespaces/game/scores.ts
|
|
1299
1358
|
function createScoresNamespace(client) {
|
|
1300
1359
|
return {
|
|
1301
|
-
submit: async (gameId, score, metadata) => {
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
});
|
|
1308
|
-
}
|
|
1360
|
+
submit: async (gameId, score, metadata) => client["request"](`/games/${gameId}/scores`, "POST", {
|
|
1361
|
+
body: {
|
|
1362
|
+
score,
|
|
1363
|
+
metadata
|
|
1364
|
+
}
|
|
1365
|
+
})
|
|
1309
1366
|
};
|
|
1310
1367
|
}
|
|
1311
1368
|
// src/namespaces/game/realtime.ts
|
|
@@ -1379,8 +1436,9 @@ function createTTLCache(options) {
|
|
|
1379
1436
|
function has(key) {
|
|
1380
1437
|
const fullKey = keyPrefix ? `${keyPrefix}:${key}` : key;
|
|
1381
1438
|
const cached = cache.get(fullKey);
|
|
1382
|
-
if (!cached)
|
|
1439
|
+
if (!cached) {
|
|
1383
1440
|
return false;
|
|
1441
|
+
}
|
|
1384
1442
|
const now = Date.now();
|
|
1385
1443
|
if (cached.expiresAt <= now) {
|
|
1386
1444
|
cache.delete(fullKey);
|
|
@@ -1422,7 +1480,9 @@ function createTimebackNamespace(client) {
|
|
|
1422
1480
|
ttl: 5000,
|
|
1423
1481
|
keyPrefix: "game.timeback.xp"
|
|
1424
1482
|
});
|
|
1425
|
-
|
|
1483
|
+
function getTimeback() {
|
|
1484
|
+
return client["initPayload"]?.timeback;
|
|
1485
|
+
}
|
|
1426
1486
|
return {
|
|
1427
1487
|
get user() {
|
|
1428
1488
|
return {
|
|
@@ -1438,21 +1498,19 @@ function createTimebackNamespace(client) {
|
|
|
1438
1498
|
get organizations() {
|
|
1439
1499
|
return getTimeback()?.organizations ?? [];
|
|
1440
1500
|
},
|
|
1441
|
-
fetch: async (options) => {
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
}, options);
|
|
1455
|
-
},
|
|
1501
|
+
fetch: async (options) => userCache.get("current", async () => {
|
|
1502
|
+
const response = await client["request"]("/timeback/user", "GET");
|
|
1503
|
+
const initPayload = client["initPayload"];
|
|
1504
|
+
if (initPayload) {
|
|
1505
|
+
initPayload.timeback = response;
|
|
1506
|
+
}
|
|
1507
|
+
return {
|
|
1508
|
+
id: response.id,
|
|
1509
|
+
role: response.role,
|
|
1510
|
+
enrollments: response.enrollments,
|
|
1511
|
+
organizations: response.organizations
|
|
1512
|
+
};
|
|
1513
|
+
}, options),
|
|
1456
1514
|
xp: {
|
|
1457
1515
|
fetch: async (options) => {
|
|
1458
1516
|
const hasGrade = options?.grade !== undefined;
|
|
@@ -1662,24 +1720,26 @@ class ConnectionMonitor {
|
|
|
1662
1720
|
this._detectInitialState();
|
|
1663
1721
|
}
|
|
1664
1722
|
start() {
|
|
1665
|
-
if (this.isMonitoring)
|
|
1723
|
+
if (this.isMonitoring) {
|
|
1666
1724
|
return;
|
|
1725
|
+
}
|
|
1667
1726
|
this.isMonitoring = true;
|
|
1668
|
-
if (this.config.enableOfflineEvents && typeof window !== "undefined") {
|
|
1669
|
-
|
|
1670
|
-
|
|
1727
|
+
if (this.config.enableOfflineEvents && typeof globalThis.window !== "undefined") {
|
|
1728
|
+
globalThis.addEventListener("online", this._handleOnline);
|
|
1729
|
+
globalThis.addEventListener("offline", this._handleOffline);
|
|
1671
1730
|
}
|
|
1672
1731
|
if (this.config.enableHeartbeat) {
|
|
1673
1732
|
this._startHeartbeat();
|
|
1674
1733
|
}
|
|
1675
1734
|
}
|
|
1676
1735
|
stop() {
|
|
1677
|
-
if (!this.isMonitoring)
|
|
1736
|
+
if (!this.isMonitoring) {
|
|
1678
1737
|
return;
|
|
1738
|
+
}
|
|
1679
1739
|
this.isMonitoring = false;
|
|
1680
|
-
if (typeof window !== "undefined") {
|
|
1681
|
-
|
|
1682
|
-
|
|
1740
|
+
if (typeof globalThis.window !== "undefined") {
|
|
1741
|
+
globalThis.removeEventListener("online", this._handleOnline);
|
|
1742
|
+
globalThis.removeEventListener("offline", this._handleOffline);
|
|
1683
1743
|
}
|
|
1684
1744
|
if (this.heartbeatInterval) {
|
|
1685
1745
|
clearInterval(this.heartbeatInterval);
|
|
@@ -1699,8 +1759,9 @@ class ConnectionMonitor {
|
|
|
1699
1759
|
}
|
|
1700
1760
|
reportRequestFailure(error) {
|
|
1701
1761
|
const isNetworkError = error instanceof TypeError || error instanceof Error && error.message.includes("fetch");
|
|
1702
|
-
if (!isNetworkError)
|
|
1762
|
+
if (!isNetworkError) {
|
|
1703
1763
|
return;
|
|
1764
|
+
}
|
|
1704
1765
|
this.consecutiveFailures++;
|
|
1705
1766
|
if (this.consecutiveFailures >= this.config.failureThreshold) {
|
|
1706
1767
|
this._setState("degraded", "Multiple consecutive request failures");
|
|
@@ -1768,8 +1829,9 @@ class ConnectionMonitor {
|
|
|
1768
1829
|
}
|
|
1769
1830
|
}
|
|
1770
1831
|
_setState(newState, reason) {
|
|
1771
|
-
if (this.state === newState)
|
|
1832
|
+
if (this.state === newState) {
|
|
1772
1833
|
return;
|
|
1834
|
+
}
|
|
1773
1835
|
const oldState = this.state;
|
|
1774
1836
|
this.state = newState;
|
|
1775
1837
|
console.debug(`[ConnectionMonitor] ${oldState} → ${newState}: ${reason}`);
|
|
@@ -1785,14 +1847,15 @@ class ConnectionMonitor {
|
|
|
1785
1847
|
// src/core/connection/utils.ts
|
|
1786
1848
|
function createDisplayAlert(authContext) {
|
|
1787
1849
|
return (message, options) => {
|
|
1788
|
-
if (authContext?.isInIframe && typeof window !== "undefined" && window.parent !== window) {
|
|
1850
|
+
if (authContext?.isInIframe && typeof globalThis.window !== "undefined" && globalThis.window.parent !== globalThis.window) {
|
|
1789
1851
|
window.parent.postMessage({
|
|
1790
1852
|
type: "PLAYCADEMY_DISPLAY_ALERT",
|
|
1791
1853
|
message,
|
|
1792
1854
|
options
|
|
1793
1855
|
}, "*");
|
|
1794
1856
|
} else {
|
|
1795
|
-
const
|
|
1857
|
+
const prefixMap = { error: "❌", warning: "⚠️", info: "ℹ️" };
|
|
1858
|
+
const prefix = (options?.type && prefixMap[options.type]) ?? "ℹ️";
|
|
1796
1859
|
console.log(`${prefix} ${message}`);
|
|
1797
1860
|
}
|
|
1798
1861
|
};
|
|
@@ -1863,28 +1926,34 @@ class ConnectionManager {
|
|
|
1863
1926
|
}
|
|
1864
1927
|
}
|
|
1865
1928
|
// src/core/request.ts
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1929
|
+
var RETRY_DELAYS_MS = [500, 1500];
|
|
1930
|
+
function wait(ms) {
|
|
1931
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1932
|
+
}
|
|
1933
|
+
var retryRuntime = { wait };
|
|
1934
|
+
function isRetryableStatus(status) {
|
|
1935
|
+
return status === 429 || status >= 500;
|
|
1936
|
+
}
|
|
1937
|
+
async function fetchWithRetry(url, init2) {
|
|
1938
|
+
for (let attempt = 0;attempt <= RETRY_DELAYS_MS.length; attempt++) {
|
|
1939
|
+
const retryDelayMs = RETRY_DELAYS_MS[attempt];
|
|
1940
|
+
const canRetry = init2.method === "GET" && retryDelayMs !== undefined;
|
|
1941
|
+
try {
|
|
1942
|
+
const response = await fetch(url, init2);
|
|
1943
|
+
if (canRetry && isRetryableStatus(response.status)) {
|
|
1944
|
+
await retryRuntime.wait(retryDelayMs);
|
|
1945
|
+
} else {
|
|
1946
|
+
return response;
|
|
1947
|
+
}
|
|
1948
|
+
} catch (error) {
|
|
1949
|
+
if (canRetry && error instanceof TypeError) {
|
|
1950
|
+
await retryRuntime.wait(retryDelayMs);
|
|
1951
|
+
} else {
|
|
1952
|
+
throw error;
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1887
1955
|
}
|
|
1956
|
+
throw new PlaycademyError("Request failed after exhausting retries");
|
|
1888
1957
|
}
|
|
1889
1958
|
function prepareRequestBody(body, headers) {
|
|
1890
1959
|
if (body instanceof FormData) {
|
|
@@ -1905,6 +1974,33 @@ function prepareRequestBody(body, headers) {
|
|
|
1905
1974
|
}
|
|
1906
1975
|
return;
|
|
1907
1976
|
}
|
|
1977
|
+
function checkDevWarnings(data) {
|
|
1978
|
+
if (!data || typeof data !== "object") {
|
|
1979
|
+
return;
|
|
1980
|
+
}
|
|
1981
|
+
const response = data;
|
|
1982
|
+
const warningType = response.__playcademyDevWarning;
|
|
1983
|
+
if (!warningType) {
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
switch (warningType) {
|
|
1987
|
+
case "timeback-not-configured": {
|
|
1988
|
+
console.warn("%c⚠️ TimeBack Not Configured", "background: #f59e0b; color: white; padding: 6px 12px; border-radius: 4px; font-weight: bold; font-size: 13px");
|
|
1989
|
+
console.log("%cTimeBack is configured in playcademy.config.js but the sandbox does not have TimeBack credentials.", "color: #f59e0b; font-weight: 500");
|
|
1990
|
+
console.log("To test TimeBack locally:");
|
|
1991
|
+
console.log(" Set the following environment variables:");
|
|
1992
|
+
console.log(" • %cTIMEBACK_ONEROSTER_API_URL", "color: #0ea5e9; font-weight: 600; font-family: monospace");
|
|
1993
|
+
console.log(" • %cTIMEBACK_CALIPER_API_URL", "color: #0ea5e9; font-weight: 600; font-family: monospace");
|
|
1994
|
+
console.log(" • %cTIMEBACK_API_CLIENT_ID/SECRET", "color: #0ea5e9; font-weight: 600; font-family: monospace");
|
|
1995
|
+
console.log(" Or deploy your game: %cplaycademy deploy", "color: #10b981; font-weight: 600; font-family: monospace");
|
|
1996
|
+
console.log(" Or wait for %c@superbuilders/timeback-local%c (coming soon)", "color: #8b5cf6; font-weight: 600; font-family: monospace", "color: inherit");
|
|
1997
|
+
break;
|
|
1998
|
+
}
|
|
1999
|
+
default: {
|
|
2000
|
+
console.warn(`[Playcademy Dev Warning] ${warningType}`);
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
1908
2004
|
async function request({
|
|
1909
2005
|
path,
|
|
1910
2006
|
baseUrl,
|
|
@@ -1916,7 +2012,7 @@ async function request({
|
|
|
1916
2012
|
const url = baseUrl.replace(/\/$/, "") + (path.startsWith("/") ? path : `/${path}`);
|
|
1917
2013
|
const headers = { ...extraHeaders };
|
|
1918
2014
|
const payload = prepareRequestBody(body, headers);
|
|
1919
|
-
const res = await
|
|
2015
|
+
const res = await fetchWithRetry(url, {
|
|
1920
2016
|
method,
|
|
1921
2017
|
headers,
|
|
1922
2018
|
body: payload,
|
|
@@ -1932,18 +2028,20 @@ async function request({
|
|
|
1932
2028
|
})) ?? undefined;
|
|
1933
2029
|
throw ApiError.fromResponse(res.status, res.statusText, errorBody);
|
|
1934
2030
|
}
|
|
1935
|
-
if (res.status === 204)
|
|
2031
|
+
if (res.status === 204) {
|
|
1936
2032
|
return;
|
|
2033
|
+
}
|
|
1937
2034
|
const contentType = res.headers.get("content-type") ?? "";
|
|
1938
2035
|
if (contentType.includes("application/json")) {
|
|
1939
2036
|
try {
|
|
1940
2037
|
const parsed = await res.json();
|
|
1941
2038
|
checkDevWarnings(parsed);
|
|
1942
2039
|
return parsed;
|
|
1943
|
-
} catch (
|
|
1944
|
-
if (
|
|
2040
|
+
} catch (error) {
|
|
2041
|
+
if (error instanceof SyntaxError) {
|
|
1945
2042
|
return;
|
|
1946
|
-
|
|
2043
|
+
}
|
|
2044
|
+
throw error;
|
|
1947
2045
|
}
|
|
1948
2046
|
}
|
|
1949
2047
|
const rawText = await res.text().catch(() => "");
|
|
@@ -1951,21 +2049,26 @@ async function request({
|
|
|
1951
2049
|
}
|
|
1952
2050
|
async function fetchManifest(deploymentUrl) {
|
|
1953
2051
|
const manifestUrl = `${deploymentUrl.replace(/\/$/, "")}/playcademy.manifest.json`;
|
|
2052
|
+
let response;
|
|
2053
|
+
try {
|
|
2054
|
+
response = await fetchWithRetry(manifestUrl, { method: "GET" });
|
|
2055
|
+
} catch (error) {
|
|
2056
|
+
log.error(`[Playcademy SDK] Error fetching manifest from ${manifestUrl}:`, {
|
|
2057
|
+
error
|
|
2058
|
+
});
|
|
2059
|
+
throw new ManifestError("Failed to load game manifest", "temporary");
|
|
2060
|
+
}
|
|
2061
|
+
if (!response.ok) {
|
|
2062
|
+
log.error(`[fetchManifest] Failed to fetch manifest from ${manifestUrl}. Status: ${response.status}`);
|
|
2063
|
+
throw new ManifestError(`Failed to fetch manifest: ${response.status} ${response.statusText}`, isRetryableStatus(response.status) ? "temporary" : "permanent");
|
|
2064
|
+
}
|
|
1954
2065
|
try {
|
|
1955
|
-
const response = await fetch(manifestUrl);
|
|
1956
|
-
if (!response.ok) {
|
|
1957
|
-
log.error(`[fetchManifest] Failed to fetch manifest from ${manifestUrl}. Status: ${response.status}`);
|
|
1958
|
-
throw new PlaycademyError(`Failed to fetch manifest: ${response.status} ${response.statusText}`);
|
|
1959
|
-
}
|
|
1960
2066
|
return await response.json();
|
|
1961
2067
|
} catch (error) {
|
|
1962
|
-
|
|
1963
|
-
throw error;
|
|
1964
|
-
}
|
|
1965
|
-
log.error(`[Playcademy SDK] Error fetching or parsing manifest from ${manifestUrl}:`, {
|
|
2068
|
+
log.error(`[Playcademy SDK] Error parsing manifest from ${manifestUrl}:`, {
|
|
1966
2069
|
error
|
|
1967
2070
|
});
|
|
1968
|
-
throw new
|
|
2071
|
+
throw new ManifestError("Failed to parse game manifest", "permanent");
|
|
1969
2072
|
}
|
|
1970
2073
|
}
|
|
1971
2074
|
|
|
@@ -1981,18 +2084,16 @@ class PlaycademyBaseClient {
|
|
|
1981
2084
|
authContext;
|
|
1982
2085
|
initPayload;
|
|
1983
2086
|
connectionManager;
|
|
2087
|
+
launchId;
|
|
1984
2088
|
_sessionManager = {
|
|
1985
|
-
startSession: async (gameId) => {
|
|
1986
|
-
|
|
1987
|
-
},
|
|
1988
|
-
endSession: async (sessionId, gameId) => {
|
|
1989
|
-
return this.request(`/games/${gameId}/sessions/${sessionId}`, "DELETE");
|
|
1990
|
-
}
|
|
2089
|
+
startSession: async (gameId) => this.request(`/games/${gameId}/sessions`, "POST"),
|
|
2090
|
+
endSession: async (sessionId, gameId) => this.request(`/games/${gameId}/sessions/${sessionId}`, "DELETE")
|
|
1991
2091
|
};
|
|
1992
2092
|
constructor(config) {
|
|
1993
2093
|
this.baseUrl = config?.baseUrl?.endsWith("/api") ? config.baseUrl : `${config?.baseUrl}/api`;
|
|
1994
2094
|
this.gameUrl = config?.gameUrl;
|
|
1995
2095
|
this.gameId = config?.gameId;
|
|
2096
|
+
this.launchId = config?.launchId ?? undefined;
|
|
1996
2097
|
this.config = config || {};
|
|
1997
2098
|
this.authStrategy = createAuthStrategy(config?.token ?? null, config?.tokenType);
|
|
1998
2099
|
this._detectAuthContext();
|
|
@@ -2001,16 +2102,16 @@ class PlaycademyBaseClient {
|
|
|
2001
2102
|
}
|
|
2002
2103
|
getBaseUrl() {
|
|
2003
2104
|
const isRelative = this.baseUrl.startsWith("/");
|
|
2004
|
-
const isBrowser2 = typeof window !== "undefined";
|
|
2005
|
-
return isRelative && isBrowser2 ? `${
|
|
2105
|
+
const isBrowser2 = typeof globalThis.window !== "undefined";
|
|
2106
|
+
return isRelative && isBrowser2 ? `${globalThis.location.origin}${this.baseUrl}` : this.baseUrl;
|
|
2006
2107
|
}
|
|
2007
2108
|
getGameBackendUrl() {
|
|
2008
2109
|
if (!this.gameUrl) {
|
|
2009
2110
|
throw new PlaycademyError("Game backend URL not configured. gameUrl must be set to use game backend features.");
|
|
2010
2111
|
}
|
|
2011
2112
|
const isRelative = this.gameUrl.startsWith("/");
|
|
2012
|
-
const isBrowser2 = typeof window !== "undefined";
|
|
2013
|
-
const effectiveGameUrl = isRelative && isBrowser2 ? `${
|
|
2113
|
+
const isBrowser2 = typeof globalThis.window !== "undefined";
|
|
2114
|
+
const effectiveGameUrl = isRelative && isBrowser2 ? `${globalThis.location.origin}${this.gameUrl}` : this.gameUrl;
|
|
2014
2115
|
return `${effectiveGameUrl}/api`;
|
|
2015
2116
|
}
|
|
2016
2117
|
ping() {
|
|
@@ -2020,6 +2121,9 @@ class PlaycademyBaseClient {
|
|
|
2020
2121
|
this.authStrategy = createAuthStrategy(token, tokenType);
|
|
2021
2122
|
this.emit("authChange", { token });
|
|
2022
2123
|
}
|
|
2124
|
+
setLaunchId(launchId) {
|
|
2125
|
+
this.launchId = launchId ?? undefined;
|
|
2126
|
+
}
|
|
2023
2127
|
getTokenType() {
|
|
2024
2128
|
return this.authStrategy.getType();
|
|
2025
2129
|
}
|
|
@@ -2042,8 +2146,9 @@ class PlaycademyBaseClient {
|
|
|
2042
2146
|
return this.connectionManager?.getState() ?? "unknown";
|
|
2043
2147
|
}
|
|
2044
2148
|
async checkConnection() {
|
|
2045
|
-
if (!this.connectionManager)
|
|
2149
|
+
if (!this.connectionManager) {
|
|
2046
2150
|
return "unknown";
|
|
2151
|
+
}
|
|
2047
2152
|
return await this.connectionManager.checkNow();
|
|
2048
2153
|
}
|
|
2049
2154
|
_setAuthContext(context) {
|
|
@@ -2061,7 +2166,8 @@ class PlaycademyBaseClient {
|
|
|
2061
2166
|
async request(path, method, options) {
|
|
2062
2167
|
const effectiveHeaders = {
|
|
2063
2168
|
...options?.headers,
|
|
2064
|
-
...this.authStrategy.getHeaders()
|
|
2169
|
+
...this.authStrategy.getHeaders(),
|
|
2170
|
+
...this.launchId ? { "x-playcademy-launch-id": this.launchId } : {}
|
|
2065
2171
|
};
|
|
2066
2172
|
try {
|
|
2067
2173
|
const result = await request({
|
|
@@ -2110,11 +2216,13 @@ class PlaycademyBaseClient {
|
|
|
2110
2216
|
this.authContext = { isInIframe: isInIframe() };
|
|
2111
2217
|
}
|
|
2112
2218
|
_initializeConnectionMonitor() {
|
|
2113
|
-
if (typeof window === "undefined")
|
|
2219
|
+
if (typeof globalThis.window === "undefined") {
|
|
2114
2220
|
return;
|
|
2221
|
+
}
|
|
2115
2222
|
const isEnabled = this.config.enableConnectionMonitoring ?? true;
|
|
2116
|
-
if (!isEnabled)
|
|
2223
|
+
if (!isEnabled) {
|
|
2117
2224
|
return;
|
|
2225
|
+
}
|
|
2118
2226
|
try {
|
|
2119
2227
|
this.connectionManager = new ConnectionManager({
|
|
2120
2228
|
baseUrl: this.baseUrl,
|
|
@@ -2129,11 +2237,13 @@ class PlaycademyBaseClient {
|
|
|
2129
2237
|
}
|
|
2130
2238
|
}
|
|
2131
2239
|
async _initializeInternalSession() {
|
|
2132
|
-
if (!this.gameId || this.internalClientSessionId)
|
|
2240
|
+
if (!this.gameId || this.internalClientSessionId) {
|
|
2133
2241
|
return;
|
|
2242
|
+
}
|
|
2134
2243
|
const shouldAutoStart = this.config.autoStartSession ?? true;
|
|
2135
|
-
if (!shouldAutoStart)
|
|
2244
|
+
if (!shouldAutoStart) {
|
|
2136
2245
|
return;
|
|
2246
|
+
}
|
|
2137
2247
|
try {
|
|
2138
2248
|
const response = await this._sessionManager.startSession(this.gameId);
|
|
2139
2249
|
this.internalClientSessionId = response.sessionId;
|