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