Skip to main content

supercov_engine/
javascript_frontend.rs

1//! JavaScript source frontend for Rust-owned executions.
2//!
3//! The frontend mutates only an already-isolated workspace. JavaScript files
4//! are transformed by the Rust instrumenter; the small Node/browser runtime
5//! remains a language shim and is copied into the workspace under `.supercov`.
6
7use std::{
8    collections::BTreeMap,
9    fs::{self, OpenOptions},
10    io::{self, Write},
11    path::{Path, PathBuf},
12    sync::atomic::{AtomicU64, Ordering},
13    time::{Instant, SystemTime, UNIX_EPOCH},
14};
15
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18
19use crate::{
20    js_instrumenter::{
21        CandidateBranch, CandidateDecision, CandidateError, CandidateLimitation, CandidatePoint,
22        instrument_candidate_with_runtime_hooks, instrument_direct_candidate_with_runtime_hooks,
23    },
24    project_discovery::{BuildAdapter, CoverageProject},
25    source_discovery::{SourceLimitation, SourceScope},
26};
27
28const RUNTIME_INSTANCE_MARKER: &str = "__SUPERCOV_RUNTIME_INSTANCE__";
29const FRONTEND_CACHE_SCHEMA_VERSION: u32 = 2;
30const FRONTEND_CACHE_FILE: &str = ".supercov/frontend-cache.json";
31const FRONTEND_CACHE_DIRECTORY: &str = ".supercov/frontend-cache-artifacts";
32const RUNTIME_FILES: &[&str] = &[
33    "atomic.mjs",
34    "capability.mjs",
35    "jest.cjs",
36    "jest.config.mjs",
37    "jestReporter.mjs",
38    "launchSupervisor.mjs",
39    "nodeAssert.mjs",
40    "nodeAssertAdapter.mjs",
41    "nodeAssertStrict.mjs",
42    "nodeTest.mjs",
43    "playwright.mjs",
44    "playwrightReporter.mjs",
45    "provenance.mjs",
46    "register.mjs",
47    "resolve-loader.mjs",
48    "runnerEvidence.mjs",
49    "runtime.mjs",
50    "transport.mjs",
51    "vitest.mjs",
52    "vitestReporter.mjs",
53];
54static UNIQUE: AtomicU64 = AtomicU64::new(0);
55
56/// Where the setup phase spends its time.
57///
58/// The timings line reports `setup` as one number, and one number cannot say
59/// which operation is slow: on a Windows runner it read 18.7 s for the same
60/// two-file fixture that takes 0.4-0.6 s on macOS -- per-file syncs, as it
61/// turned out. Every file operation the frontend performs adds to these
62/// counters, and `SUPERCOV_PHASE_TIMING=1`
63/// prints them beside the phase, so the next platform surprise is measured
64/// rather than guessed at. The stage counters (runtime, configs, sources,
65/// assertions, cache) partition the phase; the operation counters cut across
66/// those stages, and `instrument` is the parsing and rewriting inside
67/// `sources`, with the rest of that stage being the writes.
68struct SetupAccounting {
69    files: AtomicU64,
70    bytes: AtomicU64,
71    create_ns: AtomicU64,
72    write_ns: AtomicU64,
73    rename_ns: AtomicU64,
74    directories: AtomicU64,
75    directory_retries: AtomicU64,
76    directory_ns: AtomicU64,
77    runtime_ns: AtomicU64,
78    config_ns: AtomicU64,
79    sources_ns: AtomicU64,
80    instrument_ns: AtomicU64,
81    assertion_ns: AtomicU64,
82    cache_ns: AtomicU64,
83}
84
85impl SetupAccounting {
86    const fn new() -> Self {
87        Self {
88            files: AtomicU64::new(0),
89            bytes: AtomicU64::new(0),
90            create_ns: AtomicU64::new(0),
91            write_ns: AtomicU64::new(0),
92            rename_ns: AtomicU64::new(0),
93            directories: AtomicU64::new(0),
94            directory_retries: AtomicU64::new(0),
95            directory_ns: AtomicU64::new(0),
96            runtime_ns: AtomicU64::new(0),
97            config_ns: AtomicU64::new(0),
98            sources_ns: AtomicU64::new(0),
99            instrument_ns: AtomicU64::new(0),
100            assertion_ns: AtomicU64::new(0),
101            cache_ns: AtomicU64::new(0),
102        }
103    }
104}
105
106static SETUP: SetupAccounting = SetupAccounting::new();
107
108fn account(counter: &AtomicU64, started: Instant) {
109    counter.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
110}
111
112fn accounted_ms(counter: &AtomicU64) -> f64 {
113    counter.load(Ordering::Relaxed) as f64 / 1_000_000.0
114}
115
116fn counted(counter: &AtomicU64) -> u64 {
117    counter.load(Ordering::Relaxed)
118}
119
120fn timed<T>(counter: &AtomicU64, operation: impl FnOnce() -> T) -> T {
121    let started = Instant::now();
122    let value = operation();
123    account(counter, started);
124    value
125}
126
127/// One line saying where the setup phase went, when `SUPERCOV_PHASE_TIMING=1`
128/// asked for it.
129pub fn setup_timing_detail() -> Option<String> {
130    if std::env::var("SUPERCOV_PHASE_TIMING").as_deref() != Ok("1") {
131        return None;
132    }
133    Some(format!(
134        "setup detail runtime={:.1}ms configs={:.1}ms sources={:.1}ms (instrument={:.1}ms) \
135assertions={:.1}ms cache={:.1}ms | files={} bytes={} create={:.1}ms write={:.1}ms \
136rename={:.1}ms | directories={} retries={} directory-wait={:.1}ms",
137        accounted_ms(&SETUP.runtime_ns),
138        accounted_ms(&SETUP.config_ns),
139        accounted_ms(&SETUP.sources_ns),
140        accounted_ms(&SETUP.instrument_ns),
141        accounted_ms(&SETUP.assertion_ns),
142        accounted_ms(&SETUP.cache_ns),
143        counted(&SETUP.files),
144        counted(&SETUP.bytes),
145        accounted_ms(&SETUP.create_ns),
146        accounted_ms(&SETUP.write_ns),
147        accounted_ms(&SETUP.rename_ns),
148        counted(&SETUP.directories),
149        counted(&SETUP.directory_retries),
150        accounted_ms(&SETUP.directory_ns),
151    ))
152}
153
154#[derive(Debug)]
155pub enum JavascriptFrontendError {
156    Io {
157        path: PathBuf,
158        source: io::Error,
159    },
160    Instrument {
161        file: String,
162        source: CandidateError,
163    },
164    MissingRuntimeMarker,
165    Serialize(serde_json::Error),
166    UnsafeSourcePath(String),
167}
168
169impl std::fmt::Display for JavascriptFrontendError {
170    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        match self {
172            Self::Io { path, source } => write!(formatter, "{}: {source}", path.display()),
173            Self::Instrument { file, source } => {
174                write!(formatter, "failed to instrument {file}: {source:?}")
175            }
176            Self::MissingRuntimeMarker => write!(
177                formatter,
178                "generated Supercov runtime is missing its instance marker"
179            ),
180            Self::Serialize(error) => write!(formatter, "failed to serialize manifest: {error}"),
181            Self::UnsafeSourcePath(file) => write!(formatter, "unsafe source path: {file}"),
182        }
183    }
184}
185
186impl std::error::Error for JavascriptFrontendError {}
187
188fn io_error(path: &Path, source: io::Error) -> JavascriptFrontendError {
189    JavascriptFrontendError::Io {
190        path: path.to_owned(),
191        source,
192    }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase", deny_unknown_fields)]
197pub struct JavascriptManifest {
198    pub decisions: Vec<CandidateDecision>,
199    pub points: Vec<CandidatePoint>,
200    pub branches: Vec<CandidateBranch>,
201    pub limitations: Vec<CandidateLimitation>,
202    pub scope: SourceScope,
203}
204
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct PreparedJavascriptFrontend {
207    pub manifest: JavascriptManifest,
208    pub manifest_path: PathBuf,
209    pub preload_path: PathBuf,
210    pub playwright_config_path: PathBuf,
211    pub vite_config_path: PathBuf,
212    pub vitest_config_path: PathBuf,
213    pub assertion_calls: usize,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(rename_all = "camelCase", deny_unknown_fields)]
218pub struct JavascriptFrontendCache {
219    schema_version: u32,
220    key: String,
221    assertion_calls: usize,
222    artifacts: Vec<JavascriptFrontendCacheArtifact>,
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226#[serde(rename_all = "camelCase", deny_unknown_fields)]
227struct JavascriptFrontendCacheArtifact {
228    path: String,
229    cache_file: String,
230    sha256: String,
231}
232
233fn safe_relative(path: &Path) -> bool {
234    path.components().next().is_some()
235        && path
236            .components()
237            .all(|component| matches!(component, std::path::Component::Normal(_)))
238}
239
240fn regular_file(workspace: &Path, relative: &str) -> bool {
241    safe_relative(Path::new(relative))
242        && fs::symlink_metadata(workspace.join(relative))
243            .is_ok_and(|metadata| metadata.file_type().is_file())
244}
245
246fn valid_cached_artifact(workspace: &Path, artifact: &JavascriptFrontendCacheArtifact) -> bool {
247    let expected_cache_file = format!("{FRONTEND_CACHE_DIRECTORY}/{}", artifact.sha256);
248    if !safe_relative(Path::new(&artifact.path))
249        || !safe_relative(Path::new(&artifact.cache_file))
250        || artifact.cache_file != expected_cache_file
251        || artifact.sha256.len() != 64
252        || !artifact
253            .sha256
254            .bytes()
255            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
256    {
257        return false;
258    }
259    let Ok(contents) = fs::read(workspace.join(&artifact.cache_file)) else {
260        return false;
261    };
262    format!("{:x}", Sha256::digest(&contents)) == artifact.sha256
263}
264
265pub fn read_javascript_frontend_cache(
266    workspace: &Path,
267    key: &str,
268) -> Option<JavascriptFrontendCache> {
269    let metadata: JavascriptFrontendCache =
270        serde_json::from_slice(&fs::read(workspace.join(FRONTEND_CACHE_FILE)).ok()?).ok()?;
271    if metadata.schema_version != FRONTEND_CACHE_SCHEMA_VERSION
272        || metadata.key != key
273        || metadata.artifacts.is_empty()
274        || metadata
275            .artifacts
276            .iter()
277            .any(|artifact| !valid_cached_artifact(workspace, artifact))
278    {
279        return None;
280    }
281    Some(metadata)
282}
283
284pub fn javascript_frontend_reuse_paths(cache: &JavascriptFrontendCache) -> Vec<PathBuf> {
285    let _ = cache;
286    vec![
287        PathBuf::from(FRONTEND_CACHE_FILE),
288        PathBuf::from(FRONTEND_CACHE_DIRECTORY),
289    ]
290}
291
292fn restore_cached_file(path: &Path, contents: &[u8]) -> Result<(), JavascriptFrontendError> {
293    let parent = path
294        .parent()
295        .ok_or_else(|| JavascriptFrontendError::UnsafeSourcePath(path.display().to_string()))?;
296    create_directory_all(parent)?;
297    let temporary = parent.join(format!(".supercov-restore-{}", unique()));
298    let result = (|| {
299        fs::write(&temporary, contents).map_err(|source| io_error(&temporary, source))?;
300        match fs::symlink_metadata(path) {
301            Ok(metadata) if metadata.file_type().is_file() || metadata.file_type().is_symlink() => {
302                fs::remove_file(path).map_err(|source| io_error(path, source))?;
303            }
304            Ok(_) => {
305                return Err(JavascriptFrontendError::UnsafeSourcePath(
306                    path.display().to_string(),
307                ));
308            }
309            Err(source) if source.kind() == io::ErrorKind::NotFound => {}
310            Err(source) => return Err(io_error(path, source)),
311        }
312        fs::rename(&temporary, path).map_err(|source| io_error(path, source))
313    })();
314    if result.is_err() {
315        let _ = fs::remove_file(&temporary);
316    }
317    result
318}
319
320pub fn load_cached_javascript_frontend(
321    workspace: &Path,
322    cache: &JavascriptFrontendCache,
323) -> Result<PreparedJavascriptFrontend, JavascriptFrontendError> {
324    for artifact in &cache.artifacts {
325        let cache_path = workspace.join(&artifact.cache_file);
326        let contents = fs::read(&cache_path).map_err(|source| io_error(&cache_path, source))?;
327        if format!("{:x}", Sha256::digest(&contents)) != artifact.sha256 {
328            return Err(JavascriptFrontendError::UnsafeSourcePath(format!(
329                "corrupt frontend cache artifact {}",
330                artifact.cache_file
331            )));
332        }
333        restore_cached_file(&workspace.join(&artifact.path), &contents)?;
334    }
335    let generated = workspace.join(".supercov");
336    let manifest_path = generated.join("manifest.json");
337    let manifest = serde_json::from_slice(
338        &fs::read(&manifest_path).map_err(|source| io_error(&manifest_path, source))?,
339    )
340    .map_err(JavascriptFrontendError::Serialize)?;
341    Ok(PreparedJavascriptFrontend {
342        manifest,
343        manifest_path,
344        preload_path: generated.join("node_modules/register.mjs"),
345        playwright_config_path: generated.join("playwright.config.mjs"),
346        vite_config_path: generated.join("vite.config.mjs"),
347        vitest_config_path: generated.join("vitest.config.mjs"),
348        assertion_calls: cache.assertion_calls,
349    })
350}
351
352fn frontend_artifact_paths(workspace: &Path, project: &CoverageProject) -> Vec<String> {
353    let mut artifacts = vec![
354        ".supercov/node_modules/package.json".to_owned(),
355        ".supercov/node_modules/applicationRuntime.mjs".to_owned(),
356        ".supercov/node_modules/runtime.d.mts".to_owned(),
357        ".supercov/playwright.config.mjs".to_owned(),
358        ".supercov/vite.config.mjs".to_owned(),
359        ".supercov/vitest.config.mjs".to_owned(),
360        ".supercov/vite-transforms.json".to_owned(),
361        ".supercov/viteInstrumentation.mjs".to_owned(),
362        ".supercov/manifest.json".to_owned(),
363        ".supercov/instrumentation-complete".to_owned(),
364    ];
365    artifacts.extend(
366        RUNTIME_FILES
367            .iter()
368            .map(|name| format!(".supercov/node_modules/{name}")),
369    );
370    // Scope entries outside the instrumented set may still be rewritten
371    // (assertion attribution, capability imports), so they are cached like
372    // instrumented sources. Both populations feed the cache key through the
373    // source digest -- nothing cached here escapes the fingerprint.
374    artifacts.extend(project.source_files.iter().cloned());
375    artifacts.extend(
376        project
377            .source_scope
378            .entries
379            .iter()
380            .map(|entry| entry.file.clone()),
381    );
382    for root in &project.source_roots {
383        let host = if workspace.join(root).is_file() {
384            Path::new(root).parent().unwrap_or_else(|| Path::new(""))
385        } else {
386            Path::new(root)
387        };
388        for name in ["package.json", "runtime.mjs", "runtime.d.mts"] {
389            let path = host.join(".supercov/node_modules").join(name);
390            if let Some(path) = path.to_str() {
391                artifacts.push(path.replace('\\', "/"));
392            }
393        }
394    }
395    artifacts.sort();
396    artifacts.dedup();
397    artifacts.retain(|path| regular_file(workspace, path));
398    artifacts
399}
400
401fn write_javascript_frontend_cache(
402    workspace: &Path,
403    project: &CoverageProject,
404    key: &str,
405    assertion_calls: usize,
406) -> Result<(), JavascriptFrontendError> {
407    let cache_directory = workspace.join(FRONTEND_CACHE_DIRECTORY);
408    create_directory_all(&cache_directory)?;
409    let mut artifacts = Vec::new();
410    for path in frontend_artifact_paths(workspace, project) {
411        let contents = fs::read(workspace.join(&path))
412            .map_err(|source| io_error(&workspace.join(&path), source))?;
413        let sha256 = format!("{:x}", Sha256::digest(&contents));
414        let cache_file = format!("{FRONTEND_CACHE_DIRECTORY}/{sha256}");
415        let destination = workspace.join(&cache_file);
416        if !destination.is_file() {
417            atomic_write(&destination, &contents)?;
418        }
419        artifacts.push(JavascriptFrontendCacheArtifact {
420            path,
421            cache_file,
422            sha256,
423        });
424    }
425    let cache = JavascriptFrontendCache {
426        schema_version: FRONTEND_CACHE_SCHEMA_VERSION,
427        key: key.to_owned(),
428        assertion_calls,
429        artifacts,
430    };
431    let mut encoded =
432        serde_json::to_vec_pretty(&cache).map_err(JavascriptFrontendError::Serialize)?;
433    encoded.push(b'\n');
434    atomic_write(&workspace.join(FRONTEND_CACHE_FILE), &encoded)
435}
436
437#[derive(Debug, Serialize)]
438#[serde(rename_all = "camelCase")]
439struct ViteTransform {
440    source_sha256: String,
441    code: String,
442    map: Option<serde_json::Value>,
443}
444
445fn embedded_runtime(name: &str) -> Option<&'static [u8]> {
446    match name {
447        "atomic.mjs" => Some(include_bytes!("../runtime-assets/javascript/atomic.mjs")),
448        "capability.mjs" => Some(include_bytes!(
449            "../runtime-assets/javascript/capability.mjs"
450        )),
451        "jest.cjs" => Some(include_bytes!("../runtime-assets/javascript/jest.cjs")),
452        "jest.config.mjs" => Some(include_bytes!(
453            "../runtime-assets/javascript/jest.config.mjs"
454        )),
455        "jestReporter.mjs" => Some(include_bytes!(
456            "../runtime-assets/javascript/jestReporter.mjs"
457        )),
458        "launchSupervisor.mjs" => Some(include_bytes!(
459            "../runtime-assets/javascript/launchSupervisor.mjs"
460        )),
461        "nodeAssert.mjs" => Some(include_bytes!(
462            "../runtime-assets/javascript/nodeAssert.mjs"
463        )),
464        "nodeAssertAdapter.mjs" => Some(include_bytes!(
465            "../runtime-assets/javascript/nodeAssertAdapter.mjs"
466        )),
467        "nodeAssertStrict.mjs" => Some(include_bytes!(
468            "../runtime-assets/javascript/nodeAssertStrict.mjs"
469        )),
470        "nodeTest.mjs" => Some(include_bytes!("../runtime-assets/javascript/nodeTest.mjs")),
471        "playwright.mjs" => Some(include_bytes!(
472            "../runtime-assets/javascript/playwright.mjs"
473        )),
474        "playwrightReporter.mjs" => Some(include_bytes!(
475            "../runtime-assets/javascript/playwrightReporter.mjs"
476        )),
477        "provenance.mjs" => Some(include_bytes!(
478            "../runtime-assets/javascript/provenance.mjs"
479        )),
480        "register.mjs" => Some(include_bytes!("../runtime-assets/javascript/register.mjs")),
481        "resolve-loader.mjs" => Some(include_bytes!(
482            "../runtime-assets/javascript/resolve-loader.mjs"
483        )),
484        "runnerEvidence.mjs" => Some(include_bytes!(
485            "../runtime-assets/javascript/runnerEvidence.mjs"
486        )),
487        "runtime.mjs" => Some(include_bytes!("../runtime-assets/javascript/runtime.mjs")),
488        "transport.mjs" => Some(include_bytes!("../runtime-assets/javascript/transport.mjs")),
489        "vitest.mjs" => Some(include_bytes!("../runtime-assets/javascript/vitest.mjs")),
490        "vitestReporter.mjs" => Some(include_bytes!(
491            "../runtime-assets/javascript/vitestReporter.mjs"
492        )),
493        _ => None,
494    }
495}
496
497fn unique() -> String {
498    let nanos = SystemTime::now()
499        .duration_since(UNIX_EPOCH)
500        .unwrap_or_default()
501        .as_nanos();
502    format!(
503        "{}-{nanos}-{}",
504        std::process::id(),
505        UNIQUE.fetch_add(1, Ordering::Relaxed)
506    )
507}
508
509#[cfg(not(windows))]
510fn create_directory_all(path: &Path) -> Result<(), JavascriptFrontendError> {
511    SETUP.directories.fetch_add(1, Ordering::Relaxed);
512    timed(&SETUP.directory_ns, || {
513        fs::create_dir_all(path).map_err(|source| io_error(path, source))
514    })
515}
516
517#[cfg(windows)]
518fn create_directory_all(path: &Path) -> Result<(), JavascriptFrontendError> {
519    // Windows scanners and just-closed directory handles reject creation of a
520    // brand-new path with ERROR_ACCESS_DENIED for as long as they hold the
521    // parent open. On a hosted runner with real-time scanning that is not
522    // milliseconds: the first Windows build exhausted eleven 20 ms retries on
523    // the generated node_modules directory right after the mirror had filled
524    // its sibling with junctions. Back off up to a few seconds against the
525    // exact owned path -- never broaden or redirect the target -- and when it
526    // still fails, say what every ancestor was, so a failure on a machine we
527    // cannot see is a diagnosis rather than a guess.
528    const ATTEMPTS: usize = 16;
529    let started = std::time::Instant::now();
530    SETUP.directories.fetch_add(1, Ordering::Relaxed);
531    let mut delay = std::time::Duration::from_millis(20);
532    for attempt in 0..ATTEMPTS {
533        match fs::create_dir_all(path) {
534            Ok(()) => {
535                account(&SETUP.directory_ns, started);
536                return Ok(());
537            }
538            Err(source)
539                if source.kind() == io::ErrorKind::PermissionDenied && attempt + 1 < ATTEMPTS =>
540            {
541                SETUP.directory_retries.fetch_add(1, Ordering::Relaxed);
542                std::thread::sleep(delay);
543                delay = (delay * 2).min(std::time::Duration::from_millis(500));
544            }
545            Err(source) => {
546                account(&SETUP.directory_ns, started);
547                let detail = format!(
548                    "{source} (after {} attempt(s) over {:?}; ancestors: {})",
549                    attempt + 1,
550                    started.elapsed(),
551                    describe_ancestors(path)
552                );
553                return Err(io_error(path, io::Error::new(source.kind(), detail)));
554            }
555        }
556    }
557    unreachable!("the final directory-creation attempt always returns")
558}
559
560/// One line per path component from the root down: whether it exists and as
561/// what. `symlink_metadata` is used so a reparse point is reported as a link
562/// rather than as whatever it points to.
563#[cfg_attr(not(windows), allow(dead_code))]
564fn describe_ancestors(path: &Path) -> String {
565    let mut current = PathBuf::new();
566    let mut parts = Vec::new();
567    for component in path.components() {
568        current.push(component.as_os_str());
569        let state = match fs::symlink_metadata(&current) {
570            Ok(metadata) if metadata.file_type().is_symlink() => "link",
571            Ok(metadata) if metadata.file_type().is_dir() => "dir",
572            Ok(_) => "file",
573            // A component below a file is "not a directory" on Unix and "path
574            // not found" on Windows; either way nothing exists there.
575            Err(error)
576                if matches!(
577                    error.kind(),
578                    io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
579                ) =>
580            {
581                "missing"
582            }
583            Err(error) => return format!("{} -> {error}", current.display()),
584        };
585        parts.push(format!("{}={state}", current.display()));
586    }
587    parts.join("; ")
588}
589
590fn atomic_write(path: &Path, contents: &[u8]) -> Result<(), JavascriptFrontendError> {
591    let parent = path
592        .parent()
593        .ok_or_else(|| JavascriptFrontendError::UnsafeSourcePath(path.display().to_string()))?;
594    let temporary = parent.join(format!(".supercov-write-{}", unique()));
595    let result = (|| {
596        let open = || {
597            OpenOptions::new()
598                .write(true)
599                .create_new(true)
600                .open(&temporary)
601        };
602        let opened = timed(&SETUP.create_ns, open);
603        let mut output = match opened {
604            Ok(output) => output,
605            Err(source) if source.kind() == io::ErrorKind::NotFound => {
606                create_directory_all(parent)?;
607                timed(&SETUP.create_ns, open).map_err(|source| io_error(&temporary, source))?
608            }
609            Err(source) => return Err(io_error(&temporary, source)),
610        };
611        timed(&SETUP.write_ns, || output.write_all(contents))
612            .map_err(|source| io_error(&temporary, source))?;
613        // This file is not forced to disk, deliberately. Everything the
614        // frontend writes lives in the regenerable workspace cache and is
615        // listed in `frontend_artifact_paths`: a later run either rewrites it
616        // from the embedded assets and the project's sources, or restores it
617        // from the frontend cache, which verifies each artifact's sha256 when
618        // it reads the cache and again when it restores it, while mirrored
619        // sources are pruned and re-copied every run. A file left half-written
620        // by a crash therefore cannot be read back as if it were whole: it
621        // fails its digest and is regenerated. `rename` still publishes each
622        // file atomically, so no reader in this run can observe a partial one.
623        // What is given up is only surviving a power loss for files the next
624        // run rebuilds anyway.
625        //
626        // What it buys is the phase. Preparing a two-file fixture writes 61
627        // files, and the syncs were most of the wait: 240-260 ms of a 290-310
628        // ms phase on a Windows runner, and 190 ms of file sync plus 180 ms of
629        // directory sync in a 400 ms phase on macOS. Both become 14-55 ms. A
630        // Windows probe once measured this same phase at 18.7 s, which is a
631        // per-sync latency of about 300 ms; a scanner busy enough to do that
632        // no longer has anything here to block on.
633        //
634        // Durability that does matter -- evidence, run state, cache metadata
635        // -- goes through `lifecycle::atomic_write`, which still syncs.
636        timed(&SETUP.rename_ns, || fs::rename(&temporary, path))
637            .map_err(|source| io_error(path, source))?;
638        SETUP.files.fetch_add(1, Ordering::Relaxed);
639        SETUP
640            .bytes
641            .fetch_add(contents.len() as u64, Ordering::Relaxed);
642        Ok(())
643    })();
644    if result.is_err() {
645        let _ = fs::remove_file(&temporary);
646    }
647    result
648}
649
650fn checked_source_path(workspace: &Path, file: &str) -> Result<PathBuf, JavascriptFrontendError> {
651    let relative = Path::new(file);
652    if relative.is_absolute()
653        || relative
654            .components()
655            .any(|component| !matches!(component, std::path::Component::Normal(_)))
656    {
657        return Err(JavascriptFrontendError::UnsafeSourcePath(file.to_owned()));
658    }
659    Ok(workspace.join(relative))
660}
661
662fn runtime_specifier(file: &str, name: &str) -> Result<String, JavascriptFrontendError> {
663    let relative = Path::new(file);
664    if relative.is_absolute()
665        || relative
666            .components()
667            .any(|component| !matches!(component, std::path::Component::Normal(_)))
668    {
669        return Err(JavascriptFrontendError::UnsafeSourcePath(file.to_owned()));
670    }
671    let depth = relative
672        .parent()
673        .map_or(0, |parent| parent.components().count());
674    Ok(if depth == 0 {
675        format!("./.supercov/node_modules/{name}")
676    } else {
677        format!("{}.supercov/node_modules/{name}", "../".repeat(depth))
678    })
679}
680
681/// The banner that exempts an instrumented source from the host project's lint
682/// and type policy. The disable line comes FIRST so the host's own
683/// ban-ts-comment rule cannot reject the `@ts-nocheck` below it: Next.js lints
684/// instrumented sources during `next build`, and a real monorepo failed on
685/// every route file. Generated and instrumented code is immune to host lint
686/// policy as a class.
687const GENERATED_SOURCE_BANNER: &str =
688    "/* eslint-disable */\n// @ts-nocheck -- generated coverage workspace only\n";
689
690/// Prefix `code` with that banner, keeping a shebang on the first line. `#!`
691/// anywhere else is a parse error TypeScript reports as TS18026, which
692/// `@ts-nocheck` cannot suppress because it is syntax and not semantics, so a
693/// banner in front of it failed the build of every project whose entry point
694/// is executable.
695fn generated_source_banner(code: &str) -> String {
696    let Some(rest) = code.strip_prefix("#!") else {
697        return format!("{GENERATED_SOURCE_BANNER}{code}");
698    };
699    let (line, remainder) = rest.split_once('\n').unwrap_or((rest, ""));
700    format!("#!{line}\n{GENERATED_SOURCE_BANNER}{remainder}")
701}
702
703fn isolate_runtime(source: &str, collector_id: &str) -> Result<String, JavascriptFrontendError> {
704    // Generated runtime files sit inside the lint graph of bundlers that lint
705    // whatever they compile (Next.js does), so they must disarm host lint
706    // policy the same way the Rust runtime does with #[allow(warnings)].
707    let source = format!("/* eslint-disable */\n{source}");
708    let source = source.as_str();
709    let double = format!("runtimeInstanceToken = \"{RUNTIME_INSTANCE_MARKER}\"");
710    let single = format!("runtimeInstanceToken = '{RUNTIME_INSTANCE_MARKER}'");
711    if let Some(index) = source.find(&double) {
712        let mut isolated = source.to_owned();
713        isolated.replace_range(
714            index..index + double.len(),
715            &format!("runtimeInstanceToken = \"{collector_id}\""),
716        );
717        return Ok(isolated);
718    }
719    if let Some(index) = source.find(&single) {
720        let mut isolated = source.to_owned();
721        isolated.replace_range(
722            index..index + single.len(),
723            &format!("runtimeInstanceToken = '{collector_id}'"),
724        );
725        return Ok(isolated);
726    }
727    Err(JavascriptFrontendError::MissingRuntimeMarker)
728}
729
730/// Inline `map` into `code` as a data-URL source map whose single source is the
731/// ORIGINAL project file, with the original text embedded.
732///
733/// The instrumented file may have banner lines prepended AFTER the map was
734/// computed (`/* eslint-disable */` and `@ts-nocheck`); VLQ mappings are
735/// generated-line-relative with one `;` per line, so the map is shifted by
736/// prefixing one semicolon per banner line rather than re-encoding tokens. A
737/// shebang keeps the first line and maps to itself, so the banner below it
738/// shifts everything after by the same amount.
739fn inline_instrumentation_map(
740    code: &str,
741    map: Option<&serde_json::Value>,
742    original_path: &Path,
743    original_source: &str,
744) -> Option<String> {
745    let map = map?.clone();
746    let mut map = map;
747    let object = map.as_object_mut()?;
748    let banner_lines = code
749        .lines()
750        .skip(usize::from(code.starts_with("#!")))
751        .take_while(|line| {
752            line.starts_with("/* eslint-disable */") || line.starts_with("// @ts-nocheck")
753        })
754        .count();
755    if banner_lines > 0 {
756        let mappings = object.get("mappings")?.as_str()?.to_owned();
757        object.insert(
758            "mappings".into(),
759            serde_json::Value::String(format!("{}{}", ";".repeat(banner_lines), mappings)),
760        );
761    }
762    object.insert(
763        "sources".into(),
764        serde_json::json!([original_path.display().to_string()]),
765    );
766    object.insert(
767        "sourcesContent".into(),
768        serde_json::json!([original_source]),
769    );
770    let payload = serde_json::to_string(&map).ok()?;
771    use base64::Engine as _;
772    let encoded = base64::engine::general_purpose::STANDARD.encode(payload);
773    Some(format!(
774        "{code}\n//# sourceMappingURL=data:application/json;base64,{encoded}\n"
775    ))
776}
777
778/// Target-language shims are embedded in the Rust engine. Keeping a trailing
779/// source-map directive would make Node and browser tooling look for source
780/// maps that intentionally are not part of the runtime distribution.
781fn strip_source_map_reference(mut bytes: Vec<u8>) -> Vec<u8> {
782    const MARKER: &[u8] = b"\n//# sourceMappingURL=";
783    if let Some(index) = bytes
784        .windows(MARKER.len())
785        .rposition(|window| window == MARKER)
786    {
787        let suffix = &bytes[index + MARKER.len()..];
788        let suffix = suffix.strip_suffix(b"\n").unwrap_or(suffix);
789        let suffix = suffix.strip_suffix(b"\r").unwrap_or(suffix);
790        if !suffix.contains(&b'\n') && !suffix.contains(&b'\r') {
791            bytes.truncate(index + 1);
792        }
793    }
794    bytes
795}
796
797fn copy_runtime(generated: &Path, collector_id: &str) -> Result<(), JavascriptFrontendError> {
798    create_directory_all(generated)?;
799    atomic_write(
800        &generated.join("package.json"),
801        b"{\"private\":true,\"type\":\"module\"}\n",
802    )?;
803    for name in RUNTIME_FILES {
804        let destination = generated.join(name);
805        let source_path = PathBuf::from(format!("embedded:{name}"));
806        let bytes = embedded_runtime(name)
807            .expect("every declared runtime file must have an embedded asset")
808            .to_vec();
809        let bytes = strip_source_map_reference(bytes);
810        if *name == "runtime.mjs" {
811            let text = String::from_utf8(bytes).map_err(|source| {
812                io_error(
813                    &source_path,
814                    io::Error::new(io::ErrorKind::InvalidData, source),
815                )
816            })?;
817            atomic_write(
818                &destination,
819                isolate_runtime(&text, collector_id)?.as_bytes(),
820            )?;
821            atomic_write(
822                &generated.join("applicationRuntime.mjs"),
823                isolate_runtime(&text, &format!("{collector_id}-application"))?.as_bytes(),
824            )?;
825        } else {
826            atomic_write(&destination, &bytes)?;
827        }
828    }
829    atomic_write(
830        &generated.join("runtime.d.mts"),
831        // Generated files must be immune to the HOST project's lint policy --
832        // the same rule the Rust runtime enforces with #[allow(warnings)].
833        // Next.js runs the project's eslint over the build graph, and
834        // @typescript-eslint/no-explicit-any turned every `any` below into a
835        // hard "Failed to compile" for a real monorepo.
836        b"/* eslint-disable */\n\
837export declare function coverageHit(...args: any[]): any;\n\
838export declare function selectionBegin(...args: any[]): any;\n\
839export declare function selectionRight(...args: any[]): any;\n\
840export declare function selectionEnd(...args: any[]): any;\n\
841export declare function optionalSelect(...args: any[]): any;\n\
842export declare function optionalCallBegin(...args: any[]): any;\n\
843export declare function optionalCallReached(...args: any[]): any;\n\
844export declare function optionalCallContinued(...args: any[]): any;\n\
845export declare function optionalCallEnd(...args: any[]): any;\n\
846export declare function defaultSelected(...args: any[]): any;\n\
847export declare function defaultEntered(...args: any[]): any;\n\
848export declare function tryBegin(...args: any[]): any;\n\
849export declare function tryCatch(...args: any[]): any;\n\
850export declare function tryEnd(...args: any[]): any;\n\
851export declare function loopBegin(...args: any[]): any;\n\
852export declare function loopEntered(...args: any[]): any;\n\
853export declare function loopEnd(...args: any[]): any;\n\
854export declare function mcdcBegin(...args: any[]): any;\n\
855export declare function mcdcCondition(...args: any[]): any;\n\
856export declare function mcdcEnd(...args: any[]): any;\n\
857export declare function registerProbeV2(...args: any[]): any;\n\
858export declare function coverageHitV2(...args: any[]): any;\n\
859export declare function mcdcEndV2(...args: any[]): any;\n",
860    )?;
861    Ok(())
862}
863
864fn generic_runtime_binding(
865    workspace: &Path,
866    project: &CoverageProject,
867    source_path: &Path,
868    generated: &Path,
869) -> Result<String, JavascriptFrontendError> {
870    let mut hosts = project
871        .source_roots
872        .iter()
873        .filter_map(|root| {
874            let candidate = workspace.join(root);
875            if candidate.is_dir() && source_path.strip_prefix(&candidate).is_ok() {
876                Some(candidate)
877            } else if candidate.is_file() && candidate == source_path {
878                candidate.parent().map(Path::to_owned)
879            } else {
880                None
881            }
882        })
883        .collect::<Vec<_>>();
884    hosts.sort_by_key(|path| std::cmp::Reverse(path.components().count()));
885    let host = hosts
886        .into_iter()
887        .next()
888        .unwrap_or_else(|| workspace.to_owned());
889    let runtime_directory = host.join(".supercov/node_modules");
890    fs::create_dir_all(&runtime_directory)
891        .map_err(|source| io_error(&runtime_directory, source))?;
892    // A bundler may externalize the node_modules import instead of compiling
893    // it, leaving Node to interpret the .js file at run time.
894    atomic_write(
895        &runtime_directory.join("package.json"),
896        b"{\"private\":true,\"type\":\"module\"}\n",
897    )?;
898    for name in ["runtime.mjs", "runtime.d.mts"] {
899        let source = generated.join("node_modules").join(name);
900        let destination = runtime_directory.join(name);
901        let contents = fs::read(&source).map_err(|error| io_error(&source, error))?;
902        atomic_write(&destination, &contents)?;
903    }
904    let parent = source_path.parent().ok_or_else(|| {
905        JavascriptFrontendError::UnsafeSourcePath(source_path.display().to_string())
906    })?;
907    let local = parent.strip_prefix(&host).map_err(|_| {
908        JavascriptFrontendError::UnsafeSourcePath(source_path.display().to_string())
909    })?;
910    let depth = local.components().count();
911    Ok(if depth == 0 {
912        "./.supercov/node_modules/runtime.mjs".into()
913    } else {
914        format!("{}.supercov/node_modules/runtime.mjs", "../".repeat(depth))
915    })
916}
917
918fn limitation_from_source(value: &SourceLimitation) -> CandidateLimitation {
919    CandidateLimitation {
920        id: value.id.clone(),
921        kind: value.kind.clone(),
922        file: value.file.clone(),
923        line: value.line,
924        column: value.column,
925        source: value.source.clone(),
926        reason: value.reason.clone(),
927    }
928}
929
930fn relocated_project_file(
931    workspace: &Path,
932    project: &CoverageProject,
933    source: Option<&PathBuf>,
934) -> Option<PathBuf> {
935    let source = source?;
936    let relative = source.strip_prefix(&project.root).ok()?;
937    Some(workspace.join(relative))
938}
939
940fn write_vitest_config(
941    workspace: &Path,
942    project: &CoverageProject,
943    generated: &Path,
944) -> Result<PathBuf, JavascriptFrontendError> {
945    let path = generated.join("vitest.config.mjs");
946    let original = relocated_project_file(workspace, project, project.vitest_config.as_ref())
947        .map(|path| path.display().to_string());
948    let original = serde_json::to_string(&original).map_err(JavascriptFrontendError::Serialize)?;
949    let source = format!(
950        "import {{ createRequire }} from 'node:module';\n\
951         import {{ pathToFileURL }} from 'node:url';\n\
952         // pnpm's strict layout does not hoist vite to the project root: it\n\
953         // lives inside vitest's virtual store, so a bare 'vite' specifier\n\
954         // resolved from this generated file fails. Vitest depends on vite, so\n\
955         // fall back to resolving it through vitest's own tree rather than\n\
956         // requiring the project to hoist anything.\n\
957         const supercovRequire = createRequire(import.meta.url);\n\
958         const supercovLoadVite = async () => {{\n\
959           try {{\n\
960             return await import('vite');\n\
961           }} catch (error) {{\n\
962             let entry;\n\
963             try {{\n\
964               entry = createRequire(supercovRequire.resolve('vitest')).resolve('vite');\n\
965             }} catch {{\n\
966               throw error;\n\
967             }}\n\
968             return await import(pathToFileURL(entry).href);\n\
969           }}\n\
970         }};\n\
971         const viteNamespace = await supercovLoadVite();\n\
972         import {{ resolve }} from 'node:path';\n\
973         import SupercovVitestReporter from './node_modules/vitestReporter.mjs';\n\
974         import {{ supercovViteInstrumentation }} from './viteInstrumentation.mjs';\n\
975         const vite = viteNamespace.default ?? viteNamespace;\n\
976         const {{ loadConfigFromFile, mergeConfig }} = vite;\n\
977         const discoveredConfig = {original};\n\
978         export default async function supercovVitestConfig(env) {{\n\
979           const originalPath = process.env.SUPERCOV_ORIGINAL_VITEST_CONFIG || discoveredConfig;\n\
980           const loaded = originalPath ? await loadConfigFromFile(env, originalPath, process.cwd()) : undefined;\n\
981           const config = mergeConfig(loaded?.config ?? {{}}, {{\n\
982             cacheDir: resolve(process.cwd(), '.supercov/vitest-cache'),\n\
983             plugins: [supercovViteInstrumentation(process.cwd())],\n\
984             test: {{ setupFiles: [resolve(process.cwd(), '.supercov/node_modules/vitest.mjs')], maxConcurrency: 1 }},\n\
985           }});\n\
986           const configuredReporters = loaded?.config?.test?.reporters;\n\
987           config.test ??= {{}};\n\
988           config.test.reporters = configuredReporters\n\
989             ? [...(Array.isArray(configuredReporters) ? configuredReporters : [configuredReporters]), new SupercovVitestReporter()]\n\
990             : ['default', new SupercovVitestReporter()];\n\
991           return config;\n\
992         }}\n"
993    );
994    atomic_write(&path, source.as_bytes())?;
995    Ok(path)
996}
997
998fn configure_playwright_runtime(
999    generated: &Path,
1000    project: &CoverageProject,
1001) -> Result<(), JavascriptFrontendError> {
1002    let adapter_path = generated.join("playwright.mjs");
1003    let mut adapter =
1004        fs::read_to_string(&adapter_path).map_err(|source| io_error(&adapter_path, source))?;
1005    adapter = adapter
1006        .replace("__SUPERCOV_PLAYWRIGHT_MODULE__", &project.playwright_module)
1007        .replace(
1008            "__SUPERCOV_PLAYWRIGHT_TEST_EXPORT__",
1009            &project.playwright_test_export,
1010        )
1011        // Baked in rather than read from the environment alone: pooled
1012        // runners execute Playwright inside VMs whose environment the host
1013        // cannot reach, while the generated file rides the workspace mount.
1014        .replace(
1015            "__SUPERCOV_PHASE_TIMING__",
1016            if std::env::var("SUPERCOV_PHASE_TIMING").as_deref() == Ok("1") {
1017                "1"
1018            } else {
1019                "0"
1020            },
1021        );
1022    if project.playwright_module != "@playwright/test" {
1023        // A facade module exports the project's whole test API, not just the
1024        // Playwright surface: its full export set must flow through the shim,
1025        // with only the interception points (`test`, `expect`, the discovered
1026        // test export) shadowed by the shim's own declarations. The discovered
1027        // per-name re-exports below stay as a fallback for CommonJS facades,
1028        // where `export *` only forwards statically detectable names.
1029        let facade = serde_json::to_string(&project.playwright_module)
1030            .expect("serializing a module specifier cannot fail");
1031        adapter = adapter.replace(
1032            "export * from \"@playwright/test\";",
1033            &format!("export * from {facade};"),
1034        );
1035    }
1036    let mut exports = Vec::new();
1037    if project.playwright_test_export != "test" {
1038        exports.push(format!(
1039            "export {{ instrumentedTest as {} }};",
1040            project.playwright_test_export
1041        ));
1042    }
1043    exports.extend(
1044        project
1045            .playwright_exports
1046            .iter()
1047            .filter(|name| {
1048                name.as_str() != "test"
1049                    && name.as_str() != "expect"
1050                    && *name != &project.playwright_test_export
1051            })
1052            .map(|name| {
1053                let encoded = serde_json::to_string(name)
1054                    .expect("serializing a JavaScript export name cannot fail");
1055                format!("export const {name} = __supercovAdapterExport(adapter[{encoded}]);")
1056            }),
1057    );
1058    adapter = adapter.replace("/*__SUPERCOV_ADAPTER_EXPORTS__*/", &exports.join("\n"));
1059    atomic_write(&adapter_path, adapter.as_bytes())?;
1060
1061    let loader_path = generated.join("resolve-loader.mjs");
1062    let loader = fs::read_to_string(&loader_path)
1063        .map_err(|source| io_error(&loader_path, source))?
1064        .replace("__SUPERCOV_PLAYWRIGHT_MODULE__", &project.playwright_module);
1065    atomic_write(&loader_path, loader.as_bytes())
1066}
1067
1068fn write_playwright_config(
1069    workspace: &Path,
1070    project: &CoverageProject,
1071    generated: &Path,
1072) -> Result<PathBuf, JavascriptFrontendError> {
1073    let path = generated.join("playwright.config.mjs");
1074    let original = relocated_project_file(workspace, project, project.playwright_config.as_ref());
1075    let original_import = if let Some(original) = &original {
1076        let relative = original
1077            .strip_prefix(workspace)
1078            .map_err(|_| JavascriptFrontendError::UnsafeSourcePath(original.display().to_string()))?
1079            .to_string_lossy()
1080            .replace('\\', "/");
1081        let specifier = serde_json::to_string(&format!("../{relative}"))
1082            .map_err(JavascriptFrontendError::Serialize)?;
1083        format!("import original from {specifier};\n")
1084    } else {
1085        "const original = {};\n".into()
1086    };
1087    let source = format!(
1088        "import './node_modules/register.mjs';\n\
1089         import {{ dirname, isAbsolute, relative, resolve }} from 'node:path';\n\
1090         import {{ fileURLToPath }} from 'node:url';\n\
1091         {original_import}\
1092         const resolvedValue = typeof original === 'function' ? await original({{ command: 'test', mode: 'test' }}) : original;\n\
1093         const resolved = resolvedValue ?? {{}};\n\
1094         const runtimeProjectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');\n\
1095         const originalDirectory = {};
1096         const sourceProjectRoot = process.env.SUPERCOV_SOURCE_PROJECT_ROOT;\n\
1097         const runtimePath = value => {{\n\
1098           if (!value) return value;\n\
1099           const absolute = isAbsolute(value) ? value : resolve(originalDirectory, value);\n\
1100           const local = relative(runtimeProjectRoot, absolute);\n\
1101           if (local === '' || (!local.startsWith('..') && !isAbsolute(local))) return absolute;\n\
1102           if (sourceProjectRoot) {{\n\
1103             const sourceLocal = relative(sourceProjectRoot, absolute);\n\
1104             if (sourceLocal === '' || (!sourceLocal.startsWith('..') && !isAbsolute(sourceLocal))) return resolve(runtimeProjectRoot, sourceLocal);\n\
1105           }}\n\
1106           throw new Error('Supercov refuses a Playwright output/cwd outside the isolated project: ' + absolute);\n\
1107         }};\n\
1108         const normalizeWebServer = server => server ? ({{ ...server, cwd: runtimePath(server.cwd ?? originalDirectory) }}) : server;\n\
1109         const normalized = {{ ...resolved,\n\
1110           testDir: runtimePath(resolved.testDir),\n\
1111           outputDir: runtimePath(resolved.outputDir),\n\
1112           snapshotDir: runtimePath(resolved.snapshotDir),\n\
1113           projects: resolved.projects?.map(project => ({{ ...project, testDir: runtimePath(project.testDir), outputDir: runtimePath(project.outputDir), snapshotDir: runtimePath(project.snapshotDir) }})),\n\
1114           webServer: Array.isArray(resolved.webServer) ? resolved.webServer.map(normalizeWebServer) : normalizeWebServer(resolved.webServer),\n\
1115         }};\n\
1116         const configuredReporters = normalized.reporter;\n\
1117         const reporters = configuredReporters\n\
1118           ? (typeof configuredReporters === 'string' ? [[configuredReporters]] : (Array.isArray(configuredReporters[0]) ? configuredReporters : [configuredReporters]))\n\
1119           : [['list']];\n\
1120         const coverageReporter = resolve(runtimeProjectRoot, '.supercov/node_modules/playwrightReporter.mjs');\n\
1121         export default {{ ...normalized, reporter: [...reporters, [coverageReporter]] }};\n",
1122        serde_json::to_string(
1123            &original
1124                .as_ref()
1125                .and_then(|path| path.parent())
1126                .unwrap_or(workspace)
1127                .display()
1128                .to_string()
1129        )
1130        .map_err(JavascriptFrontendError::Serialize)?
1131    );
1132    atomic_write(&path, source.as_bytes())?;
1133    Ok(path)
1134}
1135
1136fn write_vite_config(
1137    workspace: &Path,
1138    generated: &Path,
1139) -> Result<PathBuf, JavascriptFrontendError> {
1140    let path = generated.join("vite.config.mjs");
1141    let workspace = serde_json::to_string(&workspace.display().to_string())
1142        .map_err(JavascriptFrontendError::Serialize)?;
1143    let source = format!(
1144        "import {{ createRequire }} from 'node:module';\n\
1145         import {{ pathToFileURL }} from 'node:url';\n\
1146         // pnpm's strict layout does not hoist vite to the project root: it\n\
1147         // lives inside vitest's virtual store, so a bare 'vite' specifier\n\
1148         // resolved from this generated file fails. Vitest depends on vite, so\n\
1149         // fall back to resolving it through vitest's own tree rather than\n\
1150         // requiring the project to hoist anything.\n\
1151         const supercovRequire = createRequire(import.meta.url);\n\
1152         const supercovLoadVite = async () => {{\n\
1153           try {{\n\
1154             return await import('vite');\n\
1155           }} catch (error) {{\n\
1156             let entry;\n\
1157             try {{\n\
1158               entry = createRequire(supercovRequire.resolve('vitest')).resolve('vite');\n\
1159             }} catch {{\n\
1160               throw error;\n\
1161             }}\n\
1162             return await import(pathToFileURL(entry).href);\n\
1163           }}\n\
1164         }};\n\
1165         const viteNamespace = await supercovLoadVite();\n\
1166         import {{ isAbsolute, relative, resolve }} from 'node:path';\n\
1167         import {{ supercovViteInstrumentation }} from './viteInstrumentation.mjs';\n\
1168         const vite = viteNamespace.default ?? viteNamespace;\n\
1169         const {{ loadConfigFromFile, mergeConfig }} = vite;\n\
1170         export default async function supercovViteConfig(env) {{\n\
1171           const isolatedRoot = {workspace};\n\
1172           const loaded = await loadConfigFromFile(env, undefined, isolatedRoot);\n\
1173           const config = loaded?.config ?? {{}};\n\
1174           const relocate = (value, label) => {{\n\
1175             const absolute = isAbsolute(value) ? value : resolve(isolatedRoot, value);\n\
1176             const local = relative(isolatedRoot, absolute);\n\
1177             if (local === '' || (!local.startsWith('..') && !isAbsolute(local))) return absolute;\n\
1178             throw new Error('Supercov refuses ' + label + ' outside the isolated project: ' + absolute);\n\
1179           }};\n\
1180           const relocateOutput = output => output ? ({{ ...output, dir: output.dir ? relocate(output.dir, 'Rollup output') : output.dir, file: output.file ? relocate(output.file, 'Rollup output') : output.file }}) : output;\n\
1181           const rollupOutput = config.build?.rollupOptions?.output;\n\
1182           const safe = {{ ...config,\n\
1183             logLevel: ['1', 'true', 'yes'].includes(process.env.SUPERCOV_VERBOSE ?? process.env.SUPERCOV_DEBUG ?? '') ? config.logLevel : 'error',\n\
1184             cacheDir: resolve(isolatedRoot, '.supercov/vite-cache'),\n\
1185             build: {{ ...config.build, outDir: relocate(config.build?.outDir ?? 'dist', 'Vite build output'), rollupOptions: {{ ...config.build?.rollupOptions, output: Array.isArray(rollupOutput) ? rollupOutput.map(relocateOutput) : relocateOutput(rollupOutput) }} }},\n\
1186           }};\n\
1187           return mergeConfig(safe, {{ plugins: [supercovViteInstrumentation(isolatedRoot)] }});\n\
1188         }}\n"
1189    );
1190    atomic_write(&path, source.as_bytes())?;
1191    Ok(path)
1192}
1193
1194fn write_vite_transforms(
1195    generated: &Path,
1196    transforms: &BTreeMap<String, ViteTransform>,
1197) -> Result<(), JavascriptFrontendError> {
1198    let mut payload = serde_json::to_vec(transforms).map_err(JavascriptFrontendError::Serialize)?;
1199    payload.push(b'\n');
1200    atomic_write(&generated.join("vite-transforms.json"), &payload)?;
1201    let adapter = "import { createHash } from 'node:crypto';\n\
1202import { readFileSync } from 'node:fs';\n\
1203import { relative, resolve, sep } from 'node:path';\n\
1204const transforms = JSON.parse(readFileSync(new URL('./vite-transforms.json', import.meta.url), 'utf8'));\n\
1205const sha256 = value => createHash('sha256').update(value).digest('hex');\n\
1206export function supercovViteInstrumentation(root) {\n\
1207  const runtimePath = resolve(root, '.supercov/node_modules/applicationRuntime.mjs');\n\
1208  return {\n\
1209    name: 'supercov-rust-instrumentation',\n\
1210    enforce: 'pre',\n\
1211    resolveId(id) { return id === 'virtual:supercov-runtime' ? runtimePath : null; },\n\
1212    transform(code, rawId) {\n\
1213      const id = rawId.split('?')[0] ?? rawId;\n\
1214      const local = relative(root, id).split(sep).join('/');\n\
1215      const transformed = transforms[local];\n\
1216      if (!transformed) return null;\n\
1217      if (sha256(code) !== transformed.sourceSha256)\n\
1218        throw new Error('Supercov source changed before Rust instrumentation: ' + local);\n\
1219      return { code: transformed.code, map: transformed.map ?? null };\n\
1220    },\n\
1221  };\n\
1222}\n";
1223    atomic_write(
1224        &generated.join("viteInstrumentation.mjs"),
1225        adapter.as_bytes(),
1226    )
1227}
1228
1229/// Prepare the complete JavaScript frontend inside an isolated workspace.
1230/// The source project is read only through the copied workspace inventory.
1231pub fn prepare_javascript_frontend(
1232    workspace: &Path,
1233    project: &CoverageProject,
1234    collector_id: &str,
1235    cache_key: &str,
1236) -> Result<PreparedJavascriptFrontend, JavascriptFrontendError> {
1237    let generated = workspace.join(".supercov");
1238    // Runtime code files live under a node_modules segment: Node attributes
1239    // stack frames from node_modules paths to dependency infrastructure, so
1240    // deprecation warnings the user's own run would suppress (Node's
1241    // isInsideNodeModules check) stay suppressed when Supercov's module
1242    // hooks are on the call path.
1243    let runtime_directory = generated.join("node_modules");
1244    timed(&SETUP.runtime_ns, || {
1245        copy_runtime(&runtime_directory, collector_id)
1246    })?;
1247    let configuration_started = Instant::now();
1248    configure_playwright_runtime(&runtime_directory, project)?;
1249    let playwright_config_path = write_playwright_config(workspace, project, &generated)?;
1250    let vite_config_path = write_vite_config(workspace, &generated)?;
1251    let vitest_config_path = write_vitest_config(workspace, project, &generated)?;
1252    account(&SETUP.config_ns, configuration_started);
1253
1254    let mut decisions = BTreeMap::new();
1255    let mut points = BTreeMap::new();
1256    let mut branches = BTreeMap::new();
1257    let mut limitations = BTreeMap::new();
1258    let mut vite_transforms = BTreeMap::new();
1259    for limitation in &project.source_limitations {
1260        limitations.insert(limitation.id.clone(), limitation_from_source(limitation));
1261    }
1262
1263    let sources_started = Instant::now();
1264    for file in &project.source_files {
1265        let path = checked_source_path(workspace, file)?;
1266        let source = fs::read_to_string(&path).map_err(|source| io_error(&path, source))?;
1267        let capability_wrapper = runtime_specifier(file, "capability.mjs")?;
1268        let mut output = timed(&SETUP.instrument_ns, || match project.build_adapter {
1269            BuildAdapter::Vite | BuildAdapter::Generic => {
1270                instrument_candidate_with_runtime_hooks(&source, file, &capability_wrapper)
1271            }
1272            BuildAdapter::Direct => {
1273                instrument_direct_candidate_with_runtime_hooks(&source, file, &capability_wrapper)
1274            }
1275        })
1276        .map_err(|source| JavascriptFrontendError::Instrument {
1277            file: file.clone(),
1278            source,
1279        })?;
1280        if project.build_adapter == BuildAdapter::Generic {
1281            let runtime = generic_runtime_binding(workspace, project, &path, &generated)?;
1282            output.code = output.code.replace("virtual:supercov-runtime", &runtime);
1283        }
1284        // Direct commands can compile TypeScript themselves (`npm test` may
1285        // begin with `tsc`), so they need the same generated-source exemption
1286        // as Supercov's separately orchestrated generic build. Instrumentation
1287        // necessarily changes control-flow expressions in ways the host type
1288        // checker cannot narrow through, while source syntax remains covered
1289        // by the parser before this banner is applied.
1290        if project.build_adapter != BuildAdapter::Vite
1291            && matches!(
1292                path.extension().and_then(|value| value.to_str()),
1293                Some("ts" | "tsx" | "mts" | "cts")
1294            )
1295        {
1296            output.code = generated_source_banner(&output.code);
1297        }
1298        if project.build_adapter == BuildAdapter::Vite {
1299            vite_transforms.insert(
1300                file.clone(),
1301                ViteTransform {
1302                    source_sha256: format!("{:x}", Sha256::digest(source.as_bytes())),
1303                    code: output.code.clone(),
1304                    map: output.map.clone(),
1305                },
1306            );
1307        } else {
1308            // Attach the instrumentation source map inline, pointed at the
1309            // ORIGINAL project file with the original text embedded. Node runs
1310            // with --enable-source-maps, and tsx/esbuild chain input maps, so
1311            // stack traces show the user's real path and line numbers instead
1312            // of instrumented workspace positions -- Supercov stays invisible
1313            // in errors. Without this the map was generated and then dropped.
1314            let code = match inline_instrumentation_map(
1315                &output.code,
1316                output.map.as_ref(),
1317                &project.root.join(file),
1318                &source,
1319            ) {
1320                Some(code) => code,
1321                None => output.code.clone(),
1322            };
1323            atomic_write(&path, code.as_bytes())?;
1324        }
1325        for value in output.decisions {
1326            decisions.insert(value.id.clone(), value);
1327        }
1328        for value in output.points {
1329            points.insert(value.id.clone(), value);
1330        }
1331        for value in output.branches {
1332            branches.insert(value.id.clone(), value);
1333        }
1334        for value in output.coverage_limitations {
1335            limitations.insert(value.id.clone(), value);
1336        }
1337    }
1338    account(&SETUP.sources_ns, sources_started);
1339    write_vite_transforms(&generated, &vite_transforms)?;
1340
1341    let assertions_started = Instant::now();
1342    let mut assertion_calls = 0;
1343    for entry in &project.source_scope.entries {
1344        let path = checked_source_path(workspace, &entry.file)?;
1345        let Ok(source) = fs::read_to_string(&path) else {
1346            continue;
1347        };
1348        let capability_wrapper = (!project.source_files.contains(&entry.file))
1349            .then(|| runtime_specifier(&entry.file, "capability.mjs"))
1350            .transpose()?;
1351        let assertion_runtime = runtime_specifier(&entry.file, "runtime.mjs")?;
1352        let output = crate::js_instrumenter::instrument_node_assertion_phases_with_runtime_imports(
1353            &source,
1354            &entry.file,
1355            std::slice::from_ref(&project.playwright_module),
1356            capability_wrapper.as_deref(),
1357            Some(&assertion_runtime),
1358        )
1359        .map_err(|source| JavascriptFrontendError::Instrument {
1360            file: entry.file.clone(),
1361            source,
1362        })?;
1363        let coverage_transformed_by_vite = project.build_adapter == BuildAdapter::Vite
1364            && project.source_files.contains(&entry.file);
1365        if (output.assertions > 0 || output.capability_imports > 0) && !coverage_transformed_by_vite
1366        {
1367            atomic_write(&path, output.code.as_bytes())?;
1368            assertion_calls += output.assertions;
1369        }
1370    }
1371
1372    account(&SETUP.assertion_ns, assertions_started);
1373
1374    let mut manifest = JavascriptManifest {
1375        decisions: decisions.into_values().collect(),
1376        points: points.into_values().collect(),
1377        branches: branches.into_values().collect(),
1378        limitations: limitations.into_values().collect(),
1379        scope: project.source_scope.clone(),
1380    };
1381    manifest.decisions.sort_by_key(|value| {
1382        (
1383            value.file.clone(),
1384            value.line,
1385            value.column,
1386            value.id.clone(),
1387        )
1388    });
1389    manifest.points.sort_by_key(|value| {
1390        (
1391            value.file.clone(),
1392            value.line,
1393            value.column,
1394            value.id.clone(),
1395        )
1396    });
1397    manifest.branches.sort_by_key(|value| {
1398        (
1399            value.file.clone(),
1400            value.line,
1401            value.column,
1402            value.id.clone(),
1403        )
1404    });
1405    manifest.limitations.sort_by_key(|value| {
1406        (
1407            value.file.clone(),
1408            value.line,
1409            value.column,
1410            value.id.clone(),
1411        )
1412    });
1413
1414    let manifest_path = generated.join("manifest.json");
1415    let mut encoded =
1416        serde_json::to_vec_pretty(&manifest).map_err(JavascriptFrontendError::Serialize)?;
1417    encoded.push(b'\n');
1418    atomic_write(&manifest_path, &encoded)?;
1419    atomic_write(
1420        &generated.join("instrumentation-complete"),
1421        b"coverage-completeness-v2\n",
1422    )?;
1423    timed(&SETUP.cache_ns, || {
1424        write_javascript_frontend_cache(workspace, project, cache_key, assertion_calls)
1425    })?;
1426    Ok(PreparedJavascriptFrontend {
1427        manifest,
1428        manifest_path,
1429        preload_path: generated.join("node_modules/register.mjs"),
1430        playwright_config_path,
1431        vite_config_path,
1432        vitest_config_path,
1433        assertion_calls,
1434    })
1435}
1436
1437#[cfg(test)]
1438mod tests {
1439    #[test]
1440    fn ancestor_description_names_each_component_and_its_state() {
1441        let root = std::env::temp_dir().join(format!("supercov-ancestors-{}", unique()));
1442        fs::create_dir_all(root.join("present")).unwrap();
1443        fs::write(root.join("present/file.txt"), b"x").unwrap();
1444        let described = super::describe_ancestors(&root.join("present/file.txt/child"));
1445        assert!(described.contains("present=dir"), "{described}");
1446        assert!(described.contains("file.txt=file"), "{described}");
1447        assert!(described.ends_with("child=missing"), "{described}");
1448        fs::remove_dir_all(&root).unwrap();
1449    }
1450
1451    use super::*;
1452    use crate::project_discovery::discover_coverage_project;
1453
1454    fn temporary(name: &str) -> PathBuf {
1455        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1456            .join("../../target/supercov-test-fixtures")
1457            .join(format!("javascript-frontend-{name}-{}", unique()));
1458        // These tests validate frontend contents and manifest construction.
1459        // The dedicated workspace/platform suite owns directory-creation,
1460        // link, rename, ENOSPC, crash, and cleanup behavior on every OS. Keep
1461        // semantic fixtures in Cargo's ignored target tree so hosted-runner
1462        // policies on the system temporary directory cannot affect them.
1463        fs::create_dir_all(&path).unwrap();
1464        crate::workspace::canonicalize_simplified(path).unwrap()
1465    }
1466
1467    #[test]
1468    fn runtime_isolation_replaces_only_the_assignment_marker() {
1469        let source = concat!(
1470            "const runtimeInstanceToken = \"__SUPERCOV_RUNTIME_INSTANCE__\";\n",
1471            "const selected = runtimeInstanceToken === \"__SUPERCOV_\" + \"RUNTIME_INSTANCE__\";\n"
1472        );
1473        let isolated = isolate_runtime(source, "collector-123").unwrap();
1474        assert!(isolated.contains("runtimeInstanceToken = \"collector-123\""));
1475        assert!(isolated.contains("=== \"__SUPERCOV_\" + \"RUNTIME_INSTANCE__\""));
1476    }
1477
1478    #[test]
1479    fn copied_runtime_does_not_reference_unshipped_source_maps() {
1480        let generated = temporary("runtime-source-maps");
1481        copy_runtime(&generated, "collector-test").unwrap();
1482        for name in ["vitest.mjs", "provenance.mjs", "atomic.mjs"] {
1483            let contents = fs::read_to_string(generated.join(name)).unwrap();
1484            assert!(
1485                !contents.contains("sourceMappingURL"),
1486                "runtime shim retained a source-map directive: {name}"
1487            );
1488        }
1489        fs::remove_dir_all(generated).unwrap();
1490    }
1491
1492    #[test]
1493    fn prepares_sorted_complete_manifest_without_touching_source_project() {
1494        let source_root = temporary("source");
1495        let workspace = temporary("workspace");
1496        fs::create_dir_all(source_root.join("src")).unwrap();
1497        fs::write(
1498            source_root.join("src/example.mjs"),
1499            "export function value(a, b) { if (a || b) return 1; return 0; }\n",
1500        )
1501        .unwrap();
1502        fs::write(source_root.join("package.json"), "{\"type\":\"module\"}\n").unwrap();
1503        fs::create_dir_all(workspace.join("src")).unwrap();
1504        fs::create_dir_all(workspace.join(".supercov")).unwrap();
1505        fs::copy(
1506            source_root.join("src/example.mjs"),
1507            workspace.join("src/example.mjs"),
1508        )
1509        .unwrap();
1510        let project = discover_coverage_project(
1511            &source_root,
1512            &BTreeMap::new(),
1513            &["node".into(), "--test".into()],
1514        )
1515        .unwrap();
1516        let original = fs::read_to_string(source_root.join("src/example.mjs")).unwrap();
1517        let prepared =
1518            prepare_javascript_frontend(&workspace, &project, "collector-test", "cache-test")
1519                .unwrap();
1520        assert_eq!(
1521            fs::read_to_string(source_root.join("src/example.mjs")).unwrap(),
1522            original
1523        );
1524        let transformed = fs::read_to_string(workspace.join("src/example.mjs")).unwrap();
1525        assert!(transformed.contains("__SUPERCOV_DIRECT_RUNTIME__"));
1526        assert_eq!(prepared.manifest.decisions.len(), 1);
1527        assert!(!prepared.manifest.points.is_empty());
1528        assert_eq!(prepared.manifest.scope, project.source_scope);
1529        assert!(prepared.manifest_path.is_file());
1530        assert!(prepared.preload_path.is_file());
1531        assert!(prepared.playwright_config_path.is_file());
1532        assert!(prepared.vite_config_path.is_file());
1533        assert!(
1534            fs::read_to_string(&prepared.vite_config_path)
1535                .unwrap()
1536                .contains("logLevel: ['1', 'true', 'yes'].includes")
1537        );
1538        assert!(prepared.vitest_config_path.is_file());
1539        assert_eq!(prepared.assertion_calls, 0);
1540        let cache = read_javascript_frontend_cache(&workspace, "cache-test").unwrap();
1541        assert_eq!(
1542            javascript_frontend_reuse_paths(&cache),
1543            [
1544                PathBuf::from(".supercov/frontend-cache.json"),
1545                PathBuf::from(".supercov/frontend-cache-artifacts"),
1546            ]
1547        );
1548        assert!(
1549            cache
1550                .artifacts
1551                .iter()
1552                .all(|artifact| !artifact.cache_file.contains("src/")
1553                    && !artifact.cache_file.contains("tests/"))
1554        );
1555        fs::write(workspace.join("src/example.mjs"), &original).unwrap();
1556        fs::remove_file(&prepared.manifest_path).unwrap();
1557        let restored = load_cached_javascript_frontend(&workspace, &cache).unwrap();
1558        assert_eq!(restored.manifest, prepared.manifest);
1559        assert_eq!(
1560            fs::read_to_string(workspace.join("src/example.mjs")).unwrap(),
1561            transformed
1562        );
1563        fs::write(workspace.join(&cache.artifacts[0].cache_file), "corrupt").unwrap();
1564        assert!(read_javascript_frontend_cache(&workspace, "cache-test").is_none());
1565        fs::remove_dir_all(source_root).unwrap();
1566        fs::remove_dir_all(workspace).unwrap();
1567    }
1568
1569    #[test]
1570    fn embedded_runtime_contains_every_declared_shim() {
1571        for name in RUNTIME_FILES {
1572            let bytes = embedded_runtime(name).unwrap();
1573            assert!(!bytes.is_empty(), "embedded runtime is empty: {name}");
1574        }
1575        assert!(
1576            std::str::from_utf8(embedded_runtime("runtime.mjs").unwrap())
1577                .unwrap()
1578                .contains(RUNTIME_INSTANCE_MARKER)
1579        );
1580    }
1581}