askexperts
Version:
AskExperts SDK: build and use AI experts - ask them questions and pay with bitcoin on an open protocol
73 lines • 2.34 kB
JavaScript
/**
* Browser implementation of WebSocket
*/
/**
* WebSocket wrapper for browser environments
* This provides a compatible interface with the 'ws' package
*/
export class WebSocket {
/**
* Create a new WebSocket
* @param url - WebSocket URL to connect to
* @param options - Connection options
*/
constructor(url, options) {
this.eventHandlers = new Map();
// In browsers, we need to handle headers differently since WebSocket constructor
// doesn't accept headers directly
let wsUrl = url;
// If headers are provided, append them as query parameters
if (options?.headers) {
const separator = url.includes('?') ? '&' : '?';
const authHeader = options.headers['Authorization'];
if (authHeader) {
wsUrl = `${url}${separator}authorization=${encodeURIComponent(authHeader)}`;
}
}
// Create the native WebSocket
this.socket = new globalThis.WebSocket(wsUrl);
// Set up event handlers
this.socket.onopen = (event) => this.triggerEvent('open', event);
this.socket.onmessage = (event) => this.triggerEvent('message', event.data);
this.socket.onclose = (event) => this.triggerEvent('close', event);
this.socket.onerror = (event) => this.triggerEvent('error', new Error('WebSocket error'));
}
/**
* Register an event handler
* @param event - Event name
* @param callback - Event handler function
*/
on(event, callback) {
if (!this.eventHandlers.has(event)) {
this.eventHandlers.set(event, new Set());
}
this.eventHandlers.get(event).add(callback);
}
/**
* Trigger an event
* @param event - Event name
* @param args - Event arguments
*/
triggerEvent(event, ...args) {
const handlers = this.eventHandlers.get(event);
if (handlers) {
for (const handler of handlers) {
handler(...args);
}
}
}
/**
* Send data through the WebSocket
* @param data - Data to send
*/
send(data) {
this.socket.send(data);
}
/**
* Close the WebSocket connection
*/
close() {
this.socket.close();
}
}
//# sourceMappingURL=browser.js.map