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.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
Merge #153
EL4CTEO03d2059844ad
diff --cc src/node.rsindex ff45d7c,debee41..b7abcfb--- a/src/node.rs+++ b/src/node.rs@@@ -2630,181 -2326,46 +2824,224 @@@ assert.ok(!same([Number.MAX_VALUE, Infilet _ = fs::remove_dir_all(&base);}+ #[test]+ fn auto_detected_esm_without_package_type_enables_and_loads() {+ // Syntax-level checks for has_esm_syntax.+ assert!(has_esm_syntax("export function f(x) { return x; }\n"));+ assert!(has_esm_syntax("const x = 1\nexport const f = (n) => n + x\n"));+ assert!(has_esm_syntax("import { a } from './a.js';\nfunction f() { return a; }\n"));+ assert!(has_esm_syntax("import './side-effect.js';\n"));+ assert!(has_esm_syntax("import type from './mod.js';\n"));+ assert!(has_esm_syntax("import type, { a } from './mod.js';\n"));+ assert!(has_esm_syntax("const re = /'/;\nexport default function f(x) { return x; }\n"));+ assert!(has_esm_syntax("function f() { return import.meta.url; }\n"));+ assert!(has_esm_syntax("\u{feff}#!/usr/bin/env node\nexport function f() {}\n"));+ assert!(has_esm_syntax("const s = `a ${1 + 2} b`;\nexport const f = () => s;\n"));+ assert!(has_esm_syntax("let i = 4;\nconst a = i++ / 2; // don't break\nexport function f(x) { return x; }\n"));+ assert!(has_esm_syntax("let i = 4;\nconst a = i-- / 2; // '\nexport function f(x) { return x; }\n"));+ assert!(has_esm_syntax("const a = { valueOf() { return 4; } } / 2; // '\nexport function f() {}\n"));+ assert!(has_esm_syntax("const a = m.get('a')! / 2; // '\nexport function f() {}\n"));+ assert!(has_esm_syntax("if (ok) /'/.test(s);\nexport function f() {}\n"));+ assert!(has_esm_syntax("const x = 1 /*\n*/ export function f(n) { return n; }\n"));+ assert!(has_esm_syntax("\u{00a0}export function f(x) { return x; }\n"));+ assert!(has_esm_syntax("const x = 1\u{2028}export function f(x) { return x; }\n"));+ assert!(!has_esm_syntax("function f(x) { return x; }\nmodule.exports = { f };\n"));+ assert!(!has_esm_syntax("exports.f = function(x) { return x; };\n"));+ assert!(!has_esm_syntax("// export function f() {}\n/* import x from 'y'; */\nmodule.exports = {};\n"));+ assert!(!has_esm_syntax("const s = \"export function f() {}\";\nconst t = `import.meta.url`;\n"));+ assert!(!has_esm_syntax("import('./x.js');\nmodule.exports = {};\n"));+ assert!(!has_esm_syntax("async function f() { return import('./x.js'); }\nmodule.exports = { f };\n"));+ assert!(!has_esm_syntax(+ "import type { Stats } from 'node:fs';\nexport type T = number;\nmodule.exports = {};\n"+ ));+ assert!(!has_esm_syntax("import type from from './types.ts';\nmodule.exports = {};\n"));+ assert!(!has_esm_syntax("import fs = require('node:fs');\nexport interface I { x: number }\n"));+ assert!(!has_esm_syntax("const obj = { export: 1, import: 2 };\nconsole.log(obj.import.meta);\n"));+ assert!(!has_esm_syntax(+ "let i = 4;\nconst a = i++ / 2; // '\nconst s = \"'; export function fake() {}\";\nmodule.exports = { a, s };\n"+ ));+ assert!(!has_esm_syntax(+ "const a = { valueOf() { return 4; } } / 2; // '\nconst s = \"'; export function fake() {}\";\nmodule.exports = { a, s };\n"+ ));+ assert!(!has_esm_syntax(+ "if (ok) /'/.test(s);\nconst t = \"'; export function fake() {}\";\nmodule.exports = { t };\n"+ ));+ // Unterminated `/` on a long line must stay linear rather than quadratic.+ let pathological = format!("{}\nconst ok = 1;\n", "x = /[".repeat(20_000));+ assert!(!has_esm_syntax(&pathological));++ 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 base = tmp.join(format!("fa-node-auto-esm-{}", std::process::id()));+ let _ = fs::remove_dir_all(&base);++ // 1. Auto-detected ESM in .ts (no package.json) and .js (package.json without "type"):+ // enable() must emit ESM createRequire(import.meta.url) so Node loads the addon instead of+ // silently swallowing ReferenceError: require is not defined.+ for (name, ext, pkg, lib_src, app_src) in [+ (+ "ts-no-pkg",+ "ts",+ None,+ "export function sq(x: number): number {\n return x * x;\n}\n",+ "import { sq } from \"./lib.ts\";\nconsole.log(sq(3));\n",+ ),+ (+ "js-pkg-no-type",+ "js",+ Some("{\"name\": \"demo\"}\n"),+ "const module = null;\nexport function sq(x) {\n return x * x;\n}\n",+ "import { sq } from \"./lib.js\";\nconsole.log(sq(3));\n",+ ),+ (+ "js-no-semicolons",+ "js",+ None,+ "const offset = 0\nexport const sq = (x) => x * x + offset\n",+ "import { sq } from \"./lib.js\"\nconsole.log(sq(3))\n",+ ),+ ] {+ let dir = base.join(name);+ fs::create_dir_all(dir.join(".fast/lib")).unwrap();+ if let Some(pkg) = pkg {+ fs::write(dir.join("package.json"), pkg).unwrap();+ }+ let lib_name = format!("lib.{ext}");+ let app_name = format!("app.{ext}");+ fs::write(dir.join(&lib_name), lib_src).unwrap();+ fs::write(dir.join(&app_name), app_src).unwrap();+ fs::write(dir.join("fake_addon.cjs"), "module.exports = { sq: (x) => x * x + 1000 };\n").unwrap();+ let port = Port {+ id: "lib.sq".into(),+ file: lib_name.clone(),+ 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 ctx = Ctx::open(&dir).unwrap();+ assert!(is_esm(&dir, &dir.join(&lib_name)), "{name}: expected auto-detected ESM");+ enable(&ctx, &port).unwrap();+ let on_disk = fs::read_to_string(dir.join(&lib_name)).unwrap();+ assert!(on_disk.contains("createRequire(import.meta.url)"), "{name}: expected ESM shim, got:\n{on_disk}");+ assert!(!on_disk.contains("module.exports"), "{name}: ESM shim must not emit CJS sync:\n{on_disk}");++ // Run with a real Node subprocess using a CJS fake addon loaded through the ESM shim.+ let runnable = on_disk.replace("./.fast/lib/fa_lib_sq.node", "./fake_addon.cjs");+ fs::write(dir.join(&lib_name), &runnable).unwrap();+ let rust_run =+ Command::new("node").arg(&app_name).current_dir(&dir).env_remove(DISABLE_ENV).output().unwrap();+ let orig_run =+ Command::new("node").arg(&app_name).current_dir(&dir).env(DISABLE_ENV, "1").output().unwrap();+ fs::write(dir.join(&lib_name), &on_disk).unwrap();+ disable(&ctx, &port).unwrap();+ let restored = fs::read_to_string(dir.join(&lib_name)).unwrap();++ assert!(rust_run.status.success(), "{name}: enabled run failed: {}", combined(&rust_run));+ assert_eq!(+ String::from_utf8_lossy(&rust_run.stdout).trim(),+ "1009",+ "{name}: Rust addon must actually load in auto-detected ESM"+ );+ assert!(orig_run.status.success(), "{name}: disabled run failed: {}", combined(&orig_run));+ assert_eq!(String::from_utf8_lossy(&orig_run.stdout).trim(), "9", "{name}: FAST_ANYTHING_DISABLE=1");+ assert_eq!(restored, lib_src, "{name}: disable must restore byte for byte");+ }++ // 2. Explicit package.json "type": "commonjs" disables syntax detection (stays CJS),+ // and a .ts file with only `import type` / `export type` + `module.exports` stays CJS.+ let cjs_pkg = base.join("pkg-cjs");+ fs::create_dir_all(&cjs_pkg).unwrap();+ fs::write(cjs_pkg.join("package.json"), "{\"type\": \"commonjs\"}\n").unwrap();+ fs::write(cjs_pkg.join("lib.js"), "export function sq(x) { return x * x; }\n").unwrap();+ assert!(!is_esm(&cjs_pkg, &cjs_pkg.join("lib.js")), "explicit type=commonjs must stay CJS");++ let ts_type_only = base.join("ts-type-only");+ fs::create_dir_all(&ts_type_only).unwrap();+ fs::write(+ ts_type_only.join("lib.ts"),+ "export type Num = number;\nfunction sq(x: Num): Num { return x * x; }\nmodule.exports = { sq };\n",+ )+ .unwrap();+ assert!(!is_esm(&ts_type_only, &ts_type_only.join("lib.ts")), "type-only TS export with CJS must stay CJS");++ // 3. Nearest package.json wins even when it omits "type" (does not inherit parent "type").+ let nested_cjs_parent = base.join("nested-cjs-parent");+ fs::create_dir_all(nested_cjs_parent.join("sub")).unwrap();+ fs::write(nested_cjs_parent.join("package.json"), "{\"type\": \"commonjs\"}\n").unwrap();+ fs::write(nested_cjs_parent.join("sub/package.json"), "{\"name\": \"sub\"}\n").unwrap();+ fs::write(nested_cjs_parent.join("sub/lib.js"), "export function sq(x) { return x * x; }\n").unwrap();+ assert!(+ is_esm(&nested_cjs_parent, &nested_cjs_parent.join("sub/lib.js")),+ "nearest package.json omitting type must detect ESM instead of inheriting parent commonjs"+ );++ let nested_esm_parent = base.join("nested-esm-parent");+ fs::create_dir_all(nested_esm_parent.join("sub")).unwrap();+ fs::write(nested_esm_parent.join("package.json"), "{\"type\": \"module\"}\n").unwrap();+ fs::write(nested_esm_parent.join("sub/package.json"), "{\"name\": \"sub\"}\n").unwrap();+ fs::write(nested_esm_parent.join("sub/lib.js"), "function sq(x) { return x * x; }\nmodule.exports = { sq };\n")+ .unwrap();+ assert!(+ !is_esm(&nested_esm_parent, &nested_esm_parent.join("sub/lib.js")),+ "nearest package.json omitting type must stay CJS for CJS syntax instead of inheriting parent module"+ );++ let _ = fs::remove_dir_all(&base);+ }+++ #[test]+ fn shadowed_io_names_and_pure_crypto_are_portable_in_scan() {+ 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-io-shadow-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ fs::write(+ dir.join("work.mjs"),+ "import crypto from \"node:crypto\";\n\+ import fs from \"node:fs\";\n\n\+ export function scoreDoc(document, window, row) {\n\+ let total = 0;\n\+ for (let i = 0; i < 4000; i++) {\n\+ total += (document.length + window + row.process + (i & fs.constants.R_OK)) % 97;\n\+ }\n\+ return crypto.createHash(\"sha256\").update(String(total)).digest(\"hex\");\n\+ }\n",+ )+ .unwrap();+ fs::write(+ dir.join("app.mjs"),+ "import { scoreDoc } from \"./work.mjs\";\n\+ let acc = 0;\n\+ for (let r = 0; r < 1500; r++) acc += scoreDoc(\"hello\", 8, { process: 3 }).length;\n\+ console.log(acc);\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 == "scoreDoc")+ .unwrap_or_else(|| panic!("missing hotspot scoreDoc; got {:?}", scanned.hotspots));+ assert!(h.portable() && h.blockers.is_empty(), "scoreDoc should be portable, got {:?}", h.blockers);+ }}