### Quickstart WebSocket with Buffering and Reconnection Source: https://github.com/jjxxs/websocket-ts/blob/master/README.md Initialize a WebSocket with message buffering and automatic reconnection. This example demonstrates setting up a WebSocket that echoes messages and attempts to reconnect every second. ```typescript import { ArrayQueue, ConstantBackoff, Websocket, WebsocketBuilder, WebsocketEvent, } from "websocket-ts"; // Initialize WebSocket with buffering and 1s reconnection delay const ws = new WebsocketBuilder("ws://localhost:8080") .withBuffer(new ArrayQueue()) // buffer messages when disconnected .withBackoff(new ConstantBackoff(1000)) // retry every 1s .build(); // Function to output & echo received messages const echoOnMessage = (i: Websocket, ev: MessageEvent) => { console.log(`received message: ${ev.data}`); i.send(`echo: ${ev.data}`); }; // Add event listeners ws.addEventListener(WebsocketEvent.open, () => console.log("opened!")); ws.addEventListener(WebsocketEvent.close, () => console.log("closed!")); ws.addEventListener(WebsocketEvent.message, echoOnMessage); ``` -------------------------------- ### WebsocketOptions Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/types.md Example of creating a WebsocketOptions object with a buffer and retry configuration. ```typescript const options: WebsocketOptions = { buffer: new ArrayQueue(), retry: { backoff: new ConstantBackoff(1000), maxRetries: 5, }, }; const ws = new Websocket("ws://localhost:8080", undefined, options); ``` -------------------------------- ### Full Event Lifecycle Management Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/event-system.md A comprehensive example demonstrating the setup of a WebSocket connection with various event handlers for open, message, error, retry, reconnect, and close events. ```typescript import { WebsocketBuilder, ConstantBackoff, ArrayQueue, WebsocketEvent, } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .withBuffer(new ArrayQueue()) .withBackoff(new ConstantBackoff(1000)) .withMaxRetries(5) .onOpen((instance) => { console.log("✓ Connected"); console.log(` URL: ${instance.url}`); console.log(` ReadyState: ${instance.readyState}`); }) .onMessage((instance, event) => { try { const data = JSON.parse(event.data); console.log("✓ Received:", data); } catch (e) { console.log("✓ Received raw:", event.data); } }) .onError((instance) => { console.error("✗ Error occurred"); }) .onRetry((instance, event) => { const detail = event.detail; console.warn( `⟳ Retry attempt ${detail.retries + 1} (waiting ${detail.backoff}ms)` ); }) .onReconnect((instance, event) => { const detail = event.detail; console.log( `✓ Reconnected after ${detail.retries} attempt(s)` ); }) .onClose((instance) => { if (instance.closedByUser) { console.log("✓ Connection closed by user"); } else { console.log("✗ Connection closed unexpectedly"); } }) .build(); // Send a message setTimeout(() => { ws.send(JSON.stringify({ type: "ping" })); }, 1000); // Clean up window.addEventListener("beforeunload", () => { ws.close(1000, "Page closing"); }); ``` -------------------------------- ### Install websocket-ts Source: https://github.com/jjxxs/websocket-ts/blob/master/README.md Install the websocket-ts library using npm. This is the first step to using the library in your project. ```bash npm install websocket-ts ``` -------------------------------- ### LinearBackoff Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Shows how to configure a WebsocketBuilder with a LinearBackoff, starting at 1 second, increasing by 1 second each retry, and capping at 10 seconds. ```typescript import { WebsocketBuilder, LinearBackoff } from "websocket-ts"; // Start at 1s, increase by 1s each retry, cap at 10s const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new LinearBackoff(1000, 1000, 10000)) .build(); // Series: 1s, 2s, 3s, 4s, 5s, 6s, 7s, 8s, 9s, 10s, 10s, 10s... ``` -------------------------------- ### WebsocketConnectionRetryOptions Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/types.md Example of configuring retry options with a linear backoff strategy, maximum retries, and instant reconnection enabled. ```typescript const retryOptions: WebsocketConnectionRetryOptions = { backoff: new LinearBackoff(100, 100, 5000), maxRetries: 20, instantReconnect: true, }; ``` -------------------------------- ### Basic WebsocketBuilder Initialization Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Initializes a new WebsocketBuilder instance with the server URL. This is the most basic setup. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .onError((instance, event) => { console.error("Connection error:", event); }) .build(); ``` -------------------------------- ### Example WebsocketEventListenerOptions Usage Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/types.md Shows how to add an event listener with specific options like 'once: true'. ```typescript ws.addEventListener(WebsocketEvent.open, handler, { once: true }); ``` -------------------------------- ### Websocket Constructor Examples Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Demonstrates various ways to instantiate the Websocket class, from basic URL strings to dynamic URLs, protocols, and custom options. ```typescript import { Websocket } from "websocket-ts"; // Basic connection with URL string const ws = new Websocket("ws://localhost:8080"); ``` ```typescript // Dynamic URL with function provider const ws = new Websocket(() => `ws://localhost:8080?token=${getToken()}`); ``` ```typescript // With protocols const ws = new Websocket("ws://localhost:8080", ["chat", "notifications"]); ``` ```typescript // With options const ws = new Websocket("ws://localhost:8080", undefined, { buffer: new ArrayQueue(), retry: { backoff: new ConstantBackoff(1000), maxRetries: 5, }, }); ``` -------------------------------- ### Example WebsocketEventListener Usage Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/types.md Demonstrates how to define and use a message event listener with the correct type. ```typescript const messageListener: WebsocketEventListener = ( instance, event ) => { // event is typed as MessageEvent console.log(event.data); }; ws.addEventListener(WebsocketEvent.message, messageListener); ``` -------------------------------- ### Initialize WebSocket with WebsocketBuilder Source: https://github.com/jjxxs/websocket-ts/blob/master/README.md Create a new WebSocket instance using the WebsocketBuilder. This is a basic setup for a WebSocket connection. ```typescript const ws = new WebsocketBuilder("ws://localhost:42421").build(); ``` -------------------------------- ### Minimal WebSocket Setup Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Demonstrates the minimal configuration required to create a WebSocket connection using WebsocketBuilder. It only requires the server URL. ```typescript import { WebsocketBuilder } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080").build(); ``` -------------------------------- ### LinearBackoff Complete Example with WebsocketBuilder Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Shows a complete example of integrating LinearBackoff with WebsocketBuilder for WebSocket connections, including retry logging. ```typescript import { WebsocketBuilder, LinearBackoff } from "websocket-ts"; // Backoff: 0s, 1s, 2s, 3s, 4s, 5s, 5s, 5s... const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new LinearBackoff(0, 1000, 5000)) .withMaxRetries(10) .onRetry((instance, event) => { console.log( `Retry attempt ${event.detail.retries}, waiting ${event.detail.backoff}ms` ); }) .build(); ``` -------------------------------- ### Configuration Validation Examples Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Illustrates valid and invalid configurations for backoff strategies and queues, showing expected errors thrown by the library. This helps in understanding configuration constraints. ```typescript // Valid new ConstantBackoff(1000); // ✓ // Invalid - throws Error new ConstantBackoff(-1000); // ✗ "Backoff must be a positive integer" new LinearBackoff(1000, -500); // ✗ "Increment must be a positive number or zero" new LinearBackoff(1000, 100, 500); // ✗ "Max must be greater than or equal to initial" new RingQueue(0); // ✗ "Capacity must be a positive integer" new ExponentialBackoff(-100); // ✗ "Base must be a positive integer or zero" ``` -------------------------------- ### Linear Backoff Strategy Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/INDEX.md Implement a LinearBackoff strategy for reconnection attempts, starting with no delay and increasing linearly up to a maximum. This example starts at 0ms, increases by 1000ms per attempt, and caps at 10000ms. ```typescript new LinearBackoff(0, 1000, 10000) // 0, 1s, 2s, ..., 10s, 10s... ``` -------------------------------- ### ExponentialBackoff Constructor Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Shows how to create an ExponentialBackoff instance with a base and maximum exponent for WebSocket retries. ```typescript import { WebsocketBuilder, ExponentialBackoff } from "websocket-ts"; // Start at 1s, double each retry, cap exponent at 6 (64s max) const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new ExponentialBackoff(1000, 6)) .build(); // Series: 1s, 2s, 4s, 8s, 16s, 32s, 64s, 64s, 64s... ``` -------------------------------- ### ArrayQueue length() Method Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Illustrates how to get the current number of elements in the ArrayQueue. The length decreases as elements are read. ```typescript const queue = new ArrayQueue(); queue.add("msg1"); queue.add("msg2"); console.log(queue.length()); // 2 queue.read(); console.log(queue.length()); // 1 ``` -------------------------------- ### Basic WebSocket Initialization Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/INDEX.md Use this snippet for a minimal WebSocket setup without any special configurations like reconnection or buffering. It establishes a connection and logs incoming messages. ```typescript import { WebsocketBuilder } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .onMessage((instance, event) => console.log(event.data)) .build(); ``` -------------------------------- ### ExponentialBackoff Complete Example with WebsocketBuilder Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Demonstrates using ExponentialBackoff with WebsocketBuilder, illustrating binary exponential backoff and retry logging. ```typescript import { WebsocketBuilder, ExponentialBackoff } from "websocket-ts"; // Binary exponential backoff: 100ms, 200ms, 400ms, 800ms, 1.6s, 3.2s, 6.4s, 12.8s, 25.6s, 51.2s const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new ExponentialBackoff(100, 9)) .withMaxRetries(15) .onRetry((instance, event) => { const seconds = (event.detail.backoff / 1000).toFixed(2); console.log( `Retry attempt ${event.detail.retries}, waiting ${seconds}s` ); }) .build(); ``` -------------------------------- ### ConstantBackoff Example Usage Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Illustrates the behavior of a ConstantBackoff instance, showing how 'current' and 'retries' properties change and how 'next()' and 'reset()' methods function. ```typescript const backoff = new ConstantBackoff(2000); console.log(backoff.current); // 2000 console.log(backoff.retries); // 0 const delay1 = backoff.next(); // 2000 (retries: 1) const delay2 = backoff.next(); // 2000 (retries: 2) const delay3 = backoff.next(); // 2000 (retries: 3) backoff.reset(); console.log(backoff.retries); // 0 ``` -------------------------------- ### ExponentialBackoff Example Usage Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Illustrates the usage of the ExponentialBackoff class, showing initial values, calculated delays with exponent capping, and resetting the backoff. ```typescript const backoff = new ExponentialBackoff(500, 5); console.log(backoff.current); // 500 console.log(backoff.retries); // 0 const delay1 = backoff.next(); // 1000 (500 * 2^1, retries: 1) const delay2 = backoff.next(); // 2000 (500 * 2^2, retries: 2) const delay3 = backoff.next(); // 4000 (500 * 2^3, retries: 3) const delay4 = backoff.next(); // 8000 (500 * 2^4, retries: 4) const delay5 = backoff.next(); // 16000 (500 * 2^5, retries: 5) — exponent capped const delay6 = backoff.next(); // 16000 (500 * 2^5, retries: 6) — stays at max backoff.reset(); console.log(backoff.retries); // 0 console.log(backoff.current); // 500 — back to initial ``` -------------------------------- ### ConstantBackoff Usage Examples Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Demonstrates how to configure a WebsocketBuilder with a ConstantBackoff strategy for retrying every 1 second or retrying immediately. ```typescript import { WebsocketBuilder, ConstantBackoff } from "websocket-ts"; // Retry every 1 second const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new ConstantBackoff(1000)) .build(); // Retry immediately without delay const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new ConstantBackoff(0)) .build(); ``` -------------------------------- ### Minimal Websocket Setup Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Configure a basic WebSocket connection without any reconnection or buffering strategies. This is suitable for simple use cases where reliability is not a primary concern. ```typescript import { WebsocketBuilder } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .onMessage((instance, event) => { console.log(event.data); }) .build(); ``` -------------------------------- ### LinearBackoff Example Usage Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Demonstrates how to use the LinearBackoff class to manage retry delays. Shows initial values, subsequent delays, and resetting the backoff. ```typescript const backoff = new LinearBackoff(1000, 500, 5000); console.log(backoff.current); // 1000 console.log(backoff.retries); // 0 const delay1 = backoff.next(); // 1500 (retries: 1) const delay2 = backoff.next(); // 2000 (retries: 2) const delay3 = backoff.next(); // 2500 (retries: 3) const delay4 = backoff.next(); // 3000 (retries: 4) const delay5 = backoff.next(); // 3500 (retries: 5) const delay6 = backoff.next(); // 4000 (retries: 6) const delay7 = backoff.next(); // 4500 (retries: 7) const delay8 = backoff.next(); // 5000 (retries: 8) — capped at max const delay9 = backoff.next(); // 5000 (retries: 9) — stays at max backoff.reset(); console.log(backoff.retries); // 0 console.log(backoff.current); // 1000 — back to initial ``` -------------------------------- ### ArrayQueue Constructor Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Demonstrates how to initialize a WebsocketBuilder with an ArrayQueue for message buffering. The library automatically infers the element type for WebSocket messages. ```typescript import { WebsocketBuilder, ArrayQueue } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .withBuffer(new ArrayQueue()) .build(); ``` -------------------------------- ### WebSocket Constructor Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/INDEX.md Instantiate a WebSocket connection directly using the constructor. This method allows for basic setup with optional protocols and configuration options. ```APIDOC ## new Websocket(url, protocols?, options?) ### Description Creates a new WebSocket instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```typescript new Websocket(url: string, protocols?: string | string[], options?: WebsocketOptions) ``` ``` -------------------------------- ### ArrayQueue add() Method Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Illustrates adding elements to an ArrayQueue. Elements are added to the end of the queue. ```typescript const queue = new ArrayQueue(); queue.add("message 1"); queue.add("message 2"); ``` -------------------------------- ### ArrayQueue forEach() Method Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Shows how to iterate over all elements in the ArrayQueue using a provided callback function. Elements are processed in their FIFO order. ```typescript const queue = new ArrayQueue(); queue.add("msg1"); queue.add("msg2"); queue.add("msg3"); queue.forEach((msg) => { console.log(msg); // msg1, msg2, msg3 }); ``` -------------------------------- ### WebsocketBuilder Initialization and Configuration Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Initialize and configure a WebSocket connection using the WebsocketBuilder fluent API. This example sets protocols, buffer, backoff strategy, max retries, and enables instant reconnect. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .withProtocols("chat") .withBuffer(new ArrayQueue()) .withBackoff(new ConstantBackoff(1000)) .withMaxRetries(5) .withInstantReconnect(true) .onOpen(() => console.log("Connected")) .onMessage((i, ev) => console.log(ev.data)) .build(); ``` -------------------------------- ### ArrayQueue isEmpty() Method Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Demonstrates checking if the ArrayQueue is empty. Returns true if no elements are present, false otherwise. ```typescript const queue = new ArrayQueue(); console.log(queue.isEmpty()); // true queue.add("message"); console.log(queue.isEmpty()); // false ``` -------------------------------- ### RingQueue Buffer Capacity Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Demonstrates calculating the appropriate capacity for a RingQueue buffer based on message rate and expected downtime. This ensures data is not lost during temporary disconnections. ```typescript new RingQueue(300) // 300 messages = 5 minutes at 1 msg/sec ``` -------------------------------- ### ArrayQueue peek() Method Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Shows how to view the next element in the ArrayQueue without removing it. Returns undefined if the queue is empty. ```typescript const queue = new ArrayQueue(); queue.add("first"); const msg = queue.peek(); // "first" const msg2 = queue.peek(); // "first" (not removed) ``` -------------------------------- ### WebSocketBuilder Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/INDEX.md Use the builder pattern for a more fluent and configurable WebSocket setup. This approach allows chaining methods to configure buffering, backoff strategies, event listeners, and more before building the final WebSocket instance. ```APIDOC ## WebsocketBuilder ### Description Provides a fluent API for configuring and creating WebSocket instances. ### Builder Methods - **`new WebsocketBuilder(url)`**: Initializes the builder with the WebSocket URL. - **`.withProtocols(protocols?)`**: Sets the sub-protocol(s) for the connection. - **`.withBuffer(buffer?)`**: Configures a message buffer (e.g., `ArrayQueue`, `RingQueue`). - **`.withBackoff(backoff?)`**: Sets the backoff strategy for reconnections (e.g., `ConstantBackoff`, `ExponentialBackoff`). - **`.withMaxRetries(maxRetries?)`**: Specifies the maximum number of retry attempts. - **`.withInstantReconnect(instantReconnect?)`**: Enables immediate reconnection on failure. - **`.onOpen(listener?, options?)`**: Registers an event listener for the 'open' event. - **`.onClose(listener?, options?)`**: Registers an event listener for the 'close' event. - **`.onError(listener?, options?)`**: Registers an event listener for the 'error' event. - **`.onMessage(listener?, options?)`**: Registers an event listener for the 'message' event. - **`.onRetry(listener?, options?)`**: Registers an event listener for the 'retry' event. - **`.onReconnect(listener?, options?)`**: Registers an event listener for the 'reconnect' event. - **`.build()`**: Constructs and returns the WebSocket instance. ### Example Usage ```typescript import { WebsocketBuilder } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .withBuffer(new ArrayQueue()) .withBackoff(new ConstantBackoff(1000)) .build(); ``` ``` -------------------------------- ### Initializing RingQueue with a Fixed Capacity Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Initialize a RingQueue with a specified capacity to buffer a fixed number of messages. This example shows how to set up a WebSocket connection with a buffer limit of 100 messages. ```typescript import { WebsocketBuilder, RingQueue } from "websocket-ts"; // Buffer at most 100 messages const ws = new WebsocketBuilder("ws://localhost:8080") .withBuffer(new RingQueue(100)) .build(); ``` -------------------------------- ### Production Websocket Configuration Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Configure a production-ready WebSocket connection with exponential backoff, bounded retries, a fixed-size RingQueue buffer, and instant first retry. This setup is designed for robustness and handles various connection states with detailed logging. ```typescript import { WebsocketBuilder, ExponentialBackoff, RingQueue, } from "websocket-ts"; const ws = new WebsocketBuilder("wss://api.example.com/stream") .withBuffer(new RingQueue(500)) // Max 500 buffered messages .withBackoff(new ExponentialBackoff(100, 8)) // 100ms to 25.6s .withMaxRetries(20) // Give up after 20 attempts .withInstantReconnect(true) // Immediate first retry .onOpen((instance) => { console.log("Connected"); }) .onMessage((instance, event) => { handleMessage(event.data); }) .onRetry((instance, event) => { console.warn( `Retry ${event.detail.retries + 1}: waiting ${event.detail.backoff}ms` ); }) .onReconnect((instance, event) => { console.log( `Reconnected after ${event.detail.retries} attempts` ); }) .onError((instance) => { console.error("Connection error"); }) .onClose((instance) => { if (!instance.closedByUser) { console.error("Unexpected disconnection"); } }) .build(); ``` -------------------------------- ### Register Event Listeners with Builder Methods Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/event-system.md Configures various event listeners (open, message, error, close, retry, reconnect) using a fluent builder API for concise setup. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .onOpen(() => console.log("Opened")) .onMessage((i, ev) => console.log("Message:", ev.data)) .onError(() => console.log("Error")) .onClose(() => console.log("Closed")) .onRetry((i, ev) => console.log(`Retrying...`)) .onReconnect((i, ev) => console.log(`Reconnected`)) .build(); ``` -------------------------------- ### Bounded Message Queue Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/INDEX.md Set up a bounded message queue with RingQueue to limit memory usage. This example allows a maximum of 100 messages, dropping the oldest when the limit is reached. ```typescript new RingQueue(100) // Max 100 messages, drops oldest when full ``` -------------------------------- ### Add WebSocket Event Listeners with Builder Methods Source: https://github.com/jjxxs/websocket-ts/blob/master/README.md Register event listeners for various WebSocket events using the builder's shorthand methods. This example shows how to handle open, close, error, message, retry, and reconnect events. ```typescript const ws = new WebsocketBuilder("ws://localhost:42421") .onOpen((i, ev) => console.log("opened")) .onClose((i, ev) => console.log("closed")) .onError((i, ev) => console.log("error")) .onMessage((i, ev) => console.log("message")) .onRetry((i, ev) => console.log("retry")) .onReconnect((i, ev) => console.log("reconnect")) .build(); ``` -------------------------------- ### Custom PriorityQueue Implementation Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Provides an example of implementing a custom queue by adhering to the `Queue` interface. This `PriorityQueue` sorts elements upon addition and is suitable for scenarios requiring custom ordering logic. ```typescript import { Queue } from "websocket-ts"; class PriorityQueue implements Queue { private elements: E[] = []; add(element: E): void { // Add with custom priority logic this.elements.push(element); this.elements.sort(); // Custom sort } read(): E | undefined { return this.elements.shift(); } clear(): void { this.elements = []; } forEach(fn: (element: E) => unknown): void { this.elements.forEach(fn); } length(): number { return this.elements.length; } isEmpty(): boolean { return this.elements.length === 0; } peek(): E | undefined { return this.elements[0]; } } const ws = new WebsocketBuilder("ws://localhost:8080") .withBuffer(new PriorityQueue()) .build(); ``` -------------------------------- ### Import Interfaces Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/INDEX.md Import specific interfaces from 'websocket-ts' for defining contracts and ensuring type safety. This example imports interfaces related to backoff strategies, queues, and buffers. ```typescript import { Backoff, Queue, WebsocketBuffer, WebsocketEvent, } from "websocket-ts"; ``` -------------------------------- ### Import Specific Classes Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/INDEX.md Import only the necessary classes from 'websocket-ts' to reduce bundle size and improve clarity. This example imports core classes like Websocket, WebsocketBuilder, and various strategy/queue implementations. ```typescript import { Websocket, WebsocketBuilder, ConstantBackoff, LinearBackoff, ExponentialBackoff, ArrayQueue, RingQueue, } from "websocket-ts"; ``` -------------------------------- ### Custom Backoff Implementation with Backoff Interface Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/backoff-strategies.md Implement the Backoff interface to create a custom retry strategy. This example demonstrates a custom backoff that increases delay based on the square root of attempts. ```typescript import { Backoff } from "websocket-ts"; class CustomBackoff implements Backoff { private _retries = 0; private i = 0; get retries(): number { return this._retries; } get current(): number { // Calculate current delay based on your strategy return 1000 * Math.sqrt(this.i); } next(): number { this._retries++; this.i++; return this.current; } reset(): void { this._retries = 0; this.i = 0; } } const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new CustomBackoff()) .build(); ``` -------------------------------- ### build() Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Constructs and returns a new Websocket instance with all configured options. The returned Websocket immediately attempts to establish a connection. ```APIDOC ## build() ### Description Constructs and returns a new Websocket instance with all configured options. The returned Websocket immediately attempts to establish a connection. ### Method Signature ```typescript public build(): Websocket ``` ### Returns - **Type**: `Websocket` - **Description**: A fully configured Websocket instance. ### Example ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .withProtocols("chat") .withBackoff(new ConstantBackoff(1000)) .withBuffer(new ArrayQueue()) .withMaxRetries(10) .onOpen(() => console.log("Connected")) .onMessage((i, ev) => console.log("Message:", ev.data)) .onError(() => console.log("Error")) .onClose(() => console.log("Closed")) .build(); // At this point, ws is connected or connecting console.log(ws.readyState); // WebSocket.CONNECTING or WebSocket.OPEN ``` ``` -------------------------------- ### onOpen() Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Registers a listener for the `open` event, fired when the connection is established. All event listener methods accept an optional `options` parameter to control listener behavior (e.g., `{ once: true }` for one-time listeners). Multiple calls to the same method add additional listeners without replacing previous ones. ```APIDOC ## onOpen() ### Description Registers a listener for the `open` event, fired when the connection is established. All event listener methods accept an optional `options` parameter to control listener behavior (e.g., `{ once: true }` for one-time listeners). Multiple calls to the same method add additional listeners without replacing previous ones. ### Method `public onOpen( listener: WebsocketEventListener, options?: WebsocketEventListenerOptions, ): WebsocketBuilder` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **listener** (`WebsocketEventListener`) - Yes - Function receiving (websocket, event) called when connection opens. - **options** (`WebsocketEventListenerOptions`) - No - Event options like `{ once: true }` ### Returns `WebsocketBuilder` — Returns this builder for chaining. ### Example ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .onOpen((instance, event) => console.log("Connected!")) .onOpen((instance, event) => { console.log("Additional open handler"); }) .build(); ``` ``` -------------------------------- ### maxRetries Property Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Gets the maximum number of times the WebSocket will attempt to reconnect after a disconnection. ```APIDOC ## maxRetries Property ### Description The maximum number of retry attempts before giving up. ### Return Type `number | undefined` - Maximum number of retries, or undefined if no limit is set. ``` -------------------------------- ### Basic WebsocketBuilder Configuration Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Demonstrates building a WebSocket connection with linear backoff and instant reconnect enabled. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .withBackoff(new LinearBackoff(1000, 1000)) // First retry: 1s, second: 2s, etc. .withInstantReconnect(true) // But first retry is immediate .build(); ``` -------------------------------- ### Building a Fully Configured WebSocket Instance Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Constructs a WebSocket instance with various configurations including protocols, backoff strategy, buffer, max retries, and multiple event listeners. The build() method initiates the connection. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .withProtocols("chat") .withBackoff(new ConstantBackoff(1000)) .withBuffer(new ArrayQueue()) .withMaxRetries(10) .onOpen(() => console.log("Connected")) .onMessage((i, ev) => console.log("Message:", ev.data)) .onError(() => console.log("Error")) .onClose(() => console.log("Closed")) .build(); // At this point, ws is connected or connecting console.log(ws.readyState); // WebSocket.CONNECTING or WebSocket.OPEN ``` -------------------------------- ### Add One-Time Listener Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/event-system.md Register an event listener that will only be triggered once. Useful for initial connection setup. ```typescript const ws = new Websocket("ws://localhost:8080"); // Fire only on the first successful connection ws.addEventListener( WebsocketEvent.open, (instance) => { console.log("First connection successful!"); }, { once: true } ); // Or using builder: const ws2 = new WebsocketBuilder("ws://localhost:8080") .onOpen((instance) => { console.log("First open"); }, { once: true }) .build(); ``` -------------------------------- ### ArrayQueue clear() Method Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Illustrates removing all elements from the ArrayQueue, effectively resetting it to an empty state. ```typescript const queue = new ArrayQueue(); queue.add("msg1"); queue.add("msg2"); console.log(queue.length()); // 2 queue.clear(); console.log(queue.length()); // 0 ``` -------------------------------- ### Constructor Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Initializes a new WebsocketBuilder instance. It takes a UrlProvider which can be a string URL or a function that returns a URL. ```APIDOC ## Constructor WebsocketBuilder ### Description Creates a new WebsocketBuilder with the specified URL. ### Parameters #### Path Parameters - **url** (UrlProvider) - Required - The URL to connect to, either as a string or a function that returns a URL. ### Example ```typescript import { WebsocketBuilder } from "websocket-ts"; const builder = new WebsocketBuilder("ws://localhost:8080"); ``` ``` -------------------------------- ### Get WebSocket Extensions Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Retrieves the extensions selected by the server during the WebSocket handshake. This information is useful for understanding the negotiated protocol features. ```typescript get extensions(): string ``` -------------------------------- ### Get Last Connection Timestamp Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Retrieves the timestamp of the last successful WebSocket connection. Useful for logging or debugging connection events. ```typescript get lastConnection(): Date | undefined ``` ```typescript ws.addEventListener(WebsocketEvent.open, () => { console.log(ws.lastConnection); // Date object of when connection opened }); ``` -------------------------------- ### url Property Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Gets the resolved URL of the current or last connection attempt. This is useful for debugging or understanding the active connection endpoint. ```APIDOC ## url Property ### Description The resolved URL of the current or last connection attempt. ### Return Type `string` - The last resolved URL, resolved from the URL provider if applicable. ### Example ```typescript const ws = new Websocket("ws://localhost:8080"); console.log(ws.url); // "ws://localhost:8080" ``` ``` -------------------------------- ### Minimal Websocket Constructor Configuration Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Shows the minimal configuration required when using the Websocket constructor directly, highlighting the default values for various settings. This is useful for understanding the default behavior. ```typescript new Websocket("ws://localhost:8080"); // Equivalent to: new Websocket("ws://localhost:8080", undefined, { buffer: undefined, retry: { backoff: undefined, maxRetries: undefined, instantReconnect: undefined, }, listeners: undefined, }); ``` -------------------------------- ### ArrayQueue read() Method Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Demonstrates removing and retrieving elements from the front of the ArrayQueue in FIFO order. Returns undefined if the queue is empty. ```typescript const queue = new ArrayQueue(); queue.add("first"); queue.add("second"); const msg1 = queue.read(); // "first" const msg2 = queue.read(); // "second" const msg3 = queue.read(); // undefined ``` -------------------------------- ### Full Websocket Configuration Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Demonstrates a comprehensive configuration of the WebsocketBuilder, including protocols, buffer, backoff strategy, retry limits, and various event handlers for connection lifecycle management. ```typescript import { WebsocketBuilder, ConstantBackoff, ArrayQueue, WebsocketEvent, } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .withProtocols("chat") .withBuffer(new ArrayQueue()) .withBackoff(new ConstantBackoff(1000)) .withMaxRetries(5) .withInstantReconnect(true) .onOpen((instance) => console.log("Connected")) .onMessage((instance, event) => { console.log("Message:", event.data); instance.send(`echo: ${event.data}`); }) .onError((instance) => console.log("Error")) .onClose((instance) => console.log("Closed")) .onRetry((instance, event) => { console.log(`Retrying: attempt ${event.detail.retries}`); }) .onReconnect((instance, event) => { console.log(`Reconnected after ${event.detail.retries} attempts`); }) .build(); ``` -------------------------------- ### Websocket Constructor with URL Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Instantiate a new Websocket connection with a static URL. ```typescript new Websocket("ws://localhost:8080") ``` -------------------------------- ### Get WebSocket Ready State Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Retrieves the current state of the WebSocket connection. This is useful for conditional logic, such as sending messages only when the connection is open. ```typescript get readyState(): number ``` ```typescript if (ws.readyState === WebSocket.OPEN) { ws.send("message"); } ``` -------------------------------- ### open Event Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/event-system.md Fired when the WebSocket connection is successfully established and ready to send/receive data. You can use `onOpen()` or `addEventListener(WebsocketEvent.open, ...)` to handle this event. ```APIDOC ## open Event ### Description Fired when the WebSocket connection is successfully established and ready to send/receive data. ### Handler Signature ```typescript (instance: Websocket, event: Event) => void ``` ### Parameters - `instance` (Websocket) - The Websocket instance - `event` (Event) - Standard DOM Event object ### Example ```typescript import { WebsocketBuilder, WebsocketEvent } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .onOpen((instance) => { console.log("Connected!"); console.log("URL:", instance.url); }) .build(); // Or with addEventListener ws.addEventListener(WebsocketEvent.open, (instance, event) => { console.log("Connection opened"); }); ``` ``` -------------------------------- ### Websocket Constructor Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Initializes a new Websocket instance, automatically attempting to establish a connection. It supports dynamic URLs, protocols, and various configuration options for buffering and retries. ```APIDOC ## Websocket Constructor ### Description Creates a new Websocket instance. The constructor automatically attempts to establish a connection immediately. ### Parameters #### Path Parameters - **url** (UrlProvider) - Required - Connection URL as a string or function that returns a URL. When a function is provided, it is called on each connection attempt, enabling dynamic URL changes for load balancing, auth token rotation, and failover scenarios. - **protocols** (string | string[]) - Optional - Optional WebSocket sub-protocol(s) to request from the server. Can be a single protocol string or an array of protocol strings. - **options** (WebsocketOptions) - Optional - Optional configuration object containing buffer, retry strategy, and initial event listeners. ### Throws This constructor does not throw. Connection errors are emitted via the `error` event. ### Example ```typescript import { Websocket } from "websocket-ts"; // Basic connection with URL string const ws = new Websocket("ws://localhost:8080"); // Dynamic URL with function provider const ws = new Websocket(() => `ws://localhost:8080?token=${getToken()}`); // With protocols const ws = new Websocket("ws://localhost:8080", ["chat", "notifications"]); // With options const ws = new Websocket("ws://localhost:8080", undefined, { buffer: new ArrayQueue(), retry: { backoff: new ConstantBackoff(1000), maxRetries: 5, }, }); ``` ``` -------------------------------- ### Retry Option with Exponential Backoff Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Configure the reconnection retry strategy to use an exponential backoff strategy, starting at 100ms and increasing exponentially up to a maximum exponent. ```typescript retry: { backoff: new ExponentialBackoff(100, 9) } ``` -------------------------------- ### Retry Option with Linear Backoff Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Configure the reconnection retry strategy to use a linear backoff strategy, starting at 0ms and incrementing by 1000ms until a maximum of 10000ms. ```typescript retry: { backoff: new LinearBackoff(0, 1000, 10000) } ``` -------------------------------- ### Websocket Constructor with Multiple Protocols Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Instantiate a new Websocket connection specifying multiple sub-protocols. ```typescript new Websocket("ws://localhost:8080", ["chat", "notifications"]) ``` -------------------------------- ### Get Buffered Amount Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Returns the number of bytes queued for transmission but not yet sent. This can help in managing data flow and understanding potential network delays. ```typescript get bufferedAmount(): number ``` -------------------------------- ### Getting the Current Length of RingQueue Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Demonstrates the length() method of RingQueue, which returns the number of elements currently stored in the queue. This is useful for monitoring buffer usage. ```typescript const queue = new RingQueue(5); queue.add("msg1"); queue.add("msg2"); console.log(queue.length()); // 2 ``` -------------------------------- ### WebsocketOptions Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/types.md Configuration object passed to the Websocket constructor to customize its behavior, including message buffering, retry strategies, and event listeners. ```APIDOC ## WebsocketOptions ### Description Configuration object passed to the `Websocket` constructor. ### Fields - `buffer` (WebsocketBuffer | undefined) - No - Message buffer for storing outgoing messages when disconnected - `retry` (WebsocketConnectionRetryOptions | undefined) - No - Retry/reconnect strategy configuration - `listeners` (WebsocketEventListeners | undefined) - No - Initial event listeners to register ### Example ```typescript const options: WebsocketOptions = { buffer: new ArrayQueue(), retry: { backoff: new ConstantBackoff(1000), maxRetries: 5, }, }; const ws = new Websocket("ws://localhost:8080", undefined, options); ``` ``` -------------------------------- ### Handle WebSocket Open Event Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/event-system.md Listen for the 'open' event to know when the connection is established. This can be done using the onOpen builder or addEventListener. ```typescript import { WebsocketBuilder, WebsocketEvent } from "websocket-ts"; const ws = new WebsocketBuilder("ws://localhost:8080") .onOpen((instance) => { console.log("Connected!"); console.log("URL:", instance.url); }) .build(); // Or with addEventListener ws.addEventListener(WebsocketEvent.open, (instance, event) => { console.log("Connection opened"); }); ``` -------------------------------- ### Handle WebSocket Message Event Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/event-system.md Process incoming messages from the server using the onMessage handler. This example shows how to parse JSON messages and handle binary data. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .onMessage((instance, event) => { console.log("Received:", event.data); if (typeof event.data === "string") { const message = JSON.parse(event.data); handleMessage(message); } else { console.log("Received binary data:", event.data); } }) .build(); ``` -------------------------------- ### Create WebsocketBuilder Instance Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Instantiate the WebsocketBuilder with a URL. The URL can be a string or a function that provides the URL. ```typescript import { WebsocketBuilder } from "websocket-ts"; const builder = new WebsocketBuilder("ws://localhost:8080"); ``` -------------------------------- ### RingQueue Overflow Behavior Example Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Demonstrates the overflow behavior of RingQueue where adding an element to a full queue automatically removes the oldest element. The queue maintains its capacity. ```typescript const queue = new RingQueue(3); queue.add("first"); queue.add("second"); queue.add("third"); console.log(queue.length()); // 3 queue.add("fourth"); // "first" is automatically removed console.log(queue.length()); // 3 console.log(queue.read()); // "second" ``` -------------------------------- ### Registering Multiple Event Listeners Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/event-system.md Demonstrates how multiple listeners for the same event (e.g., 'onOpen', 'onMessage') are registered and executed in the order they are defined. All listeners for a given event fire before any listener for the next event. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .onOpen(() => console.log("1. Opened")) .onOpen(() => console.log("2. Opened (second handler)")) .onMessage(() => console.log("3. Message 1")) .onMessage(() => console.log("4. Message 1 (second handler)")) .build(); // Output when message arrives: // 1. Opened // 2. Opened (second handler) // 3. Message 1 // 4. Message 1 (second handler) ``` -------------------------------- ### Enable Instant Reconnection Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket-builder.md Configure the builder to immediately attempt reconnection upon disconnection, bypassing any configured backoff delay for the first retry. This is useful for applications requiring high availability. ```typescript const ws = new WebsocketBuilder("ws://localhost:8080") .withInstantReconnect(true) .build(); ``` -------------------------------- ### readyState Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/websocket.md Returns the current state of the underlying WebSocket connection, indicating whether it is connecting, open, closing, or closed. ```APIDOC ## readyState ### Description The current state of the underlying WebSocket connection. ### Return Type `number` - WebSocket state: 0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED ### Example ```typescript if (ws.readyState === WebSocket.OPEN) { ws.send("message"); } ``` ``` -------------------------------- ### Websocket Constructor with Dynamic URL Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Instantiate a new Websocket connection using a function to provide the URL dynamically, useful for including tokens or other changing parameters. ```typescript new Websocket(() => `ws://localhost:8080?token=${getToken()}`) ``` -------------------------------- ### Reading Elements from RingQueue Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/api-reference/queues.md Shows how to remove and retrieve the oldest element from a RingQueue using the read() method. The example demonstrates reading multiple elements and checking the remaining queue length. ```typescript const queue = new RingQueue(5); queue.add("a"); queue.add("b"); queue.add("c"); const msg1 = queue.read(); // "a" const msg2 = queue.read(); // "b" console.log(queue.length()); // 1 ``` -------------------------------- ### Websocket Builder Types Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/types.md Illustrates the types used in the WebsocketBuilder pattern for configuring and building a Websocket instance. ```typescript new WebsocketBuilder(url: UrlProvider) .withBuffer(buffer: WebsocketBuffer | undefined) .withBackoff(backoff: Backoff | undefined) .build(): Websocket ``` -------------------------------- ### Websocket Constructor with Single Protocol Source: https://github.com/jjxxs/websocket-ts/blob/master/_autodocs/configuration.md Instantiate a new Websocket connection specifying a single sub-protocol. ```typescript new Websocket("ws://localhost:8080", "chat") ```