@xiboplayer/pwa 0.7.6 → 0.7.7

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 (39) hide show
  1. package/dist/assets/{chunk-config-CtGszMx2.js → chunk-config-OyUiSIwW.js} +2 -2
  2. package/dist/assets/{chunk-config-CtGszMx2.js.map → chunk-config-OyUiSIwW.js.map} +1 -1
  3. package/dist/assets/{index-CE38S9TE.js → index-BD2cgPb_.js} +2 -2
  4. package/dist/assets/{index-CE38S9TE.js.map → index-BD2cgPb_.js.map} +1 -1
  5. package/dist/assets/index-Bb9n-Ju-.js +2 -0
  6. package/dist/assets/{index-DBfpBHOx.js.map → index-Bb9n-Ju-.js.map} +1 -1
  7. package/dist/assets/{index-BxpD1DTX.js → index-Bdq-9Ijm.js} +2 -2
  8. package/dist/assets/{index-BxpD1DTX.js.map → index-Bdq-9Ijm.js.map} +1 -1
  9. package/dist/assets/{index-BDvux0OF.js → index-C1uotN1B.js} +2 -2
  10. package/dist/assets/{index-BDvux0OF.js.map → index-C1uotN1B.js.map} +1 -1
  11. package/dist/assets/{index-bu0rBE8x.js → index-C7M3Dt36.js} +2 -2
  12. package/dist/assets/{index-bu0rBE8x.js.map → index-C7M3Dt36.js.map} +1 -1
  13. package/dist/assets/{index-BDSqvUhR.js → index-CVLSZEkt.js} +2 -2
  14. package/dist/assets/{index-BDSqvUhR.js.map → index-CVLSZEkt.js.map} +1 -1
  15. package/dist/assets/{index-5h0f0o88.js → index-Cn_8cMrf.js} +2 -2
  16. package/dist/assets/{index-5h0f0o88.js.map → index-Cn_8cMrf.js.map} +1 -1
  17. package/dist/assets/{index-Cl94z6w6.js → index-D4BJcEJL.js} +2 -2
  18. package/dist/assets/{index-Cl94z6w6.js.map → index-D4BJcEJL.js.map} +1 -1
  19. package/dist/assets/{index-B9GIC3M0.js → index-DF23jxDG.js} +2 -2
  20. package/dist/assets/{index-B9GIC3M0.js.map → index-DF23jxDG.js.map} +1 -1
  21. package/dist/assets/index-SXOSZnY5.js +2 -0
  22. package/dist/assets/{index-IpZ9x4sq.js.map → index-SXOSZnY5.js.map} +1 -1
  23. package/dist/assets/{main-BMbDOb9z.js → main-CzNhJuY0.js} +16 -16
  24. package/dist/assets/main-CzNhJuY0.js.map +1 -0
  25. package/dist/assets/{protocol-detector-DBvKoxwk.js → protocol-detector-DUbPCvg3.js} +2 -2
  26. package/dist/assets/{protocol-detector-DBvKoxwk.js.map → protocol-detector-DUbPCvg3.js.map} +1 -1
  27. package/dist/assets/{setup-XWkrt320.js → setup-6_OH1OHn.js} +2 -2
  28. package/dist/assets/{setup-XWkrt320.js.map → setup-6_OH1OHn.js.map} +1 -1
  29. package/dist/assets/{sync-manager-DjnEDn56.js → sync-manager-DpfoR8OE.js} +2 -2
  30. package/dist/assets/{sync-manager-DjnEDn56.js.map → sync-manager-DpfoR8OE.js.map} +1 -1
  31. package/dist/assets/{widget-html-Bo9WgcY3.js → widget-html-BpnFG_FM.js} +2 -2
  32. package/dist/assets/{widget-html-Bo9WgcY3.js.map → widget-html-BpnFG_FM.js.map} +1 -1
  33. package/dist/index.html +3 -3
  34. package/dist/setup.html +3 -3
  35. package/dist/sw-pwa.js +1 -1
  36. package/package.json +13 -13
  37. package/dist/assets/index-DBfpBHOx.js +0 -2
  38. package/dist/assets/index-IpZ9x4sq.js +0 -2
  39. package/dist/assets/main-BMbDOb9z.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"setup-XWkrt320.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' + window.location.search;\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 /api/* forward proxy) ──\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('/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 `/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 `/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.data.apiClientId = clientId;\n config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html' + window.location.search;\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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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 // Always POST to proxy — updates in-memory config for REST auth,\n // cache-through, and API forwarding. Works on all players.\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 // Shell persistence (Electron config.json) — optional, on top of proxy\n const electronAPI = window.electronAPI || window.parent?.electronAPI;\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ cmsUrl, cmsKey, displayName });\n }\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 // Persist API client credentials so they survive restarts\n config.save();\n await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret }),\n });\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret });\n }\n\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' + window.location.search;\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","electronAPI","_a","backupHardwareKey","client","key","req","db","tx"],"mappings":"qJAKI,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,EAC9DC,EAAU,SAAS,eAAe,UAAU,EAC5CC,EAAe,SAAS,eAAe,eAAe,EAGtDC,EAAQC,EAAO,YACrB,SAAS,eAAe,gBAAgB,EAAE,YAAcD,EACxD,SAAS,eAAe,gBAAgB,EAAE,YAAcA,EAGxD,MAAME,EAAiBD,EAAO,QAAU,GACxC,IAAIE,EAAY,KACZC,EAAiB,KACjBC,EAAc,GAGdC,EAAY,KAChB,eAAeC,GAAe,CAC5B,GAAID,EAAW,OAAOA,EACtB,GAAI,CACF,MAAME,EAAO,IAAIC,EAAWR,CAAM,EAClC,MAAMO,EAAK,gBAAA,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BAAkB,CAAC,EAC9CA,EAAI,gBAAkB,IAAM,CAC1B,MAAMC,EAAKD,EAAI,OACVC,EAAG,iBAAiB,SAAS,MAAM,GACtCA,EAAG,kBAAkB,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,OAASzC,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,qBAAuB,OAAO,SAAS,OAG9DkB,EAAaxB,EAAO,WAAW,CAEnC,MAAY,CAEV,QAAQ,IAAI,yCAAyC,CACvD,CACF,GAAA"}
1
+ {"version":3,"file":"setup-6_OH1OHn.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' + window.location.search;\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 /api/* forward proxy) ──\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('/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 `/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 `/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.data.apiClientId = clientId;\n config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html' + window.location.search;\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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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 // Always POST to proxy — updates in-memory config for REST auth,\n // cache-through, and API forwarding. Works on all players.\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 // Shell persistence (Electron config.json) — optional, on top of proxy\n const electronAPI = window.electronAPI || window.parent?.electronAPI;\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ cmsUrl, cmsKey, displayName });\n }\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 // Persist API client credentials so they survive restarts\n config.save();\n await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret }),\n });\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret });\n }\n\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' + window.location.search;\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","electronAPI","_a","backupHardwareKey","client","key","req","db","tx"],"mappings":"qJAKI,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,EAC9DC,EAAU,SAAS,eAAe,UAAU,EAC5CC,EAAe,SAAS,eAAe,eAAe,EAGtDC,EAAQC,EAAO,YACrB,SAAS,eAAe,gBAAgB,EAAE,YAAcD,EACxD,SAAS,eAAe,gBAAgB,EAAE,YAAcA,EAGxD,MAAME,EAAiBD,EAAO,QAAU,GACxC,IAAIE,EAAY,KACZC,EAAiB,KACjBC,EAAc,GAGdC,EAAY,KAChB,eAAeC,GAAe,CAC5B,GAAID,EAAW,OAAOA,EACtB,GAAI,CACF,MAAME,EAAO,IAAIC,EAAWR,CAAM,EAClC,MAAMO,EAAK,gBAAA,EACX,QAAQ,IAAI,8BAA8B,EAC1CF,EAAYE,CACd,OAASE,EAAG,CACV,QAAQ,IAAI,6CAA8CA,EAAE,OAAO,EACnEJ,EAAY,IAAIK,EAAWV,CAAM,CACnC,CACA,OAAOK,CACT,CAGA,SAASM,EAAUC,EAAO,CACxBpB,EAAY,UAAU,OAAO,QAAQ,EACrCC,EA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,EAC7CC,EAAG,YAAY,MAAM,EAAE,IAAIH,EAAK,aAAa,EAC7CG,EAAG,WAAa,IAAMD,EAAG,MAAA,CAC3B,CACF,OAASzC,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,qBAAuB,OAAO,SAAS,OAG9DkB,EAAaxB,EAAO,WAAW,CAEnC,MAAY,CAEV,QAAQ,IAAI,yCAAyC,CACvD,CACF,GAAA"}
@@ -1,2 +1,2 @@
1
- import{createLogger as _}from"./index-5h0f0o88.js";const w="xibo-sync";class I{constructor(t=w){this.channel=new BroadcastChannel(t),this._connected=!0}send(t){this.channel&&this.channel.postMessage(t)}onMessage(t){this.channel.onmessage=e=>t(e.data)}close(){this.channel&&(this.channel.close(),this.channel=null),this._connected=!1}get connected(){return this._connected&&!!this.channel}}const u=1e3,g=3e4,S=2;class L{constructor(t,{syncGroup:e,displayId:i,topology:s,token:a}={}){this._url=t,this._syncGroup=e||null,this._displayId=i||null,this._topology=s||null,this._token=a||null,this._callback=null,this._closed=!1,this._retryMs=u,this._retryTimer=null,this._log=_("WS-Sync"),this.ws=null,this._connect()}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}onMessage(t){this._callback=t}close(){this._closed=!0,this._retryTimer&&(clearTimeout(this._retryTimer),this._retryTimer=null),this.ws&&(this.ws.close(),this.ws=null)}get connected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}_connect(){if(!this._closed){try{this.ws=new WebSocket(this._url)}catch(t){this._log.error("WebSocket creation failed:",t.message),this._scheduleReconnect();return}this.ws.onopen=()=>{if(this._log.info(`Connected to ${this._url}`),this._retryMs=u,this._syncGroup){const t={type:"join",syncGroup:this._syncGroup};this._displayId&&(t.displayId=this._displayId),this._topology&&(t.topology=this._topology),this._token&&(t.token=this._token),this.ws.send(JSON.stringify(t))}},this.ws.onmessage=async t=>{if(this._callback)try{let e=t.data;typeof e!="string"&&(e=e instanceof Blob?await e.text():String(e));const i=JSON.parse(e);this._callback(i)}catch(e){this._log.warn("Failed to parse message:",e.message)}},this.ws.onclose=()=>{this._closed||(this._log.info("Connection closed — will reconnect"),this._scheduleReconnect())},this.ws.onerror=t=>{this._log.warn("WebSocket error")}}}_scheduleReconnect(){this._closed||this._retryTimer||(this._log.info(`Reconnecting in ${this._retryMs}ms...`),this._retryTimer=setTimeout(()=>{this._retryTimer=null,this._connect()},this._retryMs),this._retryMs=Math.min(this._retryMs*S,g))}}function D({choreography:n,position:t,totalDisplays:e,topology:i,gridCols:s,gridRows:a,staggerMs:o}){return!n||n==="simultaneous"||!o?0:i&&s!=null&&a!=null?s<=1&&a<=1?0:b(n,i,s,a,o):e==null||e<=1?0:k(n,t??0,e,o)}function k(n,t,e,i){const s=e-1,a=s/2;switch(n){case"wave-right":return t*i;case"wave-left":return(s-t)*i;case"center-out":return Math.round(Math.abs(t-a))*i;case"outside-in":return(Math.round(a)-Math.round(Math.abs(t-a)))*i;case"random":return Math.floor(Math.random()*s*i);default:return 0}}function b(n,t,e,i,s){const{x:a,y:o}=t,r=e-1,l=i-1,c=r/2,y=l/2;switch(n){case"wave-right":return a*s;case"wave-left":return(r-a)*s;case"wave-down":return o*s;case"wave-up":return(l-o)*s;case"diagonal-tl":return(a+o)*s;case"diagonal-tr":return(r-a+o)*s;case"diagonal-bl":return(a+(l-o))*s;case"diagonal-br":return(r-a+(l-o))*s;case"center-out":{const h=Math.sqrt((a-c)**2+(o-y)**2);return Math.round(h)*s}case"outside-in":{const h=Math.round(Math.sqrt(c**2+y**2)),p=Math.sqrt((a-c)**2+(o-y)**2);return(h-Math.round(p))*s}case"random":{const h=r+l;return Math.floor(Math.random()*h*s)}default:return 0}}const f=5e3,d=15e3,R=1e4;class A{constructor(t){this.displayId=t.displayId,this.syncConfig=t.syncConfig,this.isLead=t.syncConfig.isLead,this.switchDelay=t.syncConfig.syncSwitchDelay||750,this.videoPauseDelay=t.syncConfig.syncVideoPauseDelay||100,this.onLayoutChange=t.onLayoutChange||(()=>{}),this.onLayoutShow=t.onLayoutShow||(()=>{}),this.onVideoStart=t.onVideoStart||(()=>{}),this.onStatsReport=t.onStatsReport||null,this.onLogsReport=t.onLogsReport||null,this.onStatsAck=t.onStatsAck||null,this.onLogsAck=t.onLogsAck||null,this.onGroupUpdate=t.onGroupUpdate||null,this.transport=t.transport||null,this.followers=new Map,this._heartbeatTimer=null,this._cleanupTimer=null,this._readyResolve=null,this._pendingLayoutId=null,this._started=!1,this._log=_(this.isLead?"Sync:LEAD":"Sync:FOLLOW")}start(){if(!this._started){if(this._started=!0,!this.transport)if(this.syncConfig.relayUrl)this.transport=new L(this.syncConfig.relayUrl,{syncGroup:this.syncConfig.syncGroup,displayId:this.displayId,topology:this.syncConfig.topology,token:this.syncConfig.syncToken});else if(typeof BroadcastChannel<"u")this.transport=new I;else{this._log.warn("No transport available — sync disabled");return}this.transport.onMessage(t=>this._handleMessage(t)),this._heartbeatTimer=setInterval(()=>this._sendHeartbeat(),f),this._sendHeartbeat(),this.isLead&&(this._cleanupTimer=setInterval(()=>this._cleanupStaleFollowers(),f)),this._log.info("Started. DisplayId:",this.displayId,this.syncConfig.relayUrl?`(relay: ${this.syncConfig.relayUrl})`:"(BroadcastChannel)")}}stop(){this._started&&(this._started=!1,this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null),this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null),this.transport&&(this.transport.close(),this.transport=null),this.followers.clear(),this._log.info("Stopped"))}async requestLayoutChange(t){if(!this.isLead){this._log.warn("requestLayoutChange called on follower — ignoring");return}t=String(t),this._pendingLayoutId=t;for(const[,s]of this.followers)Date.now()-s.lastSeen>d||(s.ready=!1,s.readyLayoutId=null);const e=Date.now()+this.switchDelay;this._log.info(`Requesting layout change: ${t} (show at ${new Date(e).toISOString()}, ${this.followers.size} followers)`),this._send({type:"layout-change",layoutId:t,showAt:e,displayId:this.displayId}),this.followers.size>0&&await this._waitForFollowersReady(t);const i=e-Date.now();i>0&&await new Promise(s=>setTimeout(s,i)),this._log.info(`Sending layout-show: ${t}`),this._send({type:"layout-show",layoutId:t,displayId:this.displayId}),this.onLayoutShow(t),this._pendingLayoutId=null}async requestVideoStart(t,e){this.isLead&&(await new Promise(i=>setTimeout(i,this.videoPauseDelay)),this._send({type:"video-start",layoutId:String(t),regionId:e,displayId:this.displayId}),this.onVideoStart(String(t),e))}reportReady(t){t=String(t),this._log.info(`Reporting ready for layout ${t}`),this._send({type:"layout-ready",layoutId:t,displayId:this.displayId})}reportStats(t){this.isLead||(this._log.info("Delegating stats to lead"),this._send({type:"stats-report",displayId:this.displayId,statsXml:t}))}reportLogs(t){this.isLead||(this._log.info("Delegating logs to lead"),this._send({type:"logs-report",displayId:this.displayId,logsXml:t}))}_handleMessage(t){if(t.type==="group-update"){this._log.info(`Group update: ${t.totalDisplays} displays`),this.onGroupUpdate&&this.onGroupUpdate(t.totalDisplays,t.topology||{});return}if(t.displayId!==this.displayId)switch(t.type){case"heartbeat":this._handleHeartbeat(t);break;case"layout-change":this.isLead||(this._log.info(`Layout change requested: ${t.layoutId}`),this.onLayoutChange(t.layoutId,t.showAt));break;case"layout-ready":this.isLead&&this._handleFollowerReady(t);break;case"layout-show":this.isLead||(this._log.info(`Layout show signal: ${t.layoutId}`),this.onLayoutShow(t.layoutId));break;case"video-start":this.isLead||(this._log.info(`Video start signal: ${t.layoutId} region ${t.regionId}`),this.onVideoStart(t.layoutId,t.regionId));break;case"stats-report":if(this.isLead&&this.onStatsReport){const e=()=>this._send({type:"stats-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onStatsReport(t.displayId,t.statsXml,e)}break;case"logs-report":if(this.isLead&&this.onLogsReport){const e=()=>this._send({type:"logs-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onLogsReport(t.displayId,t.logsXml,e)}break;case"stats-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onStatsAck&&(this._log.info("Stats acknowledged by lead"),this.onStatsAck(t.targetDisplayId));break;case"logs-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onLogsAck&&(this._log.info("Logs acknowledged by lead"),this.onLogsAck(t.targetDisplayId));break;default:this._log.warn("Unknown message type:",t.type)}}_handleHeartbeat(t){const e=this.followers.get(t.displayId);e?e.lastSeen=Date.now():(this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!1,readyLayoutId:null,role:t.role||"unknown"}),this._log.info(`Follower joined: ${t.displayId} (${this.followers.size} total)`))}_handleFollowerReady(t){const e=this.followers.get(t.displayId);e?(e.ready=!0,e.readyLayoutId=t.layoutId,e.lastSeen=Date.now()):this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!0,readyLayoutId:t.layoutId}),this._log.info(`Follower ${t.displayId} ready for layout ${t.layoutId}`),this._pendingLayoutId===t.layoutId&&this._readyResolve&&this._allFollowersReady(t.layoutId)&&(this._log.info("All followers ready"),this._readyResolve(),this._readyResolve=null)}_allFollowersReady(t){for(const[,e]of this.followers)if(!(Date.now()-e.lastSeen>d)&&(!e.ready||e.readyLayoutId!==t))return!1;return!0}_waitForFollowersReady(t){return new Promise(e=>{if(this._allFollowersReady(t)){e();return}this._readyResolve=e,setTimeout(()=>{if(this._readyResolve===e){const i=[];for(const[s,a]of this.followers)(!a.ready||a.readyLayoutId!==t)&&i.push(s);this._log.warn(`Ready timeout — proceeding without: ${i.join(", ")}`),this._readyResolve=null,e()}},R)})}_sendHeartbeat(){this._send({type:"heartbeat",displayId:this.displayId,role:this.isLead?"lead":"follower",timestamp:Date.now()})}_cleanupStaleFollowers(){const t=Date.now();for(const[e,i]of this.followers)t-i.lastSeen>d&&(this._log.info(`Removing stale follower: ${e} (last seen ${Math.round((t-i.lastSeen)/1e3)}s ago)`),this.followers.delete(e))}_send(t){if(this.transport)try{this.transport.send(t)}catch(e){this._log.error("Failed to send:",e)}}getStatus(){return{started:this._started,isLead:this.isLead,displayId:this.displayId,followers:this.followers.size,pendingLayoutId:this._pendingLayoutId,transport:this.syncConfig.relayUrl?"websocket":"broadcast-channel",followerDetails:Array.from(this.followers.entries()).map(([t,e])=>({displayId:t,lastSeen:e.lastSeen,ready:e.ready,readyLayoutId:e.readyLayoutId,stale:Date.now()-e.lastSeen>d}))}}}export{I as BroadcastChannelTransport,A as SyncManager,L as WebSocketTransport,D as computeStagger};
2
- //# sourceMappingURL=sync-manager-DjnEDn56.js.map
1
+ import{createLogger as _}from"./index-Cn_8cMrf.js";const w="xibo-sync";class I{constructor(t=w){this.channel=new BroadcastChannel(t),this._connected=!0}send(t){this.channel&&this.channel.postMessage(t)}onMessage(t){this.channel.onmessage=e=>t(e.data)}close(){this.channel&&(this.channel.close(),this.channel=null),this._connected=!1}get connected(){return this._connected&&!!this.channel}}const u=1e3,g=3e4,S=2;class L{constructor(t,{syncGroup:e,displayId:i,topology:s,token:a}={}){this._url=t,this._syncGroup=e||null,this._displayId=i||null,this._topology=s||null,this._token=a||null,this._callback=null,this._closed=!1,this._retryMs=u,this._retryTimer=null,this._log=_("WS-Sync"),this.ws=null,this._connect()}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}onMessage(t){this._callback=t}close(){this._closed=!0,this._retryTimer&&(clearTimeout(this._retryTimer),this._retryTimer=null),this.ws&&(this.ws.close(),this.ws=null)}get connected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}_connect(){if(!this._closed){try{this.ws=new WebSocket(this._url)}catch(t){this._log.error("WebSocket creation failed:",t.message),this._scheduleReconnect();return}this.ws.onopen=()=>{if(this._log.info(`Connected to ${this._url}`),this._retryMs=u,this._syncGroup){const t={type:"join",syncGroup:this._syncGroup};this._displayId&&(t.displayId=this._displayId),this._topology&&(t.topology=this._topology),this._token&&(t.token=this._token),this.ws.send(JSON.stringify(t))}},this.ws.onmessage=async t=>{if(this._callback)try{let e=t.data;typeof e!="string"&&(e=e instanceof Blob?await e.text():String(e));const i=JSON.parse(e);this._callback(i)}catch(e){this._log.warn("Failed to parse message:",e.message)}},this.ws.onclose=()=>{this._closed||(this._log.info("Connection closed — will reconnect"),this._scheduleReconnect())},this.ws.onerror=t=>{this._log.warn("WebSocket error")}}}_scheduleReconnect(){this._closed||this._retryTimer||(this._log.info(`Reconnecting in ${this._retryMs}ms...`),this._retryTimer=setTimeout(()=>{this._retryTimer=null,this._connect()},this._retryMs),this._retryMs=Math.min(this._retryMs*S,g))}}function D({choreography:n,position:t,totalDisplays:e,topology:i,gridCols:s,gridRows:a,staggerMs:o}){return!n||n==="simultaneous"||!o?0:i&&s!=null&&a!=null?s<=1&&a<=1?0:b(n,i,s,a,o):e==null||e<=1?0:k(n,t??0,e,o)}function k(n,t,e,i){const s=e-1,a=s/2;switch(n){case"wave-right":return t*i;case"wave-left":return(s-t)*i;case"center-out":return Math.round(Math.abs(t-a))*i;case"outside-in":return(Math.round(a)-Math.round(Math.abs(t-a)))*i;case"random":return Math.floor(Math.random()*s*i);default:return 0}}function b(n,t,e,i,s){const{x:a,y:o}=t,r=e-1,l=i-1,c=r/2,y=l/2;switch(n){case"wave-right":return a*s;case"wave-left":return(r-a)*s;case"wave-down":return o*s;case"wave-up":return(l-o)*s;case"diagonal-tl":return(a+o)*s;case"diagonal-tr":return(r-a+o)*s;case"diagonal-bl":return(a+(l-o))*s;case"diagonal-br":return(r-a+(l-o))*s;case"center-out":{const h=Math.sqrt((a-c)**2+(o-y)**2);return Math.round(h)*s}case"outside-in":{const h=Math.round(Math.sqrt(c**2+y**2)),p=Math.sqrt((a-c)**2+(o-y)**2);return(h-Math.round(p))*s}case"random":{const h=r+l;return Math.floor(Math.random()*h*s)}default:return 0}}const f=5e3,d=15e3,R=1e4;class A{constructor(t){this.displayId=t.displayId,this.syncConfig=t.syncConfig,this.isLead=t.syncConfig.isLead,this.switchDelay=t.syncConfig.syncSwitchDelay||750,this.videoPauseDelay=t.syncConfig.syncVideoPauseDelay||100,this.onLayoutChange=t.onLayoutChange||(()=>{}),this.onLayoutShow=t.onLayoutShow||(()=>{}),this.onVideoStart=t.onVideoStart||(()=>{}),this.onStatsReport=t.onStatsReport||null,this.onLogsReport=t.onLogsReport||null,this.onStatsAck=t.onStatsAck||null,this.onLogsAck=t.onLogsAck||null,this.onGroupUpdate=t.onGroupUpdate||null,this.transport=t.transport||null,this.followers=new Map,this._heartbeatTimer=null,this._cleanupTimer=null,this._readyResolve=null,this._pendingLayoutId=null,this._started=!1,this._log=_(this.isLead?"Sync:LEAD":"Sync:FOLLOW")}start(){if(!this._started){if(this._started=!0,!this.transport)if(this.syncConfig.relayUrl)this.transport=new L(this.syncConfig.relayUrl,{syncGroup:this.syncConfig.syncGroup,displayId:this.displayId,topology:this.syncConfig.topology,token:this.syncConfig.syncToken});else if(typeof BroadcastChannel<"u")this.transport=new I;else{this._log.warn("No transport available — sync disabled");return}this.transport.onMessage(t=>this._handleMessage(t)),this._heartbeatTimer=setInterval(()=>this._sendHeartbeat(),f),this._sendHeartbeat(),this.isLead&&(this._cleanupTimer=setInterval(()=>this._cleanupStaleFollowers(),f)),this._log.info("Started. DisplayId:",this.displayId,this.syncConfig.relayUrl?`(relay: ${this.syncConfig.relayUrl})`:"(BroadcastChannel)")}}stop(){this._started&&(this._started=!1,this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null),this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null),this.transport&&(this.transport.close(),this.transport=null),this.followers.clear(),this._log.info("Stopped"))}async requestLayoutChange(t){if(!this.isLead){this._log.warn("requestLayoutChange called on follower — ignoring");return}t=String(t),this._pendingLayoutId=t;for(const[,s]of this.followers)Date.now()-s.lastSeen>d||(s.ready=!1,s.readyLayoutId=null);const e=Date.now()+this.switchDelay;this._log.info(`Requesting layout change: ${t} (show at ${new Date(e).toISOString()}, ${this.followers.size} followers)`),this._send({type:"layout-change",layoutId:t,showAt:e,displayId:this.displayId}),this.followers.size>0&&await this._waitForFollowersReady(t);const i=e-Date.now();i>0&&await new Promise(s=>setTimeout(s,i)),this._log.info(`Sending layout-show: ${t}`),this._send({type:"layout-show",layoutId:t,displayId:this.displayId}),this.onLayoutShow(t),this._pendingLayoutId=null}async requestVideoStart(t,e){this.isLead&&(await new Promise(i=>setTimeout(i,this.videoPauseDelay)),this._send({type:"video-start",layoutId:String(t),regionId:e,displayId:this.displayId}),this.onVideoStart(String(t),e))}reportReady(t){t=String(t),this._log.info(`Reporting ready for layout ${t}`),this._send({type:"layout-ready",layoutId:t,displayId:this.displayId})}reportStats(t){this.isLead||(this._log.info("Delegating stats to lead"),this._send({type:"stats-report",displayId:this.displayId,statsXml:t}))}reportLogs(t){this.isLead||(this._log.info("Delegating logs to lead"),this._send({type:"logs-report",displayId:this.displayId,logsXml:t}))}_handleMessage(t){if(t.type==="group-update"){this._log.info(`Group update: ${t.totalDisplays} displays`),this.onGroupUpdate&&this.onGroupUpdate(t.totalDisplays,t.topology||{});return}if(t.displayId!==this.displayId)switch(t.type){case"heartbeat":this._handleHeartbeat(t);break;case"layout-change":this.isLead||(this._log.info(`Layout change requested: ${t.layoutId}`),this.onLayoutChange(t.layoutId,t.showAt));break;case"layout-ready":this.isLead&&this._handleFollowerReady(t);break;case"layout-show":this.isLead||(this._log.info(`Layout show signal: ${t.layoutId}`),this.onLayoutShow(t.layoutId));break;case"video-start":this.isLead||(this._log.info(`Video start signal: ${t.layoutId} region ${t.regionId}`),this.onVideoStart(t.layoutId,t.regionId));break;case"stats-report":if(this.isLead&&this.onStatsReport){const e=()=>this._send({type:"stats-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onStatsReport(t.displayId,t.statsXml,e)}break;case"logs-report":if(this.isLead&&this.onLogsReport){const e=()=>this._send({type:"logs-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onLogsReport(t.displayId,t.logsXml,e)}break;case"stats-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onStatsAck&&(this._log.info("Stats acknowledged by lead"),this.onStatsAck(t.targetDisplayId));break;case"logs-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onLogsAck&&(this._log.info("Logs acknowledged by lead"),this.onLogsAck(t.targetDisplayId));break;default:this._log.warn("Unknown message type:",t.type)}}_handleHeartbeat(t){const e=this.followers.get(t.displayId);e?e.lastSeen=Date.now():(this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!1,readyLayoutId:null,role:t.role||"unknown"}),this._log.info(`Follower joined: ${t.displayId} (${this.followers.size} total)`))}_handleFollowerReady(t){const e=this.followers.get(t.displayId);e?(e.ready=!0,e.readyLayoutId=t.layoutId,e.lastSeen=Date.now()):this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!0,readyLayoutId:t.layoutId}),this._log.info(`Follower ${t.displayId} ready for layout ${t.layoutId}`),this._pendingLayoutId===t.layoutId&&this._readyResolve&&this._allFollowersReady(t.layoutId)&&(this._log.info("All followers ready"),this._readyResolve(),this._readyResolve=null)}_allFollowersReady(t){for(const[,e]of this.followers)if(!(Date.now()-e.lastSeen>d)&&(!e.ready||e.readyLayoutId!==t))return!1;return!0}_waitForFollowersReady(t){return new Promise(e=>{if(this._allFollowersReady(t)){e();return}this._readyResolve=e,setTimeout(()=>{if(this._readyResolve===e){const i=[];for(const[s,a]of this.followers)(!a.ready||a.readyLayoutId!==t)&&i.push(s);this._log.warn(`Ready timeout — proceeding without: ${i.join(", ")}`),this._readyResolve=null,e()}},R)})}_sendHeartbeat(){this._send({type:"heartbeat",displayId:this.displayId,role:this.isLead?"lead":"follower",timestamp:Date.now()})}_cleanupStaleFollowers(){const t=Date.now();for(const[e,i]of this.followers)t-i.lastSeen>d&&(this._log.info(`Removing stale follower: ${e} (last seen ${Math.round((t-i.lastSeen)/1e3)}s ago)`),this.followers.delete(e))}_send(t){if(this.transport)try{this.transport.send(t)}catch(e){this._log.error("Failed to send:",e)}}getStatus(){return{started:this._started,isLead:this.isLead,displayId:this.displayId,followers:this.followers.size,pendingLayoutId:this._pendingLayoutId,transport:this.syncConfig.relayUrl?"websocket":"broadcast-channel",followerDetails:Array.from(this.followers.entries()).map(([t,e])=>({displayId:t,lastSeen:e.lastSeen,ready:e.ready,readyLayoutId:e.readyLayoutId,stale:Date.now()-e.lastSeen>d}))}}}export{I as BroadcastChannelTransport,A as SyncManager,L as WebSocketTransport,D as computeStagger};
2
+ //# sourceMappingURL=sync-manager-DpfoR8OE.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sync-manager-DjnEDn56.js","sources":["../../../sync/src/bc-transport.js","../../../sync/src/ws-transport.js","../../../sync/src/choreography.js","../../../sync/src/sync-manager.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * BroadcastChannelTransport — same-machine sync transport\n *\n * Wraps the browser BroadcastChannel API behind the sync transport interface.\n * Used for multi-tab / multi-window sync on a single device.\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nconst DEFAULT_CHANNEL = 'xibo-sync';\n\nexport class BroadcastChannelTransport {\n /**\n * @param {string} [channelName='xibo-sync']\n */\n constructor(channelName = DEFAULT_CHANNEL) {\n this.channel = new BroadcastChannel(channelName);\n this._connected = true;\n }\n\n /**\n * Send a message to all other tabs/windows on this channel.\n * @param {Object} msg — plain object (structured-cloned by BroadcastChannel)\n */\n send(msg) {\n if (!this.channel) return;\n this.channel.postMessage(msg);\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the message data (already deserialized)\n */\n onMessage(callback) {\n this.channel.onmessage = (e) => callback(e.data);\n }\n\n /** Close the channel. */\n close() {\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n this._connected = false;\n }\n\n /** @returns {boolean} Whether the channel is open */\n get connected() {\n return this._connected && !!this.channel;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * WebSocketTransport — cross-device sync transport\n *\n * Connects to the lead player's proxy WebSocket relay at /sync.\n * Used for LAN video walls where each screen is a separate device.\n *\n * Features:\n * - Auto-reconnect with exponential backoff (1s → 2s → 4s → max 30s)\n * - JSON serialization (WebSocket sends strings, not structured clones)\n * - Same transport interface as BroadcastChannelTransport\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst INITIAL_RETRY_MS = 1000;\nconst MAX_RETRY_MS = 30000;\nconst BACKOFF_FACTOR = 2;\n\nexport class WebSocketTransport {\n /**\n * @param {string} url — WebSocket URL, e.g. ws://192.168.1.100:8765/sync\n * @param {Object} [options]\n * @param {string} [options.syncGroup] — group name for relay isolation\n * @param {string} [options.displayId] — this display's unique ID\n * @param {Object} [options.topology] — this display's topology { x, y, orientation? }\n * @param {string} [options.token] — auth token for relay join validation\n */\n constructor(url, { syncGroup, displayId, topology, token } = {}) {\n this._url = url;\n this._syncGroup = syncGroup || null;\n this._displayId = displayId || null;\n this._topology = topology || null;\n this._token = token || null;\n this._callback = null;\n this._closed = false;\n this._retryMs = INITIAL_RETRY_MS;\n this._retryTimer = null;\n this._log = createLogger('WS-Sync');\n this.ws = null;\n\n this._connect();\n }\n\n /**\n * Send a message to the relay (which broadcasts to other clients).\n * @param {Object} msg — plain object (JSON-serialized for WebSocket)\n */\n send(msg) {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the parsed message object\n */\n onMessage(callback) {\n this._callback = callback;\n }\n\n /** Close the connection and stop reconnecting. */\n close() {\n this._closed = true;\n if (this._retryTimer) {\n clearTimeout(this._retryTimer);\n this._retryTimer = null;\n }\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n\n /** @returns {boolean} Whether the WebSocket is open */\n get connected() {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n /** @private */\n _connect() {\n if (this._closed) return;\n\n try {\n this.ws = new WebSocket(this._url);\n } catch (e) {\n this._log.error('WebSocket creation failed:', e.message);\n this._scheduleReconnect();\n return;\n }\n\n this.ws.onopen = () => {\n this._log.info(`Connected to ${this._url}`);\n this._retryMs = INITIAL_RETRY_MS; // Reset backoff on success\n\n // Join sync group for relay isolation (+ topology for auto-detection)\n if (this._syncGroup) {\n const join = { type: 'join', syncGroup: this._syncGroup };\n if (this._displayId) join.displayId = this._displayId;\n if (this._topology) join.topology = this._topology;\n if (this._token) join.token = this._token;\n this.ws.send(JSON.stringify(join));\n }\n };\n\n this.ws.onmessage = async (event) => {\n if (!this._callback) return;\n try {\n // Browser WebSocket delivers string; Node ws delivers Buffer;\n // Node 22+ native WebSocket delivers Blob. Handle all three.\n let raw = event.data;\n if (typeof raw !== 'string') {\n raw = (raw instanceof Blob) ? await raw.text() : String(raw);\n }\n const msg = JSON.parse(raw);\n this._callback(msg);\n } catch (e) {\n this._log.warn('Failed to parse message:', e.message);\n }\n };\n\n this.ws.onclose = () => {\n if (!this._closed) {\n this._log.info('Connection closed — will reconnect');\n this._scheduleReconnect();\n }\n };\n\n this.ws.onerror = (e) => {\n // onclose will fire after onerror, triggering reconnect\n this._log.warn('WebSocket error');\n };\n }\n\n /** @private */\n _scheduleReconnect() {\n if (this._closed || this._retryTimer) return;\n\n this._log.info(`Reconnecting in ${this._retryMs}ms...`);\n this._retryTimer = setTimeout(() => {\n this._retryTimer = null;\n this._connect();\n }, this._retryMs);\n\n this._retryMs = Math.min(this._retryMs * BACKOFF_FACTOR, MAX_RETRY_MS);\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Transition choreography — compute stagger delays for cascading\n * layout transitions across multiple displays.\n *\n * Supports two modes:\n *\n * 1D mode (position-based):\n * Displays are numbered 0..N-1 in a row. Simple linear choreographies.\n * Config: { position, totalDisplays }\n *\n * 2D mode (topology-based):\n * Each display has (x, y) coordinates and an orientation vector.\n * Enables directional sweeps, diagonal cascades, and radial effects.\n * Config: { topology: { x, y, orientation? }, gridCols, gridRows }\n *\n * Topology format:\n * { x: 1, y: 0, orientation: 0 }\n * - x, y: grid coordinates (0-indexed)\n * - orientation: degrees clockwise from upright (0=landscape, 90=portrait-right,\n * 180=inverted, 270=portrait-left). Defaults to 0.\n *\n * Choreographies:\n * simultaneous — all at once (default, no delay)\n * wave-right — sweep left to right (by x)\n * wave-left — sweep right to left (by x)\n * wave-down — sweep top to bottom (by y, 2D only)\n * wave-up — sweep bottom to top (by y, 2D only)\n * diagonal-tl — cascade from top-left corner (2D only)\n * diagonal-tr — cascade from top-right corner (2D only)\n * diagonal-bl — cascade from bottom-left corner (2D only)\n * diagonal-br — cascade from bottom-right corner (2D only)\n * center-out — explode from center to edges\n * outside-in — implode from edges to center\n * random — random delay per display\n *\n * @module @xiboplayer/sync/choreography\n */\n\n/**\n * Compute the stagger delay for a display.\n *\n * @param {Object} options\n * @param {string} options.choreography — choreography name\n * @param {number} [options.position] — 1D: this display's 0-indexed position\n * @param {number} [options.totalDisplays] — 1D: total displays in the group\n * @param {Object} [options.topology] — 2D: this display's topology { x, y, orientation? }\n * @param {number} [options.gridCols] — 2D: grid width (columns)\n * @param {number} [options.gridRows] — 2D: grid height (rows)\n * @param {number} options.staggerMs — base delay between consecutive displays (ms)\n * @returns {number} delay in ms before this display should execute its transition\n *\n * @example\n * // 1D: 4 displays, wave-right with 150ms stagger\n * computeStagger({ choreography: 'wave-right', position: 2, totalDisplays: 4, staggerMs: 150 })\n * // → 300\n *\n * @example\n * // 2D: 3×2 grid, diagonal from top-left\n * computeStagger({\n * choreography: 'diagonal-tl',\n * topology: { x: 2, y: 1 },\n * gridCols: 3, gridRows: 2,\n * staggerMs: 100,\n * })\n * // → 300 (Manhattan distance 2+1=3, so 3×100)\n */\nexport function computeStagger({ choreography, position, totalDisplays, topology, gridCols, gridRows, staggerMs }) {\n if (!choreography || choreography === 'simultaneous' || !staggerMs) {\n return 0;\n }\n\n // 2D mode: topology with grid dimensions\n if (topology && gridCols != null && gridRows != null) {\n if (gridCols <= 1 && gridRows <= 1) return 0;\n return _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs);\n }\n\n // 1D mode: position-based\n if (totalDisplays == null || totalDisplays <= 1) return 0;\n return _computeStagger1D(choreography, position ?? 0, totalDisplays, staggerMs);\n}\n\n/** @private 1D stagger computation */\nfunction _computeStagger1D(choreography, position, totalDisplays, staggerMs) {\n const last = totalDisplays - 1;\n const center = last / 2;\n\n switch (choreography) {\n case 'wave-right':\n return position * staggerMs;\n\n case 'wave-left':\n return (last - position) * staggerMs;\n\n case 'center-out':\n return Math.round(Math.abs(position - center)) * staggerMs;\n\n case 'outside-in': {\n const maxDist = Math.round(center);\n return (maxDist - Math.round(Math.abs(position - center))) * staggerMs;\n }\n\n case 'random':\n return Math.floor(Math.random() * last * staggerMs);\n\n default:\n return 0;\n }\n}\n\n/** @private 2D stagger computation */\nfunction _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs) {\n const { x, y } = topology;\n const maxX = gridCols - 1;\n const maxY = gridRows - 1;\n const centerX = maxX / 2;\n const centerY = maxY / 2;\n\n switch (choreography) {\n // Axis-aligned sweeps\n case 'wave-right':\n return x * staggerMs;\n\n case 'wave-left':\n return (maxX - x) * staggerMs;\n\n case 'wave-down':\n return y * staggerMs;\n\n case 'wave-up':\n return (maxY - y) * staggerMs;\n\n // Corner diagonals (Manhattan distance from corner)\n case 'diagonal-tl':\n return (x + y) * staggerMs;\n\n case 'diagonal-tr':\n return ((maxX - x) + y) * staggerMs;\n\n case 'diagonal-bl':\n return (x + (maxY - y)) * staggerMs;\n\n case 'diagonal-br':\n return ((maxX - x) + (maxY - y)) * staggerMs;\n\n // Radial patterns (Euclidean distance from center)\n case 'center-out': {\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return Math.round(dist) * staggerMs;\n }\n\n case 'outside-in': {\n const maxDist = Math.round(Math.sqrt(centerX ** 2 + centerY ** 2));\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return (maxDist - Math.round(dist)) * staggerMs;\n }\n\n case 'random': {\n const maxSteps = maxX + maxY; // Manhattan extent\n return Math.floor(Math.random() * maxSteps * staggerMs);\n }\n\n default:\n return 0;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * SyncManager - Multi-display synchronization\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * (same machine via BroadcastChannel) or across devices on a LAN\n * (via WebSocket relay on the lead's proxy server).\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 * Transport:\n * Pluggable — BroadcastChannelTransport (same-machine) or\n * WebSocketTransport (cross-device via relay). Selected automatically\n * based on syncConfig.relayUrl.\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 (used for WebSocket relay URL)\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 * @property {string} [relayUrl] - WebSocket relay URL for cross-device sync\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { BroadcastChannelTransport } from './bc-transport.js';\nimport { WebSocketTransport } from './ws-transport.js';\n\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 {Object} [options.transport] - Optional pre-built transport (for testing)\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 this.onGroupUpdate = options.onGroupUpdate || null;\n\n // State\n this.transport = options.transport || 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._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /**\n * Start the sync manager — selects transport, begins heartbeats.\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n // Select transport if none injected\n if (!this.transport) {\n if (this.syncConfig.relayUrl) {\n this.transport = new WebSocketTransport(this.syncConfig.relayUrl, {\n syncGroup: this.syncConfig.syncGroup,\n displayId: this.displayId,\n topology: this.syncConfig.topology,\n token: this.syncConfig.syncToken,\n });\n } else if (typeof BroadcastChannel !== 'undefined') {\n this.transport = new BroadcastChannelTransport();\n } else {\n this._log.warn('No transport available — sync disabled');\n return;\n }\n }\n\n this.transport.onMessage((msg) => this._handleMessage(msg));\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 this.syncConfig.relayUrl ? `(relay: ${this.syncConfig.relayUrl})` : '(BroadcastChannel)');\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.transport) {\n this.transport.close();\n this.transport = 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 active followers as not-ready for this layout (skip stale ones)\n for (const [, follower] of this.followers) {\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\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 // Relay-originated messages (no displayId)\n if (msg.type === 'group-update') {\n this._log.info(`Group update: ${msg.totalDisplays} displays`);\n if (this.onGroupUpdate) {\n this.onGroupUpdate(msg.totalDisplays, msg.topology || {});\n }\n return;\n }\n\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.transport) return;\n try {\n this.transport.send(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 transport: this.syncConfig.relayUrl ? 'websocket' : 'broadcast-channel',\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\nexport { BroadcastChannelTransport } from './bc-transport.js';\nexport { WebSocketTransport } from './ws-transport.js';\nexport { computeStagger } from './choreography.js';\n"],"names":["DEFAULT_CHANNEL","BroadcastChannelTransport","channelName","msg","callback","INITIAL_RETRY_MS","MAX_RETRY_MS","BACKOFF_FACTOR","WebSocketTransport","url","syncGroup","displayId","topology","token","createLogger","_a","e","join","event","raw","computeStagger","choreography","position","totalDisplays","gridCols","gridRows","staggerMs","_computeStagger2D","_computeStagger1D","last","center","x","y","maxX","maxY","centerX","centerY","dist","maxDist","maxSteps","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"mDAWA,MAAMA,EAAkB,YAEjB,MAAMC,CAA0B,CAIrC,YAAYC,EAAcF,EAAiB,CACzC,KAAK,QAAU,IAAI,iBAAiBE,CAAW,EAC/C,KAAK,WAAa,EACpB,CAMA,KAAKC,EAAK,CACH,KAAK,SACV,KAAK,QAAQ,YAAYA,CAAG,CAC9B,CAMA,UAAUC,EAAU,CAClB,KAAK,QAAQ,UAAa,GAAMA,EAAS,EAAE,IAAI,CACjD,CAGA,OAAQ,CACF,KAAK,UACP,KAAK,QAAQ,MAAK,EAClB,KAAK,QAAU,MAEjB,KAAK,WAAa,EACpB,CAGA,IAAI,WAAY,CACd,OAAO,KAAK,YAAc,CAAC,CAAC,KAAK,OACnC,CACF,CClCA,MAAMC,EAAmB,IACnBC,EAAe,IACfC,EAAiB,EAEhB,MAAMC,CAAmB,CAS9B,YAAYC,EAAK,CAAE,UAAAC,EAAW,UAAAC,EAAW,SAAAC,EAAU,MAAAC,CAAK,EAAK,GAAI,CAC/D,KAAK,KAAOJ,EACZ,KAAK,WAAaC,GAAa,KAC/B,KAAK,WAAaC,GAAa,KAC/B,KAAK,UAAYC,GAAY,KAC7B,KAAK,OAASC,GAAS,KACvB,KAAK,UAAY,KACjB,KAAK,QAAU,GACf,KAAK,SAAWR,EAChB,KAA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AAGP,CAAa,CAClB,CAAC,CACH,CAKA,gBAAiB,CACf,KAAK,MAAM,CACT,KAAM,YACN,UAAW,KAAK,UAChB,KAAM,KAAK,OAAS,OAAS,WAC7B,UAAW,KAAK,IAAG,CACzB,CAAK,CACH,CAGA,wBAAyB,CACvB,MAAMiB,EAAM,KAAK,IAAG,EACpB,SAAW,CAACF,EAAIX,CAAQ,IAAK,KAAK,UAC5Ba,EAAMb,EAAS,SAAWL,IAC5B,KAAK,KAAK,KAAK,4BAA4BgB,CAAE,eAAe,KAAK,OAAOE,EAAMb,EAAS,UAAY,GAAI,CAAC,QAAQ,EAChH,KAAK,UAAU,OAAOW,CAAE,EAG9B,CAGA,MAAMtD,EAAK,CACT,GAAK,KAAK,UACV,GAAI,CACF,KAAK,UAAU,KAAKA,CAAG,CACzB,OAAS,EAAG,CACV,KAAK,KAAK,MAAM,kBAAmB,CAAC,CACtC,CACF,CAQA,WAAY,CACV,MAAO,CACL,QAAS,KAAK,SACd,OAAQ,KAAK,OACb,UAAW,KAAK,UAChB,UAAW,KAAK,UAAU,KAC1B,gBAAiB,KAAK,iBACtB,UAAW,KAAK,WAAW,SAAW,YAAc,oBACpD,gBAAiB,MAAM,KAAK,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC,CAACsD,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWjB,CACzC,EAAQ,CACR,CACE,CACF"}
1
+ {"version":3,"file":"sync-manager-DpfoR8OE.js","sources":["../../../sync/src/bc-transport.js","../../../sync/src/ws-transport.js","../../../sync/src/choreography.js","../../../sync/src/sync-manager.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * BroadcastChannelTransport — same-machine sync transport\n *\n * Wraps the browser BroadcastChannel API behind the sync transport interface.\n * Used for multi-tab / multi-window sync on a single device.\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nconst DEFAULT_CHANNEL = 'xibo-sync';\n\nexport class BroadcastChannelTransport {\n /**\n * @param {string} [channelName='xibo-sync']\n */\n constructor(channelName = DEFAULT_CHANNEL) {\n this.channel = new BroadcastChannel(channelName);\n this._connected = true;\n }\n\n /**\n * Send a message to all other tabs/windows on this channel.\n * @param {Object} msg — plain object (structured-cloned by BroadcastChannel)\n */\n send(msg) {\n if (!this.channel) return;\n this.channel.postMessage(msg);\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the message data (already deserialized)\n */\n onMessage(callback) {\n this.channel.onmessage = (e) => callback(e.data);\n }\n\n /** Close the channel. */\n close() {\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n this._connected = false;\n }\n\n /** @returns {boolean} Whether the channel is open */\n get connected() {\n return this._connected && !!this.channel;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * WebSocketTransport — cross-device sync transport\n *\n * Connects to the lead player's proxy WebSocket relay at /sync.\n * Used for LAN video walls where each screen is a separate device.\n *\n * Features:\n * - Auto-reconnect with exponential backoff (1s → 2s → 4s → max 30s)\n * - JSON serialization (WebSocket sends strings, not structured clones)\n * - Same transport interface as BroadcastChannelTransport\n *\n * Transport interface: { send(msg), onMessage(callback), close(), get connected() }\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst INITIAL_RETRY_MS = 1000;\nconst MAX_RETRY_MS = 30000;\nconst BACKOFF_FACTOR = 2;\n\nexport class WebSocketTransport {\n /**\n * @param {string} url — WebSocket URL, e.g. ws://192.168.1.100:8765/sync\n * @param {Object} [options]\n * @param {string} [options.syncGroup] — group name for relay isolation\n * @param {string} [options.displayId] — this display's unique ID\n * @param {Object} [options.topology] — this display's topology { x, y, orientation? }\n * @param {string} [options.token] — auth token for relay join validation\n */\n constructor(url, { syncGroup, displayId, topology, token } = {}) {\n this._url = url;\n this._syncGroup = syncGroup || null;\n this._displayId = displayId || null;\n this._topology = topology || null;\n this._token = token || null;\n this._callback = null;\n this._closed = false;\n this._retryMs = INITIAL_RETRY_MS;\n this._retryTimer = null;\n this._log = createLogger('WS-Sync');\n this.ws = null;\n\n this._connect();\n }\n\n /**\n * Send a message to the relay (which broadcasts to other clients).\n * @param {Object} msg — plain object (JSON-serialized for WebSocket)\n */\n send(msg) {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /**\n * Register a callback for incoming messages.\n * @param {Function} callback — receives the parsed message object\n */\n onMessage(callback) {\n this._callback = callback;\n }\n\n /** Close the connection and stop reconnecting. */\n close() {\n this._closed = true;\n if (this._retryTimer) {\n clearTimeout(this._retryTimer);\n this._retryTimer = null;\n }\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n\n /** @returns {boolean} Whether the WebSocket is open */\n get connected() {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n /** @private */\n _connect() {\n if (this._closed) return;\n\n try {\n this.ws = new WebSocket(this._url);\n } catch (e) {\n this._log.error('WebSocket creation failed:', e.message);\n this._scheduleReconnect();\n return;\n }\n\n this.ws.onopen = () => {\n this._log.info(`Connected to ${this._url}`);\n this._retryMs = INITIAL_RETRY_MS; // Reset backoff on success\n\n // Join sync group for relay isolation (+ topology for auto-detection)\n if (this._syncGroup) {\n const join = { type: 'join', syncGroup: this._syncGroup };\n if (this._displayId) join.displayId = this._displayId;\n if (this._topology) join.topology = this._topology;\n if (this._token) join.token = this._token;\n this.ws.send(JSON.stringify(join));\n }\n };\n\n this.ws.onmessage = async (event) => {\n if (!this._callback) return;\n try {\n // Browser WebSocket delivers string; Node ws delivers Buffer;\n // Node 22+ native WebSocket delivers Blob. Handle all three.\n let raw = event.data;\n if (typeof raw !== 'string') {\n raw = (raw instanceof Blob) ? await raw.text() : String(raw);\n }\n const msg = JSON.parse(raw);\n this._callback(msg);\n } catch (e) {\n this._log.warn('Failed to parse message:', e.message);\n }\n };\n\n this.ws.onclose = () => {\n if (!this._closed) {\n this._log.info('Connection closed — will reconnect');\n this._scheduleReconnect();\n }\n };\n\n this.ws.onerror = (e) => {\n // onclose will fire after onerror, triggering reconnect\n this._log.warn('WebSocket error');\n };\n }\n\n /** @private */\n _scheduleReconnect() {\n if (this._closed || this._retryTimer) return;\n\n this._log.info(`Reconnecting in ${this._retryMs}ms...`);\n this._retryTimer = setTimeout(() => {\n this._retryTimer = null;\n this._connect();\n }, this._retryMs);\n\n this._retryMs = Math.min(this._retryMs * BACKOFF_FACTOR, MAX_RETRY_MS);\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Transition choreography — compute stagger delays for cascading\n * layout transitions across multiple displays.\n *\n * Supports two modes:\n *\n * 1D mode (position-based):\n * Displays are numbered 0..N-1 in a row. Simple linear choreographies.\n * Config: { position, totalDisplays }\n *\n * 2D mode (topology-based):\n * Each display has (x, y) coordinates and an orientation vector.\n * Enables directional sweeps, diagonal cascades, and radial effects.\n * Config: { topology: { x, y, orientation? }, gridCols, gridRows }\n *\n * Topology format:\n * { x: 1, y: 0, orientation: 0 }\n * - x, y: grid coordinates (0-indexed)\n * - orientation: degrees clockwise from upright (0=landscape, 90=portrait-right,\n * 180=inverted, 270=portrait-left). Defaults to 0.\n *\n * Choreographies:\n * simultaneous — all at once (default, no delay)\n * wave-right — sweep left to right (by x)\n * wave-left — sweep right to left (by x)\n * wave-down — sweep top to bottom (by y, 2D only)\n * wave-up — sweep bottom to top (by y, 2D only)\n * diagonal-tl — cascade from top-left corner (2D only)\n * diagonal-tr — cascade from top-right corner (2D only)\n * diagonal-bl — cascade from bottom-left corner (2D only)\n * diagonal-br — cascade from bottom-right corner (2D only)\n * center-out — explode from center to edges\n * outside-in — implode from edges to center\n * random — random delay per display\n *\n * @module @xiboplayer/sync/choreography\n */\n\n/**\n * Compute the stagger delay for a display.\n *\n * @param {Object} options\n * @param {string} options.choreography — choreography name\n * @param {number} [options.position] — 1D: this display's 0-indexed position\n * @param {number} [options.totalDisplays] — 1D: total displays in the group\n * @param {Object} [options.topology] — 2D: this display's topology { x, y, orientation? }\n * @param {number} [options.gridCols] — 2D: grid width (columns)\n * @param {number} [options.gridRows] — 2D: grid height (rows)\n * @param {number} options.staggerMs — base delay between consecutive displays (ms)\n * @returns {number} delay in ms before this display should execute its transition\n *\n * @example\n * // 1D: 4 displays, wave-right with 150ms stagger\n * computeStagger({ choreography: 'wave-right', position: 2, totalDisplays: 4, staggerMs: 150 })\n * // → 300\n *\n * @example\n * // 2D: 3×2 grid, diagonal from top-left\n * computeStagger({\n * choreography: 'diagonal-tl',\n * topology: { x: 2, y: 1 },\n * gridCols: 3, gridRows: 2,\n * staggerMs: 100,\n * })\n * // → 300 (Manhattan distance 2+1=3, so 3×100)\n */\nexport function computeStagger({ choreography, position, totalDisplays, topology, gridCols, gridRows, staggerMs }) {\n if (!choreography || choreography === 'simultaneous' || !staggerMs) {\n return 0;\n }\n\n // 2D mode: topology with grid dimensions\n if (topology && gridCols != null && gridRows != null) {\n if (gridCols <= 1 && gridRows <= 1) return 0;\n return _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs);\n }\n\n // 1D mode: position-based\n if (totalDisplays == null || totalDisplays <= 1) return 0;\n return _computeStagger1D(choreography, position ?? 0, totalDisplays, staggerMs);\n}\n\n/** @private 1D stagger computation */\nfunction _computeStagger1D(choreography, position, totalDisplays, staggerMs) {\n const last = totalDisplays - 1;\n const center = last / 2;\n\n switch (choreography) {\n case 'wave-right':\n return position * staggerMs;\n\n case 'wave-left':\n return (last - position) * staggerMs;\n\n case 'center-out':\n return Math.round(Math.abs(position - center)) * staggerMs;\n\n case 'outside-in': {\n const maxDist = Math.round(center);\n return (maxDist - Math.round(Math.abs(position - center))) * staggerMs;\n }\n\n case 'random':\n return Math.floor(Math.random() * last * staggerMs);\n\n default:\n return 0;\n }\n}\n\n/** @private 2D stagger computation */\nfunction _computeStagger2D(choreography, topology, gridCols, gridRows, staggerMs) {\n const { x, y } = topology;\n const maxX = gridCols - 1;\n const maxY = gridRows - 1;\n const centerX = maxX / 2;\n const centerY = maxY / 2;\n\n switch (choreography) {\n // Axis-aligned sweeps\n case 'wave-right':\n return x * staggerMs;\n\n case 'wave-left':\n return (maxX - x) * staggerMs;\n\n case 'wave-down':\n return y * staggerMs;\n\n case 'wave-up':\n return (maxY - y) * staggerMs;\n\n // Corner diagonals (Manhattan distance from corner)\n case 'diagonal-tl':\n return (x + y) * staggerMs;\n\n case 'diagonal-tr':\n return ((maxX - x) + y) * staggerMs;\n\n case 'diagonal-bl':\n return (x + (maxY - y)) * staggerMs;\n\n case 'diagonal-br':\n return ((maxX - x) + (maxY - y)) * staggerMs;\n\n // Radial patterns (Euclidean distance from center)\n case 'center-out': {\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return Math.round(dist) * staggerMs;\n }\n\n case 'outside-in': {\n const maxDist = Math.round(Math.sqrt(centerX ** 2 + centerY ** 2));\n const dist = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);\n return (maxDist - Math.round(dist)) * staggerMs;\n }\n\n case 'random': {\n const maxSteps = maxX + maxY; // Manhattan extent\n return Math.floor(Math.random() * maxSteps * staggerMs);\n }\n\n default:\n return 0;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * SyncManager - Multi-display synchronization\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * (same machine via BroadcastChannel) or across devices on a LAN\n * (via WebSocket relay on the lead's proxy server).\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 * Transport:\n * Pluggable — BroadcastChannelTransport (same-machine) or\n * WebSocketTransport (cross-device via relay). Selected automatically\n * based on syncConfig.relayUrl.\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 (used for WebSocket relay URL)\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 * @property {string} [relayUrl] - WebSocket relay URL for cross-device sync\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { BroadcastChannelTransport } from './bc-transport.js';\nimport { WebSocketTransport } from './ws-transport.js';\n\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 {Object} [options.transport] - Optional pre-built transport (for testing)\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 this.onGroupUpdate = options.onGroupUpdate || null;\n\n // State\n this.transport = options.transport || 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._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /**\n * Start the sync manager — selects transport, begins heartbeats.\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n // Select transport if none injected\n if (!this.transport) {\n if (this.syncConfig.relayUrl) {\n this.transport = new WebSocketTransport(this.syncConfig.relayUrl, {\n syncGroup: this.syncConfig.syncGroup,\n displayId: this.displayId,\n topology: this.syncConfig.topology,\n token: this.syncConfig.syncToken,\n });\n } else if (typeof BroadcastChannel !== 'undefined') {\n this.transport = new BroadcastChannelTransport();\n } else {\n this._log.warn('No transport available — sync disabled');\n return;\n }\n }\n\n this.transport.onMessage((msg) => this._handleMessage(msg));\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 this.syncConfig.relayUrl ? `(relay: ${this.syncConfig.relayUrl})` : '(BroadcastChannel)');\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.transport) {\n this.transport.close();\n this.transport = 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 active followers as not-ready for this layout (skip stale ones)\n for (const [, follower] of this.followers) {\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\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 // Relay-originated messages (no displayId)\n if (msg.type === 'group-update') {\n this._log.info(`Group update: ${msg.totalDisplays} displays`);\n if (this.onGroupUpdate) {\n this.onGroupUpdate(msg.totalDisplays, msg.topology || {});\n }\n return;\n }\n\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.transport) return;\n try {\n this.transport.send(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 transport: this.syncConfig.relayUrl ? 'websocket' : 'broadcast-channel',\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\nexport { BroadcastChannelTransport } from './bc-transport.js';\nexport { WebSocketTransport } from './ws-transport.js';\nexport { computeStagger } from './choreography.js';\n"],"names":["DEFAULT_CHANNEL","BroadcastChannelTransport","channelName","msg","callback","INITIAL_RETRY_MS","MAX_RETRY_MS","BACKOFF_FACTOR","WebSocketTransport","url","syncGroup","displayId","topology","token","createLogger","_a","e","join","event","raw","computeStagger","choreography","position","totalDisplays","gridCols","gridRows","staggerMs","_computeStagger2D","_computeStagger1D","last","center","x","y","maxX","maxY","centerX","centerY","dist","maxDist","maxSteps","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"mDAWA,MAAMA,EAAkB,YAEjB,MAAMC,CAA0B,CAIrC,YAAYC,EAAcF,EAAiB,CACzC,KAAK,QAAU,IAAI,iBAAiBE,CAAW,EAC/C,KAAK,WAAa,EACpB,CAMA,KAAKC,EAAK,CACH,KAAK,SACV,KAAK,QAAQ,YAAYA,CAAG,CAC9B,CAMA,UAAUC,EAAU,CAClB,KAAK,Q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KAAK,iBACtB,UAAW,KAAK,WAAW,SAAW,YAAc,oBACpD,gBAAiB,MAAM,KAAK,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC,CAACsD,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWjB,CACzC,EAAQ,CACR,CACE,CACF"}
@@ -1,2 +1,2 @@
1
- import{createLogger as C,PLAYER_API as k}from"./index-5h0f0o88.js";const R=C("Cache");class B{constructor(){this.dependants=new Map}addDependant(e,s){const t=String(e);this.dependants.has(t)||this.dependants.set(t,new Set),this.dependants.get(t).add(String(s))}removeLayoutDependants(e){const s=String(e),t=[];for(const[i,n]of this.dependants)n.delete(s),n.size===0&&(this.dependants.delete(i),t.push(i));return t.length>0&&R.info(`${t.length} media files orphaned after layout ${e} removed:`,t),t}isMediaReferenced(e){const s=this.dependants.get(String(e));return s?s.size>0:!1}async clearAll(){this.dependants.clear()}}const N=new B,_=C("StoreClient");class O{async has(e,s){try{const t=await fetch(`/store/${e}/${s}`,{method:"HEAD"});if(t.status===204)return!1;if(t.status===200)return t.headers.get("X-Store-Complete")!=="false";if(t.status===404)return!1;const i=new Error(`Store error: ${t.status}`);throw i.status=t.status,_.warn(`has(${e}/${s}): unexpected status ${t.status}`),i}catch(t){throw t.status||t.name==="AbortError"||t.name==="TimeoutError"||_.warn(`has(${e}/${s}): network error — ${t.message}`),t}}async get(e,s){var t,i;try{const n=await fetch(`/store/${e}/${s}`);if(n.status===204||n.status===404)return(t=n.body)==null||t.cancel(),null;if(!n.ok)throw(i=n.body)==null||i.cancel(),new Error(`Failed to get file: ${n.status}`);return await n.blob()}catch(n){return _.error("get error:",n.message),null}}async put(e,s,t,i="application/octet-stream"){var n;try{const r=await fetch(`/store/${e}/${s}`,{method:"PUT",headers:{"Content-Type":i},body:t});return(n=r.body)==null||n.cancel(),r.ok}catch(r){return _.error("put error:",r.message),!1}}async remove(e){try{const t=await(await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})})).json();return{deleted:t.deleted||0,total:t.total||e.length}}catch(s){return _.error("remove error:",s.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch("/store/list")).json()).files||[]}catch(e){return _.error("list error:",e.message),[]}}}const D={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function v(d){return D[d]||D.media}const u=C("Download"),P=6,S=50*1024*1024,A=3,M=100*1024*1024,z=2,b=6e5,Q=15e3;function U(d){var i,n;const s=(n=(i=(d.path||d.code||"").split(".").pop())==null?void 0:i.split("?")[0])==null?void 0:n.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[s]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},m=Symbol("BARRIER");function T(d){try{const e=new URL(d,"http://localhost"),s=e.searchParams.get("X-Amz-Date"),t=e.searchParams.get("X-Amz-Expires");if(s&&t){const i=s.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/,"$1-$2-$3T$4:$5:$6Z"),n=new Date(i).getTime()/1e3;return isNaN(n)?1/0:n+parseInt(t,10)}return 1/0}catch{return 1/0}}function F(d,e=30){const s=T(d);return s===1/0?!1:Date.now()/1e3>=s-e}class x{constructor(e,s={}){this.fileInfo=e,this.chunkIndex=s.chunkIndex??null,this.rangeStart=s.rangeStart??null,this.rangeEnd=s.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal,this._typeConfig=v(e.type)}getUrl(){const e=this.fileInfo.path;if(F(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){var t;this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e["X-Store-Chunk-Index"]=String(this.chunkIndex),this._parentFile&&(e["X-Store-Num-Chunks"]=String(this._parentFile.totalChunks),e["X-Store-Chunk-Size"]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e["X-Store-MD5"]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e["X-Cache-TTL"]=String(this.fileInfo.updateInterval)),this.fileInfo.cmsDownloadUrl&&(e["X-Cms-Download-Url"]=this.fileInfo.cmsDownloadUrl);const s=this._typeConfig.maxRetries;for(let i=1;i<=s;i++){const n=new AbortController,r=setTimeout(()=>n.abort(),b);try{const a=this.getUrl(),h={signal:n.signal};Object.keys(e).length>0&&(h.headers=e);const o=await fetch(a,h);if(!o.ok&&o.status!==206)throw new Error(`Fetch failed: ${o.status}`);return this.blob=await o.blob(),this.state="complete",this.blob}catch(a){const h=n.signal.aborted?`Timeout after ${b/1e3}s`:a.message;if(i<s){const o=((t=this._typeConfig.retryDelays)==null?void 0:t[i-1])??this._typeConfig.retryDelayMs*i,l=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";u.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${l} attempt ${i}/${s} failed: ${h}. Retrying in ${o/1e3}s...`),await new Promise(p=>setTimeout(p,o))}else throw this.state="failed",n.signal.aborted?new Error(h):a}finally{clearTimeout(r)}}}}class E{constructor(e,s={}){this.fileInfo=e,this.options=s,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((t,i)=>{this._resolve=t,this._reject=i}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(F(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:s,type:t,size:i}=this.fileInfo;u.info("[FileDownload] Starting:",`${t}/${s}`),this.totalBytes=i&&i>0?parseInt(i):0,this._contentType=U(this.fileInfo);const n=v(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!n){const a=this.getUrl(),h=new AbortController,o=setTimeout(()=>h.abort(),Q);try{const l=await fetch(a,{method:"HEAD",signal:h.signal});l.ok&&(this.totalBytes=parseInt(l.headers.get("Content-Length")||"0"),this._contentType=l.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(o)}}u.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const r=this.options.chunkSize||S;if(this.totalBytes>M){const a=[];for(let c=0;c<this.totalBytes;c+=r)a.push({start:c,end:Math.min(c+r-1,this.totalBytes-1),index:a.length});this.totalChunks=a.length;const h=a.filter(c=>!this.skipChunks.has(c.index)),o=a.length-h.length;for(const c of a)this.skipChunks.has(c.index)&&(this.downloadedBytes+=c.end-c.start+1);if(h.length===0){u.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}o>0&&u.info(`[FileDownload] Resuming: ${o} chunks cached, ${h.length} to download`);const l=o>0;if(l){const c=h.sort((g,$)=>g.index-$.index);for(const g of c){const $=new x(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});$._parentFile=this,$._priority=f.normal,this.tasks.push($)}}else for(const c of h){const g=new x(this.fileInfo,{chunkIndex:c.index,rangeStart:c.start,rangeEnd:c.end});g._parentFile=this,g._priority=c.index===0||c.index===a.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(c=>c._priority>=f.high).length;u.info(`[FileDownload] ${t}/${s}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(l?" (resume)":""))}else{this.totalChunks=1;const a=new x(this.fileInfo,{});a._parentFile=this,this.tasks.push(a)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(s){u.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(s){u.warn("[FileDownload] onChunkDownloaded callback error:",s)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:s,id:t}=this.fileInfo;if(e.chunkIndex==null)u.info("[FileDownload] Complete:",`${s}/${t}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)u.info("[FileDownload] Complete:",`${s}/${t}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const i=[];for(let r=0;r<this.totalChunks;r++){const a=this._chunkBlobs.get(r);a&&i.push(a)}const n=new Blob(i,{type:this._contentType});u.info("[FileDownload] Complete:",`${s}/${t}`,`(${n.size} bytes, reassembled)`),this._resolve(n)}this._chunkBlobs.clear()}}onTaskFailed(e,s){var t;if(!(this.state==="complete"||this.state==="failed")){if((t=s.message)!=null&&t.includes("URL expired")){const i=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";u.warn(`[FileDownload] URL expired, dropping${i}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(n=>n!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}u.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}}class L{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const s=q.stableKey(e);if(this.queue.active.has(s)){const i=this.queue.active.get(s);if(e.path&&e.path!==i.fileInfo.path){const n=T(i.fileInfo.path);T(e.path)>n&&(i.fileInfo.path=e.path)}return i}const t=new E(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(s,t),this._filesToPrepare.push(t),t}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let s=0,t=0;const i=()=>{for(;s<this._maxPreparing&&t<this._filesToPrepare.length;){const n=this._filesToPrepare[t++];s++,n.prepare(this).finally(()=>{s--,t>=this._filesToPrepare.length&&s===0?e():i()})}};this._filesToPrepare.length===0?e():i()})}_sortWithBarriers(){var r;const e=[],s=[],t=[],i=[];for(const a of this._tasks)if(a.chunkIndex==null)e.push(a);else if(a.chunkIndex===0)s.push(a);else{const h=((r=a._parentFile)==null?void 0:r.totalChunks)||0;h>1&&a.chunkIndex===h-1?t.push(a):i.push(a)}e.sort((a,h)=>{var o,l;return(((o=a._parentFile)==null?void 0:o.totalBytes)||0)-(((l=h._parentFile)==null?void 0:l.totalBytes)||0)}),i.sort((a,h)=>a.chunkIndex-h.chunkIndex);const n=[...e,...s,...t];return i.length>0&&n.push(m,...i),n}}class q{constructor(e={}){this.concurrency=e.concurrency||P,this.chunkSize=e.chunkSize||S,this.maxChunksPerFile=e.chunksPerFile||A,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const s=q.stableKey(e);if(this.active.has(s)){const i=this.active.get(s);if(e.path&&e.path!==i.fileInfo.path){const n=T(i.fileInfo.path);T(e.path)>n&&(u.info("[DownloadQueue] Refreshing URL for",s),i.fileInfo.path=e.path)}return i}const t=new E(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(s,t),u.info("[DownloadQueue] Enqueued:",s),this._schedulePrepare(t),t}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const s of e)this.queue.push(s);this._sortQueue(),u.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let s=0,t=0;for(const i of e)i===m?(this.queue.push(m),t++):(this.queue.push(i),s++);u.info(`[DownloadQueue] Ordered queue: ${s} tasks, ${t} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,s)=>s._priority-e._priority)}prioritizeLayoutFiles(e,s=f.high){var n,r,a,h;const t=new Set(e.map(String));let i=0;for(const o of this.queue){const l=((n=o._parentFile)==null?void 0:n.fileInfo.saveAs)||String((r=o._parentFile)==null?void 0:r.fileInfo.id);t.has(l)&&o._priority<s&&(o._priority=s,i++)}for(const o of this._activeTasks){const l=((a=o._parentFile)==null?void 0:a.fileInfo.saveAs)||String((h=o._parentFile)==null?void 0:h.fileInfo.id);t.has(l)&&o._priority<s&&(o._priority=s)}this._sortQueue(),u.info("[DownloadQueue] Layout files prioritized:",t.size,"files,",i,"tasks boosted to",s)}urgentChunk(e,s,t){const i=`${e}/${s}`,n=this.active.get(i);if(!n)return u.info("[DownloadQueue] urgentChunk: file not active:",i,"chunk",t),!1;if(this._activeTasks.some(o=>o._parentFile===n&&o.chunkIndex===t&&o.state==="downloading")){const o=this._activeTasks.find(l=>l._parentFile===n&&l.chunkIndex===t);return o&&o._priority<f.urgent?(o._priority=f.urgent,u.info(`[DownloadQueue] URGENT: ${i} chunk ${t} (already in-flight, limiting slots)`),!0):(u.info("[DownloadQueue] urgentChunk: already urgent:",i,"chunk",t),!1)}const a=this.queue.findIndex(o=>o!==m&&o._parentFile===n&&o.chunkIndex===t);if(a===-1)return u.info("[DownloadQueue] urgentChunk: chunk not in queue:",i,"chunk",t),!1;const h=this.queue.splice(a,1)[0];return h._priority=f.urgent,this.queue.unshift(h),u.info(`[DownloadQueue] URGENT: ${i} chunk ${t} (moved to front)`),this.processQueue(),!0}processQueue(){var i;if(this.paused)return;const e=this.queue.some(n=>n!==m&&n._priority>=f.urgent)||((i=this._activeTasks)==null?void 0:i.some(n=>n._priority>=f.urgent&&n.state==="downloading")),s=e?z:this.concurrency,t=e?f.urgent:0;for(;this.running<s&&this.queue.length>0;){const n=this.queue[0];if(n===m){if(this.running>0)break;this.queue.shift();continue}if(n._priority<t||!this._canStartTask(n)){let r=!1;for(let a=1;a<this.queue.length&&this.queue[a]!==m;a++){const h=this.queue[a];if(h._priority>=t&&this._canStartTask(h)){this.queue.splice(a,1),this._startTask(h),r=!0;break}}if(!r)break;continue}this.queue.shift(),this._startTask(n)}this.queue.length===0&&this.running===0&&u.info("[DownloadQueue] All downloads complete")}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);const s=`${e.fileInfo.type}/${e.fileInfo.id}`,t=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";u.info(`[DownloadQueue] Starting: ${s}${t} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(i=>i!==e),u.info(`[DownloadQueue] Fetched: ${s}${t} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(i=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(a=>a!==e);const{maxReenqueues:n,reenqueueDelayMs:r}=e._typeConfig;if(n>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>n){u.error(`[DownloadQueue] ${s} exceeded ${n} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,i);return}u.warn(`[DownloadQueue] ${s} failed all retries (attempt ${e._reenqueueCount}/${n}), scheduling re-enqueue in ${r/1e3}s`);const a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state="pending",e._parentFile.state="downloading",this.queue.push(e),u.info(`[DownloadQueue] ${s} re-enqueued for retry`),this.processQueue()},r);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,i)})}removeCompleted(e){const s=this.active.get(e);s&&(s.state==="complete"||s.state==="failed")&&(this.queue=this.queue.filter(t=>t===m||t._parentFile!==s),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[s,t]of this.active.entries())t.state==="complete"||t.state==="failed"||(e[s]={downloaded:t.downloadedBytes,total:t.totalBytes,percent:t.totalBytes>0?(t.downloadedBytes/t.totalBytes*100).toFixed(1):0,state:t.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(const e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}}class X{constructor(e={}){this.queue=new q(e)}enqueue(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,s){this.queue.prioritizeLayoutFiles(e,s),this.queue.processQueue()}urgentChunk(e,s,t){return this.queue.urgentChunk(e,s,t)}createTaskBuilder(){return new L(this.queue)}enqueueOrderedTasks(e){this.queue.enqueueOrderedTasks(e)}removeCompleted(e){this.queue.removeCompleted(e)}get running(){return this.queue.running}get queued(){return this.queue.queue.length}clear(){this.queue.clear()}}const y=C("CacheAnalyzer");function w(d){if(d===0)return"0 B";if(!Number.isFinite(d))return"∞";const e=["B","KB","MB","GB","TB"],s=Math.floor(Math.log(d)/Math.log(1024));return`${(d/Math.pow(1024,s)).toFixed(s>0?1:0)} ${e[s]}`}class K{constructor(e,{threshold:s=80}={}){this.cache=e,this.threshold=s}async analyze(e){const s=await this.cache.list(),t=await this._getStorageEstimate(),i=new Set(e.map(o=>String(o.id))),n=[],r=[];for(const o of s)if(i.has(String(o.id)))n.push(o);else if(o.type==="widget"){const l=String(o.id).split("/")[0];i.has(l)?n.push(o):r.push(o)}else o.type==="static"?n.push(o):r.push(o);r.sort((o,l)=>(o.cachedAt||0)-(l.cachedAt||0));const a=r.reduce((o,l)=>o+(l.size||0),0),h={timestamp:Date.now(),storage:{usage:t.usage,quota:t.quota,percent:t.quota>0?Math.round(t.usage/t.quota*100):0},files:{required:n.length,orphaned:r.length,total:s.length},orphaned:r.map(o=>({id:o.id,type:o.type,size:o.size||0,cachedAt:o.cachedAt||0})),orphanedSize:a,evicted:[],threshold:this.threshold};if(y.info(`Storage: ${w(t.usage)} / ${w(t.quota)} (${h.storage.percent}%)`),y.info(`Cache: ${n.length} required, ${r.length} orphaned (${w(a)} reclaimable)`),r.length>0)for(const o of r){const l=Date.now()-(o.cachedAt||0),p=Math.floor(l/864e5),c=Math.floor(l%864e5/36e5),g=p>0?`${p}d ago`:`${c}h ago`;y.info(` Orphaned: ${o.type}/${o.id} (${w(o.size||0)}, cached ${g})`)}if(h.storage.percent>this.threshold&&r.length>0){y.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const o=t.usage-t.quota*this.threshold/100;h.evicted=await this._evict(r,o)}else y.info(`No eviction needed (threshold: ${this.threshold}%)`);return h}async _getStorageEstimate(){var e;try{if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate)){const{usage:s,quota:t}=await navigator.storage.estimate();return{usage:s||0,quota:t||1/0}}}catch(s){y.warn("Storage estimate unavailable:",s.message)}return{usage:0,quota:1/0}}async _evict(e,s){const t=[];let i=0;for(const n of e){if(i>=s)break;t.push(n),i+=n.size||0}if(t.length===0)return[];try{const n=t.map(r=>({type:r.type,id:r.id}));await this.cache.remove(n);for(const r of t)y.info(` Evicted: ${r.type}/${r.id} (${w(r.size||0)})`);y.info(`Evicted ${t.length} files, freed ${w(i)}`)}catch(n){return y.warn("Eviction failed:",n.message),[]}return t.map(n=>({id:n.id,type:n.type,size:n.size||0,cachedAt:n.cachedAt||0}))}}const I=C("Cache"),H=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function Y(d,e,s,t){var l;const i=`${k}/widgets/${d}/${e}/${s}`,n=`<base href="${k}/media/file/">`;let r=t;t.includes("<base ")||(t.includes("<head>")?r=t.replace("<head>","<head>"+n):t.includes("<HEAD>")?r=t.replace("<HEAD>","<HEAD>"+n):r=n+t);const a="<style>img,video{object-position:center center}</style>";r.includes("object-position:center center")||(r.includes("</head>")?r=r.replace("</head>",a+"</head>"):r.includes("</HEAD>")&&(r=r.replace("</HEAD>",a+"</HEAD>"))),r=r.replace(/\[\[ViewPortWidth]]/g,"device-width"),r=r.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,p=>"/stream-proxy?url="+encodeURIComponent(p));const h=new RegExp(`https?://[^"'\\s)]+?(${k.replace(/\//g,"\\/")}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,"g");if(r=r.replace(h,(p,c)=>c),r=r.replace(/(<(?:script|link)\b[^>]*(?:src|href)=")(?!\/|https?:\/\/)(bundle\.min\.js|fonts\.css)(")/g,`$1${k}/dependencies/$2$3`),!r.includes("xiboICTargetId")){const p=`<script>var xiboICTargetId = '${s}';<\/script>`;r.includes(n)?r=r.replace(n,n+p):r.includes("<head>")?r=r.replace("<head>","<head>"+p):r=p+r}return r=r.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${H}/ic"`),I.info("Injected base tag in widget HTML"),(l=(await fetch(`/store${k}/widgets/${d}/${e}/${s}`,{method:"PUT",headers:{"Content-Type":"text/html; charset=utf-8"},body:r})).body)==null||l.cancel(),I.info(`Stored widget HTML at ${i} (${r.length} bytes)`),{cacheKey:i,html:r}}export{m as B,K as C,X as D,D as F,L,O as S,B as a,E as b,Y as c,N as d,v as g,F as i};
2
- //# sourceMappingURL=widget-html-Bo9WgcY3.js.map
1
+ import{createLogger as C,PLAYER_API as k}from"./index-Cn_8cMrf.js";const R=C("Cache");class B{constructor(){this.dependants=new Map}addDependant(e,s){const t=String(e);this.dependants.has(t)||this.dependants.set(t,new Set),this.dependants.get(t).add(String(s))}removeLayoutDependants(e){const s=String(e),t=[];for(const[i,n]of this.dependants)n.delete(s),n.size===0&&(this.dependants.delete(i),t.push(i));return t.length>0&&R.info(`${t.length} media files orphaned after layout ${e} removed:`,t),t}isMediaReferenced(e){const s=this.dependants.get(String(e));return s?s.size>0:!1}async clearAll(){this.dependants.clear()}}const N=new B,_=C("StoreClient");class O{async has(e,s){try{const t=await fetch(`/store/${e}/${s}`,{method:"HEAD"});if(t.status===204)return!1;if(t.status===200)return t.headers.get("X-Store-Complete")!=="false";if(t.status===404)return!1;const i=new Error(`Store error: ${t.status}`);throw i.status=t.status,_.warn(`has(${e}/${s}): unexpected status ${t.status}`),i}catch(t){throw t.status||t.name==="AbortError"||t.name==="TimeoutError"||_.warn(`has(${e}/${s}): network error — ${t.message}`),t}}async get(e,s){var t,i;try{const n=await fetch(`/store/${e}/${s}`);if(n.status===204||n.status===404)return(t=n.body)==null||t.cancel(),null;if(!n.ok)throw(i=n.body)==null||i.cancel(),new Error(`Failed to get file: ${n.status}`);return await n.blob()}catch(n){return _.error("get error:",n.message),null}}async put(e,s,t,i="application/octet-stream"){var n;try{const r=await fetch(`/store/${e}/${s}`,{method:"PUT",headers:{"Content-Type":i},body:t});return(n=r.body)==null||n.cancel(),r.ok}catch(r){return _.error("put error:",r.message),!1}}async remove(e){try{const t=await(await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})})).json();return{deleted:t.deleted||0,total:t.total||e.length}}catch(s){return _.error("remove error:",s.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch("/store/list")).json()).files||[]}catch(e){return _.error("list error:",e.message),[]}}}const D={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function v(d){return D[d]||D.media}const u=C("Download"),P=6,S=50*1024*1024,A=3,M=100*1024*1024,z=2,b=6e5,Q=15e3;function U(d){var i,n;const s=(n=(i=(d.path||d.code||"").split(".").pop())==null?void 0:i.split("?")[0])==null?void 0:n.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[s]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},m=Symbol("BARRIER");function T(d){try{const e=new URL(d,"http://localhost"),s=e.searchParams.get("X-Amz-Date"),t=e.searchParams.get("X-Amz-Expires");if(s&&t){const i=s.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/,"$1-$2-$3T$4:$5:$6Z"),n=new Date(i).getTime()/1e3;return isNaN(n)?1/0:n+parseInt(t,10)}return 1/0}catch{return 1/0}}function F(d,e=30){const s=T(d);return s===1/0?!1:Date.now()/1e3>=s-e}class x{constructor(e,s={}){this.fileInfo=e,this.chunkIndex=s.chunkIndex??null,this.rangeStart=s.rangeStart??null,this.rangeEnd=s.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal,this._typeConfig=v(e.type)}getUrl(){const e=this.fileInfo.path;if(F(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){var t;this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e["X-Store-Chunk-Index"]=String(this.chunkIndex),this._parentFile&&(e["X-Store-Num-Chunks"]=String(this._parentFile.totalChunks),e["X-Store-Chunk-Size"]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e["X-Store-MD5"]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e["X-Cache-TTL"]=String(this.fileInfo.updateInterval)),this.fileInfo.cmsDownloadUrl&&(e["X-Cms-Download-Url"]=this.fileInfo.cmsDownloadUrl);const s=this._typeConfig.maxRetries;for(let i=1;i<=s;i++){const n=new AbortController,r=setTimeout(()=>n.abort(),b);try{const a=this.getUrl(),h={signal:n.signal};Object.keys(e).length>0&&(h.headers=e);const o=await fetch(a,h);if(!o.ok&&o.status!==206)throw new Error(`Fetch failed: ${o.status}`);return this.blob=await o.blob(),this.state="complete",this.blob}catch(a){const h=n.signal.aborted?`Timeout after ${b/1e3}s`:a.message;if(i<s){const o=((t=this._typeConfig.retryDelays)==null?void 0:t[i-1])??this._typeConfig.retryDelayMs*i,l=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";u.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${l} attempt ${i}/${s} failed: ${h}. Retrying in ${o/1e3}s...`),await new Promise(p=>setTimeout(p,o))}else throw this.state="failed",n.signal.aborted?new Error(h):a}finally{clearTimeout(r)}}}}class E{constructor(e,s={}){this.fileInfo=e,this.options=s,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((t,i)=>{this._resolve=t,this._reject=i}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(F(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:s,type:t,size:i}=this.fileInfo;u.info("[FileDownload] Starting:",`${t}/${s}`),this.totalBytes=i&&i>0?parseInt(i):0,this._contentType=U(this.fileInfo);const n=v(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!n){const a=this.getUrl(),h=new AbortController,o=setTimeout(()=>h.abort(),Q);try{const l=await fetch(a,{method:"HEAD",signal:h.signal});l.ok&&(this.totalBytes=parseInt(l.headers.get("Content-Length")||"0"),this._contentType=l.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(o)}}u.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const r=this.options.chunkSize||S;if(this.totalBytes>M){const a=[];for(let c=0;c<this.totalBytes;c+=r)a.push({start:c,end:Math.min(c+r-1,this.totalBytes-1),index:a.length});this.totalChunks=a.length;const h=a.filter(c=>!this.skipChunks.has(c.index)),o=a.length-h.length;for(const c of a)this.skipChunks.has(c.index)&&(this.downloadedBytes+=c.end-c.start+1);if(h.length===0){u.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}o>0&&u.info(`[FileDownload] Resuming: ${o} chunks cached, ${h.length} to download`);const l=o>0;if(l){const c=h.sort((g,$)=>g.index-$.index);for(const g of c){const $=new x(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});$._parentFile=this,$._priority=f.normal,this.tasks.push($)}}else for(const c of h){const g=new x(this.fileInfo,{chunkIndex:c.index,rangeStart:c.start,rangeEnd:c.end});g._parentFile=this,g._priority=c.index===0||c.index===a.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(c=>c._priority>=f.high).length;u.info(`[FileDownload] ${t}/${s}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(l?" (resume)":""))}else{this.totalChunks=1;const a=new x(this.fileInfo,{});a._parentFile=this,this.tasks.push(a)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(s){u.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(s){u.warn("[FileDownload] onChunkDownloaded callback error:",s)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:s,id:t}=this.fileInfo;if(e.chunkIndex==null)u.info("[FileDownload] Complete:",`${s}/${t}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)u.info("[FileDownload] Complete:",`${s}/${t}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const i=[];for(let r=0;r<this.totalChunks;r++){const a=this._chunkBlobs.get(r);a&&i.push(a)}const n=new Blob(i,{type:this._contentType});u.info("[FileDownload] Complete:",`${s}/${t}`,`(${n.size} bytes, reassembled)`),this._resolve(n)}this._chunkBlobs.clear()}}onTaskFailed(e,s){var t;if(!(this.state==="complete"||this.state==="failed")){if((t=s.message)!=null&&t.includes("URL expired")){const i=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";u.warn(`[FileDownload] URL expired, dropping${i}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(n=>n!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}u.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}}class L{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const s=q.stableKey(e);if(this.queue.active.has(s)){const i=this.queue.active.get(s);if(e.path&&e.path!==i.fileInfo.path){const n=T(i.fileInfo.path);T(e.path)>n&&(i.fileInfo.path=e.path)}return i}const t=new E(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(s,t),this._filesToPrepare.push(t),t}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let s=0,t=0;const i=()=>{for(;s<this._maxPreparing&&t<this._filesToPrepare.length;){const n=this._filesToPrepare[t++];s++,n.prepare(this).finally(()=>{s--,t>=this._filesToPrepare.length&&s===0?e():i()})}};this._filesToPrepare.length===0?e():i()})}_sortWithBarriers(){var r;const e=[],s=[],t=[],i=[];for(const a of this._tasks)if(a.chunkIndex==null)e.push(a);else if(a.chunkIndex===0)s.push(a);else{const h=((r=a._parentFile)==null?void 0:r.totalChunks)||0;h>1&&a.chunkIndex===h-1?t.push(a):i.push(a)}e.sort((a,h)=>{var o,l;return(((o=a._parentFile)==null?void 0:o.totalBytes)||0)-(((l=h._parentFile)==null?void 0:l.totalBytes)||0)}),i.sort((a,h)=>a.chunkIndex-h.chunkIndex);const n=[...e,...s,...t];return i.length>0&&n.push(m,...i),n}}class q{constructor(e={}){this.concurrency=e.concurrency||P,this.chunkSize=e.chunkSize||S,this.maxChunksPerFile=e.chunksPerFile||A,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const s=q.stableKey(e);if(this.active.has(s)){const i=this.active.get(s);if(e.path&&e.path!==i.fileInfo.path){const n=T(i.fileInfo.path);T(e.path)>n&&(u.info("[DownloadQueue] Refreshing URL for",s),i.fileInfo.path=e.path)}return i}const t=new E(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(s,t),u.info("[DownloadQueue] Enqueued:",s),this._schedulePrepare(t),t}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const s of e)this.queue.push(s);this._sortQueue(),u.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let s=0,t=0;for(const i of e)i===m?(this.queue.push(m),t++):(this.queue.push(i),s++);u.info(`[DownloadQueue] Ordered queue: ${s} tasks, ${t} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,s)=>s._priority-e._priority)}prioritizeLayoutFiles(e,s=f.high){var n,r,a,h;const t=new Set(e.map(String));let i=0;for(const o of this.queue){const l=((n=o._parentFile)==null?void 0:n.fileInfo.saveAs)||String((r=o._parentFile)==null?void 0:r.fileInfo.id);t.has(l)&&o._priority<s&&(o._priority=s,i++)}for(const o of this._activeTasks){const l=((a=o._parentFile)==null?void 0:a.fileInfo.saveAs)||String((h=o._parentFile)==null?void 0:h.fileInfo.id);t.has(l)&&o._priority<s&&(o._priority=s)}this._sortQueue(),u.info("[DownloadQueue] Layout files prioritized:",t.size,"files,",i,"tasks boosted to",s)}urgentChunk(e,s,t){const i=`${e}/${s}`,n=this.active.get(i);if(!n)return u.info("[DownloadQueue] urgentChunk: file not active:",i,"chunk",t),!1;if(this._activeTasks.some(o=>o._parentFile===n&&o.chunkIndex===t&&o.state==="downloading")){const o=this._activeTasks.find(l=>l._parentFile===n&&l.chunkIndex===t);return o&&o._priority<f.urgent?(o._priority=f.urgent,u.info(`[DownloadQueue] URGENT: ${i} chunk ${t} (already in-flight, limiting slots)`),!0):(u.info("[DownloadQueue] urgentChunk: already urgent:",i,"chunk",t),!1)}const a=this.queue.findIndex(o=>o!==m&&o._parentFile===n&&o.chunkIndex===t);if(a===-1)return u.info("[DownloadQueue] urgentChunk: chunk not in queue:",i,"chunk",t),!1;const h=this.queue.splice(a,1)[0];return h._priority=f.urgent,this.queue.unshift(h),u.info(`[DownloadQueue] URGENT: ${i} chunk ${t} (moved to front)`),this.processQueue(),!0}processQueue(){var i;if(this.paused)return;const e=this.queue.some(n=>n!==m&&n._priority>=f.urgent)||((i=this._activeTasks)==null?void 0:i.some(n=>n._priority>=f.urgent&&n.state==="downloading")),s=e?z:this.concurrency,t=e?f.urgent:0;for(;this.running<s&&this.queue.length>0;){const n=this.queue[0];if(n===m){if(this.running>0)break;this.queue.shift();continue}if(n._priority<t||!this._canStartTask(n)){let r=!1;for(let a=1;a<this.queue.length&&this.queue[a]!==m;a++){const h=this.queue[a];if(h._priority>=t&&this._canStartTask(h)){this.queue.splice(a,1),this._startTask(h),r=!0;break}}if(!r)break;continue}this.queue.shift(),this._startTask(n)}this.queue.length===0&&this.running===0&&u.info("[DownloadQueue] All downloads complete")}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);const s=`${e.fileInfo.type}/${e.fileInfo.id}`,t=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";u.info(`[DownloadQueue] Starting: ${s}${t} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(i=>i!==e),u.info(`[DownloadQueue] Fetched: ${s}${t} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(i=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(a=>a!==e);const{maxReenqueues:n,reenqueueDelayMs:r}=e._typeConfig;if(n>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>n){u.error(`[DownloadQueue] ${s} exceeded ${n} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,i);return}u.warn(`[DownloadQueue] ${s} failed all retries (attempt ${e._reenqueueCount}/${n}), scheduling re-enqueue in ${r/1e3}s`);const a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state="pending",e._parentFile.state="downloading",this.queue.push(e),u.info(`[DownloadQueue] ${s} re-enqueued for retry`),this.processQueue()},r);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,i)})}removeCompleted(e){const s=this.active.get(e);s&&(s.state==="complete"||s.state==="failed")&&(this.queue=this.queue.filter(t=>t===m||t._parentFile!==s),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[s,t]of this.active.entries())t.state==="complete"||t.state==="failed"||(e[s]={downloaded:t.downloadedBytes,total:t.totalBytes,percent:t.totalBytes>0?(t.downloadedBytes/t.totalBytes*100).toFixed(1):0,state:t.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(const e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}}class X{constructor(e={}){this.queue=new q(e)}enqueue(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,s){this.queue.prioritizeLayoutFiles(e,s),this.queue.processQueue()}urgentChunk(e,s,t){return this.queue.urgentChunk(e,s,t)}createTaskBuilder(){return new L(this.queue)}enqueueOrderedTasks(e){this.queue.enqueueOrderedTasks(e)}removeCompleted(e){this.queue.removeCompleted(e)}get running(){return this.queue.running}get queued(){return this.queue.queue.length}clear(){this.queue.clear()}}const y=C("CacheAnalyzer");function w(d){if(d===0)return"0 B";if(!Number.isFinite(d))return"∞";const e=["B","KB","MB","GB","TB"],s=Math.floor(Math.log(d)/Math.log(1024));return`${(d/Math.pow(1024,s)).toFixed(s>0?1:0)} ${e[s]}`}class K{constructor(e,{threshold:s=80}={}){this.cache=e,this.threshold=s}async analyze(e){const s=await this.cache.list(),t=await this._getStorageEstimate(),i=new Set(e.map(o=>String(o.id))),n=[],r=[];for(const o of s)if(i.has(String(o.id)))n.push(o);else if(o.type==="widget"){const l=String(o.id).split("/")[0];i.has(l)?n.push(o):r.push(o)}else o.type==="static"?n.push(o):r.push(o);r.sort((o,l)=>(o.cachedAt||0)-(l.cachedAt||0));const a=r.reduce((o,l)=>o+(l.size||0),0),h={timestamp:Date.now(),storage:{usage:t.usage,quota:t.quota,percent:t.quota>0?Math.round(t.usage/t.quota*100):0},files:{required:n.length,orphaned:r.length,total:s.length},orphaned:r.map(o=>({id:o.id,type:o.type,size:o.size||0,cachedAt:o.cachedAt||0})),orphanedSize:a,evicted:[],threshold:this.threshold};if(y.info(`Storage: ${w(t.usage)} / ${w(t.quota)} (${h.storage.percent}%)`),y.info(`Cache: ${n.length} required, ${r.length} orphaned (${w(a)} reclaimable)`),r.length>0)for(const o of r){const l=Date.now()-(o.cachedAt||0),p=Math.floor(l/864e5),c=Math.floor(l%864e5/36e5),g=p>0?`${p}d ago`:`${c}h ago`;y.info(` Orphaned: ${o.type}/${o.id} (${w(o.size||0)}, cached ${g})`)}if(h.storage.percent>this.threshold&&r.length>0){y.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const o=t.usage-t.quota*this.threshold/100;h.evicted=await this._evict(r,o)}else y.info(`No eviction needed (threshold: ${this.threshold}%)`);return h}async _getStorageEstimate(){var e;try{if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate)){const{usage:s,quota:t}=await navigator.storage.estimate();return{usage:s||0,quota:t||1/0}}}catch(s){y.warn("Storage estimate unavailable:",s.message)}return{usage:0,quota:1/0}}async _evict(e,s){const t=[];let i=0;for(const n of e){if(i>=s)break;t.push(n),i+=n.size||0}if(t.length===0)return[];try{const n=t.map(r=>({type:r.type,id:r.id}));await this.cache.remove(n);for(const r of t)y.info(` Evicted: ${r.type}/${r.id} (${w(r.size||0)})`);y.info(`Evicted ${t.length} files, freed ${w(i)}`)}catch(n){return y.warn("Eviction failed:",n.message),[]}return t.map(n=>({id:n.id,type:n.type,size:n.size||0,cachedAt:n.cachedAt||0}))}}const I=C("Cache"),H=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function Y(d,e,s,t){var l;const i=`${k}/widgets/${d}/${e}/${s}`,n=`<base href="${k}/media/file/">`;let r=t;t.includes("<base ")||(t.includes("<head>")?r=t.replace("<head>","<head>"+n):t.includes("<HEAD>")?r=t.replace("<HEAD>","<HEAD>"+n):r=n+t);const a="<style>img,video{object-position:center center}</style>";r.includes("object-position:center center")||(r.includes("</head>")?r=r.replace("</head>",a+"</head>"):r.includes("</HEAD>")&&(r=r.replace("</HEAD>",a+"</HEAD>"))),r=r.replace(/\[\[ViewPortWidth]]/g,"device-width"),r=r.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,p=>"/stream-proxy?url="+encodeURIComponent(p));const h=new RegExp(`https?://[^"'\\s)]+?(${k.replace(/\//g,"\\/")}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,"g");if(r=r.replace(h,(p,c)=>c),r=r.replace(/(<(?:script|link)\b[^>]*(?:src|href)=")(?!\/|https?:\/\/)(bundle\.min\.js|fonts\.css)(")/g,`$1${k}/dependencies/$2$3`),!r.includes("xiboICTargetId")){const p=`<script>var xiboICTargetId = '${s}';<\/script>`;r.includes(n)?r=r.replace(n,n+p):r.includes("<head>")?r=r.replace("<head>","<head>"+p):r=p+r}return r=r.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${H}/ic"`),I.info("Injected base tag in widget HTML"),(l=(await fetch(`/store${k}/widgets/${d}/${e}/${s}`,{method:"PUT",headers:{"Content-Type":"text/html; charset=utf-8"},body:r})).body)==null||l.cancel(),I.info(`Stored widget HTML at ${i} (${r.length} bytes)`),{cacheKey:i,html:r}}export{m as B,K as C,X as D,D as F,L,O as S,B as a,E as b,Y as c,N as d,v as g,F as i};
2
+ //# sourceMappingURL=widget-html-BpnFG_FM.js.map