Skip to main content

bynk_driver/
test_runner.rs

1//! `bynk test`'s shared command body (Wave 5 §5.4, findings
2//! #40/#72/#20/#21 remainder): compile the project's test declarations, write
3//! them, and run them via `tsc → node` (falling back to `tsx`), folding the
4//! result into the pinned [`crate::test_json::TestRun`] document in
5//! `--format json` mode. Moved down from the old `bynkc` crate.
6//!
7//! Runners are found with [`crate::probe::detect`] and
8//! [`crate::probe::DetectOpts::default()`] (no project-local search, no `npx`
9//! fallback), the one detection implementation both CLIs share for
10//! `doctor`/`dev`. #1758: each is spawned by the path detection resolved, not by
11//! its bare name, so a Windows npm shim (`tsc.cmd`) runs, and a runner that is
12//! found but won't start is reported as such rather than as missing.
13
14use crate::emsg;
15use bynk_project::env_protocol;
16use std::path::{Path, PathBuf};
17use std::process::{Command as ProcCommand, ExitCode, Stdio};
18
19use crate::project::{BuildTarget, ImportExt, ProjectOutput};
20use clap::ValueEnum;
21
22use crate::npm_install::PackageManager;
23use crate::test_json::{Case, Location, Suite, TestRun};
24
25/// `test --format` selector, used by `bynk test` (review
26/// findings #40/#72): one enum both CLIs' `Test` subcommand uses, instead of
27/// two structurally-identical copies that must be hand-kept in sync.
28#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
29pub enum TestFormat {
30    /// The grouped `✓ / ✗` human output (the default; unchanged behaviour).
31    #[default]
32    Rich,
33    /// A single pinned JSON document of results, for tooling and CI.
34    Json,
35    /// One JSON event per line as each is produced, for a consumer that wants
36    /// results while the run is going (see [`crate::test_stream`]).
37    Ndjson,
38}
39
40/// The `test` subcommand's flags — the one contract `bynk test`
41/// `#[command(flatten)]`s (review findings #40/#72/#20/#21
42/// remainder), replacing independent hand-spellings in each CLI.
43/// Field docs here are the CLI help text for both commands' flags.
44#[derive(clap::Args, Debug, Clone)]
45pub struct TestArgs {
46    /// Input project root directory. Defaults to the current directory.
47    #[arg(default_value = ".")]
48    pub input: PathBuf,
49    /// Run over each project directly inside a directory that has no
50    /// `bynk.toml` of its own (#3274): as at a `[workspace]` root, one report
51    /// per project under a `── path ──` header, every project run, and a
52    /// non-zero exit if any fails. A subdirectory without a `bynk.toml` is not
53    /// a project and is skipped. At a workspace root it changes nothing; at a
54    /// project, or inside one, it is an error. The flags that name one
55    /// project's output (`--format json`, `--output`, `--mutate`, `--against`)
56    /// are refused, as at a workspace root.
57    #[arg(long)]
58    pub each: bool,
59    /// Where to write compiled TypeScript test runner modules.
60    /// Defaults to `<input>/out`.
61    #[arg(short, long)]
62    pub output: Option<PathBuf>,
63    /// Skip the runner invocation. With `--format rich` this emits the
64    /// generated test files (for CI flows that drive the runner separately);
65    /// with `--format json` it emits a discovery document listing every
66    /// suite and case (each `outcome: "discovered"`) without running them —
67    /// a pure compile, no `tsc`/Node.
68    #[arg(long)]
69    pub no_run: bool,
70    /// Fail (exit non-zero) when the project declares no tests, instead of the
71    /// default warning with exit 0. Applies with `--no-run` too, so a
72    /// discovery-only CI step can enforce it.
73    #[arg(long)]
74    pub require_tests: bool,
75    /// Output format. `rich` (default) is the grouped ✓ / ✗ human output;
76    /// `json` is a single pinned JSON document of results, for tooling;
77    /// `ndjson` is the same results as one JSON event per line, written as
78    /// each suite finishes. `ndjson` cannot be combined with `--coverage` or
79    /// `--no-run`.
80    #[arg(long, value_enum, default_value_t = TestFormat::Rich)]
81    pub format: TestFormat,
82    /// Compile a debug build and launch the test runner under Node's
83    /// inspector (`node --inspect-brk`), printing the inspector URL for a
84    /// JavaScript debugger to attach. The emitted `.ts` runs directly under
85    /// Node's line-preserving type-stripping, so source maps resolve
86    /// breakpoints back to `.bynk`. Requires Node ≥ 22.18 (or ≥ 23.6
87    /// unflagged). Does not run `tsc`.
88    #[arg(long)]
89    pub inspect: bool,
90    /// The root seed for generative `property` tests, as hex (e.g. `0x5f3a`).
91    /// A failing property prints the seed it used; re-running with `--seed
92    /// <hex>` reproduces that run byte-for-byte. Omitted, each run draws a
93    /// fresh random seed.
94    #[arg(long)]
95    pub seed: Option<String>,
96    /// Run only the test cases named `<name>`, skipping the rest — the filter
97    /// behind the editor's per-case `▷ Run Test` lens. Matches by exact case
98    /// name across suites. Repeat the flag to run several cases in one
99    /// process; values of the same flag combine as "or", and with `--suite`
100    /// as "and". A name that selects no case fails the run. Omitted, every
101    /// case runs. No effect with `--no-run` (discovery lists all cases
102    /// regardless).
103    #[arg(long, value_name = "NAME")]
104    pub case: Vec<String>,
105    /// Run only the cases of the suite named `<name>`, as the JSON document
106    /// reports it (`suites[].name`, without an integration suite's prefix);
107    /// any suite kind matches. Repeat the flag to select several suites. A
108    /// suite that is not selected is left out of the output entirely. A name
109    /// that selects no suite fails the run. No effect with `--no-run`.
110    #[arg(long, value_name = "NAME")]
111    pub suite: Vec<String>,
112    /// For a caller that runs one selection as several processes (`bynk test`
113    /// across a workspace's members, `--against dev` across `env` groups): this
114    /// run sees only part of the `--case`/`--suite` selection, so a value it
115    /// selects nothing for is not an error here. The caller judges the values.
116    #[arg(long, hide = true)]
117    pub partial_selection: bool,
118    /// After the suite runs, report statement/line coverage attributed to
119    /// `.bynk` source (a rich summary table, or a `coverage` block in
120    /// `--format json`). Requires the `tsc → node` path: incompatible with
121    /// `--inspect` and `--no-run`, and errors if only `tsx` is available.
122    #[arg(long)]
123    pub coverage: bool,
124    /// Run the `system` suites against a real runtime instead of in process:
125    /// `dev`, a local `bynk dev` the runner starts itself (through `bynk
126    /// test` only), or a target named under `[test.targets]` in `bynk.toml`.
127    /// A bare URL is refused, and so is a target marked `production = true`.
128    /// A named target's secrets are read from the environment. Only the
129    /// `system` suites run, and a case that uses what a real runtime can't
130    /// honour (an `on call` address, `advance Clock`, a cron or queue address,
131    /// an asset fetch) is refused unless `--skip-unsupported` is passed.
132    #[arg(long, value_name = "TARGET")]
133    pub against: Option<String>,
134    /// With `--against`, skip each `system` case a real runtime can't
135    /// honour, naming it and why, instead of refusing the run.
136    #[arg(long, requires = "against")]
137    pub skip_unsupported: bool,
138    /// With `--against`, how long a failing `expect` is retried before it
139    /// fails, for each retried stretch: the addresses since the last unsafe one (anything but `GET`,
140    /// `HEAD` or `OPTIONS`) are re-run before each retry, so a real system's
141    /// latency doesn't fail a case. A duration such as `5s`, `500ms` or `0`
142    /// (no retry).
143    #[arg(
144        long,
145        value_name = "DURATION",
146        requires = "against",
147        default_value = "5s"
148    )]
149    pub settle: Option<String>,
150    /// Run a smoke test of every `from http` route instead of the project's
151    /// own suites (#2658): each route is called with arguments `Val`
152    /// fabricates and must not answer a 5xx or a body that does not decode; a
153    /// route with a JSON body must reject a malformed one, and a route behind
154    /// an actor must refuse a call with no credential. A route whose arguments
155    /// or principal can't be fabricated is skipped and named. Combine with
156    /// `--against` to smoke a running system.
157    #[arg(long)]
158    pub smoke: bool,
159    /// With `--smoke`, print the synthesised suites as `.bynk` source and run
160    /// nothing: a starting point to copy into `tests/` and extend.
161    #[arg(long, requires = "smoke")]
162    pub print: bool,
163    /// With `--smoke --against <target>`, also call the routes that write
164    /// (`POST`, `PUT`, `PATCH`, `DELETE`). Without it a named target sees only
165    /// `GET` requests, since fabricated writes would land on a shared
166    /// deployment. In process and against `dev` every route is called.
167    #[arg(long, requires = "smoke")]
168    pub smoke_unsafe: bool,
169    /// Do not install the generated project's npm packages: stop, naming the
170    /// install command and its directory, when one is missing. For projects that
171    /// provision `node_modules` themselves, and CI. Also set by
172    /// `BYNK_NO_INSTALL=1`.
173    #[arg(long)]
174    pub no_install: bool,
175    /// Record snapshots instead of comparing against them: write a snapshot that
176    /// is not stored yet, refresh one whose value changed, and delete the
177    /// obsolete ones (those no `expect … matches snapshot` names any more).
178    /// Without it a missing snapshot fails the case, a changed one fails with a
179    /// diff, and an obsolete one is only reported. The files are
180    /// `snapshots/<suite file>.snap.json`, for review like code. Cannot be
181    /// combined with `--against`, `--smoke`, `--coverage`, `--inspect` or `--no-run`.
182    #[arg(long)]
183    pub update_snapshots: bool,
184    /// Not a flag. The file holding a smoke run's declared response statuses
185    /// (`smoke::DECLARED_ENV`), set by `bynk`, which computes the table with
186    /// `bynk-ide`. Left `None` (as library callers and tests do), the runner
187    /// reads the variable from the environment (#2998, E1).
188    #[arg(skip)]
189    pub declared_statuses: Option<PathBuf>,
190    /// Not a flag. The `bynk` binary that starts `bynk dev` for
191    /// `--against dev`, set by `bynk` itself (it is that binary). Left `None`
192    /// (as library callers and tests do), it is read from
193    /// [`crate::remote::DEV_COMMAND_ENV`].
194    #[arg(skip)]
195    pub dev_command: Option<PathBuf>,
196    /// Check that the suites would notice a small change to the code (#3069):
197    /// apply typed mutations to `src/` one at a time (a comparison operator
198    /// swapped, `&&` and `||` exchanged), run the suites that exercise the
199    /// changed unit against each, and report the mutants that survive with
200    /// their source spans. Nothing in the working tree is written. The
201    /// unmutated project must pass first. Cannot be combined with `--inspect`,
202    /// `--no-run`, `--coverage`, `--against`, `--smoke`, `--update-snapshots`,
203    /// `--case` or `--format ndjson`.
204    #[arg(long)]
205    pub mutate: bool,
206    /// With `--mutate`, mutate only the declaration `<unit.decl>` (for example
207    /// `orders.refund`), or every declaration of the unit `<unit>`.
208    #[arg(long, value_name = "DECL", requires = "mutate")]
209    pub only: Option<String>,
210    /// With `--mutate`, stop after this many mutants (in source order).
211    #[arg(long, value_name = "N", requires = "mutate")]
212    pub max_mutants: Option<usize>,
213    /// With `--mutate`, kill a mutant's run after this many seconds and count
214    /// it killed by timeout. Default: three times the unmutated run, at least
215    /// ten seconds.
216    #[arg(long, value_name = "SECONDS", requires = "mutate")]
217    pub mutate_timeout: Option<u64>,
218    /// With `--mutate`, run every suite against every mutant, not only the
219    /// suites that target the mutated unit or a unit that uses it.
220    #[arg(long, requires = "mutate")]
221    pub mutate_all_suites: bool,
222    /// With `--mutate`, exit non-zero when fewer than this percentage of the
223    /// mutants that ran were killed, or when no mutant reached a suite at all.
224    /// Without it surviving mutants are reported but do not fail the run.
225    #[arg(long, value_name = "PERCENT", requires = "mutate")]
226    pub mutate_fail_under: Option<u32>,
227    /// With `--mutate`, mutate only the declarations in files that differ from
228    /// `<GIT_REF>` (#3134): the files `git diff <GIT_REF>` names, plus files git
229    /// does not track yet. The same mutants are reported as without the flag,
230    /// minus those in unchanged files.
231    #[arg(long, value_name = "GIT_REF", requires = "mutate")]
232    pub changed: Option<String>,
233    /// With `--mutate`, run this many mutants at once, each in its own scratch
234    /// output directory (#3134). The report does not depend on it: the same
235    /// mutants, in the same order, with the same ids. Default 1.
236    #[arg(
237        long,
238        value_name = "N",
239        requires = "mutate",
240        value_parser = clap::value_parser!(u64).range(1..=256)
241    )]
242    pub mutate_jobs: Option<u64>,
243    /// Not a flag. One source file's text, replacing what is on disk for this
244    /// build: the mutant `--mutate` is running. The path is the key the
245    /// project's source map holds the file under.
246    #[arg(skip)]
247    pub mutant_overlay: Option<(PathBuf, String)>,
248    /// Not a flag. Kill the test process, and fail the run, after this long.
249    #[arg(skip)]
250    pub run_timeout: Option<std::time::Duration>,
251    /// Not a flag. Source files layered over the project's for this build, as
252    /// `--sources-stdin` does for `compile`, with the new ones it adds: the
253    /// synthetic suite of a `bynk eval` snippet (#3585) and the caller's unsaved
254    /// buffers.
255    #[arg(skip)]
256    pub overlay: Option<std::collections::HashMap<PathBuf, String>>,
257}
258
259impl TestArgs {
260    /// The arguments of `test <input> --no-run --format json`: discovery only.
261    pub(crate) fn discovery(input: PathBuf) -> Self {
262        TestArgs {
263            input,
264            each: false,
265            output: None,
266            no_run: true,
267            require_tests: false,
268            format: TestFormat::Json,
269            inspect: false,
270            seed: None,
271            case: Vec::new(),
272            suite: Vec::new(),
273            partial_selection: false,
274            coverage: false,
275            against: None,
276            skip_unsupported: false,
277            settle: None,
278            smoke: false,
279            print: false,
280            smoke_unsafe: false,
281            no_install: false,
282            update_snapshots: false,
283            declared_statuses: None,
284            dev_command: None,
285            mutate: false,
286            only: None,
287            max_mutants: None,
288            mutate_timeout: None,
289            mutate_all_suites: false,
290            mutate_fail_under: None,
291            changed: None,
292            mutate_jobs: None,
293            mutant_overlay: None,
294            run_timeout: None,
295            overlay: None,
296        }
297    }
298}
299
300/// Every (suite, case) the projects at `members` declare, by discovery, to judge
301/// a `--suite`/`--case` value against. `None` when any member does not compile
302/// or answers something else: the runs report that, and a value is not judged
303/// against a partial picture.
304pub fn discover_cases(program: &str, members: &[PathBuf]) -> Option<Vec<(String, String)>> {
305    let mut available = Vec::new();
306    for member in members {
307        let (_, text) =
308            crate::test_stream::capture(|| run_test(program, TestArgs::discovery(member.clone())));
309        let doc: serde_json::Value = serde_json::from_str(&text).ok()?;
310        if doc.get("error").is_some() {
311            return None;
312        }
313        for suite in doc.get("suites")?.as_array()? {
314            let name = suite.get("name")?.as_str()?;
315            for case in suite.get("cases")?.as_array()? {
316                available.push((name.to_string(), case.get("name")?.as_str()?.to_string()));
317            }
318        }
319    }
320    Some(available)
321}
322
323/// Where `test` writes its output: `-o`, or `<input>/out`.
324fn output_root_for(input: &Path, output: Option<&Path>) -> PathBuf {
325    output.map_or_else(|| input.join("out"), Path::to_path_buf)
326}
327
328/// Normalise a `--seed` value (`0x5f3a` or `5f3a`) to the bare-hex form the
329/// runner reads from `BYNK_TEST_SEED` (JS `parseInt(_, 16)` does not accept a
330/// `0x` prefix). Returns `None` for a non-hex value, so a typo is ignored rather
331/// than silently seeding to zero.
332fn normalise_seed(raw: &str) -> Option<String> {
333    let hex = raw
334        .strip_prefix("0x")
335        .or_else(|| raw.strip_prefix("0X"))
336        .unwrap_or(raw);
337    if hex.is_empty() || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
338        return None;
339    }
340    Some(hex.to_string())
341}
342
343/// In `--format json` mode the deterministic surface is the document on stdout,
344/// so a `<program> test:` line on stderr is fine but must never reach stdout.
345/// `program` prefixes stderr messages (`"bynk"`) so they read the
346/// same as before the move.
347pub fn run_test(program: &str, args: TestArgs) -> ExitCode {
348    let TestArgs {
349        input,
350        output,
351        no_run,
352        require_tests,
353        format,
354        inspect,
355        seed,
356        case,
357        suite,
358        partial_selection,
359        coverage,
360        against,
361        skip_unsupported,
362        settle,
363        smoke,
364        print,
365        smoke_unsafe,
366        no_install,
367        update_snapshots,
368        declared_statuses,
369        dev_command,
370        mutate,
371        only,
372        max_mutants,
373        mutate_timeout,
374        mutate_all_suites,
375        mutate_fail_under,
376        changed,
377        mutate_jobs,
378        mutant_overlay,
379        run_timeout,
380        overlay,
381        // #3274: resolved by the caller, which runs each project on its own.
382        each: _,
383    } = args;
384    // `json` is "machine-readable": the document or the stream. `stream` says
385    // which; everything that prints a document goes through `print_run`.
386    let stream = format == TestFormat::Ndjson;
387    let json = format == TestFormat::Json || stream;
388    // #2267 (decision D): coverage is a whole-run aggregate and discovery is a
389    // document, so neither is a stream; `--format json` serves both.
390    if stream && (coverage || no_run) {
391        let message = if coverage {
392            "`--format ndjson` cannot be combined with `--coverage`: coverage is a whole-run report, so use `--format json`."
393        } else {
394            "`--format ndjson` cannot be combined with `--no-run`: discovery is a document, so use `--format json`."
395        };
396        crate::test_stream::print_run(true, &TestRun::runtime_error(message, None));
397        return ExitCode::FAILURE;
398    }
399    // #3069: `--mutate` re-runs the suites against mutants of `src/`; the runs
400    // it needs are each a plain in-process run, made below by this function.
401    if mutate {
402        let with = [
403            (inspect, "--inspect"),
404            (no_run, "--no-run"),
405            (coverage, "--coverage"),
406            (against.is_some(), "--against"),
407            (smoke, "--smoke"),
408            (update_snapshots, "--update-snapshots"),
409            (!case.is_empty(), "--case"),
410            (stream, "--format ndjson"),
411        ]
412        .into_iter()
413        .find_map(|(set, flag)| set.then_some(flag));
414        if let Some(flag) = with {
415            let message = format!(
416                "`--mutate` cannot be combined with `{flag}`: it re-runs the project's own suites in process, against mutants."
417            );
418            if json {
419                crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
420            } else {
421                emsg!("{program} test: error: {message}");
422            }
423            return ExitCode::FAILURE;
424        }
425        return crate::mutate::run(
426            program,
427            crate::mutate::MutateArgs {
428                input,
429                json,
430                seed,
431                suite,
432                only,
433                max_mutants,
434                timeout: mutate_timeout.map(std::time::Duration::from_secs),
435                all_suites: mutate_all_suites,
436                fail_under: mutate_fail_under,
437                changed,
438                jobs: mutate_jobs.map_or(1, |n| n as usize),
439            },
440        );
441    }
442    // #2842: `--update-snapshots` records what an in-process run computed, so it
443    // is refused where the run is not that, or is not a full run of the suites.
444    if update_snapshots {
445        let with = [
446            (against.is_some(), "--against"),
447            (smoke, "--smoke"),
448            (coverage, "--coverage"),
449            (inspect, "--inspect"),
450            (no_run, "--no-run"),
451        ]
452        .into_iter()
453        .find_map(|(set, flag)| set.then_some(flag));
454        if let Some(flag) = with {
455            let message = format!(
456                "`--update-snapshots` cannot be combined with `{flag}`: snapshots are recorded from an in-process run of the project's own suites."
457            );
458            if json {
459                crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
460            } else {
461                emsg!("{program} test: error: {message}");
462            }
463            return ExitCode::FAILURE;
464        }
465    }
466    // #2138: `--against` — resolve and check the target before anything is
467    // built, so a refused run makes no request. `dev` starts a local `bynk dev`
468    // through the `bynk` binary named by `dev_command` / `BYNK_DEV_COMMAND`
469    // (the `bynk` CLI sets it); without one it is refused.
470    let mut remote = match against.as_deref() {
471        None => None,
472        Some(value) => {
473            let refused = |message: String| {
474                if json {
475                    crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
476                } else {
477                    emsg!("{program} test: error: {message}");
478                }
479                ExitCode::FAILURE
480            };
481            let settle_ms = match settle.as_deref().map(crate::remote::parse_settle) {
482                None => crate::remote::DEFAULT_SETTLE_MS,
483                Some(Ok(ms)) => ms,
484                Some(Err(e)) => return refused(e),
485            };
486            if inspect || coverage {
487                return refused(
488                    "`--against` cannot be combined with `--inspect` or `--coverage`, which observe the in-process run".to_string(),
489                );
490            }
491            match crate::remote::resolve(
492                value,
493                &input,
494                |name| match &dev_command {
495                    Some(bynk) if name == crate::remote::DEV_COMMAND_ENV => {
496                        Some(bynk.to_string_lossy().into_owned())
497                    }
498                    _ => std::env::var(name).ok(),
499                },
500                "starts a local `bynk dev`, and no `bynk` binary was given to start it with (set `BYNK_DEV_COMMAND`, or run `bynk test --against dev`, which supplies one)",
501            ) {
502                Ok(crate::remote::Against::Run(run)) => {
503                    Some(crate::remote::RemoteRun { settle_ms, ..run })
504                }
505                Ok(crate::remote::Against::StartDev(bynk)) => {
506                    return crate::dev_run::run(
507                        program,
508                        &crate::dev_run::DevRunArgs {
509                            input: input.clone(),
510                            output: output_root_for(&input, output.as_deref()),
511                            json,
512                            stream,
513                            seed: seed.clone(),
514                            filter: crate::test_filter::TestFilter::new(&suite, &case),
515                            skip_unsupported,
516                            settle: settle.clone(),
517                            run_id: crate::remote::fresh_run_id(),
518                            bynk,
519                            smoke,
520                        },
521                    );
522                }
523                Err(refusal) => return refused(refusal.to_string()),
524            }
525        }
526    };
527    // #854 DECISION C: `--coverage` requires the `tsc → node` path — the CI-shaped
528    // path with real `.js.map`s. `--inspect` is a debug path with no `tsc` (and a
529    // different map role), and `--no-run` never launches a process to observe.
530    // Reject both up front with an actionable message rather than producing
531    // silently-wrong or empty numbers.
532    if coverage && inspect {
533        return coverage_unsupported(
534            program,
535            json,
536            "`--coverage` cannot be combined with `--inspect` — coverage needs the `tsc → node` run, not the inspector.",
537        );
538    }
539    if coverage && no_run {
540        return coverage_unsupported(
541            program,
542            json,
543            "`--coverage` cannot be combined with `--no-run` — there is no run to measure.",
544        );
545    }
546    // v0.127 (editor-currency slice 6): the per-case run filter, #2273: now a set
547    // of cases and suites. An empty value is dropped, so an empty `--case` is
548    // still unset (run all) rather than "match the empty name".
549    let filter = crate::test_filter::TestFilter::new(&suite, &case).partial(partial_selection);
550    // v0.114: the root seed for generative `property` tests, threaded to the
551    // runner via `BYNK_TEST_SEED` (bare hex). An unparseable value is dropped
552    // with a warning so a run still proceeds with a fresh seed.
553    let seed_hex = match seed.as_deref() {
554        Some(raw) => match normalise_seed(raw) {
555            Some(hex) => Some(hex),
556            None => {
557                if !json {
558                    emsg!(
559                        "{program} test: warning: ignoring --seed `{raw}` (not a hex value like 0x5f3a)"
560                    );
561                }
562                None
563            }
564        },
565        None => None,
566    };
567    let output_root = output_root_for(&input, output.as_deref());
568    if !input.is_dir() {
569        emsg!(
570            "{program} test: error: input `{}` must be a project directory containing `.bynk` files",
571            input.display()
572        );
573        return ExitCode::FAILURE;
574    }
575    // v0.9.1: rooting strategy (#46: shared with check/compile via
576    // `project_options`) — a `bynk.toml` or `src/` subdir selects split-paths
577    // mode (sources under `[paths] src`, tests under `[paths] tests`); else the
578    // legacy single-tree where `<input>` is both the source and tests root.
579    // `--inspect` compiles a debug build: `.ts` import specifiers so the emitted
580    // entry runs directly under Node's strip-only type-stripping (slice 2), where
581    // slice 1's source maps apply unchanged. A normal run keeps `.js` specifiers
582    // for the `tsc → node` path.
583    let options = {
584        // v0.115: `test` compiles the dev/test profile — the function
585        // contract call-site guard is emitted (DECISION J). `compile`
586        // leaves it off, so contract checks never reach production.
587        // #2078: reconcile events against the committed `bynk.schema.lock`,
588        // read-only — a non-additive change fails `test` as it fails a
589        // build, and `out.schema_lock` is never written back.
590        let o = match crate::try_project_options(&input)
591            .map_err(|e| e.to_string())
592            .and_then(|o| Ok(o.schema_registry(crate::schema_lock::read_only(&input)?)))
593            // #3107: the `dev` profile, so `[profile.dev] contracts = false`
594            // turns the guard off for a test run; on by default.
595            .and_then(
596                |o| Ok(o.contracts(crate::project_contracts(&input, crate::CliProfile::Dev)?)),
597            )
598            // #2842: the stored snapshots, inlined into the test modules.
599            .and_then(|o| {
600                let files = bynk_project::snapshots::read_snapshot_files(&input)
601                    .map_err(|e| format!("could not read `snapshots/`: {e}"))?;
602                Ok(o.snapshot_files(files))
603            }) {
604            Ok(o) => match with_overlays(o, &input, mutant_overlay, overlay) {
605                Ok(o) => o,
606                Err(e) => return fail_run(program, json, stream, e),
607            },
608            Err(e) => return fail_run(program, json, stream, e),
609        };
610        // #2138: a remote run emits only the `system` suites, driven at
611        // the target's URLs.
612        let o = o.remote_tests(remote.as_ref().map(|run| crate::project::RemoteTests {
613            skip_unsupported,
614            vars: run.vars.clone(),
615            secrets: run.secrets.clone(),
616            dev: run.dev_env.is_some(),
617            only_env: run.dev_env.clone(),
618        }));
619        if inspect {
620            o.import_ext(ImportExt::Ts)
621        } else {
622            o
623        }
624    };
625    // #2658: a smoke run builds the synthesised suites in place of the
626    // project's own. Against a named target only `GET` routes are called
627    // unless `--smoke-unsafe`; in process and against `dev` every route is.
628    let mut smoke_skips: Vec<(String, crate::project::RemoteSkip)> = Vec::new();
629    let options = if smoke {
630        let methods = match remote.as_ref() {
631            Some(run) if run.dev_env.is_none() && !smoke_unsafe => crate::smoke::Methods::SafeOnly,
632            _ => crate::smoke::Methods::All,
633        };
634        // One `--against dev` group's run: the run that started it reported.
635        let report = std::env::var_os(crate::remote::DEV_URLS_ENV).is_none();
636        match crate::smoke::prepare(program, options, methods, json, stream, report && !print) {
637            Ok(mut prepared) => {
638                if print {
639                    print!("{}", prepared.smoke.print(&input));
640                    return ExitCode::SUCCESS;
641                }
642                smoke_skips = prepared.smoke.remote_skips();
643                prepared.options
644            }
645            Err(code) => return code,
646        }
647    } else {
648        options
649    };
650    let out = match crate::project::compile_project(&options) {
651        Ok(out) => out,
652        Err(failure) => {
653            if json {
654                crate::test_stream::print_run(
655                    stream,
656                    &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
657                );
658            } else {
659                crate::print_project_failure(&failure);
660            }
661            return ExitCode::FAILURE;
662        }
663    };
664    // #2461: a fenced `bynk` example in a doc comment is checked as a `case` in
665    // a synthetic suite on its unit. Only once the project itself compiles, so
666    // an example is never blamed for an error elsewhere; a failing example
667    // fails the run before anything is emitted or run. An example marked
668    // `bynk test` is then compiled in and run like any other case.
669    let mut out = out;
670    let mut doc_aliases: Vec<(String, String)> = Vec::new();
671    // A remote run builds only the `system` suites, and a smoke run only the
672    // smoke, so neither has doc examples.
673    if remote.is_none()
674        && !smoke
675        && let Some(sources) = &options.sources
676    {
677        let docs = crate::doc_examples::DocExamples::collect(sources);
678        if !docs.is_empty() {
679            let mut errors = Vec::new();
680            let mut checked = None;
681            if docs.has_base() {
682                let check = crate::project::check_project(
683                    &options.clone().sources(docs.check_overlay(sources)),
684                );
685                errors.extend(docs.remap(check.errors));
686                checked = Some((check.snapshots, check.display_root));
687            }
688            // A declaration fence in a context is checked in a copy of it,
689            // one project check per layer of copies.
690            for layer in 0..docs.layer_count() {
691                let check = crate::project::check_project(
692                    &options.clone().sources(docs.layer_overlay(layer, sources)),
693                );
694                errors.extend(docs.remap_layer(layer, check.errors));
695                checked = Some((check.snapshots, check.display_root));
696            }
697            let (snapshots, display_root) = checked.expect("a check ran");
698            if !errors.is_empty() {
699                let failure = crate::project::ProjectFailure {
700                    errors,
701                    snapshots,
702                    display_root,
703                };
704                if json {
705                    crate::test_stream::print_run(
706                        stream,
707                        &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
708                    );
709                } else {
710                    crate::print_project_failure(&failure);
711                }
712                return ExitCode::FAILURE;
713            }
714            if docs.has_runnable() {
715                out = match crate::project::compile_project(
716                    &options.clone().sources(docs.run_overlay(sources)),
717                ) {
718                    Ok(out) => out,
719                    Err(failure) => {
720                        if json {
721                            crate::test_stream::print_run(
722                                stream,
723                                &TestRun::compile_error(crate::project_failure_short_lines(
724                                    &failure,
725                                )),
726                            );
727                        } else {
728                            crate::print_project_failure(&failure);
729                        }
730                        return ExitCode::FAILURE;
731                    }
732                };
733                doc_aliases = docs.run_aliases();
734                // A doc test's location is the real file's, line and column.
735                for case in out.discovered.iter_mut().flat_map(|s| s.cases.iter_mut()) {
736                    if let Some(loc) = case.location.as_mut() {
737                        // The synthetic file is where a doc example's case lives.
738                        case.doc = crate::doc_examples::is_synthetic_path(&loc.path, &doc_aliases);
739                        loc.path = crate::doc_examples::apply_aliases(&loc.path, &doc_aliases)
740                            .into_owned();
741                    }
742                }
743            }
744        }
745    }
746    // v0.67: `--no-run --format json` is pure discovery — render the suite/case
747    // manifest the compile retained and stop. No TS is written, no `tsc`/`node`
748    // runs, and the integration workers re-compile below is skipped (the manifest
749    // already carries integration suites from the compile above). A compile
750    // failure took the `compile`-error path above, exactly as a run would.
751    if no_run && json {
752        let suites = discovery_suites(&out);
753        if suites.is_empty() && require_tests {
754            return report_no_tests(program, &input, true, stream, true);
755        }
756        crate::test_stream::print_run(stream, &TestRun::discovered(suites));
757        return ExitCode::SUCCESS;
758    }
759    // #2842: the project's snapshots for this run. A remote or smoke run builds
760    // only some of the suites, so it neither compares nor reports them.
761    let snapshot_run = if smoke || remote.is_some() {
762        None
763    } else {
764        let stored = bynk_project::snapshots::read_snapshot_files(&input).unwrap_or_default();
765        crate::snapshots::SnapshotRun::new(
766            update_snapshots,
767            &input,
768            out.snapshot_files.clone(),
769            stored,
770        )
771    };
772    // #2138: the cases the remote build skipped, and the target, named before
773    // the first request.
774    if let Some(run) = remote.as_mut() {
775        run.skipped = out
776            .discovered
777            .iter()
778            .flat_map(|s| s.skipped.iter().map(|k| (s.name.clone(), k.clone())))
779            .collect();
780        eprint!("{program} test: {}", run.banner());
781        if !json {
782            for (suite, skip) in run
783                .skipped
784                .iter()
785                .filter(|(suite, skip)| filter.selects(suite, &skip.case))
786            {
787                eprintln!(
788                    "{program} test: skipped `{suite}` case \"{}\" [{}]: {}",
789                    skip.case, skip.code, skip.reason
790                );
791            }
792        }
793        // The smoke's skips were reported when they were decided.
794        run.skipped.append(&mut smoke_skips);
795    }
796
797    // Write every artefact to disk under the output root.
798    let mut wrote_any_test = false;
799    let mut has_integration = false;
800    for (path, doc) in &out.artefacts.docs {
801        // Map-aware write (slice 2): carries the `.ts.map` siblings + trailers so
802        // a debug run (`--inspect`) can resolve `.bynk` breakpoints. Harmless for a
803        // normal run, which transpiles via `tsc` and ignores the trailer.
804        if let Err(e) = crate::write_document(path, doc, &out.artefacts.docs, &output_root) {
805            emsg!(
806                "{program} test: error: could not write `{}`: {e}",
807                output_root.join(path).display()
808            );
809            return ExitCode::FAILURE;
810        }
811        let rel = path.to_string_lossy();
812        if rel.starts_with("tests/") {
813            wrote_any_test = true;
814        }
815        if rel.starts_with("tests/integration_") {
816            has_integration = true;
817        }
818    }
819
820    // v0.16: integration tests stand their participants up as real Workers, so
821    // they import the workers-mode output (`workers/**`) and the serialise/
822    // deserialise helpers the workers commons emit. The bundle compile above
823    // does not produce those, so run a second compile in workers mode and
824    // overlay everything except the `tests/` tree (whose unit modules import
825    // the bundle output). The workers commons are a strict superset of the
826    // bundle ones, so overwriting them is safe for the bundle code too.
827    let mut workers_modules = None;
828    if has_integration {
829        // v0.115/slice 2: reuse `options` (not a fresh `project_options(&input)`)
830        // so this second compile keeps `contracts(true)` and, under `--inspect`,
831        // `import_ext(Ts)` — a from-scratch rebuild silently dropped both.
832        let workers_out =
833            crate::project::compile_project(&options.clone().target(BuildTarget::Workers));
834        let workers_out = match workers_out {
835            Ok(o) => o,
836            Err(failure) => {
837                if json {
838                    crate::test_stream::print_run(
839                        stream,
840                        &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
841                    );
842                } else {
843                    crate::print_project_failure(&failure);
844                }
845                return ExitCode::FAILURE;
846            }
847        };
848        for (path, doc) in &workers_out.artefacts.docs {
849            if path.to_string_lossy().starts_with("tests/") {
850                continue;
851            }
852            if let Err(e) =
853                crate::write_document(path, doc, &workers_out.artefacts.docs, &output_root)
854            {
855                emsg!(
856                    "{program} test: error: could not write `{}`: {e}",
857                    output_root.join(path).display()
858                );
859                return ExitCode::FAILURE;
860            }
861        }
862        workers_modules = Some(workers_out.artefacts);
863    }
864
865    if let Err(code) = finish_output(program, &output_root, &out, workers_modules.as_ref()) {
866        return code;
867    }
868
869    if !wrote_any_test {
870        return report_no_tests(program, &input, require_tests, stream, json);
871    }
872
873    let main_ts = output_root.join("tests").join("main.ts");
874    if no_run {
875        // Rich `--no-run` is the CI emit helper: write the runner modules and
876        // report where they landed. (JSON `--no-run` already returned above with
877        // the discovery document — it never reaches here.)
878        emsg!("{program} test: tests emitted to {}", main_ts.display());
879        return ExitCode::SUCCESS;
880    }
881
882    // Slice 2 (ADR 0104): launch the emitted `.ts` test entry directly under
883    // Node's inspector. No `tsc` — the `.ts` runs under line-preserving
884    // type-stripping, so the source maps written above resolve `.bynk`
885    // breakpoints. Node prints its inspector URL; a debugger attaches there.
886    if inspect {
887        return run_inspect(program, &main_ts, seed_hex.as_deref(), &filter, smoke);
888    }
889
890    let tsconfig = output_root.join("tsconfig.json");
891    // #854: coverage needs tsc's `.js.map`s (remap hop 1). Overwrite the default
892    // tsconfig the compile wrote with the `sourceMap: true` variant, kept
893    // coverage-only so a normal test run / deployment build ships no maps.
894    if coverage
895        && let Err(e) = std::fs::write(
896            &tsconfig,
897            bynk_emit::emitter::emit_tsconfig_with_source_maps(),
898        )
899    {
900        return coverage_unsupported(
901            program,
902            json,
903            format!("could not enable source maps for coverage: {e}"),
904        );
905    }
906    // Preferred: `tsc -p out/tsconfig.json` → `node out/out-js/tests/main.js`.
907    // tsc gives us full type-checking before execution and matches what a
908    // production deployment build would do. If tsc is missing, fall back to
909    // tsx, which compiles-and-runs in one step. We also try npx-mediated
910    // variants so a developer with `npm` available doesn't need a global
911    // install. If nothing works, emit an actionable error message.
912    // #4159: inside the output root, so a run's JavaScript is private to it and two
913    // runs whose `--output`s share a parent cannot clobber each other.
914    let out_js_root = output_root.join("out-js");
915    let main_js = out_js_root.join("tests").join("main.js");
916
917    // #2146: tsc emits ES modules (the compile writes `out/package.json`
918    // declaring `"type": "module"`, which the emitted tsconfig's `module:
919    // NodeNext` follows, #2148). Since #4159 `out-js` is under `out/`, so that
920    // scope already covers it; the marker is kept so the tree still runs as ES
921    // modules if it is moved. The `out/` tree is left as the compiler wrote it.
922    let prepared = write_esm_marker(&out_js_root).map_err(|e| {
923        let marker = out_js_root.join("package.json");
924        format!("could not write {}: {e}", marker.display())
925    });
926    if let Err(msg) =
927        prepared.and_then(|()| provision_npm(&input, &output_root, &out_js_root, no_install))
928    {
929        return fail_run(program, json, stream, msg);
930    }
931
932    // Try a sequence of (program, prefix args) tsc invocations. In JSON mode the
933    // tsc step is captured so its output never reaches stdout (the document is
934    // the only thing on stdout); a tsc failure on the emitted TS is a
935    // toolchain/internal problem, surfaced as a `runtime` error.
936    // #1672: the `npx` fallback provisions the TypeScript major the output is
937    // verified against and users get, not an older pin.
938    let manager = crate::npm_install::system_tool_manager(&input);
939    let mut start_failures: Vec<String> = Vec::new();
940    let tsc_runners = crate::tools::Ladder::tsc(manager);
941    for rung in tsc_runners.rungs() {
942        let mut cmd = rung.command();
943        // `--pretty false`: the plain `file(line,col): error TSn:` records
944        // `tsc_report` parses, whatever the terminal.
945        cmd.arg("-p").arg(&tsconfig).args(["--pretty", "false"]);
946        // Captured in both modes (#3068): a failure is reported as a Bynk
947        // diagnostic where the output parses, else as the raw text, as before.
948        let tsc_ok = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output() {
949            Ok(o) if o.status.success() => true,
950            Ok(o) => {
951                // tsc writes its diagnostics to *stdout*.
952                let mut detail = String::from_utf8_lossy(&o.stdout).into_owned();
953                let err_text = String::from_utf8_lossy(&o.stderr);
954                if !err_text.trim().is_empty() {
955                    if !detail.is_empty() {
956                        detail.push('\n');
957                    }
958                    detail.push_str(&err_text);
959                }
960                let failure = crate::tsc_report::diagnose(
961                    &detail,
962                    &output_root,
963                    &out.snapshots,
964                    &out.display_root,
965                );
966                if json {
967                    let run = match &failure {
968                        Some(f) => {
969                            TestRun::codegen_error(crate::project_failure_short_lines(f), detail)
970                        }
971                        None => TestRun::runtime_error(
972                            "tsc rejected the generated TypeScript",
973                            Some(detail),
974                        ),
975                    };
976                    crate::test_stream::print_run(stream, &run);
977                } else {
978                    match &failure {
979                        Some(f) => crate::print_project_failure(f),
980                        None => eprint!("{detail}"),
981                    }
982                    emsg!(
983                        "{program} test: error: tsc reported errors against {}",
984                        tsconfig.display()
985                    );
986                }
987                return ExitCode::FAILURE;
988            }
989            Err(e) => {
990                start_failures.push(rung.start_failure(&e));
991                continue;
992            }
993        };
994        if tsc_ok {
995            let mut node_cmd = crate::tools::node_command();
996            node_cmd.arg(&main_js);
997            if smoke {
998                node_cmd.env(crate::smoke::STRICT_WIRE_ENV, "1");
999            }
1000            if let Some(file) = &declared_statuses {
1001                node_cmd.env(crate::smoke::DECLARED_ENV, file);
1002            }
1003            // #854: the coverage path owns the node launch (it sets
1004            // `NODE_V8_COVERAGE` and reads the result back), so it does not go
1005            // through `finish_runner`.
1006            if coverage {
1007                return run_with_coverage(
1008                    program,
1009                    node_cmd,
1010                    json,
1011                    seed_hex.as_deref(),
1012                    &filter,
1013                    &out_js_root,
1014                    &output_root,
1015                    &input,
1016                    &out.discovered,
1017                );
1018            }
1019            return match finish_runner(
1020                program,
1021                node_cmd,
1022                format,
1023                seed_hex.as_deref(),
1024                &filter,
1025                remote.as_ref(),
1026                &smoke_skips,
1027                &out.discovered,
1028                &doc_aliases,
1029                snapshot_run.as_ref(),
1030                run_timeout,
1031            ) {
1032                Ok(code) => code,
1033                Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
1034                    return report_timeout(program, json, stream, &e);
1035                }
1036                Err(e) => {
1037                    if json {
1038                        crate::test_stream::print_run(
1039                            stream,
1040                            &TestRun::runtime_error(format!("could not run node: {e}"), None),
1041                        );
1042                    } else {
1043                        emsg!(
1044                            "{program} test: error: tsc succeeded but `node {}` failed: {e}",
1045                            main_js.display()
1046                        );
1047                    }
1048                    ExitCode::FAILURE
1049                }
1050            };
1051        }
1052    }
1053
1054    // #854 DECISION C: with `--coverage`, the `tsc → node` path is required — do
1055    // not silently fall through to `tsx`, whose on-the-fly transform muddies
1056    // which map applies. Fail clearly instead.
1057    if coverage {
1058        // #1761 review: a `tsc` that is installed but won't start is reported as
1059        // such here too, not as missing.
1060        if !start_failures.is_empty() {
1061            return report_start_failures(program, json, stream, &start_failures, true, manager);
1062        }
1063        return coverage_unsupported(
1064            program,
1065            json,
1066            "`--coverage` requires `tsc` and `node` on PATH (the CI-shaped path with `.js.map`s); the `tsx` fallback is not supported for coverage.",
1067        );
1068    }
1069
1070    // tsx fallback chain.
1071    let tsx_runners = crate::tools::Ladder::tsx(manager);
1072    for rung in tsx_runners.rungs() {
1073        let mut cmd = rung.command();
1074        cmd.arg(&main_ts);
1075        if smoke {
1076            cmd.env(crate::smoke::STRICT_WIRE_ENV, "1");
1077        }
1078        if let Some(file) = &declared_statuses {
1079            cmd.env(crate::smoke::DECLARED_ENV, file);
1080        }
1081        match finish_runner(
1082            program,
1083            cmd,
1084            format,
1085            seed_hex.as_deref(),
1086            &filter,
1087            remote.as_ref(),
1088            &smoke_skips,
1089            &out.discovered,
1090            &doc_aliases,
1091            snapshot_run.as_ref(),
1092            run_timeout,
1093        ) {
1094            Ok(code) => return code,
1095            // A run that outlived its timeout is not a runner that failed to
1096            // start: it must not be tried again with the next runner.
1097            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
1098                return report_timeout(program, json, stream, &e);
1099            }
1100            Err(e) => start_failures.push(rung.start_failure(&e)),
1101        }
1102    }
1103
1104    if !start_failures.is_empty() {
1105        return report_start_failures(program, json, stream, &start_failures, false, manager);
1106    }
1107
1108    if json {
1109        crate::test_stream::print_run(
1110            stream,
1111            &TestRun::runtime_error(
1112                "no test runner found: requires `tsc` (with Node.js) or `tsx` on PATH",
1113                None,
1114            ),
1115        );
1116    } else {
1117        emsg!(
1118            "{program} test: error: requires either `tsc` (with Node.js) or `tsx` on PATH. \
1119             Install one of:\n{}",
1120            install_advice(manager, false)
1121        );
1122    }
1123    ExitCode::FAILURE
1124}
1125
1126/// The last writes of a test run's output, once its documents are on disk:
1127/// the WebAssembly modules, then the pruning of what this run did not write.
1128///
1129/// #2321: the WebAssembly modules adapter bindings include, with the Node form
1130/// of each loader (after every document write, which restores the Workers
1131/// form). `workers` is the integration run's Workers compile, whose `tests/`
1132/// tree was not written.
1133///
1134/// #3748: what an earlier build left in the output root (a Workers build's
1135/// `workers/` tree, say) is pruned, as `bynk build` prunes, before `tsc`
1136/// checks every `.ts` under it against this run's modules.
1137fn finish_output(
1138    program: &str,
1139    output_root: &Path,
1140    out: &ProjectOutput,
1141    workers: Option<&bynk_emit::emit_model::Artefacts>,
1142) -> Result<(), ExitCode> {
1143    let mut written: std::collections::HashSet<PathBuf> = out
1144        .artefacts
1145        .docs
1146        .keys()
1147        .chain(out.artefacts.modules.keys())
1148        .cloned()
1149        .collect();
1150    for modules in [Some(&out.artefacts.modules), workers.map(|w| &w.modules)]
1151        .into_iter()
1152        .flatten()
1153    {
1154        if let Err(e) = crate::write_modules_for_node(modules, output_root) {
1155            emsg!("{program} test: error: could not write a WebAssembly module: {e}");
1156            return Err(ExitCode::FAILURE);
1157        }
1158    }
1159    if let Some(workers) = workers {
1160        written.extend(
1161            workers
1162                .docs
1163                .keys()
1164                .filter(|path| !path.to_string_lossy().starts_with("tests/"))
1165                .chain(workers.modules.keys())
1166                .cloned(),
1167        );
1168    }
1169    crate::output::prune_output_except(output_root, &written).map_err(|e| {
1170        emsg!(
1171            "{program} test: error: could not remove stale output from `{}`: {e}",
1172            output_root.display()
1173        );
1174        ExitCode::FAILURE
1175    })
1176}
1177
1178/// #3087: the project declares no tests. By default a warning and exit 0 (a
1179/// library or a fresh project runs `bynk test` before it has tests); under
1180/// `--require-tests` an error, `error.kind == "no_tests"` in JSON, and exit 1.
1181fn report_no_tests(
1182    program: &str,
1183    input: &Path,
1184    require_tests: bool,
1185    stream: bool,
1186    json: bool,
1187) -> ExitCode {
1188    if json {
1189        let run = if require_tests {
1190            TestRun::no_tests_error(format!("no tests found in {}", input.display()))
1191        } else {
1192            empty_run()
1193        };
1194        crate::test_stream::print_run(stream, &run);
1195    } else if require_tests {
1196        emsg!(
1197            "{program} test: error: no tests found in {}",
1198            input.display()
1199        );
1200    } else {
1201        emsg!(
1202            "{program} test: warning: no tests found in {}",
1203            input.display()
1204        );
1205    }
1206    if require_tests {
1207        ExitCode::FAILURE
1208    } else {
1209        ExitCode::SUCCESS
1210    }
1211}
1212
1213/// The build's options with the run's in-memory sources laid over the project's:
1214/// a mutant's one file (#3069), and a caller's buffers and synthetic files, as
1215/// `--sources-stdin` does for `compile` (#3585).
1216fn with_overlays(
1217    mut options: crate::project::CompileOptions,
1218    input: &Path,
1219    mutant: Option<(PathBuf, String)>,
1220    overlay: Option<std::collections::HashMap<PathBuf, String>>,
1221) -> Result<crate::project::CompileOptions, String> {
1222    if let Some((path, text)) = mutant {
1223        options
1224            .sources
1225            .get_or_insert_with(Default::default)
1226            .insert(path, text);
1227    }
1228    match overlay {
1229        Some(overlay) => {
1230            crate::source_overlay::apply_overlay(options, input, overlay).map_err(|e| e.to_string())
1231        }
1232        None => Ok(options),
1233    }
1234}
1235
1236/// #3069: the test process outlived `run_timeout` and was killed. Reported as
1237/// its own error kind, `"timeout"`, so a caller never reads it from a message.
1238fn report_timeout(program: &str, json: bool, stream: bool, e: &std::io::Error) -> ExitCode {
1239    if json {
1240        crate::test_stream::print_run(stream, &TestRun::timeout_error(e.to_string()));
1241    } else {
1242        emsg!("{program} test: error: the run {e}");
1243    }
1244    ExitCode::FAILURE
1245}
1246
1247/// #1758: the run found runners but none would start. Each failure names the
1248/// resolved path and the error. In rich mode the install advice follows, since
1249/// installing another runner is often the fix for a broken one. `coverage`
1250/// limits that advice to `tsc`, the only runner `--coverage` accepts.
1251fn report_start_failures(
1252    program: &str,
1253    json: bool,
1254    stream: bool,
1255    failures: &[String],
1256    coverage: bool,
1257    manager: PackageManager,
1258) -> ExitCode {
1259    if json {
1260        crate::test_stream::print_run(
1261            stream,
1262            &TestRun::runtime_error("no test runner could be started", Some(failures.join("\n"))),
1263        );
1264    } else {
1265        emsg!("{program} test: error: no test runner could be started:");
1266        for failure in failures {
1267            eprintln!("  - {failure}");
1268        }
1269        eprintln!("Or install another:\n{}", install_advice(manager, coverage));
1270    }
1271    ExitCode::FAILURE
1272}
1273
1274/// The install advice for a missing or broken runner, one indented line each.
1275/// With `coverage`, only `tsc`, since `--coverage` doesn't accept `tsx`.
1276fn install_advice(manager: PackageManager, coverage: bool) -> String {
1277    let tsc = format!(
1278        "  - `{}` (provides tsc, which type-checks; requires Node.js to run output)",
1279        manager.global_install(&crate::tools::pins::typescript_spec())
1280    );
1281    if coverage {
1282        return tsc;
1283    }
1284    // A manager with no runner (Yarn classic) points at the `npx` it falls back to.
1285    let runner = manager.runner_label().unwrap_or("npx");
1286    format!(
1287        "{tsc}\n  - `{}` (runs TypeScript in one step, without type-checking)\n  Or run inside a project where `{runner} tsc` / `{runner} tsx` resolves.",
1288        manager.global_install(crate::tools::pins::TSX_SPEC)
1289    )
1290}
1291
1292/// A normal run with no suites — the JSON-mode document for a project with no
1293/// tests, or `--no-run`.
1294fn empty_run() -> TestRun {
1295    TestRun::empty()
1296}
1297
1298/// v0.67: map the compile's retained test manifest into discovery [`Suite`]s for
1299/// the `--no-run --format json` document. Each case is `outcome: "discovered"`,
1300/// carrying its declaration `location` (when known) for editor click-through.
1301fn discovery_suites(out: &ProjectOutput) -> Vec<Suite> {
1302    out.discovered
1303        .iter()
1304        .map(|s| Suite {
1305            name: s.name.clone(),
1306            kind: s.kind.to_string(),
1307            cases: s
1308                .cases
1309                .iter()
1310                .map(|c| Case {
1311                    name: c.name.clone(),
1312                    outcome: "discovered".to_string(),
1313                    message: None,
1314                    location: c.location.as_ref().map(|l| Location {
1315                        path: l.path.clone(),
1316                        line: l.line,
1317                        col: l.col,
1318                    }),
1319                    retries: None,
1320                    detached_failures: None,
1321                    tier: c.tier.map(str::to_string),
1322                    kind: c.generative.map(str::to_string),
1323                    seed: None,
1324                    counterexample: None,
1325                    violation: None,
1326                    refusals: None,
1327                    origin: c.doc.then(|| "doc".to_string()),
1328                    warnings: None,
1329                    duration_ms: None,
1330                })
1331                .collect(),
1332        })
1333        .collect()
1334}
1335
1336/// Execute the built runner command and produce its exit code. In JSON mode the
1337/// runner's stdout (NDJSON) and stderr are captured, folded into the pinned
1338/// document, and printed; in NDJSON mode each event is forwarded as the runner
1339/// writes it ([`crate::test_stream`]); otherwise the human ✓ / ✗ output goes
1340/// to the terminal: inherited straight through when nothing needs changing,
1341/// and forwarded line by line ([`run_aliased`]) when a doc test's name needs
1342/// rewriting, a snapshot report needs taking out, or `--color` colours it.
1343/// Forwarded, the runner's stdout is a pipe, so it is given `FORCE_COLOR=1`
1344/// to keep Node's own colour, and its stdout and stderr are forwarded
1345/// separately, so a test's own `console.error` may land a line early or late
1346/// among the ✓ / ✗ lines. Either way the **exit code follows the runner's own
1347/// process status**, so a mid-run crash (a complete NDJSON prefix but no
1348/// `run-end`) is never reported as success.
1349#[allow(clippy::too_many_arguments)]
1350fn finish_runner(
1351    program: &str,
1352    mut cmd: ProcCommand,
1353    format: TestFormat,
1354    seed_hex: Option<&str>,
1355    filter: &crate::test_filter::TestFilter,
1356    remote: Option<&crate::remote::RemoteRun>,
1357    // #2658: an in-process smoke run's skips (a remote run's are on `remote`).
1358    local_skips: &[(String, crate::project::RemoteSkip)],
1359    discovered: &[crate::project::DiscoveredSuite],
1360    aliases: &[(String, String)],
1361    // #2842: the project's snapshots, when the run reports them.
1362    snapshots: Option<&crate::snapshots::SnapshotRun>,
1363    // #3069: kill the process after this long (a mutant that never ends).
1364    timeout: Option<std::time::Duration>,
1365) -> std::io::Result<ExitCode> {
1366    if let Some(hex) = seed_hex {
1367        cmd.env(env_protocol::TEST_SEED, hex);
1368    }
1369    // #2138: the remote harness reads each Worker's URL from here; the
1370    // target's secrets are already in the inherited environment.
1371    if let Some(run) = remote {
1372        cmd.env(env_protocol::TEST_TARGETS, run.targets_json());
1373        cmd.env(crate::remote::SECRETS_ENV, run.secrets_json());
1374        cmd.env(env_protocol::TEST_SETTLE_MS, run.settle_ms.to_string());
1375        // #2138: the run's own `run.id`, always set, so a value left in the
1376        // environment never makes two runs share one.
1377        cmd.env(crate::remote::RUN_ID_ENV, &run.run_id);
1378    }
1379    // The skipped cases the filter selects are not in the build, so the runner
1380    // is told they exist, and the document lists only those.
1381    let selected_skips: Vec<&(String, crate::project::RemoteSkip)> = remote
1382        .map_or(local_skips, |run| run.skipped.as_slice())
1383        .iter()
1384        .filter(|(suite, skip)| filter.selects(suite, &skip.case))
1385        .collect();
1386    filter
1387        .clone()
1388        .with_skipped(
1389            selected_skips
1390                .iter()
1391                .map(|(suite, skip)| (suite.as_str(), skip.case.as_str())),
1392        )
1393        .apply(program, &mut cmd);
1394    if let Some(run) = snapshots {
1395        if run.update {
1396            cmd.env(crate::snapshots::UPDATE_ENV, "1");
1397        }
1398        if format == TestFormat::Rich {
1399            cmd.env(crate::snapshots::REPORT_ENV, "1");
1400        }
1401    }
1402    if format == TestFormat::Ndjson {
1403        // #2267: forward each event as the runner writes it.
1404        cmd.env(env_protocol::TEST_FORMAT, "ndjson");
1405        let mut events = crate::test_stream::Stream::new(crate::test_stream::StreamContext {
1406            discovered,
1407            skipped: selected_skips
1408                .iter()
1409                .map(|(suite, k)| (suite.clone(), k.case.clone(), k.reason.clone()))
1410                .collect(),
1411            transport: remote.map(crate::remote::RemoteRun::transport),
1412            snapshots,
1413        });
1414        let status =
1415            crate::test_stream::forward(cmd, &mut events, &mut std::io::stdout().lock(), aliases)?;
1416        for warning in events.warnings() {
1417            crate::colour::eprintln(&warning.line(program));
1418        }
1419        // #2842: the files are written once the run is over, and only if the
1420        // runner got as far as its report.
1421        if let Some(run) = snapshots
1422            && let Some(report) = run.report_for(events.snapshot_report())
1423            && let Err(e) = run.settle(&report)
1424        {
1425            emsg!("{program} test: error: could not update snapshots: {e}");
1426            return Ok(ExitCode::FAILURE);
1427        }
1428        events.unmatched().report(program);
1429        return Ok(exit_from(status.success() && events.ended()));
1430    }
1431    if format == TestFormat::Json {
1432        cmd.env(env_protocol::TEST_FORMAT, "ndjson");
1433        let out = output_within(cmd.stdout(Stdio::piped()).stderr(Stdio::piped()), timeout)?;
1434        let stdout = String::from_utf8_lossy(&out.stdout);
1435        let stderr = String::from_utf8_lossy(&out.stderr);
1436        let stdout = crate::doc_examples::apply_aliases(&stdout, aliases);
1437        let stderr = crate::doc_examples::apply_aliases(&stderr, aliases);
1438        let parsed = crate::test_json::parse_ndjson(&stdout);
1439        let unmatched = parsed.unmatched.clone();
1440        let snapshot_report = parsed.snapshots.clone();
1441        let mut doc = parsed.into_document(&stderr).with_tiers(discovered);
1442        // #2842: counts in the document; the files are written as the report says.
1443        let mut settle_failed = None;
1444        if let Some(run) = snapshots {
1445            let counts = match run.report_for(snapshot_report.as_ref()) {
1446                Some(report) => match run.settle(&report) {
1447                    Ok(counts) => counts,
1448                    Err(e) => {
1449                        settle_failed = Some(e);
1450                        run.counts(Some(&report))
1451                    }
1452                },
1453                None => run.counts(None),
1454            };
1455            doc = doc.with_snapshots(Some(counts));
1456        }
1457        let skipped: Vec<(String, String, String)> = selected_skips
1458            .iter()
1459            .map(|(suite, k)| (suite.clone(), k.case.clone(), k.reason.clone()))
1460            .collect();
1461        doc = match remote {
1462            Some(run) => doc.with_remote(run.transport(), &skipped),
1463            None => doc.with_skips(&skipped),
1464        };
1465        crate::test_stream::print_text(&doc.render());
1466        for warning in doc.warnings() {
1467            crate::colour::eprintln(&warning.line(program));
1468        }
1469        unmatched.report(program);
1470        if let Some(e) = settle_failed {
1471            emsg!("{program} test: error: could not update snapshots: {e}");
1472            return Ok(ExitCode::FAILURE);
1473        }
1474        Ok(exit_from_document(out.status.success(), &doc))
1475    } else if aliases.is_empty() && snapshots.is_none() && !crate::colour::stdout() {
1476        let status = cmd
1477            .stdout(Stdio::inherit())
1478            .stderr(Stdio::inherit())
1479            .status()?;
1480        Ok(exit_from(status.success()))
1481    } else {
1482        // #2461: a doc test's output names the real file, not the synthetic
1483        // one it was compiled from, so the lines are rewritten on the way.
1484        // #2842: and the snapshot report line is taken out of the output.
1485        // And with colour on, the runner's plain lines are coloured.
1486        let (status, report) = run_aliased(cmd, aliases, crate::colour::stdout())?;
1487        if let Some(run) = snapshots {
1488            let counts = match run.report_for(report.as_ref()) {
1489                Some(report) => match run.settle(&report) {
1490                    Ok(counts) => counts,
1491                    Err(e) => {
1492                        emsg!("{program} test: error: could not update snapshots: {e}");
1493                        return Ok(ExitCode::FAILURE);
1494                    }
1495                },
1496                None => run.counts(None),
1497            };
1498            if let Some(line) = run.summary_line(counts) {
1499                println!("{line}");
1500            }
1501        }
1502        Ok(exit_from(status.success()))
1503    }
1504}
1505
1506/// Kill `child` and everything it started: its process group on Unix, its
1507/// process tree through `taskkill /T` on Windows.
1508fn kill_tree(child: &mut std::process::Child) {
1509    #[cfg(unix)]
1510    {
1511        // SAFETY: `killpg` takes plain integers; the child leads its own group
1512        // (`process_group(0)` before spawn), so the group id is its pid.
1513        unsafe {
1514            libc::killpg(child.id() as libc::pid_t, libc::SIGKILL);
1515        }
1516    }
1517    #[cfg(windows)]
1518    {
1519        let _ = ProcCommand::new("taskkill")
1520            .args(["/T", "/F", "/PID", &child.id().to_string()])
1521            .stdout(Stdio::null())
1522            .stderr(Stdio::null())
1523            .status();
1524    }
1525    let _ = child.kill();
1526}
1527
1528/// `cmd.output()`, except that a process still running after `timeout` is
1529/// killed and the call fails with [`std::io::ErrorKind::TimedOut`] (#3069).
1530/// `cmd`'s stdout and stderr must be piped.
1531fn output_within(
1532    cmd: &mut ProcCommand,
1533    timeout: Option<std::time::Duration>,
1534) -> std::io::Result<std::process::Output> {
1535    use std::io::Read;
1536    let Some(timeout) = timeout else {
1537        return cmd.output();
1538    };
1539    // The runner may start children of its own (`tsx` and `npx` start `node`;
1540    // `bynk dev` starts workers) that hold the output pipes open: put the run
1541    // in its own process group so the kill below reaches them all.
1542    #[cfg(unix)]
1543    std::os::unix::process::CommandExt::process_group(cmd, 0);
1544    let mut child = cmd.spawn()?;
1545    let drain = |pipe: Option<Box<dyn Read + Send>>| {
1546        std::thread::spawn(move || {
1547            let mut buf = Vec::new();
1548            if let Some(mut pipe) = pipe {
1549                let _ = pipe.read_to_end(&mut buf);
1550            }
1551            buf
1552        })
1553    };
1554    let out_reader = drain(
1555        child
1556            .stdout
1557            .take()
1558            .map(|p| Box::new(p) as Box<dyn Read + Send>),
1559    );
1560    let err_reader = drain(
1561        child
1562            .stderr
1563            .take()
1564            .map(|p| Box::new(p) as Box<dyn Read + Send>),
1565    );
1566    let deadline = std::time::Instant::now() + timeout;
1567    let status = loop {
1568        if let Some(status) = child.try_wait()? {
1569            break Some(status);
1570        }
1571        if std::time::Instant::now() >= deadline {
1572            kill_tree(&mut child);
1573            let _ = child.wait();
1574            break None;
1575        }
1576        std::thread::sleep(std::time::Duration::from_millis(20));
1577    };
1578    let stdout = out_reader.join().unwrap_or_default();
1579    let stderr = err_reader.join().unwrap_or_default();
1580    match status {
1581        Some(status) => Ok(std::process::Output {
1582            status,
1583            stdout,
1584            stderr,
1585        }),
1586        None => Err(std::io::Error::new(
1587            std::io::ErrorKind::TimedOut,
1588            format!("timed out after {}s", timeout.as_secs()),
1589        )),
1590    }
1591}
1592
1593/// Run `cmd`, forwarding its output line by line with the synthetic file names
1594/// in `aliases` replaced by the real ones.
1595fn run_aliased(
1596    mut cmd: ProcCommand,
1597    aliases: &[(String, String)],
1598    colour: bool,
1599) -> std::io::Result<(std::process::ExitStatus, Option<crate::snapshots::Report>)> {
1600    use std::io::{BufRead, BufReader, Write};
1601    // Reads raw bytes a line at a time (as `test_stream::forward` does), so a
1602    // line that is not UTF-8 is passed on lossily and never ends the reading: a
1603    // pipe nobody reads fills and stalls the child. A final line with no newline
1604    // keeps having none.
1605    fn forward(
1606        pipe: impl std::io::Read,
1607        aliases: &[(String, String)],
1608        mut out: impl Write,
1609        report: Option<&mut Option<crate::snapshots::Report>>,
1610        colour: bool,
1611    ) {
1612        let mut report = report;
1613        let mut lines = crate::colour::TestLines::default();
1614        let mut reader = BufReader::new(pipe);
1615        let mut buffer = Vec::new();
1616        loop {
1617            buffer.clear();
1618            match reader.read_until(b'\n', &mut buffer) {
1619                Ok(0) | Err(_) => break,
1620                Ok(_) => {}
1621            }
1622            let line = String::from_utf8_lossy(&buffer);
1623            // #2842: the runner's snapshot report is for the driver, not the terminal.
1624            if let Some(found) = report.as_deref_mut()
1625                && let Some(parsed) = crate::snapshots::Report::from_marked_line(&line)
1626            {
1627                *found = Some(parsed);
1628                continue;
1629            }
1630            let line = crate::doc_examples::apply_aliases(&line, aliases);
1631            let line = if colour {
1632                lines.paint(&line)
1633            } else {
1634                line.into_owned()
1635            };
1636            let _ = out.write_all(line.as_bytes());
1637            let _ = out.flush();
1638        }
1639    }
1640    // Piped, Node can't see the terminal: when we colour, it may too (its
1641    // `console.log` of an object, say), as it would have, inherited.
1642    if colour {
1643        cmd.env_remove("NO_COLOR").env("FORCE_COLOR", "1");
1644    }
1645    let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
1646    let stderr_pipe = child.stderr.take();
1647    let err_aliases = aliases.to_vec();
1648    let errors = std::thread::spawn(move || {
1649        if let Some(pipe) = stderr_pipe {
1650            forward(pipe, &err_aliases, std::io::stderr().lock(), None, false);
1651        }
1652    });
1653    let mut report = None;
1654    if let Some(pipe) = child.stdout.take() {
1655        forward(
1656            pipe,
1657            aliases,
1658            std::io::stdout().lock(),
1659            Some(&mut report),
1660            colour,
1661        );
1662    }
1663    let status = child.wait()?;
1664    let _ = errors.join();
1665    Ok((status, report))
1666}
1667
1668fn exit_from(success: bool) -> ExitCode {
1669    if success {
1670        ExitCode::SUCCESS
1671    } else {
1672        ExitCode::FAILURE
1673    }
1674}
1675
1676/// #4000: a JSON document that carries an `error` is an incomplete or failed run
1677/// (the runner's stream ended with no `run-end`, so a suite's `cases` may be
1678/// missing), and it must not exit 0 whatever the runner process's own status was.
1679fn exit_from_document(runner_ok: bool, doc: &TestRun) -> ExitCode {
1680    exit_from(runner_ok && doc.error.is_none())
1681}
1682
1683/// #854: a `--coverage` request that cannot be honoured (unsupported flag combo,
1684/// no `tsc → node`, or a setup error). In JSON mode it is a `runtime` error so
1685/// the document stays the only thing on stdout; in rich mode a plain stderr line.
1686fn coverage_unsupported(program: &str, json: bool, message: impl Into<String>) -> ExitCode {
1687    let message = message.into();
1688    if json {
1689        // `--format ndjson` refuses `--coverage` before this is reachable.
1690        crate::test_stream::print_run(false, &TestRun::runtime_error(message, None));
1691    } else {
1692        emsg!("{program} test --coverage: error: {message}");
1693    }
1694    ExitCode::FAILURE
1695}
1696
1697/// #854: run the emitted runner under V8 coverage and attribute the result to
1698/// `.bynk` source. Owns the `node` launch: it points `NODE_V8_COVERAGE` at a
1699/// scratch dir, runs the suite exactly as [`finish_runner`] would, then remaps
1700/// the V8 output through the emitted source maps ([`crate::coverage`]). In rich
1701/// mode the summary table is appended after the human ✓ / ✗ output; in JSON mode
1702/// the `coverage` block is folded into the pinned document. The **exit code
1703/// follows the run's own status** — coverage is a report about the run, never a
1704/// gate on it (a partial or unreadable map degrades the numbers, not the code).
1705#[allow(clippy::too_many_arguments)]
1706fn run_with_coverage(
1707    program: &str,
1708    mut cmd: ProcCommand,
1709    json: bool,
1710    seed_hex: Option<&str>,
1711    filter: &crate::test_filter::TestFilter,
1712    out_js_root: &Path,
1713    out_root: &Path,
1714    source_root: &Path,
1715    discovered: &[crate::project::DiscoveredSuite],
1716) -> ExitCode {
1717    // A scratch dir beside the build output; cleared first so a prior run's JSON
1718    // never leaks in. `NODE_V8_COVERAGE` writes one file per process on exit.
1719    let cov_dir = out_root.join(".v8-coverage");
1720    let _ = std::fs::remove_dir_all(&cov_dir);
1721    if let Err(e) = std::fs::create_dir_all(&cov_dir) {
1722        return coverage_unsupported(
1723            program,
1724            json,
1725            format!("could not create the coverage dir: {e}"),
1726        );
1727    }
1728    cmd.env("NODE_V8_COVERAGE", &cov_dir);
1729    if let Some(hex) = seed_hex {
1730        cmd.env(env_protocol::TEST_SEED, hex);
1731    }
1732    filter.apply(program, &mut cmd);
1733
1734    let collect = || {
1735        crate::coverage::collect_coverage(&cov_dir, out_js_root, out_root, source_root)
1736            .unwrap_or_default()
1737    };
1738
1739    let code = if json {
1740        cmd.env(env_protocol::TEST_FORMAT, "ndjson");
1741        let out = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output() {
1742            Ok(o) => o,
1743            Err(e) => {
1744                let _ = std::fs::remove_dir_all(&cov_dir);
1745                return coverage_unsupported(program, true, format!("could not run node: {e}"));
1746            }
1747        };
1748        let stdout = String::from_utf8_lossy(&out.stdout);
1749        let stderr = String::from_utf8_lossy(&out.stderr);
1750        let report = collect();
1751        let parsed = crate::test_json::parse_ndjson(&stdout);
1752        let unmatched = parsed.unmatched.clone();
1753        let doc = parsed
1754            .into_document(&stderr)
1755            .with_tiers(discovered)
1756            .with_coverage(&report);
1757        print!("{}", doc.render());
1758        for warning in doc.warnings() {
1759            crate::colour::eprintln(&warning.line(program));
1760        }
1761        unmatched.report(program);
1762        exit_from_document(out.status.success(), &doc)
1763    } else {
1764        let colour = crate::colour::stdout();
1765        let status = if colour {
1766            run_aliased(cmd, &[], true).map(|(status, _)| status)
1767        } else {
1768            cmd.stdout(Stdio::inherit())
1769                .stderr(Stdio::inherit())
1770                .status()
1771        };
1772        let status = match status {
1773            Ok(s) => s,
1774            Err(e) => {
1775                let _ = std::fs::remove_dir_all(&cov_dir);
1776                emsg!("{program} test --coverage: error: could not run node: {e}");
1777                return ExitCode::FAILURE;
1778            }
1779        };
1780        let report = collect();
1781        print!("{}", crate::coverage::render_rich(&report, colour));
1782        exit_from(status.success())
1783    };
1784    let _ = std::fs::remove_dir_all(&cov_dir);
1785    code
1786}
1787
1788/// #2146: mark the tsc output tree as ES modules, so Node runs the ESM that tsc
1789/// emits from the `"type": "module"` output tree (#2148).
1790fn write_esm_marker(out_js_root: &Path) -> std::io::Result<()> {
1791    std::fs::create_dir_all(out_js_root)?;
1792    std::fs::write(
1793        out_js_root.join("package.json"),
1794        "{\n  \"type\": \"module\"\n}\n",
1795    )
1796}
1797
1798/// Node's default inspector port.
1799const NODE_INSPECT_PORT: u16 = 9229;
1800
1801/// The `--inspect-brk` flag for `run_inspect` (#2115). Node's default port,
1802/// 9229, when it is free, so a debugger that looks there by default (Chrome's
1803/// `chrome://inspect`) still finds the runner. When something else holds it
1804/// (another inspected process, a stray `workerd`), plain `--inspect-brk` would
1805/// print `Starting inspector on 127.0.0.1:9229 failed: address already in use`
1806/// and run the tests *without* an inspector, so no debugger could attach. Then
1807/// ask for port 0: Node picks a free one and prints it in the `ws://` URL, which
1808/// is what attaching clients (the VS Code extension included) read.
1809fn inspect_brk_arg(default_port_free: bool) -> &'static str {
1810    if default_port_free {
1811        "--inspect-brk"
1812    } else {
1813        "--inspect-brk=127.0.0.1:0"
1814    }
1815}
1816
1817/// Slice 2 (ADR 0104): launch the emitted `.ts` test entry under Node's inspector
1818/// and hand off. Node prints its inspector `ws://` URL to stderr and pauses at the
1819/// first line (`--inspect-brk`) until a JavaScript debugger attaches; breakpoints
1820/// set in `.bynk` resolve through the emitted source maps. `--experimental-strip-types`
1821/// runs the `.ts` directly under line-preserving type-stripping (Node ≥ 22.6;
1822/// unflagged ≥ 23.6) — no `tsc`, so slice 1's `.ts.map` applies to the running file.
1823fn run_inspect(
1824    program: &str,
1825    entry: &Path,
1826    seed_hex: Option<&str>,
1827    filter: &crate::test_filter::TestFilter,
1828    smoke: bool,
1829) -> ExitCode {
1830    let Some(mut cmd) = crate::tools::resolved_node_command() else {
1831        emsg!("{program} test --inspect: error: `node` was not found on PATH");
1832        return ExitCode::FAILURE;
1833    };
1834    emsg!("{program} test --inspect: launching the test runner under Node's inspector.");
1835    eprintln!("  Attach a JavaScript debugger to the inspector URL below; breakpoints set");
1836    eprintln!("  in `.bynk` sources resolve through the emitted source maps.");
1837    eprintln!("  (Requires Node \u{2265} 22.6 for TypeScript type-stripping.)");
1838    if let Some(hex) = seed_hex {
1839        cmd.env(env_protocol::TEST_SEED, hex);
1840    }
1841    if smoke {
1842        cmd.env(crate::smoke::STRICT_WIRE_ENV, "1");
1843    }
1844    filter.apply(program, &mut cmd);
1845    let default_free = std::net::TcpListener::bind(("127.0.0.1", NODE_INSPECT_PORT)).is_ok();
1846    if !default_free {
1847        eprintln!(
1848            "  Port {NODE_INSPECT_PORT} is in use, so the inspector takes a free port; use the URL below."
1849        );
1850    }
1851    cmd.arg("--experimental-strip-types")
1852        .arg(inspect_brk_arg(default_free))
1853        .arg(entry);
1854    match cmd
1855        .stdout(Stdio::inherit())
1856        .stderr(Stdio::inherit())
1857        .status()
1858    {
1859        Ok(s) => exit_from(s.success()),
1860        Err(e) => {
1861            emsg!("{program} test --inspect: error: could not run node: {e}");
1862            ExitCode::FAILURE
1863        }
1864    }
1865}
1866
1867#[cfg(test)]
1868mod inspect_port_tests {
1869
1870    use super::inspect_brk_arg;
1871
1872    #[test]
1873    fn uses_the_default_port_when_free_and_a_free_port_otherwise() {
1874        assert_eq!(inspect_brk_arg(true), "--inspect-brk");
1875        assert_eq!(inspect_brk_arg(false), "--inspect-brk=127.0.0.1:0");
1876    }
1877}
1878
1879#[cfg(test)]
1880mod exit_from_document_tests {
1881    use super::*;
1882
1883    fn exit_for(runner_ok: bool, stdout: &str) -> ExitCode {
1884        let doc = crate::test_json::parse_ndjson(stdout).into_document("");
1885        exit_from_document(runner_ok, &doc)
1886    }
1887
1888    /// #4000: a runner that exits 0 without ever reaching `run-end` (its output
1889    /// clobbered or cut short, so a suite's `cases` are missing) is a failed run.
1890    #[test]
1891    fn a_stream_that_never_completes_fails_the_run_even_when_the_runner_exits_zero() {
1892        let failure = ExitCode::FAILURE;
1893        assert_eq!(exit_for(true, ""), failure);
1894        assert_eq!(
1895            exit_for(true, r#"{"type":"suite-begin","name":"s","kind":"system"}"#),
1896            failure
1897        );
1898        let complete = concat!(
1899            r#"{"type":"suite-begin","name":"s","kind":"system"}"#,
1900            "\n",
1901            r#"{"type":"case","name":"c","outcome":"pass"}"#,
1902            "\n",
1903            r#"{"type":"run-end","passed":1,"failed":0}"#,
1904            "\n",
1905        );
1906        assert_eq!(exit_for(true, complete), ExitCode::SUCCESS);
1907        assert_eq!(exit_for(false, complete), failure);
1908    }
1909}
1910
1911#[cfg(test)]
1912mod output_within_tests {
1913    use super::*;
1914
1915    #[cfg(unix)]
1916    #[test]
1917    fn output_within_kills_a_process_that_outlives_its_timeout() {
1918        let mut cmd = ProcCommand::new("sleep");
1919        cmd.arg("30").stdout(Stdio::piped()).stderr(Stdio::piped());
1920        let started = std::time::Instant::now();
1921        let err = output_within(&mut cmd, Some(std::time::Duration::from_millis(100)))
1922            .expect_err("sleep outlives 100ms");
1923        assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
1924        assert!(started.elapsed() < std::time::Duration::from_secs(10));
1925
1926        // A grandchild that holds the pipes open must not outlast the kill.
1927        let mut tree = ProcCommand::new("sh");
1928        tree.args(["-c", "sleep 30 & wait"])
1929            .stdout(Stdio::piped())
1930            .stderr(Stdio::piped());
1931        let started = std::time::Instant::now();
1932        let err = output_within(&mut tree, Some(std::time::Duration::from_millis(200)))
1933            .expect_err("the shell outlives 200ms");
1934        assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
1935        assert!(
1936            started.elapsed() < std::time::Duration::from_secs(10),
1937            "the grandchild was killed with its parent"
1938        );
1939
1940        let mut quick = ProcCommand::new("echo");
1941        quick
1942            .arg("hi")
1943            .stdout(Stdio::piped())
1944            .stderr(Stdio::piped());
1945        let out = output_within(&mut quick, Some(std::time::Duration::from_secs(30))).unwrap();
1946        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hi");
1947    }
1948
1949    /// #3086: the Windows path of `kill_tree` (`taskkill /T /F`), unrun until a
1950    /// Windows machine ran it. A runner whose grandchildren hold the output
1951    /// pipes open must still come back `TimedOut` promptly and have its whole
1952    /// tree killed. It carries its own outer deadline and prints what it saw, so
1953    /// a failure is a diagnosis in the log rather than a hung job.
1954    #[cfg(windows)]
1955    #[test]
1956    fn output_within_kills_a_windows_process_tree() {
1957        use std::os::windows::process::CommandExt;
1958        use std::time::{Duration, Instant};
1959
1960        // A count no other test or tool uses, so the survivors are ours alone.
1961        const MARK: &str = "-n 37 127.0.0.1";
1962
1963        fn survivors() -> Result<String, String> {
1964            let out = ProcCommand::new("powershell")
1965                .args([
1966                    "-NoProfile",
1967                    "-Command",
1968                    "Get-CimInstance Win32_Process -Filter \"Name='ping.exe'\" | \
1969                     Where-Object { $_.CommandLine -like '*-n 37 127.0.0.1*' } | \
1970                     ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }",
1971                ])
1972                .output()
1973                .map_err(|e| format!("could not run powershell: {e}"))?;
1974            if !out.status.success() {
1975                return Err(format!(
1976                    "powershell failed ({}): {}",
1977                    out.status,
1978                    String::from_utf8_lossy(&out.stderr).trim()
1979                ));
1980            }
1981            Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
1982        }
1983        fn cleanup() {
1984            let _ = ProcCommand::new("powershell")
1985                .args([
1986                    "-NoProfile",
1987                    "-Command",
1988                    "Get-CimInstance Win32_Process -Filter \"Name='ping.exe'\" | \
1989                     Where-Object { $_.CommandLine -like '*-n 37 127.0.0.1*' } | \
1990                     ForEach-Object { Stop-Process -Id $_.ProcessId -Force }",
1991                ])
1992                .output();
1993        }
1994
1995        // `cmd` runs one ping detached (`start /b`) and waits on another: two
1996        // grandchildren that both inherit the pipes `output_within` reads.
1997        let mut cmd = ProcCommand::new("cmd");
1998        cmd.raw_arg(format!("/c \"start /b ping {MARK} & ping {MARK}\""))
1999            .stdout(Stdio::piped())
2000            .stderr(Stdio::piped());
2001
2002        // Its own deadline: if `output_within` hangs on the held pipes this
2003        // test fails with output instead of stalling the merge queue.
2004        let (tx, rx) = std::sync::mpsc::channel();
2005        let started = Instant::now();
2006        std::thread::spawn(move || {
2007            let _ = tx.send(output_within(&mut cmd, Some(Duration::from_millis(500))));
2008        });
2009        let result = match rx.recv_timeout(Duration::from_secs(60)) {
2010            Ok(result) => result,
2011            Err(_) => {
2012                let seen = survivors();
2013                cleanup();
2014                panic!(
2015                    "output_within did not return within 60s of a 500ms timeout: the \
2016                     grandchildren still held the pipes after taskkill. ping processes \
2017                     alive: {seen:?}. Switch kill_tree to a Job Object (kill on close)."
2018                );
2019            }
2020        };
2021        let elapsed = started.elapsed();
2022        let err = match result {
2023            Err(e) => e,
2024            Ok(out) => {
2025                cleanup();
2026                panic!("expected a timeout, got status {:?}", out.status);
2027            }
2028        };
2029        assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "error: {err}");
2030        assert!(
2031            elapsed < Duration::from_secs(20),
2032            "TimedOut took {elapsed:?}; the pings last about 37s, so the tree was not killed"
2033        );
2034
2035        // The tree is gone: no ping of ours outlives the kill (a short settle
2036        // for the OS to reap).
2037        let deadline = Instant::now() + Duration::from_secs(10);
2038        let mut seen;
2039        loop {
2040            seen = survivors();
2041            if matches!(&seen, Ok(s) if s.is_empty()) || Instant::now() >= deadline {
2042                break;
2043            }
2044            std::thread::sleep(Duration::from_millis(250));
2045        }
2046        match seen {
2047            Ok(s) if s.is_empty() => {}
2048            Ok(s) => {
2049                cleanup();
2050                panic!("taskkill left processes running after the timeout:\n{s}");
2051            }
2052            // No PowerShell to inspect with: the prompt return above is the check.
2053            Err(e) => eprintln!("could not check for survivors ({e}); relying on the timing"),
2054        }
2055    }
2056}
2057
2058/// #3328: a Worker built for a `system` case may import a first-party npm package
2059/// (`postal-mime`, for inbound email), which `tsc` and Node resolve from
2060/// `out/node_modules`. Install the npm packages the emitted `package.json` lists (the
2061/// toolchain's own first-party ones, ADR 0799 C, and an adapter's), into
2062/// `out/node_modules`, with the project's own package manager (#3350), and make
2063/// them resolvable from the compiled `out-js`. A tree that lists none, or whose
2064/// `node_modules` already holds them, runs nothing (offline-safe on a re-run).
2065/// `--no-install` (or `BYNK_NO_INSTALL`) stops instead of installing.
2066fn provision_npm(
2067    project_root: &Path,
2068    output_root: &Path,
2069    out_js_root: &Path,
2070    no_install: bool,
2071) -> Result<(), String> {
2072    let manifest = std::fs::read_to_string(output_root.join("package.json")).unwrap_or_default();
2073    if !manifest.contains("\"dependencies\"") {
2074        return Ok(());
2075    }
2076    let modules = output_root.join("node_modules");
2077    crate::npm_install::install_for_project(
2078        project_root,
2079        output_root,
2080        crate::npm_install::configured_manager(project_root).as_deref(),
2081        crate::npm_install::Mode::of(
2082            false,
2083            no_install || crate::npm_install::no_install_from_env(),
2084        ),
2085    )?;
2086    let link = out_js_root.join("node_modules");
2087    // A link left by an earlier run may dangle (`exists` follows it), so replace it.
2088    if link.symlink_metadata().is_ok() {
2089        // A symlink goes with `remove_file`, a Windows junction with `remove_dir`.
2090        let _ = std::fs::remove_file(&link).or_else(|_| std::fs::remove_dir(&link));
2091    }
2092    // Absolute, so a relative `--output` does not leave the link pointing
2093    // beside itself.
2094    let target = std::fs::canonicalize(&modules)
2095        .map_err(|e| format!("could not resolve {}: {e}", modules.display()))?;
2096    #[cfg(unix)]
2097    std::os::unix::fs::symlink(&target, &link)
2098        .map_err(|e| format!("could not link {}: {e}", link.display()))?;
2099    // A directory junction, which needs no privilege (a symlink does on Windows).
2100    #[cfg(windows)]
2101    {
2102        // `canonicalize` gives a `\\?\` path, which `mklink` does not take.
2103        let plain = target
2104            .to_string_lossy()
2105            .trim_start_matches(r"\\?\")
2106            .to_string();
2107        let made = ProcCommand::new("cmd")
2108            .arg("/C")
2109            .arg("mklink")
2110            .arg("/J")
2111            .arg(&link)
2112            .arg(&plain)
2113            .output()
2114            .map_err(|e| format!("could not link {}: {e}", link.display()))?;
2115        if !made.status.success() {
2116            return Err(format!(
2117                "could not link {}: {}",
2118                link.display(),
2119                String::from_utf8_lossy(&made.stdout)
2120            ));
2121        }
2122    }
2123    Ok(())
2124}
2125
2126/// Report a failure of the run itself (not of a case) and give the exit code.
2127fn fail_run(program: &str, json: bool, stream: bool, msg: String) -> ExitCode {
2128    if json {
2129        crate::test_stream::print_run(stream, &TestRun::runtime_error(msg, None));
2130    } else {
2131        emsg!("{program} test: error: {msg}");
2132    }
2133    ExitCode::FAILURE
2134}