### Install ReconnectingEventSource via npm Source: https://github.com/fanout/reconnecting-eventsource/blob/master/README.md Install the library using npm for use in Node.js or browserify/webpack projects. ```sh npm install reconnecting-eventsource ``` -------------------------------- ### Build ReconnectingEventSource from Source Source: https://github.com/fanout/reconnecting-eventsource/blob/master/README.md Build the project from source by running the build script after modifying source files. ```sh npm run build ``` -------------------------------- ### readyState Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Connection state constant. Reflects the current connection state, mirroring the native EventSource constants: CONNECTING = 0, OPEN = 1, CLOSED = 2. Useful for defensive guards before calling close() or when logging connection diagnostics. ```APIDOC ## `readyState` — Connection state constant Reflects the current connection state. Mirrors the native `EventSource` constants: `CONNECTING = 0`, `OPEN = 1`, `CLOSED = 2`. Useful for defensive guards before calling `close()` or when logging connection diagnostics. ```ts import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); function logState(es: ReconnectingEventSource) { const states = ['CONNECTING', 'OPEN', 'CLOSED']; console.log('Current state:', states[es.readyState]); } es.onopen = () => logState(es); // "OPEN" es.onerror = () => logState(es); // "CONNECTING" (while retrying) // Explicitly close and confirm es.close(); logState(es); // "CLOSED" ``` ``` -------------------------------- ### Include ReconnectingEventSource in HTML Source: https://github.com/fanout/reconnecting-eventsource/blob/master/README.md Include the minified browser build of the library in your HTML file. ```html ``` -------------------------------- ### Log Connection State - TypeScript Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Logs the current connection state (CONNECTING, OPEN, CLOSED) using the readyState property. Useful for diagnostics and defensive programming. ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); function logState(es: ReconnectingEventSource) { const states = ['CONNECTING', 'OPEN', 'CLOSED']; console.log('Current state:', states[es.readyState]); } es.onopen = () => logState(es); // "OPEN" es.onerror = () => logState(es); // "CONNECTING" (while retrying) // Explicitly close and confirm es.close(); logState(es); // "CLOSED" ``` -------------------------------- ### Configure ReconnectingEventSource Source: https://github.com/fanout/reconnecting-eventsource/blob/master/README.md The constructor accepts an optional configuration object to customize reconnection behavior, such as CORS credentials and maximum retry time. ```json { // indicating if CORS should be set to include credentials, default `false` withCredentials: false, // the maximum time to wait before attempting to reconnect in ms, default `3000` // note: wait time is randomised to prevent all clients from attempting to reconnect simultaneously max_retry_time: 3000, // underlying EventSource class, default `EventSource` eventSourceClass: EventSource, } ``` -------------------------------- ### Constructor: new ReconnectingEventSource(url, configuration?) Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Creates a resilient SSE connection. It accepts standard EventSource options plus `max_retry_time`, `eventSourceClass`, and `lastEventId` for enhanced configuration. ```APIDOC ## new ReconnectingEventSource(url, configuration?) ### Description Creates a resilient SSE connection to the given URL. Accepts the same options as the native `EventSourceInit` dictionary plus three additional fields: `max_retry_time`, `eventSourceClass`, and `lastEventId`. If `EventSource` is not available in the environment and no `eventSourceClass` is provided, an `EventSourceNotAvailableError` is thrown immediately. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Configuration Options - **url** (string) - Required - The URL to connect to. - **configuration** (object) - Optional - Configuration object. - **withCredentials** (boolean) - Optional - Standard EventSourceInit option. - **max_retry_time** (number) - Optional - Max ms to wait before a reconnect attempt (randomised internally). - **lastEventId** (string) - Optional - Resume from a known event ID (appended as ?lastEventId= on connect). - **eventSourceClass** (object) - Optional - Provide a custom or polyfilled EventSource class (e.g., for IE/Edge). ### Request Example ```javascript import ReconnectingEventSource from 'reconnecting-eventsource'; // Basic usage const es = new ReconnectingEventSource('https://api.example.com/events'); // Full configuration const esFullConfig = new ReconnectingEventSource('https://api.example.com/events', { withCredentials: true, max_retry_time: 5000, lastEventId: 'evt-00123', eventSourceClass: EventSourcePolyfill }); console.log(es.readyState); // 0 (CONNECTING) ``` ### Response #### Success Response (200) N/A - This is a constructor. #### Response Example N/A ``` -------------------------------- ### Initialize ReconnectingEventSource Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Create a new ReconnectingEventSource instance. Basic usage mirrors the native EventSource constructor. Full configuration allows setting options like max_retry_time, lastEventId, and providing a custom EventSource class. ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; // Basic usage — mirrors new EventSource(url) const es = new ReconnectingEventSource('https://api.example.com/events'); // Full configuration const es = new ReconnectingEventSource('https://api.example.com/events', { // Standard EventSourceInit option withCredentials: true, // Max ms to wait before a reconnect attempt (randomised internally) max_retry_time: 5000, // Resume from a known event ID (appended as ?lastEventId= on connect) lastEventId: 'evt-00123', // Provide a custom or polyfilled EventSource class (e.g., for IE/Edge) eventSourceClass: EventSourcePolyfill, }); console.log(es.readyState); // 0 (CONNECTING) ``` -------------------------------- ### onopen — Connection opened callback Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Callback invoked once when the underlying EventSource transitions from CONNECTING to OPEN. This callback fires again on each successful re-connection. ```APIDOC ## onopen ### Description Invoked once when the underlying `EventSource` transitions from `CONNECTING` to `OPEN`. During reconnects this fires again on each successful re-connection. ### Method Assignment to `es.onopen` property. ### Parameters - **event** (Event) - The event object. ### Request Example ```javascript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.onopen = (event) => { console.log('Connection established:', event); }; ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Import ReconnectingEventSource in Node.js/Browserify/Webpack Source: https://github.com/fanout/reconnecting-eventsource/blob/master/README.md Import the library using ES6 import syntax for module bundlers. ```javascript import ReconnectingEventSource from "reconnecting-eventsource"; ``` -------------------------------- ### Browser Script Tag Usage Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Includes the ReconnectingEventSource library using a script tag for direct browser usage without a bundler. Demonstrates basic event handling. ```html ``` -------------------------------- ### Handle Connection Open Event Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt The `onopen` callback is invoked when the underlying EventSource successfully connects or reconnects. It receives a standard Event object. ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.onopen = (event: Event) => { console.log('Connection established:', event); // Output: Connection established: Event { type: 'open', ... } }; ``` -------------------------------- ### Replace EventSource with ReconnectingEventSource Source: https://github.com/fanout/reconnecting-eventsource/blob/master/README.md To use the library, simply replace the instantiation of the native EventSource with ReconnectingEventSource. ```javascript var es = new EventSource(url); ``` ```javascript var es = new ReconnectingEventSource(url); ``` -------------------------------- ### Node.js Usage (CommonJS) Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Utilizes ReconnectingEventSource in a Node.js environment, requiring an 'eventsource' polyfill and configuring options like eventSourceClass and max_retry_time. ```javascript const EventSource = require('eventsource'); // npm install eventsource const ReconnectingEventSource = require('reconnecting-eventsource').default; const es = new ReconnectingEventSource('https://api.example.com/events', { eventSourceClass: EventSource, max_retry_time: 3000, withCredentials: false, }); es.addEventListener('error', (error) => { console.error('eventSource error', error); }); es.addEventListener('message', (ev) => { console.log('id :', ev.lastEventId); console.log('message:', ev.data); // id : 7 // message: {"status":"ok","value":42} }); ``` -------------------------------- ### onmessage — Default message handler Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Fired for every unnamed SSE event. Receives a standard MessageEvent with event data and the last event ID. ```APIDOC ## onmessage ### Description Fired for every unnamed SSE event (events without an explicit `event:` field). Receives a standard `MessageEvent` whose `.data` property contains the event payload string and `.lastEventId` contains the last seen event ID. ### Method Assignment to `es.onmessage` property. ### Parameters - **event** (MessageEvent) - The message event object. - **event.data** (string) - The event payload. - **event.lastEventId** (string) - The last seen event ID. ### Request Example ```javascript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.onmessage = (event) => { console.log('Event ID :', event.lastEventId); console.log('Payload :', event.data); }; ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### EventSourceNotAvailableError Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Thrown by the constructor when EventSource is not available globally and no eventSourceClass was supplied. Catch this to provide a graceful fallback or polyfill message. ```APIDOC ## `EventSourceNotAvailableError` — Missing EventSource guard Thrown by the constructor when `EventSource` is not available globally and no `eventSourceClass` was supplied. Catch this to provide a graceful fallback or polyfill message. ```ts import ReconnectingEventSource, { EventSourceNotAvailableError } from 'reconnecting-eventsource'; import EventSourcePolyfill from 'eventsource'; // npm install eventsource let es: ReconnectingEventSource; try { es = new ReconnectingEventSource('https://api.example.com/events'); } catch (err) { if (err instanceof EventSourceNotAvailableError) { // Retry with an explicit polyfill (required in Node.js < 22, IE, older Edge) es = new ReconnectingEventSource('https://api.example.com/events', { eventSourceClass: EventSourcePolyfill as unknown as typeof EventSource, }); } else { throw err; } } ``` ``` -------------------------------- ### addEventListener(type, listener) Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Subscribes to a named SSE event type. Listeners are preserved across reconnects. ```APIDOC ## addEventListener(type, listener) ### Description Subscribes to a named SSE event type (matching the `event:` field on the wire). Listeners are preserved across reconnects — you never need to re-register them. The method signature is fully compatible with `EventTarget.addEventListener`. ### Method `es.addEventListener(type, listener)` ### Parameters - **type** (string) - The name of the event to listen for. - **listener** (function) - The callback function to execute when the event is received. ### Request Example ```javascript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/stream'); const onStockUpdate = (event) => { const data = JSON.parse(event.data); console.log(`${data.symbol}: $${data.price}`); }; es.addEventListener('stock-update', onStockUpdate); es.addEventListener('open', () => console.log('stream open')); es.addEventListener('error', (e) => console.error('stream error', e)); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### close() Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Permanently close the connection. Stops all reconnect timers and closes the underlying EventSource. Sets readyState to CLOSED (2). This is the only way to permanently stop reconnection. ```APIDOC ## `close()` — Permanently close the connection Stops all reconnect timers and closes the underlying `EventSource`. Sets `readyState` to `CLOSED` (2). This is the only way to permanently stop reconnection — if you want the server to initiate a close, send an application-level message that triggers `es.close()` on the client. ```ts import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.addEventListener('message', (event: MessageEvent) => { const payload = JSON.parse(event.data); if (payload.type === 'DONE') { es.close(); console.log('Stream closed. readyState:', es.readyState); // 2 (CLOSED) } }); ``` ``` -------------------------------- ### Subscribe to Named Events Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Use `addEventListener` to subscribe to specific SSE event types, identified by the `event:` field. Listeners are automatically maintained across reconnections. ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/stream'); // Listen for a custom named event: "event: stock-update" const onStockUpdate = (event: MessageEvent) => { const data = JSON.parse(event.data); console.log(`${data.symbol}: $${data.price}`); // Output: AAPL: $193.45 }; es.addEventListener('stock-update', onStockUpdate); // Standard open / error events also work es.addEventListener('open', () => console.log('stream open')); es.addEventListener('error', (e) => console.error('stream error', e)); ``` -------------------------------- ### onerror — Connection error callback Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Callback invoked when the connection drops or the server returns an error. The library automatically schedules a reconnect after this callback. ```APIDOC ## onerror ### Description Invoked when the connection drops or the server returns an error response. After this callback fires, the library automatically schedules a reconnect — you do not need to create a new instance. ### Method Assignment to `es.onerror` property. ### Parameters - **event** (Event) - The event object. ### Request Example ```javascript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.onerror = (event) => { console.warn('Connection lost, will retry automatically:', event); console.log('readyState:', es.readyState); // 0 }; ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Handle Default Messages Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt The `onmessage` handler processes any SSE events that do not have a specific `event:` field. It receives a `MessageEvent` containing the data payload and the last event ID. ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.onmessage = (event: MessageEvent) => { console.log('Event ID :', event.lastEventId); console.log('Payload :', event.data); // Example output: // Event ID : 42 // Payload : {"temperature":21.3,"unit":"C"} }; ``` -------------------------------- ### Stop ReconnectingEventSource Connection Source: https://github.com/fanout/reconnecting-eventsource/blob/master/README.md The client must explicitly call the `close()` method to stop the connection. This is necessary to control the reconnection behavior from the client side. ```javascript es.close(); ``` -------------------------------- ### Handle Connection Errors Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt The `onerror` callback is triggered when the connection fails or the server returns an error. The library automatically schedules a reconnect after this callback, so no manual reconnection logic is needed. ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.onerror = (event: Event) => { console.warn('Connection lost, will retry automatically:', event); // readyState transitions back to CONNECTING (0) while retrying console.log('readyState:', es.readyState); // 0 }; ``` -------------------------------- ### Handle EventSourceNotAvailableError - TypeScript Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Catches EventSourceNotAvailableError if EventSource is not globally available, allowing for a fallback using an explicit polyfill. ```typescript import ReconnectingEventSource, { EventSourceNotAvailableError } from 'reconnecting-eventsource'; import EventSourcePolyfill from 'eventsource'; // npm install eventsource let es: ReconnectingEventSource; try { es = new ReconnectingEventSource('https://api.example.com/events'); } catch (err) { if (err instanceof EventSourceNotAvailableError) { // Retry with an explicit polyfill (required in Node.js < 22, IE, older Edge) es = new ReconnectingEventSource('https://api.example.com/events', { eventSourceClass: EventSourcePolyfill as unknown as typeof EventSource, }); } else { throw err; } } ``` -------------------------------- ### Close Connection - TypeScript Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Permanently closes the EventSource connection and stops all reconnection timers. Sets readyState to CLOSED (2). ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/events'); es.addEventListener('message', (event: MessageEvent) => { const payload = JSON.parse(event.data); if (payload.type === 'DONE') { es.close(); console.log('Stream closed. readyState:', es.readyState); // 2 (CLOSED) } }); ``` -------------------------------- ### removeEventListener(type, listener) Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Removes a previously registered listener for a given event type. Once all listeners for a type are removed, the library also removes the underlying listener from the internal EventSource instance. ```APIDOC ## `removeEventListener(type, listener)` — Named event unsubscription Removes a previously registered listener for a given event type. Once all listeners for a type are removed, the library also removes the underlying listener from the internal `EventSource` instance. ```ts import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/stream'); const handler = (event: MessageEvent) => { console.log('received:', event.data); }; es.addEventListener('update', handler); // Later — stop listening for 'update' events es.removeEventListener('update', handler); console.log('handler removed; no more update events will be processed'); ``` ``` -------------------------------- ### Remove Event Listener - TypeScript Source: https://context7.com/fanout/reconnecting-eventsource/llms.txt Removes a specific event listener for a given event type. Ensure the listener function is the same one that was added. ```typescript import ReconnectingEventSource from 'reconnecting-eventsource'; const es = new ReconnectingEventSource('https://api.example.com/stream'); const handler = (event: MessageEvent) => { console.log('received:', event.data); }; es.addEventListener('update', handler); // Later — stop listening for 'update' events es.removeEventListener('update', handler); console.log('handler removed; no more update events will be processed'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.