import { dirname } from 'node:path/posix'; /** * Writes a path as a Vite Task input glob that matches only that path. Vite Task matches inputs * with wax globs, where a backslash escapes these special characters and escaping any other * character is an error. A path with a backslash cannot be written, so it gets no glob. */ export function globLiteral(path: string): string | undefined { return path.includes('\\') ? undefined : path.replaceAll(/[?*$:<>()[\]{},]/g, String.raw`\$&`); } /** * Returns, for the own files of a cached test task, the negative globs that leave the other test * files out of its inputs. A directory without own files takes one `*.test.ts` glob, which stops * at a slash. A directory with them names its other files one by one, because a negative glob * would also drop the own files and no later pattern restores them. A file without a glob stays * an input: it may rerun the task needlessly, but never hides a change. */ export function otherTestFileExclusions( testFiles: ReadonlyArray, ): (ownFiles: ReadonlyArray) => Array { const filesByDirectory = new Map>(); for (const file of testFiles) { const directory = dirname(file); filesByDirectory.set(directory, [...(filesByDirectory.get(directory) ?? []), file]); } return (ownFiles) => { const own = new Set(ownFiles); const ownDirectories = new Set(ownFiles.map((file) => dirname(file))); return [...filesByDirectory].flatMap(([directory, files]) => { if (ownDirectories.has(directory)) { return files.filter((file) => !own.has(file)).flatMap((file) => negate(globLiteral(file))); } const glob = globLiteral(directory); return negate(glob === undefined ? undefined : `${glob}/*.test.ts`); }); }; } function negate(glob: string | undefined): Array { return glob === undefined ? [] : [`!${glob}`]; }