Skip to main content

aer/proc/
js_bundle.rs

1use std::path::Path;
2
3use rolldown::{Bundler, BundlerOptions};
4use rolldown_common::Output;
5
6use super::{Asset, Environment, LayeredContext, MediaType, ProcessesAssets, ProcessingError};
7
8/// Bundles JavaScript entry points and their dependencies into a single file.
9///
10/// This processor uses [rolldown](https://rolldown.rs) to bundle
11/// JavaScript modules, similar to tools like webpack or rollup.
12///
13/// Each asset passed to this processor is treated as a distinct entry point,
14/// and modules are resolved relative to that entry point's location.
15///
16/// # Example
17///
18/// ```ignore
19/// use aer::proc::js_bundle::JsBundleProcessor;
20/// use aer::proc::{Asset, ProcessesAssets};
21///
22/// let processor = JsBundleProcessor::new();
23/// let mut asset = Asset::new("src/index.js".into(), b"".to_vec());
24/// processor.process(&mut asset).unwrap();
25/// ```
26pub struct JsBundleProcessor {
27    /// Whether to minify the output.
28    minify: bool,
29}
30
31impl JsBundleProcessor {
32    /// Creates a new JS bundle processor.
33    pub fn new(minify: bool) -> Self {
34        Self { minify }
35    }
36}
37
38impl JsBundleProcessor {
39    /// Bundles the JavaScript file at `entry_path` and returns the bundled code.
40    ///
41    /// Modules are resolved relative to the entry point's parent directory.
42    fn bundle_js(&self, entry_path: &Path) -> Result<String, ProcessingError> {
43        // Get the entry point filename for the bundler input.
44        let file_name = entry_path
45            .file_name()
46            .ok_or_else(|| ProcessingError::Compilation {
47                message: format!(
48                    "Invalid entry path '{}': must be a file path, not a directory or root",
49                    entry_path.display()
50                )
51                .into(),
52            })?;
53
54        // Use the entry point's parent directory as the working directory
55        // for module resolution. Must be absolute for rolldown's resolver.
56        let cwd = entry_path
57            .parent()
58            .filter(|p| !p.as_os_str().is_empty())
59            .map(|p| {
60                if p.is_absolute() {
61                    p.to_path_buf()
62                } else {
63                    std::env::current_dir().unwrap_or_default().join(p)
64                }
65            });
66
67        let input_path = format!("./{}", file_name.to_string_lossy());
68
69        // Create bundler options.
70        let options = BundlerOptions {
71            input: Some(vec![input_path.into()]),
72            cwd,
73            minify: if self.minify {
74                Some(rolldown::RawMinifyOptions::Bool(true))
75            } else {
76                None
77            },
78            ..Default::default()
79        };
80
81        // Create a new runtime for the async bundling operation.
82        // Note: rolldown uses async internally, so we need a runtime to
83        // execute the bundling operation.
84        let rt = tokio::runtime::Runtime::new().map_err(|e| ProcessingError::Compilation {
85            message: format!("Failed to create async runtime: {}", e).into(),
86        })?;
87
88        // Run the bundler.
89        rt.block_on(async {
90            let mut bundler = Bundler::new(options).map_err(|e| ProcessingError::Compilation {
91                message: format!("Failed to create bundler: {:?}", e).into(),
92            })?;
93
94            let output = bundler
95                .generate()
96                .await
97                .map_err(|e| ProcessingError::Compilation {
98                    message: format!("Bundling failed: {:?}", e).into(),
99                })?;
100
101            // Extract the bundled code from the first chunk.
102            for asset in output.assets {
103                if let Output::Chunk(chunk) = asset {
104                    return Ok(chunk.code.clone());
105                }
106            }
107
108            Err(ProcessingError::Compilation {
109                message: "Bundling produced no output chunks".into(),
110            })
111        })
112    }
113}
114
115impl ProcessesAssets for JsBundleProcessor {
116    fn process(
117        &self,
118        _env: &Environment,
119        _context: &LayeredContext,
120        asset: &mut Asset,
121    ) -> Result<bool, ProcessingError> {
122        // Skip assets that aren't JavaScript.
123        if *asset.media_type() != MediaType::JavaScript {
124            return Ok(false);
125        }
126
127        tracing::trace!("js_bundle: {}", asset.path());
128
129        // Get the path to the JavaScript entry point.
130        let entry_path_str = asset.path().clone();
131        let entry_path = Path::new(entry_path_str.as_str());
132
133        // Bundle the JavaScript entry point.
134        let bundled_code = self.bundle_js(entry_path)?;
135
136        // Update the asset's contents with the bundled code.
137        asset.replace_with_text(bundled_code.into(), MediaType::JavaScript);
138
139        Ok(true)
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::proc::LayeredContext;
147
148    #[test]
149    fn skips_non_javascript_assets() {
150        let processor = JsBundleProcessor { minify: false };
151
152        // Create a non-JavaScript asset.
153        let mut css_asset = Asset::new("style.css".into(), "body {}".as_bytes().to_vec());
154
155        // Processing should skip without errors.
156        let modified = processor
157            .process(
158                &Environment::test(),
159                &LayeredContext::from_flat(Default::default()),
160                &mut css_asset,
161            )
162            .unwrap();
163        assert!(!modified);
164    }
165
166    #[test]
167    fn bundles_javascript() {
168        let processor = JsBundleProcessor { minify: false };
169
170        // Create a JavaScript asset pointing to our test file.
171        let mut js_asset = Asset::new("test/js_bundle/entry.js".into(), "".as_bytes().to_vec());
172
173        // Process the asset.
174        let result = processor.process(
175            &Environment::test(),
176            &LayeredContext::from_flat(Default::default()),
177            &mut js_asset,
178        );
179        assert!(result.is_ok());
180
181        // Check that the bundled code contains content from the entry point
182        // and the imported modules.
183        let bundled = js_asset.as_text().unwrap();
184        assert!(bundled.contains("Hello from bundled JavaScript!"));
185        assert!(bundled.contains("greet"));
186        // Rolldown may inline the imported HELPER_VERSION constant, so check
187        // for its value rather than its name.
188        assert!(bundled.contains("1.0.0"));
189        assert!(bundled.contains("formatMessage"));
190    }
191}