2019-04-21 22:51:09 +02:00
|
|
|
let hotDevCallback
|
|
|
|
|
2018-07-24 11:24:40 +02:00
|
|
|
function EventSourceWrapper (options) {
|
|
|
|
var source
|
|
|
|
var lastActivity = new Date()
|
|
|
|
var listeners = []
|
|
|
|
|
|
|
|
if (!options.timeout) {
|
|
|
|
options.timeout = 20 * 1000
|
|
|
|
}
|
|
|
|
|
|
|
|
init()
|
|
|
|
var timer = setInterval(function () {
|
|
|
|
if ((new Date() - lastActivity) > options.timeout) {
|
|
|
|
handleDisconnect()
|
|
|
|
}
|
|
|
|
}, options.timeout / 2)
|
|
|
|
|
|
|
|
function init () {
|
|
|
|
source = new window.EventSource(options.path)
|
|
|
|
source.onopen = handleOnline
|
|
|
|
source.onerror = handleDisconnect
|
|
|
|
source.onmessage = handleMessage
|
|
|
|
}
|
|
|
|
|
|
|
|
function handleOnline () {
|
|
|
|
if (options.log) console.log('[HMR] connected')
|
|
|
|
lastActivity = new Date()
|
|
|
|
}
|
|
|
|
|
|
|
|
function handleMessage (event) {
|
|
|
|
lastActivity = new Date()
|
|
|
|
for (var i = 0; i < listeners.length; i++) {
|
|
|
|
listeners[i](event)
|
|
|
|
}
|
2019-04-21 22:51:09 +02:00
|
|
|
if (hotDevCallback && event.data.indexOf('action') !== -1) {
|
|
|
|
hotDevCallback(event)
|
|
|
|
}
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function handleDisconnect () {
|
|
|
|
clearInterval(timer)
|
|
|
|
source.close()
|
|
|
|
setTimeout(init, options.timeout)
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2019-04-21 22:51:09 +02:00
|
|
|
close: () => {
|
|
|
|
clearTimeout(timer)
|
|
|
|
source.close()
|
|
|
|
},
|
2018-07-24 11:24:40 +02:00
|
|
|
addMessageListener: function (fn) {
|
|
|
|
listeners.push(fn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getEventSourceWrapper (options) {
|
2019-04-21 22:51:09 +02:00
|
|
|
if (!options.ondemand) {
|
|
|
|
return {
|
|
|
|
addMessageListener: cb => {
|
|
|
|
hotDevCallback = cb
|
|
|
|
}
|
|
|
|
}
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|
2019-04-21 22:51:09 +02:00
|
|
|
return EventSourceWrapper(options)
|
2018-07-24 11:24:40 +02:00
|
|
|
}
|