quickjs-pure 0.17.40

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
//! The module system: records, linking, namespaces, and evaluation.
//!
//! The design follows §16.2 closely but leans on one thing this engine already has.
//! A module's top-level bindings compile as *closure variables* of the module body —
//! `ClosureType::ModuleDecl` for its own declarations, `ClosureType::ModuleImport` for
//! what it imports — so reading one is an ordinary `get_var_ref`. What makes modules
//! interesting is then entirely a question of **who fills the cells**:
//!
//! * a declaration gets a fresh cell, created here;
//! * an import gets *the exporting module's* cell, not a copy.
//!
//! Sharing the cell is what makes bindings live (`export let x; x = 1` is visible to the
//! importer) and what makes cyclic imports work: linking wires cells before anything
//! evaluates, so `a.js` importing from a `b.js` that imports back from `a.js` resolves to
//! cells on both sides without either body having run.
//!
//! The three phases are the spec's: load (read and compile), link (resolve imports,
//! validate exports), evaluate (run bodies depth-first, once each).

use std::collections::BTreeMap;

use js_gc::{Gc, Trace, Tracer};

use crate::interp::{Interp, JsResult, Signal, WellKnown};
use crate::object::{Callable, ClosureEnv, CompiledCode, JsObject, Property};
use crate::value::{Cell, Value};
use js_compile::bytecode::Function as CompiledFunction;
use js_parse::ast::ImportPhase;

/// The reference's textual specifier rule, shared with the AOT bundler.
///
/// See [`js_parse::normalize_specifier`]: the loader and the bundler have to agree on a
/// module's name, or a product reports "could not load module filename" for a module it is
/// carrying.
pub use js_parse::normalize_specifier;

/// Where a module is in its lifetime.
///
/// `Linking` and `Evaluated` are not just bookkeeping: they are what makes a cycle
/// terminate. A cycle is not an error — it is a graph that must be *linked* depth-first
/// and then *evaluated* in post-order, and the two-phase split is the mechanism.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModuleStatus {
    /// Loaded and compiled; imports not yet resolved.
    Unlinked,
    /// Being linked, so a re-entrant link must not recurse.
    Linking,
    /// Imports resolved and exports validated.
    Linked,
    /// Body running right now.
    ///
    /// Distinct from [`ModuleStatus::Evaluated`] because the deferred-import proposal asks
    /// the difference: `ReadyForSyncExecution` answers *false* for a module that is
    /// `~evaluating~`, and the only way a namespace read can observe that is if the two
    /// states are not the same flag. A re-entrant evaluation still stops at either.
    Evaluating,
    /// Body suspended at a top-level `await`, or waiting for a dependency that is.
    ///
    /// §16.2.1.5.3.1's `~evaluating-async~`. A module in this state has a body that has
    /// **started** — its `[[AsyncEvaluation]]` is set and it holds an
    /// `[[AsyncEvaluationOrder]]` — and it will be moved to `Evaluated` by the module
    /// machinery, not by whatever call happened to reach it.
    EvaluatingAsync,
    /// Body has run to completion, or has failed.
    ///
    /// A body that threw is `Evaluated` too — §16.2.1.5.3.1 records the completion in
    /// `[[EvaluationError]]` and marks the module evaluated, so a second attempt reports
    /// the *same* exception object rather than running the body again.
    Evaluated,
}

/// How a module's source became a module.
///
/// A JSON or text module is not code at all — it is one value exported as `default` — so
/// it has no body and no imports, which is why this is a flag rather than a second type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModuleKind {
    /// JavaScript: has a compiled body.
    JavaScript,
    /// A parsed JSON document, exported as `default`.
    Json,
    /// A plain string, exported as `default`.
    Text,
    /// A `Uint8Array`, exported as `default`.
    Bytes,
    /// A native module: exports supplied by the host, with no source at all.
    ///
    /// This is the C API's `JS_NewCModule`. The values are already built when the module
    /// appears, so the record is born evaluated — the same shape a data module has, with
    /// several exports instead of one.
    Native,
}

/// One loaded module.
///
/// Held on the GC heap because its cells and namespace are GC values. The whole record is
/// behind interior mutability the same way a [`Cell`] is: linking writes into it while
/// other modules already hold references to it.
pub struct ModuleRecord {
    inner: std::cell::RefCell<ModuleInner>,
}

impl ModuleRecord {
    /// Build a record around `inner`.
    pub fn new(inner: ModuleInner) -> ModuleRecord {
        ModuleRecord {
            inner: std::cell::RefCell::new(inner),
        }
    }

    /// Run `f` with the record borrowed.
    pub fn with<R>(&self, f: impl FnOnce(&ModuleInner) -> R) -> R {
        f(&self.inner.borrow())
    }

    /// Run `f` with the record borrowed mutably.
    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ModuleInner) -> R) -> R {
        f(&mut self.inner.borrow_mut())
    }

    /// Whether the module's body contains a top-level `await`.
    ///
    /// §16.2.1.5.3.1's `[[HasTLA]]`. A body with one compiles to an async function, so the
    /// flag is the compiled kind rather than a second piece of bookkeeping: the two can
    /// never disagree.
    pub fn has_tla(&self) -> bool {
        self.with(|r| {
            r.code
                .as_ref()
                .is_some_and(|code| code.code.kind.is_async())
        })
    }
}

/// §16.2.1.5.3.1's `[[CycleRoot]]`, defaulting to the module itself.
///
/// A free function rather than a method because the default is the module's own `Gc`
/// handle, which `&ModuleRecord` does not carry. `None` means "not in a cycle (yet)", and
/// a module that is not in a cycle is its own root — which is why the two are the same
/// answer here.
fn cycle_root_of(module: &Gc<ModuleRecord>) -> Gc<ModuleRecord> {
    module
        .with(|r| r.cycle_root.clone())
        .unwrap_or_else(|| module.clone())
}

/// `IsModuleSCCEvaluated(module)` — is the whole strongly-connected component done?
///
/// The question is asked of the **cycle root**, not of the module: a module inside a cycle
/// stops being `~evaluating-async~` only when its root does, and a member whose own body has
/// already run is still part of a component that has not. Treating "my body finished" as
/// "my component finished" is what made a deferred read run past an in-flight cycle
/// (`async-cycle-dependency-of-deferred-module`: `B` is `evaluated` while its root `A` is
/// parked, and the importer has to wait for `A`).
///
/// `[[CycleRoot]]` is empty until the component is popped off the DFS stack, so a module
/// that has never been in a cycle answers for itself.
fn is_module_scc_evaluated(module: &Gc<ModuleRecord>) -> bool {
    match module.with(|r| r.cycle_root.clone()) {
        Some(root) => root.with(|r| r.status) == ModuleStatus::Evaluated,
        None => module.with(|r| r.status) == ModuleStatus::Evaluated,
    }
}

/// Everything a module record holds; see [`ModuleRecord`].
pub struct ModuleInner {
    /// Canonical identity: the cache key, and what a cycle compares.
    pub name: String,
    /// What `import.meta.url` reports.
    pub url: String,
    /// The compiled body, or `None` for a JSON/text/bytes module.
    pub code: Option<Gc<CompiledCode>>,
    /// The tables the compiler produced.
    pub meta: js_compile::bytecode::ModuleMeta,
    /// One cell per closure variable of the body; the body reads its bindings here.
    pub cells: Vec<Gc<Cell>>,
    /// Resolved dependencies, parallel to `meta.requests`.
    pub dependencies: Vec<Option<Gc<ModuleRecord>>>,
    /// Where it is in its lifetime.
    pub status: ModuleStatus,
    /// The completion of a body that threw, rethrown on every later attempt.
    ///
    /// §16.2.1.5.3.1 stores the *abrupt completion* on the record. Without it a second
    /// read through a deferred namespace ran the body again and produced a second, equal,
    /// but not identical error object — which `import-defer/errors/module-throws` compares
    /// by identity.
    pub evaluation_error: Option<Value>,
    /// §16.2.1.5.3.1's `[[AsyncEvaluation]]`: the body has started and has not finished.
    ///
    /// Not the same as `status == EvaluatingAsync`, because the flag is also what an
    /// *importer* looks at: a request whose target has this set makes the importer wait.
    pub async_evaluation: bool,
    /// §16.2.1.5.3.1's `[[AsyncEvaluationOrder]]`.
    ///
    /// A monotonic counter, never reset. The ordering of modules that become ready in one
    /// batch is decided by it and is observable — `module-code/top-level-await/fulfillment-order`
    /// is exactly that assertion — so it cannot be "whatever order the vector happens to
    /// have".
    pub async_evaluation_order: u64,
    /// §16.2.1.5.3.1's `[[PendingAsyncDependencies]]`.
    pub pending_async_dependencies: usize,
    /// §16.2.1.5.3.1's `[[AsyncParentModules]]`: who is waiting for this module.
    pub async_parent_modules: Vec<Gc<ModuleRecord>>,
    /// §16.2.1.5.3.1's `[[CycleRoot]]`; `None` means "this module".
    pub cycle_root: Option<Gc<ModuleRecord>>,
    /// §16.2.1.5.3.1's `[[DFSIndex]]`: where the depth-first walk reached this module.
    pub dfs_index: usize,
    /// §16.2.1.5.3.1's `[[DFSAncestorIndex]]`: the earliest index reachable from here.
    ///
    /// Equal to `dfs_index` exactly when this module is the root of its cycle, which is how
    /// §16.2.1.5.3.1 step 17 knows where to stop popping the stack.
    pub dfs_ancestor_index: usize,
    /// `[[TopLevelCapability]]`: the promise a caller waits on for this module.
    ///
    /// Stored as the capability triple so both settling functions are available — the
    /// module owns the promise, and whoever imports it chains onto the same one, which is
    /// what makes the *second* `import()` of a waiting module resolve no earlier than the
    /// first (`dynamic-import-of-waiting-module`).
    pub top_level_capability: Option<(Gc<JsObject>, Value, Value)>,
    /// What kind of module it is.
    pub kind: ModuleKind,
    /// The namespace object, built on first use.
    pub namespace: Option<Gc<JsObject>>,
    /// The deferred namespace object, built on first use.
    ///
    /// A second object rather than a flag on the first: the deferred namespace's whole
    /// point is that reading it evaluates the module, and the eager one must stay usable on
    /// a module that is still `Linked`. It is cached here so two `import defer` clauses for
    /// one module hand back the same object, which the proposal requires.
    pub deferred_namespace: Option<Gc<JsObject>>,
    /// `import.meta`, built at load time.
    pub import_meta: Option<Gc<JsObject>>,
    /// The wrapper cell behind each `export * as ns from "m"`, keyed by `ns`.
    ///
    /// §16.2.1.6.3 `ResolveExport` identifies a binding by *(module, name)*, and the
    /// ambiguity test compares those identities. A namespace re-export needs a cell in the
    /// export table, and building a fresh one per lookup gave the same export two different
    /// identities — so a name reached through two `export *` that both pass through one
    /// `export * as ns` looked ambiguous. Caching makes the identity stable, which is what
    /// `namespace-unambiguous-if-export-star-as-from` checks.
    pub star_cells: BTreeMap<String, Gc<Cell>>,
}

impl Trace for ModuleRecord {
    fn trace(&self, tracer: &mut Tracer) {
        self.inner.borrow().trace(tracer);
    }
}

impl Trace for ModuleInner {
    fn trace(&self, tracer: &mut Tracer) {
        if let Some(code) = &self.code {
            tracer.visit(code);
        }
        for cell in &self.cells {
            tracer.visit(cell);
        }
        for dependency in self.dependencies.iter().flatten() {
            tracer.visit(dependency);
        }
        if let Some(namespace) = &self.namespace {
            tracer.visit(namespace);
        }
        if let Some(namespace) = &self.deferred_namespace {
            tracer.visit(namespace);
        }
        if let Some(error) = &self.evaluation_error {
            error.trace(tracer);
        }
        for parent in &self.async_parent_modules {
            tracer.visit(parent);
        }
        if let Some(root) = &self.cycle_root {
            tracer.visit(root);
        }
        if let Some((promise, resolve, reject)) = &self.top_level_capability {
            tracer.visit(promise);
            resolve.trace(tracer);
            reject.trace(tracer);
        }
        if let Some(meta) = &self.import_meta {
            tracer.visit(meta);
        }
    }
}

/// A host-supplied module, before it is compiled.
pub struct LoadedModule {
    /// Canonical identity — the cache key, and how a cycle recognises itself.
    pub name: String,
    /// `import.meta.url` for this module.
    pub url: String,
    /// The file's bytes. Not necessarily UTF-8: a `bytes` module is arbitrary.
    pub source: Vec<u8>,
}

/// How the host turns a specifier into bytes.
///
/// The engine cannot do this itself: resolving `./x.js` needs to know that the importer
/// was a file, and where. A browser-shaped host would answer differently, so the host
/// supplies this and the engine decides what to do with the bytes.
pub trait ModuleLoader {
    /// Resolve `specifier` relative to `referrer` and read it.
    ///
    /// `referrer` is empty for the entry module.
    fn load(
        &self,
        specifier: &str,
        attributes: &[(String, String)],
        referrer: &str,
    ) -> Result<LoadedModule, String>;

    /// Load a native module, if this loader has one at `name`.
    ///
    /// The answer is a *record*, not bytes: a `.so` is not text to compile, it is a library
    /// that hands back exports. `None` means "this name is not native", which sends the
    /// engine on to [`ModuleLoader::load`] — so a loader that knows nothing about native
    /// modules needs no change at all.
    ///
    /// `interp` is the interpreter doing the load, because the library's entry point takes
    /// a `JSContext *` and will call back into this very interpreter.
    fn load_native(
        &self,
        interp: &mut Interp<'_>,
        name: &str,
    ) -> Option<Result<Gc<ModuleRecord>, String>> {
        let _ = (interp, name);
        None
    }

    /// The name `specifier` resolves to from `referrer`, without reading anything.
    ///
    /// A precompiled module is registered under the name a *loader* would give it, so the
    /// engine has to know that name before it can decide whether the module is already in
    /// memory. Without this the only way to ask is [`ModuleLoader::load`], which reads the
    /// file — and a product that carries its dependencies has no files to read.
    ///
    /// `None` means "this loader can only answer by loading", which is the behaviour a
    /// loader that resolves against something other than text (an in-memory map, a
    /// network) legitimately has. Precompiled modules are then matched after the load, by
    /// the name the load reported.
    fn resolve(&self, specifier: &str, referrer: &str) -> Option<String> {
        let _ = (specifier, referrer);
        None
    }
}

/// What `ResolveExport` answered, including the two ways it can fail to name a binding.
///
/// §16.2.1.6.3 distinguishes them and so must the caller: **not found** is a missing export,
/// while **ambiguous** is a module that must fail to link even though the name exists twice.
/// Collapsing both into `Err` is what let the star loop treat an ambiguity as absence and
/// resolve the name to whichever dependency happened to be listed first.
enum Resolution {
    Cell {
        cell: Gc<Cell>,
        /// The module the binding actually lives in.
        module: Gc<ModuleRecord>,
        /// Its name there — `*namespace*` for a namespace re-export.
        binding: String,
    },
    NotFound,
    Ambiguous,
}

impl Resolution {
    /// Whether two resolutions name the **same binding**.
    ///
    /// §16.2.1.6.3 compares `[[Module]]` and `[[BindingName]]`, nothing else: two
    /// `export *` paths that arrive at one binding are not ambiguous, and two paths that
    /// arrive at different bindings are. Comparing the export *cells* instead was wrong for
    /// `export * as ns from "m"`, where the cell belongs to the re-exporting module while the
    /// binding belongs to `m` — so two modules that both re-export the same namespace looked
    /// like two different bindings.
    fn same_binding(&self, other: &Resolution) -> bool {
        match (self, other) {
            (
                Resolution::Cell {
                    module: a,
                    binding: a_name,
                    ..
                },
                Resolution::Cell {
                    module: b,
                    binding: b_name,
                    ..
                },
            ) => a.ptr_eq(b) && a_name == b_name,
            _ => false,
        }
    }
}

impl<'a> Interp<'a> {
    /// The module registry: one entry per canonical name, so each file is compiled once.
    pub fn module_registry(&self) -> &BTreeMap<String, Gc<ModuleRecord>> {
        &self.modules
    }

    /// Evaluate `specifier` as the entry module, the way `qjs -m file.js` does.
    pub fn run_main_module(&mut self, specifier: &str) -> JsResult<Value> {
        let module = self.load_module(specifier, &[], "")?;
        let name = module.with(|r| r.name.clone());
        self.main_module_name = Some(name.clone());
        // The record was built before the name was known, so `main` is stamped now.
        if let Some(meta) = module.with(|r| r.import_meta.clone()) {
            meta.define_data("main", Value::Bool(true));
        }
        self.link_module(&module)?;
        self.module_stack.push(name);
        let result = self.evaluate_module_and_wait(&module);
        self.module_stack.pop();
        result?;
        self.module_namespace(&module)
    }

    /// Run a module whose bytecode the caller already has.
    ///
    /// This is `qjs`'s `-m` for an AOT binary: nothing is parsed or compiled, but the
    /// module's *requests* still go through the host loader, so a precompiled entry
    /// module can import ordinary source files. The blob's own file name is what those
    /// requests are resolved against, which is why it has to travel in the blob rather
    /// than be supplied at the call site.
    pub fn run_precompiled_module(&mut self, code: CompiledFunction) -> JsResult<Value> {
        let name = code
            .filename
            .clone()
            .unwrap_or_else(|| "<bytecode>".to_string());
        let url = name.clone();
        let module = self.module_record_from_code(&name, &url, code)?;
        self.main_module_name = Some(name.clone());
        // Registered under its own name before linking, so a module that imports itself
        // finds this record instead of re-entering the loader for a file that may not
        // exist at all.
        self.modules.insert(cache_key(&name, &[]), module.clone());
        if let Some(meta) = module.with(|r| r.import_meta.clone()) {
            meta.define_data("main", Value::Bool(true));
        }
        self.link_module(&module)?;
        self.module_stack.push(name);
        let result = self.evaluate_module_and_wait(&module);
        self.module_stack.pop();
        result?;
        self.module_namespace(&module)
    }

    /// Register a module from bytecode, so a later import finds it without a loader.
    ///
    /// This is what an AOT product does with the modules it carries: the names are the
    /// ones the *bundler* resolved, which are the ones this interpreter would have
    /// resolved through the loader, so an `import "./dep.js"` lands here instead of on the
    /// filesystem.
    ///
    /// The module is registered as `Unlinked`: nothing is wired up until something imports
    /// it (or it is the entry), which is what keeps a bundle's registration order
    /// irrelevant — a cycle among precompiled modules links the same way a cycle among
    /// source files does.
    pub fn register_module(&mut self, code: CompiledFunction) -> JsResult<String> {
        let name = code.filename.clone().ok_or_else(|| {
            Signal::Throw(self.make_error(
                "InternalError",
                "precompiled module has no name; it was serialized without its file name",
            ))
        })?;
        let url = name.clone();
        let record = self.module_record_from_code(&name, &url, code)?;
        self.modules.insert(cache_key(&name, &[]), record);
        Ok(name)
    }

    /// Register a JSON, text or bytes module from its bytes, by name.
    ///
    /// A data module is a value, not code, so it has no bytecode to carry: the bundle keeps
    /// the file's bytes and the product hands them here. `attributes` is what decided the
    /// kind at bundle time, and passing it again keeps the two ends from disagreeing about
    /// a `.json` file imported as text.
    pub fn register_data_module(
        &mut self,
        name: &str,
        source: Vec<u8>,
        attributes: &[(String, String)],
    ) -> JsResult<()> {
        let kind = match module_kind(name, attributes) {
            Ok(kind) => kind,
            Err(message) => return Err(Signal::Throw(self.make_error("TypeError", &message))),
        };
        let loaded = LoadedModule {
            name: name.to_string(),
            url: name.to_string(),
            source,
        };
        let record = self.data_module_record(&loaded, kind)?;
        self.modules.insert(cache_key(name, attributes), record);
        Ok(())
    }

    /// Register a native module: a name and the exports a library handed back.
    ///
    /// This is what `JS_NewCModule` amounts to. The record is born evaluated and carries one
    /// cell per export, so the namespace machinery — sorted names, read-only getters,
    /// `[object Module]` — is the ordinary one rather than a second implementation for C
    /// modules.
    ///
    /// The exports are in the order the library declared them, which is the order
    /// `JS_AddModuleExport` was called in; the namespace sorts them, as it does for every
    /// module.
    pub fn register_native_module(
        &mut self,
        name: &str,
        exports: Vec<(String, Value)>,
    ) -> Gc<ModuleRecord> {
        let mut cells = Vec::with_capacity(exports.len());
        let mut entries = Vec::with_capacity(exports.len());
        for (index, (export_name, value)) in exports.into_iter().enumerate() {
            cells.push(self.new_cell(value));
            entries.push(js_compile::bytecode::ExportEntry::Local {
                export_name,
                var_idx: index as u32,
            });
        }
        let record = Gc::new(
            self.heap,
            ModuleRecord::new(ModuleInner {
                name: name.to_string(),
                url: name.to_string(),
                code: None,
                meta: js_compile::bytecode::ModuleMeta {
                    requests: Vec::new(),
                    imports: Vec::new(),
                    exports: entries,
                },
                cells,
                // A native module's exports are values, not bindings to wire up: there is
                // nothing to resolve and nothing to run, so it starts evaluated. That is
                // also what lets an ordinary module import one inside a cycle.
                dependencies: Vec::new(),
                status: ModuleStatus::Evaluated,
                evaluation_error: None,
                async_evaluation: false,
                async_evaluation_order: 0,
                pending_async_dependencies: 0,
                async_parent_modules: Vec::new(),
                cycle_root: None,
                dfs_index: 0,
                dfs_ancestor_index: 0,
                top_level_capability: None,
                kind: ModuleKind::Native,
                namespace: None,
                deferred_namespace: None,
                import_meta: None,
                star_cells: BTreeMap::new(),
            }),
        );
        self.modules.insert(cache_key(name, &[]), record.clone());
        record
    }

    /// Load and compile one module.
    pub fn load_module(
        &mut self,
        specifier: &str,
        attributes: &[(String, String)],
        referrer: &str,
    ) -> JsResult<Gc<ModuleRecord>> {
        // A module that is already in memory — registered from bytecode, which is what an
        // AOT product does with its bundle — must be found *before* the loader runs. The
        // reference has the same ordering (`js_find_loaded_module` first, `js_module_loader`
        // only if that misses); getting it the other way round makes a product carry a
        // module and still report "could not load module filename" for it.
        //
        // With no loader installed at all, the textual rule is the only one there is: it is
        // what an AOT product relies on, since its modules are registered under exactly the
        // names that rule produces and it has no files to fall back to.
        let resolved = match self.module_loader.as_ref() {
            Some(loader) => loader.resolve(specifier, referrer),
            None => Some(js_parse::normalize_specifier(referrer, specifier)),
        };
        if let Some(resolved) = &resolved {
            if let Some(existing) = self.modules.get(&cache_key(resolved, attributes)) {
                return Ok(existing.clone());
            }
        }
        let Some(loader) = self.module_loader.take() else {
            // Not in memory and nothing to read it from. Report it as the missing *file* it
            // is, which is the reference's message for this case, rather than as an
            // internal error about the host's setup.
            let name = resolved.unwrap_or_else(|| specifier.to_string());
            return Err(Signal::Throw(self.make_error(
                "ReferenceError",
                &format!("could not load module filename '{name}'"),
            )));
        };
        // A native module is a record, not bytes: ask before reading anything. The name to
        // ask about is the one textual resolution produced, so a loader does not have to
        // repeat that rule.
        let native_name = resolved.clone().unwrap_or_else(|| specifier.to_string());
        let native = if attributes.is_empty() {
            loader.load_native(self, &native_name)
        } else {
            // A C module has no `with { type: … }` form; an attribute means the loader
            // must not treat this name as native.
            None
        };
        let loaded = match native {
            Some(Ok(record)) => {
                self.module_loader = Some(loader);
                let key = cache_key(&record.with(|r| r.name.clone()), attributes);
                self.modules.insert(key, record.clone());
                return Ok(record);
            }
            Some(Err(message)) => {
                self.module_loader = Some(loader);
                return Err(Signal::Throw(self.make_error("ReferenceError", &message)));
            }
            None => loader.load(specifier, attributes, referrer),
        };
        // Put the loader back whatever happened: it is the host's, and the interpreter
        // only borrows it so that `&mut self` stays available for compiling.
        self.module_loader = Some(loader);
        let mut loaded = match loaded {
            Ok(loaded) => loaded,
            Err(message) => {
                return Err(Signal::Throw(self.make_error("ReferenceError", &message)));
            }
        };
        // A host-supplied name for the entry module wins over the path. Only the entry:
        // `referrer` is empty for it and for nothing else, so a nested import keeps the name
        // its specifier resolved to.
        if referrer.is_empty()
            && let Some(name) = &self.entry_module_name
        {
            loaded.name = name.clone();
            loaded.url = name.clone();
        }
        // One record per *(name, attributes)*, so importing the same file twice runs it
        // once — but importing it as JSON and as text is two modules with two contents,
        // which `hello_module.js` does on purpose.
        let key = cache_key(&loaded.name, attributes);
        if let Some(existing) = self.modules.get(&key) {
            return Ok(existing.clone());
        }
        let kind = match module_kind(&loaded.name, attributes) {
            Ok(kind) => kind,
            Err(message) => {
                return Err(Signal::Throw(self.make_error("TypeError", &message)));
            }
        };
        let record = match kind {
            ModuleKind::JavaScript => self.compile_module_record(&loaded)?,
            _ => self.data_module_record(&loaded, kind)?,
        };
        self.modules.insert(key, record.clone());
        Ok(record)
    }

    /// Compile a JavaScript module and create its cells.
    fn compile_module_record(&mut self, loaded: &LoadedModule) -> JsResult<Gc<ModuleRecord>> {
        let source = match std::str::from_utf8(&loaded.source) {
            Ok(source) => source,
            Err(_) => {
                return Err(Signal::Throw(self.make_error(
                    "SyntaxError",
                    &format!("{}: module source is not valid UTF-8", loaded.name),
                )));
            }
        };
        // Same shape as a script's compile error: the message, then `at <file>:<line>:<col>`
        // unless the reference reports this one without a position. The file name is *not*
        // part of the message — it belongs on the `at` line only.
        let program = match js_parse::parse_module(source) {
            Ok(program) => program,
            Err(error) => {
                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
            }
        };
        let mut code = match js_compile::compile_module_with_source(&program, source) {
            Ok(code) => code,
            Err(error) => {
                return Err(Signal::Throw(self.syntax_error_plain(&error, &loaded.name)));
            }
        };
        code.set_filename(&loaded.name);
        self.module_record_from_code(&loaded.name, &loaded.url, code)
    }

    /// Build a module record around bytecode the caller already has.
    ///
    /// The one thing that separates this from [`Interp::compile_module_record`] is where
    /// the bytecode came from — source, or a blob written by an AOT compiler. Everything
    /// after that point is the same work: one cell per closure variable, a dependency slot
    /// per request, `import.meta`, and the record itself. Keeping it in one place is what
    /// makes a precompiled module behave like a compiled one rather than *almost* like one.
    fn module_record_from_code(
        &mut self,
        name: &str,
        url: &str,
        code: CompiledFunction,
    ) -> JsResult<Gc<ModuleRecord>> {
        let meta = code
            .module
            .as_ref()
            .map(|meta| (**meta).clone())
            .unwrap_or_default();
        let closure_vars = code.closure_vars.clone();
        let compiled = Gc::new(self.heap, CompiledCode::new(code));
        // One cell per closure variable. A lexical binding starts in its dead zone and a
        // `var` as `undefined`; an import's cell is *replaced* during linking by the
        // exporter's, which is what makes it live.
        let mut cells = Vec::with_capacity(closure_vars.len());
        for closure_var in &closure_vars {
            let initial = if closure_var.is_lexical {
                Value::Uninitialized
            } else {
                Value::Undefined
            };
            cells.push(self.new_cell(initial));
        }
        let dependencies = vec![None; meta.requests.len()];
        let record = Gc::new(
            self.heap,
            ModuleRecord::new(ModuleInner {
                name: name.to_string(),
                url: url.to_string(),
                code: Some(compiled),
                meta,
                cells,
                dependencies,
                status: ModuleStatus::Unlinked,
                evaluation_error: None,
                async_evaluation: false,
                async_evaluation_order: 0,
                pending_async_dependencies: 0,
                async_parent_modules: Vec::new(),
                cycle_root: None,
                dfs_index: 0,
                dfs_ancestor_index: 0,
                top_level_capability: None,
                kind: ModuleKind::JavaScript,
                namespace: None,
                deferred_namespace: None,
                import_meta: None,
                star_cells: BTreeMap::new(),
            }),
        );
        self.install_import_meta(&record)?;
        Ok(record)
    }

    /// A JSON, text or bytes module: one value, exported as `default`.
    ///
    /// The value is produced by calling the *builtin* rather than by reaching into the
    /// JSON parser or the typed-array internals, so a data module behaves exactly like
    /// `JSON.parse(text)` or `new Uint8Array(bytes)` written out by hand — one
    /// implementation of each, not two.
    fn data_module_record(
        &mut self,
        loaded: &LoadedModule,
        kind: ModuleKind,
    ) -> JsResult<Gc<ModuleRecord>> {
        let value = match kind {
            ModuleKind::Json => {
                let text = String::from_utf8_lossy(&loaded.source).to_string();
                let Some(json) = self.global_value("JSON") else {
                    return Err(Signal::Throw(
                        self.make_error("InternalError", "JSON is not installed"),
                    ));
                };
                let Some(Value::Object(json)) = Some(json) else {
                    unreachable!()
                };
                let Some(parse) = self.get_property(&json, "parse")? else {
                    return Err(Signal::Throw(
                        self.make_error("InternalError", "JSON.parse is not installed"),
                    ));
                };
                let text = self.string(&text);
                match self.call_value(parse, Value::Object(json), vec![text]) {
                    Ok(value) => value,
                    Err(Signal::Throw(reason)) => {
                        let detail = self.describe_exception(&reason);
                        return Err(Signal::Throw(self.make_error(
                            "SyntaxError",
                            &format!("{}: {}", loaded.name, detail),
                        )));
                    }
                    Err(other) => return Err(other),
                }
            }
            ModuleKind::Text => {
                // Taken as UTF-8 with replacement: a text file that is not valid UTF-8
                // still has to become a string.
                let text = String::from_utf8_lossy(&loaded.source).to_string();
                self.string(&text)
            }
            ModuleKind::Bytes => {
                let numbers: Vec<Value> = loaded
                    .source
                    .iter()
                    .map(|byte| Value::Int(*byte as i32))
                    .collect();
                let elements = self.new_array(numbers);
                let Some(Value::Object(ctor)) = self.global_value("Uint8Array") else {
                    return Err(Signal::Throw(
                        self.make_error("InternalError", "Uint8Array is not installed"),
                    ));
                };
                self.construct(
                    Value::Object(ctor),
                    Value::Object(elements.clone()),
                    vec![Value::Object(elements)],
                )?
            }
            ModuleKind::JavaScript | ModuleKind::Native => {
                unreachable!("handled by `compile_module_record`")
            }
        };
        let cell = self.new_cell(value.clone());
        let record = Gc::new(
            self.heap,
            ModuleRecord::new(ModuleInner {
                name: loaded.name.clone(),
                url: loaded.url.clone(),
                code: None,
                meta: js_compile::bytecode::ModuleMeta {
                    requests: Vec::new(),
                    imports: Vec::new(),
                    exports: vec![js_compile::bytecode::ExportEntry::Local {
                        export_name: "default".to_string(),
                        var_idx: 0,
                    }],
                },
                cells: vec![cell],
                dependencies: Vec::new(),
                // Nothing to link and nothing to run: a data module is born evaluated,
                // which is what lets `import x from "./m.json"` work inside a cycle.
                status: ModuleStatus::Evaluated,
                evaluation_error: None,
                async_evaluation: false,
                async_evaluation_order: 0,
                pending_async_dependencies: 0,
                async_parent_modules: Vec::new(),
                cycle_root: None,
                dfs_index: 0,
                dfs_ancestor_index: 0,
                top_level_capability: None,
                kind,
                namespace: None,
                deferred_namespace: None,
                import_meta: None,
                star_cells: BTreeMap::new(),
            }),
        );
        Ok(record)
    }

    /// A binding of the global object, if it exists.
    fn global_value(&mut self, name: &str) -> Option<Value> {
        let global = self.realm.global.clone();
        self.get_property(&global, name).ok().flatten()
    }

    /// `import.meta` for `record`, built once.
    fn install_import_meta(&mut self, record: &Gc<ModuleRecord>) -> JsResult<()> {
        // §16.2.1.10 / HostGetImportMetaProperties: `import.meta` is an **ordinary object
        // with a null prototype**. That is observable and test262 leans on it —
        // `dynamic-import/assignment-expression/import-meta` does `import(import.meta)` and
        // expects the promise to *reject with a `TypeError`*, which only happens if
        // `ToString` cannot find a `toString` through a prototype. Giving it
        // `Object.prototype` (as this did) made that conversion succeed and the import ask
        // for a module named "[object Object]".
        let meta = self.new_object(None);
        let url = self.string(record.with(|r| r.url.clone()));
        // Only the two properties the reference defines; a script can add its own.
        meta.define_data("url", url);
        meta.define_data("main", Value::Bool(false));
        record.with_mut(|r| r.import_meta = Some(meta));
        Ok(())
    }

    /// Resolve every import of `module` and validate its exports, depth-first.
    pub fn link_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
        match module.with(|r| r.status) {
            // Already linked, or being linked right now — the latter is a cycle, and it is
            // exactly why the status is set *before* recursing: a cycle stops here rather
            // than recursing forever.
            ModuleStatus::Linking
            | ModuleStatus::Linked
            | ModuleStatus::Evaluating
            | ModuleStatus::EvaluatingAsync
            | ModuleStatus::Evaluated => {
                return Ok(());
            }
            ModuleStatus::Unlinked => {}
        }
        module.with_mut(|r| r.status = ModuleStatus::Linking);

        let requests = module.with(|r| r.meta.requests.clone());
        for (index, request) in requests.iter().enumerate() {
            let referrer = module.with(|r| r.name.clone());
            let dependency =
                self.load_module(&request.specifier, &request.attributes, &referrer)?;
            module.with_mut(|r| r.dependencies[index] = Some(dependency.clone()));
            self.link_module(&dependency)?;
        }

        // Wire the cells. `import { x } from "m"` makes this module's cell *be* `m`'s, so
        // a later assignment over there is visible here with no copying.
        let imports = module.with(|r| r.meta.imports.clone());
        for entry in &imports {
            let dependency =
                module.with(|r| r.dependencies.get(entry.module as usize).cloned().flatten());
            let Some(dependency) = dependency else {
                return Err(Signal::Throw(self.make_error(
                    "InternalError",
                    "an import names a module that was not loaded",
                )));
            };
            if entry.is_star {
                // `import defer * as ns` binds the deferred namespace — a different object
                // from the eager one, and the only way a `defer` request is observable.
                let namespace = if entry.phase == ImportPhase::Defer {
                    self.module_deferred_namespace(&dependency)?
                } else {
                    self.module_namespace(&dependency)?
                };
                let cell = module.with(|r| r.cells[entry.var_idx as usize].clone());
                cell.set(namespace);
                continue;
            }
            let cell = self.resolve_export(&dependency, &entry.name)?;
            module.with_mut(|r| r.cells[entry.var_idx as usize] = cell);
        }

        // Validate: `export { a } from "m"` where `m` has no `a` is a link error, and
        // saying so now beats an `undefined` that surfaces much later.
        let exports = module.with(|r| r.meta.exports.clone());
        for entry in &exports {
            if let js_compile::bytecode::ExportEntry::Indirect {
                export_name,
                module: index,
                import_name,
            } = entry
            {
                let dependency =
                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
                let Some(dependency) = dependency else {
                    continue;
                };
                // A namespace re-export names the dependency's *namespace*, which is not an
                // export of it and therefore has nothing to validate.
                if import_name == "*namespace*" {
                    continue;
                }
                if self.resolve_export(&dependency, import_name).is_err() {
                    let dependency_name = dependency.with(|r| r.name.clone());
                    return Err(Signal::Throw(self.make_error(
                        "SyntaxError",
                        &format!(
                            "Could not find export '{import_name}' in module '{dependency_name}' (re-exported as '{export_name}')"
                        ),
                    )));
                }
            }
        }

        // Create the module's hoisted bindings *now*, while linking — before any body
        // runs anywhere in the graph.
        //
        // This is the whole trick behind cyclic imports. The body's prologue is
        // `push_this; if_false <body>`, so calling it with a truthy `this` runs only the
        // hoisted declarations and returns. Doing that for every module during linking
        // means that when evaluation finally starts, every exported function in the
        // cycle already exists — which is why `b.js` can see `a`'s function even though
        // `a.js` has not run yet.
        self.hoist_module_bindings(module)?;

        module.with_mut(|r| r.status = ModuleStatus::Linked);
        Ok(())
    }

    /// Run `module`'s prologue only, creating its hoisted bindings.
    fn hoist_module_bindings(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
        let Some(code) = module.with(|r| r.code.clone()) else {
            // A JSON/text module has nothing to hoist.
            return Ok(());
        };
        let env = self.module_env(module);
        self.execute(code, env, Value::Bool(true), Vec::new(), Value::Undefined)
            .map(|_| ())
    }

    /// The closure environment a module body runs in: one cell per closure variable.
    fn module_env(&mut self, module: &Gc<ModuleRecord>) -> Gc<ClosureEnv> {
        let cells = module.with(|r| r.cells.clone());
        Gc::new(
            self.heap,
            ClosureEnv {
                cells,
                eval_scope: None,
                local_vars: None,
                local_phase: 0,
            },
        )
    }

    /// The cell behind `name` in `module`, following re-exports.
    pub fn resolve_export(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Gc<Cell>> {
        match self.resolve_export_inner(module, name, 0)? {
            Resolution::Cell { cell, .. } => Ok(cell),
            Resolution::NotFound => Err(self.missing_export(module, name)),
            Resolution::Ambiguous => Err(self.ambiguous_export(module, name)),
        }
    }

    /// The wrapper cell behind a module's *own* namespace, cached so its identity is stable.
    ///
    /// Same reason as `star_cells`: the ambiguity test compares `(module, binding)`, and an
    /// `import * as ns` re-export resolves to `{ m, *namespace* }`, so two paths reaching the
    /// same module's namespace must agree that they name one binding.
    fn namespace_cell(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<Cell>> {
        self.namespace_cell_of_phase(module, false)
    }

    /// The same, but the wrapper holds the *deferred* namespace.
    fn deferred_namespace_cell(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<Cell>> {
        self.namespace_cell_of_phase(module, true)
    }

    fn namespace_cell_of_phase(
        &mut self,
        module: &Gc<ModuleRecord>,
        deferred: bool,
    ) -> JsResult<Gc<Cell>> {
        let key = if deferred {
            "*deferred-namespace*"
        } else {
            "*namespace*"
        };
        if let Some(cell) = module.with(|r| r.star_cells.get(key).cloned()) {
            return Ok(cell);
        }
        let namespace = if deferred {
            self.module_deferred_namespace(module)?
        } else {
            self.module_namespace(module)?
        };
        let cell = self.new_cell(namespace);
        module.with_mut(|r| r.star_cells.insert(key.to_string(), cell.clone()));
        Ok(cell)
    }

    /// Why a name that two `export *` declarations both provide cannot be resolved.
    ///
    /// §16.2.1.6.3 `ResolveExport` returns **ambiguous** rather than picking one, and
    /// `GetExportedNames`/`ResolveExport` feed link-time validation: a module with an
    /// ambiguous name fails to link, so `import()` of it rejects with a `SyntaxError`.
    /// Taking the first success instead — which is what the star loop used to do — made the
    /// module load fine and hand back a namespace, and test262's `instn-iee-err-ambiguous`
    /// family checks exactly that rejection.
    fn ambiguous_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
        let module_name = module.with(|r| r.name.clone());
        Signal::Throw(self.make_error(
            "SyntaxError",
            &format!("Ambiguous export '{name}' in module '{module_name}'"),
        ))
    }

    fn resolve_export_inner(
        &mut self,
        module: &Gc<ModuleRecord>,
        name: &str,
        depth: usize,
    ) -> JsResult<Resolution> {
        // A pathological chain (`a` exports from `b`, `b` from `a`) would otherwise
        // recurse until the Rust stack gives out.
        if depth > 64 {
            return Err(Signal::Throw(
                self.make_error("SyntaxError", "circular re-export chain"),
            ));
        }
        let exports = module.with(|r| r.meta.exports.clone());
        // An explicit export wins over any `export *`.
        for entry in &exports {
            match entry {
                js_compile::bytecode::ExportEntry::Local {
                    export_name,
                    var_idx,
                } if export_name == name => {
                    return Ok(Resolution::Cell {
                        cell: module.with(|r| r.cells[*var_idx as usize].clone()),
                        module: module.clone(),
                        binding: name.to_string(),
                    });
                }
                js_compile::bytecode::ExportEntry::Indirect {
                    export_name,
                    module: index,
                    import_name,
                } if export_name == name => {
                    let dependency =
                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
                    let Some(dependency) = dependency else {
                        return Ok(Resolution::NotFound);
                    };
                    // `import * as ns from "m"; export { ns }` — §16.2.1.6.3 step 7 resolves
                    // to `{ [[Module]]: m, [[BindingName]]: namespace }`, so the identity is
                    // the *target* module and not this one.
                    if import_name == "*namespace*" {
                        // A `defer` request re-exported this way still hands back the
                        // *deferred* namespace: the phase belongs to the request, and
                        // reading through the export is what has to trigger evaluation.
                        let phase = module.with(|r| {
                            r.meta
                                .requests
                                .get(*index as usize)
                                .map(|request| request.phase)
                        });
                        let cell = if phase == Some(ImportPhase::Defer) {
                            self.deferred_namespace_cell(&dependency)?
                        } else {
                            self.namespace_cell(&dependency)?
                        };
                        return Ok(Resolution::Cell {
                            cell,
                            module: dependency,
                            binding: "*namespace*".to_string(),
                        });
                    }
                    return self.resolve_export_inner(&dependency, import_name, depth + 1);
                }
                js_compile::bytecode::ExportEntry::StarAs { export_name, .. }
                    if export_name == name =>
                {
                    // The namespace of the re-exported module, wrapped in a cell so the
                    // export table stays uniform. The cell is **cached per name**: the
                    // ambiguity test below compares binding identities, and a fresh cell on
                    // every lookup made one export look like two.
                    let target = module.with(|r| {
                        r.meta.exports.iter().find_map(|entry| match entry {
                            js_compile::bytecode::ExportEntry::StarAs {
                                export_name,
                                module: index,
                            } if export_name == name => Some(*index),
                            _ => None,
                        })
                    });
                    let Some(index) = target else {
                        return Ok(Resolution::NotFound);
                    };
                    let dependency =
                        module.with(|r| r.dependencies.get(index as usize).cloned().flatten());
                    let Some(dependency) = dependency else {
                        return Ok(Resolution::NotFound);
                    };
                    if let Some(cell) = module.with(|r| r.star_cells.get(name).cloned()) {
                        return Ok(Resolution::Cell {
                            cell,
                            module: dependency,
                            binding: "*namespace*".to_string(),
                        });
                    }
                    let namespace = self.star_namespace(module, name)?;
                    let cell = self.new_cell(namespace);
                    module.with_mut(|r| r.star_cells.insert(name.to_string(), cell.clone()));
                    return Ok(Resolution::Cell {
                        cell,
                        module: dependency,
                        binding: "*namespace*".to_string(),
                    });
                }
                _ => {}
            }
        }
        // `export * from "m"`: forwarded names are visible only if nothing above claimed
        // them, which is why this is a second pass.
        //
        // Two stars that reach the **same** binding are not ambiguous — `export * from "a";
        // export * from "b"` where both re-export `c`'s `x` resolves to one thing. Two that
        // reach different bindings are, and the comparison is on the binding itself (the
        // module's cell for that name), not on the name.
        let mut found: Option<Resolution> = None;
        for entry in &exports {
            if let js_compile::bytecode::ExportEntry::Star { module: index } = entry {
                let dependency =
                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
                let Some(dependency) = dependency else {
                    continue;
                };
                match self.resolve_export_inner(&dependency, name, depth + 1)? {
                    resolution @ Resolution::Cell { .. } => match &found {
                        None => found = Some(resolution),
                        Some(previous) if !previous.same_binding(&resolution) => {
                            return Ok(Resolution::Ambiguous);
                        }
                        Some(_) => {}
                    },
                    Resolution::NotFound => {}
                    // A nested ambiguity is not ours to resolve: it makes *this* name
                    // ambiguous too, which is what the caller needs to hear.
                    Resolution::Ambiguous => return Ok(Resolution::Ambiguous),
                }
            }
        }
        Ok(found.unwrap_or(Resolution::NotFound))
    }

    fn missing_export(&self, module: &Gc<ModuleRecord>, name: &str) -> Signal {
        let module_name = module.with(|r| r.name.clone());
        // The reference's wording, kept verbatim: an error message is part of the
        // behaviour a user sees, and `qjs` says "Could not find export".
        Signal::Throw(self.make_error(
            "SyntaxError",
            &format!("Could not find export '{name}' in module '{module_name}'"),
        ))
    }

    /// The namespace behind `export * as ns from "m"`.
    fn star_namespace(&mut self, module: &Gc<ModuleRecord>, name: &str) -> JsResult<Value> {
        let exports = module.with(|r| r.meta.exports.clone());
        for entry in &exports {
            if let js_compile::bytecode::ExportEntry::StarAs {
                export_name,
                module: index,
            } = entry
                && export_name == name
            {
                let dependency =
                    module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
                let Some(dependency) = dependency else {
                    continue;
                };
                return self.module_namespace(&dependency);
            }
        }
        Ok(Value::Undefined)
    }

    /// The names `module` exports, sorted the way §16.2.1.6 requires.
    pub fn module_export_names(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Vec<String>> {
        let mut names: Vec<String> = Vec::new();
        self.collect_export_names(module, &mut names, 0)?;
        names.sort();
        names.dedup();
        Ok(names)
    }

    fn collect_export_names(
        &mut self,
        module: &Gc<ModuleRecord>,
        out: &mut Vec<String>,
        depth: usize,
    ) -> JsResult<()> {
        if depth > 64 {
            return Ok(());
        }
        let exports = module.with(|r| r.meta.exports.clone());
        for entry in &exports {
            match entry {
                js_compile::bytecode::ExportEntry::Local { export_name, .. }
                | js_compile::bytecode::ExportEntry::Indirect { export_name, .. }
                | js_compile::bytecode::ExportEntry::StarAs { export_name, .. } => {
                    out.push(export_name.clone());
                }
                js_compile::bytecode::ExportEntry::Star { module: index } => {
                    let dependency =
                        module.with(|r| r.dependencies.get(*index as usize).cloned().flatten());
                    if let Some(dependency) = dependency {
                        let mut forwarded = Vec::new();
                        self.collect_export_names(&dependency, &mut forwarded, depth + 1)?;
                        // `export *` never forwards `default` (§16.2.1.6.2).
                        out.extend(forwarded.into_iter().filter(|name| name != "default"));
                    }
                }
            }
        }
        Ok(())
    }

    /// The namespace object of `module`, built on first use.
    ///
    /// An ordinary object with one read-only getter per export, inserted in sorted order.
    /// The getter reads the cell, which is what makes the binding live: `export let x`
    /// followed by `x = 1` in the exporting module is visible here without copying.
    pub fn module_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
        self.build_namespace(module, false)
    }

    /// The *deferred* namespace object of `module`, built on first use.
    ///
    /// Identical to [`Interp::module_namespace`] in every observable way except one: reading
    /// it evaluates the module first. That is import-defer's `[[Deferred]]`, which is a
    /// property of the *object*, not of the module — one module can be imported both ways
    /// and the two namespaces are distinct objects.
    pub fn module_deferred_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value> {
        self.build_namespace(module, true)
    }

    fn build_namespace(&mut self, module: &Gc<ModuleRecord>, deferred: bool) -> JsResult<Value> {
        let cached = module.with(|r| {
            if deferred {
                r.deferred_namespace.clone()
            } else {
                r.namespace.clone()
            }
        });
        if let Some(namespace) = cached {
            return Ok(Value::Object(namespace));
        }
        let names = self.module_export_names(module)?;
        let function_proto = self.realm.function_proto.clone();
        // §10.4.6.1: a namespace's `[[Prototype]]` is **null**.
        //
        // Not `Object.prototype` with things taken away: `Object.getPrototypeOf(ns)` is
        // `null` and `ns instanceof Object` is `false`, which test262 asserts directly in
        // both namespace families. Handing it `object_proto` also leaked every `Object.prototype`
        // member into the namespace, so `ns.hasOwnProperty` answered a function.
        let namespace = self.new_object(None);
        namespace.set_module_namespace();
        for name in &names {
            // §16.2.1.5.2 `GetModuleNamespace` keeps only the **unambiguous** names: a name
            // that two `export *` provide is left out of the namespace rather than making
            // the module unloadable. Importing it is still an error, which is why
            // `resolve_export` reports ambiguity — but a namespace is a menu, and a dish two
            // suppliers disagree about is simply not on it (`omitted-from-namespace`).
            let cell = match self.resolve_export_inner(module, name, 0)? {
                Resolution::Cell { cell, .. } => cell,
                Resolution::NotFound | Resolution::Ambiguous => continue,
            };
            let getter = JsObject::function(
                self.heap,
                Some(function_proto.clone()),
                Callable::ModuleBinding { cell },
            );
            namespace.define(
                name,
                Property {
                    value: None,
                    getter: Some(Value::Object(getter)),
                    setter: None,
                    writable: false,
                    enumerable: true,
                    configurable: false,
                    descriptor_fields: None,
                },
            );
        }
        // A namespace reports `[object Module]`, and cannot gain properties. A *deferred*
        // one says "Deferred Module" — the one visible difference between the two objects,
        // and what a test can use to tell them apart.
        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
        let tag = self.string(if deferred {
            "Deferred Module"
        } else {
            "Module"
        });
        namespace.define_key(&tag_key, Property::with_attributes(tag, false, false));
        self.object_prevent_extensions(&namespace)?;
        if deferred {
            namespace.set_deferred_namespace_module(module.clone());
        }
        module.with_mut(|r| {
            if deferred {
                r.deferred_namespace = Some(namespace.clone());
            } else {
                r.namespace = Some(namespace.clone());
            }
        });
        Ok(Value::Object(namespace))
    }

    /// §16.2.1.5.3.2 `Evaluate()` — start evaluating `module`, answer its completion promise.
    ///
    /// Nearly every caller of the old `evaluate_module_body` wants this instead, because
    /// with top-level `await` "evaluating" is no longer a call that returns when it is
    /// done: it is a *promise*. The one thing the promise guarantees is that whoever holds
    /// it learns when the graph finished, which is what `import()` and the entry point both
    /// need.
    ///
    /// `[[TopLevelCapability]]` is per **cycle root**, not per module, and it is created
    /// once: a second `import()` of a module that is still waiting chains onto the very
    /// same promise, so it cannot observe a completion the first one has not seen yet
    /// (`module-code/top-level-await/dynamic-import-of-waiting-module`).
    pub fn evaluate_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Gc<JsObject>> {
        // Already under way, or finished: the promise belongs to the cycle root.
        let root = match module.with(|r| r.status) {
            ModuleStatus::EvaluatingAsync | ModuleStatus::Evaluated => {
                let root = cycle_root_of(module);
                module.with_mut(|r| r.cycle_root = Some(root.clone()));
                root
            }
            _ => module.clone(),
        };
        if let Some((promise, _, _)) = root.with(|r| r.top_level_capability.clone()) {
            return Ok(promise);
        }
        let (capability, resolve, reject) = self.new_promise_capability();
        root.with_mut(|r| r.top_level_capability = Some((capability.clone(), resolve, reject)));

        if root.with(|r| r.status) != ModuleStatus::Linked {
            // Started by someone else and finished before we got here; the promise was
            // created above for that case and is settled below.
            self.settle_from_record(&root);
            return Ok(capability);
        }

        let mut stack: Vec<Gc<ModuleRecord>> = Vec::new();
        let mut index = 0usize;
        match self.inner_module_evaluation(&root, &mut stack, &mut index, false) {
            Ok(()) => {
                // A cycle that became async keeps its promise for the async machinery to
                // settle; everything else is done and settles itself.
                if !root.with(|r| r.async_evaluation) {
                    self.settle_from_record(&root);
                    debug_assert_eq!(root.with(|r| r.status), ModuleStatus::Evaluated);
                }
            }
            Err(Signal::Throw(reason)) => {
                // §16.2.1.5.3.2 step 5.c: every module still on the stack failed with the
                // same completion. Leaving them `Evaluating` would let a later `import()` of
                // one of them run its body again.
                for failed in stack.drain(..) {
                    failed.with_mut(|r| {
                        if r.status == ModuleStatus::Evaluating
                            || r.status == ModuleStatus::EvaluatingAsync
                        {
                            r.evaluation_error = Some(reason.clone());
                            r.status = ModuleStatus::Evaluated;
                            r.async_evaluation = false;
                            r.cycle_root = Some(root.clone());
                        }
                    });
                }
                let (_, _, reject_fn) = root
                    .with(|r| r.top_level_capability.clone())
                    .expect("just created");
                self.call_value(reject_fn, Value::Undefined, vec![reason])?;
            }
            Err(other) => return Err(other),
        }
        Ok(capability)
    }

    /// Evaluate `module` and drive the job queue until it is done.
    ///
    /// This is what the *host* does — `qjs -m file.js` cannot return a promise, so the entry
    /// point blocks — and it is the only place in this engine that waits on module
    /// evaluation. Everything inside the graph is promise-driven so that a module with a
    /// top-level `await` defers itself and nothing else.
    pub fn evaluate_module_and_wait(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
        let promise = self.evaluate_module(module)?;
        self.drain_jobs()?;
        match self
            .promise_state(&promise)
            .map(|state| state.borrow().status.clone())
        {
            Some(crate::object::PromiseStatus::Fulfilled(_)) => Ok(()),
            Some(crate::object::PromiseStatus::Rejected(reason)) => Err(Signal::Throw(reason)),
            Some(crate::object::PromiseStatus::Pending) => Err(Signal::Throw(self.make_error(
                "TypeError",
                "promise is pending: top-level await never settled",
            ))),
            None => Ok(()),
        }
    }

    /// §16.2.1.5.3.1 `EvaluateSync(module)` — run a module to completion *now*.
    ///
    /// The entry point behind `EnsureDeferredNamespaceEvaluation`, and a genuinely different
    /// one from [`Interp::evaluate_module`]: it does not create a capability, it does not
    /// wait, and it does not park. The caller has already asked
    /// [`Interp::ready_for_sync_execution`] and been told that nothing on the graph is
    /// suspended, so every body it reaches can run to its end synchronously.
    fn evaluate_module_sync(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
        match module.with(|r| r.status) {
            ModuleStatus::Evaluated => {
                return match module.with(|r| r.evaluation_error.clone()) {
                    Some(error) => Err(Signal::Throw(error)),
                    None => Ok(()),
                };
            }
            ModuleStatus::Evaluating | ModuleStatus::EvaluatingAsync => {
                return Err(self.type_error(
                    "cannot read a deferred module namespace while its module is evaluating",
                ));
            }
            _ => {}
        }
        let mut stack = Vec::new();
        let mut index = 0usize;
        match self.inner_module_evaluation(module, &mut stack, &mut index, true) {
            Ok(()) => Ok(()),
            Err(Signal::Throw(reason)) => {
                for failed in stack.drain(..) {
                    failed.with_mut(|r| {
                        r.evaluation_error = Some(reason.clone());
                        r.status = ModuleStatus::Evaluated;
                    });
                }
                Err(Signal::Throw(reason))
            }
            Err(other) => Err(other),
        }
    }

    /// Settle a finished module's top-level capability from its recorded outcome.
    ///
    /// A no-op when the module is not finished yet, which is the async case: there the
    /// settlement arrives through the body's promise instead.
    fn settle_from_record(&mut self, module: &Gc<ModuleRecord>) {
        if module.with(|r| r.status) != ModuleStatus::Evaluated {
            return;
        }
        let Some((promise, resolve, reject)) = module.with(|r| r.top_level_capability.clone())
        else {
            return;
        };
        if self.promise_state(&promise).is_some_and(|state| {
            !matches!(state.borrow().status, crate::object::PromiseStatus::Pending)
        }) {
            return;
        }
        match module.with(|r| r.evaluation_error.clone()) {
            Some(error) => {
                let _ = self.call_value(reject, Value::Undefined, vec![error]);
            }
            None => {
                let _ = self.call_value(resolve, Value::Undefined, vec![Value::Undefined]);
            }
        }
    }

    /// §16.2.1.5.3.1 `InnerModuleEvaluation`.
    ///
    /// Depth-first, once each, with the DFS indices the spec uses to find cycles and the
    /// async bookkeeping that decides who executes and in what order. A sync module runs
    /// its body here and is done; an async one starts its body, parks in
    /// `EvaluatingAsync`, and is finished later by
    /// [`Interp::async_module_execution_fulfilled`].
    fn inner_module_evaluation(
        &mut self,
        module: &Gc<ModuleRecord>,
        stack: &mut Vec<Gc<ModuleRecord>>,
        index: &mut usize,
        sync_only: bool,
    ) -> JsResult<()> {
        // Already started, or finished: follow a cycle root and report a stored failure.
        if matches!(
            module.with(|r| r.status),
            ModuleStatus::EvaluatingAsync | ModuleStatus::Evaluated
        ) {
            if let Some(error) = module.with(|r| r.evaluation_error.clone()) {
                return Err(Signal::Throw(error));
            }
            return Ok(());
        }
        // On the stack right now: a cycle, which terminates here.
        if module.with(|r| r.status) == ModuleStatus::Evaluating {
            return Ok(());
        }
        module.with_mut(|r| {
            r.status = ModuleStatus::Evaluating;
            r.dfs_index = *index;
            r.dfs_ancestor_index = *index;
            r.pending_async_dependencies = 0;
        });
        *index += 1;
        stack.push(module.clone());

        // The requests, flattened the way §16.2.1.5.3.1 asks: one entry per request, except
        // that a `defer` request contributes its *asynchronous* transitive dependencies and
        // not itself. That is what keeps
        // `import defer * as ns from "./later.js"` from running `later.js` while still
        // running `later.js`'s own top-level awaits, whose ordering no importer may move.
        let requests = module.with(|r| r.meta.requests.clone());
        let mut evaluation_list: Vec<Gc<ModuleRecord>> = Vec::new();
        let mut seen: Vec<usize> = Vec::new();
        for (position, request) in requests.iter().enumerate() {
            let Some(required) = module.with(|r| r.dependencies.get(position).cloned().flatten())
            else {
                continue;
            };
            if request.phase == ImportPhase::Defer {
                self.gather_asynchronous_transitive_dependencies(
                    &required,
                    &mut seen,
                    &mut evaluation_list,
                );
            } else if !evaluation_list.iter().any(|m| m.ptr_eq(&required)) {
                evaluation_list.push(required);
            }
        }

        for required in &evaluation_list {
            self.inner_module_evaluation(required, stack, index, sync_only)?;
            // §16.2.1.5.3.1 step 11.c: what the required module's *state* means for us.
            //
            // `evaluating` means it is above us on the stack — a cycle — and its ancestor
            // index is ours. Anything else is finished or parked, and a parked one is a
            // dependency we will have to wait for.
            //
            // The `evaluating` case still has to be checked for `[[AsyncEvaluation]]`, and
            // that is the whole point of `pending-async-dep-from-cycle`: a module that is
            // *still on the stack* has nevertheless already run its own request loop and
            // parked at its top-level `await`, so it holds an `[[AsyncEvaluationOrder]]`
            // while its status is still `evaluating`. Step 11.c.v tests that field on
            // `requiredModule` **as it stands** — only step 11.c.iv replaces it with the
            // cycle root, and that branch is the other one. Skipping the test here made the
            // importer believe it had no async dependency and run its body before the cycle
            // leaf had finished.
            let status = required.with(|r| r.status);
            let (waiting_on, parked) = if status == ModuleStatus::Evaluating {
                let ancestor = required.with(|r| r.dfs_ancestor_index);
                module.with_mut(|r| r.dfs_ancestor_index = r.dfs_ancestor_index.min(ancestor));
                let parked = required.with(|r| r.async_evaluation);
                (required.clone(), parked)
            } else {
                let root = cycle_root_of(required);
                root.with_mut(|r| r.cycle_root = Some(root.clone()));
                if let Some(error) = root.with(|r| r.evaluation_error.clone()) {
                    return Err(Signal::Throw(error));
                }
                let parked = root.with(|r| r.async_evaluation);
                (root, parked)
            };
            // `sync_only` is `EvaluateSync`, which reaches a module through a deferred
            // namespace read rather than through `InnerModuleEvaluation`'s own recursion.
            // `ReadyForSyncExecution` has already established that nothing on the chain is
            // *actually* waiting — an `evaluated` module short-circuits the walk even when
            // its cycle root is parked — so counting the pending dependency here would park
            // a module that the proposal requires to run right now.
            if parked && !sync_only {
                module.with_mut(|r| r.pending_async_dependencies += 1);
                waiting_on.with_mut(|r| r.async_parent_modules.push(module.clone()));
            }
        }

        // §16.2.1.5.3.1 steps 12–14: run it, start it, or park it.
        let pending = module.with(|r| r.pending_async_dependencies);
        if sync_only {
            // `EvaluateSync`: run the body here, whatever the request list said. A module
            // with top-level `await` cannot be reached this way — `ReadyForSyncExecution`
            // refuses it — so this is the plain synchronous execution.
            self.execute_module_body_only(module)?;
            module.with_mut(|r| r.status = ModuleStatus::Evaluated);
        } else if pending > 0 {
            module.with_mut(|r| {
                r.async_evaluation = true;
                r.async_evaluation_order = self.next_module_async_evaluation_order;
            });
            self.next_module_async_evaluation_order += 1;
        } else if module.has_tla() {
            module.with_mut(|r| {
                r.async_evaluation = true;
                r.async_evaluation_order = self.next_module_async_evaluation_order;
            });
            self.next_module_async_evaluation_order += 1;
            self.execute_async_module(module)?;
        } else {
            self.execute_module_body_only(module)?;
        }

        // §16.2.1.5.3.1 steps 15–17: when we are the root of the cycle we just closed, pop
        // it. Modules that stayed sync are finished; the ones that parked become
        // `EvaluatingAsync` and remember who owns their completion.
        let index_here = module.with(|r| r.dfs_index);
        let ancestor_here = module.with(|r| r.dfs_ancestor_index);
        if index_here == ancestor_here {
            loop {
                let Some(popped) = stack.pop() else { break };
                popped.with_mut(|r| {
                    r.status = if r.async_evaluation && !sync_only {
                        ModuleStatus::EvaluatingAsync
                    } else {
                        ModuleStatus::Evaluated
                    };
                    r.cycle_root = Some(module.clone());
                });
                if popped.ptr_eq(module) {
                    break;
                }
            }
        }
        Ok(())
    }

    /// Run `module`'s body once, as an ordinary synchronous call.
    ///
    /// The hoisted bindings already exist: `link_module` ran the prologue pass with a truthy
    /// `this`, which is what the guard in the compiled prefix detects. Here the receiver is
    /// `undefined`, so the body itself runs.
    fn execute_module_body_only(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
        let Some(code) = module.with(|r| r.code.clone()) else {
            // A JSON/text/native module has no body; its value is already in its cell.
            return Ok(());
        };
        let name = module.with(|r| r.name.clone());
        let env = self.module_env(module);
        self.module_stack.push(name);
        let result = self.execute(code, env, Value::Undefined, Vec::new(), Value::Undefined);
        self.module_stack.pop();
        result.map(|_| ())
    }

    /// §16.2.1.5.3.1 `ExecuteAsyncModule` — start a body with top-level `await` and arrange
    /// to be told when it settles.
    ///
    /// The body returns a promise; the two handlers are the whole of the async machinery's
    /// entry point. Nothing here waits — that is the point. Waiting is what the old
    /// implementation did, and it is why a module with a top-level `await` used to block
    /// every sibling in the graph instead of merely deferring itself.
    fn execute_async_module(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
        let Some(code) = module.with(|r| r.code.clone()) else {
            return Ok(());
        };
        let name = module.with(|r| r.name.clone());
        let env = self.module_env(module);
        self.module_stack.push(name);
        let started = self.run_async_body(code, env, Value::Undefined);
        self.module_stack.pop();
        let promise = match started {
            Ok(promise) => promise,
            Err(Signal::Throw(reason)) => {
                // A body that throws before its first `await` still answers a promise, so
                // this is not a completion — but if it happens, treat it as one rather than
                // losing it.
                return Err(Signal::Throw(reason));
            }
            Err(other) => return Err(other),
        };
        let Value::Object(promise) = promise else {
            return Ok(());
        };
        let on_fulfilled = JsObject::function(
            self.heap,
            Some(self.realm.function_proto.clone()),
            Callable::ModuleEvaluationFulfilled {
                module: module.clone(),
            },
        );
        let on_rejected = JsObject::function(
            self.heap,
            Some(self.realm.function_proto.clone()),
            Callable::ModuleEvaluationRejected {
                module: module.clone(),
            },
        );
        self.perform_then(
            &promise,
            Some(Value::Object(on_fulfilled)),
            Some(Value::Object(on_rejected)),
        )?;
        Ok(())
    }

    /// §16.2.1.5.3.1 `GatherAvailableAncestors` — who became ready because `module` finished.
    ///
    /// Each module waiting on `module` loses one pending dependency. One that reaches zero
    /// joins the list, and only a module *without* top-level `await` lets the walk continue
    /// through it: one with TLA has not run its body yet, so it cannot have finished for
    /// anybody else.
    fn gather_available_ancestors(
        &mut self,
        module: &Gc<ModuleRecord>,
        exec_list: &mut Vec<Gc<ModuleRecord>>,
    ) {
        let parents = module.with(|r| r.async_parent_modules.clone());
        for parent in parents {
            if exec_list.iter().any(|m| m.ptr_eq(&parent)) {
                continue;
            }
            if cycle_root_of(&parent).with(|r| r.evaluation_error.is_some()) {
                continue;
            }
            let ready = parent.with_mut(|r| {
                if r.pending_async_dependencies > 0 {
                    r.pending_async_dependencies -= 1;
                }
                r.pending_async_dependencies == 0
            });
            if ready {
                let has_tla = parent.has_tla();
                exec_list.push(parent.clone());
                if !has_tla {
                    self.gather_available_ancestors(&parent, exec_list);
                }
            }
        }
    }

    /// §16.2.1.5.3.1 `AsyncModuleExecutionFulfilled`.
    pub fn async_module_execution_fulfilled(&mut self, module: &Gc<ModuleRecord>) -> JsResult<()> {
        if module.with(|r| r.status) == ModuleStatus::Evaluated {
            return Ok(());
        }
        module.with_mut(|r| r.async_evaluation = false);
        self.mark_module_evaluated(module);

        let mut exec_list: Vec<Gc<ModuleRecord>> = Vec::new();
        self.gather_available_ancestors(module, &mut exec_list);
        exec_list.sort_by_key(|m| m.with(|r| r.async_evaluation_order));

        for ready in exec_list {
            if ready.with(|r| r.status) == ModuleStatus::Evaluated {
                continue;
            }
            if ready.has_tla() {
                self.execute_async_module(&ready)?;
                continue;
            }
            match self.execute_module_body_only(&ready) {
                Ok(()) => {
                    ready.with_mut(|r| r.async_evaluation = false);
                    self.mark_module_evaluated(&ready);
                }
                Err(Signal::Throw(reason)) => {
                    self.async_module_execution_rejected(&ready, reason);
                }
                Err(other) => return Err(other),
            }
        }
        Ok(())
    }

    /// [`Interp::async_module_execution_rejected`], for the promise-reaction arm in
    /// `interp.rs` — the algorithm itself does not report failures, because the only thing
    /// it can do with one is reject a promise that is already rejecting.
    pub(crate) fn async_module_execution_rejected_public(
        &mut self,
        module: &Gc<ModuleRecord>,
        reason: Value,
    ) {
        self.async_module_execution_rejected(module, reason);
    }

    /// §16.2.1.5.3.1 `AsyncModuleExecutionRejected`.
    fn async_module_execution_rejected(&mut self, module: &Gc<ModuleRecord>, reason: Value) {
        if module.with(|r| r.status) == ModuleStatus::Evaluated {
            return;
        }
        module.with_mut(|r| {
            r.evaluation_error = Some(reason.clone());
            r.status = ModuleStatus::Evaluated;
            r.async_evaluation = false;
        });
        // Everyone waiting on it fails with the same reason, and one of them may be the
        // cycle root whose promise a caller is holding.
        let (promise, _, reject) = module
            .with(|r| r.top_level_capability.clone())
            .map_or((None, Value::Undefined, Value::Undefined), |(p, r, j)| {
                (Some(p), r, j)
            });
        if promise.is_some() {
            let _ = self.call_value(reject, Value::Undefined, vec![reason.clone()]);
        }
        let parents = module.with(|r| r.async_parent_modules.clone());
        for parent in parents {
            self.async_module_execution_rejected(&parent, reason.clone());
        }
    }

    /// Finish a module: `Evaluated`, and settle whoever is waiting on its promise.
    fn mark_module_evaluated(&mut self, module: &Gc<ModuleRecord>) {
        module.with_mut(|r| r.status = ModuleStatus::Evaluated);
        let Some((promise, resolve, _)) = module.with(|r| r.top_level_capability.clone()) else {
            return;
        };
        if self.promise_state(&promise).is_some_and(|state| {
            !matches!(state.borrow().status, crate::object::PromiseStatus::Pending)
        }) {
            return;
        }
        let _ = self.call_value(resolve, Value::Undefined, vec![Value::Undefined]);
    }

    /// Evaluate the asynchronous modules a deferred request drags in, and nothing else.
    fn evaluate_async_transitive_dependencies(
        &mut self,
        module: &Gc<ModuleRecord>,
    ) -> JsResult<()> {
        let mut seen = Vec::new();
        let mut list = Vec::new();
        self.gather_asynchronous_transitive_dependencies(module, &mut seen, &mut list);
        for dependency in list {
            let promise = self.evaluate_module(&dependency)?;
            self.await_module_promise(Value::Object(promise))?;
        }
        Ok(())
    }

    /// `GatherAsynchronousTransitiveDependencies` — the async modules a deferred request
    /// drags into evaluation order without evaluating itself.
    ///
    /// Walks the request graph and stops at the first `[[HasTLA]]` module on each path,
    /// because that module's own dependencies are already part of *its* evaluation. A
    /// module that is evaluating or done contributes nothing, and a synthetic (JSON/text/
    /// native) module has no requests to follow.
    fn gather_asynchronous_transitive_dependencies(
        &mut self,
        module: &Gc<ModuleRecord>,
        seen: &mut Vec<usize>,
        out: &mut Vec<Gc<ModuleRecord>>,
    ) {
        let identity = module.identity();
        if seen.contains(&identity) {
            return;
        }
        seen.push(identity);
        if !module.with(|r| r.kind == ModuleKind::JavaScript) {
            return;
        }
        // The import-defer proposal's own wording of this step: stop for `~evaluating~` or
        // for `IsModuleSCCEvaluated`. Both halves matter and neither is "my status is
        // evaluated":
        //
        //  * a parked module is walked *through*, because what is actually being waited on
        //    may be further down its graph (`middle → d → b → a-tla`, where `b` has already
        //    run but `a-tla` has not);
        //  * a module inside a cycle is finished only when its **root** is, so `b` is not
        //    "done" while `a-tla` is parked.
        if module.with(|r| r.status) == ModuleStatus::Evaluating || is_module_scc_evaluated(module)
        {
            return;
        }
        if module.has_tla() {
            if !out.iter().any(|m| m.ptr_eq(module)) {
                out.push(module.clone());
            }
            return;
        }
        let count = module.with(|r| r.meta.requests.len());
        let mut collected: Vec<Gc<ModuleRecord>> = Vec::new();
        for index in 0..count {
            let Some(required) = module.with(|r| r.dependencies.get(index).cloned().flatten())
            else {
                continue;
            };
            self.gather_asynchronous_transitive_dependencies(&required, seen, &mut collected);
        }
        for candidate in collected {
            if !out.iter().any(|m| m.ptr_eq(&candidate)) {
                out.push(candidate);
            }
        }
    }

    /// `ReadyForSyncExecution` — whether evaluating `module` right now cannot suspend.
    ///
    /// This engine runs a module body to completion inside [`Interp::evaluate_module_body`],
    /// draining the job queue for a top-level `await` as it goes, so there is never a module
    /// parked in `~evaluating-async~`: the only two answers here are "already done" and
    /// "on the stack right now". Everything else — a body with top-level await anywhere
    /// below it, or a cycle back into one that is running — means a deferred namespace
    /// cannot be read synchronously, which is the `TypeError` the proposal specifies.
    fn ready_for_sync_execution(
        &mut self,
        module: &Gc<ModuleRecord>,
        seen: &mut Vec<usize>,
    ) -> bool {
        let identity = module.identity();
        if seen.contains(&identity) {
            return true;
        }
        seen.push(identity);
        // Steps 5–6, in this order: the component question first, the module's own status
        // second. Both `~evaluating~` **and** `~evaluating-async~` answer false here, which
        // is what turns a namespace read into a `TypeError` instead of a body starting.
        if is_module_scc_evaluated(module) {
            return true;
        }
        match module.with(|r| r.status) {
            ModuleStatus::Evaluating | ModuleStatus::EvaluatingAsync => return false,
            _ => {}
        }
        if module.has_tla() {
            return false;
        }
        let count = module.with(|r| r.meta.requests.len());
        for index in 0..count {
            let Some(required) = module.with(|r| r.dependencies.get(index).cloned().flatten())
            else {
                continue;
            };
            if !self.ready_for_sync_execution(&required, seen) {
                return false;
            }
        }
        true
    }

    /// `EnsureDeferredNamespaceEvaluation` — the trigger behind every read of a deferred
    /// namespace.
    ///
    /// `None` for an ordinary namespace, which is what makes this cheap on the hot path: a
    /// namespace built by `import * as ns` has no module attached and answers immediately.
    pub(crate) fn trigger_deferred_namespace(&mut self, object: &Gc<JsObject>) -> JsResult<()> {
        let Some(module) = object.deferred_namespace_module() else {
            return Ok(());
        };
        // Only a module that has *not* finished can be evaluated here, and only such a
        // module can be unready: a module that threw is finished too, and re-reporting its
        // completion is what `evaluate_module_body` does.
        if module.with(|r| r.status) != ModuleStatus::Evaluated {
            let mut seen = Vec::new();
            if !self.ready_for_sync_execution(&module, &mut seen) {
                return Err(self.type_error(
                    "cannot read a deferred module namespace while its module is evaluating",
                ));
            }
        }
        match module.with(|r| r.status) {
            // Finished already, including "finished by throwing": the recorded completion is
            // the answer, and re-running the body would build a second, non-identical error.
            ModuleStatus::Evaluated => match module.with(|r| r.evaluation_error.clone()) {
                Some(error) => Err(Signal::Throw(error)),
                None => Ok(()),
            },
            // `ready_for_sync_execution` said nothing below it can suspend, so this really
            // does finish before the call returns — and it must not go through
            // `evaluate_module`, whose async bookkeeping parks a module reached through a
            // read (`async-cycle-dependency-of-deferred-module`).
            _ => self.evaluate_module_sync(&module),
        }
    }

    /// Drive a module's own promise to a settled state.
    ///
    /// `js_execute_sync_module` in the reference does the same thing and calls a pending
    /// promise an error ("promise is pending"); draining first is the difference, and it
    /// is correct here because nothing else can be waiting: this runs before the host has
    /// been given control, and the only queued jobs are the ones this body queued for
    /// itself.
    fn await_module_promise(&mut self, promise: Value) -> JsResult<Value> {
        let Value::Object(promise) = promise else {
            return Ok(Value::Undefined);
        };
        self.drain_jobs()?;
        let state = self.promise_state(&promise);
        let Some(state) = state else {
            return Ok(Value::Undefined);
        };
        let status = state.borrow().status.clone();
        match status {
            crate::object::PromiseStatus::Fulfilled(value) => Ok(value),
            crate::object::PromiseStatus::Rejected(reason) => Err(Signal::Throw(reason)),
            crate::object::PromiseStatus::Pending => Err(Signal::Throw(self.make_error(
                "TypeError",
                "promise is pending: top-level await never settled",
            ))),
        }
    }

    /// `import(specifier)`: load, link, evaluate — asynchronously.
    ///
    /// The work happens in a job, because §13.3.10.1 makes dynamic import settle through
    /// the promise machinery: `import("x").then(f)` must call `f` after the current
    /// script finishes, never inside the `import` expression.
    pub fn dynamic_import(
        &mut self,
        specifier: Value,
        options: Value,
        phase: ImportPhase,
    ) -> JsResult<Value> {
        let promise = self.new_promise();
        // §13.3.10.1 steps 5–7, in this order and with this error handling:
        //
        //     5. Let promiseCapability be ! NewPromiseCapability(%Promise%).
        //     6. Let specifierString be ToString(specifier).
        //     7. IfAbruptRejectPromise(specifierString, promiseCapability).
        //
        // Step 7 is the whole point of the ordering: a throwing `toString` — or a Symbol
        // specifier, which `ToString` rejects — must **reject the promise**, not throw out of
        // the `import` expression. Throwing here made `import(obj)` with a throwing
        // `toString` abort the whole script, so `.catch` could never run and test262's 40-odd
        // `specifier-tostring-abrupt-rejects` cases all failed.
        //
        // `GetValue` (step 4) is a plain `?` and genuinely throws synchronously; the compiler
        // has already evaluated the argument by the time this runs, so that distinction is
        // kept where it belongs.
        let specifier = match self.to_js_string(&specifier) {
            Ok(specifier) => specifier,
            Err(Signal::Throw(reason)) => {
                self.reject_promise(&promise, reason);
                return Ok(Value::Object(promise));
            }
            Err(other) => return Err(other),
        };
        // §13.3.10.1 steps 9–10: the import-attributes bag.
        //
        // This loader applies no attributes — `with: { type: 'json' }` parses and is then
        // ignored — but the *validation* is not optional, and neither are the observable
        // reads it performs. Every abrupt completion below rejects the promise rather than
        // throwing, and the order (options is an object, then `with`, then its keys, then
        // each value) is what the tests instrument:
        //
        //     `import(x, null)`            → TypeError rejection (step 10.a)
        //     `get with() { throw e }`     → rejection with `e` (step 10.c)
        //     `with: 'string'`            → TypeError rejection (step 10.d.i)
        //     `with: { type: 23 }`        → TypeError rejection (step 10.d.v.3)
        if let Some(rejection) = self.import_attribute_error(&options) {
            self.reject_promise(&promise, rejection);
            return Ok(Value::Object(promise));
        }
        // Resolved relative to whatever is running the import — the reference asks
        // `JS_GetScriptOrModuleName(ctx, 0)`, which is the innermost frame's file name and
        // does not care whether that frame came from a module or a plain script.
        //
        // Only consulting the module stack (as this did) made every `import('./x.js')` from
        // a *script* resolve against the working directory instead of the script's own
        // directory, so `await import('./module-code_FIXTURE.js')` in test262's
        // `dynamic-import` tests failed with "could not load module filename" for a file
        // sitting right next to the test.
        let referrer = self.import_referrer();
        self.jobs.push_back(crate::interp::Job::Import {
            specifier,
            referrer,
            promise: promise.clone(),
            phase,
        });
        Ok(Value::Object(promise))
    }

    /// Validate `import(x, options)`'s second argument, answering the reason to reject with.
    ///
    /// Returns `None` when the bag is acceptable — including when it is absent, which is the
    /// overwhelmingly common case and the only one this loader ever acts on.
    ///
    /// The reads are performed even though their results are discarded, because §13.3.10.1
    /// makes them observable: a `with` getter or a `Proxy` that logs is the entire content of
    /// the `2nd-param-*` tests. Nothing here throws; every failure becomes a rejection, which
    /// is `IfAbruptRejectPromise` spelled out.
    fn import_attribute_error(&mut self, options: &Value) -> Option<Value> {
        // Step 10: an absent bag is fine, and `undefined` is how "absent" arrives here —
        // `import(x)` compiles a literal `undefined` into the slot.
        if matches!(options, Value::Undefined) {
            return None;
        }
        // 10.a: any other non-object is a TypeError.
        let Value::Object(options) = options else {
            return Some(self.type_error_value("import options must be an object"));
        };
        let options = options.clone();
        // 10.b–c: `Get(options, "with")`.
        let with = match self.read_field(&Value::Object(options), "with") {
            Ok(with) => with,
            Err(Signal::Throw(reason)) => return Some(reason),
            Err(_) => return None,
        };
        if matches!(with, Value::Undefined) {
            return None;
        }
        // 10.d.i: `with` has to be an object too.
        let Value::Object(with_object) = &with else {
            return Some(self.type_error_value("import attributes must be an object"));
        };
        let with_object = with_object.clone();
        // 10.d.ii–iii: `EnumerableOwnPropertyNames`, which can throw from a `Proxy` trap —
        // so this goes through `[[OwnPropertyKeys]]` and asks enumerability per key rather
        // than reading the object's own table.
        let keys = match self.import_attribute_keys(&with) {
            Ok(keys) => keys,
            Err(Signal::Throw(reason)) => return Some(reason),
            Err(_) => return None,
        };
        // 10.d.v: each value is read (observably) and has to be a string.
        for key in keys {
            let value = match self.read_field(&Value::Object(with_object.clone()), &key) {
                Ok(value) => value,
                Err(Signal::Throw(reason)) => return Some(reason),
                Err(_) => continue,
            };
            if !matches!(value, Value::String(_)) {
                return Some(self.type_error_value("import attribute values must be strings"));
            }
        }
        None
    }

    /// A `TypeError` as a value, for the reject paths above.
    fn type_error_value(&mut self, message: &str) -> Value {
        self.make_error("TypeError", message)
    }

    /// `EnumerableOwnPropertyNames(value, key)` (§7.3.23), as a list of string keys.
    ///
    /// The key list is snapshotted first and enumerability is asked per key as the walk
    /// reaches it, which is the order the algorithm specifies and the one a `Proxy` can
    /// observe. Symbols are dropped: an import attribute name is a String.
    fn import_attribute_keys(&mut self, value: &Value) -> JsResult<Vec<String>> {
        let Some(object) = value.as_object().cloned() else {
            return Ok(Vec::new());
        };
        let mut out = Vec::new();
        for key in self.object_own_property_keys(&object)? {
            let Some(name) = key.as_wtf8() else {
                // A symbol key is not an import attribute name.
                continue;
            };
            let enumerable = self
                .object_get_own_property(&object, &key)?
                .is_some_and(|property| property.enumerable);
            if enumerable {
                out.push(name.to_string_lossy().into_owned());
            }
        }
        Ok(out)
    }

    /// The module name a dynamic import's specifier is resolved against.
    ///
    /// The innermost frame that has a *real file* name. `eval` and `std.evalScript` compile
    /// their bodies under pseudo-names (`<input>`, `<evalScript>`) because that is what a
    /// stack trace should say, and §19.2.1.1's `GetActiveScriptOrModule` makes an eval'd body
    /// belong to the script that called it — never to a file named `<input>`. Resolving
    /// `import('./x.js')` against `<input>` produced the specifier `x.js` with no directory,
    /// which the loader then looked for in the working directory.
    ///
    /// So frames are walked outermost-last until one names something path-like; a pseudo-name
    /// (`<…>`) is skipped for the same reason a `<builtin>` frame is not a referrer.
    fn import_referrer(&self) -> String {
        self.script_or_module_file_name()
            .or_else(|| self.module_stack.last().cloned())
            .or_else(|| self.main_module_name.clone())
            .unwrap_or_default()
    }

    /// Evaluate a pending dynamic import and settle its promise.
    pub fn run_dynamic_import(
        &mut self,
        specifier: &str,
        referrer: &str,
        promise: &Gc<JsObject>,
        phase: ImportPhase,
    ) {
        // Load and link. `import.defer` and `import.source` answer here; only the ordinary
        // phase goes on to evaluate, and that one cannot answer yet.
        let module = match self
            .load_module(specifier, &[], referrer)
            .and_then(|module| self.link_module(&module).map(|()| module))
        {
            Ok(module) => module,
            Err(Signal::Throw(reason)) => {
                self.reject_promise(promise, reason);
                return;
            }
            Err(_) => return,
        };
        // `import.defer(x)` resolves once the module is *loaded and linked*, and hands back
        // the namespace object without evaluating anything — that is the entire difference
        // from `import(x)`, and it is why the promise still rejects for a missing or
        // unparsable module.
        if phase == ImportPhase::Defer {
            // The async part of the graph still runs: `InnerModuleEvaluation` would gather a
            // deferred request's asynchronous transitive dependencies, and a dynamic import
            // has no importer to do it for it. So the module's own top-level-await
            // dependencies are evaluated here, and the promise resolves with an unevaluated
            // module either way.
            let outcome = self
                .evaluate_async_transitive_dependencies(&module)
                .and_then(|()| self.module_deferred_namespace(&module));
            match outcome {
                Ok(namespace) => self.fulfill_promise(promise, namespace),
                Err(Signal::Throw(reason)) => self.reject_promise(promise, reason),
                Err(_) => {}
            }
            return;
        }
        if phase == ImportPhase::Source {
            // §16.2.1.7.2 `GetModuleSource`: a Source Text Module Record — which is the only
            // kind this engine has — always answers with a `SyntaxError`, "a source phase
            // import is not available". The *load* still happens first, which is why a
            // missing file rejects with the loader's error instead: the promise settles one
            // step later than the resolution.
            let reason = self.make_error(
                "SyntaxError",
                "a source phase import is not available for this module",
            );
            self.reject_promise(promise, reason);
            return;
        }
        // §16.2.1.5.4 `FinishDynamicImport`: the import settles when the *module* does, not
        // when this call returns. Chaining onto the module's own `[[TopLevelCapability]]` is
        // what leaves an importer of a parked module pending — and what makes a second
        // `import()` of that module resolve no earlier than the first.
        let name = module.with(|r| r.name.clone());
        self.module_stack.push(name);
        let started = self.evaluate_module(&module);
        self.module_stack.pop();
        let capability = match started {
            Ok(capability) => capability,
            Err(Signal::Throw(reason)) => {
                self.reject_promise(promise, reason);
                return;
            }
            Err(_) => return,
        };
        let on_fulfilled = JsObject::function(
            self.heap,
            Some(self.realm.function_proto.clone()),
            Callable::ModuleNamespaceForImport {
                module: module.clone(),
                promise: promise.clone(),
            },
        );
        let on_rejected = JsObject::function(
            self.heap,
            Some(self.realm.function_proto.clone()),
            Callable::PromiseReject(promise.clone()),
        );
        let chained = self.perform_then(
            &capability,
            Some(Value::Object(on_fulfilled)),
            Some(Value::Object(on_rejected)),
        );
        if let Err(Signal::Throw(reason)) = chained {
            self.reject_promise(promise, reason);
        }
    }
}

/// The registry key for a module: its canonical name plus the attributes that decided
/// what it means.
///
/// Without the attributes, `import m from "./x.json"` and
/// `import m from "./x.json" with { type: "text" }` would collide on one record and the
/// second import would silently receive the first one's value.
fn cache_key(name: &str, attributes: &[(String, String)]) -> String {
    if attributes.is_empty() {
        return name.to_string();
    }
    let mut key = name.to_string();
    for (key_name, value) in attributes {
        key.push('\u{0}');
        key.push_str(key_name);
        key.push('=');
        key.push_str(value);
    }
    key
}

/// Which kind of module `name` and `attributes` describe.
///
/// A `type` attribute wins; the `.json` suffix only decides when no attribute was given.
/// That is what makes `import m from "./m.json" with { type: "text" }` a string while
/// `import m from "./m.json"` is an object.
fn module_kind(name: &str, attributes: &[(String, String)]) -> Result<ModuleKind, String> {
    let declared = attributes
        .iter()
        .find(|(key, _)| key == "type")
        .map(|(_, value)| value.as_str());
    let kind = match declared {
        // `json5` is accepted by the reference as an alias for a dialect that permits
        // comments and trailing commas; this parser is strict JSON, so a document that
        // needs the extension fails loudly rather than silently parsing differently.
        Some("json") | Some("json5") => ModuleKind::Json,
        Some("text") => ModuleKind::Text,
        Some("bytes") => ModuleKind::Bytes,
        // An unknown type is an error rather than a fallback to JavaScript: silently
        // evaluating `with { type: "cbor" }` as code would run a data file.
        Some(other) => return Err(format!("unsupported module type: '{other}'")),
        None => {
            if name.ends_with(".json") {
                ModuleKind::Json
            } else {
                ModuleKind::JavaScript
            }
        }
    };
    Ok(kind)
}