0x1
Version:
2 lines (1 loc) • 1.32 kB
JavaScript
(function(){if(window.__0x1_liveReloadSingleton)return;window.__0x1_liveReloadSingleton=!0;let b=null,j=0,J=0,G=!1,k=null,x=3,Q=15000,H=20000,K=60000;function W(){return Date.now()-J>=Q}function z(){if(b)b.close(),b=null;if(k)clearTimeout(k),k=null;G=!1}function B(){if(!W())return;if(G&&b&&b.readyState===EventSource.OPEN)return;if(z(),j>=x)return;J=Date.now(),console.log(`[0x1] Establishing SSE connection (attempt ${j+1}/${x})`);try{b=new EventSource("/__0x1_live_reload"),b.onopen=function(){G=!0,j=0,k=setTimeout(()=>{if(z(),j<x)setTimeout(B,H)},K)},b.onmessage=function(F){try{let q=JSON.parse(F.data);if(k)clearTimeout(k),k=setTimeout(()=>{if(z(),j<x)setTimeout(B,H)},K);if(q.type==="reload"||q.type==="css-update"||q.type==="file-change")setTimeout(()=>{window.location.reload()},100);else if(q.type==="connected");else if(q.type==="heartbeat");}catch(q){console.warn("[0x1] Failed to parse reload message:",q)}},b.onerror=function(){if(b&&b.readyState===EventSource.CLOSED){if(z(),j++,j<x){let F=Math.min(H*Math.pow(2,j-1),60000);setTimeout(B,F)}}}}catch(F){if(console.error("[0x1] Failed to create SSE connection:",F),j++,j<x)setTimeout(B,H)}}window.addEventListener("beforeunload",z),document.addEventListener("visibilitychange",()=>{if(document.hidden)z();else if(!G)setTimeout(B,1000)}),setTimeout(B,1000)})();