profiler-md 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs DELETED
@@ -1,2346 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createWriteStream } from "node:fs";
3
- import { glob, readFile } from "node:fs/promises";
4
- import { dirname, resolve } from "node:path";
5
- import { pathToFileURL } from "node:url";
6
- import { promisify } from "node:util";
7
- import { brotliDecompress, gunzip } from "node:zlib";
8
- import convertSourceMap from "convert-source-map";
9
- import meow from "meow";
10
- import picomatch from "picomatch";
11
- import { Profile } from "pprof-format";
12
- import { SourceMapConsumer } from "source-map-js";
13
- import plur from "plur";
14
- import prettyBytes from "pretty-bytes";
15
- import prettyMilliseconds from "pretty-ms";
16
-
17
- //#region src/helpers/array.ts
18
- /**
19
- * A {@link TypedArray} wrapper that's growable.
20
- *
21
- * It's mainly useful when the indices are sequential IDs that arrive out of
22
- * order and with the maximum unknown.
23
- */
24
- var DynamicTypedArray = class {
25
- #array;
26
- #arrayConstructor;
27
- constructor(initialArray) {
28
- this.#array = initialArray;
29
- this.#arrayConstructor = initialArray.constructor;
30
- }
31
- ensureCapacity(minLength) {
32
- if (minLength > this.#array.length) {
33
- const grown = new this.#arrayConstructor(Math.max(minLength, this.#array.length * 2));
34
- grown.set(this.#array);
35
- this.#array = grown;
36
- }
37
- return this.#array;
38
- }
39
- };
40
-
41
- //#endregion
42
- //#region src/helpers/markdown.ts
43
- const formatHeading = (level, content) => `${`#`.repeat(level)} ${content}`;
44
- const formatTable = (headers, rows) => {
45
- const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
46
- const allRows = [headerContents, ...rows];
47
- const widths = headerContents.map((_, columnIndex) => Math.max(...allRows.map((row) => row[columnIndex]?.length ?? 0)));
48
- const isRight = (index) => typeof headers[index] !== `string` && headers[index]?.align === `right`;
49
- const alignCell = (cell, index) => isRight(index) ? cell.padStart(widths[index]) : cell.padEnd(widths[index]);
50
- const formatRow = (row) => `| ${row.map((cell, index) => alignCell(cell, index)).join(` | `)} |`;
51
- const separator = `| ${widths.map((width, index) => isRight(index) ? `${`-`.repeat(width - 1)}:` : `-`.repeat(width)).join(` | `)} |`;
52
- return [
53
- formatRow(headerContents),
54
- separator,
55
- ...rows.map(formatRow)
56
- ].join(`\n`);
57
- };
58
- const inlineCode = (text) => {
59
- const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
60
- const fence = `\``.repeat(longestBacktickRun + 1);
61
- return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
62
- };
63
-
64
- //#endregion
65
- //#region src/location.ts
66
- /**
67
- * Converts a {@link ProfileLocationInput} or a {@link ProfileLocation} or
68
- * returns undefined if it's not a valid location.
69
- */
70
- const makeProfileLocation = ({ urlOrPath, line, column }) => {
71
- if (!urlOrPath) return;
72
- const fileReference = makeFileReference(urlOrPath);
73
- if (fileReference.type !== `absolute`) return;
74
- return {
75
- url: fileReference.url,
76
- line,
77
- column
78
- };
79
- };
80
- const makeFileReference = (urlOrPath) => {
81
- if (urlOrPath.startsWith(`/`)) try {
82
- return {
83
- type: `absolute`,
84
- url: new URL(`file://${urlOrPath}`)
85
- };
86
- } catch {
87
- return {
88
- type: `relative`,
89
- path: urlOrPath
90
- };
91
- }
92
- if (!urlOrPath.includes(`:`)) return {
93
- type: `relative`,
94
- path: urlOrPath
95
- };
96
- try {
97
- return {
98
- type: `absolute`,
99
- url: new URL(urlOrPath)
100
- };
101
- } catch {
102
- return {
103
- type: `relative`,
104
- path: urlOrPath
105
- };
106
- }
107
- };
108
- const formatProfileLocation = (location, options) => {
109
- const { cwd } = options;
110
- if (!location) return inlineCode(`<native>`);
111
- location = sourceMapProfileLocation(location, options);
112
- let path;
113
- if (location.url.protocol === `file:`) {
114
- path = location.url.pathname;
115
- if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
116
- } else path = location.url.href;
117
- if (location.line !== void 0) {
118
- path += `:${location.line}`;
119
- if (location.column !== void 0) path += `:${location.column}`;
120
- }
121
- return path || inlineCode(`<native>`);
122
- };
123
-
124
- //#endregion
125
- //#region src/source-map.ts
126
- const normalizeSourceMaps = (sourceMaps) => {
127
- if (Array.isArray(sourceMaps)) sourceMaps = Object.fromEntries(sourceMaps.flatMap((sourceMap) => sourceMap.file ? [[sourceMap.file, sourceMap]] : []));
128
- return Object.entries(sourceMaps).map(([urlOrPath, sourceMap]) => ({
129
- consumer: new SourceMapConsumer(sourceMap),
130
- location: makeFileReference(urlOrPath)
131
- }));
132
- };
133
- const sourceMapProfileLocation = (location, { cwd, sourceMaps }) => {
134
- const sourceMap = sourceMaps.find((sourceMap) => sourceMap.location.type === `absolute` && sourceMap.location.url.href === location.url.href) ?? sourceMaps.find((sourceMap) => sourceMap.location.type === `relative` && location.url.pathname.endsWith(`/${sourceMap.location.path}`));
135
- if (!sourceMap) return location;
136
- let mappedPosition;
137
- try {
138
- mappedPosition = sourceMap.consumer.originalPositionFor({
139
- line: location.line ?? 1,
140
- column: (location.column ?? 1) - 1
141
- });
142
- } catch {
143
- return location;
144
- }
145
- if (!mappedPosition.source) return location;
146
- const mappedLocation = makeFileReference(mappedPosition.source);
147
- if (mappedLocation.type === `absolute`) return {
148
- url: mappedLocation.url,
149
- line: mappedPosition.line,
150
- column: mappedPosition.column + 1
151
- };
152
- if (!cwd) return location;
153
- return makeProfileLocation({
154
- urlOrPath: cwd + mappedLocation.path,
155
- line: mappedPosition.line,
156
- column: mappedPosition.column + 1
157
- }) ?? location;
158
- };
159
-
160
- //#endregion
161
- //#region src/options.ts
162
- const normalizeProfileToMdOptions = ({ topN = 20, includeEntry = defaultIncludeEntry, isThirdPartyEntry = defaultIsThirdPartyEntry, cwd, sourceMaps } = {}) => {
163
- if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
164
- if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
165
- return {
166
- topN,
167
- includeEntry: cacheEntryFunction(includeEntry),
168
- isThirdPartyEntry: cacheEntryFunction(isThirdPartyEntry),
169
- cwd: cwd ?? void 0,
170
- sourceMaps: normalizeSourceMaps(sourceMaps ?? [])
171
- };
172
- };
173
- const cacheEntryFunction = (func) => {
174
- const cache = new DynamicTypedArray(new Uint8Array(256));
175
- return (entry) => {
176
- const { id } = entry;
177
- const array = cache.ensureCapacity(id + 1);
178
- const value = array[id];
179
- if (value !== 0) return value === 2;
180
- const result = func(entry);
181
- array[id] = result ? 2 : 1;
182
- return result;
183
- };
184
- };
185
- /**
186
- * Returns whether to include the given entry in the Markdown output.
187
- *
188
- * Excludes synthetic profile data and redundant internals by default.
189
- */
190
- const defaultIncludeEntry = ({ name, location }) => {
191
- if (name === `(root)` || name === `(module)`) return false;
192
- if (!location && (name === `ModuleWrap` || name.startsWith(`system /`) || name.startsWith(`Node /`)) || location?.url.protocol === `node:` && location.url.pathname.startsWith(`internal/`)) return false;
193
- return true;
194
- };
195
- /**
196
- * Returns whether the given entry points to third-party code.
197
- *
198
- * Excludes `node_modules` only by default.
199
- */
200
- const defaultIsThirdPartyEntry = (entry) => !!entry.location?.url.pathname.includes(`/node_modules/`);
201
-
202
- //#endregion
203
- //#region src/helpers/format.ts
204
- const formatCount = (count, unit) => count.toLocaleString(`en-US`) + (unit ? ` ${plur(unit, count)}` : ``);
205
- const formatMilliseconds = (milliseconds) => prettyMilliseconds(milliseconds, {
206
- secondsDecimalDigits: 2,
207
- millisecondsDecimalDigits: 1,
208
- unitCount: 2
209
- });
210
- const formatMicrosecondsExact = (microseconds) => `${microseconds.toFixed(1)}µs`;
211
- const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
212
- const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
213
- const formatConjunction = (strings) => (conjunctionFormatter ??= new Intl.ListFormat(`en`, {
214
- style: `long`,
215
- type: `conjunction`
216
- })).format(strings);
217
- let conjunctionFormatter;
218
-
219
- //#endregion
220
- //#region src/helpers/heap.ts
221
- var MaxHeap = class {
222
- #keys;
223
- #values;
224
- /** Indices into {@link MaxHeap#keys} and {@link MaxHeap#values}. */
225
- #heap;
226
- #size;
227
- constructor(values, select) {
228
- const count = values.length;
229
- const heap = new Int32Array(count);
230
- const keys = new Float64Array(count);
231
- for (let i = 0; i < count; i++) {
232
- heap[i] = i;
233
- keys[i] = select(values[i]);
234
- }
235
- this.#keys = keys;
236
- this.#values = values;
237
- this.#heap = heap;
238
- this.#size = count;
239
- for (let i = Math.floor(count / 2) - 1; i >= 0; i--) this.#siftDown(i);
240
- }
241
- get length() {
242
- return this.#size;
243
- }
244
- pop() {
245
- if (this.#size === 0) return;
246
- const maxIndex = this.#heap[0];
247
- this.#heap[0] = this.#heap[--this.#size];
248
- this.#siftDown(0);
249
- return this.#values[maxIndex];
250
- }
251
- #siftDown(index) {
252
- while (true) {
253
- let largest = 2 * index + 1;
254
- if (largest >= this.#size) break;
255
- const right = largest + 1;
256
- if (right < this.#size) {
257
- const leftKey = this.#keys[this.#heap[largest]];
258
- const rightKey = this.#keys[this.#heap[right]];
259
- if (rightKey > leftKey || rightKey === leftKey && this.#heap[right] < this.#heap[largest]) largest = right;
260
- }
261
- const largestKey = this.#keys[this.#heap[largest]];
262
- const indexKey = this.#keys[this.#heap[index]];
263
- if (largestKey < indexKey || largestKey === indexKey && this.#heap[largest] > this.#heap[index]) break;
264
- const tmp = this.#heap[index];
265
- this.#heap[index] = this.#heap[largest];
266
- this.#heap[largest] = tmp;
267
- index = largest;
268
- }
269
- }
270
- };
271
- const selectTopN = (values, topN, select) => {
272
- if (topN === 0) return [];
273
- if (values.length <= topN) return values.toSorted((value1, value2) => select(value2) - select(value1));
274
- const heap = new MaxHeap(values, select);
275
- return Array.from({ length: topN }, () => heap.pop());
276
- };
277
-
278
- //#endregion
279
- //#region src/profile/summarize.ts
280
- var ProfileBuilder = class {
281
- #metrics;
282
- #functionKey;
283
- #functionInput;
284
- #options;
285
- #totalSampleCount;
286
- #totalValues;
287
- #categoryToMetrics;
288
- #keyToCallStack;
289
- #keyToFunction;
290
- #idToFunction;
291
- #functionIdToLastSeenSampleCount;
292
- #frameIndexToFramePairKey;
293
- constructor({ metrics, functionKey, functionInput }, options) {
294
- this.#metrics = metrics;
295
- this.#functionKey = functionKey;
296
- this.#functionInput = functionInput;
297
- this.#options = options;
298
- this.#totalSampleCount = 0;
299
- this.#totalValues = new Float64Array(this.#metrics.length);
300
- this.#categoryToMetrics = /* @__PURE__ */ new Map();
301
- this.#keyToCallStack = /* @__PURE__ */ new Map();
302
- this.#keyToFunction = /* @__PURE__ */ new Map();
303
- this.#idToFunction = [];
304
- this.#functionIdToLastSeenSampleCount = new DynamicTypedArray(new Uint32Array(1));
305
- this.#frameIndexToFramePairKey = new DynamicTypedArray(new Int32Array(64));
306
- }
307
- /** Adds a single profile sample. */
308
- addSample({ values, nodes, line }) {
309
- if (nodes.length === 0) return;
310
- const callStack = this.#getOrCreateCallStack(nodes);
311
- const callee = callStack.frames[0];
312
- const caller = callStack.frames[1];
313
- let categoryMetrics = this.#categoryToMetrics.get(callee.category);
314
- if (!categoryMetrics) {
315
- categoryMetrics = {
316
- sampleCount: 0,
317
- values: new Float64Array(this.#metrics.length)
318
- };
319
- this.#categoryToMetrics.set(callee.category, categoryMetrics);
320
- }
321
- let callerMetrics;
322
- if (caller) {
323
- callerMetrics = callee.callerIdToMetrics.get(caller.id);
324
- if (!callerMetrics) {
325
- callerMetrics = {
326
- caller,
327
- selfSampleCount: 0,
328
- selfValues: new Float64Array(this.#metrics.length)
329
- };
330
- callee.callerIdToMetrics.set(caller.id, callerMetrics);
331
- }
332
- }
333
- let lineMetrics;
334
- if (line !== void 0) {
335
- lineMetrics = callee.lineToMetrics.get(line);
336
- if (!lineMetrics) {
337
- lineMetrics = {
338
- sampleCount: 0,
339
- values: new Float64Array(this.#metrics.length)
340
- };
341
- callee.lineToMetrics.set(line, lineMetrics);
342
- }
343
- }
344
- this.#totalSampleCount++;
345
- categoryMetrics.sampleCount++;
346
- callStack.selfSampleCount++;
347
- callee.selfSampleCount++;
348
- if (callerMetrics) callerMetrics.selfSampleCount++;
349
- if (lineMetrics) lineMetrics.sampleCount++;
350
- for (let i = 0; i < values.length; i++) {
351
- this.#totalValues[i] += values[i];
352
- categoryMetrics.values[i] += values[i];
353
- callStack.selfValues[i] += values[i];
354
- callee.selfValues[i] += values[i];
355
- if (callerMetrics) callerMetrics.selfValues[i] += values[i];
356
- if (lineMetrics) lineMetrics.values[i] += values[i];
357
- }
358
- const funcCount = this.#keyToFunction.size;
359
- const functionIdToLastSeenSampleCount = this.#functionIdToLastSeenSampleCount.ensureCapacity(funcCount);
360
- for (const func of callStack.frames) {
361
- if (functionIdToLastSeenSampleCount[func.id] === this.#totalSampleCount) continue;
362
- functionIdToLastSeenSampleCount[func.id] = this.#totalSampleCount;
363
- func.totalSampleCount++;
364
- for (let i = 0; i < values.length; i++) func.totalValues[i] += values[i];
365
- }
366
- const maxFramePairCount = callStack.frames.length - 1;
367
- const frameIndexToFramePairKey = this.#frameIndexToFramePairKey.ensureCapacity(maxFramePairCount);
368
- let seenFramePairCount = 0;
369
- for (let i = 0; i < maxFramePairCount; i++) {
370
- const callee = callStack.frames[i];
371
- const caller = callStack.frames[i + 1];
372
- const pairKey = caller.id * funcCount + callee.id;
373
- let pairAlreadySeen = false;
374
- for (let j = 0; j < seenFramePairCount; j++) if (frameIndexToFramePairKey[j] === pairKey) {
375
- pairAlreadySeen = true;
376
- break;
377
- }
378
- if (pairAlreadySeen) continue;
379
- frameIndexToFramePairKey[seenFramePairCount++] = pairKey;
380
- let calleeMetrics = caller.calleeIdToMetrics.get(callee.id);
381
- if (!calleeMetrics) {
382
- calleeMetrics = {
383
- callee,
384
- totalSampleCount: 0,
385
- totalValues: new Float64Array(this.#metrics.length)
386
- };
387
- caller.calleeIdToMetrics.set(callee.id, calleeMetrics);
388
- }
389
- calleeMetrics.totalSampleCount++;
390
- for (let i = 0; i < values.length; i++) calleeMetrics.totalValues[i] += values[i];
391
- }
392
- }
393
- addLineMetrics({ node, lines }) {
394
- const func = this.#getOrCreateFunction(node);
395
- for (const { line, sampleCount, values } of lines) {
396
- let lineMetrics = func.lineToMetrics.get(line);
397
- if (!lineMetrics) {
398
- lineMetrics = {
399
- sampleCount: 0,
400
- values: new Float64Array(this.#metrics.length)
401
- };
402
- func.lineToMetrics.set(line, lineMetrics);
403
- }
404
- lineMetrics.sampleCount += sampleCount;
405
- for (let i = 0; i < values.length; i++) lineMetrics.values[i] += values[i];
406
- }
407
- }
408
- #getOrCreateCallStack(nodes) {
409
- const frames = nodes.map((node) => this.#getOrCreateFunction(node));
410
- const key = frames.map((frame) => frame.id).join(`,`);
411
- let callStack = this.#keyToCallStack.get(key);
412
- if (callStack) return callStack;
413
- callStack = {
414
- frames,
415
- selfSampleCount: 0,
416
- selfValues: new Float64Array(this.#metrics.length)
417
- };
418
- this.#keyToCallStack.set(key, callStack);
419
- return callStack;
420
- }
421
- #getOrCreateFunction(node) {
422
- let func = this.#idToFunction[node.id];
423
- if (func) return func;
424
- const key = this.#functionKey(node);
425
- func = this.#keyToFunction.get(key);
426
- if (func) {
427
- this.#idToFunction[node.id] = func;
428
- return func;
429
- }
430
- const { name: nameInput, location: locationInput } = this.#functionInput(node);
431
- const entry = {
432
- id: this.#keyToFunction.size,
433
- name: nameInput || `(anonymous)`,
434
- location: locationInput ? makeProfileLocation(locationInput) : void 0
435
- };
436
- func = {
437
- ...entry,
438
- category: categorizeFunction(entry, this.#options),
439
- selfSampleCount: 0,
440
- totalSampleCount: 0,
441
- selfValues: new Float64Array(this.#metrics.length),
442
- totalValues: new Float64Array(this.#metrics.length),
443
- lineToMetrics: /* @__PURE__ */ new Map(),
444
- callerIdToMetrics: /* @__PURE__ */ new Map(),
445
- calleeIdToMetrics: /* @__PURE__ */ new Map()
446
- };
447
- this.#idToFunction[node.id] = func;
448
- this.#keyToFunction.set(key, func);
449
- return func;
450
- }
451
- build() {
452
- const samplingIntervals = new Float64Array(this.#metrics.length);
453
- for (let i = 0; i < samplingIntervals.length; i++) samplingIntervals[i] = this.#totalValues[i] / this.#totalSampleCount;
454
- const functions = [...this.#keyToFunction.values()];
455
- const callStacks = [...this.#keyToCallStack.values()];
456
- return {
457
- metrics: this.#metrics,
458
- totalSampleCount: this.#totalSampleCount,
459
- totalValues: this.#totalValues,
460
- samplingIntervals,
461
- categoryToMetrics: this.#categoryToMetrics,
462
- functions,
463
- callStacks
464
- };
465
- }
466
- };
467
- const categorizeFunction = (entry, { isThirdPartyEntry }) => {
468
- const { name, location } = entry;
469
- if (name.startsWith(`(`) && name.endsWith(`)`) && !name.startsWith(`(anonymous`)) return name.slice(1, -1);
470
- if (name.startsWith(`RegExp: `)) return `regexp`;
471
- if (!location || location.url.protocol === `node:`) return `native`;
472
- return isThirdPartyEntry(entry) ? `third-party` : `ours`;
473
- };
474
- /**
475
- * Returns the list of callers of {@link callStacks} that is the longest common
476
- * suffix of their frames, except it never returns a call stack as long as one
477
- * of the input call stacks.
478
- *
479
- * This behavior is so that it's safe to remove that suffix from any of the call
480
- * stacks and end up with a non-empty call stack to render.
481
- */
482
- const findCommonCallStack = (callStacks) => {
483
- if (callStacks.length <= 1) return [];
484
- const minLength = Math.min(...callStacks.map((cs) => cs.frames.length));
485
- const firstFrames = callStacks[0].frames;
486
- let suffixLength = 0;
487
- for (let i = 1; i < minLength; i++) {
488
- const suffix = firstFrames.slice(-i).map((frame) => frame.id);
489
- if (callStacks.every((callStack) => callStack.frames.slice(-i).every((frame, j) => frame.id === suffix[j]))) suffixLength = i;
490
- else break;
491
- }
492
- return suffixLength > 0 ? firstFrames.slice(-suffixLength) : [];
493
- };
494
-
495
- //#endregion
496
- //#region src/profile/format.ts
497
- const formatProfile = (profile, options) => {
498
- const headingLevel = 1;
499
- return `${[
500
- formatHeading(headingLevel, formatTitle(profile)),
501
- formatOverallSummary$1(profile),
502
- formatMetricSections(profile, {
503
- ...options,
504
- headingLevel: headingLevel + 1
505
- })
506
- ].join(`\n\n`)}\n`;
507
- };
508
- const formatTitle = (profile) => capitalizeFirst(`${formatConjunction(profile.metrics.map(metricTitleName))} profile`);
509
- const metricTitleName = (metric) => {
510
- switch (metric.type) {
511
- case `time`: return `CPU`;
512
- case `size`: return `heap`;
513
- case `custom`: return metric.name;
514
- }
515
- };
516
- const formatOverallSummary$1 = (profile) => `${formatSummaryLine(profile)}\n\n${formatCategoryTable(profile)}`;
517
- const formatSummaryLine = ({ metrics, totalSampleCount, totalValues, samplingIntervals }) => {
518
- const totalsSummary = capitalizeFirst(formatConjunction(metrics.map((metric, index) => `${metricPastTenseVerb(metric)} ${formatValue(totalValues[index], metric)}`)));
519
- const samplingIntervalsSummary = `(${formatConjunction(Array.from(samplingIntervals, (interval, index) => formatSamplingInterval(interval, metrics[index])))} per sample)`;
520
- return `${totalsSummary} over ${formatCount(totalSampleCount, `sample`)} ${samplingIntervalsSummary}.`;
521
- };
522
- const formatCategoryTable = ({ metrics, totalValues, categoryToMetrics }) => {
523
- const hottestCategories = [...categoryToMetrics].sort(([, metrics1], [, metrics2]) => metrics2.values[0] - metrics1.values[0]);
524
- return formatTable([
525
- `Category`,
526
- {
527
- content: `%`,
528
- align: `right`
529
- },
530
- ...metrics.map((metric) => ({
531
- content: capitalizeFirst(metricDisplayName(metric)),
532
- align: `right`
533
- })),
534
- {
535
- content: `Samples`,
536
- align: `right`
537
- }
538
- ], hottestCategories.map(([category, { values, sampleCount }]) => [
539
- category,
540
- formatPercent(values[0] / totalValues[0]),
541
- ...metrics.map((metric, index) => formatValue(values[index], metric)),
542
- formatCount(sampleCount)
543
- ]));
544
- };
545
- const metricPastTenseVerb = (metric) => {
546
- switch (metric.type) {
547
- case `time`: return `took`;
548
- case `size`: return `allocated`;
549
- case `custom`: return `recorded`;
550
- }
551
- };
552
- const formatSamplingInterval = (samplingInterval, metric) => {
553
- switch (metric.type) {
554
- case `time`: return formatMicrosecondsExact(samplingInterval * 1e3 * metric.milliseconds);
555
- case `size`: return formatBytes(samplingInterval * metric.bytes);
556
- case `custom`: return formatCount(samplingInterval, metric.unit);
557
- }
558
- };
559
- const formatMetricSections = (profile, options) => profile.metrics.flatMap((metric, index) => {
560
- const sections = [];
561
- let sectionOptions = options;
562
- if (profile.metrics.length > 1) {
563
- sections.push(formatHeading(options.headingLevel, capitalizeFirst(metricDisplayName(metric))));
564
- sectionOptions = {
565
- ...options,
566
- headingLevel: options.headingLevel + 1
567
- };
568
- }
569
- const callStacksSection = formatHottestCallStacks(index, profile, sectionOptions);
570
- return [
571
- ...sections,
572
- formatHottestFunctions(index, profile, sectionOptions),
573
- ...callStacksSection === void 0 ? [] : [callStacksSection]
574
- ];
575
- }).join(`\n\n`);
576
- const formatHottestFunctions = (metricIndex, profile, options) => {
577
- const subsectionOptions = {
578
- ...options,
579
- headingLevel: options.headingLevel + 1
580
- };
581
- return [
582
- formatHeading(options.headingLevel, `Hottest functions`),
583
- formatHottestSelfFunctions(metricIndex, profile, subsectionOptions),
584
- formatHottestTotalFunctions(metricIndex, profile, subsectionOptions)
585
- ].join(`\n\n`);
586
- };
587
- const formatHottestSelfFunctions = (metricIndex, profile, options) => {
588
- const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (func) => func.selfValues[metricIndex]);
589
- const subsectionOptions = {
590
- ...options,
591
- headingLevel: options.headingLevel + 2
592
- };
593
- const hottestLinesSections = hottestFunctions.filter((func) => func.lineToMetrics.size > 0).map((func) => formatHottestLines(metricIndex, func, profile, subsectionOptions));
594
- const hottestCallersSections = hottestFunctions.map((func) => formatHottestCallers(metricIndex, func, profile, subsectionOptions)).filter((section) => section !== void 0);
595
- const metric = profile.metrics[metricIndex];
596
- const metricName = metricDisplayName(metric);
597
- return [
598
- formatHeading(options.headingLevel, `Self ${metricName}`),
599
- `Functions ranked by ${metricPastParticipleVerbPhrase(metric)} directly in the function body, excluding callees.`,
600
- formatTable([
601
- {
602
- content: `%`,
603
- align: `right`
604
- },
605
- {
606
- content: capitalizeFirst(metricName),
607
- align: `right`
608
- },
609
- {
610
- content: `Samples`,
611
- align: `right`
612
- },
613
- `Function`,
614
- `Location`
615
- ], hottestFunctions.map((func) => [
616
- formatPercent(func.selfValues[metricIndex] / profile.totalValues[metricIndex]),
617
- formatValue(func.selfValues[metricIndex], metric),
618
- formatCount(func.selfSampleCount),
619
- inlineCode(func.name),
620
- formatProfileLocation(func.location, options)
621
- ])),
622
- ...hottestLinesSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Lines`), `Lines ranked by contribution to each function's self ${metricName}.`] : [],
623
- ...hottestLinesSections,
624
- ...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.`] : [],
625
- ...hottestCallersSections
626
- ].join(`\n\n`);
627
- };
628
- const formatHottestLines = (metricIndex, func, profile, options) => {
629
- const selfValue = func.selfValues[metricIndex];
630
- const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics]) => metrics.values[metricIndex]);
631
- const metric = profile.metrics[metricIndex];
632
- return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
633
- {
634
- content: `%`,
635
- align: `right`
636
- },
637
- {
638
- content: capitalizeFirst(metricDisplayName(metric)),
639
- align: `right`
640
- },
641
- {
642
- content: `Samples`,
643
- align: `right`
644
- },
645
- `Location`
646
- ], hottestLines.map(([line, stats]) => [
647
- formatPercent(stats.values[metricIndex] / selfValue),
648
- formatValue(stats.values[metricIndex], metric),
649
- formatCount(stats.sampleCount),
650
- func.location ? formatProfileLocation({
651
- ...func.location,
652
- line,
653
- column: void 0
654
- }, options) : String(line)
655
- ]))].join(`\n\n`);
656
- };
657
- const formatHottestCallers = (metricIndex, func, profile, options) => {
658
- const selfValue = func.selfValues[metricIndex];
659
- const hottestCallers = selectTopN([...func.callerIdToMetrics.values()].filter((entry) => options.includeEntry(entry.caller) && entry.selfValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.selfValues[metricIndex]);
660
- if (hottestCallers.length === 0) return;
661
- const metric = profile.metrics[metricIndex];
662
- return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
663
- {
664
- content: `%`,
665
- align: `right`
666
- },
667
- {
668
- content: capitalizeFirst(metricDisplayName(metric)),
669
- align: `right`
670
- },
671
- {
672
- content: `Samples`,
673
- align: `right`
674
- },
675
- `Caller`,
676
- `Location`
677
- ], hottestCallers.map(({ caller, selfValues, selfSampleCount }) => [
678
- formatPercent(selfValues[metricIndex] / selfValue),
679
- formatValue(selfValues[metricIndex], metric),
680
- formatCount(selfSampleCount),
681
- inlineCode(caller.name),
682
- formatProfileLocation(caller.location, options)
683
- ]))].join(`\n\n`);
684
- };
685
- const formatHottestTotalFunctions = (metricIndex, profile, options) => {
686
- const totalValue = profile.totalValues[metricIndex];
687
- const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.totalValues[metricIndex] > 0), options.topN, (func) => func.totalValues[metricIndex]);
688
- const subsectionOptions = {
689
- ...options,
690
- headingLevel: options.headingLevel + 2
691
- };
692
- const calleeSections = hottestFunctions.map((func) => formatHottestCallees(metricIndex, func, profile, subsectionOptions)).filter((section) => section !== void 0);
693
- const metric = profile.metrics[metricIndex];
694
- const metricName = metricDisplayName(metric);
695
- return [
696
- formatHeading(options.headingLevel, `Total ${metricName}`),
697
- `Functions ranked by total ${metricPastParticipleVerbPhrase(metric)} in the function and all its callees.`,
698
- formatTable([
699
- {
700
- content: `%`,
701
- align: `right`
702
- },
703
- {
704
- content: capitalizeFirst(metricName),
705
- align: `right`
706
- },
707
- {
708
- content: `Samples`,
709
- align: `right`
710
- },
711
- `Function`,
712
- `Location`
713
- ], hottestFunctions.map((func) => [
714
- formatPercent(func.totalValues[metricIndex] / totalValue),
715
- formatValue(func.totalValues[metricIndex], metric),
716
- formatCount(func.totalSampleCount),
717
- inlineCode(func.name),
718
- formatProfileLocation(func.location, options)
719
- ])),
720
- ...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.`] : [],
721
- ...calleeSections
722
- ].join(`\n\n`);
723
- };
724
- const formatHottestCallees = (metricIndex, func, profile, options) => {
725
- const totalValue = func.totalValues[metricIndex];
726
- const hottestCallees = selectTopN([...func.calleeIdToMetrics.values()].filter((entry) => options.includeEntry(entry.callee) && entry.totalValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.totalValues[metricIndex]);
727
- if (hottestCallees.length === 0) return;
728
- const metric = profile.metrics[metricIndex];
729
- const metricName = metricDisplayName(metric);
730
- return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
731
- {
732
- content: `%`,
733
- align: `right`
734
- },
735
- {
736
- content: capitalizeFirst(metricName),
737
- align: `right`
738
- },
739
- {
740
- content: `Samples`,
741
- align: `right`
742
- },
743
- `Callee`,
744
- `Location`
745
- ], hottestCallees.map(({ callee, totalValues, totalSampleCount }) => [
746
- formatPercent(totalValues[metricIndex] / totalValue),
747
- formatValue(totalValues[metricIndex], metric),
748
- formatCount(totalSampleCount),
749
- inlineCode(callee.name),
750
- formatProfileLocation(callee.location, options)
751
- ]))].join(`\n\n`);
752
- };
753
- const formatHottestCallStacks = (metricIndex, profile, options) => {
754
- const totalValue = profile.totalValues[metricIndex];
755
- const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
756
- ...callStack,
757
- frames: callStack.frames.filter(options.includeEntry)
758
- })).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack) => callStack.selfValues[metricIndex]);
759
- if (hottestCallStacks.length === 0) return;
760
- const metric = profile.metrics[metricIndex];
761
- const metricName = metricDisplayName(metric);
762
- const commonCallStack = findCommonCallStack(hottestCallStacks);
763
- return [
764
- formatHeading(options.headingLevel, `Hottest call stacks`),
765
- `Call stacks ranked by ${metricPastParticipleVerbPhrase(metric)} in their top frame.`,
766
- ...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack, options)}`] : [],
767
- formatTable([
768
- {
769
- content: `%`,
770
- align: `right`
771
- },
772
- {
773
- content: capitalizeFirst(metricName),
774
- align: `right`
775
- },
776
- {
777
- content: `Samples`,
778
- align: `right`
779
- },
780
- `Call stack`
781
- ], hottestCallStacks.map(({ frames, selfValues, selfSampleCount }) => [
782
- formatPercent(selfValues[metricIndex] / totalValue),
783
- formatValue(selfValues[metricIndex], metric),
784
- formatCount(selfSampleCount),
785
- formatCallStack(commonCallStack.length > 0 ? frames.slice(0, -commonCallStack.length) : frames, options)
786
- ]))
787
- ].join(`\n\n`);
788
- };
789
- const formatCallStack = (nodes, options) => nodes.map((node, index) => {
790
- const name = inlineCode(node.name);
791
- if (!node.location) return name;
792
- const previousHref = nodes[index - 1]?.location?.url.href;
793
- if (!previousHref || node.location.url.href !== previousHref) return `${name} (${formatProfileLocation(node.location, options)})`;
794
- const { line, column } = node.location;
795
- if (line === void 0) return name;
796
- return `${name} (${line}${column === void 0 ? `` : `:${column}`})`;
797
- }).join(` ← `);
798
- const metricPastParticipleVerbPhrase = (metric) => {
799
- switch (metric.type) {
800
- case `time`: return `time spent`;
801
- case `size`: return `bytes allocated`;
802
- case `custom`: return `${metricDisplayName(metric)} recorded`;
803
- }
804
- };
805
- const metricDisplayName = (metric) => {
806
- switch (metric.type) {
807
- case `time`:
808
- case `size`: return metric.type;
809
- case `custom`: return metric.name;
810
- }
811
- };
812
- const formatValue = (value, metric) => {
813
- switch (metric.type) {
814
- case `time`: return formatMilliseconds(value * metric.milliseconds);
815
- case `size`: return formatBytes(value * metric.bytes);
816
- case `custom`: return formatCount(value, metric.unit);
817
- }
818
- };
819
- const capitalizeFirst = (string) => string.length === 0 ? string : string[0].toUpperCase() + string.slice(1);
820
-
821
- //#endregion
822
- //#region src/profile/metric.ts
823
- const determineMetric = ({ name, unit }) => METRICS.get(unit.toLowerCase()) ?? {
824
- type: `custom`,
825
- name,
826
- unit
827
- };
828
- const NANOSECONDS = {
829
- type: `time`,
830
- milliseconds: 1e-6
831
- };
832
- const MICROSECONDS = {
833
- type: `time`,
834
- milliseconds: .001
835
- };
836
- const MILLISECONDS = {
837
- type: `time`,
838
- milliseconds: 1
839
- };
840
- const SECONDS = {
841
- type: `time`,
842
- milliseconds: 1e3
843
- };
844
- const BYTES = {
845
- type: `size`,
846
- bytes: 1
847
- };
848
- const KILOBYTES = {
849
- type: `size`,
850
- bytes: 1024
851
- };
852
- const MEGABYTES = {
853
- type: `size`,
854
- bytes: 1 << 20
855
- };
856
- const GIGABYTES = {
857
- type: `size`,
858
- bytes: 1 << 30
859
- };
860
- const METRICS = new Map([
861
- [`nanoseconds`, NANOSECONDS],
862
- [`nanosecond`, NANOSECONDS],
863
- [`nanos`, NANOSECONDS],
864
- [`ns`, NANOSECONDS],
865
- [`microseconds`, MICROSECONDS],
866
- [`microsecond`, MICROSECONDS],
867
- [`micros`, MICROSECONDS],
868
- [`us`, MICROSECONDS],
869
- [`μs`, MICROSECONDS],
870
- [`milliseconds`, MILLISECONDS],
871
- [`millisecond`, MILLISECONDS],
872
- [`millis`, MILLISECONDS],
873
- [`ms`, MILLISECONDS],
874
- [`seconds`, SECONDS],
875
- [`second`, SECONDS],
876
- [`secs`, SECONDS],
877
- [`sec`, SECONDS],
878
- [`s`, SECONDS],
879
- [`bytes`, BYTES],
880
- [`byte`, BYTES],
881
- [`b`, BYTES],
882
- [`kilobytes`, KILOBYTES],
883
- [`kilobyte`, KILOBYTES],
884
- [`kbytes`, KILOBYTES],
885
- [`kbyte`, KILOBYTES],
886
- [`kb`, KILOBYTES],
887
- [`megabytes`, MEGABYTES],
888
- [`megabyte`, MEGABYTES],
889
- [`mbytes`, MEGABYTES],
890
- [`mbyte`, MEGABYTES],
891
- [`mb`, MEGABYTES],
892
- [`gigabytes`, GIGABYTES],
893
- [`gigabyte`, GIGABYTES],
894
- [`gbytes`, GIGABYTES],
895
- [`gbyte`, GIGABYTES],
896
- [`gb`, GIGABYTES],
897
- [`none`, {
898
- type: `custom`,
899
- name: `count`,
900
- unit: `count`
901
- }]
902
- ]);
903
-
904
- //#endregion
905
- //#region src/formats/pprof/format.ts
906
- const formatPprof = (profile, options) => formatProfile(profile, options);
907
-
908
- //#endregion
909
- //#region src/formats/pprof/parse.ts
910
- const parsePprof = (data) => parsePprofInternal(Profile.decode(data));
911
- const parsePprofInternal = (profile) => {
912
- const { strings } = profile.stringTable;
913
- const valueTypes = profile.sampleType.map(({ type, unit }) => ({
914
- type: strings[Number(type)] ?? ``,
915
- unit: strings[Number(unit)] ?? ``
916
- }));
917
- const functionIdToIndex = [];
918
- const functions = [];
919
- for (const func of profile.function) {
920
- const id = Number(func.id);
921
- functionIdToIndex[id] = functions.length;
922
- functions.push({
923
- id,
924
- name: strings[Number(func.name)] ?? ``,
925
- systemName: strings[Number(func.systemName)] ?? ``,
926
- filename: strings[Number(func.filename)] ?? ``,
927
- startLine: Number(func.startLine)
928
- });
929
- }
930
- const locationIdToIndex = [];
931
- const locations = [];
932
- for (const location of profile.location) {
933
- const id = Number(location.id);
934
- locationIdToIndex[id] = locations.length;
935
- locations.push({
936
- id,
937
- lines: location.line.map(({ functionId, line }) => ({
938
- functionId: functionIdToIndex[Number(functionId)],
939
- line: Number(line)
940
- }))
941
- });
942
- }
943
- return {
944
- valueTypes,
945
- samples: profile.sample.map(({ locationId, value }) => ({
946
- locationIds: locationId.map((id) => locationIdToIndex[Number(id)]),
947
- values: value.map(Number)
948
- })),
949
- locations,
950
- functions
951
- };
952
- };
953
-
954
- //#endregion
955
- //#region src/formats/pprof/summarize.ts
956
- const summarizePprof = ({ valueTypes, samples, locations, functions }, options) => {
957
- const nonCountValueTypes = [...valueTypes.entries()].filter(([, valueType]) => valueType.unit.toLowerCase() !== `count`);
958
- const profileBuilder = new ProfileBuilder({
959
- metrics: nonCountValueTypes.map(([, valueType]) => determineMetric({
960
- name: valueType.type,
961
- unit: valueType.unit
962
- })),
963
- functionKey: (func) => func.id,
964
- functionInput: (func) => ({
965
- name: func.name || func.systemName,
966
- location: {
967
- urlOrPath: func.filename,
968
- line: func.startLine > 0 ? func.startLine : void 0
969
- }
970
- })
971
- }, options);
972
- for (const sample of samples) {
973
- const { locationIds, values } = sample;
974
- const nodes = [];
975
- let calleeLine;
976
- for (const locationId of locationIds) {
977
- const location = locations[locationId];
978
- for (const { functionId, line } of location.lines) {
979
- nodes.push(functions[functionId]);
980
- calleeLine ??= line;
981
- }
982
- }
983
- if (nodes.length === 0) continue;
984
- profileBuilder.addSample({
985
- values: nonCountValueTypes.map(([index]) => values[index]),
986
- nodes,
987
- line: calleeLine
988
- });
989
- }
990
- return profileBuilder.build();
991
- };
992
-
993
- //#endregion
994
- //#region src/formats/pprof/index.ts
995
- const detectPprof = (data) => {
996
- if (data.length === 0) return;
997
- let profile;
998
- try {
999
- profile = Profile.decode(data);
1000
- } catch {
1001
- return;
1002
- }
1003
- if (profile.stringTable.strings[0] !== ``) return;
1004
- return parsePprofInternal(profile);
1005
- };
1006
- /**
1007
- * Converts the given pprof to Markdown.
1008
- *
1009
- * It is assumed that {@link data} is a valid pprof (raw protobuf). The behavior
1010
- * of this function is undefined for invalid profiles.
1011
- *
1012
- * pprof can be generated by many tools, including:
1013
- * - Go's [`runtime/pprof`](https://pkg.go.dev/runtime/pprof) package
1014
- * - Node.js's [`pprof`](https://www.npmjs.com/package/pprof) npm package
1015
- * - Python's [`py-spy`](https://github.com/benfred/py-spy)
1016
- * - Rust's [`pprof-rs`](https://github.com/tikv/pprof-rs)
1017
- * - Java/Kotlin's [`async-profiler`](https://github.com/async-profiler/async-profiler)
1018
- * - C/C++'s [`gperftools`](https://github.com/gperftools/gperftools) (via `pprof --proto`)
1019
- */
1020
- const pprofToMd = (data, options) => pprofToMdInternal(parsePprof(data), options);
1021
- const pprofToMdInternal = (pprof, options) => {
1022
- const normalizedOptions = normalizeProfileToMdOptions(options);
1023
- return formatPprof(summarizePprof(pprof, normalizedOptions), normalizedOptions);
1024
- };
1025
-
1026
- //#endregion
1027
- //#region src/formats/speedscope/format.ts
1028
- const formatSpeedscope = (profile, options) => formatProfile(profile, options);
1029
-
1030
- //#endregion
1031
- //#region src/helpers/json.ts
1032
- const parseJson = (data) => JSON.parse(data);
1033
-
1034
- //#endregion
1035
- //#region src/formats/speedscope/parse.ts
1036
- const parseSpeedscopeProfile = (data) => parseJson(data);
1037
-
1038
- //#endregion
1039
- //#region src/formats/speedscope/summarize.ts
1040
- const summarizeSpeedscopeProfile = (profile, options) => {
1041
- const nodes = profile.shared.frames.map((frame, id) => ({
1042
- ...frame,
1043
- id
1044
- }));
1045
- return profile.profiles.map((profile) => profile.type === `sampled` ? summarizeSampled(profile, nodes, options) : summarizeEvented(profile, nodes, options));
1046
- };
1047
- const summarizeSampled = (profile, nodes, options) => {
1048
- const profileBuilder = makeProfileBuilder(profile.unit, options);
1049
- for (let index = 0; index < profile.samples.length; index++) {
1050
- const weight = profile.weights[index];
1051
- if (weight <= 0) continue;
1052
- const sampleNodes = profile.samples[index].map((frameIndex) => nodes[frameIndex]).reverse();
1053
- if (sampleNodes.length === 0) continue;
1054
- profileBuilder.addSample({
1055
- values: [weight],
1056
- nodes: sampleNodes
1057
- });
1058
- }
1059
- return profileBuilder.build();
1060
- };
1061
- const summarizeEvented = (profile, nodes, options) => {
1062
- const builder = makeProfileBuilder(profile.unit, options);
1063
- const stack = [];
1064
- const emitTopSelfTime = (at) => {
1065
- if (stack.length === 0) return;
1066
- const top = stack.at(-1);
1067
- const selfTime = at - top.lastChildClosed;
1068
- if (selfTime <= 0) return;
1069
- builder.addSample({
1070
- values: [selfTime],
1071
- nodes: stack.map((entry) => entry.node).reverse()
1072
- });
1073
- top.lastChildClosed = at;
1074
- };
1075
- for (const event of profile.events) if (event.type === `O`) {
1076
- emitTopSelfTime(event.at);
1077
- stack.push({
1078
- node: nodes[event.frame],
1079
- lastChildClosed: event.at
1080
- });
1081
- } else {
1082
- emitTopSelfTime(event.at);
1083
- stack.pop();
1084
- if (stack.length > 0) stack.at(-1).lastChildClosed = event.at;
1085
- }
1086
- return builder.build();
1087
- };
1088
- const makeProfileBuilder = (unit, options) => new ProfileBuilder({
1089
- metrics: [determineMetric({
1090
- name: unit,
1091
- unit
1092
- })],
1093
- functionKey: (node) => node.id,
1094
- functionInput: (node) => ({
1095
- name: node.name,
1096
- location: node.file ? {
1097
- urlOrPath: node.file,
1098
- line: node.line,
1099
- column: node.col
1100
- } : void 0
1101
- })
1102
- }, options);
1103
-
1104
- //#endregion
1105
- //#region src/formats/speedscope/index.ts
1106
- const detectSpeedscopeProfile = (json) => {
1107
- if (typeof json !== `object` || json === null) return;
1108
- const object = json;
1109
- if (object.$schema !== `https://www.speedscope.app/file-format-schema.json` || !Array.isArray(object.profiles) || typeof object.shared !== `object` || object.shared === null) return;
1110
- return json;
1111
- };
1112
- /**
1113
- * Converts the given speedscope profile to Markdown.
1114
- *
1115
- * It is assumed that {@link data} is a valid speedscope JSON file. The behavior
1116
- * of this function is undefined for invalid profiles.
1117
- *
1118
- * Speedscope profiles can be generated by many tools, including:
1119
- * - [speedscope](https://www.speedscope.app) (drag and drop any supported profile)
1120
- * - [rbspy](https://rbspy.github.io) for Ruby
1121
- * - [py-spy](https://github.com/benfred/py-spy) for Python (`--format speedscope`)
1122
- * - [pprof-rs](https://github.com/tikv/pprof-rs) for Rust
1123
- * - [async-profiler](https://github.com/async-profiler/async-profiler) for Java/Kotlin (`-o speedscope`)
1124
- * - [phpspy](https://github.com/adsr/phpspy) for PHP (`--output-format=speedscope`)
1125
- */
1126
- const speedscopeProfileToMd = (data, options) => speedscopeProfileToMdInternal(parseSpeedscopeProfile(data), options);
1127
- const speedscopeProfileToMdInternal = (profile, options) => {
1128
- const normalizedOptions = normalizeProfileToMdOptions(options);
1129
- return summarizeSpeedscopeProfile(profile, normalizedOptions).map((profile) => formatSpeedscope(profile, normalizedOptions)).join(`\n\n`);
1130
- };
1131
-
1132
- //#endregion
1133
- //#region src/formats/v8/cpu-profile/format.ts
1134
- const formatV8CpuProfile = (profile, options) => formatProfile(profile, options);
1135
-
1136
- //#endregion
1137
- //#region src/formats/v8/cpu-profile/parse.ts
1138
- const parseV8CpuProfile = (data) => parseJson(data);
1139
-
1140
- //#endregion
1141
- //#region src/formats/v8/common.ts
1142
- const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
1143
- const callFrameFunctionInput = (callFrame) => {
1144
- const { functionName, url, lineNumber, columnNumber } = callFrame;
1145
- return {
1146
- name: functionName,
1147
- location: url ? {
1148
- urlOrPath: url,
1149
- line: lineNumber + 1,
1150
- column: columnNumber + 1
1151
- } : void 0
1152
- };
1153
- };
1154
-
1155
- //#endregion
1156
- //#region src/formats/v8/cpu-profile/summarize.ts
1157
- const summarizeV8CpuProfile = (profile, options) => {
1158
- const profileBuilder = new ProfileBuilder({
1159
- metrics: [MICROSECONDS],
1160
- functionKey: (node) => callFrameKey(node.callFrame),
1161
- functionInput: (node) => callFrameFunctionInput(node.callFrame)
1162
- }, options);
1163
- const idToIndex = [];
1164
- for (let index = 0; index < profile.nodes.length; index++) {
1165
- const node = profile.nodes[index];
1166
- idToIndex[node.id] = index;
1167
- node.id = index;
1168
- }
1169
- const indexToParentIndex = new Int32Array(profile.nodes.length).fill(-1);
1170
- for (const node of profile.nodes) if (node.children) for (const childId of node.children) {
1171
- const childIndex = idToIndex[childId];
1172
- if (childIndex === void 0) continue;
1173
- indexToParentIndex[childIndex] = node.id;
1174
- }
1175
- const indexToSelfTime = new Float64Array(profile.nodes.length);
1176
- for (let index = 0; index < profile.samples.length; index++) {
1177
- const nodeIndex = idToIndex[profile.samples[index]];
1178
- if (nodeIndex === void 0) continue;
1179
- const node = profile.nodes[nodeIndex];
1180
- const timeDelta = profile.timeDeltas[index];
1181
- indexToSelfTime[nodeIndex] += timeDelta;
1182
- const nodes = [];
1183
- let currentNode = node;
1184
- while (true) {
1185
- nodes.push(currentNode);
1186
- const parentIndex = indexToParentIndex[currentNode.id];
1187
- if (parentIndex === -1) break;
1188
- currentNode = profile.nodes[parentIndex];
1189
- }
1190
- profileBuilder.addSample({
1191
- values: [timeDelta],
1192
- nodes
1193
- });
1194
- }
1195
- for (const node of profile.nodes) {
1196
- if (!node.positionTicks) continue;
1197
- const selfTime = indexToSelfTime[node.id];
1198
- profileBuilder.addLineMetrics({
1199
- node,
1200
- lines: node.positionTicks.map(({ line, ticks }) => ({
1201
- line,
1202
- sampleCount: ticks,
1203
- values: [Math.round(selfTime * ticks / node.hitCount)]
1204
- }))
1205
- });
1206
- }
1207
- return profileBuilder.build();
1208
- };
1209
-
1210
- //#endregion
1211
- //#region src/formats/v8/cpu-profile/index.ts
1212
- const detectV8CpuProfile = (json) => {
1213
- if (typeof json !== `object` || json === null) return;
1214
- const object = json;
1215
- if (!Array.isArray(object.nodes) || !Array.isArray(object.timeDeltas)) return;
1216
- return json;
1217
- };
1218
- /**
1219
- * Converts the given V8 CPU profile to Markdown.
1220
- *
1221
- * It is assumed that {@link data} is a valid profile. The behavior of this
1222
- * function is undefined for invalid profiles.
1223
- *
1224
- * You can generate a V8 CPU profile in several ways:
1225
- * - [`node --cpu-prof`](https://nodejs.org/api/cli.html#cpu-prof)
1226
- * - [`deno run --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
1227
- * - [`bun --cpu-prof`](https://bun.com/docs/project/benchmarking#cpu-profiling)
1228
- * (NOTE: output was incorrect until
1229
- * [v1.3.13](https://bun.com/blog/bun-v1.3.13#node-js-compatibility-improvements))
1230
- * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1231
- * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1232
- * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1233
- * [Chrome DevTools](https://developer.chrome.com/docs/devtools/performance/nodejs)
1234
- * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/performance#record)
1235
- *
1236
- * Lower the sampling interval to capture more granular data.
1237
- */
1238
- const v8CpuProfileToMd = (data, options) => v8CpuProfileToMdInternal(parseV8CpuProfile(data), options);
1239
- const v8CpuProfileToMdInternal = (profile, options) => {
1240
- const normalizedOptions = normalizeProfileToMdOptions(options);
1241
- return formatV8CpuProfile(summarizeV8CpuProfile(profile, normalizedOptions), normalizedOptions);
1242
- };
1243
-
1244
- //#endregion
1245
- //#region src/formats/v8/heap-profile/format.ts
1246
- const formatV8HeapProfile = (profile, options) => formatProfile(profile, options);
1247
-
1248
- //#endregion
1249
- //#region src/formats/v8/heap-profile/parse.ts
1250
- const parseV8HeapProfile = (data) => parseJson(data);
1251
-
1252
- //#endregion
1253
- //#region src/formats/v8/heap-profile/summarize.ts
1254
- const summarizeV8HeapProfile = (profile, options) => {
1255
- const profileBuilder = new ProfileBuilder({
1256
- metrics: [BYTES],
1257
- functionKey: (node) => callFrameKey(node.callFrame),
1258
- functionInput: (node) => callFrameFunctionInput(node.callFrame)
1259
- }, options);
1260
- const flatNodes = [];
1261
- const idToIndex = [];
1262
- const indexToParentIndex = [];
1263
- const stack = [{
1264
- node: profile.head,
1265
- parentIndex: -1
1266
- }];
1267
- do {
1268
- const { node, parentIndex } = stack.pop();
1269
- const index = flatNodes.length;
1270
- idToIndex[node.id] = index;
1271
- node.id = index;
1272
- flatNodes.push(node);
1273
- indexToParentIndex.push(parentIndex);
1274
- for (const child of node.children) stack.push({
1275
- node: child,
1276
- parentIndex: index
1277
- });
1278
- } while (stack.length > 0);
1279
- for (const { size, nodeId } of profile.samples) {
1280
- const nodeIndex = idToIndex[nodeId];
1281
- if (nodeIndex === void 0) continue;
1282
- const nodes = [];
1283
- let currentIndex = nodeIndex;
1284
- while (true) {
1285
- nodes.push(flatNodes[currentIndex]);
1286
- const parentIndex = indexToParentIndex[currentIndex];
1287
- if (parentIndex === -1) break;
1288
- currentIndex = parentIndex;
1289
- }
1290
- profileBuilder.addSample({
1291
- values: [size],
1292
- nodes
1293
- });
1294
- }
1295
- return profileBuilder.build();
1296
- };
1297
-
1298
- //#endregion
1299
- //#region src/formats/v8/heap-profile/index.ts
1300
- const detectV8HeapProfile = (json) => {
1301
- if (typeof json !== `object` || json === null) return;
1302
- const object = json;
1303
- if (typeof object.head !== `object` || object.head === null || !Array.isArray(object.samples)) return;
1304
- return json;
1305
- };
1306
- /**
1307
- * Converts the given V8 sampling heap profile to Markdown.
1308
- *
1309
- * It is assumed that {@link data} is a valid profile. The behavior of this
1310
- * function is undefined for invalid profiles.
1311
- *
1312
- * You can generate a V8 heap profile in several ways:
1313
- * - [`node --heap-prof`](https://nodejs.org/api/cli.html#--heap-prof)
1314
- * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1315
- * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1316
- * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1317
- * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
1318
- * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
1319
- *
1320
- * Note that [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
1321
- * generates a heap _snapshot_ on exit, not a heap _profile_.
1322
- */
1323
- const v8HeapProfileToMd = (data, options) => v8HeapProfileToMdInternal(parseV8HeapProfile(data), options);
1324
- const v8HeapProfileToMdInternal = (profile, options) => {
1325
- const normalizedOptions = normalizeProfileToMdOptions(options);
1326
- return formatV8HeapProfile(summarizeV8HeapProfile(profile, normalizedOptions), normalizedOptions);
1327
- };
1328
-
1329
- //#endregion
1330
- //#region src/formats/v8/heap-snapshot/format.ts
1331
- const formatV8HeapSnapshot = (snapshot, options) => `${[
1332
- `# Heap snapshot`,
1333
- formatOverallSummary(snapshot),
1334
- formatLargestConstructors(snapshot, options),
1335
- formatLargestClosures(snapshot, options),
1336
- formatLargestStrings(snapshot, options)
1337
- ].filter(Boolean).join(`\n\n`)}\n`;
1338
- const formatOverallSummary = ({ totalSize, nodeCount, edgeCount, nodeCategoryToStats }) => {
1339
- const hottestObjectCategories = [...nodeCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
1340
- return [`Allocated ${formatBytes(totalSize)} across ${formatCount(nodeCount)} objects and ${formatCount(edgeCount)} references.`, formatTable([
1341
- `Category`,
1342
- {
1343
- content: `%`,
1344
- align: `right`
1345
- },
1346
- {
1347
- content: `Size`,
1348
- align: `right`
1349
- },
1350
- {
1351
- content: `Objects`,
1352
- align: `right`
1353
- }
1354
- ], hottestObjectCategories.map(([type, { size, nodeCount: objectCount }]) => [
1355
- type,
1356
- formatPercent(size / totalSize),
1357
- formatBytes(size),
1358
- formatCount(objectCount)
1359
- ]))].join(`\n\n`);
1360
- };
1361
- const formatLargestConstructors = (snapshot, options) => [
1362
- `## Largest constructors`,
1363
- formatLargestSelfSizeConstructors(snapshot, options),
1364
- formatLargestRetainedSizeConstructors(snapshot, options)
1365
- ].join(`\n\n`);
1366
- const formatLargestSelfSizeConstructors = (snapshot, options) => {
1367
- const { totalSize, constructors } = snapshot;
1368
- const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.selfSize);
1369
- const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1370
- return [
1371
- `### Self size`,
1372
- `Constructors ranked by bytes allocated for their instances, excluding objects kept reachable by them.`,
1373
- formatTable([
1374
- {
1375
- content: `%`,
1376
- align: `right`
1377
- },
1378
- {
1379
- content: `Size`,
1380
- align: `right`
1381
- },
1382
- {
1383
- content: `Instances`,
1384
- align: `right`
1385
- },
1386
- `Constructor`,
1387
- `Location`
1388
- ], largestConstructors.map((constructor) => [
1389
- formatPercent(constructor.selfSize / totalSize),
1390
- formatBytes(constructor.selfSize),
1391
- formatCount(constructor.instances.length),
1392
- inlineCode(constructor.name),
1393
- formatProfileLocation(constructor.location, options)
1394
- ])),
1395
- ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's self size.`] : [],
1396
- ...largestInstanceSections
1397
- ].join(`\n\n`);
1398
- };
1399
- const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
1400
- const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.selfSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.selfSize - group1.selfSize);
1401
- if (largestInstanceGroups.length === 0) return;
1402
- return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
1403
- {
1404
- content: `%`,
1405
- align: `right`
1406
- },
1407
- {
1408
- content: `Size`,
1409
- align: `right`
1410
- },
1411
- {
1412
- content: `Instances`,
1413
- align: `right`
1414
- },
1415
- `Path`
1416
- ], largestInstanceGroups.map((group) => [
1417
- formatPercent(group.selfSize / constructor.selfSize),
1418
- formatBytes(group.selfSize),
1419
- formatCount(group.instanceCount),
1420
- inlineCode(group.retainerPath)
1421
- ]))].join(`\n\n`);
1422
- };
1423
- const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1424
- const { totalSize, constructors } = snapshot;
1425
- const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.retainedSize);
1426
- const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1427
- return [
1428
- `### Retained size`,
1429
- `Constructors ranked by bytes allocated for their instances and all objects that would be freed if their instances were garbage collected.`,
1430
- formatTable([
1431
- {
1432
- content: `%`,
1433
- align: `right`
1434
- },
1435
- {
1436
- content: `Size`,
1437
- align: `right`
1438
- },
1439
- {
1440
- content: `Instances`,
1441
- align: `right`
1442
- },
1443
- `Constructor`,
1444
- `Location`
1445
- ], largestConstructors.map((constructor) => [
1446
- formatPercent(constructor.retainedSize / totalSize),
1447
- formatBytes(constructor.retainedSize),
1448
- formatCount(constructor.instances.length),
1449
- inlineCode(constructor.name),
1450
- formatProfileLocation(constructor.location, options)
1451
- ])),
1452
- ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's retained size.`] : [],
1453
- ...largestInstanceSections
1454
- ].join(`\n\n`);
1455
- };
1456
- const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
1457
- const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.retainedSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.retainedSize - group1.retainedSize);
1458
- if (largestInstanceGroups.length === 0) return;
1459
- return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
1460
- {
1461
- content: `%`,
1462
- align: `right`
1463
- },
1464
- {
1465
- content: `Size`,
1466
- align: `right`
1467
- },
1468
- {
1469
- content: `Instances`,
1470
- align: `right`
1471
- },
1472
- `Path`
1473
- ], largestInstanceGroups.map((group) => [
1474
- formatPercent(group.retainedSize / constructor.retainedSize),
1475
- formatBytes(group.retainedSize),
1476
- formatCount(group.instanceCount),
1477
- inlineCode(group.retainerPath)
1478
- ]))].join(`\n\n`);
1479
- };
1480
- const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
1481
- const heap = new MaxHeap(instances, sizeOf);
1482
- const pathToGroup = /* @__PURE__ */ new Map();
1483
- while (heap.length > 0 && pathToGroup.size < topN) {
1484
- const instance = heap.pop();
1485
- const retainerPath = retainerPathOf(instance.id);
1486
- let group = pathToGroup.get(retainerPath);
1487
- if (!group) {
1488
- group = {
1489
- retainerPath,
1490
- instanceCount: 0,
1491
- selfSize: 0,
1492
- retainedSize: 0
1493
- };
1494
- pathToGroup.set(retainerPath, group);
1495
- }
1496
- group.instanceCount++;
1497
- group.selfSize += instance.selfSize;
1498
- group.retainedSize += instance.retainedSize;
1499
- }
1500
- return [...pathToGroup.values()];
1501
- };
1502
- const formatLargestClosures = (snapshot, options) => {
1503
- const { totalSize, closures, retainerPathOf } = snapshot;
1504
- const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
1505
- ...closure,
1506
- id: closure.largestInstanceId
1507
- })), options.topN, (closure) => closure.retainedSize);
1508
- const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
1509
- return [
1510
- `## Largest closures`,
1511
- `Closures ranked by bytes that would be freed if the closure were garbage collected.`,
1512
- formatTable([
1513
- {
1514
- content: `%`,
1515
- align: `right`
1516
- },
1517
- {
1518
- content: `Retained`,
1519
- align: `right`
1520
- },
1521
- {
1522
- content: `Instances`,
1523
- align: `right`
1524
- },
1525
- {
1526
- content: `Paths`,
1527
- align: `right`
1528
- },
1529
- `Name`,
1530
- `Location`,
1531
- `Example path`
1532
- ], largestClosures.map((closure) => [
1533
- formatPercent(closure.retainedSize / totalSize),
1534
- formatBytes(closure.retainedSize),
1535
- formatCount(closure.instanceIds.length),
1536
- formatCount(new Set(closure.instanceIds.map(retainerPathOf)).size),
1537
- inlineCode(closure.name),
1538
- formatProfileLocation(closure.location, options),
1539
- inlineCode(retainerPathOf(closure.largestInstanceId))
1540
- ])),
1541
- ...retainedSections.length > 0 ? [`### Retained`, `Objects ranked by contribution to each closure's retained size.`] : [],
1542
- ...retainedSections
1543
- ].join(`\n\n`);
1544
- };
1545
- const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, options) => {
1546
- const instanceIdToSeen = new DynamicTypedArray(new Uint8Array(256));
1547
- const allRetainedNodes = [];
1548
- for (const instanceId of closure.instanceIds) for (const node of retainedNodesOf(instanceId)) {
1549
- const seen = instanceIdToSeen.ensureCapacity(node.id + 1);
1550
- if (seen[node.id]) continue;
1551
- seen[node.id] = 1;
1552
- if (options.includeEntry(node)) allRetainedNodes.push(node);
1553
- }
1554
- const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node) => node.selfSize);
1555
- if (retainedNodes.length === 0) return;
1556
- return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
1557
- {
1558
- content: `%`,
1559
- align: `right`
1560
- },
1561
- {
1562
- content: `Self`,
1563
- align: `right`
1564
- },
1565
- `Name`,
1566
- `Path`
1567
- ], retainedNodes.map((node) => [
1568
- formatPercent(node.selfSize / closure.retainedSize),
1569
- formatBytes(node.selfSize),
1570
- inlineCode(node.name || `(unknown)`),
1571
- inlineCode(retainerPathOf(node.id))
1572
- ]))].join(`\n\n`);
1573
- };
1574
- const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) => {
1575
- return [
1576
- `## Largest strings`,
1577
- `Strings ranked by bytes allocated for them.`,
1578
- formatTable([
1579
- {
1580
- content: `%`,
1581
- align: `right`
1582
- },
1583
- {
1584
- content: `Size`,
1585
- align: `right`
1586
- },
1587
- `Value`,
1588
- `Path`
1589
- ], selectTopN(strings, options.topN, (string) => string.selfSize).map((string) => [
1590
- formatPercent(string.selfSize / totalSize),
1591
- formatBytes(string.selfSize),
1592
- inlineCode(string.name),
1593
- inlineCode(retainerPathOf(string.id))
1594
- ]))
1595
- ].join(`\n\n`);
1596
- };
1597
-
1598
- //#endregion
1599
- //#region src/formats/v8/heap-snapshot/parse.ts
1600
- const parseV8HeapSnapshot = (data) => parseJson(data);
1601
-
1602
- //#endregion
1603
- //#region src/formats/v8/heap-snapshot/summarize.ts
1604
- const summarizeV8HeapSnapshot = (snapshot, options) => {
1605
- const { snapshot: { meta, node_count: nodeCount, edge_count: edgeCount }, nodes } = snapshot;
1606
- const [nodeTypes] = meta.node_types;
1607
- const fieldLayout = computeFieldLayout(meta);
1608
- const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
1609
- const nodeOrdinalToLocation = computeNodeOrdinalToLocation(snapshot, nodeAdjacencyGraph, fieldLayout);
1610
- const immediateDominatorGraph = computeImmediateDominatorGraph(snapshot, nodeAdjacencyGraph);
1611
- const nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(snapshot, immediateDominatorGraph, fieldLayout);
1612
- let totalSize = 0;
1613
- const nodeCategoryToStats = /* @__PURE__ */ new Map();
1614
- const constructors = [];
1615
- const nameToConstructorIndex = /* @__PURE__ */ new Map();
1616
- const nodeOrdinalToConstructorIndex = new Int32Array(nodeCount).fill(-1);
1617
- const closures = [];
1618
- const keyToClosureIndex = /* @__PURE__ */ new Map();
1619
- const nodeOrdinalToClosureIndex = new Int32Array(nodeCount).fill(-1);
1620
- const strings = [];
1621
- for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1622
- const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
1623
- const selfSize = nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset];
1624
- totalSize += selfSize;
1625
- const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1626
- const category = nodeTypes[nodeType];
1627
- let categoryStats = nodeCategoryToStats.get(category);
1628
- if (!categoryStats) {
1629
- categoryStats = {
1630
- size: 0,
1631
- nodeCount: 0
1632
- };
1633
- nodeCategoryToStats.set(category, categoryStats);
1634
- }
1635
- categoryStats.size += selfSize;
1636
- categoryStats.nodeCount++;
1637
- switch (nodeType) {
1638
- case fieldLayout.nodeTypeObject:
1639
- case fieldLayout.nodeTypeNative: {
1640
- const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
1641
- let constructorIndex = nameToConstructorIndex.get(name);
1642
- let constructor;
1643
- if (constructorIndex === void 0) {
1644
- constructorIndex = constructors.length;
1645
- constructor = {
1646
- id: nodeOrdinal,
1647
- name,
1648
- location: void 0,
1649
- selfSize: 0,
1650
- retainedSize: 0,
1651
- instances: []
1652
- };
1653
- constructors.push(constructor);
1654
- nameToConstructorIndex.set(name, constructorIndex);
1655
- } else constructor = constructors[constructorIndex];
1656
- constructor.selfSize += selfSize;
1657
- constructor.location ??= nodeOrdinalToLocation[nodeOrdinal];
1658
- constructor.instances.push({
1659
- id: nodeOrdinal,
1660
- name: constructor.name,
1661
- selfSize,
1662
- retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal],
1663
- location: constructor.location
1664
- });
1665
- nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
1666
- break;
1667
- }
1668
- case fieldLayout.nodeTypeClosure: {
1669
- const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
1670
- const location = nodeOrdinalToLocation[nodeOrdinal];
1671
- const key = `${name}|${location ? formatProfileLocation(location, options) : ``}`;
1672
- const retainedSize = nodeOrdinalToRetainedSize[nodeOrdinal];
1673
- let closureIndex = keyToClosureIndex.get(key);
1674
- if (closureIndex === void 0) {
1675
- closureIndex = closures.length;
1676
- closures.push({
1677
- name,
1678
- location,
1679
- retainedSize: 0,
1680
- largestInstanceId: nodeOrdinal,
1681
- instanceIds: []
1682
- });
1683
- keyToClosureIndex.set(key, closureIndex);
1684
- }
1685
- const closure = closures[closureIndex];
1686
- closure.instanceIds.push(nodeOrdinal);
1687
- if (retainedSize > nodeOrdinalToRetainedSize[closure.largestInstanceId]) closure.largestInstanceId = nodeOrdinal;
1688
- nodeOrdinalToClosureIndex[nodeOrdinal] = closureIndex;
1689
- break;
1690
- }
1691
- case fieldLayout.nodeTypeString:
1692
- case fieldLayout.nodeTypeSlicedString:
1693
- case fieldLayout.nodeTypeConcatenatedString:
1694
- strings.push({
1695
- id: nodeOrdinal,
1696
- name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
1697
- selfSize,
1698
- retainedSize: selfSize
1699
- });
1700
- break;
1701
- }
1702
- }
1703
- attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToConstructorIndex, constructors);
1704
- attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToClosureIndex, closures);
1705
- return {
1706
- totalSize,
1707
- nodeCount,
1708
- edgeCount,
1709
- nodeCategoryToStats,
1710
- constructors,
1711
- closures,
1712
- strings,
1713
- retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeOrdinalToLocation, immediateDominatorGraph, fieldLayout, options),
1714
- retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, immediateDominatorGraph, fieldLayout, options)
1715
- };
1716
- };
1717
- const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes, edges }, fieldLayout) => {
1718
- const ordinalToSuccessorCount = new Int32Array(nodeCount);
1719
- const ordinalToPredecessorCount = new Int32Array(nodeCount);
1720
- let nodeEdgesStartIndex = 0;
1721
- for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1722
- const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
1723
- for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
1724
- const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
1725
- if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
1726
- const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
1727
- ordinalToSuccessorCount[nodeOrdinal]++;
1728
- ordinalToPredecessorCount[successorOrdinal]++;
1729
- }
1730
- nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
1731
- }
1732
- const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
1733
- const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
1734
- for (let i = 0; i < nodeCount; i++) {
1735
- ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
1736
- ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
1737
- }
1738
- const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
1739
- const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
1740
- const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
1741
- const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
1742
- const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
1743
- ordinalToSuccessorCount.fill(0);
1744
- ordinalToPredecessorCount.fill(0);
1745
- nodeEdgesStartIndex = 0;
1746
- for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1747
- const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
1748
- for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
1749
- const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
1750
- if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
1751
- const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
1752
- const successorOffset = ordinalToSuccessorStartOffset[nodeOrdinal] + ordinalToSuccessorCount[nodeOrdinal];
1753
- offsetToSuccessorOrdinal[successorOffset] = successorOrdinal;
1754
- offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
1755
- ordinalToSuccessorCount[nodeOrdinal]++;
1756
- const predecessorOffset = ordinalToPredecessorStartOffset[successorOrdinal] + ordinalToPredecessorCount[successorOrdinal];
1757
- offsetToPredecessorOrdinal[predecessorOffset] = nodeOrdinal;
1758
- offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
1759
- ordinalToPredecessorCount[successorOrdinal]++;
1760
- }
1761
- nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
1762
- }
1763
- return {
1764
- ordinalToSuccessorStartOffset,
1765
- offsetToSuccessorOrdinal,
1766
- offsetToSuccessorEdgeIndex,
1767
- ordinalToPredecessorStartOffset,
1768
- offsetToPredecessorOrdinal,
1769
- offsetToPredecessorEdgeIndex
1770
- };
1771
- };
1772
- const computeNodeOrdinalToLocation = ({ snapshot: { node_count: nodeCount }, nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
1773
- const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
1774
- const nodeOrdinal = nodeIndex / nodeFieldCount;
1775
- const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
1776
- const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
1777
- for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
1778
- const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
1779
- if (strings[edges[edgeIndex + edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + edgeToNodeOffset];
1780
- }
1781
- };
1782
- const scriptIdToFileLocation = /* @__PURE__ */ new Map();
1783
- for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1784
- const scriptId = locations[locationIndex + locationScriptIdOffset];
1785
- if (scriptIdToFileLocation.has(scriptId)) continue;
1786
- const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
1787
- if (nodes[nodeIndex + nodeTypeOffset] !== nodeTypeClosure) continue;
1788
- const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
1789
- if (sharedNodeIndex === void 0) continue;
1790
- const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
1791
- if (scriptNodeIndex === void 0) continue;
1792
- const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
1793
- if (locationNodeIndex === void 0) continue;
1794
- const location = strings[nodes[locationNodeIndex + nodeNameOffset]];
1795
- if (!location) continue;
1796
- scriptIdToFileLocation.set(scriptId, location);
1797
- }
1798
- const nodeOrdinalToLocation = Array.from({ length: nodeCount });
1799
- const fileLocationToUrl = /* @__PURE__ */ new Map();
1800
- for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1801
- const scriptId = locations[locationIndex + locationScriptIdOffset];
1802
- const fileLocation = scriptIdToFileLocation.get(scriptId);
1803
- if (!fileLocation) continue;
1804
- let url = fileLocationToUrl.get(fileLocation);
1805
- if (url === void 0) {
1806
- url = makeProfileLocation({ urlOrPath: fileLocation })?.url ?? null;
1807
- fileLocationToUrl.set(fileLocation, url);
1808
- }
1809
- if (!url) continue;
1810
- const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
1811
- const line = locations[locationIndex + locationLineOffset];
1812
- const column = locations[locationIndex + locationColumnOffset];
1813
- nodeOrdinalToLocation[nodeIndex / nodeFieldCount] = {
1814
- url,
1815
- line: line + 1,
1816
- column: column + 1
1817
- };
1818
- }
1819
- return nodeOrdinalToLocation;
1820
- };
1821
- /**
1822
- * Computes the immediate dominators of every node.
1823
- *
1824
- * Weak edges are excluded because they don't keep nodes alive.
1825
- *
1826
- * Uses the Lengauer-Tarjan dominator tree algorithm.
1827
- *
1828
- * @see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
1829
- * @see https://www.cs.princeton.edu/courses/archive/fall03/cs528/handouts/a%20fast%20algorithm%20for%20finding.pdf
1830
- */
1831
- const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessorStartOffset, offsetToSuccessorOrdinal, ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal }) => {
1832
- const { snapshot: { node_count: nodeCount } } = snapshot;
1833
- const ordinalToImmediateDominatorOrdinal = new Int32Array(nodeCount).fill(-1);
1834
- const dfsIndexToOrdinal = new Int32Array(nodeCount);
1835
- const ordinalToParentOrdinal = new Int32Array(nodeCount).fill(-1);
1836
- const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
1837
- const ordinalToSemidominatorDfsIndex = new Int32Array(nodeCount);
1838
- ordinalToDfsIndex[0] = 0;
1839
- dfsIndexToOrdinal[0] = 0;
1840
- const dfsStackOrdinals = new Int32Array(nodeCount);
1841
- const dfsStackOffsets = new Int32Array(nodeCount);
1842
- dfsStackOffsets[0] = ordinalToSuccessorStartOffset[0];
1843
- let dfsIndex = 1;
1844
- let dfsStackSize = 1;
1845
- do {
1846
- const topOffset = dfsStackSize - 1;
1847
- const nodeOrdinal = dfsStackOrdinals[topOffset];
1848
- const nextOffset = dfsStackOffsets[topOffset];
1849
- if (nextOffset === ordinalToSuccessorStartOffset[nodeOrdinal + 1]) {
1850
- dfsStackSize--;
1851
- continue;
1852
- }
1853
- const childOrdinal = offsetToSuccessorOrdinal[nextOffset];
1854
- dfsStackOffsets[topOffset]++;
1855
- if (ordinalToDfsIndex[childOrdinal] !== -1) continue;
1856
- ordinalToParentOrdinal[childOrdinal] = nodeOrdinal;
1857
- ordinalToDfsIndex[childOrdinal] = dfsIndex;
1858
- ordinalToSemidominatorDfsIndex[childOrdinal] = dfsIndex;
1859
- dfsIndexToOrdinal[dfsIndex] = childOrdinal;
1860
- dfsIndex++;
1861
- dfsStackOrdinals[dfsStackSize] = childOrdinal;
1862
- dfsStackOffsets[dfsStackSize] = ordinalToSuccessorStartOffset[childOrdinal];
1863
- dfsStackSize++;
1864
- } while (dfsStackSize > 0);
1865
- const reachableCount = dfsIndex;
1866
- const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
1867
- const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
1868
- const ordinalToMinSemiAncestorOrdinal = new Int32Array(nodeCount);
1869
- for (let i = 0; i < nodeCount; i++) ordinalToMinSemiAncestorOrdinal[i] = i;
1870
- const compressAncestorPath = (startNodeOrdinal) => {
1871
- let pathLength = 0;
1872
- let nodeOrdinal = startNodeOrdinal;
1873
- while (ordinalToForestAncestorOrdinal[nodeOrdinal] !== -1 && ordinalToForestAncestorOrdinal[ordinalToForestAncestorOrdinal[nodeOrdinal]] !== -1) {
1874
- ancestorNodeOrdinalPath[pathLength++] = nodeOrdinal;
1875
- nodeOrdinal = ordinalToForestAncestorOrdinal[nodeOrdinal];
1876
- }
1877
- for (let pathIndex = pathLength - 1; pathIndex >= 0; pathIndex--) {
1878
- const pathNodeOrdinal = ancestorNodeOrdinalPath[pathIndex];
1879
- const ancestorOrdinal = ordinalToForestAncestorOrdinal[pathNodeOrdinal];
1880
- if (ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[ancestorOrdinal]] < ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal]]) ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal] = ordinalToMinSemiAncestorOrdinal[ancestorOrdinal];
1881
- ordinalToForestAncestorOrdinal[pathNodeOrdinal] = ordinalToForestAncestorOrdinal[ancestorOrdinal];
1882
- }
1883
- };
1884
- const minSemiAncestorOrdinal = (nodeOrdinal) => {
1885
- if (ordinalToForestAncestorOrdinal[nodeOrdinal] === -1) return nodeOrdinal;
1886
- compressAncestorPath(nodeOrdinal);
1887
- return ordinalToMinSemiAncestorOrdinal[nodeOrdinal];
1888
- };
1889
- const pendingHeadOrdinals = new Int32Array(nodeCount).fill(-1);
1890
- const pendingNextOrdinals = new Int32Array(nodeCount).fill(-1);
1891
- for (let dfsIndex = reachableCount - 1; dfsIndex >= 1; dfsIndex--) {
1892
- const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1893
- const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
1894
- const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
1895
- for (let predecessorOffset = predecessorStartOffset; predecessorOffset < predecessorEndOffset; predecessorOffset++) {
1896
- const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
1897
- if (ordinalToDfsIndex[predecessorOrdinal] === -1) continue;
1898
- const minAncestorOrdinal = minSemiAncestorOrdinal(predecessorOrdinal);
1899
- if (ordinalToSemidominatorDfsIndex[minAncestorOrdinal] < ordinalToSemidominatorDfsIndex[nodeOrdinal]) ordinalToSemidominatorDfsIndex[nodeOrdinal] = ordinalToSemidominatorDfsIndex[minAncestorOrdinal];
1900
- }
1901
- const semiBucketOrdinal = dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]];
1902
- pendingNextOrdinals[nodeOrdinal] = pendingHeadOrdinals[semiBucketOrdinal];
1903
- pendingHeadOrdinals[semiBucketOrdinal] = nodeOrdinal;
1904
- ordinalToForestAncestorOrdinal[nodeOrdinal] = ordinalToParentOrdinal[nodeOrdinal];
1905
- const parentOrdinal = ordinalToParentOrdinal[nodeOrdinal];
1906
- let pendingOrdinal = pendingHeadOrdinals[parentOrdinal];
1907
- pendingHeadOrdinals[parentOrdinal] = -1;
1908
- while (pendingOrdinal !== -1) {
1909
- const nextPending = pendingNextOrdinals[pendingOrdinal];
1910
- const ancestorOrdinal = minSemiAncestorOrdinal(pendingOrdinal);
1911
- ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : parentOrdinal;
1912
- pendingOrdinal = nextPending;
1913
- }
1914
- }
1915
- for (let dfsIndex = 1; dfsIndex < reachableCount; dfsIndex++) {
1916
- const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1917
- if (ordinalToImmediateDominatorOrdinal[nodeOrdinal] !== dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]) ordinalToImmediateDominatorOrdinal[nodeOrdinal] = ordinalToImmediateDominatorOrdinal[ordinalToImmediateDominatorOrdinal[nodeOrdinal]];
1918
- }
1919
- ordinalToImmediateDominatorOrdinal[0] = 0;
1920
- const dominatorOrdinalToDominateeCount = new Int32Array(nodeCount);
1921
- for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
1922
- const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1923
- if (dominatorOrdinal !== -1) dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
1924
- }
1925
- const immediateDominateeOrdinalToStartOffset = new Int32Array(nodeCount + 1);
1926
- for (let offset = 0; offset < nodeCount; offset++) immediateDominateeOrdinalToStartOffset[offset + 1] = immediateDominateeOrdinalToStartOffset[offset] + dominatorOrdinalToDominateeCount[offset];
1927
- const offsetToImmediateDominateeOrdinal = new Int32Array(immediateDominateeOrdinalToStartOffset[nodeCount]);
1928
- dominatorOrdinalToDominateeCount.fill(0);
1929
- for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
1930
- const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1931
- if (dominatorOrdinal !== -1) {
1932
- offsetToImmediateDominateeOrdinal[immediateDominateeOrdinalToStartOffset[dominatorOrdinal] + dominatorOrdinalToDominateeCount[dominatorOrdinal]] = nodeOrdinal;
1933
- dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
1934
- }
1935
- }
1936
- return {
1937
- dfsIndexToOrdinal,
1938
- ordinalToImmediateDominatorOrdinal,
1939
- immediateDominateeOrdinalToStartOffset,
1940
- offsetToImmediateDominateeOrdinal
1941
- };
1942
- };
1943
- const computeNodeOrdinalToRetainedSize = ({ nodes }, { dfsIndexToOrdinal, ordinalToImmediateDominatorOrdinal }, { nodeFieldCount, nodeSelfSizeOffset }) => {
1944
- const nodeOrdinalToRetainedSize = new Float64Array(ordinalToImmediateDominatorOrdinal.length);
1945
- for (let nodeOrdinal = 0; nodeOrdinal < nodeOrdinalToRetainedSize.length; nodeOrdinal++) nodeOrdinalToRetainedSize[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeSelfSizeOffset];
1946
- for (let dfsIndex = dfsIndexToOrdinal.length - 1; dfsIndex >= 1; dfsIndex--) {
1947
- const dominateeOrdinal = dfsIndexToOrdinal[dfsIndex];
1948
- nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominateeOrdinal]] += nodeOrdinalToRetainedSize[dominateeOrdinal];
1949
- }
1950
- return nodeOrdinalToRetainedSize;
1951
- };
1952
- const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, nodeOrdinalToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout, options) => {
1953
- const { nodes } = snapshot;
1954
- const hops = [];
1955
- while (true) {
1956
- const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
1957
- const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
1958
- if (predecessorStartOffset === predecessorEndOffset) break;
1959
- const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1960
- let predecessorOffset = -1;
1961
- for (let offset = predecessorStartOffset; offset < predecessorEndOffset; offset++) if (offsetToPredecessorOrdinal[offset] === dominatorOrdinal) {
1962
- predecessorOffset = offset;
1963
- break;
1964
- }
1965
- if (predecessorOffset === -1) {
1966
- nodeOrdinal = dominatorOrdinal;
1967
- continue;
1968
- }
1969
- const edgeIndex = offsetToPredecessorEdgeIndex[predecessorOffset];
1970
- const edgeLabel = formatEdgeLabel(edgeIndex, snapshot, fieldLayout, options);
1971
- const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
1972
- const retainerIndex = predecessorOrdinal * fieldLayout.nodeFieldCount;
1973
- const retainerType = nodes[retainerIndex + fieldLayout.nodeTypeOffset];
1974
- const retainerLabel = formatNodeLabel(retainerIndex, snapshot, fieldLayout, options);
1975
- const retainerLocation = nodeOrdinalToLocation[predecessorOrdinal];
1976
- hops.push({
1977
- label: `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${formatProfileLocation(retainerLocation, options)})` : ``}`,
1978
- internal: isInternalNodeType(retainerType, fieldLayout)
1979
- });
1980
- nodeOrdinal = predecessorOrdinal;
1981
- }
1982
- while (hops.at(-1)?.internal) hops.pop();
1983
- if (hops.length === 0) return `(GC root)`;
1984
- return hops.map((hop) => hop.label).join(` ← `);
1985
- };
1986
- const computeRetainedNodes = (nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, fieldLayout, options) => {
1987
- const { nodes } = snapshot;
1988
- const retainedNodes = [];
1989
- const dominateeOrdinals = [];
1990
- const childStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
1991
- const childEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
1992
- for (let offset = childStartOffset; offset < childEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
1993
- while (dominateeOrdinals.length > 0) {
1994
- const nodeOrdinal = dominateeOrdinals.pop();
1995
- const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
1996
- const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1997
- if (!isInternalNodeType(nodeType, fieldLayout)) retainedNodes.push({
1998
- id: nodeOrdinal,
1999
- name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
2000
- selfSize: nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset],
2001
- retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal]
2002
- });
2003
- const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
2004
- const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
2005
- for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
2006
- }
2007
- return retainedNodes;
2008
- };
2009
- const isInternalNodeType = (nodeType, fieldLayout) => nodeType === fieldLayout.nodeTypeHidden || nodeType === fieldLayout.nodeTypeSynthetic;
2010
- const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) => {
2011
- const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
2012
- const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
2013
- if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
2014
- const rawEdgeName = strings[edgeNameOrIndex];
2015
- const edgeLocation = makeProfileLocation({ urlOrPath: rawEdgeName });
2016
- return `.${edgeLocation ? formatProfileLocation(edgeLocation, options) : rawEdgeName}`;
2017
- };
2018
- const formatNodeLabel = (nodeIndex, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, strings }, fieldLayout, options) => {
2019
- const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
2020
- switch (nodeType) {
2021
- case fieldLayout.nodeTypeString:
2022
- case fieldLayout.nodeTypeSlicedString:
2023
- case fieldLayout.nodeTypeConcatenatedString: {
2024
- const string = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]];
2025
- return formatString(string);
2026
- }
2027
- case fieldLayout.nodeTypeClosure: return strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || `(anonymous)`;
2028
- default: {
2029
- const rawNodeName = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || nodeTypes[nodeType];
2030
- const nodeLocation = makeProfileLocation({ urlOrPath: rawNodeName });
2031
- return nodeLocation ? formatProfileLocation(nodeLocation, options) : rawNodeName;
2032
- }
2033
- }
2034
- };
2035
- const formatString = (string) => {
2036
- if (string.length > MAX_STRING_LENGTH) string = `${string.slice(0, MAX_STRING_LENGTH - 1)}…`;
2037
- return string.replaceAll(`\n`, `\\n`);
2038
- };
2039
- const MAX_STRING_LENGTH = 50;
2040
- /**
2041
- * Attributes retained sizes to groups of nodes without double-counting.
2042
- *
2043
- * Summing per-node retained sizes across all instances of a group over-counts
2044
- * when one instance dominates another from the same group (the dominated node's
2045
- * memory is already included in the dominator's retained size).
2046
- *
2047
- * This function correctly attributes by doing a DFS of the dominator tree and
2048
- * only crediting the outermost instance of each group on any root-to-leaf path.
2049
- * Inner instances are entirely contained within the outer one's retained set,
2050
- * so they add nothing.
2051
- */
2052
- const attributeGroupRetainedSizes = (nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToSummarizedNodeIndex, summarizedNodes) => {
2053
- const nodeCount = nodeOrdinalToRetainedSize.length;
2054
- const groupPathDepth = new Int32Array(summarizedNodes.length);
2055
- const stack = new Int32Array(nodeCount * 2 + 1);
2056
- stack[0] = 0;
2057
- let topOffset = 1;
2058
- do {
2059
- const encodedNodeOrdinal = stack[--topOffset];
2060
- if (encodedNodeOrdinal < 0) {
2061
- const constructorIndex = nodeOrdinalToSummarizedNodeIndex[~encodedNodeOrdinal];
2062
- if (constructorIndex !== -1) groupPathDepth[constructorIndex] = groupPathDepth[constructorIndex] - 1;
2063
- continue;
2064
- }
2065
- const nodeOrdinal = encodedNodeOrdinal;
2066
- const summarizedNodeIndex = nodeOrdinalToSummarizedNodeIndex[nodeOrdinal];
2067
- if (summarizedNodeIndex !== -1) {
2068
- const depth = groupPathDepth[summarizedNodeIndex];
2069
- if (depth === 0) summarizedNodes[summarizedNodeIndex].retainedSize += nodeOrdinalToRetainedSize[nodeOrdinal];
2070
- groupPathDepth[summarizedNodeIndex] = depth + 1;
2071
- stack[topOffset++] = ~nodeOrdinal;
2072
- }
2073
- const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
2074
- const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
2075
- for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) stack[topOffset++] = offsetToImmediateDominateeOrdinal[offset];
2076
- } while (topOffset > 0);
2077
- };
2078
- const computeFieldLayout = (meta) => {
2079
- const { node_fields: nodeFields, node_types: [nodeTypes], edge_fields: edgeFields, edge_types: [edgeTypes], location_fields: locationFields } = meta;
2080
- const nodeFieldToIndex = valueToIndex(nodeFields);
2081
- const nodeTypeToIndex = valueToIndex(nodeTypes);
2082
- const edgeFieldToIndex = valueToIndex(edgeFields);
2083
- const locationFieldToIndex = valueToIndex(locationFields);
2084
- const edgeTypeToIndex = valueToIndex(edgeTypes);
2085
- return {
2086
- nodeTypeOffset: nodeFieldToIndex.get(`type`),
2087
- nodeNameOffset: nodeFieldToIndex.get(`name`),
2088
- nodeSelfSizeOffset: nodeFieldToIndex.get(`self_size`),
2089
- nodeEdgeCountOffset: nodeFieldToIndex.get(`edge_count`),
2090
- nodeDetachednessOffset: nodeFieldToIndex.get(`detachedness`),
2091
- nodeFieldCount: nodeFields.length,
2092
- edgeTypeOffset: edgeFieldToIndex.get(`type`),
2093
- edgeNameOrIndexOffset: edgeFieldToIndex.get(`name_or_index`),
2094
- edgeToNodeOffset: edgeFieldToIndex.get(`to_node`),
2095
- edgeFieldCount: edgeFields.length,
2096
- locationObjectIndexOffset: locationFieldToIndex.get(`object_index`),
2097
- locationScriptIdOffset: locationFieldToIndex.get(`script_id`),
2098
- locationLineOffset: locationFieldToIndex.get(`line`),
2099
- locationColumnOffset: locationFieldToIndex.get(`column`),
2100
- locationFieldCount: locationFields.length,
2101
- nodeTypeHidden: nodeTypeToIndex.get(`hidden`),
2102
- nodeTypeArray: nodeTypeToIndex.get(`array`),
2103
- nodeTypeString: nodeTypeToIndex.get(`string`),
2104
- nodeTypeObject: nodeTypeToIndex.get(`object`),
2105
- nodeTypeCode: nodeTypeToIndex.get(`code`),
2106
- nodeTypeClosure: nodeTypeToIndex.get(`closure`),
2107
- nodeTypeRegexp: nodeTypeToIndex.get(`regexp`),
2108
- nodeTypeNumber: nodeTypeToIndex.get(`number`),
2109
- nodeTypeNative: nodeTypeToIndex.get(`native`),
2110
- nodeTypeSynthetic: nodeTypeToIndex.get(`synthetic`),
2111
- nodeTypeConcatenatedString: nodeTypeToIndex.get(`concatenated string`),
2112
- nodeTypeSlicedString: nodeTypeToIndex.get(`sliced string`),
2113
- nodeTypeSymbol: nodeTypeToIndex.get(`symbol`),
2114
- nodeTypeBigint: nodeTypeToIndex.get(`bigint`),
2115
- nodeTypeObjectShape: nodeTypeToIndex.get(`object shape`),
2116
- edgeTypeElement: edgeTypeToIndex.get(`element`),
2117
- edgeTypeInternal: edgeTypeToIndex.get(`internal`),
2118
- edgeTypeWeak: edgeTypeToIndex.get(`weak`)
2119
- };
2120
- };
2121
- const valueToIndex = (values) => new Map(values.map((value, index) => [value, index]));
2122
-
2123
- //#endregion
2124
- //#region src/formats/v8/heap-snapshot/index.ts
2125
- const detectV8HeapSnapshot = (json) => {
2126
- if (typeof json !== `object` || json === null) return;
2127
- const { snapshot, edges } = json;
2128
- if (typeof snapshot !== `object` || snapshot === null) return;
2129
- const { meta } = snapshot;
2130
- if (typeof meta !== `object` || meta === null || !Array.isArray(meta.node_fields)) return;
2131
- if (!Array.isArray(edges)) return;
2132
- return json;
2133
- };
2134
- /**
2135
- * Converts the given V8 heap snapshot to Markdown.
2136
- *
2137
- * It is assumed that {@link data} is a valid snapshot. The behavior of this
2138
- * function is undefined for invalid snapshots.
2139
- *
2140
- * You can generate a V8 heap snapshot in several ways:
2141
- * - [`node --heapsnapshot-near-heap-limit=1`](https://nodejs.org/api/cli.html#heapsnapshot-near-heap-limitmax-count)
2142
- * - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
2143
- * - [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
2144
- * - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
2145
- * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
2146
- * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
2147
- * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
2148
- * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
2149
- * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
2150
- */
2151
- const v8HeapSnapshotToMd = (data, options) => v8HeapSnapshotToMdInternal(parseV8HeapSnapshot(data), options);
2152
- const v8HeapSnapshotToMdInternal = (snapshot, options) => {
2153
- const normalizedOptions = normalizeProfileToMdOptions(options);
2154
- return formatV8HeapSnapshot(summarizeV8HeapSnapshot(snapshot, normalizedOptions), normalizedOptions);
2155
- };
2156
-
2157
- //#endregion
2158
- //#region src/cli.ts
2159
- const jsonProfileConverters = [
2160
- {
2161
- type: `speedscope`,
2162
- detect: detectSpeedscopeProfile,
2163
- toMdInternal: speedscopeProfileToMdInternal,
2164
- toMd: speedscopeProfileToMd
2165
- },
2166
- {
2167
- type: `v8-cpu-profile`,
2168
- detect: detectV8CpuProfile,
2169
- toMdInternal: v8CpuProfileToMdInternal,
2170
- toMd: v8CpuProfileToMd
2171
- },
2172
- {
2173
- type: `v8-heap-profile`,
2174
- detect: detectV8HeapProfile,
2175
- toMdInternal: v8HeapProfileToMdInternal,
2176
- toMd: v8HeapProfileToMd
2177
- },
2178
- {
2179
- type: `v8-heap-snapshot`,
2180
- detect: detectV8HeapSnapshot,
2181
- toMdInternal: v8HeapSnapshotToMdInternal,
2182
- toMd: v8HeapSnapshotToMd
2183
- }
2184
- ];
2185
- const binaryProfileConverters = [{
2186
- type: `pprof`,
2187
- detect: detectPprof,
2188
- toMdInternal: pprofToMdInternal,
2189
- toMd: pprofToMd
2190
- }];
2191
- const profileConverters = [...jsonProfileConverters, ...binaryProfileConverters];
2192
- const cli = meow(`
2193
- Usage: profiler-md [options] [file]
2194
-
2195
- Options:
2196
- -t, --type <type> Profile type, auto-detected from content if omitted
2197
- [${profileConverters.map(({ type }) => type).sort().join(`|`)}]
2198
- -o, --output <file> Output file (default: - for stdout)
2199
- --top-n <n> Number of top entries to show (default: 20)
2200
- --cwd <path> Working directory for relative file paths in output
2201
- --third-party <glob> Mark URLs matching this glob as third-party
2202
- (repeatable; default: node_modules)
2203
- --source-maps <glob> Apply source maps matching this glob to profile
2204
- locations; files may be source map JSON or contain
2205
- inline source map comments (repeatable)
2206
- --help Show this help message
2207
- `, {
2208
- importMeta: import.meta,
2209
- allowUnknownFlags: false,
2210
- flags: {
2211
- type: {
2212
- type: `string`,
2213
- shortFlag: `t`
2214
- },
2215
- output: {
2216
- type: `string`,
2217
- shortFlag: `o`,
2218
- default: `-`
2219
- },
2220
- topN: { type: `number` },
2221
- cwd: { type: `string` },
2222
- thirdParty: {
2223
- type: `string`,
2224
- isMultiple: true,
2225
- default: []
2226
- },
2227
- sourceMaps: {
2228
- type: `string`,
2229
- isMultiple: true,
2230
- default: []
2231
- }
2232
- }
2233
- });
2234
- const gunzipAsync = promisify(gunzip);
2235
- const brotliDecompressAsync = promisify(brotliDecompress);
2236
- /**
2237
- * Pre-resolves relative source paths against the map file's directory so that `source-map-js` returns
2238
- * absolute URLs.
2239
- */
2240
- const resolveSourceMapSources = (sourceMap, path) => {
2241
- if (sourceMap.sourceRoot) return sourceMap;
2242
- return {
2243
- ...sourceMap,
2244
- sources: sourceMap.sources.map((source) => makeFileReference(source).type === `absolute` ? source : new URL(source, pathToFileURL(resolve(dirname(path)))).href)
2245
- };
2246
- };
2247
- const decompressData = async (data, filePath) => {
2248
- if (filePath?.endsWith(`.br`)) return brotliDecompressAsync(data);
2249
- if (data[0] === 31 && data[1] === 139) return gunzipAsync(data);
2250
- return data;
2251
- };
2252
- try {
2253
- const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty, sourceMaps: sourceMapPatterns } } = cli;
2254
- let forcedProfileConverter;
2255
- if (profileType !== void 0) {
2256
- forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
2257
- if (!forcedProfileConverter) {
2258
- process.stderr.write(`error: unknown profile type "${profileType}"\nRun with --help to see supported types.\n`);
2259
- process.exit(2);
2260
- }
2261
- } else if (!filePath && process.stdin.isTTY) {
2262
- cli.showHelp(0);
2263
- process.exit(0);
2264
- }
2265
- let data;
2266
- if (filePath) try {
2267
- data = await readFile(filePath);
2268
- } catch (error) {
2269
- const message = error instanceof Error ? error.message : String(error);
2270
- process.stderr.write(`error: ${message}\n`);
2271
- process.exit(1);
2272
- }
2273
- else data = Buffer.concat(await Array.fromAsync(process.stdin));
2274
- try {
2275
- data = await decompressData(data, filePath);
2276
- } catch (error) {
2277
- const message = error instanceof Error ? error.message : String(error);
2278
- process.stderr.write(`error: failed to decompress input: ${message}\n`);
2279
- process.exit(1);
2280
- }
2281
- const thirdPartyMatchers = thirdParty.map((pattern) => picomatch(pattern, { dot: true }));
2282
- const isThirdPartyEntry = thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0;
2283
- const sourceMapPaths = (await Promise.all(sourceMapPatterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
2284
- const options = {
2285
- topN,
2286
- cwd,
2287
- isThirdPartyEntry,
2288
- sourceMaps: await Promise.all(sourceMapPaths.map(async (path) => {
2289
- const content = await readFile(path, `utf8`);
2290
- const inlineSourceMap = convertSourceMap.fromSource(content)?.toObject();
2291
- if (!inlineSourceMap) return resolveSourceMapSources(JSON.parse(content), path);
2292
- inlineSourceMap.file ??= pathToFileURL(resolve(path)).href;
2293
- return resolveSourceMapSources(inlineSourceMap, path);
2294
- }))
2295
- };
2296
- let markdown;
2297
- if (forcedProfileConverter) markdown = forcedProfileConverter.toMd(data, options);
2298
- else {
2299
- let json;
2300
- try {
2301
- json = parseJson(data);
2302
- } catch {}
2303
- if (json === void 0) for (const converter of binaryProfileConverters) {
2304
- const parsed = converter.detect(data);
2305
- if (parsed !== void 0) {
2306
- markdown = converter.toMdInternal(parsed, options);
2307
- break;
2308
- }
2309
- }
2310
- else for (const converter of jsonProfileConverters) {
2311
- const parsed = converter.detect(json);
2312
- if (parsed !== void 0) {
2313
- markdown = converter.toMdInternal(parsed, options);
2314
- break;
2315
- }
2316
- }
2317
- if (markdown === void 0) {
2318
- 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`);
2319
- process.exit(2);
2320
- }
2321
- }
2322
- let output;
2323
- if (outputPath === `-`) output = process.stdout;
2324
- else {
2325
- output = createWriteStream(outputPath);
2326
- await new Promise((resolve, reject) => {
2327
- output.once(`open`, () => resolve()).once(`error`, reject);
2328
- });
2329
- }
2330
- await new Promise((resolve, reject) => {
2331
- output.write(markdown, (error) => {
2332
- if (error) reject(error);
2333
- else if (output === process.stdout) resolve();
2334
- else output.end(resolve);
2335
- });
2336
- });
2337
- } catch (error) {
2338
- if (error instanceof Error) {
2339
- process.stderr.write(`error: ${error.message}\n`);
2340
- if (error.stack) process.stderr.write(`${error.stack}\n`);
2341
- } else process.stderr.write(`error: ${String(error)}\n`);
2342
- process.exit(1);
2343
- }
2344
-
2345
- //#endregion
2346
- export { };