use crate::analysis::RetainedSizeAnalyzer;
use crate::parser::{parse_wasm, WasmItemKind};
use anyhow::{Context, Result};
use colored::Colorize;
use humansize::{format_size, BINARY};
use std::path::Path;
pub fn run(path: &Path, json: bool) -> Result<()> {
let parsed = parse_wasm(path).context("Failed to parse WASM file")?;
if !parsed.is_component && parsed.component_exports.is_empty() {
let module_exports: Vec<_> = parsed
.items
.iter()
.filter(|item| item.kind == WasmItemKind::Export)
.collect();
if module_exports.is_empty() {
if json {
println!(
"{}",
serde_json::json!({
"error": "not_component",
"message": "This file is not a WASM component and has no exports",
"is_component": false
})
);
} else {
eprintln!(
"{}: This file is not a WASM component and has no exports.",
"Warning".yellow().bold()
);
eprintln!("For regular WASM modules, use `slimwasm top` to see item sizes.");
}
return Ok(());
}
}
let analyzer = RetainedSizeAnalyzer::new(parsed);
let analysis = analyzer.analyze(true);
if json {
output_json(&analysis, analyzer.parsed())?;
} else {
output_human(&analysis, analyzer.parsed(), path)?;
}
Ok(())
}
fn output_json(
analysis: &crate::analysis::WasmAnalysis,
parsed: &crate::parser::ParsedWasm,
) -> Result<()> {
#[derive(serde::Serialize)]
struct JsonOutput {
total_size: u64,
is_component: bool,
component_exports: Vec<ExportInfo>,
module_exports: Vec<ExportInfo>,
}
#[derive(serde::Serialize)]
struct ExportInfo {
name: String,
kind: String,
size_estimate: u64,
}
let component_exports: Vec<_> = parsed
.component_exports
.iter()
.map(|e| ExportInfo {
name: e.name.clone(),
kind: e.kind.clone(),
size_estimate: e.size_estimate,
})
.collect();
let module_exports: Vec<_> = analysis
.items
.iter()
.filter(|item| item.kind == WasmItemKind::Export)
.map(|item| ExportInfo {
name: item.name.clone(),
kind: "export".to_string(),
size_estimate: item.retained_size,
})
.collect();
let output = JsonOutput {
total_size: analysis.total_size,
is_component: analysis.is_component,
component_exports,
module_exports,
};
println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}
fn output_human(
analysis: &crate::analysis::WasmAnalysis,
parsed: &crate::parser::ParsedWasm,
path: &Path,
) -> Result<()> {
println!();
println!(
"{}",
format!(
" {} - Exports ",
path.file_name().unwrap_or_default().to_string_lossy()
)
.bold()
.white()
.on_blue()
);
println!();
println!(
" Total size: {}",
format_size(analysis.total_size, BINARY).yellow()
);
println!(
" Binary type: {}",
if analysis.is_component {
"WASM Component".cyan()
} else {
"WASM Module".white()
}
);
println!();
if !parsed.component_exports.is_empty() {
println!("{}", "Component Exports:".bold());
for export in &parsed.component_exports {
let kind_colored = match export.kind.as_str() {
"func" => "[func]".green(),
"instance" => "[instance]".cyan(),
"type" => "[type]".yellow(),
"module" => "[module]".magenta(),
_ => format!("[{}]", export.kind).white(),
};
println!(" {} {}", kind_colored, export.name);
}
println!();
}
let exports: Vec<_> = analysis
.items
.iter()
.filter(|item| item.kind == WasmItemKind::Export)
.collect();
if !exports.is_empty() {
println!("{}", "Module Exports:".bold());
let funcs: Vec<_> = analysis
.items
.iter()
.filter(|item| item.kind == WasmItemKind::Function && item.shallow_size > 0)
.collect();
for export in &exports {
let name = &export.name;
let func_size = if name.contains("func") {
funcs
.iter()
.find(|f| export.name.contains(&f.name) || f.name.contains("export"))
.map(|f| f.shallow_size)
.unwrap_or(0)
} else {
0
};
let size_str = if func_size > 0 {
format!(" ({})", format_size(func_size, BINARY))
} else {
String::new()
};
println!(" {} {}{}", "->".green(), name, size_str.dimmed());
}
println!();
}
if analysis.is_component {
println!("{}", "Component Sections:".bold());
let mut sections: Vec<_> = analysis
.section_sizes
.iter()
.filter(|(name, _)| {
name.starts_with("component")
|| name.starts_with("canonical")
|| name.starts_with("alias")
|| name.starts_with("instance")
|| name.starts_with("core")
|| name.starts_with("module")
})
.collect();
sections.sort_by(|a, b| b.1.cmp(a.1));
for (name, size) in sections {
let pct = (*size as f64 / analysis.total_size as f64) * 100.0;
println!(
" {:>10} {:>5.1}% {}",
format_size(*size, BINARY).yellow(),
pct,
name
);
}
println!();
}
let code_size = analysis.section_sizes.get("code").copied().unwrap_or(0);
let data_size = analysis.section_sizes.get("data").copied().unwrap_or(0);
println!("{}", "Summary:".bold());
println!(
" Code: {} ({:.1}%)",
format_size(code_size, BINARY),
(code_size as f64 / analysis.total_size as f64) * 100.0
);
println!(
" Data: {} ({:.1}%)",
format_size(data_size, BINARY),
(data_size as f64 / analysis.total_size as f64) * 100.0
);
println!();
Ok(())
}