|
1
|
const RELOAD_ATTEMPT_KEY = "medusa_preload_error_reloaded_at" |
|
2
|
const RELOAD_COOLDOWN_MS = 10_000 |
|
3
|
|
|
4
|
/** |
|
5
|
* Reloading is only safe if we can tell that we haven't just reloaded. If the |
|
6
|
* chunks are gone for good, an unguarded reload would loop forever, so without |
|
7
|
* a usable storage we let the error propagate instead. |
|
8
|
*/ |
|
9
|
const canAttemptReload = () => { |
|
10
|
try { |
|
11
|
const lastAttempt = Number(sessionStorage.getItem(RELOAD_ATTEMPT_KEY)) |
|
12
|
|
|
13
|
if (lastAttempt && Date.now() - lastAttempt < RELOAD_COOLDOWN_MS) { |
|
14
|
return false |
|
15
|
} |
|
16
|
|
|
17
|
sessionStorage.setItem(RELOAD_ATTEMPT_KEY, String(Date.now())) |
|
18
|
return true |
|
19
|
} catch { |
|
20
|
return false |
|
21
|
} |
|
22
|
} |
|
23
|
|
|
24
|
/** |
|
25
|
* The dashboard loads its routes as hashed chunks, and a deploy replaces those |
|
26
|
* files. A tab that was opened before the deploy requests chunks that no |
|
27
|
* longer exist, so every lazy-loaded route it hasn't visited yet fails until |
|
28
|
* the tab loads the new build. Vite reports exactly this failure through the |
|
29
|
* `vite:preloadError` event, and reloading once is its documented recovery: |
|
30
|
* https://vite.dev/guide/build#load-error-handling |
|
31
|
* |
|
32
|
* When a reload is not allowed (we just reloaded and the chunks are still |
|
33
|
* missing), the event is not canceled, so the error surfaces in the route's |
|
34
|
* error boundary. |
|
35
|
*/ |
|
36
|
export const registerReloadOnPreloadError = ( |
|
37
|
reload = () => window.location.reload() |
|
38
|
) => { |
|
39
|
window.addEventListener("vite:preloadError", (event) => { |
|
40
|
if (!canAttemptReload()) { |
|
41
|
return |
|
42
|
} |
|
43
|
|
|
44
|
event.preventDefault() |
|
45
|
reload() |
|
46
|
}) |
|
47
|
} |