: asapien/superpulse

commit 5fa4179841fafa67efc3aafa48c2e3c72908df49
parent c4c5648f28d086b5f3db2c00b7101621ec6589a9
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Wed, 7 Oct 2026 17:31:46 +0530

Build frontend bundles with esbuild
9 files changed, 361 insertions(+), 6 deletions(-)
M
.gitignore
|
2
++
M
gt.js
|
4
++--
M
index.html
|
5
++---
M
logs.js
|
3
++-
A
out/logs.js
|
50
++++++++++++++++++++++++++++++++++++++++++++++++++
A
out/tva-control.js
|
5
+++++
A
package.json
|
11
+++++++++++
A
pnpm-lock.yaml
|
285
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
pnpm-workspace.yaml
|
2
++
diff --git a/.gitignore b/.gitignore
@@ -1 +1,3 @@
 .env.php
+
+node_modules/
diff --git a/gt.js b/gt.js
@@ -1,4 +1,4 @@
-function parseGT(input) {
+window.parseGT = function parseGT(input) {
     let index = 0;
     const inputLength = input.length;
 

@@ -213,4 +213,4 @@ function parseGT(input) {
     } catch (e) {
         throw new Error(`Failed to parse input: ${e.message}`);
     }
-}
+};
diff --git a/index.html b/index.html
@@ -26,10 +26,9 @@
         <hr style="border: 1px solid black" />
       </div>
     </template>
-    <script src="tva-control.js"></script>
-    <script src="logs.js"></script>
+    <script src="out/tva-control.js"></script>
+    <script src="out/logs.js"></script>
     <div class="content">
-      <script src="gt.js"></script>
       <header class="app-chart-header">
         <div class="action-chart-container app-header-chart">
           <button
diff --git a/logs.js b/logs.js
@@ -1036,7 +1036,7 @@ function parseFeedResponse(textData) {
       // Fall through to the legacy GT parser instead of breaking the live feed.
     }
   }
-  const parsed = parseGT(textData);
+  const parsed = window.parseGT(textData);
   return Array.isArray(parsed) ? parsed : [parsed];
 }
 

@@ -1229,6 +1229,7 @@ function deviceCardUpdate(ev) {
     placeDevicePopoverNear(el);
   });
 }
+window.deviceCardUpdate = deviceCardUpdate;
 
 fetchIntervalId = setInterval(fetchUpdates, 3000);
 let actionFetchIntervalId = null;
diff --git a/out/logs.js b/out/logs.js
@@ -0,0 +1,50 @@
+(()=>{window.parseGT=function(t){let n=0,r=t.length;function a(){for(;n<r&&/\s/.test(t[n]);)n++}function o(s){let g=Math.max(0,n-10),w=Math.min(r,n+10),le=t.slice(g,w);throw new Error(`${s} at position ${n}. Context: "...${le}..."`)}function i(){a();let s=t[n];return s==="{"?l():s==="["?u():s==="'"?c():/[0-9-]/.test(s)?A():b()}function l(){t[n]!=="{"&&o("Expected '{'"),n++;let s={};for(a();n<r&&t[n]!=="}";){let g=D();a();let w=i();if(s[g]=w,a(),t[n]==="}")break}return t[n]!=="}"&&o("Expected '}' to close object"),n++,s}function u(){t[n]!=="["&&o("Expected '['"),n++;let s=[];for(a();n<r&&t[n]!=="]";){let g=i();if(s.push(g),a(),t[n]==="]")break}return t[n]!=="]"&&o("Expected ']' to close array"),n++,s}function c(){t[n]!=="'"&&o("Expected single quote"),n++;let s="";for(;n<r&&t[n]!=="'";){if(t[n]==="\\")switch(n++,n>=r&&o("Unterminated escape sequence"),t[n]){case"'":s+="'";break;case"\\":s+="\\";break;case"/":s+="/";break;case"b":s+="\b";break;case"f":s+="\f";break;case"n":s+=`
+`;break;case"r":s+="\r";break;case"t":s+="	";break;default:s+=t[n];break}else s+=t[n];n++}return t[n]!=="'"&&o("Unterminated string"),n++,s}function D(){return a(),t[n]==="'"?c():b()}function b(){let s="";for(;n<r&&!/[\]}\s]/.test(t[n]);)s+=t[n],n++;return s}function A(){let s=n;for(t[n]==="-"&&n++;n<r&&/[0-9]/.test(t[n]);)n++;if(t[n]===".")for(n++;n<r&&/[0-9]/.test(t[n]);)n++;if(/[eE]/.test(t[n]))for(n++,/[+-]/.test(t[n])&&n++;n<r&&/[0-9]/.test(t[n]);)n++;let g=t.slice(s,n);return/^-?\d+\.?\d*([eE][+-]?\d+)?$/.test(g)?parseFloat(g):(n=s,b())}try{a();let s=i();return a(),n<r&&o("Unexpected characters at end of input"),s}catch(s){throw new Error(`Failed to parse input: ${s.message}`)}};var de={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},h={endpoint:"/kidang.fcgi",otpTable:"otp",actionTable:null,defaultRangeHours:48,displayTimestampsAsLocalWallClock:!1},U=new Set,O=new Set,K={theme:"auto",ambientGlow:!0},p=ue();function ue(){try{return{...K,...JSON.parse(localStorage.getItem("logs_settings"))||{}}}catch{return{...K}}}function me(){localStorage.setItem("logs_settings",JSON.stringify(p))}var H={title:"TVA REACTIVE CHANNEL",blinkMs:1100,aliases:{bookingAgeDays:"refillSpreadDays",bookingSpreadDays:"refillSpreadDays",bpclDeposit:"bpclDepositLakhs"},ambientGlow:{enabled:p.ambientGlow!==!1,alpha:.14,radius:74,blur:42},warningLevels:[{key:"amber",label:"AMBER ALERT",priority:1,showAxis:!0,dominance:.6,axisAlpha:.28,axisWidth:1.45,axisDash:[3,5],glowAlpha:.12},{key:"red",label:"CRITICAL",priority:2,showAxis:!0,dominance:.7,axisAlpha:.42,axisWidth:1.45,axisDash:[6,6],glowAlpha:.16},{key:"double-red",label:"DOUBLE RED",priority:3,showAxis:!1,dominance:.7,borderBlink:!0,glowAlpha:.18,glowRadius:88,glowBlur:54}],colors:{amber:"#ffcc00",red:"#ff0055",critical:"#ff0055","double-red":"#ff1a1a",doubleRed:"#ff1a1a",disabled:"#777777"},staleAlpha:.35,parameters:[{key:"complaintsOpen",label:"Complaints Open",icon:"warning",scale:"count10",refreshMinutes:15,thresholds:{amberUpper:52.5,redUpper:75,amberLower:-52.5,redLower:-75}},{key:"invoiceActions",label:"Invoice Actions",icon:"invoice",scale:"count10",refreshMinutes:15,thresholds:{amberUpper:59.5,redUpper:85,amberLower:-59.5,redLower:-85}},{key:"deliveryPersonLeave",label:"Delivery Person Leave",icon:"person",scale:"count10",refreshMinutes:720,thresholds:{amberUpper:49,redUpper:70,amberLower:-49,redLower:-70}},{key:"refillSpreadDays",label:"Refill Spread",icon:"calendar",scale:"daysCritical",scaleBase:10,scaleMax:165,refreshMinutes:1440,display:{suffix:"d"},thresholds:{amberUpper:50,redUpper:100,doubleRedUpper:150,amberLower:-70,redLower:-100},detailMode:"refill-spread",areaKey:"refillSpreadAreas",detailTitle:"REFILL SPREAD AREA SCAN",detailLevels:[{level:"amber",above:5},{level:"red",above:10}]},{key:"pendencyDays",label:"Pendency",icon:"hourglass",scale:"pendency",scaleIdeal:1,scaleBase:3,scaleMax:115,refreshMinutes:720,display:{suffix:"d",decimals:1},thresholds:{amberUpper:33.33,redUpper:100,amberLower:-70,redLower:-100},detailMode:"pendency",areaKey:"pendencyAreas",detailTitle:"PENDENCY AREA SCAN",detailLevels:[{level:"amber",above:1},{level:"red",above:3}]},{key:"bpclDepositLakhs",label:"BPCL Deposit",icon:"deposit",scale:"raw",refreshMinutes:30,display:{prefix:"\u20B9",suffix:"L",decimals:1},thresholds:{amberUpper:4,redUpper:6,amberLower:-1,redLower:-3}}],extraAxes:[{label:"BPCL Deposit Good",parameterKey:"bpclDepositLakhs",value:6,color:"rgba(0,255,120,.5)",width:1.8,dash:[4,4]},{label:"BPCL Deposit Soft",parameterKey:"bpclDepositLakhs",value:4,color:"rgba(120,255,160,.34)",width:1.4,dash:[2,5]}]},f=null,v=null,k={complaintsOpen:0,invoiceActions:2,deliveryPersonLeave:0,refillSpreadDays:ge(-1,25),amberRefillSpreadDays:5,criticalRefillSpreadDays:10,doubleRedRefillSpreadDays:15,bpclDepositLakhs:3,pendencyDays:2.7,idealPendencyMaxDays:1,criticalPendencyDays:3,refillSpreadAreas:[{name:"KK NAGAR",days:12},{name:"WEST MAMBALAM",days:9},{name:"ASHOK NAGAR",days:7},{name:"T NAGAR",days:11},{name:"VADAPALANI",days:6},{name:"KODAMBAKKAM",days:8},{name:"SALIGRAMAM",days:5},{name:"VIRUGAMBAKKAM",days:10},{name:"NESAPAKKAM",days:13},{name:"JAFFERKHANPET",days:6},{name:"EKKATTUTHANGAL",days:4},{name:"MGR NAGAR",days:9},{name:"SAIDAPET",days:7}],pendencyAreas:[{name:"KK NAGAR",days:3.4},{name:"WEST MAMBALAM",days:2.9},{name:"ASHOK NAGAR",days:2.6},{name:"T NAGAR",days:3.1},{name:"VADAPALANI",days:2.2},{name:"KODAMBAKKAM",days:2.8},{name:"SALIGRAMAM",days:1.9},{name:"VIRUGAMBAKKAM",days:2.4},{name:"NESAPAKKAM",days:3},{name:"JAFFERKHANPET",days:2.1},{name:"EKKATTUTHANGAL",days:1.7},{name:"MGR NAGAR",days:2.5},{name:"SAIDAPET",days:2}]};function pe(e=new Date){let t=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Kolkata",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=r=>Number(t.find(a=>a.type===r).value);return{year:n("year"),month:n("month"),day:n("day")}}function fe(e,t,n){return Date.UTC(e,t-1,n,-5,-30,0,0)}function ge(e,t){let n=pe(),r=new Date(Date.UTC(n.year,n.month-1+e,1)),a=r.getUTCFullYear(),o=r.getUTCMonth()+1,i=fe(a,o,t),l=Date.now();return Math.max(0,Math.floor((l-i)/(1440*60*1e3)))}function J(e){let t=Number(e);return Number.isFinite(t)?t:null}function m(e,t,n){if(!Object.prototype.hasOwnProperty.call(n,e))return;let r=J(n[e]);r!==null&&(k[t]=r)}function V(e){return(Array.isArray(e)?e:e&&typeof e=="object"?Object.entries(e).map(([n,r])=>({name:n,days:r})):[]).map((n,r)=>{let a=String(n.name||n.area||n.areaName||`Area ${r+1}`).trim(),o=J(n.days??n.pendencyDays??n.currentDays);return a&&o!==null?{name:a,days:o}:null}).filter(Boolean)}function ye(e){if(!Object.prototype.hasOwnProperty.call(e,"pendencyAreas"))return;let t=V(e.pendencyAreas);t.length&&(k.pendencyAreas=t)}function he(e){if(!Object.prototype.hasOwnProperty.call(e,"refillSpreadAreas"))return;let t=V(e.refillSpreadAreas);t.length&&(k.refillSpreadAreas=t)}function W(e){return!e||String(e.type||"").toLowerCase()!=="tva-metrics"?!1:(v={...v||{},...e},delete v.type,m("complaintsOpen","complaintsOpen",e),m("invoiceActions","invoiceActions",e),m("deliveryPersonLeave","deliveryPersonLeave",e),m("refillSpreadDays","refillSpreadDays",e),m("bookingAgeDays","refillSpreadDays",e),m("bookingSpreadDays","refillSpreadDays",e),m("amberRefillSpreadDays","amberRefillSpreadDays",e),m("criticalRefillSpreadDays","criticalRefillSpreadDays",e),m("doubleRedRefillSpreadDays","doubleRedRefillSpreadDays",e),m("bpclDepositLakhs","bpclDepositLakhs",e),m("bpclDeposit","bpclDepositLakhs",e),m("pendencyDays","pendencyDays",e),m("idealPendencyMaxDays","idealPendencyMaxDays",e),m("criticalPendencyDays","criticalPendencyDays",e),ye(e),he(e),!0)}function z(e){[...e].sort((t,n)=>t.sentstamp-n.sentstamp).forEach(t=>W(C(t.msg,t.extra)))}function Z(e){return String(C(e.msg,e.extra).type||"").toLowerCase()==="tva-metrics"}window.setTvaControlData=function(e){typeof e=="string"&&(e=JSON.parse(e)),W({type:"tva-metrics",...e||{}}),R()};window.getTvaControlData=function(){return f?f.getData():JSON.parse(JSON.stringify(k))};function T(){let e=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,t=p.theme==="dark"||p.theme==="auto"&&e,n=p.theme==="light"||p.theme==="auto"&&!e;document.body.classList.toggle("logs-dark",t),document.body.classList.toggle("logs-light",n),document.querySelectorAll(".action-chart-container, .tva-control-container").forEach(r=>{p.theme==="auto"?r.removeAttribute("data-tva-theme"):r.dataset.tvaTheme=p.theme}),H.ambientGlow.enabled=p.ambientGlow!==!1,f&&typeof f.refreshTheme=="function"&&f.refreshTheme()}function Y(){let e=document.getElementById("settings-theme"),t=document.getElementById("settings-ambient-glow");!e||!t||(e.value=p.theme,t.checked=p.ambientGlow!==!1)}window.openLogsSettings=function(){Y();let e=document.getElementById("logs-settings-dialog");e&&e.showModal()};window.closeLogsSettings=function(){let e=document.getElementById("logs-settings-dialog");e&&e.close()};window.saveLogsSettings=function(){let e=document.getElementById("settings-theme"),t=document.getElementById("settings-ambient-glow");p={theme:e?e.value:"auto",ambientGlow:t?t.checked:!0},me(),T(),closeLogsSettings()};function Q(){let e=document.getElementById("tvaReactiveChart");!e||f||typeof Chart>"u"||typeof createTvaControl!="function"||(T(),f=createTvaControl({canvas:e,config:H,data:k}))}function R(){f||Q(),f&&v&&(f.update(v),v=null)}function X(){try{let e=sessionStorage.getItem("seen_lpg_leaks");return e?JSON.parse(e):[]}catch{return[]}}function be(e){try{let t=X();t.includes(e)||(t.push(e),sessionStorage.setItem("seen_lpg_leaks",JSON.stringify(t)))}catch(t){console.error(t)}}function Ae(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;let t=new e;[0,.25].forEach(n=>{let r=t.createOscillator(),a=t.createGain();r.type="sine",r.frequency.setValueAtTime(880,t.currentTime+n),a.gain.setValueAtTime(.3,t.currentTime+n),a.gain.exponentialRampToValueAtTime(.01,t.currentTime+n+.2),r.connect(a),a.connect(t.destination),r.start(t.currentTime+n),r.stop(t.currentTime+n+.2)})}catch{console.warn("Audio Context blocked. Click anywhere on the webpage once to enable sound alerts.")}}function we(e,t,n){"Notification"in window&&Notification.permission==="granted"&&new Notification("CRITICAL ALERT: LPG Leakage",{body:`From: ${e} (${n})
+${t}`})}function d(e,t){return e==null?"":typeof e!="string"?e:e?e.replace(t?/[&<>'"]/g:/[&<>]/g,n=>de[n]):""}function ee(e){if(!e)return;let t;if(e<1e10)t=new Date(e*1e3);else if(e<1e13)t=new Date(e);else if(e<1e16)t=new Date(Math.floor(e/1e3));else return;return h.displayTimestampsAsLocalWallClock?new Date(t.getTime()+t.getTimezoneOffset()*60*1e3):t}function ve(e){return!(e instanceof Date)||isNaN(e)?"":`<strong>${new Intl.DateTimeFormat("en-IN",{timeZone:"Asia/Kolkata",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}</strong>`}function De(e){if(!(e instanceof Date)||isNaN(e))return"";let t=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Kolkata",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=r=>t.find(a=>a.type===r).value;return`${n("year")}-${n("month")}-${n("day")}`}function Se(e){if(!(e instanceof Date)||isNaN(e))return"";let t=new Intl.DateTimeFormat("en-US",{timeZone:"Asia/Kolkata",day:"numeric",month:"short"}).formatToParts(e),n=t.find(a=>a.type==="day").value,r=t.find(a=>a.type==="month").value;return`<div class="date-p"><p>${n}</p><small>${r}</small><hr></div>`}function x(e){if(!e)return;e.querySelectorAll("li.date-divider").forEach(n=>n.remove());let t=null;e.querySelectorAll("li.msg-list-item").forEach(n=>{let r=ee(parseInt(n.dataset.timestamp,10));if(!r)return;let a=De(r);if(a===t)return;t=a;let o=document.createElement("li");o.className="date-divider",o.innerHTML=Se(r),e.insertBefore(o,n)})}window.copyToClipboard=function(e,t){navigator.clipboard.writeText(e).then(()=>{let n=t.innerText;t.innerText="Copied!",t.style.background="#d4edda",t.style.borderColor="#c3e6cb",setTimeout(()=>{t.innerText=n,t.style.background="#f0f0f0",t.style.borderColor="#ddd"},1200)}).catch(n=>console.error(n))};function ke(e){return`<span class="copyable-code" onclick="copyToClipboard('${e}', this)" style="cursor:pointer; background:#f0f0f0; padding:2px 6px; border-radius:4px; font-weight:bold; display:inline-block; margin-top:4px; border:1px solid #ddd; transition: all 0.2s;">${e}</span>`}function Te(e){return`<div class="leakage-alert">${d(e,!0)} detected</div>`}function C(e,t){if(e&&typeof e=="object"&&e.type)return e;if(e=e||"",typeof e=="string"&&e.trim().startsWith("{"))try{let u=JSON.parse(e);if(u&&typeof u=="object"&&u.type)return u}catch{}let n=e.match(/^rs\.([0-9.]*) debited to CC-xxx2081 .* \[(.*)\]/i);if(n)return{type:"iob-debit",amount:n[1],merchant:n[2]||"",msg:e};let r=e.match(/^rs\.([0-9.]*) credited to CC-xxx2081 .* \[(.*)\]/i);if(r)return{type:"iob-credit",amount:r[1],merchant:r[2]||"",msg:e};let a="";try{let u=t?JSON.parse(t):null;u&&u.sim&&(a=u.sim)}catch{}let o={type:"sms",msg:e,sim:a},i=e.match(/\b\d{6}\b/);i&&(o.otp=i[0]);let l=e.match(/(lpg leakage|gas leak|leakage detected)/i);return l&&(o.leakage=l[0]),o}var F={"iob-debit":e=>`<div>
+                            <details style="display: inline-block; width: 100%;"><summary style="margin-left: 6rem; display: block; color: red;">- Rs. ${d(e.amount,!0)}</summary>${d(e.msg)}</details>
+                        </div>`,"iob-credit":e=>`<div>
+                            <details style="display: inline-block; width: 100%;"><summary style="display: block; color: green;">+ Rs. ${d(e.amount,!0)}</summary>${d(e.msg)}</details>
+                        </div>`,sms:e=>`${e.leakage?Te(e.leakage):""}${d(e.msg)}${e.otp?ke(e.otp):""}`,dispatch:e=>`<span class="badge-status">${d(e.status,!0)}</span>
+                        <div class="cargo-grid">
+                        ${(e.cargo||[]).map(t=>`<div class="cargo-item"><span class="kg-badge">${d(t.kg,!0)}</span>
+                        <span class="qty">${d(String(t.qty),!0)}</span></div>`).join("")}
+                        </div>
+                        <table>
+                        <tbody>
+                            <tr>
+                                <th>vehicle no</th>
+                                <td>${d(e.vehicleNo,!0)}</td>
+                            </tr>
+                            <tr>
+                                <th>time</th>
+                                <td>${d(e.time,!0)}</td>
+                            </tr>
+                            <tr>
+                                <th>invoice no.</th>
+                                <td>${d(e.invoiceNo,!0)}</td>
+                            </tr>
+                            <tr>
+                                <th>amount</th>
+                                <td>${d(e.amount,!0)}</td>
+                            </tr>
+                        </tbody>
+                        </table>
+                        <button class="value">Acknowledge Invoice</button>`};function Ce(e){return(F[e.type]||F.sms)(e)}function Le(e){switch(e.type){case"iob-debit":case"iob-credit":return e.merchant||"";case"sms":return e.sim||"";case"dispatch":return e.vehicleNo||e.invoiceNo||"";default:return""}}function Ee({imgType:e,sender:t,headerLabel:n,timeStr:r,mid:a,deviceName:o}){let i=n?`${n} | `:"";return`<div class="msg-item-header">
+              ${e}
+                        <div style="display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px;">
+                            <span>${t}</span>
+                            <small style="font-weight: lighter; color: #727272;">${i}${r}</small>
+                        </div>
+                        <button class="device-name-button" popovertarget="device-info-popover" data-mid="${d(String(a),!0)}" onfocus="deviceCardUpdate(event)" onclick="deviceCardUpdate(event)" style="flex: 1; text-align: end; font-size: 11px; color:#aaa; font-weight:normal; font-family:monospace;">${o}</button>
+            </div>`}function te(e,t){e.style.setProperty("display",t?"flex":"none","important")}window.applyFilters=function(){let e=document.getElementById("filter-device").value,t=document.getElementById("filter-category").value,n=document.getElementById("filter-search").value.toLowerCase();document.querySelectorAll("#data-list .msg-list-item").forEach(r=>{let a=!e||r.dataset.device===e,o=!t||r.dataset.category===t,i=!n||r.innerText.toLowerCase().includes(n);te(r,a&&o&&i)})};window.applyActionFilters=function(){let e=document.getElementById("action-filter-search"),t=e?e.value.toLowerCase():"";document.querySelectorAll("#action-list .msg-list-item").forEach(n=>{let r=!t||n.innerText.toLowerCase().includes(t);te(n,r)})};window.showMobileSegment=function(e){document.querySelectorAll(".segment").forEach(t=>{t.classList.toggle("active",t.dataset.segment===String(e))}),document.querySelectorAll(".mobile-panel-switch button").forEach(t=>{let n=t.dataset.targetSegment===String(e);t.classList.toggle("active",n),t.setAttribute("aria-pressed",n?"true":"false")})};function G(e){if(!e)return null;let t=String(e).match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);if(!t)return null;let[,n,r,a,o,i]=t.map(Number);return Math.floor(Date.UTC(n,r-1,a,o-5,i-30,0,0)/1e3)}function q(e){let t={timeZone:"Asia/Kolkata",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1},r=new Intl.DateTimeFormat("en-US",t).formatToParts(e),a=o=>r.find(i=>i.type===o).value;return`${a("year")}-${a("month")}-${a("day")}T${a("hour")}:${a("minute")}`}function P(e=!1){let t=document.getElementById("range-from"),n=document.getElementById("range-to");if(!t||!n)return;let r=new Date;if(e||!rangeFieldsInitialized||!t.value){let a=new Date(r.getTime()-h.defaultRangeHours*60*60*1e3);t.value=q(a),rangeFieldsInitialized=!0}n.value=q(r)}function ne(){P();let e=document.getElementById("range-from"),t=document.getElementById("range-to"),n={},r=G(e&&e.value),a=G(t&&t.value);return r&&(n.sentstamp=r,n.fromTimestamp=r),a&&(n.toTimestamp=a),n}window.refreshRangeFeeds=function(){P(),E(),$()};function xe(e){if(!e||U.has(String(e)))return;U.add(String(e));let t=document.getElementById("filter-device");if(!t)return;let n=document.createElement("option");n.value=String(e),n.textContent=re(e)||L(e),t.appendChild(n)}function Ie(e){if(!e||O.has(e))return;O.add(e);let t=document.getElementById("filter-category");if(!t)return;let n=document.createElement("option");n.value=e,e==="otp"||e==="sms"?n.textContent=`${e.toUpperCase()} Only`:n.textContent=e.charAt(0).toUpperCase()+e.slice(1),t.appendChild(n)}function L(e){return e?`Device ${e}`:"unknown"}function re(e){let t=S[e];return t&&typeof t=="object"&&t.name?t.name:(ce(e).then(n=>ae(e,n)),L(e))}function I(e){return window.CSS&&CSS.escape?CSS.escape(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}function ae(e,t){if(!e||!t||!t.name)return;document.querySelectorAll(`.device-name-button[data-mid="${I(String(e))}"]`).forEach(r=>{r.textContent=t.name;let a=r.closest(".msg-list-item");a&&(a.dataset.device=String(e))});let n=document.querySelector(`#filter-device option[value="${I(String(e))}"]`);n&&(n.textContent=t.name)}function B(e){return{1:"sms",2:"econnect",3:"paytm",4:"tampermonkey",5:"printer"}[e+""]}function Me(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return`hsl(${Math.abs(t)%360}, 65%, 42%)`}function oe(e,t,n){let r=e.querySelectorAll("li.msg-list-item");for(let a=0;a<r.length;a++){let o=parseInt(r[a].dataset.timestamp,10);if(n>o){e.insertBefore(t,r[a]);return}}e.appendChild(t)}function $e(e){let t=String(e.sndr||"").toLowerCase(),n=String(e.msg||"").toLowerCase(),r=B(e.cid)||"";return t==="complaints"||r==="econnect"&&/\b(urgent|emergency|complain|complaint|leak)/i.test(n)}function M(e,t){let n=t.map(r=>`msg-${r.sndr}-${r.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_"));e.querySelectorAll('li[id^="msg-"]').forEach(r=>{n.includes(r.id)||r.remove()})}function se(e){let t=ee(e.sentstamp);if(!t)return null;let n=re(e.mid)||L(e.mid),r=B(e.cid)||"unknown",a=C(e.msg,e.extra),o=document.createElement("li");o.id=`msg-${e.sndr}-${e.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_"),o.className="msg-list-item",o.dataset.device=String(e.mid||"unknown"),o.dataset.category=r,o.dataset.timestamp=e.sentstamp,o.style.display="flex",o.style.alignItems="flex-start",o.style.padding="10px 12px",o.style.borderBottom="1px solid #f2f2f2",a.leakage&&(o.style.background="#fff5f5",o.style.borderLeft="4px solid #dc3545");let i=Me(e.sndr||"Unknown"),l="";return r==="sms"?l=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${i}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
+            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
+            </svg>`:r==="tampermonkey"?l='<img src="/assets/tampermonkey.svg">':r==="printer"?l='<img src="/assets/printer.svg">':l='<img style="height: 16px; width: 16px;" src="/assets/logs/cid-2-16x.png">',o.innerHTML=`
+                    <div style="flex-grow: 1; min-width: 0; display: flex; flex-direction: column;">
+                    ${Ee({imgType:l,sender:d(e.sndr,!0),headerLabel:d(Le(a),!0),timeStr:ve(t),mid:e.mid,deviceName:d(n,!0)})}
+
+                    <!-- Body markup is fully owned by the message type template -->
+                    <div class="logs-message">
+                    ${Ce(a)}
+                    </div>
+                    </div>
+                    `,o}function Ne(e){let t=e.trim();if(!t)return[];if(t.startsWith("[")||t.startsWith("{"))try{let r=JSON.parse(t);return Array.isArray(r)?r:Array.isArray(r.rows)?r.rows:Array.isArray(r.data)?r.data:[r]}catch{}let n=window.parseGT(e);return Array.isArray(n)?n:[n]}async function ie(e,t={}){let n=new URLSearchParams({table:e});Object.entries(t).forEach(([a,o])=>{o!=null&&o!==""&&n.set(a,o)});let r=await fetch(`${h.endpoint}?${n.toString()}`);if(!r.ok)throw new Error(`${e} fetch failed: ${r.status}`);return Ne(await r.text())}async function E(){try{let e=ne(),t=await ie(h.otpTable,e),n=document.getElementById("data-list"),r=e.toTimestamp?e.toTimestamp*1e3:null,a=r?t.filter(c=>c.sentstamp<=r):t;a.sort((c,D)=>D.sentstamp-c.sentstamp),z(a);let o=X(),i=[],l=[];a.forEach(c=>{if(Z(c))return;let D=B(c.cid)||"unknown";xe(c.mid),Ie(D);let b=$e(c),A=b?document.getElementById("action-list"):n;b?l.push(c):i.push(c);let s=`msg-${c.sndr}-${c.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_");if(A&&A.querySelector(`#${I(s)}`))return;C(c.msg,c.extra).leakage&&!o.includes(s)&&(be(s),o.push(s),Ae(),we(c.sndr,c.msg,c.mid));let w=se(c);A&&w&&oe(A,w,c.sentstamp)}),M(n,i);let u=document.getElementById("action-list");u&&(M(u,l),R(l),applyActionFilters(),x(u)),applyFilters(),x(n)}catch(e){console.error("Error fetching updates:",e)}}async function $(){let e=document.getElementById("action-list");if(!(!e||!h.actionTable))try{let t=ne(),n=await ie(h.actionTable,t),r=t.toTimestamp?t.toTimestamp*1e3:null,a=r?n.filter(o=>o.sentstamp<=r):n;a.sort((o,i)=>i.sentstamp-o.sentstamp),z(a),a.forEach(o=>{if(Z(o))return;let i=`msg-${o.sndr}-${o.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_");if(document.getElementById(i))return;let l=se(o);l&&oe(e,l,o.sentstamp)}),M(e,a),R(a),applyActionFilters(),x(e)}catch(t){if(String(t.message||"").match(/\b(404|500)\b/)){console.warn("Action-required feed unavailable; stopping action polling.",t),h.actionTable=null,N&&clearInterval(N);return}console.error("Error fetching action-required updates:",t)}}function y(e){return document.getElementById(e)}var S={};function ce(e){if(!e)return Promise.resolve(null);let t=String(e),n=S[t];if(n&&typeof n.then=="function")return n;if(n&&typeof n=="object")return Promise.resolve(n);let r=fetch("/logs.php?id="+encodeURIComponent(t)).then(async a=>{let o=null;try{o=await a.json()}catch{throw new Error(`Device lookup returned invalid JSON: ${a.status}`)}if(!a.ok)throw new Error(o&&o.error?o.error:`Device lookup failed: ${a.status}`);if(!o||!o.name)throw new Error("Device lookup response missing name");return o}).then(a=>(S[t]=a,ae(t,a),a)).catch(a=>(console.warn("Device lookup failed",t,a),delete S[t],null));return S[t]=r,r}function _(e){e=e||{},y("p-name").parentNode.style.borderColor=e.category_color||"gray",y("p-name").parentNode.style.borderWidth="1px",y("p-name").parentNode.style.borderStyle="solid",y("p-name").textContent=e.name||"Loading device\u2026",y("p-assigned-to").textContent=e.assigned_to||"",y("p-image").src=e.image||"",y("p-notes").textContent=e.notes||"",y("p-serial").textContent=e.serial||""}function j(e){let t=document.getElementById("device-info-popover");if(!t||!e)return;let n=e.getBoundingClientRect();t.style.position="fixed",t.style.left=`${Math.min(n.left,window.innerWidth-320)}px`,t.style.top=`${Math.min(n.bottom+6,window.innerHeight-180)}px`,t.style.inset="auto"}function Re(e){let t=e.target,n=t.dataset.mid;j(t),_({name:L(n)}),n&&ce(n).then(r=>{r&&_(r),j(t)})}window.deviceCardUpdate=Re;fetchIntervalId=setInterval(E,3e3);var N=null;E();document.addEventListener("DOMContentLoaded",()=>{window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",T),Y(),T(),P(),Q(),E(),$(),N=setInterval($,3e3)});})();
diff --git a/out/tva-control.js b/out/tva-control.js
@@ -0,0 +1,5 @@
+(()=>{(function(){function d(r,u=0){let a=Number(r);return Number.isFinite(a)?a:u}function X(r,u,a){return Math.max(u,Math.min(a,r))}function ce(r){return JSON.parse(JSON.stringify(r))}function Y(r){return String(r).replace(/-([a-z])/g,(u,a)=>a.toUpperCase())}function de(r){return String(r).replace(/[&<>"]/g,u=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[u])}function A(r,u){if(String(r).startsWith("#")&&r.length===7){let a=parseInt(r.slice(1,3),16),n=parseInt(r.slice(3,5),16),h=parseInt(r.slice(5,7),16);return`rgba(${a},${n},${h},${u})`}return r}function ee(r){return(Array.isArray(r)?r:r&&typeof r=="object"?Object.entries(r).map(([a,n])=>({name:a,days:n})):[]).map((a,n)=>({name:String(a.name||a.area||a.areaName||`Area ${n+1}`).trim(),days:d(a.days??a.pendencyDays??a.refillSpreadDays??a.currentDays)})).filter(a=>a.name)}function ue(r,u,a=15){if(!Number.isFinite(r)||!Number.isFinite(u))return"flat";let n=u-r;return n>=a?"up":n<=-a?"down":"flat"}function fe(r,u,a=Date.now()){return u?r?a-r>u:!0:!1}function z(r,u,a={}){if(!u)return r;let n={...r};return Object.entries(u).forEach(([h,i])=>{if(i==null||h==="type")return;let f=a[h]||h;f==="colors"&&i&&typeof i=="object"?n.colors={...n.colors||{},...i}:f==="metricFreshnessMinutes"&&i&&typeof i=="object"?n.metricFreshnessMinutes={...n.metricFreshnessMinutes||{},...i}:f.endsWith("Areas")?n[f]=ee(i):typeof n[f]=="number"?n[f]=d(i,n[f]):n[f]=i}),n}let me={normal:"#4f646e",stale:"#4f646e",disabled:"#777777"},te={staleText:null,neutralGradientMid:"#879aa3",staleLabelFill:null,normalLabelFill:null,normalLabelStroke:null,grid:null,detailGrid:null,tick:null,detailTick:null,transparent:"rgba(0,0,0,0)",white:"#fff",plotIcon:null};function S(r,u,a=!1){r.beginPath(),u.forEach(([n,h],i)=>i?r.lineTo(n,h):r.moveTo(n,h)),a&&r.closePath(),r.stroke()}function Ie(r,u,a,n,h){r.save(),r.strokeStyle=h,r.fillStyle=h,r.lineWidth=1.25,r.lineCap="round",r.lineJoin="round",u==="invoice"?(r.strokeRect(a-5,n+1,10,11.5),[4,7,10].forEach(i=>S(r,[[a-3,n+i],[a+3,n+i]]))):u==="person"?(r.beginPath(),r.arc(a,n+3.8,2.8,0,Math.PI*2),r.stroke(),r.beginPath(),r.moveTo(a-5,n+12),r.quadraticCurveTo(a,n+7.6,a+5,n+12),r.stroke()):u==="calendar"?(r.strokeRect(a-5,n+3,10,10),S(r,[[a-5,n+6],[a+5,n+6]]),S(r,[[a-2.8,n+1],[a-2.8,n+4]]),S(r,[[a+2.8,n+1],[a+2.8,n+4]]),r.fillRect(a-2.8,n+8,1.3,1.3),r.fillRect(a+1.5,n+8,1.3,1.3)):u==="deposit"?(r.strokeRect(a-5,n+4,10,8),S(r,[[a-6,n+4],[a,n+.5],[a+6,n+4]]),S(r,[[a-3,n+7],[a+3,n+7]]),S(r,[[a-3,n+10],[a+3,n+10]])):u==="hourglass"?S(r,[[a-5,n+1],[a+5,n+1],[a-5,n+12.5],[a+5,n+12.5]],!0):(S(r,[[a,n],[a-5.5,n+10.5],[a+5.5,n+10.5]],!0),S(r,[[a,n+3.5],[a,n+7.2]]),r.beginPath(),r.arc(a,n+9.2,.6,0,Math.PI*2),r.fill()),r.restore()}window.TvaControlInternals={getTrend:ue,isStale:fe,mergeData:z,normalizeAreas:ee},window.createTvaControl=function({canvas:u,container:a,config:n={},data:h={}}){!u&&a&&(u=a.querySelector("canvas")||a.appendChild(document.createElement("canvas"))),a=a||u.closest(".tva-control-container, .action-chart-container")||u.parentElement,a.classList.add("tva-control-container");let i=n&&Object.keys(n).length?n:h.init||{},f=i.parameters||[],B=i.warningLevels||[];if(!f.length)throw new Error("createTvaControl requires init.parameters");if(!B.length)throw new Error("createTvaControl requires init.warningLevels");let j=i.aliases||{},ae=f.map(e=>e.label),_=f.map(e=>e.key),q=B.filter(e=>e.showAxis!==!1).length*2+(i.extraAxes||[]).length,pe=()=>({colors:{...me,...i.colors||{}},uiColors:{...te,...i.uiColors||{}},staleAlpha:.35,trendThreshold:15}),s=z(pe(),h,j),re=e=>getComputedStyle(a).getPropertyValue(e).trim();function V(){let e=i.uiColors||{},t=(o,l,c)=>e[o]||re(l)||c;s.colors.normal=i.colors&&i.colors.normal?i.colors.normal:re("--tva-normal-line")||me.normal,s.colors.stale=i.colors&&i.colors.stale?i.colors.stale:re("--tva-stale-line")||s.colors.normal,s.uiColors={...te,...e,grid:t("grid","--tva-chart-grid","#222"),detailGrid:t("detailGrid","--tva-chart-detail-grid","#242424"),tick:t("tick","--tva-axis-text","#fff"),detailTick:t("detailTick","--tva-detail-axis-text","#aaa"),plotIcon:t("plotIcon","--tva-plot-icon",e.white||te.white),staleText:t("staleText","--tva-stale-text","#9aa6ac"),staleLabelFill:t("staleLabelFill","--tva-stale-label-fill","rgba(2,6,8,.84)"),normalLabelFill:t("normalLabelFill","--tva-normal-label-fill","rgba(5,34,30,.62)"),normalLabelStroke:t("normalLabelStroke","--tva-normal-label-stroke","rgba(116,137,148,.44)")}}V();let b=null,v="timeline",H=!0,L=0,x=1,J=null,R=Object.fromEntries(_.map(e=>[e,Date.now()]));h.updatedAt&&Object.entries(h.updatedAt).forEach(([e,t])=>{let o=typeof t=="string"?Date.parse(t):d(t,NaN);Number.isFinite(o)&&(R[e]=o)});let D=document.createElement("div");D.className="tva-chart-controls";let we=[{key:"timeline",label:i.title||"Timeline"},...f.filter(e=>e.detailMode).map(e=>({key:e.detailMode,label:e.detailTitle||`${e.label} Area Scan`}))].map(e=>`<option value="${de(e.key)}">${de(e.label)}</option>`).join("");D.innerHTML=`
+      <button type="button" class="tva-chart-back" hidden>\u2190</button>
+      <label class="tva-chart-heading"><span class="sr-only">Chart type</span><select class="tva-chart-mode-select">${we}</select></label>
+      <button type="button" class="tva-chart-fullscreen" title="Fullscreen chart" aria-label="Fullscreen chart"><span class="tva-fullscreen-icon" aria-hidden="true"></span></button>
+    `;let P=document.createElement("div");P.className="tva-alert-badge",P.hidden=!0,a.querySelector(".tva-chart-controls")||a.prepend(D),a.querySelector(".tva-alert-badge")||a.prepend(P),D.querySelector(".tva-chart-back").onclick=()=>se("timeline"),D.querySelector(".tva-chart-mode-select").onchange=e=>se(e.target.value),D.querySelector(".tva-chart-fullscreen").onclick=()=>{a.classList.toggle("tva-chart-fullscreen-mode"),ne(),b&&b.resize(),b&&b.update("none")};function be(e){return d(s[e.key],d(e.defaultValue))}function le(e,t,o,l){return d(e.thresholds&&e.thresholds[`${Y(t.key)}${o}`],l)}function Se(e){let t=be(e);return e.scale==="count10"?X(t*10,-100,100):e.scale==="daysCritical"?X(t/d(e.scaleBase,10)*100,0,d(e.scaleMax,165)):e.scale==="pendency"?t<=d(e.scaleIdeal,1)?0:X(t/d(e.scaleBase,3)*100,0,d(e.scaleMax,115)):t}function y(){return f.map(Se)}function I(e){return fe(R[f[e].key],d(f[e].refreshMinutes,0)*6e4)}function E(e){return s.colors[e.key]||s.colors[Y(e.key)]||s.colors.normal}function O(e,t){let o=null;return B.forEach(l=>{(t>le(f[e],l,"Upper",1/0)||t<le(f[e],l,"Lower",-1/0))&&(o=l)}),o}function K(e=!1){return e?s.colors.stale:A(s.colors.stale,d(s.staleAlpha,.35))}function Z(e,t){if(I(e))return K(!1);let o=O(e,t);return o?E(o):s.colors.normal}function he(e){let t=be(e),o=e.display||{},l=Number.isInteger(o.decimals)?o.decimals:0,c=Number.isInteger(t)||l===0?String(Math.round(t)):t.toFixed(l);return`${o.prefix||""}${c}${o.suffix||""}`}function oe(e){let t=y();return ue(J&&J[e],t[e],d(s.trendThreshold,15))}function ge(e){let t=Math.min(0,...e),o=Math.max(0,...e);t===o&&(t-=10,o+=10);let l=Math.max(8,(o-t)*.24);return{min:Math.floor(t-l),max:Math.ceil(o+l)}}function De(e){let t=y(),o=Z(e.p0DataIndex,t[e.p0DataIndex]),l=Z(e.p1DataIndex,t[e.p1DataIndex]);if(o===l||!e.p0||!e.p1)return l;let c=e.chart.ctx.createLinearGradient(e.p0.x,e.p0.y,e.p1.x,e.p1.y),m=I(e.p0DataIndex),g=I(e.p1DataIndex);if(m||g){let p=K(!1),M=K(!0),k=.12;return[[0,p],[Math.max(0,L-k),p],[L,M],[Math.min(1,L+k),p],[1,p]].sort((C,ie)=>C[0]-ie[0]).forEach(([C,ie])=>c.addColorStop(C,ie)),c}c.addColorStop(0,o);let T=O(e.p0DataIndex,t[e.p0DataIndex]),F=O(e.p1DataIndex,t[e.p1DataIndex]),w=T&&d(T.dominance,0),N=F&&d(F.dominance,0);return w?c.addColorStop(w,o):N?c.addColorStop(1-N,l):c.addColorStop(.5,s.uiColors.neutralGradientMid),c.addColorStop(1,l),c}let W=i.ambientGlow||{};function Ae(){return W.enabled!==!1&&W.enabled!==0}function Le(e){return e&&e.ambientGlow!==!1&&e.glow!==!1}function Me(e){if(v!=="timeline"||!Ae())return;let t=e.getDatasetMeta(q);if(!t||!e.chartArea)return;let o=y(),l=e.ctx;l.save(),l.beginPath(),l.rect(0,0,e.width,e.height),l.clip(),t.data.forEach((c,m)=>{if(I(m))return;let g=O(m,o[m]);if(!Le(g))return;let{x:T,y:F}=c.getProps(["x","y"],!0),w=g.glowColor||E(g),N=d(g.glowRadius,d(W.radius,72)),p=d(g.glowBlur,d(W.blur,36)),M=d(g.glowAlpha,d(W.alpha,.16)),k=N+p,C=l.createRadialGradient(T,F,0,T,F,k);C.addColorStop(0,A(w,M)),C.addColorStop(.34,A(w,M*.42)),C.addColorStop(.72,A(w,M*.12)),C.addColorStop(1,A(w,0)),l.fillStyle=C,l.fillRect(T-k,F-k,k*2,k*2)}),l.restore()}let Te={id:"tvaAmbientGlow",beforeDraw:Me},Fe={id:"tvaZeroAxis",beforeDatasetsDraw(e){if(v!=="timeline")return;let t=e.scales.y;if(!t)return;let o=t.getPixelForValue(0),l=e.ctx;l.save(),l.strokeStyle=A(s.colors.normal,.48),l.lineWidth=1.5,l.beginPath(),l.moveTo(0,o),l.lineTo(e.width,o),l.stroke(),l.restore()}};function Pe(e,t,o,l){let c=f[o],m=I(o),g=!m&&O(o,l[o]),T=g&&g.blink!==!1&&g.key!==B[0].key,{x:F,y:w}=t.getProps(["x","y"],!0),N=m?"STALE":he(c),p=e.ctx,M=w-e.chartArea.top<52?w+18:w-43;p.save(),p.globalAlpha=m?.72:T?H?1:.38:1,p.font="bold 9px monospace";let k=Math.max(28,p.measureText(N).width+10),C=Math.min(Math.max(F-k/2,e.chartArea.left+2),e.chartArea.right-k-2);p.fillStyle=m?s.uiColors.staleLabelFill:g?A(E(g),.18):s.uiColors.normalLabelFill,p.strokeStyle=m?K(!1):g?E(g):s.uiColors.normalLabelStroke,p.beginPath(),p.rect(C,M,k,31),p.fill(),p.stroke(),Ie(p,c.icon||"warning",C+k/2,M+3,m?s.uiColors.staleText:s.uiColors.plotIcon),p.fillStyle=m?s.uiColors.staleText:s.uiColors.plotIcon,p.textAlign="center",p.textBaseline="middle",p.fillText(N,C+k/2,M+24),p.restore()}let Ee={id:"tvaLabels",afterDatasetsDraw(e){if(v!=="timeline")return;let t=e.getDatasetMeta(q);if(!t)return;let o=y();t.data.forEach((l,c)=>Pe(e,l,c,o))}};function Oe(e,t){return f.map(o=>le(o,e,t,t==="Upper"?1/0:-1/0))}function $e(){return B.filter(e=>e.showAxis!==!1).flatMap(e=>["Upper","Lower"].map(t=>({label:`${e.label||e.key} ${t}`,data:Oe(e,t),borderColor:A(E(e),d(e.axisAlpha,.35)),borderWidth:d(e.axisWidth,1.6),borderDash:e.axisDash||[4,5],pointRadius:0,tension:.4})))}function Ge(){return(i.extraAxes||[]).map(e=>({label:e.label,data:f.map(t=>t.key===e.parameterKey?d(e.value):null),borderColor:e.color||s.colors.normal,borderWidth:d(e.width,1.4),borderDash:e.dash||[3,5],pointRadius:0,spanGaps:!1}))}function Ne(e){return{label:"Timeline Metric",data:e,borderWidth:3.5,tension:.4,fill:!1,borderColor:s.colors.normal,segment:{borderColor:De,borderDash:t=>I(t.p0DataIndex)||I(t.p1DataIndex)?[3,5]:[]},pointBorderColor:t=>Z(t.dataIndex,e[t.dataIndex]),pointBackgroundColor:t=>Z(t.dataIndex,e[t.dataIndex]),pointStyle:t=>I(t.dataIndex)||oe(t.dataIndex)==="flat"?"circle":"triangle",rotation:t=>oe(t.dataIndex)==="down"?180:0,pointRadius:t=>I(t.dataIndex)?3:oe(t.dataIndex)==="flat"?4:5.5,pointHoverRadius:8}}function Re(e,t){let o=t[0];o&&o.datasetIndex===q&&f[o.index].detailMode&&se(f[o.index].detailMode)}function Be(e){return{x:{offset:!1,border:{display:!1},grid:{color:s.uiColors.grid},ticks:{color:s.uiColors.tick,font:{weight:"bold",size:10},callback:(t,o)=>a.classList.contains("tva-chart-fullscreen-mode")?ae[o]:""}},y:{...ge(e),border:{display:!1},grid:{color:t=>t.tick.value===0?s.uiColors.transparent:s.uiColors.grid},ticks:{display:!1}}}}function ve(){let e=y();return{type:"line",data:{labels:ae,datasets:[...$e(),...Ge(),Ne(e)]},options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:2,right:6,top:d(i.topPadding,34),bottom:4}},onClick:Re,plugins:{title:{display:!1},legend:{display:!1},tooltip:{callbacks:{title:t=>t.length?ae[t[0].dataIndex]:"",label:t=>t.datasetIndex===q?he(f[t.dataIndex]):null}}},scales:Be(e)},plugins:[Te,Fe,Ee]}}function je(){return f.find(e=>e.detailMode===v)}function ke(e){return s.colors[e.level]||s.colors[Y(e.level)]||s.colors.normal}function ye(e,t){return t.findLast(o=>(e||0)>d(o.above,1/0))}function qe(){let e=je(),t=ee(s[e.areaKey]),o=t.map(c=>c.days),l=e.detailLevels||[];return{type:"bar",data:{labels:t.map(c=>c.name),datasets:[{data:o,borderWidth:1.2,borderRadius:8,backgroundColor:c=>{let m=ye(c.raw,l);return A(m?ke(m):s.colors.normal,m?.38:.3)},borderColor:c=>{let m=ye(c.raw,l);return m?ke(m):s.colors.normal}}]},options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},subtitle:{display:!0,text:e.detailSubtitle||"",color:s.colors[l[0]&&l[0].level]||s.colors.normal,font:{size:10,weight:"bold"}},legend:{display:!1}},scales:{x:{grid:{color:s.uiColors.detailGrid},ticks:{color:s.uiColors.tick,font:{weight:"bold",size:10}}},y:{min:0,max:Math.max(...o,...l.map(c=>d(c.above,0)))+1.5,ticks:{color:s.uiColors.detailTick,callback:c=>`${c}d`}}}}}}function We(){return y().map((e,t)=>I(t)?null:O(t,e)).filter(Boolean).sort((e,t)=>d(t.priority,0)-d(e.priority,0))[0]}function ne(){let e=D.querySelector(".tva-chart-mode-select"),t=D.querySelector(".tva-chart-back"),o=D.querySelector(".tva-chart-fullscreen"),l=We(),c=l&&(l.borderBlink||l.blinkBorder||l.borderAlert);e&&(e.value=v),t.hidden=v==="timeline",o.classList.toggle("is-restore",a.classList.contains("tva-chart-fullscreen-mode")),P.hidden=v!=="timeline"||!l,P.innerHTML=l?`<span class="tva-alert-icon" aria-hidden="true"></span>${l.label||l.key.toUpperCase()}`:"",P.style.color=l?E(l):"",a.classList.toggle("tva-border-alert",!!c),c?a.style.setProperty("--tva-border-alert-color",E(l)):a.style.removeProperty("--tva-border-alert-color")}function Q(){b&&b.destroy(),b=new Chart(u.getContext("2d"),v==="timeline"?ve():qe()),ne()}let $=null,G=null;function Ue(){return v!=="timeline"?!1:y().some((e,t)=>{if(I(t))return!1;let o=O(t,e);return!!(o&&o.blink!==!1)})}function ze(){return v==="timeline"&&y().some((e,t)=>I(t))}function U(){let e=Ue();e&&!$?$=setInterval(()=>{H=!H,b&&v==="timeline"&&b.update("none")},d(i.blinkMs,1100)):!e&&$&&(clearInterval($),$=null,H=!0);let t=ze();t&&!G?G=setInterval(()=>{L+=x*.08,L>=1?(L=1,x=-1):L<=0&&(L=0,x=1),b&&v==="timeline"&&b.update("none")},d(i.staleSweepMs,140)):!t&&G&&(clearInterval(G),G=null,L=0,x=1)}function Ce(){if(!b||v!=="timeline"){Q(),U();return}let e=ve();b.data.labels=e.data.labels,e.data.datasets.forEach((o,l)=>{b.data.datasets[l]&&(b.data.datasets[l].data=o.data)});let t=b.data.datasets[q];t&&(t.data=y()),Object.assign(b.options.scales.y,ge(y())),ne(),U(),b.update("none")}function se(e){v=e,Q(),U()}Q(),U();function _e(){let e={...ce(s),updatedAt:ce(R)};return delete e.uiColors,e.colors&&(i.colors&&i.colors.normal||delete e.colors.normal,i.colors&&i.colors.stale||delete e.colors.stale),e}function Ve(e){let t=Date.now();Object.entries(e||{}).forEach(([o,l])=>{let c=j[o]||o;_.includes(c)&&l!==void 0&&l!==null&&(R[c]=t)}),e&&e.updatedAt&&typeof e.updatedAt=="object"&&Object.entries(e.updatedAt).forEach(([o,l])=>{let c=j[o]||o,m=typeof l=="string"?Date.parse(l):d(l,NaN);_.includes(c)&&Number.isFinite(m)&&(R[c]=m)})}return{update(e){let t=y();s=z(s,e,j),V(),y().some((o,l)=>o!==t[l])&&(J=t),Ve(e),Ce()},setData(e){J=y(),s=z(pe(),e,j),V(),R=Object.fromEntries(_.map(t=>[t,Date.now()])),Ce()},refreshTheme(){V(),Q(),U()},getData(){return _e()},destroy(){$&&clearInterval($),G&&clearInterval(G),a.classList.remove("tva-border-alert"),a.style.removeProperty("--tva-border-alert-color"),b&&b.destroy(),D.remove(),P.remove()}}}})();})();
diff --git a/package.json b/package.json
@@ -0,0 +1,11 @@
+{
+  "scripts": {
+    "build": "pnpm run build:tva && pnpm run build:logs",
+    "build:tva": "esbuild tva-control.js --bundle --minify --legal-comments=none --outfile=out/tva-control.js",
+    "build:logs": "node -e 'import(\"esbuild\").then(({build})=>build({stdin:{contents:\"import \\\"./gt.js\\\";import \\\"./logs.js\\\"\",resolveDir:\".\"},outfile:\"out/logs.js\",bundle:true,minify:true,legalComments:\"none\"}))'",
+    "test": "node --check tva-control.js && node --check logs.js && node --check out/tva-control.js && node --check out/logs.js && node tests/tva-control.test.js"
+  },
+  "devDependencies": {
+    "esbuild": "latest"
+  }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
@@ -0,0 +1,285 @@
+lockfileVersion: '9.0'
+
+settings:
+  autoInstallPeers: true
+  excludeLinksFromLockfile: false
+
+importers:
+
+  .:
+    devDependencies:
+      esbuild:
+        specifier: latest
+        version: 0.28.2
+
+packages:
+
+  '@esbuild/aix-ppc64@0.28.2':
+    resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
+    engines: {node: '>=18'}
+    cpu: [ppc64]
+    os: [aix]
+
+  '@esbuild/android-arm64@0.28.2':
+    resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [android]
+
+  '@esbuild/android-arm@0.28.2':
+    resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}
+    engines: {node: '>=18'}
+    cpu: [arm]
+    os: [android]
+
+  '@esbuild/android-x64@0.28.2':
+    resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [android]
+
+  '@esbuild/darwin-arm64@0.28.2':
+    resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [darwin]
+
+  '@esbuild/darwin-x64@0.28.2':
+    resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [darwin]
+
+  '@esbuild/freebsd-arm64@0.28.2':
+    resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [freebsd]
+
+  '@esbuild/freebsd-x64@0.28.2':
+    resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [freebsd]
+
+  '@esbuild/linux-arm64@0.28.2':
+    resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [linux]
+
+  '@esbuild/linux-arm@0.28.2':
+    resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}
+    engines: {node: '>=18'}
+    cpu: [arm]
+    os: [linux]
+
+  '@esbuild/linux-ia32@0.28.2':
+    resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}
+    engines: {node: '>=18'}
+    cpu: [ia32]
+    os: [linux]
+
+  '@esbuild/linux-loong64@0.28.2':
+    resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}
+    engines: {node: '>=18'}
+    cpu: [loong64]
+    os: [linux]
+
+  '@esbuild/linux-mips64el@0.28.2':
+    resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}
+    engines: {node: '>=18'}
+    cpu: [mips64el]
+    os: [linux]
+
+  '@esbuild/linux-ppc64@0.28.2':
+    resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}
+    engines: {node: '>=18'}
+    cpu: [ppc64]
+    os: [linux]
+
+  '@esbuild/linux-riscv64@0.28.2':
+    resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}
+    engines: {node: '>=18'}
+    cpu: [riscv64]
+    os: [linux]
+
+  '@esbuild/linux-s390x@0.28.2':
+    resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}
+    engines: {node: '>=18'}
+    cpu: [s390x]
+    os: [linux]
+
+  '@esbuild/linux-x64@0.28.2':
+    resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [linux]
+
+  '@esbuild/netbsd-arm64@0.28.2':
+    resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [netbsd]
+
+  '@esbuild/netbsd-x64@0.28.2':
+    resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [netbsd]
+
+  '@esbuild/openbsd-arm64@0.28.2':
+    resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [openbsd]
+
+  '@esbuild/openbsd-x64@0.28.2':
+    resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [openbsd]
+
+  '@esbuild/openharmony-arm64@0.28.2':
+    resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [openharmony]
+
+  '@esbuild/sunos-x64@0.28.2':
+    resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [sunos]
+
+  '@esbuild/win32-arm64@0.28.2':
+    resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}
+    engines: {node: '>=18'}
+    cpu: [arm64]
+    os: [win32]
+
+  '@esbuild/win32-ia32@0.28.2':
+    resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}
+    engines: {node: '>=18'}
+    cpu: [ia32]
+    os: [win32]
+
+  '@esbuild/win32-x64@0.28.2':
+    resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}
+    engines: {node: '>=18'}
+    cpu: [x64]
+    os: [win32]
+
+  esbuild@0.28.2:
+    resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}
+    engines: {node: '>=18'}
+    hasBin: true
+
+snapshots:
+
+  '@esbuild/aix-ppc64@0.28.2':
+    optional: true
+
+  '@esbuild/android-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/android-arm@0.28.2':
+    optional: true
+
+  '@esbuild/android-x64@0.28.2':
+    optional: true
+
+  '@esbuild/darwin-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/darwin-x64@0.28.2':
+    optional: true
+
+  '@esbuild/freebsd-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/freebsd-x64@0.28.2':
+    optional: true
+
+  '@esbuild/linux-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/linux-arm@0.28.2':
+    optional: true
+
+  '@esbuild/linux-ia32@0.28.2':
+    optional: true
+
+  '@esbuild/linux-loong64@0.28.2':
+    optional: true
+
+  '@esbuild/linux-mips64el@0.28.2':
+    optional: true
+
+  '@esbuild/linux-ppc64@0.28.2':
+    optional: true
+
+  '@esbuild/linux-riscv64@0.28.2':
+    optional: true
+
+  '@esbuild/linux-s390x@0.28.2':
+    optional: true
+
+  '@esbuild/linux-x64@0.28.2':
+    optional: true
+
+  '@esbuild/netbsd-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/netbsd-x64@0.28.2':
+    optional: true
+
+  '@esbuild/openbsd-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/openbsd-x64@0.28.2':
+    optional: true
+
+  '@esbuild/openharmony-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/sunos-x64@0.28.2':
+    optional: true
+
+  '@esbuild/win32-arm64@0.28.2':
+    optional: true
+
+  '@esbuild/win32-ia32@0.28.2':
+    optional: true
+
+  '@esbuild/win32-x64@0.28.2':
+    optional: true
+
+  esbuild@0.28.2:
+    optionalDependencies:
+      '@esbuild/aix-ppc64': 0.28.2
+      '@esbuild/android-arm': 0.28.2
+      '@esbuild/android-arm64': 0.28.2
+      '@esbuild/android-x64': 0.28.2
+      '@esbuild/darwin-arm64': 0.28.2
+      '@esbuild/darwin-x64': 0.28.2
+      '@esbuild/freebsd-arm64': 0.28.2
+      '@esbuild/freebsd-x64': 0.28.2
+      '@esbuild/linux-arm': 0.28.2
+      '@esbuild/linux-arm64': 0.28.2
+      '@esbuild/linux-ia32': 0.28.2
+      '@esbuild/linux-loong64': 0.28.2
+      '@esbuild/linux-mips64el': 0.28.2
+      '@esbuild/linux-ppc64': 0.28.2
+      '@esbuild/linux-riscv64': 0.28.2
+      '@esbuild/linux-s390x': 0.28.2
+      '@esbuild/linux-x64': 0.28.2
+      '@esbuild/netbsd-arm64': 0.28.2
+      '@esbuild/netbsd-x64': 0.28.2
+      '@esbuild/openbsd-arm64': 0.28.2
+      '@esbuild/openbsd-x64': 0.28.2
+      '@esbuild/openharmony-arm64': 0.28.2
+      '@esbuild/sunos-x64': 0.28.2
+      '@esbuild/win32-arm64': 0.28.2
+      '@esbuild/win32-ia32': 0.28.2
+      '@esbuild/win32-x64': 0.28.2
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
@@ -0,0 +1,2 @@
+allowBuilds:
+  esbuild: true