forked from webpack/webpack-bundle-analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatsUtils.js
More file actions
98 lines (83 loc) · 2.33 KB
/
statsUtils.js
File metadata and controls
98 lines (83 loc) · 2.33 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
const { createWriteStream } = require("node:fs");
const { Readable } = require("node:stream");
const { pipeline } = require("node:stream/promises");
/** @typedef {import("./BundleAnalyzerPlugin").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("webpack").StatsCompilation} StatsCompilation */
class StatsSerializeStream extends Readable {
/**
* @param {StatsCompilation} stats stats
*/
constructor(stats) {
super();
this._indentLevel = 0;
this._stringifier = this._stringify(stats);
}
get _indent() {
return " ".repeat(this._indentLevel);
}
_read() {
let readMore = true;
while (readMore) {
const { value, done } = this._stringifier.next();
if (done) {
this.push(null);
readMore = false;
} else {
readMore = this.push(value);
}
}
}
/**
* @param {EXPECTED_ANY} obj obj
* @returns {Generator<string, undefined, unknown>} stringified result
* @private
*/
*_stringify(obj) {
if (
typeof obj === "string" ||
typeof obj === "number" ||
typeof obj === "boolean" ||
obj === null
) {
yield JSON.stringify(obj);
} else if (Array.isArray(obj)) {
yield "[";
this._indentLevel++;
let isFirst = true;
for (let item of obj) {
if (item === undefined) {
item = null;
}
yield `${isFirst ? "" : ","}\n${this._indent}`;
yield* this._stringify(item);
isFirst = false;
}
this._indentLevel--;
yield obj.length ? `\n${this._indent}]` : "]";
} else {
yield "{";
this._indentLevel++;
let isFirst = true;
const entries = Object.entries(obj);
for (const [itemKey, itemValue] of entries) {
if (itemValue === undefined) {
continue;
}
yield `${isFirst ? "" : ","}\n${this._indent}${JSON.stringify(itemKey)}: `;
yield* this._stringify(itemValue);
isFirst = false;
}
this._indentLevel--;
yield entries.length ? `\n${this._indent}}` : "}";
}
}
}
/**
* @param {StatsCompilation} stats stats
* @param {string} filepath filepath file path
* @returns {Promise<void>}
*/
async function writeStats(stats, filepath) {
await pipeline(new StatsSerializeStream(stats), createWriteStream(filepath));
}
module.exports = { StatsSerializeStream, writeStats };