UNPKG

capacitor-cors-bypass-enhanced

Version:

Enhanced Capacitor plugin for CORS bypass with HTTP/2, HTTP/3, gRPC, GraphQL, file operations, and advanced networking features. Modular TypeScript definitions for better maintainability.

95 lines (94 loc) 3.19 kB
/** * WebSocket Manager * Handles WebSocket connections with CORS bypass */ export class WebSocketManager { constructor(notifyListeners) { this.wsConnections = new Map(); this.connectionCounter = 0; this.notifyListeners = notifyListeners; } /** * Create a WebSocket connection */ async createWebSocketConnection(options) { const connectionId = `ws_${++this.connectionCounter}`; const { url, protocols, headers, timeout = 10000 } = options; return new Promise((resolve, reject) => { const ws = new WebSocket(url, protocols); this.wsConnections.set(connectionId, ws); const timeoutId = setTimeout(() => { ws.close(); this.wsConnections.delete(connectionId); reject(new Error('WebSocket connection timeout')); }, timeout); ws.onopen = () => { clearTimeout(timeoutId); this.notifyListeners('webSocketConnectionChange', { connectionId, status: 'connected', }); resolve({ connectionId, status: 'connected', }); }; ws.onmessage = (event) => { this.notifyListeners('webSocketMessage', { connectionId, data: event.data, type: typeof event.data === 'string' ? 'text' : 'binary', }); }; ws.onerror = () => { clearTimeout(timeoutId); this.notifyListeners('webSocketConnectionChange', { connectionId, status: 'error', error: 'WebSocket connection error', }); }; ws.onclose = () => { this.wsConnections.delete(connectionId); this.notifyListeners('webSocketConnectionChange', { connectionId, status: 'disconnected', }); }; this.notifyListeners('webSocketConnectionChange', { connectionId, status: 'connecting', }); }); } /** * Close a WebSocket connection */ async closeWebSocketConnection(options) { const { connectionId } = options; const connection = this.wsConnections.get(connectionId); if (connection) { connection.close(); this.wsConnections.delete(connectionId); } } /** * Send data through WebSocket */ async sendWebSocketMessage(options) { const { connectionId, message } = options; const connection = this.wsConnections.get(connectionId); if (connection && connection.readyState === WebSocket.OPEN) { connection.send(message); } else { throw new Error('WebSocket connection not found or not open'); } } /** * Get all active WebSocket connections */ getWebSocketConnections() { return this.wsConnections; } }