or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-structures.mdgeneration.mdindex.mdparsing.mdtokenization.mdtraversal.mdutilities.mdvalidation.md
tile.json

tessl/npm-css-tree

A tool set for CSS: fast detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/css-tree@3.1.x

To install, run

npx @tessl/cli install tessl/npm-css-tree@3.1.0

index.mddocs/

CSS Tree

CSS Tree is a comprehensive tool set for CSS providing a fast, detailed parser that converts CSS to Abstract Syntax Trees (AST), along with complementary tools for AST traversal (walker), CSS generation from AST (generator), and syntax validation (lexer). Built with performance and W3C specification compliance in mind, it supports various levels of parsing detail, graceful error recovery, and is designed for CSS analysis and source-to-source transformation tasks.

Package Information

  • Package Name: css-tree
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install css-tree

Core Imports

import * as csstree from 'css-tree';

For CommonJS:

const csstree = require('css-tree');

Modular imports for tree-shaking and performance:

import * as tokenizer from 'css-tree/tokenizer';
import * as parser from 'css-tree/parser';
import * as walker from 'css-tree/walker';
import * as generator from 'css-tree/generator';
import * as lexer from 'css-tree/lexer';
import * as utils from 'css-tree/utils';

Basic Usage

import * as csstree from 'css-tree';

// Parse CSS to AST
const ast = csstree.parse('.example { color: red; }');

// 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));
// Output: .hello{color:red}

// Syntax validation
const valueAst = csstree.parse('red 1px solid', { context: 'value' });
const matchResult = csstree.lexer.matchProperty('border', valueAst);
console.log(matchResult.isType(valueAst.children.first, 'color')); // true

Architecture

CSS Tree is built around several key components:

  • Tokenizer: Low-level CSS tokenization following W3C specifications
  • Parser: Converts CSS source into detailed AST structures with configurable parsing levels
  • Walker: Provides traversal utilities for AST exploration and manipulation
  • Generator: Converts AST back to CSS with configurable formatting options
  • Lexer: Validates CSS syntax against W3C specifications and provides semantic matching
  • List: Custom doubly-linked list implementation optimized for AST operations
  • Utilities: Helper functions for CSS identifier/string/URL encoding/decoding

Capabilities

CSS Parsing

Core CSS parsing functionality that converts CSS source code into detailed Abstract Syntax Trees with configurable parsing levels and error recovery.

function parse(css: string, options?: ParseOptions): CssNode;

interface ParseOptions {
  context?: 'stylesheet' | 'atrule' | 'atrulePrelude' | 'mediaQueryList' | 'mediaQuery' | 'rule' | 'selectorList' | 'selector' | 'block' | 'declarationList' | 'declaration' | 'value';
  atrule?: string;
  property?: string;
  positions?: boolean;
  filename?: string;
  offset?: number;
  line?: number;
  column?: number;
  parseAtrulePrelude?: boolean;
  parseRulePrelude?: boolean;
  parseValue?: boolean;
  parseCustomProperty?: boolean;
}

CSS Parsing

CSS Generation

Converts Abstract Syntax Trees back into CSS source code with configurable formatting and source map generation.

function generate(ast: CssNode, options?: GenerateOptions): string;

interface GenerateOptions {
  sourceMap?: boolean;
  file?: string;
  decorateNode?: (handlers: object) => void;
}

CSS Generation

CSS Tokenization

Low-level CSS tokenization following W3C CSS Syntax specification for breaking CSS source into tokens.

function tokenize(source: string, onToken: (type: number, start: number, end: number) => void): void;

const tokenTypes: {
  EOF: 0;
  Ident: 1;
  Function: 2;
  AtKeyword: 3;
  Hash: 4;
  String: 5;
  Number: 10;
  Dimension: 12;
  // ... additional token types
};

CSS Tokenization

AST Traversal

Comprehensive AST traversal utilities for walking, searching, and manipulating CSS Abstract Syntax Trees.

function walk(ast: CssNode, visitor: WalkVisitor): void;
function find(ast: CssNode, predicate: (node: CssNode) => boolean): CssNode | null;
function findLast(ast: CssNode, predicate: (node: CssNode) => boolean): CssNode | null;
function findAll(ast: CssNode, predicate: (node: CssNode) => boolean): CssNode[];

type WalkVisitor = (node: CssNode, item: ListItem<CssNode>, list: List<CssNode>) => void;

AST Traversal

CSS Syntax Validation

Advanced CSS syntax validation and matching against W3C specifications with support for properties, at-rules, and value types.

const lexer: Lexer;

class Lexer {
  checkStructure(ast: CssNode): void;
  matchProperty(propertyName: string, value: CssNode): MatchResult;
  matchType(typeName: string, value: CssNode): MatchResult;
  match(syntax: string, value: CssNode): MatchResult;
}

interface MatchResult {
  matched: CssNode | null;
  error: Error | null;
  isType(node: CssNode, type: string): boolean;
  getTrace(node: CssNode): TraceNode[];
}

CSS Syntax Validation

Utility Functions

Collection of utility functions for CSS identifier, string, and URL encoding/decoding, plus AST manipulation helpers.

// Identifier utilities
namespace ident {
  function encode(str: string): string;
  function decode(str: string): string;
}

// String utilities  
namespace string {
  function encode(str: string, apostrophe?: boolean): string;
  function decode(str: string): string;
}

// URL utilities
namespace url {
  function encode(str: string): string;
  function decode(str: string): string;
}

// AST utilities
function clone(node: CssNode): CssNode;
function toPlainObject(ast: CssNode): object;
function fromPlainObject(ast: object): CssNode;

Utility Functions

Data Structures

Specialized data structures including the List class for efficient AST node manipulation and various stream classes for tokenization.

class List<T> {
  constructor();
  
  readonly size: number;
  readonly isEmpty: boolean;
  readonly first: T;
  readonly last: T;
  
  forEach(fn: (item: T, index: number) => void): void;
  map<U>(fn: (item: T, index: number) => U): List<U>;
  filter(fn: (item: T, index: number) => boolean): List<T>;
  toArray(): T[];
  fromArray(array: T[]): this;
}

Data Structures

Types

interface CssNode {
  type: string;
  loc?: SourceLocation;
  children?: List<CssNode>;
}

interface SourceLocation {
  source?: string;
  start: Position;
  end: Position;
}

interface Position {
  offset: number;
  line: number;
  column: number;
}

interface ListItem<T> {
  prev: ListItem<T> | null;
  next: ListItem<T> | null;
  data: T;
}