import { resolve, posix, isAbsolute } from 'path'; import pm from 'picomatch'; import type { CreateFilter } from '../types'; import ensureArray from './utils/ensureArray'; import normalizePath from './normalizePath'; function getMatcherString(id: string, resolutionBase: string | false | null | undefined) { if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) { return normalizePath(id); } // resolve('') is valid and will default to process.cwd() const basePath = normalizePath(resolve(resolutionBase || '')) // escape all possible (posix + win) path characters that might interfere with regex .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); // Note that we use posix.join because: // 1. the basePath has been normalized to use / // 2. the incoming glob (id) matcher, also uses / // otherwise Node will force backslash (\) on windows return posix.join(basePath, normalizePath(id)); } const createFilter: CreateFilter = function createFilter(include?, exclude?, options?) { const resolutionBase = options && options.resolve; const getMatcher = (id: string | RegExp) => { if (id instanceof RegExp) { return id; } // Compiling a pattern costs far more than matching against it, so only recompile when the cwd it resolves against changes const compile = () => pm(getMatcherString(id, resolutionBase), { dot: true }); // These patterns never resolve against the cwd, so there is no need to read or track it if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) { return { test: compile() }; } let compiledCwd = process.cwd(); let fn = compile(); return { test: (what: string) => { const cwd = process.cwd(); if (cwd !== compiledCwd) { compiledCwd = cwd; fn = compile(); } return fn(what); } }; }; const includeMatchers = ensureArray(include).map(getMatcher); const excludeMatchers = ensureArray(exclude).map(getMatcher); if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === 'string' && !id.includes('\0'); return function result(id: string | unknown): boolean { if (typeof id !== 'string') return false; if (id.includes('\0')) return false; const pathId = normalizePath(id); for (let i = 0; i < excludeMatchers.length; ++i) { const matcher = excludeMatchers[i]; if (matcher instanceof RegExp) { matcher.lastIndex = 0; } if (matcher.test(pathId)) return false; } for (let i = 0; i < includeMatchers.length; ++i) { const matcher = includeMatchers[i]; if (matcher instanceof RegExp) { matcher.lastIndex = 0; } if (matcher.test(pathId)) return true; } return !includeMatchers.length; }; }; export { createFilter as default };