### Start Svelte Development Server with npm Source: https://github.com/bewinxed/river.ts/blob/main/examples/svelte/README.md Starts the local development server for a Svelte project. After installing dependencies, use `npm run dev` to run the app. An additional flag `--open` can automatically launch the app in a new browser tab. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Install river.ts package Source: https://github.com/bewinxed/river.ts/blob/main/README.md Instructions for installing the river.ts library using common Node.js package managers like npm, yarn, pnpm, and bun. ```bash npm install river.ts # or yarn add river.ts # or pnpm add river.ts # or bun add river.ts ``` -------------------------------- ### CSS Styling for Event Stream Display Source: https://github.com/bewinxed/river.ts/blob/main/tests/test.html Defines basic CSS rules for the page body and a container element with the ID 'events', used to display incoming Server-Sent Events. It sets font styles, margins, and padding. ```css body { font-family: Arial, sans-serif; margin: 20px; padding: 0; } #events { margin-top: 20px; } ``` -------------------------------- ### JavaScript Client for Server-Sent Events (SSE) Consumption Source: https://github.com/bewinxed/river.ts/blob/main/tests/test.html Initializes an EventSource connection to a specified endpoint to receive real-time updates. It includes event listeners for 'message' to process and display incoming data, and 'error' to log issues and close the connection gracefully. ```javascript const eventSource = new EventSource("http://localhost:3000/events"); eventSource.onmessage = function(event) { console.log("New event received:", event.data); const messageElement = document.createElement("div"); messageElement.textContent = event.data; document.getElementById("events").appendChild(messageElement); }; eventSource.onerror = function(error) { console.error("EventSource failed:", error); eventSource.close(); }; ``` -------------------------------- ### Create Svelte Project using npm create svelte Source: https://github.com/bewinxed/river.ts/blob/main/examples/svelte/README.md Initializes a new Svelte project using `npm create svelte@latest`. This command allows creating a project in the current directory or a specified new directory, setting up the basic project structure. ```bash # create a new project in the current directory npm create svelte@latest # create a new project in my-app npm create svelte@latest my-app ``` -------------------------------- ### Build Svelte Project for Production Source: https://github.com/bewinxed/river.ts/blob/main/examples/svelte/README.md Generates a production-ready version of the Svelte application. This command compiles and optimizes the project for deployment. The resulting build can be previewed locally using `npm run preview`. ```bash npm run build ``` -------------------------------- ### Set up client-side SSE with RiverClient Source: https://github.com/bewinxed/river.ts/blob/main/README.md Demonstrates how to initialize `RiverClient` on the client to connect to an SSE endpoint. This snippet shows how to prepare the connection with custom headers, listen for specific events like 'ping' and 'payload' (handling chunks), and manually close the connection. ```typescript import { RiverClient } from 'river.ts/client'; import { events } from './events'; const client = RiverClient.init(events, { reconnect: true // Optional: enable automatic reconnection }); client .prepare('http://localhost:3000/events', { method: 'GET', headers: { // Add any custom headers here 'Authorization': 'Bearer token123' } }) .on('ping', (data) => { console.log('Ping received:', data.message); }) .on('payload', (data) => { // For streamed events, this will be called with each chunk console.log('Payload chunk received:', data); }) .on('close', () => { console.log('Server closed the connection'); }) .stream(); // To close the connection manually client.close(); ``` -------------------------------- ### Implementing WebSocket Support with RiverSocketAdapter and Bun Source: https://github.com/bewinxed/river.ts/blob/main/README.md This snippet demonstrates how to set up and use the `RiverSocketAdapter` for WebSocket communication. It covers defining custom events, instantiating the adapter, registering event handlers, and integrating with a Bun.js WebSocket server to send and receive messages. ```typescript import { RiverEvents } from 'river.ts'; import { RiverSocketAdapter } from 'river.ts/websocket'; // Define your events const events = new RiverEvents() .defineEvent('message', { data: '' as string | Uint8Array }) .defineEvent('notification', { data: { id: 0, text: '' } }) .build(); // Create adapter const socketAdapter = new RiverSocketAdapter(events, { debug: true }); // Register event handlers socketAdapter.on('message', (data) => { console.log(`Received message: ${typeof data === 'string' ? data : 'binary data'}`); }); socketAdapter.on('notification', (data) => { console.log(`Notification #${data.id}: ${data.text}`); }); // Example using with Bun's WebSocket server const server = Bun.serve({ port: 3000, fetch(req, server) { if (server.upgrade(req)) { return; } return new Response('Expected a WebSocket connection', { status: 400 }); }, websocket: { message(ws, message) { // Process incoming messages with the adapter socketAdapter.handleMessage(message); // Send a message using the adapter socketAdapter.send('notification', { id: 1, text: 'Message received!' }, (msg) => ws.send(msg) ); }, open(ws) { console.log('Client connected'); }, close(ws, code, reason) { console.log(`Client disconnected: ${code} - ${reason}`); } } }); ``` -------------------------------- ### Set up server-side SSE with RiverEmitter Source: https://github.com/bewinxed/river.ts/blob/main/README.md Illustrates how to initialize `RiverEmitter` on the server to manage Server-Sent Events. This snippet covers streaming events to clients, broadcasting messages, sending to specific client IDs, retrieving connected clients, and handling client disconnections. ```typescript import { RiverEmitter } from 'river.ts/server'; import { events } from './events'; const emitter = RiverEmitter.init(events); // Example with a standard web server function handleSSE(req, res) { const stream = emitter.stream({ callback: async (emit, clientId) => { console.log(`Client ${clientId} connected`); // Emit single events await emit('ping', { message: 'pong' }); // Emit streamed events (will be automatically chunked) const largeDataset = Array.from({ length: 1000 }, (_, i) => ({ id: i, value: `Item ${i}` })); await emit('payload', largeDataset); // You can access the client ID that was generated or provided console.log(`Finished initial events for client ${clientId}`); }, clientId: 'custom-id-123', // Optional: set a custom client ID ondisconnect: (clientId) => { console.log(`Client ${clientId} disconnected`); }, signal: request.signal // Optional: link to an AbortSignal }); return new Response(stream, { headers: emitter.headers() }); } // Later, you can broadcast to all clients await emitter.broadcast('update', { message: 'System update completed' }); // Or send to a specific client await emitter.sendToClient('custom-id-123', 'private', { message: 'Just for you' }); // Get all connected clients const clients = emitter.getConnectedClients(); console.log(`${clients.length} clients connected`); // Disconnect a specific client await emitter.disconnectClient('custom-id-123'); ``` -------------------------------- ### Define type-safe event map with RiverEvents Source: https://github.com/bewinxed/river.ts/blob/main/README.md Demonstrates how to use the `RiverEvents` class to define a structured, type-safe map of events. This includes defining simple events like 'ping' and more complex, streamable events like 'payload' with optional chunking. ```typescript import { RiverEvents } from 'river.ts'; const events = new RiverEvents() .defineEvent('ping', { message: 'pong' }) .defineEvent('payload', { data: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ], stream: true, chunk_size: 100 // Optional: customize chunk size for streamed events }) .build(); ``` -------------------------------- ### Achieving Type Safety in River.ts Event Handling Source: https://github.com/bewinxed/river.ts/blob/main/README.md This snippet illustrates how to leverage TypeScript's type system with `river.ts` to ensure compile-time type safety for event data. It demonstrates extracting specific event data types using `EventData` and highlights how TypeScript provides strong type checking for event handlers, preventing common data access errors. ```typescript import { EventData } from 'river.ts'; import { events } from './events'; type Events = typeof events; // Get the data type for a specific event type PayloadData = EventData; // Type-safe event handlers function handlePayload(data: PayloadData) { // TypeScript knows the exact shape of this data data.forEach(item => console.log(item.id, item.name)); } // This would cause a TypeScript error if 'ping' doesn't have this structure client.on('ping', (data) => { console.log(data.missing_property); // TypeScript error! }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.