UNPKG

2.04 kBJavaScriptView Raw
1/* global __webpack_dev_server_client__ */
2
3import WebSocketClient from "./clients/WebSocketClient.js";
4import { log } from "./utils/log.js";
5
6// this WebsocketClient is here as a default fallback, in case the client is not injected
7/* eslint-disable camelcase */
8var Client =
9// eslint-disable-next-line no-nested-ternary
10typeof __webpack_dev_server_client__ !== "undefined" ? typeof __webpack_dev_server_client__.default !== "undefined" ? __webpack_dev_server_client__.default : __webpack_dev_server_client__ : WebSocketClient;
11/* eslint-enable camelcase */
12
13var retries = 0;
14var maxRetries = 10;
15
16// Initialized client is exported so external consumers can utilize the same instance
17// It is mutable to enforce singleton
18// eslint-disable-next-line import/no-mutable-exports
19export var client = null;
20
21/**
22 * @param {string} url
23 * @param {{ [handler: string]: (data?: any, params?: any) => any }} handlers
24 * @param {number} [reconnect]
25 */
26var socket = function initSocket(url, handlers, reconnect) {
27 client = new Client(url);
28 client.onOpen(function () {
29 retries = 0;
30 if (typeof reconnect !== "undefined") {
31 maxRetries = reconnect;
32 }
33 });
34 client.onClose(function () {
35 if (retries === 0) {
36 handlers.close();
37 }
38
39 // Try to reconnect.
40 client = null;
41
42 // After 10 retries stop trying, to prevent logspam.
43 if (retries < maxRetries) {
44 // Exponentially increase timeout to reconnect.
45 // Respectfully copied from the package `got`.
46 // eslint-disable-next-line no-restricted-properties
47 var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
48 retries += 1;
49 log.info("Trying to reconnect...");
50 setTimeout(function () {
51 socket(url, handlers, reconnect);
52 }, retryInMs);
53 }
54 });
55 client.onMessage(
56 /**
57 * @param {any} data
58 */
59 function (data) {
60 var message = JSON.parse(data);
61 if (handlers[message.type]) {
62 handlers[message.type](message.data, message.params);
63 }
64 });
65};
66export default socket;
\No newline at end of file