@playcademy/sdk 0.0.1-beta.17 → 0.0.1-beta.18

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
@@ -5,5 +5,5 @@
5
5
  * providing access to the main client class and supporting utilities.
6
6
  */
7
7
  export { PlaycademyClient } from './core/client';
8
- export { bus, BusEvents } from './bus';
8
+ export { messaging, MessageEvents } from './messaging';
9
9
  export type * from './types';
package/dist/index.js CHANGED
@@ -103,60 +103,92 @@ function createAuthNamespace(client) {
103
103
  };
104
104
  }
105
105
 
106
- // src/bus.ts
107
- var BusEvents, busListeners, bus;
108
- var init_bus = __esm(() => {
109
- ((BusEvents2) => {
110
- BusEvents2["INIT"] = "PLAYCADEMY_INIT";
111
- BusEvents2["TOKEN_REFRESH"] = "PLAYCADEMY_TOKEN_REFRESH";
112
- BusEvents2["PAUSE"] = "PLAYCADEMY_PAUSE";
113
- BusEvents2["RESUME"] = "PLAYCADEMY_RESUME";
114
- BusEvents2["FORCE_EXIT"] = "PLAYCADEMY_FORCE_EXIT";
115
- BusEvents2["OVERLAY"] = "PLAYCADEMY_OVERLAY";
116
- BusEvents2["READY"] = "PLAYCADEMY_READY";
117
- BusEvents2["EXIT"] = "PLAYCADEMY_EXIT";
118
- BusEvents2["TELEMETRY"] = "PLAYCADEMY_TELEMETRY";
119
- })(BusEvents ||= {});
120
- busListeners = new Map;
121
- bus = {
122
- emit(type, payload) {
123
- const isIframe = typeof window !== "undefined" && window.self !== window.top;
124
- const iframeToParentEvents = [
125
- "PLAYCADEMY_READY" /* READY */,
126
- "PLAYCADEMY_EXIT" /* EXIT */,
127
- "PLAYCADEMY_TELEMETRY" /* TELEMETRY */
128
- ];
129
- if (isIframe && iframeToParentEvents.includes(type)) {
130
- let messageData = { type };
131
- if (payload !== undefined && typeof payload === "object" && payload !== null) {
132
- messageData = { ...messageData, ...payload };
133
- }
134
- window.parent.postMessage(messageData, "*");
135
- } else {
136
- window.dispatchEvent(new CustomEvent(type, { detail: payload }));
137
- }
138
- },
139
- on(type, handler) {
140
- const listener = (event) => handler(event.detail);
141
- if (!busListeners.has(type)) {
142
- busListeners.set(type, new Map);
143
- }
144
- busListeners.get(type).set(handler, listener);
145
- window.addEventListener(type, listener);
146
- },
147
- off(type, handler) {
148
- const typeListeners = busListeners.get(type);
149
- if (!typeListeners || !typeListeners.has(handler)) {
150
- return;
151
- }
152
- const actualListener = typeListeners.get(handler);
153
- window.removeEventListener(type, actualListener);
154
- typeListeners.delete(handler);
155
- if (typeListeners.size === 0) {
156
- busListeners.delete(type);
106
+ // src/messaging.ts
107
+ class PlaycademyMessaging {
108
+ listeners = new Map;
109
+ send(type, payload) {
110
+ const context = this.getMessagingContext(type);
111
+ if (context.shouldUsePostMessage) {
112
+ this.sendViaPostMessage(type, payload, context.target, context.origin);
113
+ } else {
114
+ this.sendViaCustomEvent(type, payload);
115
+ }
116
+ }
117
+ listen(type, handler) {
118
+ const postMessageListener = (event) => {
119
+ const messageEvent = event;
120
+ if (messageEvent.data?.type === type) {
121
+ handler(messageEvent.data.payload || messageEvent.data);
157
122
  }
123
+ };
124
+ const customEventListener = (event) => {
125
+ handler(event.detail);
126
+ };
127
+ if (!this.listeners.has(type)) {
128
+ this.listeners.set(type, new Map);
158
129
  }
159
- };
130
+ const listenerMap = this.listeners.get(type);
131
+ listenerMap.set(handler, {
132
+ postMessage: postMessageListener,
133
+ customEvent: customEventListener
134
+ });
135
+ window.addEventListener("message", postMessageListener);
136
+ window.addEventListener(type, customEventListener);
137
+ }
138
+ unlisten(type, handler) {
139
+ const typeListeners = this.listeners.get(type);
140
+ if (!typeListeners || !typeListeners.has(handler)) {
141
+ return;
142
+ }
143
+ const listeners = typeListeners.get(handler);
144
+ window.removeEventListener("message", listeners.postMessage);
145
+ window.removeEventListener(type, listeners.customEvent);
146
+ typeListeners.delete(handler);
147
+ if (typeListeners.size === 0) {
148
+ this.listeners.delete(type);
149
+ }
150
+ }
151
+ getMessagingContext(eventType) {
152
+ const isIframe = typeof window !== "undefined" && window.self !== window.top;
153
+ const iframeToParentEvents = [
154
+ "PLAYCADEMY_READY" /* READY */,
155
+ "PLAYCADEMY_EXIT" /* EXIT */,
156
+ "PLAYCADEMY_TELEMETRY" /* TELEMETRY */
157
+ ];
158
+ const shouldUsePostMessage = isIframe && iframeToParentEvents.includes(eventType);
159
+ return {
160
+ shouldUsePostMessage,
161
+ target: shouldUsePostMessage ? window.parent : undefined,
162
+ origin: "*"
163
+ };
164
+ }
165
+ sendViaPostMessage(type, payload, target = window.parent, origin = "*") {
166
+ let messageData = { type };
167
+ if (payload !== undefined && typeof payload === "object" && payload !== null) {
168
+ messageData = { ...messageData, ...payload };
169
+ } else if (payload !== undefined) {
170
+ messageData.payload = payload;
171
+ }
172
+ target.postMessage(messageData, origin);
173
+ }
174
+ sendViaCustomEvent(type, payload) {
175
+ window.dispatchEvent(new CustomEvent(type, { detail: payload }));
176
+ }
177
+ }
178
+ var MessageEvents, messaging;
179
+ var init_messaging = __esm(() => {
180
+ ((MessageEvents2) => {
181
+ MessageEvents2["INIT"] = "PLAYCADEMY_INIT";
182
+ MessageEvents2["TOKEN_REFRESH"] = "PLAYCADEMY_TOKEN_REFRESH";
183
+ MessageEvents2["PAUSE"] = "PLAYCADEMY_PAUSE";
184
+ MessageEvents2["RESUME"] = "PLAYCADEMY_RESUME";
185
+ MessageEvents2["FORCE_EXIT"] = "PLAYCADEMY_FORCE_EXIT";
186
+ MessageEvents2["OVERLAY"] = "PLAYCADEMY_OVERLAY";
187
+ MessageEvents2["READY"] = "PLAYCADEMY_READY";
188
+ MessageEvents2["EXIT"] = "PLAYCADEMY_EXIT";
189
+ MessageEvents2["TELEMETRY"] = "PLAYCADEMY_TELEMETRY";
190
+ })(MessageEvents ||= {});
191
+ messaging = new PlaycademyMessaging;
160
192
  });
161
193
 
162
194
  // src/core/namespaces/runtime.ts
@@ -177,12 +209,12 @@ function createRuntimeNamespace(client) {
177
209
  console.error("[SDK] Failed to auto-end session:", client["internalClientSessionId"], error);
178
210
  }
179
211
  }
180
- bus.emit("PLAYCADEMY_EXIT" /* EXIT */, undefined);
212
+ messaging.send("PLAYCADEMY_EXIT" /* EXIT */, undefined);
181
213
  }
182
214
  };
183
215
  }
184
216
  var init_runtime = __esm(() => {
185
- init_bus();
217
+ init_messaging();
186
218
  });
187
219
 
188
220
  // src/core/namespaces/games.ts
@@ -394,15 +426,15 @@ async function init() {
394
426
  token: config.token,
395
427
  gameId: config.gameId
396
428
  });
397
- bus.on("PLAYCADEMY_TOKEN_REFRESH" /* TOKEN_REFRESH */, ({ token }) => client.setToken(token));
398
- bus.emit("PLAYCADEMY_READY" /* READY */, undefined);
429
+ messaging.listen("PLAYCADEMY_TOKEN_REFRESH" /* TOKEN_REFRESH */, ({ token }) => client.setToken(token));
430
+ messaging.send("PLAYCADEMY_READY" /* READY */, undefined);
399
431
  if (import.meta.env?.MODE === "development") {
400
432
  window.PLAYCADEMY_CLIENT = client;
401
433
  }
402
434
  return client;
403
435
  }
404
436
  var init_init = __esm(() => {
405
- init_bus();
437
+ init_messaging();
406
438
  });
407
439
 
408
440
  // src/core/static/login.ts
@@ -542,9 +574,9 @@ var init_client = __esm(() => {
542
574
 
543
575
  // src/index.ts
544
576
  init_client();
545
- init_bus();
577
+ init_messaging();
546
578
  export {
547
- bus,
579
+ messaging,
548
580
  PlaycademyClient,
549
- BusEvents
581
+ MessageEvents
550
582
  };
@@ -0,0 +1,496 @@
1
+ /**
2
+ * @fileoverview Playcademy Messaging System
3
+ *
4
+ * This file implements a unified messaging system for the Playcademy platform that handles
5
+ * communication between different contexts:
6
+ *
7
+ * 1. **Iframe-to-Parent Communication**: When games run inside iframes (production/development),
8
+ * they need to communicate with the parent window using postMessage API
9
+ *
10
+ * 2. **Local Communication**: When games run in the same context (local development),
11
+ * they use CustomEvents for internal messaging
12
+ *
13
+ * The system automatically detects the runtime environment and chooses the appropriate
14
+ * transport method, abstracting this complexity from the developer.
15
+ *
16
+ * **Architecture Overview**:
17
+ * - Games run in iframes for security and isolation
18
+ * - Parent window (Playcademy shell) manages game lifecycle
19
+ * - Messages flow bidirectionally between parent and iframe
20
+ * - Local development mode simulates this architecture without iframes
21
+ */
22
+ import type { GameContextPayload } from './types';
23
+ /**
24
+ * Enumeration of all message types used in the Playcademy messaging system.
25
+ *
26
+ * **Message Flow Patterns**:
27
+ *
28
+ * **Parent → Game (Overworld → Game)**:
29
+ * - INIT: Provides game with authentication token and configuration
30
+ * - TOKEN_REFRESH: Updates game's authentication token before expiry
31
+ * - PAUSE/RESUME: Controls game execution state
32
+ * - FORCE_EXIT: Immediately terminates the game
33
+ * - OVERLAY: Shows/hides UI overlays over the game
34
+ *
35
+ * **Game → Parent (Game → Overworld)**:
36
+ * - READY: Game has loaded and is ready to receive messages
37
+ * - EXIT: Game requests to be closed (user clicked exit, game ended, etc.)
38
+ * - TELEMETRY: Game reports performance metrics (FPS, memory usage, etc.)
39
+ */
40
+ export declare enum MessageEvents {
41
+ /**
42
+ * Initializes the game with authentication context and configuration.
43
+ * Sent immediately after game iframe loads.
44
+ * Payload: { baseUrl: string, token: string, gameId: string }
45
+ */
46
+ INIT = "PLAYCADEMY_INIT",
47
+ /**
48
+ * Updates the game's authentication token before it expires.
49
+ * Sent periodically to maintain valid authentication.
50
+ * Payload: { token: string, exp: number }
51
+ */
52
+ TOKEN_REFRESH = "PLAYCADEMY_TOKEN_REFRESH",
53
+ /**
54
+ * Pauses game execution (e.g., when user switches tabs).
55
+ * Game should pause timers, animations, and user input.
56
+ * Payload: void
57
+ */
58
+ PAUSE = "PLAYCADEMY_PAUSE",
59
+ /**
60
+ * Resumes game execution after being paused.
61
+ * Game should restore timers, animations, and user input.
62
+ * Payload: void
63
+ */
64
+ RESUME = "PLAYCADEMY_RESUME",
65
+ /**
66
+ * Forces immediate game termination (emergency exit).
67
+ * Game should clean up resources and exit immediately.
68
+ * Payload: void
69
+ */
70
+ FORCE_EXIT = "PLAYCADEMY_FORCE_EXIT",
71
+ /**
72
+ * Shows or hides UI overlays over the game.
73
+ * Game may need to pause or adjust rendering accordingly.
74
+ * Payload: boolean (true = show overlay, false = hide overlay)
75
+ */
76
+ OVERLAY = "PLAYCADEMY_OVERLAY",
77
+ /**
78
+ * Game has finished loading and is ready to receive messages.
79
+ * Sent once after game initialization is complete.
80
+ * Payload: void
81
+ */
82
+ READY = "PLAYCADEMY_READY",
83
+ /**
84
+ * Game requests to be closed/exited.
85
+ * Sent when user clicks exit button or game naturally ends.
86
+ * Payload: void
87
+ */
88
+ EXIT = "PLAYCADEMY_EXIT",
89
+ /**
90
+ * Game reports performance telemetry data.
91
+ * Sent periodically for monitoring and analytics.
92
+ * Payload: { fps: number, mem: number }
93
+ */
94
+ TELEMETRY = "PLAYCADEMY_TELEMETRY"
95
+ }
96
+ /**
97
+ * Type definition for message handler functions.
98
+ * These functions are called when a specific message type is received.
99
+ *
100
+ * @template T - The type of payload data the handler expects
101
+ * @param payload - The data sent with the message
102
+ */
103
+ type MessageHandler<T = unknown> = (payload: T) => void;
104
+ /**
105
+ * Type mapping that defines the payload structure for each message type.
106
+ * This ensures type safety when sending and receiving messages.
107
+ *
108
+ * **Usage Examples**:
109
+ * ```typescript
110
+ * // Type-safe message sending
111
+ * messaging.send(MessageEvents.INIT, { baseUrl: '/api', token: 'abc', gameId: '123' })
112
+ *
113
+ * // Type-safe message handling
114
+ * messaging.listen(MessageEvents.TOKEN_REFRESH, ({ token, exp }) => {
115
+ * console.log(`New token expires at: ${new Date(exp)}`)
116
+ * })
117
+ * ```
118
+ */
119
+ export type MessageEventMap = {
120
+ /** Game initialization context with API endpoint, auth token, and game ID */
121
+ [MessageEvents.INIT]: GameContextPayload;
122
+ /** Token refresh data with new token and expiration timestamp */
123
+ [MessageEvents.TOKEN_REFRESH]: {
124
+ token: string;
125
+ exp: number;
126
+ };
127
+ /** Pause message has no payload data */
128
+ [MessageEvents.PAUSE]: void;
129
+ /** Resume message has no payload data */
130
+ [MessageEvents.RESUME]: void;
131
+ /** Force exit message has no payload data */
132
+ [MessageEvents.FORCE_EXIT]: void;
133
+ /** Overlay visibility state (true = show, false = hide) */
134
+ [MessageEvents.OVERLAY]: boolean;
135
+ /** Ready message has no payload data */
136
+ [MessageEvents.READY]: void;
137
+ /** Exit message has no payload data */
138
+ [MessageEvents.EXIT]: void;
139
+ /** Performance telemetry data */
140
+ [MessageEvents.TELEMETRY]: {
141
+ fps: number;
142
+ mem: number;
143
+ };
144
+ };
145
+ /**
146
+ * **PlaycademyMessaging Class**
147
+ *
148
+ * This is the core messaging system that handles all communication in the Playcademy platform.
149
+ * It automatically detects the runtime environment and chooses the appropriate transport method.
150
+ *
151
+ * **Key Features**:
152
+ * 1. **Automatic Transport Selection**: Detects iframe vs local context and uses appropriate method
153
+ * 2. **Type Safety**: Full TypeScript support with payload type checking
154
+ * 3. **Bidirectional Communication**: Handles both parent→game and game→parent messages
155
+ * 4. **Event Cleanup**: Proper listener management to prevent memory leaks
156
+ *
157
+ * **Transport Methods**:
158
+ * - **postMessage**: Used for iframe-to-parent communication (production/development)
159
+ * - **CustomEvent**: Used for local same-context communication (local development)
160
+ *
161
+ * **Runtime Detection Logic**:
162
+ * - If `window.self !== window.top`: We're in an iframe, use postMessage
163
+ * - If `window.self === window.top`: We're in the same context, use CustomEvent
164
+ *
165
+ * **Example Usage**:
166
+ * ```typescript
167
+ * // Send a message (automatically chooses transport)
168
+ * messaging.send(MessageEvents.READY, undefined)
169
+ *
170
+ * // Listen for messages (handles both transports)
171
+ * messaging.listen(MessageEvents.INIT, (payload) => {
172
+ * console.log('Game initialized with:', payload)
173
+ * })
174
+ *
175
+ * // Clean up listeners
176
+ * messaging.unlisten(MessageEvents.INIT, handler)
177
+ * ```
178
+ */
179
+ declare class PlaycademyMessaging {
180
+ /**
181
+ * Internal storage for message listeners.
182
+ *
183
+ * **Structure Explanation**:
184
+ * - Outer Map: MessageEvents → Map of handlers for that event type
185
+ * - Inner Map: MessageHandler → Object containing both listener types
186
+ * - Object: { postMessage: EventListener, customEvent: EventListener }
187
+ *
188
+ * **Why Two Listeners Per Handler?**:
189
+ * Since we don't know at registration time which transport will be used,
190
+ * we register both a postMessage listener and a CustomEvent listener.
191
+ * The appropriate one will be triggered based on the runtime context.
192
+ */
193
+ private listeners;
194
+ /**
195
+ * **Send Message Method**
196
+ *
197
+ * Sends a message using the appropriate transport method based on the runtime context.
198
+ * This is the main public API for sending messages in the Playcademy system.
199
+ *
200
+ * **How It Works**:
201
+ * 1. Analyzes the message type and current runtime context
202
+ * 2. Determines if we're in an iframe and if this message should use postMessage
203
+ * 3. Routes to the appropriate transport method (postMessage or CustomEvent)
204
+ *
205
+ * **Transport Selection Logic**:
206
+ * - **postMessage**: Used when game is in iframe and sending to parent
207
+ * - **CustomEvent**: Used for local/same-context communication
208
+ *
209
+ * **Type Safety**:
210
+ * The generic type parameter `K` ensures that the payload type matches
211
+ * the expected type for the given message event.
212
+ *
213
+ * @template K - The message event type (ensures type safety)
214
+ * @param type - The message event type to send
215
+ * @param payload - The data to send with the message (type-checked)
216
+ *
217
+ * @example
218
+ * ```typescript
219
+ * // Send game ready signal (no payload)
220
+ * messaging.send(MessageEvents.READY, undefined)
221
+ *
222
+ * // Send telemetry data (typed payload)
223
+ * messaging.send(MessageEvents.TELEMETRY, { fps: 60, mem: 128 })
224
+ *
225
+ * // TypeScript will error if payload type is wrong
226
+ * messaging.send(MessageEvents.INIT, "wrong type") // ❌ Error
227
+ * ```
228
+ */
229
+ send<K extends MessageEvents>(type: K, payload: MessageEventMap[K]): void;
230
+ /**
231
+ * **Listen for Messages Method**
232
+ *
233
+ * Registers a message listener that will be called when the specified message type is received.
234
+ * This method automatically handles both postMessage and CustomEvent sources.
235
+ *
236
+ * **Why Register Two Listeners?**:
237
+ * Since we don't know at registration time which transport method will be used to send
238
+ * messages, we register listeners for both possible sources:
239
+ * 1. **postMessage listener**: Handles messages from iframe-to-parent communication
240
+ * 2. **CustomEvent listener**: Handles messages from local same-context communication
241
+ *
242
+ * **Message Processing**:
243
+ * - **postMessage**: Extracts data from `event.data.payload` or `event.data`
244
+ * - **CustomEvent**: Extracts data from `event.detail`
245
+ *
246
+ * **Type Safety**:
247
+ * The handler function receives the correctly typed payload based on the message type.
248
+ *
249
+ * @template K - The message event type (ensures type safety)
250
+ * @param type - The message event type to listen for
251
+ * @param handler - Function to call when the message is received
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * // Listen for game initialization
256
+ * messaging.listen(MessageEvents.INIT, (payload) => {
257
+ * // payload is automatically typed as GameContextPayload
258
+ * console.log(`Game ${payload.gameId} initialized`)
259
+ * console.log(`API base URL: ${payload.baseUrl}`)
260
+ * })
261
+ *
262
+ * // Listen for token refresh
263
+ * messaging.listen(MessageEvents.TOKEN_REFRESH, ({ token, exp }) => {
264
+ * // payload is automatically typed as { token: string; exp: number }
265
+ * updateAuthToken(token)
266
+ * scheduleTokenRefresh(exp)
267
+ * })
268
+ * ```
269
+ */
270
+ listen<K extends MessageEvents>(type: K, handler: MessageHandler<MessageEventMap[K]>): void;
271
+ /**
272
+ * **Remove Message Listener Method**
273
+ *
274
+ * Removes a previously registered message listener to prevent memory leaks and unwanted callbacks.
275
+ * This method cleans up both the postMessage and CustomEvent listeners that were registered.
276
+ *
277
+ * **Why Clean Up Both Listeners?**:
278
+ * When we registered the listener with `listen()`, we created two browser event listeners:
279
+ * 1. A 'message' event listener for postMessage communication
280
+ * 2. A custom event listener for local CustomEvent communication
281
+ *
282
+ * Both must be removed to prevent memory leaks and ensure the handler is completely unregistered.
283
+ *
284
+ * **Memory Management**:
285
+ * - Removes both event listeners from the browser
286
+ * - Cleans up internal tracking maps
287
+ * - If no more handlers exist for a message type, removes the entire type entry
288
+ *
289
+ * **Safe to Call Multiple Times**:
290
+ * This method is idempotent - calling it multiple times with the same handler is safe.
291
+ *
292
+ * @template K - The message event type (ensures type safety)
293
+ * @param type - The message event type to stop listening for
294
+ * @param handler - The exact handler function that was passed to listen()
295
+ *
296
+ * @example
297
+ * ```typescript
298
+ * // Register a handler
299
+ * const handleInit = (payload) => console.log('Game initialized')
300
+ * messaging.listen(MessageEvents.INIT, handleInit)
301
+ *
302
+ * // Later, remove the handler
303
+ * messaging.unlisten(MessageEvents.INIT, handleInit)
304
+ *
305
+ * // Safe to call multiple times
306
+ * messaging.unlisten(MessageEvents.INIT, handleInit) // No error
307
+ * ```
308
+ */
309
+ unlisten<K extends MessageEvents>(type: K, handler: MessageHandler<MessageEventMap[K]>): void;
310
+ /**
311
+ * **Get Messaging Context Method**
312
+ *
313
+ * Analyzes the current runtime environment and message type to determine the appropriate
314
+ * transport method and configuration for sending messages.
315
+ *
316
+ * **Runtime Environment Detection**:
317
+ * The method detects whether the code is running in an iframe by comparing:
318
+ * - `window.self`: Reference to the current window
319
+ * - `window.top`: Reference to the topmost window in the hierarchy
320
+ *
321
+ * If they're different, we're in an iframe. If they're the same, we're in the top-level window.
322
+ *
323
+ * **Message Direction Analysis**:
324
+ * Different message types flow in different directions:
325
+ * - **Game → Parent**: READY, EXIT, TELEMETRY (use postMessage when in iframe)
326
+ * - **Parent → Game**: INIT, TOKEN_REFRESH, PAUSE, etc. (use CustomEvent in local dev)
327
+ *
328
+ * **Transport Selection Logic**:
329
+ * - **postMessage**: Used when game is in iframe AND sending to parent
330
+ * - **CustomEvent**: Used for all other cases (local development, parent-to-game)
331
+ *
332
+ * **Security Considerations**:
333
+ * The origin is currently set to '*' for development convenience, but should be
334
+ * configurable for production security.
335
+ *
336
+ * @param eventType - The message event type being sent
337
+ * @returns Configuration object with transport method and target information
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * // In iframe sending READY to parent
342
+ * const context = getMessagingContext(MessageEvents.READY)
343
+ * // Returns: { shouldUsePostMessage: true, target: window.parent, origin: '*' }
344
+ *
345
+ * // In same context sending INIT
346
+ * const context = getMessagingContext(MessageEvents.INIT)
347
+ * // Returns: { shouldUsePostMessage: false, target: undefined, origin: '*' }
348
+ * ```
349
+ */
350
+ private getMessagingContext;
351
+ /**
352
+ * **Send Via PostMessage Method**
353
+ *
354
+ * Sends a message using the browser's postMessage API for iframe-to-parent communication.
355
+ * This method is used when the game is running in an iframe and needs to communicate
356
+ * with the parent window (the Playcademy shell).
357
+ *
358
+ * **PostMessage Protocol**:
359
+ * The postMessage API is the standard way for iframes to communicate with their parent.
360
+ * It's secure, cross-origin capable, and designed specifically for this use case.
361
+ *
362
+ * **Message Structure**:
363
+ * The method creates a message object with the following structure:
364
+ * - `type`: The message event type (e.g., 'PLAYCADEMY_READY')
365
+ * - Payload data: Either spread into the object or in a `payload` property
366
+ *
367
+ * **Payload Handling**:
368
+ * - **Object payloads**: Spread directly into the message (e.g., { type, token, exp })
369
+ * - **Primitive payloads**: Wrapped in a `payload` property (e.g., { type, payload: true })
370
+ * - **Undefined payloads**: Only the type is sent (e.g., { type })
371
+ *
372
+ * **Security**:
373
+ * The origin parameter controls which domains can receive the message.
374
+ * Currently set to '*' for development, but should be restricted in production.
375
+ *
376
+ * @template K - The message event type (ensures type safety)
377
+ * @param type - The message event type to send
378
+ * @param payload - The data to send with the message
379
+ * @param target - The target window (defaults to parent window)
380
+ * @param origin - The allowed origin for the message (defaults to '*')
381
+ *
382
+ * @example
383
+ * ```typescript
384
+ * // Send ready signal (no payload)
385
+ * sendViaPostMessage(MessageEvents.READY, undefined)
386
+ * // Sends: { type: 'PLAYCADEMY_READY' }
387
+ *
388
+ * // Send telemetry data (object payload)
389
+ * sendViaPostMessage(MessageEvents.TELEMETRY, { fps: 60, mem: 128 })
390
+ * // Sends: { type: 'PLAYCADEMY_TELEMETRY', fps: 60, mem: 128 }
391
+ *
392
+ * // Send overlay state (primitive payload)
393
+ * sendViaPostMessage(MessageEvents.OVERLAY, true)
394
+ * // Sends: { type: 'PLAYCADEMY_OVERLAY', payload: true }
395
+ * ```
396
+ */
397
+ private sendViaPostMessage;
398
+ /**
399
+ * **Send Via CustomEvent Method**
400
+ *
401
+ * Sends a message using the browser's CustomEvent API for local same-context communication.
402
+ * This method is used when both the sender and receiver are in the same window context,
403
+ * typically during local development or when the parent needs to send messages to the game.
404
+ *
405
+ * **CustomEvent Protocol**:
406
+ * CustomEvent is a browser API for creating and dispatching custom events within the same
407
+ * window context. It's simpler than postMessage but only works within the same origin/context.
408
+ *
409
+ * **Event Structure**:
410
+ * - **type**: The event name (e.g., 'PLAYCADEMY_INIT')
411
+ * - **detail**: The payload data attached to the event
412
+ *
413
+ * **When This Is Used**:
414
+ * - Local development when game and shell run in the same context
415
+ * - Parent-to-game communication (INIT, TOKEN_REFRESH, PAUSE, etc.)
416
+ * - Any scenario where postMessage isn't needed
417
+ *
418
+ * **Event Bubbling**:
419
+ * CustomEvents are dispatched on the window object and can be listened to by any
420
+ * code in the same context using `addEventListener(type, handler)`.
421
+ *
422
+ * @template K - The message event type (ensures type safety)
423
+ * @param type - The message event type to send (becomes the event name)
424
+ * @param payload - The data to send with the message (stored in event.detail)
425
+ *
426
+ * @example
427
+ * ```typescript
428
+ * // Send initialization data
429
+ * sendViaCustomEvent(MessageEvents.INIT, {
430
+ * baseUrl: '/api',
431
+ * token: 'abc123',
432
+ * gameId: 'game-456'
433
+ * })
434
+ * // Creates: CustomEvent('PLAYCADEMY_INIT', { detail: { baseUrl, token, gameId } })
435
+ *
436
+ * // Send pause signal
437
+ * sendViaCustomEvent(MessageEvents.PAUSE, undefined)
438
+ * // Creates: CustomEvent('PLAYCADEMY_PAUSE', { detail: undefined })
439
+ *
440
+ * // Listeners can access the data via event.detail:
441
+ * window.addEventListener('PLAYCADEMY_INIT', (event) => {
442
+ * console.log(event.detail.gameId) // 'game-456'
443
+ * })
444
+ * ```
445
+ */
446
+ private sendViaCustomEvent;
447
+ }
448
+ /**
449
+ * **Playcademy Messaging Singleton**
450
+ *
451
+ * This is the main messaging instance used throughout the Playcademy platform.
452
+ * It's exported as a singleton to ensure consistent communication across all parts
453
+ * of the application.
454
+ *
455
+ * **Why a Singleton?**:
456
+ * - Ensures all parts of the app use the same messaging instance
457
+ * - Prevents conflicts between multiple messaging systems
458
+ * - Simplifies the API - no need to pass instances around
459
+ * - Maintains consistent event listener management
460
+ *
461
+ * **Usage in Different Contexts**:
462
+ *
463
+ * **In Games**:
464
+ * ```typescript
465
+ * import { messaging, MessageEvents } from '@playcademy/sdk'
466
+ *
467
+ * // Tell parent we're ready
468
+ * messaging.send(MessageEvents.READY, undefined)
469
+ *
470
+ * // Listen for pause/resume
471
+ * messaging.listen(MessageEvents.PAUSE, () => game.pause())
472
+ * messaging.listen(MessageEvents.RESUME, () => game.resume())
473
+ * ```
474
+ *
475
+ * **In Parent Shell**:
476
+ * ```typescript
477
+ * import { messaging, MessageEvents } from '@playcademy/sdk'
478
+ *
479
+ * // Send initialization data to game
480
+ * messaging.send(MessageEvents.INIT, { baseUrl, token, gameId })
481
+ *
482
+ * // Listen for game events
483
+ * messaging.listen(MessageEvents.EXIT, () => closeGame())
484
+ * messaging.listen(MessageEvents.READY, () => showGame())
485
+ * ```
486
+ *
487
+ * **Automatic Transport Selection**:
488
+ * The messaging system automatically chooses the right transport method:
489
+ * - Uses postMessage when game is in iframe sending to parent
490
+ * - Uses CustomEvent for local development and parent-to-game communication
491
+ *
492
+ * **Type Safety**:
493
+ * All message sending and receiving is fully type-safe with TypeScript.
494
+ */
495
+ export declare const messaging: PlaycademyMessaging;
496
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@playcademy/sdk",
3
3
  "type": "module",
4
- "version": "0.0.1-beta.17",
4
+ "version": "0.0.1-beta.18",
5
5
  "exports": {
6
6
  ".": {
7
7
  "import": "./dist/index.js",
package/dist/bus.d.ts DELETED
@@ -1,37 +0,0 @@
1
- import type { GameContextPayload } from './types';
2
- export declare enum BusEvents {
3
- INIT = "PLAYCADEMY_INIT",
4
- TOKEN_REFRESH = "PLAYCADEMY_TOKEN_REFRESH",
5
- PAUSE = "PLAYCADEMY_PAUSE",
6
- RESUME = "PLAYCADEMY_RESUME",
7
- FORCE_EXIT = "PLAYCADEMY_FORCE_EXIT",
8
- OVERLAY = "PLAYCADEMY_OVERLAY",
9
- READY = "PLAYCADEMY_READY",
10
- EXIT = "PLAYCADEMY_EXIT",
11
- TELEMETRY = "PLAYCADEMY_TELEMETRY"
12
- }
13
- type BusHandler<T = unknown> = (payload: T) => void;
14
- export type BusEventMap = {
15
- [BusEvents.INIT]: GameContextPayload;
16
- [BusEvents.TOKEN_REFRESH]: {
17
- token: string;
18
- exp: number;
19
- };
20
- [BusEvents.PAUSE]: void;
21
- [BusEvents.RESUME]: void;
22
- [BusEvents.FORCE_EXIT]: void;
23
- [BusEvents.OVERLAY]: boolean;
24
- [BusEvents.READY]: void;
25
- [BusEvents.EXIT]: void;
26
- [BusEvents.TELEMETRY]: {
27
- fps: number;
28
- mem: number;
29
- };
30
- };
31
- interface Bus {
32
- emit<K extends BusEvents>(type: K, payload: BusEventMap[K]): void;
33
- on<K extends BusEvents>(type: K, handler: BusHandler<BusEventMap[K]>): void;
34
- off<K extends BusEvents>(type: K, handler: BusHandler<BusEventMap[K]>): void;
35
- }
36
- export declare const bus: Bus;
37
- export {};