deno_core 0.401.0

A modern JavaScript/TypeScript runtime built with V8, Rust, and Tokio
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// Copyright 2018-2026 the Deno authors. MIT license.

use std::cell::RefCell;
use std::iter::Chain;
use std::rc::Rc;

use crate::_ops::OpMethodDecl;
use crate::ExtensionFileSource;
use crate::FastString;
use crate::ModuleCodeString;
use crate::OpDecl;
use crate::OpMetricsFactoryFn;
use crate::OpState;
use crate::SourceMapData;
use crate::error::CoreError;
use crate::error::CoreErrorKind;
use crate::extensions::Extension;
use crate::extensions::ExtensionSourceType;
use crate::extensions::GlobalObjectMiddlewareFn;
use crate::extensions::GlobalTemplateMiddlewareFn;
use crate::extensions::OpMiddlewareFn;
use crate::modules::ModuleName;
use crate::ops::OpCtx;
use crate::runtime::ExtensionTranspiler;
use crate::runtime::JsRuntimeState;
use crate::runtime::OpDriverImpl;

/// Contribute to the `OpState` from each extension.
pub fn setup_op_state(
  op_state: &mut OpState,
  extensions: &mut [Extension],
) -> Vec<&'static str> {
  let mut lazy_extensions = Vec::with_capacity(extensions.len());
  for ext in extensions {
    if ext.needs_lazy_init {
      lazy_extensions.push(ext.name);
    }
    ext.take_state(op_state);
  }
  lazy_extensions
}

// TODO(bartlomieju): `deno_core_ext` ops should be returned as a separate
// vector - they need to be special cased and attached to `Deno.core.ops`,
// but not added to "ext:core/ops" virtual module.
/// Collects ops from extensions & applies middleware
pub fn init_ops(
  deno_core_ops: &'static [OpDecl],
  extensions: &mut [Extension],
) -> (Vec<OpDecl>, Vec<OpMethodDecl>) {
  // In debug build verify there that inter-Extension dependencies
  // are setup correctly.
  #[cfg(debug_assertions)]
  check_extensions_dependencies(extensions);

  let no_of_ops = extensions.iter().map(|e| e.op_count()).sum::<usize>();
  let mut ops = Vec::with_capacity(no_of_ops + deno_core_ops.len());

  let no_of_methods = extensions
    .iter()
    .map(|e| e.method_op_count())
    .sum::<usize>();
  let mut op_methods = Vec::with_capacity(no_of_methods);

  // Collect all middlewares - deno_core extension must not have a middleware!
  let middlewares: Vec<Box<OpMiddlewareFn>> = extensions
    .iter_mut()
    .filter_map(|e| e.take_middleware())
    .collect();

  // Create a single macroware out of all middleware functions.
  let macroware = move |d| middlewares.iter().fold(d, |d, m| m(d));

  // Collect ops from all extensions and apply a macroware to each of them.
  for core_op in deno_core_ops {
    ops.push(OpDecl {
      name: core_op.name,
      name_fast: core_op.name_fast,
      ..macroware(*core_op)
    });
  }

  for ext in extensions.iter_mut() {
    let ext_ops = ext.init_ops();
    for ext_op in ext_ops {
      ops.push(OpDecl {
        name: ext_op.name,
        name_fast: ext_op.name_fast,
        ..macroware(*ext_op)
      });
    }

    let ext_method_ops = ext.init_method_ops();
    for ext_op in ext_method_ops {
      op_methods.push(*ext_op);
    }
  }

  // In debug build verify there are no duplicate ops.
  #[cfg(debug_assertions)]
  check_no_duplicate_op_names(&ops);

  (ops, op_methods)
}

/// This functions panics if any of the extensions is missing its dependencies.
#[cfg(debug_assertions)]
fn check_extensions_dependencies(exts: &[Extension]) {
  for (index, ext) in exts.iter().enumerate() {
    let previous_exts = &exts[..index];
    ext.check_dependencies(previous_exts);
  }
}

/// This function panics if there are ops with duplicate names
#[cfg(debug_assertions)]
fn check_no_duplicate_op_names(ops: &[OpDecl]) {
  use std::collections::HashMap;

  let mut count_by_name = HashMap::new();

  for op in ops.iter() {
    count_by_name.entry(op.name).or_insert(vec![]).push(op.name);
  }

  let mut duplicate_ops = vec![];
  for (op_name, _count) in count_by_name.iter().filter(|(_k, v)| v.len() > 1) {
    duplicate_ops.push(op_name.to_string());
  }
  if !duplicate_ops.is_empty() {
    let mut msg = "Found ops with duplicate names:\n".to_string();
    for op_name in duplicate_ops {
      msg.push_str(&format!("  - {}\n", op_name));
    }
    msg.push_str("Op names need to be unique.");
    panic!("{}", msg);
  }
}

#[allow(clippy::too_many_arguments, reason = "all arguments are needed")]
pub fn create_op_ctxs(
  op_decls: Vec<OpDecl>,
  op_method_decls: &mut [OpMethodDecl],
  op_metrics_factory_fn: Option<OpMetricsFactoryFn>,
  op_driver: Rc<OpDriverImpl>,
  op_state: Rc<RefCell<OpState>>,
  runtime_state: Rc<JsRuntimeState>,
  enable_stack_trace_in_ops: bool,
) -> (Box<[OpCtx]>, usize) {
  let op_count = op_decls.len() + op_method_decls.len();
  let mut op_ctxs = Vec::with_capacity(op_count);

  let runtime_state_ptr = runtime_state.as_ref() as *const _;
  let create_ctx = |index, decl| {
    let metrics_fn = op_metrics_factory_fn
      .as_ref()
      .and_then(|f| (f)(index as _, op_count, &decl));

    OpCtx::new(
      index as _,
      v8::UnsafeRawIsolatePtr::null(),
      op_driver.clone(),
      decl,
      op_state.clone(),
      runtime_state_ptr,
      metrics_fn,
      enable_stack_trace_in_ops,
    )
  };

  for (index, decl) in op_method_decls.iter_mut().enumerate() {
    if let Some(mut constructor) = decl.constructor {
      constructor.name = decl.name.0;
      constructor.name_fast = decl.name.1;

      op_ctxs.push(create_ctx(index, constructor));
    }

    for method in decl.methods {
      op_ctxs.push(create_ctx(index, *method));
    }
    for method in decl.static_methods {
      op_ctxs.push(create_ctx(index, *method));
    }
  }

  /* method op ctxs are stored before regular op ctxs */
  let methods_ctx_offset = op_ctxs.len();

  for (index, decl) in op_decls.into_iter().enumerate() {
    op_ctxs.push(create_ctx(index + methods_ctx_offset, decl));
  }

  (op_ctxs.into_boxed_slice(), methods_ctx_offset)
}

pub fn get_middlewares_and_external_refs(
  extensions: &mut [Extension],
) -> (
  Vec<GlobalTemplateMiddlewareFn>,
  Vec<GlobalObjectMiddlewareFn>,
  Vec<v8::ExternalReference>,
) {
  // TODO(bartlomieju): these numbers were chosen arbitrarily. This is a very
  // niche features and it's unlikely a lot of extensions use it.
  let mut global_template_middlewares = Vec::with_capacity(16);
  let mut global_object_middlewares = Vec::with_capacity(16);
  let mut additional_references = Vec::with_capacity(16);

  for extension in extensions {
    if let Some(middleware) = extension.get_global_template_middleware() {
      global_template_middlewares.push(middleware);
    }
    if let Some(middleware) = extension.get_global_object_middleware() {
      global_object_middlewares.push(middleware);
    }
    additional_references
      .extend_from_slice(extension.get_external_references());
  }

  (
    global_template_middlewares,
    global_object_middlewares,
    additional_references,
  )
}

#[derive(Debug)]
pub struct LoadedSource {
  pub source_type: ExtensionSourceType,
  pub specifier: ModuleName,
  pub code: ModuleCodeString,
  pub maybe_source_map: Option<SourceMapData>,
}

#[derive(Debug, Default)]
pub struct LoadedSources {
  pub js: Vec<LoadedSource>,
  pub esm: Vec<LoadedSource>,
  pub lazy_esm: Vec<LoadedSource>,
  pub lazy_js: Vec<LoadedSource>,
  /// `(module_specifier, backing_script_specifier)` pairs collected from
  /// each extension's `synthetic_esm_modules`. Registered into the
  /// `ModuleMap` at runtime init so imports of `module_specifier` resolve
  /// to a synthetic ESM module derived from the IIFE exports of
  /// `backing_script_specifier`.
  pub synthetic_esm: Vec<(ModuleName, ModuleName)>,
  pub esm_entry_points: Vec<FastString>,
}

impl LoadedSources {
  pub fn len(&self) -> usize {
    self.js.len() + self.esm.len() + self.lazy_esm.len() + self.lazy_js.len()
  }

  pub fn is_empty(&self) -> bool {
    self.js.is_empty()
      && self.esm.is_empty()
      && self.lazy_esm.is_empty()
      && self.lazy_js.is_empty()
  }
}

type VecIntoIter<'a> = <&'a Vec<LoadedSource> as IntoIterator>::IntoIter;
type VecIntoIterMut<'a> = <&'a mut Vec<LoadedSource> as IntoIterator>::IntoIter;

impl<'a> IntoIterator for &'a LoadedSources {
  type Item = &'a LoadedSource;
  type IntoIter =
    Chain<Chain<VecIntoIter<'a>, VecIntoIter<'a>>, VecIntoIter<'a>>;
  fn into_iter(self) -> Self::IntoIter {
    self
      .js
      .iter()
      .chain(self.esm.iter())
      .chain(self.lazy_esm.iter())
  }
}

impl<'a> IntoIterator for &'a mut LoadedSources {
  type Item = &'a mut LoadedSource;
  type IntoIter =
    Chain<Chain<VecIntoIterMut<'a>, VecIntoIterMut<'a>>, VecIntoIterMut<'a>>;
  fn into_iter(self) -> Self::IntoIter {
    self
      .js
      .iter_mut()
      .chain(self.esm.iter_mut())
      .chain(self.lazy_esm.iter_mut())
  }
}

fn load(
  transpiler: Option<&ExtensionTranspiler>,
  source: &ExtensionFileSource,
  load_callback: &mut impl FnMut(&ExtensionFileSource),
) -> Result<(ModuleCodeString, Option<SourceMapData>), CoreError> {
  load_callback(source);
  let mut source_code = source.load()?;
  let mut source_map = None;
  if let Some(transpiler) = transpiler {
    (source_code, source_map) =
      transpiler(ModuleName::from_static(source.specifier), source_code)
        .map_err(CoreErrorKind::ExtensionTranspiler)?;
  }
  let mut maybe_source_map = None;
  if let Some(source_map) = source_map {
    maybe_source_map = Some(source_map);
  }
  Ok((source_code, maybe_source_map))
}

pub fn into_sources_and_source_maps(
  transpiler: Option<&ExtensionTranspiler>,
  extensions: &[Extension],
  extensions_in_snapshot: Option<&[&'static str]>,
  mut load_callback: impl FnMut(&ExtensionFileSource),
) -> Result<LoadedSources, CoreError> {
  let mut sources = LoadedSources::default();

  let extensions_in_snapshot = extensions_in_snapshot
    .unwrap_or_default()
    .iter()
    .map(Some)
    .chain(std::iter::repeat(None));

  for (extension, extension_in_snapshot) in
    extensions.iter().zip(extensions_in_snapshot)
  {
    let snapshotted = if let Some(name) = extension_in_snapshot {
      if extension.name != *name {
        return Err(
          CoreErrorKind::ExtensionSnapshotMismatch(
            crate::error::ExtensionSnapshotMismatchError {
              expected: name,
              actual: extension.name,
            },
          )
          .into_box(),
        );
      }
      true
    } else {
      false
    };

    // `lazy_loaded_*` files always need a runtime registration so
    // `core.loadExtScript()` / lazy ESM imports can find them. For extensions
    // baked into the snapshot, skip entries whose source isn't reachable at
    // runtime (`LoadedFromFsDuringSnapshot` paths only exist on the build
    // machine) — those are supplied via the snapshot build's residual table.
    // For extensions not in the snapshot (hmr / fresh runtime), load every
    // declared file from disk, matching pre-refactor behavior.
    for file in &*extension.lazy_loaded_esm_files {
      if snapshotted && !file.is_runtime_loadable() {
        continue;
      }
      let (code, maybe_source_map) =
        load(transpiler, file, &mut load_callback)?;
      sources.lazy_esm.push(LoadedSource {
        source_type: ExtensionSourceType::LazyEsm,
        specifier: ModuleName::from_static(file.specifier),
        code,
        maybe_source_map,
      });
    }

    for file in &*extension.lazy_loaded_js_files {
      if snapshotted && !file.is_runtime_loadable() {
        continue;
      }
      let (code, maybe_source_map) =
        load(transpiler, file, &mut load_callback)?;
      sources.lazy_js.push(LoadedSource {
        source_type: ExtensionSourceType::LazyJs,
        specifier: ModuleName::from_static(file.specifier),
        code,
        maybe_source_map,
      });
    }

    for (module_spec, backing_spec) in &*extension.synthetic_esm_modules {
      sources.synthetic_esm.push((
        ModuleName::from_static(module_spec),
        ModuleName::from_static(backing_spec),
      ));
    }

    if snapshotted {
      // `js`/`esm` files are already evaluated in the snapshot — no need to
      // re-execute them at runtime.
      continue;
    }

    if let Some(esm_entry_point) = extension.esm_entry_point {
      sources
        .esm_entry_points
        .push(FastString::from_static(esm_entry_point));
    }
    for file in &*extension.js_files {
      let (code, maybe_source_map) =
        load(transpiler, file, &mut load_callback)?;
      sources.js.push(LoadedSource {
        source_type: ExtensionSourceType::Js,
        specifier: ModuleName::from_static(file.specifier),
        code,
        maybe_source_map,
      });
    }
    for file in &*extension.esm_files {
      let (code, maybe_source_map) =
        load(transpiler, file, &mut load_callback)?;
      sources.esm.push(LoadedSource {
        source_type: ExtensionSourceType::Esm,
        specifier: ModuleName::from_static(file.specifier),
        code,
        maybe_source_map,
      });
    }
  }
  Ok(sources)
}