// snippets/Loading/Prefetch-Resource-Validation.js | sha256:f1c557ac1ad1c6d5 | https://github.com/nucliweb/webperf-snippets/blob/main/snippets/Loading/Prefetch-Resource-Validation.js (()=>{const e=Array.from(document.querySelectorAll('link[rel="prefetch"]'));if(0===e.length)return{script:"Prefetch-Resource-Validation",status:"ok",count:0,items:[],issues:[{code:"no-prefetch",severity:"info",message:'No prefetch hints on this page (rel="prefetch"), so there was nothing to validate.'}]};const s=performance.getEntriesByType("resource").filter(e=>!e.name.endsWith("#webperf-snippets")),t=new Map;s.forEach(e=>{try{const s=new URL(e.name,location.origin).href;t.has(s)||t.set(s,[]),t.get(s).push(e)}catch{}});const i=new Set(["script","style","font","image","video","audio","document","fetch","track","worker"]),r=[],n=[],a=new Set;let o=0,d=0;e.forEach(e=>{const s=e.href,c=e.getAttribute("as")||"unknown",l=s.split("/").pop()?.split("?")[0]?.split("#")[0]||s;let p;try{p=new URL(s,location.origin).href}catch{p=s}const h=t.get(p)||[],g=h[0],u={link:e,href:s,shortUrl:l,as:c,size:0,transferSize:0,duration:0,loaded:!1,isCurrentPage:!1,warnings:[]};if("unknown"===c?u.warnings.push({code:"missing-as",type:"missing-as",severity:"warning",message:"Missing 'as' attribute - browser cannot apply correct MIME type matching"}):i.has(c)||u.warnings.push({code:"invalid-as",type:"invalid-as",severity:"warning",message:`Invalid 'as' value: "${c}" - should be one of: ${Array.from(i).join(", ")}`}),a.has(p)&&u.warnings.push({code:"duplicate-prefetch",type:"duplicate-prefetch",severity:"warning",message:"Duplicate prefetch - this URL is prefetched multiple times"}),a.add(p),g){if(u.loaded=!0,u.size=g.decodedBodySize||0,u.transferSize=g.transferSize||0,u.duration=g.duration||0,u.cacheStatus=g.encodedBodySize>0&&0===g.transferSize?"cached":0===g.encodedBodySize&&0===g.transferSize?"unknown (CORS)":"network",o+=u.size,d+=u.transferSize,h.some(e=>"link"!==e.initiatorType&&e.startTime<5e3)&&(u.isCurrentPage=!0,u.warnings.push({code:"used-on-current-page",type:"wrong-hint",severity:"error",message:"Resource used on current page - should use preload instead"})),u.size>512e3){const e=(u.size/1048576).toFixed(2);u.warnings.push({code:"large-file",type:"large-file",severity:"warning",message:`Large file (${e}MB) - consider if prefetch is appropriate`})}let e=!1,s="";"video"===c||"audio"===c?(e=!0,s="Video/audio files are typically too large for prefetch"):"image"===c&&u.size>204800?(e=!0,s=`Image is ${(u.size/1024).toFixed(0)}KB (>200KB threshold)`):"script"===c&&u.size>1048576&&(e=!0,s=`Script is ${(u.size/1024).toFixed(0)}KB (>1MB threshold)`),e&&u.warnings.push({code:"inappropriate-type",type:"inappropriate-type",severity:"warning",message:`Type "${c}" may not be suitable for prefetch: ${s}`})}else u.warnings.push({type:"not-loaded",severity:"info",message:"Not loaded yet or failed to load"});u.warnings.length>0?r.push(u):n.push(u)});const c=[];e.length>10&&c.push({code:"too-many-prefetches",type:"excessive-count",severity:"warning",message:`${e.length} prefetch hints found (recommended: <10)`,explanation:"Excessive prefetch can waste bandwidth, especially on mobile networks"});const l=(o/1048576).toFixed(2);(d/1048576).toFixed(2),o>5242880?c.push({code:"large-total-size",type:"excessive-size",severity:"error",message:`Total prefetch size: ${l}MB (critical threshold exceeded)`,explanation:"This is very high and will significantly impact mobile users"}):o>2097152&&c.push({code:"large-total-size",type:"high-size",severity:"warning",message:`Total prefetch size: ${l}MB (warning threshold exceeded)`,explanation:"Consider reducing prefetch to improve mobile experience"});const p=[...r,...n].filter(e=>e.loaded).length,h=r.filter(e=>e.warnings.some(e=>"error"===e.severity||"warning"===e.severity)).length+c.length;c.length>0&&c.forEach(e=>{});const g=r.filter(e=>e.warnings.some(e=>"error"===e.severity)),u=r.filter(e=>!e.warnings.some(e=>"error"===e.severity)&&e.warnings.some(e=>"warning"===e.severity)),f=r.filter(e=>e.warnings.every(e=>"info"===e.severity));return g.length>0&&(g.map(e=>({Resource:e.shortUrl,Type:e.as,Size:e.size>0?`${(e.size/1024).toFixed(1)} KB`:"Unknown",Duration:e.duration>0?`${e.duration.toFixed(0)} ms`:"N/A",Issue:e.warnings.map(e=>e.message).join("; ")})),g.forEach((e,s)=>{e.warnings.forEach(e=>{})})),u.length>0&&u.map(e=>({Resource:e.shortUrl,Type:e.as,Size:e.size>0?`${(e.size/1024).toFixed(1)} KB`:"Unknown",Duration:e.duration>0?`${e.duration.toFixed(0)} ms`:"N/A",Issue:e.warnings.map(e=>e.message).join("; ")})),f.length>0&&f.map(e=>({Resource:e.shortUrl,Type:e.as,Status:e.warnings.map(e=>e.message).join("; ")})),n.length>0&&n.map(e=>({Resource:e.shortUrl,Type:e.as,Size:e.size>0?`${(e.size/1024).toFixed(1)} KB`:"Unknown",Duration:e.duration>0?`${e.duration.toFixed(0)} ms`:"N/A",Status:e.loaded?"✅ Loaded":"Pending",Cache:e.cacheStatus||"N/A"})),{script:"Prefetch-Resource-Validation",status:"ok",count:e.length,details:{loadedCount:p,validCount:n.length,issueCount:h,totalSizeBytes:o,totalTransferBytes:d},items:[...n,...r].map(e=>({href:e.shortUrl,as:e.as,sizeBytes:e.size,loaded:e.loaded,isCurrentPage:e.isCurrentPage||!1})),issues:[...c.map(e=>({code:e.code,severity:"error"===e.severity?"error":"warning",message:e.message})),...r.flatMap(e=>e.warnings.filter(e=>"info"!==e.severity).map(s=>({code:s.code,severity:s.severity,message:`${e.shortUrl}: ${s.message}`,target:e.href})))]}})();