rusty_racer 0.2.8 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,7 +31,7 @@
31
31
  // OUTERMOST op cancels a stale terminate so it can't poison the next op, while a
32
32
  // nested op's cancel never erases a termination aimed at the suspended outer JS.
33
33
  //
34
- // Attached procs and the dynamic-import resolver are kept alive by the ISOLATE'S
34
+ // Attached procs and the dynamic-import handler are kept alive by the ISOLATE'S
35
35
  // OWN ROOTS ARRAY (Core.roots), which every wrapper marks — never by a GC root.
36
36
  // A root would be a leak: a host fn closes over its embedder's world, and that
37
37
  // world reaches back to this isolate's wrappers, so rooting the proc roots the
@@ -72,7 +72,9 @@ use magnus::{
72
72
  mod marshal;
73
73
  use marshal::{JsVal, js_to_jsval, jsval_to_js, jsval_to_ruby, ruby_to_jsval};
74
74
  mod ops;
75
- use ops::{Compiled, Completion, Request, VmReply, run_source, service_request};
75
+ use ops::{
76
+ Compiled, Completion, Request, Settle, SyntheticExport, VmReply, run_source, service_request,
77
+ };
76
78
  mod stack;
77
79
  use stack::{STACK_DEBUG, StackScope, current_real_isolate, discover_scan_start_field};
78
80
  mod watchdog;
@@ -85,16 +87,16 @@ use watchdog::{
85
87
  // and PINS it (GC.compact must not move it: the copies living in Rust are
86
88
  // invisible to the compactor and would go stale).
87
89
  //
88
- // Only for a proc the isolate holds TRANSIENTLY — today just the instantiate
89
- // resolver, parked in the slot for the length of one InstantiateModule op and
90
- // restored after it. Anything held for the isolate's LIFE goes in the roots
90
+ // Only for a proc the isolate holds TRANSIENTLY — today just the resolve block
91
+ // of Module#instantiate or DynamicImport#resolve, parked in the slot for the
92
+ // length of one InstantiateModule / SettleImport op and restored after it. Anything held for the isolate's LIFE goes in the roots
91
93
  // array instead (see the module header): a lasting root is a lasting leak.
92
94
  //
93
95
  // SAFETY of the manual Send: the !Send contents (and BoxValue's drop, which
94
96
  // calls rb_gc_unregister_address) only run under the GVL. Two conventions
95
97
  // keep that true — breaking either is silent UB, so don't:
96
- // - Arc<Core> lives ONLY in the five TypedData wrappers (Isolate, Context,
97
- // Module, Script, Function). Never clone it into the V8/watchdog threads, or the
98
+ // - Arc<Core> lives ONLY in the six TypedData wrappers (Isolate, Context,
99
+ // Module, Script, Function, DynamicImport). Never clone it into the V8/watchdog threads, or the
98
100
  // last drop could run off a Ruby thread.
99
101
  // - the wrappers must not set free_immediately: their dfree (and so Core's
100
102
  // drop) has to run outside the GC sweep, where Ruby APIs are forbidden.
@@ -259,13 +261,33 @@ impl ProcTable {
259
261
  // long as a wrapper of it is reachable, in one place the GC can be shown without
260
262
  // taking any Rust lock (a mark that had to lock `procs` could deadlock against
261
263
  // the thread whose allocation triggered the GC while holding it). Slot 0 is the
262
- // dynamic-import resolver; the attached host fns follow, one per proc slot.
263
- const ROOT_IMPORT_RESOLVER: isize = 0;
264
+ // dynamic-import handler; the attached host fns follow, one per proc slot.
265
+ const ROOT_IMPORT_HANDLER: isize = 0;
264
266
  const ROOT_FIRST_PROC: isize = 1;
265
267
  fn proc_root_index(index: usize) -> isize {
266
268
  ROOT_FIRST_PROC + index as isize
267
269
  }
268
270
 
271
+ // Import attributes as a frozen Ruby Hash (String => String), in source order —
272
+ // none, the one frozen empty Hash (NO_ATTRIBUTES): what almost every request
273
+ // has, handed to a resolve block per import edge, made once.
274
+ fn attributes_hash(ruby: &Ruby, attributes: &[(String, String)]) -> Result<RHash, Error> {
275
+ if attributes.is_empty() {
276
+ return Ok(ruby.get_inner(&NO_ATTRIBUTES));
277
+ }
278
+ let hash = ruby.hash_new();
279
+ for (key, value) in attributes {
280
+ hash.aset(key.as_str(), value.as_str())?;
281
+ }
282
+ hash.freeze();
283
+ Ok(hash)
284
+ }
285
+ static NO_ATTRIBUTES: magnus::value::Lazy<RHash> = magnus::value::Lazy::new(|ruby| {
286
+ let hash = ruby.hash_new();
287
+ hash.freeze();
288
+ hash
289
+ });
290
+
269
291
  // Look up a RustyRacer::<name> exception class at raise time. The classes are
270
292
  // defined in lib/rusty_racer.rb (loaded after this extension), so they exist
271
293
  // by the time any eval can raise. Falls back to Ruby's RuntimeError.
@@ -712,7 +734,12 @@ fn reject_with_error(
712
734
 
713
735
  // A ScriptOrigin naming the script |filename|, so stack traces and parse-error
714
736
  // locations report a meaningful resource name instead of being anonymous.
715
- fn script_origin<'s>(scope: &v8::PinScope<'s, '_>, filename: &str) -> v8::ScriptOrigin<'s> {
737
+ // |host_defined| its host-defined options (`host_defined_options`).
738
+ fn script_origin<'s>(
739
+ scope: &v8::PinScope<'s, '_>,
740
+ filename: &str,
741
+ host_defined: Option<v8::Local<'s, v8::Data>>,
742
+ ) -> v8::ScriptOrigin<'s> {
716
743
  let name = v8::String::new(scope, filename).unwrap_or_else(|| v8::String::empty(scope));
717
744
  v8::ScriptOrigin::new(
718
745
  scope,
@@ -725,7 +752,7 @@ fn script_origin<'s>(scope: &v8::PinScope<'s, '_>, filename: &str) -> v8::Script
725
752
  false,
726
753
  false,
727
754
  /*is_module*/ false,
728
- None,
755
+ host_defined,
729
756
  )
730
757
  }
731
758
 
@@ -874,7 +901,11 @@ fn take_thrown<'s>(
874
901
  // owning the url->Module registry and the resolve policy (ModuleReg is only the
875
902
  // binding's id and url bookkeeping).
876
903
  // ---------------------------------------------------------------------------
877
- fn module_origin<'s>(scope: &v8::PinScope<'s, '_>, url: &str) -> v8::ScriptOrigin<'s> {
904
+ fn module_origin<'s>(
905
+ scope: &v8::PinScope<'s, '_>,
906
+ url: &str,
907
+ host_defined: Option<v8::Local<'s, v8::Data>>,
908
+ ) -> v8::ScriptOrigin<'s> {
878
909
  let name = v8::String::new(scope, url).unwrap();
879
910
  v8::ScriptOrigin::new(
880
911
  scope,
@@ -887,10 +918,30 @@ fn module_origin<'s>(scope: &v8::PinScope<'s, '_>, url: &str) -> v8::ScriptOrigi
887
918
  false,
888
919
  false,
889
920
  /*is_module*/ true,
890
- None,
921
+ host_defined,
891
922
  )
892
923
  }
893
924
 
925
+ // File a module V8 made (compiled, or synthetic) under a new id of the realm
926
+ // |context_id|'s — what a Module wrapper addresses — and index its |origin| by
927
+ // its identity (ModuleReg.urls).
928
+ pub(crate) fn register_module(
929
+ scope: &mut v8::PinScope<'_, '_>,
930
+ module: v8::Local<v8::Module>,
931
+ context_id: i32,
932
+ origin: ModuleOrigin,
933
+ ) -> i32 {
934
+ let hash = module.get_identity_hash().get();
935
+ let g = v8::Global::new(scope, module);
936
+ let weak = v8::Weak::new(scope, module);
937
+ let m = &mut istate!(scope).modules;
938
+ let id = m.next_id;
939
+ m.next_id += 1;
940
+ m.by_id.insert(id, (g, context_id));
941
+ m.add_url(hash, weak, origin);
942
+ id
943
+ }
944
+
894
945
  // Registry for the thin compile_module/instantiate API.
895
946
  #[derive(Default)]
896
947
  struct ModuleReg {
@@ -899,13 +950,14 @@ struct ModuleReg {
899
950
  // was compiled in. Strong, and gone once the wrapper is disposed or collected
900
951
  // (Core.released).
901
952
  by_id: HashMap<i32, (v8::Global<v8::Module>, i32)>,
902
- // identity hash -> (module, url): a Local<Module> V8 hands a callback
903
- // (import.meta, a referrer being linked) back to the url it was compiled
904
- // with. WEAK, so a module V8 still keeps — a dependency linked into a live
905
- // graph, a function of a disposed realm's module another realm holds —
906
- // answers whether its wrapper (or its realm) is still around or not, and
907
- // one V8 collected is pruned instead of pinned (`add_url`).
908
- urls: HashMap<i32, Vec<(v8::Weak<v8::Module>, String)>>,
953
+ // identity hash -> (module, what it was compiled with): a Local<Module> V8
954
+ // hands a callback (import.meta, a referrer being linked) back to the url
955
+ // it was compiled with, and the host-defined value it was given. WEAK, so a
956
+ // module V8 still keeps — a dependency linked into a live graph, a function
957
+ // of a disposed realm's module another realm holds — answers whether its
958
+ // wrapper (or its realm) is still around or not, and one V8 collected is
959
+ // pruned instead of pinned (`add_url`).
960
+ urls: HashMap<i32, Vec<(v8::Weak<v8::Module>, ModuleOrigin)>>,
909
961
  // `add_url`'s amortization: entries added since the last prune, and the
910
962
  // entries that prune left.
911
963
  added_since_prune: usize,
@@ -918,7 +970,7 @@ impl ModuleReg {
918
970
  // as many have been added since the last prune as it left — a scan
919
971
  // amortized O(1) per compile, keeping the index within about twice the
920
972
  // modules alive.
921
- fn add_url(&mut self, hash: i32, module: v8::Weak<v8::Module>, url: String) {
973
+ fn add_url(&mut self, hash: i32, module: v8::Weak<v8::Module>, origin: ModuleOrigin) {
922
974
  if self.added_since_prune > self.kept_at_prune {
923
975
  self.urls.retain(|_, bucket| {
924
976
  bucket.retain(|(module, _)| !module.is_empty());
@@ -928,10 +980,20 @@ impl ModuleReg {
928
980
  self.added_since_prune = 0;
929
981
  }
930
982
  self.added_since_prune += 1;
931
- self.urls.entry(hash).or_default().push((module, url));
983
+ self.urls.entry(hash).or_default().push((module, origin));
932
984
  }
933
985
  }
934
986
 
987
+ // What a module was compiled with, as a callback about it hands it on: its url
988
+ // (the filename), and the host-defined value (`host_defined:`) its ScriptOrigin
989
+ // carries, a primitive — V8 itself hands that to the dynamic-import hook of an
990
+ // import() the module makes, but to no hook about the module itself.
991
+ #[derive(Clone)]
992
+ pub(crate) struct ModuleOrigin {
993
+ pub(crate) url: String,
994
+ pub(crate) host_defined: Option<v8::Global<v8::Value>>,
995
+ }
996
+
935
997
  // Classic compiled scripts: id -> (unbound script, owning context id). An
936
998
  // UnboundScript is context-independent, but we run it in the context it was
937
999
  // compiled in (and reset/dispose of that context drops it).
@@ -955,6 +1017,60 @@ struct ScriptReg {
955
1017
  // realm it was resolved in, so it holds that other realm's function until this
956
1018
  // one is reset or the handle is released — as any reference this realm keeps
957
1019
  // to it would.
1020
+ // The import() promises waiting for their host (DynamicImport): id -> the
1021
+ // promise's resolver and the realm the import() fired in, whose module it is
1022
+ // to settle with. An entry leaves as its import is settled, as its realm is
1023
+ // reset or disposed (no script of it is left to see the promise), or as its
1024
+ // DynamicImport wrapper is let go of unsettled (nothing can settle it any more:
1025
+ // the promise stays pending, as a fetch no one answers does). Ids are never
1026
+ // reused, so a stale id can only miss.
1027
+ #[derive(Default)]
1028
+ struct ImportReg {
1029
+ by_id: HashMap<u64, (v8::Global<v8::PromiseResolver>, i32)>,
1030
+ next_id: u64,
1031
+ }
1032
+
1033
+ // A synthetic module's default export, until its evaluation steps set it
1034
+ // (synthetic_evaluation_steps): by the module's identity hash, the module
1035
+ // (weak: one never evaluated, then collected, is pruned) and the value, and the
1036
+ // realm both belong to.
1037
+ type KeptExport = (v8::Weak<v8::Module>, v8::Global<v8::Value>, i32);
1038
+ #[derive(Default)]
1039
+ pub(crate) struct SyntheticExports {
1040
+ pub(crate) by_hash: HashMap<i32, Vec<KeptExport>>,
1041
+ // `add`'s amortization, as ModuleReg::add_url's: entries added since the last
1042
+ // prune, and the entries that prune left.
1043
+ added_since_prune: usize,
1044
+ kept_at_prune: usize,
1045
+ }
1046
+
1047
+ impl SyntheticExports {
1048
+ // Keep |value| for |module| of realm |cid|, first letting go of the values of
1049
+ // modules collected unevaluated once as many were added since the last prune
1050
+ // as it left.
1051
+ pub(crate) fn add(
1052
+ &mut self,
1053
+ hash: i32,
1054
+ module: v8::Weak<v8::Module>,
1055
+ value: v8::Global<v8::Value>,
1056
+ cid: i32,
1057
+ ) {
1058
+ if self.added_since_prune > self.kept_at_prune {
1059
+ self.by_hash.retain(|_, exports| {
1060
+ exports.retain(|(module, _, _)| !module.is_empty());
1061
+ !exports.is_empty()
1062
+ });
1063
+ self.kept_at_prune = self.by_hash.values().map(Vec::len).sum();
1064
+ self.added_since_prune = 0;
1065
+ }
1066
+ self.added_since_prune += 1;
1067
+ self.by_hash
1068
+ .entry(hash)
1069
+ .or_default()
1070
+ .push((module, value, cid));
1071
+ }
1072
+ }
1073
+
958
1074
  #[derive(Default)]
959
1075
  struct FunctionReg {
960
1076
  by_id: HashMap<u64, FunctionEntry>,
@@ -972,6 +1088,7 @@ enum Released {
972
1088
  Function(u64),
973
1089
  Module(i32),
974
1090
  Script(i32),
1091
+ Import(u64),
975
1092
  }
976
1093
 
977
1094
  // The V8 thread's realm registry: the main context (id 0, swappable by reset),
@@ -1062,14 +1179,20 @@ struct IsolateState {
1062
1179
  modules: ModuleReg,
1063
1180
  scripts: ScriptReg,
1064
1181
  functions: FunctionReg,
1182
+ imports: ImportReg,
1183
+ synthetic: SyntheticExports,
1065
1184
  active_realms: Vec<i32>,
1066
1185
  instantiating: bool,
1186
+ // Set while a dynamic import's module is linked (finish_dynamic_import), so
1187
+ // resolve_imported turns a raising block into the import's rejection rather
1188
+ // than stashing it for a Ruby frame to re-raise.
1189
+ settling_import: bool,
1067
1190
  watchdog_fired: bool,
1068
1191
  auto_microtasks: bool,
1069
1192
  draining: bool,
1070
1193
  // Back-pointer to the owning Core, so a V8 callback (host fn / module
1071
1194
  // resolver) — which holds only a scope — can reach Core.procs and
1072
- // Core.dynamic_import_resolver. Set once, after the Arc<Core> is built;
1195
+ // Core.dynamic_import_handler. Set once, after the Arc<Core> is built;
1073
1196
  // valid for the whole isolate life (Core outlives the slot — the slot is
1074
1197
  // dropped during isolate disposal, which a live wrapper triggers). Null
1075
1198
  // only in the brief window before it is wired up.
@@ -1116,8 +1239,11 @@ impl IsolateState {
1116
1239
  modules: ModuleReg::default(),
1117
1240
  scripts: ScriptReg::default(),
1118
1241
  functions: FunctionReg::default(),
1242
+ imports: ImportReg::default(),
1243
+ synthetic: SyntheticExports::default(),
1119
1244
  active_realms: Vec::new(),
1120
1245
  instantiating: false,
1246
+ settling_import: false,
1121
1247
  watchdog_fired: false,
1122
1248
  auto_microtasks,
1123
1249
  draining: false,
@@ -1287,6 +1413,12 @@ fn drop_context_artifacts(state: &mut IsolateState, context_id: i32) {
1287
1413
  .functions
1288
1414
  .by_id
1289
1415
  .retain(|_, entry| entry.context_id != context_id);
1416
+ // Its import() promises are no script's to see any more.
1417
+ state.imports.by_id.retain(|_, (_, cid)| *cid != context_id);
1418
+ state.synthetic.by_hash.retain(|_, exports| {
1419
+ exports.retain(|(_, _, cid)| *cid != context_id);
1420
+ !exports.is_empty()
1421
+ });
1290
1422
  // A promise-reject recorder created in this context is unusable now.
1291
1423
  if state
1292
1424
  .realms
@@ -1310,11 +1442,14 @@ fn script_handle(
1310
1442
  .map(|(g, cid)| (g.clone(), *cid))
1311
1443
  }
1312
1444
 
1313
- // A compiled module's url (the filename it was compiled with), by identity in
1314
- // the weak url index (ModuleReg.urls) — for as long as V8 keeps the module. Used
1315
- // to give a referrer its url for the resolve round-trip and to fill
1316
- // import.meta.url.
1317
- fn module_url(scope: &mut v8::PinScope<'_, '_>, module: v8::Local<v8::Module>) -> Option<String> {
1445
+ // What a compiled module was compiled with (its url — the filename — and its
1446
+ // host-defined value), by identity in the weak url index (ModuleReg.urls) — for
1447
+ // as long as V8 keeps the module. Used to give a referrer its url for the
1448
+ // resolve round-trip and to fill import.meta.
1449
+ fn origin_of_module(
1450
+ scope: &mut v8::PinScope<'_, '_>,
1451
+ module: v8::Local<v8::Module>,
1452
+ ) -> Option<ModuleOrigin> {
1318
1453
  let hash = module.get_identity_hash().get();
1319
1454
  // A shared borrow of the slot beside the shared one to_local takes.
1320
1455
  scope
@@ -1324,42 +1459,113 @@ fn module_url(scope: &mut v8::PinScope<'_, '_>, module: v8::Local<v8::Module>) -
1324
1459
  .get(&hash)?
1325
1460
  .iter()
1326
1461
  .find(|(weak, _)| weak.to_local(scope) == Some(module))
1327
- .map(|(_, url)| url.clone())
1462
+ .map(|(_, origin)| origin.clone())
1463
+ }
1464
+
1465
+ fn module_url(scope: &mut v8::PinScope<'_, '_>, module: v8::Local<v8::Module>) -> Option<String> {
1466
+ origin_of_module(scope, module).map(|origin| origin.url)
1467
+ }
1468
+
1469
+ // The host-defined options a ScriptOrigin carries for `host_defined:` — a
1470
+ // PrimitiveArray holding the value alone — or None for none. A value that is
1471
+ // no primitive is refused before it gets here (`host_defined_arg`).
1472
+ pub(crate) fn host_defined_options<'s>(
1473
+ scope: &mut v8::PinScope<'s, '_>,
1474
+ value: Option<&JsVal>,
1475
+ ) -> Option<v8::Local<'s, v8::Data>> {
1476
+ let value = marshal::jsval_to_js(scope, value?.clone());
1477
+ let primitive = v8::Local::<v8::Primitive>::try_from(value).ok()?;
1478
+ let options = v8::PrimitiveArray::new(scope, 1);
1479
+ options.set(scope, 0, primitive);
1480
+ Some(options.into())
1481
+ }
1482
+
1483
+ // …and back: the value the host-defined options V8 hands a hook hold — their
1484
+ // first element, as any embedder that sets a PrimitiveArray of its own
1485
+ // (rather than through `host_defined:`) puts it there — or None.
1486
+ fn host_defined_value<'s>(
1487
+ scope: &mut v8::PinScope<'s, '_>,
1488
+ options: v8::Local<'s, v8::Data>,
1489
+ ) -> Option<v8::Local<'s, v8::Value>> {
1490
+ let options = v8::Local::<v8::FixedArray>::try_from(options).ok()?;
1491
+ let first = options.get(scope, 0)?;
1492
+ v8::Local::<v8::Value>::try_from(first).ok()
1493
+ }
1494
+
1495
+ // The import attributes V8 hands a hook, as (key, value) pairs: `stride` 3 for
1496
+ // a module request's (key, value, source offset), 2 for a dynamic import's.
1497
+ fn import_attributes_of(
1498
+ scope: &mut v8::PinScope<'_, '_>,
1499
+ attributes: v8::Local<v8::FixedArray>,
1500
+ stride: usize,
1501
+ ) -> Vec<(String, String)> {
1502
+ let mut pairs = Vec::with_capacity(attributes.length() / stride);
1503
+ for at in (0..attributes.length()).step_by(stride) {
1504
+ let text = |scope: &mut v8::PinScope<'_, '_>, i: usize| {
1505
+ attributes
1506
+ .get(scope, i)
1507
+ .and_then(|d| v8::Local::<v8::Value>::try_from(d).ok())
1508
+ .map(|v| v.to_rust_string_lossy(scope))
1509
+ };
1510
+ if let (Some(key), Some(value)) = (text(scope, at), text(scope, at + 1)) {
1511
+ pairs.push((key, value));
1512
+ }
1513
+ }
1514
+ pairs
1328
1515
  }
1329
1516
 
1330
1517
  // V8 calls this the first time a module reads import.meta. Fills in
1331
- // import.meta.url with the module's compile-time url (filename); other
1332
- // properties are left to the module system / embedder.
1518
+ // import.meta.url with the module's compile-time url (filename), then hands the
1519
+ // object to its realm's import-meta handler (NS.setImportMetaHandler), if it has
1520
+ // one, as `handler(meta, url, hostDefined)` — HTML's
1521
+ // HostGetImportMetaProperties, whose `resolve` only the host can make. What the
1522
+ // handler throws is dropped: there is no script of the page's to throw it at.
1333
1523
  unsafe extern "C" fn import_meta_cb(
1334
1524
  context: v8::Local<v8::Context>,
1335
1525
  module: v8::Local<v8::Module>,
1336
1526
  meta: v8::Local<v8::Object>,
1337
1527
  ) {
1338
1528
  v8::callback_scope!(unsafe scope, context);
1339
- let Some(url) = module_url(scope, module) else {
1529
+ let Some(origin) = origin_of_module(scope, module) else {
1340
1530
  return;
1341
1531
  };
1342
- if let (Some(key), Some(val)) = (v8::String::new(scope, "url"), v8::String::new(scope, &url)) {
1343
- meta.create_data_property(scope, key.into(), val.into());
1344
- }
1532
+ let Some(url) = v8::String::new(scope, &origin.url) else {
1533
+ return;
1534
+ };
1535
+ if let Some(key) = v8::String::new(scope, "url") {
1536
+ meta.create_data_property(scope, key.into(), url.into());
1537
+ }
1538
+ let global = context.global(scope);
1539
+ let key = import_meta_key(scope);
1540
+ let Some(handler) = global
1541
+ .get_private(scope, key)
1542
+ .and_then(|h| v8::Local::<v8::Function>::try_from(h).ok())
1543
+ else {
1544
+ return;
1545
+ };
1546
+ let host_defined: v8::Local<v8::Value> = match origin.host_defined {
1547
+ Some(value) => v8::Local::new(scope, value),
1548
+ None => v8::undefined(scope).into(),
1549
+ };
1550
+ v8::tc_scope!(let tc, scope);
1551
+ let receiver = v8::undefined(tc).into();
1552
+ handler.call(tc, receiver, &[meta.into(), url.into(), host_defined]);
1345
1553
  }
1346
1554
 
1347
- // V8 calls this per import edge during InstantiateModule (and while
1348
- // finish_dynamic_import links a dynamically-imported module). Maps the referrer
1349
- // to its url and calls the Ruby resolver INLINE (reacquiring the GVL): the
1350
- // static instantiate block parked in the slot for this op, or — when none is
1351
- // parked (a dynamic import's auto-link) — the Context's dynamic_import_resolver.
1555
+ // V8 calls this per import edge during InstantiateModule (and while a dynamic
1556
+ // import is settled with a module to link — DynamicImport#resolve). Maps the
1557
+ // referrer to its url and calls the Ruby resolve block parked in the slot for
1558
+ // the op INLINE (reacquiring the GVL), with the request's import attributes.
1352
1559
  fn resolve_imported<'s>(
1353
1560
  context: v8::Local<'s, v8::Context>,
1354
1561
  specifier: v8::Local<'s, v8::String>,
1355
- _import_attributes: v8::Local<'s, v8::FixedArray>,
1562
+ import_attributes: v8::Local<'s, v8::FixedArray>,
1356
1563
  referrer: v8::Local<'s, v8::Module>,
1357
1564
  ) -> Option<v8::Local<'s, v8::Module>> {
1358
1565
  v8::callback_scope!(unsafe scope, context);
1359
1566
  let spec = specifier.to_rust_string_lossy(scope);
1360
1567
  let ref_url = module_url(scope, referrer)?;
1361
- // The realm being linked (this callback's own context). Computed up front so
1362
- // it both rides along to the dynamic_import_resolver AND backs the
1568
+ // The realm being linked (this callback's own context), for the
1363
1569
  // foreign-context check below; for a real module context it is always Some.
1364
1570
  let here = id_of_context(scope, context);
1365
1571
  let core_ptr = istate!(scope).core_ptr;
@@ -1367,51 +1573,45 @@ fn resolve_imported<'s>(
1367
1573
  return None;
1368
1574
  }
1369
1575
  let core = unsafe { &*core_ptr };
1370
- // The static instantiate block parked for THIS op (Some) vs a dynamic
1371
- // import's auto-link (None -> dynamic_import_resolver, with the initiating
1372
- // realm so it can resolve per-realm).
1373
- let instantiate = istate!(scope).instantiate_resolve.as_ref().map(|r| r.get());
1374
- let mut dynamic_err = None;
1375
- let dep_id = match instantiate {
1376
- Some(resolve) => {
1377
- // The error conversion happens INSIDE with_gvl: error_to_exception
1378
- // calls into Ruby (so it can allocate, so it can GC) and BoxValue::new
1379
- // registers a GC root — neither is safe with the GVL released.
1380
- match with_gvl(core, RubyCall::Resolver(&spec), || {
1381
- resolve_module_via_ruby(core, resolve, &spec, &ref_url, None)
1382
- .map_err(|e| error_to_exception(&e).map(BoxValue::new))
1383
- }) {
1384
- Ok(id) => id,
1385
- // Stash the resolver's own raised exception (GC-rooted) so the
1386
- // InstantiateModule op can re-raise it with its original class
1387
- // instead of a generic "failed to link".
1388
- Err(exc) => {
1389
- istate!(scope).instantiate_resolve_err = exc;
1390
- None
1391
- }
1576
+ let attributes = import_attributes_of(scope, import_attributes, 3);
1577
+ let resolve = istate!(scope).instantiate_resolve.as_ref().map(|r| r.get());
1578
+ // Linking for a dynamic import (DynamicImport#resolve) has no Ruby frame to
1579
+ // re-raise a raising block into — the failure becomes the import()'s
1580
+ // rejection — so the block's own message travels out as the JS error.
1581
+ let settling = istate!(scope).settling_import;
1582
+ let mut failure = None;
1583
+ let dep_id = match resolve {
1584
+ Some(resolve) if settling => match with_gvl(core, RubyCall::Resolver(&spec), || {
1585
+ // Rendering the message reads the Ruby exception, so it stays
1586
+ // inside with_gvl.
1587
+ resolve_module_via_ruby(core, resolve, &spec, &ref_url, &attributes)
1588
+ .map_err(|e| e.to_string())
1589
+ }) {
1590
+ Ok(id) => id,
1591
+ Err(why) => {
1592
+ failure = Some(why);
1593
+ None
1392
1594
  }
1393
- }
1394
- None => {
1395
- match core.dynamic_import_resolver() {
1396
- Some(p) => match with_gvl(core, RubyCall::Resolver(&spec), || {
1397
- resolve_module_via_ruby(core, p, &spec, &ref_url, Some(here.unwrap_or(0)))
1398
- // Rendering the message reads the Ruby exception, so it too
1399
- // stays inside with_gvl.
1400
- .map_err(|e| e.to_string())
1401
- }) {
1402
- Ok(id) => id,
1403
- // Unlike the static branch there is no Ruby frame waiting to
1404
- // re-raise into — this failure becomes the import()'s promise
1405
- // rejection — so the resolver's own message has to travel out
1406
- // as the JS error or it is lost.
1407
- Err(why) => {
1408
- dynamic_err = Some(why);
1409
- None
1410
- }
1411
- },
1412
- None => None,
1595
+ },
1596
+ // The error conversion happens INSIDE with_gvl: error_to_exception
1597
+ // calls into Ruby (so it can allocate, so it can GC) and BoxValue::new
1598
+ // registers a GC root — neither is safe with the GVL released.
1599
+ Some(resolve) => match with_gvl(core, RubyCall::Resolver(&spec), || {
1600
+ resolve_module_via_ruby(core, resolve, &spec, &ref_url, &attributes)
1601
+ .map_err(|e| error_to_exception(&e).map(BoxValue::new))
1602
+ }) {
1603
+ Ok(id) => id,
1604
+ // Stash the resolver's own raised exception (GC-rooted) so the
1605
+ // InstantiateModule op can re-raise it with its original class
1606
+ // instead of a generic "failed to link".
1607
+ Err(exc) => {
1608
+ istate!(scope).instantiate_resolve_err = exc;
1609
+ None
1413
1610
  }
1414
- }
1611
+ },
1612
+ // No block: a module handed to DynamicImport#resolve unlinked, with
1613
+ // nothing to link its imports by.
1614
+ None => None,
1415
1615
  };
1416
1616
  // From here on, every exit that isn't a module throws first. V8 has no
1417
1617
  // channel for "why" — it just sees an empty return, installs no error of its
@@ -1420,9 +1620,8 @@ fn resolve_imported<'s>(
1420
1620
  // where it came from, which is the single most common module wiring mistake.
1421
1621
  // (The two bails above stay silent: both are broken internal state, not
1422
1622
  // anything the caller did.) The one path that must also stay silent is a
1423
- // STATIC resolver that raised — its own Ruby exception is already stashed
1424
- // for instantiate_module to re-raise, and ours would mask it. The dynamic
1425
- // branch has no such frame, so it carries its message in dynamic_err.
1623
+ // block that raised for Module#instantiate — its own Ruby exception is
1624
+ // already stashed for instantiate_module to re-raise, and ours would mask it.
1426
1625
  let raised = istate!(scope).instantiate_resolve_err.is_some();
1427
1626
  let fail = |scope: &mut v8::PinScope<'_, '_>, message: String| {
1428
1627
  if !raised {
@@ -1432,7 +1631,7 @@ fn resolve_imported<'s>(
1432
1631
  };
1433
1632
  let import = format!("{spec:?} imported from {ref_url}");
1434
1633
  let Some(dep_id) = dep_id else {
1435
- return match dynamic_err {
1634
+ return match failure {
1436
1635
  Some(why) => fail(scope, format!("{why} (resolving {import})")),
1437
1636
  None => fail(
1438
1637
  scope,
@@ -1440,10 +1639,8 @@ fn resolve_imported<'s>(
1440
1639
  ),
1441
1640
  };
1442
1641
  };
1443
- // The dep must live in the context actually being linked — the auto-link of
1444
- // a dynamic import runs in whatever realm import() fired in, which kAuto can
1445
- // detach from the request that started it. A foreign-context module would
1446
- // V8-CHECK-abort.
1642
+ // The dep must live in the context actually being linked; a foreign-context
1643
+ // module would V8-CHECK-abort.
1447
1644
  let found = istate!(scope)
1448
1645
  .modules
1449
1646
  .by_id
@@ -1474,72 +1671,134 @@ fn resolve_imported<'s>(
1474
1671
  Some(v8::Local::new(scope, &g))
1475
1672
  }
1476
1673
 
1477
- // V8 calls this for a JS `import(specifier)`. Returns a Promise fulfilled with
1478
- // the resolved module's namespace (or rejected). Calls the Context's
1479
- // dynamic_import_resolver INLINE (reacquiring the GVL). The resolver may return
1480
- // a merely COMPILED module: per V8's host contract, link + evaluate happen here
1481
- // (finish_dynamic_import).
1674
+ // V8 calls this for a JS `import(specifier, options)`. Returns a promise the
1675
+ // HOST settles — now or on a later task — through the RustyRacer::DynamicImport
1676
+ // handed to the Isolate's dynamic_import_handler (called INLINE, reacquiring the
1677
+ // GVL): with a module (DynamicImport#resolve), which per V8's host contract is
1678
+ // linked and evaluated here (finish_dynamic_import), or with a rejection value.
1679
+ // The promise waits in ImportReg until then; a handler that raises rejects it
1680
+ // with its message, unless it settled it first.
1482
1681
  fn dynamic_import_cb<'s>(
1483
1682
  scope: &mut v8::PinScope<'s, '_>,
1484
- _host_defined_options: v8::Local<'s, v8::Data>,
1683
+ host_defined_options: v8::Local<'s, v8::Data>,
1485
1684
  resource_name: v8::Local<'s, v8::Value>,
1486
1685
  specifier: v8::Local<'s, v8::String>,
1487
- _import_attributes: v8::Local<'s, v8::FixedArray>,
1686
+ import_attributes: v8::Local<'s, v8::FixedArray>,
1488
1687
  ) -> Option<v8::Local<'s, v8::Promise>> {
1489
1688
  let resolver = v8::PromiseResolver::new(scope)?;
1490
1689
  let promise = resolver.get_promise(scope);
1491
- let reject = |scope: &mut v8::PinScope<'s, '_>, msg: &str| {
1492
- reject_with_error(scope, resolver, msg);
1493
- };
1494
- let spec = specifier.to_rust_string_lossy(scope);
1495
- let referrer = resource_name.to_rust_string_lossy(scope);
1496
- // The realm import() fired in — handed to the resolver as a Context so it can
1497
- // resolve/compile the module in the right realm (e.g. an iframe's), not the
1498
- // main one.
1499
- let initiating = id_of_context(scope, scope.get_current_context()).unwrap_or(0);
1500
1690
  let core_ptr = istate!(scope).core_ptr;
1501
- if core_ptr.is_null() {
1502
- reject(scope, "dynamic import has no owner");
1691
+ let core = (!core_ptr.is_null()).then(|| unsafe { &*core_ptr });
1692
+ let Some((core, handler)) = core.and_then(|core| Some((core, core.dynamic_import_handler()?)))
1693
+ else {
1694
+ reject_with_error(
1695
+ scope,
1696
+ resolver,
1697
+ "import() is not supported: no dynamic_import_handler",
1698
+ );
1503
1699
  return Some(promise);
1504
- }
1505
- let core = unsafe { &*core_ptr };
1506
- let id = match core.dynamic_import_resolver() {
1507
- // A raising resolver only fails the import() (it rejects generically);
1508
- // it must NOT abort the surrounding eval, so swallow the Err here.
1509
- Some(p) => with_gvl(core, RubyCall::Resolver(&spec), || {
1510
- resolve_module_via_ruby(core, p, &spec, &referrer, Some(initiating))
1511
- })
1512
- .unwrap_or(None),
1513
- None => None,
1514
1700
  };
1515
- match id {
1516
- Some(id) => {
1517
- // The resolved module must live in the context import() ACTUALLY
1518
- // ran in — a foreign-context module would V8-CHECK-abort. Use the
1519
- // scope's current context, not the request's: under kAuto a
1520
- // microtask queued by realm B can run import() during the drain at
1521
- // the end of realm A's request, so the running realm is the truth.
1522
- let current = scope.get_current_context();
1523
- let here = id_of_context(scope, current);
1524
- let g = istate!(scope)
1525
- .modules
1526
- .by_id
1527
- .get(&id)
1528
- .filter(|(_, cid)| Some(*cid) == here)
1529
- .map(|(g, _)| g.clone());
1530
- match g {
1531
- Some(g) => {
1532
- let module = v8::Local::new(scope, &g);
1533
- finish_dynamic_import(scope, module, resolver);
1534
- }
1535
- None => reject(scope, "resolved module not found"),
1536
- }
1701
+ let specifier = specifier.to_rust_string_lossy(scope);
1702
+ // The script import() was called from, by the name it was compiled under
1703
+ // (none: e.g. a function made by `new Function` of no script's).
1704
+ let referrer = resource_name
1705
+ .is_string()
1706
+ .then(|| resource_name.to_rust_string_lossy(scope));
1707
+ let attributes = import_attributes_of(scope, import_attributes, 2);
1708
+ let host_defined = host_defined_value(scope, host_defined_options)
1709
+ .map(|value| marshal::js_to_jsval(scope, value));
1710
+ // The realm import() fired in — whose module the promise is to settle with,
1711
+ // and whose Context the handler is handed. Under kAuto a microtask queued by
1712
+ // realm B can run import() during the drain at the end of realm A's request,
1713
+ // so the running realm is the truth, not the request's.
1714
+ // (…a function of a realm reset or disposed since — another realm holds it — imports nothing: no realm is its)
1715
+ let current = scope.get_current_context();
1716
+ let Some(context_id) = id_of_context(scope, current) else {
1717
+ reject_with_error(scope, resolver, "import() of a realm that is gone");
1718
+ return Some(promise);
1719
+ };
1720
+ let kept = v8::Global::new(scope, resolver);
1721
+ let id = {
1722
+ let imports = &mut istate!(scope).imports;
1723
+ imports.next_id += 1;
1724
+ imports.by_id.insert(imports.next_id, (kept, context_id));
1725
+ imports.next_id
1726
+ };
1727
+ let raised = with_gvl(core, RubyCall::Resolver(&specifier), || {
1728
+ let Some(core) = core.me.upgrade() else {
1729
+ return Some("the isolate is gone".to_owned());
1730
+ };
1731
+ let import = DynamicImport {
1732
+ core,
1733
+ id,
1734
+ context_id,
1735
+ specifier: specifier.clone(),
1736
+ referrer,
1737
+ attributes,
1738
+ host_defined,
1739
+ settled: AtomicBool::new(false),
1740
+ };
1741
+ handler
1742
+ .call::<_, Value>((import,))
1743
+ .err()
1744
+ .map(|e| e.to_string())
1745
+ });
1746
+ if let Some(why) = raised {
1747
+ let pending = istate!(scope).imports.by_id.remove(&id);
1748
+ if let Some((resolver, _)) = pending {
1749
+ let resolver = v8::Local::new(scope, resolver);
1750
+ reject_with_error(scope, resolver, &why);
1537
1751
  }
1538
- None => reject(scope, "import() was not resolved to a module"),
1539
1752
  }
1540
1753
  Some(promise)
1541
1754
  }
1542
1755
 
1756
+ // V8 calls this as a synthetic module (op_create_synthetic_module) evaluates:
1757
+ // its `default` export set to the value kept for it, which it then lets go of.
1758
+ // Returns a fulfilled promise, as a module's evaluation does.
1759
+ fn synthetic_evaluation_steps<'s>(
1760
+ context: v8::Local<'s, v8::Context>,
1761
+ module: v8::Local<'s, v8::Module>,
1762
+ ) -> Option<v8::Local<'s, v8::Value>> {
1763
+ v8::callback_scope!(unsafe scope, context);
1764
+ let hash = module.get_identity_hash().get();
1765
+ // (…V8 told of every failure by an exception: an empty return with none pending is a CHECK)
1766
+ let at = scope.get_slot::<IsolateState>().and_then(|state| {
1767
+ state
1768
+ .synthetic
1769
+ .by_hash
1770
+ .get(&hash)?
1771
+ .iter()
1772
+ .position(|(weak, _, _)| weak.to_local(scope) == Some(module))
1773
+ });
1774
+ let kept = at.and_then(|at| {
1775
+ let by_hash = &mut istate!(scope).synthetic.by_hash;
1776
+ let exports = by_hash.get_mut(&hash)?;
1777
+ let (_, value, _) = exports.remove(at);
1778
+ if exports.is_empty() {
1779
+ by_hash.remove(&hash);
1780
+ }
1781
+ Some(value)
1782
+ });
1783
+ let Some(value) = kept else {
1784
+ throw_js_error(scope, "the synthetic module's value is gone with its realm");
1785
+ return None;
1786
+ };
1787
+ let value = v8::Local::new(scope, value);
1788
+ let Some(name) = v8::String::new(scope, "default") else {
1789
+ throw_js_error(scope, "out of memory");
1790
+ return None;
1791
+ };
1792
+ module.set_synthetic_module_export(scope, name, value)?;
1793
+ let Some(resolver) = v8::PromiseResolver::new(scope) else {
1794
+ throw_js_error(scope, "out of memory");
1795
+ return None;
1796
+ };
1797
+ let undefined = v8::undefined(scope).into();
1798
+ resolver.resolve(scope, undefined);
1799
+ Some(resolver.get_promise(scope).into())
1800
+ }
1801
+
1543
1802
  // The on-fulfilled handler for finish_dynamic_import's native then: ignores
1544
1803
  // the evaluation promise's fulfilment value and returns the module namespace
1545
1804
  // captured as the function's data, so the import() promise fulfils with the
@@ -1552,16 +1811,15 @@ fn dyn_import_namespace_cb(
1552
1811
  rv.set(args.data());
1553
1812
  }
1554
1813
 
1555
- // Complete a dynamic import with the module the resolver named. V8's
1814
+ // Complete a dynamic import with the module the host settled it with. V8's
1556
1815
  // HostImportModuleDynamicallyCallback contract makes load -> link -> evaluate
1557
- // the HOST's responsibility, so a freshly compiled (unevaluated) module is
1558
- // linked and evaluated right here; static imports met while linking resolve
1559
- // through the same dynamic_import_resolver (pump's ResolveModule fallback).
1816
+ // the HOST's responsibility, so a merely compiled module is linked (by the
1817
+ // block DynamicImport#resolve parked) and evaluated right here.
1560
1818
  // The import() promise is settled FROM the evaluation promise, which handles
1561
1819
  // sync completion, a thrown error, and top-level await uniformly — and since
1562
1820
  // V8's Module::Evaluate is idempotent (an Evaluated module returns its
1563
- // existing top-level promise), the registry-hit case costs nothing extra.
1564
- fn finish_dynamic_import(
1821
+ // existing top-level promise), a module evaluated already costs nothing extra.
1822
+ pub(crate) fn finish_dynamic_import(
1565
1823
  scope: &mut v8::PinScope<'_, '_>,
1566
1824
  module: v8::Local<v8::Module>,
1567
1825
  resolver: v8::Local<v8::PromiseResolver>,
@@ -1578,8 +1836,12 @@ fn finish_dynamic_import(
1578
1836
  );
1579
1837
  return;
1580
1838
  }
1839
+ // (…a block that raises failing the import: resolve_imported's `settling_import` — set for the link alone, not
1840
+ // for the evaluation after it, whose own Module#instantiate re-raises as it always does)
1581
1841
  istate!(tc).instantiating = true;
1842
+ istate!(tc).settling_import = true;
1582
1843
  let linked = module.instantiate_module(tc, resolve_imported);
1844
+ istate!(tc).settling_import = false;
1583
1845
  istate!(tc).instantiating = false;
1584
1846
  if linked != Some(true) {
1585
1847
  // A watchdog/terminate that landed during linking must escalate to
@@ -1763,7 +2025,7 @@ struct Core {
1763
2025
  // each `run`.
1764
2026
  depth: std::sync::atomic::AtomicU32,
1765
2027
  // Everything this isolate keeps alive on the Ruby side — the attached host fns
1766
- // and the dynamic-import resolver — in one Array the wrappers MARK (and pin).
2028
+ // and the dynamic-import handler — in one Array the wrappers MARK (and pin).
1767
2029
  // See the module header for why these must not be GC roots; ROOT_* for the
1768
2030
  // layout. Read on the V8 side without the GVL (the import hooks), which is
1769
2031
  // sound because the entries are pinned and nothing here allocates or raises.
@@ -1781,6 +2043,10 @@ struct Core {
1781
2043
  // Set with each push there, so the request boundary looks at the lock only
1782
2044
  // when there is something under it.
1783
2045
  handles_released: AtomicBool,
2046
+ // The extra realms disposed so far (ids are never reused), so any Context
2047
+ // wrapper of one — not only the one dispose was called on, a
2048
+ // DynamicImport#context's too — reads as disposed.
2049
+ disposed_realms: Mutex<std::collections::HashSet<i32>>,
1784
2050
  // Default per-eval/call timeout (ms); 0 = none. eval(timeout_ms:)'s explicit
1785
2051
  // value overrides it. Guards against an in-V8 infinite loop without a watchdog.
1786
2052
  default_timeout_ms: u64,
@@ -1862,7 +2128,25 @@ struct JsFunction {
1862
2128
  disposed: AtomicBool,
1863
2129
  }
1864
2130
 
1865
- // The five wrappers that hold an Arc<Core> all mark the isolate's roots, because any
2131
+ // An import() waiting for its host (dynamic_import_cb), handed to the
2132
+ // Isolate's dynamic_import_handler: what was asked — the specifier, the import
2133
+ // attributes, the referring script's name and host-defined value — and in
2134
+ // which realm, until #resolve / #reject / #reject_with settles it (ImportReg
2135
+ // keeps the promise). Let go of unsettled, the promise is let go of too.
2136
+ #[derive(TypedData)]
2137
+ #[magnus(class = "RustyRacer::DynamicImport", mark)]
2138
+ struct DynamicImport {
2139
+ core: Arc<Core>,
2140
+ id: u64,
2141
+ context_id: i32,
2142
+ specifier: String,
2143
+ referrer: Option<String>,
2144
+ attributes: Vec<(String, String)>,
2145
+ host_defined: Option<JsVal>,
2146
+ settled: AtomicBool,
2147
+ }
2148
+
2149
+ // The six wrappers that hold an Arc<Core> all mark the isolate's roots, because any
1866
2150
  // one of them may be the last one reachable: Ruby code is free to keep only the
1867
2151
  // Context a `Isolate#context` handed it, or only a Module, and the host fns must
1868
2152
  // stay callable through it. Marking the same array five times costs nothing (the GC
@@ -1881,6 +2165,7 @@ marks_core_roots!(Context);
1881
2165
  marks_core_roots!(JsModule);
1882
2166
  marks_core_roots!(Script);
1883
2167
  marks_core_roots!(JsFunction);
2168
+ marks_core_roots!(DynamicImport);
1884
2169
 
1885
2170
  // Set true once V8 is initialized; Platform.set_flags! refuses after that
1886
2171
  // (flags must be set before V8::initialize), like mini_racer's
@@ -2067,6 +2352,30 @@ fn set_promise_reject_handler(
2067
2352
  }
2068
2353
  }
2069
2354
 
2355
+ // NS.setImportMetaHandler(fn | null): register (or clear) the realm's handler
2356
+ // import_meta_cb hands each of its modules' import.meta to, as it is first
2357
+ // read — the realm whose namespace is called, whose global keeps it under a
2358
+ // private key (import_meta_key), so it goes with the realm, a reset's included,
2359
+ // and a realm init hook may set it before the realm is filed.
2360
+ fn set_import_meta_handler(
2361
+ scope: &mut v8::PinScope<'_, '_>,
2362
+ args: v8::FunctionCallbackArguments<'_>,
2363
+ _rv: v8::ReturnValue<'_, v8::Value>,
2364
+ ) {
2365
+ let global = scope.get_current_context().global(scope);
2366
+ let key = import_meta_key(scope);
2367
+ match v8::Local::<v8::Function>::try_from(args.get(0)) {
2368
+ Ok(f) => global.set_private(scope, key, f.into()),
2369
+ Err(_) => global.delete_private(scope, key),
2370
+ };
2371
+ }
2372
+
2373
+ // The private key a realm's global keeps its import-meta handler under.
2374
+ fn import_meta_key<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Private> {
2375
+ let name = v8::String::new(scope, "rusty_racer:import_meta_handler").expect("a short string");
2376
+ v8::Private::for_api(scope, Some(name))
2377
+ }
2378
+
2070
2379
  // NS.transferOut(arrayBufferOrView) -> a positive integer token, or 0 when the
2071
2380
  // argument can't be zero-copy transferred so the caller falls back to a copy.
2072
2381
  // Grabs the buffer's backing store, DETACHES the source (transfer semantics: its
@@ -2511,7 +2820,7 @@ fn install_host_namespace(
2511
2820
  } else {
2512
2821
  v8::Object::new(scope)
2513
2822
  };
2514
- let members: [(&str, Option<v8::Local<v8::Function>>); 9] = [
2823
+ let members: [(&str, Option<v8::Local<v8::Function>>); 10] = [
2515
2824
  (
2516
2825
  "drainMicrotasks",
2517
2826
  v8::Function::new(scope, drain_microtasks),
@@ -2522,6 +2831,10 @@ fn install_host_namespace(
2522
2831
  "setPromiseRejectHandler",
2523
2832
  v8::Function::new(scope, set_promise_reject_handler),
2524
2833
  ),
2834
+ (
2835
+ "setImportMetaHandler",
2836
+ v8::Function::new(scope, set_import_meta_handler),
2837
+ ),
2525
2838
  ("transferOut", v8::Function::new(scope, transfer_out)),
2526
2839
  ("transferIn", v8::Function::new(scope, transfer_in)),
2527
2840
  ("shareOut", v8::Function::new(scope, share_out)),
@@ -2722,7 +3035,7 @@ impl Isolate {
2722
3035
  // :auto/:explicit distinction lives in auto_microtasks (read by
2723
3036
  // auto_drain).
2724
3037
  isolate.set_microtasks_policy(v8::MicrotasksPolicy::Explicit);
2725
- // JS import() routes here; rejects unless a dynamic_import_resolver is set.
3038
+ // JS import() routes here; rejects unless a dynamic_import_handler is set.
2726
3039
  isolate.set_host_import_module_dynamically_callback(dynamic_import_cb);
2727
3040
  // Fills import.meta.url (the module's compile-time filename) on first access.
2728
3041
  isolate.set_host_initialize_import_meta_object_callback(import_meta_cb);
@@ -2775,7 +3088,7 @@ impl Isolate {
2775
3088
  // owner check.
2776
3089
  use magnus::rb_sys::{AsRawValue, FromRawValue};
2777
3090
  let owner_thread = unsafe { Value::from_raw(rb_sys::rb_thread_current()) };
2778
- // The roots array (see ROOT_IMPORT_RESOLVER): created empty, grown by the
3091
+ // The roots array (see ROOT_IMPORT_HANDLER): created empty, grown by the
2779
3092
  // first attach. Nothing roots it — the wrappers mark it, so it lives
2780
3093
  // exactly as long as this isolate is reachable from Ruby.
2781
3094
  let roots = ruby.ary_new();
@@ -2796,6 +3109,7 @@ impl Isolate {
2796
3109
  procs: Mutex::new(ProcTable::default()),
2797
3110
  released: Mutex::new(Vec::new()),
2798
3111
  handles_released: AtomicBool::new(false),
3112
+ disposed_realms: Mutex::new(std::collections::HashSet::new()),
2799
3113
  default_timeout_ms: timeout_ms,
2800
3114
  memory_limit,
2801
3115
  watchdog,
@@ -3094,7 +3408,7 @@ impl Core {
3094
3408
  .clone()
3095
3409
  }
3096
3410
 
3097
- // ── the roots array (see the module header + ROOT_IMPORT_RESOLVER) ──────
3411
+ // ── the roots array (see the module header + ROOT_IMPORT_HANDLER) ──────
3098
3412
  // Keep `val` alive for as long as this isolate is reachable from Ruby. On a
3099
3413
  // Ruby thread with the GVL: storing can grow the Array, which allocates.
3100
3414
  fn root_store<T: magnus::IntoValue>(
@@ -3455,6 +3769,7 @@ impl Core {
3455
3769
  let reply = self.run(ruby, Request::DisposeContext { context_id })?;
3456
3770
  self.reply_value(ruby, reply)?;
3457
3771
  self.release_context_procs(ruby, context_id);
3772
+ self.disposed_realms.lock().unwrap().insert(context_id);
3458
3773
  Ok(())
3459
3774
  }
3460
3775
 
@@ -3469,6 +3784,7 @@ impl Core {
3469
3784
  cached_data: Option<Vec<u8>>,
3470
3785
  produce_cache: bool,
3471
3786
  eager: bool,
3787
+ host_defined: Option<JsVal>,
3472
3788
  ) -> Result<Compiled, Error> {
3473
3789
  let reply = self.run(
3474
3790
  ruby,
@@ -3479,6 +3795,7 @@ impl Core {
3479
3795
  cached_data,
3480
3796
  produce_cache,
3481
3797
  eager,
3798
+ host_defined,
3482
3799
  },
3483
3800
  )?;
3484
3801
  match reply {
@@ -3569,6 +3886,114 @@ impl Core {
3569
3886
  self.reply_value(ruby, reply)
3570
3887
  }
3571
3888
 
3889
+ // [[specifier, attributes], …], each request's attributes a Hash (attributes_hash).
3890
+ fn module_script_id(&self, ruby: &Ruby, module_id: i32) -> Result<Value, Error> {
3891
+ let reply = self.run(ruby, Request::ModuleScriptId { module_id })?;
3892
+ self.reply_value(ruby, reply)
3893
+ }
3894
+
3895
+ fn module_requests(&self, ruby: &Ruby, module_id: i32) -> Result<Value, Error> {
3896
+ let JsVal::Array { items, .. } =
3897
+ (match self.run(ruby, Request::ModuleRequests { module_id })? {
3898
+ VmReply::Done(Ok(value)) => value,
3899
+ VmReply::Done(Err(e)) => return Err(vm_err(ruby, e)),
3900
+ _ => {
3901
+ return Err(Error::new(
3902
+ err_class(ruby, "InternalError"),
3903
+ "internal: unexpected requests reply",
3904
+ ));
3905
+ }
3906
+ })
3907
+ else {
3908
+ return Err(Error::new(
3909
+ err_class(ruby, "InternalError"),
3910
+ "internal: unexpected requests reply",
3911
+ ));
3912
+ };
3913
+ let requests = ruby.ary_new_capa(items.len());
3914
+ for item in items {
3915
+ let JsVal::Array { items: pair, .. } = item else {
3916
+ continue;
3917
+ };
3918
+ let (Some(JsVal::Str(specifier)), Some(JsVal::Obj { entries, .. })) =
3919
+ (pair.first(), pair.get(1))
3920
+ else {
3921
+ continue;
3922
+ };
3923
+ let attributes: Vec<(String, String)> = entries
3924
+ .iter()
3925
+ .filter_map(|(key, value)| match value {
3926
+ JsVal::Str(value) => Some((key.clone(), value.clone())),
3927
+ _ => None,
3928
+ })
3929
+ .collect();
3930
+ requests.push(ruby.ary_new_from_values(&[
3931
+ ruby.str_new(specifier).as_value(),
3932
+ attributes_hash(ruby, &attributes)?.as_value(),
3933
+ ]))?;
3934
+ }
3935
+ Ok(requests.as_value())
3936
+ }
3937
+
3938
+ // A synthetic module of the realm's (Request::CreateSyntheticModule): its id.
3939
+ fn synthetic_module(
3940
+ &self,
3941
+ ruby: &Ruby,
3942
+ context_id: i32,
3943
+ filename: String,
3944
+ export: SyntheticExport,
3945
+ ) -> Result<i32, Error> {
3946
+ let reply = self.run(
3947
+ ruby,
3948
+ Request::CreateSyntheticModule {
3949
+ context_id,
3950
+ filename,
3951
+ export,
3952
+ timeout_ms: self.default_timeout_ms,
3953
+ },
3954
+ )?;
3955
+ match reply {
3956
+ VmReply::Done(Ok(JsVal::Int(id))) => Ok(id as i32),
3957
+ VmReply::Done(Err(e)) => Err(vm_err(ruby, e)),
3958
+ _ => Err(Error::new(
3959
+ err_class(ruby, "InternalError"),
3960
+ "internal: unexpected synthetic module reply",
3961
+ )),
3962
+ }
3963
+ }
3964
+
3965
+ // Settle the waiting import() |import_id| (Request::SettleImport): whether it
3966
+ // was still waiting. A module is linked by |resolve| (parked as
3967
+ // instantiate_module parks its block, the outer op's put back after).
3968
+ fn settle_import(
3969
+ &self,
3970
+ ruby: &Ruby,
3971
+ import_id: u64,
3972
+ settle: Settle,
3973
+ resolve: Option<Proc>,
3974
+ ) -> Result<bool, Error> {
3975
+ self.ensure_owner_and_live(ruby)?;
3976
+ let parked = resolve.map(|p| RootedProc(BoxValue::new(p)));
3977
+ let (saved_resolve, saved_err) = self.swap_instantiate(parked, None);
3978
+ let reply = self.run(
3979
+ ruby,
3980
+ Request::SettleImport {
3981
+ import_id,
3982
+ settle,
3983
+ timeout_ms: self.default_timeout_ms,
3984
+ },
3985
+ );
3986
+ self.swap_instantiate(saved_resolve, saved_err);
3987
+ match reply? {
3988
+ VmReply::Done(Ok(JsVal::Bool(settled))) => Ok(settled),
3989
+ VmReply::Done(Err(e)) => Err(vm_err(ruby, e)),
3990
+ _ => Err(Error::new(
3991
+ err_class(ruby, "InternalError"),
3992
+ "internal: unexpected import reply",
3993
+ )),
3994
+ }
3995
+ }
3996
+
3572
3997
  // Classic script: compile, run, dispose.
3573
3998
  #[allow(clippy::too_many_arguments)]
3574
3999
  fn compile_script(
@@ -3580,6 +4005,7 @@ impl Core {
3580
4005
  cached_data: Option<Vec<u8>>,
3581
4006
  produce_cache: bool,
3582
4007
  eager: bool,
4008
+ host_defined: Option<JsVal>,
3583
4009
  ) -> Result<Compiled, Error> {
3584
4010
  let reply = self.run(
3585
4011
  ruby,
@@ -3590,6 +4016,7 @@ impl Core {
3590
4016
  cached_data,
3591
4017
  produce_cache,
3592
4018
  eager,
4019
+ host_defined,
3593
4020
  },
3594
4021
  )?;
3595
4022
  match reply {
@@ -3622,6 +4049,11 @@ impl Core {
3622
4049
  code_cache_from_reply(ruby, reply)
3623
4050
  }
3624
4051
 
4052
+ fn unbound_script_id(&self, ruby: &Ruby, script_id: i32) -> Result<Value, Error> {
4053
+ let reply = self.run(ruby, Request::UnboundScriptId { script_id })?;
4054
+ self.reply_value(ruby, reply)
4055
+ }
4056
+
3625
4057
  fn module_code_cache(&self, ruby: &Ruby, module_id: i32) -> Result<Option<Vec<u8>>, Error> {
3626
4058
  let reply = self.run(ruby, Request::ModuleCodeCache { module_id })?;
3627
4059
  code_cache_from_reply(ruby, reply)
@@ -3630,15 +4062,16 @@ impl Core {
3630
4062
  // Owner-thread only, like every other writer of the roots array (`attach`,
3631
4063
  // `attach_many`, `dispose`): the store can REALLOC the array's element storage, and
3632
4064
  // the import hooks read that storage with the GVL released.
3633
- fn set_dynamic_import_resolver(&self, ruby: &Ruby, proc: Proc) -> Result<(), Error> {
4065
+ // (…nil clearing it: an import() rejected then)
4066
+ fn set_dynamic_import_handler(&self, ruby: &Ruby, proc: Option<Proc>) -> Result<(), Error> {
3634
4067
  self.ensure_owner_and_live(ruby)?;
3635
- self.root_store(ruby, ROOT_IMPORT_RESOLVER, proc)
4068
+ self.root_store(ruby, ROOT_IMPORT_HANDLER, proc)
3636
4069
  }
3637
4070
 
3638
- // The resolver, or None if none was set. Read on the V8 side without the GVL —
4071
+ // The handler, or None if none was set. Read on the V8 side without the GVL —
3639
4072
  // see root_proc.
3640
- fn dynamic_import_resolver(&self) -> Option<Proc> {
3641
- self.root_proc(ROOT_IMPORT_RESOLVER)
4073
+ fn dynamic_import_handler(&self) -> Option<Proc> {
4074
+ self.root_proc(ROOT_IMPORT_HANDLER)
3642
4075
  }
3643
4076
 
3644
4077
  // Terminate whatever is running. IsolateHandle is Send + refcounted —
@@ -3858,9 +4291,14 @@ impl Isolate {
3858
4291
  fn pump_message_loop(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
3859
4292
  rb_self.core.pump_message_loop(ruby)
3860
4293
  }
3861
- // dynamic_import_resolver = ->(specifier, referrer_url) { module } for import().
3862
- fn set_dynamic_import_resolver(ruby: &Ruby, rb_self: &Self, proc: Proc) -> Result<(), Error> {
3863
- rb_self.core.set_dynamic_import_resolver(ruby, proc)
4294
+ // dynamic_import_handler = ->(import) { ... } for import(): handed each one's
4295
+ // RustyRacer::DynamicImport.
4296
+ fn set_dynamic_import_handler(
4297
+ ruby: &Ruby,
4298
+ rb_self: &Self,
4299
+ proc: Option<Proc>,
4300
+ ) -> Result<(), Error> {
4301
+ rb_self.core.set_dynamic_import_handler(ruby, proc)
3864
4302
  }
3865
4303
  fn dispose(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
3866
4304
  rb_self.core.dispose(ruby)
@@ -3879,7 +4317,7 @@ impl Context {
3879
4317
  }
3880
4318
  fn check_live(&self, ruby: &Ruby) -> Result<(), Error> {
3881
4319
  // id 0's lifetime is the isolate's; extras also track their own dispose.
3882
- if self.disposed.load(Ordering::SeqCst) || self.core.is_disposed() {
4320
+ if self.disposed() {
3883
4321
  return Err(Error::new(
3884
4322
  err_class(ruby, "DisposedError"),
3885
4323
  "disposed context",
@@ -3954,6 +4392,7 @@ impl Context {
3954
4392
  rb_self.check_live(ruby)?;
3955
4393
  rb_self.core.reset(ruby, rb_self.id)
3956
4394
  }
4395
+ #[allow(clippy::too_many_arguments)]
3957
4396
  fn compile_module(
3958
4397
  ruby: &Ruby,
3959
4398
  rb_self: &Self,
@@ -3962,9 +4401,11 @@ impl Context {
3962
4401
  cached_data: Option<magnus::RString>,
3963
4402
  produce_cache: bool,
3964
4403
  eager: bool,
4404
+ host_defined: Value,
3965
4405
  ) -> Result<JsModule, Error> {
3966
4406
  rb_self.check_live(ruby)?;
3967
4407
  let cache_in = binary_bytes(ruby, cached_data)?;
4408
+ let host_defined = host_defined_arg(ruby, host_defined)?;
3968
4409
  let cm = rb_self.core.compile_module(
3969
4410
  ruby,
3970
4411
  rb_self.id,
@@ -3973,17 +4414,57 @@ impl Context {
3973
4414
  cache_in,
3974
4415
  produce_cache,
3975
4416
  eager,
4417
+ host_defined,
3976
4418
  )?;
3977
- Ok(JsModule {
3978
- core: rb_self.core.clone(),
3979
- module_id: cm.id,
4419
+ Ok(rb_self.module(cm.id, cm.cached_data, cm.cache_rejected))
4420
+ }
4421
+ fn module(
4422
+ &self,
4423
+ module_id: i32,
4424
+ cached_data: Option<Vec<u8>>,
4425
+ cache_rejected: bool,
4426
+ ) -> JsModule {
4427
+ JsModule {
4428
+ core: self.core.clone(),
4429
+ module_id,
3980
4430
  disposed: AtomicBool::new(false),
3981
- cached_data: cm.cached_data,
3982
- cache_rejected: cm.cache_rejected,
3983
- })
4431
+ cached_data,
4432
+ cache_rejected,
4433
+ }
4434
+ }
4435
+ // _synthetic_module(filename, kind, payload, args): a module exporting
4436
+ // `default` alone — kind 0: payload marshalled; 1: payload a JSON text,
4437
+ // %JSON.parse%d; 2: payload a function path, called with args.
4438
+ fn synthetic_module(
4439
+ ruby: &Ruby,
4440
+ rb_self: &Self,
4441
+ filename: String,
4442
+ kind: u8,
4443
+ payload: Value,
4444
+ args: RArray,
4445
+ ) -> Result<JsModule, Error> {
4446
+ rb_self.check_live(ruby)?;
4447
+ let export = match kind {
4448
+ 0 => SyntheticExport::Value(ruby_to_jsval(payload)?),
4449
+ 1 => SyntheticExport::Json(String::try_convert(payload)?),
4450
+ _ => SyntheticExport::Call {
4451
+ path: String::try_convert(payload)?,
4452
+ args: {
4453
+ let args: Vec<Value> = (0..args.len())
4454
+ .map(|i| args.entry::<Value>(i as isize))
4455
+ .collect::<Result<_, _>>()?;
4456
+ js_args(&args)?
4457
+ },
4458
+ },
4459
+ };
4460
+ let id = rb_self
4461
+ .core
4462
+ .synthetic_module(ruby, rb_self.id, filename, export)?;
4463
+ Ok(rb_self.module(id, None, false))
3984
4464
  }
3985
4465
  // compile(source, filename:, cached_data:, produce_cache:, eager:) -> Script:
3986
4466
  // a classic <script>. Same cache semantics as compile_module.
4467
+ #[allow(clippy::too_many_arguments)]
3987
4468
  fn compile(
3988
4469
  ruby: &Ruby,
3989
4470
  rb_self: &Self,
@@ -3992,9 +4473,11 @@ impl Context {
3992
4473
  cached_data: Option<magnus::RString>,
3993
4474
  produce_cache: bool,
3994
4475
  eager: bool,
4476
+ host_defined: Value,
3995
4477
  ) -> Result<Script, Error> {
3996
4478
  rb_self.check_live(ruby)?;
3997
4479
  let cache_in = binary_bytes(ruby, cached_data)?;
4480
+ let host_defined = host_defined_arg(ruby, host_defined)?;
3998
4481
  let cs = rb_self.core.compile_script(
3999
4482
  ruby,
4000
4483
  rb_self.id,
@@ -4003,6 +4486,7 @@ impl Context {
4003
4486
  cache_in,
4004
4487
  produce_cache,
4005
4488
  eager,
4489
+ host_defined,
4006
4490
  )?;
4007
4491
  Ok(Script {
4008
4492
  core: rb_self.core.clone(),
@@ -4024,7 +4508,9 @@ impl Context {
4024
4508
  Ok(())
4025
4509
  }
4026
4510
  fn disposed(&self) -> bool {
4027
- self.disposed.load(Ordering::SeqCst) || self.core.is_disposed()
4511
+ self.disposed.load(Ordering::SeqCst)
4512
+ || self.core.is_disposed()
4513
+ || self.core.disposed_realms.lock().unwrap().contains(&self.id)
4028
4514
  }
4029
4515
  }
4030
4516
 
@@ -4141,6 +4627,21 @@ impl JsModule {
4141
4627
  rb_self.check_live(ruby)?;
4142
4628
  rb_self.core.module_graph_async(ruby, rb_self.module_id)
4143
4629
  }
4630
+ // The module's script id (V8 Module::ScriptId) — what StackFrame#script_id /
4631
+ // an embedder's stack walk names its code by — or nil: a synthetic module, an
4632
+ // errored one. Modules V8's compilation cache shares (the same source and
4633
+ // filename) share it.
4634
+ fn script_id(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
4635
+ rb_self.check_live(ruby)?;
4636
+ rb_self.core.module_script_id(ruby, rb_self.module_id)
4637
+ }
4638
+ // [[specifier, attributes], …]: the module's requests (V8 GetModuleRequests),
4639
+ // each with its import attributes as a Hash, in source order — what linking
4640
+ // it will ask its resolve block for. A synthetic module has none.
4641
+ fn requests(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
4642
+ rb_self.check_live(ruby)?;
4643
+ rb_self.core.module_requests(ruby, rb_self.module_id)
4644
+ }
4144
4645
  // The bytecode cache produced at compile (produce_cache: true), as a binary
4145
4646
  // String, or nil. Persist it cross-process and pass back via cached_data:.
4146
4647
  fn cached_data(ruby: &Ruby, rb_self: &Self) -> Value {
@@ -4195,6 +4696,13 @@ impl Script {
4195
4696
  rb_self.check_live(ruby)?;
4196
4697
  rb_self.core.run_script(ruby, rb_self.script_id, true)
4197
4698
  }
4699
+ // The script's V8 script id (UnboundScript::GetId), as Module#script_id: what
4700
+ // a stack frame of its code names it by. Scripts V8's compilation cache
4701
+ // shares (the same source and origin) share it.
4702
+ fn script_id(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
4703
+ rb_self.check_live(ruby)?;
4704
+ rb_self.core.unbound_script_id(ruby, rb_self.script_id)
4705
+ }
4198
4706
  fn cached_data(ruby: &Ruby, rb_self: &Self) -> Value {
4199
4707
  code_cache_value(ruby, rb_self.cached_data.as_ref())
4200
4708
  }
@@ -4432,38 +4940,87 @@ fn js_runtime_error(ruby: &Ruby, message: String, backtrace: Vec<String>) -> Err
4432
4940
  }
4433
4941
  }
4434
4942
 
4435
- // instantiate's resolve block returns a RustyRacer::Module (or nil for a
4436
- // genuinely-unresolved import); pull its module_id so the V8 thread can look up
4437
- // the V8 module. Verifies the module belongs to THIS Context (core identity),
4438
- // since module ids are per-V8-thread and a foreign id would alias a local one.
4439
- // A raised block propagates as Err (not silently swallowed into "not found").
4943
+ // A `host_defined:` argument: nil for none, else a primitive — an Integer, a
4944
+ // Float, a String, true or false — that a ScriptOrigin can carry.
4945
+ fn host_defined_arg(ruby: &Ruby, value: Value) -> Result<Option<JsVal>, Error> {
4946
+ if value.is_nil() {
4947
+ return Ok(None);
4948
+ }
4949
+ // (…a Symbol marshals as a String would, but names nothing a script was given: refused, as any other value is)
4950
+ if magnus::Symbol::from_value(value).is_some()
4951
+ || magnus::value::StaticSymbol::from_value(value).is_some()
4952
+ {
4953
+ return Err(Error::new(
4954
+ ruby.exception_arg_error(),
4955
+ "host_defined: must be nil, an Integer, a Float, a String, true or false",
4956
+ ));
4957
+ }
4958
+ match ruby_to_jsval(value)? {
4959
+ v @ (JsVal::Bool(_)
4960
+ | JsVal::Int(_)
4961
+ | JsVal::Num(_)
4962
+ | JsVal::Str(_)
4963
+ | JsVal::BigInt { .. }) => Ok(Some(v)),
4964
+ _ => Err(Error::new(
4965
+ ruby.exception_arg_error(),
4966
+ "host_defined: must be nil, an Integer, a Float, a String, true or false",
4967
+ )),
4968
+ }
4969
+ }
4970
+
4971
+ // A resolve block returns a RustyRacer::Module (or nil for a genuinely-
4972
+ // unresolved import); pull its module_id so the V8 side can look up the V8
4973
+ // module. Verifies the module belongs to THIS isolate (core identity), since
4974
+ // module ids are per-isolate and a foreign id would alias a local one. A
4975
+ // raised block propagates as Err (not silently swallowed into "not found").
4976
+ // The block is handed (specifier, referrer_url, attributes) — a lambda of two
4977
+ // parameters the first two alone, as it always was.
4440
4978
  fn resolve_module_via_ruby(
4441
4979
  core: &Core,
4442
4980
  resolve: Proc,
4443
4981
  specifier: &str,
4444
4982
  referrer_url: &str,
4445
- // Some(realm id) for the dynamic_import_resolver: it then receives the
4446
- // initiating realm as a 3rd Context arg so it can resolve per-realm. None for
4447
- // the static instantiate block, whose (specifier, referrer_url) contract is
4448
- // unchanged.
4449
- initiating_context: Option<i32>,
4983
+ attributes: &[(String, String)],
4450
4984
  ) -> Result<Option<i32>, Error> {
4451
4985
  let ruby = Ruby::get().unwrap();
4452
- let ret: Value = match core.me.upgrade().zip(initiating_context) {
4453
- Some((core_arc, id)) => {
4454
- let ctx = Context {
4455
- core: core_arc,
4456
- id,
4457
- disposed: AtomicBool::new(false),
4458
- };
4459
- resolve.call((specifier, referrer_url, ctx))?
4460
- }
4461
- None => resolve.call((specifier, referrer_url))?,
4986
+ let ret: Value = if !takes_three(resolve)? {
4987
+ resolve.call((specifier, referrer_url))?
4988
+ } else {
4989
+ resolve.call((specifier, referrer_url, attributes_hash(&ruby, attributes)?))?
4462
4990
  };
4463
- if ret.is_nil() {
4991
+ module_id_of(&ruby, core, ret)
4992
+ }
4993
+
4994
+ // Whether a resolve block takes a third argument: any proc does (it drops what it
4995
+ // has no parameter for); a lambda one with a rest parameter, or three in all.
4996
+ fn takes_three(resolve: Proc) -> Result<bool, Error> {
4997
+ if !resolve.is_lambda() {
4998
+ return Ok(true);
4999
+ }
5000
+ let arity = resolve.arity();
5001
+ if arity >= 0 {
5002
+ return Ok(arity >= 3);
5003
+ }
5004
+ let parameters: RArray = resolve.funcall("parameters", ())?;
5005
+ let mut count = 0;
5006
+ for parameter in parameters.into_iter() {
5007
+ let kind: magnus::Symbol = RArray::try_convert(parameter)?.entry(0)?;
5008
+ match kind.name()?.as_ref() {
5009
+ "rest" => return Ok(true),
5010
+ "req" | "opt" => count += 1,
5011
+ _ => {}
5012
+ }
5013
+ }
5014
+ Ok(count >= 3)
5015
+ }
5016
+
5017
+ // The id of the RustyRacer::Module |value| — None for nil, or a disposed one —
5018
+ // of the isolate |core|.
5019
+ fn module_id_of(ruby: &Ruby, core: &Core, value: Value) -> Result<Option<i32>, Error> {
5020
+ if value.is_nil() {
4464
5021
  return Ok(None); // legitimately unresolved
4465
5022
  }
4466
- let obj = magnus::typed_data::Obj::<JsModule>::try_convert(ret).map_err(|_| {
5023
+ let obj = magnus::typed_data::Obj::<JsModule>::try_convert(value).map_err(|_| {
4467
5024
  Error::new(
4468
5025
  ruby.exception_type_error(),
4469
5026
  "module resolver must return a RustyRacer::Module or nil",
@@ -4471,8 +5028,8 @@ fn resolve_module_via_ruby(
4471
5028
  })?;
4472
5029
  if !std::ptr::eq(Arc::as_ptr(&obj.core), core as *const Core) {
4473
5030
  return Err(Error::new(
4474
- err_class(&ruby, "Error"),
4475
- "module resolver returned a Module from a different Context",
5031
+ err_class(ruby, "Error"),
5032
+ "module resolver returned a Module of another isolate",
4476
5033
  ));
4477
5034
  }
4478
5035
  if obj.disposed.load(Ordering::SeqCst) {
@@ -4481,6 +5038,91 @@ fn resolve_module_via_ruby(
4481
5038
  Ok(Some(obj.module_id))
4482
5039
  }
4483
5040
 
5041
+ impl DynamicImport {
5042
+ fn specifier(&self) -> String {
5043
+ self.specifier.clone()
5044
+ }
5045
+ // The name of the script import() was called from (its filename), or nil.
5046
+ fn referrer(&self) -> Option<String> {
5047
+ self.referrer.clone()
5048
+ }
5049
+ // {key => value} of its `with` options' import attributes.
5050
+ fn attributes(ruby: &Ruby, rb_self: &Self) -> Result<RHash, Error> {
5051
+ attributes_hash(ruby, &rb_self.attributes)
5052
+ }
5053
+ // The `host_defined:` value of the script import() was called from, or nil.
5054
+ fn host_defined(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
5055
+ match &rb_self.host_defined {
5056
+ Some(value) => marshal::jsval_to_ruby(ruby, value),
5057
+ None => Ok(ruby.qnil().as_value()),
5058
+ }
5059
+ }
5060
+ // The realm import() was called in: a module it is resolved with is of it.
5061
+ fn context(&self) -> Context {
5062
+ Context {
5063
+ core: self.core.clone(),
5064
+ id: self.context_id,
5065
+ disposed: AtomicBool::new(false),
5066
+ }
5067
+ }
5068
+ fn is_settled(&self) -> bool {
5069
+ self.settled.load(Ordering::SeqCst)
5070
+ }
5071
+ fn settle(&self, ruby: &Ruby, settle: Settle, resolve: Option<Proc>) -> Result<bool, Error> {
5072
+ if self.settled.load(Ordering::SeqCst) || self.core.is_disposed() {
5073
+ return Ok(false);
5074
+ }
5075
+ // (…settled once the op has run, whatever it raised — a terminated evaluation's — as the registry let go of it)
5076
+ self.core.ensure_owner_and_live(ruby)?;
5077
+ let settled = self.core.settle_import(ruby, self.id, settle, resolve);
5078
+ self.settled.store(true, Ordering::SeqCst);
5079
+ settled
5080
+ }
5081
+ // _resolve(module, block): settle it with |module| — linked by |block| where
5082
+ // it is not yet (as Module#instantiate's), and evaluated — the promise then
5083
+ // fulfilled with its namespace, or rejected with what failed.
5084
+ fn resolve(
5085
+ ruby: &Ruby,
5086
+ rb_self: &Self,
5087
+ module: Value,
5088
+ block: Option<Proc>,
5089
+ ) -> Result<bool, Error> {
5090
+ let Some(module_id) = module_id_of(ruby, &rb_self.core, module)? else {
5091
+ return Err(Error::new(
5092
+ ruby.exception_arg_error(),
5093
+ "resolve needs a RustyRacer::Module that is not disposed",
5094
+ ));
5095
+ };
5096
+ rb_self.settle(ruby, Settle::Module(module_id), block)
5097
+ }
5098
+ // reject(value): rejected with |value|, marshalled into its realm.
5099
+ fn reject(ruby: &Ruby, rb_self: &Self, value: Value) -> Result<bool, Error> {
5100
+ let value = ruby_to_jsval(value)?;
5101
+ rb_self.settle(ruby, Settle::Reject(value), None)
5102
+ }
5103
+ // reject_with(path, *args): rejected with what the function at |path| (as
5104
+ // Context#call names one, in its realm) returns — or throws.
5105
+ fn reject_with(ruby: &Ruby, rb_self: &Self, args: &[Value]) -> Result<bool, Error> {
5106
+ let Some((path, args)) = args.split_first() else {
5107
+ return Err(Error::new(
5108
+ ruby.exception_arg_error(),
5109
+ "reject_with needs a function path",
5110
+ ));
5111
+ };
5112
+ let path = String::try_convert(*path)?;
5113
+ let args = js_args(args)?;
5114
+ rb_self.settle(ruby, Settle::RejectWith { path, args }, None)
5115
+ }
5116
+ }
5117
+
5118
+ impl Drop for DynamicImport {
5119
+ fn drop(&mut self) {
5120
+ if !self.settled.swap(true, Ordering::SeqCst) {
5121
+ self.core.release(Released::Import(self.id));
5122
+ }
5123
+ }
5124
+ }
5125
+
4484
5126
  #[magnus::init]
4485
5127
  fn init(ruby: &Ruby) -> Result<(), Error> {
4486
5128
  install_classes(ruby)
@@ -4510,8 +5152,8 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
4510
5152
  )?;
4511
5153
  // lib keeps the proc in an ivar (GC liveness) and calls this primitive.
4512
5154
  isolate.define_method(
4513
- "_set_dynamic_import_resolver",
4514
- method!(Isolate::set_dynamic_import_resolver, 1),
5155
+ "_set_dynamic_import_handler",
5156
+ method!(Isolate::set_dynamic_import_handler, 1),
4515
5157
  )?;
4516
5158
  isolate.define_method("heap_statistics", method!(Isolate::heap_statistics, 0))?;
4517
5159
  isolate.define_method(
@@ -4535,8 +5177,9 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
4535
5177
  context.define_method("reset", method!(Context::reset, 0))?;
4536
5178
  context.define_method("id", method!(Context::id, 0))?;
4537
5179
  // keyword-arg wrappers Context#compile_module / #compile (source, ...) in lib.
4538
- context.define_method("_compile_module", method!(Context::compile_module, 5))?;
4539
- context.define_method("_compile", method!(Context::compile, 5))?;
5180
+ context.define_method("_compile_module", method!(Context::compile_module, 6))?;
5181
+ context.define_method("_compile", method!(Context::compile, 6))?;
5182
+ context.define_method("_synthetic_module", method!(Context::synthetic_module, 4))?;
4540
5183
  context.define_method("dispose", method!(Context::dispose, 0))?;
4541
5184
  context.define_method("disposed?", method!(Context::disposed, 0))?;
4542
5185
 
@@ -4544,6 +5187,7 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
4544
5187
  let script = module.define_class("Script", ruby.class_object())?;
4545
5188
  script.define_method("run", method!(Script::run, 0))?;
4546
5189
  script.define_method("run_void", method!(Script::run_void, 0))?;
5190
+ script.define_method("script_id", method!(Script::script_id, 0))?;
4547
5191
  script.define_method("cached_data", method!(Script::cached_data, 0))?;
4548
5192
  script.define_method("cache_rejected?", method!(Script::cache_rejected, 0))?;
4549
5193
  script.define_method("create_code_cache", method!(Script::create_code_cache, 0))?;
@@ -4551,6 +5195,16 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
4551
5195
  script.define_method("disposed?", method!(Script::disposed, 0))?;
4552
5196
 
4553
5197
  // A resolved function: Context#function -> #call / #call_void.
5198
+ let import = module.define_class("DynamicImport", ruby.class_object())?;
5199
+ import.define_method("specifier", method!(DynamicImport::specifier, 0))?;
5200
+ import.define_method("referrer", method!(DynamicImport::referrer, 0))?;
5201
+ import.define_method("attributes", method!(DynamicImport::attributes, 0))?;
5202
+ import.define_method("host_defined", method!(DynamicImport::host_defined, 0))?;
5203
+ import.define_method("context", method!(DynamicImport::context, 0))?;
5204
+ import.define_method("settled?", method!(DynamicImport::is_settled, 0))?;
5205
+ import.define_method("_resolve", method!(DynamicImport::resolve, 2))?;
5206
+ import.define_method("reject", method!(DynamicImport::reject, 1))?;
5207
+ import.define_method("reject_with", method!(DynamicImport::reject_with, -1))?;
4554
5208
  let function = module.define_class("Function", ruby.class_object())?;
4555
5209
  function.define_method("call", method!(JsFunction::call, -1))?;
4556
5210
  function.define_method("call_void", method!(JsFunction::call_void, -1))?;
@@ -4572,6 +5226,8 @@ pub fn install_classes(ruby: &Ruby) -> Result<(), Error> {
4572
5226
  jsmodule.define_method("namespace", method!(JsModule::namespace, 0))?;
4573
5227
  jsmodule.define_method("_status", method!(JsModule::status, 0))?;
4574
5228
  jsmodule.define_method("graph_async?", method!(JsModule::graph_async, 0))?;
5229
+ jsmodule.define_method("requests", method!(JsModule::requests, 0))?;
5230
+ jsmodule.define_method("script_id", method!(JsModule::script_id, 0))?;
4575
5231
  jsmodule.define_method("cached_data", method!(JsModule::cached_data, 0))?;
4576
5232
  jsmodule.define_method("cache_rejected?", method!(JsModule::cache_rejected, 0))?;
4577
5233
  jsmodule.define_method("create_code_cache", method!(JsModule::create_code_cache, 0))?;