@fullhuman/postcss-purgecss
Version:
PostCSS plugin for PurgeCSS
949 lines (943 loc) • 37.9 kB
JavaScript
import * as fs from 'fs';
import { promises } from 'fs';
import * as path from 'path';
import { pathToFileURL } from 'url';
import { ContentCache, matchesPattern, PurgeCSS, standardizeSafelist, defaultOptions, mergeExtractorSelectors } from 'purgecss';
import fastGlob from 'fast-glob';
import * as os from 'os';
/**
* Selectors extracted from the content files, shared by all the instances of
* the plugin. Bundlers run PostCSS once per CSS file, and some of them (e.g.
* postcss-loader for webpack and Rspack) create a new instance of the plugin
* for every CSS file: a content file is only read and extracted again when it
* changed, or when the extractor used for it is another function.
*
* @internal
*/
const sharedContentCache = new ContentCache();
/**
* Content files read by the last run of each content option, to remove from
* the shared cache the files that no content option reads any more
*/
const contentFilesByContentKey = new Map();
/**
* Content cache of a run of the plugin: it uses the selectors of another
* cache and records the content files that PurgeCSS reads through it
*
* @internal
*/
class RunContentCache extends ContentCache {
/**
* @param cache - cache that holds the selectors
*/
constructor(cache) {
super();
this.cache = cache;
/** absolute paths of the content files read by the run */
this.files = new Set();
}
get size() {
return this.cache.size;
}
get(filePath, stats, extractor) {
this.files.add(filePath);
return this.cache.get(filePath, stats, extractor);
}
set(filePath, entry) {
this.files.add(filePath);
this.cache.set(filePath, entry);
}
has(filePath) {
return this.cache.has(filePath);
}
keys() {
return this.cache.keys();
}
delete(filePath) {
return this.cache.delete(filePath);
}
prune(filePaths) {
return this.cache.prune(filePaths);
}
clear() {
this.cache.clear();
}
}
/**
* Create the content cache of a run of the plugin
*
* @param shared - whether the selectors are shared with the other runs, or
* extracted again for this run only
*/
function createRunContentCache(shared) {
return new RunContentCache(shared ? sharedContentCache : new ContentCache());
}
/**
* Remove from the shared cache the files that a content option no longer
* reads (deleted, renamed, or no longer matched by its globs) and that no
* other content option read on its last run, so that the cache does not grow
* with every file ever read in a long dev session
*
* @param contentKey - key of the content option, e.g. its globs
* @param files - absolute paths of the content files read by the run
*/
function pruneSharedContentCache(contentKey, files) {
const previousFiles = contentFilesByContentKey.get(contentKey);
contentFilesByContentKey.set(contentKey, files);
if (!previousFiles)
return;
for (const file of previousFiles) {
if (files.has(file))
continue;
let isReadElsewhere = false;
for (const otherFiles of contentFilesByContentKey.values()) {
if (otherFiles.has(file)) {
isReadElsewhere = true;
break;
}
}
if (!isReadElsewhere)
sharedContentCache.delete(file);
}
}
/**
* Check if a PostCSS message is an export message of CSS modules, as
* postcss-modules pushes with the type `export` and the scoped names of the
* classes in `exportTokens`
*
* @param message - PostCSS message
*/
function isExportMessage(message) {
return (message.type === "export" &&
typeof message.exportTokens === "object" &&
message.exportTokens !== null);
}
/**
* Class names and IDs of the rule selectors of a root, unescaped.
* Approximate: it may hold names that are not classes or IDs, e.g. from a
* keyframe selector `50.5%` or an attribute selector `[href="#top"]`.
*
* @param root - PostCSS root
*/
function getRootNames(root) {
const names = { classes: new Set(), ids: new Set() };
root.walkRules((rule) => {
for (const match of rule.selector.matchAll(/([.#])((?:[^\s.#:[\]()>+~,*'"\\=|^$]|\\.)+)/g)) {
const name = match[2].replace(/\\(.)/g, "$1");
(match[1] === "." ? names.classes : names.ids).add(name);
}
});
return names;
}
/**
* Words of a CSS source that can be class names, IDs or values: the runs of
* characters that are not whitespace or CSS punctuation, unescaped, e.g.
* `red` and `brand` for `@value brand: red;` and `sm:p-4` for `.sm\:p-4`
*
* @param css - CSS source, before postcss-modules
*/
function getSourceWordsOf(css) {
const words = new Set();
for (const [word] of css.matchAll(/(?:[^\s.#:[\]()>+~,*'"\\=|^$;{}!/@%&]|\\.)+/g)) {
words.add(word.replace(/\\(.)/g, "$1"));
}
return words;
}
/**
* Names postcss-modules may export a value under, depending on its option
* `localsConvention`: the name, its camelCase form (as lodash.camelcase
* gives it for ASCII names) and its dashes form, e.g. `brand-color` gives
* `brand-color` and `brandColor`
*
* @param name - name of a value
*/
function getConventionNames(name) {
var _a;
const words = (_a = name.match(/[A-Z]{2,}(?=[A-Z][a-z]|[^A-Za-z]|$)|[A-Z]?[a-z]+|[A-Z]+|\d+/g)) !== null && _a !== void 0 ? _a : [];
const camelCase = words
.map((word, index) => index === 0
? word.toLowerCase()
: word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join("");
return [name, camelCase, toDashesForm(name)];
}
/**
* The dashes form of a name, as postcss-modules gives it with
* `localsConvention: "dashes"`: each run of dashes followed by a word
* character is removed and the character upper-cased, e.g. `brand--color`
* gives `brandColor`. Like `name.replace(/-+(\w)/g, ...)`, in linear time.
*
* @param name - name of a value
*/
function toDashesForm(name) {
let result = "";
let index = 0;
while (index < name.length) {
if (name[index] !== "-") {
result += name[index++];
continue;
}
let end = index;
while (end < name.length && name[end] === "-")
end++;
if (end < name.length && /\w/.test(name[end])) {
result += name[end].toUpperCase();
index = end + 1;
}
else {
result += name.slice(index, end);
index = end;
}
}
return result;
}
/**
* Values defined or imported with `@value` in a CSS source: postcss-modules
* exports them along with the classes, e.g. `@value brand: red` gives the
* token `brand: "red"`, which is no class. The map has an entry for each name
* postcss-modules may export a value under (see `getConventionNames`), with
* the value it exports, or `undefined` when the value is unknown, e.g. for an
* imported value.
*
* @param css - CSS source, before postcss-modules
*/
function getValueDefinitions(css) {
const definitions = new Map();
const add = (name, value) => {
for (const exportedName of getConventionNames(name)) {
// two values exported under the same name: the value is unknown
const isConflict = definitions.has(exportedName) &&
definitions.get(exportedName) !== value;
definitions.set(exportedName, isConflict ? undefined : value);
}
};
// the values by their exact name: a value can refer to the values defined
// before it, e.g. `@value border: 1px solid brand`
const values = new Map();
for (const [, params] of css.matchAll(/@value\s+([^;{}]+)/g)) {
// `@value a, b as c from "./colors.css"`: the words before `from` and
// the path. Split on whitespace rather than matched with a regex that
// takes quadratic time on long runs of spaces.
const words = params.trim().split(/\s+/);
if (words.length >= 3 && words[words.length - 2] === "from") {
const imported = words.slice(0, -2).join(" ");
for (const item of imported.replace(/[()]/g, "").split(",")) {
const itemWords = item.trim().split(/\s+/);
const asIndex = itemWords.lastIndexOf("as");
const alias = (asIndex > 0 ? itemWords.slice(asIndex + 1) : itemWords).join(" ");
if (alias) {
values.set(alias, undefined);
add(alias, undefined);
}
}
continue;
}
// `@value brand: red` or `@value brand red`
const definitionMatch = /^([\w-]+):?([\s\S]*)$/.exec(params.trim());
if (definitionMatch) {
const [, name, rawValue] = definitionMatch;
let isKnown = true;
const value = rawValue.trim().replace(/[\w-]+/g, (word) => {
if (!values.has(word))
return word;
const referencedValue = values.get(word);
if (referencedValue === undefined)
isKnown = false;
return referencedValue !== null && referencedValue !== void 0 ? referencedValue : word;
});
values.set(name, isKnown ? value : undefined);
add(name, isKnown ? value : undefined);
}
}
return definitions;
}
/**
* Check if an exported token is a value defined with `@value` rather than a
* class or an ID: its name is the name of a value, and its value is the one
* of the value, if known. A class whose name only looks like the name of a
* value, e.g. `.brand-color` next to `@value brandColor`, is no value.
*
* @param definitions - values of the CSS source, from `getValueDefinitions`
* @param localName - name of the token
* @param value - value of the token
*/
function isValueToken(definitions, localName, value) {
if (!definitions.has(localName))
return false;
const definition = definitions.get(localName);
return definition === undefined || definition === value.trim();
}
/**
* Check if a name matches one of the patterns of an option, as PurgeCSS does
*
* @param patterns - strings and regular expressions of an option
* @param name - local name of a class
*/
function matchesAnyPattern(patterns, name) {
return patterns.some((pattern) => matchesPattern(pattern, name));
}
/**
* Get the scoped names of the classes and IDs of the CSS modules whose local
* name is used in the content, safelisted or blocklisted.
*
* When postcss-modules runs before this plugin, as in Vite, the CSS has
* scoped (hashed) class names such as `_button_1x2y3_1` while the content
* refers to the local name, e.g. `styles.button`, and the options name the
* local name too, e.g. `safelist: ['button']`. postcss-modules gives the
* mapping in its export message: `{ button: "_button_1x2y3_1" }`. A value can
* hold several space-separated names when the class composes other classes:
* the first one is the scoped name of the class, and all of them are kept
* along with it. A blocklisted local name is not considered as used, and its
* scoped name is blocklisted. IDs, e.g. `#main`, are scoped and exported the
* same way.
*
* postcss-modules also exports the values defined with `@value`, e.g.
* `{ brand: "red" }`: a token whose names are no class or ID of the root is
* skipped. So is a token whose value names a class, e.g. a global class
* `:global(.red)`, and that is a value of the source: same name (or a
* `localsConvention` form of it) and same value, or any value for an
* imported one. A token whose first name was generated by postcss-modules
* (it is not in the source) is a class or an ID.
*
* @param root - PostCSS root, after postcss-modules
* @param messages - messages of the PostCSS result, `result.messages`
* @param selectors - selectors found in the content
* @param options - safelist and blocklist of the options
* @returns the scoped names to consider as used, safelist and blocklist
*/
function getCSSModulesClassNames(root, messages, selectors, { safelist, blocklist }) {
var _a, _b;
const classNames = {
used: [],
usedIds: [],
safelist: { standard: [], deep: [], greedy: [] },
blocklist: [],
};
const exportMessages = messages.filter(isExportMessage);
if (exportMessages.length === 0)
return classNames;
const rootNames = getRootNames(root);
const sourceCSS = (_b = (_a = root.source) === null || _a === void 0 ? void 0 : _a.input.css) !== null && _b !== void 0 ? _b : "";
const valueDefinitions = getValueDefinitions(sourceCSS);
// the names written in the source, read once rather than searching the
// source for each token
let sourceWords;
const getSourceWords = () => (sourceWords !== null && sourceWords !== void 0 ? sourceWords : (sourceWords = getSourceWordsOf(sourceCSS)));
for (const message of exportMessages) {
for (const [localName, value] of Object.entries(message.exportTokens)) {
if (typeof value !== "string")
continue;
const scopedNames = value.split(/\s+/).filter(Boolean);
// the first name may be gone if its rule only composes others
const isClass = scopedNames.some((scopedName) => rootNames.classes.has(scopedName));
// an ID composes nothing
const isId = scopedNames.length === 1 && rootNames.ids.has(value.trim());
if (!isClass && !isId)
continue;
// a name generated by postcss-modules, e.g. `_button_1x2y3_1`, is not
// in the source, unlike a value, or a global class named by a value
const isGeneratedName = (rootNames.classes.has(scopedNames[0]) ||
rootNames.ids.has(scopedNames[0])) &&
!getSourceWords().has(scopedNames[0]);
if (!isGeneratedName &&
isValueToken(valueDefinitions, localName, value)) {
continue;
}
// like in PurgeCSS, the safelists take precedence over the blocklist
const [scopedName, ...composedNames] = scopedNames;
let isSafelisted = false;
for (const kind of ["standard", "deep", "greedy"]) {
if (matchesAnyPattern(safelist[kind], localName)) {
classNames.safelist[kind].push(scopedName);
isSafelisted = true;
}
}
if (isSafelisted) {
// the classes it composes are kept as they are used with it
classNames.safelist.standard.push(...composedNames);
continue;
}
if (matchesAnyPattern(blocklist, localName)) {
classNames.blocklist.push(scopedName);
continue;
}
if (isClass && selectors.hasClass(localName)) {
classNames.used.push(...scopedNames);
}
if (isId && selectors.hasId(localName)) {
classNames.usedIds.push(scopedName);
}
}
}
return classNames;
}
/**
* Check if a path is a directory or a path inside it
*
* @param filePath - absolute path
* @param dir - absolute path of the directory
*/
function isInside(filePath, dir) {
const relativePath = path.relative(dir, filePath);
return (relativePath === "" ||
(relativePath.split(path.sep)[0] !== ".." && !path.isAbsolute(relativePath)));
}
/**
* Normalize the slashes of a glob: repeated slashes are collapsed (except
* leading ones, for UNC paths) and the `.` segments are removed, e.g.
* `.//src//**\/*.js` gives `src/**\/*.js`. The escapes are kept.
*
* @param pattern - glob, or base directory of a glob
* @returns the normalized pattern, an empty string for `.`
*/
function normalizePattern(pattern) {
return pattern
.replace(/(?<!^)\/{2,}/g, "/")
.split("/")
.filter((segment) => segment !== ".")
.join("/");
}
/**
* Number of segments of the base directory of a glob, e.g. 0 for `.`, 1 for
* `/` and 2 for `./src/components`
*
* @param base - static base directory of a glob, as given by fast-glob
*/
function countBaseSegments(base) {
const normalizedBase = normalizePattern(base);
if (normalizedBase === "")
return 0;
// a trailing slash, as in the base `/` of `/*.html`, is no segment
return normalizedBase.replace(/\/+$/, "").split("/").length;
}
/**
* The part of a pattern after its base directory, e.g. `**\/*.js` for
* `./src/**\/*.js` and the base `./src`
*
* @param pattern - glob
* @param base - static base directory of the glob, as given by fast-glob
* @returns the rest of the pattern, or `undefined` if it cannot be split
* this way, e.g. when the leading segments of the pattern contain braces
*/
function getRestOfPattern(pattern, base) {
// the base is unescaped, so count its segments rather than its characters
const segments = normalizePattern(pattern).split("/");
const baseSegmentsCount = countBaseSegments(base);
const baseSegments = segments.slice(0, baseSegmentsCount);
if (baseSegments.some((segment) => /[{}]/.test(segment)))
return undefined;
// the leading segments, unescaped, must be the base
const unescapedBase = baseSegments.join("/").replace(/\\(.)/g, "$1");
if (path.resolve(unescapedBase === "" ? "." : unescapedBase) !==
path.resolve(base)) {
return undefined;
}
const glob = segments.slice(baseSegmentsCount).join("/");
// never an absolute glob: the bundler would search the whole file system
if (glob === "" || glob.startsWith("/") || !fastGlob.isDynamicPattern(glob)) {
return undefined;
}
return glob;
}
/**
* Split a glob in the static directory it starts from and the pattern that
* remains, relative to that directory.
*
* The braces in the directory part are expanded, e.g. `{src,lib}/**\/*.js`
* gives a directory `src` and a directory `lib` rather than the whole working
* directory. The braces in the rest of the pattern are kept.
*
* @param pattern - glob, as given in the `content` option
* @returns the parts of the glob, with absolute paths
*/
function splitGlob(pattern) {
const normalizedPattern = normalizePattern(pattern);
const tasks = fastGlob.generateTasks([normalizedPattern]);
// a single base: the original pattern can be kept as is after the base,
// braces included, as long as the base itself has none
const singleTask = tasks.length === 1 ? tasks[0] : undefined;
if (singleTask === null || singleTask === void 0 ? void 0 : singleTask.dynamic) {
const glob = getRestOfPattern(normalizedPattern, singleTask.base);
if (glob !== undefined) {
return [{ type: "glob", dir: path.resolve(singleTask.base), glob }];
}
}
// the braces were expanded: one part per expanded pattern
const parts = [];
for (const task of tasks) {
for (const expandedPattern of task.positive) {
if (!fastGlob.isDynamicPattern(expandedPattern)) {
parts.push({ type: "file", file: path.resolve(expandedPattern) });
continue;
}
const glob = getRestOfPattern(expandedPattern, task.base);
const dir = path.resolve(task.base);
parts.push(glob === undefined
? { type: "files", dir }
: { type: "glob", dir, glob });
}
}
return parts;
}
/**
* Lock files that Next.js looks for to infer the root of the workspace
*/
const LOCK_FILES = [
"pnpm-lock.yaml",
"package-lock.json",
"yarn.lock",
"bun.lock",
"bun.lockb",
];
/**
* Files that declare the root of a workspace, for pnpm and Lerna
*/
const WORKSPACE_MARKERS = ["pnpm-workspace.yaml", "lerna.json"];
/**
* Real path of a path, the path itself if it cannot be resolved
*
* @param filePath - path to resolve
*/
function toRealPath(filePath) {
try {
return fs.realpathSync.native(filePath);
}
catch {
return filePath;
}
}
/**
* Check if a directory declares the root of a workspace: a workspace marker
* file, or a `package.json` with a `workspaces` field (npm, Yarn, Bun)
*
* @param dir - absolute path of the directory
*/
function isWorkspaceRoot(dir) {
if (WORKSPACE_MARKERS.some((name) => fs.existsSync(path.join(dir, name)))) {
return true;
}
try {
const packageJson = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
return (packageJson === null || packageJson === void 0 ? void 0 : packageJson.workspaces) != null;
}
catch {
return false;
}
}
/**
* Directory of the git repository or worktree that contains a directory.
* Unlike Next.js, the `.git` file of a submodule stops the search too: the
* root found can only be narrower than the one of Next.js, never wider.
*
* @param cwd - absolute path of the directory
*/
function findGitRoot(cwd) {
for (let dir = cwd;; dir = path.dirname(dir)) {
if (fs.existsSync(path.join(dir, ".git")))
return toRealPath(dir);
if (path.dirname(dir) === dir)
return undefined;
}
}
/**
* Infer the root directory of Turbopack, as Next.js does when neither
* `turbopack.root` nor `outputFileTracingRoot` is set: the outermost
* directory with a workspace marker (`pnpm-workspace.yaml`, `lerna.json`,
* `package.json` with `workspaces`) or, if there is none, with a lock file,
* within the git repository and below the home directory. Turbopack stops
* with an error for a path outside this root.
*
* @param cwd - absolute path of the project, the working directory
* @returns the absolute path of the root, `cwd` if none is found
*/
function inferTurbopackRoot(cwd) {
const fromEnv = process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT;
if (fromEnv)
return path.resolve(fromEnv);
const workspaceRoots = [];
const lockFileRoots = [];
for (let dir = cwd;; dir = path.dirname(dir)) {
if (isWorkspaceRoot(dir))
workspaceRoots.push(dir);
if (LOCK_FILES.some((name) => fs.existsSync(path.join(dir, name)))) {
lockFileRoots.push(dir);
}
if (path.dirname(dir) === dir)
break;
}
// a workspace marker takes precedence over the lock files
const candidates = workspaceRoots.length > 0 ? workspaceRoots : lockFileRoots;
const gitRoot = findGitRoot(cwd);
let homeDir;
try {
homeDir = toRealPath(os.homedir()) || undefined;
}
catch {
homeDir = undefined;
}
let root = cwd;
// from the innermost to the outermost candidate
for (const dir of candidates) {
if (dir !== cwd) {
const realDir = toRealPath(dir);
// never above the git repository, nor the home directory or above it
if (gitRoot && realDir !== gitRoot && isInside(gitRoot, realDir))
break;
if (homeDir && isInside(homeDir, realDir))
break;
}
root = dir;
}
return root;
}
/**
* Turbopack roots inferred, by working directory
*/
const turbopackRoots = new Map();
/**
* Root directory of the bundler: the paths outside it get no message.
* Under Turbopack, which stops with an error for a path outside its root,
* the root Next.js infers when the option `root` is not set. Otherwise, no
* limit.
*
* @param cwd - absolute path of the working directory
* @param root - `root` option
* @returns the absolute path of the root, `undefined` for no limit
*/
function getBundlerRoot(cwd, root) {
if (root !== undefined)
return path.resolve(cwd, root);
// Turbopack sets the environment variable TURBOPACK, to "1" or "auto"
if (!process.env.TURBOPACK)
return undefined;
let turbopackRoot = turbopackRoots.get(cwd);
if (turbopackRoot === undefined) {
turbopackRoot = inferTurbopackRoot(cwd);
turbopackRoots.set(cwd, turbopackRoot);
}
return turbopackRoot;
}
/**
* Check if a glob uses the extended glob syntax, e.g. `*.@(js|ts)`, which
* the glob engine of Turbopack does not support
*
* @param glob - glob
*/
function hasExtglob(glob) {
return /(?<!\\)[@+!?*]\(/.test(glob);
}
/**
* Stats of a path, `undefined` if it does not exist
*
* @param filePath - path to check
*/
async function statOrUndefined(filePath) {
try {
return await promises.stat(filePath);
}
catch {
return undefined;
}
}
/**
* Get the dependencies of the content, following the PostCSS guidelines for
* plugins
* (https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies),
* so that the bundlers and dev servers (Vite, webpack and Rspack with
* postcss-loader, Turbopack, Parcel) run the plugin again when a content file
* changes or is removed. webpack, Rspack, Turbopack and Parcel also run it
* again when a file matching a content glob is added; Vite turns a glob into
* the files that match it when PostCSS runs, so it picks up a new file at the
* next run of PostCSS for the CSS file only, e.g. once a file that imports
* the new one is edited:
*
* - an existing file gives a `dependency` message with its absolute path;
* - a glob gives a `dir-dependency` message with the absolute path of the
* static directory it starts from and the rest of the pattern;
* - a file that does not exist (yet) gives a `missing-dependency` message.
*
* A glob that starts from the working directory or one of its parents, e.g.
* `./*.html`, gives a `dependency` message for each content file read in its
* directory instead: postcss-loader makes webpack and Rspack watch the whole
* directory of a `dir-dependency`, whatever its glob, and the output of the
* build written there would build it again and again.
*
* The paths outside the root of the bundler are left out: the `root` option,
* or under Turbopack (Next.js), which stops with an error for a path outside
* its root, the root Next.js infers from the workspace markers and lock files.
* Turbopack does not support the extended glob syntax, e.g. `*.@(js|ts)`: a
* glob that uses it gives the directory it starts from, with the glob `**`.
*
* Paths and globs are resolved from the current working directory, like
* PurgeCSS does. Negated patterns and raw content are skipped.
*
* @param content - content option of PurgeCSS
* @param options - options of the dependency messages
* @returns the dependencies of the content
*/
async function getContentDependencies(content, { root } = {}) {
const cwd = process.cwd();
const bundlerRoot = getBundlerRoot(cwd, root);
const isTurbopack = Boolean(process.env.TURBOPACK);
const entries = content.filter((entry) => typeof entry === "string" && entry !== "" && !entry.startsWith("!"));
const stats = await Promise.all(entries.map((entry) => statOrUndefined(path.resolve(entry))));
const parts = [];
entries.forEach((entry, index) => {
const entryStats = stats[index];
// checked first, like PurgeCSS does: an existing path is not a glob
if (entryStats) {
// a directory is not a content file: its files are not read
if (entryStats.isFile()) {
parts.push({ type: "file", file: path.resolve(entry) });
}
return;
}
if (fastGlob.isDynamicPattern(entry)) {
for (const part of splitGlob(entry)) {
if (part.type !== "glob") {
parts.push(part);
}
else if (isInside(cwd, part.dir)) {
// the working directory or a parent of it: its files, see above
parts.push({ type: "files", dir: part.dir });
}
else if (isTurbopack && hasExtglob(part.glob)) {
// wider, but Turbopack would never match the files
parts.push({ type: "glob", dir: part.dir, glob: "**" });
}
else {
parts.push(part);
}
}
return;
}
parts.push({ type: "file", file: path.resolve(entry) });
});
// static paths from brace expansion, e.g. `{src/**/*.js,index.html}`
const staticFiles = parts.flatMap((part) => part.type === "file" ? [part.file] : []);
const existingFiles = new Set();
await Promise.all(staticFiles.map(async (file) => {
var _a;
if ((_a = (await statOrUndefined(file))) === null || _a === void 0 ? void 0 : _a.isFile())
existingFiles.add(file);
}));
const filesDirs = parts.flatMap((part) => part.type === "files" ? [part.dir] : []);
const isAccepted = bundlerRoot !== undefined
? (filePath) => isInside(filePath, bundlerRoot)
: () => true;
return {
getMessages(parent, contentFiles) {
const messages = new Map();
const add = (key, message) => {
if (!messages.has(key))
messages.set(key, message);
};
const addFile = (file) => {
const type = existingFiles.has(file)
? "dependency"
: "missing-dependency";
add(`file:${file}`, {
type,
plugin: "postcss-purgecss",
file,
parent,
});
};
for (const part of parts) {
if (part.type === "file") {
if (isAccepted(part.file))
addFile(part.file);
}
else if (part.type === "glob" && isAccepted(part.dir)) {
add(`dir:${part.dir}\0${part.glob}`, {
type: "dir-dependency",
plugin: "postcss-purgecss",
dir: part.dir,
glob: part.glob,
parent,
});
}
}
if (filesDirs.length > 0) {
for (const file of [...contentFiles].sort()) {
if (isAccepted(file) &&
filesDirs.some((dir) => isInside(file, dir))) {
existingFiles.add(file);
addFile(file);
}
}
}
return [...messages.values()];
},
};
}
/**
* PostCSS Plugin for PurgeCSS
*
* Most bundlers and frameworks to build websites are using PostCSS.
* The easiest way to configure PurgeCSS is with its PostCSS plugin.
*
* @packageDocumentation
*/
const PLUGIN_NAME = "postcss-purgecss";
/**
* Execute PurgeCSS process on the postCSS root node
*
* @param opts - PurgeCSS options
* @param root - root node of postCSS
* @param helpers - postCSS helpers
*/
async function purgeCSS(opts, root, { result }) {
const purgeCSS = new PurgeCSS();
let configFileOptions;
const t = path.resolve(process.cwd(), "purgecss.config.js");
// the config file is optional, but an existing one that fails to load
// (e.g. a syntax error) is reported instead of being silently ignored
if (fs.existsSync(t)) {
try {
const importedConfig = await import(pathToFileURL(t).href);
// Handle both ES modules (direct export) and CommonJS (default export)
configFileOptions =
importedConfig.default && typeof importedConfig.default === "object"
? importedConfig.default
: importedConfig;
}
catch (err) {
throw new Error(`Error loading the config file ${t}: ${err}`, {
cause: err,
});
}
}
// the safelists of the config file and of the plugin options add up
const configFileSafelist = standardizeSafelist(configFileOptions === null || configFileOptions === void 0 ? void 0 : configFileOptions.safelist);
const pluginSafelist = standardizeSafelist(opts === null || opts === void 0 ? void 0 : opts.safelist);
const options = {
...defaultOptions,
...configFileOptions,
...opts,
safelist: {
standard: [...configFileSafelist.standard, ...pluginSafelist.standard],
deep: [...configFileSafelist.deep, ...pluginSafelist.deep],
greedy: [...configFileSafelist.greedy, ...pluginSafelist.greedy],
keyframes: [...configFileSafelist.keyframes, ...pluginSafelist.keyframes],
variables: [...configFileSafelist.variables, ...pluginSafelist.variables],
},
};
if (opts && typeof opts.contentFunction === "function") {
options.content = opts.contentFunction((root.source && root.source.input.file) || "");
}
purgeCSS.options = options;
if (options.variables) {
purgeCSS.variablesStructure.safelist = options.safelist.variables || [];
}
const { content, extractors } = options;
// the selectors of the content files are shared with the other runs,
// unless the option contentCache is false
const contentCache = createRunContentCache(options.contentCache !== false);
purgeCSS.contentCache = contentCache;
// found while the content is extracted, the messages are added once the
// content files are read. Bundlers only read the messages of a successful
// run: if the extraction fails, the error is reported alone.
const dependencies = options.dependencies !== false && options.dependencies !== null
? getContentDependencies(content, typeof options.dependencies === "object" ? options.dependencies : {})
: undefined;
// still awaited below: only avoids an unhandled rejection if the
// extraction fails first
dependencies === null || dependencies === void 0 ? void 0 : dependencies.catch(() => undefined);
await purgeContent(purgeCSS, root, result, content, extractors);
if (dependencies) {
// let the dev servers run the plugin again when the content changes
result.messages.push(...(await dependencies).getMessages(result.opts.from, contentCache.files));
}
if (options.contentCache !== false) {
const contentKey = JSON.stringify([
process.cwd(),
options.skippedContentGlobs,
content.filter((entry) => typeof entry === "string"),
]);
pruneSharedContentCache(contentKey, contentCache.files);
}
}
/**
* Remove the unused CSS of the postCSS root node
*
* @param purgeCSS - PurgeCSS instance with its options
* @param root - root node of postCSS
* @param result - result of postCSS
* @param content - content option of PurgeCSS
* @param extractors - extractors option of PurgeCSS
*/
async function purgeContent(purgeCSS, root, result, content, extractors = []) {
const fileFormatContents = content.filter((o) => typeof o === "string");
const rawFormatContents = content.filter((o) => typeof o === "object");
const cssFileSelectors = await purgeCSS.extractSelectorsFromFiles(fileFormatContents, extractors);
const cssRawSelectors = await purgeCSS.extractSelectorsFromString(rawFormatContents, extractors);
const selectors = mergeExtractorSelectors(cssFileSelectors, cssRawSelectors);
// CSS modules scoped by an earlier plugin (postcss-modules in Vite): the
// content and the options use the local names of the classes, not their
// scoped names
const cssModulesClassNames = getCSSModulesClassNames(root, result.messages, selectors, purgeCSS.options);
if (cssModulesClassNames.used.length > 0 ||
cssModulesClassNames.usedIds.length > 0) {
selectors.merge({
attributes: { names: [], values: [] },
classes: cssModulesClassNames.used,
ids: cssModulesClassNames.usedIds,
tags: [],
undetermined: [],
});
}
const { safelist, blocklist } = purgeCSS.options;
purgeCSS.options = {
...purgeCSS.options,
safelist: {
...safelist,
standard: [
...safelist.standard,
...cssModulesClassNames.safelist.standard,
],
deep: [...safelist.deep, ...cssModulesClassNames.safelist.deep],
greedy: [...safelist.greedy, ...cssModulesClassNames.safelist.greedy],
},
blocklist: [...blocklist, ...cssModulesClassNames.blocklist],
};
//purge unused selectors
purgeCSS.walkThroughCSS(root, selectors);
if (purgeCSS.options.fontFace)
purgeCSS.removeUnusedFontFaces();
if (purgeCSS.options.keyframes)
purgeCSS.removeUnusedKeyframes();
if (purgeCSS.options.variables)
purgeCSS.removeUnusedCSSVariables();
if (purgeCSS.options.rejected && purgeCSS.selectorsRemoved.size > 0) {
result.messages.push({
type: "purgecss",
plugin: "postcss-purgecss",
text: `purging ${purgeCSS.selectorsRemoved.size} selectors:
${Array.from(purgeCSS.selectorsRemoved)
.map((selector) => selector.trim())
.join("\n ")}`,
});
purgeCSS.selectorsRemoved.clear();
}
}
/**
* PostCSS Plugin for PurgeCSS
*
* @param opts - PurgeCSS Options
* @returns the postCSS plugin
*
* @public
*/
const purgeCSSPlugin = function (opts) {
if (typeof opts === "undefined")
throw new Error("PurgeCSS plugin does not have the correct options");
return {
postcssPlugin: PLUGIN_NAME,
OnceExit(root, helpers) {
return purgeCSS(opts, root, helpers);
},
};
};
purgeCSSPlugin.postcss = true;
export { purgeCSSPlugin as default };