[grade=A urn:ump:josd2g7kqv476vux6euigmygdkijya2s4tsbyivtobw5ftzuf6ba] fix(DC-170): revive 19 CSP-blocked inline handlers across the dashboard — audit P0-3

The meta CSP (no unsafe-inline/unsafe-hashes) blocks ALL inline event
handlers; 19 controls were silently dead in every modern browser.

Revived:
- Disk Safety: toolbar button, injected modal Close/Save/Clean Up, and
  the 5 settings sliders (oninput -> input listeners; value labels
  never updated)
- AI chat FAB click; hover scale moved to a #ai-chat-fab:hover rule
- TOTP/login logo broken-image fallbacks: capture-phase error
  delegation + WeakSet + complete/naturalWidth race guard in
  totp-auth.js; updateTotpLogo never resurrects a broken logo
  (6 onerror attrs stripped from index.html + auth-gate.js templates)
- favicon-preview data-URI fallback (same race guard)
- app-selector folder-chip remove buttons (data-remove-folder)
- premium upsells in backup-restore + workflows (data-upgrade-msg) —
  their old onclick also called scrollToSection('license'), a function
  that has never existed anywhere in the codebase; now opens the real
  license UI via window.openLicenseModal (license.js)
- health-check Edit/Delete dispatch the same CustomEvents via
  data-health-action/data-service-id
- smart-arr Test button via data-smart-test

Verified: zero inline handler attributes remain across index.html +
hand-written js (grep); node --check clean x12; status suite 68/68;
dist rebuilt (SW dashcaddy-shell-36d9aa3364, CSP hash unchanged).
r1 grade C (missed sliders + logo onerror) -> r2 grade A:
urn:ump:mptri3qhywc2e47f2ba4qjafhwm3olzvrvt5vphxoyhea3vgt32a /
urn:ump:josd2g7kqv476vux6euigmygdkijya2s4tsbyivtobw5ftzuf6ba
This commit is contained in:
Hermes committed 2026-10-28 00:48:32 -07:00
1 parent 8a6aed546d
commit 94ee76e9de
15 files changed
+439 -348

No files matched your search

+4
View File
@@ -4366,3 +4366,7 @@ button:focus-visible {
@media (max-width: 768px) {
.cal-modal-content { min-width: 0; max-width: 100%; }
}
/* AI chat FAB hover (audit P0-3: moved off inline onmouseover/onmouseout,
which the meta CSP blocks — inline handlers never fired) */
#ai-chat-fab:hover { transform: scale(1.1); }
+71 -71
View File
@@ -1,4 +1,4 @@
(function(c){"use strict";class a{constructor(){this.errors=[],this.maxErrors=50}logError(h,b,g={}){const v={timestamp:new Date().toISOString(),context:h,message:b instanceof Error?b.message:b,stack:b instanceof Error?b.stack:null,metadata:g};this.errors.push(v),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${h}:`,b,g)}recoverFromError(h,b){switch(this.classifyError(h)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",h),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",h),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",h),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",h,{currentStep:b}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(h){const b=h.message||h.toString();return b.includes("element")&&b.includes("not found")?"ELEMENT_NOT_FOUND":b.includes("storage")||b.includes("quota")?"STORAGE_UNAVAILABLE":b.includes("driver")||b.includes("undefined")?"DRIVER_NOT_LOADED":b.includes("invalid")||b.includes("validation")?"INVALID_TOOLTIP":b.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const h={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(b=>{h.byContext[b.context]=(h.byContext[b.context]||0)+1;const g=this.classifyError({message:b.message});h.byType[g]=(h.byType[g]||0)+1}),h}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const h=document.createElement("div");return h.id="onboarding-fallback",h.style.cssText=`
(function(l){"use strict";class a{constructor(){this.errors=[],this.maxErrors=50}logError(h,b,g={}){const v={timestamp:new Date().toISOString(),context:h,message:b instanceof Error?b.message:b,stack:b instanceof Error?b.stack:null,metadata:g};this.errors.push(v),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${h}:`,b,g)}recoverFromError(h,b){switch(this.classifyError(h)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",h),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",h),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",h),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",h,{currentStep:b}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(h){const b=h.message||h.toString();return b.includes("element")&&b.includes("not found")?"ELEMENT_NOT_FOUND":b.includes("storage")||b.includes("quota")?"STORAGE_UNAVAILABLE":b.includes("driver")||b.includes("undefined")?"DRIVER_NOT_LOADED":b.includes("invalid")||b.includes("validation")?"INVALID_TOOLTIP":b.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const h={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(b=>{h.byContext[b.context]=(h.byContext[b.context]||0)+1;const g=this.classifyError({message:b.message});h.byType[g]=(h.byType[g]||0)+1}),h}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const h=document.createElement("div");return h.id="onboarding-fallback",h.style.cssText=`
position: fixed;
bottom: 20px;
right: 20px;
@@ -16,14 +16,14 @@
The interactive tour is unavailable, but you can explore the dashboard freely.
Check the documentation for help getting started.
</p>
`,document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(b){return this.data[b]||null},setItem(b,g){this.data[b]=g},removeItem(b){delete this.data[b]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}c.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window),(function(){try{var a=typeof localStorage<"u"&&localStorage.getItem("dashcaddy-health-settings")||null;if(a){var m=JSON.parse(a);m.statsPollingInterval&&m.statsPollingInterval>=5&&m.statsPollingInterval<=3600&&(window.__DC_STATS_OVERRIDE=m.statsPollingInterval*1e3)}}catch{}})();const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:typeof window<"u"&&window.__DC_STATS_OVERRIDE||5e3,WEATHER:6e5,CALENDAR:3e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const b=await h.json();if(b.tld&&(SITE.tld=b.tld.startsWith(".")?b.tld:"."+b.tld),b.dns&&(SITE.dnsIp=b.dns.ip||"",SITE.dnsPort=b.dns.port||DC.DEFAULTS.DNS_PORT),b.dnsServers&&typeof b.dnsServers=="object")for(const[v,p]of Object.entries(b.dnsServers))v!=="__proto__"&&v!=="constructor"&&v!=="prototype"&&(SITE.dnsServers[v]=p);b.configurationType&&(SITE.configurationType=b.configurationType),b.domain&&(SITE.domain=b.domain),b.defaults&&(SITE.defaults=b.defaults),b.routingMode&&(SITE.routingMode=b.routingMode),SITE.onboardingCompleted=b.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const g=document.getElementById("manage-tokens");g&&(g.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const m=document.getElementById("external-proxy-ip");m&&SITE.dnsIp&&(m.value=SITE.dnsIp,m.placeholder=SITE.dnsIp)})();function buildDomain(c){return c+SITE.tld}function buildServiceUrl(c){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+c:SITE.configurationType==="public"&&SITE.domain?"https://"+c+"."+SITE.domain:"https://"+buildDomain(c)}function getDnsServerAddr(c){const a=SITE.dnsServers[c];return a?`${a.ip}:${a.port}`:buildDomain(c)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[c,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return c;return null}function renderDnsCards(){const c=document.querySelector(".top");if(!c)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const m='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',h=c.firstElementChild;a.forEach(b=>{const g=escapeHtml(b),v=escapeHtml((SITE.dnsServers[b].name||b).toUpperCase()),p=document.createElement("div");p.className="card",p.setAttribute("data-app",b),p.setAttribute("data-status","off"),p.innerHTML=`<span id="${g}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${m}</div><span class="name">${v}</span><span class="spacer"></span><span id="${g}-pill" class="badge off" data-i18n-live-status="binary">OFF</span></div><div class="response-row"><span id="${g}-time" class="response-time">--</span></div><div class="health-row" id="health-${g}"><span id="uptime-${g}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${g}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${g}-restart" class="restart-btn" data-i18n="action.restart">Restart</button><button id="${g}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${g}-open" data-i18n="acLine truncated
`,document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(b){return this.data[b]||null},setItem(b,g){this.data[b]=g},removeItem(b){delete this.data[b]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}l.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window),(function(){try{var a=typeof localStorage<"u"&&localStorage.getItem("dashcaddy-health-settings")||null;if(a){var p=JSON.parse(a);p.statsPollingInterval&&p.statsPollingInterval>=5&&p.statsPollingInterval<=3600&&(window.__DC_STATS_OVERRIDE=p.statsPollingInterval*1e3)}}catch{}})();const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:typeof window<"u"&&window.__DC_STATS_OVERRIDE||5e3,WEATHER:6e5,CALENDAR:3e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const b=await h.json();if(b.tld&&(SITE.tld=b.tld.startsWith(".")?b.tld:"."+b.tld),b.dns&&(SITE.dnsIp=b.dns.ip||"",SITE.dnsPort=b.dns.port||DC.DEFAULTS.DNS_PORT),b.dnsServers&&typeof b.dnsServers=="object")for(const[v,f]of Object.entries(b.dnsServers))v!=="__proto__"&&v!=="constructor"&&v!=="prototype"&&(SITE.dnsServers[v]=f);b.configurationType&&(SITE.configurationType=b.configurationType),b.domain&&(SITE.domain=b.domain),b.defaults&&(SITE.defaults=b.defaults),b.routingMode&&(SITE.routingMode=b.routingMode),SITE.onboardingCompleted=b.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const g=document.getElementById("manage-tokens");g&&(g.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const p=document.getElementById("external-proxy-ip");p&&SITE.dnsIp&&(p.value=SITE.dnsIp,p.placeholder=SITE.dnsIp)})();function buildDomain(l){return l+SITE.tld}function buildServiceUrl(l){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+l:SITE.configurationType==="public"&&SITE.domain?"https://"+l+"."+SITE.domain:"https://"+buildDomain(l)}function getDnsServerAddr(l){const a=SITE.dnsServers[l];return a?`${a.ip}:${a.port}`:buildDomain(l)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[l,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return l;return null}function renderDnsCards(){const l=document.querySelector(".top");if(!l)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const p='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',h=l.firstElementChild;a.forEach(b=>{const g=escapeHtml(b),v=escapeHtml((SITE.dnsServers[b].name||b).toUpperCase()),f=document.createElement("div");f.className="card",f.setAttribute("data-app",b),f.setAttribute("data-status","off"),f.innerHTML=`<span id="${g}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${p}</div><span class="name">${v}</span><span class="spacer"></span><span id="${g}-pill" class="badge off" data-i18n-live-status="binary">OFF</span></div><div class="response-row"><span id="${g}-time" class="response-time">--</span></div><div class="health-row" id="health-${g}"><span id="uptime-${g}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${g}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${g}-restart" class="restart-btn" data-i18n="action.restart">Restart</button><button id="${g}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${g}-open" data-i18n="acLine truncated
position: fixed; top: 20px; right: 20px;
background: ${g.bg}; color: ${g.fg};
padding: 16px 24px; border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,.3);
z-index: 10000; animation: slideIn 0.3s ease-out;
max-width: 400px; white-space: pre-line; font-size: 14px;
`,document.body.appendChild(v),m>0&&setTimeout(()=>v.remove(),m)}function timeAgo(c){const a=Date.now()-new Date(c).getTime();return a<6e4?"just now":a<36e5?Math.floor(a/6e4)+"m ago":a<864e5?Math.floor(a/36e5)+"h ago":Math.floor(a/864e5)+"d ago"}function safeGet(c,a=null){try{const m=localStorage.getItem(c);return m!==null?m:a}catch{return a}}function safeSet(c,a){try{localStorage.setItem(c,a)}catch{}}function safeRemove(c){try{localStorage.removeItem(c)}catch{}}function safeSessionGet(c,a=null){try{const m=sessionStorage.getItem(c);return m!==null?m:a}catch{return a}}function safeSessionSet(c,a){try{sessionStorage.setItem(c,a)}catch{}}function safeGetJSON(c,a=null){try{const m=localStorage.getItem(c);return m?JSON.parse(m):a}catch{return a}}function escapeHtml(c){return String(c??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(c,a){document.getElementById(c)||document.body.insertAdjacentHTML("beforeend",a)}const DC_BUS={_handlers:{},on(c,a){var m;((m=this._handlers)[c]||(m[c]=[])).push(a)},off(c,a){this._handlers[c]=this._handlers[c]?.filter(m=>m!==a)},emit(c,a){this._handlers[c]?.forEach(m=>m(a))}},AppState={_apps:[],getApps(){return this._apps},setApps(c){this._apps=c,window.APPS=c,DC_BUS.emit("apps:changed",c)},findApp(c){return this._apps.find(a=>a.id===c)},addApp(c){this._apps.push(c),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(c){const a=this._apps.findIndex(m=>m.id===c);return a>-1&&(this._apps.splice(a,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),a>-1},updateApp(c,a){const m=this._apps.find(h=>h.id===c);if(m){for(const[h,b]of Object.entries(a))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(m[h]=b);DC_BUS.emit("apps:changed",this._apps)}return m}};(function(){function c(){const h=document.createElement("div");return h.className="skeleton-card",h.innerHTML='<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px"><div class="skeleton-bar" style="width:48px;height:48px;border-radius:8px;flex-shrink:0"></div><div style="flex:1"><div class="skeleton-bar" style="width:60%;height:14px;margin-bottom:6px"></div><div class="skeleton-bar" style="width:35%;height:10px"></div></div><div class="skeleton-bar" style="width:42px;height:22px;border-radius:11px"></div></div><div class="skeleton-bar" style="width:45%;height:12px;margin-bottom:10px"></div><div style="display:flex;gap:8px;margin-top:auto"><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div></div>',h}function a(h){const b=document.getElementById("cards");if(!(!b||b.querySelector(".card"))){h=h||6;for(let g=0;g<h;g++){const v=c();b.appendChild(v),setTimeout(function(){v.classList.add("loaded")},g*60)}}}function m(){const h=document.getElementById("cards");if(h){var b=h.querySelectorAll(".skeleton-card");b.length&&(b.forEach(function(g,v){setTimeout(function(){g.style.opacity="0",g.style.transform="translateY(-10px)"},v*25)}),setTimeout(function(){b.forEach(function(g){g.parentNode&&g.remove()})},b.length*25+300))}}window.SkeletonLoader={show:a,hide:m}})(),(function(){var c="theme",a="user-themes",m="custom-theme",h=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],b=h.slice(),g=["bg","fg","muted","fg-muted","card-base","card-bg","border","hover","card-hover","base","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","success","error","warning","accent","accent-strong"],v=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],p=["fg-muted","hover","card-hover","base","success","error","warning"],d={dark:{bg:"#0b0f1a",fg:"#e8ecf5",muted:"#9aa6bf","fg-muted":"#6b7a94","card-base":"#121826","card-bg":"#121826",border:"#263552",hover:"#1a2235","card-hover":"#161e2e",base:"#151c2b","ok-bg":"#0c2430","ok-fg":"#7ef2ff","bad-bg":"#2a121a","bad-fg":"#ff9aa3","dot-ok":"#35d1ff","dot-bad":"#ff5f7a",uptime:"#35d1ff",success:"#4caf50",error:"#e74c3c",warning:"#f39c12",accent:"#8FD6FF","accent-strong":"#1F7BFF"},light:{bg:"#f6f7fb",fg:"#0f1115",muted:"#5f6b7a","fg-muted":"#8993a4","card-base":"#ffffff","card-bg":"#ffffff",border:"#e2e7ef",hover:"#eef1f6","card-hover":"#f5f6fa",base:"#ebeef3","ok-bg":"#eafff1","ok-fg":"#0a7c3a","bad-bg":"#ffefef","bad-fg":"#b00020","dot-ok":"#0fb15a","dot-bad":"#d93b3b",uptime:"#0fb15a",success:"#0a7c3a",error:"#b00020",warning:"#d68a00",accent:"#4a90d9","accent-strong":"#2563eb",lightBg:!0},blue:{bg:"#1908AC",fg:"#e8f1ff",muted:"#d6e2ff","fg-muted":"#9eafdb","card-base":"#0d1533","card-bg":"#0d1533",border:"#1c2d6a",hover:"#141f4a","card-hover":"#111a3e",base:"#0f1840","ok-bg":"#162040","ok-fg":"#edffff","bad-bg":"#0a0e24","bad-fg":"#ffb3c0","dot-ok":"#c7e5ff","dot-bad":"#ffd6dc",uptime:"#7ec8ff",success:"#7ec8ff",error:"#ffb3c0", Line truncated
`,document.body.appendChild(v),p>0&&setTimeout(()=>v.remove(),p)}function timeAgo(l){const a=Date.now()-new Date(l).getTime();return a<6e4?"just now":a<36e5?Math.floor(a/6e4)+"m ago":a<864e5?Math.floor(a/36e5)+"h ago":Math.floor(a/864e5)+"d ago"}function safeGet(l,a=null){try{const p=localStorage.getItem(l);return p!==null?p:a}catch{return a}}function safeSet(l,a){try{localStorage.setItem(l,a)}catch{}}function safeRemove(l){try{localStorage.removeItem(l)}catch{}}function safeSessionGet(l,a=null){try{const p=sessionStorage.getItem(l);return p!==null?p:a}catch{return a}}function safeSessionSet(l,a){try{sessionStorage.setItem(l,a)}catch{}}function safeGetJSON(l,a=null){try{const p=localStorage.getItem(l);return p?JSON.parse(p):a}catch{return a}}function escapeHtml(l){return String(l??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(l,a){document.getElementById(l)||document.body.insertAdjacentHTML("beforeend",a)}const DC_BUS={_handlers:{},on(l,a){var p;((p=this._handlers)[l]||(p[l]=[])).push(a)},off(l,a){this._handlers[l]=this._handlers[l]?.filter(p=>p!==a)},emit(l,a){this._handlers[l]?.forEach(p=>p(a))}},AppState={_apps:[],getApps(){return this._apps},setApps(l){this._apps=l,window.APPS=l,DC_BUS.emit("apps:changed",l)},findApp(l){return this._apps.find(a=>a.id===l)},addApp(l){this._apps.push(l),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(l){const a=this._apps.findIndex(p=>p.id===l);return a>-1&&(this._apps.splice(a,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),a>-1},updateApp(l,a){const p=this._apps.find(h=>h.id===l);if(p){for(const[h,b]of Object.entries(a))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(p[h]=b);DC_BUS.emit("apps:changed",this._apps)}return p}};(function(){function l(){const h=document.createElement("div");return h.className="skeleton-card",h.innerHTML='<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px"><div class="skeleton-bar" style="width:48px;height:48px;border-radius:8px;flex-shrink:0"></div><div style="flex:1"><div class="skeleton-bar" style="width:60%;height:14px;margin-bottom:6px"></div><div class="skeleton-bar" style="width:35%;height:10px"></div></div><div class="skeleton-bar" style="width:42px;height:22px;border-radius:11px"></div></div><div class="skeleton-bar" style="width:45%;height:12px;margin-bottom:10px"></div><div style="display:flex;gap:8px;margin-top:auto"><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div></div>',h}function a(h){const b=document.getElementById("cards");if(!(!b||b.querySelector(".card"))){h=h||6;for(let g=0;g<h;g++){const v=l();b.appendChild(v),setTimeout(function(){v.classList.add("loaded")},g*60)}}}function p(){const h=document.getElementById("cards");if(h){var b=h.querySelectorAll(".skeleton-card");b.length&&(b.forEach(function(g,v){setTimeout(function(){g.style.opacity="0",g.style.transform="translateY(-10px)"},v*25)}),setTimeout(function(){b.forEach(function(g){g.parentNode&&g.remove()})},b.length*25+300))}}window.SkeletonLoader={show:a,hide:p}})(),(function(){var l="theme",a="user-themes",p="custom-theme",h=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],b=h.slice(),g=["bg","fg","muted","fg-muted","card-base","card-bg","border","hover","card-hover","base","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","success","error","warning","accent","accent-strong"],v=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],f=["fg-muted","hover","card-hover","base","success","error","warning"],d={dark:{bg:"#0b0f1a",fg:"#e8ecf5",muted:"#9aa6bf","fg-muted":"#6b7a94","card-base":"#121826","card-bg":"#121826",border:"#263552",hover:"#1a2235","card-hover":"#161e2e",base:"#151c2b","ok-bg":"#0c2430","ok-fg":"#7ef2ff","bad-bg":"#2a121a","bad-fg":"#ff9aa3","dot-ok":"#35d1ff","dot-bad":"#ff5f7a",uptime:"#35d1ff",success:"#4caf50",error:"#e74c3c",warning:"#f39c12",accent:"#8FD6FF","accent-strong":"#1F7BFF"},light:{bg:"#f6f7fb",fg:"#0f1115",muted:"#5f6b7a","fg-muted":"#8993a4","card-base":"#ffffff","card-bg":"#ffffff",border:"#e2e7ef",hover:"#eef1f6","card-hover":"#f5f6fa",base:"#ebeef3","ok-bg":"#eafff1","ok-fg":"#0a7c3a","bad-bg":"#ffefef","bad-fg":"#b00020","dot-ok":"#0fb15a","dot-bad":"#d93b3b",uptime:"#0fb15a",success:"#0a7c3a",error:"#b00020",warning:"#d68a00",accent:"#4a90d9","accent-strong":"#2563eb",lightBg:!0},blue:{bg:"#1908AC",fg:"#e8f1ff",muted:"#d6e2ff","fg-muted":"#9eafdb","card-base":"#0d1533","card-bg":"#0d1533",border:"#1c2d6a",hover:"#141f4a","card-hover":"#111a3e",base:"#0f1840","ok-bg":"#162040","ok-fg":"#edffff","bad-bg":"#0a0e24","bad-fg":"#ffb3c0","dot-ok":"#c7e5ff","dot-bad":"#ffd6dc",uptime:"#7ec8ff",success:"#7ec8ff",error:"#ffb3c0", Line truncated
background:
radial-gradient(1200px 800px at 10% -10%, rgba(`+C.r+","+C.g+","+C.b+`, .08), transparent 60%),
radial-gradient(1000px 700px at 110% 10%, rgba(`+C.r+","+C.g+","+C.b+`, .05), transparent 55%),
@@ -35,7 +35,7 @@
radial-gradient(1000px 700px at 110% -10%, rgba(`+C.r+","+C.g+","+C.b+`, .07), transparent 55%),
var(--bg);
}
`}function o(x,B){var A=B.lightBg||B.bg&&s(B.bg)>.4;return A?":root."+x+` button:hover {
`}function n(x,B){var A=B.lightBg||B.bg&&s(B.bg)>.4;return A?":root."+x+` button:hover {
background: color-mix(in srgb, var(--accent-strong) 12%, white 88%);
border-color: rgba(0, 0, 0, .15);
box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8);
@@ -44,22 +44,22 @@
background: color-mix(in srgb, var(--accent) 18%, transparent);
border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
}
`}function u(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function n(){g.forEach(function(x){document.documentElement.style.removeProperty("--"+x)})}function i(x,B){var A=x.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");A||(A="custom"),h.indexOf(A)!==-1&&(A=A+"-custom");for(var E=safeGetJSON(a,{}),C=A,T=2;E[A]&&A!==B;)A=C+"-"+T++;return A}function l(x){var B=document.getElementById("user-theme-styles");B&&B.remove(),b.length=h.length,Object.keys(d).forEach(function($){h.indexOf($)===-1&&delete d[$]});var A=x||safeGetJSON(a,{}),E=Object.keys(A);if(E=E.filter(function($){return h.indexOf($)===-1}),!!E.length){var C="";E.forEach(function($){var I=A[$];b.indexOf($)===-1&&b.push($);var P={};g.forEach(function(O){I[O]&&(P[O]=I[O])}),P["card-bg"]=I["card-base"]||I.bg,I.lightBg&&(P.lightBg=!0);var D=t(P);p.forEach(function(O){!P[O]&&D[O]&&(P[O]=D[O])}),d[$]=P,C+=":root."+$+` {
`}function u(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function o(){g.forEach(function(x){document.documentElement.style.removeProperty("--"+x)})}function r(x,B){var A=x.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");A||(A="custom"),h.indexOf(A)!==-1&&(A=A+"-custom");for(var E=safeGetJSON(a,{}),C=A,T=2;E[A]&&A!==B;)A=C+"-"+T++;return A}function c(x){var B=document.getElementById("user-theme-styles");B&&B.remove(),b.length=h.length,Object.keys(d).forEach(function($){h.indexOf($)===-1&&delete d[$]});var A=x||safeGetJSON(a,{}),E=Object.keys(A);if(E=E.filter(function($){return h.indexOf($)===-1}),!!E.length){var C="";E.forEach(function($){var I=A[$];b.indexOf($)===-1&&b.push($);var P={};g.forEach(function(O){I[O]&&(P[O]=I[O])}),P["card-bg"]=I["card-base"]||I.bg,I.lightBg&&(P.lightBg=!0);var D=t(P);f.forEach(function(O){!P[O]&&D[O]&&(P[O]=D[O])}),d[$]=P,C+=":root."+$+` {
`,g.forEach(function(O){P[O]&&(C+=" --"+O+": "+P[O]+`;
`)}),C+=`}
`,C+=e($,P),C+=o($,P)});var T=document.createElement("style");T.id="user-theme-styles",T.textContent=C,document.head.appendChild(T)}}function y(){secureFetch("/api/v1/themes").then(function(x){return x.json()}).then(function(x){if(!(!x.success||!x.themes)){var B=x.themes,A=safeGetJSON(a,{});if(JSON.stringify(B)!==JSON.stringify(A)){safeSet(a,JSON.stringify(B)),l(B);var E=safeGet(c);E&&b.indexOf(E)!==-1&&k(E)}}}).catch(function(){})}function S(){var x=safeGetJSON(m);if(x){var B=x.name||"Custom",A=i(B),E={name:B};g.forEach(function($){x[$]&&(E[$]=x[$])});var C=safeGetJSON(a,{});C[A]=E,safeSet(a,JSON.stringify(C)),safeGet(c)==="custom"&&safeSet(c,A),safeRemove(m);var T={};g.forEach(function($){E[$]&&(T[$]=E[$])}),fetch("/api/v1/themes/"+A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:T})}).catch(function(){})}}function k(x){document.documentElement.classList.add("theme-transitioning"),b.forEach(function(C){C!=="dark"&&document.documentElement.classList.remove(C)}),n(),x!=="dark"&&document.documentElement.classList.add(x),safeSet(c,x);var B=d[x],A=document.querySelector('meta[name="theme-color"]');A&&B&&A.setAttribute("content",B.bg);var E=B&&B.lightBg;!E&&B&&B.bg&&(E=s(B.bg)>.4),E?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}S(),l();var L=safeGet(c);L==="red"&&(L="black",safeSet(c,"black")),L&&L!=="dark"&&b.indexOf(L)===-1&&(L=null),k(L||u()),y(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(x){safeGet(c)||k(x.matches?"dark":"light")}),window.THEMES=b,window.BUILTIN_THEMES=h,window.THEME_COLORS=d,window.THEME_PROPS=g,window.BASE_PROPS=v,window.DERIVED_PROPS=p,window.USER_THEMES_KEY=a,window.applyTheme=k,window.clearCustomProperties=n,window.injectUserThemeStyles=l,window.syncThemesFromServer=y,window.slugifyThemeName=i,window.getActiveTheme=function(){return safeGet(c)||u()},window.deriveExtendedColors=t,window.hexToRgb=r,window.rgbToHex=f,window.blendColors=w})(),(function(){let c=null;async function a(){if(c)return c;try{const w=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!w.ok)throw new Error(`methods HTTP ${w.status}`);const s=await w.json();return c=Array.isArray(s.providers)?s.providers:[],c}catch(w){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",w),[]}}function m(w){const s=document.getElementById("totp-overlay");if(!s)return;const t=s.querySelector(".totp-card");if(!t)return;const e=t.innerHTML;t.dataset.originalBody||(t.dataset.originalBody=e);const o=w.map(u=>{const n=u.config&&(u.config.label||u.name)||u.name;return`<button class="provider-btn" data-provider="${u.name}"
`,C+=e($,P),C+=n($,P)});var T=document.createElement("style");T.id="user-theme-styles",T.textContent=C,document.head.appendChild(T)}}function y(){secureFetch("/api/v1/themes").then(function(x){return x.json()}).then(function(x){if(!(!x.success||!x.themes)){var B=x.themes,A=safeGetJSON(a,{});if(JSON.stringify(B)!==JSON.stringify(A)){safeSet(a,JSON.stringify(B)),c(B);var E=safeGet(l);E&&b.indexOf(E)!==-1&&k(E)}}}).catch(function(){})}function S(){var x=safeGetJSON(p);if(x){var B=x.name||"Custom",A=r(B),E={name:B};g.forEach(function($){x[$]&&(E[$]=x[$])});var C=safeGetJSON(a,{});C[A]=E,safeSet(a,JSON.stringify(C)),safeGet(l)==="custom"&&safeSet(l,A),safeRemove(p);var T={};g.forEach(function($){E[$]&&(T[$]=E[$])}),fetch("/api/v1/themes/"+A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:T})}).catch(function(){})}}function k(x){document.documentElement.classList.add("theme-transitioning"),b.forEach(function(C){C!=="dark"&&document.documentElement.classList.remove(C)}),o(),x!=="dark"&&document.documentElement.classList.add(x),safeSet(l,x);var B=d[x],A=document.querySelector('meta[name="theme-color"]');A&&B&&A.setAttribute("content",B.bg);var E=B&&B.lightBg;!E&&B&&B.bg&&(E=s(B.bg)>.4),E?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}S(),c();var L=safeGet(l);L==="red"&&(L="black",safeSet(l,"black")),L&&L!=="dark"&&b.indexOf(L)===-1&&(L=null),k(L||u()),y(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(x){safeGet(l)||k(x.matches?"dark":"light")}),window.THEMES=b,window.BUILTIN_THEMES=h,window.THEME_COLORS=d,window.THEME_PROPS=g,window.BASE_PROPS=v,window.DERIVED_PROPS=f,window.USER_THEMES_KEY=a,window.applyTheme=k,window.clearCustomProperties=o,window.injectUserThemeStyles=c,window.syncThemesFromServer=y,window.slugifyThemeName=r,window.getActiveTheme=function(){return safeGet(l)||u()},window.deriveExtendedColors=t,window.hexToRgb=i,window.rgbToHex=m,window.blendColors=w})(),(function(){let l=null;async function a(){if(l)return l;try{const w=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!w.ok)throw new Error(`methods HTTP ${w.status}`);const s=await w.json();return l=Array.isArray(s.providers)?s.providers:[],l}catch(w){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",w),[]}}function p(w){const s=document.getElementById("totp-overlay");if(!s)return;const t=s.querySelector(".totp-card");if(!t)return;const e=t.innerHTML;t.dataset.originalBody||(t.dataset.originalBody=e);const n=w.map(u=>{const o=u.config&&(u.config.label||u.name)||u.name;return`<button class="provider-btn" data-provider="${u.name}"
style="margin: 6px 4px; padding: 10px 16px; background: var(--accent); color: white; border: 0; border-radius: 6px; cursor: pointer; font-size: 0.95rem;">
Sign in with ${n}
Sign in with ${o}
</button>`}).join(`
`);t.innerHTML=`
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy">
<p class="subtitle">Choose how to sign in</p>
<div id="auth-gate-providers" style="margin: 14px 0 10px;">${o}</div>
<div id="auth-gate-providers" style="margin: 14px 0 10px;">${n}</div>
<div id="auth-gate-message" style="margin-top: 8px; color: var(--muted); font-size: 0.8rem;"></div>
`,s.classList.add("show"),t.querySelectorAll(".provider-btn").forEach(u=>{u.addEventListener("click",()=>{const n=u.dataset.provider,i=w.find(l=>l.name===n);b(i)})})}function h(){const w=document.getElementById("totp-overlay");if(!w)return;const s=w.querySelector(".totp-card");!s||!s.dataset.originalBody||(s.innerHTML=s.dataset.originalBody,window.location.reload())}function b(w){const s=document.getElementById("totp-overlay");if(!s)return;const t=s.querySelector(".totp-card");if(t){if(w.name==="totp"){window.location.reload();return}if(w.name==="email"){t.innerHTML=`
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
`,s.classList.add("show"),t.querySelectorAll(".provider-btn").forEach(u=>{u.addEventListener("click",()=>{const o=u.dataset.provider,r=w.find(c=>c.name===o);b(r)})})}function h(){const w=document.getElementById("totp-overlay");if(!w)return;const s=w.querySelector(".totp-card");!s||!s.dataset.originalBody||(s.innerHTML=s.dataset.originalBody,window.location.reload())}function b(w){const s=document.getElementById("totp-overlay");if(!s)return;const t=s.querySelector(".totp-card");if(t){if(w.name==="totp"){window.location.reload();return}if(w.name==="email"){t.innerHTML=`
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy">
<p class="subtitle">Sign in with email</p>
<p style="margin: 6px 0 14px; font-size: 0.85rem; color: var(--muted);">
We'll email you a one-time sign-in link.
@@ -75,13 +75,13 @@
<div style="margin-top: 16px;">
<a href="#" id="auth-gate-back" style="color: var(--muted); font-size: 0.8rem;">\u2190 Back</a>
</div>
`,s.classList.add("show");const e=t.querySelector("#auth-gate-email-input"),o=t.querySelector("#auth-gate-email-submit"),u=t.querySelector("#auth-gate-email-status"),n=t.querySelector("#auth-gate-back");o.addEventListener("click",async()=>{const i=(e.value||"").trim();if(!i||!i.includes("@")){u.textContent="Enter a valid email address.",u.style.color="var(--error, #d33)";return}o.disabled=!0,u.textContent="Sending\u2026",u.style.color="";try{const y=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:i})})).json();if(y.success){const S=y.deliveredVia||"email",k=y.maskedEmail||i;S==="dev-console"?u.innerHTML=`
`,s.classList.add("show");const e=t.querySelector("#auth-gate-email-input"),n=t.querySelector("#auth-gate-email-submit"),u=t.querySelector("#auth-gate-email-status"),o=t.querySelector("#auth-gate-back");n.addEventListener("click",async()=>{const r=(e.value||"").trim();if(!r||!r.includes("@")){u.textContent="Enter a valid email address.",u.style.color="var(--error, #d33)";return}n.disabled=!0,u.textContent="Sending\u2026",u.style.color="";try{const y=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:r})})).json();if(y.success){const S=y.deliveredVia||"email",k=y.maskedEmail||r;S==="dev-console"?u.innerHTML=`
Check the server logs for your one-time link.
(Dev mode: no SMTP configured. In production this would email <strong>${k}</strong>.)`:u.innerHTML=`Sign-in link sent to <strong>${k}</strong>.
Check your inbox (and spam folder).`,u.style.color="var(--success, #2a7)"}else u.textContent=y.error||"Could not send link.",u.style.color="var(--error, #d33)",o.disabled=!1}catch{u.textContent="Connection error. Try again.",u.style.color="var(--error, #d33)",o.disabled=!1}}),e.addEventListener("keydown",i=>{i.key==="Enter"&&o.click()}),n.addEventListener("click",i=>{i.preventDefault(),m(providers)});return}console.warn("[auth-gate] unknown provider",w.name),window.location.reload()}}async function g(){if(!document.getElementById("totp-overlay"))return;const s=await a();if(s.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(s.length===1&&s[0].name==="totp"){v(s[0]);return}m(s)}function v(w){const s=c&&c.find(u=>u.name==="email");if(!s){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const t=document.getElementById("totp-overlay"),e=t.querySelector(".totp-card");if(!e)return;if(e.dataset.originalBody||(e.dataset.originalBody=e.innerHTML),!e.querySelector("#auth-gate-email-alt")){const u=document.createElement("div");u.id="auth-gate-email-alt",u.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",u.innerHTML=`<a href="#" id="auth-gate-email-alt-link"
Check your inbox (and spam folder).`,u.style.color="var(--success, #2a7)"}else u.textContent=y.error||"Could not send link.",u.style.color="var(--error, #d33)",n.disabled=!1}catch{u.textContent="Connection error. Try again.",u.style.color="var(--error, #d33)",n.disabled=!1}}),e.addEventListener("keydown",r=>{r.key==="Enter"&&n.click()}),o.addEventListener("click",r=>{r.preventDefault(),p(providers)});return}console.warn("[auth-gate] unknown provider",w.name),window.location.reload()}}async function g(){if(!document.getElementById("totp-overlay"))return;const s=await a();if(s.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(s.length===1&&s[0].name==="totp"){v(s[0]);return}p(s)}function v(w){const s=l&&l.find(u=>u.name==="email");if(!s){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const t=document.getElementById("totp-overlay"),e=t.querySelector(".totp-card");if(!e)return;if(e.dataset.originalBody||(e.dataset.originalBody=e.innerHTML),!e.querySelector("#auth-gate-email-alt")){const u=document.createElement("div");u.id="auth-gate-email-alt",u.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",u.innerHTML=`<a href="#" id="auth-gate-email-alt-link"
style="color: var(--accent); text-decoration: none;">
Or sign in with email instead \u2192
</a>`,e.appendChild(u),u.querySelector("#auth-gate-email-alt-link").addEventListener("click",n=>{n.preventDefault(),b(s)})}t.classList.add("show")}window.__dc_049_handled=!0;function p(w){try{const s=new URL(w,window.location.origin);if(!["http:","https:"].includes(s.protocol))return!1;if(s.origin===window.location.origin)return!0;if(s.protocol!=="https:")return!1;const t=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return s.hostname===t.slice(1)||s.hostname.endsWith(t)}catch{return!1}}function d(w,s){const t=new URL(w,window.location.origin);if(t.origin===window.location.origin)return t.toString();const e=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,o=t.hostname===e.slice(1)||t.hostname.endsWith(e);if(t.protocol!=="https:"||!o||!s)return null;const u=`${t.pathname}${t.search}${t.hash}`;return t.pathname="/dashcaddy-sso",t.search="",t.hash="",t.searchParams.set("token",s),t.searchParams.set("return",u),t.toString()}async function r(w){if(!w||!p(w))return!1;try{const s=new URL(w,window.location.origin),t=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,e=s.hostname.slice(0,-t.length);if(!/^[a-z0-9][a-z0-9-]*$/.test(e))return!1;const o=await fetch(`/api/v1/auth/sso-handoff?serviceId=${encodeURIComponent(e)}`,{credentials:"include",cache:"no-store"});if(!o.ok)return!1;const u=await o.json(),n=u.success&&d(w,u.ssoToken);if(!n)return!1;try{sessionStorage.removeItem("totp_redirect")}catch{}return window.location.replace(n),!0}catch{return!1}}const f=new URLSearchParams(window.location.search);if(f.get("auth")==="required"){const w=f.get("return");if(w&&p(w))try{sessionStorage.setItem("totp_redirect",w)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(async()=>{await r(w)||await g()},0)}window._showAuthGate=g,window._authGateMethods=a})(),(function(){function c(){const p=document.querySelector(".totp-card");if(!p)return;const r=getComputedStyle(p).backgroundColor.match(/\d+/g);if(!r)return;const f=(.299*+r[0]+.587*+r[1]+.114*+r[2])/255,w=p.querySelector(".totp-logo-dark"),s=p.querySelector(".totp-logo-light");w&&(w.style.display=f>.5?"none":""),s&&(s.style.display=f>.5?"":"none")}function a(){const p=document.getElementById("totp-overlay");if(p){p.classList.add("show"),setTimeout(c,50);const d=p.querySelector(".totp-digits input");d&&setTimeout(()=>d.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function m(){const p=document.getElementById("totp-overlay");p&&p.classList.remove("show")}function h(p,d){const r=new URL(p,window.location.origin);if(r.origin===window.location.origin)return r.toString();const f=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,w=r.hostname===f.slice(1)||r.hostname.endsWith(f);if(r.protocol!=="https:"||!w)return null;if(!d)return r.toString();const s=`${r.pathname}${r.search}${r.hash}`;return r.pathname="/dashcaddy-sso",r.search="",r.hash="",r.searchParams.set("token",d),r.searchParams.set("return",s),r.toString()}const b=document.getElementById("totp-digits");if(b){const p=b.querySelectorAll("input");p.forEach((d,r)=>{d.addEventListener("input",f=>{const w=f.target.value.replace(/\D/g,"");f.target.value=w.slice(0,1),w&&r<p.length-1&&p[r+1].focus();const s=Array.from(p).map(t=>t.value).join("");s.length===6&&g(s)}),d.addEventListener("keydown",f=>{f.key==="Backspace"&&!f.target.value&&r>0&&(p[r-1].focus(),p[r-1].value="")}),d.addEventListener("paste",f=>{f.preventDefault();const w=(f.clipboardData.getData("text")||"").replace(/\D/g,"");w.length>=6&&(p.forEach((s,t)=>{s.value=w[t]||""}),p[5].focus(),g(w.slice(0,6)))})})}async function g(p){const d=document.getElementById("totp-error");d.textContent="Verifying...",d.className="totp-error verifying";const r=safeSessionGet("totp_redirect");let f=null;if(r)try{const w=new URL(r,window.location.origin),s=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,t=w.hostname.slice(0,-s.length);w.hostname.endsWith(s)&&/^[a-z0-9][a-z0-9-]*$/.test(t)&&(f=t)}catch{}try{const s=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:p,serviceId:f})})).json();if(s.success){if(d.textContent="",s.csrfToken&&(csrfToken=s.csrfToken),m(),r){try{sessionStorage.removeItem("totp_redirect")}catch{}const t=h(r,s.ssoToken);if(!t)return;window.location.href=t;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard(),window._dcAuthLost=!1,typeof window._sseResume=="function"?window._sseResume():typeof window._sseReconnect=="function"&&window._sseReconnect(),typeof window.refreshAll=="function"&&window.refreshAll()}else{d.textContent=s.error||"Invalid code",d.className="totp-error";const t=document.querySelectorAll("#totp-digits input");t.forEach(e=>{e.value=""}),t[0]?.focus()}}catch{d.textContent="Connection error",d.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const p=urlParams.get("return");if(p)try{const d=new URL(p,window.location.origin)Line truncated
</a>`,e.appendChild(u),u.querySelector("#auth-gate-email-alt-link").addEventListener("click",o=>{o.preventDefault(),b(s)})}t.classList.add("show")}window.__dc_049_handled=!0;function f(w){try{const s=new URL(w,window.location.origin);if(!["http:","https:"].includes(s.protocol))return!1;if(s.origin===window.location.origin)return!0;if(s.protocol!=="https:")return!1;const t=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return s.hostname===t.slice(1)||s.hostname.endsWith(t)}catch{return!1}}function d(w,s){const t=new URL(w,window.location.origin);if(t.origin===window.location.origin)return t.toString();const e=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,n=t.hostname===e.slice(1)||t.hostname.endsWith(e);if(t.protocol!=="https:"||!n||!s)return null;const u=`${t.pathname}${t.search}${t.hash}`;return t.pathname="/dashcaddy-sso",t.search="",t.hash="",t.searchParams.set("token",s),t.searchParams.set("return",u),t.toString()}async function i(w){if(!w||!f(w))return!1;try{const s=new URL(w,window.location.origin),t=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,e=s.hostname.slice(0,-t.length);if(!/^[a-z0-9][a-z0-9-]*$/.test(e))return!1;const n=await fetch(`/api/v1/auth/sso-handoff?serviceId=${encodeURIComponent(e)}`,{credentials:"include",cache:"no-store"});if(!n.ok)return!1;const u=await n.json(),o=u.success&&d(w,u.ssoToken);if(!o)return!1;try{sessionStorage.removeItem("totp_redirect")}catch{}return window.location.replace(o),!0}catch{return!1}}const m=new URLSearchParams(window.location.search);if(m.get("auth")==="required"){const w=m.get("return");if(w&&f(w))try{sessionStorage.setItem("totp_redirect",w)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(async()=>{await i(w)||await g()},0)}window._showAuthGate=g,window._authGateMethods=a})(),(function(){const l=new WeakSet;document.addEventListener("error",d=>{const i=d.target;i&&i.tagName==="IMG"&&i.classList.contains("totp-logo")&&(l.add(i),i.style.display="none")},!0),document.querySelectorAll(".totp-logo").forEach(d=>{d.complete&&d.naturalWidth===0&&(l.add(d),d.style.display="none")});function a(){const d=document.querySelector(".totp-card");if(!d)return;const m=getComputedStyle(d).backgroundColor.match(/\d+/g);if(!m)return;const w=(.299*+m[0]+.587*+m[1]+.114*+m[2])/255,s=d.querySelector(".totp-logo-dark"),t=d.querySelector(".totp-logo-light");s&&(s.style.display=w>.5||l.has(s)?"none":""),t&&(t.style.display=w<=.5||l.has(t)?"none":"")}function p(){const d=document.getElementById("totp-overlay");if(d){d.classList.add("show"),setTimeout(a,50);const i=d.querySelector(".totp-digits input");i&&setTimeout(()=>i.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function h(){const d=document.getElementById("totp-overlay");d&&d.classList.remove("show")}function b(d,i){const m=new URL(d,window.location.origin);if(m.origin===window.location.origin)return m.toString();const w=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,s=m.hostname===w.slice(1)||m.hostname.endsWith(w);if(m.protocol!=="https:"||!s)return null;if(!i)return m.toString();const t=`${m.pathname}${m.search}${m.hash}`;return m.pathname="/dashcaddy-sso",m.search="",m.hash="",m.searchParams.set("token",i),m.searchParams.set("return",t),m.toString()}const g=document.getElementById("totp-digits");if(g){const d=g.querySelectorAll("input");d.forEach((i,m)=>{i.addEventListener("input",w=>{const s=w.target.value.replace(/\D/g,"");w.target.value=s.slice(0,1),s&&m<d.length-1&&d[m+1].focus();const t=Array.from(d).map(e=>e.value).join("");t.length===6&&v(t)}),i.addEventListener("keydown",w=>{w.key==="Backspace"&&!w.target.value&&m>0&&(d[m-1].focus(),d[m-1].value="")}),i.addEventListener("paste",w=>{w.preventDefault();const s=(w.clipboardData.getData("text")||"").replace(/\D/g,"");s.length>=6&&(d.forEach((t,e)=>{t.value=s[e]||""}),d[5].focus(),v(s.slice(0,6)))})})}async function v(d){const i=document.getElementById("totp-error");i.textContent="Verifying...",i.className="totp-error verifying";const m=safeSessionGet("totp_redirect");let w=null;if(m)try{const s=new URL(m,window.location.origin),t=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,e=s.hostname.slice(0,-t.length);s.hostname.endsWith(t)&&/^[a-z0-9][a-z0-9-]*$/.test(e)&&(w=e)}catch{}try{const t=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:d,serviceId:w})})).json();if(t.success){if(i.textContent="",t.csrfToken&&(csrfToken=t.csrfToken),h(),m){try{sessionStorage.removeItem("totp_redirect")}catch{}const e=b(m,t.ssoToken);if(!e)return;window.location.href=e;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard(),window._dcAuthLost=!1,typeof window._sseResume=="function"?window._sseResume():typeof window._sseReconnect=="function"&&window._sseReconnect(),typeof window.refreshAll=="function"&&window.refreshAll()}else{i.textContent=t.error||"Invalid code",i.className="totp-error";Line truncated
<div class="weather-modal-content" style="min-width: 500px; max-width: 700px; max-height: 80vh;">
<h3>\u{1F4C2} Browse for Media Folders</h3>
@@ -179,7 +179,7 @@
</button>
</div>
</div>
</div>`);const a=document.getElementById("service-creds-modal");let m=null,h=null,b=!1;const g=["sonarr","radarr","prowlarr","overseerr"],v=["sonarr","radarr"];function p(e){return e.externalUrl||e.url||""}function d(e){const o=document.getElementById("svc-creds-error");o.textContent=e,o.style.display=""}function r(){const e=document.getElementById("svc-creds-error");e.textContent="",e.style.display="none"}async function f(e,o){if(!e)throw new Error(`${o} failed: no response`);let u;try{u=await e.json()}catch{throw new Error(`${o} failed: invalid server response`)}if(!e.ok||u?.success!==!0)throw new Error(u?.error||`${o} failed (${e.status||"unknown status"})`);return u}function w(e,o){return!!window.DCCredentialVault?.isAllowedReturnUrl(e,o)}window.openServiceCredsModal=async function(e,o={}){m=e,h=w(o.returnUrl,e.id)?o.returnUrl:null,b=!1,r();const u=document.getElementById("svc-creds-title"),n=document.getElementById("svc-creds-desc"),i=document.getElementById("svc-creds-seedhost"),l=document.getElementById("svc-creds-apikey"),y=document.getElementById("svc-creds-basic"),S=document.getElementById("svc-creds-quality");u.textContent=e.name+" \u2014 Encrypted Vault",document.getElementById("svc-creds-save").textContent=h?"Save to vault & open service":"Save to encrypted vault";const k=!!e.isExternal,L=g.includes(e.id)||g.includes(e.appTemplate),x=v.includes(e.id)||v.includes(e.appTemplate);i.style.display=k?"":"none",l.style.display=L?"":"none",S.style.display=x?"":"none",y.style.display=k?"none":"";const B=document.getElementById("svc-quality-select");B.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",k?(n.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${e.name}`):L?n.textContent="API key bypasses the app login screen automatically.":n.textContent="Credentials are injected automatically when accessing this service.",await s(e),a.classList.add("show")};async function s(e){const o=document.getElementById("svc-creds-dot"),u=document.getElementById("svc-creds-status"),n=document.getElementById("svc-creds-clear");let i=!1;if(e.isExternal){try{const S=await(await fetch(`/api/v1/seedhost-creds?serviceId=${e.id}`)).json();S.success?(document.getElementById("svc-seedhost-user").value=S.username||"",S.hasCredentials&&(i=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const S=await(await fetch(`/api/v1/services/${e.id}/credentials`)).json();S.success&&(S.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",i=!0):document.getElementById("svc-apikey-input").value="",S.hasBasicAuth&&!e.isExternal?(document.getElementById("svc-basic-user").value=S.username||"",i=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const l=e.id||e.appTemplate;if(v.includes(l)&&await t(e),i){b=!0,o.style.background="var(--ok-fg, #74dfc4)",u.style.color="var(--ok-fg, #74dfc4)",u.textContent="Credentials stored",n.style.display="";const y=document.getElementById(`creds-btn-${e.id}`);y&&y.classList.add("has-creds")}else o.style.background="var(--muted)",u.style.color="var(--muted)",u.textContent="No credentials stored",n.style.display="none"}async function t(e){const o=document.getElementById("svc-quality-select"),u=document.getElementById("svc-quality-status"),n=e.id||e.appTemplate,i=p(e);if(!i){o.innerHTML='<option value="">-- No service URL --</option>';return}o.innerHTML='<option value="">Loading...</option>',u.textContent="";try{const l=new URLSearchParams({service:n,url:i}),S=await(await fetch(`/api/v1/arr/quality-profiles?${l}`)).json();if(!S.success||!S.profiles?.length){o.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}o.innerHTML="";for(const k of S.profiles){const L=document.createElement("option");L.value=k.id,L.textContent=k.name,o.appendChild(L)}if(S.storedProfileId&&(o.value=String(S.storedProfileId)),!o.value){const k=S.profiles.find(L=>/720/i.test(L.name));k&&(o.value=String(k.id))}!o.value&&S.profiles.length&&(o.value=String(S.profiles[0].id)),u.innerHTML=`<span style="color: var(--ok-fg);">${S.profiles.length} profiles loaded</span>`}catch(l){o.innerHTML='<option value="">-- Failed to load --</option>',u.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${l.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!m)return;const e=m.id||m.appTemplate,o=p(m),n=document.getElementById("svc-apikey-input")?.value.trim(),i=document.getElementById("svc-quality-select"),l=document.getElementById("svc-quality-status");if(!o){l.innerHTML='<span style="color: var(--error, #c62828);">No servLine truncated
</div>`);const a=document.getElementById("service-creds-modal");let p=null,h=null,b=!1;const g=["sonarr","radarr","prowlarr","overseerr"],v=["sonarr","radarr"];function f(e){return e.externalUrl||e.url||""}function d(e){const n=document.getElementById("svc-creds-error");n.textContent=e,n.style.display=""}function i(){const e=document.getElementById("svc-creds-error");e.textContent="",e.style.display="none"}async function m(e,n){if(!e)throw new Error(`${n} failed: no response`);let u;try{u=await e.json()}catch{throw new Error(`${n} failed: invalid server response`)}if(!e.ok||u?.success!==!0)throw new Error(u?.error||`${n} failed (${e.status||"unknown status"})`);return u}function w(e,n){return!!window.DCCredentialVault?.isAllowedReturnUrl(e,n)}window.openServiceCredsModal=async function(e,n={}){p=e,h=w(n.returnUrl,e.id)?n.returnUrl:null,b=!1,i();const u=document.getElementById("svc-creds-title"),o=document.getElementById("svc-creds-desc"),r=document.getElementById("svc-creds-seedhost"),c=document.getElementById("svc-creds-apikey"),y=document.getElementById("svc-creds-basic"),S=document.getElementById("svc-creds-quality");u.textContent=e.name+" \u2014 Encrypted Vault",document.getElementById("svc-creds-save").textContent=h?"Save to vault & open service":"Save to encrypted vault";const k=!!e.isExternal,L=g.includes(e.id)||g.includes(e.appTemplate),x=v.includes(e.id)||v.includes(e.appTemplate);r.style.display=k?"":"none",c.style.display=L?"":"none",S.style.display=x?"":"none",y.style.display=k?"none":"";const B=document.getElementById("svc-quality-select");B.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",k?(o.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${e.name}`):L?o.textContent="API key bypasses the app login screen automatically.":o.textContent="Credentials are injected automatically when accessing this service.",await s(e),a.classList.add("show")};async function s(e){const n=document.getElementById("svc-creds-dot"),u=document.getElementById("svc-creds-status"),o=document.getElementById("svc-creds-clear");let r=!1;if(e.isExternal){try{const S=await(await fetch(`/api/v1/seedhost-creds?serviceId=${e.id}`)).json();S.success?(document.getElementById("svc-seedhost-user").value=S.username||"",S.hasCredentials&&(r=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const S=await(await fetch(`/api/v1/services/${e.id}/credentials`)).json();S.success&&(S.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",r=!0):document.getElementById("svc-apikey-input").value="",S.hasBasicAuth&&!e.isExternal?(document.getElementById("svc-basic-user").value=S.username||"",r=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const c=e.id||e.appTemplate;if(v.includes(c)&&await t(e),r){b=!0,n.style.background="var(--ok-fg, #74dfc4)",u.style.color="var(--ok-fg, #74dfc4)",u.textContent="Credentials stored",o.style.display="";const y=document.getElementById(`creds-btn-${e.id}`);y&&y.classList.add("has-creds")}else n.style.background="var(--muted)",u.style.color="var(--muted)",u.textContent="No credentials stored",o.style.display="none"}async function t(e){const n=document.getElementById("svc-quality-select"),u=document.getElementById("svc-quality-status"),o=e.id||e.appTemplate,r=f(e);if(!r){n.innerHTML='<option value="">-- No service URL --</option>';return}n.innerHTML='<option value="">Loading...</option>',u.textContent="";try{const c=new URLSearchParams({service:o,url:r}),S=await(await fetch(`/api/v1/arr/quality-profiles?${c}`)).json();if(!S.success||!S.profiles?.length){n.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}n.innerHTML="";for(const k of S.profiles){const L=document.createElement("option");L.value=k.id,L.textContent=k.name,n.appendChild(L)}if(S.storedProfileId&&(n.value=String(S.storedProfileId)),!n.value){const k=S.profiles.find(L=>/720/i.test(L.name));k&&(n.value=String(k.id))}!n.value&&S.profiles.length&&(n.value=String(S.profiles[0].id)),u.innerHTML=`<span style="color: var(--ok-fg);">${S.profiles.length} profiles loaded</span>`}catch(c){n.innerHTML='<option value="">-- Failed to load --</option>',u.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${c.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!p)return;const e=p.id||p.appTemplate,n=f(p),o=document.getElementById("svc-apikey-input")?.value.trim(),r=document.getElementById("svc-quality-select"),c=document.getElementById("svc-quality-status");if(!n){c.innerHTML='<span style="color: var(--error, #c62828);">No servLine truncated
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3 style="margin: 0 0 16px; font-size: 1.1rem;">Authentication Settings</h3>
@@ -288,7 +288,7 @@
</button>
</div>
</div>
</div>`);async function a(){try{const v=await(await fetch("/api/v1/totp/config")).json();if(!v.success)return;const{enabled:p,sessionDuration:d,isSetUp:r}=v.config,f=document.getElementById("totp-status-dot"),w=document.getElementById("totp-status-text"),s=document.getElementById("totp-status-banner"),t=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),o=document.getElementById("totp-duration-section"),u=document.getElementById("totp-disable-section");if(p&&r){f.style.background="var(--ok-fg, #7ef2ff)",s.style.borderColor="var(--ok-fg, #7ef2ff)",s.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",w.textContent="TOTP is active",w.style.color="var(--ok-fg, #7ef2ff)",t.style.display="block";const n=document.getElementById("totp-setup-btn");n&&(n.textContent="Generate New Secret"),e.style.display="none",o.style.display="block",u.style.display="block",document.getElementById("totp-duration-select").value=d}else f.style.background="var(--muted)",s.style.borderColor="var(--border)",s.style.background="transparent",w.textContent="TOTP is not configured",w.style.color="var(--muted)",t.style.display="block",e.style.display="none",o.style.display="none",u.style.display="none";b(p&&r,d)}catch(g){console.warn("Failed to load TOTP settings:",g)}}const m={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function h(g,v){const p=window.DCI18n;return p&&p.isLoaded()?p.t(g):v}function b(g,v){const p=document.getElementById("auth-card"),d=document.getElementById("auth-pill"),r=document.getElementById("auth-dot"),f=document.getElementById("auth-status-text");p&&(g?(p.setAttribute("data-status","on"),d.className="badge on",d.textContent=h("card.status.yes","YES"),r.className="dot ok at-bl",f.textContent="Session: "+(m[v]||v)):(p.setAttribute("data-status","off"),d.className="badge off",d.textContent=h("card.status.no","NO"),r.className="dot bad at-bl",f.textContent=h("card.auth.not_configured","Not configured")))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const v=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();v.success&&(document.getElementById("totp-qr-image").src=v.qrCode,document.getElementById("totp-manual-key").textContent=v.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(g){c.logError("[TOTP] Setup Failed",g,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const g=document.getElementById("totp-import-key").value.trim(),v=document.getElementById("totp-import-error");if(v.textContent="",!g){v.textContent="Paste a Base32 secret key first";return}try{const d=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:g})})).json();d.success?(v.textContent="",document.getElementById("totp-qr-image").src=d.qrCode,document.getElementById("totp-manual-key").textContent=d.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):v.textContent=d.error||d.message||"Import failed"}catch{v.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(g).then(()=>{const v=document.getElementById("totp-copy-key");v.textContent="\u2705",setTimeout(()=>{v.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent.trim();if(!g)return;const v={service:"DashCaddy",type:"totp-secret",secret:g,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},p=new Blob([JSON.stringify(v,null,2)],{type:"application/json"}),d=URL.createObjectURL(p),r=document.createElement("a");r.href=d,r.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(d);const f=document.getElementById("totp-download-backup");f.textContent="\u2705 Saved",setTimeLine truncated
</div>`);async function a(){try{const v=await(await fetch("/api/v1/totp/config")).json();if(!v.success)return;const{enabled:f,sessionDuration:d,isSetUp:i}=v.config,m=document.getElementById("totp-status-dot"),w=document.getElementById("totp-status-text"),s=document.getElementById("totp-status-banner"),t=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),n=document.getElementById("totp-duration-section"),u=document.getElementById("totp-disable-section");if(f&&i){m.style.background="var(--ok-fg, #7ef2ff)",s.style.borderColor="var(--ok-fg, #7ef2ff)",s.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",w.textContent="TOTP is active",w.style.color="var(--ok-fg, #7ef2ff)",t.style.display="block";const o=document.getElementById("totp-setup-btn");o&&(o.textContent="Generate New Secret"),e.style.display="none",n.style.display="block",u.style.display="block",document.getElementById("totp-duration-select").value=d}else m.style.background="var(--muted)",s.style.borderColor="var(--border)",s.style.background="transparent",w.textContent="TOTP is not configured",w.style.color="var(--muted)",t.style.display="block",e.style.display="none",n.style.display="none",u.style.display="none";b(f&&i,d)}catch(g){console.warn("Failed to load TOTP settings:",g)}}const p={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function h(g,v){const f=window.DCI18n;return f&&f.isLoaded()?f.t(g):v}function b(g,v){const f=document.getElementById("auth-card"),d=document.getElementById("auth-pill"),i=document.getElementById("auth-dot"),m=document.getElementById("auth-status-text");f&&(g?(f.setAttribute("data-status","on"),d.className="badge on",d.textContent=h("card.status.yes","YES"),i.className="dot ok at-bl",m.textContent="Session: "+(p[v]||v)):(f.setAttribute("data-status","off"),d.className="badge off",d.textContent=h("card.status.no","NO"),i.className="dot bad at-bl",m.textContent=h("card.auth.not_configured","Not configured")))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const v=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();v.success&&(document.getElementById("totp-qr-image").src=v.qrCode,document.getElementById("totp-manual-key").textContent=v.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(g){l.logError("[TOTP] Setup Failed",g,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const g=document.getElementById("totp-import-key").value.trim(),v=document.getElementById("totp-import-error");if(v.textContent="",!g){v.textContent="Paste a Base32 secret key first";return}try{const d=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:g})})).json();d.success?(v.textContent="",document.getElementById("totp-qr-image").src=d.qrCode,document.getElementById("totp-manual-key").textContent=d.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):v.textContent=d.error||d.message||"Import failed"}catch{v.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(g).then(()=>{const v=document.getElementById("totp-copy-key");v.textContent="\u2705",setTimeout(()=>{v.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent.trim();if(!g)return;const v={service:"DashCaddy",type:"totp-secret",secret:g,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},f=new Blob([JSON.stringify(v,null,2)],{type:"application/json"}),d=URL.createObjectURL(f),i=document.createElement("a");i.href=d,i.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(d);const m=document.getElementById("totp-download-backup");m.textContent="\u2705 Saved",setTimeLine truncated
<div id="token-management-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
<h3>\u{1F511} DNS Credentials</h3>
@@ -306,30 +306,30 @@
</div>
</div>
</div>
`);function c(){return Object.keys(SITE.dnsServers||{})}function a(n){return(SITE.dnsServers||{})[n]?.name||n.toUpperCase()}async function m(n,i){if(!n)throw new Error(`${i} failed: no response`);let l;try{l=await n.json()}catch{throw new Error(`${i} failed: invalid server response`)}if(!n.ok||l?.success!==!0)throw new Error(l?.error||`${i} failed (${n.status||"unknown status"})`);return l}function h(){const n=document.getElementById("dns-cred-sections");if(!n)return;n.innerHTML="";const i=c();if(i.length===0){n.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const l of i)n.insertAdjacentHTML("beforeend",`
`);function l(){return Object.keys(SITE.dnsServers||{})}function a(o){return(SITE.dnsServers||{})[o]?.name||o.toUpperCase()}async function p(o,r){if(!o)throw new Error(`${r} failed: no response`);let c;try{c=await o.json()}catch{throw new Error(`${r} failed: invalid server response`)}if(!o.ok||c?.success!==!0)throw new Error(c?.error||`${r} failed (${o.status||"unknown status"})`);return c}function h(){const o=document.getElementById("dns-cred-sections");if(!o)return;o.innerHTML="";const r=l();if(r.length===0){o.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const c of r)o.insertAdjacentHTML("beforeend",`
<div class="token-section">
<h4 class="token-section-title">${a(l)}</h4>
<h4 class="token-section-title">${a(c)}</h4>
<div class="token-grid">
<div class="token-field">
<label for="${l}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
<input type="text" id="${l}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<label for="${c}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
<input type="text" id="${c}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${l}-readonly-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${l}-readonly-token">\u{1F441}</button>
<input type="password" id="${c}-readonly-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${c}-readonly-token">\u{1F441}</button>
</div>
</div>
<div class="token-field">
<label for="${l}-admin-username">\u{1F527} Admin:</label>
<input type="text" id="${l}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<label for="${c}-admin-username">\u{1F527} Admin:</label>
<input type="text" id="${c}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${l}-admin-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${l}-admin-token">\u{1F441}</button>
<input type="password" id="${c}-admin-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${c}-admin-token">\u{1F441}</button>
</div>
</div>
</div>
<div class="token-status" id="${l}-token-status"></div>
<div class="token-status" id="${c}-token-status"></div>
</div>
`)}function b(){let n=safeSessionGet("dashcaddy-encryption-key");if(n)return n;const i=safeGet("dashcaddy-encryption-key");if(i)return safeSessionSet("dashcaddy-encryption-key",i),safeRemove("dashcaddy-encryption-key"),i;const l=new Uint8Array(32);return crypto.getRandomValues(l),n=Array.from(l,y=>y.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",n),n}const g=b();function v(n,i){if(!n)return"";const l=crypto.getRandomValues(new Uint8Array(8)),y=Array.from(l,L=>L.toString(16).padStart(2,"0")).join(""),S=new TextEncoder().encode(i+y);let k="";for(let L=0;L<n.length;L++){const x=n.charCodeAt(L)^S[L%S.length]^l[L%l.length]^L*31+17&255;k+=String.fromCharCode(x)}return y+":"+btoa(k)}function p(n,i){if(!n)return"";try{if(n.indexOf(":")===16){const k=n.substring(0,16),L=new Uint8Array(k.match(/.{2}/g).map(E=>parseInt(E,16))),x=atob(n.substring(17)),B=new TextEncoder().encode(i+k);let A="";for(let E=0;E<x.length;E++){const C=x.charCodeAt(E)^B[E%B.length]^L[E%L.length]^E*31+17&255;A+=String.fromCharCode(C)}return A}const y=atob(n);let S="";for(let k=0;k<y.length;k++){const L=y.charCodeAt(k)^i.charCodeAt(k%i.length);S+=String.fromCharCode(L)}return S}catch{return""}}function d(n,i,l){const y=safeGet(`${n}-${i}-${l}-enc`);return p(y,g)}function r(n,i,l,y){const S=`${n}-${i}-${l}-enc`;y?safeSet(S,v(y,g)):safeRemove(S)}function f(n,i){return d(n,i,"token")}function w(n,i){return d(n,i,"username")}function s(n,i,l){r(n,i,"token",l)}function t(n,i,l){r(n,i,"username",l)}function e(){const n={};for(const i of c())n[i]={readonly:{username:w(i,"readonly"),token:f(i,"readonly")},admin:{username:w(i,"admin"),token:f(i,"admin")}};return n}function o(){c().forEach(n=>{["readonly","admin"].forEach(i=>{["token","username"].forEach(l=>{safeRemove(`${n}-${i}-${l}-enc`)})}),safeRemove(`${n}-token-enc`),safeRemove(`${n}-username-enc`)})}function u(n){const i=f(n,"readonly"),l=w(n,"readonly"),y=f(n,"admin"),S=w(n,"admin"),k=p(safeGet(`${n}-token-enc`),g),L=p(safeGet(`${n}-username-enc`),g);return{username:S||l||L,token:y||i||k,readonlyToken:i||k,readonlyUsername:l||L,adminToken:y||k,adminUsername:S||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{h();const n=document.getElementById("token-management-modal"),i=e();c().forEach(l=>{const y=i[l];document.getElementById(`${l}-readonly-username`).value=y.readonly.username,document.getElementById(`${l}-readonly-token`).value=y.readonly.token,document.getElementById(`${l}-admin-username`).value=y.admin.username,document.getElementById(`${l}-admin-token`).value=y.admin.token,document.getElementById(`${l}-token-status`).textContent=""}),n.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",n=>{const i=n.target.closest(".token-toggle");if(i){const l=i.dataset.target,y=document.getElementById(l);y.type==="password"?(y.type="text",i.textContent="\u{1F648}"):(y.type="password",i.textContent="\u{1F441}");return}n.target.id==="token-management-modal"&&n.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const n=c(),i={};let l=!1;if(n.forEach(y=>{const S={},k=document.getElementById(`${y}-readonly-username`).value.trim(),L=document.getElementById(`${y}-readonly-token`).value.trim(),x=document.getElementById(`${y}-admin-username`).value.trim(),B=document.getElementById(`${y}-admin-token`).value.trim();k&&L&&(S.readonly={username:k,password:L},l=!0),x&&B&&(S.admin={username:x,password:B},l=!0),Object.keys(S).length>0&&(i[y]=S)}),l){n.forEach(y=>{i[y]&&(document.getElementById(`${y}-token-status`).textContent="Verifying...",document.getElementById(`${y}-token-status`).className="token-status")});try{const y=await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:i})}),S=await m(y,"DNS credential save");if(S.results){const k=Object.keys(i).filter(L=>S.results[L]?.success!==!0);if(k.length){const L=k.map(x=>S.results[x]?.error||`${x} failed`).join("; ");throw new Error(L)}}n.forEach(k=>{t(k,"readonly",document.getElementById(`${k}-readonly-username`).value.trim()),s(k,"readonly",document.getElementById(`${k}-readonly-token`).value.trim()),t(k,"admin",document.getElementById(`${k}-admin-username`).value.trim()),s(k,"admin",document.getElementById(`${k}-admin-token`).value.trim())}),n.forEach(k=>{const L=document.getElementById(`${k}-token-status`);if(!i[k]){L.textContent="";return}const x=S.results?.[k];L.textContent=x?.partial?"\u2713 "+x.partial:"\u2713 Verified & saved",L.className="token-status success"})}catch(y){console.error("Failed to sync DNS credentials to backend:",y),n.forEach(S=>{i[S]&&(document.getElementById(`${S}-token-status`).textContent="\u2717 "+(y.message||"Save failed"),document.getElementById(`${S}-token-status`).className="token-status error")})}}else n.forEach(y=>{document.getElementById(`${y}-token-status`).textContent=""});setTimeout(()=>{ Line truncated
`)}function b(){let o=safeSessionGet("dashcaddy-encryption-key");if(o)return o;const r=safeGet("dashcaddy-encryption-key");if(r)return safeSessionSet("dashcaddy-encryption-key",r),safeRemove("dashcaddy-encryption-key"),r;const c=new Uint8Array(32);return crypto.getRandomValues(c),o=Array.from(c,y=>y.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",o),o}const g=b();function v(o,r){if(!o)return"";const c=crypto.getRandomValues(new Uint8Array(8)),y=Array.from(c,L=>L.toString(16).padStart(2,"0")).join(""),S=new TextEncoder().encode(r+y);let k="";for(let L=0;L<o.length;L++){const x=o.charCodeAt(L)^S[L%S.length]^c[L%c.length]^L*31+17&255;k+=String.fromCharCode(x)}return y+":"+btoa(k)}function f(o,r){if(!o)return"";try{if(o.indexOf(":")===16){const k=o.substring(0,16),L=new Uint8Array(k.match(/.{2}/g).map(E=>parseInt(E,16))),x=atob(o.substring(17)),B=new TextEncoder().encode(r+k);let A="";for(let E=0;E<x.length;E++){const C=x.charCodeAt(E)^B[E%B.length]^L[E%L.length]^E*31+17&255;A+=String.fromCharCode(C)}return A}const y=atob(o);let S="";for(let k=0;k<y.length;k++){const L=y.charCodeAt(k)^r.charCodeAt(k%r.length);S+=String.fromCharCode(L)}return S}catch{return""}}function d(o,r,c){const y=safeGet(`${o}-${r}-${c}-enc`);return f(y,g)}function i(o,r,c,y){const S=`${o}-${r}-${c}-enc`;y?safeSet(S,v(y,g)):safeRemove(S)}function m(o,r){return d(o,r,"token")}function w(o,r){return d(o,r,"username")}function s(o,r,c){i(o,r,"token",c)}function t(o,r,c){i(o,r,"username",c)}function e(){const o={};for(const r of l())o[r]={readonly:{username:w(r,"readonly"),token:m(r,"readonly")},admin:{username:w(r,"admin"),token:m(r,"admin")}};return o}function n(){l().forEach(o=>{["readonly","admin"].forEach(r=>{["token","username"].forEach(c=>{safeRemove(`${o}-${r}-${c}-enc`)})}),safeRemove(`${o}-token-enc`),safeRemove(`${o}-username-enc`)})}function u(o){const r=m(o,"readonly"),c=w(o,"readonly"),y=m(o,"admin"),S=w(o,"admin"),k=f(safeGet(`${o}-token-enc`),g),L=f(safeGet(`${o}-username-enc`),g);return{username:S||c||L,token:y||r||k,readonlyToken:r||k,readonlyUsername:c||L,adminToken:y||k,adminUsername:S||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{h();const o=document.getElementById("token-management-modal"),r=e();l().forEach(c=>{const y=r[c];document.getElementById(`${c}-readonly-username`).value=y.readonly.username,document.getElementById(`${c}-readonly-token`).value=y.readonly.token,document.getElementById(`${c}-admin-username`).value=y.admin.username,document.getElementById(`${c}-admin-token`).value=y.admin.token,document.getElementById(`${c}-token-status`).textContent=""}),o.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",o=>{const r=o.target.closest(".token-toggle");if(r){const c=r.dataset.target,y=document.getElementById(c);y.type==="password"?(y.type="text",r.textContent="\u{1F648}"):(y.type="password",r.textContent="\u{1F441}");return}o.target.id==="token-management-modal"&&o.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const o=l(),r={};let c=!1;if(o.forEach(y=>{const S={},k=document.getElementById(`${y}-readonly-username`).value.trim(),L=document.getElementById(`${y}-readonly-token`).value.trim(),x=document.getElementById(`${y}-admin-username`).value.trim(),B=document.getElementById(`${y}-admin-token`).value.trim();k&&L&&(S.readonly={username:k,password:L},c=!0),x&&B&&(S.admin={username:x,password:B},c=!0),Object.keys(S).length>0&&(r[y]=S)}),c){o.forEach(y=>{r[y]&&(document.getElementById(`${y}-token-status`).textContent="Verifying...",document.getElementById(`${y}-token-status`).className="token-status")});try{const y=await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:r})}),S=await p(y,"DNS credential save");if(S.results){const k=Object.keys(r).filter(L=>S.results[L]?.success!==!0);if(k.length){const L=k.map(x=>S.results[x]?.error||`${x} failed`).join("; ");throw new Error(L)}}o.forEach(k=>{t(k,"readonly",document.getElementById(`${k}-readonly-username`).value.trim()),s(k,"readonly",document.getElementById(`${k}-readonly-token`).value.trim()),t(k,"admin",document.getElementById(`${k}-admin-username`).value.trim()),s(k,"admin",document.getElementById(`${k}-admin-token`).value.trim())}),o.forEach(k=>{const L=document.getElementById(`${k}-token-status`);if(!r[k]){L.textContent="";return}const x=S.results?.[k];L.textContent=x?.partial?"\u2713 "+x.partial:"\u2713 Verified & saved",L.className="token-status success"})}catch(y){console.error("Failed to sync DNS credentials to backend:",y),o.forEach(S=>{r[S]&&(document.getElementById(`${S}-token-status`).textContent="\u2717 "+(y.message||"Save failed"),document.getElementById(`${S}-token-status`).className="token-status error")})}}else o.forEach(y=>{document.getElementById(`${y}-token-status`).textContent=""});setTimeout(()=>{ Line truncated
Current: ${s.currentVersion}
New: ${s.updateVersion}
@@ -337,9 +337,9 @@ New: ${s.updateVersion}
`+(s.updateTitle?`${s.updateTitle}
`:"")+`The DNS server will restart during the update.
Proceed?`)){r.textContent=f,r.disabled=!1,r.title="Update DNS server";return}r.textContent="\u{1F504}",r.title="Updating...";const o=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(d)}`,{method:"POST"})).json();if(!o.success)throw new Error(o.error||"Update failed");if(o.manualUpdateRequired){r.textContent="\u2B06\uFE0F",r.title=`Update available: ${o.newVersion}`;const u=o.downloadLink?`
Download: ${o.downloadLink}`:"",n=o.instructionsLink?`
Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} update requires manual installation. Current: ${o.previousVersion} \u2192 ${o.newVersion}. Please update manually on the host machine.`,"warning",8e3),r.disabled=!1;return}r.textContent="\u2705",r.title="Updated successfully!",showNotification(`${p.toUpperCase()} updated successfully! ${o.previousVersion} \u2192 ${o.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{r.textContent=f,r.disabled=!1,r.title="Update DNS server",window.refreshAll()},1e4)}catch(w){console.error("DNS update error:",w),r.textContent="\u274C",r.title="Update failed",showNotification(`Failed to update ${p.toUpperCase()}: ${w.message}`,"error"),setTimeout(()=>{r.textContent=f,r.disabled=!1,r.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",p=>{const d=p.target.closest('[id$="-update"]');if(!d)return;const r=d.id.replace("-update","");SITE.dnsServers[r]&&a(r,SITE.dnsServers[r]?.ip)}),injectModal("dns-settings-modal",`
Proceed?`)){i.textContent=m,i.disabled=!1,i.title="Update DNS server";return}i.textContent="\u{1F504}",i.title="Updating...";const n=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(d)}`,{method:"POST"})).json();if(!n.success)throw new Error(n.error||"Update failed");if(n.manualUpdateRequired){i.textContent="\u2B06\uFE0F",i.title=`Update available: ${n.newVersion}`;const u=n.downloadLink?`
Download: ${n.downloadLink}`:"",o=n.instructionsLink?`
Instructions: ${n.instructionsLink}`:"";showNotification(`${f.toUpperCase()} update requires manual installation. Current: ${n.previousVersion} \u2192 ${n.newVersion}. Please update manually on the host machine.`,"warning",8e3),i.disabled=!1;return}i.textContent="\u2705",i.title="Updated successfully!",showNotification(`${f.toUpperCase()} updated successfully! ${n.previousVersion} \u2192 ${n.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{i.textContent=m,i.disabled=!1,i.title="Update DNS server",window.refreshAll()},1e4)}catch(w){console.error("DNS update error:",w),i.textContent="\u274C",i.title="Update failed",showNotification(`Failed to update ${f.toUpperCase()}: ${w.message}`,"error"),setTimeout(()=>{i.textContent=m,i.disabled=!1,i.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",f=>{const d=f.target.closest('[id$="-update"]');if(!d)return;const i=d.id.replace("-update","");SITE.dnsServers[i]&&a(i,SITE.dnsServers[i]?.ip)}),injectModal("dns-settings-modal",`
<div id="dns-settings-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3 id="dns-settings-title">DNS Settings</h3>
@@ -366,7 +366,7 @@ Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} upd
<button id="dns-settings-save" class="btn-accent">Save</button>
</div>
</div>
</div>`);let m=null;function h(p){m=p;const d=SITE.dnsServers[p]||{},r=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(d.name||p).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=d.ip||"",document.getElementById("dns-edit-port").value=d.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=d.name||"",r.classList.add("show")}async function b(){if(!m)return;const p=document.getElementById("dns-edit-ip").value.trim(),d=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,r=document.getElementById("dns-edit-name").value.trim();if(!p){showNotification("Server IP is required","warning");return}const f={dnsServers:{}};f.dnsServers[m]={ip:p,port:String(d)},r&&(f.dnsServers[m].name=r);try{const s=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)})).json();s.success?(SITE.dnsServers[m]=f.dnsServers[m],showNotification(`${m.toUpperCase()} settings saved`,"success"),v(),window.refreshAll()):showNotification(s.error||"Failed to save settings","error")}catch(w){showNotification("Failed to save: "+w.message,"error")}}async function g(){if(m&&confirm(`Remove ${m.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const d=await(await secureFetch("/api/v1/config")).json();d.dnsServers&&delete d.dnsServers[m];const f=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:d.dnsServers||{}})})).json();if(f.success){delete SITE.dnsServers[m];const w=document.querySelector(`.top [data-app="${m}"]`);w&&w.remove(),showNotification(`${m.toUpperCase()} removed from dashboard`,"success"),v()}else showNotification(f.error||"Failed to remove","error")}catch(p){showNotification("Failed to remove: "+p.message,"error")}}function v(){closeModal("dns-settings-modal"),m=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",v),document.getElementById("dns-settings-save")?.addEventListener("click",b),document.getElementById("dns-settings-delete")?.addEventListener("click",g),document.getElementById("dns-settings-modal")?.addEventListener("click",p=>{p.target.id==="dns-settings-modal"&&v()}),document.querySelector(".top")?.addEventListener("click",p=>{const d=p.target.closest('[id$="-settings"]');if(!d)return;const r=d.id.replace("-settings","");SITE.dnsServers[r]&&(p.stopPropagation(),h(r))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
</div>`);let p=null;function h(f){p=f;const d=SITE.dnsServers[f]||{},i=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(d.name||f).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=d.ip||"",document.getElementById("dns-edit-port").value=d.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=d.name||"",i.classList.add("show")}async function b(){if(!p)return;const f=document.getElementById("dns-edit-ip").value.trim(),d=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,i=document.getElementById("dns-edit-name").value.trim();if(!f){showNotification("Server IP is required","warning");return}const m={dnsServers:{}};m.dnsServers[p]={ip:f,port:String(d)},i&&(m.dnsServers[p].name=i);try{const s=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)})).json();s.success?(SITE.dnsServers[p]=m.dnsServers[p],showNotification(`${p.toUpperCase()} settings saved`,"success"),v(),window.refreshAll()):showNotification(s.error||"Failed to save settings","error")}catch(w){showNotification("Failed to save: "+w.message,"error")}}async function g(){if(p&&confirm(`Remove ${p.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const d=await(await secureFetch("/api/v1/config")).json();d.dnsServers&&delete d.dnsServers[p];const m=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:d.dnsServers||{}})})).json();if(m.success){delete SITE.dnsServers[p];const w=document.querySelector(`.top [data-app="${p}"]`);w&&w.remove(),showNotification(`${p.toUpperCase()} removed from dashboard`,"success"),v()}else showNotification(m.error||"Failed to remove","error")}catch(f){showNotification("Failed to remove: "+f.message,"error")}}function v(){closeModal("dns-settings-modal"),p=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",v),document.getElementById("dns-settings-save")?.addEventListener("click",b),document.getElementById("dns-settings-delete")?.addEventListener("click",g),document.getElementById("dns-settings-modal")?.addEventListener("click",f=>{f.target.id==="dns-settings-modal"&&v()}),document.querySelector(".top")?.addEventListener("click",f=>{const d=f.target.closest('[id$="-settings"]');if(!d)return;const i=d.id.replace("-settings","");SITE.dnsServers[i]&&(f.stopPropagation(),h(i))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
<div id="logs-modal" class="logs-modal">
<div class="logs-modal-content" style="min-width: 800px; max-width: 1000px;">
<div class="logs-header">
@@ -390,13 +390,13 @@ Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} upd
</div>
</div>
</div>
</div>`);let c=null,a=null,m=!1,h=null,b=null,g=!1,v=null,p=null,d=!1,r=null,f=!1;async function w(E,C=25){try{const T=getDnsServerAddr(E),$=await fetch(`/api/v1/dns/logs?server=${T}&limit=${C}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,server:I.server}:{error:I.error||"Failed to fetch logs"}}else return $.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${$.status}`}}catch(T){return console.error("DNS logs fetch failed:",T),{error:T.message}}}function s(E){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[E]||"var(--fg)"}function t(E){const C=document.createElement("div");if(C.className="log-entry",C.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",E.parsed===!1)return C.style.gridTemplateColumns="1fr",C.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(E.raw)}</span>`,C;const T=s(E.rcode),$=E.rcode==="Refused"||E.rcode==="REFUSED";return C.innerHTML=`
</div>`);let l=null,a=null,p=!1,h=null,b=null,g=!1,v=null,f=null,d=!1,i=null,m=!1;async function w(E,C=25){try{const T=getDnsServerAddr(E),$=await fetch(`/api/v1/dns/logs?server=${T}&limit=${C}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,server:I.server}:{error:I.error||"Failed to fetch logs"}}else return $.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${$.status}`}}catch(T){return console.error("DNS logs fetch failed:",T),{error:T.message}}}function s(E){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[E]||"var(--fg)"}function t(E){const C=document.createElement("div");if(C.className="log-entry",C.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",E.parsed===!1)return C.style.gridTemplateColumns="1fr",C.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(E.raw)}</span>`,C;const T=s(E.rcode),$=E.rcode==="Refused"||E.rcode==="REFUSED";return C.innerHTML=`
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(E.timestamp)}</span>
<span style="color: var(--accent); font-size: 0.75rem;" title="${escapeHtml(E.client)}">${escapeHtml(E.client)}</span>
<span style="font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; ${$?"text-decoration: line-through; opacity: 0.6;":""}" title="${escapeHtml(E.domain)}">${escapeHtml(E.domain)}</span>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(E.type)}</span>
<span style="color: ${T}; font-weight: 500; font-size: 0.75rem;">${escapeHtml(E.rcode)}</span>
`,C}async function e(){if(d){await B();return}if(g){await S();return}if(m||!c)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await w(c,E);if(T.error){C.innerHTML=`
`,C}async function e(){if(d){await B();return}if(g){await S();return}if(p||!l)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await w(l,E);if(T.error){C.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
<div>${escapeHtml(T.error)}</div>
@@ -413,13 +413,13 @@ Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} upd
</div>`}catch(T){C.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(T.message)}
</div>`}}function o(E){c=E,m=!1,g=!1;const C=document.getElementById("logs-modal"),T=document.getElementById("logs-title"),$=document.getElementById("logs-pause"),I=document.getElementById("logs-stream");T.textContent=`${E.toUpperCase()} DNS Logs`,$.textContent="\u23F8\uFE0F Pause",$.classList.remove("paused"),I&&(I.style.display="none"),C.classList.add("show"),e(),a=setInterval(e,DC.POLL.LOGS)}function u(){document.getElementById("logs-modal").classList.remove("show"),a&&(clearInterval(a),a=null),i(),c=null,g=!1,h=null,b=null,d=!1,v=null,p=null,m=!1}function n(E){r&&i();const C=document.getElementById("logs-stream"),T=document.getElementById("logs-pause"),$=document.getElementById("logs-content");a&&(clearInterval(a),a=null);try{r=new EventSource(`/api/v1/logs/stream/${E}`),f=!0,C.classList.add("active"),C.textContent="\u{1F534} Live",C.title="Streaming - click to stop",T.style.display="none";const I=document.getElementById("logs-title");I.textContent.includes("\u{1F534}")||(I.innerHTML=I.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),r.onmessage=P=>{try{const D=JSON.parse(P.data);if(D.error){console.error("Stream error:",D.error),i();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const _=(D.stream||"stdout")==="stderr",R=_?"var(--bad-fg)":"var(--fg)",M=`<span style="background: ${_?"var(--bad-bg)":"var(--ok-bg)"}; color: ${R}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${_?"STDERR":"STDOUT"}</span>`;for(O.innerHTML=`
</div>`}}function n(E){l=E,p=!1,g=!1;const C=document.getElementById("logs-modal"),T=document.getElementById("logs-title"),$=document.getElementById("logs-pause"),I=document.getElementById("logs-stream");T.textContent=`${E.toUpperCase()} DNS Logs`,$.textContent="\u23F8\uFE0F Pause",$.classList.remove("paused"),I&&(I.style.display="none"),C.classList.add("show"),e(),a=setInterval(e,DC.POLL.LOGS)}function u(){document.getElementById("logs-modal").classList.remove("show"),a&&(clearInterval(a),a=null),r(),l=null,g=!1,h=null,b=null,d=!1,v=null,f=null,p=!1}function o(E){i&&r();const C=document.getElementById("logs-stream"),T=document.getElementById("logs-pause"),$=document.getElementById("logs-content");a&&(clearInterval(a),a=null);try{i=new EventSource(`/api/v1/logs/stream/${E}`),m=!0,C.classList.add("active"),C.textContent="\u{1F534} Live",C.title="Streaming - click to stop",T.style.display="none";const I=document.getElementById("logs-title");I.textContent.includes("\u{1F534}")||(I.innerHTML=I.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),i.onmessage=P=>{try{const D=JSON.parse(P.data);if(D.error){console.error("Stream error:",D.error),r();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const _=(D.stream||"stdout")==="stderr",R=_?"var(--bad-fg)":"var(--fg)",M=`<span style="background: ${_?"var(--bad-bg)":"var(--ok-bg)"}; color: ${R}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${_?"STDERR":"STDOUT"}</span>`;for(O.innerHTML=`
<div style="flex-shrink: 0;">${M}</div>
<div style="flex: 1; color: ${R}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(D.text)}</div>
`,$.appendChild(O),$.scrollTop=$.scrollHeight;$.children.length>500;)$.removeChild($.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},r.onerror=P=>{console.error("EventSource error:",P),i()}}catch(I){console.error("Failed to start streaming:",I),i()}}function i(){r&&(r.close(),r=null),f=!1;const E=document.getElementById("logs-stream"),C=document.getElementById("logs-pause"),T=document.getElementById("logs-title");E&&(E.classList.remove("active"),E.textContent="\u{1F4E1} Live",E.title="Enable real-time streaming"),C&&(C.style.display=""),T&&(T.textContent=T.textContent.replace(" \u{1F534}","")),g&&h&&!a&&(a=setInterval(S,DC.POLL.LOGS))}async function l(E,C=100){try{const T=`/api/v1/logs/container/${E}?tail=${C}&timestamps=true`,$=await fetch(T,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,containerName:I.containerName,containerId:I.containerId}:{error:I.error||"Failed to fetch container logs"}}else return{error:`HTTP ${$.status}: ${$.statusText}`}}catch(T){return console.error("Container logs fetch failed:",T),{error:T.message}}}function y(E){const C=document.createElement("div");C.className="log-entry",C.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const T=E.stream==="stderr"?"var(--bad-fg)":"var(--fg)",$=E.stream==="stderr"?'<span style="background: var(--bad-bg); color: var(--bad-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDERR</span>':'<span style="background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDOUT</span>';return C.innerHTML=`
`,$.appendChild(O),$.scrollTop=$.scrollHeight;$.children.length>500;)$.removeChild($.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},i.onerror=P=>{console.error("EventSource error:",P),r()}}catch(I){console.error("Failed to start streaming:",I),r()}}function r(){i&&(i.close(),i=null),m=!1;const E=document.getElementById("logs-stream"),C=document.getElementById("logs-pause"),T=document.getElementById("logs-title");E&&(E.classList.remove("active"),E.textContent="\u{1F4E1} Live",E.title="Enable real-time streaming"),C&&(C.style.display=""),T&&(T.textContent=T.textContent.replace(" \u{1F534}","")),g&&h&&!a&&(a=setInterval(S,DC.POLL.LOGS))}async function c(E,C=100){try{const T=`/api/v1/logs/container/${E}?tail=${C}&timestamps=true`,$=await fetch(T,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,containerName:I.containerName,containerId:I.containerId}:{error:I.error||"Failed to fetch container logs"}}else return{error:`HTTP ${$.status}: ${$.statusText}`}}catch(T){return console.error("Container logs fetch failed:",T),{error:T.message}}}function y(E){const C=document.createElement("div");C.className="log-entry",C.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const T=E.stream==="stderr"?"var(--bad-fg)":"var(--fg)",$=E.stream==="stderr"?'<span style="background: var(--bad-bg); color: var(--bad-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDERR</span>':'<span style="background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDOUT</span>';return C.innerHTML=`
<div style="flex-shrink: 0;">${$}</div>
<div style="flex: 1; color: ${T}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(E.text)}</div>
`,C}async function S(){if(m||!h||!g)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await l(h,E);if(T.error){C.innerHTML=`
`,C}async function S(){if(p||!h||!g)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await c(h,E);if(T.error){C.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
<div>${escapeHtml(T.error)}</div>
@@ -433,10 +433,10 @@ Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} upd
</div>`}catch(T){C.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(T.message)}
</div>`}}function k(E,C){h=E,b=C,g=!0,d=!1,m=!1,i();const T=document.getElementById("logs-modal"),$=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");$.textContent=`\u{1F4CB} ${C} - Container Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),P&&(P.style.display=""),T.classList.add("show"),S(),a=setInterval(S,DC.POLL.LOGS)}async function L(E,C=100){try{const T=`/api/v1/logs/file?path=${encodeURIComponent(E)}&tail=${C}`,$=await fetch(T,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,logPath:I.logPath,totalLines:I.totalLines}:{error:I.error||"Failed to fetch file logs"}}else return{error:(await $.json().catch(()=>({}))).error||`HTTP ${$.status}`}}catch(T){return console.error("File logs fetch failed:",T),{error:T.message}}}function x(E){const C=document.createElement("div");C.className="log-entry",C.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const T=E.text;let $="INFO",I="var(--fg)";T.match(/ERROR|FATAL|CRITICAL/i)?($="ERROR",I="var(--bad-fg)"):T.match(/WARN|WARNING/i)?($="WARN",I="#f39c12"):T.match(/DEBUG/i)&&($="DEBUG",I="var(--muted)");const D=`<span style="background: ${I==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${I}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${$}</span>`;return C.innerHTML=`
</div>`}}function k(E,C){h=E,b=C,g=!0,d=!1,p=!1,r();const T=document.getElementById("logs-modal"),$=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");$.textContent=`\u{1F4CB} ${C} - Container Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),P&&(P.style.display=""),T.classList.add("show"),S(),a=setInterval(S,DC.POLL.LOGS)}async function L(E,C=100){try{const T=`/api/v1/logs/file?path=${encodeURIComponent(E)}&tail=${C}`,$=await fetch(T,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,logPath:I.logPath,totalLines:I.totalLines}:{error:I.error||"Failed to fetch file logs"}}else return{error:(await $.json().catch(()=>({}))).error||`HTTP ${$.status}`}}catch(T){return console.error("File logs fetch failed:",T),{error:T.message}}}function x(E){const C=document.createElement("div");C.className="log-entry",C.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const T=E.text;let $="INFO",I="var(--fg)";T.match(/ERROR|FATAL|CRITICAL/i)?($="ERROR",I="var(--bad-fg)"):T.match(/WARN|WARNING/i)?($="WARN",I="#f39c12"):T.match(/DEBUG/i)&&($="DEBUG",I="var(--muted)");const D=`<span style="background: ${I==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${I}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${$}</span>`;return C.innerHTML=`
<div style="flex-shrink: 0;">${D}</div>
<div style="flex: 1; color: ${I}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(T)}</div>
`,C}async function B(){if(m||!v||!d)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await L(v,E);if(T.error){C.innerHTML=`
`,C}async function B(){if(p||!v||!d)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await L(v,E);if(T.error){C.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
<div>${escapeHtml(T.error)}</div>
@@ -449,7 +449,7 @@ Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} upd
</div>`}catch(T){C.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(T.message)}
</div>`}}function A(E,C){v=E,p=C,d=!0,g=!1,m=!1;const T=document.getElementById("logs-modal"),$=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");$.textContent=`\u{1F4CB} ${C} - Application Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),P&&(P.style.display="none"),T.classList.add("show"),B(),a=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",E=>{const C=E.target.closest('[id$="-logs"]');if(!C)return;const T=C.id.replace("-logs","");SITE.dnsServers[T]&&o(T)}),document.getElementById("logs-close")?.addEventListener("click",u),document.getElementById("logs-pause")?.addEventListener("click",()=>{m=!m;const E=document.getElementById("logs-pause");m?(E.textContent="\u25B6\uFE0F Resume",E.classList.add("paused")):(E.textContent="\u23F8\uFE0F Pause",E.classList.remove("paused"),e())}),document.getElementById("log-lines")?.addEventListener("change",()=>{m||e()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!g||!h||(f?i():n(h))}),document.getElementById("logs-modal")?.addEventListener("click",E=>{E.target.id==="logs-modal"&&u()}),document.addEventListener("keydown",E=>{E.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&u()}),window.openContainerLogsModal=k,window.openFileLogsModal=A,window.openLogsModal=o})(),(function(){injectModal("service-edit-modal",`
</div>`}}function A(E,C){v=E,f=C,d=!0,g=!1,p=!1;const T=document.getElementById("logs-modal"),$=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");$.textContent=`\u{1F4CB} ${C} - Application Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),P&&(P.style.display="none"),T.classList.add("show"),B(),a=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",E=>{const C=E.target.closest('[id$="-logs"]');if(!C)return;const T=C.id.replace("-logs","");SITE.dnsServers[T]&&n(T)}),document.getElementById("logs-close")?.addEventListener("click",u),document.getElementById("logs-pause")?.addEventListener("click",()=>{p=!p;const E=document.getElementById("logs-pause");p?(E.textContent="\u25B6\uFE0F Resume",E.classList.add("paused")):(E.textContent="\u23F8\uFE0F Pause",E.classList.remove("paused"),e())}),document.getElementById("log-lines")?.addEventListener("change",()=>{p||e()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!g||!h||(m?r():o(h))}),document.getElementById("logs-modal")?.addEventListener("click",E=>{E.target.id==="logs-modal"&&u()}),document.addEventListener("keydown",E=>{E.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&u()}),window.openContainerLogsModal=k,window.openFileLogsModal=A,window.openLogsModal=n})(),(function(){injectModal("service-edit-modal",`
<div id="service-edit-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
<h3 id="service-edit-title">Edit Service</h3>
@@ -805,45 +805,45 @@ Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} upd
<button id="add-service-create" class="btn-accent">Create Service</button>
</div>
</div>
</div>`)})(),(function(){async function c(g){try{const v=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(g)}`);if(!v.ok)throw new Error(`Failed to load CAs: ${v.status}`);const p=await v.json();if(p.success){const d=document.getElementById("existing-ca-select");return d.innerHTML="",p.cas.length===0?d.innerHTML='<option value="">No CAs found in Caddyfile</option>':(d.innerHTML='<option value="">Select existing CA...</option>',p.cas.forEach(r=>{const f=document.createElement("option");typeof r=="object"?(f.value=r.id,f.textContent=r.displayName||r.name):(f.value=r,f.textContent=r),d.appendChild(f)})),p.data.cas}else throw new Error(p.message)}catch(v){console.error("Error loading CAs:",v);const p=document.getElementById("existing-ca-select");return p.innerHTML='<option value="">Error loading CAs</option>',[]}}function a(g){const{subdomain:v,port:p,ip:d,sslType:r,caName:f,existingCa:w,enableAuth:s,enableCors:t,customHeaders:e,upstreamPath:o,healthCheck:u,timeout:n,tailscaleOnly:i}=g;let l=`${buildDomain(v)} {
`;switch(i&&(l+=` @blocked not remote_ip 100.64.0.0/10
`,l+=` respond @blocked "Access denied. Tailscale connection required." 403
`),r){case"letsencrypt":break;case"caddy-managed":l+=` tls internal
`;break;case"existing-ca":w&&(l+=` tls {
</div>`)})(),(function(){async function l(g){try{const v=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(g)}`);if(!v.ok)throw new Error(`Failed to load CAs: ${v.status}`);const f=await v.json();if(f.success){const d=document.getElementById("existing-ca-select");return d.innerHTML="",f.cas.length===0?d.innerHTML='<option value="">No CAs found in Caddyfile</option>':(d.innerHTML='<option value="">Select existing CA...</option>',f.cas.forEach(i=>{const m=document.createElement("option");typeof i=="object"?(m.value=i.id,m.textContent=i.displayName||i.name):(m.value=i,m.textContent=i),d.appendChild(m)})),f.data.cas}else throw new Error(f.message)}catch(v){console.error("Error loading CAs:",v);const f=document.getElementById("existing-ca-select");return f.innerHTML='<option value="">Error loading CAs</option>',[]}}function a(g){const{subdomain:v,port:f,ip:d,sslType:i,caName:m,existingCa:w,enableAuth:s,enableCors:t,customHeaders:e,upstreamPath:n,healthCheck:u,timeout:o,tailscaleOnly:r}=g;let c=`${buildDomain(v)} {
`;switch(r&&(c+=` @blocked not remote_ip 100.64.0.0/10
`,c+=` respond @blocked "Access denied. Tailscale connection required." 403
`),i){case"letsencrypt":break;case"caddy-managed":c+=` tls internal
`;break;case"existing-ca":w&&(c+=` tls {
ca ${w}
}
`);break;case"custom-ca":f&&(l+=` tls {
ca ${f}
`);break;case"custom-ca":m&&(c+=` tls {
ca ${m}
}
`);break}if(s&&(l+=` basicauth {
`);break}if(s&&(c+=` basicauth {
admin $2a$14$hashed_password_here
}
`),t&&(l+=` header {
`,l+=` Access-Control-Allow-Origin "*"
`,l+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,l+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,l+=` }
`),e)try{const y=JSON.parse(e);l+=` header {
`,Object.entries(y).forEach(([S,k])=>{l+=` ${S} "${k}"
`}),l+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return u&&(l+=` health_uri ${u}
`),l+=` reverse_proxy ${d}:${p} {
`,o&&o!=="/"&&(l+=` rewrite ${o}
`),n&&n!==30&&(l+=` transport http {
`,l+=` dial_timeout ${n}s
`,l+=` response_header_timeout ${n}s
`,l+=` }
`),l+=` }
`,l+=`}
`,l}async function m(g,v,p=DC.DEFAULTS.TTL){const d=window.getToken(getPrimaryDnsId(),"admin");if(!d)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const r=buildDomain(g),f=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:r,ip:v,ttl:p,token:d,server:SITE.dnsIp})});if(!f.ok){const s=await f.text();throw new Error(`DNS API Error: ${f.status} - ${s}`)}const w=await f.json();if(!w.success)throw new Error(`DNS Error: ${w.error||"Unknown error"}`);return w}async function h(g){const v={id:g.subdomain,name:g.name,logo:g.logo||`/assets/${g.subdomain}.png`};g.category&&(v.category=g.category),g.containerId&&(v.containerId=g.containerId);try{const p=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!p.ok){const d=await p.json();throw new Error(d.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),v}catch(p){throw console.error("Failed to add service to config:",p),p}}async function b(g){const v=document.getElementById("service-subdomain-input").value.trim(),p=document.getElementById("service-ip-input").value.trim()||"localhost",d=document.getElementById("service-port-input").value.trim()||"80",r=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(v),upstream:`${p}:${d}`,config:g})}),f=await r.json();if(!r.ok||!f.success)throw new Error(f.error||`Caddy API Error: ${r.status}`);return f}window.loadExistingCAs=c,window.generateCaddyConfig=a,window.createDnsRecord=m,window.addServiceToConfig=h,window.addToCaddyfile=b})(),(function(){let c=null;function a(p){c=p;const d=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${p.name}`,document.getElementById("edit-service-name").value=p.name,document.getElementById("edit-service-url-display").textContent=p.url||buildServiceUrl(p.id),document.getElementById("edit-service-logo-preview").src=p.logo||`/assets/${p.id}.png`,document.getElementById("edit-subdomain").value=p.id,document.getElementById("edit-port").value=p.port||"",document.getElementById("edit-ip").value=p.ip||"localhost",document.getElementById("edit-tailscale-only").checked=p.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=p.logo||"";const r=document.getElementById("edit-service-category");r&&(r.dataset.current=p.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),d.classList.add("show")}function m(){closeModal("service-edit-modal"),c=null}async function h(){if(!c)return;const p=document.getElementById("edit-subdomain").value.trim().toLowerCase(),d=document.getElementById("edit-service-name").value.trim(),r=document.getElementById("edit-port").value.trim(),f=document.getElementById("edit-ip").value.trim()||"localhost",w=document.getElementById("edit-tailscale-only").checked,s=document.getElementById("edit-logo-url").value.trim(),t=document.getElementById("edit-service-category")?.value||"";if(!p){showNotification("Subdomain is required","warning");return}const e=c.id,o=[];if(p!==e&&o.push("subdomain"),d&&d!==c.name&&o.push("name"),r&&r!==String(c.port)&&o.push("port"),f!==c.ip&&o.push("ip"),w!==(c.tailscaleOnly||!1)&&o.push("tailscale"),s&&s!==c.logo&&o.push("logo"),t!==(c.category||"")&&o.push("category"),o.length===0){m();return}const u=document.getElementById("service-edit-save");u.textContent="Saving...",u.disabled=!0;try{const i=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:p,name:d||c.name,port:r||c.port,ip:f,tailscaleOnly:w,logo:s||void 0,category:t})})).json();if(!i.success)throw new Error(i.error||"Failed to update service");const l=window.APPS.findIndex(y=>y.id===e);l!==-1&&(window.APPS[l]={...window.APPS[l],id:p,name:d||window.APPS[l].name,port:r||window.APPS[l].port,ip:f,tailscaleOnly:w,logo:s||window.APPS[l].logo,category:t||void 0}),m(),window.buildGrid(),window.refreshAll()}catch(n){console.error("Error saving service changes:",n),showNotification(`Error saving changes: ${n.message}`,"error")}finally{u.textContent="Save Changes",u.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async p=>{const d=p.target.files[0];if(!d)return;if(!d.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const r=new FileReader;r.onload=async f=>{const w=f.target.result;if(document.getElementById("edit-service-logo-preview").src=w,document.getElementById("edit-logo-url").value=w,c)try{const t=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${c.id}.png`,data:w})})).json();t.success&&t.path&&(document.getElementById("edit-logo-url").val Line truncated
`),t&&(c+=` header {
`,c+=` Access-Control-Allow-Origin "*"
`,c+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,c+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,c+=` }
`),e)try{const y=JSON.parse(e);c+=` header {
`,Object.entries(y).forEach(([S,k])=>{c+=` ${S} "${k}"
`}),c+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return u&&(c+=` health_uri ${u}
`),c+=` reverse_proxy ${d}:${f} {
`,n&&n!=="/"&&(c+=` rewrite ${n}
`),o&&o!==30&&(c+=` transport http {
`,c+=` dial_timeout ${o}s
`,c+=` response_header_timeout ${o}s
`,c+=` }
`),c+=` }
`,c+=`}
`,c}async function p(g,v,f=DC.DEFAULTS.TTL){const d=window.getToken(getPrimaryDnsId(),"admin");if(!d)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const i=buildDomain(g),m=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:i,ip:v,ttl:f,token:d,server:SITE.dnsIp})});if(!m.ok){const s=await m.text();throw new Error(`DNS API Error: ${m.status} - ${s}`)}const w=await m.json();if(!w.success)throw new Error(`DNS Error: ${w.error||"Unknown error"}`);return w}async function h(g){const v={id:g.subdomain,name:g.name,logo:g.logo||`/assets/${g.subdomain}.png`};g.category&&(v.category=g.category),g.containerId&&(v.containerId=g.containerId);try{const f=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!f.ok){const d=await f.json();throw new Error(d.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),v}catch(f){throw console.error("Failed to add service to config:",f),f}}async function b(g){const v=document.getElementById("service-subdomain-input").value.trim(),f=document.getElementById("service-ip-input").value.trim()||"localhost",d=document.getElementById("service-port-input").value.trim()||"80",i=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(v),upstream:`${f}:${d}`,config:g})}),m=await i.json();if(!i.ok||!m.success)throw new Error(m.error||`Caddy API Error: ${i.status}`);return m}window.loadExistingCAs=l,window.generateCaddyConfig=a,window.createDnsRecord=p,window.addServiceToConfig=h,window.addToCaddyfile=b})(),(function(){let l=null;function a(f){l=f;const d=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${f.name}`,document.getElementById("edit-service-name").value=f.name,document.getElementById("edit-service-url-display").textContent=f.url||buildServiceUrl(f.id),document.getElementById("edit-service-logo-preview").src=f.logo||`/assets/${f.id}.png`,document.getElementById("edit-subdomain").value=f.id,document.getElementById("edit-port").value=f.port||"",document.getElementById("edit-ip").value=f.ip||"localhost",document.getElementById("edit-tailscale-only").checked=f.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=f.logo||"";const i=document.getElementById("edit-service-category");i&&(i.dataset.current=f.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),d.classList.add("show")}function p(){closeModal("service-edit-modal"),l=null}async function h(){if(!l)return;const f=document.getElementById("edit-subdomain").value.trim().toLowerCase(),d=document.getElementById("edit-service-name").value.trim(),i=document.getElementById("edit-port").value.trim(),m=document.getElementById("edit-ip").value.trim()||"localhost",w=document.getElementById("edit-tailscale-only").checked,s=document.getElementById("edit-logo-url").value.trim(),t=document.getElementById("edit-service-category")?.value||"";if(!f){showNotification("Subdomain is required","warning");return}const e=l.id,n=[];if(f!==e&&n.push("subdomain"),d&&d!==l.name&&n.push("name"),i&&i!==String(l.port)&&n.push("port"),m!==l.ip&&n.push("ip"),w!==(l.tailscaleOnly||!1)&&n.push("tailscale"),s&&s!==l.logo&&n.push("logo"),t!==(l.category||"")&&n.push("category"),n.length===0){p();return}const u=document.getElementById("service-edit-save");u.textContent="Saving...",u.disabled=!0;try{const r=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:f,name:d||l.name,port:i||l.port,ip:m,tailscaleOnly:w,logo:s||void 0,category:t})})).json();if(!r.success)throw new Error(r.error||"Failed to update service");const c=window.APPS.findIndex(y=>y.id===e);c!==-1&&(window.APPS[c]={...window.APPS[c],id:f,name:d||window.APPS[c].name,port:i||window.APPS[c].port,ip:m,tailscaleOnly:w,logo:s||window.APPS[c].logo,category:t||void 0}),p(),window.buildGrid(),window.refreshAll()}catch(o){console.error("Error saving service changes:",o),showNotification(`Error saving changes: ${o.message}`,"error")}finally{u.textContent="Save Changes",u.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async f=>{const d=f.target.files[0];if(!d)return;if(!d.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const i=new FileReader;i.onload=async m=>{const w=m.target.result;if(document.getElementById("edit-service-logo-preview").src=w,document.getElementById("edit-logo-url").value=w,l)try{const t=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${l.id}.png`,data:w})})).json();t.success&&t.path&&(document.getElementById("edit-logo-url").val Line truncated
This will:
1. Pull the latest image
2. Stop the container
3. Recreate with same settings
The service will be briefly unavailable.`))try{f&&(f.textContent="\u{1F504}",f.disabled=!0,f.title="Updating...");const t=await(await secureFetch(`/api/v1/containers/${p}/update`,{method:"POST"})).json();if(t.success){const e=window.APPS.find(o=>o.id===r);e&&t.newContainerId&&(e.containerId=t.newContainerId),f&&(f.textContent="\u2705",f.title="Updated successfully!",setTimeout(()=>{f.textContent=w,f.disabled=!1,f.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${d} updated successfully!`,"success")}else throw new Error(t.error||"Update failed")}catch(s){console.error("Update error:",s),f&&(f.textContent="\u274C",f.title="Update failed",setTimeout(()=>{f.textContent=w,f.disabled=!1,f.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${d}: ${s.message}`,"error")}}async function v(p,d){const r=window.APPS.find(l=>l.id===p),f=r?buildDomain(r.id):null,w=r?.containerId,s=await b(d||p,w,r?.containerId);if(s===null)return;let t={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(s&&w)try{const l=new URLSearchParams({containerId:r.containerId,subdomain:r.id,ip:r.ip||"localhost",deleteContainer:"true"}),S=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(r.id)}?${l.toString()}`,{method:"DELETE"})).json();S.success?t={...t,...S.results,dashboard:!1}:console.error("App removal failed:",S.error)}catch(l){console.error("App removal error:",l)}else if(s&&f){try{const l=r?.ip||"localhost",S=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(f)}&type=A&ipAddress=${encodeURIComponent(l)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();t.dns=S.success?"deleted":S.error||"failed"}catch(l){t.dns=l.message}try{const y=await(await secureFetch(`/api/v1/site/${encodeURIComponent(f)}`,{method:"DELETE"})).json();t.caddy=y.success||y.error&&y.error.includes("not found")?"removed":y.error||"failed"}catch(l){t.caddy=l.message}}const e=window.APPS.findIndex(l=>l.id===p);e>-1&&(window.APPS.splice(e,1),t.dashboard=!0);try{const l=safeGetJSON("custom-apps",[]),y=l.findIndex(S=>S.id===p);y>-1&&(l.splice(y,1),safeSet("custom-apps",JSON.stringify(l)))}catch{}try{const y=await(await secureFetch(`/api/v1/services/${encodeURIComponent(p)}`,{method:"DELETE"})).json();t.service=y.success?"removed":y.error||"failed"}catch(l){t.service=l.message}window.buildGrid(),window.refreshAll();let o=!1,u=[];t.dashboard||(o=!0,u.push("\u2717 Failed to remove from dashboard"));const n=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],i=l=>!l||n.some(y=>l.toLowerCase().includes(y.toLowerCase()));t.container&&!i(t.container)&&(o=!0,u.push(`\u26A0 Container: ${t.container}`)),t.dns&&!i(t.dns)&&(o=!0,u.push(`\u26A0 DNS Record: ${t.dns}`)),t.caddy&&!i(t.caddy)&&(o=!0,u.push(`\u26A0 Caddy Config: ${t.caddy}`)),t.service&&!i(t.service)&&(o=!0,u.push(`\u26A0 Service File: ${t.service}`)),o&&showNotification(`Error deleting "${d||p}": ${u.join(", ")}`,"error",6e3)}window.openServiceEditModal=a,window.showDeleteModal=b,window.updateContainer=g,window.deleteService=v})(),(function(){function c(t){return t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function a(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function m(){const t=document.getElementById("service-subdomain-input").value||"subdomain",e=document.getElementById("service-ip-input").value||h.lan||"localhost",o=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,u=document.getElementById("ssl-type-select").value,n=document.getElementById("ca-name-input").value||"sami-ca",i=document.getElementById("existing-ca-select").value,l=document.getElementById("enable-auth").checked,y=document.getElementById("enable-cors").checked,S=document.getElementById("custom-headers-input").value,k=document.getElementById("upstream-path-input").value||"/",L=document.getElementById("health-check-input").value,x=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(t)} \u2192 ${e}`);const A=document.getElementById("url-preview");A&&(A.textContent=buildServiceUrl(t));const E={subdomain:t,port:o,ip:e,sslType:u,caName:n,existingCa:i,enableAuth:l,enableCors:y,customHeaders:S,upstreamPath:k,healthCheck:L,timeout:x},C=window.generateCaddyConfig(E),T=document.getElementById("caddy-config-preview");T&&(T.value=C)}const h={localhost:"127.0.0.1",lan:"",tailscale:""};async function b(){try{const u=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(u.ok){const n=await u.json();n.lan&&(h.lan=n.lan),n.tailscale&&(h.tailscale=n.tailscale)}}catch{}const t=document.getElementById("quick-ip-lan"),e=document.getElementById("quick-ip-tailscale");t&&(h.lan?(t.dataset.ip=h.lan,t.textContent=`LAN (${h.lan})`,t.title=`LAN IP: ${h.lan}`):t Line truncated
The service will be briefly unavailable.`))try{m&&(m.textContent="\u{1F504}",m.disabled=!0,m.title="Updating...");const t=await(await secureFetch(`/api/v1/containers/${f}/update`,{method:"POST"})).json();if(t.success){const e=window.APPS.find(n=>n.id===i);e&&t.newContainerId&&(e.containerId=t.newContainerId),m&&(m.textContent="\u2705",m.title="Updated successfully!",setTimeout(()=>{m.textContent=w,m.disabled=!1,m.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${d} updated successfully!`,"success")}else throw new Error(t.error||"Update failed")}catch(s){console.error("Update error:",s),m&&(m.textContent="\u274C",m.title="Update failed",setTimeout(()=>{m.textContent=w,m.disabled=!1,m.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${d}: ${s.message}`,"error")}}async function v(f,d){const i=window.APPS.find(c=>c.id===f),m=i?buildDomain(i.id):null,w=i?.containerId,s=await b(d||f,w,i?.containerId);if(s===null)return;let t={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(s&&w)try{const c=new URLSearchParams({containerId:i.containerId,subdomain:i.id,ip:i.ip||"localhost",deleteContainer:"true"}),S=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(i.id)}?${c.toString()}`,{method:"DELETE"})).json();S.success?t={...t,...S.results,dashboard:!1}:console.error("App removal failed:",S.error)}catch(c){console.error("App removal error:",c)}else if(s&&m){try{const c=i?.ip||"localhost",S=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(m)}&type=A&ipAddress=${encodeURIComponent(c)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();t.dns=S.success?"deleted":S.error||"failed"}catch(c){t.dns=c.message}try{const y=await(await secureFetch(`/api/v1/site/${encodeURIComponent(m)}`,{method:"DELETE"})).json();t.caddy=y.success||y.error&&y.error.includes("not found")?"removed":y.error||"failed"}catch(c){t.caddy=c.message}}const e=window.APPS.findIndex(c=>c.id===f);e>-1&&(window.APPS.splice(e,1),t.dashboard=!0);try{const c=safeGetJSON("custom-apps",[]),y=c.findIndex(S=>S.id===f);y>-1&&(c.splice(y,1),safeSet("custom-apps",JSON.stringify(c)))}catch{}try{const y=await(await secureFetch(`/api/v1/services/${encodeURIComponent(f)}`,{method:"DELETE"})).json();t.service=y.success?"removed":y.error||"failed"}catch(c){t.service=c.message}window.buildGrid(),window.refreshAll();let n=!1,u=[];t.dashboard||(n=!0,u.push("\u2717 Failed to remove from dashboard"));const o=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],r=c=>!c||o.some(y=>c.toLowerCase().includes(y.toLowerCase()));t.container&&!r(t.container)&&(n=!0,u.push(`\u26A0 Container: ${t.container}`)),t.dns&&!r(t.dns)&&(n=!0,u.push(`\u26A0 DNS Record: ${t.dns}`)),t.caddy&&!r(t.caddy)&&(n=!0,u.push(`\u26A0 Caddy Config: ${t.caddy}`)),t.service&&!r(t.service)&&(n=!0,u.push(`\u26A0 Service File: ${t.service}`)),n&&showNotification(`Error deleting "${d||f}": ${u.join(", ")}`,"error",6e3)}window.openServiceEditModal=a,window.showDeleteModal=b,window.updateContainer=g,window.deleteService=v})(),(function(){function l(t){return t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function a(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function p(){const t=document.getElementById("service-subdomain-input").value||"subdomain",e=document.getElementById("service-ip-input").value||h.lan||"localhost",n=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,u=document.getElementById("ssl-type-select").value,o=document.getElementById("ca-name-input").value||"sami-ca",r=document.getElementById("existing-ca-select").value,c=document.getElementById("enable-auth").checked,y=document.getElementById("enable-cors").checked,S=document.getElementById("custom-headers-input").value,k=document.getElementById("upstream-path-input").value||"/",L=document.getElementById("health-check-input").value,x=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(t)} \u2192 ${e}`);const A=document.getElementById("url-preview");A&&(A.textContent=buildServiceUrl(t));const E={subdomain:t,port:n,ip:e,sslType:u,caName:o,existingCa:r,enableAuth:c,enableCors:y,customHeaders:S,upstreamPath:k,healthCheck:L,timeout:x},C=window.generateCaddyConfig(E),T=document.getElementById("caddy-config-preview");T&&(T.value=C)}const h={localhost:"127.0.0.1",lan:"",tailscale:""};async function b(){try{const u=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(u.ok){const o=await u.json();o.lan&&(h.lan=o.lan),o.tailscale&&(h.tailscale=o.tailscale)}}catch{}const t=document.getElementById("quick-ip-lan"),e=document.getElementById("quick-ip-tailscale");t&&(h.lan?(t.dataset.ip=h.lan,t.textContent=`LAN (${h.lan})`,t.title=`LAN IP: ${h.lan}`):t Line truncated
<span style="color: #4caf50;">\u2713 Connected</span>
<span style="color: var(--muted); margin-left: 6px;">${y.self?.hostname} (${y.self?.ip})</span>
`,i.disabled=!1):y.installed?(n.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',i.disabled=!0):(n.innerHTML='<span style="color: var(--muted);">Not available</span>',i.disabled=!0)}catch{n.innerHTML='<span style="color: var(--muted);">Could not check</span>',i.disabled=!0}i.checked=!1,m()}function p(){const t=document.getElementById("service-type-local"),e=document.getElementById("service-type-external"),o=document.getElementById("local-service-config"),u=document.getElementById("external-service-config"),n=document.getElementById("tab-local"),i=document.getElementById("tab-external");function l(){t.checked?(o.style.display="grid",u.style.display="none",n&&(n.style.background="var(--accent)",n.style.color="var(--bg)"),i&&(i.style.background="transparent",i.style.color="var(--muted)")):(o.style.display="none",u.style.display="block",i&&(i.style.background="var(--accent)",i.style.color="var(--bg)"),n&&(n.style.background="transparent",n.style.color="var(--muted)"))}t?.addEventListener("change",l),e?.addEventListener("change",l)}function d(){const t=document.getElementById("service-name-input"),e=document.getElementById("service-subdomain-input"),o=document.getElementById("subdomain-preview");let u=!1;t?.addEventListener("input",()=>{const k=c(t.value);!u&&e&&(e.value=k),o&&(o.textContent=k?`\u2192 ${buildDomain(k)}`:""),m()}),e?.addEventListener("input",()=>{u=e.value!==c(t?.value||"");const k=e.value.trim()||c(t?.value||"");o&&(o.textContent=k?`\u2192 ${buildDomain(k)}`:""),m()});const n=document.getElementById("external-service-name"),i=document.getElementById("external-service-subdomain"),l=document.getElementById("external-subdomain-preview"),y=document.getElementById("external-domain-preview");let S=!1;n?.addEventListener("input",()=>{const k=c(n.value);!S&&i&&(i.value=k);const L=i?.value||k;l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),y&&(y.textContent=L?buildDomain(L):"")}),i?.addEventListener("input",()=>{S=i.value!==c(n?.value||"");const k=i.value.trim()||c(n?.value||"");l&&(l.textContent=k?`\u2192 ${buildDomain(k)}`:""),y&&(y.textContent=k?buildDomain(k):"")})}async function r(){const t=document.getElementById("external-service-name").value.trim(),e=document.getElementById("external-service-url").value.trim(),o=(document.getElementById("external-service-subdomain").value.trim()||c(t)).toLowerCase(),u=document.getElementById("external-service-logo").value.trim(),n=document.getElementById("external-service-icon").value.trim(),i=document.getElementById("external-create-dns").checked,l=document.getElementById("external-create-caddy").checked,y=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",S=document.getElementById("external-preserve-host").checked,k=document.getElementById("external-follow-redirects").checked,L=document.getElementById("external-service-category")?.value||"";if(!t||!e){showNotification("Please fill in Name and External URL","warning");return}if(!o){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!e.startsWith("http://")&&!e.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const x=buildDomain(o);try{const B={dns:null,caddy:null,dashboard:!1};if(i)if(window.getToken(getPrimaryDnsId(),"admin"))try{const P=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:x,ip:y,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=P.success?"created":P.error||"failed"}catch(I){B.dns=I.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(l)try{const $={subdomain:o,externalUrl:e,preserveHost:S,followRedirects:k,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},P=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})).json();B.caddy=P.success?"created":P.error||"failed"}catch($){B.caddy=$.message}const A={id:o,name:t,url:`https://${x}`,externalUrl:e,logo:u||n||"\u{1F310}",isExternal:!0,isCustom:!0};L&&(A.category=L),window.APPS.push(A),B.dashboard=!0;const E=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],C=window.APPS.filter($=>!E.includes($.id));safeSet("custom-services",JSON.stringify(C));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch($){console.warn("Failed to save to services.json:",$)}window.buildGrid(),window.refreshAll(),f();const T=[`External service "${t}" added!`];i&&T.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),l&&T.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),T.push(`Access at: https://${x}`),showNotification(T.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLyoqXG4gKiBFcnJvciBIYW5kbGVyXG4gKiBIYW5kbGVzIGVycm9ycyBncmFjZWZ1bGx5IHdpdGhvdXQgYnJlYWtpbmcgdGhlIG9uYm9hcmRpbmcgdG91clxuICovXG5cbihmdW5jdGlvbih3aW5kb3cpIHtcbiAgJ3VzZSBzdHJpY3QnO1xuXG4gIGNsYXNzIEVycm9ySGFuZGxlciB7XG4gICAgY29uc3RydWN0b3IoKSB7XG4gICAgICB0aGlzLmVycm9ycyA9IFtdO1xuICAgICAgdGhpcy5tYXhFcnJvcnMgPSA1MDsgLy8gS2VlcCBsYXN0IDUwIGVycm9yc1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIExvZyBhbiBlcnJvciB3aXRob3V0IGJyZWFraW5nIHRoZSB0b3VyXG4gICAgICogQHBhcmFtIHtzdHJpbmd9IGNvbnRleHQgLSBDb250ZXh0IHdoZXJlIGVycm9yIG9jY3VycmVkXG4gICAgICogQHBhcmFtIHtFcnJvcnxzdHJpbmd9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdCBvciBtZXNzYWdlXG4gICAgICogQHBhcmFtIHtPYmplY3R9IG1ldGFkYXRhIC0gQWRkaXRpb25hbCBtZXRhZGF0YVxuICAgICAqL1xuICAgIGxvZ0Vycm9yKGNvbnRleHQsIGVycm9yLCBtZXRhZGF0YSA9IHt9KSB7XG4gICAgICBjb25zdCBlcnJvckVudHJ5ID0ge1xuICAgICAgICB0aW1lc3RhbXA6IG5ldyBEYXRlKCkudG9JU09TdHJpbmcoKSxcbiAgICAgICAgY29udGV4dCxcbiAgICAgICAgbWVzc2FnZTogZXJyb3IgaW5zdGFuY2VvZiBFcnJvciA/IGVycm9yLm1lc3NhZ2UgOiBlcnJvcixcbiAgICAgICAgc3RhY2s6IGVycm9yIGluc3RhbmNlb2YgRXJyb3IgPyBlcnJvci5zdGFjayA6IG51bGwsXG4gICAgICAgIG1ldGFkYXRhXG4gICAgICB9O1xuXG4gICAgICAvLyBBZGQgdG8gZXJyb3JzIGFycmF5XG4gICAgICB0aGlzLmVycm9ycy5wdXNoKGVycm9yRW50cnkpO1xuXG4gICAgICAvLyBLZWVwIG9ubHkgbGFzdCBtYXhFcnJvcnNcbiAgICAgIGlmICh0aGlzLmVycm9ycy5sZW5ndGggPiB0aGlzLm1heEVycm9ycykge1xuICAgICAgICB0aGlzLmVycm9ycy5zaGlmdCgpO1xuICAgICAgfVxuXG4gICAgICAvLyBMb2cgdG8gY29uc29sZVxuICAgICAgY29uc29sZS5lcnJvcihgW09uYm9hcmRpbmcgRXJyb3JdICR7Y29udGV4dH06YCwgZXJyb3IsIG1ldGFkYXRhKTtcblxuICAgICAgLy8gT3B0aW9uYWxseSBzZW5kIHRvIGVycm9yIHRyYWNraW5nIHNlcnZpY2VcbiAgICAgIC8vIHRoaXMuc2VuZFRvRXJyb3JUcmFja2luZyhlcnJvckVudHJ5KTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBBdHRlbXB0IHRvIHJlY292ZXIgZnJvbSBhbiBlcnJvciBhbmQgY29udGludWUgdG91clxuICAgICAqIEBwYXJhbSB7RXJyb3J9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdFxuICAgICAqIEBwYXJhbSB7bnVtYmVyfSBjdXJyZW50U3RlcCAtIEN1cnJlbnQgc3RlcCBpbmRleFxuICAgICAqIEByZXR1cm5zIHtPYmplY3R9IFJlY292ZXJ5IGFjdGlvblxuICAgICAqL1xuICAgIHJlY292ZXJGcm9tRXJyb3IoZXJyb3IsIGN1cnJlbnRTdGVwKSB7XG4gICAgICBjb25zdCBlcnJvclR5cGUgPSB0aGlzLmNsYXNzaWZ5RXJyb3IoZXJyb3IpO1xuXG4gICAgICBzd2l0Y2ggKGVycm9yVHlwZSkge1xuICAgICAgICBjYXNlICdFTEVNRU5UX05PVF9GT1VORCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignRWxlbWVudCBOb3QgRm91bmQnLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4geyBcbiAgICAgICAgICAgIGFjdGlvbjogJ1NLSVBfU1RFUCcsIFxuICAgICAgICAgICAgbmV4dFN0ZXA6IGN1cnJlbnRTdGVwICsgMSxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdUYXJnZXQgZWxlbWVudCBub3QgZm91bmQsIHNraXBwaW5nIHRvIG5leHQgc3RlcCdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ1NUT1JBR0VfVU5BVkFJTEFCTEUnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ1N0b3JhZ2UgVW5hdmFpbGFibGUnLCBlcnJvcik7XG4gICAgICAgICAgcmV0dXJuIHsgXG4gICAgICAgICAgICBhY3Rpb246ICdVU0VfTUVNT1JZX1NUT1JBR0UnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ0xvY2FsIHN0b3JhZ2UgdW5hdmFpbGFibGUsIHVzaW5nIGluLW1lbW9yeSBzdG9yYWdlJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnRFJJVkVSX05PVF9MT0FERUQnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ0RyaXZlci5qcyBOb3QgTG9hZGVkJywgZXJyb3IpO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdEcml2ZXIuanMgbGlicmFyeSBub3QgbG9hZGVkLCBjYW5ub3Qgc3RhcnQgdG91cidcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ0lOVkFMSURfVE9PTFRJUCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignSW52YWxpZCBUb29sdGlwIENvbmZpZ3VyYXRpb24nLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnU0tJUF9TVEVQJyxcbiAgICAgICAgICAgIG5leHRTdGVwOiBjdXJyZW50U3RlcCArIDEsXG4gICAgICAgICAgICBtZXNzYWdlOiAnSW52YWxpZCB0b29sdGlwIGNvbmZpZ3VyYXRpb24sIHNraXBwaW5nJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnVEhFTUVfREVURUNUSU9OX0ZBSUxFRCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVGhlbWUgRGV0ZWN0aW9uIEZhaWxlZCcsIGVycm9yKTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnVVNFX0RFRkFVTFRfVEhFTUUnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ1VzaW5nIGRlZmF1bHQgZGFyayB0aGVtZSdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVW5rbm93biBFcnJvcicsIGVycm9yLCB7IGN1cnJlbnRTdGVwIH0pO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdVbmV4cGVjdGVkIGVycm9yIG9jY3VycmVkLCBhYm9ydGluZyB0b3VyJ1xuICAgICAgICAgIH07XG4gICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQ2xhc3NpZnkgZXJyb3IgdHlwZVxuICAgICAqIEBwcml2YXRlXG4gICAgICogQHBhcmFtIHtFcnJvcn0gZXJyb3IgLSBUaGUgZXJyb3Igb2JqZWN0XG4gICAgICogQHJldHVybnMge3N0cmluZ30gRXJyb3IgdHlwZVxuICAgICAqL1xuICAgIGNsYXNzaWZ5RXJyb3IoZXJyb3IpIHtcbiAgICAgIGNvbnN0IG1lc3NhZ2UgPSBlcnJvci5tZXNzYWdlIHx8IGVycm9yLnRvU3RyaW5nKCk7XG5cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdlbGVtZW50JykgJiYgbWVzc2FnZS5pbmNsdWRlcygnbm90IGZvdW5kJykpIHtcbiAgICAgICAgcmV0dXJuICdFTEVNRU5UX05PVF9GT1VORCc7XG4gICAgICB9XG4gICAgICBpZiAobWVzc2FnZS5pbmNsdWRlcygnc3RvcmFnZScpIHx8IG1lc3NhZ2UuaW5jbHVkZXMoJ3F1b3RhJykpIHtcbiAgICAgICAgcmV0dXJuICdTVE9SQUdFX1VOQVZBSUxBQkxFJztcbiAgICAgIH1cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdkcml2ZXInKSB8fCBtZXNzYWdlLmluY2x1ZGVzKCd1bmRlZmluZWQnKSkge1xuICAgI Line truncated
`,r.disabled=!1):y.installed?(o.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',r.disabled=!0):(o.innerHTML='<span style="color: var(--muted);">Not available</span>',r.disabled=!0)}catch{o.innerHTML='<span style="color: var(--muted);">Could not check</span>',r.disabled=!0}r.checked=!1,p()}function f(){const t=document.getElementById("service-type-local"),e=document.getElementById("service-type-external"),n=document.getElementById("local-service-config"),u=document.getElementById("external-service-config"),o=document.getElementById("tab-local"),r=document.getElementById("tab-external");function c(){t.checked?(n.style.display="grid",u.style.display="none",o&&(o.style.background="var(--accent)",o.style.color="var(--bg)"),r&&(r.style.background="transparent",r.style.color="var(--muted)")):(n.style.display="none",u.style.display="block",r&&(r.style.background="var(--accent)",r.style.color="var(--bg)"),o&&(o.style.background="transparent",o.style.color="var(--muted)"))}t?.addEventListener("change",c),e?.addEventListener("change",c)}function d(){const t=document.getElementById("service-name-input"),e=document.getElementById("service-subdomain-input"),n=document.getElementById("subdomain-preview");let u=!1;t?.addEventListener("input",()=>{const k=l(t.value);!u&&e&&(e.value=k),n&&(n.textContent=k?`\u2192 ${buildDomain(k)}`:""),p()}),e?.addEventListener("input",()=>{u=e.value!==l(t?.value||"");const k=e.value.trim()||l(t?.value||"");n&&(n.textContent=k?`\u2192 ${buildDomain(k)}`:""),p()});const o=document.getElementById("external-service-name"),r=document.getElementById("external-service-subdomain"),c=document.getElementById("external-subdomain-preview"),y=document.getElementById("external-domain-preview");let S=!1;o?.addEventListener("input",()=>{const k=l(o.value);!S&&r&&(r.value=k);const L=r?.value||k;c&&(c.textContent=L?`\u2192 ${buildDomain(L)}`:""),y&&(y.textContent=L?buildDomain(L):"")}),r?.addEventListener("input",()=>{S=r.value!==l(o?.value||"");const k=r.value.trim()||l(o?.value||"");c&&(c.textContent=k?`\u2192 ${buildDomain(k)}`:""),y&&(y.textContent=k?buildDomain(k):"")})}async function i(){const t=document.getElementById("external-service-name").value.trim(),e=document.getElementById("external-service-url").value.trim(),n=(document.getElementById("external-service-subdomain").value.trim()||l(t)).toLowerCase(),u=document.getElementById("external-service-logo").value.trim(),o=document.getElementById("external-service-icon").value.trim(),r=document.getElementById("external-create-dns").checked,c=document.getElementById("external-create-caddy").checked,y=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",S=document.getElementById("external-preserve-host").checked,k=document.getElementById("external-follow-redirects").checked,L=document.getElementById("external-service-category")?.value||"";if(!t||!e){showNotification("Please fill in Name and External URL","warning");return}if(!n){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!e.startsWith("http://")&&!e.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const x=buildDomain(n);try{const B={dns:null,caddy:null,dashboard:!1};if(r)if(window.getToken(getPrimaryDnsId(),"admin"))try{const P=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:x,ip:y,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=P.success?"created":P.error||"failed"}catch(I){B.dns=I.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(c)try{const $={subdomain:n,externalUrl:e,preserveHost:S,followRedirects:k,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},P=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})).json();B.caddy=P.success?"created":P.error||"failed"}catch($){B.caddy=$.message}const A={id:n,name:t,url:`https://${x}`,externalUrl:e,logo:u||o||"\u{1F310}",isExternal:!0,isCustom:!0};L&&(A.category=L),window.APPS.push(A),B.dashboard=!0;const E=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],C=window.APPS.filter($=>!E.includes($.id));safeSet("custom-services",JSON.stringify(C));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch($){console.warn("Failed to save to services.json:",$)}window.buildGrid(),window.refreshAll(),m();const T=[`External service "${t}" added!`];r&&T.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),c&&T.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),T.push(`Access at: https://${x}`),showNotification(T.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLyoqXG4gKiBFcnJvciBIYW5kbGVyXG4gKiBIYW5kbGVzIGVycm9ycyBncmFjZWZ1bGx5IHdpdGhvdXQgYnJlYWtpbmcgdGhlIG9uYm9hcmRpbmcgdG91clxuICovXG5cbihmdW5jdGlvbih3aW5kb3cpIHtcbiAgJ3VzZSBzdHJpY3QnO1xuXG4gIGNsYXNzIEVycm9ySGFuZGxlciB7XG4gICAgY29uc3RydWN0b3IoKSB7XG4gICAgICB0aGlzLmVycm9ycyA9IFtdO1xuICAgICAgdGhpcy5tYXhFcnJvcnMgPSA1MDsgLy8gS2VlcCBsYXN0IDUwIGVycm9yc1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIExvZyBhbiBlcnJvciB3aXRob3V0IGJyZWFraW5nIHRoZSB0b3VyXG4gICAgICogQHBhcmFtIHtzdHJpbmd9IGNvbnRleHQgLSBDb250ZXh0IHdoZXJlIGVycm9yIG9jY3VycmVkXG4gICAgICogQHBhcmFtIHtFcnJvcnxzdHJpbmd9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdCBvciBtZXNzYWdlXG4gICAgICogQHBhcmFtIHtPYmplY3R9IG1ldGFkYXRhIC0gQWRkaXRpb25hbCBtZXRhZGF0YVxuICAgICAqL1xuICAgIGxvZ0Vycm9yKGNvbnRleHQsIGVycm9yLCBtZXRhZGF0YSA9IHt9KSB7XG4gICAgICBjb25zdCBlcnJvckVudHJ5ID0ge1xuICAgICAgICB0aW1lc3RhbXA6IG5ldyBEYXRlKCkudG9JU09TdHJpbmcoKSxcbiAgICAgICAgY29udGV4dCxcbiAgICAgICAgbWVzc2FnZTogZXJyb3IgaW5zdGFuY2VvZiBFcnJvciA/IGVycm9yLm1lc3NhZ2UgOiBlcnJvcixcbiAgICAgICAgc3RhY2s6IGVycm9yIGluc3RhbmNlb2YgRXJyb3IgPyBlcnJvci5zdGFjayA6IG51bGwsXG4gICAgICAgIG1ldGFkYXRhXG4gICAgICB9O1xuXG4gICAgICAvLyBBZGQgdG8gZXJyb3JzIGFycmF5XG4gICAgICB0aGlzLmVycm9ycy5wdXNoKGVycm9yRW50cnkpO1xuXG4gICAgICAvLyBLZWVwIG9ubHkgbGFzdCBtYXhFcnJvcnNcbiAgICAgIGlmICh0aGlzLmVycm9ycy5sZW5ndGggPiB0aGlzLm1heEVycm9ycykge1xuICAgICAgICB0aGlzLmVycm9ycy5zaGlmdCgpO1xuICAgICAgfVxuXG4gICAgICAvLyBMb2cgdG8gY29uc29sZVxuICAgICAgY29uc29sZS5lcnJvcihgW09uYm9hcmRpbmcgRXJyb3JdICR7Y29udGV4dH06YCwgZXJyb3IsIG1ldGFkYXRhKTtcblxuICAgICAgLy8gT3B0aW9uYWxseSBzZW5kIHRvIGVycm9yIHRyYWNraW5nIHNlcnZpY2VcbiAgICAgIC8vIHRoaXMuc2VuZFRvRXJyb3JUcmFja2luZyhlcnJvckVudHJ5KTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBBdHRlbXB0IHRvIHJlY292ZXIgZnJvbSBhbiBlcnJvciBhbmQgY29udGludWUgdG91clxuICAgICAqIEBwYXJhbSB7RXJyb3J9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdFxuICAgICAqIEBwYXJhbSB7bnVtYmVyfSBjdXJyZW50U3RlcCAtIEN1cnJlbnQgc3RlcCBpbmRleFxuICAgICAqIEByZXR1cm5zIHtPYmplY3R9IFJlY292ZXJ5IGFjdGlvblxuICAgICAqL1xuICAgIHJlY292ZXJGcm9tRXJyb3IoZXJyb3IsIGN1cnJlbnRTdGVwKSB7XG4gICAgICBjb25zdCBlcnJvclR5cGUgPSB0aGlzLmNsYXNzaWZ5RXJyb3IoZXJyb3IpO1xuXG4gICAgICBzd2l0Y2ggKGVycm9yVHlwZSkge1xuICAgICAgICBjYXNlICdFTEVNRU5UX05PVF9GT1VORCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignRWxlbWVudCBOb3QgRm91bmQnLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4geyBcbiAgICAgICAgICAgIGFjdGlvbjogJ1NLSVBfU1RFUCcsIFxuICAgICAgICAgICAgbmV4dFN0ZXA6IGN1cnJlbnRTdGVwICsgMSxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdUYXJnZXQgZWxlbWVudCBub3QgZm91bmQsIHNraXBwaW5nIHRvIG5leHQgc3RlcCdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ1NUT1JBR0VfVU5BVkFJTEFCTEUnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ1N0b3JhZ2UgVW5hdmFpbGFibGUnLCBlcnJvcik7XG4gICAgICAgICAgcmV0dXJuIHsgXG4gICAgICAgICAgICBhY3Rpb246ICdVU0VfTUVNT1JZX1NUT1JBR0UnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ0xvY2FsIHN0b3JhZ2UgdW5hdmFpbGFibGUsIHVzaW5nIGluLW1lbW9yeSBzdG9yYWdlJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnRFJJVkVSX05PVF9MT0FERUQnOlxuICAgICAgICAgIHRoaXMubG9nRXJyb3IoJ0RyaXZlci5qcyBOb3QgTG9hZGVkJywgZXJyb3IpO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdEcml2ZXIuanMgbGlicmFyeSBub3QgbG9hZGVkLCBjYW5ub3Qgc3RhcnQgdG91cidcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGNhc2UgJ0lOVkFMSURfVE9PTFRJUCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignSW52YWxpZCBUb29sdGlwIENvbmZpZ3VyYXRpb24nLCBlcnJvciwgeyBjdXJyZW50U3RlcCB9KTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnU0tJUF9TVEVQJyxcbiAgICAgICAgICAgIG5leHRTdGVwOiBjdXJyZW50U3RlcCArIDEsXG4gICAgICAgICAgICBtZXNzYWdlOiAnSW52YWxpZCB0b29sdGlwIGNvbmZpZ3VyYXRpb24sIHNraXBwaW5nJ1xuICAgICAgICAgIH07XG5cbiAgICAgICAgY2FzZSAnVEhFTUVfREVURUNUSU9OX0ZBSUxFRCc6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVGhlbWUgRGV0ZWN0aW9uIEZhaWxlZCcsIGVycm9yKTtcbiAgICAgICAgICByZXR1cm4ge1xuICAgICAgICAgICAgYWN0aW9uOiAnVVNFX0RFRkFVTFRfVEhFTUUnLFxuICAgICAgICAgICAgbWVzc2FnZTogJ1VzaW5nIGRlZmF1bHQgZGFyayB0aGVtZSdcbiAgICAgICAgICB9O1xuXG4gICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgdGhpcy5sb2dFcnJvcignVW5rbm93biBFcnJvcicsIGVycm9yLCB7IGN1cnJlbnRTdGVwIH0pO1xuICAgICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBhY3Rpb246ICdBQk9SVF9UT1VSJyxcbiAgICAgICAgICAgIG1lc3NhZ2U6ICdVbmV4cGVjdGVkIGVycm9yIG9jY3VycmVkLCBhYm9ydGluZyB0b3VyJ1xuICAgICAgICAgIH07XG4gICAgICB9XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogQ2xhc3NpZnkgZXJyb3IgdHlwZVxuICAgICAqIEBwcml2YXRlXG4gICAgICogQHBhcmFtIHtFcnJvcn0gZXJyb3IgLSBUaGUgZXJyb3Igb2JqZWN0XG4gICAgICogQHJldHVybnMge3N0cmluZ30gRXJyb3IgdHlwZVxuICAgICAqL1xuICAgIGNsYXNzaWZ5RXJyb3IoZXJyb3IpIHtcbiAgICAgIGNvbnN0IG1lc3NhZ2UgPSBlcnJvci5tZXNzYWdlIHx8IGVycm9yLnRvU3RyaW5nKCk7XG5cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdlbGVtZW50JykgJiYgbWVzc2FnZS5pbmNsdWRlcygnbm90IGZvdW5kJykpIHtcbiAgICAgICAgcmV0dXJuICdFTEVNRU5UX05PVF9GT1VORCc7XG4gICAgICB9XG4gICAgICBpZiAobWVzc2FnZS5pbmNsdWRlcygnc3RvcmFnZScpIHx8IG1lc3NhZ2UuaW5jbHVkZXMoJ3F1b3RhJykpIHtcbiAgICAgICAgcmV0dXJuICdTVE9SQUdFX1VOQVZBSUxBQkxFJztcbiAgICAgIH1cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdkcml2ZXInKSB8fCBtZXNzYWdlLmluY2x1ZGVzKCd1bmRlZmluZWQnKSkge1xuICAgI Line truncated
+254 -254
View File
@@ -67,7 +67,7 @@
<div class="mb-16">
<label class="form-label-bold">Favicon (Browser Tab Icon):</label>
<div id="favicon-preview-container" style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px; padding: 12px; border-radius: 6px; background: var(--card-bg);">
<img id="favicon-preview" src="/assets/dashcaddy-favicon.ico" alt="Current favicon" style="width: 32px; height: 32px; image-rendering: pixelated;" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22><rect fill=%22%23667%22 width=%2232%22 height=%2232%22 rx=%224%22/></svg>'" />
<img id="favicon-preview" src="/assets/dashcaddy-favicon.ico" alt="Current favicon" style="width: 32px; height: 32px; image-rendering: pixelated;" />
<span id="favicon-status" class="text-tiny-muted">Using DashCaddy favicon</span>
</div>
<input type="file" id="favicon-upload" accept="image/png,image/svg+xml" class="input-card-alt" />
@@ -90,44 +90,44 @@
<button id="logo-save" class="btn-accent">Save</button>
</div>
</div>
</div>`);const x=document.getElementById("logo-modal"),b=document.getElementById("logo-preview-dark"),j=document.getElementById("logo-preview-light"),g=document.getElementById("logo-status"),N=document.getElementById("logo-same-both"),A=document.getElementById("logo-dual-uploads"),D=document.getElementById("logo-single-upload"),R=document.getElementById("logo-upload-dark"),f=document.getElementById("logo-upload-light"),C=document.getElementById("logo-upload-single"),E=document.querySelector("#brand .brand-logo-dark"),M=document.querySelector("#brand .brand-logo-light"),w=document.querySelector(".top-row"),z=document.getElementById("dashboard-title"),S=DC.NAME;let T=null,P=null,v=null,B="left",H=S;N?.addEventListener("change",()=>{N.checked?(A.style.display="none",D.style.display="",T=null,P=null):(A.style.display="flex",D.style.display="none",v=null)});function O(n,e){if(!n||!n.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const r=new FileReader;r.onload=s=>e(s.target.result),r.readAsDataURL(n)}R?.addEventListener("change",n=>{O(n.target.files[0],e=>{T=e,b.src=e,g.textContent="New dark logo ready to save"})}),f?.addEventListener("change",n=>{O(n.target.files[0],e=>{P=e,j.src=e,g.textContent="New light logo ready to save"})}),C?.addEventListener("change",n=>{O(n.target.files[0],e=>{v=e,b.src=e,j.src=e,g.textContent="New logo ready to save (both themes)"})});function u(n){w.setAttribute("data-logo-pos",n),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===n?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===n?"white":"var(--fg)"})}function m(n){H=n||S,document.title=H;const e=document.querySelector(".dashboard-title");e&&(e.textContent=H)}async function L(){try{const n=await fetch("/api/v1/logo");if(n.ok){const e=await n.json();e.customLogoDark&&(E.src=e.customLogoDark,b.src=e.customLogoDark),e.customLogoLight&&(M.src=e.customLogoLight,j.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(E.src=e.customLogo,M.src=e.customLogo,b.src=e.customLogo,j.src=e.customLogo),e.isDefault||(g.textContent="Using custom logo"),e.position&&(B=e.position,u(e.position)),e.dashboardTitle&&m(e.dashboardTitle)}}catch(n){console.warn("Could not load custom logo:",n.message)}}document.querySelectorAll(".logo-pos-btn").forEach(n=>{n.addEventListener("click",()=>{B=n.dataset.pos,u(B)})}),document.getElementById("brand")?.addEventListener("click",()=>{T=null,P=null,v=null,R&&(R.value=""),f&&(f.value=""),C&&(C.value=""),N&&(N.checked=!1),A.style.display="flex",D.style.display="none",b.src=E.src,j.src=M.src;const n=E.src.includes("custom-logo")||M.src.includes("custom-logo");g.textContent=n?"Using custom logo":"Using default logos",u(B),z.value=H,x.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const n=z.value.trim()||S,e={position:B,dashboardTitle:n};N?.checked&&v?(e.dataDark=v,e.dataLight=v):(T&&(e.dataDark=T),P&&(e.dataLight=P));const r=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(r.ok){const s=await r.json(),a="?t="+Date.now();s.pathDark&&(E.src=s.pathDark+a,b.src=s.pathDark+a),s.pathLight&&(M.src=s.pathLight+a,j.src=s.pathLight+a),u(B),m(n),x.classList.remove("show")}else{const s=await r.json();showNotification("Failed to save: "+s.error,"error")}}catch(n){showNotification("Error saving: "+n.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults?
</div>`);const w=document.getElementById("logo-modal"),x=document.getElementById("logo-preview-dark"),j=document.getElementById("logo-preview-light"),g=document.getElementById("logo-status"),N=document.getElementById("logo-same-both"),P=document.getElementById("logo-dual-uploads"),M=document.getElementById("logo-single-upload"),R=document.getElementById("logo-upload-dark"),h=document.getElementById("logo-upload-light"),C=document.getElementById("logo-upload-single"),E=document.querySelector("#brand .brand-logo-dark"),H=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),z=document.getElementById("dashboard-title"),S=DC.NAME;let T=null,D=null,y=null,B="left",$=S;N?.addEventListener("change",()=>{N.checked?(P.style.display="none",M.style.display="",T=null,D=null):(P.style.display="flex",M.style.display="none",y=null)});function U(e,s){if(!e||!e.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const r=new FileReader;r.onload=o=>s(o.target.result),r.readAsDataURL(e)}R?.addEventListener("change",e=>{U(e.target.files[0],s=>{T=s,x.src=s,g.textContent="New dark logo ready to save"})}),h?.addEventListener("change",e=>{U(e.target.files[0],s=>{D=s,j.src=s,g.textContent="New light logo ready to save"})}),C?.addEventListener("change",e=>{U(e.target.files[0],s=>{y=s,x.src=s,j.src=s,g.textContent="New logo ready to save (both themes)"})});function m(e){k.setAttribute("data-logo-pos",e),document.querySelectorAll(".logo-pos-btn").forEach(s=>{s.style.background=s.dataset.pos===e?"var(--accent)":"var(--card-bg)",s.style.color=s.dataset.pos===e?"white":"var(--fg)"})}function v(e){$=e||S,document.title=$;const s=document.querySelector(".dashboard-title");s&&(s.textContent=$)}async function I(){try{const e=await fetch("/api/v1/logo");if(e.ok){const s=await e.json();s.customLogoDark&&(E.src=s.customLogoDark,x.src=s.customLogoDark),s.customLogoLight&&(H.src=s.customLogoLight,j.src=s.customLogoLight),!s.customLogoDark&&!s.customLogoLight&&s.customLogo&&(E.src=s.customLogo,H.src=s.customLogo,x.src=s.customLogo,j.src=s.customLogo),s.isDefault||(g.textContent="Using custom logo"),s.position&&(B=s.position,m(s.position)),s.dashboardTitle&&v(s.dashboardTitle)}}catch(e){console.warn("Could not load custom logo:",e.message)}}document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.addEventListener("click",()=>{B=e.dataset.pos,m(B)})}),document.getElementById("brand")?.addEventListener("click",()=>{T=null,D=null,y=null,R&&(R.value=""),h&&(h.value=""),C&&(C.value=""),N&&(N.checked=!1),P.style.display="flex",M.style.display="none",x.src=E.src,j.src=H.src;const e=E.src.includes("custom-logo")||H.src.includes("custom-logo");g.textContent=e?"Using custom logo":"Using default logos",m(B),z.value=$,w.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const e=z.value.trim()||S,s={position:B,dashboardTitle:e};N?.checked&&y?(s.dataDark=y,s.dataLight=y):(T&&(s.dataDark=T),D&&(s.dataLight=D));const r=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(r.ok){const o=await r.json(),a="?t="+Date.now();o.pathDark&&(E.src=o.pathDark+a,x.src=o.pathDark+a),o.pathLight&&(H.src=o.pathLight+a,j.src=o.pathLight+a),m(B),v(e),w.classList.remove("show")}else{const o=await r.json();showNotification("Failed to save: "+o.error,"error")}}catch(e){showNotification("Error saving: "+e.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults?
This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(E.src="/assets/dashcaddy-logo-dark.png",M.src="/assets/dashcaddy-logo-light.png",b.src="/assets/dashcaddy-logo-dark.png",j.src="/assets/dashcaddy-logo-light.png",g.textContent="Using default logos",T=null,P=null,v=null,z.value=S,m(S),B="left",u("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const r=document.querySelector('link[rel="icon"]'),s=document.getElementById("favicon-preview"),a=document.getElementById("favicon-status");r&&(r.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),s&&(s.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),a&&(a.textContent="Using DashCaddy favicon"),d=null}}catch(n){showNotification("Error resetting branding: "+n.message,"error")}}),wireModal(x,document.getElementById("logo-cancel"));const k=document.getElementById("favicon-preview"),I=document.getElementById("favicon-status"),i=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let d=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function y(){try{const n=await fetch("/api/v1/favicon");if(n.ok){const e=await n.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),k.src=e.customFavicon+"?t="+Date.now(),I.textContent="Using custom favicon")}}catch(n){console.warn("Could not load custom favicon:",n.message)}}i?.addEventListener("change",n=>{const e=n.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),i.value="";return}const r=new FileReader;r.onload=s=>{d=s.target.result,k.src=d,I.textContent="New favicon ready to save"},r.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(d)try{const n=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:d})});if(n.ok){const e=await n.json();c.href=e.path+"?t="+Date.now(),k.src=e.path+"?t="+Date.now(),I.textContent="Using custom favicon",d=null}else{const e=await n.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(n){showNotification("Error saving favicon: "+n.message,"error")}}),y(),L();const p=document.getElementById("settings-timezone");p&&(new MutationObserver(()=>{x.classList.contains("show")&&p.options.length===0&&(async()=>{let e;try{const r=await fetch("/api/v1/config");r.ok&&(e=(await r.json()).timezone)}catch{}window.populateTimezoneSelect(p,e)})()}).observe(x,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=p.value;if(e)try{const r=await fetch("/api/v1/config");if(!r.ok)return;const s=await r.json();s.timezone=e,s.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})}catch(r){console.warn("Failed to save timezone:",r.message)}}))})(),window.populateTimezoneSelect=function(x,b){const j=Intl.supportedValuesOf("timeZone"),g=b||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";x.innerHTML="";for(const N of j){const A=document.createElement("option");A.value=N,A.textContent=N.replace(/_/g," "),N===g&&(A.selected=!0),x.appendChild(A)}},(function(){let x="homelab",b=null;async function j(){try{const m=await fetch("/api/v1/config");if(m.ok&&(b=await m.json(),b&&b.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(m){console.warn("Could not fetch server config, checking localStorage fallback:",m.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}j();const g=document.getElementById("setup-timezone");g&&window.populateTimezoneSelect(g);function N(u){document.querySelectorAll(".setup-step").forEach(L=>{L.style.display="none"});const m=document.getElementById(u);m&&(m.style.display="block")}function A(){const u=document.getElementById("setup-summary-content");if(!u)return;let m='<div style="display: grid; gap: 20px;">';if(x==="homelab"){const k=document.getElementById("setup-tld")?.value?.trim()||".home",I=document.getElementById("setup-ca-name")?.value?.trim()||"",i=document.getElementById("setup-dns-ip")?.value?.trim()||"",c=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;m+=`
This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(E.src="/assets/dashcaddy-logo-dark.png",H.src="/assets/dashcaddy-logo-light.png",x.src="/assets/dashcaddy-logo-dark.png",j.src="/assets/dashcaddy-logo-light.png",g.textContent="Using default logos",T=null,D=null,y=null,z.value=S,v(S),B="left",m("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const r=document.querySelector('link[rel="icon"]'),o=document.getElementById("favicon-preview"),a=document.getElementById("favicon-status");r&&(r.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),o&&(o.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),a&&(a.textContent="Using DashCaddy favicon"),d=null}}catch(e){showNotification("Error resetting branding: "+e.message,"error")}}),wireModal(w,document.getElementById("logo-cancel"));const b=document.getElementById("favicon-preview"),L=document.getElementById("favicon-status"),l=document.getElementById("favicon-upload");if(b){const e=()=>{b.src="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22><rect fill=%22%23667%22 width=%2232%22 height=%2232%22 rx=%224%22/></svg>"};b.addEventListener("error",e),b.complete&&b.naturalWidth===0&&e()}const c=document.querySelector('link[rel="icon"]')||document.createElement("link");let d=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function f(){try{const e=await fetch("/api/v1/favicon");if(e.ok){const s=await e.json();s.customFavicon&&(c.href=s.customFavicon+"?t="+Date.now(),b.src=s.customFavicon+"?t="+Date.now(),L.textContent="Using custom favicon")}}catch(e){console.warn("Could not load custom favicon:",e.message)}}l?.addEventListener("change",e=>{const s=e.target.files[0];if(!s)return;if(!s.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),l.value="";return}const r=new FileReader;r.onload=o=>{d=o.target.result,b.src=d,L.textContent="New favicon ready to save"},r.readAsDataURL(s)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(d)try{const e=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:d})});if(e.ok){const s=await e.json();c.href=s.path+"?t="+Date.now(),b.src=s.path+"?t="+Date.now(),L.textContent="Using custom favicon",d=null}else{const s=await e.json();showNotification("Failed to save favicon: "+s.error,"error")}}catch(e){showNotification("Error saving favicon: "+e.message,"error")}}),f(),I();const p=document.getElementById("settings-timezone");p&&(new MutationObserver(()=>{w.classList.contains("show")&&p.options.length===0&&(async()=>{let s;try{const r=await fetch("/api/v1/config");r.ok&&(s=(await r.json()).timezone)}catch{}window.populateTimezoneSelect(p,s)})()}).observe(w,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const s=p.value;if(s)try{const r=await fetch("/api/v1/config");if(!r.ok)return;const o=await r.json();o.timezone=s,o.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(r){console.warn("Failed to save timezone:",r.message)}}))})(),window.populateTimezoneSelect=function(w,x){const j=Intl.supportedValuesOf("timeZone"),g=x||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";w.innerHTML="";for(const N of j){const P=document.createElement("option");P.value=N,P.textContent=N.replace(/_/g," "),N===g&&(P.selected=!0),w.appendChild(P)}},(function(){let w="homelab",x=null;async function j(){try{const v=await fetch("/api/v1/config");if(v.ok&&(x=await v.json(),x&&x.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(v){console.warn("Could not fetch server config, checking localStorage fallback:",v.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}j();const g=document.getElementById("setup-timezone");g&&window.populateTimezoneSelect(g);function N(m){document.querySelectorAll(".setup-step").forEach(I=>{I.style.display="none"});const v=document.getElementById(m);v&&(v.style.display="block")}function P(){const m=document.getElementById("setup-summary-content");if(!m)return;let v='<div style="display: grid; gap: 20px;">';if(w==="homelab"){const b=document.getElementById("setup-tld")?.value?.trim()||".home",L=document.getElementById("setup-ca-name")?.value?.trim()||"",l=document.getElementById("setup-dns-ip")?.value?.trim()||"",c=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;v+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Home Lab Configuration</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>TLD:</strong> ${k}</div>
<div><strong>Certificate Authority:</strong> ${I}</div>
<div><strong>DNS Server:</strong> ${i}:${c}</div>
<div><strong>Example URLs:</strong> https://uptime${k}, https://nextcloud${k}</div>
<div><strong>TLD:</strong> ${b}</div>
<div><strong>Certificate Authority:</strong> ${L}</div>
<div><strong>DNS Server:</strong> ${l}:${c}</div>
<div><strong>Example URLs:</strong> https://uptime${b}, https://nextcloud${b}</div>
</div>
</div>
`}else if(x==="simple"){const k=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";m+=`
`}else if(w==="simple"){const b=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";v+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Simple Setup</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Access Method:</strong> IP:Port only</div>
<div><strong>Default IP:</strong> ${k}</div>
<div><strong>Default IP:</strong> ${b}</div>
<div><strong>SSL:</strong> None (HTTP only)</div>
<div><strong>Example URLs:</strong> http://${k}:8080, http://${k}:3000</div>
<div><strong>Example URLs:</strong> http://${b}:8080, http://${b}:3000</div>
</div>
</div>
`}else if(x==="public"){const k=document.getElementById("setup-public-domain")?.value?.trim()||"",I=document.getElementById("setup-public-email")?.value?.trim()||"",i=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",c=i==="subdirectory"?`https://${k}/sonarr, https://${k}/grafana`:`https://sonarr.${k}, https://grafana.${k}`;m+=`
`}else if(w==="public"){const b=document.getElementById("setup-public-domain")?.value?.trim()||"",L=document.getElementById("setup-public-email")?.value?.trim()||"",l=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",c=l==="subdirectory"?`https://${b}/sonarr, https://${b}/grafana`:`https://sonarr.${b}, https://grafana.${b}`;v+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Public Server</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Domain:</strong> ${k}</div>
<div><strong>Domain:</strong> ${b}</div>
<div><strong>SSL:</strong> Let's Encrypt</div>
<div><strong>Email:</strong> ${I}</div>
<div><strong>Routing:</strong> ${i==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div>
<div><strong>Email:</strong> ${L}</div>
<div><strong>Routing:</strong> ${l==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div>
<div><strong>Example URLs:</strong> ${c}</div>
</div>
</div>
`}const L=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";m+=`
`}const I=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";v+=`
<div style="margin-top: 8px; padding-top: 12px; border-top: 1px solid var(--border);">
<div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${L.replace(/_/g," ")}</div>
<div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${I.replace(/_/g," ")}</div>
</div>
`,m+="</div>",u.innerHTML=m,N("setup-step-summary")}async function D(u){try{const m=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return m.ok?(await m.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${m.status}`),{function:"saveConfigToServer"}),!1)}catch(m){return errorHandler.logError("[SetupWizard] Save Config",m,{function:"saveConfigToServer"}),!1}}async function R(){const u={setupComplete:!0,configurationType:x,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(x==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const I=document.getElementById("setup-dns-provider")?.value||"technitium";u.dns={provider:I,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},u.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else x==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):x==="public"&&(u.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",u.email=document.getElementById("setup-public-email")?.value?.trim()||"",u.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u.defaults={dnsType:u.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const m=await D(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const L=x==="homelab"?"Professional Home Lab":x==="simple"?"Simple Setup":"Public Server",k=m?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${L}. Settings saved to: ${k}`,"success",5e3),setTimeout(()=>location.reload(),500)}const f=document.getElementById("setup-step-1-next");f&&(f.onclick=function(u){u.preventDefault();const m=document.querySelector('input[name="config-type"]:checked');m&&(x=m.value),N(x==="homelab"?"setup-step-homelab":x==="simple"?"setup-step-simple":x==="public"?"setup-step-public":"setup-step-homelab")});const C=document.getElementById("setup-skip");C&&(C.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await D({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const E=document.getElementById("setup-tld");E&&(E.oninput=function(u){const m=u.target.value||".home",L=document.getElementById("tld-preview"),k=document.getElementById("tld-preview-2");L&&(L.textContent=m),k&&(k.textContent=m)});const M=document.getElementById("setup-homelab-back");M&&(M.onclick=function(u){u.preventDefault(),N("setup-step-1")});const w=document.getElementById("setup-homelab-next");w&&(w.onclick=function(u){u.preventDefault();const m=document.getElementById("setup-tld")?.value?.trim()||"",L=document.getElementById("setup-ca-name")?.value?.trim()||"",k=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!m||!m.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!L){showNotification("Please enter a Certificate Authority name","warning");return}if(!k){showNotification("Please enter your DNS server IP address","warning");return}A()});const z=document.getElementById("setup-simple-back");z&&(z.onclick=function(u){u.preventDefault(),N("setup-step-1")});const S=document.getElementById("setup-simple-next");S&&(S.onclick=function(u){u.preventDefault(),A()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var m=document.getElementById("dns-requirement-note");m&&(m.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const T=document.getElementById("setup-public-back");T&&(T.onclick=function(u){u.preventDefault(),N("setup-step-1")});const P=document.getElementById("setup-public-next");P&&(P.onclick=function(u){u.preventDefault();const m=document.getElementById("setup-public-domain")?.value?.trim()||"",L=document.getElementById("setup-public-email")?.value?.trim()||"";if(!m){showNotification("Please enter your domain name","warning");return}if(!L||!L.includes("@")){showNotification("Please enter a valid email address","warning");return}A()});const v=document.getElementById("setup-summary-back");v&&(v.onclick=function(u){u.preventDefault(),x==="homelab"?N("setup-step-homela Line truncated
`,v+="</div>",m.innerHTML=v,N("setup-step-summary")}async function M(m){try{const v=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});return v.ok?(await v.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${v.status}`),{function:"saveConfigToServer"}),!1)}catch(v){return errorHandler.logError("[SetupWizard] Save Config",v,{function:"saveConfigToServer"}),!1}}async function R(){const m={setupComplete:!0,configurationType:w,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(w==="homelab"){m.tld=document.getElementById("setup-tld")?.value?.trim()||".home",m.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const L=document.getElementById("setup-dns-provider")?.value||"technitium";m.dns={provider:L,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},m.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else w==="simple"?(m.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",m.defaults={dnsType:"none",sslType:"none",targetIP:m.defaultIP}):w==="public"&&(m.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",m.email=document.getElementById("setup-public-email")?.value?.trim()||"",m.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",m.defaults={dnsType:m.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const v=await M(m);safeSet("dashcaddy-config",JSON.stringify(m)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const I=w==="homelab"?"Professional Home Lab":w==="simple"?"Simple Setup":"Public Server",b=v?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${I}. Settings saved to: ${b}`,"success",5e3),setTimeout(()=>location.reload(),500)}const h=document.getElementById("setup-step-1-next");h&&(h.onclick=function(m){m.preventDefault();const v=document.querySelector('input[name="config-type"]:checked');v&&(w=v.value),N(w==="homelab"?"setup-step-homelab":w==="simple"?"setup-step-simple":w==="public"?"setup-step-public":"setup-step-homelab")});const C=document.getElementById("setup-skip");C&&(C.onclick=async function(m){m.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await M({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const E=document.getElementById("setup-tld");E&&(E.oninput=function(m){const v=m.target.value||".home",I=document.getElementById("tld-preview"),b=document.getElementById("tld-preview-2");I&&(I.textContent=v),b&&(b.textContent=v)});const H=document.getElementById("setup-homelab-back");H&&(H.onclick=function(m){m.preventDefault(),N("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(m){m.preventDefault();const v=document.getElementById("setup-tld")?.value?.trim()||"",I=document.getElementById("setup-ca-name")?.value?.trim()||"",b=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!v||!v.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!I){showNotification("Please enter a Certificate Authority name","warning");return}if(!b){showNotification("Please enter your DNS server IP address","warning");return}P()});const z=document.getElementById("setup-simple-back");z&&(z.onclick=function(m){m.preventDefault(),N("setup-step-1")});const S=document.getElementById("setup-simple-next");S&&(S.onclick=function(m){m.preventDefault(),P()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(m){m.onchange=function(){var v=document.getElementById("dns-requirement-note");v&&(v.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const T=document.getElementById("setup-public-back");T&&(T.onclick=function(m){m.preventDefault(),N("setup-step-1")});const D=document.getElementById("setup-public-next");D&&(D.onclick=function(m){m.preventDefault();const v=document.getElementById("setup-public-domain")?.value?.trim()||"",I=document.getElementById("setup-public-email")?.value?.trim()||"";if(!v){showNotification("Please enter your domain name","warning");return}if(!I||!I.includes("@")){showNotification("Please enter a valid email address","warning");return}P()});const y=document.getElementById("setup-summary-back");y&&(y.onclick=function(m){m.preventDefault(),w==="homelab"?N("setup-step-homela Line truncated
<div class="app-selector-content">
<h2 style="margin: 0 0 24px; color: var(--fg); text-align: center;">Choose an App</h2>
<div id="app-selector-grid" class="app-selector-grid"></div>
@@ -333,12 +333,12 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
</button>
</div>
</div>
</div>`);const b="custom-apps";let j=null,g=null;const N=document.getElementById("app-selector-modal"),A=document.getElementById("app-selector-grid");async function D(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return j=c.templates,g=c.categories,!0}catch(i){x.logError("[AppSelector] Fetch Templates",i,{function:"fetchApiTemplates"})}return!1}async function R(i){try{return await(await fetch(`/api/v1/apps/ports/${i}/check`)).json()}catch(c){return x.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function f(i){try{const d=await(await fetch(`/api/v1/apps/ports/${i}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){x.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return i}async function C(){if(A.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!j&&!await D()){A.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}A.innerHTML="";const i={};for(const[d,y]of Object.entries(j)){const p=y.category||"Other";i[p]||(i[p]=[]),i[p].push({id:d,...y})}const c=g?Object.keys(g):Object.keys(i).sort();for(const d of c){const y=i[d];if(!y||y.length===0)continue;y.sort((e,r)=>(r.popularity||0)-(e.popularity||0));const p=document.createElement("div");p.className="app-category-header";const n=g?.[d]||{};p.innerHTML=`${escapeHtml(n.icon||"")} ${escapeHtml(d)}`,n.color&&(p.style.borderBottomColor=n.color),A.appendChild(p),y.forEach(e=>{const r=document.createElement("div");r.className="app-option";const s=e.isDashboardWidget,a=s&&safeGet("widget-"+e.id+"-enabled")!=="false",t=s?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${a?"#2ecc7130":"#e74c3c30"}; color: ${a?"#2ecc71":"#e74c3c"}; font-weight: 600;">${a?"ON":"OFF"}</div>`:"",o=!s&&e.difficulty?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"}20; color: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"};">${escapeHtml(e.difficulty)}</div>`:"";r.innerHTML=`
<div class="app-option-icon">${escapeHtml(e.icon||"\u{1F4E6}")}</div>
<div class="app-option-name">${escapeHtml(e.name)}</div>
<div class="app-option-desc">${escapeHtml(e.description||"")}</div>
${t}${o}
`,s?r.onclick=()=>E(e,r):r.onclick=()=>M(e),A.appendChild(r)})}window.renderRecipeCards&&await window.renderRecipeCards(A)}function E(i,c){const d="widget-"+i.id+"-enabled",p=!(safeGet(d)!=="false");safeSet(d,String(p));const n=i.widgetSelector;if(n){const r=document.querySelector(n);r&&(r.style.display=p?"":"none")}const e=c.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=p?"ON":"OFF",e.style.background=p?"#2ecc7130":"#e74c3c30",e.style.color=p?"#2ecc71":"#e74c3c"),showNotification(`${i.name} widget ${p?"enabled":"disabled"}`,"success",2e3)}async function M(i){const c=document.getElementById("app-deploy-modal"),d=document.getElementById("app-deploy-title"),y=document.getElementById("deploy-subdomain"),p=document.getElementById("deploy-url-preview"),n=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),r=document.getElementById("deploy-tailscale-only"),s=document.getElementById("tailscale-status");try{const G=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:i.id})})).json();if(G.success&&G.exists){const Y=G.container;confirm(`Found existing ${i.name} container:
</div>`);const x="custom-apps";let j=null,g=null;const N=document.getElementById("app-selector-modal"),P=document.getElementById("app-selector-grid");async function M(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return j=c.templates,g=c.categories,!0}catch(l){w.logError("[AppSelector] Fetch Templates",l,{function:"fetchApiTemplates"})}return!1}async function R(l){try{return await(await fetch(`/api/v1/apps/ports/${l}/check`)).json()}catch(c){return w.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function h(l){try{const d=await(await fetch(`/api/v1/apps/ports/${l}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){w.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return l}async function C(){if(P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!j&&!await M()){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}P.innerHTML="";const l={};for(const[d,f]of Object.entries(j)){const p=f.category||"Other";l[p]||(l[p]=[]),l[p].push({id:d,...f})}const c=g?Object.keys(g):Object.keys(l).sort();for(const d of c){const f=l[d];if(!f||f.length===0)continue;f.sort((s,r)=>(r.popularity||0)-(s.popularity||0));const p=document.createElement("div");p.className="app-category-header";const e=g?.[d]||{};p.innerHTML=`${escapeHtml(e.icon||"")} ${escapeHtml(d)}`,e.color&&(p.style.borderBottomColor=e.color),P.appendChild(p),f.forEach(s=>{const r=document.createElement("div");r.className="app-option";const o=s.isDashboardWidget,a=o&&safeGet("widget-"+s.id+"-enabled")!=="false",t=o?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${a?"#2ecc7130":"#e74c3c30"}; color: ${a?"#2ecc71":"#e74c3c"}; font-weight: 600;">${a?"ON":"OFF"}</div>`:"",n=!o&&s.difficulty?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${s.difficulty==="Easy"?"#2ecc71":s.difficulty==="Intermediate"?"#f39c12":"#e74c3c"}20; color: ${s.difficulty==="Easy"?"#2ecc71":s.difficulty==="Intermediate"?"#f39c12":"#e74c3c"};">${escapeHtml(s.difficulty)}</div>`:"";r.innerHTML=`
<div class="app-option-icon">${escapeHtml(s.icon||"\u{1F4E6}")}</div>
<div class="app-option-name">${escapeHtml(s.name)}</div>
<div class="app-option-desc">${escapeHtml(s.description||"")}</div>
${t}${n}
`,o?r.onclick=()=>E(s,r):r.onclick=()=>H(s),P.appendChild(r)})}window.renderRecipeCards&&await window.renderRecipeCards(P)}function E(l,c){const d="widget-"+l.id+"-enabled",p=!(safeGet(d)!=="false");safeSet(d,String(p));const e=l.widgetSelector;if(e){const r=document.querySelector(e);r&&(r.style.display=p?"":"none")}const s=c.querySelector('div[style*="border-radius: 4px"]');s&&(s.textContent=p?"ON":"OFF",s.style.background=p?"#2ecc7130":"#e74c3c30",s.style.color=p?"#2ecc71":"#e74c3c"),showNotification(`${l.name} widget ${p?"enabled":"disabled"}`,"success",2e3)}async function H(l){const c=document.getElementById("app-deploy-modal"),d=document.getElementById("app-deploy-title"),f=document.getElementById("deploy-subdomain"),p=document.getElementById("deploy-url-preview"),e=document.getElementById("deploy-ip"),s=document.getElementById("deploy-port"),r=document.getElementById("deploy-tailscale-only"),o=document.getElementById("tailscale-status");try{const V=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l.id})})).json();if(V.success&&V.exists){const Y=V.container;confirm(`Found existing ${l.name} container:
Container: ${Y.name}
Status: ${Y.status}
@@ -347,38 +347,38 @@ Port: ${Y.primaryPort||"N/A"}
Would you like to use this existing container?
Click OK to configure DNS/Caddy for the existing container.
Click Cancel to deploy a new container.`)&&(i._useExisting=!0,i._existingContainer=Y)}}catch{}d.textContent=`Deploy ${i.name}`;const a=i.subdomain||i.id.replace(/-/g,"");y.value=a;const t=document.getElementById("subpath-compat-warning");if(t)if(SITE.routingMode==="subdirectory"){const W=i.subpathSupport||"strip";W==="none"?(t.style.display="block",t.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+i.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):W==="strip"?(t.style.display="block",t.innerHTML='<span style="color: var(--muted);">&#9432; '+i.name+" has unverified subdirectory support. It may require additional configuration.</span>"):t.style.display="none"}else t.style.display="none";const o=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),l=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),h=document.querySelector(`input[name="dns-type"][value="${o}"]`),$=document.querySelector(`input[name="ssl-type"][value="${l}"]`);h?h.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,$?$.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,n.value=SITE.defaults.targetIP||"localhost",r.checked=!1;const U=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),F=document.querySelector("#app-deploy-modal details"),_=F?.querySelector("div");if(F&&_&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,G=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(_.appendChild(W),W.dataset.moved="1"),G&&!G.dataset.moved&&(_.appendChild(G),G.dataset.moved="1")}const J=document.getElementById("media-path-section"),q=document.getElementById("deploy-media-path"),K=document.getElementById("media-path-description");if(i.mediaMount){J.style.display="block",q.value="",q.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const X=await(await fetch("/api/v1/media/detected-mounts")).json();if(X.success&&X.mounts.length>0){W.style.display="block",G.innerHTML="";const ae=[...new Set(X.mounts.map(te=>te.hostPath))];q.value=ae.join(", "),X.mounts.forEach(te=>{const Q=document.createElement("button");Q.type="button";const de=ae.includes(te.hostPath);Q.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Q.innerHTML=`<span style="font-weight: 500;">${escapeHtml(te.folderName)}</span><br><span style="font-size: 0.7rem; color: var(--muted);">from ${escapeHtml(te.sourceImage)}</span>`,Q.title=`${te.hostPath} (from ${te.sourceContainer})`,Q.onclick=()=>{const le=q.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(te.hostPath);pe>=0?(le.splice(pe,1),Q.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(te.hostPath),Q.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),q.value=le.join(", ")},G.appendChild(Q)})}else W.style.display="none"}catch{W.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(q)}}else J.style.display="none",q.value="",document.getElementById("detected-mounts-container").style.display="none";const Z=document.getElementById("plex-claim-section");Z&&(i.id==="plex"||i.claimToken?(Z.style.display="block",document.getElementById("deploy-plex-claim").value=""):Z.style.display="none");const ee=document.getElementById("volume-mounts-section"),ne=document.getElementById("volume-mounts-list");if(ne.innerHTML="",i.docker?.volumes?.length){const W=i.mediaMount?.containerPath,G=i.docker.volumes.filter(Y=>!Y.includes("{{MEDIA_PATH}}")&&!(W&&Y.endsWith(":"+W)));G.length>0?(ee.style.display="block",G.forEach((Y,X)=>{const[ae,te]=Y.split(":"),Q=document.createElement("div");Q.style.cssText="display: flex; gap: 6px; align-items: center;",Q.innerHTML=`
Click Cancel to deploy a new container.`)&&(l._useExisting=!0,l._existingContainer=Y)}}catch{}d.textContent=`Deploy ${l.name}`;const a=l.subdomain||l.id.replace(/-/g,"");f.value=a;const t=document.getElementById("subpath-compat-warning");if(t)if(SITE.routingMode==="subdirectory"){const W=l.subpathSupport||"strip";W==="none"?(t.style.display="block",t.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+l.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):W==="strip"?(t.style.display="block",t.innerHTML='<span style="color: var(--muted);">&#9432; '+l.name+" has unverified subdirectory support. It may require additional configuration.</span>"):t.style.display="none"}else t.style.display="none";const n=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),i=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),u=document.querySelector(`input[name="dns-type"][value="${n}"]`),A=document.querySelector(`input[name="ssl-type"][value="${i}"]`);u?u.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,A?A.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,e.value=SITE.defaults.targetIP||"localhost",r.checked=!1;const O=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),F=_?.querySelector("div");if(_&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,V=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1"),V&&!V.dataset.moved&&(F.appendChild(V),V.dataset.moved="1")}const q=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),G=document.getElementById("media-path-description");if(l.mediaMount){q.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),V=document.getElementById("detected-mounts-list");try{const X=await(await fetch("/api/v1/media/detected-mounts")).json();if(X.success&&X.mounts.length>0){W.style.display="block",V.innerHTML="";const ae=[...new Set(X.mounts.map(te=>te.hostPath))];J.value=ae.join(", "),X.mounts.forEach(te=>{const Q=document.createElement("button");Q.type="button";const de=ae.includes(te.hostPath);Q.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Q.innerHTML=`<span style="font-weight: 500;">${escapeHtml(te.folderName)}</span><br><span style="font-size: 0.7rem; color: var(--muted);">from ${escapeHtml(te.sourceImage)}</span>`,Q.title=`${te.hostPath} (from ${te.sourceContainer})`,Q.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(te.hostPath);pe>=0?(le.splice(pe,1),Q.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(te.hostPath),Q.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},V.appendChild(Q)})}else W.style.display="none"}catch{W.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else q.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Z=document.getElementById("plex-claim-section");Z&&(l.id==="plex"||l.claimToken?(Z.style.display="block",document.getElementById("deploy-plex-claim").value=""):Z.style.display="none");const ee=document.getElementById("volume-mounts-section"),ne=document.getElementById("volume-mounts-list");if(ne.innerHTML="",l.docker?.volumes?.length){const W=l.mediaMount?.containerPath,V=l.docker.volumes.filter(Y=>!Y.includes("{{MEDIA_PATH}}")&&!(W&&Y.endsWith(":"+W)));V.length>0?(ee.style.display="block",V.forEach((Y,X)=>{const[ae,te]=Y.split(":"),Q=document.createElement("div");Q.style.cssText="display: flex; gap: 6px; align-items: center;",Q.innerHTML=`
<input type="text" class="vol-host-path" data-container-path="${te}" value="${ae}"
style="flex: 1; padding: 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem;" />
<span style="color: var(--muted); font-size: 0.85rem; white-space: nowrap;">\u2192 ${te}</span>
<button type="button" class="vol-browse-btn" style="padding: 8px 10px; background: var(--accent); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.8rem;">\u{1F4C2}</button>
`,ne.appendChild(Q),Q.querySelector(".vol-browse-btn").onclick=()=>{const de=Q.querySelector(".vol-host-path");openFolderBrowser(de)}})):ee.style.display="none"}else ee.style.display="none";const oe=i.defaultPort||8080;e.value="",e.placeholder=`Default: ${oe}`;let V=document.getElementById("deploy-port-status");V||(V=document.createElement("div"),V.id="deploy-port-status",V.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(V));async function ie(){const W=e.value||oe;V.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const G=await R(W);if(G.available)V.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(W))} is available</span>`;else{const Y=await f(oe);V.innerHTML=`
<span style="color: #e74c3c;">Port ${escapeHtml(W)} in use by ${escapeHtml(G.conflict?.usedBy||"unknown")}</span>
`;const X=document.createElement("button");X.type="button",X.textContent=`Use ${Y}`,X.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",X.onclick=()=>{document.getElementById("deploy-port").value=Y,V.innerHTML=`<span style="color: #4caf50;">Using suggested port ${escapeHtml(String(Y))}</span>`},V.appendChild(X)}}let re;e.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const G=await(await fetch("/api/v1/tailscale/status")).json();G.success&&G.installed&&G.connected?s.innerHTML=`
`,ne.appendChild(Q),Q.querySelector(".vol-browse-btn").onclick=()=>{const de=Q.querySelector(".vol-host-path");openFolderBrowser(de)}})):ee.style.display="none"}else ee.style.display="none";const oe=l.defaultPort||8080;s.value="",s.placeholder=`Default: ${oe}`;let K=document.getElementById("deploy-port-status");K||(K=document.createElement("div"),K.id="deploy-port-status",K.style.cssText="font-size: 0.8rem; margin-top: 4px;",s.parentNode.appendChild(K));async function ie(){const W=s.value||oe;K.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const V=await R(W);if(V.available)K.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(W))} is available</span>`;else{const Y=await h(oe);K.innerHTML=`
<span style="color: #e74c3c;">Port ${escapeHtml(W)} in use by ${escapeHtml(V.conflict?.usedBy||"unknown")}</span>
`;const X=document.createElement("button");X.type="button",X.textContent=`Use ${Y}`,X.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",X.onclick=()=>{document.getElementById("deploy-port").value=Y,K.innerHTML=`<span style="color: #4caf50;">Using suggested port ${escapeHtml(String(Y))}</span>`},K.appendChild(X)}}let re;s.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const V=await(await fetch("/api/v1/tailscale/status")).json();V.success&&V.installed&&V.connected?o.innerHTML=`
<span style="color: #4caf50;">Connected</span>
<span style="color: var(--muted); margin-left: 8px;">${G.self?.hostname} (${G.self?.ip})</span>
<span style="color: var(--muted); margin-left: 8px;">| ${G.deviceCount} devices</span>
`:G.installed?s.innerHTML='<span style="color: #ff9800;">Not connected</span>':(s.innerHTML='<span style="color: var(--muted);">Not available</span>',r.disabled=!0)}catch{s.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function se(){const W=y.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,Y=document.querySelector('input[name="ssl-type"]:checked').value;let X="";if(SITE.routingMode==="subdirectory"&&SITE.domain)X=`https://${SITE.domain}/${W}`;else if(G==="private")X=`${Y==="none"?"http":"https"}://${buildDomain(W)}`;else if(G==="public"){const ae=Y==="none"?"http":"https",te=SITE.domain||W;X=SITE.domain?`${ae}://${W}.${SITE.domain}`:`${ae}://${W}`}else{const ae=e.value||i.defaultPort||DC.DEFAULTS.SERVICE_PORT;X=`http://${n.value}:${ae}`}p.textContent=X}y.oninput=se,n.oninput=se,e.oninput=se,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=se}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=se}),se(),N.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(i)}async function w(i){const c=i.appTemplate,d=safeGetJSON(b,[]),y=c._useExisting&&c._existingContainer,p=d.find(n=>n.id===i.subdomain);if(!(p&&!y&&!confirm(`An app with subdomain "${i.subdomain}" already exists. Redeploy?`))){if(p){const n=d.indexOf(p);d.splice(n,1),safeSet(b,JSON.stringify(d))}if(y)i.port=c._existingContainer.primaryPort;else{const n=i.port||c.defaultPort||8080;showNotification(`Checking port ${n} availability...`,"info",0);const e=await R(n);if(!e.available){const r=await f(c.defaultPort||8080);if(confirm(`Port ${n} is already in use by ${e.conflict?.usedBy||"another container"}.
<span style="color: var(--muted); margin-left: 8px;">${V.self?.hostname} (${V.self?.ip})</span>
<span style="color: var(--muted); margin-left: 8px;">| ${V.deviceCount} devices</span>
`:V.installed?o.innerHTML='<span style="color: #ff9800;">Not connected</span>':(o.innerHTML='<span style="color: var(--muted);">Not available</span>',r.disabled=!0)}catch{o.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function se(){const W=f.value||"subdomain",V=document.querySelector('input[name="dns-type"]:checked').value,Y=document.querySelector('input[name="ssl-type"]:checked').value;let X="";if(SITE.routingMode==="subdirectory"&&SITE.domain)X=`https://${SITE.domain}/${W}`;else if(V==="private")X=`${Y==="none"?"http":"https"}://${buildDomain(W)}`;else if(V==="public"){const ae=Y==="none"?"http":"https",te=SITE.domain||W;X=SITE.domain?`${ae}://${W}.${SITE.domain}`:`${ae}://${W}`}else{const ae=s.value||l.defaultPort||DC.DEFAULTS.SERVICE_PORT;X=`http://${e.value}:${ae}`}p.textContent=X}f.oninput=se,e.oninput=se,s.oninput=se,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=se}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=se}),se(),N.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(l)}async function k(l){const c=l.appTemplate,d=safeGetJSON(x,[]),f=c._useExisting&&c._existingContainer,p=d.find(e=>e.id===l.subdomain);if(!(p&&!f&&!confirm(`An app with subdomain "${l.subdomain}" already exists. Redeploy?`))){if(p){const e=d.indexOf(p);d.splice(e,1),safeSet(x,JSON.stringify(d))}if(f)l.port=c._existingContainer.primaryPort;else{const e=l.port||c.defaultPort||8080;showNotification(`Checking port ${e} availability...`,"info",0);const s=await R(e);if(!s.available){const r=await h(c.defaultPort||8080);if(confirm(`Port ${e} is already in use by ${s.conflict?.usedBy||"another container"}.
Would you like to use port ${r} instead?`))i.port=r;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(y?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const n={appId:c.id,config:{subdomain:i.subdomain,ip:i.ip,createDns:i.dnsType==="private",port:i.port||c.defaultPort||null,sslType:i.sslType,dnsType:i.dnsType,tailscaleOnly:i.tailscaleOnly||!1,mediaPath:i.mediaPath||null,plexClaimToken:i.plexClaimToken||null,customVolumes:i.customVolumes||null}};y&&(n.config.useExisting=!0,n.config.existingContainerId=c._existingContainer.id,n.config.existingPort=c._existingContainer.primaryPort,!i.port&&c._existingContainer.primaryPort&&(n.config.port=c._existingContainer.primaryPort));const e={app:c.id,port:i.port||c.defaultPort||null,subdomain:i.subdomain||"",media_path:i.mediaPath||"",env:i.plexClaimToken?{PLEX_CLAIM:i.plexClaimToken}:{}},s=await(await secureFetch("/api/v1/deploys/catalog/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.success){const a={id:i.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:null,url:s.url||`http://127.0.0.1:${e.port}`,ip:i.ip,appTemplate:c.id,tailscaleOnly:i.tailscaleOnly||!1};d.push(a),safeSet(b,JSON.stringify(d)),window.APPS&&!window.APPS.some(o=>o.id===c.id)&&(window.APPS.push(a),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let t=s.usedExisting?`${c.name} configured with existing container!
URL: ${s.url}`:`${c.name} deployed successfully!
URL: ${s.url}`;s.warning&&(t+=`
Would you like to use port ${r} instead?`))l.port=r;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(f?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const e={appId:c.id,config:{subdomain:l.subdomain,ip:l.ip,createDns:l.dnsType==="private",port:l.port||c.defaultPort||null,sslType:l.sslType,dnsType:l.dnsType,tailscaleOnly:l.tailscaleOnly||!1,mediaPath:l.mediaPath||null,plexClaimToken:l.plexClaimToken||null,customVolumes:l.customVolumes||null}};f&&(e.config.useExisting=!0,e.config.existingContainerId=c._existingContainer.id,e.config.existingPort=c._existingContainer.primaryPort,!l.port&&c._existingContainer.primaryPort&&(e.config.port=c._existingContainer.primaryPort));const s={app:c.id,port:l.port||c.defaultPort||null,subdomain:l.subdomain||"",media_path:l.mediaPath||"",env:l.plexClaimToken?{PLEX_CLAIM:l.plexClaimToken}:{}},o=await(await secureFetch("/api/v1/deploys/catalog/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json();if(o.success){const a={id:l.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:null,url:o.url||`http://127.0.0.1:${s.port}`,ip:l.ip,appTemplate:c.id,tailscaleOnly:l.tailscaleOnly||!1};d.push(a),safeSet(x,JSON.stringify(d)),window.APPS&&!window.APPS.some(n=>n.id===c.id)&&(window.APPS.push(a),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let t=o.usedExisting?`${c.name} configured with existing container!
URL: ${o.url}`:`${c.name} deployed successfully!
URL: ${o.url}`;o.warning&&(t+=`
\u26A0 Warning: ${s.warning}`),showNotification(t,"success",8e3),delete c._useExisting,delete c._existingContainer,s.url&&s.url.startsWith("https://")&&z(s.url,c.name),s.setupInstructions&&s.setupInstructions.length>0&&setTimeout(()=>{const o=s.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${c.name}: ${o}`,"info",1e4)},1e3)}else throw new Error(s.error||"Deployment failed")}catch(n){x.logError("[AppSelector] Deployment",n,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${n.message}`,"error",8e3)}}}async function z(i,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const y=12,p=async()=>{d++;try{const n=await fetch(i,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return d<y?setTimeout(p,5e3):showNotification(`\u26A0\uFE0F ${c} deployed but SSL certificate may still be generating.
Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(p,3e3)}function S(){safeGetJSON(b,[]).forEach(c=>{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{C(),N.classList.add("show")}),window.openDeployConfigFor=async function(i){if(!j&&!await D())return!1;const c=String(i||"").toLowerCase(),d=Object.entries(j).find(([p])=>p.toLowerCase()===c);if(!d)return!1;const y={id:d[0],...d[1]};return y.isDashboardWidget?(await C(),N.classList.add("show"),"selector"):(await M(y),!0)},wireModal(N,document.getElementById("app-selector-cancel"));const T=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const i=JSON.parse(T.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(p=>{d.push({hostPath:p.value.trim(),containerPath:p.dataset.containerPath})});const y={appTemplate:i,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:d.length>0?d:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!y.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(i.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}T.classList.remove("show"),w(y)}),wireModal(T);const P=document.getElementById("folder-browser-modal"),v=document.getElementById("folder-browser-path"),B=document.getElementById("folder-browser-list"),H=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let u="",m=[],L=null;window.openFolderBrowser=function(i){L=i,m=i.value.split(",").map(c=>c.trim()).filter(c=>c),u="",I(),k(""),P.classList.add("show")};async function k(i){v.textContent=i||"Select a drive...",B.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const d=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(i)}`)).json();if(!d.success){B.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(d.error)}</div>`;return}u=d.path||"",v.textContent=u||"Select a drive...";let y="";d.parent&&d.parent!==d.path&&(y+=`<div class="folder-item" data-path="${escapeHtml(d.parent)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px;">
\u26A0 Warning: ${o.warning}`),showNotification(t,"success",8e3),delete c._useExisting,delete c._existingContainer,o.url&&o.url.startsWith("https://")&&z(o.url,c.name),o.setupInstructions&&o.setupInstructions.length>0&&setTimeout(()=>{const n=o.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(o.error||"Deployment failed")}catch(e){w.logError("[AppSelector] Deployment",e,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${e.message}`,"error",8e3)}}}async function z(l,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const f=12,p=async()=>{d++;try{const e=await fetch(l,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return d<f?setTimeout(p,5e3):showNotification(`\u26A0\uFE0F ${c} deployed but SSL certificate may still be generating.
Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(p,3e3)}function S(){safeGetJSON(x,[]).forEach(c=>{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{C(),N.classList.add("show")}),window.openDeployConfigFor=async function(l){if(!j&&!await M())return!1;const c=String(l||"").toLowerCase(),d=Object.entries(j).find(([p])=>p.toLowerCase()===c);if(!d)return!1;const f={id:d[0],...d[1]};return f.isDashboardWidget?(await C(),N.classList.add("show"),"selector"):(await H(f),!0)},wireModal(N,document.getElementById("app-selector-cancel"));const T=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const l=JSON.parse(T.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(p=>{d.push({hostPath:p.value.trim(),containerPath:p.dataset.containerPath})});const f={appTemplate:l,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:d.length>0?d:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!f.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(l.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}T.classList.remove("show"),k(f)}),wireModal(T);const D=document.getElementById("folder-browser-modal"),y=document.getElementById("folder-browser-path"),B=document.getElementById("folder-browser-list"),$=document.getElementById("folder-browser-selected"),U=document.getElementById("folder-browser-selected-list");let m="",v=[],I=null;window.openFolderBrowser=function(l){I=l,v=l.value.split(",").map(c=>c.trim()).filter(c=>c),m="",L(),b(""),D.classList.add("show")};async function b(l){y.textContent=l||"Select a drive...",B.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const d=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(l)}`)).json();if(!d.success){B.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(d.error)}</div>`;return}m=d.path||"",y.textContent=m||"Select a drive...";let f="";d.parent&&d.parent!==d.path&&(f+=`<div class="folder-item" data-path="${escapeHtml(d.parent)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px;">
<span style="font-size: 1.2rem;">\u2B06\uFE0F</span>
<span style="color: var(--muted);">.. Parent Directory</span>
</div>`),d.items.length===0&&!d.parent?y+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':d.items.length===0?y+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':d.items.forEach(p=>{const n=p.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=m.includes(p.path),r=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";y+=`<div class="folder-item" data-path="${escapeHtml(p.path)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px; ${r}">
<span style="font-size: 1.2rem;">${n}</span>
</div>`),d.items.length===0&&!d.parent?f+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':d.items.length===0?f+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':d.items.forEach(p=>{const e=p.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",s=v.includes(p.path),r=s?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";f+=`<div class="folder-item" data-path="${escapeHtml(p.path)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px; ${r}">
<span style="font-size: 1.2rem;">${e}</span>
<span style="flex: 1;">${escapeHtml(p.name)}</span>
${e?'<span style="color: var(--success);">\u2713</span>':""}
</div>`}),B.innerHTML=y,B.querySelectorAll(".folder-item").forEach(p=>{p.addEventListener("click",()=>{k(p.dataset.path)}),p.addEventListener("mouseenter",()=>{p.style.background="var(--card-bg)"}),p.addEventListener("mouseleave",()=>{const n=m.includes(p.dataset.path);p.style.background=n?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){B.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Failed to load: ${escapeHtml(c.message)}</div>`}}function I(){if(m.length===0){H.style.display="none";return}H.style.display="block",O.innerHTML=m.map(i=>`
${s?'<span style="color: var(--success);">\u2713</span>':""}
</div>`}),B.innerHTML=f,B.querySelectorAll(".folder-item").forEach(p=>{p.addEventListener("click",()=>{b(p.dataset.path)}),p.addEventListener("mouseenter",()=>{p.style.background="var(--card-bg)"}),p.addEventListener("mouseleave",()=>{const e=v.includes(p.dataset.path);p.style.background=e?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){B.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Failed to load: ${escapeHtml(c.message)}</div>`}}function L(){if(v.length===0){$.style.display="none";return}$.style.display="block",U.innerHTML=v.map(l=>`
<span style="padding: 6px 12px; background: var(--card-bg); border: 1px solid var(--success); border-radius: 4px; display: flex; align-items: center; gap: 6px;">
${escapeHtml(i)}
<button type="button" onclick="removeSelectedFolder('${escapeHtml(i)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button>
${escapeHtml(l)}
<button type="button" data-remove-folder="${escapeHtml(l)}" aria-label="Remove ${escapeHtml(l)}" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button>
</span>
`).join("")}window.removeSelectedFolder=function(i){m=m.filter(c=>c!==i),I(),k(u)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{u&&!m.includes(u)&&(m.push(u),I(),k(u))}),wireModal(P,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{L&&(L.value=m.join(", ")),P.classList.remove("show")}),S()})(),(function(){injectModal("recipe-deploy-modal",`<div id="recipe-deploy-modal" class="weather-modal">
`).join(""),U.querySelectorAll("[data-remove-folder]").forEach(l=>{l.addEventListener("click",()=>window.removeSelectedFolder(l.dataset.removeFolder))})}window.removeSelectedFolder=function(l){v=v.filter(c=>c!==l),L(),b(m)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{m&&!v.includes(m)&&(v.push(m),L(),b(m))}),wireModal(D,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{I&&(I.value=v.join(", ")),D.classList.remove("show")}),S()})(),(function(){injectModal("recipe-deploy-modal",`<div id="recipe-deploy-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 620px; max-width: 740px;">
<h3 id="recipe-deploy-title">Deploy Recipe</h3>
@@ -445,70 +445,70 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="recipe-next" class="btn-accent-solid">Next</button>
</div>
</div>
</div>`);let x=null,b=null,j=null,g=1,N=!1;const A=document.getElementById("recipe-deploy-modal"),D=document.getElementById("recipe-cancel"),R=document.getElementById("recipe-prev"),f=document.getElementById("recipe-next");wireModal(A,D);async function C(){try{const u=await fetch("/api/v1/recipes/templates"),m=await u.json();if(m.success)return x=m.templates,b=m.categories,!0;if(u.status===403)return N=!1,!1}catch(u){console.warn("Failed to fetch recipe templates:",u.message)}return!1}async function E(){try{N=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{N=!1}return N}window.renderRecipeCards=async function(u){await E();let m;if(N&&x?m=x:m=M(),!m||m.length===0)return;const L=document.createElement("div");L.className="app-category-header",L.innerHTML="\u{1F9EA} Recipes",L.style.borderBottomColor="#8e44ad",u.appendChild(L);const k=Array.isArray(m)?m:Object.values(m);k.sort((I,i)=>(i.popularity||0)-(I.popularity||0));for(const I of k){const i=document.createElement("div");i.className="app-option",i.style.position="relative";const c=`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: rgba(142,68,173,0.2); color: #a855f7;">${I.componentCount||I.components?.length||"?"} apps</div>`,d=N?"":'<div style="position: absolute; top: 6px; right: 6px; font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; background: rgba(241,196,15,0.2); color: #f1c40f; font-weight: 600;">PREMIUM</div>';i.innerHTML=`
</div>`);let w=null,x=null,j=null,g=1,N=!1;const P=document.getElementById("recipe-deploy-modal"),M=document.getElementById("recipe-cancel"),R=document.getElementById("recipe-prev"),h=document.getElementById("recipe-next");wireModal(P,M);async function C(){try{const m=await fetch("/api/v1/recipes/templates"),v=await m.json();if(v.success)return w=v.templates,x=v.categories,!0;if(m.status===403)return N=!1,!1}catch(m){console.warn("Failed to fetch recipe templates:",m.message)}return!1}async function E(){try{N=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{N=!1}return N}window.renderRecipeCards=async function(m){await E();let v;if(N&&w?v=w:v=H(),!v||v.length===0)return;const I=document.createElement("div");I.className="app-category-header",I.innerHTML="\u{1F9EA} Recipes",I.style.borderBottomColor="#8e44ad",m.appendChild(I);const b=Array.isArray(v)?v:Object.values(v);b.sort((L,l)=>(l.popularity||0)-(L.popularity||0));for(const L of b){const l=document.createElement("div");l.className="app-option",l.style.position="relative";const c=`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: rgba(142,68,173,0.2); color: #a855f7;">${L.componentCount||L.components?.length||"?"} apps</div>`,d=N?"":'<div style="position: absolute; top: 6px; right: 6px; font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; background: rgba(241,196,15,0.2); color: #f1c40f; font-weight: 600;">PREMIUM</div>';l.innerHTML=`
${d}
<div class="app-option-icon">${escapeHtml(I.icon||"\u{1F9EA}")}</div>
<div class="app-option-name">${escapeHtml(I.name)}</div>
<div class="app-option-desc">${escapeHtml(I.description||"")}</div>
<div class="app-option-icon">${escapeHtml(L.icon||"\u{1F9EA}")}</div>
<div class="app-option-name">${escapeHtml(L.name)}</div>
<div class="app-option-desc">${escapeHtml(L.description||"")}</div>
${c}
`,i.onclick=()=>{if(!N){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}w(I)},u.appendChild(i)}};function M(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function w(u){j=u,g=1;const m=document.getElementById("app-selector-modal");m&&m.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${u.name}`,z(),S(),A.classList.add("show")}function z(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(u=>{const m=parseInt(u.dataset.step);u.classList.toggle("active",m===g),u.classList.toggle("completed",m<g)});for(let u=1;u<=4;u++){const m=document.getElementById(`recipe-step-${u}`);m&&(m.style.display=u===g?"":"none")}R.style.display=g>1&&g<4?"":"none",g===4?(f.style.display="none",D.textContent="Close"):g===3?(f.textContent="\u{1F680} Deploy",f.style.display="",D.textContent="Cancel"):(f.textContent="Next",f.style.display="",D.textContent="Cancel")}function S(){const u=document.getElementById("recipe-component-list");u.innerHTML="";const m=j.components||[];for(const L of m){const k=document.createElement("div");k.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const I=L.required,i=L.internal;k.innerHTML=`
<input type="checkbox" ${I?"checked disabled":"checked"} data-component-id="${L.id}"
`,l.onclick=()=>{if(!N){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(L)},m.appendChild(l)}};function H(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function k(m){j=m,g=1;const v=document.getElementById("app-selector-modal");v&&v.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${m.name}`,z(),S(),P.classList.add("show")}function z(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(m=>{const v=parseInt(m.dataset.step);m.classList.toggle("active",v===g),m.classList.toggle("completed",v<g)});for(let m=1;m<=4;m++){const v=document.getElementById(`recipe-step-${m}`);v&&(v.style.display=m===g?"":"none")}R.style.display=g>1&&g<4?"":"none",g===4?(h.style.display="none",M.textContent="Close"):g===3?(h.textContent="\u{1F680} Deploy",h.style.display="",M.textContent="Cancel"):(h.textContent="Next",h.style.display="",M.textContent="Cancel")}function S(){const m=document.getElementById("recipe-component-list");m.innerHTML="";const v=j.components||[];for(const I of v){const b=document.createElement("div");b.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const L=I.required,l=I.internal;b.innerHTML=`
<input type="checkbox" ${L?"checked disabled":"checked"} data-component-id="${I.id}"
style="width: 18px; height: 18px; accent-color: var(--accent);" />
<div style="flex: 1;">
<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(L.role||L.id)}</div>
<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(I.role||I.id)}</div>
<div style="font-size: 0.78rem; color: var(--muted);">
${L.templateRef?escapeHtml(L.templateRef):"Built-in"}
${I?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'}
${i?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""}
${I.templateRef?escapeHtml(I.templateRef):"Built-in"}
${L?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'}
${l?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""}
</div>
${L.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(L.note)}</div>`:""}
${I.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(I.note)}</div>`:""}
</div>
`,u.appendChild(k)}}function T(){const u=document.getElementById("recipe-volumes-section"),m=document.getElementById("recipe-volume-list"),L=j.sharedVolumes;if(L&&Object.keys(L).length>0){u.style.display="",m.innerHTML="";for(const[k,I]of Object.entries(L)){const i=document.createElement("div");i.style.cssText="display: grid; gap: 4px;",i.innerHTML=`
<label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(I.label||k)}</label>
<input type="text" data-volume-key="${k}" value="${escapeHtml(I.defaultPath||"")}"
placeholder="${escapeHtml(I.defaultPath||"/path")}"
`,m.appendChild(b)}}function T(){const m=document.getElementById("recipe-volumes-section"),v=document.getElementById("recipe-volume-list"),I=j.sharedVolumes;if(I&&Object.keys(I).length>0){m.style.display="",v.innerHTML="";for(const[b,L]of Object.entries(I)){const l=document.createElement("div");l.style.cssText="display: grid; gap: 4px;",l.innerHTML=`
<label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(L.label||b)}</label>
<input type="text" data-volume-key="${b}" value="${escapeHtml(L.defaultPath||"")}"
placeholder="${escapeHtml(L.defaultPath||"/path")}"
style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-family: monospace; font-size: 0.85rem;" />
<div class="form-hint-sm">${escapeHtml(I.description||"")}</div>
`,m.appendChild(i)}}else u.style.display="none"}function P(){const u=document.getElementById("recipe-review-content"),m=v(),L=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),k={};L.forEach(d=>{k[d.dataset.volumeKey]=d.value});const I=document.getElementById("recipe-timezone").value||"UTC",i=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;u.innerHTML=`
<div class="form-hint-sm">${escapeHtml(L.description||"")}</div>
`,v.appendChild(l)}}else m.style.display="none"}function D(){const m=document.getElementById("recipe-review-content"),v=y(),I=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),b={};I.forEach(d=>{b[d.dataset.volumeKey]=d.value});const L=document.getElementById("recipe-timezone").value||"UTC",l=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;m.innerHTML=`
<div style="font-weight: 600; font-size: 1rem; margin-bottom: 12px;">${escapeHtml(j.name)}</div>
<div style="color: var(--muted); margin-bottom: 16px;">${escapeHtml(j.description||"")}</div>
<div style="margin-bottom: 12px;">
<strong>Components (${m.length}):</strong>
<strong>Components (${v.length}):</strong>
<div style="display: grid; gap: 4px; margin-top: 6px;">
${m.map(d=>`<div style="padding: 4px 0; font-size: 0.85rem;">
${v.map(d=>`<div style="padding: 4px 0; font-size: 0.85rem;">
\u2022 <strong>${escapeHtml(d.role||d.id)}</strong> ${d.internal?'<span style="color:var(--muted)">(internal)</span>':""}
</div>`).join("")}
</div>
</div>
${Object.keys(k).length>0?`<div style="margin-bottom: 12px;">
${Object.keys(b).length>0?`<div style="margin-bottom: 12px;">
<strong>Volumes:</strong>
${Object.entries(k).map(([d,y])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${d}: ${escapeHtml(y)}</div>`).join("")}
${Object.entries(b).map(([d,f])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${d}: ${escapeHtml(f)}</div>`).join("")}
</div>`:""}
<div style="font-size: 0.85rem; color: var(--muted);">
Timezone: ${escapeHtml(I)} &bull; IP: ${escapeHtml(i)} ${c?"&bull; Tailscale only":""}
Timezone: ${escapeHtml(L)} &bull; IP: ${escapeHtml(l)} ${c?"&bull; Tailscale only":""}
</div>
${j.network?`<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">Docker network: <code>${escapeHtml(j.network.name)}</code></div>`:""}
`}function v(){const u=document.querySelectorAll("#recipe-component-list input[data-component-id]"),m=new Set;u.forEach(k=>{k.checked&&m.add(k.dataset.componentId)});const L=j.components||[];return L.filter(k=>k.required).forEach(k=>m.add(k.id)),L.filter(k=>m.has(k.id))}async function B(){const u=document.getElementById("recipe-progress-list"),m=document.getElementById("recipe-deploy-result");m.style.display="none",u.innerHTML="";const L=v();for(const c of L){const d=document.createElement("div");d.id=`recipe-progress-${c.id}`,d.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",d.innerHTML=`
`}function y(){const m=document.querySelectorAll("#recipe-component-list input[data-component-id]"),v=new Set;m.forEach(b=>{b.checked&&v.add(b.dataset.componentId)});const I=j.components||[];return I.filter(b=>b.required).forEach(b=>v.add(b.id)),I.filter(b=>v.has(b.id))}async function B(){const m=document.getElementById("recipe-progress-list"),v=document.getElementById("recipe-deploy-result");v.style.display="none",m.innerHTML="";const I=y();for(const c of I){const d=document.createElement("div");d.id=`recipe-progress-${c.id}`,d.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",d.innerHTML=`
<span class="recipe-progress-icon" style="font-size: 1.1rem;">\u23F3</span>
<span style="flex:1; font-weight: 500;">${escapeHtml(c.role||c.id)}</span>
<span class="recipe-progress-status" style="color: var(--muted);">Queued</span>
`,u.appendChild(d)}const k=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),I={};k.forEach(c=>{I[c.dataset.volumeKey]=c.value});const i={selectedComponents:L.map(c=>c.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:I},componentOverrides:{}};for(const c of L)H(c.id,"deploying","Deploying...");try{const d=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:j.id,config:i})})).json();if(d.success){for(const y of d.deployed||[])H(y.id,"success",y.url?`Running \u2192 ${y.url}`:"Running");for(const y of d.errors||[])H(y.componentId,"error",y.error);m.style.display="",m.innerHTML=`
`,m.appendChild(d)}const b=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),L={};b.forEach(c=>{L[c.dataset.volumeKey]=c.value});const l={selectedComponents:I.map(c=>c.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:L},componentOverrides:{}};for(const c of I)$(c.id,"deploying","Deploying...");try{const d=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:j.id,config:l})})).json();if(d.success){for(const f of d.deployed||[])$(f.id,"success",f.url?`Running \u2192 ${f.url}`:"Running");for(const f of d.errors||[])$(f.componentId,"error",f.error);v.style.display="",v.innerHTML=`
<div style="padding: 14px; border-radius: 8px; background: rgba(46,204,113,0.1); border: 1px solid rgba(46,204,113,0.3);">
<div style="font-weight: 600; color: var(--ok-fg); margin-bottom: 6px;">${escapeHtml(d.message||"Deployed!")}</div>
${d.setupInstructions?`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 8px;">
<strong>Setup tips:</strong>
<ul style="margin: 4px 0 0 16px; padding: 0;">${d.setupInstructions.map(y=>`<li>${escapeHtml(y)}</li>`).join("")}</ul>
<ul style="margin: 4px 0 0 16px; padding: 0;">${d.setupInstructions.map(f=>`<li>${escapeHtml(f)}</li>`).join("")}</ul>
</div>`:""}
</div>
`,showNotification(`${j.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else m.style.display="",m.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
`,showNotification(`${j.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else v.style.display="",v.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Deployment failed:</strong> ${escapeHtml(d.error||"Unknown error")}
</div>`,showNotification(`Recipe deployment failed: ${d.error}`,"error",5e3)}catch(c){m.style.display="",m.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
</div>`,showNotification(`Recipe deployment failed: ${d.error}`,"error",5e3)}catch(c){v.style.display="",v.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Network error:</strong> ${escapeHtml(c.message)}
</div>`}}function H(u,m,L){const k=document.getElementById(`recipe-progress-${u}`);if(!k)return;const I=k.querySelector(".recipe-progress-icon"),i=k.querySelector(".recipe-progress-status");m==="deploying"?(I.textContent="\u23F3",i.style.color="var(--accent)"):m==="success"?(I.textContent="\u2705",i.style.color="var(--ok-fg)"):m==="error"&&(I.textContent="\u274C",i.style.color="var(--bad-fg)"),i.textContent=L}f.addEventListener("click",()=>{if(g===3){g=4,z(),B();return}g<3&&(g++,z(),g===2&&T(),g===3&&P())}),R.addEventListener("click",()=>{g>1&&g<4&&(g--,z())}),window.groupRecipeCards=function(){const u=document.querySelectorAll(".service-card[data-recipe-id]");if(u.length===0)return;const m={};u.forEach(L=>{const k=L.dataset.recipeId;m[k]||(m[k]=[]),m[k].push(L)});for(const[L,k]of Object.entries(m))k.length<2||k.forEach((I,i)=>{if(I.style.borderLeft="3px solid rgba(142,68,173,0.5)",i===0){let c=I.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",c.textContent=L.replace(/-/g," "),I.style.position="relative",I.appendChild(c))}})},window.manageRecipe=async function(u,m){const L=`/api/v1/recipes/${u}/${m}`,k=m==="remove"?"DELETE":"POST",I=m==="remove"?`/api/v1/recipes/${u}`:L;if(!(m==="remove"&&!confirm(`Remove the entire ${u} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(I,{method:k})).json();c.success?(showNotification(`Recipe ${m}: ${c.results?.filter(d=>d.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${m} failed: ${c.error}`,"error",5e3)}catch(i){showNotification(`Network error: ${i.message}`,"error",5e3)}};const O=document.createElement("style");O.textContent=`
</div>`}}function $(m,v,I){const b=document.getElementById(`recipe-progress-${m}`);if(!b)return;const L=b.querySelector(".recipe-progress-icon"),l=b.querySelector(".recipe-progress-status");v==="deploying"?(L.textContent="\u23F3",l.style.color="var(--accent)"):v==="success"?(L.textContent="\u2705",l.style.color="var(--ok-fg)"):v==="error"&&(L.textContent="\u274C",l.style.color="var(--bad-fg)"),l.textContent=I}h.addEventListener("click",()=>{if(g===3){g=4,z(),B();return}g<3&&(g++,z(),g===2&&T(),g===3&&D())}),R.addEventListener("click",()=>{g>1&&g<4&&(g--,z())}),window.groupRecipeCards=function(){const m=document.querySelectorAll(".service-card[data-recipe-id]");if(m.length===0)return;const v={};m.forEach(I=>{const b=I.dataset.recipeId;v[b]||(v[b]=[]),v[b].push(I)});for(const[I,b]of Object.entries(v))b.length<2||b.forEach((L,l)=>{if(L.style.borderLeft="3px solid rgba(142,68,173,0.5)",l===0){let c=L.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",c.textContent=I.replace(/-/g," "),L.style.position="relative",L.appendChild(c))}})},window.manageRecipe=async function(m,v){const I=`/api/v1/recipes/${m}/${v}`,b=v==="remove"?"DELETE":"POST",L=v==="remove"?`/api/v1/recipes/${m}`:I;if(!(v==="remove"&&!confirm(`Remove the entire ${m} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(L,{method:b})).json();c.success?(showNotification(`Recipe ${v}: ${c.results?.filter(d=>d.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${v} failed: ${c.error}`,"error",5e3)}catch(l){showNotification(`Network error: ${l.message}`,"error",5e3)}};const U=document.createElement("style");U.textContent=`
.recipe-step {
flex: 1;
text-align: center;
@@ -550,7 +550,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
.recipe-step-panel {
min-height: 180px;
}
`,document.head.appendChild(O),E()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const x=document.getElementById("reload-caddy-top"),b=x.textContent;try{x.textContent="\u23F3 Reloading...",x.disabled=!0;const j=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),g=await j.json();if(j.ok&&g.success)x.textContent="\u2705 Reloaded!",setTimeout(()=>{x.textContent=b,x.disabled=!1},2e3);else throw new Error(g.error||"Reload failed")}catch(j){x.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${j.message}`,"error"),setTimeout(()=>{x.textContent=b,x.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",`<div id="error-log-modal" class="weather-modal">
`,document.head.appendChild(U),E()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const w=document.getElementById("reload-caddy-top"),x=w.textContent;try{w.textContent="\u23F3 Reloading...",w.disabled=!0;const j=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),g=await j.json();if(j.ok&&g.success)w.textContent="\u2705 Reloaded!",setTimeout(()=>{w.textContent=x,w.disabled=!1},2e3);else throw new Error(g.error||"Reload failed")}catch(j){w.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${j.message}`,"error"),setTimeout(()=>{w.textContent=x,w.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",`<div id="error-log-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 950px; max-width: 1150px;">
<h3>\u{1F4CB} Error Logs</h3>
<p class="modal-subtitle">
@@ -597,8 +597,8 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="error-log-close">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("error-log-modal"),b=document.getElementById("view-error-logs"),j=document.getElementById("error-log-refresh"),g=document.getElementById("error-log-clear"),N=document.getElementById("error-log-close"),A=document.getElementById("error-log-level"),D=document.getElementById("error-log-context"),R=document.getElementById("error-log-search"),f=document.getElementById("error-log-since"),C=document.getElementById("error-log-until"),E=document.getElementById("error-log-container"),M=document.getElementById("error-log-load-more"),w=document.getElementById("error-log-total"),z=50;let S=0,T=null,P=0,v=[];function B(I){if(!I)return null;const i=new Date(I);return isNaN(i.getTime())?null:i.toISOString()}async function H(){try{const I=await fetch("/api/v1/error-logs/contexts");if(!I.ok)return;const i=await I.json();if(!i.success||!Array.isArray(i.contexts))return;v=i.contexts;const c=D.value;D.innerHTML='<option value="">All</option>';for(const d of i.contexts){const y=document.createElement("option");y.value=d.name,y.textContent=`${d.name} (${d.count})`,D.appendChild(y)}c&&i.contexts.some(d=>d.name===c)&&(D.value=c)}catch{}}function O(){const I=new URLSearchParams;I.set("limit",String(z)),I.set("offset",String(S)),A.value&&I.set("level",A.value),D.value&&I.set("context",D.value);const i=B(f.value),c=B(C.value);i&&I.set("since",i),c&&I.set("until",c);const d=(R.value||"").trim();return d&&I.set("search",d),I}async function u(I){try{I?(T&&T.abort(),T=new AbortController):(T&&T.abort(),T=new AbortController,S=0,P++,E.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const i=P,c=O(),d=await fetch("/api/v1/error-logs?"+c.toString(),{signal:T.signal});if(!d.ok){E.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: HTTP ${d.status}</div>`,M.style.display="none",w.textContent="";return}const y=await d.json();if(!y.success){E.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(y.error||"unknown")}</div>`,M.style.display="none",w.textContent="";return}if(!I&&i!==P)return;const p=Array.isArray(y.logs)?y.logs:[];if(p.length===0&&!I){const e=y.filters&&(y.filters.level||y.filters.context||y.filters.search||y.filters.since||y.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";E.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CB}</span>${escapeHtml(e)}</div>`,M.style.display="none",w.textContent=y.total?`${y.total} total`:"";return}let n="";I||(n='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',n+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);">',n+='<th style="padding: 6px; text-align: left; width: 160px;">When</th>',n+='<th style="padding: 6px; text-align: left; width: 80px;">Level</th>',n+='<th style="padding: 6px; text-align: left; width: 140px;">Context</th>',n+='<th style="padding: 6px; text-align: left;">Message</th>',n+='<th style="padding: 6px; text-align: left; width: 110px;">IP</th>',n+="</tr>");for(const e of p){const r=(e.level||"?").toUpperCase(),s=r==="ERR"?"var(--bad-fg)":r==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",a=e.timestamp?new Date(e.timestamp).toLocaleString():"\u2014",t=e.context||"\u2014",o=(e.error||"").split(`
`)[0],l=e.request&&e.request.ip||"";n+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="error-log-row">',n+=`<td style="padding: 6px; color: var(--muted);" title="${escapeHtml(e.timestamp||"")}">${escapeHtml(a)}</td>`,n+=`<td style="padding: 6px;"><span style="color: ${s}; font-weight: 600;">${escapeHtml(r)}</span></td>`,n+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(t)}</td>`,n+=`<td style="padding: 6px;">${escapeHtml(o)}</td>`,n+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(l)}</td>`,n+="</tr>",e.detail&&(n+=`<tr class="error-log-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace; max-height: 320px; overflow: auto;">${escapeHtml(e.detail)}</pre></td></tr>`)}if(!I)n+="</table>",E.innerHTML=n;else{const e=E.querySelector("table");e&&e.insertAdjacentHTML("beforeend",n)}S+=p.length,M.style.display=y.hasMore?"":"none",w.textContent=`${y.total} total${y.hasMore?" (showing "+S+")":""}`,E.querySelectorAll(".error-log-row").forEach(e=>{e.dataset.wired||(e.dataset.wired="true",e.addEventListener("click",()=>{const r=e.nextElementSibling;r&&r.classList.contains("error-log-detail")&&(r.style.display=r.style.display==="none"?"":"none")}))})}catch(i){if(i&&i.name==="AbortError")return;E.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(i.message)}</div>`,w.textContent=""}}async function m(){if(confirm("Clear the entire error log? This cannot be undone."))try{const i=await(await secureFetch("/api/v1/error-logs",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"CLEAR"})})).json();i.success?(await H(),u(!1),showNotification("\u2705 Error logs cleared","success",3e3)):showNotification("\u274C "+(i.error||"Clear failed"),"error",4e3)}catch(I){showNotification("\u274C "+I.message,"error",4e3)}}let L;function k(){A?.addEventListener("change",()=>u(!1)),D?.addEventListener("change",()=>u(!1)),R?.addEventListener("input",()=>{clearTimeout(L),L=setTimeout(()=>u(!1),250)});let I;[f,C].forEach(i=>{i?.addEventListener("change",()=>{clearTimeout(I),I=setTimeout(()=>u(!1),250)})}),j?.addEventListener("click",()=>u(!1)),M?.addEventListener("click",()=>u(!0)),g?.addEventListener("click",m),wireModal(x,N)}b?.addEventListener("click",async()=>{x?.classList.add("show"),await H(),u(!1)}),k()})(),(function(){injectModal("container-logs-modal",`<div id="container-logs-modal" class="weather-modal" style="z-index: 1001;">
</div>`);const w=document.getElementById("error-log-modal"),x=document.getElementById("view-error-logs"),j=document.getElementById("error-log-refresh"),g=document.getElementById("error-log-clear"),N=document.getElementById("error-log-close"),P=document.getElementById("error-log-level"),M=document.getElementById("error-log-context"),R=document.getElementById("error-log-search"),h=document.getElementById("error-log-since"),C=document.getElementById("error-log-until"),E=document.getElementById("error-log-container"),H=document.getElementById("error-log-load-more"),k=document.getElementById("error-log-total"),z=50;let S=0,T=null,D=0,y=[];function B(L){if(!L)return null;const l=new Date(L);return isNaN(l.getTime())?null:l.toISOString()}async function $(){try{const L=await fetch("/api/v1/error-logs/contexts");if(!L.ok)return;const l=await L.json();if(!l.success||!Array.isArray(l.contexts))return;y=l.contexts;const c=M.value;M.innerHTML='<option value="">All</option>';for(const d of l.contexts){const f=document.createElement("option");f.value=d.name,f.textContent=`${d.name} (${d.count})`,M.appendChild(f)}c&&l.contexts.some(d=>d.name===c)&&(M.value=c)}catch{}}function U(){const L=new URLSearchParams;L.set("limit",String(z)),L.set("offset",String(S)),P.value&&L.set("level",P.value),M.value&&L.set("context",M.value);const l=B(h.value),c=B(C.value);l&&L.set("since",l),c&&L.set("until",c);const d=(R.value||"").trim();return d&&L.set("search",d),L}async function m(L){try{L?(T&&T.abort(),T=new AbortController):(T&&T.abort(),T=new AbortController,S=0,D++,E.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const l=D,c=U(),d=await fetch("/api/v1/error-logs?"+c.toString(),{signal:T.signal});if(!d.ok){E.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: HTTP ${d.status}</div>`,H.style.display="none",k.textContent="";return}const f=await d.json();if(!f.success){E.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(f.error||"unknown")}</div>`,H.style.display="none",k.textContent="";return}if(!L&&l!==D)return;const p=Array.isArray(f.logs)?f.logs:[];if(p.length===0&&!L){const s=f.filters&&(f.filters.level||f.filters.context||f.filters.search||f.filters.since||f.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";E.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CB}</span>${escapeHtml(s)}</div>`,H.style.display="none",k.textContent=f.total?`${f.total} total`:"";return}let e="";L||(e='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',e+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);">',e+='<th style="padding: 6px; text-align: left; width: 160px;">When</th>',e+='<th style="padding: 6px; text-align: left; width: 80px;">Level</th>',e+='<th style="padding: 6px; text-align: left; width: 140px;">Context</th>',e+='<th style="padding: 6px; text-align: left;">Message</th>',e+='<th style="padding: 6px; text-align: left; width: 110px;">IP</th>',e+="</tr>");for(const s of p){const r=(s.level||"?").toUpperCase(),o=r==="ERR"?"var(--bad-fg)":r==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",a=s.timestamp?new Date(s.timestamp).toLocaleString():"\u2014",t=s.context||"\u2014",n=(s.error||"").split(`
`)[0],i=s.request&&s.request.ip||"";e+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="error-log-row">',e+=`<td style="padding: 6px; color: var(--muted);" title="${escapeHtml(s.timestamp||"")}">${escapeHtml(a)}</td>`,e+=`<td style="padding: 6px;"><span style="color: ${o}; font-weight: 600;">${escapeHtml(r)}</span></td>`,e+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(t)}</td>`,e+=`<td style="padding: 6px;">${escapeHtml(n)}</td>`,e+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(i)}</td>`,e+="</tr>",s.detail&&(e+=`<tr class="error-log-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace; max-height: 320px; overflow: auto;">${escapeHtml(s.detail)}</pre></td></tr>`)}if(!L)e+="</table>",E.innerHTML=e;else{const s=E.querySelector("table");s&&s.insertAdjacentHTML("beforeend",e)}S+=p.length,H.style.display=f.hasMore?"":"none",k.textContent=`${f.total} total${f.hasMore?" (showing "+S+")":""}`,E.querySelectorAll(".error-log-row").forEach(s=>{s.dataset.wired||(s.dataset.wired="true",s.addEventListener("click",()=>{const r=s.nextElementSibling;r&&r.classList.contains("error-log-detail")&&(r.style.display=r.style.display==="none"?"":"none")}))})}catch(l){if(l&&l.name==="AbortError")return;E.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(l.message)}</div>`,k.textContent=""}}async function v(){if(confirm("Clear the entire error log? This cannot be undone."))try{const l=await(await secureFetch("/api/v1/error-logs",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"CLEAR"})})).json();l.success?(await $(),m(!1),showNotification("\u2705 Error logs cleared","success",3e3)):showNotification("\u274C "+(l.error||"Clear failed"),"error",4e3)}catch(L){showNotification("\u274C "+L.message,"error",4e3)}}let I;function b(){P?.addEventListener("change",()=>m(!1)),M?.addEventListener("change",()=>m(!1)),R?.addEventListener("input",()=>{clearTimeout(I),I=setTimeout(()=>m(!1),250)});let L;[h,C].forEach(l=>{l?.addEventListener("change",()=>{clearTimeout(L),L=setTimeout(()=>m(!1),250)})}),j?.addEventListener("click",()=>m(!1)),H?.addEventListener("click",()=>m(!0)),g?.addEventListener("click",v),wireModal(w,N)}x?.addEventListener("click",async()=>{w?.classList.add("show"),await $(),m(!1)}),b()})(),(function(){injectModal("container-logs-modal",`<div id="container-logs-modal" class="weather-modal" style="z-index: 1001;">
<div class="weather-modal-content" style="min-width: 900px; max-width: 95vw; height: 80vh; display: flex; flex-direction: column;">
<div class="logs-header" style="display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; border-bottom: 1px solid var(--border); margin-bottom: 12px;">
<div>
@@ -648,14 +648,14 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="cl-close-btn" class="btn-secondary">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("container-logs-modal"),b=document.getElementById("cl-container-select"),j=document.getElementById("cl-log-content"),g=document.getElementById("cl-log-search"),N=document.getElementById("cl-log-tail"),A=document.getElementById("cl-refresh"),D=document.getElementById("cl-stream"),R=document.getElementById("cl-download"),f=document.getElementById("cl-clear-search"),C=document.getElementById("cl-close"),E=document.getElementById("cl-close-btn"),M=document.getElementById("cl-stream-status"),w=document.getElementById("cl-stream-indicator"),z=document.getElementById("cl-stream-text"),S=document.getElementById("cl-line-count"),T=document.getElementById("cl-filter-count"),P=document.getElementById("cl-image"),v=document.getElementById("cl-status"),B=document.getElementById("cl-created");let H=null,O=[],u=[],m=null,L=!1,k=null;function I(o){if(!o)return"-";const l=new Date(o);return isNaN(l.getTime())?o:l.toLocaleString()}function i(o){if(!o)return"";const l=document.createElement("div");return l.textContent=o,l.innerHTML}function c(o,l){const h=o.stream==="stderr"?"log-stderr":"log-stdout",$=o.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return`
<div class="log-entry ${h}" data-index="${l}" style="padding: 4px 8px; border-bottom: 1px solid #333; display: flex; gap: 8px;">
<span class="log-line-num" style="color: #666; min-width: 40px; text-align: right; user-select: none;">${l+1}</span>
<span class="log-stream-icon" style="color: ${o.stream==="stderr"?"#f59e0b":"#22c55e"};">${$}</span>
<span class="log-text" style="flex: 1; white-space: pre-wrap; word-break: break-all; color: #e5e5e5;">${i(o.text)}</span>
</div>`);const w=document.getElementById("container-logs-modal"),x=document.getElementById("cl-container-select"),j=document.getElementById("cl-log-content"),g=document.getElementById("cl-log-search"),N=document.getElementById("cl-log-tail"),P=document.getElementById("cl-refresh"),M=document.getElementById("cl-stream"),R=document.getElementById("cl-download"),h=document.getElementById("cl-clear-search"),C=document.getElementById("cl-close"),E=document.getElementById("cl-close-btn"),H=document.getElementById("cl-stream-status"),k=document.getElementById("cl-stream-indicator"),z=document.getElementById("cl-stream-text"),S=document.getElementById("cl-line-count"),T=document.getElementById("cl-filter-count"),D=document.getElementById("cl-image"),y=document.getElementById("cl-status"),B=document.getElementById("cl-created");let $=null,U=[],m=[],v=null,I=!1,b=null;function L(n){if(!n)return"-";const i=new Date(n);return isNaN(i.getTime())?n:i.toLocaleString()}function l(n){if(!n)return"";const i=document.createElement("div");return i.textContent=n,i.innerHTML}function c(n,i){const u=n.stream==="stderr"?"log-stderr":"log-stdout",A=n.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return`
<div class="log-entry ${u}" data-index="${i}" style="padding: 4px 8px; border-bottom: 1px solid #333; display: flex; gap: 8px;">
<span class="log-line-num" style="color: #666; min-width: 40px; text-align: right; user-select: none;">${i+1}</span>
<span class="log-stream-icon" style="color: ${n.stream==="stderr"?"#f59e0b":"#22c55e"};">${A}</span>
<span class="log-text" style="flex: 1; white-space: pre-wrap; word-break: break-all; color: #e5e5e5;">${l(n.text)}</span>
</div>
`}function d(o,l=""){if(!o||o.length===0){j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs available</div>',S.textContent="0 lines",T.textContent="0 filtered";return}if(O=o,u=l?o.filter(h=>h.text&&h.text.toLowerCase().includes(l.toLowerCase())):o,S.textContent=`${o.length} lines`,T.textContent=l?`${u.length} of ${o.length} shown`:`${o.length} shown`,u.length===0){j.innerHTML=`<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs match "${i(l)}"</div>`;return}j.innerHTML=u.map((h,$)=>c(h,$)).join(""),j.scrollTop=j.scrollHeight}async function y(){try{const l=(await getJSON("/api/v1/logs/containers")).containers||[],h=b.value;b.innerHTML='<option value="">Select a container...</option>',l.forEach($=>{const U=document.createElement("option");U.value=$.id,U.textContent=`${$.name} (${$.image.split(":")[0]}) - ${$.status}`,U.dataset.name=$.name,U.dataset.image=$.image,U.dataset.status=$.status,U.dataset.created=$.created,b.appendChild(U)}),h&&b.querySelector(`option[value="${h}"]`)&&(b.value=h,p(h))}catch(o){console.error("Failed to load containers:",o)}}function p(o){const l=b.querySelector(`option[value="${o}"]`);l&&(P.textContent=l.dataset.image||"-",v.textContent=l.dataset.status||"-",v.style.color=l.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",B.textContent=I(l.dataset.created))}async function n(){const o=b.value;if(!o){j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>';return}r(),H=o,p(o);const l=N.value,h=g.value.trim();j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading logs...</div>';try{const $=`/api/v1/logs/container/${o}${l!=="all"?`?tail=${l}`:""}`,U=await getJSON($);U.logs&&U.logs.length>0?d(U.logs,h):(j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs found for this container</div>',S.textContent="0 lines",T.textContent="0 filtered")}catch($){j.innerHTML=`<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error loading logs: ${i($.message)}</div>`}}function e(){const o=b.value;if(!o)return;r(),L=!0,D.textContent="\u23F9 Stop",M.style.display="flex",w.textContent="\u{1F7E2}",z.textContent="Connecting...";const l=`/api/v1/logs/stream/${o}`;m=new EventSource(l),m.onopen=()=>{w.textContent="\u{1F7E2}",z.textContent="Connected - streaming logs"},m.onmessage=h=>{try{const $=JSON.parse(h.data);if($.error){w.textContent="\u{1F534}",z.textContent=`Error: ${$.error}`;return}O.push($),u.push($),S.textContent=`${O.length} lines`,T.textContent=`${u.length} shown`;const U=g.value.trim();if(!U||$.text&&$.text.toLowerCase().includes(U.toLowerCase())){const F=document.createElement("div");F.innerHTML=c($,u.length-1);const _=F.firstElementChild;_.style.background="#1a3a1a",j.appendChild(_),j.scrollTop=j.scrollHeight}}catch($){console.error("Error parsing log:",$)}},m.onerror=()=>{w.textContent="\u{1F534}",z.textContent="Disconnected",L=!1,D.textContent="\u25B6 Stream"},x._eventSource=m}function r(){m&&(m.close(),m=null),x._eventSource&&(x._eventSource.close(),x._eventSource=null),L=!1,D.textContent="\u25B6 Stream",M.style.display="none"}function s(){if(!O||O.length===0){showNotification("No logs to download","error");return}const o=b.querySelector(`option[value="${H}"]`)?.dataset.name||H,l=new Date().toISOString().replace(/[:.]/g,"-"),h=`${o}-logs-${l}.txt`,$=O.map(J=>{const q=J.timestamp||"",K=J.stream==="stderr"?"[ERR]":"[OUT]";return`${q?q+" ":""}${K} ${J.text}`}).join(`
`),U=new Blob([$],{type:"text/plain"}),F=URL.createObjectURL(U),_=document.createElement("a");_.href=F,_.download=h,document.body.appendChild(_),_.click(),document.body.removeChild(_),URL.revokeObjectURL(F),showNotification(`Downloaded ${O.length} log lines`,"success")}b?.addEventListener("change",()=>{n()}),N?.addEventListener("change",()=>{n()}),A?.addEventListener("click",()=>{n()}),D?.addEventListener("click",()=>{L?r():e()}),R?.addEventListener("click",()=>{s()}),f?.addEventListener("click",()=>{g.value="",d(O,"")}),g?.addEventListener("input",()=>{clearTimeout(k),k=setTimeout(()=>{d(O,g.value.trim())},300)}),g?.addEventListener("keydown",o=>{o.key==="Escape"&&(g.value="",d(O,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{x.classList.add("show"),y()});function t(){r(),x.classList.remove("show")}C?.addEventListener("click",t),E?.addEventListener("click",t),document.addEventListener("keydown",o=>{o.key==="Escape"&&x.classList.contains("show")&&t()}),x.addEventListener("click",o=>{o.target===x&&t()}),window.openContainerLogsModal=function(o,l){x.classList.add("show"),y().then(()=>{const h=Array.from(b.options).find($=>$.value===o||$.dataset.name===l);h?(b.value=h.value,p(h.value),n()):o?(H=o,P.textContent=l||o,v.textContent="-",B.textContent="-",n()):j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>'})}})(),(function(){"use strict";const x=[{unit:"caddy",label:"Caddy (reverse proxy)"},{unit:"dashcaddy-api",label:"DashCaddy API (host systemd unit, not this container)"},{unit:"docker",label:"Docker daemon"},{unit:"ssh",label:"SSH server"},{unit:"systemd-journald",label:"systemd-journald"},{unit:"tailscaled",label:"Tailscale"},{unit:"networkd-dispatcher",label:"Networkd dispatcher"}];injectModal("journald-modal",`
`}function d(n,i=""){if(!n||n.length===0){j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs available</div>',S.textContent="0 lines",T.textContent="0 filtered";return}if(U=n,m=i?n.filter(u=>u.text&&u.text.toLowerCase().includes(i.toLowerCase())):n,S.textContent=`${n.length} lines`,T.textContent=i?`${m.length} of ${n.length} shown`:`${n.length} shown`,m.length===0){j.innerHTML=`<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs match "${l(i)}"</div>`;return}j.innerHTML=m.map((u,A)=>c(u,A)).join(""),j.scrollTop=j.scrollHeight}async function f(){try{const i=(await getJSON("/api/v1/logs/containers")).containers||[],u=x.value;x.innerHTML='<option value="">Select a container...</option>',i.forEach(A=>{const O=document.createElement("option");O.value=A.id,O.textContent=`${A.name} (${A.image.split(":")[0]}) - ${A.status}`,O.dataset.name=A.name,O.dataset.image=A.image,O.dataset.status=A.status,O.dataset.created=A.created,x.appendChild(O)}),u&&x.querySelector(`option[value="${u}"]`)&&(x.value=u,p(u))}catch(n){console.error("Failed to load containers:",n)}}function p(n){const i=x.querySelector(`option[value="${n}"]`);i&&(D.textContent=i.dataset.image||"-",y.textContent=i.dataset.status||"-",y.style.color=i.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",B.textContent=L(i.dataset.created))}async function e(){const n=x.value;if(!n){j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>';return}r(),$=n,p(n);const i=N.value,u=g.value.trim();j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading logs...</div>';try{const A=`/api/v1/logs/container/${n}${i!=="all"?`?tail=${i}`:""}`,O=await getJSON(A);O.logs&&O.logs.length>0?d(O.logs,u):(j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs found for this container</div>',S.textContent="0 lines",T.textContent="0 filtered")}catch(A){j.innerHTML=`<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error loading logs: ${l(A.message)}</div>`}}function s(){const n=x.value;if(!n)return;r(),I=!0,M.textContent="\u23F9 Stop",H.style.display="flex",k.textContent="\u{1F7E2}",z.textContent="Connecting...";const i=`/api/v1/logs/stream/${n}`;v=new EventSource(i),v.onopen=()=>{k.textContent="\u{1F7E2}",z.textContent="Connected - streaming logs"},v.onmessage=u=>{try{const A=JSON.parse(u.data);if(A.error){k.textContent="\u{1F534}",z.textContent=`Error: ${A.error}`;return}U.push(A),m.push(A),S.textContent=`${U.length} lines`,T.textContent=`${m.length} shown`;const O=g.value.trim();if(!O||A.text&&A.text.toLowerCase().includes(O.toLowerCase())){const _=document.createElement("div");_.innerHTML=c(A,m.length-1);const F=_.firstElementChild;F.style.background="#1a3a1a",j.appendChild(F),j.scrollTop=j.scrollHeight}}catch(A){console.error("Error parsing log:",A)}},v.onerror=()=>{k.textContent="\u{1F534}",z.textContent="Disconnected",I=!1,M.textContent="\u25B6 Stream"},w._eventSource=v}function r(){v&&(v.close(),v=null),w._eventSource&&(w._eventSource.close(),w._eventSource=null),I=!1,M.textContent="\u25B6 Stream",H.style.display="none"}function o(){if(!U||U.length===0){showNotification("No logs to download","error");return}const n=x.querySelector(`option[value="${$}"]`)?.dataset.name||$,i=new Date().toISOString().replace(/[:.]/g,"-"),u=`${n}-logs-${i}.txt`,A=U.map(q=>{const J=q.timestamp||"",G=q.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${G} ${q.text}`}).join(`
`),O=new Blob([A],{type:"text/plain"}),_=URL.createObjectURL(O),F=document.createElement("a");F.href=_,F.download=u,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(_),showNotification(`Downloaded ${U.length} log lines`,"success")}x?.addEventListener("change",()=>{e()}),N?.addEventListener("change",()=>{e()}),P?.addEventListener("click",()=>{e()}),M?.addEventListener("click",()=>{I?r():s()}),R?.addEventListener("click",()=>{o()}),h?.addEventListener("click",()=>{g.value="",d(U,"")}),g?.addEventListener("input",()=>{clearTimeout(b),b=setTimeout(()=>{d(U,g.value.trim())},300)}),g?.addEventListener("keydown",n=>{n.key==="Escape"&&(g.value="",d(U,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{w.classList.add("show"),f()});function t(){r(),w.classList.remove("show")}C?.addEventListener("click",t),E?.addEventListener("click",t),document.addEventListener("keydown",n=>{n.key==="Escape"&&w.classList.contains("show")&&t()}),w.addEventListener("click",n=>{n.target===w&&t()}),window.openContainerLogsModal=function(n,i){w.classList.add("show"),f().then(()=>{const u=Array.from(x.options).find(A=>A.value===n||A.dataset.name===i);u?(x.value=u.value,p(u.value),e()):n?($=n,D.textContent=i||n,y.textContent="-",B.textContent="-",e()):j.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>'})}})(),(function(){"use strict";const w=[{unit:"caddy",label:"Caddy (reverse proxy)"},{unit:"dashcaddy-api",label:"DashCaddy API (host systemd unit, not this container)"},{unit:"docker",label:"Docker daemon"},{unit:"ssh",label:"SSH server"},{unit:"systemd-journald",label:"systemd-journald"},{unit:"tailscaled",label:"Tailscale"},{unit:"networkd-dispatcher",label:"Networkd dispatcher"}];injectModal("journald-modal",`
<div id="journald-modal" class="weather-modal" style="z-index: 1002;">
<div class="weather-modal-content" style="min-width: 900px; max-width: 95vw; height: 80vh; display: flex; flex-direction: column;">
<div class="logs-header" style="display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; border-bottom: 1px solid var(--border); margin-bottom: 12px;">
@@ -698,7 +698,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
</div>
</div>
</div>
`);const b=document.getElementById("journald-modal"),j=document.getElementById("jd-unit-select"),g=document.getElementById("jd-search"),N=document.getElementById("jd-tail"),A=document.getElementById("jd-refresh"),D=document.getElementById("jd-stream"),R=document.getElementById("jd-clear-search"),f=document.getElementById("jd-close"),C=document.getElementById("jd-close-btn"),E=document.getElementById("jd-content"),M=document.getElementById("jd-line-count"),w=document.getElementById("jd-filter-count"),z=document.getElementById("jd-overflow"),S=document.getElementById("jd-unit-display"),T=document.getElementById("jd-stream-state");let P=!1,v=[],B=!1,H=null,O=null;function u(p){const n=document.createElement("div");return n.textContent=String(p),n.innerHTML}function m(p){P=p,j.innerHTML="",x.forEach(n=>{const e=document.createElement("option");e.value=n.unit,e.textContent=n.label+" ("+n.unit+")",j.appendChild(e)}),j.disabled=!p,p?(A.disabled=!1,D.disabled=!1):(E.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">journald bind-mount not available in this container.<br/><small>Requires <code>/var/log/journal</code> + <code>/usr/bin/journalctl</code> mounted (start.sh).</small></div>',A.disabled=!0,D.disabled=!0)}async function L(){try{const p=await fetch("/api/v1/logs/journal/units");if(!p.ok){m(!1);return}const n=await p.json();m(!!n.available)}catch{m(!1)}}function k(){const p=(g.value||"").trim().toLowerCase(),n=p?v.filter(e=>(e.textContent||"").toLowerCase().includes(p)):v;if(n.length===0)E.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No entries'+(p?` matching &quot;${u(p)}&quot;`:"")+"</div>";else{const e=n.map(s=>{const a=s.timestamp?u(s.timestamp):"\u2014",t=u(s.textContent);return`<div class="jd-line" style="padding: 1px 0; line-height: 1.4; color: #d4d4d4;"><span style="color: var(--muted); margin-right: 8px;">${a}</span>${t}</div>`}).join("");E.innerHTML=e,E.scrollHeight-E.scrollTop-E.clientHeight<80&&(E.scrollTop=E.scrollHeight)}M.textContent=`${v.length} entries`,w.textContent=p?`${n.length} of ${v.length} shown`:`${v.length} shown`}async function I(){if(!P)return;c();const p=j.value;if(!p)return;const n=Math.max(1,Math.min(5e3,Number(N.value)||200)),e=(g.value||"").trim();E.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading\u2026</div>';try{const r=new URL("/api/v1/logs/journal",window.location.origin);r.searchParams.set("unit",p),r.searchParams.set("tail",String(n)),e&&r.searchParams.set("search",e);const s=await fetch(r.toString()),a=await s.json();if(!s.ok||!a.success){E.innerHTML='<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Failed: '+u(a&&a.error||"HTTP "+s.status)+"</div>";return}S.textContent=p,v=(a.entries||[]).map(t=>({timestamp:t.timestamp,unit:t.unit,textContent:t.text||""})),z.style.display="none",k()}catch(r){E.innerHTML='<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error: '+u(r.message)+"</div>"}}function i(){if(!P)return;c();const p=j.value;if(!p)return;const n=(g.value||"").trim();S.textContent=p,D.textContent="\u23F8 Stop",D.classList.add("streaming"),T.textContent="streaming",T.style.color="var(--ok-fg, #4ade80)",v=[],k(),z.style.display="none";const e=new URL("/api/v1/logs/journal/stream",window.location.origin);e.searchParams.set("unit",p),n&&e.searchParams.set("search",n),H=new EventSource(e.toString()),H.onmessage=r=>{try{const s=JSON.parse(r.data);if(s.error){/stream (exceeded|line cap)/.test(s.error)&&(z.style.display="",c()),E.innerHTML+='<div class="jd-line" style="color: var(--bad-fg, #ef4444); padding: 4px 0;">\u26A0 '+u(s.error)+"</div>",E.scrollTop=E.scrollHeight;return}v.push({timestamp:s.timestamp,unit:s.unit||p,textContent:s.text||""}),v.length>5e3&&(v=v.slice(v.length-5e3),z.style.display=""),k()}catch{}},H.onerror=()=>{},B=!0}function c(){if(B=!1,H){try{H.close()}catch{}H=null}D.textContent="\u25B6 Stream",D.classList.remove("streaming"),T.textContent="disconnected",T.style.color="var(--muted)"}function d(){c(),b.classList.remove("show")}A.addEventListener("click",I),D.addEventListener("click",()=>B?c():i()),R.addEventListener("click",()=>{g.value="",k()}),g.addEventListener("input",()=>{clearTimeout(O),O=setTimeout(k,200)}),g.addEventListener("keydown",p=>{p.key==="Escape"&&(g.value="",k())}),f.addEventListener("click",d),C.addEventListener("click",d),b.addEventListener("click",p=>{p.target===b&&d()}),document.addEventListener("keydown",p=>{p.key==="Escape"&&b.classList.contains("show")&&d()}),j.addEventListener("change",()=>{v.length>0&&I()});function y(){b.classList.add("show"),L()}window.openJournaldModal=y,document.getElementById("view-journald-logs")?.addEventListener("click",y)})(),(function(){injectModal("snapshot-modal",`<div id="snapshot-modal" class="weather-modal">
`);const x=document.getElementById("journald-modal"),j=document.getElementById("jd-unit-select"),g=document.getElementById("jd-search"),N=document.getElementById("jd-tail"),P=document.getElementById("jd-refresh"),M=document.getElementById("jd-stream"),R=document.getElementById("jd-clear-search"),h=document.getElementById("jd-close"),C=document.getElementById("jd-close-btn"),E=document.getElementById("jd-content"),H=document.getElementById("jd-line-count"),k=document.getElementById("jd-filter-count"),z=document.getElementById("jd-overflow"),S=document.getElementById("jd-unit-display"),T=document.getElementById("jd-stream-state");let D=!1,y=[],B=!1,$=null,U=null;function m(p){const e=document.createElement("div");return e.textContent=String(p),e.innerHTML}function v(p){D=p,j.innerHTML="",w.forEach(e=>{const s=document.createElement("option");s.value=e.unit,s.textContent=e.label+" ("+e.unit+")",j.appendChild(s)}),j.disabled=!p,p?(P.disabled=!1,M.disabled=!1):(E.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">journald bind-mount not available in this container.<br/><small>Requires <code>/var/log/journal</code> + <code>/usr/bin/journalctl</code> mounted (start.sh).</small></div>',P.disabled=!0,M.disabled=!0)}async function I(){try{const p=await fetch("/api/v1/logs/journal/units");if(!p.ok){v(!1);return}const e=await p.json();v(!!e.available)}catch{v(!1)}}function b(){const p=(g.value||"").trim().toLowerCase(),e=p?y.filter(s=>(s.textContent||"").toLowerCase().includes(p)):y;if(e.length===0)E.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No entries'+(p?` matching &quot;${m(p)}&quot;`:"")+"</div>";else{const s=e.map(o=>{const a=o.timestamp?m(o.timestamp):"\u2014",t=m(o.textContent);return`<div class="jd-line" style="padding: 1px 0; line-height: 1.4; color: #d4d4d4;"><span style="color: var(--muted); margin-right: 8px;">${a}</span>${t}</div>`}).join("");E.innerHTML=s,E.scrollHeight-E.scrollTop-E.clientHeight<80&&(E.scrollTop=E.scrollHeight)}H.textContent=`${y.length} entries`,k.textContent=p?`${e.length} of ${y.length} shown`:`${y.length} shown`}async function L(){if(!D)return;c();const p=j.value;if(!p)return;const e=Math.max(1,Math.min(5e3,Number(N.value)||200)),s=(g.value||"").trim();E.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading\u2026</div>';try{const r=new URL("/api/v1/logs/journal",window.location.origin);r.searchParams.set("unit",p),r.searchParams.set("tail",String(e)),s&&r.searchParams.set("search",s);const o=await fetch(r.toString()),a=await o.json();if(!o.ok||!a.success){E.innerHTML='<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Failed: '+m(a&&a.error||"HTTP "+o.status)+"</div>";return}S.textContent=p,y=(a.entries||[]).map(t=>({timestamp:t.timestamp,unit:t.unit,textContent:t.text||""})),z.style.display="none",b()}catch(r){E.innerHTML='<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error: '+m(r.message)+"</div>"}}function l(){if(!D)return;c();const p=j.value;if(!p)return;const e=(g.value||"").trim();S.textContent=p,M.textContent="\u23F8 Stop",M.classList.add("streaming"),T.textContent="streaming",T.style.color="var(--ok-fg, #4ade80)",y=[],b(),z.style.display="none";const s=new URL("/api/v1/logs/journal/stream",window.location.origin);s.searchParams.set("unit",p),e&&s.searchParams.set("search",e),$=new EventSource(s.toString()),$.onmessage=r=>{try{const o=JSON.parse(r.data);if(o.error){/stream (exceeded|line cap)/.test(o.error)&&(z.style.display="",c()),E.innerHTML+='<div class="jd-line" style="color: var(--bad-fg, #ef4444); padding: 4px 0;">\u26A0 '+m(o.error)+"</div>",E.scrollTop=E.scrollHeight;return}y.push({timestamp:o.timestamp,unit:o.unit||p,textContent:o.text||""}),y.length>5e3&&(y=y.slice(y.length-5e3),z.style.display=""),b()}catch{}},$.onerror=()=>{},B=!0}function c(){if(B=!1,$){try{$.close()}catch{}$=null}M.textContent="\u25B6 Stream",M.classList.remove("streaming"),T.textContent="disconnected",T.style.color="var(--muted)"}function d(){c(),x.classList.remove("show")}P.addEventListener("click",L),M.addEventListener("click",()=>B?c():l()),R.addEventListener("click",()=>{g.value="",b()}),g.addEventListener("input",()=>{clearTimeout(U),U=setTimeout(b,200)}),g.addEventListener("keydown",p=>{p.key==="Escape"&&(g.value="",b())}),h.addEventListener("click",d),C.addEventListener("click",d),x.addEventListener("click",p=>{p.target===x&&d()}),document.addEventListener("keydown",p=>{p.key==="Escape"&&x.classList.contains("show")&&d()}),j.addEventListener("change",()=>{y.length>0&&L()});function f(){x.classList.add("show"),I()}window.openJournaldModal=f,document.getElementById("view-journald-logs")?.addEventListener("click",f)})(),(function(){injectModal("snapshot-modal",`<div id="snapshot-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 700px; max-width: 850px;">
<h3>\u{1F4BE} Container Snapshots</h3>
<p class="modal-subtitle">
@@ -752,7 +752,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="snapshot-close">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("snapshot-modal"),b=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),g=document.getElementById("snapshot-container-select"),N=document.getElementById("snapshot-details"),A=document.getElementById("snapshot-create-btn"),D=document.getElementById("snapshot-create-status");let R=null;async function f(){try{const S=await(await fetch("/api/v1/containers")).json();if(!S.success||!S.containers)return;g.innerHTML='<option value="">-- Select a container --</option>';for(const T of S.containers){const P=document.createElement("option");P.value=T.id,P.textContent=`${T.name||T.id} (${T.image||"unknown"})`,P.dataset.name=T.name,P.dataset.image=T.image,P.dataset.status=T.status,P.dataset.created=T.created,g.appendChild(P)}}catch(z){console.error("Failed to load containers:",z)}}function C(z){if(!z||!z.value){N.style.display="none",R=null;return}R=z.value,document.getElementById("snapshot-image").textContent=z.dataset.image||"-",document.getElementById("snapshot-status").textContent=z.dataset.status||"-",document.getElementById("snapshot-created").textContent=z.dataset.created?new Date(z.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=z.value.substring(0,12),N.style.display=""}async function E(){if(!R){D.textContent="Please select a container first",D.style.color="var(--bad-fg)";return}const z=document.getElementById("snapshot-name").value.trim();if(!z){D.textContent="Please enter a snapshot name",D.style.color="var(--bad-fg)";return}const S=document.getElementById("snapshot-leave-running").checked;A.disabled=!0,A.textContent="Creating...",D.textContent="";try{const P=await(await fetch(`/api/v1/containers/${encodeURIComponent(R)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:z,leaveRunning:S})})).json();P.success?(D.textContent=`\u2713 Snapshot "${z}" created successfully`,D.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(D.textContent=`\u2717 Failed: ${P.error||"Unknown error"}`,D.style.color="var(--bad-fg)")}catch(T){D.textContent=`\u2717 Error: ${T.message}`,D.style.color="var(--bad-fg)"}finally{A.disabled=!1,A.textContent="\u{1F4BE} Create Snapshot"}}function M(){x.classList.add("show"),f()}function w(){x.classList.remove("show"),N.style.display="none",R=null,g.selectedIndex=0}b?.addEventListener("click",M),j?.addEventListener("click",w),wireModal(x,j),g?.addEventListener("change",z=>{const S=g.options[g.selectedIndex];C(S)}),A?.addEventListener("click",E),x?.querySelectorAll(".panel-tab").forEach(z=>{z.addEventListener("click",()=>{x.querySelectorAll(".panel-tab").forEach(S=>S.classList.remove("active")),x.querySelectorAll(".panel-section").forEach(S=>S.classList.remove("active")),z.classList.add("active"),x.querySelector(`#${z.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`<div id="arr-setup-modal" class="weather-modal">
</div>`);const w=document.getElementById("snapshot-modal"),x=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),g=document.getElementById("snapshot-container-select"),N=document.getElementById("snapshot-details"),P=document.getElementById("snapshot-create-btn"),M=document.getElementById("snapshot-create-status");let R=null;async function h(){try{const S=await(await fetch("/api/v1/containers")).json();if(!S.success||!S.containers)return;g.innerHTML='<option value="">-- Select a container --</option>';for(const T of S.containers){const D=document.createElement("option");D.value=T.id,D.textContent=`${T.name||T.id} (${T.image||"unknown"})`,D.dataset.name=T.name,D.dataset.image=T.image,D.dataset.status=T.status,D.dataset.created=T.created,g.appendChild(D)}}catch(z){console.error("Failed to load containers:",z)}}function C(z){if(!z||!z.value){N.style.display="none",R=null;return}R=z.value,document.getElementById("snapshot-image").textContent=z.dataset.image||"-",document.getElementById("snapshot-status").textContent=z.dataset.status||"-",document.getElementById("snapshot-created").textContent=z.dataset.created?new Date(z.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=z.value.substring(0,12),N.style.display=""}async function E(){if(!R){M.textContent="Please select a container first",M.style.color="var(--bad-fg)";return}const z=document.getElementById("snapshot-name").value.trim();if(!z){M.textContent="Please enter a snapshot name",M.style.color="var(--bad-fg)";return}const S=document.getElementById("snapshot-leave-running").checked;P.disabled=!0,P.textContent="Creating...",M.textContent="";try{const D=await(await fetch(`/api/v1/containers/${encodeURIComponent(R)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:z,leaveRunning:S})})).json();D.success?(M.textContent=`\u2713 Snapshot "${z}" created successfully`,M.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(M.textContent=`\u2717 Failed: ${D.error||"Unknown error"}`,M.style.color="var(--bad-fg)")}catch(T){M.textContent=`\u2717 Error: ${T.message}`,M.style.color="var(--bad-fg)"}finally{P.disabled=!1,P.textContent="\u{1F4BE} Create Snapshot"}}function H(){w.classList.add("show"),h()}function k(){w.classList.remove("show"),N.style.display="none",R=null,g.selectedIndex=0}x?.addEventListener("click",H),j?.addEventListener("click",k),wireModal(w,j),g?.addEventListener("change",z=>{const S=g.options[g.selectedIndex];C(S)}),P?.addEventListener("click",E),w?.querySelectorAll(".panel-tab").forEach(z=>{z.addEventListener("click",()=>{w.querySelectorAll(".panel-tab").forEach(S=>S.classList.remove("active")),w.querySelectorAll(".panel-section").forEach(S=>S.classList.remove("active")),z.classList.add("active"),w.querySelector(`#${z.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`<div id="arr-setup-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 600px; max-width: 720px;">
<h3>\u{1F3AC} Smart Arr Connect</h3>
<p style="color: var(--muted); margin: 0 0 16px; font-size: 0.9rem;">
@@ -831,73 +831,73 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="arr-setup-cancel">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("arr-setup-modal"),b=document.getElementById("arr-setup-btn"),j=document.getElementById("arr-setup-cancel"),g=document.getElementById("smart-connect-btn"),N=document.getElementById("smart-phase-detect"),A=document.getElementById("smart-phase-credentials"),D=document.getElementById("smart-phase-progress"),R=document.getElementById("smart-phase-results"),f=document.getElementById("smart-detect-results"),C=document.getElementById("smart-credential-inputs"),E=document.getElementById("smart-progress-steps"),M=document.getElementById("smart-results-content"),w=document.getElementById("smart-plex-libraries"),z=document.getElementById("smart-retry-btn");let S=null;const T={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},P={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function v(k){N.style.display=k==="detect"?"block":"none",A.style.display=k==="credentials"?"block":"none",D.style.display=k==="progress"?"block":"none",R.style.display=k==="results"?"block":"none"}function B(k){const I={connected:{bg:"var(--ok-fg)",icon:"&#10003;",text:"Connected"},needs_key:{bg:"#f39c12",icon:"&#128273;",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"&mdash;",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"&#10007;",text:"Error"}},i=I[k]||I.not_found;return`<span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: color-mix(in srgb, ${i.bg} 20%, transparent); color: ${i.bg};">${i.icon} ${i.text}</span>`}async function H(){v("detect"),f.style.display="none";try{if(S=await(await fetch("/api/v1/arr/smart-detect")).json(),!S.success){f.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Detection failed: ${escapeHtml(S.error)}</div>`,f.style.display="block";return}let I='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[c,d]of Object.entries(S.services)){const y=T[c]||"\u{1F4E6}",p=P[c]||c,n=d.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(d.source)}</span>`:"",e=d.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(d.version)}</span>`:"",r=(d.hasApiKey||d.hasToken)&&d.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";I+=`<div style="display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${y}</span>
</div>`);const w=document.getElementById("arr-setup-modal"),x=document.getElementById("arr-setup-btn"),j=document.getElementById("arr-setup-cancel"),g=document.getElementById("smart-connect-btn"),N=document.getElementById("smart-phase-detect"),P=document.getElementById("smart-phase-credentials"),M=document.getElementById("smart-phase-progress"),R=document.getElementById("smart-phase-results"),h=document.getElementById("smart-detect-results"),C=document.getElementById("smart-credential-inputs"),E=document.getElementById("smart-progress-steps"),H=document.getElementById("smart-results-content"),k=document.getElementById("smart-plex-libraries"),z=document.getElementById("smart-retry-btn");let S=null;const T={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},D={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function y(b){N.style.display=b==="detect"?"block":"none",P.style.display=b==="credentials"?"block":"none",M.style.display=b==="progress"?"block":"none",R.style.display=b==="results"?"block":"none"}function B(b){const L={connected:{bg:"var(--ok-fg)",icon:"&#10003;",text:"Connected"},needs_key:{bg:"#f39c12",icon:"&#128273;",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"&mdash;",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"&#10007;",text:"Error"}},l=L[b]||L.not_found;return`<span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: color-mix(in srgb, ${l.bg} 20%, transparent); color: ${l.bg};">${l.icon} ${l.text}</span>`}async function $(){y("detect"),h.style.display="none";try{if(S=await(await fetch("/api/v1/arr/smart-detect")).json(),!S.success){h.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Detection failed: ${escapeHtml(S.error)}</div>`,h.style.display="block";return}let L='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[c,d]of Object.entries(S.services)){const f=T[c]||"\u{1F4E6}",p=D[c]||c,e=d.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(d.source)}</span>`:"",s=d.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(d.version)}</span>`:"",r=(d.hasApiKey||d.hasToken)&&d.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";L+=`<div style="display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${f}</span>
<div style="flex: 1;">
<div style="font-weight: 500; font-size: 0.9rem;">${p}</div>
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
${n} ${e} ${r}
${e} ${s} ${r}
</div>
</div>
${B(d.status)}
</div>`}I+="</div>";const i=S.summary;I+=`<div style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; font-size: 0.85rem;">
${escapeHtml(String(i.fullyConnected))}/${escapeHtml(String(i.totalDetected+(5-i.totalDetected)))} services detected &middot;
${escapeHtml(String(i.fullyConnected))} connected${i.needsApiKey>0?` &middot; <strong>${escapeHtml(String(i.needsApiKey))} needs API key</strong>`:""}
</div>`,f.innerHTML=I,f.style.display="block",O(S),setTimeout(()=>{v("credentials")},800)}catch(k){f.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(k.message)}</div>`,f.style.display="block"}}function O(k){let I="";const i=k.services,c=["radarr","sonarr","prowlarr"];for(const p of c){const n=i[p];if(!n||n.status==="not_found"&&!n.url)continue;const e=T[p],r=P[p],s=n.status==="connected";I+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${s?"var(--ok-fg)":"var(--border)"};">
</div>`}L+="</div>";const l=S.summary;L+=`<div style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; font-size: 0.85rem;">
${escapeHtml(String(l.fullyConnected))}/${escapeHtml(String(l.totalDetected+(5-l.totalDetected)))} services detected &middot;
${escapeHtml(String(l.fullyConnected))} connected${l.needsApiKey>0?` &middot; <strong>${escapeHtml(String(l.needsApiKey))} needs API key</strong>`:""}
</div>`,h.innerHTML=L,h.style.display="block",U(S),setTimeout(()=>{y("credentials")},800)}catch(b){h.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(b.message)}</div>`,h.style.display="block"}}function U(b){let L="";const l=b.services,c=["radarr","sonarr","prowlarr"];for(const p of c){const e=l[p];if(!e||e.status==="not_found"&&!e.url)continue;const s=T[p],r=D[p],o=e.status==="connected";L+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${o?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
<span style="font-size: 1.1rem;">${e}</span>
<span style="font-size: 1.1rem;">${s}</span>
<span style="font-weight: 500;">${r}</span>
<span id="smart-${p}-status" style="margin-left: auto; font-size: 0.75rem;">
${s?'<span style="color: var(--ok-fg);">&#10003; Connected</span>':""}
${o?'<span style="color: var(--ok-fg);">&#10003; Connected</span>':""}
</span>
</div>
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px;">
<div>
<label style="font-size: 0.75rem; color: var(--muted);">URL:</label>
<input type="text" id="smart-${p}-url" value="${escapeHtml(n.url||"")}" placeholder="https://seedbox.com/${p}/"
<input type="text" id="smart-${p}-url" value="${escapeHtml(e.url||"")}" placeholder="https://seedbox.com/${p}/"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div>
<div>
<label style="font-size: 0.75rem; color: var(--muted);">API Key:</label>
<input type="password" id="smart-${p}-key" placeholder="${s?"(saved)":"Paste API key"}"
<input type="password" id="smart-${p}-key" placeholder="${o?"(saved)":"Paste API key"}"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div>
</div>
<button onclick="smartTestConnection('${p}')" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
</div>`}const d=i.plex;if(d){const p=d.status==="connected";I+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${p?"var(--ok-fg)":"var(--border)"}; margin-bottom: 10px;">
<button type="button" data-smart-test="${p}" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
</div>`}const d=l.plex;if(d){const p=d.status==="connected";L+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${p?"var(--ok-fg)":"var(--border)"}; margin-bottom: 10px;">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F3AC}</span>
<span style="font-weight: 500;">Plex</span>
${B(d.status)}
<span style="margin-left: auto; font-size: 0.75rem; color: var(--muted);">${escapeHtml(d.source||"")}</span>
</div>
</div>`}const y=i.seerr;if(y){const p=y.status==="connected";let n="";if(y.configuredServices){const e=y.configuredServices;n=`<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">
Configured: ${e.radarr?"&#10003; Radarr":"&#10007; Radarr"} &middot;
${e.sonarr?"&#10003; Sonarr":"&#10007; Sonarr"} &middot;
${e.plex?"&#10003; Plex":"&#10007; Plex"}
</div>`}I+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${p?"var(--ok-fg)":"var(--border)"};">
</div>`}const f=l.seerr;if(f){const p=f.status==="connected";let e="";if(f.configuredServices){const s=f.configuredServices;e=`<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">
Configured: ${s.radarr?"&#10003; Radarr":"&#10007; Radarr"} &middot;
${s.sonarr?"&#10003; Sonarr":"&#10007; Sonarr"} &middot;
${s.plex?"&#10003; Plex":"&#10007; Plex"}
</div>`}L+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${p?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F4CB}</span>
<span style="font-weight: 500;">Seerr</span>
${B(y.status)}
${B(f.status)}
</div>
${n}
</div>`}C.innerHTML=I}window.smartTestConnection=async function(k){const I=document.getElementById(`smart-${k}-url`),i=document.getElementById(`smart-${k}-key`),c=document.getElementById(`smart-${k}-status`),d=I?.value.trim(),y=i?.value.trim();if(!d||!y){c.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}c.innerHTML='<span class="brand-spinner"></span>';try{const n=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:k,url:d,apiKey:y})})).json();n.success?c.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(n.appName||"Connected")} v${escapeHtml(n.version||"")}</span>`:c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(n.error)}</span>`}catch(p){c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(p.message)}</span>`}};async function u(){v("progress"),E.innerHTML='<div style="text-align: center; padding: 20px;"><span class="brand-spinner"></span><div style="color: var(--muted); margin-top: 8px;">Connecting services...</div></div>';const k={};for(const i of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${i}-url`)?.value.trim(),d=document.getElementById(`smart-${i}-key`)?.value.trim();d&&c?k[i]={apiKey:d,url:c}:d&&(k[i]={apiKey:d})}const I={services:Object.keys(k).length>0?k:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)})).json();let d="";for(const y of c.steps||[]){const p=y.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',n=y.status==="success"?"var(--muted)":"var(--bad-fg)";d+=`<div style="display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;">
${e}
</div>`}C.innerHTML=L,C.querySelectorAll("[data-smart-test]").forEach(p=>{p.addEventListener("click",()=>window.smartTestConnection(p.dataset.smartTest))})}window.smartTestConnection=async function(b){const L=document.getElementById(`smart-${b}-url`),l=document.getElementById(`smart-${b}-key`),c=document.getElementById(`smart-${b}-status`),d=L?.value.trim(),f=l?.value.trim();if(!d||!f){c.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}c.innerHTML='<span class="brand-spinner"></span>';try{const e=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:b,url:d,apiKey:f})})).json();e.success?c.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(e.appName||"Connected")} v${escapeHtml(e.version||"")}</span>`:c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(e.error)}</span>`}catch(p){c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(p.message)}</span>`}};async function m(){y("progress"),E.innerHTML='<div style="text-align: center; padding: 20px;"><span class="brand-spinner"></span><div style="color: var(--muted); margin-top: 8px;">Connecting services...</div></div>';const b={};for(const l of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${l}-url`)?.value.trim(),d=document.getElementById(`smart-${l}-key`)?.value.trim();d&&c?b[l]={apiKey:d,url:c}:d&&(b[l]={apiKey:d})}const L={services:Object.keys(b).length>0?b:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)})).json();let d="";for(const f of c.steps||[]){const p=f.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',e=f.status==="success"?"var(--muted)":"var(--bad-fg)";d+=`<div style="display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;">
${p}
<span>${escapeHtml(y.step)}</span>
<span style="margin-left: auto; font-size: 0.75rem; color: ${n};">${escapeHtml(y.details||"")}</span>
</div>`}E.innerHTML=d,setTimeout(()=>m(c),500)}catch(i){E.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(i.message)}</div>`}}function m(k){v("results");const I=k.summary||{},i=I.failed===0&&I.succeeded>0,c=i?"var(--ok-fg)":"#f39c12",d=i?"&#10003;":"&#9888;",y=i?"All Connected!":`${escapeHtml(String(I.succeeded))}/${escapeHtml(String(I.totalSteps))} Steps Succeeded`;let p=`<div style="text-align: center; padding: 16px; background: color-mix(in srgb, ${c} 12%, transparent); border-radius: 10px; border: 1px solid ${c}; margin-bottom: 12px;">
<span>${escapeHtml(f.step)}</span>
<span style="margin-left: auto; font-size: 0.75rem; color: ${e};">${escapeHtml(f.details||"")}</span>
</div>`}E.innerHTML=d,setTimeout(()=>v(c),500)}catch(l){E.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(l.message)}</div>`}}function v(b){y("results");const L=b.summary||{},l=L.failed===0&&L.succeeded>0,c=l?"var(--ok-fg)":"#f39c12",d=l?"&#10003;":"&#9888;",f=l?"All Connected!":`${escapeHtml(String(L.succeeded))}/${escapeHtml(String(L.totalSteps))} Steps Succeeded`;let p=`<div style="text-align: center; padding: 16px; background: color-mix(in srgb, ${c} 12%, transparent); border-radius: 10px; border: 1px solid ${c}; margin-bottom: 12px;">
<div style="font-size: 1.5rem; color: ${c};">${d}</div>
<div style="font-size: 1.1rem; font-weight: 600; color: ${c};">${y}</div>
<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(I.succeeded))} succeeded, ${escapeHtml(String(I.failed))} failed</div>
</div>`;p+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const n of k.steps||[]){const e=n.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>';p+=`<div style="display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: 0.8rem;">
${e} ${escapeHtml(n.step)} <span style="margin-left: auto; color: var(--muted); font-size: 0.75rem;">${escapeHtml(n.details||"")}</span>
</div>`}p+="</div>",M.innerHTML=p,z.style.display=I.failed>0?"block":"none",k.steps?.some(n=>n.step.includes("Plex")&&n.status==="success")&&L()}async function L(){try{const I=await(await fetch("/api/v1/plex/libraries")).json();if(I.success&&I.libraries?.length>0){let i=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 8px; font-size: 0.85rem; color: var(--accent);">\u{1F3AC} ${escapeHtml(I.serverName)} Libraries</h4>
<div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const c of I.libraries){const d=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";i+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
<div style="font-size: 1.1rem; font-weight: 600; color: ${c};">${f}</div>
<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(L.succeeded))} succeeded, ${escapeHtml(String(L.failed))} failed</div>
</div>`;p+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const e of b.steps||[]){const s=e.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>';p+=`<div style="display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: 0.8rem;">
${s} ${escapeHtml(e.step)} <span style="margin-left: auto; color: var(--muted); font-size: 0.75rem;">${escapeHtml(e.details||"")}</span>
</div>`}p+="</div>",H.innerHTML=p,z.style.display=L.failed>0?"block":"none",b.steps?.some(e=>e.step.includes("Plex")&&e.status==="success")&&I()}async function I(){try{const L=await(await fetch("/api/v1/plex/libraries")).json();if(L.success&&L.libraries?.length>0){let l=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 8px; font-size: 0.85rem; color: var(--accent);">\u{1F3AC} ${escapeHtml(L.serverName)} Libraries</h4>
<div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const c of L.libraries){const d=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";l+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
${d} <strong>${escapeHtml(c.title)}</strong>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(String(c.count))} items</span>
</div>`}i+="</div></div>",w.innerHTML=i,w.style.display="block"}}catch{}}b?.addEventListener("click",()=>{x.classList.add("show"),w.style.display="none",H()}),wireModal(x,j),g?.addEventListener("click",u),z?.addEventListener("click",u)})(),(function(){const x=new ErrorHandler;injectModal("notifications-modal",`<div id="notifications-modal" class="weather-modal">
</div>`}l+="</div></div>",k.innerHTML=l,k.style.display="block"}}catch{}}x?.addEventListener("click",()=>{w.classList.add("show"),k.style.display="none",$()}),wireModal(w,j),g?.addEventListener("click",m),z?.addEventListener("click",m)})(),(function(){const w=new ErrorHandler;injectModal("notifications-modal",`<div id="notifications-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F514} Notification Settings</h3>
@@ -1109,15 +1109,15 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="notifications-save" class="btn-accent">Save Settings</button>
</div>
</div>
</div>`);const b=document.getElementById("notifications-modal"),j=document.getElementById("manage-notifications"),g=document.getElementById("notifications-save"),N=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(w=>{const z=document.getElementById(`${w}-enabled`),S=document.getElementById(`${w}-config`);z?.addEventListener("change",()=>{S.style.display=z.checked?"block":"none"})});const A=document.getElementById("health-check-enabled"),D=document.getElementById("health-check-config");A?.addEventListener("change",()=>{D.style.opacity=A.checked?"1":"0.5"});async function R(){try{const z=await(await fetch("/api/v1/notifications/config")).json();if(z.success){const S=z.config;document.getElementById("notifications-enabled").checked=S.enabled,document.getElementById("discord-enabled").checked=S.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=S.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=S.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=S.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=S.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=S.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=S.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=S.providers?.email?.enabled?"block":"none",S.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=S.providers.ntfy.serverUrl),S.providers?.email?.host&&(document.getElementById("email-host").value=S.providers.email.host),S.providers?.email?.from&&(document.getElementById("email-from").value=S.providers.email.from),S.providers?.email?.to&&(document.getElementById("email-to").value=S.providers.email.to),S.providers?.email?.port&&(document.getElementById("email-port").value=S.providers.email.port),S.providers?.email?.secure!==void 0&&(document.getElementById("email-secure").checked=S.providers.email.secure===!0),S.providers?.email?.username&&(document.getElementById("email-user").value=S.providers.email.username);const T=document.getElementById("email-pass");S.providers?.email?.hasPassword?(T.value="",T.placeholder="saved \u2014 leave blank to keep"):T.placeholder="app password",document.getElementById("health-check-enabled").checked=S.healthCheck?.enabled||!1,S.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=S.healthCheck.intervalMinutes),S.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(S.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=S.events?.["container-down"]!==!1,document.getElementById("event-container-up").checked=S.events?.["container-up"]===!0,document.getElementById("event-deploy-success").checked=S.events?.["deploy-success"]!==!1,document.getElementById("event-deploy-failed").checked=S.events?.["deploy-failed"]!==!1,document.getElementById("event-ssl-cert-expiry").checked=S.events?.["ssl-cert-expiry"]!==!1,document.getElementById("event-dns-propagation").checked=S.events?.["dns-propagation"]!==!1,document.getElementById("event-drift-detected").checked=S.events?.["drift-detected"]!==!1,document.getElementById("event-dependency-restart").checked=S.events?.["dependency-restart"]!==!1,document.getElementById("event-recipe-removed").checked=S.events?.["recipe-removed"]!==!1,document.getElementById("event-workflow").checked=S.events?.workflow!==!1,document.getElementById("event-backup-complete").checked=S.events?.["backup-complete"]!==!1,document.getElementById("event-backup-failed").checked=S.events?.["backup-failed"]!==!1,document.getElementById("event-update-available").checked=S.events?.["update-available"]!==!1,document.getElementById("event-resource-alert").checked=S.events?.alert!==!1}}catch(w){x.logError("[Notifications] Load Config",w,{function:"loadConfig"})}}async function f(){try{const z=await(await fetch("/api/v1/notifications/history?limit=10")).json(),S=document.getElementById("notification-history");z.success&&z.history?.length>0?S.innerHTML=z.history.map(T=>{const P=new Date(T.timestamp).toLocaleString();return`
</div>`);const x=document.getElementById("notifications-modal"),j=document.getElementById("manage-notifications"),g=document.getElementById("notifications-save"),N=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const z=document.getElementById(`${k}-enabled`),S=document.getElementById(`${k}-config`);z?.addEventListener("change",()=>{S.style.display=z.checked?"block":"none"})});const P=document.getElementById("health-check-enabled"),M=document.getElementById("health-check-config");P?.addEventListener("change",()=>{M.style.opacity=P.checked?"1":"0.5"});async function R(){try{const z=await(await fetch("/api/v1/notifications/config")).json();if(z.success){const S=z.config;document.getElementById("notifications-enabled").checked=S.enabled,document.getElementById("discord-enabled").checked=S.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=S.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=S.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=S.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=S.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=S.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=S.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=S.providers?.email?.enabled?"block":"none",S.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=S.providers.ntfy.serverUrl),S.providers?.email?.host&&(document.getElementById("email-host").value=S.providers.email.host),S.providers?.email?.from&&(document.getElementById("email-from").value=S.providers.email.from),S.providers?.email?.to&&(document.getElementById("email-to").value=S.providers.email.to),S.providers?.email?.port&&(document.getElementById("email-port").value=S.providers.email.port),S.providers?.email?.secure!==void 0&&(document.getElementById("email-secure").checked=S.providers.email.secure===!0),S.providers?.email?.username&&(document.getElementById("email-user").value=S.providers.email.username);const T=document.getElementById("email-pass");S.providers?.email?.hasPassword?(T.value="",T.placeholder="saved \u2014 leave blank to keep"):T.placeholder="app password",document.getElementById("health-check-enabled").checked=S.healthCheck?.enabled||!1,S.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=S.healthCheck.intervalMinutes),S.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(S.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=S.events?.["container-down"]!==!1,document.getElementById("event-container-up").checked=S.events?.["container-up"]===!0,document.getElementById("event-deploy-success").checked=S.events?.["deploy-success"]!==!1,document.getElementById("event-deploy-failed").checked=S.events?.["deploy-failed"]!==!1,document.getElementById("event-ssl-cert-expiry").checked=S.events?.["ssl-cert-expiry"]!==!1,document.getElementById("event-dns-propagation").checked=S.events?.["dns-propagation"]!==!1,document.getElementById("event-drift-detected").checked=S.events?.["drift-detected"]!==!1,document.getElementById("event-dependency-restart").checked=S.events?.["dependency-restart"]!==!1,document.getElementById("event-recipe-removed").checked=S.events?.["recipe-removed"]!==!1,document.getElementById("event-workflow").checked=S.events?.workflow!==!1,document.getElementById("event-backup-complete").checked=S.events?.["backup-complete"]!==!1,document.getElementById("event-backup-failed").checked=S.events?.["backup-failed"]!==!1,document.getElementById("event-update-available").checked=S.events?.["update-available"]!==!1,document.getElementById("event-resource-alert").checked=S.events?.alert!==!1}}catch(k){w.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function h(){try{const z=await(await fetch("/api/v1/notifications/history?limit=10")).json(),S=document.getElementById("notification-history");z.success&&z.history?.length>0?S.innerHTML=z.history.map(T=>{const D=new Date(T.timestamp).toLocaleString();return`
<div style="padding: 6px 8px; border-bottom: 1px solid var(--border); display: flex; gap: 8px; align-items: flex-start;">
<span style="color: ${{success:"var(--ok-fg)",error:"var(--bad-fg)",warning:"#f39c12",info:"var(--accent)"}[T.type]||"var(--muted)"}">${T.type==="success"?"\u2713":T.type==="error"?"\u2717":"\u2139"}</span>
<div style="flex: 1; min-width: 0;">
<div style="font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(T.title)}</div>
<div style="font-size: 0.7rem; color: var(--muted);">${P}</div>
<div style="font-size: 0.7rem; color: var(--muted);">${D}</div>
</div>
</div>
`}).join(""):S.innerHTML='<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>'}catch(w){x.logError("[Notifications] Load History",w,{function:"loadHistory"})}}async function C(){try{const w={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,username:document.getElementById("email-user").value.trim(),password:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{"container-down":document.getElementById("event-container-down").checked,"container-up":document.getElementById("event-container-up").checked,"deploy-success":document.getElementById("event-deploy-success").checked,"deploy-failed":document.getElementById("event-deploy-failed").checked,"ssl-cert-expiry":document.getElementById("event-ssl-cert-expiry").checked,"dns-propagation":document.getElementById("event-dns-propagation").checked,"drift-detected":document.getElementById("event-drift-detected").checked,"dependency-restart":document.getElementById("event-dependency-restart").checked,"recipe-removed":document.getElementById("event-recipe-removed").checked,workflow:document.getElementById("event-workflow").checked,"backup-complete":document.getElementById("event-backup-complete").checked,"backup-failed":document.getElementById("event-backup-failed").checked,"update-available":document.getElementById("event-update-available").checked,alert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},S=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)})).json();S.success?(showNotification("Notification settings saved","success",3e3),b.classList.remove("show")):showNotification(`Failed to save: ${S.error}`,"error",3e3)}catch(w){showNotification(`Error: ${w.message}`,"error",3e3)}}async function E(w){try{const S=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:w})})).json();S.success?showNotification(`Test ${w} notification sent!`,"success",3e3):showNotification(`Test failed: ${S.error}`,"error",3e3)}catch(z){showNotification(`Error: ${z.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>E("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>E("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>E("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>E("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const z=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();z.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(z.lastCheck).toLocaleString()} (${z.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(w){showNotification(`Error: ${w.message}`,"error",3e3)}}),j?.addEventListener("click",()=>{b.classList.add("show"),R(),f()}),g?.addEventListener("click",C),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const w=document.getElementById("notifications-send-test"),z=w.textContent;w.textContent="Sending...",w.disabled=!0;try{const T=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();T.success?(showNotification("Test notification sent!","success",3e3),M()):showNotification(`Test failed: ${T.results?.map(P=>`${P.provider}: ${P.error||"ok"}`).join(", ")}`,"error",5e3)}catch(S){showNotification(`Error: ${S.message}`,"error",3e3)}finally{w.textContent=z,w.disabled=!1}});async function M(){try{const z=await(await fetch("/api/v1/notifications/status")).json();if(z.success&&z.lastSent){ Line truncated
`}).join(""):S.innerHTML='<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>'}catch(k){w.logError("[Notifications] Load History",k,{function:"loadHistory"})}}async function C(){try{const k={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,username:document.getElementById("email-user").value.trim(),password:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{"container-down":document.getElementById("event-container-down").checked,"container-up":document.getElementById("event-container-up").checked,"deploy-success":document.getElementById("event-deploy-success").checked,"deploy-failed":document.getElementById("event-deploy-failed").checked,"ssl-cert-expiry":document.getElementById("event-ssl-cert-expiry").checked,"dns-propagation":document.getElementById("event-dns-propagation").checked,"drift-detected":document.getElementById("event-drift-detected").checked,"dependency-restart":document.getElementById("event-dependency-restart").checked,"recipe-removed":document.getElementById("event-recipe-removed").checked,workflow:document.getElementById("event-workflow").checked,"backup-complete":document.getElementById("event-backup-complete").checked,"backup-failed":document.getElementById("event-backup-failed").checked,"update-available":document.getElementById("event-update-available").checked,alert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},S=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();S.success?(showNotification("Notification settings saved","success",3e3),x.classList.remove("show")):showNotification(`Failed to save: ${S.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function E(k){try{const S=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:k})})).json();S.success?showNotification(`Test ${k} notification sent!`,"success",3e3):showNotification(`Test failed: ${S.error}`,"error",3e3)}catch(z){showNotification(`Error: ${z.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>E("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>E("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>E("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>E("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const z=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();z.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(z.lastCheck).toLocaleString()} (${z.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),j?.addEventListener("click",()=>{x.classList.add("show"),R(),h()}),g?.addEventListener("click",C),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),z=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const T=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();T.success?(showNotification("Test notification sent!","success",3e3),H()):showNotification(`Test failed: ${T.results?.map(D=>`${D.provider}: ${D.error||"ok"}`).join(", ")}`,"error",5e3)}catch(S){showNotification(`Error: ${S.message}`,"error",3e3)}finally{k.textContent=z,k.disabled=!1}});async function H(){try{const z=await(await fetch("/api/v1/notifications/status")).json();if(z.success&&z.lastSent){ Line truncated
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F4BE} Backup & Restore</h3>
<p class="modal-subtitle">
@@ -1223,9 +1223,9 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="backup-cancel">Close</button>
</div>
</div>
</div>`);var A=document.getElementById("backup-modal"),D=document.getElementById("backup-restore-btn"),R=document.getElementById("backup-cancel"),f=document.getElementById("backup-export-btn"),C=document.getElementById("backup-select-file"),E=document.getElementById("backup-file-input"),M=document.getElementById("backup-file-name"),w=document.getElementById("backup-preview"),z=document.getElementById("backup-preview-content"),S=document.getElementById("backup-do-restore-btn"),T=document.getElementById("backup-result"),P=document.getElementById("backup-schedules-container"),v=document.getElementById("backup-history-container"),B=document.getElementById("backup-disk-container"),H=document.getElementById("pointintime-container"),O=null;D?.addEventListener("click",function(){A.classList.add("show"),T&&(T.style.display="none"),w&&(w.style.display="none"),M&&(M.style.display="none"),O=null}),wireModal(A,R),f?.addEventListener("click",async function(){f.disabled=!0,f.innerHTML='<span class="brand-spinner"></span> Exporting...';try{var e=await fetch("/api/v1/backup/export"),r=await e.json();r.browserState=b();var s=new Blob([JSON.stringify(r,null,2)],{type:"application/json"}),a=URL.createObjectURL(s),t=document.createElement("a");t.href=a,t.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(t),t.click(),document.body.removeChild(t),URL.revokeObjectURL(a);var o=Object.keys(r.browserState).length,l=r.themes?Object.keys(r.themes).length:0;T.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+o+" browser settings"+(l?" + "+l+" themes":""),T.style.display="block",T.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",T.style.border="1px solid var(--ok-fg)"}catch(h){T.innerHTML="\u274C Export failed: "+escapeHtml(h.message),T.style.display="block",T.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",T.style.border="1px solid var(--bad-fg)"}f.disabled=!1,f.innerHTML="\u2B07\uFE0F Download Full Backup"}),C?.addEventListener("click",function(){E.click()}),E?.addEventListener("change",async function(e){var r=e.target.files[0];if(r){M.textContent="\u{1F4C4} "+r.name,M.style.display="block",T.style.display="none";try{var s=await r.text(),a=JSON.parse(s);if(g(a)){O=a;var t='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(a.version)+")</div>";t+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',a.services?.length&&(t+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4CB} '+a.services.length+" services</span>"),a.customApps?.length&&(t+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4E6} '+a.customApps.length+" custom apps</span>"),a.theme&&(t+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(a.theme)+"</span>"),a.userThemes&&(t+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} '+Object.keys(a.userThemes).length+" custom themes</span>"),t+="</div>",z.innerHTML=t,w.style.display="block";return}var o=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),l=await o.json();if(l.success){O=a;var t='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(a.exportedAt).toLocaleString()+" (v"+escapeHtml(a.version)+")</div>";t+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',t+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var h in l.preview.files){var $=l.preview.files[h],U=$.action==="create"?"\u{1F195}":"\u{1F4DD}";t+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+U+" "+escapeHtml($.description)+"</span>"}t+="</div>",l.preview.serviceCount&&(t+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+l.preview.serviceCount+" services</div>"),l.preview.themeCount&&(t+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+l.preview.themeCount+" custom themes</div>"),l.preview.browserStateCount&&(t+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',t+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+l.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),z.innerHTML=t,w.style.display="block"}else T.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(l.error),T.style.display="block",T.style.background="color-mix(in srgb, #f39c12 15%, transparent)",T.style.border="1px solid #f39c12",w.style.display="none"}catch(F){T.innerHTML="\u274CLine truncated
</div>`);var P=document.getElementById("backup-modal"),M=document.getElementById("backup-restore-btn"),R=document.getElementById("backup-cancel"),h=document.getElementById("backup-export-btn"),C=document.getElementById("backup-select-file"),E=document.getElementById("backup-file-input"),H=document.getElementById("backup-file-name"),k=document.getElementById("backup-preview"),z=document.getElementById("backup-preview-content"),S=document.getElementById("backup-do-restore-btn"),T=document.getElementById("backup-result"),D=document.getElementById("backup-schedules-container");function y(r){!r||!r.querySelectorAll||r.querySelectorAll("[data-upgrade-msg]").forEach(o=>{o.addEventListener("click",()=>{showNotification(o.dataset.upgradeMsg,"info"),window.openLicenseModal&&window.openLicenseModal()})})}var B=document.getElementById("backup-history-container"),$=document.getElementById("backup-disk-container"),U=document.getElementById("pointintime-container"),m=null;M?.addEventListener("click",function(){P.classList.add("show"),T&&(T.style.display="none"),k&&(k.style.display="none"),H&&(H.style.display="none"),m=null}),wireModal(P,R),h?.addEventListener("click",async function(){h.disabled=!0,h.innerHTML='<span class="brand-spinner"></span> Exporting...';try{var r=await fetch("/api/v1/backup/export"),o=await r.json();o.browserState=x();var a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),t=URL.createObjectURL(a),n=document.createElement("a");n.href=t,n.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(t);var i=Object.keys(o.browserState).length,u=o.themes?Object.keys(o.themes).length:0;T.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+i+" browser settings"+(u?" + "+u+" themes":""),T.style.display="block",T.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",T.style.border="1px solid var(--ok-fg)"}catch(A){T.innerHTML="\u274C Export failed: "+escapeHtml(A.message),T.style.display="block",T.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",T.style.border="1px solid var(--bad-fg)"}h.disabled=!1,h.innerHTML="\u2B07\uFE0F Download Full Backup"}),C?.addEventListener("click",function(){E.click()}),E?.addEventListener("change",async function(r){var o=r.target.files[0];if(o){H.textContent="\u{1F4C4} "+o.name,H.style.display="block",T.style.display="none";try{var a=await o.text(),t=JSON.parse(a);if(g(t)){m=t;var n='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(t.version)+")</div>";n+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',t.services?.length&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4CB} '+t.services.length+" services</span>"),t.customApps?.length&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4E6} '+t.customApps.length+" custom apps</span>"),t.theme&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(t.theme)+"</span>"),t.userThemes&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} '+Object.keys(t.userThemes).length+" custom themes</span>"),n+="</div>",z.innerHTML=n,k.style.display="block";return}var i=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),u=await i.json();if(u.success){m=t;var n='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(t.exportedAt).toLocaleString()+" (v"+escapeHtml(t.version)+")</div>";n+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',n+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var A in u.preview.files){var O=u.preview.files[A],_=O.action==="create"?"\u{1F195}":"\u{1F4DD}";n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+_+" "+escapeHtml(O.description)+"</span>"}n+="</div>",u.preview.serviceCount&&(n+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+u.preview.serviceCount+" services</div>"),u.preview.themeCount&&(n+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+u.preview.themeCount+" custom themes</div>"),u.preview.browserStateCount&&(n+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',n+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+u.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),z.innerHTML=n,k.style.display="block"}else T.innerHTML="\u2Line truncated
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var s=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(r),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),a=await s.json();a.success?(showNotification(e+" restored to "+r,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Restore error: "+t.message,"error")}}})(),(function(){injectModal("stats-modal",`<div id="stats-modal" class="weather-modal">
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var a=await secureFetch("/api/v1/apps/"+encodeURIComponent(r)+"/revert/"+encodeURIComponent(o),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),t=await a.json();t.success?(showNotification(r+" restored to "+o,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(t.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`<div id="stats-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u{1F4CA} Resource Monitor</h3>
<p class="modal-subtitle">
@@ -1305,72 +1305,72 @@ This will replace current configuration, credentials, and data. Containers will
<button id="stats-cancel">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("stats-modal"),b=document.getElementById("container-stats-btn"),j=document.getElementById("stats-cancel"),g=document.getElementById("stats-refresh-btn"),N=document.getElementById("stats-auto-refresh"),A=document.getElementById("stats-container"),D=document.getElementById("stats-aggregated-container"),R=document.getElementById("stats-alerts-container"),f=document.getElementById("stats-last-update");let C=null,E=null;function M(d){if(d===0||!d)return"0 B";const y=1024,p=["B","KB","MB","GB"],n=Math.floor(Math.log(d)/Math.log(y));return parseFloat((d/Math.pow(y,n)).toFixed(1))+" "+p[n]}function w(d){return d<30?"#2ecc71":d<70?"#f39c12":"#e74c3c"}function z(d){return d<50?"#2ecc71":d<80?"#f39c12":"#e74c3c"}async function S(){try{let d=null,y=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(d=e.stats,y=!0,E=e.stats)}catch{}if(!y){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){d={};for(const r of e.stats)d[r.name]={name:r.name,current:{cpu:r.cpu,memory:{percent:r.memory.percent,usage:r.memory.used,limit:r.memory.limit,usageMB:Math.round(r.memory.used/1048576),limitMB:Math.round(r.memory.limit/1048576)},network:{rxBytes:r.network.rx,txBytes:r.network.tx,rxMB:(r.network.rx/1048576).toFixed(1),txMB:(r.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:r.status};E=d}}if(!d||Object.keys(d).length===0){A.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">No running containers found</div>';return}let p='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[n,e]of Object.entries(d)){const r=e.current||e,s=r.cpu?.percent||0,a=r.memory?.percent||0,t=w(s),o=z(a),l=r.memory?.usage||r.memory?.used||0,h=r.memory?.limit||0,$=r.network?.rxBytes||r.network?.rx||0,U=r.network?.txBytes||r.network?.tx||0,F=e.aggregated;p+=`
</div>`);const w=document.getElementById("stats-modal"),x=document.getElementById("container-stats-btn"),j=document.getElementById("stats-cancel"),g=document.getElementById("stats-refresh-btn"),N=document.getElementById("stats-auto-refresh"),P=document.getElementById("stats-container"),M=document.getElementById("stats-aggregated-container"),R=document.getElementById("stats-alerts-container"),h=document.getElementById("stats-last-update");let C=null,E=null;function H(d){if(d===0||!d)return"0 B";const f=1024,p=["B","KB","MB","GB"],e=Math.floor(Math.log(d)/Math.log(f));return parseFloat((d/Math.pow(f,e)).toFixed(1))+" "+p[e]}function k(d){return d<30?"#2ecc71":d<70?"#f39c12":"#e74c3c"}function z(d){return d<50?"#2ecc71":d<80?"#f39c12":"#e74c3c"}async function S(){try{let d=null,f=!1;try{const s=await(await fetch("/api/v1/monitoring/stats")).json();s.success&&s.stats&&(d=s.stats,f=!0,E=s.stats)}catch{}if(!f){const s=await(await fetch("/api/v1/stats/containers")).json();if(s.success&&s.stats){d={};for(const r of s.stats)d[r.name]={name:r.name,current:{cpu:r.cpu,memory:{percent:r.memory.percent,usage:r.memory.used,limit:r.memory.limit,usageMB:Math.round(r.memory.used/1048576),limitMB:Math.round(r.memory.limit/1048576)},network:{rxBytes:r.network.rx,txBytes:r.network.tx,rxMB:(r.network.rx/1048576).toFixed(1),txMB:(r.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:r.status};E=d}}if(!d||Object.keys(d).length===0){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">No running containers found</div>';return}let p='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[e,s]of Object.entries(d)){const r=s.current||s,o=r.cpu?.percent||0,a=r.memory?.percent||0,t=k(o),n=z(a),i=r.memory?.usage||r.memory?.used||0,u=r.memory?.limit||0,A=r.network?.rxBytes||r.network?.rx||0,O=r.network?.txBytes||r.network?.tx||0,_=s.aggregated;p+=`
<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 10px;">
<span style="font-weight: 600; flex: 1;">${e.name||n}</span>
${F?`<span style="font-size: 0.65rem; color: var(--muted); padding: 2px 6px; background: color-mix(in srgb, var(--accent) 10%, transparent); border-radius: 4px;">avg ${F.cpu?.avg?.toFixed(0)||0}% cpu</span>`:""}
<span style="font-size: 0.75rem; color: var(--muted); background: var(--base); padding: 2px 8px; border-radius: 4px;">${e.status||"running"}</span>
<span style="font-weight: 600; flex: 1;">${s.name||e}</span>
${_?`<span style="font-size: 0.65rem; color: var(--muted); padding: 2px 6px; background: color-mix(in srgb, var(--accent) 10%, transparent); border-radius: 4px;">avg ${_.cpu?.avg?.toFixed(0)||0}% cpu</span>`:""}
<span style="font-size: 0.75rem; color: var(--muted); background: var(--base); padding: 2px 8px; border-radius: 4px;">${s.status||"running"}</span>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
<div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">CPU</div>
<div style="display: flex; align-items: center; gap: 8px;">
<div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${Math.min(s,100)}%; background: ${t}; border-radius: 3px; transition: width 0.3s;"></div>
<div style="height: 100%; width: ${Math.min(o,100)}%; background: ${t}; border-radius: 3px; transition: width 0.3s;"></div>
</div>
<span style="font-size: 0.8rem; font-weight: 500; color: ${t}; min-width: 45px; text-align: right;">${s.toFixed(1)}%</span>
<span style="font-size: 0.8rem; font-weight: 500; color: ${t}; min-width: 45px; text-align: right;">${o.toFixed(1)}%</span>
</div>
</div>
<div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Memory</div>
<div style="display: flex; align-items: center; gap: 8px;">
<div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${Math.min(a,100)}%; background: ${o}; border-radius: 3px; transition: width 0.3s;"></div>
<div style="height: 100%; width: ${Math.min(a,100)}%; background: ${n}; border-radius: 3px; transition: width 0.3s;"></div>
</div>
<span style="font-size: 0.8rem; font-weight: 500; color: ${o}; min-width: 45px; text-align: right;">${a.toFixed(1)}%</span>
<span style="font-size: 0.8rem; font-weight: 500; color: ${n}; min-width: 45px; text-align: right;">${a.toFixed(1)}%</span>
</div>
<div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${M(l)} / ${M(h)}</div>
<div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${H(i)} / ${H(u)}</div>
</div>
<div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Network</div>
<div style="font-size: 0.8rem;">
<span style="color: #3498db;">\u2193 ${M($)}</span>
<span style="color: #3498db;">\u2193 ${H(A)}</span>
<span style="color: var(--muted); margin: 0 4px;">/</span>
<span style="color: #e74c3c;">\u2191 ${M(U)}</span>
<span style="color: #e74c3c;">\u2191 ${H(O)}</span>
</div>
</div>
</div>
</div>`}p+="</div>",A.innerHTML=p,f.textContent="Updated: "+new Date().toLocaleTimeString()}catch(d){A.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(d.message)}</div>`}}async function T(){if(!D)return;const d=E;if(!d||Object.keys(d).length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4C8}</span>No monitoring data available. Open the Live Stats tab first.</div>';return}let y='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[p,n]of Object.entries(d)){const e=n.aggregated;e&&(y+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="font-weight: 600; margin-bottom: 10px;">${n.name||p}</div>
</div>`}p+="</div>",P.innerHTML=p,h.textContent="Updated: "+new Date().toLocaleTimeString()}catch(d){P.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(d.message)}</div>`}}async function T(){if(!M)return;const d=E;if(!d||Object.keys(d).length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4C8}</span>No monitoring data available. Open the Live Stats tab first.</div>';return}let f='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[p,e]of Object.entries(d)){const s=e.aggregated;s&&(f+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="font-weight: 600; margin-bottom: 10px;">${e.name||p}</div>
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;">
<div class="stat-mini-card"><span class="stat-val">${e.cpu?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${e.cpu?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${e.memory?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg Mem</span></div>
<div class="stat-mini-card"><span class="stat-val">${e.memory?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max Mem</span></div>
<div class="stat-mini-card"><span class="stat-val">${s.cpu?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${s.cpu?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${s.memory?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg Mem</span></div>
<div class="stat-mini-card"><span class="stat-val">${s.memory?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max Mem</span></div>
</div>
${e.dataPoints?`<div style="font-size: 0.7rem; color: var(--muted); margin-top: 6px;">${e.dataPoints} data points over ${e.timeRange||24}h</div>`:""}
</div>`)}y+="</div>",D.innerHTML=y}async function P(){if(!R)return;R.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const d=E;if(!d||Object.keys(d).length===0){R.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let y=!1;try{y=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{y=!1}let p=[];try{const o=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();o.success&&(p=o.history||[])}catch{}let n={};try{const o=await(await fetch("/api/v1/monitoring/alerts/config")).json();o.success&&(n=o.configs||{})}catch{}const r=Object.entries(d).map(([t,o])=>{const l=n[t]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return`
${s.dataPoints?`<div style="font-size: 0.7rem; color: var(--muted); margin-top: 6px;">${s.dataPoints} data points over ${s.timeRange||24}h</div>`:""}
</div>`)}f+="</div>",M.innerHTML=f}async function D(){if(!R)return;R.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const d=E;if(!d||Object.keys(d).length===0){R.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let f=!1;try{f=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{f=!1}let p=[];try{const n=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();n.success&&(p=n.history||[])}catch{}let e={};try{const n=await(await fetch("/api/v1/monitoring/alerts/config")).json();n.success&&(e=n.configs||{})}catch{}const r=Object.entries(d).map(([t,n])=>{const i=e[t]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return`
<tr data-container="${t}">
<td style="font-weight: 600; padding: 8px;">${o.name||t}</td>
<td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${l.cpuThreshold??80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${y?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${l.memoryThreshold??90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${y?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${l.diskIOThreshold??50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${y?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${l.autoRestart?"checked":""} ${y?"":"disabled"} /></td>
<td style="font-weight: 600; padding: 8px;">${n.name||t}</td>
<td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${i.cpuThreshold??80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${f?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${i.memoryThreshold??90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${f?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${i.diskIOThreshold??50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${f?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${i.autoRestart?"checked":""} ${f?"":"disabled"} /></td>
<td style="padding: 4px 8px;">
<button class="alert-test-btn btn-xs" data-container="${t}" data-name="${o.name||t}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button>
<button class="alert-test-btn btn-xs" data-container="${t}" data-name="${n.name||t}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button>
</td>
</tr>
`}).join(""),s=p.map(t=>{const o=new Date(t.timestamp).toLocaleString(),l=t.notified?"\u2713":"\u2014";return`
`}).join(""),o=p.map(t=>{const n=new Date(t.timestamp).toLocaleString(),i=t.notified?"\u2713":"\u2014";return`
<tr>
<td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${o}</td>
<td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${n}</td>
<td style="padding: 6px 8px; font-weight: 500;">${t.containerName||t.containerId}</td>
<td style="padding: 6px 8px; text-transform: capitalize;">${t.metric||t.type}</td>
<td style="padding: 6px 8px;">${typeof t.value=="number"?t.value.toFixed(1):t.value}${t.metric==="disk"?" MB/s":"%"}</td>
<td style="padding: 6px 8px; text-align: center;">${l}</td>
<td style="padding: 6px 8px; text-align: center;">${i}</td>
<td style="padding: 6px 8px; font-size: 0.75rem; color: ${t.autoRestartTriggered?"#f39c12":"var(--muted)"};">${t.autoRestartTriggered?"\u21BB":""}</td>
</tr>
`}).join(""),a=y?`
`}).join(""),a=f?`
<div style="margin-bottom: 20px;">
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
<h4 style="margin: 0; font-size: 0.9rem;">\u2699\uFE0F Alert Configuration</h4>
@@ -1405,7 +1405,7 @@ This will replace current configuration, credentials, and data. Containers will
${a}
<div>
<h4 style="margin: 0 0 10px; font-size: 0.9rem;">\u{1F4CB} Recent Alerts</h4>
${s?`
${o?`
<div style="overflow-x: auto;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.8rem;">
<thead>
@@ -1418,26 +1418,26 @@ This will replace current configuration, credentials, and data. Containers will
<th style="padding: 6px 8px;"></th>
</tr>
</thead>
<tbody>${s}</tbody>
<tbody>${o}</tbody>
</table>
</div>
`:'<div style="color: var(--muted); text-align: center; padding: 20px;">No alerts recorded yet.</div>'}
</div>
`,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const t={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(o=>{const l=o.dataset.container;t[l]={cpuThreshold:parseInt(o.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(o.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(o.querySelector(".alert-disk")?.value)||50,autoRestart:!!o.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const l=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t})})).json(),h=document.getElementById("save-all-alerts");h.textContent=l.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{h.textContent="Save All"},2e3)}catch{const l=document.getElementById("save-all-alerts");l.textContent="\u274C Error",setTimeout(()=>{l.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",t=>{t.preventDefault(),x.classList.remove("show"),B(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(t=>{t.addEventListener("click",async()=>{const o=t.textContent;t.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${t.dataset.container}/test`,{method:"POST"}),t.textContent="\u2705",showNotification("Test alert sent for "+t.dataset.name,"success",3e3)}catch{t.textContent="\u274C"}setTimeout(()=>{t.textContent=o},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{x.classList.remove("show"),B(),typeof openLicenseModal=="function"&&openLicenseModal()})}function v(){C&&clearInterval(C),N?.checked&&(C=setInterval(S,DC.POLL.STATS))}function B(){C&&(clearInterval(C),C=null)}b?.addEventListener("click",()=>{x.classList.add("show"),S(),v()}),j?.addEventListener("click",()=>{x.classList.remove("show"),B()}),x?.addEventListener("click",d=>{d.target===x&&(x.classList.remove("show"),B())}),g?.addEventListener("click",S),N?.addEventListener("change",()=>{N.checked?v():B()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",T),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",P);const H=document.getElementById("stats-history-container"),O=document.getElementById("stats-history-container-area"),u=document.querySelectorAll(".stats-range-btn");let m="1h";function L(d){switch(d){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function k(d){return d==="raw"?"live (10s samples)":d==="hourly"?"hourly average":d==="daily"?"daily average":d}function I(d,y,p,n,e){if(!d||d.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(n)}</div>`;const r=d.map(y).filter(J=>J!=null);if(r.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(n)}</div>`;const s=Math.max(...r,1),a=Math.min(...r,0),t=s-a||1,o=600,l=80,h=4,$=(o-h*2)/Math.max(r.length-1,1),U=r.map((J,q)=>{const K=h+q*$,Z=l-h-(J-a)/t*(l-h*2);return`${K.toFixed(1)},${Z.toFixed(1)}`}).join(" "),F=r[r.length-1],_=r.reduce((J,q)=>J+q,0)/r.length;return`
`,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const t={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(n=>{const i=n.dataset.container;t[i]={cpuThreshold:parseInt(n.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(n.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(n.querySelector(".alert-disk")?.value)||50,autoRestart:!!n.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const i=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t})})).json(),u=document.getElementById("save-all-alerts");u.textContent=i.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{u.textContent="Save All"},2e3)}catch{const i=document.getElementById("save-all-alerts");i.textContent="\u274C Error",setTimeout(()=>{i.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",t=>{t.preventDefault(),w.classList.remove("show"),B(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.textContent;t.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${t.dataset.container}/test`,{method:"POST"}),t.textContent="\u2705",showNotification("Test alert sent for "+t.dataset.name,"success",3e3)}catch{t.textContent="\u274C"}setTimeout(()=>{t.textContent=n},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{w.classList.remove("show"),B(),typeof openLicenseModal=="function"&&openLicenseModal()})}function y(){C&&clearInterval(C),N?.checked&&(C=setInterval(S,DC.POLL.STATS))}function B(){C&&(clearInterval(C),C=null)}x?.addEventListener("click",()=>{w.classList.add("show"),S(),y()}),j?.addEventListener("click",()=>{w.classList.remove("show"),B()}),w?.addEventListener("click",d=>{d.target===w&&(w.classList.remove("show"),B())}),g?.addEventListener("click",S),N?.addEventListener("change",()=>{N.checked?y():B()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",T),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",D);const $=document.getElementById("stats-history-container"),U=document.getElementById("stats-history-container-area"),m=document.querySelectorAll(".stats-range-btn");let v="1h";function I(d){switch(d){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function b(d){return d==="raw"?"live (10s samples)":d==="hourly"?"hourly average":d==="daily"?"daily average":d}function L(d,f,p,e,s){if(!d||d.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(e)}</div>`;const r=d.map(f).filter(q=>q!=null);if(r.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(e)}</div>`;const o=Math.max(...r,1),a=Math.min(...r,0),t=o-a||1,n=600,i=80,u=4,A=(n-u*2)/Math.max(r.length-1,1),O=r.map((q,J)=>{const G=u+J*A,Z=i-u-(q-a)/t*(i-u*2);return`${G.toFixed(1)},${Z.toFixed(1)}`}).join(" "),_=r[r.length-1],F=r.reduce((q,J)=>q+J,0)/r.length;return`
<div style="margin-bottom: 14px;">
<div style="display: flex; align-items: baseline; gap: 12px; margin-bottom: 4px;">
<span style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(n)}</span>
<span style="font-size: 0.75rem; color: var(--muted);">last ${F.toFixed(1)}${e} \xB7 avg ${_.toFixed(1)}${e} \xB7 max ${s.toFixed(1)}${e}</span>
<span style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(e)}</span>
<span style="font-size: 0.75rem; color: var(--muted);">last ${_.toFixed(1)}${s} \xB7 avg ${F.toFixed(1)}${s} \xB7 max ${o.toFixed(1)}${s}</span>
</div>
<svg viewBox="0 0 ${o} ${l}" preserveAspectRatio="none" style="width: 100%; height: ${l}px; background: var(--base); border-radius: 4px;">
<polyline fill="none" stroke="${p}" stroke-width="1.5" points="${U}" />
<svg viewBox="0 0 ${n} ${i}" preserveAspectRatio="none" style="width: 100%; height: ${i}px; background: var(--base); border-radius: 4px;">
<polyline fill="none" stroke="${p}" stroke-width="1.5" points="${O}" />
</svg>
</div>
`}function i(){if(!H)return;const d=E||{},y=H.value,p=Object.entries(d);if(p.length===0){H.innerHTML='<option value="">No containers</option>';return}H.innerHTML=p.map(([n,e])=>`<option value="${escapeHtml(n)}">${escapeHtml(e.name||n)}</option>`).join(""),y&&d[y]&&(H.value=y)}async function c(){if(!O||!H)return;const d=H.value;if(!d){O.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No container selected.</div>';return}const y=Date.now(),p=y-L(m);O.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading history...</div>';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${p}&endTime=${y}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const r=e.samples||[],s=e.tier||"raw";if(r.length===0){O.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No data for the last ${m}. Tier: ${k(s)}.</div>`;return}const a=s==="raw",t=a?U=>U.cpu?.percent:U=>U.cpu?.avg,o=a?U=>U.memory?.percent:U=>U.memory?.avgPercent,l=a?U=>U.network?.rxMB||0:U=>U.network?.rxMB||0,h=a?U=>U.network?.txMB||0:U=>U.network?.txMB||0;let $=`
`}function l(){if(!$)return;const d=E||{},f=$.value,p=Object.entries(d);if(p.length===0){$.innerHTML='<option value="">No containers</option>';return}$.innerHTML=p.map(([e,s])=>`<option value="${escapeHtml(e)}">${escapeHtml(s.name||e)}</option>`).join(""),f&&d[f]&&($.value=f)}async function c(){if(!U||!$)return;const d=$.value;if(!d){U.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No container selected.</div>';return}const f=Date.now(),p=f-I(v);U.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading history...</div>';try{const s=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${p}&endTime=${f}`)).json();if(!s.success)throw new Error(s.error||"Failed to load history");const r=s.samples||[],o=s.tier||"raw";if(r.length===0){U.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No data for the last ${v}. Tier: ${b(o)}.</div>`;return}const a=o==="raw",t=a?O=>O.cpu?.percent:O=>O.cpu?.avg,n=a?O=>O.memory?.percent:O=>O.memory?.avgPercent,i=a?O=>O.network?.rxMB||0:O=>O.network?.rxMB||0,u=a?O=>O.network?.txMB||0:O=>O.network?.txMB||0;let A=`
<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">
${r.length} samples \xB7 ${escapeHtml(k(s))} \xB7 ${new Date(p).toLocaleString()} \u2192 ${new Date(y).toLocaleString()}
${r.length} samples \xB7 ${escapeHtml(b(o))} \xB7 ${new Date(p).toLocaleString()} \u2192 ${new Date(f).toLocaleString()}
</div>
`;$+=I(r,t,"#2ecc71","CPU","%"),$+=I(r,o,"#3498db","Memory","%"),$+=I(r,l,"#9b59b6","Network RX"," MB"),$+=I(r,h,"#e67e22","Network TX"," MB"),O.innerHTML=$}catch(n){O.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u26A0\uFE0F</span>Failed to load history: ${escapeHtml(n.message)}</div>`}}u.forEach(d=>{d.addEventListener("click",()=>{u.forEach(y=>y.classList.remove("active")),d.classList.add("active"),m=d.dataset.range,c()})}),H?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{i(),c()})})(),(function(){injectModal("health-modal",`<div id="health-modal" class="weather-modal">
`;A+=L(r,t,"#2ecc71","CPU","%"),A+=L(r,n,"#3498db","Memory","%"),A+=L(r,i,"#9b59b6","Network RX"," MB"),A+=L(r,u,"#e67e22","Network TX"," MB"),U.innerHTML=A}catch(e){U.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u26A0\uFE0F</span>Failed to load history: ${escapeHtml(e.message)}</div>`}}m.forEach(d=>{d.addEventListener("click",()=>{m.forEach(f=>f.classList.remove("active")),d.classList.add("active"),v=d.dataset.range,c()})}),$?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{l(),c()})})(),(function(){injectModal("health-modal",`<div id="health-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 800px; max-width: 1000px;">
<h3>\u{1F3E5} Health Check Dashboard</h3>
<p class="modal-subtitle">
@@ -1561,24 +1561,24 @@ This will replace current configuration, credentials, and data. Containers will
<button id="health-cancel">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("health-modal"),b=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),g=document.getElementById("health-refresh-btn"),N=document.getElementById("health-status-container"),A=document.getElementById("health-incidents-container"),D=document.getElementById("health-config-container"),R=document.getElementById("health-last-update"),f=document.getElementById("health-add-btn"),C=document.getElementById("health-config-form"),E=document.getElementById("health-form-title"),M=document.getElementById("health-form-cancel"),w=document.getElementById("health-form-save"),z="dashcaddy-health-settings",S={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},T=document.getElementById("health-global-save"),P=document.getElementById("health-global-reset"),v=document.getElementById("health-global-status"),B=document.getElementById("health-setting-retention"),H=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),u=document.getElementById("health-setting-max-entries"),m=document.getElementById("health-setting-disk-threshold");function L(){try{const a=safeGet(z),t=a?JSON.parse(a):{};return Object.assign({},S,t)}catch{return Object.assign({},S)}}function k(){const a=L();B&&(B.value=a.retentionDays),H&&(H.value=a.pollingInterval),O&&(O.value=a.statsPollingInterval),u&&(u.value=a.maxEntriesPerService),m&&(m.value=a.diskUsageThreshold)}function I(){const a={retentionDays:Math.max(1,Math.min(3650,parseInt(B?.value)||S.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(H?.value)||S.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||S.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(u?.value)||S.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(m?.value)||S.diskUsageThreshold))};try{safeSet(z,JSON.stringify(a)),k(),v&&(v.textContent="Saved \u2713",v.style.color="var(--ok-fg)",setTimeout(()=>{v&&(v.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(t){v&&(v.textContent="Save failed",v.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+t.message,"error")}}function i(){try{safeSet(z,JSON.stringify(S))}catch{}k(),v&&(v.textContent="Reset to defaults \u2713",v.style.color="var(--ok-fg)",setTimeout(()=>{v&&(v.textContent="")},2500))}k(),T?.addEventListener("click",I),P?.addEventListener("click",i);let c=null;function d(a){return a>=99.9?"var(--ok-fg)":a>=95?"#f39c12":"var(--bad-fg)"}function y(a){const t={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`<span style="padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: ${t[a]||"var(--muted)"}20; color: ${t[a]||"var(--muted)"};">${a}</span>`}async function p(){try{const t=await(await fetch("/api/v1/health-checks/status")).json();if(!t.success||!t.status||Object.keys(t.status).length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F3E5}</span>No health checks configured. Go to the Configure tab to add services.</div>';return}const o=Object.values(t.status);let l='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';l+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',l+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',l+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',l+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const h of o){const $=h.status==="up",U=$?"var(--dot-ok)":"var(--dot-bad)",F=h.uptime?.["24h"]??"-",_=h.uptime?.["7d"]??"-",J=h.avgResponseTime!=null?Math.round(h.avgResponseTime)+"ms":"-",q=h.timestamp?timeAgo(h.timestamp):"-";l+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(h.serviceId)}">`,l+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(h.name||h.serviceId)}</td>`,l+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${U}; margin-right: 6px;"></span>${$?"Up":"Down"}</td>`,l+=`<td style="padding: 8px; color: ${typeof F=="number"?d(F):"var(--muted)"};">${typeof F=="number"?F.toFixed(1)+"%":F}</td>`,l+=`<td style="padding: 8px; color: ${typeof _=="number"?d(_):"var(--muted)"};">${typeof _=="number"?_.toFixed(1)+"%":_}</td>`,l+=`<td style="padding: 8px;">${J}</td>`,l+=`<td style="padding: 8px; color: var(--muted);">${q}</td>`,l+="</tr>",l+=`<tr id="health-detail-${escapeHtml(h.serviceId)}" style="display: none;"><td colspan="6" style="padding: 12px; background: var(--bg); border-bottom: 1px solid var(--border);"><div class="panel-empty"><span class="brand-spinner"></span> Loading Line truncated
</div>`);const w=document.getElementById("health-modal"),x=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),g=document.getElementById("health-refresh-btn"),N=document.getElementById("health-status-container"),P=document.getElementById("health-incidents-container"),M=document.getElementById("health-config-container"),R=document.getElementById("health-last-update"),h=document.getElementById("health-add-btn"),C=document.getElementById("health-config-form"),E=document.getElementById("health-form-title"),H=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save"),z="dashcaddy-health-settings",S={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},T=document.getElementById("health-global-save"),D=document.getElementById("health-global-reset"),y=document.getElementById("health-global-status"),B=document.getElementById("health-setting-retention"),$=document.getElementById("health-setting-interval"),U=document.getElementById("health-setting-stats-interval"),m=document.getElementById("health-setting-max-entries"),v=document.getElementById("health-setting-disk-threshold");function I(){try{const a=safeGet(z),t=a?JSON.parse(a):{};return Object.assign({},S,t)}catch{return Object.assign({},S)}}function b(){const a=I();B&&(B.value=a.retentionDays),$&&($.value=a.pollingInterval),U&&(U.value=a.statsPollingInterval),m&&(m.value=a.maxEntriesPerService),v&&(v.value=a.diskUsageThreshold)}function L(){const a={retentionDays:Math.max(1,Math.min(3650,parseInt(B?.value)||S.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt($?.value)||S.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(U?.value)||S.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(m?.value)||S.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(v?.value)||S.diskUsageThreshold))};try{safeSet(z,JSON.stringify(a)),b(),y&&(y.textContent="Saved \u2713",y.style.color="var(--ok-fg)",setTimeout(()=>{y&&(y.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(t){y&&(y.textContent="Save failed",y.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+t.message,"error")}}function l(){try{safeSet(z,JSON.stringify(S))}catch{}b(),y&&(y.textContent="Reset to defaults \u2713",y.style.color="var(--ok-fg)",setTimeout(()=>{y&&(y.textContent="")},2500))}b(),T?.addEventListener("click",L),D?.addEventListener("click",l);let c=null;function d(a){return a>=99.9?"var(--ok-fg)":a>=95?"#f39c12":"var(--bad-fg)"}function f(a){const t={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`<span style="padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: ${t[a]||"var(--muted)"}20; color: ${t[a]||"var(--muted)"};">${a}</span>`}async function p(){try{const t=await(await fetch("/api/v1/health-checks/status")).json();if(!t.success||!t.status||Object.keys(t.status).length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F3E5}</span>No health checks configured. Go to the Configure tab to add services.</div>';return}const n=Object.values(t.status);let i='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';i+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',i+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',i+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',i+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const u of n){const A=u.status==="up",O=A?"var(--dot-ok)":"var(--dot-bad)",_=u.uptime?.["24h"]??"-",F=u.uptime?.["7d"]??"-",q=u.avgResponseTime!=null?Math.round(u.avgResponseTime)+"ms":"-",J=u.timestamp?timeAgo(u.timestamp):"-";i+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(u.serviceId)}">`,i+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(u.name||u.serviceId)}</td>`,i+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${O}; margin-right: 6px;"></span>${A?"Up":"Down"}</td>`,i+=`<td style="padding: 8px; color: ${typeof _=="number"?d(_):"var(--muted)"};">${typeof _=="number"?_.toFixed(1)+"%":_}</td>`,i+=`<td style="padding: 8px; color: ${typeof F=="number"?d(F):"var(--muted)"};">${typeof F=="number"?F.toFixed(1)+"%":F}</td>`,i+=`<td style="padding: 8px;">${q}</td>`,i+=`<td style="padding: 8px; color: var(--muted);">${J}</td>`,i+="</tr>",i+=`<tr id="health-detail-${escapeHtml(u.serviceId)}" style="display: none;"><td colspan="6" style="padding: 12px; background: var(--bg); border-bottom: 1px solid var(--border);"><div class="panel-empty"><span class="brand-spinner"></span> Loading Line truncated
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; font-size: 0.82rem;">
<div><span style="color: var(--muted);">Total Checks</span><br><strong>${J.totalChecks||0}</strong></div>
<div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${d(J.uptime||0)};">${(J.uptime||0).toFixed(2)}%</strong></div>
<div><span style="color: var(--muted);">Avg Response</span><br><strong>${Math.round(q.avg||0)}ms</strong></div>
<div><span style="color: var(--muted);">P95 / P99</span><br><strong>${Math.round(q.p95||0)}ms / ${Math.round(q.p99||0)}ms</strong></div>
<div><span style="color: var(--muted);">Min Response</span><br><strong>${Math.round(q.min||0)}ms</strong></div>
<div><span style="color: var(--muted);">Max Response</span><br><strong>${Math.round(q.max||0)}ms</strong></div>
<div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${J.upChecks||0}</strong></div>
<div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${J.downChecks||0}</strong></div>
</div>`}else U.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(F){U.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(F.message)}</div>`}}})})}catch(a){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(a.message)}</div>`}}async function n(){try{const[a,t]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),o=await a.json(),l=await t.json();let h="";const $=o.success&&o.incidents?o.incidents:[];if($.length>0){h+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+$.length+")</h4>";for(const F of $)h+=`<div style="padding: 10px 12px; margin-bottom: 8px; border: 1px solid var(--bad-fg)30; border-radius: 8px; background: var(--bad-bg);">
<div><span style="color: var(--muted);">Total Checks</span><br><strong>${q.totalChecks||0}</strong></div>
<div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${d(q.uptime||0)};">${(q.uptime||0).toFixed(2)}%</strong></div>
<div><span style="color: var(--muted);">Avg Response</span><br><strong>${Math.round(J.avg||0)}ms</strong></div>
<div><span style="color: var(--muted);">P95 / P99</span><br><strong>${Math.round(J.p95||0)}ms / ${Math.round(J.p99||0)}ms</strong></div>
<div><span style="color: var(--muted);">Min Response</span><br><strong>${Math.round(J.min||0)}ms</strong></div>
<div><span style="color: var(--muted);">Max Response</span><br><strong>${Math.round(J.max||0)}ms</strong></div>
<div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${q.upChecks||0}</strong></div>
<div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${q.downChecks||0}</strong></div>
</div>`}else O.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(_){O.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(_.message)}</div>`}}})})}catch(a){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(a.message)}</div>`}}async function e(){try{const[a,t]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),n=await a.json(),i=await t.json();let u="";const A=n.success&&n.incidents?n.incidents:[];if(A.length>0){u+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+A.length+")</h4>";for(const _ of A)u+=`<div style="padding: 10px 12px; margin-bottom: 8px; border: 1px solid var(--bad-fg)30; border-radius: 8px; background: var(--bad-bg);">
<div style="display: flex; justify-content: space-between; align-items: center;">
<span style="font-weight: 500;">${escapeHtml(F.serviceId)}</span>
<span>${y(F.severity)}</span>
<span style="font-weight: 500;">${escapeHtml(_.serviceId)}</span>
<span>${f(_.severity)}</span>
</div>
<div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(F.message)}</div>
<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(F.createdAt)} \xB7 ${F.occurrences||1} occurrence(s)</div>
</div>`;h+="</div>"}else h+='<div style="padding: 12px; margin-bottom: 16px; border: 1px solid var(--ok-fg)30; border-radius: 8px; background: var(--ok-bg); text-align: center; color: var(--ok-fg); font-size: 0.9rem;">All services operational \u2014 no open incidents</div>';const U=l.success&&l.history?l.history:[];if(U.length>0){h+='<h4 style="margin: 0 0 8px; color: var(--muted);">Incident History</h4>',h+='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',h+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Service</th><th style="padding: 6px; text-align: left;">Type</th><th style="padding: 6px; text-align: left;">Severity</th><th style="padding: 6px; text-align: left;">Status</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">When</th></tr>';for(const F of U){const _=F.status==="resolved",J=_&&F.duration?F.duration<6e4?Math.round(F.duration/1e3)+"s":Math.round(F.duration/6e4)+"m":"-";h+='<tr style="border-bottom: 1px solid var(--border);">',h+=`<td style="padding: 6px;">${escapeHtml(F.serviceId)}</td>`,h+=`<td style="padding: 6px;">${escapeHtml(F.type)}</td>`,h+=`<td style="padding: 6px;">${y(F.severity)}</td>`,h+=`<td style="padding: 6px;"><span style="color: ${_?"var(--ok-fg)":"var(--bad-fg)"};">${F.status}</span></td>`,h+=`<td style="padding: 6px;">${J}</td>`,h+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(F.createdAt)}</td>`,h+="</tr>"}h+="</table>"}A.innerHTML=h||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(a){A.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(a.message)}</div>`}}async function e(){try{const t=await(await fetch("/api/v1/health-checks/status")).json(),o=t.success&&t.status?Object.values(t.status):[];if(o.length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span>No health checks configured yet. Click "Add Health Check" below.</div>';return}let l='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';l+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Service</th><th style="padding: 8px; text-align: left;">Status</th><th style="padding: 8px; text-align: left;">SLA Target</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const h of o){const $=h.status==="up";l+='<tr style="border-bottom: 1px solid var(--border);">',l+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(h.name||h.serviceId)}</td>`,l+=`<td style="padding: 8px; color: ${$?"var(--ok-fg)":"var(--bad-fg)"};">${$?"Up":"Down"}</td>`,l+=`<td style="padding: 8px;">${h.sla?.target?h.sla.target+"%":"-"}</td>`,l+='<td style="padding: 8px; text-align: right;">',l+=`<button onclick="document.dispatchEvent(new CustomEvent('health-edit', {detail:'${escapeHtml(h.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`,l+=`<button onclick="document.dispatchEvent(new CustomEvent('health-delete', {detail:'${escapeHtml(h.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`,l+="</td></tr>"}l+="</table>",D.innerHTML=l}catch(a){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(a.message)}</div>`}}function r(a,t,o,l,h,$,U){c=a||null,E.textContent=a?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=a||"",document.getElementById("health-form-id").disabled=!!a,document.getElementById("health-form-name").value=t||"",document.getElementById("health-form-url").value=o||"",document.getElementById("health-form-timeout").value=l||1e4,document.getElementById("health-form-codes").value=h||"200",document.getElementById("health-form-sla").value=$||99.9,document.getElementById("health-form-slow").value=U||5e3,C.style.display="",f.style.display="none"}function s(){C.style.display="none",f.style.display="",c=null}f?.addEventListener("click",()=>r("","","",1e4,"200",99.9,5e3)),M?.addEventListener("click",s),w?.addEventListener("click",async()=>{const a=c||document.getElementById("health-form-id").value.trim();if(!a)return showNotification("Service ID is required","warning");const t=document.getElementById("health-form-url").value.trim();if(!t)return showNotification("URL is required","warning");const o=document.getElementById("health-form-codes").value.split(",").map(h=>parseInt(h.trim())).filter(Boolean),l={name:document.getElementById("health-form-name").value.trim()||a,url:t,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:o.length?o:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)|Line truncated
<div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(_.message)}</div>
<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(_.createdAt)} \xB7 ${_.occurrences||1} occurrence(s)</div>
</div>`;u+="</div>"}else u+='<div style="padding: 12px; margin-bottom: 16px; border: 1px solid var(--ok-fg)30; border-radius: 8px; background: var(--ok-bg); text-align: center; color: var(--ok-fg); font-size: 0.9rem;">All services operational \u2014 no open incidents</div>';const O=i.success&&i.history?i.history:[];if(O.length>0){u+='<h4 style="margin: 0 0 8px; color: var(--muted);">Incident History</h4>',u+='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',u+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Service</th><th style="padding: 6px; text-align: left;">Type</th><th style="padding: 6px; text-align: left;">Severity</th><th style="padding: 6px; text-align: left;">Status</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">When</th></tr>';for(const _ of O){const F=_.status==="resolved",q=F&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";u+='<tr style="border-bottom: 1px solid var(--border);">',u+=`<td style="padding: 6px;">${escapeHtml(_.serviceId)}</td>`,u+=`<td style="padding: 6px;">${escapeHtml(_.type)}</td>`,u+=`<td style="padding: 6px;">${f(_.severity)}</td>`,u+=`<td style="padding: 6px;"><span style="color: ${F?"var(--ok-fg)":"var(--bad-fg)"};">${_.status}</span></td>`,u+=`<td style="padding: 6px;">${q}</td>`,u+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(_.createdAt)}</td>`,u+="</tr>"}u+="</table>"}P.innerHTML=u||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(a){P.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(a.message)}</div>`}}async function s(){try{const t=await(await fetch("/api/v1/health-checks/status")).json(),n=t.success&&t.status?Object.values(t.status):[];if(n.length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span>No health checks configured yet. Click "Add Health Check" below.</div>';return}let i='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';i+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Service</th><th style="padding: 8px; text-align: left;">Status</th><th style="padding: 8px; text-align: left;">SLA Target</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const u of n){const A=u.status==="up";i+='<tr style="border-bottom: 1px solid var(--border);">',i+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(u.name||u.serviceId)}</td>`,i+=`<td style="padding: 8px; color: ${A?"var(--ok-fg)":"var(--bad-fg)"};">${A?"Up":"Down"}</td>`,i+=`<td style="padding: 8px;">${u.sla?.target?u.sla.target+"%":"-"}</td>`,i+='<td style="padding: 8px; text-align: right;">',i+=`<button data-health-action="health-edit" data-service-id="${escapeHtml(u.serviceId)}" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`,i+=`<button data-health-action="health-delete" data-service-id="${escapeHtml(u.serviceId)}" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`,i+="</td></tr>"}i+="</table>",M.innerHTML=i,M.querySelectorAll("[data-health-action]").forEach(u=>{u.addEventListener("click",()=>{document.dispatchEvent(new CustomEvent(u.dataset.healthAction,{detail:u.dataset.serviceId}))})})}catch(a){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(a.message)}</div>`}}function r(a,t,n,i,u,A,O){c=a||null,E.textContent=a?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=a||"",document.getElementById("health-form-id").disabled=!!a,document.getElementById("health-form-name").value=t||"",document.getElementById("health-form-url").value=n||"",document.getElementById("health-form-timeout").value=i||1e4,document.getElementById("health-form-codes").value=u||"200",document.getElementById("health-form-sla").value=A||99.9,document.getElementById("health-form-slow").value=O||5e3,C.style.display="",h.style.display="none"}function o(){C.style.display="none",h.style.display="",c=null}h?.addEventListener("click",()=>r("","","",1e4,"200",99.9,5e3)),H?.addEventListener("click",o),k?.addEventListener("click",async()=>{const a=c||document.getElementById("health-form-id").value.trim();if(!a)return showNotification("Service ID is required","warning");const t=document.getElementById("health-form-url").value.trim();if(!t)return showNotification("URL is required","warning");const n=document.getElementById("health-form-codes").value.split(",").map(u=>parseInt(u.trim())).filter(Boolean),i={name:document.getElementById("health-form-name").value.trim()||a,url:t,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:n.length?n:[200],sla:{target:parseFloat(documenLine truncated
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u2B06\uFE0F Update Management</h3>
<p class="modal-subtitle">
@@ -1652,17 +1652,17 @@ This will replace current configuration, credentials, and data. Containers will
<button id="updates-cancel">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("updates-modal"),b=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),g=document.getElementById("updates-check-btn"),N=document.getElementById("updates-available-container"),A=document.getElementById("updates-history-container"),D=document.getElementById("updates-auto-container"),R=document.getElementById("updates-last-check");async function f(){try{const n=await(await fetch("/api/v1/updates/available")).json();if(!n.success)throw new Error(n.error);const e=n.updates||[];if(e.length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',R.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let r='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';r+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const t of e){const o=(()=>{const l=window.APPS||[];for(const h of l)if(h.containerId===t.containerId||h.name===t.containerName||h.id===t.containerName)return h.id;return t.containerName})();r+=`<tr data-app-id="${escapeHtml(o)}" style="border-bottom: 1px solid var(--border);">`,r+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(t.containerName)}</td>`,r+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(t.imageName)}</td>`,r+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(t.currentDigest)}</code></td>`,r+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(t.latestDigest)}</code></td>`,r+='<td style="padding: 8px; text-align: right;">',r+=`<button class="update-now-btn" data-id="${escapeHtml(t.containerId)}" data-name="${escapeHtml(t.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,r+=`<button class="rollback-btn" data-id="${escapeHtml(t.containerId)}" data-name="${escapeHtml(t.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,r+="</td></tr>"}r+="</table>",N.innerHTML=r,R.textContent=e.length+" update(s) available";const s=document.getElementById("updates-count-badge"),a=document.getElementById("updates-update-all-btn");s&&(s.textContent=e.length+" pending",s.style.display=""),a&&e.length>0&&(a.style.display=""),window._pendingUpdates=e,N.querySelectorAll(".update-now-btn").forEach(t=>{t.addEventListener("click",async()=>{const o=t.dataset.id,l=t.dataset.name;if(confirm(`Update "${l}" to the latest version? The container will restart.`)){t.textContent="Updating...",t.disabled=!0;try{const $=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if($.success)t.textContent="Done!",t.style.background="var(--ok-fg)",setTimeout(()=>f(),2e3);else throw new Error($.error||"Update failed")}catch(h){t.textContent="Failed",t.style.color="var(--bad-fg)",showNotification("Update error: "+h.message,"error"),setTimeout(()=>{t.textContent="Update",t.disabled=!1,t.style.color="",t.style.background=""},3e3)}}})}),N.querySelectorAll(".rollback-btn").forEach(t=>{t.addEventListener("click",async()=>{const o=t.dataset.id,l=t.dataset.name;if(confirm(`Rollback "${l}" to its previous version?`)){t.textContent="Rolling back...",t.disabled=!0;try{const $=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(o)}`,{method:"POST"})).json();if($.success)t.textContent="Rolled back!",setTimeout(()=>f(),2e3);else throw new Error($.error||"Rollback failed")}catch(h){t.textContent="Failed",showNotification("Rollback error: "+h.message,"error"),setTimeout(()=>{t.textContent="Rollback",t.disabled=!1},3e3)}}})})}catch(p){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}async function C(){const p=window._pendingUpdates||[];if(!p.length)return;const n=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${p.length} containers? Each will restart.`))return;n.textContent="\u23F3 Updating...",n.disabled=!0;let e=0,r=0;for(const s of p)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:r++}catch{r++}n.textCLine truncated
<select class="auto-schedule" data-id="${escapeHtml(h)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<option value=""${U?"":" selected"}>Disabled</option>
<option value="daily"${U==="daily"?" selected":""}>Daily</option>
<option value="weekly"${U==="weekly"?" selected":""}>Weekly</option>
<option value="monthly"${U==="monthly"?" selected":""}>Monthly</option>
</select></td>`,t+=`<td style="padding: 8px;"><input type="text" class="auto-window" data-id="${escapeHtml(h)}" value="${escapeHtml(_)}" placeholder="02:00-04:00" style="width: 90px; padding: 3px 6px; font-size: 0.78rem; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg);" /></td>`,t+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(h)}"${F?" checked":""} /></td>`,t+=`<td style="padding: 8px; font-size: 0.78rem; color: var(--muted);">${J}</td>`,t+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(h)}" data-name="${escapeHtml(l)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,t+="</tr>"}t+="</table>",D.innerHTML=t,D.querySelectorAll(".save-auto-btn").forEach(o=>{o.addEventListener("click",async()=>{const l=o.dataset.id,h=o.closest("tr"),$=h.querySelector(".auto-schedule").value,U=h.querySelector(".auto-rollback").checked,F=h.querySelector(".auto-window").value.trim();o.textContent="Saving...",o.disabled=!0;try{const J=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!$,schedule:$||"weekly",autoRollback:U,maintenanceWindow:F||void 0})})).json();if(J.success)o.textContent="\u2713 Saved";else throw new Error(J.error)}catch(_){o.textContent="\u2717 Error",showNotification("Save error: "+_.message,"error")}setTimeout(()=>{o.textContent="Save",o.disabled=!1},2e3)})})}catch(p){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}const z=document.getElementById("dashcaddy-current-version"),S=document.getElementById("dashcaddy-update-badge"),T=document.getElementById("dashcaddy-update-details"),P=document.getElementById("dashcaddy-new-version"),v=document.getElementById("dashcaddy-changelog"),B=document.getElementById("dashcaddy-apply-btn"),H=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),u=document.getElementById("dashcaddy-status-bar"),m=document.getElementById("dashcaddy-history-container");let L=null;function k(p,n){u&&(u.style.display="block",u.style.background=n==="error"?"var(--bad-bg)":n==="success"?"var(--ok-bg)":"var(--bg)",u.style.color=n==="error"?"var(--bad-fg)":n==="success"?"var(--ok-fg)":"var(--fg)",u.textContent=p)}async function I(){try{const n=await(await fetch("/api/v1/system/version")).json();if(n.success){const e=n.commit&&n.commit!=="unknown"?n.commit:null;z.textContent="v"+n.version+(e?" ("+e.substring(0,7)+")":"")}}catch{z.textContent="Unable to fetch version"}}async function i(p){p||(H.textContent="Checking...",H.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(L=e,e.success&&e.available&&e.remote){S.style.display="",T.style.display="",P.textContent="v"+e.remote.version,v.textContent=e.remote.changelog||"No changelog available.";const r=document.getElementById("updates-btn");if(r&&!r.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",r.style.position="relative",r.appendChild(a)}const s=document.getElementById("updates-dashcaddy-tab");if(s&&!s.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",s.appendChild(a)}}else S.style.display="none",T.style.display="none",await I(),p||k("You are running the latest version.","success");p||(H.textContent="Check for Updates",H.disabled=!1)}catch(n){p||(k("Failed to check: "+n.message,"error"),H.textContent="Check for Updates",H.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;B.textContent="Updating...",B.disabled=!0,k("Downloading and applying update...","info");try{const n=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(n.success)return k("Update initiated: v"+(n.fromVersion||"?")+" \u2192 v"+(n.toVersion||"?")+". The container will restart shortly.","success"),B.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(n.error||"Update failed")}catch(p){throw k("Update failed: "+p.message,"error"),B.textContent="Update Now",B.disabled=!1,p}}async function d(){try{const n=await(await fetch("/api/v1/system/update-history")).json(),e=n.success&&n.history?n.history:[];if(e.length===0){m.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let r='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';r+='<tr style="border-bottom: 1px solid var(--border); color: var(--mutLine truncated
`+e.join(`
</div>`);const w=document.getElementById("updates-modal"),x=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),g=document.getElementById("updates-check-btn"),N=document.getElementById("updates-available-container"),P=document.getElementById("updates-history-container"),M=document.getElementById("updates-auto-container"),R=document.getElementById("updates-last-check");async function h(){try{const e=await(await fetch("/api/v1/updates/available")).json();if(!e.success)throw new Error(e.error);const s=e.updates||[];if(s.length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',R.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let r='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';r+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const t of s){const n=(()=>{const i=window.APPS||[];for(const u of i)if(u.containerId===t.containerId||u.name===t.containerName||u.id===t.containerName)return u.id;return t.containerName})();r+=`<tr data-app-id="${escapeHtml(n)}" style="border-bottom: 1px solid var(--border);">`,r+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(t.containerName)}</td>`,r+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(t.imageName)}</td>`,r+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(t.currentDigest)}</code></td>`,r+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(t.latestDigest)}</code></td>`,r+='<td style="padding: 8px; text-align: right;">',r+=`<button class="update-now-btn" data-id="${escapeHtml(t.containerId)}" data-name="${escapeHtml(t.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,r+=`<button class="rollback-btn" data-id="${escapeHtml(t.containerId)}" data-name="${escapeHtml(t.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,r+="</td></tr>"}r+="</table>",N.innerHTML=r,R.textContent=s.length+" update(s) available";const o=document.getElementById("updates-count-badge"),a=document.getElementById("updates-update-all-btn");o&&(o.textContent=s.length+" pending",o.style.display=""),a&&s.length>0&&(a.style.display=""),window._pendingUpdates=s,N.querySelectorAll(".update-now-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,i=t.dataset.name;if(confirm(`Update "${i}" to the latest version? The container will restart.`)){t.textContent="Updating...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(A.success)t.textContent="Done!",t.style.background="var(--ok-fg)",setTimeout(()=>h(),2e3);else throw new Error(A.error||"Update failed")}catch(u){t.textContent="Failed",t.style.color="var(--bad-fg)",showNotification("Update error: "+u.message,"error"),setTimeout(()=>{t.textContent="Update",t.disabled=!1,t.style.color="",t.style.background=""},3e3)}}})}),N.querySelectorAll(".rollback-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,i=t.dataset.name;if(confirm(`Rollback "${i}" to its previous version?`)){t.textContent="Rolling back...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(n)}`,{method:"POST"})).json();if(A.success)t.textContent="Rolled back!",setTimeout(()=>h(),2e3);else throw new Error(A.error||"Rollback failed")}catch(u){t.textContent="Failed",showNotification("Rollback error: "+u.message,"error"),setTimeout(()=>{t.textContent="Rollback",t.disabled=!1},3e3)}}})})}catch(p){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}async function C(){const p=window._pendingUpdates||[];if(!p.length)return;const e=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${p.length} containers? Each will restart.`))return;e.textContent="\u23F3 Updating...",e.disabled=!0;let s=0,r=0;for(const o of p)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?s++:r++}catch{r++}e.textCLine truncated
<select class="auto-schedule" data-id="${escapeHtml(u)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<option value=""${O?"":" selected"}>Disabled</option>
<option value="daily"${O==="daily"?" selected":""}>Daily</option>
<option value="weekly"${O==="weekly"?" selected":""}>Weekly</option>
<option value="monthly"${O==="monthly"?" selected":""}>Monthly</option>
</select></td>`,t+=`<td style="padding: 8px;"><input type="text" class="auto-window" data-id="${escapeHtml(u)}" value="${escapeHtml(F)}" placeholder="02:00-04:00" style="width: 90px; padding: 3px 6px; font-size: 0.78rem; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg);" /></td>`,t+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(u)}"${_?" checked":""} /></td>`,t+=`<td style="padding: 8px; font-size: 0.78rem; color: var(--muted);">${q}</td>`,t+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(u)}" data-name="${escapeHtml(i)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,t+="</tr>"}t+="</table>",M.innerHTML=t,M.querySelectorAll(".save-auto-btn").forEach(n=>{n.addEventListener("click",async()=>{const i=n.dataset.id,u=n.closest("tr"),A=u.querySelector(".auto-schedule").value,O=u.querySelector(".auto-rollback").checked,_=u.querySelector(".auto-window").value.trim();n.textContent="Saving...",n.disabled=!0;try{const q=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(i)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!A,schedule:A||"weekly",autoRollback:O,maintenanceWindow:_||void 0})})).json();if(q.success)n.textContent="\u2713 Saved";else throw new Error(q.error)}catch(F){n.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{n.textContent="Save",n.disabled=!1},2e3)})})}catch(p){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}const z=document.getElementById("dashcaddy-current-version"),S=document.getElementById("dashcaddy-update-badge"),T=document.getElementById("dashcaddy-update-details"),D=document.getElementById("dashcaddy-new-version"),y=document.getElementById("dashcaddy-changelog"),B=document.getElementById("dashcaddy-apply-btn"),$=document.getElementById("dashcaddy-check-btn"),U=document.getElementById("dashcaddy-rollback-btn"),m=document.getElementById("dashcaddy-status-bar"),v=document.getElementById("dashcaddy-history-container");let I=null;function b(p,e){m&&(m.style.display="block",m.style.background=e==="error"?"var(--bad-bg)":e==="success"?"var(--ok-bg)":"var(--bg)",m.style.color=e==="error"?"var(--bad-fg)":e==="success"?"var(--ok-fg)":"var(--fg)",m.textContent=p)}async function L(){try{const e=await(await fetch("/api/v1/system/version")).json();if(e.success){const s=e.commit&&e.commit!=="unknown"?e.commit:null;z.textContent="v"+e.version+(s?" ("+s.substring(0,7)+")":"")}}catch{z.textContent="Unable to fetch version"}}async function l(p){p||($.textContent="Checking...",$.disabled=!0);try{const s=await(await fetch("/api/v1/system/update-check")).json();if(I=s,s.success&&s.available&&s.remote){S.style.display="",T.style.display="",D.textContent="v"+s.remote.version,y.textContent=s.remote.changelog||"No changelog available.";const r=document.getElementById("updates-btn");if(r&&!r.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",r.style.position="relative",r.appendChild(a)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(a)}}else S.style.display="none",T.style.display="none",await L(),p||b("You are running the latest version.","success");p||($.textContent="Check for Updates",$.disabled=!1)}catch(e){p||(b("Failed to check: "+e.message,"error"),$.textContent="Check for Updates",$.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;B.textContent="Updating...",B.disabled=!0,b("Downloading and applying update...","info");try{const e=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(e.success)return b("Update initiated: v"+(e.fromVersion||"?")+" \u2192 v"+(e.toVersion||"?")+". The container will restart shortly.","success"),B.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(s=>s.remove()),!0;throw new Error(e.error||"Update failed")}catch(p){throw b("Update failed: "+p.message,"error"),B.textContent="Update Now",B.disabled=!1,p}}async function d(){try{const e=await(await fetch("/api/v1/system/update-history")).json(),s=e.success&&e.history?e.history:[];if(s.length===0){v.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let r='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';r+='<tr style="border-bottom: 1px solid var(--border); color: var(--mutLine truncated
`+s.join(`
`)+`
Enter version to rollback to:`);if(!r)return;if(!e.includes(r)){showNotification("Invalid version: "+r,"error");return}if(!confirm("Rollback DashCaddy to v"+r+"? The container will restart."))return;k("Rolling back to v"+r+"...","info");const a=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:r})})).json();if(a.success)k("Rollback to v"+r+" initiated. Container will restart.","success");else throw new Error(a.error||"Rollback failed")}catch(p){k("Rollback failed: "+p.message,"error")}}H?.addEventListener("click",()=>i(!1)),B?.addEventListener("click",()=>c().catch(()=>{})),O?.addEventListener("click",y),g?.addEventListener("click",E),b?.addEventListener("click",()=>{x?.classList.add("show"),f()}),wireModal(x,j),window.openUpdateModal=function(p){x?.classList.add("show"),f().then(()=>{if(!p)return;const n=N.querySelector(`[data-app-id="${p}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{n.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",M),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",w),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{I(),d(),L||i(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=i,setTimeout(()=>i(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`<div id="docker-resources-modal" class="weather-modal">
Enter version to rollback to:`);if(!r)return;if(!s.includes(r)){showNotification("Invalid version: "+r,"error");return}if(!confirm("Rollback DashCaddy to v"+r+"? The container will restart."))return;b("Rolling back to v"+r+"...","info");const a=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:r})})).json();if(a.success)b("Rollback to v"+r+" initiated. Container will restart.","success");else throw new Error(a.error||"Rollback failed")}catch(p){b("Rollback failed: "+p.message,"error")}}$?.addEventListener("click",()=>l(!1)),B?.addEventListener("click",()=>c().catch(()=>{})),U?.addEventListener("click",f),g?.addEventListener("click",E),x?.addEventListener("click",()=>{w?.classList.add("show"),h()}),wireModal(w,j),window.openUpdateModal=function(p){w?.classList.add("show"),h().then(()=>{if(!p)return;const e=N.querySelector(`[data-app-id="${p}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{e.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",H),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{L(),d(),I||l(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=l,setTimeout(()=>l(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`<div id="docker-resources-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u{1F433} Docker Resources</h3>
<p class="modal-subtitle">Manage volumes, networks, and view disk usage.</p>
@@ -1711,7 +1711,7 @@ Enter version to rollback to:`);if(!r)return;if(!e.includes(r)){showNotification
<button id="dr-close">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("docker-resources-modal"),b=document.getElementById("docker-resources-btn"),j=document.getElementById("dr-close");function g(R){if(!R||R===0)return"0 B";const f=["B","KB","MB","GB","TB"],C=Math.floor(Math.log(Math.abs(R))/Math.log(1024));return(R/Math.pow(1024,C)).toFixed(1)+" "+f[C]}async function N(){const R=document.getElementById("dr-vol-list");try{const C=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(C.length===0){R.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No volumes found.</div>';return}let E='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';E+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const M of C){const w=M.name==="buildkit"||M.name.length===64;E+='<tr style="border-bottom: 1px solid var(--border);">',E+=`<td style="padding: 6px; font-weight: 500; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml(M.name)}">${escapeHtml(M.name.length>40?M.name.substring(0,37)+"...":M.name)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.driver)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.scope)}</td>`,E+='<td style="padding: 6px; text-align: right;">',w||(E+=`<button class="dr-vol-del" data-name="${escapeHtml(M.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),E+="</td></tr>"}E+="</table>",R.innerHTML=E,R.querySelectorAll(".dr-vol-del").forEach(M=>{M.addEventListener("click",async()=>{if(confirm(`Delete volume "${M.dataset.name}"? Data will be lost.`)){M.textContent="...",M.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(M.dataset.name)}?force=true`),N()}catch(w){showNotification("Delete failed: "+w.message,"error"),M.textContent="Delete",M.disabled=!1}}})})}catch(f){R.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(f.message)}</div>`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-vol-name"),f=R.value.trim();if(!f){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:f}),R.value="",showNotification(`Volume "${f}" created`,"success"),N()}catch(C){showNotification("Create failed: "+C.message,"error")}});async function A(){const R=document.getElementById("dr-net-list");try{const C=(await getJSON("/api/v1/docker/networks")).networks||[];if(C.length===0){R.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F310}</span>No networks found.</div>';return}let E='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';E+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px;">Containers</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const M of C){const w=["bridge","host","none"].includes(M.name);E+='<tr style="border-bottom: 1px solid var(--border);">',E+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(M.name)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.driver)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.scope)}</td>`,E+=`<td style="padding: 6px; text-align: center;">${M.containers}</td>`,E+='<td style="padding: 6px; text-align: right;">',w||(E+=`<button class="dr-net-del" data-id="${escapeHtml(M.id)}" data-name="${escapeHtml(M.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),E+="</td></tr>"}E+="</table>",R.innerHTML=E,R.querySelectorAll(".dr-net-del").forEach(M=>{M.addEventListener("click",async()=>{if(confirm(`Delete network "${M.dataset.name}"?`)){M.textContent="...",M.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent(M.dataset.id)}`),A()}catch(w){showNotification("Delete failed: "+w.message,"error"),M.textContent="Delete",M.disabled=!1}}})})}catch(f){R.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(f.message)}</div>`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-net-name"),f=document.getElementById("dr-net-driver"),C=R.value.trim();if(!C){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:C,driver:f.value}),R.value="",showNotification(`Network "${C}" created`,"success"),A()}catch(E){showNotification("Create failed: "+E.message,"error")}});async fuLine truncated
</div>`);const w=document.getElementById("docker-resources-modal"),x=document.getElementById("docker-resources-btn"),j=document.getElementById("dr-close");function g(R){if(!R||R===0)return"0 B";const h=["B","KB","MB","GB","TB"],C=Math.floor(Math.log(Math.abs(R))/Math.log(1024));return(R/Math.pow(1024,C)).toFixed(1)+" "+h[C]}async function N(){const R=document.getElementById("dr-vol-list");try{const C=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(C.length===0){R.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No volumes found.</div>';return}let E='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';E+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const H of C){const k=H.name==="buildkit"||H.name.length===64;E+='<tr style="border-bottom: 1px solid var(--border);">',E+=`<td style="padding: 6px; font-weight: 500; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml(H.name)}">${escapeHtml(H.name.length>40?H.name.substring(0,37)+"...":H.name)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(H.driver)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(H.scope)}</td>`,E+='<td style="padding: 6px; text-align: right;">',k||(E+=`<button class="dr-vol-del" data-name="${escapeHtml(H.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),E+="</td></tr>"}E+="</table>",R.innerHTML=E,R.querySelectorAll(".dr-vol-del").forEach(H=>{H.addEventListener("click",async()=>{if(confirm(`Delete volume "${H.dataset.name}"? Data will be lost.`)){H.textContent="...",H.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(H.dataset.name)}?force=true`),N()}catch(k){showNotification("Delete failed: "+k.message,"error"),H.textContent="Delete",H.disabled=!1}}})})}catch(h){R.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(h.message)}</div>`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-vol-name"),h=R.value.trim();if(!h){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:h}),R.value="",showNotification(`Volume "${h}" created`,"success"),N()}catch(C){showNotification("Create failed: "+C.message,"error")}});async function P(){const R=document.getElementById("dr-net-list");try{const C=(await getJSON("/api/v1/docker/networks")).networks||[];if(C.length===0){R.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F310}</span>No networks found.</div>';return}let E='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';E+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px;">Containers</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const H of C){const k=["bridge","host","none"].includes(H.name);E+='<tr style="border-bottom: 1px solid var(--border);">',E+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(H.name)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(H.driver)}</td>`,E+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(H.scope)}</td>`,E+=`<td style="padding: 6px; text-align: center;">${H.containers}</td>`,E+='<td style="padding: 6px; text-align: right;">',k||(E+=`<button class="dr-net-del" data-id="${escapeHtml(H.id)}" data-name="${escapeHtml(H.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),E+="</td></tr>"}E+="</table>",R.innerHTML=E,R.querySelectorAll(".dr-net-del").forEach(H=>{H.addEventListener("click",async()=>{if(confirm(`Delete network "${H.dataset.name}"?`)){H.textContent="...",H.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent(H.dataset.id)}`),P()}catch(k){showNotification("Delete failed: "+k.message,"error"),H.textContent="Delete",H.disabled=!1}}})})}catch(h){R.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(h.message)}</div>`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-net-name"),h=document.getElementById("dr-net-driver"),C=R.value.trim();if(!C){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:C,driver:h.value}),R.value="",showNotification(`Network "${C}" created`,"success"),P()}catch(E){showNotification("Create failed: "+E.message,"error")}});async fuLine truncated
<div class="weather-modal-content" style="min-width: 650px; max-width: 800px;">
<h3>\u{1F4E6} Import Docker Compose</h3>
<p class="modal-subtitle">Paste a docker-compose.yml to import and deploy services.</p>
@@ -1752,8 +1752,8 @@ Enter version to rollback to:`);if(!r)return;if(!e.includes(r)){showNotification
<div id="compose-progress-content"></div>
</div>
</div>
</div>`);const x=document.getElementById("compose-import-modal"),b=document.getElementById("compose-import-btn"),j=document.getElementById("compose-cancel");wireModal(x,j);let g=null;function N(D){document.getElementById("compose-step-paste").style.display=D==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=D==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=D==="progress"?"":"none"}b?.addEventListener("click",()=>{N("paste"),g=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",x?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",D=>{const R=D.target.files[0];if(!R)return;const f=new FileReader;f.onload=()=>{document.getElementById("compose-yaml").value=f.result},f.readAsText(R)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const D=document.getElementById("compose-yaml").value.trim(),R=document.getElementById("compose-stack-name").value.trim()||"stack";if(!D){showNotification("Paste a docker-compose.yml","warning");return}const f=document.getElementById("compose-parse-btn"),C=f.textContent;f.textContent="Parsing...",f.disabled=!0;try{const E=await postJSON("/api/v1/apps/import-compose",{yaml:D,stackName:R});g=E,g.stackName=R,A(E),N("preview")}catch(E){showNotification("Parse failed: "+E.message,"error")}finally{f.textContent=C,f.disabled=!1}});function A(D){const R=document.getElementById("compose-preview-content");let f="";D.networks&&D.networks.length>0&&(f+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Networks: ${D.networks.map(C=>`<code>${escapeHtml(C)}</code>`).join(", ")}</div>`),D.volumes&&D.volumes.length>0&&(f+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Volumes: ${D.volumes.map(C=>`<code>${escapeHtml(C)}</code>`).join(", ")}</div>`),f+=`<div style="font-weight: 600; margin-bottom: 8px;">${D.services.length} service(s)</div>`,f+='<div class="scroll-container" style="max-height: 350px;">';for(const C of D.services){const E=C.skip?"var(--bad-fg)":"var(--border)";if(f+=`<div style="padding: 10px 14px; border: 1px solid ${E}; border-radius: 8px; margin-bottom: 8px; background: var(--bg);">`,f+=`<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(C.name)}`,C.skip&&(f+=` <span style="color: var(--bad-fg); font-weight: 400; font-size: 0.78rem;">\u2014 skipped: ${escapeHtml(C.reason)}</span>`),f+="</div>",!C.skip&&(f+=`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Image: <code>${escapeHtml(C.image)}</code></div>`,C.ports?.length&&(f+=`<div style="font-size: 0.8rem; color: var(--muted);">Ports: ${C.ports.map(M=>`${M.host}:${M.container}`).join(", ")}</div>`),C.volumes?.length&&(f+=`<div style="font-size: 0.8rem; color: var(--muted);">Volumes: ${C.volumes.length}</div>`),Object.keys(C.environment||{}).length&&(f+=`<div style="font-size: 0.8rem; color: var(--muted);">Env vars: ${Object.keys(C.environment).length}</div>`),C.envFileWarning&&(f+=`<div style="font-size: 0.78rem; color: var(--bad-fg);">\u26A0 ${escapeHtml(C.envFileWarning)}</div>`),C.resources?.cpus||C.resources?.memory)){const M=[];C.resources.cpus&&M.push(`CPU: ${C.resources.cpus}`),C.resources.memory&&M.push(`Mem: ${C.resources.memory}MB`),f+=`<div style="font-size: 0.8rem; color: var(--muted);">Limits: ${M.join(", ")}</div>`}f+="</div>"}f+="</div>",R.innerHTML=f}document.getElementById("compose-back-btn")?.addEventListener("click",()=>N("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!g)return;const D=document.getElementById("compose-deploy-btn");D.textContent="Deploying...",D.disabled=!0,N("progress");const R=document.getElementById("compose-progress-content");R.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Deploying services...</div>';try{const f=await postJSON("/api/v1/apps/deploy-compose",{services:g.services,networks:g.networks,stackName:g.stackName});let C=`<div style="font-weight: 600; margin-bottom: 12px;">Stack "${escapeHtml(f.stackName)}" \u2014 Deployment Complete</div>`;C+='<div class="scroll-container" style="max-height: 350px;">';for(const E of f.results){const M=E.status==="deployed"||E.status==="created"?"\u2705":E.status==="exists"?"\u26A1":E.status==="skipped"?"\u23ED":"\u274C";C+='<div style="padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 0.85rem;">',C+=`${M} <strong>${escapeHtml(E.name)}</strong> (${E.type}) \u2014 ${escapeHtml(E.status)}`,E.error&&(C+=` <span style="color: var(--bad-fg);">${escapeHtml(E.error)}</span>`),E.subdomain&&(C+=` \u2192 <code>${escapeHtml(E.subdomain)}</code>`),E.reason&&(C+=` <span style="color: var(--muted);">(${escapeHtml(E.reason)})</span>`),C+="</div>"}C+="</div>",C+='<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-done-btn">Done</button></div>Line truncated
<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-retry-btn">Back</button></div>`,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>N("paste"))}finally{D.textContent="Deploy All",D.disabled=!1}})})(),(function(){injectModal("exec-modal",`<div id="exec-modal" class="weather-modal">
</div>`);const w=document.getElementById("compose-import-modal"),x=document.getElementById("compose-import-btn"),j=document.getElementById("compose-cancel");wireModal(w,j);let g=null;function N(M){document.getElementById("compose-step-paste").style.display=M==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=M==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=M==="progress"?"":"none"}x?.addEventListener("click",()=>{N("paste"),g=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",w?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",M=>{const R=M.target.files[0];if(!R)return;const h=new FileReader;h.onload=()=>{document.getElementById("compose-yaml").value=h.result},h.readAsText(R)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const M=document.getElementById("compose-yaml").value.trim(),R=document.getElementById("compose-stack-name").value.trim()||"stack";if(!M){showNotification("Paste a docker-compose.yml","warning");return}const h=document.getElementById("compose-parse-btn"),C=h.textContent;h.textContent="Parsing...",h.disabled=!0;try{const E=await postJSON("/api/v1/apps/import-compose",{yaml:M,stackName:R});g=E,g.stackName=R,P(E),N("preview")}catch(E){showNotification("Parse failed: "+E.message,"error")}finally{h.textContent=C,h.disabled=!1}});function P(M){const R=document.getElementById("compose-preview-content");let h="";M.networks&&M.networks.length>0&&(h+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Networks: ${M.networks.map(C=>`<code>${escapeHtml(C)}</code>`).join(", ")}</div>`),M.volumes&&M.volumes.length>0&&(h+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Volumes: ${M.volumes.map(C=>`<code>${escapeHtml(C)}</code>`).join(", ")}</div>`),h+=`<div style="font-weight: 600; margin-bottom: 8px;">${M.services.length} service(s)</div>`,h+='<div class="scroll-container" style="max-height: 350px;">';for(const C of M.services){const E=C.skip?"var(--bad-fg)":"var(--border)";if(h+=`<div style="padding: 10px 14px; border: 1px solid ${E}; border-radius: 8px; margin-bottom: 8px; background: var(--bg);">`,h+=`<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(C.name)}`,C.skip&&(h+=` <span style="color: var(--bad-fg); font-weight: 400; font-size: 0.78rem;">\u2014 skipped: ${escapeHtml(C.reason)}</span>`),h+="</div>",!C.skip&&(h+=`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Image: <code>${escapeHtml(C.image)}</code></div>`,C.ports?.length&&(h+=`<div style="font-size: 0.8rem; color: var(--muted);">Ports: ${C.ports.map(H=>`${H.host}:${H.container}`).join(", ")}</div>`),C.volumes?.length&&(h+=`<div style="font-size: 0.8rem; color: var(--muted);">Volumes: ${C.volumes.length}</div>`),Object.keys(C.environment||{}).length&&(h+=`<div style="font-size: 0.8rem; color: var(--muted);">Env vars: ${Object.keys(C.environment).length}</div>`),C.envFileWarning&&(h+=`<div style="font-size: 0.78rem; color: var(--bad-fg);">\u26A0 ${escapeHtml(C.envFileWarning)}</div>`),C.resources?.cpus||C.resources?.memory)){const H=[];C.resources.cpus&&H.push(`CPU: ${C.resources.cpus}`),C.resources.memory&&H.push(`Mem: ${C.resources.memory}MB`),h+=`<div style="font-size: 0.8rem; color: var(--muted);">Limits: ${H.join(", ")}</div>`}h+="</div>"}h+="</div>",R.innerHTML=h}document.getElementById("compose-back-btn")?.addEventListener("click",()=>N("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!g)return;const M=document.getElementById("compose-deploy-btn");M.textContent="Deploying...",M.disabled=!0,N("progress");const R=document.getElementById("compose-progress-content");R.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Deploying services...</div>';try{const h=await postJSON("/api/v1/apps/deploy-compose",{services:g.services,networks:g.networks,stackName:g.stackName});let C=`<div style="font-weight: 600; margin-bottom: 12px;">Stack "${escapeHtml(h.stackName)}" \u2014 Deployment Complete</div>`;C+='<div class="scroll-container" style="max-height: 350px;">';for(const E of h.results){const H=E.status==="deployed"||E.status==="created"?"\u2705":E.status==="exists"?"\u26A1":E.status==="skipped"?"\u23ED":"\u274C";C+='<div style="padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 0.85rem;">',C+=`${H} <strong>${escapeHtml(E.name)}</strong> (${E.type}) \u2014 ${escapeHtml(E.status)}`,E.error&&(C+=` <span style="color: var(--bad-fg);">${escapeHtml(E.error)}</span>`),E.subdomain&&(C+=` \u2192 <code>${escapeHtml(E.subdomain)}</code>`),E.reason&&(C+=` <span style="color: var(--muted);">(${escapeHtml(E.reason)})</span>`),C+="</div>"}C+="</div>",C+='<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-done-btn">Done</button></div>Line truncated
<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-retry-btn">Back</button></div>`,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>N("paste"))}finally{M.textContent="Deploy All",M.disabled=!1}})})(),(function(){injectModal("exec-modal",`<div id="exec-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 700px; max-width: 900px; padding-bottom: 0;">
<h3 id="exec-title">Terminal</h3>
<div id="exec-terminal" style="height: 420px; border-radius: 6px; overflow: hidden; background: #1e1e1e;"></div>
@@ -1761,11 +1761,11 @@ Enter version to rollback to:`);if(!r)return;if(!e.includes(r)){showNotification
<button id="exec-close">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("exec-modal"),b=document.getElementById("exec-terminal"),j=document.getElementById("exec-close");let g=null,N=null,A=null;function D(){if(N){try{N.close()}catch{}N=null}if(g){try{g.dispose()}catch{}g=null}A=null,b.innerHTML=""}function R(f,C){if(D(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${C||f}`,x?.classList.add("show"),typeof Terminal>"u"){b.innerHTML='<div style="color: #f44; padding: 20px; font-family: monospace;">xterm.js not loaded</div>';return}g=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(A=new FitAddon.FitAddon,g.loadAddon(A)),g.open(b),A&&setTimeout(()=>A.fit(),50);const E=location.protocol==="https:"?"wss:":"ws:";N=new WebSocket(`${E}//${location.host}/ws/exec/${encodeURIComponent(f)}`),N.binaryType="arraybuffer",N.onopen=()=>{if(g.writeln("\x1B[32mConnecting...\x1B[0m"),A){const w=A.proposeDimensions();w&&N.send(JSON.stringify({type:"resize",cols:w.cols,rows:w.rows}))}},N.onmessage=w=>{if(typeof w.data=="string"){try{const z=JSON.parse(w.data);if(z.type==="connected"){g.writeln(`\x1B[32mConnected (${z.shell})\x1B[0m\r
</div>`);const w=document.getElementById("exec-modal"),x=document.getElementById("exec-terminal"),j=document.getElementById("exec-close");let g=null,N=null,P=null;function M(){if(N){try{N.close()}catch{}N=null}if(g){try{g.dispose()}catch{}g=null}P=null,x.innerHTML=""}function R(h,C){if(M(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${C||h}`,w?.classList.add("show"),typeof Terminal>"u"){x.innerHTML='<div style="color: #f44; padding: 20px; font-family: monospace;">xterm.js not loaded</div>';return}g=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(P=new FitAddon.FitAddon,g.loadAddon(P)),g.open(x),P&&setTimeout(()=>P.fit(),50);const E=location.protocol==="https:"?"wss:":"ws:";N=new WebSocket(`${E}//${location.host}/ws/exec/${encodeURIComponent(h)}`),N.binaryType="arraybuffer",N.onopen=()=>{if(g.writeln("\x1B[32mConnecting...\x1B[0m"),P){const k=P.proposeDimensions();k&&N.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}},N.onmessage=k=>{if(typeof k.data=="string"){try{const z=JSON.parse(k.data);if(z.type==="connected"){g.writeln(`\x1B[32mConnected (${z.shell})\x1B[0m\r
`);return}if(z.type==="error"){g.writeln(`\x1B[31mError: ${z.message}\x1B[0m`);return}if(z.type==="exit"){g.writeln(`\r
\x1B[33mSession ended.\x1B[0m`);return}}catch{}g.write(w.data)}else g.write(new Uint8Array(w.data))},N.onclose=()=>{g&&g.writeln(`\r
\x1B[33mSession ended.\x1B[0m`);return}}catch{}g.write(k.data)}else g.write(new Uint8Array(k.data))},N.onclose=()=>{g&&g.writeln(`\r
\x1B[33mDisconnected.\x1B[0m`)},N.onerror=()=>{g&&g.writeln(`\r
\x1B[31mConnection error.\x1B[0m`)},g.onData(w=>{N&&N.readyState===WebSocket.OPEN&&N.send(w)}),g.onResize(({cols:w,rows:z})=>{N&&N.readyState===WebSocket.OPEN&&N.send(JSON.stringify({type:"resize",cols:w,rows:z}))});const M=()=>{A&&A.fit()};window.addEventListener("resize",M),x._resizeHandler=M}j?.addEventListener("click",()=>{D(),x._resizeHandler&&window.removeEventListener("resize",x._resizeHandler),x?.classList.remove("show")}),x?.addEventListener("click",f=>{f.target===x&&(D(),x._resizeHandler&&window.removeEventListener("resize",x._resizeHandler),x?.classList.remove("show"))}),window.openExecModal=R})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal">
\x1B[31mConnection error.\x1B[0m`)},g.onData(k=>{N&&N.readyState===WebSocket.OPEN&&N.send(k)}),g.onResize(({cols:k,rows:z})=>{N&&N.readyState===WebSocket.OPEN&&N.send(JSON.stringify({type:"resize",cols:k,rows:z}))});const H=()=>{P&&P.fit()};window.addEventListener("resize",H),w._resizeHandler=H}j?.addEventListener("click",()=>{M(),w._resizeHandler&&window.removeEventListener("resize",w._resizeHandler),w?.classList.remove("show")}),w?.addEventListener("click",h=>{h.target===w&&(M(),w._resizeHandler&&window.removeEventListener("resize",w._resizeHandler),w?.classList.remove("show"))}),window.openExecModal=R})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 950px; max-width: 1150px;">
<h3>\u{1F4DC} Audit Log</h3>
<p class="modal-subtitle">
@@ -1811,7 +1811,7 @@ Enter version to rollback to:`);if(!r)return;if(!e.includes(r)){showNotification
<button id="audit-cancel">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("audit-modal"),b=document.getElementById("audit-log-btn"),j=document.getElementById("audit-cancel"),g=document.getElementById("audit-refresh-btn"),N=document.getElementById("audit-clear-btn"),A=document.getElementById("audit-filter"),D=document.getElementById("audit-outcome-filter"),R=document.getElementById("audit-since"),f=document.getElementById("audit-until"),C=document.getElementById("audit-log-container"),E=document.getElementById("audit-load-more");let M=0,w=null,z=0;const S=50;function T(H){if(!H)return null;const O=new Date(H);return isNaN(O.getTime())?null:O.toISOString()}async function P(H){try{H?(w&&w.abort(),w=new AbortController):(w&&w.abort(),w=new AbortController,M=0,z++,C.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const O=z,u=new URLSearchParams;u.set("limit",String(S)),u.set("offset",String(M));const m=A.value,L=D.value,k=T(R.value),I=T(f.value);m&&u.set("action",m),L&&u.set("outcome",L),k&&u.set("since",k),I&&u.set("until",I);const i=await fetch("/api/v1/audit-logs?"+u.toString(),{signal:w.signal});if(!i.ok){C.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: HTTP ${i.status}</div>`,E.style.display="none";return}const c=await i.json();if(!c.success){C.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(c.error||"unknown")}</div>`,E.style.display="none";return}if(!H&&O!==z)return;const d=Array.isArray(c.entries)?c.entries:[];if(d.length===0&&!H){const p=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";C.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>${escapeHtml(p)}</div>`,E.style.display="none";return}let y="";H||(y='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',y+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);">',y+='<th style="padding: 6px; text-align: left;">When</th>',y+='<th style="padding: 6px; text-align: left;">Actor</th>',y+='<th style="padding: 6px; text-align: left;">IP</th>',y+='<th style="padding: 6px; text-align: left;">Action</th>',y+='<th style="padding: 6px; text-align: left;">Resource</th>',y+='<th style="padding: 6px; text-align: left;">Result</th>',y+="</tr>");for(const p of d){const n=p.outcome==="success",e=v(p);y+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',y+=`<td style="padding: 6px; color: var(--muted);" title="${escapeHtml(p.timestamp||"")}">${timeAgo(p.timestamp)}</td>`,y+=`<td style="padding: 6px; font-size: 0.78rem;">${e}</td>`,y+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(p.ip||"-")}</td>`,y+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(p.action||"-")}</td>`,y+=`<td style="padding: 6px;">${escapeHtml(p.resource||"-")}</td>`,y+=`<td style="padding: 6px;"><span style="color: ${n?"var(--ok-fg)":"var(--bad-fg)"};">${n?"\u2713":"\u2717"} ${escapeHtml(p.outcome||"")}</span></td>`,y+="</tr>",p.details&&Object.keys(p.details).length>0&&(y+=`<tr class="audit-detail" style="display: none;"><td colspan="6" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace;">${escapeHtml(JSON.stringify(p.details,null,2))}</pre></td></tr>`)}if(!H)y+="</table>",C.innerHTML=y;else{const p=C.querySelector("table");p&&p.insertAdjacentHTML("beforeend",y)}M+=d.length,E.style.display=c.hasMore?"":"none",C.querySelectorAll(".audit-row").forEach(p=>{p.dataset.wired||(p.dataset.wired="true",p.addEventListener("click",()=>{const n=p.nextElementSibling;n&&n.classList.contains("audit-detail")&&(n.style.display=n.style.display==="none"?"":"none")}))})}catch(O){if(O&&O.name==="AbortError")return;C.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(O.message)}</div>`}}function v(H){const O=H.details||{},u=O.userEmail,m=O.userId,L=O.userRole,k=O.viaProvider;if(u){const I=L?` <span style="color: var(--muted); font-size: 0.72rem;">[${escapeHtml(L)}${k?"/"+escapeHtml(k):""}]</span>`:"";return`${escapeHtml(u)}${I}`}return m?`<span style="font-family: monospace; color: var(--muted);">${escapeHtml(m)}</span>`:H.ip?'<span style="color: var(--muted);">anon</span>':'<span style="color: var(--muted);">system</span>'}b?.addEventListener("click",()=>{x?.classList.add("show"),P(!1)}),wireModal(x,j),g?.addEventListener("click",()=>P(!1)),A?.addEventListener("change",()=>P(!1)),D?.addEventListener("change",()=>P(!1));let B;[R,f].forEach(H=>{H?.addEventListener("change",()=>{clearTimeout(B),B=setTimeout(()=>P(!1),250)})}),E?.addEventListener("click",()=>P(!0)),N?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const O=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"Line truncated
</div>`);const w=document.getElementById("audit-modal"),x=document.getElementById("audit-log-btn"),j=document.getElementById("audit-cancel"),g=document.getElementById("audit-refresh-btn"),N=document.getElementById("audit-clear-btn"),P=document.getElementById("audit-filter"),M=document.getElementById("audit-outcome-filter"),R=document.getElementById("audit-since"),h=document.getElementById("audit-until"),C=document.getElementById("audit-log-container"),E=document.getElementById("audit-load-more");let H=0,k=null,z=0;const S=50;function T($){if(!$)return null;const U=new Date($);return isNaN(U.getTime())?null:U.toISOString()}async function D($){try{$?(k&&k.abort(),k=new AbortController):(k&&k.abort(),k=new AbortController,H=0,z++,C.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const U=z,m=new URLSearchParams;m.set("limit",String(S)),m.set("offset",String(H));const v=P.value,I=M.value,b=T(R.value),L=T(h.value);v&&m.set("action",v),I&&m.set("outcome",I),b&&m.set("since",b),L&&m.set("until",L);const l=await fetch("/api/v1/audit-logs?"+m.toString(),{signal:k.signal});if(!l.ok){C.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: HTTP ${l.status}</div>`,E.style.display="none";return}const c=await l.json();if(!c.success){C.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(c.error||"unknown")}</div>`,E.style.display="none";return}if(!$&&U!==z)return;const d=Array.isArray(c.entries)?c.entries:[];if(d.length===0&&!$){const p=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";C.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>${escapeHtml(p)}</div>`,E.style.display="none";return}let f="";$||(f='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',f+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);">',f+='<th style="padding: 6px; text-align: left;">When</th>',f+='<th style="padding: 6px; text-align: left;">Actor</th>',f+='<th style="padding: 6px; text-align: left;">IP</th>',f+='<th style="padding: 6px; text-align: left;">Action</th>',f+='<th style="padding: 6px; text-align: left;">Resource</th>',f+='<th style="padding: 6px; text-align: left;">Result</th>',f+="</tr>");for(const p of d){const e=p.outcome==="success",s=y(p);f+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',f+=`<td style="padding: 6px; color: var(--muted);" title="${escapeHtml(p.timestamp||"")}">${timeAgo(p.timestamp)}</td>`,f+=`<td style="padding: 6px; font-size: 0.78rem;">${s}</td>`,f+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(p.ip||"-")}</td>`,f+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(p.action||"-")}</td>`,f+=`<td style="padding: 6px;">${escapeHtml(p.resource||"-")}</td>`,f+=`<td style="padding: 6px;"><span style="color: ${e?"var(--ok-fg)":"var(--bad-fg)"};">${e?"\u2713":"\u2717"} ${escapeHtml(p.outcome||"")}</span></td>`,f+="</tr>",p.details&&Object.keys(p.details).length>0&&(f+=`<tr class="audit-detail" style="display: none;"><td colspan="6" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace;">${escapeHtml(JSON.stringify(p.details,null,2))}</pre></td></tr>`)}if(!$)f+="</table>",C.innerHTML=f;else{const p=C.querySelector("table");p&&p.insertAdjacentHTML("beforeend",f)}H+=d.length,E.style.display=c.hasMore?"":"none",C.querySelectorAll(".audit-row").forEach(p=>{p.dataset.wired||(p.dataset.wired="true",p.addEventListener("click",()=>{const e=p.nextElementSibling;e&&e.classList.contains("audit-detail")&&(e.style.display=e.style.display==="none"?"":"none")}))})}catch(U){if(U&&U.name==="AbortError")return;C.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(U.message)}</div>`}}function y($){const U=$.details||{},m=U.userEmail,v=U.userId,I=U.userRole,b=U.viaProvider;if(m){const L=I?` <span style="color: var(--muted); font-size: 0.72rem;">[${escapeHtml(I)}${b?"/"+escapeHtml(b):""}]</span>`:"";return`${escapeHtml(m)}${L}`}return v?`<span style="font-family: monospace; color: var(--muted);">${escapeHtml(v)}</span>`:$.ip?'<span style="color: var(--muted);">anon</span>':'<span style="color: var(--muted);">system</span>'}x?.addEventListener("click",()=>{w?.classList.add("show"),D(!1)}),wireModal(w,j),g?.addEventListener("click",()=>D(!1)),P?.addEventListener("change",()=>D(!1)),M?.addEventListener("change",()=>D(!1));let B;[R,h].forEach($=>{$?.addEventListener("change",()=>{clearTimeout(B),B=setTimeout(()=>D(!1),250)})}),E?.addEventListener("click",()=>D(!0)),N?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const U=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"Line truncated
<div class="weather-modal-content" style="min-width: 980px; max-width: 1280px;">
<h3>\u{1F6E1}\uFE0F Security Center</h3>
<p class="modal-subtitle">
@@ -1890,28 +1890,28 @@ Enter version to rollback to:`);if(!r)return;if(!e.includes(r)){showNotification
<button id="sec-cancel">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("security-modal"),b=document.getElementById("security-center-btn"),j=document.getElementById("sec-cancel"),g=x.querySelectorAll(".sec-tab"),N=x.querySelectorAll(".sec-panel");let A=[],D=[],R=null;g.forEach(i=>{i.addEventListener("click",()=>{g.forEach(c=>c.classList.toggle("active",c===i)),N.forEach(c=>c.style.display=c.dataset.panel===i.dataset.tab?"":"none"),i.dataset.tab==="overview"&&M(),i.dataset.tab==="events"&&B(),i.dataset.tab==="hosts"&&m()})}),b&&b.addEventListener("click",()=>{x.classList.add("show"),M(),C()}),j.addEventListener("click",f),x.addEventListener("click",i=>{i.target===x&&f()});function f(){x.classList.remove("show"),E()}function C(){if(E(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{R=new EventSource("/api/v1/security/events/stream"),R.addEventListener("init",i=>{try{A=JSON.parse(i.data).events||[],H()}catch{}}),R.addEventListener("security",i=>{try{const c=JSON.parse(i.data);A.unshift(c),A.length>500&&(A.length=500);const d=x.querySelector(".sec-tab.active")?.dataset?.tab;d==="events"?H():d==="overview"&&M()}catch{}}),R.onerror=()=>{}}catch(i){console.warn("[security] SSE failed:",i.message)}}function E(){if(R){try{R.close()}catch{}R=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{x.classList.contains("show")&&C()});async function M(){try{const i=new Date(Date.now()-864e5).toISOString(),[c,d,y]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(i)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(i)}`)]),p=(await c.json()).data||{},n=(await d.json()).data?.hosts||[],e=(await y.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${p.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${p.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${p.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${n.length} hosts`,w("sec-top-actors",p.top_actors||[]),w("sec-top-targets",p.top_targets||[])}catch(i){console.warn("[security] refreshOverview failed:",i.message)}}function w(i,c){const d=document.getElementById(i);if(!c.length){d.innerHTML='<div class="panel-empty">No data</div>';return}d.innerHTML='<table style="width:100%;font-size:0.85rem;">'+c.map(y=>`<tr><td style="padding:3px 0;word-break:break-all;">${k(String(y.key))}</td><td style="text-align:right;color:var(--muted);">${y.count}</td></tr>`).join("")+"</table>"}const z=document.getElementById("sec-filter-source"),S=document.getElementById("sec-filter-severity"),T=document.getElementById("sec-filter-host"),P=document.getElementById("sec-filter-actor"),v=document.getElementById("sec-refresh-btn");[z,S,T].forEach(i=>i.addEventListener("change",B)),P.addEventListener("input",I(B,250)),v.addEventListener("click",B);async function B(){try{const i=new URLSearchParams;i.set("limit","200"),z.value&&i.set("source_type",z.value),S.value&&i.set("severity",S.value),T.value&&i.set("source_host",T.value),P.value&&i.set("actor_prefix",P.value),A=(await(await fetch(`/api/v1/security/events?${i}`)).json()).data.events||[],H(),(!T.options.length||T.options.length===1)&&await u()}catch(i){document.getElementById("sec-events-container").innerHTML='<div class="panel-empty">Load failed: '+k(i.message)+"</div>"}}function H(){const i=document.getElementById("sec-events-container");if(!A.length){i.innerHTML='<div class="panel-empty">No events</div>';return}i.innerHTML=A.slice(0,200).map(O).join("")}function O(i){const c=i.severity||"info",d={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",y=i.ts?new Date(i.ts).toLocaleTimeString():"",p=i.source_type||"",n=i.actor||"\u2014",e=i.target||"",r=i.action||"",s=i.outcome||"";return`<div class="sec-event-row" style="display:grid;grid-template-columns:84px 80px 1fr 1fr 100px 90px;gap:8px;padding:5px 8px;border-bottom:1px solid var(--border);font-size:0.82rem;align-items:center;">
<span style="color:${d};font-weight:600;">${k(c)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${k(p)}</span>
<span title="${k(n)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${k(n)}</span>
<span title="${k(e)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${k(r)} ${k(e)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${k(s)}</span>
<span style="color:var(--muted);font-size:0.75rem;text-align:right;">${k(y)}</span>
</div>`}async function u(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],d=T.value;T.innerHTML='<option value="">All hosts</option>'+c.map(y=>`<option value="${k(y.id)}">${k(y.label||y.id)}</option>`).join(""),d&&(T.value=d)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",L),document.getElementById("sec-hosts-refresh").addEventListener("click",m);async function m(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];D=c;const d=document.getElementById("sec-hosts-container");if(!c.length){d.innerHTML='<div class="panel-empty">No hosts registered. Click \u2795 Register Host to add one.</div>';return}d.innerHTML=c.map(y=>{const p=y.enabled?y.last_seen_at?Date.now()-Date.parse(y.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`<div style="padding:10px 12px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
</div>`);const w=document.getElementById("security-modal"),x=document.getElementById("security-center-btn"),j=document.getElementById("sec-cancel"),g=w.querySelectorAll(".sec-tab"),N=w.querySelectorAll(".sec-panel");let P=[],M=[],R=null;g.forEach(l=>{l.addEventListener("click",()=>{g.forEach(c=>c.classList.toggle("active",c===l)),N.forEach(c=>c.style.display=c.dataset.panel===l.dataset.tab?"":"none"),l.dataset.tab==="overview"&&H(),l.dataset.tab==="events"&&B(),l.dataset.tab==="hosts"&&v()})}),x&&x.addEventListener("click",()=>{w.classList.add("show"),H(),C()}),j.addEventListener("click",h),w.addEventListener("click",l=>{l.target===w&&h()});function h(){w.classList.remove("show"),E()}function C(){if(E(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{R=new EventSource("/api/v1/security/events/stream"),R.addEventListener("init",l=>{try{P=JSON.parse(l.data).events||[],$()}catch{}}),R.addEventListener("security",l=>{try{const c=JSON.parse(l.data);P.unshift(c),P.length>500&&(P.length=500);const d=w.querySelector(".sec-tab.active")?.dataset?.tab;d==="events"?$():d==="overview"&&H()}catch{}}),R.onerror=()=>{}}catch(l){console.warn("[security] SSE failed:",l.message)}}function E(){if(R){try{R.close()}catch{}R=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{w.classList.contains("show")&&C()});async function H(){try{const l=new Date(Date.now()-864e5).toISOString(),[c,d,f]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(l)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(l)}`)]),p=(await c.json()).data||{},e=(await d.json()).data?.hosts||[],s=(await f.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${s} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${p.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${p.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${p.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${e.length} hosts`,k("sec-top-actors",p.top_actors||[]),k("sec-top-targets",p.top_targets||[])}catch(l){console.warn("[security] refreshOverview failed:",l.message)}}function k(l,c){const d=document.getElementById(l);if(!c.length){d.innerHTML='<div class="panel-empty">No data</div>';return}d.innerHTML='<table style="width:100%;font-size:0.85rem;">'+c.map(f=>`<tr><td style="padding:3px 0;word-break:break-all;">${b(String(f.key))}</td><td style="text-align:right;color:var(--muted);">${f.count}</td></tr>`).join("")+"</table>"}const z=document.getElementById("sec-filter-source"),S=document.getElementById("sec-filter-severity"),T=document.getElementById("sec-filter-host"),D=document.getElementById("sec-filter-actor"),y=document.getElementById("sec-refresh-btn");[z,S,T].forEach(l=>l.addEventListener("change",B)),D.addEventListener("input",L(B,250)),y.addEventListener("click",B);async function B(){try{const l=new URLSearchParams;l.set("limit","200"),z.value&&l.set("source_type",z.value),S.value&&l.set("severity",S.value),T.value&&l.set("source_host",T.value),D.value&&l.set("actor_prefix",D.value),P=(await(await fetch(`/api/v1/security/events?${l}`)).json()).data.events||[],$(),(!T.options.length||T.options.length===1)&&await m()}catch(l){document.getElementById("sec-events-container").innerHTML='<div class="panel-empty">Load failed: '+b(l.message)+"</div>"}}function $(){const l=document.getElementById("sec-events-container");if(!P.length){l.innerHTML='<div class="panel-empty">No events</div>';return}l.innerHTML=P.slice(0,200).map(U).join("")}function U(l){const c=l.severity||"info",d={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",f=l.ts?new Date(l.ts).toLocaleTimeString():"",p=l.source_type||"",e=l.actor||"\u2014",s=l.target||"",r=l.action||"",o=l.outcome||"";return`<div class="sec-event-row" style="display:grid;grid-template-columns:84px 80px 1fr 1fr 100px 90px;gap:8px;padding:5px 8px;border-bottom:1px solid var(--border);font-size:0.82rem;align-items:center;">
<span style="color:${d};font-weight:600;">${b(c)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${b(p)}</span>
<span title="${b(e)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${b(e)}</span>
<span title="${b(s)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${b(r)} ${b(s)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${b(o)}</span>
<span style="color:var(--muted);font-size:0.75rem;text-align:right;">${b(f)}</span>
</div>`}async function m(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],d=T.value;T.innerHTML='<option value="">All hosts</option>'+c.map(f=>`<option value="${b(f.id)}">${b(f.label||f.id)}</option>`).join(""),d&&(T.value=d)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",I),document.getElementById("sec-hosts-refresh").addEventListener("click",v);async function v(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];M=c;const d=document.getElementById("sec-hosts-container");if(!c.length){d.innerHTML='<div class="panel-empty">No hosts registered. Click \u2795 Register Host to add one.</div>';return}d.innerHTML=c.map(f=>{const p=f.enabled?f.last_seen_at?Date.now()-Date.parse(f.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`<div style="padding:10px 12px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
<div>
<strong>${k(y.label||y.id)}</strong>
<span style="color:var(--muted);margin-left:8px;font-size:0.8rem;">${k(y.type)}</span>
<strong>${b(f.label||f.id)}</strong>
<span style="color:var(--muted);margin-left:8px;font-size:0.8rem;">${b(f.type)}</span>
<div style="color:var(--muted);font-size:0.78rem;margin-top:2px;">
id: ${k(y.id)} \xB7
registered ${new Date(y.registered_at).toLocaleDateString()} \xB7
last seen ${y.last_seen_at?new Date(y.last_seen_at).toLocaleString():"never"}
id: ${b(f.id)} \xB7
registered ${new Date(f.registered_at).toLocaleDateString()} \xB7
last seen ${f.last_seen_at?new Date(f.last_seen_at).toLocaleString():"never"}
</div>
</div>
<div>
<span style="font-size:0.85rem;margin-right:12px;">${p}</span>
${y.id==="self"?"":`<button class="btn-sm sec-host-del" data-id="${k(y.id)}" style="color:var(--bad-fg);">Remove</button>`}
${f.id==="self"?"":`<button class="btn-sm sec-host-del" data-id="${b(f.id)}" style="color:var(--bad-fg);">Remove</button>`}
</div>
</div>`}).join(""),d.querySelectorAll(".sec-host-del").forEach(y=>{y.addEventListener("click",async()=>{confirm(`Remove host ${y.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(y.dataset.id)}`,{method:"DELETE"}),m())})})}catch(i){document.getElementById("sec-hosts-container").innerHTML='<div class="panel-empty">Load failed: '+k(i.message)+"</div>"}}async function L(){const i=prompt("Host id (lowercase, no spaces):");if(!i)return;const c=prompt("Display label:",i)||i,d=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const y=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:i,label:c,type:d})}),p=await y.json();if(!y.ok){alert("Failed: "+(p?.error?.message||y.statusText));return}alert(`\u2705 Host registered!
</div>`}).join(""),d.querySelectorAll(".sec-host-del").forEach(f=>{f.addEventListener("click",async()=>{confirm(`Remove host ${f.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(f.dataset.id)}`,{method:"DELETE"}),v())})})}catch(l){document.getElementById("sec-hosts-container").innerHTML='<div class="panel-empty">Load failed: '+b(l.message)+"</div>"}}async function I(){const l=prompt("Host id (lowercase, no spaces):");if(!l)return;const c=prompt("Display label:",l)||l,d=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const f=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:l,label:c,type:d})}),p=await f.json();if(!f.ok){alert("Failed: "+(p?.error?.message||f.statusText));return}alert(`\u2705 Host registered!
id: ${p.data.host.id}
label: ${p.data.host.label}
@@ -1922,7 +1922,7 @@ type: ${p.data.host.type}
${p.data.api_key}
Send this key as: Authorization: Bearer <api_key>
To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(y){alert("Failed: "+y.message)}}function k(i){return String(i).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}function I(i,c){let d;return function(){clearTimeout(d),d=setTimeout(()=>i.apply(this,arguments),c)}}})(),window.__dc133_buildRepoOptions=function(x,b){var j=b||function(g){return String(g).replace(/[&<>"']/g,function(N){return{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[N]})};return'<option value="">\u2014 choose a repo \u2014</option>'+(x||[]).map(function(g){return'<option value="'+j(g.url)+'" data-id="'+j(g.id)+'">'+j(g.full_name)+(g.description?" \u2014 "+j(g.description):"")+"</option>"}).join("")},window.__dc133_requestToken=function(x,b){if(x)return"";var j=String(b||"").trim();return j||void 0},(function(){injectModal("deploys-modal",`<div id="deploys-modal" class="weather-modal">
To endpoint: POST /api/v1/security/events/ingest or /events/batch`),v()}catch(f){alert("Failed: "+f.message)}}function b(l){return String(l).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}function L(l,c){let d;return function(){clearTimeout(d),d=setTimeout(()=>l.apply(this,arguments),c)}}})(),window.__dc133_buildRepoOptions=function(w,x){var j=x||function(g){return String(g).replace(/[&<>"']/g,function(N){return{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[N]})};return'<option value="">\u2014 choose a repo \u2014</option>'+(w||[]).map(function(g){return'<option value="'+j(g.url)+'" data-id="'+j(g.id)+'">'+j(g.full_name)+(g.description?" \u2014 "+j(g.description):"")+"</option>"}).join("")},window.__dc133_requestToken=function(w,x){if(w)return"";var j=String(x||"").trim();return j||void 0},(function(){injectModal("deploys-modal",`<div id="deploys-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 860px; max-width: 1200px;">
<h3>\u{1F69A} Deploys</h3>
<p class="modal-subtitle">
@@ -2006,16 +2006,16 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(y)
<button class="btn" id="dep-close">Close</button>
</div>
</div>
</div>`);const x=P=>document.getElementById(P);let b=null,j=!1;function g(P){return window.escapeHtml?window.escapeHtml(String(P)):String(P).replace(/[&<>"']/g,v=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[v])}async function N(P,v){const B=await fetch("/dashcaddy-api/api/v1/deploys"+P,Object.assign({credentials:"include"},v||{}));let H=null;try{H=await B.json()}catch{H={success:!1,error:"non-JSON response"}}return{status:B.status,body:H}}function A(P){const v=x("dep-output");v.style.display="block",v.textContent=P||"(no output)",v.scrollTop=v.scrollHeight}async function D(){const P=x("dep-services"),{body:v}=await N("/services");if(!v.success){P.innerHTML="<em>"+g(v.error||"unavailable")+"</em>";return}const B=v.services||[];if(!B.length){P.innerHTML="<em>No shipdeck deployments on record yet.</em>";return}P.innerHTML='<table class="table" style="width:100%;"><thead><tr><th>Service</th><th>Last action</th><th>When</th><th>Release</th><th></th></tr></thead><tbody>'+B.map(H=>"<tr><td><strong>"+g(H.name)+"</strong></td><td>"+g(H.last_action)+"</td><td>"+g(H.last_time)+"</td><td>"+g(H.last_epoch)+'</td><td><button class="btn btn-sm dep-rollback" data-service="'+g(H.name)+'">Rollback</button> <button class="btn btn-sm dep-status" data-service="'+g(H.name)+'">Status</button></td></tr>').join("")+"</tbody></table>"}async function R(){const P=x("dep-repo-select"),{body:v}=await N("/repos");if(!v.success){P.innerHTML="<option>"+g(v.error||"unavailable")+"</option>";return}const B=v.repos||[];P.innerHTML=B.length?B.map(H=>'<option value="'+g(H.dir)+'">'+g(H.name)+"</option>").join(""):'<option value="">(no repos with a Shipdeckfile found)</option>'}async function f(P){const v=x("dep-journal"),B=P?"?service="+encodeURIComponent(P):"",{body:H}=await N("/journal"+B),O=H.rows||[];if(!O.length){v.innerHTML="<em>No journal rows.</em>";return}v.innerHTML='<table class="table" style="width:100%;"><thead><tr><th>Time</th><th>Service</th><th>Action</th><th>Release</th><th>Duration</th></tr></thead><tbody>'+O.map(u=>"<tr><td>"+g(u.time)+"</td><td>"+g(u.service)+"</td><td>"+g(u.action)+"</td><td>"+g(u.epoch)+"</td><td>"+g(u.duration||"\u2014")+"</td></tr>").join("")+"</tbody></table>"}async function C(){const P=document.getElementById("dep-gh-gitea"),v=document.getElementById("dep-gh-gitea-host"),B=document.getElementById("dep-gh-gitea-token"),H=document.getElementById("dep-gh-anonymous"),O={};if(v&&v.value.trim()&&(O.gitea_url="https://"+v.value.trim().replace(/^https?:\/*/,"")),H&&H.checked)O.token="";else{const u=window.__dc133_requestToken(!1,B&&B.value);u!==void 0&&(O.token=u)}try{const{status:u,body:m}=await N("/gitea-repos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!m.success||!(m.repos||[]).length){P.innerHTML='<option value="">'+g(m.error||"no repos found")+"</option>";return}P.innerHTML=window.__dc133_buildRepoOptions(m.repos,g)}catch{P.innerHTML='<option value="">unavailable</option>'}}async function E(){const P=document.getElementById("dep-gh-btn"),v=document.getElementById("dep-gh-url").value.trim(),B=(document.getElementById("dep-gh-service").value.trim()||"").toLowerCase(),H=document.getElementById("dep-gh-args").value.trim();if(!v||!B){A("Repo URL and name are required.");return}const O=H?H.split(/\s+/):[];M(!0,P,"Install"),A("Installing "+v+`
Cloning, building, gating and DNS-ing... (~30-60s)`);try{const u=!!(document.getElementById("dep-gh-anonymous")||{}).checked,m=(document.getElementById("dep-gh-gitea-token")||{value:""}).value,L=window.__dc133_requestToken(u,m),{status:k,body:I}=await N("/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo_url:v,service:B,args:O,token:L})});if(!I.success){A((I.output?I.output+`
`:"")+"FAIL "+(I.error||"HTTP "+k)),M(!1,P,"Install");return}const i=I.service||{};if(!(window.APPS||[]).some(d=>d.id===i.id)){const d={id:i.id,name:i.name||i.id,url:i.url,logo:i.logo,tailscaleOnly:!0,isCustom:!0};try{await fetch("/dashcaddy-api/api/v1/services",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),window.APPS.push(d),typeof window.renderApps=="function"&&window.renderApps(),typeof window.renderGrid=="function"&&window.renderGrid()}catch{}}A("INSTALLED "+(i.name||i.id)+" in "+(i.deploy_seconds||"?")+`s
Card: `+(i.url||"")+`
`+(I.output||"").slice(-800)),D()}catch(u){A("install error: "+u.message)}M(!1,P,"Install")}function M(P,v,B){v&&(v.disabled=P,B&&(v.textContent=P?"Working\u2026":B))}async function w(){const P=x("dep-deploy-btn"),v=x("dep-repo-select").value;if(v){M(!0,P,"Deploy"),A("Deploying "+v+`
This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:v})});A((B.output||B.error||"")+(B.success?`
</div>`);const w=D=>document.getElementById(D);let x=null,j=!1;function g(D){return window.escapeHtml?window.escapeHtml(String(D)):String(D).replace(/[&<>"']/g,y=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[y])}async function N(D,y){const B=await fetch("/dashcaddy-api/api/v1/deploys"+D,Object.assign({credentials:"include"},y||{}));let $=null;try{$=await B.json()}catch{$={success:!1,error:"non-JSON response"}}return{status:B.status,body:$}}function P(D){const y=w("dep-output");y.style.display="block",y.textContent=D||"(no output)",y.scrollTop=y.scrollHeight}async function M(){const D=w("dep-services"),{body:y}=await N("/services");if(!y.success){D.innerHTML="<em>"+g(y.error||"unavailable")+"</em>";return}const B=y.services||[];if(!B.length){D.innerHTML="<em>No shipdeck deployments on record yet.</em>";return}D.innerHTML='<table class="table" style="width:100%;"><thead><tr><th>Service</th><th>Last action</th><th>When</th><th>Release</th><th></th></tr></thead><tbody>'+B.map($=>"<tr><td><strong>"+g($.name)+"</strong></td><td>"+g($.last_action)+"</td><td>"+g($.last_time)+"</td><td>"+g($.last_epoch)+'</td><td><button class="btn btn-sm dep-rollback" data-service="'+g($.name)+'">Rollback</button> <button class="btn btn-sm dep-status" data-service="'+g($.name)+'">Status</button></td></tr>').join("")+"</tbody></table>"}async function R(){const D=w("dep-repo-select"),{body:y}=await N("/repos");if(!y.success){D.innerHTML="<option>"+g(y.error||"unavailable")+"</option>";return}const B=y.repos||[];D.innerHTML=B.length?B.map($=>'<option value="'+g($.dir)+'">'+g($.name)+"</option>").join(""):'<option value="">(no repos with a Shipdeckfile found)</option>'}async function h(D){const y=w("dep-journal"),B=D?"?service="+encodeURIComponent(D):"",{body:$}=await N("/journal"+B),U=$.rows||[];if(!U.length){y.innerHTML="<em>No journal rows.</em>";return}y.innerHTML='<table class="table" style="width:100%;"><thead><tr><th>Time</th><th>Service</th><th>Action</th><th>Release</th><th>Duration</th></tr></thead><tbody>'+U.map(m=>"<tr><td>"+g(m.time)+"</td><td>"+g(m.service)+"</td><td>"+g(m.action)+"</td><td>"+g(m.epoch)+"</td><td>"+g(m.duration||"\u2014")+"</td></tr>").join("")+"</tbody></table>"}async function C(){const D=document.getElementById("dep-gh-gitea"),y=document.getElementById("dep-gh-gitea-host"),B=document.getElementById("dep-gh-gitea-token"),$=document.getElementById("dep-gh-anonymous"),U={};if(y&&y.value.trim()&&(U.gitea_url="https://"+y.value.trim().replace(/^https?:\/*/,"")),$&&$.checked)U.token="";else{const m=window.__dc133_requestToken(!1,B&&B.value);m!==void 0&&(U.token=m)}try{const{status:m,body:v}=await N("/gitea-repos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(U)});if(!v.success||!(v.repos||[]).length){D.innerHTML='<option value="">'+g(v.error||"no repos found")+"</option>";return}D.innerHTML=window.__dc133_buildRepoOptions(v.repos,g)}catch{D.innerHTML='<option value="">unavailable</option>'}}async function E(){const D=document.getElementById("dep-gh-btn"),y=document.getElementById("dep-gh-url").value.trim(),B=(document.getElementById("dep-gh-service").value.trim()||"").toLowerCase(),$=document.getElementById("dep-gh-args").value.trim();if(!y||!B){P("Repo URL and name are required.");return}const U=$?$.split(/\s+/):[];H(!0,D,"Install"),P("Installing "+y+`
Cloning, building, gating and DNS-ing... (~30-60s)`);try{const m=!!(document.getElementById("dep-gh-anonymous")||{}).checked,v=(document.getElementById("dep-gh-gitea-token")||{value:""}).value,I=window.__dc133_requestToken(m,v),{status:b,body:L}=await N("/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo_url:y,service:B,args:U,token:I})});if(!L.success){P((L.output?L.output+`
`:"")+"FAIL "+(L.error||"HTTP "+b)),H(!1,D,"Install");return}const l=L.service||{};if(!(window.APPS||[]).some(d=>d.id===l.id)){const d={id:l.id,name:l.name||l.id,url:l.url,logo:l.logo,tailscaleOnly:!0,isCustom:!0};try{await fetch("/dashcaddy-api/api/v1/services",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),window.APPS.push(d),typeof window.renderApps=="function"&&window.renderApps(),typeof window.renderGrid=="function"&&window.renderGrid()}catch{}}P("INSTALLED "+(l.name||l.id)+" in "+(l.deploy_seconds||"?")+`s
Card: `+(l.url||"")+`
`+(L.output||"").slice(-800)),M()}catch(m){P("install error: "+m.message)}H(!1,D,"Install")}function H(D,y,B){y&&(y.disabled=D,B&&(y.textContent=D?"Working\u2026":B))}async function k(){const D=w("dep-deploy-btn"),y=w("dep-repo-select").value;if(y){H(!0,D,"Deploy"),P("Deploying "+y+`
This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:y})});P((B.output||B.error||"")+(B.success?`
\u2705 SUCCESS`:`
\u274C FAILED`)),D()}catch(B){A("deploy error: "+B.message)}M(!1,P,"Deploy")}}async function z(P,v){if(confirm("Roll back "+P+" to the previous release?")){M(!0,v,"Rollback"),A("Rolling back "+P+"\u2026");try{const{body:B}=await N("/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:P})});A((B.output||B.error||"")+(B.success?`
\u274C FAILED`)),M()}catch(B){P("deploy error: "+B.message)}H(!1,D,"Deploy")}}async function z(D,y){if(confirm("Roll back "+D+" to the previous release?")){H(!0,y,"Rollback"),P("Rolling back "+D+"\u2026");try{const{body:B}=await N("/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:D})});P((B.output||B.error||"")+(B.success?`
\u2705 ROLLED BACK`:`
\u274C FAILED`)),D()}catch(B){A("rollback error: "+B.message)}M(!1,v,"Rollback")}}async function S(P,v){M(!0,v,"Status");try{const{body:B}=await N("/status?service="+encodeURIComponent(P));A(B.output||B.error||"(no output)")}catch(B){A("status error: "+B.message)}M(!1,v,"Status")}function T(){b=document.getElementById("deploys-btn"),b&&(b.addEventListener("click",async()=>{x("deploys-modal").classList.add("open"),j||(j=!0,D(),R(),f(""),C())}),x("dep-close").addEventListener("click",()=>{x("deploys-modal").classList.remove("open")}),document.querySelectorAll(".dep-tab").forEach(P=>{P.addEventListener("click",()=>{document.querySelectorAll(".dep-tab").forEach(v=>v.classList.remove("active")),P.classList.add("active"),document.querySelectorAll("#deploys-modal .dep-panel").forEach(v=>{v.style.display=v.dataset.panel===P.dataset.tab?"block":"none"})})}),x("dep-deploy-btn").addEventListener("click",w),x("dep-gh-btn").addEventListener("click",E),["dep-gh-gitea-host","dep-gh-gitea-token"].forEach(P=>{const v=document.getElementById(P);v&&v.addEventListener("change",()=>C())}),document.getElementById("dep-gh-gitea").addEventListener("change",P=>{const v=P.target.value;if(v){document.getElementById("dep-gh-url").value=v;const B=P.target.selectedOptions[0],H=B&&B.dataset?B.dataset.id:"",O=document.getElementById("dep-gh-service");H&&!O.value&&(O.value=H)}}),x("dep-journal-btn").addEventListener("click",()=>f(x("dep-journal-name").value.trim())),x("dep-status-btn").addEventListener("click",()=>{const P=x("dep-status-name").value.trim();P&&S(P)}),x("dep-services").addEventListener("click",P=>{const v=P.target.closest(".dep-rollback");if(v)return z(v.dataset.service,v);const B=P.target.closest(".dep-status");if(B)return S(B.dataset.service,B)}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",T):T()})(),(function(){const x=new ErrorHandler;injectModal("weather-modal",`<div id="weather-modal" class="weather-modal"><div class="weather-modal-content"><h3>Weather Settings</h3>
\u274C FAILED`)),M()}catch(B){P("rollback error: "+B.message)}H(!1,y,"Rollback")}}async function S(D,y){H(!0,y,"Status");try{const{body:B}=await N("/status?service="+encodeURIComponent(D));P(B.output||B.error||"(no output)")}catch(B){P("status error: "+B.message)}H(!1,y,"Status")}function T(){x=document.getElementById("deploys-btn"),x&&(x.addEventListener("click",async()=>{w("deploys-modal").classList.add("open"),j||(j=!0,M(),R(),h(""),C())}),w("dep-close").addEventListener("click",()=>{w("deploys-modal").classList.remove("open")}),document.querySelectorAll(".dep-tab").forEach(D=>{D.addEventListener("click",()=>{document.querySelectorAll(".dep-tab").forEach(y=>y.classList.remove("active")),D.classList.add("active"),document.querySelectorAll("#deploys-modal .dep-panel").forEach(y=>{y.style.display=y.dataset.panel===D.dataset.tab?"block":"none"})})}),w("dep-deploy-btn").addEventListener("click",k),w("dep-gh-btn").addEventListener("click",E),["dep-gh-gitea-host","dep-gh-gitea-token"].forEach(D=>{const y=document.getElementById(D);y&&y.addEventListener("change",()=>C())}),document.getElementById("dep-gh-gitea").addEventListener("change",D=>{const y=D.target.value;if(y){document.getElementById("dep-gh-url").value=y;const B=D.target.selectedOptions[0],$=B&&B.dataset?B.dataset.id:"",U=document.getElementById("dep-gh-service");$&&!U.value&&(U.value=$)}}),w("dep-journal-btn").addEventListener("click",()=>h(w("dep-journal-name").value.trim())),w("dep-status-btn").addEventListener("click",()=>{const D=w("dep-status-name").value.trim();D&&S(D)}),w("dep-services").addEventListener("click",D=>{const y=D.target.closest(".dep-rollback");if(y)return z(y.dataset.service,y);const B=D.target.closest(".dep-status");if(B)return S(B.dataset.service,B)}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",T):T()})(),(function(){const w=new ErrorHandler;injectModal("weather-modal",`<div id="weather-modal" class="weather-modal"><div class="weather-modal-content"><h3>Weather Settings</h3>
<label for="weather-location-input">Location:</label>
<input type="text" id="weather-location-input" placeholder="City name or ZIP (e.g., Hamburg, 90210)" maxlength="100">
<div style="font-size: 0.78rem; color: var(--muted); margin-top: 4px;">Enter a city name, postal code, or &ldquo;City, Country&rdquo;</div>
@@ -2026,23 +2026,23 @@ This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST"
<label class="weather-unit-option"><input type="radio" name="weather-unit-radio" value="metric"><span class="weather-unit-card">&deg;C / km/h</span></label>
</div>
</div>
<div class="weather-modal-buttons"><button id="weather-cancel">Cancel</button><button id="weather-save">Save</button></div></div></div>`);const b="weather-location",j="weather-zip",g="weather-geo",N="weather-unit";!safeGet(b)&&safeGet(j)&&safeSet(b,safeGet(j));function A(){return safeGet(N)||"imperial"}function D(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const R={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},f={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},C=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function E(v){return C[Math.round(v/22.5)%16]}async function M(v){const B=safeGet(g);if(B)try{const L=JSON.parse(B);if(L.query===v)return L}catch{}const H=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(v)}&count=1&language=en&format=json`);if(!H.ok)throw new Error("Geocoding failed");const O=await H.json();if(!O.results||!O.results.length)throw new Error("Location not found");const u=O.results[0],m={query:v,lat:u.latitude,lon:u.longitude,city:u.name,state:u.admin1||"",country:u.country||"",countryCode:u.country_code||""};return safeSet(g,JSON.stringify(m)),m}function w(v){return v.countryCode==="US"&&v.state?`${v.city}, ${v.state}`:v.country?`${v.city}, ${v.country}`:v.city}async function z(v){try{const B=await M(v),H=A(),O=H==="metric"?"celsius":"fahrenheit",u=H==="metric"?"kmh":"mph",m=`https://api.open-meteo.com/v1/forecast?latitude=${B.lat}&longitude=${B.lon}&current=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${O}&wind_speed_unit=${u}`,L=await fetch(m);if(!L.ok)throw new Error("Weather fetch failed");const I=(await L.json()).current,i=I.weather_code;return{temp:Math.round(I.temperature_2m),condition:R[i]||"Unknown",icon:f[i]||"\u{1F324}\uFE0F",locationStr:w(B),windSpeed:Math.round(I.wind_speed_10m),windDir:E(I.wind_direction_10m),unit:H}}catch(B){return console.warn("Weather fetch failed:",B),null}}async function S(){const v=D();if(!v.icon||!v.temp||!v.condition||!v.location||!v.wind){console.warn("Weather widget elements not found");return}const B=safeGet(b);if(!B){v.location.textContent="Set Location",v.temp.textContent="--\xB0",v.condition.textContent="Click \u2699\uFE0F to configure",v.wind.textContent="--",v.icon.innerHTML='<span class="weather-emoji">\u{1F324}\uFE0F</span>';return}try{const H=await z(B);if(H){const O=H.unit==="metric"?"\xB0C":"\xB0F",u=H.unit==="metric"?"km/h":"mph";v.location.textContent=H.locationStr,v.temp.textContent=`${H.temp}${O}`,v.condition.textContent=H.condition,v.wind.textContent=`Wind: ${H.windSpeed} ${u} ${H.windDir}`,v.icon.innerHTML=`<span class="weather-emoji">${escapeHtml(H.icon)}</span>`}}catch(H){x.logError("[Weather] Update Error",H,{function:"updateWeather"}),v.location.textContent="Weather Error",v.temp.textContent="Error",v.condition.textContent="Failed to load",v.wind.textContent="--"}}const T=document.getElementById("weather-modal"),P=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{P.value=safeGet(b)||"";const v=A(),B=T.querySelector(`input[name="weather-unit-radio"][value="${v}"]`);B&&(B.checked=!0),T.classList.add("show"),P.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const v=P.value.trim();if(v){safeGet(b)!==v&&safeSet(g,""),safeSet(b,v);const H=T.querySelector('input[name="weather-unit-radio"]:checked'),O=H?H.value:"imperial",u=A();safeSet(N,O),u!==O&&safeSet(g,""),T.classList.remove("show"),S()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(T),document.addEventListener("keydown",v=>{v.keyLine truncated
<circle cx="${o}" cy="${l}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/>
${_}
<div class="weather-modal-buttons"><button id="weather-cancel">Cancel</button><button id="weather-save">Save</button></div></div></div>`);const x="weather-location",j="weather-zip",g="weather-geo",N="weather-unit";!safeGet(x)&&safeGet(j)&&safeSet(x,safeGet(j));function P(){return safeGet(N)||"imperial"}function M(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const R={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},h={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},C=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function E(y){return C[Math.round(y/22.5)%16]}async function H(y){const B=safeGet(g);if(B)try{const I=JSON.parse(B);if(I.query===y)return I}catch{}const $=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(y)}&count=1&language=en&format=json`);if(!$.ok)throw new Error("Geocoding failed");const U=await $.json();if(!U.results||!U.results.length)throw new Error("Location not found");const m=U.results[0],v={query:y,lat:m.latitude,lon:m.longitude,city:m.name,state:m.admin1||"",country:m.country||"",countryCode:m.country_code||""};return safeSet(g,JSON.stringify(v)),v}function k(y){return y.countryCode==="US"&&y.state?`${y.city}, ${y.state}`:y.country?`${y.city}, ${y.country}`:y.city}async function z(y){try{const B=await H(y),$=P(),U=$==="metric"?"celsius":"fahrenheit",m=$==="metric"?"kmh":"mph",v=`https://api.open-meteo.com/v1/forecast?latitude=${B.lat}&longitude=${B.lon}&current=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${U}&wind_speed_unit=${m}`,I=await fetch(v);if(!I.ok)throw new Error("Weather fetch failed");const L=(await I.json()).current,l=L.weather_code;return{temp:Math.round(L.temperature_2m),condition:R[l]||"Unknown",icon:h[l]||"\u{1F324}\uFE0F",locationStr:k(B),windSpeed:Math.round(L.wind_speed_10m),windDir:E(L.wind_direction_10m),unit:$}}catch(B){return console.warn("Weather fetch failed:",B),null}}async function S(){const y=M();if(!y.icon||!y.temp||!y.condition||!y.location||!y.wind){console.warn("Weather widget elements not found");return}const B=safeGet(x);if(!B){y.location.textContent="Set Location",y.temp.textContent="--\xB0",y.condition.textContent="Click \u2699\uFE0F to configure",y.wind.textContent="--",y.icon.innerHTML='<span class="weather-emoji">\u{1F324}\uFE0F</span>';return}try{const $=await z(B);if($){const U=$.unit==="metric"?"\xB0C":"\xB0F",m=$.unit==="metric"?"km/h":"mph";y.location.textContent=$.locationStr,y.temp.textContent=`${$.temp}${U}`,y.condition.textContent=$.condition,y.wind.textContent=`Wind: ${$.windSpeed} ${m} ${$.windDir}`,y.icon.innerHTML=`<span class="weather-emoji">${escapeHtml($.icon)}</span>`}}catch($){w.logError("[Weather] Update Error",$,{function:"updateWeather"}),y.location.textContent="Weather Error",y.temp.textContent="Error",y.condition.textContent="Failed to load",y.wind.textContent="--"}}const T=document.getElementById("weather-modal"),D=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{D.value=safeGet(x)||"";const y=P(),B=T.querySelector(`input[name="weather-unit-radio"][value="${y}"]`);B&&(B.checked=!0),T.classList.add("show"),D.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const y=D.value.trim();if(y){safeGet(x)!==y&&safeSet(g,""),safeSet(x,y);const $=T.querySelector('input[name="weather-unit-radio"]:checked'),U=$?$.value:"imperial",m=P();safeSet(N,U),m!==U&&safeSet(g,""),T.classList.remove("show"),S()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(T),document.addEventListener("keydown",y=>{y.keyLine truncated
<circle cx="${n}" cy="${i}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/>
${F}
<line x1="${o}" y1="${l}" x2="${o+28*Math.cos(U*Math.PI/180)}" y2="${l+28*Math.sin(U*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/>
<line x1="${o}" y1="${l}" x2="${o+38*Math.cos($*Math.PI/180)}" y2="${l+38*Math.sin($*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/>
<line x1="${o}" y1="${l}" x2="${o+42*Math.cos(h*Math.PI/180)}" y2="${l+42*Math.sin(h*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/>
<circle cx="${o}" cy="${l}" r="3" fill="var(--fg)"/>
</svg>`,q=n.getHours()>=12?"PM":"AM";b.innerHTML=`<div class="analog-clock-wrap">${J}<div class="analog-info"><span class="analog-digital">${n.getHours()%12||12}:${String(s).padStart(2,"0")} ${q}</span><span class="analog-date-sm">${z(n)}</span></div></div>`,C="analog"}function m(){const n=new Date,e=n.getHours()%12||12,r=n.getMinutes(),s=n.getSeconds(),a="clock-widget"+(A!=="default"?" "+A:"");switch(x.className!==a&&(x.className=a),A){case"lcd":v(n);break;case"lcd-blue":v(n);break;case"lcd-amber":v(n);break;case"lcd-retro":v(n);break;case"lcd-taxi":v(n);break;case"flip":B(n);break;case"binary":O(n);break;case"analog":u(n,!1);break;case"roman":u(n,!0);break;default:P(n)}r===0&&s===0&&e!==D&&(D=e,w(e)),r!==0&&(D=-1)}function L(){clearTimeout(M);const n=document.hidden?6e4:1e3,e=n-Date.now()%n+25;M=setTimeout(()=>{m(),L()},e)}document.addEventListener("visibilitychange",()=>{f="",S(),m(),L()}),m(),L();const k=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let I='<div class="clock-style-grid">';k.forEach(n=>{I+=`<label class="clock-style-option">
<input type="radio" name="clock-style-radio" value="${n.id}">
<span class="clock-style-card"><span class="clock-style-icon">${n.icon}</span><span class="clock-style-label">${n.label}</span></span>
</label>`}),I+="</div>",injectModal("clock-settings-modal",`<div id="clock-settings-modal" class="weather-modal">
${_}
<line x1="${n}" y1="${i}" x2="${n+28*Math.cos(O*Math.PI/180)}" y2="${i+28*Math.sin(O*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/>
<line x1="${n}" y1="${i}" x2="${n+38*Math.cos(A*Math.PI/180)}" y2="${i+38*Math.sin(A*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/>
<line x1="${n}" y1="${i}" x2="${n+42*Math.cos(u*Math.PI/180)}" y2="${i+42*Math.sin(u*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/>
<circle cx="${n}" cy="${i}" r="3" fill="var(--fg)"/>
</svg>`,J=e.getHours()>=12?"PM":"AM";x.innerHTML=`<div class="analog-clock-wrap">${q}<div class="analog-info"><span class="analog-digital">${e.getHours()%12||12}:${String(o).padStart(2,"0")} ${J}</span><span class="analog-date-sm">${z(e)}</span></div></div>`,C="analog"}function v(){const e=new Date,s=e.getHours()%12||12,r=e.getMinutes(),o=e.getSeconds(),a="clock-widget"+(P!=="default"?" "+P:"");switch(w.className!==a&&(w.className=a),P){case"lcd":y(e);break;case"lcd-blue":y(e);break;case"lcd-amber":y(e);break;case"lcd-retro":y(e);break;case"lcd-taxi":y(e);break;case"flip":B(e);break;case"binary":U(e);break;case"analog":m(e,!1);break;case"roman":m(e,!0);break;default:D(e)}r===0&&o===0&&s!==M&&(M=s,k(s)),r!==0&&(M=-1)}function I(){clearTimeout(H);const e=document.hidden?6e4:1e3,s=e-Date.now()%e+25;H=setTimeout(()=>{v(),I()},s)}document.addEventListener("visibilitychange",()=>{h="",S(),v(),I()}),v(),I();const b=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let L='<div class="clock-style-grid">';b.forEach(e=>{L+=`<label class="clock-style-option">
<input type="radio" name="clock-style-radio" value="${e.id}">
<span class="clock-style-card"><span class="clock-style-icon">${e.icon}</span><span class="clock-style-label">${e.label}</span></span>
</label>`}),L+="</div>",injectModal("clock-settings-modal",`<div id="clock-settings-modal" class="weather-modal">
<div class="weather-modal-content" style="max-width: 420px;">
<h3>Clock Settings</h3>
<div style="margin-bottom: 16px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--fg);">Style</label>
${I}
${L}
</div>
<div style="margin-bottom: 16px; padding-top: 12px; border-top: 1px solid var(--border);">
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; color: var(--fg);">
@@ -2066,7 +2066,7 @@ This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST"
<button id="clock-settings-save">Save</button>
</div>
</div>
</div>`);const i=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),d=document.getElementById("clock-chime-volume"),y=document.getElementById("clock-volume-section");function p(){const n=safeGet("clock-style")||"default",e=i.querySelector(`input[value="${n}"]`);e&&(e.checked=!0),c.checked=safeGet("clock-chimes")==="true",d.value=safeGet("clock-chime-volume")||"50",y.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{y.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{p(),i.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const n=parseInt(d.value,10)/100,e=new Audio("/assets/sounds/church-bell.mp3");e.volume=n,e.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const n=i.querySelector('input[name="clock-style-radio"]:checked'),e=n?n.value:"default";safeSet("clock-style",e),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",d.value),A=e,f="",S(),m(),L(),i.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{i.classList.remove("show")}),wireModal(i),i?.querySelectorAll('input[name="clock-style-radio"]').forEach(n=>{n.addEventListener("change",()=>{A=n.value,f="",S(),m()})})})(),(function(){function x(g){const N=new Date(g.start),A=isNaN(N.getTime())?`invalid:${g.start==null?"null":String(g.start)}`:N.toISOString();return g.uid?`${g.uid}@${A}`:`${A}|${g.title||""}`}function b(){const g=new Map;return{size:()=>g.size,merge(N,A){if(A)for(const[D,R]of g){const f=new Date(R.start).getTime();f>=A.start.getTime()&&f<=A.end.getTime()&&g.delete(D)}for(const D of N&&Array.isArray(N.events)?N.events:[])g.set(x(D),D);return{events:[...g.values()].sort((D,R)=>new Date(D.start)-new Date(R.start))}}}}const j={eventKey:x,createCache:b};typeof module<"u"&&module.exports&&(module.exports=j),typeof window<"u"&&(window.CalendarCache=j)})(),(function(){const x=new ErrorHandler;injectModal("calendar-modal",`<div id="calendar-modal" class="weather-modal">
</div>`);const l=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),d=document.getElementById("clock-chime-volume"),f=document.getElementById("clock-volume-section");function p(){const e=safeGet("clock-style")||"default",s=l.querySelector(`input[value="${e}"]`);s&&(s.checked=!0),c.checked=safeGet("clock-chimes")==="true",d.value=safeGet("clock-chime-volume")||"50",f.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{f.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{p(),l.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const e=parseInt(d.value,10)/100,s=new Audio("/assets/sounds/church-bell.mp3");s.volume=e,s.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const e=l.querySelector('input[name="clock-style-radio"]:checked'),s=e?e.value:"default";safeSet("clock-style",s),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",d.value),P=s,h="",S(),v(),I(),l.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{l.classList.remove("show")}),wireModal(l),l?.querySelectorAll('input[name="clock-style-radio"]').forEach(e=>{e.addEventListener("change",()=>{P=e.value,h="",S(),v()})})})(),(function(){function w(g){const N=new Date(g.start),P=isNaN(N.getTime())?`invalid:${g.start==null?"null":String(g.start)}`:N.toISOString();return g.uid?`${g.uid}@${P}`:`${P}|${g.title||""}`}function x(){const g=new Map;return{size:()=>g.size,merge(N,P){if(P)for(const[M,R]of g){const h=new Date(R.start).getTime();h>=P.start.getTime()&&h<=P.end.getTime()&&g.delete(M)}for(const M of N&&Array.isArray(N.events)?N.events:[])g.set(w(M),M);return{events:[...g.values()].sort((M,R)=>new Date(M.start)-new Date(R.start))}}}}const j={eventKey:w,createCache:x};typeof module<"u"&&module.exports&&(module.exports=j),typeof window<"u"&&(window.CalendarCache=j)})(),(function(){const w=new ErrorHandler;injectModal("calendar-modal",`<div id="calendar-modal" class="weather-modal">
<div class="weather-modal-content cal-modal-content" role="dialog" aria-modal="true" aria-labelledby="calendar-modal-title">
<h3 id="calendar-modal-title">\u{1F4C5} Calendar</h3>
<div class="cal-monthbar">
@@ -2118,18 +2118,18 @@ This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST"
</details>
</div>
<div class="weather-modal-buttons"><button id="calendar-close">Close</button></div>
</div></div>`);function b(a){return String(a??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const j=()=>({icon:document.querySelector(".calendar-widget-icon"),text:document.querySelector(".calendar-widget-text")});function g(a,t){const o=new Date(a),l=new Date;l.setHours(0,0,0,0);const h=new Date(o);h.setHours(0,0,0,0);const $=Math.round((h-l)/864e5),U=$===0?"Today":$===1?"Tomorrow":o.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"}),F=t?"all-day":o.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return`${U} ${F}`}function N(a,t){return t?"all-day":new Date(a).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}function A(a){return`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`}const D=typeof window<"u"&&window.CalendarCache?window.CalendarCache.createCache():null;function R(a,t){return D?D.merge(a,t):a}let f=[];function C(a){const t=a||new Date,o=new Date(t.getFullYear(),t.getMonth()-1,1,0,0,0,0),l=new Date(t.getFullYear(),t.getMonth()+2,0,23,59,59,999);return{start:o,end:l}}function E(a){return f.some(t=>t.start.getTime()<=a.start.getTime()&&t.end.getTime()>=a.end.getTime())}function M(a){const t=f.filter(l=>l.end.getTime()>=a.start.getTime()&&l.start.getTime()<=a.end.getTime()),o=f.filter(l=>!t.includes(l));t.length&&(a={start:new Date(Math.min(a.start.getTime(),...t.map(l=>l.start.getTime()))),end:new Date(Math.max(a.end.getTime(),...t.map(l=>l.end.getTime())))}),f=o.concat([a]).sort((l,h)=>l.start-h.start)}let w=null,z={events:[]};async function S(a){const t=C(w);if(!a&&E(t))return z;const o=await secureFetch(`/api/v1/calendar/events?start=${t.start.toISOString()}&end=${t.end.toISOString()}`,{cache:"no-store"});if(o.status===404)return{notConfigured:!0};if(!o.ok)throw new Error(`Calendar API HTTP ${o.status}`);const l=await o.json();return z=R(l,t),M(t),z}function T(a){const t=j();if(!t.icon||!t.text)return;const o=B(a&&Array.isArray(a.events)?a.events:[]);if(!o.length){t.icon.textContent="\u{1F4C5}",t.text.innerHTML='<span class="cal-chip-muted">No upcoming appointments</span>';return}const l=o[0];t.icon.textContent=l.allDay?"\u{1F5D3}\uFE0F":"\u23F0",t.text.innerHTML=`<span class="cal-chip-title">${b(l.title||"Untitled")}</span><span class="cal-chip-when">\xB7 ${b(g(l.start,l.allDay))}</span>`}function P(a){const t={};for(const o of a&&Array.isArray(a.events)?a.events:[]){const l=A(new Date(o.start));(t[l]=t[l]||[]).push(o)}return t}function v(a){const t=document.getElementById("cal-grid"),o=document.getElementById("cal-month-label");if(!t||!o)return;w||(w=new Date,w.setDate(1));const l=w.getFullYear(),h=w.getMonth();o.textContent=w.toLocaleDateString(void 0,{month:"long",year:"numeric"});const $=P(a),U=A(new Date),F=new Date(l,h,1).getDay(),_=new Date(l,h+1,0).getDate();let J=["S","M","T","W","T","F","S"].map(q=>`<div class="cal-dow">${q}</div>`).join("");for(let q=0;q<F;q++)J+='<div class="cal-day cal-pad"></div>';for(let q=1;q<=_;q++){const K=`${l}-${String(h+1).padStart(2,"0")}-${String(q).padStart(2,"0")}`,Z=$[K]||[],ee=["cal-day"];K===U&&ee.push("cal-today"),Z.length&&ee.push("cal-has-events");const ne=Z.slice(0,3).map(V=>`<span class="cal-dot" title="${b(N(V.start,V.allDay))}"></span>`).join(""),oe=Z.map(V=>`${N(V.start,V.allDay)} \u2014 ${V.title||"Untitled"}`).join(`
`);J+=`<div class="${ee.join(" ")}" title="${b(oe||K)}"><span class="cal-daynum">${q}</span>${ne?`<span class="cal-dots">${ne}</span>`:""}</div>`}t.innerHTML=J}function B(a){const t=Date.now();return(Array.isArray(a)?a:[]).filter(o=>(o.end?new Date(o.end).getTime():new Date(o.start).getTime())>=t).sort((o,l)=>new Date(o.start)-new Date(l.start))}function H(a){const t=document.getElementById("calendar-upcoming-list");if(!t)return;const o=B(a&&Array.isArray(a.events)?a.events:[]);if(!o.length){t.innerHTML='<div class="cal-empty">No upcoming appointments.</div>';return}t.innerHTML=o.slice(0,12).map(l=>`<div class="cal-row">
<span class="cal-when">${b(g(l.start,l.allDay))}</span>
<span class="cal-evtitle">${b(l.title||"Untitled")}</span>
${l.location?`<span class="cal-loc">${b(l.location)}</span>`:""}
</div>`).join("")}async function O(){const a=document.getElementById("calendar-sources-list");if(!a)return;let t=[];try{const o=await secureFetch("/api/v1/calendar/sources",{cache:"no-store"});if(o.ok){const l=await o.json();t=l&&Array.isArray(l.sources)?l.sources:Array.isArray(l)?l:[]}}catch{}if(!t.length){a.innerHTML='<div class="cal-empty">No calendars connected. Deploy Radicale from the App Selector to auto-connect one, or add a CalDAV/ICS URL below.</div>';return}a.innerHTML=t.map(o=>`
</div></div>`);function x(a){return String(a??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const j=()=>({icon:document.querySelector(".calendar-widget-icon"),text:document.querySelector(".calendar-widget-text")});function g(a,t){const n=new Date(a),i=new Date;i.setHours(0,0,0,0);const u=new Date(n);u.setHours(0,0,0,0);const A=Math.round((u-i)/864e5),O=A===0?"Today":A===1?"Tomorrow":n.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"}),_=t?"all-day":n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return`${O} ${_}`}function N(a,t){return t?"all-day":new Date(a).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}function P(a){return`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`}const M=typeof window<"u"&&window.CalendarCache?window.CalendarCache.createCache():null;function R(a,t){return M?M.merge(a,t):a}let h=[];function C(a){const t=a||new Date,n=new Date(t.getFullYear(),t.getMonth()-1,1,0,0,0,0),i=new Date(t.getFullYear(),t.getMonth()+2,0,23,59,59,999);return{start:n,end:i}}function E(a){return h.some(t=>t.start.getTime()<=a.start.getTime()&&t.end.getTime()>=a.end.getTime())}function H(a){const t=h.filter(i=>i.end.getTime()>=a.start.getTime()&&i.start.getTime()<=a.end.getTime()),n=h.filter(i=>!t.includes(i));t.length&&(a={start:new Date(Math.min(a.start.getTime(),...t.map(i=>i.start.getTime()))),end:new Date(Math.max(a.end.getTime(),...t.map(i=>i.end.getTime())))}),h=n.concat([a]).sort((i,u)=>i.start-u.start)}let k=null,z={events:[]};async function S(a){const t=C(k);if(!a&&E(t))return z;const n=await secureFetch(`/api/v1/calendar/events?start=${t.start.toISOString()}&end=${t.end.toISOString()}`,{cache:"no-store"});if(n.status===404)return{notConfigured:!0};if(!n.ok)throw new Error(`Calendar API HTTP ${n.status}`);const i=await n.json();return z=R(i,t),H(t),z}function T(a){const t=j();if(!t.icon||!t.text)return;const n=B(a&&Array.isArray(a.events)?a.events:[]);if(!n.length){t.icon.textContent="\u{1F4C5}",t.text.innerHTML='<span class="cal-chip-muted">No upcoming appointments</span>';return}const i=n[0];t.icon.textContent=i.allDay?"\u{1F5D3}\uFE0F":"\u23F0",t.text.innerHTML=`<span class="cal-chip-title">${x(i.title||"Untitled")}</span><span class="cal-chip-when">\xB7 ${x(g(i.start,i.allDay))}</span>`}function D(a){const t={};for(const n of a&&Array.isArray(a.events)?a.events:[]){const i=P(new Date(n.start));(t[i]=t[i]||[]).push(n)}return t}function y(a){const t=document.getElementById("cal-grid"),n=document.getElementById("cal-month-label");if(!t||!n)return;k||(k=new Date,k.setDate(1));const i=k.getFullYear(),u=k.getMonth();n.textContent=k.toLocaleDateString(void 0,{month:"long",year:"numeric"});const A=D(a),O=P(new Date),_=new Date(i,u,1).getDay(),F=new Date(i,u+1,0).getDate();let q=["S","M","T","W","T","F","S"].map(J=>`<div class="cal-dow">${J}</div>`).join("");for(let J=0;J<_;J++)q+='<div class="cal-day cal-pad"></div>';for(let J=1;J<=F;J++){const G=`${i}-${String(u+1).padStart(2,"0")}-${String(J).padStart(2,"0")}`,Z=A[G]||[],ee=["cal-day"];G===O&&ee.push("cal-today"),Z.length&&ee.push("cal-has-events");const ne=Z.slice(0,3).map(K=>`<span class="cal-dot" title="${x(N(K.start,K.allDay))}"></span>`).join(""),oe=Z.map(K=>`${N(K.start,K.allDay)} \u2014 ${K.title||"Untitled"}`).join(`
`);q+=`<div class="${ee.join(" ")}" title="${x(oe||G)}"><span class="cal-daynum">${J}</span>${ne?`<span class="cal-dots">${ne}</span>`:""}</div>`}t.innerHTML=q}function B(a){const t=Date.now();return(Array.isArray(a)?a:[]).filter(n=>(n.end?new Date(n.end).getTime():new Date(n.start).getTime())>=t).sort((n,i)=>new Date(n.start)-new Date(i.start))}function $(a){const t=document.getElementById("calendar-upcoming-list");if(!t)return;const n=B(a&&Array.isArray(a.events)?a.events:[]);if(!n.length){t.innerHTML='<div class="cal-empty">No upcoming appointments.</div>';return}t.innerHTML=n.slice(0,12).map(i=>`<div class="cal-row">
<span class="cal-when">${x(g(i.start,i.allDay))}</span>
<span class="cal-evtitle">${x(i.title||"Untitled")}</span>
${i.location?`<span class="cal-loc">${x(i.location)}</span>`:""}
</div>`).join("")}async function U(){const a=document.getElementById("calendar-sources-list");if(!a)return;let t=[];try{const n=await secureFetch("/api/v1/calendar/sources",{cache:"no-store"});if(n.ok){const i=await n.json();t=i&&Array.isArray(i.sources)?i.sources:Array.isArray(i)?i:[]}}catch{}if(!t.length){a.innerHTML='<div class="cal-empty">No calendars connected. Deploy Radicale from the App Selector to auto-connect one, or add a CalDAV/ICS URL below.</div>';return}a.innerHTML=t.map(n=>`
<div class="cal-row cal-src-row">
<span class="cal-evtitle">${b(o.name||o.id)}
<span class="cal-loc">\xB7 ${b(o.type)}${o.autoProvisioned?" \xB7 auto-wired":""}</span></span>
<button class="cal-src-toggle cal-btn" data-id="${b(o.id)}" data-enabled="${o.enabled!==!1?"1":"0"}">${o.enabled!==!1?"\u2713 on":"off"}</button>
<button class="cal-src-del cal-btn cal-btn-danger" data-id="${b(o.id)}">remove</button>
</div>`).join(""),a.querySelectorAll(".cal-src-toggle").forEach(o=>o.addEventListener("click",async()=>{const l=o.dataset.id,h=o.dataset.enabled!=="1";o.disabled=!0;try{const $=await secureFetch(`/api/v1/calendar/sources/${encodeURIComponent(l)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:h})});if(!$.ok)throw new Error(`HTTP ${$.status}`);O(),m(!0)}catch($){showNotification(`Calendar source update failed: ${$.message}`,"error")}finally{o.disabled=!1}})),a.querySelectorAll(".cal-src-del").forEach(o=>o.addEventListener("click",async()=>{const l=o.dataset.id;o.disabled=!0;try{const h=await secureFetch(`/api/v1/calendar/sources/${encodeURIComponent(l)}`,{method:"DELETE"});if(!h.ok)throw new Error(`HTTP ${h.status}`);O(),m(!0)}catch(h){showNotification(`Calendar source removal failed: ${h.message}`,"error")}finally{o.disabled=!1}}))}let u=null;async function m(a){if(m._inFlight){a&&(m._pendingForce=!0);return}m._inFlight=!0;try{let t=await S(!!a);if(a&&w){const o=w;w=null;const l=await S(!0);w=o;const h=await S(!0);T(l),v(h),H(l),u=l,m._inFlight=!1;return}if(w){const o=w;w=null;const l=await S(!1);w=o;const h=await S(!1);T(l),v(h),H(l),u=l,m._inFlight=!1;return}u=t,T(t),document.getElementById("calendar-modal").classList.contains("show")&&(v(t),H(t))}catch(t){x.logError("calendar-widget",t);const o=j();o.text&&(o.text.innerHTML='<span class="cal-chip-muted">Calendar offline</span>')}finally{m._inFlight=!1,m._pendingForce&&(m._pendingForce=!1,m(!0))}}let L=null;function k(){L=document.activeElement,document.getElementById("calendar-modal").classList.add("show"),v(u||{events:[]}),H(u||{events:[]}),O(),m(),document.getElementById("calendar-close").focus()}function I(){document.getElementById("calendar-modal").classList.remove("show"),L&&typeof L.focus=="function"&&L.focus()}function i(){return{type:document.getElementById("cal-add-type").value,name:document.getElementById("cal-add-name").value.trim(),url:document.getElementById("cal-add-url").value.trim(),user:document.getElementById("cal-add-user").value.trim(),pass:document.getElementById("cal-add-pass").value}}function c(a){document.getElementById("cal-add-status").textContent=a}document.getElementById("cal-add-test").addEventListener("click",async()=>{const a=i();if(!a.url){c("Enter a URL first.");return}c("Testing\u2026");try{const o=await(await secureFetch("/api/v1/calendar/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:a.url,user:a.user,pass:a.pass})})).json(),l=o&&o.probe;l&&l.ok?c(`\u2713 Reachable (${l.server||"server"})${l.looksLikeCalendar?" \u2014 looks like a calendar":""}`):c(`\u2717 ${l&&l.error?l.error:"Not reachable"}`)}catch(t){c(`\u2717 ${t.message}`)}}),document.getElementById("cal-add-save").addEventListener("click",async()=>{const a=i();if(!a.name||!a.url){c("Name and URL are required.");return}try{const t=await secureFetch("/api/v1/calendar/sources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a.name,type:a.type,url:a.url,user:a.user,pass:a.pass})});if(!t.ok){const o=await t.json().catch(()=>({}));c(`\u2717 ${o.error||o.message||`HTTP ${t.status}`}`);return}c("Saved."),document.getElementById("cal-add-details").open=!1,["cal-add-name","cal-add-url","cal-add-user","cal-add-pass"].forEach(o=>{document.getElementById(o).value=""}),O(),m(!0)}catch(t){c(`\u2717 ${t.message}`)}});const d=document.getElementById("calendar-widget");d&&(d.addEventListener("click",k),d.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" "||a.key==="Spacebar")&&(a.preventDefault(),k())}));const y=document.getElementById("calendar-settings");y&&y.addEventListener("click",a=>{a.stopPropagation(),k()});const p=document.getElementById("calendar-modal");p&&(document.getElementById("calendar-close").addEventListener("click",I),p.addEventListener("click",a=>{a.target===p&&I()}),document.addEventListener("keydown",a=>{a.key==="Escape"&&p.classList.contains("show")&&I()}));async function n(a){w||(w=new Date,w.setDate(1)),w=new Date(w.getFullYear(),w.getMonth()+a,1);const t=await S(!1).catch(()=>u);v(t||{events:[]})}const e=document.getElementById("cal-prev");e&&e.addEventListener("click",()=>{n(-1)});const r=document.getElementById("cal-next");r&&r.addEventListener("click",()=>{n(1)}),window.refreshCalendarWidget=m;const s=typeof DC<"u"&&DC.POLL&&DC.POLL.CALENDAR||3e5;setInterval(()=>{document.hidden||m(!0)},s),document.addEventListener("visibilitychange",()=>{document.hidden||m(!0)}),setTimeout(m,400)})(),(function(){const x=new ErrorHandler;injectModal("ai-connect-modal",`<div id="ai-connect-modal" class="weather-modal">
<span class="cal-evtitle">${x(n.name||n.id)}
<span class="cal-loc">\xB7 ${x(n.type)}${n.autoProvisioned?" \xB7 auto-wired":""}</span></span>
<button class="cal-src-toggle cal-btn" data-id="${x(n.id)}" data-enabled="${n.enabled!==!1?"1":"0"}">${n.enabled!==!1?"\u2713 on":"off"}</button>
<button class="cal-src-del cal-btn cal-btn-danger" data-id="${x(n.id)}">remove</button>
</div>`).join(""),a.querySelectorAll(".cal-src-toggle").forEach(n=>n.addEventListener("click",async()=>{const i=n.dataset.id,u=n.dataset.enabled!=="1";n.disabled=!0;try{const A=await secureFetch(`/api/v1/calendar/sources/${encodeURIComponent(i)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:u})});if(!A.ok)throw new Error(`HTTP ${A.status}`);U(),v(!0)}catch(A){showNotification(`Calendar source update failed: ${A.message}`,"error")}finally{n.disabled=!1}})),a.querySelectorAll(".cal-src-del").forEach(n=>n.addEventListener("click",async()=>{const i=n.dataset.id;n.disabled=!0;try{const u=await secureFetch(`/api/v1/calendar/sources/${encodeURIComponent(i)}`,{method:"DELETE"});if(!u.ok)throw new Error(`HTTP ${u.status}`);U(),v(!0)}catch(u){showNotification(`Calendar source removal failed: ${u.message}`,"error")}finally{n.disabled=!1}}))}let m=null;async function v(a){if(v._inFlight){a&&(v._pendingForce=!0);return}v._inFlight=!0;try{let t=await S(!!a);if(a&&k){const n=k;k=null;const i=await S(!0);k=n;const u=await S(!0);T(i),y(u),$(i),m=i,v._inFlight=!1;return}if(k){const n=k;k=null;const i=await S(!1);k=n;const u=await S(!1);T(i),y(u),$(i),m=i,v._inFlight=!1;return}m=t,T(t),document.getElementById("calendar-modal").classList.contains("show")&&(y(t),$(t))}catch(t){w.logError("calendar-widget",t);const n=j();n.text&&(n.text.innerHTML='<span class="cal-chip-muted">Calendar offline</span>')}finally{v._inFlight=!1,v._pendingForce&&(v._pendingForce=!1,v(!0))}}let I=null;function b(){I=document.activeElement,document.getElementById("calendar-modal").classList.add("show"),y(m||{events:[]}),$(m||{events:[]}),U(),v(),document.getElementById("calendar-close").focus()}function L(){document.getElementById("calendar-modal").classList.remove("show"),I&&typeof I.focus=="function"&&I.focus()}function l(){return{type:document.getElementById("cal-add-type").value,name:document.getElementById("cal-add-name").value.trim(),url:document.getElementById("cal-add-url").value.trim(),user:document.getElementById("cal-add-user").value.trim(),pass:document.getElementById("cal-add-pass").value}}function c(a){document.getElementById("cal-add-status").textContent=a}document.getElementById("cal-add-test").addEventListener("click",async()=>{const a=l();if(!a.url){c("Enter a URL first.");return}c("Testing\u2026");try{const n=await(await secureFetch("/api/v1/calendar/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:a.url,user:a.user,pass:a.pass})})).json(),i=n&&n.probe;i&&i.ok?c(`\u2713 Reachable (${i.server||"server"})${i.looksLikeCalendar?" \u2014 looks like a calendar":""}`):c(`\u2717 ${i&&i.error?i.error:"Not reachable"}`)}catch(t){c(`\u2717 ${t.message}`)}}),document.getElementById("cal-add-save").addEventListener("click",async()=>{const a=l();if(!a.name||!a.url){c("Name and URL are required.");return}try{const t=await secureFetch("/api/v1/calendar/sources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a.name,type:a.type,url:a.url,user:a.user,pass:a.pass})});if(!t.ok){const n=await t.json().catch(()=>({}));c(`\u2717 ${n.error||n.message||`HTTP ${t.status}`}`);return}c("Saved."),document.getElementById("cal-add-details").open=!1,["cal-add-name","cal-add-url","cal-add-user","cal-add-pass"].forEach(n=>{document.getElementById(n).value=""}),U(),v(!0)}catch(t){c(`\u2717 ${t.message}`)}});const d=document.getElementById("calendar-widget");d&&(d.addEventListener("click",b),d.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" "||a.key==="Spacebar")&&(a.preventDefault(),b())}));const f=document.getElementById("calendar-settings");f&&f.addEventListener("click",a=>{a.stopPropagation(),b()});const p=document.getElementById("calendar-modal");p&&(document.getElementById("calendar-close").addEventListener("click",L),p.addEventListener("click",a=>{a.target===p&&L()}),document.addEventListener("keydown",a=>{a.key==="Escape"&&p.classList.contains("show")&&L()}));async function e(a){k||(k=new Date,k.setDate(1)),k=new Date(k.getFullYear(),k.getMonth()+a,1);const t=await S(!1).catch(()=>m);y(t||{events:[]})}const s=document.getElementById("cal-prev");s&&s.addEventListener("click",()=>{e(-1)});const r=document.getElementById("cal-next");r&&r.addEventListener("click",()=>{e(1)}),window.refreshCalendarWidget=v;const o=typeof DC<"u"&&DC.POLL&&DC.POLL.CALENDAR||3e5;setInterval(()=>{document.hidden||v(!0)},o),document.addEventListener("visibilitychange",()=>{document.hidden||v(!0)}),setTimeout(v,400)})(),(function(){const w=new ErrorHandler;injectModal("ai-connect-modal",`<div id="ai-connect-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width:560px;max-width:720px;">
<h3>\u{1F916} Connect your AI assistant</h3>
<div id="aiconn-intro" style="font-size:0.85rem;color:var(--muted);margin-bottom:12px;">
@@ -2183,12 +2183,12 @@ This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST"
<span id="aiconn-status" style="flex:1;font-size:0.78rem;color:var(--muted);align-self:center;"></span>
<button id="aiconn-close">Close</button>
</div>
</div></div>`);const b=f=>document.getElementById(f);let j=null;function g(f){b("aiconn-status").textContent=f}async function N(){try{const f=await secureFetch("/api/v1/mcp/info");if(!f.ok)throw new Error(`HTTP ${f.status}`);const C=await f.json();j=C,b("aiconn-endpoint").style.display="block",b("aiconn-endpoint-url").textContent=C.endpoint,b("aiconn-tools").textContent=`${C.toolCount} tools \xB7 MCP ${C.protocolVersion} \xB7 DashCaddy v${C.serverVersion}`}catch(f){x.log(f,"ai-connect-info"),g("MCP endpoint unavailable on this build.")}}async function A(){const f=b("aiconn-connections");try{const E=await(await secureFetch("/api/v1/mcp/connections")).json().catch(()=>({})),M=E&&Array.isArray(E.connections)?E.connections:[];if(!M.length){f.innerHTML='<div style="font-size:0.8rem;color:var(--muted);">No connections yet \u2014 choose an assistant above.</div>';return}f.innerHTML=M.map(w=>`
</div></div>`);const x=h=>document.getElementById(h);let j=null;function g(h){x("aiconn-status").textContent=h}async function N(){try{const h=await secureFetch("/api/v1/mcp/info");if(!h.ok)throw new Error(`HTTP ${h.status}`);const C=await h.json();j=C,x("aiconn-endpoint").style.display="block",x("aiconn-endpoint-url").textContent=C.endpoint,x("aiconn-tools").textContent=`${C.toolCount} tools \xB7 MCP ${C.protocolVersion} \xB7 DashCaddy v${C.serverVersion}`}catch(h){w.log(h,"ai-connect-info"),g("MCP endpoint unavailable on this build.")}}async function P(){const h=x("aiconn-connections");try{const E=await(await secureFetch("/api/v1/mcp/connections")).json().catch(()=>({})),H=E&&Array.isArray(E.connections)?E.connections:[];if(!H.length){h.innerHTML='<div style="font-size:0.8rem;color:var(--muted);">No connections yet \u2014 choose an assistant above.</div>';return}h.innerHTML=H.map(k=>`
<div style="display:flex;gap:8px;align-items:center;font-size:0.8rem;">
<span style="flex:1;">${escapeHtml(w.name)}
<span style="color:var(--muted);">\xB7 ${(w.scopes||[]).join(",")} \xB7 since ${escapeHtml((w.createdAt||"").slice(0,10))}${w.lastUsed?" \xB7 last used "+escapeHtml(String(w.lastUsed).slice(0,10)):""}</span></span>
<button class="aiconn-revoke" data-id="${escapeHtml(w.id)}" style="font-size:0.75rem;color:var(--err-fg);">Revoke</button>
</div>`).join(""),f.querySelectorAll(".aiconn-revoke").forEach(w=>w.addEventListener("click",async()=>{w.disabled=!0;try{const z=await secureFetch(`/api/v1/auth/keys/${encodeURIComponent(w.dataset.id)}`,{method:"DELETE"});if(z.ok)g("Connection revoked."),A();else{const S=await z.json().catch(()=>({}));g(S.error||"Revoke failed."),w.disabled=!1}}catch(z){g("Revoke failed: "+z.message),w.disabled=!1}}))}catch{f.innerHTML='<div style="font-size:0.8rem;color:var(--muted);">Could not load connections.</div>'}}async function D(f){g(`Creating ${f} connection\u2026`);try{const C=await secureFetch("/api/v1/mcp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client:f})}),E=await C.json().catch(()=>({}));if(!C.ok||!E.key){g(E.error||`Failed (HTTP ${C.status})`);return}b("aiconn-key").textContent=E.key;const M=E.httpConfig?JSON.stringify(E.httpConfig,null,2):"";b("aiconn-snippet").textContent=M||"(see note below)",b("aiconn-client-note").textContent=E.note||"",b("aiconn-config-title").textContent=f==="chatgpt"?"Access key (ChatGPT note below):":"Your access key (shown once):",b("aiconn-step-pick").style.display="none",b("aiconn-step-config").style.display="block",g(""),A()}catch(C){x.log(C,"ai-connect-create"),g("Failed: "+C.message)}}function R(f,C){navigator.clipboard&&navigator.clipboard.writeText?navigator.clipboard.writeText(f).then(()=>g(C)).catch(()=>g("Copy failed \u2014 select manually.")):g("Clipboard unavailable \u2014 select manually.")}b("ai-connect-btn").addEventListener("click",()=>{b("ai-connect-modal").style.display="flex",b("aiconn-step-pick").style.display="block",b("aiconn-step-config").style.display="none",g(""),N(),A()}),b("aiconn-close").addEventListener("click",()=>{b("ai-connect-modal").style.display="none"}),b("aiconn-back").addEventListener("click",()=>{b("aiconn-step-config").style.display="none",b("aiconn-step-pick").style.display="block"}),document.querySelectorAll(".aiconn-client-btn").forEach(f=>f.addEventListener("click",()=>D(f.dataset.client))),b("aiconn-copy-key").addEventListener("click",()=>R(b("aiconn-key").textContent,"Key copied \u2014 paste it into your client.")),b("aiconn-copy-snippet").addEventListener("click",()=>R(b("aiconn-snippet").textContent,"Config copied.")),b("aiconn-copy-endpoint").addEventListener("click",()=>R(j?j.endpoint:b("aiconn-endpoint-url").textContent,"Endpoint copied."))})(),(function(){async function x(){try{const R=await(await fetch("/api/v1/health-checks/status")).json();if(!R.success||!R.status)return;for(const[f,C]of Object.entries(R.status)){const E=document.getElementById("uptime-"+f),M=document.getElementById("uptime-bar-"+f);if(!E)continue;const w=C.uptime?.["24h"];if(w!=null){const z=w.toFixed(1);E.textContent=`${z}% uptime`,E.className="uptime-chip",w>=99.9?E.classList.add("excellent"):w>=99?E.classList.add("good"):w>=95?E.classList.add("degraded"):E.classList.add("poor"),M&&(M.style.width=z+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let b;try{b=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{b=new Set}let j=[];async function g(D){try{const f=await(await fetch("/api/v1/updates/available")).json();if(!f.success)return;document.querySelectorAll(".update-available-badge").forEach(E=>E.classList.remove("visible"));const C=f.updates||[];if(j=C,D&&C.length>0){const E=window._lastKnownUpdateCount||0;E>0&&C.length>E&&showNotification(`${C.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=C.length}if(!C.length)return;for(const E of C){const M=window.APPS||[];for(const w of M)if(w.containerId===E.containerId||w.id===E.containerName||w.name===E.containerName){if(b.has(w.id))break;const z=document.getElementById("update-badge-"+w.id),S=document.getElementById("update-btn-"+w.id);z&&(z.classList.add("visible"),z.title="Update available \u2014 click to open Update Management.",z.style.cursor="pointer",z.onclick=T=>{T.stopPropagation(),window.openUpdateModal&&window.openUpdateModal(w.id)}),S&&(S.style.background="#f97316",S.style.borderColor="#f97316",S.style.boxShadow="0 0 6px #f9731688",S.title="Update available \u2014 click to open Update Management.");break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function N(){setTimeout(()=>{x(),g()},5e3),setInterval(()=>{x(),g(!0)},6e4)}const A=window.refreshAll;A&&(window.refreshAll=async function(){try{await A(),setTimeout(x,1e3)}catch(D){console.warn("[Card Badges] Error in refreshAll hook:",D.message)}}),N()})(),(function(){var x=null,b=null,j={},g={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},N=[["bg","Background","base"],["card-base","Card","base"],["fg","Text","base"],["muted","Muted Text","base"],["border","Border","base"],["accent","Accent","accent"],["accent-strong","Accent Strong","accent"]Line truncated
<span style="flex:1;">${escapeHtml(k.name)}
<span style="color:var(--muted);">\xB7 ${(k.scopes||[]).join(",")} \xB7 since ${escapeHtml((k.createdAt||"").slice(0,10))}${k.lastUsed?" \xB7 last used "+escapeHtml(String(k.lastUsed).slice(0,10)):""}</span></span>
<button class="aiconn-revoke" data-id="${escapeHtml(k.id)}" style="font-size:0.75rem;color:var(--err-fg);">Revoke</button>
</div>`).join(""),h.querySelectorAll(".aiconn-revoke").forEach(k=>k.addEventListener("click",async()=>{k.disabled=!0;try{const z=await secureFetch(`/api/v1/auth/keys/${encodeURIComponent(k.dataset.id)}`,{method:"DELETE"});if(z.ok)g("Connection revoked."),P();else{const S=await z.json().catch(()=>({}));g(S.error||"Revoke failed."),k.disabled=!1}}catch(z){g("Revoke failed: "+z.message),k.disabled=!1}}))}catch{h.innerHTML='<div style="font-size:0.8rem;color:var(--muted);">Could not load connections.</div>'}}async function M(h){g(`Creating ${h} connection\u2026`);try{const C=await secureFetch("/api/v1/mcp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client:h})}),E=await C.json().catch(()=>({}));if(!C.ok||!E.key){g(E.error||`Failed (HTTP ${C.status})`);return}x("aiconn-key").textContent=E.key;const H=E.httpConfig?JSON.stringify(E.httpConfig,null,2):"";x("aiconn-snippet").textContent=H||"(see note below)",x("aiconn-client-note").textContent=E.note||"",x("aiconn-config-title").textContent=h==="chatgpt"?"Access key (ChatGPT note below):":"Your access key (shown once):",x("aiconn-step-pick").style.display="none",x("aiconn-step-config").style.display="block",g(""),P()}catch(C){w.log(C,"ai-connect-create"),g("Failed: "+C.message)}}function R(h,C){navigator.clipboard&&navigator.clipboard.writeText?navigator.clipboard.writeText(h).then(()=>g(C)).catch(()=>g("Copy failed \u2014 select manually.")):g("Clipboard unavailable \u2014 select manually.")}x("ai-connect-btn").addEventListener("click",()=>{x("ai-connect-modal").style.display="flex",x("aiconn-step-pick").style.display="block",x("aiconn-step-config").style.display="none",g(""),N(),P()}),x("aiconn-close").addEventListener("click",()=>{x("ai-connect-modal").style.display="none"}),x("aiconn-back").addEventListener("click",()=>{x("aiconn-step-config").style.display="none",x("aiconn-step-pick").style.display="block"}),document.querySelectorAll(".aiconn-client-btn").forEach(h=>h.addEventListener("click",()=>M(h.dataset.client))),x("aiconn-copy-key").addEventListener("click",()=>R(x("aiconn-key").textContent,"Key copied \u2014 paste it into your client.")),x("aiconn-copy-snippet").addEventListener("click",()=>R(x("aiconn-snippet").textContent,"Config copied.")),x("aiconn-copy-endpoint").addEventListener("click",()=>R(j?j.endpoint:x("aiconn-endpoint-url").textContent,"Endpoint copied."))})(),(function(){async function w(){try{const R=await(await fetch("/api/v1/health-checks/status")).json();if(!R.success||!R.status)return;for(const[h,C]of Object.entries(R.status)){const E=document.getElementById("uptime-"+h),H=document.getElementById("uptime-bar-"+h);if(!E)continue;const k=C.uptime?.["24h"];if(k!=null){const z=k.toFixed(1);E.textContent=`${z}% uptime`,E.className="uptime-chip",k>=99.9?E.classList.add("excellent"):k>=99?E.classList.add("good"):k>=95?E.classList.add("degraded"):E.classList.add("poor"),H&&(H.style.width=z+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let x;try{x=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{x=new Set}let j=[];async function g(M){try{const h=await(await fetch("/api/v1/updates/available")).json();if(!h.success)return;document.querySelectorAll(".update-available-badge").forEach(E=>E.classList.remove("visible"));const C=h.updates||[];if(j=C,M&&C.length>0){const E=window._lastKnownUpdateCount||0;E>0&&C.length>E&&showNotification(`${C.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=C.length}if(!C.length)return;for(const E of C){const H=window.APPS||[];for(const k of H)if(k.containerId===E.containerId||k.id===E.containerName||k.name===E.containerName){if(x.has(k.id))break;const z=document.getElementById("update-badge-"+k.id),S=document.getElementById("update-btn-"+k.id);z&&(z.classList.add("visible"),z.title="Update available \u2014 click to open Update Management.",z.style.cursor="pointer",z.onclick=T=>{T.stopPropagation(),window.openUpdateModal&&window.openUpdateModal(k.id)}),S&&(S.style.background="#f97316",S.style.borderColor="#f97316",S.style.boxShadow="0 0 6px #f9731688",S.title="Update available \u2014 click to open Update Management.");break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function N(){setTimeout(()=>{w(),g()},5e3),setInterval(()=>{w(),g(!0)},6e4)}const P=window.refreshAll;P&&(window.refreshAll=async function(){try{await P(),setTimeout(w,1e3)}catch(M){console.warn("[Card Badges] Error in refreshAll hook:",M.message)}}),N()})(),(function(){var w=null,x=null,j={},g={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},N=[["bg","Background","base"],["card-base","Card","base"],["fg","Text","base"],["muted","Muted Text","base"],["border","Border","base"],["accent","Accent","accent"],["accent-strong","Accent Strong","accent"]Line truncated
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3>DashCaddy License</h3>
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
@@ -2225,16 +2225,16 @@ This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST"
<button id="license-activate" class="btn-accent">Activate</button>
</div>
</div>
</div>`);const x=document.getElementById("license-modal"),b=document.getElementById("license-code-input"),j=document.getElementById("license-activate"),g=document.getElementById("license-deactivate"),N=document.getElementById("license-error"),A=document.getElementById("license-success"),D=document.getElementById("license-badge-icon"),R=document.getElementById("license-badge-text"),f=document.getElementById("license-badge"),C=document.getElementById("license-details"),E=document.getElementById("license-feature-list"),M=document.getElementById("license-activate-section");let w=null;function z(){N.style.display="none",A.style.display="none"}function S(L){z(),N.textContent=L,N.style.display="block"}function T(L){z(),A.textContent=L,A.style.display="block"}function P(L){if(w=L,L.active){f.style.background="rgba(46,204,113,0.15)",f.style.color="var(--ok-fg)",D.textContent="\u2605",R.textContent="Premium Active";const i=L.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(L.expiresAt).toLocaleDateString()}</strong> (${L.daysRemaining} days remaining)</div>`;C.innerHTML=`
<div>Code: <code style="font-family: monospace;">${L.code||"***"}</code></div>
${i}
`,M.style.display="none",j.style.display="none",g.style.display=""}else f.style.background="rgba(149,165,166,0.15)",f.style.color="var(--muted)",D.textContent="\u2606",R.textContent=L.expired?"License Expired":"Free Tier",C.innerHTML=L.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",M.style.display="",j.style.display="",g.style.display="none";const k=L.premiumFeatures||{},I=new Set(L.features||[]);E.innerHTML=Object.entries(k).map(([i,c])=>`<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${I.has(i)?"\u2705":"\u{1F512}"}</span>
</div>`);const w=document.getElementById("license-modal"),x=document.getElementById("license-code-input"),j=document.getElementById("license-activate"),g=document.getElementById("license-deactivate"),N=document.getElementById("license-error"),P=document.getElementById("license-success"),M=document.getElementById("license-badge-icon"),R=document.getElementById("license-badge-text"),h=document.getElementById("license-badge"),C=document.getElementById("license-details"),E=document.getElementById("license-feature-list"),H=document.getElementById("license-activate-section");let k=null;function z(){N.style.display="none",P.style.display="none"}function S(I){z(),N.textContent=I,N.style.display="block"}function T(I){z(),P.textContent=I,P.style.display="block"}function D(I){if(k=I,I.active){h.style.background="rgba(46,204,113,0.15)",h.style.color="var(--ok-fg)",M.textContent="\u2605",R.textContent="Premium Active";const l=I.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(I.expiresAt).toLocaleDateString()}</strong> (${I.daysRemaining} days remaining)</div>`;C.innerHTML=`
<div>Code: <code style="font-family: monospace;">${I.code||"***"}</code></div>
${l}
`,H.style.display="none",j.style.display="none",g.style.display=""}else h.style.background="rgba(149,165,166,0.15)",h.style.color="var(--muted)",M.textContent="\u2606",R.textContent=I.expired?"License Expired":"Free Tier",C.innerHTML=I.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",H.style.display="",j.style.display="",g.style.display="none";const b=I.premiumFeatures||{},L=new Set(I.features||[]);E.innerHTML=Object.entries(b).map(([l,c])=>`<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${L.has(l)?"\u2705":"\u{1F512}"}</span>
<div>
<div style="font-weight: 600; font-size: 0.9rem;">${c.name}</div>
<div style="font-size: 0.78rem; color: var(--muted);">${c.description}</div>
</div>
</div>`).join("")}async function v(){try{const k=await(await fetch("/api/v1/license/status")).json();k.success&&(P(k.license),O(k.license))}catch(L){console.warn("Failed to load license status:",L.message)}}async function B(){const L=b.value.trim();if(!L){S("Please enter a license code.");return}z(),j.disabled=!0,j.textContent="Activating...";try{const I=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:L})})).json();I.success?(T(I.message),b.value="",P(I.license),showNotification("License activated! Premium features unlocked.","success",5e3),O(I.license)):S(I.error||"Activation failed")}catch(k){S("Network error: "+k.message)}finally{j.disabled=!1,j.textContent="Activate"}}async function H(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){g.disabled=!0,g.textContent="Deactivating...";try{const k=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();k.success?(T(k.message),await v(),showNotification("License deactivated.","info",3e3),O({active:!1})):S(k.error||"Deactivation failed")}catch(L){S("Network error: "+L.message)}finally{g.disabled=!1,g.textContent="Deactivate"}}}function O(L){const k=document.getElementById("license-status-topbar"),I=document.getElementById("license-topbar-icon"),i=document.getElementById("license-topbar-text"),c=document.getElementById("license-topbar-time");if(k)if(k.className="license-status-topbar "+(L.active?"premium":"free"),L.active)if(I.textContent="\u2605",i.textContent="PREMIUM",L.lifetime)c.textContent="\xB7 LIFETIME";else{const d=L.daysRemaining;c.textContent=d!=null?"\xB7 "+d+"d remaining":""}else I.textContent="\u2606",i.textContent=L.expired?"EXPIRED":"FREE TIER",c.textContent=""}function u(){z(),v(),x.classList.add("show")}b.addEventListener("input",function(){let L=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(L.length>this._prevLength&&(L=L.replace(/-/g,""),L.length>2&&!L.startsWith("DC")&&(L="DC"+L),L.startsWith("DC")&&L.length>2)){const k=["DC"],I=L.substring(2);for(let i=0;i<I.length;i+=5)k.push(I.substring(i,i+5));L=k.join("-")}this._prevLength=L.length,this.value=L}),j.addEventListener("click",B),g.addEventListener("click",H),b.addEventListener("keydown",L=>{L.key==="Enter"&&B()}),wireModal(x,document.getElementById("license-cancel"));const m=document.getElementById("license-status-topbar");m&&m.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=u,window.checkPremiumFeature=async function(L){try{return(await(await fetch(`/api/v1/license/feature/${L}`)).json()).available}catch{return!1}},v().then(L=>{w&&O(w)})})(),(function(){"use strict";if(window.__dc_058_share_modal_loaded)return;window.__dc_058_share_modal_loaded=!0;const x=[{ms:3600*1e3,label:"1 hour"},{ms:1440*60*1e3,label:"24 hours"},{ms:10080*60*1e3,label:"7 days"}];injectModal("share-modal",`
</div>`).join("")}async function y(){try{const b=await(await fetch("/api/v1/license/status")).json();b.success&&(D(b.license),U(b.license))}catch(I){console.warn("Failed to load license status:",I.message)}}async function B(){const I=x.value.trim();if(!I){S("Please enter a license code.");return}z(),j.disabled=!0,j.textContent="Activating...";try{const L=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:I})})).json();L.success?(T(L.message),x.value="",D(L.license),showNotification("License activated! Premium features unlocked.","success",5e3),U(L.license)):S(L.error||"Activation failed")}catch(b){S("Network error: "+b.message)}finally{j.disabled=!1,j.textContent="Activate"}}async function $(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){g.disabled=!0,g.textContent="Deactivating...";try{const b=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();b.success?(T(b.message),await y(),showNotification("License deactivated.","info",3e3),U({active:!1})):S(b.error||"Deactivation failed")}catch(I){S("Network error: "+I.message)}finally{g.disabled=!1,g.textContent="Deactivate"}}}function U(I){const b=document.getElementById("license-status-topbar"),L=document.getElementById("license-topbar-icon"),l=document.getElementById("license-topbar-text"),c=document.getElementById("license-topbar-time");if(b)if(b.className="license-status-topbar "+(I.active?"premium":"free"),I.active)if(L.textContent="\u2605",l.textContent="PREMIUM",I.lifetime)c.textContent="\xB7 LIFETIME";else{const d=I.daysRemaining;c.textContent=d!=null?"\xB7 "+d+"d remaining":""}else L.textContent="\u2606",l.textContent=I.expired?"EXPIRED":"FREE TIER",c.textContent=""}function m(){z(),y(),w.classList.add("show")}x.addEventListener("input",function(){let I=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(I.length>this._prevLength&&(I=I.replace(/-/g,""),I.length>2&&!I.startsWith("DC")&&(I="DC"+I),I.startsWith("DC")&&I.length>2)){const b=["DC"],L=I.substring(2);for(let l=0;l<L.length;l+=5)b.push(L.substring(l,l+5));I=b.join("-")}this._prevLength=I.length,this.value=I}),j.addEventListener("click",B),g.addEventListener("click",$),x.addEventListener("keydown",I=>{I.key==="Enter"&&B()}),wireModal(w,document.getElementById("license-cancel"));const v=document.getElementById("license-status-topbar");v&&v.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=m,window.checkPremiumFeature=async function(I){try{return(await(await fetch(`/api/v1/license/feature/${I}`)).json()).available}catch{return!1}},y().then(I=>{k&&U(k)})})(),(function(){"use strict";if(window.__dc_058_share_modal_loaded)return;window.__dc_058_share_modal_loaded=!0;const w=[{ms:3600*1e3,label:"1 hour"},{ms:1440*60*1e3,label:"24 hours"},{ms:10080*60*1e3,label:"7 days"}];injectModal("share-modal",`
<div id="share-modal" class="weather-modal" role="dialog" aria-labelledby="share-modal-title">
<div class="weather-modal-content" style="min-width: 460px; max-width: 580px;">
<h3 id="share-modal-title">Share <span id="share-modal-service-name">\u2026</span></h3>
@@ -2256,7 +2256,7 @@ This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST"
<div class="share-tab-panel" data-panel="public">
<label class="form-label-bold" for="share-public-ttl">Link duration:</label>
<select id="share-public-ttl" style="width: 100%; padding: 8px 10px; margin: 6px 0 12px; background: var(--input-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;">
${x.map(n=>`<option value="${n.ms}">${n.label}</option>`).join("")}
${w.map(e=>`<option value="${e.ms}">${e.label}</option>`).join("")}
</select>
<button id="share-public-create" class="btn-accent" type="button"
style="width: 100%; padding: 10px; background: var(--accent); color: #04141f; border: 0; border-radius: 4px; font-weight: 600; cursor: pointer;">
@@ -2303,17 +2303,17 @@ This can take ~30-60s\u2026`);try{const{body:B}=await N("/deploy",{method:"POST"
</div>
</div>
</div>
`);const b=document.getElementById("share-modal"),j=document.getElementById("share-modal-service-name"),g=document.getElementById("share-issued"),N=document.getElementById("share-issued-url"),A=document.getElementById("share-issued-copy"),D=document.getElementById("share-issued-meta"),R=document.getElementById("share-error"),f=document.getElementById("share-success"),C=document.getElementById("share-outstanding-list"),E=document.getElementById("share-cancel"),M=document.getElementById("share-public-create"),w=document.getElementById("share-ts-create"),z=document.getElementById("share-ts-email"),S=document.getElementById("share-public-ttl");let T=null,P="public";function v(){R.style.display="none",f.style.display="none",g.style.display="none"}function B(n){f.style.display="none",g.style.display="none",R.textContent=n,R.style.display="block"}function H(n){R.style.display="none",f.textContent=n,f.style.display="block"}function O(){return window.location.origin}function u(n){return n.startsWith("http")?n:O()+n}function m(n){if(!n)return"";const e=new Date(n);return Number.isNaN(e.getTime())?"":e.toLocaleString()}function L(n){if(n<=0)return"expired";const e=Math.floor(n/36e5);if(e>=24)return`${Math.floor(e/24)}d ${e%24}h left`;const r=Math.floor(n%36e5/6e4);return`${e}h ${r}m left`}function k(n){P=n,v(),b.querySelectorAll(".share-tab").forEach(e=>{const r=e.dataset.tab===n;e.classList.toggle("active",r),e.style.borderBottomColor=r?"var(--accent)":"transparent",e.style.color=r?"var(--fg)":"var(--muted)",e.style.fontWeight=r?"600":"400"}),b.querySelectorAll(".share-tab-panel").forEach(e=>{e.style.display=e.dataset.panel===n?"":"none"})}async function I(){C.innerHTML='<span style="color: var(--muted);">Loading\u2026</span>';try{const n=await fetch("/api/v1/share",{credentials:"same-origin"});if(!n.ok){C.innerHTML='<span style="color: var(--muted);">No shares listed.</span>';return}const e=await n.json(),s=(e&&e.data||[]).filter(a=>a.serviceId===T.id);if(s.length===0){C.innerHTML='<span style="color: var(--muted);">No outstanding shares for this service.</span>';return}C.innerHTML=s.map(a=>{const t=a.expiresAt?L(new Date(a.expiresAt).getTime()-Date.now()):"";return`
`);const x=document.getElementById("share-modal"),j=document.getElementById("share-modal-service-name"),g=document.getElementById("share-issued"),N=document.getElementById("share-issued-url"),P=document.getElementById("share-issued-copy"),M=document.getElementById("share-issued-meta"),R=document.getElementById("share-error"),h=document.getElementById("share-success"),C=document.getElementById("share-outstanding-list"),E=document.getElementById("share-cancel"),H=document.getElementById("share-public-create"),k=document.getElementById("share-ts-create"),z=document.getElementById("share-ts-email"),S=document.getElementById("share-public-ttl");let T=null,D="public";function y(){R.style.display="none",h.style.display="none",g.style.display="none"}function B(e){h.style.display="none",g.style.display="none",R.textContent=e,R.style.display="block"}function $(e){R.style.display="none",h.textContent=e,h.style.display="block"}function U(){return window.location.origin}function m(e){return e.startsWith("http")?e:U()+e}function v(e){if(!e)return"";const s=new Date(e);return Number.isNaN(s.getTime())?"":s.toLocaleString()}function I(e){if(e<=0)return"expired";const s=Math.floor(e/36e5);if(s>=24)return`${Math.floor(s/24)}d ${s%24}h left`;const r=Math.floor(e%36e5/6e4);return`${s}h ${r}m left`}function b(e){D=e,y(),x.querySelectorAll(".share-tab").forEach(s=>{const r=s.dataset.tab===e;s.classList.toggle("active",r),s.style.borderBottomColor=r?"var(--accent)":"transparent",s.style.color=r?"var(--fg)":"var(--muted)",s.style.fontWeight=r?"600":"400"}),x.querySelectorAll(".share-tab-panel").forEach(s=>{s.style.display=s.dataset.panel===e?"":"none"})}async function L(){C.innerHTML='<span style="color: var(--muted);">Loading\u2026</span>';try{const e=await fetch("/api/v1/share",{credentials:"same-origin"});if(!e.ok){C.innerHTML='<span style="color: var(--muted);">No shares listed.</span>';return}const s=await e.json(),o=(s&&s.data||[]).filter(a=>a.serviceId===T.id);if(o.length===0){C.innerHTML='<span style="color: var(--muted);">No outstanding shares for this service.</span>';return}C.innerHTML=o.map(a=>{const t=a.expiresAt?I(new Date(a.expiresAt).getTime()-Date.now()):"";return`
<div class="share-row" data-share-id="${escapeHtml(a.id)}"
style="display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px dashed var(--border);">
<span style="flex: 1;">
<strong>${a.kind==="tailscale"?"Tailscale":"Public"}</strong>
<span style="color: var(--muted);"> \xB7 expires ${escapeHtml(m(a.expiresAt))} (${t})</span>
<span style="color: var(--muted);"> \xB7 expires ${escapeHtml(v(a.expiresAt))} (${t})</span>
</span>
<button class="share-revoke" data-share-id="${escapeHtml(a.id)}" type="button"
style="padding: 4px 10px; background: transparent; color: var(--bad-fg); border: 1px solid var(--bad-fg); border-radius: 4px; cursor: pointer; font-size: 0.8rem;">
Revoke
</button>
</div>
`}).join(""),C.querySelectorAll(".share-revoke").forEach(a=>{a.addEventListener("click",()=>i(a.dataset.shareId))})}catch{C.innerHTML='<span style="color: var(--muted);">Could not load outstanding shares.</span>'}}async function i(n){try{const e=await fetch(`/api/v1/share/${encodeURIComponent(n)}`,{method:"DELETE",credentials:"same-origin"});if(!e.ok){const r=await e.json().catch(()=>({}));B(r&&r.error||`Revoke failed (HTTP ${e.status}).`);return}H("Share revoked."),I()}catch{B("Network error while revoking.")}}async function c(){if(!T)return;v(),M.disabled=!0;const n=M.textContent;M.textContent="Creating\u2026";try{const e=parseInt(S.value,10),r=await fetch("/api/v1/share",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:T.id,ttlMs:e})}),s=await r.json().catch(()=>({}));if(!r.ok||!s.success){y(r.status,s);return}const a=s.data.urlPath;N.value=u(a),D.textContent=`Public link \xB7 expires ${m(s.data.expiresAt)}`,g.style.display="block",H("Share link created."),I()}catch{B("Network error while creating share.")}finally{M.disabled=!1,M.textContent=n}}async function d(){if(!T)return;const n=(z.value||"").trim();if(!n||!n.includes("@")){B("A valid recipient email is required.");return}v(),w.disabled=!0;const e=w.textContent;w.textContent="Creating\u2026";try{const r=await fetch("/api/v1/share/tailscale",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:T.id,email:n})}),s=await r.json().catch(()=>({}));if(!r.ok||!s.success){y(r.status,s);return}const a=s.data&&s.data.urlPath;a?(N.value=u(a),D.textContent=`Tailscale invite \xB7 emailed to ${n} (or use this URL manually if delivery failed).`):(N.value="",D.textContent=`Tailscale invite sent to ${n}.`),g.style.display="block",H("Tailscale invite created."),z.value="",I()}catch{B("Network error while creating Tailscale invite.")}finally{w.disabled=!1,w.textContent=e}}function y(n,e){const r=e&&e.error||"";if(n===402){B("Share is a Pro feature. Activate a license to unlock.");return}if(n===400&&/tailscale/i.test(r)){B("Tailscale is not configured on this host. Set up Tailscale in the dashboard first.");return}if(n===403){B("You do not have permission to share services.");return}if(n===404){B("Service not found. It may have been deleted.");return}B(r||`Request failed (HTTP ${n}).`)}function p(n){!n||!n.id||(T={id:n.id,name:n.name||n.id},j.textContent=T.name,v(),k("public"),z.value="",S.value=String(x[1].ms),b.classList.add("show"),I())}b.querySelectorAll(".share-tab").forEach(n=>{n.addEventListener("click",()=>k(n.dataset.tab))}),M.addEventListener("click",c),w.addEventListener("click",d),E.addEventListener("click",()=>b.classList.remove("show")),wireModal(b,E),A.addEventListener("click",async()=>{const n=N.value;if(n)try{navigator.clipboard&&navigator.clipboard.writeText?await navigator.clipboard.writeText(n):(N.select(),document.execCommand("copy"));const e=A.textContent;A.textContent="Copied!",setTimeout(()=>{A.textContent=e},1200)}catch{B("Could not copy to clipboard. Select the URL manually.")}}),window.openShareModal=p})();
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLy8gTG9nbyBDdXN0b21pemF0aW9uIFN5c3RlbVxuKGZ1bmN0aW9uKCkge1xuICAvLyBJbmplY3QgbW9kYWwgSFRNTFxuICBpbmplY3RNb2RhbCgnbG9nby1tb2RhbCcsIGA8ZGl2IGlkPVwibG9nby1tb2RhbFwiIGNsYXNzPVwid2VhdGhlci1tb2RhbFwiPlxuICAgIDxkaXYgY2xhc3M9XCJ3ZWF0aGVyLW1vZGFsLWNvbnRlbnRcIiBzdHlsZT1cIm1pbi13aWR0aDogNDAwcHg7IG1heC13aWR0aDogNTIwcHg7XCI+XG4gICAgICA8aDM+RGFzaGJvYXJkIFNldHRpbmdzPC9oMz5cbiAgICAgIDxwIHN0eWxlPVwiZm9udC1zaXplOiAwLjg1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW46IDAgMCAxNnB4O1wiPlxuICAgICAgICBDdXN0b21pemUgeW91ciBkYXNoYm9hcmQncyBhcHBlYXJhbmNlIGFuZCBzeXN0ZW0gcHJlZmVyZW5jZXMuXG4gICAgICA8L3A+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgZm9yPVwiZGFzaGJvYXJkLXRpdGxlXCIgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5EYXNoYm9hcmQgVGl0bGU6PC9sYWJlbD5cbiAgICAgICAgPGlucHV0IHR5cGU9XCJ0ZXh0XCIgaWQ9XCJkYXNoYm9hcmQtdGl0bGVcIiBwbGFjZWhvbGRlcj1cIkRhc2hDYWRkeVwiIG1heGxlbmd0aD1cIjUwXCIgc3R5bGU9XCJ3aWR0aDogMTAwJTsgcGFkZGluZzogMTBweCAxMnB4OyBib3JkZXI6IDFweCBzb2xpZCB2YXIoLS1ib3JkZXIpOyBib3JkZXItcmFkaXVzOiA0cHg7IGJhY2tncm91bmQ6IHZhcigtLWNhcmQtYmcpOyBjb2xvcjogdmFyKC0tZmcpOyBmb250LXNpemU6IDFyZW07XCIgLz5cbiAgICAgICAgPHAgY2xhc3M9XCJ0aW55LWhpbnRcIj5TaG93biBpbiBicm93c2VyIHRhYiBhbmQgaGVhZGVyIChtYXggNTAgY2hhcmFjdGVycyk8L3A+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGhyIGNsYXNzPVwiaHItZGl2aWRlclwiIC8+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5Mb2dvOjwvbGFiZWw+XG4gICAgICAgIDxwIGNsYXNzPVwidGlueS1oaW50XCIgc3R5bGU9XCJtYXJnaW4tdG9wOiAycHg7XCI+U2VwYXJhdGUgbG9nb3MgZm9yIGRhcmsgYW5kIGxpZ2h0IHRoZW1lcywgb3IgdXNlIHRoZSBzYW1lIGZvciBib3RoLjwvcD5cbiAgICAgIDwvZGl2PlxuXG4gICAgICA8ZGl2IHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4OyBtYXJnaW4tYm90dG9tOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogIzFhMWEyZTsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgyNTUsMjU1LDI1NSwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1kYXJrXCIgc3JjPVwiL2Fzc2V0cy9kYXNoY2FkZHktbG9nby1kYXJrLnBuZ1wiIGFsdD1cIkRhcmsgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjOWFhNmJmOyBtYXJnaW4tdG9wOiA2cHg7XCI+RGFyayB0aGVtZXM8L3A+XG4gICAgICAgIDwvZGl2PlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogI2YwZjBmMDsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgwLDAsMCwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1saWdodFwiIHNyYz1cIi9hc3NldHMvZGFzaGNhZGR5LWxvZ28tbGlnaHQucG5nXCIgYWx0PVwiTGlnaHQgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjNWY2YjdhOyBtYXJnaW4tdG9wOiA2cHg7XCI+TGlnaHQgdGhlbWVzPC9wPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIDwvZGl2PlxuICAgICAgPHAgaWQ9XCJsb2dvLXN0YXR1c1wiIHN0eWxlPVwiZm9udC1zaXplOiAwLjc1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW4tYm90dG9tOiAxMnB4OyB0ZXh0LWFsaWduOiBjZW50ZXI7XCI+VXNpbmcgZGVmYXVsdCBsb2dvczwvcD5cblxuICAgICAgPGRpdiBjbGFzcz1cIm1iLTE2XCI+XG4gICAgICAgIDxsYWJlbCBzdHlsZT1cImRpc3BsYXk6IGZsZXg7IGFsaWduLWl0ZW1zOiBjZW50ZXI7IGdhcDogOHB4OyBmb250LXNpemU6IDAuODJyZW07IGN1cnNvcjogcG9pbnRlcjsgdXNlci1zZWxlY3Q6IG5vbmU7XCI+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJjaGVja2JveFwiIGlkPVwibG9nby1zYW1lLWJvdGhcIiAvPiBVc2Ugc2FtZSBsb2dvIGZvciBib3RoXG4gICAgICAgIDwvbGFiZWw+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tZHVhbC11cGxvYWRzXCIgY2xhc3M9XCJtYi0xNlwiIHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTtcIj5cbiAgICAgICAgICA8bGFiZWwgZm9yPVwibG9nby11cGxvYWQtZGFya1wiIHN0eWxlPVwiZGlzcGxheTogYmxvY2s7IG1hcmdpbi1ib3R0b206IDZweDsgZm9udC1zaXplOiAwLjhyZW07XCI+RGFyayB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1kYXJrXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiBzdHlsZT1cImZvbnQtc2l6ZTogMC43NXJlbTtcIiAvPlxuICAgICAgICA8L2Rpdj5cbiAgICAgICAgPGRpdiBzdHlsZT1cImZsZXg6IDE7XCI+XG4gICAgICAgICAgPGxhYmVsIGZvcj1cImxvZ28tdXBsb2FkLWxpZ2h0XCIgc3R5bGU9XCJkaXNwbGF5OiBibG9jazsgbWFyZ2luLWJvdHRvbTogNnB4OyBmb250LXNpemU6IDAuOHJlbTtcIj5MaWdodCB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1saWdodFwiIGFjY2VwdD1cImltYWdlLypcIiBjbGFzcz1cImlucHV0LWNhcmQtYWx0XCIgc3R5bGU9XCJmb250LXNpemU6IDAuNzVyZW07XCIgLz5cbiAgICAgICAgPC9kaXY+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tc2luZ2xlLXVwbG9hZFwiIGNsYXNzPVwibWItMTZcIiBzdHlsZT1cImRpc3BsYXk6IG5vbmU7XCI+XG4gICAgICAgIDxsYWJlbCBmb3I9XCJsb2dvLXVwbG9hZC1zaW5nbGVcIiBzdHlsZT1cImRpc3BsYXk6IGJsb2NrOyBtYXJnaW4tYm90dG9tOiA2cHg7IGZvbnQtc2l6ZTogMC44cmVtO1wiPlVwbG9hZCBsb2dvOjwvbGFiZWw+XG4gICAgICAgIDxpbnB1dCB0eXBlPVwiZmlsZVwiIGlkPVwibG9nby11cGxvYWQtc2luZ2xlXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiAvPlxuICAgICAgICA8cCBjbGFzcz1cInRpbnktaGludFwiPlRoaXMgbG9nbyB3aWxsIGJlIHVzZWQgb24gYWxsIHRoZW1lc Line truncated
`}).join(""),C.querySelectorAll(".share-revoke").forEach(a=>{a.addEventListener("click",()=>l(a.dataset.shareId))})}catch{C.innerHTML='<span style="color: var(--muted);">Could not load outstanding shares.</span>'}}async function l(e){try{const s=await fetch(`/api/v1/share/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"same-origin"});if(!s.ok){const r=await s.json().catch(()=>({}));B(r&&r.error||`Revoke failed (HTTP ${s.status}).`);return}$("Share revoked."),L()}catch{B("Network error while revoking.")}}async function c(){if(!T)return;y(),H.disabled=!0;const e=H.textContent;H.textContent="Creating\u2026";try{const s=parseInt(S.value,10),r=await fetch("/api/v1/share",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:T.id,ttlMs:s})}),o=await r.json().catch(()=>({}));if(!r.ok||!o.success){f(r.status,o);return}const a=o.data.urlPath;N.value=m(a),M.textContent=`Public link \xB7 expires ${v(o.data.expiresAt)}`,g.style.display="block",$("Share link created."),L()}catch{B("Network error while creating share.")}finally{H.disabled=!1,H.textContent=e}}async function d(){if(!T)return;const e=(z.value||"").trim();if(!e||!e.includes("@")){B("A valid recipient email is required.");return}y(),k.disabled=!0;const s=k.textContent;k.textContent="Creating\u2026";try{const r=await fetch("/api/v1/share/tailscale",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:T.id,email:e})}),o=await r.json().catch(()=>({}));if(!r.ok||!o.success){f(r.status,o);return}const a=o.data&&o.data.urlPath;a?(N.value=m(a),M.textContent=`Tailscale invite \xB7 emailed to ${e} (or use this URL manually if delivery failed).`):(N.value="",M.textContent=`Tailscale invite sent to ${e}.`),g.style.display="block",$("Tailscale invite created."),z.value="",L()}catch{B("Network error while creating Tailscale invite.")}finally{k.disabled=!1,k.textContent=s}}function f(e,s){const r=s&&s.error||"";if(e===402){B("Share is a Pro feature. Activate a license to unlock.");return}if(e===400&&/tailscale/i.test(r)){B("Tailscale is not configured on this host. Set up Tailscale in the dashboard first.");return}if(e===403){B("You do not have permission to share services.");return}if(e===404){B("Service not found. It may have been deleted.");return}B(r||`Request failed (HTTP ${e}).`)}function p(e){!e||!e.id||(T={id:e.id,name:e.name||e.id},j.textContent=T.name,y(),b("public"),z.value="",S.value=String(w[1].ms),x.classList.add("show"),L())}x.querySelectorAll(".share-tab").forEach(e=>{e.addEventListener("click",()=>b(e.dataset.tab))}),H.addEventListener("click",c),k.addEventListener("click",d),E.addEventListener("click",()=>x.classList.remove("show")),wireModal(x,E),P.addEventListener("click",async()=>{const e=N.value;if(e)try{navigator.clipboard&&navigator.clipboard.writeText?await navigator.clipboard.writeText(e):(N.select(),document.execCommand("copy"));const s=P.textContent;P.textContent="Copied!",setTimeout(()=>{P.textContent=s},1200)}catch{B("Could not copy to clipboard. Select the URL manually.")}}),window.openShareModal=p})();
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLy8gTG9nbyBDdXN0b21pemF0aW9uIFN5c3RlbVxuKGZ1bmN0aW9uKCkge1xuICAvLyBJbmplY3QgbW9kYWwgSFRNTFxuICBpbmplY3RNb2RhbCgnbG9nby1tb2RhbCcsIGA8ZGl2IGlkPVwibG9nby1tb2RhbFwiIGNsYXNzPVwid2VhdGhlci1tb2RhbFwiPlxuICAgIDxkaXYgY2xhc3M9XCJ3ZWF0aGVyLW1vZGFsLWNvbnRlbnRcIiBzdHlsZT1cIm1pbi13aWR0aDogNDAwcHg7IG1heC13aWR0aDogNTIwcHg7XCI+XG4gICAgICA8aDM+RGFzaGJvYXJkIFNldHRpbmdzPC9oMz5cbiAgICAgIDxwIHN0eWxlPVwiZm9udC1zaXplOiAwLjg1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW46IDAgMCAxNnB4O1wiPlxuICAgICAgICBDdXN0b21pemUgeW91ciBkYXNoYm9hcmQncyBhcHBlYXJhbmNlIGFuZCBzeXN0ZW0gcHJlZmVyZW5jZXMuXG4gICAgICA8L3A+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgZm9yPVwiZGFzaGJvYXJkLXRpdGxlXCIgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5EYXNoYm9hcmQgVGl0bGU6PC9sYWJlbD5cbiAgICAgICAgPGlucHV0IHR5cGU9XCJ0ZXh0XCIgaWQ9XCJkYXNoYm9hcmQtdGl0bGVcIiBwbGFjZWhvbGRlcj1cIkRhc2hDYWRkeVwiIG1heGxlbmd0aD1cIjUwXCIgc3R5bGU9XCJ3aWR0aDogMTAwJTsgcGFkZGluZzogMTBweCAxMnB4OyBib3JkZXI6IDFweCBzb2xpZCB2YXIoLS1ib3JkZXIpOyBib3JkZXItcmFkaXVzOiA0cHg7IGJhY2tncm91bmQ6IHZhcigtLWNhcmQtYmcpOyBjb2xvcjogdmFyKC0tZmcpOyBmb250LXNpemU6IDFyZW07XCIgLz5cbiAgICAgICAgPHAgY2xhc3M9XCJ0aW55LWhpbnRcIj5TaG93biBpbiBicm93c2VyIHRhYiBhbmQgaGVhZGVyIChtYXggNTAgY2hhcmFjdGVycyk8L3A+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGhyIGNsYXNzPVwiaHItZGl2aWRlclwiIC8+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5Mb2dvOjwvbGFiZWw+XG4gICAgICAgIDxwIGNsYXNzPVwidGlueS1oaW50XCIgc3R5bGU9XCJtYXJnaW4tdG9wOiAycHg7XCI+U2VwYXJhdGUgbG9nb3MgZm9yIGRhcmsgYW5kIGxpZ2h0IHRoZW1lcywgb3IgdXNlIHRoZSBzYW1lIGZvciBib3RoLjwvcD5cbiAgICAgIDwvZGl2PlxuXG4gICAgICA8ZGl2IHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4OyBtYXJnaW4tYm90dG9tOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogIzFhMWEyZTsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgyNTUsMjU1LDI1NSwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1kYXJrXCIgc3JjPVwiL2Fzc2V0cy9kYXNoY2FkZHktbG9nby1kYXJrLnBuZ1wiIGFsdD1cIkRhcmsgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjOWFhNmJmOyBtYXJnaW4tdG9wOiA2cHg7XCI+RGFyayB0aGVtZXM8L3A+XG4gICAgICAgIDwvZGl2PlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogI2YwZjBmMDsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgwLDAsMCwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1saWdodFwiIHNyYz1cIi9hc3NldHMvZGFzaGNhZGR5LWxvZ28tbGlnaHQucG5nXCIgYWx0PVwiTGlnaHQgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjNWY2YjdhOyBtYXJnaW4tdG9wOiA2cHg7XCI+TGlnaHQgdGhlbWVzPC9wPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIDwvZGl2PlxuICAgICAgPHAgaWQ9XCJsb2dvLXN0YXR1c1wiIHN0eWxlPVwiZm9udC1zaXplOiAwLjc1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW4tYm90dG9tOiAxMnB4OyB0ZXh0LWFsaWduOiBjZW50ZXI7XCI+VXNpbmcgZGVmYXVsdCBsb2dvczwvcD5cblxuICAgICAgPGRpdiBjbGFzcz1cIm1iLTE2XCI+XG4gICAgICAgIDxsYWJlbCBzdHlsZT1cImRpc3BsYXk6IGZsZXg7IGFsaWduLWl0ZW1zOiBjZW50ZXI7IGdhcDogOHB4OyBmb250LXNpemU6IDAuODJyZW07IGN1cnNvcjogcG9pbnRlcjsgdXNlci1zZWxlY3Q6IG5vbmU7XCI+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJjaGVja2JveFwiIGlkPVwibG9nby1zYW1lLWJvdGhcIiAvPiBVc2Ugc2FtZSBsb2dvIGZvciBib3RoXG4gICAgICAgIDwvbGFiZWw+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tZHVhbC11cGxvYWRzXCIgY2xhc3M9XCJtYi0xNlwiIHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTtcIj5cbiAgICAgICAgICA8bGFiZWwgZm9yPVwibG9nby11cGxvYWQtZGFya1wiIHN0eWxlPVwiZGlzcGxheTogYmxvY2s7IG1hcmdpbi1ib3R0b206IDZweDsgZm9udC1zaXplOiAwLjhyZW07XCI+RGFyayB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1kYXJrXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiBzdHlsZT1cImZvbnQtc2l6ZTogMC43NXJlbTtcIiAvPlxuICAgICAgICA8L2Rpdj5cbiAgICAgICAgPGRpdiBzdHlsZT1cImZsZXg6IDE7XCI+XG4gICAgICAgICAgPGxhYmVsIGZvcj1cImxvZ28tdXBsb2FkLWxpZ2h0XCIgc3R5bGU9XCJkaXNwbGF5OiBibG9jazsgbWFyZ2luLWJvdHRvbTogNnB4OyBmb250LXNpemU6IDAuOHJlbTtcIj5MaWdodCB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1saWdodFwiIGFjY2VwdD1cImltYWdlLypcIiBjbGFzcz1cImlucHV0LWNhcmQtYWx0XCIgc3R5bGU9XCJmb250LXNpemU6IDAuNzVyZW07XCIgLz5cbiAgICAgICAgPC9kaXY+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tc2luZ2xlLXVwbG9hZFwiIGNsYXNzPVwibWItMTZcIiBzdHlsZT1cImRpc3BsYXk6IG5vbmU7XCI+XG4gICAgICAgIDxsYWJlbCBmb3I9XCJsb2dvLXVwbG9hZC1zaW5nbGVcIiBzdHlsZT1cImRpc3BsYXk6IGJsb2NrOyBtYXJnaW4tYm90dG9tOiA2cHg7IGZvbnQtc2l6ZTogMC44cmVtO1wiPlVwbG9hZCBsb2dvOjwvbGFiZWw+XG4gICAgICAgIDxpbnB1dCB0eXBlPVwiZmlsZVwiIGlkPVwibG9nby11cGxvYWQtc2luZ2xlXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiAvPlxuICAgICAgICA8cCBjbGFzcz1cInRpbnktaGludFwiPlRoaXMgbG9nbyB3aWxsIGJlIHVzZWQgb24gYWxsIHRoZW1lc Line truncated
+4 -4
View File
@@ -31,8 +31,8 @@
<!-- TOTP Login Overlay -->
<div id="totp-overlay">
<div class="totp-card">
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy">
<p class="subtitle">Enter your 6-digit authentication code</p>
<div class="totp-digits" id="totp-digits">
<input type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="one-time-code">
@@ -220,7 +220,7 @@
<button id="security-center-btn" aria-label="Security Center">🛡️ Security</button>
<button id="deploys-btn" aria-label="Deploys">🚚 Deploys</button>
<button id="log-insights-btn" aria-label="Log Insights">🔍 Insights</button>
<button onclick="openDiskSettings()" aria-label="Disk Safety">💾 Disk</button>
<button id="disk-settings-open" aria-label="Disk Safety">💾 Disk</button>
<button id="docker-resources-btn" aria-label="Docker resources">🐳 Docker</button>
</div>
</div>
@@ -1048,7 +1048,7 @@
<script src="/dist/onboarding.js" defer></script>
<script src="/dist/init.js" defer></script>
<!-- AI Chat Floating Button -->
<button onclick="toggleAIChat()" style="position:fixed;bottom:20px;right:20px;width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#8b5cf6);border:none;box-shadow:0 4px 20px rgba(99,102,241,0.4);cursor:pointer;z-index:9998;font-size:1.5rem;display:flex;align-items:center;justify-content:center;transition:transform 0.2s;" onmouseover="this.style.transform='scale(1.1)'" onmouseout="this.style.transform='scale(1)'" title="AI Assistant">🤖</button>
<button id="ai-chat-fab" style="position:fixed;bottom:20px;right:20px;width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#8b5cf6);border:none;box-shadow:0 4px 20px rgba(99,102,241,0.4);cursor:pointer;z-index:9998;font-size:1.5rem;display:flex;align-items:center;justify-content:center;transition:transform 0.2s;" title="AI Assistant">🤖</button>
</body>
</html>
+5
View File
@@ -345,6 +345,11 @@
if (e.target && e.target.id === 'ai-settings-btn') openSettings();
}, true);
// Audit P0-3: the FAB's inline onclick/onmouseover/onmouseout were dead
// under the meta CSP. Click wired here; hover moved to a CSS :hover rule.
const fab = document.getElementById('ai-chat-fab');
if (fab) fab.addEventListener('click', () => toggle());
window.aiChat = { send, deploy, toggle };
window.toggleAIChat = toggle;
})();
+5 -1
View File
@@ -1090,9 +1090,13 @@
folderBrowserSelectedList.innerHTML = selectedFolders.map(path => `
<span style="padding: 6px 12px; background: var(--card-bg); border: 1px solid var(--success); border-radius: 4px; display: flex; align-items: center; gap: 6px;">
${escapeHtml(path)}
<button type="button" onclick="removeSelectedFolder('${escapeHtml(path)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">×</button>
<button type="button" data-remove-folder="${escapeHtml(path)}" aria-label="Remove ${escapeHtml(path)}" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">×</button>
</span>
`).join('');
// Audit P0-3: was inline onclick (dead under the meta CSP)
folderBrowserSelectedList.querySelectorAll('[data-remove-folder]').forEach((btn) => {
btn.addEventListener('click', () => window.removeSelectedFolder(btn.dataset.removeFolder));
});
}
window.removeSelectedFolder = function(path) {
+4 -4
View File
@@ -56,8 +56,8 @@
}).join('\n');
card.innerHTML = `
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy">
<p class="subtitle">Choose how to sign in</p>
<div id="auth-gate-providers" style="margin: 14px 0 10px;">${providerButtons}</div>
<div id="auth-gate-message" style="margin-top: 8px; color: var(--muted); font-size: 0.8rem;"></div>
@@ -102,8 +102,8 @@
if (provider.name === 'email') {
card.innerHTML = `
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy">
<p class="subtitle">Sign in with email</p>
<p style="margin: 6px 0 14px; font-size: 0.85rem; color: var(--muted);">
We'll email you a one-time sign-in link.
+18 -2
View File
@@ -204,6 +204,20 @@
var restoreBtn = document.getElementById('backup-do-restore-btn');
var resultDiv = document.getElementById('backup-result');
var scheduleContainer = document.getElementById('backup-schedules-container');
// Audit P0-3 (2026-10-27): premium upsell buttons used inline onclick,
// which the meta CSP blocks — dead buttons. (Their onclick also called
// scrollToSection('license'), which has NEVER existed — doubly dead.)
// data-upgrade-msg + wiring; license UI opens via window.openLicenseModal.
function wireUpgradeButtons(root) {
if (!root || !root.querySelectorAll) return;
root.querySelectorAll('[data-upgrade-msg]').forEach((btn) => {
btn.addEventListener('click', () => {
showNotification(btn.dataset.upgradeMsg, 'info');
if (window.openLicenseModal) window.openLicenseModal();
});
});
}
var historyContainer = document.getElementById('backup-history-container');
var diskContainer = document.getElementById('backup-disk-container');
var pointintimeContainer = document.getElementById('pointintime-container');
@@ -420,8 +434,9 @@
'<div style="font-size: 2rem; margin-bottom: 12px;">⭐</div>' +
'<div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div>' +
'<div style="font-size: 0.85rem; color: var(--muted);">Auto-backup scheduling requires a DashCaddy Premium subscription.</div>' +
'<button onclick="showNotification(\'Upgrade to Premium to enable auto-backups!\', \'info\'); scrollToSection(\'license\');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
'<button type="button" data-upgrade-msg="Upgrade to Premium to enable auto-backups!" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
'</div>';
wireUpgradeButtons(scheduleContainer);
return;
}
@@ -749,8 +764,9 @@
'<div style="font-size: 2rem; margin-bottom: 12px;">⭐</div>' +
'<div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div>' +
'<div style="font-size: 0.85rem; color: var(--muted);">Point-in-time restore requires DashCaddy Premium with auto-backup enabled.</div>' +
'<button onclick="showNotification(\'Upgrade to Premium for point-in-time restore!\', \'info\'); scrollToSection(\'license\');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
'<button type="button" data-upgrade-msg="Upgrade to Premium for point-in-time restore!" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>' +
'</div>';
wireUpgradeButtons(pointintimeContainer);
return;
}
} catch (e) { /* ignore */ }
+9 -1
View File
@@ -114,11 +114,19 @@
if (!isPremium) {
html += `<div class="accent-info-box" style="margin-top: 16px; text-align: center;">
<span>🔒 Upgrade to unlock automated workflows</span>
<button onclick="showNotification('Upgrade to Premium to enable workflows!', 'info'); scrollToSection('license');" style="margin-left: 12px; padding: 6px 16px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>
<button type="button" data-upgrade-msg="Upgrade to Premium to enable workflows!" style="margin-left: 12px; padding: 6px 16px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button>
</div>`;
}
container.innerHTML = `<div class="workflow-list">${html}</div>`;
// Audit P0-3: was inline onclick (dead under the meta CSP); it also
// called the nonexistent scrollToSection — openLicenseModal instead
container.querySelectorAll('[data-upgrade-msg]').forEach((btn) => {
btn.addEventListener('click', () => {
showNotification(btn.dataset.upgradeMsg, 'info');
if (window.openLicenseModal) window.openLicenseModal();
});
});
wireWorkflowEvents();
} else {
container.innerHTML = '<div class="panel-empty"><span class="empty-icon">⚠️</span>Failed to load workflows</div>';
+22 -4
View File
@@ -33,7 +33,7 @@
<div style="background:var(--bg-card,#1a1a2e);border-radius:12px;padding:28px;max-width:520px;width:90%;max-height:85vh;overflow-y:auto;border:1px solid var(--border,#333);">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
<h2 style="margin:0;font-size:1.3rem;">💾 Disk Safety</h2>
<button onclick="document.getElementById('disk-settings-modal').remove()" style="background:none;border:none;font-size:1.5rem;cursor:pointer;color:var(--text-muted,#888);">×</button>
<button id="disk-close-btn" aria-label="Close" style="background:none;border:none;font-size:1.5rem;cursor:pointer;color:var(--text-muted,#888);">×</button>
</div>
<div style="background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.2);border-radius:8px;padding:14px;margin-bottom:20px;">
@@ -65,13 +65,26 @@
</div>
<div style="display:flex;gap:10px;margin-top:24px;">
<button onclick="saveDiskSettings()" style="flex:1;padding:10px 16px;background:#6366f1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Save Settings</button>
<button onclick="cleanupDiskNow()" style="flex:1;padding:10px 16px;background:rgba(239,68,68,0.15);color:#f87171;border:1px solid rgba(239,68,68,0.3);border-radius:8px;cursor:pointer;font-weight:600;">Clean Up Now</button>
<button id="disk-save-btn" style="flex:1;padding:10px 16px;background:#6366f1;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Save Settings</button>
<button id="disk-cleanup-btn" style="flex:1;padding:10px 16px;background:rgba(239,68,68,0.15);color:#f87171;border:1px solid rgba(239,68,68,0.3);border-radius:8px;cursor:pointer;font-weight:600;">Clean Up Now</button>
</div>
<p style="font-size:0.8rem;color:var(--text-muted,#666);margin-top:12px;text-align:center;">Some changes apply on next container restart.</p>
</div>
`;
document.body.appendChild(modal);
// Audit P0-3 (2026-10-27): the meta CSP blocks inline event handlers, so
// the injected onclick/oninput attributes were dead — Save/Clean Up/
// Close did nothing and slider value labels never updated. Wire after
// injection instead.
document.getElementById('disk-close-btn').addEventListener('click', () => modal.remove());
document.getElementById('disk-save-btn').addEventListener('click', () => saveDiskSettings());
document.getElementById('disk-cleanup-btn').addEventListener('click', () => cleanupDiskNow());
modal.querySelectorAll('input[type="range"]').forEach((inp) => {
inp.addEventListener('input', () => {
const out = document.getElementById(`${inp.id}-val`);
if (out) out.textContent = inp.value;
});
});
}
function settingRow(label, id, current, unit, displayVal, min, max) {
@@ -79,7 +92,7 @@
<div>
<label style="font-size:0.85rem;color:var(--text-muted,#aaa);display:block;margin-bottom:4px;">${label}</label>
<div style="display:flex;align-items:center;gap:10px;">
<input type="range" id="disk-${id}" min="${min}" max="${max}" value="${displayVal}" oninput="document.getElementById('disk-${id}-val').textContent=this.value"
<input type="range" id="disk-${id}" min="${min}" max="${max}" value="${displayVal}"
style="flex:1;accent-color:#6366f1;">
<span id="disk-${id}-val" style="min-width:50px;text-align:right;font-weight:600;">${displayVal}</span>
<span style="font-size:0.8rem;color:var(--text-muted,#666);min-width:60px;">${unit}</span>
@@ -130,4 +143,9 @@
window.openDiskSettings = function() { loadDiskSettings(); };
window.saveDiskSettings = saveDiskSettings;
window.cleanupDiskNow = cleanupDiskNow;
// Audit P0-3: index.html's Disk button carried an inline handler calling
// openDiskSettings() — dead under the meta CSP. Wired here instead.
const diskOpenBtn = document.getElementById('disk-settings-open');
if (diskOpenBtn) diskOpenBtn.addEventListener('click', () => loadDiskSettings());
})();
+9 -2
View File
@@ -375,12 +375,19 @@
html += `<td style="padding: 8px; color: ${isUp ? 'var(--ok-fg)' : 'var(--bad-fg)'};">${isUp ? 'Up' : 'Down'}</td>`;
html += `<td style="padding: 8px;">${s.sla?.target ? s.sla.target + '%' : '-'}</td>`;
html += `<td style="padding: 8px; text-align: right;">`;
html += `<button onclick="document.dispatchEvent(new CustomEvent('health-edit', {detail:'${escapeHtml(s.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`;
html += `<button onclick="document.dispatchEvent(new CustomEvent('health-delete', {detail:'${escapeHtml(s.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`;
html += `<button data-health-action="health-edit" data-service-id="${escapeHtml(s.serviceId)}" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`;
html += `<button data-health-action="health-delete" data-service-id="${escapeHtml(s.serviceId)}" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`;
html += '</td></tr>';
}
html += '</table>';
configContainer.innerHTML = html;
// Audit P0-3: the Edit/Delete buttons dispatched CustomEvents from
// inline onclick — dead under the meta CSP. Same events, wired.
configContainer.querySelectorAll('[data-health-action]').forEach((btn) => {
btn.addEventListener('click', () => {
document.dispatchEvent(new CustomEvent(btn.dataset.healthAction, { detail: btn.dataset.serviceId }));
});
});
} catch (e) {
configContainer.innerHTML = `<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(e.message)}</div>`;
}
+10 -1
View File
@@ -70,7 +70,7 @@
<div class="mb-16">
<label class="form-label-bold">Favicon (Browser Tab Icon):</label>
<div id="favicon-preview-container" style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px; padding: 12px; border-radius: 6px; background: var(--card-bg);">
<img id="favicon-preview" src="/assets/dashcaddy-favicon.ico" alt="Current favicon" style="width: 32px; height: 32px; image-rendering: pixelated;" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22><rect fill=%22%23667%22 width=%2232%22 height=%2232%22 rx=%224%22/></svg>'" />
<img id="favicon-preview" src="/assets/dashcaddy-favicon.ico" alt="Current favicon" style="width: 32px; height: 32px; image-rendering: pixelated;" />
<span id="favicon-status" class="text-tiny-muted">Using DashCaddy favicon</span>
</div>
<input type="file" id="favicon-upload" accept="image/png,image/svg+xml" class="input-card-alt" />
@@ -344,6 +344,15 @@
const faviconPreview = document.getElementById('favicon-preview');
const faviconStatus = document.getElementById('favicon-status');
const faviconUpload = document.getElementById('favicon-upload');
// Audit P0-3: the missing-favicon fallback used inline onerror (dead under
// the meta CSP). Same data-URI fallback, wired + race-guarded.
if (faviconPreview) {
const faviconFallback = () => {
faviconPreview.src = 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22><rect fill=%22%23667%22 width=%2232%22 height=%2232%22 rx=%224%22/></svg>';
};
faviconPreview.addEventListener('error', faviconFallback);
if (faviconPreview.complete && faviconPreview.naturalWidth === 0) faviconFallback();
}
const faviconLink = document.querySelector('link[rel="icon"]') || document.createElement('link');
let pendingFaviconData = null;
+5 -1
View File
@@ -221,7 +221,7 @@
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div>
</div>
<button onclick="smartTestConnection('${svc}')" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
<button type="button" data-smart-test="${svc}" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
</div>`;
}
@@ -263,6 +263,10 @@
}
credentialInputs.innerHTML = html;
// Audit P0-3: was inline onclick calling smartTestConnection (dead under CSP)
credentialInputs.querySelectorAll('[data-smart-test]').forEach((btn) => {
btn.addEventListener('click', () => window.smartTestConnection(btn.dataset.smartTest));
});
}
// Test connection (global for onclick)
+18 -2
View File
@@ -1,5 +1,21 @@
// ===== TOTP AUTHENTICATION GATE =====
(function() {
// Audit P0-3 (2026-10-27): broken-logo hiding used inline onerror, which
// the meta CSP blocks (dead handler). Track failures via capture-phase
// delegation (catches injected <img>s at any time) + a load-state sweep,
// and never resurrect a broken logo in updateTotpLogo().
const brokenLogos = new WeakSet();
document.addEventListener('error', (e) => {
const t = e.target;
if (t && t.tagName === 'IMG' && t.classList.contains('totp-logo')) {
brokenLogos.add(t);
t.style.display = 'none';
}
}, true);
document.querySelectorAll('.totp-logo').forEach((img) => {
if (img.complete && img.naturalWidth === 0) { brokenLogos.add(img); img.style.display = 'none'; }
});
function updateTotpLogo() {
const card = document.querySelector('.totp-card');
if (!card) return;
@@ -9,8 +25,8 @@
const lum = (0.299 * +m[0] + 0.587 * +m[1] + 0.114 * +m[2]) / 255;
const dark = card.querySelector('.totp-logo-dark');
const light = card.querySelector('.totp-logo-light');
if (dark) dark.style.display = lum > 0.5 ? 'none' : '';
if (light) light.style.display = lum > 0.5 ? '' : 'none';
if (dark) dark.style.display = (lum > 0.5 || brokenLogos.has(dark)) ? 'none' : '';
if (light) light.style.display = (lum <= 0.5 || brokenLogos.has(light)) ? 'none' : '';
}
function showTotpOverlay() {
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'dashcaddy-shell-7fc13e7762';
const CACHE = 'dashcaddy-shell-36d9aa3364';
const PRECACHE = [
'/',
'/index.html',