@air-jam/sdk 0.1.1 → 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.
@@ -34,10 +34,10 @@ import type {
34
34
  import {
35
35
  controllerStateSchema,
36
36
  controllerSystemSchema,
37
- hostRegistrationSchema,
37
+ hostCreateRoomSchema,
38
+ hostReconnectSchema,
38
39
  roomCodeSchema,
39
40
  } from "../protocol";
40
- import { generateRoomCode } from "../utils/ids";
41
41
  import { detectRunMode } from "../utils/mode";
42
42
  import { urlBuilder } from "../utils/url-builder";
43
43
 
@@ -276,15 +276,24 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
276
276
  // Always connect - forceConnect kept for API compatibility
277
277
  const shouldConnect = true;
278
278
 
279
- // Generate fallback room ID once
280
- const [fallbackRoomId] = useState(() => generateRoomCode());
279
+ // Subscribe to store state to get roomId (server-issued for standalone mode)
280
+ const storeRoomId = useStore(store, (s) => s.roomId);
281
281
 
282
282
  // Parse room ID from various sources
283
- const parsedRoomId = useMemo<RoomCode>(() => {
283
+ // For child mode: use arcadeParams.room (from URL)
284
+ // For standalone mode: use store.roomId (set after server responds)
285
+ const parsedRoomId = useMemo<RoomCode | null>(() => {
284
286
  if (arcadeParams) {
287
+ // Child mode: room ID comes from URL params
285
288
  return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
286
289
  }
287
290
 
291
+ // Standalone mode: use store.roomId (server-issued)
292
+ if (storeRoomId) {
293
+ return roomCodeSchema.parse(storeRoomId.toUpperCase());
294
+ }
295
+
296
+ // Fallback: check URL param or options (for reconnection scenarios)
288
297
  if (typeof window !== "undefined") {
289
298
  const params = new URLSearchParams(window.location.search);
290
299
  const paramRoom = params.get("room");
@@ -298,15 +307,8 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
298
307
  return roomCodeSchema.parse(options.roomId.toUpperCase());
299
308
  }
300
309
 
301
- return fallbackRoomId;
302
- }, [options.roomId, fallbackRoomId, arcadeParams]);
303
-
304
- // Update InputManager room ID when parsedRoomId changes
305
- useEffect(() => {
306
- if (inputManager) {
307
- inputManager.setRoomId(parsedRoomId);
308
- }
309
- }, [inputManager, parsedRoomId]);
310
+ return null;
311
+ }, [options.roomId, storeRoomId, arcadeParams]);
310
312
 
311
313
  const [joinUrl, setJoinUrl] = useState<string>("");
312
314
 
@@ -330,6 +332,7 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
330
332
  players: state.players,
331
333
  gameState: state.gameState,
332
334
  mode: state.mode,
335
+ roomId: state.roomId,
333
336
  })),
334
337
  );
335
338
 
@@ -352,6 +355,8 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
352
355
  return;
353
356
  }
354
357
 
358
+ if (!parsedRoomId) return;
359
+
355
360
  const payload = controllerSystemSchema.safeParse({
356
361
  roomId: parsedRoomId,
357
362
  command: "toggle_pause",
@@ -363,7 +368,7 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
363
368
 
364
369
  const sendState = useCallback(
365
370
  (state: ControllerStatePayload): boolean => {
366
- if (!socket || !socket.connected) {
371
+ if (!socket || !socket.connected || !parsedRoomId) {
367
372
  return false;
368
373
  }
369
374
  const payload = controllerStateSchema.safeParse({
@@ -407,14 +412,15 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
407
412
 
408
413
  // Build controller URL
409
414
  useEffect(() => {
415
+ if (!parsedRoomId) return; // Don't build URL until we have a room ID
416
+
410
417
  (async () => {
411
418
  const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
412
- path: config.controllerPath,
413
419
  host: config.publicHost,
414
420
  });
415
421
  setJoinUrl(url);
416
422
  })();
417
- }, [parsedRoomId, config.controllerPath, config.publicHost]);
423
+ }, [parsedRoomId, config.publicHost, options.roomId]);
418
424
 
419
425
  // Get setRegisteredRoomId from store
420
426
  const setRegisteredRoomId = useStore(store, (s) => s.setRegisteredRoomId);
@@ -424,7 +430,11 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
424
430
  const storeState = store.getState();
425
431
  storeState.setMode(detectRunMode());
426
432
  storeState.setRole("host");
427
- storeState.setRoomId(parsedRoomId);
433
+ // Don't set roomId here - it will be set after server responds
434
+ // Only set it if we have it (child mode or reconnection)
435
+ if (parsedRoomId) {
436
+ storeState.setRoomId(parsedRoomId);
437
+ }
428
438
  storeState.setStatus("connecting");
429
439
  storeState.setError(undefined);
430
440
 
@@ -436,14 +446,14 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
436
446
  const registerHost = async () => {
437
447
  const storeState = store.getState();
438
448
 
439
- // Prevent duplicate registration for the same room
449
+ // Prevent duplicate registration
440
450
  const currentRegisteredRoomId = store.getState().registeredRoomId;
441
- if (currentRegisteredRoomId === parsedRoomId && socket.connected) {
451
+ if (currentRegisteredRoomId && socket.connected) {
442
452
  return;
443
453
  }
444
454
 
445
455
  if (arcadeParams) {
446
- // Child Mode - join as child
456
+ // Child Mode - join as child (unchanged)
447
457
  const childRoomId = roomCodeSchema.parse(
448
458
  arcadeParams.room.toUpperCase(),
449
459
  );
@@ -463,28 +473,68 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
463
473
  setRegisteredRoomId(childRoomId);
464
474
  });
465
475
  } else {
466
- // Standalone Mode - register as master host
467
- const payload = hostRegistrationSchema.parse({
468
- roomId: parsedRoomId,
469
- maxPlayers: options.maxPlayers ?? config.maxPlayers,
470
- apiKey: options.apiKey ?? config.apiKey,
471
- });
476
+ // Standalone Mode - use server-issued room IDs
477
+ const createNewRoom = () => {
478
+ const payload = hostCreateRoomSchema.parse({
479
+ maxPlayers: options.maxPlayers ?? config.maxPlayers,
480
+ apiKey: options.apiKey ?? config.apiKey,
481
+ });
482
+
483
+ socket.emit("host:createRoom", payload, (ack) => {
484
+ if (!ack.ok) {
485
+ storeState.setError(ack.message ?? "Failed to create room");
486
+ storeState.setStatus("disconnected");
487
+ setRegisteredRoomId(null);
488
+ return;
489
+ }
490
+
491
+ if (ack.roomId) {
492
+ storeState.setStatus("connected");
493
+ storeState.setRoomId(ack.roomId);
494
+ setRegisteredRoomId(ack.roomId);
495
+
496
+ // Save room ID to sessionStorage for reconnection on reload
497
+ if (typeof window !== "undefined") {
498
+ sessionStorage.setItem("airjam_room_id", ack.roomId);
499
+ }
500
+ } else {
501
+ storeState.setError("Server did not return room ID");
502
+ storeState.setStatus("disconnected");
503
+ }
504
+ });
505
+ };
472
506
 
473
- socket.emit("host:register", payload, (ack) => {
474
- if (!ack.ok) {
475
- storeState.setError(ack.message ?? "Failed to register host");
476
- storeState.setStatus("disconnected");
477
- setRegisteredRoomId(null);
478
- return;
479
- }
480
- storeState.setStatus("connected");
481
- if (ack.roomId) {
482
- storeState.setRoomId(ack.roomId);
483
- setRegisteredRoomId(ack.roomId);
507
+ // Check for saved room ID in sessionStorage (for reconnection)
508
+ if (typeof window !== "undefined") {
509
+ const savedRoomId = sessionStorage.getItem("airjam_room_id");
510
+ if (savedRoomId) {
511
+ // Attempt to reconnect to existing room
512
+ const reconnectPayload = hostReconnectSchema.parse({
513
+ roomId: savedRoomId,
514
+ apiKey: options.apiKey ?? config.apiKey,
515
+ });
516
+
517
+ socket.emit("host:reconnect", reconnectPayload, (ack) => {
518
+ if (ack.ok && ack.roomId) {
519
+ storeState.setStatus("connected");
520
+ storeState.setRoomId(ack.roomId);
521
+ setRegisteredRoomId(ack.roomId);
522
+ } else {
523
+ // Reconnection failed (room expired), create new room
524
+ if (typeof window !== "undefined") {
525
+ sessionStorage.removeItem("airjam_room_id");
526
+ }
527
+ createNewRoom();
528
+ }
529
+ });
484
530
  } else {
485
- setRegisteredRoomId(parsedRoomId);
531
+ // No saved room ID, create new room
532
+ createNewRoom();
486
533
  }
487
- });
534
+ } else {
535
+ // Not in browser environment, create new room
536
+ createNewRoom();
537
+ }
488
538
  }
489
539
  };
490
540
 
@@ -527,7 +577,7 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
527
577
  };
528
578
 
529
579
  const handleState = (payload: ControllerStateMessage): void => {
530
- if (payload.roomId !== parsedRoomId) return;
580
+ if (!parsedRoomId || payload.roomId !== parsedRoomId) return;
531
581
 
532
582
  const storeState = store.getState();
533
583
  if (payload.state.gameState) {
@@ -556,15 +606,10 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
556
606
 
557
607
  // If socket is already connected, register immediately
558
608
  const currentRegisteredRoomId = store.getState().registeredRoomId;
559
- if (socket.connected && currentRegisteredRoomId !== parsedRoomId) {
609
+ if (socket.connected && !currentRegisteredRoomId) {
560
610
  registerHost();
561
611
  }
562
612
 
563
- // Reset registered room when parsedRoomId changes
564
- if (currentRegisteredRoomId && currentRegisteredRoomId !== parsedRoomId) {
565
- setRegisteredRoomId(null);
566
- }
567
-
568
613
  return () => {
569
614
  socket.off("connect", handleConnect);
570
615
  socket.off("disconnect", handleDisconnect);
@@ -580,8 +625,8 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
580
625
  config.apiKey,
581
626
  options.maxPlayers,
582
627
  options.apiKey,
583
- parsedRoomId,
584
628
  arcadeParams,
629
+ parsedRoomId, // Include parsedRoomId since it's used in handleState callback
585
630
  shouldConnect,
586
631
  socket,
587
632
  store,
@@ -606,7 +651,7 @@ export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
606
651
  );
607
652
 
608
653
  return {
609
- roomId: parsedRoomId,
654
+ roomId: parsedRoomId ?? ("" as RoomCode), // Return empty string as fallback if not yet available
610
655
  joinUrl,
611
656
  connectionStatus: connectionState.connectionStatus,
612
657
  players: connectionState.players,
@@ -51,6 +51,10 @@ const getRoomFromLocation = (): string | null => {
51
51
  return code ? code.toUpperCase() : null;
52
52
  };
53
53
 
54
+ // Throttling variables for logging
55
+ let lastSendInputLogTime = 0;
56
+ let lastSendInputFailLogTime = 0;
57
+
54
58
  export const useAirJamShell = (
55
59
  options: AirJamShellOptions = {},
56
60
  ): AirJamShellApi => {
@@ -256,6 +260,7 @@ export const useAirJamShell = (
256
260
  socket.on("disconnect", handleDisconnect);
257
261
  socket.on("server:welcome", handleWelcome);
258
262
  socket.on("server:state", handleState);
263
+
259
264
  socket.on("client:loadUi", handleLoadUi);
260
265
  socket.on("client:unloadUi", handleUnloadUi);
261
266
  socket.on("server:error", handleError);
@@ -280,12 +285,43 @@ export const useAirJamShell = (
280
285
  const sendInput = useCallback(
281
286
  (input: ControllerInputPayload): boolean => {
282
287
  const storeState = store.getState();
288
+ const now = Date.now();
289
+
290
+ // Only log when there's actual user input (not just the loop sending zeros)
291
+ const hasActiveInput =
292
+ input.action === true ||
293
+ (typeof input.vector === "object" &&
294
+ input.vector !== null &&
295
+ (Math.abs((input.vector as { x?: number; y?: number }).x ?? 0) >
296
+ 0.01 ||
297
+ Math.abs((input.vector as { x?: number; y?: number }).y ?? 0) >
298
+ 0.01));
299
+
300
+ // Throttled logging - only log active input, once per second max
301
+ if (
302
+ hasActiveInput &&
303
+ (!lastSendInputLogTime || now - lastSendInputLogTime > 1000)
304
+ ) {
305
+ lastSendInputLogTime = now;
306
+ }
283
307
 
284
308
  if (!parsedRoomId || !storeState.controllerId || !socket) {
309
+ if (
310
+ !lastSendInputFailLogTime ||
311
+ now - lastSendInputFailLogTime > 1000
312
+ ) {
313
+ lastSendInputFailLogTime = now;
314
+ }
285
315
  storeState.setError("Not connected to a room");
286
316
  return false;
287
317
  }
288
318
  if (!socket.connected) {
319
+ if (
320
+ !lastSendInputFailLogTime ||
321
+ now - lastSendInputFailLogTime > 1000
322
+ ) {
323
+ lastSendInputFailLogTime = now;
324
+ }
289
325
  return false;
290
326
  }
291
327
 
@@ -39,6 +39,9 @@
39
39
  import type { z } from "zod";
40
40
  import type { ControllerInputEvent } from "../protocol";
41
41
 
42
+ // Throttling for debug logging
43
+ let lastInputManagerLogTime = 0;
44
+
42
45
  /**
43
46
  * Configuration for input handling with optional validation and latching.
44
47
  *
@@ -165,11 +168,9 @@ export class InputManager<TSchema extends z.ZodSchema = z.ZodSchema> {
165
168
  private inputBuffer = new Map<string, Record<string, unknown>>();
166
169
  private latchState = new Map<string, LatchState>();
167
170
  private config: InputConfig<TSchema>;
168
- private roomId?: string;
169
171
 
170
- constructor(config: InputConfig<TSchema> = {}, roomId?: string) {
172
+ constructor(config: InputConfig<TSchema> = {}) {
171
173
  this.config = config;
172
- this.roomId = roomId;
173
174
  }
174
175
 
175
176
  /**
@@ -177,13 +178,33 @@ export class InputManager<TSchema extends z.ZodSchema = z.ZodSchema> {
177
178
  * Should be called when 'server:input' event is received.
178
179
  */
179
180
  handleInput(payload: ControllerInputEvent): void {
180
- // Security/Sanity check: Only process inputs from our room
181
- if (this.roomId && payload.roomId !== this.roomId) {
182
- return;
183
- }
181
+ // Note: We don't filter by roomId here because:
182
+ // 1. The server already routes input correctly to the right host
183
+ // 2. Multiple host instances might share the same InputManager instance
184
+ // 3. The roomId check was causing false rejections when hosts re-register
184
185
 
185
186
  // Store raw input as-is (arbitrary structure)
186
187
  this.inputBuffer.set(payload.controllerId, payload.input);
188
+
189
+ // Throttled logging - only log active input, once per second max
190
+ const now = Date.now();
191
+ const input = payload?.input;
192
+ const hasActiveInput =
193
+ input &&
194
+ (input.action === true ||
195
+ (typeof input.vector === "object" &&
196
+ input.vector !== null &&
197
+ (Math.abs((input.vector as { x?: number; y?: number }).x ?? 0) >
198
+ 0.01 ||
199
+ Math.abs((input.vector as { x?: number; y?: number }).y ?? 0) >
200
+ 0.01)));
201
+
202
+ if (
203
+ hasActiveInput &&
204
+ (!lastInputManagerLogTime || now - lastInputManagerLogTime > 1000)
205
+ ) {
206
+ lastInputManagerLogTime = now;
207
+ }
187
208
  }
188
209
 
189
210
  /**
@@ -232,13 +253,6 @@ export class InputManager<TSchema extends z.ZodSchema = z.ZodSchema> {
232
253
  this.latchState.delete(controllerId);
233
254
  }
234
255
 
235
- /**
236
- * Updates the room ID filter.
237
- */
238
- setRoomId(roomId: string | undefined): void {
239
- this.roomId = roomId;
240
- }
241
-
242
256
  /**
243
257
  * Internal method to apply latching logic.
244
258
  */
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;
@@ -270,6 +290,14 @@ export interface ClientToServerEvents {
270
290
  payload: HostRegisterSystemPayload,
271
291
  callback: (ack: HostRegistrationAck) => void,
272
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;
273
301
  "system:launchGame": (
274
302
  payload: SystemLaunchGamePayload,
275
303
  callback: (ack: SystemLaunchGameAck) => void,
@@ -1,4 +1,4 @@
1
- import { useEffect } from "react";
1
+ import { useEffect, useRef } from "react";
2
2
  import { create, type StateCreator } from "zustand";
3
3
  import { useAirJamContext, useAirJamState } from "../context/air-jam-context";
4
4
  import type {
@@ -58,6 +58,9 @@ export function createAirJamStore<
58
58
  });
59
59
 
60
60
  // 2. The Hook Component
61
+ // Track if game UI is unloaded to disable proxy actions
62
+ const gameUiUnloadedRef = { current: false };
63
+
61
64
  const useSyncedStore = <U>(
62
65
  selector: (state: T) => U = (s) => s as unknown as U,
63
66
  ): U => {
@@ -71,6 +74,12 @@ export function createAirJamStore<
71
74
  const socket =
72
75
  role === "host" ? getSocket("host") : getSocket("controller");
73
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
+
74
83
  // --- NETWORKING LOGIC ---
75
84
  useEffect(() => {
76
85
  if (!socket || !roomId || !role) {
@@ -109,6 +118,9 @@ export function createAirJamStore<
109
118
 
110
119
  // CONTROLLER: Listen for state updates
111
120
  if (role === "controller") {
121
+ // Reset unloaded flag when we have a new room/socket (game is loading)
122
+ gameUiUnloadedRef.current = false;
123
+
112
124
  const handleSync = (payload: AirJamStateSyncPayload) => {
113
125
  const { data } = payload;
114
126
  // Merge incoming state, but KEEP the local actions
@@ -128,9 +140,39 @@ export function createAirJamStore<
128
140
  };
129
141
 
130
142
  socket.on("airjam:state_sync", handleSync);
131
- return () => socket.off("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
+ };
132
174
  }
133
- }, [socket, role, roomId]);
175
+ }, [socket, role, roomId, socket?.id]);
134
176
 
135
177
  // --- PROXY ACTIONS (The Magic) ---
136
178
  // On the Controller, we replace actions with Network Calls
@@ -176,17 +218,37 @@ export function createAirJamStore<
176
218
  // We cast to the same type as T["actions"] to maintain type compatibility
177
219
  (proxyActions as Record<string, (...args: unknown[]) => void>)[key] =
178
220
  (...args: unknown[]) => {
179
- // 1. Optimistic Update (Optional, disabled for safety by default)
180
- // originalActions[key](...args);
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
+ }
181
232
 
182
- // 2. Send RPC to Host (include controllerId to handle reconnections)
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
183
243
  if (!controllerId) {
184
244
  console.warn(
185
245
  "[AirJamStore] Cannot send action RPC: controllerId not set",
186
246
  );
187
247
  return;
188
248
  }
189
- socket.emit("controller:action_rpc", {
249
+
250
+ // 4. Send RPC to Host (include controllerId to handle reconnections)
251
+ activeSocket.emit("controller:action_rpc", {
190
252
  roomId,
191
253
  actionName: key,
192
254
  args,
@@ -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":";;;AAiBO,IAAM,iBAAiB,CAAA,CAC3B,MAAA,EAAO,CACP,IAAA,GACA,GAAA,CAAI,CAAC,CAAA,CACL,GAAA,CAAI,CAAC,CAAA,CACL,KAAA,CAAM,eAAe,EAAE,OAAA,EAAS,0CAA0C;AAEtE,IAAM,qBAAA,GAAwB,EAAE,MAAA,CAAO;AAAA,EAC5C,MAAA,EAAQ,cAAA;AAAA,EACR,YAAA,EAAc,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA,EAC9B,KAAA,EAAO,EAAE,MAAA,CAAO,CAAA,CAAE,QAAO,EAAG,CAAA,CAAE,SAAS;AAAA;AACzC,CAAC;AAUM,IAAM,qBAAA,GAAwB,EAAE,MAAA,CAAO;AAAA,EAC5C,MAAA,EAAQ,cAAA;AAAA,EACR,KAAA,EAAO,EAAE,MAAA,CAAO;AAAA,IACd,WAAA,EAAa,EAAE,IAAA,CAAK,CAAC,YAAY,WAAW,CAAC,EAAE,QAAA,EAAS;AAAA,IACxD,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chunk-7M5D3Y3L.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 HostStateSyncPayload {\n roomId: string;\n data: Record<string, unknown>;\n}\n\nexport interface ControllerActionRpcPayload {\n roomId: string;\n actionName: string;\n args: unknown[];\n controllerId: string;\n}\n\nexport interface AirJamStateSyncPayload {\n roomId: string;\n data: Record<string, unknown>;\n}\n\nexport interface AirJamActionRpcPayload {\n actionName: string;\n args: unknown[];\n controllerId: 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 \"host:state_sync\": (payload: HostStateSyncPayload) => void;\n \"controller:action_rpc\": (payload: ControllerActionRpcPayload) => 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 \"airjam:state_sync\": (payload: AirJamStateSyncPayload) => void;\n \"airjam:action_rpc\": (payload: AirJamActionRpcPayload) => 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"]}