Zodiac API Documentation - v0.0.3
    Preparing search index...

    Class BrowserChannel

    Basic usage:

    import { BrowserChannel, defineMessage, z } from '@xtr-dev/zodiac';

    // Create channel
    const channel = new BrowserChannel();

    // Configure reconnection (optional)
    channel.setReconnectOptions(10, 500); // 10 attempts, 500ms base delay

    // Define message types
    const statusUpdate = defineMessage('status', z.object({
    user: z.string(),
    online: z.boolean(),
    lastSeen: z.number()
    }));

    // Set up handlers before connecting
    channel.on(statusUpdate, (data) => {
    console.log(`${data.user} is ${data.online ? 'online' : 'offline'}`);
    });

    // Connect to WebSocket server
    try {
    await channel.connect('ws://localhost:8080');
    console.log('Connected successfully!');

    // Send messages
    await channel.sendMessage(statusUpdate, {
    user: 'alice',
    online: true,
    lastSeen: Date.now()
    });
    } catch (error) {
    console.error('Failed to connect:', error);
    }

    With custom reconnection settings:

    const channel = new BrowserChannel();

    // Custom reconnection: 15 attempts, starting at 2 seconds
    channel.setReconnectOptions(15, 2000);

    await channel.connect('wss://api.example.com/ws');

    // The channel will automatically reconnect if connection drops
    // Schedule: 2s, 4s, 8s, 16s, 32s, 64s, ...

    Error handling:

    channel.on('error-event', (data) => {
    console.error('Server error:', data.message);
    });

    try {
    await channel.sendMessage(someMessage, data);
    } catch (error) {
    if (error.name === 'ZodError') {
    console.error('Invalid data:', error.errors);
    } else {
    console.error('Network error:', error.message);
    }
    }

    Hierarchy

    • BaseChannel
      • BrowserChannel
    Index

    Constructors

    Methods

    • Sends a type-safe, validated message using a message definition.

      This is the preferred way to send messages as it provides:

      • Compile-time type checking
      • Runtime validation with Zod
      • Automatic message ID handling

      Type Parameters

      Parameters

      • definition: T

        Message definition created with defineMessage()

      • data: InferMessageData<T>

        Message data that matches the definition's schema

      Returns Promise<void>

      When data doesn't match the 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).

      Type Parameters

      • T

      Parameters

      • id: string

        String identifier for the message type

      • handler: MessageHandler<T>

        Function to handle incoming messages

      Returns void

    • Registers a type-safe message handler using a message definition. This is the preferred method as it provides full type safety.

      Type Parameters

      Parameters

      Returns void

      const chatMsg = defineMessage('chat', z.object({
      user: z.string(),
      text: z.string()
      }));

      // Fully typed handler - data.user and data.text are known
      channel.on(chatMsg, (data, message) => {
      console.log(`${data.user}: ${data.text}`);
      console.log(`Sent at: ${message.timestamp}`);
      });
    • Removes a message handler for a specific message type (by string ID).

      Type Parameters

      • T

      Parameters

      • id: string

        String identifier for the message type

      • handler: MessageHandler<T>

        The exact handler function to remove

      Returns void

    • Removes a type-safe message handler using a message definition.

      Type Parameters

      Parameters

      Returns void

      const handler = (data) => console.log(data.text);

      // Register handler
      channel.on(chatMsg, handler);

      // Remove the same handler instance
      channel.off(chatMsg, handler);
    • Checks if the channel is currently connected and ready for communication.

      Returns boolean

      true if connected, false otherwise

      if (channel.isOpen()) {
      await channel.sendMessage(someMessage, data);
      } else {
      console.log('Channel is not connected');
      }
    • Establishes a WebSocket connection to the specified server.

      Automatically handles connection state validation and sets up reconnection logic for dropped connections.

      Parameters

      • url: string

        WebSocket server URL (ws:// or wss://)

      Returns Promise<void>

      If already connected or connection is in progress

      If WebSocket creation fails

      // Connect to local development server
      await channel.connect('ws://localhost:8080');

      // Connect to secure production server
      await channel.connect('wss://api.myapp.com/websocket');
    • Closes the connection and cleans up resources.

      Returns Promise<void>

    • Sends raw data over the channel. Use sendMessage() for type-safe validated sending instead.

      Type Parameters

      • T

      Parameters

      • id: string

        Message type identifier

      • data: T

        Raw message data

      Returns Promise<void>

    • 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.

      Parameters

      • maxAttempts: number

        Maximum number of reconnection attempts (default: 5)

      • baseDelay: number

        Initial delay in milliseconds (default: 1000)

      Returns void

      // More aggressive reconnection
      channel.setReconnectOptions(20, 500);
      // Will try: 500ms, 1s, 2s, 4s, 8s, 16s, 32s...

      // Less aggressive reconnection
      channel.setReconnectOptions(3, 5000);
      // Will try: 5s, 10s, 20s, then give up

      // Disable reconnection
      channel.setReconnectOptions(0, 1000);