next-style 2.2.1 → 2.2.3

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/dist/index.d.ts CHANGED
@@ -1,9 +1,126 @@
1
1
  import { Properties, Pseudos } from 'csstype';
2
2
 
3
+ /**
4
+ * The compiled representation of a single `css({})` call.
5
+ * Produced by `StyleCollector` and consumed by the PostCSS plugin.
6
+ */
7
+ interface CompiledStyle {
8
+ /** Scoped class name, e.g. `"ns-1x2y3z"`. */
9
+ className: string;
10
+ /** Base CSS rule block for this class. */
11
+ css: string;
12
+ /** Map of normalized media query string → CSS rule block. */
13
+ mediaQueries: Record<string, string>;
14
+ /** Map of pseudo selector (e.g. `":hover"`) → CSS rule block. */
15
+ pseudoClasses: Record<string, string>;
16
+ /** Concatenated `@keyframes` blocks referenced by this style. */
17
+ keyframes: string;
18
+ /** Map of `@supports` condition → CSS rule block. */
19
+ supports: Record<string, string>;
20
+ /** Map of `@layer` name → CSS rule block. */
21
+ layers: Record<string, string>;
22
+ }
23
+ /**
24
+ * Collects, compiles, and deduplicates styles registered via `css()` and `global()`.
25
+ *
26
+ * A single shared instance is held by the runtime module. The PostCSS plugin
27
+ * calls `getAllStyles()` at build time to drain the collected CSS.
28
+ *
29
+ * @example
30
+ * const collector = new StyleCollector()
31
+ * const className = collector.addStyle({ color: 'red' }) // "ns-abc123"
32
+ * const css = collector.getAllStyles() // ".ns-abc123 { color: red; }"
33
+ */
34
+ declare class StyleCollector {
35
+ private styles;
36
+ /**
37
+ * Compiles a style object and registers it in the collector.
38
+ * Returns the same class name for identical style objects (deduplication).
39
+ *
40
+ * @param styleObj - Raw style object from a `css({})` call.
41
+ * @returns Scoped class name string.
42
+ */
43
+ addStyle(styleObj: any): string;
44
+ /**
45
+ * Registers a global style rule (no scoped class).
46
+ * Subsequent calls with the same selector are ignored (idempotent).
47
+ *
48
+ * @param selector - CSS selector string, e.g. `"body"` or `"h1, h2"`.
49
+ * @param styleObj - Style properties to apply to the selector.
50
+ */
51
+ addGlobalStyle(selector: string, styleObj: any): void;
52
+ private compileStyle;
53
+ private parseStyles;
54
+ private buildDeclarations;
55
+ /**
56
+ * Serialises all collected styles into a single CSS string.
57
+ *
58
+ * Output order:
59
+ * 1. `@keyframes` blocks
60
+ * 2. Base class rules
61
+ * 3. Pseudo-class/element rules
62
+ * 4. `@layer` blocks
63
+ * 5. `@supports` blocks
64
+ * 6. Media queries (ascending `min-width`, mobile-first)
65
+ *
66
+ * @returns Full CSS string ready to be injected or written to a file.
67
+ */
68
+ getAllStyles(): string;
69
+ private extractMinWidth;
70
+ /**
71
+ * Writes all collected styles to a temp file so the PostCSS plugin
72
+ * (which runs in a separate process) can read them.
73
+ *
74
+ * Call this after all `css()` / `global()` calls have been evaluated,
75
+ * e.g. at the end of a build-time entry point.
76
+ *
77
+ * @param filePath - Destination file path. Defaults to `os.tmpdir()/next-style.css`.
78
+ */
79
+ flush(filePath?: string): void;
80
+ /**
81
+ * Returns the default cache file path, resolved at call-time from
82
+ * `process.cwd()` so it reflects the actual working directory of the
83
+ * running process rather than the directory at module-load time.
84
+ */
85
+ static defaultCacheFile(): string;
86
+ /**
87
+ * Returns a snapshot of the internal style map.
88
+ * Intended for inspection and testing — not for direct mutation.
89
+ */
90
+ getStyleMap(): Map<string, CompiledStyle>;
91
+ }
92
+ /**
93
+ * Creates an isolated `StyleCollector` paired with a transform helper.
94
+ *
95
+ * Primarily used by SWC/Babel transforms and test harnesses that need
96
+ * a fresh collector per file or per test, independent of the shared
97
+ * runtime instance.
98
+ *
99
+ * @example
100
+ * const { collector, transformCssCall } = createTransformer()
101
+ * const className = transformCssCall({ color: 'red' })
102
+ * const css = collector.getAllStyles()
103
+ */
104
+ declare function createTransformer(): {
105
+ collector: StyleCollector;
106
+ /**
107
+ * Equivalent to calling `css()` against this transformer's isolated collector.
108
+ * @param styleObj - Raw style object.
109
+ * @returns Scoped class name string.
110
+ */
111
+ transformCssCall(styleObj: any): string;
112
+ };
113
+
114
+ /**
115
+ * CSS properties with full type safety and autocomplete via csstype.
116
+ * Accepts both string and number values (e.g. `fontSize: 16` or `fontSize: '16px'`).
117
+ */
3
118
  type CSSProperties = Properties<string | number>;
119
+ /** @internal Mapped type for pseudo-classes/elements — avoids index signature limitation */
4
120
  type PseudoStyles = {
5
121
  [P in Pseudos]?: CSSProperties;
6
122
  };
123
+ /** @internal At-rule keys (@media, @container, @supports, @layer, @keyframes) */
7
124
  type AtRuleStyles = {
8
125
  '@sm'?: CSSProperties;
9
126
  '@md'?: CSSProperties;
@@ -28,33 +145,119 @@ type AtRuleStyles = {
28
145
  * - Feature queries: `'@supports (display: grid)'`
29
146
  * - Keyframe animations: `'@keyframes fadeIn'`
30
147
  * - Cascade layers: `'@layer utilities'`
148
+ *
149
+ * @example
150
+ * const style: CSSObject = {
151
+ * fontSize: '16px',
152
+ * '@md': { fontSize: '20px' },
153
+ * ':hover': { color: 'blue' },
154
+ * '@keyframes spin': { to: { transform: 'rotate(360deg)' } },
155
+ * }
31
156
  */
32
157
  type CSSObject = CSSProperties & PseudoStyles & AtRuleStyles & {
33
158
  [key: string]: any;
34
159
  };
35
160
  /**
36
161
  * Converts a style object into a unique CSS class name.
162
+ *
37
163
  * Styles are collected at build time by the PostCSS plugin and emitted as
38
164
  * a single static CSS file — there is zero runtime overhead in production.
165
+ * Identical style objects always return the same class name (deduplication).
166
+ *
167
+ * @param styles - A `CSSObject` describing the styles for this element.
168
+ * @returns A stable class name string (e.g. `"ns-1x2y3z"`).
39
169
  *
40
170
  * @example
41
171
  * const button = css({
42
172
  * padding: '8px 16px',
173
+ * borderRadius: '6px',
43
174
  * backgroundColor: '#7F77DD',
44
175
  * ':hover': { backgroundColor: '#534AB7' },
45
176
  * '@md': { padding: '10px 20px' },
46
177
  * })
178
+ *
179
+ * export function Button() {
180
+ * return <button className={button}>Click me</button>
181
+ * }
47
182
  */
48
183
  declare function css(styles: CSSObject): string;
49
184
  /**
50
185
  * Registers global CSS styles applied directly to selectors (no scoped class).
51
186
  *
187
+ * Useful for CSS resets, base typography, and third-party element overrides.
188
+ * Like `css()`, styles are extracted at build time — no runtime cost.
189
+ *
190
+ * @param styles - A record mapping CSS selectors to `CSSObject` style definitions.
191
+ *
52
192
  * @example
53
193
  * global({
54
194
  * '*': { boxSizing: 'border-box', margin: '0' },
55
195
  * 'body': { fontFamily: 'Inter, sans-serif', lineHeight: '1.6' },
196
+ * 'h1, h2, h3': { fontWeight: 500 },
56
197
  * })
57
198
  */
58
199
  declare function global(styles: Record<string, CSSObject>): void;
59
200
 
60
- export { type CSSObject, css, global };
201
+ declare const collector: StyleCollector;
202
+
203
+ /**
204
+ * Converts a camelCase CSS property name to kebab-case.
205
+ *
206
+ * @param str - camelCase string, e.g. `"backgroundColor"`.
207
+ * @returns kebab-case string, e.g. `"background-color"`.
208
+ *
209
+ * @example
210
+ * camelToKebab('fontSize') // "font-size"
211
+ * camelToKebab('borderTopWidth') // "border-top-width"
212
+ */
213
+ declare function camelToKebab(str: string): string;
214
+ /**
215
+ * Generates a short, stable hash string from a style object or string.
216
+ * Used to produce unique class name suffixes (e.g. `"ns-1x2y3z"`).
217
+ *
218
+ * @param styles - Style object or pre-serialised string.
219
+ * @returns Base-36 hash string.
220
+ */
221
+ declare function generateClassHash(styles: any): string;
222
+ /**
223
+ * Shorthand breakpoint aliases mapped to their full `@media` query strings.
224
+ *
225
+ * | Key | Expands to |
226
+ * |--------|-------------------------------------|
227
+ * | `@sm` | `@media (min-width: 640px)` |
228
+ * | `@md` | `@media (min-width: 768px)` |
229
+ * | `@lg` | `@media (min-width: 1024px)` |
230
+ * | `@xl` | `@media (min-width: 1280px)` |
231
+ * | `@2xl` | `@media (min-width: 1536px)` |
232
+ */
233
+ declare const BREAKPOINTS: Record<string, string>;
234
+ /**
235
+ * Resolves a breakpoint shorthand to its full `@media` query string.
236
+ * Passes through unrecognised strings unchanged.
237
+ *
238
+ * @param query - Shorthand key (e.g. `"@md"`) or an arbitrary media query.
239
+ * @returns Full media query string (e.g. `"@media (min-width: 768px)"`).
240
+ *
241
+ * @example
242
+ * normalizeMediaQuery('@md') // "@media (min-width: 768px)"
243
+ * normalizeMediaQuery('@media (max-width: 600px)') // "@media (max-width: 600px)"
244
+ */
245
+ declare function normalizeMediaQuery(query: string): string;
246
+ /**
247
+ * Returns `true` if the value is a valid CSS property value that can be
248
+ * serialised to a declaration (string, number, or nested object).
249
+ *
250
+ * @param _key - CSS property name (unused, reserved for future validation).
251
+ * @param value - Value to check.
252
+ */
253
+ declare function validateCSSProperty(_key: string, value: any): boolean;
254
+ /**
255
+ * Removes duplicate entries from a style map, keeping the first occurrence.
256
+ * Two entries are considered duplicates when their serialised values are identical.
257
+ *
258
+ * @param styles - Map of class name → style data.
259
+ * @returns New map with duplicates removed.
260
+ */
261
+ declare function deduplicateStyles(styles: Map<string, any>): Map<string, any>;
262
+
263
+ export { BREAKPOINTS, type CSSObject, type CSSProperties, type CompiledStyle, StyleCollector, camelToKebab, createTransformer, css, deduplicateStyles, generateClassHash, global, normalizeMediaQuery, collector as styleCollector, validateCSSProperty };
package/dist/index.js CHANGED
@@ -1,31 +1,31 @@
1
- var b=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,s)=>(typeof require<"u"?require:e)[s]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});function E(n){return n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function C(n){let e=typeof n=="string"?n:JSON.stringify(n),s=2166136261;for(let r=0;r<e.length;r++)s^=e.charCodeAt(r),s=s*16777619>>>0;return s.toString(36)}var R={"@sm":"@media (min-width: 640px)","@md":"@media (min-width: 768px)","@lg":"@media (min-width: 1024px)","@xl":"@media (min-width: 1280px)","@2xl":"@media (min-width: 1536px)"};function w(n){return R[n]??n}var u=class n{constructor(){this.styles=new Map}addStyle(e){let r=`ns-${C(e)}`;if(this.styles.has(r))return r;let t=this.compileStyle(e);return this.styles.set(r,t),r}addGlobalStyle(e,s){let r=`global:${e}`;if(this.styles.has(r))return;let t=this.buildDeclarations(s);t&&this.styles.set(r,{className:r,css:`${e} {
2
- ${t}}`,mediaQueries:{},pseudoClasses:{},keyframes:"",supports:{},layers:{}})}compileStyle(e){let{mediaQueries:s,pseudoClasses:r,normalStyles:t,keyframes:l,supports:y,container:f,layer:g}=this.parseStyles(e),o=`ns-${C(e)}`,$=this.buildDeclarations(t),A=`.${o} {
3
- ${$}}`,p={};Object.entries(s).forEach(([c,d])=>{let a=w(c),m=this.buildDeclarations(d," ");if(p[a]){let D=p[a].split(`
1
+ import A from"fs";import D from"path";function P(n){return n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function b(n){let e=typeof n=="string"?n:JSON.stringify(n),t=0;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);t=(t<<5)-t+s,t=t&t}return Math.abs(t).toString(36)}var C={"@sm":"@media (min-width: 640px)","@md":"@media (min-width: 768px)","@lg":"@media (min-width: 1024px)","@xl":"@media (min-width: 1280px)","@2xl":"@media (min-width: 1536px)"};function O(n){return C[n]??n}function W(n,e){return typeof e=="string"||typeof e=="number"||typeof e=="object"&&!Array.isArray(e)}function T(n){let e=new Map,t=new Set;return n.forEach((r,s)=>{let l=JSON.stringify(r);t.has(l)||(t.add(l),e.set(s,r))}),e}var y=class n{constructor(){this.styles=new Map}addStyle(e){let r=`ns-${b(e)}`;if(this.styles.has(r))return r;let s=this.compileStyle(e);return this.styles.set(r,s),r}addGlobalStyle(e,t){let r=`global:${e}`;if(this.styles.has(r))return;let s=this.buildDeclarations(t);s&&this.styles.set(r,{className:r,css:`${e} {
2
+ ${s}}`,mediaQueries:{},pseudoClasses:{},keyframes:"",supports:{},layers:{}})}compileStyle(e){let{mediaQueries:t,pseudoClasses:r,normalStyles:s,keyframes:l,supports:m,container:f,layer:h}=this.parseStyles(e),o=`ns-${b(e)}`,$=this.buildDeclarations(s),N=`.${o} {
3
+ ${$}}`,p={};Object.entries(t).forEach(([c,d])=>{let a=O(c),S=this.buildDeclarations(d," ");if(p[a]){let Q=p[a].split(`
4
4
  `).slice(2,-2).join(`
5
5
  `);p[a]=`${a} {
6
6
  .${o} {
7
- ${D}
8
- ${m} }
7
+ ${Q}
8
+ ${S} }
9
9
  }`}else p[a]=`${a} {
10
10
  .${o} {
11
- ${m} }
11
+ ${S} }
12
12
  }`}),Object.entries(f).forEach(([c,d])=>{let a=this.buildDeclarations(d," ");p[c]=`${c} {
13
13
  .${o} {
14
14
  ${a} }
15
- }`});let x={};Object.entries(r).forEach(([c,d])=>{let a=this.buildDeclarations(d);x[c]=`.${o}${c} {
16
- ${a}}`});let h="";Object.entries(l).forEach(([c,d])=>{h+=`@keyframes ${c} {
17
- `,Object.entries(d).forEach(([a,m])=>{let O=this.buildDeclarations(m," ");h+=` ${a} {
18
- ${O} }
19
- `}),h+=`}
20
- `});let P={};Object.entries(y).forEach(([c,d])=>{let a=this.buildDeclarations(d," ");P[c]=`@supports ${c} {
15
+ }`});let j={};Object.entries(r).forEach(([c,d])=>{let a=this.buildDeclarations(d);j[c]=`.${o}${c} {
16
+ ${a}}`});let u="";Object.entries(l).forEach(([c,d])=>{u+=`@keyframes ${c} {
17
+ `,Object.entries(d).forEach(([a,S])=>{let M=this.buildDeclarations(S," ");u+=` ${a} {
18
+ ${M} }
19
+ `}),u+=`}
20
+ `});let E={};Object.entries(m).forEach(([c,d])=>{let a=this.buildDeclarations(d," ");E[c]=`@supports ${c} {
21
21
  .${o} {
22
22
  ${a} }
23
- }`});let j={};return Object.entries(g).forEach(([c,d])=>{let a=this.buildDeclarations(d," ");j[c]=`@layer ${c} {
24
- ${a}}`}),{className:o,css:A,mediaQueries:p,pseudoClasses:x,keyframes:h,supports:P,layers:j}}parseStyles(e){let s={},r={},t={},l={},y={},f={},g={};return Object.entries(e).forEach(([i,o])=>{if(i.startsWith("@keyframes "))l[i.slice(11)]=o;else if(i==="@keyframes"&&typeof o=="object")Object.assign(l,o);else if(i.startsWith("@supports")){let $=i.slice(0,9)==="@supports"?i.slice(9).trim():i;y[$]=o}else i.startsWith("@container")?f[i]=o:i.startsWith("@layer")?g[i.slice(7)||"default"]=o:i in R||i.startsWith("@media")?r[i]=o:i.startsWith(":")||i.startsWith("::")?t[i]=o:s[i]=o}),{normalStyles:s,mediaQueries:r,pseudoClasses:t,keyframes:l,supports:y,container:f,layer:g}}buildDeclarations(e,s=" "){let r="";return Object.entries(e).forEach(([t,l])=>{(typeof l=="string"||typeof l=="number")&&(r+=`${s}${E(t)}: ${l};
25
- `)}),r}getAllStyles(){let e="";return this.styles.forEach(s=>{s.keyframes&&(e+=`${s.keyframes}
26
- `),s.css&&(e+=`${s.css}
27
- `),Object.values(s.pseudoClasses).forEach(t=>{e+=`${t}
28
- `}),Object.values(s.layers).forEach(t=>{e+=`${t}
29
- `}),Object.values(s.supports).forEach(t=>{e+=`${t}
30
- `}),Object.entries(s.mediaQueries).sort(([t],[l])=>this.extractMinWidth(t)-this.extractMinWidth(l)).forEach(([,t])=>{e+=`${t}
31
- `})}),e}extractMinWidth(e){let s=e.match(/min-width:\s*(\d+)px/);return s?parseInt(s[1],10):0}flush(e){if(!(typeof window<"u"))try{let s=b("fs"),r=b("path"),t=e??n.defaultCacheFile();s.mkdirSync(r.dirname(t),{recursive:!0}),s.writeFileSync(t,this.getAllStyles(),"utf-8")}catch(s){console.error("[next-style] Failed to flush styles to cache file:",s)}}static defaultCacheFile(){return b("path").join(process.cwd(),"node_modules",".cache","next-style","styles.css")}getStyleMap(){return new Map(this.styles)}};function W(n){let e=S.addStyle(n);return typeof window>"u"&&S.flush(),e}function M(n){Object.entries(n).forEach(([e,s])=>{S.addGlobalStyle(e,s)}),typeof window>"u"&&S.flush()}var S=new u;export{W as css,M as global};
23
+ }`});let w={};return Object.entries(h).forEach(([c,d])=>{let a=this.buildDeclarations(d," ");w[c]=`@layer ${c} {
24
+ ${a}}`}),{className:o,css:N,mediaQueries:p,pseudoClasses:j,keyframes:u,supports:E,layers:w}}parseStyles(e){let t={},r={},s={},l={},m={},f={},h={};return Object.entries(e).forEach(([i,o])=>{if(i.startsWith("@keyframes "))l[i.slice(11)]=o;else if(i==="@keyframes"&&typeof o=="object")Object.assign(l,o);else if(i.startsWith("@supports")){let $=i.slice(0,9)==="@supports"?i.slice(9).trim():i;m[$]=o}else i.startsWith("@container")?f[i]=o:i.startsWith("@layer")?h[i.slice(7)||"default"]=o:i in C||i.startsWith("@media")?r[i]=o:i.startsWith(":")||i.startsWith("::")?s[i]=o:t[i]=o}),{normalStyles:t,mediaQueries:r,pseudoClasses:s,keyframes:l,supports:m,container:f,layer:h}}buildDeclarations(e,t=" "){let r="";return Object.entries(e).forEach(([s,l])=>{(typeof l=="string"||typeof l=="number")&&(r+=`${t}${P(s)}: ${l};
25
+ `)}),r}getAllStyles(){let e="";return this.styles.forEach(t=>{t.keyframes&&(e+=`${t.keyframes}
26
+ `),t.css&&(e+=`${t.css}
27
+ `),Object.values(t.pseudoClasses).forEach(s=>{e+=`${s}
28
+ `}),Object.values(t.layers).forEach(s=>{e+=`${s}
29
+ `}),Object.values(t.supports).forEach(s=>{e+=`${s}
30
+ `}),Object.entries(t.mediaQueries).sort(([s],[l])=>this.extractMinWidth(s)-this.extractMinWidth(l)).forEach(([,s])=>{e+=`${s}
31
+ `})}),e}extractMinWidth(e){let t=e.match(/min-width:\s*(\d+)px/);return t?parseInt(t[1],10):0}flush(e){try{let t=e??n.defaultCacheFile();A.mkdirSync(D.dirname(t),{recursive:!0}),A.writeFileSync(t,this.getAllStyles(),"utf-8")}catch(t){console.error("Failed to flush styles to cache file:",t)}}static defaultCacheFile(){return D.join(process.cwd(),"node_modules",".cache","next-style","styles.css")}getStyleMap(){return new Map(this.styles)}};function K(){let n=new y;return{collector:n,transformCssCall(e){return n.addStyle(e)}}}function z(n){let e=g.addStyle(n);return g.flush(),e}function F(n){Object.entries(n).forEach(([e,t])=>{g.addGlobalStyle(e,t)}),g.flush()}var g=new y;export{C as BREAKPOINTS,y as StyleCollector,P as camelToKebab,K as createTransformer,z as css,T as deduplicateStyles,b as generateClassHash,F as global,O as normalizeMediaQuery,g as styleCollector,W as validateCSSProperty};