"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const S=require("node:fs"),u=require("node:path"),R=require("../index-BywbRDsb.cjs"),G=require("node:fs/promises"),J=require("node:crypto");var N=typeof document<"u"?document.currentScript:null;const Q="https://fonts.googleapis.com/css2",M="normal",X=400,B="Mozilla/5.0 (compatible; BeatUI Tailwind Plugin; +https://tempots.com)";async function K(e){const{projectRoot:n,requests:t,logger:r}=e;if(!t||t.length===0)return null;const o=e.cacheDir?u.resolve(e.cacheDir):u.join(n,"node_modules",".beatui","google-fonts"),s=[],d=new Map;await G.mkdir(o,{recursive:!0}).catch(g=>{r?.(`Unable to create BeatUI Google Fonts cache directory: ${g}`)});for(const g of t)try{const i=W(g),l=await Y({request:g,cssUrl:i,cacheRoot:o,logger:r});if(!l)continue;const b=await se({cssText:l,cacheRoot:o,assetMap:d,logger:r});s.push(b)}catch(i){r?.(`Unexpected error while downloading Google Font "${g.family}": ${String(i)}`)}return s.length===0||d.size===0?null:{cssText:s.join(`
`),assets:Array.from(d.values())}}async function Y({request:e,cssUrl:n,cacheRoot:t,logger:r}){const o=u.join(t,Z(e,n));try{const s=await fetch(n,{headers:{"User-Agent":B}});if(!s.ok)throw new Error(`Failed to download Google Font CSS: ${s.status} ${s.statusText}`);const d=await s.text();return await G.writeFile(o,d),d}catch(s){if(S.existsSync(o))try{const d=await G.readFile(o,"utf8");return r?.(`Using cached Google Font CSS for ${e.family} because download failed.`),d}catch(d){r?.(`Failed to read cached Google Font CSS for ${e.family}: ${d}`)}return r?.(`Unable to download Google Font CSS for ${e.family}: ${s}`),null}}function Z(e,n){const t=J.createHash("sha1").update(n).digest("hex").slice(0,10);return`${e.family.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-")||"font"}-${t}.css`}function W(e){const{family:n}=e,t=n.trim().replace(/\s+/g," "),r=q(e.weights),o=ee(e.styles),s=new URLSearchParams;return s.append("family",te(t,r,o)),e.display&&s.append("display",e.display),e.subsets&&e.subsets.length>0&&s.append("subset",e.subsets.join(",")),e.text&&s.append("text",e.text),`${Q}?${s.toString()}`}function q(e){return!e||e.length===0?[]:Array.from(new Set(e)).sort((n,t)=>n-t)}function ee(e){if(!e||e.length===0)return[M];const n=Array.from(new Set(e)),t=n.includes("italic"),r=n.includes("normal");return!t&&!r&&n.push(M),n.sort((o,s)=>o===s?0:o==="normal"?-1:1)}function te(e,n,t){if(n.length===0&&t.every(i=>i==="normal"))return e;const r=t.includes("italic"),o=t.includes("normal"),s=n.length>0?n:[X];if(!r)return`${e}:wght@${s.join(";")}`;const d=new Set;o&&s.forEach(i=>{d.add(`0,${i}`)}),s.forEach(i=>{d.add(`1,${i}`)});const g=Array.from(d).sort((i,l)=>{const[b,$]=i.split(",").map(Number),[T,v]=l.split(",").map(Number);return b-T||$-v});return`${e}:ital,wght@${g.join(";")}`}const ne=/url\(([^)]+)\)/g;async function se({cssText:e,cacheRoot:n,assetMap:t,logger:r}){let o=e;const s=new Set;let d;for(;(d=ne.exec(e))!==null;){const i=d[1].trim().replace(/^['"]|['"]$/g,"");i.startsWith("http")&&s.add(i)}for(const g of s){const i=await re(g,n,t,r);if(!i)continue;const l=g.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),b=new RegExp(`url\\((['"])${l}\\1\\)`,"g"),$=new RegExp(`url\\(${l}\\)`,"g");o=o.replace(b,`url(${i.placeholder})`),o=o.replace($,`url(${i.placeholder})`)}return o}async function re(e,n,t,r){const o=t.get(e);if(o)return o;let s;try{const l=new URL(e);s=u.basename(l.pathname)}catch(l){return r?.(`Invalid Google Font URL skipped: ${e} (${l})`),null}if(!s)return r?.(`Unable to derive file name for Google Font URL: ${e}`),null;const d=u.join(n,s),g=`__BEATUI_GOOGLE_FONT_${t.size}__`;if(!S.existsSync(d))try{const l=await fetch(e,{headers:{"User-Agent":B}});if(!l.ok)return r?.(`Failed to download Google Font asset ${s}: ${l.status} ${l.statusText}`),null;const b=Buffer.from(await l.arrayBuffer());await G.writeFile(d,b)}catch(l){return r?.(`Unexpected error while downloading Google Font asset ${s}: ${String(l)}`),null}const i={url:e,fileName:s,localPath:d,placeholder:g};return t.set(e,i),i}function z(e){const n=typeof e=="string"?new URL(e):e;if(n.protocol!=="file:")throw new TypeError(`Expected file URL, received: ${n.href}`);const t=n.hostname,r=t===""||t==="localhost",o=decodeURIComponent(n.pathname);if(process.platform==="win32"){let s=o.replace(/\//g,"\\");return!r&&t?`\\\\${t}${s}`:(s.startsWith("\\")&&(s=s.slice(1)),s)}return!r&&t?`//${t}${o}`:o}const D="@tempots/beatui/tailwind.css",y="beatui.tailwind.css",w=u.dirname(z(typeof document>"u"?require("url").pathToFileURL(__filename).href:N&&N.tagName.toUpperCase()==="SCRIPT"&&N.src||new URL("tailwind/vite-plugin.cjs.js",document.baseURI).href)),j=oe(w)??w;function x(e){if(Object.keys(e).length===0)return"";let n=`:root {
`;for(const[t,r]of Object.entries(e))n+=`  ${t}: ${r};
`;return n+=`}
`,n}function oe(e){let n=e;const t=u.parse(n).root;for(;n&&n!==t;){const r=u.join(n,"package.json");if(S.existsSync(r))try{if(JSON.parse(S.readFileSync(r,"utf8"))?.name==="@tempots/beatui")return n}catch{}n=u.dirname(n)}return null}function ae(e){if(e==null)return null;const n=typeof e=="string"?e:e.id;if(!n)return null;const[t]=n.split("?");return t.startsWith("virtual:")||t.startsWith("\0")?null:t.startsWith("/@fs/")?decodeURIComponent(t.slice(4)):t.startsWith("file://")?z(t):u.isAbsolute(t)?t:null}function ie(e){const n=new Set([u.resolve(w,y),u.resolve(w,"../",y),u.resolve(w,"../../",y),u.resolve(w,"tailwind.css"),u.resolve(w,"../tailwind.css"),u.resolve(w,"../../tailwind.css"),u.resolve(w,"../styles/tailwind.css"),u.resolve(w,"../../styles/tailwind.css"),u.resolve(j,"dist",y),u.resolve(j,y),u.resolve(j,"tailwind.css"),u.resolve(j,"src/styles/tailwind.css"),u.resolve(e,"node_modules/@tempots/beatui/tailwind.css")]);for(const t of n)if(S.existsSync(t))return t;return null}function le(e){return e?Array.isArray(e)?e:[e]:[]}function ce(e,n){let t=e;for(const[r,o]of n)t=t.split(r).join(o);return t}async function ue(e,n){if(e==null||typeof e!="object")return null;const t=e.resolve;if(!t)return null;try{return await t.call(e,n,void 0,{skipSelf:!0})}catch{return null}}function V(e={}){let n=process.cwd();const t=e.injectCss!==!1,r=e.rtlAttribute??"dir",o=e.rtlValue??"rtl";let s="/";const g=e.semanticColors!=null||e.semanticFonts!=null||e.semanticRadii!=null||e.semanticShadows!=null||e.semanticMotion!=null||e.semanticSpacing!=null||e.semanticTextShadows!=null?x(R.generateSemanticTokenVariables({colors:e.semanticColors,fonts:e.semanticFonts,radii:e.semanticRadii,shadows:e.semanticShadows,motion:e.semanticMotion,spacing:e.semanticSpacing,textShadows:e.semanticTextShadows})):"",i=e.fontFamilies?x(R.generateFontFamilyOverrideVariables(e.fontFamilies)):"",l={};e.baseSpacing&&(l[R.getSpacingVarName("base")]=e.baseSpacing),e.baseFontSize&&(l[R.getBaseFontSizeVarName()]=e.baseFontSize),e.baseMotionDuration&&(l[R.getMotionDurationVarName("base")]=e.baseMotionDuration);const b=x(l),$=le(e.googleFonts);let T="",v=[];const I=new Map,P=new Map,_=new Map,H="/@beatui/google-fonts",U=[];let O=null,C=null,A=!1;const L=h=>{const f=[b,g,i];return T&&(h==="dev"?f.push(ce(T,I)):f.push(T)),f.filter(a=>a&&a.length>0).join(`
`)};return{name:"beatui-tailwind",enforce:"pre",async configResolved(h){if(n=h.root,A=h.command==="build",s=h.base&&h.base!=="/"?h.base.endsWith("/")?h.base:`${h.base}/`:"/",t){const a=await ue(this,D);C=ae(a)??ie(n)}const f=a=>{this&&typeof this.warn=="function"?this.warn(a):h.logger.warn(a)};if($.length>0){const a=Array.from(new Set($.map(W))),c=await K({projectRoot:n,requests:$,logger:m=>f(`[BeatUI] ${m}`)});if(T=c?.cssText??"",v=c?.assets??[],I.clear(),P.clear(),_.clear(),U.length=0,v.length>0)for(const m of v){const p=`${H}/${m.fileName}`;I.set(m.placeholder,p),_.set(p,m.localPath)}else U.push(...a)}else U.length=0;t&&!C&&f("[BeatUI] Unable to resolve @tempots/beatui/tailwind.css. CSS will not be auto-injected.")},configureServer(h){!t||C==null||(h.middlewares.use((f,a,c)=>{const m=f.method??"GET";if(!["GET","HEAD"].includes(m)){c();return}const p=(f.url??"").split("?")[0];if(!new Set([`/${y}`,s==="/"?null:`${s}${y}`].filter(F=>!!F)).has(p)){c();return}a.setHeader("Content-Type","text/css");try{let F=S.readFileSync(C,"utf8");const k=L("dev");k&&(F+=`
${k}`),a.end(F)}catch(F){h.config.logger.error(`[BeatUI] Failed to stream ${D}: ${String(F)}`),a.statusCode=500,a.end()}}),_.size>0&&h.middlewares.use((f,a,c)=>{const m=f.method??"GET";if(!["GET","HEAD"].includes(m)){c();return}const p=(f.url??"").split("?")[0],E=p?_.get(p):void 0;if(!E){c();return}a.setHeader("Content-Type","font/woff2"),S.createReadStream(E).on("error",()=>{a.statusCode=500,a.end()}).pipe(a)}))},buildStart(){if(!A||!t||C==null)return;P.clear(),O=null;const h=C;let f=S.readFileSync(h,"utf8");const a=L("raw");if(a&&(f+=`
${a}`),O=this.emitFile({type:"asset",fileName:y,source:f}),v.length>0)for(const c of v)try{const m=S.readFileSync(c.localPath),p=this.emitFile({type:"asset",name:`assets/${c.fileName}`,source:m});P.set(c.placeholder,p)}catch(m){this.warn(`[BeatUI] Failed to include Google Font asset ${c.fileName}: ${String(m)}`)}},generateBundle(h,f){if(!A||!O)return;const a=this.getFileName(O),c=f[a];if(!c||c.type!=="asset"||typeof c.source!="string")return;let m=c.source;for(const[p,E]of P){const F=this.getFileName(E);m=m.split(p).join(F)}c.source=m},transformIndexHtml(h){const f=[];if(t&&C){const c=s==="/"?`/${y}`:`${s}${y}`;f.push({tag:"link",attrs:{rel:"stylesheet",href:c},injectTo:"head-prepend"})}U.length>0&&f.push({tag:"link",attrs:{rel:"preconnect",href:"https://fonts.googleapis.com"},injectTo:"head"},{tag:"link",attrs:{rel:"preconnect",href:"https://fonts.gstatic.com",crossorigin:""},injectTo:"head"},...U.map(c=>({tag:"link",attrs:{rel:"stylesheet",href:c,"data-beatui-google-font":""},injectTo:"head"})));const a=`
        (() => {
          const apply = () => {
            const root = document.documentElement
            const target = document.body
            if (!target) return
            const dirValue = root.getAttribute('${r.replace(/'/g,"\\'")}')
            const isRtl = dirValue === '${o.replace(/'/g,"\\'")}'
            target.classList.toggle('b-rtl', isRtl)
            target.classList.toggle('b-ltr', !isRtl)
          }
          if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', apply, { once: true })
          } else {
            apply()
          }
          const observer = new MutationObserver(apply)
          observer.observe(document.documentElement, {
            attributes: true,
            attributeFilter: ['${r.replace(/'/g,"\\'")}'],
          })
        })();
      `;return f.push({tag:"script",attrs:{type:"module"},children:a,injectTo:"body"}),{html:h,tags:f}}}}exports.beatuiTailwindPlugin=V;exports.default=V;
