@tbela99/css-parser 1.4.2 → 1.4.4

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 (122) hide show
  1. package/CHANGELOG.md +354 -4
  2. package/README.md +69 -1077
  3. package/dist/config.json.js +76 -3
  4. package/dist/index-umd-web.js +26838 -18743
  5. package/dist/index.cjs +26819 -18731
  6. package/dist/index.d.ts +2471 -1884
  7. package/dist/lib/ast/clone.js +46 -0
  8. package/dist/lib/ast/expand.js +90 -65
  9. package/dist/lib/ast/features/calc.js +86 -43
  10. package/dist/lib/ast/features/if.js +221 -0
  11. package/dist/lib/ast/features/index.js +1 -0
  12. package/dist/lib/ast/features/inlinecssvariables.js +33 -28
  13. package/dist/lib/ast/features/prefix.js +406 -44
  14. package/dist/lib/ast/features/shorthand.js +6 -9
  15. package/dist/lib/ast/features/transform.js +14 -15
  16. package/dist/lib/ast/find.js +175 -0
  17. package/dist/lib/ast/math/expression.js +145 -99
  18. package/dist/lib/ast/math/math.js +30 -41
  19. package/dist/lib/ast/minify.js +551 -232
  20. package/dist/lib/ast/transform/compute.js +82 -69
  21. package/dist/lib/ast/transform/matrix.js +12 -26
  22. package/dist/lib/ast/transform/minify.js +154 -150
  23. package/dist/lib/ast/transform/perspective.js +1 -1
  24. package/dist/lib/ast/transform/rotate.js +1 -1
  25. package/dist/lib/ast/transform/scale.js +1 -1
  26. package/dist/lib/ast/transform/skew.js +1 -1
  27. package/dist/lib/ast/transform/translate.js +1 -1
  28. package/dist/lib/ast/transform/utils.js +3 -2
  29. package/dist/lib/ast/types.js +345 -30
  30. package/dist/lib/ast/walk.js +119 -64
  31. package/dist/lib/fs/resolve.js +94 -88
  32. package/dist/lib/parser/declaration/list.js +117 -26
  33. package/dist/lib/parser/declaration/map.js +141 -96
  34. package/dist/lib/parser/declaration/set.js +30 -25
  35. package/dist/lib/parser/parse.js +1810 -1739
  36. package/dist/lib/parser/tokenize.js +662 -403
  37. package/dist/lib/parser/utils/angle.js +29 -0
  38. package/dist/lib/parser/utils/at-rule-container.js +486 -0
  39. package/dist/lib/parser/utils/at-rule-font-feature-values.js +13 -0
  40. package/dist/lib/parser/utils/at-rule-generic.js +118 -0
  41. package/dist/lib/parser/utils/at-rule-import.js +393 -0
  42. package/dist/lib/parser/utils/at-rule-media.js +603 -0
  43. package/dist/lib/parser/utils/at-rule-support.js +431 -0
  44. package/dist/lib/parser/utils/at-rule-when-else.js +363 -0
  45. package/dist/lib/parser/utils/at-rule.js +31 -0
  46. package/dist/lib/parser/utils/cache.js +19 -0
  47. package/dist/lib/parser/utils/config.js +1 -0
  48. package/dist/lib/parser/utils/declaration.js +672 -91
  49. package/dist/lib/parser/utils/hash.js +1 -1
  50. package/dist/lib/parser/utils/selector.js +518 -0
  51. package/dist/lib/parser/utils/text.js +17 -1
  52. package/dist/lib/parser/utils/token.js +104 -0
  53. package/dist/lib/parser/utils/type.js +29 -18
  54. package/dist/lib/renderer/render.js +870 -269
  55. package/dist/lib/renderer/sourcemap/sourcemap.js +17 -7
  56. package/dist/lib/syntax/color/a98rgb.js +8 -12
  57. package/dist/lib/syntax/color/alpha.js +64 -0
  58. package/dist/lib/syntax/color/cmyk.js +23 -21
  59. package/dist/lib/syntax/color/color-mix.js +311 -237
  60. package/dist/lib/syntax/color/color.js +98 -92
  61. package/dist/lib/syntax/color/hex.js +29 -33
  62. package/dist/lib/syntax/color/hsl.js +7 -14
  63. package/dist/lib/syntax/color/hwb.js +14 -27
  64. package/dist/lib/syntax/color/lab.js +23 -24
  65. package/dist/lib/syntax/color/lch.js +16 -18
  66. package/dist/lib/syntax/color/oklab.js +21 -40
  67. package/dist/lib/syntax/color/oklch.js +16 -18
  68. package/dist/lib/syntax/color/p3.js +0 -8
  69. package/dist/lib/syntax/color/rec2020.js +9 -13
  70. package/dist/lib/syntax/color/relativecolor.js +160 -48
  71. package/dist/lib/syntax/color/rgb.js +14 -18
  72. package/dist/lib/syntax/color/srgb.js +30 -29
  73. package/dist/lib/syntax/color/utils/color-type.js +18 -0
  74. package/dist/lib/syntax/color/utils/colorspace.js +46 -0
  75. package/dist/lib/syntax/color/utils/components.js +36 -16
  76. package/dist/lib/syntax/color/utils/distance.js +21 -11
  77. package/dist/lib/syntax/color/utils/make-color.js +56 -0
  78. package/dist/lib/syntax/color/xyz.js +10 -22
  79. package/dist/lib/syntax/color/xyzd50.js +6 -20
  80. package/dist/lib/syntax/constants.js +464 -0
  81. package/dist/lib/syntax/syntax.js +825 -592
  82. package/dist/lib/validation/config.js +72 -33
  83. package/dist/lib/validation/config.json.js +1185 -85
  84. package/dist/lib/validation/match.js +3120 -0
  85. package/dist/lib/validation/parser/parse.js +683 -935
  86. package/dist/lib/validation/parser/typedef.js +106 -0
  87. package/dist/lib/validation/utils/list.js +4 -11
  88. package/dist/lib/validation/utils/whitespace.js +2 -8
  89. package/dist/node.js +102 -57
  90. package/dist/web.js +100 -48
  91. package/package.json +31 -17
  92. package/dist/lib/syntax/color/utils/constants.js +0 -214
  93. package/dist/lib/syntax/utils.js +0 -70
  94. package/dist/lib/validation/at-rules/container.js +0 -342
  95. package/dist/lib/validation/at-rules/counter-style.js +0 -90
  96. package/dist/lib/validation/at-rules/custom-media.js +0 -50
  97. package/dist/lib/validation/at-rules/document.js +0 -89
  98. package/dist/lib/validation/at-rules/else.js +0 -5
  99. package/dist/lib/validation/at-rules/font-feature-values.js +0 -63
  100. package/dist/lib/validation/at-rules/import.js +0 -150
  101. package/dist/lib/validation/at-rules/keyframes.js +0 -67
  102. package/dist/lib/validation/at-rules/layer.js +0 -41
  103. package/dist/lib/validation/at-rules/media.js +0 -255
  104. package/dist/lib/validation/at-rules/namespace.js +0 -81
  105. package/dist/lib/validation/at-rules/page-margin-box.js +0 -64
  106. package/dist/lib/validation/at-rules/page.js +0 -100
  107. package/dist/lib/validation/at-rules/supports.js +0 -295
  108. package/dist/lib/validation/at-rules/when.js +0 -185
  109. package/dist/lib/validation/atrule.js +0 -184
  110. package/dist/lib/validation/selector.js +0 -36
  111. package/dist/lib/validation/syntax.js +0 -1073
  112. package/dist/lib/validation/syntaxes/complex-selector-list.js +0 -27
  113. package/dist/lib/validation/syntaxes/complex-selector.js +0 -52
  114. package/dist/lib/validation/syntaxes/compound-selector.js +0 -196
  115. package/dist/lib/validation/syntaxes/family-name.js +0 -57
  116. package/dist/lib/validation/syntaxes/keyframe-selector.js +0 -36
  117. package/dist/lib/validation/syntaxes/layer-name.js +0 -57
  118. package/dist/lib/validation/syntaxes/relative-selector-list.js +0 -31
  119. package/dist/lib/validation/syntaxes/relative-selector.js +0 -38
  120. package/dist/lib/validation/syntaxes/selector-list.js +0 -5
  121. package/dist/lib/validation/syntaxes/selector.js +0 -5
  122. package/dist/lib/validation/syntaxes/url.js +0 -40
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  [![playground](https://img.shields.io/badge/playground-try%20it%20now-%230a7398
2
2
  )](https://tbela99.github.io/css-parser/playground/) [![npm](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Ftbela99%2Fcss-parser%2Fmaster%2Fpackage.json&query=version&logo=npm&label=npm&link=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40tbela99%2Fcss-parser)](https://www.npmjs.com/package/@tbela99/css-parser) [![npm](https://img.shields.io/jsr/v/%40tbela99/css-parser?link=https%3A%2F%2Fjsr.io%2F%40tbela99%2Fcss-parser
3
- )](https://jsr.io/@tbela99/css-parser) [![cov](https://tbela99.github.io/css-parser/badges/coverage.svg)](https://github.com/tbela99/css-parser/actions) [![Doc](https://img.shields.io/badge/online-documentation-blue)](https://tbela99.github.io/css-parser/docs) [![NPM Downloads](https://img.shields.io/npm/dm/%40tbela99%2Fcss-parser)](https://www.npmjs.com/package/@tbela99/css-parser) [![bundle size](https://img.shields.io/bundlejs/size/%40tbela99/css-parser%400.9.0?exports=cjs)](https://www.npmjs.com/package/@tbela99/css-parser)
3
+ )](https://jsr.io/@tbela99/css-parser) [![cov](https://tbela99.github.io/css-parser/badges/coverage.svg)](https://github.com/tbela99/css-parser/actions) [![Doc](https://tbela99.github.io/css-parser/docs/coverage.svg)](https://tbela99.github.io/css-parser/docs) [![NPM Downloads](https://img.shields.io/npm/dm/%40tbela99%2Fcss-parser)](https://www.npmjs.com/package/@tbela99/css-parser) [![bundle size](https://img.shields.io/bundlejs/size/%40tbela99/css-parser%400.9.0?exports=cjs)](https://www.npmjs.com/package/@tbela99/css-parser)
4
4
 
5
5
  # css-parser
6
6
 
7
- CSS parser, minifier and validator for node and the browser
7
+ CSS parser, transformer, minifier and validator for node and the browser
8
8
 
9
9
  ## Installation
10
10
 
@@ -22,809 +22,68 @@ $ deno add @tbela99/css-parser
22
22
 
23
23
  ## Features
24
24
 
25
- - no dependency
26
- - CSS validation based upon mdn-data
27
- - CSS modules support
28
- - fault-tolerant parser implementing the CSS syntax module 3 recommendations.
29
- - fast and efficient minification without unsafe transforms,
30
- see [benchmark](https://tbela99.github.io/css-parser/benchmark/index.html)
31
- - colors minification: color(), lab(), lch(), oklab(), oklch(), color-mix(), light-dark(), system colors and
32
- relative color
33
- - color conversion to any supported color format
34
- - automatic nested css rules generation
35
- - nested css rules conversion to legacy syntax
36
- - sourcemap generation
37
- - css shorthands computation. see the supported properties list below
38
- - css transform functions minification
39
- - css math functions evaluation: calc(), clamp(), min(), max(), etc.
40
- - css variables inlining
41
- - duplicate properties removal
42
- - @import rules flattening
43
- - experimental CSS prefix removal
44
-
45
- ## Online documentation
46
-
47
- See the full documentation at the [CSS Parser](https://tbela99.github.io/css-parser/docs) documentation site
25
+ * **Zero dependencies** — lightweight and easy to integrate into any project.
26
+ * **Standards-based CSS validation** powered by MDN data.
27
+ * **Full CSS Modules support** for modern component-based workflows.
28
+ * **Fault-tolerant parsing** that follows the CSS Syntax Module Level 3 specification.
29
+ * **High-performance minification** with safe optimizations and no unsafe transforms.
30
+ * **Advanced color processing** with support for modern color spaces and functions, including `color()`, `lab()`, `lch()`, `oklab()`, `oklch()`, `color-mix()`, `light-dark()`, system colors, and relative colors.
31
+ * **Color conversion engine** capable of transforming colors between all supported formats.
32
+ * **Automatic CSS nesting generation** from compatible selectors.
33
+ * **Source map generation** for easier debugging and development workflows.
34
+ * **Shorthand property computation** to reduce output size and improve optimization.
35
+ * **Transform function optimization** for more compact CSS output.
36
+ * **Math function evaluation**, including `calc()`, `clamp()`, `min()`, `max()`, and related expressions.
37
+ * **CSS variable inlining** where values can be safely resolved.
38
+ * **Duplicate declaration removal** to eliminate redundant rules.
39
+ * **`@import` flattening** to produce self-contained stylesheets.
40
+
41
+ ## Vendor prefix removal
42
+ **Experimental vendor prefix cleanup** to modernize generated CSS.
43
+
44
+ ## Syntax lowering
45
+ CSS-Parser can transform these modern CSS features into lower-level CSS syntax:
46
+ * **Nested CSS transpilation** to legacy-compatible syntax.
47
+ * **`if()` function transpilation** for broader browser compatibility.
48
+ * **`color-mix()` function conversion** convert new color-mix() syntax to any of the supported colors.
49
+
50
+ ## Benchmark
51
+
52
+ Across all tested datasets, css-parser consistently produces the smallest output among the benchmarked tools, including Lightning CSS, cssnano, csso, clean-css, css-tree, and esbuild.
53
+
54
+ The [benchmark](https://tbela99.github.io/css-parser/benchmark/index.html) evaluates minification effectiveness on a diverse set of real-world stylesheets, including Bootstrap 4, Bootstrap 5, Tailwind CSS, Animate.css, Foundation, Font Awesome, Normalize.css, and others.
55
+
56
+ A sample result:
57
+
58
+ | File | ligthningcss | CSS Parser |
59
+ | ------------------------------ | ------------- | ------------- |
60
+ | tailwind.css - 2380419 bytes | 1864728 bytes | 1633251 bytes |
61
+ | bootstrap-4.css - 200078 bytes | 153616 bytes | 144700 bytes |
62
+ | bootstrap-5.css - 205481 bytes | 159987 bytes | 151258 bytes |
63
+
64
+ On the [complete benchmark suite](https://tbela99.github.io/css-parser/benchmark/index.html), css-parser generated a total output size of 2,204,888 bytes, compared to 2,494,113 bytes for Lightning CSS and larger outputs for all other tested minifiers.
65
+ While some tools prioritize raw execution speed, css-parser focuses on maximizing compression while preserving stylesheet semantics, resulting in consistently smaller production bundles.
48
66
 
49
67
  ## Playground
50
68
 
51
69
  Try it [online](https://tbela99.github.io/css-parser/playground/)
52
70
 
53
- ## Import
54
-
55
- There are several ways to import the library into your application.
56
-
57
- ### Node
58
-
59
- import as a module
60
-
61
- ```javascript
62
-
63
- import {transform} from '@tbela99/css-parser';
64
-
65
- // ...
66
- ```
67
-
68
- ### Deno
69
-
70
- import as a module
71
-
72
- ```javascript
73
-
74
- import {transform} from '@tbela99/css-parser';
75
-
76
- // ...
77
- ```
78
-
79
- import as a CommonJS module
80
-
81
- ```javascript
82
-
83
- const {transform} = require('@tbela99/css-parser/cjs');
84
-
85
- // ...
86
- ```
87
-
88
- ### Web
89
-
90
- Programmatic import
91
-
92
- ```javascript
93
-
94
- import {transform} from '@tbela99/css-parser/web';
95
-
96
- // ...
97
- ```
98
-
99
- Javascript module from cdn
100
-
101
- ```html
102
-
103
- <script type="module">
104
-
105
- import {transform} from 'https://esm.sh/@tbela99/css-parser@1.3.4/web';
106
-
107
- const css = `
108
- .s {
109
-
110
- background: color-mix(in hsl, color(display-p3 0 1 0) 80%, yellow);
111
- }
112
- `;
113
-
114
- console.debug(await transform(css).then(r => r.code));
115
-
116
- </script>
117
- ```
118
-
119
- Javascript module
120
-
121
- ```javascript
122
-
123
- <script src="dist/web.js" type="module"></script>
124
- ```
125
-
126
- Javascript umd module from cdn
127
-
128
- ```html
129
-
130
- <script src="https://unpkg.com/@tbela99/css-parser@1.3.4/dist/index-umd-web.js"></script>
131
- <script>
132
-
133
- (async () => {
134
-
135
- const css = `
136
-
137
- .table {
138
- border-collapse: collapse;
139
- width: 100%;
140
- }
141
-
142
- .table td, .table th {
143
- border: 1px solid #ddd;
144
- padding: 8px;
145
- }
146
-
147
- .table tr:nth-child(even){background-color: #f2f2f2;}
148
-
149
- .table tr:hover {background-color: #ddd;}
150
-
151
- .table th {
152
- padding-top: 12px;
153
- padding-bottom: 12px;
154
- text-align: left;
155
- background-color: #4CAF50;
156
- color: white;
157
- }
158
- `;
159
-
160
- console.debug(await CSSParser.transform(css, {beautify: true, convertColor: CSSParser.ColorType.OKLCH}).then(r => r.code));
161
- })();
162
-
163
- </script>
164
- ```
165
-
166
- ## Exported functions
167
-
168
- ```ts
169
-
170
- /* parse and render css */
171
- transform(css: string | ReadableStream<string>, options?: TransformOptions = {}): Promise<TransformResult>
172
- /* parse css */
173
- parse(css: string | ReadableStream<string>, options?: ParseOptions = {}): Promise<ParseResult>;
174
- /* render ast */
175
- render(ast: AstNode, options?: RenderOptions = {}): RenderResult;
176
- /* parse and render css file or url */
177
- transformFile(filePathOrUrl: string, options?: TransformOptions = {}, asStream?: boolean): Promise<TransformResult>;
178
- /* parse css file or url */
179
- parseFile(filePathOrUrl: string, options?: ParseOptions = {}, asStream?: boolean): Promise<ParseResult>;
180
-
181
- ```
182
-
183
- ## Transform
184
-
185
- Parse and render css in a single pass.
186
-
187
- ### Example
188
-
189
- ```javascript
190
-
191
- import {transform} from '@tbela99/css-parser';
192
-
193
- const {ast, code, map, errors, stats} = await transform(css, {minify: true, resolveImport: true, cwd: 'files/css'});
194
- ```
195
-
196
- ### Example
197
-
198
- Read from stdin with node using readable stream
199
-
200
- ```typescript
201
- import {transform} from "../src/node";
202
- import {Readable} from "node:stream";
203
- import type {TransformResult} from '../src/@types/index.d.ts';
204
-
205
- const readableStream: ReadableStream<string> = Readable.toWeb(process.stdin) as ReadableStream<string>;
206
- const result: TransformResult = await transform(readableStream, {beautify: true});
207
-
208
- console.log(result.code);
209
- ```
210
-
211
- ### TransformOptions
212
-
213
- Include ParseOptions and RenderOptions
214
-
215
- #### ParseOptions
216
-
217
- > Minify Options
218
-
219
- - minify: boolean, optional. default to _true_. optimize ast.
220
- - pass: number, optional. minification passes. default to 1
221
- - nestingRules: boolean, optional. automatically generated nested rules.
222
- - expandNestingRules: boolean, optional. convert nesting rules into separate rules. will automatically set nestingRules
223
- to false.
224
- - removeDuplicateDeclarations: boolean, optional. remove duplicate declarations.
225
- - computeTransform: boolean, optional. compute css transform functions.
226
- - computeShorthand: boolean, optional. compute shorthand properties.
227
- - computeCalcExpression: boolean, optional. evaluate calc() expression
228
- - inlineCssVariables: boolean, optional. replace some css variables with their actual value. they must be declared once
229
- in the :root {} or html {} rule.
230
- - removeEmpty: boolean, optional. remove empty rule lists from the ast.
231
-
232
- > CSS modules Options
233
-
234
- - module: boolean | ModuleCaseTransformEnum | ModuleScopeEnumOptions | ModuleOptions, optional. css modules options.
235
-
236
- > CSS Prefix Removal Options
237
-
238
- - removePrefix: boolean, optional. remove CSS prefixes.
239
-
240
- > Validation Options
241
-
242
- - validation: ValidationLevel | boolean, optional. enable validation. permitted values are:
243
- - ValidationLevel.None: no validation
244
- - ValidationLevel.Default: validate selectors and at-rules (default)
245
- - ValidationLevel.All. validate all nodes
246
- - true: same as ValidationLevel.All.
247
- - false: same as ValidationLevel.None
248
- - lenient: boolean, optional. preserve invalid tokens.
249
-
250
- > Sourcemap Options
251
-
252
- - src: string, optional. original css file location to be used with sourcemap, also used to resolve url().
253
- - sourcemap: boolean, optional. preserve node location data.
254
-
255
- > Ast Traversal Options
256
-
257
- - visitor: VisitorNodeMap, optional. node visitor used to transform the ast.
258
-
259
- > Urls and \@import Options
260
-
261
- - resolveImport: boolean, optional. replace @import rule by the content of the referenced stylesheet.
262
- - resolveUrls: boolean, optional. resolve css 'url()' according to the parameters 'src' and 'cwd'
263
-
264
- > Misc Options
265
- - removeCharset: boolean, optional. remove @charset.
266
- - cwd: string, optional. destination directory used to resolve url().
267
- - signal: AbortSignal, optional. abort parsing.
268
-
269
- #### RenderOptions
270
-
271
- > Minify Options
272
-
273
- - beautify: boolean, optional. default to _false_. beautify css output.
274
- - minify: boolean, optional. default to _true_. minify css values.
275
- - withParents: boolean, optional. render this node and its parents.
276
- - removeEmpty: boolean, optional. remove empty rule lists from the ast.
277
- - expandNestingRules: boolean, optional. expand nesting rules.
278
- - preserveLicense: boolean, force preserving comments starting with '/\*!' when minify is enabled.
279
- - removeComments: boolean, remove comments in generated css.
280
- - convertColor: boolean | ColorType, convert colors to the specified color. default to ColorType.HEX. supported values are:
281
- - true: same as ColorType.HEX
282
- - false: no color conversion
283
- - ColorType.HEX
284
- - ColorType.RGB or ColorType.RGBA
285
- - ColorType.HSL
286
- - ColorType.HWB
287
- - ColorType.CMYK or ColorType.DEVICE_CMYK
288
- - ColorType.SRGB
289
- - ColorType.SRGB_LINEAR
290
- - ColorType.DISPLAY_P3
291
- - ColorType.PROPHOTO_RGB
292
- - ColorType.A98_RGB
293
- - ColorType.REC2020
294
- - ColorType.XYZ or ColorType.XYZ_D65
295
- - ColorType.XYZ_D50
296
- - ColorType.LAB
297
- - ColorType.LCH
298
- - ColorType.OKLAB
299
- - ColorType.OKLCH
300
-
301
- > Sourcemap Options
302
-
303
- - sourcemap: boolean | 'inline', optional. generate sourcemap.
304
-
305
- > Misc Options
306
-
307
- - indent: string, optional. css indention string. uses space character by default.
308
- - newLine: string, optional. new line character.
309
- - output: string, optional. file where to store css. url() are resolved according to the specified value. no file is
310
- created though.
311
- - cwd: string, optional. destination directory used to resolve url().
312
-
313
- ## Parsing
314
-
315
- ### Usage
316
-
317
- ```javascript
318
-
319
- parse(css, parseOptions = {})
320
- ```
321
-
322
- ### Example
323
-
324
- ````javascript
325
-
326
- const {ast, errors, stats} = await parse(css);
327
- ````
328
-
329
- ## Rendering
330
-
331
- ### Usage
332
-
333
- ```javascript
334
- render(ast, RenderOptions = {});
335
- ```
336
-
337
- ### Examples
338
-
339
- Rendering ast
340
-
341
- ```javascript
342
- import {parse, render} from '@tbela99/css-parser';
343
-
344
- const css = `
345
- @media screen and (min-width: 40em) {
346
- .featurette-heading {
347
- font-size: 50px;
348
- }
349
- .a {
350
- color: red;
351
- width: 3px;
352
- }
353
- }
354
- `;
355
-
356
- const result = await parse(css, options);
357
-
358
- // print declaration without parents
359
- console.error(render(result.ast.chi[0].chi[1].chi[1], {withParents: false}));
360
- // -> width:3px
361
-
362
- // print declaration with parents
363
- console.debug(render(result.ast.chi[0].chi[1].chi[1], {withParents: true}));
364
- // -> @media screen and (min-width:40em){.a{width:3px}}
365
-
366
- ```
367
-
368
- ### CSS Modules
369
-
370
- CSS modules features are fully supported. refer to the [CSS modules](https://tbela99.github.io/css-parser/docs/documents/Guide.CSS_modules.html) documentation for more information.
371
-
372
- ```javascript
373
- import {transform} from '@tbela99/css-parser';
374
-
375
- const css = `
376
- .table {
377
- border-collapse: collapse;
378
- width: 100%;
379
- }
380
-
381
- .table td, .table th {
382
- border: 1px solid #ddd;
383
- padding: 8px;
384
- }
385
-
386
- .table tr:nth-child(even){background-color: #f2f2f2;}
387
-
388
- .table tr:hover {background-color: #ddd;}
389
-
390
- .table th {
391
- padding-top: 12px;
392
- padding-bottom: 12px;
393
- text-align: left;
394
- background-color: #4CAF50;
395
- color: white;
396
- }
397
- `;
398
-
399
- const result = await transform(css, {module: true});
400
-
401
- // css code
402
- console.log(result.code);
403
- // css mapping
404
- console.log(result.mapping);
405
- ```
406
-
407
- ### Convert colors
408
-
409
- ```javascript
410
- import {transform, ColorType} from '@tbela99/css-parser';
411
-
412
-
413
- const css = `
414
- .hsl { color: #b3222280; }
415
- `;
416
- const result: TransformResult = await transform(css, {
417
- beautify: true,
418
- convertColor: ColorType.SRGB
419
- });
420
-
421
- console.log(result.css);
422
-
423
- ```
424
-
425
- result
426
-
427
- ```css
428
- .hsl {
429
- color: color(srgb .7019607843137254 .13333333333333333 .13333333333333333/50%)
430
- }
431
- ```
432
-
433
- ### Merge similar rules
434
-
435
- CSS
436
-
437
- ```css
438
-
439
- .clear {
440
- width: 0;
441
- height: 0;
442
- color: transparent;
443
- }
444
-
445
- .clearfix:before {
446
-
447
- height: 0;
448
- width: 0;
449
- }
450
- ```
451
-
452
- ```javascript
453
-
454
- import {transform} from '@tbela99/css-parser';
455
-
456
- const result = await transform(css);
457
-
458
- ```
459
-
460
- Result
461
-
462
- ```css
463
- .clear, .clearfix:before {
464
- height: 0;
465
- width: 0
466
- }
467
-
468
- .clear {
469
- color: #0000
470
- }
471
- ```
472
-
473
- ### Automatic CSS Nesting
474
-
475
- CSS
476
-
477
- ```javascript
478
- const {parse, render} = require("@tbela99/css-parser/cjs");
479
-
480
- const css = `
481
- table.colortable td {
482
- text-align:center;
483
- }
484
- table.colortable td.c {
485
- text-transform:uppercase;
486
- }
487
- table.colortable td:first-child, table.colortable td:first-child+td {
488
- border:1px solid black;
489
- }
490
- table.colortable th {
491
- text-align:center;
492
- background:black;
493
- color:white;
494
- }
495
- `;
496
-
497
- const result = await parse(css, {nestingRules: true}).then(result => render(result.ast, {minify: false}).code);
498
- ```
499
-
500
- Result
501
-
502
- ```css
503
- table.colortable {
504
- & td {
505
- text-align: center;
506
-
507
- &.c {
508
- text-transform: uppercase
509
- }
510
-
511
- &:first-child, &:first-child + td {
512
- border: 1px solid #000
513
- }
514
- }
515
-
516
- & th {
517
- text-align: center;
518
- background: #000;
519
- color: #fff
520
- }
521
- }
522
- ```
523
-
524
- ### CSS Validation
525
-
526
- CSS
527
-
528
- ```css
529
-
530
- #404 {
531
- --animate-duration: 1s;
532
- }
533
-
534
- .s, #404 {
535
- --animate-duration: 1s;
536
- }
537
-
538
- .s [type="text" {
539
- --animate-duration: 1s;
540
- }
541
-
542
- .s [type="text"]]
543
- {
544
- --animate-duration: 1s;
545
- }
546
-
547
- .s [type="text"] {
548
- --animate-duration: 1s;
549
- }
550
-
551
- .s [type="text" i] {
552
- --animate-duration: 1s;
553
- }
554
-
555
- .s [type="text" s]
556
- {
557
- --animate-duration: 1s
558
- ;
559
- }
560
-
561
- .s [type="text" b]
562
- {
563
- --animate-duration: 1s;
564
- }
565
-
566
- .s [type="text" b],{
567
- --animate-duration: 1s
568
- ;
569
- }
570
-
571
- .s [type="text" b]
572
- + {
573
- --animate-duration: 1s;
574
- }
575
-
576
- .s [type="text" b]
577
- + b {
578
- --animate-duration: 1s;
579
- }
580
-
581
- .s [type="text" i] + b {
582
- --animate-duration: 1s;
583
- }
584
-
585
-
586
- .s [type="text"())]{
587
- --animate-duration: 1s;
588
- }
589
- .s(){
590
- --animate-duration: 1s;
591
- }
592
- .s:focus {
593
- --animate-duration: 1s;
594
- }
595
- ```
596
-
597
- with validation enabled
598
-
599
- ```javascript
600
- import {parse, render} from '@tbela99/css-parser';
601
-
602
- const options = {minify: true, validate: true};
603
- const {code} = await parse(css, options).then(result => render(result.ast, {minify: false}));
604
- //
605
- console.debug(code);
606
- ```
607
-
608
- ```css
609
- .s:is([type=text],[type=text i],[type=text s],[type=text i]+b,:focus) {
610
- --animate-duration: 1s
611
- }
612
- ```
613
-
614
- with validation disabled
615
-
616
- ```javascript
617
- import {parse, render} from '@tbela99/css-parser';
618
-
619
- const options = {minify: true, validate: false};
620
- const {code} = await parse(css, options).then(result => render(result.ast, {minify: false}));
621
- //
622
- console.debug(code);
623
- ```
624
-
625
- ```css
626
- .s:is([type=text],[type=text i],[type=text s],[type=text b],[type=text b]+b,[type=text i]+b,:focus) {
627
- --animate-duration: 1s
628
- }
629
- ```
630
-
631
- ### Nested CSS Expansion
632
-
633
- CSS
634
-
635
- ```css
636
- table.colortable {
637
- & td {
638
- text-align: center;
639
-
640
- &.c {
641
- text-transform: uppercase
642
- }
643
-
644
- &:first-child, &:first-child + td {
645
- border: 1px solid #000
646
- }
647
- }
648
-
649
- & th {
650
- text-align: center;
651
- background: #000;
652
- color: #fff
653
- }
654
- }
655
- ```
656
-
657
- Javascript
658
-
659
- ```javascript
660
- import {parse, render} from '@tbela99/css-parser';
661
-
662
- const options = {minify: true};
663
- const {code} = await parse(css, options).then(result => render(result.ast, {minify: false, expandNestingRules: true}));
664
- //
665
- console.debug(code);
666
- ```
667
-
668
- Result
669
-
670
- ```css
671
-
672
- table.colortable td {
673
- text-align: center;
674
- }
675
-
676
- table.colortable td.c {
677
- text-transform: uppercase;
678
- }
679
-
680
- table.colortable td:first-child, table.colortable td:first-child + td {
681
- border: 1px solid black;
682
- }
683
-
684
- table.colortable th {
685
- text-align: center;
686
- background: black;
687
- color: white;
688
- }
689
- ```
690
-
691
- ### Calc() resolution
692
-
693
- ```javascript
694
-
695
- import {parse, render} from '@tbela99/css-parser';
696
-
697
- const css = `
698
- a {
699
-
700
- width: calc(100px * log(625, 5));
701
- }
702
- .foo-bar {
703
- width: calc(100px * 2);
704
- height: calc(((75.37% - 63.5px) - 900px) + (2 * 100px));
705
- max-width: calc(3.5rem + calc(var(--bs-border-width) * 2));
706
- }
707
- `;
708
-
709
- const prettyPrint = await parse(css).then(result => render(result.ast, {minify: false}).code);
710
-
711
- ```
712
-
713
- result
714
-
715
- ```css
716
- a {
717
- width: 400px;
718
- }
719
-
720
- .foo-bar {
721
- width: 200px;
722
- height: calc(75.37% - 763.5px);
723
- max-width: calc(3.5rem + var(--bs-border-width) * 2)
724
- }
725
- ```
726
-
727
- ### CSS variable inlining
728
-
729
- ```javascript
730
-
731
- import {parse, render} from '@tbela99/css-parser';
732
-
733
- const css = `
734
-
735
- :root {
736
-
737
- --preferred-width: 20px;
738
- }
739
- .foo-bar {
740
-
741
- width: calc(calc(var(--preferred-width) + 1px) / 3 + 5px);
742
- height: calc(100% / 4);}
743
- `
744
-
745
- const prettyPrint = await parse(css, {inlineCssVariables: true}).then(result => render(result.ast, {minify: false}).code);
746
-
747
- ```
748
-
749
- result
750
-
751
- ```css
752
- .foo-bar {
753
- width: 12px;
754
- height: 25%
755
- }
756
-
757
- ```
758
-
759
- ### CSS variable inlining and relative color
760
-
761
- ```javascript
762
-
763
- import {parse, render} from '@tbela99/css-parser';
764
-
765
- const css = `
766
-
767
- :root {
768
- --color: green;
769
- }
770
- ._19_u :focus {
771
- color: hsl(from var(--color) calc(h * 2) s l);
772
-
773
- }
774
- `
775
-
776
- const prettyPrint = await parse(css, {inlineCssVariables: true}).then(result => render(result.ast, {minify: false}).code);
777
-
778
- ```
779
-
780
- result
781
-
782
- ```css
783
- ._19_u :focus {
784
- color: navy
785
- }
786
-
787
- ```
788
-
789
- ### CSS variable inlining and relative color
790
-
791
- ```javascript
792
-
793
- import {parse, render} from '@tbela99/css-parser';
794
-
795
- const css = `
796
-
797
- html { --bluegreen: oklab(54.3% -22.5% -5%); }
798
- .overlay {
799
- background: oklab(from var(--bluegreen) calc(1.0 - l) calc(a * 0.8) b);
800
- }
801
- `
802
-
803
- const prettyPrint = await parse(css, {inlineCssVariables: true}).then(result => render(result.ast, {minify: false}).code);
804
-
805
- ```
806
-
807
- result
808
-
809
- ```css
810
- .overlay {
811
- background: #0c6464
812
- }
813
-
814
- ```
815
-
816
- # Node Walker
817
-
818
- ```javascript
819
-
820
- import {walk} from '@tbela99/css-parser';
821
-
822
- for (const {node, parent, root} of walk(ast)) {
823
-
824
- // do something
825
- }
826
- ```
827
-
71
+ ## Documentation
72
+
73
+ - [Installation](https://tbela99.github.io/css-parser/docs/documents/Guide.Getting_started.html#installation)
74
+ - [Usage](https://tbela99.github.io/css-parser/docs/documents/Guide.Usage.html)
75
+ - [Parsing CSS](https://tbela99.github.io/css-parser/docs/documents/Guide.Usage.html#parsing)
76
+ - [Parsing files](https://tbela99.github.io/css-parser/docs/documents/Guide.Usage.html#parsing-files)
77
+ - [Parsing streams](https://tbela99.github.io/css-parser/docs/documents/Guide.Usage.html#parsing-from-a-readable-stream)
78
+ - [Rendering AST](https://tbela99.github.io/css-parser/docs/documents/Guide.Usage.html#rendering-ast)
79
+ - [Transform](https://tbela99.github.io/css-parser/docs/documents/Guide.Usage.html#transform)
80
+ - [Validation](https://tbela99.github.io/css-parser/docs/documents/Guide.Validation.html)
81
+ - [CSS Modules](https://tbela99.github.io/css-parser/docs/documents/Guide.CSS_Modules.html)
82
+ - [Minification](https://tbela99.github.io/css-parser/docs/documents/Guide.Minification.html)
83
+ - [Custom Transform](https://tbela99.github.io/css-parser/docs/documents/Guide.Custom_Transform.html)
84
+ - [Ast Manipulation](https://tbela99.github.io/css-parser/docs/documents/Guide.Ast_Manipulation.html)
85
+ - [Utility Functions](https://tbela99.github.io/css-parser/docs/documents/Guide.Utility_Functions.html)
86
+ -
828
87
  ## AST
829
88
 
830
89
  ### Comment
@@ -837,18 +96,24 @@ for (const {node, parent, root} of walk(ast)) {
837
96
  - typ: number
838
97
  - nam: string, declaration name
839
98
  - val: array of tokens
99
+ - state: EnumAstNodeStatus, validation state
100
+ - errors: ErrorDescription[], validation errors
840
101
 
841
102
  ### Rule
842
103
 
843
104
  - typ: number
844
105
  - sel: string, css selector
845
106
  - chi: array of children
107
+ - state: EnumAstNodeStatus, validation state
108
+ - errors: ErrorDescription[], validation errors
846
109
 
847
110
  ### AtRule
848
111
 
849
112
  - typ: number
850
113
  - nam: string. AtRule name
851
114
  - val: rule prelude
115
+ - state: EnumAstNodeStatus, validation state
116
+ - errors: ErrorDescription[], validation errors
852
117
 
853
118
  ### AtRuleStyleSheet
854
119
 
@@ -860,32 +125,12 @@ for (const {node, parent, root} of walk(ast)) {
860
125
  - typ: number
861
126
  - sel: string, css selector
862
127
  - chi: array of children
128
+ - state: EnumAstNodeStatus, validation state
129
+ - errors: ErrorDescription[], validation errors
863
130
 
864
131
  ## Sourcemap
865
132
 
866
- - [x] sourcemap generation
867
-
868
- ## Minification
869
-
870
- - [x] minify keyframes
871
- - [x] minify transform functions
872
- - [x] evaluate math functions calc(), clamp(), min(), max(), round(), mod(), rem(), sin(), cos(), tan(), asin(),
873
- acos(), atan(), atan2(), pow(), sqrt(), hypot(), log(), exp(), abs(), sign()
874
- - [x] minify colors
875
- - [x] minify numbers and Dimensions tokens
876
- - [x] multi-pass minification
877
- - [x] inline css variables
878
- - [x] merge identical rules
879
- - [x] merge adjacent rules
880
- - [x] compute shorthand: see the list below
881
- - [x] remove redundant declarations
882
- - [x] conditionally unwrap :is()
883
- - [x] automatic css nesting
884
- - [x] automatically wrap selectors using :is()
885
- - [x] avoid reparsing (declarations, selectors, at-rule)
886
- - [x] node and browser versions
887
- - [x] decode and replace utf-8 escape sequence
888
- - [x] experimental CSS prefix removal
133
+ - [x] Sourcemap generation
889
134
 
890
135
  ## Computed shorthands properties
891
136
 
@@ -941,257 +186,4 @@ for (const {node, parent, root} of walk(ast)) {
941
186
 
942
187
  ## Performance
943
188
 
944
- - [x] flatten @import
945
-
946
- ## Node Transformation
947
-
948
- Ast can be transformed using node visitors
949
-
950
- ### Example 1: Declaration
951
-
952
- the visitor is called for any declaration encountered
953
-
954
- ```typescript
955
-
956
- import {AstDeclaration, ParserOptions} from "../src/@types";
957
-
958
- const options: ParserOptions = {
959
-
960
- visitor: {
961
-
962
- Declaration: (node: AstDeclaration) => {
963
-
964
- if (node.nam == '-webkit-transform') {
965
-
966
- node.nam = 'transform'
967
- }
968
- }
969
- }
970
- }
971
-
972
- const css = `
973
-
974
- .foo {
975
- -webkit-transform: scale(calc(100 * 2/ 15));
976
- }
977
- `;
978
-
979
- const result = await transform(css, options);
980
- console.debug(result.code);
981
-
982
- // .foo{transform:scale(calc(40/3))}
983
- ```
984
-
985
- ### Example 2: Declaration
986
-
987
- the visitor is called only on 'height' declarations
988
-
989
- ```typescript
990
-
991
- import {AstDeclaration, EnumToken, LengthToken, ParserOptions, transform} from '@tbela99/css-parser';
992
-
993
- const options: ParserOptions = {
994
-
995
- visitor: {
996
-
997
- Declaration: {
998
-
999
- // called only for height declaration
1000
- height: (node: AstDeclaration): AstDeclaration[] => {
1001
-
1002
-
1003
- return [
1004
- node,
1005
- {
1006
-
1007
- typ: EnumToken.DeclarationNodeType,
1008
- nam: 'width',
1009
- val: [
1010
- <LengthToken>{
1011
- typ: EnumToken.LengthTokenType,
1012
- val: 3,
1013
- unit: 'px'
1014
- }
1015
- ]
1016
- }
1017
- ];
1018
- }
1019
- }
1020
- }
1021
- };
1022
-
1023
- const css = `
1024
-
1025
- .foo {
1026
- height: calc(100px * 2/ 15);
1027
- }
1028
- .selector {
1029
- color: lch(from peru calc(l * 0.8) calc(c * 0.7) calc(h + 180))
1030
- }
1031
- `;
1032
-
1033
- const result = await transform(css, options);
1034
- console.debug(result.code);
1035
-
1036
- // .foo{height:calc(40px/3);width:3px}.selector{color:#0880b0}
1037
-
1038
- ```
1039
-
1040
- ### Example 3: At-Rule
1041
-
1042
- the visitor is called on any at-rule
1043
-
1044
- ```typescript
1045
-
1046
- import {AstAtRule, ParserOptions} from "../src/@types";
1047
- import {transform} from "../src/node";
1048
-
1049
-
1050
- const options: ParserOptions = {
1051
-
1052
- visitor: {
1053
-
1054
- AtRule: (node: AstAtRule): AstAtRule => {
1055
-
1056
- if (node.nam == 'media') {
1057
-
1058
- return {...node, val: 'all'}
1059
- }
1060
- }
1061
- }
1062
- };
1063
-
1064
- const css = `
1065
-
1066
- @media screen {
1067
-
1068
- .foo {
1069
-
1070
- height: calc(100px * 2/ 15);
1071
- }
1072
- }
1073
- `;
1074
-
1075
- const result = await transform(css, options);
1076
- console.debug(result.code);
1077
-
1078
- // .foo{height:calc(40px/3)}
1079
-
1080
- ```
1081
-
1082
- ### Example 4: At-Rule
1083
-
1084
- the visitor is called only for at-rule media
1085
-
1086
- ```typescript
1087
-
1088
- import {AstAtRule, ParserOptions} from "../src/@types";
1089
- import {transform} from "../src/node";
1090
-
1091
- const options: ParserOptions = {
1092
-
1093
- visitor: {
1094
-
1095
- AtRule: {
1096
-
1097
- media: (node: AstAtRule): AstAtRule => {
1098
-
1099
- node.val = 'all';
1100
- return node
1101
- }
1102
- }
1103
- }
1104
- };
1105
-
1106
- const css = `
1107
-
1108
- @media screen {
1109
-
1110
- .foo {
1111
-
1112
- height: calc(100px * 2/ 15);
1113
- }
1114
- }
1115
- `;
1116
-
1117
- const result = await transform(css, options);
1118
- console.debug(result.code);
1119
-
1120
- // .foo{height:calc(40px/3)}
1121
-
1122
- ```
1123
-
1124
- ### Example 5: Rule
1125
-
1126
- the visitor is called on any Rule
1127
-
1128
- ```typescript
1129
-
1130
- import {AstAtRule, ParserOptions} from "../src/@types";
1131
- import {transform} from "../src/node";
1132
-
1133
- const options: ParserOptions = {
1134
-
1135
- visitor: {
1136
-
1137
- Rule(node: AstRule): AstRule {
1138
-
1139
- node.sel = '.foo,.bar,.fubar'
1140
- return node;
1141
- }
1142
- }
1143
- };
1144
-
1145
- const css = `
1146
-
1147
- .foo {
1148
-
1149
- height: calc(100px * 2/ 15);
1150
- }
1151
- `;
1152
-
1153
- const result = await transform(css, options);
1154
- console.debug(result.code);
1155
-
1156
- // .foo,.bar,.fubar{height:calc(40px/3)}
1157
-
1158
- ```
1159
-
1160
- ### Example 6: Rule
1161
-
1162
- Adding declarations to any rule
1163
-
1164
- ```typescript
1165
-
1166
- import {AstRule, parseDeclarations, ParserOptions, transform} from '@tbela99/css-parser';
1167
-
1168
- const options: ParserOptions = {
1169
-
1170
- removeEmpty: false,
1171
- visitor: {
1172
-
1173
- Rule: async (node: AstRule): Promise<AstRule | null> => {
1174
-
1175
- if (node.sel == '.foo') {
1176
-
1177
- node.chi.push(...await parseDeclarations('width: 3px'));
1178
- return node;
1179
- }
1180
-
1181
- return null;
1182
- }
1183
- }
1184
- };
1185
-
1186
- const css = `
1187
-
1188
- .foo {
1189
- }
1190
- `;
1191
-
1192
- const result = await transform(css, options);
1193
- console.debug(result.code);
1194
-
1195
- // .foo{width:3px}
1196
-
1197
- ```
189
+ - [x] Bundle file referenced by the @import statement.