swc_bundler/bundler/chunk/plan/
mod.rs

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
use anyhow::{bail, Error};
use swc_common::collections::AHashMap;
use swc_graph_analyzer::{DepGraph, GraphAnalyzer};

use crate::{
    bundler::{load::TransformedModule, scope::Scope},
    dep_graph::ModuleGraph,
    BundleKind, Bundler, Load, ModuleId, Resolve,
};

#[cfg(test)]
mod tests;

#[derive(Debug, Default)]
struct PlanBuilder {
    kinds: AHashMap<ModuleId, BundleKind>,
}

#[derive(Debug, Default)]
pub(super) struct Plan {
    pub entries: AHashMap<ModuleId, BundleKind>,

    /// Id of all modules.
    pub all: Vec<ModuleId>,
}

impl DepGraph for Scope {
    type ModuleId = ModuleId;

    fn deps_of(&self, module_id: Self::ModuleId) -> Vec<Self::ModuleId> {
        let m = self.get_module(module_id).expect("failed to get module");

        m.imports
            .specifiers
            .iter()
            .chain(m.exports.reexports.iter())
            .map(|v| v.0.module_id)
            .collect()
    }
}

impl<L, R> Bundler<'_, L, R>
where
    L: Load,
    R: Resolve,
{
    pub(super) fn determine_entries(
        &self,
        entries: AHashMap<String, TransformedModule>,
    ) -> Result<(Plan, ModuleGraph, Vec<Vec<ModuleId>>), Error> {
        let mut builder = PlanBuilder::default();
        let mut analyzer = GraphAnalyzer::new(&self.scope);

        for (name, module) in entries {
            if let Some(v) = builder.kinds.insert(module.id, BundleKind::Named { name }) {
                bail!("Multiple entries with same input path detected: {:?}", v)
            }

            analyzer.load(module.id);
        }
        let res = analyzer.into_result();

        // dbg!(&builder.cycles);

        Ok((
            Plan {
                entries: builder.kinds,
                all: res.all,
            },
            res.graph,
            res.cycles,
        ))
    }
}