Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

Merge #89: node regex literals

EL4CTEOf9f948249087
diff --cc src/node.rs
index 677b18b,a094e62..a2a3ee2
--- a/src/node.rs
+++ b/src/node.rs
@@@ -710,1055 -648,427 +710,1280 @@@ fn without_shim(text: &str, port: &Port
mod tests {
use super::*;
- #[test]
- fn bun_and_deno_get_their_own_command_lines() {
- let args = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
- assert_eq!(Runtime::of("/usr/local/bin/bun"), Some(Runtime::Bun));
- assert_eq!(Runtime::of("C:\\deno\\deno.exe"), Some(Runtime::Deno));
- assert!(is_node("bun") && is_node("deno") && !is_node("python"));
- assert_eq!(Runtime::Node.with(&["--require", "r.cjs"], &args("app.js x")), args("--require r.cjs app.js x"));
- assert_eq!(Runtime::Bun.with(&["--preload", "r.cjs"], &args("run app.ts")), args("--preload r.cjs app.ts"));
- assert_eq!(Runtime::Deno.with(&["--cpu-prof"], &args("run -A app.ts x")), args("run --cpu-prof -A app.ts x"));
- assert_eq!(Runtime::Deno.with(&["--cpu-prof"], &args("app.ts")), args("run --cpu-prof app.ts"));
- assert_eq!(Runtime::Deno.script(Path::new("runner.mjs")), args("run -A runner.mjs"));
- assert_eq!(entry(&args("run -A --allow-ffi app.ts data.txt")).map(String::as_str), Some("app.ts"));
- assert_eq!(entry(&args("run app.ts")).map(String::as_str), Some("app.ts"));
- }
-
- #[test]
- fn worker_threads_are_recorded() {
- if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
- eprintln!("no node on PATH, skipping");
- return;
- }
- let dir = std::env::temp_dir().join(format!("fa-node-workers-{}", std::process::id()));
- fs::create_dir_all(&dir).unwrap();
- fs::write(dir.join("recorder.cjs"), RECORDER).unwrap();
- fs::write(
- dir.join("lib.cjs"),
- "function sq(x) {\n return x * x;\n}\nsq = globalThis.__fastAnythingWrap ? globalThis.__fastAnythingWrap(sq) : sq;\nmodule.exports = { sq };\n",
- )
- .unwrap();
- fs::write(
- dir.join("app.cjs"),
- "const { Worker, isMainThread, parentPort } = require(\"node:worker_threads\");\n\
- const { sq } = require(\"./lib.cjs\");\n\
- if (isMainThread) {\n\
- \x20 sq(1);\n\
- \x20 for (let i = 0; i < 2; i++) new Worker(__filename).on(\"message\", (m) => console.log(m));\n\
- } else {\n\
- \x20 let t = 0;\n\
- \x20 for (let i = 0; i < 5; i++) t += sq(i);\n\
- \x20 parentPort.postMessage(t);\n\
- }\n",
- )
- .unwrap();
- let out = Command::new("node")
- .args(["--require", "./recorder.cjs", "app.cjs"])
- .current_dir(&dir)
- .env("FAST_ANYTHING_RECORD_OUT", dir.join("rec.jsonl"))
- .env("FAST_ANYTHING_RECORD_META", dir.join("rec.meta.json"))
- .env("FAST_ANYTHING_RECORD_LIMIT", "500")
- .output()
- .unwrap();
- let meta = fs::read_to_string(dir.join("rec.meta.json")).unwrap_or_default();
- let lines = fs::read_to_string(dir.join("rec.jsonl")).unwrap_or_default().lines().count();
- let leftovers = fs::read_dir(&dir)
- .unwrap()
- .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().contains(".t"))
- .count();
- let _ = fs::remove_dir_all(&dir);
- assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
- let meta: Value = serde_json::from_str(&meta).unwrap();
- assert_eq!((meta["calls"].clone(), lines), (json!(11), 11), "1 call in the main thread, 5 in each worker");
- assert_eq!(leftovers, 0, "worker files are absorbed and removed");
- }
-
- #[test]
- fn maps_typescript() {
- assert_eq!(rust_type("number").as_deref(), Some("f64"));
- assert_eq!(rust_type("string[]").as_deref(), Some("Vec<String>"));
- assert_eq!(rust_type("Array<number>").as_deref(), Some("Vec<f64>"));
- assert_eq!(rust_type("readonly number[]").as_deref(), Some("Vec<f64>"));
- assert_eq!(rust_type("number | undefined").as_deref(), Some("Option<f64>"));
- assert_eq!(rust_type("string | null").as_deref(), Some("Option<String>"));
- assert_eq!(rust_type("Float64Array").as_deref(), Some("Float64Array"));
- assert_eq!(rust_type("Uint8ClampedArray").as_deref(), Some("Uint8ClampedArray"));
- assert_eq!(rust_type("BigInt64Array"), None);
- assert_eq!(rust_type("Buffer").as_deref(), Some("Buffer"));
- assert_eq!(rust_type("Set<string>").as_deref(), Some("std::collections::HashSet<String>"));
- assert_eq!(rust_type("Set<number>"), None);
- assert_eq!(rust_type("Map<string, number>"), None);
- assert_eq!(rust_type("Record<string, number>").as_deref(), Some("std::collections::HashMap<String, f64>"));
- assert_eq!(rust_type("string | number"), None);
- assert_eq!(rust_type("[number, number][]").as_deref(), Some("Vec<Vec<f64>>"));
- assert_eq!(rust_type("[number, string]"), None);
- assert_eq!(rust_type("Point"), None);
- }
-
- #[test]
- fn finds_the_script() {
- let args: Vec<String> =
- ["--require", "x.cjs", "--no-warnings", "app.mjs", "data.txt"].map(String::from).to_vec();
- assert_eq!(entry(&args).map(String::as_str), Some("app.mjs"));
- assert!(is_node("node") && is_node("/usr/bin/node") && is_node("C:\\nodejs\\node.exe") && !is_node("python"));
- assert_eq!(snake("editDistance"), "edit_distance");
- assert_eq!(snake("type"), "r#type");
- }
-
- #[test]
- fn entry_script_blocks_go_before_the_main_block() {
- let app = "function f(x) {\n return x;\n}\n\nif (import.meta.main) {\n console.log(f(1));\n}\n";
- let on = add_marked(app, "app.mjs:f", "f = g;", true);
- let (block, main) = (on.find("f = g;").unwrap(), on.find("if (import.meta.main)").unwrap());
- assert!(block < main, "{on}");
- assert_eq!(backend::strip_marked(&on, "//", "app.mjs:f"), app);
- let cjs = "function f(x) {\n return x;\n}\nif (require.main === module) main();\n";
- let on = add_marked(cjs, "app.js:f", "f = g;", true);
- assert!(on.find("f = g;").unwrap() < on.find("if (require.main").unwrap(), "{on}");
- assert!(add_marked(app, "m.f", "f = g;", false).trim_end().ends_with("// <<< fast-anything: m.f <<<"));
- }
-
- #[test]
- fn const_functions_switch_to_let_and_back() {
- let port = Port {
- id: "lib.pairs".into(),
- file: "lib.ts".into(),
- module: "lib".into(),
- func: "pairs".into(),
- ext: "fa_lib_pairs".into(),
- crate_dir: ".fast/ports/lib.pairs".into(),
- recorded: 1,
- calls_seen: 1,
- verify: None,
- enabled: false,
- lang: backend::Lang::Node,
- owner: None,
- line: 1,
- sources: vec![],
- };
- for original in [
- "export const pairs = (names: string[]): number => {\n return 0;\n};\n",
- "const pairs = function (names) {\n return 0;\n};\nmodule.exports = { pairs };\n",
- "const pairsCount = 1;\nexport const\tpairs = (n) => n;\r\n",
- ] {
- let on = with_shim(original, &port, "pairs = rust.pairs;");
- assert!(declaration(&on, "let", "pairs").is_some() && declaration(&on, "const", "pairs").is_none(), "{on}");
- assert_eq!(on.contains("const pairsCount"), original.contains("const pairsCount"), "{on}");
- assert_eq!(with_shim(&on, &port, "pairs = rust.pairs;"), on, "enabling twice changes nothing");
- assert_eq!(without_shim(&on, &port), original);
- }
- // a function that was declared with let stays let
- let original = "let pairs = (n) => n;\n";
- let on = with_shim(original, &port, "pairs = rust.pairs;");
- assert!(!on.contains("puts the const back"));
- assert_eq!(without_shim(&on, &port), original);
- }
-
- #[test]
- fn static_methods_go_through_their_class() {
- let port = Port {
- id: "lib.Text.pairs".into(),
- file: "lib.mjs".into(),
- module: "lib".into(),
- func: "pairs".into(),
- ext: "fa_lib_text_pairs".into(),
- crate_dir: ".fast/ports/lib.Text.pairs".into(),
- recorded: 1,
- calls_seen: 1,
- verify: None,
- enabled: false,
- lang: backend::Lang::Node,
- owner: Some("Text".into()),
- line: 2,
- sources: vec![],
- };
- let block = shim(&port, "./x.node", true);
- assert!(block.contains("Text.pairs = process.getBuiltinModule"), "{block}");
- assert!(block.contains("(\"./x.node\").pairs;"), "{block}");
- // a same-named const elsewhere is left alone
- let original = "const pairs = 1;\nexport class Text {\n static pairs(n) {\n return n;\n }\n}\n";
- let on = with_shim(original, &port, &block);
- assert!(on.starts_with("const pairs = 1;"), "{on}");
- assert_eq!(without_shim(&on, &port), original);
- }
-
- #[test]
- fn shim_loads_the_addon() {
- let port = Port {
- id: "fuzzy.levenshtein".into(),
- file: "fuzzy.mjs".into(),
- module: "fuzzy".into(),
- func: "levenshtein".into(),
- ext: "fa_fuzzy_levenshtein".into(),
- crate_dir: ".fast/ports/fuzzy.levenshtein".into(),
- recorded: 1,
- calls_seen: 1,
- verify: None,
- enabled: false,
- lang: backend::Lang::Node,
- owner: None,
- line: 1,
- sources: vec![],
- };
- let esm = shim(&port, "./.fast/lib/fa_fuzzy_levenshtein.node", true);
- assert!(esm.contains("createRequire(import.meta.url)(\"./.fast/lib/fa_fuzzy_levenshtein.node\").levenshtein"));
- assert!(shim(&port, "./x.node", false).contains("levenshtein = require(\"./x.node\").levenshtein;"));
- let original = "export function levenshtein(a, b) {\n return 0;\n}\n";
- let on = backend::append_marked(original, "//", &port.id, &esm);
- assert_eq!(backend::strip_marked(&on, "//", &port.id), original);
- }
-
+ #[test]
+ fn scan_handles_regex_literals_and_division_ambiguity() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let tmp = std::env::temp_dir();
+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
+ let dir = tmp.join(format!("fa-node-regex-lexer-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ // Put regexes with quotes, character-class slashes, and return-regex above a single hot
+ // function so V8 sampling reliably captures it even on fast CI runners.
+ fs::write(
+ dir.join("work.mjs"),
+ "export function stripQuotes(s) {\n\
+ \x20 return s.replace(/['\"]/g, \"\").replace(/[/']/g, \"-\");\n\
+ }\n\n\
+ export function hasQuote(s) {\n\
+ \x20 return /'/.test(s);\n\
+ }\n\n\
+ export function afterRegex(n) {\n\
+ \x20 let t = 0;\n\
+ \x20 for (let i = 0; i < n; i++) t += (i * i) % 97;\n\
+ \x20 return t;\n\
+ }\n",
+ )
+ .unwrap();
+ fs::write(
+ dir.join("app.mjs"),
+ "import { stripQuotes, hasQuote, afterRegex } from './work.mjs';\n\
+ let s = stripQuotes(\"a/b'c\") + hasQuote(\"'\");\n\
+ let total = 0;\n\
+ for (let r = 0; r < 200; r++) total += afterRegex(100000);\n\
+ console.log(s, total);\n",
+ )
+ .unwrap();
+ let scanned = crate::pipeline::scan(&dir, vec!["node".into(), "app.mjs".into()], None);
+ let _ = fs::remove_dir_all(&dir);
+ let scanned = scanned.unwrap();
+ let h = scanned.hotspots.iter().find(|h| h.name == "afterRegex").unwrap_or_else(|| {
+ panic!("missing hotspot afterRegex; got {:?}", scanned.hotspots.iter().map(|h| &h.name).collect::<Vec<_>>())
+ });
+ assert!(h.portable(), "afterRegex should be portable, got blockers {:?}", h.blockers);
+ }
+
+ #[test]
+ fn code_only_handles_regex_and_division_deterministically() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let tmp = std::env::temp_dir();
+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
+ let dir = tmp.join(format!("fa-node-codeonly-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ // Export codeOnly/describe from a temporary copy of runner.mjs to assert exact blanking on tricky tokens
+ // (and verify linear time on adversarial unterminated-slash lines).
+ let stripped = RUNNER.split("const [mode, jobPath]").next().unwrap();
+ fs::write(dir.join("lib.mjs"), format!("{stripped}\nexport {{ codeOnly, describe }};\n")).unwrap();
+ fs::write(
+ dir.join("check.mjs"),
+ r#"import assert from "node:assert/strict";
+ import fs from "node:fs";
+ import path from "node:path";
+ import { fileURLToPath } from "node:url";
+ import { codeOnly, describe } from "./lib.mjs";
+
+ const root = path.dirname(fileURLToPath(import.meta.url));
+
+ // Division preserved intact (two slashes on the same line pin every guard against regex misreads)
+ for (const line of [
+ "const r = a / b / c;",
+ "const r = (a + b) / 2 / arr[0];",
+ "const r = arr[0] / 2 / 3;",
+ "const r = obj.return / 2 / 3;",
+ "const r = i++ / 2 / 3;",
+ "const r = i-- / 2 / 3;",
+ "const r = 10 / 2 / 3;",
+ "const r = 1.5 / 2 / 3;",
+ 'const r = "10" / 2 / 3;',
+ "const r = of / 2 / 3;",
+ "const r = { a: 1 } / 2 / 3;",
+ "return { a: 1 } / 2 / 3;",
+ "const r = { a: () => { return 1; } } / 2 / 3;",
+ "const r = π / 2 / 3;",
+ "const r = 数量 / 2 / 3;",
+ "const r = a! / console.log(1) / 2;",
+ "const r = a!! / 2 / 3;",
+ ]) {
+ assert.equal(codeOnly(line), line.replace('"10"', '" "'), `division misread: ${line}`);
+ }
+ assert.equal(codeOnly("const r = /a/ / 2 / 3;"), "const r = / / / 2 / 3;");
+
+ // Division followed by a quoted line comment (must not pair `/` with `//`)
+ for (const prefix of [
+ "const x = y / 2",
+ "const x = obj.return / 2",
+ "const x = i++ / 2",
+ "const x = of / 2",
+ "const x = { a: 1 } / 2",
+ "const x = π / 2",
+ "const x = m.get('a')! / 2",
+ ]) {
+ const src = `${prefix}; // don't "break"\nconst z = 1;`;
+ const res = codeOnly(src);
+ assert.equal(res.length, src.length, `length drift for ${prefix}`);
+ assert.ok(res.startsWith(`${prefix.replace("'a'", "' '")}; `), `prefix damaged: ${res}`);
+ assert.ok(res.endsWith("\nconst z = 1;"), `next line swallowed for ${prefix}: ${res}`);
+ }
+
+ // Regex literals: start-of-file, quotes, char-class slashes, escapes, flags, keywords, blocks, prefix `!`
+ assert.equal(codeOnly("/'/.test(s);"), "/ /.test(s);");
+ assert.equal(codeOnly("/>/.test(s);"), "/ /.test(s);");
+ assert.equal(codeOnly("a < /'/.source.length;"), "a < / /.source.length;");
+ assert.equal(codeOnly("s.replace(/['\"]/g, \"\")"), "s.replace(/ /g, \"\")");
+ assert.equal(codeOnly("s.replace(/[/]/g, \"-\")"), "s.replace(/ /g, \" \")");
+ assert.equal(codeOnly("return /https?:\\/\\//.test(s);"), "return / /.test(s);");
+ assert.equal(codeOnly("const t = `a / b / 'c'`;\nconst ok = 1;"), "const t = ` `;\nconst ok = 1;");
+
+ for (const [src, expected] of [
+ ["return /'/.test(s);", "return / /.test(s);"],
+ ["case /'/: break;", "case / /: break;"],
+ ["throw /'/;", "throw / /;"],
+ ["typeof /'/", "typeof / /"],
+ ["void /'/", "void / /"],
+ ["delete /'/", "delete / /"],
+ ["new /'/", "new / /"],
+ ["yield /'/", "yield / /"],
+ ["await /'/", "await / /"],
+ ["if (a) b(); else /'/.test(s);", "if (a) b(); else / /.test(s);"],
+ ["do /'/.test(s); while (0);", "do / /.test(s); while (0);"],
+ ["x in /'/", "x in / /"],
+ ["function foo() {} /'/.test(s);", "function foo() {} / /.test(s);"],
+ ["if (ok) { a(); } /'/.test(s);", "if (ok) { a(); } / /.test(s);"],
+ ["const f = () => { return 1; } /'/.test(s);", "const f = () => { return 1; } / /.test(s);"],
+ ["class C {} /'/.test(s);", "class C {} / /.test(s);"],
+ ["class C extends ns.Base {} /'/.test(s);", "class C extends ns.Base {} / /.test(s);"],
+ ["if (!/'/.test(s)) {}", "if (!/ /.test(s)) {}"],
+ ["foo()\n!/'/.test(s);", "foo()\n!/ /.test(s);"],
+ ["foo() /*\n*/ !/'/.test(s);", "foo() \n !/ /.test(s);"],
+ ["a != /'/.source;", "a != / /.source;"],
+ ["a !== /'/.source;", "a !== / /.source;"],
+ ]) {
+ assert.equal(codeOnly(src), expected, `regex misread: ${src}`);
+ }
+
+ // Unterminated `/` on a line never crosses LF, CRLF, or trailing backslash before newline
+ assert.equal(codeOnly("x = /a\nconst b = 1 / 2;"), "x = /a\nconst b = 1 / 2;");
+ assert.equal(codeOnly("x = /a\r\nconst b = 1 / 2;"), "x = /a\r\nconst b = 1 / 2;");
+ assert.equal(codeOnly("x = /a\\\nconst b = /'/;"), "x = /a\\\nconst b = / /;");
+
+ // Escaped quotes inside regex and comments don't leak into later functions
+ const modFile = path.join(root, "sample.mjs");
+ const sample = [
+ "export function f1(s) { return s.replace(/['\"]/g, ''); }",
+ "export function f2(s) { return s.replace(/[/]/g, '-'); }",
+ "export function f3(s) { return /'/.test(s); }",
+ "export function f4(a, b, c) { return a / b / c; }",
+ "export function f5(y) { const x = y / 2; // don't break\n return x; }",
+ "export function f6(s) { const t = `a / b`; return t + s; }",
+ ].join("\n") + "\n";
+ fs.writeFileSync(modFile, sample);
+ for (const [line0, name] of [[0, "f1"], [1, "f2"], [2, "f3"], [3, "f4"], [4, "f5"], [6, "f6"]]) {
+ const info = describe(modFile, line0, name, null, root);
+ assert.ok(info, `describe missed ${name}`);
+ assert.deepEqual(info.blockers, [], `${name} had unexpected blockers: ${info.blockers}`);
+ }
+
+ // JSX closing tags (`</tag>`, `</>`) and self-closing tags (`/>`) must not be misread as regex
+ const jsxFile = path.join(root, "sample.jsx");
+ const jsxSample = [
+ 'export function ViewA() { return <span>Home</span><a href="/about">About</a>; }',
+ "export function afterA(x) { return x + 1; }",
+ "export function ViewB() { return <span>a</span><span>{console.log(1)}</span>; }",
+ "export function ViewC(a) { return <div><span>a</span>{a && <span>b</span>}</div>; }",
+ "export function ViewD() { return <Icon size={16} /><button onClick={() => console.log(1)}>ok</button>; }",
+ "export function ViewFrag() { return <><span>a</span></>; }",
+ "export function afterFrag(x) { return x + 2; }",
+ ].join("\n") + "\n";
+ fs.writeFileSync(jsxFile, jsxSample);
+ for (const [line0, name] of [[1, "afterA"], [3, "ViewC"], [6, "afterFrag"]]) {
+ const info = describe(jsxFile, line0, name, null, root);
+ assert.ok(info, `describe missed JSX ${name}`);
+ assert.deepEqual(info.blockers, [], `JSX ${name} had unexpected blockers: ${info.blockers}`);
+ }
+ for (const [line0, name] of [[2, "ViewB"], [4, "ViewD"]]) {
+ const info = describe(jsxFile, line0, name, null, root);
+ assert.ok(info, `describe missed JSX ${name}`);
+ assert.ok(info.blockers.some((b) => b.includes("console")), `JSX ${name} lost console blocker: ${info.blockers}`);
+ }
+
+ // TypeScript postfix non-null assertion `!` before `/` must not swallow following functions or console I/O
+ const tsxFile = path.join(root, "sample.tsx");
+ const tsxSample = [
+ "export function tsDiv(m) { const x = m.get('a')! / 2; // don't break",
+ " return x; }",
+ "export function afterTs(x) { return x + 1; }",
+ "export function tsConsole(a) { return a! / console.log(1) / 2; }",
+ ].join("\n") + "\n";
+ fs.writeFileSync(tsxFile, tsxSample);
+ const afterTs = describe(tsxFile, 2, "afterTs", null, root);
+ assert.ok(afterTs, "describe missed afterTs");
+ assert.deepEqual(afterTs.blockers, [], `afterTs had unexpected blockers: ${afterTs.blockers}`);
+ const tsConsole = describe(tsxFile, 3, "tsConsole", null, root);
+ assert.ok(tsConsole, "describe missed tsConsole");
+ assert.ok(tsConsole.blockers.some((b) => b.includes("console")), `tsConsole lost console blocker: ${tsConsole.blockers}`);
+
+ // Adversarial inputs with unterminated slashes (odd repeat count prevents even-pairing false passes)
+ for (const worst of [
+ "x = /a\n".repeat(5001) + "const ok = 1;",
+ "x = /[".repeat(10000) + "\nconst ok = 1;",
+ ]) {
+ const res = codeOnly(worst);
+ assert.equal(res, worst);
+ }
+ "#,
+ )
+ .unwrap();
+ let out = Command::new("node").arg("check.mjs").current_dir(&dir).output().unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", combined(&out));
+ }
++
+ #[test]
+ fn bun_and_deno_get_their_own_command_lines() {
+ let args = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
+ assert_eq!(Runtime::of("/usr/local/bin/bun"), Some(Runtime::Bun));
+ assert_eq!(Runtime::of("C:\\deno\\deno.exe"), Some(Runtime::Deno));
+ assert!(is_node("bun") && is_node("deno") && !is_node("python"));
+ assert_eq!(Runtime::Node.with(&["--require", "r.cjs"], &args("app.js x")), args("--require r.cjs app.js x"));
+ assert_eq!(Runtime::Bun.with(&["--preload", "r.cjs"], &args("run app.ts")), args("--preload r.cjs app.ts"));
+ assert_eq!(Runtime::Deno.with(&["--cpu-prof"], &args("run -A app.ts x")), args("run --cpu-prof -A app.ts x"));
+ assert_eq!(Runtime::Deno.with(&["--cpu-prof"], &args("app.ts")), args("run --cpu-prof app.ts"));
+ assert_eq!(Runtime::Deno.script(Path::new("runner.mjs")), args("run -A runner.mjs"));
+ assert_eq!(entry(&args("run -A --allow-ffi app.ts data.txt")).map(String::as_str), Some("app.ts"));
+ assert_eq!(entry(&args("run app.ts")).map(String::as_str), Some("app.ts"));
+ }
+
+ #[test]
+ fn worker_threads_are_recorded() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-node-workers-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("recorder.cjs"), RECORDER).unwrap();
+ fs::write(
+ dir.join("lib.cjs"),
+ "function sq(x) {\n return x * x;\n}\nsq = globalThis.__fastAnythingWrap ? globalThis.__fastAnythingWrap(sq) : sq;\nmodule.exports = { sq };\n",
+ )
+ .unwrap();
+ fs::write(
+ dir.join("app.cjs"),
+ "const { Worker, isMainThread, parentPort } = require(\"node:worker_threads\");\n\
+ const { sq } = require(\"./lib.cjs\");\n\
+ if (isMainThread) {\n\
+ \x20 sq(1);\n\
+ \x20 for (let i = 0; i < 2; i++) new Worker(__filename).on(\"message\", (m) => console.log(m));\n\
+ } else {\n\
+ \x20 let t = 0;\n\
+ \x20 for (let i = 0; i < 5; i++) t += sq(i);\n\
+ \x20 parentPort.postMessage(t);\n\
+ }\n",
+ )
+ .unwrap();
+ let out = Command::new("node")
+ .args(["--require", "./recorder.cjs", "app.cjs"])
+ .current_dir(&dir)
+ .env("FAST_ANYTHING_RECORD_OUT", dir.join("rec.jsonl"))
+ .env("FAST_ANYTHING_RECORD_META", dir.join("rec.meta.json"))
+ .env("FAST_ANYTHING_RECORD_LIMIT", "500")
+ .output()
+ .unwrap();
+ let meta = fs::read_to_string(dir.join("rec.meta.json")).unwrap_or_default();
+ let lines = fs::read_to_string(dir.join("rec.jsonl")).unwrap_or_default().lines().count();
+ let leftovers = fs::read_dir(&dir)
+ .unwrap()
+ .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().contains(".t"))
+ .count();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let meta: Value = serde_json::from_str(&meta).unwrap();
+ assert_eq!((meta["calls"].clone(), lines), (json!(11), 11), "1 call in the main thread, 5 in each worker");
+ assert_eq!(leftovers, 0, "worker files are absorbed and removed");
+ }
+
+ /// Calls reached through an import: `readFileSync` after `import { readFileSync } from "node:fs"`,
+ /// `cp.spawnSync` after `const cp = require("child_process")`. Each case says what scan must block,
+ /// and what it must leave alone (pure members, shadowed names, the app's own modules, comments).
+ const IMPORT_CASES: &[(&str, &str, &str, &[&str])] = &[
+ (
+ "named",
+ "import { readFileSync } from \"node:fs\";\nexport function f(p) {\n return readFileSync(p, \"utf8\").length;\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "alias",
+ "import { execSync as run } from \"child_process\";\nexport function f(x) {\n run(\"true\");\n return x;\n}\n",
+ "f",
+ &["does I/O: child_process.execSync"],
+ ),
+ (
+ "namespace",
+ "import * as files from \"node:fs\";\nexport function f(p) {\n return files.statSync(p).size;\n}\n",
+ "f",
+ &["does I/O: fs.statSync"],
+ ),
+ (
+ "default",
+ "import disk from \"fs\";\nexport function f(p, x) {\n disk.writeFileSync(p, String(x));\n return x;\n}\n",
+ "f",
+ &["does I/O: fs.writeFileSync"],
+ ),
+ (
+ "promises member",
+ "import { promises as fsp } from \"fs\";\nexport function f(p) {\n return fsp.stat(p);\n}\n",
+ "f",
+ &["does I/O: fs.promises"],
+ ),
+ (
+ "fs/promises",
+ "import { readFile } from \"node:fs/promises\";\nexport function f(p) {\n return readFile(p);\n}\n",
+ "f",
+ &["does I/O: fs.readFile"],
+ ),
+ (
+ "multi-line",
+ "import {\n readFileSync,\n statSync,\n} from \"node:fs\";\nexport function f(p) {\n return statSync(p).size;\n}\n",
+ "f",
+ &["does I/O: fs.statSync"],
+ ),
+ (
+ "random",
+ "import { randomInt } from \"node:crypto\";\nexport function f(x) {\n return x + randomInt(10);\n}\n",
+ "f",
+ &["not deterministic: crypto.randomInt"],
+ ),
+ (
+ "perf alias",
+ "import { performance as perf } from \"node:perf_hooks\";\nexport function f(x) {\n return x + perf.now();\n}\n",
+ "f",
+ &["not deterministic: perf_hooks.performance"],
+ ),
+ (
+ "process member",
+ "import { env } from \"node:process\";\nexport function f(x) {\n return env.HOME ?? x;\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "require destructure",
+ "const { readFileSync: rd } = require(\"fs\");\nfunction f(p) {\n return rd(p).length;\n}\nmodule.exports = { f };\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "require module",
+ "const cp = require(\"node:child_process\");\nfunction f(x) {\n cp.spawnSync(\"true\");\n return x;\n}\nmodule.exports = { f };\n",
+ "f",
+ &["does I/O: child_process.spawnSync"],
+ ),
+ (
+ "require member",
+ "const fsp = require(\"fs\").promises;\nfunction f(p) {\n return fsp.readFile(p);\n}\nmodule.exports = { f };\n",
+ "f",
+ &["does I/O: fs.promises"],
+ ),
+ (
+ "fs as fs, once",
+ "import fs from \"node:fs\";\nexport function f(p) {\n return fs.readFileSync(p).length;\n}\n",
+ "f",
+ &["does I/O: fs"],
+ ),
+ (
+ "hash pure",
+ "import { createHash } from \"node:crypto\";\nexport function f(s) {\n return createHash(\"sha1\").update(s).digest(\"hex\");\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "path pure",
+ "import { join } from \"node:path\";\nexport function f(a, b) {\n return join(a, b);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "fs.constants pure",
+ "import { constants } from \"node:fs\";\nexport function f(x) {\n return constants.F_OK + x;\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "net.isIP pure",
+ "import * as net from \"node:net\";\nexport function f(s) {\n return net.isIP(s) === 4;\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "param shadow",
+ "import { env } from \"node:process\";\nexport function f(env) {\n return env.k;\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "local shadow",
+ "import { readFileSync } from \"fs\";\nexport function f(x) {\n const readFileSync = (v) => v + 1;\n return readFileSync(x);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "arrow param shadow",
+ "import * as os from \"node:os\";\nexport function f(items) {\n return items.map((os) => os.name);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "object key",
+ "import { env } from \"node:process\";\nexport function f(x) {\n return { env: x };\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "commented import",
+ "/*\nimport { statSync } from \"fs\";\n*/\nfunction statSync(x) {\n return { size: x };\n}\nexport function f(x) {\n return statSync(x).size;\n}\n",
+ "f",
+ &[],
+ ),
+ ("own module", "import { load } from \"./io.mjs\";\nexport function f(x) {\n return load(x);\n}\n", "f", &[]),
+ (
+ "other function",
+ "import { readFileSync } from \"fs\";\nexport function load(p) {\n return readFileSync(p);\n}\nexport function f(x) {\n return x * 2;\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "type import",
+ "import type { Stats } from \"node:fs\";\nexport function f(s: Stats): number {\n return s.size;\n}\n",
+ "f",
+ &[],
+ ),
+ // a name taken over in one place still counts everywhere else
+ (
+ "arrow shadow, used outside it",
+ "import * as os from \"node:os\";\nexport function f(items) {\n const host = os.hostname();\n return items.map((os) => os.name).concat(host);\n}\n",
+ "f",
+ &["does I/O: os.hostname"],
+ ),
+ (
+ "used in a default",
+ "import { readFileSync } from \"node:fs\";\nexport function f(p, fallback = readFileSync(\"/x\", \"utf8\")) {\n return readFileSync(p, \"utf8\") || fallback;\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "used in an arrow's default",
+ "import { env } from \"node:process\";\nexport function f(xs) {\n return xs.map((x = env.DEFAULT) => x);\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "destructured key",
+ "import { env } from \"node:process\";\nexport function f(cfg) {\n const { env: mode } = cfg;\n return mode + env.HOME;\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "computed key",
+ "import { env } from \"node:process\";\nexport function f(cfg) {\n const { [env.KEY]: val } = cfg;\n return val;\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "parameter pattern key",
+ "import { env } from \"node:process\";\nexport function f({ env: mode }) {\n return mode + env.HOME;\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "for-of pattern",
+ "import { env } from \"node:process\";\nexport function f(items, t) {\n for (const { a } of items) t[env.HOME] = a;\n return t;\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ // import forms
+ (
+ "comment in an import",
+ "import {\n // sync read\n readFileSync,\n} from \"node:fs\";\nexport function f(p) {\n return readFileSync(p, \"utf8\").length;\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "require, comment inside",
+ "const {\n readFileSync, // reads\n statSync,\n} = require(\"node:fs\");\nfunction f(p) {\n return statSync(p).size;\n}\nmodule.exports = { f };\n",
+ "f",
+ &["does I/O: fs.statSync"],
+ ),
+ (
+ "require, defaults",
+ "const { fn = () => 1, readFileSync } = require(\"node:fs\");\nfunction f(p) {\n return readFileSync(p).length;\n}\nmodule.exports = { f };\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "require, nested",
+ "const { promises: { readFile } } = require(\"node:fs\");\nfunction f(p) {\n return readFile(p);\n}\nmodule.exports = { f };\n",
+ "f",
+ &["does I/O: fs.promises"],
+ ),
+ (
+ "require, .default",
+ "const { randomBytes } = require(\"node:crypto\").default;\nfunction f() {\n return randomBytes(16).toString(\"hex\");\n}\nmodule.exports = { f };\n",
+ "f",
+ &["not deterministic: crypto.randomBytes"],
+ ),
+ (
+ "require, .default pure",
+ "const { isIP } = require(\"node:net\").default;\nfunction f(s) {\n return isIP(s);\n}\nmodule.exports = { f };\n",
+ "f",
+ &[],
+ ),
+ (
+ "require in a function keeps the top one",
+ "const { readFileSync: run } = require(\"node:fs\");\nfunction helper() {\n const run = require(\"node:path\").join;\n return run(\"a\", \"b\");\n}\nfunction f(p) {\n return run(p, \"utf8\").length;\n}\nmodule.exports = { helper, f };\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "require in a function stays there",
+ "const env = { scale: 2 };\nfunction readHome() {\n const { env } = require(\"node:process\");\n return env.HOME;\n}\nfunction f(x) {\n return x * env.scale;\n}\nmodule.exports = { readHome, f };\n",
+ "f",
+ &[],
+ ),
+ (
+ "compact import",
+ "import{readFileSync}from\"node:fs\";\nexport function f(p) {\n return readFileSync(p).length;\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "type: import = require",
+ "import cp = require(\"node:child_process\");\nexport function f(x: number): number {\n cp.spawnSync(\"true\");\n return x;\n}\n",
+ "f",
+ &["does I/O: child_process.spawnSync"],
+ ),
+ (
+ "top-level alias",
+ "import fs from \"node:fs\";\nconst { readFileSync } = fs;\nexport function f(p) {\n return readFileSync(p).length;\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "member named type",
+ "import { type as osType } from \"node:os\";\nexport function f() {\n return osType();\n}\n",
+ "f",
+ &["does I/O: os.type"],
+ ),
+ // modules and members
+ (
+ "console",
+ "import { log } from \"node:console\";\nexport function f(x) {\n log(x);\n return x * 2;\n}\n",
+ "f",
+ &["does I/O: console.log"],
+ ),
+ (
+ "pseudoRandomBytes",
+ "import { pseudoRandomBytes } from \"node:crypto\";\nexport function f() {\n return pseudoRandomBytes(16).toString(\"hex\");\n}\n",
+ "f",
+ &["not deterministic: crypto.pseudoRandomBytes"],
+ ),
+ (
+ "crypto destructured",
+ "import * as c from \"node:crypto\";\nexport function f() {\n const { randomUUID } = c;\n return randomUUID();\n}\n",
+ "f",
+ &["not deterministic: crypto"],
+ ),
+ // names that aren't the import
+ (
+ "method shorthand",
+ "import { env } from \"node:process\";\nexport function f(x) {\n return { env(v) { return v + 1; } }.env(x);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "function expression param",
+ "import * as os from \"node:os\";\nexport function f(items) {\n return items.map(function (os) {\n return os.name;\n });\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "nested function param",
+ "import { env } from \"node:process\";\nexport function f() {\n function getK(env) {\n return env.k;\n }\n return getK({ k: 1 });\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "second declarator",
+ "import { readFileSync } from \"node:fs\";\nexport function f(x) {\n const a = 1, readFileSync = (v) => v + 1;\n return readFileSync(x) + a;\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "type: optional key",
+ "import { env } from \"node:process\";\nexport function f(x: string): string {\n const cfg: { env?: string } = { env: x };\n return cfg.env;\n}\n",
+ "f",
+ &[],
+ ),
+ // scopes that end where JavaScript ends them
+ (
+ "for-of loop variable",
+ "import { env } from \"node:process\";\nexport function f(items) {\n for (const env of items) {\n if (env.stop) break;\n }\n return env.HOME;\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "var in a nested function",
+ "import { env } from \"node:process\";\nexport function f() {\n function helper() {\n var env = { HOME: \"x\" };\n return env.HOME;\n }\n return env.HOME + helper();\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "var in an arrow",
+ "import { env } from \"node:process\";\nexport function f(items) {\n const xs = items.map((x) => { var env = x; return env; });\n return env.HOME + xs;\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "named function expression",
+ "import { readFileSync } from \"node:fs\";\nexport function f(p) {\n const g = function readFileSync(x) { return x; };\n return readFileSync(p).length + g(1);\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "arrow without semicolons",
+ "import * as os from \"node:os\";\nexport function f() {\n const getName = (os) => os.name\n return os.hostname() + getName({ name: 1 })\n}\n",
+ "f",
+ &["does I/O: os.hostname"],
+ ),
+ (
+ "arrow in a ternary",
+ "import * as os from \"node:os\";\nexport function f(x) {\n return x ? (os) => os.name : os.hostname();\n}\n",
+ "f",
+ &["does I/O: os.hostname"],
+ ),
+ (
+ "arrow with a ternary body",
+ "import * as os from \"node:os\";\nexport function f(items, c) {\n return items.map((os) => (c ? os.a : os.b));\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "call in a ternary",
+ "import { readFileSync } from \"node:fs\";\nexport function f(cond, p) {\n return cond ? JSON.parse(readFileSync(p, \"utf8\")) : { empty: true };\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "type: function type annotation",
+ "import { env } from \"node:process\";\nexport function f(): number {\n const fn: (env: string) => number = () => env.HOME.length;\n return fn(\"a\");\n}\n",
+ "f",
+ &["does I/O: process.env"],
+ ),
+ (
+ "type: arrow return type",
+ "import * as os from \"node:os\";\nexport function f(items: Array<{ name: string }>): string[] {\n return items.map((os): string => os.name);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "type: generic nested function",
+ "import { env } from \"node:process\";\nexport function f(): number {\n function id<T>(env: T): T {\n return env;\n }\n return id(1);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "type: key after a semicolon",
+ "import { env } from \"node:process\";\nexport function f(x: string): string {\n const cfg: { a: number; env?: string } = { a: 1, env: x };\n return cfg.env ?? \"\";\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "type: import type{",
+ "import type{ Stats } from \"node:fs\";\nexport function f(x: unknown): boolean {\n const s = x as Stats;\n return s.size > 0;\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "comparison before a binding",
+ "import { env } from \"node:process\";\nexport function f(x) {\n const ok = x < 10, env = { k: x };\n return env.k + ok;\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "declaration over two lines",
+ "import { readFileSync } from \"node:fs\";\nexport function f(x) {\n const a = x +\n 1, readFileSync = (v) => v;\n return readFileSync(a);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "property on the next line",
+ "import { exec } from \"node:child_process\";\nexport function f(re, s) {\n return re\n .exec(s);\n}\n",
+ "f",
+ &[],
+ ),
+ (
+ "import in a template string",
+ "const doc = `\nimport { readFileSync } from \"fs\";\n`;\nfunction readFileSync(x) {\n return x;\n}\nexport function f(x) {\n return readFileSync(x) + doc;\n}\n",
+ "f",
+ &[],
+ ),
+ // more import forms
+ (
+ "require, no semicolons",
+ "const { a } = getConfig()\nconst { readFileSync } = require(\"node:fs\")\nfunction f(p) {\n return readFileSync(p, \"utf8\").length\n}\nfunction getConfig() {\n return { a: 1 }\n}\nmodule.exports = { f, a }\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "require, rest",
+ "const { createHash, ...rest } = require(\"node:crypto\");\nfunction f() {\n return rest.randomInt(10);\n}\nmodule.exports = { f, createHash };\n",
+ "f",
+ &["not deterministic: crypto.randomInt"],
+ ),
+ (
+ "require, after a regex with a brace",
+ "const OPEN = /\\{/;\nconst { readFileSync } = require(\"node:fs\");\nfunction f(p) {\n return readFileSync(p, \"utf8\").length + OPEN.source.length;\n}\nmodule.exports = { f };\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "require, .default.member pure",
+ "const isIP = require(\"node:net\").default.isIP;\nfunction f(s) {\n return isIP(s) === 4;\n}\nmodule.exports = { f };\n",
+ "f",
+ &[],
+ ),
+ (
+ "chained alias",
+ "import fs from \"node:fs\";\nconst read = fs.promises.readFile;\nexport function f(p) {\n return read(p);\n}\n",
+ "f",
+ &["does I/O: fs.promises"],
+ ),
+ (
+ "exported alias",
+ "import fs from \"node:fs\";\nexport const { readFileSync } = fs;\nexport function f(p) {\n return readFileSync(p).length;\n}\n",
+ "f",
+ &["does I/O: fs.readFileSync"],
+ ),
+ (
+ "type: as const without semicolons",
+ "import { writeFileSync } from \"node:fs\";\nexport function f(p: string) {\n const opts = { encoding: \"utf8\" } as const\n writeFileSync(p, \"hi\", opts)\n return 1\n}\n",
+ "f",
+ &["does I/O: fs.writeFileSync"],
+ ),
+ (
+ "type: a function type's parameter",
+ "import { env } from \"node:process\";\nexport function f(): number {\n const fn: (env: string) => number = (s) => s.length;\n return fn(\"a\");\n}\n",
+ "f",
+ &[],
+ ),
+ ];
+
+ #[test]
+ fn scan_sees_io_reached_through_an_import() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ // the profile step describes the 40 hottest functions: 30 cases a run
+ for (chunk, cases) in IMPORT_CASES.chunks(30).enumerate() {
+ let dir = std::env::temp_dir().join(format!("fa-node-imports-{}-{chunk}", std::process::id()));
+ let prof = dir.join("cpuprof");
+ fs::create_dir_all(&prof).unwrap();
+ // a made-up profile with one sample in each case's function
+ let root = json!({ "functionName": "(root)", "url": "", "lineNumber": -1, "columnNumber": -1 });
+ let mut nodes = vec![json!({ "id": 1, "callFrame": root, "children": [] })];
+ for (i, (name, src, func, _)) in cases.iter().enumerate() {
+ let ext = if name.starts_with("require") {
+ "cjs"
+ } else if name.starts_with("type") {
+ "ts"
+ } else {
+ "mjs"
+ };
+ let file = dir.join(format!("case{i}.{ext}"));
+ fs::write(&file, src).unwrap();
+ let line = src.lines().position(|l| l.contains(&format!("function {func}("))).unwrap();
+ let url = format!("file://{}", file.display());
+ let frame = json!({ "functionName": func, "url": url, "lineNumber": line, "columnNumber": 0 });
+ nodes.push(json!({ "id": i + 2, "callFrame": frame, "children": [] }));
+ }
+ let ids: Vec<usize> = (2..cases.len() + 2).collect();
+ nodes[0]["children"] = json!(ids);
+ let deltas = vec![1000; ids.len()];
+ let profile =
+ json!({ "nodes": nodes, "startTime": 0, "endTime": 1_000_000, "samples": ids, "timeDeltas": deltas });
+ fs::write(prof.join("a.cpuprofile"), profile.to_string()).unwrap();
+ fs::write(dir.join("runner.mjs"), RUNNER).unwrap();
+ let result = dir.join("profile.json");
+ let job = json!({ "root": dir, "dir": prof, "entry": dir.join("main.mjs"), "out": result });
+ fs::write(dir.join("job.json"), job.to_string()).unwrap();
+ let out =
+ Command::new("node").args(["runner.mjs", "profile", "job.json"]).current_dir(&dir).output().unwrap();
+ let result = fs::read_to_string(&result).unwrap_or_default();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let result: Value = serde_json::from_str(&result).unwrap();
+ let functions = result["functions"].as_array().unwrap();
+ for (i, (name, _, _, expected)) in cases.iter().enumerate() {
+ let prefix = format!("case{i}.");
+ let f = functions
+ .iter()
+ .find(|f| f["file"].as_str().is_some_and(|p| p.starts_with(&prefix)))
+ .unwrap_or_else(|| panic!("{name}: not described"));
+ let got: Vec<&str> = f["blockers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(Value::as_str)
+ .filter(|b| b.starts_with("does I/O") || b.starts_with("not deterministic"))
+ .collect();
+ assert_eq!(got, *expected, "{name}");
+ }
+ }
+ }
+
+ #[test]
+ fn maps_typescript() {
+ assert_eq!(rust_type("number").as_deref(), Some("f64"));
+ assert_eq!(rust_type("string[]").as_deref(), Some("Vec<String>"));
+ assert_eq!(rust_type("Array<number>").as_deref(), Some("Vec<f64>"));
+ assert_eq!(rust_type("readonly number[]").as_deref(), Some("Vec<f64>"));
+ assert_eq!(rust_type("number | undefined").as_deref(), Some("Option<f64>"));
+ assert_eq!(rust_type("string | null").as_deref(), Some("Option<String>"));
+ assert_eq!(rust_type("Float64Array").as_deref(), Some("Float64Array"));
+ assert_eq!(rust_type("Uint8ClampedArray").as_deref(), Some("Uint8ClampedArray"));
+ assert_eq!(rust_type("BigInt64Array"), None);
+ assert_eq!(rust_type("Buffer").as_deref(), Some("Buffer"));
+ assert_eq!(rust_type("Set<string>").as_deref(), Some("std::collections::HashSet<String>"));
+ assert_eq!(rust_type("Set<number>"), None);
+ assert_eq!(rust_type("Map<string, number>"), None);
+ assert_eq!(rust_type("Record<string, number>").as_deref(), Some("std::collections::HashMap<String, f64>"));
+ assert_eq!(rust_type("string | number"), None);
+ assert_eq!(rust_type("[number, number][]").as_deref(), Some("Vec<Vec<f64>>"));
+ assert_eq!(rust_type("[number, string]"), None);
+ assert_eq!(rust_type("Point"), None);
+ }
+
+ #[test]
+ fn finds_the_script() {
+ let args: Vec<String> =
+ ["--require", "x.cjs", "--no-warnings", "app.mjs", "data.txt"].map(String::from).to_vec();
+ assert_eq!(entry(&args).map(String::as_str), Some("app.mjs"));
+ assert!(is_node("node") && is_node("/usr/bin/node") && is_node("C:\\nodejs\\node.exe") && !is_node("python"));
+ assert_eq!(snake("editDistance"), "edit_distance");
+ assert_eq!(snake("type"), "r#type");
+ }
+
+ #[test]
+ fn entry_script_blocks_go_before_the_main_block() {
+ let app = "function f(x) {\n return x;\n}\n\nif (import.meta.main) {\n console.log(f(1));\n}\n";
+ let on = add_marked(app, "app.mjs:f", "f = g;", true);
+ let (block, main) = (on.find("f = g;").unwrap(), on.find("if (import.meta.main)").unwrap());
+ assert!(block < main, "{on}");
+ assert_eq!(backend::strip_marked(&on, "//", "app.mjs:f"), app);
+ let cjs = "function f(x) {\n return x;\n}\nif (require.main === module) main();\n";
+ let on = add_marked(cjs, "app.js:f", "f = g;", true);
+ assert!(on.find("f = g;").unwrap() < on.find("if (require.main").unwrap(), "{on}");
+ assert!(add_marked(app, "m.f", "f = g;", false).trim_end().ends_with("// <<< fast-anything: m.f <<<"));
+ }
+
+ #[test]
+ fn const_functions_switch_to_let_and_back() {
+ let port = Port {
+ id: "lib.pairs".into(),
+ file: "lib.ts".into(),
+ module: "lib".into(),
+ func: "pairs".into(),
+ ext: "fa_lib_pairs".into(),
+ crate_dir: ".fast/ports/lib.pairs".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: None,
+ line: 1,
+ sources: vec![],
+ };
+ for original in [
+ "export const pairs = (names: string[]): number => {\n return 0;\n};\n",
+ "const pairs = function (names) {\n return 0;\n};\nmodule.exports = { pairs };\n",
+ "const pairsCount = 1;\nexport const\tpairs = (n) => n;\r\n",
+ ] {
+ let on = with_shim(original, &port, "pairs = rust.pairs;");
+ assert!(declaration(&on, "let", "pairs").is_some() && declaration(&on, "const", "pairs").is_none(), "{on}");
+ assert_eq!(on.contains("const pairsCount"), original.contains("const pairsCount"), "{on}");
+ assert_eq!(with_shim(&on, &port, "pairs = rust.pairs;"), on, "enabling twice changes nothing");
+ assert_eq!(without_shim(&on, &port), original);
+ }
+ // a function that was declared with let stays let
+ let original = "let pairs = (n) => n;\n";
+ let on = with_shim(original, &port, "pairs = rust.pairs;");
+ assert!(!on.contains("puts the const back"));
+ assert_eq!(without_shim(&on, &port), original);
+ }
+
+ #[test]
+ fn static_methods_go_through_their_class() {
+ let port = Port {
+ id: "lib.Text.pairs".into(),
+ file: "lib.mjs".into(),
+ module: "lib".into(),
+ func: "pairs".into(),
+ ext: "fa_lib_text_pairs".into(),
+ crate_dir: ".fast/ports/lib.Text.pairs".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: Some("Text".into()),
+ line: 2,
+ sources: vec![],
+ };
+ let block = shim(&port, "./x.node", true);
+ assert!(block.contains("Text.pairs = process.getBuiltinModule"), "{block}");
+ assert!(block.contains("(\"./x.node\").pairs;"), "{block}");
+ // a same-named const elsewhere is left alone
+ let original = "const pairs = 1;\nexport class Text {\n static pairs(n) {\n return n;\n }\n}\n";
+ let on = with_shim(original, &port, &block);
+ assert!(on.starts_with("const pairs = 1;"), "{on}");
+ assert_eq!(without_shim(&on, &port), original);
+ }
+
+ #[test]
+ fn shim_loads_the_addon() {
+ let port = Port {
+ id: "fuzzy.levenshtein".into(),
+ file: "fuzzy.mjs".into(),
+ module: "fuzzy".into(),
+ func: "levenshtein".into(),
+ ext: "fa_fuzzy_levenshtein".into(),
+ crate_dir: ".fast/ports/fuzzy.levenshtein".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: None,
+ line: 1,
+ sources: vec![],
+ };
+ let esm = shim(&port, "./.fast/lib/fa_fuzzy_levenshtein.node", true);
+ assert!(esm.contains("createRequire(import.meta.url)(\"./.fast/lib/fa_fuzzy_levenshtein.node\").levenshtein"));
+ assert!(!esm.contains("module.exports"), "ESM shim must stay untouched: {esm}");
+ assert!(shim(&port, "./x.node", false).contains("levenshtein = require(\"./x.node\").levenshtein;"));
+ let original = "export function levenshtein(a, b) {\n return 0;\n}\n";
+ let on = backend::append_marked(original, "//", &port.id, &esm);
+ assert_eq!(backend::strip_marked(&on, "//", &port.id), original);
+ }
+
+ #[test]
+ fn cjs_exports_are_recorded() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let cases = [
+ (
+ "object",
+ "function sq(x) {\n return x * x;\n}\nmodule.exports = { sq };\n",
+ "const { sq } = require(\"./lib.js\");\nconsole.log(sq(2) + sq(3) + sq(4));\n",
+ 3u64,
+ ),
+ (
+ "default",
+ "function sq(x) {\n return x * x;\n}\nmodule.exports = sq;\n",
+ "const sq = require(\"./lib.js\");\nconsole.log(sq(2) + sq(3));\n",
+ 2u64,
+ ),
+ (
+ "named",
+ "function sq(x) {\n return x * x;\n}\nexports.sq = sq;\n",
+ "const { sq } = require(\"./lib.js\");\nconsole.log(sq(5));\n",
+ 1u64,
+ ),
+ (
+ "alias-and-const",
+ "const sq = (x) => x * x;\nconst other = (x) => x + 1;\nmodule.exports = { sq, square: sq, other };\n",
+ "const { sq, square, other } = require(\"./lib.js\");\nif (other(3) !== 4) process.exit(2);\nconsole.log(sq(2) + square(3));\n",
+ 2u64,
+ ),
+ (
+ "default-with-props",
+ "function sq(x) {\n return x * x;\n}\nsq.helper = (x) => x + 1;\nsq.VERSION = \"1.0\";\nsq.default = sq;\nmodule.exports = sq;\n",
+ "const sq = require(\"./lib.js\");\nif (sq.helper(3) !== 4 || sq.VERSION !== \"1.0\") process.exit(2);\nconsole.log(sq(2) + sq.default(3));\n",
+ 2u64,
+ ),
+ (
+ "function-container",
+ "function sq(x) {\n return x * x;\n}\nfunction container() { return 0; }\ncontainer.sq = sq;\nmodule.exports = container;\n",
+ "const c = require(\"./lib.js\");\nconsole.log(c.sq(2) + c.sq(3));\n",
+ 2u64,
+ ),
+ (
+ "getter-and-readonly",
+ "\"use strict\";\nfunction sq(x) {\n return x * x;\n}\nconst ex = {};\nObject.defineProperty(ex, \"ro\", { value: sq, enumerable: true, writable: false });\nObject.defineProperty(ex, \"boom\", { enumerable: true, get() { throw new Error(\"getter ran\"); } });\nObject.defineProperty(ex, \"live\", { enumerable: true, get: () => sq });\nex.sq = sq;\nmodule.exports = ex;\n",
+ "const { sq, live } = require(\"./lib.js\");\nconsole.log(sq(4) + live(5));\n",
+ 2u64,
+ ),
+ (
+ "readonly-module-exports",
+ "\"use strict\";\nfunction sq(x) {\n return x * x;\n}\nObject.defineProperty(module, \"exports\", { value: sq, writable: false, configurable: false });\n",
+ "const sq = require(\"./lib.js\");\nconsole.log(sq(3));\n",
+ 0u64,
+ ),
+ (
+ "null-exports",
+ "function sq(x) {\n return x * x;\n}\nsq(2);\nmodule.exports = null;\n",
+ "require(\"./lib.js\");\n",
+ 0u64,
+ ),
+ (
+ "auto-esm-module-null",
+ "const module = null;\nexport function sq(x) {\n return x * x;\n}\n",
+ "import { sq } from \"./lib.js\";\nconsole.log(sq(3));\n",
+ 1u64,
+ ),
+ ];
+ let base = std::env::temp_dir().join(format!("fa-node-cjs-rec-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&base);
+ for (name, lib_src, app_src, expected_calls) in cases {
+ let dir = base.join(name);
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("lib.js"), lib_src).unwrap();
+ fs::write(dir.join("app.js"), app_src).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let hs = Hotspot {
+ id: "lib.sq".into(),
+ file: "lib.js".into(),
+ name: "sq".into(),
+ qualname: "sq".into(),
+ module: Some("lib".into()),
+ ..Default::default()
+ };
+ let out = dir.join("rec.jsonl");
+ let rec = record(&ctx, "node", &[String::from("app.js")], &hs, &out, 500);
+ let restored = fs::read_to_string(dir.join("lib.js")).unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ let rec = rec.unwrap_or_else(|e| panic!("{name}: record failed: {e:#}"));
+ assert_eq!(rec.calls, expected_calls, "{name}: wrong call count");
+ assert_eq!(rec.kept, expected_calls as usize, "{name}: wrong kept count");
+ assert_eq!(restored, lib_src, "{name}: lib.js must be restored byte for byte after record");
+ }
+ let _ = fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn cjs_exports_are_enabled_and_restored() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let cases = [
+ (
+ "object",
+ "function sq(x) {\n return x * x;\n}\nmodule.exports = { sq };\n",
+ "const { sq } = require(\"./lib.js\");\nconsole.log(sq(3));\n",
+ "1009",
+ "9",
+ ),
+ (
+ "default",
+ "function sq(x) {\n return x * x;\n}\nmodule.exports = sq;\n",
+ "const sq = require(\"./lib.js\");\nconsole.log(sq(3));\n",
+ "1009",
+ "9",
+ ),
+ (
+ "named",
+ "function sq(x) {\n return x * x;\n}\nexports.sq = sq;\n",
+ "const { sq } = require(\"./lib.js\");\nconsole.log(sq(3));\n",
+ "1009",
+ "9",
+ ),
+ (
+ "alias-crlf-const",
+ "const sq = (x) => x * x;\r\nconst other = (x) => x + 1;\r\nmodule.exports = { sq, square: sq, other };\r\n",
+ "const { sq, square, other } = require(\"./lib.js\");\nconsole.log(`${sq(3)},${square(4)},${other(3)}`);\n",
+ "1009,1016,4",
+ "9,16,4",
+ ),
+ (
+ "default-with-props",
+ "function sq(x) {\n return x * x;\n}\nsq.helper = (x) => x + 1;\nsq.VERSION = \"1.0\";\nsq.default = sq;\nmodule.exports = sq;\n",
+ "const sq = require(\"./lib.js\");\nconsole.log(`${sq(3)},${sq.default(4)},${sq.helper(3)},${sq.VERSION}`);\n",
+ "1009,1016,4,1.0",
+ "9,16,4,1.0",
+ ),
+ (
+ "function-container",
+ "function sq(x) {\n return x * x;\n}\nfunction container() { return 0; }\ncontainer.sq = sq;\nmodule.exports = container;\n",
+ "const c = require(\"./lib.js\");\nconsole.log(c.sq(3));\n",
+ "1009",
+ "9",
+ ),
+ (
+ "getter-and-readonly",
+ "\"use strict\";\nfunction sq(x) {\n return x * x;\n}\nconst ex = {};\nObject.defineProperty(ex, \"ro\", { value: sq, enumerable: true, writable: false });\nObject.defineProperty(ex, \"boom\", { enumerable: true, get() { throw new Error(\"getter ran\"); } });\nObject.defineProperty(ex, \"live\", { enumerable: true, get: () => sq });\nex.sq = sq;\nmodule.exports = ex;\n",
+ "const { sq, live } = require(\"./lib.js\");\nconsole.log(`${sq(3)},${live(4)}`);\n",
+ "1009,1016",
+ "9,16",
+ ),
+ (
+ "auto-esm-module-null",
+ "const module = null;\nexport function sq(x) {\n return x * x;\n}\n",
+ "import { sq } from \"./lib.js\";\nconsole.log(sq(3));\n",
+ "9",
+ "9",
+ ),
+ ];
+ let base = std::env::temp_dir().join(format!("fa-node-cjs-en-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&base);
+ for (name, lib_src, app_src, want_rust, want_orig) in cases {
+ let dir = base.join(name);
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("fake_addon.cjs"), "module.exports = { sq: (x) => x * x + 1000 };\n").unwrap();
+ fs::write(dir.join("app.js"), app_src).unwrap();
+ let port = Port {
+ id: "lib.sq".into(),
+ file: "lib.js".into(),
+ module: "lib".into(),
+ func: "sq".into(),
+ ext: "fa_lib_sq".into(),
+ crate_dir: ".fast/ports/lib.sq".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: None,
+ line: 1,
+ sources: vec![],
+ };
+ let enabled = with_shim(lib_src, &port, &shim(&port, "./fake_addon.cjs", false));
+ fs::write(dir.join("lib.js"), &enabled).unwrap();
+ let rust_run =
+ Command::new("node").arg("app.js").current_dir(&dir).env_remove(DISABLE_ENV).output().unwrap();
+ let orig_run = Command::new("node").arg("app.js").current_dir(&dir).env(DISABLE_ENV, "1").output().unwrap();
+ let restored = without_shim(&enabled, &port);
+
+ // Also verify real enable()/disable() round-trip on disk.
+ fs::write(dir.join("lib.js"), lib_src).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ enable(&ctx, &port).unwrap();
+ let on_disk = fs::read_to_string(dir.join("lib.js")).unwrap();
+ disable(&ctx, &port).unwrap();
+ let back_on_disk = fs::read_to_string(dir.join("lib.js")).unwrap();
+ let _ = fs::remove_dir_all(&dir);
+
+ assert!(rust_run.status.success(), "{name}: enabled run failed: {}", combined(&rust_run));
+ assert_eq!(String::from_utf8_lossy(&rust_run.stdout).trim(), want_rust, "{name}: enabled output");
+ assert!(orig_run.status.success(), "{name}: disabled run failed: {}", combined(&orig_run));
+ assert_eq!(String::from_utf8_lossy(&orig_run.stdout).trim(), want_orig, "{name}: disabled output");
+ assert_eq!(restored, lib_src, "{name}: without_shim must restore byte for byte");
+ assert!(on_disk.contains("module.exports"), "{name}: CJS enable should include exports sync");
+ assert_eq!(back_on_disk, lib_src, "{name}: disable must restore byte for byte");
+ }
+
+ // ESM files keep the original ESM path unchanged and restore byte for byte.
+ let esm_dir = base.join("esm");
+ fs::create_dir_all(&esm_dir).unwrap();
+ let esm_src = "export function sq(x) {\n return x * x;\n}\n";
+ fs::write(esm_dir.join("lib.mjs"), esm_src).unwrap();
+ let ctx = Ctx::open(&esm_dir).unwrap();
+ let esm_port = Port {
+ id: "lib.sq".into(),
+ file: "lib.mjs".into(),
+ module: "lib".into(),
+ func: "sq".into(),
+ ext: "fa_lib_sq".into(),
+ crate_dir: ".fast/ports/lib.sq".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: None,
+ line: 1,
+ sources: vec![],
+ };
+ enable(&ctx, &esm_port).unwrap();
+ let esm_on = fs::read_to_string(esm_dir.join("lib.mjs")).unwrap();
+ disable(&ctx, &esm_port).unwrap();
+ let esm_off = fs::read_to_string(esm_dir.join("lib.mjs")).unwrap();
+ assert!(!esm_on.contains("module.exports"), "ESM enable must not add CJS sync: {esm_on}");
+ assert_eq!(esm_off, esm_src, "ESM disable must restore byte for byte");
+
+ // Verify two const functions in the same CJS file don't collide on _faOrig and restore byte for byte.
+ let two_dir = base.join("two");
+ fs::create_dir_all(&two_dir).unwrap();
+ let two_src = "const a = (x) => x + 1;\nconst b = (x) => x + 2;\nmodule.exports = { a, b };\n";
+ fs::write(two_dir.join("fake_addon.cjs"), "module.exports = { a: (x) => x + 100, b: (x) => x + 200 };\n")
+ .unwrap();
+ fs::write(two_dir.join("app.js"), "const { a, b } = require(\"./lib.js\");\nconsole.log(`${a(1)},${b(1)}`);\n")
+ .unwrap();
+ let mk_port = |func: &str| Port {
+ id: format!("lib.{func}"),
+ file: "lib.js".into(),
+ module: "lib".into(),
+ func: func.into(),
+ ext: format!("fa_lib_{func}"),
+ crate_dir: format!(".fast/ports/lib.{func}"),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: None,
+ line: 1,
+ sources: vec![],
+ };
+ let (pa, pb) = (mk_port("a"), mk_port("b"));
+ let on_a = with_shim(two_src, &pa, &shim(&pa, "./fake_addon.cjs", false));
+ let on_ab = with_shim(&on_a, &pb, &shim(&pb, "./fake_addon.cjs", false));
+ fs::write(two_dir.join("lib.js"), &on_ab).unwrap();
+ let two_run =
+ Command::new("node").arg("app.js").current_dir(&two_dir).env_remove(DISABLE_ENV).output().unwrap();
+ assert!(two_run.status.success(), "two-port run failed: {}", combined(&two_run));
+ assert_eq!(String::from_utf8_lossy(&two_run.stdout).trim(), "101,201");
+ assert_eq!(without_shim(&without_shim(&on_ab, &pa), &pb), two_src);
+
+ // Verify CJS record_wrap is a safe no-op when __fastAnythingWrap is unset, and ESM record_wrap has no CJS sync.
+ let nowrap_dir = base.join("nowrap");
+ fs::create_dir_all(&nowrap_dir).unwrap();
+ let nw_src = "function sq(x) {\n return x * x;\n}\nmodule.exports = { sq };\n";
+ let nw_wrapped = add_marked(nw_src, "recording lib.sq", &record_wrap("sq", false), false);
+ fs::write(nowrap_dir.join("lib.js"), &nw_wrapped).unwrap();
+ fs::write(nowrap_dir.join("app.js"), "const { sq } = require(\"./lib.js\");\nconsole.log(sq(4));\n").unwrap();
+ let nw_run = Command::new("node").arg("app.js").current_dir(&nowrap_dir).output().unwrap();
+ assert!(nw_run.status.success(), "nowrap failed: {}", combined(&nw_run));
+ assert_eq!(String::from_utf8_lossy(&nw_run.stdout).trim(), "16");
+ assert!(!record_wrap("sq", true).contains("module.exports"));
+
+ // Verify static method exported via class and aliased property in CJS.
+ let st_dir = base.join("static");
+ fs::create_dir_all(&st_dir).unwrap();
+ let st_src =
+ "class Calc {\n static sq(x) {\n return x * x;\n }\n}\nmodule.exports = { Calc, sq: Calc.sq };\n";
+ fs::write(st_dir.join("fake_addon.cjs"), "module.exports = { sq: (x) => x * x + 1000 };\n").unwrap();
+ fs::write(
+ st_dir.join("app.js"),
+ "const { Calc, sq } = require(\"./lib.js\");\nconsole.log(`${Calc.sq(3)},${sq(4)}`);\n",
+ )
+ .unwrap();
+ let st_port = Port { owner: Some("Calc".into()), id: "lib.Calc.sq".into(), ..mk_port("sq") };
+ let st_on = with_shim(st_src, &st_port, &shim(&st_port, "./fake_addon.cjs", false));
+ fs::write(st_dir.join("lib.js"), &st_on).unwrap();
+ let st_run = Command::new("node").arg("app.js").current_dir(&st_dir).env_remove(DISABLE_ENV).output().unwrap();
+ assert!(st_run.status.success(), "static CJS run failed: {}", combined(&st_run));
+ assert_eq!(String::from_utf8_lossy(&st_run.stdout).trim(), "1009,1016");
+ assert_eq!(without_shim(&st_on, &st_port), st_src);
+
+ // Verify is_esm_file across runtimes and extensions.
+ assert!(!is_esm_file(&base, &base.join("a.js"), Runtime::Node));
+ assert!(is_esm_file(&base, &base.join("a.mjs"), Runtime::Node));
+ assert!(is_esm_file(&base, &base.join("a.js"), Runtime::Deno));
+ assert!(is_esm_file(&base, &base.join("a.ts"), Runtime::Deno));
+ assert!(!is_esm_file(&base, &base.join("a.cjs"), Runtime::Deno));
+ assert!(!is_esm_file(&base, &base.join("a.cts"), Runtime::Deno));
+
+ let _ = fs::remove_dir_all(&base);
+ }
}
diff --cc src/node/runner.mjs
index 8afaf3a,06394c8..e814692
--- a/src/node/runner.mjs
+++ b/src/node/runner.mjs
@@@ -459,8 -330,7 +676,8 @@@ function describe(file, line0, name, en
if (!parsed.has(file)) {
try {
const src = readFileSync(file, "utf8");
- const code = codeOnly(src);
- parsed.set(file, { src, code: codeOnly(src, { jsx: /\.[jt]sx$/i.test(file) }), top: topLevelFunctions(src) });
++ const code = codeOnly(src, { jsx: /\.[jt]sx$/i.test(file) });
+ parsed.set(file, { src, code, top: topLevelFunctions(src), imports: importsOf(src, code) });
} catch {
parsed.set(file, null);
}