@xiboplayer/pwa 0.5.0 → 0.5.1

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.
@@ -0,0 +1,2 @@
1
+ import"./modulepreload-polyfill-B5Qt9EMX.js";import{b as e,C as D}from"./cms-api-Cqh1b8je.js";import{R as A,X as K}from"./xmds-client-BPdCcQeh.js";const P="0.5.1";document.getElementById("version-footer").textContent=`Xibo Player v${P}`;const L=document.getElementById("setup-form"),y=document.getElementById("error"),c=document.getElementById("submit-btn"),w=document.getElementById("phase-unlock"),f=document.getElementById("phase-setup"),B=document.getElementById("phase-waiting"),v=document.getElementById("countdown"),R=document.getElementById("waiting-display-name"),U=document.getElementById("btn-back"),N=document.getElementById("success-flash"),I=e.hardwareKey;document.getElementById("hw-key-display").textContent=I;document.getElementById("hw-key-waiting").textContent=I;let u=null,s=null,k=15,i=null;async function E(){if(i)return i;try{const t=new A(e);await t.registerDisplay(),console.log("[Setup] Using REST transport"),i=t}catch(t){console.log("[Setup] REST unavailable, using XMDS/SOAP:",t.message),i=new K(e)}return i}function m(t){w.classList.remove("active"),f.classList.remove("active"),B.classList.remove("active"),t.classList.add("active")}function z(t){y.textContent=t,y.style.display="block"}function T(){y.style.display="none"}function p(){let t=k;v.textContent=t,clearInterval(s),s=setInterval(()=>{t--,v.textContent=Math.max(0,t),t<=0&&clearInterval(s)},1e3)}function g(){N.classList.add("active"),setTimeout(()=>{window.location.href="./index.html"},800)}async function X(){try{const n=await(await E()).registerDisplay();if(console.log("[Setup] Poll result:",n.code,n.message),n.code==="READY"){clearInterval(u),clearInterval(s),g();return}p()}catch(t){console.warn("[Setup] Poll failed:",t.message),p()}}function C(t){R.textContent=t,m(B),p(),u=setInterval(X,k*1e3)}function b(){clearInterval(u),clearInterval(s),u=null}async function Y(t,n){const a=document.getElementById("api-client-id").value.trim(),o=document.getElementById("api-client-secret").value.trim();if(!a||!o)return!1;try{const l=new D({baseUrl:t,clientId:a,clientSecret:o});await l.authenticate();const d=await l.findDisplay(n);return d?d.licensed===1?(console.log("[Setup] Display already authorized"),!0):(await l.authorizeDisplay(d.displayId),console.log("[Setup] Display auto-authorized via API!"),e.apiClientId=a,e.apiClientSecret=o,!0):(console.log("[Setup] Display not found via API (may not be registered yet)"),!1)}catch(l){return console.warn("[Setup] Auto-authorize failed:",l.message),!1}}const r=e.isConfigured()&&e.cmsKey,h=new URLSearchParams(window.location.search).has("unlocked"),S=document.getElementById("btn-back-player");r&&!h&&m(w);(r||h)&&(S.style.display="block",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));function x(){b(),window.location.href="./index.html"}S.addEventListener("click",x);(r||h)&&document.addEventListener("keydown",t=>{t.key==="Escape"&&(t.preventDefault(),x())});document.getElementById("unlock-form").addEventListener("submit",t=>{t.preventDefault();const n=document.getElementById("unlock-error");document.getElementById("unlock-key").value.trim()===e.cmsKey?(n.style.display="none",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""),m(f)):(n.textContent="Incorrect CMS key",n.style.display="block")});!r&&e.isConfigured()&&(document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));L.addEventListener("submit",async t=>{t.preventDefault(),T();const n=document.getElementById("cms-url").value.trim().replace(/\/$/,""),a=document.getElementById("cms-key").value.trim(),o=document.getElementById("display-name").value.trim();e.cmsUrl=n,e.cmsKey=a,e.displayName=o,j(e.hardwareKey);try{c.textContent="Connecting...",c.disabled=!0,i=null;const l=await E();if((await l.registerDisplay()).code==="READY")g();else{if(c.textContent="Authorizing...",await Y(n,I)&&(await l.registerDisplay()).code==="READY"){g();return}C(o)}}catch(l){z(`Connection failed: ${l.message}`),c.textContent="Connect",c.disabled=!1}});U.addEventListener("click",()=>{b(),m(f),c.textContent="Connect",c.disabled=!1});async function j(t){try{const n=indexedDB.open("xibo-hw-backup",1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains("keys")||a.createObjectStore("keys")},n.onsuccess=()=>{const a=n.result,o=a.transaction("keys","readwrite");o.objectStore("keys").put(t,"hardwareKey"),o.oncomplete=()=>a.close()}}catch(n){console.warn("[Setup] IndexedDB backup failed:",n)}}c.disabled=!1;c.textContent="Connect";e.isConfigured()&&!r&&(async()=>{try{(await(await E()).registerDisplay()).code==="READY"?window.location.href="./index.html":C(e.displayName)}catch{console.log("[Setup] Auto-check failed, showing form")}})();
2
+ //# sourceMappingURL=setup-Byd6qu0w.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-Byd6qu0w.js","sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config, CmsApiClient } 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 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 function showSuccess() {\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = './index.html';\n }, 800);\n }\n\n // ── Authorization Polling ──\n async function checkAuthorization() {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n console.log('[Setup] Poll result:', result.code, result.message);\n\n if (result.code === 'READY') {\n // Authorized!\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n showSuccess();\n return;\n }\n\n // Still waiting — restart countdown\n startCountdown();\n } catch (error) {\n console.warn('[Setup] Poll failed:', error.message);\n startCountdown();\n }\n }\n\n function startPolling(displayName) {\n waitingNameEl.textContent = displayName;\n showPhase(phaseWaiting);\n startCountdown();\n pollTimer = setInterval(checkAuthorization, pollSeconds * 1000);\n }\n\n function stopPolling() {\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n pollTimer = null;\n }\n\n // ── Auto-authorize via CMS API ──\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 const api = new CmsApiClient({ baseUrl: cmsUrl, clientId, clientSecret });\n await api.authenticate();\n\n const display = await api.findDisplay(hardwareKey);\n if (!display) {\n console.log('[Setup] Display not found via API (may not be registered yet)');\n return false;\n }\n\n if (display.licensed === 1) {\n console.log('[Setup] Display already authorized');\n return true;\n }\n\n // Auto-authorize\n await api.authorizeDisplay(display.displayId);\n console.log('[Setup] Display auto-authorized via API!');\n\n // Save API credentials for future use\n config.apiClientId = clientId;\n config.apiClientSecret = clientSecret;\n\n return true;\n } catch (error) {\n console.warn('[Setup] Auto-authorize failed:', error.message);\n return false;\n }\n }\n\n // ── Unlock gate for reconfiguration ──\n const isReconfigure = config.isConfigured() && config.cmsKey;\n const alreadyUnlocked = new URLSearchParams(window.location.search).has('unlocked');\n const btnBackPlayer = document.getElementById('btn-back-player');\n if (isReconfigure && !alreadyUnlocked) {\n // Show unlock phase instead of setup form\n showPhase(phaseUnlock);\n }\n if (isReconfigure || alreadyUnlocked) {\n // Show \"Back to Player\" on the setup form\n btnBackPlayer.style.display = 'block';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = './index.html';\n }\n btnBackPlayer.addEventListener('click', goBackToPlayer);\n\n // Esc also goes back to player when reconfiguring\n if (isReconfigure || alreadyUnlocked) {\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n goBackToPlayer();\n }\n });\n }\n\n // ── Unlock form handler ──\n document.getElementById('unlock-form').addEventListener('submit', (e) => {\n e.preventDefault();\n const unlockError = document.getElementById('unlock-error');\n const enteredKey = document.getElementById('unlock-key').value.trim();\n\n if (enteredKey === config.cmsKey) {\n unlockError.style.display = 'none';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n showPhase(phaseSetup);\n } else {\n unlockError.textContent = 'Incorrect CMS key';\n unlockError.style.display = 'block';\n }\n });\n\n // ── Pre-fill if first-time setup (no unlock gate) ──\n if (!isReconfigure && config.isConfigured()) {\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n }\n\n // ── Form Submit ──\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n hideError();\n\n const cmsUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n const cmsKey = document.getElementById('cms-key').value.trim();\n const displayName = document.getElementById('display-name').value.trim();\n\n // Save config\n config.cmsUrl = cmsUrl;\n config.cmsKey = cmsKey;\n config.displayName = displayName;\n\n // Also backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n try {\n submitBtn.textContent = 'Connecting...';\n submitBtn.disabled = true;\n\n // Try REST first, fall back to SOAP\n transport = null; // reset transport for fresh detection\n const client = await getTransport();\n const result = await client.registerDisplay();\n\n if (result.code === 'READY') {\n showSuccess();\n } else {\n // Try auto-authorize via CMS API if credentials provided\n submitBtn.textContent = 'Authorizing...';\n const autoAuthed = await tryAutoAuthorize(cmsUrl, hwKey);\n\n if (autoAuthed) {\n // Verify registration\n const recheck = await client.registerDisplay();\n if (recheck.code === 'READY') {\n showSuccess();\n return;\n }\n }\n\n // Not authorized yet — switch to polling phase\n startPolling(displayName);\n }\n } catch (error) {\n showError(`Connection failed: ${error.message}`);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n }\n });\n\n // ── Back button ──\n btnBack.addEventListener('click', () => {\n stopPolling();\n showPhase(phaseSetup);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n });\n\n // ── IndexedDB hardware key backup ──\n async function backupHardwareKey(key) {\n try {\n const req = indexedDB.open('xibo-hw-backup', 1);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains('keys')) {\n db.createObjectStore('keys');\n }\n };\n req.onsuccess = () => {\n const db = req.result;\n const tx = db.transaction('keys', 'readwrite');\n tx.objectStore('keys').put(key, 'hardwareKey');\n tx.oncomplete = () => db.close();\n };\n } catch (e) {\n console.warn('[Setup] IndexedDB backup failed:', e);\n }\n }\n\n // ── Enable submit ──\n submitBtn.disabled = false;\n submitBtn.textContent = 'Connect';\n\n // ── Auto-resume polling if already registered but not authorized ──\n // Skip auto-resume when reconfiguring (user explicitly opened setup)\n if (config.isConfigured() && !isReconfigure) {\n (async () => {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n if (result.code === 'READY') {\n window.location.href = './index.html';\n } else {\n // Not authorized — go straight to polling\n startPolling(config.displayName);\n }\n } catch (e) {\n // Connection failed, show form\n console.log('[Setup] Auto-check failed, showing form');\n }\n })();\n }\n "],"names":["appVersion","form","errorEl","submitBtn","phaseUnlock","phaseSetup","phaseWaiting","countdownEl","waitingNameEl","btnBack","successFlash","hwKey","config","pollTimer","countdownTimer","pollSeconds","transport","getTransport","rest","RestClient","e","XmdsClient","showPhase","phase","showError","msg","hideError","startCountdown","remaining","showSuccess","checkAuthorization","result","error","startPolling","displayName","stopPolling","tryAutoAuthorize","cmsUrl","hardwareKey","clientId","clientSecret","api","CmsApiClient","display","isReconfigure","alreadyUnlocked","btnBackPlayer","goBackToPlayer","unlockError","cmsKey","backupHardwareKey","client","key","req","db","tx"],"mappings":"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"}
package/dist/index.html CHANGED
@@ -88,7 +88,7 @@
88
88
  height: 100%;
89
89
  }
90
90
  </style>
91
- <script type="module" crossorigin src="./assets/main-93Kmpgur.js"></script>
91
+ <script type="module" crossorigin src="./assets/main-B65Xrh0d.js"></script>
92
92
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
93
93
  <link rel="modulepreload" crossorigin href="./assets/cms-api-Cqh1b8je.js">
94
94
  <link rel="modulepreload" crossorigin href="./assets/widget-html-Cb84FvUB.js">
@@ -111,14 +111,14 @@
111
111
 
112
112
  // Check if player is configured with valid CMS connection params
113
113
  const params = new URLSearchParams(window.location.search);
114
- const hasUrlConfig = params.has('cmsAddress') && params.has('cmsKey');
114
+ const hasUrlConfig = params.has('cmsUrl') && params.has('cmsKey');
115
115
 
116
116
  let hasStoredConfig = false;
117
117
  try {
118
118
  const raw = localStorage.getItem('xibo_config');
119
119
  if (raw) {
120
120
  const cfg = JSON.parse(raw);
121
- hasStoredConfig = !!(cfg.cmsAddress && cfg.cmsKey);
121
+ hasStoredConfig = !!(cfg.cmsUrl && cfg.cmsKey);
122
122
  }
123
123
  } catch (e) { /* corrupt config — treat as missing */ }
124
124
 
package/dist/setup.html CHANGED
@@ -287,7 +287,7 @@
287
287
  color: #444;
288
288
  }
289
289
  </style>
290
- <script type="module" crossorigin src="./assets/setup-C_0dET1G.js"></script>
290
+ <script type="module" crossorigin src="./assets/setup-Byd6qu0w.js"></script>
291
291
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
292
292
  <link rel="modulepreload" crossorigin href="./assets/cms-api-Cqh1b8je.js">
293
293
  <link rel="modulepreload" crossorigin href="./assets/xmds-client-BPdCcQeh.js">
@@ -317,8 +317,8 @@
317
317
  <div id="phase-setup" class="phase active">
318
318
  <form id="setup-form">
319
319
  <div class="form-group">
320
- <label for="cms-address">CMS Address</label>
321
- <input type="url" id="cms-address" placeholder="https://cms.example.com" required>
320
+ <label for="cms-url">CMS URL</label>
321
+ <input type="url" id="cms-url" placeholder="https://cms.example.com" required>
322
322
  </div>
323
323
 
324
324
  <div class="form-group">
@@ -351,6 +351,7 @@
351
351
  </details>
352
352
 
353
353
  <button type="submit" id="submit-btn" disabled>Loading...</button>
354
+ <button type="button" id="btn-back-player" class="btn-secondary" style="display: none;">Back to Player</button>
354
355
  </form>
355
356
 
356
357
  <div id="error" class="error-msg"></div>
@@ -389,8 +390,8 @@
389
390
  </div>
390
391
  </div>
391
392
 
392
- <div class="footer">
393
- Xibo Player v0.1.0
393
+ <div class="footer" id="version-footer">
394
+ Xibo Player
394
395
  </div>
395
396
  </div>
396
397
 
package/dist/sw-pwa.js CHANGED
@@ -1,2 +1,2 @@
1
- import{r as U,L as O,B as H,D as Z}from"./assets/widget-html-Cb84FvUB.js";import{VERSION as Q}from"./assets/index-pcbcUHVR.js";import"./assets/cms-api-Cqh1b8je.js";const y=(()=>{var h;return typeof self<"u"&&((h=self.registration)!=null&&h.scope)?new URL(self.registration.scope).pathname.replace(/\/$/,""):"/player/pwa"})();function x(h,t=1){if(h===0)return"0 Bytes";if(h<1024)return`${h} Bytes`;const e=h/1024;if(e<1024)return`${e.toFixed(t)} KB`;const a=e/1024;return a<1024?`${a.toFixed(t)} MB`:`${(a/1024).toFixed(t)} GB`}function G(h,t){const e=h.replace(/bytes=/,"").split("-"),a=parseInt(e[0],10),s=e[1]?parseInt(e[1],10):t-1;return{start:a,end:s}}function K(h,t,e){const a=Math.floor(h/e),s=Math.floor(t/e);return{startChunk:a,endChunk:s,count:s-a+1}}function j(h,t,e,a,s){if(h.length===1){const o=t%a,d=e-t+1;return h[0].slice(o,o+d)}const i=[],n=t%a,l=e%a;i.push(h[0].slice(n));for(let o=1;o<h.length-1;o++)i.push(h[o]);return h.length>1&&i.push(h[h.length-1].slice(0,l+1)),new Blob(i,{type:s})}class D{constructor(t){this.name=t,this.level=typeof self<"u"&&self.swLogLevel||"INFO"}debug(...t){this.level==="DEBUG"&&console.log(`[${this.name}] DEBUG:`,...t)}info(...t){(this.level==="DEBUG"||this.level==="INFO")&&console.log(`[${this.name}]`,...t)}warn(...t){console.warn(`[${this.name}]`,...t)}error(...t){console.error(`[${this.name}]`,...t)}}function ee(h){h||(h=new D("ChunkConfig"));const t=typeof navigator<"u"&&navigator.deviceMemory||null;let e=4;if(t)e=t,h.info("Detected device memory:",t,"GB");else if(typeof navigator<"u"){const l=navigator.userAgent.toLowerCase();l.includes("raspberry pi")||l.includes("armv6")?(e=.5,h.info("Detected Pi Zero (512 MB RAM estimated)")):l.includes("armv7")?(e=1,h.info("Detected ARM device (1 GB RAM estimated)")):h.info("Using default RAM estimate:",e,"GB")}let a,s,i,n;return e<=.5?(a=10*1024*1024,s=25,i=25*1024*1024,n=1,h.info("Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download")):e<=1?(a=20*1024*1024,s=50,i=50*1024*1024,n=2,h.info("1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads")):e<=2?(a=30*1024*1024,s=100,i=75*1024*1024,n=2,h.info("2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads")):e<=4?(a=50*1024*1024,s=200,i=100*1024*1024,n=4,h.info("4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads")):(a=100*1024*1024,s=500,i=200*1024*1024,n=6,h.info("High-RAM config: 100 MB chunks, 500 MB cache, 6 concurrent downloads")),{chunkSize:a,blobCacheSize:s,threshold:i,concurrency:n}}class te{constructor({cacheName:t="xibo-media-v1",chunkSize:e}={}){this.cache=null,this.cacheName=t,this.chunkSize=e,this.log=new D("Cache"),this.metadataCache=new Map}async init(){this.cache=await caches.open(this.cacheName)}async get(t){return this.cache||await this.init(),await this.cache.match(t,{ignoreSearch:!0,ignoreVary:!0})}async put(t,e,a){this.cache||await this.init();const s=new Response(e,{headers:{"Content-Type":a,"Content-Length":e.size,"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes"}});await this.cache.put(t,s)}async delete(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(this.metadataCache.delete(t),e){const a=[this.cache.delete(`${t}/metadata`)];for(let s=0;s<e.numChunks;s++)a.push(this.cache.delete(`${t}/chunk-${s}`));return await Promise.all(a),!0}return await this.cache.delete(t)}async clear(){this.cache||await this.init();const t=await this.cache.keys();await Promise.all(t.map(e=>this.cache.delete(e))),this.metadataCache.clear(),this.log.info("Cleared",t.length,"cached files")}async fileExists(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(e)return{exists:!0,chunked:!0,metadata:e};if(await this.get(t))return{exists:!0,chunked:!1,metadata:null};const s=await this.getMetadata(t);return s&&s.chunked?(this.metadataCache.set(t,s),{exists:!0,chunked:!0,metadata:s}):{exists:!1,chunked:!1,metadata:null}}async getFileSize(t){const e=await this.fileExists(t);if(!e.exists)return null;if(e.chunked)return e.metadata.totalSize;const a=await this.get(t),s=a==null?void 0:a.headers.get("Content-Length");return s?parseInt(s):null}async putChunked(t,e,a){this.cache||await this.init();const s=this.chunkSize,i=e.size,n=Math.ceil(i/s);this.log.info(`Storing as ${n} chunks: ${t} (${x(i)})`);const l={totalSize:i,chunkSize:s,numChunks:n,contentType:a,chunked:!0,complete:!1,createdAt:Date.now()},o=new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}});await this.cache.put(`${t}/metadata`,o),this.metadataCache.set(t,l);for(let d=0;d<n;d++){const u=d*s,f=Math.min(u+s,i),c=e.slice(u,f),$=new Response(c,{headers:{"Content-Type":a,"Content-Length":c.size,"X-Chunk-Index":d,"X-Total-Chunks":n}});await this.cache.put(`${t}/chunk-${d}`,$),((d+1)%5===0||d===n-1)&&this.log.info(`Stored chunk ${d+1}/${n} (${x(c.size)})`)}l.complete=!0,await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,l),this.log.info(`Chunked storage complete: ${t}`)}async getMetadata(t){const e=this.metadataCache.get(t);if(e)return e;this.cache||await this.init();const a=await this.cache.match(`${t}/metadata`);if(!a)return null;const s=await a.text(),i=JSON.parse(s);return this.metadataCache.set(t,i),i}async updateMetadata(t,e){this.cache||await this.init(),await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,e)}async getAllFiles(){this.cache||await this.init();const t=await this.cache.keys(),e=[],a=new Set;for(const s of t){const n=new URL(s.url).pathname;if(n.includes("/chunk-")||n.endsWith("/metadata")){const o=n.replace(/\/(chunk-\d+|metadata)$/,"");if(a.has(o))continue;a.add(o);const d=await this.getMetadata(o),u=o.match(/\/cache\/(media|layout|widget)\/(.+)/);u&&e.push({id:u[2],type:u[1],size:(d==null?void 0:d.totalSize)||0,cachedAt:(d==null?void 0:d.createdAt)||0});continue}if(n.includes("/cache/static/")||a.has(n))continue;a.add(n);const l=n.match(/\/cache\/(media|layout|widget)\/(.+)/);if(l){const o=await this.cache.match(s);e.push({id:l[2],type:l[1],size:parseInt((o==null?void 0:o.headers.get("Content-Length"))||"0"),cachedAt:0})}}return e}async isChunked(t){const e=await this.getMetadata(t);return(e==null?void 0:e.chunked)===!0}async getChunk(t,e){return this.cache||await this.init(),await this.cache.match(`${t}/chunk-${e}`)}}class ae{constructor(t=200){this.cache=new Map,this.maxBytes=t*1024*1024,this.currentBytes=0,this.log=new D("BlobCache")}has(t){return this.cache.has(t)}async get(t,e){if(this.cache.has(t)){const s=this.cache.get(t);return s.lastAccess=Date.now(),this.log.debug(`HIT: ${t} (${x(s.size)})`),s.blob}this.log.debug(`MISS: ${t} - loading from Cache API`);const a=await e();for(;this.currentBytes+a.size>this.maxBytes&&this.cache.size>0;)this.evictLRU();if(this.currentBytes+a.size<=this.maxBytes){this.cache.set(t,{blob:a,lastAccess:Date.now(),size:a.size}),this.currentBytes+=a.size;const s=(this.currentBytes/this.maxBytes*100).toFixed(1);this.log.debug(`CACHED: ${t} (${x(a.size)}) - utilization: ${s}%`)}else this.log.debug(`Skipping memory cache (too large): ${t} (${x(a.size)} > ${x(this.maxBytes)})`);return a}evictLRU(){let t=null,e=null;for(const[a,s]of this.cache)(!t||s.lastAccess<t.lastAccess)&&(t=s,e=a);e&&(this.currentBytes-=t.size,this.cache.delete(e),this.log.debug(`EVICTED LRU: ${e} (${x(t.size)})`))}clear(){this.cache.clear(),this.currentBytes=0,this.log.info("Cleared all cached blobs")}getStats(){return{entries:this.cache.size,bytes:this.currentBytes,maxBytes:this.maxBytes,utilization:(this.currentBytes/this.maxBytes*100).toFixed(1)+"%"}}}class se{constructor(t,e,a,{staticCache:s="xibo-static-v1"}={}){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.staticCache=s,this.pendingFetches=new Map,this.log=new D("SW"),this.pendingChunkLoads=new Map}async routeFileRequest(t,e,a){const s=await this.cacheManager.fileExists(t);if(!s.exists)return{found:!1,handler:null,data:null};if(s.chunked){const i={metadata:s.metadata,cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-chunked",data:i}:a?{found:!0,handler:"range-chunked",data:{...i,rangeHeader:a}}:{found:!0,handler:"full-chunked",data:i}}else{const n={cached:await this.cacheManager.get(t),cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-whole",data:n}:a?{found:!0,handler:"range-whole",data:{...n,rangeHeader:a}}:{found:!0,handler:"full-whole",data:n}}}async handleRequest(t){var f;const e=new URL(t.request.url);if(this.log.info("handleRequest called for:",e.href),this.log.info("pathname:",e.pathname),e.pathname===y+"/"||e.pathname===y+"/index.html"||e.pathname===y+"/setup.html"){const $=await(await caches.open(this.staticCache)).match(t.request);return $?(this.log.info("Serving static file from cache:",e.pathname),$):(this.log.info("Fetching static file from network:",e.pathname),fetch(t.request))}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&(e.searchParams.get("fileType")==="bundle"||e.searchParams.get("fileType")==="fontCss"||e.searchParams.get("fileType")==="font")){const c=e.searchParams.get("file"),$=`${y}/cache/static/${c}`,M=await caches.open(this.staticCache),C=await M.match($);if(C)return this.log.info("Serving widget resource from cache:",c),C.clone();if(this.pendingFetches.has(c))return this.log.info("Deduplicating widget resource fetch:",c),(await this.pendingFetches.get(c)).clone();this.log.info("Fetching widget resource from CMS:",c);const T=(async()=>{try{const g=await fetch(t.request);if(g.ok){this.log.info("Caching widget resource:",c,`(${g.headers.get("Content-Type")})`);const v=g.clone();return await M.put($,v),g}else return this.log.warn("Widget resource not available (",g.status,"):",c,"- NOT caching"),g}catch(g){return this.log.error("Failed to fetch widget resource:",c,g),new Response("Failed to fetch widget resource",{status:502,statusText:"Bad Gateway",headers:{"Content-Type":"text/plain"}})}})();this.pendingFetches.set(c,T);try{return(await T).clone()}finally{this.pendingFetches.delete(c)}}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&e.searchParams.has("file")){const c=e.searchParams.get("file"),$=c.split(".")[0],M=e.searchParams.get("type"),C=M==="L"?"layout":"media";this.log.info("XMDS request:",c,"type:",M,"→",y+"/cache/"+C+"/"+$);const T=`${y}/cache/${C}/${$}`,g=await this.cacheManager.get(T);return g?new Response(g.clone().body,{headers:{"Content-Type":g.headers.get("Content-Type")||"video/mp4","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000","Accept-Ranges":"bytes"}}):(this.log.info("XMDS file not cached, passing through:",c),fetch(t.request))}if(e.pathname.startsWith(y+"/cache/static/")){const c=e.pathname.split("/").pop();this.log.info("Static resource request:",c);const M=await(await caches.open(this.staticCache)).match(`${y}/cache/static/${c}`);if(M)return this.log.info("Serving static resource from static cache:",c),M.clone();const C=await this.cacheManager.get(e.pathname);return C?(this.log.info("Serving static resource from media cache:",c),new Response(C.clone().body,{headers:{"Content-Type":C.headers.get("Content-Type")||"application/octet-stream","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})):(this.log.warn("Static resource not cached:",c),new Response("Resource not cached",{status:404}))}if(!e.pathname.startsWith(y+"/cache/"))return this.log.info("NOT a cache request, returning null:",e.pathname),null;if(this.log.info("IS a cache request, proceeding...",e.pathname),e.pathname.startsWith(y+"/cache/widget/")){this.log.info("Widget HTML request:",e.pathname);const c=await this.cacheManager.get(e.pathname);return c?new Response(c.clone().body,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}}):new Response("<!DOCTYPE html><html><body>Widget not found</body></html>",{status:404,headers:{"Content-Type":"text/html"}})}const a=e.pathname.replace(/\.json$/,""),s=t.request.method,i=t.request.headers.get("Range");this.log.debug("Request URL:",e.pathname),this.log.debug("Cache key:",a),i?this.log.info(s,a,`Range: ${i}`):this.log.info(s,a);const n=await this.routeFileRequest(a,s,i);if(n.found)switch(n.handler){case"head-whole":return this.handleHeadWhole((f=n.data.cached)==null?void 0:f.headers.get("Content-Length"));case"head-chunked":return this.handleHeadChunked(n.data.metadata,n.data.cacheKey);case"range-whole":return this.handleRangeRequest(n.data.cached,n.data.rangeHeader,n.data.cacheKey);case"range-chunked":return this.handleChunkedRangeRequest(n.data.cacheKey,n.data.rangeHeader,n.data.metadata);case"full-whole":return this.handleFullWhole(n.data.cached,n.data.cacheKey);case"full-chunked":return this.handleFullChunked(n.data.cacheKey,n.data.metadata);default:return this.log.error("Unknown handler:",n.handler),new Response("Internal error: unknown handler",{status:500})}const l=a.split("/"),o=l[l.length-2],d=l[l.length-1];let u=null;for(const[,c]of this.downloadManager.queue.active.entries())if(c.fileInfo.type===o&&String(c.fileInfo.id)===d){u=c;break}if(u){this.log.info("Download in progress, waiting:",a);try{await u.wait();const c=await this.routeFileRequest(a,s,i);if(c.found)switch(this.log.info("Download complete, serving via",c.handler),c.handler){case"full-whole":return this.handleFullWhole(c.data.cached,c.data.cacheKey);case"full-chunked":return this.handleFullChunked(c.data.cacheKey,c.data.metadata);default:return this.handleRequest(t)}}catch(c){return this.log.error("Download failed:",a,c),new Response("Download failed: "+c.message,{status:500})}}return this.log.info("Not found:",a),new Response("Not found",{status:404})}handleHeadWhole(t){return this.log.info("HEAD response: File exists (whole file)"),new Response(null,{status:200,headers:{"Content-Length":t?t.toString():"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleHeadChunked(t,e){return await this.cacheManager.getChunk(e,0)?(this.log.info("HEAD response: File exists (chunked)"),new Response(null,{status:200,headers:{"Content-Length":t.totalSize.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})):(this.log.info("HEAD response: Chunked file not yet playable (chunk 0 missing):",e),new Response(null,{status:404}))}handleFullWhole(t,e){const a=t.headers.get("Content-Length"),s=a?x(parseInt(a)):"unknown size";return this.log.info("Serving from cache:",e,`(${s})`),new Response(t.body,{headers:{"Content-Type":t.headers.get("Content-Type")||"application/octet-stream","Content-Length":a||"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})}async handleFullChunked(t,e){this.log.info("Chunked file GET without Range:",t,`- serving full file from ${e.numChunks} chunks`);const a=`bytes=0-${e.totalSize-1}`;return this.handleChunkedRangeRequest(t,a,e)}async handleRangeRequest(t,e,a){const s=await this.blobCache.get(a,async()=>await t.clone().blob()),i=s.size,{start:n,end:l}=G(e,i),o=s.slice(n,l+1);return this.log.debug(`Range: bytes ${n}-${l}/${i} (${x(o.size)} of ${x(i)})`),new Response(o,{status:206,statusText:"Partial Content",headers:{"Content-Type":t.headers.get("Content-Type")||"video/mp4","Content-Length":o.size.toString(),"Content-Range":`bytes ${n}-${l}/${i}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleChunkedRangeRequest(t,e,a){const{totalSize:s,chunkSize:i,numChunks:n,contentType:l}=a,{start:o,end:d}=G(e,s);let u=d;const f=e.replace(/bytes=/,"");if(f.indexOf("-")===f.length-1){const p=Math.floor(o/i),r=n-1;let w=!0;for(let m=p;m<=r;m++){const k=`${t}/chunk-${m}`;if(this.blobCache.has(k))continue;if(!await this.cacheManager.getChunk(t,m)){w=!1;break}}if(w)this.log.info(`All chunks cached from ${p} to ${r}, serving full range (bytes ${o}-${u}/${s})`);else{const m=Math.min((p+1)*i-1,s-1);m<u&&(u=m,this.log.info(`Progressive streaming: capping bytes=${o}- to chunk ${p} (bytes ${o}-${u}/${s})`))}}const{startChunk:$,endChunk:M,count:C}=K(o,u,i);this.log.debug(`Chunked range: bytes ${o}-${u}/${s} (chunks ${$}-${M}, ${C} chunks)`);const T=p=>{const r=`${t}/chunk-${p}`;return this.blobCache.get(r,()=>{if(this.pendingChunkLoads.has(r))return this.pendingChunkLoads.get(r);const w=(async()=>{let m=await this.cacheManager.getChunk(t,p);if(m)return await m.blob();this.log.info(`Chunk ${p}/${n} not yet available for ${t}, signalling urgent...`);{const k=t.split("/"),b=k[k.length-1],E=k[k.length-2];this.downloadManager.queue.urgentChunk(E,b,p)}for(let k=0;k<60;k++)if(await new Promise(b=>setTimeout(b,1e3)),m=await this.cacheManager.getChunk(t,p),m)return this.log.info(`Chunk ${p}/${n} arrived for ${t} after ${k+1}s`),await m.blob();throw new Error(`Chunk ${p} not available for ${t} after 60s`)})();return this.pendingChunkLoads.set(r,w),w.finally(()=>this.pendingChunkLoads.delete(r)),w})},g=[];let v=!0;for(let p=$;p<=M;p++){const r=await this.cacheManager.getChunk(t,p);if(r){const w=`${t}/chunk-${p}`,m=await this.blobCache.get(w,async()=>await r.blob());g.push(m)}else{v=!1;break}}if(v&&g.length===C){const p=j(g,o,u,i);return this.log.debug(`Serving chunked range: ${x(p.size)} from ${C} chunk(s)`),new Response(p,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":p.size.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}this.log.info(`Streaming response for ${t} bytes ${o}-${u} (waiting for chunks)`);const L=u-o+1,z=new ReadableStream({async start(p){try{const r=[];for(let k=$;k<=M;k++){const b=await T(k);r.push(b)}const m=await j(r,o,u,i).arrayBuffer();p.enqueue(new Uint8Array(m)),p.close()}catch(r){this.log.error(`Stream error for ${t}: ${r.message}`),p.error(r)}}});return new Response(z,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":L.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}}function I(h,t){const e=new Set,a=h.matchAll(/<media[^>]+fileId="(\d+)"/g);for(const n of a)e.add(n[1]);const s=h.matchAll(/<media\s+([^>]+)>/g);for(const n of s){const l=n[1];if(!l.includes("fileId=")){const o=l.match(/\bid="(\d+)"/);o&&e.add(o[1])}}const i=h.matchAll(/<layout[^>]+background="(\d+)"/g);for(const n of i)e.add(n[1]);return t&&t.debug(`extractMediaIdsFromXlf: found ${e.size} IDs: ${[...e].join(", ")} (XLF ${h.length} bytes)`),e}const X={js:"application/javascript",css:"text/css",otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"};class ne{constructor(t,e,a,s){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.config={cacheName:"xibo-media-v1",staticCache:"xibo-static-v1",...s},this.log=new D("SW Message"),this.pendingChunkStorage=new Map}async handleMessage(t){const{type:e,data:a}=t.data;switch(e==="GET_DOWNLOAD_PROGRESS"?this.log.debug("Received:",e):this.log.info("Received:",e),e){case"PING":return this.log.info("PING received, broadcasting SW_READY"),(await self.clients.matchAll()).forEach(i=>{i.postMessage({type:"SW_READY"})}),{success:!0};case"DOWNLOAD_FILES":return await this.handleDownloadFiles(a);case"PRIORITIZE_DOWNLOAD":return this.handlePrioritizeDownload(a.fileType,a.fileId);case"CLEAR_CACHE":return await this.handleClearCache();case"GET_DOWNLOAD_PROGRESS":return await this.handleGetProgress();case"DELETE_FILES":return await this.handleDeleteFiles(a.files);case"PREWARM_VIDEO_CHUNKS":return await this.handlePrewarmVideoChunks(a.mediaIds);case"PRIORITIZE_LAYOUT_FILES":return this.downloadManager.prioritizeLayoutFiles(a.mediaIds),{success:!0};case"URGENT_CHUNK":return this.handleUrgentChunk(a.fileType,a.fileId,a.chunkIndex);case"GET_ALL_FILES":return await this.handleGetAllFiles();default:return this.log.warn("Unknown message type:",e),{success:!1,error:"Unknown message type"}}}async handleDeleteFiles(t){if(!t||!Array.isArray(t))return{success:!1,error:"No files provided"};let e=0;for(const a of t){const s=`${y}/cache/${a.type}/${a.id}`;await this.cacheManager.delete(s)?(this.log.info("Purged:",s),e++):this.log.debug("Not cached (skip purge):",s)}return this.log.info(`Purge complete: ${e}/${t.length} files deleted`),{success:!0,deleted:e,total:t.length}}async handlePrewarmVideoChunks(t){if(!t||!Array.isArray(t)||t.length===0)return{success:!1,error:"No mediaIds provided"};let e=0;for(const a of t){const s=`${y}/cache/media/${a}`,i=await this.cacheManager.getMetadata(s);if(i!=null&&i.chunked){const n=i.numChunks-1,l=[0];n>0&&l.push(n);for(const o of l){const d=`${s}/chunk-${o}`;await this.blobCache.get(d,async()=>{const u=await this.cacheManager.getChunk(s,o);return u?await u.blob():new Blob})}this.log.info(`Pre-warmed ${l.length} chunks for media ${a} (${i.numChunks} total)`),e++}else{const n=await this.cacheManager.get(s);n&&(await this.blobCache.get(s,async()=>await n.clone().blob()),this.log.info(`Pre-warmed whole file for media ${a}`),e++)}}return{success:!0,warmed:e,total:t.length}}handlePrioritizeDownload(t,e){this.log.info("Prioritize request:",`${t}/${e}`);const a=this.downloadManager.queue.prioritize(t,e);return this.downloadManager.queue.processQueue(),{success:!0,found:a}}handleUrgentChunk(t,e,a){return this.log.info("Urgent chunk request:",`${t}/${e}`,"chunk",a),{success:!0,acted:this.downloadManager.queue.urgentChunk(t,e,a)}}async handleDownloadFiles({layoutOrder:t,files:e,layoutDependants:a}){const s=this.downloadManager,i=s.queue;let n=0;const l=[],o=new Map,d=[],u=new Map;for(const r of e)r.type==="layout"?o.set(parseInt(r.id),r):r.type==="resource"||r.code==="fonts.css"||r.path&&(r.path.includes("bundle.min")||r.path.includes("fonts"))?d.push(r):u.set(String(r.id),r);this.log.info(`Download: ${t.length} layouts, ${u.size} media, ${d.length} resources`);const f=new Map,c=[];for(const r of t){const w=o.get(r);w!=null&&w.path&&c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);let b;if(k)b=await k.clone().text();else{const E=await fetch(U(w.path));if(!E.ok){this.log.warn(`XLF fetch failed: ${r} (${E.status})`);return}const F=await E.blob();await this.cacheManager.put(m,F,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (${F.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:F.size})),b=await F.text()}f.set(r,I(b,this.log))})())}for(const[r,w]of o)t.includes(r)||c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);if(!k&&w.path){const b=await fetch(U(w.path));if(b.ok){const E=await b.blob();await this.cacheManager.put(m,E,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (non-scheduled, ${E.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:E.size}));const S=await E.text();f.set(r,I(S,this.log))}}else if(k){const b=await k.clone().text();f.set(r,I(b,this.log))}})());await Promise.allSettled(c),this.log.info(`Parsed ${f.size} XLFs`);const $=new O(i);for(const r of d)await this._enqueueFile(s,$,r,l)&&n++;const M=await $.build();M.length>0&&(M.push(H),i.enqueueOrderedTasks(M));const C=new Set,T=[...f.keys()].filter(r=>!t.includes(r)),g=new Map;for(const[r,w]of u)w.saveAs&&g.set(w.saveAs,r);const v=new Map;if(a)for(const[r,w]of Object.entries(a))v.set(parseInt(r,10),w);for(const r of t){const w=f.get(r);if(!w)continue;const m=new Set(w);for(const S of T){const R=f.get(S);if(R)for(const Y of R)m.add(Y)}const k=v.get(r)||[];for(const S of k){const R=g.get(S);R&&m.add(R)}const b=[];for(const S of m){if(C.has(S))continue;const R=u.get(S);R&&(b.push(R),C.add(S))}if(b.length===0)continue;this.log.info(`Layout ${r}: ${b.length} media`),b.sort((S,R)=>(S.size||0)-(R.size||0));const E=new O(i);for(const S of b)await this._enqueueFile(s,E,S,l)&&n++;const F=await E.build();F.length>0&&(F.push(H),i.enqueueOrderedTasks(F))}const L=[...u.keys()].filter(r=>!C.has(r));if(L.length>0){this.log.info(`${L.length} media not in any XLF: ${L.join(", ")}`);const r=new O(i);for(const m of L){const k=u.get(m);k&&await this._enqueueFile(s,r,k,l)&&n++}const w=await r.build();w.length>0&&i.enqueueOrderedTasks(w)}const z=i.running,p=i.queue.length;return this.log.info("Downloads active:",z,", queued:",p),{success:!0,enqueuedCount:n,activeCount:z,queuedCount:p}}async _enqueueFile(t,e,a,s){if(!a.path||a.path==="null"||a.path==="undefined")return this.log.debug("Skipping file with no path:",a.id),!1;const i=`${y}/cache/${a.type}/${a.id}`,n=await this.cacheManager.fileExists(i);if(n.exists)if(n.chunked&&n.metadata&&!n.metadata.complete){const{numChunks:u}=n.metadata,f=new Set;for(let c=0;c<u;c++)await this.cacheManager.getChunk(i,c)&&f.add(c);if(f.size===u)return this.log.info("All chunks present but metadata incomplete, marking complete:",i),n.metadata.complete=!0,await this.cacheManager.updateMetadata(i,n.metadata),!1;this.log.info(`Incomplete chunked download: ${f.size}/${u} chunks cached, resuming:`,i),a.skipChunks=f}else return this.log.debug("File already cached:",i,n.chunked?"(chunked)":"(whole file)"),await this.ensureStaticCacheEntry(a),!1;const l=`${a.type}/${a.id}`;if(t.getTask(l))return this.log.debug("File already downloading:",l,"- skipping duplicate"),!1;const d=e.addFile(a);if(d.state==="pending"){const u=this.cacheFileAfterDownload(d,a);return s.push(u),!0}return!1}async cacheFileAfterDownload(t,e){try{const a=`${y}/cache/${e.type}/${e.id}`,s=e.type==="layout"?"text/xml":e.type==="widget"?"text/html":"application/octet-stream",i=parseInt(e.size)||0;if(i>this.config.chunkStorageThreshold)return await this._progressiveCacheFile(t,e,a,s,i);const n=await t.wait();return await this.cacheManager.put(a,n,s),this.log.info("Cached after download:",a,`(${n.size} bytes)`),(await self.clients.matchAll()).forEach(o=>{o.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:n.size})}),this._cacheStaticResource(e,n),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),n}catch(a){throw this.log.error("Failed to cache after download:",e.id,a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),a}}async _progressiveCacheFile(t,e,a,s,i){const{chunkSize:n,cacheName:l}=this.config,o=await caches.open(l);let d=0,u=!1;const f=Math.ceil(i/n);this.log.info(`Progressive download: ${a} (${x(i)}, ~${f} chunks)`);const c={totalSize:i,chunkSize:n,numChunks:f,contentType:s,chunked:!0,complete:!1,createdAt:Date.now()};await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})),this.cacheManager.metadataCache.set(a,c),this.log.info("Metadata stored, ready for progressive streaming:",a),t.onChunkDownloaded=async(C,T,g)=>{const v=new Response(T,{headers:{"Content-Type":s,"Content-Length":T.size,"X-Chunk-Index":C,"X-Total-Chunks":g}});if(await o.put(`${a}/chunk-${C}`,v),d++,(d%2===0||d===g)&&this.log.info(`Progressive: chunk ${d}/${g} cached for ${e.id}`),!u&&(C===0||C===g-1)){const L=C===0||await this.cacheManager.getChunk(a,0),z=C===g-1||await this.cacheManager.getChunk(a,g-1);L&&z&&(u=!0,(await self.clients.matchAll()).forEach(r=>{r.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,progressive:!0,chunksReady:d,totalChunks:g})}),this.log.info("Chunk 0 + last chunk cached — client notified, early playback ready:",a))}g!==f&&(c.numChunks=g,await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})))};const $=await t.wait();return d===0?(this.log.warn("Progressive callback never fired, falling back to putChunked:",a),$.size>0?await this.cacheManager.putChunked(a,$,s):await this.cacheManager.put(a,$,s),(await self.clients.matchAll()).forEach(T=>{T.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:$.size||i})}),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),$):t._urlExpired?(this.log.warn(`URL expired mid-download, partial cache: ${a} (${d}/${f} chunks stored)`),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s})):(this.log.info(`Progressive download complete: ${a} (${d} chunks stored)`),c.complete=!0,await this.cacheManager.updateMetadata(a,c),(await self.clients.matchAll()).forEach(C=>{C.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,complete:!0})}),this.pendingChunkStorage.delete(a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s}))}_cacheStaticResource(t,e){const a=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;a&&(a.endsWith(".js")||a.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(a))&&(async()=>{try{const s=await caches.open(this.config.staticCache),i=`${y}/cache/static/${a}`,n=a.split(".").pop().toLowerCase(),l=X[n]||"application/octet-stream";await Promise.all([s.put(i,new Response(e.slice(0,e.size,e.type),{headers:{"Content-Type":l}})),this.cacheManager.put(i,e.slice(0,e.size,e.type),l)]),this.log.info("Also cached as static resource:",a,`(${l})`)}catch(s){this.log.warn("Failed to cache static resource:",a,s)}})()}async ensureStaticCacheEntry(t){const e=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;if(!e||!(e.endsWith(".js")||e.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(e)))return;const a=await caches.open(this.config.staticCache),s=`${y}/cache/static/${e}`;if(await a.match(s))return;const n=`${y}/cache/${t.type}/${t.id}`,l=await this.cacheManager.get(n);if(!l)return;const o=await l.blob(),d=e.split(".").pop().toLowerCase(),u=X[d]||"application/octet-stream",f=`${y}/cache/static/${e}`;await Promise.all([a.put(s,new Response(o.slice(0,o.size,o.type),{headers:{"Content-Type":u}})),this.cacheManager.put(f,o.slice(0,o.size,o.type),u)]),this.log.info("Backfilled static cache for:",e,`(${u}, ${o.size} bytes)`)}async handleGetAllFiles(){return{success:!0,files:await this.cacheManager.getAllFiles()}}async handleClearCache(){return this.log.info("Clearing cache"),await this.cacheManager.clear(),{success:!0}}async handleGetProgress(){return{success:!0,progress:this.downloadManager.getProgress()}}}const q="2026-02-24T14:19:08.357Z",N="xibo-media-v1",P="xibo-static-v1",ie=[y+"/",y+"/index.html",y+"/setup.html"],A=new D("SW"),B=ee(A),_=B.chunkSize,oe=B.threshold,ce=B.blobCacheSize,re=B.concurrency;A.info("Loading modular Service Worker:",q);const V=new Z({concurrency:re,chunkSize:_,chunksPerFile:2}),W=new te({cacheName:N,chunkSize:_}),J=new ae(ce),he=new se(V,W,J,{staticCache:P}),le=new ne(V,W,J,{cacheName:N,staticCache:P,chunkSize:_,chunkStorageThreshold:oe});async function ue(h){const t=new URL(h.request.url),e=t.pathname.replace(y+"/ic",""),a=h.request.method;A.info("Interactive Control request:",a,e);let s=null;if(a==="POST"||a==="PUT")try{s=await h.request.text()}catch{}const i=await self.clients.matchAll({type:"window"});if(i.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const n=i[0];try{const l=await new Promise((o,d)=>{const u=new MessageChannel,f=setTimeout(()=>d(new Error("IC timeout")),5e3);u.port1.onmessage=c=>{clearTimeout(f),o(c.data)},n.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:e,search:t.search,body:s},[u.port2])});return new Response(l.body||"",{status:l.status||200,headers:{"Content-Type":l.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(l){return A.error("IC handler error:",l),new Response(JSON.stringify({error:l.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",h=>{A.info("Installing... Version:",q),h.waitUntil(Promise.all([W.init(),caches.open(P).then(t=>(A.info("Caching static files"),t.addAll(ie)))]).then(async()=>{if(A.info("Cache initialized"),self.registration.active)try{const e=await(await caches.open("xibo-sw-version")).match("version");if(e){const a=await e.text();if(a===q){A.info("Same version already active, skipping activation to preserve streams");return}A.info("Version changed:",a,"→",q)}}catch{}return A.info("New version, activating immediately"),self.skipWaiting()}))});self.addEventListener("activate",h=>{A.info("Activating... Version:",q,"| @xiboplayer/cache:",Q),h.waitUntil(caches.keys().then(t=>Promise.all(t.filter(e=>e.startsWith("xibo-")&&e!==N&&e!==P&&e!=="xibo-sw-version").map(e=>(A.info("Deleting old cache:",e),caches.delete(e))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(q)),A.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{A.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(e=>{e.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",h=>{const t=new URL(h.request.url);if(t.pathname.startsWith(y+"/cache/")||t.pathname.startsWith(y+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&h.request.method==="GET"){if(t.pathname.startsWith(y+"/ic/")){h.respondWith(ue(h));return}h.respondWith(he.handleRequest(h))}});self.addEventListener("message",h=>{h.waitUntil(le.handleMessage(h).then(t=>{var e;(e=h.ports[0])==null||e.postMessage(t)}))});A.info("Modular Service Worker ready");
1
+ import{r as U,L as O,B as H,D as Z}from"./assets/widget-html-Cb84FvUB.js";import{VERSION as Q}from"./assets/index-pcbcUHVR.js";import"./assets/cms-api-Cqh1b8je.js";const y=(()=>{var h;return typeof self<"u"&&((h=self.registration)!=null&&h.scope)?new URL(self.registration.scope).pathname.replace(/\/$/,""):"/player/pwa"})();function x(h,t=1){if(h===0)return"0 Bytes";if(h<1024)return`${h} Bytes`;const e=h/1024;if(e<1024)return`${e.toFixed(t)} KB`;const a=e/1024;return a<1024?`${a.toFixed(t)} MB`:`${(a/1024).toFixed(t)} GB`}function G(h,t){const e=h.replace(/bytes=/,"").split("-"),a=parseInt(e[0],10),s=e[1]?parseInt(e[1],10):t-1;return{start:a,end:s}}function K(h,t,e){const a=Math.floor(h/e),s=Math.floor(t/e);return{startChunk:a,endChunk:s,count:s-a+1}}function j(h,t,e,a,s){if(h.length===1){const o=t%a,d=e-t+1;return h[0].slice(o,o+d)}const i=[],n=t%a,l=e%a;i.push(h[0].slice(n));for(let o=1;o<h.length-1;o++)i.push(h[o]);return h.length>1&&i.push(h[h.length-1].slice(0,l+1)),new Blob(i,{type:s})}class D{constructor(t){this.name=t,this.level=typeof self<"u"&&self.swLogLevel||"INFO"}debug(...t){this.level==="DEBUG"&&console.log(`[${this.name}] DEBUG:`,...t)}info(...t){(this.level==="DEBUG"||this.level==="INFO")&&console.log(`[${this.name}]`,...t)}warn(...t){console.warn(`[${this.name}]`,...t)}error(...t){console.error(`[${this.name}]`,...t)}}function ee(h){h||(h=new D("ChunkConfig"));const t=typeof navigator<"u"&&navigator.deviceMemory||null;let e=4;if(t)e=t,h.info("Detected device memory:",t,"GB");else if(typeof navigator<"u"){const l=navigator.userAgent.toLowerCase();l.includes("raspberry pi")||l.includes("armv6")?(e=.5,h.info("Detected Pi Zero (512 MB RAM estimated)")):l.includes("armv7")?(e=1,h.info("Detected ARM device (1 GB RAM estimated)")):h.info("Using default RAM estimate:",e,"GB")}let a,s,i,n;return e<=.5?(a=10*1024*1024,s=25,i=25*1024*1024,n=1,h.info("Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download")):e<=1?(a=20*1024*1024,s=50,i=50*1024*1024,n=2,h.info("1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads")):e<=2?(a=30*1024*1024,s=100,i=75*1024*1024,n=2,h.info("2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads")):e<=4?(a=50*1024*1024,s=200,i=100*1024*1024,n=4,h.info("4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads")):(a=100*1024*1024,s=500,i=200*1024*1024,n=6,h.info("High-RAM config: 100 MB chunks, 500 MB cache, 6 concurrent downloads")),{chunkSize:a,blobCacheSize:s,threshold:i,concurrency:n}}class te{constructor({cacheName:t="xibo-media-v1",chunkSize:e}={}){this.cache=null,this.cacheName=t,this.chunkSize=e,this.log=new D("Cache"),this.metadataCache=new Map}async init(){this.cache=await caches.open(this.cacheName)}async get(t){return this.cache||await this.init(),await this.cache.match(t,{ignoreSearch:!0,ignoreVary:!0})}async put(t,e,a){this.cache||await this.init();const s=new Response(e,{headers:{"Content-Type":a,"Content-Length":e.size,"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes"}});await this.cache.put(t,s)}async delete(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(this.metadataCache.delete(t),e){const a=[this.cache.delete(`${t}/metadata`)];for(let s=0;s<e.numChunks;s++)a.push(this.cache.delete(`${t}/chunk-${s}`));return await Promise.all(a),!0}return await this.cache.delete(t)}async clear(){this.cache||await this.init();const t=await this.cache.keys();await Promise.all(t.map(e=>this.cache.delete(e))),this.metadataCache.clear(),this.log.info("Cleared",t.length,"cached files")}async fileExists(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(e)return{exists:!0,chunked:!0,metadata:e};if(await this.get(t))return{exists:!0,chunked:!1,metadata:null};const s=await this.getMetadata(t);return s&&s.chunked?(this.metadataCache.set(t,s),{exists:!0,chunked:!0,metadata:s}):{exists:!1,chunked:!1,metadata:null}}async getFileSize(t){const e=await this.fileExists(t);if(!e.exists)return null;if(e.chunked)return e.metadata.totalSize;const a=await this.get(t),s=a==null?void 0:a.headers.get("Content-Length");return s?parseInt(s):null}async putChunked(t,e,a){this.cache||await this.init();const s=this.chunkSize,i=e.size,n=Math.ceil(i/s);this.log.info(`Storing as ${n} chunks: ${t} (${x(i)})`);const l={totalSize:i,chunkSize:s,numChunks:n,contentType:a,chunked:!0,complete:!1,createdAt:Date.now()},o=new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}});await this.cache.put(`${t}/metadata`,o),this.metadataCache.set(t,l);for(let d=0;d<n;d++){const u=d*s,f=Math.min(u+s,i),c=e.slice(u,f),$=new Response(c,{headers:{"Content-Type":a,"Content-Length":c.size,"X-Chunk-Index":d,"X-Total-Chunks":n}});await this.cache.put(`${t}/chunk-${d}`,$),((d+1)%5===0||d===n-1)&&this.log.info(`Stored chunk ${d+1}/${n} (${x(c.size)})`)}l.complete=!0,await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,l),this.log.info(`Chunked storage complete: ${t}`)}async getMetadata(t){const e=this.metadataCache.get(t);if(e)return e;this.cache||await this.init();const a=await this.cache.match(`${t}/metadata`);if(!a)return null;const s=await a.text(),i=JSON.parse(s);return this.metadataCache.set(t,i),i}async updateMetadata(t,e){this.cache||await this.init(),await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,e)}async getAllFiles(){this.cache||await this.init();const t=await this.cache.keys(),e=[],a=new Set;for(const s of t){const n=new URL(s.url).pathname;if(n.includes("/chunk-")||n.endsWith("/metadata")){const o=n.replace(/\/(chunk-\d+|metadata)$/,"");if(a.has(o))continue;a.add(o);const d=await this.getMetadata(o),u=o.match(/\/cache\/(media|layout|widget)\/(.+)/);u&&e.push({id:u[2],type:u[1],size:(d==null?void 0:d.totalSize)||0,cachedAt:(d==null?void 0:d.createdAt)||0});continue}if(n.includes("/cache/static/")||a.has(n))continue;a.add(n);const l=n.match(/\/cache\/(media|layout|widget)\/(.+)/);if(l){const o=await this.cache.match(s);e.push({id:l[2],type:l[1],size:parseInt((o==null?void 0:o.headers.get("Content-Length"))||"0"),cachedAt:0})}}return e}async isChunked(t){const e=await this.getMetadata(t);return(e==null?void 0:e.chunked)===!0}async getChunk(t,e){return this.cache||await this.init(),await this.cache.match(`${t}/chunk-${e}`)}}class ae{constructor(t=200){this.cache=new Map,this.maxBytes=t*1024*1024,this.currentBytes=0,this.log=new D("BlobCache")}has(t){return this.cache.has(t)}async get(t,e){if(this.cache.has(t)){const s=this.cache.get(t);return s.lastAccess=Date.now(),this.log.debug(`HIT: ${t} (${x(s.size)})`),s.blob}this.log.debug(`MISS: ${t} - loading from Cache API`);const a=await e();for(;this.currentBytes+a.size>this.maxBytes&&this.cache.size>0;)this.evictLRU();if(this.currentBytes+a.size<=this.maxBytes){this.cache.set(t,{blob:a,lastAccess:Date.now(),size:a.size}),this.currentBytes+=a.size;const s=(this.currentBytes/this.maxBytes*100).toFixed(1);this.log.debug(`CACHED: ${t} (${x(a.size)}) - utilization: ${s}%`)}else this.log.debug(`Skipping memory cache (too large): ${t} (${x(a.size)} > ${x(this.maxBytes)})`);return a}evictLRU(){let t=null,e=null;for(const[a,s]of this.cache)(!t||s.lastAccess<t.lastAccess)&&(t=s,e=a);e&&(this.currentBytes-=t.size,this.cache.delete(e),this.log.debug(`EVICTED LRU: ${e} (${x(t.size)})`))}clear(){this.cache.clear(),this.currentBytes=0,this.log.info("Cleared all cached blobs")}getStats(){return{entries:this.cache.size,bytes:this.currentBytes,maxBytes:this.maxBytes,utilization:(this.currentBytes/this.maxBytes*100).toFixed(1)+"%"}}}class se{constructor(t,e,a,{staticCache:s="xibo-static-v1"}={}){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.staticCache=s,this.pendingFetches=new Map,this.log=new D("SW"),this.pendingChunkLoads=new Map}async routeFileRequest(t,e,a){const s=await this.cacheManager.fileExists(t);if(!s.exists)return{found:!1,handler:null,data:null};if(s.chunked){const i={metadata:s.metadata,cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-chunked",data:i}:a?{found:!0,handler:"range-chunked",data:{...i,rangeHeader:a}}:{found:!0,handler:"full-chunked",data:i}}else{const n={cached:await this.cacheManager.get(t),cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-whole",data:n}:a?{found:!0,handler:"range-whole",data:{...n,rangeHeader:a}}:{found:!0,handler:"full-whole",data:n}}}async handleRequest(t){var f;const e=new URL(t.request.url);if(this.log.info("handleRequest called for:",e.href),this.log.info("pathname:",e.pathname),e.pathname===y+"/"||e.pathname===y+"/index.html"||e.pathname===y+"/setup.html"){const $=await(await caches.open(this.staticCache)).match(t.request);return $?(this.log.info("Serving static file from cache:",e.pathname),$):(this.log.info("Fetching static file from network:",e.pathname),fetch(t.request))}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&(e.searchParams.get("fileType")==="bundle"||e.searchParams.get("fileType")==="fontCss"||e.searchParams.get("fileType")==="font")){const c=e.searchParams.get("file"),$=`${y}/cache/static/${c}`,M=await caches.open(this.staticCache),C=await M.match($);if(C)return this.log.info("Serving widget resource from cache:",c),C.clone();if(this.pendingFetches.has(c))return this.log.info("Deduplicating widget resource fetch:",c),(await this.pendingFetches.get(c)).clone();this.log.info("Fetching widget resource from CMS:",c);const T=(async()=>{try{const g=await fetch(t.request);if(g.ok){this.log.info("Caching widget resource:",c,`(${g.headers.get("Content-Type")})`);const v=g.clone();return await M.put($,v),g}else return this.log.warn("Widget resource not available (",g.status,"):",c,"- NOT caching"),g}catch(g){return this.log.error("Failed to fetch widget resource:",c,g),new Response("Failed to fetch widget resource",{status:502,statusText:"Bad Gateway",headers:{"Content-Type":"text/plain"}})}})();this.pendingFetches.set(c,T);try{return(await T).clone()}finally{this.pendingFetches.delete(c)}}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&e.searchParams.has("file")){const c=e.searchParams.get("file"),$=c.split(".")[0],M=e.searchParams.get("type"),C=M==="L"?"layout":"media";this.log.info("XMDS request:",c,"type:",M,"→",y+"/cache/"+C+"/"+$);const T=`${y}/cache/${C}/${$}`,g=await this.cacheManager.get(T);return g?new Response(g.clone().body,{headers:{"Content-Type":g.headers.get("Content-Type")||"video/mp4","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000","Accept-Ranges":"bytes"}}):(this.log.info("XMDS file not cached, passing through:",c),fetch(t.request))}if(e.pathname.startsWith(y+"/cache/static/")){const c=e.pathname.split("/").pop();this.log.info("Static resource request:",c);const M=await(await caches.open(this.staticCache)).match(`${y}/cache/static/${c}`);if(M)return this.log.info("Serving static resource from static cache:",c),M.clone();const C=await this.cacheManager.get(e.pathname);return C?(this.log.info("Serving static resource from media cache:",c),new Response(C.clone().body,{headers:{"Content-Type":C.headers.get("Content-Type")||"application/octet-stream","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})):(this.log.warn("Static resource not cached:",c),new Response("Resource not cached",{status:404}))}if(!e.pathname.startsWith(y+"/cache/"))return this.log.info("NOT a cache request, returning null:",e.pathname),null;if(this.log.info("IS a cache request, proceeding...",e.pathname),e.pathname.startsWith(y+"/cache/widget/")){this.log.info("Widget HTML request:",e.pathname);const c=await this.cacheManager.get(e.pathname);return c?new Response(c.clone().body,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}}):new Response("<!DOCTYPE html><html><body>Widget not found</body></html>",{status:404,headers:{"Content-Type":"text/html"}})}const a=e.pathname.replace(/\.json$/,""),s=t.request.method,i=t.request.headers.get("Range");this.log.debug("Request URL:",e.pathname),this.log.debug("Cache key:",a),i?this.log.info(s,a,`Range: ${i}`):this.log.info(s,a);const n=await this.routeFileRequest(a,s,i);if(n.found)switch(n.handler){case"head-whole":return this.handleHeadWhole((f=n.data.cached)==null?void 0:f.headers.get("Content-Length"));case"head-chunked":return this.handleHeadChunked(n.data.metadata,n.data.cacheKey);case"range-whole":return this.handleRangeRequest(n.data.cached,n.data.rangeHeader,n.data.cacheKey);case"range-chunked":return this.handleChunkedRangeRequest(n.data.cacheKey,n.data.rangeHeader,n.data.metadata);case"full-whole":return this.handleFullWhole(n.data.cached,n.data.cacheKey);case"full-chunked":return this.handleFullChunked(n.data.cacheKey,n.data.metadata);default:return this.log.error("Unknown handler:",n.handler),new Response("Internal error: unknown handler",{status:500})}const l=a.split("/"),o=l[l.length-2],d=l[l.length-1];let u=null;for(const[,c]of this.downloadManager.queue.active.entries())if(c.fileInfo.type===o&&String(c.fileInfo.id)===d){u=c;break}if(u){this.log.info("Download in progress, waiting:",a);try{await u.wait();const c=await this.routeFileRequest(a,s,i);if(c.found)switch(this.log.info("Download complete, serving via",c.handler),c.handler){case"full-whole":return this.handleFullWhole(c.data.cached,c.data.cacheKey);case"full-chunked":return this.handleFullChunked(c.data.cacheKey,c.data.metadata);default:return this.handleRequest(t)}}catch(c){return this.log.error("Download failed:",a,c),new Response("Download failed: "+c.message,{status:500})}}return this.log.info("Not found:",a),new Response("Not found",{status:404})}handleHeadWhole(t){return this.log.info("HEAD response: File exists (whole file)"),new Response(null,{status:200,headers:{"Content-Length":t?t.toString():"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleHeadChunked(t,e){return await this.cacheManager.getChunk(e,0)?(this.log.info("HEAD response: File exists (chunked)"),new Response(null,{status:200,headers:{"Content-Length":t.totalSize.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})):(this.log.info("HEAD response: Chunked file not yet playable (chunk 0 missing):",e),new Response(null,{status:404}))}handleFullWhole(t,e){const a=t.headers.get("Content-Length"),s=a?x(parseInt(a)):"unknown size";return this.log.info("Serving from cache:",e,`(${s})`),new Response(t.body,{headers:{"Content-Type":t.headers.get("Content-Type")||"application/octet-stream","Content-Length":a||"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})}async handleFullChunked(t,e){this.log.info("Chunked file GET without Range:",t,`- serving full file from ${e.numChunks} chunks`);const a=`bytes=0-${e.totalSize-1}`;return this.handleChunkedRangeRequest(t,a,e)}async handleRangeRequest(t,e,a){const s=await this.blobCache.get(a,async()=>await t.clone().blob()),i=s.size,{start:n,end:l}=G(e,i),o=s.slice(n,l+1);return this.log.debug(`Range: bytes ${n}-${l}/${i} (${x(o.size)} of ${x(i)})`),new Response(o,{status:206,statusText:"Partial Content",headers:{"Content-Type":t.headers.get("Content-Type")||"video/mp4","Content-Length":o.size.toString(),"Content-Range":`bytes ${n}-${l}/${i}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleChunkedRangeRequest(t,e,a){const{totalSize:s,chunkSize:i,numChunks:n,contentType:l}=a,{start:o,end:d}=G(e,s);let u=d;const f=e.replace(/bytes=/,"");if(f.indexOf("-")===f.length-1){const p=Math.floor(o/i),r=n-1;let w=!0;for(let m=p;m<=r;m++){const k=`${t}/chunk-${m}`;if(this.blobCache.has(k))continue;if(!await this.cacheManager.getChunk(t,m)){w=!1;break}}if(w)this.log.info(`All chunks cached from ${p} to ${r}, serving full range (bytes ${o}-${u}/${s})`);else{const m=Math.min((p+1)*i-1,s-1);m<u&&(u=m,this.log.info(`Progressive streaming: capping bytes=${o}- to chunk ${p} (bytes ${o}-${u}/${s})`))}}const{startChunk:$,endChunk:M,count:C}=K(o,u,i);this.log.debug(`Chunked range: bytes ${o}-${u}/${s} (chunks ${$}-${M}, ${C} chunks)`);const T=p=>{const r=`${t}/chunk-${p}`;return this.blobCache.get(r,()=>{if(this.pendingChunkLoads.has(r))return this.pendingChunkLoads.get(r);const w=(async()=>{let m=await this.cacheManager.getChunk(t,p);if(m)return await m.blob();this.log.info(`Chunk ${p}/${n} not yet available for ${t}, signalling urgent...`);{const k=t.split("/"),b=k[k.length-1],E=k[k.length-2];this.downloadManager.queue.urgentChunk(E,b,p)}for(let k=0;k<60;k++)if(await new Promise(b=>setTimeout(b,1e3)),m=await this.cacheManager.getChunk(t,p),m)return this.log.info(`Chunk ${p}/${n} arrived for ${t} after ${k+1}s`),await m.blob();throw new Error(`Chunk ${p} not available for ${t} after 60s`)})();return this.pendingChunkLoads.set(r,w),w.finally(()=>this.pendingChunkLoads.delete(r)),w})},g=[];let v=!0;for(let p=$;p<=M;p++){const r=await this.cacheManager.getChunk(t,p);if(r){const w=`${t}/chunk-${p}`,m=await this.blobCache.get(w,async()=>await r.blob());g.push(m)}else{v=!1;break}}if(v&&g.length===C){const p=j(g,o,u,i);return this.log.debug(`Serving chunked range: ${x(p.size)} from ${C} chunk(s)`),new Response(p,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":p.size.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}this.log.info(`Streaming response for ${t} bytes ${o}-${u} (waiting for chunks)`);const L=u-o+1,z=new ReadableStream({async start(p){try{const r=[];for(let k=$;k<=M;k++){const b=await T(k);r.push(b)}const m=await j(r,o,u,i).arrayBuffer();p.enqueue(new Uint8Array(m)),p.close()}catch(r){this.log.error(`Stream error for ${t}: ${r.message}`),p.error(r)}}});return new Response(z,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":L.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}}function I(h,t){const e=new Set,a=h.matchAll(/<media[^>]+fileId="(\d+)"/g);for(const n of a)e.add(n[1]);const s=h.matchAll(/<media\s+([^>]+)>/g);for(const n of s){const l=n[1];if(!l.includes("fileId=")){const o=l.match(/\bid="(\d+)"/);o&&e.add(o[1])}}const i=h.matchAll(/<layout[^>]+background="(\d+)"/g);for(const n of i)e.add(n[1]);return t&&t.debug(`extractMediaIdsFromXlf: found ${e.size} IDs: ${[...e].join(", ")} (XLF ${h.length} bytes)`),e}const X={js:"application/javascript",css:"text/css",otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"};class ne{constructor(t,e,a,s){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.config={cacheName:"xibo-media-v1",staticCache:"xibo-static-v1",...s},this.log=new D("SW Message"),this.pendingChunkStorage=new Map}async handleMessage(t){const{type:e,data:a}=t.data;switch(e==="GET_DOWNLOAD_PROGRESS"?this.log.debug("Received:",e):this.log.info("Received:",e),e){case"PING":return this.log.info("PING received, broadcasting SW_READY"),(await self.clients.matchAll()).forEach(i=>{i.postMessage({type:"SW_READY"})}),{success:!0};case"DOWNLOAD_FILES":return await this.handleDownloadFiles(a);case"PRIORITIZE_DOWNLOAD":return this.handlePrioritizeDownload(a.fileType,a.fileId);case"CLEAR_CACHE":return await this.handleClearCache();case"GET_DOWNLOAD_PROGRESS":return await this.handleGetProgress();case"DELETE_FILES":return await this.handleDeleteFiles(a.files);case"PREWARM_VIDEO_CHUNKS":return await this.handlePrewarmVideoChunks(a.mediaIds);case"PRIORITIZE_LAYOUT_FILES":return this.downloadManager.prioritizeLayoutFiles(a.mediaIds),{success:!0};case"URGENT_CHUNK":return this.handleUrgentChunk(a.fileType,a.fileId,a.chunkIndex);case"GET_ALL_FILES":return await this.handleGetAllFiles();default:return this.log.warn("Unknown message type:",e),{success:!1,error:"Unknown message type"}}}async handleDeleteFiles(t){if(!t||!Array.isArray(t))return{success:!1,error:"No files provided"};let e=0;for(const a of t){const s=`${y}/cache/${a.type}/${a.id}`;await this.cacheManager.delete(s)?(this.log.info("Purged:",s),e++):this.log.debug("Not cached (skip purge):",s)}return this.log.info(`Purge complete: ${e}/${t.length} files deleted`),{success:!0,deleted:e,total:t.length}}async handlePrewarmVideoChunks(t){if(!t||!Array.isArray(t)||t.length===0)return{success:!1,error:"No mediaIds provided"};let e=0;for(const a of t){const s=`${y}/cache/media/${a}`,i=await this.cacheManager.getMetadata(s);if(i!=null&&i.chunked){const n=i.numChunks-1,l=[0];n>0&&l.push(n);for(const o of l){const d=`${s}/chunk-${o}`;await this.blobCache.get(d,async()=>{const u=await this.cacheManager.getChunk(s,o);return u?await u.blob():new Blob})}this.log.info(`Pre-warmed ${l.length} chunks for media ${a} (${i.numChunks} total)`),e++}else{const n=await this.cacheManager.get(s);n&&(await this.blobCache.get(s,async()=>await n.clone().blob()),this.log.info(`Pre-warmed whole file for media ${a}`),e++)}}return{success:!0,warmed:e,total:t.length}}handlePrioritizeDownload(t,e){this.log.info("Prioritize request:",`${t}/${e}`);const a=this.downloadManager.queue.prioritize(t,e);return this.downloadManager.queue.processQueue(),{success:!0,found:a}}handleUrgentChunk(t,e,a){return this.log.info("Urgent chunk request:",`${t}/${e}`,"chunk",a),{success:!0,acted:this.downloadManager.queue.urgentChunk(t,e,a)}}async handleDownloadFiles({layoutOrder:t,files:e,layoutDependants:a}){const s=this.downloadManager,i=s.queue;let n=0;const l=[],o=new Map,d=[],u=new Map;for(const r of e)r.type==="layout"?o.set(parseInt(r.id),r):r.type==="resource"||r.code==="fonts.css"||r.path&&(r.path.includes("bundle.min")||r.path.includes("fonts"))?d.push(r):u.set(String(r.id),r);this.log.info(`Download: ${t.length} layouts, ${u.size} media, ${d.length} resources`);const f=new Map,c=[];for(const r of t){const w=o.get(r);w!=null&&w.path&&c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);let b;if(k)b=await k.clone().text();else{const E=await fetch(U(w.path));if(!E.ok){this.log.warn(`XLF fetch failed: ${r} (${E.status})`);return}const F=await E.blob();await this.cacheManager.put(m,F,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (${F.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:F.size})),b=await F.text()}f.set(r,I(b,this.log))})())}for(const[r,w]of o)t.includes(r)||c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);if(!k&&w.path){const b=await fetch(U(w.path));if(b.ok){const E=await b.blob();await this.cacheManager.put(m,E,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (non-scheduled, ${E.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:E.size}));const S=await E.text();f.set(r,I(S,this.log))}}else if(k){const b=await k.clone().text();f.set(r,I(b,this.log))}})());await Promise.allSettled(c),this.log.info(`Parsed ${f.size} XLFs`);const $=new O(i);for(const r of d)await this._enqueueFile(s,$,r,l)&&n++;const M=await $.build();M.length>0&&(M.push(H),i.enqueueOrderedTasks(M));const C=new Set,T=[...f.keys()].filter(r=>!t.includes(r)),g=new Map;for(const[r,w]of u)w.saveAs&&g.set(w.saveAs,r);const v=new Map;if(a)for(const[r,w]of Object.entries(a))v.set(parseInt(r,10),w);for(const r of t){const w=f.get(r);if(!w)continue;const m=new Set(w);for(const S of T){const R=f.get(S);if(R)for(const Y of R)m.add(Y)}const k=v.get(r)||[];for(const S of k){const R=g.get(S);R&&m.add(R)}const b=[];for(const S of m){if(C.has(S))continue;const R=u.get(S);R&&(b.push(R),C.add(S))}if(b.length===0)continue;this.log.info(`Layout ${r}: ${b.length} media`),b.sort((S,R)=>(S.size||0)-(R.size||0));const E=new O(i);for(const S of b)await this._enqueueFile(s,E,S,l)&&n++;const F=await E.build();F.length>0&&(F.push(H),i.enqueueOrderedTasks(F))}const L=[...u.keys()].filter(r=>!C.has(r));if(L.length>0){this.log.info(`${L.length} media not in any XLF: ${L.join(", ")}`);const r=new O(i);for(const m of L){const k=u.get(m);k&&await this._enqueueFile(s,r,k,l)&&n++}const w=await r.build();w.length>0&&i.enqueueOrderedTasks(w)}const z=i.running,p=i.queue.length;return this.log.info("Downloads active:",z,", queued:",p),{success:!0,enqueuedCount:n,activeCount:z,queuedCount:p}}async _enqueueFile(t,e,a,s){if(!a.path||a.path==="null"||a.path==="undefined")return this.log.debug("Skipping file with no path:",a.id),!1;const i=`${y}/cache/${a.type}/${a.id}`,n=await this.cacheManager.fileExists(i);if(n.exists)if(n.chunked&&n.metadata&&!n.metadata.complete){const{numChunks:u}=n.metadata,f=new Set;for(let c=0;c<u;c++)await this.cacheManager.getChunk(i,c)&&f.add(c);if(f.size===u)return this.log.info("All chunks present but metadata incomplete, marking complete:",i),n.metadata.complete=!0,await this.cacheManager.updateMetadata(i,n.metadata),!1;this.log.info(`Incomplete chunked download: ${f.size}/${u} chunks cached, resuming:`,i),a.skipChunks=f}else return this.log.debug("File already cached:",i,n.chunked?"(chunked)":"(whole file)"),await this.ensureStaticCacheEntry(a),!1;const l=`${a.type}/${a.id}`;if(t.getTask(l))return this.log.debug("File already downloading:",l,"- skipping duplicate"),!1;const d=e.addFile(a);if(d.state==="pending"){const u=this.cacheFileAfterDownload(d,a);return s.push(u),!0}return!1}async cacheFileAfterDownload(t,e){try{const a=`${y}/cache/${e.type}/${e.id}`,s=e.type==="layout"?"text/xml":e.type==="widget"?"text/html":"application/octet-stream",i=parseInt(e.size)||0;if(i>this.config.chunkStorageThreshold)return await this._progressiveCacheFile(t,e,a,s,i);const n=await t.wait();return await this.cacheManager.put(a,n,s),this.log.info("Cached after download:",a,`(${n.size} bytes)`),(await self.clients.matchAll()).forEach(o=>{o.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:n.size})}),this._cacheStaticResource(e,n),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),n}catch(a){throw this.log.error("Failed to cache after download:",e.id,a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),a}}async _progressiveCacheFile(t,e,a,s,i){const{chunkSize:n,cacheName:l}=this.config,o=await caches.open(l);let d=0,u=!1;const f=Math.ceil(i/n);this.log.info(`Progressive download: ${a} (${x(i)}, ~${f} chunks)`);const c={totalSize:i,chunkSize:n,numChunks:f,contentType:s,chunked:!0,complete:!1,createdAt:Date.now()};await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})),this.cacheManager.metadataCache.set(a,c),this.log.info("Metadata stored, ready for progressive streaming:",a),t.onChunkDownloaded=async(C,T,g)=>{const v=new Response(T,{headers:{"Content-Type":s,"Content-Length":T.size,"X-Chunk-Index":C,"X-Total-Chunks":g}});if(await o.put(`${a}/chunk-${C}`,v),d++,(d%2===0||d===g)&&this.log.info(`Progressive: chunk ${d}/${g} cached for ${e.id}`),!u&&(C===0||C===g-1)){const L=C===0||await this.cacheManager.getChunk(a,0),z=C===g-1||await this.cacheManager.getChunk(a,g-1);L&&z&&(u=!0,(await self.clients.matchAll()).forEach(r=>{r.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,progressive:!0,chunksReady:d,totalChunks:g})}),this.log.info("Chunk 0 + last chunk cached — client notified, early playback ready:",a))}g!==f&&(c.numChunks=g,await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})))};const $=await t.wait();return d===0?(this.log.warn("Progressive callback never fired, falling back to putChunked:",a),$.size>0?await this.cacheManager.putChunked(a,$,s):await this.cacheManager.put(a,$,s),(await self.clients.matchAll()).forEach(T=>{T.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:$.size||i})}),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),$):t._urlExpired?(this.log.warn(`URL expired mid-download, partial cache: ${a} (${d}/${f} chunks stored)`),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s})):(this.log.info(`Progressive download complete: ${a} (${d} chunks stored)`),c.complete=!0,await this.cacheManager.updateMetadata(a,c),(await self.clients.matchAll()).forEach(C=>{C.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,complete:!0})}),this.pendingChunkStorage.delete(a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s}))}_cacheStaticResource(t,e){const a=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;a&&(a.endsWith(".js")||a.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(a))&&(async()=>{try{const s=await caches.open(this.config.staticCache),i=`${y}/cache/static/${a}`,n=a.split(".").pop().toLowerCase(),l=X[n]||"application/octet-stream";await Promise.all([s.put(i,new Response(e.slice(0,e.size,e.type),{headers:{"Content-Type":l}})),this.cacheManager.put(i,e.slice(0,e.size,e.type),l)]),this.log.info("Also cached as static resource:",a,`(${l})`)}catch(s){this.log.warn("Failed to cache static resource:",a,s)}})()}async ensureStaticCacheEntry(t){const e=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;if(!e||!(e.endsWith(".js")||e.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(e)))return;const a=await caches.open(this.config.staticCache),s=`${y}/cache/static/${e}`;if(await a.match(s))return;const n=`${y}/cache/${t.type}/${t.id}`,l=await this.cacheManager.get(n);if(!l)return;const o=await l.blob(),d=e.split(".").pop().toLowerCase(),u=X[d]||"application/octet-stream",f=`${y}/cache/static/${e}`;await Promise.all([a.put(s,new Response(o.slice(0,o.size,o.type),{headers:{"Content-Type":u}})),this.cacheManager.put(f,o.slice(0,o.size,o.type),u)]),this.log.info("Backfilled static cache for:",e,`(${u}, ${o.size} bytes)`)}async handleGetAllFiles(){return{success:!0,files:await this.cacheManager.getAllFiles()}}async handleClearCache(){return this.log.info("Clearing cache"),await this.cacheManager.clear(),{success:!0}}async handleGetProgress(){return{success:!0,progress:this.downloadManager.getProgress()}}}const q="2026-02-24T20:21:48.344Z",N="xibo-media-v1",P="xibo-static-v1",ie=[y+"/",y+"/index.html",y+"/setup.html"],A=new D("SW"),B=ee(A),_=B.chunkSize,oe=B.threshold,ce=B.blobCacheSize,re=B.concurrency;A.info("Loading modular Service Worker:",q);const V=new Z({concurrency:re,chunkSize:_,chunksPerFile:2}),W=new te({cacheName:N,chunkSize:_}),J=new ae(ce),he=new se(V,W,J,{staticCache:P}),le=new ne(V,W,J,{cacheName:N,staticCache:P,chunkSize:_,chunkStorageThreshold:oe});async function ue(h){const t=new URL(h.request.url),e=t.pathname.replace(y+"/ic",""),a=h.request.method;A.info("Interactive Control request:",a,e);let s=null;if(a==="POST"||a==="PUT")try{s=await h.request.text()}catch{}const i=await self.clients.matchAll({type:"window"});if(i.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const n=i[0];try{const l=await new Promise((o,d)=>{const u=new MessageChannel,f=setTimeout(()=>d(new Error("IC timeout")),5e3);u.port1.onmessage=c=>{clearTimeout(f),o(c.data)},n.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:e,search:t.search,body:s},[u.port2])});return new Response(l.body||"",{status:l.status||200,headers:{"Content-Type":l.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(l){return A.error("IC handler error:",l),new Response(JSON.stringify({error:l.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",h=>{A.info("Installing... Version:",q),h.waitUntil(Promise.all([W.init(),caches.open(P).then(t=>(A.info("Caching static files"),t.addAll(ie)))]).then(async()=>{if(A.info("Cache initialized"),self.registration.active)try{const e=await(await caches.open("xibo-sw-version")).match("version");if(e){const a=await e.text();if(a===q){A.info("Same version already active, skipping activation to preserve streams");return}A.info("Version changed:",a,"→",q)}}catch{}return A.info("New version, activating immediately"),self.skipWaiting()}))});self.addEventListener("activate",h=>{A.info("Activating... Version:",q,"| @xiboplayer/cache:",Q),h.waitUntil(caches.keys().then(t=>Promise.all(t.filter(e=>e.startsWith("xibo-")&&e!==N&&e!==P&&e!=="xibo-sw-version").map(e=>(A.info("Deleting old cache:",e),caches.delete(e))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(q)),A.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{A.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(e=>{e.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",h=>{const t=new URL(h.request.url);if(t.pathname.startsWith(y+"/cache/")||t.pathname.startsWith(y+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&h.request.method==="GET"){if(t.pathname.startsWith(y+"/ic/")){h.respondWith(ue(h));return}h.respondWith(he.handleRequest(h))}});self.addEventListener("message",h=>{h.waitUntil(le.handleMessage(h).then(t=>{var e;(e=h.ports[0])==null||e.postMessage(t)}))});A.info("Modular Service Worker ready");
2
2
  //# sourceMappingURL=sw-pwa.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiboplayer/pwa",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Lightweight PWA Xibo Player with RendererLite",
5
5
  "type": "module",
6
6
  "files": [