-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (54 loc) · 1.57 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
const attachHook = require('./attachHook')
const ipc = require('electron').ipcRenderer
const _funcs = []
const sources = {}
const updateSrcs = {}
const evalFuncs = {}
const pureModules = {}
const fs = require('fs')
ipc.on('hp:file-changed', (event, f) => {
fs.readFile(f, 'utf-8', (err, raw) => {
const { root, hpCallFunc } = attachHook.parse(raw)
if (pureModules[f]) {
// when a pure module changes,
// - delete the module cache
// - re-run all hotpockets
delete require.cache[f]
Object.keys(evalFuncs).forEach(f => {
evalFuncs[f]('(' + updateSrcs[f] + ')()')
})
return
}
if (hasNonHpChanges(sources[f], { root, hpCallFunc })) {
location.reload()
return
}
if (hpCallFunc && evalFuncs[f]) {
evalFuncs[f]('(' + hpCallFunc.source() + ')()')
}
})
})
attachHook(sources, pureModules, {
extension: '.js',
pauseOnEvalError: true
})
module.exports = function (filename, updateFunc, evalFunc) {
// handle case where source has not been transformed by attachHook
if (typeof filename === 'function') {
filename()
return
}
updateSrcs[filename] = updateFunc.toString()
evalFuncs[filename] = evalFunc
// call update once to start
updateFunc()
}
module.exports.pure = function (filename) {
pureModules[filename] = true
}
function hasNonHpChanges (oldSrc, { root, hpCallFunc }) {
// if there's no hotpocket, every change is a non-hp change
if (!hpCallFunc) { return true }
const newSrc = root.toString().replace(hpCallFunc.source(), '')
return oldSrc !== newSrc
}