Skip to main content

quickjs/
module.rs

1//! The module system: records, linking, namespaces, and evaluation.
2//!
3//! The design follows §16.2 closely but leans on one thing this engine already has.
4//! A module's top-level bindings compile as *closure variables* of the module body —
5//! `ClosureType::ModuleDecl` for its own declarations, `ClosureType::ModuleImport` for
6//! what it imports — so reading one is an ordinary `get_var_ref`. What makes modules
7//! interesting is then entirely a question of **who fills the cells**:
8//!
9//! * a declaration gets a fresh cell, created here;
10//! * an import gets *the exporting module's* cell, not a copy.
11//!
12//! Sharing the cell is what makes bindings live (`export let x; x = 1` is visible to the
13//! importer) and what makes cyclic imports work: linking wires cells before anything
14//! evaluates, so `a.js` importing from a `b.js` that imports back from `a.js` resolves to
15//! cells on both sides without either body having run.
16//!
17//! The three phases are the spec's: load (read and compile), link (resolve imports,
18//! validate exports), evaluate (run bodies depth-first, once each).
19
20use std::collections::BTreeMap;
21
22use js_gc::{Gc, Trace, Tracer};
23
24use crate::interp::{Interp, JsResult, Signal, WellKnown};
25use crate::object::{Callable, ClosureEnv, CompiledCode, JsObject, Property};
26use crate::value::{Cell, Value};
27use js_compile::bytecode::Function as CompiledFunction;
28use js_parse::ast::ImportPhase;
29
30/// The reference's textual specifier rule, shared with the AOT bundler.
31///
32/// See [`js_parse::normalize_specifier`]: the loader and the bundler have to agree on a
33/// module's name, or a product reports "could not load module filename" for a module it is
34/// carrying.
35pub use js_parse::normalize_specifier;
36
37/// Where a module is in its lifetime.
38///
39/// `Linking` and `Evaluated` are not just bookkeeping: they are what makes a cycle
40/// terminate. A cycle is not an error — it is a graph that must be *linked* depth-first
41/// and then *evaluated* in post-order, and the two-phase split is the mechanism.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum ModuleStatus {
44    /// Loaded and compiled; imports not yet resolved.
45    Unlinked,
46    /// Being linked, so a re-entrant link must not recurse.
47    Linking,
48    /// Imports resolved and exports validated.
49    Linked,
50    /// Body running right now.
51    ///
52    /// Distinct from [`ModuleStatus::Evaluated`] because the deferred-import proposal asks
53    /// the difference: `ReadyForSyncExecution` answers *false* for a module that is
54    /// `~evaluating~`, and the only way a namespace read can observe that is if the two
55    /// states are not the same flag. A re-entrant evaluation still stops at either.
56    Evaluating,
57    /// Body suspended at a top-level `await`, or waiting for a dependency that is.
58    ///
59    /// §16.2.1.5.3.1's `~evaluating-async~`. A module in this state has a body that has
60    /// **started** — its `[[AsyncEvaluation]]` is set and it holds an
61    /// `[[AsyncEvaluationOrder]]` — and it will be moved to `Evaluated` by the module
62    /// machinery, not by whatever call happened to reach it.
63    EvaluatingAsync,
64    /// Body has run to completion, or has failed.
65    ///
66    /// A body that threw is `Evaluated` too — §16.2.1.5.3.1 records the completion in
67    /// `[[EvaluationError]]` and marks the module evaluated, so a second attempt reports
68    /// the *same* exception object rather than running the body again.
69    Evaluated,
70}
71
72/// How a module's source became a module.
73///
74/// A JSON or text module is not code at all — it is one value exported as `default` — so
75/// it has no body and no imports, which is why this is a flag rather than a second type.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum ModuleKind {
78    /// JavaScript: has a compiled body.
79    JavaScript,
80    /// A parsed JSON document, exported as `default`.
81    Json,
82    /// A plain string, exported as `default`.
83    Text,
84    /// A `Uint8Array`, exported as `default`.
85    Bytes,
86    /// A native module: exports supplied by the host, with no source at all.
87    ///
88    /// This is the C API's `JS_NewCModule`. The values are already built when the module
89    /// appears, so the record is born evaluated — the same shape a data module has, with
90    /// several exports instead of one.
91    Native,
92}
93
94/// One loaded module.
95///
96/// Held on the GC heap because its cells and namespace are GC values. The whole record is
97/// behind interior mutability the same way a [`Cell`] is: linking writes into it while
98/// other modules already hold references to it.
99pub struct ModuleRecord {
100    inner: std::cell::RefCell<ModuleInner>,
101}
102
103impl ModuleRecord {
104    /// Build a record around `inner`.
105    pub fn new(inner: ModuleInner) -> ModuleRecord {
106        ModuleRecord {
107            inner: std::cell::RefCell::new(inner),
108        }
109    }
110
111    /// Run `f` with the record borrowed.
112    pub fn with<R>(&self, f: impl FnOnce(&ModuleInner) -> R) -> R {
113        f(&self.inner.borrow())
114    }
115
116    /// Run `f` with the record borrowed mutably.
117    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ModuleInner) -> R) -> R {
118        f(&mut self.inner.borrow_mut())
119    }
120
121    /// Whether the module's body contains a top-level `await`.
122    ///
123    /// §16.2.1.5.3.1's `[[HasTLA]]`. A body with one compiles to an async function, so the
124    /// flag is the compiled kind rather than a second piece of bookkeeping: the two can
125    /// never disagree.
126    pub fn has_tla(&self) -> bool {
127        self.with(|r| {
128            r.code
129                .as_ref()
130                .is_some_and(|code| code.code.kind.is_async())
131        })
132    }
133}
134
135/// §16.2.1.5.3.1's `[[CycleRoot]]`, defaulting to the module itself.
136///
137/// A free function rather than a method because the default is the module's own `Gc`
138/// handle, which `&ModuleRecord` does not carry. `None` means "not in a cycle (yet)", and
139/// a module that is not in a cycle is its own root — which is why the two are the same
140/// answer here.
141fn cycle_root_of(module: &Gc<ModuleRecord>) -> Gc<ModuleRecord> {
142    module
143        .with(|r| r.cycle_root.clone())
144        .unwrap_or_else(|| module.clone())
145}
146
147/// `IsModuleSCCEvaluated(module)` — is the whole strongly-connected component done?
148///
149/// The question is asked of the **cycle root**, not of the module: a module inside a cycle
150/// stops being `~evaluating-async~` only when its root does, and a member whose own body has
151/// already run is still part of a component that has not. Treating "my body finished" as
152/// "my component finished" is what made a deferred read run past an in-flight cycle
153/// (`async-cycle-dependency-of-deferred-module`: `B` is `evaluated` while its root `A` is
154/// parked, and the importer has to wait for `A`).
155///
156/// `[[CycleRoot]]` is empty until the component is popped off the DFS stack, so a module
157/// that has never been in a cycle answers for itself.
158fn is_module_scc_evaluated(module: &Gc<ModuleRecord>) -> bool {
159    match module.with(|r| r.cycle_root.clone()) {
160        Some(root) => root.with(|r| r.status) == ModuleStatus::Evaluated,
161        None => module.with(|r| r.status) == ModuleStatus::Evaluated,
162    }
163}
164
165/// Everything a module record holds; see [`ModuleRecord`].
166pub struct ModuleInner {
167    /// Canonical identity: the cache key, and what a cycle compares.
168    pub name: String,
169    /// What `import.meta.url` reports.
170    pub url: String,
171    /// The compiled body, or `None` for a JSON/text/bytes module.
172    pub code: Option<Gc<CompiledCode>>,
173    /// The tables the compiler produced.
174    pub meta: js_compile::bytecode::ModuleMeta,
175    /// One cell per closure variable of the body; the body reads its bindings here.
176    pub cells: Vec<Gc<Cell>>,
177    /// Resolved dependencies, parallel to `meta.requests`.
178    pub dependencies: Vec<Option<Gc<ModuleRecord>>>,
179    /// Where it is in its lifetime.
180    pub status: ModuleStatus,
181    /// The completion of a body that threw, rethrown on every later attempt.
182    ///
183    /// §16.2.1.5.3.1 stores the *abrupt completion* on the record. Without it a second
184    /// read through a deferred namespace ran the body again and produced a second, equal,
185    /// but not identical error object — which `import-defer/errors/module-throws` compares
186    /// by identity.
187    pub evaluation_error: Option<Value>,
188    /// §16.2.1.5.3.1's `[[AsyncEvaluation]]`: the body has started and has not finished.
189    ///
190    /// Not the same as `status == EvaluatingAsync`, because the flag is also what an
191    /// *importer* looks at: a request whose target has this set makes the importer wait.
192    pub async_evaluation: bool,
193    /// §16.2.1.5.3.1's `[[AsyncEvaluationOrder]]`.
194    ///
195    /// A monotonic counter, never reset. The ordering of modules that become ready in one
196    /// batch is decided by it and is observable — `module-code/top-level-await/fulfillment-order`
197    /// is exactly that assertion — so it cannot be "whatever order the vector happens to
198    /// have".
199    pub async_evaluation_order: u64,
200    /// §16.2.1.5.3.1's `[[PendingAsyncDependencies]]`.
201    pub pending_async_dependencies: usize,
202    /// §16.2.1.5.3.1's `[[AsyncParentModules]]`: who is waiting for this module.
203    pub async_parent_modules: Vec<Gc<ModuleRecord>>,
204    /// §16.2.1.5.3.1's `[[CycleRoot]]`; `None` means "this module".
205    pub cycle_root: Option<Gc<ModuleRecord>>,
206    /// §16.2.1.5.3.1's `[[DFSIndex]]`: where the depth-first walk reached this module.
207    pub dfs_index: usize,
208    /// §16.2.1.5.3.1's `[[DFSAncestorIndex]]`: the earliest index reachable from here.
209    ///
210    /// Equal to `dfs_index` exactly when this module is the root of its cycle, which is how
211    /// §16.2.1.5.3.1 step 17 knows where to stop popping the stack.
212    pub dfs_ancestor_index: usize,
213    /// `[[TopLevelCapability]]`: the promise a caller waits on for this module.
214    ///
215    /// Stored as the capability triple so both settling functions are available — the
216    /// module owns the promise, and whoever imports it chains onto the same one, which is
217    /// what makes the *second* `import()` of a waiting module resolve no earlier than the
218    /// first (`dynamic-import-of-waiting-module`).
219    pub top_level_capability: Option<(Gc<JsObject>, Value, Value)>,
220    /// What kind of module it is.
221    pub kind: ModuleKind,
222    /// The namespace object, built on first use.
223    pub namespace: Option<Gc<JsObject>>,
224    /// The deferred namespace object, built on first use.
225    ///
226    /// A second object rather than a flag on the first: the deferred namespace's whole
227    /// point is that reading it evaluates the module, and the eager one must stay usable on
228    /// a module that is still `Linked`. It is cached here so two `import defer` clauses for
229    /// one module hand back the same object, which the proposal requires.
230    pub deferred_namespace: Option<Gc<JsObject>>,
231    /// `import.meta`, built at load time.
232    pub import_meta: Option<Gc<JsObject>>,
233    /// The wrapper cell behind each `export * as ns from "m"`, keyed by `ns`.
234    ///
235    /// §16.2.1.6.3 `ResolveExport` identifies a binding by *(module, name)*, and the
236    /// ambiguity test compares those identities. A namespace re-export needs a cell in the
237    /// export table, and building a fresh one per lookup gave the same export two different
238    /// identities — so a name reached through two `export *` that both pass through one
239    /// `export * as ns` looked ambiguous. Caching makes the identity stable, which is what
240    /// `namespace-unambiguous-if-export-star-as-from` checks.
241    pub star_cells: BTreeMap<String, Gc<Cell>>,
242}
243
244impl Trace for ModuleRecord {
245    fn trace(&self, tracer: &mut Tracer) {
246        self.inner.borrow().trace(tracer);
247    }
248}
249
250impl Trace for ModuleInner {
251    fn trace(&self, tracer: &mut Tracer) {
252        if let Some(code) = &self.code {
253            tracer.visit(code);
254        }
255        for cell in &self.cells {
256            tracer.visit(cell);
257        }
258        for dependency in self.dependencies.iter().flatten() {
259            tracer.visit(dependency);
260        }
261        if let Some(namespace) = &self.namespace {
262            tracer.visit(namespace);
263        }
264        if let Some(namespace) = &self.deferred_namespace {
265            tracer.visit(namespace);
266        }
267        if let Some(error) = &self.evaluation_error {
268            error.trace(tracer);
269        }
270        for parent in &self.async_parent_modules {
271            tracer.visit(parent);
272        }
273        if let Some(root) = &self.cycle_root {
274            tracer.visit(root);
275        }
276        if let Some((promise, resolve, reject)) = &self.top_level_capability {
277            tracer.visit(promise);
278            resolve.trace(tracer);
279            reject.trace(tracer);
280        }
281        if let Some(meta) = &self.import_meta {
282            tracer.visit(meta);
283        }
284    }
285}
286
287/// A host-supplied module, before it is compiled.
288pub struct LoadedModule {
289    /// Canonical identity — the cache key, and how a cycle recognises itself.
290    pub name: String,
291    /// `import.meta.url` for this module.
292    pub url: String,
293    /// The file's bytes. Not necessarily UTF-8: a `bytes` module is arbitrary.
294    pub source: Vec<u8>,
295}
296
297/// How the host turns a specifier into bytes.
298///
299/// The engine cannot do this itself: resolving `./x.js` needs to know that the importer
300/// was a file, and where. A browser-shaped host would answer differently, so the host
301/// supplies this and the engine decides what to do with the bytes.
302pub trait ModuleLoader {
303    /// Resolve `specifier` relative to `referrer` and read it.
304    ///
305    /// `referrer` is empty for the entry module.
306    fn load(
307        &self,
308        specifier: &str,
309        attributes: &[(String, String)],
310        referrer: &str,
311    ) -> Result<LoadedModule, String>;
312
313    /// Load a native module, if this loader has one at `name`.
314    ///
315    /// The answer is a *record*, not bytes: a `.so` is not text to compile, it is a library
316    /// that hands back exports. `None` means "this name is not native", which sends the
317    /// engine on to [`ModuleLoader::load`] — so a loader that knows nothing about native
318    /// modules needs no change at all.
319    ///
320    /// `interp` is the interpreter doing the load, because the library's entry point takes
321    /// a `JSContext *` and will call back into this very interpreter.
322    fn load_native(
323        &self,
324        interp: &mut Interp<'_>,
325        name: &str,
326    ) -> Option<Result<Gc<ModuleRecord>, String>> {
327        let _ = (interp, name);
328        None
329    }
330
331    /// The name `specifier` resolves to from `referrer`, without reading anything.
332    ///
333    /// A precompiled module is registered under the name a *loader* would give it, so the
334    /// engine has to know that name before it can decide whether the module is already in
335    /// memory. Without this the only way to ask is [`ModuleLoader::load`], which reads the
336    /// file — and a product that carries its dependencies has no files to read.
337    ///
338    /// `None` means "this loader can only answer by loading", which is the behaviour a
339    /// loader that resolves against something other than text (an in-memory map, a
340    /// network) legitimately has. Precompiled modules are then matched after the load, by
341    /// the name the load reported.
342    fn resolve(&self, specifier: &str, referrer: &str) -> Option<String> {
343        let _ = (specifier, referrer);
344        None
345    }
346}
347
348/// What `ResolveExport` answered, including the two ways it can fail to name a binding.
349///
350/// §16.2.1.6.3 distinguishes them and so must the caller: **not found** is a missing export,
351/// while **ambiguous** is a module that must fail to link even though the name exists twice.
352/// Collapsing both into `Err` is what let the star loop treat an ambiguity as absence and
353/// resolve the name to whichever dependency happened to be listed first.
354enum Resolution {
355    Cell {
356        cell: Gc<Cell>,
357        /// The module the binding actually lives in.
358        module: Gc<ModuleRecord>,
359        /// Its name there — `*namespace*` for a namespace re-export.
360        binding: String,
361    },
362    NotFound,
363    Ambiguous,
364}
365
366impl Resolution {
367    /// Whether two resolutions name the **same binding**.
368    ///
369    /// §16.2.1.6.3 compares `[[Module]]` and `[[BindingName]]`, nothing else: two
370    /// `export *` paths that arrive at one binding are not ambiguous, and two paths that
371    /// arrive at different bindings are. Comparing the export *cells* instead was wrong for
372    /// `export * as ns from "m"`, where the cell belongs to the re-exporting module while the
373    /// binding belongs to `m` — so two modules that both re-export the same namespace looked
374    /// like two different bindings.
375    fn same_binding(&self, other: &Resolution) -> bool {
376        match (self, other) {
377            (
378                Resolution::Cell {
379                    module: a,
380                    binding: a_name,
381                    ..
382                },
383                Resolution::Cell {
384                    module: b,
385                    binding: b_name,
386                    ..
387                },
388            ) => a.ptr_eq(b) && a_name == b_name,
389            _ => false,
390        }
391    }
392}
393
394impl<'a> Interp<'a> {
395    /// The module registry: one entry per canonical name, so each file is compiled once.
396    pub fn module_registry(&self) -> &BTreeMap<String, Gc<ModuleRecord>> {
397        &self.modules
398    }
399
400    /// Evaluate `specifier` as the entry module, the way `qjs -m file.js` does.
401    pub fn run_main_module(&mut self, specifier: &str) -> JsResult<Value> {
402        let module = self.load_module(specifier, &[], "")?;
403        let name = module.with(|r| r.name.clone());
404        self.main_module_name = Some(name.clone());
405        // The record was built before the name was known, so `main` is stamped now.
406        if let Some(meta) = module.with(|r| r.import_meta.clone()) {
407            meta.define_data("main", Value::Bool(true));
408        }
409        self.link_module(&module)?;
410        self.module_stack.push(name);
411        let result = self.evaluate_module_and_wait(&module);
412        self.module_stack.pop();
413        result?;
414        self.module_namespace(&module)
415    }
416
417    /// Run a module whose bytecode the caller already has.
418    ///
419    /// This is `qjs`'s `-m` for an AOT binary: nothing is parsed or compiled, but the
420    /// module's *requests* still go through the host loader, so a precompiled entry
421    /// module can import ordinary source files. The blob's own file name is what those
422    /// requests are resolved against, which is why it has to travel in the blob rather
423    /// than be supplied at the call site.
424    pub fn run_precompiled_module(&mut self, code: CompiledFunction) -> JsResult<Value> {
425        let name = code
426            .filename
427            .clone()
428            .unwrap_or_else(|| "<bytecode>".to_string());
429        let url = name.clone();
430        let module = self.module_record_from_code(&name, &url, code)?;
431        self.main_module_name = Some(name.clone());
432        // Registered under its own name before linking, so a module that imports itself
433        // finds this record instead of re-entering the loader for a file that may not
434        // exist at all.
435        self.modules.insert(cache_key(&name, &[]), module.clone());
436        if let Some(meta) = module.with(|r| r.import_meta.clone()) {
437            meta.define_data("main", Value::Bool(true));
438        }
439        self.link_module(&module)?;
440        self.module_stack.push(name);
441        let result = self.evaluate_module_and_wait(&module);
442        self.module_stack.pop();
443        result?;
444        self.module_namespace(&module)
445    }
446
447    /// Register a module from bytecode, so a later import finds it without a loader.
448    ///
449    /// This is what an AOT product does with the modules it carries: the names are the
450    /// ones the *bundler* resolved, which are the ones this interpreter would have
451    /// resolved through the loader, so an `import "./dep.js"` lands here instead of on the
452    /// filesystem.
453    ///
454    /// The module is registered as `Unlinked`: nothing is wired up until something imports
455    /// it (or it is the entry), which is what keeps a bundle's registration order
456    /// irrelevant — a cycle among precompiled modules links the same way a cycle among
457    /// source files does.
458    pub fn register_module(&mut self, code: CompiledFunction) -> JsResult<String> {
459        let name = code.filename.clone().ok_or_else(|| {
460            Signal::Throw(self.make_error(
461                "InternalError",
462                "precompiled module has no name; it was serialized without its file name",
463            ))
464        })?;
465        let url = name.clone();
466        let record = self.module_record_from_code(&name, &url, code)?;
467        self.modules.insert(cache_key(&name, &[]), record);
468        Ok(name)
469    }
470
471    /// Register a JSON, text or bytes module from its bytes, by name.
472    ///
473    /// A data module is a value, not code, so it has no bytecode to carry: the bundle keeps
474    /// the file's bytes and the product hands them here. `attributes` is what decided the
475    /// kind at bundle time, and passing it again keeps the two ends from disagreeing about
476    /// a `.json` file imported as text.
477    pub fn register_data_module(
478        &mut self,
479        name: &str,
480        source: Vec<u8>,
481        attributes: &[(String, String)],
482    ) -> JsResult<()> {
483        let kind = match module_kind(name, attributes) {
484            Ok(kind) => kind,
485            Err(message) => return Err(Signal::Throw(self.make_error("TypeError", &message))),
486        };
487        let loaded = LoadedModule {
488            name: name.to_string(),
489            url: name.to_string(),
490            source,
491        };
492        let record = self.data_module_record(&loaded, kind)?;
493        self.modules.insert(cache_key(name, attributes), record);
494        Ok(())
495    }
496
497    /// Register a native module: a name and the exports a library handed back.
498    ///
499    /// This is what `JS_NewCModule` amounts to. The record is born evaluated and carries one
500    /// cell per export, so the namespace machinery — sorted names, read-only getters,
501    /// `[object Module]` — is the ordinary one rather than a second implementation for C
502    /// modules.
503    ///
504    /// The exports are in the order the library declared them, which is the order
505    /// `JS_AddModuleExport` was called in; the namespace sorts them, as it does for every
506    /// module.
507    pub fn register_native_module(
508        &mut self,
509        name: &str,
510        exports: Vec<(String, Value)>,
511    ) -> Gc<ModuleRecord> {
512        let mut cells = Vec::with_capacity(exports.len());
513        let mut entries = Vec::with_capacity(exports.len());
514        for (index, (export_name, value)) in exports.into_iter().enumerate() {
515            cells.push(self.new_cell(value));
516            entries.push(js_compile::bytecode::ExportEntry::Local {
517                export_name,
518                var_idx: index as u32,
519            });
520        }
521        let record = Gc::new(
522            self.heap,
523            ModuleRecord::new(ModuleInner {
524                name: name.to_string(),
525                url: name.to_string(),
526                code: None,
527                meta: js_compile::bytecode::ModuleMeta {
528                    requests: Vec::new(),
529                    imports: Vec::new(),
530                    exports: entries,
531                },
532                cells,
533                // A native module's exports are values, not bindings to wire up: there is
534                // nothing to resolve and nothing to run, so it starts evaluated. That is
535                // also what lets an ordinary module import one inside a cycle.
536                dependencies: Vec::new(),
537                status: ModuleStatus::Evaluated,
538                evaluation_error: None,
539                async_evaluation: false,
540                async_evaluation_order: 0,
541                pending_async_dependencies: 0,
542                async_parent_modules: Vec::new(),
543                cycle_root: None,
544                dfs_index: 0,
545                dfs_ancestor_index: 0,
546                top_level_capability: None,
547                kind: ModuleKind::Native,
548                namespace: None,
549                deferred_namespace: None,
550                import_meta: None,
551                star_cells: BTreeMap::new(),
552            }),
553        );
554        self.modules.insert(cache_key(name, &[]), record.clone());
555        record
556    }
557
558    /// Load and compile one module.
559    pub fn load_module(
560        &mut self,
561        specifier: &str,
562        attributes: &[(String, String)],
563        referrer: &str,
564    ) -> JsResult<Gc<ModuleRecord>> {
565        // A module that is already in memory — registered from bytecode, which is what an
566        // AOT product does with its bundle — must be found *before* the loader runs. The
567        // reference has the same ordering (`js_find_loaded_module` first, `js_module_loader`
568        // only if that misses); getting it the other way round makes a product carry a
569        // module and still report "could not load module filename" for it.
570        //
571        // With no loader installed at all, the textual rule is the only one there is: it is
572        // what an AOT product relies on, since its modules are registered under exactly the
573        // names that rule produces and it has no files to fall back to.
574        let resolved = match self.module_loader.as_ref() {
575            Some(loader) => loader.resolve(specifier, referrer),
576            None => Some(js_parse::normalize_specifier(referrer, specifier)),
577        };
578        if let Some(resolved) = &resolved {
579            if let Some(existing) = self.modules.get(&cache_key(resolved, attributes)) {
580                return Ok(existing.clone());
581            }
582        }
583        let Some(loader) = self.module_loader.take() else {
584            // Not in memory and nothing to read it from. Report it as the missing *file* it
585            // is, which is the reference's message for this case, rather than as an
586            // internal error about the host's setup.
587            let name = resolved.unwrap_or_else(|| specifier.to_string());
588            return Err(Signal::Throw(self.make_error(
589                "ReferenceError",
590                &format!("could not load module filename '{name}'"),
591            )));
592        };
593        // A native module is a record, not bytes: ask before reading anything. The name to
594        // ask about is the one textual resolution produced, so a loader does not have to
595        // repeat that rule.
596        let native_name = resolved.clone().unwrap_or_else(|| specifier.to_string());
597        let native = if attributes.is_empty() {
598            loader.load_native(self, &native_name)
599        } else {
600            // A C module has no `with { type: … }` form; an attribute means the loader
601            // must not treat this name as native.
602            None
603        };
604        let loaded = match native {
605            Some(Ok(record)) => {
606                self.module_loader = Some(loader);
607                let key = cache_key(&record.with(|r| r.name.clone()), attributes);
608                self.modules.insert(key, record.clone());
609                return Ok(record);
610            }
611            Some(Err(message)) => {
612                self.module_loader = Some(loader);
613                return Err(Signal::Throw(self.make_error("ReferenceError", &message)));
614            }
615            None => loader.load(specifier, attributes, referrer),
616        };
617        // Put the loader back whatever happened: it is the host's, and the interpreter
618        // only borrows it so that `&mut self` stays available for compiling.
619        self.module_loader = Some(loader);
620        let mut loaded = match loaded {
621            Ok(loaded) => loaded,
622            Err(message) => {
623                return Err(Signal::Throw(self.make_error("ReferenceError", &message)));
624            }
625        };
626        // A host-supplied name for the entry module wins over the path. Only the entry:
627        // `referrer` is empty for it and for nothing else, so a nested import keeps the name
628        // its specifier resolved to.
629        if referrer.is_empty()
630            && let Some(name) = &self.entry_module_name
631        {
632            loaded.name = name.clone();
633            loaded.url = name.clone();
634        }
635        // One record per *(name, attributes)*, so importing the same file twice runs it
636        // once — but importing it as JSON and as text is two modules with two contents,
637        // which `hello_module.js` does on purpose.
638        let key = cache_key(&loaded.name, attributes);
639        if let Some(existing) = self.modules.get(&key) {
640            return Ok(existing.clone());
641        }
642        let kind = match module_kind(&loaded.name, attributes) {
643            Ok(kind) => kind,
644            Err(message) => {
645                return Err(Signal::Throw(self.make_error("TypeError", &message)));
646            }
647        };
648        let record = match kind {
649            ModuleKind::JavaScript => self.compile_module_record(&loaded)?,
650            _ => self.data_module_record(&loaded, kind)?,
651        };
652        self.modules.insert(key, record.clone());
653        Ok(record)
654    }
655
656    /// Compile a JavaScript module and create its cells.
657    fn compile_module_record(&mut self, loaded: &LoadedModule) -> JsResult<Gc<ModuleRecord>> {
658        let source = match std::str::from_utf8(&loaded.source) {
659            Ok(source) => source,
660            Err(_) => {
661                return Err(Signal::Throw(self.make_error(
662                    "SyntaxError",
663                    &format!("{}: module source is not valid UTF-8", loaded.name),
664                )));
665            }
666        };
667        // Same shape as a script's compile error: the message, then `at <file>:<line>:<col>`
668        // unless the reference reports this one without a position. The file name is *not*
669        // part of the message — it belongs on the `at` line only.
670        let program = match js_parse::parse_module(source) {
671            Ok(program) => program,
672            Err(error) => {
673                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
674            }
675        };
676        let mut code = match js_compile::compile_module_with_source(&program, source) {
677            Ok(code) => code,
678            Err(error) => {
679                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
680            }
681        };
682        code.set_filename(&loaded.name);
683        self.module_record_from_code(&loaded.name, &loaded.url, code)
684    }
685
686    /// Build a module record around bytecode the caller already has.
687    ///
688    /// The one thing that separates this from [`Interp::compile_module_record`] is where
689    /// the bytecode came from — source, or a blob written by an AOT compiler. Everything
690    /// after that point is the same work: one cell per closure variable, a dependency slot
691    /// per request, `import.meta`, and the record itself. Keeping it in one place is what
692    /// makes a precompiled module behave like a compiled one rather than *almost* like one.
693    fn module_record_from_code(
694        &mut self,
695        name: &str,
696        url: &str,
697        code: CompiledFunction,
698    ) -> JsResult<Gc<ModuleRecord>> {
699        let meta = code
700            .module
701            .as_ref()
702            .map(|meta| (**meta).clone())
703            .unwrap_or_default();
704        let closure_vars = code.closure_vars.clone();
705        let compiled = Gc::new(self.heap, CompiledCode::new(code));
706        // One cell per closure variable. A lexical binding starts in its dead zone and a
707        // `var` as `undefined`; an import's cell is *replaced* during linking by the
708        // exporter's, which is what makes it live.
709        let mut cells = Vec::with_capacity(closure_vars.len());
710        for closure_var in &closure_vars {
711            let initial = if closure_var.is_lexical {
712                Value::Uninitialized
713            } else {
714                Value::Undefined
715            };
716            cells.push(self.new_cell(initial));
717        }
718        let dependencies = vec![None; meta.requests.len()];
719        let record = Gc::new(
720            self.heap,
721            ModuleRecord::new(ModuleInner {
722                name: name.to_string(),
723                url: url.to_string(),
724                code: Some(compiled),
725                meta,
726                cells,
727                dependencies,
728                status: ModuleStatus::Unlinked,
729                evaluation_error: None,
730                async_evaluation: false,
731                async_evaluation_order: 0,
732                pending_async_dependencies: 0,
733                async_parent_modules: Vec::new(),
734                cycle_root: None,
735                dfs_index: 0,
736                dfs_ancestor_index: 0,
737                top_level_capability: None,
738                kind: ModuleKind::JavaScript,
739                namespace: None,
740                deferred_namespace: None,
741                import_meta: None,
742                star_cells: BTreeMap::new(),
743            }),
744        );
745        self.install_import_meta(&record)?;
746        Ok(record)
747    }
748
749    /// A JSON, text or bytes module: one value, exported as `default`.
750    ///
751    /// The value is produced by calling the *builtin* rather than by reaching into the
752    /// JSON parser or the typed-array internals, so a data module behaves exactly like
753    /// `JSON.parse(text)` or `new Uint8Array(bytes)` written out by hand — one
754    /// implementation of each, not two.
755    fn data_module_record(
756        &mut self,
757        loaded: &LoadedModule,
758        kind: ModuleKind,
759    ) -> JsResult<Gc<ModuleRecord>> {
760        let value = match kind {
761            ModuleKind::Json => {
762                let text = String::from_utf8_lossy(&loaded.source).to_string();
763                let Some(json) = self.global_value("JSON") else {
764                    return Err(Signal::Throw(
765                        self.make_error("InternalError", "JSON is not installed"),
766                    ));
767                };
768                let Some(Value::Object(json)) = Some(json) else {
769                    unreachable!()
770                };
771                let Some(parse) = self.get_property(&json, "parse")? else {
772                    return Err(Signal::Throw(
773                        self.make_error("InternalError", "JSON.parse is not installed"),
774                    ));
775                };
776                let text = self.string(&text);
777                match self.call_value(parse, Value::Object(json), vec![text]) {
778                    Ok(value) => value,
779                    Err(Signal::Throw(reason)) => {
780                        let detail = self.describe_exception(&reason);
781                        return Err(Signal::Throw(self.make_error(
782                            "SyntaxError",
783                            &format!("{}: {}", loaded.name, detail),
784                        )));
785                    }
786                    Err(other) => return Err(other),
787                }
788            }
789            ModuleKind::Text => {
790                // Taken as UTF-8 with replacement: a text file that is not valid UTF-8
791                // still has to become a string.
792                let text = String::from_utf8_lossy(&loaded.source).to_string();
793                self.string(&text)
794            }
795            ModuleKind::Bytes => {
796                let numbers: Vec<Value> = loaded
797                    .source
798                    .iter()
799                    .map(|byte| Value::Int(*byte as i32))
800                    .collect();
801                let elements = self.new_array(numbers);
802                let Some(Value::Object(ctor)) = self.global_value("Uint8Array") else {
803                    return Err(Signal::Throw(
804                        self.make_error("InternalError", "Uint8Array is not installed"),
805                    ));
806                };
807                self.construct(
808                    Value::Object(ctor),
809                    Value::Object(elements.clone()),
810                    vec![Value::Object(elements)],
811                )?
812            }
813            ModuleKind::JavaScript | ModuleKind::Native => {
814                unreachable!("handled by `compile_module_record`")
815            }
816        };
817        let cell = self.new_cell(value.clone());
818        let record = Gc::new(
819            self.heap,
820            ModuleRecord::new(ModuleInner {
821                name: loaded.name.clone(),
822                url: loaded.url.clone(),
823                code: None,
824                meta: js_compile::bytecode::ModuleMeta {
825                    requests: Vec::new(),
826                    imports: Vec::new(),
827                    exports: vec![js_compile::bytecode::ExportEntry::Local {
828                        export_name: "default".to_string(),
829                        var_idx: 0,
830                    }],
831                },
832                cells: vec![cell],
833                dependencies: Vec::new(),
834                // Nothing to link and nothing to run: a data module is born evaluated,
835                // which is what lets `import x from "./m.json"` work inside a cycle.
836                status: ModuleStatus::Evaluated,
837                evaluation_error: None,
838                async_evaluation: false,
839                async_evaluation_order: 0,
840                pending_async_dependencies: 0,
841                async_parent_modules: Vec::new(),
842                cycle_root: None,
843                dfs_index: 0,
844                dfs_ancestor_index: 0,
845                top_level_capability: None,
846                kind,
847                namespace: None,
848                deferred_namespace: None,
849                import_meta: None,
850                star_cells: BTreeMap::new(),
851            }),
852        );
853        Ok(record)
854    }
855
856    /// A binding of the global object, if it exists.
857    fn global_value(&mut self, name: &str) -> Option<Value> {
858        let global = self.realm.global.clone();
859        self.get_property(&global, name).ok().flatten()
860    }
861
862    /// `import.meta` for `record`, built once.
863    fn install_import_meta(&mut self, record: &Gc<ModuleRecord>) -> JsResult<()> {
864        // §16.2.1.10 / HostGetImportMetaProperties: `import.meta` is an **ordinary object
865        // with a null prototype**. That is observable and test262 leans on it —
866        // `dynamic-import/assignment-expression/import-meta` does `import(import.meta)` and
867        // expects the promise to *reject with a `TypeError`*, which only happens if
868        // `ToString` cannot find a `toString` through a prototype. Giving it
869        // `Object.prototype` (as this did) made that conversion succeed and the import ask
870        // for a module named "[object Object]".
871        let meta = self.new_object(None);
872        let url = self.string(record.with(|r| r.url.clone()));
873        // Only the two properties the reference defines; a script can add its own.
874        meta.define_data("url", url);
875        meta.define_data("main", Value::Bool(false));
876        record.with_mut(|r| r.import_meta = Some(meta));
877        Ok(())
878    }
879
880    /// Resolve every import of `module` and validate its exports, depth-first.
881    pub fn link_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
882        match module.with(|r| r.status) {
883            // Already linked, or being linked right now — the latter is a cycle, and it is
884            // exactly why the status is set *before* recursing: a cycle stops here rather
885            // than recursing forever.
886            ModuleStatus::Linking
887            | ModuleStatus::Linked
888            | ModuleStatus::Evaluating
889            | ModuleStatus::EvaluatingAsync
890            | ModuleStatus::Evaluated => {
891                return Ok(());
892            }
893            ModuleStatus::Unlinked => {}
894        }
895        module.with_mut(|r| r.status = ModuleStatus::Linking);
896
897        let requests = module.with(|r| r.meta.requests.clone());
898        for (index, request) in requests.iter().enumerate() {
899            let referrer = module.with(|r| r.name.clone());
900            let dependency =
901                self.load_module(&request.specifier, &request.attributes, &referrer)?;
902            module.with_mut(|r| r.dependencies[index] = Some(dependency.clone()));
903            self.link_module(&dependency)?;
904        }
905
906        // Wire the cells. `import { x } from "m"` makes this module's cell *be* `m`'s, so
907        // a later assignment over there is visible here with no copying.
908        let imports = module.with(|r| r.meta.imports.clone());
909        for entry in &imports {
910            let dependency =
911                module.with(|r| r.dependencies.get(entry.module as usize).cloned().flatten());
912            let Some(dependency) = dependency else {
913                return Err(Signal::Throw(self.make_error(
914                    "InternalError",
915                    "an import names a module that was not loaded",
916                )));
917            };
918            if entry.is_star {
919                // `import defer * as ns` binds the deferred namespace — a different object
920                // from the eager one, and the only way a `defer` request is observable.
921                let namespace = if entry.phase == ImportPhase::Defer {
922                    self.module_deferred_namespace(&dependency)?
923                } else {
924                    self.module_namespace(&dependency)?
925                };
926                let cell = module.with(|r| r.cells[entry.var_idx as usize].clone());
927                cell.set(namespace);
928                continue;
929            }
930            let cell = self.resolve_export(&dependency, &entry.name)?;
931            module.with_mut(|r| r.cells[entry.var_idx as usize] = cell);
932        }
933
934        // Validate: `export { a } from "m"` where `m` has no `a` is a link error, and
935        // saying so now beats an `undefined` that surfaces much later.
936        let exports = module.with(|r| r.meta.exports.clone());
937        for entry in &exports {
938            if let js_compile::bytecode::ExportEntry::Indirect {
939                export_name,
940                module: index,
941                import_name,
942            } = entry
943            {
944                let dependency =
945                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
946                let Some(dependency) = dependency else {
947                    continue;
948                };
949                // A namespace re-export names the dependency's *namespace*, which is not an
950                // export of it and therefore has nothing to validate.
951                if import_name == "*namespace*" {
952                    continue;
953                }
954                if self.resolve_export(&dependency, import_name).is_err() {
955                    let dependency_name = dependency.with(|r| r.name.clone());
956                    return Err(Signal::Throw(self.make_error(
957                        "SyntaxError",
958                        &format!(
959                            "Could not find export '{import_name}' in module '{dependency_name}' (re-exported as '{export_name}')"
960                        ),
961                    )));
962                }
963            }
964        }
965
966        // Create the module's hoisted bindings *now*, while linking — before any body
967        // runs anywhere in the graph.
968        //
969        // This is the whole trick behind cyclic imports. The body's prologue is
970        // `push_this; if_false <body>`, so calling it with a truthy `this` runs only the
971        // hoisted declarations and returns. Doing that for every module during linking
972        // means that when evaluation finally starts, every exported function in the
973        // cycle already exists — which is why `b.js` can see `a`'s function even though
974        // `a.js` has not run yet.
975        self.hoist_module_bindings(module)?;
976
977        module.with_mut(|r| r.status = ModuleStatus::Linked);
978        Ok(())
979    }
980
981    /// Run `module`'s prologue only, creating its hoisted bindings.
982    fn hoist_module_bindings(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
983        let Some(code) = module.with(|r| r.code.clone()) else {
984            // A JSON/text module has nothing to hoist.
985            return Ok(());
986        };
987        let env = self.module_env(module);
988        self.execute(code, env, Value::Bool(true), Vec::new(), Value::Undefined)
989            .map(|_| ())
990    }
991
992    /// The closure environment a module body runs in: one cell per closure variable.
993    fn module_env(&mut self, module: &Gc<ModuleRecord>) -> Gc<ClosureEnv> {
994        let cells = module.with(|r| r.cells.clone());
995        Gc::new(
996            self.heap,
997            ClosureEnv {
998                cells,
999                eval_scope: None,
1000                local_vars: None,
1001                local_phase: 0,
1002            },
1003        )
1004    }
1005
1006    /// The cell behind `name` in `module`, following re-exports.
1007    pub fn resolve_export(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Gc<Cell>> {
1008        match self.resolve_export_inner(module, name, 0)? {
1009            Resolution::Cell { cell, .. } => Ok(cell),
1010            Resolution::NotFound => Err(self.missing_export(module, name)),
1011            Resolution::Ambiguous => Err(self.ambiguous_export(module, name)),
1012        }
1013    }
1014
1015    /// The wrapper cell behind a module's *own* namespace, cached so its identity is stable.
1016    ///
1017    /// Same reason as `star_cells`: the ambiguity test compares `(module, binding)`, and an
1018    /// `import * as ns` re-export resolves to `{ m, *namespace* }`, so two paths reaching the
1019    /// same module's namespace must agree that they name one binding.
1020    fn namespace_cell(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<Cell>> {
1021        self.namespace_cell_of_phase(module, false)
1022    }
1023
1024    /// The same, but the wrapper holds the *deferred* namespace.
1025    fn deferred_namespace_cell(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<Cell>> {
1026        self.namespace_cell_of_phase(module, true)
1027    }
1028
1029    fn namespace_cell_of_phase(
1030        &mut self,
1031        module: &Gc<ModuleRecord>,
1032        deferred: bool,
1033    ) -> JsResult<Gc<Cell>> {
1034        let key = if deferred {
1035            "*deferred-namespace*"
1036        } else {
1037            "*namespace*"
1038        };
1039        if let Some(cell) = module.with(|r| r.star_cells.get(key).cloned()) {
1040            return Ok(cell);
1041        }
1042        let namespace = if deferred {
1043            self.module_deferred_namespace(module)?
1044        } else {
1045            self.module_namespace(module)?
1046        };
1047        let cell = self.new_cell(namespace);
1048        module.with_mut(|r| r.star_cells.insert(key.to_string(), cell.clone()));
1049        Ok(cell)
1050    }
1051
1052    /// Why a name that two `export *` declarations both provide cannot be resolved.
1053    ///
1054    /// §16.2.1.6.3 `ResolveExport` returns **ambiguous** rather than picking one, and
1055    /// `GetExportedNames`/`ResolveExport` feed link-time validation: a module with an
1056    /// ambiguous name fails to link, so `import()` of it rejects with a `SyntaxError`.
1057    /// Taking the first success instead — which is what the star loop used to do — made the
1058    /// module load fine and hand back a namespace, and test262's `instn-iee-err-ambiguous`
1059    /// family checks exactly that rejection.
1060    fn ambiguous_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
1061        let module_name = module.with(|r| r.name.clone());
1062        Signal::Throw(self.make_error(
1063            "SyntaxError",
1064            &format!("Ambiguous export '{name}' in module '{module_name}'"),
1065        ))
1066    }
1067
1068    fn resolve_export_inner(
1069        &mut self,
1070        module: &Gc<ModuleRecord>,
1071        name: &str,
1072        depth: usize,
1073    ) -> JsResult<Resolution> {
1074        // A pathological chain (`a` exports from `b`, `b` from `a`) would otherwise
1075        // recurse until the Rust stack gives out.
1076        if depth > 64 {
1077            return Err(Signal::Throw(
1078                self.make_error("SyntaxError", "circular re-export chain"),
1079            ));
1080        }
1081        let exports = module.with(|r| r.meta.exports.clone());
1082        // An explicit export wins over any `export *`.
1083        for entry in &exports {
1084            match entry {
1085                js_compile::bytecode::ExportEntry::Local {
1086                    export_name,
1087                    var_idx,
1088                } if export_name == name => {
1089                    return Ok(Resolution::Cell {
1090                        cell: module.with(|r| r.cells[*var_idx as usize].clone()),
1091                        module: module.clone(),
1092                        binding: name.to_string(),
1093                    });
1094                }
1095                js_compile::bytecode::ExportEntry::Indirect {
1096                    export_name,
1097                    module: index,
1098                    import_name,
1099                } if export_name == name => {
1100                    let dependency =
1101                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
1102                    let Some(dependency) = dependency else {
1103                        return Ok(Resolution::NotFound);
1104                    };
1105                    // `import * as ns from "m"; export { ns }` — §16.2.1.6.3 step 7 resolves
1106                    // to `{ [[Module]]: m, [[BindingName]]: namespace }`, so the identity is
1107                    // the *target* module and not this one.
1108                    if import_name == "*namespace*" {
1109                        // A `defer` request re-exported this way still hands back the
1110                        // *deferred* namespace: the phase belongs to the request, and
1111                        // reading through the export is what has to trigger evaluation.
1112                        let phase = module.with(|r| {
1113                            r.meta
1114                                .requests
1115                                .get(*index as usize)
1116                                .map(|request| request.phase)
1117                        });
1118                        let cell = if phase == Some(ImportPhase::Defer) {
1119                            self.deferred_namespace_cell(&dependency)?
1120                        } else {
1121                            self.namespace_cell(&dependency)?
1122                        };
1123                        return Ok(Resolution::Cell {
1124                            cell,
1125                            module: dependency,
1126                            binding: "*namespace*".to_string(),
1127                        });
1128                    }
1129                    return self.resolve_export_inner(&dependency, import_name, depth + 1);
1130                }
1131                js_compile::bytecode::ExportEntry::StarAs { export_name, .. }
1132                    if export_name == name =>
1133                {
1134                    // The namespace of the re-exported module, wrapped in a cell so the
1135                    // export table stays uniform. The cell is **cached per name**: the
1136                    // ambiguity test below compares binding identities, and a fresh cell on
1137                    // every lookup made one export look like two.
1138                    let target = module.with(|r| {
1139                        r.meta.exports.iter().find_map(|entry| match entry {
1140                            js_compile::bytecode::ExportEntry::StarAs {
1141                                export_name,
1142                                module: index,
1143                            } if export_name == name => Some(*index),
1144                            _ => None,
1145                        })
1146                    });
1147                    let Some(index) = target else {
1148                        return Ok(Resolution::NotFound);
1149                    };
1150                    let dependency =
1151                        module.with(|r| r.dependencies.get(index as usize).cloned().flatten());
1152                    let Some(dependency) = dependency else {
1153                        return Ok(Resolution::NotFound);
1154                    };
1155                    if let Some(cell) = module.with(|r| r.star_cells.get(name).cloned()) {
1156                        return Ok(Resolution::Cell {
1157                            cell,
1158                            module: dependency,
1159                            binding: "*namespace*".to_string(),
1160                        });
1161                    }
1162                    let namespace = self.star_namespace(module, name)?;
1163                    let cell = self.new_cell(namespace);
1164                    module.with_mut(|r| r.star_cells.insert(name.to_string(), cell.clone()));
1165                    return Ok(Resolution::Cell {
1166                        cell,
1167                        module: dependency,
1168                        binding: "*namespace*".to_string(),
1169                    });
1170                }
1171                _ => {}
1172            }
1173        }
1174        // `export * from "m"`: forwarded names are visible only if nothing above claimed
1175        // them, which is why this is a second pass.
1176        //
1177        // Two stars that reach the **same** binding are not ambiguous — `export * from "a";
1178        // export * from "b"` where both re-export `c`'s `x` resolves to one thing. Two that
1179        // reach different bindings are, and the comparison is on the binding itself (the
1180        // module's cell for that name), not on the name.
1181        let mut found: Option<Resolution> = None;
1182        for entry in &exports {
1183            if let js_compile::bytecode::ExportEntry::Star { module: index } = entry {
1184                let dependency =
1185                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
1186                let Some(dependency) = dependency else {
1187                    continue;
1188                };
1189                match self.resolve_export_inner(&dependency, name, depth + 1)? {
1190                    resolution @ Resolution::Cell { .. } => match &found {
1191                        None => found = Some(resolution),
1192                        Some(previous) if !previous.same_binding(&resolution) => {
1193                            return Ok(Resolution::Ambiguous);
1194                        }
1195                        Some(_) => {}
1196                    },
1197                    Resolution::NotFound => {}
1198                    // A nested ambiguity is not ours to resolve: it makes *this* name
1199                    // ambiguous too, which is what the caller needs to hear.
1200                    Resolution::Ambiguous => return Ok(Resolution::Ambiguous),
1201                }
1202            }
1203        }
1204        Ok(found.unwrap_or(Resolution::NotFound))
1205    }
1206
1207    fn missing_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
1208        let module_name = module.with(|r| r.name.clone());
1209        // The reference's wording, kept verbatim: an error message is part of the
1210        // behaviour a user sees, and `qjs` says "Could not find export".
1211        Signal::Throw(self.make_error(
1212            "SyntaxError",
1213            &format!("Could not find export '{name}' in module '{module_name}'"),
1214        ))
1215    }
1216
1217    /// The namespace behind `export * as ns from "m"`.
1218    fn star_namespace(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Value> {
1219        let exports = module.with(|r| r.meta.exports.clone());
1220        for entry in &exports {
1221            if let js_compile::bytecode::ExportEntry::StarAs {
1222                export_name,
1223                module: index,
1224            } = entry
1225                && export_name == name
1226            {
1227                let dependency =
1228                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
1229                let Some(dependency) = dependency else {
1230                    continue;
1231                };
1232                return self.module_namespace(&dependency);
1233            }
1234        }
1235        Ok(Value::Undefined)
1236    }
1237
1238    /// The names `module` exports, sorted the way §16.2.1.6 requires.
1239    pub fn module_export_names(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Vec<String>> {
1240        let mut names: Vec<String> = Vec::new();
1241        self.collect_export_names(module, &mut names, 0)?;
1242        names.sort();
1243        names.dedup();
1244        Ok(names)
1245    }
1246
1247    fn collect_export_names(
1248        &mut self,
1249        module: &Gc<ModuleRecord>,
1250        out: &mut Vec<String>,
1251        depth: usize,
1252    ) -> JsResult<()> {
1253        if depth > 64 {
1254            return Ok(());
1255        }
1256        let exports = module.with(|r| r.meta.exports.clone());
1257        for entry in &exports {
1258            match entry {
1259                js_compile::bytecode::ExportEntry::Local { export_name, .. }
1260                | js_compile::bytecode::ExportEntry::Indirect { export_name, .. }
1261                | js_compile::bytecode::ExportEntry::StarAs { export_name, .. } => {
1262                    out.push(export_name.clone());
1263                }
1264                js_compile::bytecode::ExportEntry::Star { module: index } => {
1265                    let dependency =
1266                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
1267                    if let Some(dependency) = dependency {
1268                        let mut forwarded = Vec::new();
1269                        self.collect_export_names(&dependency, &mut forwarded, depth + 1)?;
1270                        // `export *` never forwards `default` (§16.2.1.6.2).
1271                        out.extend(forwarded.into_iter().filter(|name| name != "default"));
1272                    }
1273                }
1274            }
1275        }
1276        Ok(())
1277    }
1278
1279    /// The namespace object of `module`, built on first use.
1280    ///
1281    /// An ordinary object with one read-only getter per export, inserted in sorted order.
1282    /// The getter reads the cell, which is what makes the binding live: `export let x`
1283    /// followed by `x = 1` in the exporting module is visible here without copying.
1284    pub fn module_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
1285        self.build_namespace(module, false)
1286    }
1287
1288    /// The *deferred* namespace object of `module`, built on first use.
1289    ///
1290    /// Identical to [`Interp::module_namespace`] in every observable way except one: reading
1291    /// it evaluates the module first. That is import-defer's `[[Deferred]]`, which is a
1292    /// property of the *object*, not of the module — one module can be imported both ways
1293    /// and the two namespaces are distinct objects.
1294    pub fn module_deferred_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
1295        self.build_namespace(module, true)
1296    }
1297
1298    fn build_namespace(&mut self, module: &Gc<ModuleRecord>, deferred: bool) -> JsResult<Value> {
1299        let cached = module.with(|r| {
1300            if deferred {
1301                r.deferred_namespace.clone()
1302            } else {
1303                r.namespace.clone()
1304            }
1305        });
1306        if let Some(namespace) = cached {
1307            return Ok(Value::Object(namespace));
1308        }
1309        let names = self.module_export_names(module)?;
1310        let function_proto = self.realm.function_proto.clone();
1311        // §10.4.6.1: a namespace's `[[Prototype]]` is **null**.
1312        //
1313        // Not `Object.prototype` with things taken away: `Object.getPrototypeOf(ns)` is
1314        // `null` and `ns instanceof Object` is `false`, which test262 asserts directly in
1315        // both namespace families. Handing it `object_proto` also leaked every `Object.prototype`
1316        // member into the namespace, so `ns.hasOwnProperty` answered a function.
1317        let namespace = self.new_object(None);
1318        namespace.set_module_namespace();
1319        for name in &names {
1320            // §16.2.1.5.2 `GetModuleNamespace` keeps only the **unambiguous** names: a name
1321            // that two `export *` provide is left out of the namespace rather than making
1322            // the module unloadable. Importing it is still an error, which is why
1323            // `resolve_export` reports ambiguity — but a namespace is a menu, and a dish two
1324            // suppliers disagree about is simply not on it (`omitted-from-namespace`).
1325            let cell = match self.resolve_export_inner(module, name, 0)? {
1326                Resolution::Cell { cell, .. } => cell,
1327                Resolution::NotFound | Resolution::Ambiguous => continue,
1328            };
1329            let getter = JsObject::function(
1330                self.heap,
1331                Some(function_proto.clone()),
1332                Callable::ModuleBinding { cell },
1333            );
1334            namespace.define(
1335                name,
1336                Property {
1337                    value: None,
1338                    getter: Some(Value::Object(getter)),
1339                    setter: None,
1340                    writable: false,
1341                    enumerable: true,
1342                    configurable: false,
1343                    descriptor_fields: None,
1344                },
1345            );
1346        }
1347        // A namespace reports `[object Module]`, and cannot gain properties. A *deferred*
1348        // one says "Deferred Module" — the one visible difference between the two objects,
1349        // and what a test can use to tell them apart.
1350        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1351        let tag = self.string(if deferred {
1352            "Deferred Module"
1353        } else {
1354            "Module"
1355        });
1356        namespace.define_key(&tag_key, Property::with_attributes(tag, false, false));
1357        self.object_prevent_extensions(&namespace)?;
1358        if deferred {
1359            namespace.set_deferred_namespace_module(module.clone());
1360        }
1361        module.with_mut(|r| {
1362            if deferred {
1363                r.deferred_namespace = Some(namespace.clone());
1364            } else {
1365                r.namespace = Some(namespace.clone());
1366            }
1367        });
1368        Ok(Value::Object(namespace))
1369    }
1370
1371    /// §16.2.1.5.3.2 `Evaluate()` — start evaluating `module`, answer its completion promise.
1372    ///
1373    /// Nearly every caller of the old `evaluate_module_body` wants this instead, because
1374    /// with top-level `await` "evaluating" is no longer a call that returns when it is
1375    /// done: it is a *promise*. The one thing the promise guarantees is that whoever holds
1376    /// it learns when the graph finished, which is what `import()` and the entry point both
1377    /// need.
1378    ///
1379    /// `[[TopLevelCapability]]` is per **cycle root**, not per module, and it is created
1380    /// once: a second `import()` of a module that is still waiting chains onto the very
1381    /// same promise, so it cannot observe a completion the first one has not seen yet
1382    /// (`module-code/top-level-await/dynamic-import-of-waiting-module`).
1383    pub fn evaluate_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<JsObject>> {
1384        // Already under way, or finished: the promise belongs to the cycle root.
1385        let root = match module.with(|r| r.status) {
1386            ModuleStatus::EvaluatingAsync | ModuleStatus::Evaluated => {
1387                let root = cycle_root_of(module);
1388                module.with_mut(|r| r.cycle_root = Some(root.clone()));
1389                root
1390            }
1391            _ => module.clone(),
1392        };
1393        if let Some((promise, _, _)) = root.with(|r| r.top_level_capability.clone()) {
1394            return Ok(promise);
1395        }
1396        let (capability, resolve, reject) = self.new_promise_capability();
1397        root.with_mut(|r| r.top_level_capability = Some((capability.clone(), resolve, reject)));
1398
1399        if root.with(|r| r.status) != ModuleStatus::Linked {
1400            // Started by someone else and finished before we got here; the promise was
1401            // created above for that case and is settled below.
1402            self.settle_from_record(&root);
1403            return Ok(capability);
1404        }
1405
1406        let mut stack: Vec<Gc<ModuleRecord>> = Vec::new();
1407        let mut index = 0usize;
1408        match self.inner_module_evaluation(&root, &mut stack, &mut index, false) {
1409            Ok(()) => {
1410                // A cycle that became async keeps its promise for the async machinery to
1411                // settle; everything else is done and settles itself.
1412                if !root.with(|r| r.async_evaluation) {
1413                    self.settle_from_record(&root);
1414                    debug_assert_eq!(root.with(|r| r.status), ModuleStatus::Evaluated);
1415                }
1416            }
1417            Err(Signal::Throw(reason)) => {
1418                // §16.2.1.5.3.2 step 5.c: every module still on the stack failed with the
1419                // same completion. Leaving them `Evaluating` would let a later `import()` of
1420                // one of them run its body again.
1421                for failed in stack.drain(..) {
1422                    failed.with_mut(|r| {
1423                        if r.status == ModuleStatus::Evaluating
1424                            || r.status == ModuleStatus::EvaluatingAsync
1425                        {
1426                            r.evaluation_error = Some(reason.clone());
1427                            r.status = ModuleStatus::Evaluated;
1428                            r.async_evaluation = false;
1429                            r.cycle_root = Some(root.clone());
1430                        }
1431                    });
1432                }
1433                let (_, _, reject_fn) = root
1434                    .with(|r| r.top_level_capability.clone())
1435                    .expect("just created");
1436                self.call_value(reject_fn, Value::Undefined, vec![reason])?;
1437            }
1438            Err(other) => return Err(other),
1439        }
1440        Ok(capability)
1441    }
1442
1443    /// Evaluate `module` and drive the job queue until it is done.
1444    ///
1445    /// This is what the *host* does — `qjs -m file.js` cannot return a promise, so the entry
1446    /// point blocks — and it is the only place in this engine that waits on module
1447    /// evaluation. Everything inside the graph is promise-driven so that a module with a
1448    /// top-level `await` defers itself and nothing else.
1449    pub fn evaluate_module_and_wait(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
1450        let promise = self.evaluate_module(module)?;
1451        self.drain_jobs()?;
1452        match self
1453            .promise_state(&promise)
1454            .map(|state| state.borrow().status.clone())
1455        {
1456            Some(crate::object::PromiseStatus::Fulfilled(_)) => Ok(()),
1457            Some(crate::object::PromiseStatus::Rejected(reason)) => Err(Signal::Throw(reason)),
1458            Some(crate::object::PromiseStatus::Pending) => Err(Signal::Throw(self.make_error(
1459                "TypeError",
1460                "promise is pending: top-level await never settled",
1461            ))),
1462            None => Ok(()),
1463        }
1464    }
1465
1466    /// §16.2.1.5.3.1 `EvaluateSync(module)` — run a module to completion *now*.
1467    ///
1468    /// The entry point behind `EnsureDeferredNamespaceEvaluation`, and a genuinely different
1469    /// one from [`Interp::evaluate_module`]: it does not create a capability, it does not
1470    /// wait, and it does not park. The caller has already asked
1471    /// [`Interp::ready_for_sync_execution`] and been told that nothing on the graph is
1472    /// suspended, so every body it reaches can run to its end synchronously.
1473    fn evaluate_module_sync(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
1474        match module.with(|r| r.status) {
1475            ModuleStatus::Evaluated => {
1476                return match module.with(|r| r.evaluation_error.clone()) {
1477                    Some(error) => Err(Signal::Throw(error)),
1478                    None => Ok(()),
1479                };
1480            }
1481            ModuleStatus::Evaluating | ModuleStatus::EvaluatingAsync => {
1482                return Err(self.type_error(
1483                    "cannot read a deferred module namespace while its module is evaluating",
1484                ));
1485            }
1486            _ => {}
1487        }
1488        let mut stack = Vec::new();
1489        let mut index = 0usize;
1490        match self.inner_module_evaluation(module, &mut stack, &mut index, true) {
1491            Ok(()) => Ok(()),
1492            Err(Signal::Throw(reason)) => {
1493                for failed in stack.drain(..) {
1494                    failed.with_mut(|r| {
1495                        r.evaluation_error = Some(reason.clone());
1496                        r.status = ModuleStatus::Evaluated;
1497                    });
1498                }
1499                Err(Signal::Throw(reason))
1500            }
1501            Err(other) => Err(other),
1502        }
1503    }
1504
1505    /// Settle a finished module's top-level capability from its recorded outcome.
1506    ///
1507    /// A no-op when the module is not finished yet, which is the async case: there the
1508    /// settlement arrives through the body's promise instead.
1509    fn settle_from_record(&mut self, module: &Gc<ModuleRecord>) {
1510        if module.with(|r| r.status) != ModuleStatus::Evaluated {
1511            return;
1512        }
1513        let Some((promise, resolve, reject)) = module.with(|r| r.top_level_capability.clone())
1514        else {
1515            return;
1516        };
1517        if self.promise_state(&promise).is_some_and(|state| {
1518            !matches!(state.borrow().status, crate::object::PromiseStatus::Pending)
1519        }) {
1520            return;
1521        }
1522        match module.with(|r| r.evaluation_error.clone()) {
1523            Some(error) => {
1524                let _ = self.call_value(reject, Value::Undefined, vec![error]);
1525            }
1526            None => {
1527                let _ = self.call_value(resolve, Value::Undefined, vec![Value::Undefined]);
1528            }
1529        }
1530    }
1531
1532    /// §16.2.1.5.3.1 `InnerModuleEvaluation`.
1533    ///
1534    /// Depth-first, once each, with the DFS indices the spec uses to find cycles and the
1535    /// async bookkeeping that decides who executes and in what order. A sync module runs
1536    /// its body here and is done; an async one starts its body, parks in
1537    /// `EvaluatingAsync`, and is finished later by
1538    /// [`Interp::async_module_execution_fulfilled`].
1539    fn inner_module_evaluation(
1540        &mut self,
1541        module: &Gc<ModuleRecord>,
1542        stack: &mut Vec<Gc<ModuleRecord>>,
1543        index: &mut usize,
1544        sync_only: bool,
1545    ) -> JsResult<()> {
1546        // Already started, or finished: follow a cycle root and report a stored failure.
1547        if matches!(
1548            module.with(|r| r.status),
1549            ModuleStatus::EvaluatingAsync | ModuleStatus::Evaluated
1550        ) {
1551            if let Some(error) = module.with(|r| r.evaluation_error.clone()) {
1552                return Err(Signal::Throw(error));
1553            }
1554            return Ok(());
1555        }
1556        // On the stack right now: a cycle, which terminates here.
1557        if module.with(|r| r.status) == ModuleStatus::Evaluating {
1558            return Ok(());
1559        }
1560        module.with_mut(|r| {
1561            r.status = ModuleStatus::Evaluating;
1562            r.dfs_index = *index;
1563            r.dfs_ancestor_index = *index;
1564            r.pending_async_dependencies = 0;
1565        });
1566        *index += 1;
1567        stack.push(module.clone());
1568
1569        // The requests, flattened the way §16.2.1.5.3.1 asks: one entry per request, except
1570        // that a `defer` request contributes its *asynchronous* transitive dependencies and
1571        // not itself. That is what keeps
1572        // `import defer * as ns from "./later.js"` from running `later.js` while still
1573        // running `later.js`'s own top-level awaits, whose ordering no importer may move.
1574        let requests = module.with(|r| r.meta.requests.clone());
1575        let mut evaluation_list: Vec<Gc<ModuleRecord>> = Vec::new();
1576        let mut seen: Vec<usize> = Vec::new();
1577        for (position, request) in requests.iter().enumerate() {
1578            let Some(required) = module.with(|r| r.dependencies.get(position).cloned().flatten())
1579            else {
1580                continue;
1581            };
1582            if request.phase == ImportPhase::Defer {
1583                self.gather_asynchronous_transitive_dependencies(
1584                    &required,
1585                    &mut seen,
1586                    &mut evaluation_list,
1587                );
1588            } else if !evaluation_list.iter().any(|m| m.ptr_eq(&required)) {
1589                evaluation_list.push(required);
1590            }
1591        }
1592
1593        for required in &evaluation_list {
1594            self.inner_module_evaluation(required, stack, index, sync_only)?;
1595            // §16.2.1.5.3.1 step 11.c: what the required module's *state* means for us.
1596            //
1597            // `evaluating` means it is above us on the stack — a cycle — and its ancestor
1598            // index is ours. Anything else is finished or parked, and a parked one is a
1599            // dependency we will have to wait for.
1600            //
1601            // The `evaluating` case still has to be checked for `[[AsyncEvaluation]]`, and
1602            // that is the whole point of `pending-async-dep-from-cycle`: a module that is
1603            // *still on the stack* has nevertheless already run its own request loop and
1604            // parked at its top-level `await`, so it holds an `[[AsyncEvaluationOrder]]`
1605            // while its status is still `evaluating`. Step 11.c.v tests that field on
1606            // `requiredModule` **as it stands** — only step 11.c.iv replaces it with the
1607            // cycle root, and that branch is the other one. Skipping the test here made the
1608            // importer believe it had no async dependency and run its body before the cycle
1609            // leaf had finished.
1610            let status = required.with(|r| r.status);
1611            let (waiting_on, parked) = if status == ModuleStatus::Evaluating {
1612                let ancestor = required.with(|r| r.dfs_ancestor_index);
1613                module.with_mut(|r| r.dfs_ancestor_index = r.dfs_ancestor_index.min(ancestor));
1614                let parked = required.with(|r| r.async_evaluation);
1615                (required.clone(), parked)
1616            } else {
1617                let root = cycle_root_of(required);
1618                root.with_mut(|r| r.cycle_root = Some(root.clone()));
1619                if let Some(error) = root.with(|r| r.evaluation_error.clone()) {
1620                    return Err(Signal::Throw(error));
1621                }
1622                let parked = root.with(|r| r.async_evaluation);
1623                (root, parked)
1624            };
1625            // `sync_only` is `EvaluateSync`, which reaches a module through a deferred
1626            // namespace read rather than through `InnerModuleEvaluation`'s own recursion.
1627            // `ReadyForSyncExecution` has already established that nothing on the chain is
1628            // *actually* waiting — an `evaluated` module short-circuits the walk even when
1629            // its cycle root is parked — so counting the pending dependency here would park
1630            // a module that the proposal requires to run right now.
1631            if parked && !sync_only {
1632                module.with_mut(|r| r.pending_async_dependencies += 1);
1633                waiting_on.with_mut(|r| r.async_parent_modules.push(module.clone()));
1634            }
1635        }
1636
1637        // §16.2.1.5.3.1 steps 12–14: run it, start it, or park it.
1638        let pending = module.with(|r| r.pending_async_dependencies);
1639        if sync_only {
1640            // `EvaluateSync`: run the body here, whatever the request list said. A module
1641            // with top-level `await` cannot be reached this way — `ReadyForSyncExecution`
1642            // refuses it — so this is the plain synchronous execution.
1643            self.execute_module_body_only(module)?;
1644            module.with_mut(|r| r.status = ModuleStatus::Evaluated);
1645        } else if pending > 0 {
1646            module.with_mut(|r| {
1647                r.async_evaluation = true;
1648                r.async_evaluation_order = self.next_module_async_evaluation_order;
1649            });
1650            self.next_module_async_evaluation_order += 1;
1651        } else if module.has_tla() {
1652            module.with_mut(|r| {
1653                r.async_evaluation = true;
1654                r.async_evaluation_order = self.next_module_async_evaluation_order;
1655            });
1656            self.next_module_async_evaluation_order += 1;
1657            self.execute_async_module(module)?;
1658        } else {
1659            self.execute_module_body_only(module)?;
1660        }
1661
1662        // §16.2.1.5.3.1 steps 15–17: when we are the root of the cycle we just closed, pop
1663        // it. Modules that stayed sync are finished; the ones that parked become
1664        // `EvaluatingAsync` and remember who owns their completion.
1665        let index_here = module.with(|r| r.dfs_index);
1666        let ancestor_here = module.with(|r| r.dfs_ancestor_index);
1667        if index_here == ancestor_here {
1668            loop {
1669                let Some(popped) = stack.pop() else { break };
1670                popped.with_mut(|r| {
1671                    r.status = if r.async_evaluation && !sync_only {
1672                        ModuleStatus::EvaluatingAsync
1673                    } else {
1674                        ModuleStatus::Evaluated
1675                    };
1676                    r.cycle_root = Some(module.clone());
1677                });
1678                if popped.ptr_eq(module) {
1679                    break;
1680                }
1681            }
1682        }
1683        Ok(())
1684    }
1685
1686    /// Run `module`'s body once, as an ordinary synchronous call.
1687    ///
1688    /// The hoisted bindings already exist: `link_module` ran the prologue pass with a truthy
1689    /// `this`, which is what the guard in the compiled prefix detects. Here the receiver is
1690    /// `undefined`, so the body itself runs.
1691    fn execute_module_body_only(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
1692        let Some(code) = module.with(|r| r.code.clone()) else {
1693            // A JSON/text/native module has no body; its value is already in its cell.
1694            return Ok(());
1695        };
1696        let name = module.with(|r| r.name.clone());
1697        let env = self.module_env(module);
1698        self.module_stack.push(name);
1699        let result = self.execute(code, env, Value::Undefined, Vec::new(), Value::Undefined);
1700        self.module_stack.pop();
1701        result.map(|_| ())
1702    }
1703
1704    /// §16.2.1.5.3.1 `ExecuteAsyncModule` — start a body with top-level `await` and arrange
1705    /// to be told when it settles.
1706    ///
1707    /// The body returns a promise; the two handlers are the whole of the async machinery's
1708    /// entry point. Nothing here waits — that is the point. Waiting is what the old
1709    /// implementation did, and it is why a module with a top-level `await` used to block
1710    /// every sibling in the graph instead of merely deferring itself.
1711    fn execute_async_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
1712        let Some(code) = module.with(|r| r.code.clone()) else {
1713            return Ok(());
1714        };
1715        let name = module.with(|r| r.name.clone());
1716        let env = self.module_env(module);
1717        self.module_stack.push(name);
1718        let started = self.run_async_body(code, env, Value::Undefined);
1719        self.module_stack.pop();
1720        let promise = match started {
1721            Ok(promise) => promise,
1722            Err(Signal::Throw(reason)) => {
1723                // A body that throws before its first `await` still answers a promise, so
1724                // this is not a completion — but if it happens, treat it as one rather than
1725                // losing it.
1726                return Err(Signal::Throw(reason));
1727            }
1728            Err(other) => return Err(other),
1729        };
1730        let Value::Object(promise) = promise else {
1731            return Ok(());
1732        };
1733        let on_fulfilled = JsObject::function(
1734            self.heap,
1735            Some(self.realm.function_proto.clone()),
1736            Callable::ModuleEvaluationFulfilled {
1737                module: module.clone(),
1738            },
1739        );
1740        let on_rejected = JsObject::function(
1741            self.heap,
1742            Some(self.realm.function_proto.clone()),
1743            Callable::ModuleEvaluationRejected {
1744                module: module.clone(),
1745            },
1746        );
1747        self.perform_then(
1748            &promise,
1749            Some(Value::Object(on_fulfilled)),
1750            Some(Value::Object(on_rejected)),
1751        )?;
1752        Ok(())
1753    }
1754
1755    /// §16.2.1.5.3.1 `GatherAvailableAncestors` — who became ready because `module` finished.
1756    ///
1757    /// Each module waiting on `module` loses one pending dependency. One that reaches zero
1758    /// joins the list, and only a module *without* top-level `await` lets the walk continue
1759    /// through it: one with TLA has not run its body yet, so it cannot have finished for
1760    /// anybody else.
1761    fn gather_available_ancestors(
1762        &mut self,
1763        module: &Gc<ModuleRecord>,
1764        exec_list: &mut Vec<Gc<ModuleRecord>>,
1765    ) {
1766        let parents = module.with(|r| r.async_parent_modules.clone());
1767        for parent in parents {
1768            if exec_list.iter().any(|m| m.ptr_eq(&parent)) {
1769                continue;
1770            }
1771            if cycle_root_of(&parent).with(|r| r.evaluation_error.is_some()) {
1772                continue;
1773            }
1774            let ready = parent.with_mut(|r| {
1775                if r.pending_async_dependencies > 0 {
1776                    r.pending_async_dependencies -= 1;
1777                }
1778                r.pending_async_dependencies == 0
1779            });
1780            if ready {
1781                let has_tla = parent.has_tla();
1782                exec_list.push(parent.clone());
1783                if !has_tla {
1784                    self.gather_available_ancestors(&parent, exec_list);
1785                }
1786            }
1787        }
1788    }
1789
1790    /// §16.2.1.5.3.1 `AsyncModuleExecutionFulfilled`.
1791    pub fn async_module_execution_fulfilled(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
1792        if module.with(|r| r.status) == ModuleStatus::Evaluated {
1793            return Ok(());
1794        }
1795        module.with_mut(|r| r.async_evaluation = false);
1796        self.mark_module_evaluated(module);
1797
1798        let mut exec_list: Vec<Gc<ModuleRecord>> = Vec::new();
1799        self.gather_available_ancestors(module, &mut exec_list);
1800        exec_list.sort_by_key(|m| m.with(|r| r.async_evaluation_order));
1801
1802        for ready in exec_list {
1803            if ready.with(|r| r.status) == ModuleStatus::Evaluated {
1804                continue;
1805            }
1806            if ready.has_tla() {
1807                self.execute_async_module(&ready)?;
1808                continue;
1809            }
1810            match self.execute_module_body_only(&ready) {
1811                Ok(()) => {
1812                    ready.with_mut(|r| r.async_evaluation = false);
1813                    self.mark_module_evaluated(&ready);
1814                }
1815                Err(Signal::Throw(reason)) => {
1816                    self.async_module_execution_rejected(&ready, reason);
1817                }
1818                Err(other) => return Err(other),
1819            }
1820        }
1821        Ok(())
1822    }
1823
1824    /// [`Interp::async_module_execution_rejected`], for the promise-reaction arm in
1825    /// `interp.rs` — the algorithm itself does not report failures, because the only thing
1826    /// it can do with one is reject a promise that is already rejecting.
1827    pub(crate) fn async_module_execution_rejected_public(
1828        &mut self,
1829        module: &Gc<ModuleRecord>,
1830        reason: Value,
1831    ) {
1832        self.async_module_execution_rejected(module, reason);
1833    }
1834
1835    /// §16.2.1.5.3.1 `AsyncModuleExecutionRejected`.
1836    fn async_module_execution_rejected(&mut self, module: &Gc<ModuleRecord>, reason: Value) {
1837        if module.with(|r| r.status) == ModuleStatus::Evaluated {
1838            return;
1839        }
1840        module.with_mut(|r| {
1841            r.evaluation_error = Some(reason.clone());
1842            r.status = ModuleStatus::Evaluated;
1843            r.async_evaluation = false;
1844        });
1845        // Everyone waiting on it fails with the same reason, and one of them may be the
1846        // cycle root whose promise a caller is holding.
1847        let (promise, _, reject) = module
1848            .with(|r| r.top_level_capability.clone())
1849            .map_or((None, Value::Undefined, Value::Undefined), |(p, r, j)| {
1850                (Some(p), r, j)
1851            });
1852        if promise.is_some() {
1853            let _ = self.call_value(reject, Value::Undefined, vec![reason.clone()]);
1854        }
1855        let parents = module.with(|r| r.async_parent_modules.clone());
1856        for parent in parents {
1857            self.async_module_execution_rejected(&parent, reason.clone());
1858        }
1859    }
1860
1861    /// Finish a module: `Evaluated`, and settle whoever is waiting on its promise.
1862    fn mark_module_evaluated(&mut self, module: &Gc<ModuleRecord>) {
1863        module.with_mut(|r| r.status = ModuleStatus::Evaluated);
1864        let Some((promise, resolve, _)) = module.with(|r| r.top_level_capability.clone()) else {
1865            return;
1866        };
1867        if self.promise_state(&promise).is_some_and(|state| {
1868            !matches!(state.borrow().status, crate::object::PromiseStatus::Pending)
1869        }) {
1870            return;
1871        }
1872        let _ = self.call_value(resolve, Value::Undefined, vec![Value::Undefined]);
1873    }
1874
1875    /// Evaluate the asynchronous modules a deferred request drags in, and nothing else.
1876    fn evaluate_async_transitive_dependencies(
1877        &mut self,
1878        module: &Gc<ModuleRecord>,
1879    ) -> JsResult<()> {
1880        let mut seen = Vec::new();
1881        let mut list = Vec::new();
1882        self.gather_asynchronous_transitive_dependencies(module, &mut seen, &mut list);
1883        for dependency in list {
1884            let promise = self.evaluate_module(&dependency)?;
1885            self.await_module_promise(Value::Object(promise))?;
1886        }
1887        Ok(())
1888    }
1889
1890    /// `GatherAsynchronousTransitiveDependencies` — the async modules a deferred request
1891    /// drags into evaluation order without evaluating itself.
1892    ///
1893    /// Walks the request graph and stops at the first `[[HasTLA]]` module on each path,
1894    /// because that module's own dependencies are already part of *its* evaluation. A
1895    /// module that is evaluating or done contributes nothing, and a synthetic (JSON/text/
1896    /// native) module has no requests to follow.
1897    fn gather_asynchronous_transitive_dependencies(
1898        &mut self,
1899        module: &Gc<ModuleRecord>,
1900        seen: &mut Vec<usize>,
1901        out: &mut Vec<Gc<ModuleRecord>>,
1902    ) {
1903        let identity = module.identity();
1904        if seen.contains(&identity) {
1905            return;
1906        }
1907        seen.push(identity);
1908        if !module.with(|r| r.kind == ModuleKind::JavaScript) {
1909            return;
1910        }
1911        // The import-defer proposal's own wording of this step: stop for `~evaluating~` or
1912        // for `IsModuleSCCEvaluated`. Both halves matter and neither is "my status is
1913        // evaluated":
1914        //
1915        //  * a parked module is walked *through*, because what is actually being waited on
1916        //    may be further down its graph (`middle → d → b → a-tla`, where `b` has already
1917        //    run but `a-tla` has not);
1918        //  * a module inside a cycle is finished only when its **root** is, so `b` is not
1919        //    "done" while `a-tla` is parked.
1920        if module.with(|r| r.status) == ModuleStatus::Evaluating || is_module_scc_evaluated(module)
1921        {
1922            return;
1923        }
1924        if module.has_tla() {
1925            if !out.iter().any(|m| m.ptr_eq(module)) {
1926                out.push(module.clone());
1927            }
1928            return;
1929        }
1930        let count = module.with(|r| r.meta.requests.len());
1931        let mut collected: Vec<Gc<ModuleRecord>> = Vec::new();
1932        for index in 0..count {
1933            let Some(required) = module.with(|r| r.dependencies.get(index).cloned().flatten())
1934            else {
1935                continue;
1936            };
1937            self.gather_asynchronous_transitive_dependencies(&required, seen, &mut collected);
1938        }
1939        for candidate in collected {
1940            if !out.iter().any(|m| m.ptr_eq(&candidate)) {
1941                out.push(candidate);
1942            }
1943        }
1944    }
1945
1946    /// `ReadyForSyncExecution` — whether evaluating `module` right now cannot suspend.
1947    ///
1948    /// This engine runs a module body to completion inside [`Interp::evaluate_module_body`],
1949    /// draining the job queue for a top-level `await` as it goes, so there is never a module
1950    /// parked in `~evaluating-async~`: the only two answers here are "already done" and
1951    /// "on the stack right now". Everything else — a body with top-level await anywhere
1952    /// below it, or a cycle back into one that is running — means a deferred namespace
1953    /// cannot be read synchronously, which is the `TypeError` the proposal specifies.
1954    fn ready_for_sync_execution(
1955        &mut self,
1956        module: &Gc<ModuleRecord>,
1957        seen: &mut Vec<usize>,
1958    ) -> bool {
1959        let identity = module.identity();
1960        if seen.contains(&identity) {
1961            return true;
1962        }
1963        seen.push(identity);
1964        // Steps 5–6, in this order: the component question first, the module's own status
1965        // second. Both `~evaluating~` **and** `~evaluating-async~` answer false here, which
1966        // is what turns a namespace read into a `TypeError` instead of a body starting.
1967        if is_module_scc_evaluated(module) {
1968            return true;
1969        }
1970        match module.with(|r| r.status) {
1971            ModuleStatus::Evaluating | ModuleStatus::EvaluatingAsync => return false,
1972            _ => {}
1973        }
1974        if module.has_tla() {
1975            return false;
1976        }
1977        let count = module.with(|r| r.meta.requests.len());
1978        for index in 0..count {
1979            let Some(required) = module.with(|r| r.dependencies.get(index).cloned().flatten())
1980            else {
1981                continue;
1982            };
1983            if !self.ready_for_sync_execution(&required, seen) {
1984                return false;
1985            }
1986        }
1987        true
1988    }
1989
1990    /// `EnsureDeferredNamespaceEvaluation` — the trigger behind every read of a deferred
1991    /// namespace.
1992    ///
1993    /// `None` for an ordinary namespace, which is what makes this cheap on the hot path: a
1994    /// namespace built by `import * as ns` has no module attached and answers immediately.
1995    pub(crate) fn trigger_deferred_namespace(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
1996        let Some(module) = object.deferred_namespace_module() else {
1997            return Ok(());
1998        };
1999        // Only a module that has *not* finished can be evaluated here, and only such a
2000        // module can be unready: a module that threw is finished too, and re-reporting its
2001        // completion is what `evaluate_module_body` does.
2002        if module.with(|r| r.status) != ModuleStatus::Evaluated {
2003            let mut seen = Vec::new();
2004            if !self.ready_for_sync_execution(&module, &mut seen) {
2005                return Err(self.type_error(
2006                    "cannot read a deferred module namespace while its module is evaluating",
2007                ));
2008            }
2009        }
2010        match module.with(|r| r.status) {
2011            // Finished already, including "finished by throwing": the recorded completion is
2012            // the answer, and re-running the body would build a second, non-identical error.
2013            ModuleStatus::Evaluated => match module.with(|r| r.evaluation_error.clone()) {
2014                Some(error) => Err(Signal::Throw(error)),
2015                None => Ok(()),
2016            },
2017            // `ready_for_sync_execution` said nothing below it can suspend, so this really
2018            // does finish before the call returns — and it must not go through
2019            // `evaluate_module`, whose async bookkeeping parks a module reached through a
2020            // read (`async-cycle-dependency-of-deferred-module`).
2021            _ => self.evaluate_module_sync(&module),
2022        }
2023    }
2024
2025    /// Drive a module's own promise to a settled state.
2026    ///
2027    /// `js_execute_sync_module` in the reference does the same thing and calls a pending
2028    /// promise an error ("promise is pending"); draining first is the difference, and it
2029    /// is correct here because nothing else can be waiting: this runs before the host has
2030    /// been given control, and the only queued jobs are the ones this body queued for
2031    /// itself.
2032    fn await_module_promise(&mut self, promise: Value) -> JsResult<Value> {
2033        let Value::Object(promise) = promise else {
2034            return Ok(Value::Undefined);
2035        };
2036        self.drain_jobs()?;
2037        let state = self.promise_state(&promise);
2038        let Some(state) = state else {
2039            return Ok(Value::Undefined);
2040        };
2041        let status = state.borrow().status.clone();
2042        match status {
2043            crate::object::PromiseStatus::Fulfilled(value) => Ok(value),
2044            crate::object::PromiseStatus::Rejected(reason) => Err(Signal::Throw(reason)),
2045            crate::object::PromiseStatus::Pending => Err(Signal::Throw(self.make_error(
2046                "TypeError",
2047                "promise is pending: top-level await never settled",
2048            ))),
2049        }
2050    }
2051
2052    /// `import(specifier)`: load, link, evaluate — asynchronously.
2053    ///
2054    /// The work happens in a job, because §13.3.10.1 makes dynamic import settle through
2055    /// the promise machinery: `import("x").then(f)` must call `f` after the current
2056    /// script finishes, never inside the `import` expression.
2057    pub fn dynamic_import(
2058        &mut self,
2059        specifier: Value,
2060        options: Value,
2061        phase: ImportPhase,
2062    ) -> JsResult<Value> {
2063        let promise = self.new_promise();
2064        // §13.3.10.1 steps 5–7, in this order and with this error handling:
2065        //
2066        //     5. Let promiseCapability be ! NewPromiseCapability(%Promise%).
2067        //     6. Let specifierString be ToString(specifier).
2068        //     7. IfAbruptRejectPromise(specifierString, promiseCapability).
2069        //
2070        // Step 7 is the whole point of the ordering: a throwing `toString` — or a Symbol
2071        // specifier, which `ToString` rejects — must **reject the promise**, not throw out of
2072        // the `import` expression. Throwing here made `import(obj)` with a throwing
2073        // `toString` abort the whole script, so `.catch` could never run and test262's 40-odd
2074        // `specifier-tostring-abrupt-rejects` cases all failed.
2075        //
2076        // `GetValue` (step 4) is a plain `?` and genuinely throws synchronously; the compiler
2077        // has already evaluated the argument by the time this runs, so that distinction is
2078        // kept where it belongs.
2079        let specifier = match self.to_js_string(&specifier) {
2080            Ok(specifier) => specifier,
2081            Err(Signal::Throw(reason)) => {
2082                self.reject_promise(&promise, reason);
2083                return Ok(Value::Object(promise));
2084            }
2085            Err(other) => return Err(other),
2086        };
2087        // §13.3.10.1 steps 9–10: the import-attributes bag.
2088        //
2089        // This loader applies no attributes — `with: { type: 'json' }` parses and is then
2090        // ignored — but the *validation* is not optional, and neither are the observable
2091        // reads it performs. Every abrupt completion below rejects the promise rather than
2092        // throwing, and the order (options is an object, then `with`, then its keys, then
2093        // each value) is what the tests instrument:
2094        //
2095        //     `import(x, null)`            → TypeError rejection (step 10.a)
2096        //     `get with() { throw e }`     → rejection with `e` (step 10.c)
2097        //     `with: 'string'`            → TypeError rejection (step 10.d.i)
2098        //     `with: { type: 23 }`        → TypeError rejection (step 10.d.v.3)
2099        if let Some(rejection) = self.import_attribute_error(&options) {
2100            self.reject_promise(&promise, rejection);
2101            return Ok(Value::Object(promise));
2102        }
2103        // Resolved relative to whatever is running the import — the reference asks
2104        // `JS_GetScriptOrModuleName(ctx, 0)`, which is the innermost frame's file name and
2105        // does not care whether that frame came from a module or a plain script.
2106        //
2107        // Only consulting the module stack (as this did) made every `import('./x.js')` from
2108        // a *script* resolve against the working directory instead of the script's own
2109        // directory, so `await import('./module-code_FIXTURE.js')` in test262's
2110        // `dynamic-import` tests failed with "could not load module filename" for a file
2111        // sitting right next to the test.
2112        let referrer = self.import_referrer();
2113        self.jobs.push_back(crate::interp::Job::Import {
2114            specifier,
2115            referrer,
2116            promise: promise.clone(),
2117            phase,
2118        });
2119        Ok(Value::Object(promise))
2120    }
2121
2122    /// Validate `import(x, options)`'s second argument, answering the reason to reject with.
2123    ///
2124    /// Returns `None` when the bag is acceptable — including when it is absent, which is the
2125    /// overwhelmingly common case and the only one this loader ever acts on.
2126    ///
2127    /// The reads are performed even though their results are discarded, because §13.3.10.1
2128    /// makes them observable: a `with` getter or a `Proxy` that logs is the entire content of
2129    /// the `2nd-param-*` tests. Nothing here throws; every failure becomes a rejection, which
2130    /// is `IfAbruptRejectPromise` spelled out.
2131    fn import_attribute_error(&mut self, options: &Value) -> Option<Value> {
2132        // Step 10: an absent bag is fine, and `undefined` is how "absent" arrives here —
2133        // `import(x)` compiles a literal `undefined` into the slot.
2134        if matches!(options, Value::Undefined) {
2135            return None;
2136        }
2137        // 10.a: any other non-object is a TypeError.
2138        let Value::Object(options) = options else {
2139            return Some(self.type_error_value("import options must be an object"));
2140        };
2141        let options = options.clone();
2142        // 10.b–c: `Get(options, "with")`.
2143        let with = match self.read_field(&Value::Object(options), "with") {
2144            Ok(with) => with,
2145            Err(Signal::Throw(reason)) => return Some(reason),
2146            Err(_) => return None,
2147        };
2148        if matches!(with, Value::Undefined) {
2149            return None;
2150        }
2151        // 10.d.i: `with` has to be an object too.
2152        let Value::Object(with_object) = &with else {
2153            return Some(self.type_error_value("import attributes must be an object"));
2154        };
2155        let with_object = with_object.clone();
2156        // 10.d.ii–iii: `EnumerableOwnPropertyNames`, which can throw from a `Proxy` trap —
2157        // so this goes through `[[OwnPropertyKeys]]` and asks enumerability per key rather
2158        // than reading the object's own table.
2159        let keys = match self.import_attribute_keys(&with) {
2160            Ok(keys) => keys,
2161            Err(Signal::Throw(reason)) => return Some(reason),
2162            Err(_) => return None,
2163        };
2164        // 10.d.v: each value is read (observably) and has to be a string.
2165        for key in keys {
2166            let value = match self.read_field(&Value::Object(with_object.clone()), &key) {
2167                Ok(value) => value,
2168                Err(Signal::Throw(reason)) => return Some(reason),
2169                Err(_) => continue,
2170            };
2171            if !matches!(value, Value::String(_)) {
2172                return Some(self.type_error_value("import attribute values must be strings"));
2173            }
2174        }
2175        None
2176    }
2177
2178    /// A `TypeError` as a value, for the reject paths above.
2179    fn type_error_value(&mut self, message: &str) -> Value {
2180        self.make_error("TypeError", message)
2181    }
2182
2183    /// `EnumerableOwnPropertyNames(value, key)` (§7.3.23), as a list of string keys.
2184    ///
2185    /// The key list is snapshotted first and enumerability is asked per key as the walk
2186    /// reaches it, which is the order the algorithm specifies and the one a `Proxy` can
2187    /// observe. Symbols are dropped: an import attribute name is a String.
2188    fn import_attribute_keys(&mut self, value: &Value) -> JsResult<Vec<String>> {
2189        let Some(object) = value.as_object().cloned() else {
2190            return Ok(Vec::new());
2191        };
2192        let mut out = Vec::new();
2193        for key in self.object_own_property_keys(&object)? {
2194            let Some(name) = key.as_wtf8() else {
2195                // A symbol key is not an import attribute name.
2196                continue;
2197            };
2198            let enumerable = self
2199                .object_get_own_property(&object, &key)?
2200                .is_some_and(|property| property.enumerable);
2201            if enumerable {
2202                out.push(name.to_string_lossy().into_owned());
2203            }
2204        }
2205        Ok(out)
2206    }
2207
2208    /// The module name a dynamic import's specifier is resolved against.
2209    ///
2210    /// The innermost frame that has a *real file* name. `eval` and `std.evalScript` compile
2211    /// their bodies under pseudo-names (`<input>`, `<evalScript>`) because that is what a
2212    /// stack trace should say, and §19.2.1.1's `GetActiveScriptOrModule` makes an eval'd body
2213    /// belong to the script that called it — never to a file named `<input>`. Resolving
2214    /// `import('./x.js')` against `<input>` produced the specifier `x.js` with no directory,
2215    /// which the loader then looked for in the working directory.
2216    ///
2217    /// So frames are walked outermost-last until one names something path-like; a pseudo-name
2218    /// (`<…>`) is skipped for the same reason a `<builtin>` frame is not a referrer.
2219    fn import_referrer(&self) -> String {
2220        self.script_or_module_file_name()
2221            .or_else(|| self.module_stack.last().cloned())
2222            .or_else(|| self.main_module_name.clone())
2223            .unwrap_or_default()
2224    }
2225
2226    /// Evaluate a pending dynamic import and settle its promise.
2227    pub fn run_dynamic_import(
2228        &mut self,
2229        specifier: &str,
2230        referrer: &str,
2231        promise: &Gc<JsObject>,
2232        phase: ImportPhase,
2233    ) {
2234        // Load and link. `import.defer` and `import.source` answer here; only the ordinary
2235        // phase goes on to evaluate, and that one cannot answer yet.
2236        let module = match self
2237            .load_module(specifier, &[], referrer)
2238            .and_then(|module| self.link_module(&module).map(|()| module))
2239        {
2240            Ok(module) => module,
2241            Err(Signal::Throw(reason)) => {
2242                self.reject_promise(promise, reason);
2243                return;
2244            }
2245            Err(_) => return,
2246        };
2247        // `import.defer(x)` resolves once the module is *loaded and linked*, and hands back
2248        // the namespace object without evaluating anything — that is the entire difference
2249        // from `import(x)`, and it is why the promise still rejects for a missing or
2250        // unparsable module.
2251        if phase == ImportPhase::Defer {
2252            // The async part of the graph still runs: `InnerModuleEvaluation` would gather a
2253            // deferred request's asynchronous transitive dependencies, and a dynamic import
2254            // has no importer to do it for it. So the module's own top-level-await
2255            // dependencies are evaluated here, and the promise resolves with an unevaluated
2256            // module either way.
2257            let outcome = self
2258                .evaluate_async_transitive_dependencies(&module)
2259                .and_then(|()| self.module_deferred_namespace(&module));
2260            match outcome {
2261                Ok(namespace) => self.fulfill_promise(promise, namespace),
2262                Err(Signal::Throw(reason)) => self.reject_promise(promise, reason),
2263                Err(_) => {}
2264            }
2265            return;
2266        }
2267        if phase == ImportPhase::Source {
2268            // §16.2.1.7.2 `GetModuleSource`: a Source Text Module Record — which is the only
2269            // kind this engine has — always answers with a `SyntaxError`, "a source phase
2270            // import is not available". The *load* still happens first, which is why a
2271            // missing file rejects with the loader's error instead: the promise settles one
2272            // step later than the resolution.
2273            let reason = self.make_error(
2274                "SyntaxError",
2275                "a source phase import is not available for this module",
2276            );
2277            self.reject_promise(promise, reason);
2278            return;
2279        }
2280        // §16.2.1.5.4 `FinishDynamicImport`: the import settles when the *module* does, not
2281        // when this call returns. Chaining onto the module's own `[[TopLevelCapability]]` is
2282        // what leaves an importer of a parked module pending — and what makes a second
2283        // `import()` of that module resolve no earlier than the first.
2284        let name = module.with(|r| r.name.clone());
2285        self.module_stack.push(name);
2286        let started = self.evaluate_module(&module);
2287        self.module_stack.pop();
2288        let capability = match started {
2289            Ok(capability) => capability,
2290            Err(Signal::Throw(reason)) => {
2291                self.reject_promise(promise, reason);
2292                return;
2293            }
2294            Err(_) => return,
2295        };
2296        let on_fulfilled = JsObject::function(
2297            self.heap,
2298            Some(self.realm.function_proto.clone()),
2299            Callable::ModuleNamespaceForImport {
2300                module: module.clone(),
2301                promise: promise.clone(),
2302            },
2303        );
2304        let on_rejected = JsObject::function(
2305            self.heap,
2306            Some(self.realm.function_proto.clone()),
2307            Callable::PromiseReject(promise.clone()),
2308        );
2309        let chained = self.perform_then(
2310            &capability,
2311            Some(Value::Object(on_fulfilled)),
2312            Some(Value::Object(on_rejected)),
2313        );
2314        if let Err(Signal::Throw(reason)) = chained {
2315            self.reject_promise(promise, reason);
2316        }
2317    }
2318}
2319
2320/// The registry key for a module: its canonical name plus the attributes that decided
2321/// what it means.
2322///
2323/// Without the attributes, `import m from "./x.json"` and
2324/// `import m from "./x.json" with { type: "text" }` would collide on one record and the
2325/// second import would silently receive the first one's value.
2326fn cache_key(name: &str, attributes: &[(String, String)]) -> String {
2327    if attributes.is_empty() {
2328        return name.to_string();
2329    }
2330    let mut key = name.to_string();
2331    for (key_name, value) in attributes {
2332        key.push('\u{0}');
2333        key.push_str(key_name);
2334        key.push('=');
2335        key.push_str(value);
2336    }
2337    key
2338}
2339
2340/// Which kind of module `name` and `attributes` describe.
2341///
2342/// A `type` attribute wins; the `.json` suffix only decides when no attribute was given.
2343/// That is what makes `import m from "./m.json" with { type: "text" }` a string while
2344/// `import m from "./m.json"` is an object.
2345fn module_kind(name: &str, attributes: &[(String, String)]) -> Result<ModuleKind, String> {
2346    let declared = attributes
2347        .iter()
2348        .find(|(key, _)| key == "type")
2349        .map(|(_, value)| value.as_str());
2350    let kind = match declared {
2351        // `json5` is accepted by the reference as an alias for a dialect that permits
2352        // comments and trailing commas; this parser is strict JSON, so a document that
2353        // needs the extension fails loudly rather than silently parsing differently.
2354        Some("json") | Some("json5") => ModuleKind::Json,
2355        Some("text") => ModuleKind::Text,
2356        Some("bytes") => ModuleKind::Bytes,
2357        // An unknown type is an error rather than a fallback to JavaScript: silently
2358        // evaluating `with { type: "cbor" }` as code would run a data file.
2359        Some(other) => return Err(format!("unsupported module type: '{other}'")),
2360        None => {
2361            if name.ends_with(".json") {
2362                ModuleKind::Json
2363            } else {
2364                ModuleKind::JavaScript
2365            }
2366        }
2367    };
2368    Ok(kind)
2369}