UNPKG

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