This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 125
/
HappyPlugin.js
375 lines (307 loc) · 10.8 KB
/
HappyPlugin.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
var fs = require('fs');
var path = require('path');
var async = require('async');
var assert = require('assert');
var HappyThreadPool = require('./HappyThreadPool');
var HappyForegroundThreadPool = require('./HappyForegroundThreadPool');
var HappyFSCache = require('./HappyFSCache');
var HappyUtils = require('./HappyUtils');
var WebpackUtils = require('./WebpackUtils');
var OptionParser = require('./OptionParser');
var JSONSerializer = require('./JSONSerializer');
var SourceMapSerializer = require('./SourceMapSerializer');
var fnOnce = require('./fnOnce');
var ErrorSerializer = require('./ErrorSerializer');
var pkg = require('../package.json');
function HappyPlugin(userConfig) {
if (!(this instanceof HappyPlugin)) {
return new HappyPlugin(userConfig);
}
this.name = 'HappyPack';
this.state = {
started: false,
loaders: [],
baseLoaderRequest: '',
foregroundThreadPool: null,
verbose: false,
debug: false,
};
this.config = OptionParser(userConfig, {
id: { type: 'string', default: '1' },
compilerId: { type: 'string', default: 'default' },
tempDir: { type: 'string', default: '.happypack' },
threads: { type: 'number', default: 3 },
threadPool: { type: 'object', default: null },
cache: { type: 'boolean', default: true },
cachePath: { type: 'string' },
cacheContext: { type: 'object', default: {} },
cacheSignatureGenerator: { type: 'function' },
verbose: { type: 'boolean', default: true },
verboseWhenProfiling: { type: 'boolean', default: false },
debug: { type: 'boolean', default: process.env.DEBUG === '1' },
enabled: { type: 'boolean', default: true },
loaders: {
validate: function(value) {
if (!Array.isArray(value)) {
return 'Loaders must be an array!';
}
else if (value.length === 0) {
return 'You must specify at least one loader!';
}
else if (value.some(function(loader) {
return typeof loader !== 'string' && !loader.path && !loader.loader;
})) {
return 'Loader must have a @path or @loader property or be a string.'
}
},
}
}, "HappyPack[" + this.id + "]");
this.id = this.config.id;
HappyUtils.mkdirSync(this.config.tempDir);
return this;
}
HappyPlugin.prototype.apply = function(compiler) {
var that, engageWatchMode;
if (this.config.enabled === false) {
return;
}
that = this;
this.state.verbose = isVerbose(compiler, this);
this.state.debug = isDebug(compiler, this);
this.threadPool = this.config.threadPool || HappyThreadPool({
id: this.id,
size: this.config.threads,
verbose: this.state.verbose,
debug: this.state.debug,
});
this.cache = HappyFSCache({
id: this.id,
path: this.config.cachePath ?
path.resolve(this.config.cachePath.replace(/\[id\]/g, this.id)) :
path.resolve(this.config.tempDir, 'cache--' + this.id + '.json'),
verbose: this.state.verbose,
generateSignature: this.config.cacheSignatureGenerator
});
engageWatchMode = fnOnce(function() {
// Once the initial build has completed, we create a foreground worker and
// perform all compilations in this thread instead:
compiler.plugin('done', function() {
that.state.foregroundThreadPool = HappyForegroundThreadPool({
loaders: that.state.loaders,
});
that.state.foregroundThreadPool.start(that.config.compilerId, compiler, '{}', Function.prototype);
});
// TODO: anything special to do here?
compiler.plugin('failed', function(err) {
console.warn('Fatal watch error!!!', err);
});
});
compiler.plugin('watch-run', function(_, done) {
if (engageWatchMode() === fnOnce.ALREADY_CALLED) {
done();
}
else {
that.start(compiler, done);
}
});
compiler.plugin('run', that.start.bind(that));
// cleanup hooks:
compiler.plugin('done', that.stop.bind(that));
if (compiler.options.bail) {
compiler.plugin('compilation', function(compilation) {
compilation.plugin('failed-module', that.stop.bind(that));
});
}
};
HappyPlugin.prototype.start = function(compiler, done) {
var that = this;
if (that.state.verbose) {
console.log('Happy[%s]: Version: %s. Using cache? %s. Threads: %d%s',
that.id, pkg.version,
that.config.cache ? 'Yes' : 'No',
that.threadPool.size,
that.config.threadPool ? ' (shared pool)' : ''
);
}
async.series([
function normalizeLoaders(callback) {
var loaders = that.config.loaders;
assert(loaders && loaders.length > 0,
"HappyPlugin[" + that.id + "]; you have not specified any loaders " +
"and there is no matching loader entry with this id."
);
that.state.loaders = loaders.reduce(function(list, entry) {
return list.concat(WebpackUtils.normalizeLoader(entry));
}, []);
callback(null);
},
function resolveLoaders(callback) {
var loaderPaths = that.state.loaders.map(function(loader) {
return loader.path;
});
WebpackUtils.resolveLoaders(compiler, loaderPaths, function(err, resolvedPaths) {
if (err) return callback(err);
resolvedPaths.forEach(function (resolvedPath, index) {
var loader = that.state.loaders[index];
loader.path = resolvedPath;
loader.request = (loader.query) ? loader.path + loader.query : loader.path;
});
that.state.baseLoaderRequest = that.state.loaders.map(function(loader) {
return loader.path + (loader.query || '');
}).join('!');
callback();
});
},
function loadCache(callback) {
if (that.config.cache) {
that.cache.load({
loaders: that.state.loaders,
external: that.config.cacheContext
});
}
callback();
},
function launchAndConfigureThreads(callback) {
var serializedOptions;
var compilerOptions = HappyPlugin.extractCompilerOptions(compiler.options);
try {
serializedOptions = JSONSerializer.serialize(compilerOptions);
}
catch(e) {
console.error('Happy[%s]: Internal error; unable to serialize options!!!', that.id);
console.error(compilerOptions);
return callback(e);
}
that.threadPool.start(that.config.compilerId, compiler, serializedOptions, callback);
},
function markStarted(callback) {
if (that.state.verbose) {
console.log('Happy[%s]: All set; signaling webpack to proceed.', that.id);
}
that.state.started = true;
callback();
}
], done);
};
HappyPlugin.prototype.stop = function() {
assert(this.state.started, "HappyPlugin cannot be stopped until it is started!");
if (this.config.cache) {
this.cache.save();
}
this.threadPool.stop(this.config.compilerId);
};
HappyPlugin.prototype.compile = function(loader, loaderContext, done) {
if (this.state.foregroundThreadPool) {
return compileInForeground.call(this, loader, loaderContext, done);
}
else {
return compileInBackground.call(this, loader, loaderContext, done);
}
};
HappyPlugin.prototype.generateRequest = function(resource) {
return this.state.baseLoaderRequest + '!' + resource;
};
// export this so that users get to override if needed
HappyPlugin.SERIALIZABLE_OPTIONS = [
'amd',
'bail',
'cache',
'context',
'entry',
'externals',
'debug',
'devtool',
'devServer',
'loader',
'module',
'node',
'output',
'profile',
'recordsPath',
'recordsInputPath',
'recordsOutputPath',
'resolve',
'resolveLoader',
'target',
'watch',
];
HappyPlugin.extractCompilerOptions = function(options) {
var ALLOWED_KEYS = HappyPlugin.SERIALIZABLE_OPTIONS;
return Object.keys(options).reduce(function(hsh, key) {
if (ALLOWED_KEYS.indexOf(key) > -1) {
hsh[key] = options[key];
}
return hsh;
}, {});
};
// convenience accessor to relieve people from requiring the file directly:
HappyPlugin.ThreadPool = HappyThreadPool;
function isVerbose(compiler, plugin) {
return plugin.config.verbose && (
!compiler.options.profile ||
plugin.config.verboseWhenProfiling
);
};
function isDebug(compiler, plugin) {
return plugin.config.debug && (
!compiler.options.profile ||
plugin.config.verboseWhenProfiling
);
};
function compileInBackground(loader, loaderContext, done) {
var filePath = loaderContext.resourcePath;
if (!this.cache.hasChanged(filePath) && !this.cache.hasErrored(filePath)) {
var cached = readFromCache(this.cache, filePath);
return done(null, cached.sourceCode, cached.sourceMap);
}
if (this.state.debug) {
console.warn('File has changed; re-compiling... (%s)', filePath);
}
compileAndUpdateCache.call(this, this.threadPool, loader, loaderContext, done);
}
// compile the source using the foreground worker instead of sending to the
// background threads:
function compileInForeground(loader, loaderContext, done) {
compileAndUpdateCache.call(this, this.state.foregroundThreadPool, loader, loaderContext, done);
}
function readFromCache(cache, filePath) {
var cached = {};
var sourceCodeFilePath = cache.getCompiledSourceCodePath(filePath);
var sourceMapFilePath = cache.getCompiledSourceMapPath(filePath);
cached.sourceCode = fs.readFileSync(sourceCodeFilePath, 'utf-8');
if (HappyUtils.isReadable(sourceMapFilePath)) {
cached.sourceMap = SourceMapSerializer.deserialize(
fs.readFileSync(sourceMapFilePath, 'utf-8')
);
}
return cached;
}
function compileAndUpdateCache(threadPool, loader, loaderContext, done) {
var cache = this.cache;
var filePath = loaderContext.resourcePath;
// Compute the signature /before/ compiling to avoid a race condition where the compiled file's source is
// updated in the filesytem (externally, e.g. via git) before computing the signature, which would cause
// a stale compiled file to be stuck in the cache.
var signature = cache.generateSignature(filePath);
threadPool.compile(loaderContext.remoteLoaderId, loader, {
loaders: this.state.loaders,
compiledPath: path.resolve(this.config.tempDir, cache.getCompiledSourceCodePath(filePath) || HappyUtils.generateCompiledPath(filePath)),
loaderContext: loaderContext,
}, function(result) {
var contents = fs.readFileSync(result.compiledPath, 'utf-8')
var compiledMap;
if (!result.success) {
var error = ErrorSerializer.deserialize(contents);
cache.set(filePath, error, null, signature);
done(error);
}
else {
cache.set(filePath, null, result.compiledPath, signature);
compiledMap = SourceMapSerializer.deserialize(
fs.readFileSync(cache.getCompiledSourceMapPath(filePath), 'utf-8')
);
done(null, contents, compiledMap);
}
});
};
module.exports = HappyPlugin;