WPSSocket.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* global ʎɐɹɔosǝʌɹǝs */
  2. /**
  3. * Initializes a socket server for HMR for webpack-plugin-serve.
  4. * @param {function(*): void} messageHandler A handler to consume Webpack compilation messages.
  5. * @returns {void}
  6. */
  7. function initWPSSocket(messageHandler) {
  8. /**
  9. * The hard-coded options injection key from webpack-plugin-serve.
  10. *
  11. * [Ref](https://github.com/shellscape/webpack-plugin-serve/blob/aeb49f14e900802c98df4a4607a76bc67b1cffdf/lib/index.js#L258)
  12. * @type {Object | undefined}
  13. */
  14. let options;
  15. try {
  16. options = ʎɐɹɔosǝʌɹǝs;
  17. } catch (e) {
  18. // Bail out because this indicates the plugin is not included
  19. return;
  20. }
  21. const { ClientSocket } = require('webpack-plugin-serve/lib/client/ClientSocket');
  22. const { address, client = {}, secure } = options;
  23. const protocol = secure ? 'wss' : 'ws';
  24. const socket = new ClientSocket(client, protocol + '://' + (client.address || address) + '/wps');
  25. socket.addEventListener('message', function listener(message) {
  26. const { action, data } = JSON.parse(message.data);
  27. switch (action) {
  28. case 'done': {
  29. messageHandler({ type: 'ok' });
  30. break;
  31. }
  32. case 'problems': {
  33. if (data.errors.length) {
  34. messageHandler({ type: 'errors', data: data.errors });
  35. } else if (data.warnings.length) {
  36. messageHandler({ type: 'warnings', data: data.warnings });
  37. }
  38. break;
  39. }
  40. default: {
  41. // Do nothing
  42. }
  43. }
  44. });
  45. }
  46. module.exports = initWPSSocket;