ModuleGraph

Struct ModuleGraph 

Source
pub struct ModuleGraph { /* private fields */ }
Expand description

In-memory module dependency graph.

This implementation uses HashMaps for fast lookups and is fully synchronous.

Implementations§

Source§

impl ModuleGraph

Source

pub fn dependency_chains_to( &self, target: &ModuleId, ) -> Result<Vec<DependencyChain>>

Find all dependency chains from entry points to a target module.

This traces all possible paths through the import graph, useful for understanding why a module is included in the bundle and what depends on it.

Source

pub fn analyze_dependency_chains( &self, target: &ModuleId, ) -> Result<ChainAnalysis>

Analyze dependency chains to a module.

Provides comprehensive statistics about all paths leading to a module.

Source

pub fn import_depth(&self, module: &ModuleId) -> Result<Option<usize>>

Get the import depth of a module from entry points.

Returns the shortest distance from any entry point to this module, or None if the module is unreachable.

Source

pub fn modules_by_depth(&self) -> Result<HashMap<usize, Vec<ModuleId>>>

Group modules by their import depth from entry points.

This creates layers of the dependency graph, useful for visualizing the structure and understanding module organization.

Source

pub fn is_reachable_only_through_dead_code( &self, module: &ModuleId, ) -> Result<bool>

Check if a module is only reachable through dead code.

A module is considered “reachable only through dead code” if:

  • It has no direct path from any entry point, OR
  • All paths to it go through unreachable modules

This is a strong indicator that the module can be safely removed.

Source§

impl ModuleGraph

Source

pub fn new() -> Result<Self>

Create a new empty graph.

Source

pub fn from_modules<I>(modules: I) -> Result<Self>
where I: IntoIterator<Item = Module>,

Construct a graph from an iterator of modules (without edges).

Source

pub fn from_collected_data(collection: CollectionState) -> Result<Self>

Create a ModuleGraph from collected module data.

Source§

impl ModuleGraph

Source

pub fn unused_exports(&self) -> Result<Vec<UnusedExport>>

Discover unused exports, respecting framework markers and namespace imports.

Source

pub fn compute_export_usage_counts(&self) -> Result<()>

Computes and sets usage counts for all exports in the module graph.

For each export in each module, this counts how many times it’s imported across all dependent modules and updates the usage_count field.

Usage counts are determined by:

  • Named imports: Each import { foo } increments the count for export “foo”
  • Default imports: Each import foo increments the count for export “default”
  • Namespace imports: Each import * as ns increments the count for ALL exports by 1 (except star re-exports which only forward, not consume)
  • Re-exports: Counted separately as they create new import paths

After calling this method, each Export will have usage_count set to:

  • Some(0) if the export is unused
  • Some(n) where n > 0 for the number of import sites
Source§

impl ModuleGraph

Source

pub async fn apply_framework_rule( &self, rule: Box<dyn FrameworkRule>, ) -> Result<()>

Apply a custom framework rule.

Framework rules mark exports as framework-used based on naming conventions. This prevents false-positive “unused export” warnings.

Note: FrameworkRule::apply is async, so we use tokio::runtime::Handle::current() to execute it. This maintains compatibility with the async trait while Apply a single framework rule asynchronously.

§Platform Availability

This method is only available on native platforms (not WASM) because it requires tokio runtime support.

Source

pub async fn apply_framework_rules( &self, rules: Vec<Box<dyn FrameworkRule>>, ) -> Result<()>

Apply multiple framework rules asynchronously.

§Platform Availability

This method is only available on native platforms (not WASM) because it requires tokio runtime support.

Source

pub fn has_dependency(&self, from: &ModuleId, to: &ModuleId) -> Result<bool>

Check if a direct dependency exists between two modules.

Source

pub fn framework_used_exports(&self) -> Result<Vec<(ModuleId, Export)>>

Get all framework-used exports in the graph.

Source§

impl ModuleGraph

Source

pub fn side_effect_only_imports(&self) -> Result<Vec<SideEffectImport>>

Get all side-effect-only imports across the graph.

Side-effect imports like import 'polyfill' execute code but don’t bind any values. These are important to track as they can’t be tree-shaken and always contribute to bundle size.

Source

pub fn namespace_imports(&self) -> Result<Vec<NamespaceImportInfo>>

Get all namespace imports and their usage.

Namespace imports (import * as foo) import all exports from a module. This is useful for tracking potential over-imports that could be optimized to named imports.

Source

pub fn type_only_imports(&self) -> Result<Vec<TypeOnlyImport>>

Get all type-only imports (TypeScript).

Type-only imports are erased at runtime and don’t contribute to bundle size. Tracking these helps understand the TypeScript structure without conflating with runtime dependencies.

Source§

impl ModuleGraph

Source

pub fn add_module(&self, module: Module) -> Result<()>

Add a module into the graph.

Source

pub fn add_dependency(&self, from: ModuleId, to: ModuleId) -> Result<()>

Add a dependency edge, creating forward and reverse mappings.

Source

pub fn add_dependencies<I>(&self, from: ModuleId, targets: I) -> Result<()>
where I: IntoIterator<Item = ModuleId>,

Add multiple dependencies from a single module.

Source

pub fn add_entry_point(&self, id: ModuleId) -> Result<()>

Mark a module as an entry point.

Source

pub fn add_external_dependency(&self, dep: ExternalDependency) -> Result<()>

Add an external dependency record.

Source§

impl ModuleGraph

Source

pub fn unused_npm_dependencies( &self, package_json: &PackageJson, include_dev: bool, include_peer: bool, ) -> Result<Vec<UnusedDependency>>

Detect unused npm dependencies by cross-referencing package.json with imports.

This identifies dependencies declared in package.json but never actually imported in the codebase. Useful for cleaning up unused packages.

§Parameters
  • package_json: Parsed package.json file
  • include_dev: Whether to check devDependencies
  • include_peer: Whether to check peerDependencies
Source

pub fn dependency_coverage( &self, package_json: &PackageJson, ) -> Result<DependencyCoverage>

Get dependency coverage statistics.

Provides detailed metrics about which dependencies are actually used vs declared in package.json.

Source§

impl ModuleGraph

Source

pub fn module(&self, id: &ModuleId) -> Result<Option<Module>>

Retrieve a module by ID.

Returns an owned Module. Internally uses Arc for efficient storage, so this clone is inexpensive (only shared data like Vec are reference-counted).

§Example
let module = graph.module(module_id)?.unwrap();
println!("Path: {}", module.path.display());
Source

pub fn module_by_path(&self, path: &Path) -> Result<Option<Module>>

Get module by filesystem path.

Returns an owned Module. Internally uses Arc for efficient storage, so this clone is inexpensive.

Source

pub fn modules(&self) -> Result<Vec<Module>>

Get all modules.

Returns owned Module instances. Internally uses Arc for efficient storage, so these clones are inexpensive.

Source

pub fn dependencies(&self, id: &ModuleId) -> Result<Vec<ModuleId>>

Dependencies of a module (forward edges).

Source

pub fn dependents(&self, id: &ModuleId) -> Result<Vec<ModuleId>>

Dependents of a module (reverse edges).

Source

pub fn contains(&self, id: &ModuleId) -> Result<bool>

Whether a module is present.

Source

pub fn entry_points(&self) -> Result<Vec<ModuleId>>

Entry points set.

Source

pub fn len(&self) -> Result<usize>

Return total module count.

Source

pub fn is_empty(&self) -> Result<bool>

Check whether graph is empty.

Source

pub fn imports_for_module(&self, id: &ModuleId) -> Result<Option<Vec<Import>>>

Get imports for a module.

Source

pub fn external_dependencies(&self) -> Result<Vec<ExternalDependency>>

Aggregate external dependencies based on import data.

Source

pub fn unreachable_modules(&self) -> Result<Vec<Module>>

Compute modules with no dependents and no side effects.

Returns owned Module instances. Internally uses Arc for efficient storage, so these clones are inexpensive.

Source§

impl ModuleGraph

Source

pub fn to_dot_format(&self) -> Result<String>

Export the graph as DOT format for visualization.

Source

pub fn to_json(&self) -> Result<String>

Export the graph and modules to JSON.

Source

pub fn to_bytes(&self) -> Result<Vec<u8>>

Serialize the graph to binary format using bincode.

This includes a format version for forward compatibility and the full graph state (modules, dependencies, dependents, entry points, external deps).

§Format Version

The binary format starts with a u32 version number:

  • Version 1: Initial implementation with GraphInner serialization
§Errors

Returns an error if serialization fails or if the graph is poisoned.

Source

pub fn from_bytes(bytes: &[u8]) -> Result<Self>

Deserialize the graph from binary format.

§Errors

Returns an error if:

  • Deserialization fails
  • The format version is incompatible with the current implementation
Source§

impl ModuleGraph

Source

pub fn statistics(&self) -> Result<GraphStatistics>

Compute statistics snapshot for dashboards.

Source§

impl ModuleGraph

Source

pub fn unused_symbols(&self) -> Result<Vec<UnusedSymbol>>

Get all unused symbols across the entire graph.

This queries the symbol table for each module and returns symbols that are declared but never referenced.

Source

pub fn unused_symbols_in_module(&self, id: &ModuleId) -> Result<Vec<Symbol>>

Get unused symbols for a specific module.

Returns an empty vector if the module doesn’t exist.

Source

pub fn all_symbols(&self) -> Result<Vec<UnusedSymbol>>

Get all symbols across the entire graph (not just unused ones).

This is useful for code quality analysis that needs to check all symbols, regardless of whether they’re used or not.

Source

pub fn unreachable_code(&self) -> Result<Vec<UnreachableCode>>

Get unreachable code detected across the graph.

Note: Unreachable code detection must be performed during module analysis (when source code is available) rather than from the graph. Use crate::graph::semantic::detect_unreachable_code() during module building.

This method currently returns an empty vector as a placeholder for graph-level aggregation if unreachable code data is stored in modules in the future.

Source

pub fn symbol_statistics(&self) -> Result<SymbolStatistics>

Compute symbol statistics across the entire graph.

Aggregates symbol information from all modules to provide a high-level view of symbol usage patterns.

Source

pub fn unused_private_class_members( &self, ) -> Result<HashMap<String, Vec<UnusedSymbol>>>

Get all unused private class members across the graph, grouped by class.

Private class members are safe to remove when unused, as they cannot be accessed from outside the class. This method groups results by class name for easier analysis.

Source

pub fn all_class_members(&self) -> Result<Vec<ClassMemberInfo>>

Get all class members (public and private) for comprehensive analysis.

This provides complete visibility into class structure, useful for refactoring and understanding class complexity.

Source

pub fn unused_public_class_members(&self) -> Result<Vec<UnusedSymbol>>

Get unused public class members.

Warning: Removing public members is potentially breaking for library code. Use with caution and only for application code where you control all usage.

Source

pub fn unused_enum_members(&self) -> Result<HashMap<String, Vec<UnusedSymbol>>>

Get all unused enum members across the graph, grouped by enum.

Enum members that are never referenced can often be safely removed, especially in application code. This groups results by enum for easier analysis.

Source

pub fn all_enum_members(&self) -> Result<HashMap<String, Vec<EnumMemberInfo>>>

Get all enum members (used and unused) for comprehensive enum analysis.

This provides complete visibility into enum structure, useful for understanding enum coverage and usage patterns.

Source§

impl ModuleGraph

Source

pub fn depends_on(&self, from: &ModuleId, to: &ModuleId) -> Result<bool>

Returns true if from depends on to (directly or transitively).

Source

pub fn transitive_dependencies( &self, id: &ModuleId, ) -> Result<HashSet<ModuleId>>

Collect transitive dependencies of a module.

Trait Implementations§

Source§

impl Clone for ModuleGraph

Source§

fn clone(&self) -> ModuleGraph

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ModuleGraph

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<'a, T> FromIn<'a, T> for T

Source§

fn from_in(t: T, _: &'a Allocator) -> T

Converts to this type from the input type within the given allocator.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<'a, T, U> IntoIn<'a, U> for T
where U: FromIn<'a, T>,

Source§

fn into_in(self, allocator: &'a Allocator) -> U

Converts this type into the (usually inferred) input type within the given allocator.
Source§

impl<D> OwoColorize for D

Source§

fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>
where C: Color,

Set the foreground color generically Read more
Source§

fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>
where C: Color,

Set the background color generically. Read more
Source§

fn black(&self) -> FgColorDisplay<'_, Black, Self>

Change the foreground color to black
Source§

fn on_black(&self) -> BgColorDisplay<'_, Black, Self>

Change the background color to black
Source§

fn red(&self) -> FgColorDisplay<'_, Red, Self>

Change the foreground color to red
Source§

fn on_red(&self) -> BgColorDisplay<'_, Red, Self>

Change the background color to red
Source§

fn green(&self) -> FgColorDisplay<'_, Green, Self>

Change the foreground color to green
Source§

fn on_green(&self) -> BgColorDisplay<'_, Green, Self>

Change the background color to green
Source§

fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>

Change the foreground color to yellow
Source§

fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>

Change the background color to yellow
Source§

fn blue(&self) -> FgColorDisplay<'_, Blue, Self>

Change the foreground color to blue
Source§

fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>

Change the background color to blue
Source§

fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to magenta
Source§

fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to magenta
Source§

fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to purple
Source§

fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to purple
Source§

fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>

Change the foreground color to cyan
Source§

fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>

Change the background color to cyan
Source§

fn white(&self) -> FgColorDisplay<'_, White, Self>

Change the foreground color to white
Source§

fn on_white(&self) -> BgColorDisplay<'_, White, Self>

Change the background color to white
Source§

fn default_color(&self) -> FgColorDisplay<'_, Default, Self>

Change the foreground color to the terminal default
Source§

fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>

Change the background color to the terminal default
Source§

fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>

Change the foreground color to bright black
Source§

fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>

Change the background color to bright black
Source§

fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>

Change the foreground color to bright red
Source§

fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>

Change the background color to bright red
Source§

fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>

Change the foreground color to bright green
Source§

fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>

Change the background color to bright green
Source§

fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>

Change the foreground color to bright yellow
Source§

fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>

Change the background color to bright yellow
Source§

fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>

Change the foreground color to bright blue
Source§

fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>

Change the background color to bright blue
Source§

fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright magenta
Source§

fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright magenta
Source§

fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright purple
Source§

fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright purple
Source§

fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>

Change the foreground color to bright cyan
Source§

fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>

Change the background color to bright cyan
Source§

fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>

Change the foreground color to bright white
Source§

fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>

Change the background color to bright white
Source§

fn bold(&self) -> BoldDisplay<'_, Self>

Make the text bold
Source§

fn dimmed(&self) -> DimDisplay<'_, Self>

Make the text dim
Source§

fn italic(&self) -> ItalicDisplay<'_, Self>

Make the text italicized
Source§

fn underline(&self) -> UnderlineDisplay<'_, Self>

Make the text underlined
Make the text blink
Make the text blink (but fast!)
Source§

fn reversed(&self) -> ReversedDisplay<'_, Self>

Swap the foreground and background colors
Source§

fn hidden(&self) -> HiddenDisplay<'_, Self>

Hide the text
Source§

fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>

Cross out the text
Source§

fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either OwoColorize::fg or a color-specific method, such as OwoColorize::green, Read more
Source§

fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either OwoColorize::bg or a color-specific method, such as OwoColorize::on_yellow, Read more
Source§

fn fg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> FgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the foreground color to a specific RGB value.
Source§

fn bg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> BgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the background color to a specific RGB value.
Source§

fn truecolor(&self, r: u8, g: u8, b: u8) -> FgDynColorDisplay<'_, Rgb, Self>

Sets the foreground color to an RGB value.
Source§

fn on_truecolor(&self, r: u8, g: u8, b: u8) -> BgDynColorDisplay<'_, Rgb, Self>

Sets the background color to an RGB value.
Source§

fn style(&self, style: Style) -> Styled<&Self>

Apply a runtime-determined style
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.