All files / packages/sds-metadata/src/parsers css-parser.ts

0% Statements 0/21
0% Branches 0/2
0% Functions 0/5
0% Lines 0/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                                                                                                             
import fs from "fs";
import postcss, { Rule, Root, LazyResult } from "postcss";
import {
  SelectorProcessor,
  DeclarationProcessor,
} from "../types.js";
 
/**
 * Class for parsing CSS files and processing selectors and declarations
 */
export class CSSParser {
  private inputFilePath: string;
  private result: LazyResult<Root> | undefined;
 
  constructor(filePath: string) {
    this.inputFilePath = filePath;
  }
 
  async parse() {
    const css = await fs.promises.readFile(this.inputFilePath, "utf8");
    this.result = postcss().process(css, { from: this.inputFilePath });
  }
 
  getRulesToProcess(): Rule[] {
    const rulesToProcess: Rule[] = [];
    this.result?.root.nodes.forEach(node => {
      if(node.type === 'rule'){
        rulesToProcess.push(node);
      }
      if(node.type === 'atrule' && (node.name === 'layer')){
        node.walkRules(rule => {
          rulesToProcess.push(rule)
        });
      }
    });
    return rulesToProcess;
  }
 
  processSelectors<T>(processor: SelectorProcessor<T>) {
    const rulesToProcess = this.getRulesToProcess();
    rulesToProcess.forEach((rule) => {
      processor.processSelector(rule.selector, rule);
    });
    return processor.getResults();
  }
 
  processDeclerations<T>(processor: DeclarationProcessor<T>) {
    const rulesToProcess = this.getRulesToProcess();
    rulesToProcess.forEach((rule) => {
      rule.walkDecls((decl) => {
        processor.processDeclaration(decl);
      });
    });
    return processor.getResults();
  }
 
  static async parseCSSFile(filePath: string): Promise<CSSParser> {
    const cssParser = new CSSParser(filePath);
    await cssParser.parse();
    return cssParser;
  }
}