profiler-md 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +1291 -815
- package/dist/index.d.mts +90 -38
- package/dist/index.js +2 -2
- package/package.json +24 -12
- package/readme.md +30 -25
package/dist/cli.mjs
CHANGED
|
@@ -1,18 +1,144 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createWriteStream } from "node:fs";
|
|
3
3
|
import { readFile } from "node:fs/promises";
|
|
4
|
-
import {
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { brotliDecompress, gunzip } from "node:zlib";
|
|
5
6
|
import meow from "meow";
|
|
6
7
|
import picomatch from "picomatch";
|
|
8
|
+
import { Profile } from "pprof-format";
|
|
9
|
+
import plur from "plur";
|
|
7
10
|
import prettyBytes from "pretty-bytes";
|
|
8
11
|
import prettyMilliseconds from "pretty-ms";
|
|
9
12
|
|
|
10
|
-
//#region src/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
//#region src/helpers/array.ts
|
|
14
|
+
/**
|
|
15
|
+
* A {@link TypedArray} wrapper that's growable.
|
|
16
|
+
*
|
|
17
|
+
* It's mainly useful when the indices are sequential IDs that arrive out of
|
|
18
|
+
* order and with the maximum unknown.
|
|
19
|
+
*/
|
|
20
|
+
var DynamicTypedArray = class {
|
|
21
|
+
#array;
|
|
22
|
+
#arrayConstructor;
|
|
23
|
+
constructor(initialArray) {
|
|
24
|
+
this.#array = initialArray;
|
|
25
|
+
this.#arrayConstructor = initialArray.constructor;
|
|
26
|
+
}
|
|
27
|
+
ensureCapacity(minLength) {
|
|
28
|
+
if (minLength > this.#array.length) {
|
|
29
|
+
const grown = new this.#arrayConstructor(Math.max(minLength, this.#array.length * 2));
|
|
30
|
+
grown.set(this.#array);
|
|
31
|
+
this.#array = grown;
|
|
32
|
+
}
|
|
33
|
+
return this.#array;
|
|
34
|
+
}
|
|
15
35
|
};
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/options.ts
|
|
39
|
+
const normalizeProfileToMdOptions = ({ topN = 20, includeEntry = defaultIncludeEntry, isThirdPartyEntry = defaultIsThirdPartyEntry, cwd } = {}) => {
|
|
40
|
+
if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
|
|
41
|
+
if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
|
|
42
|
+
return {
|
|
43
|
+
topN,
|
|
44
|
+
includeEntry: cacheEntryFunction(includeEntry),
|
|
45
|
+
isThirdPartyEntry: cacheEntryFunction(isThirdPartyEntry),
|
|
46
|
+
cwd: cwd ?? void 0
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
const cacheEntryFunction = (func) => {
|
|
50
|
+
const cache = new DynamicTypedArray(new Uint8Array(256));
|
|
51
|
+
return (entry) => {
|
|
52
|
+
const { id } = entry;
|
|
53
|
+
const array = cache.ensureCapacity(id + 1);
|
|
54
|
+
const value = array[id];
|
|
55
|
+
if (value !== 0) return value === 2;
|
|
56
|
+
const result = func(entry);
|
|
57
|
+
array[id] = result ? 2 : 1;
|
|
58
|
+
return result;
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Returns whether to include the given entry in the Markdown output.
|
|
63
|
+
*
|
|
64
|
+
* Excludes synthetic profile data and redundant internals by default.
|
|
65
|
+
*/
|
|
66
|
+
const defaultIncludeEntry = ({ name, location }) => {
|
|
67
|
+
if (name === `(root)` || name === `(module)`) return false;
|
|
68
|
+
if (!location && (name === `ModuleWrap` || name.startsWith(`system /`) || name.startsWith(`Node /`)) || location?.url.protocol === `node:` && location.url.pathname.startsWith(`internal/`)) return false;
|
|
69
|
+
return true;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Returns whether the given entry points to third-party code.
|
|
73
|
+
*
|
|
74
|
+
* Excludes `node_modules` only by default.
|
|
75
|
+
*/
|
|
76
|
+
const defaultIsThirdPartyEntry = (entry) => !!entry.location?.url.pathname.includes(`/node_modules/`);
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/helpers/format.ts
|
|
80
|
+
const formatCount = (count, unit) => count.toLocaleString(`en-US`) + (unit ? ` ${plur(unit, count)}` : ``);
|
|
81
|
+
const formatMilliseconds = (milliseconds) => prettyMilliseconds(milliseconds, {
|
|
82
|
+
secondsDecimalDigits: 2,
|
|
83
|
+
millisecondsDecimalDigits: 1,
|
|
84
|
+
unitCount: 2
|
|
85
|
+
});
|
|
86
|
+
const formatMicrosecondsExact = (microseconds) => `${microseconds.toFixed(1)}µs`;
|
|
87
|
+
const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
|
|
88
|
+
const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
|
|
89
|
+
const formatConjunction = (strings) => (conjunctionFormatter ??= new Intl.ListFormat(`en`, {
|
|
90
|
+
style: `long`,
|
|
91
|
+
type: `conjunction`
|
|
92
|
+
})).format(strings);
|
|
93
|
+
let conjunctionFormatter;
|
|
94
|
+
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region src/helpers/heap.ts
|
|
97
|
+
var MaxHeap = class {
|
|
98
|
+
#heap;
|
|
99
|
+
#size;
|
|
100
|
+
#compare;
|
|
101
|
+
constructor(values, compare) {
|
|
102
|
+
this.#heap = [...values.entries()];
|
|
103
|
+
this.#size = this.#heap.length;
|
|
104
|
+
this.#compare = ([index1, value1], [index2, value2]) => {
|
|
105
|
+
const result = compare(value1, value2);
|
|
106
|
+
return result === 0 ? index2 - index1 : result;
|
|
107
|
+
};
|
|
108
|
+
for (let i = Math.floor(this.#size / 2) - 1; i >= 0; i--) this.#siftDown(i);
|
|
109
|
+
}
|
|
110
|
+
get length() {
|
|
111
|
+
return this.#size;
|
|
112
|
+
}
|
|
113
|
+
pop() {
|
|
114
|
+
if (this.#size === 0) return;
|
|
115
|
+
const max = this.#heap[0][1];
|
|
116
|
+
this.#heap[0] = this.#heap[--this.#size];
|
|
117
|
+
this.#siftDown(0);
|
|
118
|
+
return max;
|
|
119
|
+
}
|
|
120
|
+
#siftDown(i) {
|
|
121
|
+
while (true) {
|
|
122
|
+
let largest = 2 * i + 1;
|
|
123
|
+
if (largest >= this.#size) break;
|
|
124
|
+
const right = largest + 1;
|
|
125
|
+
if (right < this.#size && this.#compare(this.#heap[right], this.#heap[largest]) > 0) largest = right;
|
|
126
|
+
if (this.#compare(this.#heap[largest], this.#heap[i]) <= 0) break;
|
|
127
|
+
[this.#heap[i], this.#heap[largest]] = [this.#heap[largest], this.#heap[i]];
|
|
128
|
+
i = largest;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
const selectTopN = (values, topN, compare) => {
|
|
133
|
+
if (topN === 0) return [];
|
|
134
|
+
if (values.length <= topN) return values.toSorted((value1, value2) => compare(value2, value1));
|
|
135
|
+
const heap = new MaxHeap(values, compare);
|
|
136
|
+
return Array.from({ length: topN }, () => heap.pop());
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
//#endregion
|
|
140
|
+
//#region src/helpers/markdown.ts
|
|
141
|
+
const formatHeading = (level, content) => `${`#`.repeat(level)} ${content}`;
|
|
16
142
|
const formatTable = (headers, rows) => {
|
|
17
143
|
const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
|
|
18
144
|
const allRows = [headerContents, ...rows];
|
|
@@ -27,200 +153,383 @@ const formatTable = (headers, rows) => {
|
|
|
27
153
|
...rows.map(formatRow)
|
|
28
154
|
].join(`\n`);
|
|
29
155
|
};
|
|
156
|
+
const inlineCode = (text) => {
|
|
157
|
+
const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
|
|
158
|
+
const fence = `\``.repeat(longestBacktickRun + 1);
|
|
159
|
+
return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
|
|
160
|
+
};
|
|
30
161
|
|
|
31
162
|
//#endregion
|
|
32
|
-
//#region src/
|
|
163
|
+
//#region src/location.ts
|
|
33
164
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
* This is the default value for {@link V8ProfileToMdOptions.includeRow}.
|
|
37
|
-
*
|
|
38
|
-
* It makes reasonable assumptions about which rows are uninteresting to
|
|
39
|
-
* display. For example, Node internals related to ESM loading are excluded.
|
|
165
|
+
* Converts a {@link ProfileLocationInput} or a {@link ProfileLocation} or
|
|
166
|
+
* returns undefined if it's not a valid location.
|
|
40
167
|
*/
|
|
41
|
-
const
|
|
42
|
-
if (
|
|
43
|
-
if (
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
* Excludes `node_modules` only by default.
|
|
52
|
-
*/
|
|
53
|
-
const defaultIsThirdPartyURL = (url) => url.pathname.includes(`/node_modules/`);
|
|
54
|
-
const normalizeV8ProfileToMdOptions = ({ topN = 20, includeRow = defaultIncludeRow, isThirdPartyURL = defaultIsThirdPartyURL, cwd } = {}) => {
|
|
55
|
-
if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
|
|
56
|
-
if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
|
|
57
|
-
const includeRowCache = /* @__PURE__ */ new Map();
|
|
58
|
-
const isThirdPartyUrlCache = /* @__PURE__ */ new Map();
|
|
59
|
-
return {
|
|
60
|
-
topN,
|
|
61
|
-
includeRow: (row) => {
|
|
62
|
-
let result = includeRowCache.get(row.id);
|
|
63
|
-
if (result !== void 0) return result;
|
|
64
|
-
result = includeRow(row);
|
|
65
|
-
includeRowCache.set(row.id, result);
|
|
66
|
-
return result;
|
|
67
|
-
},
|
|
68
|
-
isThirdPartyURL: (url) => {
|
|
69
|
-
const { href } = url;
|
|
70
|
-
let result = isThirdPartyUrlCache.get(href);
|
|
71
|
-
if (result !== void 0) return result;
|
|
72
|
-
result = isThirdPartyURL(url);
|
|
73
|
-
isThirdPartyUrlCache.set(href, result);
|
|
74
|
-
return result;
|
|
75
|
-
},
|
|
76
|
-
cwd: cwd ?? void 0
|
|
77
|
-
};
|
|
78
|
-
};
|
|
79
|
-
const formatLocation = (location, { cwd }) => {
|
|
80
|
-
let url;
|
|
81
|
-
try {
|
|
82
|
-
url = new URL(location);
|
|
83
|
-
} catch {}
|
|
84
|
-
let path;
|
|
85
|
-
if (url) {
|
|
86
|
-
if (url.protocol !== `file:`) return location || void 0;
|
|
87
|
-
path = url.pathname;
|
|
88
|
-
} else path = location;
|
|
89
|
-
if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
|
|
90
|
-
return path;
|
|
91
|
-
};
|
|
92
|
-
const categorizeCallFrame = (callFrame, { isThirdPartyURL }) => {
|
|
93
|
-
if (!callFrame.url) {
|
|
94
|
-
const { functionName } = callFrame;
|
|
95
|
-
if (functionName.startsWith(`(`) && functionName.endsWith(`)`)) return functionName.slice(1, -1);
|
|
96
|
-
if (functionName.startsWith(`RegExp: `)) return `regexp`;
|
|
97
|
-
return `native`;
|
|
168
|
+
const makeProfileLocation = ({ urlOrPath, line, column }) => {
|
|
169
|
+
if (!urlOrPath) return;
|
|
170
|
+
if (urlOrPath.startsWith(`/`)) try {
|
|
171
|
+
return {
|
|
172
|
+
url: new URL(`file://${urlOrPath}`),
|
|
173
|
+
line,
|
|
174
|
+
column
|
|
175
|
+
};
|
|
176
|
+
} catch {
|
|
177
|
+
return;
|
|
98
178
|
}
|
|
99
|
-
|
|
179
|
+
if (!urlOrPath.includes(`:`)) return;
|
|
100
180
|
try {
|
|
101
|
-
|
|
181
|
+
return {
|
|
182
|
+
url: new URL(urlOrPath),
|
|
183
|
+
line,
|
|
184
|
+
column
|
|
185
|
+
};
|
|
102
186
|
} catch {
|
|
103
|
-
return
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
const formatProfileLocation = (location, { cwd }) => {
|
|
191
|
+
if (!location) return inlineCode(`<native>`);
|
|
192
|
+
let path;
|
|
193
|
+
if (location.url.protocol === `file:`) {
|
|
194
|
+
path = location.url.pathname;
|
|
195
|
+
if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
|
|
196
|
+
} else path = location.url.href;
|
|
197
|
+
if (location.line !== void 0) {
|
|
198
|
+
path += `:${location.line}`;
|
|
199
|
+
if (location.column !== void 0) path += `:${location.column}`;
|
|
200
|
+
}
|
|
201
|
+
return path || inlineCode(`<native>`);
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
//#endregion
|
|
205
|
+
//#region src/profile/summarize.ts
|
|
206
|
+
var ProfileBuilder = class {
|
|
207
|
+
#metrics;
|
|
208
|
+
#functionKey;
|
|
209
|
+
#functionInput;
|
|
210
|
+
#options;
|
|
211
|
+
#totalSampleCount;
|
|
212
|
+
#totalValues;
|
|
213
|
+
#categoryToMetrics;
|
|
214
|
+
#keyToCallStack;
|
|
215
|
+
#keyToFunction;
|
|
216
|
+
#idToFunction;
|
|
217
|
+
#functionIdToLastSeenSampleCount;
|
|
218
|
+
#frameIndexToFramePairKey;
|
|
219
|
+
constructor({ metrics, functionKey, functionInput }, options) {
|
|
220
|
+
this.#metrics = metrics;
|
|
221
|
+
this.#functionKey = functionKey;
|
|
222
|
+
this.#functionInput = functionInput;
|
|
223
|
+
this.#options = options;
|
|
224
|
+
this.#totalSampleCount = 0;
|
|
225
|
+
this.#totalValues = new Float64Array(this.#metrics.length);
|
|
226
|
+
this.#categoryToMetrics = /* @__PURE__ */ new Map();
|
|
227
|
+
this.#keyToCallStack = /* @__PURE__ */ new Map();
|
|
228
|
+
this.#keyToFunction = /* @__PURE__ */ new Map();
|
|
229
|
+
this.#idToFunction = [];
|
|
230
|
+
this.#functionIdToLastSeenSampleCount = new DynamicTypedArray(new Uint32Array(1));
|
|
231
|
+
this.#frameIndexToFramePairKey = new DynamicTypedArray(new Int32Array(64));
|
|
232
|
+
}
|
|
233
|
+
/** Adds a single profile sample. */
|
|
234
|
+
addSample({ values, nodes, line }) {
|
|
235
|
+
if (nodes.length === 0) return;
|
|
236
|
+
const callStack = this.#getOrCreateCallStack(nodes);
|
|
237
|
+
const callee = callStack.frames[0];
|
|
238
|
+
const caller = callStack.frames[1];
|
|
239
|
+
let categoryMetrics = this.#categoryToMetrics.get(callee.category);
|
|
240
|
+
if (!categoryMetrics) {
|
|
241
|
+
categoryMetrics = {
|
|
242
|
+
sampleCount: 0,
|
|
243
|
+
values: new Float64Array(this.#metrics.length)
|
|
244
|
+
};
|
|
245
|
+
this.#categoryToMetrics.set(callee.category, categoryMetrics);
|
|
246
|
+
}
|
|
247
|
+
let callerMetrics;
|
|
248
|
+
if (caller) {
|
|
249
|
+
callerMetrics = callee.callerIdToMetrics.get(caller.id);
|
|
250
|
+
if (!callerMetrics) {
|
|
251
|
+
callerMetrics = {
|
|
252
|
+
caller,
|
|
253
|
+
selfSampleCount: 0,
|
|
254
|
+
selfValues: new Float64Array(this.#metrics.length)
|
|
255
|
+
};
|
|
256
|
+
callee.callerIdToMetrics.set(caller.id, callerMetrics);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
let lineMetrics;
|
|
260
|
+
if (line !== void 0) {
|
|
261
|
+
lineMetrics = callee.lineToMetrics.get(line);
|
|
262
|
+
if (!lineMetrics) {
|
|
263
|
+
lineMetrics = {
|
|
264
|
+
sampleCount: 0,
|
|
265
|
+
values: new Float64Array(this.#metrics.length)
|
|
266
|
+
};
|
|
267
|
+
callee.lineToMetrics.set(line, lineMetrics);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
this.#totalSampleCount++;
|
|
271
|
+
categoryMetrics.sampleCount++;
|
|
272
|
+
callStack.selfSampleCount++;
|
|
273
|
+
callee.selfSampleCount++;
|
|
274
|
+
if (callerMetrics) callerMetrics.selfSampleCount++;
|
|
275
|
+
if (lineMetrics) lineMetrics.sampleCount++;
|
|
276
|
+
for (let i = 0; i < values.length; i++) {
|
|
277
|
+
this.#totalValues[i] += values[i];
|
|
278
|
+
categoryMetrics.values[i] += values[i];
|
|
279
|
+
callStack.selfValues[i] += values[i];
|
|
280
|
+
callee.selfValues[i] += values[i];
|
|
281
|
+
if (callerMetrics) callerMetrics.selfValues[i] += values[i];
|
|
282
|
+
if (lineMetrics) lineMetrics.values[i] += values[i];
|
|
283
|
+
}
|
|
284
|
+
const funcCount = this.#keyToFunction.size;
|
|
285
|
+
const functionIdToLastSeenSampleCount = this.#functionIdToLastSeenSampleCount.ensureCapacity(funcCount);
|
|
286
|
+
for (const func of callStack.frames) {
|
|
287
|
+
if (functionIdToLastSeenSampleCount[func.id] === this.#totalSampleCount) continue;
|
|
288
|
+
functionIdToLastSeenSampleCount[func.id] = this.#totalSampleCount;
|
|
289
|
+
func.totalSampleCount++;
|
|
290
|
+
for (let i = 0; i < values.length; i++) func.totalValues[i] += values[i];
|
|
291
|
+
}
|
|
292
|
+
const maxFramePairCount = callStack.frames.length - 1;
|
|
293
|
+
const frameIndexToFramePairKey = this.#frameIndexToFramePairKey.ensureCapacity(maxFramePairCount);
|
|
294
|
+
let seenFramePairCount = 0;
|
|
295
|
+
for (let i = 0; i < maxFramePairCount; i++) {
|
|
296
|
+
const callee = callStack.frames[i];
|
|
297
|
+
const caller = callStack.frames[i + 1];
|
|
298
|
+
const pairKey = caller.id * funcCount + callee.id;
|
|
299
|
+
let pairAlreadySeen = false;
|
|
300
|
+
for (let j = 0; j < seenFramePairCount; j++) if (frameIndexToFramePairKey[j] === pairKey) {
|
|
301
|
+
pairAlreadySeen = true;
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
if (pairAlreadySeen) continue;
|
|
305
|
+
frameIndexToFramePairKey[seenFramePairCount++] = pairKey;
|
|
306
|
+
let calleeMetrics = caller.calleeIdToMetrics.get(callee.id);
|
|
307
|
+
if (!calleeMetrics) {
|
|
308
|
+
calleeMetrics = {
|
|
309
|
+
callee,
|
|
310
|
+
totalSampleCount: 0,
|
|
311
|
+
totalValues: new Float64Array(this.#metrics.length)
|
|
312
|
+
};
|
|
313
|
+
caller.calleeIdToMetrics.set(callee.id, calleeMetrics);
|
|
314
|
+
}
|
|
315
|
+
calleeMetrics.totalSampleCount++;
|
|
316
|
+
for (let i = 0; i < values.length; i++) calleeMetrics.totalValues[i] += values[i];
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
addLineMetrics({ node, lines }) {
|
|
320
|
+
const func = this.#getOrCreateFunction(node);
|
|
321
|
+
for (const { line, sampleCount, values } of lines) {
|
|
322
|
+
let lineMetrics = func.lineToMetrics.get(line);
|
|
323
|
+
if (!lineMetrics) {
|
|
324
|
+
lineMetrics = {
|
|
325
|
+
sampleCount: 0,
|
|
326
|
+
values: new Float64Array(this.#metrics.length)
|
|
327
|
+
};
|
|
328
|
+
func.lineToMetrics.set(line, lineMetrics);
|
|
329
|
+
}
|
|
330
|
+
lineMetrics.sampleCount += sampleCount;
|
|
331
|
+
for (let i = 0; i < values.length; i++) lineMetrics.values[i] += values[i];
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
#getOrCreateCallStack(nodes) {
|
|
335
|
+
const frames = nodes.map((node) => this.#getOrCreateFunction(node));
|
|
336
|
+
const key = frames.map((frame) => frame.id).join(`,`);
|
|
337
|
+
let callStack = this.#keyToCallStack.get(key);
|
|
338
|
+
if (callStack) return callStack;
|
|
339
|
+
callStack = {
|
|
340
|
+
frames,
|
|
341
|
+
selfSampleCount: 0,
|
|
342
|
+
selfValues: new Float64Array(this.#metrics.length)
|
|
343
|
+
};
|
|
344
|
+
this.#keyToCallStack.set(key, callStack);
|
|
345
|
+
return callStack;
|
|
346
|
+
}
|
|
347
|
+
#getOrCreateFunction(node) {
|
|
348
|
+
let func = this.#idToFunction[node.id];
|
|
349
|
+
if (func) return func;
|
|
350
|
+
const key = this.#functionKey(node);
|
|
351
|
+
func = this.#keyToFunction.get(key);
|
|
352
|
+
if (func) {
|
|
353
|
+
this.#idToFunction[node.id] = func;
|
|
354
|
+
return func;
|
|
355
|
+
}
|
|
356
|
+
const { name: nameInput, location: locationInput } = this.#functionInput(node);
|
|
357
|
+
const entry = {
|
|
358
|
+
id: this.#keyToFunction.size,
|
|
359
|
+
name: nameInput || `(anonymous)`,
|
|
360
|
+
location: locationInput ? makeProfileLocation(locationInput) : void 0
|
|
361
|
+
};
|
|
362
|
+
func = {
|
|
363
|
+
...entry,
|
|
364
|
+
category: categorizeFunction(entry, this.#options),
|
|
365
|
+
selfSampleCount: 0,
|
|
366
|
+
totalSampleCount: 0,
|
|
367
|
+
selfValues: new Float64Array(this.#metrics.length),
|
|
368
|
+
totalValues: new Float64Array(this.#metrics.length),
|
|
369
|
+
lineToMetrics: /* @__PURE__ */ new Map(),
|
|
370
|
+
callerIdToMetrics: /* @__PURE__ */ new Map(),
|
|
371
|
+
calleeIdToMetrics: /* @__PURE__ */ new Map()
|
|
372
|
+
};
|
|
373
|
+
this.#idToFunction[node.id] = func;
|
|
374
|
+
this.#keyToFunction.set(key, func);
|
|
375
|
+
return func;
|
|
376
|
+
}
|
|
377
|
+
build() {
|
|
378
|
+
const samplingIntervals = new Float64Array(this.#metrics.length);
|
|
379
|
+
for (let i = 0; i < samplingIntervals.length; i++) samplingIntervals[i] = this.#totalValues[i] / this.#totalSampleCount;
|
|
380
|
+
const functions = [...this.#keyToFunction.values()];
|
|
381
|
+
const callStacks = [...this.#keyToCallStack.values()];
|
|
382
|
+
return {
|
|
383
|
+
metrics: this.#metrics,
|
|
384
|
+
totalSampleCount: this.#totalSampleCount,
|
|
385
|
+
totalValues: this.#totalValues,
|
|
386
|
+
samplingIntervals,
|
|
387
|
+
categoryToMetrics: this.#categoryToMetrics,
|
|
388
|
+
functions,
|
|
389
|
+
callStacks
|
|
390
|
+
};
|
|
104
391
|
}
|
|
105
|
-
if (urlObject.protocol !== `file:`) return `native`;
|
|
106
|
-
return isThirdPartyURL(urlObject) ? `third-party` : `ours`;
|
|
107
392
|
};
|
|
393
|
+
const categorizeFunction = (entry, { isThirdPartyEntry }) => {
|
|
394
|
+
const { name, location } = entry;
|
|
395
|
+
if (name.startsWith(`(`) && name.endsWith(`)`) && !name.startsWith(`(anonymous`)) return name.slice(1, -1);
|
|
396
|
+
if (name.startsWith(`RegExp: `)) return `regexp`;
|
|
397
|
+
if (!location || location.url.protocol === `node:`) return `native`;
|
|
398
|
+
return isThirdPartyEntry(entry) ? `third-party` : `ours`;
|
|
399
|
+
};
|
|
400
|
+
/**
|
|
401
|
+
* Returns the list of callers of {@link callStacks} that is the longest common
|
|
402
|
+
* suffix of their frames, except it never returns a call stack as long as one
|
|
403
|
+
* of the input call stacks.
|
|
404
|
+
*
|
|
405
|
+
* This behavior is so that it's safe to remove that suffix from any of the call
|
|
406
|
+
* stacks and end up with a non-empty call stack to render.
|
|
407
|
+
*/
|
|
108
408
|
const findCommonCallStack = (callStacks) => {
|
|
109
409
|
if (callStacks.length <= 1) return [];
|
|
110
|
-
const minLength = Math.min(...callStacks.map((
|
|
111
|
-
const
|
|
410
|
+
const minLength = Math.min(...callStacks.map((cs) => cs.frames.length));
|
|
411
|
+
const firstFrames = callStacks[0].frames;
|
|
112
412
|
let suffixLength = 0;
|
|
113
413
|
for (let i = 1; i < minLength; i++) {
|
|
114
|
-
const suffix =
|
|
115
|
-
if (callStacks.every((callStack) => callStack.
|
|
414
|
+
const suffix = firstFrames.slice(-i).map((frame) => frame.id);
|
|
415
|
+
if (callStacks.every((callStack) => callStack.frames.slice(-i).every((frame, j) => frame.id === suffix[j]))) suffixLength = i;
|
|
116
416
|
else break;
|
|
117
417
|
}
|
|
118
|
-
return suffixLength > 0 ?
|
|
119
|
-
};
|
|
120
|
-
const formatCallStack = (callStack) => callStack.map(({ callFrame, name, location }, index) => {
|
|
121
|
-
name = inlineCode(name);
|
|
122
|
-
if (!callFrame.url) return name;
|
|
123
|
-
const previousUrl = callStack[index - 1]?.callFrame.url;
|
|
124
|
-
return `${name} (${callFrame.url === previousUrl ? `${callFrame.lineNumber + 1}:${callFrame.columnNumber + 1}` : location ?? inlineCode(`<native>`)})`;
|
|
125
|
-
}).join(` ← `);
|
|
126
|
-
const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
|
|
127
|
-
/** Returns the full call stack for a node (bottom-up). */
|
|
128
|
-
const summarizeCallStack = (graph, rawNodeId) => {
|
|
129
|
-
const stack = [];
|
|
130
|
-
let currentRawNodeId = rawNodeId;
|
|
131
|
-
do {
|
|
132
|
-
const node = graph.rawIdToSummarizedNode.get(currentRawNodeId);
|
|
133
|
-
stack.push(node);
|
|
134
|
-
currentRawNodeId = graph.rawIdToParentRawId.get(currentRawNodeId);
|
|
135
|
-
} while (currentRawNodeId !== void 0);
|
|
136
|
-
return stack;
|
|
418
|
+
return suffixLength > 0 ? firstFrames.slice(-suffixLength) : [];
|
|
137
419
|
};
|
|
138
420
|
|
|
139
421
|
//#endregion
|
|
140
|
-
//#region src/
|
|
141
|
-
const
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
//#endregion
|
|
152
|
-
//#region src/internal/heap.ts
|
|
153
|
-
const selectTopN = (values, topN, compare) => {
|
|
154
|
-
if (topN === 0) return [];
|
|
155
|
-
if (values.length <= topN) return values.toSorted(compare);
|
|
156
|
-
const stableCompare = ([index1, value1], [index2, value2]) => {
|
|
157
|
-
const result = compare(value1, value2);
|
|
158
|
-
return result === 0 ? index1 - index2 : result;
|
|
159
|
-
};
|
|
160
|
-
const heap = [...values.entries()];
|
|
161
|
-
for (let i = Math.floor(topN / 2) - 1; i >= 0; i--) siftDown(heap, i, topN, stableCompare);
|
|
162
|
-
for (let i = topN; i < values.length; i++) {
|
|
163
|
-
const candidate = [i, values[i]];
|
|
164
|
-
if (stableCompare(candidate, heap[0]) < 0) {
|
|
165
|
-
heap[0] = candidate;
|
|
166
|
-
siftDown(heap, 0, topN, stableCompare);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
return heap.slice(0, topN).sort(stableCompare).map(([, value]) => value);
|
|
422
|
+
//#region src/profile/format.ts
|
|
423
|
+
const formatProfile = (profile, options) => {
|
|
424
|
+
const headingLevel = 1;
|
|
425
|
+
return `${[
|
|
426
|
+
formatHeading(headingLevel, formatTitle(profile)),
|
|
427
|
+
formatOverallSummary$1(profile),
|
|
428
|
+
formatMetricSections(profile, {
|
|
429
|
+
...options,
|
|
430
|
+
headingLevel: headingLevel + 1
|
|
431
|
+
})
|
|
432
|
+
].join(`\n\n`)}\n`;
|
|
170
433
|
};
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if (compare(heap[i], heap[minChild]) >= 0) break;
|
|
178
|
-
[heap[i], heap[minChild]] = [heap[minChild], heap[i]];
|
|
179
|
-
i = minChild;
|
|
434
|
+
const formatTitle = (profile) => capitalizeFirst(`${formatConjunction(profile.metrics.map(metricTitleName))} profile`);
|
|
435
|
+
const metricTitleName = (metric) => {
|
|
436
|
+
switch (metric.type) {
|
|
437
|
+
case `time`: return `CPU`;
|
|
438
|
+
case `size`: return `heap`;
|
|
439
|
+
case `custom`: return metric.name;
|
|
180
440
|
}
|
|
181
441
|
};
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const formatOverallProfileSummary$1 = ({ totalTime, totalSampleCount, samplingInterval, callFrameCategoryToStats }) => {
|
|
192
|
-
const hottestCallFrameCategories = [...callFrameCategoryToStats].sort(([, stats1], [, stats2]) => stats2.time - stats1.time);
|
|
193
|
-
return [`Took ${formatMicroseconds(totalTime)} over ${formatCount(totalSampleCount, `sample`)} (${formatMicrosecondsExact(samplingInterval)} per sample).`, formatTable([
|
|
442
|
+
const formatOverallSummary$1 = (profile) => `${formatSummaryLine(profile)}\n\n${formatCategoryTable(profile)}`;
|
|
443
|
+
const formatSummaryLine = ({ metrics, totalSampleCount, totalValues, samplingIntervals }) => {
|
|
444
|
+
const totalsSummary = capitalizeFirst(formatConjunction(metrics.map((metric, index) => `${metricPastTenseVerb(metric)} ${formatValue(totalValues[index], metric)}`)));
|
|
445
|
+
const samplingIntervalsSummary = `(${formatConjunction(Array.from(samplingIntervals, (interval, index) => formatSamplingInterval(interval, metrics[index])))} per sample)`;
|
|
446
|
+
return `${totalsSummary} over ${formatCount(totalSampleCount, `sample`)} ${samplingIntervalsSummary}.`;
|
|
447
|
+
};
|
|
448
|
+
const formatCategoryTable = ({ metrics, totalValues, categoryToMetrics }) => {
|
|
449
|
+
const hottestCategories = [...categoryToMetrics].sort(([, metrics1], [, metrics2]) => metrics2.values[0] - metrics1.values[0]);
|
|
450
|
+
return formatTable([
|
|
194
451
|
`Category`,
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
452
|
+
{
|
|
453
|
+
content: `%`,
|
|
454
|
+
align: `right`
|
|
455
|
+
},
|
|
456
|
+
...metrics.map((metric) => ({
|
|
457
|
+
content: capitalizeFirst(metricDisplayName(metric)),
|
|
458
|
+
align: `right`
|
|
459
|
+
})),
|
|
460
|
+
{
|
|
461
|
+
content: `Samples`,
|
|
462
|
+
align: `right`
|
|
463
|
+
}
|
|
464
|
+
], hottestCategories.map(([category, { values, sampleCount }]) => [
|
|
199
465
|
category,
|
|
200
|
-
formatPercent(
|
|
201
|
-
|
|
466
|
+
formatPercent(values[0] / totalValues[0]),
|
|
467
|
+
...metrics.map((metric, index) => formatValue(values[index], metric)),
|
|
202
468
|
formatCount(sampleCount)
|
|
203
|
-
]))
|
|
469
|
+
]));
|
|
204
470
|
};
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
471
|
+
const metricPastTenseVerb = (metric) => {
|
|
472
|
+
switch (metric.type) {
|
|
473
|
+
case `time`: return `took`;
|
|
474
|
+
case `size`: return `allocated`;
|
|
475
|
+
case `custom`: return `recorded`;
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
const formatSamplingInterval = (samplingInterval, metric) => {
|
|
479
|
+
switch (metric.type) {
|
|
480
|
+
case `time`: return formatMicrosecondsExact(samplingInterval * 1e3 * metric.milliseconds);
|
|
481
|
+
case `size`: return formatBytes(samplingInterval * metric.bytes);
|
|
482
|
+
case `custom`: return formatCount(samplingInterval, metric.unit);
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
const formatMetricSections = (profile, options) => profile.metrics.flatMap((metric, index) => {
|
|
486
|
+
const sections = [];
|
|
487
|
+
let sectionOptions = options;
|
|
488
|
+
if (profile.metrics.length > 1) {
|
|
489
|
+
sections.push(formatHeading(options.headingLevel, capitalizeFirst(metricDisplayName(metric))));
|
|
490
|
+
sectionOptions = {
|
|
491
|
+
...options,
|
|
492
|
+
headingLevel: options.headingLevel + 1
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
const callStacksSection = formatHottestCallStacks(index, profile, sectionOptions);
|
|
214
496
|
return [
|
|
215
|
-
|
|
216
|
-
|
|
497
|
+
...sections,
|
|
498
|
+
formatHottestFunctions(index, profile, sectionOptions),
|
|
499
|
+
...callStacksSection === void 0 ? [] : [callStacksSection]
|
|
500
|
+
];
|
|
501
|
+
}).join(`\n\n`);
|
|
502
|
+
const formatHottestFunctions = (metricIndex, profile, options) => {
|
|
503
|
+
const subsectionOptions = {
|
|
504
|
+
...options,
|
|
505
|
+
headingLevel: options.headingLevel + 1
|
|
506
|
+
};
|
|
507
|
+
return [
|
|
508
|
+
formatHeading(options.headingLevel, `Hottest functions`),
|
|
509
|
+
formatHottestSelfFunctions(metricIndex, profile, subsectionOptions),
|
|
510
|
+
formatHottestTotalFunctions(metricIndex, profile, subsectionOptions)
|
|
511
|
+
].join(`\n\n`);
|
|
512
|
+
};
|
|
513
|
+
const formatHottestSelfFunctions = (metricIndex, profile, options) => {
|
|
514
|
+
const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (function1, function2) => function1.selfValues[metricIndex] - function2.selfValues[metricIndex]);
|
|
515
|
+
const subsectionOptions = {
|
|
516
|
+
...options,
|
|
517
|
+
headingLevel: options.headingLevel + 2
|
|
518
|
+
};
|
|
519
|
+
const hottestLinesSections = hottestFunctions.filter((func) => func.lineToMetrics.size > 0).map((func) => formatHottestLines(metricIndex, func, profile, subsectionOptions));
|
|
520
|
+
const hottestCallersSections = hottestFunctions.map((func) => formatHottestCallers(metricIndex, func, profile, subsectionOptions)).filter((section) => section !== void 0);
|
|
521
|
+
const metric = profile.metrics[metricIndex];
|
|
522
|
+
const metricName = metricDisplayName(metric);
|
|
523
|
+
return [
|
|
524
|
+
formatHeading(options.headingLevel, `Self ${metricName}`),
|
|
525
|
+
`Functions ranked by ${metricPastParticipleVerbPhrase(metric)} directly in the function body, excluding callees.`,
|
|
217
526
|
formatTable([
|
|
218
527
|
{
|
|
219
528
|
content: `%`,
|
|
220
529
|
align: `right`
|
|
221
530
|
},
|
|
222
531
|
{
|
|
223
|
-
content:
|
|
532
|
+
content: capitalizeFirst(metricName),
|
|
224
533
|
align: `right`
|
|
225
534
|
},
|
|
226
535
|
{
|
|
@@ -229,28 +538,30 @@ const formatHottestSelfTimeFunctions = ({ totalTime, nodes }, options) => {
|
|
|
229
538
|
},
|
|
230
539
|
`Function`,
|
|
231
540
|
`Location`
|
|
232
|
-
],
|
|
233
|
-
formatPercent(
|
|
234
|
-
|
|
235
|
-
formatCount(selfSampleCount),
|
|
236
|
-
inlineCode(name),
|
|
237
|
-
location
|
|
541
|
+
], hottestFunctions.map((func) => [
|
|
542
|
+
formatPercent(func.selfValues[metricIndex] / profile.totalValues[metricIndex]),
|
|
543
|
+
formatValue(func.selfValues[metricIndex], metric),
|
|
544
|
+
formatCount(func.selfSampleCount),
|
|
545
|
+
inlineCode(func.name),
|
|
546
|
+
formatProfileLocation(func.location, options)
|
|
238
547
|
])),
|
|
239
|
-
...hottestLinesSections.length > 0 ? [
|
|
548
|
+
...hottestLinesSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Lines`), `Lines ranked by contribution to each function's self ${metricName}.`] : [],
|
|
240
549
|
...hottestLinesSections,
|
|
241
|
-
...
|
|
242
|
-
...
|
|
550
|
+
...hottestCallersSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callers`), `Callers ranked by contribution to each function's self ${metricName}. Caller attribution may be imprecise due to inlining.`] : [],
|
|
551
|
+
...hottestCallersSections
|
|
243
552
|
].join(`\n\n`);
|
|
244
553
|
};
|
|
245
|
-
const formatHottestLines = (
|
|
246
|
-
const
|
|
247
|
-
|
|
554
|
+
const formatHottestLines = (metricIndex, func, profile, options) => {
|
|
555
|
+
const selfValue = func.selfValues[metricIndex];
|
|
556
|
+
const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics1], [, metrics2]) => metrics1.values[metricIndex] - metrics2.values[metricIndex]);
|
|
557
|
+
const metric = profile.metrics[metricIndex];
|
|
558
|
+
return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
|
|
248
559
|
{
|
|
249
560
|
content: `%`,
|
|
250
561
|
align: `right`
|
|
251
562
|
},
|
|
252
563
|
{
|
|
253
|
-
content:
|
|
564
|
+
content: capitalizeFirst(metricDisplayName(metric)),
|
|
254
565
|
align: `right`
|
|
255
566
|
},
|
|
256
567
|
{
|
|
@@ -258,23 +569,29 @@ const formatHottestLines = (node, { topN }) => {
|
|
|
258
569
|
align: `right`
|
|
259
570
|
},
|
|
260
571
|
`Location`
|
|
261
|
-
], hottestLines.map(([line,
|
|
262
|
-
formatPercent(
|
|
263
|
-
|
|
264
|
-
formatCount(sampleCount),
|
|
265
|
-
|
|
572
|
+
], hottestLines.map(([line, stats]) => [
|
|
573
|
+
formatPercent(stats.values[metricIndex] / selfValue),
|
|
574
|
+
formatValue(stats.values[metricIndex], metric),
|
|
575
|
+
formatCount(stats.sampleCount),
|
|
576
|
+
func.location ? formatProfileLocation({
|
|
577
|
+
...func.location,
|
|
578
|
+
line,
|
|
579
|
+
column: void 0
|
|
580
|
+
}, options) : String(line)
|
|
266
581
|
]))].join(`\n\n`);
|
|
267
582
|
};
|
|
268
|
-
const formatHottestCallers
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
583
|
+
const formatHottestCallers = (metricIndex, func, profile, options) => {
|
|
584
|
+
const selfValue = func.selfValues[metricIndex];
|
|
585
|
+
const hottestCallers = selectTopN([...func.callerIdToMetrics.values()].filter((entry) => options.includeEntry(entry.caller) && entry.selfValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry1, entry2) => entry1.selfValues[metricIndex] - entry2.selfValues[metricIndex]);
|
|
586
|
+
if (hottestCallers.length === 0) return;
|
|
587
|
+
const metric = profile.metrics[metricIndex];
|
|
588
|
+
return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
|
|
272
589
|
{
|
|
273
590
|
content: `%`,
|
|
274
591
|
align: `right`
|
|
275
592
|
},
|
|
276
593
|
{
|
|
277
|
-
content:
|
|
594
|
+
content: capitalizeFirst(metricDisplayName(metric)),
|
|
278
595
|
align: `right`
|
|
279
596
|
},
|
|
280
597
|
{
|
|
@@ -283,27 +600,34 @@ const formatHottestCallers$1 = (node, options) => {
|
|
|
283
600
|
},
|
|
284
601
|
`Caller`,
|
|
285
602
|
`Location`
|
|
286
|
-
],
|
|
287
|
-
formatPercent(
|
|
288
|
-
|
|
603
|
+
], hottestCallers.map(({ caller, selfValues, selfSampleCount }) => [
|
|
604
|
+
formatPercent(selfValues[metricIndex] / selfValue),
|
|
605
|
+
formatValue(selfValues[metricIndex], metric),
|
|
289
606
|
formatCount(selfSampleCount),
|
|
290
607
|
inlineCode(caller.name),
|
|
291
|
-
caller.location
|
|
608
|
+
formatProfileLocation(caller.location, options)
|
|
292
609
|
]))].join(`\n\n`);
|
|
293
610
|
};
|
|
294
|
-
const
|
|
295
|
-
const
|
|
296
|
-
const
|
|
611
|
+
const formatHottestTotalFunctions = (metricIndex, profile, options) => {
|
|
612
|
+
const totalValue = profile.totalValues[metricIndex];
|
|
613
|
+
const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.totalValues[metricIndex] > 0), options.topN, (func1, func2) => func1.totalValues[metricIndex] - func2.totalValues[metricIndex]);
|
|
614
|
+
const subsectionOptions = {
|
|
615
|
+
...options,
|
|
616
|
+
headingLevel: options.headingLevel + 2
|
|
617
|
+
};
|
|
618
|
+
const calleeSections = hottestFunctions.map((func) => formatHottestCallees(metricIndex, func, profile, subsectionOptions)).filter((section) => section !== void 0);
|
|
619
|
+
const metric = profile.metrics[metricIndex];
|
|
620
|
+
const metricName = metricDisplayName(metric);
|
|
297
621
|
return [
|
|
298
|
-
|
|
299
|
-
`Functions ranked by total
|
|
622
|
+
formatHeading(options.headingLevel, `Total ${metricName}`),
|
|
623
|
+
`Functions ranked by total ${metricPastParticipleVerbPhrase(metric)} in the function and all its callees.`,
|
|
300
624
|
formatTable([
|
|
301
625
|
{
|
|
302
626
|
content: `%`,
|
|
303
627
|
align: `right`
|
|
304
628
|
},
|
|
305
629
|
{
|
|
306
|
-
content:
|
|
630
|
+
content: capitalizeFirst(metricName),
|
|
307
631
|
align: `right`
|
|
308
632
|
},
|
|
309
633
|
{
|
|
@@ -312,27 +636,30 @@ const formatHottestTotalTimeFunctions = ({ totalTime, nodes }, options) => {
|
|
|
312
636
|
},
|
|
313
637
|
`Function`,
|
|
314
638
|
`Location`
|
|
315
|
-
],
|
|
316
|
-
formatPercent(
|
|
317
|
-
|
|
318
|
-
formatCount(
|
|
319
|
-
inlineCode(
|
|
320
|
-
|
|
639
|
+
], hottestFunctions.map((func) => [
|
|
640
|
+
formatPercent(func.totalValues[metricIndex] / totalValue),
|
|
641
|
+
formatValue(func.totalValues[metricIndex], metric),
|
|
642
|
+
formatCount(func.totalSampleCount),
|
|
643
|
+
inlineCode(func.name),
|
|
644
|
+
formatProfileLocation(func.location, options)
|
|
321
645
|
])),
|
|
322
|
-
...
|
|
323
|
-
...
|
|
646
|
+
...calleeSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callees`), `Callees ranked by contribution to each function's total ${metricName}. Callee attribution may be imprecise due to inlining.`] : [],
|
|
647
|
+
...calleeSections
|
|
324
648
|
].join(`\n\n`);
|
|
325
649
|
};
|
|
326
|
-
const formatHottestCallees
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
650
|
+
const formatHottestCallees = (metricIndex, func, profile, options) => {
|
|
651
|
+
const totalValue = func.totalValues[metricIndex];
|
|
652
|
+
const hottestCallees = selectTopN([...func.calleeIdToMetrics.values()].filter((entry) => options.includeEntry(entry.callee) && entry.totalValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry1, entry2) => entry1.totalValues[metricIndex] - entry2.totalValues[metricIndex]);
|
|
653
|
+
if (hottestCallees.length === 0) return;
|
|
654
|
+
const metric = profile.metrics[metricIndex];
|
|
655
|
+
const metricName = metricDisplayName(metric);
|
|
656
|
+
return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
|
|
330
657
|
{
|
|
331
658
|
content: `%`,
|
|
332
659
|
align: `right`
|
|
333
660
|
},
|
|
334
661
|
{
|
|
335
|
-
content:
|
|
662
|
+
content: capitalizeFirst(metricName),
|
|
336
663
|
align: `right`
|
|
337
664
|
},
|
|
338
665
|
{
|
|
@@ -341,32 +668,35 @@ const formatHottestCallees$1 = (node, options) => {
|
|
|
341
668
|
},
|
|
342
669
|
`Callee`,
|
|
343
670
|
`Location`
|
|
344
|
-
],
|
|
345
|
-
formatPercent(
|
|
346
|
-
|
|
671
|
+
], hottestCallees.map(({ callee, totalValues, totalSampleCount }) => [
|
|
672
|
+
formatPercent(totalValues[metricIndex] / totalValue),
|
|
673
|
+
formatValue(totalValues[metricIndex], metric),
|
|
347
674
|
formatCount(totalSampleCount),
|
|
348
675
|
inlineCode(callee.name),
|
|
349
|
-
callee.location
|
|
676
|
+
formatProfileLocation(callee.location, options)
|
|
350
677
|
]))].join(`\n\n`);
|
|
351
678
|
};
|
|
352
|
-
const formatHottestCallStacks
|
|
353
|
-
const
|
|
679
|
+
const formatHottestCallStacks = (metricIndex, profile, options) => {
|
|
680
|
+
const totalValue = profile.totalValues[metricIndex];
|
|
681
|
+
const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
|
|
354
682
|
...callStack,
|
|
355
|
-
|
|
356
|
-
})).filter((callStack) => callStack.
|
|
683
|
+
frames: callStack.frames.filter(options.includeEntry)
|
|
684
|
+
})).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack1, callStack2) => callStack1.selfValues[metricIndex] - callStack2.selfValues[metricIndex]);
|
|
357
685
|
if (hottestCallStacks.length === 0) return;
|
|
686
|
+
const metric = profile.metrics[metricIndex];
|
|
687
|
+
const metricName = metricDisplayName(metric);
|
|
358
688
|
const commonCallStack = findCommonCallStack(hottestCallStacks);
|
|
359
689
|
return [
|
|
360
|
-
|
|
361
|
-
`Call stacks ranked by
|
|
362
|
-
...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack)}`] : [],
|
|
690
|
+
formatHeading(options.headingLevel, `Hottest call stacks`),
|
|
691
|
+
`Call stacks ranked by ${metricPastParticipleVerbPhrase(metric)} in their top frame.`,
|
|
692
|
+
...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack, options)}`] : [],
|
|
363
693
|
formatTable([
|
|
364
694
|
{
|
|
365
695
|
content: `%`,
|
|
366
696
|
align: `right`
|
|
367
697
|
},
|
|
368
698
|
{
|
|
369
|
-
content:
|
|
699
|
+
content: capitalizeFirst(metricName),
|
|
370
700
|
align: `right`
|
|
371
701
|
},
|
|
372
702
|
{
|
|
@@ -374,194 +704,439 @@ const formatHottestCallStacks$1 = ({ totalTime, callStacks }, options) => {
|
|
|
374
704
|
align: `right`
|
|
375
705
|
},
|
|
376
706
|
`Call stack`
|
|
377
|
-
], hottestCallStacks.map(({
|
|
378
|
-
formatPercent(
|
|
379
|
-
|
|
707
|
+
], hottestCallStacks.map(({ frames, selfValues, selfSampleCount }) => [
|
|
708
|
+
formatPercent(selfValues[metricIndex] / totalValue),
|
|
709
|
+
formatValue(selfValues[metricIndex], metric),
|
|
380
710
|
formatCount(selfSampleCount),
|
|
381
|
-
formatCallStack(commonCallStack.length > 0 ?
|
|
711
|
+
formatCallStack(commonCallStack.length > 0 ? frames.slice(0, -commonCallStack.length) : frames, options)
|
|
382
712
|
]))
|
|
383
713
|
].join(`\n\n`);
|
|
384
714
|
};
|
|
715
|
+
const formatCallStack = (nodes, options) => nodes.map((node, index) => {
|
|
716
|
+
const name = inlineCode(node.name);
|
|
717
|
+
if (!node.location) return name;
|
|
718
|
+
const previousHref = nodes[index - 1]?.location?.url.href;
|
|
719
|
+
if (!previousHref || node.location.url.href !== previousHref) return `${name} (${formatProfileLocation(node.location, options)})`;
|
|
720
|
+
const { line, column } = node.location;
|
|
721
|
+
if (line === void 0) return name;
|
|
722
|
+
return `${name} (${line}${column === void 0 ? `` : `:${column}`})`;
|
|
723
|
+
}).join(` ← `);
|
|
724
|
+
const metricPastParticipleVerbPhrase = (metric) => {
|
|
725
|
+
switch (metric.type) {
|
|
726
|
+
case `time`: return `time spent`;
|
|
727
|
+
case `size`: return `bytes allocated`;
|
|
728
|
+
case `custom`: return `${metricDisplayName(metric)} recorded`;
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
const metricDisplayName = (metric) => {
|
|
732
|
+
switch (metric.type) {
|
|
733
|
+
case `time`:
|
|
734
|
+
case `size`: return metric.type;
|
|
735
|
+
case `custom`: return metric.name;
|
|
736
|
+
}
|
|
737
|
+
};
|
|
738
|
+
const formatValue = (value, metric) => {
|
|
739
|
+
switch (metric.type) {
|
|
740
|
+
case `time`: return formatMilliseconds(value * metric.milliseconds);
|
|
741
|
+
case `size`: return formatBytes(value * metric.bytes);
|
|
742
|
+
case `custom`: return formatCount(value, metric.unit);
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
const capitalizeFirst = (string) => string.length === 0 ? string : string[0].toUpperCase() + string.slice(1);
|
|
385
746
|
|
|
386
747
|
//#endregion
|
|
387
|
-
//#region src/
|
|
388
|
-
const
|
|
748
|
+
//#region src/profile/metric.ts
|
|
749
|
+
const determineMetric = ({ name, unit }) => METRICS.get(unit.toLowerCase()) ?? {
|
|
750
|
+
type: `custom`,
|
|
751
|
+
name,
|
|
752
|
+
unit
|
|
753
|
+
};
|
|
754
|
+
const NANOSECONDS = {
|
|
755
|
+
type: `time`,
|
|
756
|
+
milliseconds: 1e-6
|
|
757
|
+
};
|
|
758
|
+
const MICROSECONDS = {
|
|
759
|
+
type: `time`,
|
|
760
|
+
milliseconds: .001
|
|
761
|
+
};
|
|
762
|
+
const MILLISECONDS = {
|
|
763
|
+
type: `time`,
|
|
764
|
+
milliseconds: 1
|
|
765
|
+
};
|
|
766
|
+
const SECONDS = {
|
|
767
|
+
type: `time`,
|
|
768
|
+
milliseconds: 1e3
|
|
769
|
+
};
|
|
770
|
+
const BYTES = {
|
|
771
|
+
type: `size`,
|
|
772
|
+
bytes: 1
|
|
773
|
+
};
|
|
774
|
+
const KILOBYTES = {
|
|
775
|
+
type: `size`,
|
|
776
|
+
bytes: 1024
|
|
777
|
+
};
|
|
778
|
+
const MEGABYTES = {
|
|
779
|
+
type: `size`,
|
|
780
|
+
bytes: 1 << 20
|
|
781
|
+
};
|
|
782
|
+
const GIGABYTES = {
|
|
783
|
+
type: `size`,
|
|
784
|
+
bytes: 1 << 30
|
|
785
|
+
};
|
|
786
|
+
const METRICS = new Map([
|
|
787
|
+
[`nanoseconds`, NANOSECONDS],
|
|
788
|
+
[`nanosecond`, NANOSECONDS],
|
|
789
|
+
[`nanos`, NANOSECONDS],
|
|
790
|
+
[`ns`, NANOSECONDS],
|
|
791
|
+
[`microseconds`, MICROSECONDS],
|
|
792
|
+
[`microsecond`, MICROSECONDS],
|
|
793
|
+
[`micros`, MICROSECONDS],
|
|
794
|
+
[`us`, MICROSECONDS],
|
|
795
|
+
[`μs`, MICROSECONDS],
|
|
796
|
+
[`milliseconds`, MILLISECONDS],
|
|
797
|
+
[`millisecond`, MILLISECONDS],
|
|
798
|
+
[`millis`, MILLISECONDS],
|
|
799
|
+
[`ms`, MILLISECONDS],
|
|
800
|
+
[`seconds`, SECONDS],
|
|
801
|
+
[`second`, SECONDS],
|
|
802
|
+
[`secs`, SECONDS],
|
|
803
|
+
[`sec`, SECONDS],
|
|
804
|
+
[`s`, SECONDS],
|
|
805
|
+
[`bytes`, BYTES],
|
|
806
|
+
[`byte`, BYTES],
|
|
807
|
+
[`b`, BYTES],
|
|
808
|
+
[`kilobytes`, KILOBYTES],
|
|
809
|
+
[`kilobyte`, KILOBYTES],
|
|
810
|
+
[`kbytes`, KILOBYTES],
|
|
811
|
+
[`kbyte`, KILOBYTES],
|
|
812
|
+
[`kb`, KILOBYTES],
|
|
813
|
+
[`megabytes`, MEGABYTES],
|
|
814
|
+
[`megabyte`, MEGABYTES],
|
|
815
|
+
[`mbytes`, MEGABYTES],
|
|
816
|
+
[`mbyte`, MEGABYTES],
|
|
817
|
+
[`mb`, MEGABYTES],
|
|
818
|
+
[`gigabytes`, GIGABYTES],
|
|
819
|
+
[`gigabyte`, GIGABYTES],
|
|
820
|
+
[`gbytes`, GIGABYTES],
|
|
821
|
+
[`gbyte`, GIGABYTES],
|
|
822
|
+
[`gb`, GIGABYTES],
|
|
823
|
+
[`none`, {
|
|
824
|
+
type: `custom`,
|
|
825
|
+
name: `count`,
|
|
826
|
+
unit: `count`
|
|
827
|
+
}]
|
|
828
|
+
]);
|
|
389
829
|
|
|
390
830
|
//#endregion
|
|
391
|
-
//#region src/
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
const
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
const
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
};
|
|
429
|
-
keyToSummarizedCallStack.set(key, summarizedCallStack);
|
|
430
|
-
}
|
|
431
|
-
rawNodeIdToSummarizedCallStack.set(rawNodeId, summarizedCallStack);
|
|
432
|
-
}
|
|
433
|
-
summarizedCallStack.selfTime += timeDelta;
|
|
434
|
-
summarizedCallStack.selfSampleCount++;
|
|
435
|
-
const callStack = summarizedCallStack.nodes;
|
|
436
|
-
for (const stackNode of callStack) {
|
|
437
|
-
if (ordinalToIterationLastVisited[stackNode.ordinal] === index) continue;
|
|
438
|
-
ordinalToIterationLastVisited[stackNode.ordinal] = index;
|
|
439
|
-
stackNode.totalTime += timeDelta;
|
|
440
|
-
stackNode.totalSampleCount++;
|
|
441
|
-
}
|
|
442
|
-
const caller = callStack[1];
|
|
443
|
-
if (caller) {
|
|
444
|
-
let callerSelfTime = node.callerIdToStats.get(caller.id);
|
|
445
|
-
if (!callerSelfTime) {
|
|
446
|
-
callerSelfTime = {
|
|
447
|
-
caller,
|
|
448
|
-
selfTime: 0,
|
|
449
|
-
selfSampleCount: 0
|
|
450
|
-
};
|
|
451
|
-
node.callerIdToStats.set(caller.id, callerSelfTime);
|
|
452
|
-
}
|
|
453
|
-
callerSelfTime.selfTime += timeDelta;
|
|
454
|
-
callerSelfTime.selfSampleCount++;
|
|
455
|
-
}
|
|
456
|
-
for (let i = 0; i < callStack.length - 1; i++) {
|
|
457
|
-
const callee = callStack[i];
|
|
458
|
-
const caller = callStack[i + 1];
|
|
459
|
-
const pairOrdinal = caller.ordinal * summarizedNodeCount + callee.ordinal;
|
|
460
|
-
if (pairOrdinalToIterationLastVisited[pairOrdinal] === index) continue;
|
|
461
|
-
pairOrdinalToIterationLastVisited[pairOrdinal] = index;
|
|
462
|
-
let calleeTotalTime = caller.calleeIdToStats.get(callee.id);
|
|
463
|
-
if (!calleeTotalTime) {
|
|
464
|
-
calleeTotalTime = {
|
|
465
|
-
callee,
|
|
466
|
-
totalTime: 0,
|
|
467
|
-
totalSampleCount: 0
|
|
468
|
-
};
|
|
469
|
-
caller.calleeIdToStats.set(callee.id, calleeTotalTime);
|
|
470
|
-
}
|
|
471
|
-
calleeTotalTime.totalTime += timeDelta;
|
|
472
|
-
calleeTotalTime.totalSampleCount++;
|
|
473
|
-
}
|
|
474
|
-
let categoryStats = callFrameCategoryToStats.get(node.category);
|
|
475
|
-
if (!categoryStats) {
|
|
476
|
-
categoryStats = {
|
|
477
|
-
time: 0,
|
|
478
|
-
sampleCount: 0
|
|
479
|
-
};
|
|
480
|
-
callFrameCategoryToStats.set(node.category, categoryStats);
|
|
481
|
-
}
|
|
482
|
-
categoryStats.time += timeDelta;
|
|
483
|
-
categoryStats.sampleCount++;
|
|
831
|
+
//#region src/formats/pprof/format.ts
|
|
832
|
+
const formatPprof = (profile, options) => formatProfile(profile, options);
|
|
833
|
+
|
|
834
|
+
//#endregion
|
|
835
|
+
//#region src/formats/pprof/parse.ts
|
|
836
|
+
const parsePprof = (data) => parsePprofInternal(Profile.decode(data));
|
|
837
|
+
const parsePprofInternal = (profile) => {
|
|
838
|
+
const { strings } = profile.stringTable;
|
|
839
|
+
const valueTypes = profile.sampleType.map(({ type, unit }) => ({
|
|
840
|
+
type: strings[Number(type)] ?? ``,
|
|
841
|
+
unit: strings[Number(unit)] ?? ``
|
|
842
|
+
}));
|
|
843
|
+
const functionIdToIndex = [];
|
|
844
|
+
const functions = [];
|
|
845
|
+
for (const func of profile.function) {
|
|
846
|
+
const id = Number(func.id);
|
|
847
|
+
functionIdToIndex[id] = functions.length;
|
|
848
|
+
functions.push({
|
|
849
|
+
id,
|
|
850
|
+
name: strings[Number(func.name)] ?? ``,
|
|
851
|
+
systemName: strings[Number(func.systemName)] ?? ``,
|
|
852
|
+
filename: strings[Number(func.filename)] ?? ``,
|
|
853
|
+
startLine: Number(func.startLine)
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
const locationIdToIndex = [];
|
|
857
|
+
const locations = [];
|
|
858
|
+
for (const location of profile.location) {
|
|
859
|
+
const id = Number(location.id);
|
|
860
|
+
locationIdToIndex[id] = locations.length;
|
|
861
|
+
locations.push({
|
|
862
|
+
id,
|
|
863
|
+
lines: location.line.map(({ functionId, line }) => ({
|
|
864
|
+
functionId: functionIdToIndex[Number(functionId)],
|
|
865
|
+
line: Number(line)
|
|
866
|
+
}))
|
|
867
|
+
});
|
|
484
868
|
}
|
|
485
869
|
return {
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
870
|
+
valueTypes,
|
|
871
|
+
samples: profile.sample.map(({ locationId, value }) => ({
|
|
872
|
+
locationIds: locationId.map((id) => locationIdToIndex[Number(id)]),
|
|
873
|
+
values: value.map(Number)
|
|
874
|
+
})),
|
|
875
|
+
locations,
|
|
876
|
+
functions
|
|
492
877
|
};
|
|
493
878
|
};
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
const
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
keyToSummarizedNode.set(key, summarizedNode);
|
|
523
|
-
}
|
|
524
|
-
rawIdToSummarizedNode.set(node.id, summarizedNode);
|
|
525
|
-
summarizedNode.selfSampleCount += node.hitCount;
|
|
526
|
-
if (node.positionTicks) {
|
|
527
|
-
const tickStats = [];
|
|
528
|
-
let totalTicks = 0;
|
|
529
|
-
for (const tick of node.positionTicks) {
|
|
530
|
-
const line = tick.line - 1;
|
|
531
|
-
let stats = summarizedNode.lineToStats.get(line);
|
|
532
|
-
if (!stats) {
|
|
533
|
-
stats = {
|
|
534
|
-
time: 0,
|
|
535
|
-
sampleCount: 0
|
|
536
|
-
};
|
|
537
|
-
summarizedNode.lineToStats.set(line, stats);
|
|
538
|
-
}
|
|
539
|
-
stats.sampleCount += tick.ticks;
|
|
540
|
-
totalTicks += tick.ticks;
|
|
541
|
-
tickStats.push(stats);
|
|
879
|
+
|
|
880
|
+
//#endregion
|
|
881
|
+
//#region src/formats/pprof/summarize.ts
|
|
882
|
+
const summarizePprof = ({ valueTypes, samples, locations, functions }, options) => {
|
|
883
|
+
const nonCountValueTypes = [...valueTypes.entries()].filter(([, valueType]) => valueType.unit.toLowerCase() !== `count`);
|
|
884
|
+
const profileBuilder = new ProfileBuilder({
|
|
885
|
+
metrics: nonCountValueTypes.map(([, valueType]) => determineMetric({
|
|
886
|
+
name: valueType.type,
|
|
887
|
+
unit: valueType.unit
|
|
888
|
+
})),
|
|
889
|
+
functionKey: (func) => func.id,
|
|
890
|
+
functionInput: (func) => ({
|
|
891
|
+
name: func.name || func.systemName,
|
|
892
|
+
location: {
|
|
893
|
+
urlOrPath: func.filename,
|
|
894
|
+
line: func.startLine > 0 ? func.startLine : void 0
|
|
895
|
+
}
|
|
896
|
+
})
|
|
897
|
+
}, options);
|
|
898
|
+
for (const sample of samples) {
|
|
899
|
+
const { locationIds, values } = sample;
|
|
900
|
+
const nodes = [];
|
|
901
|
+
let calleeLine;
|
|
902
|
+
for (const locationId of locationIds) {
|
|
903
|
+
const location = locations[locationId];
|
|
904
|
+
for (const { functionId, line } of location.lines) {
|
|
905
|
+
nodes.push(functions[functionId]);
|
|
906
|
+
calleeLine ??= line;
|
|
542
907
|
}
|
|
543
|
-
const fractions = new Float64Array(node.positionTicks.length);
|
|
544
|
-
for (let i = 0; i < node.positionTicks.length; i++) fractions[i] = node.positionTicks[i].ticks / totalTicks;
|
|
545
|
-
rawIdToTickInfo.set(node.id, {
|
|
546
|
-
stats: tickStats,
|
|
547
|
-
fractions
|
|
548
|
-
});
|
|
549
|
-
}
|
|
550
|
-
if (node.children) for (const childId of node.children) {
|
|
551
|
-
if (rawIdToParentRawId.has(childId)) throw new Error(`Unexpected node ID with multiple parent IDs: ${childId}`);
|
|
552
|
-
rawIdToParentRawId.set(childId, node.id);
|
|
553
908
|
}
|
|
909
|
+
if (nodes.length === 0) continue;
|
|
910
|
+
profileBuilder.addSample({
|
|
911
|
+
values: nonCountValueTypes.map(([index]) => values[index]),
|
|
912
|
+
nodes,
|
|
913
|
+
line: calleeLine
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
return profileBuilder.build();
|
|
917
|
+
};
|
|
918
|
+
|
|
919
|
+
//#endregion
|
|
920
|
+
//#region src/formats/pprof/index.ts
|
|
921
|
+
const detectPprof = (data) => {
|
|
922
|
+
if (data.length === 0) return;
|
|
923
|
+
let profile;
|
|
924
|
+
try {
|
|
925
|
+
profile = Profile.decode(data);
|
|
926
|
+
} catch {
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
if (profile.stringTable.strings[0] !== ``) return;
|
|
930
|
+
return parsePprofInternal(profile);
|
|
931
|
+
};
|
|
932
|
+
/**
|
|
933
|
+
* Converts the given pprof to Markdown.
|
|
934
|
+
*
|
|
935
|
+
* It is assumed that {@link data} is a valid pprof (raw protobuf). The behavior
|
|
936
|
+
* of this function is undefined for invalid profiles.
|
|
937
|
+
*
|
|
938
|
+
* pprof can be generated by many tools, including:
|
|
939
|
+
* - Go's [`runtime/pprof`](https://pkg.go.dev/runtime/pprof) package
|
|
940
|
+
* - Node.js's [`pprof`](https://www.npmjs.com/package/pprof) npm package
|
|
941
|
+
* - Python's [`py-spy`](https://github.com/benfred/py-spy)
|
|
942
|
+
* - Rust's [`pprof-rs`](https://github.com/tikv/pprof-rs)
|
|
943
|
+
*/
|
|
944
|
+
const pprofToMd = (data, options) => pprofToMdInternal(parsePprof(data), options);
|
|
945
|
+
const pprofToMdInternal = (pprof, options) => {
|
|
946
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
947
|
+
return formatPprof(summarizePprof(pprof, normalizedOptions), normalizedOptions);
|
|
948
|
+
};
|
|
949
|
+
|
|
950
|
+
//#endregion
|
|
951
|
+
//#region src/formats/speedscope/format.ts
|
|
952
|
+
const formatSpeedscope = (profile, options) => formatProfile(profile, options);
|
|
953
|
+
|
|
954
|
+
//#endregion
|
|
955
|
+
//#region src/helpers/json.ts
|
|
956
|
+
const parseJson = (data) => JSON.parse(data);
|
|
957
|
+
|
|
958
|
+
//#endregion
|
|
959
|
+
//#region src/formats/speedscope/parse.ts
|
|
960
|
+
const parseSpeedscopeProfile = (data) => parseJson(data);
|
|
961
|
+
|
|
962
|
+
//#endregion
|
|
963
|
+
//#region src/formats/speedscope/summarize.ts
|
|
964
|
+
const summarizeSpeedscopeProfile = (profile, options) => {
|
|
965
|
+
const nodes = profile.shared.frames.map((frame, id) => ({
|
|
966
|
+
...frame,
|
|
967
|
+
id
|
|
968
|
+
}));
|
|
969
|
+
return profile.profiles.map((profile) => profile.type === `sampled` ? summarizeSampled(profile, nodes, options) : summarizeEvented(profile, nodes, options));
|
|
970
|
+
};
|
|
971
|
+
const summarizeSampled = (profile, nodes, options) => {
|
|
972
|
+
const profileBuilder = makeProfileBuilder(profile.unit, options);
|
|
973
|
+
for (let index = 0; index < profile.samples.length; index++) {
|
|
974
|
+
const weight = profile.weights[index];
|
|
975
|
+
if (weight <= 0) continue;
|
|
976
|
+
const sampleNodes = profile.samples[index].map((frameIndex) => nodes[frameIndex]).reverse();
|
|
977
|
+
if (sampleNodes.length === 0) continue;
|
|
978
|
+
profileBuilder.addSample({
|
|
979
|
+
values: [weight],
|
|
980
|
+
nodes: sampleNodes
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
return profileBuilder.build();
|
|
984
|
+
};
|
|
985
|
+
const summarizeEvented = (profile, nodes, options) => {
|
|
986
|
+
const builder = makeProfileBuilder(profile.unit, options);
|
|
987
|
+
const stack = [];
|
|
988
|
+
const emitTopSelfTime = (at) => {
|
|
989
|
+
if (stack.length === 0) return;
|
|
990
|
+
const top = stack.at(-1);
|
|
991
|
+
const selfTime = at - top.lastChildClosed;
|
|
992
|
+
if (selfTime <= 0) return;
|
|
993
|
+
builder.addSample({
|
|
994
|
+
values: [selfTime],
|
|
995
|
+
nodes: stack.map((entry) => entry.node).reverse()
|
|
996
|
+
});
|
|
997
|
+
top.lastChildClosed = at;
|
|
998
|
+
};
|
|
999
|
+
for (const event of profile.events) if (event.type === `O`) {
|
|
1000
|
+
emitTopSelfTime(event.at);
|
|
1001
|
+
stack.push({
|
|
1002
|
+
node: nodes[event.frame],
|
|
1003
|
+
lastChildClosed: event.at
|
|
1004
|
+
});
|
|
1005
|
+
} else {
|
|
1006
|
+
emitTopSelfTime(event.at);
|
|
1007
|
+
stack.pop();
|
|
1008
|
+
if (stack.length > 0) stack.at(-1).lastChildClosed = event.at;
|
|
554
1009
|
}
|
|
1010
|
+
return builder.build();
|
|
1011
|
+
};
|
|
1012
|
+
const makeProfileBuilder = (unit, options) => new ProfileBuilder({
|
|
1013
|
+
metrics: [determineMetric({
|
|
1014
|
+
name: unit,
|
|
1015
|
+
unit
|
|
1016
|
+
})],
|
|
1017
|
+
functionKey: (node) => node.id,
|
|
1018
|
+
functionInput: (node) => ({
|
|
1019
|
+
name: node.name,
|
|
1020
|
+
location: node.file ? {
|
|
1021
|
+
urlOrPath: node.file,
|
|
1022
|
+
line: node.line,
|
|
1023
|
+
column: node.col
|
|
1024
|
+
} : void 0
|
|
1025
|
+
})
|
|
1026
|
+
}, options);
|
|
1027
|
+
|
|
1028
|
+
//#endregion
|
|
1029
|
+
//#region src/formats/speedscope/index.ts
|
|
1030
|
+
const detectSpeedscopeProfile = (json) => {
|
|
1031
|
+
if (typeof json !== `object` || json === null) return;
|
|
1032
|
+
const object = json;
|
|
1033
|
+
if (object.$schema !== `https://www.speedscope.app/file-format-schema.json` || !Array.isArray(object.profiles) || typeof object.shared !== `object` || object.shared === null) return;
|
|
1034
|
+
return json;
|
|
1035
|
+
};
|
|
1036
|
+
/**
|
|
1037
|
+
* Converts the given speedscope profile to Markdown.
|
|
1038
|
+
*
|
|
1039
|
+
* It is assumed that {@link data} is a valid speedscope JSON file. The behavior
|
|
1040
|
+
* of this function is undefined for invalid profiles.
|
|
1041
|
+
*
|
|
1042
|
+
* Speedscope profiles can be generated by many tools, including:
|
|
1043
|
+
* - [speedscope](https://www.speedscope.app) (drag and drop any supported profile)
|
|
1044
|
+
* - [rbspy](https://rbspy.github.io) for Ruby
|
|
1045
|
+
* - [py-spy](https://github.com/benfred/py-spy) for Python (`--format speedscope`)
|
|
1046
|
+
* - [pprof-rs](https://github.com/tikv/pprof-rs) for Rust
|
|
1047
|
+
*/
|
|
1048
|
+
const speedscopeProfileToMd = (data, options) => speedscopeProfileToMdInternal(parseSpeedscopeProfile(data), options);
|
|
1049
|
+
const speedscopeProfileToMdInternal = (profile, options) => {
|
|
1050
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1051
|
+
return summarizeSpeedscopeProfile(profile, normalizedOptions).map((profile) => formatSpeedscope(profile, normalizedOptions)).join(`\n\n`);
|
|
1052
|
+
};
|
|
1053
|
+
|
|
1054
|
+
//#endregion
|
|
1055
|
+
//#region src/formats/v8/cpu-profile/format.ts
|
|
1056
|
+
const formatV8CpuProfile = (profile, options) => formatProfile(profile, options);
|
|
1057
|
+
|
|
1058
|
+
//#endregion
|
|
1059
|
+
//#region src/formats/v8/cpu-profile/parse.ts
|
|
1060
|
+
const parseV8CpuProfile = (data) => parseJson(data);
|
|
1061
|
+
|
|
1062
|
+
//#endregion
|
|
1063
|
+
//#region src/formats/v8/common.ts
|
|
1064
|
+
const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
|
|
1065
|
+
const callFrameFunctionInput = (callFrame) => {
|
|
1066
|
+
const { functionName, url, lineNumber, columnNumber } = callFrame;
|
|
555
1067
|
return {
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
1068
|
+
name: functionName,
|
|
1069
|
+
location: url ? {
|
|
1070
|
+
urlOrPath: url,
|
|
1071
|
+
line: lineNumber + 1,
|
|
1072
|
+
column: columnNumber + 1
|
|
1073
|
+
} : void 0
|
|
560
1074
|
};
|
|
561
1075
|
};
|
|
562
1076
|
|
|
563
1077
|
//#endregion
|
|
564
|
-
//#region src/v8/cpu-profile/
|
|
1078
|
+
//#region src/formats/v8/cpu-profile/summarize.ts
|
|
1079
|
+
const summarizeV8CpuProfile = (profile, options) => {
|
|
1080
|
+
const profileBuilder = new ProfileBuilder({
|
|
1081
|
+
metrics: [MICROSECONDS],
|
|
1082
|
+
functionKey: (node) => callFrameKey(node.callFrame),
|
|
1083
|
+
functionInput: (node) => callFrameFunctionInput(node.callFrame)
|
|
1084
|
+
}, options);
|
|
1085
|
+
const idToIndex = [];
|
|
1086
|
+
for (let index = 0; index < profile.nodes.length; index++) {
|
|
1087
|
+
const node = profile.nodes[index];
|
|
1088
|
+
idToIndex[node.id] = index;
|
|
1089
|
+
node.id = index;
|
|
1090
|
+
}
|
|
1091
|
+
const indexToParentIndex = new Int32Array(profile.nodes.length).fill(-1);
|
|
1092
|
+
for (const node of profile.nodes) if (node.children) for (const childId of node.children) {
|
|
1093
|
+
const childIndex = idToIndex[childId];
|
|
1094
|
+
if (childIndex === void 0) continue;
|
|
1095
|
+
indexToParentIndex[childIndex] = node.id;
|
|
1096
|
+
}
|
|
1097
|
+
const indexToSelfTime = new Float64Array(profile.nodes.length);
|
|
1098
|
+
for (let index = 0; index < profile.samples.length; index++) {
|
|
1099
|
+
const nodeIndex = idToIndex[profile.samples[index]];
|
|
1100
|
+
if (nodeIndex === void 0) continue;
|
|
1101
|
+
const node = profile.nodes[nodeIndex];
|
|
1102
|
+
const timeDelta = profile.timeDeltas[index];
|
|
1103
|
+
indexToSelfTime[nodeIndex] += timeDelta;
|
|
1104
|
+
const nodes = [];
|
|
1105
|
+
let currentNode = node;
|
|
1106
|
+
while (true) {
|
|
1107
|
+
nodes.push(currentNode);
|
|
1108
|
+
const parentIndex = indexToParentIndex[currentNode.id];
|
|
1109
|
+
if (parentIndex === -1) break;
|
|
1110
|
+
currentNode = profile.nodes[parentIndex];
|
|
1111
|
+
}
|
|
1112
|
+
profileBuilder.addSample({
|
|
1113
|
+
values: [timeDelta],
|
|
1114
|
+
nodes
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1117
|
+
for (const node of profile.nodes) {
|
|
1118
|
+
if (!node.positionTicks) continue;
|
|
1119
|
+
const selfTime = indexToSelfTime[node.id];
|
|
1120
|
+
profileBuilder.addLineMetrics({
|
|
1121
|
+
node,
|
|
1122
|
+
lines: node.positionTicks.map(({ line, ticks }) => ({
|
|
1123
|
+
line,
|
|
1124
|
+
sampleCount: ticks,
|
|
1125
|
+
values: [Math.round(selfTime * ticks / node.hitCount)]
|
|
1126
|
+
}))
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
return profileBuilder.build();
|
|
1130
|
+
};
|
|
1131
|
+
|
|
1132
|
+
//#endregion
|
|
1133
|
+
//#region src/formats/v8/cpu-profile/index.ts
|
|
1134
|
+
const detectV8CpuProfile = (json) => {
|
|
1135
|
+
if (typeof json !== `object` || json === null) return;
|
|
1136
|
+
const object = json;
|
|
1137
|
+
if (!Array.isArray(object.nodes) || !Array.isArray(object.timeDeltas)) return;
|
|
1138
|
+
return json;
|
|
1139
|
+
};
|
|
565
1140
|
/**
|
|
566
1141
|
* Converts the given V8 CPU profile to Markdown.
|
|
567
1142
|
*
|
|
@@ -570,336 +1145,86 @@ const computeProfileGraph$1 = (profile, options) => {
|
|
|
570
1145
|
*
|
|
571
1146
|
* You can generate a V8 CPU profile in several ways:
|
|
572
1147
|
* - [`node --cpu-prof`](https://nodejs.org/api/cli.html#cpu-prof)
|
|
573
|
-
* - [`deno --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
|
|
1148
|
+
* - [`deno run --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
|
|
574
1149
|
* - [`bun --cpu-prof`](https://bun.com/docs/project/benchmarking#cpu-profiling)
|
|
1150
|
+
* (NOTE: output was incorrect until
|
|
1151
|
+
* [v1.3.13](https://bun.com/blog/bun-v1.3.13#node-js-compatibility-improvements))
|
|
1152
|
+
* - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
|
|
1153
|
+
* [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
|
|
1154
|
+
* or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
|
|
1155
|
+
* [Chrome DevTools](https://developer.chrome.com/docs/devtools/performance/nodejs)
|
|
1156
|
+
* - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/performance#record)
|
|
575
1157
|
*
|
|
576
1158
|
* Lower the sampling interval to capture more granular data.
|
|
577
1159
|
*/
|
|
578
|
-
const v8CpuProfileToMd = (data, options) =>
|
|
579
|
-
|
|
580
|
-
|
|
1160
|
+
const v8CpuProfileToMd = (data, options) => v8CpuProfileToMdInternal(parseV8CpuProfile(data), options);
|
|
1161
|
+
const v8CpuProfileToMdInternal = (profile, options) => {
|
|
1162
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1163
|
+
return formatV8CpuProfile(summarizeV8CpuProfile(profile, normalizedOptions), normalizedOptions);
|
|
581
1164
|
};
|
|
582
1165
|
|
|
583
1166
|
//#endregion
|
|
584
|
-
//#region src/v8/heap-profile/format.ts
|
|
585
|
-
const
|
|
586
|
-
`# Heap profile`,
|
|
587
|
-
formatOverallProfileSummary(profile),
|
|
588
|
-
formatHottestFunctions(profile, options),
|
|
589
|
-
formatHottestCallStacks(profile, options)
|
|
590
|
-
].filter(Boolean).join(`\n\n`)}\n`;
|
|
591
|
-
const formatOverallProfileSummary = ({ totalSize, sampleCount, samplingInterval, callFrameCategoryToStats }) => {
|
|
592
|
-
const hottestCallFrameCategories = [...callFrameCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
|
|
593
|
-
return [`Allocated ${formatBytes(totalSize)} over ${formatCount(sampleCount, `sample`)} (${formatBytes(samplingInterval)} per sample).`, formatTable([
|
|
594
|
-
`Category`,
|
|
595
|
-
`%`,
|
|
596
|
-
`Size`,
|
|
597
|
-
`Samples`
|
|
598
|
-
], hottestCallFrameCategories.map(([category, { size, sampleCount }]) => [
|
|
599
|
-
category,
|
|
600
|
-
formatPercent(size / totalSize),
|
|
601
|
-
formatBytes(size),
|
|
602
|
-
formatCount(sampleCount)
|
|
603
|
-
]))].join(`\n\n`);
|
|
604
|
-
};
|
|
605
|
-
const formatHottestFunctions = (profile, options) => [
|
|
606
|
-
`## Hottest functions`,
|
|
607
|
-
formatHottestSelfSizeFunctions(profile, options),
|
|
608
|
-
formatHottestTotalSizeFunctions(profile, options)
|
|
609
|
-
].join(`\n\n`);
|
|
610
|
-
const formatHottestSelfSizeFunctions = ({ totalSize, nodes }, options) => {
|
|
611
|
-
const hottestSelfSizeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.selfSize - node1.selfSize);
|
|
612
|
-
const hottestCallerSections = hottestSelfSizeNodes.map((node) => formatHottestCallers(node, options)).filter((section) => section !== void 0);
|
|
613
|
-
return [
|
|
614
|
-
`### Self size`,
|
|
615
|
-
`Functions ranked by bytes allocated directly in the function body, excluding callees.`,
|
|
616
|
-
formatTable([
|
|
617
|
-
{
|
|
618
|
-
content: `%`,
|
|
619
|
-
align: `right`
|
|
620
|
-
},
|
|
621
|
-
{
|
|
622
|
-
content: `Size`,
|
|
623
|
-
align: `right`
|
|
624
|
-
},
|
|
625
|
-
{
|
|
626
|
-
content: `Samples`,
|
|
627
|
-
align: `right`
|
|
628
|
-
},
|
|
629
|
-
`Function`,
|
|
630
|
-
`Location`
|
|
631
|
-
], hottestSelfSizeNodes.map(({ name, location, selfSize, selfSampleCount }) => [
|
|
632
|
-
formatPercent(selfSize / totalSize),
|
|
633
|
-
formatBytes(selfSize),
|
|
634
|
-
formatCount(selfSampleCount),
|
|
635
|
-
inlineCode(name),
|
|
636
|
-
location ?? inlineCode(`<native>`)
|
|
637
|
-
])),
|
|
638
|
-
...hottestCallerSections.length > 0 ? [`#### Callers`, `Callers ranked by contribution to each function's self size.`] : [],
|
|
639
|
-
...hottestCallerSections
|
|
640
|
-
].join(`\n\n`);
|
|
641
|
-
};
|
|
642
|
-
const formatHottestCallers = (node, options) => {
|
|
643
|
-
const hottestCallers = [...node.callerIdToStats.values()].filter(({ caller }) => options.includeRow(caller)).sort((entry1, entry2) => entry2.selfSize - entry1.selfSize).slice(0, Math.ceil(options.topN / 4));
|
|
644
|
-
if (hottestCallers.length === 0) return;
|
|
645
|
-
return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
|
|
646
|
-
{
|
|
647
|
-
content: `%`,
|
|
648
|
-
align: `right`
|
|
649
|
-
},
|
|
650
|
-
{
|
|
651
|
-
content: `Size`,
|
|
652
|
-
align: `right`
|
|
653
|
-
},
|
|
654
|
-
{
|
|
655
|
-
content: `Samples`,
|
|
656
|
-
align: `right`
|
|
657
|
-
},
|
|
658
|
-
`Caller`,
|
|
659
|
-
`Location`
|
|
660
|
-
], hottestCallers.map(({ caller, selfSize, selfSampleCount }) => [
|
|
661
|
-
formatPercent(selfSize / node.selfSize),
|
|
662
|
-
formatBytes(selfSize),
|
|
663
|
-
formatCount(selfSampleCount),
|
|
664
|
-
inlineCode(caller.name),
|
|
665
|
-
caller.location ?? inlineCode(`<native>`)
|
|
666
|
-
]))].join(`\n\n`);
|
|
667
|
-
};
|
|
668
|
-
const formatHottestTotalSizeFunctions = ({ totalSize, nodes }, options) => {
|
|
669
|
-
const hottestTotalSizeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.totalSize - node1.totalSize);
|
|
670
|
-
const hottestCalleeSections = hottestTotalSizeNodes.map((node) => formatHottestCallees(node, options)).filter((section) => section !== void 0);
|
|
671
|
-
return [
|
|
672
|
-
`### Total size`,
|
|
673
|
-
`Functions ranked by total bytes allocated in the function and all its callees.`,
|
|
674
|
-
formatTable([
|
|
675
|
-
{
|
|
676
|
-
content: `%`,
|
|
677
|
-
align: `right`
|
|
678
|
-
},
|
|
679
|
-
{
|
|
680
|
-
content: `Size`,
|
|
681
|
-
align: `right`
|
|
682
|
-
},
|
|
683
|
-
{
|
|
684
|
-
content: `Samples`,
|
|
685
|
-
align: `right`
|
|
686
|
-
},
|
|
687
|
-
`Function`,
|
|
688
|
-
`Location`
|
|
689
|
-
], hottestTotalSizeNodes.map(({ name, location, totalSize: nodeTotal, totalSampleCount }) => [
|
|
690
|
-
formatPercent(nodeTotal / totalSize),
|
|
691
|
-
formatBytes(nodeTotal),
|
|
692
|
-
formatCount(totalSampleCount),
|
|
693
|
-
inlineCode(name),
|
|
694
|
-
location ?? inlineCode(`<native>`)
|
|
695
|
-
])),
|
|
696
|
-
...hottestCalleeSections.length > 0 ? [`#### Callees`, `Callees ranked by contribution to each function's total size.`] : [],
|
|
697
|
-
...hottestCalleeSections
|
|
698
|
-
].join(`\n\n`);
|
|
699
|
-
};
|
|
700
|
-
const formatHottestCallees = (node, options) => {
|
|
701
|
-
const hottestCallees = [...node.calleeIdToStats.values()].filter(({ callee }) => options.includeRow(callee)).sort((entry1, entry2) => entry2.totalSize - entry1.totalSize).slice(0, Math.ceil(options.topN / 4));
|
|
702
|
-
if (hottestCallees.length === 0) return;
|
|
703
|
-
return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
|
|
704
|
-
{
|
|
705
|
-
content: `%`,
|
|
706
|
-
align: `right`
|
|
707
|
-
},
|
|
708
|
-
{
|
|
709
|
-
content: `Size`,
|
|
710
|
-
align: `right`
|
|
711
|
-
},
|
|
712
|
-
{
|
|
713
|
-
content: `Samples`,
|
|
714
|
-
align: `right`
|
|
715
|
-
},
|
|
716
|
-
`Callee`,
|
|
717
|
-
`Location`
|
|
718
|
-
], hottestCallees.map(({ callee, totalSize, totalSampleCount }) => [
|
|
719
|
-
formatPercent(totalSize / node.totalSize),
|
|
720
|
-
formatBytes(totalSize),
|
|
721
|
-
formatCount(totalSampleCount),
|
|
722
|
-
inlineCode(callee.name),
|
|
723
|
-
callee.location ?? inlineCode(`<native>`)
|
|
724
|
-
]))].join(`\n\n`);
|
|
725
|
-
};
|
|
726
|
-
const formatHottestCallStacks = (profile, options) => {
|
|
727
|
-
const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
|
|
728
|
-
...callStack,
|
|
729
|
-
nodes: callStack.nodes.filter(options.includeRow)
|
|
730
|
-
})).filter((callStack) => callStack.nodes.length > 1), options.topN, (callStack1, callStack2) => callStack2.selfSize - callStack1.selfSize);
|
|
731
|
-
if (hottestCallStacks.length === 0) return;
|
|
732
|
-
const commonCallStack = findCommonCallStack(hottestCallStacks);
|
|
733
|
-
return [
|
|
734
|
-
`## Hottest call stacks`,
|
|
735
|
-
`Call stacks ranked by bytes allocated in their top frame.`,
|
|
736
|
-
...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack)}`] : [],
|
|
737
|
-
formatTable([
|
|
738
|
-
{
|
|
739
|
-
content: `%`,
|
|
740
|
-
align: `right`
|
|
741
|
-
},
|
|
742
|
-
{
|
|
743
|
-
content: `Size`,
|
|
744
|
-
align: `right`
|
|
745
|
-
},
|
|
746
|
-
{
|
|
747
|
-
content: `Samples`,
|
|
748
|
-
align: `right`
|
|
749
|
-
},
|
|
750
|
-
`Call stack`
|
|
751
|
-
], hottestCallStacks.map(({ nodes, selfSize, selfSampleCount }) => [
|
|
752
|
-
formatPercent(selfSize / profile.totalSize),
|
|
753
|
-
formatBytes(selfSize),
|
|
754
|
-
formatCount(selfSampleCount),
|
|
755
|
-
formatCallStack(commonCallStack.length > 0 ? nodes.slice(0, -commonCallStack.length) : nodes)
|
|
756
|
-
]))
|
|
757
|
-
].join(`\n\n`);
|
|
758
|
-
};
|
|
1167
|
+
//#region src/formats/v8/heap-profile/format.ts
|
|
1168
|
+
const formatV8HeapProfile = (profile, options) => formatProfile(profile, options);
|
|
759
1169
|
|
|
760
1170
|
//#endregion
|
|
761
|
-
//#region src/v8/heap-profile/parse.ts
|
|
762
|
-
const
|
|
1171
|
+
//#region src/formats/v8/heap-profile/parse.ts
|
|
1172
|
+
const parseV8HeapProfile = (data) => parseJson(data);
|
|
763
1173
|
|
|
764
1174
|
//#endregion
|
|
765
|
-
//#region src/v8/heap-profile/summarize.ts
|
|
766
|
-
const
|
|
767
|
-
const
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
const
|
|
773
|
-
const
|
|
774
|
-
const
|
|
775
|
-
const
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
if (!node) continue;
|
|
780
|
-
node.selfSize += size;
|
|
781
|
-
node.selfSampleCount++;
|
|
782
|
-
let summarizedCallStack = rawNodeIdToSummarizedCallStack.get(nodeId);
|
|
783
|
-
if (!summarizedCallStack) {
|
|
784
|
-
const callStack = summarizeCallStack(graph, nodeId);
|
|
785
|
-
const key = callStack.map((stackNode) => stackNode.ordinal).join(`,`);
|
|
786
|
-
summarizedCallStack = keyToSummarizedCallStack.get(key);
|
|
787
|
-
if (!summarizedCallStack) {
|
|
788
|
-
summarizedCallStack = {
|
|
789
|
-
nodes: callStack,
|
|
790
|
-
selfSize: 0,
|
|
791
|
-
selfSampleCount: 0
|
|
792
|
-
};
|
|
793
|
-
keyToSummarizedCallStack.set(key, summarizedCallStack);
|
|
794
|
-
}
|
|
795
|
-
rawNodeIdToSummarizedCallStack.set(nodeId, summarizedCallStack);
|
|
796
|
-
}
|
|
797
|
-
summarizedCallStack.selfSize += size;
|
|
798
|
-
summarizedCallStack.selfSampleCount++;
|
|
799
|
-
const callStack = summarizedCallStack.nodes;
|
|
800
|
-
for (const stackNode of callStack) {
|
|
801
|
-
if (ordinalToIterationLastVisited[stackNode.ordinal] === index) continue;
|
|
802
|
-
ordinalToIterationLastVisited[stackNode.ordinal] = index;
|
|
803
|
-
stackNode.totalSize += size;
|
|
804
|
-
stackNode.totalSampleCount++;
|
|
805
|
-
}
|
|
806
|
-
const caller = callStack[1];
|
|
807
|
-
if (caller) {
|
|
808
|
-
let callerStats = node.callerIdToStats.get(caller.id);
|
|
809
|
-
if (!callerStats) {
|
|
810
|
-
callerStats = {
|
|
811
|
-
caller,
|
|
812
|
-
selfSize: 0,
|
|
813
|
-
selfSampleCount: 0
|
|
814
|
-
};
|
|
815
|
-
node.callerIdToStats.set(caller.id, callerStats);
|
|
816
|
-
}
|
|
817
|
-
callerStats.selfSize += size;
|
|
818
|
-
callerStats.selfSampleCount++;
|
|
819
|
-
}
|
|
820
|
-
for (let i = 0; i < callStack.length - 1; i++) {
|
|
821
|
-
const callee = callStack[i];
|
|
822
|
-
const caller = callStack[i + 1];
|
|
823
|
-
const pairOrdinal = caller.ordinal * summarizedNodeCount + callee.ordinal;
|
|
824
|
-
if (pairOrdinalToIterationLastVisited[pairOrdinal] === index) continue;
|
|
825
|
-
pairOrdinalToIterationLastVisited[pairOrdinal] = index;
|
|
826
|
-
let calleeStats = caller.calleeIdToStats.get(callee.id);
|
|
827
|
-
if (!calleeStats) {
|
|
828
|
-
calleeStats = {
|
|
829
|
-
callee,
|
|
830
|
-
totalSize: 0,
|
|
831
|
-
totalSampleCount: 0
|
|
832
|
-
};
|
|
833
|
-
caller.calleeIdToStats.set(callee.id, calleeStats);
|
|
834
|
-
}
|
|
835
|
-
calleeStats.totalSize += size;
|
|
836
|
-
calleeStats.totalSampleCount++;
|
|
837
|
-
}
|
|
838
|
-
let categoryStats = callFrameCategoryToStats.get(node.category);
|
|
839
|
-
if (!categoryStats) {
|
|
840
|
-
categoryStats = {
|
|
841
|
-
size: 0,
|
|
842
|
-
sampleCount: 0
|
|
843
|
-
};
|
|
844
|
-
callFrameCategoryToStats.set(node.category, categoryStats);
|
|
845
|
-
}
|
|
846
|
-
categoryStats.size += size;
|
|
847
|
-
categoryStats.sampleCount++;
|
|
848
|
-
}
|
|
849
|
-
return {
|
|
850
|
-
totalSize,
|
|
851
|
-
sampleCount,
|
|
852
|
-
samplingInterval,
|
|
853
|
-
callFrameCategoryToStats,
|
|
854
|
-
nodes: [...graph.keyToSummarizedNode.values()],
|
|
855
|
-
callStacks: [...keyToSummarizedCallStack.values()]
|
|
856
|
-
};
|
|
857
|
-
};
|
|
858
|
-
const computeProfileGraph = (profile, options) => {
|
|
859
|
-
const rawIdToSummarizedNode = /* @__PURE__ */ new Map();
|
|
860
|
-
const keyToSummarizedNode = /* @__PURE__ */ new Map();
|
|
861
|
-
const rawIdToParentRawId = /* @__PURE__ */ new Map();
|
|
862
|
-
let nextOrdinal = 0;
|
|
863
|
-
const stack = [{ node: profile.head }];
|
|
1175
|
+
//#region src/formats/v8/heap-profile/summarize.ts
|
|
1176
|
+
const summarizeV8HeapProfile = (profile, options) => {
|
|
1177
|
+
const profileBuilder = new ProfileBuilder({
|
|
1178
|
+
metrics: [BYTES],
|
|
1179
|
+
functionKey: (node) => callFrameKey(node.callFrame),
|
|
1180
|
+
functionInput: (node) => callFrameFunctionInput(node.callFrame)
|
|
1181
|
+
}, options);
|
|
1182
|
+
const flatNodes = [];
|
|
1183
|
+
const idToIndex = [];
|
|
1184
|
+
const indexToParentIndex = [];
|
|
1185
|
+
const stack = [{
|
|
1186
|
+
node: profile.head,
|
|
1187
|
+
parentIndex: -1
|
|
1188
|
+
}];
|
|
864
1189
|
do {
|
|
865
|
-
const { node,
|
|
866
|
-
const
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
summarizedNode = {
|
|
872
|
-
id: node.id,
|
|
873
|
-
ordinal: nextOrdinal++,
|
|
874
|
-
callFrame: node.callFrame,
|
|
875
|
-
name: functionName || `(anonymous)`,
|
|
876
|
-
location: fileLocation ? `${fileLocation}:${lineNumber + 1}:${columnNumber + 1}` : void 0,
|
|
877
|
-
category: categorizeCallFrame(node.callFrame, options),
|
|
878
|
-
selfSize: 0,
|
|
879
|
-
totalSize: 0,
|
|
880
|
-
selfSampleCount: 0,
|
|
881
|
-
totalSampleCount: 0,
|
|
882
|
-
callerIdToStats: /* @__PURE__ */ new Map(),
|
|
883
|
-
calleeIdToStats: /* @__PURE__ */ new Map()
|
|
884
|
-
};
|
|
885
|
-
keyToSummarizedNode.set(key, summarizedNode);
|
|
886
|
-
}
|
|
887
|
-
rawIdToSummarizedNode.set(node.id, summarizedNode);
|
|
888
|
-
if (parentId !== void 0) rawIdToParentRawId.set(node.id, parentId);
|
|
1190
|
+
const { node, parentIndex } = stack.pop();
|
|
1191
|
+
const index = flatNodes.length;
|
|
1192
|
+
idToIndex[node.id] = index;
|
|
1193
|
+
node.id = index;
|
|
1194
|
+
flatNodes.push(node);
|
|
1195
|
+
indexToParentIndex.push(parentIndex);
|
|
889
1196
|
for (const child of node.children) stack.push({
|
|
890
1197
|
node: child,
|
|
891
|
-
|
|
1198
|
+
parentIndex: index
|
|
892
1199
|
});
|
|
893
1200
|
} while (stack.length > 0);
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
1201
|
+
for (const { size, nodeId } of profile.samples) {
|
|
1202
|
+
const nodeIndex = idToIndex[nodeId];
|
|
1203
|
+
if (nodeIndex === void 0) continue;
|
|
1204
|
+
const nodes = [];
|
|
1205
|
+
let currentIndex = nodeIndex;
|
|
1206
|
+
while (true) {
|
|
1207
|
+
nodes.push(flatNodes[currentIndex]);
|
|
1208
|
+
const parentIndex = indexToParentIndex[currentIndex];
|
|
1209
|
+
if (parentIndex === -1) break;
|
|
1210
|
+
currentIndex = parentIndex;
|
|
1211
|
+
}
|
|
1212
|
+
profileBuilder.addSample({
|
|
1213
|
+
values: [size],
|
|
1214
|
+
nodes
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
return profileBuilder.build();
|
|
899
1218
|
};
|
|
900
1219
|
|
|
901
1220
|
//#endregion
|
|
902
|
-
//#region src/v8/heap-profile/index.ts
|
|
1221
|
+
//#region src/formats/v8/heap-profile/index.ts
|
|
1222
|
+
const detectV8HeapProfile = (json) => {
|
|
1223
|
+
if (typeof json !== `object` || json === null) return;
|
|
1224
|
+
const object = json;
|
|
1225
|
+
if (typeof object.head !== `object` || object.head === null || !Array.isArray(object.samples)) return;
|
|
1226
|
+
return json;
|
|
1227
|
+
};
|
|
903
1228
|
/**
|
|
904
1229
|
* Converts the given V8 sampling heap profile to Markdown.
|
|
905
1230
|
*
|
|
@@ -908,19 +1233,24 @@ const computeProfileGraph = (profile, options) => {
|
|
|
908
1233
|
*
|
|
909
1234
|
* You can generate a V8 heap profile in several ways:
|
|
910
1235
|
* - [`node --heap-prof`](https://nodejs.org/api/cli.html#--heap-prof)
|
|
911
|
-
* - [`
|
|
1236
|
+
* - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
|
|
1237
|
+
* [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
|
|
1238
|
+
* or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
|
|
1239
|
+
* [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
|
|
1240
|
+
* - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
|
|
912
1241
|
*
|
|
913
1242
|
* Note that [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
|
|
914
1243
|
* generates a heap _snapshot_ on exit, not a heap _profile_.
|
|
915
1244
|
*/
|
|
916
|
-
const v8HeapProfileToMd = (data, options) =>
|
|
917
|
-
|
|
918
|
-
|
|
1245
|
+
const v8HeapProfileToMd = (data, options) => v8HeapProfileToMdInternal(parseV8HeapProfile(data), options);
|
|
1246
|
+
const v8HeapProfileToMdInternal = (profile, options) => {
|
|
1247
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1248
|
+
return formatV8HeapProfile(summarizeV8HeapProfile(profile, normalizedOptions), normalizedOptions);
|
|
919
1249
|
};
|
|
920
1250
|
|
|
921
1251
|
//#endregion
|
|
922
|
-
//#region src/v8/heap-snapshot/format.ts
|
|
923
|
-
const
|
|
1252
|
+
//#region src/formats/v8/heap-snapshot/format.ts
|
|
1253
|
+
const formatV8HeapSnapshot = (snapshot, options) => `${[
|
|
924
1254
|
`# Heap snapshot`,
|
|
925
1255
|
formatOverallSummary(snapshot),
|
|
926
1256
|
formatLargestConstructors(snapshot, options),
|
|
@@ -957,7 +1287,7 @@ const formatLargestConstructors = (snapshot, options) => [
|
|
|
957
1287
|
].join(`\n\n`);
|
|
958
1288
|
const formatLargestSelfSizeConstructors = (snapshot, options) => {
|
|
959
1289
|
const { totalSize, constructors } = snapshot;
|
|
960
|
-
const largestConstructors = selectTopN(constructors.filter(options.
|
|
1290
|
+
const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.selfSize - constructor2.selfSize);
|
|
961
1291
|
const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
|
|
962
1292
|
return [
|
|
963
1293
|
`### Self size`,
|
|
@@ -982,16 +1312,16 @@ const formatLargestSelfSizeConstructors = (snapshot, options) => {
|
|
|
982
1312
|
formatBytes(constructor.selfSize),
|
|
983
1313
|
formatCount(constructor.instances.length),
|
|
984
1314
|
inlineCode(constructor.name),
|
|
985
|
-
constructor.location
|
|
1315
|
+
formatProfileLocation(constructor.location, options)
|
|
986
1316
|
])),
|
|
987
1317
|
...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's self size.`] : [],
|
|
988
1318
|
...largestInstanceSections
|
|
989
1319
|
].join(`\n\n`);
|
|
990
1320
|
};
|
|
991
1321
|
const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
|
|
992
|
-
const
|
|
993
|
-
if (
|
|
994
|
-
return [`##### ${inlineCode(constructor.name)} (${constructor.location
|
|
1322
|
+
const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.selfSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.selfSize - group1.selfSize);
|
|
1323
|
+
if (largestInstanceGroups.length === 0) return;
|
|
1324
|
+
return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
|
|
995
1325
|
{
|
|
996
1326
|
content: `%`,
|
|
997
1327
|
align: `right`
|
|
@@ -1000,16 +1330,21 @@ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf
|
|
|
1000
1330
|
content: `Size`,
|
|
1001
1331
|
align: `right`
|
|
1002
1332
|
},
|
|
1333
|
+
{
|
|
1334
|
+
content: `Instances`,
|
|
1335
|
+
align: `right`
|
|
1336
|
+
},
|
|
1003
1337
|
`Path`
|
|
1004
|
-
],
|
|
1005
|
-
formatPercent(
|
|
1006
|
-
formatBytes(
|
|
1007
|
-
|
|
1338
|
+
], largestInstanceGroups.map((group) => [
|
|
1339
|
+
formatPercent(group.selfSize / constructor.selfSize),
|
|
1340
|
+
formatBytes(group.selfSize),
|
|
1341
|
+
formatCount(group.instanceCount),
|
|
1342
|
+
inlineCode(group.retainerPath)
|
|
1008
1343
|
]))].join(`\n\n`);
|
|
1009
1344
|
};
|
|
1010
1345
|
const formatLargestRetainedSizeConstructors = (snapshot, options) => {
|
|
1011
1346
|
const { totalSize, constructors } = snapshot;
|
|
1012
|
-
const largestConstructors = selectTopN(constructors.filter(options.
|
|
1347
|
+
const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.retainedSize - constructor2.retainedSize);
|
|
1013
1348
|
const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
|
|
1014
1349
|
return [
|
|
1015
1350
|
`### Retained size`,
|
|
@@ -1034,16 +1369,16 @@ const formatLargestRetainedSizeConstructors = (snapshot, options) => {
|
|
|
1034
1369
|
formatBytes(constructor.retainedSize),
|
|
1035
1370
|
formatCount(constructor.instances.length),
|
|
1036
1371
|
inlineCode(constructor.name),
|
|
1037
|
-
constructor.location
|
|
1372
|
+
formatProfileLocation(constructor.location, options)
|
|
1038
1373
|
])),
|
|
1039
1374
|
...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's retained size.`] : [],
|
|
1040
1375
|
...largestInstanceSections
|
|
1041
1376
|
].join(`\n\n`);
|
|
1042
1377
|
};
|
|
1043
1378
|
const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
|
|
1044
|
-
const
|
|
1045
|
-
if (
|
|
1046
|
-
return [`##### ${inlineCode(constructor.name)} (${constructor.location
|
|
1379
|
+
const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.retainedSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.retainedSize - group1.retainedSize);
|
|
1380
|
+
if (largestInstanceGroups.length === 0) return;
|
|
1381
|
+
return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
|
|
1047
1382
|
{
|
|
1048
1383
|
content: `%`,
|
|
1049
1384
|
align: `right`
|
|
@@ -1052,16 +1387,46 @@ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPa
|
|
|
1052
1387
|
content: `Size`,
|
|
1053
1388
|
align: `right`
|
|
1054
1389
|
},
|
|
1390
|
+
{
|
|
1391
|
+
content: `Instances`,
|
|
1392
|
+
align: `right`
|
|
1393
|
+
},
|
|
1055
1394
|
`Path`
|
|
1056
|
-
],
|
|
1057
|
-
formatPercent(
|
|
1058
|
-
formatBytes(
|
|
1059
|
-
|
|
1395
|
+
], largestInstanceGroups.map((group) => [
|
|
1396
|
+
formatPercent(group.retainedSize / constructor.retainedSize),
|
|
1397
|
+
formatBytes(group.retainedSize),
|
|
1398
|
+
formatCount(group.instanceCount),
|
|
1399
|
+
inlineCode(group.retainerPath)
|
|
1060
1400
|
]))].join(`\n\n`);
|
|
1061
1401
|
};
|
|
1402
|
+
const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
|
|
1403
|
+
const heap = new MaxHeap(instances, (instance1, instance2) => sizeOf(instance1) - sizeOf(instance2));
|
|
1404
|
+
const pathToGroup = /* @__PURE__ */ new Map();
|
|
1405
|
+
while (heap.length > 0 && pathToGroup.size < topN) {
|
|
1406
|
+
const instance = heap.pop();
|
|
1407
|
+
const retainerPath = retainerPathOf(instance.id);
|
|
1408
|
+
let group = pathToGroup.get(retainerPath);
|
|
1409
|
+
if (!group) {
|
|
1410
|
+
group = {
|
|
1411
|
+
retainerPath,
|
|
1412
|
+
instanceCount: 0,
|
|
1413
|
+
selfSize: 0,
|
|
1414
|
+
retainedSize: 0
|
|
1415
|
+
};
|
|
1416
|
+
pathToGroup.set(retainerPath, group);
|
|
1417
|
+
}
|
|
1418
|
+
group.instanceCount++;
|
|
1419
|
+
group.selfSize += instance.selfSize;
|
|
1420
|
+
group.retainedSize += instance.retainedSize;
|
|
1421
|
+
}
|
|
1422
|
+
return [...pathToGroup.values()];
|
|
1423
|
+
};
|
|
1062
1424
|
const formatLargestClosures = (snapshot, options) => {
|
|
1063
1425
|
const { totalSize, closures, retainerPathOf } = snapshot;
|
|
1064
|
-
const largestClosures = selectTopN(closures.filter(
|
|
1426
|
+
const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
|
|
1427
|
+
...closure,
|
|
1428
|
+
id: closure.largestInstanceId
|
|
1429
|
+
})), options.topN, (closure1, closure2) => closure1.retainedSize - closure2.retainedSize);
|
|
1065
1430
|
const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
|
|
1066
1431
|
return [
|
|
1067
1432
|
`## Largest closures`,
|
|
@@ -1075,30 +1440,48 @@ const formatLargestClosures = (snapshot, options) => {
|
|
|
1075
1440
|
content: `Retained`,
|
|
1076
1441
|
align: `right`
|
|
1077
1442
|
},
|
|
1443
|
+
{
|
|
1444
|
+
content: `Instances`,
|
|
1445
|
+
align: `right`
|
|
1446
|
+
},
|
|
1447
|
+
{
|
|
1448
|
+
content: `Paths`,
|
|
1449
|
+
align: `right`
|
|
1450
|
+
},
|
|
1078
1451
|
`Name`,
|
|
1079
1452
|
`Location`,
|
|
1080
|
-
`
|
|
1453
|
+
`Example path`
|
|
1081
1454
|
], largestClosures.map((closure) => [
|
|
1082
1455
|
formatPercent(closure.retainedSize / totalSize),
|
|
1083
1456
|
formatBytes(closure.retainedSize),
|
|
1457
|
+
formatCount(closure.instanceIds.length),
|
|
1458
|
+
formatCount(new Set(closure.instanceIds.map(retainerPathOf)).size),
|
|
1084
1459
|
inlineCode(closure.name),
|
|
1085
|
-
closure.location
|
|
1086
|
-
inlineCode(retainerPathOf(closure.
|
|
1460
|
+
formatProfileLocation(closure.location, options),
|
|
1461
|
+
inlineCode(retainerPathOf(closure.largestInstanceId))
|
|
1087
1462
|
])),
|
|
1088
1463
|
...retainedSections.length > 0 ? [`### Retained`, `Objects ranked by contribution to each closure's retained size.`] : [],
|
|
1089
1464
|
...retainedSections
|
|
1090
1465
|
].join(`\n\n`);
|
|
1091
1466
|
};
|
|
1092
1467
|
const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, options) => {
|
|
1093
|
-
const
|
|
1468
|
+
const instanceIdToSeen = new DynamicTypedArray(new Uint8Array(256));
|
|
1469
|
+
const allRetainedNodes = [];
|
|
1470
|
+
for (const instanceId of closure.instanceIds) for (const node of retainedNodesOf(instanceId)) {
|
|
1471
|
+
const seen = instanceIdToSeen.ensureCapacity(node.id + 1);
|
|
1472
|
+
if (seen[node.id]) continue;
|
|
1473
|
+
seen[node.id] = 1;
|
|
1474
|
+
if (options.includeEntry(node)) allRetainedNodes.push(node);
|
|
1475
|
+
}
|
|
1476
|
+
const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node1, node2) => node1.selfSize - node2.selfSize);
|
|
1094
1477
|
if (retainedNodes.length === 0) return;
|
|
1095
|
-
return [`#### ${inlineCode(closure.name)} (${closure.location
|
|
1478
|
+
return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
|
|
1096
1479
|
{
|
|
1097
1480
|
content: `%`,
|
|
1098
1481
|
align: `right`
|
|
1099
1482
|
},
|
|
1100
1483
|
{
|
|
1101
|
-
content: `
|
|
1484
|
+
content: `Self`,
|
|
1102
1485
|
align: `right`
|
|
1103
1486
|
},
|
|
1104
1487
|
`Name`,
|
|
@@ -1124,8 +1507,8 @@ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) =
|
|
|
1124
1507
|
align: `right`
|
|
1125
1508
|
},
|
|
1126
1509
|
`Value`,
|
|
1127
|
-
`
|
|
1128
|
-
], selectTopN(strings, options.topN, (string1, string2) =>
|
|
1510
|
+
`Path`
|
|
1511
|
+
], selectTopN(strings, options.topN, (string1, string2) => string1.selfSize - string2.selfSize).map((string) => [
|
|
1129
1512
|
formatPercent(string.selfSize / totalSize),
|
|
1130
1513
|
formatBytes(string.selfSize),
|
|
1131
1514
|
inlineCode(string.name),
|
|
@@ -1135,17 +1518,17 @@ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) =
|
|
|
1135
1518
|
};
|
|
1136
1519
|
|
|
1137
1520
|
//#endregion
|
|
1138
|
-
//#region src/v8/heap-snapshot/parse.ts
|
|
1139
|
-
const
|
|
1521
|
+
//#region src/formats/v8/heap-snapshot/parse.ts
|
|
1522
|
+
const parseV8HeapSnapshot = (data) => parseJson(data);
|
|
1140
1523
|
|
|
1141
1524
|
//#endregion
|
|
1142
|
-
//#region src/v8/heap-snapshot/summarize.ts
|
|
1143
|
-
const
|
|
1525
|
+
//#region src/formats/v8/heap-snapshot/summarize.ts
|
|
1526
|
+
const summarizeV8HeapSnapshot = (snapshot, options) => {
|
|
1144
1527
|
const { snapshot: { meta, node_count: nodeCount, edge_count: edgeCount }, nodes } = snapshot;
|
|
1145
1528
|
const [nodeTypes] = meta.node_types;
|
|
1146
1529
|
const fieldLayout = computeFieldLayout(meta);
|
|
1147
1530
|
const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
|
|
1148
|
-
const
|
|
1531
|
+
const nodeOrdinalToLocation = computeNodeOrdinalToLocation(snapshot, nodeAdjacencyGraph, fieldLayout);
|
|
1149
1532
|
const immediateDominatorGraph = computeImmediateDominatorGraph(snapshot, nodeAdjacencyGraph);
|
|
1150
1533
|
const nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(snapshot, immediateDominatorGraph, fieldLayout);
|
|
1151
1534
|
let totalSize = 0;
|
|
@@ -1154,6 +1537,8 @@ const summarizeSnapshot = (snapshot, options) => {
|
|
|
1154
1537
|
const nameToConstructorIndex = /* @__PURE__ */ new Map();
|
|
1155
1538
|
const nodeOrdinalToConstructorIndex = new Int32Array(nodeCount).fill(-1);
|
|
1156
1539
|
const closures = [];
|
|
1540
|
+
const keyToClosureIndex = /* @__PURE__ */ new Map();
|
|
1541
|
+
const nodeOrdinalToClosureIndex = new Int32Array(nodeCount).fill(-1);
|
|
1157
1542
|
const strings = [];
|
|
1158
1543
|
for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
1159
1544
|
const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
|
|
@@ -1191,7 +1576,7 @@ const summarizeSnapshot = (snapshot, options) => {
|
|
|
1191
1576
|
nameToConstructorIndex.set(name, constructorIndex);
|
|
1192
1577
|
} else constructor = constructors[constructorIndex];
|
|
1193
1578
|
constructor.selfSize += selfSize;
|
|
1194
|
-
constructor.location ??=
|
|
1579
|
+
constructor.location ??= nodeOrdinalToLocation[nodeOrdinal];
|
|
1195
1580
|
constructor.instances.push({
|
|
1196
1581
|
id: nodeOrdinal,
|
|
1197
1582
|
name: constructor.name,
|
|
@@ -1202,15 +1587,29 @@ const summarizeSnapshot = (snapshot, options) => {
|
|
|
1202
1587
|
nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
|
|
1203
1588
|
break;
|
|
1204
1589
|
}
|
|
1205
|
-
case fieldLayout.nodeTypeClosure:
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1590
|
+
case fieldLayout.nodeTypeClosure: {
|
|
1591
|
+
const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
|
|
1592
|
+
const location = nodeOrdinalToLocation[nodeOrdinal];
|
|
1593
|
+
const key = `${name}|${location ? formatProfileLocation(location, options) : ``}`;
|
|
1594
|
+
const retainedSize = nodeOrdinalToRetainedSize[nodeOrdinal];
|
|
1595
|
+
let closureIndex = keyToClosureIndex.get(key);
|
|
1596
|
+
if (closureIndex === void 0) {
|
|
1597
|
+
closureIndex = closures.length;
|
|
1598
|
+
closures.push({
|
|
1599
|
+
name,
|
|
1600
|
+
location,
|
|
1601
|
+
retainedSize: 0,
|
|
1602
|
+
largestInstanceId: nodeOrdinal,
|
|
1603
|
+
instanceIds: []
|
|
1604
|
+
});
|
|
1605
|
+
keyToClosureIndex.set(key, closureIndex);
|
|
1606
|
+
}
|
|
1607
|
+
const closure = closures[closureIndex];
|
|
1608
|
+
closure.instanceIds.push(nodeOrdinal);
|
|
1609
|
+
if (retainedSize > nodeOrdinalToRetainedSize[closure.largestInstanceId]) closure.largestInstanceId = nodeOrdinal;
|
|
1610
|
+
nodeOrdinalToClosureIndex[nodeOrdinal] = closureIndex;
|
|
1213
1611
|
break;
|
|
1612
|
+
}
|
|
1214
1613
|
case fieldLayout.nodeTypeString:
|
|
1215
1614
|
case fieldLayout.nodeTypeSlicedString:
|
|
1216
1615
|
case fieldLayout.nodeTypeConcatenatedString:
|
|
@@ -1224,6 +1623,7 @@ const summarizeSnapshot = (snapshot, options) => {
|
|
|
1224
1623
|
}
|
|
1225
1624
|
}
|
|
1226
1625
|
attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToConstructorIndex, constructors);
|
|
1626
|
+
attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToClosureIndex, closures);
|
|
1227
1627
|
return {
|
|
1228
1628
|
totalSize,
|
|
1229
1629
|
nodeCount,
|
|
@@ -1232,7 +1632,7 @@ const summarizeSnapshot = (snapshot, options) => {
|
|
|
1232
1632
|
constructors,
|
|
1233
1633
|
closures,
|
|
1234
1634
|
strings,
|
|
1235
|
-
retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph,
|
|
1635
|
+
retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeOrdinalToLocation, immediateDominatorGraph, fieldLayout, options),
|
|
1236
1636
|
retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, immediateDominatorGraph, fieldLayout, options)
|
|
1237
1637
|
};
|
|
1238
1638
|
};
|
|
@@ -1291,44 +1691,54 @@ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes,
|
|
|
1291
1691
|
offsetToPredecessorEdgeIndex
|
|
1292
1692
|
};
|
|
1293
1693
|
};
|
|
1294
|
-
const
|
|
1694
|
+
const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
|
|
1295
1695
|
const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
|
|
1296
|
-
const nodeOrdinal = nodeIndex /
|
|
1696
|
+
const nodeOrdinal = nodeIndex / nodeFieldCount;
|
|
1297
1697
|
const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
|
|
1298
1698
|
const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
|
|
1299
1699
|
for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
|
|
1300
1700
|
const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
|
|
1301
|
-
if (strings[edges[edgeIndex +
|
|
1701
|
+
if (strings[edges[edgeIndex + edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + edgeToNodeOffset];
|
|
1302
1702
|
}
|
|
1303
1703
|
};
|
|
1304
1704
|
const scriptIdToFileLocation = /* @__PURE__ */ new Map();
|
|
1305
|
-
for (let locationIndex = 0; locationIndex < locations.length; locationIndex +=
|
|
1306
|
-
const scriptId = locations[locationIndex +
|
|
1705
|
+
for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
|
|
1706
|
+
const scriptId = locations[locationIndex + locationScriptIdOffset];
|
|
1307
1707
|
if (scriptIdToFileLocation.has(scriptId)) continue;
|
|
1308
|
-
const nodeIndex = locations[locationIndex +
|
|
1309
|
-
if (nodes[nodeIndex +
|
|
1708
|
+
const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
|
|
1709
|
+
if (nodes[nodeIndex + nodeTypeOffset] !== nodeTypeClosure) continue;
|
|
1310
1710
|
const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
|
|
1311
1711
|
if (sharedNodeIndex === void 0) continue;
|
|
1312
1712
|
const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
|
|
1313
1713
|
if (scriptNodeIndex === void 0) continue;
|
|
1314
1714
|
const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
|
|
1315
1715
|
if (locationNodeIndex === void 0) continue;
|
|
1316
|
-
const location = strings[nodes[locationNodeIndex +
|
|
1716
|
+
const location = strings[nodes[locationNodeIndex + nodeNameOffset]];
|
|
1317
1717
|
if (!location) continue;
|
|
1318
|
-
|
|
1319
|
-
if (fileLocation) scriptIdToFileLocation.set(scriptId, fileLocation);
|
|
1718
|
+
scriptIdToFileLocation.set(scriptId, location);
|
|
1320
1719
|
}
|
|
1321
|
-
const
|
|
1322
|
-
|
|
1323
|
-
|
|
1720
|
+
const nodeOrdinalToLocation = [];
|
|
1721
|
+
const fileLocationToUrl = /* @__PURE__ */ new Map();
|
|
1722
|
+
for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
|
|
1723
|
+
const scriptId = locations[locationIndex + locationScriptIdOffset];
|
|
1324
1724
|
const fileLocation = scriptIdToFileLocation.get(scriptId);
|
|
1325
1725
|
if (!fileLocation) continue;
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1726
|
+
let url = fileLocationToUrl.get(fileLocation);
|
|
1727
|
+
if (url === void 0) {
|
|
1728
|
+
url = makeProfileLocation({ urlOrPath: fileLocation })?.url ?? null;
|
|
1729
|
+
fileLocationToUrl.set(fileLocation, url);
|
|
1730
|
+
}
|
|
1731
|
+
if (!url) continue;
|
|
1732
|
+
const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
|
|
1733
|
+
const line = locations[locationIndex + locationLineOffset];
|
|
1734
|
+
const column = locations[locationIndex + locationColumnOffset];
|
|
1735
|
+
nodeOrdinalToLocation[nodeIndex / nodeFieldCount] = {
|
|
1736
|
+
url,
|
|
1737
|
+
line: line + 1,
|
|
1738
|
+
column: column + 1
|
|
1739
|
+
};
|
|
1330
1740
|
}
|
|
1331
|
-
return
|
|
1741
|
+
return nodeOrdinalToLocation;
|
|
1332
1742
|
};
|
|
1333
1743
|
/**
|
|
1334
1744
|
* Computes the immediate dominators of every node.
|
|
@@ -1377,7 +1787,8 @@ const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessorStartOffse
|
|
|
1377
1787
|
const reachableCount = dfsIndex;
|
|
1378
1788
|
const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
|
|
1379
1789
|
const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
|
|
1380
|
-
const ordinalToMinSemiAncestorOrdinal = Int32Array
|
|
1790
|
+
const ordinalToMinSemiAncestorOrdinal = new Int32Array(nodeCount);
|
|
1791
|
+
for (let i = 0; i < nodeCount; i++) ordinalToMinSemiAncestorOrdinal[i] = i;
|
|
1381
1792
|
const compressAncestorPath = (startNodeOrdinal) => {
|
|
1382
1793
|
let pathLength = 0;
|
|
1383
1794
|
let nodeOrdinal = startNodeOrdinal;
|
|
@@ -1460,7 +1871,7 @@ const computeNodeOrdinalToRetainedSize = ({ nodes }, { dfsIndexToOrdinal, ordina
|
|
|
1460
1871
|
}
|
|
1461
1872
|
return nodeOrdinalToRetainedSize;
|
|
1462
1873
|
};
|
|
1463
|
-
const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex },
|
|
1874
|
+
const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, nodeOrdinalToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout, options) => {
|
|
1464
1875
|
const { nodes } = snapshot;
|
|
1465
1876
|
const hops = [];
|
|
1466
1877
|
while (true) {
|
|
@@ -1483,9 +1894,9 @@ const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartO
|
|
|
1483
1894
|
const retainerIndex = predecessorOrdinal * fieldLayout.nodeFieldCount;
|
|
1484
1895
|
const retainerType = nodes[retainerIndex + fieldLayout.nodeTypeOffset];
|
|
1485
1896
|
const retainerLabel = formatNodeLabel(retainerIndex, snapshot, fieldLayout, options);
|
|
1486
|
-
const retainerLocation =
|
|
1897
|
+
const retainerLocation = nodeOrdinalToLocation[predecessorOrdinal];
|
|
1487
1898
|
hops.push({
|
|
1488
|
-
label: `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${retainerLocation})` : ``}`,
|
|
1899
|
+
label: `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${formatProfileLocation(retainerLocation, options)})` : ``}`,
|
|
1489
1900
|
internal: isInternalNodeType(retainerType, fieldLayout)
|
|
1490
1901
|
});
|
|
1491
1902
|
nodeOrdinal = predecessorOrdinal;
|
|
@@ -1523,7 +1934,8 @@ const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) =>
|
|
|
1523
1934
|
const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
|
|
1524
1935
|
if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
|
|
1525
1936
|
const rawEdgeName = strings[edgeNameOrIndex];
|
|
1526
|
-
|
|
1937
|
+
const edgeLocation = makeProfileLocation({ urlOrPath: rawEdgeName });
|
|
1938
|
+
return `.${edgeLocation ? formatProfileLocation(edgeLocation, options) : rawEdgeName}`;
|
|
1527
1939
|
};
|
|
1528
1940
|
const formatNodeLabel = (nodeIndex, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, strings }, fieldLayout, options) => {
|
|
1529
1941
|
const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
|
|
@@ -1537,7 +1949,8 @@ const formatNodeLabel = (nodeIndex, { snapshot: { meta: { node_types: [nodeTypes
|
|
|
1537
1949
|
case fieldLayout.nodeTypeClosure: return strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || `(anonymous)`;
|
|
1538
1950
|
default: {
|
|
1539
1951
|
const rawNodeName = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || nodeTypes[nodeType];
|
|
1540
|
-
|
|
1952
|
+
const nodeLocation = makeProfileLocation({ urlOrPath: rawNodeName });
|
|
1953
|
+
return nodeLocation ? formatProfileLocation(nodeLocation, options) : rawNodeName;
|
|
1541
1954
|
}
|
|
1542
1955
|
}
|
|
1543
1956
|
};
|
|
@@ -1630,7 +2043,16 @@ const computeFieldLayout = (meta) => {
|
|
|
1630
2043
|
const valueToIndex = (values) => new Map(values.map((value, index) => [value, index]));
|
|
1631
2044
|
|
|
1632
2045
|
//#endregion
|
|
1633
|
-
//#region src/v8/heap-snapshot/index.ts
|
|
2046
|
+
//#region src/formats/v8/heap-snapshot/index.ts
|
|
2047
|
+
const detectV8HeapSnapshot = (json) => {
|
|
2048
|
+
if (typeof json !== `object` || json === null) return;
|
|
2049
|
+
const { snapshot, edges } = json;
|
|
2050
|
+
if (typeof snapshot !== `object` || snapshot === null) return;
|
|
2051
|
+
const { meta } = snapshot;
|
|
2052
|
+
if (typeof meta !== `object` || meta === null || !Array.isArray(meta.node_fields)) return;
|
|
2053
|
+
if (!Array.isArray(edges)) return;
|
|
2054
|
+
return json;
|
|
2055
|
+
};
|
|
1634
2056
|
/**
|
|
1635
2057
|
* Converts the given V8 heap snapshot to Markdown.
|
|
1636
2058
|
*
|
|
@@ -1639,43 +2061,67 @@ const valueToIndex = (values) => new Map(values.map((value, index) => [value, in
|
|
|
1639
2061
|
*
|
|
1640
2062
|
* You can generate a V8 heap snapshot in several ways:
|
|
1641
2063
|
* - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
|
|
2064
|
+
* - [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
|
|
1642
2065
|
* - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
|
|
2066
|
+
* - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
|
|
2067
|
+
* [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
|
|
2068
|
+
* or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
|
|
2069
|
+
* [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
|
|
2070
|
+
* - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
|
|
1643
2071
|
*/
|
|
1644
|
-
const v8HeapSnapshotToMd = (data, options) =>
|
|
1645
|
-
|
|
1646
|
-
|
|
2072
|
+
const v8HeapSnapshotToMd = (data, options) => v8HeapSnapshotToMdInternal(parseV8HeapSnapshot(data), options);
|
|
2073
|
+
const v8HeapSnapshotToMdInternal = (snapshot, options) => {
|
|
2074
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
2075
|
+
return formatV8HeapSnapshot(summarizeV8HeapSnapshot(snapshot, normalizedOptions), normalizedOptions);
|
|
1647
2076
|
};
|
|
1648
2077
|
|
|
1649
2078
|
//#endregion
|
|
1650
2079
|
//#region src/cli.ts
|
|
1651
|
-
const
|
|
1652
|
-
|
|
2080
|
+
const jsonProfileConverters = [
|
|
2081
|
+
{
|
|
2082
|
+
type: `speedscope`,
|
|
2083
|
+
detect: detectSpeedscopeProfile,
|
|
2084
|
+
toMdInternal: speedscopeProfileToMdInternal,
|
|
2085
|
+
toMd: speedscopeProfileToMd
|
|
2086
|
+
},
|
|
2087
|
+
{
|
|
1653
2088
|
type: `v8-cpu-profile`,
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
2089
|
+
detect: detectV8CpuProfile,
|
|
2090
|
+
toMdInternal: v8CpuProfileToMdInternal,
|
|
2091
|
+
toMd: v8CpuProfileToMd
|
|
2092
|
+
},
|
|
2093
|
+
{
|
|
1657
2094
|
type: `v8-heap-profile`,
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
2095
|
+
detect: detectV8HeapProfile,
|
|
2096
|
+
toMdInternal: v8HeapProfileToMdInternal,
|
|
2097
|
+
toMd: v8HeapProfileToMd
|
|
2098
|
+
},
|
|
2099
|
+
{
|
|
1661
2100
|
type: `v8-heap-snapshot`,
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
2101
|
+
detect: detectV8HeapSnapshot,
|
|
2102
|
+
toMdInternal: v8HeapSnapshotToMdInternal,
|
|
2103
|
+
toMd: v8HeapSnapshotToMd
|
|
2104
|
+
}
|
|
2105
|
+
];
|
|
2106
|
+
const binaryProfileConverters = [{
|
|
2107
|
+
type: `pprof`,
|
|
2108
|
+
detect: detectPprof,
|
|
2109
|
+
toMdInternal: pprofToMdInternal,
|
|
2110
|
+
toMd: pprofToMd
|
|
2111
|
+
}];
|
|
2112
|
+
const profileConverters = [...jsonProfileConverters, ...binaryProfileConverters];
|
|
1666
2113
|
const cli = meow(`
|
|
1667
2114
|
Usage: profiler-md [options] [file]
|
|
1668
2115
|
|
|
1669
2116
|
Options:
|
|
1670
|
-
-t, --type <type> Profile type
|
|
2117
|
+
-t, --type <type> Profile type, auto-detected from content if omitted
|
|
2118
|
+
[${profileConverters.map(({ type }) => type).join(`|`)}]
|
|
1671
2119
|
-o, --output <file> Output file (default: - for stdout)
|
|
1672
2120
|
--top-n <n> Number of top entries to show (default: 20)
|
|
1673
2121
|
--cwd <path> Working directory for relative file paths in output
|
|
1674
|
-
--third-party <glob> Mark URLs matching this glob as third-party
|
|
2122
|
+
--third-party <glob> Mark URLs matching this glob as third-party
|
|
2123
|
+
(repeatable; default: node_modules)
|
|
1675
2124
|
--help Show this help message
|
|
1676
|
-
|
|
1677
|
-
Supported profile types:
|
|
1678
|
-
${Array.from(extensionToProfileConverter, ([extension, { type }]) => ` *${extension} -> ${type}`).join(`\n`)}
|
|
1679
2125
|
`, {
|
|
1680
2126
|
importMeta: import.meta,
|
|
1681
2127
|
allowUnknownFlags: false,
|
|
@@ -1698,28 +2144,25 @@ ${Array.from(extensionToProfileConverter, ([extension, { type }]) => ` *${ext
|
|
|
1698
2144
|
}
|
|
1699
2145
|
}
|
|
1700
2146
|
});
|
|
2147
|
+
const gunzipAsync = promisify(gunzip);
|
|
2148
|
+
const brotliDecompressAsync = promisify(brotliDecompress);
|
|
2149
|
+
const decompressData = async (data, filePath) => {
|
|
2150
|
+
if (filePath?.endsWith(`.br`)) return brotliDecompressAsync(data);
|
|
2151
|
+
if (data[0] === 31 && data[1] === 139) return gunzipAsync(data);
|
|
2152
|
+
return data;
|
|
2153
|
+
};
|
|
1701
2154
|
try {
|
|
1702
2155
|
const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty } } = cli;
|
|
1703
|
-
let
|
|
2156
|
+
let forcedProfileConverter;
|
|
1704
2157
|
if (profileType !== void 0) {
|
|
1705
|
-
|
|
1706
|
-
if (!
|
|
2158
|
+
forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
|
|
2159
|
+
if (!forcedProfileConverter) {
|
|
1707
2160
|
process.stderr.write(`error: unknown profile type "${profileType}"\nRun with --help to see supported types.\n`);
|
|
1708
2161
|
process.exit(2);
|
|
1709
2162
|
}
|
|
1710
|
-
} else if (filePath) {
|
|
1711
|
-
const extension = extname(filePath);
|
|
1712
|
-
profileConverter = extensionToProfileConverter.get(extension);
|
|
1713
|
-
if (!profileConverter) {
|
|
1714
|
-
process.stderr.write(`error: unrecognized file extension "${extension}"\nUse --type to specify the profile type, or run with --help to see supported types.\n`);
|
|
1715
|
-
process.exit(2);
|
|
1716
|
-
}
|
|
1717
|
-
} else if (process.stdin.isTTY) {
|
|
2163
|
+
} else if (!filePath && process.stdin.isTTY) {
|
|
1718
2164
|
cli.showHelp(0);
|
|
1719
2165
|
process.exit(0);
|
|
1720
|
-
} else {
|
|
1721
|
-
process.stderr.write(`error: --type is required when reading from stdin\nRun with --help to see supported types.\n`);
|
|
1722
|
-
process.exit(2);
|
|
1723
2166
|
}
|
|
1724
2167
|
let data;
|
|
1725
2168
|
if (filePath) try {
|
|
@@ -1730,12 +2173,45 @@ try {
|
|
|
1730
2173
|
process.exit(1);
|
|
1731
2174
|
}
|
|
1732
2175
|
else data = Buffer.concat(await Array.fromAsync(process.stdin));
|
|
2176
|
+
try {
|
|
2177
|
+
data = await decompressData(data, filePath);
|
|
2178
|
+
} catch (error) {
|
|
2179
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2180
|
+
process.stderr.write(`error: failed to decompress input: ${message}\n`);
|
|
2181
|
+
process.exit(1);
|
|
2182
|
+
}
|
|
1733
2183
|
const thirdPartyMatchers = thirdParty.map((glob) => picomatch(glob, { dot: true }));
|
|
1734
|
-
const
|
|
2184
|
+
const options = {
|
|
1735
2185
|
topN,
|
|
1736
2186
|
cwd,
|
|
1737
|
-
|
|
1738
|
-
}
|
|
2187
|
+
isThirdPartyEntry: thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0
|
|
2188
|
+
};
|
|
2189
|
+
let markdown;
|
|
2190
|
+
if (forcedProfileConverter) markdown = forcedProfileConverter.toMd(data, options);
|
|
2191
|
+
else {
|
|
2192
|
+
let json;
|
|
2193
|
+
try {
|
|
2194
|
+
json = parseJson(data);
|
|
2195
|
+
} catch {}
|
|
2196
|
+
if (json === void 0) for (const converter of binaryProfileConverters) {
|
|
2197
|
+
const parsed = converter.detect(data);
|
|
2198
|
+
if (parsed !== void 0) {
|
|
2199
|
+
markdown = converter.toMdInternal(parsed, options);
|
|
2200
|
+
break;
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
else for (const converter of jsonProfileConverters) {
|
|
2204
|
+
const parsed = converter.detect(json);
|
|
2205
|
+
if (parsed !== void 0) {
|
|
2206
|
+
markdown = converter.toMdInternal(parsed, options);
|
|
2207
|
+
break;
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
if (markdown === void 0) {
|
|
2211
|
+
process.stderr.write(`error: could not detect profile format from content\nUse --type to specify the format, or run with --help to see supported types.\n`);
|
|
2212
|
+
process.exit(2);
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
1739
2215
|
let output;
|
|
1740
2216
|
if (outputPath === `-`) output = process.stdout;
|
|
1741
2217
|
else {
|