"use strict";const u=require("chalk"),d=require("fs"),y=require("path"),v=require("sharp"),B={includePublic:!0,png:{quality:80},jpeg:{quality:80},jpg:{quality:80},tiff:{quality:80},gif:{},webp:{lossless:!0,quality:80},avif:{lossless:!0,quality:80}};function w(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function I(n){return Object.prototype.toString.call(n)==="[object String]"}function D(n){return Array.isArray(n)}function O(n,e){const a=r=>{if(typeof r!="object"||w(r)||r===null)return r;const f=Array.isArray(r)?[]:{};for(const m in r){const F=r[m];f[m]=a(F)}return f},g=a(n);for(const r in e)g[r]===void 0&&(g[r]=e[r]);return g}function k(n,e){return I(e)?n===e:w(e)?e.test(n):D(e)?e.includes(n):!1}function A(n){let e=[];try{d.existsSync(n)&&(d.lstatSync(n).isDirectory()?d.readdirSync(n).forEach(function(r){const f=A(y.join(n,"/",r));e=e.concat(f)}):e.push(n))}catch(a){console.log(a)}return e}function L(n={}){const e=O(n,B);let a,g,r;const f=new Map,m=new Map,F=async(c,i)=>{try{const t=y.basename(c).split(".").pop(),o=await v(i,{animated:t==="gif"}).toFormat(t,e[t]).toBuffer(),s=i.byteLength,l=o.byteLength,p=s{let i=c.filter(t=>/\.(jpe?g|png|gif|tiff|webp|avif)$/i.test(t));return e.include&&(i=i.filter(t=>{const o=y.basename(t);return k(o,e.include)})),e.test&&(i=i.filter(t=>{const o=y.basename(t);return k(o,e.test)})),e.exclude&&(i=i.filter(t=>{const o=y.basename(t);return!k(o,e.exclude)})),i};return{name:"vite-plugin-compress-images",apply:"build",enforce:"post",configResolved(c){g=c,r=g.logger.info,typeof c.publicDir=="string"&&(a=c.publicDir.replace(/\\/g,"/"))},async generateBundle(c,i){const t=Object.keys(i),o=z(t);if(o.length!==0)for(const s of o){const l=i[s].source,{content:p}=await F(s,l);p&&(i[s].source=p)}},async closeBundle(){if(a&&e.includePublic){const c=A(a),i=z(c);if(i.length===0)return;for(const t of i){const o=d.readFileSync(t),{content:s,isSkip:l}=await F(t,o);s&&!l&&d.writeFileSync(t,s)}}if(f.size>0){r(` ✨ ${u.blue("[vite-plugin-image-compress]")} - optimized images successfully: `);const c=Array.from(f.keys(),l=>l.replace(`${a}/`,"").length),i=Math.max(...c),t=Math.max(...Array.from(f.values(),l=>(l.ratio>0?`+${l.ratio}%`:`${l.ratio}%`).length));let o=0,s=0;f.forEach((l,p)=>{const{isSkip:S,ratio:$,size:x,oldSize:b}=l;let j=p.replace(`${a}/`,"");const h=$>=0?`+${$}%`:`${$}%`,M=`${$>=0?u.red(h):u.green(h)}`+" ".repeat(t-String(h).length),q=S?`original: ${b.toFixed(2)} KB <= optimized: ${x.toFixed(2)} kB`:`${b.toFixed(2)} KB -> ${x.toFixed(2)} kB`;r(`${u.gray(y.basename(g.build.outDir))}/${u.blue(j)}${" ".repeat(2+i-j.length)}${M} ${S?u.yellow("skipped")+" "+u.gray(q):u.gray(q)} `),S||(o+=b,s+=b-x)}),s>0&&r(` 💰 total savings = ${u.green(s.toFixed(2))} / ${u.green(o.toFixed(2))} ≈ ${u.green(`${(s/o*100).toFixed(2)}%`)}`)}}}}module.exports=L;