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
//! Feature flag analyzer for detecting unused features
//!
//! Analyzes Cargo.toml dependencies to find enabled features that might not be used,
//! potentially reducing binary size by 10-30%.

use thiserror::Error;

/// Errors that can occur during feature analysis
#[derive(Error, Debug)]
pub enum FeatureAnalysisError {
    /// cargo metadata command failed
    #[error("Failed to run cargo metadata: {0}")]
    MetadataCommand(#[from] cargo_metadata::Error),

    /// I/O error
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// UTF-8 conversion error
    #[error("UTF-8 error: {0}")]
    Utf8(#[from] std::string::FromUtf8Error),

    /// cargo tree command failed
    #[error("cargo tree failed")]
    CargoTreeFailed,
}
use crate::infra::{CommandExecutor, RealCommandExecutor};
use cargo_metadata::MetadataCommand;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::Path;

/// Feature flag analyzer
///
/// Identifies potentially unused feature flags in dependencies
/// to reduce WASM bundle size.
///
/// # Examples
///
/// ```no_run
/// use wasm_slim::analyzer::FeatureAnalyzer;
/// use std::path::Path;
///
/// let analyzer = FeatureAnalyzer::new(Path::new("."));
/// let results = analyzer.analyze()?;
///
/// println!("Found {} potentially unused features", results.unused_features.len());
/// println!("Estimated savings: {} KB", results.estimated_savings_kb);
///
/// for feature in &results.unused_features {
///     println!("  {}::{} ({})", feature.package, feature.feature, feature.enabled_by);
/// }
/// # Ok::<(), anyhow::Error>(())
/// ```
pub struct FeatureAnalyzer<CE: CommandExecutor = RealCommandExecutor> {
    project_root: std::path::PathBuf,
    cmd_executor: CE,
}

/// Unused feature detection result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnusedFeature {
    /// Package name
    pub package: String,
    /// Feature name
    pub feature: String,
    /// How the feature is enabled (default, explicit, transitive)
    pub enabled_by: String,
    /// Estimated size impact in KB
    pub estimated_impact_kb: u64,
    /// Confidence level (High, Medium, Low)
    pub confidence: String,
}

/// Complete feature analysis results
#[derive(Debug, Serialize, Deserialize)]
pub struct FeatureAnalysisResults {
    /// Total features analyzed
    pub total_features: usize,
    /// Potentially unused features
    pub unused_features: Vec<UnusedFeature>,
    /// Estimated total savings in KB
    pub estimated_savings_kb: u64,
    /// Recommendations
    pub recommendations: Vec<String>,
}

impl FeatureAnalyzer<RealCommandExecutor> {
    /// Create a new feature analyzer with real command execution
    pub fn new(project_root: impl AsRef<Path>) -> Self {
        Self::with_executor(project_root, RealCommandExecutor)
    }
}

impl<CE: CommandExecutor> FeatureAnalyzer<CE> {
    /// Create a new feature analyzer with a custom command executor
    pub fn with_executor(project_root: impl AsRef<Path>, cmd_executor: CE) -> Self {
        Self {
            project_root: project_root.as_ref().to_path_buf(),
            cmd_executor,
        }
    }

    /// Analyze feature flags in the project
    #[must_use = "Analysis results should be used or printed"]
    pub fn analyze(&self) -> Result<FeatureAnalysisResults, FeatureAnalysisError> {
        // Get cargo metadata
        let metadata = MetadataCommand::new()
            .current_dir(&self.project_root)
            .exec()?;

        // Get feature tree
        let feature_tree = self.get_feature_tree()?;

        let mut unused_features = Vec::new();
        let mut total_features = 0;

        // Analyze each package's features
        for package in &metadata.packages {
            // Skip workspace members (analyze only dependencies)
            if metadata.workspace_members.contains(&package.id) {
                continue;
            }

            // Get enabled features for this package
            let enabled_features = feature_tree
                .get(&package.name.to_string())
                .cloned()
                .unwrap_or_default();

            total_features += enabled_features.len();

            // Check for default features
            if enabled_features.contains("default") && !package.features.is_empty() {
                // Default features are often bloated
                let default_features = package.features.get("default").cloned().unwrap_or_default();

                if !default_features.is_empty() {
                    unused_features.push(UnusedFeature {
                        package: package.name.to_string(),
                        feature: "default".to_string(),
                        enabled_by: "implicit".to_string(),
                        estimated_impact_kb: 50, // Conservative estimate
                        confidence: "Medium".to_string(),
                    });
                }
            }

            // Check for commonly unused features
            for feature in &enabled_features {
                if self.is_commonly_unused_feature(&package.name, feature) {
                    unused_features.push(UnusedFeature {
                        package: package.name.to_string(),
                        feature: feature.clone(),
                        enabled_by: "explicit".to_string(),
                        estimated_impact_kb: self.estimate_feature_impact(&package.name, feature),
                        confidence: self.get_confidence_level(&package.name, feature),
                    });
                }
            }
        }

        // Calculate total estimated savings
        let estimated_savings_kb = unused_features.iter().map(|f| f.estimated_impact_kb).sum();

        // Generate recommendations
        let recommendations = self.generate_recommendations(&unused_features);

        Ok(FeatureAnalysisResults {
            total_features,
            unused_features,
            estimated_savings_kb,
            recommendations,
        })
    }

    /// Get feature tree using cargo tree
    fn get_feature_tree(&self) -> Result<HashMap<String, HashSet<String>>, FeatureAnalysisError> {
        let output = self.cmd_executor.execute(
            |cmd| {
                cmd.arg("tree")
                    .arg("--format")
                    .arg("{p} {f}")
                    .arg("--edges")
                    .arg("normal")
                    .current_dir(&self.project_root)
            },
            "cargo",
        )?;

        if !output.status.success() {
            return Err(FeatureAnalysisError::CargoTreeFailed);
        }

        let stdout = String::from_utf8(output.stdout)?;
        let mut feature_map = HashMap::new();

        for line in stdout.lines() {
            // Parse format: "package_name v0.1.0 feature1,feature2"
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                let package_name = parts[0];

                // Extract features from the rest
                let features_parts: Vec<&str> = parts.iter().skip(1).copied().collect();
                let features_str = features_parts.join(" ");
                let features: HashSet<String> = features_str
                    .split(',')
                    .filter(|s| !s.is_empty() && !s.starts_with('v'))
                    .map(|s| String::from(s.trim()))
                    .collect();

                if !features.is_empty() {
                    feature_map
                        .entry(String::from(package_name))
                        .or_insert_with(HashSet::new)
                        .extend(features);
                }
            }
        }

        Ok(feature_map)
    }

    /// Check if a feature is commonly unused
    fn is_commonly_unused_feature(&self, package: &str, feature: &str) -> bool {
        // Database of commonly unused features by package
        match (package, feature) {
            // Serde features
            ("serde", "rc") => true,
            ("serde", "unstable") => true,

            // Tokio features
            ("tokio", "fs") => true, // Not needed in WASM
            ("tokio", "io-std") => true,
            ("tokio", "process") => true,
            ("tokio", "signal") => true,

            // Regex features
            ("regex", "unicode") => true, // Large, often unnecessary
            ("regex", "unicode-perl") => true,

            // Chrono features
            ("chrono", "clock") => true, // WASM alternatives exist
            ("chrono", "std") => false,  // Usually needed

            // Generic patterns
            (_, "std") if feature == "std" => false, // Usually needed
            (_, f) if f.contains("test") || f.contains("bench") => true,
            (_, f) if f.contains("unstable") || f.contains("nightly") => true,

            _ => false,
        }
    }

    /// Estimate size impact of a feature
    fn estimate_feature_impact(&self, package: &str, feature: &str) -> u64 {
        // Estimates based on common feature sizes
        match (package, feature) {
            ("regex", "unicode") => 300, // Unicode tables are large
            ("tokio", _) => 100,
            ("serde", _) => 20,
            ("chrono", _) => 50,
            (_, "default") => 50,
            _ => 30, // Conservative default
        }
    }

    /// Get confidence level for unused feature detection
    fn get_confidence_level(&self, package: &str, feature: &str) -> String {
        match (package, feature) {
            // High confidence: Well-known bloat features
            ("regex", "unicode") => "High".to_string(),
            ("tokio", "fs") | ("tokio", "process") => "High".to_string(),

            // Medium confidence: Commonly unused
            (_, "default") => "Medium".to_string(),
            (_, f) if f.contains("test") => "High".to_string(),

            // Low confidence: Need manual verification
            _ => "Low".to_string(),
        }
    }

    /// Generate recommendations based on unused features
    fn generate_recommendations(&self, unused_features: &[UnusedFeature]) -> Vec<String> {
        let mut recommendations = Vec::new();

        if unused_features.is_empty() {
            recommendations.push("✅ No obvious unused features detected".to_string());
            return recommendations;
        }

        // Group by package
        let mut by_package: HashMap<String, Vec<&UnusedFeature>> = HashMap::new();
        for feature in unused_features {
            by_package
                .entry(feature.package.clone())
                .or_default()
                .push(feature);
        }

        for (package, features) in by_package {
            if features.iter().any(|f| f.feature == "default") {
                recommendations.push(format!(
                    "Add 'default-features = false' to '{}' in Cargo.toml",
                    package
                ));
            }

            let explicit_features: Vec<_> =
                features.iter().filter(|f| f.feature != "default").collect();

            if !explicit_features.is_empty() {
                let feature_names: Vec<_> = explicit_features
                    .iter()
                    .map(|f| f.feature.as_str())
                    .collect();
                recommendations.push(format!(
                    "Consider removing features {:?} from '{}' if not used",
                    feature_names, package
                ));
            }
        }

        recommendations
    }
}

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

    #[test]
    fn test_is_commonly_unused_feature_identifies_known_features() {
        let analyzer = FeatureAnalyzer::new(".");

        assert!(analyzer.is_commonly_unused_feature("regex", "unicode"));
        assert!(analyzer.is_commonly_unused_feature("tokio", "fs"));
        assert!(!analyzer.is_commonly_unused_feature("serde", "derive"));
    }

    #[test]
    fn test_estimate_feature_impact_returns_size_estimate() {
        let analyzer = FeatureAnalyzer::new(".");

        let impact = analyzer.estimate_feature_impact("regex", "unicode");
        assert!(impact > 100); // Should be significant

        let default_impact = analyzer.estimate_feature_impact("unknown", "default");
        assert!(default_impact > 0);
    }

    #[test]
    fn test_get_confidence_level_returns_correct_level() {
        let analyzer = FeatureAnalyzer::new(".");

        assert_eq!(analyzer.get_confidence_level("regex", "unicode"), "High");
        assert_eq!(
            analyzer.get_confidence_level("unknown", "default"),
            "Medium"
        );
    }

    #[test]
    fn test_generate_recommendations_creates_actionable_suggestions() {
        let analyzer = FeatureAnalyzer::new(".");

        let unused = vec![UnusedFeature {
            package: "serde".to_string(),
            feature: "default".to_string(),
            enabled_by: "implicit".to_string(),
            estimated_impact_kb: 50,
            confidence: "Medium".to_string(),
        }];

        let recs = analyzer.generate_recommendations(&unused);
        assert!(!recs.is_empty());
        assert!(recs[0].contains("default-features = false"));
    }

    #[test]
    fn test_unused_feature_creation() {
        let feature = UnusedFeature {
            package: "test-pkg".to_string(),
            feature: "test-feature".to_string(),
            enabled_by: "default".to_string(),
            estimated_impact_kb: 100,
            confidence: "High".to_string(),
        };

        assert_eq!(feature.package, "test-pkg");
        assert_eq!(feature.feature, "test-feature");
        assert_eq!(feature.estimated_impact_kb, 100);
    }

    #[test]
    fn test_feature_analysis_results_creation() {
        let results = FeatureAnalysisResults {
            total_features: 10,
            unused_features: vec![],
            estimated_savings_kb: 0,
            recommendations: vec!["test".to_string()],
        };

        assert_eq!(results.total_features, 10);
        assert_eq!(results.unused_features.len(), 0);
        assert_eq!(results.recommendations.len(), 1);
    }

    #[test]
    fn test_is_commonly_unused_feature_with_various_packages() {
        let analyzer = FeatureAnalyzer::new(".");

        // Test the function can be called with different inputs
        let _result1 = analyzer.is_commonly_unused_feature("tokio", "fs");
        let _result2 = analyzer.is_commonly_unused_feature("regex", "unicode");
        let _result3 = analyzer.is_commonly_unused_feature("unknown", "feature");

        // Test passes if no panic occurs
    }

    #[test]
    fn test_estimate_feature_impact_for_known_packages() {
        let analyzer = FeatureAnalyzer::new(".");

        // Large features should have higher impact
        let unicode_impact = analyzer.estimate_feature_impact("regex", "unicode");
        let small_impact = analyzer.estimate_feature_impact("unknown", "unknown");

        assert!(unicode_impact > small_impact);
    }

    #[test]
    fn test_get_confidence_level_for_different_packages() {
        let analyzer = FeatureAnalyzer::new(".");

        // Test that the function returns valid confidence levels
        let level1 = analyzer.get_confidence_level("regex", "unicode");
        let level2 = analyzer.get_confidence_level("tokio", "fs");
        let level3 = analyzer.get_confidence_level("unknown", "unknown");

        // Verify the levels are one of the expected values
        assert!(["High", "Medium", "Low"].contains(&level1.as_str()));
        assert!(["High", "Medium", "Low"].contains(&level2.as_str()));
        assert!(["High", "Medium", "Low"].contains(&level3.as_str()));
    }

    #[test]
    fn test_generate_recommendations_with_multiple_unused_features() {
        let analyzer = FeatureAnalyzer::new(".");

        let unused = vec![
            UnusedFeature {
                package: "tokio".to_string(),
                feature: "fs".to_string(),
                enabled_by: "default".to_string(),
                estimated_impact_kb: 100,
                confidence: "High".to_string(),
            },
            UnusedFeature {
                package: "regex".to_string(),
                feature: "unicode".to_string(),
                enabled_by: "default".to_string(),
                estimated_impact_kb: 200,
                confidence: "High".to_string(),
            },
        ];

        let recs = analyzer.generate_recommendations(&unused);
        assert!(!recs.is_empty());
    }

    #[test]
    fn test_generate_recommendations_with_empty_list() {
        let analyzer = FeatureAnalyzer::new(".");
        let recs = analyzer.generate_recommendations(&[]);

        // Should still provide general recommendations
        assert!(!recs.is_empty());
    }

    #[test]
    fn test_feature_analyzer_new_with_different_paths() {
        let analyzer1 = FeatureAnalyzer::new(".");
        let analyzer2 = FeatureAnalyzer::new("/tmp");
        let analyzer3 = FeatureAnalyzer::new("relative/path");

        // All should be created successfully
        assert_eq!(analyzer1.project_root, PathBuf::from("."));
        assert_eq!(analyzer2.project_root, PathBuf::from("/tmp"));
        assert_eq!(analyzer3.project_root, PathBuf::from("relative/path"));
    }
}