import WebSocketClient from "./clients/WebSocketClient.js";
import { log } from "./utils/log.js";
const Client = "u" > typeof __rspack_dev_server_client__ ? void 0 !== __rspack_dev_server_client__.default ? __rspack_dev_server_client__.default : __rspack_dev_server_client__ : WebSocketClient;
let retries = 0;
let maxRetries = 10;
let client = null;
let timeout;
function socket(url, handlers, reconnect) {
    client = new Client(url);
    client.onOpen(()=>{
        retries = 0;
        if (timeout) clearTimeout(timeout);
        if (void 0 !== reconnect) maxRetries = reconnect;
    });
    client.onClose(()=>{
        if (0 === retries) handlers.close();
        client = null;
        if (retries < maxRetries) {
            const retryInMs = 1000 * Math.pow(2, retries) + 100 * Math.random();
            retries += 1;
            log.info('Trying to reconnect...');
            timeout = setTimeout(()=>{
                socket(url, handlers, reconnect);
            }, retryInMs);
        }
    });
    client.onMessage((data)=>{
        const message = JSON.parse(data);
        if (handlers[message.type]) handlers[message.type](message.data, message.params);
    });
}
const client_src_socket = socket;
export default client_src_socket;
export { client };
