// snippets/Loading/TTFB-Sub-Parts.js | sha256:bd057af385152ba3 | https://github.com/nucliweb/webperf-snippets/blob/main/snippets/Loading/TTFB-Sub-Parts.js (()=>{new PerformanceObserver(e=>{const[t]=e.getEntriesByType("navigation"),r=t.activationStart||0,n=Math.max((t.workerStart||t.fetchStart)-r,0),o=Math.max(t.domainLookupStart-r,0),a=Math.max(t.connectStart-r,0),i=Math.max(t.connectEnd-r,0),s=t.secureConnectionStart>0?Math.max(t.secureConnectionStart-r,0):i,c=Math.max(t.responseStart-r,0);let d,u;c<=800?(d="Good",u="#22c55e"):c<=1800?(d="Needs Improvement",u="#f59e0b"):(d="Poor",u="#ef4444");const m=[{name:"Redirect/Wait",duration:n,icon:"🔄"},{name:"Service Worker/Cache",duration:o-n,icon:"⚙️"},{name:"DNS Lookup",duration:a-o,icon:"🔍"},{name:"TCP Connection",duration:s-a,icon:"🔌"},{name:"SSL/TLS",duration:i-s,icon:"🔒"},{name:"Server Response",duration:c-i,icon:"📥"}];m.forEach(({})=>{}),m.reduce((e,t)=>e.duration>t.duration?e:t)}).observe({type:"navigation",buffered:!0});const[e]=performance.getEntriesByType("navigation");if(!e)return{script:"TTFB-Sub-Parts",status:"error",error:"No navigation entry"};const t=e.activationStart||0,r=Math.max(0,e.responseStart-t),n=Math.round(r),o=n<=800?"good":n<=1800?"needs-improvement":"poor",a=Math.max((e.workerStart||e.fetchStart)-t,0),i=Math.max(e.domainLookupStart-t,0),s=Math.max(e.connectStart-t,0),c=Math.max(e.connectEnd-t,0),d=e.secureConnectionStart>0?Math.max(e.secureConnectionStart-t,0):c,u=[{key:"redirectWait",duration:a},{key:"serviceWorkerCache",duration:i-a},{key:"dnsLookup",duration:s-i},{key:"tcpConnection",duration:d-s},{key:"sslTls",duration:c-d},{key:"serverResponse",duration:r-c}],m=u.reduce((e,t)=>e.duration>t.duration?e:t),h={redirectWait:"redirect and wait",serviceWorkerCache:"service worker and cache",dnsLookup:"DNS lookup",tcpConnection:"TCP connection",sslTls:"SSL/TLS",serverResponse:"server response"},p={redirectWait:"minimize redirects and link to the final URL",serviceWorkerCache:"review the service worker startup and consider a cache-first strategy",dnsLookup:"use dns-prefetch or a faster DNS provider",tcpConnection:"enable HTTP/2 or HTTP/3 and keep connections alive",sslTls:"enable TLS 1.3 and session resumption, and check the certificate chain",serverResponse:"optimize server processing, cache the HTML and check slow queries"},k=[];if("good"!==o){const e=Math.round(m.duration),t=r>0?Math.round(m.duration/r*100):0;k.push({code:"slow-ttfb",severity:"poor"===o?"error":"warning",message:`TTFB is ${n} ms (${o}); ${h[m.key]} takes ${e} ms of it (${t}%). Fix: ${p[m.key]}.`})}return{script:"TTFB-Sub-Parts",status:"ok",metric:"TTFB",value:n,unit:"ms",rating:o,thresholds:{good:800,needsImprovement:1800},details:{subParts:Object.fromEntries(u.map(e=>[e.key,{value:Math.round(e.duration),unit:"ms"}])),slowestPhase:m.key},issues:k}})();