// snippets/Loading/First-And-Third-Party-Script-Timings.js | sha256:e7def6fa54125f16 | https://github.com/nucliweb/webperf-snippets/blob/main/snippets/Loading/First-And-Third-Party-Script-Timings.js (()=>{const t=[];function e(t){const e=t.replace(/\.$/,"");if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e)||e.includes(":"))return e;const s=e.split(".");return s.length<=2?e:2===s[s.length-1].length&&["ac","co","com","edu","go","gob","gouv","gov","govt","mil","ne","net","nom","or","org","sch"].includes(s[s.length-2])?s.slice(-3).join("."):s.slice(-2).join(".")}const s=performance.getEntriesByType("resource").filter(t=>!t.name.endsWith("#webperf-snippets")).filter(t=>"script"===t.initiatorType).map(s=>{const n=new URL(s.name),o=function(s){const n=e(s);return n===e(location.hostname)||t.some(t=>e(String(t).trim().toLowerCase().replace(/^[a-z]+:\/\//,"").split("/")[0])===n)}(n.hostname),r=s.requestStart>0,a={dns:s.domainLookupEnd-s.domainLookupStart,tcp:s.connectEnd-s.connectStart,tls:s.secureConnectionStart>0?s.connectEnd-s.secureConnectionStart:0,request:s.responseStart-s.requestStart,response:s.responseEnd-s.responseStart,total:s.responseEnd-s.startTime};if(s.secureConnectionStart>0&&(a.tcp=s.secureConnectionStart-s.connectStart),!r)for(const t of["dns","tcp","tls","request","response"])a[t]=null;return{name:s.name,shortName:n.pathname.split("/").pop()||n.hostname,host:n.hostname,firstParty:o,hasTiming:r,size:s.transferSize||0,...a}}),n=s.filter(t=>t.firstParty),o=s.filter(t=>!t.firstParty);function r(t){const e=t.filter(t=>t.hasTiming),s={};return["dns","tcp","tls","request","response","total"].forEach(t=>{const n=e.map(e=>e[t]).filter(t=>t>0);s[t]=n.length>0?{avg:n.reduce((t,e)=>t+e,0)/n.length,max:Math.max(...n),total:n.reduce((t,e)=>t+e,0)}:{avg:0,max:0,total:0}}),{count:t.length,withTiming:e.length,withoutTiming:t.length-e.length,stats:s}}const a=r(n),i=r(o),c=t=>null===t?null:Math.round(t),l=t=>t>0?t.toFixed(1)+"ms":"-",p=(t,e)=>{if(t<=0||e<=0)return"";const s=Math.min(Math.round(t/e*15),15);return"█".repeat(s)+"░".repeat(15-s)};if([{key:"dns",name:"DNS Lookup",icon:"🔍"},{key:"tcp",name:"TCP Connection",icon:"🔌"},{key:"tls",name:"TLS/SSL",icon:"🔒"},{key:"request",name:"Request (TTFB)",icon:"📤"},{key:"response",name:"Response",icon:"📥"},{key:"total",name:"Total",icon:"⏱️"}].forEach(({key:t})=>{l(a.stats[t]?.avg||0).padStart(10),l(i.stats[t]?.avg||0).padStart(10)}),0===n.length);else{const t=Math.max(...n.map(t=>t.total));n.sort((t,e)=>e.total-t.total).slice(0,15).map(e=>({Script:e.shortName,DNS:l(e.dns),TCP:l(e.tcp),TLS:l(e.tls),Request:l(e.request),Response:l(e.response),Total:l(e.total),"":p(e.total,t)}))}if(0===o.length);else{const t=Math.max(...o.map(t=>t.total));o.sort((t,e)=>e.total-t.total).slice(0,15).map(e=>({Script:e.shortName,Host:e.host.length>25?e.host.slice(0,22)+"...":e.host,DNS:l(e.dns),TCP:l(e.tcp),TLS:l(e.tls),Request:l(e.request),Response:l(e.response),Total:l(e.total),"":p(e.total,t)}))}const h=s.filter(t=>t.total>500);h.length>0&&h.sort((t,e)=>e.total-t.total).forEach(t=>{const e=[];t.dns>50&&e.push(`DNS: ${l(t.dns)}`),t.tcp>50&&e.push(`TCP: ${l(t.tcp)}`),t.tls>50&&e.push(`TLS: ${l(t.tls)}`),t.request>100&&e.push(`Request: ${l(t.request)}`),t.response>200&&e.push(`Response: ${l(t.response)}`)});const u=s.some(t=>t.dns>100),m=s.some(t=>t.tcp>100),d=s.some(t=>t.request>200),g=[...s].sort((t,e)=>e.total-t.total);return{script:"First-And-Third-Party-Script-Timings",status:"ok",count:s.length,corsLimitedAnalysis:i.withoutTiming>0,details:{firstPartyCount:n.length,thirdPartyCount:o.length,corsRestrictedCount:i.withoutTiming,slowScriptCount:h.length,firstPartyAvgTotalMs:Math.round(a.stats.total?.avg||0),thirdPartyAvgTotalMs:Math.round(i.stats.total?.avg||0)},items:g.slice(0,50).map(t=>({shortName:t.shortName,host:t.host,firstParty:t.firstParty,totalMs:Math.round(t.total),dnsMs:c(t.dns),tcpMs:c(t.tcp),requestMs:c(t.request),responseMs:c(t.response),hasTiming:t.hasTiming})),issues:[...h.length>0?[{code:"slow-scripts",severity:"warning",message:`${h.length} script(s) take over 500ms to load`}]:[],...u?[{code:"slow-dns",severity:"warning",message:"Slow DNS lookups detected (>100ms). Add dns-prefetch or preconnect."}]:[],...m?[{code:"slow-connection",severity:"warning",message:"Slow TCP connections detected (>100ms). Add preconnect for critical origins."}]:[],...d?[{code:"slow-server",severity:"warning",message:"Slow server response times detected (>200ms). Consider CDN or self-hosting."}]:[]]}})();