UNPKG

purgecss

Version:

Remove unused css selectors

1,810 lines • 66.2 kB
import * as fs from 'fs';
import * as glob from 'fast-glob';
import * as path from 'path';
import * as postcss from 'postcss';
import selectorParser from 'postcss-selector-parser';
import { pathToFileURL } from 'url';
import { promisify } from 'util';

const IGNORE_ANNOTATION_CURRENT = "purgecss ignore current";
const IGNORE_ANNOTATION_NEXT = "purgecss ignore";
const IGNORE_ANNOTATION_START = "purgecss start ignore";
const IGNORE_ANNOTATION_END = "purgecss end ignore";
const CONFIG_FILENAME = "purgecss.config.js";
// Error Message
const ERROR_CONFIG_FILE_LOADING = "Error loading the config file";

function mergeSets(into, from) {
    if (from) {
        from.forEach(into.add, into);
    }
}
/**
 * @public
 */
class ExtractorResultSets {
    constructor(er) {
        this.undetermined = new Set();
        this.attrNames = new Set();
        this.attrValues = new Set();
        this.classes = new Set();
        this.ids = new Set();
        this.tags = new Set();
        this.merge(er);
    }
    merge(that) {
        if (Array.isArray(that)) {
            mergeSets(this.undetermined, that);
        }
        else if (that instanceof ExtractorResultSets) {
            mergeSets(this.undetermined, that.undetermined);
            mergeSets(this.attrNames, that.attrNames);
            mergeSets(this.attrValues, that.attrValues);
            mergeSets(this.classes, that.classes);
            mergeSets(this.ids, that.ids);
            mergeSets(this.tags, that.tags);
        }
        else {
            // ExtractorResultDetailed:
            mergeSets(this.undetermined, that.undetermined);
            if (that.attributes) {
                mergeSets(this.attrNames, that.attributes.names);
                mergeSets(this.attrValues, that.attributes.values);
            }
            mergeSets(this.classes, that.classes);
            mergeSets(this.ids, that.ids);
            mergeSets(this.tags, that.tags);
        }
        return this;
    }
    hasAttrName(name) {
        return this.attrNames.has(name) || this.undetermined.has(name);
    }
    someAttrValue(predicate) {
        for (const val of this.attrValues) {
            if (predicate(val))
                return true;
        }
        for (const val of this.undetermined) {
            if (predicate(val))
                return true;
        }
        return false;
    }
    hasAttrPrefix(prefix) {
        return this.someAttrValue((value) => value.startsWith(prefix));
    }
    hasAttrSuffix(suffix) {
        return this.someAttrValue((value) => value.endsWith(suffix));
    }
    hasAttrSubstr(substr) {
        const wordSubstr = substr.trim().split(" ");
        return wordSubstr.every((word) => this.someAttrValue((value) => value.includes(word)));
    }
    hasAttrValue(value) {
        return this.attrValues.has(value) || this.undetermined.has(value);
    }
    hasClass(name) {
        return this.classes.has(name) || this.undetermined.has(name);
    }
    hasId(id) {
        return this.ids.has(id) || this.undetermined.has(id);
    }
    hasTag(tag) {
        return this.tags.has(tag) || this.undetermined.has(tag);
    }
    /**
     * Replace the selectors with the equal strings of a pool, adding the
     * missing ones to it, so that the selectors kept in memory for many files,
     * e.g. by a content cache, share one string per distinct selector. The
     * strings added are copies: the selectors extracted from a file can be
     * slices of its whole content, which they would keep in memory.
     *
     * @param pool - strings shared by the selectors, by value
     *
     * @internal
     */
    internSelectors(pool) {
        const intern = (selectors) => {
            const interned = new Set();
            for (const selector of selectors) {
                let shared = pool.get(selector);
                if (shared === undefined) {
                    // a new string, not a slice of the content of the file
                    shared = (" " + selector).slice(1);
                    pool.set(shared, shared);
                }
                interned.add(shared);
            }
            return interned;
        };
        this.undetermined = intern(this.undetermined);
        this.attrNames = intern(this.attrNames);
        this.attrValues = intern(this.attrValues);
        this.classes = intern(this.classes);
        this.ids = intern(this.ids);
        this.tags = intern(this.tags);
    }
}

const CSS_SAFELIST = ["*", ":root", ":after", ":before"];
const DYNAMIC_ATTRIBUTES = ["value", "checked", "selected", "open"];

/**
 * @public
 */
const defaultOptions = {
    css: [],
    content: [],
    defaultExtractor: (content) => content.match(/[A-Za-z0-9_-]+/g) || [],
    extractors: [],
    fontFace: false,
    keyframes: false,
    rejected: false,
    rejectedCss: false,
    sourceMap: false,
    stdin: false,
    stdout: false,
    variables: false,
    safelist: {
        standard: [],
        deep: [],
        greedy: [],
        variables: [],
        keyframes: [],
    },
    blocklist: [],
    skippedContentGlobs: [],
    dynamicAttributes: [],
};

// a regular expression written as a string, e.g. "/^btn-/" or "/^btn-/i", for
// configuration files that cannot contain regular expressions, such as JSON
const REGEXP_STRING = /^\/(.+)\/([dgimsuvy]*)$/;
const regExpStrings = new Map();
/**
 * Get the regular expression written in a string between slashes, e.g.
 * "/^btn-/", or undefined if the string is not written like this
 *
 * @param pattern - string of the options
 */
function toRegExp(pattern) {
    if (!regExpStrings.has(pattern)) {
        const match = REGEXP_STRING.exec(pattern);
        regExpStrings.set(pattern, match ? new RegExp(match[1], match[2]) : undefined);
    }
    return regExpStrings.get(pattern);
}
/**
 * Check if a value matches a pattern of the options: a regular expression,
 * or a string written between slashes like "/^btn-/", is tested against the
 * value, any other string matches the value exactly
 *
 * @param pattern - string or regular expression
 * @param value - value to match, e.g. a selector or a variable name
 *
 * @public
 */
function matchesPattern(pattern, value) {
    const regExp = typeof pattern === "string" ? toRegExp(pattern) : pattern;
    if (!regExp) {
        return pattern === value;
    }
    // a regex with the g or y flag keeps its lastIndex between calls
    regExp.lastIndex = 0;
    return regExp.test(value);
}

/**
 * @public
 */
class VariableNode {
    constructor(declaration) {
        /**
         * @deprecated The dependencies between declarations are no longer
         * recorded, so this list is always empty. The variables used by a used
         * variable are found by name in `VariablesStructure.removeUnused`. It will
         * be removed in the next major version.
         */
        this.nodes = [];
        this.isUsed = false;
        this.value = declaration;
    }
}
/**
 * @public
 */
class VariablesStructure {
    constructor() {
        this.nodes = new Map();
        this.properties = new Map();
        this.usedVariables = new Set();
        this.safelist = [];
    }
    addVariable(declaration) {
        const { prop } = declaration;
        const node = new VariableNode(declaration);
        // push in place, copying the list on each redefinition would be quadratic
        const variableNodes = this.nodes.get(prop);
        if (variableNodes) {
            variableNodes.push(node);
        }
        else {
            this.nodes.set(prop, [node]);
        }
    }
    /**
     * Register an `@property` at-rule so it can be removed along with the
     * declarations of the variable it defines
     *
     * @param atRule - `@property` at-rule
     */
    addProperty(atRule) {
        const name = atRule.params.trim();
        const properties = this.properties.get(name) || [];
        this.properties.set(name, [...properties, atRule]);
    }
    /**
     * @deprecated The variables used by a custom property are found by name in
     * `removeUnused`, so the dependencies between declarations are no longer
     * recorded and this method does nothing. It will be removed in the next
     * major version.
     */
    addVariableUsage(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    declaration, 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    matchedVariables) {
        // nothing to record
    }
    addVariableUsageInProperties(matchedVariables) {
        for (const variableMatch of matchedVariables) {
            // capturing group containing the variable is in index 1
            const variableName = variableMatch[1];
            this.usedVariables.add(variableName);
        }
    }
    /**
     * Mark every declaration of the variable as used. The variables it uses are
     * not marked, `removeUnused` adds them to the used variables first.
     *
     * @param variableName - name of the variable, e.g. `--color`
     */
    setAsUsed(variableName) {
        var _a;
        for (const node of (_a = this.nodes.get(variableName)) !== null && _a !== void 0 ? _a : []) {
            node.isUsed = true;
        }
    }
    removeUnused() {
        // add the variables used by the used variables, by reading every
        // declaration of each used variable. The set also iterates over the
        // variables added during the loop, so variables used through other
        // variables are found too, whatever the order of the declarations
        for (const used of this.usedVariables) {
            const usedNodes = this.nodes.get(used);
            if (usedNodes) {
                for (const usedNode of usedNodes) {
                    const usedVariablesMatchesInDeclaration = usedNode.value.value.matchAll(/\bvar\(\s*(.+?)\s*[,)]/g);
                    for (const usage of usedVariablesMatchesInDeclaration) {
                        if (!this.usedVariables.has(usage[1])) {
                            this.usedVariables.add(usage[1]);
                        }
                    }
                }
            }
        }
        for (const used of this.usedVariables) {
            this.setAsUsed(used);
        }
        for (const [name, declarations] of this.nodes) {
            for (const declaration of declarations) {
                if (!declaration.isUsed && !this.isVariablesSafelisted(name)) {
                    declaration.value.remove();
                }
            }
        }
        for (const [name, properties] of this.properties) {
            if (!this.usedVariables.has(name) && !this.isVariablesSafelisted(name)) {
                for (const property of properties) {
                    property.remove();
                }
            }
        }
    }
    isVariablesSafelisted(variable) {
        return this.safelist.some((safelistItem) => matchesPattern(safelistItem, variable));
    }
}

/**
 * Time, in milliseconds, a content file must have gone unmodified and
 * unchanged before the selectors extracted from it are kept in the cache once
 * the extraction is done. File systems store modification and change times
 * with a limited precision (2 seconds for the modification time on FAT, a few
 * milliseconds for the change time on Linux before 6.13): a file modified or
 * changed less than that before being read could be modified again with the
 * same times.
 */
const RECENTLY_MODIFIED_MS = 2000;
/**
 * Cache of the selectors extracted from content files, shared across
 * PurgeCSS instances.
 *
 * Integrations that run PurgeCSS many times with the same content, e.g. a
 * PostCSS plugin called once per CSS file or a bundler plugin in watch mode,
 * can set the same cache on every PurgeCSS instance they create with
 * {@link PurgeCSS.contentCache}. A content file is then only read and
 * extracted again when its modification time, change time, size, inode or
 * the extractor used for it changed. Runs at the same time share the files
 * being read and extracted: each file is extracted once.
 *
 * A file modified or changed (e.g. its modification time set back) less than
 * 2 seconds before it was read is extracted again on the next run, as a
 * modification within the precision of the file system timestamps would keep
 * the same modification and change times.
 *
 * The paths given to the methods are resolved from the current working
 * directory.
 *
 * Globs are still resolved on every run, so new files are picked up and
 * deleted files no longer contribute selectors. The entries of the files that
 * are no longer used stay in the cache until {@link ContentCache.prune},
 * {@link ContentCache.delete} or {@link ContentCache.clear} is called.
 *
 * The extractors are called concurrently and in no particular order: they
 * must not depend on the order of the files or on a state kept between files.
 *
 * @example
 * ```ts
 * const contentCache = new ContentCache()
 * for (const css of cssFiles) {
 *   const purgeCSS = new PurgeCSS()
 *   purgeCSS.contentCache = contentCache
 *   await purgeCSS.purge({ content: ['src/pages/*.html'], css: [css] })
 * }
 * ```
 *
 * @public
 */
class ContentCache {
    constructor() {
        this.entries = new Map();
        /**
         * Strings of the selectors of the entries, one per distinct selector: the
         * files of a project share most of their selectors, which would otherwise
         * be kept once per file, each one keeping the whole content of its file
         * in memory. It holds the selectors of the files removed from the cache
         * too, until {@link ContentCache.clear}.
         */
        this.selectorsPool = new Map();
    }
    /**
     * Number of files in the cache
     */
    get size() {
        return this.entries.size;
    }
    /**
     * Get the selectors of a file if they are still valid. The selectors may
     * still be being extracted by another run.
     *
     * @param filePath - path of the content file
     * @param stats - current stats of the file
     * @param extractor - extractor function used for the file
     * @returns the selectors extracted from the file, or `undefined` when the
     * file is not in the cache or changed since it was extracted
     */
    get(filePath, stats, extractor) {
        const entry = this.entries.get(path.resolve(filePath));
        if (entry &&
            entry.mtimeMs === stats.mtimeMs &&
            entry.ctimeMs === stats.ctimeMs &&
            entry.size === stats.size &&
            entry.ino === stats.ino &&
            entry.extractor === extractor) {
            return entry.selectors;
        }
        return undefined;
    }
    /**
     * Store the selectors of a file. The entry is removed when its selectors
     * reject, or once they resolve when the file was modified or changed less
     * than 2 seconds before {@link ContentCacheEntry.checkedAt}.
     *
     * @param filePath - path of the content file
     * @param entry - selectors of the file and what they were extracted from
     */
    set(filePath, entry) {
        filePath = path.resolve(filePath);
        this.entries.set(filePath, entry);
        const forget = () => {
            if (this.entries.get(filePath) === entry)
                this.entries.delete(filePath);
        };
        entry.selectors.then((selectors) => {
            const changedAt = Math.max(entry.mtimeMs, entry.ctimeMs);
            if (entry.checkedAt - changedAt < RECENTLY_MODIFIED_MS) {
                forget();
            }
            else if (this.entries.get(filePath) === entry &&
                typeof (selectors === null || selectors === void 0 ? void 0 : selectors.internSelectors) === "function") {
                // the selectors are equal strings: the runs that read them get the
                // same selectors
                selectors.internSelectors(this.selectorsPool);
            }
        }, forget);
    }
    /**
     * Check if a file is in the cache, whether its entry is still valid or not
     *
     * @param filePath - path of the content file
     */
    has(filePath) {
        return this.entries.has(path.resolve(filePath));
    }
    /**
     * Absolute paths of the files in the cache
     */
    keys() {
        return this.entries.keys();
    }
    /**
     * Remove a file from the cache
     *
     * @param filePath - path of the content file
     * @returns true if the file was in the cache
     */
    delete(filePath) {
        return this.entries.delete(path.resolve(filePath));
    }
    /**
     * Remove the files that are not in the given list, e.g. the files of a
     * previous build that the content globs no longer match
     *
     * @param filePaths - paths of the files to keep
     * @returns the number of files removed
     */
    prune(filePaths) {
        const kept = new Set();
        for (const filePath of filePaths)
            kept.add(path.resolve(filePath));
        let removed = 0;
        for (const filePath of this.entries.keys()) {
            if (!kept.has(filePath)) {
                this.entries.delete(filePath);
                removed++;
            }
        }
        return removed;
    }
    /**
     * Remove all the files from the cache
     */
    clear() {
        this.entries.clear();
        this.selectorsPool.clear();
    }
}

/**
 * Core package of PurgeCSS
 *
 * Contains the core methods to analyze the files, remove unused CSS.
 *
 * @packageDocumentation
 */
const asyncFs = {
    access: promisify(fs.access),
    readFile: promisify(fs.readFile),
    stat: promisify(fs.stat),
};
/**
 * Maximum number of content files read at the same time, by all the PurgeCSS
 * runs of the process together
 */
const CONTENT_FILES_CONCURRENCY = 32;
/**
 * Create a limiter that runs at most `concurrency` tasks at the same time.
 * The tasks start in the order they were given to the limiter.
 *
 * @param concurrency - maximum number of pending tasks
 */
function createLimiter(concurrency) {
    let pending = 0;
    const queue = [];
    return async (task) => {
        if (pending < concurrency) {
            pending++;
        }
        else {
            // the slot is handed over by the task that ends
            await new Promise((resolve) => queue.push(resolve));
        }
        try {
            return await task();
        }
        finally {
            const next = queue.shift();
            if (next)
                next();
            else
                pending--;
        }
    };
}
/**
 * Limiter shared by all the PurgeCSS instances, so that concurrent runs do
 * not open more files at the same time than a single run
 */
const limitContentFile = createLimiter(CONTENT_FILES_CONCURRENCY);
/**
 * Call an async function for each item, through the content files limiter.
 * The calls start in the order of the items but can end in any order.
 *
 * Once a call fails, no other call starts. The returned promise rejects, once
 * the pending calls are over, with the error of the first item that failed in
 * the order of the items: as the calls start in order, it is the error that
 * calling the function on the items one after the other would give.
 *
 * @param items - items to call the function on
 * @param callback - async function called for each item
 */
async function forEachContentFile(items, callback) {
    // index and error of the first item that failed, in the order of the items
    let failedIndex = items.length;
    let failedError;
    await Promise.all(items.map((item, index) => limitContentFile(async () => {
        // do not start once an item failed
        if (failedIndex < items.length)
            return;
        try {
            await callback(item);
        }
        catch (error) {
            if (index < failedIndex) {
                failedIndex = index;
                failedError = error;
            }
        }
    })));
    if (failedIndex < items.length)
        throw failedError;
}
/**
 * Format the user defined safelist into a standardized safelist object
 *
 * @param userDefinedSafelist - the user defined safelist
 * @returns the formatted safelist object that can be used in the PurgeCSS options
 *
 * @public
 */
function standardizeSafelist(userDefinedSafelist = []) {
    if (Array.isArray(userDefinedSafelist)) {
        return {
            ...defaultOptions.safelist,
            standard: userDefinedSafelist,
        };
    }
    return {
        ...defaultOptions.safelist,
        ...userDefinedSafelist,
    };
}
/**
 * Load the configuration file from the path
 *
 * @param configFile - Path of the config file
 * @returns The options from the configuration file
 *
 * @throws Error
 * This exception is thrown if the configuration file was not imported
 *
 * @public
 */
async function setOptions(configFile = CONFIG_FILENAME) {
    let options;
    try {
        const t = path.resolve(process.cwd(), configFile);
        const importedConfig = await import(pathToFileURL(t).href);
        // Handle both ES modules (direct export) and CommonJS (default export)
        options =
            importedConfig.default && typeof importedConfig.default === "object"
                ? importedConfig.default
                : importedConfig;
    }
    catch (err) {
        // a config file can throw any value, e.g. `throw "error"`
        const message = err instanceof Error ? err.message : String(err);
        throw new Error(`${ERROR_CONFIG_FILE_LOADING} ${message}`, {
            cause: err,
        });
    }
    return {
        ...defaultOptions,
        ...options,
        safelist: standardizeSafelist(options.safelist),
    };
}
/**
 * Use the extract function to get the list of selectors
 *
 * @param content - content (e.g. html file)
 * @param extractor - PurgeCSS extractor used to extract the selectors
 * @returns the sets containing the result of the extractor function
 */
async function extractSelectors(content, extractor) {
    return new ExtractorResultSets(await extractor(content));
}
/**
 * Check if the node is a css comment indication to ignore the selector rule
 *
 * @param node - node of postcss AST
 * @param type - type of css comment
 * @returns true if the node is a PurgeCSS ignore comment
 */
function isIgnoreAnnotation(node, type) {
    switch (type) {
        case "next":
            return node.text.includes(IGNORE_ANNOTATION_NEXT);
        case "start":
            return node.text.includes(IGNORE_ANNOTATION_START);
        case "end":
            return node.text.includes(IGNORE_ANNOTATION_END);
    }
}
/**
 * Check if the node is a comment that can be removed along with its parent
 * when the parent has nothing else left. PurgeCSS ignore annotations are
 * kept since they still need to be processed.
 *
 * @param node - node of postcss AST
 * @returns true if the node is a removable comment
 */
function isRemovableComment(node) {
    return (isPostCSSComment(node) &&
        !isIgnoreAnnotation(node, "next") &&
        !isIgnoreAnnotation(node, "start") &&
        !isIgnoreAnnotation(node, "end"));
}
/**
 * The node itself when it is a proxy, as the nodes passed to postcss plugin
 * visitors are
 *
 * @param node - node of postcss AST
 */
function getRawNode(node) {
    var _a;
    return (_a = node.proxyOf) !== null && _a !== void 0 ? _a : node;
}
/**
 * Children of a node, from the node itself when it is a proxy
 *
 * @param node - node of postcss AST
 */
function getRawChildren(node) {
    return getRawNode(node).nodes;
}
/**
 * Removals of nodes made while walking through the css, applied all at once
 * once the walk is over.
 *
 * Removing a node from a postcss container is a splice of its children
 * array, which is linear in the number of children: removing the unused
 * rules one by one from a big stylesheet is quadratic. The removals are
 * recorded instead, and this class answers the questions the walk asks about
 * the tree (parent, previous sibling, empty container) as if the recorded
 * nodes were already removed. `apply` then removes them in one pass per
 * container, which gives the same tree as removing them one by one.
 */
class DeferredRemovals {
    constructor() {
        this.removed = new Set();
        /**
         * For each container that was checked for emptiness, the number of its
         * children not removed, and the number of those that are not removable
         * comments. Computed on the first check, then kept up to date.
         */
        this.counts = new Map();
        /**
         * For a removed node, the index of a sibling before it from which to
         * continue looking for the previous sibling not removed. All the siblings
         * in between are removed.
         */
        this.skips = new Map();
        /**
         * For each root that had children removed, the index of its first child
         * that may not be removed. All the children before it are removed.
         */
        this.firstChildren = new Map();
    }
    /**
     * Record the removal of a node. Like `node.remove()`, it does nothing if the
     * node has no parent or is already removed.
     *
     * @param node - node to remove
     */
    remove(node) {
        const raw = getRawNode(node);
        const parent = raw.parent;
        if (!parent || this.removed.has(raw))
            return;
        if (parent.type === "root")
            this.moveRootSpacing(parent, raw);
        this.removed.add(raw);
        const counts = this.counts.get(getRawNode(parent));
        if (counts) {
            counts.live--;
            if (!isRemovableComment(raw))
                counts.kept--;
        }
    }
    /**
     * When the first child of a root is removed, `Root.removeChild` gives the
     * spacing before it to the next child: do the same at the time of the
     * removal, as the next child can be copied as is in the rejected css
     *
     * @param root - parent of the node
     * @param node - node about to be removed
     */
    moveRootSpacing(root, node) {
        var _a;
        const children = getRawChildren(root);
        if (!children)
            return;
        const rawRoot = getRawNode(root);
        let first = (_a = this.firstChildren.get(rawRoot)) !== null && _a !== void 0 ? _a : 0;
        while (first < children.length && this.removed.has(children[first])) {
            first++;
        }
        this.firstChildren.set(rawRoot, first);
        if (children[first] !== node)
            return;
        let next = first + 1;
        while (next < children.length && this.removed.has(children[next])) {
            next++;
        }
        if (next < children.length) {
            children[next].raws.before = node.raws.before;
        }
    }
    /**
     * Remove a node from the tree right away. Only used for nodes in containers
     * that have not been walked through yet, as it shifts the children indexes.
     *
     * @param node - node to remove
     */
    removeNow(node) {
        const parent = node.parent;
        if (parent)
            this.counts.delete(getRawNode(parent));
        node.remove();
    }
    /**
     * Parent of the node, `undefined` if the node is removed
     *
     * @param node - node of postcss AST
     */
    parentOf(node) {
        const raw = getRawNode(node);
        return this.removed.has(raw) ? undefined : raw.parent;
    }
    /**
     * Previous sibling of the node not removed, like `node.prev()`
     *
     * @param node - node of postcss AST, not removed
     * @param index - index of the node in the children of its parent
     */
    previousSibling(node, index) {
        var _a;
        const raw = getRawNode(node);
        const parent = raw.parent;
        if (!parent)
            return undefined;
        const nodes = getRawChildren(parent);
        if (!nodes)
            return undefined;
        if (nodes[index] !== raw)
            index = nodes.indexOf(raw);
        let i = index - 1;
        const skipped = [];
        while (i >= 0 && this.removed.has(nodes[i])) {
            skipped.push(nodes[i]);
            i = (_a = this.skips.get(nodes[i])) !== null && _a !== void 0 ? _a : i - 1;
        }
        // nodes are never added back: jump straight there next time
        for (const skippedNode of skipped)
            this.skips.set(skippedNode, i);
        return i >= 0 ? nodes[i] : undefined;
    }
    countsOf(container, children) {
        const raw = getRawNode(container);
        let counts = this.counts.get(raw);
        if (!counts) {
            counts = { live: 0, kept: 0 };
            for (const child of children) {
                if (this.removed.has(child))
                    continue;
                counts.live++;
                if (!isRemovableComment(child))
                    counts.kept++;
            }
            this.counts.set(raw, counts);
        }
        return counts;
    }
    /**
     * Check if the container corresponds to an empty css rule, once the
     * recorded nodes are removed
     *
     * @param node - container of postcss AST
     * @returns true if the rule is empty
     */
    isEmpty(node) {
        if (isPostCSSRule(node) && !node.selector)
            return true;
        const children = getRawChildren(node);
        if (!children) {
            return isPostCSSAtRule(node) && !node.params;
        }
        const { live, kept } = this.countsOf(node, children);
        if (live === 0)
            return true;
        // only comments that can be removed along with it are left
        return (isPostCSSRule(node) || isPostCSSAtRule(node)) && kept === 0;
    }
    /**
     * Remove the recorded nodes from the tree, in one pass per container
     */
    apply() {
        var _a;
        const parents = new Set();
        for (const node of this.removed) {
            if (node.parent)
                parents.add(getRawNode(node.parent));
        }
        for (const parent of parents) {
            const container = parent;
            const nodes = (_a = container.nodes) !== null && _a !== void 0 ? _a : [];
            const kept = [];
            // positions of the removed children, to update the running iterators
            // like `removeChild` does
            const removedPositions = [];
            for (let i = 0; i < nodes.length; i++) {
                if (this.removed.has(nodes[i])) {
                    removedPositions.push(i);
                }
                else {
                    kept.push(nodes[i]);
                }
            }
            container.nodes = kept;
            if (container.indexes) {
                for (const id in container.indexes) {
                    const index = container.indexes[id];
                    let shift = 0;
                    while (shift < removedPositions.length &&
                        removedPositions[shift] <= index) {
                        shift++;
                    }
                    container.indexes[id] = index - shift;
                }
            }
        }
        for (const node of this.removed) {
            node.parent = undefined;
        }
        for (const parent of parents) {
            parent.markDirty();
        }
        this.removed.clear();
        this.counts.clear();
        this.skips.clear();
        this.firstChildren.clear();
    }
}
/**
 * Copy of a container without its children
 *
 * @param container - rule or at-rule of postcss AST
 */
function cloneWithoutChildren(container) {
    const raw = getRawNode(container);
    const nodes = raw.nodes;
    // the children are not cloned only to be thrown away
    raw.nodes = [];
    try {
        return raw.clone();
    }
    finally {
        raw.nodes = nodes;
    }
}
/**
 * Build the rejected css of a rule: a copy of the rule with only its rejected
 * selectors, wrapped in empty copies of all its ancestors (at-rules and nested
 * rules) so that it keeps the context it applies in, e.g.
 * `@supports (display: grid) { @media print { .rejected {} } }`.
 *
 * Returns `undefined` when an ancestor was already removed from the tree: the
 * ancestor was rejected with all its content, which already contains the rule.
 *
 * @param rule - rule with rejected selectors
 * @param rejectedSelectors - selectors removed from the rule
 * @param removals - removals recorded during the walk
 */
function getRejectedNode(rule, rejectedSelectors, removals) {
    const rejectedRule = rule.clone();
    rejectedRule.selectors = rejectedSelectors;
    let rejectedNode = rejectedRule;
    let ancestor = removals.parentOf(rule);
    while (isPostCSSRule(ancestor) || isPostCSSAtRule(ancestor)) {
        rejectedNode = cloneWithoutChildren(ancestor).append(rejectedNode);
        ancestor = removals.parentOf(ancestor);
    }
    // the chain of ancestors stops at the root unless one of them was removed
    return ancestor ? rejectedNode : undefined;
}
/**
 * Check if the node has a css comment indicating to ignore the current selector rule
 *
 * @param rule - rule of postcss AST
 * @param removals - removals recorded during the walk
 */
function hasIgnoreAnnotation(rule, removals) {
    let found = false;
    rule.walkComments((node) => {
        if (node &&
            node.type === "comment" &&
            node.text.includes(IGNORE_ANNOTATION_CURRENT)) {
            found = true;
            // the content of the rule is not walked through yet
            removals.removeNow(node);
        }
    });
    return found;
}
/**
 * Merge two extractor selectors
 *
 * @param extractorSelectorsA - extractor selectors A
 * @param extractorSelectorsB - extractor selectors B
 * @returns  the merged extractor result sets
 *
 * @public
 */
function mergeExtractorSelectors(...extractors) {
    const result = new ExtractorResultSets([]);
    extractors.forEach(result.merge, result);
    return result;
}
/**
 * Strips quotes of a string
 *
 * @param str - string to be stripped
 */
function stripQuotes(str) {
    return str.replace(/(^["'])|(["']$)/g, "");
}
/**
 * Returns true if the attribute is found in the extractor selectors
 *
 * @param attributeNode - node of type `attribute`
 * @param selectors - extractor selectors
 */
function isAttributeFound(attributeNode, selectors) {
    if (!selectors.hasAttrName(attributeNode.attribute)) {
        return false;
    }
    if (typeof attributeNode.value === "undefined") {
        return true;
    }
    switch (attributeNode.operator) {
        case "$=":
            return selectors.hasAttrSuffix(attributeNode.value);
        case "~=":
        case "*=":
            return selectors.hasAttrSubstr(attributeNode.value);
        case "=":
            return selectors.hasAttrValue(attributeNode.value);
        case "|=":
        case "^=":
            return selectors.hasAttrPrefix(attributeNode.value);
        default:
            return true;
    }
}
/**
 * Returns true if the class is found in the extractor selectors
 *
 * @param classNode - node of type `class`
 * @param selectors - extractor selectors
 */
function isClassFound(classNode, selectors) {
    return selectors.hasClass(classNode.value);
}
/**
 * Returns true if the identifier is found in the extractor selectors
 *
 * @param identifierNode - node of type `identifier`
 * @param selectors - extractor selectors
 */
function isIdentifierFound(identifierNode, selectors) {
    return selectors.hasId(identifierNode.value);
}
/**
 * Returns true if the tag is found in the extractor selectors
 *
 * @param tagNode - node of type `tag`
 * @param selectors - extractor selectors
 */
function isTagFound(tagNode, selectors) {
    return selectors.hasTag(tagNode.value);
}
/**
 * Returns true if the selector is inside a pseudo class
 * (e.g. :nth-child, :nth-of-type, :only-child, :not)
 *
 * @param selector - selector
 */
function isInPseudoClass(selector) {
    return ((selector.parent &&
        selector.parent.type === "pseudo" &&
        selector.parent.value.startsWith(":")) ||
        false);
}
/**
 * Returns true if the selector is inside the pseudo classes :where() or :is()
 * @param selector - selector
 */
function isInPseudoClassWhereOrIs(selector) {
    return ((selector.parent &&
        selector.parent.type === "pseudo" &&
        (selector.parent.value === ":where" ||
            selector.parent.value === ":is")) ||
        false);
}
/**
 * Returns true if the selector is nested anywhere inside a :not() pseudo class.
 * Removing a selector there changes the meaning of the negation, so it is kept.
 *
 * @param selector - selector
 */
function isInsideNotPseudoClass(selector) {
    let node = selector.parent;
    while (node) {
        if (node.type === "pseudo" && node.value === ":not") {
            return true;
        }
        node = node.parent;
    }
    return false;
}
/**
 * Returns true if the selector is a pseudo class at the root level
 * Pseudo classes checked: :where, :is, :has, :not
 * @param selector - selector
 */
function isPseudoClassAtRootLevel(selector) {
    var _a;
    let result = false;
    if (selector.type === "selector" &&
        ((_a = selector.parent) === null || _a === void 0 ? void 0 : _a.type) === "root" &&
        selector.nodes.length === 1) {
        selector.walk((node) => {
            if (node.type === "pseudo" &&
                (node.value === ":where" ||
                    node.value === ":is" ||
                    node.value === ":has" ||
                    node.value === ":not")) {
                result = true;
            }
        });
    }
    return result;
}
function isPostCSSAtRule(node) {
    return (node === null || node === void 0 ? void 0 : node.type) === "atrule";
}
function isPostCSSRule(node) {
    return (node === null || node === void 0 ? void 0 : node.type) === "rule";
}
function isPostCSSComment(node) {
    return (node === null || node === void 0 ? void 0 : node.type) === "comment";
}
/**
 * Class used to instantiate PurgeCSS and can then be used
 * to purge CSS files.
 *
 * @example
 * ```ts
 * await new PurgeCSS().purge({
 *    content: ['index.html'],
 *    css: ['css/app.css']
 * })
 * ```
 *
 * @public
 */
class PurgeCSS {
    constructor() {
        this.ignore = false;
        this.atRules = {
            fontFace: [],
            keyframes: [],
        };
        this.usedAnimations = new Set();
        this.usedFontFaces = new Set();
        this.selectorsRemoved = new Set();
        this.removedNodes = [];
        this.variablesStructure = new VariablesStructure();
        this.options = defaultOptions;
        /** removals of nodes made during the walk through the css */
        this.removals = new DeferredRemovals();
    }
    collectDeclarationsData(declaration, isIgnored) {
        const { prop, value } = declaration;
        // collect css properties data
        if (this.options.variables) {
            // custom properties kept by an ignore annotation are not registered so
            // they are never removed, but the variables they use still count as used.
            // The variables used by a registered custom property are read from its
            // value when removing the unused variables, if it is used itself
            if (prop.startsWith("--") && !isIgnored) {
                this.variablesStructure.addVariable(declaration);
            }
            else {
                this.variablesStructure.addVariableUsageInProperties(value.matchAll(/\bvar\(\s*(.+?)\s*[,)]/g));
            }
        }
        // collect keyframes data
        if (this.options.keyframes) {
            if (prop === "animation" || prop === "animation-name") {
                for (const word of value.split(/[\s,]+/)) {
                    this.usedAnimations.add(word);
                }
                return;
            }
            // Also check CSS custom properties for animation names
            // e.g., --my-animation: fadeIn 0.4s;
            if (prop.startsWith("--")) {
                for (const word of value.split(/[\s,]+/)) {
                    this.usedAnimations.add(word);
                }
            }
        }
        // collect font faces data
        if (this.options.fontFace) {
            if (prop === "font-family") {
                for (const fontName of value.split(",")) {
                    const cleanedFontFace = stripQuotes(fontName.trim());
                    this.usedFontFaces.add(cleanedFontFace);
                }
            }
            return;
        }
    }
    /**
     * Collect the data of the declarations directly inside a node
     *
     * @param node - rule or at-rule of postcss AST
     * @param isIgnored - whether the node is kept by an ignore annotation
     */
    collectDeclarationsDataOfNode(node, isIgnored = false) {
        node.each((childNode) => {
            if (childNode.type !== "decl")
                return;
            this.collectDeclarationsData(childNode, isIgnored);
        });
    }
    /**
     * Check if a node is kept by an ignore annotation: inside an ignore range,
     * or right after an ignore next line comment, which is then removed
     *
     * @param node - node of postcss AST
     * @param index - index of the node in the children of its parent
     */
    isIgnored(node, index) {
        if (this.ignore) {
            return true;
        }
        const annotation = this.removals.previousSibling(node, index);
        if (isPostCSSComment(annotation) &&
            isIgnoreAnnotation(annotation, "next")) {
            this.removals.remove(annotation);
            return true;
        }
        return false;
    }
    /**
     * Get the extractor corresponding to the extension file
     * @param filename - Name of the file
     * @param extractors - Array of extractors definition
     */
    getFileExtractor(filename, extractors) {
        const extractorObj = extractors.find((extractor) => extractor.extensions.find((ext) => filename.endsWith(ext)));
        return typeof extractorObj === "undefined"
            ? this.options.defaultExtractor
            : extractorObj.extractor;
    }
    /**
     * Extract the selectors present in the files using a PurgeCSS extractor
     *
     * @param files - Array of files path or glob pattern
     * @param extractors - Array of extractors
     */
    async extractSelectorsFromFiles(files, extractors) {
        const selectors = new ExtractorResultSets([]);
        const filesNames = [];
        for (const globFile of files) {
            try {
                await asyncFs.access(globFile, fs.constants.F_OK);
                filesNames.push(globFile);
                // eslint-disable-next-line @typescript-eslint/no-unused-vars
            }
            catch (err) {
                filesNames.push(...glob.sync(globFile, {
                    onlyFiles: true,
                    ignore: this.options.skippedContentGlobs.map((glob) => glob.replace(/^\.\//, "")),
                }));
            }
        }
        if (files.length > 0 && filesNames.length === 0) {
            console.warn("No files found from the passed PurgeCSS option 'content'.");
        }
        // files are read and extracted concurrently, and the selectors of each
        // file are merged as soon as they are extracted, so that they are not
        // kept in memory until every file is done. The merged sets are the same
        // whatever the order.
        await forEachContentFile(filesNames, async (file) => {
            selectors.merge(await this.extractSelectorsFromFile(file, extractors));
        });
        return selectors;
    }
    /**
     * Extract the selectors present in a file, reusing the selectors of the
     * content cache when the file did not change
     *
     * @param file - path of the file
     * @param extractors - Array of extractors
     */
    async extractSelectorsFromFile(file, extractors) {
        const extractor = this.getFileExtractor(file, extractors);
        const contentCache = this.contentCache;
        if (!contentCache) {
            const content = await asyncFs.readFile(file, "utf-8");
            return extractSelectors(content, extractor);
        }
        const filePath = path.resolve(file);
        // the file is stat before being read: if it changes in between, the
        // stored stats are the old ones and it is read again next time
        const checkedAt = Date.now();
        const { mtimeMs, ctimeMs, size, ino } = await asyncFs.stat(filePath);
        const stats = { mtimeMs, ctimeMs, size, ino };
        const cachedSelectors = contentCache.get(filePath, stats, extractor);
        if (cachedSelectors) {
            return cachedSelectors;
        }
        // stored before being awaited, so that the runs at the same time wait
        // for this extraction instead of starting their own
        const selectors = asyncFs
            .readFile(filePath, "utf-8")
            .then((content) => extractSelectors(content, extractor));
        contentCache.set(filePath, { ...stats, extractor, selectors, checkedAt });
        return selectors;
    }
    /**
     * Extract the selectors present in the passed string using a PurgeCSS extractor
     *
     * @param content - Array of content
     * @param extractors - Array of extractors
     */
    async extractSelectorsFromString(content, extractors) {
        const selectors = new ExtractorResultSets([]);
        for (const { raw, extension } of content) {
            const extractor = this.getFileExtractor(`.${extension}`, extractors);
            const extractedSelectors = await extractSelectors(raw, extractor);
            selectors.merge(extractedSelectors);
        }
        return selectors;
    }
    /**
     * Evaluate at-rule and register it for future reference
     * @param node - node of postcss AST
     * @param index - index of the node in the children of its parent
     */
    evaluateAtRule(node, index) {
        const isIgnored = this.isIgnored(node, index);
        // when tracking variables, collect var() usages from declarations
        // nested inside at-rules (e.g. @media, @supports, ...)
        if (this.options.variables &&
            (node.name === "media" || node.name === "supports")) {
            this.collectDeclarationsDataOfNode(node, isIgnored);
        }
        // exit if it is kept by an ignore annotation
        if (isIgnored) {
            return;
        }
        // @property rules of css variables
        if (this.options.variables &&
            node.name === "property" &&
            node.params.trim().startsWith("--")) {
            this.variablesStructure.addProperty(node);
            return;
        }
        // keyframes
        if (this.options.keyframes && node.name.endsWith("keyframes")) {
            this.atRules.keyframes.push(node);
            return;
        }
        // font-face
        if (this.options.fontFace && node.name === "font-face" && node.nodes) {
            for (const childNode of node.nodes) {
                if (childNode.type === "decl" && childNode.prop === "font-family") {
                    this.atRules.fontFace.push({
                        name: stripQuotes(childNode.value),
                        node,
                    });
                }
            }
        }
    }
    /**
     * Evaluate css selector and decide if it should be removed or not
     *
     * @param node - node of postcss AST
     * @param index - index of the node in the children of its parent
     * @param selectors - selectors used in content files
     */
    evaluateRule(node, index, selectors) {
        // exit if it is kept by an ignore annotation (ignore range or ignore next
        // line comment), still collecting what its declarations use
        if (this.isIgnored(node, index)) {
            if (isPostCSSRule(node))
                this.collectDeclarationsDataOfNode(node, true);
            return;
        }
        // collect variables and exit if it is inside a keyframes
        if (node.parent &&
            isPostCSSAtRule(node.parent) &&
            node.parent.name.endsWith("keyframes")) {
            // declarations inside keyframes rules
            if (isPostCSSRule(node))
                this.collectDeclarationsDataOfNode(node);
            return;
        }
        // exit if it is not a rule
        if (!isPostCSSRule(node)) {
            return;
        }
        // exit if it has an ignore rule comment inside, still collecting what its
        // declarations use
        if (hasIgnoreAnnotation(node, this.removals)) {
            this.collectDeclarationsDataOfNode(node, true);
            return;
        }
        const selectorsRemovedFromRule = [];
        // selector transformer, walk over the list of the parsed selectors twice.
        // First pass will remove the unused selectors. It goes through
        // pseudo-classes like :where() and :is() and remove the unused
        // selectors inside of them, but will not remove the pseudo-classes
        // themselves. Second pass will remove selectors containing empty
        // :where and :is.
        node.selector = selectorParser((selectorsParsed) => {
            selectorsParsed.walk((selector) => {
                if (selector.type !== "selector") {
                    return;
                }
                const keepSelector = this.shouldKeepSelector(selector, selectors);
                if (!keepSelector) {
                    // the whitespace after the previous comma belongs to the selector
                    const removedSelector = selector.toString().trim();
                    if (this.options.rejected) {
                        this.selectorsRemoved.add(removedSelector);
                    }
                    if (this.options.rejectedCss) {
                        selectorsRemovedFromRule.push(removedSelector);
                    }
                    selector.remove();
                }
            });
            // removes selectors containing empty :where and :is
            selectorsParsed.walk((selector) => {
                if (selector.type !== "selector") {
                    return;
                }
                if (selector.toString() && /(:where)|(:is)/.test(selector.toString())) {
                    selector.walk((node) => {
                        if (node.type !== "pseudo")
                            return;
                        if (node.value !== ":where" && node.value !== ":is")
                            return;
                        if (node.nodes.length === 0) {
                            selector.remove();
                        }
                    });
                }
            });
        }).processSync(node.selector);
        // declarations
        if (node.selector)
            this.collectDeclarationsDataOfNode(node);
        // rebuild the rule with the removed selectors, before the rule and its
        // emptied parents are detached from the tree
        if (this.options.rejectedCss && selectorsRemovedFromRule.length > 0) {
            const rejectedNode = getRejectedNode(node, selectorsRemovedFromRule, this.removals);
            if (rejectedNode)
                this.removedNodes.push(rejectedNode);
        }
        // remove empty rules
        const parent = this.removals.parentOf(node);
        if (!node.selector) {
            this.removals.remove(node);
        }
        // remove the parents left empty, going up through nested rules and
        // at-rules (e.g. @supports inside @media) but not past the root
        let emptyCandidate = parent;
        while (emptyCandidate && this.removals.isEmpty(emptyCandidate)) {
            const grandParent = this.removals.parentOf(emptyCandidate);
            this.removals.remove(emptyCandidate);
            emptyCandidate =
                isPostCSSRule(grandParent) || isPostCSSAtRule(grandParent)
                    ? grandParent
                    : undefined;
        }
    }
    /**
     * Get the purged version of the css based on the files
     *
     * @param cssOptions - css options, files or raw strings
     * @param selectors - set of extracted css selectors
     */
    async getPurgedCSS(cssOptions, selectors) {
        const sources = [];
        // resolve any globs
        const processedOptions = [];
        for (const option of cssOptions) {
            if (typeof option === "string") {
                processedOptions.push(...glob.sync(option, {
                    onlyFiles: true,
                    ignore: this.options.skippedContentGlobs,
                }));
            }
            else {
                processedOptions.push(option);
            }
        }
        // unused font faces, keyframes and variables are removed once every css
        // file has been walked through, so that a font face, keyframes or variable
        // defined in one file and used in another one is kept. The files are kept
        // in memory until then, and only when one of these options is enabled
        const removesUnusedAcrossFiles = this.options.fontFace || this.options.keyframes || this.options.variables;
        const purgedRoots = [];
        for (const option of processedOptions) {
            const cssContent = typeof option === "string"
                ? this.options.stdin
                    ? option
                    : await asyncFs.readFile(option, "utf-8")
                : option.raw;
            // the name of raw css is used as its path in the source maps, like
            // the path of a css file: the map sources are relative to the
            // directory of `sourceMap.to`, which defaults to that path
            const from = typeof option === "string"
                ? this.options.stdin
                    ? undefined
                    : option
                : option.name || undefined;
            const root = postcss.parse(cssContent, { from });
            // the rejected css of a file only contains the rules removed from it
            this.removedNodes = [];
            // purge unused selectors
            this.walkThroughCSS(root, selectors);
            const purgedRoot = {
                root,
                from,
                file: typeof option === "string" ? option : option.name,
            };
            if (this.options.rejected) {
                purgedRoot.rejected = Array.from(this.selectorsRemoved);
                this.selectorsRemoved.clear();
            }
            if (this.options.rejectedCss) {
                purgedRoot.rejectedCss = postcss
                    .root({ nodes: this.removedNodes })
                    .toString();
            }
            if (removesUnusedAcrossFiles) {
                purgedRoots.push(purgedRoot);
            }
            else {
                sources.push(this.getResultPurge(purgedRoot));
            }
        }
        if (this.options.fontFace)
            this.removeUnusedFontFaces();
        if (this.options.keyframes)
            this.removeUnusedKeyframes();
        if (this.options.variables)
            this.removeUnusedCSSVariables();
        for (const purgedRoot of purgedRoots) {
            sources.push(this.getResultPurge(purgedRoot));
        }
        return sources;
    }
    /**
     * Build the result of a purged css file
     *
     * @param purgedRoot - purged css file
     */
    getResultPurge({ root, from, file, rejected, rejectedCss, }) {
        var _a;
        const postCSSResult = root.toResult({
            map: this.options.sourceMap,
            to: typeof this.options.sourceMap === "object" && this.options.sourceMap.to
                ? this.options.sourceMap.to
                : from,
        });
        const result = {
            css: postCSSResult.toString(),
            file,
        };
        if (this.options.sourceMap) {
            result.sourceMap = (_a = postCSSResult.map) === null || _a === void 0 ? void 0 : _a.toString();
        }
        if (this.options.rejected) {
            result.rejected = rejected;
        }
        if (this.options.rejectedCss) {
            result.rejectedCss = rejectedCss;
        }
        return result;
    }
    /**
     * Check if the keyframe is safelisted with the option safelist keyframes
     *
     * @param keyframesName - name of the keyframe animation
     */
    isKeyframesSafelisted(keyframesName) {
        return this.options.safelist.keyframes.some((safelistItem) => matchesPattern(safelistItem, keyframesName));
    }
    /**
     * Check if the selector is blocklisted with the option blocklist
     *
     * @param selector - css selector
     */
    isSelectorBlocklisted(selector) {
        return this.options.blocklist.some((blocklistItem) => matchesPattern(blocklistItem, selector));
    }
    /**
     * Check if the selector is safelisted with the option safelist standard
     *
     * @param selector - css selector
     */
    isSelectorSafelisted(selector) {
        const isSafelisted = this.options.safelist.standard.some((safelistItem) => matchesPattern(safelistItem, selector));
        const isPseudoElement = /^::.*/.test(selector);
        return CSS_SAFELIST.includes(selector) || isPseudoElement || isSafelisted;
    }
    /**
     * Check if the selector is safelisted with the option safelist deep
     *
     * @param selector - selector
     */
    isSelectorSafelistedDeep(selector) {
        return this.options.safelist.deep.some((safelistItem) => matchesPattern(safelistItem, selector));
    }
    /**
     * Check if the selector is safelisted with the option safelist greedy
     *
     * @param selector - selector
     */
    isSelectorSafelistedGreedy(selector) {
        return this.options.safelist.greedy.some((safelistItem) => matchesPattern(safelistItem, selector));
    }
    /**
     * Check if the attribute is dynamic, i.e. it can be set or changed at runtime.
     * Attribute selectors on dynamic attributes are always kept, whatever their
     * value, as the attribute may not appear in the content files.
     *
     * `value` is highly used in input elements and can change based on the user,
     * idem for `checked`, `selected` and `open`, so they are always dynamic.
     * Other attributes can be added with the option dynamicAttributes.
     *
     * @param attributeName - name of the attribute, e.g. `aria-selected`
     */
    isAttributeDynamic(attributeName) {
        return (DYNAMIC_ATTRIBUTES.includes(attributeName) ||
            this.options.dynamicAttributes.some((dynamicAttribute) => matchesPattern(dynamicAttribute, attributeName)));
    }
    /**
     * Remove unused CSS
     *
     * @param userOptions - PurgeCSS options or path to the configuration file
     * @returns an array of object containing the filename and the associated CSS
     *
     * @example Using a configuration file named purgecss.config.js
     * ```ts
     * const purgeCSSResults = await new PurgeCSS().purge()
     * ```
     *
     * @example Using a custom path to the configuration file
     * ```ts
     * const purgeCSSResults = await new PurgeCSS().purge('./purgecss.config.js')
     * ```
     *
     * @example Using the PurgeCSS options
     * ```ts
     * const purgeCSSResults = await new PurgeCSS().purge({
     *    content: ['index.html', '**\/*.js', '**\/*.html', '**\/*.vue'],
     *    css: ['css/app.css']
     * })
     * ```
     */
    async purge(userOptions) {
        this.options =
            typeof userOptions !== "object"
                ? await setOptions(userOptions)
                : {
                    ...defaultOptions,
                    ...userOptions,
                    safelist: standardizeSafelist(userOptions.safelist),
                };
        const { content, css, extractors, safelist } = this.options;
        if (this.options.variables) {
            this.variablesStructure.safelist = safelist.variables || [];
        }
        const fileFormatContents = content.filter((o) => typeof o === "string");
        const rawFormatContents = content.filter((o) => typeof o === "object");
        const cssFileSelectors = await this.extractSelectorsFromFiles(fileFormatContents, extractors);
        const cssRawSelectors = await this.extractSelectorsFromString(rawFormatContents, extractors);
        return this.getPurgedCSS(css, mergeExtractorSelectors(cssFileSelectors, cssRawSelectors));
    }
    /**
     * Remove unused CSS variables
     */
    removeUnusedCSSVariables() {
        this.variablesStructure.removeUnused();
    }
    /**
     * Remove unused font-faces
     */
    removeUnusedFontFaces() {
        for (const { name, node } of this.atRules.fontFace) {
            if (!this.usedFontFaces.has(name)) {
                node.remove();
            }
        }
    }
    /**
     * Remove unused keyframes
     */
    removeUnusedKeyframes() {
        for (const node of this.atRules.keyframes) {
            if (!this.usedAnimations.has(node.params) &&
                !this.isKeyframesSafelisted(node.params)) {
                node.remove();
            }
        }
    }
    /**
     * Transform a selector node into a string
     */
    getSelectorValue(selector) {
        return ((selector.type === "attribute" && selector.attribute) || selector.value);
    }
    /**
     * Determine if the selector should be kept, based on the selectors found in the files
     *
     * @param selector - set of css selectors found in the content files or string
     * @param selectorsFromExtractor - selectors in the css rule
     *
     * @returns true if the selector should be kept in the processed CSS
     */
    shouldKeepSelector(selector, selectorsFromExtractor) {
        // selectors in pseudo classes are ignored except :where() and :is(). For those pseudo-classes, we are treating the selectors inside the same way as they would be outside.
        if (isInPseudoClass(selector) && !isInPseudoClassWhereOrIs(selector)) {
            return true;
        }
        // keep the blocklist from matching the pseudo class name itself (":is", ":not", …)
        if (isPseudoClassAtRootLevel(selector)) {
            return true;
        }
        // :where() and :is() inside :not() are kept as a whole, otherwise the
        // emptied pseudo class would drop the negated rule
        if (isInPseudoClassWhereOrIs(selector) &&
            isInsideNotPseudoClass(selector)) {
            return true;
        }
        // if there is any greedy safelist pattern, run all the selector parts through them
        // if there is any match, return true
        if (this.options.safelist.greedy.length > 0) {
            const selectorParts = selector.nodes.map(this.getSelectorValue);
            if (selectorParts.some((selectorPart) => selectorPart && this.isSelectorSafelistedGreedy(selectorPart))) {
                return true;
            }
        }
        for (const selectorNode of selector.nodes) {
            const selectorValue = this.getSelectorValue(selectorNode);
            // if the selector is safelisted with children
            // returns true to keep all children selectors
            if (selectorValue && this.isSelectorSafelistedDeep(selectorValue)) {
                return true;
            }
            // The selector is found in the internal and user-defined safelist
            if (selectorValue &&
                (CSS_SAFELIST.includes(selectorValue) ||
                    this.isSelectorSafelisted(selectorValue))) {
                continue;
            }
            // The selector is present in the blocklist
            if (selectorValue && this.isSelectorBlocklisted(selectorValue)) {
                return false;
            }
            let isPresent;
            switch (selectorNode.type) {
                case "attribute":
                    isPresent = this.isAttributeDynamic(selectorNode.attribute)
                        ? true
                        : isAttributeFound(selectorNode, selectorsFromExtractor);
                    break;
                case "class":
                    isPresent = isClassFound(selectorNode, selectorsFromExtractor);
                    break;
                case "id":
                    isPresent = isIdentifierFound(selectorNode, selectorsFromExtractor);
                    break;
                case "tag":
                    isPresent = isTagFound(selectorNode, selectorsFromExtractor);
                    break;
                default:
                    // Pseudo-classes (:where, :is, :not, …) carry no matchable name at
                    // this level; their inner selectors are evaluated separately. Skip
                    // them without treating the compound as unused.
                    continue;
            }
            // a matchable part (class/id/tag/attribute) was not found: drop it
            if (!isPresent) {
                return false;
            }
        }
        // nothing was found missing: keep the selector
        return true;
    }
    /**
     * Walk through the CSS AST and remove unused CSS
     *
     * @param root - root node of the postcss AST
     * @param selectors - selectors used in content files
     */
    walkThroughCSS(root, selectors) {
        // the nodes are removed once the whole tree has been walked through
        try {
            root.walk((node, index) => {
                if (node.type === "rule") {
                    return this.evaluateRule(node, index, selectors);
                }
                if (node.type === "atrule") {
                    return this.evaluateAtRule(node, index);
                }
                if (node.type === "comment") {
                    if (isIgnoreAnnotation(node, "start")) {
                        this.ignore = true;
                        // remove ignore annotation
                        this.removals.remove(node);
                    }
                    else if (isIgnoreAnnotation(node, "end")) {
                        this.ignore = false;
                        // remove ignore annotation
                        this.removals.remove(node);
                    }
                }
            });
        }
        finally {
            this.removals.apply();
        }
    }
}

export { ContentCache, ExtractorResultSets, PurgeCSS, VariableNode, VariablesStructure, defaultOptions, matchesPattern, mergeExtractorSelectors, setOptions, standardizeSafelist };