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