-
-
Notifications
You must be signed in to change notification settings - Fork 503
Expand file tree
/
Copy pathviewer.js
More file actions
353 lines (303 loc) · 9.82 KB
/
viewer.js
File metadata and controls
353 lines (303 loc) · 9.82 KB
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
const fs = require("node:fs");
const http = require("node:http");
const path = require("node:path");
const { bold } = require("picocolors");
const sirv = require("sirv");
const WebSocket = require("ws");
const Logger = require("./Logger");
const analyzer = require("./analyzer");
const { renderViewer } = require("./template");
const { open } = require("./utils");
/** @typedef {import("http").Server} Server */
/** @typedef {import("ws").WebSocketServer} WebSocketServer */
/** @typedef {import("webpack").StatsCompilation} StatsCompilation */
/** @typedef {import("./BundleAnalyzerPlugin").Sizes} Sizes */
/** @typedef {import("./BundleAnalyzerPlugin").CompressionAlgorithm} CompressionAlgorithm */
/** @typedef {import("./BundleAnalyzerPlugin").ReportTitle} ReportTitle */
/** @typedef {import("./BundleAnalyzerPlugin").AnalyzerUrl} AnalyzerUrl */
/** @typedef {import("./BundleAnalyzerPlugin").ExcludeAssets} ExcludeAssets */
/** @typedef {import("./analyzer").ViewerDataOptions} ViewerDataOptions */
/** @typedef {import("./analyzer").ChartData} ChartData */
const projectRoot = path.resolve(__dirname, "..");
/**
* @param {string | (() => string)} reportTitle report title
* @returns {string} resolved title
*/
function resolveTitle(reportTitle) {
if (typeof reportTitle === "function") {
return reportTitle();
}
return reportTitle;
}
/**
* @param {Sizes} defaultSizes default sizes
* @param {CompressionAlgorithm} compressionAlgorithm compression algorithm
* @returns {Sizes} default sizes
*/
function resolveDefaultSizes(defaultSizes, compressionAlgorithm) {
if (["gzip", "brotli", "zstd"].includes(defaultSizes)) {
return compressionAlgorithm;
}
return defaultSizes;
}
/** @typedef {(string | undefined | null)[]} Entrypoints */
/**
* @param {StatsCompilation} bundleStats bundle stats
* @returns {Entrypoints} entrypoints
*/
function getEntrypoints(bundleStats) {
if (
bundleStats === null ||
bundleStats === undefined ||
!bundleStats.entrypoints
) {
return [];
}
return Object.values(bundleStats.entrypoints).map(
(entrypoint) => entrypoint.name,
);
}
/**
* @param {ViewerDataOptions} analyzerOpts analyzer options
* @param {StatsCompilation} bundleStats bundle stats
* @param {string | null} bundleDir bundle dir
* @returns {ChartData | null} chart data
*/
function getChartData(analyzerOpts, bundleStats, bundleDir) {
/** @type {ChartData | undefined | null} */
let chartData;
const { logger } = analyzerOpts;
try {
chartData = analyzer.getViewerData(bundleStats, bundleDir, analyzerOpts);
} catch (err) {
logger.error(`Couldn't analyze webpack bundle:\n${err}`);
logger.debug(/** @type {Error} */ (err).stack);
chartData = null;
}
// chartData can either be an array (bundleInfo[]) or null. It can't be an plain object anyway
if (
// analyzer.getViewerData() doesn't failed in the previous step
chartData &&
!Array.isArray(chartData)
) {
logger.error("Couldn't find any javascript bundles in provided stats file");
chartData = null;
}
return chartData;
}
/**
* @typedef {object} ServerOptions
* @property {number} port port
* @property {string} host host
* @property {boolean} openBrowser true when need to open browser, otherwise false
* @property {string | null} bundleDir bundle dir
* @property {import("webpack").OutputFileSystem | null=} outputFs filesystem for reading bundle files
* @property {Logger} logger logger
* @property {Sizes} defaultSizes default sizes
* @property {CompressionAlgorithm} compressionAlgorithm compression algorithm
* @property {ExcludeAssets | null} excludeAssets exclude assets
* @property {ReportTitle} reportTitle report title
* @property {AnalyzerUrl} analyzerUrl analyzer url
*/
/** @typedef {{ ws: WebSocketServer, http: Server, updateChartData: (bundleStats: StatsCompilation) => void }} ViewerServerObj */
/**
* @param {StatsCompilation} bundleStats bundle stats
* @param {ServerOptions} opts options
* @returns {Promise<ViewerServerObj>} server
*/
async function startServer(bundleStats, opts) {
const {
port = 8888,
host = "127.0.0.1",
openBrowser = true,
bundleDir = null,
outputFs,
logger = new Logger(),
defaultSizes = "parsed",
compressionAlgorithm,
excludeAssets = null,
reportTitle,
analyzerUrl,
} = opts || {};
const analyzerOpts = { logger, excludeAssets, compressionAlgorithm, outputFs };
let chartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!chartData) {
throw new Error("Can't get chart data");
}
const sirvMiddleware = sirv(`${projectRoot}/public`, {
// disables caching and traverse the file system on every request
dev: true,
});
const entrypoints = getEntrypoints(bundleStats);
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
const html = renderViewer({
mode: "server",
title: resolveTitle(reportTitle),
chartData: /** @type {ChartData} */ (chartData),
entrypoints,
defaultSizes: resolveDefaultSizes(defaultSizes, compressionAlgorithm),
compressionAlgorithm,
enableWebSocket: true,
});
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html);
} else {
sirvMiddleware(req, res);
}
});
await new Promise(
/**
* @param {(value: void) => void} resolve resolve
*/
(resolve) => {
server.listen(port, host, () => {
resolve();
const url = analyzerUrl({
listenPort: port,
listenHost: host,
boundAddress: server.address(),
});
logger.info(
`${bold("Webpack Bundle Analyzer")} is started at ${bold(url)}\n` +
`Use ${bold("Ctrl+C")} to close it`,
);
if (openBrowser) {
open(url, logger);
}
});
},
);
const wss = new WebSocket.Server({ server });
wss.on("connection", (ws) => {
ws.on("error", (err) => {
// Ignore network errors like `ECONNRESET`, `EPIPE`, etc.
if (/** @type {NodeJS.ErrnoException} */ (err).errno) return;
logger.info(err.message);
});
});
/**
* @param {StatsCompilation} bundleStats bundle stats
*/
function updateChartData(bundleStats) {
const newChartData = getChartData(analyzerOpts, bundleStats, bundleDir);
if (!newChartData) return;
chartData = newChartData;
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(
JSON.stringify({
event: "chartDataUpdated",
data: newChartData,
}),
);
}
}
}
return {
ws: wss,
http: server,
updateChartData,
};
}
/**
* @typedef {object} GenerateReportOptions
* @property {boolean} openBrowser true when need to open browser, otherwise false
* @property {string} reportFilename report filename
* @property {ReportTitle} reportTitle report title
* @property {string | null} bundleDir bundle dir
* @property {import("webpack").OutputFileSystem | null=} outputFs filesystem for reading bundle files
* @property {Logger} logger logger
* @property {Sizes} defaultSizes default sizes
* @property {CompressionAlgorithm} compressionAlgorithm compression algorithm
* @property {ExcludeAssets} excludeAssets exclude assets
*/
/**
* @param {StatsCompilation} bundleStats bundle stats
* @param {GenerateReportOptions} opts opts
* @returns {Promise<void>}
*/
async function generateReport(bundleStats, opts) {
const {
openBrowser = true,
reportFilename,
reportTitle,
bundleDir = null,
outputFs,
logger = new Logger(),
defaultSizes = "parsed",
compressionAlgorithm,
excludeAssets = null,
} = opts || {};
const chartData = getChartData(
{ logger, excludeAssets, compressionAlgorithm, outputFs },
bundleStats,
bundleDir,
);
const entrypoints = getEntrypoints(bundleStats);
if (!chartData) return;
const reportHtml = renderViewer({
mode: "static",
title: resolveTitle(reportTitle),
chartData,
entrypoints,
defaultSizes: resolveDefaultSizes(defaultSizes, compressionAlgorithm),
compressionAlgorithm,
enableWebSocket: false,
});
const reportFilepath = path.resolve(
bundleDir || process.cwd(),
reportFilename,
);
fs.mkdirSync(path.dirname(reportFilepath), { recursive: true });
fs.writeFileSync(reportFilepath, reportHtml);
logger.info(
`${bold("Webpack Bundle Analyzer")} saved report to ${bold(reportFilepath)}`,
);
if (openBrowser) {
open(`file://${reportFilepath}`, logger);
}
}
/**
* @typedef {object} GenerateJSONReportOptions
* @property {string} reportFilename report filename
* @property {string | null} bundleDir bundle dir
* @property {import("webpack").OutputFileSystem | null=} outputFs filesystem for reading bundle files
* @property {Logger} logger logger
* @property {ExcludeAssets} excludeAssets exclude assets
* @property {CompressionAlgorithm} compressionAlgorithm compression algorithm
*/
/**
* @param {StatsCompilation} bundleStats bundle stats
* @param {GenerateJSONReportOptions} opts options
* @returns {Promise<void>}
*/
async function generateJSONReport(bundleStats, opts) {
const {
reportFilename,
bundleDir = null,
outputFs,
logger = new Logger(),
excludeAssets = null,
compressionAlgorithm,
} = opts || {};
const chartData = getChartData(
{ logger, excludeAssets, compressionAlgorithm, outputFs },
bundleStats,
bundleDir,
);
if (!chartData) return;
await fs.promises.mkdir(path.dirname(reportFilename), { recursive: true });
await fs.promises.writeFile(reportFilename, JSON.stringify(chartData));
logger.info(
`${bold("Webpack Bundle Analyzer")} saved JSON report to ${bold(reportFilename)}`,
);
}
module.exports = {
generateJSONReport,
generateReport,
getEntrypoints,
// deprecated
start: startServer,
startServer,
};