//#region src/transport/types.d.ts /** * Transport Types * * Core type definitions for the transport layer abstraction. */ /** Connection lifecycle states */ type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting" | "failed"; /** Connection quality levels for monitoring */ type ConnectionQuality = "excellent" | "good" | "degraded" | "poor"; /** * Transport mode for event delivery. * * - 'websocket': WebSocket via SessionGatewayClient (default, traditional server) * - 'sse': HTTP SSE (serverless/Cloudflare Workers) */ type TransportMode = "websocket" | "sse"; /** SSE event from server */ interface SSEEvent { id?: string; event?: string; data: string; retry?: number; } /** Request options for HTTP calls */ interface RequestOptions { method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; path: string; body?: unknown; headers?: Record; signal?: AbortSignal; timeout?: number; } /** Stream subscription options */ interface StreamOptions { /** HTTP method (default: GET, use POST for streaming endpoints that accept a body) */ method?: "GET" | "POST"; path: string; /** Request body (for POST requests) */ body?: unknown; headers?: Record; /** Last event ID for resumption */ lastEventId?: string; /** Reconnection configuration */ reconnect?: ReconnectionConfig; /** Abort signal */ signal?: AbortSignal; } /** Reconnection configuration with exponential backoff */ interface ReconnectionConfig { /** Initial delay in milliseconds (default: 1000) */ initialDelayMs?: number; /** Maximum delay in milliseconds (default: 30000) */ maxDelayMs?: number; /** Backoff multiplier (default: 1.5) */ multiplier?: number; /** Jitter factor 0-1 (default: 0.2) */ jitter?: number; /** Maximum reconnection attempts (default: 10, -1 for infinite) */ maxAttempts?: number; } /** Default reconnection config */ declare const DEFAULT_RECONNECTION_CONFIG: Required; /** Transport quality metrics */ interface TransportMetrics { /** Total requests made */ requestCount: number; /** Failed requests */ failedRequests: number; /** Average latency in ms */ avgLatencyMs: number; /** Current reconnection attempt (0 if connected) */ reconnectionAttempt: number; /** Total reconnection attempts since start */ totalReconnections: number; /** Missed heartbeats in current connection */ missedHeartbeats: number; /** Last successful request timestamp */ lastRequestAt?: number; /** Connection uptime in ms */ uptimeMs: number; } /** Transport event types */ interface TransportEvents { /** Connection state changed */ stateChange: (state: ConnectionState) => void; /** Error occurred */ error: (error: Error) => void; /** Reconnecting with attempt count */ reconnecting: (attempt: number, maxAttempts: number) => void; /** Successfully reconnected */ reconnected: () => void; /** Quality changed */ qualityChange: (quality: ConnectionQuality) => void; /** Heartbeat received */ heartbeat: (timestamp: number) => void; } /** Base transport configuration */ interface TransportConfig { /** Base URL for requests */ baseUrl: string; /** Default headers for all requests */ headers?: Record; /** Request timeout in ms (default: 30000) */ timeout?: number; /** Heartbeat interval in ms for quality monitoring (default: 30000) */ heartbeatIntervalMs?: number; /** Enable automatic reconnection (default: true) */ autoReconnect?: boolean; /** Reconnection config */ reconnection?: ReconnectionConfig; } /** Subscription state */ type SubscriptionState = "active" | "paused" | "closed"; //#endregion //#region src/transport/connection-manager.d.ts interface ConnectionManagerConfig extends ReconnectionConfig { onReconnecting?: (attempt: number, maxAttempts: number) => void; onReconnected?: () => void; onFailed?: (error: Error) => void; } declare class ConnectionManager { private readonly config; private attempt; private aborted; private readonly callbacks; constructor(config?: ConnectionManagerConfig); /** * Calculate delay for current attempt with exponential backoff and jitter. */ private calculateDelay; /** * Wait for the calculated delay. */ private wait; /** * Check if more reconnection attempts are allowed. */ canRetry(): boolean; /** * Get current attempt number. */ getAttempt(): number; /** * Reset the connection manager state. */ reset(): void; /** * Abort any pending reconnection attempts. */ abort(): void; /** * Execute a reconnection attempt with the provided connect function. * Returns true if connection succeeded, false if should retry. */ reconnect(connectFn: () => Promise): Promise; /** * Run reconnection loop until success or max attempts. */ runReconnectionLoop(connectFn: () => Promise): Promise; } //#endregion //#region src/transport/interface.d.ts /** * SSE Subscription handle for consuming server-sent events. * Supports pause/resume, async iteration, and event callbacks. */ interface Subscription { /** Unique identifier for this subscription */ readonly streamId: string; /** Current subscription state */ readonly state: SubscriptionState; /** Pause event processing (events may still be buffered) */ pause(): void; /** Resume event processing */ resume(): void; /** Close the subscription and release resources */ close(): void; /** Register callback for each event */ onEvent(callback: (event: SSEEvent) => void): () => void; /** Register callback for errors */ onError(callback: (error: Error) => void): () => void; /** Register callback for reconnection attempts */ onReconnect(callback: (lastEventId: string | undefined) => void): () => void; /** Async iterator for event consumption */ [Symbol.asyncIterator](): AsyncIterator; } /** * Transport Adapter - core abstraction for network communication. * * Implementations provide HTTP request/response and SSE streaming * with connection management, reconnection, and quality monitoring. */ interface TransportAdapter { /** Current connection state */ readonly state: ConnectionState; /** Connect to the server */ connect(): Promise; /** Disconnect from the server */ disconnect(): Promise; /** Check if currently connected */ isConnected(): boolean; /** * Make an HTTP request. * Routes through the transport layer for connection management. */ request(options: RequestOptions): Promise; /** * Subscribe to an SSE stream. * Handles reconnection and Last-Event-ID resumption. */ subscribe(options: StreamOptions): Subscription; /** Register event listener, returns unsubscribe function */ on(event: K, listener: TransportEvents[K]): () => void; /** Get current transport metrics */ getMetrics(): TransportMetrics; /** Get current connection quality */ getQuality(): ConnectionQuality; } /** * Base class for transport adapters with shared functionality. * Handles event emission, metrics tracking, and connection state. */ declare abstract class BaseTransportAdapter implements TransportAdapter { protected _state: ConnectionState; protected _quality: ConnectionQuality; protected readonly config: Required; protected readonly listeners: Map unknown>>; protected metrics: TransportMetrics; protected connectionStartTime?: number; private latencySum; constructor(config: TransportConfig); get state(): ConnectionState; abstract connect(): Promise; abstract disconnect(): Promise; abstract request(options: RequestOptions): Promise; abstract subscribe(options: StreamOptions): Subscription; isConnected(): boolean; on(event: K, listener: TransportEvents[K]): () => void; getMetrics(): TransportMetrics; getQuality(): ConnectionQuality; protected emit(event: K, ...args: Parameters): void; protected setState(state: ConnectionState): void; protected setQuality(quality: ConnectionQuality): void; protected recordRequest(durationMs: number, failed: boolean): void; protected recordReconnection(): void; protected recordMissedHeartbeat(): void; protected resetHeartbeatCounter(): void; private updateQuality; protected buildUrl(path: string): string; protected buildHeaders(extra?: Record): Record; } //#endregion //#region src/transport/mock.d.ts /** Recorded request for verification */ interface RecordedRequest { method: string; path: string; body?: unknown; headers?: Record; timestamp: number; } /** Mock response configuration */ interface MockResponse { status?: number; data?: T; error?: Error; delay?: number; } /** Mock stream event */ interface MockStreamEvent { event?: string; data: string; id?: string; delay?: number; } /** Mock subscription for testing */ declare class MockSubscription implements Subscription { readonly streamId: string; private _state; private eventCallbacks; private errorCallbacks; private reconnectCallbacks; private events; private eventIndex; private closed; constructor(streamId: string, events?: MockStreamEvent[]); get state(): SubscriptionState; pause(): void; resume(): void; close(): void; onEvent(callback: (event: SSEEvent) => void): () => void; onError(callback: (error: Error) => void): () => void; onReconnect(callback: (lastEventId: string | undefined) => void): () => void; [Symbol.asyncIterator](): AsyncIterator; /** Push a new event to the stream (for testing) */ pushEvent(event: SSEEvent): void; /** Simulate an error (for testing) */ simulateError(error: Error): void; /** Simulate reconnection (for testing) */ simulateReconnect(lastEventId?: string): void; private deliverPending; /** Start delivering events automatically */ startDelivery(): void; } /** Configuration for MockTransportAdapter */ interface MockTransportConfig extends Partial { /** Auto-connect on creation (default: true) */ autoConnect?: boolean; } /** * Mock transport adapter for testing. * Provides full control over responses and streams. */ declare class MockTransportAdapter extends BaseTransportAdapter { private readonly responses; private readonly streams; private readonly subscriptions; readonly requests: RecordedRequest[]; constructor(config?: MockTransportConfig); connect(): Promise; disconnect(): Promise; request(options: RequestOptions): Promise; subscribe(options: StreamOptions): Subscription; /** Mock a response for a specific path */ mockResponse(path: string, response: MockResponse): void; /** Mock a response for a specific method and path */ mockMethodResponse(method: string, path: string, response: MockResponse): void; /** Mock a stream with events */ mockStream(path: string, events: MockStreamEvent[]): void; /** Get a subscription by stream ID */ getSubscription(streamId: string): MockSubscription | undefined; /** Get all active subscriptions */ getActiveSubscriptions(): MockSubscription[]; /** Push an event to all subscriptions for a path */ pushEventToPath(_path: string, event: SSEEvent): void; /** Clear all recorded requests */ clearRequests(): void; /** Clear all mocked responses */ clearMocks(): void; /** Get requests matching a path pattern */ getRequestsForPath(path: string): RecordedRequest[]; /** Get the last request made */ getLastRequest(): RecordedRequest | undefined; /** Simulate connection failure */ simulateDisconnect(): void; /** Simulate reconnection */ simulateReconnect(): void; } //#endregion export { TransportMode as S, StreamOptions as _, RecordedRequest as a, TransportEvents as b, TransportAdapter as c, ConnectionQuality as d, ConnectionState as f, SSEEvent as g, RequestOptions as h, MockTransportConfig as i, ConnectionManager as l, ReconnectionConfig as m, MockStreamEvent as n, BaseTransportAdapter as o, DEFAULT_RECONNECTION_CONFIG as p, MockTransportAdapter as r, Subscription as s, MockResponse as t, ConnectionManagerConfig as u, SubscriptionState as v, TransportMetrics as x, TransportConfig as y }; //# sourceMappingURL=index-Dq6SfGaX.d.ts.map