UNPKG

one

Version:

One is a new React Framework that makes Vite serve both native and web.

86 lines (85 loc) 2.4 kB
import { CACHE_KEY } from "./constants.mjs"; import { getURL } from "./getURL.mjs"; import { handleSkewError } from "./utils/dynamicImport.mjs"; let stale = false; let polling = null; let inFlightCheck = null; function isVersionStale() { if (stale) return true; if (typeof window !== "undefined" && window.__oneVersionStale) return true; return false; } function markStale(version) { stale = true; if (typeof window !== "undefined") { ; window.__oneVersionStale = true; window.dispatchEvent(new CustomEvent("one-version-update", { detail: { version } })); } } function checkSkewAndReload() { if (typeof window === "undefined") return Promise.resolve(false); if (process.env.ONE_SKEW_PROTECTION === "false") return Promise.resolve(false); if (isVersionStale()) { handleSkewError(); return Promise.resolve(true); } if (inFlightCheck) return inFlightCheck; inFlightCheck = (async () => { try { const res = await fetch(`${getURL()}/version.json`, { headers: { "cache-control": "no-cache", pragma: "no-cache" } }); if (!res.ok) return false; const data = await res.json(); if (data.version && data.version !== CACHE_KEY) { markStale(data.version); handleSkewError(); return true; } return false; } catch { return false; } finally { inFlightCheck = null; } })(); return inFlightCheck; } function setupSkewProtection() { if (typeof window === "undefined") return; if (process.env.NODE_ENV === "development") return; if (process.env.ONE_SKEW_PROTECTION !== "proactive") return; const POLL_INTERVAL = 12e4; const baseUrl = getURL(); async function check() { try { const res = await fetch(`${baseUrl}/version.json`, { headers: { "cache-control": "no-cache", pragma: "no-cache" } }); if (!res.ok) { polling = setTimeout(check, POLL_INTERVAL); return; } const data = await res.json(); if (data.version !== CACHE_KEY) { markStale(data.version); return; } } catch {} polling = setTimeout(check, POLL_INTERVAL); } polling = setTimeout(check, POLL_INTERVAL); } export { checkSkewAndReload, isVersionStale, setupSkewProtection }; //# sourceMappingURL=skewProtection.mjs.map