nodejs/module.rs
1//! CommonJS module loader.
2//!
3//! Node's `require()` semantics, layered on the existing engine — no bespoke VM
4//! primitive. A `.js` file is wrapped in the canonical Node module wrapper
5//! `(function (exports, require, module, __dirname, __filename) { … })`, compiled
6//! through the ordinary `compile` → `load_merged` path to obtain the wrapper
7//! FUNCTION value, then `host::invoke`d with a fresh `module = { exports: {} }`.
8//! Whatever the body assigns to `module.exports` (or hangs off `exports`) is the
9//! module's value; it is cached by resolved absolute path so a second `require`
10//! of the same file returns the identical object and circular requires observe
11//! the partially-filled `exports`.
12//!
13//! Core modules (`fs`, `path`, `http`, …) short-circuit to their native
14//! `JsObj::Builtin` namespace (see `stdlib::resolve`) and are never read from
15//! disk. Everything else — relative paths, JSON files, and bare `node_modules`
16//! packages with their `package.json` `"exports"`/`"main"` and `index.js`
17//! fallbacks — resolves on the real filesystem and runs the genuine, unmodified
18//! source.
19//!
20//! Per-module `require` is a real JS closure that bakes in the defining module's
21//! directory, so a `require(...)` deferred inside a function called much later
22//! still resolves against the module that defined it (a single global
23//! "current dir" would resolve against the wrong module). The closure is minted
24//! by a one-time compiled factory (`FACTORY`) invoked with the directory and the
25//! module's filename (the requirer a `Cannot find module` stack names);
26//! it dispatches back into this loader through the `__cjs_require` /
27//! `__cjs_resolve` global native builtins.
28
29use std::cell::RefCell;
30use std::collections::HashMap;
31use std::path::{Path, PathBuf};
32
33use crate::host::{self, with_host, JsObj};
34use fusevm::Value;
35
36thread_local! {
37 /// Require cache: resolved absolute path → the `module` object (its `.exports`
38 /// is re-read on every hit, matching Node — `module.exports = X` reassignment
39 /// is observed by later requires).
40 static CACHE: RefCell<HashMap<PathBuf, Value>> = RefCell::new(HashMap::new());
41 /// Resolved `(specifier, from_dir)` to the CANONICAL absolute path it named,
42 /// so a repeated `require` of an already-loaded module costs one hash lookup
43 /// instead of walking `node_modules` and calling `canonicalize` again.
44 ///
45 /// Node keeps the same table (`Module._pathCache`) with the same
46 /// consequence: a file that appears after a specifier has already resolved
47 /// is not picked up by a later `require` of that specifier.
48 static PATH_CACHE: RefCell<HashMap<(String, PathBuf), PathBuf>> =
49 RefCell::new(HashMap::new());
50 /// Base directory the ENTRY script's top-level `require` resolves against
51 /// (the dir of `node app.js`, or cwd for `node -e`).
52 static ENTRY_DIR: RefCell<PathBuf> = RefCell::new(std::env::current_dir().unwrap_or_default());
53 /// The ENTRY module's `filename` (`<cwd>/[eval]` under `-e`) — the bottom
54 /// of every require stack.
55 static ENTRY_FILE: RefCell<String> = const { RefCell::new(String::new()) };
56 /// Each loaded module's filename → the filename of the module whose
57 /// `require` first loaded it: node's `moduleParentCache`, walked to build
58 /// the `requireStack` of a `Cannot find module` error.
59 static PARENTS: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
60 /// The compiled per-module `require`-closure factory (see module docs),
61 /// minted once per host and reused for every module.
62 static FACTORY: RefCell<Option<Value>> = const { RefCell::new(None) };
63 /// The compiled synthetic-CallSite-array factory (for `Error.captureStackTrace`
64 /// under a custom `Error.prepareStackTrace`), minted once per host.
65 static CALLSITE_FACTORY: RefCell<Option<Value>> = const { RefCell::new(None) };
66}
67
68/// Clear all per-host loader state. Called from `host::reset_host` so a fresh
69/// eval (which rebuilds the heap) never reuses a stale heap handle.
70pub fn reset() {
71 crate::esm::reset();
72 CACHE.with(|c| c.borrow_mut().clear());
73 PATH_CACHE.with(|c| c.borrow_mut().clear());
74 PARENTS.with(|c| c.borrow_mut().clear());
75 ENTRY_FILE.with(|f| f.borrow_mut().clear());
76 FACTORY.with(|f| *f.borrow_mut() = None);
77 CALLSITE_FACTORY.with(|f| *f.borrow_mut() = None);
78 ENTRY_DIR.with(|d| *d.borrow_mut() = std::env::current_dir().unwrap_or_default());
79}
80
81/// The resolved filenames of every currently loaded module, in load order —
82/// the keys `require.cache` exposes.
83pub fn cache_keys() -> Vec<String> {
84 CACHE.with(|c| {
85 c.borrow()
86 .keys()
87 .map(|p| p.to_string_lossy().into_owned())
88 .collect()
89 })
90}
91
92/// The module object cached under the resolved filename `key`, if any.
93pub fn cache_get(key: &str) -> Option<Value> {
94 CACHE.with(|c| c.borrow().get(Path::new(key)).cloned())
95}
96
97/// Drop `key` from the module cache, so the next `require` of that file runs it
98/// again. This is what `delete require.cache[id]` must do to mean anything.
99pub fn cache_delete(key: &str) -> bool {
100 CACHE.with(|c| c.borrow_mut().remove(Path::new(key)).is_some())
101}
102
103/// Set the base directory the ENTRY script's `require` resolves against.
104pub fn set_entry_dir(dir: PathBuf) {
105 ENTRY_DIR.with(|d| *d.borrow_mut() = dir);
106}
107
108/// The ENTRY script's base directory.
109pub fn entry_dir() -> PathBuf {
110 ENTRY_DIR.with(|d| d.borrow().clone())
111}
112
113/// The ENTRY module's `filename`, the requirer the top-level `require` names.
114pub fn entry_file() -> String {
115 ENTRY_FILE.with(|f| f.borrow().clone())
116}
117
118/// Node's `Cannot find module` error (`Module._resolveFilename`): the message
119/// lists the require stack — the requiring module, then each module that first
120/// loaded the one before it — and the error carries `code` and `requireStack`
121/// as own properties, in that order.
122pub fn not_found_error(spec: &str, from_file: &str) -> String {
123 let mut stack: Vec<String> = Vec::new();
124 let mut cursor = Some(from_file.to_string()).filter(|f| !f.is_empty());
125 while let Some(file) = cursor {
126 cursor = PARENTS.with(|p| p.borrow().get(&file).cloned());
127 stack.push(file);
128 }
129 let mut msg = format!("Cannot find module '{spec}'");
130 if !stack.is_empty() {
131 msg.push_str("\nRequire stack:\n- ");
132 msg.push_str(&stack.join("\n- "));
133 }
134 let text = host::plain_coded_error("Error", "MODULE_NOT_FOUND", &msg);
135 let err = with_host(|h| crate::builtins::synth_error(h, &text));
136 let stack = with_host(|h| {
137 let items: Vec<Value> = stack.into_iter().map(|s| h.new_str(s)).collect();
138 h.new_array(items)
139 });
140 let _ = crate::builtins::set_property_pub(&err, "requireStack", stack);
141 with_host(|h| h.exc = Some(err));
142 text
143}
144
145/// Install the CJS wrapper variables the ENTRY script sees.
146///
147/// A `require`d module already receives `exports`/`require`/`module`/`__dirname`
148/// /`__filename` as wrapper parameters (see `compile_wrapper`); the entry
149/// script used to receive none of them, so `typeof module` was `"undefined"`
150/// there and every UMD header took its browser branch. Node gives the entry
151/// script the same five names, with values that DEPEND ON THE ENTRY POINT:
152///
153/// | | `node f.js` | `node -e` | `node -` / piped |
154/// | --- | --- | --- | --- |
155/// | `__filename` | resolved abs path | `[eval]` | `[stdin]` |
156/// | `__dirname` | its directory | `.` | `.` |
157/// | `module.id` | `.` | `[eval]` | `[stdin]` |
158/// | `module.path` | its directory | `.` | `.` |
159///
160/// `module.filename` is `path.resolve(__filename)` in every case, so under `-e`
161/// it is `<cwd>/[eval]` — a path that does not exist, which is Node's own
162/// value. Measured on node v26.7.0.
163///
164/// `origin` is the `__filename` value: an absolute script path, or `[eval]` /
165/// `[stdin]` for the two source-on-the-command-line entry points.
166pub fn install_entry_globals(origin: &str) {
167 let from_file = origin != "[eval]" && origin != "[stdin]";
168 let (dirname, id) = if from_file {
169 let dir = Path::new(origin)
170 .parent()
171 .map(|p| p.to_string_lossy().into_owned())
172 .unwrap_or_else(|| ".".into());
173 (dir, ".".to_string())
174 } else {
175 (".".to_string(), origin.to_string())
176 };
177 let filename = crate::stdlib::path::resolve_one(origin);
178 ENTRY_FILE.with(|f| *f.borrow_mut() = filename.clone());
179 let module = new_module(&id, &dirname, &filename);
180 let exports = module_exports(&module);
181 with_host(|h| {
182 let origin_str = h.new_str(origin.to_string());
183 let dirname = h.new_str(dirname);
184 h.set_global("__filename", origin_str);
185 h.set_global("__dirname", dirname);
186 h.set_global("module", module.clone());
187 // `require.main === module` in the entry script is the canonical
188 // "am I the program" test, and it read `undefined === <module>`
189 // because nothing ever set `main`. The ENTRY module is the value for
190 // every `require` in the process, not just this one, so it is recorded
191 // for the per-module closures too (`make_require` installs it).
192 // …but only when the program IS a module. `node -e` and a script on
193 // stdin run as a Script, not a CommonJS module, and node reports
194 // `require.main` as `undefined` for both.
195 if from_file {
196 h.set_builtin_static("require", "main", module.clone());
197 }
198 h.set_global("exports", exports.clone());
199 // Top-level `this`: the module's `exports` from a file (CommonJS
200 // module), `globalThis` from `-e` and from stdin (a Script). See
201 // `JsHost::set_top_this` for the measurements.
202 let top = if from_file {
203 exports
204 } else {
205 h.global_object()
206 };
207 h.set_top_this(top);
208 });
209}
210
211// ── resolution ───────────────────────────────────────────────────────────────
212
213/// Append `.ext` to a path (Node appends the extension, it does not replace an
214/// existing one — `foo.min` → `foo.min.js`, not `foo.js`).
215fn add_ext(p: &Path, ext: &str) -> PathBuf {
216 let mut s = p.as_os_str().to_owned();
217 s.push(".");
218 s.push(ext);
219 PathBuf::from(s)
220}
221
222/// `require`-as-a-file: `p`, then `p.js`, then `p.json`. `.node` native addons
223/// are skipped (unsupported), matching the resolution order minus that step.
224fn load_as_file(p: &Path) -> Option<PathBuf> {
225 if p.is_file() {
226 return Some(p.to_path_buf());
227 }
228 for ext in ["js", "json"] {
229 let cand = add_ext(p, ext);
230 if cand.is_file() {
231 return Some(cand);
232 }
233 }
234 None
235}
236
237/// `require`-as-a-directory: honor `package.json` `"exports"`/`"main"`, else
238/// `index.js` / `index.json`.
239fn load_as_dir(p: &Path) -> Option<PathBuf> {
240 let pkg = p.join("package.json");
241 if pkg.is_file() {
242 if let Some(main) = pkg_entry(&pkg) {
243 let mp = p.join(&main);
244 if let Some(f) = load_as_file(&mp).or_else(|| load_index(&mp)) {
245 return Some(f);
246 }
247 }
248 }
249 load_index(p)
250}
251
252/// `index.js` / `index.json` inside directory `p`.
253fn load_index(p: &Path) -> Option<PathBuf> {
254 for name in ["index.js", "index.json"] {
255 let cand = p.join(name);
256 if cand.is_file() {
257 return Some(cand);
258 }
259 }
260 None
261}
262
263/// The relative entry path a `package.json` declares: the `"."` (or main-string)
264/// `"exports"` target if present, else `"main"`. Only the common `"exports"`
265/// shapes are handled — a bare string, or an object whose `"."` maps to a string
266/// or to `{ "require"/"default"/"node": "…" }`. Anything more exotic falls back
267/// to `"main"`, then to the directory's `index.js`.
268fn pkg_entry(pkg: &Path) -> Option<String> {
269 let text = std::fs::read_to_string(pkg).ok()?;
270 let json: serde_json::Value = serde_json::from_str(&text).ok()?;
271 if let Some(e) = exports_main(json.get("exports")) {
272 return Some(strip_dot_slash(&e));
273 }
274 json.get("main")
275 .and_then(|m| m.as_str())
276 .map(strip_dot_slash)
277}
278
279/// Resolve the `"exports"` field down to a single relative path for the `"."`
280/// (package root) entry, across the shapes CommonJS packages commonly ship.
281fn exports_main(exports: Option<&serde_json::Value>) -> Option<String> {
282 let exports = exports?;
283 // `"exports": "./index.js"` — a bare string is the `"."` target.
284 if let Some(s) = exports.as_str() {
285 return Some(s.to_string());
286 }
287 let obj = exports.as_object()?;
288 // Either a subpath map keyed by `"."`, or a bare conditions map at the root.
289 let target = obj.get(".").unwrap_or(exports);
290 condition_target(target)
291}
292
293/// Reduce an `"exports"` target — a string, or a conditions object — to a path,
294/// preferring the CommonJS-relevant conditions (`require`/`node`/`default`).
295fn condition_target(target: &serde_json::Value) -> Option<String> {
296 if let Some(s) = target.as_str() {
297 return Some(s.to_string());
298 }
299 let obj = target.as_object()?;
300 for cond in ["require", "node", "default"] {
301 if let Some(v) = obj.get(cond) {
302 if let Some(s) = condition_target(v) {
303 return Some(s);
304 }
305 }
306 }
307 None
308}
309
310/// Drop a leading `./` from a package-relative path.
311fn strip_dot_slash(s: &str) -> String {
312 s.strip_prefix("./").unwrap_or(s).to_string()
313}
314
315/// Resolve `spec` (already known to be a bare specifier) by walking parent
316/// directories from `from_dir`, checking `<dir>/node_modules/<spec>` at each
317/// level with the file-then-directory rules.
318fn resolve_bare(spec: &str, from_dir: &Path) -> Option<PathBuf> {
319 let mut dir = Some(from_dir);
320 while let Some(d) = dir {
321 // Skip a `node_modules/node_modules` descent.
322 if d.file_name().is_some_and(|n| n == "node_modules") {
323 dir = d.parent();
324 continue;
325 }
326 let candidate = d.join("node_modules").join(spec);
327 if let Some(f) = load_as_file(&candidate).or_else(|| load_as_dir(&candidate)) {
328 return Some(f);
329 }
330 dir = d.parent();
331 }
332 None
333}
334
335/// Resolve `spec` relative to `from_dir` to an absolute file path, or `None` if
336/// no file matches (core modules are handled earlier, by the caller).
337pub fn resolve(spec: &str, from_dir: &Path) -> Option<PathBuf> {
338 let is_relative =
339 spec.starts_with("./") || spec.starts_with("../") || spec == "." || spec == "..";
340 let is_absolute = spec.starts_with('/');
341 if is_relative || is_absolute {
342 // NORMALIZED, not merely joined: `Path::join` keeps the `.` in
343 // `<dir>/./d.js`, and that string is what `require.resolve` returns and
344 // what keys the module cache — so `./d.js` and `d.js` from the same
345 // directory would be two cache entries of one file.
346 let joined = if is_absolute {
347 spec.to_string()
348 } else {
349 from_dir.join(spec).to_string_lossy().into_owned()
350 };
351 let base = PathBuf::from(crate::stdlib::path::resolve_one(&joined));
352 return load_as_file(&base).or_else(|| load_as_dir(&base));
353 }
354 resolve_bare(spec, from_dir)
355}
356
357// ── loading / execution ──────────────────────────────────────────────────────
358
359/// `require(spec)` from `from_dir`: the single entry point shared by the
360/// top-level `require` builtin and the per-module `__cjs_require`. Returns the
361/// module's exports value.
362pub fn require(spec: &str, from_dir: &Path, from_file: &str) -> Result<Value, String> {
363 // Core module: the native namespace value, never a file (mirrors the legacy
364 // `require` path — `require('events')` yields the EventEmitter ctor, etc.).
365 if let Some(v) = crate::stdlib::data_module(spec) {
366 return Ok(v);
367 }
368 if let Some(ns) = crate::stdlib::resolve(spec) {
369 return Ok(with_host(|h| h.alloc(JsObj::Builtin(ns.to_string()))));
370 }
371 // Resolution is filesystem work — a `node_modules` walk, a set of extension
372 // probes, then `canonicalize` — and a program that requires the same
373 // specifier in a loop paid all of it on every call even though the module
374 // itself was already loaded and cached. The answer is memoized per
375 // `(specifier, from_dir)`.
376 let key = (spec.to_string(), from_dir.to_path_buf());
377 if let Some(hit) = PATH_CACHE.with(|c| c.borrow().get(&key).cloned()) {
378 return load_file(&hit, from_file);
379 }
380 let path = resolve(spec, from_dir).ok_or_else(|| not_found_error(spec, from_file))?;
381 // A canonical absolute key so the same file required via different relative
382 // specifiers shares one cache entry.
383 let path = std::fs::canonicalize(&path).unwrap_or(path);
384 PATH_CACHE.with(|c| c.borrow_mut().insert(key, path.clone()));
385 load_file(&path, from_file)
386}
387
388/// Load the resolved absolute file `path` (`.json` parses to its value; `.js`
389/// runs through the module wrapper) and return its exports, caching by path.
390fn load_file(path: &Path, parent: &str) -> Result<Value, String> {
391 if let Some(cached) = CACHE.with(|c| c.borrow().get(path).cloned()) {
392 // Re-read `.exports` — a cached module may have reassigned it.
393 return Ok(module_exports(&cached));
394 }
395 // A fresh module object records the requirer that created it.
396 if !parent.is_empty() {
397 let key = path.to_string_lossy().into_owned();
398 PARENTS.with(|p| p.borrow_mut().insert(key, parent.to_string()));
399 }
400 if path.extension().is_some_and(|e| e == "json") {
401 let text = std::fs::read_to_string(path)
402 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
403 let src = with_host(|h| h.new_str(text));
404 let val = crate::builtins::call_builtin_function("JSON.parse", vec![src])?;
405 // A JSON module's value IS the parsed data; cache a synthetic wrapper so
406 // repeated requires share it.
407 let abs = path.to_string_lossy().into_owned();
408 let dir = path.parent().unwrap_or(Path::new("")).to_string_lossy();
409 let module = new_module(&abs, &dir, &abs);
410 with_host(|h| {
411 if let Some(JsObj::Object(p)) = h.get_mut(&module) {
412 p.insert("exports".to_string(), val.clone());
413 p.insert("loaded".to_string(), Value::Bool(true));
414 }
415 });
416 CACHE.with(|c| c.borrow_mut().insert(path.to_path_buf(), module));
417 return Ok(val);
418 }
419
420 // `require(esm)`: a file whose format is ES module — by its `.mjs`
421 // extension or its package's `"type": "module"` — loads through the ES
422 // module loader and yields its namespace.
423 if is_declared_esm(path) {
424 return crate::esm::require_module(path, parent);
425 }
426 let source = std::fs::read_to_string(path)
427 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
428 let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
429
430 // Compile the Node module wrapper to obtain the wrapper FUNCTION value.
431 // A compile error names the offending file: through the source arrow when
432 // the parser placed it, else in the message.
433 // A source of undeclared format that fails only because it is written as
434 // an ES module is one (node's syntax detection), and loads as one.
435 let wrapper = match compile_wrapper(&source, path) {
436 Ok(w) => w,
437 Err(e) if crate::esm::detect_module(&source, &e) => {
438 return crate::esm::require_module(path, parent);
439 }
440 // With its position recorded, the report's source arrow names the file,
441 // as node's does; otherwise the message has to.
442 Err(e) if with_host(|h| h.throw_site.as_ref().is_some_and(|s| s.msg == e)) => {
443 return Err(e)
444 }
445 Err(e) => return Err(format!("{e}\n while loading {}", path.display())),
446 };
447
448 // The `module` object, plus the aliases the wrapper receives. A required
449 // module's `id` IS its absolute filename (only the entry module's is `.`).
450 let abs = path.to_string_lossy().into_owned();
451 let module = new_module(&abs, &dir.to_string_lossy(), &abs);
452 let exports = module_exports(&module);
453 let require_fn = make_require(&dir, &abs)?;
454 let (dirname, filename) = with_host(|h| {
455 (
456 h.new_str(dir.to_string_lossy().to_string()),
457 h.new_str(path.to_string_lossy().to_string()),
458 )
459 });
460
461 // Cache BEFORE running so a circular `require` back to this module observes
462 // the partial `exports`.
463 CACHE.with(|c| c.borrow_mut().insert(path.to_path_buf(), module.clone()));
464
465 // node calls the wrapper with `this` = `module.exports`.
466 host::invoke(
467 &wrapper,
468 vec![
469 exports.clone(),
470 require_fn,
471 module.clone(),
472 dirname,
473 filename,
474 ],
475 Some(exports),
476 )?;
477 mark_loaded(&module);
478
479 Ok(module_exports(&module))
480}
481
482/// A fresh `module` object: `{ id, path, exports, filename, loaded, children,
483/// paths }`, in that key order.
484///
485/// The order is observable (`Object.keys(module)`) and this is node's. Only
486/// `exports` used to be present, so a module reading `module.id` or
487/// `module.filename` — both of which a bundler-emitted or `__dirname`-avoiding
488/// package does — got `undefined`.
489///
490/// `paths` is the `node_modules` chain from `dir` up to the root, the same walk
491/// `require` performs to resolve a bare specifier. `loaded` starts `false`; it
492/// is set once the body returns.
493fn new_module(id: &str, dir: &str, filename: &str) -> Value {
494 let mut node_modules: Vec<String> = Vec::new();
495 let mut cur = Some(Path::new(dir));
496 while let Some(d) = cur.filter(|d| !d.as_os_str().is_empty()) {
497 node_modules.push(d.join("node_modules").to_string_lossy().into_owned());
498 cur = d.parent();
499 }
500 with_host(|h| {
501 let exports = h.new_object(indexmap::IndexMap::new());
502 let mut props = indexmap::IndexMap::new();
503 props.insert("id".to_string(), h.new_str(id.to_string()));
504 props.insert("path".to_string(), h.new_str(dir.to_string()));
505 props.insert("exports".to_string(), exports);
506 props.insert("filename".to_string(), h.new_str(filename.to_string()));
507 props.insert("loaded".to_string(), Value::Bool(false));
508 // `module.parent` is long deprecated but PRESENT: node reports `null`
509 // for a file the loader reached directly, and code still tests
510 // `if (!module.parent)` to detect "run as the entry point". The key was
511 // missing entirely, so `'parent' in module` was false.
512 let null = h.null();
513 props.insert("parent".to_string(), null);
514 let children = h.new_array(Vec::new());
515 props.insert("children".to_string(), children);
516 let paths: Vec<Value> = node_modules.into_iter().map(|p| h.new_str(p)).collect();
517 let paths = h.new_array(paths);
518 props.insert("paths".to_string(), paths);
519 let obj = h.new_object(props);
520 // `parent` is present but NOT enumerable: `Object.keys(module)` does not
521 // list it, while `'parent' in module` is true. Adding it as an ordinary
522 // property changed the key order the es_parity module tests pin.
523 h.hide_prop(&obj, "parent");
524 obj
525 })
526}
527
528/// The directories `require.resolve` would search for `spec`, in order.
529///
530/// A RELATIVE specifier resolves against one directory — the requiring one — so
531/// node reports just that. A bare package name walks the `node_modules` chain
532/// up to the root.
533pub fn resolve_paths(spec: &str, from_dir: &std::path::Path) -> Vec<String> {
534 if spec.starts_with('.') || spec.starts_with('/') {
535 return vec![from_dir.to_string_lossy().into_owned()];
536 }
537 let mut out = Vec::new();
538 let mut cur = Some(from_dir);
539 while let Some(d) = cur {
540 out.push(d.join("node_modules").to_string_lossy().into_owned());
541 cur = d.parent();
542 }
543 out
544}
545
546/// Flip `module.loaded` once the body has run, as Node's loader does.
547fn mark_loaded(module: &Value) {
548 with_host(|h| {
549 if let Some(JsObj::Object(p)) = h.get_mut(module) {
550 p.insert("loaded".to_string(), Value::Bool(true));
551 }
552 });
553}
554
555/// Read `module.exports` (falls back to `undefined` for a malformed module).
556fn module_exports(module: &Value) -> Value {
557 with_host(|h| match h.get(module) {
558 Some(JsObj::Object(p)) => p.get("exports").cloned().unwrap_or(Value::Undef),
559 _ => Value::Undef,
560 })
561}
562
563/// Compile `<source>` wrapped in the Node module wrapper and return the wrapper
564/// FUNCTION value.
565fn compile_wrapper(source: &str, path: &Path) -> Result<Value, String> {
566 // A module may open with a hashbang line, which is only a comment at the
567 // start of the TEXT; inside the wrapper it would not be, so it becomes a
568 // `//` comment of the same length.
569 let source = match source.strip_prefix("#!") {
570 Some(rest) => format!("//{rest}"),
571 None => source.to_string(),
572 };
573 // A trailing newline before `})` guards a source ending in a `//` comment.
574 // Its stack frames and source arrow name the file, counting lines from
575 // the module's own first line rather than the wrapper's.
576 let origin = host::ScriptOrigin {
577 name: path.to_string_lossy().into_owned(),
578 line_shift: 1,
579 internal: false,
580 };
581 let text =
582 format!("(function (exports, require, module, __dirname, __filename) {{\n{source}\n}})");
583 crate::eval_in_global_scope_from(&text, Some(origin.clone())).inspect_err(|e| {
584 let at = crate::parser::take_error_pos();
585 host::note_syntax_error(&text, origin, e, at);
586 })
587}
588
589/// Compile+run a single JS expression on the LIVE host — no reset, no
590/// event-loop drain — and return its value.
591///
592/// This delegates to `crate::eval_in_global_scope`, the frontend's one
593/// runtime-source evaluator, and two things changed with it. The wrapper used to
594/// be compiled as `var __cjs_wN = (function …);` and read back out of the scope
595/// with `read_name`, because a bare expression statement pops its value; a
596/// completion-value compile returns the expression directly, so the capture
597/// variable and its uniquifying counter are gone. And the run used to happen on
598/// the CALLER's frame, which let a module body see the locals of whatever
599/// function called `require`: measured against node v26.7.0,
600/// `function outer(){ let secret = 1; return require('./m.js'); }` with `m.js` =
601/// `module.exports = typeof secret` is `"undefined"` there and was `"number"`
602/// here.
603fn eval_binding(src: &str) -> Result<Value, String> {
604 crate::eval_internal(src)
605}
606
607/// Build a per-module `require` closure bound to `dir` (see module docs).
608fn make_require(dir: &Path, file: &str) -> Result<Value, String> {
609 let factory = factory()?;
610 let (dir_str, file_str) = with_host(|h| {
611 (
612 h.new_str(dir.to_string_lossy().to_string()),
613 h.new_str(file.to_string()),
614 )
615 });
616 let req = host::invoke(&factory, vec![dir_str, file_str], None)?;
617 // Every `require` in the process reports the same `main` — the ENTRY
618 // module — which is what `require.main === module` tests against.
619 if let Some(main) = with_host(|h| h.builtin_static("require", "main")) {
620 // `req` is a FUNCTION value, so its properties live in the fn-prop side
621 // table, not in an object property map.
622 with_host(|h| h.set_fn_prop(&req, "main", main));
623 }
624 Ok(req)
625}
626
627/// The one-time compiled `require`-closure factory. `require.resolve` /
628/// `require.cache` are provided since some packages read them.
629fn factory() -> Result<Value, String> {
630 if let Some(f) = FACTORY.with(|f| f.borrow().clone()) {
631 return Ok(f);
632 }
633 let src = "(function (__cjs_dir, __cjs_file) {\n\
634 var req = function (spec) { return __cjs_require(spec, __cjs_dir, __cjs_file); };\n\
635 req.resolve = function (spec) { return __cjs_resolve(spec, __cjs_dir, __cjs_file); };\n\
636 req.cache = __cjs_cache;\n\
637 req.main = undefined;\n\
638 req.extensions = {};\n\
639 return req;\n\
640 });";
641 let f = eval_binding(src)?;
642 FACTORY.with(|c| *c.borrow_mut() = Some(f.clone()));
643 Ok(f)
644}
645
646/// An array of `depth` synthetic V8 CallSite objects for `Error.captureStackTrace`.
647/// Stack-introspection packages (e.g. `depd`) set `Error.prepareStackTrace` to a
648/// function that receives this array; the getters return neutral placeholders (no
649/// real frame info is available), which is enough for those packages to build
650/// their deprecation sites without throwing.
651pub fn callsite_stack(depth: usize) -> Result<Value, String> {
652 let factory = if let Some(f) = CALLSITE_FACTORY.with(|f| f.borrow().clone()) {
653 f
654 } else {
655 let src = "(function (n) {\n\
656 var a = [];\n\
657 for (var i = 0; i < n; i++) {\n\
658 a.push({\n\
659 getFileName: function () { return null; },\n\
660 getLineNumber: function () { return 0; },\n\
661 getColumnNumber: function () { return 0; },\n\
662 getFunctionName: function () { return null; },\n\
663 getMethodName: function () { return null; },\n\
664 getTypeName: function () { return null; },\n\
665 getThis: function () { return undefined; },\n\
666 isNative: function () { return false; },\n\
667 isEval: function () { return false; },\n\
668 toString: function () { return '<anonymous>'; }\n\
669 });\n\
670 }\n\
671 return a;\n\
672 });";
673 let f = eval_binding(src)?;
674 CALLSITE_FACTORY.with(|c| *c.borrow_mut() = Some(f.clone()));
675 f
676 };
677 host::invoke(&factory, vec![Value::Float(depth as f64)], None)
678}
679
680/// Whether `path` is an ES module by declaration alone — its `.mjs` extension,
681/// or a `.js` file in a package scope whose `"type"` is `"module"` — so no
682/// source has to be parsed to know. (A `.js` file of undeclared type is found
683/// to be one only when its CommonJS parse fails; see `load_file`.)
684fn is_declared_esm(path: &Path) -> bool {
685 match path.extension().and_then(|e| e.to_str()) {
686 Some("mjs") => true,
687 Some("js") => crate::esm::file_format_declared(path) == Some(crate::esm::Format::Module),
688 _ => false,
689 }
690}
691
692/// Load the resolved CommonJS file `path` (the ES module loader's path into
693/// this one): its `module.exports`, shared with every `require` of the file.
694pub fn require_file(path: &Path, parent: &str) -> Result<Value, String> {
695 load_file(path, parent)
696}