1use std::{
4 collections::BTreeMap,
5 ffi::OsString,
6 path::{Path, PathBuf},
7 time::{Instant, SystemTime, UNIX_EPOCH},
8};
9
10use serde::{Deserialize, Serialize};
11use supercov_contracts::{
12 AttributionPrecision, ExecutionModel, FrontendAttribution, FrontendLimitation,
13 FrontendLimitationScope, FrontendRunDeclaration, FrontendRunnerDeclaration,
14 LANGUAGE_FRONTEND_PROTOCOL_VERSION, StructuralSource,
15};
16
17use crate::{
18 build_cache::{build_cache_key, read_build_cache, reuse_paths, write_build_cache},
19 coverage_report::{PersistedCoverageModel, RawTestResult, javascript_coverage_model},
20 evidence_archive::{
21 EvidenceArchiveEntry, EvidenceArchiveSource, collect_sources, write_archive,
22 },
23 integrity::{FrontendIntegrityInputs, create_run_integrity},
24 javascript_frontend::{
25 javascript_frontend_reuse_paths, load_cached_javascript_frontend,
26 prepare_javascript_frontend, read_javascript_frontend_cache,
27 },
28 lifecycle::{
29 ProjectLock, RunState, RunStateStatus, finalize_published_run, interrupt_run_state,
30 publish_run, recover_abandoned_runs, remove_stored_tree_deferred, update_run_state,
31 write_run_state,
32 },
33 orchestration::{
34 ExecutionPhase, ExecutionPlan, OrchestrationError, PhaseKind, execute_plan_with_supervisor,
35 },
36 process_supervision::{
37 CommandSpec, ForwardedSignal, ProcessSupervisor, SupervisionOptions, positive_milliseconds,
38 },
39 project_discovery::{BuildAdapter, discover_coverage_project},
40 run_store::{
41 InstrumentedBuildCache, RawEvidenceMetadata, RunIntegrity, RunMetadata, RunTimings,
42 },
43 workspace::{
44 cached_workspace_path, prepare_cached_workspace, prune_cached_workspace_sources,
45 sync_command_outputs, workspace_output_baseline,
46 },
47};
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase", deny_unknown_fields)]
51pub struct DirectJavascriptRunRequest {
52 pub root: PathBuf,
53 pub command: Vec<String>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub run_id: Option<String>,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub started_at: Option<String>,
58 #[serde(skip)]
59 pub watchdog_program: Option<PathBuf>,
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase", deny_unknown_fields)]
64pub struct DirectJavascriptRunResult {
65 pub run_id: String,
66 pub run_directory: PathBuf,
67 pub workspace: PathBuf,
68 pub exit_code: i32,
69 pub assertion_calls: usize,
70 pub recovered_runs: Vec<String>,
71 pub metadata: RunMetadata,
72}
73
74#[derive(Debug)]
75pub enum DirectJavascriptRunError {
76 Interrupted {
77 signal: ForwardedSignal,
78 exit_code: i32,
79 timings: RunTimings,
80 total_ms: f64,
81 },
82 Failed(String),
83}
84
85impl std::fmt::Display for DirectJavascriptRunError {
86 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 match self {
88 Self::Interrupted { signal, .. } => {
89 write!(formatter, "interrupted by {}", signal_name(*signal))
90 }
91 Self::Failed(message) => formatter.write_str(message),
92 }
93 }
94}
95
96impl std::error::Error for DirectJavascriptRunError {}
97
98impl From<String> for DirectJavascriptRunError {
99 fn from(value: String) -> Self {
100 Self::Failed(value)
101 }
102}
103
104fn signal_name(signal: ForwardedSignal) -> &'static str {
105 match signal {
106 ForwardedSignal::Sighup => "SIGHUP",
107 ForwardedSignal::Sigint => "SIGINT",
108 ForwardedSignal::Sigterm => "SIGTERM",
109 }
110}
111
112fn javascript_runner_declaration(
113 runner: String,
114 results: &[&RawTestResult],
115) -> FrontendRunnerDeclaration {
116 let has_observations = |raw: &&RawTestResult| {
117 !raw.phases.is_empty()
118 || !raw.server.is_empty()
119 || raw.runtime.iter().chain(&raw.browser).any(|snapshot| {
120 !snapshot.decisions.is_empty()
121 || !snapshot.hits.is_empty()
122 || !snapshot.events.is_empty()
123 })
124 };
125 let exact_test = results.iter().all(|raw| {
126 raw.test_id
127 .as_deref()
128 .is_some_and(|value| !value.is_empty())
129 && raw
130 .scope
131 .as_ref()
132 .is_none_or(|scope| raw.test_id.as_deref() == Some(scope.test_id.as_str()))
133 });
134 let exact_worker = results.iter().all(|raw| {
135 !has_observations(raw)
136 || raw
137 .scope
138 .as_ref()
139 .is_some_and(|scope| !scope.worker_id.is_empty())
140 });
141 let exact_retry = results.iter().all(|raw| {
142 raw.retry.is_some()
143 && raw
144 .scope
145 .as_ref()
146 .is_none_or(|scope| raw.retry == Some(scope.retry))
147 });
148 let contextual = !results.is_empty() && exact_test && exact_worker && exact_retry;
149 let precision = |exact| {
150 if exact {
151 AttributionPrecision::Exact
152 } else {
153 AttributionPrecision::Unavailable
154 }
155 };
156 let attribution = FrontendAttribution {
157 run: AttributionPrecision::Exact,
158 worker: precision(contextual),
159 test: precision(contextual),
160 retry: precision(contextual),
161 phase: precision(contextual),
162 action: precision(contextual),
163 assertion: precision(contextual),
164 };
165 let mut limitations = Vec::new();
166 if !contextual {
167 for (suffix, scope) in [
168 ("worker", FrontendLimitationScope::Worker),
169 ("test", FrontendLimitationScope::Test),
170 ("retry", FrontendLimitationScope::Retry),
171 ("phase", FrontendLimitationScope::Phase),
172 ("action", FrontendLimitationScope::Action),
173 ("assertion", FrontendLimitationScope::Assertion),
174 ] {
175 limitations.push(FrontendLimitation {
176 id: format!("{runner}-no-{suffix}").replace(':', "-"),
177 scopes: vec![scope],
178 reason: format!(
179 "Runner {runner} did not expose exact {suffix} identity for every result"
180 ),
181 });
182 }
183 }
184 FrontendRunnerDeclaration {
185 runner,
186 execution_model: if contextual {
187 ExecutionModel::ParallelContextPropagated
188 } else {
189 ExecutionModel::ParallelUnattributed
190 },
191 attribution,
192 limitations,
193 }
194}
195
196fn javascript_archive_entries(
197 mut entries: Vec<EvidenceArchiveEntry>,
198 manifest: &crate::javascript_frontend::JavascriptManifest,
199 run_id: &str,
200 exit_code: i32,
201) -> Result<Vec<EvidenceArchiveEntry>, String> {
202 let mut results = Vec::new();
203 for entry in &entries {
204 if entry.path == "mcdc.json" || entry.path.ends_with("/mcdc.json") {
205 results.push(
206 serde_json::from_slice::<RawTestResult>(&entry.contents)
207 .map_err(|error| format!("invalid {}: {error}", entry.path))?,
208 );
209 } else if entry.path == "mcdc.jsonl" || entry.path.ends_with(".mcdc.jsonl") {
210 let contents = entry
211 .contents
212 .strip_suffix(b"\n")
213 .ok_or_else(|| format!("{} does not end with a newline", entry.path))?;
214 for (index, line) in contents.split(|byte| *byte == b'\n').enumerate() {
215 if line.is_empty() {
216 return Err(format!(
217 "{} contains a blank record at line {}",
218 entry.path,
219 index + 1
220 ));
221 }
222 results.push(
223 serde_json::from_slice::<RawTestResult>(line).map_err(|error| {
224 format!(
225 "invalid {} record at line {}: {error}",
226 entry.path,
227 index + 1
228 )
229 })?,
230 );
231 }
232 }
233 }
234 if results.is_empty() {
235 let status = match exit_code {
236 0 => "passed",
237 supercov_contracts::COMMAND_TIMEOUT_EXIT_CODE => "timedOut",
238 _ => "failed",
239 };
240 let command_result = RawTestResult {
241 test_id: Some(format!("command:{run_id}")),
242 scope: None,
243 test: "Test command".into(),
244 test_file: None,
245 title: Some("Test command".into()),
246 retry: Some(0),
247 status: Some(status.into()),
248 expected_status: None,
249 flaky: false,
250 provenance: crate::coverage_report::TestProvenance {
251 runner: "command".into(),
252 kind: "setup".into(),
253 project: None,
254 source: "engine".into(),
255 },
256 role: "setup".into(),
257 attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
258 phases: vec![],
259 runtime: vec![],
260 browser: vec![],
261 server: vec![],
262 };
263 entries.push(EvidenceArchiveEntry {
264 path: "results/command/mcdc.json".into(),
265 contents: serde_json::to_vec(&command_result).map_err(|error| error.to_string())?,
266 });
267 results.push(command_result);
268 }
269 let mut by_runner = BTreeMap::<String, Vec<&RawTestResult>>::new();
270 for result in &results {
271 by_runner
272 .entry(result.provenance.runner.clone())
273 .or_default()
274 .push(result);
275 }
276 if entries
277 .iter()
278 .any(|entry| entry.path.starts_with("server/background/") && entry.path.ends_with(".jsonl"))
279 {
280 by_runner.entry("background".into()).or_default();
281 }
282 let declaration = FrontendRunDeclaration {
283 protocol_version: LANGUAGE_FRONTEND_PROTOCOL_VERSION,
284 frontend_id: "javascript".into(),
285 frontend_version: "javascript-owned-v1".into(),
286 language: "javascript".into(),
287 structural_source: StructuralSource::OwnedProbes,
288 runners: by_runner
289 .into_iter()
290 .map(|(runner, results)| javascript_runner_declaration(runner, &results))
291 .collect(),
292 structural_limitations: manifest
293 .limitations
294 .iter()
295 .map(|limitation| limitation.id.clone())
296 .collect(),
297 };
298 entries.push(EvidenceArchiveEntry {
299 path: "coverage-model.json".into(),
300 contents: serde_json::to_vec(
301 &PersistedCoverageModel::from_declaration(&javascript_coverage_model())
302 .expect("JavaScript coverage model is contract-valid"),
303 )
304 .map_err(|error| error.to_string())?,
305 });
306 entries.push(EvidenceArchiveEntry {
307 path: "frontend.json".into(),
308 contents: serde_json::to_vec(&declaration).map_err(|error| error.to_string())?,
309 });
310 Ok(entries)
311}
312
313struct RunCleanup {
314 root: PathBuf,
315 run_id: String,
316 started_at: String,
317 lock: ProjectLock,
318 workspace: Option<PathBuf>,
319 state_written: bool,
320 terminal_recorded: bool,
321}
322
323impl RunCleanup {
324 fn lock(&self) -> &ProjectLock {
325 &self.lock
326 }
327
328 fn set_workspace(&mut self, workspace: PathBuf) {
329 self.workspace = Some(workspace);
330 }
331
332 fn mark_state_written(&mut self) {
333 self.state_written = true;
334 }
335
336 fn mark_terminal(&mut self) {
337 self.terminal_recorded = true;
338 }
339}
340
341impl Drop for RunCleanup {
342 fn drop(&mut self) {
343 if self.state_written && !self.terminal_recorded {
344 let _ = update_run_state(
345 &self.root,
346 &self.run_id,
347 RunStateStatus::Failed,
348 &self.started_at,
349 Some("Rust run exited before reaching a terminal lifecycle state".into()),
350 );
351 }
352 if let Some(workspace) = &self.workspace {
353 let _ = remove_stored_tree_deferred(
354 &self.root,
355 &workspace.join(".supercov/evidence").join(&self.run_id),
356 );
357 let _ = remove_stored_tree_deferred(
358 &self.root,
359 &workspace
360 .join(".supercov/server-evidence")
361 .join(&self.run_id),
362 );
363 let keep_workspace =
364 std::env::var("SUPERCOV_KEEP_WORKSPACE").is_ok_and(|value| !value.is_empty());
365 if !keep_workspace {
366 let _ = prune_cached_workspace_sources(&self.root, &self.lock);
367 }
368 }
369 let _ = self.lock.release();
370 }
371}
372
373fn now_nonce() -> u128 {
374 SystemTime::now()
375 .duration_since(UNIX_EPOCH)
376 .unwrap_or_default()
377 .as_millis()
378}
379
380fn elapsed_ms(started: Instant) -> f64 {
381 started.elapsed().as_secs_f64() * 1000.0
382}
383
384fn rounded_millisecond(value: f64) -> f64 {
385 (value * 10.0).round() / 10.0
386}
387
388fn supervision_options() -> Result<SupervisionOptions, String> {
389 let defaults = SupervisionOptions::default();
390 Ok(SupervisionOptions {
391 diagnostic_interval: positive_milliseconds(
392 std::env::var("SUPERCOV_DIAGNOSTIC_INTERVAL_MS")
393 .ok()
394 .as_deref(),
395 "SUPERCOV_DIAGNOSTIC_INTERVAL_MS",
396 )
397 .map_err(|error| error.to_string())?
398 .unwrap_or(defaults.diagnostic_interval),
399 timeout: positive_milliseconds(
400 std::env::var("SUPERCOV_COMMAND_TIMEOUT_MS").ok().as_deref(),
401 "SUPERCOV_COMMAND_TIMEOUT_MS",
402 )
403 .map_err(|error| error.to_string())?,
404 termination_grace: defaults.termination_grace,
405 })
406}
407
408fn remove_derived_pnpm_config(environment: &mut BTreeMap<OsString, OsString>) {
409 const PNPM_ONLY_NPM_CONFIG: &[&str] = &[
415 "npm_config_auto_install_peers",
416 "npm_config_enable_pre_post_scripts",
417 "npm_config_shamefully_hoist",
418 ];
419 environment.retain(|key, _| {
420 let key = key.to_string_lossy().to_ascii_lowercase();
421 !PNPM_ONLY_NPM_CONFIG.contains(&key.as_str())
422 });
423}
424
425fn environment_with(values: BTreeMap<String, String>) -> Vec<(OsString, OsString)> {
426 let mut environment = std::env::vars_os().collect::<BTreeMap<_, _>>();
427 remove_derived_pnpm_config(&mut environment);
428 for (key, value) in values {
429 environment.retain(|existing, _| !existing.to_string_lossy().eq_ignore_ascii_case(&key));
430 environment.insert(key.into(), value.into());
431 }
432 environment.into_iter().collect()
433}
434
435fn node_options(preload: &Path) -> String {
436 let preload = std::path::absolute(preload).unwrap_or_else(|_| preload.to_path_buf());
442 [
448 std::env::var("NODE_OPTIONS").ok(),
449 Some("--enable-source-maps".into()),
450 Some(format!("--import={}", crate::workspace::file_url(&preload))),
451 ]
452 .into_iter()
453 .flatten()
454 .filter(|value| !value.is_empty())
455 .collect::<Vec<_>>()
456 .join(" ")
457}
458
459pub fn current_javascript_integrity(
463 root: &Path,
464 command: &[String],
465 source_roots: Option<&[String]>,
466) -> Result<RunIntegrity, String> {
467 let mut environment = std::env::vars().collect::<BTreeMap<_, _>>();
468 match source_roots.filter(|roots| !roots.is_empty()) {
473 Some(roots) => {
474 environment.insert(
475 crate::source_discovery::SOURCE_ROOTS_VARIABLE.into(),
476 roots.join(","),
477 );
478 }
479 None => {
480 environment.remove(crate::source_discovery::SOURCE_ROOTS_VARIABLE);
481 }
482 }
483 let project = discover_coverage_project(root, &environment, command)
484 .map_err(|error| error.to_string())?;
485 javascript_integrity_for_project(root, &project)
486}
487
488fn javascript_integrity_for_project(
489 root: &Path,
490 project: &crate::project_discovery::CoverageProject,
491) -> Result<RunIntegrity, String> {
492 let frontend = FrontendIntegrityInputs::embedded_javascript();
493 create_run_integrity(root, project, &frontend).map_err(|error| error.to_string())
494}
495
496pub fn run_direct_javascript(
499 request: &DirectJavascriptRunRequest,
500 diagnostics: &mut dyn std::io::Write,
501) -> Result<DirectJavascriptRunResult, DirectJavascriptRunError> {
502 if request.command.is_empty() {
503 return Err(DirectJavascriptRunError::Failed(
504 "test command must not be empty".into(),
505 ));
506 }
507 let total_started = Instant::now();
508 let initialization_started = Instant::now();
509 let root = crate::workspace::canonicalize_simplified(&request.root)
510 .map_err(|error| format!("{}: {error}", request.root.display()))?;
511 let nonce = now_nonce();
512 let run_id = request
513 .run_id
514 .clone()
515 .unwrap_or_else(|| format!("rust-{nonce}"));
516 let started_at = request
517 .started_at
518 .clone()
519 .unwrap_or_else(|| format!("unix-ms-{nonce}"));
520 let lock =
521 ProjectLock::acquire(&root, &run_id, &started_at).map_err(|error| error.to_string())?;
522 let mut cleanup = RunCleanup {
523 root: root.clone(),
524 run_id: run_id.clone(),
525 started_at: started_at.clone(),
526 lock,
527 workspace: None,
528 state_written: false,
529 terminal_recorded: false,
530 };
531 let recovered_runs =
532 recover_abandoned_runs(&root, &started_at).map_err(|error| error.to_string())?;
533 if !recovered_runs.is_empty() {
534 writeln!(
535 diagnostics,
536 "[supercov] recovered abandoned run(s): {}",
537 recovered_runs.join(", ")
538 )
539 .map_err(|error| error.to_string())?;
540 }
541 let environment = std::env::vars().collect::<BTreeMap<_, _>>();
542 let source_roots = crate::source_discovery::configured_source_roots(&environment);
543 let project = discover_coverage_project(&root, &environment, &request.command)
544 .map_err(|error| error.to_string())?;
545 let integrity = javascript_integrity_for_project(&root, &project)?;
546 let source_inputs = crate::source_capture::capture(
547 &root,
548 "javascript",
549 crate::integrity::javascript_assertion_paths(&root, &project).map_err(|e| e.to_string())?,
550 )?;
551 let build_cache_key = build_cache_key(&integrity, &project)?;
552 let frontend_cache_key = format!(
555 "{}:{}:{}:{}",
556 integrity.fingerprint.combined,
557 integrity.fingerprint.execution,
558 crate::source_manifest::digest(&request.command),
559 crate::source_manifest::digest(&project.root.to_string_lossy())
560 );
561 let prior_workspace = cached_workspace_path(&root).map_err(|error| error.to_string())?;
562 let reusable_build = if project.build_adapter == BuildAdapter::Direct {
563 None
564 } else {
565 read_build_cache(&prior_workspace, &build_cache_key)
566 };
567 let reusable_frontend = read_javascript_frontend_cache(&prior_workspace, &frontend_cache_key);
568 let mut cached_paths = reusable_build.as_ref().map(reuse_paths).unwrap_or_default();
569 if let Some(frontend) = &reusable_frontend {
570 cached_paths.extend(javascript_frontend_reuse_paths(frontend));
571 cached_paths.sort();
572 cached_paths.dedup();
573 }
574 let initialization_ms = elapsed_ms(initialization_started);
575
576 let workspace_started = Instant::now();
577 let workspace_progress = crate::progress::ProgressLine::start("preparing isolated workspace");
578 let workspace = prepare_cached_workspace(&root, cleanup.lock(), &cached_paths)
579 .map_err(|error| error.to_string())?;
580 drop(workspace_progress);
581 cleanup.set_workspace(workspace.clone());
582 if let Err(error) = crate::workspace::mirror_git_repository(&root, &workspace)
583 && std::env::var_os("SUPERCOV_DEBUG").is_some()
584 {
585 eprintln!("[supercov] the workspace has no git repository of its own: {error}");
586 }
587 let workspace_preparation_ms = elapsed_ms(workspace_started);
588 writeln!(
589 diagnostics,
590 "[supercov] instrumenting isolated workspace {}",
591 workspace.display()
592 )
593 .map_err(|error| error.to_string())?;
594 cleanup.mark_state_written();
595 write_run_state(
596 &root,
597 &RunState {
598 id: run_id.clone(),
599 pid: std::process::id(),
600 root: root.display().to_string(),
601 workspace: workspace.display().to_string(),
602 started_at: started_at.clone(),
603 updated_at: started_at.clone(),
604 status: RunStateStatus::Preparing,
605 signal: None,
606 error: None,
607 },
608 )
609 .map_err(|error| error.to_string())?;
610
611 let adapter_started = Instant::now();
612 let instrumentation_progress = crate::progress::ProgressLine::start("instrumenting sources");
613 let collector_id = format!("collector-{}", integrity.fingerprint.execution);
614 let frontend = if let Some(cache) = &reusable_frontend {
615 load_cached_javascript_frontend(&workspace, cache)
616 } else {
617 prepare_javascript_frontend(
618 &workspace,
619 &project,
620 &collector_id,
621 &frontend_cache_key,
622 &request.command,
623 )
624 }
625 .map_err(|error| error.to_string())?;
626 crate::workspace::hide_rewritten_files(
627 &workspace,
628 &crate::javascript_frontend::rewritten_files(&workspace),
629 );
630 drop(instrumentation_progress);
631 let adapter_setup_ms = elapsed_ms(adapter_started);
632 if let Some(detail) = crate::javascript_frontend::setup_timing_detail() {
633 writeln!(diagnostics, "[supercov] {detail}").map_err(|error| error.to_string())?;
634 }
635
636 let evidence_relative = format!(".supercov/evidence/{run_id}");
637 let evidence_directory = workspace.join(&evidence_relative);
638 let server_evidence_root = workspace.join(".supercov/server-evidence");
639 let diagnostic_owner = workspace.join(format!(".supercov/diagnostic-owner-{run_id}"));
640 let mut overrides = BTreeMap::from([
641 ("NODE_OPTIONS".into(), node_options(&frontend.preload_path)),
642 ("SUPERCOV_CJS_INTERCEPT".into(), "1".into()),
643 ("SUPERCOV_DIRECT_INSTRUMENTATION".into(), "1".into()),
644 ("TAP_ALLOW_INCOMPLETE_COVERAGE".into(), "1".into()),
649 (
653 "SUPERCOV_EVIDENCE_DIR".into(),
654 evidence_directory.display().to_string(),
655 ),
656 (
657 "SUPERCOV_DIAGNOSTIC_OWNER_FILE".into(),
658 diagnostic_owner.display().to_string(),
659 ),
660 (
661 "SUPERCOV_EXECUTION_FINGERPRINT".into(),
662 integrity.fingerprint.execution.clone(),
663 ),
664 (
665 "SUPERCOV_EXECUTION_LOG".into(),
666 evidence_directory
667 .join("execution.jsonl")
668 .display()
669 .to_string(),
670 ),
671 (
672 "SUPERCOV_MANIFEST".into(),
673 frontend.manifest_path.display().to_string(),
674 ),
675 (
676 "SUPERCOV_PROJECT_ROOT".into(),
677 workspace.display().to_string(),
678 ),
679 ("SUPERCOV_RUN_ID".into(), run_id.clone()),
680 (
681 "SUPERCOV_SERVER_EVIDENCE_ROOT".into(),
682 server_evidence_root.display().to_string(),
683 ),
684 (
685 "SUPERCOV_SOURCE_PROJECT_ROOT".into(),
686 root.display().to_string(),
687 ),
688 ]);
689 overrides.insert(
693 "SUPERCOV_GENERATED_VITEST_CONFIG".into(),
694 frontend.vitest_config_path.display().to_string(),
695 );
696 overrides.insert(
697 "SUPERCOV_GENERATED_PLAYWRIGHT_CONFIG".into(),
698 frontend.playwright_config_path.display().to_string(),
699 );
700 overrides.insert(
701 "SUPERCOV_PLAYWRIGHT_MODULE".into(),
702 project.playwright_module.clone(),
703 );
704 overrides.insert(
705 "SUPERCOV_PLAYWRIGHT_TEST_EXPORT".into(),
706 project.playwright_test_export.clone(),
707 );
708 overrides.insert(
709 "SUPERCOV_PLAYWRIGHT_WRAPPER".into(),
710 "./.supercov/node_modules/playwright.mjs".into(),
711 );
712 if let Some(original) = project
713 .playwright_config
714 .as_ref()
715 .and_then(|path| path.strip_prefix(&root).ok())
716 .map(|path| workspace.join(path))
717 {
718 overrides.insert(
719 "SUPERCOV_ORIGINAL_PLAYWRIGHT_CONFIG".into(),
720 original.display().to_string(),
721 );
722 }
723 overrides.extend(project.build_environment.clone());
724 let settings = serde_json::json!({
728 "root": workspace.display().to_string(),
729 "environment": overrides
730 .iter()
731 .filter(|(name, _)| name.starts_with("SUPERCOV_"))
732 .collect::<BTreeMap<_, _>>(),
733 });
734 let settings_path = frontend.preload_path.with_file_name("run.json");
735 std::fs::write(
736 &settings_path,
737 serde_json::to_vec(&settings).map_err(|error| error.to_string())?,
738 )
739 .map_err(|error| format!("{}: {error}", settings_path.display()))?;
740 let preparation = if reusable_build.is_some() {
741 writeln!(
742 diagnostics,
743 "[supercov] reusing exact-fingerprint instrumented build {}",
744 &build_cache_key[..12]
745 )
746 .map_err(|error| error.to_string())?;
747 Vec::new()
748 } else if project.build_adapter != BuildAdapter::Direct {
749 let mut arguments = project.build_command[1..]
750 .iter()
751 .map(OsString::from)
752 .collect::<Vec<_>>();
753 if project.build_adapter == BuildAdapter::Vite {
754 let npm = Path::new(&project.build_command[0])
757 .file_stem()
758 .is_some_and(|name| name.eq_ignore_ascii_case("npm"));
759 if npm {
760 arguments.push(OsString::from("--"));
761 }
762 arguments.extend([
763 OsString::from("--config"),
764 OsString::from(".supercov/vite.config.mjs"),
765 OsString::from("--logLevel"),
766 OsString::from("error"),
767 ]);
768 }
769 let mut build_overrides = overrides.clone();
770 build_overrides.insert("NODE_ENV".into(), "production".into());
771 build_overrides.insert("npm_config_loglevel".into(), "error".into());
772 let build_environment = environment_with(build_overrides);
773 vec![ExecutionPhase {
774 name: "build".into(),
775 kind: PhaseKind::Build,
776 command: CommandSpec {
777 program: project.build_command[0].clone().into(),
778 arguments,
779 cwd: workspace.clone(),
780 environment: Some(build_environment),
781 captured_output: Some(
782 workspace
783 .join(".supercov")
784 .join(format!("build-output-{run_id}.log")),
785 ),
786 },
787 }]
788 } else {
789 Vec::new()
790 };
791 let plan = ExecutionPlan {
792 preparation,
793 test: ExecutionPhase {
794 name: "test".into(),
795 kind: PhaseKind::Test,
796 command: CommandSpec {
797 program: request.command[0].clone().into(),
798 arguments: request.command[1..].iter().map(OsString::from).collect(),
799 cwd: workspace.clone(),
800 environment: Some(environment_with(overrides)),
801 captured_output: None,
802 },
803 },
804 };
805 let options = supervision_options()?;
806 let watchdog_program = request.watchdog_program.as_ref().ok_or_else(|| {
807 DirectJavascriptRunError::Failed(
808 "the JavaScript run is missing its crash-containment executable".into(),
809 )
810 })?;
811 let supervisor = ProcessSupervisor::new_crash_safe(watchdog_program)
812 .map_err(|error| DirectJavascriptRunError::Failed(error.to_string()))?;
813 let output_baseline = std::cell::RefCell::new(None);
814 let execution = match execute_plan_with_supervisor(
815 &supervisor,
816 &plan,
817 options,
818 diagnostics,
819 |phase, diagnostics| {
820 let status = if phase.kind == PhaseKind::Test {
821 *output_baseline.borrow_mut() =
825 Some(workspace_output_baseline(&workspace).map_err(|error| {
826 OrchestrationError::PhaseSetup {
827 phase: phase.name.clone(),
828 reason: error.to_string(),
829 }
830 })?);
831 if frontend.assertion_calls > 0 {
832 writeln!(
833 diagnostics,
834 "[supercov] attributed {} native node:assert call(s)",
835 frontend.assertion_calls
836 )
837 .map_err(|error| OrchestrationError::PhaseSetup {
838 phase: phase.name.clone(),
839 reason: error.to_string(),
840 })?;
841 }
842 writeln!(
843 diagnostics,
844 "[supercov] running in isolated workspace: {}",
845 request.command.join(" ")
846 )
847 .map_err(|error| OrchestrationError::PhaseSetup {
848 phase: phase.name.clone(),
849 reason: error.to_string(),
850 })?;
851 RunStateStatus::Testing
852 } else {
853 RunStateStatus::Building
854 };
855 update_run_state(&root, &run_id, status, &started_at, None).map_err(|error| {
856 OrchestrationError::PhaseSetup {
857 phase: phase.name.clone(),
858 reason: error.to_string(),
859 }
860 })?;
861 Ok(())
862 },
863 ) {
864 Ok(execution) => execution,
865 Err(error) => {
866 let message = error.to_string();
867 let state_updated = update_run_state(
868 &root,
869 &run_id,
870 RunStateStatus::Failed,
871 &started_at,
872 Some(message.clone()),
873 )
874 .is_ok();
875 if state_updated {
876 cleanup.mark_terminal();
877 }
878 return Err(message.into());
879 }
880 };
881 let instrumented_build_ms = execution
882 .phases
883 .iter()
884 .find(|phase| phase.kind == PhaseKind::Build)
885 .map_or(0.0, |phase| phase.duration_ms as f64);
886 let test_command_ms = execution
887 .phases
888 .iter()
889 .find(|phase| phase.kind == PhaseKind::Test)
890 .map_or(0.0, |phase| phase.duration_ms as f64);
891 let build_succeeded = execution
892 .phases
893 .iter()
894 .find(|phase| phase.kind == PhaseKind::Build)
895 .is_some_and(|phase| phase.result.exit_code() == 0);
896 if project.build_adapter != BuildAdapter::Direct && reusable_build.is_none() && build_succeeded
897 {
898 write_build_cache(&root, &workspace, &build_cache_key, &started_at)?;
899 }
900 if let Some(signal) = execution.interrupted_signal {
901 interrupt_run_state(&root, &run_id, &started_at, signal_name(signal))
902 .map_err(|error| error.to_string())?;
903 cleanup.mark_terminal();
904 return Err(DirectJavascriptRunError::Interrupted {
905 signal,
906 exit_code: execution.exit_code,
907 timings: RunTimings {
908 initialization_ms: rounded_millisecond(initialization_ms),
909 workspace_preparation_ms: rounded_millisecond(workspace_preparation_ms),
910 adapter_setup_ms: rounded_millisecond(adapter_setup_ms),
911 instrumented_build_ms: rounded_millisecond(instrumented_build_ms),
912 test_command_ms: rounded_millisecond(test_command_ms),
913 evidence_publication_ms: 0.0,
914 },
915 total_ms: rounded_millisecond(elapsed_ms(total_started)),
916 });
917 }
918 if let Some(baseline) = output_baseline.borrow().as_ref() {
923 let protected = project
924 .source_files
925 .iter()
926 .map(PathBuf::from)
927 .collect::<std::collections::BTreeSet<_>>();
928 let outputs = sync_command_outputs(&root, &workspace, baseline, &protected)
929 .map_err(|error| error.to_string())?;
930 if outputs.synced > 0 {
931 let _ = writeln!(
932 diagnostics,
933 "[supercov] synced {} file(s) the command created or changed back to the project",
934 outputs.synced
935 );
936 }
937 if !outputs.skipped_instrumented.is_empty() {
938 let _ = writeln!(
939 diagnostics,
940 "[supercov] {} file(s) stayed in the isolated workspace: they are instrumented copies, or were built from them, and must not overwrite your project: {}",
941 outputs.skipped_instrumented.len(),
942 outputs
943 .skipped_instrumented
944 .iter()
945 .take(3)
946 .map(|path| path.display().to_string())
947 .collect::<Vec<_>>()
948 .join(", ")
949 );
950 }
951 if !outputs.deleted_in_workspace.is_empty() {
952 let _ = writeln!(
953 diagnostics,
954 "[supercov] the command deleted {} file(s) in the isolated workspace; deletions are not propagated to the project",
955 outputs.deleted_in_workspace.len()
956 );
957 }
958 }
959 update_run_state(
960 &root,
961 &run_id,
962 RunStateStatus::Publishing,
963 &started_at,
964 None,
965 )
966 .map_err(|error| error.to_string())?;
967
968 let publication_started = Instant::now();
969 let archive_path = root
970 .join(".supercov/work")
971 .join(&run_id)
972 .join("evidence.raw.gz");
973 let entries = collect_sources(&[
974 EvidenceArchiveSource::File {
975 file: frontend.manifest_path,
976 path: "manifest.json".into(),
977 },
978 EvidenceArchiveSource::File {
979 file: workspace.join(".supercov/statement-exclusions.json"),
980 path: "statement-exclusions.json".into(),
981 },
982 EvidenceArchiveSource::Directory {
983 directory: evidence_directory,
984 prefix: None,
985 },
986 EvidenceArchiveSource::Directory {
987 directory: server_evidence_root.join(&run_id),
988 prefix: Some("server".into()),
989 },
990 ])
991 .map_err(|error| error.to_string())?;
992 let entries =
993 javascript_archive_entries(entries, &frontend.manifest, &run_id, execution.exit_code)?;
994 let entries = crate::source_capture::append(entries, &source_inputs)?;
995 let raw = write_archive(entries, &archive_path).map_err(|error| error.to_string())?;
996 remove_stored_tree_deferred(&root, &workspace.join(".supercov/evidence"))
997 .map_err(|error| error.to_string())?;
998 remove_stored_tree_deferred(&root, &server_evidence_root).map_err(|error| error.to_string())?;
999 let evidence_publication_ms = elapsed_ms(publication_started);
1000 let timings = RunTimings {
1001 initialization_ms: rounded_millisecond(initialization_ms),
1002 workspace_preparation_ms: rounded_millisecond(workspace_preparation_ms),
1003 adapter_setup_ms: rounded_millisecond(adapter_setup_ms),
1004 instrumented_build_ms: rounded_millisecond(instrumented_build_ms),
1005 test_command_ms: rounded_millisecond(test_command_ms),
1006 evidence_publication_ms: rounded_millisecond(evidence_publication_ms),
1007 };
1008 let metadata = RunMetadata {
1009 id: run_id.clone(),
1010 started_at: started_at.clone(),
1011 duration_ms: rounded_millisecond(elapsed_ms(total_started)),
1012 command: request.command.clone(),
1013 test_exit_code: Some(execution.exit_code),
1014 integrity,
1015 raw_evidence: RawEvidenceMetadata {
1016 schema_version: raw.schema_version,
1017 format: raw.format.into(),
1018 file: raw.file.into(),
1019 files: raw.files,
1020 uncompressed_bytes: raw.uncompressed_bytes,
1021 compressed_bytes: raw.compressed_bytes,
1022 },
1023 isolated_build: Some(true),
1024 instrumented_build_cache: Some(InstrumentedBuildCache {
1025 key: build_cache_key,
1026 reused: reusable_build.is_some(),
1027 }),
1028 timings: Some(timings),
1029 merged: None,
1030 parents: None,
1031 source_roots: source_roots.clone(),
1032 };
1033 let run_directory =
1034 publish_run(&root, &metadata, &archive_path).map_err(|error| error.to_string())?;
1035 let terminal_status = if execution.exit_code == 0 {
1036 RunStateStatus::Complete
1037 } else {
1038 RunStateStatus::Failed
1039 };
1040 update_run_state(&root, &run_id, terminal_status, &started_at, None)
1041 .map_err(|error| error.to_string())?;
1042 finalize_published_run(&root, &run_id).map_err(|error| error.to_string())?;
1043 cleanup.mark_terminal();
1044 Ok(DirectJavascriptRunResult {
1045 run_id,
1046 run_directory,
1047 workspace,
1048 exit_code: execution.exit_code,
1049 assertion_calls: frontend.assertion_calls,
1050 recovered_runs,
1051 metadata,
1052 })
1053}
1054
1055#[cfg(test)]
1056mod environment_tests {
1057 use super::*;
1058
1059 #[test]
1060 fn nested_npm_drops_only_pnpm_derived_environment_aliases() {
1061 let mut environment = BTreeMap::from([
1062 ("npm_config_auto_install_peers".into(), "true".into()),
1063 ("NPM_CONFIG_SHAMEFULLY_HOIST".into(), "true".into()),
1064 (
1065 "npm_config_registry".into(),
1066 "https://registry.npmjs.org".into(),
1067 ),
1068 ("USER_VALUE".into(), "kept".into()),
1069 ]);
1070 remove_derived_pnpm_config(&mut environment);
1071 assert_eq!(
1072 environment,
1073 BTreeMap::from([
1074 ("USER_VALUE".into(), "kept".into()),
1075 (
1076 "npm_config_registry".into(),
1077 "https://registry.npmjs.org".into()
1078 ),
1079 ])
1080 );
1081 }
1082}