profiler-md 0.0.2 → 0.1.1

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 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 { extname } from "node:path";
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/internal/markdown.ts
11
- const inlineCode = (text) => {
12
- const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
13
- const fence = `\``.repeat(longestBacktickRun + 1);
14
- return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
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/v8/common.ts
163
+ //#region src/location.ts
33
164
  /**
34
- * Returns whether to include the given row in the Markdown output.
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 defaultIncludeRow = ({ name, location }) => {
42
- if (name === `(root)`) return false;
43
- if (!location && (name === `ModuleWrap` || name.startsWith(`system /`) || name.startsWith(`Node /`)) || location?.startsWith(`node:internal/`)) return false;
44
- return true;
45
- };
46
- /**
47
- * Returns whether the given URL points to third-party code.
48
- *
49
- * This is the default value for {@link V8ProfileToMdOptions.isThirdPartyURL}.
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
- let urlObject;
179
+ if (!urlOrPath.includes(`:`)) return;
100
180
  try {
101
- urlObject = new URL(callFrame.url);
181
+ return {
182
+ url: new URL(urlOrPath),
183
+ line,
184
+ column
185
+ };
102
186
  } catch {
103
- return `native`;
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((callStack) => callStack.nodes.length));
111
- const firstNodes = callStacks[0].nodes;
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 = firstNodes.slice(-i).map((node) => callFrameKey(node.callFrame));
115
- if (callStacks.every((callStack) => callStack.nodes.slice(-i).every((node, j) => callFrameKey(node.callFrame) === suffix[j]))) suffixLength = i;
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 ? firstNodes.slice(-suffixLength) : [];
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/internal/format.ts
141
- const formatCount = (count, unit) => count.toLocaleString(`en-US`) + (unit ? ` ${unit}${count === 1 ? `` : `s`}` : ``);
142
- const formatMicroseconds = (microseconds) => prettyMilliseconds(microseconds / 1e3, {
143
- secondsDecimalDigits: 2,
144
- millisecondsDecimalDigits: 1,
145
- unitCount: 2
146
- });
147
- const formatMicrosecondsExact = (microseconds) => `${microseconds.toFixed(1)}µs`;
148
- const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
149
- const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
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 siftDown = (heap, i, size, compare) => {
172
- while (true) {
173
- let minChild = 2 * i + 1;
174
- if (minChild >= size) break;
175
- const right = minChild + 1;
176
- if (right < size && compare(heap[minChild], heap[right]) < 0) minChild = right;
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
- //#endregion
184
- //#region src/v8/cpu-profile/format.ts
185
- const formatSummarizedProfile$1 = (profile, options) => `${[
186
- `# CPU profile`,
187
- formatOverallProfileSummary$1(profile),
188
- formatHottestFunctions$1(profile, options),
189
- formatHottestCallStacks$1(profile, options)
190
- ].filter(Boolean).join(`\n\n`)}\n`;
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
- `Time`,
197
- `Samples`
198
- ], hottestCallFrameCategories.map(([category, { time, sampleCount }]) => [
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(time / totalTime),
201
- formatMicroseconds(time),
466
+ formatPercent(values[0] / totalValues[0]),
467
+ ...metrics.map((metric, index) => formatValue(values[index], metric)),
202
468
  formatCount(sampleCount)
203
- ]))].join(`\n\n`);
469
+ ]));
204
470
  };
205
- const formatHottestFunctions$1 = (profile, options) => [
206
- `## Hottest functions`,
207
- formatHottestSelfTimeFunctions(profile, options),
208
- formatHottestTotalTimeFunctions(profile, options)
209
- ].join(`\n\n`);
210
- const formatHottestSelfTimeFunctions = ({ totalTime, nodes }, options) => {
211
- const hottestSelfTimeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.selfTime - node1.selfTime);
212
- const hottestLinesSections = hottestSelfTimeNodes.filter((node) => node.lineToStats.size > 0).map((node) => formatHottestLines(node, options));
213
- const hottestCallerSections = hottestSelfTimeNodes.map((node) => formatHottestCallers$1(node, options)).filter((section) => section !== void 0);
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
- `### Self time`,
216
- `Functions ranked by time in the function body, excluding callees.`,
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: `Time`,
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
- ], hottestSelfTimeNodes.map(({ name, location, selfTime, selfSampleCount }) => [
233
- formatPercent(selfTime / totalTime),
234
- formatMicroseconds(selfTime),
235
- formatCount(selfSampleCount),
236
- inlineCode(name),
237
- location ?? inlineCode(`<native>`)
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 ? [`#### Lines`, `Lines ranked by contribution to each function's self time.`] : [],
548
+ ...hottestLinesSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Lines`), `Lines ranked by contribution to each function's self ${metricName}.`] : [],
240
549
  ...hottestLinesSections,
241
- ...hottestCallerSections.length > 0 ? [`#### Callers`, `Callers ranked by contribution to each function's self time. Caller attribution may be imprecise due to V8 JIT inlining.`] : [],
242
- ...hottestCallerSections
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 = (node, { topN }) => {
246
- const hottestLines = [...node.lineToStats].sort(([, stats1], [, stats2]) => stats2.time - stats1.time).slice(0, Math.ceil(topN / 4));
247
- return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
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: `Time`,
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, { time, sampleCount }]) => [
262
- formatPercent(time / node.selfTime),
263
- formatMicroseconds(time),
264
- formatCount(sampleCount),
265
- `${node.fileLocation}:${line + 1}`
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$1 = (node, options) => {
269
- const hottestCallerSelfTimes = [...node.callerIdToStats.values()].filter(({ caller }) => options.includeRow(caller)).sort((caller1, caller2) => caller2.selfTime - caller1.selfTime).slice(0, Math.ceil(options.topN / 4));
270
- if (hottestCallerSelfTimes.length === 0) return;
271
- return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
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: `Time`,
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
- ], hottestCallerSelfTimes.map(({ caller, selfTime, selfSampleCount }) => [
287
- formatPercent(selfTime / node.selfTime),
288
- formatMicroseconds(selfTime),
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 ?? inlineCode(`<native>`)
608
+ formatProfileLocation(caller.location, options)
292
609
  ]))].join(`\n\n`);
293
610
  };
294
- const formatHottestTotalTimeFunctions = ({ totalTime, nodes }, options) => {
295
- const hottestTotalTimeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.totalTime - node1.totalTime);
296
- const hottestCalleeSections = hottestTotalTimeNodes.map((node) => formatHottestCallees$1(node, options)).filter((section) => section !== void 0);
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
- `### Total time`,
299
- `Functions ranked by total time in the function and all its callees.`,
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: `Time`,
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
- ], hottestTotalTimeNodes.map((node) => [
316
- formatPercent(node.totalTime / totalTime),
317
- formatMicroseconds(node.totalTime),
318
- formatCount(node.totalSampleCount),
319
- inlineCode(node.name),
320
- node.location ?? inlineCode(`<native>`)
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
- ...hottestCalleeSections.length > 0 ? [`#### Callees`, `Callees ranked by contribution to each function's total time. Callee attribution may be imprecise due to V8 JIT inlining.`] : [],
323
- ...hottestCalleeSections
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$1 = (node, options) => {
327
- const hottestCalleeTotalTimes = [...node.calleeIdToStats.values()].filter(({ callee }) => options.includeRow(callee)).sort((callee1, callee2) => callee2.totalTime - callee1.totalTime).slice(0, Math.ceil(options.topN / 4));
328
- if (hottestCalleeTotalTimes.length === 0) return;
329
- return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
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: `Time`,
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
- ], hottestCalleeTotalTimes.map(({ callee, totalTime, totalSampleCount }) => [
345
- formatPercent(totalTime / node.totalTime),
346
- formatMicroseconds(totalTime),
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 ?? inlineCode(`<native>`)
676
+ formatProfileLocation(callee.location, options)
350
677
  ]))].join(`\n\n`);
351
678
  };
352
- const formatHottestCallStacks$1 = ({ totalTime, callStacks }, options) => {
353
- const hottestCallStacks = selectTopN(callStacks.map((callStack) => ({
679
+ const formatHottestCallStacks = (metricIndex, profile, options) => {
680
+ const totalValue = profile.totalValues[metricIndex];
681
+ const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
354
682
  ...callStack,
355
- nodes: callStack.nodes.filter(options.includeRow)
356
- })).filter((callStack) => callStack.nodes.length > 1), options.topN, (callStack1, callStack2) => callStack2.selfTime - callStack1.selfTime);
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
- `## Hottest call stacks`,
361
- `Call stacks ranked by time spent in their top frame.`,
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: `Time`,
699
+ content: capitalizeFirst(metricName),
370
700
  align: `right`
371
701
  },
372
702
  {
@@ -374,194 +704,443 @@ const formatHottestCallStacks$1 = ({ totalTime, callStacks }, options) => {
374
704
  align: `right`
375
705
  },
376
706
  `Call stack`
377
- ], hottestCallStacks.map(({ nodes, selfTime, selfSampleCount }) => [
378
- formatPercent(selfTime / totalTime),
379
- formatMicroseconds(selfTime),
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 ? nodes.slice(0, -commonCallStack.length) : nodes)
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/v8/cpu-profile/parse.ts
388
- const parseProfile$1 = (data) => JSON.parse(data);
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/v8/cpu-profile/summarize.ts
392
- const summarizeProfile$1 = (profile, options) => {
393
- const graph = computeProfileGraph$1(profile, options);
394
- const totalTime = profile.endTime - profile.startTime;
395
- const totalSampleCount = profile.samples.length;
396
- const samplingInterval = totalTime / totalSampleCount;
397
- const nodes = [...graph.keyToSummarizedNode.values()];
398
- const rawNodeIdToSummarizedCallStack = /* @__PURE__ */ new Map();
399
- const keyToSummarizedCallStack = /* @__PURE__ */ new Map();
400
- const callFrameCategoryToStats = /* @__PURE__ */ new Map();
401
- const summarizedNodeCount = graph.keyToSummarizedNode.size;
402
- const ordinalToIterationLastVisited = new Int32Array(summarizedNodeCount).fill(-1);
403
- const pairOrdinalToIterationLastVisited = new Int32Array(summarizedNodeCount * summarizedNodeCount).fill(-1);
404
- for (let index = 0; index < profile.samples.length; index++) {
405
- const rawNodeId = profile.samples[index];
406
- const timeDelta = profile.timeDeltas[index];
407
- const node = graph.rawIdToSummarizedNode.get(rawNodeId);
408
- if (!node) continue;
409
- node.selfTime += timeDelta;
410
- const tickInfo = graph.rawIdToTickInfo.get(rawNodeId);
411
- if (tickInfo) {
412
- const { stats: tickStats, fractions: tickFractions } = tickInfo;
413
- for (let i = 0; i < tickStats.length; i++) {
414
- const tickStat = tickStats[i];
415
- tickStat.time += timeDelta * tickFractions[i];
416
- }
417
- }
418
- let summarizedCallStack = rawNodeIdToSummarizedCallStack.get(rawNodeId);
419
- if (!summarizedCallStack) {
420
- const callStack = summarizeCallStack(graph, rawNodeId);
421
- const key = callStack.map((node) => node.ordinal).join(`,`);
422
- summarizedCallStack = keyToSummarizedCallStack.get(key);
423
- if (!summarizedCallStack) {
424
- summarizedCallStack = {
425
- nodes: callStack,
426
- selfTime: 0,
427
- selfSampleCount: 0
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
- totalTime,
487
- totalSampleCount,
488
- samplingInterval,
489
- callFrameCategoryToStats,
490
- nodes,
491
- callStacks: [...keyToSummarizedCallStack.values()]
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
- const computeProfileGraph$1 = (profile, options) => {
495
- const rawIdToSummarizedNode = /* @__PURE__ */ new Map();
496
- const keyToSummarizedNode = /* @__PURE__ */ new Map();
497
- const rawIdToParentRawId = /* @__PURE__ */ new Map();
498
- const rawIdToTickInfo = /* @__PURE__ */ new Map();
499
- let nextOrdinal = 0;
500
- for (const node of profile.nodes) {
501
- const key = callFrameKey(node.callFrame);
502
- let summarizedNode = keyToSummarizedNode.get(key);
503
- if (!summarizedNode) {
504
- const { functionName, url, lineNumber, columnNumber } = node.callFrame;
505
- const fileLocation = formatLocation(url, options);
506
- summarizedNode = {
507
- id: node.id,
508
- ordinal: nextOrdinal++,
509
- callFrame: node.callFrame,
510
- name: functionName || `(anonymous)`,
511
- fileLocation,
512
- location: fileLocation ? `${fileLocation}:${lineNumber + 1}:${columnNumber + 1}` : void 0,
513
- category: categorizeCallFrame(node.callFrame, options),
514
- selfSampleCount: 0,
515
- totalSampleCount: 0,
516
- lineToStats: /* @__PURE__ */ new Map(),
517
- selfTime: 0,
518
- totalTime: 0,
519
- callerIdToStats: /* @__PURE__ */ new Map(),
520
- calleeIdToStats: /* @__PURE__ */ new Map()
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
+ * - Java/Kotlin's [`async-profiler`](https://github.com/async-profiler/async-profiler)
944
+ * - C/C++'s [`gperftools`](https://github.com/gperftools/gperftools) (via `pprof --proto`)
945
+ */
946
+ const pprofToMd = (data, options) => pprofToMdInternal(parsePprof(data), options);
947
+ const pprofToMdInternal = (pprof, options) => {
948
+ const normalizedOptions = normalizeProfileToMdOptions(options);
949
+ return formatPprof(summarizePprof(pprof, normalizedOptions), normalizedOptions);
950
+ };
951
+
952
+ //#endregion
953
+ //#region src/formats/speedscope/format.ts
954
+ const formatSpeedscope = (profile, options) => formatProfile(profile, options);
955
+
956
+ //#endregion
957
+ //#region src/helpers/json.ts
958
+ const parseJson = (data) => JSON.parse(data);
959
+
960
+ //#endregion
961
+ //#region src/formats/speedscope/parse.ts
962
+ const parseSpeedscopeProfile = (data) => parseJson(data);
963
+
964
+ //#endregion
965
+ //#region src/formats/speedscope/summarize.ts
966
+ const summarizeSpeedscopeProfile = (profile, options) => {
967
+ const nodes = profile.shared.frames.map((frame, id) => ({
968
+ ...frame,
969
+ id
970
+ }));
971
+ return profile.profiles.map((profile) => profile.type === `sampled` ? summarizeSampled(profile, nodes, options) : summarizeEvented(profile, nodes, options));
972
+ };
973
+ const summarizeSampled = (profile, nodes, options) => {
974
+ const profileBuilder = makeProfileBuilder(profile.unit, options);
975
+ for (let index = 0; index < profile.samples.length; index++) {
976
+ const weight = profile.weights[index];
977
+ if (weight <= 0) continue;
978
+ const sampleNodes = profile.samples[index].map((frameIndex) => nodes[frameIndex]).reverse();
979
+ if (sampleNodes.length === 0) continue;
980
+ profileBuilder.addSample({
981
+ values: [weight],
982
+ nodes: sampleNodes
983
+ });
984
+ }
985
+ return profileBuilder.build();
986
+ };
987
+ const summarizeEvented = (profile, nodes, options) => {
988
+ const builder = makeProfileBuilder(profile.unit, options);
989
+ const stack = [];
990
+ const emitTopSelfTime = (at) => {
991
+ if (stack.length === 0) return;
992
+ const top = stack.at(-1);
993
+ const selfTime = at - top.lastChildClosed;
994
+ if (selfTime <= 0) return;
995
+ builder.addSample({
996
+ values: [selfTime],
997
+ nodes: stack.map((entry) => entry.node).reverse()
998
+ });
999
+ top.lastChildClosed = at;
1000
+ };
1001
+ for (const event of profile.events) if (event.type === `O`) {
1002
+ emitTopSelfTime(event.at);
1003
+ stack.push({
1004
+ node: nodes[event.frame],
1005
+ lastChildClosed: event.at
1006
+ });
1007
+ } else {
1008
+ emitTopSelfTime(event.at);
1009
+ stack.pop();
1010
+ if (stack.length > 0) stack.at(-1).lastChildClosed = event.at;
554
1011
  }
1012
+ return builder.build();
1013
+ };
1014
+ const makeProfileBuilder = (unit, options) => new ProfileBuilder({
1015
+ metrics: [determineMetric({
1016
+ name: unit,
1017
+ unit
1018
+ })],
1019
+ functionKey: (node) => node.id,
1020
+ functionInput: (node) => ({
1021
+ name: node.name,
1022
+ location: node.file ? {
1023
+ urlOrPath: node.file,
1024
+ line: node.line,
1025
+ column: node.col
1026
+ } : void 0
1027
+ })
1028
+ }, options);
1029
+
1030
+ //#endregion
1031
+ //#region src/formats/speedscope/index.ts
1032
+ const detectSpeedscopeProfile = (json) => {
1033
+ if (typeof json !== `object` || json === null) return;
1034
+ const object = json;
1035
+ if (object.$schema !== `https://www.speedscope.app/file-format-schema.json` || !Array.isArray(object.profiles) || typeof object.shared !== `object` || object.shared === null) return;
1036
+ return json;
1037
+ };
1038
+ /**
1039
+ * Converts the given speedscope profile to Markdown.
1040
+ *
1041
+ * It is assumed that {@link data} is a valid speedscope JSON file. The behavior
1042
+ * of this function is undefined for invalid profiles.
1043
+ *
1044
+ * Speedscope profiles can be generated by many tools, including:
1045
+ * - [speedscope](https://www.speedscope.app) (drag and drop any supported profile)
1046
+ * - [rbspy](https://rbspy.github.io) for Ruby
1047
+ * - [py-spy](https://github.com/benfred/py-spy) for Python (`--format speedscope`)
1048
+ * - [pprof-rs](https://github.com/tikv/pprof-rs) for Rust
1049
+ * - [async-profiler](https://github.com/async-profiler/async-profiler) for Java/Kotlin (`-o speedscope`)
1050
+ * - [phpspy](https://github.com/adsr/phpspy) for PHP (`--output-format=speedscope`)
1051
+ */
1052
+ const speedscopeProfileToMd = (data, options) => speedscopeProfileToMdInternal(parseSpeedscopeProfile(data), options);
1053
+ const speedscopeProfileToMdInternal = (profile, options) => {
1054
+ const normalizedOptions = normalizeProfileToMdOptions(options);
1055
+ return summarizeSpeedscopeProfile(profile, normalizedOptions).map((profile) => formatSpeedscope(profile, normalizedOptions)).join(`\n\n`);
1056
+ };
1057
+
1058
+ //#endregion
1059
+ //#region src/formats/v8/cpu-profile/format.ts
1060
+ const formatV8CpuProfile = (profile, options) => formatProfile(profile, options);
1061
+
1062
+ //#endregion
1063
+ //#region src/formats/v8/cpu-profile/parse.ts
1064
+ const parseV8CpuProfile = (data) => parseJson(data);
1065
+
1066
+ //#endregion
1067
+ //#region src/formats/v8/common.ts
1068
+ const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
1069
+ const callFrameFunctionInput = (callFrame) => {
1070
+ const { functionName, url, lineNumber, columnNumber } = callFrame;
555
1071
  return {
556
- rawIdToSummarizedNode,
557
- keyToSummarizedNode,
558
- rawIdToParentRawId,
559
- rawIdToTickInfo
1072
+ name: functionName,
1073
+ location: url ? {
1074
+ urlOrPath: url,
1075
+ line: lineNumber + 1,
1076
+ column: columnNumber + 1
1077
+ } : void 0
560
1078
  };
561
1079
  };
562
1080
 
563
1081
  //#endregion
564
- //#region src/v8/cpu-profile/index.ts
1082
+ //#region src/formats/v8/cpu-profile/summarize.ts
1083
+ const summarizeV8CpuProfile = (profile, options) => {
1084
+ const profileBuilder = new ProfileBuilder({
1085
+ metrics: [MICROSECONDS],
1086
+ functionKey: (node) => callFrameKey(node.callFrame),
1087
+ functionInput: (node) => callFrameFunctionInput(node.callFrame)
1088
+ }, options);
1089
+ const idToIndex = [];
1090
+ for (let index = 0; index < profile.nodes.length; index++) {
1091
+ const node = profile.nodes[index];
1092
+ idToIndex[node.id] = index;
1093
+ node.id = index;
1094
+ }
1095
+ const indexToParentIndex = new Int32Array(profile.nodes.length).fill(-1);
1096
+ for (const node of profile.nodes) if (node.children) for (const childId of node.children) {
1097
+ const childIndex = idToIndex[childId];
1098
+ if (childIndex === void 0) continue;
1099
+ indexToParentIndex[childIndex] = node.id;
1100
+ }
1101
+ const indexToSelfTime = new Float64Array(profile.nodes.length);
1102
+ for (let index = 0; index < profile.samples.length; index++) {
1103
+ const nodeIndex = idToIndex[profile.samples[index]];
1104
+ if (nodeIndex === void 0) continue;
1105
+ const node = profile.nodes[nodeIndex];
1106
+ const timeDelta = profile.timeDeltas[index];
1107
+ indexToSelfTime[nodeIndex] += timeDelta;
1108
+ const nodes = [];
1109
+ let currentNode = node;
1110
+ while (true) {
1111
+ nodes.push(currentNode);
1112
+ const parentIndex = indexToParentIndex[currentNode.id];
1113
+ if (parentIndex === -1) break;
1114
+ currentNode = profile.nodes[parentIndex];
1115
+ }
1116
+ profileBuilder.addSample({
1117
+ values: [timeDelta],
1118
+ nodes
1119
+ });
1120
+ }
1121
+ for (const node of profile.nodes) {
1122
+ if (!node.positionTicks) continue;
1123
+ const selfTime = indexToSelfTime[node.id];
1124
+ profileBuilder.addLineMetrics({
1125
+ node,
1126
+ lines: node.positionTicks.map(({ line, ticks }) => ({
1127
+ line,
1128
+ sampleCount: ticks,
1129
+ values: [Math.round(selfTime * ticks / node.hitCount)]
1130
+ }))
1131
+ });
1132
+ }
1133
+ return profileBuilder.build();
1134
+ };
1135
+
1136
+ //#endregion
1137
+ //#region src/formats/v8/cpu-profile/index.ts
1138
+ const detectV8CpuProfile = (json) => {
1139
+ if (typeof json !== `object` || json === null) return;
1140
+ const object = json;
1141
+ if (!Array.isArray(object.nodes) || !Array.isArray(object.timeDeltas)) return;
1142
+ return json;
1143
+ };
565
1144
  /**
566
1145
  * Converts the given V8 CPU profile to Markdown.
567
1146
  *
@@ -570,336 +1149,86 @@ const computeProfileGraph$1 = (profile, options) => {
570
1149
  *
571
1150
  * You can generate a V8 CPU profile in several ways:
572
1151
  * - [`node --cpu-prof`](https://nodejs.org/api/cli.html#cpu-prof)
573
- * - [`deno --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
1152
+ * - [`deno run --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
574
1153
  * - [`bun --cpu-prof`](https://bun.com/docs/project/benchmarking#cpu-profiling)
1154
+ * (NOTE: output was incorrect until
1155
+ * [v1.3.13](https://bun.com/blog/bun-v1.3.13#node-js-compatibility-improvements))
1156
+ * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1157
+ * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1158
+ * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1159
+ * [Chrome DevTools](https://developer.chrome.com/docs/devtools/performance/nodejs)
1160
+ * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/performance#record)
575
1161
  *
576
1162
  * Lower the sampling interval to capture more granular data.
577
1163
  */
578
- const v8CpuProfileToMd = (data, options) => {
579
- const normalizedOptions = normalizeV8ProfileToMdOptions(options);
580
- return formatSummarizedProfile$1(summarizeProfile$1(parseProfile$1(data), normalizedOptions), normalizedOptions);
1164
+ const v8CpuProfileToMd = (data, options) => v8CpuProfileToMdInternal(parseV8CpuProfile(data), options);
1165
+ const v8CpuProfileToMdInternal = (profile, options) => {
1166
+ const normalizedOptions = normalizeProfileToMdOptions(options);
1167
+ return formatV8CpuProfile(summarizeV8CpuProfile(profile, normalizedOptions), normalizedOptions);
581
1168
  };
582
1169
 
583
1170
  //#endregion
584
- //#region src/v8/heap-profile/format.ts
585
- const formatSummarizedProfile = (profile, options) => `${[
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
- };
1171
+ //#region src/formats/v8/heap-profile/format.ts
1172
+ const formatV8HeapProfile = (profile, options) => formatProfile(profile, options);
759
1173
 
760
1174
  //#endregion
761
- //#region src/v8/heap-profile/parse.ts
762
- const parseProfile = (data) => JSON.parse(data);
1175
+ //#region src/formats/v8/heap-profile/parse.ts
1176
+ const parseV8HeapProfile = (data) => parseJson(data);
763
1177
 
764
1178
  //#endregion
765
- //#region src/v8/heap-profile/summarize.ts
766
- const summarizeProfile = (profile, options) => {
767
- const graph = computeProfileGraph(profile, options);
768
- const totalSize = profile.samples.reduce((sum, sample) => sum + sample.size, 0);
769
- const sampleCount = profile.samples.length;
770
- const samplingInterval = totalSize / sampleCount;
771
- const rawNodeIdToSummarizedCallStack = /* @__PURE__ */ new Map();
772
- const keyToSummarizedCallStack = /* @__PURE__ */ new Map();
773
- const callFrameCategoryToStats = /* @__PURE__ */ new Map();
774
- const summarizedNodeCount = graph.keyToSummarizedNode.size;
775
- const ordinalToIterationLastVisited = new Int32Array(summarizedNodeCount).fill(-1);
776
- const pairOrdinalToIterationLastVisited = new Int32Array(summarizedNodeCount * summarizedNodeCount).fill(-1);
777
- for (const [index, { size, nodeId }] of profile.samples.entries()) {
778
- const node = graph.rawIdToSummarizedNode.get(nodeId);
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 }];
1179
+ //#region src/formats/v8/heap-profile/summarize.ts
1180
+ const summarizeV8HeapProfile = (profile, options) => {
1181
+ const profileBuilder = new ProfileBuilder({
1182
+ metrics: [BYTES],
1183
+ functionKey: (node) => callFrameKey(node.callFrame),
1184
+ functionInput: (node) => callFrameFunctionInput(node.callFrame)
1185
+ }, options);
1186
+ const flatNodes = [];
1187
+ const idToIndex = [];
1188
+ const indexToParentIndex = [];
1189
+ const stack = [{
1190
+ node: profile.head,
1191
+ parentIndex: -1
1192
+ }];
864
1193
  do {
865
- const { node, parentId } = stack.pop();
866
- const key = callFrameKey(node.callFrame);
867
- let summarizedNode = keyToSummarizedNode.get(key);
868
- if (!summarizedNode) {
869
- const { functionName, url, lineNumber, columnNumber } = node.callFrame;
870
- const fileLocation = formatLocation(url, options);
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);
1194
+ const { node, parentIndex } = stack.pop();
1195
+ const index = flatNodes.length;
1196
+ idToIndex[node.id] = index;
1197
+ node.id = index;
1198
+ flatNodes.push(node);
1199
+ indexToParentIndex.push(parentIndex);
889
1200
  for (const child of node.children) stack.push({
890
1201
  node: child,
891
- parentId: node.id
1202
+ parentIndex: index
892
1203
  });
893
1204
  } while (stack.length > 0);
894
- return {
895
- rawIdToSummarizedNode,
896
- keyToSummarizedNode,
897
- rawIdToParentRawId
898
- };
1205
+ for (const { size, nodeId } of profile.samples) {
1206
+ const nodeIndex = idToIndex[nodeId];
1207
+ if (nodeIndex === void 0) continue;
1208
+ const nodes = [];
1209
+ let currentIndex = nodeIndex;
1210
+ while (true) {
1211
+ nodes.push(flatNodes[currentIndex]);
1212
+ const parentIndex = indexToParentIndex[currentIndex];
1213
+ if (parentIndex === -1) break;
1214
+ currentIndex = parentIndex;
1215
+ }
1216
+ profileBuilder.addSample({
1217
+ values: [size],
1218
+ nodes
1219
+ });
1220
+ }
1221
+ return profileBuilder.build();
899
1222
  };
900
1223
 
901
1224
  //#endregion
902
- //#region src/v8/heap-profile/index.ts
1225
+ //#region src/formats/v8/heap-profile/index.ts
1226
+ const detectV8HeapProfile = (json) => {
1227
+ if (typeof json !== `object` || json === null) return;
1228
+ const object = json;
1229
+ if (typeof object.head !== `object` || object.head === null || !Array.isArray(object.samples)) return;
1230
+ return json;
1231
+ };
903
1232
  /**
904
1233
  * Converts the given V8 sampling heap profile to Markdown.
905
1234
  *
@@ -908,19 +1237,24 @@ const computeProfileGraph = (profile, options) => {
908
1237
  *
909
1238
  * You can generate a V8 heap profile in several ways:
910
1239
  * - [`node --heap-prof`](https://nodejs.org/api/cli.html#--heap-prof)
911
- * - [`v8.writeHeapProfileSync()`](https://nodejs.org/api/v8.html#v8writeheapprofilesyncfilename)
1240
+ * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1241
+ * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1242
+ * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1243
+ * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
1244
+ * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
912
1245
  *
913
1246
  * Note that [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
914
1247
  * generates a heap _snapshot_ on exit, not a heap _profile_.
915
1248
  */
916
- const v8HeapProfileToMd = (data, options) => {
917
- const normalizedOptions = normalizeV8ProfileToMdOptions(options);
918
- return formatSummarizedProfile(summarizeProfile(parseProfile(data), normalizedOptions), normalizedOptions);
1249
+ const v8HeapProfileToMd = (data, options) => v8HeapProfileToMdInternal(parseV8HeapProfile(data), options);
1250
+ const v8HeapProfileToMdInternal = (profile, options) => {
1251
+ const normalizedOptions = normalizeProfileToMdOptions(options);
1252
+ return formatV8HeapProfile(summarizeV8HeapProfile(profile, normalizedOptions), normalizedOptions);
919
1253
  };
920
1254
 
921
1255
  //#endregion
922
- //#region src/v8/heap-snapshot/format.ts
923
- const formatSummarizedSnapshot = (snapshot, options) => `${[
1256
+ //#region src/formats/v8/heap-snapshot/format.ts
1257
+ const formatV8HeapSnapshot = (snapshot, options) => `${[
924
1258
  `# Heap snapshot`,
925
1259
  formatOverallSummary(snapshot),
926
1260
  formatLargestConstructors(snapshot, options),
@@ -957,7 +1291,7 @@ const formatLargestConstructors = (snapshot, options) => [
957
1291
  ].join(`\n\n`);
958
1292
  const formatLargestSelfSizeConstructors = (snapshot, options) => {
959
1293
  const { totalSize, constructors } = snapshot;
960
- const largestConstructors = selectTopN(constructors.filter(options.includeRow), options.topN, (constructor1, constructor2) => constructor2.selfSize - constructor1.selfSize);
1294
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.selfSize - constructor2.selfSize);
961
1295
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
962
1296
  return [
963
1297
  `### Self size`,
@@ -982,16 +1316,16 @@ const formatLargestSelfSizeConstructors = (snapshot, options) => {
982
1316
  formatBytes(constructor.selfSize),
983
1317
  formatCount(constructor.instances.length),
984
1318
  inlineCode(constructor.name),
985
- constructor.location ?? inlineCode(`<native>`)
1319
+ formatProfileLocation(constructor.location, options)
986
1320
  ])),
987
1321
  ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's self size.`] : [],
988
1322
  ...largestInstanceSections
989
1323
  ].join(`\n\n`);
990
1324
  };
991
1325
  const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
992
- const largestInstances = selectTopN(constructor.instances, Math.ceil(options.topN / 4), (instance1, instance2) => instance2.selfSize - instance1.selfSize);
993
- if (largestInstances.length === 0) return;
994
- return [`##### ${inlineCode(constructor.name)} (${constructor.location ?? inlineCode(`<native>`)})`, formatTable([
1326
+ const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.selfSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.selfSize - group1.selfSize);
1327
+ if (largestInstanceGroups.length === 0) return;
1328
+ return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
995
1329
  {
996
1330
  content: `%`,
997
1331
  align: `right`
@@ -1000,16 +1334,21 @@ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf
1000
1334
  content: `Size`,
1001
1335
  align: `right`
1002
1336
  },
1337
+ {
1338
+ content: `Instances`,
1339
+ align: `right`
1340
+ },
1003
1341
  `Path`
1004
- ], largestInstances.map((instance) => [
1005
- formatPercent(instance.selfSize / constructor.selfSize),
1006
- formatBytes(instance.selfSize),
1007
- inlineCode(retainerPathOf(instance.id))
1342
+ ], largestInstanceGroups.map((group) => [
1343
+ formatPercent(group.selfSize / constructor.selfSize),
1344
+ formatBytes(group.selfSize),
1345
+ formatCount(group.instanceCount),
1346
+ inlineCode(group.retainerPath)
1008
1347
  ]))].join(`\n\n`);
1009
1348
  };
1010
1349
  const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1011
1350
  const { totalSize, constructors } = snapshot;
1012
- const largestConstructors = selectTopN(constructors.filter(options.includeRow), options.topN, (constructor1, constructor2) => constructor2.retainedSize - constructor1.retainedSize);
1351
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.retainedSize - constructor2.retainedSize);
1013
1352
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1014
1353
  return [
1015
1354
  `### Retained size`,
@@ -1034,16 +1373,16 @@ const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1034
1373
  formatBytes(constructor.retainedSize),
1035
1374
  formatCount(constructor.instances.length),
1036
1375
  inlineCode(constructor.name),
1037
- constructor.location ?? inlineCode(`<native>`)
1376
+ formatProfileLocation(constructor.location, options)
1038
1377
  ])),
1039
1378
  ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's retained size.`] : [],
1040
1379
  ...largestInstanceSections
1041
1380
  ].join(`\n\n`);
1042
1381
  };
1043
1382
  const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
1044
- const largestInstances = selectTopN(constructor.instances, Math.ceil(options.topN / 4), (instance1, instance2) => instance2.retainedSize - instance1.retainedSize);
1045
- if (largestInstances.length === 0) return;
1046
- return [`##### ${inlineCode(constructor.name)} (${constructor.location ?? inlineCode(`<native>`)})`, formatTable([
1383
+ const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.retainedSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.retainedSize - group1.retainedSize);
1384
+ if (largestInstanceGroups.length === 0) return;
1385
+ return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
1047
1386
  {
1048
1387
  content: `%`,
1049
1388
  align: `right`
@@ -1052,16 +1391,46 @@ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPa
1052
1391
  content: `Size`,
1053
1392
  align: `right`
1054
1393
  },
1394
+ {
1395
+ content: `Instances`,
1396
+ align: `right`
1397
+ },
1055
1398
  `Path`
1056
- ], largestInstances.map((instance) => [
1057
- formatPercent(instance.retainedSize / constructor.retainedSize),
1058
- formatBytes(instance.retainedSize),
1059
- inlineCode(retainerPathOf(instance.id))
1399
+ ], largestInstanceGroups.map((group) => [
1400
+ formatPercent(group.retainedSize / constructor.retainedSize),
1401
+ formatBytes(group.retainedSize),
1402
+ formatCount(group.instanceCount),
1403
+ inlineCode(group.retainerPath)
1060
1404
  ]))].join(`\n\n`);
1061
1405
  };
1406
+ const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
1407
+ const heap = new MaxHeap(instances, (instance1, instance2) => sizeOf(instance1) - sizeOf(instance2));
1408
+ const pathToGroup = /* @__PURE__ */ new Map();
1409
+ while (heap.length > 0 && pathToGroup.size < topN) {
1410
+ const instance = heap.pop();
1411
+ const retainerPath = retainerPathOf(instance.id);
1412
+ let group = pathToGroup.get(retainerPath);
1413
+ if (!group) {
1414
+ group = {
1415
+ retainerPath,
1416
+ instanceCount: 0,
1417
+ selfSize: 0,
1418
+ retainedSize: 0
1419
+ };
1420
+ pathToGroup.set(retainerPath, group);
1421
+ }
1422
+ group.instanceCount++;
1423
+ group.selfSize += instance.selfSize;
1424
+ group.retainedSize += instance.retainedSize;
1425
+ }
1426
+ return [...pathToGroup.values()];
1427
+ };
1062
1428
  const formatLargestClosures = (snapshot, options) => {
1063
1429
  const { totalSize, closures, retainerPathOf } = snapshot;
1064
- const largestClosures = selectTopN(closures.filter(options.includeRow), options.topN, (closure1, closure2) => closure2.retainedSize - closure1.retainedSize);
1430
+ const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
1431
+ ...closure,
1432
+ id: closure.largestInstanceId
1433
+ })), options.topN, (closure1, closure2) => closure1.retainedSize - closure2.retainedSize);
1065
1434
  const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
1066
1435
  return [
1067
1436
  `## Largest closures`,
@@ -1075,30 +1444,48 @@ const formatLargestClosures = (snapshot, options) => {
1075
1444
  content: `Retained`,
1076
1445
  align: `right`
1077
1446
  },
1447
+ {
1448
+ content: `Instances`,
1449
+ align: `right`
1450
+ },
1451
+ {
1452
+ content: `Paths`,
1453
+ align: `right`
1454
+ },
1078
1455
  `Name`,
1079
1456
  `Location`,
1080
- `Path`
1457
+ `Example path`
1081
1458
  ], largestClosures.map((closure) => [
1082
1459
  formatPercent(closure.retainedSize / totalSize),
1083
1460
  formatBytes(closure.retainedSize),
1461
+ formatCount(closure.instanceIds.length),
1462
+ formatCount(new Set(closure.instanceIds.map(retainerPathOf)).size),
1084
1463
  inlineCode(closure.name),
1085
- closure.location ?? inlineCode(`<unknown>`),
1086
- inlineCode(retainerPathOf(closure.id))
1464
+ formatProfileLocation(closure.location, options),
1465
+ inlineCode(retainerPathOf(closure.largestInstanceId))
1087
1466
  ])),
1088
1467
  ...retainedSections.length > 0 ? [`### Retained`, `Objects ranked by contribution to each closure's retained size.`] : [],
1089
1468
  ...retainedSections
1090
1469
  ].join(`\n\n`);
1091
1470
  };
1092
1471
  const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, options) => {
1093
- const retainedNodes = selectTopN(retainedNodesOf(closure.id).filter(options.includeRow), Math.ceil(options.topN / 4), (node1, node2) => node2.selfSize - node1.selfSize);
1472
+ const instanceIdToSeen = new DynamicTypedArray(new Uint8Array(256));
1473
+ const allRetainedNodes = [];
1474
+ for (const instanceId of closure.instanceIds) for (const node of retainedNodesOf(instanceId)) {
1475
+ const seen = instanceIdToSeen.ensureCapacity(node.id + 1);
1476
+ if (seen[node.id]) continue;
1477
+ seen[node.id] = 1;
1478
+ if (options.includeEntry(node)) allRetainedNodes.push(node);
1479
+ }
1480
+ const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node1, node2) => node1.selfSize - node2.selfSize);
1094
1481
  if (retainedNodes.length === 0) return;
1095
- return [`#### ${inlineCode(closure.name)} (${closure.location ?? inlineCode(`<unknown>`)})`, formatTable([
1482
+ return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
1096
1483
  {
1097
1484
  content: `%`,
1098
1485
  align: `right`
1099
1486
  },
1100
1487
  {
1101
- content: `Size`,
1488
+ content: `Self`,
1102
1489
  align: `right`
1103
1490
  },
1104
1491
  `Name`,
@@ -1124,8 +1511,8 @@ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) =
1124
1511
  align: `right`
1125
1512
  },
1126
1513
  `Value`,
1127
- `Location`
1128
- ], selectTopN(strings, options.topN, (string1, string2) => string2.selfSize - string1.selfSize).map((string) => [
1514
+ `Path`
1515
+ ], selectTopN(strings, options.topN, (string1, string2) => string1.selfSize - string2.selfSize).map((string) => [
1129
1516
  formatPercent(string.selfSize / totalSize),
1130
1517
  formatBytes(string.selfSize),
1131
1518
  inlineCode(string.name),
@@ -1135,17 +1522,17 @@ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) =
1135
1522
  };
1136
1523
 
1137
1524
  //#endregion
1138
- //#region src/v8/heap-snapshot/parse.ts
1139
- const parseSnapshot = (data) => JSON.parse(data);
1525
+ //#region src/formats/v8/heap-snapshot/parse.ts
1526
+ const parseV8HeapSnapshot = (data) => parseJson(data);
1140
1527
 
1141
1528
  //#endregion
1142
- //#region src/v8/heap-snapshot/summarize.ts
1143
- const summarizeSnapshot = (snapshot, options) => {
1529
+ //#region src/formats/v8/heap-snapshot/summarize.ts
1530
+ const summarizeV8HeapSnapshot = (snapshot, options) => {
1144
1531
  const { snapshot: { meta, node_count: nodeCount, edge_count: edgeCount }, nodes } = snapshot;
1145
1532
  const [nodeTypes] = meta.node_types;
1146
1533
  const fieldLayout = computeFieldLayout(meta);
1147
1534
  const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
1148
- const nodeIndexToLocation = computeNodeIndexToLocation(snapshot, nodeAdjacencyGraph, fieldLayout, options);
1535
+ const nodeOrdinalToLocation = computeNodeOrdinalToLocation(snapshot, nodeAdjacencyGraph, fieldLayout);
1149
1536
  const immediateDominatorGraph = computeImmediateDominatorGraph(snapshot, nodeAdjacencyGraph);
1150
1537
  const nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(snapshot, immediateDominatorGraph, fieldLayout);
1151
1538
  let totalSize = 0;
@@ -1154,6 +1541,8 @@ const summarizeSnapshot = (snapshot, options) => {
1154
1541
  const nameToConstructorIndex = /* @__PURE__ */ new Map();
1155
1542
  const nodeOrdinalToConstructorIndex = new Int32Array(nodeCount).fill(-1);
1156
1543
  const closures = [];
1544
+ const keyToClosureIndex = /* @__PURE__ */ new Map();
1545
+ const nodeOrdinalToClosureIndex = new Int32Array(nodeCount).fill(-1);
1157
1546
  const strings = [];
1158
1547
  for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1159
1548
  const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
@@ -1191,7 +1580,7 @@ const summarizeSnapshot = (snapshot, options) => {
1191
1580
  nameToConstructorIndex.set(name, constructorIndex);
1192
1581
  } else constructor = constructors[constructorIndex];
1193
1582
  constructor.selfSize += selfSize;
1194
- constructor.location ??= nodeIndexToLocation.get(nodeIndex);
1583
+ constructor.location ??= nodeOrdinalToLocation[nodeOrdinal];
1195
1584
  constructor.instances.push({
1196
1585
  id: nodeOrdinal,
1197
1586
  name: constructor.name,
@@ -1202,15 +1591,29 @@ const summarizeSnapshot = (snapshot, options) => {
1202
1591
  nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
1203
1592
  break;
1204
1593
  }
1205
- case fieldLayout.nodeTypeClosure:
1206
- closures.push({
1207
- id: nodeOrdinal,
1208
- name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
1209
- selfSize,
1210
- retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal],
1211
- location: nodeIndexToLocation.get(nodeIndex)
1212
- });
1594
+ case fieldLayout.nodeTypeClosure: {
1595
+ const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
1596
+ const location = nodeOrdinalToLocation[nodeOrdinal];
1597
+ const key = `${name}|${location ? formatProfileLocation(location, options) : ``}`;
1598
+ const retainedSize = nodeOrdinalToRetainedSize[nodeOrdinal];
1599
+ let closureIndex = keyToClosureIndex.get(key);
1600
+ if (closureIndex === void 0) {
1601
+ closureIndex = closures.length;
1602
+ closures.push({
1603
+ name,
1604
+ location,
1605
+ retainedSize: 0,
1606
+ largestInstanceId: nodeOrdinal,
1607
+ instanceIds: []
1608
+ });
1609
+ keyToClosureIndex.set(key, closureIndex);
1610
+ }
1611
+ const closure = closures[closureIndex];
1612
+ closure.instanceIds.push(nodeOrdinal);
1613
+ if (retainedSize > nodeOrdinalToRetainedSize[closure.largestInstanceId]) closure.largestInstanceId = nodeOrdinal;
1614
+ nodeOrdinalToClosureIndex[nodeOrdinal] = closureIndex;
1213
1615
  break;
1616
+ }
1214
1617
  case fieldLayout.nodeTypeString:
1215
1618
  case fieldLayout.nodeTypeSlicedString:
1216
1619
  case fieldLayout.nodeTypeConcatenatedString:
@@ -1224,6 +1627,7 @@ const summarizeSnapshot = (snapshot, options) => {
1224
1627
  }
1225
1628
  }
1226
1629
  attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToConstructorIndex, constructors);
1630
+ attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToClosureIndex, closures);
1227
1631
  return {
1228
1632
  totalSize,
1229
1633
  nodeCount,
@@ -1232,7 +1636,7 @@ const summarizeSnapshot = (snapshot, options) => {
1232
1636
  constructors,
1233
1637
  closures,
1234
1638
  strings,
1235
- retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeIndexToLocation, immediateDominatorGraph, fieldLayout, options),
1639
+ retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeOrdinalToLocation, immediateDominatorGraph, fieldLayout, options),
1236
1640
  retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, immediateDominatorGraph, fieldLayout, options)
1237
1641
  };
1238
1642
  };
@@ -1291,44 +1695,54 @@ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes,
1291
1695
  offsetToPredecessorEdgeIndex
1292
1696
  };
1293
1697
  };
1294
- const computeNodeIndexToLocation = ({ nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, fieldLayout, options) => {
1698
+ const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
1295
1699
  const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
1296
- const nodeOrdinal = nodeIndex / fieldLayout.nodeFieldCount;
1700
+ const nodeOrdinal = nodeIndex / nodeFieldCount;
1297
1701
  const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
1298
1702
  const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
1299
1703
  for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
1300
1704
  const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
1301
- if (strings[edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + fieldLayout.edgeToNodeOffset];
1705
+ if (strings[edges[edgeIndex + edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + edgeToNodeOffset];
1302
1706
  }
1303
1707
  };
1304
1708
  const scriptIdToFileLocation = /* @__PURE__ */ new Map();
1305
- for (let locationIndex = 0; locationIndex < locations.length; locationIndex += fieldLayout.locationFieldCount) {
1306
- const scriptId = locations[locationIndex + fieldLayout.locationScriptIdOffset];
1709
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1710
+ const scriptId = locations[locationIndex + locationScriptIdOffset];
1307
1711
  if (scriptIdToFileLocation.has(scriptId)) continue;
1308
- const nodeIndex = locations[locationIndex + fieldLayout.locationObjectIndexOffset];
1309
- if (nodes[nodeIndex + fieldLayout.nodeTypeOffset] !== fieldLayout.nodeTypeClosure) continue;
1712
+ const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
1713
+ if (nodes[nodeIndex + nodeTypeOffset] !== nodeTypeClosure) continue;
1310
1714
  const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
1311
1715
  if (sharedNodeIndex === void 0) continue;
1312
1716
  const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
1313
1717
  if (scriptNodeIndex === void 0) continue;
1314
1718
  const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
1315
1719
  if (locationNodeIndex === void 0) continue;
1316
- const location = strings[nodes[locationNodeIndex + fieldLayout.nodeNameOffset]];
1720
+ const location = strings[nodes[locationNodeIndex + nodeNameOffset]];
1317
1721
  if (!location) continue;
1318
- const fileLocation = formatLocation(location, options);
1319
- if (fileLocation) scriptIdToFileLocation.set(scriptId, fileLocation);
1722
+ scriptIdToFileLocation.set(scriptId, location);
1320
1723
  }
1321
- const nodeIndexToLocation = /* @__PURE__ */ new Map();
1322
- for (let locationIndex = 0; locationIndex < locations.length; locationIndex += fieldLayout.locationFieldCount) {
1323
- const scriptId = locations[locationIndex + fieldLayout.locationScriptIdOffset];
1724
+ const nodeOrdinalToLocation = [];
1725
+ const fileLocationToUrl = /* @__PURE__ */ new Map();
1726
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1727
+ const scriptId = locations[locationIndex + locationScriptIdOffset];
1324
1728
  const fileLocation = scriptIdToFileLocation.get(scriptId);
1325
1729
  if (!fileLocation) continue;
1326
- const nodeIndex = locations[locationIndex + fieldLayout.locationObjectIndexOffset];
1327
- const line = locations[locationIndex + fieldLayout.locationLineOffset];
1328
- const column = locations[locationIndex + fieldLayout.locationColumnOffset];
1329
- nodeIndexToLocation.set(nodeIndex, `${fileLocation}:${line + 1}:${column + 1}`);
1730
+ let url = fileLocationToUrl.get(fileLocation);
1731
+ if (url === void 0) {
1732
+ url = makeProfileLocation({ urlOrPath: fileLocation })?.url ?? null;
1733
+ fileLocationToUrl.set(fileLocation, url);
1734
+ }
1735
+ if (!url) continue;
1736
+ const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
1737
+ const line = locations[locationIndex + locationLineOffset];
1738
+ const column = locations[locationIndex + locationColumnOffset];
1739
+ nodeOrdinalToLocation[nodeIndex / nodeFieldCount] = {
1740
+ url,
1741
+ line: line + 1,
1742
+ column: column + 1
1743
+ };
1330
1744
  }
1331
- return nodeIndexToLocation;
1745
+ return nodeOrdinalToLocation;
1332
1746
  };
1333
1747
  /**
1334
1748
  * Computes the immediate dominators of every node.
@@ -1377,7 +1791,8 @@ const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessorStartOffse
1377
1791
  const reachableCount = dfsIndex;
1378
1792
  const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
1379
1793
  const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
1380
- const ordinalToMinSemiAncestorOrdinal = Int32Array.from({ length: nodeCount }, (_, index) => index);
1794
+ const ordinalToMinSemiAncestorOrdinal = new Int32Array(nodeCount);
1795
+ for (let i = 0; i < nodeCount; i++) ordinalToMinSemiAncestorOrdinal[i] = i;
1381
1796
  const compressAncestorPath = (startNodeOrdinal) => {
1382
1797
  let pathLength = 0;
1383
1798
  let nodeOrdinal = startNodeOrdinal;
@@ -1460,7 +1875,7 @@ const computeNodeOrdinalToRetainedSize = ({ nodes }, { dfsIndexToOrdinal, ordina
1460
1875
  }
1461
1876
  return nodeOrdinalToRetainedSize;
1462
1877
  };
1463
- const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, nodeIndexToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout, options) => {
1878
+ const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, nodeOrdinalToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout, options) => {
1464
1879
  const { nodes } = snapshot;
1465
1880
  const hops = [];
1466
1881
  while (true) {
@@ -1483,9 +1898,9 @@ const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartO
1483
1898
  const retainerIndex = predecessorOrdinal * fieldLayout.nodeFieldCount;
1484
1899
  const retainerType = nodes[retainerIndex + fieldLayout.nodeTypeOffset];
1485
1900
  const retainerLabel = formatNodeLabel(retainerIndex, snapshot, fieldLayout, options);
1486
- const retainerLocation = nodeIndexToLocation.get(retainerIndex);
1901
+ const retainerLocation = nodeOrdinalToLocation[predecessorOrdinal];
1487
1902
  hops.push({
1488
- label: `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${retainerLocation})` : ``}`,
1903
+ label: `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${formatProfileLocation(retainerLocation, options)})` : ``}`,
1489
1904
  internal: isInternalNodeType(retainerType, fieldLayout)
1490
1905
  });
1491
1906
  nodeOrdinal = predecessorOrdinal;
@@ -1523,7 +1938,8 @@ const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) =>
1523
1938
  const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
1524
1939
  if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
1525
1940
  const rawEdgeName = strings[edgeNameOrIndex];
1526
- return `.${formatLocation(rawEdgeName, options) ?? rawEdgeName}`;
1941
+ const edgeLocation = makeProfileLocation({ urlOrPath: rawEdgeName });
1942
+ return `.${edgeLocation ? formatProfileLocation(edgeLocation, options) : rawEdgeName}`;
1527
1943
  };
1528
1944
  const formatNodeLabel = (nodeIndex, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, strings }, fieldLayout, options) => {
1529
1945
  const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
@@ -1537,7 +1953,8 @@ const formatNodeLabel = (nodeIndex, { snapshot: { meta: { node_types: [nodeTypes
1537
1953
  case fieldLayout.nodeTypeClosure: return strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || `(anonymous)`;
1538
1954
  default: {
1539
1955
  const rawNodeName = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || nodeTypes[nodeType];
1540
- return formatLocation(rawNodeName, options) ?? rawNodeName;
1956
+ const nodeLocation = makeProfileLocation({ urlOrPath: rawNodeName });
1957
+ return nodeLocation ? formatProfileLocation(nodeLocation, options) : rawNodeName;
1541
1958
  }
1542
1959
  }
1543
1960
  };
@@ -1630,7 +2047,16 @@ const computeFieldLayout = (meta) => {
1630
2047
  const valueToIndex = (values) => new Map(values.map((value, index) => [value, index]));
1631
2048
 
1632
2049
  //#endregion
1633
- //#region src/v8/heap-snapshot/index.ts
2050
+ //#region src/formats/v8/heap-snapshot/index.ts
2051
+ const detectV8HeapSnapshot = (json) => {
2052
+ if (typeof json !== `object` || json === null) return;
2053
+ const { snapshot, edges } = json;
2054
+ if (typeof snapshot !== `object` || snapshot === null) return;
2055
+ const { meta } = snapshot;
2056
+ if (typeof meta !== `object` || meta === null || !Array.isArray(meta.node_fields)) return;
2057
+ if (!Array.isArray(edges)) return;
2058
+ return json;
2059
+ };
1634
2060
  /**
1635
2061
  * Converts the given V8 heap snapshot to Markdown.
1636
2062
  *
@@ -1638,44 +2064,69 @@ const valueToIndex = (values) => new Map(values.map((value, index) => [value, in
1638
2064
  * function is undefined for invalid snapshots.
1639
2065
  *
1640
2066
  * You can generate a V8 heap snapshot in several ways:
2067
+ * - [`node --heapsnapshot-near-heap-limit=1`](https://nodejs.org/api/cli.html#heapsnapshot-near-heap-limitmax-count)
1641
2068
  * - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
2069
+ * - [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
1642
2070
  * - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
2071
+ * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
2072
+ * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
2073
+ * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
2074
+ * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
2075
+ * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
1643
2076
  */
1644
- const v8HeapSnapshotToMd = (data, options) => {
1645
- const normalizedOptions = normalizeV8ProfileToMdOptions(options);
1646
- return formatSummarizedSnapshot(summarizeSnapshot(parseSnapshot(data), normalizedOptions), normalizedOptions);
2077
+ const v8HeapSnapshotToMd = (data, options) => v8HeapSnapshotToMdInternal(parseV8HeapSnapshot(data), options);
2078
+ const v8HeapSnapshotToMdInternal = (snapshot, options) => {
2079
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2080
+ return formatV8HeapSnapshot(summarizeV8HeapSnapshot(snapshot, normalizedOptions), normalizedOptions);
1647
2081
  };
1648
2082
 
1649
2083
  //#endregion
1650
2084
  //#region src/cli.ts
1651
- const extensionToProfileConverter = new Map([
1652
- [`.cpuprofile`, {
2085
+ const jsonProfileConverters = [
2086
+ {
2087
+ type: `speedscope`,
2088
+ detect: detectSpeedscopeProfile,
2089
+ toMdInternal: speedscopeProfileToMdInternal,
2090
+ toMd: speedscopeProfileToMd
2091
+ },
2092
+ {
1653
2093
  type: `v8-cpu-profile`,
1654
- convert: v8CpuProfileToMd
1655
- }],
1656
- [`.heapprofile`, {
2094
+ detect: detectV8CpuProfile,
2095
+ toMdInternal: v8CpuProfileToMdInternal,
2096
+ toMd: v8CpuProfileToMd
2097
+ },
2098
+ {
1657
2099
  type: `v8-heap-profile`,
1658
- convert: v8HeapProfileToMd
1659
- }],
1660
- [`.heapsnapshot`, {
2100
+ detect: detectV8HeapProfile,
2101
+ toMdInternal: v8HeapProfileToMdInternal,
2102
+ toMd: v8HeapProfileToMd
2103
+ },
2104
+ {
1661
2105
  type: `v8-heap-snapshot`,
1662
- convert: v8HeapSnapshotToMd
1663
- }]
1664
- ]);
1665
- const profileTypeToConverter = new Map(Array.from(extensionToProfileConverter.values(), (profileConverter) => [profileConverter.type, profileConverter]));
2106
+ detect: detectV8HeapSnapshot,
2107
+ toMdInternal: v8HeapSnapshotToMdInternal,
2108
+ toMd: v8HeapSnapshotToMd
2109
+ }
2110
+ ];
2111
+ const binaryProfileConverters = [{
2112
+ type: `pprof`,
2113
+ detect: detectPprof,
2114
+ toMdInternal: pprofToMdInternal,
2115
+ toMd: pprofToMd
2116
+ }];
2117
+ const profileConverters = [...jsonProfileConverters, ...binaryProfileConverters];
1666
2118
  const cli = meow(`
1667
2119
  Usage: profiler-md [options] [file]
1668
2120
 
1669
2121
  Options:
1670
- -t, --type <type> Profile type (auto-detected from file extension by default)
2122
+ -t, --type <type> Profile type, auto-detected from content if omitted
2123
+ [${profileConverters.map(({ type }) => type).sort().join(`|`)}]
1671
2124
  -o, --output <file> Output file (default: - for stdout)
1672
2125
  --top-n <n> Number of top entries to show (default: 20)
1673
2126
  --cwd <path> Working directory for relative file paths in output
1674
- --third-party <glob> Mark URLs matching this glob as third-party (repeatable; default: node_modules)
2127
+ --third-party <glob> Mark URLs matching this glob as third-party
2128
+ (repeatable; default: node_modules)
1675
2129
  --help Show this help message
1676
-
1677
- Supported profile types:
1678
- ${Array.from(extensionToProfileConverter, ([extension, { type }]) => ` *${extension} -> ${type}`).join(`\n`)}
1679
2130
  `, {
1680
2131
  importMeta: import.meta,
1681
2132
  allowUnknownFlags: false,
@@ -1698,28 +2149,25 @@ ${Array.from(extensionToProfileConverter, ([extension, { type }]) => ` *${ext
1698
2149
  }
1699
2150
  }
1700
2151
  });
2152
+ const gunzipAsync = promisify(gunzip);
2153
+ const brotliDecompressAsync = promisify(brotliDecompress);
2154
+ const decompressData = async (data, filePath) => {
2155
+ if (filePath?.endsWith(`.br`)) return brotliDecompressAsync(data);
2156
+ if (data[0] === 31 && data[1] === 139) return gunzipAsync(data);
2157
+ return data;
2158
+ };
1701
2159
  try {
1702
2160
  const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty } } = cli;
1703
- let profileConverter;
2161
+ let forcedProfileConverter;
1704
2162
  if (profileType !== void 0) {
1705
- profileConverter = profileTypeToConverter.get(profileType);
1706
- if (!profileConverter) {
2163
+ forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
2164
+ if (!forcedProfileConverter) {
1707
2165
  process.stderr.write(`error: unknown profile type "${profileType}"\nRun with --help to see supported types.\n`);
1708
2166
  process.exit(2);
1709
2167
  }
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) {
2168
+ } else if (!filePath && process.stdin.isTTY) {
1718
2169
  cli.showHelp(0);
1719
2170
  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
2171
  }
1724
2172
  let data;
1725
2173
  if (filePath) try {
@@ -1730,12 +2178,45 @@ try {
1730
2178
  process.exit(1);
1731
2179
  }
1732
2180
  else data = Buffer.concat(await Array.fromAsync(process.stdin));
2181
+ try {
2182
+ data = await decompressData(data, filePath);
2183
+ } catch (error) {
2184
+ const message = error instanceof Error ? error.message : String(error);
2185
+ process.stderr.write(`error: failed to decompress input: ${message}\n`);
2186
+ process.exit(1);
2187
+ }
1733
2188
  const thirdPartyMatchers = thirdParty.map((glob) => picomatch(glob, { dot: true }));
1734
- const markdown = profileConverter.convert(data, {
2189
+ const options = {
1735
2190
  topN,
1736
2191
  cwd,
1737
- isThirdPartyURL: thirdPartyMatchers.length > 0 ? (url) => defaultIsThirdPartyURL(url) || thirdPartyMatchers.some((match) => match(url.pathname)) : void 0
1738
- });
2192
+ isThirdPartyEntry: thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0
2193
+ };
2194
+ let markdown;
2195
+ if (forcedProfileConverter) markdown = forcedProfileConverter.toMd(data, options);
2196
+ else {
2197
+ let json;
2198
+ try {
2199
+ json = parseJson(data);
2200
+ } catch {}
2201
+ if (json === void 0) for (const converter of binaryProfileConverters) {
2202
+ const parsed = converter.detect(data);
2203
+ if (parsed !== void 0) {
2204
+ markdown = converter.toMdInternal(parsed, options);
2205
+ break;
2206
+ }
2207
+ }
2208
+ else for (const converter of jsonProfileConverters) {
2209
+ const parsed = converter.detect(json);
2210
+ if (parsed !== void 0) {
2211
+ markdown = converter.toMdInternal(parsed, options);
2212
+ break;
2213
+ }
2214
+ }
2215
+ if (markdown === void 0) {
2216
+ 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`);
2217
+ process.exit(2);
2218
+ }
2219
+ }
1739
2220
  let output;
1740
2221
  if (outputPath === `-`) output = process.stdout;
1741
2222
  else {