@air-jam/sdk 0.1.0 → 0.1.2

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.
Files changed (37) hide show
  1. package/dist/{chunk-XSXI3RIS.js → chunk-B5DURUWT.js} +11 -3
  2. package/dist/chunk-B5DURUWT.js.map +1 -0
  3. package/dist/index.cjs +2346 -1931
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +97 -41
  6. package/dist/index.d.ts +97 -41
  7. package/dist/index.js +2401 -2001
  8. package/dist/index.js.map +1 -1
  9. package/dist/protocol.cjs +10 -0
  10. package/dist/protocol.cjs.map +1 -1
  11. package/dist/protocol.d.cts +42 -1
  12. package/dist/protocol.d.ts +42 -1
  13. package/dist/protocol.js +1 -1
  14. package/package.json +5 -1
  15. package/src/AirJamClient.ts +1 -552
  16. package/src/audio/audio-manager.ts +12 -1
  17. package/src/audio/volume-store.ts +47 -0
  18. package/src/components/air-jam-debug.tsx +77 -0
  19. package/src/components/air-jam-overlay.tsx +243 -186
  20. package/src/components/controller-shell.tsx +174 -182
  21. package/src/components/debug-state-dialog.tsx +83 -0
  22. package/src/components/player-avatar.tsx +64 -0
  23. package/src/components/qr-scanner-dialog.tsx +2 -2
  24. package/src/components/ui/button.tsx +1 -1
  25. package/src/components/ui/dialog.tsx +122 -0
  26. package/src/constants.ts +3 -2
  27. package/src/context/air-jam-context.tsx +3 -14
  28. package/src/hooks/use-air-jam-controller.ts +1 -1
  29. package/src/hooks/use-air-jam-host.ts +94 -49
  30. package/src/hooks/use-air-jam-shell.ts +36 -0
  31. package/src/index.ts +6 -0
  32. package/src/internal/input-manager.ts +28 -14
  33. package/src/protocol.ts +55 -0
  34. package/src/store/create-air-jam-store.ts +274 -0
  35. package/src/store/index.ts +1 -0
  36. package/src/utils/url-builder.ts +3 -3
  37. package/dist/chunk-XSXI3RIS.js.map +0 -1
package/src/protocol.ts CHANGED
@@ -227,6 +227,26 @@ export const hostJoinAsChildSchema = z.object({
227
227
 
228
228
  export type HostJoinAsChildPayload = z.infer<typeof hostJoinAsChildSchema>;
229
229
 
230
+ /**
231
+ * Schema for creating a new room (server-issued room ID)
232
+ */
233
+ export const hostCreateRoomSchema = z.object({
234
+ maxPlayers: z.number().int().min(1).max(16).default(8),
235
+ apiKey: z.string().optional(),
236
+ });
237
+
238
+ export type HostCreateRoomPayload = z.infer<typeof hostCreateRoomSchema>;
239
+
240
+ /**
241
+ * Schema for reconnecting to an existing room
242
+ */
243
+ export const hostReconnectSchema = z.object({
244
+ roomId: roomCodeSchema,
245
+ apiKey: z.string().optional(),
246
+ });
247
+
248
+ export type HostReconnectPayload = z.infer<typeof hostReconnectSchema>;
249
+
230
250
  export interface SystemLaunchGameAck {
231
251
  ok: boolean;
232
252
  joinToken?: string;
@@ -238,6 +258,29 @@ export interface ClientLoadUiPayload {
238
258
  url: string;
239
259
  }
240
260
 
261
+ export interface HostStateSyncPayload {
262
+ roomId: string;
263
+ data: Record<string, unknown>;
264
+ }
265
+
266
+ export interface ControllerActionRpcPayload {
267
+ roomId: string;
268
+ actionName: string;
269
+ args: unknown[];
270
+ controllerId: string;
271
+ }
272
+
273
+ export interface AirJamStateSyncPayload {
274
+ roomId: string;
275
+ data: Record<string, unknown>;
276
+ }
277
+
278
+ export interface AirJamActionRpcPayload {
279
+ actionName: string;
280
+ args: unknown[];
281
+ controllerId: string;
282
+ }
283
+
241
284
  export interface ClientToServerEvents {
242
285
  "host:register": (
243
286
  payload: z.infer<typeof hostRegistrationSchema>,
@@ -247,6 +290,14 @@ export interface ClientToServerEvents {
247
290
  payload: HostRegisterSystemPayload,
248
291
  callback: (ack: HostRegistrationAck) => void,
249
292
  ) => void;
293
+ "host:createRoom": (
294
+ payload: HostCreateRoomPayload,
295
+ callback: (ack: HostRegistrationAck) => void,
296
+ ) => void;
297
+ "host:reconnect": (
298
+ payload: HostReconnectPayload,
299
+ callback: (ack: HostRegistrationAck) => void,
300
+ ) => void;
250
301
  "system:launchGame": (
251
302
  payload: SystemLaunchGamePayload,
252
303
  callback: (ack: SystemLaunchGameAck) => void,
@@ -270,6 +321,8 @@ export interface ClientToServerEvents {
270
321
  "host:signal": (payload: SignalPayload) => void;
271
322
  "host:play_sound": (payload: PlaySoundEventPayload) => void;
272
323
  "controller:play_sound": (payload: PlaySoundEventPayload) => void;
324
+ "host:state_sync": (payload: HostStateSyncPayload) => void;
325
+ "controller:action_rpc": (payload: ControllerActionRpcPayload) => void;
273
326
  }
274
327
 
275
328
  export interface PlaySoundPayload {
@@ -293,6 +346,8 @@ export interface ServerToClientEvents {
293
346
  "server:closeChild": () => void;
294
347
  "client:loadUi": (payload: ClientLoadUiPayload) => void;
295
348
  "client:unloadUi": () => void;
349
+ "airjam:state_sync": (payload: AirJamStateSyncPayload) => void;
350
+ "airjam:action_rpc": (payload: AirJamActionRpcPayload) => void;
296
351
  }
297
352
 
298
353
  export interface InterServerEvents {
@@ -0,0 +1,274 @@
1
+ import { useEffect, useRef } from "react";
2
+ import { create, type StateCreator } from "zustand";
3
+ import { useAirJamContext, useAirJamState } from "../context/air-jam-context";
4
+ import type {
5
+ AirJamActionRpcPayload,
6
+ AirJamStateSyncPayload,
7
+ } from "../protocol";
8
+
9
+ /**
10
+ * Creates a networked Zustand store that automatically syncs state between host and controllers.
11
+ *
12
+ * The store pattern works as follows:
13
+ * - Host: Stores state locally and broadcasts changes to all controllers
14
+ * - Controller: Sends action RPCs to host, receives state updates from host
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * interface GameState {
19
+ * phase: "lobby" | "playing" | "gameover";
20
+ * scores: { team1: number; team2: number };
21
+ * actions: {
22
+ * setPhase: (phase: "lobby" | "playing") => void;
23
+ * scorePoint: (team: "team1" | "team2") => void;
24
+ * };
25
+ * }
26
+ *
27
+ * export const useGameStore = createAirJamStore<GameState>((set) => ({
28
+ * phase: "lobby",
29
+ * scores: { team1: 0, team2: 0 },
30
+ * actions: {
31
+ * setPhase: (phase) => set({ phase }),
32
+ * scorePoint: (team) => set((state) => ({
33
+ * scores: { ...state.scores, [team]: state.scores[team] + 1 }
34
+ * })),
35
+ * },
36
+ * }));
37
+ * ```
38
+ */
39
+ export function createAirJamStore<
40
+ T extends {
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ actions: Record<string, (...args: any[]) => any>;
43
+ },
44
+ >(initializer: StateCreator<T>) {
45
+ // 1. Create the Vanilla Zustand Store with an internal sync action
46
+ const store = create<T>((set, get, api) => {
47
+ const baseState = initializer(set, get, api);
48
+ // Add internal _syncState action for external updates
49
+ return {
50
+ ...baseState,
51
+ actions: {
52
+ ...baseState.actions,
53
+ _syncState: (partial: Partial<T>) => {
54
+ set(partial as T);
55
+ },
56
+ },
57
+ } as T;
58
+ });
59
+
60
+ // 2. The Hook Component
61
+ // Track if game UI is unloaded to disable proxy actions
62
+ const gameUiUnloadedRef = { current: false };
63
+
64
+ const useSyncedStore = <U>(
65
+ selector: (state: T) => U = (s) => s as unknown as U,
66
+ ): U => {
67
+ // Standard Zustand selector behavior
68
+ const slice = store(selector);
69
+
70
+ const { getSocket } = useAirJamContext();
71
+ const role = useAirJamState((state) => state.role);
72
+ const roomId = useAirJamState((state) => state.roomId);
73
+ const controllerId = useAirJamState((state) => state.controllerId);
74
+ const socket =
75
+ role === "host" ? getSocket("host") : getSocket("controller");
76
+
77
+ // Keep a ref to the socket so we can access the LATEST one inside closures
78
+ const socketRef = useRef(socket);
79
+ useEffect(() => {
80
+ socketRef.current = socket;
81
+ }, [socket]);
82
+
83
+ // --- NETWORKING LOGIC ---
84
+ useEffect(() => {
85
+ if (!socket || !roomId || !role) {
86
+ return;
87
+ }
88
+
89
+ // HOST: Broadcast changes to everyone
90
+ if (role === "host") {
91
+ // Subscribe to store changes
92
+ const unsubscribe = store.subscribe((newState) => {
93
+ // Optimization: Don't broadcast 'actions' function
94
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
95
+ const { actions, ...stateData } = newState;
96
+ socket.emit("host:state_sync", { roomId, data: stateData });
97
+ });
98
+
99
+ // Listen for Action Requests (RPCs) from controllers
100
+ const handleAction = (payload: AirJamActionRpcPayload) => {
101
+ const { actionName, args, controllerId } = payload;
102
+ // Execute the action on the Host (Source of Truth)
103
+ // We can optionally pass controllerId as the last arg if the action expects it
104
+ const actionFn = store.getState().actions[actionName];
105
+ if (actionFn) {
106
+ // Spread args and optionally append controllerId
107
+ actionFn(...args, controllerId);
108
+ }
109
+ };
110
+
111
+ socket.on("airjam:action_rpc", handleAction);
112
+
113
+ return () => {
114
+ unsubscribe();
115
+ socket.off("airjam:action_rpc", handleAction);
116
+ };
117
+ }
118
+
119
+ // CONTROLLER: Listen for state updates
120
+ if (role === "controller") {
121
+ // Reset unloaded flag when we have a new room/socket (game is loading)
122
+ gameUiUnloadedRef.current = false;
123
+
124
+ const handleSync = (payload: AirJamStateSyncPayload) => {
125
+ const { data } = payload;
126
+ // Merge incoming state, but KEEP the local actions
127
+ // Use the internal _syncState action to update state (triggers Zustand subscriptions)
128
+ const currentState = store.getState();
129
+ const actions = currentState.actions as T["actions"] & {
130
+ _syncState?: (partial: Partial<T>) => void;
131
+ };
132
+
133
+ // Update store using internal action - this triggers Zustand subscriptions properly
134
+ if (actions._syncState) {
135
+ actions._syncState(data as Partial<T>);
136
+ } else {
137
+ // Fallback to setState if _syncState not available
138
+ store.setState(data as Partial<T>);
139
+ }
140
+ };
141
+
142
+ socket.on("airjam:state_sync", handleSync);
143
+
144
+ // Also listen for client:unloadUi to clean up when game exits
145
+ // This ensures listeners are removed even if the component doesn't unmount
146
+ const handleUnloadUi = () => {
147
+ gameUiUnloadedRef.current = true; // Disable proxy actions
148
+ socket.off("airjam:state_sync", handleSync);
149
+ };
150
+
151
+ // Also listen for client:loadUi to re-enable proxy actions when new game loads
152
+ const handleLoadUi = () => {
153
+ gameUiUnloadedRef.current = false; // Re-enable proxy actions when game loads
154
+ };
155
+ socket.on("client:loadUi", handleLoadUi);
156
+
157
+ // Also listen for socket disconnect as a fallback to disable proxy actions
158
+ const handleDisconnect = () => {
159
+ gameUiUnloadedRef.current = true; // Disable proxy actions on disconnect
160
+ };
161
+ socket.on("disconnect", handleDisconnect);
162
+
163
+ // Register client:unloadUi listener
164
+ // Socket.IO listeners work even if registered before connection, but we include socket.id
165
+ // in dependencies to ensure the effect re-runs when socket connects (socket.id changes from undefined to a string)
166
+ socket.on("client:unloadUi", handleUnloadUi);
167
+
168
+ return () => {
169
+ socket.off("airjam:state_sync", handleSync);
170
+ socket.off("client:loadUi", handleLoadUi);
171
+ socket.off("client:unloadUi", handleUnloadUi);
172
+ socket.off("disconnect", handleDisconnect);
173
+ };
174
+ }
175
+ }, [socket, role, roomId, socket?.id]);
176
+
177
+ // --- PROXY ACTIONS (The Magic) ---
178
+ // On the Controller, we replace actions with Network Calls
179
+ if (role === "controller" && socket && roomId) {
180
+ // We need to return a modified slice where the actions are proxied
181
+ // This handles two cases:
182
+ // 1. Selector returns full state: { actions: {...}, ... }
183
+ // 2. Selector returns just actions: { joinTeam: fn, ... }
184
+
185
+ let originalActions: T["actions"] | null = null;
186
+
187
+ // Case 1: Slice has "actions" property (full state)
188
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
189
+ originalActions = (slice as { actions: T["actions"] }).actions;
190
+ }
191
+ // Case 2: Slice IS the actions object (selector returned state.actions)
192
+ else if (typeof slice === "object" && slice !== null) {
193
+ // Check if this looks like an actions object (has function properties matching store actions)
194
+ const fullState = store.getState();
195
+ if (fullState.actions) {
196
+ const sliceKeys = Object.keys(slice);
197
+ const actionKeys = Object.keys(fullState.actions);
198
+ // If slice keys match action keys and are all functions, it's the actions object
199
+ if (
200
+ sliceKeys.length > 0 &&
201
+ sliceKeys.every(
202
+ (key) =>
203
+ typeof (slice as Record<string, unknown>)[key] === "function" &&
204
+ actionKeys.includes(key),
205
+ )
206
+ ) {
207
+ originalActions = slice as T["actions"];
208
+ }
209
+ }
210
+ }
211
+
212
+ if (originalActions) {
213
+ // Use the same type as T["actions"] for proxy actions
214
+ const proxyActions = {} as T["actions"];
215
+
216
+ Object.keys(originalActions).forEach((key) => {
217
+ // Type assertion needed because we're creating proxies dynamically
218
+ // We cast to the same type as T["actions"] to maintain type compatibility
219
+ (proxyActions as Record<string, (...args: unknown[]) => void>)[key] =
220
+ (...args: unknown[]) => {
221
+ // --- EXECUTION TIME GUARDS (THE FIX) ---
222
+ // Check guards at EXECUTION time, not creation time
223
+ // This ensures old closures are still safe even if they're called after game exit
224
+
225
+ // 1. Check if UI is unloaded right now (at execution time)
226
+ if (gameUiUnloadedRef.current) {
227
+ console.warn(
228
+ `[AirJamStore] Action "${key}" blocked: Game UI unloaded.`,
229
+ );
230
+ return;
231
+ }
232
+
233
+ // 2. Check if we have a valid socket right now (at execution time)
234
+ const activeSocket = socketRef.current;
235
+ if (!activeSocket || !activeSocket.connected) {
236
+ console.warn(
237
+ `[AirJamStore] Action "${key}" blocked: Socket disconnected.`,
238
+ );
239
+ return;
240
+ }
241
+
242
+ // 3. Check controllerId
243
+ if (!controllerId) {
244
+ console.warn(
245
+ "[AirJamStore] Cannot send action RPC: controllerId not set",
246
+ );
247
+ return;
248
+ }
249
+
250
+ // 4. Send RPC to Host (include controllerId to handle reconnections)
251
+ activeSocket.emit("controller:action_rpc", {
252
+ roomId,
253
+ actionName: key,
254
+ args,
255
+ controllerId,
256
+ });
257
+ };
258
+ });
259
+
260
+ // Return proxied actions - if slice was the actions object, return proxyActions directly
261
+ // Otherwise, return slice with actions replaced
262
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
263
+ return { ...slice, actions: proxyActions } as U;
264
+ } else {
265
+ return proxyActions as U;
266
+ }
267
+ }
268
+ }
269
+
270
+ return slice;
271
+ };
272
+
273
+ return useSyncedStore;
274
+ }
@@ -0,0 +1 @@
1
+ export * from "./create-air-jam-store";
@@ -1,4 +1,4 @@
1
- import { DEFAULT_CONTROLLER_PATH, DEFAULT_SERVER_PORT } from "../constants";
1
+ import { CONTROLLER_PATH, DEFAULT_SERVER_PORT } from "../constants";
2
2
  import type { RoomCode } from "../protocol";
3
3
  import { getLocalNetworkIp } from "./network-ip";
4
4
 
@@ -76,16 +76,16 @@ class UrlBuilder {
76
76
 
77
77
  /**
78
78
  * Build a controller URL with room code.
79
+ * Controller is always at {baseUrl}/controller (standardized convention).
79
80
  * Automatically uses local IP when running on localhost.
80
81
  */
81
82
  async buildControllerUrl(
82
83
  roomId: RoomCode,
83
84
  options?: {
84
- path?: string;
85
85
  host?: string;
86
86
  },
87
87
  ): Promise<string> {
88
- const path = options?.path || DEFAULT_CONTROLLER_PATH;
88
+ const path = CONTROLLER_PATH;
89
89
 
90
90
  // If explicit host is provided, use it
91
91
  if (options?.host) {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/protocol.ts"],"names":["ErrorCode"],"mappings":"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","file":"chunk-XSXI3RIS.js","sourcesContent":["import { z } from \"zod\";\n\nexport type RoomCode = string;\n\nexport type ConnectionRole = \"host\" | \"controller\";\n\nexport type ConnectionStatus =\n | \"idle\"\n | \"connecting\"\n | \"connected\"\n | \"disconnected\"\n | \"reconnecting\";\n\nexport type RunMode = \"standalone\" | \"platform\";\n\nexport type GameState = \"paused\" | \"playing\";\n\nexport const roomCodeSchema = z\n .string()\n .trim()\n .min(4)\n .max(8)\n .regex(/^[A-Z0-9]+$/, { message: \"room code must contain only A-Z or 0-9\" });\n\nexport const controllerInputSchema = z.object({\n roomId: roomCodeSchema,\n controllerId: z.string().min(3),\n input: z.record(z.string(), z.unknown()), // Arbitrary JSON object - developers define their own structure\n});\n\nexport type ControllerInputPayload = Record<string, unknown>;\n\nexport interface ControllerInputEvent {\n roomId: RoomCode;\n controllerId: string;\n input: ControllerInputPayload;\n}\n\nexport const controllerStateSchema = z.object({\n roomId: roomCodeSchema,\n state: z.object({\n orientation: z.enum([\"portrait\", \"landscape\"]).optional(),\n message: z.string().optional(),\n gameState: z.enum([\"paused\", \"playing\"]).optional(),\n }),\n});\n\nexport type ControllerStateMessage = z.infer<typeof controllerStateSchema>;\n\nexport type ControllerStatePayload = z.infer<\n typeof controllerStateSchema\n>[\"state\"];\n\nexport const hostRegistrationSchema = z.object({\n roomId: roomCodeSchema,\n maxPlayers: z.number().int().min(1).max(16).default(8),\n apiKey: z.string().optional(),\n mode: z.enum([\"master\", \"child\"]).default(\"child\"),\n controllerUrl: z.string().url().optional(),\n});\n\nexport type HostRegistrationPayload = z.infer<typeof hostRegistrationSchema>;\n\nexport const controllerJoinSchema = z.object({\n roomId: roomCodeSchema,\n controllerId: z.string().min(3),\n nickname: z.string().trim().min(1).max(24).optional(),\n});\n\nexport type ControllerJoinPayload = z.infer<typeof controllerJoinSchema>;\n\nexport const controllerLeaveSchema = z.object({\n roomId: roomCodeSchema,\n controllerId: z.string().min(3),\n});\n\nexport type ControllerLeavePayload = z.infer<typeof controllerLeaveSchema>;\n\nexport interface PlayerProfile {\n id: string;\n label: string;\n color?: string;\n}\n\nexport interface HostRegistrationAck {\n ok: boolean;\n roomId?: RoomCode;\n message?: string;\n code?: ErrorCode | string;\n}\n\nexport interface ControllerJoinAck {\n ok: boolean;\n controllerId?: string;\n roomId?: RoomCode;\n message?: string;\n code?: ErrorCode | string;\n}\n\nexport const controllerSystemSchema = z.object({\n roomId: roomCodeSchema,\n command: z.enum([\"exit\", \"ready\", \"toggle_pause\"]),\n});\n\nexport type ControllerSystemPayload = z.infer<typeof controllerSystemSchema>;\n\n/**\n * Standard error codes for Air Jam\n */\nexport enum ErrorCode {\n // Room errors\n ROOM_NOT_FOUND = \"ROOM_NOT_FOUND\",\n ROOM_FULL = \"ROOM_FULL\",\n\n // Auth errors\n INVALID_API_KEY = \"INVALID_API_KEY\",\n UNAUTHORIZED = \"UNAUTHORIZED\",\n\n // Token errors\n INVALID_TOKEN = \"INVALID_TOKEN\",\n TOKEN_EXPIRED = \"TOKEN_EXPIRED\",\n\n // Connection errors\n CONNECTION_FAILED = \"CONNECTION_FAILED\",\n ALREADY_CONNECTED = \"ALREADY_CONNECTED\",\n\n // Validation errors\n INVALID_PAYLOAD = \"INVALID_PAYLOAD\",\n INVALID_ROOM_CODE = \"INVALID_ROOM_CODE\",\n\n // Server errors\n INTERNAL_SERVER_ERROR = \"INTERNAL_SERVER_ERROR\",\n SERVICE_UNAVAILABLE = \"SERVICE_UNAVAILABLE\",\n\n // Generic\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\n/**\n * Standardized error payload\n */\nexport interface ServerErrorPayload {\n code: ErrorCode | string; // Allow custom codes\n message: string;\n details?: unknown;\n}\n\nexport interface ControllerWelcomePayload {\n controllerId: string;\n roomId: RoomCode;\n player?: PlayerProfile;\n}\n\nexport interface ControllerJoinedNotice {\n controllerId: string;\n nickname?: string;\n player?: PlayerProfile;\n}\n\nexport interface ControllerLeftNotice {\n controllerId: string;\n}\n\nexport interface RoomReadyNotice {\n roomId: RoomCode;\n}\n\nexport interface HostLeftNotice {\n roomId: RoomCode;\n reason: string;\n}\n\nexport type SignalType = \"HAPTIC\" | \"TOAST\";\n\nexport interface HapticSignalPayload {\n pattern: \"light\" | \"medium\" | \"heavy\" | \"success\" | \"failure\" | \"custom\";\n sequence?: number | number[];\n}\n\nexport interface ToastSignalPayload {\n message: string;\n color?: string;\n duration?: number;\n}\n\nexport type SignalPayload =\n | {\n targetId?: string;\n type: \"HAPTIC\";\n payload: HapticSignalPayload;\n }\n | {\n targetId?: string;\n type: \"TOAST\";\n payload: ToastSignalPayload;\n };\n\nexport interface PlaySoundEventPayload {\n roomId: string;\n targetControllerId?: string; // If null, broadcast to all\n soundId: string;\n volume?: number;\n loop?: boolean;\n}\n\nexport const hostRegisterSystemSchema = z.object({\n roomId: roomCodeSchema,\n apiKey: z.string().optional(),\n});\n\nexport type HostRegisterSystemPayload = z.infer<\n typeof hostRegisterSystemSchema\n>;\n\nexport const systemLaunchGameSchema = z.object({\n roomId: roomCodeSchema,\n gameId: z.string(),\n gameUrl: z.string().url(),\n});\n\nexport type SystemLaunchGamePayload = z.infer<typeof systemLaunchGameSchema>;\n\nexport const hostJoinAsChildSchema = z.object({\n roomId: roomCodeSchema,\n joinToken: z.string(),\n});\n\nexport type HostJoinAsChildPayload = z.infer<typeof hostJoinAsChildSchema>;\n\nexport interface SystemLaunchGameAck {\n ok: boolean;\n joinToken?: string;\n message?: string;\n code?: ErrorCode | string;\n}\n\nexport interface ClientLoadUiPayload {\n url: string;\n}\n\nexport interface ClientToServerEvents {\n \"host:register\": (\n payload: z.infer<typeof hostRegistrationSchema>,\n callback: (ack: HostRegistrationAck) => void,\n ) => void;\n \"host:registerSystem\": (\n payload: HostRegisterSystemPayload,\n callback: (ack: HostRegistrationAck) => void,\n ) => void;\n \"system:launchGame\": (\n payload: SystemLaunchGamePayload,\n callback: (ack: SystemLaunchGameAck) => void,\n ) => void;\n \"host:joinAsChild\": (\n payload: HostJoinAsChildPayload,\n callback: (ack: HostRegistrationAck) => void,\n ) => void;\n \"system:closeGame\": (payload: { roomId: string }) => void;\n \"host:state\": (payload: z.infer<typeof controllerStateSchema>) => void;\n \"controller:join\": (\n payload: z.infer<typeof controllerJoinSchema>,\n callback: (ack: ControllerJoinAck) => void,\n ) => void;\n \"controller:leave\": (payload: z.infer<typeof controllerLeaveSchema>) => void;\n \"controller:input\": (payload: z.infer<typeof controllerInputSchema>) => void;\n \"controller:system\": (\n payload: z.infer<typeof controllerSystemSchema>,\n ) => void;\n \"host:system\": (payload: z.infer<typeof controllerSystemSchema>) => void;\n \"host:signal\": (payload: SignalPayload) => void;\n \"host:play_sound\": (payload: PlaySoundEventPayload) => void;\n \"controller:play_sound\": (payload: PlaySoundEventPayload) => void;\n}\n\nexport interface PlaySoundPayload {\n id: string;\n volume?: number;\n loop?: boolean;\n}\n\nexport interface ServerToClientEvents {\n \"server:roomReady\": (payload: RoomReadyNotice) => void;\n \"server:controllerJoined\": (payload: ControllerJoinedNotice) => void;\n \"server:controllerLeft\": (payload: ControllerLeftNotice) => void;\n \"server:input\": (payload: ControllerInputEvent) => void;\n \"server:error\": (payload: ServerErrorPayload) => void;\n \"server:state\": (payload: z.infer<typeof controllerStateSchema>) => void;\n \"server:welcome\": (payload: ControllerWelcomePayload) => void;\n \"server:hostLeft\": (payload: HostLeftNotice) => void;\n \"server:signal\": (payload: SignalPayload) => void;\n \"server:playSound\": (payload: PlaySoundPayload) => void;\n \"server:redirect\": (url: string) => void;\n \"server:closeChild\": () => void;\n \"client:loadUi\": (payload: ClientLoadUiPayload) => void;\n \"client:unloadUi\": () => void;\n}\n\nexport interface InterServerEvents {\n ping: () => void;\n}\n\nexport type SocketData = Record<string, unknown>;\n\n// --- Proxy Protocol (iframe <-> parent) ---\n// Note: Proxy protocol is largely deprecated in favor of Direct Connect (airjam_force_connect=true),\n// but might still be used for UI coordination (e.g. hiding headers).\n\nexport const AIRJAM_PROXY_PREFIX = \"AIRJAM_\";\n\nexport interface ProxyMessageBase {\n type: string;\n}\n\nexport interface ProxyReadyMessage extends ProxyMessageBase {\n type: \"AIRJAM_READY\";\n}\n\nexport interface ProxyInputMessage extends ProxyMessageBase {\n type: \"AIRJAM_INPUT\";\n payload: ControllerInputPayload;\n}\n\nexport interface ProxyStateMessage extends ProxyMessageBase {\n type: \"AIRJAM_STATE\";\n payload: ControllerStatePayload;\n}\n\nexport type AirJamProxyMessage =\n | ProxyReadyMessage\n | ProxyInputMessage\n | ProxyStateMessage;\n"]}