piu_core 0.412.1

A modern JavaScript/TypeScript runtime built with V8, Rust, and Tokio
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
// Copyright 2018-2026 the Deno authors. MIT license.

use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::rc::Rc;

use super::RequestedModuleType;
use crate::ModuleCodeString;
use crate::ModuleSource;
use crate::fast_string::FastString;
use crate::modules::ModuleId;
use crate::modules::ModuleInfo;
use crate::modules::ModuleLoadId;
use crate::modules::ModuleName;
use crate::modules::ModuleReference;
use crate::modules::ModuleRequest;
use crate::modules::ModuleType;

/// A symbolic module entity.
#[derive(Debug, PartialEq)]
pub(crate) enum SymbolicModule {
  /// This module is an alias to another module.
  /// This is useful such that multiple names could point to
  /// the same underlying module (particularly due to redirects).
  Alias(ModuleName),
  /// This module associates with a V8 module by id.
  Mod(ModuleId),
}

/// Map of [`ModuleName`] and [`RequestedModuleType`] to a data field.
struct ModuleNameTypeMap<T> {
  submaps: Vec<HashMap<ModuleName, T>>,
  map_index: HashMap<RequestedModuleType, usize>,
  len: usize,
}

impl<T> Default for ModuleNameTypeMap<T> {
  fn default() -> Self {
    Self {
      submaps: Default::default(),
      map_index: Default::default(),
      len: 0,
    }
  }
}

impl<T> ModuleNameTypeMap<T> {
  pub fn len(&self) -> usize {
    self.len
  }

  fn map_index(&self, ty: &RequestedModuleType) -> Option<usize> {
    self.map_index.get(ty).copied()
  }

  pub fn get<Q>(&self, ty: &RequestedModuleType, name: &Q) -> Option<&T>
  where
    ModuleName: std::borrow::Borrow<Q>,
    Q: std::cmp::Eq + std::hash::Hash + std::fmt::Debug + ?Sized,
  {
    let index = self.map_index(ty)?;
    let map = self.submaps.get(index)?;
    map.get(name)
  }

  pub fn insert(
    &mut self,
    module_type: &RequestedModuleType,
    name: FastString,
    module: T,
  ) {
    let index = match self.map_index(module_type) {
      Some(index) => index,
      None => {
        let index = self.submaps.len();
        self.map_index.insert(module_type.clone(), index);
        self.submaps.push(Default::default());
        index
      }
    };

    if self
      .submaps
      .get_mut(index)
      .unwrap()
      .insert(name, module)
      .is_none()
    {
      self.len += 1;
    }
  }

  /// Rather than providing an iterator, we provide a drain method. This is mainly because Rust
  /// doesn't have generators.
  pub fn drain(
    mut self,
    mut f: impl FnMut(usize, &RequestedModuleType, ModuleName, T),
  ) {
    let mut i = 0;
    for (ty, value) in self.map_index.into_iter() {
      for (key, value) in self.submaps.get_mut(value).unwrap().drain() {
        f(i, &ty, key, value);
        i += 1;
      }
    }
  }
}

/// An array of tuples that provide module exports.
///
/// "default" name will make the export "default" - ie. one that can be imported
/// with `import foo from "./virtual.js"`;.
/// All other name provide "named exports" - ie. ones that can be imported like
/// so: `import { name1, name2 } from "./virtual.js`.
pub(crate) type SyntheticModuleExports =
  Vec<(v8::Global<v8::String>, v8::Global<v8::Value>)>;

// TODO(bartlomieju): add an assertion that checks for that assumption?
// If it's true we can simplify the type to be an `Option` instead of a `HashMap`.
/// This hash map is not expected to hold more than one element at a time.
/// It is a temporary store, so we can forward data to
/// `synthetic_module_evaluation_steps` callback.
pub(crate) type SyntheticModuleExportsStore =
  HashMap<v8::Global<v8::Module>, SyntheticModuleExports>;

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) enum ModuleSourceKind {
  Wasm,
}

impl ModuleSourceKind {
  pub fn from_module_type(module_type: &ModuleType) -> Option<Self> {
    match module_type {
      ModuleType::Wasm => Some(Self::Wasm),
      _ => None,
    }
  }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
enum ModuleSourceType {
  Loaded(ModuleType),
  Requested(RequestedModuleType),
}

#[derive(Debug, Eq, PartialEq, Hash)]
pub(crate) struct ModuleSourceKey {
  pub name: ModuleName,
  typ: ModuleSourceType,
}

impl ModuleSourceKey {
  pub fn from_reference(module_reference: &ModuleReference) -> Self {
    Self {
      name: module_reference.specifier.to_string().into(),
      typ: ModuleSourceType::Requested(
        module_reference.requested_module_type.clone(),
      ),
    }
  }

  pub fn from_loaded_source(loaded_source: &mut ModuleSource) -> Self {
    let name = if let Some(module_url_found) =
      loaded_source.cheap_copy_module_url_found()
    {
      module_url_found
    } else {
      loaded_source.cheap_copy_module_url_specified()
    };
    Self {
      name,
      typ: ModuleSourceType::Loaded(loaded_source.module_type.clone()),
    }
  }
}

#[derive(Default)]
pub(crate) struct ModuleMapData {
  /// Inverted index from module to index in `info`.
  pub(crate) handles_inverted: HashMap<v8::Global<v8::Module>, usize>,
  /// The handles we have loaded so far, corresponding with the [`ModuleInfo`] in `info`.
  pub(crate) handles: Vec<v8::Global<v8::Module>>,
  pub(crate) main_module_callbacks: Vec<v8::Global<v8::Function>>,
  /// The modules we have loaded so far.
  pub(crate) info: Vec<ModuleInfo>,
  /// [`ModuleName`] to [`SymbolicModule`] for modules.
  by_name: ModuleNameTypeMap<SymbolicModule>,
  /// The next ID used for a load.
  pub(crate) next_load_id: ModuleLoadId,
  /// If a main module has been loaded, points to it by index.
  pub(crate) main_module_id: Option<ModuleId>,
  /// This store is used to temporarily store data that is used
  /// to evaluate a "synthetic module".
  pub(crate) synthetic_module_exports_store: SyntheticModuleExportsStore,
  pub(crate) lazy_esm_sources:
    Rc<RefCell<HashMap<ModuleName, ModuleCodeString>>>,
  /// Specifiers of lazy-loaded ESM modules known to exist. Used to check if
  /// a module should be loaded from `lazy_esm_sources` without going through
  /// the external module loader.
  pub(crate) known_lazy_esm: RefCell<HashSet<Cow<'static, str>>>,
  pub(crate) lazy_script_sources:
    Rc<RefCell<HashMap<ModuleName, ModuleCodeString>>>,
  /// Results of `load_ext_script` evaluations. Populated on first
  /// evaluation so later callers (`Deno.core.loadExtScript()` from JS,
  /// the `synthetic_esm` dispatch from Rust) share a single evaluated
  /// exports value — the source is removed from `lazy_script_sources`
  /// on first eval, so subsequent reads come from here. Runtime-only —
  /// not snapshotted.
  pub(crate) loaded_script_results:
    Rc<RefCell<HashMap<ModuleName, v8::Global<v8::Value>>>>,
  /// `synthetic_esm` registry: module specifier (e.g. `node:worker_threads`)
  /// to backing-script specifier (e.g. `ext:deno_node/worker_threads.ts`).
  /// Populated at extension init from each extension's
  /// `synthetic_esm_files` list. Runtime-only — not snapshotted.
  pub(crate) synthetic_esm_modules:
    Rc<RefCell<HashMap<ModuleName, ModuleName>>>,
  /// Set of scripts currently being loaded (for circular dep detection).
  pub(crate) lazy_script_loading: Rc<RefCell<HashSet<ModuleName>>>,
  /// Snapshot-time `__bootstrap` view (frozen clone of `core.ops` etc.)
  /// registered from JS via `op_set_captured_bootstrap`. `load_ext_script`
  /// temporarily installs this on `globalThis.__bootstrap` for the duration
  /// of each script evaluation if `__bootstrap` isn't already on the global
  /// — every lazy_loaded_js polyfill's IIFE preamble destructures it, and
  /// the `synthetic_esm` dispatch goes straight through Rust without the
  /// JS `core.loadExtScript` wrapper. Runtime-only — not snapshotted.
  pub(crate) captured_bootstrap: RefCell<Option<v8::Global<v8::Value>>>,
  pub(crate) sources: HashMap<ModuleSourceKey, v8::Global<v8::Object>>,
  /// Import edges dropped by `ModuleMap::drop_instantiated_requests`, kept
  /// only in test builds so tests can still assert on what was parsed out of
  /// the module source.
  #[cfg(test)]
  pub(crate) dropped_requests: HashMap<ModuleId, Vec<ModuleRequest>>,
  /// Specifiers of `lazy_loaded_esm` / `lazy_loaded_js` files whose source
  /// was actually compiled by V8 during snapshot creation. Their bytes live
  /// in the snapshot blob; the binary does not need a separate copy.
  pub(crate) consumed_lazy_specifiers: RefCell<HashSet<String>>,
}

impl ModuleMapData {
  pub fn create_module_info(
    &mut self,
    name: FastString,
    module_type: ModuleType,
    handle: v8::Global<v8::Module>,
    main: bool,
    requests: Vec<ModuleRequest>,
  ) -> ModuleId {
    let data = self;
    let id = data.handles.len();
    let is_internal =
      crate::modules::map::is_internal_module_specifier(name.as_str());
    // If this module came from a `lazy_loaded_esm` source, V8 has now compiled
    // it and the module is reachable by name, so our heap copy of the source
    // text is dead weight — drop it. `known_lazy_esm` still records that the
    // specifier exists, and every remaining reader of `lazy_esm_sources`
    // checks `get_id` first (`ModuleMap::resolve_callback`,
    // `lazy_load_esm_module`) or falls back to the already-registered module
    // (`RecursiveModuleLoad`).
    {
      let mut sources = data.lazy_esm_sources.borrow_mut();
      if !sources.is_empty() {
        sources.remove(name.as_str());
      }
    }
    let (name1, name2) = name.into_cheap_copy();
    data.handles_inverted.insert(handle.clone(), id);
    data.handles.push(handle);
    if main {
      data.main_module_id = Some(id);
    }
    // TODO(bartlomieju): verify if we can store `ModuleType` here instead
    let requested_module_type = RequestedModuleType::from(module_type.clone());
    data
      .by_name
      .insert(&requested_module_type, name1, SymbolicModule::Mod(id));
    data.info.push(ModuleInfo {
      id,
      main,
      name: name2,
      requests,
      module_type,
      is_internal,
    });

    id
  }

  /// Get module id, following all aliases in case of module specifier
  /// that had been redirected.
  pub fn get_id(
    &self,
    name: &str,
    requested_module_type: impl AsRef<RequestedModuleType>,
  ) -> Option<ModuleId> {
    let map = &self.by_name;
    let first_symbolic_module =
      map.get(requested_module_type.as_ref(), name)?;
    let mut mod_name = match first_symbolic_module {
      SymbolicModule::Mod(mod_id) => return Some(*mod_id),
      SymbolicModule::Alias(target) => target,
    };
    loop {
      let symbolic_module =
        map.get(requested_module_type.as_ref(), mod_name)?;
      match symbolic_module {
        SymbolicModule::Alias(target) => {
          debug_assert!(mod_name != target);
          mod_name = target;
        }
        SymbolicModule::Mod(mod_id) => return Some(*mod_id),
      }
    }
  }

  pub(crate) fn alias(
    &mut self,
    name: FastString,
    requested_module_type: &RequestedModuleType,
    target: FastString,
  ) {
    debug_assert_ne!(name, target);
    self.by_name.insert(
      requested_module_type,
      name,
      SymbolicModule::Alias(target),
    );
  }

  /// Register an additional `(name, requested_module_type) -> module_id`
  /// mapping for a module that was already registered under a different
  /// requested module type. Used to make modules visible to imports whose
  /// `with { type: ... }` attribute doesn't match the loaded module's
  /// actual type — for example when a `module.registerHooks()` load hook
  /// returns `format: "module"` for an import with a custom type
  /// attribute like `with { type: "x-css" }`.
  pub(crate) fn register_under_type(
    &mut self,
    name: FastString,
    requested_module_type: &RequestedModuleType,
    module_id: ModuleId,
  ) {
    self.by_name.insert(
      requested_module_type,
      name,
      SymbolicModule::Mod(module_id),
    );
  }

  #[cfg(test)]
  pub(crate) fn is_alias(
    &self,
    name: &str,
    requested_module_type: impl AsRef<RequestedModuleType>,
  ) -> bool {
    let map = &self.by_name;
    let entry = map.get(requested_module_type.as_ref(), name);
    matches!(entry, Some(SymbolicModule::Alias(_)))
  }

  pub(crate) fn get_handle(
    &self,
    id: ModuleId,
  ) -> Option<v8::Global<v8::Module>> {
    self.handles.get(id).cloned()
  }

  pub(crate) fn get_name_by_module(
    &self,
    global: &v8::Global<v8::Module>,
  ) -> Option<String> {
    match self.handles_inverted.get(global) {
      Some(id) => self.get_name_by_id(*id),
      _ => None,
    }
  }

  pub(crate) fn get_type_by_module(
    &self,
    global: &v8::Global<v8::Module>,
  ) -> Option<ModuleType> {
    match self.handles_inverted.get(global) {
      Some(id) => {
        let info = self.info.get(*id).unwrap();
        Some(info.module_type.clone())
      }
      _ => None,
    }
  }

  pub(crate) fn get_info_by_module(
    &self,
    global: &v8::Global<v8::Module>,
  ) -> Option<&ModuleInfo> {
    match self.handles_inverted.get(global) {
      Some(id) => Some(self.info.get(*id).unwrap()),
      _ => None,
    }
  }

  pub(crate) fn is_main_module(&self, global: &v8::Global<v8::Module>) -> bool {
    self
      .main_module_id
      .map(|id| self.handles_inverted.get(global) == Some(&id))
      .unwrap_or_default()
  }

  pub(crate) fn get_name_by_id(&self, id: ModuleId) -> Option<String> {
    // TODO(mmastrac): Don't clone
    self.info.get(id).map(|info| info.name.as_str().to_owned())
  }

  // TODO(mmastrac): this is better than giving the entire crate access to the internals.
  #[cfg(test)]
  pub fn assert_module_map(
    &self,
    modules: &Vec<ModuleInfo>,
    restored_from_snapshot: usize,
  ) {
    use crate::runtime::NO_OF_BUILTIN_MODULES;
    let data = self;
    assert_eq!(data.handles.len(), modules.len() + NO_OF_BUILTIN_MODULES);
    assert_eq!(data.info.len(), modules.len() + NO_OF_BUILTIN_MODULES);
    assert_eq!(data.next_load_id as usize, modules.len());
    assert_eq!(data.by_name.len(), modules.len() + NO_OF_BUILTIN_MODULES);

    for info in modules {
      assert!(data.handles.get(info.id).is_some());
      let actual = data.info.get(info.id).unwrap();
      assert_eq!(actual.id, info.id);
      assert_eq!(actual.main, info.main);
      assert_eq!(actual.name, info.name);
      assert_eq!(actual.module_type, info.module_type);
      assert_eq!(actual.is_internal, info.is_internal);
      if info.id < restored_from_snapshot {
        assert!(
          actual.requests.is_empty(),
          "import edges of snapshot-instantiated module {} should be dropped",
          info.name
        );
      } else {
        // Instantiation drops the live edges (see
        // `ModuleMap::drop_instantiated_requests`), which stashes them here
        // for tests.
        let actual_requests = if actual.requests.is_empty() {
          self
            .dropped_requests
            .get(&info.id)
            .map(|r| r.as_slice())
            .unwrap_or_default()
        } else {
          actual.requests.as_slice()
        };
        assert_eq!(actual_requests, info.requests.as_slice());
      }
      let requested_module_type =
        RequestedModuleType::from(info.module_type.clone());
      assert_eq!(
        data.by_name.get(&requested_module_type, &info.name),
        Some(&SymbolicModule::Mod(info.id))
      );
    }
  }
}

#[cfg(test)]
mod tests {
  use url::Url;

  use super::*;
  use crate::ascii_str;

  #[test]
  fn module_name_map_test() {
    let mut data: ModuleNameTypeMap<usize> = ModuleNameTypeMap::default();
    data.insert(
      &RequestedModuleType::Json,
      ascii_str!("http://example.com/").into(),
      1,
    );
    assert_eq!(
      Some(&1),
      data.get(
        &RequestedModuleType::Json,
        Url::parse("http://example.com/").unwrap().as_str()
      )
    );
  }
}