Skip to main content

nodejs/
esm.rs

1//! ECMAScript modules (ECMA-262 §16.2) on the existing engine.
2//!
3//! The pipeline, in the spec's terms:
4//!
5//! * **ParseModule** — [`crate::parser::parse_module`] parses with the Module
6//!   goal and [`analyze`] derives the module record's static fields: its
7//!   `[[RequestedModules]]`, `[[ImportEntries]]`, and the local / indirect /
8//!   star export entries (16.2.1.6.1), with the early errors that depend on
9//!   them (duplicate exports, exporting an undeclared name, an import binding
10//!   colliding with a declaration).
11//! * **Link / Evaluate** — the module-record algorithms (`InnerModuleLinking`,
12//!   `ResolveExport`, `GetExportedNames`, `InnerModuleEvaluation` with the
13//!   asynchronous-evaluation machinery for top-level `await`) are ported
14//!   step for step in `esm_loader.js`, which drives the records this file
15//!   produces through the `@@esm.*` natives in [`native`].
16//! * **InitializeEnvironment / ExecuteModule** — [`lower`] turns a module body
17//!   into one ordinary function the compiler already knows how to build:
18//!
19//!   ```text
20//!   (function [*] (%imp, %meta, %reg) {
21//!       %reg([() => local₀, () => local₁, …]);   // the export bindings
22//!       [yield;]                                 // only for a module in a cycle
23//!       …body…
24//!   })
25//!   ```
26//!
27//!   The function's scope IS the module environment: its hoisted function
28//!   declarations exist on entry and its `let`/`const`/`class` bindings sit in
29//!   their temporal dead zone until evaluation reaches them. Each exported
30//!   binding is handed to the loader as a getter closure over that scope, so a
31//!   read is always the binding's CURRENT value (a live binding), and a read
32//!   before initialisation throws the TDZ `ReferenceError`. Every reference to
33//!   an imported name is rewritten to `%imp[k]()`, a call of the getter the
34//!   loader resolved for import entry `k`; an assignment to one throws
35//!   `TypeError: Assignment to constant variable.` (an import binding is
36//!   immutable, 9.1.1.5.5). A module that is part of an import cycle is built
37//!   as a GENERATOR instead, so the loader can run its prologue — creating the
38//!   environment and registering its getters — before any module in the cycle
39//!   evaluates, which is what lets a cycle call a hoisted function of a module
40//!   that has not started yet. An acyclic module runs as a plain function, on
41//!   the ordinary stack.
42
43use std::collections::{HashMap, HashSet};
44use std::path::{Path, PathBuf};
45
46use crate::ast::*;
47
48/// Hidden parameter names of the lowered module function. No source text can
49/// spell a `%`, so they never collide with a user binding.
50const IMP: &str = "%imp";
51const META: &str = "%meta";
52const REG: &str = "%reg";
53/// The global the lowered `import(…)` calls (`builtins::global_binding`).
54pub const IMPORT_FN: &str = "%esm.import";
55/// Prefix a free reference to a CommonJS wrapper name gets in module code, so
56/// that it resolves to nothing: `require` is a lazily-bound global of this
57/// runtime, but in an ES module it is not defined at all. `arguments` is in
58/// the list too: module code runs inside the lowered function, whose own
59/// `arguments` the module's top level must not see.
60pub const CJS_FREE_PREFIX: &str = "%esm.cjs.";
61const CJS_NAMES: &[&str] = &[
62    "require",
63    "module",
64    "exports",
65    "__filename",
66    "__dirname",
67    "arguments",
68];
69
70/// One `[[ImportEntries]]` record (16.2.1.6, Table 61).
71#[derive(Debug, Clone)]
72pub struct ImportEntry {
73    /// Index into [`ModuleInfo::requests`].
74    pub request: usize,
75    /// The imported name, or `None` for `import * as ns` (namespace-object).
76    pub import_name: Option<String>,
77    pub local: String,
78    /// The declaration's `{ … }` clause (see [`ImportDecl::clause`]).
79    pub clause: Span,
80}
81
82/// One indirect export (`export { a as b } from "m"`, `export * as ns from "m"`).
83#[derive(Debug, Clone)]
84pub struct IndirectExport {
85    pub export_name: String,
86    pub request: usize,
87    /// `None` is `export * as ns`: the binding is the module's namespace.
88    pub import_name: Option<String>,
89}
90
91/// The static half of a Source Text Module Record.
92#[derive(Debug, Clone, Default)]
93pub struct ModuleInfo {
94    /// `[[RequestedModules]]`: (specifier, attributes), deduplicated, in source
95    /// order of first appearance.
96    pub requests: Vec<(String, Vec<(String, String)>)>,
97    pub imports: Vec<ImportEntry>,
98    /// `(exportName, localName)` — the order of the getters the prologue
99    /// registers.
100    pub local_exports: Vec<(String, String)>,
101    pub indirect_exports: Vec<IndirectExport>,
102    /// Request indices of `export * from "m"`.
103    pub star_exports: Vec<usize>,
104    /// `[[HasTLA]]`: an `await` (or `for await`) outside any function.
105    pub has_tla: bool,
106}
107
108fn syntax(msg: impl std::fmt::Display) -> String {
109    format!("SyntaxError: {msg}")
110}
111
112/// The names a statement list declares lexically at its own level (let,
113/// const, class, and — in strict code — function declarations).
114fn lexical_names(stmts: &[Stmt], out: &mut Vec<String>) {
115    for s in stmts {
116        match &s.kind {
117            StmtKind::Decl { kind, decls } if *kind != DeclKind::Var => {
118                for d in decls {
119                    crate::compiler::pattern_names(&d.target, out);
120                }
121            }
122            StmtKind::ClassDecl(c) => out.extend(c.name.clone()),
123            StmtKind::FuncDecl { name, .. } => out.push(name.clone()),
124            _ => {}
125        }
126    }
127}
128
129/// Every name a function body binds at its top: its `var`s (hoisted through
130/// blocks) and its own lexical declarations.
131fn body_names(stmts: &[Stmt], out: &mut Vec<String>) {
132    for s in stmts {
133        crate::compiler::collect_var_names(s, out);
134    }
135    lexical_names(stmts, out);
136}
137
138fn add_request(info: &mut ModuleInfo, spec: &str, attrs: &[(String, String)]) -> usize {
139    if let Some(i) = info
140        .requests
141        .iter()
142        .position(|(s, a)| s == spec && a.as_slice() == attrs)
143    {
144        return i;
145    }
146    info.requests.push((spec.to_string(), attrs.to_vec()));
147    info.requests.len() - 1
148}
149
150/// ParseModule's static semantics for `stmts` (16.2.1.6.1), plus the module
151/// early errors (16.2.1.1).
152pub fn analyze(stmts: &[Stmt]) -> Result<ModuleInfo, String> {
153    let mut info = ModuleInfo::default();
154    // Declared names of the module scope, for the export/import checks.
155    let mut declared: Vec<String> = Vec::new();
156    for s in stmts {
157        match &s.kind {
158            StmtKind::Export(ExportDecl::Decl(d))
159            | StmtKind::Export(ExportDecl::DefaultDecl(d)) => {
160                crate::compiler::collect_var_names(d, &mut declared);
161                lexical_names(std::slice::from_ref(&**d), &mut declared);
162            }
163            StmtKind::Export(_) | StmtKind::Import(_) => {}
164            _ => {
165                crate::compiler::collect_var_names(s, &mut declared);
166                lexical_names(std::slice::from_ref(s), &mut declared);
167            }
168        }
169    }
170    // Import entries first: an `export { x }` of an imported `x` re-exports it.
171    for s in stmts {
172        if let StmtKind::Import(d) = &s.kind {
173            let req = add_request(&mut info, &d.specifier, &d.attributes);
174            for spec in &d.specs {
175                let (import_name, local) = match spec {
176                    ImportSpec::Default(l) => (Some("default".to_string()), l.clone()),
177                    ImportSpec::Namespace(l) => (None, l.clone()),
178                    ImportSpec::Named { imported, local } => {
179                        (Some(imported.clone()), local.clone())
180                    }
181                };
182                if declared.contains(&local) || info.imports.iter().any(|e| e.local == local) {
183                    return Err(syntax(format!(
184                        "Identifier '{local}' has already been declared"
185                    )));
186                }
187                info.imports.push(ImportEntry {
188                    request: req,
189                    import_name,
190                    local,
191                    clause: d.clause,
192                });
193            }
194        }
195    }
196    // Two `export default` declarations both bind `*default*`, which V8
197    // reports as a redeclaration of its internal name.
198    let mut default_seen = false;
199    let default_decl = |seen: &mut bool| -> Result<(), String> {
200        if std::mem::replace(seen, true) {
201            return Err(syntax("Identifier '.default' has already been declared"));
202        }
203        Ok(())
204    };
205    let mut exported: Vec<String> = Vec::new();
206    let mut note_export = |name: &str| -> Result<(), String> {
207        if exported.iter().any(|e| e == name) {
208            return Err(syntax(format!("Duplicate export of '{name}'")));
209        }
210        exported.push(name.to_string());
211        Ok(())
212    };
213    for s in stmts {
214        let StmtKind::Export(e) = &s.kind else {
215            continue;
216        };
217        match e {
218            ExportDecl::Decl(d) => {
219                let mut names = Vec::new();
220                crate::compiler::collect_var_names(d, &mut names);
221                lexical_names(std::slice::from_ref(&**d), &mut names);
222                for n in names {
223                    note_export(&n)?;
224                    info.local_exports.push((n.clone(), n));
225                }
226            }
227            ExportDecl::DefaultDecl(d) => {
228                default_decl(&mut default_seen)?;
229                note_export("default")?;
230                let mut names = Vec::new();
231                lexical_names(std::slice::from_ref(&**d), &mut names);
232                let local = names.pop().unwrap_or_else(|| "default".to_string());
233                info.local_exports.push(("default".into(), local));
234            }
235            ExportDecl::DefaultExpr(_) => {
236                default_decl(&mut default_seen)?;
237                note_export("default")?;
238                info.local_exports
239                    .push(("default".into(), "default".into()));
240            }
241            ExportDecl::Named {
242                specs, from: None, ..
243            } => {
244                for sp in specs {
245                    note_export(&sp.exported)?;
246                    match info.imports.iter().find(|i| i.local == sp.local) {
247                        // Re-exporting a named import is an indirect export of
248                        // the binding it imports; a namespace import is a local
249                        // binding of its own (16.2.1.6.1 step 10.a).
250                        Some(ImportEntry {
251                            request,
252                            import_name: Some(name),
253                            ..
254                        }) => info.indirect_exports.push(IndirectExport {
255                            export_name: sp.exported.clone(),
256                            request: *request,
257                            import_name: Some(name.clone()),
258                        }),
259                        Some(_) => info
260                            .local_exports
261                            .push((sp.exported.clone(), sp.local.clone())),
262                        None if declared.contains(&sp.local) => info
263                            .local_exports
264                            .push((sp.exported.clone(), sp.local.clone())),
265                        None => {
266                            return Err(syntax(format!(
267                                "Export '{}' is not defined in module",
268                                sp.local
269                            )))
270                        }
271                    }
272                }
273            }
274            ExportDecl::Named {
275                specs,
276                from: Some(from),
277                attributes,
278            } => {
279                let req = add_request(&mut info, from, attributes);
280                for sp in specs {
281                    note_export(&sp.exported)?;
282                    info.indirect_exports.push(IndirectExport {
283                        export_name: sp.exported.clone(),
284                        request: req,
285                        import_name: Some(sp.local.clone()),
286                    });
287                }
288            }
289            ExportDecl::Star {
290                alias,
291                from,
292                attributes,
293            } => {
294                let req = add_request(&mut info, from, attributes);
295                match alias {
296                    Some(a) => {
297                        note_export(a)?;
298                        info.indirect_exports.push(IndirectExport {
299                            export_name: a.clone(),
300                            request: req,
301                            import_name: None,
302                        });
303                    }
304                    None => info.star_exports.push(req),
305                }
306            }
307        }
308    }
309    info.has_tla = stmts.iter().any(stmt_has_tla);
310    Ok(info)
311}
312
313/// Whether evaluating `s` at the module top level can `await` — an `await`
314/// or `for await` that is not inside a nested function.
315fn stmt_has_tla(s: &Stmt) -> bool {
316    let mut found = false;
317    let mut probe = AwaitProbe { found: &mut found };
318    probe.stmt(s);
319    found
320}
321
322struct AwaitProbe<'a> {
323    found: &'a mut bool,
324}
325
326impl AwaitProbe<'_> {
327    fn stmt(&mut self, s: &Stmt) {
328        if *self.found {
329            return;
330        }
331        match &s.kind {
332            StmtKind::ForOf { is_await: true, .. } => *self.found = true,
333            StmtKind::FuncDecl { .. } => {}
334            _ => walk_stmt_children(s, &mut |n| match n {
335                Node::S(st) => self.stmt(st),
336                Node::E(e) => self.expr(e),
337            }),
338        }
339    }
340    fn expr(&mut self, e: &Expr) {
341        if *self.found {
342            return;
343        }
344        match e {
345            Expr::Await(..) => *self.found = true,
346            // A nested function's `await` belongs to it.
347            Expr::Function { .. } => {}
348            // Class bodies are functions too, but a computed key or the
349            // heritage runs in the enclosing scope.
350            Expr::Class(c) => self.class_outer(c),
351            _ => walk_expr_children(e, &mut |x| self.expr(x)),
352        }
353    }
354    fn class_outer(&mut self, c: &ClassNode) {
355        if let Some(p) = &c.parent {
356            self.expr(p);
357        }
358        for m in &c.members {
359            if m.computed {
360                self.expr(&m.key);
361            }
362        }
363    }
364}
365
366/// Visit the direct child statements and expressions of `s` (read-only).
367/// A child of a statement, as [`walk_stmt_children`] hands it over.
368enum Node<'a> {
369    S(&'a Stmt),
370    E(&'a Expr),
371}
372
373fn walk_stmt_children<'a>(s: &'a Stmt, f: &mut dyn FnMut(Node<'a>)) {
374    match &s.kind {
375        StmtKind::Expr(e) | StmtKind::Throw(e) => f(Node::E(e)),
376        StmtKind::Return(e) => e.iter().for_each(|e| f(Node::E(e))),
377        StmtKind::Decl { decls, .. } => {
378            for d in decls {
379                f(Node::E(&d.target));
380                if let Some(i) = &d.init {
381                    f(Node::E(i));
382                }
383            }
384        }
385        StmtKind::Block(b) => b.iter().for_each(|s| f(Node::S(s))),
386        StmtKind::FuncDecl { .. }
387        | StmtKind::Break(_)
388        | StmtKind::Continue(_)
389        | StmtKind::Empty => {}
390        StmtKind::ClassDecl(c) => {
391            if let Some(p) = &c.parent {
392                f(Node::E(p));
393            }
394            for m in &c.members {
395                if m.computed {
396                    f(Node::E(&m.key));
397                }
398            }
399        }
400        StmtKind::If { test, cons, alt } => {
401            f(Node::E(test));
402            f(Node::S(cons));
403            if let Some(a) = alt {
404                f(Node::S(a));
405            }
406        }
407        StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
408            f(Node::E(test));
409            f(Node::S(body));
410        }
411        StmtKind::With { object, body } => {
412            f(Node::E(object));
413            f(Node::S(body));
414        }
415        StmtKind::For {
416            init,
417            test,
418            update,
419            body,
420        } => {
421            if let Some(i) = init {
422                f(Node::S(i));
423            }
424            test.iter().for_each(|e| f(Node::E(e)));
425            update.iter().for_each(|e| f(Node::E(e)));
426            f(Node::S(body));
427        }
428        StmtKind::ForOf {
429            target, iter, body, ..
430        } => {
431            f(Node::E(target));
432            f(Node::E(iter));
433            f(Node::S(body));
434        }
435        StmtKind::ForIn {
436            target,
437            object,
438            body,
439            ..
440        } => {
441            f(Node::E(target));
442            f(Node::E(object));
443            f(Node::S(body));
444        }
445        StmtKind::Switch { disc, cases } => {
446            f(Node::E(disc));
447            for c in cases {
448                c.test.iter().for_each(|e| f(Node::E(e)));
449                c.body.iter().for_each(|s| f(Node::S(s)));
450            }
451        }
452        StmtKind::Labeled { body, .. } => f(Node::S(body)),
453        StmtKind::Try {
454            block,
455            handler,
456            finalizer,
457        } => {
458            block.iter().for_each(|s| f(Node::S(s)));
459            if let Some((p, b)) = handler {
460                p.iter().for_each(|e| f(Node::E(e)));
461                b.iter().for_each(|s| f(Node::S(s)));
462            }
463            if let Some(fin) = finalizer {
464                fin.iter().for_each(|s| f(Node::S(s)));
465            }
466        }
467        StmtKind::Import(_) => {}
468        StmtKind::Export(e) => match e {
469            ExportDecl::Decl(d) | ExportDecl::DefaultDecl(d) => f(Node::S(d)),
470            ExportDecl::DefaultExpr(x) => f(Node::E(x)),
471            _ => {}
472        },
473    }
474}
475
476/// Visit the direct child expressions of `e` (read-only, not into bodies of
477/// nested functions' statements).
478fn walk_expr_children(e: &Expr, ex: &mut dyn FnMut(&Expr)) {
479    match e {
480        Expr::Template { exprs, .. } => exprs.iter().for_each(&mut *ex),
481        Expr::TaggedTemplate { tag, exprs, .. } => {
482            ex(tag);
483            exprs.iter().for_each(&mut *ex);
484        }
485        Expr::Yield { arg, .. } => arg.iter().for_each(|x| ex(x)),
486        Expr::Await(x, _) | Expr::Spread(x) | Expr::Unary(_, x) => ex(x),
487        Expr::Array(items) | Expr::Sequence(items) => items.iter().for_each(&mut *ex),
488        Expr::Object(props) => {
489            for p in props {
490                match p {
491                    Prop::KeyValue {
492                        key,
493                        value,
494                        computed,
495                    } => {
496                        if *computed {
497                            ex(key);
498                        }
499                        ex(value);
500                    }
501                    Prop::Spread(x) => ex(x),
502                    Prop::Accessor { key, computed, .. } => {
503                        if *computed {
504                            ex(key);
505                        }
506                    }
507                }
508            }
509        }
510        Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => {
511            ex(l);
512            ex(r);
513        }
514        Expr::Conditional { test, cons, alt } => {
515            ex(test);
516            ex(cons);
517            ex(alt);
518        }
519        Expr::Assign { target, value, .. } => {
520            ex(target);
521            ex(value);
522        }
523        Expr::Update { target, .. } => ex(target),
524        Expr::Call { func, args, .. } => {
525            ex(func);
526            args.iter().for_each(&mut *ex);
527        }
528        Expr::New { callee, args, .. } => {
529            ex(callee);
530            args.iter().for_each(&mut *ex);
531        }
532        Expr::Member { object, .. } => ex(object),
533        Expr::Index { object, index, .. } => {
534            ex(object);
535            ex(index);
536        }
537        Expr::Class(_) | Expr::Function { .. } => {}
538        Expr::Null
539        | Expr::Undefined
540        | Expr::True
541        | Expr::False
542        | Expr::Number(_)
543        | Expr::BigInt(_)
544        | Expr::Regex(..)
545        | Expr::Str(_)
546        | Expr::Ident(_)
547        | Expr::This
548        | Expr::Super
549        | Expr::NewTarget
550        | Expr::Hole => {}
551    }
552}
553
554// ── lowering ────────────────────────────────────────────────────────────────
555
556/// `(() => { throw new TypeError("Assignment to constant variable."); })()` —
557/// what a write to an import binding becomes (SetMutableBinding on an
558/// immutable binding, 9.1.1.5.5 / 9.1.1.1.5).
559fn const_assignment_throw() -> Expr {
560    let throw = Stmt::from(StmtKind::Throw(Expr::New {
561        callee: Box::new(Expr::Ident("TypeError".into())),
562        args: vec![Expr::Str("Assignment to constant variable.".into())],
563        pos: 0,
564    }));
565    Expr::Call {
566        func: Box::new(arrow(FnBody::Block(vec![throw]))),
567        args: Vec::new(),
568        optional: false,
569        pos: 0,
570    }
571}
572
573/// `({ set v(_) { throw new TypeError("Assignment to constant variable.") } }).v`
574/// — a reference to stand in for an import binding as a destructuring or
575/// `for`-head target: writing it throws what writing the binding must.
576fn const_assignment_target() -> Expr {
577    let Expr::Call { func, .. } = const_assignment_throw() else {
578        unreachable!("const_assignment_throw builds a call")
579    };
580    let Expr::Function { body, .. } = *func else {
581        unreachable!("the callee is an arrow")
582    };
583    let setter = Expr::Function {
584        params: vec![Param {
585            pattern: Expr::Ident("_".into()),
586            default: None,
587            rest: false,
588        }],
589        body,
590        is_arrow: false,
591        name: None,
592        is_generator: false,
593        is_async: false,
594        is_method: true,
595        span: (0, 0),
596    };
597    Expr::Member {
598        object: Box::new(Expr::Object(vec![Prop::Accessor {
599            key: Expr::Str("v".into()),
600            computed: false,
601            is_getter: false,
602            func: setter,
603        }])),
604        property: "v".into(),
605        optional: false,
606        pos: 0,
607    }
608}
609
610fn arrow(body: FnBody) -> Expr {
611    Expr::Function {
612        params: Vec::new(),
613        body,
614        is_arrow: true,
615        name: None,
616        is_generator: false,
617        is_async: false,
618        is_method: false,
619        span: (0, 0),
620    }
621}
622
623/// Rewrites one module body: import references, `import.meta`, `import(…)`,
624/// and free CommonJS names, honouring every nested scope that shadows them.
625struct Rewriter<'a> {
626    /// Import local name → its index in `%imp`.
627    imports: HashMap<String, usize>,
628    /// The CommonJS wrapper names the module does not itself declare.
629    cjs_free: Vec<&'static str>,
630    /// Names bound by the scopes enclosing the current point, innermost last.
631    scopes: Vec<HashSet<String>>,
632    referrer: &'a str,
633}
634
635impl Rewriter<'_> {
636    fn shadowed(&self, n: &str) -> bool {
637        self.scopes.iter().any(|s| s.contains(n))
638    }
639    fn import_index(&self, n: &str) -> Option<usize> {
640        self.imports.get(n).copied().filter(|_| !self.shadowed(n))
641    }
642    fn import_read(k: usize) -> Expr {
643        Expr::Call {
644            func: Box::new(Expr::Index {
645                object: Box::new(Expr::Ident(IMP.into())),
646                index: Box::new(Expr::Number(k as f64)),
647                optional: false,
648                pos: 0,
649            }),
650            args: Vec::new(),
651            optional: false,
652            pos: 0,
653        }
654    }
655    fn with_scope<T>(&mut self, names: Vec<String>, f: impl FnOnce(&mut Self) -> T) -> T {
656        self.scopes.push(names.into_iter().collect());
657        let out = f(self);
658        self.scopes.pop();
659        out
660    }
661    fn stmts(&mut self, stmts: &mut [Stmt]) {
662        for s in stmts {
663            self.stmt(s);
664        }
665    }
666
667    fn block(&mut self, stmts: &mut [Stmt]) {
668        let mut names = Vec::new();
669        lexical_names(stmts, &mut names);
670        self.with_scope(names, |r| r.stmts(stmts));
671    }
672
673    fn stmt(&mut self, s: &mut Stmt) {
674        match &mut s.kind {
675            StmtKind::Expr(e) | StmtKind::Throw(e) => self.expr(e),
676            StmtKind::Return(e) => {
677                if let Some(e) = e {
678                    self.expr(e);
679                }
680            }
681            StmtKind::Decl { decls, .. } => {
682                for d in decls {
683                    self.binding_pattern(&mut d.target);
684                    if let Some(i) = &mut d.init {
685                        self.expr(i);
686                    }
687                }
688            }
689            StmtKind::Block(b) => self.block(b),
690            StmtKind::FuncDecl { params, body, .. } => self.function(params, body, None, false),
691            StmtKind::ClassDecl(c) => self.class(c),
692            StmtKind::If { test, cons, alt } => {
693                self.expr(test);
694                self.stmt(cons);
695                if let Some(a) = alt {
696                    self.stmt(a);
697                }
698            }
699            StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
700                self.expr(test);
701                self.stmt(body);
702            }
703            StmtKind::With { object, body } => {
704                self.expr(object);
705                self.stmt(body);
706            }
707            StmtKind::For {
708                init,
709                test,
710                update,
711                body,
712            } => {
713                let mut names = Vec::new();
714                if let Some(i) = init {
715                    lexical_names(std::slice::from_ref(&**i), &mut names);
716                }
717                self.with_scope(names, |r| {
718                    if let Some(i) = init {
719                        r.stmt(i);
720                    }
721                    if let Some(t) = test {
722                        r.expr(t);
723                    }
724                    if let Some(u) = update {
725                        r.expr(u);
726                    }
727                    r.stmt(body);
728                });
729            }
730            StmtKind::ForOf {
731                decl_kind,
732                target,
733                iter,
734                body,
735                ..
736            }
737            | StmtKind::ForIn {
738                decl_kind,
739                target,
740                object: iter,
741                body,
742                ..
743            } => {
744                let mut names = Vec::new();
745                if matches!(decl_kind, Some(DeclKind::Let) | Some(DeclKind::Const)) {
746                    crate::compiler::pattern_names(target, &mut names);
747                }
748                let declares = decl_kind.is_some();
749                self.with_scope(names, |r| {
750                    r.expr(iter);
751                    if declares {
752                        r.binding_pattern(target);
753                    } else {
754                        r.assignment_pattern(target);
755                    }
756                    r.stmt(body);
757                });
758            }
759            StmtKind::Switch { disc, cases } => {
760                self.expr(disc);
761                let mut names = Vec::new();
762                for c in cases.iter() {
763                    lexical_names(&c.body, &mut names);
764                }
765                self.with_scope(names, |r| {
766                    for c in cases {
767                        if let Some(t) = &mut c.test {
768                            r.expr(t);
769                        }
770                        r.stmts(&mut c.body);
771                    }
772                });
773            }
774            StmtKind::Labeled { body, .. } => self.stmt(body),
775            StmtKind::Try {
776                block,
777                handler,
778                finalizer,
779            } => {
780                self.block(block);
781                if let Some((param, body)) = handler {
782                    let mut names = Vec::new();
783                    if let Some(p) = param {
784                        crate::compiler::pattern_names(p, &mut names);
785                    }
786                    lexical_names(body, &mut names);
787                    self.with_scope(names, |r| {
788                        if let Some(p) = param {
789                            r.binding_pattern(p);
790                        }
791                        r.stmts(body);
792                    });
793                }
794                if let Some(f) = finalizer {
795                    self.block(f);
796                }
797            }
798            StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Empty => {}
799            StmtKind::Import(_) | StmtKind::Export(_) => {}
800        }
801    }
802
803    /// A function's parameters and body, in a scope binding its parameters,
804    /// its `var`s and top-level declarations, its own name (a named function
805    /// expression) and, unless it is an arrow, `arguments`.
806    fn function(
807        &mut self,
808        params: &mut [Param],
809        body: &mut [Stmt],
810        own: Option<&str>,
811        arrow: bool,
812    ) {
813        let mut names: Vec<String> = own.map(str::to_string).into_iter().collect();
814        if !arrow {
815            names.push("arguments".into());
816        }
817        for p in params.iter() {
818            crate::compiler::pattern_names(&p.pattern, &mut names);
819        }
820        body_names(body, &mut names);
821        self.with_scope(names, |r| {
822            for p in params.iter_mut() {
823                r.binding_pattern(&mut p.pattern);
824                if let Some(d) = &mut p.default {
825                    r.expr(d);
826                }
827            }
828            r.stmts(body);
829        });
830    }
831
832    fn class(&mut self, c: &mut ClassNode) {
833        let names: Vec<String> = c.name.clone().into_iter().collect();
834        self.with_scope(names, |r| {
835            if let Some(p) = &mut c.parent {
836                r.expr(p);
837            }
838            for m in &mut c.members {
839                if m.computed {
840                    r.expr(&mut m.key);
841                }
842                match m.kind {
843                    MemberKind::Field => {
844                        if let Some(i) = &mut m.field_init {
845                            r.with_scope(vec!["arguments".into()], |r| r.expr(i));
846                        }
847                    }
848                    _ => r.function(&mut m.params, &mut m.body, None, false),
849                }
850            }
851        });
852    }
853
854    /// A declaration target: its names are bindings, but default values and
855    /// computed keys inside it are expressions.
856    fn binding_pattern(&mut self, target: &mut Expr) {
857        match target {
858            Expr::Ident(_) => {}
859            Expr::Array(items) => items.iter_mut().for_each(|i| self.binding_pattern(i)),
860            Expr::Object(props) => {
861                for p in props {
862                    match p {
863                        Prop::KeyValue {
864                            key,
865                            value,
866                            computed,
867                        } => {
868                            if *computed {
869                                self.expr(key);
870                            }
871                            self.binding_pattern(value);
872                        }
873                        Prop::Spread(e) => self.binding_pattern(e),
874                        Prop::Accessor { .. } => {}
875                    }
876                }
877            }
878            Expr::Assign { target, value, .. } => {
879                self.binding_pattern(target);
880                self.expr(value);
881            }
882            Expr::Spread(inner) => self.binding_pattern(inner),
883            other => self.expr(other),
884        }
885    }
886
887    /// An assignment target pattern: member targets and defaults are
888    /// expressions; a plain name is a reference (checked by the caller).
889    fn assignment_pattern(&mut self, target: &mut Expr) {
890        match target {
891            // An import binding inside a destructuring target or a `for`
892            // head is written through a reference whose PutValue throws, so
893            // the elements before it are still assigned, in order.
894            Expr::Ident(n) if self.import_index(n).is_some() => *target = const_assignment_target(),
895            Expr::Ident(_) => self.expr(target),
896            Expr::Array(items) => items.iter_mut().for_each(|i| self.assignment_pattern(i)),
897            Expr::Object(props) => {
898                for p in props {
899                    match p {
900                        Prop::KeyValue {
901                            key,
902                            value,
903                            computed,
904                        } => {
905                            if *computed {
906                                self.expr(key);
907                            }
908                            self.assignment_pattern(value);
909                        }
910                        Prop::Spread(e) => self.assignment_pattern(e),
911                        Prop::Accessor { .. } => {}
912                    }
913                }
914            }
915            Expr::Assign { target, value, .. } => {
916                self.assignment_pattern(target);
917                self.expr(value);
918            }
919            Expr::Spread(inner) => self.assignment_pattern(inner),
920            other => self.expr(other),
921        }
922    }
923
924    fn expr(&mut self, e: &mut Expr) {
925        match e {
926            Expr::Ident(n) => {
927                if let Some(k) = self.import_index(n) {
928                    *e = Self::import_read(k);
929                } else if self.cjs_free.contains(&n.as_str()) && !self.shadowed(n) {
930                    *n = format!("{CJS_FREE_PREFIX}{n}");
931                }
932            }
933            Expr::Member {
934                object, property, ..
935            } if matches!(&**object, Expr::Ident(i) if i == "import") && property == "meta" => {
936                *e = Expr::Ident(META.into());
937            }
938            Expr::Call { func, args, .. } if matches!(&**func, Expr::Ident(i) if i == "import") => {
939                for a in args.iter_mut() {
940                    self.expr(a);
941                }
942                let mut full = Vec::with_capacity(3);
943                let mut it = std::mem::take(args).into_iter();
944                full.push(it.next().unwrap_or(Expr::Undefined));
945                full.push(Expr::Str(self.referrer.to_string()));
946                full.extend(it.next());
947                *e = Expr::Call {
948                    func: Box::new(Expr::Ident(IMPORT_FN.into())),
949                    args: full,
950                    optional: false,
951                    pos: 0,
952                };
953            }
954            Expr::Assign { target, op, value } => {
955                let hits = matches!(&**target, Expr::Ident(n) if self.import_index(n).is_some());
956                if !hits {
957                    // A plain name that is not an import is still rewritten
958                    // when it is a free CommonJS name (`exports = …`).
959                    if matches!(&**target, Expr::Array(_) | Expr::Object(_)) {
960                        self.assignment_pattern(target);
961                    } else {
962                        self.expr(target);
963                    }
964                    self.expr(value);
965                    return;
966                }
967                self.expr(value);
968                let value = std::mem::replace(&mut **value, Expr::Undefined);
969                let throw = const_assignment_throw();
970                *e = match (op.as_ref(), &**target) {
971                    // `x ||= v` only writes when the test lets it through.
972                    (Some(AssignOp::Logical(lop)), Expr::Ident(n)) => {
973                        let read = Self::import_read(self.import_index(n).unwrap_or(0));
974                        Expr::Logical(
975                            *lop,
976                            Box::new(read),
977                            Box::new(Expr::Sequence(vec![value, throw])),
978                        )
979                    }
980                    (Some(AssignOp::Binary(bop)), Expr::Ident(n)) => {
981                        let read = Self::import_read(self.import_index(n).unwrap_or(0));
982                        Expr::Sequence(vec![
983                            Expr::Binary(*bop, Box::new(read), Box::new(value)),
984                            throw,
985                        ])
986                    }
987                    _ => Expr::Sequence(vec![value, throw]),
988                };
989            }
990            Expr::Update { target, .. } => {
991                if let Expr::Ident(n) = &**target {
992                    if let Some(k) = self.import_index(n) {
993                        let read = Expr::Unary(UnOp::Pos, Box::new(Self::import_read(k)));
994                        *e = Expr::Sequence(vec![read, const_assignment_throw()]);
995                        return;
996                    }
997                }
998                self.expr(target);
999            }
1000            Expr::Function {
1001                params,
1002                body,
1003                is_arrow,
1004                name,
1005                ..
1006            } => {
1007                let arrow = *is_arrow;
1008                let own = name.clone();
1009                match body {
1010                    FnBody::Block(b) => self.function(params, b, own.as_deref(), arrow),
1011                    FnBody::Expr(x) => {
1012                        let mut stmts = Vec::new();
1013                        self.function(params, &mut stmts, own.as_deref(), arrow);
1014                        let mut names: Vec<String> = Vec::new();
1015                        for p in params.iter() {
1016                            crate::compiler::pattern_names(&p.pattern, &mut names);
1017                        }
1018                        if !arrow {
1019                            names.push("arguments".into());
1020                        }
1021                        self.with_scope(names, |r| r.expr(x));
1022                    }
1023                }
1024            }
1025            Expr::Class(c) => self.class(c),
1026            Expr::Object(props) => {
1027                for p in props {
1028                    match p {
1029                        Prop::KeyValue {
1030                            key,
1031                            value,
1032                            computed,
1033                        } => {
1034                            if *computed {
1035                                self.expr(key);
1036                            }
1037                            self.expr(value);
1038                        }
1039                        Prop::Spread(x) => self.expr(x),
1040                        Prop::Accessor {
1041                            key,
1042                            computed,
1043                            func,
1044                            ..
1045                        } => {
1046                            if *computed {
1047                                self.expr(key);
1048                            }
1049                            self.expr(func);
1050                        }
1051                    }
1052                }
1053            }
1054            Expr::Template { exprs, .. } => exprs.iter_mut().for_each(|x| self.expr(x)),
1055            Expr::TaggedTemplate { tag, exprs, .. } => {
1056                self.expr(tag);
1057                exprs.iter_mut().for_each(|x| self.expr(x));
1058            }
1059            Expr::Yield { arg, .. } => {
1060                if let Some(a) = arg {
1061                    self.expr(a);
1062                }
1063            }
1064            Expr::Await(x, _) | Expr::Spread(x) | Expr::Unary(_, x) => self.expr(x),
1065            Expr::Array(items) | Expr::Sequence(items) => {
1066                items.iter_mut().for_each(|x| self.expr(x))
1067            }
1068            Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => {
1069                self.expr(l);
1070                self.expr(r);
1071            }
1072            Expr::Conditional { test, cons, alt } => {
1073                self.expr(test);
1074                self.expr(cons);
1075                self.expr(alt);
1076            }
1077            Expr::Call { func, args, .. } => {
1078                self.expr(func);
1079                args.iter_mut().for_each(|x| self.expr(x));
1080            }
1081            Expr::New { callee, args, .. } => {
1082                self.expr(callee);
1083                args.iter_mut().for_each(|x| self.expr(x));
1084            }
1085            Expr::Member { object, .. } => self.expr(object),
1086            Expr::Index { object, index, .. } => {
1087                self.expr(object);
1088                self.expr(index);
1089            }
1090            Expr::Null
1091            | Expr::Undefined
1092            | Expr::True
1093            | Expr::False
1094            | Expr::Number(_)
1095            | Expr::BigInt(_)
1096            | Expr::Regex(..)
1097            | Expr::Str(_)
1098            | Expr::This
1099            | Expr::Super
1100            | Expr::NewTarget
1101            | Expr::Hole => {}
1102        }
1103    }
1104}
1105
1106/// Lower a parsed module body (see the module docs) to the function
1107/// expression the loader instantiates. `referrer` is the module's filename,
1108/// which every `import(…)` in it resolves against; `generator` selects the
1109/// form a module in an import cycle needs.
1110pub fn lower(stmts: Vec<Stmt>, info: &ModuleInfo, referrer: &str, generator: bool) -> Expr {
1111    let mut body: Vec<Stmt> = Vec::with_capacity(stmts.len() + 2);
1112    for s in stmts {
1113        let line = s.line;
1114        match s.kind {
1115            StmtKind::Import(_) => {}
1116            StmtKind::Export(ExportDecl::Decl(d))
1117            | StmtKind::Export(ExportDecl::DefaultDecl(d)) => body.push(*d),
1118            // `export default <expr>` binds the expression's value to the
1119            // `*default*` binding (spelled `default`, which no source name can
1120            // reach), and an anonymous function or class is named "default".
1121            StmtKind::Export(ExportDecl::DefaultExpr(e)) => body.push(Stmt::new(
1122                StmtKind::Decl {
1123                    kind: DeclKind::Const,
1124                    decls: vec![Declarator {
1125                        target: Expr::Ident("default".into()),
1126                        init: Some(e),
1127                        bound: Vec::new(),
1128                    }],
1129                },
1130                line,
1131            )),
1132            StmtKind::Export(_) => {}
1133            other => body.push(Stmt::new(other, line)),
1134        }
1135    }
1136    let mut declared = Vec::new();
1137    body_names(&body, &mut declared);
1138    let mut rw = Rewriter {
1139        imports: info
1140            .imports
1141            .iter()
1142            .enumerate()
1143            .map(|(k, e)| (e.local.clone(), k))
1144            .collect(),
1145        cjs_free: CJS_NAMES
1146            .iter()
1147            .copied()
1148            .filter(|n| !declared.iter().any(|d| d == n))
1149            .collect(),
1150        scopes: Vec::new(),
1151        referrer,
1152    };
1153    rw.stmts(&mut body);
1154    // The getter for each local export, in `local_exports` order. A getter of
1155    // a re-exported namespace import reads through `%imp` like any reference.
1156    let getters: Vec<Expr> = info
1157        .local_exports
1158        .iter()
1159        .map(|(_, local)| {
1160            let mut read = Expr::Ident(local.clone());
1161            rw.expr(&mut read);
1162            arrow(FnBody::Expr(Box::new(read)))
1163        })
1164        .collect();
1165    let mut prologue = vec![Stmt::from(StmtKind::Expr(Expr::Call {
1166        func: Box::new(Expr::Ident(REG.into())),
1167        args: vec![Expr::Array(getters)],
1168        optional: false,
1169        pos: 0,
1170    }))];
1171    if generator {
1172        prologue.push(Stmt::from(StmtKind::Expr(Expr::Yield {
1173            arg: None,
1174            delegate: false,
1175        })));
1176    }
1177    prologue.extend(body);
1178    let param = |n: &str| Param {
1179        pattern: Expr::Ident(n.into()),
1180        default: None,
1181        rest: false,
1182    };
1183    Expr::Function {
1184        params: vec![param(IMP), param(META), param(REG)],
1185        body: FnBody::Block(prologue),
1186        is_arrow: false,
1187        name: None,
1188        is_generator: generator,
1189        is_async: info.has_tla,
1190        is_method: false,
1191        span: (0, 0),
1192    }
1193}
1194
1195// ── format detection ────────────────────────────────────────────────────────
1196
1197/// The script-goal parse errors that only module syntax produces. Node's
1198/// syntax detection (`containsModuleSyntax`) runs a source with no declared
1199/// format as an ES module exactly when its CommonJS parse fails with one of
1200/// these and its module parse succeeds.
1201const MODULE_ONLY_ERRORS: &[&str] = &[
1202    "SyntaxError: Cannot use import statement outside a module",
1203    "SyntaxError: Unexpected token 'export'",
1204    "SyntaxError: Cannot use 'import.meta' outside a module",
1205    "SyntaxError: await is only valid in async functions and the top level bodies of modules",
1206];
1207
1208/// Node's syntax detection, given the error the CommonJS (script-goal)
1209/// compile of `src` failed with: the source is an ES module when module
1210/// syntax explains that error and the module-goal parse succeeds.
1211///
1212/// A top-level `await` is recognised by its token rather than by V8's exact
1213/// message, because where an `await` operand sits decides which message a
1214/// script parse reports (`f(await x)` is "missing ) after argument list").
1215pub fn detect_module(src: &str, script_err: &str) -> bool {
1216    let explained = MODULE_ONLY_ERRORS.iter().any(|m| script_err.starts_with(m))
1217        || script_err.starts_with("SyntaxError") && src.contains("await");
1218    explained && crate::parser::parse_module(src).is_ok()
1219}
1220
1221/// Node's syntax detection for a source of undeclared format.
1222pub fn has_module_syntax(src: &str) -> bool {
1223    match crate::parser::parse(src) {
1224        Ok(_) => false,
1225        Err(e) => detect_module(src, &e),
1226    }
1227}
1228
1229/// What a resolved module is (node's `defaultLoad` formats).
1230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1231pub enum Format {
1232    Module,
1233    CommonJs,
1234    Json,
1235    Builtin,
1236}
1237
1238impl Format {
1239    fn name(self) -> &'static str {
1240        match self {
1241            Format::Module => "module",
1242            Format::CommonJs => "commonjs",
1243            Format::Json => "json",
1244            Format::Builtin => "builtin",
1245        }
1246    }
1247}
1248
1249thread_local! {
1250    /// `package.json` path → its parsed contents (`None` when unreadable or
1251    /// not JSON), read once per process like node's package-json cache.
1252    static PACKAGE_JSON: std::cell::RefCell<HashMap<PathBuf, Option<serde_json::Value>>> =
1253        std::cell::RefCell::new(HashMap::new());
1254}
1255
1256fn read_package_json(path: &Path) -> Option<serde_json::Value> {
1257    if let Some(hit) = PACKAGE_JSON.with(|c| c.borrow().get(path).cloned()) {
1258        return hit;
1259    }
1260    let parsed = std::fs::read_to_string(path)
1261        .ok()
1262        .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok());
1263    PACKAGE_JSON.with(|c| c.borrow_mut().insert(path.to_path_buf(), parsed.clone()));
1264    parsed
1265}
1266
1267/// The nearest `package.json` at or above `dir` (`GetPackageScopeConfig`),
1268/// stopping at a `node_modules` boundary.
1269fn package_scope(dir: &Path) -> Option<serde_json::Value> {
1270    package_scope_file(dir).and_then(|pj| read_package_json(&pj))
1271}
1272
1273/// The path of the nearest `package.json` at or above `dir`.
1274fn package_scope_file(dir: &Path) -> Option<PathBuf> {
1275    let mut cur = Some(dir);
1276    while let Some(d) = cur {
1277        let pj = d.join("package.json");
1278        if pj.is_file() {
1279            return Some(pj);
1280        }
1281        if d.file_name().is_some_and(|n| n == "node_modules") {
1282            return None;
1283        }
1284        cur = d.parent();
1285    }
1286    None
1287}
1288
1289/// The format `path` DECLARES — by extension or its package scope's
1290/// `"type"` — or `None` when only its syntax can tell.
1291pub fn file_format_declared(path: &Path) -> Option<Format> {
1292    match path.extension().and_then(|e| e.to_str()) {
1293        Some("mjs") => return Some(Format::Module),
1294        Some("cjs") => return Some(Format::CommonJs),
1295        Some("json") => return Some(Format::Json),
1296        _ => {}
1297    }
1298    let scope_type = path
1299        .parent()
1300        .and_then(package_scope)
1301        .and_then(|p| p.get("type").and_then(|t| t.as_str()).map(str::to_string));
1302    match scope_type.as_deref() {
1303        Some("module") => Some(Format::Module),
1304        Some("commonjs") => Some(Format::CommonJs),
1305        _ => None,
1306    }
1307}
1308
1309/// The format of the file at `path` (`ESM_FILE_FORMAT`): by extension, then
1310/// by the package scope's `"type"`, then by syntax detection.
1311pub fn file_format(path: &Path) -> Format {
1312    file_format_declared(path).unwrap_or_else(|| match std::fs::read_to_string(path) {
1313        Ok(src) if has_module_syntax(&src) => Format::Module,
1314        _ => Format::CommonJs,
1315    })
1316}
1317
1318// ── resolution (node's ESM resolver, `defaultResolve`) ──────────────────────
1319
1320fn not_found(what: &str, parent: Option<&str>) -> String {
1321    let msg = match parent {
1322        Some(p) => format!("Cannot find {what} imported from {p}"),
1323        None => format!("Cannot find {what}"),
1324    };
1325    crate::host::plain_coded_error("Error", "ERR_MODULE_NOT_FOUND", &msg)
1326}
1327
1328/// `file://` URL of an absolute path, percent-encoded as `pathToFileURL` does.
1329pub fn file_url(path: &str) -> String {
1330    url::Url::from_file_path(path)
1331        .map(|u| u.to_string())
1332        .unwrap_or_else(|_| format!("file://{path}"))
1333}
1334
1335/// A module the resolver found: its URL (the module-map key), its file (empty
1336/// for a builtin), and its format.
1337pub struct Resolved {
1338    pub url: String,
1339    pub file: String,
1340    pub format: Format,
1341}
1342
1343fn builtin(spec: &str) -> Option<Resolved> {
1344    // The URL names the module as written (`node:events`), not the internal
1345    // namespace `stdlib::resolve` maps it to.
1346    crate::stdlib::resolve(spec).map(|_| Resolved {
1347        url: format!("node:{}", spec.strip_prefix("node:").unwrap_or(spec)),
1348        file: String::new(),
1349        format: Format::Builtin,
1350    })
1351}
1352
1353/// Resolve `spec` imported from the module file `parent` (`None`: the
1354/// current directory, as for `node -e`).
1355pub fn resolve(spec: &str, parent: Option<&str>) -> Result<Resolved, String> {
1356    if let Some(name) = spec.strip_prefix("node:") {
1357        return builtin(spec).ok_or_else(|| {
1358            crate::host::plain_coded_error(
1359                "Error",
1360                "ERR_UNKNOWN_BUILTIN_MODULE",
1361                &format!("No such built-in module: node:{name}"),
1362            )
1363        });
1364    }
1365    let base_dir = match parent {
1366        Some(p) => Path::new(p)
1367            .parent()
1368            .map(Path::to_path_buf)
1369            .unwrap_or_default(),
1370        None => std::env::current_dir().unwrap_or_default(),
1371    };
1372    let base_url = url::Url::from_directory_path(&base_dir)
1373        .map_err(|_| crate::host::type_error(&format!("Invalid URL: {}", base_dir.display())))?;
1374    let relative = spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/');
1375    let url = if relative {
1376        base_url
1377            .join(spec)
1378            .map_err(|_| crate::host::type_error(&format!("Invalid URL: {spec}")))?
1379    } else if let Ok(u) = url::Url::parse(spec) {
1380        if u.scheme() != "file" {
1381            return Err(crate::host::plain_coded_error(
1382                "Error",
1383                "ERR_UNSUPPORTED_ESM_URL_SCHEME",
1384                &format!(
1385                    "Only URLs with a scheme in: file and node are supported by the default ESM loader. Received protocol '{}:'",
1386                    u.scheme()
1387                ),
1388            ));
1389        }
1390        u
1391    } else {
1392        if let Some(b) = builtin(spec) {
1393            return Ok(b);
1394        }
1395        let file = if spec.starts_with('#') {
1396            imports_resolve(spec, &base_dir, parent)?
1397        } else {
1398            package_resolve(spec, &base_dir, parent)?
1399        };
1400        url::Url::from_file_path(&file)
1401            .map_err(|_| crate::host::type_error(&format!("Invalid URL: {}", file.display())))?
1402    };
1403    finalize(url, parent)
1404}
1405
1406/// `finalizeResolution`: the URL must name an existing file (no extension
1407/// probing, no directory index), and its identity is the REAL path.
1408fn finalize(url: url::Url, parent: Option<&str>) -> Result<Resolved, String> {
1409    let path = url
1410        .to_file_path()
1411        .map_err(|_| crate::host::type_error(&format!("Invalid URL: {url}")))?;
1412    if path.is_dir() {
1413        return Err(crate::host::plain_coded_error(
1414            "Error",
1415            "ERR_UNSUPPORTED_DIR_IMPORT",
1416            &format!(
1417                "Directory import '{}' is not supported resolving ES modules imported from {}",
1418                path.display(),
1419                parent.unwrap_or("")
1420            ),
1421        ));
1422    }
1423    if !path.is_file() {
1424        return Err(not_found(&format!("module '{}'", path.display()), parent));
1425    }
1426    let real = std::fs::canonicalize(&path).unwrap_or(path);
1427    let mut url = url::Url::from_file_path(&real).unwrap_or(url.clone());
1428    // `?query` / `#hash` are part of a module's identity.
1429    url.set_query(url.query().map(str::to_string).as_deref());
1430    let file = real.to_string_lossy().into_owned();
1431    Ok(Resolved {
1432        url: url.to_string(),
1433        format: file_format(&real),
1434        file,
1435    })
1436}
1437
1438/// The conditions node's ESM resolver matches in a package's `"exports"`.
1439const IMPORT_CONDITIONS: &[&str] = &["node", "import", "module-sync", "default"];
1440
1441/// `PACKAGE_RESOLVE`: a bare specifier, through `node_modules`.
1442fn package_resolve(spec: &str, from: &Path, parent: Option<&str>) -> Result<PathBuf, String> {
1443    let (name, rest) = match spec.strip_prefix('@') {
1444        Some(s) => match s.split_once('/') {
1445            Some((scope, tail)) => {
1446                let (pkg, sub) = tail.split_once('/').unwrap_or((tail, ""));
1447                (format!("@{scope}/{pkg}"), sub.to_string())
1448            }
1449            None => (spec.to_string(), String::new()),
1450        },
1451        None => {
1452            let (pkg, sub) = spec.split_once('/').unwrap_or((spec, ""));
1453            (pkg.to_string(), sub.to_string())
1454        }
1455    };
1456    let subpath = if rest.is_empty() {
1457        ".".to_string()
1458    } else {
1459        format!("./{rest}")
1460    };
1461    // PACKAGE_SELF_RESOLVE: a package may import itself by its own name,
1462    // through its own `"exports"`.
1463    if let Some(pj) = package_scope_file(from) {
1464        if let Some(json) = read_package_json(&pj) {
1465            let exports = json.get("exports").filter(|e| !e.is_null());
1466            if let (Some(exports), Some(own)) = (exports, json.get("name").and_then(|n| n.as_str()))
1467            {
1468                if own == name {
1469                    let pkg = pj.parent().unwrap_or(Path::new("/"));
1470                    return exports_resolve(pkg, &subpath, exports, &pj, parent);
1471                }
1472            }
1473        }
1474    }
1475    let mut dir = Some(from);
1476    while let Some(d) = dir {
1477        let pkg_dir = d.join("node_modules").join(&name);
1478        if pkg_dir.is_dir() {
1479            let pj_path = pkg_dir.join("package.json");
1480            let pj = read_package_json(&pj_path);
1481            if let Some(exports) = pj
1482                .as_ref()
1483                .and_then(|p| p.get("exports"))
1484                .filter(|e| !e.is_null())
1485            {
1486                return exports_resolve(&pkg_dir, &subpath, exports, &pj_path, parent);
1487            }
1488            if subpath == "." {
1489                return legacy_main(&pkg_dir, pj.as_ref())
1490                    .ok_or_else(|| not_found(&format!("package '{}'", pkg_dir.display()), parent));
1491            }
1492            return Ok(pkg_dir.join(&rest));
1493        }
1494        dir = d.parent();
1495    }
1496    Err(not_found(&format!("package '{name}'"), parent))
1497}
1498
1499/// `legacyMainResolve`: `"main"` with the CommonJS extension probes, then
1500/// `index.js`.
1501fn legacy_main(pkg: &Path, pj: Option<&serde_json::Value>) -> Option<PathBuf> {
1502    let mut cands: Vec<PathBuf> = Vec::new();
1503    if let Some(main) = pj.and_then(|p| p.get("main")).and_then(|m| m.as_str()) {
1504        let m = pkg.join(main);
1505        cands.push(m.clone());
1506        for ext in ["js", "json", "node"] {
1507            cands.push(PathBuf::from(format!("{}.{ext}", m.display())));
1508        }
1509        for idx in ["index.js", "index.json", "index.node"] {
1510            cands.push(m.join(idx));
1511        }
1512    }
1513    for idx in ["index.js", "index.json", "index.node"] {
1514        cands.push(pkg.join(idx));
1515    }
1516    cands.into_iter().find(|c| c.is_file())
1517}
1518
1519fn not_exported(pkg_json: &Path, subpath: &str, parent: Option<&str>) -> String {
1520    let from = parent
1521        .map(|p| format!(" imported from {p}"))
1522        .unwrap_or_default();
1523    let msg = if subpath == "." {
1524        format!(
1525            "No \"exports\" main defined in {}{from}",
1526            pkg_json.display()
1527        )
1528    } else {
1529        format!(
1530            "Package subpath '{subpath}' is not defined by \"exports\" in {}{from}",
1531            pkg_json.display()
1532        )
1533    };
1534    crate::host::plain_coded_error("Error", "ERR_PACKAGE_PATH_NOT_EXPORTED", &msg)
1535}
1536
1537/// `PACKAGE_EXPORTS_RESOLVE` for `subpath` (`"."` or `"./x"`).
1538fn exports_resolve(
1539    pkg: &Path,
1540    subpath: &str,
1541    exports: &serde_json::Value,
1542    pj: &Path,
1543    parent: Option<&str>,
1544) -> Result<PathBuf, String> {
1545    // A string, an array, or an object without `.`-keys is the `"."` entry.
1546    let is_subpath_map = exports
1547        .as_object()
1548        .is_some_and(|o| o.keys().next().is_some_and(|k| k.starts_with('.')));
1549    let found = match exports.as_object() {
1550        Some(map) if is_subpath_map => match_subpath_map(map, subpath),
1551        _ => (subpath == ".").then(|| (exports, String::new())),
1552    };
1553    let found = found
1554        .and_then(|(t, pattern)| target_string(t, &pattern))
1555        .and_then(|s| s.strip_prefix("./").map(|rel| pkg.join(rel)));
1556    found.ok_or_else(|| not_exported(pj, subpath, parent))
1557}
1558
1559/// The entry of an `"exports"` / `"imports"` map that `key` selects: an exact
1560/// key, else the longest `prefix*suffix` pattern key that matches
1561/// (`PATTERN_KEY_COMPARE`), with what `*` matched.
1562fn match_subpath_map<'a>(
1563    map: &'a serde_json::Map<String, serde_json::Value>,
1564    key: &str,
1565) -> Option<(&'a serde_json::Value, String)> {
1566    if let Some(t) = map.get(key).filter(|_| !key.contains('*')) {
1567        return Some((t, String::new()));
1568    }
1569    let mut best: Option<(&str, String)> = None;
1570    for k in map.keys() {
1571        let Some((pre, post)) = k.split_once('*') else {
1572            continue;
1573        };
1574        if key.starts_with(pre)
1575            && key.len() >= pre.len() + post.len()
1576            && key.ends_with(post)
1577            && best.as_ref().map_or(true, |(b, _)| k.len() > b.len())
1578        {
1579            best = Some((
1580                k.as_str(),
1581                key[pre.len()..key.len() - post.len()].to_string(),
1582            ));
1583        }
1584    }
1585    best.map(|(k, mid)| (&map[k], mid))
1586}
1587
1588/// `PACKAGE_TARGET_RESOLVE` down to the target string (with `*` replaced by
1589/// `pattern`): a string, a conditions object tried in key order, or a
1590/// fallback array.
1591fn target_string(target: &serde_json::Value, pattern: &str) -> Option<String> {
1592    match target {
1593        serde_json::Value::String(s) => Some(s.replace('*', pattern)),
1594        serde_json::Value::Object(o) => o
1595            .iter()
1596            .filter(|(k, _)| IMPORT_CONDITIONS.contains(&k.as_str()))
1597            .find_map(|(_, v)| target_string(v, pattern)),
1598        serde_json::Value::Array(a) => a.iter().find_map(|v| target_string(v, pattern)),
1599        _ => None,
1600    }
1601}
1602
1603/// `PACKAGE_IMPORTS_RESOLVE`: a `#name` specifier through the `"imports"` of
1604/// the importing file's package. A target is a `./` path inside the package or
1605/// a bare specifier resolved as a package.
1606fn imports_resolve(spec: &str, from: &Path, parent: Option<&str>) -> Result<PathBuf, String> {
1607    let undefined = || {
1608        let from_text = parent
1609            .map(|p| format!(" imported from {p}"))
1610            .unwrap_or_default();
1611        crate::host::plain_coded_error(
1612            "TypeError",
1613            "ERR_PACKAGE_IMPORT_NOT_DEFINED",
1614            &format!("Package import specifier \"{spec}\" is not defined{from_text}"),
1615        )
1616    };
1617    let pj = package_scope_file(from).ok_or_else(undefined)?;
1618    let pkg = pj.parent().unwrap_or(Path::new("/"));
1619    let json = read_package_json(&pj).ok_or_else(undefined)?;
1620    let map = json
1621        .get("imports")
1622        .and_then(|i| i.as_object())
1623        .ok_or_else(undefined)?;
1624    let (target, pattern) = match_subpath_map(map, spec).ok_or_else(undefined)?;
1625    let target = target_string(target, &pattern).ok_or_else(undefined)?;
1626    match target.strip_prefix("./") {
1627        Some(rel) => Ok(pkg.join(rel)),
1628        None => package_resolve(&target, pkg, parent),
1629    }
1630}
1631
1632// ── CommonJS named exports (cjs-module-lexer) ───────────────────────────────
1633
1634/// The names an `import { … }` of a CommonJS module may use: the exports
1635/// node's `cjs-module-lexer` detects statically, without running the module —
1636/// `exports.x = …`, `module.exports.x = …`, `Object.defineProperty(exports,
1637/// "x", …)`, the keys of a `module.exports = { a, b: … }` literal — plus the
1638/// names of a module it re-exports through `module.exports = require("…")`.
1639pub fn cjs_export_names(file: &Path, seen: &mut HashSet<PathBuf>) -> Vec<String> {
1640    let mut out: Vec<String> = Vec::new();
1641    if !seen.insert(file.to_path_buf()) {
1642        return out;
1643    }
1644    let Ok(src) = std::fs::read_to_string(file) else {
1645        return out;
1646    };
1647    let Ok(stmts) = crate::parser::parse(&src) else {
1648        return out;
1649    };
1650    let mut reexports: Vec<String> = Vec::new();
1651    let mut scan = CjsScan {
1652        names: &mut out,
1653        reexports: &mut reexports,
1654    };
1655    for s in &stmts {
1656        scan.stmt(s);
1657    }
1658    let dir = file.parent().unwrap_or(Path::new("/"));
1659    for spec in reexports {
1660        if let Some(target) = crate::module::resolve(&spec, dir) {
1661            for n in cjs_export_names(&target, seen) {
1662                if !out.contains(&n) {
1663                    out.push(n);
1664                }
1665            }
1666        }
1667    }
1668    out.retain(|n| n != "default");
1669    out
1670}
1671
1672struct CjsScan<'a> {
1673    names: &'a mut Vec<String>,
1674    reexports: &'a mut Vec<String>,
1675}
1676
1677/// `exports` or `module.exports`.
1678fn is_exports_obj(e: &Expr) -> bool {
1679    match e {
1680        Expr::Ident(n) => n == "exports",
1681        Expr::Member {
1682            object, property, ..
1683        } => property == "exports" && matches!(&**object, Expr::Ident(m) if m == "module"),
1684        _ => false,
1685    }
1686}
1687
1688impl CjsScan<'_> {
1689    fn add(&mut self, n: &str) {
1690        if !self.names.iter().any(|x| x == n) {
1691            self.names.push(n.to_string());
1692        }
1693    }
1694    fn stmt(&mut self, s: &Stmt) {
1695        walk_stmt_children(s, &mut |n| match n {
1696            Node::S(st) => self.stmt(st),
1697            Node::E(e) => self.expr(e),
1698        });
1699        if let StmtKind::FuncDecl { body, .. } = &s.kind {
1700            body.iter().for_each(|st| self.stmt(st));
1701        }
1702    }
1703    fn expr(&mut self, e: &Expr) {
1704        match e {
1705            Expr::Assign { target, value, .. } => {
1706                match &**target {
1707                    Expr::Member {
1708                        object, property, ..
1709                    } if is_exports_obj(object) => self.add(property),
1710                    Expr::Index { object, index, .. } if is_exports_obj(object) => {
1711                        if let Expr::Str(k) = &**index {
1712                            self.add(k);
1713                        }
1714                    }
1715                    t if is_exports_obj(t) && matches!(t, Expr::Member { .. }) => match &**value {
1716                        // The lexer reads `{ a, b: c, 'd': e, ...f }`: a key
1717                        // whose value is an identifier (or a shorthand), a
1718                        // spread is skipped, and anything else ends the scan —
1719                        // after the key of a `key: require(…)`.
1720                        Expr::Object(props) => {
1721                            for p in props {
1722                                match p {
1723                                    Prop::KeyValue {
1724                                        key: Expr::Str(k),
1725                                        computed: false,
1726                                        value,
1727                                    } => match value {
1728                                        Expr::Ident(_) => self.add(k),
1729                                        Expr::Call { func, .. } if matches!(&**func, Expr::Ident(r) if r == "require") =>
1730                                        {
1731                                            self.add(k);
1732                                            break;
1733                                        }
1734                                        _ => break,
1735                                    },
1736                                    Prop::Spread(_) => {}
1737                                    _ => break,
1738                                }
1739                            }
1740                        }
1741                        Expr::Call { func, args, .. } if matches!(&**func, Expr::Ident(r) if r == "require") => {
1742                            if let Some(Expr::Str(s)) = args.first() {
1743                                self.reexports.push(s.clone());
1744                            }
1745                        }
1746                        _ => {}
1747                    },
1748                    _ => {}
1749                }
1750                walk_expr_children(e, &mut |x| self.expr(x));
1751            }
1752            // `Object.defineProperty(exports, "x", …)`.
1753            Expr::Call { func, args, .. } => {
1754                if let Expr::Member {
1755                    object, property, ..
1756                } = &**func
1757                {
1758                    if property == "defineProperty"
1759                        && matches!(&**object, Expr::Ident(o) if o == "Object")
1760                        && args.first().is_some_and(is_exports_obj)
1761                    {
1762                        if let Some(Expr::Str(k)) = args.get(1) {
1763                            self.add(k);
1764                        }
1765                    }
1766                }
1767                walk_expr_children(e, &mut |x| self.expr(x));
1768            }
1769            Expr::Function { body, .. } => match body {
1770                FnBody::Block(b) => b.iter().for_each(|st| self.stmt(st)),
1771                FnBody::Expr(x) => self.expr(x),
1772            },
1773            _ => walk_expr_children(e, &mut |x| self.expr(x)),
1774        }
1775    }
1776}
1777
1778// ── module registry and the natives `esm_loader.js` calls ───────────────────
1779
1780use crate::host::{self, with_host, JsObj};
1781use fusevm::Value;
1782
1783/// A parsed module waiting to be instantiated: its lowered function (built as
1784/// a plain function; [`compile`] turns it into the generator form a cycle
1785/// needs) and the text its spans index.
1786struct Parsed {
1787    lowered: Option<Expr>,
1788    source: String,
1789    /// The module's `file://` URL, which its stack frames and source arrow name.
1790    url: String,
1791}
1792
1793thread_local! {
1794    static PARSED: std::cell::RefCell<Vec<Parsed>> = const { std::cell::RefCell::new(Vec::new()) };
1795    /// Module text with no file behind it, keyed by the name it runs under.
1796    static VIRTUAL: std::cell::RefCell<HashMap<String, String>> =
1797        std::cell::RefCell::new(HashMap::new());
1798    /// The loader API object `esm_loader.js` returns, built once per host.
1799    static LOADER: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
1800}
1801
1802/// Drop every module record. Called from `module::reset` with the heap.
1803pub fn reset() {
1804    PARSED.with(|p| p.borrow_mut().clear());
1805    VIRTUAL.with(|v| v.borrow_mut().clear());
1806    LOADER.with(|l| *l.borrow_mut() = None);
1807    PACKAGE_JSON.with(|c| c.borrow_mut().clear());
1808}
1809
1810fn s(v: &Value) -> String {
1811    with_host(|h| h.str_of(v))
1812}
1813
1814fn js_str(text: &str) -> Value {
1815    with_host(|h| h.new_str(text.to_string()))
1816}
1817
1818fn js_array(items: Vec<Value>) -> Value {
1819    with_host(|h| h.new_array(items))
1820}
1821
1822fn js_name(n: &Option<String>) -> Value {
1823    match n {
1824        Some(n) => js_str(n),
1825        None => with_host(|h| h.null()),
1826    }
1827}
1828
1829/// The record fields of a parsed module, as the loader reads them.
1830/// Node's rendering of an import clause as the destructuring it suggests in
1831/// its "Named export not found" error: whitespace collapsed, `as` turned into
1832/// `:` (`{ a as b }` → `{ a: b }`).
1833fn clause_text(source: &str, (start, end): Span) -> String {
1834    let raw = source.get(start as usize..end as usize).unwrap_or("");
1835    let words: Vec<&str> = raw.split_whitespace().collect();
1836    words.join(" ").replace(" as ", ": ")
1837}
1838
1839fn info_value(id: usize, info: &ModuleInfo, source: &str) -> Value {
1840    let requests = info
1841        .requests
1842        .iter()
1843        .map(|(spec, attrs)| {
1844            let mut props = indexmap::IndexMap::new();
1845            for (k, v) in attrs {
1846                props.insert(k.clone(), js_str(v));
1847            }
1848            let attrs = with_host(|h| h.new_object(props));
1849            js_array(vec![js_str(spec), attrs])
1850        })
1851        .collect();
1852    let imports = info
1853        .imports
1854        .iter()
1855        .map(|e| {
1856            js_array(vec![
1857                Value::Float(e.request as f64),
1858                js_name(&e.import_name),
1859                js_str(&e.local),
1860                js_str(&clause_text(source, e.clause)),
1861            ])
1862        })
1863        .collect();
1864    let locals = info
1865        .local_exports
1866        .iter()
1867        .map(|(e, l)| js_array(vec![js_str(e), js_str(l)]))
1868        .collect();
1869    let indirect = info
1870        .indirect_exports
1871        .iter()
1872        .map(|e| {
1873            js_array(vec![
1874                js_str(&e.export_name),
1875                Value::Float(e.request as f64),
1876                js_name(&e.import_name),
1877            ])
1878        })
1879        .collect();
1880    let stars = info
1881        .star_exports
1882        .iter()
1883        .map(|r| Value::Float(*r as f64))
1884        .collect();
1885    let mut props = indexmap::IndexMap::new();
1886    props.insert("id".to_string(), Value::Float(id as f64));
1887    props.insert("requests".to_string(), js_array(requests));
1888    props.insert("imports".to_string(), js_array(imports));
1889    props.insert("localExports".to_string(), js_array(locals));
1890    props.insert("indirectExports".to_string(), js_array(indirect));
1891    props.insert("starExports".to_string(), js_array(stars));
1892    props.insert("hasTLA".to_string(), Value::Bool(info.has_tla));
1893    with_host(|h| h.new_object(props))
1894}
1895
1896/// ParseModule for the file at `path`: the record fields, with the parsed
1897/// body kept for [`compile`].
1898fn parse_file(path: &str) -> Result<Value, String> {
1899    let source = match VIRTUAL.with(|v| v.borrow_mut().remove(path)) {
1900        Some(text) => text,
1901        None => {
1902            std::fs::read_to_string(path).map_err(|e| format!("Error: cannot read {path}: {e}"))?
1903        }
1904    };
1905    let stmts = crate::parser::parse_module(&source).inspect_err(|e| {
1906        let at = crate::parser::take_error_pos();
1907        host::note_syntax_error(&source, host::ScriptOrigin::named(file_url(path)), e, at);
1908    })?;
1909    let info = analyze(&stmts)?;
1910    let lowered = lower(stmts, &info, path, false);
1911    // The early errors of the module's own statement list (duplicate lexical
1912    // declarations, a `var` colliding with a `let`, …) are checked here, on
1913    // the lowered body, rather than when the loader first instantiates it.
1914    if let Expr::Function {
1915        body: FnBody::Block(b),
1916        ..
1917    } = &lowered
1918    {
1919        crate::compiler::check_early_errors(b).inspect_err(|e| {
1920            let at = crate::parser::take_error_pos();
1921            host::note_syntax_error(&source, host::ScriptOrigin::named(file_url(path)), e, at);
1922        })?;
1923    }
1924    let id = PARSED.with(|p| p.borrow().len());
1925    let record = info_value(id, &info, &source);
1926    PARSED.with(|p| {
1927        p.borrow_mut().push(Parsed {
1928            lowered: Some(lowered),
1929            source,
1930            url: file_url(path),
1931        })
1932    });
1933    Ok(record)
1934}
1935
1936/// Compile parsed module `id` to its function; `generator` selects the form a
1937/// module in an import cycle is built in (see the module docs).
1938fn compile(id: usize, generator: bool) -> Result<Value, String> {
1939    let (lowered, source, url) = PARSED.with(|p| {
1940        let mut p = p.borrow_mut();
1941        let entry = &mut p[id];
1942        (
1943            entry.lowered.take(),
1944            std::mem::take(&mut entry.source),
1945            entry.url.clone(),
1946        )
1947    });
1948    let mut lowered = lowered.ok_or_else(|| host::type_error("module instantiated twice"))?;
1949    if generator {
1950        if let Expr::Function {
1951            body: FnBody::Block(b),
1952            is_generator,
1953            ..
1954        } = &mut lowered
1955        {
1956            *is_generator = true;
1957            b.insert(
1958                1,
1959                Stmt::from(StmtKind::Expr(Expr::Yield {
1960                    arg: None,
1961                    delegate: false,
1962                })),
1963            );
1964        }
1965    }
1966    let stmts = vec![Stmt::from(StmtKind::Expr(lowered))];
1967    let prog = crate::with_source(
1968        crate::compiler::compile_completion_strict(&stmts, false, true, false),
1969        &source,
1970    )?;
1971    host::run_chunk_in_global_scope(crate::load_merged_from(
1972        prog,
1973        Some(host::ScriptOrigin::named(url)),
1974    ))
1975}
1976
1977/// Mark `ns` (a Proxy) as a module namespace object, which `util.inspect`
1978/// and the refused-write messages recognise.
1979fn mark_namespace(ns: &Value) {
1980    with_host(|h| {
1981        if let Some(JsObj::Proxy { target, .. }) = h.get(ns).cloned() {
1982            if let Some(JsObj::Object(p)) = h.get_mut(&target) {
1983                p.insert(NAMESPACE_MARK.to_string(), Value::Bool(true));
1984            }
1985        }
1986    });
1987}
1988
1989/// Hidden slot on a namespace's proxy target.
1990const NAMESPACE_MARK: &str = "@@esmNamespace";
1991
1992/// Whether `v` is a module namespace object.
1993pub fn is_namespace(v: &Value) -> bool {
1994    with_host(|h| match h.get(v) {
1995        Some(JsObj::Proxy { target, .. }) => {
1996            matches!(h.get(target), Some(JsObj::Object(p)) if p.contains_key(NAMESPACE_MARK))
1997        }
1998        _ => false,
1999    })
2000}
2001
2002/// The `@@esm.<name>` natives.
2003pub fn native(name: &str, args: &[Value]) -> Result<Value, String> {
2004    let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Undef);
2005    match name {
2006        "resolve" => {
2007            let parent = match arg(1) {
2008                Value::Undef => None,
2009                v => Some(s(&v)),
2010            };
2011            let r = resolve(&s(&arg(0)), parent.as_deref())?;
2012            Ok(js_array(vec![
2013                js_str(&r.url),
2014                js_str(&r.file),
2015                js_str(r.format.name()),
2016            ]))
2017        }
2018        "parse" => parse_file(&s(&arg(0))),
2019        "compile" => {
2020            let id = with_host(|h| h.to_number(&arg(0))) as usize;
2021            let generator = with_host(|h| h.truthy(&arg(1)));
2022            compile(id, generator)
2023        }
2024        "cjsNames" => {
2025            let names = cjs_export_names(Path::new(&s(&arg(0))), &mut HashSet::new());
2026            Ok(js_array(names.iter().map(|n| js_str(n)).collect()))
2027        }
2028        "requireCjs" => crate::module::require_file(Path::new(&s(&arg(0))), ""),
2029        "builtin" => {
2030            let url = s(&arg(0));
2031            let spec = url.strip_prefix("node:").unwrap_or(&url);
2032            crate::module::require(spec, &crate::module::entry_dir(), "")
2033        }
2034        "json" => {
2035            let path = s(&arg(0));
2036            let text = std::fs::read_to_string(&path)
2037                .map_err(|e| format!("Error: cannot read {path}: {e}"))?;
2038            crate::builtins::call_builtin_function("JSON.parse", vec![js_str(&text)])
2039        }
2040        "markNamespace" => {
2041            mark_namespace(&arg(0));
2042            Ok(Value::Undef)
2043        }
2044        // The two entry points compiled code reaches through globals.
2045        "import" => loader_call("dynamicImport", args.to_vec()),
2046        "main" => loader_call("runMain", args.to_vec()),
2047        _ => Err(host::type_error(&format!("@@esm.{name} is not a function"))),
2048    }
2049}
2050
2051/// The loader API (`esm_loader.js`), evaluated once per host.
2052fn loader() -> Result<Value, String> {
2053    if let Some(l) = LOADER.with(|l| l.borrow().clone()) {
2054        return Ok(l);
2055    }
2056    let factory = crate::eval_in_global_scope_from(
2057        include_str!("esm_loader.js"),
2058        Some(host::ScriptOrigin::internal(
2059            "node:internal/modules/esm/loader",
2060        )),
2061    )?;
2062    let mut natives = indexmap::IndexMap::new();
2063    for n in [
2064        "resolve",
2065        "parse",
2066        "compile",
2067        "cjsNames",
2068        "requireCjs",
2069        "builtin",
2070        "json",
2071        "markNamespace",
2072    ] {
2073        let f = with_host(|h| h.alloc(JsObj::Builtin(format!("@@esm.{n}"))));
2074        natives.insert(n.to_string(), f);
2075    }
2076    let natives = with_host(|h| h.new_object(natives));
2077    let api = host::invoke(&factory, vec![natives], None)?;
2078    LOADER.with(|l| *l.borrow_mut() = Some(api.clone()));
2079    Ok(api)
2080}
2081
2082fn loader_call(method: &str, args: Vec<Value>) -> Result<Value, String> {
2083    let api = loader()?;
2084    let f = crate::builtins::get_property(&api, method)?;
2085    host::invoke(&f, args, None)
2086}
2087
2088/// `require()` of an ES module file (node's `require(esm)`): its namespace,
2089/// or the value it exports under the name `"module.exports"`.
2090pub fn require_module(path: &Path, parent: &str) -> Result<Value, String> {
2091    loader_call(
2092        "requireModule",
2093        vec![js_str(&path.to_string_lossy()), js_str(parent)],
2094    )
2095}
2096
2097/// The statements that run an ES module ENTRY point: one call that loads and
2098/// links its graph and queues its evaluation (`esm_loader.js` `runMain`).
2099///
2100/// `entry` is the module's file; `source`, when given, is its text — the
2101/// `[eval1]` module `node -e` and piped stdin run has no file behind it.
2102/// `is_main` is `import.meta.main`, true only for a file entry point.
2103pub fn main_program(entry: &str, source: Option<String>, is_main: bool) -> Vec<Stmt> {
2104    if let Some(text) = source {
2105        VIRTUAL.with(|v| v.borrow_mut().insert(entry.to_string(), text));
2106    }
2107    // The entry module's body runs in a function of its own; the program
2108    // frame that starts the loader is no part of a stack node prints.
2109    with_host(|h| h.module_frame_done = true);
2110    let call = Expr::Call {
2111        func: Box::new(Expr::Ident(MAIN_FN.into())),
2112        args: vec![
2113            Expr::Str(entry.to_string()),
2114            Expr::Str(file_url(entry)),
2115            if is_main { Expr::True } else { Expr::False },
2116        ],
2117        optional: false,
2118        pos: 0,
2119    };
2120    vec![Stmt::from(StmtKind::Expr(call))]
2121}
2122
2123/// The global [`main_program`] calls.
2124pub const MAIN_FN: &str = "%esm.main";
2125
2126/// The refused-write operations of a module namespace object, which V8
2127/// reports in its own words rather than as a proxy trap's.
2128pub enum Refused {
2129    Set,
2130    Delete,
2131    Define,
2132}
2133
2134/// V8's `TypeError` for a refused `op` on property `key` of `recv`, when
2135/// `recv` is a module namespace object.
2136pub fn namespace_refusal(recv: &Value, op: Refused, key: &str) -> Option<String> {
2137    if !is_namespace(recv) {
2138        return None;
2139    }
2140    Some(host::type_error(&match op {
2141        Refused::Set => format!("Cannot assign to property '{key}' of [object Module]"),
2142        Refused::Delete => format!("Cannot delete property '{key}' of [object Module]"),
2143        Refused::Define => format!("Cannot redefine property: {key}"),
2144    }))
2145}
2146
2147/// When the event loop has drained with the ENTRY module still suspended in a
2148/// top-level `await`, node warns and exits 13 (unless the program chose an
2149/// exit code). Called once the loop is empty, before the `exit` event.
2150///
2151/// node prints one warning per module of the entry's graph that is stalled in
2152/// its own body (`ModuleWrap`'s check over V8's stalled-module messages), each
2153/// with the source arrow of the `await` it is suspended in, then the blank
2154/// lines its `FormatErrorMessage` leaves behind an empty reason.
2155pub fn settle_unfinished_entry() -> Result<(), String> {
2156    if LOADER.with(|l| l.borrow().is_none()) {
2157        return Ok(());
2158    }
2159    let pending = loader_call("mainUnsettled", Vec::new())?;
2160    if matches!(pending, Value::Undef) {
2161        return Ok(());
2162    }
2163    let stalled = with_host(|h| h.iter_vec(&pending)).unwrap_or_default();
2164    let mut out = String::new();
2165    for entry in stalled {
2166        let pair = with_host(|h| h.iter_vec(&entry)).unwrap_or_default();
2167        let url = with_host(|h| h.str_of(pair.first().unwrap_or(&Value::Undef)));
2168        let pos = pair.get(1).map_or(0, host::suspended_await_pos);
2169        out.push_str("Warning: Detected unsettled top-level await at ");
2170        match with_host(|h| host::source_arrow(h, pos)) {
2171            Some(arrow) => {
2172                out.push_str(&arrow);
2173                out.push_str("\n\n\n");
2174            }
2175            None => {
2176                out.push_str(&url);
2177                out.push('\n');
2178            }
2179        }
2180    }
2181    with_host(|h| {
2182        h.write_out(&out, true);
2183        h.exit_code.get_or_insert(13);
2184    });
2185    Ok(())
2186}