dumpling 0.1.0

A fast JavaScript runtime and bundler in Rust
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
use std::path::PathBuf;
use std::collections::HashMap;
use std::fs;
use std::env;
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use async_recursion::async_recursion;

use crate::modules::{Module, ModuleResolver};
use crate::error::{Result, DumplingError};
use crate::typescript::{TypeScriptConfig, is_typescript_file, get_declaration_path};
use crate::code_splitting::{CodeSplitter, SplittingConfig, Chunk};

/// Bundle entry point to output file (convenience function)
pub async fn bundle(entry: PathBuf, output: PathBuf, format: &str, minify: bool, sourcemap: bool) -> Result<()> {
    let current_dir = env::current_dir()?;
    let mut bundler = Bundler::new(current_dir);
    bundler.bundle(entry, output, format, minify, sourcemap, false).await
}

/// Bundle with TypeScript declarations
pub async fn bundle_with_ts(entry: PathBuf, output: PathBuf, format: &str, minify: bool, sourcemap: bool, declarations: bool) -> Result<()> {
    let current_dir = env::current_dir()?;
    let mut bundler = Bundler::new(current_dir);
    bundler.bundle(entry, output, format, minify, sourcemap, declarations).await
}

/// Bundle with code splitting
pub async fn bundle_with_splitting(
    entry: PathBuf, 
    output: PathBuf, 
    format: &str, 
    minify: bool, 
    sourcemap: bool, 
    declarations: bool,
    split: bool,
    vendor_size: usize
) -> Result<()> {
    let current_dir = env::current_dir()?;
    let mut bundler = Bundler::new(current_dir);
    bundler.bundle_with_code_splitting(entry, output, format, minify, sourcemap, declarations, split, vendor_size).await
}

#[derive(Debug, Clone)]
pub enum BundleFormat {
    Iife,  // Immediately Invoked Function Expression
    Esm,   // ES Modules
    Cjs,   // CommonJS
}

impl BundleFormat {
    pub fn from_str(s: &str) -> Result<Self> {
        match s {
            "iife" => Ok(BundleFormat::Iife),
            "esm" => Ok(BundleFormat::Esm),
            "cjs" => Ok(BundleFormat::Cjs),
            _ => Err(DumplingError::Build(format!("Unknown bundle format: {}", s))),
        }
    }
}

pub struct Bundler {
    resolver: ModuleResolver,
    root: PathBuf,
}

impl Bundler {
    pub fn new(root: PathBuf) -> Self {
        Self {
            resolver: ModuleResolver::new(root.clone()),
            root,
        }
    }

    fn cache_dir(&self) -> PathBuf {
        self.root.join(".dumpling").join("cache")
    }

    fn compute_input_hash(&self, graph: &DependencyGraph) -> u64 {
        let mut hasher = DefaultHasher::new();
        for module_id in graph.topological_sort().unwrap_or_default() {
            if let Some(module) = graph.get_module(&module_id) {
                let path_str = module.path.display().to_string();
                path_str.hash(&mut hasher);
                if let Ok(meta) = fs::metadata(&module.path) {
                    if let Ok(mtime) = meta.modified() {
                        format!("{:?}", mtime).hash(&mut hasher);
                    }
                }
            }
        }
        hasher.finish()
    }

    fn cache_key(&self, output: &PathBuf, format: &str, minify: bool) -> String {
        let mut hasher = DefaultHasher::new();
        output.display().to_string().hash(&mut hasher);
        format.hash(&mut hasher);
        minify.hash(&mut hasher);
        format!("{:x}", hasher.finish())
    }

    fn read_cache(&self, cache_key: &str, input_hash: u64) -> Option<String> {
        let cache_path = self.cache_dir().join(cache_key);
        let hash_file = cache_path.join("input.hash");
        let bundle_file = cache_path.join("bundle.js");
        let cached_hash: u64 = fs::read_to_string(&hash_file).ok()?.trim().parse().ok()?;
        if cached_hash != input_hash {
            return None;
        }
        fs::read_to_string(&bundle_file).ok()
    }

    fn write_cache(&self, cache_key: &str, input_hash: u64, bundle: &str) -> Result<()> {
        let cache_path = self.cache_dir().join(cache_key);
        fs::create_dir_all(&cache_path)?;
        fs::write(cache_path.join("input.hash"), format!("{}", input_hash))?;
        fs::write(cache_path.join("bundle.js"), bundle)?;
        Ok(())
    }
    
    /// Generate TypeScript declaration files for all TypeScript modules
    fn generate_declarations(&self, graph: &DependencyGraph) -> Result<()> {
        let ts_transpiler = crate::typescript::TypeScriptTranspiler::new(TypeScriptConfig::default());
        
        for module_id in graph.modules.keys() {
            if let Some(module) = graph.get_module(module_id) {
                if is_typescript_file(&module.path) {
                    // Generate declaration file
                    let declaration_path = get_declaration_path(&module.path);
                    let ts_source = std::fs::read_to_string(&module.path)?;
                    
                    match ts_transpiler.generate_declaration(&module.path, &ts_source) {
                        Ok(declaration) => {
                            // Create parent directory if it doesn't exist
                            if let Some(parent) = declaration_path.parent() {
                                fs::create_dir_all(parent)?;
                            }
                            fs::write(&declaration_path, declaration)?;
                            println!("  Generated declaration: {}", declaration_path.display());
                        }
                        Err(e) => {
                            println!("  Warning: Failed to generate declaration for {}: {}", module.path.display(), e);
                        }
                    }
                }
            }
        }
        
        Ok(())
    }

    pub async fn bundle(
        &mut self,
        entry: PathBuf,
        output: PathBuf,
        format: &str,
        minify: bool,
        sourcemap: bool,
        declarations: bool,
    ) -> Result<()> {
        let format_enum = BundleFormat::from_str(format)?;
        let mut graph = DependencyGraph::new();
        self.build_graph(&entry, &mut graph, None).await?;
        let input_hash = self.compute_input_hash(&graph);
        let cache_key = self.cache_key(&output, format, minify);

        let bundle = if let Some(cached) = self.read_cache(&cache_key, input_hash) {
            println!("✓ Using cached bundle for {} -> {}", entry.display(), output.display());
            cached
        } else {
            let bundle = self.generate_bundle(&graph, &format_enum, minify).await?;
            self.write_cache(&cache_key, input_hash, &bundle)?;
            bundle
        };

        // Create output directory if it doesn't exist
        if let Some(parent) = output.parent() {
            fs::create_dir_all(parent)?;
        }

        // Write output
        let mut final_bundle = bundle.clone();
        if sourcemap {
            let map_name = output.file_name().unwrap_or_default().to_string_lossy();
            let map_path = format!("{}.map", map_name);
            let source_map = self.generate_source_map(&bundle, &entry);
            fs::write(output.parent().unwrap().join(&map_path), &source_map)?;
            final_bundle.push_str(&format!("\n//# sourceMappingURL={}\n", map_path));
        }
        fs::write(&output, &final_bundle)?;

        // Generate TypeScript declaration files if requested
        if declarations {
            self.generate_declarations(&graph)?;
        }

        println!("✓ Bundled {} -> {} ({})", entry.display(), output.display(), format);

        Ok(())
    }

    fn generate_source_map(&self, _bundle: &str, entry: &PathBuf) -> String {
        // Minimal source map: maps output line 1 to entry file
        let version = 3;
        let file = entry.file_name().unwrap_or_default().to_string_lossy();
        let mapping = "AAAA";
        format!(
            r#"{{"version":{},"sources":["{}"],"names":[],"mappings":"{}"}}"#,
            version, file, mapping
        )
    }
    
    /// Bundle entry point to a string (for runtime execution)
    pub async fn bundle_to_string(
        &mut self,
        entry: &PathBuf,
        format: &str,
        minify: bool,
    ) -> Result<String> {
        let format = BundleFormat::from_str(format)?;
        
        // Build dependency graph
        let mut graph = DependencyGraph::new();
        if let Err(e) = self.build_graph(entry, &mut graph, None).await {
            // Add context to bundling errors
            let error_context = crate::error::ErrorContext::new()
                .with_file(entry.clone());
            return Err(DumplingError::Bundling(format!("Failed to build dependency graph: {}", e))
                .with_context(error_context).into());
        }
        
        // Generate bundle
        self.generate_bundle(&graph, &format, minify).await
    }
    
    #[async_recursion]
    async fn build_graph(
        &mut self,
        path: &PathBuf,
        graph: &mut DependencyGraph,
        parent_id: Option<String>,
    ) -> Result<String> {
        let module = self.resolver.load_module(path.clone()).await?;
        let module_id = module.id.clone();
        
        // Check for circular dependencies
        if parent_id.is_some() && graph.has_circular_dependency(&module_id, parent_id.as_ref().unwrap()) {
            return Err(DumplingError::Build(format!(
                "Circular dependency detected: {} -> {}",
                parent_id.unwrap(),
                module_id
            )));
        }
        
        // Add module to graph
        graph.add_module(module.clone(), parent_id);
        
        // Process dependencies
        let mut resolved_deps = Vec::new();
        for dep in &module.dependencies {
            let dep_path = self.resolver.resolve(dep, path.parent().unwrap()).await?;
            let dep_id = self.build_graph(&dep_path, graph, Some(module_id.clone())).await?;
            resolved_deps.push((dep.clone(), dep_id));
        }
        
        graph.set_resolved_dependencies(&module_id, resolved_deps);
        
        Ok(module_id)
    }
    
    async fn generate_bundle(
        &self,
        graph: &DependencyGraph,
        format: &BundleFormat,
        minify: bool,
    ) -> Result<String> {
        let mut code = String::new();
        
        match format {
            BundleFormat::Iife => {
                code.push_str("(function() {\n");
                code.push_str("var __modules = {};\n");
                
                // Add all modules
                for module_id in graph.topological_sort()? {
                    let module = graph.get_module(&module_id).unwrap();
                    let wrapped = self.wrap_module_iife(module, graph)?;
                    code.push_str(&wrapped);
                    code.push('\n');
                }
                
                // Execute entry module
                let entry_id = graph.entry_id.as_ref().unwrap();
                code.push_str(&format!("__modules[\"{}\"]();\n", entry_id));
                
                code.push_str("})();\n");
            }
            BundleFormat::Esm => {
                // Add all modules as ES modules
                for module_id in graph.topological_sort()? {
                    let module = graph.get_module(&module_id).unwrap();
                    let transformed = self.transform_module_esm(module, graph)?;
                    code.push_str(&transformed);
                    code.push('\n');
                }
                
                // Import and execute entry module
                let entry_id = graph.entry_id.as_ref().unwrap();
                code.push_str(&format!("import \"./{}\";\n", entry_id));
            }
            BundleFormat::Cjs => {
                code.push_str("var __modules = {};\n");
                code.push_str("function require(id) { return __modules[id] ? __modules[id]() : (function(){ throw new Error('Cannot find module \\'' + id + '\\''); })(); }\n");
                // Add all modules as CommonJS
                for module_id in graph.topological_sort()? {
                    let module = graph.get_module(&module_id).unwrap();
                    let wrapped = self.wrap_module_cjs(module, graph)?;
                    code.push_str(&wrapped);
                    code.push('\n');
                }
                
                // Execute entry module
                let entry_id = graph.entry_id.as_ref().unwrap();
                code.push_str(&format!("require(\"{}\");\n", entry_id));
            }
        }
        
        if minify {
            code = self.minify_code(&code);
        }
        
        Ok(code)
    }

    fn escape_css_for_js(css: &str) -> String {
        css.replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('\n', "\\n")
            .replace('\r', "\\r")
    }

    fn wrap_css_module_iife(&self, module: &Module) -> Result<String> {
        let escaped = Self::escape_css_for_js(&module.source);
        let hmr_id = Self::css_hmr_id(&module.id);
        Ok(format!(
            r#"__modules["{}"] = function() {{
  if (typeof document !== "undefined") {{
    var s = document.createElement("style");
    s.setAttribute("data-dumpling-hmr","{}");
    s.textContent = "{}";
    (document.head || document.documentElement).appendChild(s);
  }}
}};"#,
            module.id.replace('\\', "\\\\").replace('"', "\\\""),
            hmr_id,
            escaped
        ))
    }

    fn wrap_css_module_cjs(&self, module: &Module) -> Result<String> {
        let escaped = Self::escape_css_for_js(&module.source);
        let hmr_id = Self::css_hmr_id(&module.id);
        Ok(format!(
            r#"__modules["{}"] = function() {{
  if (typeof document !== "undefined") {{
    var s = document.createElement("style");
    s.setAttribute("data-dumpling-hmr","{}");
    s.textContent = "{}";
    (document.head || document.documentElement).appendChild(s);
  }}
  return {{}};
}};"#,
            module.id.replace('\\', "\\\\").replace('"', "\\\""),
            hmr_id,
            escaped
        ))
    }

    /// HMR id for CSS: use filename for matching (e.g. "style.css")
    fn css_hmr_id(module_id: &str) -> String {
        module_id
            .split('/')
            .last()
            .unwrap_or(module_id)
            .replace('\\', "/")
    }
    
    fn wrap_module_iife(&self, module: &Module, graph: &DependencyGraph) -> Result<String> {
        if module.is_css() {
            return self.wrap_css_module_iife(module);
        }
        let mut code = String::new();
        let module_id = &module.id;
        
        // Start module wrapper
        code.push_str(&format!("__modules[\"{}\"] = function() {{\n", module_id));
        
        // Inject require function for CommonJS-style modules
        let deps = graph.get_resolved_dependencies(module_id);
        if !deps.is_empty() {
            code.push_str("var require = (function() {\n");
            code.push_str("  var __specMap = {\n");
            for (i, (spec, dep_id)) in deps.iter().enumerate() {
                let comma = if i < deps.len() - 1 { "," } else { "" };
                code.push_str(&format!("    \"{}\": \"{}\"{}\n", spec.replace('\\', "\\\\").replace('"', "\\\""), dep_id.replace('\\', "\\\\").replace('"', "\\\""), comma));
            }
            code.push_str("  };\n");
            code.push_str("  return function(spec) {\n");
            code.push_str("    if (!(spec in __specMap)) throw new Error('Cannot find module \\'' + spec + '\\'');\n");
            code.push_str("    return __modules[__specMap[spec]]();\n");
            code.push_str("  };\n");
            code.push_str("})();\n");
        }
        
        // Add module source
        code.push_str(&module.source);
        code.push('\n');
        
        // End module wrapper
        code.push_str("};\n");
        
        Ok(code)
    }
    
    fn wrap_module_cjs(&self, module: &Module, graph: &DependencyGraph) -> Result<String> {
        if module.is_css() {
            return self.wrap_css_module_cjs(module);
        }
        let mut code = String::new();
        let module_id = &module.id;
        
        // Start module wrapper
        code.push_str(&format!(
            "__modules[\"{}\"] = function() {{\n",
            module_id
        ));
        code.push_str("var module = { exports: {} };\n");
        code.push_str("var exports = module.exports;\n");
        
        // Inject require function that resolves all dependencies
        let deps = graph.get_resolved_dependencies(module_id);
        if !deps.is_empty() {
            code.push_str("var require = (function() {\n");
            code.push_str("  var __specMap = {\n");
            for (i, (spec, dep_id)) in deps.iter().enumerate() {
                let comma = if i < deps.len() - 1 { "," } else { "" };
                code.push_str(&format!("    \"{}\": \"{}\"{}\n", spec.replace('\\', "\\\\").replace('"', "\\\""), dep_id.replace('\\', "\\\\").replace('"', "\\\""), comma));
            }
            code.push_str("  };\n");
            code.push_str("  return function(spec) {\n");
            code.push_str("    if (!(spec in __specMap)) throw new Error('Cannot find module \\'' + spec + '\\'');\n");
            code.push_str("    return __modules[__specMap[spec]]();\n");
            code.push_str("  };\n");
            code.push_str("})();\n");
        }
        
        // Add module source
        code.push_str(&module.source);
        code.push('\n');
        
        // Return module.exports
        code.push_str("return module.exports;\n");
        code.push_str("};\n");
        
        Ok(code)
    }
    
    fn transform_module_esm(&self, module: &Module, _graph: &DependencyGraph) -> Result<String> {
        if module.is_css() {
            let escaped = Self::escape_css_for_js(&module.source);
            let hmr_id = Self::css_hmr_id(&module.id);
            return Ok(format!(
                r#"// {}
if (typeof document !== "undefined") {{
  var s = document.createElement("style");
  s.setAttribute("data-dumpling-hmr","{}");
  s.textContent = "{}";
  (document.head || document.documentElement).appendChild(s);
}}"#,
                module.id,
                hmr_id,
                escaped
            ));
        }
        let mut code = String::new();
        
        // Transform imports/exports to relative paths
        // This is a simplified version - in practice you'd use a proper AST transformer
        code.push_str("// ");
        code.push_str(&module.id);
        code.push('\n');
        code.push_str(&module.source);
        
        Ok(code)
    }
    
    fn sanitize_identifier(&self, identifier: &str) -> String {
        identifier
            .replace("./", "")
            .replace("../", "")
            .replace("/", "_")
            .replace("-", "_")
            .replace("@", "_")
            .chars()
            .map(|c| if c.is_alphanumeric() || c == '_' { c } else { '_' })
            .collect()
    }
    
    fn minify_code(&self, code: &str) -> String {
        // Basic minification - remove comments and extra whitespace
        code.lines()
            .filter(|line| !line.trim_start().starts_with("//"))
            .map(|line| line.trim())
            .collect::<Vec<_>>()
            .join(";")
    }

    pub async fn bundle_with_code_splitting(
        &mut self,
        entry: PathBuf,
        output: PathBuf,
        format: &str,
        minify: bool,
        sourcemap: bool,
        declarations: bool,
        split: bool,
        vendor_size: usize,
    ) -> Result<()> {
        let format_enum = BundleFormat::from_str(format)?;
        let mut graph = DependencyGraph::new();
        self.build_graph(&entry, &mut graph, None).await?;
        
        // Create output directory
        let output_dir = output.parent().map(|p| p.to_path_buf()).unwrap_or_else(|| PathBuf::from("."));
        fs::create_dir_all(&output_dir)?;
        
        if split {
            // Use code splitting
            let mut config = SplittingConfig::default();
            config.chunk_size_limit = vendor_size * 1024; // Convert KB to bytes
            config.vendor_chunk = true;
            
            let splitter = CodeSplitter::new(config);
            let chunks = splitter.split(&graph, &output_dir)?;
            
            // Generate each chunk
            let mut total_size = 0;
            for chunk in &chunks {
                let chunk_path = output_dir.join(&chunk.file_name);
                let chunk_content = self.generate_chunk(&graph, &chunk, &format_enum, minify).await?;
                
                if sourcemap {
                    let map_name = format!("{}.map", chunk.file_name);
                    let source_map = self.generate_chunk_source_map(&chunk, &chunk_path);
                    fs::write(output_dir.join(&map_name), &source_map)?;
                    let final_content = format!("{}\n//# sourceMappingURL={}\n", chunk_content, map_name);
                    fs::write(&chunk_path, &final_content)?;
                } else {
                    fs::write(&chunk_path, &chunk_content)?;
                }
                
                println!("✓ Generated chunk: {} ({})", chunk.file_name, Self::format_size(chunk.size));
                total_size += chunk.size;
            }
            
            // Generate chunk loader
            let loader_path = output_dir.join("chunk-loader.js");
            let chunk_ids: Vec<String> = chunks.iter().map(|c| c.id.clone()).collect();
            let loader_content = splitter.generate_chunk_loader(&chunks);
            fs::write(&loader_path, &loader_content)?;
            println!("✓ Generated chunk loader: chunk-loader.js");
            
            // Generate entry HTML file
            self.generate_entry_html(&output_dir, &chunks)?;
            
            println!("✓ Total bundle size: {} ({} chunks)", Self::format_size(total_size), chunks.len());
        } else {
            // Standard bundling without splitting
            self.bundle(entry, output, format, minify, sourcemap, declarations).await?;
        }
        
        // Generate TypeScript declaration files if requested
        if declarations {
            self.generate_declarations(&graph)?;
        }
        
        Ok(())
    }

    async fn generate_chunk(
        &self,
        graph: &DependencyGraph,
        chunk: &Chunk,
        format: &BundleFormat,
        minify: bool,
    ) -> Result<String> {
        let mut code = String::new();
        
        match format {
            BundleFormat::Esm => {
                // Generate ES modules chunk
                for module_id in &chunk.modules {
                    if let Some(module) = graph.get_module(module_id) {
                        let transformed = self.transform_chunk_module(module, graph)?;
                        code.push_str(&transformed);
                        code.push_str("\n");
                    }
                }
            }
            BundleFormat::Iife | BundleFormat::Cjs => {
                // Generate wrapped chunk
                code.push_str(&format!("// Chunk: {}\n", chunk.id));
                code.push_str("(function() {\n");
                
                for module_id in &chunk.modules {
                    if let Some(module) = graph.get_module(module_id) {
                        let wrapped = self.wrap_chunk_module(module, graph, format)?;
                        code.push_str(&wrapped);
                        code.push_str("\n");
                    }
                }
                
                code.push_str("})();\n");
            }
        }
        
        if minify {
            code = self.minify_code(&code);
        }
        
        Ok(code)
    }

    fn transform_chunk_module(&self, module: &Module, _graph: &DependencyGraph) -> Result<String> {
        let mut code = String::new();
        
        // Add module comment
        code.push_str(&format!("// Module: {}\n", module.id));
        
        // For chunking, we need to transform dynamic imports to use the chunk loader
        let splitter = CodeSplitter::new(SplittingConfig::default());
        let chunk_ids: Vec<String> = vec![];
        let transformed_source = splitter.update_dynamic_imports(&module.source, &chunk_ids);
        code.push_str(&transformed_source);
        
        Ok(code)
    }

    fn wrap_chunk_module(&self, module: &Module, graph: &DependencyGraph, format: &BundleFormat) -> Result<String> {
        let mut code = String::new();
        
        // Add module comment
        code.push_str(&format!("// Module: {}\n", module.id));
        
        match format {
            BundleFormat::Iife => {
                code.push_str("var __modules = __modules || {};\n");
                code.push_str(&format!("__modules['{}'] = function() {{\n", module.id));
                
                // Add dependencies
                let deps = graph.get_resolved_dependencies(&module.id);
                if !deps.is_empty() {
                    code.push_str("var require = function(spec) {\n");
                    code.push_str("  return __modules[spec] ? __modules[spec]() : (function(){ throw new Error('Cannot find module \\'' + spec + '\\''); })();\n");
                    code.push_str("};\n");
                }
                
                code.push_str(&module.source);
                code.push_str("\n};\n");
            }
            BundleFormat::Cjs => {
                code.push_str("var __modules = __modules || {};\n");
                code.push_str(&format!("__modules['{}'] = function() {{\n", module.id));
                
                // Add dependencies
                let deps = graph.get_resolved_dependencies(&module.id);
                if !deps.is_empty() {
                    code.push_str("var require = function(spec) {\n");
                    code.push_str("  return __modules[spec] ? __modules[spec]() : (function(){ throw new Error('Cannot find module \\'' + spec + '\\''); })();\n");
                    code.push_str("};\n");
                }
                
                code.push_str("var module = { exports: {} };\n");
                code.push_str("var exports = module.exports;\n");
                code.push_str(&module.source);
                code.push_str("\nreturn module.exports;\n");
                code.push_str("};\n");
            }
            _ => return Err(DumplingError::Build("Unsupported format for code splitting".to_string())),
        }
        
        Ok(code)
    }

    fn generate_chunk_source_map(&self, _chunk: &Chunk, chunk_path: &PathBuf) -> String {
        let version = 3;
        let file_name = chunk_path.file_name().unwrap_or_default().to_string_lossy();
        
        // Simplified source map for chunks
        format!(
            r#"{{"version":{},"file":"{}","sources":[],"names":[],"mappings":""}}"#,
            version, file_name
        )
    }

    fn format_size(bytes: usize) -> String {
        if bytes < 1024 {
            format!("{} B", bytes)
        } else if bytes < 1024 * 1024 {
            format!("{:.1} KB", bytes as f64 / 1024.0)
        } else {
            format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
        }
    }

    fn generate_entry_html(&self, output_dir: &PathBuf, chunks: &[Chunk]) -> Result<()> {
        let mut html = String::new();
        
        html.push_str("<!DOCTYPE html>\n");
        html.push_str("<html>\n");
        html.push_str("<head>\n");
        html.push_str("  <meta charset=\"utf-8\">\n");
        html.push_str("  <title>Dumpling App</title>\n");
        html.push_str("</head>\n");
        html.push_str("<body>\n");
        
        // Load vendor chunk first if it exists
        if let Some(vendor_chunk) = chunks.iter().find(|c| c.id == "vendor") {
            html.push_str(&format!("  <script src=\"{}\"></script>\n", vendor_chunk.file_name));
        }
        
        // Load other chunks (main should be last)
        for chunk in chunks {
            if chunk.id != "vendor" {
                html.push_str(&format!("  <script src=\"{}\"></script>\n", chunk.file_name));
            }
        }
        
        html.push_str("</body>\n");
        html.push_str("</html>\n");
        
        let html_path = output_dir.join("index.html");
        fs::write(&html_path, html)?;
        println!("✓ Generated entry HTML: index.html");
        
        Ok(())
    }
}

#[derive(Debug)]
pub struct DependencyGraph {
    modules: HashMap<String, Module>,
    dependencies: HashMap<String, Vec<(String, String)>>, // module_id -> (import_spec, dep_id)
    reverse_dependencies: HashMap<String, Vec<String>>,   // module_id -> [parent_ids]
    pub entry_id: Option<String>,
}

impl DependencyGraph {
    pub fn new() -> Self {
        Self {
            modules: HashMap::new(),
            dependencies: HashMap::new(),
            reverse_dependencies: HashMap::new(),
            entry_id: None,
        }
    }
    
    pub fn add_module(&mut self, module: Module, parent_id: Option<String>) {
        let module_id = module.id.clone();
        
        if self.entry_id.is_none() {
            self.entry_id = Some(module_id.clone());
        }
        
        self.modules.insert(module_id.clone(), module);
        
        if let Some(parent) = parent_id {
            self.reverse_dependencies
                .entry(module_id)
                .or_insert_with(Vec::new)
                .push(parent);
        }
    }
    
    pub fn set_resolved_dependencies(&mut self, module_id: &str, deps: Vec<(String, String)>) {
        self.dependencies.insert(module_id.to_string(), deps);
    }
    
    pub fn get_module(&self, module_id: &str) -> Option<&Module> {
        self.modules.get(module_id)
    }
    
    pub fn get_resolved_dependencies(&self, module_id: &str) -> Vec<(String, String)> {
        self.dependencies
            .get(module_id)
            .cloned()
            .unwrap_or_default()
    }
    
    pub fn has_circular_dependency(&self, current: &str, target: &str) -> bool {
        if current == target {
            return true;
        }
        
        if let Some(deps) = self.dependencies.get(target) {
            for (_, dep_id) in deps {
                if self.has_circular_dependency(current, dep_id) {
                    return true;
                }
            }
        }
        
        false
    }
    
    pub fn topological_sort(&self) -> Result<Vec<String>> {
        let mut visited = HashMap::new();
        let mut temp_visited = HashMap::new();
        let mut result = Vec::new();
        
        for module_id in self.modules.keys() {
            if !visited.contains_key(module_id) {
                self.visit(module_id, &mut visited, &mut temp_visited, &mut result)?;
            }
        }
        
        result.reverse();
        Ok(result)
    }
    
    fn visit(
        &self,
        module_id: &str,
        visited: &mut HashMap<String, bool>,
        temp_visited: &mut HashMap<String, bool>,
        result: &mut Vec<String>,
    ) -> Result<()> {
        if temp_visited.contains_key(module_id) {
            return Err(DumplingError::Build("Circular dependency detected".to_string()));
        }
        
        if visited.contains_key(module_id) {
            return Ok(());
        }
        
        temp_visited.insert(module_id.to_string(), true);
        
        if let Some(deps) = self.dependencies.get(module_id) {
            for (_, dep_id) in deps {
                self.visit(dep_id, visited, temp_visited, result)?;
            }
        }
        
        temp_visited.remove(module_id);
        visited.insert(module_id.to_string(), true);
        result.push(module_id.to_string());
        
        Ok(())
    }
}