",m.innerHTML=y,z("setup-step-summary")}async function H(m){try{const y=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});return y.ok?(await y.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${y.status}`),{function:"saveConfigToServer"}),!1)}catch(y){return errorHandler.logError("[SetupWizard] Save Config",y,{function:"saveConfigToServer"}),!1}}async function A(){const m={setupComplete:!0,configurationType:b,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(b==="homelab"){m.tld=document.getElementById("setup-tld")?.value?.trim()||".home",m.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const E=document.getElementById("setup-dns-provider")?.value||"technitium";m.dns={provider:E,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 b==="simple"?(m.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",m.defaults={dnsType:"none",sslType:"none",targetIP:m.defaultIP}):b==="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 y=await H(m);safeSet("dashcaddy-config",JSON.stringify(m)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const S=b==="homelab"?"Professional Home Lab":b==="simple"?"Simple Setup":"Public Server",f=y?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${S}. Settings saved to: ${f}`,"success",5e3),setTimeout(()=>location.reload(),500)}const x=document.getElementById("setup-step-1-next");x&&(x.onclick=function(m){m.preventDefault();const y=document.querySelector('input[name="config-type"]:checked');y&&(b=y.value),z(b==="homelab"?"setup-step-homelab":b==="simple"?"setup-step-simple":b==="public"?"setup-step-public":"setup-step-homelab")});const B=document.getElementById("setup-skip");B&&(B.onclick=async function(m){m.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await H({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const w=document.getElementById("setup-tld");w&&(w.oninput=function(m){const y=m.target.value||".home",S=document.getElementById("tld-preview"),f=document.getElementById("tld-preview-2");S&&(S.textContent=y),f&&(f.textContent=y)});const M=document.getElementById("setup-homelab-back");M&&(M.onclick=function(m){m.preventDefault(),z("setup-step-1")});const L=document.getElementById("setup-homelab-next");L&&(L.onclick=function(m){m.preventDefault();const y=document.getElementById("setup-tld")?.value?.trim()||"",S=document.getElementById("setup-ca-name")?.value?.trim()||"",f=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!y||!y.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!S){showNotification("Please enter a Certificate Authority name","warning");return}if(!f){showNotification("Please enter your DNS server IP address","warning");return}P()});const $=document.getElementById("setup-simple-back");$&&($.onclick=function(m){m.preventDefault(),z("setup-step-1")});const u=document.getElementById("setup-simple-next");u&&(u.onclick=function(m){m.preventDefault(),P()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(m){m.onchange=function(){var y=document.getElementById("dns-requirement-note");y&&(y.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const v=document.getElementById("setup-public-back");v&&(v.onclick=function(m){m.preventDefault(),z("setup-step-1")});const D=document.getElementById("setup-public-next");D&&(D.onclick=function(m){m.preventDefault();const y=document.getElementById("setup-public-domain")?.value?.trim()||"",S=document.getElementById("setup-public-email")?.value?.trim()||"";if(!y){showNotification("Please enter your domain name","warning");return}if(!S||!S.includes("@")){showNotification("Please enter a valid email address","warning");return}P()});const I=document.getElementById("setup-summary-back");I&&(I.onclick=function(m){m.preventDefault(),b==="homelab"?z("setup-step-homelab"):b==="simple"?z("setup-step-simple"):b==="public"&&z("setup-step-public")});const R=document.getElementById("setup-summary-next");R&&(R.onclick=function(m){m.preventDefault(),z("setup-step-disk-safety")});const N=document.getElementById("setup-disk-safety-back");N&&(N.onclick=function(m){m.preventDefault(),z("setup-step-summary")});const O=document.getElementById("setup-disk-safety-finish");O&&(O.onclick=function(m){m.preventDefault(),A()}),window.getGlobalConfig=async function(){try{const y=await fetch("/api/v1/config");if(y.ok){const S=await y.json();if(S&&S.setupComplete)return S}}catch{console.warn("Could not fetch config from server")}const m=safeGet("dashcaddy-config");return m?JSON.parse(m):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}}})(),(function(){const b=new ErrorHandler;injectModal("app-selector-modal",`
+ `,g+="
",u.innerHTML=g,D("setup-step-summary")}async function P(u){try{const g=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return g.ok?(await g.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${g.status}`),{function:"saveConfigToServer"}),!1)}catch(g){return errorHandler.logError("[SetupWizard] Save Config",g,{function:"saveConfigToServer"}),!1}}async function R(){const u={setupComplete:!0,configurationType:f,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(f==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const w=document.getElementById("setup-dns-provider")?.value||"technitium";u.dns={provider:w,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 f==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):f==="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 g=await P(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const S=f==="homelab"?"Professional Home Lab":f==="simple"?"Simple Setup":"Public Server",y=g?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${S}. Settings saved to: ${y}`,"success",5e3),setTimeout(()=>location.reload(),500)}const k=document.getElementById("setup-step-1-next");k&&(k.onclick=function(u){u.preventDefault();const g=document.querySelector('input[name="config-type"]:checked');g&&(f=g.value),D(f==="homelab"?"setup-step-homelab":f==="simple"?"setup-step-simple":f==="public"?"setup-step-public":"setup-step-homelab")});const M=document.getElementById("setup-skip");M&&(M.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await P({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 g=u.target.value||".home",S=document.getElementById("tld-preview"),y=document.getElementById("tld-preview-2");S&&(S.textContent=g),y&&(y.textContent=g)});const z=document.getElementById("setup-homelab-back");z&&(z.onclick=function(u){u.preventDefault(),D("setup-step-1")});const C=document.getElementById("setup-homelab-next");C&&(C.onclick=function(u){u.preventDefault();const g=document.getElementById("setup-tld")?.value?.trim()||"",S=document.getElementById("setup-ca-name")?.value?.trim()||"",y=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!g||!g.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!S){showNotification("Please enter a Certificate Authority name","warning");return}if(!y){showNotification("Please enter your DNS server IP address","warning");return}A()});const N=document.getElementById("setup-simple-back");N&&(N.onclick=function(u){u.preventDefault(),D("setup-step-1")});const x=document.getElementById("setup-simple-next");x&&(x.onclick=function(u){u.preventDefault(),A()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var g=document.getElementById("dns-requirement-note");g&&(g.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const I=document.getElementById("setup-public-back");I&&(I.onclick=function(u){u.preventDefault(),D("setup-step-1")});const H=document.getElementById("setup-public-next");H&&(H.onclick=function(u){u.preventDefault();const g=document.getElementById("setup-public-domain")?.value?.trim()||"",S=document.getElementById("setup-public-email")?.value?.trim()||"";if(!g){showNotification("Please enter your domain name","warning");return}if(!S||!S.includes("@")){showNotification("Please enter a valid email address","warning");return}A()});const m=document.getElementById("setup-summary-back");m&&(m.onclick=function(u){u.preventDefault(),f==="homelab"?D("setup-step-homelab"):f==="simple"?D("setup-step-simple"):f==="public"&&D("setup-step-public")});const L=document.getElementById("setup-summary-next");L&&(L.onclick=function(u){u.preventDefault(),D("setup-step-disk-safety")});const T=document.getElementById("setup-disk-safety-back");T&&(T.onclick=function(u){u.preventDefault(),D("setup-step-summary")});const O=document.getElementById("setup-disk-safety-finish");O&&(O.onclick=function(u){u.preventDefault(),R()}),window.getGlobalConfig=async function(){try{const g=await fetch("/api/v1/config");if(g.ok){const S=await g.json();if(S&&S.setupComplete)return S}}catch{console.warn("Could not fetch config from server")}const u=safeGet("dashcaddy-config");return u?JSON.parse(u):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}}})(),(function(){const f=new ErrorHandler;injectModal("app-selector-modal",`
Choose an App
@@ -333,12 +333,12 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
-
`);const C="custom-apps";let j=null,k=null;const z=document.getElementById("app-selector-modal"),P=document.getElementById("app-selector-grid");async function H(){try{const p=await(await fetch("/api/v1/apps/templates")).json();if(p.success)return j=p.templates,k=p.categories,!0}catch(s){b.logError("[AppSelector] Fetch Templates",s,{function:"fetchApiTemplates"})}return!1}async function A(s){try{return await(await fetch(`/api/v1/apps/ports/${s}/check`)).json()}catch(p){return b.logError("[AppSelector] Check Port",p,{function:"checkPortAvailability"}),{available:!0}}}async function x(s){try{const l=await(await fetch(`/api/v1/apps/ports/${s}/suggest`)).json();if(l.success)return l.suggestedPort}catch(p){b.logError("[AppSelector] Get Suggested Port",p,{function:"getSuggestedPort"})}return s}async function B(){if(P.innerHTML='
Loading app templates...
',!j&&!await H()){P.innerHTML='
Failed to load app templates. Please try again.
';return}P.innerHTML="";const s={};for(const[l,g]of Object.entries(j)){const c=g.category||"Other";s[c]||(s[c]=[]),s[c].push({id:l,...g})}const p=k?Object.keys(k):Object.keys(s).sort();for(const l of p){const g=s[l];if(!g||g.length===0)continue;g.sort((e,a)=>(a.popularity||0)-(e.popularity||0));const c=document.createElement("div");c.className="app-category-header";const t=k?.[l]||{};c.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(l)}`,t.color&&(c.style.borderBottomColor=t.color),P.appendChild(c),g.forEach(e=>{const a=document.createElement("div");a.className="app-option";const o=e.isDashboardWidget,i=o&&safeGet("widget-"+e.id+"-enabled")!=="false",n=o?`
${i?"ON":"OFF"}
`:"",r=!o&&e.difficulty?`
${escapeHtml(e.difficulty)}
`:"";a.innerHTML=`
+ `);const B="custom-apps";let j=null,b=null;const D=document.getElementById("app-selector-modal"),A=document.getElementById("app-selector-grid");async function P(){try{const p=await(await fetch("/api/v1/apps/templates")).json();if(p.success)return j=p.templates,b=p.categories,!0}catch(s){f.logError("[AppSelector] Fetch Templates",s,{function:"fetchApiTemplates"})}return!1}async function R(s){try{return await(await fetch(`/api/v1/apps/ports/${s}/check`)).json()}catch(p){return f.logError("[AppSelector] Check Port",p,{function:"checkPortAvailability"}),{available:!0}}}async function k(s){try{const l=await(await fetch(`/api/v1/apps/ports/${s}/suggest`)).json();if(l.success)return l.suggestedPort}catch(p){f.logError("[AppSelector] Get Suggested Port",p,{function:"getSuggestedPort"})}return s}async function M(){if(A.innerHTML='
Loading app templates...
',!j&&!await P()){A.innerHTML='
Failed to load app templates. Please try again.
';return}A.innerHTML="";const s={};for(const[l,v]of Object.entries(j)){const c=v.category||"Other";s[c]||(s[c]=[]),s[c].push({id:l,...v})}const p=b?Object.keys(b):Object.keys(s).sort();for(const l of p){const v=s[l];if(!v||v.length===0)continue;v.sort((e,a)=>(a.popularity||0)-(e.popularity||0));const c=document.createElement("div");c.className="app-category-header";const t=b?.[l]||{};c.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(l)}`,t.color&&(c.style.borderBottomColor=t.color),A.appendChild(c),v.forEach(e=>{const a=document.createElement("div");a.className="app-option";const o=e.isDashboardWidget,i=o&&safeGet("widget-"+e.id+"-enabled")!=="false",n=o?`
${i?"ON":"OFF"}
`:"",r=!o&&e.difficulty?`
${escapeHtml(e.difficulty)}
`:"";a.innerHTML=`
${escapeHtml(e.icon||"\u{1F4E6}")}
${escapeHtml(e.name)}
${escapeHtml(e.description||"")}
${n}${r}
- `,o?a.onclick=()=>w(e,a):a.onclick=()=>M(e),P.appendChild(a)})}window.renderRecipeCards&&await window.renderRecipeCards(P)}function w(s,p){const l="widget-"+s.id+"-enabled",c=!(safeGet(l)!=="false");safeSet(l,String(c));const t=s.widgetSelector;if(t){const a=document.querySelector(t);a&&(a.style.display=c?"":"none")}const e=p.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=c?"ON":"OFF",e.style.background=c?"#2ecc7130":"#e74c3c30",e.style.color=c?"#2ecc71":"#e74c3c"),showNotification(`${s.name} widget ${c?"enabled":"disabled"}`,"success",2e3)}async function M(s){const p=document.getElementById("app-deploy-modal"),l=document.getElementById("app-deploy-title"),g=document.getElementById("deploy-subdomain"),c=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),a=document.getElementById("deploy-tailscale-only"),o=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:s.id})})).json();if(G.success&&G.exists){const V=G.container;confirm(`Found existing ${s.name} container:
+ `,o?a.onclick=()=>E(e,a):a.onclick=()=>z(e),A.appendChild(a)})}window.renderRecipeCards&&await window.renderRecipeCards(A)}function E(s,p){const l="widget-"+s.id+"-enabled",c=!(safeGet(l)!=="false");safeSet(l,String(c));const t=s.widgetSelector;if(t){const a=document.querySelector(t);a&&(a.style.display=c?"":"none")}const e=p.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=c?"ON":"OFF",e.style.background=c?"#2ecc7130":"#e74c3c30",e.style.color=c?"#2ecc71":"#e74c3c"),showNotification(`${s.name} widget ${c?"enabled":"disabled"}`,"success",2e3)}async function z(s){const p=document.getElementById("app-deploy-modal"),l=document.getElementById("app-deploy-title"),v=document.getElementById("deploy-subdomain"),c=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),a=document.getElementById("deploy-tailscale-only"),o=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:s.id})})).json();if(G.success&&G.exists){const V=G.container;confirm(`Found existing ${s.name} container:
Container: ${V.name}
Status: ${V.status}
@@ -347,38 +347,38 @@ Port: ${V.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.`)&&(s._useExisting=!0,s._existingContainer=V)}}catch{}l.textContent=`Deploy ${s.name}`;const i=s.subdomain||s.id.replace(/-/g,"");g.value=i;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const W=s.subpathSupport||"strip";W==="none"?(n.style.display="block",n.innerHTML='⚠ '+s.name+" does not support subdirectory mode. It may not work correctly at a subpath."):W==="strip"?(n.style.display="block",n.innerHTML='ⓘ '+s.name+" has unverified subdirectory support. It may require additional configuration."):n.style.display="none"}else n.style.display="none";const r=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),d=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),h=document.querySelector(`input[name="dns-type"][value="${r}"]`),T=document.querySelector(`input[name="ssl-type"][value="${d}"]`);h?h.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,T?T.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",a.checked=!1;const U=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),q=document.querySelector("#app-deploy-modal details"),F=q?.querySelector("div");if(q&&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&&(F.appendChild(W),W.dataset.moved="1"),G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1")}const _=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(s.mediaMount){_.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){W.style.display="block",G.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.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);`,Z.innerHTML=`${escapeHtml(ee.folderName)} from ${escapeHtml(ee.sourceImage)}`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},G.appendChild(Z)})}else W.style.display="none"}catch{W.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else _.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(s.id==="plex"||s.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",s.docker?.volumes?.length){const W=s.mediaMount?.containerPath,G=s.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(W&&V.endsWith(":"+W)));G.length>0?(ne.style.display="block",G.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=`
+Click Cancel to deploy a new container.`)&&(s._useExisting=!0,s._existingContainer=V)}}catch{}l.textContent=`Deploy ${s.name}`;const i=s.subdomain||s.id.replace(/-/g,"");v.value=i;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const W=s.subpathSupport||"strip";W==="none"?(n.style.display="block",n.innerHTML='⚠ '+s.name+" does not support subdirectory mode. It may not work correctly at a subpath."):W==="strip"?(n.style.display="block",n.innerHTML='ⓘ '+s.name+" has unverified subdirectory support. It may require additional configuration."):n.style.display="none"}else n.style.display="none";const r=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),d=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),h=document.querySelector(`input[name="dns-type"][value="${r}"]`),$=document.querySelector(`input[name="ssl-type"][value="${d}"]`);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,t.value=SITE.defaults.targetIP||"localhost",a.checked=!1;const U=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,G=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"),G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1")}const q=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(s.mediaMount){q.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){W.style.display="block",G.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.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);`,Z.innerHTML=`${escapeHtml(ee.folderName)} from ${escapeHtml(ee.sourceImage)}`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},G.appendChild(Z)})}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 Q=document.getElementById("plex-claim-section");Q&&(s.id==="plex"||s.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",s.docker?.volumes?.length){const W=s.mediaMount?.containerPath,G=s.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(W&&V.endsWith(":"+W)));G.length>0?(ne.style.display="block",G.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=`
\u2192 ${ee}
- `,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=s.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const W=e.value||se;Y.innerHTML='Checking port...';const G=await A(W);if(G.available)Y.innerHTML=`Port ${escapeHtml(String(W))} is available`;else{const V=await x(se);Y.innerHTML=`
+ `,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=s.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const W=e.value||se;Y.innerHTML='Checking port...';const G=await R(W);if(G.available)Y.innerHTML=`Port ${escapeHtml(String(W))} is available`;else{const V=await k(se);Y.innerHTML=`
Port ${escapeHtml(W)} in use by ${escapeHtml(G.conflict?.usedBy||"unknown")}
`;const K=document.createElement("button");K.type="button",K.textContent=`Use ${V}`,K.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",K.onclick=()=>{document.getElementById("deploy-port").value=V,Y.innerHTML=`Using suggested port ${escapeHtml(String(V))}`},Y.appendChild(K)}}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?o.innerHTML=`
Connected${G.self?.hostname} (${G.self?.ip})| ${G.deviceCount} devices
- `:G.installed?o.innerHTML='Not connected':(o.innerHTML='Not available',a.disabled=!0)}catch{o.innerHTML='Could not check status'}function ae(){const W=g.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${W}`;else if(G==="private")K=`${V==="none"?"http":"https"}://${buildDomain(W)}`;else if(G==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||W;K=SITE.domain?`${te}://${W}.${SITE.domain}`:`${te}://${W}`}else{const te=e.value||s.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}c.textContent=K}g.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=ae}),ae(),z.classList.remove("show"),p.classList.add("show"),p.dataset.appTemplate=JSON.stringify(s)}async function L(s){const p=s.appTemplate,l=safeGetJSON(C,[]),g=p._useExisting&&p._existingContainer,c=l.find(t=>t.id===s.subdomain);if(!(c&&!g&&!confirm(`An app with subdomain "${s.subdomain}" already exists. Redeploy?`))){if(c){const t=l.indexOf(c);l.splice(t,1),safeSet(C,JSON.stringify(l))}if(g)s.port=p._existingContainer.primaryPort;else{const t=s.port||p.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await A(t);if(!e.available){const a=await x(p.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}.
+ `:G.installed?o.innerHTML='Not connected':(o.innerHTML='Not available',a.disabled=!0)}catch{o.innerHTML='Could not check status'}function ae(){const W=v.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${W}`;else if(G==="private")K=`${V==="none"?"http":"https"}://${buildDomain(W)}`;else if(G==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||W;K=SITE.domain?`${te}://${W}.${SITE.domain}`:`${te}://${W}`}else{const te=e.value||s.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}c.textContent=K}v.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=ae}),ae(),D.classList.remove("show"),p.classList.add("show"),p.dataset.appTemplate=JSON.stringify(s)}async function C(s){const p=s.appTemplate,l=safeGetJSON(B,[]),v=p._useExisting&&p._existingContainer,c=l.find(t=>t.id===s.subdomain);if(!(c&&!v&&!confirm(`An app with subdomain "${s.subdomain}" already exists. Redeploy?`))){if(c){const t=l.indexOf(c);l.splice(t,1),safeSet(B,JSON.stringify(l))}if(v)s.port=p._existingContainer.primaryPort;else{const t=s.port||p.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await R(t);if(!e.available){const a=await k(p.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}.
-Would you like to use port ${a} instead?`))s.port=a;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(g?`Configuring ${p.name} with existing container...`:`Deploying ${p.name}...`,"info",0);try{const t={appId:p.id,config:{subdomain:s.subdomain,ip:s.ip,createDns:s.dnsType==="private",port:s.port||p.defaultPort||null,sslType:s.sslType,dnsType:s.dnsType,tailscaleOnly:s.tailscaleOnly||!1,mediaPath:s.mediaPath||null,plexClaimToken:s.plexClaimToken||null,customVolumes:s.customVolumes||null}};g&&(t.config.useExisting=!0,t.config.existingContainerId=p._existingContainer.id,t.config.existingPort=p._existingContainer.primaryPort,!s.port&&p._existingContainer.primaryPort&&(t.config.port=p._existingContainer.primaryPort));const a=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(a.success){const o={id:s.subdomain,name:p.name,logo:`/assets/${p.id}.png`,containerId:a.containerId,url:a.url,ip:s.ip,appTemplate:p.id,tailscaleOnly:s.tailscaleOnly||!1};l.push(o),safeSet(C,JSON.stringify(l)),window.APPS&&!window.APPS.some(n=>n.id===p.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let i=a.usedExisting?`${p.name} configured with existing container!
+Would you like to use port ${a} instead?`))s.port=a;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(v?`Configuring ${p.name} with existing container...`:`Deploying ${p.name}...`,"info",0);try{const t={appId:p.id,config:{subdomain:s.subdomain,ip:s.ip,createDns:s.dnsType==="private",port:s.port||p.defaultPort||null,sslType:s.sslType,dnsType:s.dnsType,tailscaleOnly:s.tailscaleOnly||!1,mediaPath:s.mediaPath||null,plexClaimToken:s.plexClaimToken||null,customVolumes:s.customVolumes||null}};v&&(t.config.useExisting=!0,t.config.existingContainerId=p._existingContainer.id,t.config.existingPort=p._existingContainer.primaryPort,!s.port&&p._existingContainer.primaryPort&&(t.config.port=p._existingContainer.primaryPort));const a=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(a.success){const o={id:s.subdomain,name:p.name,logo:`/assets/${p.id}.png`,containerId:a.containerId,url:a.url,ip:s.ip,appTemplate:p.id,tailscaleOnly:s.tailscaleOnly||!1};l.push(o),safeSet(B,JSON.stringify(l)),window.APPS&&!window.APPS.some(n=>n.id===p.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let i=a.usedExisting?`${p.name} configured with existing container!
URL: ${a.url}`:`${p.name} deployed successfully!
URL: ${a.url}`;a.warning&&(i+=`
-\u26A0 Warning: ${a.warning}`),showNotification(i,"success",8e3),delete p._useExisting,delete p._existingContainer,a.url&&a.url.startsWith("https://")&&$(a.url,p.name),a.setupInstructions&&a.setupInstructions.length>0&&setTimeout(()=>{const n=a.setupInstructions.join(`
-`);showNotification(`Setup Instructions for ${p.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(a.error||"Deployment failed")}catch(t){b.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${p.name}: ${t.message}`,"error",8e3)}}}async function $(s,p){showNotification(`\u23F3 Generating SSL certificate for ${p}...`,"warning",6e4);let l=0;const g=12,c=async()=>{l++;try{const t=await fetch(s,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${p} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return l{window.APPS.some(l=>l.id===p.id)||window.APPS.push(p)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{B(),z.classList.add("show")}),wireModal(z,document.getElementById("app-selector-cancel"));const v=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{v.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const s=JSON.parse(v.dataset.appTemplate),p=document.getElementById("deploy-media-path").value.trim(),l=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(c=>{l.push({hostPath:c.value.trim(),containerPath:c.dataset.containerPath})});const g={appTemplate:s,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:p||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:l.length>0?l:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!g.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(s.mediaMount?.required&&!p){showNotification("Please enter a media library path for this application","warning");return}v.classList.remove("show"),L(g)}),wireModal(v);const D=document.getElementById("folder-browser-modal"),I=document.getElementById("folder-browser-path"),R=document.getElementById("folder-browser-list"),N=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let m="",y=[],S=null;window.openFolderBrowser=function(s){S=s,y=s.value.split(",").map(p=>p.trim()).filter(p=>p),m="",E(),f(""),D.classList.add("show")};async function f(s){I.textContent=s||"Select a drive...",R.innerHTML='
`;return}m=l.path||"",I.textContent=m||"Select a drive...";let g="";l.parent&&l.parent!==l.path&&(g+=`
+\u26A0 Warning: ${a.warning}`),showNotification(i,"success",8e3),delete p._useExisting,delete p._existingContainer,a.url&&a.url.startsWith("https://")&&N(a.url,p.name),a.setupInstructions&&a.setupInstructions.length>0&&setTimeout(()=>{const n=a.setupInstructions.join(`
+`);showNotification(`Setup Instructions for ${p.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(a.error||"Deployment failed")}catch(t){f.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${p.name}: ${t.message}`,"error",8e3)}}}async function N(s,p){showNotification(`\u23F3 Generating SSL certificate for ${p}...`,"warning",6e4);let l=0;const v=12,c=async()=>{l++;try{const t=await fetch(s,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${p} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return l{window.APPS.some(l=>l.id===p.id)||window.APPS.push(p)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{M(),D.classList.add("show")}),wireModal(D,document.getElementById("app-selector-cancel"));const I=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{I.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const s=JSON.parse(I.dataset.appTemplate),p=document.getElementById("deploy-media-path").value.trim(),l=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(c=>{l.push({hostPath:c.value.trim(),containerPath:c.dataset.containerPath})});const v={appTemplate:s,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:p||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:l.length>0?l:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!v.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(s.mediaMount?.required&&!p){showNotification("Please enter a media library path for this application","warning");return}I.classList.remove("show"),C(v)}),wireModal(I);const H=document.getElementById("folder-browser-modal"),m=document.getElementById("folder-browser-path"),L=document.getElementById("folder-browser-list"),T=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let u="",g=[],S=null;window.openFolderBrowser=function(s){S=s,g=s.value.split(",").map(p=>p.trim()).filter(p=>p),u="",w(),y(""),H.classList.add("show")};async function y(s){m.textContent=s||"Select a drive...",L.innerHTML='
`,M.style.display="none",L.textContent="";return}if(!E&&s!==D)return;const c=Array.isArray(g.logs)?g.logs:[];if(c.length===0&&!E){const e=g.filters&&(g.filters.level||g.filters.context||g.filters.search||g.filters.since||g.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";w.innerHTML=`
");for(const e of c){const a=(e.level||"?").toUpperCase(),o=a==="ERR"?"var(--bad-fg)":a==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",i=e.timestamp?new Date(e.timestamp).toLocaleString():"\u2014",n=e.context||"\u2014",r=(e.error||"").split(`
-`)[0],d=e.request&&e.request.ip||"";t+='
`,z.style.display="none",C.textContent="";return}if(!w&&s!==H)return;const c=Array.isArray(v.logs)?v.logs:[];if(c.length===0&&!w){const e=v.filters&&(v.filters.level||v.filters.context||v.filters.search||v.filters.since||v.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";E.innerHTML=`
");for(const e of c){const a=(e.level||"?").toUpperCase(),o=a==="ERR"?"var(--bad-fg)":a==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",i=e.timestamp?new Date(e.timestamp).toLocaleString():"\u2014",n=e.context||"\u2014",r=(e.error||"").split(`
+`)[0],d=e.request&&e.request.ip||"";t+='
'})}})(),(function(){"use strict";const b=[{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 l(r,d=""){if(!r||r.length===0){j.innerHTML='
No logs available
',x.textContent="0 lines",I.textContent="0 filtered";return}if(O=r,u=d?r.filter(h=>h.text&&h.text.toLowerCase().includes(d.toLowerCase())):r,x.textContent=`${r.length} lines`,I.textContent=d?`${u.length} of ${r.length} shown`:`${r.length} shown`,u.length===0){j.innerHTML=`
No logs match "${s(d)}"
`;return}j.innerHTML=u.map((h,$)=>p(h,$)).join(""),j.scrollTop=j.scrollHeight}async function v(){try{const d=(await getJSON("/api/v1/logs/containers")).containers||[],h=B.value;B.innerHTML='',d.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,c(h))}catch(r){console.error("Failed to load containers:",r)}}function c(r){const d=B.querySelector(`option[value="${r}"]`);d&&(H.textContent=d.dataset.image||"-",m.textContent=d.dataset.status||"-",m.style.color=d.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",L.textContent=w(d.dataset.created))}async function t(){const r=B.value;if(!r){j.innerHTML='
'})}})(),(function(){"use strict";const f=[{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",`
@@ -698,7 +698,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
`}).join("");w.innerHTML=e,w.scrollHeight-w.scrollTop-w.clientHeight<80&&(w.scrollTop=w.scrollHeight)}M.textContent=`${I.length} entries`,L.textContent=c?`${t.length} of ${I.length} shown`:`${I.length} shown`}async function E(){if(!D)return;p();const c=j.value;if(!c)return;const t=Math.max(1,Math.min(5e3,Number(z.value)||200)),e=(k.value||"").trim();w.innerHTML='
`}).join("");E.innerHTML=e,E.scrollHeight-E.scrollTop-E.clientHeight<80&&(E.scrollTop=E.scrollHeight)}z.textContent=`${m.length} entries`,C.textContent=c?`${t.length} of ${m.length} shown`:`${m.length} shown`}async function w(){if(!H)return;p();const c=j.value;if(!c)return;const t=Math.max(1,Math.min(5e3,Number(D.value)||200)),e=(b.value||"").trim();E.innerHTML='
@@ -752,7 +752,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const b=document.getElementById("snapshot-modal"),C=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),k=document.getElementById("snapshot-container-select"),z=document.getElementById("snapshot-details"),P=document.getElementById("snapshot-create-btn"),H=document.getElementById("snapshot-create-status");let A=null;async function x(){try{const u=await(await fetch("/api/v1/containers")).json();if(!u.success||!u.containers)return;k.innerHTML='';for(const v of u.containers){const D=document.createElement("option");D.value=v.id,D.textContent=`${v.name||v.id} (${v.image||"unknown"})`,D.dataset.name=v.name,D.dataset.image=v.image,D.dataset.status=v.status,D.dataset.created=v.created,k.appendChild(D)}}catch($){console.error("Failed to load containers:",$)}}function B($){if(!$||!$.value){z.style.display="none",A=null;return}A=$.value,document.getElementById("snapshot-image").textContent=$.dataset.image||"-",document.getElementById("snapshot-status").textContent=$.dataset.status||"-",document.getElementById("snapshot-created").textContent=$.dataset.created?new Date($.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=$.value.substring(0,12),z.style.display=""}async function w(){if(!A){H.textContent="Please select a container first",H.style.color="var(--bad-fg)";return}const $=document.getElementById("snapshot-name").value.trim();if(!$){H.textContent="Please enter a snapshot name",H.style.color="var(--bad-fg)";return}const u=document.getElementById("snapshot-leave-running").checked;P.disabled=!0,P.textContent="Creating...",H.textContent="";try{const D=await(await fetch(`/api/v1/containers/${encodeURIComponent(A)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$,leaveRunning:u})})).json();D.success?(H.textContent=`\u2713 Snapshot "${$}" created successfully`,H.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(H.textContent=`\u2717 Failed: ${D.error||"Unknown error"}`,H.style.color="var(--bad-fg)")}catch(v){H.textContent=`\u2717 Error: ${v.message}`,H.style.color="var(--bad-fg)"}finally{P.disabled=!1,P.textContent="\u{1F4BE} Create Snapshot"}}function M(){b.classList.add("show"),x()}function L(){b.classList.remove("show"),z.style.display="none",A=null,k.selectedIndex=0}C?.addEventListener("click",M),j?.addEventListener("click",L),wireModal(b,j),k?.addEventListener("change",$=>{const u=k.options[k.selectedIndex];B(u)}),P?.addEventListener("click",w),b?.querySelectorAll(".panel-tab").forEach($=>{$.addEventListener("click",()=>{b.querySelectorAll(".panel-tab").forEach(u=>u.classList.remove("active")),b.querySelectorAll(".panel-section").forEach(u=>u.classList.remove("active")),$.classList.add("active"),b.querySelector(`#${$.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
+
`);const f=document.getElementById("snapshot-modal"),B=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),b=document.getElementById("snapshot-container-select"),D=document.getElementById("snapshot-details"),A=document.getElementById("snapshot-create-btn"),P=document.getElementById("snapshot-create-status");let R=null;async function k(){try{const x=await(await fetch("/api/v1/containers")).json();if(!x.success||!x.containers)return;b.innerHTML='';for(const I of x.containers){const H=document.createElement("option");H.value=I.id,H.textContent=`${I.name||I.id} (${I.image||"unknown"})`,H.dataset.name=I.name,H.dataset.image=I.image,H.dataset.status=I.status,H.dataset.created=I.created,b.appendChild(H)}}catch(N){console.error("Failed to load containers:",N)}}function M(N){if(!N||!N.value){D.style.display="none",R=null;return}R=N.value,document.getElementById("snapshot-image").textContent=N.dataset.image||"-",document.getElementById("snapshot-status").textContent=N.dataset.status||"-",document.getElementById("snapshot-created").textContent=N.dataset.created?new Date(N.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=N.value.substring(0,12),D.style.display=""}async function E(){if(!R){P.textContent="Please select a container first",P.style.color="var(--bad-fg)";return}const N=document.getElementById("snapshot-name").value.trim();if(!N){P.textContent="Please enter a snapshot name",P.style.color="var(--bad-fg)";return}const x=document.getElementById("snapshot-leave-running").checked;A.disabled=!0,A.textContent="Creating...",P.textContent="";try{const H=await(await fetch(`/api/v1/containers/${encodeURIComponent(R)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:N,leaveRunning:x})})).json();H.success?(P.textContent=`\u2713 Snapshot "${N}" created successfully`,P.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(P.textContent=`\u2717 Failed: ${H.error||"Unknown error"}`,P.style.color="var(--bad-fg)")}catch(I){P.textContent=`\u2717 Error: ${I.message}`,P.style.color="var(--bad-fg)"}finally{A.disabled=!1,A.textContent="\u{1F4BE} Create Snapshot"}}function z(){f.classList.add("show"),k()}function C(){f.classList.remove("show"),D.style.display="none",R=null,b.selectedIndex=0}B?.addEventListener("click",z),j?.addEventListener("click",C),wireModal(f,j),b?.addEventListener("change",N=>{const x=b.options[b.selectedIndex];M(x)}),A?.addEventListener("click",E),f?.querySelectorAll(".panel-tab").forEach(N=>{N.addEventListener("click",()=>{f.querySelectorAll(".panel-tab").forEach(x=>x.classList.remove("active")),f.querySelectorAll(".panel-section").forEach(x=>x.classList.remove("active")),N.classList.add("active"),f.querySelector(`#${N.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
\u{1F3AC} Smart Arr Connect
@@ -831,19 +831,19 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const b=document.getElementById("arr-setup-modal"),C=document.getElementById("arr-setup-btn"),j=document.getElementById("arr-setup-cancel"),k=document.getElementById("smart-connect-btn"),z=document.getElementById("smart-phase-detect"),P=document.getElementById("smart-phase-credentials"),H=document.getElementById("smart-phase-progress"),A=document.getElementById("smart-phase-results"),x=document.getElementById("smart-detect-results"),B=document.getElementById("smart-credential-inputs"),w=document.getElementById("smart-progress-steps"),M=document.getElementById("smart-results-content"),L=document.getElementById("smart-plex-libraries"),$=document.getElementById("smart-retry-btn");let u=null;const v={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 I(f){z.style.display=f==="detect"?"block":"none",P.style.display=f==="credentials"?"block":"none",H.style.display=f==="progress"?"block":"none",A.style.display=f==="results"?"block":"none"}function R(f){const E={connected:{bg:"var(--ok-fg)",icon:"✓",text:"Connected"},needs_key:{bg:"#f39c12",icon:"🔑",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"—",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"✗",text:"Error"}},s=E[f]||E.not_found;return`${s.icon} ${s.text}`}async function N(){I("detect"),x.style.display="none";try{if(u=await(await fetch("/api/v1/arr/smart-detect")).json(),!u.success){x.innerHTML=`
`,x.style.display="block"}}function O(f){let E="";const s=f.services,p=["radarr","sonarr","prowlarr"];for(const c of p){const t=s[c];if(!t||t.status==="not_found"&&!t.url)continue;const e=v[c],a=D[c],o=t.status==="connected";E+=`
`,k.style.display="block"}}function O(y){let w="";const s=y.services,p=["radarr","sonarr","prowlarr"];for(const c of p){const t=s[c];if(!t||t.status==="not_found"&&!t.url)continue;const e=I[c],a=H[c],o=t.status==="connected";w+=`
${e}${a}
@@ -864,40 +864,40 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
`}B.innerHTML=E}window.smartTestConnection=async function(f){const E=document.getElementById(`smart-${f}-url`),s=document.getElementById(`smart-${f}-key`),p=document.getElementById(`smart-${f}-status`),l=E?.value.trim(),g=s?.value.trim();if(!l||!g){p.innerHTML='Enter URL and API key';return}p.innerHTML='';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:f,url:l,apiKey:g})})).json();t.success?p.innerHTML=`✓ ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}`:p.innerHTML=`✗ ${escapeHtml(t.error)}`}catch(c){p.innerHTML=`✗ ${escapeHtml(c.message)}`}};async function m(){I("progress"),w.innerHTML='
Connecting services...
';const f={};for(const s of["radarr","sonarr","prowlarr"]){const p=document.getElementById(`smart-${s}-url`)?.value.trim(),l=document.getElementById(`smart-${s}-key`)?.value.trim();l&&p?f[s]={apiKey:l,url:p}:l&&(f[s]={apiKey:l})}const E={services:Object.keys(f).length>0?f: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 p=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)})).json();let l="";for(const g of p.steps||[]){const c=g.status==="success"?'✓':'✗',t=g.status==="success"?"var(--muted)":"var(--bad-fg)";l+=`
+
`}M.innerHTML=w}window.smartTestConnection=async function(y){const w=document.getElementById(`smart-${y}-url`),s=document.getElementById(`smart-${y}-key`),p=document.getElementById(`smart-${y}-status`),l=w?.value.trim(),v=s?.value.trim();if(!l||!v){p.innerHTML='Enter URL and API key';return}p.innerHTML='';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:y,url:l,apiKey:v})})).json();t.success?p.innerHTML=`✓ ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}`:p.innerHTML=`✗ ${escapeHtml(t.error)}`}catch(c){p.innerHTML=`✗ ${escapeHtml(c.message)}`}};async function u(){m("progress"),E.innerHTML='
Connecting services...
';const y={};for(const s of["radarr","sonarr","prowlarr"]){const p=document.getElementById(`smart-${s}-url`)?.value.trim(),l=document.getElementById(`smart-${s}-key`)?.value.trim();l&&p?y[s]={apiKey:l,url:p}:l&&(y[s]={apiKey:l})}const w={services:Object.keys(y).length>0?y: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 p=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)})).json();let l="";for(const v of p.steps||[]){const c=v.status==="success"?'✓':'✗',t=v.status==="success"?"var(--muted)":"var(--bad-fg)";l+=`
"}}}async function y(e,a){try{var o=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,...a})}),i=await o.json();i.success?showNotification("Schedule updated for "+e,"success"):(showNotification("Update failed: "+(i.error||"Unknown"),"error"),m())}catch(n){showNotification("Error: "+n.message,"error")}}async function S(e){try{var a=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(e),{method:"POST",headers:{"Content-Type":"application/json"}}),o=await a.json();o.success?showNotification("Backup started for "+e+"!","success"):showNotification("Backup failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function f(e){if(confirm("Remove backup schedule for "+e+"?"))try{var a=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(e),{method:"DELETE"}),o=await a.json();o.success?(showNotification("Schedule removed for "+e,"success"),m()):showNotification("Delete failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function E(){var e=document.getElementById("new-schedule-appid")?.value?.trim(),a=document.getElementById("new-schedule-interval")?.value||"daily",o=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!e){showNotification("Please enter an App ID","warning");return}try{var i=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,schedule:a,retention:{keep:o},enabled:!0})}),n=await i.json();if(n.success){showNotification("Schedule created for "+e,"success"),m();var r=document.getElementById("new-schedule-appid");r&&(r.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(d){showNotification("Error: "+d.message,"error")}}async function s(){if(R){R.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/files"),a=await e.json();if(!a.success)throw new Error(a.error||"Failed to load");var o=a.files||[];if(o.length===0){R.innerHTML='
"}}}window.__restoreServerBackup=async function(e){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var a=await secureFetch("/api/v1/backups/restore/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),o=await a.json();o.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(o.error||"Unknown error"),"error")}catch(i){showNotification("Restore error: "+i.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",m),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",s),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",l),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",p);async function l(){if(N){try{var e=await fetch("/api/v1/license/status"),a=await e.json();if(a.tier!=="premium"){N.innerHTML=`
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
"}}}async function g(e,a){try{var o=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,...a})}),i=await o.json();i.success?showNotification("Schedule updated for "+e,"success"):(showNotification("Update failed: "+(i.error||"Unknown"),"error"),u())}catch(n){showNotification("Error: "+n.message,"error")}}async function S(e){try{var a=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(e),{method:"POST",headers:{"Content-Type":"application/json"}}),o=await a.json();o.success?showNotification("Backup started for "+e+"!","success"):showNotification("Backup failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function y(e){if(confirm("Remove backup schedule for "+e+"?"))try{var a=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(e),{method:"DELETE"}),o=await a.json();o.success?(showNotification("Schedule removed for "+e,"success"),u()):showNotification("Delete failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function w(){var e=document.getElementById("new-schedule-appid")?.value?.trim(),a=document.getElementById("new-schedule-interval")?.value||"daily",o=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!e){showNotification("Please enter an App ID","warning");return}try{var i=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,schedule:a,retention:{keep:o},enabled:!0})}),n=await i.json();if(n.success){showNotification("Schedule created for "+e,"success"),u();var r=document.getElementById("new-schedule-appid");r&&(r.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(d){showNotification("Error: "+d.message,"error")}}async function s(){if(L){L.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/files"),a=await e.json();if(!a.success)throw new Error(a.error||"Failed to load");var o=a.files||[];if(o.length===0){L.innerHTML='
"}}}window.__restoreServerBackup=async function(e){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var a=await secureFetch("/api/v1/backups/restore/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),o=await a.json();o.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(o.error||"Unknown error"),"error")}catch(i){showNotification("Restore error: "+i.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",u),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",s),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",l),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",p);async function l(){if(T){try{var e=await fetch("/api/v1/license/status"),a=await e.json();if(a.tier!=="premium"){T.innerHTML=`
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
Configuration differs \u2014 restoring will replace current settings
':r+='
No changes
',r+="
"}r+='
',document.body.insertAdjacentHTML("beforeend",r),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function($){$.target===this&&this.remove()})}catch($){showNotification("Compare error: "+$.message,"error")}}async function t(e,a){if(confirm("Restore "+a+" for "+e+`?
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var o=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),i=await o.json();i.success?(showNotification(e+" restored to "+a,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(i.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`
@@ -1305,11 +1305,11 @@ This will replace current configuration, credentials, and data. Containers will
- `);const b=document.getElementById("stats-modal"),C=document.getElementById("container-stats-btn"),j=document.getElementById("stats-cancel"),k=document.getElementById("stats-refresh-btn"),z=document.getElementById("stats-auto-refresh"),P=document.getElementById("stats-container"),H=document.getElementById("stats-aggregated-container"),A=document.getElementById("stats-alerts-container"),x=document.getElementById("stats-last-update");let B=null,w=null;function M(l){if(l===0||!l)return"0 B";const g=1024,c=["B","KB","MB","GB"],t=Math.floor(Math.log(l)/Math.log(g));return parseFloat((l/Math.pow(g,t)).toFixed(1))+" "+c[t]}function L(l){return l<30?"#2ecc71":l<70?"#f39c12":"#e74c3c"}function $(l){return l<50?"#2ecc71":l<80?"#f39c12":"#e74c3c"}async function u(){try{let l=null,g=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(l=e.stats,g=!0,w=e.stats)}catch{}if(!g){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){l={};for(const a of e.stats)l[a.name]={name:a.name,current:{cpu:a.cpu,memory:{percent:a.memory.percent,usage:a.memory.used,limit:a.memory.limit,usageMB:Math.round(a.memory.used/1048576),limitMB:Math.round(a.memory.limit/1048576)},network:{rxBytes:a.network.rx,txBytes:a.network.tx,rxMB:(a.network.rx/1048576).toFixed(1),txMB:(a.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:a.status};w=l}}if(!l||Object.keys(l).length===0){P.innerHTML='
${escapeHtml(t)}
- last ${q.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${o.toFixed(1)}${e}
+ last ${_.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${o.toFixed(1)}${e}
- `}function s(){if(!N)return;const l=w||{},g=N.value,c=Object.entries(l);if(c.length===0){N.innerHTML='';return}N.innerHTML=c.map(([t,e])=>``).join(""),g&&l[g]&&(N.value=g)}async function p(){if(!O||!N)return;const l=N.value;if(!l){O.innerHTML='
';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(l)}?startTime=${c}&endTime=${g}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const a=e.samples||[],o=e.tier||"raw";if(a.length===0){O.innerHTML=`
\u{1F4CA}No data for the last ${y}. Tier: ${f(o)}.
`;return}const i=o==="raw",n=i?U=>U.cpu?.percent:U=>U.cpu?.avg,r=i?U=>U.memory?.percent:U=>U.memory?.avgPercent,d=i?U=>U.network?.rxMB||0:U=>U.network?.rxMB||0,h=i?U=>U.network?.txMB||0:U=>U.network?.txMB||0;let T=`
+ `}function s(){if(!T)return;const l=E||{},v=T.value,c=Object.entries(l);if(c.length===0){T.innerHTML='';return}T.innerHTML=c.map(([t,e])=>``).join(""),v&&l[v]&&(T.value=v)}async function p(){if(!O||!T)return;const l=T.value;if(!l){O.innerHTML='
';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(l)}?startTime=${c}&endTime=${v}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const a=e.samples||[],o=e.tier||"raw";if(a.length===0){O.innerHTML=`
\u{1F4CA}No data for the last ${g}. Tier: ${y(o)}.
@@ -1561,24 +1561,24 @@ This will replace current configuration, credentials, and data. Containers will
-
`);const b=document.getElementById("health-modal"),C=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),k=document.getElementById("health-refresh-btn"),z=document.getElementById("health-status-container"),P=document.getElementById("health-incidents-container"),H=document.getElementById("health-config-container"),A=document.getElementById("health-last-update"),x=document.getElementById("health-add-btn"),B=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),M=document.getElementById("health-form-cancel"),L=document.getElementById("health-form-save"),$="dashcaddy-health-settings",u={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},v=document.getElementById("health-global-save"),D=document.getElementById("health-global-reset"),I=document.getElementById("health-global-status"),R=document.getElementById("health-setting-retention"),N=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),m=document.getElementById("health-setting-max-entries"),y=document.getElementById("health-setting-disk-threshold");function S(){try{const i=safeGet($),n=i?JSON.parse(i):{};return Object.assign({},u,n)}catch{return Object.assign({},u)}}function f(){const i=S();R&&(R.value=i.retentionDays),N&&(N.value=i.pollingInterval),O&&(O.value=i.statsPollingInterval),m&&(m.value=i.maxEntriesPerService),y&&(y.value=i.diskUsageThreshold)}function E(){const i={retentionDays:Math.max(1,Math.min(3650,parseInt(R?.value)||u.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(N?.value)||u.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||u.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(m?.value)||u.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(y?.value)||u.diskUsageThreshold))};try{safeSet($,JSON.stringify(i)),f(),I&&(I.textContent="Saved \u2713",I.style.color="var(--ok-fg)",setTimeout(()=>{I&&(I.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(n){I&&(I.textContent="Save failed",I.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+n.message,"error")}}function s(){try{safeSet($,JSON.stringify(u))}catch{}f(),I&&(I.textContent="Reset to defaults \u2713",I.style.color="var(--ok-fg)",setTimeout(()=>{I&&(I.textContent="")},2500))}f(),v?.addEventListener("click",E),D?.addEventListener("click",s);let p=null;function l(i){return i>=99.9?"var(--ok-fg)":i>=95?"#f39c12":"var(--bad-fg)"}function g(i){const n={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${i}`}async function c(){try{const n=await(await fetch("/api/v1/health-checks/status")).json();if(!n.success||!n.status||Object.keys(n.status).length===0){z.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const r=Object.values(n.status);let d='
';d+='
',d+='
Service
Status
',d+='
Uptime 24h
Uptime 7d
',d+='
Avg Response
Last Check
';for(const h of r){const T=h.status==="up",U=T?"var(--dot-ok)":"var(--dot-bad)",q=h.uptime?.["24h"]??"-",F=h.uptime?.["7d"]??"-",_=h.avgResponseTime!=null?Math.round(h.avgResponseTime)+"ms":"-",J=h.timestamp?timeAgo(h.timestamp):"-";d+=`
`,d+=`
${escapeHtml(h.name||h.serviceId)}
`,d+=`
${T?"Up":"Down"}
`,d+=`
${typeof q=="number"?q.toFixed(1)+"%":q}
`,d+=`
${typeof F=="number"?F.toFixed(1)+"%":F}
`,d+=`
${_}
`,d+=`
${J}
`,d+="
",d+=`
Loading details...
`}d+="
",z.innerHTML=d,A.textContent="Updated "+new Date().toLocaleTimeString(),z.querySelectorAll("tr[data-health-id]").forEach(h=>{h.addEventListener("click",async()=>{const T=h.dataset.healthId,U=document.getElementById("health-detail-"+T);if(U){if(U.style.display!=="none"){U.style.display="none";return}U.style.display="";try{const F=await(await fetch(`/api/v1/health-checks/${T}/stats?hours=24`)).json();if(F.success&&F.stats){const _=F.stats,J=_.responseTime||{};U.querySelector("td").innerHTML=`
+ `);const f=document.getElementById("health-modal"),B=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),b=document.getElementById("health-refresh-btn"),D=document.getElementById("health-status-container"),A=document.getElementById("health-incidents-container"),P=document.getElementById("health-config-container"),R=document.getElementById("health-last-update"),k=document.getElementById("health-add-btn"),M=document.getElementById("health-config-form"),E=document.getElementById("health-form-title"),z=document.getElementById("health-form-cancel"),C=document.getElementById("health-form-save"),N="dashcaddy-health-settings",x={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},I=document.getElementById("health-global-save"),H=document.getElementById("health-global-reset"),m=document.getElementById("health-global-status"),L=document.getElementById("health-setting-retention"),T=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),u=document.getElementById("health-setting-max-entries"),g=document.getElementById("health-setting-disk-threshold");function S(){try{const i=safeGet(N),n=i?JSON.parse(i):{};return Object.assign({},x,n)}catch{return Object.assign({},x)}}function y(){const i=S();L&&(L.value=i.retentionDays),T&&(T.value=i.pollingInterval),O&&(O.value=i.statsPollingInterval),u&&(u.value=i.maxEntriesPerService),g&&(g.value=i.diskUsageThreshold)}function w(){const i={retentionDays:Math.max(1,Math.min(3650,parseInt(L?.value)||x.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(T?.value)||x.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||x.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(u?.value)||x.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(g?.value)||x.diskUsageThreshold))};try{safeSet(N,JSON.stringify(i)),y(),m&&(m.textContent="Saved \u2713",m.style.color="var(--ok-fg)",setTimeout(()=>{m&&(m.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(n){m&&(m.textContent="Save failed",m.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+n.message,"error")}}function s(){try{safeSet(N,JSON.stringify(x))}catch{}y(),m&&(m.textContent="Reset to defaults \u2713",m.style.color="var(--ok-fg)",setTimeout(()=>{m&&(m.textContent="")},2500))}y(),I?.addEventListener("click",w),H?.addEventListener("click",s);let p=null;function l(i){return i>=99.9?"var(--ok-fg)":i>=95?"#f39c12":"var(--bad-fg)"}function v(i){const n={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${i}`}async function c(){try{const n=await(await fetch("/api/v1/health-checks/status")).json();if(!n.success||!n.status||Object.keys(n.status).length===0){D.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const r=Object.values(n.status);let d='
';d+='
',d+='
Service
Status
',d+='
Uptime 24h
Uptime 7d
',d+='
Avg Response
Last Check
';for(const h of r){const $=h.status==="up",U=$?"var(--dot-ok)":"var(--dot-bad)",_=h.uptime?.["24h"]??"-",F=h.uptime?.["7d"]??"-",q=h.avgResponseTime!=null?Math.round(h.avgResponseTime)+"ms":"-",J=h.timestamp?timeAgo(h.timestamp):"-";d+=`
';for(const q of U){const F=q.status==="resolved",_=F&&q.duration?q.duration<6e4?Math.round(q.duration/1e3)+"s":Math.round(q.duration/6e4)+"m":"-";h+='
',h+=`
${escapeHtml(q.serviceId)}
`,h+=`
${escapeHtml(q.type)}
`,h+=`
${g(q.severity)}
`,h+=`
${q.status}
`,h+=`
${_}
`,h+=`
${timeAgo(q.createdAt)}
`,h+="
"}h+="
"}P.innerHTML=h||'
\u{1F6A8}No incidents recorded yet.
'}catch(i){P.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}async function e(){try{const n=await(await fetch("/api/v1/health-checks/status")).json(),r=n.success&&n.status?Object.values(n.status):[];if(r.length===0){H.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
';return}let d='
';d+='
Service
Status
SLA Target
Actions
';for(const h of r){const T=h.status==="up";d+='
',d+=`
${escapeHtml(h.name||h.serviceId)}
`,d+=`
${T?"Up":"Down"}
`,d+=`
${h.sla?.target?h.sla.target+"%":"-"}
`,d+='
',d+=``,d+=``,d+="
"}d+="
",H.innerHTML=d}catch(i){H.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}function a(i,n,r,d,h,T,U){p=i||null,w.textContent=i?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=i||"",document.getElementById("health-form-id").disabled=!!i,document.getElementById("health-form-name").value=n||"",document.getElementById("health-form-url").value=r||"",document.getElementById("health-form-timeout").value=d||1e4,document.getElementById("health-form-codes").value=h||"200",document.getElementById("health-form-sla").value=T||99.9,document.getElementById("health-form-slow").value=U||5e3,B.style.display="",x.style.display="none"}function o(){B.style.display="none",x.style.display="",p=null}x?.addEventListener("click",()=>a("","","",1e4,"200",99.9,5e3)),M?.addEventListener("click",o),L?.addEventListener("click",async()=>{const i=p||document.getElementById("health-form-id").value.trim();if(!i)return showNotification("Service ID is required","warning");const n=document.getElementById("health-form-url").value.trim();if(!n)return showNotification("URL is required","warning");const r=document.getElementById("health-form-codes").value.split(",").map(h=>parseInt(h.trim())).filter(Boolean),d={name:document.getElementById("health-form-name").value.trim()||i,url:n,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:r.length?r:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{L.textContent="Saving...",L.disabled=!0;const T=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(i)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();if(!T.success)throw new Error(T.error||"Save failed");o(),e(),c()}catch(h){showNotification("Error: "+h.message,"error")}finally{L.textContent="Save",L.disabled=!1}}),document.addEventListener("health-edit",async i=>{const n=i.detail;a(n,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async i=>{const n=i.detail;if(confirm(`Delete health check for "${n}"?`))try{const d=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(n)}/configure`,{method:"DELETE"})).json();if(!d.success)throw new Error(d.error);e(),c()}catch(r){showNotification("Error: "+r.message,"error")}}),C?.addEventListener("click",()=>{b?.classList.add("show"),c()}),wireModal(b,j),k?.addEventListener("click",c),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",t),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",e)})(),(function(){injectModal("updates-modal",`
+
${escapeHtml(_.message)}
+
Started ${timeAgo(_.createdAt)} \xB7 ${_.occurrences||1} occurrence(s)
';for(const _ of U){const F=_.status==="resolved",q=F&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";h+='
',h+=`
${escapeHtml(_.serviceId)}
`,h+=`
${escapeHtml(_.type)}
`,h+=`
${v(_.severity)}
`,h+=`
${_.status}
`,h+=`
${q}
`,h+=`
${timeAgo(_.createdAt)}
`,h+="
"}h+="
"}A.innerHTML=h||'
\u{1F6A8}No incidents recorded yet.
'}catch(i){A.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}async function e(){try{const n=await(await fetch("/api/v1/health-checks/status")).json(),r=n.success&&n.status?Object.values(n.status):[];if(r.length===0){P.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
';return}let d='
';d+='
Service
Status
SLA Target
Actions
';for(const h of r){const $=h.status==="up";d+='
',d+=`
${escapeHtml(h.name||h.serviceId)}
`,d+=`
${$?"Up":"Down"}
`,d+=`
${h.sla?.target?h.sla.target+"%":"-"}
`,d+='
',d+=``,d+=``,d+="
"}d+="
",P.innerHTML=d}catch(i){P.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}function a(i,n,r,d,h,$,U){p=i||null,E.textContent=i?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=i||"",document.getElementById("health-form-id").disabled=!!i,document.getElementById("health-form-name").value=n||"",document.getElementById("health-form-url").value=r||"",document.getElementById("health-form-timeout").value=d||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,M.style.display="",k.style.display="none"}function o(){M.style.display="none",k.style.display="",p=null}k?.addEventListener("click",()=>a("","","",1e4,"200",99.9,5e3)),z?.addEventListener("click",o),C?.addEventListener("click",async()=>{const i=p||document.getElementById("health-form-id").value.trim();if(!i)return showNotification("Service ID is required","warning");const n=document.getElementById("health-form-url").value.trim();if(!n)return showNotification("URL is required","warning");const r=document.getElementById("health-form-codes").value.split(",").map(h=>parseInt(h.trim())).filter(Boolean),d={name:document.getElementById("health-form-name").value.trim()||i,url:n,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:r.length?r:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{C.textContent="Saving...",C.disabled=!0;const $=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(i)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();if(!$.success)throw new Error($.error||"Save failed");o(),e(),c()}catch(h){showNotification("Error: "+h.message,"error")}finally{C.textContent="Save",C.disabled=!1}}),document.addEventListener("health-edit",async i=>{const n=i.detail;a(n,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async i=>{const n=i.detail;if(confirm(`Delete health check for "${n}"?`))try{const d=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(n)}/configure`,{method:"DELETE"})).json();if(!d.success)throw new Error(d.error);e(),c()}catch(r){showNotification("Error: "+r.message,"error")}}),B?.addEventListener("click",()=>{f?.classList.add("show"),c()}),wireModal(f,j),b?.addEventListener("click",c),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",t),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",e)})(),(function(){injectModal("updates-modal",`
\u2B06\uFE0F Update Management
@@ -1652,17 +1652,17 @@ This will replace current configuration, credentials, and data. Containers will
- `);const b=document.getElementById("updates-modal"),C=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),k=document.getElementById("updates-check-btn"),z=document.getElementById("updates-available-container"),P=document.getElementById("updates-history-container"),H=document.getElementById("updates-auto-container"),A=document.getElementById("updates-last-check");async function x(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){z.innerHTML='
';for(const n of e){const r=(()=>{const d=window.APPS||[];for(const h of d)if(h.containerId===n.containerId||h.name===n.containerName||h.id===n.containerName)return h.id;return n.containerName})();a+=`
`,a+=`
${escapeHtml(n.containerName)}
`,a+=`
${escapeHtml(n.imageName)}
`,a+=`
${escapeHtml(n.currentDigest)}
`,a+=`
${escapeHtml(n.latestDigest)}
`,a+='
',a+=``,a+=``,a+="
"}a+="
",z.innerHTML=a,A.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),i=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),i&&e.length>0&&(i.style.display=""),window._pendingUpdates=e,z.querySelectorAll(".update-now-btn").forEach(n=>{n.addEventListener("click",async()=>{const r=n.dataset.id,d=n.dataset.name;if(confirm(`Update "${d}" to the latest version? The container will restart.`)){n.textContent="Updating...",n.disabled=!0;try{const T=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(T.success)n.textContent="Done!",n.style.background="var(--ok-fg)",setTimeout(()=>x(),2e3);else throw new Error(T.error||"Update failed")}catch(h){n.textContent="Failed",n.style.color="var(--bad-fg)",showNotification("Update error: "+h.message,"error"),setTimeout(()=>{n.textContent="Update",n.disabled=!1,n.style.color="",n.style.background=""},3e3)}}})}),z.querySelectorAll(".rollback-btn").forEach(n=>{n.addEventListener("click",async()=>{const r=n.dataset.id,d=n.dataset.name;if(confirm(`Rollback "${d}" to its previous version?`)){n.textContent="Rolling back...",n.disabled=!0;try{const T=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(r)}`,{method:"POST"})).json();if(T.success)n.textContent="Rolled back!",setTimeout(()=>x(),2e3);else throw new Error(T.error||"Rollback failed")}catch(h){n.textContent="Failed",showNotification("Rollback error: "+h.message,"error"),setTimeout(()=>{n.textContent="Rollback",n.disabled=!1},3e3)}}})})}catch(c){z.innerHTML=`
Failed: ${escapeHtml(c.message)}
`}}async function B(){const c=window._pendingUpdates||[];if(!c.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${c.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,a=0;for(const o of c)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?e++:a++}catch{a++}t.textContent="\u2705 Done",showNotification(`Update all: ${e} succeeded, ${a} failed.`,e>0&&a===0?"success":"error"),setTimeout(()=>{t.textContent="\u2B06\uFE0F Update All",t.disabled=!1,x()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",B);async function w(){k.textContent="\u{1F50D} Checking...",k.disabled=!0;try{const t=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!t.success)throw new Error(t.error);k.textContent="\u2705 Done!",await x()}catch(c){k.textContent="\u274C Failed",showNotification("Check error: "+c.message,"error")}setTimeout(()=>{k.textContent="\u{1F50D} Check for Updates",k.disabled=!1},3e3)}async function M(){try{P.innerHTML='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';n+='
',n+='
Container
Schedule
Window
Rollback
Last Run
Actions
';for(const r of o){const d=r.name||r.Names?.[0]?.replace(/^\//,"")||r.Id?.substring(0,12),h=r.containerId||r.Id,T=i[h]||{},U=T.enabled?T.schedule||"weekly":"",q=T.autoRollback!==!1,F=T.maintenanceWindow||"",_=T.lastAutoUpdate?timeAgo(T.lastAutoUpdate):"Never";n+=`
`,n+=`
${escapeHtml(d)}
`,n+=`
+ `);const f=document.getElementById("updates-modal"),B=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),b=document.getElementById("updates-check-btn"),D=document.getElementById("updates-available-container"),A=document.getElementById("updates-history-container"),P=document.getElementById("updates-auto-container"),R=document.getElementById("updates-last-check");async function k(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){D.innerHTML='
';for(const n of e){const r=(()=>{const d=window.APPS||[];for(const h of d)if(h.containerId===n.containerId||h.name===n.containerName||h.id===n.containerName)return h.id;return n.containerName})();a+=`
`,a+=`
${escapeHtml(n.containerName)}
`,a+=`
${escapeHtml(n.imageName)}
`,a+=`
${escapeHtml(n.currentDigest)}
`,a+=`
${escapeHtml(n.latestDigest)}
`,a+='
',a+=``,a+=``,a+="
"}a+="
",D.innerHTML=a,R.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),i=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),i&&e.length>0&&(i.style.display=""),window._pendingUpdates=e,D.querySelectorAll(".update-now-btn").forEach(n=>{n.addEventListener("click",async()=>{const r=n.dataset.id,d=n.dataset.name;if(confirm(`Update "${d}" to the latest version? The container will restart.`)){n.textContent="Updating...",n.disabled=!0;try{const $=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if($.success)n.textContent="Done!",n.style.background="var(--ok-fg)",setTimeout(()=>k(),2e3);else throw new Error($.error||"Update failed")}catch(h){n.textContent="Failed",n.style.color="var(--bad-fg)",showNotification("Update error: "+h.message,"error"),setTimeout(()=>{n.textContent="Update",n.disabled=!1,n.style.color="",n.style.background=""},3e3)}}})}),D.querySelectorAll(".rollback-btn").forEach(n=>{n.addEventListener("click",async()=>{const r=n.dataset.id,d=n.dataset.name;if(confirm(`Rollback "${d}" to its previous version?`)){n.textContent="Rolling back...",n.disabled=!0;try{const $=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(r)}`,{method:"POST"})).json();if($.success)n.textContent="Rolled back!",setTimeout(()=>k(),2e3);else throw new Error($.error||"Rollback failed")}catch(h){n.textContent="Failed",showNotification("Rollback error: "+h.message,"error"),setTimeout(()=>{n.textContent="Rollback",n.disabled=!1},3e3)}}})})}catch(c){D.innerHTML=`
Failed: ${escapeHtml(c.message)}
`}}async function M(){const c=window._pendingUpdates||[];if(!c.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${c.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,a=0;for(const o of c)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?e++:a++}catch{a++}t.textContent="\u2705 Done",showNotification(`Update all: ${e} succeeded, ${a} failed.`,e>0&&a===0?"success":"error"),setTimeout(()=>{t.textContent="\u2B06\uFE0F Update All",t.disabled=!1,k()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",M);async function E(){b.textContent="\u{1F50D} Checking...",b.disabled=!0;try{const t=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!t.success)throw new Error(t.error);b.textContent="\u2705 Done!",await k()}catch(c){b.textContent="\u274C Failed",showNotification("Check error: "+c.message,"error")}setTimeout(()=>{b.textContent="\u{1F50D} Check for Updates",b.disabled=!1},3e3)}async function z(){try{A.innerHTML='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';n+='
',n+='
Container
Schedule
Window
Rollback
Last Run
Actions
';for(const r of o){const d=r.name||r.Names?.[0]?.replace(/^\//,"")||r.Id?.substring(0,12),h=r.containerId||r.Id,$=i[h]||{},U=$.enabled?$.schedule||"weekly":"",_=$.autoRollback!==!1,F=$.maintenanceWindow||"",q=$.lastAutoUpdate?timeAgo($.lastAutoUpdate):"Never";n+=`
`}}const $=document.getElementById("dashcaddy-current-version"),u=document.getElementById("dashcaddy-update-badge"),v=document.getElementById("dashcaddy-update-details"),D=document.getElementById("dashcaddy-new-version"),I=document.getElementById("dashcaddy-changelog"),R=document.getElementById("dashcaddy-apply-btn"),N=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),m=document.getElementById("dashcaddy-status-bar"),y=document.getElementById("dashcaddy-history-container");let S=null;function f(c,t){m&&(m.style.display="block",m.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",m.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",m.textContent=c)}async function E(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;$.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{$.textContent="Unable to fetch version"}}async function s(c){c||(N.textContent="Checking...",N.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(S=e,e.success&&e.available&&e.remote){u.style.display="",v.style.display="",D.textContent="v"+e.remote.version,I.textContent=e.remote.changelog||"No changelog available.";const a=document.getElementById("updates-btn");if(a&&!a.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",a.style.position="relative",a.appendChild(i)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(i)}}else u.style.display="none",v.style.display="none",await E(),c||f("You are running the latest version.","success");c||(N.textContent="Check for Updates",N.disabled=!1)}catch(t){c||(f("Failed to check: "+t.message,"error"),N.textContent="Check for Updates",N.disabled=!1)}}async function p(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;R.textContent="Updating...",R.disabled=!0,f("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return f("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),R.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(c){throw f("Update failed: "+c.message,"error"),R.textContent="Update Now",R.disabled=!1,c}}async function l(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){y.innerHTML='
\u{1F4E6}No self-update history.
';return}let a='
';a+='
When
Version
From
Status
';for(const o of e){const i=o.status==="success"?"\u2713 success":o.status==="pending"?"\u23F3 pending":o.status==="partial"?"\u26A0 partial":"\u2717 "+o.status,n=o.status==="success"?"var(--ok-fg)":o.status==="pending"?"var(--muted)":"var(--bad-fg)";a+='
`}}const N=document.getElementById("dashcaddy-current-version"),x=document.getElementById("dashcaddy-update-badge"),I=document.getElementById("dashcaddy-update-details"),H=document.getElementById("dashcaddy-new-version"),m=document.getElementById("dashcaddy-changelog"),L=document.getElementById("dashcaddy-apply-btn"),T=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),u=document.getElementById("dashcaddy-status-bar"),g=document.getElementById("dashcaddy-history-container");let S=null;function y(c,t){u&&(u.style.display="block",u.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",u.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",u.textContent=c)}async function w(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;N.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{N.textContent="Unable to fetch version"}}async function s(c){c||(T.textContent="Checking...",T.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(S=e,e.success&&e.available&&e.remote){x.style.display="",I.style.display="",H.textContent="v"+e.remote.version,m.textContent=e.remote.changelog||"No changelog available.";const a=document.getElementById("updates-btn");if(a&&!a.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",a.style.position="relative",a.appendChild(i)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(i)}}else x.style.display="none",I.style.display="none",await w(),c||y("You are running the latest version.","success");c||(T.textContent="Check for Updates",T.disabled=!1)}catch(t){c||(y("Failed to check: "+t.message,"error"),T.textContent="Check for Updates",T.disabled=!1)}}async function p(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;L.textContent="Updating...",L.disabled=!0,y("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return y("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),L.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(c){throw y("Update failed: "+c.message,"error"),L.textContent="Update Now",L.disabled=!1,c}}async function l(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){g.innerHTML='
\u{1F4E6}No self-update history.
';return}let a='
';a+='
When
Version
From
Status
';for(const o of e){const i=o.status==="success"?"\u2713 success":o.status==="pending"?"\u23F3 pending":o.status==="partial"?"\u26A0 partial":"\u2717 "+o.status,n=o.status==="success"?"var(--ok-fg)":o.status==="pending"?"var(--muted)":"var(--bad-fg)";a+='
"}}async function v(){try{const t=await(await fetch("/api/v1/system/rollback-versions")).json(),e=t.success&&t.versions?t.versions:[];if(e.length===0){showNotification("No rollback versions available.","info");return}const a=prompt(`Available rollback versions:
`+e.join(`
`)+`
-Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification("Invalid version: "+a,"error");return}if(!confirm("Rollback DashCaddy to v"+a+"? The container will restart."))return;f("Rolling back to v"+a+"...","info");const i=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:a})})).json();if(i.success)f("Rollback to v"+a+" initiated. Container will restart.","success");else throw new Error(i.error||"Rollback failed")}catch(c){f("Rollback failed: "+c.message,"error")}}N?.addEventListener("click",()=>s(!1)),R?.addEventListener("click",()=>p().catch(()=>{})),O?.addEventListener("click",g),k?.addEventListener("click",w),C?.addEventListener("click",()=>{b?.classList.add("show"),x()}),wireModal(b,j),window.openUpdateModal=function(c){b?.classList.add("show"),x().then(()=>{if(!c)return;const t=z.querySelector(`[data-app-id="${c}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",M),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",L),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{E(),l(),S||s(!0)}),window.dcApplyUpdate=p,window.dcCheckForUpdate=s,setTimeout(()=>s(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
+Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification("Invalid version: "+a,"error");return}if(!confirm("Rollback DashCaddy to v"+a+"? The container will restart."))return;y("Rolling back to v"+a+"...","info");const i=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:a})})).json();if(i.success)y("Rollback to v"+a+" initiated. Container will restart.","success");else throw new Error(i.error||"Rollback failed")}catch(c){y("Rollback failed: "+c.message,"error")}}T?.addEventListener("click",()=>s(!1)),L?.addEventListener("click",()=>p().catch(()=>{})),O?.addEventListener("click",v),b?.addEventListener("click",E),B?.addEventListener("click",()=>{f?.classList.add("show"),k()}),wireModal(f,j),window.openUpdateModal=function(c){f?.classList.add("show"),k().then(()=>{if(!c)return;const t=D.querySelector(`[data-app-id="${c}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",z),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",C),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{w(),l(),S||s(!0)}),window.dcApplyUpdate=p,window.dcCheckForUpdate=s,setTimeout(()=>s(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
\u{1F433} Docker Resources
Manage volumes, networks, and view disk usage.
@@ -1711,7 +1711,7 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
",A.innerHTML=w,A.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`),z()}catch(L){showNotification("Delete failed: "+L.message,"error"),M.textContent="Delete",M.disabled=!1}}})})}catch(x){A.innerHTML=`
Failed: ${escapeHtml(x.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const A=document.getElementById("dr-vol-name"),x=A.value.trim();if(!x){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:x}),A.value="",showNotification(`Volume "${x}" created`,"success"),z()}catch(B){showNotification("Create failed: "+B.message,"error")}});async function P(){const A=document.getElementById("dr-net-list");try{const B=(await getJSON("/api/v1/docker/networks")).networks||[];if(B.length===0){A.innerHTML='
\u{1F310}No networks found.
';return}let w='
';w+='
Name
Driver
Scope
Containers
Actions
';for(const M of B){const L=["bridge","host","none"].includes(M.name);w+='
",R.innerHTML=E,R.querySelectorAll(".dr-vol-del").forEach(z=>{z.addEventListener("click",async()=>{if(confirm(`Delete volume "${z.dataset.name}"? Data will be lost.`)){z.textContent="...",z.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(z.dataset.name)}?force=true`),D()}catch(C){showNotification("Delete failed: "+C.message,"error"),z.textContent="Delete",z.disabled=!1}}})})}catch(k){R.innerHTML=`
Failed: ${escapeHtml(k.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-vol-name"),k=R.value.trim();if(!k){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:k}),R.value="",showNotification(`Volume "${k}" created`,"success"),D()}catch(M){showNotification("Create failed: "+M.message,"error")}});async function A(){const R=document.getElementById("dr-net-list");try{const M=(await getJSON("/api/v1/docker/networks")).networks||[];if(M.length===0){R.innerHTML='
\u{1F310}No networks found.
';return}let E='
';E+='
Name
Driver
Scope
Containers
Actions
';for(const z of M){const C=["bridge","host","none"].includes(z.name);E+='
';for(const w of x.results){const M=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";B+='
';for(const E of k.results){const z=E.status==="deployed"||E.status==="created"?"\u2705":E.status==="exists"?"\u26A1":E.status==="skipped"?"\u23ED":"\u274C";M+='
`,w.style.display="none";return}if(!N&&O!==$)return;const l=Array.isArray(p.entries)?p.entries:[];if(l.length===0&&!N){const c=p.filters&&(p.filters.action||p.filters.outcome||p.filters.since||p.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";B.innerHTML=`
\u{1F4DC}${escapeHtml(c)}
`,w.style.display="none";return}let g="";N||(g='
',g+='
',g+='
When
',g+='
Actor
',g+='
IP
',g+='
Action
',g+='
Resource
',g+='
Result
',g+="
");for(const c of l){const t=c.outcome==="success",e=I(c);g+='
`,E.style.display="none";return}if(!T&&O!==N)return;const l=Array.isArray(p.entries)?p.entries:[];if(l.length===0&&!T){const c=p.filters&&(p.filters.action||p.filters.outcome||p.filters.since||p.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";M.innerHTML=`
\u{1F4DC}${escapeHtml(c)}
`,E.style.display="none";return}let v="";T||(v='
',v+='
',v+='
When
',v+='
Actor
',v+='
IP
',v+='
Action
',v+='
Resource
',v+='
Result
',v+="
");for(const c of l){const t=c.outcome==="success",e=m(c);v+='
`}async function m(){try{const p=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],l=v.value;v.innerHTML=''+p.map(g=>``).join(""),l&&(v.value=l)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",S),document.getElementById("sec-hosts-refresh").addEventListener("click",y);async function y(){try{const p=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];H=p;const l=document.getElementById("sec-hosts-container");if(!p.length){l.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
`}async function u(){try{const p=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],l=I.value;I.innerHTML=''+p.map(v=>``).join(""),l&&(I.value=l)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",S),document.getElementById("sec-hosts-refresh").addEventListener("click",g);async function g(){try{const p=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];P=p;const l=document.getElementById("sec-hosts-container");if(!p.length){l.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
`}).join(""),l.querySelectorAll(".sec-host-del").forEach(g=>{g.addEventListener("click",async()=>{confirm(`Remove host ${g.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(g.dataset.id)}`,{method:"DELETE"}),y())})})}catch(s){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+f(s.message)+"
"}}async function S(){const s=prompt("Host id (lowercase, no spaces):");if(!s)return;const p=prompt("Display label:",s)||s,l=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const g=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:s,label:p,type:l})}),c=await g.json();if(!g.ok){alert("Failed: "+(c?.error?.message||g.statusText));return}alert(`\u2705 Host registered!
+ `}).join(""),l.querySelectorAll(".sec-host-del").forEach(v=>{v.addEventListener("click",async()=>{confirm(`Remove host ${v.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(v.dataset.id)}`,{method:"DELETE"}),g())})})}catch(s){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+y(s.message)+"
"}}async function S(){const s=prompt("Host id (lowercase, no spaces):");if(!s)return;const p=prompt("Display label:",s)||s,l=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const v=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:s,label:p,type:l})}),c=await v.json();if(!v.ok){alert("Failed: "+(c?.error?.message||v.statusText));return}alert(`\u2705 Host registered!
id: ${c.data.host.id}
label: ${c.data.host.label}
@@ -1922,7 +1922,7 @@ type: ${c.data.host.type}
${c.data.api_key}
Send this key as: Authorization: Bearer
-To endpoint: POST /api/v1/security/events/ingest or /events/batch`),y()}catch(g){alert("Failed: "+g.message)}}function f(s){return String(s).replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p])}function E(s,p){let l;return function(){clearTimeout(l),l=setTimeout(()=>s.apply(this,arguments),p)}}})(),(function(){injectModal("deploys-modal",`
+To endpoint: POST /api/v1/security/events/ingest or /events/batch`),g()}catch(v){alert("Failed: "+v.message)}}function y(s){return String(s).replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p])}function w(s,p){let l;return function(){clearTimeout(l),l=setTimeout(()=>s.apply(this,arguments),p)}}})(),window.__dc133_buildRepoOptions=function(f,B){var j=B||function(b){return String(b).replace(/[&<>"']/g,function(D){return{"&":"&","<":"<",">":">",'"':""","'":"'"}[D]})};return''+(f||[]).map(function(b){return'"}).join("")},window.__dc133_requestToken=function(f,B){if(f)return"";var j=String(B||"").trim();return j||void 0},(function(){injectModal("deploys-modal",`
\u{1F69A} Deploys
@@ -1932,7 +1932,7 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),y()}catch(g)
-
+
@@ -1962,6 +1962,43 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),y()}catch(g)
Loading\u2026
+
+
+
+
+ Gitea server (any instance)
+
+
+
+
+
+
+
+
+
+
+
+ Go repos with a main package install automatically: build, systemd release,
+ Caddy gate (tailnet-only), DNS, verify, dashboard card. Takes ~30-60s.
+
+
+
+
@@ -1969,12 +2006,16 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),y()}catch(g)
- `);const b=u=>document.getElementById(u);let C=null,j=!1;function k(u){return window.escapeHtml?window.escapeHtml(String(u)):String(u).replace(/[&<>"']/g,v=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[v])}async function z(u,v){const D=await fetch("/dashcaddy-api/api/v1/deploys"+u,Object.assign({credentials:"include"},v||{}));let I=null;try{I=await D.json()}catch{I={success:!1,error:"non-JSON response"}}return{status:D.status,body:I}}function P(u){const v=b("dep-output");v.style.display="block",v.textContent=u||"(no output)",v.scrollTop=v.scrollHeight}async function H(){const u=b("dep-services"),{body:v}=await z("/services");if(!v.success){u.innerHTML=""+k(v.error||"unavailable")+"";return}const D=v.services||[];if(!D.length){u.innerHTML="No shipdeck deployments on record yet.";return}u.innerHTML='
Service
Last action
When
Release
'+D.map(I=>"
"+k(I.name)+"
"+k(I.last_action)+"
"+k(I.last_time)+"
"+k(I.last_epoch)+'
').join("")+"
"}async function A(){const u=b("dep-repo-select"),{body:v}=await z("/repos");if(!v.success){u.innerHTML="";return}const D=v.repos||[];u.innerHTML=D.length?D.map(I=>'").join(""):''}async function x(u){const v=b("dep-journal"),D=u?"?service="+encodeURIComponent(u):"",{body:I}=await z("/journal"+D),R=I.rows||[];if(!R.length){v.innerHTML="No journal rows.";return}v.innerHTML='
Time
Service
Action
Release
Duration
'+R.map(N=>"
"+k(N.time)+"
"+k(N.service)+"
"+k(N.action)+"
"+k(N.epoch)+"
"+k(N.duration||"\u2014")+"
").join("")+"
"}function B(u,v,D){v&&(v.disabled=u,D&&(v.textContent=u?"Working\u2026":D))}async function w(){const u=b("dep-deploy-btn"),v=b("dep-repo-select").value;if(v){B(!0,u,"Deploy"),P("Deploying "+v+`
-This can take ~30-60s\u2026`);try{const{body:D}=await z("/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:v})});P((D.output||D.error||"")+(D.success?`
+ `);const f=H=>document.getElementById(H);let B=null,j=!1;function b(H){return window.escapeHtml?window.escapeHtml(String(H)):String(H).replace(/[&<>"']/g,m=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[m])}async function D(H,m){const L=await fetch("/dashcaddy-api/api/v1/deploys"+H,Object.assign({credentials:"include"},m||{}));let T=null;try{T=await L.json()}catch{T={success:!1,error:"non-JSON response"}}return{status:L.status,body:T}}function A(H){const m=f("dep-output");m.style.display="block",m.textContent=H||"(no output)",m.scrollTop=m.scrollHeight}async function P(){const H=f("dep-services"),{body:m}=await D("/services");if(!m.success){H.innerHTML=""+b(m.error||"unavailable")+"";return}const L=m.services||[];if(!L.length){H.innerHTML="No shipdeck deployments on record yet.";return}H.innerHTML='
Service
Last action
When
Release
'+L.map(T=>"
"+b(T.name)+"
"+b(T.last_action)+"
"+b(T.last_time)+"
"+b(T.last_epoch)+'
').join("")+"
"}async function R(){const H=f("dep-repo-select"),{body:m}=await D("/repos");if(!m.success){H.innerHTML="";return}const L=m.repos||[];H.innerHTML=L.length?L.map(T=>'").join(""):''}async function k(H){const m=f("dep-journal"),L=H?"?service="+encodeURIComponent(H):"",{body:T}=await D("/journal"+L),O=T.rows||[];if(!O.length){m.innerHTML="No journal rows.";return}m.innerHTML='
Time
Service
Action
Release
Duration
'+O.map(u=>"
"+b(u.time)+"
"+b(u.service)+"
"+b(u.action)+"
"+b(u.epoch)+"
"+b(u.duration||"\u2014")+"
").join("")+"
"}async function M(){const H=document.getElementById("dep-gh-gitea"),m=document.getElementById("dep-gh-gitea-host"),L=document.getElementById("dep-gh-gitea-token"),T=document.getElementById("dep-gh-anonymous"),O={};if(m&&m.value.trim()&&(O.gitea_url="https://"+m.value.trim().replace(/^https?:\/*/,"")),T&&T.checked)O.token="";else{const u=window.__dc133_requestToken(!1,L&&L.value);u!==void 0&&(O.token=u)}try{const{status:u,body:g}=await D("/gitea-repos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!g.success||!(g.repos||[]).length){H.innerHTML='";return}H.innerHTML=window.__dc133_buildRepoOptions(g.repos,b)}catch{H.innerHTML=''}}async function E(){const H=document.getElementById("dep-gh-btn"),m=document.getElementById("dep-gh-url").value.trim(),L=(document.getElementById("dep-gh-service").value.trim()||"").toLowerCase(),T=document.getElementById("dep-gh-args").value.trim();if(!m||!L){A("Repo URL and name are required.");return}const O=T?T.split(/\s+/):[];z(!0,H,"Install"),A("Installing "+m+`
+Cloning, building, gating and DNS-ing... (~30-60s)`);try{const u=!!(document.getElementById("dep-gh-anonymous")||{}).checked,g=(document.getElementById("dep-gh-gitea-token")||{value:""}).value,S=window.__dc133_requestToken(u,g),{status:y,body:w}=await D("/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo_url:m,service:L,args:O,token:S})});if(!w.success){A((w.output?w.output+`
+`:"")+"FAIL "+(w.error||"HTTP "+y)),z(!1,H,"Install");return}const s=w.service||{};if(!(window.APPS||[]).some(l=>l.id===s.id)){const l={id:s.id,name:s.name||s.id,url:s.url,logo:s.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(l)}),window.APPS.push(l),typeof window.renderApps=="function"&&window.renderApps(),typeof window.renderGrid=="function"&&window.renderGrid()}catch{}}A("INSTALLED "+(s.name||s.id)+" in "+(s.deploy_seconds||"?")+`s
+Card: `+(s.url||"")+`
+`+(w.output||"").slice(-800)),P()}catch(u){A("install error: "+u.message)}z(!1,H,"Install")}function z(H,m,L){m&&(m.disabled=H,L&&(m.textContent=H?"Working\u2026":L))}async function C(){const H=f("dep-deploy-btn"),m=f("dep-repo-select").value;if(m){z(!0,H,"Deploy"),A("Deploying "+m+`
+This can take ~30-60s\u2026`);try{const{body:L}=await D("/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:m})});A((L.output||L.error||"")+(L.success?`
\u2705 SUCCESS`:`
-\u274C FAILED`)),H()}catch(D){P("deploy error: "+D.message)}B(!1,u,"Deploy")}}async function M(u,v){if(confirm("Roll back "+u+" to the previous release?")){B(!0,v,"Rollback"),P("Rolling back "+u+"\u2026");try{const{body:D}=await z("/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:u})});P((D.output||D.error||"")+(D.success?`
+\u274C FAILED`)),P()}catch(L){A("deploy error: "+L.message)}z(!1,H,"Deploy")}}async function N(H,m){if(confirm("Roll back "+H+" to the previous release?")){z(!0,m,"Rollback"),A("Rolling back "+H+"\u2026");try{const{body:L}=await D("/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:H})});A((L.output||L.error||"")+(L.success?`
\u2705 ROLLED BACK`:`
-\u274C FAILED`)),H()}catch(D){P("rollback error: "+D.message)}B(!1,v,"Rollback")}}async function L(u,v){B(!0,v,"Status");try{const{body:D}=await z("/status?service="+encodeURIComponent(u));P(D.output||D.error||"(no output)")}catch(D){P("status error: "+D.message)}B(!1,v,"Status")}function $(){C=document.getElementById("deploys-btn"),C&&(C.addEventListener("click",async()=>{b("deploys-modal").classList.add("open"),j||(j=!0,H(),A(),x(""))}),b("dep-close").addEventListener("click",()=>{b("deploys-modal").classList.remove("open")}),document.querySelectorAll(".dep-tab").forEach(u=>{u.addEventListener("click",()=>{document.querySelectorAll(".dep-tab").forEach(v=>v.classList.remove("active")),u.classList.add("active"),document.querySelectorAll("#deploys-modal .dep-panel").forEach(v=>{v.style.display=v.dataset.panel===u.dataset.tab?"block":"none"})})}),b("dep-deploy-btn").addEventListener("click",w),b("dep-journal-btn").addEventListener("click",()=>x(b("dep-journal-name").value.trim())),b("dep-status-btn").addEventListener("click",()=>{const u=b("dep-status-name").value.trim();u&&L(u)}),b("dep-services").addEventListener("click",u=>{const v=u.target.closest(".dep-rollback");if(v)return M(v.dataset.service,v);const D=u.target.closest(".dep-status");if(D)return L(D.dataset.service,D)}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",$):$()})(),(function(){const b=new ErrorHandler;injectModal("weather-modal",`