/** * @license * Copyright 2024 Nuraly, Laabidi Aymen * SPDX-License-Identifier: MIT */ import type { ChatbotProvider, ProviderCapabilities, ProviderConfig, ChatbotContext } from '../core/types.js'; /** * Message type mapping for the native WebSocket JSON protocol. * Each key maps a logical type to the wire string used in the `type` field. */ export interface NativeWebSocketMessageTypes { /** Type value for outgoing messages (default: 'message:send') */ send: string; /** Type value for complete response (default: 'message:response') */ response: string; /** Type value for streaming chunks (default: 'message:stream') */ stream?: string; /** Type value for error messages (default: 'message:error') */ error?: string; /** Type value for typing indicator start (default: 'typing:start') */ typingStart?: string; /** Type value for typing indicator end (default: 'typing:end') */ typingEnd?: string; /** Type value for outgoing heartbeat (default: 'ping') */ ping?: string; /** Type value for incoming heartbeat response (default: 'pong') */ pong?: string; /** Type value for tool/function call start (default: 'tool:call') */ toolCall?: string; /** Type value for tool/function call end (default: 'tool:end') */ toolCallEnd?: string; } /** * Native WebSocket provider configuration */ export interface NativeWebSocketProviderConfig extends ProviderConfig { /** WebSocket URL (ws:// or wss://) */ url: string; /** Sub-protocols for the WebSocket constructor */ protocols?: string | string[]; /** Message type mapping */ messageTypes: NativeWebSocketMessageTypes; /** JSON field name used for message routing (default: 'type') */ typeField?: string; /** Query parameters appended to the URL (useful for auth tokens) */ queryParams?: Record; /** Auto-reconnect on disconnect (default: true) */ autoReconnect?: boolean; /** Maximum reconnection attempts (default: 5) */ maxReconnectAttempts?: number; /** Base delay for reconnection in ms (default: 1000) */ reconnectBaseDelay?: number; /** Maximum delay for reconnection in ms (default: 30000) */ reconnectMaxDelay?: number; /** Connection timeout in ms (default: 10000) */ connectionTimeout?: number; /** Response timeout in ms (default: 30000) */ responseTimeout?: number; /** Enable heartbeat ping/pong (default: true) */ enableHeartbeat?: boolean; /** Heartbeat interval in ms (default: 30000) */ heartbeatInterval?: number; /** Heartbeat pong timeout in ms (default: 10000) */ heartbeatTimeout?: number; /** Build custom payload from message and context */ buildPayload?: (text: string, context: ChatbotContext) => any; /** Extract message string from response data */ extractMessage?: (data: any) => string; /** Called when connection state changes */ onConnectionChange?: (connected: boolean) => void; /** Called on each reconnect attempt */ onReconnectAttempt?: (attempt: number, maxAttempts: number) => void; } /** * Native WebSocket provider for real-time chatbot communication. * * Uses the browser's built-in WebSocket API with a JSON envelope protocol. * Zero additional dependencies — works with any backend that speaks plain * WebSocket with JSON messages (Go, Rust, Python/FastAPI, Java/Quarkus, etc.). * * @example Basic usage * ```typescript * const provider = new NativeWebSocketProvider(); * await provider.connect({ * url: 'wss://api.example.com/chat', * messageTypes: { * send: 'chat:message', * response: 'chat:response', * stream: 'chat:stream' * } * }); * ``` * * @example With auth via query params * ```typescript * const provider = new NativeWebSocketProvider(); * await provider.connect({ * url: 'wss://api.example.com/chat', * queryParams: { token: 'my-jwt-token' }, * messageTypes: { * send: 'ask', * response: 'answer' * } * }); * ``` * * @example Custom type field * ```typescript * const provider = new NativeWebSocketProvider(); * await provider.connect({ * url: 'wss://api.example.com/ws', * typeField: 'event', * messageTypes: { * send: 'user_message', * response: 'bot_response', * stream: 'bot_chunk' * } * }); * ``` */ export declare class NativeWebSocketProvider implements ChatbotProvider { readonly id = "native-websocket"; readonly name = "Native WebSocket Provider"; readonly capabilities: ProviderCapabilities; protected ws: WebSocket | null; protected config: NativeWebSocketProviderConfig | null; protected connected: boolean; /** Called when a tool/function call is detected */ onToolCall?: (name: string) => void; /** Called when a tool/function call ends */ onToolCallEnd?: () => void; protected responseResolvers: Map void; reject: (error: Error) => void; chunks: string[]; isStreaming: boolean; }>; protected reconnectAttempt: number; protected reconnectTimer: ReturnType | null; protected heartbeatTimer: ReturnType | null; protected pongTimer: ReturnType | null; protected intentionalClose: boolean; protected messageListeners: Map void>>; connect(config: NativeWebSocketProviderConfig): Promise; protected createConnection(): Promise; protected buildUrl(): string; protected handleMessage(event: MessageEvent): void; private parseMessageData; private dispatchToListeners; private handleResponseMessage; private handleStreamMessage; private handleErrorMessage; protected getLatestResolver(): { resolve: (value: string) => void; reject: (error: Error) => void; chunks: string[]; isStreaming: boolean; } | null | undefined; protected extractMessageId(data: any): string; protected extractMessageContent(data: any): string; protected startHeartbeat(): void; protected handlePong(): void; protected stopHeartbeat(): void; protected attemptReconnect(): void; disconnect(): Promise; isConnected(): boolean; sendMessage(text: string, context: ChatbotContext): AsyncIterator; /** * Send a typed JSON message over the WebSocket. */ send(type: string, payload?: Record): void; /** * Subscribe to messages of a specific type. Returns an unsubscribe function. */ onMessage(type: string, callback: (data: any) => void): () => void; /** * Get the underlying WebSocket instance for advanced usage. */ getWebSocket(): WebSocket | null; protected buildPayload(text: string, context: ChatbotContext, messageId: string): any; protected formatError(title: string, description: string): string; onError(error: Error): void; } //# sourceMappingURL=native-ws-provider.d.ts.map