<commit_before>import stripAnsi from 'strip-ansi';
import { transform } from '@linaria/babel-preset';
import type { Replacement } from '@linaria/babel-preset';

type Errors = {
  [key: string]:
    | {
        name?: string;
        code?: string;
        message: string;
        pos?: number;
        loc?: {
          line: number;
          column: number;
        };
      }
    | null
    | undefined;
};

type Cache = {
  [key: string]: Replacement[] | null | undefined;
};

type Warning = {
  rule?: string;
  text: string;
  severity: 'error' | 'warning';
  line: number;
  column: number;
};

type LintResult = {
  errored: boolean;
  warnings: Warning[];
};

interface IPosition {
  line: number;
  column: number;
}

interface ISourceOffset {
  generated: IPosition;
  name: string;
  original: IPosition;
}

function preprocessor() {
  const errors: Errors = {};
  const cache: Cache = {};
  const offsets: Record<string, ISourceOffset[] | undefined> = {};

  return {
    code(input: string, filename: string) {
      let result;

      try {
        result = transform(input, {
          filename,
        });

        cache[filename] = undefined;
        errors[filename] = undefined;
        offsets[filename] = [];
      } catch (e: unknown) {
        cache[filename] = undefined;
        offsets[filename] = undefined;
        errors[filename] = e as Error;

        // Ignore parse errors here
        // We handle it separately
        return '';
      }

      const { rules, replacements } = result;

      if (!rules) {
        return '';
      }

      // Construct a CSS-ish file from the unprocessed style rules
      let generatedLineNumber = 1;
      let cssText = Object.values(rules)
        .map((rule) => {
          const ruleText = `.${rule.className} {${rule.cssText}}`;

          if (rule.start && 'line' in rule.start) {
            offsets[filename]?.push({
              generated: {
                line: generatedLineNumber,
                column: 1,
              },
              original: {
                ...rule.start,
              },
              name: rule.displayName,
            });

            generatedLineNumber += 1;
          }

          generatedLineNumber += ruleText.split('\n').length + 2;
          return ruleText;
        })
        .join('\n\n');

      cache[filename] = replacements;
      offsets[filename] = offsets[filename]?.reverse();

      console.log(cssText);

      return cssText + '\n';
    },
    result(result: LintResult, filename: string) {
      const error = errors[filename];
      const replacements = cache[filename];
      const sourceMap = offsets[filename];

      if (sourceMap) {
        result.warnings = result.warnings.map((warning) => {
          const offset = sourceMap.find(
            (o) => o.generated.line <= warning.line
          );
          if (offset) {
            warning.line += offset.original.line - offset.generated.line;
          }

          return warning;
        });
      }

      if (error) {
        // Babel adds this to the error message
        const prefix = `${filename}: `;
<commit_msg>fix(stylelint): remove console.log from stylelint preprocessor (#969)<commit_after>import stripAnsi from 'strip-ansi';
import { transform } from '@linaria/babel-preset';
import type { Replacement } from '@linaria/babel-preset';

type Errors = {
  [key: string]:
    | {
        name?: string;
        code?: string;
        message: string;
        pos?: number;
        loc?: {
          line: number;
          column: number;
        };
      }
    | null
    | undefined;
};

type Cache = {
  [key: string]: Replacement[] | null | undefined;
};

type Warning = {
  rule?: string;
  text: string;
  severity: 'error' | 'warning';
  line: number;
  column: number;
};

type LintResult = {
  errored: boolean;
  warnings: Warning[];
};

interface IPosition {
  line: number;
  column: number;
}

interface ISourceOffset {
  generated: IPosition;
  name: string;
  original: IPosition;
}

function preprocessor() {
  const errors: Errors = {};
  const cache: Cache = {};
  const offsets: Record<string, ISourceOffset[] | undefined> = {};

  return {
    code(input: string, filename: string) {
      let result;

      try {
        result = transform(input, {
          filename,
        });

        cache[filename] = undefined;
        errors[filename] = undefined;
        offsets[filename] = [];
      } catch (e: unknown) {
        cache[filename] = undefined;
        offsets[filename] = undefined;
        errors[filename] = e as Error;

        // Ignore parse errors here
        // We handle it separately
        return '';
      }

      const { rules, replacements } = result;

      if (!rules) {
        return '';
      }

      // Construct a CSS-ish file from the unprocessed style rules
      let generatedLineNumber = 1;
      let cssText = Object.values(rules)
        .map((rule) => {
          const ruleText = `.${rule.className} {${rule.cssText}}`;

          if (rule.start && 'line' in rule.start) {
            offsets[filename]?.push({
              generated: {
                line: generatedLineNumber,
                column: 1,
              },
              original: {
                ...rule.start,
              },
              name: rule.displayName,
            });

            generatedLineNumber += 1;
          }

          generatedLineNumber += ruleText.split('\n').length + 2;
          return ruleText;
        })
        .join('\n\n');

      cache[filename] = replacements;
      offsets[filename] = offsets[filename]?.reverse();

      return cssText + '\n';
    },
    result(result: LintResult, filename: string) {
      const error = errors[filename];
      const replacements = cache[filename];
      const sourceMap = offsets[filename];

      if (sourceMap) {
        result.warnings = result.warnings.map((warning) => {
          const offset = sourceMap.find(
            (o) => o.generated.line <= warning.line
          );
          if (offset) {
            warning.line += offset.original.line - offset.generated.line;
          }

          return warning;
        });
      }

      if (error) {
        // Babel adds this to the error message
        const prefix = `${filename}: `;

{'fraction_non_alphanumeric': 0.12892430278884462, 'fraction_numerical': 0.001752988047808765, 'mean_word_length': 1.8696844993141288, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2963115', 'n_tokens_mistral': 1812, 'n_tokens_neox': 1742, 'n_words': 447}