@tbela99/css-parser 1.8.1 → 2.0.0

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 (105) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +129 -31
  3. package/dist/index-umd-web.js +27382 -24086
  4. package/dist/index.d.ts +2737 -2200
  5. package/dist/package.json.js +2 -2
  6. package/dist/src/data/properties.json.js +1 -1
  7. package/dist/src/data/validation.json.js +1 -1
  8. package/dist/src/lib/ast/arena-node.js +548 -0
  9. package/dist/src/lib/ast/arena.js +3198 -0
  10. package/dist/src/lib/ast/features/calc.js +85 -76
  11. package/dist/src/lib/ast/features/if.js +155 -115
  12. package/dist/src/lib/ast/features/index.js +1 -1
  13. package/dist/src/lib/ast/features/inlinecssvariables.js +77 -84
  14. package/dist/src/lib/ast/features/prefix.js +184 -183
  15. package/dist/src/lib/ast/features/shorthand.js +40 -46
  16. package/dist/src/lib/ast/features/transform.js +24 -24
  17. package/dist/src/lib/ast/features/type.js +1 -1
  18. package/dist/src/lib/ast/fingerprint.js +333 -0
  19. package/dist/src/lib/ast/math/expression.js +458 -543
  20. package/dist/src/lib/ast/math/math.js +19 -41
  21. package/dist/src/lib/ast/minify.js +590 -647
  22. package/dist/src/lib/ast/transform/compute.js +82 -85
  23. package/dist/src/lib/ast/transform/matrix.js +21 -38
  24. package/dist/src/lib/ast/transform/minify.js +82 -193
  25. package/dist/src/lib/ast/transform/perspective.js +2 -3
  26. package/dist/src/lib/ast/transform/rotate.js +1 -1
  27. package/dist/src/lib/ast/transform/scale.js +1 -1
  28. package/dist/src/lib/ast/transform/skew.js +1 -1
  29. package/dist/src/lib/ast/transform/translate.js +1 -1
  30. package/dist/src/lib/ast/transform/utils.js +2 -2
  31. package/dist/src/lib/ast/types.js +263 -258
  32. package/dist/src/lib/ast/walk.js +246 -610
  33. package/dist/src/lib/fs/resolve.js +1 -1
  34. package/dist/src/lib/parser/declaration/list.js +223 -139
  35. package/dist/src/lib/parser/declaration/map.js +251 -238
  36. package/dist/src/lib/parser/declaration/set.js +74 -66
  37. package/dist/src/lib/parser/linesmap.js +1 -1
  38. package/dist/src/lib/parser/parse.js +1379 -1662
  39. package/dist/src/lib/parser/source.js +7 -4
  40. package/dist/src/lib/parser/tokenize.js +406 -199
  41. package/dist/src/lib/parser/utils/angle.js +11 -13
  42. package/dist/src/lib/parser/utils/at-rule-container.js +183 -168
  43. package/dist/src/lib/parser/utils/at-rule-font-feature-values.js +5 -5
  44. package/dist/src/lib/parser/utils/at-rule-generic.js +31 -24
  45. package/dist/src/lib/parser/utils/at-rule-import.js +44 -44
  46. package/dist/src/lib/parser/utils/at-rule-media.js +216 -205
  47. package/dist/src/lib/parser/utils/at-rule-support.js +83 -88
  48. package/dist/src/lib/parser/utils/at-rule-when-else.js +47 -47
  49. package/dist/src/lib/parser/utils/at-rule.js +5 -5
  50. package/dist/src/lib/parser/utils/base64.js +2 -2
  51. package/dist/src/lib/parser/utils/cache.js +1 -1
  52. package/dist/src/lib/parser/utils/config.js +1 -1
  53. package/dist/src/lib/parser/utils/declaration.js +233 -234
  54. package/dist/src/lib/parser/utils/eq.js +50 -3
  55. package/dist/src/lib/parser/utils/hash.js +2 -35
  56. package/dist/src/lib/parser/utils/selector.js +309 -387
  57. package/dist/src/lib/parser/utils/text.js +18 -4
  58. package/dist/src/lib/parser/utils/token.js +16 -69
  59. package/dist/src/lib/parser/utils/type.js +37 -24
  60. package/dist/src/lib/printer/render.js +965 -511
  61. package/dist/src/lib/printer/sourcemap/lib/codec.js +1 -1
  62. package/dist/src/lib/printer/sourcemap/sourcemap.js +1 -1
  63. package/dist/src/lib/syntax/color/a98rgb.js +1 -1
  64. package/dist/src/lib/syntax/color/alpha.js +36 -37
  65. package/dist/src/lib/syntax/color/cmyk.js +35 -52
  66. package/dist/src/lib/syntax/color/color-mix.js +96 -132
  67. package/dist/src/lib/syntax/color/color.js +222 -231
  68. package/dist/src/lib/syntax/color/hex.js +45 -55
  69. package/dist/src/lib/syntax/color/hsl.js +54 -62
  70. package/dist/src/lib/syntax/color/hwb.js +60 -68
  71. package/dist/src/lib/syntax/color/lab.js +59 -67
  72. package/dist/src/lib/syntax/color/lch.js +59 -67
  73. package/dist/src/lib/syntax/color/oklab.js +60 -68
  74. package/dist/src/lib/syntax/color/oklch.js +60 -67
  75. package/dist/src/lib/syntax/color/p3.js +1 -1
  76. package/dist/src/lib/syntax/color/prophotorgb.js +1 -1
  77. package/dist/src/lib/syntax/color/rec2020.js +1 -1
  78. package/dist/src/lib/syntax/color/relative-color.js +94 -144
  79. package/dist/src/lib/syntax/color/rgb.js +54 -57
  80. package/dist/src/lib/syntax/color/srgb.js +55 -53
  81. package/dist/src/lib/syntax/color/utils/color-type.js +13 -10
  82. package/dist/src/lib/syntax/color/utils/colorspace.js +11 -11
  83. package/dist/src/lib/syntax/color/utils/components.js +19 -20
  84. package/dist/src/lib/syntax/color/utils/distance.js +15 -13
  85. package/dist/src/lib/syntax/color/utils/make-color.js +15 -19
  86. package/dist/src/lib/syntax/color/utils/matrix.js +2 -2
  87. package/dist/src/lib/syntax/color/xyz.js +1 -1
  88. package/dist/src/lib/syntax/color/xyzd50.js +1 -1
  89. package/dist/src/lib/syntax/constants.js +2 -16
  90. package/dist/src/lib/syntax/syntax.js +301 -407
  91. package/dist/src/lib/validation/config.js +1 -1
  92. package/dist/src/lib/validation/match.js +959 -723
  93. package/dist/src/lib/validation/parser/parse.js +230 -112
  94. package/dist/src/lib/validation/parser/typedef.js +1 -1
  95. package/dist/src/lib/validation/utils/list.js +27 -12
  96. package/dist/src/node.js +12 -72
  97. package/dist/src/types.js +1 -1
  98. package/dist/src/utils/sync.js +9 -6
  99. package/dist/src/web.js +11 -73
  100. package/package.json +9 -10
  101. package/dist/index.cjs +0 -35874
  102. package/dist/src/lib/ast/clone.js +0 -51
  103. package/dist/src/lib/ast/expand.js +0 -311
  104. package/dist/src/lib/ast/find.js +0 -192
  105. package/dist/src/lib/ast/node.js +0 -59
package/CHANGELOG.md CHANGED
@@ -1,5 +1,71 @@
1
1
  # Changelog
2
2
 
3
+ # 2.0.0 (unreleased)
4
+
5
+ breaking changes
6
+
7
+ see the [migration guide](./files/migration.md)
8
+
9
+ - [x] removed the deprecated commonjs build (`dist/index.cjs`, export `@tbela99/css-parser/cjs`): the package is an ES module
10
+ - [x] `EnumToken.CommentTokenType` is 1: the value 0 is reserved for the null node, the `EnumToken` values are renumbered
11
+ - [x] the arena is never compacted nor trimmed by the library: detached nodes and the tokens allocated while rendering stay allocated. call `arena.compact()` to reclaim the memory
12
+ - [x] the initial arena capacity is computed from the input length: the arena seldom grows
13
+ - [x] `render()` renders copies (`withParents`, `expandNestingRules`) in the same arena, under a temporary stylesheet node
14
+ - [x] memory is reclaimed on demand only: `arena.mark(...nodes)` marks nodes, `arena.release()` releases the marked nodes, `arena.trim()` releases them and compacts the arena. `arena.rewind()` is removed
15
+ - [x] removed the deprecated `ValidationLevel` enum: the `validation` option is a boolean
16
+ - [x] removed the deprecated `parseFile()` and `transformFile()` functions: use `parse({file})` and `transform({file})`
17
+ - [x] removed the deprecated node types `EnumToken.InvalidRuleNodeType`, `EnumToken.InvalidAtRuleNodeType` and `EnumToken.InvalidDeclarationNodeType` (they were no longer produced: invalid nodes keep their type and get the `EnumAstNodeStatus.Invalid` state) and the deprecated `AstInvalidRule`, `AstInvalidAtRule` and `AstInvalidDeclaration` types. the `EnumToken` values that followed them are renumbered: use the `EnumToken` names, not their values
18
+ - [x] removed `EnumToken.InvalidClassSelectorTokenType`, `EnumToken.InvalidAttrTokenType` and `EnumToken.InvalidMediaQueryTokenType` (not produced by the parser) and `EnumToken.InvalidCommentTokenType`: a CDO / CDC comment outside of the stylesheet is a `EnumToken.BadCdoTokenType` token, reported and rendered as an empty string as before. the `InvalidClassSelectorToken`, `InvalidAttrToken` and `InvalidMediaQueryToken` types are removed. `EnumToken` starts at 1
19
+ - [x] the arrays returned by the object views (`chi`, `val`, `tokens`, fields), their locations (`loc`) and their error lists (`errors`) are frozen: assign the property to modify the arena
20
+ - [x] the traversal and search functions are methods of the arena: `walk()`, `walkValues()`, `find()`, `findAll()`, `findLast()`, `findByValue()` and `findValue()` are removed, use `arena.walk(node, filter?, reverse?)`, `arena.walkValues(tokens, filter?, reverse?)`, `arena.find(node, matcher)`, `arena.findAll(node, matcher)`, `arena.findLast(node, matcher)`, `arena.findByValue(node, matcher)` and `arena.findValue(node, matcher)`
21
+ - [x] `arena.walk()` and `arena.walkValues()` return node ids instead of result objects (`{node, parent, root, arena, parents}`, `{value, parent, previousValue, nextValue, root, parents}`): the parent is `arena.getParent(node)`, the parent of a value token `arena.getValueParent(token)` (the field list token of a structured token is skipped) and the node that owns it `arena.getValueOwner(token)`. `walkValues()` has no `root` argument, it accepts an array of token ids or a node id (its value tokens are walked). `findByValue()` returns `{node, value}` (ids), `findValue()` returns the token id. the `WalkResult`, `WalkAttributesResult` and `TokenSearchResult` types are removed
22
+ - [x] the callbacks are called with the arena and the node id, the arguments that can be read from the arena are removed: walk filters `(arena, node)`, walkValues filters `(arena, token, event)` and type filters `(arena, token)`, matchers `(arena, node)` / `(arena, token)`, `arena.findToken()`, `arena.tokens()`, `arena.children()` and `arena.siblings()` filters `(arena, id)`
23
+ - [x] visitors are called with the arena and the node id: `handler(arena, id)` instead of `handler(node, arena, parent, root)`. they return nothing to keep the node, or an object (an object view or a plain object) or a node id, or an array of objects and node ids, to replace it
24
+ - [x] `arena.toObject(id)` returns an object view of the node (`AstArenaNode`) instead of a plain copy: its properties (`typ`, `nam`, `sel`, `val`, `chi`, `tokens`, `unit`, `kin`, `l`, `r`, `op`, `loc`, `state`, `errors`, `parent`, ...) are getters and setters that read and write the arena, the view only holds the arena (`ARENA`) and the node id (`ARENAID`, keyed symbols). `arena.toPlainObject(id)` (and `view.toJSON()`, `JSON.stringify(view)`) returns the plain copy. `arena.fromObject()` imports views: importing a view of the same arena is a noop, the views of another arena are copied
25
+ - [x] the css module variables (`result.cssModuleVariables`) are object views of the variable nodes
26
+ - [x] removed `replaceNodeOrValue()`; use `arena.replaceToken(id, ...tokens)` for value token replacement
27
+ - [x] removed `replaceNode()`; use `arena.replaceChild(id, ...nodes)` to replace AST nodes
28
+ - [x] removed `cloneNode()` and `cloneValue()`: use `arena.clone(id, deep?, cloneMap?)`
29
+ - [x] removed `expand()`: use `arena.expand(node)`
30
+ - [x] removed `getNodeProperty()` and `setNodeProperty()`: use the arena methods (`arena.getState()`, `arena.setState()`, `arena.getErrors()`, ...) or the object view properties (`arena.toObject(id).state = ...`)
31
+ - [x] `WalkerEvent` and `WalkerOptionEnum` are declared with the other enums (they are still exported by the package)
32
+
33
+ performance
34
+
35
+ - [x] the parser recycles the tokens that are not attached to the tree (whitespace, `:`, `;`, `{`, `}`, ...): the arena allocates about half the nodes. `arena.recycle(id)` reuses the id of a detached leaf node
36
+ - [x] the initial arena capacity is one node for every 4 bytes of css
37
+ - [x] the validations of declaration values are cached per arena: a value is validated once per property syntax. the failed validations are cached too: their errors are rebuilt with the node and the location of each declaration. the cache is keyed by the string table of the arena: compacting the arena does not reuse stale results
38
+ - [x] validation allocates less: the validation context is a class, the options are not copied, `matchAllSyntaxes()` passes its result object to the matching functions
39
+ - [x] the syntax definitions are tokenized by character code (no per character strings, regular expressions or position copies)
40
+ - [x] tokenizer: symbols, units and function names are looked up in hash tables by source range (no string per lookup), the characters are read by code (no single character strings), numbers are parsed without a string when the result is exact, the whitespace text is not kept
41
+ - [x] `arena.walk()` and `arena.walkValues()` return iterator objects instead of generators: one small object per walk, the iteration result object is reused, no closure, no result object or array per visited node. the children are read when the next node is requested. the iteration protocol (`next()`, `return()`, `for ... of`) is unchanged
42
+ - [x] parser: the declaration colors are parsed without an iterator, the selector string is built without intermediate arrays, maps or closures, `toLowerCase()` is not called on lowercase strings
43
+ - [x] renderer: `renderValue()` creates no options / cache object and no closure per call, token lists are rendered from the linked lists, `render()` copies the options with a fast clone and does not flatten the rendered children to remove the last semicolon
44
+ - [x] renderer: identical declarations (same name and value tokens) are rendered once per render: `.s{width:10px} .g{width:10px}` renders `width:10px` once. colors and constructs (functions, parentheses, binary expressions, ...) are memoized too, the individual tokens are not (`convertColor()` is called once per distinct color, fewer tokens are allocated while rendering). the source map locations are still computed for every node
45
+ - [x] renderer: numbers are minified once, the last semicolon of a block is known from the type of the last child (the rendered child is not read)
46
+ - [x] renderer: the memo keys are serialized compactly (most tokens take 1 or 2 values) directly in the key pool, the memos are reused by the next renders
47
+ - [x] minifier: the rule / at-rule preludes are not parsed again after the selectors are rewritten (at-rules used to get their name parsed as prelude tokens), the default values of the shorthand properties are parsed once
48
+ - [x] minifier: the rule sizes are compared with a renderer that resolves the options once and shares the rendered values, tokens are compared and deduplicated by structure instead of signature strings
49
+ - [x] parser: small inputs of known length do not allocate 4096 nodes
50
+ - [x] the single line methods (arena accessors and setters, tokenizer, line map and source file accessors, validation context, memo lookups) are inlined at their call sites inside the library. each inlined line is preceded by a `// inlined: <call>` comment. the public methods are unchanged
51
+
52
+ features
53
+
54
+ - [x] `AstArenaNode`: lightweight object view of an arena node, see `arena.toObject()`
55
+ - [x] `arena.getValueParent(token)`, `arena.getValueOwner(token)`, `arena.toPlainObject(id)`
56
+ - [x] arena accessors: `arena.getNextSibling(id)`, `arena.getPreviousSibling(id)`, `arena.getFirstToken(id)`, `arena.getLastToken(id)`, `arena.getCapacity()`, `arena.getLastId()` and `arena.getStringCount()`
57
+
58
+ documentation
59
+
60
+ - [x] [Arena Memory](./files/arena.md): memory used by the arena, capacity and growth, what allocates nodes, reclaiming memory with `mark()`, `release()`, `compact()`, `trim()`
61
+ - [x] the traversal, the visitors and the object views are documented with the new signatures ([Ast Manipulation](./files/ast.md), [Custom Transform](./files/transform.md), [Validation](./files/validation.md), [Plugins](./files/plugins.md), [Utility Functions](./files/utilities.md))
62
+ - [x] [Migration](./files/migration.md): the breaking changes of 2.0 and how to update the code
63
+ - [x] the documentation, the README and the examples read and write the arena with its methods (`arena.getType(n)`, `arena.getName(n)`, `arena.getFirstChild(n)`, `arena.setType(n, type)`, ...) instead of accessing the columns
64
+
65
+ # 1.8.2
66
+
67
+ remove left over console debug
68
+
3
69
  # 1.8.1
4
70
 
5
71
  no code change
package/README.md CHANGED
@@ -4,9 +4,13 @@
4
4
 
5
5
  # css-parser
6
6
 
7
- An all-in-one CSS parsing solution for Node.js and the browser, covering parsing, validation, transformation, minification, and AST-based tooling.
7
+ A zero-allocation, high-performance CSS processing engine for Node.js and the browser, combining parsing, validation, transformation, minification, and AST-based tooling in a single solution.
8
8
 
9
- The library always fully parses the stylesheet into a structured AST, and token values are exposed as typed data so custom transforms, plugins, and analysis can work with reliable, semantic input instead of raw strings.
9
+ Every stylesheet is fully parsed into a structured AST, with token values represented as typed data. This provides a reliable semantic foundation for custom transformations, plugin development, and advanced stylesheet analysis without relying on raw string manipulation.
10
+
11
+ > [!NOTE]
12
+ > Version 2.0 has been rewritten to use arena memory for AST nodes and tokens, improving memory usage and performance. On the Tailwind CSS parsing and validation workload, runtime is 42% faster than v1.8.2 while using 60% less memory.<br>
13
+ This major release also introduces breaking changes and removes deprecated features. See the [migration guide](https://tbela99.github.io/css-parser/docs/documents/Guide.Migration.html) for details.
10
14
 
11
15
  ## Installation
12
16
 
@@ -108,8 +112,8 @@ Performance vs execution speed comparison
108
112
 
109
113
  | File: tailwind.css | Speed optimization | Minification optimization |
110
114
  | --------------------- | ------------------ | ------------------------- |
111
- | Size: 2,380,419 bytes | 1,890,728 bytes | 1,633,188 bytes |
112
- | Time | 205.91 ms | 471.89 ms |
115
+ | Size: 2,380,419 bytes | 1,890,835 bytes | 1,633,188 bytes |
116
+ | Time | 128.67 ms | 268.86 ms |
113
117
  | Size reduction | -20.6% | -31.4% |
114
118
 
115
119
  ## Playground
@@ -134,51 +138,145 @@ Try it [online](https://tbela99.github.io/css-parser/playground/)
134
138
  - [Syntax Lowering](https://tbela99.github.io/css-parser/docs/documents/Guide.Syntax_Lowering.html)
135
139
  - [Prefix Removal](https://tbela99.github.io/css-parser/docs/documents/Guide.Prefix_Removal.html)
136
140
  - [Ast Manipulation](https://tbela99.github.io/css-parser/docs/documents/Guide.Ast_Manipulation.html)
141
+ - [Arena Memory](https://tbela99.github.io/css-parser/docs/documents/Guide.Arena_Memory.html)
137
142
  - [Utility Functions](https://tbela99.github.io/css-parser/docs/documents/Guide.Utility_Functions.html)
143
+ - [Migration to 2.0](https://tbela99.github.io/css-parser/docs/documents/Guide.Migration.html)
138
144
 
139
145
  ## AST
140
146
 
147
+ Ast nodes and value tokens are allocated in an arena (`AstArena`) and referenced by their id (a number). The node data is stored
148
+ column-wise in typed arrays (structure of arrays) and is read / written through the arena. The parser does not allocate
149
+ node or token objects:
150
+
151
+ ```ts
152
+ import {parse, render, EnumToken} from '@tbela99/css-parser';
153
+
154
+ const {arena, ast} = await parse(`.foo { color: red }`);
155
+ const rule = arena.getFirstChild(ast);
156
+ const declaration = arena.getFirstChild(rule);
157
+
158
+ console.log(arena.getType(rule) == EnumToken.RuleNodeType, arena.getSelector(rule)); // true '.foo'
159
+ console.log(arena.getName(declaration)); // 'color'
160
+ console.log(arena.tokens(declaration).map((token) => [EnumToken[arena.getType(token)], arena.str(token)])); // [['Color', 'red']]
161
+ console.log(render(arena, ast).code); // .foo{color:red}
162
+ ```
163
+
141
164
  ### Comment
142
165
 
143
- - typ: number
144
- - val: string, the comment
166
+ - `arena.getType(n)`: EnumToken.CommentNodeType
167
+ - `arena.getValue(n)`: string, the comment
145
168
 
146
- ### AtRuleStyleSheet
169
+ ### StyleSheet
147
170
 
148
- - typ: number
149
- - chi: array of children
171
+ - `arena.getType(n)`: EnumToken.StyleSheetNodeType
172
+ - `arena.children(n)`: array of children ids
150
173
 
151
174
  ### Declaration
152
175
 
153
- - typ: number
154
- - nam: string, declaration name
155
- - val: array of tokens
156
- - state: EnumAstNodeStatus, validation state
157
- - errors: ErrorDescription[], validation errors
176
+ - `arena.getType(n)`: EnumToken.DeclarationNodeType
177
+ - `arena.getName(n)`: string, declaration name
178
+ - `arena.tokens(n)`: array of token ids, the declaration value
179
+ - `arena.getState(n)`: EnumAstNodeStatus, validation state
180
+ - `arena.getErrors(n)`: ErrorDescription[], validation errors
158
181
 
159
- ### Rule
182
+ ### Rule and KeyframesRule
160
183
 
161
- - typ: number
162
- - sel: string, css selector
163
- - chi: array of children
164
- - state: EnumAstNodeStatus, validation state
165
- - errors: ErrorDescription[], validation errors
184
+ - `arena.getType(n)`: EnumToken.RuleNodeType or EnumToken.KeyframesRuleNodeType
185
+ - `arena.getSelector(n)`: string, css selector
186
+ - `arena.tokens(n)`: array of token ids, the parsed selector
187
+ - `arena.children(n)`: array of children ids
188
+ - `arena.getState(n)`: EnumAstNodeStatus, validation state
189
+ - `arena.getErrors(n)`: ErrorDescription[], validation errors
166
190
 
167
191
  ### AtRule and KeyframesAtRule
168
192
 
169
- - typ: number
170
- - nam: string. AtRule name
171
- - val: rule prelude
172
- - state: EnumAstNodeStatus, validation state
173
- - errors: ErrorDescription[], validation errors
193
+ - `arena.getType(n)`: EnumToken.AtRuleNodeType or EnumToken.KeyframesAtRuleNodeType
194
+ - `arena.getName(n)`: string. AtRule name
195
+ - `arena.getValue(n)`: rule prelude
196
+ - `arena.tokens(n)`: array of token ids, the parsed prelude
197
+ - `arena.children(n)`: array of children ids (at-rules with a block)
198
+ - `arena.getState(n)`: EnumAstNodeStatus, validation state
199
+ - `arena.getErrors(n)`: ErrorDescription[], validation errors
200
+
201
+ ### Object views
202
+
203
+ `arena.toObject(id)` returns an object view of a node or a token (`AstArenaNode`): its properties (`typ`, `nam`, `sel`,
204
+ `val`, `chi`, `tokens`, `loc`, `state`, `errors`, `parent`, ...) are getters and setters that read and write the arena.
205
+ The view only holds the arena and the node id (`view[ARENAID]`). Importing a view of the same arena is a noop:
206
+
207
+ ```ts
208
+ const rule = arena.toObject(arena.getFirstChild(ast));
209
+
210
+ rule.sel = '.bar';
211
+ rule.chi[0].nam = 'background-color';
212
+
213
+ // the returned arrays are frozen: assign the property to modify the arena
214
+ rule.chi = [...rule.chi, {typ: EnumToken.DeclarationNodeType, nam: 'width', val: [{typ: EnumToken.LengthTokenType, val: 3, unit: 'px'}]}];
215
+
216
+ console.log(arena.fromObject(rule) == rule[ARENAID]); // true: nothing is copied
217
+ console.log(JSON.stringify(rule)); // deep plain copy
218
+ ```
219
+
220
+ ### Traversal and visitors
221
+
222
+ The traversal and search functions are methods of the arena: `arena.walk()`, `arena.walkValues()`, `arena.find()`,
223
+ `arena.findAll()`, `arena.findLast()`, `arena.findByValue()`, `arena.findValue()`. They return node ids. Their callbacks,
224
+ like the visitors, are called with the arena and the node id: everything else is read from the arena.
225
+
226
+ ```ts
227
+ for (const node of arena.walk(ast)) {
228
+
229
+ console.log(EnumToken[arena.getType(node)], arena.getParent(node));
230
+ }
174
231
 
175
- ### KeyframesRule
232
+ const result = await transform(css, {
233
+ visitor: {
234
+
235
+ Declaration(arena: AstArena, id: number) {
236
+
237
+ const node = arena.toObject(id);
238
+
239
+ if (node.nam == 'height') {
240
+
241
+ node.nam = 'width';
242
+ }
243
+ }
244
+ }
245
+ });
246
+ ```
247
+
248
+ A visitor returns nothing to keep the node, or an object or a node id (or an array of objects and node ids) to replace it.
249
+
250
+ ### Arena memory
251
+
252
+ The arena never frees memory by itself: detached nodes keep their memory and their ids stay valid. A long-lived arena
253
+ can be compacted. `compact()` and `trim()` renumber the nodes and return the mapping of the old ids to the new ids:
254
+
255
+ ```ts
256
+ console.log(arena.getCapacity(), arena.getLastId(), arena.getStringCount()); // capacity, last allocated id, interned strings
257
+
258
+ arena.mark(node); // mark a node to be released later
259
+ const mapping = arena.trim(result.errors); // release the marked nodes, drop the unreachable nodes, shrink the columns
260
+ const newId = mapping[oldId]; // 0 when the node has been dropped
261
+ ```
262
+
263
+ See [Arena Memory](https://tbela99.github.io/css-parser/docs/documents/Guide.Arena_Memory.html).
264
+
265
+ ### Workers
266
+
267
+ The arena can be moved to a worker (and back) without copying the node data:
268
+
269
+ ```ts
270
+ // main thread
271
+ const [properties, transferables] = AstArena.toTransferableArenaObject(result.arena);
272
+ worker.postMessage({ast: result.ast, properties, transferables}, transferables);
273
+
274
+ // worker
275
+ const arena = AstArena.fromTransferableArenaObjects(event.data.properties, event.data.transferables);
276
+ console.log(render(arena, event.data.ast).code);
277
+ ```
176
278
 
177
- - typ: number
178
- - sel: string, css selector
179
- - chi: array of children
180
- - state: EnumAstNodeStatus, validation state
181
- - errors: ErrorDescription[], validation errors
279
+ See [Ast Manipulation](https://tbela99.github.io/css-parser/docs/documents/Guide.Ast_Manipulation.html).
182
280
 
183
281
  ## Sourcemap
184
282