Skip to main content

supercov_engine/
project_discovery.rs

1//! Runner/build/project discovery for zero-configuration JavaScript suites.
2
3use std::{
4    collections::{BTreeMap, BTreeSet, HashMap},
5    fs, io,
6    path::{Path, PathBuf},
7};
8
9use oxc_allocator::Allocator;
10use oxc_ast::ast::{
11    Argument, ArrayExpressionElement, CallExpression, Expression, ImportDeclarationSpecifier,
12    ImportExpression, ImportOrExportKind, Program, Statement,
13};
14use oxc_ast_visit::{Visit, walk};
15use oxc_parser::Parser;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use crate::source_discovery::{
20    DiscoveredSourceScope, SourceDiscoveryError, SourceLimitation, SourceScope,
21    discover_source_scope,
22};
23
24const PLAYWRIGHT_CONFIGS: &[&str] = &[
25    "playwright.config.ts",
26    "playwright.config.mts",
27    "playwright.config.js",
28    "playwright.config.mjs",
29    "playwright.config.cts",
30    "playwright.config.cjs",
31];
32const VITEST_CONFIGS: &[&str] = &[
33    "vitest.config.ts",
34    "vitest.config.mts",
35    "vitest.config.js",
36    "vitest.config.mjs",
37    "vitest.config.cts",
38    "vitest.config.cjs",
39    "vite.config.ts",
40    "vite.config.mts",
41    "vite.config.js",
42    "vite.config.mjs",
43];
44const JEST_CONFIGS: &[&str] = &[
45    "jest.config.ts",
46    "jest.config.mts",
47    "jest.config.js",
48    "jest.config.mjs",
49    "jest.config.cts",
50    "jest.config.cjs",
51];
52const TEST_DIRECTORIES: &[&str] = &["test", "tests", "e2e", "spec", "specs"];
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase", deny_unknown_fields)]
56pub struct CoverageProject {
57    pub root: PathBuf,
58    pub source_roots: Vec<String>,
59    pub source_files: Vec<String>,
60    pub source_scope: SourceScope,
61    pub source_limitations: Vec<SourceLimitation>,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub playwright_config: Option<PathBuf>,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub vitest_config: Option<PathBuf>,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub jest_config: Option<PathBuf>,
68    pub uses_jest: bool,
69    /// The tests bundle sources for a browser through a runner Supercov has
70    /// no adapter for -- karma, testem, airtap, zuul, mochify -- so each
71    /// script-style file carries the runtime the page otherwise lacks.
72    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
73    pub browser_runner: bool,
74    pub playwright_module: String,
75    pub playwright_test_export: String,
76    pub playwright_exports: Vec<String>,
77    /// The project's build, when the tests may need its output and the
78    /// command does not run it: what a failed run names. Supercov runs the
79    /// command it is given and no build of its own.
80    #[serde(default, skip_serializing_if = "Vec::is_empty")]
81    pub unrun_build: Vec<String>,
82}
83
84#[derive(Debug)]
85pub enum ProjectDiscoveryError {
86    Source(SourceDiscoveryError),
87    Io { path: PathBuf, source: io::Error },
88    NoSourceFiles,
89}
90
91impl From<SourceDiscoveryError> for ProjectDiscoveryError {
92    fn from(value: SourceDiscoveryError) -> Self {
93        Self::Source(value)
94    }
95}
96
97impl std::fmt::Display for ProjectDiscoveryError {
98    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        match self {
100            Self::Source(error) => write!(formatter, "{error}"),
101            Self::Io { path, source } => write!(formatter, "{}: {source}", path.display()),
102            Self::NoSourceFiles => write!(
103                formatter,
104                "No application source files were discovered. If your sources live somewhere unusual, set SUPERCOV_SOURCE_ROOTS=src,app. Alternatively, Supercov may not support your project layout or test framework yet — if so, please open an issue or PR: https://github.com/supercorp-ai/supercov"
105            ),
106        }
107    }
108}
109
110impl std::error::Error for ProjectDiscoveryError {}
111
112fn package_json(root: &Path) -> Value {
113    fs::read(root.join("package.json"))
114        .ok()
115        .and_then(|contents| serde_json::from_slice(&contents).ok())
116        .unwrap_or(Value::Null)
117}
118
119fn script<'a>(manifest: &'a Value, name: &str) -> Option<&'a str> {
120    manifest.get("scripts")?.get(name)?.as_str()
121}
122
123fn regular_file(path: &Path) -> bool {
124    fs::symlink_metadata(path)
125        .map(|metadata| metadata.file_type().is_file())
126        .unwrap_or(false)
127}
128
129fn source_file(path: &Path) -> bool {
130    let name = path
131        .file_name()
132        .and_then(|name| name.to_str())
133        .unwrap_or("");
134    let lower = name.to_ascii_lowercase();
135    [
136        ".js", ".jsx", ".ts", ".tsx", ".cjs", ".cjsx", ".cts", ".ctsx", ".mjs", ".mjsx", ".mts",
137        ".mtsx",
138    ]
139    .iter()
140    .any(|extension| lower.ends_with(extension))
141}
142
143fn read_directory(path: &Path) -> Result<Vec<fs::DirEntry>, ProjectDiscoveryError> {
144    let mut entries = fs::read_dir(path)
145        .map_err(|source| ProjectDiscoveryError::Io {
146            path: path.to_owned(),
147            source,
148        })?
149        .collect::<Result<Vec<_>, _>>()
150        .map_err(|source| ProjectDiscoveryError::Io {
151            path: path.to_owned(),
152            source,
153        })?;
154    entries.sort_by_key(fs::DirEntry::file_name);
155    Ok(entries)
156}
157
158fn parse_program<'a>(
159    allocator: &'a Allocator,
160    path: &Path,
161    source: &'a str,
162) -> Option<Program<'a>> {
163    let source_type = crate::js_instrumenter::project_source_type(path).ok()?;
164    let parsed = Parser::new(allocator, source, source_type).parse();
165    parsed.errors.is_empty().then_some(parsed.program)
166}
167
168#[derive(Debug, Clone)]
169struct TestApiCandidate {
170    module: String,
171    score: usize,
172    test_export: Option<String>,
173    exports: Vec<String>,
174}
175
176fn imported_test_apis(path: &Path, source: &str) -> Vec<TestApiCandidate> {
177    let allocator = Allocator::default();
178    let Some(program) = parse_program(&allocator, path, source) else {
179        return Vec::new();
180    };
181    // Aggregate per module across the whole file: a facade's helpers are
182    // often imported in their own statement (`import { createTestProduct }
183    // from "@acme/fixtures"`), and those names must reach the generated shim
184    // even though that statement alone carries no test-API signal.
185    let mut by_module = BTreeMap::<String, TestApiCandidate>::new();
186    for statement in &program.body {
187        let Statement::ImportDeclaration(declaration) = statement else {
188            continue;
189        };
190        if declaration.import_kind == ImportOrExportKind::Type {
191            continue;
192        }
193        let module = declaration.source.value.to_string();
194        let candidate = by_module
195            .entry(module.clone())
196            .or_insert_with(|| TestApiCandidate {
197                module,
198                score: 0,
199                test_export: None,
200                exports: Vec::new(),
201            });
202        for specifier in declaration.specifiers.iter().flatten() {
203            let ImportDeclarationSpecifier::ImportSpecifier(specifier) = specifier else {
204                continue;
205            };
206            if specifier.import_kind == ImportOrExportKind::Type {
207                continue;
208            }
209            let imported = specifier.imported.name().to_string();
210            let local = specifier.local.name.as_str();
211            candidate.exports.push(imported.clone());
212            if local == "test" {
213                candidate.score += 20;
214                candidate.test_export = Some(imported.clone());
215            } else if imported.to_ascii_lowercase().ends_with("test") {
216                candidate.score += 8;
217            }
218            if local == "expect" || imported == "expect" {
219                candidate.score += 10;
220            }
221        }
222    }
223    by_module
224        .into_values()
225        .filter(|candidate| candidate.score > 0)
226        .map(|mut candidate| {
227            if candidate.module == "@playwright/test" {
228                candidate.score += 100;
229            } else if candidate.module.to_ascii_lowercase().contains("playwright") {
230                candidate.score += 5;
231            }
232            candidate
233        })
234        .collect()
235}
236
237fn test_api_candidates(directory: &Path, output: &mut Vec<TestApiCandidate>) {
238    let Ok(entries) = read_directory(directory) else {
239        return;
240    };
241    for entry in entries {
242        let name = entry.file_name();
243        let Some(name) = name.to_str() else { continue };
244        if name == "node_modules" || name == "results" || name.starts_with('.') {
245            continue;
246        }
247        let path = entry.path();
248        let Ok(file_type) = entry.file_type() else {
249            continue;
250        };
251        if file_type.is_symlink() {
252            continue;
253        }
254        if file_type.is_dir() {
255            test_api_candidates(&path, output);
256        } else if file_type.is_file()
257            && source_file(&path)
258            && let Ok(source) = fs::read_to_string(&path)
259        {
260            output.extend(imported_test_apis(&path, &source));
261        }
262    }
263}
264
265#[derive(Debug, Clone)]
266struct PlaywrightAdapter {
267    module: String,
268    test_export: String,
269    exports: Vec<String>,
270}
271
272fn discover_playwright_adapter(root: &Path) -> PlaywrightAdapter {
273    let mut candidates = Vec::new();
274    for directory in TEST_DIRECTORIES {
275        test_api_candidates(&root.join(directory), &mut candidates);
276    }
277    let mut scores = HashMap::<String, usize>::new();
278    for candidate in &candidates {
279        *scores.entry(candidate.module.clone()).or_default() += candidate.score;
280    }
281    let module = scores
282        .into_iter()
283        .min_by(|(left_module, left_score), (right_module, right_score)| {
284            right_score
285                .cmp(left_score)
286                .then_with(|| left_module.cmp(right_module))
287        })
288        .map(|(module, _)| module)
289        .unwrap_or_else(|| "@playwright/test".into());
290    let matching = candidates
291        .iter()
292        .filter(|candidate| candidate.module == module)
293        .collect::<Vec<_>>();
294    let test_export = matching
295        .iter()
296        .filter_map(|candidate| {
297            candidate
298                .test_export
299                .as_ref()
300                .map(|export| (candidate.score, export))
301        })
302        .max_by_key(|(score, _)| *score)
303        .map(|(_, export)| export.clone())
304        .unwrap_or_else(|| "test".into());
305    let exports = matching
306        .iter()
307        .flat_map(|candidate| candidate.exports.iter().cloned())
308        .collect::<BTreeSet<_>>()
309        .into_iter()
310        .collect();
311    PlaywrightAdapter {
312        module,
313        test_export,
314        exports,
315    }
316}
317
318fn nested_playwright_configs(root: &Path) -> Vec<PathBuf> {
319    fn visit(directory: &Path, depth: usize, found: &mut Vec<PathBuf>) {
320        if depth > 4 {
321            return;
322        }
323        let Ok(entries) = read_directory(directory) else {
324            return;
325        };
326        for entry in entries {
327            let name = entry.file_name();
328            let Some(name) = name.to_str() else { continue };
329            if name.starts_with('.') || name == "node_modules" {
330                continue;
331            }
332            let path = entry.path();
333            let Ok(file_type) = entry.file_type() else {
334                continue;
335            };
336            if file_type.is_symlink() {
337                continue;
338            }
339            if file_type.is_dir() {
340                visit(&path, depth + 1, found);
341            } else if file_type.is_file() && playwright_config_name(name) {
342                found.push(path);
343            }
344        }
345    }
346
347    let mut found = Vec::new();
348    for directory in ["test", "tests", "e2e"] {
349        visit(&root.join(directory), 0, &mut found);
350    }
351    found.sort();
352    found
353}
354
355fn playwright_config_name(name: &str) -> bool {
356    let lower = name.to_ascii_lowercase();
357    if !lower.starts_with("playwright") || !lower.contains(".config.") {
358        return false;
359    }
360    source_file(Path::new(name))
361        && lower[..lower.find(".config.").unwrap_or(0)]
362            .chars()
363            .all(|character| {
364                character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_')
365            })
366}
367
368pub fn expanded_command(root: &Path, command: &[String]) -> String {
369    let manifest = package_json(root);
370    let executable = command
371        .first()
372        .and_then(|value| Path::new(value).file_name())
373        .and_then(|value| value.to_str())
374        .unwrap_or("")
375        .trim_end_matches(".cmd")
376        .trim_end_matches(".exe")
377        .to_ascii_lowercase();
378    let run_index = command.iter().position(|argument| argument == "run");
379    let script_name = run_index
380        .and_then(|index| command.get(index + 1))
381        .or_else(|| {
382            (["npm", "pnpm", "yarn", "bun"].contains(&executable.as_str()) && run_index.is_none())
383                .then(|| command.get(1))
384                .flatten()
385        });
386    let joined = command.join(" ");
387    if ["npm", "pnpm", "yarn", "bun"].contains(&executable.as_str())
388        && let Some(script_name) = script_name
389    {
390        return format!("{joined} {}", script(&manifest, script_name).unwrap_or(""));
391    }
392    joined
393}
394
395fn relative_build_output(source: &str) -> bool {
396    let mut rest = source;
397    let mut relative = false;
398    while let Some(stripped) = rest.strip_prefix("../").or_else(|| rest.strip_prefix("./")) {
399        relative = true;
400        rest = stripped;
401    }
402    relative
403        && matches!(
404            rest.split('/').next(),
405            Some("dist" | "build" | "out" | "output")
406        )
407}
408
409fn string_expression<'a>(expression: &'a Expression<'_>) -> Option<&'a str> {
410    let Expression::StringLiteral(literal) = expression else {
411        return None;
412    };
413    Some(literal.value.as_str())
414}
415
416struct BuildOutputScanner<'a> {
417    found: bool,
418    build_output_scripts: &'a BTreeSet<String>,
419}
420
421fn child_process_launcher(expression: &Expression<'_>) -> bool {
422    let name = match expression {
423        Expression::Identifier(identifier) => Some(identifier.name.as_str()),
424        Expression::StaticMemberExpression(member) => Some(member.property.name.as_str()),
425        _ => None,
426    };
427    name.is_some_and(|name| {
428        [
429            "spawn",
430            "spawnSync",
431            "exec",
432            "execSync",
433            "execFile",
434            "execFileSync",
435        ]
436        .contains(&name)
437    })
438}
439
440/// The package script a launch runs, whether the call names a program and an
441/// argument array (`spawn("npm", ["run", "start"])`) or hands the shell one
442/// command string (`execSync("npm run start")`, or `spawn` with `shell`). The
443/// string form is how most suites start a server, and it is the form the
444/// array-only match missed.
445fn launched_package_script<'a>(
446    program: &'a str,
447    arguments: Option<&'a oxc_ast::ast::ArrayExpression<'a>>,
448) -> Option<String> {
449    let words: Vec<String> = match arguments {
450        Some(arguments) => {
451            if !package_manager(program) {
452                return None;
453            }
454            arguments
455                .elements
456                .iter()
457                .map(|element| match element {
458                    ArrayExpressionElement::StringLiteral(value) => Some(value.value.to_string()),
459                    _ => None,
460                })
461                .collect::<Option<Vec<_>>>()?
462        }
463        None => {
464            let mut tokens = command_tokens(program);
465            if tokens.is_empty() || !package_manager(&tokens.remove(0)) {
466                return None;
467            }
468            tokens
469        }
470    };
471    match words.first().map(String::as_str) {
472        Some("run") => words.get(1).cloned(),
473        Some(_) => words.first().cloned(),
474        None => None,
475    }
476}
477
478fn package_manager(value: &str) -> bool {
479    let executable = value
480        .rsplit(['/', '\\'])
481        .next()
482        .unwrap_or(value)
483        .trim_end_matches(".cmd")
484        .trim_end_matches(".exe");
485    ["npm", "pnpm", "yarn", "bun"].contains(&executable)
486}
487
488fn script_references_build_output(command: &str) -> bool {
489    command_tokens(command).iter().any(|token| {
490        let token = token.trim_start_matches("../").trim_start_matches("./");
491        let mut segments = token.split(['/', '\\']);
492        let directory = segments.next();
493        // A bare `build` is a subcommand -- `vite build` produces output, it
494        // does not consume any -- so only a path reaching INTO the directory
495        // means the script runs something already compiled.
496        segments.next().is_some() && matches!(directory, Some("dist" | "build" | "out" | "output"))
497    })
498}
499
500fn build_output_scripts(manifest: &Value) -> BTreeSet<String> {
501    manifest
502        .get("scripts")
503        .and_then(Value::as_object)
504        .into_iter()
505        .flatten()
506        .filter_map(|(name, command)| match command.as_str() {
507            Some(command) if script_references_build_output(command) => Some(name.clone()),
508            _ => None,
509        })
510        .collect()
511}
512
513impl<'a> Visit<'a> for BuildOutputScanner<'_> {
514    fn visit_import_declaration(&mut self, declaration: &oxc_ast::ast::ImportDeclaration<'a>) {
515        self.found |= relative_build_output(declaration.source.value.as_str());
516        walk::walk_import_declaration(self, declaration);
517    }
518
519    fn visit_import_expression(&mut self, expression: &ImportExpression<'a>) {
520        if let Some(source) = string_expression(&expression.source) {
521            self.found |= relative_build_output(source);
522        }
523        walk::walk_import_expression(self, expression);
524    }
525
526    fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
527        if matches!(&call.callee, Expression::Identifier(identifier) if identifier.name == "require")
528            && let Some(Argument::StringLiteral(source)) = call.arguments.first()
529        {
530            self.found |= relative_build_output(source.value.as_str());
531        }
532        if child_process_launcher(&call.callee)
533            && let Some(Argument::StringLiteral(program)) = call.arguments.first()
534        {
535            let arguments = match call.arguments.get(1) {
536                Some(Argument::ArrayExpression(arguments)) => Some(&**arguments),
537                _ => None,
538            };
539            self.found |= launched_package_script(program.value.as_str(), arguments)
540                .is_some_and(|script| self.build_output_scripts.contains(&script));
541        }
542        walk::walk_call_expression(self, call);
543    }
544}
545
546/// Whether tests consume compiled output directly or launch a package script
547/// that does. Either form requires the instrumented build before the runner.
548fn tests_require_build_output(root: &Path, manifest: &Value) -> bool {
549    fn visit(directory: &Path, build_output_scripts: &BTreeSet<String>) -> bool {
550        let Ok(entries) = read_directory(directory) else {
551            return false;
552        };
553        for entry in entries {
554            let name = entry.file_name();
555            let Some(name) = name.to_str() else { continue };
556            if name == "node_modules" || name.starts_with('.') {
557                continue;
558            }
559            let path = entry.path();
560            let Ok(file_type) = entry.file_type() else {
561                continue;
562            };
563            if file_type.is_symlink() {
564                continue;
565            }
566            if file_type.is_dir() && visit(&path, build_output_scripts) {
567                return true;
568            }
569            if file_type.is_file()
570                && source_file(&path)
571                && let Ok(source) = fs::read_to_string(&path)
572            {
573                let allocator = Allocator::default();
574                if let Some(program) = parse_program(&allocator, &path, &source) {
575                    let mut scanner = BuildOutputScanner {
576                        found: false,
577                        build_output_scripts,
578                    };
579                    scanner.visit_program(&program);
580                    if scanner.found {
581                        return true;
582                    }
583                }
584            }
585        }
586        false
587    }
588
589    let build_output_scripts = build_output_scripts(manifest);
590    ["test", "tests", "spec", "specs", "e2e", "__tests__"]
591        .iter()
592        .any(|directory| visit(&root.join(directory), &build_output_scripts))
593}
594
595fn command_tokens(value: &str) -> Vec<String> {
596    value
597        .split_whitespace()
598        .map(|token| {
599            token
600                .trim_matches(|character: char| matches!(character, '\'' | '"' | '(' | ')'))
601                .trim_end_matches([';', ','])
602                .to_ascii_lowercase()
603        })
604        .collect()
605}
606
607fn has_tool(tokens: &[String], tool: &str) -> bool {
608    tokens.iter().any(|token| {
609        let file = token.rsplit('/').next().unwrap_or(token);
610        file == tool
611            || file.strip_suffix(".cmd") == Some(tool)
612            || file.strip_suffix(".exe") == Some(tool)
613    })
614}
615
616/// `tokens` and the tokens of every package script they run, however deep:
617/// debug's `npm test` runs `npm run test:browser`, which runs karma.
618fn reachable_script_tokens(manifest: &Value, tokens: &[String]) -> Vec<String> {
619    let mut all = tokens.to_vec();
620    let mut visited = BTreeSet::new();
621    let mut index = 0;
622    while index < all.len() {
623        let runner = all[index]
624            .rsplit('/')
625            .next()
626            .unwrap_or(&all[index])
627            .to_owned();
628        let named = match runner.as_str() {
629            "npm" | "pnpm" | "yarn" | "bun" => {
630                let next = all.get(index + 1).map(String::as_str);
631                match next {
632                    Some("run" | "run-script") => all.get(index + 2).cloned(),
633                    Some("test" | "t") => Some("test".to_owned()),
634                    Some(name) if runner != "npm" => Some(name.to_owned()),
635                    _ => None,
636                }
637            }
638            _ => None,
639        };
640        if let Some(name) = named
641            && visited.insert(name.clone())
642            && let Some(body) = script(manifest, &name)
643        {
644            all.extend(command_tokens(body));
645        }
646        index += 1;
647    }
648    all
649}
650
651fn configured_path(
652    root: &Path,
653    environment: &BTreeMap<String, String>,
654    key: &str,
655) -> Option<PathBuf> {
656    environment.get(key).map(|value| root.join(value))
657}
658
659fn first_config(root: &Path, candidates: &[&str]) -> Option<PathBuf> {
660    candidates
661        .iter()
662        .map(|candidate| root.join(candidate))
663        .find(|path| regular_file(path))
664}
665
666/// The package manager the project's tests were started with, to run its
667/// build the same way. A Yarn or pnpm workspace's scripts call the manager
668/// that runs them; building through npm changed that for no reason.
669fn build_package_manager(command: &[String]) -> String {
670    command
671        .first()
672        .filter(|program| package_manager(program))
673        .cloned()
674        .unwrap_or_else(|| "npm".into())
675}
676
677pub fn discover_coverage_project(
678    root: &Path,
679    environment: &BTreeMap<String, String>,
680    command: &[String],
681) -> Result<CoverageProject, ProjectDiscoveryError> {
682    let manifest = package_json(root);
683    let configured_roots = crate::source_discovery::configured_source_roots(environment);
684    let DiscoveredSourceScope {
685        source_files,
686        source_roots,
687        scope,
688        limitations,
689    } = discover_source_scope(root, configured_roots.as_deref())?;
690    if source_files.is_empty() {
691        return Err(ProjectDiscoveryError::NoSourceFiles);
692    }
693    let playwright_config = configured_path(root, environment, "SUPERCOV_PLAYWRIGHT_CONFIG")
694        .or_else(|| first_config(root, PLAYWRIGHT_CONFIGS))
695        .or_else(|| nested_playwright_configs(root).into_iter().next());
696    let vitest_config = configured_path(root, environment, "SUPERCOV_VITEST_CONFIG")
697        .or_else(|| first_config(root, VITEST_CONFIGS));
698    let jest_config = configured_path(root, environment, "SUPERCOV_JEST_CONFIG")
699        .or_else(|| first_config(root, JEST_CONFIGS));
700    let discovered_playwright = discover_playwright_adapter(root);
701    let playwright_module = environment
702        .get("SUPERCOV_PLAYWRIGHT_MODULE")
703        .cloned()
704        .unwrap_or_else(|| discovered_playwright.module.clone());
705    let playwright_test_export = environment
706        .get("SUPERCOV_PLAYWRIGHT_TEST_EXPORT")
707        .cloned()
708        .unwrap_or_else(|| {
709            if playwright_module == discovered_playwright.module {
710                discovered_playwright.test_export.clone()
711            } else {
712                "test".into()
713            }
714        });
715    let expanded_test_command = expanded_command(root, command);
716    let tokens = command_tokens(&expanded_test_command);
717    let uses_jest =
718        jest_config.is_some() || has_tool(&tokens, "jest") || manifest.get("jest").is_some();
719    let script_tokens = reachable_script_tokens(&manifest, &tokens);
720    let browser_runner = ["karma", "testem", "airtap", "zuul", "mochify"]
721        .iter()
722        .any(|tool| has_tool(&script_tokens, tool));
723    let source_transforming_runner = has_tool(&tokens, "jest") || has_tool(&tokens, "vitest");
724    let node_test = has_tool(&tokens, "node") && tokens.iter().any(|token| token == "--test");
725    let typescript_test = tokens.iter().any(|token| {
726        [".ts", ".tsx", ".cts", ".mts"]
727            .iter()
728            .any(|extension| token.ends_with(extension) || token.contains(&format!("{extension}*")))
729    });
730    let owns_build = ["vite", "tsc", "webpack", "rollup", "next", "remix"]
731        .iter()
732        .any(|tool| has_tool(&tokens, tool));
733    // Reading the suite is the expensive half of this question, so it stays on
734    // the right of `&&`: a command that never executes source directly answers
735    // it without parsing a single test file.
736    let executes_source_directly = (source_transforming_runner
737        || (node_test && typescript_test && !owns_build))
738        && !tests_require_build_output(root, &manifest);
739    // Supercov runs the command it is given and no build of its own. It used
740    // to run the project's `build` script first whenever the tests might
741    // need its output: twenty seconds nobody asked for before a suite that
742    // builds the application itself, in two of five popular repositories,
743    // and a run cancelled when that build failed. The build is only what a
744    // failed run names, when the command does not already reach it.
745    let build_script = script(&manifest, "build")
746        .map(command_tokens)
747        .unwrap_or_default();
748    let command_builds = !build_script.is_empty()
749        && build_script
750            .iter()
751            .all(|token| script_tokens.contains(token));
752    let unrun_build = if !build_script.is_empty() && !command_builds && !executes_source_directly {
753        vec![build_package_manager(command), "run".into(), "build".into()]
754    } else {
755        Vec::new()
756    };
757    let playwright_exports = if playwright_module == discovered_playwright.module {
758        discovered_playwright.exports
759    } else {
760        vec![playwright_test_export.clone(), "expect".into()]
761    };
762    Ok(CoverageProject {
763        root: root.to_owned(),
764        source_roots,
765        source_files,
766        source_scope: scope,
767        source_limitations: limitations,
768        playwright_config,
769        vitest_config,
770        jest_config,
771        uses_jest,
772        browser_runner,
773        playwright_module,
774        playwright_test_export,
775        playwright_exports,
776        unrun_build,
777    })
778}
779
780#[cfg(test)]
781mod tests {
782    use std::time::{SystemTime, UNIX_EPOCH};
783
784    use super::*;
785
786    fn project(label: &str, files: &[(&str, &str)]) -> PathBuf {
787        let nonce = SystemTime::now()
788            .duration_since(UNIX_EPOCH)
789            .unwrap()
790            .as_nanos();
791        let root = std::env::temp_dir().join(format!(
792            "supercov-project-{label}-{}-{nonce}",
793            std::process::id()
794        ));
795        fs::create_dir_all(&root).unwrap();
796        for (file, contents) in files {
797            let path = root.join(file);
798            fs::create_dir_all(path.parent().unwrap()).unwrap();
799            fs::write(path, contents).unwrap();
800        }
801        root
802    }
803
804    fn command(values: &[&str]) -> Vec<String> {
805        values.iter().map(|value| (*value).into()).collect()
806    }
807
808    #[test]
809    fn discovers_conventional_vite_playwright_and_vitest_configuration() {
810        let root = project(
811            "vite",
812            &[
813                (
814                    "package.json",
815                    r#"{"scripts":{"build":"vite build"},"devDependencies":{"vite":"1"}}"#,
816                ),
817                ("src/main.ts", "export const ready = true"),
818                ("playwright.config.ts", "export default {}"),
819                ("vitest.config.ts", "export default {}"),
820                (
821                    "tests/example.spec.ts",
822                    "import { test } from '@playwright/test'",
823                ),
824            ],
825        );
826        let discovered = discover_coverage_project(&root, &BTreeMap::new(), &[]).unwrap();
827        assert_eq!(discovered.source_roots, ["src"]);
828        assert_eq!(
829            discovered.playwright_config,
830            Some(root.join("playwright.config.ts"))
831        );
832        assert_eq!(
833            discovered.vitest_config,
834            Some(root.join("vitest.config.ts"))
835        );
836        assert_eq!(discovered.playwright_module, "@playwright/test");
837        assert_eq!(discovered.playwright_test_export, "test");
838        assert_eq!(discovered.playwright_exports, ["test"]);
839        // The command runs as given: the project\'s build is only what a
840        // failed run names.
841        assert_eq!(discovered.unrun_build, command(&["npm", "run", "build"]));
842        fs::remove_dir_all(root).unwrap();
843    }
844
845    #[test]
846    fn a_browser_runner_the_tests_reach_through_nested_scripts_is_found() {
847        // debug's `npm test` runs `npm run test:browser`, which runs karma.
848        let root = project(
849            "karma",
850            &[
851                (
852                    "package.json",
853                    r#"{"scripts":{"test":"npm run test:node && npm run test:browser","test:node":"mocha test.js","test:browser":"karma start --single-run"}}"#,
854                ),
855                ("src/index.js", "module.exports = 1"),
856            ],
857        );
858        let command = ["npm".to_owned(), "test".to_owned()];
859        let discovered = discover_coverage_project(&root, &BTreeMap::new(), &command).unwrap();
860        assert!(discovered.browser_runner);
861        let node_only = ["npm".to_owned(), "run".to_owned(), "test:node".to_owned()];
862        let discovered = discover_coverage_project(&root, &BTreeMap::new(), &node_only).unwrap();
863        assert!(!discovered.browser_runner);
864    }
865
866    #[test]
867    fn skips_unrelated_builds_for_source_transforming_and_node_test_suites() {
868        for (label, test_script, test_file) in [
869            ("jest", "jest", "require('../src/index.ts')"),
870            ("vitest", "vitest run", "import '../src/index.ts'"),
871            (
872                "node",
873                "node --test tests/*.test.ts",
874                "import '../src/index.ts'",
875            ),
876        ] {
877            let root = project(
878                label,
879                &[
880                    (
881                        "package.json",
882                        &format!(
883                            r#"{{"scripts":{{"build":"node build","test":"{test_script}"}}}}"#
884                        ),
885                    ),
886                    ("src/index.ts", "export const ready = true"),
887                    ("tests/index.test.ts", test_file),
888                ],
889            );
890            let discovered =
891                discover_coverage_project(&root, &BTreeMap::new(), &command(&["npm", "test"]))
892                    .unwrap();
893            assert!(discovered.unrun_build.is_empty(), "{label}");
894            fs::remove_dir_all(root).unwrap();
895        }
896    }
897
898    #[test]
899    fn names_the_build_with_the_package_manager_the_tests_were_started_with() {
900        let root = project(
901            "yarn-build",
902            &[
903                (
904                    "package.json",
905                    r#"{"scripts":{"build":"tsc","test":"jest --runInBand"}}"#,
906                ),
907                ("src/index.ts", "export const ready = true"),
908                ("test/index.test.js", "require('../dist/index.js')"),
909            ],
910        );
911        let discovered =
912            discover_coverage_project(&root, &BTreeMap::new(), &command(&["yarn", "test"]))
913                .unwrap();
914        assert_eq!(discovered.unrun_build, command(&["yarn", "run", "build"]));
915        fs::remove_dir_all(root).unwrap();
916    }
917
918    #[test]
919    fn names_the_build_when_tests_import_compiled_output() {
920        let root = project(
921            "compiled",
922            &[
923                (
924                    "package.json",
925                    r#"{"scripts":{"build":"tsc","test":"jest --runInBand"}}"#,
926                ),
927                ("src/index.ts", "export const ready = true"),
928                ("test/index.test.js", "require('../dist/index.js')"),
929            ],
930        );
931        let discovered =
932            discover_coverage_project(&root, &BTreeMap::new(), &command(&["npm", "test"])).unwrap();
933        assert_eq!(discovered.unrun_build, command(&["npm", "run", "build"]));
934        assert!(discovered.uses_jest);
935        fs::remove_dir_all(root).unwrap();
936    }
937
938    #[test]
939    fn names_the_build_when_source_direct_tests_spawn_a_compiled_package_script() {
940        let root = project(
941            "spawned-compiled-script",
942            &[
943                (
944                    "package.json",
945                    r#"{"scripts":{"build":"tsc","start":"node dist/index.js","test":"node --test tests/*.test.ts"}}"#,
946                ),
947                ("src/index.ts", "export const ready = true"),
948                (
949                    "tests/index.test.ts",
950                    "import { spawn } from 'node:child_process';\nspawn('npm', ['run', 'start']);\n",
951                ),
952            ],
953        );
954        let discovered =
955            discover_coverage_project(&root, &BTreeMap::new(), &command(&["npm", "test"])).unwrap();
956        assert_eq!(discovered.unrun_build, command(&["npm", "run", "build"]));
957        fs::remove_dir_all(root).unwrap();
958    }
959
960    #[test]
961    fn names_the_build_when_tests_exec_a_compiled_package_script_as_one_string() {
962        // `execSync("npm run start")` hands the shell a single string. It is
963        // how most suites start the server they test against, and the
964        // array-only match let it through to the same hang as an unbuilt
965        // gateway.
966        let root = project(
967            "exec-compiled-script",
968            &[
969                (
970                    "package.json",
971                    r#"{"scripts":{"build":"tsc","start":"node dist/index.js","test":"node --test tests/*.test.ts"}}"#,
972                ),
973                ("src/index.ts", "export const ready = true"),
974                (
975                    "tests/index.test.ts",
976                    "import { execSync } from 'node:child_process';\nexecSync('npm run start');\n",
977                ),
978            ],
979        );
980        let discovered =
981            discover_coverage_project(&root, &BTreeMap::new(), &command(&["npm", "test"])).unwrap();
982        assert_eq!(discovered.unrun_build, command(&["npm", "run", "build"]));
983        fs::remove_dir_all(root).unwrap();
984    }
985
986    #[test]
987    fn keeps_source_direct_when_a_spawned_script_only_runs_a_build_subcommand() {
988        let root = project(
989            "spawned-build-subcommand",
990            &[
991                (
992                    "package.json",
993                    r#"{"scripts":{"build":"tsc","dev":"vite build","test":"node --test tests/*.test.ts"}}"#,
994                ),
995                ("src/index.ts", "export const ready = true"),
996                (
997                    "tests/index.test.ts",
998                    "import { spawn } from 'node:child_process';\nspawn('npm', ['run', 'dev']);\n",
999                ),
1000            ],
1001        );
1002        let discovered =
1003            discover_coverage_project(&root, &BTreeMap::new(), &command(&["npm", "test"])).unwrap();
1004        assert!(discovered.unrun_build.is_empty());
1005        fs::remove_dir_all(root).unwrap();
1006    }
1007
1008    #[test]
1009    fn discovers_a_project_owned_playwright_fixture_via_the_ast() {
1010        let root = project(
1011            "fixture",
1012            &[
1013                ("package.json", r#"{"scripts":{"build":"vite build"}}"#),
1014                ("app/root.tsx", "export default null"),
1015                (
1016                    "tests/nested/playwright.browser.config.ts",
1017                    "export default {}",
1018                ),
1019                (
1020                    "tests/example.spec.ts",
1021                    "import { type Ignored, browserTest as test, expect, fixtureValue } from '@acme/browser-fixtures'\n\
1022                     import { createFixtureProduct } from '@acme/browser-fixtures'",
1023                ),
1024            ],
1025        );
1026        let discovered = discover_coverage_project(&root, &BTreeMap::new(), &[]).unwrap();
1027        assert_eq!(
1028            discovered.playwright_config,
1029            Some(root.join("tests/nested/playwright.browser.config.ts"))
1030        );
1031        assert_eq!(discovered.playwright_module, "@acme/browser-fixtures");
1032        assert_eq!(discovered.playwright_test_export, "browserTest");
1033        // The helper imported in its own statement must reach the shim: a
1034        // facade's non-test exports vanish otherwise, and every spec importing
1035        // one fails to link.
1036        assert_eq!(
1037            discovered.playwright_exports,
1038            [
1039                "browserTest",
1040                "createFixtureProduct",
1041                "expect",
1042                "fixtureValue"
1043            ]
1044        );
1045        fs::remove_dir_all(root).unwrap();
1046    }
1047
1048    #[test]
1049    fn environment_overrides_are_authoritative() {
1050        let root = project(
1051            "override",
1052            &[
1053                ("package.json", r#"{"scripts":{"build":"vite build"}}"#),
1054                ("custom/main.ts", "main"),
1055                ("configs/browser.ts", "config"),
1056                (
1057                    "tests/example.spec.ts",
1058                    "import { test } from '@playwright/test'",
1059                ),
1060            ],
1061        );
1062        let environment = BTreeMap::from([
1063            ("SUPERCOV_SOURCE_ROOTS".into(), "custom".into()),
1064            (
1065                "SUPERCOV_PLAYWRIGHT_CONFIG".into(),
1066                "configs/browser.ts".into(),
1067            ),
1068            ("SUPERCOV_PLAYWRIGHT_MODULE".into(), "@custom/test".into()),
1069            ("SUPERCOV_PLAYWRIGHT_TEST_EXPORT".into(), "scenario".into()),
1070        ]);
1071        let discovered = discover_coverage_project(&root, &environment, &[]).unwrap();
1072        assert_eq!(discovered.source_roots, ["custom"]);
1073        assert_eq!(
1074            discovered.playwright_config,
1075            Some(root.join("configs/browser.ts"))
1076        );
1077        assert_eq!(discovered.playwright_module, "@custom/test");
1078        assert_eq!(discovered.playwright_test_export, "scenario");
1079        assert_eq!(discovered.playwright_exports, ["scenario", "expect"]);
1080        fs::remove_dir_all(root).unwrap();
1081    }
1082}