-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.js
407 lines (369 loc) · 13.4 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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
'use strict';
var path = require('path');
var cproc = require('child_process');
var through = require('through2');
var convert = require('convert-source-map');
var EventEmitter = require('events').EventEmitter;
var sm = require('source-map');
var crypto = require('crypto');
var fs = require('fs');
var _ = require('lodash');
var RSVP = require('rsvp');
var readFile = RSVP.denodeify(fs.readFile);
var has = require('./lib/has');
var readline = require('readline');
var synchd = require('synchd');
function hashStr(str) {
var hasher = crypto.createHash('sha256');
hasher.update(str);
return hasher.digest('base64').slice(0, 20);
}
var readManagerTemplate = _.once(function() {
return readFile(path.join(__dirname, 'hmr-manager-template.js'), 'utf8');
});
var validUpdateModes = ['websocket', 'ajax', 'fs', 'none'];
var updateModesNeedingUrl = ['ajax'];
function makeIdentitySourceMap(content, resourcePath) {
var map = new sm.SourceMapGenerator();
map.setSourceContent(resourcePath, content);
content.split('\n').map(function(line, index) {
map.addMapping({
source: resourcePath,
original: {
line: index+1,
column: 0
},
generated: {
line: index+1,
column: 0
}
});
});
return map.toJSON();
}
function readOpt(opts, long, short, defval) {
return has(opts, long) ? opts[long] : (short && has(opts, short)) ? opts[short] : defval;
}
function boolOpt(value) {
return Boolean(value && value !== 'false');
}
module.exports = function(bundle, opts) {
if (!opts) opts = {};
var updateMode = readOpt(opts, 'mode', 'm', 'websocket');
if (updateMode === 'xhr') {
console.warn('Use update mode "ajax" instead of "xhr".');
updateMode = 'ajax';
}
var updateUrl = readOpt(opts, 'url', 'u', null);
var port = readOpt(opts, 'port', 'p', 3123);
var hostname = readOpt(opts, 'hostname', 'h', 'localhost');
var updateCacheBust = boolOpt(readOpt(opts, 'cacheBust', 'b', false));
var bundleKey = readOpt(opts, 'key', 'k', updateMode+':'+updateUrl);
var cert = readOpt(opts, 'tlscert', 'C', null);
var key = readOpt(opts, 'tlskey', 'K', null);
var tlsoptions = opts.tlsoptions;
var supportModes = (opts.supportModes && opts.supportModes._) || opts.supportModes || [];
var noServe = boolOpt(readOpt(opts, 'noServe', null, false));
var ignoreUnaccepted = boolOpt(readOpt(opts, 'ignoreUnaccepted', null, true));
var disableHostCheck = boolOpt(readOpt(opts, 'disableHostCheck', null, false));
var basedir = opts.basedir !== undefined ? opts.basedir : process.cwd();
var em = new EventEmitter();
supportModes = _.uniq(['none', updateMode].concat(supportModes));
supportModes.forEach(function(updateMode) {
if (!_.includes(validUpdateModes, updateMode)) {
throw new Error("Invalid mode "+updateMode);
}
});
if (!updateUrl && _.includes(updateModesNeedingUrl, updateMode)) {
throw new Error("url option must be specified for "+updateMode+" mode");
}
var incPath = './'+path.relative(basedir, require.resolve('./inc/index'));
var sioPath = null;
if (_.includes(supportModes, 'websocket')) {
sioPath = './'+path.relative(basedir, require.resolve('socket.io-client'));
}
var useLocalSocketServer = !noServe && _.includes(supportModes, 'websocket');
var server;
var serverCommLock = {};
var nextServerConfirm = RSVP.defer();
function sendToServer(data) {
return new Promise(function(resolve, reject) {
server.stdio[3].write(JSON.stringify(data), function(err) {
if (err) return reject(err);
server.stdio[3].write('\n', function(err) {
if (err) return reject(err);
resolve();
});
});
});
}
var runServer = _.once(function() {
// Start a new process with an extra socket opened to it.
// See https://github.com/nodejs/node-v0.x-archive/issues/5727 for a
// description. It's faster than using `process.send`.
server = cproc.spawn(
process.argv[0],
[__dirname+'/socket-server.js'],
{ stdio: ['inherit','inherit','inherit','pipe'] }
);
var childReadline = readline.createInterface({
input: server.stdio[3],
output: process.stdout,
terminal: false
});
childReadline.on('line', function(line) {
var msg = JSON.parse(line);
if (msg.type === 'confirmNewModuleData') {
nextServerConfirm.resolve();
nextServerConfirm = RSVP.defer();
} else {
console.warn('[HMR builder] Unknown message type from server:', msg.type);
}
});
server.stdio[3].on('finish', function() {
em.emit('error', new Error("Browserify-HMR lost connection to socket server"));
});
return new Promise(function(resolve, reject) {
var readJobs = [];
if (cert) {
readJobs.push(readFile(cert, 'utf8').then(function(data) {
tlsoptions = tlsoptions || {};
tlsoptions.cert = data;
}));
}
if (key) {
readJobs.push(readFile(key, 'utf8').then(function(data) {
tlsoptions = tlsoptions || {};
tlsoptions.key = data;
}));
}
if (readJobs.length) {
resolve(Promise.all(readJobs));
} else {
resolve();
}
}).then(function(){
return sendToServer({
type: 'config',
disableHostCheck: disableHostCheck,
hostname: hostname,
port: port,
tlsoptions: tlsoptions
});
});
});
var currentModuleData = {};
function setNewModuleData(moduleData) {
if (!useLocalSocketServer) {
return Promise.resolve();
}
return runServer().then(function() {
var newModuleData = _.chain(moduleData)
.toPairs()
.filter(function(pair) {
return pair[1].isNew;
})
.map(function(pair) {
return [pair[0], {
index: pair[1].index,
hash: pair[1].hash,
source: pair[1].source,
parents: pair[1].parents,
deps: pair[1].deps
}];
})
.fromPairs()
.value();
var removedModules = _.chain(currentModuleData)
.keys()
.filter(function(name) {
return !has(moduleData, name);
})
.value();
currentModuleData = moduleData;
// This following block talking to the server should execute serially,
// never concurrently.
return synchd.synchd(serverCommLock, function() {
// Don't send all of the module data over at once. Send it piece by
// piece. The socket server won't apply the changes until it gets the
// type:"removedModules" message.
return Object.keys(newModuleData).reduce(function(promise, name) {
return promise.then(function() {
return sendToServer({
type: 'newModule',
name: name,
data: newModuleData[name]
});
});
}, Promise.resolve()).then(function() {
return sendToServer({
type: 'removedModules',
removedModules: removedModules
});
});
}).then(function() {
// Waiting for the response doesn't need to be in the exclusive section.
return nextServerConfirm.promise;
});
});
}
function fileKey(filename) {
return path.relative(basedir, filename);
}
var hmrManagerFilename;
// keys are filenames, values are {hash, transformedSource}
var transformCache = {};
function setupPipelineMods() {
var originalEntries = [];
bundle.pipeline.get('record').push(through.obj(function(row, enc, next) {
if (row.entry) {
originalEntries.push(row.file);
next(null);
} else {
next(null, row);
}
}, function(next) {
var source = [sioPath, incPath].filter(Boolean).concat(originalEntries).map(function(name) {
return 'require('+JSON.stringify(name)+');\n';
}).join('');
// Put the hmr file name in basedir to prevent this:
// https://github.com/babel/babelify/issues/85
hmrManagerFilename = path.join(basedir, '__hmr_manager.js');
this.push({
entry: true,
expose: false,
basedir: undefined,
file: hmrManagerFilename,
id: hmrManagerFilename,
source: source,
order: 0
});
next();
}));
var moduleMeta = {};
function makeModuleMetaEntry(name) {
if (!has(moduleMeta, name)) {
moduleMeta[name] = {
index: null,
hash: null,
parents: []
};
}
}
bundle.pipeline.get('deps').push(through.obj(function(row, enc, next) {
if (row.file !== hmrManagerFilename) {
makeModuleMetaEntry(fileKey(row.file));
_.forOwn(row.deps, function(name, ref) {
// dependencies that aren't included in the bundle have the name false
if (name) {
makeModuleMetaEntry(fileKey(name));
moduleMeta[fileKey(name)].parents.push(fileKey(row.file));
}
});
}
next(null, row);
}));
var moduleData = {};
var newTransformCache = {};
var managerRow = null;
var rowBuffer = [];
if (bundle.pipeline.get('dedupe').length > 1) {
console.warn("[HMR] Warning: other plugins have added dedupe transforms. This may interfere.");
}
// Disable dedupe transforms because it screws with our change tracking.
bundle.pipeline.splice('dedupe', 1, through.obj());
bundle.pipeline.get('label').push(through.obj(function(row, enc, next) {
if (row.file === hmrManagerFilename) {
managerRow = row;
next(null);
} else {
// row.id used when fullPaths flag is used
moduleMeta[fileKey(row.file)].index = has(row, 'index') ? row.index : row.id;
var hash = moduleMeta[fileKey(row.file)].hash = hashStr(row.source);
var originalSource = row.source;
var isNew, thunk;
if (has(transformCache, row.file) && transformCache[row.file].hash === hash) {
isNew = false;
row.source = transformCache[row.file].transformedSource;
newTransformCache[row.file] = transformCache[row.file];
thunk = () => Promise.resolve(row);
} else {
isNew = true;
thunk = async () => {
const header = '_hmr['+JSON.stringify(bundleKey)+
'].initModule('+JSON.stringify(fileKey(row.file))+', module);\n(function(){\n';
const footer = '\n}).apply(this, arguments);\n';
const inputMapCV = convert.fromSource(row.source);
let inputMap;
if (inputMapCV) {
inputMap = inputMapCV.toObject();
row.source = convert.removeComments(row.source);
} else {
inputMap = makeIdentitySourceMap(row.source, path.relative(basedir, row.file));
}
const result = await sm.SourceMapConsumer.with(
inputMap,
null,
async sourceMapConsumer => {
const node = new sm.SourceNode(null, null, null, [
new sm.SourceNode(null, null, null, header),
sm.SourceNode.fromStringWithSourceMap(row.source, sourceMapConsumer),
new sm.SourceNode(null, null, null, footer)
]);
return node.toStringWithSourceMap();
}
);
row.source = result.code + convert.fromObject(result.map.toJSON()).toComment();
newTransformCache[row.file] = {
hash: hash,
transformedSource: row.source
};
return row;
};
}
if (useLocalSocketServer) {
moduleData[fileKey(row.file)] = {
isNew: isNew,
index: moduleMeta[fileKey(row.file)].index,
hash: hash,
source: originalSource,
parents: moduleMeta[fileKey(row.file)].parents,
deps: row.indexDeps || row.deps
};
// Buffer everything so we can get the websocket stuff done sooner
// without being slowed down by the final bundling.
rowBuffer.push(thunk);
next(null);
} else {
thunk().then(thunkResult => {
next(null, thunkResult);
});
}
}
}, function(done) {
const self = this;
transformCache = newTransformCache;
setNewModuleData(moduleData).then(async () => {
const mgrTemplate = await readManagerTemplate();
for (const thunk of rowBuffer) {
self.push(await thunk());
}
managerRow.source = mgrTemplate
.replace('null/*!^^moduleMeta*/', _.constant(JSON.stringify(moduleMeta)))
.replace('null/*!^^originalEntries*/', _.constant(JSON.stringify(originalEntries)))
.replace('null/*!^^updateUrl*/', _.constant(JSON.stringify(updateUrl)))
.replace('null/*!^^updateMode*/', _.constant(JSON.stringify(updateMode)))
.replace('null/*!^^supportModes*/', _.constant(JSON.stringify(supportModes)))
.replace('null/*!^^ignoreUnaccepted*/', _.constant(JSON.stringify(ignoreUnaccepted)))
.replace('null/*!^^updateCacheBust*/', _.constant(JSON.stringify(updateCacheBust)))
.replace('null/*!^^bundleKey*/', _.constant(JSON.stringify(bundleKey)))
.replace('null/*!^^sioPath*/', _.constant(JSON.stringify(sioPath)))
.replace('null/*!^^incPath*/', _.constant(JSON.stringify(incPath)));
self.push(managerRow);
}).then(done, done);
}));
}
setupPipelineMods();
bundle.on('reset', setupPipelineMods);
return em;
};