(() => {
'use strict';
let api,esc,formatDate,user;
const statuses={healthy:['上次正常','green'],error:['上次失败','red'],pending:['待检查','yellow'],disabled:['已停用','secondary'],paused:['已暂停','secondary'],running:['执行中','blue'],unknown:['状态未知','orange'],stale:['记录已过期','yellow'],healthy_stale:['成功记录已过期','yellow'],unconfigured:['未配置','secondary']};
const guards={running:['守护正常','green'],starting:['启动中','blue'],backoff:['等待恢复','orange'],cooldown:['恢复冷却中','orange'],stale:['守护心跳过期','red'],unmanaged:['未通过守护启动','yellow'],stopped:['已停止','secondary'],stopping:['停止中','secondary']};
const reasons={healthy:'两个服务端口心跳正常',initial_start:'首次启动',unexpected_exit:'业务进程意外退出',health_timeout:'服务持续无响应',manual_restart:'手动重启',manual_stop:'手动停止',port_conflict:'服务端口已被占用',spawn_failed:'进程启动失败',startup_failed:'启动失败'};
const events={guard_started:'守护启动',child_exit:'业务进程退出',unresponsive:'服务持续无响应',restarting:'准备自动恢复',cooldown:'多次失败,进入冷却',manual_restart:'手动重启',guard_stopped:'守护停止',monitor_error:'守护检查异常',spawn_failed:'业务进程启动失败',autostart_installed:'启用 Windows 登录自启',autostart_removed:'移除 Windows 登录自启'};
function duration(seconds){seconds=Math.max(0,Math.floor(seconds));const days=Math.floor(seconds/86400),hours=Math.floor(seconds%86400/3600),minutes=Math.floor(seconds%3600/60);return (days?days+' 天 ':'')+(hours?hours+' 小时 ':'')+(minutes?minutes+' 分钟 ':seconds%60+' 秒');}
function badge(status,map=statuses){const [label,color]=map[status]||['状态未知','secondary'];return `${label}`;}
async function render(container,isActive=()=>true){
const live=()=>isActive()&&container.isConnected;let pending=false,timer;
container.innerHTML=`
`;
const button=container.querySelector('#health-refresh'),notice=container.querySelector('#health-refresh-state');
function draw(data){
const {runtime}=data,guard=runtime.guard;
container.querySelector('#health-runtime').innerHTML=`${esc(duration(runtime.uptimeSeconds))}
本次启动:${esc(formatDate(runtime.startedAt))}
Windows 登录自启:${runtime.autostart.enabled?'已启用(当前用户)':'未启用'}
累计恢复 / 重启:${Number(guard.restartCount)||0} 次
最近心跳:${esc(formatDate(guard.heartbeatAt))}
${esc(runtime.managed?(reasons[guard.reason]||'等待健康检查结果'):'当前服务直接启动,尚未由守护程序接管。')}
${guard.nextRestartAt?`
下次尝试:${esc(formatDate(guard.nextRestartAt))}
`:''}
`;
container.querySelector('#health-groups').innerHTML=data.groups.map(group=>`${group.message?`
${esc(group.message)}
`:group.items.length?group.items.map(item=>`
${esc(item.name)}${badge(item.status)}
${esc(item.detail)}
- 最近检查
- ${esc(formatDate(item.checkedAt))}
- 最近成功
- ${esc(formatDate(item.lastSuccessAt))}
- 最近失败
- ${esc(formatDate(item.lastFailureAt))}
`).join(''):'
尚无可查看的配置。
'}
`).join('');
container.querySelector('#health-events').innerHTML=`${guard.events?.length?guard.events.slice(0,12).map(event=>`
${esc(formatDate(event.at))}${esc(events[event.kind]||'运行状态变化')}${event.code!==undefined&&event.code!==null?'(退出码 '+esc(event.code)+')':''}${event.delayMs?','+Math.ceil(event.delayMs/1000)+' 秒后尝试':''}
`).join(''):'
暂无守护事件。'}
`;
}
async function refresh(){
if(pending||!live())return;pending=true;button.disabled=true;clearTimeout(timer);
try{const data=await api('/health',undefined,{signal:AbortSignal.timeout(8000)});if(!live())return;draw(data);notice.className='card-footer small text-secondary';notice.innerHTML=`健康状态已更新${esc(formatDate(data.at))}`;}
catch{if(live()){const access=container.querySelector('#health-access');if(access){access.className='badge bg-red-lt ms-auto';access.textContent='连接中断';}notice.className='card-footer small text-danger';notice.textContent='暂时无法连接服务,保留上次状态;恢复后会自动更新。';}}
finally{pending=false;if(live()){button.disabled=false;timer=setTimeout(refresh,10000);}}
}
if(user?.role==='admin'){const box=container.querySelector('#health-maintenance');box.innerHTML='';const load=async()=>{const b=container.querySelector('#capacity-refresh');b.disabled=true;try{const d=await api('/maintenance');if(live())container.querySelector('#capacity-content').innerHTML='默认永久保留;会话归档及异常退役保留原证据。
状态数据 '+(d.state.bytes/1048576).toFixed(2)+' MiB · PDF '+d.pdf.files+' 份 / '+(d.pdf.bytes/1048576).toFixed(2)+' MiB · 导出台账 '+d.jobs.total+' 条
导出 PDF 历史备份与恢复按停服操作指南执行;只恢复到新空目录。
';}catch(e){if(live())container.querySelector('#capacity-content').textContent=e.message;}finally{if(live())b.disabled=false;}};container.querySelector('#capacity-refresh').onclick=load;void load();}
button.onclick=refresh;await refresh();
}
window.HealthViews={configure:options=>({api,esc,formatDate,user}=options),render};
})();