UNPKG

@thi.ng/meta-css

Version:

Data-driven CSS framework codegen, transpiler & bundler

48 lines (42 loc) 40.1 kB
// @bun var Go={default:95,command:92,error:91,hint:90,multi:90,param:96,required:33};var ut=(t)=>t;function W(t,o=Object.create(null)){return(...n)=>{let r=n.join("-");return r in o?o[r]:o[r]=t(...n)}}var nt=W((t,o)=>t.repeat(o));var Po=(t)=>/^[a-f0-9]+$/i.test(t);var jo=(t)=>/^[-+]?\d+$/.test(t),Xo=(t)=>/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(t);var D=(t,o=(n)=>n!==void 0?": "+n:"")=>class extends Error{origMessage;constructor(n){super(t(n)+o(n));this.origMessage=n!==void 0?String(n):""}};var Rr=D(()=>"illegal argument(s)"),C=(t)=>{throw new Rr(t)};var Oo=(t)=>Xo(t)?parseFloat(t):C(`not a numeric value: ${t}`),Zo=(t)=>t.map(Oo),No=(t)=>Po(t)?parseInt(t,16):C(`not a hex value: ${t}`),Ko=(t)=>t.map(No),_o=(t)=>jo(t)?parseInt(t):C(`not an integer: ${t}`),bo=(t)=>t.map(_o);var Wt=(t,o)=>(n)=>({coerce:t,hint:o,group:"main",...n}),Dt=(t,o)=>(n)=>({hint:yr(o,n.delim),multi:!0,coerce:t,group:"main",...n}),yr=(t,o)=>t+(o?`[${o}..]`:""),M=(t)=>({flag:!0,default:!1,group:"flags",...t}),Y=Wt(ut,"STR"),Yt=Dt(ut,"STR"),ef=Wt(Oo,"NUM"),Bf=Wt(No,"HEX"),Jt=Wt(_o,"INT"),$f=Dt(Zo,"NUM"),uf=Dt(Ko,"HEX"),Tf=Dt(bo,"INT");var Ff={dryRun:M({desc:"Dry run (no changes applied)"})},wf={quiet:M({alias:"q",desc:"Disable all logging"})},po={verbose:M({alias:"v",desc:"Display extra information"})};var B=Array.isArray;var $=((t)=>{return t[t.FINE=0]="FINE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.SEVERE=4]="SEVERE",t[t.NONE=5]="NONE",t})($||{});var Mr=0;class Tt{constructor(t,o=$.FINE,n){this.parent=n,this.id=t||`logger-${Mr++}`,this.level=typeof o==="string"?$[o]:o}id;level;addChild(t){return t.parent=this,t}enabled(t){return this.level<=t}fine(...t){this.log($.FINE,t)}debug(...t){this.log($.DEBUG,t)}info(...t){this.log($.INFO,t)}warn(...t){this.log($.WARN,t)}severe(...t){this.log($.SEVERE,t)}none(){}log(t,o){this.level<=t&&this.logEntry([t,this.id,Date.now(),...o])}}var Vo=(t)=>t.map((o)=>{if(typeof o==="function")o=o();if(!(typeof o==="string"||typeof o==="number"))o=JSON.stringify(o);return o}).join(" ");class zt extends Tt{constructor(t,o,n,r){super(o,n,r);this.target=t}childLogger(t,o){return new zt(this.target,t,o??this.level,this)}logEntry(t){if(t[0]<this.level)return;this.target.write(`[${$[t[0]]}] ${t[1]}: ${Vo(t.slice(3))} `),this.parent?.logEntry(t)}}var ho={black:1,blue:5,cyan:7,gray:17,green:3,magenta:6,red:2,white:24,yellow:4,lightBlue:21,lightCyan:23,lightGray:8,lightGreen:19,lightMagenta:22,lightRed:18,lightYellow:20,bgBlack:32,bgBlue:160,bgCyan:224,bgGray:544,bgGreen:96,bgMagenta:192,bgRed:64,bgWhite:768,bgYellow:128,bgLightBlue:672,bgLightCyan:736,bgLightGray:256,bgLightGreen:608,bgLightMagenta:704,bgLightRed:576,bgLightYellow:640};var Ir=(t,o)=>(n)=>t.format(o,n),io=(t)=>Object.keys(ho).reduce((o,n)=>(o[n]=Ir(t,ho[n]),o),{format:t});var qo="\x1B[0m";var Ur=["","1","2","1;2","4","1;4","2;4","1;2;4"],Pt={format:(t,o)=>Pt.start(t)+o+Pt.end,start:W((t)=>{let o=[],n=t&15;return n&&o.push(29+(t>>4&1)*60+n),n=t>>5&15,n&&o.push(39+(t>>9&1)*60+n),n=t>>10,n&&o.push(Ur[n]),"\x1B["+o.join(";")+"m"}),end:qo,prefix:qo,suffix:` `};var Qo={format:(t,o)=>String(o),prefix:"",suffix:` `,start:()=>"",end:""};var jt=io(Pt),ko=io(Qo);var Wr=(t)=>t.toUpperCase(),vo=(t)=>t.toLowerCase(),Xt=(t)=>t.length?t[0].toUpperCase()+t.substring(1):t,rt=(t,o="-")=>vo(t.replace(/([a-z0-9\u00e0-\u00fd])([A-Z\u00c0-\u00dd])/g,(n,r,m)=>r+o+m));var lo=(t,o="-")=>vo(t).replace(new RegExp(`\\${o}+(\\w)`,"g"),(n,r)=>Wr(r));var go=(t=!1,o)=>(n)=>t||typeof n!=="string"&&typeof n!=="number"?JSON.stringify(n,null,o):String(n);var xo=Object.getPrototypeOf,J=(t)=>{let o;return t!=null&&typeof t==="object"&&((o=xo(t))===null||xo(o)===null)};var Dr=/\x1b\[[0-9;]+m/g,Yr=(t)=>t.replace(Dr,"");var Zt=(t)=>Yr(t).length;var ao=W((t,o=" ")=>{let n=nt(String(o),t);return(r,m)=>{if(r==null)return n;return r=r.toString(),m=m!==void 0?m:r.length,m<t?r+n.substring(m):r}});function*mt(t,o=/\r?\n/g,n=!1){let r=0,m=t.length,f=~~n,E;if(typeof o==="string")E=new RegExp(o,"g");else if(!o.flags.includes("g"))E=new RegExp(o,o.flags+"g");else E=o;for(;r<m;){let G=E.exec(t);if(!G){yield t.substring(r);return}let O=G[0].length;yield t.substring(r,G.index+f*O),r=G.index+O}}class Co{n=0;w=[];constructor(t,o){t!=null&&this.add(t,o)}add(t,o=t.length){return this.w.push(t),this.n+=o+~~(this.n>0),this}toString(){return this.w.join(" ")}}var Jr={length:(t)=>t.length,split:(t,o)=>o},co={length:Zt,split:(t,o)=>{let n=/\x1b\[[0-9;]+m/g,r=o,m;while(m=n.exec(t)){if(m.index>=o)break;let f=m[0].length;r+=f,o+=f}return r}},so=(t,o,n,r)=>{let m=t[t.length-1];m&&r-m.n>n?m.add(o,n):t.push(new Co(o,n))},zr=(t,{width:o,min:n,hard:r,splitter:m},f=0,E=[])=>{let G=m.length(t),O=o-f;if(O<n&&O<G)O=o;while(r&&G>O){let N=m.split(t,O),_=t.substring(0,N);so(E,_,O,o),t=t.substring(N),O=o,G=m.length(t)}return so(E,t,G,o),E},Pr=(t,o,n=[])=>{if(!t.length)return n.push(new Co),n;let r={width:80,min:4,hard:!1,splitter:Jr,...o};for(let m of mt(t,o.delimWord||/\s/g)){let f=n[n.length-1];zr(m,r,f&&f.n>0?f.n+1:0,n)}return n},tn=(t,o)=>{let n=[];for(let r of mt(t,o.delimLine))n=n.concat(Pr(r,o));return n};var U=(t,o)=>o!=null?`\x1B[${o}m${t}\x1B[0m`:t,Kt=(t,o)=>ao(o)(t,Zt(t)),bt=(t,o)=>t?tn(t,{width:o,splitter:co,hard:!1}):[],pt=(t,o,n)=>{let r=nt(" ",o);return bt(t,n-o).map((m,f)=>f?r+m:m).join(` `)},l=(t)=>J(t)?{...Go,...t}:t!==!1?Go:{};var Ft=(t,o={})=>{o={lineWidth:80,paramWidth:32,showDefaults:!0,prefix:"",suffix:"",groups:["flags","main"],...o};let n=l(o.color),r=(E)=>E.map((G)=>jr(G,t[G],o,n,o.paramWidth)),m=Object.keys(t).sort(),f=o.groups?o.groups.map((E)=>[E,m.filter((G)=>t[G].group===E)]).filter((E)=>!!E[1].length):[["options",m]];return[...bt(o.prefix,o.lineWidth),...f.map(([E,G])=>[...o.showGroupNames?[`${Xt(E)}: `]:[],...r(G),""].join(` `)),...bt(o.suffix,o.lineWidth)].join(` `)},jr=(t,o,n,r,m)=>{let f=Xr(o,r),E=Zr(o,r,f),G=U(`--${rt(t)}`,r.param),O=`${E}${G}${f}`,N=o.optional===!1&&o.default===void 0,_=[];N&&_.push("required"),o.multi&&_.push("multiple");let h=Kr(_,r,N)+(o.desc||"")+br(o,n,r);return Kt(O,n.paramWidth)+pt(h,m,n.lineWidth)},Xr=(t,o)=>t.hint?U(" "+t.hint,o.hint):"",Zr=(t,o,n)=>t.alias?`${U("-"+t.alias,o.param)}${n}, `:"",Kr=(t,o,n)=>t.length?U(`[${t.join(", ")}] `,n?o.required:o.multi):"",br=(t,o,n)=>o.showDefaults&&t.default!=null&&t.default!==!1?U(` (default: ${go(!0)(t.defaultHint!=null?t.defaultHint:t.default)})`,n.default):"";var pr=D(()=>"parse error"),on=(t,o,n)=>{n={start:2,showUsage:!0,help:["--help","-h"],...n};try{return Vr(t,o,n)}catch(r){if(n.showUsage)console.log(U(r.message,l(n.usageOpts?.color).error)+` `+Ft(t,n.usageOpts));throw new pr(r.message)}},Vr=(t,o,n)=>{let r=qr(t),m={},f,E,G=n.start;for(;G<o.length;){let O=o[G];if(!f){if(n.help.includes(O)){console.log(Ft(t,n.usageOpts));return}let N=Qr(t,r,m,O);if(f=N.id,E=N.spec,G=G+~~(N.state<2),N.state)break}else{if(kr(E,m,f,O))break;f=null,G++}}return f&&C(`missing value for: --${rt(f)}`),{result:vr(t,m),index:G,rest:o.slice(G),done:G>=o.length}},qr=(t)=>Object.entries(t).reduce((o,[n,r])=>r.alias?(o[r.alias]=n,o):o,{}),Qr=(t,o,n,r)=>{if(r[0]==="-"){let m;if(r[1]==="-"){if(r==="--")return{state:1};m=lo(r.substring(2))}else m=o[r.substring(1)],!m&&C(`unknown option: ${r}`);let f=t[m];if(!f&&C(m),f.flag){if(n[m]=!0,m=void 0,f.fn&&!f.fn("true"))return{state:1,spec:f}}return{state:0,id:m,spec:f}}return{state:2}},kr=(t,o,n,r)=>{if(t.multi)B(o[n])?o[n].push(r):o[n]=[r];else o[n]=r;return t.fn&&!t.fn(r)},vr=(t,o)=>{let n;for(let r in t)if(n=t[r],o[r]===void 0){if(n.default!==void 0)o[r]=n.default;else if(n.optional===!1)C(`missing arg: --${rt(r)}`)}else if(n.coerce)dr(n,o,r);return o},dr=(t,o,n)=>{try{if(t.multi&&t.delim)o[n]=o[n].reduce((r,m)=>(r.push(...m.split(t.delim)),r),[]);o[n]=t.coerce(o[n])}catch(r){throw new Error(`arg --${rt(n)}: ${r.message}`)}};var mn=async(t)=>{let o=t.argv||process.argv,n=!process.env.NO_COLOR,r=l(n),m={prefix:"",color:n,...t.usage};try{let f,E,G=t.start??2;if(t.single){if(f=Object.keys(t.commands)[0],!f)C("no command provided");E=t.commands[f]}else{if(f=o[G],E=t.commands[f],!E)m.prefix+=lr(t.commands,m),nn(t,m);G++}let O;try{O=on({...t.opts,...E.opts},o,{usageOpts:m,start:G})}catch(_){process.exit(1)}if(!O)process.exit(0);if(E.inputs!==void 0){let _=O.rest.length,h;if(B(E.inputs)){let[i,A]=E.inputs;if(_<i||_>A)h=A<1/0?`expected ${i}-${A} inputs`:`expected at least ${i} inputs`}else if(_!==E.inputs)h=`expected ${E.inputs} input(s)`;if(h)rn(h,r),nn(t,m)}let N=await t.ctx({logger:new zt(process.stderr,t.name,"INFO"),format:n?jt:ko,opts:O.result,inputs:O.rest},E);if(await E.fn(N),t.post)await t.post(N,E)}catch(f){rn(f.message,r),process.exit(1)}},nn=(t,o)=>{process.stderr.write(Ft(t.opts,o)),process.exit(1)},lr=(t,{color:o,lineWidth:n=80}={})=>{let r=Object.keys(t),m=Math.max(...r.map((E)=>E.length)),f=l(o);return[` Available commands: `,...r.map((E)=>`${Kt(U(E,f.command),m)} : ${pt(t[E].desc,m+3,n)}`),` `].join(` `)},rn=(t,o)=>process.stderr.write(U(t,o.error)+` `);var fn=(t,o,n=!1)=>{if(n)t.level=$.NONE;else if(o)t.level=$.DEBUG};var En=(t,o,n)=>` \u2588 \u2588 \u2588 \u2502 \u2588\u2588 \u2588 \u2502 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2502 ${t} v${o} \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2588 \u2502 ${n} \u2588 \u2502 \u2588 \u2588 \u2502`;var u=(t)=>typeof t==="string";var gr=[[process.env.HOME?new RegExp(process.env.HOME,"g"):/~/,"~"]];var Vt=(t)=>{for(let[o,n]of gr)t=t.replace(o,n);return t};import{existsSync as xr,mkdirSync as ar,statSync as DE}from"fs";import{dirname as sr}from"path";var cr=(t)=>t.length>0&&!xr(t)?(ar(t,{recursive:!0}),!0):!1,Gn=(t)=>cr(sr(t));var X=(t)=>typeof t==="function";import{readFileSync as nm}from"fs";import{writeFileSync as tm}from"fs";var On=(t,o,n,r,m=!1)=>om(tm,t,o,n,r,m);var om=(t,o,n,r,m,f=!1)=>{if(m?.info(`${f?"[dryrun] ":""}writing file: ${Vt(o)}`),f)return;return Gn(o),t(o,n,!r&&u(n)?"utf-8":r)};var w=(t,o,n="utf-8")=>{return o?.debug("reading file:",Vt(t)),nm(t,n)};var Ao=(t,o,n,r=!1)=>On(t,B(o)?o.join(` `):o,"utf-8",n,r);var Z=(t,o)=>JSON.parse(w(t,o));var b=Symbol(),Lo=()=>{};var wt=Object.freeze({level:$.NONE,addChild(t){return t},childLogger:()=>wt,enabled:()=>!1,fine(){},debug(){},info(){},warn(){},severe(){},none(){},logEntry(){}});import{join as dm}from"path";var eo=(t,o)=>{if(t===o)return 0;if(t==null)return o==null?0:-1;if(o==null)return t==null?0:1;if(typeof t.compare==="function")return t.compare(o);if(typeof o.compare==="function")return-o.compare(t);return t<o?-1:t>o?1:0};var rm=D(()=>"Assertion failed"),qt=(typeof process!=="undefined"&&process.env!==void 0?!0:import.meta.env?import.meta.env.MODE!=="production"||!!import.meta.env.UMBRELLA_ASSERTS||!!import.meta.env.VITE_UMBRELLA_ASSERTS:!0)?(t,o)=>{if(typeof t==="function"&&!t()||!t)throw new rm(typeof o==="function"?o():o)}:()=>{};var Qt=(t)=>t!=null&&typeof t!=="function"&&t.length!==void 0;var Nn=(t)=>{return(t==null||!t[Symbol.iterator])&&C(`value is not iterable: ${t}`),t};var _n=(t)=>Qt(t)?t:[...Nn(t)];var St=(t)=>t[t.length-1];var kt=(t,o)=>typeof t?.[o]==="function";var T=(t)=>typeof t?.[Symbol.iterator]==="function";var vt=(t)=>t!=null&&typeof t!=="string"&&typeof t[Symbol.iterator]==="function";var mm=D(()=>"illegal arity"),ft=(t)=>{throw new mm(t)};var fm=D(()=>"illegal state"),Et=(t)=>{throw new fm(t)};var hn=["-moz-","-ms-","-o-","-webkit-"],Gt={rules:"",ruleSep:",",valSep:"",decls:"",declStart:"{",declEnd:"}",indent:"",comments:!1},dt={rules:` `,ruleSep:", ",valSep:" ",decls:` `,declStart:` { `,declEnd:`} `,indent:" ",comments:!0};function Bo(...t){let[o,n,r,m,f,E,G,O,N,_]=t;switch(t.length){case 0:ft(0);case 1:return o;case 2:return(...i)=>o(n(...i));case 3:return(...i)=>o(n(r(...i)));case 4:return(...i)=>o(n(r(m(...i))));case 5:return(...i)=>o(n(r(m(f(...i)))));case 6:return(...i)=>o(n(r(m(f(E(...i))))));case 7:return(...i)=>o(n(r(m(f(E(G(...i)))))));case 8:return(...i)=>o(n(r(m(f(E(G(O(...i))))))));case 9:return(...i)=>o(n(r(m(f(E(G(O(N(...i)))))))));case 10:default:let h=(...i)=>o(n(r(m(f(E(G(O(N(_(...i))))))))));return t.length===10?h:Bo(h,...t.slice(10))}}var g=(t)=>kt(t,"xform")?t.xform():t;function z(...t){return t=t.map(g),Bo.apply(null,t)}var p=(t,o)=>[t[0],t[1],o];class Ht{value;constructor(t){this.value=t}deref(){return this.value}}var S=(t)=>t instanceof Ht,Cn=(t)=>t instanceof Ht?t:new Ht(t),P=(t)=>t instanceof Ht?t.deref():t;var Em=(t)=>t.length===2?[void 0,t[1]]:t.length===3?[t[1],t[2]]:ft(t.length);function Ot(...t){let o=t[0],n=o[0],r=o[1],m=o[2];t=Em(t);let f=t[0]==null?n():t[0],E=t[1];return P(r(kt(E,"$reduce")?E.$reduce(m,f):Qt(E)?Gm(m,f,E):Om(m,f,E)))}var Gm=(t,o,n)=>{for(let r=0,m=n.length;r<m;r++)if(o=t(o,n[r]),S(o)){o=o.deref();break}return o},Om=(t,o,n)=>{for(let r of n)if(o=t(o,r),S(o)){o=o.deref();break}return o},Nt=(t,o)=>[t,ut,o],An=(t,o)=>{let n=o.length-1;return T(o[n])?o.length>1?Ot(t.apply(null,o.slice(0,n)),o[n]):Ot(t(),o[0]):void 0};function _t(t){return t?[...t]:Nt(()=>[],(o,n)=>(o.push(n),o))}function*ht(t,o){let n=g(t)(_t()),r=n[1],m=n[2];for(let f of o){let E=m([],f);if(S(E)){yield*P(r(E.deref()));return}if(E.length)yield*E}yield*P(r([]))}function*x(t,o){let n=g(t)([Lo,Lo,(r,m)=>m])[2];for(let r of o){let m=n(b,r);if(S(m)){if(m=P(m.deref()),m!==b)yield m;return}if(m!==b)yield m}}var lt=(t,o,n=x)=>{let r=o.length-1;return T(o[r])?o.length>1?n(t.apply(null,o.slice(0,r)),o[r]):n(t(),o[0]):void 0};function $o(t,o){return T(o)?ht($o(t),u(o)?[o]:o):(n)=>{let r=n[2],m=(f,E)=>{let G=t(E);if(G){for(let O of G)if(f=m(f,O),S(f))break;return f}return r(f,E)};return p(n,m)}}function Ln(t){return $o((o)=>vt(o)?o:void 0,t)}function e(t,o){return T(o)?x(e(t),o):(n)=>{let r=n[2];return p(n,(m,f)=>r(m,t(f)))}}function*gt(...t){let o=t.length-1;if(o<0)return;let n=new Array(o+1).fill(0),r=t.map(_n),m=r.reduce((f,E)=>f*E.length,1);for(let f=0;f<m;f++){let E=[];for(let G=o;G>=0;G--){let O=r[G],N=n[G];if(N===O.length)n[G]=N=0,G>0&&n[G-1]++;E[G]=O[N]}n[o]++,yield E}}function*en(t,o=1/0){while(o-- >0)yield t}function uo(t,o){t=t||"";let n=!0;return o?[...o].join(t):Nt(()=>"",(r,m)=>(r=n?r+m:r+t+m,n=!1,r))}function xt(...t){return Nm(xt,Ot,t)}var Nm=(t,o,n)=>{let r,m;switch(n.length){case 4:m=n[3],r=n[2];break;case 3:m=n[2];break;case 2:return e((f)=>t(n[0],n[1],f));default:ft(n.length)}return o(g(n[0])(n[1]),r,m)};var _m=new Set,hm=":[",Bn=z(Ln(),e((t)=>t[0]==="&"?t.substring(1):hm.includes(t[0])?t:" "+t)),im=(t,o)=>z(t,e((n)=>u(n)&&n.startsWith(" .")?n+o:n)),it=(t,o,n,r)=>{let m=n.length,f=[],E,G,O=(N,_)=>{let h=null;if(B(_))it(t,To(o,f),_,r);else if(T(_)&&!u(_))it(t,To(o,f),[..._],r);else if((G=X(_))||(h=r.fns[_]))if(!o.length){if(h)return h.apply(null,n.slice(N+1))(t,r),!0;_(t,r)}else if(G)O(N,_());else C(`quoted fn ('${_}') only allowed at head position`);else if(J(_))E=Object.assign(E||{},_);else if(_!=null)f.push(_)};for(let N=0;N<m;N++)if(O(N,n[N]))return t;return E&&t.push(Cm(o,f,E,r)),t},To=(t,o)=>t.length?[...gt(t,o)]:o,Cm=(t,o,n,r)=>{let m=r.format,f=j(r),E=r.scope?im(Bn,r.scope):Bn;return[f,xt(e((G)=>xt(E,uo(),B(G)?G:[G]).trim()),uo(m.ruleSep),To(t,o)),m.declStart,Rt(n,r),f,m.declEnd].join("")},Rt=(t,o)=>{let n=o.format,r=o.autoprefix||_m,m=j(o,o.depth+1),f=[];for(let E in t)if(t.hasOwnProperty(E)){let G=t[E];if(X(G))G=G(t);if(B(G))G=G.map((O)=>B(O)?O.join(" "):O).join(n.ruleSep);if(r.has(E))for(let O of o.vendors)f.push(`${m}${O}${E}:${n.valSep}${G};`);f.push(`${m}${E}:${n.valSep}${G};`)}return f.join(n.decls)+n.decls},j=(t,o=t.depth)=>o>1?[...en(t.format.indent,o)].join(""):o>0?t.format.indent:"";function $n(t,...o){let n=o.length===1?o[0]:o.reduce((r,m,f)=>{return r[f/(o.length-1)*100|0]=m,r},{});return(r,m)=>{let f=j(m);m.depth++;let E=j(m);r.push(`${f}@keyframes ${t}${m.format.declStart}`);for(let G in n)if(n.hasOwnProperty(G))r.push([E,G+"%",m.format.declStart,Rt(n[G],m),E,m.format.declEnd].join(""));return m.depth--,r.push(f+m.format.declEnd),r}}var un=(t,o=!1)=>(n,r)=>{let m=j(r),f=j(r,r.depth+1);if(r.format.comments||o)n.push(m+"/*",t.split(` `).map((E)=>f+E).join(` `),m+"*/");return n};var at=(t,o,n)=>(r,m)=>{let f=j(m);return r.push(`${f}${t} ${Am(o)}${m.format.declStart}`),m.depth++,it(r,[],n,m),m.depth--,r.push(f+m.format.declEnd),r},Am=(t)=>{if(u(t))return t;let o=[];for(let n in t)if(t.hasOwnProperty(n)){let r=t[n];if(r===!0)r=Tn.has(n)?n:`(${n})`;else if(r===!1)r=`(not ${Tn.has(n)?n:`(${n})`})`;else if(r==="only")r+=" "+n;else r=`(${n}:${r})`;o.push(r)}return o.join(" and ")},Tn=new Set(["all","print","screen"]);var a=(t,o)=>{return o={format:Gt,vendors:hn,fns:{},depth:0,...o},B(o.autoprefix)&&(o.autoprefix=new Set(o.autoprefix)),J(t)?Rt(t,o):X(t)?t([],o).join(o.format.rules):it([],[],B(t)?t:vt(t)?[...t]:C("invalid rules"),o).join(o.format.rules)};var Fn=(t,...o)=>(n,r)=>(n.push(o.length?`@import url(${t}) ${o.join(r.format.ruleSep)};`:`@import url(${t});`),n);var Ct=(t,o)=>at("@media",t,o);function wn(...t){return(o,n)=>(o.push(t.length>1?`@namespace ${t[0]} url(${t[1]});`:`@namespace url(${t[0]});`),o)}var Sn=(t,o)=>at("@supports",t,o);var st={"@comment":un,"@import":Fn,"@keyframes":$n,"@media":Ct,"@namespace":wn,"@supports":Sn};var Hn=4,Rn=(t)=>Hn=t,y=(t)=>t===(t|0)?String(t):t.toFixed(Hn).replace(/^0./,".").replace(/^-0./,"-.").replace(/0+$/,"");var yn=(t)=>`${y(t)}em`,Mn=(t)=>`${y(t)}ex`;var In=(t)=>`${y(t)}rem`,Fo=(t)=>`${y(t)}%`,Un=(t)=>`${y(t)}px`,Wn=(t)=>`${y(t)}vh`,Dn=(t)=>`${y(t)}vw`,Yn=(t)=>`${y(t)}vmin`,Jn=(t)=>`${y(t)}vmax`,zn=(t)=>`${t|0}ms`,Pn=(t)=>`${y(t)}s`;var jn=(t)=>`${y(t)}deg`,Xn=(t)=>`${y(t)}rad`,Zn=(t)=>`${y(t)}turn`,Kn=(t)=>`url(${t})`;var F=((t)=>{return t[t.IDLE=0]="IDLE",t[t.ACTIVE=1]="ACTIVE",t[t.DONE=2]="DONE",t[t.UNSUBSCRIBED=3]="UNSUBSCRIBED",t[t.ERROR=4]="ERROR",t})(F||{});var Lm=0,em=()=>Lm++,s=(t,o)=>!o||!o.id?{...o,id:t+"-"+em()}:o;class wo extends Tt{set(t){this.parent=t}childLogger(t,o){return new wo(t,o??this.level,this)}logEntry(t){this.parent.logEntry(t)}}var bn=new wo("root",$.FINE,wt);var H=bn.childLogger("rstream");class V{constructor(t,o){this.wrapped=t,o=s("sub",{closeIn:"last",closeOut:"last",cache:!0,...o}),this.parent=o.parent,this.id=o.id,this.closeIn=o.closeIn,this.closeOut=o.closeOut,this.cacheLast=o.cache,o.xform&&(this.xform=o.xform(_t()))}id;closeIn;closeOut;parent;__owner;xform;cacheLast;last=b;state=F.IDLE;subs=[];deref(){return this.last!==b?this.last:void 0}getState(){return this.state}setState(t){this.state=t}subscribe(t,o={}){this.ensureState();let n;if(t instanceof V&&!o.xform)t.ensureState(),qt(!t.parent,`sub '${t.id}' already has a parent`),t.parent=this,n=t;else n=new V(t,{...o,parent:this});return this.subs.push(n),this.setState(F.ACTIVE),n.setState(F.ACTIVE),this.last!=b&&n.next(this.last),n}transform(...t){let o,n;if(J(St(t)))n=t.pop(),o={error:n.error};return this.subscribe(o,s("xform",t.length>0?{...n,xform:z(...t)}:n))}map(t,o){return this.transform(e(t),o||{})}unsubscribe(t){return t?this.unsubscribeChild(t):this.unsubscribeSelf()}unsubscribeSelf(){return H.debug(this.id,"unsub self"),this.parent?.unsubscribe(this),this.state<F.UNSUBSCRIBED&&(this.state=F.UNSUBSCRIBED),this.release(),!0}unsubscribeChild(t){H.debug(this.id,"unsub child",t.id);let o=this.subs.indexOf(t);if(o>=0){if(this.subs.splice(o,1),this.closeOut==="first"||!this.subs.length&&this.closeOut!=="never")this.unsubscribe();return!0}return!1}next(t){if(this.state>=F.DONE)return;this.xform?this.dispatchXform(t):this.dispatch(t)}done(){if(H.debug(this.id,"entering done()"),this.state>=F.DONE)return;if(this.xform){if(!this.dispatchXformDone())return}if(this.state=F.DONE,this.dispatchTo("done"))this.state<F.UNSUBSCRIBED&&this.unsubscribe();H.debug(this.id,"exiting done()")}error(t){let n=this.wrapped?.error;return n&&H.debug(this.id,"attempting wrapped error handler"),n?.(t)||this.unhandledError(t)}unhandledError(t){return(H.parent!==wt?H:console).warn(this.id,"unhandled error:",t),this.unsubscribe(),this.state=F.ERROR,!1}dispatchTo(t,o){let n=this.wrapped;if(n)try{n[t]&&n[t](o)}catch(m){if(!this.error(m))return!1}let r=t==="next"?this.subs:[...this.subs];for(let m=r.length;m-- >0;){n=r[m];try{n[t]&&n[t](o)}catch(f){if(t==="error"||!n.error||!n.error(f))return this.unhandledError(f)}}return!0}dispatch(t){H.debug(this.id,"dispatch",t),this.cacheLast&&(this.last=t),this.dispatchTo("next",t)}dispatchXform(t){let o;try{o=this.xform[2]([],t)}catch(n){this.error(n);return}if(this.dispatchXformVals(o))S(o)&&this.done()}dispatchXformDone(){let t;try{t=this.xform[1]([])}catch(o){return this.error(o)}return this.dispatchXformVals(t)}dispatchXformVals(t){let o=P(t);for(let n=0,r=o.length;n<r&&this.state<F.DONE;n++)this.dispatch(o[n]);return this.state<F.ERROR}ensureState(){if(this.state>=F.DONE)Et(`operation not allowed in state ${F[this.state]}`)}release(){this.subs.length=0,delete this.parent,delete this.xform,delete this.last}}var pn=(t,o)=>{let n=new Vn(o);return n.next(t),n};class Vn extends V{src;_cancel;_inited;constructor(t,o){let[n,r]=X(t)?[t,o||{}]:[void 0,t||{}];super(r.error?{error:r.error}:void 0,s("stream",r));this.src=n,this._inited=!1}subscribe(t,o={}){let n=super.subscribe(t,o);if(!this._inited){if(this.src)try{this._cancel=this.src(this)||(()=>{return})}catch(r){let m=this.wrapped;if(!m||!m.error||!m.error(r))this.unhandledError(r)}this._inited=!0}return n}unsubscribe(t){let o=super.unsubscribe(t);if(o&&(!t||(!this.subs||!this.subs.length)&&this.closeOut!=="never"))this.cancel();return o}done(){this.cancel(),super.done(),delete this.src,delete this._cancel}error(t){if(super.error(t))return!0;return this.cancel(),!1}cancel(){if(this._cancel){H.debug(this.id,"cancel");let t=this._cancel;delete this._cancel,t()}}}var qn=(t,o)=>t==="first"||t==="last"&&!o;function So(t){return t?Ot(So(),t):Nt(()=>({}),(o,[n,r])=>(o[n]=r,o))}var Qn=()=>(t)=>{let o=t[2];return p(t,(n,r)=>{if(r){for(let m of P(r)||[])if(n=o(n,m),S(n))break}return S(r)?Cn(n):n})};function Ho(t,o){return T(o)?ht(Ho(t),o):z(e(t),Qn())}function Ro(t,o){return T(o)?x(Ro(t),o):e(X(t)?(n)=>[t(n),n]:(n)=>[t,n])}function yo(...t){let o=lt(yo,t);if(o)return o;let n=t[0],r=t[1]!==!1;return e((m)=>{let f=r?{}:m;for(let E in m)f[E]=n(m[E]);return f})}var kn=(t)=>t;function Mo(...t){let o=lt(Mo,t,ht);if(o)return o;let{key:n=kn,mergeOnly:r=!1,reset:m=!0,all:f=!0,backPressure:E=0}=t[1],G=B(t[0])?new Set(t[0]):t[0],O=new Set,N=new Map,_={},h=([i,A,I])=>{let v=!0;if(r||E<1)return[i,(L)=>{if(m&&f&&O.size>0||!m&&v)L=I(L,_),_={},O.clear(),v=!1;return A(L)},(L,d)=>{let R=n(d);if(G.has(R)){if(_[R]=d,O.add(R),r||vn(G,O))if(L=I(L,_),v=!1,m)_={},O.clear();else _={..._}}return L}];else return[i,(L)=>{if(f&&O.size>0)L=I(L,dn(N,O)),N.clear(),O.clear();return A(L)},(L,d)=>{let R=n(d);if(G.has(R)){let K=N.get(R);!K&&N.set(R,K=[]),K.length>=E&&Et(`max back pressure (${E}) exceeded for input: ${String(R)}`),K.push(d),O.add(R);while(vn(G,O))if(L=I(L,dn(N,O)),v=!1,S(L))break}return L}]};return h.keys=()=>G,h.clear=()=>{N.clear(),G.clear(),O.clear(),_={}},h.add=(i)=>{G.add(i)},h.delete=(i,A=!0)=>{if(N.delete(i),G.delete(i),A)O.delete(i),delete _[i]},h}var vn=(t,o)=>{if(o.size<t.size)return!1;for(let n of t)if(!o.has(n))return!1;return!0},dn=(t,o)=>{let n={};for(let r of o){let m=t.get(r);n[r]=m.shift(),!m.length&&o.delete(r)}return n};var ln=(t,o)=>{let n=!0;for(let r of o)n=t.removeID(r)&&n;return n};var ct=(t)=>new gn(t);class gn extends V{sources;idSources;realSourceIDs;invRealSourceIDs;psync;clean;constructor(t){let o=Mo(new Set,{key:(r)=>r[0],mergeOnly:t.mergeOnly===!0,reset:t.reset===!0,all:t.all!==!1,backPressure:t.backPressure||0}),n=yo((r)=>r[1]);super(void 0,s("streamsync",{...t,xform:t.xform?z(o,n,t.xform):z(o,n)}));this.sources=new Map,this.realSourceIDs=new Map,this.invRealSourceIDs=new Map,this.idSources=new Map,this.psync=o,this.clean=!!t.clean,t.src&&this.addAll(t.src)}add(t,o){o||(o=t.id),this.ensureState(),this.psync.add(o),this.realSourceIDs.set(o,t.id),this.invRealSourceIDs.set(t.id,o),this.idSources.set(t.id,t),this.sources.set(t,t.subscribe({next:(n)=>n[1]instanceof V?this.add(n[1]):this.next(n),done:()=>this.markDone(t),__owner:this},{xform:Ro(o),id:`in-${o}`}))}addAll(t){for(let o in t)this.psync.add(o);for(let o in t)this.add(t[o],o)}remove(t){let o=this.sources.get(t);if(o){let n=this.invRealSourceIDs.get(t.id);return H.info(`removing src: ${t.id} (${n})`),this.psync.delete(n,this.clean),this.realSourceIDs.delete(n),this.invRealSourceIDs.delete(t.id),this.idSources.delete(t.id),this.sources.delete(t),o.unsubscribe(),!0}return!1}removeID(t){let o=this.getSourceForID(t);return o?this.remove(o):!1}removeAll(t){for(let n of t)this.psync.delete(this.invRealSourceIDs.get(n.id));let o=!0;for(let n of t)o=this.remove(n)&&o;return o}removeAllIDs(t){return ln(this,t)}getSourceForID(t){return this.idSources.get(this.realSourceIDs.get(t))}getSources(){let t={};for(let[o,n]of this.idSources)t[this.invRealSourceIDs.get(o)]=n;return t}unsubscribe(t){if(!t){H.debug(this.id,"unsub sources");for(let o of this.sources.values())o.unsubscribe();this.sources.clear(),this.psync.clear(),this.realSourceIDs.clear(),this.invRealSourceIDs.clear(),this.idSources.clear()}return super.unsubscribe(t)}markDone(t){this.remove(t),qn(this.closeIn,this.sources.size)&&this.done()}}var Io=W((t,o=" ")=>{let n=nt(String(o),t);return(r,m)=>{if(r==null)return n;return r=r.toString(),m=m!==void 0?m:r.length,m<t?n.substring(m)+r:r}}),CO=Io(2,"0"),AO=Io(3,"0"),xn=Io(4,"0");var Bm=/\{(\d+)\}/g;var Uo=(t,...o)=>o.length>0?t.replace(Bm,(n,r)=>String(o[parseInt(r,10)])):t;var an=(t)=>({key:(o)=>o,group:_t(),...t});function Wo(...t){let o=An(Wo,t);if(o)return o;let n=an(t[0]),[r,m,f]=n.group;return[()=>({}),(E)=>{for(let G in E)E[G]=m(E[G]);return E},(E,G)=>{let O=n.key(G);return E[O]=E[O]?f(E[O],G):f(r(),G),E}]}function Do(t,o){return T(o)?x(Do(t),o):(n)=>{let r=n[2];return p(n,(m,f)=>t(f)?r(m,f):m)}}import{watch as nr}from"fs";import{resolve as c}from"path";var sn={specs:Y({alias:"s",optional:!1,desc:"Path to generated JSON defs"})},to={bundle:M({alias:"b",desc:"Bundle inputs (see `out` option)"})},At={include:Yt({alias:"I",desc:"Include CSS files (prepend)"})},oo={eval:Y({alias:"e",desc:"eval meta stylesheet in given string (ignores other inputs & includes)"})},no={force:Yt({alias:"f",hint:"STR",desc:"CSS classes to force include (wildcards are supported, @-prefix will read from file)",delim:","})},cn={media:Yt({alias:"m",hint:"ID",desc:"Media query IDs (use 'ALL' for all)",delim:","})},tr={onlyDecls:M({desc:"Only emit framework decls"})},q={out:Y({alias:"o",desc:"Output file (or stdout)"})},ro={prec:Jt({default:3,desc:"Number of fractional digits"})},Q={pretty:M({alias:"p",desc:"Pretty print output"})},Lt={noDecls:M({alias:"d",desc:"Don't emit framework decls"})},et={noHeader:M({desc:"Don't emit generated header comment"})},Bt={scope:Y({desc:"Suffix for CSS class names"})},$t={watch:M({alias:"w",desc:"Watch input files for changes"})};import{watch as $m}from"fs";import{resolve as or}from"path";var k=(t,o,n)=>{o=u(o)?o:o.join(` `),t?Ao(or(t),o,n):process.stdout.write(o+` `)},mo=({info:{name:t,version:o}})=>`/*! ${t} v${o} - generated by thi.ng/meta-css @ ${new Date().toISOString()} */`,yt=(t,o)=>{let n=()=>{o.info("closing watchers..."),r.forEach((m)=>m.watcher.close())},r=t.map((m,f)=>{m=or(m);let E=pn(w(m,o),{id:`in${xn(f)}`});return{input:E,watcher:$m(m,{},(G)=>{if(G==="change")try{E.next(w(m,o))}catch(O){o.warn(O.message),n()}else o.warn("input removed:",m),n()})}});return process.on("SIGINT",n),ct({src:So(e(({input:m})=>[m.id,m],r))})},fo=(t)=>Object.keys(t).reduce((o,n)=>{if(!n.startsWith("__"))o[n]=t[n];return o},{});var mr={desc:"Transpile (and optionally bundle) meta stylesheets to CSS",opts:{...to,...oo,...no,...At,...Lt,...et,...q,...Q,...Bt,...sn,...$t,noWrite:M({desc:"Don't write files, use stdout only"})},fn:Yo};async function Yo(t){let o=Z(c(t.opts.specs),t.logger),n=Sm(o,t.opts.force||[],t.logger);if(t.opts.bundle)if(t.opts.watch)await Tm(t,n);else It(t,o,n,t.opts.eval?[t.opts.eval]:t.inputs.map((r)=>w(c(r),t.logger)),t.opts.out);else if(t.opts.watch)await um(t,o,n);else if(t.opts.eval)try{It(t,o,n,[t.opts.eval])}catch(r){t.logger.warn(r.message)}else for(let r of t.inputs)try{r=c(r);let m=!t.opts.noWrite?r.replace(/\.mcss$/,".css"):void 0;It(t,o,n,[w(r,t.logger)],m)}catch(m){t.logger.warn(m.message)}}var um=async(t,o,n)=>{let r=c(t.opts.specs),m,f={process:()=>{try{return o=Z(r,t.logger),m.forEach((G)=>G.process()),!0}catch(G){return t.logger.warn(G.message+": "+r),!1}},watcher:nr(r,{},(G)=>{if(G==="change")f.process();else t.logger.warn("specs file removed:",r),E()})},E=()=>{t.logger.info("closing watchers..."),f.watcher.close(),m.forEach((G)=>G.watcher.close())};m=t.inputs.map((G)=>{G=c(G);let O=!t.opts.noWrite?G.replace(/\.mcss$/,".css"):void 0,N=()=>{try{return It(t,o,n,[w(G,t.logger)],O),!0}catch(_){if(t.logger.warn(_.message+": "+G),m)E();return!1}};if(!N())process.exit(1);return{process:N,watcher:nr(G,{},(_)=>{if(_==="change")N();else t.logger.warn("input removed:",G),E()})}}),t.logger.info("waiting for changes, press ctrl+c to cancel..."),process.on("SIGINT",E)},Tm=async(t,o)=>{ct({src:{styles:yt(t.inputs,t.logger),specs:yt([t.opts.specs],t.logger).map((n)=>JSON.parse(Object.values(n)[0]))}}).subscribe({next({styles:n,specs:r}){try{It(t,r,o,Object.keys(n).sort().map((m)=>n[m]),t.opts.out)}catch(m){t.logger.warn(m.message)}}})},It=({logger:t,opts:{include:o,noDecls:n,noHeader:r,pretty:m,scope:f}},E,G,O,N)=>{let _={logger:t,specs:E,css:{format:m?dt:Gt,fns:st,scope:f},mediaQueryIDs:new Set(Object.keys(E.media)),mediaQueryRules:{...G.mediaQueryRules},plainRules:{...G.plainRules}},h=o?o.map((i)=>w(c(i),t).trim()):[];if(!r)h.push(mo(E));if(!n&&E.decls.length)h.push(a(E.decls,_.css));O.forEach((i)=>Hm(i,_)),wm(h,_),Fm(h,_),k(N,h,t)},Fm=(t,{css:o,logger:n,mediaQueryRules:r,specs:m})=>{for(let f in r){let E=Er(r[f],m);n.debug("mediaquery rules",f,E),t.push(a(Ct(Im(m.media,f),E),o))}},wm=(t,{css:o,logger:n,plainRules:r,specs:m})=>{let f=Er(r,m);n.debug("plain rules",f),t.push(a(f,o))},Sm=(t,o,n)=>{let r=new Set(Object.keys(t.media)),m=new Set(Object.keys(t.classes)),f={},E={};if(o.length&&o[0][0]==="@")o=[...mt(w(c(o[0].substring(1)),n))];for(let G of o){if(!G||G.startsWith("//"))continue;let{token:O,query:N}=Gr(G,r),_;if(O.includes("*")){let h=new RegExp(`^${O.replace("*",".*")}$`);_=[...Do((i)=>h.test(i),m)]}else if(m.has(O))_=[O];else{n.warn(`unknown include rule ID: ${G}, skipping...`);continue}for(let h of _)n.debug("including class:",h),N?Or(f,N,`.${h}`,h):Nr(E,`.${h}`,h)}return{mediaQueryRules:f,plainRules:E}},Hm=(t,{specs:o,mediaQueryIDs:n,mediaQueryRules:r,plainRules:m})=>{let f=Ut(),E=Ut(f),G={root:f,curr:E,scopes:[E]};for(let O of mt(t)){if(!O||/^\s*\/\//.test(O))continue;for(let N of Rm(O)){if(!N)continue;let _=G.curr;switch(_.state){case"sel":case"nest":if(N==="{"){if(_.state==="sel")_.sel=_.sel.map((h)=>h.replace(",","")),_.path=ym(G.scopes);_.state="class"}else if(N==="}")rr(G);else{let h=St(_.sel);if(!h||h.endsWith(","))_.sel.push(N);else _.sel[_.sel.length-1]+=" "+N}break;case"class":if(N==="{")_.state="nest",G.scopes.push(G.curr=Ut(_));else if(N==="}")rr(G);else{let{token:h,query:i}=Gr(N,n);if(!o.classes[h]&&!(_r(h)||ir(h)||hr(h)))C(`unknown class ID: ${h}`);if(i)Or(r,i,_.path,h);else Nr(m,_.path,h)}break;default:Et(_.state)}}}};function*Rm(t){let o=-1,n=t.length,r=0,m=0,f=!1;for(let E=0;E<n;E++){let G=t[E];if(G==='"'&&!(r||m))if(f)yield t.substring(o,E+1),o=-1,f=!1;else f=!0;else if(G===" "||G==="\t"){if(!(r||m||f)&&o>=0)yield t.substring(o,E),o=-1}else if(G==="{"||G==="}"){if(o>=0)yield t.substring(o,E);yield G,o=-1}else if(G==="(")r++;else if(G===")"){if(--r<0)C(`invalid nesting in line: '${t}'`)}else if(G==="["){if(o<0)o=E;m++}else if(G==="]"){if(--m<0)C(`invalid arg nesting in line: '${t}'`)}else if(o<0)o=E}if(f)C("string literals must be fully on a single line");if(r)C("template calls must be fully on a single line");if(m)C("verbatim properties must be fully on a single line");if(o>=0)yield t.substring(o,n)}var Mt=":",fr="///",Ut=(t)=>({state:"sel",sel:t?[]:["<root>"],path:"",parent:t}),rr=(t)=>{let o=!t.curr.sel.length;if(qt(!!t.curr.parent,"stack underflow"),t.scopes.pop(),t.scopes.length>0){if(t.curr=St(t.scopes),!o&&t.curr.state==="nest")t.scopes.push(t.curr=Ut(t.curr))}else t.scopes.push(t.curr=Ut(t.root))},ym=(t)=>t.map((o)=>o.sel.join(",")).join(fr),Er=(t,o)=>Object.entries(t).map(([n,r])=>Mm(n,r,o)),Mm=(t,o,n)=>{let r=[],m=r,f=t.split(fr);for(let E=0;E<f.length;E++){let G=f[E].split(",");if(E==f.length-1){let O=Object.assign({},...e((N)=>ir(N)?Dm(N):_r(N)?Um(N):hr(N)?Wm(n,N):fo(n.classes[N]),o));G.push(O)}m.push(G),m=G}return r[0]},Gr=(t,o)=>{if(/^::?/.test(t))return{token:t};let n=t.lastIndexOf(Mt);if(n<0)return{token:t};let r=t.indexOf("("),m=t.indexOf("[");if(r>0||m>0){let G=r>0?m>0?Math.min(r,m):r:m;if(G<n&&t.indexOf(Mt)>G)return{token:t};n=t.substring(0,G).lastIndexOf(Mt)}let f=t.substring(0,n);if(!f.split(Mt).every((G)=>o.has(G)))C(`invalid media query in token: ${t}`);return{token:t.substring(n+1),query:f}},Im=(t,o)=>o.split(Mt).reduce((n,r)=>Object.assign(n,t[r]),{}),Or=(t,o,n,r)=>{if(!t[o])t[o]={};(t[o][n]||(t[o][n]=new Set)).add(r)},Nr=(t,o,n)=>(t[o]||(t[o]=new Set)).add(n),Um=(t)=>{let o=t.indexOf("="),n=t.substring(0,o),r=t.substring(o+1);return{[`--${n}`]:r[0]==='"'?r.slice(1,-1):r}},Wm=(t,o)=>{let n=o.indexOf("("),r=o.substring(0,n),m=o.substring(n+1,o.length-1).split(/(?<!\\),/g).map((E)=>E.trim().replace("\\,",",")),f=t.templates[r];if(!f)C(`unknown template: ${r}`);if(m.length!==f.__arity)C(`template "${r}" expected ${f.__arity} arguments`);return Object.entries(f).reduce((E,[G,O])=>{if(!G.startsWith("__")){if(G=Uo(G,...m),u(O))O=Uo(O,...m);E[G]=O}return E},{})},Dm=(t)=>{let[o,n,r]=/^(.+)-\[(.+)\]/.exec(t);return{[n]:r}},_r=(t)=>/^[a-z0-9:_-]+=.+/i.test(t),hr=(t)=>t.includes("(")&&t.endsWith(")"),ir=(t)=>t.indexOf("-[")>0&&t.endsWith("]");var Ar={deg:jn,em:yn,ex:Mn,ms:zn,percent:Fo,px:Un,rad:Xn,rem:In,second:Pn,turn:Zn,url:Kn,vh:Wn,vmax:Jn,vmin:Yn,vw:Dn,"%":Fo},Ym={percent:"{0}%",second:"{0}s",url:"url({0})"},Jm={"":[""],a:[""],h:["-left","-right"],v:["-top","-bottom"],t:["-top"],top:["top"],b:["-bottom"],bottom:["bottom"],r:["-right"],right:["right"],l:["-left"],left:["left"],x:["-x"],y:["-y"],in:[""],out:[""]},Lr={desc:"Generate framework rules from specs",opts:{...q,...ro,...Q,...$t},fn:Jo};async function Jo(t){if(t.opts.watch)await zm(t);else await er(t.inputs.map((o)=>w(o,t.logger)),t.opts,t.logger)}var zm=async(t)=>{yt(t.inputs,t.logger).subscribe({next(o){try{er(Object.keys(o).sort().map((n)=>o[n]),t.opts,t.logger)}catch(n){t.logger.warn(n.message)}}})},er=async(t,o,n)=>{let r={info:{name:"TODO",version:"0.0.0"},media:{},classes:{},templates:{},decls:[]};Rn(o.prec);for(let m of t){let f=JSON.parse(m);if(Object.assign(r.info,f.info),Object.assign(r.media,f.media),f.decls)r.decls.push(...f.decls);if(f.specs)for(let E of f.specs)try{Br(f,E,r.classes,n)}catch(G){n.warn(`error processing spec: ${E.name}`,G,", skipping...")}if(f.templates)for(let E of f.templates)Pm(f,E,r.templates,n)}return k(o.out,JSON.stringify(r,null,o.pretty?4:0),n),r},Br=(t,o,n,r,m=!1)=>{let f=B(o.vars)?o.vars:[""],E=u(o.props)?{[o.props]:"<v>"}:o.props,G=jm(o,t),O=new Set;for(let N of f){let _=t.vars?.[N]||Jm[N];if(!_)C(`unknown variation ID: ${N}`);for(let[h,i]of gt(_,Object.keys(G))){let A=tt(o.name,N,h,i,G[i]),I=o.unit?tt(o.unit,N,h,i,G[i]):void 0,v=m?Zm(I):Xm(G[i],I);if(!n[A]){if(n[A]={},o.user!=null)n[A].__user=o.user;if(o.doc!=null)n[A].__doc=Km(o.doc,N,h,i,v)}else if(!O.has(A))C(`duplicate class ID: ${A}`);O.add(A);let L=-1;for(let[d,R]of Object.entries(E)){let K=tt(d,N,h,i,G[i]),Eo=tt(!I||u(R)?String(R):Ar[I](R),N,h,i,v);if(n[A][K]=Eo,r.debug(A,K,Eo),m)L=Cr(Eo,Cr(K,L))}if(m)n[A].__arity=L+1}}return n},Pm=(t,o,n,r)=>Br(t,{...o,values:[""]},n,r,!0),Cr=(t,o)=>{let n=/\{(\d+)\}/g,r;while(r=n.exec(t))o=Math.max(o,+r[1]);return o},jm=(t,o)=>{let n=u(t.values)?o.tables?.[t.values]||C(`invalid table ID: ${t.values}`):t.values;if(J(n))return n;let r=t.key==="v"?(m)=>String(m):t.key==="i+1"?(m,f)=>String(f+1):t.key==="i"||t.key===void 0?(m,f)=>String(f):C(`invalid key type: ${t.key}`);return n.reduce((m,f,E)=>{return m[r(f,E)]=f,m},{})},Xm=(t,o)=>{if(!o||u(t))return t;let n=Ar[o];if(!n)C(`invalid unit: ${o}`);return n(t)},Zm=(t)=>t?Ym[t]||"{0}"+t:"{0}",tt=(t,o,n,r,m)=>t.replace(/<vid>/g,o).replace(/<var>/g,n).replace(/<k>/g,r).replace(/<v>/g,String(m)),Km=({group:t,desc:o,args:n},r,m,f,E)=>({group:t?tt(t,r,m,f,E):"TODO",desc:o?tt(o,r,m,f,E):void 0,args:n?n.map((G)=>tt(G,r,m,f,E)):void 0});var $r={desc:"Combination of the generate & convert commands",opts:{...to,...oo,...no,...At,...Lt,...et,...ro,...Q,...Bt,...$t,outCss:Y({desc:"Output file for CSS bundle",optional:!1}),outSpecs:Y({desc:"Output file for framework",optional:!1})},fn:async(t)=>{let{opts:o,inputs:n}=t,[r,m]=n.reduce((G,O)=>(G[O.endsWith(".json")?0:1].push(O),G),[[],[]]),f={inputs:r,format:t.format,logger:t.logger,opts:{...o,out:o.outSpecs}},E={inputs:m,format:t.format,logger:t.logger,opts:{...o,noWrite:!1,out:o.outCss,scope:o.scope,specs:o.outSpecs}};await Jo(f),await Yo(E)}};import{resolve as bm}from"path";var Fr={desc:"Generate Markdown documentation for framework specs",opts:{...q,level:Jt({alias:"l",desc:"Initial heading level",default:1}),title:Y({alias:"t",desc:"Custom main title, set to NONE to disable"})},inputs:1,fn:async(t)=>{let{logger:o,opts:n,inputs:r}=t,m=Z(bm(r[0]),o),f=pm(m,n);k(n.out,f,o)}},pm=(t,{level:o,title:n})=>{let r=Object.keys(t.classes).length,m=Object.keys(t.templates).length,f=[`Currently, there are ${r+m} CSS utility classes (incl. ${m} templates) defined in "${t.info.name}" (v${t.info.version}):`,"",`${ot(o+1)} Classes by category`,"",...Tr(t.classes,qm,o+2),`${ot(o+1)} Templates by category`,"",...Tr(t.templates,Qm,o+2),`${ot(o+1)} Media queries`,"",...Object.entries(t.media).map(([E,G])=>`- **${E}**: \`${JSON.stringify(G)}\``),""];if(n!=="NONE")f.unshift(`${ot(o)} ${n??t.info.name} `);return f},ur=(t)=>t.split(/(\d+)/).map((o)=>{let n=parseInt(o);return isNaN(n)?o:n}),Vm=(t,o)=>{if(/\d+/.test(t)&&/\d+/.test(o)){let n=ur(t),r=ur(o),m=n.length;if(m===r.length){for(let f=0;f<m;f++)if(n[f]!==r[f])return eo(n[f],r[f]);return 0}return n.length-r.length}return eo(t,o)},Tr=(t,o,n)=>{let r=Wo({key:([m,{__doc:f}])=>f?.group||"TODO",group:[()=>[],(m)=>m.sort(),(m,f)=>(m.push(f[0]),m)]},Object.entries(t));return Ho((m)=>{let f=r[m].sort(Vm).map((G)=>o(G,t[G].__doc,n+1)),E=f.length;return[`${ot(n)} ${Xt(m)}`,E>3?` <details><summary>${E} items:</summary> `:"",f.join(` `),E>3?`</details> `:""]},Object.keys(r).sort())},qm=(t,o)=>{if(!o?.desc)return`- \`${t}\``;let n=o.desc;if(/^-[a-z]/.test(n))n=n.substring(1);return`- \`${t}\` (${n})`},Qm=(t,o,n)=>{if(!o?.args)return`${ot(n)} ${t}(...) TODO`;let r=o.args.map((m)=>/^\w+/.exec(m)[0]).join(", ");return[`${ot(n)} \`${t}(${r})\``,"",...o.args.map(km),o.desc?` ${o.desc} `:""].join(` `)},km=(t)=>`- ${t.replace(/^(\w+)/,(o,n)=>`**${n}**`)}`,ot=W((t)=>"#".repeat(t));import{resolve as wr}from"path";var Hr={desc:"Export entire generated framework as CSS",opts:{...At,...Lt,...tr,...q,...Q,...et,...cn,...Bt},inputs:1,fn:async(t)=>{let{logger:o,opts:{include:n,media:r,noDecls:m,noHeader:f,onlyDecls:E,out:G,pretty:O,scope:N},inputs:_}=t,h={format:O?dt:Gt,fns:st,scope:N},i=Z(wr(_[0]),o),A=n?n.map((I)=>w(wr(I),o).trim()):[];if(!f)A.push(mo(i));if(!m&&i.decls.length)A.push(a(i.decls,h));if(!E)A.push(vm(i,r,h,o));k(G,A,o)}},vm=(t,o,n,r)=>{let m=Sr("",t);if(o){let f=o[0]==="ALL"?Object.keys(t.media):o;for(let E of f)if(t.media[E])m.push(Ct(t.media[E],Sr("-"+E,t)));else r.warn(`invalid media query ID: ${E}, skipping...`)}return a(m,n)},Sr=(t,o)=>Object.entries(o.classes).map(([n,r])=>[`.${n}${t}`,fo(r)]);var zo=Z(dm(process.argv[2],"package.json"));mn({name:"metacss",start:3,opts:{...po},commands:{convert:mr,develop:$r,doc:Fr,export:Hr,generate:Lr},ctx:async(t)=>{return fn(t.logger,t.opts.verbose),{...t,format:jt}},usage:{prefix:`${En(zo.name,zo.version,zo.description)} Usage: metacss <cmd> [opts] input [...] metacss <cmd> --help `,showGroupNames:!0,paramWidth:24}});