Skip to main content

bynk_driver/
test_runner.rs

1//! `bynkc test` / `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 `bynkc` — both `bynkc` and `bynk`
6//! need one implementation instead of two.
7//!
8//! Runners are found with [`crate::probe::detect`] and
9//! [`crate::probe::DetectOpts::default()`] (no project-local search, no `npx`
10//! fallback), the one detection implementation both CLIs share for
11//! `doctor`/`dev`. #1758: each is spawned by the path detection resolved, not by
12//! its bare name, so a Windows npm shim (`tsc.cmd`) runs, and a runner that is
13//! found but won't start is reported as such rather than as missing.
14
15use std::path::{Path, PathBuf};
16use std::process::{Command as ProcCommand, ExitCode, Stdio};
17
18use bynk_emit::project::{BuildTarget, ImportExt, ProjectOutput};
19use clap::ValueEnum;
20
21use crate::probe::{DetectOpts, SystemToolbox};
22use crate::test_json::{Case, Location, Suite, TestRun};
23
24/// Where `name` is installed on `PATH`, if it is. #1758: callers spawn this
25/// path, not the bare name, so a Windows npm shim (`tsc.cmd`) that detection
26/// finds is also the program that runs.
27fn resolve_tool(name: &str) -> Option<PathBuf> {
28    crate::probe::detect(&SystemToolbox, name, DetectOpts::default())
29        .provenance
30        .path()
31        .map(Path::to_path_buf)
32}
33
34/// #1758: a runner that was found but would not start. Recorded instead of
35/// silently skipped, so a run with no working runner reports the real cause
36/// rather than advising an install of something already installed.
37fn start_failure(path: &Path, e: &std::io::Error) -> String {
38    format!(
39        "`{}` was found but could not be started: {e}",
40        path.display()
41    )
42}
43
44/// `test --format` selector, shared by `bynkc test` and `bynk test` (review
45/// findings #40/#72): one enum both CLIs' `Test` subcommand uses, instead of
46/// two structurally-identical copies that must be hand-kept in sync.
47#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
48pub enum TestFormat {
49    /// The grouped `✓ / ✗` human output (the default; unchanged behaviour).
50    #[default]
51    Rich,
52    /// A single pinned JSON document of results, for tooling and CI.
53    Json,
54    /// One JSON event per line as each is produced, for a consumer that wants
55    /// results while the run is going (see [`crate::test_stream`]).
56    Ndjson,
57}
58
59impl TestFormat {
60    /// The `--format` token this maps to when `bynk test` shells a resolved
61    /// `bynkc` (`TestFormat::as_str` isn't `ValueEnum`-derived, since the
62    /// wire value and the token clap parses happen to coincide, but the two
63    /// concerns — "what did the user type" vs. "what do I forward" — are
64    /// worth keeping textually distinct call sites for).
65    pub fn as_bynkc_arg(self) -> &'static str {
66        match self {
67            TestFormat::Rich => "rich",
68            TestFormat::Json => "json",
69            TestFormat::Ndjson => "ndjson",
70        }
71    }
72}
73
74/// The `test` subcommand's flags — the one contract `bynkc test` and `bynk
75/// test` both `#[command(flatten)]` (review findings #40/#72/#20/#21
76/// remainder), replacing four independent hand-spellings (`bynkc::cli`,
77/// `bynk::cli`, `bynk::test::TestArgs`, and the argv-literal rebuild that
78/// turned the latter back into flags for the `bynkc` shell-out) with one.
79/// Field docs here are the CLI help text for both commands' flags.
80#[derive(clap::Args, Debug, Clone)]
81pub struct TestArgs {
82    /// Input project root directory. Defaults to the current directory.
83    #[arg(default_value = ".")]
84    pub input: PathBuf,
85    /// Where to write compiled TypeScript test runner modules.
86    /// Defaults to `<input>/out`.
87    #[arg(short, long)]
88    pub output: Option<PathBuf>,
89    /// Skip the runner invocation. With `--format rich` this emits the
90    /// generated test files (for CI flows that drive the runner separately);
91    /// with `--format json` it emits a discovery document listing every
92    /// suite and case (each `outcome: "discovered"`) without running them —
93    /// a pure compile, no `tsc`/Node.
94    #[arg(long)]
95    pub no_run: bool,
96    /// Output format. `rich` (default) is the grouped ✓ / ✗ human output;
97    /// `json` is a single pinned JSON document of results, for tooling;
98    /// `ndjson` is the same results as one JSON event per line, written as
99    /// each suite finishes. `ndjson` cannot be combined with `--coverage` or
100    /// `--no-run`.
101    #[arg(long, value_enum, default_value_t = TestFormat::Rich)]
102    pub format: TestFormat,
103    /// Compile a debug build and launch the test runner under Node's
104    /// inspector (`node --inspect-brk`), printing the inspector URL for a
105    /// JavaScript debugger to attach. The emitted `.ts` runs directly under
106    /// Node's line-preserving type-stripping, so source maps resolve
107    /// breakpoints back to `.bynk`. Requires Node ≥ 22.18 (or ≥ 23.6
108    /// unflagged). Does not run `tsc`.
109    #[arg(long)]
110    pub inspect: bool,
111    /// The root seed for generative `property` tests, as hex (e.g. `0x5f3a`).
112    /// A failing property prints the seed it used; re-running with `--seed
113    /// <hex>` reproduces that run byte-for-byte. Omitted, each run draws a
114    /// fresh random seed.
115    #[arg(long)]
116    pub seed: Option<String>,
117    /// Run only the test cases named `<name>`, skipping the rest — the filter
118    /// behind the editor's per-case `▷ Run Test` lens. Matches by exact case
119    /// name across suites. Repeat the flag to run several cases in one
120    /// process; values of the same flag combine as "or", and with `--suite`
121    /// as "and". A name that selects no case fails the run. Omitted, every
122    /// case runs. No effect with `--no-run` (discovery lists all cases
123    /// regardless).
124    #[arg(long, value_name = "NAME")]
125    pub case: Vec<String>,
126    /// Run only the cases of the suite named `<name>`, as the JSON document
127    /// reports it (`suites[].name`, without an integration suite's prefix);
128    /// any suite kind matches. Repeat the flag to select several suites. A
129    /// suite that is not selected is left out of the output entirely. A name
130    /// that selects no suite fails the run. No effect with `--no-run`.
131    #[arg(long, value_name = "NAME")]
132    pub suite: Vec<String>,
133    /// For a caller that runs one selection as several processes (`bynk test`
134    /// across a workspace's members, `--against dev` across `env` groups): this
135    /// run sees only part of the `--case`/`--suite` selection, so a value it
136    /// selects nothing for is not an error here. The caller judges the values.
137    #[arg(long, hide = true)]
138    pub partial_selection: bool,
139    /// After the suite runs, report statement/line coverage attributed to
140    /// `.bynk` source (a rich summary table, or a `coverage` block in
141    /// `--format json`). Requires the `tsc → node` path: incompatible with
142    /// `--inspect` and `--no-run`, and errors if only `tsx` is available.
143    #[arg(long)]
144    pub coverage: bool,
145    /// Run the `system` suites against a real runtime instead of in process:
146    /// `dev`, a local `bynk dev` the runner starts itself (through `bynk
147    /// test` only), or a target named under `[test.targets]` in `bynk.toml`.
148    /// A bare URL is refused, and so is a target marked `production = true`.
149    /// A named target's secrets are read from the environment. Only the
150    /// `system` suites run, and a case that uses what a real runtime can't
151    /// honour (an `on call` address, `advance Clock`, a cron or queue address,
152    /// an asset fetch) is refused unless `--skip-unsupported` is passed.
153    #[arg(long, value_name = "TARGET")]
154    pub against: Option<String>,
155    /// With `--against`, skip each `system` case a real runtime can't
156    /// honour, naming it and why, instead of refusing the run.
157    #[arg(long, requires = "against")]
158    pub skip_unsupported: bool,
159    /// With `--against`, how long a failing `expect` is retried before it
160    /// fails, for each retried stretch: the addresses since the last unsafe one (anything but `GET`,
161    /// `HEAD` or `OPTIONS`) are re-run before each retry, so a real system's
162    /// latency doesn't fail a case. A duration such as `5s`, `500ms` or `0`
163    /// (no retry).
164    #[arg(
165        long,
166        value_name = "DURATION",
167        requires = "against",
168        default_value = "5s"
169    )]
170    pub settle: Option<String>,
171}
172
173/// Where `test` writes its output: `-o`, or `<input>/out`.
174fn output_root_for(input: &Path, output: Option<&Path>) -> PathBuf {
175    output.map_or_else(|| input.join("out"), Path::to_path_buf)
176}
177
178/// Normalise a `--seed` value (`0x5f3a` or `5f3a`) to the bare-hex form the
179/// runner reads from `BYNK_TEST_SEED` (JS `parseInt(_, 16)` does not accept a
180/// `0x` prefix). Returns `None` for a non-hex value, so a typo is ignored rather
181/// than silently seeding to zero.
182fn normalise_seed(raw: &str) -> Option<String> {
183    let hex = raw
184        .strip_prefix("0x")
185        .or_else(|| raw.strip_prefix("0X"))
186        .unwrap_or(raw);
187    if hex.is_empty() || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
188        return None;
189    }
190    Some(hex.to_string())
191}
192
193/// In `--format json` mode the deterministic surface is the document on stdout,
194/// so a `<program> test:` line on stderr is fine but must never reach stdout.
195/// `program` prefixes stderr messages (`"bynkc"` or `"bynk"`) so they read the
196/// same as before the move.
197pub fn run_test(program: &str, args: TestArgs) -> ExitCode {
198    let TestArgs {
199        input,
200        output,
201        no_run,
202        format,
203        inspect,
204        seed,
205        case,
206        suite,
207        partial_selection,
208        coverage,
209        against,
210        skip_unsupported,
211        settle,
212    } = args;
213    // `json` is "machine-readable": the document or the stream. `stream` says
214    // which; everything that prints a document goes through `print_run`.
215    let stream = format == TestFormat::Ndjson;
216    let json = format == TestFormat::Json || stream;
217    // #2267 (decision D): coverage is a whole-run aggregate and discovery is a
218    // document, so neither is a stream; `--format json` serves both.
219    if stream && (coverage || no_run) {
220        let message = if coverage {
221            "`--format ndjson` cannot be combined with `--coverage`: coverage is a whole-run report, so use `--format json`."
222        } else {
223            "`--format ndjson` cannot be combined with `--no-run`: discovery is a document, so use `--format json`."
224        };
225        crate::test_stream::print_run(true, &TestRun::runtime_error(message, None));
226        return ExitCode::FAILURE;
227    }
228    // #2138: `--against` — resolve and check the target before anything is
229    // built, so a refused run makes no request. `dev` is the `bynk` driver's
230    // to start (`bynk test --against dev`); here it is refused.
231    let mut remote = match against.as_deref() {
232        None => None,
233        Some(value) => {
234            let refused = |message: String| {
235                if json {
236                    crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
237                } else {
238                    eprintln!("{program} test: {message}");
239                }
240                ExitCode::FAILURE
241            };
242            let settle_ms = match settle.as_deref().map(crate::remote::parse_settle) {
243                None => crate::remote::DEFAULT_SETTLE_MS,
244                Some(Ok(ms)) => ms,
245                Some(Err(e)) => return refused(e),
246            };
247            if inspect || coverage {
248                return refused(
249                    "`--against` cannot be combined with `--inspect` or `--coverage`, which observe the in-process run".to_string(),
250                );
251            }
252            match crate::remote::resolve(
253                value,
254                &input,
255                |name| std::env::var(name).ok(),
256                "starts a local `bynk dev`, which only the `bynk` driver can do: run `bynk test --against dev`",
257            ) {
258                Ok(crate::remote::Against::Run(run)) => {
259                    Some(crate::remote::RemoteRun { settle_ms, ..run })
260                }
261                Ok(crate::remote::Against::StartDev(bynk)) => {
262                    return crate::dev_run::run(
263                        program,
264                        &crate::dev_run::DevRunArgs {
265                            input: input.clone(),
266                            output: output_root_for(&input, output.as_deref()),
267                            json,
268                            stream,
269                            seed: seed.clone(),
270                            filter: crate::test_filter::TestFilter::new(&suite, &case),
271                            skip_unsupported,
272                            settle: settle.clone(),
273                            run_id: crate::remote::fresh_run_id(),
274                            bynk,
275                        },
276                    );
277                }
278                Err(refusal) => return refused(refusal.to_string()),
279            }
280        }
281    };
282    // #854 DECISION C: `--coverage` requires the `tsc → node` path — the CI-shaped
283    // path with real `.js.map`s. `--inspect` is a debug path with no `tsc` (and a
284    // different map role), and `--no-run` never launches a process to observe.
285    // Reject both up front with an actionable message rather than producing
286    // silently-wrong or empty numbers.
287    if coverage && inspect {
288        return coverage_unsupported(
289            program,
290            json,
291            "`--coverage` cannot be combined with `--inspect` — coverage needs the `tsc → node` run, not the inspector.",
292        );
293    }
294    if coverage && no_run {
295        return coverage_unsupported(
296            program,
297            json,
298            "`--coverage` cannot be combined with `--no-run` — there is no run to measure.",
299        );
300    }
301    // v0.127 (editor-currency slice 6): the per-case run filter, #2273: now a set
302    // of cases and suites. An empty value is dropped, so an empty `--case` is
303    // still unset (run all) rather than "match the empty name".
304    let filter = crate::test_filter::TestFilter::new(&suite, &case).partial(partial_selection);
305    // v0.114: the root seed for generative `property` tests, threaded to the
306    // runner via `BYNK_TEST_SEED` (bare hex). An unparseable value is dropped
307    // with a warning so a run still proceeds with a fresh seed.
308    let seed_hex = match seed.as_deref() {
309        Some(raw) => match normalise_seed(raw) {
310            Some(hex) => Some(hex),
311            None => {
312                if !json {
313                    eprintln!(
314                        "{program} test: ignoring --seed `{raw}` (not a hex value like 0x5f3a)"
315                    );
316                }
317                None
318            }
319        },
320        None => None,
321    };
322    let output_root = output_root_for(&input, output.as_deref());
323    if !input.is_dir() {
324        eprintln!(
325            "{program} test: input `{}` must be a project directory containing `.bynk` files",
326            input.display()
327        );
328        return ExitCode::FAILURE;
329    }
330    // v0.9.1: rooting strategy (#46: shared with check/compile via
331    // `project_options`) — a `bynk.toml` or `src/` subdir selects split-paths
332    // mode (sources under `[paths] src`, tests under `[paths] tests`); else the
333    // legacy single-tree where `<input>` is both the source and tests root.
334    // `--inspect` compiles a debug build: `.ts` import specifiers so the emitted
335    // entry runs directly under Node's strip-only type-stripping (slice 2), where
336    // slice 1's source maps apply unchanged. A normal run keeps `.js` specifiers
337    // for the `tsc → node` path.
338    let options = {
339        // v0.115: `test` compiles the dev/test profile — the function
340        // contract call-site guard is emitted (DECISION J). `compile`
341        // leaves it off, so contract checks never reach production.
342        // #2078: reconcile events against the committed `bynk.schema.lock`,
343        // read-only — a non-additive change fails `test` as it fails a
344        // build, and `out.schema_lock` is never written back.
345        let o = match crate::try_project_options(&input)
346            .map_err(|e| e.to_string())
347            .and_then(|o| Ok(o.schema_registry(crate::schema_lock::read_only(&input)?)))
348        {
349            Ok(o) => o.contracts(true),
350            Err(e) => {
351                if json {
352                    crate::test_stream::print_run(stream, &TestRun::runtime_error(e, None));
353                } else {
354                    eprintln!("{program} test: {e}");
355                }
356                return ExitCode::FAILURE;
357            }
358        };
359        // #2138: a remote run emits only the `system` suites, driven at
360        // the target's URLs.
361        let o = o.remote_tests(remote.as_ref().map(|run| bynk_emit::project::RemoteTests {
362            skip_unsupported,
363            vars: run.vars.clone(),
364            secrets: run.secrets.clone(),
365            dev: run.dev_env.is_some(),
366            only_env: run.dev_env.clone(),
367        }));
368        if inspect {
369            o.import_ext(ImportExt::Ts)
370        } else {
371            o
372        }
373    };
374    let out = match bynk_emit::project::compile_project(&options) {
375        Ok(out) => out,
376        Err(failure) => {
377            if json {
378                crate::test_stream::print_run(
379                    stream,
380                    &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
381                );
382            } else {
383                crate::print_project_failure(&failure);
384            }
385            return ExitCode::FAILURE;
386        }
387    };
388    // v0.67: `--no-run --format json` is pure discovery — render the suite/case
389    // manifest the compile retained and stop. No TS is written, no `tsc`/`node`
390    // runs, and the integration workers re-compile below is skipped (the manifest
391    // already carries integration suites from the compile above). A compile
392    // failure took the `compile`-error path above, exactly as a run would.
393    if no_run && json {
394        crate::test_stream::print_run(stream, &TestRun::discovered(discovery_suites(&out)));
395        return ExitCode::SUCCESS;
396    }
397    // #2138: the cases the remote build skipped, and the target, named before
398    // the first request.
399    if let Some(run) = remote.as_mut() {
400        run.skipped = out
401            .discovered
402            .iter()
403            .flat_map(|s| s.skipped.iter().map(|k| (s.name.clone(), k.clone())))
404            .collect();
405        eprint!("{program} test: {}", run.banner());
406        if !json {
407            for (suite, skip) in run
408                .skipped
409                .iter()
410                .filter(|(suite, skip)| filter.selects(suite, &skip.case))
411            {
412                eprintln!(
413                    "{program} test: skipped `{suite}` case \"{}\" [{}]: {}",
414                    skip.case, skip.code, skip.reason
415                );
416            }
417        }
418    }
419
420    // Write every artefact to disk under the output root.
421    let mut wrote_any_test = false;
422    let mut has_integration = false;
423    for (path, doc) in &out.artefacts.docs {
424        // Map-aware write (slice 2): carries the `.ts.map` siblings + trailers so
425        // a debug run (`--inspect`) can resolve `.bynk` breakpoints. Harmless for a
426        // normal run, which transpiles via `tsc` and ignores the trailer.
427        if let Err(e) = crate::write_document(path, doc, &out.artefacts.docs, &output_root) {
428            eprintln!(
429                "{program} test: could not write `{}`: {e}",
430                output_root.join(path).display()
431            );
432            return ExitCode::FAILURE;
433        }
434        let rel = path.to_string_lossy();
435        if rel.starts_with("tests/") {
436            wrote_any_test = true;
437        }
438        if rel.starts_with("tests/integration_") {
439            has_integration = true;
440        }
441    }
442
443    // v0.16: integration tests stand their participants up as real Workers, so
444    // they import the workers-mode output (`workers/**`) and the serialise/
445    // deserialise helpers the workers commons emit. The bundle compile above
446    // does not produce those, so run a second compile in workers mode and
447    // overlay everything except the `tests/` tree (whose unit modules import
448    // the bundle output). The workers commons are a strict superset of the
449    // bundle ones, so overwriting them is safe for the bundle code too.
450    let mut workers_modules = None;
451    if has_integration {
452        // v0.115/slice 2: reuse `options` (not a fresh `project_options(&input)`)
453        // so this second compile keeps `contracts(true)` and, under `--inspect`,
454        // `import_ext(Ts)` — a from-scratch rebuild silently dropped both.
455        let workers_out =
456            bynk_emit::project::compile_project(&options.clone().target(BuildTarget::Workers));
457        let workers_out = match workers_out {
458            Ok(o) => o,
459            Err(failure) => {
460                if json {
461                    crate::test_stream::print_run(
462                        stream,
463                        &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
464                    );
465                } else {
466                    crate::print_project_failure(&failure);
467                }
468                return ExitCode::FAILURE;
469            }
470        };
471        for (path, doc) in &workers_out.artefacts.docs {
472            if path.to_string_lossy().starts_with("tests/") {
473                continue;
474            }
475            if let Err(e) =
476                crate::write_document(path, doc, &workers_out.artefacts.docs, &output_root)
477            {
478                eprintln!(
479                    "{program} test: could not write `{}`: {e}",
480                    output_root.join(path).display()
481                );
482                return ExitCode::FAILURE;
483            }
484        }
485        workers_modules = Some(workers_out.artefacts.modules.clone());
486    }
487
488    // #2321: the WebAssembly modules adapter bindings include, with the Node form
489    // of each loader (after every document write, which restores the Workers
490    // form).
491    for modules in [Some(&out.artefacts.modules), workers_modules.as_ref()]
492        .into_iter()
493        .flatten()
494    {
495        if let Err(e) = crate::write_modules_for_node(modules, &output_root) {
496            eprintln!("{program} test: could not write a WebAssembly module: {e}");
497            return ExitCode::FAILURE;
498        }
499    }
500
501    if !wrote_any_test {
502        if json {
503            crate::test_stream::print_run(stream, &empty_run());
504        } else {
505            eprintln!(
506                "{program} test: no test declarations found in `{}`",
507                input.display()
508            );
509        }
510        return ExitCode::SUCCESS;
511    }
512
513    let main_ts = output_root.join("tests").join("main.ts");
514    if no_run {
515        // Rich `--no-run` is the CI emit helper: write the runner modules and
516        // report where they landed. (JSON `--no-run` already returned above with
517        // the discovery document — it never reaches here.)
518        eprintln!("{program} test: tests emitted to {}", main_ts.display());
519        return ExitCode::SUCCESS;
520    }
521
522    // Slice 2 (ADR 0104): launch the emitted `.ts` test entry directly under
523    // Node's inspector. No `tsc` — the `.ts` runs under line-preserving
524    // type-stripping, so the source maps written above resolve `.bynk`
525    // breakpoints. Node prints its inspector URL; a debugger attaches there.
526    if inspect {
527        return run_inspect(program, &main_ts, seed_hex.as_deref(), &filter);
528    }
529
530    let tsconfig = output_root.join("tsconfig.json");
531    // #854: coverage needs tsc's `.js.map`s (remap hop 1). Overwrite the default
532    // tsconfig the compile wrote with the `sourceMap: true` variant, kept
533    // coverage-only so a normal test run / deployment build ships no maps.
534    if coverage
535        && let Err(e) = std::fs::write(
536            &tsconfig,
537            bynk_emit::emitter::emit_tsconfig_with_source_maps(),
538        )
539    {
540        return coverage_unsupported(
541            program,
542            json,
543            format!("could not enable source maps for coverage: {e}"),
544        );
545    }
546    // Preferred: `tsc -p out/tsconfig.json` → `node out-js/tests/main.js`.
547    // tsc gives us full type-checking before execution and matches what a
548    // production deployment build would do. If tsc is missing, fall back to
549    // tsx, which compiles-and-runs in one step. We also try npx-mediated
550    // variants so a developer with `npm` available doesn't need a global
551    // install. If nothing works, emit an actionable error message.
552    let out_js_root = output_root
553        .parent()
554        .map(|p| p.join("out-js"))
555        .unwrap_or_else(|| PathBuf::from("out-js"));
556    let main_js = out_js_root.join("tests").join("main.js");
557
558    // #2146: tsc emits ES modules (the compile writes `out/package.json`
559    // declaring `"type": "module"`, which the emitted tsconfig's `module:
560    // NodeNext` follows, #2148), but `out-js` sits in no such `package.json`
561    // scope, so mark it ESM for Node to run the result as such. The `out/`
562    // tree is left as the compiler wrote it.
563    if let Err(e) = write_esm_marker(&out_js_root) {
564        let msg = format!(
565            "could not write {}: {e}",
566            out_js_root.join("package.json").display()
567        );
568        if json {
569            crate::test_stream::print_run(stream, &TestRun::runtime_error(msg, None));
570        } else {
571            eprintln!("{program} test: {msg}");
572        }
573        return ExitCode::FAILURE;
574    }
575
576    // Try a sequence of (program, prefix args) tsc invocations. In JSON mode the
577    // tsc step is captured so its output never reaches stdout (the document is
578    // the only thing on stdout); a tsc failure on the emitted TS is a
579    // toolchain/internal problem, surfaced as a `runtime` error.
580    // #1672: the `npx` fallback provisions the TypeScript major the output is
581    // verified against and users get, not an older pin.
582    let typescript_pkg = format!("typescript@{}", bynk_emit::TYPESCRIPT_MAJOR_TESTED);
583    let mut start_failures: Vec<String> = Vec::new();
584    let tsc_runners: Vec<(&str, Vec<&str>)> = vec![
585        ("tsc", vec![]),
586        ("npx", vec!["--yes", "-p", typescript_pkg.as_str(), "tsc"]),
587    ];
588    for (prog, prefix) in &tsc_runners {
589        let Some(path) = resolve_tool(prog) else {
590            continue;
591        };
592        let mut cmd = ProcCommand::new(&path);
593        for p in prefix {
594            cmd.arg(p);
595        }
596        cmd.arg("-p").arg(&tsconfig);
597        let tsc_ok = if json {
598            match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output() {
599                Ok(out) if out.status.success() => true,
600                Ok(out) => {
601                    // tsc writes its diagnostics to *stdout*; capturing only
602                    // stderr left the document's most useful field empty.
603                    let mut detail = String::from_utf8_lossy(&out.stdout).into_owned();
604                    let err_text = String::from_utf8_lossy(&out.stderr);
605                    if !err_text.trim().is_empty() {
606                        if !detail.is_empty() {
607                            detail.push('\n');
608                        }
609                        detail.push_str(&err_text);
610                    }
611                    crate::test_stream::print_run(
612                        stream,
613                        &TestRun::runtime_error(
614                            "tsc rejected the generated TypeScript",
615                            Some(detail),
616                        ),
617                    );
618                    return ExitCode::FAILURE;
619                }
620                Err(e) => {
621                    start_failures.push(start_failure(&path, &e));
622                    continue;
623                }
624            }
625        } else {
626            match cmd
627                .stdout(Stdio::inherit())
628                .stderr(Stdio::inherit())
629                .status()
630            {
631                Ok(s) if s.success() => true,
632                Ok(_) => {
633                    eprintln!(
634                        "{program} test: tsc reported errors against {}",
635                        tsconfig.display()
636                    );
637                    return ExitCode::FAILURE;
638                }
639                Err(e) => {
640                    start_failures.push(start_failure(&path, &e));
641                    continue;
642                }
643            }
644        };
645        if tsc_ok {
646            let mut node_cmd = ProcCommand::new(crate::probe::program_path("node"));
647            node_cmd.arg(&main_js);
648            // #854: the coverage path owns the node launch (it sets
649            // `NODE_V8_COVERAGE` and reads the result back), so it does not go
650            // through `finish_runner`.
651            if coverage {
652                return run_with_coverage(
653                    program,
654                    node_cmd,
655                    json,
656                    seed_hex.as_deref(),
657                    &filter,
658                    &out_js_root,
659                    &output_root,
660                    &input,
661                    &out.discovered,
662                );
663            }
664            return match finish_runner(
665                program,
666                node_cmd,
667                format,
668                seed_hex.as_deref(),
669                &filter,
670                remote.as_ref(),
671                &out.discovered,
672            ) {
673                Ok(code) => code,
674                Err(e) => {
675                    if json {
676                        crate::test_stream::print_run(
677                            stream,
678                            &TestRun::runtime_error(format!("could not run node: {e}"), None),
679                        );
680                    } else {
681                        eprintln!(
682                            "{program} test: tsc succeeded but `node {}` failed: {e}",
683                            main_js.display()
684                        );
685                    }
686                    ExitCode::FAILURE
687                }
688            };
689        }
690    }
691
692    // #854 DECISION C: with `--coverage`, the `tsc → node` path is required — do
693    // not silently fall through to `tsx`, whose on-the-fly transform muddies
694    // which map applies. Fail clearly instead.
695    if coverage {
696        // #1761 review: a `tsc` that is installed but won't start is reported as
697        // such here too, not as missing.
698        if !start_failures.is_empty() {
699            return report_start_failures(program, json, stream, &start_failures, true);
700        }
701        return coverage_unsupported(
702            program,
703            json,
704            "`--coverage` requires `tsc` and `node` on PATH (the CI-shaped path with `.js.map`s); the `tsx` fallback is not supported for coverage.",
705        );
706    }
707
708    // tsx fallback chain.
709    let tsx_runners: Vec<(&str, Vec<&str>)> = vec![("tsx", vec![]), ("npx", vec!["--yes", "tsx"])];
710    for (prog, prefix) in &tsx_runners {
711        let Some(path) = resolve_tool(prog) else {
712            continue;
713        };
714        let mut cmd = ProcCommand::new(&path);
715        for p in prefix {
716            cmd.arg(p);
717        }
718        cmd.arg(&main_ts);
719        match finish_runner(
720            program,
721            cmd,
722            format,
723            seed_hex.as_deref(),
724            &filter,
725            remote.as_ref(),
726            &out.discovered,
727        ) {
728            Ok(code) => return code,
729            Err(e) => start_failures.push(start_failure(&path, &e)),
730        }
731    }
732
733    if !start_failures.is_empty() {
734        return report_start_failures(program, json, stream, &start_failures, false);
735    }
736
737    if json {
738        crate::test_stream::print_run(
739            stream,
740            &TestRun::runtime_error(
741                "no test runner found: requires `tsc` (with Node.js) or `tsx` on PATH",
742                None,
743            ),
744        );
745    } else {
746        eprintln!(
747            "{program} test: requires either `tsc` (with Node.js) or `tsx` on PATH. \
748             Install one of:\n{}",
749            install_advice(false)
750        );
751    }
752    ExitCode::FAILURE
753}
754
755/// #1758: the run found runners but none would start. Each failure names the
756/// resolved path and the error. In rich mode the install advice follows, since
757/// installing another runner is often the fix for a broken one. `coverage`
758/// limits that advice to `tsc`, the only runner `--coverage` accepts.
759fn report_start_failures(
760    program: &str,
761    json: bool,
762    stream: bool,
763    failures: &[String],
764    coverage: bool,
765) -> ExitCode {
766    if json {
767        crate::test_stream::print_run(
768            stream,
769            &TestRun::runtime_error("no test runner could be started", Some(failures.join("\n"))),
770        );
771    } else {
772        eprintln!("{program} test: no test runner could be started:");
773        for failure in failures {
774            eprintln!("  - {failure}");
775        }
776        eprintln!("Or install another:\n{}", install_advice(coverage));
777    }
778    ExitCode::FAILURE
779}
780
781/// The install advice for a missing or broken runner, one indented line each.
782/// With `coverage`, only `tsc`, since `--coverage` doesn't accept `tsx`.
783fn install_advice(coverage: bool) -> String {
784    let tsc = format!(
785        "  - `npm install -g typescript@{}` (provides tsc, which type-checks; requires Node.js to run output)",
786        bynk_emit::TYPESCRIPT_MAJOR_TESTED
787    );
788    if coverage {
789        return tsc;
790    }
791    format!(
792        "{tsc}\n  - `npm install -g tsx` (runs TypeScript in one step, without type-checking)\n  Or run inside a project where `npx tsc` / `npx tsx` resolves."
793    )
794}
795
796/// A normal run with no suites — the JSON-mode document for a project with no
797/// tests, or `--no-run`.
798fn empty_run() -> TestRun {
799    TestRun::empty()
800}
801
802/// v0.67: map the compile's retained test manifest into discovery [`Suite`]s for
803/// the `--no-run --format json` document. Each case is `outcome: "discovered"`,
804/// carrying its declaration `location` (when known) for editor click-through.
805fn discovery_suites(out: &ProjectOutput) -> Vec<Suite> {
806    out.discovered
807        .iter()
808        .map(|s| Suite {
809            name: s.name.clone(),
810            kind: s.kind.to_string(),
811            cases: s
812                .cases
813                .iter()
814                .map(|c| Case {
815                    name: c.name.clone(),
816                    outcome: "discovered".to_string(),
817                    message: None,
818                    location: c.location.as_ref().map(|l| Location {
819                        path: l.path.clone(),
820                        line: l.line,
821                        col: l.col,
822                    }),
823                    retries: None,
824                    tier: c.tier.map(str::to_string),
825                    kind: c.generative.map(str::to_string),
826                    seed: None,
827                    counterexample: None,
828                    violation: None,
829                    refusals: None,
830                    duration_ms: None,
831                })
832                .collect(),
833        })
834        .collect()
835}
836
837/// Execute the built runner command and produce its exit code. In JSON mode the
838/// runner's stdout (NDJSON) and stderr are captured, folded into the pinned
839/// document, and printed; in NDJSON mode each event is forwarded as the runner
840/// writes it ([`crate::test_stream`]); otherwise stdio is inherited so the human
841/// ✓ / ✗ output flows straight through. Either way the **exit code follows the runner's own
842/// process status**, so a mid-run crash (a complete NDJSON prefix but no
843/// `run-end`) is never reported as success.
844fn finish_runner(
845    program: &str,
846    mut cmd: ProcCommand,
847    format: TestFormat,
848    seed_hex: Option<&str>,
849    filter: &crate::test_filter::TestFilter,
850    remote: Option<&crate::remote::RemoteRun>,
851    discovered: &[bynk_emit::project::DiscoveredSuite],
852) -> std::io::Result<ExitCode> {
853    if let Some(hex) = seed_hex {
854        cmd.env("BYNK_TEST_SEED", hex);
855    }
856    // #2138: the remote harness reads each Worker's URL from here; the
857    // target's secrets are already in the inherited environment.
858    if let Some(run) = remote {
859        cmd.env("BYNK_TEST_TARGETS", run.targets_json());
860        cmd.env(crate::remote::SECRETS_ENV, run.secrets_json());
861        cmd.env("BYNK_TEST_SETTLE_MS", run.settle_ms.to_string());
862        // #2138: the run's own `run.id`, always set, so a value left in the
863        // environment never makes two runs share one.
864        cmd.env(crate::remote::RUN_ID_ENV, &run.run_id);
865    }
866    // The skipped cases the filter selects are not in the build, so the runner
867    // is told they exist, and the document lists only those.
868    let selected_skips: Vec<&(String, bynk_emit::project::RemoteSkip)> = remote
869        .map(|run| {
870            run.skipped
871                .iter()
872                .filter(|(suite, skip)| filter.selects(suite, &skip.case))
873                .collect()
874        })
875        .unwrap_or_default();
876    filter
877        .clone()
878        .with_skipped(
879            selected_skips
880                .iter()
881                .map(|(suite, skip)| (suite.as_str(), skip.case.as_str())),
882        )
883        .apply(program, &mut cmd);
884    if format == TestFormat::Ndjson {
885        // #2267: forward each event as the runner writes it.
886        cmd.env("BYNK_TEST_FORMAT", "ndjson");
887        let mut events = crate::test_stream::Stream::new(crate::test_stream::StreamContext {
888            discovered,
889            skipped: selected_skips
890                .iter()
891                .map(|(suite, k)| (suite.clone(), k.case.clone(), k.reason.clone()))
892                .collect(),
893            transport: remote.map(crate::remote::RemoteRun::transport),
894        });
895        let status = crate::test_stream::forward(cmd, &mut events, &mut std::io::stdout().lock())?;
896        events.unmatched().report(program);
897        return Ok(exit_from(status.success()));
898    }
899    if format == TestFormat::Json {
900        cmd.env("BYNK_TEST_FORMAT", "ndjson");
901        let out = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output()?;
902        let stdout = String::from_utf8_lossy(&out.stdout);
903        let stderr = String::from_utf8_lossy(&out.stderr);
904        let parsed = crate::test_json::parse_ndjson(&stdout);
905        let unmatched = parsed.unmatched.clone();
906        let mut doc = parsed.into_document(&stderr).with_tiers(discovered);
907        if let Some(run) = remote {
908            let skipped: Vec<(String, String, String)> = selected_skips
909                .iter()
910                .map(|(suite, k)| (suite.clone(), k.case.clone(), k.reason.clone()))
911                .collect();
912            doc = doc.with_remote(run.transport(), &skipped);
913        }
914        print!("{}", doc.render());
915        unmatched.report(program);
916        Ok(exit_from(out.status.success()))
917    } else {
918        let status = cmd
919            .stdout(Stdio::inherit())
920            .stderr(Stdio::inherit())
921            .status()?;
922        Ok(exit_from(status.success()))
923    }
924}
925
926fn exit_from(success: bool) -> ExitCode {
927    if success {
928        ExitCode::SUCCESS
929    } else {
930        ExitCode::FAILURE
931    }
932}
933
934/// #854: a `--coverage` request that cannot be honoured (unsupported flag combo,
935/// no `tsc → node`, or a setup error). In JSON mode it is a `runtime` error so
936/// the document stays the only thing on stdout; in rich mode a plain stderr line.
937fn coverage_unsupported(program: &str, json: bool, message: impl Into<String>) -> ExitCode {
938    let message = message.into();
939    if json {
940        // `--format ndjson` refuses `--coverage` before this is reachable.
941        crate::test_stream::print_run(false, &TestRun::runtime_error(message, None));
942    } else {
943        eprintln!("{program} test --coverage: {message}");
944    }
945    ExitCode::FAILURE
946}
947
948/// #854: run the emitted runner under V8 coverage and attribute the result to
949/// `.bynk` source. Owns the `node` launch: it points `NODE_V8_COVERAGE` at a
950/// scratch dir, runs the suite exactly as [`finish_runner`] would, then remaps
951/// the V8 output through the emitted source maps ([`crate::coverage`]). In rich
952/// mode the summary table is appended after the human ✓ / ✗ output; in JSON mode
953/// the `coverage` block is folded into the pinned document. The **exit code
954/// follows the run's own status** — coverage is a report about the run, never a
955/// gate on it (a partial or unreadable map degrades the numbers, not the code).
956#[allow(clippy::too_many_arguments)]
957fn run_with_coverage(
958    program: &str,
959    mut cmd: ProcCommand,
960    json: bool,
961    seed_hex: Option<&str>,
962    filter: &crate::test_filter::TestFilter,
963    out_js_root: &Path,
964    out_root: &Path,
965    source_root: &Path,
966    discovered: &[bynk_emit::project::DiscoveredSuite],
967) -> ExitCode {
968    // A scratch dir beside the build output; cleared first so a prior run's JSON
969    // never leaks in. `NODE_V8_COVERAGE` writes one file per process on exit.
970    let cov_dir = out_root.join(".v8-coverage");
971    let _ = std::fs::remove_dir_all(&cov_dir);
972    if let Err(e) = std::fs::create_dir_all(&cov_dir) {
973        return coverage_unsupported(
974            program,
975            json,
976            format!("could not create the coverage dir: {e}"),
977        );
978    }
979    cmd.env("NODE_V8_COVERAGE", &cov_dir);
980    if let Some(hex) = seed_hex {
981        cmd.env("BYNK_TEST_SEED", hex);
982    }
983    filter.apply(program, &mut cmd);
984
985    let collect = || {
986        crate::coverage::collect_coverage(&cov_dir, out_js_root, out_root, source_root)
987            .unwrap_or_default()
988    };
989
990    let code = if json {
991        cmd.env("BYNK_TEST_FORMAT", "ndjson");
992        let out = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output() {
993            Ok(o) => o,
994            Err(e) => {
995                let _ = std::fs::remove_dir_all(&cov_dir);
996                return coverage_unsupported(program, true, format!("could not run node: {e}"));
997            }
998        };
999        let stdout = String::from_utf8_lossy(&out.stdout);
1000        let stderr = String::from_utf8_lossy(&out.stderr);
1001        let report = collect();
1002        let parsed = crate::test_json::parse_ndjson(&stdout);
1003        let unmatched = parsed.unmatched.clone();
1004        let doc = parsed
1005            .into_document(&stderr)
1006            .with_tiers(discovered)
1007            .with_coverage(&report);
1008        print!("{}", doc.render());
1009        unmatched.report(program);
1010        exit_from(out.status.success())
1011    } else {
1012        let status = cmd
1013            .stdout(Stdio::inherit())
1014            .stderr(Stdio::inherit())
1015            .status();
1016        let status = match status {
1017            Ok(s) => s,
1018            Err(e) => {
1019                let _ = std::fs::remove_dir_all(&cov_dir);
1020                eprintln!("{program} test --coverage: could not run node: {e}");
1021                return ExitCode::FAILURE;
1022            }
1023        };
1024        let report = collect();
1025        print!("{}", crate::coverage::render_rich(&report));
1026        exit_from(status.success())
1027    };
1028    let _ = std::fs::remove_dir_all(&cov_dir);
1029    code
1030}
1031
1032/// #2146: mark the tsc output tree as ES modules, so Node runs the ESM that tsc
1033/// emits from the `"type": "module"` output tree (#2148).
1034fn write_esm_marker(out_js_root: &Path) -> std::io::Result<()> {
1035    std::fs::create_dir_all(out_js_root)?;
1036    std::fs::write(
1037        out_js_root.join("package.json"),
1038        "{\n  \"type\": \"module\"\n}\n",
1039    )
1040}
1041
1042/// Node's default inspector port.
1043const NODE_INSPECT_PORT: u16 = 9229;
1044
1045/// The `--inspect-brk` flag for `run_inspect` (#2115). Node's default port,
1046/// 9229, when it is free, so a debugger that looks there by default (Chrome's
1047/// `chrome://inspect`) still finds the runner. When something else holds it
1048/// (another inspected process, a stray `workerd`), plain `--inspect-brk` would
1049/// print `Starting inspector on 127.0.0.1:9229 failed: address already in use`
1050/// and run the tests *without* an inspector, so no debugger could attach. Then
1051/// ask for port 0: Node picks a free one and prints it in the `ws://` URL, which
1052/// is what attaching clients (the VS Code extension included) read.
1053fn inspect_brk_arg(default_port_free: bool) -> &'static str {
1054    if default_port_free {
1055        "--inspect-brk"
1056    } else {
1057        "--inspect-brk=127.0.0.1:0"
1058    }
1059}
1060
1061/// Slice 2 (ADR 0104): launch the emitted `.ts` test entry under Node's inspector
1062/// and hand off. Node prints its inspector `ws://` URL to stderr and pauses at the
1063/// first line (`--inspect-brk`) until a JavaScript debugger attaches; breakpoints
1064/// set in `.bynk` resolve through the emitted source maps. `--experimental-strip-types`
1065/// runs the `.ts` directly under line-preserving type-stripping (Node ≥ 22.6;
1066/// unflagged ≥ 23.6) — no `tsc`, so slice 1's `.ts.map` applies to the running file.
1067fn run_inspect(
1068    program: &str,
1069    entry: &Path,
1070    seed_hex: Option<&str>,
1071    filter: &crate::test_filter::TestFilter,
1072) -> ExitCode {
1073    let Some(node) = resolve_tool("node") else {
1074        eprintln!("{program} test --inspect: `node` was not found on PATH");
1075        return ExitCode::FAILURE;
1076    };
1077    eprintln!("{program} test --inspect: launching the test runner under Node's inspector.");
1078    eprintln!("  Attach a JavaScript debugger to the inspector URL below; breakpoints set");
1079    eprintln!("  in `.bynk` sources resolve through the emitted source maps.");
1080    eprintln!("  (Requires Node \u{2265} 22.6 for TypeScript type-stripping.)");
1081    let mut cmd = ProcCommand::new(node);
1082    if let Some(hex) = seed_hex {
1083        cmd.env("BYNK_TEST_SEED", hex);
1084    }
1085    filter.apply(program, &mut cmd);
1086    let default_free = std::net::TcpListener::bind(("127.0.0.1", NODE_INSPECT_PORT)).is_ok();
1087    if !default_free {
1088        eprintln!(
1089            "  Port {NODE_INSPECT_PORT} is in use, so the inspector takes a free port; use the URL below."
1090        );
1091    }
1092    cmd.arg("--experimental-strip-types")
1093        .arg(inspect_brk_arg(default_free))
1094        .arg(entry);
1095    match cmd
1096        .stdout(Stdio::inherit())
1097        .stderr(Stdio::inherit())
1098        .status()
1099    {
1100        Ok(s) => exit_from(s.success()),
1101        Err(e) => {
1102            eprintln!("{program} test --inspect: could not run node: {e}");
1103            ExitCode::FAILURE
1104        }
1105    }
1106}
1107
1108#[cfg(test)]
1109mod inspect_port_tests {
1110    use super::inspect_brk_arg;
1111
1112    #[test]
1113    fn uses_the_default_port_when_free_and_a_free_port_otherwise() {
1114        assert_eq!(inspect_brk_arg(true), "--inspect-brk");
1115        assert_eq!(inspect_brk_arg(false), "--inspect-brk=127.0.0.1:0");
1116    }
1117}