Sends a type-safe, validated message using a message definition.
This is the preferred way to send messages as it provides:
The message definition type
Message definition created with defineMessage()
Message data that matches the definition's schema
const userMsg = defineMessage('user', z.object({
name: z.string(),
age: z.number().min(0)
}));
// Type-safe and validated
await channel.sendMessage(userMsg, {
name: 'Alice',
age: 25
});
// TypeScript error: missing required field
await channel.sendMessage(userMsg, { name: 'Bob' }); // Error!
// Runtime error: validation fails
await channel.sendMessage(userMsg, { name: 'Charlie', age: -1 }); // Throws!
Registers a message handler for a specific message type (by string ID).
String identifier for the message type
Function to handle incoming messages
Registers a type-safe message handler using a message definition. This is the preferred method as it provides full type safety.
Message definition created with defineMessage()
Type-safe handler function
Removes a message handler for a specific message type (by string ID).
String identifier for the message type
The exact handler function to remove
Removes a type-safe message handler using a message definition.
Message definition created with defineMessage()
The exact handler function to remove
Establishes a WebSocket connection to the specified server.
Automatically handles connection state validation and sets up reconnection logic for dropped connections.
WebSocket server URL (ws:// or wss://)
Closes the connection and cleans up resources.
Sends raw data over the channel. Use sendMessage() for type-safe validated sending instead.
Message type identifier
Raw message data
Configures automatic reconnection behavior.
Call this before connecting to customize how the channel handles connection failures. Uses exponential backoff: each retry waits longer than the previous attempt.
Maximum number of reconnection attempts (default: 5)
Initial delay in milliseconds (default: 1000)
Example
Basic usage:
Example
With custom reconnection settings:
Example
Error handling: