-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
375 lines (336 loc) · 9.56 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
/**
* @file index
* @author imcuttle
* @date 2018/4/4
* @description
*/
const { detectDep, tree: detectDepTree } = require('detect-dep');
const assert = require('assert');
const visitTree = require('@moyuyc/visit-tree');
const nps = require('path');
const chokidar = require('chokidar');
const debug = require('debug')('hot-module-require');
const EventEmitter = require('events');
function delay(timeout) {
return new Promise((resolve) => {
setTimeout(resolve, timeout);
});
}
function toArray(item) {
return Array.isArray(item) ? item : [item];
}
function _moduleKey(resolvedModulePath) {
return `dep: ${resolvedModulePath}`;
}
const BOTH_EVENT_TYPE = '$both';
function visitUniqTree(tree, visit) {
const map = new WeakMap();
visitTree(tree, (node, ctx) => {
// Skip the visited node
if (map.has(node)) {
return ctx.skip();
}
visit && visit(node, ctx);
map.set(node, 'visited');
});
}
/**
* make a hot require instance
* @param dirname
* @param presetOpts {{}}
* @param [presetOpts.recursive=true] {boolean} Analysis file recursively
* @see More options see [detect-dep](https://github.com/imcuttle/detect-dep)
* @public
* @return {HotRequire}
*/
function makeHotRequireFunction(dirname = '', presetOpts = {}) {
assert(dirname, 'missing dirname');
assert(typeof dirname === 'string', 'dirname must be a string');
presetOpts = Object.assign({ recursive: true }, presetOpts);
const resolve = presetOpts.resolvePath
? (modulePath) => {
return presetOpts.resolvePath(modulePath, { dirname, ...presetOpts });
}
: function (modulePath) {
let resolvedModulePath;
if (modulePath.startsWith('.')) {
resolvedModulePath = require.resolve(nps.resolve(dirname, modulePath));
} else {
resolvedModulePath = require.resolve(modulePath);
}
return resolvedModulePath;
};
function getDependenceTree(modulePath, opts) {
const resolvedOptions = Object.assign({ moduleImport: false }, presetOpts, opts);
let resolvedModulePath = hotRequire.resolve(modulePath);
if (!resolvedOptions.recursive) {
return {
id: resolvedModulePath,
children: detectDep(resolvedModulePath, resolvedOptions).map((path) => {
return {
id: path,
children: [],
};
}),
};
}
return detectDepTree(resolvedModulePath, resolvedOptions);
}
function addDependencies(modulePath, deps = []) {
const { dependence, dependent } = hotRequire;
let resolvedModulePath = hotRequire.resolve(modulePath);
function add(map, key, value) {
if (!map.has(key)) {
map.set(key, []);
}
let arr = map.get(key);
if (arr.indexOf(value) < 0) {
arr.push(value);
}
}
deps.forEach((dep) => {
hotRequire.watcher.add(dep);
add(dependence, resolvedModulePath, dep);
add(dependent, dep, resolvedModulePath);
});
hotRequire.watcher.add(resolvedModulePath);
}
function removeDependencies(modulePath, deps) {
const { dependence, dependent } = hotRequire;
let resolvedModulePath = hotRequire.resolve(modulePath);
if (!deps) {
deps = dependence.get(resolvedModulePath);
}
function remove(map, key, value) {
if (!map.has(key)) {
return;
}
let arr = map.get(key);
let i = arr.indexOf(value);
if (i >= 0) {
arr.splice(i, 1);
}
}
(deps || []).forEach((dep) => {
remove(dependence, resolvedModulePath, dep);
remove(dependent, dep, resolvedModulePath);
if (!dependent.get(dep) || !dependent.get(dep).length) {
hotRequire.watcher.unwatch(dep);
}
});
if (!dependent.get(resolvedModulePath) || !dependent.get(resolvedModulePath).length) {
hotRequire.watcher.unwatch(resolvedModulePath);
}
}
function hotRegister(modulePath, opts = {}) {
function innerRegister(modulePath, opts = {}, map = {}) {
opts = Object.assign({}, presetOpts, opts);
let resolvedModulePath = hotRequire.resolve(modulePath);
if (map.hasOwnProperty(resolvedModulePath)) {
return;
}
map[resolvedModulePath] = 'visiting';
if (nps.isAbsolute(resolvedModulePath)) {
let depTree = hotRequire.getDependenceTree(resolvedModulePath, opts);
visitUniqTree(depTree, (node, ctx) => {
hotRequire.removeDependencies(node.id);
const deps = node.children.map((mod) => mod.id);
hotRequire.addDependencies(node.id, deps);
debug('deps %O \nof file: %s', deps, node.id);
});
}
map[resolvedModulePath] = 'visited';
}
return innerRegister(modulePath, opts);
}
/**
* @name HotRequire
* @public
* @typedef {Function & {remove: Function}}
*/
function hotRequire(modulePath) {
modulePath = hotRequire.resolve(modulePath);
const listener = (oldModule, path) => {};
hotRequire.accept([modulePath], listener);
return Object.assign(() => require(modulePath), {
remove: () => {
return hotRequire.refuse(modulePath, listener);
},
});
}
const watcher = chokidar.watch([], {
persistent: true,
});
const dependent = new Map();
const dependence = new Map();
const emitter = new EventEmitter();
function hotUpdate(path, opts) {
function innerHotUpdate(path, opts, map = {}) {
if (map.hasOwnProperty(path)) {
return;
}
let old = require.cache[path];
debug('hotUpdate %s \n', path);
delete require.cache[path];
// Update dep tree
hotRequire.register(path);
// Trigger event
emitter.emit(_moduleKey(path), old, path);
// Backward update
const { dependent, dependence } = hotRequire;
let dependents = dependent.get(path);
debug('file %s => dependents: %O.', path, dependents);
// Create a new map, For tracking one direction instead of the global dep graph
map = Object.assign(
{
[path]: 'visiting',
},
map,
);
dependents &&
dependents.forEach((path) => {
// return p.then(() => )
innerHotUpdate(path, opts, map);
});
map[path] = 'visited';
}
return innerHotUpdate(path, opts, {});
// Remove the dependencies
// let deps = dependence.get(path)
// deps &&
// deps.forEach(dep => {
// dependents = dependent.get(dep)
// if (dependents) {
// let i = dependents.indexOf(path)
// if (i >= 0) {
// dependents.splice(i, 1)
// }
// }
// })
}
watcher.on('change', (path) => {
debug('watch file %s changed.', path);
debug('dependent: %O', dependent);
debug('dependence: %O', dependence);
hotUpdate(path);
});
/**
* Resolve file name
* @memberOf HotRequire
* @public
* @param name {string}
*/
hotRequire.resolve = resolve;
/**
* file Watcher
* @memberOf HotRequire
* @public
* @see [chokidar](https://npmjs.com/chokidar)
*/
hotRequire.watcher = watcher;
/**
* The event emitter
* @memberOf HotRequire
* @public
*/
hotRequire.emitter = emitter;
/**
* The map about dependent relations
* @memberOf HotRequire
* @public
* @type {Map}
*/
hotRequire.dependent = dependent;
/**
* The map about dependence relations
* @memberOf HotRequire
* @public
* @type {Map}
*/
hotRequire.dependence = dependence;
/**
* Get dependence tree of which file
* @memberOf HotRequire
* @public
* @param modulePath {string}
* @param opts
* @see https://github.com/imcuttle/detect-dep#tree
* @return {{}}
*/
hotRequire.getDependenceTree = getDependenceTree;
hotRequire.register = hotRegister;
hotRequire.hotUpdate = hotUpdate;
/**
* Add Dependencies
* @memberOf HotRequire
* @public
* @param modulePath {string}
* @param deps {string[]}
*/
hotRequire.addDependencies = addDependencies;
/**
* Remove Dependencies
* @memberOf HotRequire
* @public
* @param modulePath {string}
* @param deps {string[]}
*/
hotRequire.removeDependencies = removeDependencies;
/**
* Watch file with callback and make dependence(dependent) relations
* @memberOf HotRequire
* @public
* @param deps {string[]}
* @param callback {function}
*/
hotRequire.accept = function accept(deps, callback) {
if (!deps) {
emitter.addListener(BOTH_EVENT_TYPE, callback);
return;
}
toArray(deps).forEach((dep) => {
let resolvedModulePath = hotRequire.resolve(dep);
hotRequire.register(dep);
emitter.addListener(_moduleKey(resolvedModulePath), callback);
});
};
/**
* Watch file with callback and make dependence(dependent) relations
* @memberOf HotRequire
* @public
* @param deps {string[]}
* @param callback {function}
*/
hotRequire.refuse = function refuse(deps, callback) {
function remove(type, path) {
if (!callback) {
emitter.removeAllListeners(type);
} else {
emitter.removeListener(type, callback);
}
// Remove dependencies & unwatch
if (path && !emitter.listeners(type).length) {
removeDependencies(path);
}
}
if (!deps) {
remove(BOTH_EVENT_TYPE);
return;
}
toArray(deps).forEach((dep) => {
let resolvedModulePath = hotRequire.resolve(dep);
remove(_moduleKey(resolvedModulePath), resolvedModulePath);
});
};
/**
* Close file watcher
* @memberOf HotRequire
* @return void
* @public
*/
hotRequire.close = function () {
hotRequire.watcher.close();
};
return hotRequire;
}
module.exports = makeHotRequireFunction;