diff --git a/engine/native/src/js.rs b/engine/native/src/js.rs index b5cf50b0..b7ca3400 100644 --- a/engine/native/src/js.rs +++ b/engine/native/src/js.rs @@ -279,6 +279,13 @@ fn run_here(root: &Path, cwd: &Path, entry: Entry, argv: Vec, env: serde exit = 1; OUT.with(|o| o.borrow_mut().1.push_str(&format!("{e}\n"))); } + } else if node { + // Node's process.exitCode: the status a script that ends on its own leaves (engine/cli's native.ts sets it, so a + // shell verb's refusal exits 1) + let _ = c.eval("globalThis.__raea_exit_code = () => { const n = Number(globalThis.process?.exitCode ?? 0); return Number.isInteger(n) ? n : 1; };", "exit-code"); + if let Some(Ok(n)) = c.call("__raea_exit_code", &[]) { + exit = n as i32; + } } drop(c); SOURCES.with(|s| s.borrow_mut().clear()); diff --git a/engine/native/tests/node.rs b/engine/native/tests/node.rs index 64416427..4f535ef1 100644 --- a/engine/native/tests/node.rs +++ b/engine/native/tests/node.rs @@ -79,3 +79,17 @@ process.exit(5); }); assert_eq!(got, want); } + +#[test] +fn a_script_that_sets_exit_code_exits_with_it() { + let d = std::env::temp_dir().join(format!("raea-node-exitcode-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("set.ts"), "process.stderr.write(\"refused\\n\");\nprocess.exitCode = 3;\n").unwrap(); + std::fs::write(d.join("plain.ts"), "process.stdout.write(\"ok\");\n").unwrap(); + let set = raea_native::js::run_node(&d.join("set.ts"), &[], String::new(), Duration::from_secs(20)); + let plain = raea_native::js::run_node(&d.join("plain.ts"), &[], String::new(), Duration::from_secs(20)); + let _ = std::fs::remove_dir_all(&d); + // as Node: the status it set, and what it wrote before ending + assert_eq!((set.exit, set.stderr.as_str()), (3, "refused\n")); + assert_eq!((plain.exit, plain.stdout.as_str()), (0, "ok")); +}