-
Notifications
You must be signed in to change notification settings - Fork 51
/
index.js
executable file
·326 lines (287 loc) · 7.92 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/* jshint node:true */
const crypto = require('crypto');
const lr = require('tiny-lr');
const portfinder = require('portfinder');
const anymatch = require('anymatch');
const servers = {};
const schema = require('./schema.json');
let {validate} = require('schema-utils');
const PLUGIN_NAME = 'LiveReloadPlugin';
class LiveReloadPlugin {
constructor(options = {}) {
// Fallback to schema-utils v1 for webpack v4
if (!validate)
validate = require('schema-utils');
validate(schema, options, {name: 'Livereload Plugin'});
this.defaultPort = 35729;
this.options = Object.assign({
protocol: '',
port: this.defaultPort,
hostname: '" + location.hostname + "',
ignore: null,
quiet: false,
useSourceHash: false,
useSourceSize: false,
appendScriptTag: false,
delay: 0,
}, options);
// Random alphanumeric string appended to id to allow multiple instances of live reload
this.instanceId = crypto.randomBytes(8).toString('hex');
this.lastHash = null;
this.lastChildHashes = [];
this.server = null;
this.sourceHashs = {};
this.sourceSizes = {};
this.webpack = null;
this.infrastructureLogger = null;
this.isWebpack4 = false;
}
apply(compiler) {
this.webpack = compiler.webpack ? compiler.webpack : require('webpack');
this.infrastructureLogger = compiler.getInfrastructureLogger ? compiler.getInfrastructureLogger(PLUGIN_NAME) : null;
this.isWebpack4 = compiler.webpack ? false : typeof compiler.resolvers !== 'undefined';
compiler.hooks.compilation.tap(PLUGIN_NAME, this._applyCompilation.bind(this));
compiler.hooks.watchRun.tapAsync(PLUGIN_NAME, this._start.bind(this));
compiler.hooks.afterEmit.tap(PLUGIN_NAME, this._afterEmit.bind(this));
compiler.hooks.emit.tap(PLUGIN_NAME, this._emit.bind(this));
compiler.hooks.failed.tap(PLUGIN_NAME, this._failed.bind(this));
}
/**
* @param a1
* @param a2
* @returns {boolean|*}
*/
static arraysEqual(a1, a2) {
return a1.length === a2.length && a1.every((v,i) => v === a2[i])
}
/**
* @param str
* @returns {string}
*/
static generateHashCode(str) {
const hash = crypto.createHash('sha256');
hash.update(str);
return hash.digest('hex');
}
/**
*
* @param compilation
* @returns {*}
* @private
*/
_applyCompilation(compilation) {
if (this.isWebpack4) {
return compilation.mainTemplate.hooks.startup.tap(PLUGIN_NAME, this._scriptTag.bind(this));
}
this.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation).renderRequire.tap(PLUGIN_NAME, this._scriptTag.bind(this));
}
/**
* @param watching
* @param cb
* @private
*/
_start(watching, cb) {
if (servers[this.options.port]) {
this.server = servers[this.options.port];
return cb();
}
const listen = (err = null, port = null) => {
if (err) return cb(err);
this.options.port = port || this.options.port;
this.server = servers[this.options.port] = lr({
...this.options,
errorListener: (err) => {
this.logger.error(`Live Reload disabled: ${err.message}`);
if (err.code !== 'EADDRINUSE') {
this.logger.error(err.stack);
}
cb();
},
});
this.server.listen(this.options.port, (err) => {
if (!err && !this.options.quiet) {
this.logger.info(`Live Reload listening on port ${this.options.port}`);
}
cb();
});
};
if(this.options.port === 0) {
portfinder.basePort = this.defaultPort;
portfinder.getPort(listen);
} else {
listen();
}
}
/**
* @returns {boolean}
* @private
*/
_isRunning() {
return !!this.server;
}
/**
* @private
* @param compilation
*/
_afterEmit(compilation) {
const hash = compilation.hash;
const childHashes = (compilation.children || []).map(child => child.hash);
const include = Object.entries(compilation.assets)
.filter(this._fileIgnoredOrNotEmitted.bind(this))
.filter(this._fileSizeDoesntMatch.bind(this))
.filter(this._fileHashDoesntMatch.bind(this))
.map((data) => data[0])
;
if (
this._isRunning()
&& include.length > 0
&& (hash !== this.lastHash || !LiveReloadPlugin.arraysEqual(childHashes, this.lastChildHashes))
) {
this.lastHash = hash;
this.lastChildHashes = childHashes;
setTimeout(() => {
this.server.notifyClients(include);
}, this.options.delay);
}
}
/**
* @private
* @param compilation
*/
_emit(compilation) {
Object.entries(compilation.assets).forEach(this._calculateSourceHash.bind(this));
}
/**
* @private
*/
_failed() {
this.lastHash = null;
this.lastChildHashes = [];
this.sourceHashs = {};
this.sourceSizes = {};
}
/**
* @returns {string}
* @private
*/
_autoloadJs() {
const protocol = this.options.protocol;
const fullProtocol = `${protocol}${protocol ? ':' : ''}`
return (
`
// webpack-livereload-plugin
(function() {
if (typeof window === "undefined") { return };
var id = "webpack-livereload-plugin-script-${this.instanceId}";
if (document.getElementById(id)) { return; }
var el = document.createElement("script");
el.id = id;
el.async = true;
el.src = "${fullProtocol}//${this.options.hostname}:${this.options.port}/livereload.js";
document.getElementsByTagName("head")[0].appendChild(el);
console.log("[Live Reload] enabled");
}());
`
);
}
/**
* @param source
* @returns {*}
* @private
*/
_scriptTag(source) {
if (this.options.appendScriptTag && this._isRunning()) {
return this._autoloadJs() + source;
}
else {
return source;
}
}
/**
* @param data
* @returns {boolean|*}
* @private
*/
_fileIgnoredOrNotEmitted(data) {
const size = this.isWebpack4 ? data[1].emitted : data[1].size();
if (Array.isArray(this.options.ignore)) {
return !anymatch(this.options.ignore, data[0]) && size;
}
return !data[0].match(this.options.ignore) && size;
}
/**
* Check compiled source size
*
* @param data
* @returns {boolean}
* @private
*/
_fileSizeDoesntMatch(data) {
if (!this.options.useSourceSize)
return true;
if (this.sourceSizes[data[0]] === data[1].size()) {
return false;
}
this.sourceSizes[data[0]] = data[1].size();
return true;
}
/**
* Check compiled source hash
*
* @param data
* @returns {boolean}
* @private
*/
_fileHashDoesntMatch(data) {
if (!this.options.useSourceHash)
return true;
if (
this.sourceHashs[data[0]] !== undefined
&& this.sourceHashs[data[0]].hash === this.sourceHashs[data[0]].calculated
) {
return false;
}
// Update source hash
this.sourceHashs[data[0]].hash = this.sourceHashs[data[0]].calculated;
return true;
}
/**
* Calculate compiled source hash
*
* @param data
* @returns {void}
* @private
*/
_calculateSourceHash(data) {
if (!this.options.useSourceHash) return;
// Calculate source hash
this.sourceHashs[data[0]] = {
hash: this.sourceHashs[data[0]] ? this.sourceHashs[data[0]].hash : null,
calculated: LiveReloadPlugin.generateHashCode(data[1].source())
};
}
/**
* @private
*/
get logger() {
if (this.infrastructureLogger) {
return this.infrastructureLogger;
}
// Fallback logger webpack v3
return {
error: console.error,
warn: console.log,
info: console.log,
log: console.log,
debug: console.log,
trace: console.log,
group: console.log,
groupEnd: console.log,
groupCollapsed: console.log,
status: console.log,
clear: console.log,
profile: console.log,
}
}
}
module.exports = LiveReloadPlugin;