or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analysis-engine.mdcli-tool.mdindex.mdreport-generation.mdwebpack-plugin.md

analysis-engine.mddocs/

0

# Analysis Engine

1

2

The analysis engine is the core component that processes webpack stats files and generates visualization data. It handles bundle parsing, module extraction, size calculation, and data transformation for the interactive treemap visualization.

3

4

## Capabilities

5

6

### Bundle Data Analysis

7

8

Extract and process webpack bundle statistics to generate visualization data.

9

10

```javascript { .api }

11

/**

12

* Processes webpack bundle stats and generates viewer data

13

* @param bundleStats - Webpack stats object from stats.toJson()

14

* @param bundleDir - Directory containing bundle files for parsing

15

* @param options - Analysis configuration options

16

* @returns Array of bundle information for visualization

17

*/

18

function getViewerData(

19

bundleStats: object,

20

bundleDir: string,

21

options?: AnalyzerOptions

22

): BundleInfo[];

23

24

interface AnalyzerOptions {

25

/** Logger instance for output messages */

26

logger?: Logger;

27

/** Patterns to exclude assets from analysis */

28

excludeAssets?: string | RegExp | ((assetName: string) => boolean) | Array<string | RegExp | ((assetName: string) => boolean)>;

29

}

30

31

interface BundleInfo {

32

/** Bundle filename */

33

label: string;

34

/** Indicates this is a webpack asset */

35

isAsset: boolean;

36

/** Original size from webpack stats */

37

statSize: number;

38

/** Parsed size from actual bundle file */

39

parsedSize?: number;

40

/** Gzipped size of parsed bundle */

41

gzipSize?: number;

42

/** Hierarchical module data for treemap visualization */

43

groups: ChartData[];

44

/** Mapping of entrypoints where this bundle is initial */

45

isInitialByEntrypoint: { [entrypoint: string]: boolean };

46

}

47

```

48

49

**Usage Examples:**

50

51

```javascript

52

const { getViewerData } = require('webpack-bundle-analyzer/lib/analyzer');

53

const fs = require('fs');

54

55

// Load webpack stats

56

const stats = JSON.parse(fs.readFileSync('stats.json'));

57

58

// Basic analysis

59

const bundleData = getViewerData(stats, './dist');

60

61

// With custom logger and asset exclusion

62

const Logger = require('webpack-bundle-analyzer/lib/Logger');

63

const logger = new Logger('info');

64

65

const bundleData = getViewerData(stats, './dist', {

66

logger,

67

excludeAssets: /\.css$/

68

});

69

```

70

71

### Stats File Reading

72

73

Read and parse webpack stats JSON files with streaming support for large files.

74

75

```javascript { .api }

76

/**

77

* Reads webpack stats from JSON file with streaming parser

78

* @param filename - Path to webpack stats JSON file

79

* @returns Promise resolving to parsed stats object

80

*/

81

function readStatsFromFile(filename: string): Promise<object>;

82

```

83

84

**Usage Examples:**

85

86

```javascript

87

const { readStatsFromFile } = require('webpack-bundle-analyzer/lib/analyzer');

88

89

// Read stats file

90

const stats = await readStatsFromFile('./webpack-stats.json');

91

92

// Use with analysis

93

const bundleData = getViewerData(stats, './dist');

94

```

95

96

### Chart Data Structure

97

98

Hierarchical data structure representing module organization for treemap visualization.

99

100

```javascript { .api }

101

interface ChartData {

102

/** Display label for the module or folder */

103

label: string;

104

/** Size value for this node */

105

value: number;

106

/** Child nodes for nested structure */

107

children?: ChartData[];

108

/** Additional metadata */

109

[key: string]: any;

110

}

111

```

112

113

### Module Tree Processing

114

115

The analysis engine processes webpack modules into a hierarchical tree structure based on file paths and module organization.

116

117

**Tree Building Process:**

118

119

1. **Module Extraction**: Extract all modules from webpack chunks

120

2. **Path Parsing**: Parse module identifiers into folder/file structures

121

3. **Tree Construction**: Build hierarchical folder tree with modules as leaves

122

4. **Size Calculation**: Calculate sizes at each tree level (stat, parsed, gzip)

123

5. **Chart Data Generation**: Convert tree to visualization-ready format

124

125

**Module Types Handled:**

126

127

- Regular modules with file paths

128

- Concatenated modules (webpack optimization)

129

- Entry modules at bundle boundaries

130

- Runtime modules (filtered out)

131

- Child chunk modules

132

133

### Asset Filtering

134

135

Flexible asset filtering system supporting multiple pattern types and combinations.

136

137

```javascript { .api }

138

// Asset filter function signature

139

type AssetFilter = (assetName: string) => boolean;

140

141

// Supported pattern types

142

type FilterPattern =

143

| string // Converted to RegExp

144

| RegExp // Direct pattern matching

145

| ((assetName: string) => boolean); // Custom filter function

146

147

// Create filter from patterns

148

function createAssetsFilter(

149

excludePatterns: FilterPattern | FilterPattern[]

150

): AssetFilter;

151

```

152

153

**Usage Examples:**

154

155

```javascript

156

const { createAssetsFilter } = require('webpack-bundle-analyzer/lib/utils');

157

158

// String pattern (converted to RegExp)

159

const filter1 = createAssetsFilter('vendor');

160

161

// RegExp pattern

162

const filter2 = createAssetsFilter(/\.(css|png|jpg)$/);

163

164

// Custom function

165

const filter3 = createAssetsFilter((assetName) =>

166

assetName.includes('legacy') || assetName.startsWith('polyfill')

167

);

168

169

// Multiple patterns

170

const filter4 = createAssetsFilter([

171

'vendor',

172

/\.css$/,

173

(name) => name.includes('test')

174

]);

175

176

// Use with analysis

177

const bundleData = getViewerData(stats, './dist', {

178

excludeAssets: filter4

179

});

180

```

181

182

### Size Metrics

183

184

Multiple size metrics provide different perspectives on bundle composition.

185

186

```javascript { .api }

187

interface SizeMetrics {

188

/** Original size from webpack stats (before minification) */

189

statSize: number;

190

/** Actual parsed bundle size (after minification) */

191

parsedSize?: number;

192

/** Gzipped size of parsed bundle */

193

gzipSize?: number;

194

}

195

196

type SizeType = 'stat' | 'parsed' | 'gzip';

197

```

198

199

**Size Calculation Details:**

200

201

- **Stat Size**: Taken directly from webpack stats object, represents source sizes

202

- **Parsed Size**: Calculated by parsing actual bundle files, reflects build output

203

- **Gzip Size**: Computed by gzipping parsed bundle content, shows transfer size

204

205

### Bundle Processing Pipeline

206

207

The analysis engine follows a structured pipeline for processing webpack stats:

208

209

1. **Stats Validation**: Validate webpack stats structure and format

210

2. **Asset Discovery**: Identify JavaScript assets with chunks

211

3. **Bundle Parsing**: Parse bundle files to extract module sources (if bundleDir provided)

212

4. **Module Processing**: Extract modules from chunks and organize by assets

213

5. **Tree Construction**: Build hierarchical module trees for each asset

214

6. **Size Calculation**: Calculate all size metrics (stat, parsed, gzip)

215

7. **Data Transformation**: Convert to visualization-ready format

216

8. **Entrypoint Mapping**: Map assets to webpack entrypoints

217

218

### Error Handling

219

220

Robust error handling for common analysis scenarios.

221

222

**Common Error Scenarios:**

223

224

- Missing bundle files (bundleDir specified but files don't exist)

225

- Malformed webpack stats structure

226

- Unparseable bundle files (minified with unsupported patterns)

227

- Memory filesystem usage (no physical bundle files)

228

229

**Error Recovery:**

230

231

- Falls back to stats-only analysis when bundle parsing fails

232

- Continues processing other assets when individual bundles fail

233

- Provides informative warnings for missing or problematic files

234

- Gracefully handles development vs production scenarios

235

236

**Usage Examples:**

237

238

```javascript

239

const { getViewerData } = require('webpack-bundle-analyzer/lib/analyzer');

240

const Logger = require('webpack-bundle-analyzer/lib/Logger');

241

242

const logger = new Logger('info');

243

244

try {

245

// Analysis with potential bundle file issues

246

const bundleData = getViewerData(stats, './dist', { logger });

247

248

if (!bundleData || bundleData.length === 0) {

249

console.log('No JavaScript bundles found in stats');

250

}

251

} catch (error) {

252

console.error('Analysis failed:', error.message);

253

}

254

```