UNPKG

@lobstar/core

Version:

A simple network and lobby manager for multiplayer web games

98 lines (97 loc) 3.02 kB
import { PeerOptions } from "peerjs"; export type NetworkEvents = { message: { data: unknown; peerId: string; }; connection: { peerId: string; metadata: unknown; }; disconnection: { peerId: string; }; error: { error: unknown; context?: string; }; }; type NetworkManagerOptions = { debug?: boolean; peerOptions?: PeerOptions; }; export declare class NetworkManager { private debug; private peer; private peerOptions; private connections; private emitter; constructor({ debug, peerOptions }?: NetworkManagerOptions); /** * Initialize the network manager, optionally with a specific peer ID. * If no ID is provided, PeerJS will generate one. * @param {string} [peerId] - Optional identifier for this peer */ initialize(peerId?: string): Promise<void>; private log; /** * Set up event listeners for the peer */ private setupEventListeners; /** * Connect to another peer * @param {string} peerId - ID of the peer to connect to * @param {unknown} [metadata] - Optional metadata to send with connection */ connectToPeer(peerId: string, metadata?: unknown): void; /** * Handle a new connection (both incoming and outgoing) * @param {DataConnection} connection - The PeerJS connection object */ private handleNewConnection; /** * Broadcast a message to all connected peers * @param {unknown} data - The data to broadcast */ broadcast(data: unknown, excludeSelf?: boolean): void; /** * Send a message to a specific peer * @param {string} peerId - ID of the target peer * @param {unknown} data - The data to send * @returns {boolean} Whether the message was sent successfully */ sendToPeer(peerId: string, data: unknown): boolean; /** * Register an event listener * @param {K} event - Event name to listen for * @param {function} handler - Event handler function */ on<K extends keyof NetworkEvents>(event: K, handler: (data: NetworkEvents[K]) => void): void; /** * Remove an event listener * @param {K} event - Event name to remove listener from * @param {function} handler - Event handler to remove */ off<K extends keyof NetworkEvents>(event: K, handler: (data: NetworkEvents[K]) => void): void; /** * Get the current peer ID * @returns {string} The peer ID, or null if not initialized */ getPeerId(): string | null; /** * Get all connected peer IDs * @returns {string[]} Array of connected peer IDs */ getConnectedPeers(): string[]; /** * Disconnect a specific peer connection. * @param {string} peerId - ID of the peer to disconnect * @returns {boolean} Whether a connection was found and closed */ disconnectPeer(peerId: string): boolean; /** * Clean up resources */ destroy(): void; } export {};