wasm-slim 0.1.1

WASM bundle size optimizer
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
//! Template system for wasm-slim optimization presets
//!
//! Provides production-tested optimization templates for different use cases:
//! - `minimal`: Maximum size reduction, may affect performance
//! - `balanced`: Warp-style settings (opt-level="s", lto=true) - recommended
//! - `aggressive`: All optimizations enabled, maximum reduction
//! - Framework-specific: Yew, Leptos, Dioxus presets
//!
//! # Examples
//!
//! ```no_run
//! use wasm_slim::config::{Template, TemplateType};
//!
//! // Use a preset
//! let template = Template::new(TemplateType::Balanced);
//! println!("Using: {}", template.name);
//!
//! // Customize with builder
//! use wasm_slim::config::TemplateBuilder;
//! let custom = TemplateBuilder::from_template(&template)
//!     .with_opt_level("3")
//!     .build();
//! ```

use serde::{Deserialize, Serialize};
use std::str::FromStr;

use super::profile_config::ProfileConfig;
use super::wasm_config::{WasmBindgenConfig, WasmOptConfig};

/// Template type identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TemplateType {
    /// Minimal size, may impact performance
    Minimal,
    /// Balanced size/performance (Warp-validated, recommended)
    Balanced,
    /// Maximum size reduction with all optimizations
    Aggressive,
    /// Yew framework optimizations
    Yew,
    /// Leptos framework optimizations
    Leptos,
    /// Dioxus framework optimizations
    Dioxus,
    /// User-defined custom template
    Custom,
}

impl FromStr for TemplateType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "minimal" => Ok(Self::Minimal),
            "balanced" => Ok(Self::Balanced),
            "aggressive" => Ok(Self::Aggressive),
            "yew" => Ok(Self::Yew),
            "leptos" => Ok(Self::Leptos),
            "dioxus" => Ok(Self::Dioxus),
            "custom" => Ok(Self::Custom),
            _ => Err(format!("Unknown template type: {}", s)),
        }
    }
}

impl TemplateType {
    /// Get template name
    pub fn name(&self) -> &'static str {
        match self {
            Self::Minimal => "minimal",
            Self::Balanced => "balanced",
            Self::Aggressive => "aggressive",
            Self::Yew => "yew",
            Self::Leptos => "leptos",
            Self::Dioxus => "dioxus",
            Self::Custom => "custom",
        }
    }

    /// Get template description
    pub fn description(&self) -> &'static str {
        match self {
            Self::Minimal => "Maximum size reduction, may affect performance",
            Self::Balanced => "Balanced size/performance (Warp-validated, recommended)",
            Self::Aggressive => "All optimizations enabled, maximum reduction",
            Self::Yew => "Optimized for Yew framework projects",
            Self::Leptos => "Optimized for Leptos framework projects",
            Self::Dioxus => "Optimized for Dioxus framework projects",
            Self::Custom => "User-defined custom configuration",
        }
    }
}

/// Complete optimization template
///
/// Provides pre-configured optimization settings for different use cases:
/// - **minimal**: Maximum size reduction (may affect performance)
/// - **balanced**: Size/performance balance (recommended, Warp-validated)
/// - **aggressive**: Aggressive optimizations
/// - Framework-specific: **yew**, **leptos**, **dioxus**
///
/// # Examples
///
/// ```
/// use wasm_slim::config::{Template, TemplateType};
///
/// // Get the balanced template (recommended)
/// let template = Template::new(TemplateType::Balanced);
/// println!("Using template: {}", template.name);
/// println!("Description: {}", template.description);
///
/// // Get a template by name
/// if let Some(template) = Template::get("minimal") {
///     println!("Found template: {}", template.name);
/// }
///
/// // List all available templates
/// for name in Template::names() {
///     println!("Available: {}", name);
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Template {
    /// Template type
    pub template_type: TemplateType,
    /// Template name
    pub name: String,
    /// Template description
    pub description: String,
    /// Cargo profile settings
    pub profile: ProfileConfig,
    /// wasm-opt settings
    pub wasm_opt: WasmOptConfig,
    /// wasm-bindgen settings
    pub wasm_bindgen: WasmBindgenConfig,
    /// Recommended dependencies to optimize
    pub dependency_hints: Vec<String>,
    /// Additional notes
    pub notes: Vec<String>,
}

impl Template {
    /// Create a new template with defaults
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm_slim::config::{Template, TemplateType};
    ///
    /// let minimal = Template::new(TemplateType::Minimal);
    /// assert_eq!(minimal.name, "minimal");
    ///
    /// let balanced = Template::new(TemplateType::Balanced);
    /// assert_eq!(balanced.name, "balanced");
    /// ```
    pub fn new(template_type: TemplateType) -> Self {
        match template_type {
            TemplateType::Minimal => Self::minimal(),
            TemplateType::Balanced => Self::balanced(),
            TemplateType::Aggressive => Self::aggressive(),
            TemplateType::Yew => Self::yew(),
            TemplateType::Leptos => Self::leptos(),
            TemplateType::Dioxus => Self::dioxus(),
            TemplateType::Custom => Self::custom(),
        }
    }

    /// Minimal template - maximum size reduction
    fn minimal() -> Self {
        Self {
            template_type: TemplateType::Minimal,
            name: "minimal".to_string(),
            description: "Maximum size reduction, may affect performance".to_string(),
            profile: ProfileConfig {
                opt_level: "z".to_string(),
                lto: "fat".to_string(),
                strip: true,
                codegen_units: 1,
                panic: "abort".to_string(),
            },
            wasm_opt: WasmOptConfig {
                flags: vec![
                    "-Oz".to_string(),
                    "--enable-mutable-globals".to_string(),
                    "--enable-bulk-memory".to_string(),
                    "--enable-sign-ext".to_string(),
                    "--enable-nontrapping-float-to-int".to_string(),
                    "--strip-debug".to_string(),
                    "--strip-dwarf".to_string(),
                    "--strip-producers".to_string(),
                ],
            },
            wasm_bindgen: WasmBindgenConfig {
                debug: false,
                remove_producers_section: true,
                flags: vec![],
            },
            dependency_hints: vec![
                "Set default-features = false on all dependencies".to_string(),
                "Use getrandom with wasm_js feature".to_string(),
            ],
            notes: vec![
                "Prioritizes size over performance".to_string(),
                "May increase compile time significantly".to_string(),
            ],
        }
    }

    /// Balanced template - Warp-validated settings (RECOMMENDED)
    fn balanced() -> Self {
        Self {
            template_type: TemplateType::Balanced,
            name: "balanced".to_string(),
            description: "Balanced size/performance (Warp-validated, recommended)".to_string(),
            profile: ProfileConfig {
                opt_level: "s".to_string(),
                lto: "fat".to_string(),
                strip: true,
                codegen_units: 1,
                panic: "abort".to_string(),
            },
            wasm_opt: WasmOptConfig {
                flags: vec![
                    "-Oz".to_string(),
                    "--enable-mutable-globals".to_string(),
                    "--enable-bulk-memory".to_string(),
                    "--enable-sign-ext".to_string(),
                    "--enable-nontrapping-float-to-int".to_string(),
                    "--strip-debug".to_string(),
                    "--strip-dwarf".to_string(),
                    "--strip-producers".to_string(),
                ],
            },
            wasm_bindgen: WasmBindgenConfig {
                debug: false,
                remove_producers_section: true,
                flags: vec![],
            },
            dependency_hints: vec![
                "Minimize feature flags where possible".to_string(),
                "Use getrandom with wasm_js feature".to_string(),
            ],
            notes: vec![
                "Production-tested by Warp.dev (62% size reduction)".to_string(),
                "Good balance between size and performance".to_string(),
                "Recommended for most projects".to_string(),
            ],
        }
    }

    /// Aggressive template - all optimizations enabled
    fn aggressive() -> Self {
        Self {
            template_type: TemplateType::Aggressive,
            name: "aggressive".to_string(),
            description: "All optimizations enabled, maximum reduction".to_string(),
            profile: ProfileConfig {
                opt_level: "z".to_string(),
                lto: "fat".to_string(),
                strip: true,
                codegen_units: 1,
                panic: "abort".to_string(),
            },
            wasm_opt: WasmOptConfig {
                flags: vec![
                    "-Oz".to_string(),
                    "--enable-mutable-globals".to_string(),
                    "--enable-bulk-memory".to_string(),
                    "--enable-sign-ext".to_string(),
                    "--enable-nontrapping-float-to-int".to_string(),
                    "--strip-debug".to_string(),
                    "--strip-dwarf".to_string(),
                    "--strip-producers".to_string(),
                    "--vacuum".to_string(),
                    "--closed-world".to_string(),
                    "--gufa-optimizing".to_string(),
                ],
            },
            wasm_bindgen: WasmBindgenConfig {
                debug: false,
                remove_producers_section: true,
                flags: vec!["--omit-default-module-path".to_string()],
            },
            dependency_hints: vec![
                "Set default-features = false on ALL dependencies".to_string(),
                "Use getrandom with wasm_js feature".to_string(),
                "Consider lighter alternatives for heavy deps".to_string(),
                "Externalize assets (fonts, images)".to_string(),
            ],
            notes: vec![
                "Maximum size reduction at all costs".to_string(),
                "Significantly longer compile times".to_string(),
                "May affect runtime performance".to_string(),
                "Use for production builds with strict size budgets".to_string(),
                "Use nightly Rust for build-std (additional 10-20% reduction)".to_string(),
            ],
        }
    }

    /// Yew framework template
    fn yew() -> Self {
        let mut template = Self::balanced();
        template.template_type = TemplateType::Yew;
        template.name = "yew".to_string();
        template.description = "Optimized for Yew framework projects".to_string();
        template.dependency_hints = vec![
            "yew = { version = \"*\", default-features = false }".to_string(),
            "Use yew-router with minimal features".to_string(),
            "Avoid heavy dependencies in components".to_string(),
            "Consider code-splitting for large apps".to_string(),
        ];
        template.notes = vec![
            "Based on balanced template".to_string(),
            "Optimized for Yew's component model".to_string(),
            "Minimizes framework overhead".to_string(),
        ];
        template
    }

    /// Leptos framework template
    fn leptos() -> Self {
        let mut template = Self::balanced();
        template.template_type = TemplateType::Leptos;
        template.name = "leptos".to_string();
        template.description = "Optimized for Leptos framework projects".to_string();
        template.dependency_hints = vec![
            "leptos = { version = \"*\", default-features = false }".to_string(),
            "Enable only needed features (csr, hydrate, ssr)".to_string(),
            "Use leptos_router with minimal features".to_string(),
            "Leverage Leptos's fine-grained reactivity".to_string(),
        ];
        template.notes = vec![
            "Based on balanced template".to_string(),
            "Optimized for Leptos's fine-grained reactivity".to_string(),
            "Supports both CSR and SSR modes".to_string(),
            "Use nightly + build-std for 10-20% additional reduction".to_string(),
            "Consider lightweight serialization (miniserde, serde-lite)".to_string(),
        ];
        template
    }

    /// Dioxus framework template
    fn dioxus() -> Self {
        let mut template = Self::balanced();
        template.template_type = TemplateType::Dioxus;
        template.name = "dioxus".to_string();
        template.description = "Optimized for Dioxus framework projects".to_string();
        template.dependency_hints = vec![
            "dioxus = { version = \"*\", default-features = false }".to_string(),
            "Enable only target features (web, desktop, mobile)".to_string(),
            "Use dioxus-router with minimal features".to_string(),
            "Leverage Dioxus's virtual DOM efficiently".to_string(),
        ];
        template.notes = vec![
            "Based on balanced template".to_string(),
            "Optimized for Dioxus's component model".to_string(),
            "Supports multiple platforms".to_string(),
        ];
        template
    }

    /// Custom template - user-defined
    fn custom() -> Self {
        Self {
            template_type: TemplateType::Custom,
            name: "custom".to_string(),
            description: "User-defined custom configuration".to_string(),
            profile: ProfileConfig {
                opt_level: "s".to_string(),
                lto: "fat".to_string(),
                strip: true,
                codegen_units: 1,
                panic: "abort".to_string(),
            },
            wasm_opt: WasmOptConfig {
                flags: vec!["-Oz".to_string()],
            },
            wasm_bindgen: WasmBindgenConfig {
                debug: false,
                remove_producers_section: false,
                flags: vec![],
            },
            dependency_hints: vec![],
            notes: vec!["Customize this template in .wasm-slim.toml".to_string()],
        }
    }

    /// Get all available template types
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm_slim::config::Template;
    ///
    /// let templates = Template::available_templates();
    /// assert!(!templates.is_empty());
    /// assert!(templates.len() >= 6); // minimal, balanced, aggressive, yew, leptos, dioxus
    /// ```
    pub fn available_templates() -> Vec<TemplateType> {
        vec![
            TemplateType::Minimal,
            TemplateType::Balanced,
            TemplateType::Aggressive,
            TemplateType::Yew,
            TemplateType::Leptos,
            TemplateType::Dioxus,
        ]
    }

    /// Get a template by name (data-driven lookup)
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm_slim::config::Template;
    ///
    /// // Get a template by name
    /// let template = Template::get("balanced").expect("balanced template exists");
    /// assert_eq!(template.name, "balanced");
    ///
    /// // Invalid name returns None
    /// assert!(Template::get("nonexistent").is_none());
    /// ```
    pub fn get(name: &str) -> Option<Self> {
        TemplateType::from_str(name).ok().map(Self::new)
    }

    /// Get all template names (sorted alphabetically)
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm_slim::config::Template;
    ///
    /// let names = Template::names();
    /// assert!(names.contains(&"minimal".to_string()));
    /// assert!(names.contains(&"balanced".to_string()));
    /// assert!(names.contains(&"aggressive".to_string()));
    ///
    /// // Names are sorted alphabetically
    /// let mut sorted_names = names.clone();
    /// sorted_names.sort();
    /// assert_eq!(names, sorted_names);
    /// ```
    pub fn names() -> Vec<String> {
        let mut names: Vec<String> = Self::available_templates()
            .iter()
            .map(|t| t.name().to_string())
            .collect();
        names.sort();
        names
    }

    /// Get all templates (sorted by name)
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm_slim::config::Template;
    ///
    /// let templates = Template::all();
    /// assert!(!templates.is_empty());
    ///
    /// // Verify templates are sorted by name
    /// for i in 1..templates.len() {
    ///     assert!(templates[i-1].name <= templates[i].name);
    /// }
    /// ```
    pub fn all() -> Vec<Self> {
        let mut templates: Vec<Self> = Self::available_templates()
            .into_iter()
            .map(Self::new)
            .collect();
        templates.sort_by(|a, b| a.name.cmp(&b.name));
        templates
    }
}

/// Builder for customizing templates
pub struct TemplateBuilder {
    template: Template,
}

impl TemplateBuilder {
    /// Create a builder from a template
    pub fn from_template(template: &Template) -> Self {
        Self {
            template: template.clone(),
        }
    }

    /// Set optimization level
    pub fn with_opt_level(mut self, opt_level: &str) -> Self {
        self.template.profile.opt_level = opt_level.to_string();
        self
    }

    /// Set LTO mode
    pub fn with_lto(mut self, lto: &str) -> Self {
        self.template.profile.lto = lto.to_string();
        self
    }

    /// Set strip option
    pub fn with_strip(mut self, strip: bool) -> Self {
        self.template.profile.strip = strip;
        self
    }

    /// Set codegen units
    pub fn with_codegen_units(mut self, units: u32) -> Self {
        self.template.profile.codegen_units = units;
        self
    }

    /// Set panic mode
    pub fn with_panic(mut self, panic: &str) -> Self {
        self.template.profile.panic = panic.to_string();
        self
    }

    /// Set wasm-opt flags
    pub fn with_wasm_opt_flags(mut self, flags: Vec<String>) -> Self {
        self.template.wasm_opt.flags = flags;
        self
    }

    /// Build the final template
    pub fn build(self) -> Template {
        self.template
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_template_methods() {
        let minimal = Template::new(TemplateType::Minimal);
        assert_eq!(minimal.name, "minimal");
        assert_eq!(minimal.profile.opt_level, "z");

        let balanced = Template::new(TemplateType::Balanced);
        assert_eq!(balanced.name, "balanced");
        assert_eq!(balanced.profile.opt_level, "s");
    }

    #[test]
    fn test_template_get_by_name() {
        assert!(Template::get("minimal").is_some());
        assert!(Template::get("balanced").is_some());
        assert!(Template::get("nonexistent").is_none());
    }

    #[test]
    fn test_template_builder() {
        let custom = TemplateBuilder::from_template(&Template::new(TemplateType::Balanced))
            .with_opt_level("3")
            .with_codegen_units(8)
            .build();

        assert_eq!(custom.profile.opt_level, "3");
        assert_eq!(custom.profile.codegen_units, 8);
    }

    #[test]
    fn test_template_type_from_str_parses_case_insensitively() {
        assert_eq!(TemplateType::from_str("minimal"), Ok(TemplateType::Minimal));
        assert_eq!(
            TemplateType::from_str("Balanced"),
            Ok(TemplateType::Balanced)
        );
        assert_eq!(
            TemplateType::from_str("AGGRESSIVE"),
            Ok(TemplateType::Aggressive)
        );
        assert_eq!(TemplateType::from_str("yew"), Ok(TemplateType::Yew));
        assert!(TemplateType::from_str("invalid").is_err());
    }

    #[test]
    fn test_template_new_creates_with_correct_defaults() {
        let minimal = Template::new(TemplateType::Minimal);
        assert_eq!(minimal.name, "minimal");
        assert_eq!(minimal.profile.opt_level, "z");

        let balanced = Template::new(TemplateType::Balanced);
        assert_eq!(balanced.name, "balanced");
        assert_eq!(balanced.profile.opt_level, "s");

        let aggressive = Template::new(TemplateType::Aggressive);
        assert_eq!(aggressive.name, "aggressive");
        assert!(aggressive.wasm_opt.flags.len() > 8);
    }

    #[test]
    fn test_template_new_for_frameworks_includes_dependency_hints() {
        let yew = Template::new(TemplateType::Yew);
        assert_eq!(yew.name, "yew");
        assert!(!yew.dependency_hints.is_empty());

        let leptos = Template::new(TemplateType::Leptos);
        assert_eq!(leptos.name, "leptos");

        let dioxus = Template::new(TemplateType::Dioxus);
        assert_eq!(dioxus.name, "dioxus");
    }

    #[test]
    fn test_template_get_and_all_work_correctly() {
        assert!(Template::get("balanced").is_some());
        assert!(Template::get("minimal").is_some());
        assert!(Template::get("yew").is_some());
        assert!(Template::get("invalid").is_none());

        let templates = Template::all();
        assert_eq!(templates.len(), 6);

        let names = Template::names();
        assert!(names.contains(&"balanced".to_string()));
    }

    #[test]
    fn test_template_balanced_matches_warp_configuration() {
        let balanced = Template::new(TemplateType::Balanced);
        assert_eq!(balanced.profile.opt_level, "s");
        assert_eq!(balanced.profile.lto, "fat");
        assert!(balanced.profile.strip);
        assert!(balanced.notes.iter().any(|n| n.contains("Warp")));
    }

    #[test]
    fn test_template_type_from_str_handles_any_case() {
        assert_eq!(TemplateType::from_str("minimal"), Ok(TemplateType::Minimal));
        assert_eq!(TemplateType::from_str("MINIMAL"), Ok(TemplateType::Minimal));
        assert_eq!(TemplateType::from_str("MiNiMaL"), Ok(TemplateType::Minimal));
        assert_eq!(
            TemplateType::from_str("Balanced"),
            Ok(TemplateType::Balanced)
        );
        assert_eq!(
            TemplateType::from_str("BALANCED"),
            Ok(TemplateType::Balanced)
        );
    }

    #[test]
    fn test_template_type_from_str_with_invalid_names_returns_error() {
        assert!(TemplateType::from_str("invalid").is_err());
        assert!(TemplateType::from_str("").is_err());
        assert!(TemplateType::from_str("min").is_err());
        assert!(TemplateType::from_str("minimall").is_err());
        assert!(TemplateType::from_str("balance").is_err());
        assert!(TemplateType::from_str("react").is_err());
    }

    #[test]
    fn test_template_type_from_str_error_messages_are_descriptive() {
        let err = TemplateType::from_str("invalid").unwrap_err();
        assert!(err.contains("Unknown template type"));
        assert!(err.contains("invalid"));
    }

    #[test]
    fn test_template_get_with_nonexistent_name_returns_none() {
        assert!(Template::get("nonexistent").is_none());
        assert!(Template::get("").is_none());
        assert!(Template::get("react").is_none());
        assert!(Template::get("vue").is_none());
    }

    #[test]
    fn test_template_contains_all_expected_templates() {
        assert!(Template::get("minimal").is_some());
        assert!(Template::get("balanced").is_some());
        assert!(Template::get("aggressive").is_some());
        assert!(Template::get("yew").is_some());
        assert!(Template::get("leptos").is_some());
        assert!(Template::get("dioxus").is_some());

        let templates = Template::all();
        assert_eq!(templates.len(), 6);
    }

    #[test]
    fn test_template_names_returns_sorted_list() {
        let names = Template::names();

        let mut sorted_names = names.clone();
        sorted_names.sort();
        assert_eq!(names, sorted_names);
    }

    #[test]
    fn test_template_all_returns_sorted_by_name() {
        let templates = Template::all();

        for i in 1..templates.len() {
            assert!(templates[i - 1].name <= templates[i].name);
        }
    }

    #[test]
    fn test_template_type_all_variants_have_valid_names() {
        let types = vec![
            TemplateType::Minimal,
            TemplateType::Balanced,
            TemplateType::Aggressive,
            TemplateType::Yew,
            TemplateType::Leptos,
            TemplateType::Dioxus,
            TemplateType::Custom,
        ];

        for template_type in types {
            let name = template_type.name();
            assert!(!name.is_empty());
            assert!(name.chars().all(|c| c.is_ascii_lowercase() || c == '-'));
        }
    }

    #[test]
    fn test_template_type_all_variants_have_descriptions() {
        let types = vec![
            TemplateType::Minimal,
            TemplateType::Balanced,
            TemplateType::Aggressive,
            TemplateType::Yew,
            TemplateType::Leptos,
            TemplateType::Dioxus,
            TemplateType::Custom,
        ];

        for template_type in types {
            let desc = template_type.description();
            assert!(!desc.is_empty());
            assert!(desc.chars().next().unwrap().is_uppercase());
        }
    }

    #[test]
    fn test_template_profile_settings_are_valid() {
        let templates = vec![
            Template::new(TemplateType::Minimal),
            Template::new(TemplateType::Balanced),
            Template::new(TemplateType::Aggressive),
        ];

        for template in templates {
            assert!(["s", "z", "3"].contains(&template.profile.opt_level.as_str()));
            assert!(["fat", "thin", "true", "false"].contains(&template.profile.lto.as_str()));
            assert!(template.profile.codegen_units >= 1 && template.profile.codegen_units <= 256);
            assert!(["abort", "unwind"].contains(&template.profile.panic.as_str()));
        }
    }

    #[test]
    fn test_template_wasm_opt_flags_are_valid() {
        let templates = vec![
            Template::new(TemplateType::Minimal),
            Template::new(TemplateType::Balanced),
            Template::new(TemplateType::Aggressive),
        ];

        for template in templates {
            assert!(!template.wasm_opt.flags.is_empty());
            for flag in &template.wasm_opt.flags {
                assert!(flag.starts_with("-"), "Flag '{}' should start with -", flag);
            }
        }
    }

    #[test]
    fn test_template_framework_variants_have_dependency_hints() {
        let yew = Template::new(TemplateType::Yew);
        assert!(!yew.dependency_hints.is_empty());

        let leptos = Template::new(TemplateType::Leptos);
        assert!(!leptos.dependency_hints.is_empty());

        let dioxus = Template::new(TemplateType::Dioxus);
        assert!(!dioxus.dependency_hints.is_empty());
    }

    #[test]
    fn test_template_clone_preserves_all_fields() {
        let original = Template::new(TemplateType::Balanced);
        let cloned = original.clone();

        assert_eq!(original.name, cloned.name);
        assert_eq!(original.profile.opt_level, cloned.profile.opt_level);
        assert_eq!(original.wasm_opt.flags, cloned.wasm_opt.flags);
    }

    #[test]
    fn test_template_type_all_variants_can_be_parsed() {
        let types = vec![
            (TemplateType::Minimal, "minimal"),
            (TemplateType::Balanced, "balanced"),
            (TemplateType::Aggressive, "aggressive"),
            (TemplateType::Yew, "yew"),
            (TemplateType::Leptos, "leptos"),
            (TemplateType::Dioxus, "dioxus"),
            (TemplateType::Custom, "custom"),
        ];

        for (expected_type, name) in types {
            let parsed = TemplateType::from_str(name).unwrap();
            assert_eq!(parsed, expected_type);
            assert_eq!(expected_type.name(), name);
        }
    }
}