@andreasnicolaou/reactive-event-source
Version:
A lightweight reactive wrapper around EventSource using RxJS, providing automatic reconnection and buffering.
76 lines (75 loc) • 2.92 kB
TypeScript
import { Observable } from 'rxjs';
export type EventSourceEventType = 'open' | 'message' | 'error' | (string & {});
export type EventSourceOptions = {
maxRetries: number;
initialDelay: number;
maxDelay: number;
connectionTimeout?: number;
withCredentials?: boolean;
};
export declare class ReactiveEventSource {
private readonly destroy$;
private readonly eventSource$;
private readonly eventSubjects;
private lastEventSource;
private readonly options;
private readonly url;
/**
* Creates an instance of reactive event source.
* @param url - The URL or URL object for the SSE connection.
* @param options - Optional configuration for retry behavior and credentials.
*/
constructor(url: string | URL, options?: Partial<EventSourceOptions>);
/**
* Gets the current connection state of the EventSource
* @returns {0 | 1 | 2} The ready state:
* - 0 (CONNECTING): The connection is being established
* - 1 (OPEN): The connection is active and receiving events
* - 2 (CLOSED): The connection is closed or failed
* @author Andreas Nicolaou
* @memberof ReactiveEventSource
*/
get readyState(): number;
/**
* Determines if credentials (cookies, HTTP auth) are sent with requests
* @returns {boolean} True if credentials are being sent, false otherwise
* @author Andreas Nicolaou
* @memberof ReactiveEventSource
*/
get withCredentials(): boolean;
/**
* Gets the resolved URL string used for the EventSource connection
* @returns {string} The fully qualified URL as a string
* @author Andreas Nicolaou
* @memberof ReactiveEventSource
*/
get URL(): string;
/**
* Closes the SSE connection and completes all internal subjects and observables.
* @author Andreas Nicolaou
* @memberof ReactiveEventSource
*/
close(): void;
/**
* Subscribes to a specific SSE event type and returns it as an Observable.
* @param eventType - The name of the event to listen for (e.g., "message", "error", "open").
* @returns An Observable that emits events of the given type.
* @author Andreas Nicolaou
* @memberof ReactiveEventSource
*/
on(eventType?: EventSourceEventType): Observable<MessageEvent>;
/**
* Creates an observable EventSource instance with optional credentials and automatic reconnection.
* @returns An observable that manages the EventSource lifecycle and reconnection strategy.
* @author Andreas Nicolaou
* @memberof ReactiveEventSource
*/
private createEventSource;
/**
* Sets up listeners on the EventSource for core events (open, message, error),
* forwarding those events to the corresponding subjects for subscribers.
* @author Andreas Nicolaou
* @memberof ReactiveEventSource
*/
private setupEventForwarding;
}