### Install Dependencies and Run Servers Source: https://github.com/laplace-live/event-bridge/blob/master/CLAUDE.md Setup development environment by installing dependencies. Start either the Go server or the deprecated Bun server. ```bash # Install dependencies bun install # Run Go server (recommended) go run ./packages/server --debug # Or run Bun server bun run --cwd packages/server-bun start --debug ``` -------------------------------- ### SDK Installation and Usage Source: https://github.com/laplace-live/event-bridge/blob/master/README.md Instructions for installing the SDK via npm and a basic usage example demonstrating how to connect to the event bridge, listen for specific events, and listen for all events. ```bash # Install from npm bun add @laplace.live/event-bridge-sdk ``` ```typescript import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', token: 'your-auth-token', // If auth is enabled }) // Connect to the bridge await client.connect() // Listen for specific events client.on('message', event => { console.log('Received message:', event) }) // Listen for all events client.onAny(event => { console.log('Received event:', event.type) }) ``` -------------------------------- ### Run CLI Demo from Directory Source: https://github.com/laplace-live/event-bridge/blob/master/examples/cli-demo/README.md Starts the LAPLACE Event Bridge CLI demo directly from the example's directory using Bun. ```bash bun start ``` -------------------------------- ### Start Server with CLI Options Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Starts the server with multiple command-line options for debugging, authentication, and network interface configuration. ```bash bun run start --debug --auth "your-secure-token" --host 0.0.0.0 ``` -------------------------------- ### Start Bun Bridge Server (Deprecated) Source: https://github.com/laplace-live/event-bridge/blob/master/README.md Starts the deprecated Bun/Node.js implementation of the bridge server. Use this for reference or if you rely on this version. Requires Bun to be installed. ```bash bun run --cwd packages/server-bun start --debug --auth "your-secure-token" ``` -------------------------------- ### Install LAPLACE Event Bridge SDK Source: https://github.com/laplace-live/event-bridge/blob/master/packages/sdk/README.md Install the SDK using npm, Yarn, or Bun. ```bash # Using npm npm install @laplace.live/event-bridge-sdk # Using Yarn yarn add @laplace.live/event-bridge-sdk # Using Bun bun add @laplace.live/event-bridge-sdk ``` -------------------------------- ### Connect to Custom WebSocket Server Source: https://github.com/laplace-live/event-bridge/blob/master/examples/cli-demo/README.md Example of running the CLI demo and connecting to a specific WebSocket server URL using a command-line argument. ```bash bun start --url ws://example.com:9696 ``` -------------------------------- ### Install Event Bridge SDK Source: https://github.com/laplace-live/event-bridge/blob/master/README.md Install the SDK using npm or bun. This is the first step to integrating with the event bridge. ```bash # Install from npm bun add @laplace.live/event-bridge-sdk ``` -------------------------------- ### Start Development Server with Bun Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/README.md Starts the development server with hot reload capabilities. The application will be accessible at http://localhost:4000. ```bash bun dev ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/laplace-live/event-bridge/blob/master/examples/cli-demo/README.md Installs project dependencies using the Bun package manager. Run this from the project root. ```bash bun install ``` -------------------------------- ### Bun Server with Routes and WebSockets Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/CLAUDE.md Example of setting up a Bun server with basic routing, API endpoints, and WebSocket support. The `development.hmr` option enables Hot Module Replacement. ```typescript import index from "./index.html" Bun.serve({ routes: { "/": index, "/api/users/:id": { GET: (req) => { return new Response(JSON.stringify({ id: req.params.id })); }, }, }, // optional websocket support websocket: { open: (ws) => { ws.send("Hello, world!"); }, message: (ws, message) => { ws.send(message); }, close: (ws) => { // handle close } }, development: { hmr: true, console: true, } }) ``` -------------------------------- ### Start the Bridge Server Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Starts the WebSocket bridge server. The server defaults to http://localhost:9696. ```bash bun run start ``` -------------------------------- ### Configure Authentication via Command Line Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Starts the server with an authentication token provided via the --auth command-line argument. This token is required for all connections when enabled. ```bash bun run start --auth "your-secure-token" ``` -------------------------------- ### Run Production Server with Bun Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/README.md Runs the application in production mode using Bun. Alternatively, set NODE_ENV=production before running the start script. ```bash bun start ``` ```bash NODE_ENV=production bun src/index.tsx ``` -------------------------------- ### Run Go Bridge Server from Source Source: https://github.com/laplace-live/event-bridge/blob/master/README.md Use this command to run the Go implementation of the bridge server directly from source. Requires Go to be installed. ```bash go run ./packages/server --debug ``` -------------------------------- ### Configure Network Interface via Command Line Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Starts the server listening on all network interfaces (0.0.0.0) using the --host command-line argument. By default, the server listens on localhost. ```bash bun run start --host 0.0.0.0 ``` -------------------------------- ### Run TUI Demo with Default Settings Source: https://github.com/laplace-live/event-bridge/blob/master/examples/tui-demo/README.md Starts the LAPLACE Event Bridge TUI Demo using default configuration. This is the basic command to launch the application. ```bash bun run dev ``` -------------------------------- ### Start LAPLACE Event Bridge Go Server Source: https://context7.com/laplace-live/event-bridge/llms.txt Run the Go server from source or build a native binary. Supports CLI flags for configuration like host, port, and authentication token. ```bash go run ./packages/server --debug ``` ```bash cd packages/server go build -o leb-server . ./leb-server --host 0.0.0.0 --port 9696 --auth "my-secret-token" --debug ``` ```bash export LEB_AUTH="my-secret-token" export DEBUG=1 export HOST=0.0.0.0 ./leb-server ``` ```bash ./scripts/build ``` -------------------------------- ### Install LAPLACE Event Bridge SDK Source: https://context7.com/laplace-live/event-bridge/llms.txt Install the TypeScript SDK using npm, yarn, or bun. This SDK provides a client library for Node.js, Bun, and browser environments. ```bash npm install @laplace.live/event-bridge-sdk # or yarn add @laplace.live/event-bridge-sdk # or bun add @laplace.live/event-bridge-sdk ``` -------------------------------- ### Run Go Event Bridge Server Source: https://github.com/laplace-live/event-bridge/blob/master/CLAUDE.md Start the recommended Go implementation of the event bridge server. Use command-line flags for authentication, host binding, and debug mode. ```bash go run ./packages/server --auth "token" --host 0.0.0.0 --debug ``` -------------------------------- ### Running Bun Server Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/CLAUDE.md Command to start the Bun server with hot-reloading enabled. Use `--hot` for development to automatically restart the server on file changes. ```sh bun --hot ./index.ts ``` -------------------------------- ### Enable Debug Mode via Command Line Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Starts the server with debug mode enabled using the --debug command-line flag, providing detailed logging. ```bash bun run start --debug ``` -------------------------------- ### Bun Test Example Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/CLAUDE.md A basic test case using Bun's built-in testing framework. Ensure tests are in files ending with `.test.ts` or `.test.js`. ```typescript import { test, expect } from "bun:test"; test("hello world", () => { expect(1).toBe(1); }); ``` -------------------------------- ### React Frontend Component Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/CLAUDE.md A React component example that imports CSS directly. Bun's bundler handles CSS processing. This script is intended to be imported into an HTML file. ```tsx import React from "react"; // import .css files directly and it works import './index.css'; import { createRoot } from "react-dom/client"; const root = createRoot(document.body); export default function Frontend() { return

Hello, world!

; } root.render(); ``` -------------------------------- ### Display Help for TUI Demo CLI Options Source: https://github.com/laplace-live/event-bridge/blob/master/examples/tui-demo/README.md Shows all available command-line arguments and their descriptions for the TUI Demo. Useful for understanding configuration options. ```bash bun run dev -- --help ``` -------------------------------- ### Build Go Server Source: https://github.com/laplace-live/event-bridge/blob/master/CLAUDE.md Compile the Go server implementation into a standalone binary. ```bash cd packages/server && go build ``` -------------------------------- ### Build Application for Deployment with Bun Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/README.md Builds the application for deployment. Supports options like output directory, minification, and sourcemaps. ```bash bun run build ``` -------------------------------- ### Build and Run Go Bridge Server Binary Source: https://github.com/laplace-live/event-bridge/blob/master/README.md Builds a native binary for the Go bridge server and then runs it. You can specify host and authentication token. ```bash cd packages/server go build -o leb-server . ./leb-server --host 0.0.0.0 --auth "your-secure-token" ``` -------------------------------- ### Get Client ID with client.getClientId() Source: https://context7.com/laplace-live/event-bridge/llms.txt Retrieves the unique client ID assigned by the bridge server after a successful connection. Returns null if not connected. The ID resets on disconnect. ```typescript await client.connect() const id = client.getClientId() console.log('My client ID:', id) // "client-1" ``` -------------------------------- ### Run and Build LAPLACE Event Bridge Server Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server/README.md Navigate to the server-go package directory and run the server in development mode with debug enabled, or compile a native binary for your platform and run it with custom authentication and host settings. ```bash cd packages/server-go go run . --debug go build -o leb-go ./leb-go --auth "my-secret" --host 0.0.0.0 ``` -------------------------------- ### Cross-platform Build Script Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server/README.md Execute the provided build script from the packages/server-go directory to generate cross-platform binaries. The resulting binaries are statically linked and have no runtime dependencies beyond the standard C library on Windows. ```bash # From packages/server-go ./scripts/build ``` -------------------------------- ### HTML Import for Frontend Development Source: https://github.com/laplace-live/event-bridge/blob/master/examples/react-demo/CLAUDE.md Demonstrates how an HTML file can import frontend scripts and stylesheets. Bun automatically transpiles and bundles these assets. ```html

Hello, world!

``` -------------------------------- ### Build and Publish SDK Source: https://github.com/laplace-live/event-bridge/blob/master/CLAUDE.md Commands for building the TypeScript SDK and publishing it to a package registry. Requires npm access for publishing. ```bash # Build SDK bun run build:sdk # Publish SDK (requires npm access) bun run publish:sdk ``` -------------------------------- ### Create a Changeset for SDK Release Source: https://github.com/laplace-live/event-bridge/blob/master/README.md Use the Changesets CLI to document SDK changes and manage versioning. This process involves selecting the package, choosing a version bump, and writing a description for the changes. ```bash bunx @changesets/cli ``` -------------------------------- ### Run TUI Demo with Custom WebSocket URL Source: https://github.com/laplace-live/event-bridge/blob/master/examples/tui-demo/README.md Launches the TUI Demo and connects to a specific Event Bridge WebSocket server. Replace the URL with your desired endpoint. ```bash bun run dev -- --url "wss://event-fetcher.laplace.cn/?token=laplace" ``` -------------------------------- ### Run CLI Demo with Bun Source: https://github.com/laplace-live/event-bridge/blob/master/examples/cli-demo/README.md Executes the LAPLACE Event Bridge CLI demo using Bun. This command can be run from the project root. ```bash bun run --cwd examples/cli-demo start ``` -------------------------------- ### React Integration Pattern Source: https://context7.com/laplace-live/event-bridge/llms.txt Demonstrates how to integrate the Event Bridge SDK into a React application using a singleton client and a Zustand store for state management. ```APIDOC ## React Integration Pattern ### Using the SDK in a React application The SDK works in any framework. The pattern below initializes a singleton client, connects it on module load, and integrates with a Zustand store to drive UI updates. ```typescript // lib/chat.ts — singleton client with Zustand store integration import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' import { useChatStore } from '../store/chatStore' export function initializeEventBridge() { const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', token: 'my-token', reconnect: true, }) const { addMessage } = useChatStore.getState() client.connect().catch(err => console.error('Connection failed:', err)) client.onAny(event => addMessage(event)) client.onConnectionStateChange(state => { console.log('Connection state:', state) }) return client } export const eventBridgeClient = initializeEventBridge() // store/chatStore.ts — Zustand store keeping last 50 events import type { LaplaceEvent } from '@laplace.live/event-types' import { create } from 'zustand' interface ChatState { messages: LaplaceEvent[] addMessage: (message: LaplaceEvent) => void clearMessages: () => void } export const useChatStore = create(set => ({ messages: [], addMessage: msg => set(state => ({ messages: [...state.messages, msg].slice(-50) })), clearMessages: () => set({ messages: [] }), })) // App.tsx — disconnect on unmount import { useEffect } from 'react' import { eventBridgeClient } from './lib/chat' export function App() { useEffect(() => { return () => { eventBridgeClient.disconnect() } }, []) const { messages } = useChatStore() return ( ) } ``` ``` -------------------------------- ### Initialize WebSocket Client and UI Elements Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/client-demo.html Initializes global variables for the WebSocket connection and references UI elements. This code should be run when the page loads. ```javascript let socket = null // UI elements const connectBtn = document.getElementById('connectBtn') const disconnectBtn = document.getElementById('disconnectBtn') const sendMessageBtn = document.getElementById('sendMessageBtn') const messageInput = document.getElementById('messageInput') const messagesContainer = document.getElementById('messages') const statusIndicator = document.getElementById('statusIndicator') // Connection settings const serverHost = document.getElementById('serverHost') const serverPort = document.getElementById('serverPort') const authToken = document.getElementById('authToken') ``` -------------------------------- ### Connect to WebSocket Server Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/client-demo.html Establishes a WebSocket connection to the server using provided host, port, and optional authentication token. Handles connection opening, message reception, closure, and errors. ```javascript function connect() { // Close any existing connection if (socket) { socket.close() } // Get connection settings const host = serverHost.value || 'localhost' const port = serverPort.value || '9696' const token = authToken.value // Create connection URL const wsUrl = `ws://${host}:${port} ` // Setup protocol for authentication if token is provided const protocols = token ? `['client', token]` : undefined // Create new WebSocket connection with authentication socket = new WebSocket(wsUrl, protocols) addMessage( `Connecting to ${wsUrl}${token ? ' with authentication' : ''}` , 'system') // Connection opened socket.addEventListener('open', event => { updateStatus('Connected', 'green') addMessage('Connected to WebSocket server', 'system') toggleButtons(true) }) // Listen for messages socket.addEventListener('message', event => { try { const message = JSON.parse(event.data) addMessage(JSON.stringify(message, null, 2), 'received') } catch (e) { addMessage(event.data, 'received') } }) // Connection closed socket.addEventListener('close', event => { updateStatus('Disconnected', 'red') addMessage('Disconnected from WebSocket server', 'system') toggleButtons(false) }) // Connection error socket.addEventListener('error', event => { updateStatus('Error', 'red') addMessage('WebSocket connection error', 'error') toggleButtons(false) }) } ``` -------------------------------- ### CLI Integration Pattern Source: https://context7.com/laplace-live/event-bridge/llms.txt Illustrates how to use the Event Bridge SDK as a command-line subscriber to listen for and process chat events. ```APIDOC ## CLI Integration Pattern ### Using the SDK as a command-line subscriber ```typescript #!/usr/bin/env bun // examples/cli-demo pattern — connect and print chat events to stdout import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' const client = new LaplaceEventBridgeClient({ url: process.env.BRIDGE_URL ?? 'ws://localhost:9696', token: process.env.BRIDGE_TOKEN, reconnect: true, reconnectInterval: 3000, maxReconnectAttempts: 10, }) client.on('message', event => { const ts = new Date(event.timestamp).toLocaleTimeString() console.log(`[${ts}] [room:${event.origin}] ${event.username}: ${event.message}`) }) client.onConnectionStateChange(state => { console.error(`[bridge] ${state}`) }) process.on('SIGINT', () => { client.disconnect() process.exit(0) }) try { await client.connect() console.log('Listening. Press Ctrl+C to exit.') } catch (err) { console.error('Failed to connect:', err) process.exit(1) } ``` ``` -------------------------------- ### Connect to Event Bridge with SDK Source: https://github.com/laplace-live/event-bridge/blob/master/README.md Instantiate the client and connect to the event bridge. Ensure the URL and token (if authentication is enabled) are correctly provided. The client can then listen for specific or all events. ```typescript import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', token: 'your-auth-token', // If auth is enabled }) // Connect to the bridge await client.connect() // Listen for specific events client.on('message', event => { console.log('Received message:', event) }) // Listen for all events client.onAny(event => { console.log('Received event:', event.type) }) ``` -------------------------------- ### Initialize LaplaceEventBridgeClient Source: https://context7.com/laplace-live/event-bridge/llms.txt Create a new client instance with optional configuration for WebSocket URL, authentication token, and reconnection settings. Connection is not automatic; call connect() separately. ```typescript import { LaplaceEventBridgeClient, ConnectionState } from '@laplace.live/event-bridge-sdk' const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', // default: 'ws://localhost:9696' token: 'my-secret-token', // optional; sent as subprotocol and query param reconnect: true, // default: true — auto-reconnect on disconnect reconnectInterval: 3000, // default: 3000ms base interval (exponential backoff) maxReconnectAttempts: 1000, // default: 1000 pingTimeout: 90000, // default: 90000ms — dead-connection detection (server >= 4.0.3) }) // Exponential backoff schedule with base 3000ms: // Attempt 1: 3000ms | Attempt 2: 4500ms | Attempt 3: 6750ms | ... capped at 60s ``` -------------------------------- ### Configure Authentication via Environment Variable Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Sets the authentication token using the LEB_AUTH environment variable. This token is required for all connections when enabled. ```bash export LEB_AUTH="your-secure-token" ``` -------------------------------- ### Configure Network Interface via Environment Variable Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Sets the network interface for the server to listen on using the HOST environment variable. 'localhost' or '127.0.0.1' restricts connections to the local machine. ```bash export HOST="localhost" ``` -------------------------------- ### Connect and Subscribe to Events Source: https://github.com/laplace-live/event-bridge/blob/master/CLAUDE.md Establishes a connection to the Event Bridge and sets up listeners for specific events, any event, and connection state changes. ```typescript const client = new LaplaceEventBridgeClient(options) await client.connect() client.on('message', event => { // Handle specific event type }) client.onAny(event => { // Handle all events }) client.onConnectionStateChange(state => { // Handle connection states }) ``` -------------------------------- ### Initialize Event Bridge Client SDK Source: https://github.com/laplace-live/event-bridge/blob/master/CLAUDE.md Instantiate the TypeScript client for connecting to the event bridge. Configure the WebSocket URL, authentication token, and reconnection behavior. ```typescript import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', token: 'auth-token', // Optional authentication reconnect: true, // Auto-reconnect support }) ``` -------------------------------- ### React Integration: Initialize Event Bridge Client Source: https://context7.com/laplace-live/event-bridge/llms.txt Initializes a singleton Event Bridge client, connects it on module load, and integrates with a Zustand store for UI updates. Handles connection and message events. ```typescript // lib/chat.ts — singleton client with Zustand store integration import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' import { useChatStore } from '../store/chatStore' export function initializeEventBridge() { const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', token: 'my-token', reconnect: true, }) const { addMessage } = useChatStore.getState() client.connect().catch(err => console.error('Connection failed:', err)) client.onAny(event => addMessage(event)) client.onConnectionStateChange(state => { console.log('Connection state:', state) }) return client } export const eventBridgeClient = initializeEventBridge() ``` ```typescript // store/chatStore.ts — Zustand store keeping last 50 events import type { LaplaceEvent } from '@laplace.live/event-types' import { create } from 'zustand' interface ChatState { messages: LaplaceEvent[] addMessage: (message: LaplaceEvent) => void clearMessages: () => void } export const useChatStore = create(set => ({ messages: [], addMessage: msg => set(state => ({ messages: [...state.messages, msg].slice(-50) })), clearMessages: () => set({ messages: [] }), })) ``` ```typescript // App.tsx — disconnect on unmount import { useEffect } from 'react' import { eventBridgeClient } from './lib/chat' export function App() { useEffect(() => { return () => { eventBridgeClient.disconnect() } }, []) const { messages } = useChatStore() return (
    {messages.map(event => event.type === 'message' ? (
  • {event.username}: {event.message}
  • ) : null )}
) } ``` -------------------------------- ### LaplaceEventBridgeClient Constructor Source: https://context7.com/laplace-live/event-bridge/llms.txt Initializes a new client instance for the LAPLACE Event Bridge SDK. Does not connect automatically. ```APIDOC ## `new LaplaceEventBridgeClient(options)` Creates a new client instance for the LAPLACE Event Bridge SDK. ### Parameters - **`options`** (object) - Optional configuration object. - **`url`** (string) - The WebSocket server URL. Defaults to `'ws://localhost:9696'`. - **`token`** (string) - Optional authentication token. Sent as subprotocol and query parameter. - **`reconnect`** (boolean) - Whether to automatically reconnect on disconnect. Defaults to `true`. - **`reconnectInterval`** (number) - The base interval in milliseconds for exponential backoff reconnection. Defaults to `3000`. - **`maxReconnectAttempts`** (number) - The maximum number of reconnection attempts. Defaults to `1000`. - **`pingTimeout`** (number) - Timeout in milliseconds for dead-connection detection (requires server version >= 4.0.3). Defaults to `90000`. ### Usage Example ```typescript import { LaplaceEventBridgeClient, ConnectionState } from '@laplace.live/event-bridge-sdk' const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', token: 'my-secret-token', reconnect: true, reconnectInterval: 3000, maxReconnectAttempts: 1000, pingTimeout: 90000, }) // Note: Call client.connect() to establish the WebSocket connection. // The reconnect schedule uses exponential backoff, e.g.: // Attempt 1: 3000ms | Attempt 2: 4500ms | Attempt 3: 6750ms | ... (capped at 60s) ``` ``` -------------------------------- ### LAPLACE Event Bridge Server CLI Flags Source: https://context7.com/laplace-live/event-bridge/llms.txt Reference for server CLI flags, their environment variable equivalents, and default values. Used for configuring server behavior. ```bash | Flag | Env var(s) | Default | |---|---|---| | `--debug` | `DEBUG=1` or `DEBUG=true` | disabled | | `--auth ` | `LEB_AUTH` or `LAPLACE_EVENT_BRIDGE_AUTH` | none | | `--host ` | `HOST` | `localhost` | | `--port ` | — | `9696` | ``` -------------------------------- ### Commit SDK Changes with Changeset Source: https://github.com/laplace-live/event-bridge/blob/master/README.md After creating a changeset, commit the changes along with the generated changeset file. This ensures that the release process is properly documented. ```bash git add . git commit -m "feat(sdk): your change description" ``` -------------------------------- ### CLI Integration: Connect and Print Chat Events Source: https://context7.com/laplace-live/event-bridge/llms.txt A command-line tool that connects to the Event Bridge, listens for 'message' events, and prints them to stdout with timestamps. Includes reconnection logic and graceful shutdown. ```typescript #!/usr/bin/env bun // examples/cli-demo pattern — connect and print chat events to stdout import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' const client = new LaplaceEventBridgeClient({ url: process.env.BRIDGE_URL ?? 'ws://localhost:9696', token: process.env.BRIDGE_TOKEN, reconnect: true, reconnectInterval: 3000, maxReconnectAttempts: 10, }) client.on('message', event => { const ts = new Date(event.timestamp).toLocaleTimeString() console.log(`[${ts}] [room:${event.origin}] ${event.username}: ${event.message}`) }) client.onConnectionStateChange(state => { console.error(`[bridge] ${state}`) }) process.on('SIGINT', () => { client.disconnect() process.exit(0) }) try { await client.connect() console.log('Listening. Press Ctrl+C to exit.') } catch (err) { console.error('Failed to connect:', err) process.exit(1) } ``` -------------------------------- ### LaplaceEventBridgeClient Methods Source: https://github.com/laplace-live/event-bridge/blob/master/packages/sdk/README.md This section details the core methods available on the LaplaceEventBridgeClient for interacting with the Event Bridge. ```APIDOC ## connect() ### Description Connect to the event bridge. Returns a Promise that resolves when connected. ### Method `connect()` ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```typescript await client.connect() ``` ### Response #### Success Response Resolves a Promise when the connection is established. #### Response Example N/A ``` ```APIDOC ## disconnect() ### Description Disconnect from the event bridge. ### Method `disconnect()` ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```typescript client.disconnect() ``` ### Response None ``` ```APIDOC ## on(eventType, handler) ### Description Register an event handler for a specific event type with automatic type inference. Returns an unsubscribe function. ### Method `on(eventType: string, handler: Function)` ### Endpoint N/A (SDK method) ### Parameters - **eventType** (string) - Required - The type of event to listen for. - **handler** (Function) - Required - The callback function to execute when the event is received. ### Request Example ```typescript client.on('message', event => { console.log(`${event.username}: ${event.message}`) }) ``` ### Response - **Function**: Returns a function that can be called to unsubscribe the handler. ``` ```APIDOC ## onAny(handler) ### Description Register a handler for all events. Returns an unsubscribe function. ### Method `onAny(handler: Function)` ### Endpoint N/A (SDK method) ### Parameters - **handler** (Function) - Required - The callback function to execute for any received event. ### Request Example ```typescript client.onAny(event => { console.log(`Received event of type: ${event.type}`) }) ``` ### Response - **Function**: Returns a function that can be called to unsubscribe the handler. ``` ```APIDOC ## onConnectionStateChange(handler) ### Description Register a handler for connection state changes. Returns an unsubscribe function. ### Method `onConnectionStateChange(handler: Function)` ### Endpoint N/A (SDK method) ### Parameters - **handler** (Function) - Required - The callback function to execute when the connection state changes. ### Request Example ```typescript client.onConnectionStateChange(state => { console.log(`Connection state changed to: ${state}`) }) ``` ### Response - **Function**: Returns a function that can be called to unsubscribe the handler. ``` ```APIDOC ## off(eventType, handler) ### Description Remove an event handler for a specific event type. ### Method `off(eventType: string, handler: Function)` ### Endpoint N/A (SDK method) ### Parameters - **eventType** (string) - Required - The type of event the handler was registered for. - **handler** (Function) - Required - The specific handler function to remove. ### Request Example ```typescript client.off('message', myMessageHandler) ``` ### Response None ``` ```APIDOC ## offAny(handler) ### Description Remove a handler for all events. ### Method `offAny(handler: Function)` ### Endpoint N/A (SDK method) ### Parameters - **handler** (Function) - Required - The specific handler function to remove. ### Request Example ```typescript client.offAny(myAnyHandler) ``` ### Response None ``` ```APIDOC ## offConnectionStateChange(handler) ### Description Remove a connection state change handler. ### Method `offConnectionStateChange(handler: Function)` ### Endpoint N/A (SDK method) ### Parameters - **handler** (Function) - Required - The specific handler function to remove. ### Request Example ```typescript client.offConnectionStateChange(myStateChangeHandler) ``` ### Response None ``` ```APIDOC ## isConnectedToBridge() ### Description Check if the client is connected to the bridge. (Deprecated: use `getConnectionState()` instead) ### Method `isConnectedToBridge()` ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```typescript if (client.isConnectedToBridge()) { console.log('Currently connected.') } ``` ### Response - **boolean**: `true` if connected, `false` otherwise. ``` ```APIDOC ## getConnectionState() ### Description Get the current connection state. ### Method `getConnectionState()` ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```typescript const state = client.getConnectionState() console.log(`Current state: ${state}`) ``` ### Response - **ConnectionState**: The current state of the connection (e.g., 'connected', 'disconnected'). ``` ```APIDOC ## getClientId() ### Description Get the client ID assigned by the bridge. ### Method `getClientId()` ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```typescript const clientId = client.getClientId() console.log(`Client ID: ${clientId}`) ``` ### Response - **string**: The unique client ID. ``` ```APIDOC ## send(event) ### Description Send an event to the bridge. ### Method `send(event: object)` ### Endpoint N/A (SDK method) ### Parameters - **event** (object) - Required - The event object to send. ### Request Example ```typescript client.send({ type: 'message', username: 'User', message: 'Hello, Event Bridge!' }) ``` ### Response None ``` -------------------------------- ### Connection Options Interface Source: https://github.com/laplace-live/event-bridge/blob/master/packages/sdk/README.md Defines the configuration options for establishing a connection to the Event Bridge. ```typescript interface ConnectionOptions { url?: string // WebSocket URL, default: 'ws://localhost:9696' token?: string // Authentication token, default: '' reconnect?: boolean // Auto reconnect on disconnect, default: true reconnectInterval?: number // Milliseconds between reconnect attempts, default: 3000 maxReconnectAttempts?: number // Maximum reconnect attempts, default: 1000 } ``` -------------------------------- ### ConnectionOptions Interface Source: https://context7.com/laplace-live/event-bridge/llms.txt Defines the available options for establishing a connection to the Event Bridge. Includes settings for URL, authentication, and reconnection behavior. ```typescript interface ConnectionOptions { /** WebSocket URL. Default: 'ws://localhost:9696' */ url?: string /** Authentication token. Sent as second WebSocket subprotocol and ?token= query param. */ token?: string /** Auto-reconnect on disconnect. Default: true */ reconnect?: boolean /** * Base reconnect interval in milliseconds. Uses exponential backoff capped at 60s. * Default: 3000 * * Example schedule (base=3000, multiplier=1.5x): * Attempt 1: 3000ms * Attempt 2: 4500ms * Attempt 3: 6750ms * Attempt 4: 10125ms * ... * Attempt 8: 51258ms * Attempt 9+: 60000ms (capped) */ reconnectInterval?: number /** Maximum number of reconnect attempts before giving up. Default: 1000 */ maxReconnectAttempts?: number /** * Ping timeout in milliseconds. If no ping is received within this window, * the connection is considered dead and closed (triggering reconnect). * Only active for server versions >= 4.0.3. * Default: 90000 (90 seconds) */ pingTimeout?: number } ``` -------------------------------- ### Basic Usage of LaplaceEventBridgeClient Source: https://github.com/laplace-live/event-bridge/blob/master/packages/sdk/README.md Connect to the bridge, listen for messages and system events, and handle connection state changes. Disconnect when done. ```typescript import { LaplaceEventBridgeClient } from '@laplace.live/event-bridge-sdk' // Create a new client const client = new LaplaceEventBridgeClient({ url: 'ws://localhost:9696', token: 'your-auth-token', // Optional reconnect: true, }) // Connect to the bridge await client.connect() client.on('message', event => { console.log(`${event.username}: ${event.message}`) }) client.on('system', event => { console.log(`System: ${event.message}`) }) // Listen for any event client.onAny(event => { console.log(`Received event of type: ${event.type}`) }) // Monitor connection state changes client.onConnectionStateChange(state => { console.log(`Connection state changed to: ${state}`) // Handle different connection states switch (state) { case 'connected': console.log('Connected to the server!') break case 'reconnecting': console.log('Attempting to reconnect...') break case 'disconnected': console.log('Disconnected from the server') break case 'connecting': console.log('Establishing connection...') break } }) // Disconnect when done client.disconnect() ``` -------------------------------- ### Enable Debug Mode via Environment Variable Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Enables detailed debug logging by setting the DEBUG environment variable to 1. ```bash export DEBUG=1 ``` -------------------------------- ### client.connect() Source: https://context7.com/laplace-live/event-bridge/llms.txt Opens the WebSocket connection to the Event Bridge. This method returns a Promise that resolves when the connection is successfully established or rejects if an error occurs. It also handles automatic reconnection based on configured options. ```APIDOC ## client.connect() ### Description Opens the WebSocket connection. Returns a `Promise` that resolves when the connection is established (`onopen`) or rejects on error. Automatically handles reconnection according to the configured options. ### Method ```typescript client.connect() ``` ### Request Example ```typescript try { await client.connect() console.log('Connected! Client ID:', client.getClientId()) } catch (err) { console.error('Connection failed:', err) } ``` ### Response - **Promise** - Resolves on successful connection, rejects on error. ``` -------------------------------- ### Store Integration for Events Source: https://github.com/laplace-live/event-bridge/blob/master/CLAUDE.md Adds incoming events to a store, such as Zustand or Pinia, for centralized state management. This pattern is commonly used for managing event data. ```typescript client.onAny(event => { store.addMessage(event) }) ``` -------------------------------- ### Check Connection State with client.getConnectionState() Source: https://context7.com/laplace-live/event-bridge/llms.txt Checks the current connection state before sending an event. Prefer this over deprecated methods. Requires importing ConnectionState. ```typescript import { ConnectionState } from '@laplace.live/event-bridge-sdk' if (client.getConnectionState() === ConnectionState.CONNECTED) { client.send(myEvent) } else { console.log('Not connected, state:', client.getConnectionState()) } ``` -------------------------------- ### Connect to Event Bridge Source: https://context7.com/laplace-live/event-bridge/llms.txt Opens the WebSocket connection. Automatically handles reconnection. Call this to establish a connection to the Event Bridge. ```typescript try { await client.connect() console.log('Connected! Client ID:', client.getClientId()) // Output: "Welcome to LAPLACE Event Bridge v4.1.0: ws://localhost:9696 with client ID client-1" } catch (err) { console.error('Connection failed:', err) // client will attempt reconnection automatically if reconnect: true } ``` -------------------------------- ### ConnectionOptions Interface Source: https://context7.com/laplace-live/event-bridge/llms.txt Defines the available options for configuring the Event Bridge client connection, such as WebSocket URL, authentication token, and reconnection behavior. ```APIDOC ## `ConnectionOptions` interface Full reference for all constructor options: ```typescript interface ConnectionOptions { /** WebSocket URL. Default: 'ws://localhost:9696' */ url?: string /** Authentication token. Sent as second WebSocket subprotocol and ?token= query param. */ token?: string /** Auto-reconnect on disconnect. Default: true */ reconnect?: boolean /** * Base reconnect interval in milliseconds. Uses exponential backoff capped at 60s. * Default: 3000 * * Example schedule (base=3000, multiplier=1.5x): * Attempt 1: 3000ms * Attempt 2: 4500ms * Attempt 3: 6750ms * Attempt 4: 10125ms * ... * Attempt 8: 51258ms * Attempt 9+: 60000ms (capped) */ reconnectInterval?: number /** Maximum number of reconnect attempts before giving up. Default: 1000 */ maxReconnectAttempts?: number /** * Ping timeout in milliseconds. If no ping is received within this window, * the connection is considered dead and closed (triggering reconnect). * Only active for server versions >= 4.0.3. * Default: 90000 (90 seconds) */ pingTimeout?: number } ``` ``` -------------------------------- ### client.onConnectionStateChange(handler) Source: https://context7.com/laplace-live/event-bridge/llms.txt Registers a handler that is invoked whenever the client's connection state changes. The handler is called immediately with the current state upon registration. It returns a function to unsubscribe the handler. ```APIDOC ## client.onConnectionStateChange(handler) ### Description Registers a handler that fires whenever the connection state changes. Called **immediately** with the current state upon registration. Returns an unsubscribe function. ### Method ```typescript client.onConnectionStateChange(handler: function) ``` ### Parameters #### Path Parameters - **handler** (function) - Required - The callback function to execute when the connection state changes. Receives the current state as an argument. ### Request Example ```typescript const ConnectionState = { DISCONNECTED: 'disconnected', CONNECTING: 'connecting', CONNECTED: 'connected', RECONNECTING: 'reconnecting', } const unsubState = client.onConnectionStateChange(state => { switch (state) { case 'connected': console.log('✅ Connected, client ID:', client.getClientId()) break case 'connecting': console.log('⏳ Connecting...') break case 'reconnecting': console.log('🔄 Reconnecting...') break case 'disconnected': console.log('❌ Disconnected') break } }) // Unsubscribe unsubState() ``` ### Response - **function** - An unsubscribe function to remove the event listener. ``` -------------------------------- ### Client Authentication Protocol Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/README.md Specifies the WebSocket protocol format for clients when authentication is enabled. The auth token must be included. ```plaintext ['laplace-event-bridge-role-client', 'your-auth-token'] ``` -------------------------------- ### Toggle Button States Source: https://github.com/laplace-live/event-bridge/blob/master/packages/server-bun/client-demo.html Enables or disables the connect, disconnect, and send message buttons based on the connection status. ```javascript function toggleButtons(connected) { connectBtn.disabled = connected disconnectBtn.disabled = !connected sendMessageBtn.disabled = !connected } ``` -------------------------------- ### client.onAny(handler) Source: https://context7.com/laplace-live/event-bridge/llms.txt Registers a handler that will be called for every event, regardless of its type. This is useful for logging or routing all incoming events. It returns a function to unsubscribe the handler. ```APIDOC ## client.onAny(handler) ### Description Registers a handler that receives **every** event regardless of type. Returns an unsubscribe function. Useful for logging, forwarding to a database, or fan-out routing. ### Method ```typescript client.onAny(handler: function) ``` ### Parameters #### Path Parameters - **handler** (function) - Required - The callback function to execute for all events. ### Request Example ```typescript const unsubAny = client.onAny(event => { console.log('Event type:', event.type, '| Origin:', event.origin) // Forward every event to an external store store.dispatch({ type: 'LAPLACE_EVENT', payload: event }) }) // Unsubscribe unsubAny() ``` ### Response - **function** - An unsubscribe function to remove the event listener. ``` -------------------------------- ### Send System Message with client.send() Source: https://context7.com/laplace-live/event-bridge/llms.txt Sends a system message to the bridge. Ensure the socket is open before sending to avoid errors. This is typically used by server-role connections. ```typescript import type { LaplaceEvent } from '@laplace.live/event-types' function sendSystemMessage(text: string) { const event: LaplaceEvent = { type: 'system', id: `system-${Date.now()}`, message: text, timestamp: Date.now(), timestampNormalized: Date.now(), origin: 0, originIdx: 0, uid: 0, username: 'my-app', read: false, } try { client.send(event) } catch (err) { console.error('Not connected:', err) } } setTimeout(() => sendSystemMessage('Hello from my integration!'), 3000) ``` -------------------------------- ### Register Connection State Change Handler Source: https://context7.com/laplace-live/event-bridge/llms.txt Registers a handler that fires when the connection state changes. Called immediately with the current state upon registration. Returns an unsubscribe function. ```typescript const ConnectionState = { DISCONNECTED: 'disconnected', CONNECTING: 'connecting', CONNECTED: 'connected', RECONNECTING: 'reconnecting', } const unsubState = client.onConnectionStateChange(state => { switch (state) { case 'connected': console.log('✅ Connected, client ID:', client.getClientId()) break case 'connecting': console.log('⏳ Connecting...') break case 'reconnecting': console.log('🔄 Reconnecting...') break case 'disconnected': console.log('❌ Disconnected') break } }) ``` -------------------------------- ### Type Inference for Event Handlers Source: https://github.com/laplace-live/event-bridge/blob/master/packages/sdk/README.md Demonstrates automatic type inference for 'message' and 'gift' events, allowing direct access to event properties. ```typescript // This will infer that 'event' is of type 'Message' client.on('message', event => { // TypeScript knows these properties exist console.log(event.username) console.log(event.message) }) // This will infer that 'event' is of type 'Gift' client.on('gift', event => { // TypeScript knows these properties exist console.log(event.giftName) console.log(event.giftCount) }) ``` -------------------------------- ### Register Handler for All Events Source: https://context7.com/laplace-live/event-bridge/llms.txt Registers a handler that receives every event, regardless of type. Useful for logging or fan-out routing. Returns an unsubscribe function. ```typescript const unsubAny = client.onAny(event => { // event.type discriminates the union — use a switch for type-safe handling console.log('Event type:', event.type, '| Origin:', event.origin) // Forward every event to an external store store.dispatch({ type: 'LAPLACE_EVENT', payload: event }) }) ``` -------------------------------- ### Server WebSocket Protocol Source: https://context7.com/laplace-live/event-bridge/llms.txt Defines the WebSocket roles, authentication methods, and message formats for the LAPLACE Event Bridge server. ```APIDOC ## Server WebSocket Protocol ### Role Identification Use the `Sec-WebSocket-Protocol` header to identify roles: - `laplace-event-bridge-role-server`: Publisher (LAPLACE Chat) - `laplace-event-bridge-role-client`: Subscriber (your application) ### Authentication Token authentication can be passed as a second subprotocol value or as a `?token=` query parameter. Example: `ws://localhost:9696?token=my-secret-token` ### Connection Establishment Upon connection, the server sends a `established` message: ```json { "type": "established", "clientId": "client-1", "isServer": false, "message": "Connected to LAPLACE Event Bridge: ws://localhost:9696" } ``` ### Event Broadcasting (Server Role) Server-role broadcasts are sent to all clients and include a `source` field. Example: `message` event: ```json { "type": "message", "username": "SomeUser", "message": "Hello!", "source": "server-1", ... } ``` ### Server Broadcast Confirmation After a successful broadcast, the server-role receives confirmation: ```json { "type": "broadcast-success", "clientCount": 3, "timestamp": 1712345678000 } ``` ### Client Message Handling If a client sends a message (not relayed), it receives: ```json { "type": "client-message-received", "message": "Message received (client-to-server messages are not relayed)", "timestamp": 1712345678000 } ``` ### Ping/Pong Heartbeat (Server >= 4.0.3) - Server sends: `{ "type": "ping", "timestamp": 1712345678000 }` - Client must reply: `{ "type": "pong", "timestamp": 1712345678000, "respondingTo": 1712345678000 }` ```