socket.js 2.4 KB

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