@salty-css/vite 0.0.1-alpha.13 → 0.0.1-alpha.130

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.
Files changed (5) hide show
  1. package/README.md +143 -26
  2. package/index.cjs +24 -14
  3. package/index.d.ts +1 -0
  4. package/index.js +342 -218
  5. package/package.json +10 -2
package/README.md CHANGED
@@ -1,15 +1,132 @@
1
- # Salty Css
1
+ ![Salty CSS Banner](https://raw.githubusercontent.com/gist/tremppu/ef2b867907cbf262ab7373f41558a403/raw/a2137de136ee2296e386682beb4487bba0f58a2f/salty-logo-svg-dvd.svg)
2
2
 
3
- ## Basic usage example with Button
3
+ # Salty CSS - CSS-in-JS library that is kinda sweet
4
4
 
5
- ### Initial requirements
5
+ Is there anything saltier than CSS in frontend web development? Salty CSS is built to provide better developer experience for developers looking for performant and feature rich CSS-in-JS solutions.
6
6
 
7
- 1. Add `saltyPlugin` to vite or webpack config from `@salty-css/vite` or `@salty-css/webpack`
8
- 2. Create `salty-config.ts` to the root of your project
9
- 3. Import global styles to any regular .css file from `saltygen/index.css` (does not exist during first run, cli command coming later)
10
- 4. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
7
+ ## Features
11
8
 
12
- ### Code examples
9
+ - Build time compilation to achieve awesome runtime performance and minimal size
10
+ - Next.js, React Server Components, Vite and Webpack support
11
+ - Type safety with out of the box TypeScript and ESLint plugin
12
+ - Advanced CSS variables configuration to allow smooth token usage
13
+ - Style templates to create reusable styles easily
14
+
15
+ ## Get started
16
+
17
+ Fastest way to get started with any framework is `npx salty-css init [directory]` command
18
+
19
+ - Next.js → [Next.js guide](#nextjs) + [Next.js example app](https://github.com/margarita-form/salty-css-website)
20
+ - React + Vite → [React + Vite guide](#react--vite) + [React example code](#code-examples)
21
+ - React + Webpack → Guide coming soon
22
+
23
+ ## Useful commands
24
+
25
+ - Create component: `npx salty-css generate [filePath]`
26
+ - Build: `npx salty-css build [directory]`
27
+ - Update Salty CSS packages: `npx salty-css up`
28
+
29
+ ## Salty CSS styled function
30
+
31
+ ```ts
32
+ // components/wrapper.css.ts
33
+ import { styled } from '@salty-css/react/styled';
34
+
35
+ // Define a component with styled function. First argument is the component name or existing component to extend and second argument is the object containing the styles and other options
36
+ export const Component = styled('div', {
37
+ className: 'wrapper', // Define custom class name that will be included for this component
38
+ element: 'section', // Define the html element that will be rendered for this component, overrides the first 'div' argument
39
+ base: {
40
+ // 👉 Add your CSS-in-JS base styles here! 👈
41
+ },
42
+ variants: {
43
+ // Define conditional styles that will be applied to the component based on the variant prop values
44
+ },
45
+ compoundVariants: [
46
+ // Define conditional styles that will be applied to the component based on the combination of variant prop values
47
+ ],
48
+ defaultVariants: {
49
+ // Set default variant prop values
50
+ },
51
+ defaultProps: {
52
+ // Add additional default props for the component (eg, id and other html element attributes)
53
+ },
54
+ passProps: true, // Pass variant props to the rendered element / parent component (default: false)
55
+ });
56
+ ```
57
+
58
+ ## Salty CSS CLI
59
+
60
+ In your existing repository you can use `npx salty-css [command]` to initialize a project, generate components, update related packages and build required files.
61
+
62
+ - Initialize project → `npx salty-css init [directory]` - Installs required packages, detects framework in use and creates project files to the provided directory. Directory can be left blank if you want files to be created to the current directory.
63
+ - Generate component → `npx salty-css update [version]` - Update @salty-css packages in your repository. Default version is "latest". Additional options like `--dir`, `--tag`, `--name` and `--className` are also supported.
64
+ - Build files → `npx salty-css build [directory]` - Compile Salty CSS related files in your project. This should not be needed if you are using tools like Next.js or Vite
65
+
66
+ ## Usage
67
+
68
+ ### Next.js
69
+
70
+ ![salty-next](https://github.com/user-attachments/assets/2cf6a93f-cdd5-4f5f-ab2e-3bc8bcfb83e8)
71
+
72
+ Salty CSS provides Next.js App & Pages router support with full React Server Components support.
73
+
74
+ ### Add Salty CSS to Next.js
75
+
76
+ 1. In your existing Next.js repository you can run `npx salty-css init` to automatically configure Salty CSS.
77
+ 2. Create your first Salty CSS component with `npx salty-css generate [filePath]` (e.g. src/custom-wrapper)
78
+ 3. Import your component for example to `page.tsx` and see it working!
79
+
80
+ And note: steps 2 & 3 are just to show how get new components up and running, step 1 does all of the important stuff 🤯
81
+
82
+ #### Manual configuration
83
+
84
+ 1. For Next.js support install `npm i @salty-css/next @salty-css/core @salty-css/react`
85
+ 2. Create `salty.config.ts` to your app directory
86
+ 3. Add Salty CSS plugin to next.js config
87
+
88
+ - **Next.js 15:** In `next.config.ts` add import for salty plugin `import { withSaltyCss } from '@salty-css/next';` and then add `withSaltyCss` to wrap your nextConfig export like so `export default withSaltyCss(nextConfig);`
89
+ - **Next.js 14 and older:** In `next.config.js` add import for salty plugin `const { withSaltyCss } = require('@salty-css/next');` and then add `withSaltyCss` to wrap your nextConfig export like so `module.exports = withSaltyCss(nextConfig);`
90
+
91
+ 4. Make sure that `salty.config.ts` and `next.config.ts` are in the same folder!
92
+ 5. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
93
+ 6. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
94
+
95
+ [Check out Next.js demo project](https://github.com/margarita-form/salty-css-website) or [react example code](#code-examples)
96
+
97
+ ---
98
+
99
+ ### React + Vite
100
+
101
+ ![salty-vite-react](https://github.com/user-attachments/assets/12ec5b6a-0dcc-48fa-afc1-d337fc8f800c)
102
+
103
+ ### Add Salty CSS to your React + Vite app
104
+
105
+ 1. In your existing Vite repository you can run `npx salty-css init` to automatically configure Salty CSS.
106
+ 2. Create your first Salty CSS component with `npx salty-css generate [filePath]` (e.g. src/custom-wrapper)
107
+ 3. Import your component for example to `main.tsx` and see it working!
108
+
109
+ And note: steps 2 & 3 are just to show how get new components up and running, step 1 does all of the important stuff 🤯
110
+
111
+ #### Manual configuration
112
+
113
+ 1. For Vite support install `npm i @salty-css/vite @salty-css/core`
114
+ 2. In `vite.config` add import for salty plugin `import { saltyPlugin } from '@salty-css/vite';` and then add `saltyPlugin(__dirname)` to your vite configuration plugins
115
+ 3. Make sure that `salty.config.ts` and `vite.config.ts` are in the same folder!
116
+ 4. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
117
+ 5. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
118
+
119
+ [Check out react example code](#code-examples)
120
+
121
+ ---
122
+
123
+ ### Create components
124
+
125
+ 1. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
126
+
127
+ ## Code examples
128
+
129
+ ### Basic usage example with Button
13
130
 
14
131
  **Salty config**
15
132
 
@@ -31,23 +148,6 @@ export const config = defineConfig({
31
148
  });
32
149
  ```
33
150
 
34
- **Your React component file**
35
-
36
- ```tsx
37
- import { Wrapper } from '../components/wrapper/wrapper.css';
38
- import { Button } from '../components/button/button.css';
39
-
40
- export const IndexPage = () => {
41
- return (
42
- <Wrapper>
43
- <Button variant="solid" onClick={() => alert('It is a button.')}>
44
- Outlined
45
- </Button>
46
- </Wrapper>
47
- );
48
- };
49
- ```
50
-
51
151
  **Wrapper** (`components/wrapper/wrapper.css.ts`)
52
152
 
53
153
  ```tsx
@@ -72,7 +172,7 @@ export const Button = styled('button', {
72
172
  padding: `0.6em 1.2em`,
73
173
  border: '1px solid currentColor',
74
174
  background: 'transparent',
75
- color: 'currentColor/40',
175
+ color: 'currentColor',
76
176
  cursor: 'pointer',
77
177
  transition: '200ms',
78
178
  textDecoration: 'none',
@@ -108,4 +208,21 @@ export const Button = styled('button', {
108
208
  });
109
209
  ```
110
210
 
211
+ **Your React component file**
212
+
213
+ ```tsx
214
+ import { Wrapper } from '../components/wrapper/wrapper.css';
215
+ import { Button } from '../components/button/button.css';
216
+
217
+ export const IndexPage = () => {
218
+ return (
219
+ <Wrapper>
220
+ <Button variant="solid" onClick={() => alert('It is a button.')}>
221
+ Outlined
222
+ </Button>
223
+ </Wrapper>
224
+ );
225
+ };
226
+ ```
227
+
111
228
  More examples coming soon
package/index.cjs CHANGED
@@ -1,18 +1,28 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const K=require("esbuild"),W=require("winston"),L=require("child_process"),y=require("path"),d=require("fs"),G=require("fs/promises");function R(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(s,e,n.get?n:{enumerable:!0,get:()=>t[e]})}}return s.default=t,Object.freeze(s)}const Z=R(K),k=R(W),q=t=>String.fromCharCode(t+(t>25?39:97)),U=(t,s)=>{let e="",n;for(n=Math.abs(t);n>52;n=n/52|0)e=q(n%52)+e;return e=q(n%52)+e,e.length<s?e=e.padStart(s,"a"):e.length>s&&(e=e.slice(-s)),e},X=(t,s)=>{let e=s.length;for(;e;)t=t*33^s.charCodeAt(--e);return t},_=(t,s=3)=>{const e=X(5381,JSON.stringify(t))>>>0;return U(e,s)};function V(t){return t?typeof t!="string"?String(t):t.replace(/\s/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(s,e)=>(e>0?"-":"")+s.toLowerCase()):""}const Y=(t,s)=>{if(typeof t!="string")return{result:t};if(!s)return{result:t};const e=[];return Object.values(s).forEach(n=>{const{pattern:o,transform:g}=n;t=t.replace(o,$=>{const{value:a,css:f}=g($);return f&&e.push(f),a})}),{result:t,additionalCss:e}},I=t=>typeof t!="string"?{result:t}:/\{[^{}]+\}/g.test(t)?{result:t.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${V(n[1].replaceAll(".","-"))})`)}:{result:t},D=(t,s,e,n)=>{const o=[],g=Object.entries(t).reduce((a,[f,r])=>{const i=f.trim();if(typeof r=="function"&&(r=r()),typeof r=="object"){if(!r)return a;if(i==="variants")return Object.entries(r).forEach(([u,c])=>{c&&Object.entries(c).forEach(([m,l])=>{if(!l)return;const O=`${s}.${u}-${m}`,P=D(l,O);o.push(P)})}),a;if(i==="defaultVariants")return a;if(i==="compoundVariants")return r.forEach(u=>{const{css:c,...m}=u,l=Object.entries(m).reduce((P,[x,N])=>`${P}.${x}-${N}`,s),O=D(c,l);o.push(O)}),a;if(i.startsWith("@")){const u=D(r,s),c=`${i} {
2
- ${u.replace(`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const fe=require("esbuild"),pe=require("child_process"),c=require("path"),f=require("fs"),U=require("fs/promises"),J=require("winston");var Z=typeof document<"u"?document.currentScript:null;function de(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,n.get?n:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const X=de(fe),K=e=>String.fromCharCode(e+(e>25?39:97)),ye=(e,t)=>{let s="",n;for(n=Math.abs(e);n>52;n=n/52|0)s=K(n%52)+s;return s=K(n%52)+s,s.length<t?s=s.padStart(t,"a"):s.length>t&&(s=s.slice(-t)),s},ge=(e,t)=>{let s=t.length;for(;s;)e=e*33^t.charCodeAt(--s);return e},H=(e,t=5)=>{const s=ge(5381,JSON.stringify(e))>>>0;return ye(s,t)};function D(e){return e?typeof e!="string"?D(String(e)):e.replace(/[\s.]/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(t,s)=>(s>0?"-":"")+t.toLowerCase()):""}const me=(e,t)=>{if(typeof e!="string")return{result:e};if(!t)return{result:e};const s=[];return Object.values(t).forEach(n=>{const{pattern:i,transform:r}=n;e=e.replace(i,d=>{const{value:l,css:m}=r(d);return m&&s.push(m),l})}),{result:e,additionalCss:s}},Y=e=>typeof e!="string"?{result:e}:/\{[^{}]+\}/g.test(e)?{result:e.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${D(n[1].replaceAll(".","-"))})`)}:{result:e},N=(e,t,s,n)=>{if(!e)return"";const i=[],r=Object.entries(e).reduce((l,[m,o])=>{const a=m.trim();if(typeof o=="function"&&(o=o()),typeof o=="object"){if(!o)return l;if(a==="variants")return Object.entries(o).forEach(([y,S])=>{S&&Object.entries(S).forEach(([C,T])=>{if(!T)return;const P=`${t}.${y}-${C}`,p=N(T,P);i.push(p)})}),l;if(a==="defaultVariants")return l;if(a==="compoundVariants")return o.forEach(y=>{const{css:S,...C}=y,T=Object.entries(C).reduce((p,[g,$])=>`${p}.${g}-${$}`,t),P=N(S,T);i.push(P)}),l;if(a.startsWith("@")){const y=N(o,t),S=`${a} {
2
+ ${y.replace(`
3
3
  `,`
4
4
  `)}
5
- }`;return o.push(c),a}const h=f.includes("&")?i.replace("&",s):i.startsWith(":")?`${s}${i}`:`${s} ${i}`,F=D(r,h);return o.push(F),a}const p=i.startsWith("-")?i:V(i),b=(h,F=";")=>a=`${a}${h}${F}`,j=h=>b(`${p}:${h}`);if(typeof r=="number")return j(r);if(typeof r!="string")if("toString"in r)r=r.toString();else return a;const{modifiers:S}={},C=function*(){yield I(r),yield Y(r,S)}();for(const{result:h,additionalCss:F=[]}of C)r=h,F.forEach(u=>{const c=D(u,"");b(c,"")});return j(r)},"");if(!g)return o.join(`
6
- `);if(!s)return g;let $="";return $=`${s} { ${g} }`,[$,...o].join(`
7
- `)},z=(t,s=[])=>{const e=[],n={};if(Object.entries(t).forEach(([o,g])=>{if(typeof g=="object"){if(!g)return;const $=o.trim(),a=z(g,[...s,$]);e.push(a)}else n[o]=g}),Object.keys(n).length){const o=s.map(V).join("-"),g=D(n,`.${o}`);e.push(g)}return e.join(`
8
- `)};k.createLogger({level:"info",format:k.format.combine(k.format.colorize(),k.format.cli()),transports:[new k.transports.Console({})]});const E=t=>y.join(t,"./saltygen"),Q=["salty","css","styles","styled"],v=(t=[])=>new RegExp(`\\.(${[...Q,...t].join("|")})\\.`),T=(t,s=[])=>v(s).test(t),tt=async t=>{const s=E(t),e=y.join(t,"salty-config.ts"),n=y.join(s,"salty-config.js");await Z.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",external:["react"]});const o=Date.now(),{config:g}=await import(`${n}?t=${o}`);return g},B=async t=>{const s=await tt(t),e=new Set,n=(u,c=[])=>u?Object.entries(u).flatMap(([m,l])=>{if(!l)return;if(typeof l=="object")return n(l,[...c,m]);const O=[...c,m].join(".");e.add(`"${O}"`);const P=[...c.map(V),V(m)].join("-"),{result:x}=I(l);return`--${P}: ${x};`}):[],o=u=>u?Object.entries(u).flatMap(([c,m])=>{const l=n(m);return c==="base"?l.join(""):`${c} { ${l.join("")} }`}):[],g=u=>u?Object.entries(u).flatMap(([c,m])=>Object.entries(m).flatMap(([l,O])=>{const P=n(O,[c]),x=`.${c}-${l}, [data-${c}="${l}"]`,N=P.join("");return`${x} { ${N} }`})):[],$=n(s.variables),a=o(s.responsiveVariables),f=g(s.conditionalVariables),r=E(t),i=y.join(r,"css/variables.css"),p=`:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;d.writeFileSync(i,p);const b=y.join(r,"types/css-tokens.d.ts"),S=`type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;d.writeFileSync(b,S);const w=y.join(r,"css/global.css"),C=D(s.global,"");d.writeFileSync(w,C);const h=y.join(r,"css/templates.css"),F=z(s.templates);d.writeFileSync(h,F)},A=async(t,s)=>{const e=_(t),n=y.join(s,"js",e+".js");await Z.build({entryPoints:[t],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",target:["es2022"],keepNames:!0,external:["react"]});const o=Date.now();return await import(`${n}?t=${o}`)},M=async t=>{const s=E(t),e=y.join(s,"salty-config.js"),{config:n}=await import(e);return n},st=async t=>{try{const s=[],e=[],n=E(t),o=y.join(n,"index.css");(()=>{d.existsSync(n)&&L.execSync("rm -rf "+n),d.mkdirSync(n),d.mkdirSync(y.join(n,"css")),d.mkdirSync(y.join(n,"types"))})(),await B(t);const $=await M(t);async function a(p,b){const j=d.statSync(p);if(j.isDirectory()){const S=d.readdirSync(p);await Promise.all(S.map(w=>a(y.join(p,w),y.join(b,w))))}else if(j.isFile()&&T(p)){const w=await A(p,n),C=[];Object.entries(w).forEach(([c,m])=>{if(m.isKeyframes&&m.css){const N=`${m.animationName}.css`,H=`css/${N}`,J=y.join(n,H);s.push(N),d.writeFileSync(J,m.css);return}if(!m.generator)return;const l=m.generator._withBuildContext({name:c,config:$}),O=`${l.hash}-${l.priority}.css`;e[l.priority]||(e[l.priority]=[]),e[l.priority].push(O),C.push(O);const P=`css/${O}`,x=y.join(n,P);d.writeFileSync(x,l.css)});const h=C.map(c=>`@import url('./${c}');`).join(`
9
- `),F=_(p,6),u=y.join(n,`css/${F}.css`);d.writeFileSync(u,h)}}await a(t,n);const f=s.map(p=>`@import url('./css/${p}');`).join(`
10
- `);let i=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
5
+ }`;return i.push(S),l}const b=m.includes("&")?a.replace("&",t):a.startsWith(":")?`${t}${a}`:`${t} ${a}`,u=N(o,b);return i.push(u),l}const w=a.startsWith("-")?a:D(a),F=(b,u=";")=>l=`${l}${b}${u}`,k=b=>F(`${w}:${b}`);if(typeof o=="number")return k(o);if(typeof o!="string")if("toString"in o)o=o.toString();else return l;const{modifiers:x}={},h=function*(){yield Y(o),yield me(o,x)}();for(const{result:b,additionalCss:u=[]}of h)o=b,u.forEach(y=>{const S=N(y,"");F(S,"")});return k(o)},"");if(!r)return i.join(`
6
+ `);if(!t)return r;let d="";return d=`${t} { ${r} }`,[d,...i].join(`
7
+ `)},Q=(e,t=[])=>{if(!e)return"";const s=[],n={};if(Object.entries(e).forEach(([i,r])=>{if(typeof r=="object"){if(!r)return;const d=i.trim(),l=Q(r,[...t,d]);s.push(l)}else n[i]=r}),Object.keys(n).length){const i=t.map(D).join("-"),r=N(n,`.${i}`);s.push(r)}return s.join(`
8
+ `)},he=e=>Object.entries(e).reduce((t,[s,n])=>(typeof n=="object"&&(t[s]=v(n).map(i=>`"${i}"`).join(" | ")),t),{}),v=(e,t="",s=new Set)=>e?(Object.entries(e).forEach(([n,i])=>{const r=t?`${t}.${n}`:n;return typeof i=="object"?v(i,r,s):s.add(t)}),[...s]):[],ee=e=>{if(!e||e==="/")throw new Error("Could not find package.json file");const t=c.join(e,"package.json");return f.existsSync(t)?t:ee(c.join(e,".."))},be=async e=>{const t=ee(e);return await U.readFile(t,"utf-8").then(JSON.parse).catch(()=>{})},je=async e=>{const t=await be(e);if(t)return t.type};let V;const te=async e=>{if(V)return V;const t=await je(e);return t==="module"?V="esm":(t==="commonjs"||(typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href).endsWith(".cjs"))&&(V="cjs"),V||"esm"},q=J.createLogger({level:"debug",format:J.format.combine(J.format.colorize(),J.format.cli()),transports:[new J.transports.Console({})]});function se(e){return e?typeof e!="string"?se(String(e)):e.replace(/[\s-]/g,".").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(t,s)=>(s>0?".":"")+t.toLowerCase()):""}const Se={"*, *::before, *::after":{boxSizing:"border-box"},"*":{margin:0},html:{lineHeight:1.15,textSizeAdjust:"100%",WebkitFontSmoothing:"antialiased"},"img, picture, video, canvas, svg":{display:"block",maxWidth:"100%"},"p, h1, h2, h3, h4, h5, h6":{overflowWrap:"break-word"},p:{textWrap:"pretty"},"h1, h2, h3, h4, h5, h6":{textWrap:"balance"},button:{lineHeight:"1em"},"input, optgroup, select, textarea":{fontFamily:"inherit",fontSize:"100%",lineHeight:"1.15em"}},I={externalModules:[]},ne=e=>{if(I.externalModules.length>0)return I.externalModules;const t=c.join(e,"salty.config.ts"),n=f.readFileSync(t,"utf8").match(/externalModules:\s?\[(.*)\]/);if(!n)return[];const i=n[1].split(",").map(r=>r.replace(/['"`]/g,"").trim());return I.externalModules=i,i},W=e=>c.join(e,"./saltygen"),$e=["salty","css","styles","styled"],we=(e=[])=>new RegExp(`\\.(${[...$e,...e].join("|")})\\.`),z=(e,t=[])=>we(t).test(e),Fe=async e=>{const t=W(e),s=c.join(e,"salty.config.ts"),n=c.join(t,"salty.config.js"),i=await te(e),r=ne(e);await X.build({entryPoints:[s],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:i,external:r});const d=Date.now(),{config:l}=await import(`${n}?t=${d}`);return l},oe=async e=>{const t=await Fe(e),s=new Set,n=(p,g=[])=>p?Object.entries(p).flatMap(([$,j])=>{if(!j)return;if(typeof j=="object")return n(j,[...g,$]);const A=se($),R=D($),E=[...g,A].join(".");s.add(`"${E}"`);const O=[...g.map(D),R].join("-"),{result:_}=Y(j);return`--${O}: ${_};`}):[],i=p=>p?Object.entries(p).flatMap(([g,$])=>{const j=n($);return g==="base"?j.join(""):`${g} { ${j.join("")} }`}):[],r=p=>p?Object.entries(p).flatMap(([g,$])=>Object.entries($).flatMap(([j,A])=>{const R=n(A,[g]),E=`.${g}-${j}, [data-${g}="${j}"]`,O=R.join("");return`${E} { ${O} }`})):[],d=n(t.variables),l=i(t.responsiveVariables),m=r(t.conditionalVariables),o=W(e),a=c.join(o,"css/_variables.css"),w=`:root { ${d.join("")} ${l.join("")} } ${m.join("")}`;f.writeFileSync(a,w);const F=c.join(o,"css/_global.css"),k=N(t.global,"");f.writeFileSync(F,`@layer global { ${k} }`);const x=c.join(o,"css/_reset.css"),h=t.reset==="none"?{}:typeof t.reset=="object"?t.reset:Se,b=N(h,"");f.writeFileSync(x,`@layer reset { ${b} }`);const u=c.join(o,"css/_templates.css"),y=Q(t.templates),S=he(t.templates);f.writeFileSync(u,y);const C=c.join(o,"types/css-tokens.d.ts"),P=`
9
+ // Variable types
10
+ type VariableTokens = ${[...s].join("|")};
11
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
11
12
 
12
- ${["@import url('./css/variables.css');","@import url('./css/global.css');","@import url('./css/templates.css');"].join(`
13
+ // Template types
14
+ type TemplateTokens = {
15
+ ${Object.entries(S).map(([p,g])=>`${p}?: ${g}`).join(`
13
16
  `)}
14
- ${f}`;if($.importStrategy!=="component"){const p=e.flat().map(b=>`@import url('./css/${b}');`).join(`
15
- `);i+=p}d.writeFileSync(o,i)}catch(s){console.error(s)}},et=async(t,s)=>{try{const e=[],n=y.join(t,"./saltygen"),o=y.join(n,"index.css");if(T(s)){const $=await M(t),a=await A(s,n);Object.entries(a).forEach(([b,j])=>{if(!j.generator)return;const S=j.generator._withBuildContext({name:b,config:$}),w=`${S.hash}-${S.priority}.css`,C=`css/${w}`,h=y.join(n,C);e.push(w),d.writeFileSync(h,S.css)});const f=d.readFileSync(o,"utf8").split(`
16
- `),r=e.map(b=>`@import url('../saltygen/css/${b}');`),p=[...new Set([...f,...r])].join(`
17
- `);d.writeFileSync(o,p)}}catch(e){console.error(e)}},nt=async(t,s)=>{try{const e=y.join(t,"./saltygen");if(T(s)){let o=d.readFileSync(s,"utf8");o.replace(/^(?!export\s)const\s.*/gm,i=>`export ${i}`)!==o&&await G.writeFile(s,o);const $=await M(t),a=await A(s,e);let f=o;Object.entries(a).forEach(([i,p])=>{var u;if(p.isKeyframes){console.log("value",p);return}if(!p.generator)return;const b=p.generator._withBuildContext({name:i,config:$}),j=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(o);if(!j)return console.error("Could not find the original declaration");const S=(u=j.at(1))==null?void 0:u.trim(),{element:w,variantKeys:C}=b.props,h=`${i} = styled(${S}, "${b.classNames}", "${b._callerName}", ${JSON.stringify(w)}, ${JSON.stringify(C)});`,F=new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`,"g");f=f.replace(F,h)});const r=_(s,6);return $.importStrategy==="component"&&(f=`import '../../saltygen/css/${r}.css';
18
- ${f}`),f=f.replace("{ styled }","{ styledClient as styled }"),f=f.replace("@salty-css/react/styled","@salty-css/react/styled-client"),f}}catch(e){console.error(e)}},ot=t=>({name:"stylegen",buildStart:()=>st(t),load:async s=>{if(T(s))return await nt(t,s)},watchChange:{handler:async s=>{T(s)&&await et(t,s),s.includes("salty-config")&&await B(t)}}});exports.saltyPlugin=ot;
17
+ }
18
+ `;f.writeFileSync(C,P)},B=async(e,t,s)=>{const n=H(t),i=c.join(s,"./temp");f.existsSync(i)||f.mkdirSync(i);const r=c.parse(t);let d=f.readFileSync(t,"utf8");d=d.replace(/styled\([^"'`{,]+,/g,"styled('div',");const l=c.join(s,"js",n+".js"),m=ne(e),o=await te(e);await X.build({stdin:{contents:d,sourcefile:r.base,resolveDir:r.dir,loader:"tsx"},minify:!1,treeShaking:!0,bundle:!0,outfile:l,format:o,target:["node20"],keepNames:!0,external:m,packages:"external"});const a=Date.now();return await import(`${l}?t=${a}`)},L=async e=>{const t=W(e),s=c.join(t,"salty.config.js"),{config:n}=await import(s);return n},re=()=>{try{return process.env.NODE_ENV==="production"}catch{return!1}},xe=async(e,t=re())=>{try{const s=Date.now();t?q.info("Generating CSS in production mode! 🔥"):q.info("Generating CSS in development mode! 🚀");const n=[],i=[],r=W(e),d=c.join(r,"index.css");(()=>{f.existsSync(r)&&pe.execSync("rm -rf "+r),f.mkdirSync(r),f.mkdirSync(c.join(r,"css")),f.mkdirSync(c.join(r,"types"))})(),await oe(e);const m=await L(e);async function o(u,y){const S=["node_modules","saltygen"],C=f.statSync(u);if(C.isDirectory()){const T=f.readdirSync(u);if(S.some(p=>u.includes(p)))return;await Promise.all(T.map(p=>o(c.join(u,p),c.join(y,p))))}else if(C.isFile()&&z(u)){const P=await B(e,u,r),p=[];Object.entries(P).forEach(([E,O])=>{if(O.isKeyframes&&O.css){const G=`a_${O.animationName}.css`,le=`css/${G}`,ue=c.join(r,le);n.push(G),f.writeFileSync(ue,O.css);return}if(!O.generator)return;const _=O.generator._withBuildContext({name:E,config:m,prod:t});i[_.priority]||(i[_.priority]=[]),i[_.priority].push(_.cssFileName),p.push(_.cssFileName);const ce=`css/${_.cssFileName}`,ae=c.join(r,ce);f.writeFileSync(ae,_.css)});const g=p.map(E=>`@import url('./${E}');`).join(`
19
+ `),$=H(u,6),j=c.parse(u),A=D(j.name),R=c.join(r,`css/f_${A}-${$}.css`);f.writeFileSync(R,g)}}await o(e,r);const a=n.map(u=>`@import url('./css/${u}');`).join(`
20
+ `);let x=`@layer reset, global, l0, l1, l2, l3, l4, l5, l6, l7, l8;
21
+
22
+ ${["_variables.css","_reset.css","_global.css","_templates.css"].filter(u=>{try{return f.readFileSync(c.join(r,"css",u),"utf8").length>0}catch{return!1}}).map(u=>`@import url('./css/${u}');`).join(`
23
+ `)}
24
+ ${a}`;if(m.importStrategy!=="component"){const u=i.flat().map(y=>`@import url('./css/${y}');`).join(`
25
+ `);x+=u}f.writeFileSync(d,x);const h=Date.now()-s,b=h<200?"🔥":h<500?"🚀":h<1e3?"🎉":h<2e3?"🚗":h<5e3?"🤔":"🥴";q.info(`Generated CSS in ${h}ms! ${b}`)}catch(s){console.error(s)}},ke=async(e,t)=>{try{const s=[],n=c.join(e,"./saltygen"),i=c.join(n,"index.css");if(z(t)){const d=await L(e),l=await B(e,t,n);Object.entries(l).forEach(([F,k])=>{if(!k.generator)return;const x=k.generator._withBuildContext({name:F,config:d}),M=`css/${x.cssFileName}`,h=c.join(n,M);s.push(x.cssFileName),f.writeFileSync(h,x.css)});const m=f.readFileSync(i,"utf8").split(`
26
+ `),o=s.map(F=>`@import url('../saltygen/css/${F}');`),w=[...new Set([...m,...o])].join(`
27
+ `);f.writeFileSync(i,w)}}catch(s){console.error(s)}},Ce=async(e,t,s=re())=>{try{const n=c.join(e,"./saltygen");if(z(t)){const r=f.readFileSync(t,"utf8");r.replace(/^(?!export\s)const\s.*/gm,a=>`export ${a}`)!==r&&await U.writeFile(t,r);const l=await L(e),m=await B(e,t,n);let o=r;if(Object.entries(m).forEach(([a,w])=>{var $;if(w.isKeyframes||!w.generator)return;const F=w.generator._withBuildContext({name:a,config:l,prod:s}),k=new RegExp(`\\s${a}[=\\s]+[^()]+styled\\(([^,]+),`,"g").exec(r);if(!k)return console.error("Could not find the original declaration");const x=($=k.at(1))==null?void 0:$.trim(),M=new RegExp(`\\s${a}[=\\s]+styled\\(`,"g").exec(o);if(!M)return console.error("Could not find the original declaration");const{index:h}=M;let b=!1;const u=setTimeout(()=>b=!0,5e3);let y=0,S=!1,C=0;for(;!S&&!b;){const j=o[h+y];j==="("&&C++,j===")"&&C--,C===0&&j===")"&&(S=!0),y>o.length&&(b=!0),y++}if(!b)clearTimeout(u);else throw new Error("Failed to find the end of the styled call and timed out");const T=h+y,P=o.slice(h,T),p=o,g=` ${a} = styled(${x}, "${F.classNames}", ${JSON.stringify(F.props)});`;o=o.replace(P,g),p===o&&console.error("Minimize file failed to change content",{name:a,tagName:x})}),l.importStrategy==="component"){const a=H(t,6),w=c.parse(t);o=`import '../../saltygen/css/${`f_${D(w.name)}-${a}.css`}';
28
+ ${o}`}return o=o.replace("{ styled }","{ styledClient as styled }"),o=o.replace("@salty-css/react/styled","@salty-css/react/styled-client"),o}}catch(n){console.error("Error in minimizeFile:",n)}},ie=e=>({name:"stylegen",buildStart:()=>xe(e),load:async t=>{if(z(t))return await Ce(e,t)},watchChange:{handler:async t=>{z(t)&&await ke(e,t),t.includes("salty.config")&&await oe(e)}}});exports.default=ie;exports.saltyPlugin=ie;
package/index.d.ts CHANGED
@@ -6,3 +6,4 @@ export declare const saltyPlugin: (dir: string) => {
6
6
  handler: (filePath: string) => Promise<void>;
7
7
  };
8
8
  };
9
+ export default saltyPlugin;
package/index.js CHANGED
@@ -1,279 +1,403 @@
1
- import * as I from "esbuild";
2
- import * as P from "winston";
3
- import { execSync as L } from "child_process";
4
- import { join as u } from "path";
5
- import { writeFileSync as x, existsSync as q, mkdirSync as A, statSync as G, readdirSync as U, readFileSync as B } from "fs";
6
- import { writeFile as X } from "fs/promises";
7
- const Z = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), Y = (t, s) => {
8
- let e = "", n;
9
- for (n = Math.abs(t); n > 52; n = n / 52 | 0) e = Z(n % 52) + e;
10
- return e = Z(n % 52) + e, e.length < s ? e = e.padStart(s, "a") : e.length > s && (e = e.slice(-s)), e;
11
- }, Q = (t, s) => {
12
- let e = s.length;
13
- for (; e; ) t = t * 33 ^ s.charCodeAt(--e);
1
+ import * as Q from "esbuild";
2
+ import { execSync as ut } from "child_process";
3
+ import { join as a, parse as G } from "path";
4
+ import { existsSync as K, writeFileSync as k, mkdirSync as R, statSync as dt, readdirSync as gt, readFileSync as z } from "fs";
5
+ import { readFile as yt, writeFile as mt } from "fs/promises";
6
+ import { createLogger as ht, format as H, transports as bt } from "winston";
7
+ const Y = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), $t = (t, e) => {
8
+ let s = "", o;
9
+ for (o = Math.abs(t); o > 52; o = o / 52 | 0) s = Y(o % 52) + s;
10
+ return s = Y(o % 52) + s, s.length < e ? s = s.padStart(e, "a") : s.length > e && (s = s.slice(-e)), s;
11
+ }, St = (t, e) => {
12
+ let s = e.length;
13
+ for (; s; ) t = t * 33 ^ e.charCodeAt(--s);
14
14
  return t;
15
- }, R = (t, s = 3) => {
16
- const e = Q(5381, JSON.stringify(t)) >>> 0;
17
- return Y(e, s);
15
+ }, L = (t, e = 5) => {
16
+ const s = St(5381, JSON.stringify(t)) >>> 0;
17
+ return $t(s, e);
18
18
  };
19
- function k(t) {
20
- return t ? typeof t != "string" ? String(t) : t.replace(/\s/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (s, e) => (e > 0 ? "-" : "") + s.toLowerCase()) : "";
19
+ function O(t) {
20
+ return t ? typeof t != "string" ? O(String(t)) : t.replace(/[\s.]/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (e, s) => (s > 0 ? "-" : "") + e.toLowerCase()) : "";
21
21
  }
22
- const v = (t, s) => {
22
+ const jt = (t, e) => {
23
23
  if (typeof t != "string") return { result: t };
24
- if (!s) return { result: t };
25
- const e = [];
26
- return Object.values(s).forEach((n) => {
27
- const { pattern: r, transform: g } = n;
28
- t = t.replace(r, ($) => {
29
- const { value: a, css: f } = g($);
30
- return f && e.push(f), a;
24
+ if (!e) return { result: t };
25
+ const s = [];
26
+ return Object.values(e).forEach((o) => {
27
+ const { pattern: i, transform: r } = o;
28
+ t = t.replace(i, (u) => {
29
+ const { value: l, css: y } = r(u);
30
+ return y && s.push(y), l;
31
31
  });
32
- }), { result: t, additionalCss: e };
33
- }, H = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${k(n[1].replaceAll(".", "-"))})`) } : { result: t }, O = (t, s, e, n) => {
34
- const r = [], g = Object.entries(t).reduce((a, [f, o]) => {
35
- const i = f.trim();
36
- if (typeof o == "function" && (o = o()), typeof o == "object") {
37
- if (!o) return a;
38
- if (i === "variants")
39
- return Object.entries(o).forEach(([y, c]) => {
40
- c && Object.entries(c).forEach(([m, l]) => {
41
- if (!l) return;
42
- const F = `${s}.${y}-${m}`, N = O(l, F);
43
- r.push(N);
32
+ }), { result: t, additionalCss: s };
33
+ }, v = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...o) => `var(--${O(o[1].replaceAll(".", "-"))})`) } : { result: t }, E = (t, e, s, o) => {
34
+ if (!t) return "";
35
+ const i = [], r = Object.entries(t).reduce((l, [y, n]) => {
36
+ const c = y.trim();
37
+ if (typeof n == "function" && (n = n()), typeof n == "object") {
38
+ if (!n) return l;
39
+ if (c === "variants")
40
+ return Object.entries(n).forEach(([d, $]) => {
41
+ $ && Object.entries($).forEach(([C, T]) => {
42
+ if (!T) return;
43
+ const N = `${e}.${d}-${C}`, p = E(T, N);
44
+ i.push(p);
44
45
  });
45
- }), a;
46
- if (i === "defaultVariants")
47
- return a;
48
- if (i === "compoundVariants")
49
- return o.forEach((y) => {
50
- const { css: c, ...m } = y, l = Object.entries(m).reduce((N, [D, V]) => `${N}.${D}-${V}`, s), F = O(c, l);
51
- r.push(F);
52
- }), a;
53
- if (i.startsWith("@")) {
54
- const y = O(o, s), c = `${i} {
55
- ${y.replace(`
46
+ }), l;
47
+ if (c === "defaultVariants")
48
+ return l;
49
+ if (c === "compoundVariants")
50
+ return n.forEach((d) => {
51
+ const { css: $, ...C } = d, T = Object.entries(C).reduce((p, [g, S]) => `${p}.${g}-${S}`, e), N = E($, T);
52
+ i.push(N);
53
+ }), l;
54
+ if (c.startsWith("@")) {
55
+ const d = E(n, e), $ = `${c} {
56
+ ${d.replace(`
56
57
  `, `
57
58
  `)}
58
59
  }`;
59
- return r.push(c), a;
60
+ return i.push($), l;
60
61
  }
61
- const d = f.includes("&") ? i.replace("&", s) : i.startsWith(":") ? `${s}${i}` : `${s} ${i}`, S = O(o, d);
62
- return r.push(S), a;
62
+ const h = y.includes("&") ? c.replace("&", e) : c.startsWith(":") ? `${e}${c}` : `${e} ${c}`, f = E(n, h);
63
+ return i.push(f), l;
63
64
  }
64
- const p = i.startsWith("-") ? i : k(i), h = (d, S = ";") => a = `${a}${d}${S}`, b = (d) => h(`${p}:${d}`);
65
- if (typeof o == "number") return b(o);
66
- if (typeof o != "string")
67
- if ("toString" in o) o = o.toString();
68
- else return a;
69
- const { modifiers: j } = {}, C = function* () {
70
- yield H(o), yield v(o, j);
65
+ const j = c.startsWith("-") ? c : O(c), w = (h, f = ";") => l = `${l}${h}${f}`, x = (h) => w(`${j}:${h}`);
66
+ if (typeof n == "number") return x(n);
67
+ if (typeof n != "string")
68
+ if ("toString" in n) n = n.toString();
69
+ else return l;
70
+ const { modifiers: F } = {}, m = function* () {
71
+ yield v(n), yield jt(n, F);
71
72
  }();
72
- for (const { result: d, additionalCss: S = [] } of C)
73
- o = d, S.forEach((y) => {
74
- const c = O(y, "");
75
- h(c, "");
73
+ for (const { result: h, additionalCss: f = [] } of m)
74
+ n = h, f.forEach((d) => {
75
+ const $ = E(d, "");
76
+ w($, "");
76
77
  });
77
- return b(o);
78
+ return x(n);
78
79
  }, "");
79
- if (!g) return r.join(`
80
+ if (!r) return i.join(`
80
81
  `);
81
- if (!s) return g;
82
- let $ = "";
83
- return $ = `${s} { ${g} }`, [$, ...r].join(`
82
+ if (!e) return r;
83
+ let u = "";
84
+ return u = `${e} { ${r} }`, [u, ...i].join(`
84
85
  `);
85
- }, J = (t, s = []) => {
86
- const e = [], n = {};
87
- if (Object.entries(t).forEach(([r, g]) => {
88
- if (typeof g == "object") {
89
- if (!g) return;
90
- const $ = r.trim(), a = J(g, [...s, $]);
91
- e.push(a);
86
+ }, tt = (t, e = []) => {
87
+ if (!t) return "";
88
+ const s = [], o = {};
89
+ if (Object.entries(t).forEach(([i, r]) => {
90
+ if (typeof r == "object") {
91
+ if (!r) return;
92
+ const u = i.trim(), l = tt(r, [...e, u]);
93
+ s.push(l);
92
94
  } else
93
- n[r] = g;
94
- }), Object.keys(n).length) {
95
- const r = s.map(k).join("-"), g = O(n, `.${r}`);
96
- e.push(g);
95
+ o[i] = r;
96
+ }), Object.keys(o).length) {
97
+ const i = e.map(O).join("-"), r = E(o, `.${i}`);
98
+ s.push(r);
97
99
  }
98
- return e.join(`
100
+ return s.join(`
99
101
  `);
102
+ }, wt = (t) => Object.entries(t).reduce((e, [s, o]) => (typeof o == "object" && (e[s] = et(o).map((i) => `"${i}"`).join(" | ")), e), {}), et = (t, e = "", s = /* @__PURE__ */ new Set()) => t ? (Object.entries(t).forEach(([o, i]) => {
103
+ const r = e ? `${e}.${o}` : o;
104
+ return typeof i == "object" ? et(i, r, s) : s.add(e);
105
+ }), [...s]) : [], st = (t) => {
106
+ if (!t || t === "/") throw new Error("Could not find package.json file");
107
+ const e = a(t, "package.json");
108
+ return K(e) ? e : st(a(t, ".."));
109
+ }, Ft = async (t) => {
110
+ const e = st(t);
111
+ return await yt(e, "utf-8").then(JSON.parse).catch(() => {
112
+ });
113
+ }, xt = async (t) => {
114
+ const e = await Ft(t);
115
+ if (e)
116
+ return e.type;
100
117
  };
101
- P.createLogger({
102
- level: "info",
103
- format: P.format.combine(P.format.colorize(), P.format.cli()),
104
- transports: [new P.transports.Console({})]
118
+ let _;
119
+ const nt = async (t) => {
120
+ if (_) return _;
121
+ const e = await xt(t);
122
+ return e === "module" ? _ = "esm" : (e === "commonjs" || import.meta.url.endsWith(".cjs")) && (_ = "cjs"), _ || "esm";
123
+ }, B = ht({
124
+ level: "debug",
125
+ format: H.combine(H.colorize(), H.cli()),
126
+ transports: [new bt.Console({})]
105
127
  });
106
- const T = (t) => u(t, "./saltygen"), tt = ["salty", "css", "styles", "styled"], st = (t = []) => new RegExp(`\\.(${[...tt, ...t].join("|")})\\.`), E = (t, s = []) => st(s).test(t), et = async (t) => {
107
- const s = T(t), e = u(t, "salty-config.ts"), n = u(s, "salty-config.js");
108
- await I.build({
109
- entryPoints: [e],
128
+ function ot(t) {
129
+ return t ? typeof t != "string" ? ot(String(t)) : t.replace(/[\s-]/g, ".").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (e, s) => (s > 0 ? "." : "") + e.toLowerCase()) : "";
130
+ }
131
+ const Ct = {
132
+ /** Set box model to border-box */
133
+ "*, *::before, *::after": {
134
+ boxSizing: "border-box"
135
+ },
136
+ /** Remove default margin and padding */
137
+ "*": {
138
+ margin: 0
139
+ },
140
+ /** Remove adjust font properties */
141
+ html: {
142
+ lineHeight: 1.15,
143
+ textSizeAdjust: "100%",
144
+ WebkitFontSmoothing: "antialiased"
145
+ },
146
+ /** Make media elements responsive */
147
+ "img, picture, video, canvas, svg": {
148
+ display: "block",
149
+ maxWidth: "100%"
150
+ },
151
+ /** Avoid overflow of text */
152
+ "p, h1, h2, h3, h4, h5, h6": {
153
+ overflowWrap: "break-word"
154
+ },
155
+ /** Improve text wrapping */
156
+ p: {
157
+ textWrap: "pretty"
158
+ },
159
+ "h1, h2, h3, h4, h5, h6": {
160
+ textWrap: "balance"
161
+ },
162
+ /** Improve button line height */
163
+ button: {
164
+ lineHeight: "1em"
165
+ },
166
+ /** Improve form elements */
167
+ "input, optgroup, select, textarea": {
168
+ fontFamily: "inherit",
169
+ fontSize: "100%",
170
+ lineHeight: "1.15em"
171
+ }
172
+ }, I = {
173
+ externalModules: []
174
+ }, rt = (t) => {
175
+ if (I.externalModules.length > 0) return I.externalModules;
176
+ const e = a(t, "salty.config.ts"), o = z(e, "utf8").match(/externalModules:\s?\[(.*)\]/);
177
+ if (!o) return [];
178
+ const i = o[1].split(",").map((r) => r.replace(/['"`]/g, "").trim());
179
+ return I.externalModules = i, i;
180
+ }, Z = (t) => a(t, "./saltygen"), kt = ["salty", "css", "styles", "styled"], Tt = (t = []) => new RegExp(`\\.(${[...kt, ...t].join("|")})\\.`), W = (t, e = []) => Tt(e).test(t), Nt = async (t) => {
181
+ const e = Z(t), s = a(t, "salty.config.ts"), o = a(e, "salty.config.js"), i = await nt(t), r = rt(t);
182
+ await Q.build({
183
+ entryPoints: [s],
110
184
  minify: !0,
111
185
  treeShaking: !0,
112
186
  bundle: !0,
113
- outfile: n,
114
- format: "esm",
115
- external: ["react"]
187
+ outfile: o,
188
+ format: i,
189
+ external: r
116
190
  });
117
- const r = Date.now(), { config: g } = await import(`${n}?t=${r}`);
118
- return g;
119
- }, K = async (t) => {
120
- const s = await et(t), e = /* @__PURE__ */ new Set(), n = (y, c = []) => y ? Object.entries(y).flatMap(([m, l]) => {
121
- if (!l) return;
122
- if (typeof l == "object") return n(l, [...c, m]);
123
- const F = [...c, m].join(".");
124
- e.add(`"${F}"`);
125
- const N = [...c.map(k), k(m)].join("-"), { result: D } = H(l);
126
- return `--${N}: ${D};`;
127
- }) : [], r = (y) => y ? Object.entries(y).flatMap(([c, m]) => {
128
- const l = n(m);
129
- return c === "base" ? l.join("") : `${c} { ${l.join("")} }`;
130
- }) : [], g = (y) => y ? Object.entries(y).flatMap(([c, m]) => Object.entries(m).flatMap(([l, F]) => {
131
- const N = n(F, [c]), D = `.${c}-${l}, [data-${c}="${l}"]`, V = N.join("");
132
- return `${D} { ${V} }`;
133
- })) : [], $ = n(s.variables), a = r(s.responsiveVariables), f = g(s.conditionalVariables), o = T(t), i = u(o, "css/variables.css"), p = `:root { ${$.join("")} ${a.join("")} } ${f.join("")}`;
134
- x(i, p);
135
- const h = u(o, "types/css-tokens.d.ts"), j = `type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;
136
- x(h, j);
137
- const w = u(o, "css/global.css"), C = O(s.global, "");
138
- x(w, C);
139
- const d = u(o, "css/templates.css"), S = J(s.templates);
140
- x(d, S);
141
- }, M = async (t, s) => {
142
- const e = R(t), n = u(s, "js", e + ".js");
143
- await I.build({
144
- entryPoints: [t],
145
- minify: !0,
191
+ const u = Date.now(), { config: l } = await import(`${o}?t=${u}`);
192
+ return l;
193
+ }, it = async (t) => {
194
+ const e = await Nt(t), s = /* @__PURE__ */ new Set(), o = (p, g = []) => p ? Object.entries(p).flatMap(([S, b]) => {
195
+ if (!b) return;
196
+ if (typeof b == "object") return o(b, [...g, S]);
197
+ const A = ot(S), J = O(S), M = [...g, A].join(".");
198
+ s.add(`"${M}"`);
199
+ const P = [...g.map(O), J].join("-"), { result: D } = v(b);
200
+ return `--${P}: ${D};`;
201
+ }) : [], i = (p) => p ? Object.entries(p).flatMap(([g, S]) => {
202
+ const b = o(S);
203
+ return g === "base" ? b.join("") : `${g} { ${b.join("")} }`;
204
+ }) : [], r = (p) => p ? Object.entries(p).flatMap(([g, S]) => Object.entries(S).flatMap(([b, A]) => {
205
+ const J = o(A, [g]), M = `.${g}-${b}, [data-${g}="${b}"]`, P = J.join("");
206
+ return `${M} { ${P} }`;
207
+ })) : [], u = o(e.variables), l = i(e.responsiveVariables), y = r(e.conditionalVariables), n = Z(t), c = a(n, "css/_variables.css"), j = `:root { ${u.join("")} ${l.join("")} } ${y.join("")}`;
208
+ k(c, j);
209
+ const w = a(n, "css/_global.css"), x = E(e.global, "");
210
+ k(w, `@layer global { ${x} }`);
211
+ const F = a(n, "css/_reset.css"), m = e.reset === "none" ? {} : typeof e.reset == "object" ? e.reset : Ct, h = E(m, "");
212
+ k(F, `@layer reset { ${h} }`);
213
+ const f = a(n, "css/_templates.css"), d = tt(e.templates), $ = wt(e.templates);
214
+ k(f, d);
215
+ const C = a(n, "types/css-tokens.d.ts"), N = `
216
+ // Variable types
217
+ type VariableTokens = ${[...s].join("|")};
218
+ type PropertyValueToken = \`{\${VariableTokens}}\`;
219
+
220
+ // Template types
221
+ type TemplateTokens = {
222
+ ${Object.entries($).map(([p, g]) => `${p}?: ${g}`).join(`
223
+ `)}
224
+ }
225
+ `;
226
+ k(C, N);
227
+ }, q = async (t, e, s) => {
228
+ const o = L(e), i = a(s, "./temp");
229
+ K(i) || R(i);
230
+ const r = G(e);
231
+ let u = z(e, "utf8");
232
+ u = u.replace(/styled\([^"'`{,]+,/g, "styled('div',");
233
+ const l = a(s, "js", o + ".js"), y = rt(t), n = await nt(t);
234
+ await Q.build({
235
+ stdin: {
236
+ contents: u,
237
+ sourcefile: r.base,
238
+ resolveDir: r.dir,
239
+ loader: "tsx"
240
+ },
241
+ minify: !1,
146
242
  treeShaking: !0,
147
243
  bundle: !0,
148
- outfile: n,
149
- format: "esm",
150
- target: ["es2022"],
244
+ outfile: l,
245
+ format: n,
246
+ target: ["node20"],
151
247
  keepNames: !0,
152
- external: ["react"]
248
+ external: y,
249
+ packages: "external"
153
250
  });
154
- const r = Date.now();
155
- return await import(`${n}?t=${r}`);
156
- }, _ = async (t) => {
157
- const s = T(t), e = u(s, "salty-config.js"), { config: n } = await import(e);
158
- return n;
159
- }, nt = async (t) => {
251
+ const c = Date.now();
252
+ return await import(`${l}?t=${c}`);
253
+ }, U = async (t) => {
254
+ const e = Z(t), s = a(e, "salty.config.js"), { config: o } = await import(s);
255
+ return o;
256
+ }, ct = () => {
160
257
  try {
161
- const s = [], e = [], n = T(t), r = u(n, "index.css");
258
+ return process.env.NODE_ENV === "production";
259
+ } catch {
260
+ return !1;
261
+ }
262
+ }, Pt = async (t, e = ct()) => {
263
+ try {
264
+ const s = Date.now();
265
+ e ? B.info("Generating CSS in production mode! 🔥") : B.info("Generating CSS in development mode! 🚀");
266
+ const o = [], i = [], r = Z(t), u = a(r, "index.css");
162
267
  (() => {
163
- q(n) && L("rm -rf " + n), A(n), A(u(n, "css")), A(u(n, "types"));
164
- })(), await K(t);
165
- const $ = await _(t);
166
- async function a(p, h) {
167
- const b = G(p);
168
- if (b.isDirectory()) {
169
- const j = U(p);
170
- await Promise.all(j.map((w) => a(u(p, w), u(h, w))));
171
- } else if (b.isFile() && E(p)) {
172
- const w = await M(p, n), C = [];
173
- Object.entries(w).forEach(([c, m]) => {
174
- if (m.isKeyframes && m.css) {
175
- const V = `${m.animationName}.css`, W = `css/${V}`, z = u(n, W);
176
- s.push(V), x(z, m.css);
268
+ K(r) && ut("rm -rf " + r), R(r), R(a(r, "css")), R(a(r, "types"));
269
+ })(), await it(t);
270
+ const y = await U(t);
271
+ async function n(f, d) {
272
+ const $ = ["node_modules", "saltygen"], C = dt(f);
273
+ if (C.isDirectory()) {
274
+ const T = gt(f);
275
+ if ($.some((p) => f.includes(p))) return;
276
+ await Promise.all(T.map((p) => n(a(f, p), a(d, p))));
277
+ } else if (C.isFile() && W(f)) {
278
+ const N = await q(t, f, r), p = [];
279
+ Object.entries(N).forEach(([M, P]) => {
280
+ if (P.isKeyframes && P.css) {
281
+ const X = `a_${P.animationName}.css`, ft = `css/${X}`, pt = a(r, ft);
282
+ o.push(X), k(pt, P.css);
177
283
  return;
178
284
  }
179
- if (!m.generator) return;
180
- const l = m.generator._withBuildContext({
181
- name: c,
182
- config: $
183
- }), F = `${l.hash}-${l.priority}.css`;
184
- e[l.priority] || (e[l.priority] = []), e[l.priority].push(F), C.push(F);
185
- const N = `css/${F}`, D = u(n, N);
186
- x(D, l.css);
285
+ if (!P.generator) return;
286
+ const D = P.generator._withBuildContext({
287
+ name: M,
288
+ config: y,
289
+ prod: e
290
+ });
291
+ i[D.priority] || (i[D.priority] = []), i[D.priority].push(D.cssFileName), p.push(D.cssFileName);
292
+ const at = `css/${D.cssFileName}`, lt = a(r, at);
293
+ k(lt, D.css);
187
294
  });
188
- const d = C.map((c) => `@import url('./${c}');`).join(`
189
- `), S = R(p, 6), y = u(n, `css/${S}.css`);
190
- x(y, d);
295
+ const g = p.map((M) => `@import url('./${M}');`).join(`
296
+ `), S = L(f, 6), b = G(f), A = O(b.name), J = a(r, `css/f_${A}-${S}.css`);
297
+ k(J, g);
191
298
  }
192
299
  }
193
- await a(t, n);
194
- const f = s.map((p) => `@import url('./css/${p}');`).join(`
300
+ await n(t, r);
301
+ const c = o.map((f) => `@import url('./css/${f}');`).join(`
195
302
  `);
196
- let i = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
303
+ let F = `@layer reset, global, l0, l1, l2, l3, l4, l5, l6, l7, l8;
197
304
 
198
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
305
+ ${["_variables.css", "_reset.css", "_global.css", "_templates.css"].filter((f) => {
306
+ try {
307
+ return z(a(r, "css", f), "utf8").length > 0;
308
+ } catch {
309
+ return !1;
310
+ }
311
+ }).map((f) => `@import url('./css/${f}');`).join(`
199
312
  `)}
200
- ${f}`;
201
- if ($.importStrategy !== "component") {
202
- const p = e.flat().map((h) => `@import url('./css/${h}');`).join(`
313
+ ${c}`;
314
+ if (y.importStrategy !== "component") {
315
+ const f = i.flat().map((d) => `@import url('./css/${d}');`).join(`
203
316
  `);
204
- i += p;
317
+ F += f;
205
318
  }
206
- x(r, i);
319
+ k(u, F);
320
+ const m = Date.now() - s, h = m < 200 ? "🔥" : m < 500 ? "🚀" : m < 1e3 ? "🎉" : m < 2e3 ? "🚗" : m < 5e3 ? "🤔" : "🥴";
321
+ B.info(`Generated CSS in ${m}ms! ${h}`);
207
322
  } catch (s) {
208
323
  console.error(s);
209
324
  }
210
- }, rt = async (t, s) => {
325
+ }, Dt = async (t, e) => {
211
326
  try {
212
- const e = [], n = u(t, "./saltygen"), r = u(n, "index.css");
213
- if (E(s)) {
214
- const $ = await _(t), a = await M(s, n);
215
- Object.entries(a).forEach(([h, b]) => {
216
- if (!b.generator) return;
217
- const j = b.generator._withBuildContext({
218
- name: h,
219
- config: $
220
- }), w = `${j.hash}-${j.priority}.css`, C = `css/${w}`, d = u(n, C);
221
- e.push(w), x(d, j.css);
327
+ const s = [], o = a(t, "./saltygen"), i = a(o, "index.css");
328
+ if (W(e)) {
329
+ const u = await U(t), l = await q(t, e, o);
330
+ Object.entries(l).forEach(([w, x]) => {
331
+ if (!x.generator) return;
332
+ const F = x.generator._withBuildContext({
333
+ name: w,
334
+ config: u
335
+ }), V = `css/${F.cssFileName}`, m = a(o, V);
336
+ s.push(F.cssFileName), k(m, F.css);
222
337
  });
223
- const f = B(r, "utf8").split(`
224
- `), o = e.map((h) => `@import url('../saltygen/css/${h}');`), p = [.../* @__PURE__ */ new Set([...f, ...o])].join(`
338
+ const y = z(i, "utf8").split(`
339
+ `), n = s.map((w) => `@import url('../saltygen/css/${w}');`), j = [.../* @__PURE__ */ new Set([...y, ...n])].join(`
225
340
  `);
226
- x(r, p);
341
+ k(i, j);
227
342
  }
228
- } catch (e) {
229
- console.error(e);
343
+ } catch (s) {
344
+ console.error(s);
230
345
  }
231
- }, ot = async (t, s) => {
346
+ }, Et = async (t, e, s = ct()) => {
232
347
  try {
233
- const e = u(t, "./saltygen");
234
- if (E(s)) {
235
- let r = B(s, "utf8");
236
- r.replace(/^(?!export\s)const\s.*/gm, (i) => `export ${i}`) !== r && await X(s, r);
237
- const $ = await _(t), a = await M(s, e);
238
- let f = r;
239
- Object.entries(a).forEach(([i, p]) => {
240
- var y;
241
- if (p.isKeyframes) {
242
- console.log("value", p);
243
- return;
348
+ const o = a(t, "./saltygen");
349
+ if (W(e)) {
350
+ const r = z(e, "utf8");
351
+ r.replace(/^(?!export\s)const\s.*/gm, (c) => `export ${c}`) !== r && await mt(e, r);
352
+ const l = await U(t), y = await q(t, e, o);
353
+ let n = r;
354
+ if (Object.entries(y).forEach(([c, j]) => {
355
+ var S;
356
+ if (j.isKeyframes || !j.generator) return;
357
+ const w = j.generator._withBuildContext({
358
+ name: c,
359
+ config: l,
360
+ prod: s
361
+ }), x = new RegExp(`\\s${c}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(r);
362
+ if (!x) return console.error("Could not find the original declaration");
363
+ const F = (S = x.at(1)) == null ? void 0 : S.trim(), V = new RegExp(`\\s${c}[=\\s]+styled\\(`, "g").exec(n);
364
+ if (!V) return console.error("Could not find the original declaration");
365
+ const { index: m } = V;
366
+ let h = !1;
367
+ const f = setTimeout(() => h = !0, 5e3);
368
+ let d = 0, $ = !1, C = 0;
369
+ for (; !$ && !h; ) {
370
+ const b = n[m + d];
371
+ b === "(" && C++, b === ")" && C--, C === 0 && b === ")" && ($ = !0), d > n.length && (h = !0), d++;
244
372
  }
245
- if (!p.generator) return;
246
- const h = p.generator._withBuildContext({
247
- name: i,
248
- config: $
249
- }), b = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),`, "g").exec(r);
250
- if (!b)
251
- return console.error("Could not find the original declaration");
252
- const j = (y = b.at(1)) == null ? void 0 : y.trim(), { element: w, variantKeys: C } = h.props, d = `${i} = styled(${j}, "${h.classNames}", "${h._callerName}", ${JSON.stringify(w)}, ${JSON.stringify(
253
- C
254
- )});`, S = new RegExp(`${i}[=\\s]+[^()]+styled\\(([^,]+),[^;]+;`, "g");
255
- f = f.replace(S, d);
256
- });
257
- const o = R(s, 6);
258
- return $.importStrategy === "component" && (f = `import '../../saltygen/css/${o}.css';
259
- ${f}`), f = f.replace("{ styled }", "{ styledClient as styled }"), f = f.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), f;
373
+ if (!h) clearTimeout(f);
374
+ else throw new Error("Failed to find the end of the styled call and timed out");
375
+ const T = m + d, N = n.slice(m, T), p = n, g = ` ${c} = styled(${F}, "${w.classNames}", ${JSON.stringify(w.props)});`;
376
+ n = n.replace(N, g), p === n && console.error("Minimize file failed to change content", { name: c, tagName: F });
377
+ }), l.importStrategy === "component") {
378
+ const c = L(e, 6), j = G(e);
379
+ n = `import '../../saltygen/css/${`f_${O(j.name)}-${c}.css`}';
380
+ ${n}`;
381
+ }
382
+ return n = n.replace("{ styled }", "{ styledClient as styled }"), n = n.replace("@salty-css/react/styled", "@salty-css/react/styled-client"), n;
260
383
  }
261
- } catch (e) {
262
- console.error(e);
384
+ } catch (o) {
385
+ console.error("Error in minimizeFile:", o);
263
386
  }
264
- }, ft = (t) => ({
387
+ }, Jt = (t) => ({
265
388
  name: "stylegen",
266
- buildStart: () => nt(t),
267
- load: async (s) => {
268
- if (E(s))
269
- return await ot(t, s);
389
+ buildStart: () => Pt(t),
390
+ load: async (e) => {
391
+ if (W(e))
392
+ return await Et(t, e);
270
393
  },
271
394
  watchChange: {
272
- handler: async (s) => {
273
- E(s) && await rt(t, s), s.includes("salty-config") && await K(t);
395
+ handler: async (e) => {
396
+ W(e) && await Dt(t, e), e.includes("salty.config") && await it(t);
274
397
  }
275
398
  }
276
399
  });
277
400
  export {
278
- ft as saltyPlugin
401
+ Jt as default,
402
+ Jt as saltyPlugin
279
403
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/vite",
3
- "version": "0.0.1-alpha.13",
3
+ "version": "0.0.1-alpha.130",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.mjs",
6
6
  "typings": "./dist/index.d.ts",
@@ -10,7 +10,12 @@
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "homepage": "https://github.com/margarita-form/salty-css",
13
+ "description": "Vite plugin for Salty CSS",
14
+ "homepage": "https://salty-css.dev/",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/margarita-form/salty-css.git"
18
+ },
14
19
  "bugs": {
15
20
  "url": "https://github.com/margarita-form/salty-css/issues"
16
21
  },
@@ -27,5 +32,8 @@
27
32
  "import": "./index.js",
28
33
  "require": "./index.cjs"
29
34
  }
35
+ },
36
+ "dependencies": {
37
+ "@salty-css/core": "^0.0.1-alpha.130"
30
38
  }
31
39
  }