pax_global_header00006660000000000000000000000064141571237410014517gustar00rootroot0000000000000052 comment=929e47a8ba80501ce8e35a1f152c79aa26c77ae0 csstree-2.0.4/000077500000000000000000000000001415712374100131725ustar00rootroot00000000000000csstree-2.0.4/.editorconfig000066400000000000000000000002461415712374100156510ustar00rootroot00000000000000# editorconfig.org root = true [*] charset = utf-8 indent_style = space indent_size = 4 end_of_line = lf trim_trailing_whitespace = true insert_final_newline = true csstree-2.0.4/.eslintrc000066400000000000000000000065701415712374100150260ustar00rootroot00000000000000{ "env": { "node": true, "mocha": true, "es6": true }, "parserOptions": { "ecmaVersion": 2020, "sourceType": "module" }, "rules": { "no-duplicate-case": 2, "no-undef": 2, "no-unused-vars": [ 2, { "vars": "all", "args": "after-used" } ], "no-empty": [ 2, { "allowEmptyCatch": true } ], "no-implicit-coercion": [ 2, { "boolean": true, "string": true, "number": true } ], "no-with": 2, "brace-style": 2, "no-mixed-spaces-and-tabs": 2, "no-multiple-empty-lines": 2, "no-multi-str": 2, "dot-location": [ 2, "property" ], "operator-linebreak": [ 2, "after", { "overrides": { "?": "before", ":": "before" } } ], "key-spacing": [ 2, { "beforeColon": false, "afterColon": true } ], "space-unary-ops": [ 2, { "words": false, "nonwords": false } ], "no-spaced-func": 2, "space-before-function-paren": [ 2, { "anonymous": "ignore", "named": "never" } ], "array-bracket-spacing": [ 2, "never" ], "space-in-parens": [ 2, "never" ], "comma-dangle": [ 2, "never" ], "no-trailing-spaces": 2, "yoda": [ 2, "never" ], "camelcase": [ 2, { "properties": "never" } ], "comma-style": [ 2, "last" ], "curly": [ 2, "all" ], "dot-notation": 2, "eol-last": 2, "one-var": [ 2, "never" ], "wrap-iife": 2, "space-infix-ops": 2, "keyword-spacing": [ 2, { "overrides": { "else": { "before": true }, "while": { "before": true }, "catch": { "before": true }, "finally": { "before": true } } } ], "spaced-comment": [ 2, "always" ], "space-before-blocks": [ 2, "always" ], "semi": [ 2, "always" ], "indent": [ 2, 4, { "SwitchCase": 1 } ], "linebreak-style": [ 2, "unix" ], "quotes": [ 2, "single", { "avoidEscape": true } ] } } csstree-2.0.4/.github/000077500000000000000000000000001415712374100145325ustar00rootroot00000000000000csstree-2.0.4/.github/workflows/000077500000000000000000000000001415712374100165675ustar00rootroot00000000000000csstree-2.0.4/.github/workflows/build.yml000066400000000000000000000046751415712374100204250ustar00rootroot00000000000000name: Build on: push: pull_request: env: PRIMARY_NODEJS_VERSION: 16 REPORTER: "min" jobs: lint: name: Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup node ${{ env.PRIMARY_NODEJS_VERSION }} uses: actions/setup-node@v2 with: node-version: ${{ env.PRIMARY_NODEJS_VERSION }} cache: "npm" - run: npm ci - run: npm run lint test-bundle: name: Test bundle runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup node ${{ env.PRIMARY_NODEJS_VERSION }} uses: actions/setup-node@v2 with: node-version: ${{ env.PRIMARY_NODEJS_VERSION }} cache: "npm" - run: npm ci - run: npm run bundle-and-test unit-tests: name: Unit tests runs-on: ubuntu-latest strategy: matrix: # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ node_version: - 10 - 12.20.0 - 14.13.0 - 16 steps: - uses: actions/checkout@v2 - name: Setup node ${{ matrix.node_version }} uses: actions/setup-node@v2 with: node-version: ${{ matrix.node_version }} cache: "npm" - run: npm ci - run: npm run test if: ${{ matrix.node_version != '10' }} - run: npm run esm-to-cjs-and-test - run: npm run coverage if: ${{ matrix.node_version == env.PRIMARY_NODEJS_VERSION }} - name: Coveralls parallel if: ${{ matrix.node_version == env.PRIMARY_NODEJS_VERSION }} uses: coverallsapp/github-action@1.1.3 with: github-token: ${{ secrets.GITHUB_TOKEN }} flag-name: node-${{ matrix.node_version }} parallel: true send-to-coveralls: name: Send coverage to Coveralls needs: unit-tests runs-on: ubuntu-latest steps: - name: Send coverage to Coveralls uses: coverallsapp/github-action@1.1.3 with: github-token: ${{ secrets.GITHUB_TOKEN }} parallel-finished: true csstree-2.0.4/.gitignore000066400000000000000000000000761415712374100151650ustar00rootroot00000000000000/.nyc_output/ /.vscode/ /coverage/ /cjs/ /node_modules/ /tmp/ csstree-2.0.4/CHANGELOG.md000066400000000000000000001244051415712374100150110ustar00rootroot00000000000000## 2.0.4 (December 17, 2021) - Fixed `generate()` in safe mode to add a whitespace between `` and ``, otherwise some values are broken in IE11, e.g. `border` properties (#173) - Removed allowance for `:` for an attribute name on `AttributeSelector` parsing as it does not meet the CSS specs ([details](https://github.com/csstree/csstree/discussions/149)) - Extended Node.js support to include `^10` ## 2.0.3 (December 14, 2021) - Fixed unintended whitespace on `generate()` in `safe` mode between `type-selector` and `id-selector` (e.g. `a#id`). A regression was introduces in `2.0.2` since IE11 fails on values when `` goes after `` without a whitespace in the middle, e.g. `1px solid#000`. Thus, in one case, a space between the `` and the `` is required, and in the other, vice versa. Until a better solution found, a workaround is used on `id-selector` generation by producing a `` instead of ``. ## 2.0.2 (December 10, 2021) - Updated `width`, `min-width` and `max-width` syntax definitions - Patched counter related syntaxes to match specs until updated in `mdn-data` - Replaced `source-map` with `source-map-js` which reduce install size by ~700KB - Fixed `calc()` function consumption on definition syntax matching - Fixed `generate()` auto emitting a whitespace edge cases when next token starts with a dash (minus) - Fixed `generate()` safe mode to cover more cases for IE11 - Fixed CommonJS bundling by adding browser files `dist/data.cjs` and `dist/version.cjs` - Added exports: - `css-tree/definition-syntax-data` - `css-tree/definition-syntax-data-patch` ## 2.0.1 (December 4, 2021) - Extended Node.js support to include `^12.20.0` and `^14.13.0` versions ## 2.0.0 (December 3, 2021) - Package - Dropped support for Node.js prior 14.16 (following patch versions are changed it to `^10 || ^12.20.0 || ^14.13.0 || >=15.0.0`) - Converted to ES modules. However, CommonJS is supported as well (dual module) - Added exports for standalone parts instead of internal paths usage (use as `import * as parser from "css-tree/parser"` or `require("css-tree/parser")`): - `css-tree/tokenizer` - `css-tree/parser` - `css-tree/walker` - `css-tree/generator` - `css-tree/lexer` - `css-tree/definition-syntax` - `css-tree/utils` - Changed bundle set to provide `dist/csstree.js` (an IIFE version with `csstree` as a global name) and `dist/csstree.esm.js` (as ES module). Both are minified - Bumped `mdn-data` to `2.0.23` - Tokenizer - Changed `tokenize()` to take a function as second argument, which will be called for every token. No stream instance is creating when second argument is ommited. - Changed `TokenStream#getRawLength()` to take second parameter as a function (rule) that check a char code to stop a scanning - Added `TokenStream#forEachToken(fn)` method - Removed `TokenStream#skipWS()` method - Removed `TokenStream#getTokenLength()` method - Parser - Moved `SyntaxError` (custom parser's error class) from root of public API to parser via `parse.SyntaxError` - Removed `parseError` field in parser's `SyntaxError` - Changed selector parsing to produce `{ type: 'Combinator', name: ' ' }` node instead of `WhiteSpace` node - Removed producing of `WhiteSpace` nodes with the single exception for a custom property declaration with a single white space token as a value - Parser adds a whitespace to `+` and `-` operators, when a whitespace is before and/or after an operator - Exposed parser's inner configuration as `parse.config` - Added `consumeUntilBalanceEnd()`, `consumeUntilLeftCurlyBracket()`, `consumeUntilLeftCurlyBracketOrSemicolon()`, `consumeUntilExclamationMarkOrSemicolon()` and `consumeUntilSemicolonIncluded()` methods to parser's inner API to use with `Raw` instead of `Raw.mode` - Changed `Nth` to always consume `of` clause when presented, so it became more general and moves validation to lexer - Changed `String` node type to store decoded string value, i.e. with no quotes and escape sequences - Changed `Url` node type to store decoded url value as a string instead of `String` or `Raw` node, i.e. with no quotes, escape sequences and `url()` wrapper - Generator - Generator is now determines itself when a white space required between emitting tokens - Changed `chunk()` handler to `token()` (output a single token) and `tokenize()` (split a string into tokens and output each of them) - Added `mode` option for `generate()` to specify a mode of token separation: `spec` or `safe` (by default) - Added `emit(token, type, auto)` handler as implementation specific token processor - Changed `Nth` to serialize `+n` as `n` - Added auto-encoding for a `string` and `url` tokens on serialization - Lexer - Removed `Lexer#matchDeclaration()` method - Utils - Added `ident`, `string` and `url` helpers to decode/encode corresponding values, e.g. `url.decode('url("image.jpg")')` === `'image.jpg'` - List - Changed `List` to be iterable (iterates data) - Changed `List#first`, `List#last` and `List#isEmpty` to getters - Changed `List#getSize()` method to `List#size` getter - Removed `List#each()` and `List#eachRight()` methods, `List#forEach()` and `List#forEachRight()` should be used instead ## 1.1.3 (March 31, 2021) - Fixed matching on CSS wide keywords for at-rule's prelude and descriptors - Added `fit-content` to `width` property patch as browsers are supported it as a keyword (nonstandard), but spec defines it as a function - Fixed parsing a value contains parentheses or brackets and `parseValue` option is set to `false`, in that case `!important` was included into a value but must not (#155) ## 1.1.2 (November 26, 2020) - Rolled back to use spread syntax in object literals since it not supported by nodejs < 8.3 (#145) ## 1.1.1 (November 18, 2020) - Fixed edge cases in mismatch location computation for `SyntaxMatchError` ## 1.1.0 (November 17, 2020) - Bumped `mdn-data` to 2.0.14 - Extended `fork()` method to allow append syntax instead of overriding for `types`, `properties` and `atrules`, e.g. `csstree.fork({ types: { color: '| foo | bar' } })` - Extended lexer API for validation - Added `Lexer#checkAtruleName(atruleName)`, `Lexer#checkAtrulePrelude(atruleName, prelude)`, `Lexer#checkAtruleDescriptorName(atruleName, descriptorName)` and `Lexer#checkPropertyName(propertyName)` - Added `Lexer#getAtrule(atruleName, fallbackBasename)` method - Extended `Lexer#getAtrulePrelude()` and `Lexer#getProperty()` methods to take `fallbackBasename` parameter - Improved `SyntaxMatchError` location details - Changed error messages ## 1.0.1 (November 11, 2020) - Fixed edge cases for parsing of custom property value with a single whitespace when `parseCustomProperty:true` ## 1.0.0 (October 27, 2020) - Added `onComment` option to parser config - Added support for `break` and `skip` values in `walk()` to control traversal - Added `List#reduce()` and `List#reduceRight()` methods - Bumped `mdn-data` to 2.0.12 - Exposed version of the lib (i.e. `import { version } from 'css-tree'`) - Fixed `Lexer#dump()` to dump atrules syntaxes as well - Fixed matching comma separated `` list (#135) - Renamed `HexColor` node type into `Hash` - Removed `element()` specific parsing rules - Removed `dist/default-syntax.json` from package ## 1.0.0-alpha.39 (December 5, 2019) - Fixed walker with `visit: "Declaration"` to iterate `DeclarationList` (#114) ## 1.0.0-alpha.38 (November 25, 2019) - Bumped `mdn-data` to `2.0.6` - Added initial implmentation for at-rule matching via `Lexer#matchAtrulePrelude()` and `Lexer#matchAtruleDescriptor()` methods - Added `-moz-control-character-visibility`, `-ms-grid-columns`, `-ms-grid-rows` and `-ms-hyphenate-limit-last` properties to patch (#111) - Added `flow`, `flow-root` and `table-caption` values to patched `display` (#112) ## 1.0.0-alpha.37 (October 22, 2019) - Bumped `source-map` version to `^0.6.1` to fix source map generation inconsistency across node.js versions due to mappings sorting bug and v8 moving to [a stable Array#sort](https://v8.dev/blog/array-sort) ([fix commit](https://github.com/mozilla/source-map/commit/f35a2e4212dd025cb5e1fc219e7ac8a4b96c2cc9) in `source-map`) ## 1.0.0-alpha.36 (October 13, 2019) - Dropped support for Node < 8 - Updated dev deps (fixed `npm audit` issues) - Reworked build pipeline - Package provides `dist/csstree.js` and `dist/csstree.min.js` now (instead of single `dist/csstree.js` that was a min version) - Bundle size (min version) reduced from 191Kb to 158Kb due to some optimisations - Definition syntax - Renamed `grammar` into `definitionSyntax` (named per spec) - Added `compact` option to `generate()` method to avoid formatting (spaces) when possible - Lexer - Changed `dump()` method to produce syntaxes in compact form by default ## 1.0.0-alpha.35 (October 7, 2019) - Walker - Changed implementation to avoid runtime compilation due to CSP issues (see #91, #109) - Added `find()`, `findLast()` and `findAll()` methods (e.g. `csstree.find(ast, node => node.type === 'ClassSelector')`) ## 1.0.0-alpha.34 (July 27, 2019) - Tokenizer - Added `isBOM()` function - Added `charCodeCategory()` function - Removed `firstCharOffset()` function (use `isBOM()` instead) - Removed `CHARCODE` dictionary - Removed `INPUT_STREAM_CODE*` dictionaries - Lexer - Allowed comments in matching value (just ignore them like whitespaces) - Increased iteration count in value matching from 10k up to 15k - Fixed missed `debugger` (#104) ## 1.0.0-alpha.33 (July 11, 2019) - Lexer - Fixed low priority productions matching by changing an approach for robust one (#103) ## 1.0.0-alpha.32 (July 11, 2019) - Lexer - Fixed low priority productions matching in long `||-` and `&&-` groups (#103) ## 1.0.0-alpha.31 (July 11, 2019) - Bumped `mdn/data` to `2.0.4` (#99) - Lexer - Added [bracketed range notation](https://drafts.csswg.org/css-values-4/#numeric-ranges) support and related refactoring - Removed ``, `` and `` from generic types. In fact, types moved to patch, because those types can be expressed in a regular grammar due to bracketed range notation implemented - Added support for multiple token string matching - Improved `` production matching to claim the keyword only if no other unfulfilled production can claim it (#101) - Improved `` production matching to claim "unitless zero" only if no other unfulfilled production can claim it - Changed lexer's constructor to prevent generic types override when used - Fixed large `||`- and `&&`-group matching, matching continues from the beginning on term match (#85) - Fixed checking that value has `var()` occurrences when value is a string (such values can't be matched on syntax currently and fail with specific error that can be used for ignorance in validation tools) - Fixed `` and `` matching when a value contains a function, parentheses or braces ## 1.0.0-alpha.30 (July 3, 2019) - Bumped `mdn/data` to `~2.0.3` - Removed type removals from `mdn/data` due to lack of some generic types and specific lexer restictions (since lexer was reworked, see below) - Reduced and updated patches - Tokenizer - Reworked tokenizer itself to compliment [CSS Syntax Module Level 3](https://drafts.csswg.org/css-syntax/#tokenization) - `Tokenizer` class splitted into several abstractions: - Added `TokenStream` class - Added `OffsetToLocation` class - Added `tokenize()` function that creates `TokenStream` instance for given string or updates a `TokenStream` instance passed as second parameter - Removed `Tokenizer` class - Removed `Raw` token type - Renamed `Identifier` token type to `Ident` - Added token types: `Hash`, `BadString`, `BadUrl`, `Delim`, `Percentage`, `Dimension`, `Colon`, `Semicolon`, `Comma`, `LeftSquareBracket`, `RightSquareBracket`, `LeftParenthesis`, `RightParenthesis`, `LeftCurlyBracket`, `RightCurlyBracket` - Replaced `Punctuator` with `Delim` token type, that excludes specific characters with its own token type like `Colon`, `Semicolon` etc - Removed `findCommentEnd`, `findStringEnd`, `findDecimalNumberEnd`, `findNumberEnd`, `findEscapeEnd`, `findIdentifierEnd` and `findUrlRawEnd` helper function - Removed `SYMBOL_TYPE`, `PUNCTUATION` and `STOP_URL_RAW` dictionaries - Added `isDigit`, `isHexDigit`, `isUppercaseLetter`, `isLowercaseLetter`, `isLetter`, `isNonAscii`, `isNameStart`, `isName`, `isNonPrintable`, `isNewline`, `isWhiteSpace`, `isValidEscape`, `isIdentifierStart`, `isNumberStart`, `consumeEscaped`, `consumeName`, `consumeNumber` and `consumeBadUrlRemnants` helper functions - Parser - Changed parsing algorithms to work with new token type set - Changed `HexColor` consumption in way to relax checking a value, i.e. now `value` is a sequence of one or more name chars - Added `&` as a property hack - Relaxed `var()` parsing to only check that a first arguments is an identifier (not a custom property name as before) - Lexer - Reworked syntax matching to relay on token set only (having AST is optional now) - Extended `Lexer#match()`, `Lexer#matchType()` and `Lexer#matchProperty()` methods to take a string as value, beside AST as a value - Extended `Lexer#match()` method to take a string as a syntax, beside of syntax descriptor - Reworked generic types: - Removed ``, `` (moved to patch) and `` types - Added types: - Related to token types: ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, `<[-token>`, `<]-token>`, `<(-token>`, `<)-token>`, `<{-token>` and `<}-token>` - Complex types: ``, ``, ``, ``, `` and `` - Renamed `` to `` as per spec - Renamed `` (IE legacy extension) to `<-ms-legacy-expression>` and may to be removed in next releases ## 1.0.0-alpha.29 (May 30, 2018) - Lexer - Syntax matching was completely reworked. Now it's token-based and uses state machine. Public API has not changed. However, some internal data structures have changed. Most significal change in syntax match result tree structure, it's became token-based instead of node-based. - Grammar - Changed grammar tree format: - Added `Token` node type to represent a single code point (``) - Added `Multiplier` that wraps a single node (`term` property) - Added `AtKeyword` to represent `` - Removed `Slash` and `Percent` node types, they are replaced for a node with `Token` type - Changed `Function` to represent `` with no children - Removed `multiplier` property from `Group` - Changed `generate()` method: - Method takes an `options` as second argument now (`generate(node, forceBraces, decorator)` -> `generate(node, options)`). Two options are supported: `forceBraces` and `decorator` - When a second parameter is a function it treats as `decorate` option value, i.e. `generate(node, fn)` -> `generate(node, { decorate: fn })` - Decorate function invokes with additional parameter – a reference to a node - Tokenizer - Renamed `Atrule` const to `AtKeyword` ## 1.0.0-alpha.28 (February 19, 2018) - Renamed `lexer.grammar.translate()` method into `generate()` - Fixed `<'-webkit-font-smoothing'>` and `<'-moz-osx-font-smoothing'>` syntaxes (#75) - Added vendor keywords for `<'overflow'>` property syntax (#76) - Pinned `mdn-data` to `~1.1.0` and fixed issues with some updated property syntaxes ## 1.0.0-alpha.27 (January 14, 2018) - Generator - Changed node's `generate()` methods invocation, methods now take a node as a single argument and context (i.e. `this`) that have methods: `chunk()`, `node()` and `children()` - Renamed `translate()` to `generate()` and changed to take `options` argument - Removed `translateMarkup(ast, enter, leave)` method, use `generate(ast, { decorator: (handlers) => { ... }})` instead - Removed `translateWithSourceMap(ast)`, use `generate(ast, { sourceMap: true })` instead - Changed to support for children as an array - Walker - Changed `walk()` to take an `options` argument instead of handler, with `enter`, `leave`, `visit` and `reverse` options (`walk(ast, fn)` is still works and equivalent to `walk(ast, { enter: fn })`) - Removed `walkUp(ast, fn)`, use `walk(ast, { leave: fn })` - Removed `walkRules(ast, fn)`, use `walk(ast, { visit: 'Rule', enter: fn })` instead - Removed `walkRulesRight(ast, fn)`, use `walk(ast, { visit: 'Rule', reverse: true, enter: fn })` instead - Removed `walkDeclarations(ast, fn)`, use `walk(ast, { visit: 'Declaration', enter: fn })` instead - Changed to support for children as array in most cases (`reverse: true` will fail on arrays since they have no `forEachRight()` method) - Misc - List - Added `List#forEach()` method - Added `List#forEachRight()` method - Added `List#filter()` method - Changed `List#map()` method to return a `List` instance instead of `Array` - Added `List#push()` method, similar to `List#appendData()` but returns nothing - Added `List#pop()` method - Added `List#unshift()` method, similar to `List#prependData()` but returns nothing - Added `List#shift()` method - Added `List#prependList()` method - Changed `List#insert()`, `List#insertData()`, `List#appendList()` and `List#insertList()` methods to return a list that performed an operation - Changed `keyword()` method - Changed `name` field to include a vendor prefix - Added `basename` field to contain a name without a vendor prefix - Added `custom` field that contain a `true` when keyword is a custom property reference - Changed `property()` method - Changed `name` field to include a vendor prefix - Added `basename` field to contain a name without any prefixes, i.e. a hack and a vendor prefix - Added `vendorPrefix()` method - Added `isCustomProperty()` method ## 1.0.0-alpha.26 (November 9, 2017) - Tokenizer - Added `Tokenizer#isBalanceEdge()` method - Removed `Tokenizer.endsWith()` method - Parser - Made the parser tolerant to errors by default - Removed `tolerant` parser option (no parsing modes anymore) - Removed `property` parser option (a value parsing does not depend on property name anymore) - Canceled error for a handing semicolon in a block - Canceled error for unclosed `Brackets`, `Function` and `Parentheses` when EOF is reached - Fixed error when prelude ends with a comment for at-rules with custom prelude consumer - Relaxed at-rule parsing: - Canceled error when EOF is reached after a prelude - Canceled error for an at-rule with custom block consumer when at-rule has no block (just don't apply consumer in that case) - Canceled error on at-rule parsing when it occurs outside prelude or block (at-rule is converting to `Raw` node) - Allowed for any at-rule to have a prelude and a block, even if it's invalid per at-rule syntax (the responsibility for this check is moved to lexer, since it's possible to construct a AST with such errors) - Made a declaration value a safe parsing point (i.e. error on value parsing lead to a value is turning into `Raw` node, not a declaration as before) - Excluded surrounding white spaces and comments from a `Raw` node that represents a declaration value - Changed `Value` parse handler to return a node only with type `Value` (previously it returned a `Raw` node in some cases) - Fixed issue with `onParseError()` is not invoked for errors occured on selector or declaration value parsing in some cases - Changed using of `onParseError()` to stop parsing if handler throws an exception - Lexer - Changed `grammar.walk()` to invoke passed handler on entering to node rather than on leaving the node - Improved `grammar.walk()` to take a walk handler pair as an object, i.e. `walk(node, { enter: fn, leave: fn })` - Changed `Lexer#match*()` methods to take a node of any type, but with a `children` field - Added `Lexer#match(syntax, node)` method - Fixed `Lexer#matchType()` method to stop return a positive result for the CSS wide keywords ## 1.0.0-alpha25 (October 9, 2017) - Parser - Added fallback node as argument to `onParseError()` handler - Fixed raw consuming in tolerant mode when selector is invalid (greedy consuming and redundant warnings) - Fixed exception in tolerant mode caused by unknown at-rule with unclosed block - Changed handling of semicolons: - Hanging semicolon inside declaration blocks raise an error or turns into a `Raw` node in tolerant mode instead of being ignored - Semicolon outside of declaration blocks opens a `Rule` node as part of selector instead of being ignored - Aligned `parseAtrulePrelude` behaviour to `parseRulePrelude` - Removed `Raw` node wraping into `AtrulePrelude` when `parseAtrulePrelude` is disabled - Removed error emitting when at-rule has a custom prelude customer but no prelude is found (it should be validated by a lexer later) - Generator - Fixed performance issue with `translateWithSourceMap()`, flattening the string (because of mixing building string and indexing into it) turned it into a quadratic algorithm (approximate numbers can be found in [the quiz created by this case](https://gist.github.com/lahmatiy/ea25d0e623d88ca9848384b5707d52d9)) - Added support for a single solidus hack for `property()` - Minor fixes for custom errors ## 1.0.0-alpha24 (September 14, 2017) - Improved CSSTree to be stable for standart build-in objects extension (#58) - Parser - Renamed rule's `selector` to `prelude`. The reasons: [spec names this part so](https://www.w3.org/TR/css-syntax-3/#qualified-rule), and this branch can contain not only a selector (`SelectorList`) but also a raw payload (`Raw`). What's changed: - Renamed `Rule.selector` to `Rule.prelude` - Renamed `parseSelector` parser option to `parseRulePrelude` - Removed option for selector parse in `SelectorList` - Lexer - Fixed undefined positions in a error when match a syntax to empty or white space only value - Improved `Lexer#checkStructure()` - Return a warning as an object with node reference and message - No exception on unknown node type, return a warning instead ## 1.0.0-alpha23 (September 10, 2017) - Fixed `Tokenizer#getRawLength()`'s false positive balance match to the end of input in some cases (#56) - Rename walker's entry point methods to be the same as CSSTree exposed methods (i.e. `walk()`, `walkUp()` etc) - Rename at-rule's `expression` to `prelude` (since [spec names it so](https://www.w3.org/TR/css-syntax-3/#at-rule)) - `AtruleExpression` node type → `AtrulePrelude` - `Atrule.expression` field → `Atrule.prelude` - `parseAtruleExpression` parser's option → `parseAtrulePrelude` - `atruleExpression` parse context → `atrulePrelude` - `atruleExpression` walk context reference → `atrulePrelude` ## 1.0.0-alpha22 (September 8, 2017) - Parser - Fixed exception on parsing of unclosed `{}-block` in tolerant mode - Added tolerant mode support for `DeclarationList` - Added standalone entry point, i.e. default parser can be used via `require('css-tree/lib/parser')` (#47) - Generator - Changed generator to produce `+n` when `AnPlusB.a` is `+1` to be "round-trip" with parser - Added standalone entry point, i.e. default generators can be used via `require('css-tree/lib/generator')` - Walker - Added standalone entry point, i.e. default walkers can be used via `require('css-tree/lib/walker')` (#47) - Lexer - Added `default` keyword to the list of invalid values for `` (since it reversed per [spec](https://www.w3.org/TR/css-values/#custom-idents)) - Convertors (`toPlainObject()` and `fromPlainObject()`) moved to `lib/convertor` (entry point is `require('css-tree/lib/convertor')`) ## 1.0.0-alpha21 (September 5, 2017) - Tokenizer - Added `Raw` token type - Improved tokenization of `url()` with raw as url to be more spec complient - Added `Tokenizer#balance` array computation on token layout - Added `Tokenizer#getRawLength()` to compute a raw length with respect of block balance - Added `Tokenizer#getTokenStart(offset)` method to get token start offset by token index - Added `idx` and `balance` fields to each token of `Tokenizer#dump()` method result - Parser - Added `onParseError` option - Reworked node parsers that consume a `Raw` node to use a new approach. Since now a `Raw` node builds in `parser#Raw()` function only - Changed semantic of `parser#Raw()`, it takes 5 parameters now (it might to be changed in future) - Changed `parser#tolerantParse()` to pass a start token index to fallback function instead of source offset - Fixed `AtruleExpression` consuming in tolerant mode - Atrule handler to convert an empty `AtruleExpression` node into `null` - Changed `AtruleExpression` handler to always return a node (before it could return a `null` in some cases) - Lexer - Fixed comma match node for `#` multiplier - Added reference name to `SyntaxReferenceError` - Additional fixes on custom errors - Reduced possible corruption of base config by `syntax.fork()` ## 1.0.0-alpha20 (August 28, 2017) - Tokenizer - Added `Atrule` token type (`` per spec) - Added `Function` token type (`` per spec) - Added `Url` token type - Replaced `Tokenizer#getTypes()` method with `Tokenizer#dump()` to get all tokens as an array - Renamed `Tokenizer.TYPE.Whitespace` to `Tokenizer.TYPE.WhiteSpace` - Renamed `Tokenizer.findWhitespaceEnd()` to `Tokenizer.findWhiteSpaceEnd()` - Parser - Added initial implementation of tollerant mode (turn on by passing `tolerant: true` option). In this mode parse errors are never occour and any invalid part of CSS turns into a `Raw` node. Current safe points: `Atrule`, `AtruleExpression`, `Rule`, `Selector` and `Declaration`. Feature is experimental and further improvements are planned. - Changed `Atrule.expression` to contain a `AtruleExpression` node or `null` only (other node types is wrapping into a `AtruleExpression` node) - Renamed `AttributeSelector.operator` to `AttributeSelector.matcher` - Generator - `translate()` method is now can take a function as second argument, that recieves every generated chunk. When no function is passed, default handler is used, it concats all the chunks and method returns a string. - Lexer - Used [mdn/data](https://github.com/mdn/data) package as source of lexer's grammar instead of local dictionaries - Added `x` unit to `` generic type - Improved match tree: - Omited Group (sequences) match nodes - Omited empty match nodes (for terms with `zero or more` multipliers) - Added `ASTNode` node type to contain a reference to AST node - Fixed node duplication (uncompleted match were added to tree) - Added AST node reference in match nodes - Added comma match node by `#` multiplier - Grammar - Changed `translate()` function to get a handler as third argument (optional). That handler recieves result of node traslation and can be used for decoration purposes. See [example](https://github.com/csstree/docs/blob/04c65af44477b5ea05feb373482898122b2a4528/docs/syntax.html#L619-L627) - Added `SyntaxParseError` to grammar export - Reworked group and multipliers representation in syntax tree: - Replaced `Sequence` for `Group` node type (`Sequence` node type removed) - Added `explicit` boolean property for `Group` - Only groups can have a multiplier now (other node types is wrapping into a single term implicit group when multiplier is applied) - Renamed `nonEmpty` Group's property to `disallowEmpty` - Added optimisation for syntax tree by dropping redundant root `Group` when it contains a single `Group` term (return this `Group` as a result) - Changed lexer's match functionality - Changed `Lexer#matchProperty()` and `Lexer#matchType()` to return an object instead of match tree. A match tree stores in `matched` field when AST is matched to grammar successfully, otherwise an error in `error` field. The result object also has some methods to test AST node against a match tree: `getTrace()`, `isType()`, `isProperty()` and `isKeyword()` - Added `Lexer#matchDeclaration()` method - Removed `Lexer#lastMatchError` (error stores in match result object in `error` field) - Added initial implementation of search for AST segments (new lexer methods: `Lexer#findValueSegments()`, `Lexer#findDeclarationValueSegments()` and `Lexer#findAllSegments`) - Implemented `SyntaxReferenceError` for unknown property and type references - Renamed field in resulting object of `property()` function: `variable` → `custom` - Fixed issue with readonly properties (e.g. `line` and `column`) of `Error` and exception on attempt to write in iOS Safari ## 1.0.0-alpha19 (April 24, 2017) - Extended `List` class with new methods: - `List#prepend(item)` - `List#prependData(data)` - `List#insertData(data)` - `List#insertList(list)` - `List#replace(item, itemOrList)` ## 1.0.0-alpha18 (April 3, 2017) - Added `atrule` walk context (#39) - Changed a result of generate method for `AnPlusB`, `AttributeSelector`, `Function`, `MediaFeature` and `Ratio` ([1e95877](https://github.com/csstree/csstree/commit/1e9587710efa8e9338bcf0bc794b4b45f286231d)) - Fixed typo in `List` exception messages (@strarsis, #42) - Improved tokenizer to convert an input to a string ## 1.0.0-alpha17 (March 13, 2017) - Implemented new concept of `syntax` - Changed main `exports` to expose a default syntax - Defined initial [CSS syntax](lib/syntax/default.js) - Implemented `createSyntax()` method to create a new syntax from scratch - Implemented `fork()` method to create a new syntax based on given via extension - Parser - Implemented `mediaQueryList` and `mediaQuery` parsing contexts - Implemented `CDO` and `CDC` node types - Implemented additional declaration property prefix hacks (`#` and `+`) - Added support for UTF-16LE BOM - Added support for `@font-face` at-rule - Added `chroma()` to legacy IE filter functions - Improved `HexColor` to consume hex only - Improved support for `\0` and `\9` hacks (#2) - Relaxed number check for `Ratio` terms - Allowed fractal values as a `Ratio` term - Disallowed zero number as a `Ratio` term - Changed important clause parsing - Allowed any identifier for important (to support hacks like `!ie`) - Store `true` for `important` field in case identifier equals to `important` and string otherwise - Fixed parse error formatted message rendering to take into account tabs - Removed exposing of `Parser` class - Removed `readSelectorSequence()`, `readSequenceFallback()` and `readSelectorSequenceFallback` methods - Used single universal sequence consumer for `AtruleExpression`, `Selector` and `Value` - Generator - Reworked generator to use auto-generated functions based on syntax definition (additional work to be done in next releases) - Implemented `translateMarkup(ast, before, after)` method for complex cases - Reworked `translateWithSourceMap` to be more flexible (based on `translateMarkup`, additional work to be done in next releases) - Walker - Reworked walker to use auto-generated function based on syntax definition (additional work to be done in next releases) - Lexer - Prepared for better extensibility (additional work to be done in next releases) - Implemented `checkStructure(ast)` method to check AST structure based on syntax definition - Update syntax dictionaries to latest `mdn/data` - Add missing `<'offset-position'>` syntax - Extended `` property with `-webkit-sticky` (@sergejmueller, #37) - Improved mismatch error position - Implemented script (`gen:syntax`) to generate AST format reference page (`docs/ast.md`) using syntax definition ## 1.0.0-alpha16 (February 12, 2017) - Exposed `Parser` class - Added `startOffset` option to `Tokenizer` (constructor and `setSource()` method) - Added fallback functions for default (`readSequenceFallback`) and selector (`readSelectorSequenceFallback`) sequence readers - Fixed edge cases for `AnPlusB` - Fixed wrong whitespace ignoring in `Selector` consumer ## 1.0.0-alpha15 (February 8, 2017) - Fixed broken `atruleExpression` context - Fixed vendor prefix detection in `keyword()` and `property()` - Fixed `property()` to not lowercase custom property names - Added `variable` boolean flag in `property()` result - Renamed `scanner` into `tokenizer` - Ranamed `syntax` into `lexer` - Moved `docs/*.html` files to [csstree/docs](https://github.com/csstree/docs) repo - Added `element()` function for `Value` context (`-moz-element()` supported as well) - Merged `Universal` node type into `Type` - Renamed node types: - `Id` -> `IdSelector` - `Class` -> `ClassSelector` - `Type` -> `TypeSelector` - `Attribute` -> `AttributeSelector` - `PseudoClass` -> `PseudoClassSelector` - `PseudoElement` -> `PseudoElementSelector` - `Hash` -> `HexColor` - `Space` -> `WhiteSpace` - `An+B` -> `AnPlusB` - Removed `Progid` node type - Relaxed `MediaQuery` consumer to not validate syntax on parse and to include whitespaces in children sequence as is - Added `WhiteSpace.value` property to store whitespace sequence - Implemented parser options to specify what should be parsed in details (when option is `false` some part of CSS represents as balanced `Raw`): - `parseAtruleExpression` – to parse at-rule expressions (`true` by default) - `parseSelector` – to parse rule's selector (`true` by default) - `parseValue` - to parse declaration's value (`true` by default) - `parseCustomProperty` – to parse value and fallback of custom property (`false` by default) - Changed tokenization to stick leading hyphen minus to identifier token - Changed selector parsing: - Don't convert spaces into descendant combinator - Don't validate selector structure on parsing (selectors may be checked by lexer later) - Initial refactoring of [docs](https://github.com/csstree/csstree/blob/master/docs) - Various improvements and fixes ## 1.0.0-alpha14 (February 3, 2017) - Implemented `DeclarationList`, `MediaQueryList`, `MediaQuery`, `MediaFeature` and `Ratio` node types - Implemented `declarationList` context (useful to parse HTML `style` attribute content) - Implemented custom consumers for `@import`, `@media`, `@page` and `@supports` at-rules - Implemented `atrule` option for `parse()` config, is used for `atruleExpession` context to specify custom consumer for at-rule if any - Added `Scanner#skipWS()`, `Scanner#eatNonWS()`, `Scanner#consume()` and `Scanner#consumeNonWS()` helper methods - Added custom consumers for known functional-pseudos, consume unknown functional-pseudo content as balanced `Raw` - Allowed any `PseudoElement` to be a functional-pseudo (#33) - Improved walker implementations to reduce GC thrashing by reusing cursors - Changed `Atrule.block` to contain a `Block` node type only if any - Changed `Block.loc` positions to include curly brackets - Changed `Atrule.expression` to store a `null` if no expression - Changed parser to use `StyleSheet` node type only for top level node (when context is `stylesheet`, that's by default) - Changed `Parentheses`, `Brackets` and `Function` consumers to use passed sequence reader instead of its own - Changed `Value` and `AtruleExpression` consumers to use common sequence reader (that reader was used by `Value` consumer before) - Changed default sequence reader to exclude storage of spaces around `Comma` - Changed processing of custom properties: - Consume declaration value as balanced `Raw` - Consume `var()` fallback value as balanced `Raw` - Validate first argument of `var()` starts with double dash - Custom property's value and fallback includes spaces around - Fixed `Nth` to have a `loc` property - Fixed `SelectorList.loc` and `Selector.loc` positions to exclude spaces - Fixed issue Browserify build fail with `default-syntax.json` is not found error (#32, @philschatz) - Disallowed `Type` selector starting with dash (parser throws an error in this case now) - Disallowed empty selectors for `Rule` (not sure if it's correct but looks reasonable) - Removed `>>` combinator support until any browser support (no signals about that yet) - Removed `PseudoElement.legacy` property - Removed special case for `:before`, `:after`, `:first-letter` and `:first-line` to represent them as `PseudoElement`, now those pseudos are represented as `PseudoClass` nodes - Removed deprecated `Syntax#match()` method - Parser was splitted into modules and related changes, one step closer to an extensible parser - Various fixes and improvements, all changes have negligible impact on performance ## 1.0.0-alpha13 (January 19, 2017) - Changed location storing in `SyntaxMatchError` - Changed property to store mismatch offset to `mismatchOffset` - Changed `offset` property to store bad node offset in source CSS if any - Added `loc` property that stores bad node `loc` if any ## 1.0.0-alpha12 (January 19, 2017) - Fixed `Syntax#matchProperty()` method to always return a positive result for custom properties since syntax is never defined for them (#31) - Implemented `fromPlainObject()` and `toPlainObject()` to convert plain object to AST or AST to plain object (currently converts `List` <-> `Array`) ## 1.0.0-alpha11 (January 18, 2017) - Added support for `:matches()` (#28) - Added support for `:has()` - Added support for `::slotted()` - Implemented `Brackets` node type - Implemented basic support for at-rule inside rule block (#24) - Renamed `Selector` node type to `SelectorList` - Renamed `SimpleSelector` node type to `Selector` - Renamed `UnicodeRange.name` property to `UnicodeRange.value` - Replaced `Negation` node type for regular `PseudoClass` - Unified name of node property to store nested nodes, it always `children` now: - `StyleSheet.rules` -> `StyleSheet.children` - `SelectorList.selectors` -> `SelectorList.children` - `Block.declarations` -> `Block.children` - `*.sequence` -> `*.children` - Fixed edge cases in parsing `Hex` and `UnicodeRange` when number not an integer - Changed `nth-` pseudos parsing - Implemented `An+B` node type to represent expressions like `2n + 1` or `-3n` - Fixed edge cases when `a` or `b` is not an integer - Changed `odd` and `even` keywords processing, keywords are storing as `Identifier` node type now - Changed `Nth` node type format to store a `nth`-query and an optional `selector` - Implemented `of` clause for `nth-` pseudos (a.e. `:nth-child(2n + 1 of li, img)`) - Limited `Nth` parsing rules to `:nth-child()`, `:nth-last-child()`, `:nth-of-type()` and `:nth-last-of-type()` pseudos - Changed the way to store locations - Renamed `info` node property to `loc` - Changed format of `loc` to store `start` and `end` positions ## 1.0.0-alpha10 (January 11, 2017) - Reworked `Scanner` to be a single point to its functionality - Exposed `Scanner` class to be useful for external projects - Changed `walk()` function behaviour to traverse AST nodes in natural order - Implemented `walkUp()` function to traverse AST nodes from deepest to parent (behaves as `walk()` before) ## 1.0.0-alpha9 (December 21, 2016) - Fixed `` generic according to specs that allow a `` equals to zero to be used as valid value (#30) ## 1.0.0-alpha8 (November 11, 2016) - Fixed `Scanner#skip()` issue method when cursor is moving to the end of source - Simplified `Progid` node - Changed behaviour for bad selector processing, now parsing fails instead of selector ignoring - Fixed `` generic syntax - Added `q` unit for `` generic syntax - Refactored syntax parser (performance) - Reduced startup time by implementing lazy syntax parsing (default syntax doesn't parse on module load) - Updated syntax dictionaries and used [`mdn/data`](https://github.com/mdn/data) instead of `Template:CSSData` - Renamed `syntax.stringify()` method to `syntax.translate()` - Simplified generic syntax functions, those functions receive a single AST node for checking and should return `true` or `false` - Added exception for values that contains `var()`, those values are always valid for now - Added more tests and increase code coverage to `98.5%` ## 1.0.0-alpha7 (October 7, 2016) - Added support for explicit descendant combinator (`>>`) - Implemented `Type` and `Universal` type nodes - Improved `Number` parsing by including sign and exponent (#26) - Parse `before`, `after`, `first-letter` and `first-line` pseudos with single colon as `PseudoElement` - Changed `FunctionalPseudo` node type to `PseudoClass` - Fixed attribute selector name parsing (namespace edge cases) - Fixed location calculation for specified offset when `eof` is reached - Added more non-standard colors (#25) - Removed obsolete `Syntax#getAll()` method - Fixed various edge cases, code clean up and performance improvements ## 1.0.0-alpha6 (September 23, 2016) - More accurate positions for syntax mismatch errors - Added [`apple`](https://webkit.org/blog/3709/using-the-system-font-in-web-content/) specific font keywords (#20) - Changed `Property` node stucture from object to string - Renamed `Ruleset` node type to `Rule` - Removed `Argument` node type - Fixed `Dimension` and `Percentage` position computation - Fixed bad selector parsing (temporary solution) - Fixed location computation for CSS with very long lines that may lead to really long parsing with `positions:true` (even freeze) - Fixed `line` and `column` computation for `SyntaxMatch` error - Improved performance of parsing and translation. Now CSSTree is under 10ms in [PostCSS benchmark](https://github.com/postcss/benchmark). csstree-2.0.4/LICENSE000066400000000000000000000020511415712374100141750ustar00rootroot00000000000000Copyright (C) 2016-2022 by Roman Dvornov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. csstree-2.0.4/README.md000066400000000000000000000203351415712374100144540ustar00rootroot00000000000000CSSTree logo # CSSTree [![NPM version](https://img.shields.io/npm/v/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Build Status](https://github.com/csstree/csstree/actions/workflows/build.yml/badge.svg)](https://github.com/csstree/csstree/actions/workflows/build.yml) [![Coverage Status](https://coveralls.io/repos/github/csstree/csstree/badge.svg?branch=master)](https://coveralls.io/github/csstree/csstree?branch=master) [![NPM Downloads](https://img.shields.io/npm/dm/css-tree.svg)](https://www.npmjs.com/package/css-tree) [![Twitter](https://img.shields.io/badge/Twitter-@csstree-blue.svg)](https://twitter.com/csstree) CSSTree is a tool set for CSS: [fast](https://github.com/postcss/benchmark) detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks. ## Features - **Detailed parsing with an adjustable level of detail** By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declaration values for component parts. - **Tolerant to errors by design** Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (`Raw`) that allows processing it later. - **Fast and efficient** CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment. - **Syntax validation** The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future. ## Projects using CSSTree - [Svelte](https://github.com/sveltejs/svelte) – Cybernetically enhanced web apps - [SVGO](https://github.com/svg/svgo) – Node.js tool for optimizing SVG files - [CSSO](https://github.com/css/csso) – CSS minifier with structural optimizations - [NativeScript](https://github.com/NativeScript/NativeScript) – NativeScript empowers you to access native APIs from JavaScript directly - [react-native-svg](https://github.com/react-native-svg/react-native-svg) – SVG library for React Native, React Native Web, and plain React web projects - [penthouse](https://github.com/pocketjoso/penthouse) – Critical Path CSS Generator - [Bit](https://github.com/teambit/bit) – Bit is the platform for collaborating on components - and more... ## Documentation - [AST format](docs/ast.md) - [Parsing CSS → AST](docs/parsing.md) - [parse(source[, options])](docs/parsing.md#parsesource-options) - [Serialization AST → CSS](docs/generate.md) - [generate(ast[, options])](docs/generate.md#generateast-options) - [AST traversal](docs/traversal.md) - [walk(ast, options)](docs/traversal.md#walkast-options) - [find(ast, fn)](docs/traversal.md#findast-fn) - [findLast(ast, fn)](docs/traversal.md#findlastast-fn) - [findAll(ast, fn)](docs/traversal.md#findallast-fn) - [Util functions](docs/utils.md) - Value encoding & decoding - [property(name)](docs/utils.md#propertyname) - [keyword(name)](docs/utils.md#keywordname) - [ident](docs/utils.md#ident) - [string](docs/utils.md#string) - [url](docs/utils.md#url) - AST transforming - [clone(ast)](docs/utils.md#cloneast) - [fromPlainObject(object)](docs/utils.md#fromplainobjectobject) - [toPlainObject(ast)](docs/utils.md#toplainobjectast) - [Value Definition Syntax](docs/definition-syntax.md) - [parse(source)](docs/definition-syntax.md#parsesource) - [walk(node, options, context)](docs/definition-syntax.md#walknode-options-context) - [generate(node, options)](docs/definition-syntax.md#generatenode-options) - [AST format](docs/definition-syntax.md#ast-format) ## Tools * [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) – explore CSSTree AST format with zero setup * [CSS syntax reference](https://csstree.github.io/docs/syntax.html) * [CSS syntax validator](https://csstree.github.io/docs/validator.html) ## Related projects * [csstree-validator](https://github.com/csstree/validator) – NPM package to validate CSS * [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) – plugin for stylelint to validate CSS * [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator) * [Gulp plugin](https://github.com/csstree/gulp-csstree) * [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree) * [VS Code plugin](https://github.com/csstree/vscode-plugin) * [Atom plugin](https://github.com/csstree/atom-plugin) ## Usage Install with npm: ``` npm install css-tree ``` Basic usage: ```js import * as csstree from 'css-tree'; // parse CSS to AST const ast = csstree.parse('.example { world: "!" }'); // traverse AST and modify it csstree.walk(ast, (node) => { if (node.type === 'ClassSelector' && node.name === 'example') { node.name = 'hello'; } }); // generate CSS from AST console.log(csstree.generate(ast)); // .hello{world:"!"} ``` Syntax matching: ```js // parse CSS to AST as a declaration value const ast = csstree.parse('red 1px solid', { context: 'value' }); // match to syntax of `border` property const matchResult = csstree.lexer.matchProperty('border', ast); // check first value node is a console.log(matchResult.isType(ast.children.first(), 'color')); // true // get a type list matched to a node console.log(matchResult.getTrace(ast.children.first())); // [ { type: 'Property', name: 'border' }, // { type: 'Type', name: 'color' }, // { type: 'Type', name: 'named-color' }, // { type: 'Keyword', name: 'red' } ] ``` ### Exports Is it possible to import just a needed part of library like a parser or a walker. That's might useful for loading time or bundle size optimisations. ```js import * as tokenizer from 'css-tree/tokenizer'; import * as parser from 'css-tree/parser'; import * as walker from 'css-tree/walker'; import * as lexer from 'css-tree/lexer'; import * as definitionSyntax from 'css-tree/definition-syntax'; import * as data from 'css-tree/definition-syntax-data'; import * as dataPatch from 'css-tree/definition-syntax-data-patch'; import * as utils from 'css-tree/utils'; ``` ### Using in a browser Bundles are available for use in a browser: - `dist/csstree.js` – minified IIFE with `csstree` as global ```html ``` - `dist/csstree.esm.js` – minified ES module ```html ``` One of CDN services like `unpkg` or `jsDelivr` can be used. By default (for short path) a ESM version is exposing. For IIFE version a full path to a bundle should be specified: ```html ``` ## Top level API ![API map](https://cdn.rawgit.com/csstree/csstree/aaf327e/docs/api-map.svg) ## License MIT csstree-2.0.4/data/000077500000000000000000000000001415712374100141035ustar00rootroot00000000000000csstree-2.0.4/data/patch.json000066400000000000000000001156211415712374100161030ustar00rootroot00000000000000{ "atrules": { "charset": { "prelude": "" }, "font-face": { "descriptors": { "unicode-range": { "comment": "replaces , an old production name", "syntax": "#" } } } }, "properties": { "-moz-background-clip": { "comment": "deprecated syntax in old Firefox, https://developer.mozilla.org/en/docs/Web/CSS/background-clip", "syntax": "padding | border" }, "-moz-border-radius-bottomleft": { "comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-left-radius", "syntax": "<'border-bottom-left-radius'>" }, "-moz-border-radius-bottomright": { "comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius", "syntax": "<'border-bottom-right-radius'>" }, "-moz-border-radius-topleft": { "comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-left-radius", "syntax": "<'border-top-left-radius'>" }, "-moz-border-radius-topright": { "comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius", "syntax": "<'border-bottom-right-radius'>" }, "-moz-control-character-visibility": { "comment": "firefox specific keywords, https://bugzilla.mozilla.org/show_bug.cgi?id=947588", "syntax": "visible | hidden" }, "-moz-osx-font-smoothing": { "comment": "misssed old syntax https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth", "syntax": "auto | grayscale" }, "-moz-user-select": { "comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/user-select", "syntax": "none | text | all | -moz-none" }, "-ms-flex-align": { "comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align", "syntax": "start | end | center | baseline | stretch" }, "-ms-flex-item-align": { "comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-align", "syntax": "auto | start | end | center | baseline | stretch" }, "-ms-flex-line-pack": { "comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-line-pack", "syntax": "start | end | center | justify | distribute | stretch" }, "-ms-flex-negative": { "comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation", "syntax": "<'flex-shrink'>" }, "-ms-flex-pack": { "comment": "misssed old syntax implemented in IE, https://www.w3.org/TR/2012/WD-css3-flexbox-20120322/#flex-pack", "syntax": "start | end | center | justify | distribute" }, "-ms-flex-order": { "comment": "misssed old syntax implemented in IE; https://msdn.microsoft.com/en-us/library/jj127303(v=vs.85).aspx", "syntax": "" }, "-ms-flex-positive": { "comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation", "syntax": "<'flex-grow'>" }, "-ms-flex-preferred-size": { "comment": "misssed old syntax implemented in IE; TODO: find references for comfirmation", "syntax": "<'flex-basis'>" }, "-ms-interpolation-mode": { "comment": "https://msdn.microsoft.com/en-us/library/ff521095(v=vs.85).aspx", "syntax": "nearest-neighbor | bicubic" }, "-ms-grid-column-align": { "comment": "add this property first since it uses as fallback for flexbox, https://msdn.microsoft.com/en-us/library/windows/apps/hh466338.aspx", "syntax": "start | end | center | stretch" }, "-ms-grid-row-align": { "comment": "add this property first since it uses as fallback for flexbox, https://msdn.microsoft.com/en-us/library/windows/apps/hh466348.aspx", "syntax": "start | end | center | stretch" }, "-ms-hyphenate-limit-last": { "comment": "misssed old syntax implemented in IE; https://www.w3.org/TR/css-text-4/#hyphenate-line-limits", "syntax": "none | always | column | page | spread" }, "-webkit-appearance": { "comment": "webkit specific keywords", "references": [ "http://css-infos.net/property/-webkit-appearance" ], "syntax": "none | button | button-bevel | caps-lock-indicator | caret | checkbox | default-button | inner-spin-button | listbox | listitem | media-controls-background | media-controls-fullscreen-background | media-current-time-display | media-enter-fullscreen-button | media-exit-fullscreen-button | media-fullscreen-button | media-mute-button | media-overlay-play-button | media-play-button | media-seek-back-button | media-seek-forward-button | media-slider | media-sliderthumb | media-time-remaining-display | media-toggle-closed-captions-button | media-volume-slider | media-volume-slider-container | media-volume-sliderthumb | menulist | menulist-button | menulist-text | menulist-textfield | meter | progress-bar | progress-bar-value | push-button | radio | scrollbarbutton-down | scrollbarbutton-left | scrollbarbutton-right | scrollbarbutton-up | scrollbargripper-horizontal | scrollbargripper-vertical | scrollbarthumb-horizontal | scrollbarthumb-vertical | scrollbartrack-horizontal | scrollbartrack-vertical | searchfield | searchfield-cancel-button | searchfield-decoration | searchfield-results-button | searchfield-results-decoration | slider-horizontal | slider-vertical | sliderthumb-horizontal | sliderthumb-vertical | square-button | textarea | textfield | -apple-pay-button" }, "-webkit-background-clip": { "comment": "https://developer.mozilla.org/en/docs/Web/CSS/background-clip", "syntax": "[ | border | padding | content | text ]#" }, "-webkit-column-break-after": { "comment": "added, http://help.dottoro.com/lcrthhhv.php", "syntax": "always | auto | avoid" }, "-webkit-column-break-before": { "comment": "added, http://help.dottoro.com/lcxquvkf.php", "syntax": "always | auto | avoid" }, "-webkit-column-break-inside": { "comment": "added, http://help.dottoro.com/lclhnthl.php", "syntax": "always | auto | avoid" }, "-webkit-font-smoothing": { "comment": "https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth", "syntax": "auto | none | antialiased | subpixel-antialiased" }, "-webkit-mask-box-image": { "comment": "missed; https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-mask-box-image", "syntax": "[ | | none ] [ {4} <-webkit-mask-box-repeat>{2} ]?" }, "-webkit-print-color-adjust": { "comment": "missed", "references": [ "https://developer.mozilla.org/en/docs/Web/CSS/-webkit-print-color-adjust" ], "syntax": "economy | exact" }, "-webkit-text-security": { "comment": "missed; http://help.dottoro.com/lcbkewgt.php", "syntax": "none | circle | disc | square" }, "-webkit-user-drag": { "comment": "missed; http://help.dottoro.com/lcbixvwm.php", "syntax": "none | element | auto" }, "-webkit-user-select": { "comment": "auto is supported by old webkit, https://developer.mozilla.org/en-US/docs/Web/CSS/user-select", "syntax": "auto | none | text | all" }, "alignment-baseline": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/text.html#AlignmentBaselineProperty" ], "syntax": "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical" }, "baseline-shift": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/text.html#BaselineShiftProperty" ], "syntax": "baseline | sub | super | " }, "behavior": { "comment": "added old IE property https://msdn.microsoft.com/en-us/library/ms530723(v=vs.85).aspx", "syntax": "+" }, "clip-rule": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/masking.html#ClipRuleProperty" ], "syntax": "nonzero | evenodd" }, "content": { "comment": "https://www.w3.org/TR/css-content-3/#content-property", "syntax": "normal | none | [ | ] [/ [ | ]+ ]?" }, "counter-reset": { "comment": " -> ", "references": [ "https://www.w3.org/TR/css-lists-3/#counter-reset" ], "syntax": "[ ? ]+ | none" }, "counter-increment": { "comment": " -> ", "references": [ "https://www.w3.org/TR/css-lists-3/#propdef-counter-increment" ], "syntax": "[ ? ]+ | none" }, "counter-set": { "comment": " -> ", "references": [ "https://www.w3.org/TR/css-lists-3/#propdef-counter-set" ], "syntax": "[ ? ]+ | none" }, "cue": { "comment": "https://www.w3.org/TR/css3-speech/#property-index", "syntax": "<'cue-before'> <'cue-after'>?" }, "cue-after": { "comment": "https://www.w3.org/TR/css3-speech/#property-index", "syntax": " ? | none" }, "cue-before": { "comment": "https://www.w3.org/TR/css3-speech/#property-index", "syntax": " ? | none" }, "cursor": { "comment": "added legacy keywords: hand, -webkit-grab. -webkit-grabbing, -webkit-zoom-in, -webkit-zoom-out, -moz-grab, -moz-grabbing, -moz-zoom-in, -moz-zoom-out", "references": [ "https://www.sitepoint.com/css3-cursor-styles/" ], "syntax": "[ [ [ ]? , ]* [ auto | default | none | context-menu | help | pointer | progress | wait | cell | crosshair | text | vertical-text | alias | copy | move | no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll | zoom-in | zoom-out | grab | grabbing | hand | -webkit-grab | -webkit-grabbing | -webkit-zoom-in | -webkit-zoom-out | -moz-grab | -moz-grabbing | -moz-zoom-in | -moz-zoom-out ] ]" }, "display": { "comment": "extended with -ms-flexbox", "syntax": "| <-non-standard-display>" }, "position": { "comment": "extended with -webkit-sticky", "syntax": "| -webkit-sticky" }, "dominant-baseline": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/text.html#DominantBaselineProperty" ], "syntax": "auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge" }, "image-rendering": { "comment": "extended with <-non-standard-image-rendering>, added SVG keywords optimizeSpeed and optimizeQuality", "references": [ "https://developer.mozilla.org/en/docs/Web/CSS/image-rendering", "https://www.w3.org/TR/SVG/painting.html#ImageRenderingProperty" ], "syntax": "| optimizeSpeed | optimizeQuality | <-non-standard-image-rendering>" }, "fill": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/painting.html#FillProperty" ], "syntax": "" }, "fill-opacity": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/painting.html#FillProperty" ], "syntax": "" }, "fill-rule": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/painting.html#FillProperty" ], "syntax": "nonzero | evenodd" }, "filter": { "comment": "extend with IE legacy syntaxes", "syntax": "| <-ms-filter-function-list>" }, "glyph-orientation-horizontal": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/text.html#GlyphOrientationHorizontalProperty" ], "syntax": "" }, "glyph-orientation-vertical": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/text.html#GlyphOrientationVerticalProperty" ], "syntax": "" }, "kerning": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/text.html#KerningProperty" ], "syntax": "auto | " }, "letter-spacing": { "comment": "fix syntax -> ", "references": [ "https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/letter-spacing" ], "syntax": "normal | " }, "marker": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/painting.html#MarkerProperties" ], "syntax": "none | " }, "marker-end": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/painting.html#MarkerProperties" ], "syntax": "none | " }, "marker-mid": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/painting.html#MarkerProperties" ], "syntax": "none | " }, "marker-start": { "comment": "added SVG property", "references": [ "https://www.w3.org/TR/SVG/painting.html#MarkerProperties" ], "syntax": "none | " }, "max-width": { "comment": "extend by non-standard width keywords https://developer.mozilla.org/en-US/docs/Web/CSS/max-width", "syntax": "| <-non-standard-width>" }, "width": { "references": [ "https://developer.mozilla.org/en-US/docs/Web/CSS/width", "https://github.com/csstree/stylelint-validator/issues/29" ], "syntax": "| fill | stretch | intrinsic | -moz-max-content | -webkit-max-content | -moz-fit-content | -webkit-fit-content" }, "min-width": { "comment": "extend by non-standard width keywords https://developer.mozilla.org/en-US/docs/Web/CSS/width", "syntax": "| <-non-standard-width>" }, "overflow": { "comment": "extend by vendor keywords https://developer.mozilla.org/en-US/docs/Web/CSS/overflow", "syntax": "| <-non-standard-overflow>" }, "pause": { "comment": "https://www.w3.org/TR/css3-speech/#property-index", "syntax": "<'pause-before'> <'pause-after'>?" }, "pause-after": { "comment": "https://www.w3.org/TR/css3-speech/#property-index", "syntax": "