@xiboplayer/pwa 0.7.21 → 0.7.23

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 (58) hide show
  1. package/dist/assets/__vite-browser-external-DeMPM02e.js +2 -0
  2. package/dist/assets/__vite-browser-external-DeMPM02e.js.map +1 -0
  3. package/dist/assets/chunk-DzMEjpoC.js +1 -0
  4. package/dist/assets/{html2canvas-BAfZNSwU.js → html2canvas-EikzC5d8.js} +2 -2
  5. package/dist/assets/{html2canvas-BAfZNSwU.js.map → html2canvas-EikzC5d8.js.map} +1 -1
  6. package/dist/assets/main-CRdq5ifQ.js +3 -0
  7. package/dist/assets/{main-vwJkNw4Y.js.map → main-CRdq5ifQ.js.map} +1 -1
  8. package/dist/assets/main-DTR2QDcF.js +108 -0
  9. package/dist/assets/main-DTR2QDcF.js.map +1 -0
  10. package/dist/assets/{pdf-Bxz9Nzto.js → pdf-CMz6puSt.js} +1 -1
  11. package/dist/assets/{pdf-Bxz9Nzto.js.map → pdf-CMz6puSt.js.map} +1 -1
  12. package/dist/assets/{setup-B4gZX38p.js → setup-Bw8T9Qq6.js} +2 -2
  13. package/dist/assets/{setup-B4gZX38p.js.map → setup-Bw8T9Qq6.js.map} +1 -1
  14. package/dist/assets/src-A5KHvitf.js +2 -0
  15. package/dist/assets/{src-CROvYSP8.js.map → src-A5KHvitf.js.map} +1 -1
  16. package/dist/assets/{src-DAB0dqGG.js → src-BHsN2u2P.js} +2 -2
  17. package/dist/assets/{src-DAB0dqGG.js.map → src-BHsN2u2P.js.map} +1 -1
  18. package/dist/assets/src-BLUMUwZR.js +1 -0
  19. package/dist/assets/src-BXXcWcHh.js +1 -0
  20. package/dist/assets/src-BxSOopk7.js +1 -0
  21. package/dist/assets/{src-WDu491CE.js → src-BxaX1gGg.js} +2 -2
  22. package/dist/assets/{src-WDu491CE.js.map → src-BxaX1gGg.js.map} +1 -1
  23. package/dist/assets/{src-BtVLiVYZ.js → src-CCAyzQUp.js} +3 -3
  24. package/dist/assets/{src-BtVLiVYZ.js.map → src-CCAyzQUp.js.map} +1 -1
  25. package/dist/assets/src-CWJcD3kA.js +1 -0
  26. package/dist/assets/{src-Cx3tXAAu.js → src-CZ1k5h23.js} +3 -3
  27. package/dist/assets/{src-Cx3tXAAu.js.map → src-CZ1k5h23.js.map} +1 -1
  28. package/dist/assets/src-ClrziKzV.js +16 -0
  29. package/dist/assets/src-ClrziKzV.js.map +1 -0
  30. package/dist/assets/{src-C_Lx4lXp.js → src-CtjjclS4.js} +2 -2
  31. package/dist/assets/{src-C_Lx4lXp.js.map → src-CtjjclS4.js.map} +1 -1
  32. package/dist/assets/src-CuVaZcMo.js +2 -0
  33. package/dist/assets/{src-B_BNICay.js.map → src-CuVaZcMo.js.map} +1 -1
  34. package/dist/assets/src-Cy5OUviT.js +1 -0
  35. package/dist/assets/src-DK5BYonP.js +630 -0
  36. package/dist/assets/src-DK5BYonP.js.map +1 -0
  37. package/dist/assets/src-Dk-W3N33.js +1 -0
  38. package/dist/assets/{src-cUopH0nN.js → src-xPTO7Ts6.js} +3 -3
  39. package/dist/assets/{src-cUopH0nN.js.map → src-xPTO7Ts6.js.map} +1 -1
  40. package/dist/assets/sync-manager-zf1tikPt.js +2 -0
  41. package/dist/assets/sync-manager-zf1tikPt.js.map +1 -0
  42. package/dist/index.html +1 -1
  43. package/dist/setup.html +3 -4
  44. package/dist/sw-pwa.js +2 -2
  45. package/dist/sw-pwa.js.map +1 -1
  46. package/package.json +15 -13
  47. package/dist/assets/chunk-7ZXdHUL4.js +0 -1
  48. package/dist/assets/main-oacre7st.js +0 -108
  49. package/dist/assets/main-oacre7st.js.map +0 -1
  50. package/dist/assets/main-vwJkNw4Y.js +0 -3
  51. package/dist/assets/src-B_BNICay.js +0 -2
  52. package/dist/assets/src-Bjt9ooXK.js +0 -16
  53. package/dist/assets/src-Bjt9ooXK.js.map +0 -1
  54. package/dist/assets/src-CKpVxGpH.js +0 -629
  55. package/dist/assets/src-CKpVxGpH.js.map +0 -1
  56. package/dist/assets/src-CROvYSP8.js +0 -2
  57. package/dist/assets/sync-manager-8Z-qwkod.js +0 -2
  58. package/dist/assets/sync-manager-8Z-qwkod.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import"./modulepreload-polyfill-Cf3xff8G.js";import{i as e}from"./src-BtVLiVYZ.js";import{n as t,r as n}from"./src-Bjt9ooXK.js";var r=`0.7.21`;document.getElementById(`version-footer`).textContent=`xiboplayer v${r}`;var i=document.getElementById(`setup-form`),a=document.getElementById(`error`),o=document.getElementById(`submit-btn`),s=document.getElementById(`phase-unlock`),c=document.getElementById(`phase-setup`),l=document.getElementById(`phase-waiting`),u=document.getElementById(`countdown`),d=document.getElementById(`waiting-display-name`),f=document.getElementById(`btn-back`),p=document.getElementById(`success-flash`),m=e.hardwareKey;document.getElementById(`hw-key-display`).textContent=m,document.getElementById(`hw-key-waiting`).textContent=m;var h=e.cmsUrl||``,g=null,_=null,v=15,y=null;async function b(){if(y)return y;try{let t=new n(e);await t.registerDisplay(),console.log(`[Setup] Using REST transport`),y=t}catch(n){console.log(`[Setup] REST unavailable, using XMDS/SOAP:`,n.message),y=new t(e)}return y}function x(e){s.classList.remove(`active`),c.classList.remove(`active`),l.classList.remove(`active`),e.classList.add(`active`)}function S(e){a.textContent=e,a.style.display=`block`}function C(){a.style.display=`none`}function w(){let e=v;u.textContent=e,clearInterval(_),_=setInterval(()=>{e--,u.textContent=Math.max(0,e),e<=0&&clearInterval(_)},1e3)}async function T(){if(document.getElementById(`cms-url`).value.trim().replace(/\/$/,``)!==h){console.log(`[Setup] CMS URL changed — wiping cached content`);let e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}p.classList.add(`active`),setTimeout(()=>{window.location.href=`/player/index.html`+window.location.search},800)}async function E(){try{let e=await(await b()).registerDisplay();if(console.log(`[Setup] Poll result:`,e.code,e.message),e.code===`READY`){clearInterval(g),clearInterval(_),T();return}w()}catch(e){console.warn(`[Setup] Poll failed:`,e.message),w()}}function D(e){d.textContent=e,x(l),w(),g=setInterval(E,v*1e3)}function O(){clearInterval(g),clearInterval(_),g=null}async function k(t,n){let r=document.getElementById(`api-client-id`).value.trim(),i=document.getElementById(`api-client-secret`).value.trim();if(!r||!i)return!1;try{let t=await fetch(`/api/authorize/access_token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:r,client_secret:i})});if(!t.ok)throw Error(`OAuth2 failed: ${t.status}`);let{access_token:a}=await t.json(),o=await fetch(`/api/display?hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${a}`}});if(!o.ok)throw Error(`Find display failed: ${o.status}`);let s=await o.json();if(!s.length)return console.log(`[Setup] Display not found via API (may not be registered yet)`),!1;let c=s[0];if(c.licensed===1)return console.log(`[Setup] Display already authorized`),!0;let l=await fetch(`/api/display/authorise/${c.displayId}`,{method:`PUT`,headers:{Authorization:`Bearer ${a}`}});if(!l.ok)throw Error(`Authorize failed: ${l.status}`);return console.log(`[Setup] Display auto-authorized via proxy!`),e.data.apiClientId=r,e.data.apiClientSecret=i,!0}catch(e){return console.warn(`[Setup] Auto-authorize failed:`,e.message),!1}}var A=e.isConfigured()&&e.cmsKey,j=new URLSearchParams(window.location.search).has(`unlocked`),M=document.getElementById(`btn-back-player`);A&&!j&&x(s),(A||j)&&(M.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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``));function N(){O(),window.location.href=`/player/index.html`+window.location.search}M.addEventListener(`click`,N),(A||j)&&document.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),N())}),document.getElementById(`unlock-form`).addEventListener(`submit`,t=>{t.preventDefault();let 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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``),x(c)):(n.textContent=`Incorrect CMS key`,n.style.display=`block`)}),!A&&e.isConfigured()&&(document.getElementById(`cms-url`).value=e.cmsUrl,document.getElementById(`cms-key`).value=e.cmsKey,document.getElementById(`display-name`).value=e.displayName,e.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``)),i.addEventListener(`submit`,async t=>{t.preventDefault(),C();let n=document.getElementById(`cms-url`).value.trim().replace(/\/$/,``),r=document.getElementById(`cms-key`).value.trim(),i=document.getElementById(`display-name`).value.trim();try{if(o.textContent=`Saving...`,o.disabled=!0,!(await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cmsUrl:n,cmsKey:r,displayName:i})})).ok)throw Error(`Failed to save config`);let t=window.electronAPI||window.parent?.electronAPI;t?.setConfig&&await t.setConfig({cmsUrl:n,cmsKey:r,displayName:i}),e.data.cmsUrl=n,e.data.cmsKey=r,e.data.displayName=i,e.save(),P(e.hardwareKey),o.textContent=`Connecting...`,y=null;let a=await b();if((await a.registerDisplay()).code===`READY`)T();else{if(o.textContent=`Authorizing...`,await k(n,m)&&(e.save(),await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret})}),t?.setConfig&&await t.setConfig({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret}),(await a.registerDisplay()).code===`READY`)){T();return}D(i)}}catch(e){S(`Connection failed: ${e.message}`),o.textContent=`Connect`,o.disabled=!1}}),f.addEventListener(`click`,()=>{O(),x(c),o.textContent=`Connect`,o.disabled=!1});async function P(e){try{let t=indexedDB.open(`xibo-hw-backup`,1);t.onupgradeneeded=()=>{let e=t.result;e.objectStoreNames.contains(`keys`)||e.createObjectStore(`keys`)},t.onsuccess=()=>{let n=t.result,r=n.transaction(`keys`,`readwrite`);r.objectStore(`keys`).put(e,`hardwareKey`),r.oncomplete=()=>n.close()}}catch(e){console.warn(`[Setup] IndexedDB backup failed:`,e)}}o.disabled=!1,o.textContent=`Connect`,e.isConfigured()&&!A&&(async()=>{try{(await(await b()).registerDisplay()).code===`READY`?window.location.href=`/player/index.html`+window.location.search:D(e.displayName)}catch{console.log(`[Setup] Auto-check failed, showing form`)}})();
2
- //# sourceMappingURL=setup-B4gZX38p.js.map
1
+ import"./modulepreload-polyfill-Cf3xff8G.js";import{l as e}from"./src-CCAyzQUp.js";import{a as t,s as n}from"./src-ClrziKzV.js";var r=`0.7.23`;document.getElementById(`version-footer`).textContent=`xiboplayer v${r}`;var i=document.getElementById(`setup-form`),a=document.getElementById(`error`),o=document.getElementById(`submit-btn`),s=document.getElementById(`phase-unlock`),c=document.getElementById(`phase-setup`),l=document.getElementById(`phase-waiting`),u=document.getElementById(`countdown`),d=document.getElementById(`waiting-display-name`),f=document.getElementById(`btn-back`),p=document.getElementById(`success-flash`),m=e.hardwareKey;document.getElementById(`hw-key-display`).textContent=m,document.getElementById(`hw-key-waiting`).textContent=m;var h=e.cmsUrl||``,g=null,_=null,v=15,y=null;async function b(){if(y)return y;try{let t=new n(e);await t.registerDisplay(),console.log(`[Setup] Using REST transport`),y=t}catch(n){console.log(`[Setup] REST unavailable, using XMDS/SOAP:`,n.message),y=new t(e)}return y}function x(e){s.classList.remove(`active`),c.classList.remove(`active`),l.classList.remove(`active`),e.classList.add(`active`)}function S(e){a.textContent=e,a.style.display=`block`}function C(){a.style.display=`none`}function w(){let e=v;u.textContent=e,clearInterval(_),_=setInterval(()=>{e--,u.textContent=Math.max(0,e),e<=0&&clearInterval(_)},1e3)}async function T(){if(document.getElementById(`cms-url`).value.trim().replace(/\/$/,``)!==h){console.log(`[Setup] CMS URL changed — wiping cached content`);let e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}p.classList.add(`active`),setTimeout(()=>{window.location.href=`/player/index.html`+window.location.search},800)}async function E(){try{let e=await(await b()).registerDisplay();if(console.log(`[Setup] Poll result:`,e.code,e.message),e.code===`READY`){clearInterval(g),clearInterval(_),T();return}w()}catch(e){console.warn(`[Setup] Poll failed:`,e.message),w()}}function D(e){d.textContent=e,x(l),w(),g=setInterval(E,v*1e3)}function O(){clearInterval(g),clearInterval(_),g=null}async function k(t,n){let r=document.getElementById(`api-client-id`).value.trim(),i=document.getElementById(`api-client-secret`).value.trim();if(!r||!i)return!1;try{let t=await fetch(`/api/authorize/access_token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:r,client_secret:i})});if(!t.ok)throw Error(`OAuth2 failed: ${t.status}`);let{access_token:a}=await t.json(),o=await fetch(`/api/display?hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${a}`}});if(!o.ok)throw Error(`Find display failed: ${o.status}`);let s=await o.json();if(!s.length)return console.log(`[Setup] Display not found via API (may not be registered yet)`),!1;let c=s[0];if(c.licensed===1)return console.log(`[Setup] Display already authorized`),!0;let l=await fetch(`/api/display/authorise/${c.displayId}`,{method:`PUT`,headers:{Authorization:`Bearer ${a}`}});if(!l.ok)throw Error(`Authorize failed: ${l.status}`);return console.log(`[Setup] Display auto-authorized via proxy!`),e.data.apiClientId=r,e.data.apiClientSecret=i,!0}catch(e){return console.warn(`[Setup] Auto-authorize failed:`,e.message),!1}}var A=e.isConfigured()&&e.cmsKey,j=new URLSearchParams(window.location.search).has(`unlocked`),M=document.getElementById(`btn-back-player`);A&&!j&&x(s),(A||j)&&(M.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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``));function N(){O(),window.location.href=`/player/index.html`+window.location.search}M.addEventListener(`click`,N),(A||j)&&document.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),N())}),document.getElementById(`unlock-form`).addEventListener(`submit`,t=>{t.preventDefault();let 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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``),x(c)):(n.textContent=`Incorrect CMS key`,n.style.display=`block`)}),!A&&e.isConfigured()&&(document.getElementById(`cms-url`).value=e.cmsUrl,document.getElementById(`cms-key`).value=e.cmsKey,document.getElementById(`display-name`).value=e.displayName,e.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``)),i.addEventListener(`submit`,async t=>{t.preventDefault(),C();let n=document.getElementById(`cms-url`).value.trim().replace(/\/$/,``),r=document.getElementById(`cms-key`).value.trim(),i=document.getElementById(`display-name`).value.trim();try{if(o.textContent=`Saving...`,o.disabled=!0,!(await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cmsUrl:n,cmsKey:r,displayName:i})})).ok)throw Error(`Failed to save config`);let t=window.electronAPI||window.parent?.electronAPI;t?.setConfig&&await t.setConfig({cmsUrl:n,cmsKey:r,displayName:i}),e.data.cmsUrl=n,e.data.cmsKey=r,e.data.displayName=i,e.save(),P(e.hardwareKey),o.textContent=`Connecting...`,y=null;let a=await b();if((await a.registerDisplay()).code===`READY`)T();else{if(o.textContent=`Authorizing...`,await k(n,m)&&(e.save(),await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret})}),t?.setConfig&&await t.setConfig({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret}),(await a.registerDisplay()).code===`READY`)){T();return}D(i)}}catch(e){S(`Connection failed: ${e.message}`),o.textContent=`Connect`,o.disabled=!1}}),f.addEventListener(`click`,()=>{O(),x(c),o.textContent=`Connect`,o.disabled=!1});async function P(e){try{let t=indexedDB.open(`xibo-hw-backup`,1);t.onupgradeneeded=()=>{let e=t.result;e.objectStoreNames.contains(`keys`)||e.createObjectStore(`keys`)},t.onsuccess=()=>{let n=t.result,r=n.transaction(`keys`,`readwrite`);r.objectStore(`keys`).put(e,`hardwareKey`),r.oncomplete=()=>n.close()}}catch(e){console.warn(`[Setup] IndexedDB backup failed:`,e)}}o.disabled=!1,o.textContent=`Connect`,e.isConfigured()&&!A&&(async()=>{try{(await(await b()).registerDisplay()).code===`READY`?window.location.href=`/player/index.html`+window.location.search:D(e.displayName)}catch{console.log(`[Setup] Auto-check failed, showing form`)}})();
2
+ //# sourceMappingURL=setup-Bw8T9Qq6.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"setup-B4gZX38p.js","names":[],"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 = `xiboplayer 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 "],"mappings":"gIAKI,IAAM,EAAA,SACN,SAAS,eAAe,iBAAiB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U,SAAW,IACrB,CAGF,eAAe,EAAkB,EAAK,CACpC,GAAI,CACF,IAAM,EAAM,UAAU,KAAK,iBAAkB,EAAE,CAC/C,EAAI,oBAAwB,CAC1B,IAAM,EAAK,EAAI,OACV,EAAG,iBAAiB,SAAS,OAAO,EACvC,EAAG,kBAAkB,OAAO,EAGhC,EAAI,cAAkB,CACpB,IAAM,EAAK,EAAI,OACT,EAAK,EAAG,YAAY,OAAQ,YAAY,CAC9C,EAAG,YAAY,OAAO,CAAC,IAAI,EAAK,cAAc,CAC9C,EAAG,eAAmB,EAAG,OAAO,QAE3B,EAAG,CACV,QAAQ,KAAK,mCAAoC,EAAE,EAKvD,EAAU,SAAW,GACrB,EAAU,YAAc,UAIpB,EAAO,cAAc,EAAI,CAAC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM,GAAc,EACP,iBAAiB,EAClC,OAAS,QAClB,OAAO,SAAS,KAAO,qBAAuB,OAAO,SAAS,OAG9D,EAAa,EAAO,YAAY,MAExB,CAEV,QAAQ,IAAI,0CAA0C,KAEtD"}
1
+ {"version":3,"file":"setup-Bw8T9Qq6.js","names":[],"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 = `xiboplayer 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 "],"mappings":"gIAKI,IAAM,EAAA,SACN,SAAS,eAAe,iBAAiB,CAAC,YAAc,eAAe,IAGvE,IAAM,EAAO,SAAS,eAAe,aAAa,CAC5C,EA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M,UAAU,KAAK,iBAAkB,EAAE,CAC/C,EAAI,oBAAwB,CAC1B,IAAM,EAAK,EAAI,OACV,EAAG,iBAAiB,SAAS,OAAO,EACvC,EAAG,kBAAkB,OAAO,EAGhC,EAAI,cAAkB,CACpB,IAAM,EAAK,EAAI,OACT,EAAK,EAAG,YAAY,OAAQ,YAAY,CAC9C,EAAG,YAAY,OAAO,CAAC,IAAI,EAAK,cAAc,CAC9C,EAAG,eAAmB,EAAG,OAAO,QAE3B,EAAG,CACV,QAAQ,KAAK,mCAAoC,EAAE,EAKvD,EAAU,SAAW,GACrB,EAAU,YAAc,UAIpB,EAAO,cAAc,EAAI,CAAC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM,GAAc,EACP,iBAAiB,EAClC,OAAS,QAClB,OAAO,SAAS,KAAO,qBAAuB,OAAO,SAAS,OAG9D,EAAa,EAAO,YAAY,MAExB,CAEV,QAAQ,IAAI,0CAA0C,KAEtD"}
@@ -0,0 +1,2 @@
1
+ import{v as e}from"./src-CCAyzQUp.js";var t={name:`@xiboplayer/schedule`,version:`0.7.23`,description:`Complete scheduling solution: campaigns, dayparting, interrupts, and overlays`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./schedule":`./src/schedule.js`,"./interrupts":`./src/interrupts.js`,"./overlays":`./src/overlays.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`},devDependencies:{vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`scheduling`,`dayparting`,`campaigns`,`interrupts`,`overlays`,`shareOfVoice`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/schedule`},homepage:`https://xiboplayer.org`},n=e(`schedule:criteria`),r=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],i={weatherTemp:`temperature`,weatherHumidity:`humidity`,weatherWindSpeed:`windSpeed`,weatherCondition:`condition`,weatherCloudCover:`cloudCover`};function a(e,t,a={},o={}){switch(e){case`dayOfWeek`:return r[t.getDay()];case`dayOfMonth`:return String(t.getDate());case`month`:return String(t.getMonth()+1);case`hour`:return String(t.getHours());case`isoDay`:return String(t.getDay()===0?7:t.getDay());default:if(i[e]){let t=i[e];return o[t]===void 0?(n.debug(`Weather metric "${e}" requested but no weather data available`),null):String(o[t])}return a[e]===void 0?(n.debug(`Unknown metric: ${e}`),null):String(a[e])}}function o(e,t,r,i){if(e===null)return!1;if(i===`number`){let n=parseFloat(e),i=parseFloat(r);if(isNaN(n)||isNaN(i))return!1;switch(t){case`equals`:return n===i;case`notEquals`:return n!==i;case`greaterThan`:return n>i;case`greaterThanOrEquals`:return n>=i;case`lessThan`:return n<i;case`lessThanOrEquals`:return n<=i;default:return!1}}let a=e.toLowerCase(),o=r.toLowerCase();switch(t){case`equals`:return a===o;case`notEquals`:return a!==o;case`contains`:return a.includes(o);case`notContains`:return!a.includes(o);case`startsWith`:return a.startsWith(o);case`endsWith`:return a.endsWith(o);case`in`:return o.split(`,`).map(e=>e.trim().toLowerCase()).includes(a);case`greaterThan`:return a>o;case`lessThan`:return a<o;default:return n.debug(`Unknown condition: ${t}`),!1}}function s(e,t={}){if(!e||e.length===0)return!0;let r=t.now||new Date,i=t.displayProperties||{},s=t.weatherData||{};for(let t of e){let e=a(t.metric,r,i,s);if(!o(e,t.condition,t.value,t.type))return n.debug(`Criteria failed: ${t.metric} ${t.condition} "${t.value}" (actual: "${e}")`),!1}return!0}function c(e){return parseInt(String(e).replace(`.xlf`,``),10)}function l(e,t=null){let n=new DOMParser().parseFromString(e,`text/xml`).querySelector(`layout`);if(!n)return{duration:60,isDynamic:!1};let r=parseInt(n.getAttribute(`duration`)||`0`,10);if(r>0)return{duration:r,isDynamic:!1};let i=0,a=!1;for(let e of n.querySelectorAll(`region`)){let n=e.getAttribute(`type`);if(n===`drawer`)continue;let r=n===`canvas`,o=0;for(let n of e.querySelectorAll(`media`)){let e=parseInt(n.getAttribute(`duration`)||`0`,10),i=parseInt(n.getAttribute(`useDuration`)||`1`,10),s=n.getAttribute(`fileId`)||``,c=t?.get(s),l;c===void 0?e>0&&i!==0?l=e:(l=60,a=!0):l=c,r?o=Math.max(o,l):o+=l}i=Math.max(i,o)}return{duration:i>0?i:60,isDynamic:a}}function u(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function d(e,t,n){if(!t||t===0)return!0;let r=n-36e5,i=e.filter(e=>e>r);if(i.length>=t)return!1;if(i.length>0){let e=36e5/t;if(n-Math.max(...i)<e)return!1}return!0}function f(e,t,n){let r=e.filter(e=>!e.maxPlaysPerHour||e.maxPlaysPerHour===0?!0:d(t.get(e.file)||[],e.maxPlaysPerHour,n));if(r.length===0)return[];let i=Math.max(...r.map(e=>e.priority));return r.filter(e=>e.priority===i).map(e=>e.file)}function p(e,t,n={}){let r=n.from||new Date,i=n.hours||2,a=new Date(r.getTime()+i*36e5);n.currentLayoutStartedAt;let o=n.defaultLayout||null,s=n.durations||null;if(!e||e.length===0)return[];let c=[],l=new Date(r),u=t%e.length;for(;l<a&&c.length<500;){let t=e[u],n=s&&s.get(t.layoutId)||t.duration,r=l.getTime()+n*1e3;c.push({layoutFile:t.layoutId,startTime:new Date(l),endTime:new Date(r),duration:n,isDefault:o?t.layoutId===o:!1}),l=new Date(r),u=(u+1)%e.length}return c}function m(e,t){for(e=Math.abs(Math.round(e)),t=Math.abs(Math.round(t));t;)[e,t]=[t,e%t];return e}function h(e,t){return e===0||t===0?0:Math.abs(Math.round(e)*Math.round(t))/m(e,t)}function g(e){return e.reduce((e,t)=>h(e,t),1)}function _(e,t,n={}){let{defaultLayout:r=null,defaultDuration:i=60}=n;if(e.length===0&&!r)return{queue:[],periodSeconds:0};let a=new Map;for(let t of e)t.duration>0&&a.set(t.file,t.duration);let o=e=>t.get(e)||a.get(e)||i,s=e.filter(e=>e.maxPlaysPerHour>0),c;s.length>0?(c=g(s.map(e=>Math.round(3600/e.maxPlaysPerHour))),c>7200&&(c=7200)):c=e.reduce((e,t)=>e+o(t.file),0)+(r&&!e.some(e=>e.file===r)?o(r):0)||i;let l=[],d=new Map,p=0,m=c*1e3;for(;p<m&&l.length<500;){let t=f(e,d,p);if(t.length===0){if(r){let e=o(r);l.push({layoutId:r,duration:e}),p+=e*1e3}else p+=6e4;continue}for(let n=0;n<t.length&&p<m&&l.length<500;n++){let r=t[n],i=o(r);if(l.push({layoutId:r,duration:i}),d.has(r)||d.set(r,[]),d.get(r).push(p),p+=i*1e3,!u(t,f(e,d,p)))break}}if(l.length===0&&r){let e=o(r);l.push({layoutId:r,duration:e})}return{queue:l,periodSeconds:c}}var v=e(`Schedule`),y=class{constructor(e={}){this.schedule=null,this.playHistory=new Map,this.interruptScheduler=e.interruptScheduler||null,this.displayProperties=e.displayProperties||{},this.weatherData={},this.playerLocation=null,this._layoutMetadata=new Map,this._scheduleQueue=null,this._queuePosition=0,this._queueLayoutSet=null}setSchedule(e){this.schedule=e,this._invalidateQueue()}setWeatherData(e){this.weatherData=e||{}}getDataConnectors(){return this.schedule?.dataConnectors||[]}getDependantsMap(){let e=new Map;if(!this.schedule)return e;let t=this.schedule.dependants||[],n=n=>{let r=c(n.file||n.id),i=[...t,...n.dependants||[]];i.length>0&&e.set(r,i)};if(this.schedule.layouts)for(let e of this.schedule.layouts)n(e);if(this.schedule.campaigns)for(let e of this.schedule.campaigns)for(let t of e.layouts)n(t);return e}isRecurringScheduleActive(e,t){if(!e.recurrenceType)return!0;if(e.recurrenceRange&&t>new Date(e.recurrenceRange))return!1;switch(e.recurrenceType){case`Week`:if(e.recurrenceRepeatsOn){let n=this.getIsoDayOfWeek(t);if(!e.recurrenceRepeatsOn.split(`,`).map(e=>parseInt(e.trim())).includes(n))return!1}return!0;case`Day`:{let n=e.recurrenceDetail||1;if(n>1&&e.fromdt){let r=new Date(e.fromdt),i=t.getTime()-r.getTime(),a=Math.floor(i/864e5);if(a<0||a%n!==0)return!1}return!0}case`Month`:{if(e.recurrenceRepeatsOn){let n=e.recurrenceRepeatsOn.split(`,`).map(e=>parseInt(e.trim())),r=t.getDate();if(!n.includes(r))return!1}let n=e.recurrenceDetail||1;if(n>1&&e.fromdt){let r=new Date(e.fromdt),i=(t.getFullYear()-r.getFullYear())*12+t.getMonth()-r.getMonth();if(i<0||i%n!==0)return!1}return!0}default:return v.debug(`Unsupported recurrence type: ${e.recurrenceType}`),!0}}getIsoDayOfWeek(e){let t=e.getDay();return t===0?7:t}isTimeActive(e,t){let n=e.fromdt?new Date(e.fromdt):null,r=e.todt?new Date(e.todt):null;if(e.recurrenceType===`Week`||e.recurrenceType===`Day`||e.recurrenceType===`Month`){if(n&&r){let e=t.getHours()*3600+t.getMinutes()*60+t.getSeconds(),i=n.getHours()*3600+n.getMinutes()*60+n.getSeconds(),a=r.getHours()*3600+r.getMinutes()*60+r.getSeconds();return i<=a?e>=i&&e<=a:e>=i||e<=a}return!0}return!(n&&t<n||r&&t>r)}getCurrentLayouts(){return this._getLayoutsAt(new Date)}getLayoutsAtTime(e){return this._getLayoutsAt(e,{skipRateLimiting:!0,skipInterrupts:!0,quiet:!0})}getAllLayoutsAtTime(e){if(!this.schedule)return[];let t=e,n=[];if(this.schedule.layouts)for(let e of this.schedule.layouts)this.isRecurringScheduleActive(e,t)&&this.isTimeActive(e,t)&&(e.criteria&&e.criteria.length>0&&!s(e.criteria,{now:t,displayProperties:this.displayProperties,weatherData:this.weatherData})||e.isGeoAware&&e.geoLocation&&!this.isWithinGeoFence(e.geoLocation)||n.push({file:e.file,priority:e.priority||0,maxPlaysPerHour:e.maxPlaysPerHour||0,duration:e.duration||0}));if(this.schedule.campaigns){for(let e of this.schedule.campaigns)if(this.isRecurringScheduleActive(e,t)&&this.isTimeActive(e,t))for(let t of e.layouts)n.push({file:t.file,priority:e.priority||0,maxPlaysPerHour:t.maxPlaysPerHour||0,duration:t.duration||0})}return n}detectConflicts(e={}){let t=e.from||new Date,n=e.hours||24,r=new Date(t.getTime()+n*36e5),i=6e4,a=[],o=null;for(let e=t.getTime();e<r.getTime();e+=i){let t=new Date(e),n=this.getAllLayoutsAtTime(t);if(n.length===0){o&&=(a.push(o),null);continue}let r=Math.max(...n.map(e=>e.priority)),s=n.filter(e=>e.priority<r);if(s.length===0){o&&=(a.push(o),null);continue}let c=n.filter(e=>e.priority===r),l=c.map(e=>e.file).sort().join(`,`),u=s.map(e=>`${e.file}:${e.priority}`).sort().join(`,`);o&&o._winnerKey===l&&o._hiddenKey===u?o.endTime=new Date(e+i):(o&&a.push(o),o={startTime:new Date(e),endTime:new Date(e+i),winner:{file:c[0].file,priority:r},hidden:s.map(e=>({file:e.file,priority:e.priority})),_winnerKey:l,_hiddenKey:u})}o&&a.push(o);for(let e of a)delete e._winnerKey,delete e._hiddenKey;return a}_getLayoutsAt(e,t={}){if(!this.schedule)return[];let{skipRateLimiting:n=!1,skipInterrupts:r=!1,quiet:i=!1}=t,a=i?()=>{}:(...e)=>v.info(...e),o=[];if(this._maxActivePriority=0,this.schedule.campaigns)for(let t of this.schedule.campaigns)this.isRecurringScheduleActive(t,e)&&this.isTimeActive(t,e)&&(this._maxActivePriority=Math.max(this._maxActivePriority,t.priority||0),o.push({type:`campaign`,priority:t.priority,layouts:t.layouts,campaignId:t.id}));if(this.schedule.layouts){for(let t of this.schedule.layouts)if(this.isRecurringScheduleActive(t,e)&&this.isTimeActive(t,e)){if(t.criteria&&t.criteria.length>0&&!s(t.criteria,{now:e,displayProperties:this.displayProperties,weatherData:this.weatherData})){a(`[Schedule] Layout`,t.id,`filtered by criteria`);continue}if(t.isGeoAware&&t.geoLocation&&!this.isWithinGeoFence(t.geoLocation)){a(`[Schedule] Layout`,t.id,`filtered by geofence`);continue}if(this._maxActivePriority=Math.max(this._maxActivePriority,t.priority||0),!n&&!this.canPlayLayout(t.id,t.maxPlaysPerHour)){a(`[Schedule] Layout`,t.id,`filtered by maxPlaysPerHour (limit:`,t.maxPlaysPerHour,`)`);continue}o.push({type:`layout`,priority:t.priority||0,layouts:[t],layoutId:t.id})}}if(o.length===0)return this.schedule.default?[this.schedule.default]:[];let c=Math.max(...o.map(e=>e.priority));a(`[Schedule] Max priority:`,c,`from`,o.length,`active items`);let l=[];for(let e of o)e.priority===c?(a(`[Schedule] Including priority`,e.priority,`layouts:`,e.layouts.map(e=>e.file)),l.push(...e.layouts)):a(`[Schedule] Skipping priority`,e.priority,`< max`,c);this._layoutMetadata.clear();for(let e of l)this._layoutMetadata.set(e.file,{syncEvent:e.syncEvent||!1,shareOfVoice:e.shareOfVoice||0,scheduleid:e.scheduleid,priority:e.priority||0});if(!r&&this.interruptScheduler){let{normalLayouts:e,interruptLayouts:t}=this.interruptScheduler.separateLayouts(l);if(t.length>0){a(`[Schedule] Found`,t.length,`interrupt layouts with shareOfVoice`);let n=this.interruptScheduler.processInterrupts(e,t).map(e=>e.file);return a(`[Schedule] Final layouts (with interrupts):`,n),n}}let u=l.map(e=>e.file);return a(`[Schedule] Final layouts:`,u),u}shouldCheckSchedule(e){return e?Date.now()-e>=6e4:!0}canPlayLayout(e,t){return d(this.playHistory.get(e)||[],t,Date.now())}recordPlay(e){this.playHistory.has(e)||this.playHistory.set(e,[]);let t=this.playHistory.get(e);t.push(Date.now());let n=Date.now()-3600*1e3,r=t.filter(e=>e>n);this.playHistory.set(e,r),v.info(`Recorded play for layout ${e} (${r.length} plays in last hour)`)}isSyncEvent(e){return this._layoutMetadata.get(e)?.syncEvent===!0}getLayoutMetadata(e){return this._layoutMetadata.get(e)||null}getScheduleQueue(e,t={}){let n=this.getAllLayoutsAtTime(new Date),r=n.map(e=>`${e.file}:${e.priority}:${e.maxPlaysPerHour}`).sort().join(`|`);if(this._scheduleQueue&&this._queueLayoutSet===r)return this._scheduleQueue;let i=_(n,e,{defaultLayout:this.schedule?.default||null,defaultDuration:60,dynamicLayouts:t.dynamicLayouts||new Set}),a=this._queueLayoutSet;return this._scheduleQueue=i,this._queueLayoutSet=r,a!==r&&(this._queuePosition=0),i.queue.length>0&&(v.info(`[Schedule] Built queue: ${i.queue.length} entries, period ${i.periodSeconds}s (pos ${this._queuePosition})`),v.info(`[Schedule] Queue: ${i.queue.map(e=>`${e.layoutId}(${e.duration}s)`).join(` → `)}`)),i}popNextFromQueue(e,t={}){let{queue:n}=this.getScheduleQueue(e,t);if(n.length===0)return null;let r=n[this._queuePosition%n.length];return this._queuePosition=(this._queuePosition+1)%n.length,r}getQueuePosition(){return this._queuePosition}rewindQueue(e,t,n={}){let{queue:r}=this.getScheduleQueue(t,n);if(r.length===0)return null;this._queuePosition=(this._queuePosition-e+r.length*e)%r.length;let i=r[this._queuePosition];return this._queuePosition=(this._queuePosition+1)%r.length,i}peekNextInQueue(e,t={}){let{queue:n}=this.getScheduleQueue(e,t);return n.length===0?null:n[this._queuePosition%n.length]}peekAfterNext(e,t={}){let{queue:n}=this.getScheduleQueue(e,t);return n.length<=1?null:n[(this._queuePosition+1)%n.length]}invalidateQueue(){this._invalidateQueue()}_invalidateQueue(){this._scheduleQueue=null}hasSyncEvents(){for(let e of this._layoutMetadata.values())if(e.syncEvent)return!0;return!1}getActiveActions(){if(!this.schedule?.actions)return[];let e=new Date;return this.schedule.actions.filter(t=>this.isTimeActive(t,e))}getCommands(){return this.schedule?.commands||[]}findActionByTrigger(e){return this.getActiveActions().find(t=>t.triggerCode===e)||null}clearPlayHistory(){this.playHistory.clear(),v.info(`Play history cleared`)}setLocation(e,t){this.playerLocation={latitude:e,longitude:t},v.info(`Location set: ${e}, ${t}`)}setDisplayProperties(e){this.displayProperties=e||{}}isWithinGeoFence(e,t=500){if(!this.playerLocation)return v.debug(`No player location, skipping geofence check`),!0;if(!e)return!0;let n=e.split(`,`).map(e=>parseFloat(e.trim()));if(n.length<2||isNaN(n[0])||isNaN(n[1]))return v.warn(`Invalid geoLocation format:`,e),!0;let r=n[0],i=n[1],a=n[2]||t,o=this.haversineDistance(this.playerLocation.latitude,this.playerLocation.longitude,r,i),s=o<=a;return v.info(`Geofence: ${o.toFixed(0)}m from (${r},${i}), radius ${a}m → ${s?`WITHIN`:`OUTSIDE`}`),s}haversineDistance(e,t,n,r){let i=e=>e*Math.PI/180,a=i(n-e),o=i(r-t),s=Math.sin(a/2)**2+Math.cos(i(e))*Math.cos(i(n))*Math.sin(o/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s))}},b=new y,x=e(`schedule:interrupts`),S=class{constructor(){this.interruptCommittedDurations=new Map}isInterrupt(e){return!!(e.shareOfVoice&&e.shareOfVoice>0)}resetCommittedDurations(){this.interruptCommittedDurations.clear(),x.debug(`Reset interrupt committed durations`)}getCommittedDuration(e){return this.interruptCommittedDurations.get(e)||0}addCommittedDuration(e,t){let n=this.getCommittedDuration(e);this.interruptCommittedDurations.set(e,n+t)}isInterruptDurationSatisfied(e){if(!e.shareOfVoice)return!0;let t=e.id||e.file,n=e.shareOfVoice/100*3600;return this.getCommittedDuration(t)>=n}getRequiredSeconds(e){return e.shareOfVoice?e.shareOfVoice/100*3600:0}processInterrupts(e,t){if(!t||t.length===0)return x.debug(`No interrupt layouts, returning normal layouts`),e;if(!e||e.length===0)return x.warn(`No normal layouts available, interrupts will fill entire hour`),this.fillHourWithInterrupts(t);x.info(`Processing ${t.length} interrupt layouts with ${e.length} normal layouts`);for(let e of t){let t=e.id||e.file;this.interruptCommittedDurations.set(t,0)}let n=[],r=0,i=0,a=!1;for(;!a;){if(i>=t.length){i=0;let e=!0;for(let n of t)if(!this.isInterruptDurationSatisfied(n)){e=!1;break}if(e){a=!0;break}}let e=t[i];if(!this.isInterruptDurationSatisfied(e)){let t=e.id||e.file;this.addCommittedDuration(t,e.duration),r+=e.duration,n.push(e)}i++}if(x.debug(`Resolved ${n.length} interrupt plays (${r}s total)`),r>=3600)return x.info(`Interrupts fill entire hour (>= 3600s), no room for normal layouts`),n;let o=3600-r,s=this.fillTimeWithLayouts(e,o);x.debug(`Resolved ${s.length} normal plays (${o}s target)`);let c=this.interleaveLayouts(s,n);return x.info(`Final loop: ${c.length} layouts (${s.length} normal + ${n.length} interrupts)`),c}fillTimeWithLayouts(e,t){let n=[],r=t,i=0;for(;r>0;){i>=e.length&&(i=0);let t=e[i];n.push(t),r-=t.duration,i++}return n}fillHourWithInterrupts(e){return this.fillTimeWithLayouts(e,3600)}interleaveLayouts(e,t){let n=[],r=Math.max(e.length,t.length),i=Math.ceil(1*r/e.length),a=Math.floor(1*r/t.length);x.debug(`Interleaving: pickCount=${r}, normalPick=${i}, interruptPick=${a}`);let o=0,s=0,c=0;for(let l=0;l<r;l++)l%i===0&&(o>=e.length&&(o=0),n.push(e[o]),c+=e[o].duration,o++),l%a===0&&s<t.length&&(n.push(t[s]),c+=t[s].duration,s++);for(;c<3600;)o>=e.length&&(o=0),n.push(e[o]),c+=e[o].duration,o++;return x.debug(`Interleaved ${n.length} layouts, total duration: ${c}s`),n}separateLayouts(e){let t=[],n=[];for(let r of e)this.isInterrupt(r)?n.push(r):t.push(r);return{normalLayouts:t,interruptLayouts:n}}};new S;var C=e(`schedule:overlays`),w=class{constructor(){this.overlays=[],this.displayProperties={},this.scheduleManager=null,C.debug(`OverlayScheduler initialized`)}setScheduleManager(e){this.scheduleManager=e}setDisplayProperties(e){this.displayProperties=e||{}}setOverlays(e){this.overlays=e||[],C.info(`Loaded ${this.overlays.length} overlay(s)`)}getCurrentOverlays(){if(!this.overlays||this.overlays.length===0)return[];let e=new Date,t=[];for(let n of this.overlays){if(!this.isTimeActive(n,e)){C.debug(`Overlay ${n.file} not in time window`);continue}if(n.isGeoAware&&n.geoLocation&&this.scheduleManager&&!this.scheduleManager.isWithinGeoFence(n.geoLocation)){C.debug(`Overlay ${n.file} filtered by geofence`);continue}if(n.criteria&&n.criteria.length>0&&!s(n.criteria,{now:e,displayProperties:this.displayProperties})){C.debug(`Overlay ${n.file} filtered by criteria`);continue}t.push(n)}return t.sort((e,t)=>{let n=e.priority||0;return(t.priority||0)-n}),t.length>0&&C.info(`Active overlays: ${t.length}`),t}isTimeActive(e,t){if(this.scheduleManager){let n={...e};return!n.fromdt&&n.fromDt&&(n.fromdt=n.fromDt),!n.todt&&n.toDt&&(n.todt=n.toDt),this.scheduleManager.isTimeActive(n,t)}let n=e.fromdt||e.fromDt?new Date(e.fromdt||e.fromDt):null,r=e.todt||e.toDt?new Date(e.todt||e.toDt):null;return!(n&&t<n||r&&t>r)}shouldCheckOverlays(e){return e?Date.now()-e>=6e4:!0}getOverlayByFile(e){return this.overlays.find(t=>t.file===e)||null}clear(){this.overlays=[],C.debug(`Cleared all overlays`)}};new w;var T=t.version;export{b as a,l as c,y as i,c as l,w as n,_ as o,S as r,p as s,T as t};
2
+ //# sourceMappingURL=src-A5KHvitf.js.map