rspack_core 0.100.1

rspack core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
use std::{
  any::Any,
  borrow::Cow,
  fmt::{Debug, Display, Formatter},
  hash::Hash,
  sync::Arc,
};

use async_trait::async_trait;
use json::JsonValue;
use rspack_cacheable::{
  cacheable, cacheable_dyn,
  with::{AsCacheable, AsInner, AsInnerConverter, AsMap, AsOption, AsPreset, AsVec},
};
use rspack_collections::{Identifiable, Identifier, IdentifierMap, IdentifierSet};
use rspack_error::{Diagnosable, Result};
use rspack_fs::ReadableFileSystem;
use rspack_hash::RspackHashDigest;
use rspack_paths::ArcPathSet;
use rspack_sources::BoxSource;
use rspack_util::{
  atom::Atom,
  ext::{AsAny, DynHash},
  fx_hash::{FxIndexMap, FxIndexSet},
  source_map::ModuleSourceMapConfig,
};
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use serde::Serialize;
use swc_core::atoms::Wtf8Atom;

use crate::{
  AsyncDependenciesBlock, BindingCell, BoxDependency, BoxDependencyTemplate, BoxModuleDependency,
  ChunkGraph, ChunkUkey, CodeGenerationResult, CollectedTypeScriptInfo, Compilation,
  CompilationAsset, CompilationId, CompilerId, CompilerOptions, ConcatenationScope,
  ConnectionState, Context, ContextModule, DependenciesBlock, DependencyId, ExportProvided,
  ExportsInfoArtifact, ExternalModule, GetTargetResult, ModuleCodeTemplate, ModuleGraph,
  ModuleGraphCacheArtifact, ModuleLayer, ModuleType, NormalModule, OptimizationBailoutItem,
  RawModule, Resolve, ResolverFactory, RuntimeSpec, SelfModule, SharedPluginDriver,
  SideEffectsStateArtifact, SourceType, concatenated_module::ConcatenatedModule,
  dependencies_block::dependencies_block_update_hash, get_target,
  value_cache_versions::ValueCacheVersions,
};

pub struct BuildContext {
  pub compiler_id: CompilerId,
  pub compilation_id: CompilationId,
  pub compiler_options: Arc<CompilerOptions>,
  pub resolver_factory: Arc<ResolverFactory>,
  pub runtime_template: ModuleCodeTemplate,
  pub plugin_driver: SharedPluginDriver,
  pub fs: Arc<dyn ReadableFileSystem>,
}

#[cacheable]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RscModuleType {
  /// Represents a server entry module with "use server-entry" directive.
  ///
  /// Transformation flow:
  /// 1. Original module with "use server-entry" is transformed into a proxy module
  /// 2. The proxy module (with `module_type = ServerEntry`) imports the original implementation
  /// 3. The original implementation module may resulting in `module_type = Client`
  ///
  /// Note: "use server" and "use client" directives can coexist in the same file.
  ServerEntry,
  Server,
  Client,
}

#[cacheable]
#[derive(Debug, Clone)]
pub struct RscMeta {
  pub module_type: RscModuleType,

  #[cacheable(with=AsVec<AsPreset>)]
  pub server_refs: Vec<Wtf8Atom>,

  #[cacheable(with=AsVec<AsPreset>)]
  pub client_refs: Vec<Wtf8Atom>,
  pub is_cjs: bool,

  #[cacheable(with=AsMap<AsPreset, AsPreset>)]
  pub action_ids: FxIndexMap<Atom, Atom>,
}

#[cacheable]
#[derive(Debug, Clone)]
pub enum CanonicalizedDataUrlOption {
  Source,
  Bytes,
  Asset(bool),
}

impl CanonicalizedDataUrlOption {
  pub fn is_source(&self) -> bool {
    matches!(self, Self::Source)
  }

  pub fn is_bytes(&self) -> bool {
    matches!(self, Self::Bytes)
  }

  pub fn is_inline(&self) -> bool {
    matches!(self, Self::Asset(true))
  }

  pub fn is_resource(&self) -> bool {
    matches!(self, Self::Asset(false))
  }
}

#[cacheable]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CssExport {
  pub ident: String,
  pub from: Option<String>,
  pub id: Option<DependencyId>,
  pub orig_name: String,
}

pub type CssExports = FxIndexMap<String, FxIndexSet<CssExport>>;

#[cacheable]
#[derive(Debug, Clone)]
pub struct BuildInfo {
  /// Whether the result is cacheable, i.e shared between builds.
  pub cacheable: bool,
  pub hash: Option<RspackHashDigest>,
  pub strict: bool,
  pub module_argument: ModuleArgument,
  pub exports_argument: ExportsArgument,
  pub file_dependencies: ArcPathSet,
  pub context_dependencies: ArcPathSet,
  pub missing_dependencies: ArcPathSet,
  pub build_dependencies: ArcPathSet,
  pub value_dependencies: HashMap<String, String>,
  #[cacheable(with=AsVec<AsPreset>)]
  pub esm_named_exports: HashSet<Atom>,
  pub all_star_exports: Vec<DependencyId>,
  pub need_create_require: bool,
  #[cacheable(with=AsOption<AsPreset>)]
  pub json_data: Option<JsonValue>,
  pub asset_data_url: Option<CanonicalizedDataUrlOption>,
  #[cacheable(with=AsOption<AsMap<AsCacheable, AsVec>>)]
  pub css_exports: Option<CssExports>,
  pub css_local_names: Option<HashMap<String, String>>,
  #[cacheable(with=AsOption<AsVec<AsPreset>>)]
  pub side_effects_free: Option<HashSet<Atom>>,
  #[cacheable(with=AsOption<AsVec<AsPreset>>)]
  pub top_level_declarations: Option<HashSet<Atom>>,
  pub module_concatenation_bailout: Option<String>,
  pub assets: BindingCell<HashMap<String, CompilationAsset>>,
  pub module: bool,
  pub inline_exports: bool,
  pub collected_typescript_info: Option<CollectedTypeScriptInfo>,
  pub rsc: Option<RscMeta>,
  /// Stores external fields from the JS side (Record<string, any>),
  /// while other properties are stored in KnownBuildInfo.
  #[cacheable(with=AsPreset)]
  pub extras: serde_json::Map<String, serde_json::Value>,
  #[cacheable(with=AsVec)]
  pub deferred_pure_checks: HashSet<DeferredPureCheck>,
}

impl Default for BuildInfo {
  fn default() -> Self {
    Self {
      cacheable: true,
      hash: None,
      strict: false,
      module_argument: Default::default(),
      exports_argument: Default::default(),
      file_dependencies: ArcPathSet::default(),
      context_dependencies: ArcPathSet::default(),
      missing_dependencies: ArcPathSet::default(),
      build_dependencies: ArcPathSet::default(),
      value_dependencies: HashMap::default(),
      esm_named_exports: HashSet::default(),
      all_star_exports: Vec::default(),
      need_create_require: false,
      json_data: None,
      asset_data_url: None,
      css_exports: None,
      css_local_names: None,
      side_effects_free: None,
      top_level_declarations: None,
      module_concatenation_bailout: None,
      assets: Default::default(),
      module: false,
      inline_exports: false,
      collected_typescript_info: None,
      rsc: None,
      extras: Default::default(),
      deferred_pure_checks: HashSet::default(),
    }
  }
}

#[cacheable]
#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BuildMetaExportsType {
  #[default]
  Unset,
  Default,
  Namespace,
  Flagged,
  Dynamic,
}

impl Display for BuildMetaExportsType {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    let d = match self {
      BuildMetaExportsType::Unset => "unknown exports (runtime-defined)",
      BuildMetaExportsType::Default => "default exports",
      BuildMetaExportsType::Namespace => "namespace exports",
      BuildMetaExportsType::Flagged => "flagged exports",
      BuildMetaExportsType::Dynamic => "dynamic exports",
    };

    f.write_str(d)
  }
}

#[derive(Debug, Clone, Copy, Hash)]
pub enum ExportsType {
  DefaultOnly,
  Namespace,
  DefaultWithNamed,
  Dynamic,
}

#[cacheable]
#[derive(Debug, Default, Clone, Copy, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BuildMetaDefaultObject {
  #[default]
  False,
  Redirect,
  RedirectWarn,
}

#[cacheable]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DeferredPureCheck {
  #[cacheable(with=AsPreset)]
  pub atom: Atom,
  pub dep_id: DependencyId,
  pub start: u32,
  pub end: u32,
}

#[cacheable]
#[derive(Debug, Default, Clone, Copy, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ModuleArgument {
  #[default]
  Module,
  RspackModule,
}

#[cacheable]
#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ExportsArgument {
  #[default]
  Exports,
  RspackExports,
}

#[cacheable]
#[derive(Debug, Default, Clone, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildMeta {
  pub strict_esm_module: bool,
  // same as is_async https://github.com/webpack/webpack/blob/3919c844eca394d73ca930e4fc5506fb86e2b094/lib/Module.js#L107
  pub has_top_level_await: bool,
  pub esm: bool,
  pub exports_type: BuildMetaExportsType,
  pub default_object: BuildMetaDefaultObject,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub side_effect_free: Option<bool>,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub exports_final_name: Option<Vec<(String, String)>>,
}

// webpack build info
#[derive(Debug)]
pub struct BuildResult {
  pub module: BoxModule,
  /// Whether the result is cacheable, i.e shared between builds.
  pub dependencies: Vec<BoxDependency>,
  pub blocks: Vec<Box<AsyncDependenciesBlock>>,
  pub optimization_bailouts: Vec<OptimizationBailoutItem>,
}

#[cacheable]
#[derive(Debug, Default, Clone)]
pub struct FactoryMeta {
  pub side_effect_free: Option<bool>,
}

pub type ModuleIdentifier = Identifier;
pub type ResourceIdentifier = Identifier;

#[derive(Debug)]
pub struct ModuleCodeGenerationContext<'a> {
  pub compilation: &'a Compilation,
  pub runtime: Option<&'a RuntimeSpec>,
  pub concatenation_scope: Option<ConcatenationScope>,
  pub runtime_template: &'a mut ModuleCodeTemplate,
}

#[cacheable_dyn]
#[async_trait]
pub trait Module:
  Debug
  + Send
  + Sync
  + Any
  + AsAny
  + Identifiable
  + DependenciesBlock
  + Diagnosable
  + ModuleSourceMapConfig
{
  /// Defines what kind of module this is.
  fn module_type(&self) -> &ModuleType;

  /// Defines what kind of code generation results this module can generate.
  fn source_types(&self, module_graph: &ModuleGraph) -> &[SourceType];

  /// The source of the module. This could be optional, modules like the `NormalModule` can have the corresponding source.
  /// However, modules that is created from "nowhere" (e.g. `ExternalModule` and `MissingModule`) does not have its source.
  fn source(&self) -> Option<&BoxSource>;

  /// User readable identifier of the module.
  fn readable_identifier(&self, _context: &Context) -> Cow<'_, str>;

  /// The size of the original source, which will used as a parameter for code-splitting.
  /// Only when calculating the size of the RuntimeModule is the Compilation depended on
  fn size(&self, source_type: Option<&SourceType>, compilation: Option<&Compilation>) -> f64;

  /// The actual build of the module, which will be called by the `Compilation`.
  /// Build can also returns the dependencies of the module, which will be used by the `Compilation` to build the dependency graph.
  async fn build(
    self: Box<Self>,
    _build_context: BuildContext,
    _compilation: Option<&Compilation>,
  ) -> Result<BuildResult>;

  fn factory_meta(&self) -> Option<&FactoryMeta>;

  fn set_factory_meta(&mut self, factory_meta: FactoryMeta);

  fn build_info(&self) -> &BuildInfo;

  fn build_info_mut(&mut self) -> &mut BuildInfo;

  fn build_meta(&self) -> &BuildMeta;

  fn build_meta_mut(&mut self) -> &mut BuildMeta;

  fn get_exports_argument(&self) -> ExportsArgument {
    self.build_info().exports_argument
  }

  fn get_module_argument(&self) -> ModuleArgument {
    self.build_info().module_argument
  }

  fn get_exports_type(
    &self,
    module_graph: &ModuleGraph,
    module_graph_cache: &ModuleGraphCacheArtifact,
    exports_info_artifact: &ExportsInfoArtifact,
    strict: bool,
  ) -> ExportsType {
    module_graph_cache.cached_get_exports_type((self.identifier(), strict), || {
      get_exports_type_impl(
        self.identifier(),
        self.build_meta(),
        module_graph,
        exports_info_artifact,
        strict,
      )
    })
  }

  fn get_strict_esm_module(&self) -> bool {
    self.build_meta().strict_esm_module
  }

  /// The actual code generation of the module, which will be called by the `Compilation`.
  /// The code generation result should not be cached as it is implemented elsewhere to
  /// provide a universal cache mechanism (time to invalidate cache, etc.)
  ///
  /// Code generation will often iterate through every `source_types` given by the module
  /// to provide multiple code generation results for different `source_type`s.
  async fn code_generation(
    &self,
    _code_generation_context: &mut ModuleCodeGenerationContext,
  ) -> Result<CodeGenerationResult>;

  /// Name matched against bundle-splitting conditions.
  fn name_for_condition(&self) -> Option<Box<str>> {
    // Align with https://github.com/webpack/webpack/blob/8241da7f1e75c5581ba535d127fa66aeb9eb2ac8/lib/Module.js#L852
    None
  }

  /// Update hash for cgm.hash (chunk graph module hash)
  /// Different cgm code generation result should have different cgm.hash,
  /// so this also accept compilation (mainly chunk graph) and runtime as args.
  /// (Difference with `impl Hash for Module`: this is just a part for calculating cgm.hash, not for Module itself)
  async fn get_runtime_hash(
    &self,
    compilation: &Compilation,
    runtime: Option<&RuntimeSpec>,
  ) -> Result<RspackHashDigest>;

  fn lib_ident(&self, _options: LibIdentOptions) -> Option<Cow<'_, str>> {
    // Align with https://github.com/webpack/webpack/blob/4b4ca3bb53f36a5b8fc6bc1bd976ed7af161bd80/lib/Module.js#L845
    None
  }

  /// Code generation dependencies of the module, which means the code generation of this module
  /// depends on the code generation results of dependencies which are returned by this function.
  /// e.g `Css` module may rely on the code generation result of `CssUrlDependency` to re-direct
  /// the url of the referenced assets.
  fn get_code_generation_dependencies(&self) -> Option<&[BoxModuleDependency]> {
    None
  }

  fn get_presentational_dependencies(&self) -> Option<&[BoxDependencyTemplate]> {
    None
  }

  fn get_concatenation_bailout_reason(
    &self,
    _mg: &ModuleGraph,
    _cg: &ChunkGraph,
  ) -> Option<Cow<'static, str>> {
    Some(
      format!(
        "Module Concatenation is not implemented for {}",
        self.module_type()
      )
      .into(),
    )
  }

  /// Resolve options matched by module rules.
  /// e.g `javascript/esm` may have special resolving options like `fullySpecified`.
  /// `css` and `css/module` may have special resolving options like `preferRelative`.
  fn get_resolve_options(&self) -> Option<Arc<Resolve>> {
    None
  }

  fn get_context(&self) -> Option<Box<Context>> {
    None
  }

  fn get_layer(&self) -> Option<&ModuleLayer> {
    None
  }

  fn chunk_condition(&self, _chunk_key: &ChunkUkey, _compilation: &Compilation) -> Option<bool> {
    None
  }

  fn get_side_effects_connection_state(
    &self,
    _module_graph: &ModuleGraph,
    _module_graph_cache: &ModuleGraphCacheArtifact,
    _side_effects_state_artifact: &SideEffectsStateArtifact,
    _module_chain: &mut IdentifierSet,
    _connection_state_cache: &mut IdentifierMap<ConnectionState>,
  ) -> ConnectionState {
    ConnectionState::Active(true)
  }

  fn need_build(&self, value_cache_version: &ValueCacheVersions) -> bool {
    let build_info = self.build_info();
    !build_info.cacheable
      || value_cache_version.has_diff(&build_info.value_dependencies)
      || self.diagnostics().iter().any(|item| item.is_error())
  }

  fn need_id(&self) -> bool {
    true
  }
}

fn get_exports_type_impl(
  identifier: ModuleIdentifier,
  build_meta: &BuildMeta,
  mg: &ModuleGraph,
  exports_info_artifact: &ExportsInfoArtifact,
  strict: bool,
) -> ExportsType {
  let export_type = &build_meta.exports_type;
  let default_object = &build_meta.default_object;
  match export_type {
    BuildMetaExportsType::Flagged => {
      if strict {
        ExportsType::DefaultWithNamed
      } else {
        ExportsType::Namespace
      }
    }
    BuildMetaExportsType::Namespace => ExportsType::Namespace,
    BuildMetaExportsType::Default => match default_object {
      BuildMetaDefaultObject::Redirect => ExportsType::DefaultWithNamed,
      BuildMetaDefaultObject::RedirectWarn => {
        if strict {
          ExportsType::DefaultOnly
        } else {
          ExportsType::DefaultWithNamed
        }
      }
      BuildMetaDefaultObject::False => ExportsType::DefaultOnly,
    },
    BuildMetaExportsType::Dynamic => {
      if strict {
        ExportsType::DefaultWithNamed
      } else {
        fn handle_default(default_object: &BuildMetaDefaultObject) -> ExportsType {
          match default_object {
            BuildMetaDefaultObject::Redirect => ExportsType::DefaultWithNamed,
            BuildMetaDefaultObject::RedirectWarn => ExportsType::DefaultWithNamed,
            _ => ExportsType::DefaultOnly,
          }
        }

        let name = Atom::from("__esModule");
        let exports_info = exports_info_artifact.get_exports_info_optional(&identifier);
        if let Some(export_info) = exports_info.as_ref().map(|info| {
          info
            .as_data(exports_info_artifact)
            .get_read_only_export_info(&name)
        }) {
          if matches!(export_info.provided(), Some(ExportProvided::NotProvided)) {
            handle_default(default_object)
          } else {
            let Some(GetTargetResult::Target(target)) = get_target(
              export_info,
              mg,
              exports_info_artifact,
              &|_| true,
              &mut Default::default(),
            ) else {
              return ExportsType::Dynamic;
            };
            if target
              .export
              .and_then(|t| {
                if t.len() == 1 {
                  t.first().cloned()
                } else {
                  None
                }
              })
              .is_some_and(|v| v == "__esModule")
            {
              let Some(target_exports_type) = mg
                .module_by_identifier(&target.module)
                .map(|m| m.build_meta().exports_type)
              else {
                return ExportsType::Dynamic;
              };
              match target_exports_type {
                BuildMetaExportsType::Flagged | BuildMetaExportsType::Namespace => {
                  ExportsType::Namespace
                }
                BuildMetaExportsType::Default => handle_default(default_object),
                _ => ExportsType::Dynamic,
              }
            } else {
              ExportsType::Dynamic
            }
          }
        } else {
          ExportsType::DefaultWithNamed
        }
      }
    }
    // align to undefined
    BuildMetaExportsType::Unset => {
      if strict {
        ExportsType::DefaultWithNamed
      } else {
        ExportsType::Dynamic
      }
    }
  }
}

pub fn module_update_hash(
  module: &dyn Module,
  hasher: &mut dyn std::hash::Hasher,
  compilation: &Compilation,
  runtime: Option<&RuntimeSpec>,
) {
  let chunk_graph = &compilation.build_chunk_graph_artifact.chunk_graph;
  chunk_graph
    .get_module_graph_hash(module, compilation, runtime)
    .dyn_hash(hasher);
  if let Some(deps) = module.get_presentational_dependencies() {
    for dep in deps {
      dep.update_hash(hasher, compilation, runtime);
    }
  }
  dependencies_block_update_hash(
    module.get_dependencies(),
    module.get_blocks(),
    hasher,
    compilation,
    runtime,
  );
}

pub trait ModuleExt {
  fn boxed(self) -> BoxModule;
}

impl<T: Module> ModuleExt for T {
  fn boxed(self) -> BoxModule {
    BoxModule(Box::new(self))
  }
}

/// A newtype wrapper around `Box<dyn Module>` for improved type safety.
#[cacheable(with=AsInner)]
#[repr(transparent)]
pub struct BoxModule(Box<dyn Module>);

impl BoxModule {
  /// Create a new BoxModule from a boxed Module trait object.
  pub fn new(module: Box<dyn Module>) -> Self {
    BoxModule(module)
  }

  pub async fn build(
    self,
    build_context: BuildContext,
    compilation: Option<&Compilation>,
  ) -> Result<BuildResult> {
    self.0.build(build_context, compilation).await
  }
}

impl AsInnerConverter for BoxModule {
  type Inner = Box<dyn Module>;

  fn to_inner(&self) -> &Self::Inner {
    &self.0
  }

  fn from_inner(data: Self::Inner) -> Self {
    BoxModule(data)
  }
}

impl std::ops::Deref for BoxModule {
  type Target = Box<dyn Module>;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl std::ops::DerefMut for BoxModule {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0
  }
}

impl From<Box<dyn Module>> for BoxModule {
  fn from(inner: Box<dyn Module>) -> Self {
    BoxModule(inner)
  }
}

impl AsRef<dyn Module> for BoxModule {
  fn as_ref(&self) -> &dyn Module {
    self.0.as_ref()
  }
}

impl AsMut<dyn Module> for BoxModule {
  fn as_mut(&mut self) -> &mut dyn Module {
    self.0.as_mut()
  }
}

impl Debug for BoxModule {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    self.0.fmt(f)
  }
}

impl Identifiable for BoxModule {
  /// Uniquely identify a module. If two modules share the same module identifier, then they are considered as the same module.
  /// e.g `javascript/auto|<absolute-path>/index.js` and `javascript/auto|<absolute-path>/index.js` are considered as the same.
  fn identifier(&self) -> Identifier {
    self.0.as_ref().identifier()
  }
}

impl dyn Module {
  pub fn downcast_ref<T: Module + Any>(&self) -> Option<&T> {
    self.as_any().downcast_ref::<T>()
  }

  pub fn downcast_mut<T: Module + Any>(&mut self) -> Option<&mut T> {
    self.as_any_mut().downcast_mut::<T>()
  }
}

#[macro_export]
macro_rules! impl_module_meta_info {
  () => {
    fn factory_meta(&self) -> Option<&$crate::FactoryMeta> {
      self.factory_meta.as_ref()
    }

    fn set_factory_meta(&mut self, v: $crate::FactoryMeta) {
      self.factory_meta = Some(v);
    }

    fn build_info(&self) -> &$crate::BuildInfo {
      &self.build_info
    }

    fn build_info_mut(&mut self) -> &mut $crate::BuildInfo {
      &mut self.build_info
    }

    fn build_meta(&self) -> &$crate::BuildMeta {
      &self.build_meta
    }

    fn build_meta_mut(&mut self) -> &mut $crate::BuildMeta {
      &mut self.build_meta
    }
  };
}

macro_rules! impl_module_downcast_helpers {
  ($ty:ty, $ident:ident) => {
    impl dyn Module {
      ::paste::paste! {
        pub fn [<as_ $ident>](&self) -> Option<&$ty> {
          self.as_any().downcast_ref::<$ty>()
        }

        pub fn [<as_ $ident _mut>](&mut self) -> Option<&mut $ty> {
          self.as_any_mut().downcast_mut::<$ty>()
        }

        pub fn [<try_as_ $ident>](&self) -> Result<&$ty> {
          self.[<as_ $ident>]().ok_or_else(|| {
            ::rspack_error::error!(
              "Failed to cast module to a {}",
              stringify!($ty)
            )
          })
        }

        pub fn [<try_as_ $ident _mut>](&mut self) -> Result<&mut $ty> {
          self.[<as_ $ident _mut>]().ok_or_else(|| {
            ::rspack_error::error!(
              "Failed to cast module to a {}",
              stringify!($ty)
            )
          })
        }
      }
    }
  };
}

impl_module_downcast_helpers!(NormalModule, normal_module);
impl_module_downcast_helpers!(RawModule, raw_module);
impl_module_downcast_helpers!(ContextModule, context_module);
impl_module_downcast_helpers!(ExternalModule, external_module);
impl_module_downcast_helpers!(SelfModule, self_module);
impl_module_downcast_helpers!(ConcatenatedModule, concatenated_module);

pub struct LibIdentOptions<'me> {
  pub context: &'me str,
}

#[cfg(test)]
mod test {
  use std::borrow::Cow;

  use rspack_cacheable::cacheable;
  use rspack_collections::{Identifiable, Identifier};
  use rspack_error::{Result, impl_empty_diagnosable_trait};
  use rspack_hash::RspackHashDigest;
  use rspack_sources::BoxSource;
  use rspack_util::source_map::{ModuleSourceMapConfig, SourceMapKind};

  use super::{BoxModule, Module};
  use crate::{
    AsyncDependenciesBlockIdentifier, BuildContext, BuildResult, CodeGenerationResult, Compilation,
    Context, DependenciesBlock, DependencyId, ModuleCodeGenerationContext, ModuleExt, ModuleGraph,
    ModuleType, RuntimeSpec, SourceType,
  };

  #[cacheable]
  #[derive(Debug)]
  struct RawModule(String);

  #[cacheable]
  #[derive(Debug)]
  struct ExternalModule(String);

  macro_rules! impl_noop_trait_module_type {
    ($ident: ident) => {
      impl Identifiable for $ident {
        fn identifier(&self) -> Identifier {
          self.0.clone().into()
        }
      }

      impl_empty_diagnosable_trait!($ident);

      impl DependenciesBlock for $ident {
        fn add_block_id(&mut self, _: AsyncDependenciesBlockIdentifier) {
          unreachable!()
        }

        fn get_blocks(&self) -> &[AsyncDependenciesBlockIdentifier] {
          unreachable!()
        }

        fn add_dependency_id(&mut self, _: DependencyId) {
          unreachable!()
        }

        fn remove_dependency_id(&mut self, _: DependencyId) {
          unreachable!()
        }

        fn get_dependencies(&self) -> &[DependencyId] {
          unreachable!()
        }
      }

      #[::rspack_cacheable::cacheable_dyn]
      #[::async_trait::async_trait]
      impl Module for $ident {
        fn module_type(&self) -> &ModuleType {
          unreachable!()
        }

        fn source_types(&self, _module_graph: &ModuleGraph) -> &[SourceType] {
          unreachable!()
        }

        fn source(&self) -> Option<&BoxSource> {
          unreachable!()
        }

        fn size(
          &self,
          _source_type: Option<&SourceType>,
          _compilation: Option<&Compilation>,
        ) -> f64 {
          unreachable!()
        }

        fn readable_identifier(&self, _context: &Context) -> Cow<'_, str> {
          self.0.clone().into()
        }

        async fn build(
          self: Box<Self>,
          _build_context: BuildContext,
          _compilation: Option<&Compilation>,
        ) -> Result<BuildResult> {
          unreachable!()
        }

        async fn get_runtime_hash(
          &self,
          _compilation: &Compilation,
          _runtime: Option<&RuntimeSpec>,
        ) -> Result<RspackHashDigest> {
          unreachable!()
        }

        async fn code_generation(
          &self,
          _code_generation_context: &mut ModuleCodeGenerationContext,
        ) -> Result<CodeGenerationResult> {
          unreachable!()
        }

        fn factory_meta(&self) -> Option<&crate::FactoryMeta> {
          unreachable!()
        }

        fn build_info(&self) -> &crate::BuildInfo {
          unreachable!()
        }

        fn build_info_mut(&mut self) -> &mut crate::BuildInfo {
          unreachable!()
        }

        fn build_meta(&self) -> &crate::BuildMeta {
          unreachable!()
        }

        fn build_meta_mut(&mut self) -> &mut crate::BuildMeta {
          unreachable!()
        }

        fn set_factory_meta(&mut self, _: crate::FactoryMeta) {
          unreachable!()
        }
      }

      impl ModuleSourceMapConfig for $ident {
        fn get_source_map_kind(&self) -> &SourceMapKind {
          unreachable!()
        }
        fn set_source_map_kind(&mut self, _source_map: SourceMapKind) {
          unreachable!()
        }
      }
    };
  }

  impl_noop_trait_module_type!(RawModule);
  impl_noop_trait_module_type!(ExternalModule);

  #[test]
  fn should_downcast_successfully() {
    let a: BoxModule = ExternalModule(String::from("a")).boxed();
    let b: BoxModule = RawModule(String::from("a")).boxed();

    assert!(a.downcast_ref::<ExternalModule>().is_some());
    assert!(b.downcast_ref::<RawModule>().is_some());

    let a = a.as_ref();
    let b = b.as_ref();
    assert!(a.downcast_ref::<ExternalModule>().is_some());
    assert!(b.downcast_ref::<RawModule>().is_some());
  }
}