@playcademy/sdk 0.16.0 → 0.16.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _playcademy_types from '@playcademy/types';
2
2
  import { LocalDayContext } from '@playcademy/types';
3
- import { TimebackGrade, TimebackSubject, HeartbeatRequest } from '@playcademy/types/timeback';
3
+ import { TimebackGrade, TimebackSubject, ELevel, ChildEndActivityScoreData, EndActivityRequest, HeartbeatRequest, EndActivityScoreData, EndActivityResponse } from '@playcademy/types/timeback';
4
4
  import { TimebackUserRole, UserEnrollment, UserOrganization, UserInfo } from '@playcademy/types/user';
5
5
  import { AUTH_PROVIDER_IDS } from '@playcademy/constants';
6
6
 
@@ -227,6 +227,8 @@ declare abstract class PlaycademyBaseClient {
227
227
  isInIframe: boolean;
228
228
  };
229
229
  protected initPayload?: InitPayload;
230
+ /** Memoized `client.parent` handle; built on first access in child mode. */
231
+ private parentHandle?;
230
232
  protected launchId?: string;
231
233
  protected gameOrigin?: string;
232
234
  private browserTimeZone?;
@@ -247,6 +249,13 @@ declare abstract class PlaycademyBaseClient {
247
249
  * Local day context supplied by the platform during iframe initialization.
248
250
  */
249
251
  get localDay(): LocalDayContext | undefined;
252
+ /**
253
+ * Null outside `mode: 'child'` even if a payload smuggled in a `parent`
254
+ * block, so `if (client.parent)` is a reliable child-mode test. The
255
+ * returned handle is the wire block plus `checkpoint()`, memoized so
256
+ * `client.parent === client.parent`.
257
+ */
258
+ get parent(): ParentGameHandle | null;
250
259
  /**
251
260
  * Sets the authentication token for API requests.
252
261
  */
@@ -520,11 +529,32 @@ declare enum MessageEvents {
520
529
  */
521
530
  DEMO_END = "PLAYCADEMY_DEMO_END",
522
531
  /**
523
- * Game shares its latest TimeBack heartbeat window with the parent shell.
524
- * The shell can relay this payload during top-level page teardown, which is
525
- * more reliable than relying only on cross-origin iframe unload events.
532
+ * Game shares its latest TimeBack heartbeat window with the embedding
533
+ * window. The hub relays this payload during top-level page teardown
534
+ * (more reliable than cross-origin iframe unload events); in child mode
535
+ * this stream is the heartbeat's only delivery path.
526
536
  */
527
537
  TIMEBACK_HEARTBEAT_RELAY = "PLAYCADEMY_TIMEBACK_HEARTBEAT_RELAY",
538
+ /**
539
+ * Game announces its tracker opened a run (startActivity).
540
+ * Today only child-mode games emit this: the parent opens its own
541
+ * Timeback run on receipt, so tracked time starts when the lesson
542
+ * does, not when the iframe boots.
543
+ */
544
+ TIMEBACK_ACTIVITY_START = "PLAYCADEMY_TIMEBACK_ACTIVITY_START",
545
+ /**
546
+ * Game relays its full end-activity report instead of POSTing it to
547
+ * its own backend. Today only child-mode games emit this: the parent
548
+ * reports the result to Timeback under its own identity.
549
+ */
550
+ TIMEBACK_ACTIVITY_END = "PLAYCADEMY_TIMEBACK_ACTIVITY_END",
551
+ /**
552
+ * Child game → parent game. An opaque checkpoint of the child's
553
+ * internal state, streamed during play so the parent always holds a
554
+ * near-current copy (the death-time postMessage hop is unreliable;
555
+ * continuous checkpointing is the design). Latest wins.
556
+ */
557
+ CHECKPOINT = "PLAYCADEMY_CHECKPOINT",
528
558
  /**
529
559
  * Notifies about authentication state changes.
530
560
  * Can be sent in both directions depending on auth flow.
@@ -594,11 +624,36 @@ interface MessageEventMap {
594
624
  [MessageEvents.DEMO_END]: DemoEndPayload;
595
625
  /** Latest TimeBack heartbeat window for parent-shell unload relay */
596
626
  [MessageEvents.TIMEBACK_HEARTBEAT_RELAY]: TimebackHeartbeatRelayRequest;
627
+ /** Child-mode run-opened announcement */
628
+ [MessageEvents.TIMEBACK_ACTIVITY_START]: TimebackActivityStartRelay;
629
+ /** Child-mode end-activity report relay */
630
+ [MessageEvents.TIMEBACK_ACTIVITY_END]: TimebackActivityEndRelay;
631
+ [MessageEvents.CHECKPOINT]: ChildCheckpointRelay;
597
632
  /** Authentication state change notification */
598
633
  [MessageEvents.AUTH_STATE_CHANGE]: AuthStateChangePayload;
599
634
  /** OAuth callback data from popup/new-tab windows */
600
635
  [MessageEvents.AUTH_CALLBACK]: AuthCallbackPayload;
601
636
  }
637
+ /**
638
+ * Options for `messaging.listen()`.
639
+ */
640
+ interface ListenOptions {
641
+ /**
642
+ * Accept postMessages only from the embedding window (`window.parent`).
643
+ *
644
+ * Defaults by direction: on for launcher-directed control messages
645
+ * (see the direction table), off otherwise. A child iframe posts to
646
+ * this window too (that is how the embed relay works), but it must
647
+ * never be able to impersonate the platform above; pass `false` to
648
+ * loosen a launcher-directed listener deliberately (for example a
649
+ * test rig that posts control messages from a non-parent window).
650
+ * Local CustomEvent delivery is unaffected, since a separate
651
+ * document cannot dispatch into this one. At the top window nothing
652
+ * can match (`window.parent === window`), which is correct: a
653
+ * standalone run has no launcher.
654
+ */
655
+ fromParent?: boolean;
656
+ }
602
657
  /**
603
658
  * **PlaycademyMessaging Class**
604
659
  *
@@ -734,7 +789,7 @@ declare class PlaycademyMessaging {
734
789
  * })
735
790
  * ```
736
791
  */
737
- listen<K extends MessageEvents>(type: K, handler: MessageHandler<MessageEventMap[K]>): void;
792
+ listen<K extends MessageEvents>(type: K, handler: MessageHandler<MessageEventMap[K]>, options?: ListenOptions): void;
738
793
  /**
739
794
  * **Remove Message Listener Method**
740
795
  *
@@ -966,146 +1021,14 @@ declare class PlaycademyMessaging {
966
1021
  declare const messaging: PlaycademyMessaging;
967
1022
 
968
1023
  /**
969
- * Playcademy SDK client for game developers.
970
- * Provides namespaced access to platform features for games running inside Cademy.
1024
+ * `endActivity()`'s resolution in child mode: the report was relayed to the
1025
+ * parent game rather than POSTed to the platform, so no platform award data
1026
+ * (courseId, xpAwarded) exists. The parent reports under its own identity.
971
1027
  */
972
- declare class PlaycademyClient extends PlaycademyBaseClient {
973
- /**
974
- * Connect external identity providers to the user's Playcademy account.
975
- * - `connect(provider)` - Link Discord, Google, etc. via OAuth popup
976
- */
977
- identity: {
978
- connect: (options: AuthOptions) => Promise<AuthResult>;
979
- _getContext: () => {
980
- isInIframe: boolean;
981
- };
982
- };
983
- /**
984
- * Game runtime lifecycle and asset loading.
985
- * - `exit()` - Return to Cademy hub
986
- * - `getGameToken()` - Get short-lived auth token
987
- * - `assets.url()`, `assets.json()`, `assets.fetch()` - Load game assets
988
- * - `on('pause')`, `on('resume')` - Handle visibility changes
989
- */
990
- runtime: {
991
- exit: () => void;
992
- onInit: (handler: (context: GameContextPayload) => void) => void;
993
- onTokenRefresh: (handler: (data: {
994
- token: string;
995
- exp: number;
996
- }) => void) => void;
997
- onPause: (handler: () => void) => void;
998
- onResume: (handler: () => void) => void;
999
- onForceExit: (handler: () => void) => void;
1000
- onOverlay: (handler: (isVisible: boolean) => void) => void;
1001
- ready: () => void;
1002
- sendTelemetry: (data: {
1003
- fps: number;
1004
- mem: number;
1005
- }) => void;
1006
- removeListener: (eventType: MessageEvents, handler: ((context: GameContextPayload) => void) | ((data: {
1007
- token: string;
1008
- exp: number;
1009
- }) => void) | (() => void) | ((isVisible: boolean) => void)) => void;
1010
- removeAllListeners: () => void;
1011
- getListenerCounts: () => Record<string, number>;
1012
- assets: {
1013
- url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1014
- fetch: (path: string, options?: RequestInit) => Promise<Response>;
1015
- json: <T = unknown>(path: string) => Promise<T>;
1016
- blob: (path: string) => Promise<Blob>;
1017
- text: (path: string) => Promise<string>;
1018
- arrayBuffer: (path: string) => Promise<ArrayBuffer>;
1019
- };
1020
- };
1021
- /**
1022
- * TimeBack integration for activity tracking and user context.
1023
- *
1024
- * User context (cached from init, refreshable):
1025
- * - `user.role` - User's role (student, parent, teacher, etc.)
1026
- * - `user.enrollments` - Courses the player is enrolled in for this game
1027
- * - `user.refresh({ only: ['enrollments'] })` - Refresh enrollments from server
1028
- * - `user.organizations` - Schools/districts the player belongs to
1029
- * - `user.fetch()` - Refresh user context from server
1030
- *
1031
- * Activity tracking:
1032
- * - `currentRunId` - Current activity run ID, or undefined when inactive
1033
- * - `startActivity(metadata)` - Begin tracking an activity, return its run
1034
- * ID, and automatically handle hidden-tab and visible-tab inactivity
1035
- * with configurable paused-heartbeat timeout behavior
1036
- * - `pauseActivity()` / `resumeActivity()` - Pause/resume timer
1037
- * - `endActivity(scoreData)` - Submit activity results to TimeBack
1038
- */
1039
- timeback: {
1040
- readonly user: TimebackUser;
1041
- readonly currentRunId: string | undefined;
1042
- startActivity: (metadata: _playcademy_types.ActivityData, options?: StartActivityOptions) => StartActivityResult;
1043
- pauseActivity: () => void;
1044
- resumeActivity: () => void;
1045
- endActivity: (data: _playcademy_types.EndActivityScoreData) => Promise<_playcademy_types.EndActivityResponse>;
1046
- course: {
1047
- advance: (options?: {
1048
- subject?: _playcademy_types.TimebackSubject;
1049
- }) => Promise<_playcademy_types.AdvanceCourseResponse>;
1050
- unenroll: (options?: {
1051
- subject?: _playcademy_types.TimebackSubject;
1052
- force?: boolean;
1053
- }) => Promise<_playcademy_types.UnenrollCourseResponse>;
1054
- };
1055
- };
1056
- /**
1057
- * Game score submission and leaderboards.
1058
- * - `submit(score, metadata?)` - Record a game score
1059
- */
1060
- scores: {
1061
- submit: (score: number, metadata?: Record<string, unknown>) => Promise<ScoreSubmission>;
1062
- };
1063
- /**
1064
- * Read-only leaderboard access for the current game scope.
1065
- * - `fetch(options?)` - Fetch leaderboard entries
1066
- */
1067
- leaderboard: {
1068
- fetch: (options?: _playcademy_types.LeaderboardOptions) => Promise<_playcademy_types.GameLeaderboardEntry[]>;
1069
- };
1070
- /**
1071
- * Demo-mode helpers. Methods throw when called outside `client.mode === 'demo'`,
1072
- * so callers should gate on the mode before reaching in.
1073
- * - `profile.get()` - Read the anonymous demo player's profile
1074
- * - `profile.update(updates)` - Update the demo player's profile (today: the required `displayName`)
1075
- * - `end(score, options?)` - Signal to the parent shell that the demo has ended
1076
- */
1077
- demo: {
1078
- profile: {
1079
- get: () => Promise<_playcademy_types.DemoProfile>;
1080
- update: (updates: _playcademy_types.DemoProfileUpdate) => Promise<_playcademy_types.DemoProfile>;
1081
- };
1082
- end: (score: number, options?: DemoEndOptions) => void;
1083
- };
1084
- /**
1085
- * Make requests to your game's custom backend API routes.
1086
- * - `get(path)`, `post(path, body)`, `put()`, `delete()` - HTTP methods
1087
- * - Routes are relative to your game's deployment (e.g., '/hello' → your-game.playcademy.gg/api/hello)
1088
- */
1089
- backend: {
1090
- get<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1091
- post<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1092
- put<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1093
- patch<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1094
- delete<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1095
- request<T = unknown>(path: string, method: Method, body?: unknown, headers?: Record<string, string>): Promise<T>;
1096
- download(path: string, method?: Method, body?: unknown, headers?: Record<string, string>): Promise<Response>;
1097
- url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1098
- };
1099
- /** Auto-initializes a PlaycademyClient with context from the environment */
1100
- static init: typeof init;
1101
- /** Authenticates a user with email and password */
1102
- static login: typeof login;
1103
- /** Static identity utilities for OAuth operations */
1104
- static identity: {
1105
- parseOAuthState: typeof parseOAuthState;
1106
- };
1028
+ interface RelayedEndActivityResult {
1029
+ status: 'relayed';
1030
+ runId: string;
1107
1031
  }
1108
-
1109
1032
  /**
1110
1033
  * Options for configuring activity tracking behavior.
1111
1034
  */
@@ -1443,8 +1366,79 @@ type TokenType = 'session' | 'apiKey' | 'gameJwt';
1443
1366
  * - `'standalone'` — game is running outside any iframe (e.g. `bun run dev`
1444
1367
  * or direct-deploy preview) with a mock token and no real platform
1445
1368
  * context. API calls will not succeed; use this to branch UX locally.
1369
+ * - `'child'` — game is embedded by another game (the parent), which ran
1370
+ * the INIT handshake itself and included a `parent` block in the payload.
1371
+ * The user and token are real (the parent's own). Direct Timeback
1372
+ * reporting is suppressed and relayed to the parent instead; read
1373
+ * `client.parent` for the parent's identity and launch instructions.
1374
+ */
1375
+ type PlaycademyMode = 'platform' | 'demo' | 'standalone' | 'child';
1376
+ /**
1377
+ * What a parent game asks a child game to deliver.
1378
+ *
1379
+ * This contract is platform-defined so any parent can launch any child
1380
+ * without pair-specific vocabularies. `lessonId` addresses the child's own
1381
+ * catalog; the child maps it to internal content. Pair-specific extras
1382
+ * belong in `extensions`, which the platform never interprets (the same
1383
+ * split LTI makes between its resource link and custom claims).
1384
+ *
1385
+ * Parent and child ship independently, so children should still validate
1386
+ * the intent at runtime; SDK compatibility floors manage version skew.
1446
1387
  */
1447
- type PlaycademyMode = 'platform' | 'demo' | 'standalone';
1388
+ interface LaunchIntent {
1389
+ /** The activity to deliver, addressed in the child's own catalog. */
1390
+ lessonId: string;
1391
+ /** Pedagogy stage of the lesson (the platform's E1-E4 taxonomy). */
1392
+ eLevel: ELevel;
1393
+ /** Pair-specific extras. Never interpreted by the platform. */
1394
+ extensions?: Record<string, unknown>;
1395
+ }
1396
+ /**
1397
+ * What `client.parent` actually returns: the parent's wire context plus
1398
+ * the child's one capability toward it. The wire block
1399
+ * (`ParentGameContext`) stays a pure serializable payload; this handle
1400
+ * wraps it. Null outside child mode, so `if (client.parent)` remains the
1401
+ * child-launch test.
1402
+ */
1403
+ type ParentGameHandle = ParentGameContext & {
1404
+ /**
1405
+ * Streams an opaque checkpoint of this game's state to the parent,
1406
+ * so an interrupted launch can resume later (the parent hands it
1407
+ * back as `client.parent.resume`). Call it whenever your state
1408
+ * meaningfully changes — never wait for teardown, the closing-tab
1409
+ * message hop is unreliable. State must be JSON-serializable and
1410
+ * under 64KB; anything else is dropped with a warning. This is not
1411
+ * your save system: the parent holds it for resume only.
1412
+ */
1413
+ checkpoint(state: unknown): void;
1414
+ };
1415
+ /**
1416
+ * The parent game's block in a `mode: 'child'` INIT payload. Present only
1417
+ * when a parent game launched this client (see the parent-child game
1418
+ * embedding proposal, `docs/dev/timeback/`).
1419
+ */
1420
+ interface ParentGameContext {
1421
+ /** The parent game's own platform game ID (NOT this game's ID). */
1422
+ gameId: string;
1423
+ /** What the parent wants this child to deliver. */
1424
+ intent: LaunchIntent;
1425
+ /**
1426
+ * An earlier launch's checkpoint state, when the parent is resuming
1427
+ * an interrupted lesson. Opaque: this game wrote it via
1428
+ * `client.parent.checkpoint()`, and only this game can interpret it.
1429
+ * Validate it like the intent — a blob from an older build of this
1430
+ * game should be ignored, not trusted.
1431
+ */
1432
+ resume?: unknown;
1433
+ /**
1434
+ * The interrupted run id, present when the parent is resuming a
1435
+ * lesson. Consumed by the SDK: the launch's first `startActivity()`
1436
+ * adopts it automatically, which is what continues the platform run.
1437
+ * Games never read this; pass an explicit `runId` to
1438
+ * `startActivity()` to start a deliberate fresh attempt instead.
1439
+ */
1440
+ resumeRunId?: string;
1441
+ }
1448
1442
  interface ClientConfig {
1449
1443
  baseUrl: string;
1450
1444
  gameUrl?: string;
@@ -1473,6 +1467,8 @@ interface InitPayload {
1473
1467
  launchId?: string;
1474
1468
  /** When `true`, the parent shell provides a heartbeat relay via postMessage, so the SDK can skip its own `fetch({ keepalive })` beacon on pagehide. Defaults to `false`. */
1475
1469
  hasHeartbeatRelay?: boolean;
1470
+ /** Parent game context. Present only when `mode` is `'child'`. */
1471
+ parent?: ParentGameContext;
1476
1472
  }
1477
1473
  interface GameContextPayload extends InitPayload {
1478
1474
  forwardKeys?: string[];
@@ -1486,6 +1482,198 @@ interface ClientEvents {
1486
1482
  };
1487
1483
  }
1488
1484
 
1485
+ /**
1486
+ * Playcademy SDK client for game developers.
1487
+ * Provides namespaced access to platform features for games running inside Cademy.
1488
+ */
1489
+ declare class PlaycademyClient extends PlaycademyBaseClient {
1490
+ /**
1491
+ * Connect external identity providers to the user's Playcademy account.
1492
+ * - `connect(provider)` - Link Discord, Google, etc. via OAuth popup
1493
+ */
1494
+ identity: {
1495
+ connect: (options: AuthOptions) => Promise<AuthResult>;
1496
+ _getContext: () => {
1497
+ isInIframe: boolean;
1498
+ };
1499
+ };
1500
+ /**
1501
+ * Game runtime lifecycle and asset loading.
1502
+ * - `exit()` - Return to Cademy hub
1503
+ * - `getGameToken()` - Get short-lived auth token
1504
+ * - `assets.url()`, `assets.json()`, `assets.fetch()` - Load game assets
1505
+ * - `on('pause')`, `on('resume')` - Handle visibility changes
1506
+ */
1507
+ runtime: {
1508
+ exit: () => void;
1509
+ onInit: (handler: (context: GameContextPayload) => void) => void;
1510
+ onTokenRefresh: (handler: (data: {
1511
+ token: string;
1512
+ exp: number;
1513
+ }) => void) => void;
1514
+ onPause: (handler: () => void) => void;
1515
+ onResume: (handler: () => void) => void;
1516
+ onForceExit: (handler: () => void) => void;
1517
+ onOverlay: (handler: (isVisible: boolean) => void) => void;
1518
+ ready: () => void;
1519
+ sendTelemetry: (data: {
1520
+ fps: number;
1521
+ mem: number;
1522
+ }) => void;
1523
+ removeListener: (eventType: MessageEvents, handler: ((context: GameContextPayload) => void) | ((data: {
1524
+ token: string;
1525
+ exp: number;
1526
+ }) => void) | (() => void) | ((isVisible: boolean) => void)) => void;
1527
+ removeAllListeners: () => void;
1528
+ getListenerCounts: () => Record<string, number>;
1529
+ assets: {
1530
+ url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1531
+ fetch: (path: string, options?: RequestInit) => Promise<Response>;
1532
+ json: <T = unknown>(path: string) => Promise<T>;
1533
+ blob: (path: string) => Promise<Blob>;
1534
+ text: (path: string) => Promise<string>;
1535
+ arrayBuffer: (path: string) => Promise<ArrayBuffer>;
1536
+ };
1537
+ };
1538
+ /**
1539
+ * TimeBack integration for activity tracking and user context.
1540
+ *
1541
+ * User context (cached from init, refreshable):
1542
+ * - `user.role` - User's role (student, parent, teacher, etc.)
1543
+ * - `user.enrollments` - Courses the player is enrolled in for this game
1544
+ * - `user.refresh({ only: ['enrollments'] })` - Refresh enrollments from server
1545
+ * - `user.organizations` - Schools/districts the player belongs to
1546
+ * - `user.fetch()` - Refresh user context from server
1547
+ *
1548
+ * Activity tracking:
1549
+ * - `currentRunId` - Current activity run ID, or undefined when inactive
1550
+ * - `startActivity(metadata)` - Begin tracking an activity, return its run
1551
+ * ID, and automatically handle hidden-tab and visible-tab inactivity
1552
+ * with configurable paused-heartbeat timeout behavior
1553
+ * - `pauseActivity()` / `resumeActivity()` - Pause/resume timer
1554
+ * - `endActivity(scoreData)` - Submit activity results to TimeBack
1555
+ */
1556
+ timeback: {
1557
+ assessments: {
1558
+ start: (input: _playcademy_types.StartAssessmentInput) => Promise<_playcademy_types.AssessmentAttemptSnapshot>;
1559
+ latest: (options: _playcademy_types.GetLatestAssessmentOptions) => Promise<_playcademy_types.LatestAssessmentResult | null>;
1560
+ get: (attemptId: string) => Promise<_playcademy_types.AssessmentAttemptSnapshot>;
1561
+ save: (attemptId: string, input: _playcademy_types.SaveAssessmentInput) => Promise<_playcademy_types.AssessmentSaveResult>;
1562
+ submit: (attemptId: string, input: _playcademy_types.SubmitAssessmentInput) => Promise<_playcademy_types.AssessmentSubmitResult>;
1563
+ };
1564
+ readonly user: TimebackUser;
1565
+ readonly currentRunId: string | undefined;
1566
+ startActivity: (metadata: _playcademy_types.ActivityData, options?: StartActivityOptions) => StartActivityResult;
1567
+ pauseActivity: () => void;
1568
+ resumeActivity: () => void;
1569
+ endActivity: (data: _playcademy_types.EndActivityScoreData) => Promise<_playcademy_types.EndActivityResponse | RelayedEndActivityResult>;
1570
+ course: {
1571
+ advance: (options?: {
1572
+ subject?: _playcademy_types.TimebackSubject;
1573
+ }) => Promise<_playcademy_types.AdvanceCourseResponse>;
1574
+ unenroll: (options?: {
1575
+ subject?: _playcademy_types.TimebackSubject;
1576
+ force?: boolean;
1577
+ }) => Promise<_playcademy_types.UnenrollCourseResponse>;
1578
+ };
1579
+ };
1580
+ /**
1581
+ * Game score submission and leaderboards.
1582
+ * - `submit(score, metadata?)` - Record a game score
1583
+ */
1584
+ scores: {
1585
+ submit: (score: number, metadata?: Record<string, unknown>) => Promise<ScoreSubmission>;
1586
+ };
1587
+ /**
1588
+ * Read-only leaderboard access for the current game scope.
1589
+ * - `fetch(options?)` - Fetch leaderboard entries
1590
+ */
1591
+ leaderboard: {
1592
+ fetch: (options?: _playcademy_types.LeaderboardOptions) => Promise<_playcademy_types.GameLeaderboardEntry[]>;
1593
+ };
1594
+ /**
1595
+ * Demo-mode helpers. Methods throw when called outside `client.mode === 'demo'`,
1596
+ * so callers should gate on the mode before reaching in.
1597
+ * - `profile.get()` - Read the anonymous demo player's profile
1598
+ * - `profile.update(updates)` - Update the demo player's profile (today: the required `displayName`)
1599
+ * - `end(score, options?)` - Signal to the parent shell that the demo has ended
1600
+ */
1601
+ demo: {
1602
+ profile: {
1603
+ get: () => Promise<_playcademy_types.DemoProfile>;
1604
+ update: (updates: _playcademy_types.DemoProfileUpdate) => Promise<_playcademy_types.DemoProfile>;
1605
+ };
1606
+ end: (score: number, options?: DemoEndOptions) => void;
1607
+ };
1608
+ /**
1609
+ * Make requests to your game's custom backend API routes.
1610
+ * - `get(path)`, `post(path, body)`, `put()`, `delete()` - HTTP methods
1611
+ * - Routes are relative to your game's deployment (e.g., '/hello' → your-game.playcademy.gg/api/hello)
1612
+ */
1613
+ backend: {
1614
+ get<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1615
+ post<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1616
+ put<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1617
+ patch<T = unknown>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
1618
+ delete<T = unknown>(path: string, headers?: Record<string, string>): Promise<T>;
1619
+ request<T = unknown>(path: string, method: Method, body?: unknown, headers?: Record<string, string>): Promise<T>;
1620
+ download(path: string, method?: Method, body?: unknown, headers?: Record<string, string>): Promise<Response>;
1621
+ url(pathOrStrings: string | TemplateStringsArray, ...values: unknown[]): string;
1622
+ };
1623
+ /**
1624
+ * Launch other Playcademy games as embedded children (platform mode only).
1625
+ * - `launch({ slug, container, intent })` - Mount a child game in a nested
1626
+ * iframe with `mode: 'child'`; returns a session handle with `finished`
1627
+ * and `closed` promises and `close()`
1628
+ */
1629
+ embed: {
1630
+ launch(options: EmbedLaunchOptions): EmbedSession;
1631
+ };
1632
+ /** Auto-initializes a PlaycademyClient with context from the environment */
1633
+ static init: typeof init;
1634
+ /** Authenticates a user with email and password */
1635
+ static login: typeof login;
1636
+ /** Static identity utilities for OAuth operations */
1637
+ static identity: {
1638
+ parseOAuthState: typeof parseOAuthState;
1639
+ };
1640
+ }
1641
+ /**
1642
+ * A game client narrowed to a child launch (`mode: 'child'`).
1643
+ *
1644
+ * Produced by `isChildLaunched()`. Three members sharpen: `mode` becomes
1645
+ * the literal `'child'`, `parent` is non-null, and
1646
+ * `timeback.endActivity()` gains a relaxed call signature where
1647
+ * `xpAwarded` is optional and the result is always the relayed shape.
1648
+ * Built as an intersection so the class's private state stays assignable;
1649
+ * the relaxed signature joins the base one as an overload, which is why
1650
+ * an un-narrowed client still requires `xpAwarded`.
1651
+ */
1652
+ type ChildLaunchedClient = PlaycademyClient & {
1653
+ mode: 'child';
1654
+ parent: ParentGameHandle;
1655
+ timeback: {
1656
+ endActivity(data: ChildEndActivityScoreData): Promise<RelayedEndActivityResult>;
1657
+ };
1658
+ };
1659
+ /**
1660
+ * Narrows a client to `ChildLaunchedClient` when a parent game launched
1661
+ * it. TypeScript cannot condition a signature on a runtime mode, but it
1662
+ * can flow this narrowing: inside the guarded branch, `client.parent` is
1663
+ * non-null and `endActivity()` may omit `xpAwarded` (the parent game
1664
+ * decides the award).
1665
+ *
1666
+ * @example
1667
+ * ```typescript
1668
+ * if (isChildLaunched(client)) {
1669
+ * const { lessonId, eLevel } = client.parent.intent
1670
+ * // ... play the lesson ...
1671
+ * await client.timeback.endActivity({ correctQuestions, totalQuestions })
1672
+ * }
1673
+ * ```
1674
+ */
1675
+ declare function isChildLaunched(client: PlaycademyClient): client is ChildLaunchedClient;
1676
+
1489
1677
  /**
1490
1678
  * Event and message payload types for SDK messaging system
1491
1679
  */
@@ -1576,6 +1764,42 @@ interface DemoEndPayload extends DemoEndOptions {
1576
1764
  }
1577
1765
  type TimebackHeartbeatRelayRequest = Omit<HeartbeatRequest, 'gameId' | 'studentId' | 'windowStartedAtMs' | 'windowSequence'> & {
1578
1766
  windowStartedAtMs: number;
1767
+ /**
1768
+ * Marks a closed heartbeat window from the child's 15s accounting
1769
+ * cadence: the window's totals are final, its key never recurs, and
1770
+ * the parent forwards it exactly once (retries are safe against the
1771
+ * server's first-write-wins window dedupe). Absent on the 1s display
1772
+ * snapshots of the still-open window.
1773
+ */
1774
+ windowClosed?: boolean;
1775
+ };
1776
+ /**
1777
+ * Wire payload for `PLAYCADEMY_CHECKPOINT`. An opaque snapshot of the
1778
+ * child game's internal state; the SDK and the parent never interpret
1779
+ * `state`. The parent stamps the resume envelope's `childRunId` from the
1780
+ * activity-start announcement, so the checkpoint itself carries no ids.
1781
+ */
1782
+ interface ChildCheckpointRelay {
1783
+ state: unknown;
1784
+ }
1785
+ /**
1786
+ * Wire payload for `PLAYCADEMY_TIMEBACK_ACTIVITY_START`. A child-mode game
1787
+ * announces that its tracker opened a run, so the parent can open its own
1788
+ * Timeback run at the moment the lesson actually begins.
1789
+ */
1790
+ type TimebackActivityStartRelay = Pick<TimebackHeartbeatRelayRequest, 'runId' | 'resumeId' | 'activityData'>;
1791
+ /**
1792
+ * Wire payload for `PLAYCADEMY_TIMEBACK_ACTIVITY_END`. The same end-activity
1793
+ * body a platform-mode game would POST to its backend, relayed to the parent
1794
+ * instead. `timingData.durationSeconds` is the full active sitting and
1795
+ * `sessionTimingData` carries the FULL session totals: a relayed window is
1796
+ * never marked persisted (a postMessage hand-off proves nothing about the
1797
+ * parent's POST), so the parent reconciles these totals against the windows
1798
+ * the server confirmed before reporting the completion's remainder.
1799
+ */
1800
+ type TimebackActivityEndRelay = Omit<EndActivityRequest, 'gameId' | 'studentId' | 'xpEarned'> & {
1801
+ /** The child's XP suggestion; the parent decides the actual award. */
1802
+ xpEarned?: number;
1579
1803
  };
1580
1804
 
1581
1805
  /**
@@ -1585,6 +1809,243 @@ interface LoginResponse {
1585
1809
  token: string;
1586
1810
  }
1587
1811
 
1812
+ /**
1813
+ * Public types for the launch protocol's parent side: the embedded
1814
+ * child-game session behind `client.embed.launch()`. Only what `launch()`
1815
+ * callers touch lives here; the implementation and its constructor-side
1816
+ * plumbing contracts live in `core/launch/session.ts`.
1817
+ */
1818
+
1819
+ /**
1820
+ * How a child launch is recorded on this game's Timeback course.
1821
+ * The same metadata you would give `startActivity()` if your own document
1822
+ * were running the lesson: the embed session runs the whole
1823
+ * start-through-end lifecycle for you, stamped with this.
1824
+ */
1825
+ interface EmbedTimebackRecording {
1826
+ /** The activity on this game's own course the launch is recorded as. */
1827
+ activityId: string;
1828
+ /** Display name for dashboards; prettified from `activityId` when omitted. */
1829
+ activityName?: string;
1830
+ /** With `subject`, routes the recording to one of this game's courses. */
1831
+ grade: TimebackGrade;
1832
+ /** With `grade`, routes the recording to one of this game's courses. */
1833
+ subject: TimebackSubject;
1834
+ /** Course id hint, same semantics as `startActivity()`. */
1835
+ courseId?: string;
1836
+ }
1837
+ /**
1838
+ * Everything a parent needs to resume an interrupted launch later. The
1839
+ * parent persists this wherever the interruption demands (memory for
1840
+ * exit-and-return, localStorage for tab close, its backend KV for
1841
+ * cross-device) and hands it back via `embed.launch({ resume })`.
1842
+ */
1843
+ interface EmbedResumeEnvelope {
1844
+ /**
1845
+ * The child's opaque checkpoint state, exactly as it last reported
1846
+ * it. Never introspect it: only the child can interpret its own
1847
+ * state, and it validates the blob on the way back in.
1848
+ */
1849
+ state: unknown;
1850
+ /**
1851
+ * The child's own run id from the interrupted launch, when a run was
1852
+ * active. On resume it crosses to the child, whose SDK re-announces
1853
+ * it automatically at the next launch's first start; the announced match
1854
+ * is what makes reusing `parentRunId` safe.
1855
+ */
1856
+ childRunId?: string;
1857
+ /**
1858
+ * The interrupted platform run, when Timeback reporting was active.
1859
+ * Reused (with a fresh sitting id) only when the child accepts the
1860
+ * resume; otherwise a fresh run is minted.
1861
+ */
1862
+ parentRunId?: string;
1863
+ }
1864
+ /**
1865
+ * Custom persistence for resume envelopes, passed as `launch()`'s
1866
+ * `resume` option. The default (when `resume` is omitted) is a built-in
1867
+ * localStorage store keyed by user, parent game, child game, and the
1868
+ * intent's lesson identity; supply your own store to keep envelopes
1869
+ * elsewhere (for example your backend, for cross-device resume).
1870
+ */
1871
+ interface EmbedResumeStore {
1872
+ /**
1873
+ * Returns the stored envelope for this lesson identity, or
1874
+ * null/undefined when there is nothing to resume. May be async; the
1875
+ * boot waits for it before the child's INIT is sent.
1876
+ */
1877
+ load(): EmbedResumeEnvelope | null | undefined | Promise<EmbedResumeEnvelope | null | undefined>;
1878
+ /**
1879
+ * Persists the latest envelope. Called on every checkpoint the child
1880
+ * relays (envelopes are capped at 64KB) and again when run identity
1881
+ * is minted. Writes should be synchronous or fire-and-forget: the
1882
+ * SDK never blocks on them, and a throw costs that envelope's
1883
+ * persistence, never the launch. Returned promises are used only for
1884
+ * ordering: `save` and `clear` run strictly in call order, so a slow
1885
+ * async save cannot land after the completion's clear.
1886
+ */
1887
+ save(envelope: EmbedResumeEnvelope): void;
1888
+ /** Deletes the stored envelope. Called once when the launch completes. */
1889
+ clear(): void;
1890
+ }
1891
+ /**
1892
+ * Play-time totals for a child launch, measured by the child's own
1893
+ * tracker (the parent's document is idle while the student plays).
1894
+ */
1895
+ interface EmbedSessionTiming {
1896
+ /** Seconds of active play. */
1897
+ activeSeconds: number;
1898
+ /** Seconds the child's tracker classified as paused or inactive, when known. */
1899
+ inactiveSeconds?: number;
1900
+ }
1901
+ /**
1902
+ * The launch's activity record, resolved by `session.finished`.
1903
+ *
1904
+ * `'completed'` carries the child's report and the `end()` capability;
1905
+ * `'abandoned'` means the session ended first (child exit or `close()`);
1906
+ * `'failed'` means the launch never happened. Failure is a state to
1907
+ * render, not an exception to catch — `finished` never rejects.
1908
+ */
1909
+ type EmbedActivity = EmbedActivityCompleted | EmbedActivityAbandoned | EmbedActivityFailed;
1910
+ /** The child called `endActivity()` and its report was relayed. */
1911
+ interface EmbedActivityCompleted {
1912
+ status: 'completed';
1913
+ /** Correct answers, from the child's report. */
1914
+ correct: number;
1915
+ /** Total questions, from the child's report. */
1916
+ total: number;
1917
+ timing: EmbedSessionTiming;
1918
+ /**
1919
+ * The child's full relayed end-activity body: its own activity ids,
1920
+ * suggested XP, and extensions. Audit data — the parent decides what
1921
+ * actually reaches the platform, via `end()`.
1922
+ */
1923
+ childReport: TimebackActivityEndRelay;
1924
+ /**
1925
+ * Posts the launch's completion to the parent's own backend: the
1926
+ * parent-minted run id, the `timeback` recording, the caller's score
1927
+ * and XP decision, and the child's ids as audit extensions. Requires
1928
+ * the `timeback` option at launch. Calling twice returns the same
1929
+ * promise, so a launch can never double-report from the client.
1930
+ */
1931
+ end(scores: EndActivityScoreData): Promise<EndActivityResponse>;
1932
+ }
1933
+ /**
1934
+ * The session ended (child exit or `close()`) before a report arrived.
1935
+ * Played time has already reached the platform through forwarded
1936
+ * heartbeats; an abandoned launch leaves no completion, exactly like a
1937
+ * student wandering away from any other game.
1938
+ */
1939
+ interface EmbedActivityAbandoned {
1940
+ status: 'abandoned';
1941
+ timing: EmbedSessionTiming;
1942
+ /**
1943
+ * The final resume envelope, when the child checkpointed during the
1944
+ * launch. Persist it (see `EmbedResumeEnvelope`) and pass it back to
1945
+ * `embed.launch({ resume })` to pick the lesson up later. Absent
1946
+ * when the child never checkpointed.
1947
+ */
1948
+ resume?: EmbedResumeEnvelope;
1949
+ }
1950
+ /** The launch never happened: the child could not be resolved or booted. */
1951
+ interface EmbedActivityFailed {
1952
+ status: 'failed';
1953
+ /** Why — unknown slug, missing deployment URL, INIT error or timeout. */
1954
+ error: PlaycademyError;
1955
+ }
1956
+ /**
1957
+ * Handle for one embedded child-game session.
1958
+ */
1959
+ interface EmbedSession {
1960
+ /** The mounted child iframe. Useful for focus management. */
1961
+ readonly iframe: HTMLIFrameElement;
1962
+ /**
1963
+ * The latest resume envelope, live during play; null until the child
1964
+ * first checkpoints. Read it on your own cadence to persist
1965
+ * mid-lesson (for example a debounced upload to your backend), so a
1966
+ * closed tab can resume on another device.
1967
+ */
1968
+ readonly checkpoint: EmbedResumeEnvelope | null;
1969
+ /**
1970
+ * Resolves the launch's activity record when it ends — the
1971
+ * `animation.finished` idiom. Never rejects: operational failures
1972
+ * resolve as `{ status: 'failed', error }`.
1973
+ */
1974
+ readonly finished: Promise<EmbedActivity>;
1975
+ /**
1976
+ * Resolves when the session is torn down and the iframe is unmounted:
1977
+ * on child exit, `close()`, boot failure, or when the SDK detects the
1978
+ * iframe was removed from the DOM. `finished` can resolve earlier than
1979
+ * this (a completed child usually shows a results screen before
1980
+ * exiting), so use `closed` to dismiss surrounding UI.
1981
+ */
1982
+ readonly closed: Promise<void>;
1983
+ /**
1984
+ * Tears the session down: unmounts the iframe and stops all listeners.
1985
+ * Resolves a still-pending `finished` as `'abandoned'`. Safe to call
1986
+ * more than once. Calling it is the deterministic path; the SDK also
1987
+ * tears down when the child exits, and detects an iframe removed
1988
+ * without `close()` within ~5 seconds, so nothing leaks either way.
1989
+ */
1990
+ close(): void;
1991
+ }
1992
+
1993
+ /**
1994
+ * Options for `client.embed.launch()`.
1995
+ */
1996
+ interface EmbedLaunchOptions {
1997
+ /** Slug of the child game to launch. Resolved to a game id at launch time. */
1998
+ slug: string;
1999
+ /** Element the child iframe is mounted into. The iframe fills it. */
2000
+ container: HTMLElement;
2001
+ /**
2002
+ * What the child should deliver. This is the platform-defined
2003
+ * {@link LaunchIntent} contract; it crosses the iframe in the INIT
2004
+ * payload's `parent` block and surfaces in the child as `client.parent.intent`.
2005
+ */
2006
+ intent: LaunchIntent;
2007
+ /**
2008
+ * Whether and how an interrupted launch can resume.
2009
+ *
2010
+ * Omitted (the default): the SDK persists the child's latest
2011
+ * checkpoint in localStorage, keyed by user, this game, the child,
2012
+ * and the intent's lesson identity. The next launch with the same
2013
+ * identity resumes automatically; completion clears the entry. Inert
2014
+ * for children that never call `client.parent.checkpoint()`.
2015
+ *
2016
+ * `false`: no persistence and no automatic resume. The manual surface
2017
+ * (`session.checkpoint`, the abandoned outcome's `resume`) still works.
2018
+ *
2019
+ * An {@link EmbedResumeEnvelope}: fully manual, one-shot. The launch
2020
+ * resumes from exactly this envelope and nothing is persisted.
2021
+ *
2022
+ * An {@link EmbedResumeStore}: delegate persistence (for example to
2023
+ * your backend, for cross-device resume).
2024
+ *
2025
+ * Whatever the policy, the child receives only the opaque `state`
2026
+ * (as `client.parent.resume`) and decides whether to use it; run ids
2027
+ * stay parent-side and drive run continuity when the child accepts.
2028
+ */
2029
+ resume?: false | EmbedResumeEnvelope | EmbedResumeStore;
2030
+ /**
2031
+ * Records the launch on this game's Timeback course: the metadata
2032
+ * you would have given `startActivity()` if your own document were
2033
+ * running the lesson. Stays in the parent SDK, stamping every
2034
+ * forwarded heartbeat and the final completion; it never crosses the
2035
+ * iframe. Omit for a pure UX embed.
2036
+ */
2037
+ timeback?: EmbedTimebackRecording;
2038
+ /**
2039
+ * Overrides the child's resolved deployment URL. Intended for local
2040
+ * development, where the child runs on a dev server the platform
2041
+ * doesn't know about. With `gameUrl` set, a slug that fails to
2042
+ * resolve degrades to a warning (the slug stands in as the child's
2043
+ * game id) instead of failing the launch, so an unregistered child
2044
+ * still launches locally.
2045
+ */
2046
+ gameUrl?: string;
2047
+ }
2048
+
1588
2049
  /**
1589
2050
  * Scores namespace types
1590
2051
  */
@@ -1665,5 +2126,5 @@ interface DevUploadHooks {
1665
2126
  onClose?: () => void;
1666
2127
  }
1667
2128
 
1668
- export { ApiError, MessageEvents, PlaycademyClient, PlaycademyError, extractApiErrorInfo, messaging };
1669
- export type { ApiErrorCode, ApiErrorInfo, DevUploadEvent, DevUploadHooks, ErrorResponseBody, PlaycademyMode };
2129
+ export { ApiError, MessageEvents, PlaycademyClient, PlaycademyError, extractApiErrorInfo, isChildLaunched, messaging };
2130
+ export type { ApiErrorCode, ApiErrorInfo, ChildLaunchedClient, DevUploadEvent, DevUploadHooks, ErrorResponseBody, PlaycademyMode };