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.
@@ -0,0 +1,3402 @@
1
+ #!/usr/bin/env node
2
+ import { formatDocPage, getDocPage } from "@optique/core";
3
+ import { object, or } from "@optique/core/constructs";
4
+ import { message, text } from "@optique/core/message";
5
+ import { map, multiple, optional, withDefault } from "@optique/core/modifiers";
6
+ import { argument, flag, option } from "@optique/core/primitives";
7
+ import { defineProgram } from "@optique/core/program";
8
+ import { choice, integer, string } from "@optique/core/valueparser";
9
+ import { path, run } from "@optique/run";
10
+ import { SourceMapConsumer } from "source-map-js";
11
+ import globals from "globals";
12
+ import plur from "plur";
13
+ import prettyBytes from "pretty-bytes";
14
+ import prettyMilliseconds from "pretty-ms";
15
+ import { JumboJSON } from "jumbo-json";
16
+ import { Profile } from "pprof-format";
17
+ import { glob, readFile } from "node:fs/promises";
18
+ import { Ansis } from "ansis";
19
+ import { createWriteStream, openAsBlob } from "node:fs";
20
+ import { spawn } from "node:child_process";
21
+ import { blob } from "node:stream/consumers";
22
+ import { pipeline } from "node:stream/promises";
23
+ import { createBrotliDecompress, createGunzip } from "node:zlib";
24
+ import { dirname, resolve } from "node:path";
25
+ import { pathToFileURL } from "node:url";
26
+ import convertSourceMap from "convert-source-map";
27
+ import picomatch from "picomatch";
28
+
29
+ //#region package.json
30
+ var name = "profiler-md";
31
+ var version = "0.3.0";
32
+ var description = "Converts performance profiles to human and LLM friendly Markdown.";
33
+
34
+ //#endregion
35
+ //#region src/helpers/array.ts
36
+ /**
37
+ * A {@link TypedArray} wrapper that's growable.
38
+ *
39
+ * It's mainly useful when the indices are sequential IDs that arrive out of
40
+ * order and with the maximum unknown.
41
+ */
42
+ var DynamicTypedArray = class {
43
+ #array;
44
+ #arrayConstructor;
45
+ constructor(initialArray) {
46
+ this.#array = initialArray;
47
+ this.#arrayConstructor = initialArray.constructor;
48
+ }
49
+ ensureCapacity(minLength) {
50
+ if (minLength > this.#array.length) {
51
+ const grown = new this.#arrayConstructor(Math.max(minLength, this.#array.length * 2));
52
+ grown.set(this.#array);
53
+ this.#array = grown;
54
+ }
55
+ return this.#array;
56
+ }
57
+ };
58
+
59
+ //#endregion
60
+ //#region src/helpers/markdown.ts
61
+ const formatHeading = (level, content) => `${`#`.repeat(level)} ${content}`;
62
+ const formatTable = (headers, rows) => {
63
+ const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
64
+ const allRows = [headerContents, ...rows];
65
+ const widths = headerContents.map((_, columnIndex) => Math.max(...allRows.map((row) => row[columnIndex]?.length ?? 0)));
66
+ const isRight = (index) => typeof headers[index] !== `string` && headers[index]?.align === `right`;
67
+ const alignCell = (cell, index) => isRight(index) ? cell.padStart(widths[index]) : cell.padEnd(widths[index]);
68
+ const formatRow = (row) => `| ${row.map((cell, index) => alignCell(cell, index)).join(` | `)} |`;
69
+ const separator = `| ${widths.map((width, index) => isRight(index) ? `${`-`.repeat(width - 1)}:` : `-`.repeat(width)).join(` | `)} |`;
70
+ return [
71
+ formatRow(headerContents),
72
+ separator,
73
+ ...rows.map(formatRow)
74
+ ].join(`\n`);
75
+ };
76
+ const inlineCode = (text) => {
77
+ const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
78
+ const fence = `\``.repeat(longestBacktickRun + 1);
79
+ return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
80
+ };
81
+
82
+ //#endregion
83
+ //#region src/location.ts
84
+ /**
85
+ * Converts a {@link ProfileLocationInput} or a {@link ProfileLocation} or
86
+ * returns undefined if it's not a valid location.
87
+ */
88
+ const makeProfileLocation = ({ urlOrPath, line, column }) => {
89
+ if (!urlOrPath) return;
90
+ const fileReference = makeFileReference(urlOrPath);
91
+ if (fileReference.type !== `absolute`) return;
92
+ return {
93
+ url: fileReference.url,
94
+ line,
95
+ column
96
+ };
97
+ };
98
+ const makeFileReference = (urlOrPath) => {
99
+ if (urlOrPath.startsWith(`/`)) try {
100
+ return {
101
+ type: `absolute`,
102
+ url: new URL(`file://${urlOrPath}`)
103
+ };
104
+ } catch {
105
+ return {
106
+ type: `relative`,
107
+ path: urlOrPath
108
+ };
109
+ }
110
+ if (!urlOrPath.includes(`:`)) return {
111
+ type: `relative`,
112
+ path: urlOrPath
113
+ };
114
+ try {
115
+ return {
116
+ type: `absolute`,
117
+ url: new URL(urlOrPath)
118
+ };
119
+ } catch {
120
+ return {
121
+ type: `relative`,
122
+ path: urlOrPath
123
+ };
124
+ }
125
+ };
126
+ const formatProfileLocation = (location, options) => {
127
+ const { cwd } = options;
128
+ if (!location) return inlineCode(`<native>`);
129
+ location = sourceMapProfileLocation(location, options);
130
+ let path;
131
+ if (location.url.protocol === `file:`) {
132
+ path = location.url.pathname;
133
+ if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
134
+ } else path = location.url.href;
135
+ if (location.line !== void 0) {
136
+ path += `:${location.line}`;
137
+ if (location.column !== void 0) path += `:${location.column}`;
138
+ }
139
+ return path || inlineCode(`<native>`);
140
+ };
141
+
142
+ //#endregion
143
+ //#region src/source-map.ts
144
+ const normalizeSourceMaps = (sourceMaps) => {
145
+ if (Array.isArray(sourceMaps)) sourceMaps = Object.fromEntries(sourceMaps.flatMap((sourceMap) => sourceMap.file ? [[sourceMap.file, sourceMap]] : []));
146
+ return Object.entries(sourceMaps).map(([urlOrPath, sourceMap]) => ({
147
+ consumer: new SourceMapConsumer(sourceMap),
148
+ location: makeFileReference(urlOrPath)
149
+ }));
150
+ };
151
+ const sourceMapProfileLocation = (location, { cwd, sourceMaps }) => {
152
+ 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}`));
153
+ if (!sourceMap) return location;
154
+ let mappedPosition;
155
+ try {
156
+ mappedPosition = sourceMap.consumer.originalPositionFor({
157
+ line: location.line ?? 1,
158
+ column: (location.column ?? 1) - 1
159
+ });
160
+ } catch {
161
+ return location;
162
+ }
163
+ if (!mappedPosition.source) return location;
164
+ const mappedLocation = makeFileReference(mappedPosition.source);
165
+ if (mappedLocation.type === `absolute`) return {
166
+ url: mappedLocation.url,
167
+ line: mappedPosition.line,
168
+ column: mappedPosition.column + 1
169
+ };
170
+ if (!cwd) return location;
171
+ return makeProfileLocation({
172
+ urlOrPath: cwd + mappedLocation.path,
173
+ line: mappedPosition.line,
174
+ column: mappedPosition.column + 1
175
+ }) ?? location;
176
+ };
177
+
178
+ //#endregion
179
+ //#region src/options.ts
180
+ const normalizeProfileToMdOptions = ({ topN = 20, categorizeEntry = defaultCategorizeEntry, showEntry = defaultShowEntry, cwd, sourceMaps } = {}) => {
181
+ if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
182
+ if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
183
+ return {
184
+ topN,
185
+ categorizeEntry: cacheEntryFunction(categorizeEntry),
186
+ showEntry: cacheEntryPredicate(showEntry),
187
+ cwd: cwd ?? void 0,
188
+ sourceMaps: normalizeSourceMaps(sourceMaps ?? [])
189
+ };
190
+ };
191
+ const cacheEntryFunction = (func) => {
192
+ const cache = [];
193
+ return (entry) => {
194
+ const { id } = entry;
195
+ const cached = cache[id];
196
+ if (cached !== void 0) return cached;
197
+ const result = func(entry);
198
+ cache[id] = result;
199
+ return result;
200
+ };
201
+ };
202
+ const cacheEntryPredicate = (func) => {
203
+ const cache = new DynamicTypedArray(new Uint8Array(256));
204
+ return (entry) => {
205
+ const { id } = entry;
206
+ const array = cache.ensureCapacity(id + 1);
207
+ const value = array[id];
208
+ if (value !== 0) return value === 2;
209
+ const result = func(entry);
210
+ array[id] = result ? 2 : 1;
211
+ return result;
212
+ };
213
+ };
214
+ /**
215
+ * Returns an arbitrary category string for this entry.
216
+ *
217
+ * Categorizes into `ours`, `stdlib`, `third-party`, and a few other categories
218
+ * by default.
219
+ */
220
+ const defaultCategorizeEntry = (entry) => {
221
+ const { name, location } = entry;
222
+ if (name?.startsWith(`(`) && name.endsWith(`)`) && !name.startsWith(`(anonymous`)) return name.slice(1, -1);
223
+ if (name === `Garbage Collection`) return `garbage collector`;
224
+ else if (name?.startsWith(`RegExp: `)) return `regexp`;
225
+ if (!location || location.url.protocol === `node:`) return `stdlib`;
226
+ if (location.url.pathname.includes(`/node_modules/`)) return `third-party`;
227
+ return `ours`;
228
+ };
229
+ /**
230
+ * Returns whether to include the given entry in the Markdown output.
231
+ *
232
+ * Excludes synthetic and external-private entries.
233
+ */
234
+ const defaultShowEntry = (entry) => !isSyntheticEntry(entry) && !isExternalPrivateEntry(entry);
235
+ /**
236
+ * Returns true if the entry is a synthetic artifacts.
237
+ *
238
+ * These entries are artifacts generated by the profiler and don't correspond to
239
+ * something that actually exists in code or at runtime. For example, a
240
+ * synthetic `(root)` node is typically created for heap snapshots.
241
+ */
242
+ const isSyntheticEntry = ({ name }) => name === `(root)` || name === `<root>` || name === `(module)`;
243
+ /**
244
+ * Returns true if the entry corresponds to an external function (`stdlib` or
245
+ * `third-party`) that's never directly called by `ours` code.
246
+ *
247
+ * These entries are typically implementation details of external code that your
248
+ * own code cannot directly call. Excluding these entries from the Markdown
249
+ * leaves only your code and the public API surface of stdlib and third-pary
250
+ * code.
251
+ */
252
+ const isExternalPrivateEntry = (entry) => {
253
+ if (entry.type !== `function`) return false;
254
+ if (entry.category !== `stdlib` && entry.category !== `third-party`) return false;
255
+ for (const { caller } of entry.callerIdToMetrics.values()) if (caller.category === `ours`) return false;
256
+ return true;
257
+ };
258
+
259
+ //#endregion
260
+ //#region src/helpers/format.ts
261
+ const formatCount = (count, unit) => count.toLocaleString(`en-US`) + (unit ? ` ${plur(unit, count)}` : ``);
262
+ const formatMicroseconds = (microseconds) => microseconds >= 1e3 ? formatMilliseconds(microseconds / 1e3) : `${microseconds.toFixed(1)}µs`;
263
+ const formatMilliseconds = (milliseconds) => prettyMilliseconds(milliseconds, {
264
+ secondsDecimalDigits: 2,
265
+ millisecondsDecimalDigits: 1,
266
+ unitCount: 2
267
+ });
268
+ const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
269
+ const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
270
+ const formatConjunction = (strings) => (conjunctionFormatter ??= new Intl.ListFormat(`en`, {
271
+ style: `long`,
272
+ type: `conjunction`
273
+ })).format(strings);
274
+ let conjunctionFormatter;
275
+
276
+ //#endregion
277
+ //#region src/helpers/heap.ts
278
+ var MaxHeap = class {
279
+ #keys;
280
+ #values;
281
+ /** Indices into {@link MaxHeap#keys} and {@link MaxHeap#values}. */
282
+ #heap;
283
+ #size;
284
+ constructor(values, select) {
285
+ const count = values.length;
286
+ const heap = new Int32Array(count);
287
+ const keys = new Float64Array(count);
288
+ for (let i = 0; i < count; i++) {
289
+ heap[i] = i;
290
+ keys[i] = select(values[i]);
291
+ }
292
+ this.#keys = keys;
293
+ this.#values = values;
294
+ this.#heap = heap;
295
+ this.#size = count;
296
+ for (let i = Math.floor(count / 2) - 1; i >= 0; i--) this.#siftDown(i);
297
+ }
298
+ get length() {
299
+ return this.#size;
300
+ }
301
+ pop() {
302
+ if (this.#size === 0) return;
303
+ const maxIndex = this.#heap[0];
304
+ this.#heap[0] = this.#heap[--this.#size];
305
+ this.#siftDown(0);
306
+ return this.#values[maxIndex];
307
+ }
308
+ #siftDown(index) {
309
+ while (true) {
310
+ let largest = 2 * index + 1;
311
+ if (largest >= this.#size) break;
312
+ const right = largest + 1;
313
+ if (right < this.#size) {
314
+ const leftKey = this.#keys[this.#heap[largest]];
315
+ const rightKey = this.#keys[this.#heap[right]];
316
+ if (rightKey > leftKey || rightKey === leftKey && this.#heap[right] < this.#heap[largest]) largest = right;
317
+ }
318
+ const largestKey = this.#keys[this.#heap[largest]];
319
+ const indexKey = this.#keys[this.#heap[index]];
320
+ if (largestKey < indexKey || largestKey === indexKey && this.#heap[largest] > this.#heap[index]) break;
321
+ const tmp = this.#heap[index];
322
+ this.#heap[index] = this.#heap[largest];
323
+ this.#heap[largest] = tmp;
324
+ index = largest;
325
+ }
326
+ }
327
+ };
328
+ const selectTopN = (values, topN, select) => {
329
+ if (topN === 0) return [];
330
+ if (values.length <= topN) return values.toSorted((value1, value2) => select(value2) - select(value1));
331
+ const heap = new MaxHeap(values, select);
332
+ return Array.from({ length: topN }, () => heap.pop());
333
+ };
334
+
335
+ //#endregion
336
+ //#region src/snapshot/format.ts
337
+ const formatHeapSnapshot = (snapshot, options) => {
338
+ const hasLocation = snapshot.constructors.some((constructor) => constructor.location) || snapshot.closures.some((closure) => closure.location);
339
+ return `${[
340
+ formatHeading(1, `Heap snapshot`),
341
+ ...formatOverallSummary$1(snapshot),
342
+ ...formatLargestConstructors(snapshot, hasLocation, options),
343
+ ...formatLargestClosures(snapshot, hasLocation, options),
344
+ ...formatLargestStrings(snapshot, options)
345
+ ].join(`\n\n`)}\n`;
346
+ };
347
+ const formatOverallSummary$1 = ({ totalSize, nodeCount, edgeCount, nodeCategoryToStats }) => {
348
+ const hottestObjectCategories = [...nodeCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
349
+ if (hottestObjectCategories.length === 0) return [];
350
+ return [`Allocated ${formatBytes(totalSize)} across ${formatCount(nodeCount)} nodes and ${formatCount(edgeCount)} edges.`, formatTable([
351
+ `Category`,
352
+ {
353
+ content: `%`,
354
+ align: `right`
355
+ },
356
+ {
357
+ content: `Size`,
358
+ align: `right`
359
+ },
360
+ {
361
+ content: `Nodes`,
362
+ align: `right`
363
+ }
364
+ ], hottestObjectCategories.map(([category, { size, nodeCount: objectCount }]) => [
365
+ category,
366
+ formatPercent(size / totalSize),
367
+ formatBytes(size),
368
+ formatCount(objectCount)
369
+ ]))];
370
+ };
371
+ const formatLargestConstructors = (snapshot, hasLocation, options) => {
372
+ const largestConstructorsSections = [...formatLargestSelfSizeConstructors(snapshot, hasLocation, options), ...formatLargestRetainedSizeConstructors(snapshot, hasLocation, options)];
373
+ if (largestConstructorsSections.length === 0) return [];
374
+ return [formatHeading(2, `Largest constructors`), ...largestConstructorsSections];
375
+ };
376
+ const formatLargestSelfSizeConstructors = (snapshot, hasLocation, options) => {
377
+ const { totalSize, constructors } = snapshot;
378
+ const largestConstructors = selectTopN(constructors.filter(options.showEntry), options.topN, (constructor) => constructor.selfSize);
379
+ if (largestConstructors.length === 0) return [];
380
+ const largestInstanceSections = largestConstructors.flatMap((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, hasLocation, options));
381
+ return [
382
+ formatHeading(3, `Self size`),
383
+ `Constructors ranked by bytes allocated for their instances, excluding nodes kept reachable by them.`,
384
+ formatTable([
385
+ {
386
+ content: `%`,
387
+ align: `right`
388
+ },
389
+ {
390
+ content: `Size`,
391
+ align: `right`
392
+ },
393
+ {
394
+ content: `Instances`,
395
+ align: `right`
396
+ },
397
+ `Constructor`,
398
+ ...hasLocation ? [`Location`] : []
399
+ ], largestConstructors.map((constructor) => [
400
+ formatPercent(constructor.selfSize / totalSize),
401
+ formatBytes(constructor.selfSize),
402
+ formatCount(constructor.instances.length),
403
+ inlineCode(constructor.name),
404
+ ...hasLocation ? [formatProfileLocation(constructor.location, options)] : []
405
+ ])),
406
+ ...largestInstanceSections.length > 0 ? [formatHeading(4, `Instances`), `Instances ranked by contribution to each constructor's self size.`] : [],
407
+ ...largestInstanceSections
408
+ ];
409
+ };
410
+ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, hasLocation, options) => {
411
+ const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.selfSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.selfSize - group1.selfSize);
412
+ if (largestInstanceGroups.length === 0) return [];
413
+ return [formatHeading(5, `${inlineCode(constructor.name)}${hasLocation ? ` (${formatProfileLocation(constructor.location, options)})` : ``}`), formatTable([
414
+ {
415
+ content: `%`,
416
+ align: `right`
417
+ },
418
+ {
419
+ content: `Size`,
420
+ align: `right`
421
+ },
422
+ {
423
+ content: `Instances`,
424
+ align: `right`
425
+ },
426
+ `Path`
427
+ ], largestInstanceGroups.map((group) => [
428
+ formatPercent(group.selfSize / constructor.selfSize),
429
+ formatBytes(group.selfSize),
430
+ formatCount(group.instanceCount),
431
+ inlineCode(group.retainerPath)
432
+ ]))];
433
+ };
434
+ const formatLargestRetainedSizeConstructors = (snapshot, hasLocation, options) => {
435
+ const { totalSize, constructors } = snapshot;
436
+ const largestConstructors = selectTopN(constructors.filter(options.showEntry), options.topN, (constructor) => constructor.retainedSize);
437
+ if (largestConstructors.length === 0) return [];
438
+ const largestInstanceSections = largestConstructors.flatMap((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, hasLocation, options));
439
+ return [
440
+ formatHeading(3, `Retained size`),
441
+ `Constructors ranked by bytes allocated for their instances and all nodes that would be freed if their instances were garbage collected.`,
442
+ formatTable([
443
+ {
444
+ content: `%`,
445
+ align: `right`
446
+ },
447
+ {
448
+ content: `Size`,
449
+ align: `right`
450
+ },
451
+ {
452
+ content: `Instances`,
453
+ align: `right`
454
+ },
455
+ `Constructor`,
456
+ ...hasLocation ? [`Location`] : []
457
+ ], largestConstructors.map((constructor) => [
458
+ formatPercent(constructor.retainedSize / totalSize),
459
+ formatBytes(constructor.retainedSize),
460
+ formatCount(constructor.instances.length),
461
+ inlineCode(constructor.name),
462
+ ...hasLocation ? [formatProfileLocation(constructor.location, options)] : []
463
+ ])),
464
+ ...largestInstanceSections.length > 0 ? [formatHeading(4, `Instances`), `Instances ranked by contribution to each constructor's retained size.`] : [],
465
+ ...largestInstanceSections
466
+ ];
467
+ };
468
+ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, hasLocation, options) => {
469
+ const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.retainedSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.retainedSize - group1.retainedSize);
470
+ if (largestInstanceGroups.length === 0) return [];
471
+ return [formatHeading(5, `${inlineCode(constructor.name)}${hasLocation ? ` (${formatProfileLocation(constructor.location, options)})` : ``}`), formatTable([
472
+ {
473
+ content: `%`,
474
+ align: `right`
475
+ },
476
+ {
477
+ content: `Size`,
478
+ align: `right`
479
+ },
480
+ {
481
+ content: `Instances`,
482
+ align: `right`
483
+ },
484
+ `Path`
485
+ ], largestInstanceGroups.map((group) => [
486
+ formatPercent(group.retainedSize / constructor.retainedSize),
487
+ formatBytes(group.retainedSize),
488
+ formatCount(group.instanceCount),
489
+ inlineCode(group.retainerPath)
490
+ ]))];
491
+ };
492
+ const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
493
+ const heap = new MaxHeap(instances, sizeOf);
494
+ const pathToGroup = /* @__PURE__ */ new Map();
495
+ while (heap.length > 0 && pathToGroup.size < topN) {
496
+ const instance = heap.pop();
497
+ const retainerPath = retainerPathOf(instance.id);
498
+ let group = pathToGroup.get(retainerPath);
499
+ if (!group) {
500
+ group = {
501
+ retainerPath,
502
+ instanceCount: 0,
503
+ selfSize: 0,
504
+ retainedSize: 0
505
+ };
506
+ pathToGroup.set(retainerPath, group);
507
+ }
508
+ group.instanceCount++;
509
+ group.selfSize += instance.selfSize;
510
+ group.retainedSize += instance.retainedSize;
511
+ }
512
+ return [...pathToGroup.values()];
513
+ };
514
+ const formatLargestClosures = (snapshot, hasLocation, options) => {
515
+ const { totalSize, closures, retainerPathOf } = snapshot;
516
+ const largestClosures = selectTopN(closures.filter((closure) => options.showEntry({
517
+ ...closure,
518
+ id: closure.largestInstanceId
519
+ })), options.topN, (closure) => closure.retainedSize);
520
+ if (largestClosures.length === 0) return [];
521
+ const retainedSections = largestClosures.flatMap((closure) => formatClosureRetainedObjects(closure, snapshot, hasLocation, options));
522
+ return [
523
+ formatHeading(2, `Largest closures`),
524
+ `Closures ranked by bytes that would be freed if the closure were garbage collected.`,
525
+ formatTable([
526
+ {
527
+ content: `%`,
528
+ align: `right`
529
+ },
530
+ {
531
+ content: `Retained`,
532
+ align: `right`
533
+ },
534
+ {
535
+ content: `Instances`,
536
+ align: `right`
537
+ },
538
+ {
539
+ content: `Paths`,
540
+ align: `right`
541
+ },
542
+ `Name`,
543
+ ...hasLocation ? [`Location`] : [],
544
+ `Example path`
545
+ ], largestClosures.map((closure) => [
546
+ formatPercent(closure.retainedSize / totalSize),
547
+ formatBytes(closure.retainedSize),
548
+ formatCount(closure.instanceIds.length),
549
+ formatCount(new Set(closure.instanceIds.map(retainerPathOf)).size),
550
+ inlineCode(closure.name),
551
+ ...hasLocation ? [formatProfileLocation(closure.location, options)] : [],
552
+ inlineCode(retainerPathOf(closure.largestInstanceId))
553
+ ])),
554
+ ...retainedSections.length > 0 ? [formatHeading(3, `Retained`), `Nodes ranked by contribution to each closure's retained size.`] : [],
555
+ ...retainedSections
556
+ ];
557
+ };
558
+ const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, hasLocation, options) => {
559
+ const instanceIdToSeen = new DynamicTypedArray(new Uint8Array(256));
560
+ const allRetainedNodes = [];
561
+ for (const instanceId of closure.instanceIds) for (const node of retainedNodesOf(instanceId)) {
562
+ const seen = instanceIdToSeen.ensureCapacity(node.id + 1);
563
+ if (seen[node.id]) continue;
564
+ seen[node.id] = 1;
565
+ if (options.showEntry(node)) allRetainedNodes.push(node);
566
+ }
567
+ const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node) => node.selfSize);
568
+ if (retainedNodes.length === 0) return [];
569
+ return [formatHeading(4, `${inlineCode(closure.name)}${hasLocation ? ` (${formatProfileLocation(closure.location, options)})` : ``}`), formatTable([
570
+ {
571
+ content: `%`,
572
+ align: `right`
573
+ },
574
+ {
575
+ content: `Self`,
576
+ align: `right`
577
+ },
578
+ `Name`,
579
+ `Path`
580
+ ], retainedNodes.map((node) => [
581
+ formatPercent(node.selfSize / closure.retainedSize),
582
+ formatBytes(node.selfSize),
583
+ inlineCode(node.name || `(unknown)`),
584
+ inlineCode(retainerPathOf(node.id))
585
+ ]))];
586
+ };
587
+ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) => {
588
+ const largestStrings = selectTopN(strings, options.topN, (string) => string.selfSize);
589
+ if (largestStrings.length === 0) return [];
590
+ const hasValues = largestStrings.some((string) => string.name !== void 0);
591
+ return [
592
+ formatHeading(2, `Largest strings`),
593
+ `Strings ranked by bytes allocated for them.`,
594
+ formatTable([
595
+ {
596
+ content: `%`,
597
+ align: `right`
598
+ },
599
+ {
600
+ content: `Size`,
601
+ align: `right`
602
+ },
603
+ ...hasValues ? [`Value`] : [],
604
+ `Path`
605
+ ], largestStrings.map((string) => [
606
+ formatPercent(string.selfSize / totalSize),
607
+ formatBytes(string.selfSize),
608
+ ...hasValues ? [inlineCode(string.name ?? `(unknown)`)] : [],
609
+ inlineCode(retainerPathOf(string.id))
610
+ ]))
611
+ ];
612
+ };
613
+
614
+ //#endregion
615
+ //#region src/snapshot/graph.ts
616
+ /**
617
+ * Computes the immediate dominators of every node.
618
+ *
619
+ * Uses the Lengauer-Tarjan dominator tree algorithm.
620
+ *
621
+ * @see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
622
+ * @see https://www.cs.princeton.edu/courses/archive/fall03/cs528/handouts/a%20fast%20algorithm%20for%20finding.pdf
623
+ */
624
+ const computeImmediateDominatorGraph = (nodeCount, { ordinalToSuccessorStartOffset, offsetToSuccessorOrdinal, ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal }) => {
625
+ const ordinalToImmediateDominatorOrdinal = new Int32Array(nodeCount).fill(-1);
626
+ const dfsIndexToOrdinal = new Int32Array(nodeCount);
627
+ const ordinalToParentOrdinal = new Int32Array(nodeCount).fill(-1);
628
+ const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
629
+ const ordinalToSemidominatorDfsIndex = new Int32Array(nodeCount);
630
+ ordinalToDfsIndex[0] = 0;
631
+ dfsIndexToOrdinal[0] = 0;
632
+ const dfsStackOrdinals = new Int32Array(nodeCount);
633
+ const dfsStackOffsets = new Int32Array(nodeCount);
634
+ dfsStackOffsets[0] = ordinalToSuccessorStartOffset[0];
635
+ let dfsIndex = 1;
636
+ let dfsStackSize = 1;
637
+ do {
638
+ const topOffset = dfsStackSize - 1;
639
+ const nodeOrdinal = dfsStackOrdinals[topOffset];
640
+ const nextOffset = dfsStackOffsets[topOffset];
641
+ if (nextOffset === ordinalToSuccessorStartOffset[nodeOrdinal + 1]) {
642
+ dfsStackSize--;
643
+ continue;
644
+ }
645
+ const childOrdinal = offsetToSuccessorOrdinal[nextOffset];
646
+ dfsStackOffsets[topOffset]++;
647
+ if (ordinalToDfsIndex[childOrdinal] !== -1) continue;
648
+ ordinalToParentOrdinal[childOrdinal] = nodeOrdinal;
649
+ ordinalToDfsIndex[childOrdinal] = dfsIndex;
650
+ ordinalToSemidominatorDfsIndex[childOrdinal] = dfsIndex;
651
+ dfsIndexToOrdinal[dfsIndex] = childOrdinal;
652
+ dfsIndex++;
653
+ dfsStackOrdinals[dfsStackSize] = childOrdinal;
654
+ dfsStackOffsets[dfsStackSize] = ordinalToSuccessorStartOffset[childOrdinal];
655
+ dfsStackSize++;
656
+ } while (dfsStackSize > 0);
657
+ const reachableCount = dfsIndex;
658
+ const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
659
+ const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
660
+ const ordinalToMinSemiAncestorOrdinal = new Int32Array(nodeCount);
661
+ for (let i = 0; i < nodeCount; i++) ordinalToMinSemiAncestorOrdinal[i] = i;
662
+ const compressAncestorPath = (startNodeOrdinal) => {
663
+ let pathLength = 0;
664
+ let nodeOrdinal = startNodeOrdinal;
665
+ while (ordinalToForestAncestorOrdinal[nodeOrdinal] !== -1 && ordinalToForestAncestorOrdinal[ordinalToForestAncestorOrdinal[nodeOrdinal]] !== -1) {
666
+ ancestorNodeOrdinalPath[pathLength++] = nodeOrdinal;
667
+ nodeOrdinal = ordinalToForestAncestorOrdinal[nodeOrdinal];
668
+ }
669
+ for (let pathIndex = pathLength - 1; pathIndex >= 0; pathIndex--) {
670
+ const pathNodeOrdinal = ancestorNodeOrdinalPath[pathIndex];
671
+ const ancestorOrdinal = ordinalToForestAncestorOrdinal[pathNodeOrdinal];
672
+ if (ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[ancestorOrdinal]] < ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal]]) ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal] = ordinalToMinSemiAncestorOrdinal[ancestorOrdinal];
673
+ ordinalToForestAncestorOrdinal[pathNodeOrdinal] = ordinalToForestAncestorOrdinal[ancestorOrdinal];
674
+ }
675
+ };
676
+ const minSemiAncestorOrdinal = (nodeOrdinal) => {
677
+ if (ordinalToForestAncestorOrdinal[nodeOrdinal] === -1) return nodeOrdinal;
678
+ compressAncestorPath(nodeOrdinal);
679
+ return ordinalToMinSemiAncestorOrdinal[nodeOrdinal];
680
+ };
681
+ const pendingHeadOrdinals = new Int32Array(nodeCount).fill(-1);
682
+ const pendingNextOrdinals = new Int32Array(nodeCount).fill(-1);
683
+ for (let dfsIndex = reachableCount - 1; dfsIndex >= 1; dfsIndex--) {
684
+ const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
685
+ const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
686
+ const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
687
+ for (let predecessorOffset = predecessorStartOffset; predecessorOffset < predecessorEndOffset; predecessorOffset++) {
688
+ const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
689
+ if (ordinalToDfsIndex[predecessorOrdinal] === -1) continue;
690
+ const minAncestorOrdinal = minSemiAncestorOrdinal(predecessorOrdinal);
691
+ if (ordinalToSemidominatorDfsIndex[minAncestorOrdinal] < ordinalToSemidominatorDfsIndex[nodeOrdinal]) ordinalToSemidominatorDfsIndex[nodeOrdinal] = ordinalToSemidominatorDfsIndex[minAncestorOrdinal];
692
+ }
693
+ const semiBucketOrdinal = dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]];
694
+ pendingNextOrdinals[nodeOrdinal] = pendingHeadOrdinals[semiBucketOrdinal];
695
+ pendingHeadOrdinals[semiBucketOrdinal] = nodeOrdinal;
696
+ ordinalToForestAncestorOrdinal[nodeOrdinal] = ordinalToParentOrdinal[nodeOrdinal];
697
+ const parentOrdinal = ordinalToParentOrdinal[nodeOrdinal];
698
+ let pendingOrdinal = pendingHeadOrdinals[parentOrdinal];
699
+ pendingHeadOrdinals[parentOrdinal] = -1;
700
+ while (pendingOrdinal !== -1) {
701
+ const nextPending = pendingNextOrdinals[pendingOrdinal];
702
+ const ancestorOrdinal = minSemiAncestorOrdinal(pendingOrdinal);
703
+ ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : parentOrdinal;
704
+ pendingOrdinal = nextPending;
705
+ }
706
+ }
707
+ for (let dfsIndex = 1; dfsIndex < reachableCount; dfsIndex++) {
708
+ const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
709
+ if (ordinalToImmediateDominatorOrdinal[nodeOrdinal] !== dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]) ordinalToImmediateDominatorOrdinal[nodeOrdinal] = ordinalToImmediateDominatorOrdinal[ordinalToImmediateDominatorOrdinal[nodeOrdinal]];
710
+ }
711
+ ordinalToImmediateDominatorOrdinal[0] = 0;
712
+ const dominatorOrdinalToDominateeCount = new Int32Array(nodeCount);
713
+ for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
714
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
715
+ if (dominatorOrdinal !== -1) dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
716
+ }
717
+ const immediateDominateeOrdinalToStartOffset = new Int32Array(nodeCount + 1);
718
+ for (let offset = 0; offset < nodeCount; offset++) immediateDominateeOrdinalToStartOffset[offset + 1] = immediateDominateeOrdinalToStartOffset[offset] + dominatorOrdinalToDominateeCount[offset];
719
+ const offsetToImmediateDominateeOrdinal = new Int32Array(immediateDominateeOrdinalToStartOffset[nodeCount]);
720
+ dominatorOrdinalToDominateeCount.fill(0);
721
+ for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
722
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
723
+ if (dominatorOrdinal !== -1) {
724
+ offsetToImmediateDominateeOrdinal[immediateDominateeOrdinalToStartOffset[dominatorOrdinal] + dominatorOrdinalToDominateeCount[dominatorOrdinal]] = nodeOrdinal;
725
+ dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
726
+ }
727
+ }
728
+ return {
729
+ dfsIndexToOrdinal,
730
+ ordinalToImmediateDominatorOrdinal,
731
+ immediateDominateeOrdinalToStartOffset,
732
+ offsetToImmediateDominateeOrdinal
733
+ };
734
+ };
735
+
736
+ //#endregion
737
+ //#region src/snapshot/retained.ts
738
+ const computeNodeOrdinalToRetainedSize = (nodes, nodeFieldCount, selfSizeOffset, { dfsIndexToOrdinal, ordinalToImmediateDominatorOrdinal }) => {
739
+ const nodeOrdinalToRetainedSize = new Float64Array(ordinalToImmediateDominatorOrdinal.length);
740
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeOrdinalToRetainedSize.length; nodeOrdinal++) nodeOrdinalToRetainedSize[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + selfSizeOffset];
741
+ for (let dfsIndex = dfsIndexToOrdinal.length - 1; dfsIndex >= 1; dfsIndex--) {
742
+ const dominateeOrdinal = dfsIndexToOrdinal[dfsIndex];
743
+ nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominateeOrdinal]] += nodeOrdinalToRetainedSize[dominateeOrdinal];
744
+ }
745
+ return nodeOrdinalToRetainedSize;
746
+ };
747
+ /**
748
+ * Attributes retained sizes to categories of nodes without double-counting.
749
+ *
750
+ * Summing per-node retained sizes across all instances of a category
751
+ * over-counts when one instance dominates another from the same category (the
752
+ * dominated node's memory is already included in the dominator's retained
753
+ * size).
754
+ *
755
+ * This function correctly attributes by doing a DFS of the dominator tree and
756
+ * only crediting the outermost instance of each category on any root-to-leaf
757
+ * path. Inner instances are entirely contained within the outer one's retained
758
+ * set, so they add nothing.
759
+ */
760
+ const attributeCategoryRetainedSizes = (nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToAggregatedNodeIndex, aggregatedNodes) => {
761
+ const nodeCount = nodeOrdinalToRetainedSize.length;
762
+ const categoryPathDepth = new Int32Array(aggregatedNodes.length);
763
+ const stack = new Int32Array(nodeCount * 2 + 1);
764
+ stack[0] = 0;
765
+ let topOffset = 1;
766
+ do {
767
+ const encodedNodeOrdinal = stack[--topOffset];
768
+ if (encodedNodeOrdinal < 0) {
769
+ const constructorIndex = nodeOrdinalToAggregatedNodeIndex[~encodedNodeOrdinal];
770
+ if (constructorIndex !== -1) categoryPathDepth[constructorIndex] = categoryPathDepth[constructorIndex] - 1;
771
+ continue;
772
+ }
773
+ const nodeOrdinal = encodedNodeOrdinal;
774
+ const aggregatedNodeIndex = nodeOrdinalToAggregatedNodeIndex[nodeOrdinal];
775
+ if (aggregatedNodeIndex !== -1) {
776
+ const depth = categoryPathDepth[aggregatedNodeIndex];
777
+ if (depth === 0) aggregatedNodes[aggregatedNodeIndex].retainedSize += nodeOrdinalToRetainedSize[nodeOrdinal];
778
+ categoryPathDepth[aggregatedNodeIndex] = depth + 1;
779
+ stack[topOffset++] = ~nodeOrdinal;
780
+ }
781
+ const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
782
+ const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
783
+ for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) stack[topOffset++] = offsetToImmediateDominateeOrdinal[offset];
784
+ } while (topOffset > 0);
785
+ };
786
+
787
+ //#endregion
788
+ //#region src/snapshot/aggregate.ts
789
+ var SnapshotAggregator = class {
790
+ #nodes;
791
+ #nodeCount;
792
+ #edgeCount;
793
+ #nodeFieldCount;
794
+ #nodeSelfSizeOffset;
795
+ #nodeAdjacencyGraph;
796
+ #formatEdgeLabel;
797
+ #formatNodeLabel;
798
+ #isInternalNode;
799
+ #totalSize = 0;
800
+ #nodeCategoryToStats = /* @__PURE__ */ new Map();
801
+ #immediateDominatorGraph;
802
+ #nodeOrdinalToRetainedSize;
803
+ #constructors = [];
804
+ #nameToConstructorIndex = /* @__PURE__ */ new Map();
805
+ #nodeOrdinalToConstructorIndex;
806
+ #closures = [];
807
+ #keyToClosureIndex = /* @__PURE__ */ new Map();
808
+ #nodeOrdinalToClosureIndex;
809
+ #strings = [];
810
+ constructor({ nodes, nodeCount, edgeCount, nodeFieldCount, nodeSelfSizeOffset, nodeAdjacencyGraph, formatEdgeLabel, formatNodeLabel, isInternalNode }) {
811
+ this.#nodes = nodes;
812
+ this.#nodeCount = nodeCount;
813
+ this.#edgeCount = edgeCount;
814
+ this.#nodeFieldCount = nodeFieldCount;
815
+ this.#nodeSelfSizeOffset = nodeSelfSizeOffset;
816
+ this.#nodeAdjacencyGraph = nodeAdjacencyGraph;
817
+ this.#formatEdgeLabel = formatEdgeLabel;
818
+ this.#formatNodeLabel = formatNodeLabel;
819
+ this.#isInternalNode = isInternalNode;
820
+ this.#immediateDominatorGraph = computeImmediateDominatorGraph(nodeCount, nodeAdjacencyGraph);
821
+ this.#nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(nodes, nodeFieldCount, nodeSelfSizeOffset, this.#immediateDominatorGraph);
822
+ this.#nodeOrdinalToConstructorIndex = new Int32Array(nodeCount).fill(-1);
823
+ this.#nodeOrdinalToClosureIndex = new Int32Array(nodeCount).fill(-1);
824
+ }
825
+ addCategoryNode(nodeOrdinal, category) {
826
+ const selfSize = this.#selfSize(nodeOrdinal);
827
+ this.#totalSize += selfSize;
828
+ let stats = this.#nodeCategoryToStats.get(category);
829
+ if (!stats) {
830
+ stats = {
831
+ size: 0,
832
+ nodeCount: 0
833
+ };
834
+ this.#nodeCategoryToStats.set(category, stats);
835
+ }
836
+ stats.size += selfSize;
837
+ stats.nodeCount++;
838
+ }
839
+ addConstructorNode(nodeOrdinal, location) {
840
+ const name = this.#formatNodeLabel(nodeOrdinal);
841
+ const selfSize = this.#selfSize(nodeOrdinal);
842
+ const retainedSize = this.#nodeOrdinalToRetainedSize[nodeOrdinal];
843
+ let constructorIndex = this.#nameToConstructorIndex.get(name);
844
+ let constructor;
845
+ if (constructorIndex === void 0) {
846
+ constructorIndex = this.#constructors.length;
847
+ constructor = {
848
+ type: `node`,
849
+ id: nodeOrdinal,
850
+ name,
851
+ location,
852
+ selfSize: 0,
853
+ retainedSize: 0,
854
+ instances: []
855
+ };
856
+ this.#constructors.push(constructor);
857
+ this.#nameToConstructorIndex.set(name, constructorIndex);
858
+ } else {
859
+ constructor = this.#constructors[constructorIndex];
860
+ constructor.location ??= location;
861
+ }
862
+ constructor.selfSize += selfSize;
863
+ constructor.instances.push({
864
+ type: `node`,
865
+ id: nodeOrdinal,
866
+ name,
867
+ selfSize,
868
+ retainedSize,
869
+ location: constructor.location
870
+ });
871
+ this.#nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
872
+ }
873
+ addClosureNode(nodeOrdinal, location) {
874
+ const name = this.#formatNodeLabel(nodeOrdinal);
875
+ const key = location ? `${name}|${location.url.href}:${location.line}:${location.column}` : name;
876
+ const retainedSize = this.#nodeOrdinalToRetainedSize[nodeOrdinal];
877
+ let closureIndex = this.#keyToClosureIndex.get(key);
878
+ if (closureIndex === void 0) {
879
+ closureIndex = this.#closures.length;
880
+ this.#closures.push({
881
+ type: `node`,
882
+ id: nodeOrdinal,
883
+ name,
884
+ location,
885
+ selfSize: 0,
886
+ retainedSize: 0,
887
+ largestInstanceId: nodeOrdinal,
888
+ instanceIds: []
889
+ });
890
+ this.#keyToClosureIndex.set(key, closureIndex);
891
+ }
892
+ const closure = this.#closures[closureIndex];
893
+ closure.selfSize += this.#selfSize(nodeOrdinal);
894
+ closure.instanceIds.push(nodeOrdinal);
895
+ if (retainedSize > this.#nodeOrdinalToRetainedSize[closure.largestInstanceId]) closure.largestInstanceId = nodeOrdinal;
896
+ this.#nodeOrdinalToClosureIndex[nodeOrdinal] = closureIndex;
897
+ }
898
+ addStringNode(nodeOrdinal, name) {
899
+ const selfSize = this.#selfSize(nodeOrdinal);
900
+ this.#strings.push({
901
+ type: `node`,
902
+ id: nodeOrdinal,
903
+ name,
904
+ selfSize,
905
+ retainedSize: selfSize
906
+ });
907
+ }
908
+ #selfSize(nodeOrdinal) {
909
+ return this.#nodes[nodeOrdinal * this.#nodeFieldCount + this.#nodeSelfSizeOffset];
910
+ }
911
+ aggregate() {
912
+ attributeCategoryRetainedSizes(this.#nodeOrdinalToRetainedSize, this.#immediateDominatorGraph, this.#nodeOrdinalToConstructorIndex, this.#constructors);
913
+ attributeCategoryRetainedSizes(this.#nodeOrdinalToRetainedSize, this.#immediateDominatorGraph, this.#nodeOrdinalToClosureIndex, this.#closures);
914
+ return {
915
+ totalSize: this.#totalSize,
916
+ nodeCount: this.#nodeCount,
917
+ edgeCount: this.#edgeCount,
918
+ nodeCategoryToStats: this.#nodeCategoryToStats,
919
+ constructors: this.#constructors,
920
+ closures: this.#closures,
921
+ strings: this.#strings,
922
+ retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, this.#nodeAdjacencyGraph, this.#immediateDominatorGraph, this.#formatEdgeLabel, this.#isInternalNode),
923
+ retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, this.#immediateDominatorGraph, this.#nodeOrdinalToRetainedSize, this.#nodes, this.#nodeFieldCount, this.#nodeSelfSizeOffset, this.#formatNodeLabel, this.#isInternalNode)
924
+ };
925
+ }
926
+ };
927
+ const computeRetainerPath = (nodeOrdinal, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, { ordinalToImmediateDominatorOrdinal }, formatEdgeLabel, isInternalNode) => {
928
+ const hops = [];
929
+ while (true) {
930
+ const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
931
+ const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
932
+ if (predecessorStartOffset === predecessorEndOffset) break;
933
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
934
+ let predecessorOffset = -1;
935
+ for (let offset = predecessorStartOffset; offset < predecessorEndOffset; offset++) if (offsetToPredecessorOrdinal[offset] === dominatorOrdinal) {
936
+ predecessorOffset = offset;
937
+ break;
938
+ }
939
+ if (predecessorOffset === -1) {
940
+ nodeOrdinal = dominatorOrdinal;
941
+ continue;
942
+ }
943
+ const edgeIndex = offsetToPredecessorEdgeIndex[predecessorOffset];
944
+ const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
945
+ hops.push({
946
+ label: formatEdgeLabel(predecessorOrdinal, edgeIndex),
947
+ internal: isInternalNode(predecessorOrdinal)
948
+ });
949
+ nodeOrdinal = predecessorOrdinal;
950
+ }
951
+ while (hops.at(-1)?.internal) hops.pop();
952
+ if (hops.length === 0) return `(GC root)`;
953
+ return hops.map((hop) => hop.label).join(` ← `);
954
+ };
955
+ const computeRetainedNodes = (nodeOrdinal, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToRetainedSize, nodes, nodeFieldCount, nodeSelfSizeOffset, formatNodeLabel, isInternalNode) => {
956
+ const retainedNodes = [];
957
+ const dominateeOrdinals = [];
958
+ const childStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
959
+ const childEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
960
+ for (let offset = childStartOffset; offset < childEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
961
+ while (dominateeOrdinals.length > 0) {
962
+ const current = dominateeOrdinals.pop();
963
+ if (!isInternalNode(current)) retainedNodes.push({
964
+ type: `node`,
965
+ id: current,
966
+ name: formatNodeLabel(current),
967
+ selfSize: nodes[current * nodeFieldCount + nodeSelfSizeOffset],
968
+ retainedSize: nodeOrdinalToRetainedSize[current]
969
+ });
970
+ const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[current];
971
+ const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[current + 1];
972
+ for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
973
+ }
974
+ return retainedNodes;
975
+ };
976
+
977
+ //#endregion
978
+ //#region src/formats/jsc-heap-snapshot/aggregate.ts
979
+ const aggregateJSCHeapSnapshot = (snapshot) => {
980
+ const { nodes, nodeClassNames, edges, edgeTypes, edgeNames } = snapshot;
981
+ const nodeCount = nodes.length / NODE_FIELD_COUNT;
982
+ const rawEdgeCount = edges.length / EDGE_FIELD_COUNT;
983
+ const stringClassNameIndex = nodeClassNames.indexOf(`string`);
984
+ const indexEdgeType = edgeTypes.indexOf(`Index`);
985
+ const classNameIndexToCategoryOrdinal = computeClassNameIndexToCategoryOrdinal(nodeClassNames);
986
+ const { nodeAdjacencyGraph, edgeCount } = computeNodeAdjacencyGraph$1(edges, nodeCount, rawEdgeCount);
987
+ const snapshotAggregator = new SnapshotAggregator({
988
+ nodeCount,
989
+ edgeCount,
990
+ nodeAdjacencyGraph,
991
+ nodes,
992
+ nodeFieldCount: NODE_FIELD_COUNT,
993
+ nodeSelfSizeOffset: NODE_SIZE_OFFSET,
994
+ formatEdgeLabel: (retainerOrdinal, edgeIndex) => {
995
+ return `${edges[edgeIndex + EDGE_TYPE_OFFSET] === indexEdgeType ? `[${edges[edgeIndex + EDGE_NAME_OFFSET]}]` : `.${edgeNames[edges[edgeIndex + EDGE_NAME_OFFSET]]}`} ${nodeClassNames[nodes[retainerOrdinal * NODE_FIELD_COUNT + NODE_CLASS_OFFSET]]}`;
996
+ },
997
+ formatNodeLabel: (nodeOrdinal) => {
998
+ return nodeClassNames[nodes[nodeOrdinal * NODE_FIELD_COUNT + NODE_CLASS_OFFSET]];
999
+ },
1000
+ isInternalNode: (nodeOrdinal) => {
1001
+ return (nodes[nodeOrdinal * NODE_FIELD_COUNT + NODE_FLAGS_OFFSET] & NODE_INTERNAL_FLAG) !== 0;
1002
+ }
1003
+ });
1004
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1005
+ const nodeIndex = nodeOrdinal * NODE_FIELD_COUNT;
1006
+ const classNameIndex = nodes[nodeIndex + NODE_CLASS_OFFSET];
1007
+ const flags = nodes[nodeIndex + NODE_FLAGS_OFFSET];
1008
+ snapshotAggregator.addCategoryNode(nodeOrdinal, categorizeNode(classNameIndex, flags, classNameIndexToCategoryOrdinal));
1009
+ if (classNameIndex === stringClassNameIndex) snapshotAggregator.addStringNode(nodeOrdinal);
1010
+ else snapshotAggregator.addConstructorNode(nodeOrdinal);
1011
+ }
1012
+ return snapshotAggregator.aggregate();
1013
+ };
1014
+ const computeClassNameIndexToCategoryOrdinal = (nodeClassNames) => {
1015
+ const classNameToCategoryOrdinal = getClassNameToCategoryOrdinal();
1016
+ const classNameIndexToCategoryOrdinal = new Int8Array(nodeClassNames.length).fill(-1);
1017
+ for (let index = 0; index < nodeClassNames.length; index++) {
1018
+ const categoryOrdinal = classNameToCategoryOrdinal[nodeClassNames[index]];
1019
+ if (categoryOrdinal !== void 0) classNameIndexToCategoryOrdinal[index] = categoryOrdinal;
1020
+ }
1021
+ return classNameIndexToCategoryOrdinal;
1022
+ };
1023
+ const getClassNameToCategoryOrdinal = () => {
1024
+ if (classNameToCategoryOrdinal !== void 0) return classNameToCategoryOrdinal;
1025
+ classNameToCategoryOrdinal = {};
1026
+ for (const name of Object.keys(globals.builtin)) classNameToCategoryOrdinal[name] = 12;
1027
+ for (const name of Object.keys(globals.browser)) classNameToCategoryOrdinal[name] = 13;
1028
+ Object.assign(classNameToCategoryOrdinal, {
1029
+ string: 0,
1030
+ Array: 1,
1031
+ "Array Iterator": 1,
1032
+ "Immutable Butterfly": 1,
1033
+ SparseArrayValueMap: 1,
1034
+ Int8Array: 1,
1035
+ Uint8Array: 1,
1036
+ Uint8ClampedArray: 1,
1037
+ Int16Array: 1,
1038
+ Uint16Array: 1,
1039
+ Int32Array: 1,
1040
+ Uint32Array: 1,
1041
+ Float16Array: 1,
1042
+ Float32Array: 1,
1043
+ Float64Array: 1,
1044
+ BigInt64Array: 1,
1045
+ BigUint64Array: 1,
1046
+ Function: 2,
1047
+ GeneratorFunction: 2,
1048
+ AsyncFunction: 2,
1049
+ AsyncGeneratorFunction: 2,
1050
+ Callee: 2,
1051
+ CallbackObject: 2,
1052
+ FunctionExecutable: 3,
1053
+ UnlinkedFunctionExecutable: 3,
1054
+ NativeExecutable: 3,
1055
+ ProgramExecutable: 3,
1056
+ ModuleProgramExecutable: 3,
1057
+ FunctionCodeBlock: 3,
1058
+ UnlinkedFunctionCodeBlock: 3,
1059
+ ModuleRecord: 3,
1060
+ JSSourceCode: 3,
1061
+ RegExp: 4,
1062
+ Number: 5,
1063
+ symbol: 6,
1064
+ Symbol: 6,
1065
+ BigInt: 7,
1066
+ JSLexicalEnvironment: 8,
1067
+ JSModuleEnvironment: 8,
1068
+ JSGlobalLexicalEnvironment: 8,
1069
+ JSWindowProxy: 8,
1070
+ InjectedScriptHost: 8,
1071
+ CommandLineAPIHost: 8,
1072
+ "<root>": 8,
1073
+ Object: 10,
1074
+ Prototype: 10,
1075
+ Generator: 10,
1076
+ AsyncGenerator: 10,
1077
+ "Map Iterator": 10,
1078
+ "Set Iterator": 10,
1079
+ "String Iterator": 10,
1080
+ "RegExp String Iterator": 10,
1081
+ AsyncFromSyncIterator: 10,
1082
+ AsyncIterator: 10,
1083
+ Arguments: 10,
1084
+ Int8ArrayPrototype: 10,
1085
+ Uint8ArrayPrototype: 10,
1086
+ Uint8ClampedArrayPrototype: 10,
1087
+ Int16ArrayPrototype: 10,
1088
+ Uint16ArrayPrototype: 10,
1089
+ Int32ArrayPrototype: 10,
1090
+ Uint32ArrayPrototype: 10,
1091
+ Float32ArrayPrototype: 10,
1092
+ Float64ArrayPrototype: 10,
1093
+ InternalPromise: 12,
1094
+ InternalPromisePrototype: 12,
1095
+ ShadowRealm: 12,
1096
+ ModuleNamespaceObject: 12,
1097
+ "Intl.DurationFormat": 12,
1098
+ "Intl.ListFormat": 12,
1099
+ "Intl.DateTimeFormat": 12,
1100
+ WindowProperties: 13,
1101
+ TextEncoderStreamEncoder: 13,
1102
+ ModuleLoader: 13
1103
+ });
1104
+ return classNameToCategoryOrdinal;
1105
+ };
1106
+ let classNameToCategoryOrdinal;
1107
+ const categorizeNode = (classNameIndex, flags, classNameIndexToCategoryOrdinal) => {
1108
+ let categoryOrdinal = classNameIndexToCategoryOrdinal[classNameIndex];
1109
+ if (categoryOrdinal === -1) if (flags & NODE_INTERNAL_FLAG) categoryOrdinal = 8;
1110
+ else if (flags & NODE_ELEMENT_FLAG) categoryOrdinal = 9;
1111
+ else if (flags & NODE_OBJECT_FLAG) categoryOrdinal = 10;
1112
+ else categoryOrdinal = 11;
1113
+ return CATEGORY_ORDINAL_TO_NAME[categoryOrdinal];
1114
+ };
1115
+ const CATEGORY_ORDINAL_TO_NAME = [
1116
+ `string`,
1117
+ `array`,
1118
+ `closure`,
1119
+ `code`,
1120
+ `regexp`,
1121
+ `number`,
1122
+ `symbol`,
1123
+ `bigint`,
1124
+ `internal`,
1125
+ `element`,
1126
+ `object`,
1127
+ `unknown`,
1128
+ `built-in`,
1129
+ `native`
1130
+ ];
1131
+ const computeNodeAdjacencyGraph$1 = (edges, nodeCount, rawEdgeCount) => {
1132
+ const ordinalToSuccessorCount = new Int32Array(nodeCount);
1133
+ const ordinalToPredecessorCount = new Int32Array(nodeCount);
1134
+ for (let edgeOrdinal = 0; edgeOrdinal < rawEdgeCount; edgeOrdinal++) {
1135
+ const edgeIndex = edgeOrdinal * EDGE_FIELD_COUNT;
1136
+ const fromNodeOrdinal = edges[edgeIndex + EDGE_FROM_OFFSET];
1137
+ const toNodeOrdinal = edges[edgeIndex + EDGE_TO_OFFSET];
1138
+ if (fromNodeOrdinal >= nodeCount || toNodeOrdinal >= nodeCount) continue;
1139
+ ordinalToSuccessorCount[fromNodeOrdinal]++;
1140
+ ordinalToPredecessorCount[toNodeOrdinal]++;
1141
+ }
1142
+ const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
1143
+ const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
1144
+ for (let i = 0; i < nodeCount; i++) {
1145
+ ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
1146
+ ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
1147
+ }
1148
+ const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
1149
+ const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
1150
+ const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
1151
+ const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
1152
+ const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
1153
+ ordinalToSuccessorCount.fill(0);
1154
+ ordinalToPredecessorCount.fill(0);
1155
+ for (let edgeOrdinal = 0; edgeOrdinal < rawEdgeCount; edgeOrdinal++) {
1156
+ const edgeIndex = edgeOrdinal * EDGE_FIELD_COUNT;
1157
+ const fromNodeOrdinal = edges[edgeIndex + EDGE_FROM_OFFSET];
1158
+ const toNodeOrdinal = edges[edgeIndex + EDGE_TO_OFFSET];
1159
+ if (fromNodeOrdinal >= nodeCount || toNodeOrdinal >= nodeCount) continue;
1160
+ const successorOffset = ordinalToSuccessorStartOffset[fromNodeOrdinal] + ordinalToSuccessorCount[fromNodeOrdinal];
1161
+ offsetToSuccessorOrdinal[successorOffset] = toNodeOrdinal;
1162
+ offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
1163
+ ordinalToSuccessorCount[fromNodeOrdinal]++;
1164
+ const predecessorOffset = ordinalToPredecessorStartOffset[toNodeOrdinal] + ordinalToPredecessorCount[toNodeOrdinal];
1165
+ offsetToPredecessorOrdinal[predecessorOffset] = fromNodeOrdinal;
1166
+ offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
1167
+ ordinalToPredecessorCount[toNodeOrdinal]++;
1168
+ }
1169
+ return {
1170
+ nodeAdjacencyGraph: {
1171
+ ordinalToSuccessorStartOffset,
1172
+ offsetToSuccessorOrdinal,
1173
+ offsetToSuccessorEdgeIndex,
1174
+ ordinalToPredecessorStartOffset,
1175
+ offsetToPredecessorOrdinal,
1176
+ offsetToPredecessorEdgeIndex
1177
+ },
1178
+ edgeCount: totalEdges
1179
+ };
1180
+ };
1181
+ const NODE_SIZE_OFFSET = 1;
1182
+ const NODE_CLASS_OFFSET = 2;
1183
+ const NODE_FLAGS_OFFSET = 3;
1184
+ const NODE_FIELD_COUNT = 4;
1185
+ const EDGE_FROM_OFFSET = 0;
1186
+ const EDGE_TO_OFFSET = 1;
1187
+ const EDGE_TYPE_OFFSET = 2;
1188
+ const EDGE_NAME_OFFSET = 3;
1189
+ const EDGE_FIELD_COUNT = 4;
1190
+ const NODE_INTERNAL_FLAG = 1;
1191
+ const NODE_OBJECT_FLAG = 2;
1192
+ const NODE_ELEMENT_FLAG = 4;
1193
+
1194
+ //#endregion
1195
+ //#region src/formats/jsc-heap-snapshot/parse.ts
1196
+ const parseJSCHeapSnapshotAsync = (data) => JumboJSON.parseAsync(data);
1197
+
1198
+ //#endregion
1199
+ //#region src/formats/jsc-heap-snapshot/index.ts
1200
+ const detectJSCHeapSnapshot = (json) => {
1201
+ if (typeof json !== `object` || json === null) return;
1202
+ const { version, type, nodes } = json;
1203
+ if (version !== 2 || type !== `Inspector` || !Array.isArray(nodes)) return;
1204
+ return json;
1205
+ };
1206
+ /**
1207
+ * Asynchronously converts the given JSC heap snapshot to Markdown.
1208
+ *
1209
+ * It is assumed that {@link data} is a valid snapshot. The behavior of this
1210
+ * function is undefined for invalid snapshots.
1211
+ *
1212
+ * See the [JSC heap snapshot docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/jsc-heap-snapshot.md)
1213
+ * for supported runtimes and generation instructions
1214
+ * (`profiler-md --help jsc-heap-snapshot`).
1215
+ */
1216
+ const jscHeapSnapshotToMdAsync = async (data, options) => jscHeapSnapshotToMdInternal(await parseJSCHeapSnapshotAsync(data), options);
1217
+ const jscHeapSnapshotToMdInternal = (snapshot, options) => {
1218
+ const normalizedOptions = normalizeProfileToMdOptions(options);
1219
+ return formatHeapSnapshot(aggregateJSCHeapSnapshot(snapshot), normalizedOptions);
1220
+ };
1221
+
1222
+ //#endregion
1223
+ //#region src/profile/aggregate.ts
1224
+ var ProfileAggregator = class {
1225
+ #metrics;
1226
+ #functionKey;
1227
+ #functionInput;
1228
+ #options;
1229
+ #totalSampleCount;
1230
+ #totalValues;
1231
+ #categoryToMetrics;
1232
+ #keyToCallStack;
1233
+ #keyToFunction;
1234
+ #idToFunction;
1235
+ #functionIdToLastSeenSampleCount;
1236
+ #frameIndexToFramePairKey;
1237
+ constructor({ metrics, functionKey, functionInput }, options) {
1238
+ this.#metrics = metrics;
1239
+ this.#functionKey = functionKey;
1240
+ this.#functionInput = functionInput;
1241
+ this.#options = options;
1242
+ this.#totalSampleCount = 0;
1243
+ this.#totalValues = new Float64Array(this.#metrics.length);
1244
+ this.#categoryToMetrics = /* @__PURE__ */ new Map();
1245
+ this.#keyToCallStack = /* @__PURE__ */ new Map();
1246
+ this.#keyToFunction = /* @__PURE__ */ new Map();
1247
+ this.#idToFunction = [];
1248
+ this.#functionIdToLastSeenSampleCount = new DynamicTypedArray(new Uint32Array(1));
1249
+ this.#frameIndexToFramePairKey = new DynamicTypedArray(new Int32Array(64));
1250
+ }
1251
+ /** Adds a single profile sample. */
1252
+ addSample({ values, nodes, line }) {
1253
+ if (nodes.length === 0) return;
1254
+ const callStack = this.#getOrCreateCallStack(nodes);
1255
+ const callee = callStack.frames[0];
1256
+ const caller = callStack.frames[1];
1257
+ let categoryMetrics = this.#categoryToMetrics.get(callee.category);
1258
+ if (!categoryMetrics) {
1259
+ categoryMetrics = {
1260
+ sampleCount: 0,
1261
+ values: new Float64Array(this.#metrics.length)
1262
+ };
1263
+ this.#categoryToMetrics.set(callee.category, categoryMetrics);
1264
+ }
1265
+ let callerMetrics;
1266
+ if (caller) {
1267
+ callerMetrics = callee.callerIdToMetrics.get(caller.id);
1268
+ if (!callerMetrics) {
1269
+ callerMetrics = {
1270
+ caller,
1271
+ selfSampleCount: 0,
1272
+ selfValues: new Float64Array(this.#metrics.length)
1273
+ };
1274
+ callee.callerIdToMetrics.set(caller.id, callerMetrics);
1275
+ }
1276
+ }
1277
+ let lineMetrics;
1278
+ if (line !== void 0) {
1279
+ lineMetrics = callee.lineToMetrics.get(line);
1280
+ if (!lineMetrics) {
1281
+ lineMetrics = {
1282
+ sampleCount: 0,
1283
+ values: new Float64Array(this.#metrics.length)
1284
+ };
1285
+ callee.lineToMetrics.set(line, lineMetrics);
1286
+ }
1287
+ }
1288
+ this.#totalSampleCount++;
1289
+ categoryMetrics.sampleCount++;
1290
+ callStack.selfSampleCount++;
1291
+ callee.selfSampleCount++;
1292
+ if (callerMetrics) callerMetrics.selfSampleCount++;
1293
+ if (lineMetrics) lineMetrics.sampleCount++;
1294
+ for (let i = 0; i < values.length; i++) {
1295
+ this.#totalValues[i] += values[i];
1296
+ categoryMetrics.values[i] += values[i];
1297
+ callStack.selfValues[i] += values[i];
1298
+ callee.selfValues[i] += values[i];
1299
+ if (callerMetrics) callerMetrics.selfValues[i] += values[i];
1300
+ if (lineMetrics) lineMetrics.values[i] += values[i];
1301
+ }
1302
+ const funcCount = this.#keyToFunction.size;
1303
+ const functionIdToLastSeenSampleCount = this.#functionIdToLastSeenSampleCount.ensureCapacity(funcCount);
1304
+ for (const func of callStack.frames) {
1305
+ if (functionIdToLastSeenSampleCount[func.id] === this.#totalSampleCount) continue;
1306
+ functionIdToLastSeenSampleCount[func.id] = this.#totalSampleCount;
1307
+ func.totalSampleCount++;
1308
+ for (let i = 0; i < values.length; i++) func.totalValues[i] += values[i];
1309
+ }
1310
+ const maxFramePairCount = callStack.frames.length - 1;
1311
+ const frameIndexToFramePairKey = this.#frameIndexToFramePairKey.ensureCapacity(maxFramePairCount);
1312
+ let seenFramePairCount = 0;
1313
+ for (let i = 0; i < maxFramePairCount; i++) {
1314
+ const callee = callStack.frames[i];
1315
+ const caller = callStack.frames[i + 1];
1316
+ const pairKey = caller.id * funcCount + callee.id;
1317
+ let pairAlreadySeen = false;
1318
+ for (let j = 0; j < seenFramePairCount; j++) if (frameIndexToFramePairKey[j] === pairKey) {
1319
+ pairAlreadySeen = true;
1320
+ break;
1321
+ }
1322
+ if (pairAlreadySeen) continue;
1323
+ frameIndexToFramePairKey[seenFramePairCount++] = pairKey;
1324
+ let calleeMetrics = caller.calleeIdToMetrics.get(callee.id);
1325
+ if (!calleeMetrics) {
1326
+ calleeMetrics = {
1327
+ callee,
1328
+ totalSampleCount: 0,
1329
+ totalValues: new Float64Array(this.#metrics.length)
1330
+ };
1331
+ caller.calleeIdToMetrics.set(callee.id, calleeMetrics);
1332
+ }
1333
+ calleeMetrics.totalSampleCount++;
1334
+ for (let i = 0; i < values.length; i++) calleeMetrics.totalValues[i] += values[i];
1335
+ }
1336
+ }
1337
+ addLineMetrics({ node, lines }) {
1338
+ const func = this.#getOrCreateFunction(node);
1339
+ for (const { line, sampleCount, values } of lines) {
1340
+ let lineMetrics = func.lineToMetrics.get(line);
1341
+ if (!lineMetrics) {
1342
+ lineMetrics = {
1343
+ sampleCount: 0,
1344
+ values: new Float64Array(this.#metrics.length)
1345
+ };
1346
+ func.lineToMetrics.set(line, lineMetrics);
1347
+ }
1348
+ lineMetrics.sampleCount += sampleCount;
1349
+ for (let i = 0; i < values.length; i++) lineMetrics.values[i] += values[i];
1350
+ }
1351
+ }
1352
+ #getOrCreateCallStack(nodes) {
1353
+ const frames = nodes.map((node) => this.#getOrCreateFunction(node));
1354
+ const key = frames.map((frame) => frame.id).join(`,`);
1355
+ let callStack = this.#keyToCallStack.get(key);
1356
+ if (callStack) return callStack;
1357
+ callStack = {
1358
+ frames,
1359
+ selfSampleCount: 0,
1360
+ selfValues: new Float64Array(this.#metrics.length)
1361
+ };
1362
+ this.#keyToCallStack.set(key, callStack);
1363
+ return callStack;
1364
+ }
1365
+ #getOrCreateFunction(node) {
1366
+ const { id } = node;
1367
+ if (id !== void 0) {
1368
+ const func = this.#idToFunction[id];
1369
+ if (func) return func;
1370
+ }
1371
+ const key = this.#functionKey(node);
1372
+ let func = this.#keyToFunction.get(key);
1373
+ if (func) {
1374
+ if (id !== void 0) this.#idToFunction[id] = func;
1375
+ return func;
1376
+ }
1377
+ const { name: nameInput, location: locationInput } = this.#functionInput(node);
1378
+ const entry = {
1379
+ id: this.#keyToFunction.size,
1380
+ name: nameInput || `(anonymous)`,
1381
+ location: locationInput ? makeProfileLocation(locationInput) : void 0
1382
+ };
1383
+ func = {
1384
+ type: `function`,
1385
+ ...entry,
1386
+ category: this.#options.categorizeEntry(entry),
1387
+ selfSampleCount: 0,
1388
+ totalSampleCount: 0,
1389
+ selfValues: new Float64Array(this.#metrics.length),
1390
+ totalValues: new Float64Array(this.#metrics.length),
1391
+ lineToMetrics: /* @__PURE__ */ new Map(),
1392
+ callerIdToMetrics: /* @__PURE__ */ new Map(),
1393
+ calleeIdToMetrics: /* @__PURE__ */ new Map()
1394
+ };
1395
+ if (id !== void 0) this.#idToFunction[id] = func;
1396
+ this.#keyToFunction.set(key, func);
1397
+ return func;
1398
+ }
1399
+ aggregate() {
1400
+ const samplingRates = new Float64Array(this.#metrics.length);
1401
+ for (let i = 0; i < samplingRates.length; i++) samplingRates[i] = this.#totalValues[i] / this.#totalSampleCount;
1402
+ const functions = [...this.#keyToFunction.values()];
1403
+ const callStacks = [...this.#keyToCallStack.values()];
1404
+ return {
1405
+ metrics: this.#metrics,
1406
+ totalSampleCount: this.#totalSampleCount,
1407
+ totalValues: this.#totalValues,
1408
+ samplingRates,
1409
+ categoryToMetrics: this.#categoryToMetrics,
1410
+ functions,
1411
+ callStacks
1412
+ };
1413
+ }
1414
+ };
1415
+ /**
1416
+ * Returns the list of callers of {@link callStacks} that is the longest common
1417
+ * suffix of their frames, except it never returns a call stack as long as one
1418
+ * of the input call stacks.
1419
+ *
1420
+ * This behavior is so that it's safe to remove that suffix from any of the call
1421
+ * stacks and end up with a non-empty call stack to format.
1422
+ */
1423
+ const findCommonCallStack = (callStacks) => {
1424
+ if (callStacks.length <= 1) return [];
1425
+ const minLength = Math.min(...callStacks.map((cs) => cs.frames.length));
1426
+ const firstFrames = callStacks[0].frames;
1427
+ let suffixLength = 0;
1428
+ for (let i = 1; i < minLength; i++) {
1429
+ const suffix = firstFrames.slice(-i).map((frame) => frame.id);
1430
+ if (callStacks.every((callStack) => callStack.frames.slice(-i).every((frame, j) => frame.id === suffix[j]))) suffixLength = i;
1431
+ else break;
1432
+ }
1433
+ return suffixLength > 0 ? firstFrames.slice(-suffixLength) : [];
1434
+ };
1435
+
1436
+ //#endregion
1437
+ //#region src/profile/format.ts
1438
+ const formatProfile = (profile, options) => {
1439
+ const headingLevel = 1;
1440
+ return `${[
1441
+ formatHeading(headingLevel, formatTitle(profile)),
1442
+ ...formatOverallSummary(profile),
1443
+ ...formatMetricSections(profile, {
1444
+ ...options,
1445
+ headingLevel: headingLevel + 1
1446
+ })
1447
+ ].join(`\n\n`)}\n`;
1448
+ };
1449
+ const formatTitle = (profile) => capitalizeFirst(`${formatConjunction(profile.metrics.map((metric) => metric.phrases.titleNoun))} profile`);
1450
+ const formatOverallSummary = (profile) => [formatSummaryLine(profile), ...formatCategoryTable(profile)];
1451
+ const formatSummaryLine = ({ metrics, totalSampleCount, totalValues, samplingRates }) => {
1452
+ const totalsSummary = capitalizeFirst(formatConjunction(metrics.map((metric, index) => `${metric.phrases.pastTenseVerb} ${formatValue(totalValues[index], metric)}`)));
1453
+ const samplingRatesSummary = `(${formatConjunction(Array.from(samplingRates, (rate, index) => formatSamplingRate(rate, metrics[index])))} per sample)`;
1454
+ return `${totalsSummary} over ${formatCount(totalSampleCount, `sample`)} ${samplingRatesSummary}.`;
1455
+ };
1456
+ const formatCategoryTable = ({ metrics, totalValues, categoryToMetrics }) => {
1457
+ const hottestCategories = [...categoryToMetrics].sort(([, metrics1], [, metrics2]) => metrics2.values[0] - metrics1.values[0]);
1458
+ if (hottestCategories.length === 0) return [];
1459
+ return [formatTable([
1460
+ `Category`,
1461
+ {
1462
+ content: `%`,
1463
+ align: `right`
1464
+ },
1465
+ ...metrics.map((metric) => ({
1466
+ content: capitalizeFirst(metric.phrases.columnNoun),
1467
+ align: `right`
1468
+ })),
1469
+ {
1470
+ content: `Samples`,
1471
+ align: `right`
1472
+ }
1473
+ ], hottestCategories.map(([category, { values, sampleCount }]) => [
1474
+ category,
1475
+ formatPercent(values[0] / totalValues[0]),
1476
+ ...metrics.map((metric, index) => formatValue(values[index], metric)),
1477
+ formatCount(sampleCount)
1478
+ ]))];
1479
+ };
1480
+ const formatSamplingRate = (samplingRate, metric) => {
1481
+ switch (metric.type) {
1482
+ case `time`: return formatMicroseconds(samplingRate * 1e3 * metric.milliseconds);
1483
+ case `size`: return formatBytes(samplingRate * metric.bytes);
1484
+ case `custom`: return formatCount(samplingRate, metric.unit);
1485
+ }
1486
+ };
1487
+ const formatMetricSections = (profile, options) => profile.metrics.flatMap((metric, index) => {
1488
+ const sections = [];
1489
+ let sectionOptions = options;
1490
+ if (profile.metrics.length > 1) {
1491
+ sections.push(formatHeading(options.headingLevel, capitalizeFirst(metric.phrases.titleNoun)));
1492
+ sectionOptions = {
1493
+ ...options,
1494
+ headingLevel: options.headingLevel + 1
1495
+ };
1496
+ }
1497
+ return [
1498
+ ...sections,
1499
+ ...formatHottestFunctions(index, profile, sectionOptions),
1500
+ ...formatHottestCallStacks(index, profile, sectionOptions)
1501
+ ];
1502
+ });
1503
+ const formatHottestFunctions = (metricIndex, profile, options) => {
1504
+ const subsectionOptions = {
1505
+ ...options,
1506
+ headingLevel: options.headingLevel + 1
1507
+ };
1508
+ const functionsSections = [...formatHottestSelfFunctions(metricIndex, profile, subsectionOptions), ...formatHottestTotalFunctions(metricIndex, profile, subsectionOptions)];
1509
+ if (functionsSections.length === 0) return [];
1510
+ return [formatHeading(options.headingLevel, `Hottest functions`), ...functionsSections];
1511
+ };
1512
+ const formatHottestSelfFunctions = (metricIndex, profile, options) => {
1513
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.showEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (func) => func.selfValues[metricIndex]);
1514
+ if (hottestFunctions.length === 0) return [];
1515
+ const subsectionOptions = {
1516
+ ...options,
1517
+ headingLevel: options.headingLevel + 2
1518
+ };
1519
+ const hottestLinesSections = hottestFunctions.filter((func) => func.lineToMetrics.size > 0).flatMap((func) => formatHottestLines(metricIndex, func, profile, subsectionOptions));
1520
+ const hottestCallersSections = hottestFunctions.flatMap((func) => formatHottestCallers(metricIndex, func, profile, subsectionOptions));
1521
+ const metric = profile.metrics[metricIndex];
1522
+ return [
1523
+ formatHeading(options.headingLevel, `Self ${metric.phrases.columnNoun}`),
1524
+ `Functions ranked by ${metric.phrases.pastParticipleVerbPhrase} directly in the function body, excluding callees.`,
1525
+ formatTable([
1526
+ {
1527
+ content: `%`,
1528
+ align: `right`
1529
+ },
1530
+ {
1531
+ content: capitalizeFirst(metric.phrases.columnNoun),
1532
+ align: `right`
1533
+ },
1534
+ {
1535
+ content: `Samples`,
1536
+ align: `right`
1537
+ },
1538
+ `Function`,
1539
+ `Location`
1540
+ ], hottestFunctions.map((func) => [
1541
+ formatPercent(func.selfValues[metricIndex] / profile.totalValues[metricIndex]),
1542
+ formatValue(func.selfValues[metricIndex], metric),
1543
+ formatCount(func.selfSampleCount),
1544
+ inlineCode(func.name),
1545
+ formatProfileLocation(func.location, options)
1546
+ ])),
1547
+ ...hottestLinesSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Lines`), `Lines ranked by contribution to each function's self ${metric.phrases.columnNoun}.`] : [],
1548
+ ...hottestLinesSections,
1549
+ ...hottestCallersSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callers`), `Callers ranked by contribution to each function's self ${metric.phrases.columnNoun}. Caller attribution may be imprecise due to inlining.`] : [],
1550
+ ...hottestCallersSections
1551
+ ];
1552
+ };
1553
+ const formatHottestLines = (metricIndex, func, profile, options) => {
1554
+ const selfValue = func.selfValues[metricIndex];
1555
+ const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics]) => metrics.values[metricIndex]);
1556
+ if (hottestLines.length === 0) return [];
1557
+ const metric = profile.metrics[metricIndex];
1558
+ return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
1559
+ {
1560
+ content: `%`,
1561
+ align: `right`
1562
+ },
1563
+ {
1564
+ content: capitalizeFirst(metric.phrases.columnNoun),
1565
+ align: `right`
1566
+ },
1567
+ {
1568
+ content: `Samples`,
1569
+ align: `right`
1570
+ },
1571
+ `Location`
1572
+ ], hottestLines.map(([line, stats]) => [
1573
+ formatPercent(stats.values[metricIndex] / selfValue),
1574
+ formatValue(stats.values[metricIndex], metric),
1575
+ formatCount(stats.sampleCount),
1576
+ func.location ? formatProfileLocation({
1577
+ ...func.location,
1578
+ line,
1579
+ column: void 0
1580
+ }, options) : String(line)
1581
+ ]))];
1582
+ };
1583
+ const formatHottestCallers = (metricIndex, func, profile, options) => {
1584
+ const selfValue = func.selfValues[metricIndex];
1585
+ const hottestCallers = selectTopN([...func.callerIdToMetrics.values()].filter((entry) => options.showEntry(entry.caller) && entry.selfValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.selfValues[metricIndex]);
1586
+ if (hottestCallers.length === 0) return [];
1587
+ const metric = profile.metrics[metricIndex];
1588
+ return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
1589
+ {
1590
+ content: `%`,
1591
+ align: `right`
1592
+ },
1593
+ {
1594
+ content: capitalizeFirst(metric.phrases.columnNoun),
1595
+ align: `right`
1596
+ },
1597
+ {
1598
+ content: `Samples`,
1599
+ align: `right`
1600
+ },
1601
+ `Caller`,
1602
+ `Location`
1603
+ ], hottestCallers.map(({ caller, selfValues, selfSampleCount }) => [
1604
+ formatPercent(selfValues[metricIndex] / selfValue),
1605
+ formatValue(selfValues[metricIndex], metric),
1606
+ formatCount(selfSampleCount),
1607
+ inlineCode(caller.name),
1608
+ formatProfileLocation(caller.location, options)
1609
+ ]))];
1610
+ };
1611
+ const formatHottestTotalFunctions = (metricIndex, profile, options) => {
1612
+ const totalValue = profile.totalValues[metricIndex];
1613
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.showEntry(func) && func.totalValues[metricIndex] > 0), options.topN, (func) => func.totalValues[metricIndex]);
1614
+ if (hottestFunctions.length === 0) return [];
1615
+ const subsectionOptions = {
1616
+ ...options,
1617
+ headingLevel: options.headingLevel + 2
1618
+ };
1619
+ const calleeSections = hottestFunctions.flatMap((func) => formatHottestCallees(metricIndex, func, profile, subsectionOptions));
1620
+ const metric = profile.metrics[metricIndex];
1621
+ return [
1622
+ formatHeading(options.headingLevel, `Total ${metric.phrases.columnNoun}`),
1623
+ `Functions ranked by total ${metric.phrases.pastParticipleVerbPhrase} in the function and all its callees.`,
1624
+ formatTable([
1625
+ {
1626
+ content: `%`,
1627
+ align: `right`
1628
+ },
1629
+ {
1630
+ content: capitalizeFirst(metric.phrases.columnNoun),
1631
+ align: `right`
1632
+ },
1633
+ {
1634
+ content: `Samples`,
1635
+ align: `right`
1636
+ },
1637
+ `Function`,
1638
+ `Location`
1639
+ ], hottestFunctions.map((func) => [
1640
+ formatPercent(func.totalValues[metricIndex] / totalValue),
1641
+ formatValue(func.totalValues[metricIndex], metric),
1642
+ formatCount(func.totalSampleCount),
1643
+ inlineCode(func.name),
1644
+ formatProfileLocation(func.location, options)
1645
+ ])),
1646
+ ...calleeSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callees`), `Callees ranked by contribution to each function's total ${metric.phrases.columnNoun}. Callee attribution may be imprecise due to inlining.`] : [],
1647
+ ...calleeSections
1648
+ ];
1649
+ };
1650
+ const formatHottestCallees = (metricIndex, func, profile, options) => {
1651
+ const totalValue = func.totalValues[metricIndex];
1652
+ const hottestCallees = selectTopN([...func.calleeIdToMetrics.values()].filter((entry) => options.showEntry(entry.callee) && entry.totalValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.totalValues[metricIndex]);
1653
+ if (hottestCallees.length === 0) return [];
1654
+ const metric = profile.metrics[metricIndex];
1655
+ return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
1656
+ {
1657
+ content: `%`,
1658
+ align: `right`
1659
+ },
1660
+ {
1661
+ content: capitalizeFirst(metric.phrases.columnNoun),
1662
+ align: `right`
1663
+ },
1664
+ {
1665
+ content: `Samples`,
1666
+ align: `right`
1667
+ },
1668
+ `Callee`,
1669
+ `Location`
1670
+ ], hottestCallees.map(({ callee, totalValues, totalSampleCount }) => [
1671
+ formatPercent(totalValues[metricIndex] / totalValue),
1672
+ formatValue(totalValues[metricIndex], metric),
1673
+ formatCount(totalSampleCount),
1674
+ inlineCode(callee.name),
1675
+ formatProfileLocation(callee.location, options)
1676
+ ]))];
1677
+ };
1678
+ const formatHottestCallStacks = (metricIndex, profile, options) => {
1679
+ const totalValue = profile.totalValues[metricIndex];
1680
+ const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
1681
+ ...callStack,
1682
+ frames: callStack.frames.filter(options.showEntry)
1683
+ })).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack) => callStack.selfValues[metricIndex]);
1684
+ if (hottestCallStacks.length === 0) return [];
1685
+ const metric = profile.metrics[metricIndex];
1686
+ const commonCallStack = findCommonCallStack(hottestCallStacks);
1687
+ return [
1688
+ formatHeading(options.headingLevel, `Hottest call stacks`),
1689
+ `Call stacks ranked by ${metric.phrases.pastParticipleVerbPhrase} in their leaf frame.`,
1690
+ ...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack, options)}`] : [],
1691
+ formatTable([
1692
+ {
1693
+ content: `%`,
1694
+ align: `right`
1695
+ },
1696
+ {
1697
+ content: capitalizeFirst(metric.phrases.columnNoun),
1698
+ align: `right`
1699
+ },
1700
+ {
1701
+ content: `Samples`,
1702
+ align: `right`
1703
+ },
1704
+ `Call stack`
1705
+ ], hottestCallStacks.map(({ frames, selfValues, selfSampleCount }) => [
1706
+ formatPercent(selfValues[metricIndex] / totalValue),
1707
+ formatValue(selfValues[metricIndex], metric),
1708
+ formatCount(selfSampleCount),
1709
+ formatCallStack(commonCallStack.length > 0 ? frames.slice(0, -commonCallStack.length) : frames, options)
1710
+ ]))
1711
+ ];
1712
+ };
1713
+ const formatCallStack = (nodes, options) => nodes.map((node, index) => {
1714
+ const name = inlineCode(node.name);
1715
+ if (!node.location) return name;
1716
+ const previousHref = nodes[index - 1]?.location?.url.href;
1717
+ if (!previousHref || node.location.url.href !== previousHref) return `${name} (${formatProfileLocation(node.location, options)})`;
1718
+ const { line, column } = node.location;
1719
+ if (line === void 0) return name;
1720
+ return `${name} (${line}${column === void 0 ? `` : `:${column}`})`;
1721
+ }).join(` ← `);
1722
+ const formatValue = (value, metric) => {
1723
+ switch (metric.type) {
1724
+ case `time`: return formatMilliseconds(value * metric.milliseconds);
1725
+ case `size`: return formatBytes(value * metric.bytes);
1726
+ case `custom`: return formatCount(value, metric.unit);
1727
+ }
1728
+ };
1729
+ const capitalizeFirst = (string) => string.length === 0 ? string : string[0].toUpperCase() + string.slice(1);
1730
+
1731
+ //#endregion
1732
+ //#region src/profile/metric.ts
1733
+ const determineMetric = ({ name, unit }) => {
1734
+ const metric = UNIT_TO_METRIC.get(unit.toLowerCase()) ?? {
1735
+ type: `custom`,
1736
+ unit,
1737
+ phrases: {
1738
+ titleNoun: name,
1739
+ columnNoun: name,
1740
+ pastTenseVerb: `recorded`,
1741
+ pastParticipleVerbPhrase: `${name} recorded`
1742
+ }
1743
+ };
1744
+ const phrases = METRIC_TYPE_AND_NAME_TO_PHRASES.get(metric.type)?.get(name.toLowerCase());
1745
+ if (phrases) return {
1746
+ ...metric,
1747
+ phrases
1748
+ };
1749
+ return metric;
1750
+ };
1751
+ const TIME_PHRASES = {
1752
+ titleNoun: `CPU`,
1753
+ columnNoun: `time`,
1754
+ pastTenseVerb: `took`,
1755
+ pastParticipleVerbPhrase: `time spent`
1756
+ };
1757
+ const SIZE_PHRASES = {
1758
+ titleNoun: `heap`,
1759
+ columnNoun: `size`,
1760
+ pastTenseVerb: `allocated`,
1761
+ pastParticipleVerbPhrase: `bytes allocated`
1762
+ };
1763
+ const NANOSECONDS = {
1764
+ type: `time`,
1765
+ milliseconds: 1e-6,
1766
+ phrases: TIME_PHRASES
1767
+ };
1768
+ const MICROSECONDS = {
1769
+ type: `time`,
1770
+ milliseconds: .001,
1771
+ phrases: TIME_PHRASES
1772
+ };
1773
+ const MILLISECONDS = {
1774
+ type: `time`,
1775
+ milliseconds: 1,
1776
+ phrases: TIME_PHRASES
1777
+ };
1778
+ const SECONDS = {
1779
+ type: `time`,
1780
+ milliseconds: 1e3,
1781
+ phrases: TIME_PHRASES
1782
+ };
1783
+ const BYTES = {
1784
+ type: `size`,
1785
+ bytes: 1,
1786
+ phrases: SIZE_PHRASES
1787
+ };
1788
+ const KILOBYTES = {
1789
+ type: `size`,
1790
+ bytes: 1024,
1791
+ phrases: SIZE_PHRASES
1792
+ };
1793
+ const MEGABYTES = {
1794
+ type: `size`,
1795
+ bytes: 1 << 20,
1796
+ phrases: SIZE_PHRASES
1797
+ };
1798
+ const GIGABYTES = {
1799
+ type: `size`,
1800
+ bytes: 1 << 30,
1801
+ phrases: SIZE_PHRASES
1802
+ };
1803
+ const UNIT_TO_METRIC = new Map([
1804
+ [`nanoseconds`, NANOSECONDS],
1805
+ [`nanosecond`, NANOSECONDS],
1806
+ [`nanos`, NANOSECONDS],
1807
+ [`ns`, NANOSECONDS],
1808
+ [`microseconds`, MICROSECONDS],
1809
+ [`microsecond`, MICROSECONDS],
1810
+ [`micros`, MICROSECONDS],
1811
+ [`us`, MICROSECONDS],
1812
+ [`μs`, MICROSECONDS],
1813
+ [`milliseconds`, MILLISECONDS],
1814
+ [`millisecond`, MILLISECONDS],
1815
+ [`millis`, MILLISECONDS],
1816
+ [`ms`, MILLISECONDS],
1817
+ [`seconds`, SECONDS],
1818
+ [`second`, SECONDS],
1819
+ [`secs`, SECONDS],
1820
+ [`sec`, SECONDS],
1821
+ [`s`, SECONDS],
1822
+ [`bytes`, BYTES],
1823
+ [`byte`, BYTES],
1824
+ [`b`, BYTES],
1825
+ [`kilobytes`, KILOBYTES],
1826
+ [`kilobyte`, KILOBYTES],
1827
+ [`kbytes`, KILOBYTES],
1828
+ [`kbyte`, KILOBYTES],
1829
+ [`kb`, KILOBYTES],
1830
+ [`megabytes`, MEGABYTES],
1831
+ [`megabyte`, MEGABYTES],
1832
+ [`mbytes`, MEGABYTES],
1833
+ [`mbyte`, MEGABYTES],
1834
+ [`mb`, MEGABYTES],
1835
+ [`gigabytes`, GIGABYTES],
1836
+ [`gigabyte`, GIGABYTES],
1837
+ [`gbytes`, GIGABYTES],
1838
+ [`gbyte`, GIGABYTES],
1839
+ [`gb`, GIGABYTES],
1840
+ [`none`, {
1841
+ type: `custom`,
1842
+ unit: `count`,
1843
+ phrases: {
1844
+ titleNoun: `count`,
1845
+ columnNoun: `count`,
1846
+ pastTenseVerb: `recorded`,
1847
+ pastParticipleVerbPhrase: `count recorded`
1848
+ }
1849
+ }]
1850
+ ]);
1851
+ const METRIC_TYPE_AND_NAME_TO_PHRASES = new Map([[`size`, new Map([[`alloc_space`, {
1852
+ titleNoun: `allocated heap`,
1853
+ columnNoun: `size`,
1854
+ pastTenseVerb: `allocated`,
1855
+ pastParticipleVerbPhrase: `bytes allocated`
1856
+ }], [`inuse_space`, {
1857
+ titleNoun: `retained heap`,
1858
+ columnNoun: `size`,
1859
+ pastTenseVerb: `retained`,
1860
+ pastParticipleVerbPhrase: `bytes retained`
1861
+ }]])]]);
1862
+
1863
+ //#endregion
1864
+ //#region src/formats/pprof/aggregate.ts
1865
+ const aggregatePprof = ({ valueTypes, samples, locations, functions }, options) => {
1866
+ const nonCountValueTypes = [...valueTypes.entries()].filter(([, valueType]) => valueType.unit.toLowerCase() !== `count`);
1867
+ const profileAggregator = new ProfileAggregator({
1868
+ metrics: nonCountValueTypes.map(([, valueType]) => determineMetric({
1869
+ name: valueType.type,
1870
+ unit: valueType.unit
1871
+ })),
1872
+ functionKey: (func) => func.id,
1873
+ functionInput: (func) => ({
1874
+ name: func.name || func.systemName,
1875
+ location: {
1876
+ urlOrPath: func.filename,
1877
+ line: func.startLine > 0 ? func.startLine : void 0
1878
+ }
1879
+ })
1880
+ }, options);
1881
+ for (const sample of samples) {
1882
+ const { locationIds, values } = sample;
1883
+ const nodes = [];
1884
+ let calleeLine;
1885
+ for (const locationId of locationIds) {
1886
+ const location = locations[locationId];
1887
+ for (const { functionId, line } of location.lines) {
1888
+ nodes.push(functions[functionId]);
1889
+ calleeLine ??= line;
1890
+ }
1891
+ }
1892
+ if (nodes.length === 0) continue;
1893
+ profileAggregator.addSample({
1894
+ values: nonCountValueTypes.map(([index]) => values[index]),
1895
+ nodes,
1896
+ line: calleeLine
1897
+ });
1898
+ }
1899
+ return profileAggregator.aggregate();
1900
+ };
1901
+
1902
+ //#endregion
1903
+ //#region src/helpers/bytes.ts
1904
+ const streamToUint8Array = async (stream) => {
1905
+ const chunks = [];
1906
+ const reader = stream.getReader();
1907
+ try {
1908
+ while (true) {
1909
+ const { done, value } = await reader.read();
1910
+ if (done) break;
1911
+ chunks.push(value);
1912
+ }
1913
+ } finally {
1914
+ reader.releaseLock();
1915
+ }
1916
+ return concatUint8Arrays(chunks);
1917
+ };
1918
+ const concatUint8Arrays = (arrays) => {
1919
+ const arrayArray = Array.isArray(arrays) ? arrays : [...arrays];
1920
+ const concatenated = new Uint8Array(arrayArray.reduce((size, array) => size + array.length, 0));
1921
+ let offset = 0;
1922
+ for (const array of arrayArray) {
1923
+ concatenated.set(array, offset);
1924
+ offset += array.length;
1925
+ }
1926
+ return concatenated;
1927
+ };
1928
+
1929
+ //#endregion
1930
+ //#region src/formats/pprof/parse.ts
1931
+ const parsePprofAsync = async (data) => parsePprof(await (data instanceof Blob ? data.bytes() : streamToUint8Array(data)));
1932
+ const parsePprof = (data) => {
1933
+ if (!ArrayBuffer.isView(data)) {
1934
+ if (!Array.isArray(data)) data = [...data];
1935
+ data = concatUint8Arrays(data);
1936
+ }
1937
+ return parsePprofInternal(Profile.decode(data));
1938
+ };
1939
+ const parsePprofInternal = (profile) => {
1940
+ const { strings } = profile.stringTable;
1941
+ const valueTypes = profile.sampleType.map(({ type, unit }) => ({
1942
+ type: strings[Number(type)] ?? ``,
1943
+ unit: strings[Number(unit)] ?? ``
1944
+ }));
1945
+ const functionIdToIndex = [];
1946
+ const functions = [];
1947
+ for (const func of profile.function) {
1948
+ const id = Number(func.id);
1949
+ functionIdToIndex[id] = functions.length;
1950
+ functions.push({
1951
+ id,
1952
+ name: strings[Number(func.name)] ?? ``,
1953
+ systemName: strings[Number(func.systemName)] ?? ``,
1954
+ filename: strings[Number(func.filename)] ?? ``,
1955
+ startLine: Number(func.startLine)
1956
+ });
1957
+ }
1958
+ const locationIdToIndex = [];
1959
+ const locations = [];
1960
+ for (const location of profile.location) {
1961
+ const id = Number(location.id);
1962
+ locationIdToIndex[id] = locations.length;
1963
+ locations.push({
1964
+ id,
1965
+ lines: location.line.map(({ functionId, line }) => ({
1966
+ functionId: functionIdToIndex[Number(functionId)],
1967
+ line: Number(line)
1968
+ }))
1969
+ });
1970
+ }
1971
+ return {
1972
+ valueTypes,
1973
+ samples: profile.sample.map(({ locationId, value }) => ({
1974
+ locationIds: locationId.map((id) => locationIdToIndex[Number(id)]),
1975
+ values: value.map(Number)
1976
+ })),
1977
+ locations,
1978
+ functions
1979
+ };
1980
+ };
1981
+
1982
+ //#endregion
1983
+ //#region src/formats/pprof/index.ts
1984
+ const detectPprof = async (data) => {
1985
+ if (data.size === 0) return;
1986
+ let profile;
1987
+ try {
1988
+ profile = Profile.decode(await data.bytes());
1989
+ } catch {
1990
+ return;
1991
+ }
1992
+ if (profile.stringTable.strings[0] !== ``) return;
1993
+ return parsePprofInternal(profile);
1994
+ };
1995
+ /**
1996
+ * Asynchronously converts the given pprof to Markdown.
1997
+ *
1998
+ * It is assumed that {@link data} is a valid pprof (raw protobuf). The behavior
1999
+ * of this function is undefined for invalid profiles.
2000
+ *
2001
+ * See the [pprof docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/pprof.md)
2002
+ * for supported tools and generation instructions (`profiler-md --help pprof`).
2003
+ */
2004
+ const pprofToMdAsync = async (data, options) => pprofToMdInternal(await parsePprofAsync(data), options);
2005
+ const pprofToMdInternal = (pprof, options) => {
2006
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2007
+ return formatProfile(aggregatePprof(pprof, normalizedOptions), normalizedOptions);
2008
+ };
2009
+
2010
+ //#endregion
2011
+ //#region src/formats/speedscope/aggregate.ts
2012
+ const aggregateSpeedscopeProfile = (profile, options) => {
2013
+ const nodes = profile.shared.frames.map((frame, id) => ({
2014
+ ...frame,
2015
+ id
2016
+ }));
2017
+ return profile.profiles.map((profile) => profile.type === `sampled` ? aggregateSampled(profile, nodes, options) : aggregateEvented(profile, nodes, options));
2018
+ };
2019
+ const aggregateSampled = (profile, nodes, options) => {
2020
+ const profileAggregator = makeProfileAggregator(profile.unit, options);
2021
+ for (let index = 0; index < profile.samples.length; index++) {
2022
+ const weight = profile.weights[index];
2023
+ if (weight <= 0) continue;
2024
+ const sampleNodes = profile.samples[index].map((frameIndex) => nodes[frameIndex]).reverse();
2025
+ if (sampleNodes.length === 0) continue;
2026
+ profileAggregator.addSample({
2027
+ values: [weight],
2028
+ nodes: sampleNodes
2029
+ });
2030
+ }
2031
+ return profileAggregator.aggregate();
2032
+ };
2033
+ const aggregateEvented = (profile, nodes, options) => {
2034
+ const profileAggregator = makeProfileAggregator(profile.unit, options);
2035
+ const stack = [];
2036
+ const emitTopSelfTime = (at) => {
2037
+ if (stack.length === 0) return;
2038
+ const top = stack.at(-1);
2039
+ const selfTime = at - top.lastChildClosed;
2040
+ if (selfTime <= 0) return;
2041
+ profileAggregator.addSample({
2042
+ values: [selfTime],
2043
+ nodes: stack.map((entry) => entry.node).reverse()
2044
+ });
2045
+ top.lastChildClosed = at;
2046
+ };
2047
+ for (const event of profile.events) if (event.type === `O`) {
2048
+ emitTopSelfTime(event.at);
2049
+ stack.push({
2050
+ node: nodes[event.frame],
2051
+ lastChildClosed: event.at
2052
+ });
2053
+ } else {
2054
+ emitTopSelfTime(event.at);
2055
+ stack.pop();
2056
+ if (stack.length > 0) stack.at(-1).lastChildClosed = event.at;
2057
+ }
2058
+ return profileAggregator.aggregate();
2059
+ };
2060
+ const makeProfileAggregator = (unit, options) => new ProfileAggregator({
2061
+ metrics: [determineMetric({
2062
+ name: unit,
2063
+ unit
2064
+ })],
2065
+ functionKey: (node) => node.id,
2066
+ functionInput: (node) => ({
2067
+ name: node.name,
2068
+ location: node.file ? {
2069
+ urlOrPath: node.file,
2070
+ line: node.line,
2071
+ column: node.col
2072
+ } : void 0
2073
+ })
2074
+ }, options);
2075
+
2076
+ //#endregion
2077
+ //#region src/formats/speedscope/parse.ts
2078
+ const parseSpeedscopeProfileAsync = (data) => JumboJSON.parseAsync(data);
2079
+
2080
+ //#endregion
2081
+ //#region src/formats/speedscope/index.ts
2082
+ const detectSpeedscopeProfile = (json) => {
2083
+ if (typeof json !== `object` || json === null) return;
2084
+ const object = json;
2085
+ if (object.$schema !== `https://www.speedscope.app/file-format-schema.json` || !Array.isArray(object.profiles) || typeof object.shared !== `object` || object.shared === null) return;
2086
+ return json;
2087
+ };
2088
+ /**
2089
+ * Asynchronously converts the given Speedscope profile to Markdown.
2090
+ *
2091
+ * It is assumed that {@link data} is a valid Speedscope JSON file. The behavior
2092
+ * of this function is undefined for invalid profiles.
2093
+ *
2094
+ * See the [Speedscope docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/speedscope.md)
2095
+ * for supported tools and generation instructions
2096
+ * (`profiler-md --help speedscope`).
2097
+ */
2098
+ const speedscopeProfileToMdAsync = async (data, options) => speedscopeProfileToMdInternal(await parseSpeedscopeProfileAsync(data), options);
2099
+ const speedscopeProfileToMdInternal = (profile, options) => {
2100
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2101
+ return aggregateSpeedscopeProfile(profile, normalizedOptions).map((profile) => formatProfile(profile, normalizedOptions)).join(`\n\n`);
2102
+ };
2103
+
2104
+ //#endregion
2105
+ //#region src/formats/v8/common.ts
2106
+ const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
2107
+ const callFrameFunctionInput = (callFrame) => {
2108
+ const { functionName, url, lineNumber, columnNumber } = callFrame;
2109
+ return {
2110
+ name: functionName,
2111
+ location: url ? {
2112
+ urlOrPath: url,
2113
+ line: lineNumber + 1,
2114
+ column: columnNumber + 1
2115
+ } : void 0
2116
+ };
2117
+ };
2118
+
2119
+ //#endregion
2120
+ //#region src/formats/v8/cpu-profile/aggregate.ts
2121
+ const aggregateV8CpuProfile = (profile, options) => {
2122
+ const profileAggregator = new ProfileAggregator({
2123
+ metrics: [MICROSECONDS],
2124
+ functionKey: (node) => callFrameKey(node.callFrame),
2125
+ functionInput: (node) => callFrameFunctionInput(node.callFrame)
2126
+ }, options);
2127
+ const idToIndex = [];
2128
+ for (let index = 0; index < profile.nodes.length; index++) {
2129
+ const node = profile.nodes[index];
2130
+ idToIndex[node.id] = index;
2131
+ node.id = index;
2132
+ }
2133
+ const indexToParentIndex = new Int32Array(profile.nodes.length).fill(-1);
2134
+ for (const node of profile.nodes) if (node.children) for (const childId of node.children) {
2135
+ const childIndex = idToIndex[childId];
2136
+ if (childIndex === void 0) continue;
2137
+ indexToParentIndex[childIndex] = node.id;
2138
+ }
2139
+ const indexToSelfTime = new Float64Array(profile.nodes.length);
2140
+ for (let index = 0; index < profile.samples.length; index++) {
2141
+ const nodeIndex = idToIndex[profile.samples[index]];
2142
+ if (nodeIndex === void 0) continue;
2143
+ const node = profile.nodes[nodeIndex];
2144
+ const timeDelta = profile.timeDeltas[index];
2145
+ indexToSelfTime[nodeIndex] += timeDelta;
2146
+ const nodes = [];
2147
+ let currentNode = node;
2148
+ while (true) {
2149
+ nodes.push(currentNode);
2150
+ const parentIndex = indexToParentIndex[currentNode.id];
2151
+ if (parentIndex === -1) break;
2152
+ currentNode = profile.nodes[parentIndex];
2153
+ }
2154
+ profileAggregator.addSample({
2155
+ values: [timeDelta],
2156
+ nodes
2157
+ });
2158
+ }
2159
+ for (const node of profile.nodes) {
2160
+ if (!node.positionTicks) continue;
2161
+ const selfTime = indexToSelfTime[node.id];
2162
+ profileAggregator.addLineMetrics({
2163
+ node,
2164
+ lines: node.positionTicks.map(({ line, ticks }) => ({
2165
+ line,
2166
+ sampleCount: ticks,
2167
+ values: [Math.round(selfTime * ticks / node.hitCount)]
2168
+ }))
2169
+ });
2170
+ }
2171
+ return profileAggregator.aggregate();
2172
+ };
2173
+
2174
+ //#endregion
2175
+ //#region src/formats/v8/cpu-profile/parse.ts
2176
+ const parseV8CpuProfileAsync = (data) => JumboJSON.parseAsync(data);
2177
+
2178
+ //#endregion
2179
+ //#region src/formats/v8/cpu-profile/index.ts
2180
+ const detectV8CpuProfile = (json) => {
2181
+ if (typeof json !== `object` || json === null) return;
2182
+ const object = json;
2183
+ if (!Array.isArray(object.nodes) || !Array.isArray(object.timeDeltas)) return;
2184
+ return json;
2185
+ };
2186
+ /**
2187
+ * Asynchronously converts the given V8 CPU profile to Markdown.
2188
+ *
2189
+ * It is assumed that {@link data} is a valid profile. The behavior of this
2190
+ * function is undefined for invalid profiles.
2191
+ *
2192
+ * See the [V8 CPU profile docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-cpu-profile.md)
2193
+ * for supported runtimes and generation instructions
2194
+ * (`profiler-md --help v8-cpu-profile`).
2195
+ */
2196
+ const v8CpuProfileToMdAsync = async (data, options) => v8CpuProfileToMdInternal(await parseV8CpuProfileAsync(data), options);
2197
+ const v8CpuProfileToMdInternal = (profile, options) => {
2198
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2199
+ return formatProfile(aggregateV8CpuProfile(profile, normalizedOptions), normalizedOptions);
2200
+ };
2201
+
2202
+ //#endregion
2203
+ //#region src/formats/v8/heap-profile/aggregate.ts
2204
+ const aggregateV8HeapProfile = (profile, options) => {
2205
+ const profileAggregator = new ProfileAggregator({
2206
+ metrics: [BYTES],
2207
+ functionKey: (node) => callFrameKey(node.callFrame),
2208
+ functionInput: (node) => callFrameFunctionInput(node.callFrame)
2209
+ }, options);
2210
+ const flatNodes = [];
2211
+ const idToIndex = [];
2212
+ const indexToParentIndex = [];
2213
+ const stack = [{
2214
+ node: profile.head,
2215
+ parentIndex: -1
2216
+ }];
2217
+ do {
2218
+ const { node, parentIndex } = stack.pop();
2219
+ const index = flatNodes.length;
2220
+ idToIndex[node.id] = index;
2221
+ node.id = index;
2222
+ flatNodes.push(node);
2223
+ indexToParentIndex.push(parentIndex);
2224
+ for (const child of node.children) stack.push({
2225
+ node: child,
2226
+ parentIndex: index
2227
+ });
2228
+ } while (stack.length > 0);
2229
+ for (const { size, nodeId } of profile.samples) {
2230
+ const nodeIndex = idToIndex[nodeId];
2231
+ if (nodeIndex === void 0) continue;
2232
+ const nodes = [];
2233
+ let currentIndex = nodeIndex;
2234
+ while (true) {
2235
+ nodes.push(flatNodes[currentIndex]);
2236
+ const parentIndex = indexToParentIndex[currentIndex];
2237
+ if (parentIndex === -1) break;
2238
+ currentIndex = parentIndex;
2239
+ }
2240
+ profileAggregator.addSample({
2241
+ values: [size],
2242
+ nodes
2243
+ });
2244
+ }
2245
+ return profileAggregator.aggregate();
2246
+ };
2247
+
2248
+ //#endregion
2249
+ //#region src/formats/v8/heap-profile/parse.ts
2250
+ const parseV8HeapProfileAsync = (data) => JumboJSON.parseAsync(data);
2251
+
2252
+ //#endregion
2253
+ //#region src/formats/v8/heap-profile/index.ts
2254
+ const detectV8HeapProfile = (json) => {
2255
+ if (typeof json !== `object` || json === null) return;
2256
+ const object = json;
2257
+ if (typeof object.head !== `object` || object.head === null || !Array.isArray(object.samples)) return;
2258
+ return json;
2259
+ };
2260
+ /**
2261
+ * Asynchronously converts the given V8 sampling heap profile to Markdown.
2262
+ *
2263
+ * It is assumed that {@link data} is a valid profile. The behavior of this
2264
+ * function is undefined for invalid profiles.
2265
+ *
2266
+ * See the [V8 heap profile docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-heap-profile.md)
2267
+ * for supported runtimes and generation instructions
2268
+ * (`profiler-md --help v8-heap-profile`).
2269
+ */
2270
+ const v8HeapProfileToMdAsync = async (data, options) => v8HeapProfileToMdInternal(await parseV8HeapProfileAsync(data), options);
2271
+ const v8HeapProfileToMdInternal = (profile, options) => {
2272
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2273
+ return formatProfile(aggregateV8HeapProfile(profile, normalizedOptions), normalizedOptions);
2274
+ };
2275
+
2276
+ //#endregion
2277
+ //#region src/formats/v8/heap-snapshot/aggregate.ts
2278
+ const aggregateV8HeapSnapshot = (snapshot, options) => {
2279
+ const { snapshot: { meta, node_count: nodeCount, edge_count: edgeCount }, nodes } = snapshot;
2280
+ const [nodeTypes] = meta.node_types;
2281
+ const fieldLayout = computeFieldLayout(meta);
2282
+ const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
2283
+ const nodeOrdinalToLocation = computeNodeOrdinalToLocation(snapshot, nodeAdjacencyGraph, fieldLayout);
2284
+ const snapshotAggregator = new SnapshotAggregator({
2285
+ nodeCount,
2286
+ edgeCount,
2287
+ nodeAdjacencyGraph,
2288
+ nodes,
2289
+ nodeFieldCount: fieldLayout.nodeFieldCount,
2290
+ nodeSelfSizeOffset: fieldLayout.nodeSelfSizeOffset,
2291
+ formatEdgeLabel: (retainerOrdinal, edgeIndex) => {
2292
+ const edgeLabel = formatEdgeLabel(edgeIndex, snapshot, fieldLayout, options);
2293
+ const retainerLabel = formatNodeLabel(retainerOrdinal, snapshot, fieldLayout, options);
2294
+ const retainerLocation = nodeOrdinalToLocation[retainerOrdinal];
2295
+ return `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${formatProfileLocation(retainerLocation, options)})` : ``}`;
2296
+ },
2297
+ formatNodeLabel: (nodeOrdinal) => formatNodeLabel(nodeOrdinal, snapshot, fieldLayout, options),
2298
+ isInternalNode: (nodeOrdinal) => {
2299
+ const nodeType = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeTypeOffset];
2300
+ return nodeType === fieldLayout.nodeTypeHidden || nodeType === fieldLayout.nodeTypeSynthetic;
2301
+ }
2302
+ });
2303
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
2304
+ const nodeType = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeTypeOffset];
2305
+ const category = nodeTypes[nodeType];
2306
+ snapshotAggregator.addCategoryNode(nodeOrdinal, category);
2307
+ switch (nodeType) {
2308
+ case fieldLayout.nodeTypeObject:
2309
+ case fieldLayout.nodeTypeNative:
2310
+ snapshotAggregator.addConstructorNode(nodeOrdinal, nodeOrdinalToLocation[nodeOrdinal]);
2311
+ break;
2312
+ case fieldLayout.nodeTypeClosure:
2313
+ snapshotAggregator.addClosureNode(nodeOrdinal, nodeOrdinalToLocation[nodeOrdinal]);
2314
+ break;
2315
+ case fieldLayout.nodeTypeString:
2316
+ case fieldLayout.nodeTypeSlicedString:
2317
+ case fieldLayout.nodeTypeConcatenatedString:
2318
+ snapshotAggregator.addStringNode(nodeOrdinal, formatNodeLabel(nodeOrdinal, snapshot, fieldLayout, options));
2319
+ break;
2320
+ }
2321
+ }
2322
+ return snapshotAggregator.aggregate();
2323
+ };
2324
+ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes, edges }, fieldLayout) => {
2325
+ const ordinalToSuccessorCount = new Int32Array(nodeCount);
2326
+ const ordinalToPredecessorCount = new Int32Array(nodeCount);
2327
+ let nodeEdgesStartIndex = 0;
2328
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
2329
+ const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
2330
+ for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
2331
+ const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
2332
+ if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
2333
+ const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
2334
+ ordinalToSuccessorCount[nodeOrdinal]++;
2335
+ ordinalToPredecessorCount[successorOrdinal]++;
2336
+ }
2337
+ nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
2338
+ }
2339
+ const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
2340
+ const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
2341
+ for (let i = 0; i < nodeCount; i++) {
2342
+ ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
2343
+ ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
2344
+ }
2345
+ const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
2346
+ const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
2347
+ const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
2348
+ const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
2349
+ const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
2350
+ ordinalToSuccessorCount.fill(0);
2351
+ ordinalToPredecessorCount.fill(0);
2352
+ nodeEdgesStartIndex = 0;
2353
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
2354
+ const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
2355
+ for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
2356
+ const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
2357
+ if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
2358
+ const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
2359
+ const successorOffset = ordinalToSuccessorStartOffset[nodeOrdinal] + ordinalToSuccessorCount[nodeOrdinal];
2360
+ offsetToSuccessorOrdinal[successorOffset] = successorOrdinal;
2361
+ offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
2362
+ ordinalToSuccessorCount[nodeOrdinal]++;
2363
+ const predecessorOffset = ordinalToPredecessorStartOffset[successorOrdinal] + ordinalToPredecessorCount[successorOrdinal];
2364
+ offsetToPredecessorOrdinal[predecessorOffset] = nodeOrdinal;
2365
+ offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
2366
+ ordinalToPredecessorCount[successorOrdinal]++;
2367
+ }
2368
+ nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
2369
+ }
2370
+ return {
2371
+ ordinalToSuccessorStartOffset,
2372
+ offsetToSuccessorOrdinal,
2373
+ offsetToSuccessorEdgeIndex,
2374
+ ordinalToPredecessorStartOffset,
2375
+ offsetToPredecessorOrdinal,
2376
+ offsetToPredecessorEdgeIndex
2377
+ };
2378
+ };
2379
+ const computeNodeOrdinalToLocation = ({ snapshot: { node_count: nodeCount }, nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
2380
+ const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
2381
+ const nodeOrdinal = nodeIndex / nodeFieldCount;
2382
+ const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
2383
+ const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
2384
+ for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
2385
+ const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
2386
+ if (strings[edges[edgeIndex + edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + edgeToNodeOffset];
2387
+ }
2388
+ };
2389
+ const scriptIdToFileLocation = /* @__PURE__ */ new Map();
2390
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
2391
+ const scriptId = locations[locationIndex + locationScriptIdOffset];
2392
+ if (scriptIdToFileLocation.has(scriptId)) continue;
2393
+ const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
2394
+ if (nodes[nodeIndex + nodeTypeOffset] !== nodeTypeClosure) continue;
2395
+ const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
2396
+ if (sharedNodeIndex === void 0) continue;
2397
+ const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
2398
+ if (scriptNodeIndex === void 0) continue;
2399
+ const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
2400
+ if (locationNodeIndex === void 0) continue;
2401
+ const location = strings[nodes[locationNodeIndex + nodeNameOffset]];
2402
+ if (!location) continue;
2403
+ scriptIdToFileLocation.set(scriptId, location);
2404
+ }
2405
+ const nodeOrdinalToLocation = Array.from({ length: nodeCount });
2406
+ const fileLocationToUrl = /* @__PURE__ */ new Map();
2407
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
2408
+ const scriptId = locations[locationIndex + locationScriptIdOffset];
2409
+ const fileLocation = scriptIdToFileLocation.get(scriptId);
2410
+ if (!fileLocation) continue;
2411
+ let url = fileLocationToUrl.get(fileLocation);
2412
+ if (url === void 0) {
2413
+ url = makeProfileLocation({ urlOrPath: fileLocation })?.url ?? null;
2414
+ fileLocationToUrl.set(fileLocation, url);
2415
+ }
2416
+ if (!url) continue;
2417
+ const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
2418
+ const line = locations[locationIndex + locationLineOffset];
2419
+ const column = locations[locationIndex + locationColumnOffset];
2420
+ nodeOrdinalToLocation[nodeIndex / nodeFieldCount] = {
2421
+ url,
2422
+ line: line + 1,
2423
+ column: column + 1
2424
+ };
2425
+ }
2426
+ return nodeOrdinalToLocation;
2427
+ };
2428
+ const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) => {
2429
+ const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
2430
+ const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
2431
+ if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
2432
+ const rawEdgeName = strings[edgeNameOrIndex];
2433
+ const edgeLocation = makeProfileLocation({ urlOrPath: rawEdgeName });
2434
+ return `.${edgeLocation ? formatProfileLocation(edgeLocation, options) : rawEdgeName}`;
2435
+ };
2436
+ const formatNodeLabel = (nodeOrdinal, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, strings }, fieldLayout, options) => {
2437
+ const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
2438
+ const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
2439
+ switch (nodeType) {
2440
+ case fieldLayout.nodeTypeString:
2441
+ case fieldLayout.nodeTypeSlicedString:
2442
+ case fieldLayout.nodeTypeConcatenatedString: {
2443
+ const string = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]];
2444
+ return formatString(string);
2445
+ }
2446
+ case fieldLayout.nodeTypeClosure: return strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || `(anonymous)`;
2447
+ default: {
2448
+ const rawNodeName = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || nodeTypes[nodeType];
2449
+ const nodeLocation = makeProfileLocation({ urlOrPath: rawNodeName });
2450
+ return nodeLocation ? formatProfileLocation(nodeLocation, options) : rawNodeName;
2451
+ }
2452
+ }
2453
+ };
2454
+ const formatString = (string) => {
2455
+ if (string.length > MAX_STRING_LENGTH) string = `${string.slice(0, MAX_STRING_LENGTH - 1)}…`;
2456
+ return string.replaceAll(`\n`, `\\n`);
2457
+ };
2458
+ const MAX_STRING_LENGTH = 50;
2459
+ const computeFieldLayout = (meta) => {
2460
+ const { node_fields: nodeFields, node_types: [nodeTypes], edge_fields: edgeFields, edge_types: [edgeTypes], location_fields: locationFields } = meta;
2461
+ const nodeFieldToIndex = valueToIndex(nodeFields);
2462
+ const nodeTypeToIndex = valueToIndex(nodeTypes);
2463
+ const edgeFieldToIndex = valueToIndex(edgeFields);
2464
+ const locationFieldToIndex = valueToIndex(locationFields);
2465
+ const edgeTypeToIndex = valueToIndex(edgeTypes);
2466
+ return {
2467
+ nodeTypeOffset: nodeFieldToIndex.get(`type`),
2468
+ nodeNameOffset: nodeFieldToIndex.get(`name`),
2469
+ nodeSelfSizeOffset: nodeFieldToIndex.get(`self_size`),
2470
+ nodeEdgeCountOffset: nodeFieldToIndex.get(`edge_count`),
2471
+ nodeDetachednessOffset: nodeFieldToIndex.get(`detachedness`),
2472
+ nodeFieldCount: nodeFields.length,
2473
+ edgeTypeOffset: edgeFieldToIndex.get(`type`),
2474
+ edgeNameOrIndexOffset: edgeFieldToIndex.get(`name_or_index`),
2475
+ edgeToNodeOffset: edgeFieldToIndex.get(`to_node`),
2476
+ edgeFieldCount: edgeFields.length,
2477
+ locationObjectIndexOffset: locationFieldToIndex.get(`object_index`),
2478
+ locationScriptIdOffset: locationFieldToIndex.get(`script_id`),
2479
+ locationLineOffset: locationFieldToIndex.get(`line`),
2480
+ locationColumnOffset: locationFieldToIndex.get(`column`),
2481
+ locationFieldCount: locationFields.length,
2482
+ nodeTypeHidden: nodeTypeToIndex.get(`hidden`),
2483
+ nodeTypeArray: nodeTypeToIndex.get(`array`),
2484
+ nodeTypeString: nodeTypeToIndex.get(`string`),
2485
+ nodeTypeObject: nodeTypeToIndex.get(`object`),
2486
+ nodeTypeCode: nodeTypeToIndex.get(`code`),
2487
+ nodeTypeClosure: nodeTypeToIndex.get(`closure`),
2488
+ nodeTypeRegexp: nodeTypeToIndex.get(`regexp`),
2489
+ nodeTypeNumber: nodeTypeToIndex.get(`number`),
2490
+ nodeTypeNative: nodeTypeToIndex.get(`native`),
2491
+ nodeTypeSynthetic: nodeTypeToIndex.get(`synthetic`),
2492
+ nodeTypeConcatenatedString: nodeTypeToIndex.get(`concatenated string`),
2493
+ nodeTypeSlicedString: nodeTypeToIndex.get(`sliced string`),
2494
+ nodeTypeSymbol: nodeTypeToIndex.get(`symbol`),
2495
+ nodeTypeBigint: nodeTypeToIndex.get(`bigint`),
2496
+ nodeTypeObjectShape: nodeTypeToIndex.get(`object shape`),
2497
+ edgeTypeElement: edgeTypeToIndex.get(`element`),
2498
+ edgeTypeInternal: edgeTypeToIndex.get(`internal`),
2499
+ edgeTypeWeak: edgeTypeToIndex.get(`weak`)
2500
+ };
2501
+ };
2502
+ const valueToIndex = (values) => new Map(values.map((value, index) => [value, index]));
2503
+
2504
+ //#endregion
2505
+ //#region src/formats/v8/heap-snapshot/parse.ts
2506
+ const parseV8HeapSnapshotAsync = (data) => JumboJSON.parseAsync(data);
2507
+
2508
+ //#endregion
2509
+ //#region src/formats/v8/heap-snapshot/index.ts
2510
+ const detectV8HeapSnapshot = (json) => {
2511
+ if (typeof json !== `object` || json === null) return;
2512
+ const { snapshot, edges } = json;
2513
+ if (typeof snapshot !== `object` || snapshot === null) return;
2514
+ const { meta } = snapshot;
2515
+ if (typeof meta !== `object` || meta === null || !Array.isArray(meta.node_fields)) return;
2516
+ if (!Array.isArray(edges)) return;
2517
+ return json;
2518
+ };
2519
+ /**
2520
+ * Asynchronously converts the given V8 heap snapshot to Markdown.
2521
+ *
2522
+ * It is assumed that {@link data} is a valid snapshot. The behavior of this
2523
+ * function is undefined for invalid snapshots.
2524
+ *
2525
+ * See the [V8 heap snapshot docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-heap-snapshot.md)
2526
+ * for supported runtimes and generation instructions
2527
+ * (`profiler-md --help v8-heap-snapshot`).
2528
+ */
2529
+ const v8HeapSnapshotToMdAsync = async (data, options) => v8HeapSnapshotToMdInternal(await parseV8HeapSnapshotAsync(data), options);
2530
+ const v8HeapSnapshotToMdInternal = (snapshot, options) => {
2531
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2532
+ return formatHeapSnapshot(aggregateV8HeapSnapshot(snapshot, normalizedOptions), normalizedOptions);
2533
+ };
2534
+
2535
+ //#endregion
2536
+ //#region src/formats/webkit-timeline-recording/aggregate.ts
2537
+ const aggregateWebKitTimelineRecording = ({ recording: { sampleStackTraces, sampleDurations } }, options) => {
2538
+ const profileAggregator = new ProfileAggregator({
2539
+ metrics: [SECONDS],
2540
+ functionKey: (node) => `${node.name}|${node.url}|${node.line}|${node.column}`,
2541
+ functionInput: (node) => ({
2542
+ name: node.name,
2543
+ location: node.url ? {
2544
+ urlOrPath: node.url,
2545
+ line: node.line === -1 ? void 0 : node.line,
2546
+ column: node.column === -1 ? void 0 : node.column
2547
+ } : void 0
2548
+ })
2549
+ }, options);
2550
+ for (let index = 0; index < sampleStackTraces.length; index++) {
2551
+ const duration = sampleDurations[index];
2552
+ const { stackFrames } = sampleStackTraces[index];
2553
+ if (stackFrames.length === 0) continue;
2554
+ const expressionLine = stackFrames[0].expressionLocation?.line;
2555
+ profileAggregator.addSample({
2556
+ values: [duration],
2557
+ nodes: stackFrames,
2558
+ line: expressionLine !== void 0 && expressionLine !== -1 ? expressionLine : void 0
2559
+ });
2560
+ }
2561
+ return profileAggregator.aggregate();
2562
+ };
2563
+
2564
+ //#endregion
2565
+ //#region src/formats/webkit-timeline-recording/parse.ts
2566
+ const parseWebKitTimelineRecordingAsync = (data) => JumboJSON.parseAsync(data);
2567
+
2568
+ //#endregion
2569
+ //#region src/formats/webkit-timeline-recording/index.ts
2570
+ const detectWebKitTimelineRecording = (json) => {
2571
+ if (typeof json !== `object` || json === null) return;
2572
+ const object = json;
2573
+ if (object.version !== 1) return;
2574
+ if (typeof object.recording !== `object` || object.recording === null) return;
2575
+ const recording = object.recording;
2576
+ if (!Array.isArray(recording.sampleStackTraces) || !Array.isArray(recording.sampleDurations)) return;
2577
+ return json;
2578
+ };
2579
+ /**
2580
+ * Asynchronously converts the given WebKit timeline recording to Markdown.
2581
+ *
2582
+ * It is assumed that {@link data} is a valid recording. The behavior of this
2583
+ * function is undefined for invalid recordings.
2584
+ *
2585
+ * See the [WebKit timeline recording docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/webkit-timeline-recording.md)
2586
+ * for generation instructions (`profiler-md --help webkit-timeline-recording`).
2587
+ */
2588
+ const webkitTimelineRecordingToMdAsync = async (data, options) => webkitTimelineRecordingToMdInternal(await parseWebKitTimelineRecordingAsync(data), options);
2589
+ const webkitTimelineRecordingToMdInternal = (recording, options) => {
2590
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2591
+ return formatProfile(aggregateWebKitTimelineRecording(recording, normalizedOptions), normalizedOptions);
2592
+ };
2593
+
2594
+ //#endregion
2595
+ //#region src/cli/formats.ts
2596
+ const languages = new Map([
2597
+ [`c`, {
2598
+ name: `C`,
2599
+ formats: [`pprof`],
2600
+ aliases: [{
2601
+ id: `cpp`,
2602
+ name: `C++`
2603
+ }]
2604
+ }],
2605
+ [`go`, {
2606
+ name: `Go`,
2607
+ formats: [`pprof`]
2608
+ }],
2609
+ [`java`, {
2610
+ name: `Java`,
2611
+ formats: [`pprof`, `speedscope`],
2612
+ aliases: [{
2613
+ id: `kotlin`,
2614
+ name: `Kotlin`
2615
+ }]
2616
+ }],
2617
+ [`javascript`, {
2618
+ name: `JavaScript`,
2619
+ formats: [
2620
+ `jsc-heap-snapshot`,
2621
+ `pprof`,
2622
+ `speedscope`,
2623
+ `v8-cpu-profile`,
2624
+ `v8-heap-profile`,
2625
+ `v8-heap-snapshot`,
2626
+ `webkit-timeline-recording`
2627
+ ],
2628
+ examples: {
2629
+ "jsc-heap-snapshot": [{
2630
+ filename: `jsc-heap-snapshot.json`,
2631
+ label: `Safari`
2632
+ }],
2633
+ pprof: [{
2634
+ filename: `node.pprof`,
2635
+ label: `Node.js`
2636
+ }],
2637
+ speedscope: [{
2638
+ filename: `node.speedscope.json`,
2639
+ label: `Node.js`
2640
+ }],
2641
+ "v8-cpu-profile": [
2642
+ {
2643
+ filename: `node.cpuprofile`,
2644
+ label: `Node.js`
2645
+ },
2646
+ {
2647
+ filename: `deno.cpuprofile`,
2648
+ label: `Deno`
2649
+ },
2650
+ {
2651
+ filename: `bun.cpuprofile`,
2652
+ label: `Bun`
2653
+ }
2654
+ ],
2655
+ "v8-heap-profile": [{
2656
+ filename: `node.heapprofile`,
2657
+ label: `Node.js`
2658
+ }],
2659
+ "v8-heap-snapshot": [{
2660
+ filename: `node.heapsnapshot`,
2661
+ label: `Node.js`
2662
+ }],
2663
+ "webkit-timeline-recording": [{
2664
+ filename: `webkit-timeline-recording.json`,
2665
+ label: `example`
2666
+ }]
2667
+ },
2668
+ aliases: [{
2669
+ id: `typescript`,
2670
+ name: `TypeScript`
2671
+ }]
2672
+ }],
2673
+ [`php`, {
2674
+ name: `PHP`,
2675
+ formats: [`speedscope`]
2676
+ }],
2677
+ [`python`, {
2678
+ name: `Python`,
2679
+ formats: [`pprof`, `speedscope`]
2680
+ }],
2681
+ [`ruby`, {
2682
+ name: `Ruby`,
2683
+ formats: [`speedscope`]
2684
+ }],
2685
+ [`rust`, {
2686
+ name: `Rust`,
2687
+ formats: [`pprof`, `speedscope`],
2688
+ examples: { pprof: [{
2689
+ filename: `rust.pprof`,
2690
+ label: `example`
2691
+ }] }
2692
+ }]
2693
+ ]);
2694
+ const languageAliasToPrimary = new Map([...languages.entries()].flatMap(([primaryId, { aliases }]) => aliases?.map(({ id }) => [id, primaryId]) ?? []));
2695
+ const formats = new Map([
2696
+ [`jsc-heap-snapshot`, {
2697
+ name: `JSC heap snapshot`,
2698
+ kind: `json`,
2699
+ detect: detectJSCHeapSnapshot,
2700
+ toMdInternal: jscHeapSnapshotToMdInternal,
2701
+ toMdAsync: jscHeapSnapshotToMdAsync
2702
+ }],
2703
+ [`pprof`, {
2704
+ name: `pprof`,
2705
+ kind: `binary`,
2706
+ detect: detectPprof,
2707
+ toMdInternal: pprofToMdInternal,
2708
+ toMdAsync: pprofToMdAsync
2709
+ }],
2710
+ [`speedscope`, {
2711
+ name: `Speedscope`,
2712
+ kind: `json`,
2713
+ detect: detectSpeedscopeProfile,
2714
+ toMdInternal: speedscopeProfileToMdInternal,
2715
+ toMdAsync: speedscopeProfileToMdAsync
2716
+ }],
2717
+ [`v8-cpu-profile`, {
2718
+ name: `V8 CPU profile`,
2719
+ kind: `json`,
2720
+ detect: detectV8CpuProfile,
2721
+ toMdInternal: v8CpuProfileToMdInternal,
2722
+ toMdAsync: v8CpuProfileToMdAsync
2723
+ }],
2724
+ [`v8-heap-profile`, {
2725
+ name: `V8 heap profile`,
2726
+ kind: `json`,
2727
+ detect: detectV8HeapProfile,
2728
+ toMdInternal: v8HeapProfileToMdInternal,
2729
+ toMdAsync: v8HeapProfileToMdAsync
2730
+ }],
2731
+ [`v8-heap-snapshot`, {
2732
+ name: `V8 heap snapshot`,
2733
+ kind: `json`,
2734
+ detect: detectV8HeapSnapshot,
2735
+ toMdInternal: v8HeapSnapshotToMdInternal,
2736
+ toMdAsync: v8HeapSnapshotToMdAsync
2737
+ }],
2738
+ [`webkit-timeline-recording`, {
2739
+ name: `WebKit timeline recording`,
2740
+ kind: `json`,
2741
+ detect: detectWebKitTimelineRecording,
2742
+ toMdInternal: webkitTimelineRecordingToMdInternal,
2743
+ toMdAsync: webkitTimelineRecordingToMdAsync
2744
+ }]
2745
+ ]);
2746
+
2747
+ //#endregion
2748
+ //#region src/cli/cli.ts
2749
+ const formatTopics = [...formats.keys()];
2750
+ const languageTopics = [...languages.entries()].flatMap(([id, { aliases }]) => [id, ...aliases?.map((alias) => alias.id) ?? []]);
2751
+ const topics = [...formatTopics, ...languageTopics];
2752
+ const parser = object({
2753
+ help: optional(or(option(`-h`, `--help`, choice(topics, { metavar: `[TOPIC]` }), { description: message`Show this help message or topic docs` }), flag(`-h`, `--help`, { hidden: `help` }))),
2754
+ format: optional(option(`-f`, `--format`, choice(formatTopics, { metavar: `FORMAT` }), { description: message`Input profile format (default: auto)` })),
2755
+ output: withDefault(option(`-o`, `--output`, path({ metavar: `FILE` }), { description: message`Output file (default: - for stdout)` }), `-`),
2756
+ topN: optional(option(`--top-n`, integer({ metavar: `N` }), { description: message`Number of top entries to show (default: 20)` })),
2757
+ cwd: optional(option(`--cwd`, path(), { description: message`Directory to show paths relative to (default: cwd)` })),
2758
+ thirdParty: multiple(option(`--third-party`, string({ metavar: `GLOB` }), { description: message`Additional URLs to consider third-party (repeatable)` })),
2759
+ sourceMaps: multiple(option(`--source-maps`, string({ metavar: `GLOB` }), { description: message`Source maps (JSON or inline) to apply to profile locations (repeatable)` })),
2760
+ pager: map(option(`--no-pager`, { description: message`Disable stdout output paging (default: auto)` }), (value) => !value),
2761
+ color: optional(or(flag(`--color`, { description: message`Enable or disable ANSI syntax highlighting (default: auto)` }), map(flag(`--no-color`), () => false))),
2762
+ file: optional(argument(path({ metavar: `FILE` }), { description: message`Profile file to convert (reads from stdin if omitted)` }))
2763
+ });
2764
+ const program = defineProgram({
2765
+ parser,
2766
+ metadata: {
2767
+ name,
2768
+ version,
2769
+ description: message`${text(description)}`
2770
+ }
2771
+ });
2772
+ const getHelpText = () => `${[
2773
+ formatDocPage(program.metadata.name, {
2774
+ ...getDocPage(parser),
2775
+ ...program.metadata
2776
+ }, { maxWidth: process.stdout.columns ?? 80 }),
2777
+ `Formats: ${formatTopics.join(`, `)}`,
2778
+ `Languages: ${languageTopics.join(`, `)}`
2779
+ ].join(`\n`)}\n`;
2780
+ const parseArgs = () => run(program, {
2781
+ colors: false,
2782
+ version: program.metadata.version,
2783
+ completion: `option`,
2784
+ errorExitCode: 2
2785
+ });
2786
+
2787
+ //#endregion
2788
+ //#region src/cli/error.ts
2789
+ var CliError = class extends Error {
2790
+ exitCode;
2791
+ constructor(message, exitCode) {
2792
+ super(message);
2793
+ this.name = "CliError";
2794
+ this.exitCode = exitCode;
2795
+ }
2796
+ };
2797
+ const reportError = (error) => {
2798
+ if (error instanceof CliError) {
2799
+ process.stderr.write(`error: ${error.message}\n`);
2800
+ process.exit(error.exitCode);
2801
+ }
2802
+ if (error instanceof Error) {
2803
+ process.stderr.write(`error: ${error.message}\n`);
2804
+ if (error.stack) process.stderr.write(`${error.stack}\n`);
2805
+ process.exit(1);
2806
+ }
2807
+ process.stderr.write(`error: ${String(error)}\n`);
2808
+ process.exit(1);
2809
+ };
2810
+
2811
+ //#endregion
2812
+ //#region src/cli/convert.ts
2813
+ const jsonFormats = [...formats.entries()].filter((entry) => entry[1].kind === `json`);
2814
+ const binaryFormats = [...formats.entries()].filter((entry) => entry[1].kind === `binary`);
2815
+ const convertToMarkdown = async (data, forcedFormat, options) => {
2816
+ if (forcedFormat) return forcedFormat.toMdAsync(data, options);
2817
+ const markdown = await autoDetectAndConvert(data, options);
2818
+ if (markdown === void 0) throw new CliError(`could not detect profile format from content\nUse --format to specify the format, or run with --help to see supported formats.`, 2);
2819
+ return markdown;
2820
+ };
2821
+ const autoDetectAndConvert = async (data, options) => {
2822
+ let json;
2823
+ try {
2824
+ json = await JumboJSON.parseAsync(data);
2825
+ } catch {}
2826
+ if (json === void 0) {
2827
+ for (const [, format] of binaryFormats) {
2828
+ const parsed = await format.detect(data);
2829
+ if (parsed !== void 0) return format.toMdInternal(parsed, options);
2830
+ }
2831
+ return;
2832
+ }
2833
+ for (const [, format] of jsonFormats) {
2834
+ const parsed = format.detect(json);
2835
+ if (parsed !== void 0) return format.toMdInternal(parsed, options);
2836
+ }
2837
+ };
2838
+
2839
+ //#endregion
2840
+ //#region src/cli/pager.ts
2841
+ const openPager = async () => {
2842
+ const raw = process.env.PAGER;
2843
+ if (raw?.trim() === ``) return null;
2844
+ const env = {
2845
+ LESS: `FRSX -#6`,
2846
+ ...process.env
2847
+ };
2848
+ const child = (raw === void 0 ? null : await trySpawn(raw, env)) ?? await trySpawn(`less`, env);
2849
+ if (!child) return null;
2850
+ return { write: async (text) => {
2851
+ await new Promise((resolve) => {
2852
+ child.stdin.write(text, () => child.stdin.end(resolve));
2853
+ });
2854
+ await waitForExit(child);
2855
+ } };
2856
+ };
2857
+ const trySpawn = (command, env) => {
2858
+ const [bin, ...args] = command.trim().split(/\s+/u);
2859
+ if (!bin) return Promise.resolve(null);
2860
+ const child = spawn(bin, args, {
2861
+ stdio: [
2862
+ `pipe`,
2863
+ `inherit`,
2864
+ `inherit`
2865
+ ],
2866
+ env
2867
+ });
2868
+ return new Promise((resolve) => {
2869
+ child.once(`spawn`, () => {
2870
+ child.stdin.on(`error`, (error) => {
2871
+ if (error.code !== `EPIPE`) throw error;
2872
+ });
2873
+ resolve(child);
2874
+ });
2875
+ child.once(`error`, () => resolve(null));
2876
+ });
2877
+ };
2878
+ const waitForExit = (child) => new Promise((resolve, reject) => {
2879
+ child.once(`exit`, () => resolve());
2880
+ child.once(`error`, reject);
2881
+ });
2882
+
2883
+ //#endregion
2884
+ //#region src/cli/output.ts
2885
+ const writeOutput = async (text, outputPath, { pager }) => {
2886
+ await ((pager && isTTYOutput(outputPath) ? await openPager() : null) ?? await openOutput(outputPath)).write(text);
2887
+ };
2888
+ const isTTYOutput = (outputPath) => outputPath === `-` && Boolean(process.stdout.isTTY);
2889
+ const openOutput = async (outputPath) => {
2890
+ if (outputPath === `-`) return { write: (text) => new Promise((resolve, reject) => {
2891
+ process.stdout.write(text, (error) => error ? reject(error) : resolve());
2892
+ }) };
2893
+ const stream = createWriteStream(outputPath);
2894
+ await new Promise((resolve, reject) => {
2895
+ stream.once(`open`, () => resolve()).once(`error`, reject);
2896
+ });
2897
+ return { write: (text) => new Promise((resolve, reject) => {
2898
+ stream.write(text, (error) => error ? reject(error) : stream.end(resolve));
2899
+ }) };
2900
+ };
2901
+
2902
+ //#endregion
2903
+ //#region src/cli/ansis.ts
2904
+ const makeAnsis = ({ outputPath }) => {
2905
+ if (isTTYOutput(outputPath)) return new Ansis();
2906
+ return new Ansis({
2907
+ ...globalThis,
2908
+ process: {
2909
+ ...process,
2910
+ env: {
2911
+ NO_COLOR: `1`,
2912
+ ...process.env
2913
+ }
2914
+ }
2915
+ });
2916
+ };
2917
+
2918
+ //#endregion
2919
+ //#region src/cli/theme-kindling.ts
2920
+ const darkSlate = `#2d353b`;
2921
+ const mutedSage = `#859289`;
2922
+ const warmSand = `#d3c6aa`;
2923
+ const dimAmber = `#7a6535`;
2924
+ const amberBrown = `#cb9d68`;
2925
+ const goldenAmber = `#dbbc7f`;
2926
+ const kindlingTheme = {
2927
+ name: `kindling`,
2928
+ displayName: `Kindling`,
2929
+ type: `dark`,
2930
+ fg: warmSand,
2931
+ bg: darkSlate,
2932
+ colors: {
2933
+ "editor.foreground": warmSand,
2934
+ "editor.background": darkSlate
2935
+ },
2936
+ settings: [
2937
+ {
2938
+ scope: `punctuation.definition.heading.markdown`,
2939
+ settings: { foreground: dimAmber }
2940
+ },
2941
+ {
2942
+ scope: [
2943
+ `heading.1.markdown`,
2944
+ `heading.2.markdown`,
2945
+ `heading.3.markdown`,
2946
+ `heading.4.markdown`,
2947
+ `heading.5.markdown`,
2948
+ `heading.6.markdown`
2949
+ ],
2950
+ settings: {
2951
+ foreground: goldenAmber,
2952
+ fontStyle: `bold`
2953
+ }
2954
+ },
2955
+ {
2956
+ scope: `markup.bold.markdown`,
2957
+ settings: {
2958
+ foreground: warmSand,
2959
+ fontStyle: `bold`
2960
+ }
2961
+ },
2962
+ {
2963
+ scope: `markup.italic.markdown`,
2964
+ settings: {
2965
+ foreground: warmSand,
2966
+ fontStyle: `italic`
2967
+ }
2968
+ },
2969
+ {
2970
+ scope: [
2971
+ `markup.inline.raw.string.markdown`,
2972
+ `markup.fenced_code.block.markdown`,
2973
+ `string.other.link.description.title.markdown`
2974
+ ],
2975
+ settings: { foreground: amberBrown }
2976
+ },
2977
+ {
2978
+ scope: `punctuation.definition.raw.markdown`,
2979
+ settings: { foreground: goldenAmber }
2980
+ },
2981
+ {
2982
+ scope: [
2983
+ `punctuation.definition.bold.markdown`,
2984
+ `punctuation.definition.italic.markdown`,
2985
+ `punctuation.definition.markdown`,
2986
+ `markup.quote.markdown`,
2987
+ `punctuation.definition.quote.begin.markdown`,
2988
+ `punctuation.definition.list.begin.markdown`,
2989
+ `punctuation.definition.table.markdown`,
2990
+ `punctuation.definition.link.markdown`
2991
+ ],
2992
+ settings: { foreground: mutedSage }
2993
+ },
2994
+ {
2995
+ scope: [
2996
+ `markup.list.unnumbered.markdown`,
2997
+ `markup.list.numbered.markdown`,
2998
+ `markup.table.markdown`
2999
+ ],
3000
+ settings: { foreground: warmSand }
3001
+ },
3002
+ {
3003
+ scope: `meta.separator.markdown`,
3004
+ settings: {
3005
+ foreground: mutedSage,
3006
+ fontStyle: `bold`
3007
+ }
3008
+ },
3009
+ {
3010
+ scope: `markup.underline.link.markdown`,
3011
+ settings: {
3012
+ foreground: amberBrown,
3013
+ fontStyle: `underline`
3014
+ }
3015
+ },
3016
+ {
3017
+ scope: `comment`,
3018
+ settings: {
3019
+ foreground: mutedSage,
3020
+ fontStyle: `italic`
3021
+ }
3022
+ },
3023
+ {
3024
+ scope: [
3025
+ `keyword`,
3026
+ `keyword.control`,
3027
+ `keyword.other`,
3028
+ `storage.type`,
3029
+ `storage.modifier`
3030
+ ],
3031
+ settings: { foreground: goldenAmber }
3032
+ },
3033
+ {
3034
+ scope: [`string`, `string.template`],
3035
+ settings: { foreground: `#d98c5a` }
3036
+ },
3037
+ {
3038
+ scope: [
3039
+ `constant.numeric`,
3040
+ `constant.language`,
3041
+ `constant.character`
3042
+ ],
3043
+ settings: { foreground: `#e69875` }
3044
+ },
3045
+ {
3046
+ scope: [
3047
+ `entity.name.function`,
3048
+ `support.function`,
3049
+ `meta.function-call entity.name.function`
3050
+ ],
3051
+ settings: { foreground: `#ca6e63` }
3052
+ },
3053
+ {
3054
+ scope: [
3055
+ `entity.name.type`,
3056
+ `entity.name.class`,
3057
+ `support.type`,
3058
+ `support.class`,
3059
+ `entity.other.inherited-class`,
3060
+ `support.variable.property`
3061
+ ],
3062
+ settings: { foreground: warmSand }
3063
+ },
3064
+ {
3065
+ scope: `variable.parameter`,
3066
+ settings: {
3067
+ foreground: warmSand,
3068
+ fontStyle: `italic`
3069
+ }
3070
+ },
3071
+ {
3072
+ scope: `entity.other.attribute-name`,
3073
+ settings: { foreground: amberBrown }
3074
+ },
3075
+ {
3076
+ scope: [`keyword.operator`, `punctuation.accessor`],
3077
+ settings: { foreground: mutedSage }
3078
+ },
3079
+ {
3080
+ scope: [`meta.tag`, `entity.name.tag`],
3081
+ settings: { foreground: `#c4907a` }
3082
+ }
3083
+ ]
3084
+ };
3085
+
3086
+ //#endregion
3087
+ //#region src/cli/highlight.ts
3088
+ const highlightMarkdown = async (markdown, options) => {
3089
+ const ansis = makeAnsis(options);
3090
+ if (!ansis.isSupported()) return markdown;
3091
+ const { tokens, fg } = (await getHighlighter()).codeToTokens(markdown, {
3092
+ lang: `markdown`,
3093
+ theme: `kindling`,
3094
+ includeExplanation: `scopeName`
3095
+ });
3096
+ return renderTokens(tokens, fg, computeLineToIntensity(tokens), ansis);
3097
+ };
3098
+ const getHighlighter = () => highlighterPromise ??= createHighlighterCore();
3099
+ let highlighterPromise = null;
3100
+ const createHighlighterCore = async () => {
3101
+ const markdown = import(`@shikijs/langs/markdown`);
3102
+ const c = import(`@shikijs/langs/c`);
3103
+ const go = import(`@shikijs/langs/go`);
3104
+ const java = import(`@shikijs/langs/java`);
3105
+ const js = import(`@shikijs/langs/js`);
3106
+ const python = import(`@shikijs/langs/python`);
3107
+ const rust = import(`@shikijs/langs/rust`);
3108
+ const sh = import(`@shikijs/langs/sh`);
3109
+ const toml = import(`@shikijs/langs/toml`);
3110
+ const shikiCore = import(`@shikijs/core`);
3111
+ const onigurumaEngine = import(`@shikijs/engine-oniguruma`);
3112
+ const onigurumaEngineWasm = import(`@shikijs/engine-oniguruma/wasm-inlined`);
3113
+ return (await shikiCore).createHighlighterCore({
3114
+ langs: [
3115
+ markdown,
3116
+ c,
3117
+ go,
3118
+ java,
3119
+ js,
3120
+ python,
3121
+ rust,
3122
+ sh,
3123
+ toml
3124
+ ],
3125
+ themes: [kindlingTheme],
3126
+ engine: (await onigurumaEngine).createOnigurumaEngine(onigurumaEngineWasm)
3127
+ });
3128
+ };
3129
+ const computeLineToIntensity = (lines) => {
3130
+ const lineToIntensity = /* @__PURE__ */ new Map();
3131
+ const sections = [];
3132
+ let currentTable = null;
3133
+ for (const [lineIndex, lineTokens] of lines.entries()) {
3134
+ const line = parseLine(lineTokens);
3135
+ switch (line.kind) {
3136
+ case `heading`: {
3137
+ while (sections.length > 0 && sections.at(-1).level >= line.level) sections.pop();
3138
+ currentTable = null;
3139
+ const intensity = lookupAncestorIntensity(sections, line.inlineCode, line.afterInlineCode);
3140
+ sections.push({
3141
+ level: line.level,
3142
+ intensity,
3143
+ nameLocationToIntensity: /* @__PURE__ */ new Map()
3144
+ });
3145
+ if (intensity !== null) lineToIntensity.set(lineIndex, intensity);
3146
+ break;
3147
+ }
3148
+ case `table-row`: {
3149
+ if (currentTable === null) {
3150
+ currentTable = parseTableHeader(line.text);
3151
+ break;
3152
+ }
3153
+ if (currentTable.percentColumnIndex === -1) break;
3154
+ const intensity = tableRowIntensity(line.text, currentTable, sections.at(-1));
3155
+ if (intensity !== null) lineToIntensity.set(lineIndex, intensity);
3156
+ break;
3157
+ }
3158
+ case `other`:
3159
+ currentTable = null;
3160
+ break;
3161
+ }
3162
+ }
3163
+ return lineToIntensity;
3164
+ };
3165
+ const parseLine = (tokens) => {
3166
+ if (tokens.length === 0) return { kind: `other` };
3167
+ const headingLevel = determineHeadingLevel(tokens);
3168
+ if (headingLevel !== null) {
3169
+ const { inlineCode, afterInlineCode } = extractHeadingParts(tokens);
3170
+ return {
3171
+ kind: `heading`,
3172
+ level: headingLevel,
3173
+ inlineCode,
3174
+ afterInlineCode
3175
+ };
3176
+ }
3177
+ if (tokens.some((token) => tokenHasScope(token, `markup.table.markdown`))) return {
3178
+ kind: `table-row`,
3179
+ text: joinTokens(tokens)
3180
+ };
3181
+ return { kind: `other` };
3182
+ };
3183
+ const determineHeadingLevel = (tokens) => {
3184
+ for (const token of tokens) for (const { scopeName } of token.explanation?.[0]?.scopes ?? []) if (scopeName.startsWith(`heading.`) && scopeName.endsWith(`.markdown`)) {
3185
+ const level = Number.parseInt(scopeName.slice(`heading.`.length, -`.markdown`.length), 10);
3186
+ if (level >= 1 && level <= 6) return level;
3187
+ }
3188
+ return null;
3189
+ };
3190
+ const extractHeadingParts = (line) => {
3191
+ const inlineCodeRange = findInlineCodeRange(line);
3192
+ if (inlineCodeRange === null) return {
3193
+ inlineCode: null,
3194
+ afterInlineCode: ``
3195
+ };
3196
+ const [start, endExclusive] = inlineCodeRange;
3197
+ return {
3198
+ inlineCode: joinTokens(line.slice(start, endExclusive)),
3199
+ afterInlineCode: joinTokens(line.slice(endExclusive))
3200
+ };
3201
+ };
3202
+ const findInlineCodeRange = (line) => {
3203
+ const start = line.findIndex((token) => tokenHasScope(token, `markup.inline.raw.string.markdown`));
3204
+ if (start === -1) return null;
3205
+ let endExclusive = start + 1;
3206
+ while (endExclusive < line.length && tokenHasScope(line[endExclusive], `markup.inline.raw.string.markdown`)) endExclusive++;
3207
+ return [start, endExclusive];
3208
+ };
3209
+ const tokenHasScope = (token, scope) => !!token.explanation?.[0]?.scopes.some(({ scopeName }) => scopeName === scope);
3210
+ const joinTokens = (tokens) => tokens.map((token) => token.content).join(``);
3211
+ const lookupAncestorIntensity = (sections, inlineCode, afterInlineCode) => {
3212
+ if (inlineCode === null) return null;
3213
+ const trimmed = afterInlineCode.trim();
3214
+ if (!trimmed.startsWith(`(`) || !trimmed.endsWith(`)`)) return null;
3215
+ const key = `${inlineCode} (${trimmed.slice(1, -1)})`;
3216
+ for (let i = sections.length - 1; i >= 0; i--) {
3217
+ const intensity = sections[i].nameLocationToIntensity.get(key);
3218
+ if (intensity !== void 0) return intensity;
3219
+ }
3220
+ return null;
3221
+ };
3222
+ const parseTableHeader = (line) => {
3223
+ const cells = parseTableCells(line);
3224
+ return {
3225
+ percentColumnIndex: cells.indexOf(`%`),
3226
+ locationColumnIndex: cells.indexOf(`Location`),
3227
+ nameColumnIndex: -1
3228
+ };
3229
+ };
3230
+ const tableRowIntensity = (row, table, headingSection) => {
3231
+ const cells = parseTableCells(row);
3232
+ const percentageCell = cells[table.percentColumnIndex];
3233
+ if (percentageCell === void 0) return null;
3234
+ const percentage = parsePercent(percentageCell);
3235
+ if (percentage === null) return null;
3236
+ if (table.locationColumnIndex !== -1 && headingSection !== void 0) {
3237
+ if (table.nameColumnIndex === -1) table.nameColumnIndex = cells.findIndex((cell) => cell.startsWith(`\``) && cell.endsWith(`\``));
3238
+ if (table.nameColumnIndex !== -1) {
3239
+ const nameCell = cells[table.nameColumnIndex];
3240
+ const locationCell = cells[table.locationColumnIndex];
3241
+ const intensity = (headingSection.intensity ?? 1) * percentage;
3242
+ headingSection.nameLocationToIntensity.set(`${nameCell} (${locationCell})`, intensity);
3243
+ return intensity;
3244
+ }
3245
+ }
3246
+ return (headingSection?.intensity ?? 1) * percentage;
3247
+ };
3248
+ const parseTableCells = (line) => {
3249
+ let inner = line.trim();
3250
+ if (inner.startsWith(`|`)) inner = inner.slice(1);
3251
+ if (inner.endsWith(`|`)) inner = inner.slice(0, -1);
3252
+ return inner.split(`|`).map((cell) => cell.trim());
3253
+ };
3254
+ const parsePercent = (cell) => {
3255
+ const trimmed = cell.trim();
3256
+ if (!trimmed.endsWith(`%`)) return null;
3257
+ const value = Number.parseFloat(trimmed.slice(0, -1));
3258
+ return Number.isNaN(value) ? null : value / 100;
3259
+ };
3260
+ const renderTokens = (tokens, themeFg, lineToIntensity, ansis) => tokens.map((line, lineIndex) => {
3261
+ const intensity = lineToIntensity.get(lineIndex) ?? 0;
3262
+ return line.map((token) => renderToken(token, themeFg, intensity, ansis)).join(``);
3263
+ }).join(`\n`);
3264
+ const renderToken = (token, themeFg, intensity, ansis) => {
3265
+ const baseRgb = parseRgb(token.color ?? themeFg);
3266
+ const { red, green, blue } = intensity > 0 ? tintHeat(baseRgb, intensity ** .5 * .75) : baseRgb;
3267
+ let styled = ansis.rgb(red, green, blue)(token.content);
3268
+ if (token.fontStyle) {
3269
+ if (token.fontStyle & FONT_STYLE_BOLD) styled = ansis.bold(styled);
3270
+ if (token.fontStyle & FONT_STYLE_ITALIC) styled = ansis.italic(styled);
3271
+ if (token.fontStyle & FONT_STYLE_UNDERLINE) styled = ansis.underline(styled);
3272
+ if (token.fontStyle & FONT_STYLE_STRIKETHROUGH) styled = ansis.strikethrough(styled);
3273
+ }
3274
+ return styled;
3275
+ };
3276
+ const parseRgb = (hex) => {
3277
+ const value = hex.replace(/^#/u, ``);
3278
+ return {
3279
+ red: Number.parseInt(value.slice(0, 2), 16),
3280
+ green: Number.parseInt(value.slice(2, 4), 16),
3281
+ blue: Number.parseInt(value.slice(4, 6), 16)
3282
+ };
3283
+ };
3284
+ const tintHeat = ({ red, green, blue }, intensity) => ({
3285
+ red: Math.round(red + (255 - red) * intensity),
3286
+ green: Math.round(green * (1 - intensity * .7)),
3287
+ blue: Math.round(blue * (1 - intensity * .7))
3288
+ });
3289
+ const FONT_STYLE_ITALIC = 1;
3290
+ const FONT_STYLE_BOLD = 2;
3291
+ const FONT_STYLE_UNDERLINE = 4;
3292
+ const FONT_STYLE_STRIKETHROUGH = 8;
3293
+
3294
+ //#endregion
3295
+ //#region src/cli/help.ts
3296
+ const printHelpTopic = async (topic, { pager }) => {
3297
+ if (topic === void 0) {
3298
+ await writeOutput(getHelpText(), `-`, { pager });
3299
+ process.exit(0);
3300
+ }
3301
+ const language = languages.get(languageAliasToPrimary.get(topic) ?? topic);
3302
+ const format = formats.get(topic);
3303
+ if (!language && !format) {
3304
+ process.stderr.write(`error: unknown topic "${topic}"\nAvailable topics: ${topics.join(`, `)}\n`);
3305
+ process.exit(2);
3306
+ }
3307
+ const doc = await readFile(new URL(`../../docs/${format ? `formats` : `languages`}/${topic}.md`, import.meta.url), `utf8`);
3308
+ const seeAlso = format ? [...languages.entries()].flatMap(([id, language]) => {
3309
+ if (!language.formats.includes(topic)) return [];
3310
+ return [id, ...language.aliases?.map((alias) => alias.id) ?? []];
3311
+ }) : language ? language.formats : [];
3312
+ const seeAlsoSuffix = seeAlso.length > 0 ? `\nSee also: ${seeAlso.join(`, `)}\n` : ``;
3313
+ const outputPath = `-`;
3314
+ await writeOutput(await highlightMarkdown(`${doc}${seeAlsoSuffix}`, { outputPath }), outputPath, { pager });
3315
+ process.exit(0);
3316
+ };
3317
+
3318
+ //#endregion
3319
+ //#region src/cli/input.ts
3320
+ const openInputAsBlob = async (filePath) => decompressBlob(await openRawInputAsBlob(filePath), filePath);
3321
+ const openRawInputAsBlob = async (filePath) => {
3322
+ if (!filePath) return blob(process.stdin);
3323
+ try {
3324
+ return await openAsBlob(filePath);
3325
+ } catch (error) {
3326
+ throw new CliError(error instanceof Error ? error.message : String(error), 1);
3327
+ }
3328
+ };
3329
+ const decompressBlob = async (data, filePath) => {
3330
+ try {
3331
+ if (filePath?.endsWith(`.br`)) return await decompressStream(data, createBrotliDecompress());
3332
+ const header = new Uint8Array(await data.slice(0, 2).arrayBuffer());
3333
+ if (header[0] === 31 && header[1] === 139) return await decompressStream(data, createGunzip());
3334
+ return data;
3335
+ } catch (error) {
3336
+ throw new CliError(`failed to decompress input: ${error instanceof Error ? error.message : String(error)}`, 1);
3337
+ }
3338
+ };
3339
+ const decompressStream = async (data, transform) => {
3340
+ const decompressedData = blob(transform);
3341
+ await pipeline(data.stream(), transform);
3342
+ return decompressedData;
3343
+ };
3344
+
3345
+ //#endregion
3346
+ //#region src/cli/options.ts
3347
+ const buildOptions = async ({ topN, cwd, thirdParty, sourceMaps }) => ({
3348
+ topN,
3349
+ cwd,
3350
+ categorizeEntry: buildCategorizeEntry(thirdParty),
3351
+ sourceMaps: await loadSourceMaps(sourceMaps)
3352
+ });
3353
+ const buildCategorizeEntry = (patterns) => {
3354
+ if (patterns.length === 0) return;
3355
+ const isMatch = picomatch([...patterns], { dot: true });
3356
+ return (entry) => {
3357
+ if (entry.location && isMatch(entry.location.url.pathname)) return `third-party`;
3358
+ return defaultCategorizeEntry(entry);
3359
+ };
3360
+ };
3361
+ const loadSourceMaps = async (patterns) => {
3362
+ const paths = (await Promise.all(patterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
3363
+ return Promise.all(paths.map(async (path) => {
3364
+ const content = await readFile(path, `utf8`);
3365
+ const inlineSourceMap = convertSourceMap.fromSource(content)?.toObject();
3366
+ if (!inlineSourceMap) return resolveSourceMapSources(JSON.parse(content), path);
3367
+ inlineSourceMap.file ??= pathToFileURL(resolve(path)).href;
3368
+ return resolveSourceMapSources(inlineSourceMap, path);
3369
+ }));
3370
+ };
3371
+ /**
3372
+ * Pre-resolves relative source paths against the map file's directory so that `source-map-js` returns
3373
+ * absolute URLs.
3374
+ */
3375
+ const resolveSourceMapSources = (sourceMap, path) => {
3376
+ if (sourceMap.sourceRoot) return sourceMap;
3377
+ return {
3378
+ ...sourceMap,
3379
+ sources: sourceMap.sources.map((source) => makeFileReference(source).type === `absolute` ? source : new URL(source, pathToFileURL(resolve(dirname(path)))).href)
3380
+ };
3381
+ };
3382
+
3383
+ //#endregion
3384
+ //#region src/cli/index.ts
3385
+ try {
3386
+ const { help, output: outputPath, format: profileFormat, topN, cwd, thirdParty, sourceMaps, pager, file: filePath } = parseArgs();
3387
+ if (help !== void 0) await printHelpTopic(typeof help === `string` ? help : void 0, { pager });
3388
+ const forcedFormat = profileFormat === void 0 ? void 0 : formats.get(profileFormat);
3389
+ if (!filePath && process.stdin.isTTY) await printHelpTopic(void 0, { pager });
3390
+ const [data, options] = await Promise.all([openInputAsBlob(filePath), buildOptions({
3391
+ topN,
3392
+ cwd,
3393
+ thirdParty,
3394
+ sourceMaps
3395
+ })]);
3396
+ await writeOutput(await highlightMarkdown(await convertToMarkdown(data, forcedFormat, options), { outputPath }), outputPath, { pager });
3397
+ } catch (error) {
3398
+ reportError(error);
3399
+ }
3400
+
3401
+ //#endregion
3402
+ export { };