rspack_core/
runtime_module.rs

1use std::fmt::Debug;
2
3use async_trait::async_trait;
4use rspack_cacheable::cacheable;
5use rspack_collections::Identifier;
6
7use crate::{ChunkUkey, Compilation, Module};
8
9#[async_trait]
10pub trait RuntimeModule: Module + CustomSourceRuntimeModule {
11  fn name(&self) -> Identifier;
12  fn attach(&mut self, _chunk: ChunkUkey) {}
13  fn stage(&self) -> RuntimeModuleStage {
14    RuntimeModuleStage::Normal
15  }
16  fn full_hash(&self) -> bool {
17    false
18  }
19  fn dependent_hash(&self) -> bool {
20    false
21  }
22  // if wrap iife
23  fn should_isolate(&self) -> bool {
24    true
25  }
26  fn template(&self) -> Vec<(String, String)> {
27    vec![]
28  }
29  async fn generate(&self, compilation: &Compilation) -> rspack_error::Result<String>;
30  async fn generate_with_custom(&self, compilation: &Compilation) -> rspack_error::Result<String> {
31    if let Some(custom_source) = self.get_custom_source() {
32      Ok(custom_source)
33    } else {
34      self.generate(compilation).await
35    }
36  }
37}
38
39#[async_trait]
40pub trait CustomSourceRuntimeModule {
41  fn set_custom_source(&mut self, source: String);
42  fn get_custom_source(&self) -> Option<String>;
43  fn get_constructor_name(&self) -> String;
44}
45
46pub type BoxRuntimeModule = Box<dyn RuntimeModule>;
47
48#[cacheable]
49#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub enum RuntimeModuleStage {
51  Normal,  // Runtime modules without any dependencies to other runtime modules
52  Basic,   // Runtime modules with simple dependencies on other runtime modules
53  Attach,  // Runtime modules which attach to handlers of other runtime modules
54  Trigger, // Runtime modules which trigger actions on bootstrap
55}
56
57impl Default for RuntimeModuleStage {
58  fn default() -> Self {
59    Self::Normal
60  }
61}
62
63impl From<u32> for RuntimeModuleStage {
64  fn from(stage: u32) -> Self {
65    match stage {
66      0 => RuntimeModuleStage::Normal,
67      5 => RuntimeModuleStage::Basic,
68      10 => RuntimeModuleStage::Attach,
69      20 => RuntimeModuleStage::Trigger,
70      _ => RuntimeModuleStage::Normal,
71    }
72  }
73}
74
75pub trait RuntimeModuleExt {
76  fn boxed(self) -> Box<dyn RuntimeModule>;
77}
78
79impl<T: RuntimeModule + 'static> RuntimeModuleExt for T {
80  fn boxed(self) -> Box<dyn RuntimeModule> {
81    Box::new(self)
82  }
83}