@salty-css/core 0.0.1-alpha.84 → 0.0.1-alpha.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/main.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("commander"),H=require("fs"),s=require("fs/promises"),n=require("path"),ae=require("ejs"),oe=require("../compiler/index.cjs"),re=require("../pascal-case-iWoaJWwT.cjs"),L=require("winston"),ce=require("child_process"),le=require("ora");var B=typeof document<"u"?document.currentScript:null;const t=L.createLogger({level:"debug",format:L.format.combine(L.format.colorize(),L.format.cli()),transports:[new L.transports.Console({})]}),h=p=>{t.error(p)},ee=p=>new Promise((w,j)=>{ce.exec(p,F=>{if(F)return j(F);w()})}),D=async(...p)=>{const w=p.map(k=>k.replace("-D","").split("@").slice(0,-1).join("@").trim()).join(", "),j=le(`Installing packages: ${w}`).start(),F=p.join(" ");await ee(`npm install ${F}`),j.succeed(`Installed packages: ${w}`)},de=()=>H.existsSync(n.join(process.cwd(),"node_modules",".bin","prettier"));async function x(p){try{if(!de())return;await ee(`./node_modules/.bin/prettier --write "${p}"`),t.info(`Formatted ${p} with Prettier`)}catch(w){t.error(`Error formatting ${p} with Prettier:`,w)}}async function pe(){const p=new se.Command;p.name("salty-css").description("Salty-CSS CLI tool to help with annoying configuration tasks.");const w={"salty.config.ts":Promise.resolve().then(()=>require("../salty.config-Dk6ZcCxI.cjs")),"saltygen/index.css":Promise.resolve().then(()=>require("../index-84Wroia-.cjs")),"react/react-styled-file.ts":Promise.resolve().then(()=>require("../react-styled-file-Dkubsz-U.cjs")),"react/react-vanilla-file.ts":Promise.resolve().then(()=>require("../react-vanilla-file-CG_WJLam.cjs"))},j=async(i,o)=>{const{default:c}=await w[i],u=ae.render(c,o);return{fileName:i,content:u}},F=async()=>{const i=n.join(process.cwd(),".saltyrc");return await s.readFile(i,"utf-8").then(JSON.parse).catch(()=>({}))},k=n.join(process.cwd(),"package.json"),I=async(i=k)=>{const o=await s.readFile(i,"utf-8").then(JSON.parse).catch(()=>{});if(!o)throw"Could not read package.json file!";return o},te=async(i,o=k)=>{typeof i=="object"&&(i=JSON.stringify(i,null,2)),await s.writeFile(o,i)},V=async()=>{const i=new URL("../package.json",typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("bin/main.cjs",document.baseURI).href);return I(i)},K=await(async()=>(await F()).defaultProject)(),b=await V(),q={core:`@salty-css/core@${b.version}`,react:`@salty-css/react@${b.version}`,eslintConfigCore:`@salty-css/eslint-config-core@${b.version}`,vite:`@salty-css/vite@${b.version}`,next:`@salty-css/next@${b.version}`},z=i=>{const o=i==="."?"":i,c=process.cwd();return n.join(c,o)};p.command("init [directory]").description("Initialize a new Salty-CSS project.").option("-d, --dir <dir>","Project directory to initialize the project in.").option("--css-file <css-file>","Existing CSS file where to import the generated CSS. Path must be relative to the given project directory.").option("--skip-install","Skip installing dependencies.").action(async function(i="."){if(!await I().catch(()=>{}))return h("Salty CSS project must be initialized in a directory with a package.json file.");t.info("Initializing a new Salty-CSS project!");const{dir:c=i,cssFile:u,skipInstall:g}=this.opts();if(!c)return h("Project directory must be provided. Add it as the first argument after init command or use the --dir option.");g||await D(q.core,q.react);const f=process.cwd(),l=z(c),$=await Promise.all([j("salty.config.ts"),j("saltygen/index.css")]);await s.mkdir(l,{recursive:!0});const m=$.map(async({fileName:e,content:a})=>{const d=n.join(l,e);if(await s.readFile(d,"utf-8").catch(()=>{})!==void 0){t.debug("File already exists: "+d);return}const C=e.split("/").slice(0,-1).join("/");C&&await s.mkdir(n.join(l,C),{recursive:!0}),t.info("Creating file: "+d),await s.writeFile(d,a),await x(d)});await Promise.all(m);const J=n.relative(f,l)||".",v=n.join(f,".saltyrc"),r=await s.readFile(v,"utf-8").catch(()=>{});if(r===void 0){t.info("Creating file: "+v);const a=JSON.stringify({defaultProject:J,projects:[J]},null,2);await s.writeFile(v,a)}else{t.info("Edit file: "+v);const e=JSON.parse(r),a=new Set((e==null?void 0:e.projects)||[]);a.add(J),e.projects=[...a];const d=JSON.stringify(e,null,2);await s.writeFile(v,d)}const S=n.join(f,".gitignore"),T=await s.readFile(S,"utf-8").catch(()=>{});T!==void 0&&(T.includes("saltygen")||(t.info("Edit file: "+S),await s.writeFile(S,T+`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=require("commander"),L=require("fs"),s=require("fs/promises"),n=require("path"),ie=require("ejs"),t=require("../index-BKoD9apd.cjs"),se=require("../pascal-case-iWoaJWwT.cjs"),oe=require("child_process"),ae=require("ora");var W=typeof document<"u"?document.currentScript:null;const Y=g=>new Promise((h,C)=>{oe.exec(g,x=>{if(x)return C(x);h()})}),N=async(...g)=>{const h=g.map(F=>F.replace("-D","").split("@").slice(0,-1).join("@").trim()).join(", "),C=ae(`Installing packages: ${h}`).start(),x=g.join(" ");await Y(`npm install ${x}`),C.succeed(`Installed packages: ${h}`)},re=()=>L.existsSync(n.join(process.cwd(),"node_modules",".bin","prettier"));async function P(g){try{if(!re())return;await Y(`./node_modules/.bin/prettier --write "${g}"`),t.logger.info(`Formatted ${g} with Prettier`)}catch(h){t.logger.error(`Error formatting ${g} with Prettier:`,h)}}async function ce(){const g=new ne.Command;g.name("salty-css").description("Salty-CSS CLI tool to help with annoying configuration tasks.");const h={"salty.config.ts":Promise.resolve().then(()=>require("../salty.config-Dk6ZcCxI.cjs")),"saltygen/index.css":Promise.resolve().then(()=>require("../index-84Wroia-.cjs")),"react/react-styled-file.ts":Promise.resolve().then(()=>require("../react-styled-file-Dkubsz-U.cjs")),"react/react-vanilla-file.ts":Promise.resolve().then(()=>require("../react-vanilla-file-CG_WJLam.cjs"))},C=async(i,a)=>{const{default:c}=await h[i],f=ie.render(c,a);return{fileName:i,content:f}},x=async()=>{const i=n.join(process.cwd(),".saltyrc");return await s.readFile(i,"utf-8").then(JSON.parse).catch(()=>({}))},F=n.join(process.cwd(),"package.json"),D=async(i=F)=>{const a=await s.readFile(i,"utf-8").then(JSON.parse).catch(()=>{});if(!a)throw"Could not read package.json file!";return a},Z=async(i,a=F)=>{typeof i=="object"&&(i=JSON.stringify(i,null,2)),await s.writeFile(a,i)},M=async()=>{const i=new URL("../package.json",typeof document>"u"?require("url").pathToFileURL(__filename).href:W&&W.tagName.toUpperCase()==="SCRIPT"&&W.src||new URL("bin/main.cjs",document.baseURI).href);return D(i)},B=await(async()=>(await x()).defaultProject)(),k=await M(),I={core:`@salty-css/core@${k.version}`,react:`@salty-css/react@${k.version}`,eslintConfigCore:`@salty-css/eslint-config-core@${k.version}`,vite:`@salty-css/vite@${k.version}`,next:`@salty-css/next@${k.version}`},R=i=>{const a=i==="."?"":i,c=process.cwd();return n.join(c,a)};g.command("init [directory]").description("Initialize a new Salty-CSS project.").option("-d, --dir <dir>","Project directory to initialize the project in.").option("--css-file <css-file>","Existing CSS file where to import the generated CSS. Path must be relative to the given project directory.").option("--skip-install","Skip installing dependencies.").action(async function(i="."){if(!await D().catch(()=>{}))return t.logError("Salty CSS project must be initialized in a directory with a package.json file.");t.logger.info("Initializing a new Salty-CSS project!");const{dir:c=i,cssFile:f,skipInstall:u}=this.opts();if(!c)return t.logError("Project directory must be provided. Add it as the first argument after init command or use the --dir option.");u||await N(I.core,I.react);const p=process.cwd(),l=R(c),b=await Promise.all([C("salty.config.ts"),C("saltygen/index.css")]);await s.mkdir(l,{recursive:!0});const m=b.map(async({fileName:e,content:o})=>{const d=n.join(l,e);if(await s.readFile(d,"utf-8").catch(()=>{})!==void 0){t.logger.debug("File already exists: "+d);return}const S=e.split("/").slice(0,-1).join("/");S&&await s.mkdir(n.join(l,S),{recursive:!0}),t.logger.info("Creating file: "+d),await s.writeFile(d,o),await P(d)});await Promise.all(m);const E=n.relative(p,l)||".",j=n.join(p,".saltyrc"),r=await s.readFile(j,"utf-8").catch(()=>{});if(r===void 0){t.logger.info("Creating file: "+j);const o=JSON.stringify({defaultProject:E,projects:[E]},null,2);await s.writeFile(j,o)}else{t.logger.info("Edit file: "+j);const e=JSON.parse(r),o=new Set((e==null?void 0:e.projects)||[]);o.add(E),e.projects=[...o];const d=JSON.stringify(e,null,2);await s.writeFile(j,d)}const w=n.join(p,".gitignore"),A=await s.readFile(w,"utf-8").catch(()=>{});A!==void 0&&(A.includes("saltygen")||(t.logger.info("Edit file: "+w),await s.writeFile(w,A+`
2
2
 
3
3
  # Salty-CSS
4
4
  saltygen
5
- `)));const P=["src","public","assets","styles","css","app"],G=["styles","css","app","pages"],W=["index","styles","main","global","globals"],U=[".css",".scss",".sass"],N=await(async()=>{if(u)return u;for(const e of P)for(const a of W)for(const d of U){const y=n.join(l,e,a+d);if(await s.readFile(y,"utf-8").catch(()=>{})!==void 0)return n.relative(l,y);for(const O of G){const A=n.join(l,e,O,a+d);if(await s.readFile(A,"utf-8").catch(()=>{})!==void 0)return n.relative(l,A)}}})();if(N){const e=n.join(l,N),a=await s.readFile(e,"utf-8").catch(()=>{});if(a!==void 0&&!a.includes("saltygen")){const y=n.join(e,".."),O=`@import '${n.relative(y,n.join(l,"saltygen/index.css"))}';`;t.info("Adding global import statement to CSS file: "+e),await s.writeFile(e,O+`
6
- `+a),await x(e)}}else t.warn("Could not find a CSS file to import the generated CSS. Please add it manually.");const X=n.join(f,".eslintrc.json"),ne=H.existsSync(X),Y=n.join(l,".eslintrc.json"),Z=H.existsSync(Y);if(ne||Z){g||await D(q.eslintConfigCore);const e=Z?Y:X,a=await s.readFile(e,"utf-8").catch(()=>{});if(!a)return h("Could not read ESLint config file.");if(!a.includes("salty-css")){const y=JSON.parse(a);t.info("Edit file: "+e),y.extends||(y.extends=[]),y.extends.push("@salty-css/core");const C=JSON.stringify(y,null,2);await s.writeFile(e,C),await x(e)}}const _=n.join(l,"vite.config.ts"),M=await s.readFile(_,"utf-8").catch(()=>{});if(M!==void 0&&!M.includes("saltyPlugin")){t.info("Edit file: "+_);const a=`import { saltyPlugin } from '@salty-css/vite';
7
- `,y=M.replace(/(plugins: \[)/,`$1
8
- saltyPlugin(__dirname),`);g||await D(`-D ${q.vite}`),t.info("Adding Salty-CSS plugin to Vite config..."),await s.writeFile(_,a+y),await x(_)}const R=["next.config.js","next.config.cjs","next.config.ts","next.config.mjs"].map(e=>n.join(l,e)).find(e=>H.existsSync(e));if(R){let e=await s.readFile(R,"utf-8").catch(()=>{});if(e!==void 0&&!e.includes("withSaltyCss")){let d=!1;/\splugins([^=]*)=[^[]\[/.test(e)&&!d&&(e=e.replace(/\splugins([^=]*)=[^[]\[/,(A,E)=>` plugins${E}= [withSaltyCss,`),d=!0);const C=e.includes("module.exports"),O=C?`const { withSaltyCss } = require('@salty-css/next');
5
+ `)));const v=["src","public","assets","styles","css","app"],H=["styles","css","app","pages"],z=["index","styles","main","global","globals"],T=[".css",".scss",".sass"],$=await(async()=>{if(f)return f;for(const e of v)for(const o of z)for(const d of T){const y=n.join(l,e,o+d);if(await s.readFile(y,"utf-8").catch(()=>{})!==void 0)return n.relative(l,y);for(const q of H){const O=n.join(l,e,q,o+d);if(await s.readFile(O,"utf-8").catch(()=>{})!==void 0)return n.relative(l,O)}}})();if($){const e=n.join(l,$),o=await s.readFile(e,"utf-8").catch(()=>{});if(o!==void 0&&!o.includes("saltygen")){const y=n.join(e,".."),q=`@import '${n.relative(y,n.join(l,"saltygen/index.css"))}';`;t.logger.info("Adding global import statement to CSS file: "+e),await s.writeFile(e,q+`
6
+ `+o),await P(e)}}else t.logger.warn("Could not find a CSS file to import the generated CSS. Please add it manually.");const K=n.join(p,".eslintrc.json"),ee=L.existsSync(K),Q=n.join(l,".eslintrc.json"),X=L.existsSync(Q);if(ee||X){u||await N(I.eslintConfigCore);const e=X?Q:K,o=await s.readFile(e,"utf-8").catch(()=>{});if(!o)return t.logError("Could not read ESLint config file.");if(!o.includes("salty-css")){const y=JSON.parse(o);t.logger.info("Edit file: "+e),y.extends||(y.extends=[]),y.extends.push("@salty-css/core");const S=JSON.stringify(y,null,2);await s.writeFile(e,S),await P(e)}}const U=n.join(l,"vite.config.ts"),G=await s.readFile(U,"utf-8").catch(()=>{});if(G!==void 0&&!G.includes("saltyPlugin")){t.logger.info("Edit file: "+U);const o=`import { saltyPlugin } from '@salty-css/vite';
7
+ `,y=G.replace(/(plugins: \[)/,`$1
8
+ saltyPlugin(__dirname),`);u||await N(`-D ${I.vite}`),t.logger.info("Adding Salty-CSS plugin to Vite config..."),await s.writeFile(U,o+y),await P(U)}const _=["next.config.js","next.config.cjs","next.config.ts","next.config.mjs"].map(e=>n.join(l,e)).find(e=>L.existsSync(e));if(_){let e=await s.readFile(_,"utf-8").catch(()=>{});if(e!==void 0&&!e.includes("withSaltyCss")){let d=!1;/\splugins([^=]*)=[^[]\[/.test(e)&&!d&&(e=e.replace(/\splugins([^=]*)=[^[]\[/,(O,J)=>` plugins${J}= [withSaltyCss,`),d=!0);const S=e.includes("module.exports"),q=S?`const { withSaltyCss } = require('@salty-css/next');
9
9
  `:`import { withSaltyCss } from '@salty-css/next';
10
- `;C&&!d?(e=e.replace(/module.exports = ([^;]+)/,(A,E)=>`module.exports = withSaltyCss(${E})`),d=!0):d||(e=e.replace(/export default ([^;]+)/,(A,E)=>`export default withSaltyCss(${E})`)),g||await D(`-D ${q.next}`),t.info("Adding Salty-CSS plugin to Next.js config..."),await s.writeFile(R,O+e),await x(R)}}const ie=await I().catch(()=>h("Could not read package.json file.")).then(e=>(e.scripts||(e.scripts={}),e.scripts.prepare?e.scripts.prepare.includes("salty-css")||(t.info("Edit file: "+k),e.scripts.prepare=e.scripts.prepare+" && npx salty-css build"):(t.info("Edit file: "+k),e.scripts.prepare="npx salty-css build"),e));await te(ie),t.info("🎉 Salty CSS project initialized successfully!"),t.info("Next steps:"),t.info("1. Configure variables and templates in `salty.config.ts`"),t.info("2. Create a new component with `npx salty-css generate [component-name]`"),t.info("3. Run `npx salty-css build` to generate the CSS"),t.info("4. Read about the features in the documentation: https://salty-css.dev"),t.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐")}),p.command("build [directory]").alias("b").description("Build the Salty-CSS project.").option("-d, --dir <dir>","Project directory to build the project in.").action(async function(i=K){t.info("Building the Salty-CSS project...");const{dir:o=i}=this.opts();if(!o)return h("Project directory must be provided. Add it as the first argument after build command or use the --dir option.");const c=z(o);await oe.generateCss(c)}),p.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>","File to generate.").option("-d, --dir <dir>","Project directory to generate the file in.").option("-t, --tag <tag>","HTML tag of the component.","div").option("-n, --name <name>","Name of the component.").option("-c, --className <className>","CSS class of the component.").option("-rc, --reactComponent <rc>","Generate a React component as well.").action(async function(i,o=K){const{file:c=i,dir:u=o,tag:g,name:f,className:l,reactComponent:$=!1}=this.opts();if(!c)return h("File to generate must be provided. Add it as the first argument after generate command or use the --file option.");if(!u)return h("Project directory must be provided. Add it as the second argument after generate command or use the --dir option.");const m=z(u),J=c.split("/").slice(0,-1).join("/");J&&await s.mkdir(n.join(m,J),{recursive:!0});const v=n.join(m,c),r=n.parse(v);r.ext||(r.ext=".ts"),r.name.endsWith(".css")||(r.name=r.name+".css"),r.base=r.name+r.ext;const S=n.format(r);if(await s.readFile(S,"utf-8").catch(()=>{})!==void 0){t.error("File already exists:",S);return}let P=re.pascalCase(f||r.base.replace(/\.css\.\w+$/,""));if($){const W=P+"Component";P=P+"Wrapper";const U=r.base.replace(/\.css\.\w+$/,""),{content:Q}=await j("react/react-vanilla-file.ts",{tag:g,componentName:W,styledComponentName:P,className:l,fileName:U});r.name=U.replace(/\.css$/,""),r.ext=".tsx",r.base=r.name+r.ext;const N=n.format(r);t.info("Generating a new file: "+N),await s.writeFile(N,Q),await x(N)}const{content:G}=await j("react/react-styled-file.ts",{tag:g,name:P,className:l});t.info("Generating a new file: "+S),await s.writeFile(S,G),await x(S)}),p.command("update [version]").alias("up").description("Update Salty-CSS packages to the latest or specified version.").option("-v, --version <version>","Version to update to.").option("--legacy-peer-deps <legacyPeerDeps>","Use legacy peer dependencies (not recommended).",!1).action(async function(i="latest"){const{legacyPeerDeps:o,version:c=i}=this.opts(),u=n.join(process.cwd(),"package.json"),g=await I(u).catch(m=>h(m));if(!g)return;const f={...g.dependencies,...g.devDependencies},l=Object.keys(f).filter(m=>m==="salty-css"||m.startsWith("@salty-css/"));if(!l.length)return h("No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: "+u);const $=l.map(m=>c==="@"?`${m}@${b.version}`:`${m}@${c.replace(/^@/,"")}`);o?(t.warn("Using legacy peer dependencies to update packages."),await D(...$,"--legacy-peer-deps")):await D(...$),t.info("Salty-CSS packages updated successfully!")}),p.option("-v, --version","Show the current version of Salty-CSS.").action(async function(){const i=await V();t.info("CLI is running: "+i.version);const o=n.join(process.cwd(),"package.json"),c=await I(o).catch(f=>h(f));if(!c)return;const u={...c.dependencies,...c.devDependencies},g=Object.keys(u).filter(f=>f==="salty-css"||f.startsWith("@salty-css/"));if(!g.length)return h("No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: "+o);for(const f of g)t.info(`${f}: ${u[f]}`)}),p.parseAsync(process.argv)}exports.main=pe;
10
+ `;S&&!d?(e=e.replace(/module.exports = ([^;]+)/,(O,J)=>`module.exports = withSaltyCss(${J})`),d=!0):d||(e=e.replace(/export default ([^;]+)/,(O,J)=>`export default withSaltyCss(${J})`)),u||await N(`-D ${I.next}`),t.logger.info("Adding Salty-CSS plugin to Next.js config..."),await s.writeFile(_,q+e),await P(_)}}const te=await D().catch(()=>t.logError("Could not read package.json file.")).then(e=>(e.scripts||(e.scripts={}),e.scripts.prepare?e.scripts.prepare.includes("salty-css")||(t.logger.info("Edit file: "+F),e.scripts.prepare=e.scripts.prepare+" && npx salty-css build"):(t.logger.info("Edit file: "+F),e.scripts.prepare="npx salty-css build"),e));await Z(te),t.logger.info("🎉 Salty CSS project initialized successfully!"),t.logger.info("Next steps:"),t.logger.info("1. Configure variables and templates in `salty.config.ts`"),t.logger.info("2. Create a new component with `npx salty-css generate [component-name]`"),t.logger.info("3. Run `npx salty-css build` to generate the CSS"),t.logger.info("4. Read about the features in the documentation: https://salty-css.dev"),t.logger.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐")}),g.command("build [directory]").alias("b").description("Build the Salty-CSS project.").option("-d, --dir <dir>","Project directory to build the project in.").action(async function(i=B){t.logger.info("Building the Salty-CSS project...");const{dir:a=i}=this.opts();if(!a)return t.logError("Project directory must be provided. Add it as the first argument after build command or use the --dir option.");const c=R(a);await t.generateCss(c)}),g.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>","File to generate.").option("-d, --dir <dir>","Project directory to generate the file in.").option("-t, --tag <tag>","HTML tag of the component.","div").option("-n, --name <name>","Name of the component.").option("-c, --className <className>","CSS class of the component.").option("-rc, --reactComponent <rc>","Generate a React component as well.").action(async function(i,a=B){const{file:c=i,dir:f=a,tag:u,name:p,className:l,reactComponent:b=!1}=this.opts();if(!c)return t.logError("File to generate must be provided. Add it as the first argument after generate command or use the --file option.");if(!f)return t.logError("Project directory must be provided. Add it as the second argument after generate command or use the --dir option.");const m=R(f),E=c.split("/").slice(0,-1).join("/");E&&await s.mkdir(n.join(m,E),{recursive:!0});const j=n.join(m,c),r=n.parse(j);r.ext||(r.ext=".ts"),r.name.endsWith(".css")||(r.name=r.name+".css"),r.base=r.name+r.ext;const w=n.format(r);if(await s.readFile(w,"utf-8").catch(()=>{})!==void 0){t.logger.error("File already exists:",w);return}let v=se.pascalCase(p||r.base.replace(/\.css\.\w+$/,""));if(b){const z=v+"Component";v=v+"Wrapper";const T=r.base.replace(/\.css\.\w+$/,""),{content:V}=await C("react/react-vanilla-file.ts",{tag:u,componentName:z,styledComponentName:v,className:l,fileName:T});r.name=T.replace(/\.css$/,""),r.ext=".tsx",r.base=r.name+r.ext;const $=n.format(r);t.logger.info("Generating a new file: "+$),await s.writeFile($,V),await P($)}const{content:H}=await C("react/react-styled-file.ts",{tag:u,name:v,className:l});t.logger.info("Generating a new file: "+w),await s.writeFile(w,H),await P(w)}),g.command("update [version]").alias("up").description("Update Salty-CSS packages to the latest or specified version.").option("-v, --version <version>","Version to update to.").option("--legacy-peer-deps <legacyPeerDeps>","Use legacy peer dependencies (not recommended).",!1).action(async function(i="latest"){const{legacyPeerDeps:a,version:c=i}=this.opts(),f=n.join(process.cwd(),"package.json"),u=await D(f).catch(m=>t.logError(m));if(!u)return;const p={...u.dependencies,...u.devDependencies},l=Object.keys(p).filter(m=>m==="salty-css"||m.startsWith("@salty-css/"));if(!l.length)return t.logError("No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: "+f);const b=l.map(m=>c==="@"?`${m}@${k.version}`:`${m}@${c.replace(/^@/,"")}`);a?(t.logger.warn("Using legacy peer dependencies to update packages."),await N(...b,"--legacy-peer-deps")):await N(...b),t.logger.info("Salty-CSS packages updated successfully!")}),g.option("-v, --version","Show the current version of Salty-CSS.").action(async function(){const i=await M();t.logger.info("CLI is running: "+i.version);const a=n.join(process.cwd(),"package.json"),c=await D(a).catch(p=>t.logError(p));if(!c)return;const f={...c.dependencies,...c.devDependencies},u=Object.keys(f).filter(p=>p==="salty-css"||p.startsWith("@salty-css/"));if(!u.length)return t.logError("No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: "+a);for(const p of u)t.logger.info(`${p}: ${f[p]}`)}),g.parseAsync(process.argv)}exports.main=ce;
package/bin/main.js CHANGED
@@ -1,38 +1,31 @@
1
- import { Command as rt } from "commander";
1
+ import { Command as ot } from "commander";
2
2
  import { existsSync as G } from "fs";
3
- import { mkdir as V, readFile as y, writeFile as h } from "fs/promises";
4
- import { join as a, relative as z, parse as ct, format as nt } from "path";
5
- import { render as lt } from "ejs";
6
- import { generateCss as dt } from "../compiler/index.js";
7
- import { p as pt } from "../pascal-case-BQpR5PdN.js";
8
- import { createLogger as ft, format as K, transports as gt } from "winston";
9
- import { exec as ut } from "child_process";
10
- import mt from "ora";
11
- const e = ft({
12
- level: "debug",
13
- format: K.combine(K.colorize(), K.cli()),
14
- transports: [new gt.Console({})]
15
- }), w = (d) => {
16
- e.error(d);
17
- }, st = (d) => new Promise((C, P) => {
18
- ut(d, (b) => {
19
- if (b) return P(b);
3
+ import { mkdir as V, readFile as m, writeFile as h } from "fs/promises";
4
+ import { join as a, relative as z, parse as rt, format as et } from "path";
5
+ import { render as ct } from "ejs";
6
+ import { l as e, a as w, g as lt } from "../index-BGaLvshf.js";
7
+ import { p as dt } from "../pascal-case-BQpR5PdN.js";
8
+ import { exec as pt } from "child_process";
9
+ import ft from "ora";
10
+ const nt = (d) => new Promise((C, P) => {
11
+ pt(d, (F) => {
12
+ if (F) return P(F);
20
13
  C();
21
14
  });
22
15
  }), I = async (...d) => {
23
- const C = d.map((F) => F.replace("-D", "").split("@").slice(0, -1).join("@").trim()).join(", "), P = mt(`Installing packages: ${C}`).start(), b = d.join(" ");
24
- await st(`npm install ${b}`), P.succeed(`Installed packages: ${C}`);
25
- }, yt = () => G(a(process.cwd(), "node_modules", ".bin", "prettier"));
16
+ const C = d.map((b) => b.replace("-D", "").split("@").slice(0, -1).join("@").trim()).join(", "), P = ft(`Installing packages: ${C}`).start(), F = d.join(" ");
17
+ await nt(`npm install ${F}`), P.succeed(`Installed packages: ${C}`);
18
+ }, gt = () => G(a(process.cwd(), "node_modules", ".bin", "prettier"));
26
19
  async function k(d) {
27
20
  try {
28
- if (!yt()) return;
29
- await st(`./node_modules/.bin/prettier --write "${d}"`), e.info(`Formatted ${d} with Prettier`);
21
+ if (!gt()) return;
22
+ await nt(`./node_modules/.bin/prettier --write "${d}"`), e.info(`Formatted ${d} with Prettier`);
30
23
  } catch (C) {
31
24
  e.error(`Error formatting ${d} with Prettier:`, C);
32
25
  }
33
26
  }
34
- async function Jt() {
35
- const d = new rt();
27
+ async function kt() {
28
+ const d = new ot();
36
29
  d.name("salty-css").description("Salty-CSS CLI tool to help with annoying configuration tasks.");
37
30
  const C = {
38
31
  // Core files
@@ -42,22 +35,22 @@ async function Jt() {
42
35
  "react/react-styled-file.ts": import("../react-styled-file-CGVf5n1B.js"),
43
36
  "react/react-vanilla-file.ts": import("../react-vanilla-file-CCXbsjIb.js")
44
37
  }, P = async (n, i) => {
45
- const { default: r } = await C[n], f = lt(r, i);
38
+ const { default: r } = await C[n], f = ct(r, i);
46
39
  return { fileName: n, content: f };
47
- }, b = async () => {
40
+ }, F = async () => {
48
41
  const n = a(process.cwd(), ".saltyrc");
49
- return await y(n, "utf-8").then(JSON.parse).catch(() => ({}));
50
- }, F = a(process.cwd(), "package.json"), A = async (n = F) => {
51
- const i = await y(n, "utf-8").then(JSON.parse).catch(() => {
42
+ return await m(n, "utf-8").then(JSON.parse).catch(() => ({}));
43
+ }, b = a(process.cwd(), "package.json"), A = async (n = b) => {
44
+ const i = await m(n, "utf-8").then(JSON.parse).catch(() => {
52
45
  });
53
46
  if (!i) throw "Could not read package.json file!";
54
47
  return i;
55
- }, at = async (n, i = F) => {
48
+ }, st = async (n, i = b) => {
56
49
  typeof n == "object" && (n = JSON.stringify(n, null, 2)), await h(i, n);
57
- }, Q = async () => {
50
+ }, K = async () => {
58
51
  const n = new URL("../package.json", import.meta.url);
59
52
  return A(n);
60
- }, X = await (async () => (await b()).defaultProject)(), $ = await Q(), O = {
53
+ }, Q = await (async () => (await F()).defaultProject)(), $ = await K(), O = {
61
54
  core: `@salty-css/core@${$.version}`,
62
55
  react: `@salty-css/react@${$.version}`,
63
56
  eslintConfigCore: `@salty-css/eslint-config-core@${$.version}`,
@@ -76,9 +69,9 @@ async function Jt() {
76
69
  g || await I(O.core, O.react);
77
70
  const p = process.cwd(), c = W(r), J = await Promise.all([P("salty.config.ts"), P("saltygen/index.css")]);
78
71
  await V(c, { recursive: !0 });
79
- const m = J.map(async ({ fileName: t, content: s }) => {
72
+ const y = J.map(async ({ fileName: t, content: s }) => {
80
73
  const l = a(c, t);
81
- if (await y(l, "utf-8").catch(() => {
74
+ if (await m(l, "utf-8").catch(() => {
82
75
  }) !== void 0) {
83
76
  e.debug("File already exists: " + l);
84
77
  return;
@@ -86,8 +79,8 @@ async function Jt() {
86
79
  const v = t.split("/").slice(0, -1).join("/");
87
80
  v && await V(a(c, v), { recursive: !0 }), e.info("Creating file: " + l), await h(l, s), await k(l);
88
81
  });
89
- await Promise.all(m);
90
- const N = z(p, c) || ".", j = a(p, ".saltyrc"), o = await y(j, "utf-8").catch(() => {
82
+ await Promise.all(y);
83
+ const N = z(p, c) || ".", j = a(p, ".saltyrc"), o = await m(j, "utf-8").catch(() => {
91
84
  });
92
85
  if (o === void 0) {
93
86
  e.info("Creating file: " + j);
@@ -103,7 +96,7 @@ async function Jt() {
103
96
  const l = JSON.stringify(t, null, 2);
104
97
  await h(j, l);
105
98
  }
106
- const S = a(p, ".gitignore"), T = await y(S, "utf-8").catch(() => {
99
+ const S = a(p, ".gitignore"), T = await m(S, "utf-8").catch(() => {
107
100
  });
108
101
  T !== void 0 && (T.includes("saltygen") || (e.info("Edit file: " + S), await h(S, T + `
109
102
 
@@ -116,17 +109,17 @@ saltygen
116
109
  for (const s of q)
117
110
  for (const l of U) {
118
111
  const u = a(c, t, s + l);
119
- if (await y(u, "utf-8").catch(() => {
112
+ if (await m(u, "utf-8").catch(() => {
120
113
  }) !== void 0) return z(c, u);
121
114
  for (const H of M) {
122
115
  const L = a(c, t, H, s + l);
123
- if (await y(L, "utf-8").catch(() => {
116
+ if (await m(L, "utf-8").catch(() => {
124
117
  }) !== void 0) return z(c, L);
125
118
  }
126
119
  }
127
120
  })();
128
121
  if (E) {
129
- const t = a(c, E), s = await y(t, "utf-8").catch(() => {
122
+ const t = a(c, E), s = await m(t, "utf-8").catch(() => {
130
123
  });
131
124
  if (s !== void 0 && !s.includes("saltygen")) {
132
125
  const u = a(t, ".."), H = `@import '${z(u, a(c, "saltygen/index.css"))}';`;
@@ -135,10 +128,10 @@ saltygen
135
128
  }
136
129
  } else
137
130
  e.warn("Could not find a CSS file to import the generated CSS. Please add it manually.");
138
- const Z = a(p, ".eslintrc.json"), it = G(Z), tt = a(c, ".eslintrc.json"), et = G(tt);
139
- if (it || et) {
131
+ const Y = a(p, ".eslintrc.json"), at = G(Y), Z = a(c, ".eslintrc.json"), tt = G(Z);
132
+ if (at || tt) {
140
133
  g || await I(O.eslintConfigCore);
141
- const t = et ? tt : Z, s = await y(t, "utf-8").catch(() => {
134
+ const t = tt ? Z : Y, s = await m(t, "utf-8").catch(() => {
142
135
  });
143
136
  if (!s) return w("Could not read ESLint config file.");
144
137
  if (!s.includes("salty-css")) {
@@ -148,7 +141,7 @@ saltygen
148
141
  await h(t, v), await k(t);
149
142
  }
150
143
  }
151
- const R = a(c, "vite.config.ts"), B = await y(R, "utf-8").catch(() => {
144
+ const R = a(c, "vite.config.ts"), B = await m(R, "utf-8").catch(() => {
152
145
  });
153
146
  if (B !== void 0 && !B.includes("saltyPlugin")) {
154
147
  e.info("Edit file: " + R);
@@ -159,7 +152,7 @@ saltygen
159
152
  }
160
153
  const _ = ["next.config.js", "next.config.cjs", "next.config.ts", "next.config.mjs"].map((t) => a(c, t)).find((t) => G(t));
161
154
  if (_) {
162
- let t = await y(_, "utf-8").catch(() => {
155
+ let t = await m(_, "utf-8").catch(() => {
163
156
  });
164
157
  if (t !== void 0 && !t.includes("withSaltyCss")) {
165
158
  let l = !1;
@@ -170,51 +163,51 @@ saltygen
170
163
  v && !l ? (t = t.replace(/module.exports = ([^;]+)/, (L, D) => `module.exports = withSaltyCss(${D})`), l = !0) : l || (t = t.replace(/export default ([^;]+)/, (L, D) => `export default withSaltyCss(${D})`)), g || await I(`-D ${O.next}`), e.info("Adding Salty-CSS plugin to Next.js config..."), await h(_, H + t), await k(_);
171
164
  }
172
165
  }
173
- const ot = await A().catch(() => w("Could not read package.json file.")).then((t) => (t.scripts || (t.scripts = {}), t.scripts.prepare ? t.scripts.prepare.includes("salty-css") || (e.info("Edit file: " + F), t.scripts.prepare = t.scripts.prepare + " && npx salty-css build") : (e.info("Edit file: " + F), t.scripts.prepare = "npx salty-css build"), t));
174
- await at(ot), e.info("🎉 Salty CSS project initialized successfully!"), e.info("Next steps:"), e.info("1. Configure variables and templates in `salty.config.ts`"), e.info("2. Create a new component with `npx salty-css generate [component-name]`"), e.info("3. Run `npx salty-css build` to generate the CSS"), e.info("4. Read about the features in the documentation: https://salty-css.dev"), e.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐");
175
- }), d.command("build [directory]").alias("b").description("Build the Salty-CSS project.").option("-d, --dir <dir>", "Project directory to build the project in.").action(async function(n = X) {
166
+ const it = await A().catch(() => w("Could not read package.json file.")).then((t) => (t.scripts || (t.scripts = {}), t.scripts.prepare ? t.scripts.prepare.includes("salty-css") || (e.info("Edit file: " + b), t.scripts.prepare = t.scripts.prepare + " && npx salty-css build") : (e.info("Edit file: " + b), t.scripts.prepare = "npx salty-css build"), t));
167
+ await st(it), e.info("🎉 Salty CSS project initialized successfully!"), e.info("Next steps:"), e.info("1. Configure variables and templates in `salty.config.ts`"), e.info("2. Create a new component with `npx salty-css generate [component-name]`"), e.info("3. Run `npx salty-css build` to generate the CSS"), e.info("4. Read about the features in the documentation: https://salty-css.dev"), e.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐");
168
+ }), d.command("build [directory]").alias("b").description("Build the Salty-CSS project.").option("-d, --dir <dir>", "Project directory to build the project in.").action(async function(n = Q) {
176
169
  e.info("Building the Salty-CSS project...");
177
170
  const { dir: i = n } = this.opts();
178
171
  if (!i) return w("Project directory must be provided. Add it as the first argument after build command or use the --dir option.");
179
172
  const r = W(i);
180
- await dt(r);
181
- }), d.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>", "File to generate.").option("-d, --dir <dir>", "Project directory to generate the file in.").option("-t, --tag <tag>", "HTML tag of the component.", "div").option("-n, --name <name>", "Name of the component.").option("-c, --className <className>", "CSS class of the component.").option("-rc, --reactComponent <rc>", "Generate a React component as well.").action(async function(n, i = X) {
173
+ await lt(r);
174
+ }), d.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>", "File to generate.").option("-d, --dir <dir>", "Project directory to generate the file in.").option("-t, --tag <tag>", "HTML tag of the component.", "div").option("-n, --name <name>", "Name of the component.").option("-c, --className <className>", "CSS class of the component.").option("-rc, --reactComponent <rc>", "Generate a React component as well.").action(async function(n, i = Q) {
182
175
  const { file: r = n, dir: f = i, tag: g, name: p, className: c, reactComponent: J = !1 } = this.opts();
183
176
  if (!r) return w("File to generate must be provided. Add it as the first argument after generate command or use the --file option.");
184
177
  if (!f) return w("Project directory must be provided. Add it as the second argument after generate command or use the --dir option.");
185
- const m = W(f), N = r.split("/").slice(0, -1).join("/");
186
- N && await V(a(m, N), { recursive: !0 });
187
- const j = a(m, r), o = ct(j);
178
+ const y = W(f), N = r.split("/").slice(0, -1).join("/");
179
+ N && await V(a(y, N), { recursive: !0 });
180
+ const j = a(y, r), o = rt(j);
188
181
  o.ext || (o.ext = ".ts"), o.name.endsWith(".css") || (o.name = o.name + ".css"), o.base = o.name + o.ext;
189
- const S = nt(o);
190
- if (await y(S, "utf-8").catch(() => {
182
+ const S = et(o);
183
+ if (await m(S, "utf-8").catch(() => {
191
184
  }) !== void 0) {
192
185
  e.error("File already exists:", S);
193
186
  return;
194
187
  }
195
- let x = pt(p || o.base.replace(/\.css\.\w+$/, ""));
188
+ let x = dt(p || o.base.replace(/\.css\.\w+$/, ""));
196
189
  if (J) {
197
190
  const q = x + "Component";
198
191
  x = x + "Wrapper";
199
- const U = o.base.replace(/\.css\.\w+$/, ""), { content: Y } = await P("react/react-vanilla-file.ts", { tag: g, componentName: q, styledComponentName: x, className: c, fileName: U });
192
+ const U = o.base.replace(/\.css\.\w+$/, ""), { content: X } = await P("react/react-vanilla-file.ts", { tag: g, componentName: q, styledComponentName: x, className: c, fileName: U });
200
193
  o.name = U.replace(/\.css$/, ""), o.ext = ".tsx", o.base = o.name + o.ext;
201
- const E = nt(o);
202
- e.info("Generating a new file: " + E), await h(E, Y), await k(E);
194
+ const E = et(o);
195
+ e.info("Generating a new file: " + E), await h(E, X), await k(E);
203
196
  }
204
197
  const { content: M } = await P("react/react-styled-file.ts", { tag: g, name: x, className: c });
205
198
  e.info("Generating a new file: " + S), await h(S, M), await k(S);
206
199
  }), d.command("update [version]").alias("up").description("Update Salty-CSS packages to the latest or specified version.").option("-v, --version <version>", "Version to update to.").option("--legacy-peer-deps <legacyPeerDeps>", "Use legacy peer dependencies (not recommended).", !1).action(async function(n = "latest") {
207
- const { legacyPeerDeps: i, version: r = n } = this.opts(), f = a(process.cwd(), "package.json"), g = await A(f).catch((m) => w(m));
200
+ const { legacyPeerDeps: i, version: r = n } = this.opts(), f = a(process.cwd(), "package.json"), g = await A(f).catch((y) => w(y));
208
201
  if (!g) return;
209
- const p = { ...g.dependencies, ...g.devDependencies }, c = Object.keys(p).filter((m) => m === "salty-css" || m.startsWith("@salty-css/"));
202
+ const p = { ...g.dependencies, ...g.devDependencies }, c = Object.keys(p).filter((y) => y === "salty-css" || y.startsWith("@salty-css/"));
210
203
  if (!c.length)
211
204
  return w(
212
205
  "No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: " + f
213
206
  );
214
- const J = c.map((m) => r === "@" ? `${m}@${$.version}` : `${m}@${r.replace(/^@/, "")}`);
207
+ const J = c.map((y) => r === "@" ? `${y}@${$.version}` : `${y}@${r.replace(/^@/, "")}`);
215
208
  i ? (e.warn("Using legacy peer dependencies to update packages."), await I(...J, "--legacy-peer-deps")) : await I(...J), e.info("Salty-CSS packages updated successfully!");
216
209
  }), d.option("-v, --version", "Show the current version of Salty-CSS.").action(async function() {
217
- const n = await Q();
210
+ const n = await K();
218
211
  e.info("CLI is running: " + n.version);
219
212
  const i = a(process.cwd(), "package.json"), r = await A(i).catch((p) => w(p));
220
213
  if (!r) return;
@@ -228,5 +221,5 @@ saltygen
228
221
  }), d.parseAsync(process.argv);
229
222
  }
230
223
  export {
231
- Jt as main
224
+ kt as main
232
225
  };
@@ -1,11 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Y=require("esbuild"),Z=require("child_process"),N=require("../dash-case-DKzpenwY.cjs"),o=require("path"),a=require("fs"),I=require("fs/promises"),R=require("../parse-templates-DVK3iZIl.cjs");var V=typeof document<"u"?document.currentScript:null;function Q(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const z=Q(Y),B=t=>{if(!t||t==="/")throw new Error("Could not find package.json file");const e=o.join(t,"package.json");return a.existsSync(e)?e:B(o.join(t,".."))},tt=async t=>{const e=B(t);return await I.readFile(e,"utf-8").then(JSON.parse).catch(()=>{})},et=async t=>{const e=await tt(t);if(e)return e.type};let D;const H=async t=>{if(D)return D;const e=await et(t);return e==="module"?D="esm":(e==="commonjs"||(typeof document>"u"?require("url").pathToFileURL(__filename).href:V&&V.tagName.toUpperCase()==="SCRIPT"&&V.src||new URL("compiler/index.cjs",document.baseURI).href).endsWith(".cjs"))&&(D="cjs"),D||"esm"},_={externalModules:[]},U=t=>{if(_.externalModules.length>0)return _.externalModules;const e=o.join(t,"salty.config.ts"),s=a.readFileSync(e,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!s)return[];const l=s[1].split(",").map(w=>w.replace(/['"`]/g,"").trim());return _.externalModules=l,l},v=t=>o.join(t,"./saltygen"),W=["salty","css","styles","styled"],K=(t=[])=>new RegExp(`\\.(${[...W,...t].join("|")})\\.`),E=(t,e=[])=>K(e).test(t),st=async t=>{const e=v(t),n=o.join(t,"salty.config.ts"),s=o.join(e,"salty.config.js"),l=await H(t),w=U(t);await z.build({entryPoints:[n],minify:!0,treeShaking:!0,bundle:!0,outfile:s,format:l,external:w});const f=Date.now(),{config:g}=await import(`${s}?t=${f}`);return g},L=async t=>{const e=await st(t),n=new Set,s=(r,u=[])=>r?Object.entries(r).flatMap(([d,p])=>{if(!p)return;if(typeof p=="object")return s(p,[...u,d]);const x=[...u,d].join(".");n.add(`"${x}"`);const h=[...u.map(N.dashCase),N.dashCase(d)].join("-"),{result:j}=R.parseValueTokens(p);return`--${h}: ${j};`}):[],l=r=>r?Object.entries(r).flatMap(([u,d])=>{const p=s(d);return u==="base"?p.join(""):`${u} { ${p.join("")} }`}):[],w=r=>r?Object.entries(r).flatMap(([u,d])=>Object.entries(d).flatMap(([p,x])=>{const h=s(x,[u]),j=`.${u}-${p}, [data-${u}="${p}"]`,P=h.join("");return`${j} { ${P} }`})):[],f=s(e.variables),g=l(e.responsiveVariables),i=w(e.conditionalVariables),$=v(t),S=o.join($,"css/variables.css"),k=`:root { ${f.join("")} ${g.join("")} } ${i.join("")}`;a.writeFileSync(S,k);const m=o.join($,"types/css-tokens.d.ts"),y=`type VariableTokens = ${[...n].join("|")||'""'}; type PropertyValueToken = \`{\${VariableTokens}}\``;a.writeFileSync(m,y);const C=o.join($,"css/global.css"),F=R.parseStyles(e.global,"");a.writeFileSync(C,F);const b=o.join($,"css/templates.css"),T=R.parseTemplates(e.templates);a.writeFileSync(b,T)},O=async(t,e,n)=>{const s=N.toHash(e),l=o.join(n,"js",s+".js"),w=await H(t),f=U(t);await z.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:l,format:w,target:["es2022"],keepNames:!0,external:f});const g=Date.now();return await import(`${l}?t=${g}`)},J=async t=>{const e=v(t),n=o.join(e,"salty.config.js"),{config:s}=await import(n);return s},nt=async t=>{try{const e=[],n=[],s=v(t),l=o.join(s,"index.css");(()=>{a.existsSync(s)&&Z.execSync("rm -rf "+s),a.mkdirSync(s),a.mkdirSync(o.join(s,"css")),a.mkdirSync(o.join(s,"types"))})(),await L(t);const f=await J(t);async function g(c,y){const C=["node_modules","saltygen"],F=a.statSync(c);if(F.isDirectory()){const b=a.readdirSync(c);if(C.some(r=>c.includes(r)))return;await Promise.all(b.map(r=>g(o.join(c,r),o.join(y,r))))}else if(F.isFile()&&E(c)){const T=await O(t,c,s),r=[];Object.entries(T).forEach(([x,h])=>{if(h.isKeyframes&&h.css){const q=`${h.animationName}.css`,A=`css/${q}`,X=o.join(s,A);e.push(q),a.writeFileSync(X,h.css);return}if(!h.generator)return;const j=h.generator._withBuildContext({name:x,config:f}),P=`${j.hash}-${j.priority}.css`;n[j.priority]||(n[j.priority]=[]),n[j.priority].push(P),r.push(P);const M=`css/${P}`,G=o.join(s,M);a.writeFileSync(G,j.css)});const u=r.map(x=>`@import url('./${x}');`).join(`
2
- `),d=N.toHash(c,6),p=o.join(s,`css/${d}.css`);a.writeFileSync(p,u)}}await g(t,s);const i=e.map(c=>`@import url('./css/${c}');`).join(`
3
- `);let m=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
4
-
5
- ${["variables.css","global.css","templates.css"].filter(c=>{try{return a.readFileSync(o.join(s,"css",c),"utf8").length>0}catch{return!1}}).map(c=>`@import url('./css/${c}');`).join(`
6
- `)}
7
- ${i}`;if(f.importStrategy!=="component"){const c=n.flat().map(y=>`@import url('./css/${y}');`).join(`
8
- `);m+=c}a.writeFileSync(l,m)}catch(e){console.error(e)}},ot=async(t,e)=>{try{const n=[],s=o.join(t,"./saltygen"),l=o.join(s,"index.css");if(E(e)){const f=await J(t),g=await O(t,e,s);Object.entries(g).forEach(([m,c])=>{if(!c.generator)return;const y=c.generator._withBuildContext({name:m,config:f}),C=`${y.hash}-${y.priority}.css`,F=`css/${C}`,b=o.join(s,F);n.push(C),a.writeFileSync(b,y.css)});const i=a.readFileSync(l,"utf8").split(`
9
- `),$=n.map(m=>`@import url('../saltygen/css/${m}');`),k=[...new Set([...i,...$])].join(`
10
- `);a.writeFileSync(l,k)}}catch(n){console.error(n)}},it=async(t,e)=>{try{const n=o.join(t,"./saltygen");if(E(e)){const l=a.readFileSync(e,"utf8");l.replace(/^(?!export\s)const\s.*/gm,S=>`export ${S}`)!==l&&await I.writeFile(e,l);const f=await J(t),g=await O(t,e,n);let i=l;Object.entries(g).forEach(([S,k])=>{var P;if(k.isKeyframes||!k.generator)return;const m=k.generator._withBuildContext({name:S,config:f}),c=new RegExp(`\\s${S}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(l);if(!c)return console.error("Could not find the original declaration");const y=(P=c.at(1))==null?void 0:P.trim(),C=new RegExp(`\\s${S}[=\\s]+styled\\(`,"g").exec(i);if(!C)return console.error("Could not find the original declaration");const{index:F}=C;let b=!1;const T=setTimeout(()=>b=!0,5e3);let r=0,u=!1,d=0;for(;!u&&!b;){const M=i[F+r];M==="("&&d++,M===")"&&d--,d===0&&M===")"&&(u=!0),r>i.length&&(b=!0),r++}if(!b)clearTimeout(T);else throw new Error("Failed to find the end of the styled call and timed out");const p=F+r,x=i.slice(F,p),h=i,j=` ${S} = styled(${y}, "${m.classNames}", "${m._callerName}", ${JSON.stringify(m.props)});`;i=i.replace(x,j),h===i&&console.error("Minimize file failed to change content",{name:S,tagName:y})});const $=N.toHash(e,6);return f.importStrategy==="component"&&(i=`import '../../saltygen/css/${$}.css';
11
- ${i}`),i=i.replace("{ styled }","{ styledClient as styled }"),i=i.replace("@salty-css/react/styled","@salty-css/react/styled-client"),i}}catch(n){console.error("Error in minimizeFile:",n)}};exports.compileSaltyFile=O;exports.generateConfigStyles=L;exports.generateCss=nt;exports.generateFile=ot;exports.isSaltyFile=E;exports.minimizeFile=it;exports.saltyFileExtensions=W;exports.saltyFileRegExp=K;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("esbuild");require("child_process");require("../dash-case-DKzpenwY.cjs");require("path");require("fs");require("fs/promises");require("../parse-templates-DVK3iZIl.cjs");const e=require("../index-BKoD9apd.cjs");exports.compileSaltyFile=e.compileSaltyFile;exports.generateConfigStyles=e.generateConfigStyles;exports.generateCss=e.generateCss;exports.generateFile=e.generateFile;exports.isSaltyFile=e.isSaltyFile;exports.minimizeFile=e.minimizeFile;exports.saltyFileExtensions=e.saltyFileExtensions;exports.saltyFileRegExp=e.saltyFileRegExp;
@@ -11,6 +11,6 @@ export declare const compileSaltyFile: (dirname: string, sourceFilePath: string,
11
11
  css?: string;
12
12
  };
13
13
  }>;
14
- export declare const generateCss: (dirname: string) => Promise<void>;
14
+ export declare const generateCss: (dirname: string, prod?: boolean) => Promise<void>;
15
15
  export declare const generateFile: (dirname: string, file: string) => Promise<void>;
16
- export declare const minimizeFile: (dirname: string, file: string) => Promise<string | undefined>;
16
+ export declare const minimizeFile: (dirname: string, file: string, prod?: boolean) => Promise<string | undefined>;
package/compiler/index.js CHANGED
@@ -1,214 +1,18 @@
1
- import * as z from "esbuild";
2
- import { execSync as U } from "child_process";
3
- import { t as J, d as _ } from "../dash-case-DMQMcCO6.js";
4
- import { join as n } from "path";
5
- import { existsSync as W, writeFileSync as j, mkdirSync as v, statSync as X, readdirSync as Y, readFileSync as N } from "fs";
6
- import { readFile as Z, writeFile as Q } from "fs/promises";
7
- import { p as tt, a as st, b as et } from "../parse-templates-DUUSaubj.js";
8
- const H = (t) => {
9
- if (!t || t === "/") throw new Error("Could not find package.json file");
10
- const s = n(t, "package.json");
11
- return W(s) ? s : H(n(t, ".."));
12
- }, nt = async (t) => {
13
- const s = H(t);
14
- return await Z(s, "utf-8").then(JSON.parse).catch(() => {
15
- });
16
- }, ot = async (t) => {
17
- const s = await nt(t);
18
- if (s)
19
- return s.type;
20
- };
21
- let M;
22
- const K = async (t) => {
23
- if (M) return M;
24
- const s = await ot(t);
25
- return s === "module" ? M = "esm" : (s === "commonjs" || import.meta.url.endsWith(".cjs")) && (M = "cjs"), M || "esm";
26
- }, V = {
27
- externalModules: []
28
- }, G = (t) => {
29
- if (V.externalModules.length > 0) return V.externalModules;
30
- const s = n(t, "salty.config.ts"), e = N(s, "utf8").match(/externalModules:\s?\[(.*)\]/);
31
- if (!e) return [];
32
- const i = e[1].split(",").map((w) => w.replace(/['"`]/g, "").trim());
33
- return V.externalModules = i, i;
34
- }, E = (t) => n(t, "./saltygen"), ct = ["salty", "css", "styles", "styled"], rt = (t = []) => new RegExp(`\\.(${[...ct, ...t].join("|")})\\.`), O = (t, s = []) => rt(s).test(t), at = async (t) => {
35
- const s = E(t), o = n(t, "salty.config.ts"), e = n(s, "salty.config.js"), i = await K(t), w = G(t);
36
- await z.build({
37
- entryPoints: [o],
38
- minify: !0,
39
- treeShaking: !0,
40
- bundle: !0,
41
- outfile: e,
42
- format: i,
43
- external: w
44
- });
45
- const f = Date.now(), { config: y } = await import(`${e}?t=${f}`);
46
- return y;
47
- }, it = async (t) => {
48
- const s = await at(t), o = /* @__PURE__ */ new Set(), e = (a, l = []) => a ? Object.entries(a).flatMap(([g, p]) => {
49
- if (!p) return;
50
- if (typeof p == "object") return e(p, [...l, g]);
51
- const C = [...l, g].join(".");
52
- o.add(`"${C}"`);
53
- const m = [...l.map(_), _(g)].join("-"), { result: h } = et(p);
54
- return `--${m}: ${h};`;
55
- }) : [], i = (a) => a ? Object.entries(a).flatMap(([l, g]) => {
56
- const p = e(g);
57
- return l === "base" ? p.join("") : `${l} { ${p.join("")} }`;
58
- }) : [], w = (a) => a ? Object.entries(a).flatMap(([l, g]) => Object.entries(g).flatMap(([p, C]) => {
59
- const m = e(C, [l]), h = `.${l}-${p}, [data-${l}="${p}"]`, P = m.join("");
60
- return `${h} { ${P} }`;
61
- })) : [], f = e(s.variables), y = i(s.responsiveVariables), c = w(s.conditionalVariables), x = E(t), $ = n(x, "css/variables.css"), k = `:root { ${f.join("")} ${y.join("")} } ${c.join("")}`;
62
- j($, k);
63
- const d = n(x, "types/css-tokens.d.ts"), u = `type VariableTokens = ${[...o].join("|") || '""'}; type PropertyValueToken = \`{\${VariableTokens}}\``;
64
- j(d, u);
65
- const S = n(x, "css/global.css"), F = tt(s.global, "");
66
- j(S, F);
67
- const b = n(x, "css/templates.css"), D = st(s.templates);
68
- j(b, D);
69
- }, R = async (t, s, o) => {
70
- const e = J(s), i = n(o, "js", e + ".js"), w = await K(t), f = G(t);
71
- await z.build({
72
- entryPoints: [s],
73
- minify: !0,
74
- treeShaking: !0,
75
- bundle: !0,
76
- outfile: i,
77
- format: w,
78
- target: ["es2022"],
79
- keepNames: !0,
80
- external: f
81
- });
82
- const y = Date.now();
83
- return await import(`${i}?t=${y}`);
84
- }, B = async (t) => {
85
- const s = E(t), o = n(s, "salty.config.js"), { config: e } = await import(o);
86
- return e;
87
- }, dt = async (t) => {
88
- try {
89
- const s = [], o = [], e = E(t), i = n(e, "index.css");
90
- (() => {
91
- W(e) && U("rm -rf " + e), v(e), v(n(e, "css")), v(n(e, "types"));
92
- })(), await it(t);
93
- const f = await B(t);
94
- async function y(r, u) {
95
- const S = ["node_modules", "saltygen"], F = X(r);
96
- if (F.isDirectory()) {
97
- const b = Y(r);
98
- if (S.some((a) => r.includes(a))) return;
99
- await Promise.all(b.map((a) => y(n(r, a), n(u, a))));
100
- } else if (F.isFile() && O(r)) {
101
- const D = await R(t, r, e), a = [];
102
- Object.entries(D).forEach(([C, m]) => {
103
- if (m.isKeyframes && m.css) {
104
- const I = `${m.animationName}.css`, A = `css/${I}`, L = n(e, A);
105
- s.push(I), j(L, m.css);
106
- return;
107
- }
108
- if (!m.generator) return;
109
- const h = m.generator._withBuildContext({
110
- name: C,
111
- config: f
112
- }), P = `${h.hash}-${h.priority}.css`;
113
- o[h.priority] || (o[h.priority] = []), o[h.priority].push(P), a.push(P);
114
- const T = `css/${P}`, q = n(e, T);
115
- j(q, h.css);
116
- });
117
- const l = a.map((C) => `@import url('./${C}');`).join(`
118
- `), g = J(r, 6), p = n(e, `css/${g}.css`);
119
- j(p, l);
120
- }
121
- }
122
- await y(t, e);
123
- const c = s.map((r) => `@import url('./css/${r}');`).join(`
124
- `);
125
- let d = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
126
-
127
- ${["variables.css", "global.css", "templates.css"].filter((r) => {
128
- try {
129
- return N(n(e, "css", r), "utf8").length > 0;
130
- } catch {
131
- return !1;
132
- }
133
- }).map((r) => `@import url('./css/${r}');`).join(`
134
- `)}
135
- ${c}`;
136
- if (f.importStrategy !== "component") {
137
- const r = o.flat().map((u) => `@import url('./css/${u}');`).join(`
138
- `);
139
- d += r;
140
- }
141
- j(i, d);
142
- } catch (s) {
143
- console.error(s);
144
- }
145
- }, mt = async (t, s) => {
146
- try {
147
- const o = [], e = n(t, "./saltygen"), i = n(e, "index.css");
148
- if (O(s)) {
149
- const f = await B(t), y = await R(t, s, e);
150
- Object.entries(y).forEach(([d, r]) => {
151
- if (!r.generator) return;
152
- const u = r.generator._withBuildContext({
153
- name: d,
154
- config: f
155
- }), S = `${u.hash}-${u.priority}.css`, F = `css/${S}`, b = n(e, F);
156
- o.push(S), j(b, u.css);
157
- });
158
- const c = N(i, "utf8").split(`
159
- `), x = o.map((d) => `@import url('../saltygen/css/${d}');`), k = [.../* @__PURE__ */ new Set([...c, ...x])].join(`
160
- `);
161
- j(i, k);
162
- }
163
- } catch (o) {
164
- console.error(o);
165
- }
166
- }, ht = async (t, s) => {
167
- try {
168
- const o = n(t, "./saltygen");
169
- if (O(s)) {
170
- const i = N(s, "utf8");
171
- i.replace(/^(?!export\s)const\s.*/gm, ($) => `export ${$}`) !== i && await Q(s, i);
172
- const f = await B(t), y = await R(t, s, o);
173
- let c = i;
174
- Object.entries(y).forEach(([$, k]) => {
175
- var P;
176
- if (k.isKeyframes || !k.generator) return;
177
- const d = k.generator._withBuildContext({
178
- name: $,
179
- config: f
180
- }), r = new RegExp(`\\s${$}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(i);
181
- if (!r) return console.error("Could not find the original declaration");
182
- const u = (P = r.at(1)) == null ? void 0 : P.trim(), S = new RegExp(`\\s${$}[=\\s]+styled\\(`, "g").exec(c);
183
- if (!S) return console.error("Could not find the original declaration");
184
- const { index: F } = S;
185
- let b = !1;
186
- const D = setTimeout(() => b = !0, 5e3);
187
- let a = 0, l = !1, g = 0;
188
- for (; !l && !b; ) {
189
- const T = c[F + a];
190
- T === "(" && g++, T === ")" && g--, g === 0 && T === ")" && (l = !0), a > c.length && (b = !0), a++;
191
- }
192
- if (!b) clearTimeout(D);
193
- else throw new Error("Failed to find the end of the styled call and timed out");
194
- const p = F + a, C = c.slice(F, p), m = c, h = ` ${$} = styled(${u}, "${d.classNames}", "${d._callerName}", ${JSON.stringify(d.props)});`;
195
- c = c.replace(C, h), m === c && console.error("Minimize file failed to change content", { name: $, tagName: u });
196
- });
197
- const x = J(s, 6);
198
- return f.importStrategy === "component" && (c = `import '../../saltygen/css/${x}.css';
199
- ${c}`), c = c.replace("{ styled }", "{ styledClient as styled }"), c = c.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), c;
200
- }
201
- } catch (o) {
202
- console.error("Error in minimizeFile:", o);
203
- }
204
- };
1
+ import "esbuild";
2
+ import "child_process";
3
+ import "../dash-case-DMQMcCO6.js";
4
+ import "path";
5
+ import "fs";
6
+ import "fs/promises";
7
+ import "../parse-templates-DUUSaubj.js";
8
+ import { d as p, c as n, g, e as F, i as y, m as x, s as S, b as c } from "../index-BGaLvshf.js";
205
9
  export {
206
- R as compileSaltyFile,
207
- it as generateConfigStyles,
208
- dt as generateCss,
209
- mt as generateFile,
210
- O as isSaltyFile,
211
- ht as minimizeFile,
212
- ct as saltyFileExtensions,
213
- rt as saltyFileRegExp
10
+ p as compileSaltyFile,
11
+ n as generateConfigStyles,
12
+ g as generateCss,
13
+ F as generateFile,
14
+ y as isSaltyFile,
15
+ x as minimizeFile,
16
+ S as saltyFileExtensions,
17
+ c as saltyFileRegExp
214
18
  };
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var l=(a,t,s)=>t in a?m(a,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[t]=s;var c=(a,t,s)=>l(a,typeof t!="symbol"?t+"":t,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../dash-case-DKzpenwY.cjs"),p=require("../parse-templates-DVK3iZIl.cjs");class g{constructor(t,s){c(this,"_callerName");c(this,"_context");this.tagName=t,this.params=s}get hash(){return u.toHash(this.params.base||this.params)}get priority(){var t;return typeof this.tagName=="function"||typeof this.tagName=="object"?(((t=this.tagName.generator)==null?void 0:t.priority)||0)+1:0}get classNames(){const t=[this.hash],{className:s}=this.params;return s&&t.push(s),t.join(" ")}get cssClassName(){return this.hash}get cssDisplayNameVar(){return`--${this.hash}-display-name: ${this._callerName};`}get templateKeys(){var t;return(t=this._context)!=null&&t.config.templates?p.getTemplateKeys(this._context.config.templates):[]}get css(){var e;const{base:t={},variants:s={},compoundVariants:r=[]}=this.params,i={...t,variants:s,compoundVariants:r};return p.parseStyles(i,`.${this.cssClassName}`,this.priority,(e=this._context)==null?void 0:e.config)}get props(){const{element:t}=this.params,s=this.params.variants?Object.keys(this.params.variants).map(e=>{var n;const o=(n=this.params.defaultVariants)==null?void 0:n[e];return o!==void 0?`${e}=${String(o)}`:e}):void 0,r=new Set([]),i=/\{props\.([\w\d]+)\}/gi.exec(JSON.stringify(this.params.base));return i&&i.forEach((e,o,n)=>{const h=n.at(1);h&&r.add(h)}),{element:t,variantKeys:s,propValueKeys:[...r]}}_withBuildContext(t){this._context=t;const{name:s,config:r}=t;return this._callerName=s,this}}exports.StyleComponentGenerator=g;
1
+ "use strict";var m=Object.defineProperty;var l=(a,t,s)=>t in a?m(a,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):a[t]=s;var o=(a,t,s)=>l(a,typeof t!="symbol"?t+"":t,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../dash-case-DKzpenwY.cjs"),p=require("../parse-templates-DVK3iZIl.cjs");class g{constructor(t,s){o(this,"_isProd");o(this,"_callerName");o(this,"_context");this.tagName=t,this.params=s}get hash(){return u.toHash(this.params.base||this.params)}get priority(){var t;return typeof this.tagName=="function"||typeof this.tagName=="object"?(((t=this.tagName.generator)==null?void 0:t.priority)||0)+1:0}get classNames(){const t=[this.hash],{className:s}=this.params;return s&&t.push(s),t.join(" ")}get cssClassName(){return this.hash}get cssDisplayNameVar(){return`--${this.hash}-display-name: ${this._callerName};`}get templateKeys(){var t;return(t=this._context)!=null&&t.config.templates?p.getTemplateKeys(this._context.config.templates):[]}get css(){var e;const{base:t={},variants:s={},compoundVariants:i=[]}=this.params,r={...t,variants:s,compoundVariants:i};return p.parseStyles(r,`.${this.cssClassName}`,this.priority,(e=this._context)==null?void 0:e.config)}get props(){const{element:t}=this.params,s=this.params.variants?Object.keys(this.params.variants).map(e=>{var n;const c=(n=this.params.defaultVariants)==null?void 0:n[e];return c!==void 0?`${e}=${String(c)}`:e}):void 0,i=new Set([]),r=/\{props\.([\w\d]+)\}/gi.exec(JSON.stringify(this.params.base));return r&&r.forEach((e,c,n)=>{const h=n.at(1);h&&i.add(h)}),{element:t,variantKeys:s,propValueKeys:[...i],attr:{"data-component-name":this._isProd?void 0:this._callerName}}}_withBuildContext(t){this._context=t;const{name:s,config:i,prod:r}=t;return this._isProd=r,this._callerName=s,this}}exports.StyleComponentGenerator=g;
@@ -1,12 +1,13 @@
1
- var h = Object.defineProperty;
2
- var m = (e, t, s) => t in e ? h(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
- var c = (e, t, s) => m(e, typeof t != "symbol" ? t + "" : t, s);
1
+ var p = Object.defineProperty;
2
+ var m = (e, t, s) => t in e ? p(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
+ var n = (e, t, s) => m(e, typeof t != "symbol" ? t + "" : t, s);
4
4
  import { t as l } from "../dash-case-DMQMcCO6.js";
5
5
  import { g, p as u } from "../parse-templates-DUUSaubj.js";
6
- class d {
6
+ class N {
7
7
  constructor(t, s) {
8
- c(this, "_callerName");
9
- c(this, "_context");
8
+ n(this, "_isProd");
9
+ n(this, "_callerName");
10
+ n(this, "_context");
10
11
  this.tagName = t, this.params = s;
11
12
  }
12
13
  get hash() {
@@ -32,30 +33,33 @@ class d {
32
33
  }
33
34
  get css() {
34
35
  var a;
35
- const { base: t = {}, variants: s = {}, compoundVariants: r = [] } = this.params, i = { ...t, variants: s, compoundVariants: r };
36
- return u(i, `.${this.cssClassName}`, this.priority, (a = this._context) == null ? void 0 : a.config);
36
+ const { base: t = {}, variants: s = {}, compoundVariants: i = [] } = this.params, r = { ...t, variants: s, compoundVariants: i };
37
+ return u(r, `.${this.cssClassName}`, this.priority, (a = this._context) == null ? void 0 : a.config);
37
38
  }
38
39
  get props() {
39
40
  const { element: t } = this.params, s = this.params.variants ? Object.keys(this.params.variants).map((a) => {
40
- var n;
41
- const o = (n = this.params.defaultVariants) == null ? void 0 : n[a];
42
- return o !== void 0 ? `${a}=${String(o)}` : a;
43
- }) : void 0, r = /* @__PURE__ */ new Set([]), i = /\{props\.([\w\d]+)\}/gi.exec(JSON.stringify(this.params.base));
44
- return i && i.forEach((a, o, n) => {
45
- const p = n.at(1);
46
- p && r.add(p);
41
+ var o;
42
+ const c = (o = this.params.defaultVariants) == null ? void 0 : o[a];
43
+ return c !== void 0 ? `${a}=${String(c)}` : a;
44
+ }) : void 0, i = /* @__PURE__ */ new Set([]), r = /\{props\.([\w\d]+)\}/gi.exec(JSON.stringify(this.params.base));
45
+ return r && r.forEach((a, c, o) => {
46
+ const h = o.at(1);
47
+ h && i.add(h);
47
48
  }), {
48
49
  element: t,
49
50
  variantKeys: s,
50
- propValueKeys: [...r]
51
+ propValueKeys: [...i],
52
+ attr: {
53
+ "data-component-name": this._isProd ? void 0 : this._callerName
54
+ }
51
55
  };
52
56
  }
53
57
  _withBuildContext(t) {
54
58
  this._context = t;
55
- const { name: s, config: r } = t;
56
- return this._callerName = s, this;
59
+ const { name: s, config: i, prod: r } = t;
60
+ return this._isProd = r, this._callerName = s, this;
57
61
  }
58
62
  }
59
63
  export {
60
- d as StyleComponentGenerator
64
+ N as StyleComponentGenerator
61
65
  };
@@ -3,10 +3,14 @@ export interface GeneratorProps {
3
3
  element?: string;
4
4
  variantKeys?: string[];
5
5
  propValueKeys?: string[];
6
+ attr: {
7
+ [key: string]: any;
8
+ };
6
9
  }
7
10
  export declare class StyleComponentGenerator {
8
11
  tagName: Tag<any>;
9
12
  params: StyledParams;
13
+ _isProd: boolean | undefined;
10
14
  _callerName: string | undefined;
11
15
  _context: {
12
16
  name: string;
@@ -24,5 +28,6 @@ export declare class StyleComponentGenerator {
24
28
  _withBuildContext(context: {
25
29
  name: string;
26
30
  config: any;
31
+ prod: boolean;
27
32
  }): this;
28
33
  }
@@ -0,0 +1,232 @@
1
+ import * as H from "esbuild";
2
+ import { execSync as Q } from "child_process";
3
+ import { t as B, d as W } from "./dash-case-DMQMcCO6.js";
4
+ import { join as o } from "path";
5
+ import { existsSync as K, writeFileSync as w, mkdirSync as V, statSync as tt, readdirSync as st, readFileSync as v } from "fs";
6
+ import { readFile as et, writeFile as nt } from "fs/promises";
7
+ import { p as ot, a as rt, b as ct } from "./parse-templates-DUUSaubj.js";
8
+ import { createLogger as at, format as J, transports as it } from "winston";
9
+ const L = (t) => {
10
+ if (!t || t === "/") throw new Error("Could not find package.json file");
11
+ const s = o(t, "package.json");
12
+ return K(s) ? s : L(o(t, ".."));
13
+ }, lt = async (t) => {
14
+ const s = L(t);
15
+ return await et(s, "utf-8").then(JSON.parse).catch(() => {
16
+ });
17
+ }, pt = async (t) => {
18
+ const s = await lt(t);
19
+ if (s)
20
+ return s.type;
21
+ };
22
+ let M;
23
+ const q = async (t) => {
24
+ if (M) return M;
25
+ const s = await pt(t);
26
+ return s === "module" ? M = "esm" : (s === "commonjs" || import.meta.url.endsWith(".cjs")) && (M = "cjs"), M || "esm";
27
+ }, R = at({
28
+ level: "debug",
29
+ format: J.combine(J.colorize(), J.cli()),
30
+ transports: [new it.Console({})]
31
+ }), Ct = (t) => {
32
+ R.error(t);
33
+ }, O = {
34
+ externalModules: []
35
+ }, A = (t) => {
36
+ if (O.externalModules.length > 0) return O.externalModules;
37
+ const s = o(t, "salty.config.ts"), e = v(s, "utf8").match(/externalModules:\s?\[(.*)\]/);
38
+ if (!e) return [];
39
+ const n = e[1].split(",").map((l) => l.replace(/['"`]/g, "").trim());
40
+ return O.externalModules = n, n;
41
+ }, N = (t) => o(t, "./saltygen"), ft = ["salty", "css", "styles", "styled"], ut = (t = []) => new RegExp(`\\.(${[...ft, ...t].join("|")})\\.`), I = (t, s = []) => ut(s).test(t), gt = async (t) => {
42
+ const s = N(t), i = o(t, "salty.config.ts"), e = o(s, "salty.config.js"), n = await q(t), l = A(t);
43
+ await H.build({
44
+ entryPoints: [i],
45
+ minify: !0,
46
+ treeShaking: !0,
47
+ bundle: !0,
48
+ outfile: e,
49
+ format: n,
50
+ external: l
51
+ });
52
+ const S = Date.now(), { config: f } = await import(`${e}?t=${S}`);
53
+ return f;
54
+ }, dt = async (t) => {
55
+ const s = await gt(t), i = /* @__PURE__ */ new Set(), e = (u, a = []) => u ? Object.entries(u).flatMap(([m, p]) => {
56
+ if (!p) return;
57
+ if (typeof p == "object") return e(p, [...a, m]);
58
+ const P = [...a, m].join(".");
59
+ i.add(`"${P}"`);
60
+ const x = [...a.map(W), W(m)].join("-"), { result: y } = ct(p);
61
+ return `--${x}: ${y};`;
62
+ }) : [], n = (u) => u ? Object.entries(u).flatMap(([a, m]) => {
63
+ const p = e(m);
64
+ return a === "base" ? p.join("") : `${a} { ${p.join("")} }`;
65
+ }) : [], l = (u) => u ? Object.entries(u).flatMap(([a, m]) => Object.entries(m).flatMap(([p, P]) => {
66
+ const x = e(P, [a]), y = `.${a}-${p}, [data-${a}="${p}"]`, b = x.join("");
67
+ return `${y} { ${b} }`;
68
+ })) : [], S = e(s.variables), f = n(s.responsiveVariables), C = l(s.conditionalVariables), r = N(t), T = o(r, "css/variables.css"), g = `:root { ${S.join("")} ${f.join("")} } ${C.join("")}`;
69
+ w(T, g);
70
+ const h = o(r, "types/css-tokens.d.ts"), c = `type VariableTokens = ${[...i].join("|") || '""'}; type PropertyValueToken = \`{\${VariableTokens}}\``;
71
+ w(h, c);
72
+ const d = o(r, "css/global.css"), k = ot(s.global, "");
73
+ w(d, k);
74
+ const $ = o(r, "css/templates.css"), j = rt(s.templates);
75
+ w($, j);
76
+ }, _ = async (t, s, i) => {
77
+ const e = B(s), n = o(i, "js", e + ".js"), l = await q(t), S = A(t);
78
+ await H.build({
79
+ entryPoints: [s],
80
+ minify: !0,
81
+ treeShaking: !0,
82
+ bundle: !0,
83
+ outfile: n,
84
+ format: l,
85
+ target: ["es2022"],
86
+ keepNames: !0,
87
+ external: S
88
+ });
89
+ const f = Date.now();
90
+ return await import(`${n}?t=${f}`);
91
+ }, z = async (t) => {
92
+ const s = N(t), i = o(s, "salty.config.js"), { config: e } = await import(i);
93
+ return e;
94
+ }, U = () => {
95
+ try {
96
+ return process.env.NODE_ENV === "production";
97
+ } catch {
98
+ return !1;
99
+ }
100
+ }, Ft = async (t, s = U()) => {
101
+ try {
102
+ s ? R.info("Generating CSS in production mode! 🔥") : R.info("Generating CSS in development mode! 🚀");
103
+ const i = [], e = [], n = N(t), l = o(n, "index.css");
104
+ (() => {
105
+ K(n) && Q("rm -rf " + n), V(n), V(o(n, "css")), V(o(n, "types"));
106
+ })(), await dt(t);
107
+ const f = await z(t);
108
+ async function C(c, d) {
109
+ const k = ["node_modules", "saltygen"], $ = tt(c);
110
+ if ($.isDirectory()) {
111
+ const j = st(c);
112
+ if (k.some((a) => c.includes(a))) return;
113
+ await Promise.all(j.map((a) => C(o(c, a), o(d, a))));
114
+ } else if ($.isFile() && I(c)) {
115
+ const u = await _(t, c, n), a = [];
116
+ Object.entries(u).forEach(([x, y]) => {
117
+ if (y.isKeyframes && y.css) {
118
+ const G = `${y.animationName}.css`, Y = `css/${G}`, Z = o(n, Y);
119
+ i.push(G), w(Z, y.css);
120
+ return;
121
+ }
122
+ if (!y.generator) return;
123
+ const b = y.generator._withBuildContext({
124
+ name: x,
125
+ config: f,
126
+ prod: s
127
+ }), D = `${b.hash}-${b.priority}.css`;
128
+ e[b.priority] || (e[b.priority] = []), e[b.priority].push(D), a.push(D);
129
+ const E = `css/${D}`, X = o(n, E);
130
+ w(X, b.css);
131
+ });
132
+ const m = a.map((x) => `@import url('./${x}');`).join(`
133
+ `), p = B(c, 6), P = o(n, `css/${p}.css`);
134
+ w(P, m);
135
+ }
136
+ }
137
+ await C(t, n);
138
+ const r = i.map((c) => `@import url('./css/${c}');`).join(`
139
+ `);
140
+ let F = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
141
+
142
+ ${["variables.css", "global.css", "templates.css"].filter((c) => {
143
+ try {
144
+ return v(o(n, "css", c), "utf8").length > 0;
145
+ } catch {
146
+ return !1;
147
+ }
148
+ }).map((c) => `@import url('./css/${c}');`).join(`
149
+ `)}
150
+ ${r}`;
151
+ if (f.importStrategy !== "component") {
152
+ const c = e.flat().map((d) => `@import url('./css/${d}');`).join(`
153
+ `);
154
+ F += c;
155
+ }
156
+ w(l, F);
157
+ } catch (i) {
158
+ console.error(i);
159
+ }
160
+ }, jt = async (t, s) => {
161
+ try {
162
+ const i = [], e = o(t, "./saltygen"), n = o(e, "index.css");
163
+ if (I(s)) {
164
+ const S = await z(t), f = await _(t, s, e);
165
+ Object.entries(f).forEach(([h, F]) => {
166
+ if (!F.generator) return;
167
+ const c = F.generator._withBuildContext({
168
+ name: h,
169
+ config: S
170
+ }), d = `${c.hash}-${c.priority}.css`, k = `css/${d}`, $ = o(e, k);
171
+ i.push(d), w($, c.css);
172
+ });
173
+ const C = v(n, "utf8").split(`
174
+ `), r = i.map((h) => `@import url('../saltygen/css/${h}');`), g = [.../* @__PURE__ */ new Set([...C, ...r])].join(`
175
+ `);
176
+ w(n, g);
177
+ }
178
+ } catch (i) {
179
+ console.error(i);
180
+ }
181
+ }, xt = async (t, s, i = U()) => {
182
+ try {
183
+ const e = o(t, "./saltygen");
184
+ if (I(s)) {
185
+ const l = v(s, "utf8");
186
+ l.replace(/^(?!export\s)const\s.*/gm, (g) => `export ${g}`) !== l && await nt(s, l);
187
+ const f = await z(t), C = await _(t, s, e);
188
+ let r = l;
189
+ Object.entries(C).forEach(([g, h]) => {
190
+ var D;
191
+ if (h.isKeyframes || !h.generator) return;
192
+ const F = h.generator._withBuildContext({
193
+ name: g,
194
+ config: f,
195
+ prod: i
196
+ }), c = new RegExp(`\\s${g}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(l);
197
+ if (!c) return console.error("Could not find the original declaration");
198
+ const d = (D = c.at(1)) == null ? void 0 : D.trim(), k = new RegExp(`\\s${g}[=\\s]+styled\\(`, "g").exec(r);
199
+ if (!k) return console.error("Could not find the original declaration");
200
+ const { index: $ } = k;
201
+ let j = !1;
202
+ const u = setTimeout(() => j = !0, 5e3);
203
+ let a = 0, m = !1, p = 0;
204
+ for (; !m && !j; ) {
205
+ const E = r[$ + a];
206
+ E === "(" && p++, E === ")" && p--, p === 0 && E === ")" && (m = !0), a > r.length && (j = !0), a++;
207
+ }
208
+ if (!j) clearTimeout(u);
209
+ else throw new Error("Failed to find the end of the styled call and timed out");
210
+ const P = $ + a, x = r.slice($, P), y = r, b = ` ${g} = styled(${d}, "${F.classNames}", ${JSON.stringify(F.props)});`;
211
+ r = r.replace(x, b), y === r && console.error("Minimize file failed to change content", { name: g, tagName: d });
212
+ });
213
+ const T = B(s, 6);
214
+ return f.importStrategy === "component" && (r = `import '../../saltygen/css/${T}.css';
215
+ ${r}`), r = r.replace("{ styled }", "{ styledClient as styled }"), r = r.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), r;
216
+ }
217
+ } catch (e) {
218
+ console.error("Error in minimizeFile:", e);
219
+ }
220
+ };
221
+ export {
222
+ Ct as a,
223
+ ut as b,
224
+ dt as c,
225
+ _ as d,
226
+ jt as e,
227
+ Ft as g,
228
+ I as i,
229
+ R as l,
230
+ xt as m,
231
+ ft as s
232
+ };
@@ -0,0 +1,11 @@
1
+ "use strict";const te=require("esbuild"),se=require("child_process"),N=require("./dash-case-DKzpenwY.cjs"),i=require("path"),l=require("fs"),H=require("fs/promises"),J=require("./parse-templates-DVK3iZIl.cjs"),v=require("winston");var q=typeof document<"u"?document.currentScript:null;function ne(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const U=ne(te),G=e=>{if(!e||e==="/")throw new Error("Could not find package.json file");const t=i.join(e,"package.json");return l.existsSync(t)?t:G(i.join(e,".."))},oe=async e=>{const t=G(e);return await H.readFile(t,"utf-8").then(JSON.parse).catch(()=>{})},ie=async e=>{const t=await oe(e);if(t)return t.type};let T;const L=async e=>{if(T)return T;const t=await ie(e);return t==="module"?T="esm":(t==="commonjs"||(typeof document>"u"?require("url").pathToFileURL(__filename).href:q&&q.tagName.toUpperCase()==="SCRIPT"&&q.src||new URL("index-BKoD9apd.cjs",document.baseURI).href).endsWith(".cjs"))&&(T="cjs"),T||"esm"},O=v.createLogger({level:"debug",format:v.format.combine(v.format.colorize(),v.format.cli()),transports:[new v.transports.Console({})]}),re=e=>{O.error(e)},I={externalModules:[]},W=e=>{if(I.externalModules.length>0)return I.externalModules;const t=i.join(e,"salty.config.ts"),s=l.readFileSync(t,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!s)return[];const o=s[1].split(",").map(u=>u.replace(/['"`]/g,"").trim());return I.externalModules=o,o},V=e=>i.join(e,"./saltygen"),K=["salty","css","styles","styled"],A=(e=[])=>new RegExp(`\\.(${[...K,...e].join("|")})\\.`),R=(e,t=[])=>A(t).test(e),ce=async e=>{const t=V(e),n=i.join(e,"salty.config.ts"),s=i.join(t,"salty.config.js"),o=await L(e),u=W(e);await U.build({entryPoints:[n],minify:!0,treeShaking:!0,bundle:!0,outfile:s,format:o,external:u});const b=Date.now(),{config:p}=await import(`${s}?t=${b}`);return p},X=async e=>{const t=await ce(e),n=new Set,s=(g,a=[])=>g?Object.entries(g).flatMap(([m,f])=>{if(!f)return;if(typeof f=="object")return s(f,[...a,m]);const P=[...a,m].join(".");n.add(`"${P}"`);const x=[...a.map(N.dashCase),N.dashCase(m)].join("-"),{result:h}=J.parseValueTokens(f);return`--${x}: ${h};`}):[],o=g=>g?Object.entries(g).flatMap(([a,m])=>{const f=s(m);return a==="base"?f.join(""):`${a} { ${f.join("")} }`}):[],u=g=>g?Object.entries(g).flatMap(([a,m])=>Object.entries(m).flatMap(([f,P])=>{const x=s(P,[a]),h=`.${a}-${f}, [data-${a}="${f}"]`,w=x.join("");return`${h} { ${w} }`})):[],b=s(t.variables),p=o(t.responsiveVariables),F=u(t.conditionalVariables),r=V(e),E=i.join(r,"css/variables.css"),d=`:root { ${b.join("")} ${p.join("")} } ${F.join("")}`;l.writeFileSync(E,d);const j=i.join(r,"types/css-tokens.d.ts"),c=`type VariableTokens = ${[...n].join("|")||'""'}; type PropertyValueToken = \`{\${VariableTokens}}\``;l.writeFileSync(j,c);const y=i.join(r,"css/global.css"),k=J.parseStyles(t.global,"");l.writeFileSync(y,k);const S=i.join(r,"css/templates.css"),C=J.parseTemplates(t.templates);l.writeFileSync(S,C)},_=async(e,t,n)=>{const s=N.toHash(t),o=i.join(n,"js",s+".js"),u=await L(e),b=W(e);await U.build({entryPoints:[t],minify:!0,treeShaking:!0,bundle:!0,outfile:o,format:u,target:["es2022"],keepNames:!0,external:b});const p=Date.now();return await import(`${o}?t=${p}`)},z=async e=>{const t=V(e),n=i.join(t,"salty.config.js"),{config:s}=await import(n);return s},Y=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},ae=async(e,t=Y())=>{try{t?O.info("Generating CSS in production mode! 🔥"):O.info("Generating CSS in development mode! 🚀");const n=[],s=[],o=V(e),u=i.join(o,"index.css");(()=>{l.existsSync(o)&&se.execSync("rm -rf "+o),l.mkdirSync(o),l.mkdirSync(i.join(o,"css")),l.mkdirSync(i.join(o,"types"))})(),await X(e);const p=await z(e);async function F(c,y){const k=["node_modules","saltygen"],S=l.statSync(c);if(S.isDirectory()){const C=l.readdirSync(c);if(k.some(a=>c.includes(a)))return;await Promise.all(C.map(a=>F(i.join(c,a),i.join(y,a))))}else if(S.isFile()&&R(c)){const g=await _(e,c,o),a=[];Object.entries(g).forEach(([x,h])=>{if(h.isKeyframes&&h.css){const B=`${h.animationName}.css`,Q=`css/${B}`,ee=i.join(o,Q);n.push(B),l.writeFileSync(ee,h.css);return}if(!h.generator)return;const w=h.generator._withBuildContext({name:x,config:p,prod:t}),D=`${w.hash}-${w.priority}.css`;s[w.priority]||(s[w.priority]=[]),s[w.priority].push(D),a.push(D);const M=`css/${D}`,Z=i.join(o,M);l.writeFileSync(Z,w.css)});const m=a.map(x=>`@import url('./${x}');`).join(`
2
+ `),f=N.toHash(c,6),P=i.join(o,`css/${f}.css`);l.writeFileSync(P,m)}}await F(e,o);const r=n.map(c=>`@import url('./css/${c}');`).join(`
3
+ `);let $=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
4
+
5
+ ${["variables.css","global.css","templates.css"].filter(c=>{try{return l.readFileSync(i.join(o,"css",c),"utf8").length>0}catch{return!1}}).map(c=>`@import url('./css/${c}');`).join(`
6
+ `)}
7
+ ${r}`;if(p.importStrategy!=="component"){const c=s.flat().map(y=>`@import url('./css/${y}');`).join(`
8
+ `);$+=c}l.writeFileSync(u,$)}catch(n){console.error(n)}},le=async(e,t)=>{try{const n=[],s=i.join(e,"./saltygen"),o=i.join(s,"index.css");if(R(t)){const b=await z(e),p=await _(e,t,s);Object.entries(p).forEach(([j,$])=>{if(!$.generator)return;const c=$.generator._withBuildContext({name:j,config:b}),y=`${c.hash}-${c.priority}.css`,k=`css/${y}`,S=i.join(s,k);n.push(y),l.writeFileSync(S,c.css)});const F=l.readFileSync(o,"utf8").split(`
9
+ `),r=n.map(j=>`@import url('../saltygen/css/${j}');`),d=[...new Set([...F,...r])].join(`
10
+ `);l.writeFileSync(o,d)}}catch(n){console.error(n)}},ue=async(e,t,n=Y())=>{try{const s=i.join(e,"./saltygen");if(R(t)){const u=l.readFileSync(t,"utf8");u.replace(/^(?!export\s)const\s.*/gm,d=>`export ${d}`)!==u&&await H.writeFile(t,u);const p=await z(e),F=await _(e,t,s);let r=u;Object.entries(F).forEach(([d,j])=>{var D;if(j.isKeyframes||!j.generator)return;const $=j.generator._withBuildContext({name:d,config:p,prod:n}),c=new RegExp(`\\s${d}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(u);if(!c)return console.error("Could not find the original declaration");const y=(D=c.at(1))==null?void 0:D.trim(),k=new RegExp(`\\s${d}[=\\s]+styled\\(`,"g").exec(r);if(!k)return console.error("Could not find the original declaration");const{index:S}=k;let C=!1;const g=setTimeout(()=>C=!0,5e3);let a=0,m=!1,f=0;for(;!m&&!C;){const M=r[S+a];M==="("&&f++,M===")"&&f--,f===0&&M===")"&&(m=!0),a>r.length&&(C=!0),a++}if(!C)clearTimeout(g);else throw new Error("Failed to find the end of the styled call and timed out");const P=S+a,x=r.slice(S,P),h=r,w=` ${d} = styled(${y}, "${$.classNames}", ${JSON.stringify($.props)});`;r=r.replace(x,w),h===r&&console.error("Minimize file failed to change content",{name:d,tagName:y})});const E=N.toHash(t,6);return p.importStrategy==="component"&&(r=`import '../../saltygen/css/${E}.css';
11
+ ${r}`),r=r.replace("{ styled }","{ styledClient as styled }"),r=r.replace("@salty-css/react/styled","@salty-css/react/styled-client"),r}}catch(s){console.error("Error in minimizeFile:",s)}};exports.compileSaltyFile=_;exports.generateConfigStyles=X;exports.generateCss=ae;exports.generateFile=le;exports.isSaltyFile=R;exports.logError=re;exports.logger=O;exports.minimizeFile=ue;exports.saltyFileExtensions=K;exports.saltyFileRegExp=A;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/core",
3
- "version": "0.0.1-alpha.84",
3
+ "version": "0.0.1-alpha.86",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.mjs",
6
6
  "typings": "./dist/index.d.ts",