/
on-demand-entries-utils.js
47 lines (41 loc) · 1.26 KB
/
on-demand-entries-utils.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
/* global location */
import { getEventSourceWrapper } from './error-overlay/eventsource'
let evtSource
export let currentPage
export function closePing() {
if (evtSource) evtSource.close()
evtSource = null
}
export function setupPing(assetPrefix, pathnameFn, retry) {
const pathname = pathnameFn()
// Make sure to only create new EventSource request if page has changed
if (pathname === currentPage && !retry) return
currentPage = pathname
// close current EventSource connection
closePing()
evtSource = getEventSourceWrapper({
path: `${assetPrefix}/_next/webpack-hmr?page=${encodeURIComponent(
currentPage
)}`,
timeout: 5000,
})
evtSource.addMessageListener((event) => {
if (event.data.indexOf('{') === -1) return
try {
const payload = JSON.parse(event.data)
if (payload.invalid) {
// Payload can be invalid even if the page does not exist.
// So, we need to make sure it exists before reloading.
fetch(location.href, {
credentials: 'same-origin',
}).then((pageRes) => {
if (pageRes.status === 200) {
location.reload()
}
})
}
} catch (err) {
console.error('on-demand-entries failed to parse response', err)
}
})
}