CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-postcss-selector-parser

Selector parser with built in methods for working with selector strings.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

index.mddocs/

PostCSS Selector Parser

PostCSS Selector Parser is a robust CSS selector parser that enables developers to parse, manipulate, and transform CSS selectors programmatically. It provides a comprehensive API for walking through selector ASTs, modifying selector components, and rebuilding selector strings with precise control over formatting and whitespace.

Package Information

  • Package Name: postcss-selector-parser
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install postcss-selector-parser

Core Imports

const parser = require('postcss-selector-parser');

For ESM:

import parser from 'postcss-selector-parser';

With destructuring:

const { attribute, className, combinator, comment, id, nesting, pseudo, root, selector, string, tag, universal } = require('postcss-selector-parser');

Basic Usage

const parser = require('postcss-selector-parser');

// Simple transformation
const transform = selectors => {
    selectors.walk(selector => {
        console.log(String(selector));
    });
};

const transformed = parser(transform).processSync('h1, h2, h3');

// Normalize selector whitespace
const normalized = parser().processSync('h1, h2, h3', {lossless: false});
// Result: "h1,h2,h3"

// Async processing
const result = await parser().process('.class1, .class2');

Architecture

PostCSS Selector Parser is built around several key components:

  • Parser Function: Main entry point that creates processor instances with optional transform functions
  • Processor: Handles parsing, transformation, and output generation with both sync and async methods
  • AST Nodes: Comprehensive node types for all CSS selector components (tags, classes, IDs, attributes, etc.)
  • Node Constructors: Factory functions for creating new AST nodes programmatically
  • Type Guards: Runtime type checking functions for identifying node types
  • Container Interface: Common methods for nodes that can contain children (Root, Selector, Pseudo)

Capabilities

Core Parser & Processor

Main parser function and processor class for parsing and transforming CSS selectors. Supports both synchronous and asynchronous processing with configurable options.

function parser(transform?: ProcessorFn, options?: Options): Processor;

interface Processor {
  res: Root;
  result: string;
  ast(selectors: Selectors, options?: Options): Promise<Root>;
  astSync(selectors: Selectors, options?: Options): Root;
  transform(selectors: Selectors, options?: Options): Promise<any>;
  transformSync(selectors: Selectors, options?: Options): any;
  process(selectors: Selectors, options?: Options): Promise<string>;
  processSync(selectors: Selectors, options?: Options): string;
}

Parser & Processor

AST Node Creation

Factory functions for creating all types of CSS selector AST nodes. Essential for programmatically building selector structures.

function attribute(props?: AttributeOptions): Attribute;
function className(props?: NamespaceOptions): ClassName;
function combinator(props?: NodeOptions): Combinator;
function comment(props?: NodeOptions): Comment;
function id(props?: NamespaceOptions): Identifier;
function nesting(props?: NodeOptions): Nesting;
function pseudo(props?: ContainerOptions): Pseudo;
function root(props?: ContainerOptions): Root;
function selector(props?: ContainerOptions): Selector;
function string(props?: NodeOptions): String;
function tag(props?: NamespaceOptions): Tag;
function universal(props?: NamespaceOptions): Universal;

Node Constructors

AST Node Manipulation

Base methods available on all AST nodes for manipulation, navigation, and tree modification. Includes specialized container methods for nodes that can have children.

interface Base {
  type: string;
  parent: Container;
  value: string;
  remove(): Node;
  replaceWith(...nodes: Node[]): Node;
  next(): Node;
  prev(): Node;
  clone(opts?: object): this;
  toString(): string;
}

interface Container extends Base {
  nodes: Node[];
  append(node: Node): this;
  prepend(node: Node): this;
  each(callback: (node: Node, index: number) => boolean | void): boolean | undefined;
  walk(callback: (node: Node, index: number) => boolean | void): boolean | undefined;
}

Node Manipulation

Type Guards & Validation

Runtime type checking functions for identifying and validating AST node types. Essential for safely working with the parsed AST.

function isNode(node: any): boolean;
function isContainer(node: any): boolean;
function isNamespace(node: any): boolean;
function isRoot(node: any): boolean;
function isSelector(node: any): boolean;
function isAttribute(node: any): boolean;
function isClassName(node: any): boolean;
function isCombinator(node: any): boolean;
function isComment(node: any): boolean;
function isIdentifier(node: any): boolean;
function isNesting(node: any): boolean;
function isPseudo(node: any): boolean;
function isPseudoElement(node: any): boolean;
function isPseudoClass(node: any): boolean;
function isString(node: any): boolean;
function isTag(node: any): boolean;
function isUniversal(node: any): boolean;

Type Guards

Node Type Constants

String constants for identifying AST node types. Available as properties on the main parser function.

const TAG = "tag";
const STRING = "string";
const SELECTOR = "selector";
const ROOT = "root";
const PSEUDO = "pseudo";
const NESTING = "nesting";
const ID = "id";
const COMMENT = "comment";
const COMBINATOR = "combinator";
const CLASS = "class";
const ATTRIBUTE = "attribute";
const UNIVERSAL = "universal";

Types

type Selectors = string | PostCSSRuleNode;
type ProcessorFn = (root: Root) => any;
type SyncProcessor = ProcessorFn;
type AsyncProcessor = (root: Root) => Promise<any>;

interface ErrorOptions {
  plugin?: string;
  word?: string;
  index?: number;
}

interface PostCSSRuleNode {
  selector: string;
  error(message: string, options?: ErrorOptions): Error;
}

interface Options {
  lossless?: boolean;
  updateSelector?: boolean;
}

interface NodeOptions {
  value?: string;
  spaces?: Spaces;
  source?: NodeSource;
  sourceIndex?: number;
}

interface ContainerOptions extends NodeOptions {
  nodes?: Node[];
}

interface NamespaceOptions extends NodeOptions {
  namespace?: string | true;
}

interface AttributeOptions extends NamespaceOptions {
  attribute: string;
  operator?: AttributeOperator;
  insensitive?: boolean;
  quoteMark?: QuoteMark;
  quoted?: boolean; // deprecated, use quoteMark
  raws?: AttributeRaws;
}

interface AttributeRaws {
  attribute?: string;
  operator?: string;
  value?: string;
  insensitive?: string;
  unquoted?: string;
  spaces?: {
    before?: string;
    after?: string;
    attribute?: { before?: string; after?: string };
    operator?: { before?: string; after?: string };
    value?: { before?: string; after?: string };
  };
}

type AttributeOperator = "=" | "~=" | "|=" | "^=" | "$=" | "*=";
type QuoteMark = '"' | "'" | null;

interface Spaces {
  before: string;
  after: string;
}

interface NodeSource {
  start?: { line: number; column: number };
  end?: { line: number; column: number };
}

Install with Tessl CLI

npx tessl i tessl/npm-postcss-selector-parser

docs

index.md

node-constructors.md

node-manipulation.md

parser-processor.md

type-guards.md

tile.json