@xiboplayer/pwa 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/assets/cms-api-B3gEu-pj.js.map +1 -1
  2. package/dist/assets/{index-CpeXG_hc.js → index-B1uJ1dV6.js} +2 -2
  3. package/dist/assets/{index-CpeXG_hc.js.map → index-B1uJ1dV6.js.map} +1 -1
  4. package/dist/assets/{index-CKuRgFp6.js → index-B5-XtSOy.js} +2 -2
  5. package/dist/assets/{index-CKuRgFp6.js.map → index-B5-XtSOy.js.map} +1 -1
  6. package/dist/assets/{index-BCL7JKFz.js → index-BMRsBy7Q.js} +2 -2
  7. package/dist/assets/{index-BCL7JKFz.js.map → index-BMRsBy7Q.js.map} +1 -1
  8. package/dist/assets/{index-DiLroK9-.js → index-BqbbAxtv.js} +2 -2
  9. package/dist/assets/{index-DiLroK9-.js.map → index-BqbbAxtv.js.map} +1 -1
  10. package/dist/assets/{index-CzhSvB4B.js → index-CQlonuj8.js} +2 -2
  11. package/dist/assets/{index-CzhSvB4B.js.map → index-CQlonuj8.js.map} +1 -1
  12. package/dist/assets/{index-DPcIXGuN.js → index-DFC6Djf2.js} +2 -2
  13. package/dist/assets/{index-DPcIXGuN.js.map → index-DFC6Djf2.js.map} +1 -1
  14. package/dist/assets/index-DRNGw10G.js +2 -0
  15. package/dist/assets/{index-m5gp9Gft.js.map → index-DRNGw10G.js.map} +1 -1
  16. package/dist/assets/{index-DA3or6a6.js → index-S6HEUd-4.js} +2 -2
  17. package/dist/assets/{index-DA3or6a6.js.map → index-S6HEUd-4.js.map} +1 -1
  18. package/dist/assets/index-TnmfaJL8.js +2 -0
  19. package/dist/assets/{index-DByQCT0-.js.map → index-TnmfaJL8.js.map} +1 -1
  20. package/dist/assets/{main-DfHNWLGS.js → main-BmWbr7-n.js} +3 -3
  21. package/dist/assets/{main-DfHNWLGS.js.map → main-BmWbr7-n.js.map} +1 -1
  22. package/dist/assets/setup-BTfmakR4.js +2 -0
  23. package/dist/assets/setup-BTfmakR4.js.map +1 -0
  24. package/dist/assets/sync-manager-DBfiw5Ey.js.map +1 -1
  25. package/dist/assets/widget-html-B_acad6q.js.map +1 -1
  26. package/dist/assets/xmds-client-Ci6s-34Q.js.map +1 -1
  27. package/dist/index.html +2 -2
  28. package/dist/setup.html +1 -1
  29. package/dist/sw-pwa.js +1 -1
  30. package/dist/sw-pwa.js.map +1 -1
  31. package/package.json +13 -13
  32. package/dist/assets/index-DByQCT0-.js +0 -2
  33. package/dist/assets/index-m5gp9Gft.js +0 -2
  34. package/dist/assets/setup-D67k289O.js +0 -2
  35. package/dist/assets/setup-D67k289O.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ import"./modulepreload-polyfill-B5Qt9EMX.js";import{b as e}from"./cms-api-B3gEu-pj.js";import{R as P,X as K}from"./xmds-client-Ci6s-34Q.js";const $="0.5.3";document.getElementById("version-footer").textContent=`Xibo Player v${$}`;const L=document.getElementById("setup-form"),h=document.getElementById("error"),c=document.getElementById("submit-btn"),S=document.getElementById("phase-unlock"),I=document.getElementById("phase-setup"),b=document.getElementById("phase-waiting"),C=document.getElementById("countdown"),T=document.getElementById("waiting-display-name"),z=document.getElementById("btn-back"),N=document.getElementById("success-flash"),E=e.hardwareKey;document.getElementById("hw-key-display").textContent=E;document.getElementById("hw-key-waiting").textContent=E;const j=e.cmsUrl||"";let m=null,r=null,x=15,l=null;async function v(){if(l)return l;try{const t=new P(e);await t.registerDisplay(),console.log("[Setup] Using REST transport"),l=t}catch(t){console.log("[Setup] REST unavailable, using XMDS/SOAP:",t.message),l=new K(e)}return l}function y(t){S.classList.remove("active"),I.classList.remove("active"),b.classList.remove("active"),t.classList.add("active")}function O(t){h.textContent=t,h.style.display="block"}function _(){h.style.display="none"}function f(){let t=x;C.textContent=t,clearInterval(r),r=setInterval(()=>{t--,C.textContent=Math.max(0,t),t<=0&&clearInterval(r)},1e3)}async function w(){if(document.getElementById("cms-url").value.trim().replace(/\/$/,"")!==j){console.log("[Setup] CMS URL changed — wiping cached content");const n=await caches.keys();await Promise.all(n.map(a=>caches.delete(a)))}N.classList.add("active"),setTimeout(()=>{window.location.href="/player/index.html"},800)}async function M(){try{const n=await(await v()).registerDisplay();if(console.log("[Setup] Poll result:",n.code,n.message),n.code==="READY"){clearInterval(m),clearInterval(r),w();return}f()}catch(t){console.warn("[Setup] Poll failed:",t.message),f()}}function R(t){T.textContent=t,y(b),f(),m=setInterval(M,x*1e3)}function A(){clearInterval(m),clearInterval(r),m=null}async function X(t,n){const a=document.getElementById("api-client-id").value.trim(),o=document.getElementById("api-client-secret").value.trim();if(!a||!o)return!1;try{const s=await fetch(`/rest-proxy?cms=${encodeURIComponent(t)}&path=/api/authorize/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:a,client_secret:o})});if(!s.ok)throw new Error(`OAuth2 failed: ${s.status}`);const{access_token:i}=await s.json(),u=await fetch(`/rest-proxy?cms=${encodeURIComponent(t)}&path=/api/display&hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${i}`}});if(!u.ok)throw new Error(`Find display failed: ${u.status}`);const p=await u.json();if(!p.length)return console.log("[Setup] Display not found via API (may not be registered yet)"),!1;const g=p[0];if(g.licensed===1)return console.log("[Setup] Display already authorized"),!0;const B=await fetch(`/rest-proxy?cms=${encodeURIComponent(t)}&path=/api/display/authorise/${g.displayId}`,{method:"PUT",headers:{Authorization:`Bearer ${i}`}});if(!B.ok)throw new Error(`Authorize failed: ${B.status}`);return console.log("[Setup] Display auto-authorized via proxy!"),e.apiClientId=a,e.apiClientSecret=o,!0}catch(s){return console.warn("[Setup] Auto-authorize failed:",s.message),!1}}const d=e.isConfigured()&&e.cmsKey,k=new URLSearchParams(window.location.search).has("unlocked"),D=document.getElementById("btn-back-player");d&&!k&&y(S);(d||k)&&(D.style.display="block",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));function U(){A(),window.location.href="/player/index.html"}D.addEventListener("click",U);(d||k)&&document.addEventListener("keydown",t=>{t.key==="Escape"&&(t.preventDefault(),U())});document.getElementById("unlock-form").addEventListener("submit",t=>{t.preventDefault();const n=document.getElementById("unlock-error");document.getElementById("unlock-key").value.trim()===e.cmsKey?(n.style.display="none",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""),y(I)):(n.textContent="Incorrect CMS key",n.style.display="block")});!d&&e.isConfigured()&&(document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));L.addEventListener("submit",async t=>{t.preventDefault(),_();const n=document.getElementById("cms-url").value.trim().replace(/\/$/,""),a=document.getElementById("cms-key").value.trim(),o=document.getElementById("display-name").value.trim();try{if(c.textContent="Saving...",c.disabled=!0,!(await fetch("/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cmsUrl:n,cmsKey:a,displayName:o})})).ok)throw new Error("Failed to save config");e.data.cmsUrl=n,e.data.cmsKey=a,e.data.displayName=o,e.save(),Y(e.hardwareKey),c.textContent="Connecting...",l=null;const i=await v();if((await i.registerDisplay()).code==="READY")w();else{if(c.textContent="Authorizing...",await X(n,E)&&(await i.registerDisplay()).code==="READY"){w();return}R(o)}}catch(s){O(`Connection failed: ${s.message}`),c.textContent="Connect",c.disabled=!1}});z.addEventListener("click",()=>{A(),y(I),c.textContent="Connect",c.disabled=!1});async function Y(t){try{const n=indexedDB.open("xibo-hw-backup",1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains("keys")||a.createObjectStore("keys")},n.onsuccess=()=>{const a=n.result,o=a.transaction("keys","readwrite");o.objectStore("keys").put(t,"hardwareKey"),o.oncomplete=()=>a.close()}}catch(n){console.warn("[Setup] IndexedDB backup failed:",n)}}c.disabled=!1;c.textContent="Connect";e.isConfigured()&&!d&&(async()=>{try{(await(await v()).registerDisplay()).code==="READY"?window.location.href="/player/index.html":R(e.displayName)}catch{console.log("[Setup] Auto-check failed, showing form")}})();
2
+ //# sourceMappingURL=setup-BTfmakR4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-BTfmakR4.js","sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config } from '@xiboplayer/utils';\n import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n\n // Inject version from Vite build\n const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '?';\n document.getElementById('version-footer').textContent = `Xibo Player v${appVersion}`;\n\n // ── Elements ──\n const form = document.getElementById('setup-form');\n const errorEl = document.getElementById('error');\n const submitBtn = document.getElementById('submit-btn');\n const phaseUnlock = document.getElementById('phase-unlock');\n const phaseSetup = document.getElementById('phase-setup');\n const phaseWaiting = document.getElementById('phase-waiting');\n const countdownEl = document.getElementById('countdown');\n const waitingNameEl = document.getElementById('waiting-display-name');\n const btnBack = document.getElementById('btn-back');\n const successFlash = document.getElementById('success-flash');\n\n // Show hardware key\n const hwKey = config.hardwareKey;\n document.getElementById('hw-key-display').textContent = hwKey;\n document.getElementById('hw-key-waiting').textContent = hwKey;\n\n // ── State ──\n const previousCmsUrl = config.cmsUrl || '';\n let pollTimer = null;\n let countdownTimer = null;\n let pollSeconds = 15;\n\n // ── Transport: try REST first, fall back to SOAP ──\n let transport = null;\n async function getTransport() {\n if (transport) return transport;\n try {\n const rest = new RestClient(config);\n await rest.registerDisplay();\n console.log('[Setup] Using REST transport');\n transport = rest;\n } catch (e) {\n console.log('[Setup] REST unavailable, using XMDS/SOAP:', e.message);\n transport = new XmdsClient(config);\n }\n return transport;\n }\n\n // ── Helpers ──\n function showPhase(phase) {\n phaseUnlock.classList.remove('active');\n phaseSetup.classList.remove('active');\n phaseWaiting.classList.remove('active');\n phase.classList.add('active');\n }\n\n function showError(msg) {\n errorEl.textContent = msg;\n errorEl.style.display = 'block';\n }\n\n function hideError() {\n errorEl.style.display = 'none';\n }\n\n function startCountdown() {\n let remaining = pollSeconds;\n countdownEl.textContent = remaining;\n clearInterval(countdownTimer);\n countdownTimer = setInterval(() => {\n remaining--;\n countdownEl.textContent = Math.max(0, remaining);\n if (remaining <= 0) clearInterval(countdownTimer);\n }, 1000);\n }\n\n async function showSuccess() {\n // If CMS URL changed, wipe all cached content (media, layouts, widgets\n // from the old CMS are useless) and the SW's cached index.html (which\n // may have a stale config injection script).\n const newUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n if (newUrl !== previousCmsUrl) {\n console.log('[Setup] CMS URL changed — wiping cached content');\n const cacheNames = await caches.keys();\n await Promise.all(cacheNames.map(name => caches.delete(name)));\n }\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = '/player/index.html';\n }, 800);\n }\n\n // ── Authorization Polling ──\n async function checkAuthorization() {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n console.log('[Setup] Poll result:', result.code, result.message);\n\n if (result.code === 'READY') {\n // Authorized!\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n showSuccess();\n return;\n }\n\n // Still waiting — restart countdown\n startCountdown();\n } catch (error) {\n console.warn('[Setup] Poll failed:', error.message);\n startCountdown();\n }\n }\n\n function startPolling(displayName) {\n waitingNameEl.textContent = displayName;\n showPhase(phaseWaiting);\n startCountdown();\n pollTimer = setInterval(checkAuthorization, pollSeconds * 1000);\n }\n\n function stopPolling() {\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n pollTimer = null;\n }\n\n // ── Auto-authorize via CMS API (through rest-proxy to avoid CORS) ──\n async function tryAutoAuthorize(cmsUrl, hardwareKey) {\n const clientId = document.getElementById('api-client-id').value.trim();\n const clientSecret = document.getElementById('api-client-secret').value.trim();\n if (!clientId || !clientSecret) return false;\n\n try {\n // Step 1: OAuth2 token via proxy\n const tokenResp = await fetch(`/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/authorize/access_token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }),\n });\n if (!tokenResp.ok) throw new Error(`OAuth2 failed: ${tokenResp.status}`);\n const { access_token } = await tokenResp.json();\n\n // Step 2: Find display by hardwareKey via proxy\n const displayResp = await fetch(\n `/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/display&hardwareKey=${encodeURIComponent(hardwareKey)}`,\n { headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!displayResp.ok) throw new Error(`Find display failed: ${displayResp.status}`);\n const displays = await displayResp.json();\n if (!displays.length) { console.log('[Setup] Display not found via API (may not be registered yet)'); return false; }\n\n const display = displays[0];\n if (display.licensed === 1) { console.log('[Setup] Display already authorized'); return true; }\n\n // Step 3: Authorize display via proxy\n const authResp = await fetch(\n `/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/display/authorise/${display.displayId}`,\n { method: 'PUT', headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!authResp.ok) throw new Error(`Authorize failed: ${authResp.status}`);\n\n console.log('[Setup] Display auto-authorized via proxy!');\n config.apiClientId = clientId;\n config.apiClientSecret = clientSecret;\n return true;\n } catch (error) {\n console.warn('[Setup] Auto-authorize failed:', error.message);\n return false;\n }\n }\n\n // ── Unlock gate for reconfiguration ──\n const isReconfigure = config.isConfigured() && config.cmsKey;\n const alreadyUnlocked = new URLSearchParams(window.location.search).has('unlocked');\n const btnBackPlayer = document.getElementById('btn-back-player');\n if (isReconfigure && !alreadyUnlocked) {\n // Show unlock phase instead of setup form\n showPhase(phaseUnlock);\n }\n if (isReconfigure || alreadyUnlocked) {\n // Show \"Back to Player\" on the setup form\n btnBackPlayer.style.display = 'block';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html';\n }\n btnBackPlayer.addEventListener('click', goBackToPlayer);\n\n // Esc also goes back to player when reconfiguring\n if (isReconfigure || alreadyUnlocked) {\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n goBackToPlayer();\n }\n });\n }\n\n // ── Unlock form handler ──\n document.getElementById('unlock-form').addEventListener('submit', (e) => {\n e.preventDefault();\n const unlockError = document.getElementById('unlock-error');\n const enteredKey = document.getElementById('unlock-key').value.trim();\n\n if (enteredKey === config.cmsKey) {\n unlockError.style.display = 'none';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n showPhase(phaseSetup);\n } else {\n unlockError.textContent = 'Incorrect CMS key';\n unlockError.style.display = 'block';\n }\n });\n\n // ── Pre-fill if first-time setup (no unlock gate) ──\n if (!isReconfigure && config.isConfigured()) {\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n }\n\n // ── Form Submit ──\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n hideError();\n\n const cmsUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n const cmsKey = document.getElementById('cms-key').value.trim();\n const displayName = document.getElementById('display-name').value.trim();\n\n // Write config.json via proxy (master config file)\n // The boot path (proxy injection → Config.load()) handles the rest.\n try {\n submitBtn.textContent = 'Saving...';\n submitBtn.disabled = true;\n\n const saveResp = await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ cmsUrl, cmsKey, displayName }),\n });\n if (!saveResp.ok) throw new Error('Failed to save config');\n\n // Also update in-memory config for the test connection below\n config.data.cmsUrl = cmsUrl;\n config.data.cmsKey = cmsKey;\n config.data.displayName = displayName;\n config.save();\n\n // Backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n submitBtn.textContent = 'Connecting...';\n\n // Try REST first, fall back to SOAP\n transport = null; // reset transport for fresh detection\n const client = await getTransport();\n const result = await client.registerDisplay();\n\n if (result.code === 'READY') {\n showSuccess();\n } else {\n // Try auto-authorize via CMS API if credentials provided\n submitBtn.textContent = 'Authorizing...';\n const autoAuthed = await tryAutoAuthorize(cmsUrl, hwKey);\n\n if (autoAuthed) {\n // Verify registration\n const recheck = await client.registerDisplay();\n if (recheck.code === 'READY') {\n showSuccess();\n return;\n }\n }\n\n // Not authorized yet — switch to polling phase\n startPolling(displayName);\n }\n } catch (error) {\n showError(`Connection failed: ${error.message}`);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n }\n });\n\n // ── Back button ──\n btnBack.addEventListener('click', () => {\n stopPolling();\n showPhase(phaseSetup);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n });\n\n // ── IndexedDB hardware key backup ──\n async function backupHardwareKey(key) {\n try {\n const req = indexedDB.open('xibo-hw-backup', 1);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains('keys')) {\n db.createObjectStore('keys');\n }\n };\n req.onsuccess = () => {\n const db = req.result;\n const tx = db.transaction('keys', 'readwrite');\n tx.objectStore('keys').put(key, 'hardwareKey');\n tx.oncomplete = () => db.close();\n };\n } catch (e) {\n console.warn('[Setup] IndexedDB backup failed:', e);\n }\n }\n\n // ── Enable submit ──\n submitBtn.disabled = false;\n submitBtn.textContent = 'Connect';\n\n // ── Auto-resume polling if already registered but not authorized ──\n // Skip auto-resume when reconfiguring (user explicitly opened setup)\n if (config.isConfigured() && !isReconfigure) {\n (async () => {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n if (result.code === 'READY') {\n window.location.href = '/player/index.html';\n } else {\n // Not authorized — go straight to polling\n startPolling(config.displayName);\n }\n } catch (e) {\n // Connection failed, show form\n console.log('[Setup] Auto-check failed, showing form');\n }\n })();\n }\n "],"names":["appVersion","form","errorEl","submitBtn","phaseUnlock","phaseSetup","phaseWaiting","countdownEl","waitingNameEl","btnBack","successFlash","hwKey","config","previousCmsUrl","pollTimer","countdownTimer","pollSeconds","transport","getTransport","rest","RestClient","e","XmdsClient","showPhase","phase","showError","msg","hideError","startCountdown","remaining","showSuccess","cacheNames","name","checkAuthorization","result","error","startPolling","displayName","stopPolling","tryAutoAuthorize","cmsUrl","hardwareKey","clientId","clientSecret","tokenResp","access_token","displayResp","displays","display","authResp","isReconfigure","alreadyUnlocked","btnBackPlayer","goBackToPlayer","unlockError","cmsKey","backupHardwareKey","client","key","req","db","tx"],"mappings":"4IAKI,MAAMA,EAAsD,QAC5D,SAAS,eAAe,gBAAgB,EAAE,YAAc,gBAAgBA,CAAU,GAGlF,MAAMC,EAAO,SAAS,eAAe,YAAY,EAC3CC,EAAU,SAAS,eAAe,OAAO,EACzCC,EAAY,SAAS,eAAe,YAAY,EAChDC,EAAc,SAAS,eAAe,cAAc,EACpDC,EAAa,SAAS,eAAe,aAAa,EAClDC,EAAe,SAAS,eAAe,eAAe,EACtDC,EAAc,SAAS,eAAe,WAAW,EACjDC,EAAgB,SAAS,eAAe,sBAAsB,E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BAAkB,MAAM,CAE/B,EACAD,EAAI,UAAY,IAAM,CACpB,MAAMC,EAAKD,EAAI,OACTE,EAAKD,EAAG,YAAY,OAAQ,WAAW,EAC7CC,EAAG,YAAY,MAAM,EAAE,IAAIH,EAAK,aAAa,EAC7CG,EAAG,WAAa,IAAMD,EAAG,MAAA,CAC3B,CACF,OAASvC,EAAG,CACV,QAAQ,KAAK,mCAAoCA,CAAC,CACpD,CACF,CAGAlB,EAAU,SAAW,GACrBA,EAAU,YAAc,UAIpBS,EAAO,gBAAkB,CAACsC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAMhC,EAAA,GACO,gBAAA,GACjB,OAAS,QAClB,OAAO,SAAS,KAAO,qBAGvBkB,EAAaxB,EAAO,WAAW,CAEnC,MAAY,CAEV,QAAQ,IAAI,yCAAyC,CACvD,CACF,GAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"sync-manager-DBfiw5Ey.js","sources":["../../node_modules/.pnpm/@xiboplayer+sync@0.5.1/node_modules/@xiboplayer/sync/src/sync-manager.js"],"sourcesContent":["/**\n * SyncManager - Multi-display synchronization via BroadcastChannel\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * on the same machine (video wall, multi-monitor setups).\n *\n * Protocol:\n * Lead Follower(s)\n * ──── ──────────\n * layout-change(layoutId, showAt) → receives, loads layout\n * ← layout-ready(layoutId, displayId)\n * (waits for all followers ready)\n * layout-show(layoutId) → shows layout simultaneously\n *\n * Heartbeat:\n * All nodes broadcast heartbeat every 5s.\n * Lead tracks active followers. If a follower goes silent for 15s,\n * it's considered offline and excluded from ready-wait.\n *\n * @module @xiboplayer/sync\n */\n\n/**\n * @typedef {Object} SyncConfig\n * @property {string} syncGroup - \"lead\" or leader's LAN IP\n * @property {number} syncPublisherPort - TCP port (unused in browser, kept for compat)\n * @property {number} syncSwitchDelay - Delay in ms before showing new content\n * @property {number} syncVideoPauseDelay - Delay in ms before unpausing video\n * @property {boolean} isLead - Whether this display is the leader\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst CHANNEL_NAME = 'xibo-sync';\nconst HEARTBEAT_INTERVAL = 5000; // Send heartbeat every 5s\nconst FOLLOWER_TIMEOUT = 15000; // Consider follower offline after 15s silence\nconst READY_TIMEOUT = 10000; // Max wait for followers to be ready\n\nexport class SyncManager {\n /**\n * @param {Object} options\n * @param {string} options.displayId - This display's unique hardware key\n * @param {SyncConfig} options.syncConfig - Sync configuration from RegisterDisplay\n * @param {Function} [options.onLayoutChange] - Called when lead requests layout change\n * @param {Function} [options.onLayoutShow] - Called when lead gives show signal\n * @param {Function} [options.onVideoStart] - Called when lead gives video start signal\n * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\n */\n constructor(options) {\n this.displayId = options.displayId;\n this.syncConfig = options.syncConfig;\n this.isLead = options.syncConfig.isLead;\n this.switchDelay = options.syncConfig.syncSwitchDelay || 750;\n this.videoPauseDelay = options.syncConfig.syncVideoPauseDelay || 100;\n\n // Callbacks\n this.onLayoutChange = options.onLayoutChange || (() => {});\n this.onLayoutShow = options.onLayoutShow || (() => {});\n this.onVideoStart = options.onVideoStart || (() => {});\n this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\n\n // State\n this.channel = null;\n this.followers = new Map(); // displayId → { lastSeen, ready }\n this._heartbeatTimer = null;\n this._cleanupTimer = null;\n this._readyResolve = null; // Resolve function for current ready-wait\n this._pendingLayoutId = null; // Layout we're waiting for readiness on\n this._started = false;\n\n // Logger with role prefix for clarity in multi-tab console\n this._tag = this.isLead ? '[Sync:LEAD]' : '[Sync:FOLLOW]';\n this._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /**\n * Start the sync manager (opens BroadcastChannel, begins heartbeats)\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n if (typeof BroadcastChannel === 'undefined') {\n this._log.warn( 'BroadcastChannel not available — sync disabled');\n return;\n }\n\n this.channel = new BroadcastChannel(CHANNEL_NAME);\n this.channel.onmessage = (event) => this._handleMessage(event.data);\n\n // Start heartbeat\n this._heartbeatTimer = setInterval(() => this._sendHeartbeat(), HEARTBEAT_INTERVAL);\n this._sendHeartbeat(); // Send initial heartbeat immediately\n\n // Lead: periodically clean up stale followers\n if (this.isLead) {\n this._cleanupTimer = setInterval(() => this._cleanupStaleFollowers(), HEARTBEAT_INTERVAL);\n }\n\n this._log.info( 'Started. DisplayId:', this.displayId);\n }\n\n /**\n * Stop the sync manager\n */\n stop() {\n if (!this._started) return;\n this._started = false;\n\n if (this._heartbeatTimer) {\n clearInterval(this._heartbeatTimer);\n this._heartbeatTimer = null;\n }\n if (this._cleanupTimer) {\n clearInterval(this._cleanupTimer);\n this._cleanupTimer = null;\n }\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n\n this.followers.clear();\n this._log.info( 'Stopped');\n }\n\n // ── Lead API ──────────────────────────────────────────────────────\n\n /**\n * [Lead only] Request all displays to change to a layout.\n * Waits for followers to report ready, then sends show signal.\n *\n * @param {string|number} layoutId - Layout to change to\n * @returns {Promise<void>} Resolves when show signal is sent\n */\n async requestLayoutChange(layoutId) {\n if (!this.isLead) {\n this._log.warn( 'requestLayoutChange called on follower — ignoring');\n return;\n }\n\n layoutId = String(layoutId);\n this._pendingLayoutId = layoutId;\n\n // Mark all followers as not-ready for this layout\n for (const [, follower] of this.followers) {\n follower.ready = false;\n follower.readyLayoutId = null;\n }\n\n const showAt = Date.now() + this.switchDelay;\n\n this._log.info( `Requesting layout change: ${layoutId} (show at ${new Date(showAt).toISOString()}, ${this.followers.size} followers)`);\n\n // Broadcast layout-change to all followers\n this._send({\n type: 'layout-change',\n layoutId,\n showAt,\n displayId: this.displayId,\n });\n\n // Wait for all active followers to report ready (or timeout)\n if (this.followers.size > 0) {\n await this._waitForFollowersReady(layoutId);\n }\n\n // Apply switch delay (remaining time from showAt)\n const remaining = showAt - Date.now();\n if (remaining > 0) {\n await new Promise(resolve => setTimeout(resolve, remaining));\n }\n\n // Send show signal\n this._log.info( `Sending layout-show: ${layoutId}`);\n this._send({\n type: 'layout-show',\n layoutId,\n displayId: this.displayId,\n });\n\n // Also trigger on self (lead shows too)\n this.onLayoutShow(layoutId);\n\n this._pendingLayoutId = null;\n }\n\n /**\n * [Lead only] Signal followers to start video playback.\n *\n * @param {string|number} layoutId - Layout containing the video\n * @param {string} regionId - Region with the video widget\n */\n async requestVideoStart(layoutId, regionId) {\n if (!this.isLead) return;\n\n // Wait videoPauseDelay before unpausing\n await new Promise(resolve => setTimeout(resolve, this.videoPauseDelay));\n\n this._send({\n type: 'video-start',\n layoutId: String(layoutId),\n regionId,\n displayId: this.displayId,\n });\n\n // Also trigger on self\n this.onVideoStart(String(layoutId), regionId);\n }\n\n // ── Follower API ──────────────────────────────────────────────────\n\n /**\n * [Follower only] Report that layout is loaded and ready to show.\n * Called by platform layer after layout content is prepared.\n *\n * @param {string|number} layoutId - Layout that is ready\n */\n reportReady(layoutId) {\n layoutId = String(layoutId);\n\n this._log.info( `Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\n });\n }\n\n // ── Message handling ──────────────────────────────────────────────\n\n /** @private */\n _handleMessage(msg) {\n // Ignore our own messages\n if (msg.displayId === this.displayId) return;\n\n switch (msg.type) {\n case 'heartbeat':\n this._handleHeartbeat(msg);\n break;\n\n case 'layout-change':\n // Follower: lead is requesting a layout change\n if (!this.isLead) {\n this._log.info( `Layout change requested: ${msg.layoutId}`);\n this.onLayoutChange(msg.layoutId, msg.showAt);\n }\n break;\n\n case 'layout-ready':\n // Lead: follower reports ready\n if (this.isLead) {\n this._handleFollowerReady(msg);\n }\n break;\n\n case 'layout-show':\n // Follower: lead says show now\n if (!this.isLead) {\n this._log.info( `Layout show signal: ${msg.layoutId}`);\n this.onLayoutShow(msg.layoutId);\n }\n break;\n\n case 'video-start':\n // Follower: lead says start video\n if (!this.isLead) {\n this._log.info( `Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn( 'Unknown message type:', msg.type);\n }\n }\n\n /** @private */\n _handleHeartbeat(msg) {\n const existing = this.followers.get(msg.displayId);\n if (existing) {\n existing.lastSeen = Date.now();\n } else {\n // New follower discovered\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: false,\n readyLayoutId: null,\n role: msg.role || 'unknown',\n });\n this._log.info( `Follower joined: ${msg.displayId} (${this.followers.size} total)`);\n }\n }\n\n /** @private */\n _handleFollowerReady(msg) {\n const follower = this.followers.get(msg.displayId);\n if (!follower) {\n // Late joiner — register them\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: true,\n readyLayoutId: msg.layoutId,\n });\n } else {\n follower.ready = true;\n follower.readyLayoutId = msg.layoutId;\n follower.lastSeen = Date.now();\n }\n\n this._log.info( `Follower ${msg.displayId} ready for layout ${msg.layoutId}`);\n\n // Check if all followers are now ready\n if (this._pendingLayoutId === msg.layoutId && this._readyResolve) {\n if (this._allFollowersReady(msg.layoutId)) {\n this._log.info( 'All followers ready');\n this._readyResolve();\n this._readyResolve = null;\n }\n }\n }\n\n /** @private */\n _allFollowersReady(layoutId) {\n for (const [, follower] of this.followers) {\n // Skip stale followers\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n if (!follower.ready || follower.readyLayoutId !== layoutId) {\n return false;\n }\n }\n return true;\n }\n\n /** @private */\n _waitForFollowersReady(layoutId) {\n return new Promise((resolve) => {\n // Already all ready?\n if (this._allFollowersReady(layoutId)) {\n resolve();\n return;\n }\n\n this._readyResolve = resolve;\n\n // Timeout: don't wait forever for unresponsive followers\n setTimeout(() => {\n if (this._readyResolve === resolve) {\n const notReady = [];\n for (const [id, f] of this.followers) {\n if (!f.ready || f.readyLayoutId !== layoutId) {\n notReady.push(id);\n }\n }\n this._log.warn( `Ready timeout — proceeding without: ${notReady.join(', ')}`);\n this._readyResolve = null;\n resolve();\n }\n }, READY_TIMEOUT);\n });\n }\n\n // ── Heartbeat & cleanup ───────────────────────────────────────────\n\n /** @private */\n _sendHeartbeat() {\n this._send({\n type: 'heartbeat',\n displayId: this.displayId,\n role: this.isLead ? 'lead' : 'follower',\n timestamp: Date.now(),\n });\n }\n\n /** @private */\n _cleanupStaleFollowers() {\n const now = Date.now();\n for (const [id, follower] of this.followers) {\n if (now - follower.lastSeen > FOLLOWER_TIMEOUT) {\n this._log.info( `Removing stale follower: ${id} (last seen ${Math.round((now - follower.lastSeen) / 1000)}s ago)`);\n this.followers.delete(id);\n }\n }\n }\n\n /** @private */\n _send(msg) {\n if (!this.channel) return;\n try {\n this.channel.postMessage(msg);\n } catch (e) {\n this._log.error( 'Failed to send:', e);\n }\n }\n\n // ── Status ────────────────────────────────────────────────────────\n\n /**\n * Get current sync status\n * @returns {Object}\n */\n getStatus() {\n return {\n started: this._started,\n isLead: this.isLead,\n displayId: this.displayId,\n followers: this.followers.size,\n pendingLayoutId: this._pendingLayoutId,\n followerDetails: Array.from(this.followers.entries()).map(([id, f]) => ({\n displayId: id,\n lastSeen: f.lastSeen,\n ready: f.ready,\n readyLayoutId: f.readyLayoutId,\n stale: Date.now() - f.lastSeen > FOLLOWER_TIMEOUT,\n })),\n };\n }\n}\n"],"names":["CHANNEL_NAME","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","createLogger","event","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","msg","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"0CAiCA,MAAMA,EAAe,YACfC,EAAqB,IACrBC,EAAmB,KACnBC,EAAgB,IAEf,MAAMC,CAAY,CAavB,YAAYC,EAAS,CACnB,KAAK,UAAYA,EAAQ,UACzB,KAAK,WAAaA,EAAQ,WAC1B,KAAK,OAASA,EAAQ,WAAW,OACjC,KAAK,YAAcA,EAAQ,WAAW,iBAAmB,IACzD,KAAK,gBAAkBA,EAAQ,WAAW,qBAAuB,IAGjE,KAAK,eAAiBA,EA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AAiB,KAAK,iBACtB,gBAAiB,MAAM,KAAK,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC,CAACK,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWpB,CACzC,EAAQ,CACR,CACE,CACF","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"sync-manager-DBfiw5Ey.js","sources":["../../node_modules/.pnpm/@xiboplayer+sync@0.5.3/node_modules/@xiboplayer/sync/src/sync-manager.js"],"sourcesContent":["/**\n * SyncManager - Multi-display synchronization via BroadcastChannel\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * on the same machine (video wall, multi-monitor setups).\n *\n * Protocol:\n * Lead Follower(s)\n * ──── ──────────\n * layout-change(layoutId, showAt) → receives, loads layout\n * ← layout-ready(layoutId, displayId)\n * (waits for all followers ready)\n * layout-show(layoutId) → shows layout simultaneously\n *\n * Heartbeat:\n * All nodes broadcast heartbeat every 5s.\n * Lead tracks active followers. If a follower goes silent for 15s,\n * it's considered offline and excluded from ready-wait.\n *\n * @module @xiboplayer/sync\n */\n\n/**\n * @typedef {Object} SyncConfig\n * @property {string} syncGroup - \"lead\" or leader's LAN IP\n * @property {number} syncPublisherPort - TCP port (unused in browser, kept for compat)\n * @property {number} syncSwitchDelay - Delay in ms before showing new content\n * @property {number} syncVideoPauseDelay - Delay in ms before unpausing video\n * @property {boolean} isLead - Whether this display is the leader\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst CHANNEL_NAME = 'xibo-sync';\nconst HEARTBEAT_INTERVAL = 5000; // Send heartbeat every 5s\nconst FOLLOWER_TIMEOUT = 15000; // Consider follower offline after 15s silence\nconst READY_TIMEOUT = 10000; // Max wait for followers to be ready\n\nexport class SyncManager {\n /**\n * @param {Object} options\n * @param {string} options.displayId - This display's unique hardware key\n * @param {SyncConfig} options.syncConfig - Sync configuration from RegisterDisplay\n * @param {Function} [options.onLayoutChange] - Called when lead requests layout change\n * @param {Function} [options.onLayoutShow] - Called when lead gives show signal\n * @param {Function} [options.onVideoStart] - Called when lead gives video start signal\n * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\n */\n constructor(options) {\n this.displayId = options.displayId;\n this.syncConfig = options.syncConfig;\n this.isLead = options.syncConfig.isLead;\n this.switchDelay = options.syncConfig.syncSwitchDelay || 750;\n this.videoPauseDelay = options.syncConfig.syncVideoPauseDelay || 100;\n\n // Callbacks\n this.onLayoutChange = options.onLayoutChange || (() => {});\n this.onLayoutShow = options.onLayoutShow || (() => {});\n this.onVideoStart = options.onVideoStart || (() => {});\n this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\n\n // State\n this.channel = null;\n this.followers = new Map(); // displayId → { lastSeen, ready }\n this._heartbeatTimer = null;\n this._cleanupTimer = null;\n this._readyResolve = null; // Resolve function for current ready-wait\n this._pendingLayoutId = null; // Layout we're waiting for readiness on\n this._started = false;\n\n // Logger with role prefix for clarity in multi-tab console\n this._tag = this.isLead ? '[Sync:LEAD]' : '[Sync:FOLLOW]';\n this._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /**\n * Start the sync manager (opens BroadcastChannel, begins heartbeats)\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n if (typeof BroadcastChannel === 'undefined') {\n this._log.warn( 'BroadcastChannel not available — sync disabled');\n return;\n }\n\n this.channel = new BroadcastChannel(CHANNEL_NAME);\n this.channel.onmessage = (event) => this._handleMessage(event.data);\n\n // Start heartbeat\n this._heartbeatTimer = setInterval(() => this._sendHeartbeat(), HEARTBEAT_INTERVAL);\n this._sendHeartbeat(); // Send initial heartbeat immediately\n\n // Lead: periodically clean up stale followers\n if (this.isLead) {\n this._cleanupTimer = setInterval(() => this._cleanupStaleFollowers(), HEARTBEAT_INTERVAL);\n }\n\n this._log.info( 'Started. DisplayId:', this.displayId);\n }\n\n /**\n * Stop the sync manager\n */\n stop() {\n if (!this._started) return;\n this._started = false;\n\n if (this._heartbeatTimer) {\n clearInterval(this._heartbeatTimer);\n this._heartbeatTimer = null;\n }\n if (this._cleanupTimer) {\n clearInterval(this._cleanupTimer);\n this._cleanupTimer = null;\n }\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n\n this.followers.clear();\n this._log.info( 'Stopped');\n }\n\n // ── Lead API ──────────────────────────────────────────────────────\n\n /**\n * [Lead only] Request all displays to change to a layout.\n * Waits for followers to report ready, then sends show signal.\n *\n * @param {string|number} layoutId - Layout to change to\n * @returns {Promise<void>} Resolves when show signal is sent\n */\n async requestLayoutChange(layoutId) {\n if (!this.isLead) {\n this._log.warn( 'requestLayoutChange called on follower — ignoring');\n return;\n }\n\n layoutId = String(layoutId);\n this._pendingLayoutId = layoutId;\n\n // Mark all followers as not-ready for this layout\n for (const [, follower] of this.followers) {\n follower.ready = false;\n follower.readyLayoutId = null;\n }\n\n const showAt = Date.now() + this.switchDelay;\n\n this._log.info( `Requesting layout change: ${layoutId} (show at ${new Date(showAt).toISOString()}, ${this.followers.size} followers)`);\n\n // Broadcast layout-change to all followers\n this._send({\n type: 'layout-change',\n layoutId,\n showAt,\n displayId: this.displayId,\n });\n\n // Wait for all active followers to report ready (or timeout)\n if (this.followers.size > 0) {\n await this._waitForFollowersReady(layoutId);\n }\n\n // Apply switch delay (remaining time from showAt)\n const remaining = showAt - Date.now();\n if (remaining > 0) {\n await new Promise(resolve => setTimeout(resolve, remaining));\n }\n\n // Send show signal\n this._log.info( `Sending layout-show: ${layoutId}`);\n this._send({\n type: 'layout-show',\n layoutId,\n displayId: this.displayId,\n });\n\n // Also trigger on self (lead shows too)\n this.onLayoutShow(layoutId);\n\n this._pendingLayoutId = null;\n }\n\n /**\n * [Lead only] Signal followers to start video playback.\n *\n * @param {string|number} layoutId - Layout containing the video\n * @param {string} regionId - Region with the video widget\n */\n async requestVideoStart(layoutId, regionId) {\n if (!this.isLead) return;\n\n // Wait videoPauseDelay before unpausing\n await new Promise(resolve => setTimeout(resolve, this.videoPauseDelay));\n\n this._send({\n type: 'video-start',\n layoutId: String(layoutId),\n regionId,\n displayId: this.displayId,\n });\n\n // Also trigger on self\n this.onVideoStart(String(layoutId), regionId);\n }\n\n // ── Follower API ──────────────────────────────────────────────────\n\n /**\n * [Follower only] Report that layout is loaded and ready to show.\n * Called by platform layer after layout content is prepared.\n *\n * @param {string|number} layoutId - Layout that is ready\n */\n reportReady(layoutId) {\n layoutId = String(layoutId);\n\n this._log.info( `Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\n });\n }\n\n // ── Message handling ──────────────────────────────────────────────\n\n /** @private */\n _handleMessage(msg) {\n // Ignore our own messages\n if (msg.displayId === this.displayId) return;\n\n switch (msg.type) {\n case 'heartbeat':\n this._handleHeartbeat(msg);\n break;\n\n case 'layout-change':\n // Follower: lead is requesting a layout change\n if (!this.isLead) {\n this._log.info( `Layout change requested: ${msg.layoutId}`);\n this.onLayoutChange(msg.layoutId, msg.showAt);\n }\n break;\n\n case 'layout-ready':\n // Lead: follower reports ready\n if (this.isLead) {\n this._handleFollowerReady(msg);\n }\n break;\n\n case 'layout-show':\n // Follower: lead says show now\n if (!this.isLead) {\n this._log.info( `Layout show signal: ${msg.layoutId}`);\n this.onLayoutShow(msg.layoutId);\n }\n break;\n\n case 'video-start':\n // Follower: lead says start video\n if (!this.isLead) {\n this._log.info( `Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn( 'Unknown message type:', msg.type);\n }\n }\n\n /** @private */\n _handleHeartbeat(msg) {\n const existing = this.followers.get(msg.displayId);\n if (existing) {\n existing.lastSeen = Date.now();\n } else {\n // New follower discovered\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: false,\n readyLayoutId: null,\n role: msg.role || 'unknown',\n });\n this._log.info( `Follower joined: ${msg.displayId} (${this.followers.size} total)`);\n }\n }\n\n /** @private */\n _handleFollowerReady(msg) {\n const follower = this.followers.get(msg.displayId);\n if (!follower) {\n // Late joiner — register them\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: true,\n readyLayoutId: msg.layoutId,\n });\n } else {\n follower.ready = true;\n follower.readyLayoutId = msg.layoutId;\n follower.lastSeen = Date.now();\n }\n\n this._log.info( `Follower ${msg.displayId} ready for layout ${msg.layoutId}`);\n\n // Check if all followers are now ready\n if (this._pendingLayoutId === msg.layoutId && this._readyResolve) {\n if (this._allFollowersReady(msg.layoutId)) {\n this._log.info( 'All followers ready');\n this._readyResolve();\n this._readyResolve = null;\n }\n }\n }\n\n /** @private */\n _allFollowersReady(layoutId) {\n for (const [, follower] of this.followers) {\n // Skip stale followers\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n if (!follower.ready || follower.readyLayoutId !== layoutId) {\n return false;\n }\n }\n return true;\n }\n\n /** @private */\n _waitForFollowersReady(layoutId) {\n return new Promise((resolve) => {\n // Already all ready?\n if (this._allFollowersReady(layoutId)) {\n resolve();\n return;\n }\n\n this._readyResolve = resolve;\n\n // Timeout: don't wait forever for unresponsive followers\n setTimeout(() => {\n if (this._readyResolve === resolve) {\n const notReady = [];\n for (const [id, f] of this.followers) {\n if (!f.ready || f.readyLayoutId !== layoutId) {\n notReady.push(id);\n }\n }\n this._log.warn( `Ready timeout — proceeding without: ${notReady.join(', ')}`);\n this._readyResolve = null;\n resolve();\n }\n }, READY_TIMEOUT);\n });\n }\n\n // ── Heartbeat & cleanup ───────────────────────────────────────────\n\n /** @private */\n _sendHeartbeat() {\n this._send({\n type: 'heartbeat',\n displayId: this.displayId,\n role: this.isLead ? 'lead' : 'follower',\n timestamp: Date.now(),\n });\n }\n\n /** @private */\n _cleanupStaleFollowers() {\n const now = Date.now();\n for (const [id, follower] of this.followers) {\n if (now - follower.lastSeen > FOLLOWER_TIMEOUT) {\n this._log.info( `Removing stale follower: ${id} (last seen ${Math.round((now - follower.lastSeen) / 1000)}s ago)`);\n this.followers.delete(id);\n }\n }\n }\n\n /** @private */\n _send(msg) {\n if (!this.channel) return;\n try {\n this.channel.postMessage(msg);\n } catch (e) {\n this._log.error( 'Failed to send:', e);\n }\n }\n\n // ── Status ────────────────────────────────────────────────────────\n\n /**\n * Get current sync status\n * @returns {Object}\n */\n getStatus() {\n return {\n started: this._started,\n isLead: this.isLead,\n displayId: this.displayId,\n followers: this.followers.size,\n pendingLayoutId: this._pendingLayoutId,\n followerDetails: Array.from(this.followers.entries()).map(([id, f]) => ({\n displayId: id,\n lastSeen: f.lastSeen,\n ready: f.ready,\n readyLayoutId: f.readyLayoutId,\n stale: Date.now() - f.lastSeen > FOLLOWER_TIMEOUT,\n })),\n };\n }\n}\n"],"names":["CHANNEL_NAME","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","createLogger","event","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","msg","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"0CAiCA,MAAMA,EAAe,YACfC,EAAqB,IACrBC,EAAmB,KACnBC,EAAgB,IAEf,MAAMC,CAAY,CAavB,YAAYC,EAAS,CACnB,KAAK,UAAYA,EAAQ,UACzB,KAAK,WAAaA,EAAQ,WAC1B,KAAK,OAASA,EAAQ,WAAW,OACjC,KAAK,YAAcA,EAAQ,WAAW,iBAAmB,IACzD,KAAK,gBAAkBA,EAAQ,WAAW,qBAAuB,IAGjE,KAAK,eAAiBA,EAAQ,iBAAmB,IAAM,CAAC,GACxD,KAAK,aAAeA,EAAQ,eAAiB,IAAM,CAAC,GACpD,KAAK,aAAeA,EAAQ,eAAiB,IAAM,CAAC,GACpD,KAAK,cAAgBA,EAAQ,eAAiB,KAC9C,KAAK,aAAeA,EAAQ,cAAgB,KAC5C,KAAK,WAAaA,EAAQ,YAAc,KACxC,KAAK,UAAYA,EAAQ,WAAa,KAGtC,KAAK,QAAU,KACf,KAAK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