// snippets/Loading/Cache-Strategy-Analysis.js | sha256:5d3f9e708bc0711f | https://github.com/nucliweb/webperf-snippets/blob/main/snippets/Loading/Cache-Strategy-Analysis.js (async()=>{function e(e){try{const t=new URL(e,location.href);return/^https?:$/.test(t.protocol)?(t.hash="webperf-snippets",t.href):e}catch{return e}}const t=[];function n(e){const t=e.replace(/\.$/,"");if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(":"))return t;const n=t.split(".");return n.length<=2?t:2===n[n.length-1].length&&["ac","co","com","edu","go","gob","gouv","gov","govt","mil","ne","net","nom","or","org","sch"].includes(n[n.length-2])?n.slice(-3).join("."):n.slice(-2).join(".")}function r(e){if(null==e||Number.isNaN(e))return"-";if(0===e)return"0 B";const t=["B","KB","MB","GB"],n=Math.max(0,Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1));return(e/Math.pow(1024,n)).toFixed(1)+" "+t[n]}function o(e){const t=(e.name||"").split("?")[0].toLowerCase();return/\.(woff2?|ttf|otf|eot)$/.test(t)?"font":/\.(png|jpe?g|gif|webp|avif|svg|ico|bmp)$/.test(t)?"image":/\.(mp4|webm|ogg|mov)$/.test(t)?"video":/\.(mp3|wav|flac|aac)$/.test(t)?"audio":/\.css$/.test(t)?"style":/\.js$/.test(t)?"script":{script:"script",link:"style",css:"style",img:"image",image:"image",video:"video",audio:"audio",font:"font",fetch:"fetch",xmlhttprequest:"xhr",iframe:"iframe",other:"other"}[e.initiatorType]||e.initiatorType||"other"}function s(e){return[/[.-][a-f0-9]{8,32}\.(js|css|woff2?|ttf|eot|svg|png|jpe?g|webp|avif)(\?|$)/,/[?&](v|version|hash|rev|_v)=[a-zA-Z0-9._-]+/].some(t=>t.test(e))}function a(e){return["script","style","font","image"].includes(e)}function i(e){const t={};if(!e)return t;for(const n of e.split(",")){const[e,r]=n.trim().split("=");t[e.trim().toLowerCase()]=void 0===r||r.trim().replace(/"/g,"")}return t}function c(e){if(!e)return"unknown";const t=i(e["cache-control"]||""),n=!!e.expires;if(t["no-store"])return"no-store";if(t["no-cache"])return"no-cache";if(t.immutable)return"immutable";if(t["stale-while-revalidate"])return"swr";if(t["must-revalidate"]&&(e.etag||e["last-modified"]))return"must-revalidate";const r=void 0!==t["max-age"]?parseInt(t["max-age"],10):null,o=(void 0!==t["s-maxage"]?parseInt(t["s-maxage"],10):null)??r;return null!==o?0===o?"no-cache":o<3600?"short":o<=86400?"medium":"long":n&&!e["cache-control"]?"expires-only":0!==Object.keys(t).length||n?"unknown":"none"}function l(e){if(!e)return{cdn:"unknown",status:"unknown"};if(e["cf-cache-status"])return{cdn:"Cloudflare",status:e["cf-cache-status"]};if(e["x-vercel-cache"])return{cdn:"Vercel",status:e["x-vercel-cache"]};if(e["x-cache"]){const t=e["x-cache"].toUpperCase();return{cdn:e["x-amz-cf-id"]?"CloudFront":"CDN",status:t.includes("HIT")?"HIT":"MISS"}}if(e.age)return{cdn:"Proxy/CDN",status:`HIT (Age: ${e.age}s)`};if(e.via)return{cdn:`Proxy (${e.via})`,status:"proxied"};if(e["server-timing"]){const t=e["server-timing"].toLowerCase();if(t.includes("cdn-cache")||t.includes("cache;"))return{cdn:"CDN (Server-Timing)",status:t.includes("hit")?"HIT":"MISS"}}return{cdn:"none",status:"no-cdn-headers"}}const d=performance.getEntriesByType("resource").filter(e=>!e.name.endsWith("#webperf-snippets")),h=new Map;for(const e of d)h.set(e.name,(h.get(e.name)||0)+1);const u=d.map(e=>{let r;try{r=new URL(e.name)}catch{r={hostname:location.hostname,pathname:e.name}}const a=function(e){const r=n(e);return r===n(location.hostname)||t.some(e=>n(String(e).trim().toLowerCase().replace(/^[a-z]+:\/\//,"").split("/")[0])===r)}(r.hostname),i=e.encodedBodySize>0&&0===e.transferSize,c=0===e.encodedBodySize&&0===e.transferSize&&!a;return{url:e.name,shortName:(r.pathname||e.name).split("/").filter(Boolean).pop()||r.hostname,host:r.hostname,firstParty:a,type:o(e),transferSize:e.transferSize||0,encodedBodySize:e.encodedBodySize||0,decodedBodySize:e.decodedBodySize||0,isCached:i,isCorsRestricted:c,nextHopProtocol:e.nextHopProtocol||"unknown",duration:e.duration,hasHash:s(e.name),isDuplicate:(h.get(e.name)||1)>1,headers:null,cacheStrategy:null,cdnInfo:null,antiPatterns:[]}}),f=new Set(["script","style","font","image"]),g=u.filter(e=>e.url.startsWith(location.origin+"/")&&f.has(e.type)),m=[...new Set(g.map(e=>e.url))],p=new Map;for(let t=0;t{try{const n=await fetch(e(t),{method:"HEAD",cache:"no-store"});if(!n.ok)return void p.set(t,null);const r={};for(const[e,t]of n.headers)r[e.toLowerCase()]=t;p.set(t,r)}catch{p.set(t,null)}}))}for(const e of u)e.headers=p.get(e.url)||null;for(const e of u)e.cacheStrategy=e.headers?c(e.headers):e.isCorsRestricted?"unknown (CORS)":e.isCached?"cached (inferred)":"unknown",e.cdnInfo=l(e.headers);const y=new Set(["immutable","long","medium","swr","must-revalidate","cached (inferred)"]);for(const e of u){if(!e.headers)continue;const t=i(e.headers["cache-control"]||""),n=void 0!==t["max-age"]?parseInt(t["max-age"],10):null,o=e.cacheStrategy,s=e.type;a(s)&&t["no-store"]&&e.antiPatterns.push({code:"static-no-store",id:"static-no-store",severity:"error",message:`${s} asset with no-store; static assets should be cacheable`}),e.hasHash&&null!==n&&n<86400&&!t["no-store"]&&e.antiPatterns.push({code:"versioned-short-cache",id:"versioned-short-cache",severity:"warning",message:`Versioned URL (hash detected) but max-age=${n}s: consider long cache or immutable`}),e.hasHash&&!t.immutable&&!t["no-store"]&&(null===n||n>=86400)&&e.antiPatterns.push({code:"versioned-not-immutable",id:"versioned-not-immutable",severity:"info",message:"Versioned URL (hash detected) without Cache-Control: immutable"}),e.decodedBodySize>102400&&["none","no-store","no-cache"].includes(o)&&e.antiPatterns.push({code:"large-no-cache",id:"large-no-cache",severity:"error",message:`Large resource (${r(e.decodedBodySize)}) with no effective cache`}),e.headers.expires&&!e.headers["cache-control"]&&e.antiPatterns.push({code:"expires-without-cc",id:"expires-without-cc",severity:"warning",message:"Uses Expires header without Cache-Control (outdated pattern)"}),a(s)&&0===n&&e.antiPatterns.push({code:"maxage-zero-static",id:"maxage-zero-static",severity:"warning",message:"Static asset with max-age=0, which forces revalidation on every request"}),a(s)&&null!==n&&n>0&&n<3600&&!t["no-store"]&&e.antiPatterns.push({code:"short-cache-static",id:"short-cache-static",severity:"warning",message:`Static asset with max-age=${n}s (< 1h): consider a longer cache duration`})}const w=u.filter(e=>e.cdnInfo&&"none"!==e.cdnInfo.cdn&&"unknown"!==e.cdnInfo.cdn),v=w.filter(e=>e.cdnInfo.status.toUpperCase().startsWith("HIT")).length,S=w.length>0?Math.round(v/w.length*100):null,C=u.filter(e=>null!==e.headers),x=C.filter(e=>y.has(e.cacheStrategy)),b=C.length>0?Math.round(x.length/C.length*100):null,P=u.filter(e=>e.isCached).reduce((e,t)=>e+t.decodedBodySize,0),$={};for(const e of u){const t=e.nextHopProtocol||"unknown";$[t]=($[t]||0)+1}const z=u.filter(e=>e.encodedBodySize>1024&&e.decodedBodySize>0&&e.encodedBodySize/e.decodedBodySize>.9&&["script","style","fetch","xhr"].includes(e.type)),B=[...new Set(u.filter(e=>e.isDuplicate).map(e=>e.url))].map(e=>{const t=u.filter(t=>t.url===e),n=t.filter(e=>!e.isCached).length;return{url:e,shortName:t[0]?.shortName||e,count:h.get(e),type:t[0]?.type||"unknown",uncachedLoads:n,costly:n>0}}),k=B.filter(e=>e.costly),R=B.filter(e=>!e.costly);for(const e of z)e.antiPatterns.push({code:"uncompressed",id:"uncompressed",severity:"warning",message:`${e.type} sent uncompressed (${r(e.encodedBodySize)} on the wire for ${r(e.decodedBodySize)}): enable Brotli or gzip`});for(const e of k)u.find(t=>t.url===e.url).antiPatterns.push({code:"duplicate-uncached",id:"duplicate-uncached",severity:"warning",message:`Loaded ${e.count} times, ${e.uncachedLoads} from the network: load it once or make it cacheable`});if(0===u.length)return{script:"Cache-Strategy-Analysis",status:"error",error:"No resources in the Performance API buffer (performance.clearResourceTimings() may have been called). Reload the page and run the snippet again."};const H=u.flatMap(e=>e.antiPatterns.map(t=>({...t,resource:e.shortName,url:e.url}))),I={};for(const e of u){const t=e.cacheStrategy;I[t]||(I[t]=0),I[t]++}const M=u.filter(e=>["none","no-store","no-cache"].includes(e.cacheStrategy)),T=u.filter(e=>"short"===e.cacheStrategy),L=u.filter(e=>null!==e.headers).length,N=Math.round(L/u.length*100),A=u.filter(e=>e.isCorsRestricted).length,D=u.filter(e=>!(null!==e.headers||e.isCorsRestricted||e.url.startsWith(location.origin+"/")&&f.has(e.type)));let E=null;if(N<50){const e=new Map;for(const t of u.filter(e=>null===e.headers))e.set(t.host,(e.get(t.host)||0)+1);const t=[...e.entries()].sort((e,t)=>t[1]-e[1]).slice(0,3).map(([e])=>e).join(", ");E={severity:"info",code:"header-coverage",id:"header-coverage",message:`Cache headers were read for ${L} of ${u.length} resources (${N}%): the rest are on other origins or are not static assets, so their Cache-Control cannot be read from the page. Most of them are on ${t}; check those hosts in the Network panel or with curl -I`}}if(D.length>0&&[...new Set(D.map(e=>e.type))].join(", "),H.length>0&&(H.filter(e=>"error"===e.severity),H.filter(e=>"warning"===e.severity),H.filter(e=>"info"===e.severity)),["immutable","long","medium","short","swr","must-revalidate","no-cache","no-store","expires-only","none","cached (inferred)","unknown (CORS)","unknown"].filter(e=>I[e]).map(e=>({Strategy:e,Count:I[e],"% of Total":`${Math.round(I[e]/u.length*100)}%`,Effective:y.has(e)?"✅":"❌"})),H.length>0)for(const e of["error","warning","info"])H.filter(t=>t.severity===e);const j=["🔴","🟡","â„šī¸"],U=[],O=(e,t)=>U.push({icon:e,text:t});if(M.filter(e=>a(e.type)).length>0&&O("🔴","Add Cache-Control headers to static assets (JS, CSS, fonts, images). Start with max-age=86400 and move to immutable for versioned files."),T.filter(e=>e.hasHash).length>0&&O("🟡","Versioned files (with content hash) should use long cache or Cache-Control: immutable; they can be cached indefinitely since the URL changes on update."),H.some(e=>"expires-without-cc"===e.id)&&O("🟡","Replace Expires headers with Cache-Control: max-age. Expires is an outdated mechanism and less reliable."),null!==b&&b<50&&O("🔴",`Cache efficiency is low (${b}%, measured on the ${C.length} resources whose cache headers could be read). Review caching strategy for those static assets.`),null!==S&&S<70&&O("🟡",`CDN hit rate is ${S}%. Check CDN cache rules and ensure static assets have appropriate TTLs.`),$["http/1.1"]>0&&O("🟡",`${$["http/1.1"]} resources still use HTTP/1.1. Consider upgrading to HTTP/2 for better multiplexing.`),z.length>0&&O("🟡",`${z.length} text resources appear uncompressed. Enable Brotli or gzip compression on your server.`),k.length>0?O("🟡",`${k.length} resources are loaded multiple times with uncached network requests. Check for duplicate script, stylesheet, or fetch includes.`):R.length>0&&O("â„šī¸",`${R.length} resources are requested multiple times but served from cache; low performance impact, but worth reviewing for correctness.`),A>0&&0===L&&O("â„šī¸","All resources are cross-origin CORS-restricted, so header analysis was limited. Add Timing-Allow-Origin for more insights."),U.length>0)for(const e of U);u.filter(e=>!e.firstParty);const q=null===b?null:b>=80?"good":b>=50?"needs-improvement":"poor",V=u.filter(e=>e.antiPatterns.length>0||["none","no-store","no-cache","short"].includes(e.cacheStrategy));return{script:"Cache-Strategy-Analysis",status:"ok",count:u.length,corsLimitedAnalysis:A>0,details:{totalResources:u.length,actionableCount:V.length,headersAnalyzed:L,corsRestricted:A,excludedFromHeaders:D.length,headerCoveragePercent:N,cacheEfficiencyPercent:b,cacheEfficiencyRating:q,cacheEfficiencyResources:C.length,bandwidthSavedBytes:P,strategyDistribution:I,cdnDetected:w.length>0,cdnHitRate:S,cdnHitRateRating:null===S?null:S>=70?"good":"poor",antiPatternCount:H.length,duplicatesCostlyCount:k.length,uncompressedCount:z.length,protocolDistribution:$},items:V.sort((e,t)=>t.antiPatterns.length-e.antiPatterns.length||t.decodedBodySize-e.decodedBodySize).slice(0,50).map(e=>({shortName:e.shortName,host:e.host,type:e.type,firstParty:e.firstParty,cacheStrategy:e.cacheStrategy,sizeBytes:e.decodedBodySize,isCached:e.isCached,antiPatterns:e.antiPatterns.map(e=>e.id)})),issues:[...H.map(e=>({code:e.code,severity:e.severity,id:e.id,resource:e.resource,message:e.message,target:e.url})),...E?[E]:[]],recommendations:[...U].sort((e,t)=>j.indexOf(e.icon)-j.indexOf(t.icon)).map(e=>e.text)}})();