forked from alexisvincent/systemjs-hot-reloader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhot-reloader.js
More file actions
216 lines (210 loc) · 7.28 KB
/
Copy pathhot-reloader.js
File metadata and controls
216 lines (210 loc) · 7.28 KB
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
/* eslint-env browser */
import socketIO from 'socket.io-client'
import Emitter from 'weakee'
import debug from 'debug'
const d = debug('jspm-hot-reloader')
function identity (value) {
return value
}
class HotReloader extends Emitter {
constructor (backendUrl, transform = identity) {
if (!backendUrl) {
backendUrl = '//' + document.location.host
}
super()
this.originalSystemImport = System.import
const self = this
self.clientImportedModules = []
System.import = function () {
const args = arguments
self.clientImportedModules.push(args[0])
return self.originalSystemImport.apply(System, arguments).catch((err) => {
self.lastFailedSystemImport = args
throw err
})
}
this.socket = socketIO(backendUrl)
this.socket.on('connect', () => {
console.log('hot reload connected to watcher on ', backendUrl)
this.socket.emit('identification', navigator.userAgent)
})
this.socket.on('reload', () => {
console.log('whole page reload requested')
document.location.reload(true)
})
this.socket.on('change', this.onFileChanged.bind(this))
window.onerror = (err) => {
this.socket.emit('error', err) // emitting errors for jspm-dev-buddy
}
this.socket.on('disconnect', () => {
d('hot reload disconnected from ', backendUrl)
})
this.pushImporters(System.loads)
}
onFileChanged (ev) {
let moduleName = ev.path
this.emit('change', moduleName)
if (moduleName === 'index.html') {
document.location.reload(true)
} else {
if (this.lastFailedSystemImport) { // for wehn inital System.import fails
return this.originalSystemImport.apply(System, this.lastFailedSystemImport).then(() => {
console.log(this.lastFailedSystemImport[0], 'broken module reimported succesfully')
this.lastFailedSystemImport = null
})
}
if (this.currentHotReload) {
this.currentHotReload = this.currentHotReload.then(() => {
// chain promises TODO we can solve this better- this often leads to the same module being reloaded mutliple times
return this.hotReload(moduleName)
})
} else {
if (this.failedReimport) {
this.reImportRootModules(this.failedReimport, new Date())
} else {
this.currentHotReload = this.hotReload(moduleName)
}
}
}
}
pushImporters (moduleMap, overwriteOlds) {
Object.keys(moduleMap).forEach((moduleName) => {
let mod = System.loads[moduleName]
if (!mod.importers) {
mod.importers = []
}
mod.deps.forEach((dependantName) => {
let normalizedDependantName = mod.depMap[dependantName]
let dependantMod = System.loads[normalizedDependantName]
if (!dependantMod) {
return
}
if (!dependantMod.importers) {
dependantMod.importers = []
}
if (overwriteOlds) {
let imsIndex = dependantMod.importers.length
while (imsIndex--) {
if (dependantMod.importers[imsIndex].name === mod.name) {
dependantMod.importers[imsIndex] = mod
return
}
}
}
dependantMod.importers.push(mod)
})
})
}
deleteModule (moduleToDelete, from) {
let name = moduleToDelete.name
if (!this.modulesJustDeleted[name]) {
let exportedValue
this.modulesJustDeleted[name] = moduleToDelete
if (!moduleToDelete.exports) {
// this is a module from System.loads
exportedValue = System.get(name)
if (!exportedValue) {
d(`missing exported value on ${name}, reloading whole page because module record is broken`)
return document.location.reload(true)
}
} else {
exportedValue = moduleToDelete.exports
}
if (typeof exportedValue.__unload === 'function') {
exportedValue.__unload() // calling module unload hook
}
System.delete(name)
this.emit('deleted', moduleToDelete)
d('deleted a module ', name, ' because it has dependency on ', from)
}
}
getModuleRecord (moduleName) {
return System.normalize(moduleName).then(normalizedName => {
let aModule = System._loader.moduleRecords[normalizedName]
if (!aModule) {
aModule = System.loads[normalizedName]
if (aModule) {
return aModule
}
return System.normalize(moduleName + '!').then(normalizedName => { // .jsx! for example are stored like this
let aModule = System._loader.moduleRecords[normalizedName]
if (aModule) {
return aModule
}
throw new Error('module was not found in Systemjs moduleRecords')
})
}
return aModule
})
}
hotReload (moduleName) {
const self = this
const start = new Date().getTime()
this.modulesJustDeleted = {} // TODO use weakmap
return this.getModuleRecord(moduleName).then(module => {
this.deleteModule(module, 'origin')
let toReimport = []
function deleteAllImporters (mod) {
let importersToBeDeleted = mod.importers
return importersToBeDeleted.map((importer) => {
if (self.modulesJustDeleted.hasOwnProperty(importer.name)) {
d('already deleted', importer.name)
return false
}
self.deleteModule(importer, mod.name)
if (importer.importers.length === 0 && toReimport.indexOf(importer.name) === -1) {
toReimport.push(importer.name)
return true
} else {
// recourse
let deleted = deleteAllImporters(importer)
return deleted
}
})
}
if (typeof module.importers === 'undefined' || module.importers.length === 0) {
toReimport.push(module.name)
} else {
let deleted = deleteAllImporters(module)
if (deleted.find((res) => res === false) !== undefined) {
toReimport.push(module.name)
}
}
d('toReimport', toReimport)
if (toReimport.length === 0) {
toReimport = self.clientImportedModules
}
return this.reImportRootModules(toReimport, start)
}, (err) => {
this.emit('moduleRecordNotFound', err)
// not found any module for this file, not really an error
})
}
reImportRootModules (toReimport, start) {
const promises = toReimport.map((moduleName) => {
return this.originalSystemImport.call(System, moduleName).then(moduleReloaded => {
console.log('reimported ', moduleName)
if (typeof moduleReloaded.__reload === 'function') {
const deletedModule = this.modulesJustDeleted[moduleName]
if (deletedModule !== undefined) {
moduleReloaded.__reload(deletedModule.exports) // calling module reload hook
}
}
})
})
return Promise.all(promises).then(() => {
this.emit('allReimported', toReimport)
this.pushImporters(this.modulesJustDeleted, true)
this.modulesJustDeleted = {}
this.failedReimport = null
this.currentHotReload = null
console.log('all reimported in ', new Date().getTime() - start, 'ms')
}, (err) => {
this.emit('error', err)
console.error(err)
this.failedReimport = toReimport
this.currentHotReload = null
})
}
}
export default HotReloader