profiler-md 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { JumboJSON } from "jumbo-json";
3
- import { gfmTableToMarkdown } from "mdast-util-gfm-table";
4
- import { toMarkdown } from "mdast-util-to-markdown";
5
2
  import { SourceMapConsumer } from "source-map-js";
6
3
  import plur from "plur";
7
4
  import prettyBytes from "pretty-bytes";
8
5
  import prettyMilliseconds from "pretty-ms";
6
+ import { gfmTableToMarkdown } from "mdast-util-gfm-table";
7
+ import { toMarkdown } from "mdast-util-to-markdown";
9
8
  import { Profile } from "pprof-format";
9
+ import { JumboJSON } from "jumbo-json";
10
10
  import globals from "globals";
11
11
  import { formatDocPage, getDocPage, runParser } from "@optique/core";
12
12
  import { object, or, tuple } from "@optique/core/constructs";
@@ -17,33 +17,17 @@ import { defineProgram } from "@optique/core/program";
17
17
  import { formatUsageTerm } from "@optique/core/usage";
18
18
  import { choice, float, integer, string } from "@optique/core/valueparser";
19
19
  import { path } from "@optique/run";
20
- import { glob, readFile, stat } from "node:fs/promises";
20
+ import { access, constants, glob, readFile, stat } from "node:fs/promises";
21
21
  import { Ansis } from "ansis";
22
- import { createWriteStream, openAsBlob } from "node:fs";
22
+ import { createReadStream, createWriteStream, openAsBlob } from "node:fs";
23
+ import { dirname, resolve } from "node:path";
23
24
  import { spawn } from "node:child_process";
24
25
  import { blob } from "node:stream/consumers";
25
26
  import { pipeline } from "node:stream/promises";
26
27
  import { createBrotliDecompress, createGunzip } from "node:zlib";
27
- import { dirname, resolve } from "node:path";
28
28
  import { pathToFileURL } from "node:url";
29
29
  import convertSourceMap from "convert-source-map";
30
30
 
31
- //#region src/error.ts
32
- /**
33
- * Thrown when a caller's input or options are unusable: an unrecognized
34
- * format, a malformed profile, an invalid option.
35
- *
36
- * A failure the caller cannot fix throws a plain `Error` instead, because such
37
- * a failure is a bug in this package.
38
- */
39
- var ProfilerMdError = class extends Error {
40
- constructor(message, options) {
41
- super(message, options);
42
- this.name = "ProfilerMdError";
43
- }
44
- };
45
-
46
- //#endregion
47
31
  //#region src/helpers/bytes.ts
48
32
  const streamToUint8Array = async (stream) => {
49
33
  const chunks = [];
@@ -79,8 +63,8 @@ const concatUint8Arrays = (arrays) => {
79
63
  * Decoding is synchronous and correct across multi-byte sequences split at a
80
64
  * chunk boundary.
81
65
  *
82
- * Throws on invalid UTF-8, including a truncated trailing sequence, so a caller
83
- * can treat a failure as "these bytes aren't this text format".
66
+ * Replaces an invalid sequence, including a truncated trailing one, with
67
+ * U+FFFD.
84
68
  *
85
69
  * Yields the same lines as `decoder.decode(bytes).split('\n')` would (with `\r`
86
70
  * stripped), i.e. a trailing empty line when the input ends with a newline.
@@ -101,8 +85,8 @@ function* decodeUtf8Lines(bytes, chunkSize = DECODE_CHUNK_SIZE) {
101
85
  * whole input. Decoding is correct across multi-byte sequences split at a chunk
102
86
  * boundary.
103
87
  *
104
- * Throws on invalid UTF-8, including a truncated trailing sequence, so a caller
105
- * can treat a failure as "these bytes aren't this text format".
88
+ * Replaces an invalid sequence, including a truncated trailing one, with
89
+ * U+FFFD.
106
90
  *
107
91
  * Yields a trailing empty line when the input ends with a newline.
108
92
  */
@@ -137,7 +121,7 @@ const hasLeadingNulByte = (bytes) => bytes.subarray(0, NUL_SCAN_LENGTH).includes
137
121
  const NUL_SCAN_LENGTH = 4096;
138
122
  /** A streaming UTF-8 and line-splitting decoder. */
139
123
  var Utf8LineDecoder = class {
140
- #decoder = new TextDecoder(`utf-8`, { fatal: true });
124
+ #decoder = new TextDecoder(`utf-8`);
141
125
  #pending = ``;
142
126
  *push(bytes) {
143
127
  this.#pending += this.#decoder.decode(bytes, { stream: true });
@@ -145,11 +129,6 @@ var Utf8LineDecoder = class {
145
129
  this.#pending = lines.pop();
146
130
  for (const line of lines) yield stripCarriageReturn(line);
147
131
  }
148
- /**
149
- * Flush buffered bytes.
150
- *
151
- * @throws if a trailing sequence is truncated.
152
- */
153
132
  *flush() {
154
133
  this.#pending += this.#decoder.decode();
155
134
  yield stripCarriageReturn(this.#pending);
@@ -287,93 +266,25 @@ const START_JSON_DOCUMENT_PREFIX_LENGTH = 16;
287
266
  const MAYBE_JSON_PREFIX_LENGTH = 1024;
288
267
 
289
268
  //#endregion
290
- //#region src/helpers/markdown.ts
291
- const text$1 = (value) => ({
292
- type: `text`,
293
- value: value.replaceAll(/\r(?!\n)/gu, ` `)
294
- });
295
- const inlineCode = (value) => ({
296
- type: `inlineCode`,
297
- value: value.replaceAll(/\r\n|[\r\n]/gu, ` `).replaceAll(`\\|`, `\\ |`)
298
- });
299
- const heading = (depth, children) => ({
300
- type: `heading`,
301
- depth,
302
- children: toPhrasing(children)
303
- });
304
- const paragraph = (children) => ({
305
- type: `paragraph`,
306
- children: toPhrasing(children)
307
- });
308
- const toPhrasing = (children) => typeof children === `string` ? [text$1(children)] : children;
269
+ //#region src/error.ts
309
270
  /**
310
- * Builds phrasing content from a template, turning literal segments and
311
- * interpolated strings into text nodes and splicing in interpolated nodes.
271
+ * Thrown when a caller's input or options are unusable: an unrecognized
272
+ * format, a malformed profile, an invalid option.
273
+ *
274
+ * A failure the caller cannot fix throws a plain `Error` instead, because such
275
+ * a failure is a bug in this package. The exception is a parser failing on an
276
+ * error it did not classify, which is either an input violating the format in
277
+ * a way the parser does not check or a parser bug. That failure throws a
278
+ * `ProfilerMdError` too, and `mayBeParserBug` identifies it.
312
279
  */
313
- const phrasing = (strings, ...values) => {
314
- const children = [];
315
- const push = (value) => {
316
- if (typeof value === `string`) {
317
- if (value) children.push(text$1(value));
318
- } else if (Array.isArray(value)) children.push(...value);
319
- else children.push(value);
320
- };
321
- for (const [index, string] of strings.entries()) {
322
- push(string);
323
- if (index < values.length) push(values[index]);
280
+ var ProfilerMdError = class extends Error {
281
+ constructor(message, options) {
282
+ super(message, options);
283
+ this.name = "ProfilerMdError";
324
284
  }
325
- return children;
326
- };
327
- /**
328
- * Phrasing for an entity heading: a code-span name followed by its
329
- * parenthesized location. {@link headingNameLocationKey} recovers the
330
- * {@link nameLocationKey} key from this shape, so entity headings must be
331
- * built through this helper for the CLI highlighter's heading ↔ table
332
- * matching to work.
333
- */
334
- const nameLocationPhrasing = (name, location) => phrasing`${inlineCode(name)} (${location})`;
335
- /** The key matching a {@link nameLocationPhrasing} heading to a table row. */
336
- const nameLocationKey = (name, location) => `${name} (${location})`;
337
- /**
338
- * Extracts the {@link nameLocationKey} key from a heading with the
339
- * {@link nameLocationPhrasing} shape, or returns null if the heading doesn't
340
- * have that shape.
341
- */
342
- const headingNameLocationKey = (heading) => {
343
- const nameIndex = heading.children.findIndex((child) => child.type === `inlineCode`);
344
- if (nameIndex === -1) return null;
345
- const name = nodeText(heading.children[nameIndex]);
346
- const after = heading.children.slice(nameIndex + 1).map(nodeText).join(``).trim();
347
- if (!after.startsWith(`(`) || !after.endsWith(`)`)) return null;
348
- return nameLocationKey(name, after.slice(1, -1));
349
- };
350
- /** The concatenated text content of a node's subtree. */
351
- const nodeText = (node) => {
352
- if (`value` in node && typeof node.value === `string`) return node.value;
353
- if (`children` in node && Array.isArray(node.children)) return node.children.map(nodeText).join(``);
354
- return ``;
355
285
  };
356
- /**
357
- * Prepends the given section header (a heading and any description) to
358
- * {@link sections}, or returns no sections if there are none.
359
- */
360
- const formatSectionGroup = (header, sections) => sections.length === 0 ? [] : [...header, ...sections];
361
- const table = (headers, rows) => ({
362
- type: `table`,
363
- align: headers.map((header) => typeof header !== `string` && header.align === `right` ? `right` : null),
364
- children: [tableRow(headers.map((header) => [text$1(typeof header === `string` ? header : header.content)])), ...rows.map(tableRow)]
365
- });
366
- const tableRow = (cells) => ({
367
- type: `tableRow`,
368
- children: cells.map((children) => ({
369
- type: `tableCell`,
370
- children
371
- }))
372
- });
373
- const mdastToMarkdown = (children) => toMarkdown({
374
- type: `root`,
375
- children
376
- }, { extensions: [gfmTableToMarkdown()] });
286
+ /** An error's message on one line, for embedding in another message. */
287
+ const reasonOf = (error) => (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, ` `).trim();
377
288
 
378
289
  //#endregion
379
290
  //#region src/source-map.ts
@@ -382,8 +293,14 @@ const normalizeSourceMaps = (sourceMaps) => {
382
293
  return Object.entries(sourceMaps).flatMap(([urlOrPath, sourceMap]) => {
383
294
  const fileReference = makeFileReference(urlOrPath);
384
295
  if (!fileReference) return [];
296
+ let consumer;
297
+ try {
298
+ consumer = new SourceMapConsumer(sourceMap);
299
+ } catch (error) {
300
+ throw new ProfilerMdError(`sourceMaps entry for ${urlOrPath} is an invalid source map: ${reasonOf(error)}`, { cause: error });
301
+ }
385
302
  return {
386
- consumer: new SourceMapConsumer(sourceMap),
303
+ consumer,
387
304
  fileReference
388
305
  };
389
306
  });
@@ -651,96 +568,6 @@ const commonSegmentPrefixLength = (segments1, segments2) => {
651
568
  return common;
652
569
  };
653
570
 
654
- //#endregion
655
- //#region src/helpers/graph.ts
656
- /**
657
- * Assigns each node its strongly connected component index via iterative
658
- * Tarjan. Nodes in one component are reachable from each other, so they form a
659
- * cycle.
660
- *
661
- * A node is an index into {@link nodeToEdges}, which contains its outgoing
662
- * edges, and {@link select} maps an edge to the node it points to.
663
- */
664
- const stronglyConnectedComponents = (nodeToEdges, select) => new ComponentSearch(nodeToEdges, select).search();
665
- /** One iterative Tarjan run over a graph's outgoing edges. */
666
- var ComponentSearch = class {
667
- #nodeToEdges;
668
- #select;
669
- /** Per node, its discovery index, or `-1` before it is reached. */
670
- #indices;
671
- /** Per node, the lowest discovery index reachable from it. */
672
- #lowLinks;
673
- #componentIndices;
674
- /** The nodes whose component is still open, and their membership. */
675
- #stack = [];
676
- #onStack;
677
- #nextIndex = 0;
678
- #nextComponent = 0;
679
- constructor(nodeToEdges, select) {
680
- const count = nodeToEdges.length;
681
- this.#nodeToEdges = nodeToEdges;
682
- this.#select = select;
683
- this.#indices = new Array(count).fill(-1);
684
- this.#lowLinks = new Array(count).fill(-1);
685
- this.#componentIndices = new Array(count).fill(-1);
686
- this.#onStack = new Array(count).fill(false);
687
- }
688
- search() {
689
- for (let start = 0; start < this.#nodeToEdges.length; start++) if (this.#indices[start] === -1) this.#searchFrom(start);
690
- return this.#componentIndices;
691
- }
692
- /** Traverses every unreached node reachable from {@link start}. */
693
- #searchFrom(start) {
694
- const traversal = [this.#discover(start)];
695
- while (traversal.length > 0) {
696
- const frame = traversal.at(-1);
697
- if (frame.nextEdge < frame.edges.length) {
698
- const target = this.#select(frame.edges[frame.nextEdge++]);
699
- if (this.#indices[target] === -1) traversal.push(this.#discover(target));
700
- else if (this.#onStack[target]) this.#lowerLink(frame.node, this.#indices[target]);
701
- continue;
702
- }
703
- traversal.pop();
704
- if (this.#lowLinks[frame.node] === this.#indices[frame.node]) this.#closeComponent(frame.node);
705
- const source = traversal.at(-1);
706
- if (source) this.#lowerLink(source.node, this.#lowLinks[frame.node]);
707
- }
708
- }
709
- /**
710
- * Records a node reached for the first time and returns its traversal frame,
711
- * which resumes partway through the edges after the traversal returns from a
712
- * target.
713
- */
714
- #discover(node) {
715
- this.#indices[node] = this.#nextIndex;
716
- this.#lowLinks[node] = this.#nextIndex;
717
- this.#nextIndex++;
718
- this.#stack.push(node);
719
- this.#onStack[node] = true;
720
- return {
721
- node,
722
- edges: this.#nodeToEdges[node],
723
- nextEdge: 0
724
- };
725
- }
726
- #lowerLink(node, lowLink) {
727
- this.#lowLinks[node] = Math.min(this.#lowLinks[node], lowLink);
728
- }
729
- /**
730
- * Assigns a component to {@link root} and to every node stacked above it, the
731
- * rest of the cycle it forms.
732
- */
733
- #closeComponent(root) {
734
- while (true) {
735
- const member = this.#stack.pop();
736
- this.#onStack[member] = false;
737
- this.#componentIndices[member] = this.#nextComponent;
738
- if (member === root) break;
739
- }
740
- this.#nextComponent++;
741
- }
742
- };
743
-
744
571
  //#endregion
745
572
  //#region src/formats/callgrind/matches.ts
746
573
  const matchesCallgrind = (bytes) => {
@@ -1140,6 +967,28 @@ var FormatDetectError = class extends ProfilerMdError {
1140
967
  this.errors = errors;
1141
968
  }
1142
969
  };
970
+ /**
971
+ * Thrown when the format the caller specified rejected the input.
972
+ *
973
+ * {@link FormatRejectionError.cause} is the error the format's parse threw.
974
+ */
975
+ var FormatRejectionError = class extends ProfilerMdError {
976
+ constructor(message, options) {
977
+ super(message, options);
978
+ this.name = "FormatRejectionError";
979
+ }
980
+ };
981
+ /**
982
+ * The errors a conversion error wraps that a parser threw without classifying
983
+ * them, in detection order. Empty when the error is not a conversion error, or
984
+ * when every wrapped error is a {@link FormatParseError}.
985
+ */
986
+ const unclassifiedParseFailures = (error) => {
987
+ if (error instanceof FormatDetectError) return error.errors.filter(isUnclassifiedParseFailure);
988
+ if (error instanceof FormatRejectionError) return isUnclassifiedParseFailure(error.cause) ? [error.cause] : [];
989
+ return [];
990
+ };
991
+ const isUnclassifiedParseFailure = (error) => !(error instanceof FormatParseError);
1143
992
 
1144
993
  //#endregion
1145
994
  //#region src/formats/callgrind/parse.ts
@@ -1765,6 +1614,7 @@ const collapsedConverter = {
1765
1614
  languages: [
1766
1615
  `elixir`,
1767
1616
  `java`,
1617
+ `php`,
1768
1618
  `python`,
1769
1619
  `ruby`
1770
1620
  ],
@@ -2450,40 +2300,129 @@ const selectTopN = (values, topN, select) => {
2450
2300
  };
2451
2301
 
2452
2302
  //#endregion
2453
- //#region src/modalities/table.ts
2454
- /**
2455
- * A right-aligned numeric cell formatted via {@link format}, with deltas
2456
- * formatted via {@link formatDelta} (defaults to {@link format}).
2457
- */
2458
- const numberCell = (value, format, formatDelta = format) => ({
2459
- type: `number`,
2460
- value,
2461
- format,
2462
- formatDelta
2463
- });
2464
- /** A right-aligned numeric cell formatted as a percent. */
2465
- const percentCell = (fraction) => numberCell(fraction, formatPercent);
2466
- /** A right-aligned numeric cell formatted as a count. */
2467
- const countCell = (count) => numberCell(count, formatCount);
2468
- /** A right-aligned numeric cell formatted as bytes. */
2469
- const bytesCell = (bytes) => numberCell(bytes, formatBytes, formatBytesDelta);
2470
- /** A left-aligned text cell. */
2471
- const textCell = (children) => ({
2303
+ //#region src/helpers/markdown.ts
2304
+ const text$1 = (value) => ({
2472
2305
  type: `text`,
2473
- children: typeof children === `string` ? [text$1(children)] : children
2306
+ value: value.replaceAll(/\r(?!\n)/gu, ` `)
2474
2307
  });
2475
- /** A left-aligned cell holding a single code span. */
2476
- const codeCell = (value) => textCell([inlineCode(value)]);
2477
- const formatTable = (columns, rows) => table(columns.map((column) => column.header), rows.map((row) => columns.map((column) => formatCell(column.cellOf(row)))));
2478
- const formatCell = (cell) => {
2479
- switch (cell.type) {
2480
- case `number`: return [text$1(cell.format(cell.value))];
2481
- case `text`: return cell.children;
2482
- }
2483
- };
2484
- /**
2485
- * Formats {@link rows} as a diff table, inserting `Change` and `Delta` columns
2486
- * derived from the {@link Column.primary} column at the
2308
+ const inlineCode = (value) => ({
2309
+ type: `inlineCode`,
2310
+ value: value.replaceAll(/\r\n|[\r\n]/gu, ` `).replaceAll(`\\|`, `\\ |`)
2311
+ });
2312
+ const heading = (depth, children) => ({
2313
+ type: `heading`,
2314
+ depth,
2315
+ children: toPhrasing(children)
2316
+ });
2317
+ const paragraph = (children) => ({
2318
+ type: `paragraph`,
2319
+ children: toPhrasing(children)
2320
+ });
2321
+ const toPhrasing = (children) => typeof children === `string` ? [text$1(children)] : children;
2322
+ /**
2323
+ * Builds phrasing content from a template, turning literal segments and
2324
+ * interpolated strings into text nodes and splicing in interpolated nodes.
2325
+ */
2326
+ const phrasing = (strings, ...values) => {
2327
+ const children = [];
2328
+ const push = (value) => {
2329
+ if (typeof value === `string`) {
2330
+ if (value) children.push(text$1(value));
2331
+ } else if (Array.isArray(value)) children.push(...value);
2332
+ else children.push(value);
2333
+ };
2334
+ for (const [index, string] of strings.entries()) {
2335
+ push(string);
2336
+ if (index < values.length) push(values[index]);
2337
+ }
2338
+ return children;
2339
+ };
2340
+ /**
2341
+ * Phrasing for an entity heading: a code-span name followed by its
2342
+ * parenthesized location. {@link headingNameLocationKey} recovers the
2343
+ * {@link nameLocationKey} key from this shape, so entity headings must be
2344
+ * built through this helper for the CLI highlighter's heading ↔ table
2345
+ * matching to work.
2346
+ */
2347
+ const nameLocationPhrasing = (name, location) => phrasing`${inlineCode(name)} (${location})`;
2348
+ /** The key matching a {@link nameLocationPhrasing} heading to a table row. */
2349
+ const nameLocationKey = (name, location) => `${name} (${location})`;
2350
+ /**
2351
+ * Extracts the {@link nameLocationKey} key from a heading with the
2352
+ * {@link nameLocationPhrasing} shape, or returns null if the heading doesn't
2353
+ * have that shape.
2354
+ */
2355
+ const headingNameLocationKey = (heading) => {
2356
+ const nameIndex = heading.children.findIndex((child) => child.type === `inlineCode`);
2357
+ if (nameIndex === -1) return null;
2358
+ const name = nodeText(heading.children[nameIndex]);
2359
+ const after = heading.children.slice(nameIndex + 1).map(nodeText).join(``).trim();
2360
+ if (!after.startsWith(`(`) || !after.endsWith(`)`)) return null;
2361
+ return nameLocationKey(name, after.slice(1, -1));
2362
+ };
2363
+ /** The concatenated text content of a node's subtree. */
2364
+ const nodeText = (node) => {
2365
+ if (`value` in node && typeof node.value === `string`) return node.value;
2366
+ if (`children` in node && Array.isArray(node.children)) return node.children.map(nodeText).join(``);
2367
+ return ``;
2368
+ };
2369
+ /**
2370
+ * Prepends the given section header (a heading and any description) to
2371
+ * {@link sections}, or returns no sections if there are none.
2372
+ */
2373
+ const formatSectionGroup = (header, sections) => sections.length === 0 ? [] : [...header, ...sections];
2374
+ const table = (headers, rows) => ({
2375
+ type: `table`,
2376
+ align: headers.map((header) => typeof header !== `string` && header.align === `right` ? `right` : null),
2377
+ children: [tableRow(headers.map((header) => [text$1(typeof header === `string` ? header : header.content)])), ...rows.map(tableRow)]
2378
+ });
2379
+ const tableRow = (cells) => ({
2380
+ type: `tableRow`,
2381
+ children: cells.map((children) => ({
2382
+ type: `tableCell`,
2383
+ children
2384
+ }))
2385
+ });
2386
+ const mdastToMarkdown = (children) => toMarkdown({
2387
+ type: `root`,
2388
+ children
2389
+ }, { extensions: [gfmTableToMarkdown()] });
2390
+
2391
+ //#endregion
2392
+ //#region src/modalities/table.ts
2393
+ /**
2394
+ * A right-aligned numeric cell formatted via {@link format}, with deltas
2395
+ * formatted via {@link formatDelta} (defaults to {@link format}).
2396
+ */
2397
+ const numberCell = (value, format, formatDelta = format) => ({
2398
+ type: `number`,
2399
+ value,
2400
+ format,
2401
+ formatDelta
2402
+ });
2403
+ /** A right-aligned numeric cell formatted as a percent. */
2404
+ const percentCell = (fraction) => numberCell(fraction, formatPercent);
2405
+ /** A right-aligned numeric cell formatted as a count. */
2406
+ const countCell = (count) => numberCell(count, formatCount);
2407
+ /** A right-aligned numeric cell formatted as bytes. */
2408
+ const bytesCell = (bytes) => numberCell(bytes, formatBytes, formatBytesDelta);
2409
+ /** A left-aligned text cell. */
2410
+ const textCell = (children) => ({
2411
+ type: `text`,
2412
+ children: typeof children === `string` ? [text$1(children)] : children
2413
+ });
2414
+ /** A left-aligned cell holding a single code span. */
2415
+ const codeCell = (value) => textCell([inlineCode(value)]);
2416
+ const formatTable = (columns, rows) => table(columns.map((column) => column.header), rows.map((row) => columns.map((column) => formatCell(column.cellOf(row)))));
2417
+ const formatCell = (cell) => {
2418
+ switch (cell.type) {
2419
+ case `number`: return [text$1(cell.format(cell.value))];
2420
+ case `text`: return cell.children;
2421
+ }
2422
+ };
2423
+ /**
2424
+ * Formats {@link rows} as a diff table, inserting `Change` and `Delta` columns
2425
+ * derived from the {@link Column.primary} column at the
2487
2426
  * {@link Column.changeDeltaBefore} column.
2488
2427
  *
2489
2428
  * The two sides' cells line up by column, so each numeric cell formats its own
@@ -2576,7 +2515,7 @@ const CATEGORY_NAMES = {
2576
2515
  stdlib: `Standard library`,
2577
2516
  native: `Native`,
2578
2517
  unknown: `Unknown`,
2579
- "garbage collector": `Garbage collector`,
2518
+ "garbage-collector": `Garbage collector`,
2580
2519
  compiler: `Compiler`,
2581
2520
  jit: `JIT`,
2582
2521
  kernel: `Kernel`,
@@ -2584,15 +2523,15 @@ const CATEGORY_NAMES = {
2584
2523
  object: `Object`,
2585
2524
  array: `Array`,
2586
2525
  string: `String`,
2587
- "concatenated string": `Concatenated string`,
2588
- "sliced string": `Sliced string`,
2526
+ "concatenated-string": `Concatenated string`,
2527
+ "sliced-string": `Sliced string`,
2589
2528
  function: `Function`,
2590
2529
  code: `Code`,
2591
2530
  regexp: `Regular expression`,
2592
2531
  number: `Number`,
2593
- "big number": `Big number`,
2532
+ "big-number": `Big number`,
2594
2533
  symbol: `Symbol`,
2595
- "object shape": `Object shape`,
2534
+ "object-shape": `Object shape`,
2596
2535
  internal: `Internal`,
2597
2536
  synthetic: `Synthetic`
2598
2537
  };
@@ -3659,16 +3598,16 @@ const HEAP_SNAPSHOT_NODE_CATEGORIES = [
3659
3598
  `object`,
3660
3599
  `array`,
3661
3600
  `string`,
3662
- `concatenated string`,
3663
- `sliced string`,
3601
+ `concatenated-string`,
3602
+ `sliced-string`,
3664
3603
  `function`,
3665
3604
  `code`,
3666
3605
  `regexp`,
3667
3606
  `number`,
3668
- `big number`,
3607
+ `big-number`,
3669
3608
  `symbol`,
3670
3609
  `native`,
3671
- `object shape`,
3610
+ `object-shape`,
3672
3611
  `internal`,
3673
3612
  `synthetic`,
3674
3613
  `unknown`
@@ -4496,7 +4435,7 @@ const SYNTHETIC_FRAME_LABEL = /^\((?<label>[A-Za-z][A-Za-z0-9 _-]*)\)$/u;
4496
4435
  * name (`jit`, `kernel`, `native`).
4497
4436
  */
4498
4437
  const SYNTHETIC_FRAME_LABEL_CATEGORIES = /* @__PURE__ */ new Map([
4499
- [`garbage collector`, `garbage collector`],
4438
+ [`garbage collector`, `garbage-collector`],
4500
4439
  [`compiler`, `compiler`],
4501
4440
  [`idle`, `idle`],
4502
4441
  [`unknown`, `unknown`]
@@ -4599,7 +4538,7 @@ const JVM_STDLIB_PACKAGE = /^(?:(?:java|javax|jdk|sun|com[./]sun|kotlin|kotlinx|
4599
4538
  *
4600
4539
  * A GC write barrier is generated code executed inline in a compiled method, so
4601
4540
  * it satisfies `jit` as literally as the dispatch stubs do. It is
4602
- * `garbage collector` because a named activity takes precedence, leaving `jit`
4541
+ * `garbage-collector` because a named activity takes precedence, leaving `jit`
4603
4542
  * for generated code with no more specific one. Folding it into `jit` would
4604
4543
  * hide the cost of collection and leave `jit` meaning two unrelated things.
4605
4544
  */
@@ -4607,7 +4546,7 @@ const hotspotRuntimeCategory = (entry) => {
4607
4546
  const { name } = entry;
4608
4547
  if (name === void 0 || !isHotspotNativeStackFrame(entry)) return;
4609
4548
  if (JIT_STUB.test(name)) return `jit`;
4610
- if (GC_STUB.test(name)) return `garbage collector`;
4549
+ if (GC_STUB.test(name)) return `garbage-collector`;
4611
4550
  return HOTSPOT_COMPILER.test(name) ? `compiler` : void 0;
4612
4551
  };
4613
4552
  /**
@@ -4719,7 +4658,7 @@ const nativeModuleCategory = ({ name, location }) => location && !sourceReferenc
4719
4658
  const jvmConstructorCategory = (name) => CLASS_NAME_TO_CATEGORY$1.get(name);
4720
4659
  const CLASS_NAME_TO_CATEGORY$1 = new Map(Object.entries({
4721
4660
  "java.lang.String": `string`,
4722
- "java.lang.Class": `object shape`,
4661
+ "java.lang.Class": `object-shape`,
4723
4662
  "java.util.regex.Pattern": `regexp`,
4724
4663
  "java.lang.Byte": `number`,
4725
4664
  "java.lang.Short": `number`,
@@ -4727,8 +4666,8 @@ const CLASS_NAME_TO_CATEGORY$1 = new Map(Object.entries({
4727
4666
  "java.lang.Long": `number`,
4728
4667
  "java.lang.Float": `number`,
4729
4668
  "java.lang.Double": `number`,
4730
- "java.math.BigInteger": `big number`,
4731
- "java.math.BigDecimal": `big number`
4669
+ "java.math.BigInteger": `big-number`,
4670
+ "java.math.BigDecimal": `big-number`
4732
4671
  }));
4733
4672
  /** Converts an internal class name (`java/util/Arrays`) to source form. */
4734
4673
  const jvmSourceClassName = (internalName) => internalName.replaceAll(`/`, `.`);
@@ -5202,7 +5141,7 @@ const buildHeapSnapshot = (dump, nodes) => {
5202
5141
  const unresolvedCategoryOf$2 = (nodeOrdinal, { bytes }, { recordOffsets }) => {
5203
5142
  if (nodeOrdinal === GC_ROOT_ORDINAL) return { category: `synthetic` };
5204
5143
  switch (bytes[recordOffsets[nodeOrdinal] - 1]) {
5205
- case HPROF_GC_CLASS_DUMP: return { category: `object shape` };
5144
+ case HPROF_GC_CLASS_DUMP: return { category: `object-shape` };
5206
5145
  case HPROF_GC_INSTANCE_DUMP: return { category: `object` };
5207
5146
  default: return { category: `array` };
5208
5147
  }
@@ -5769,11 +5708,11 @@ const CONTENTIONS = countMetricOf(`contention`, { improvement: `decrease` });
5769
5708
  * metric and is ranked by its sample count.
5770
5709
  *
5771
5710
  * Allocation events sample: `jdk.ObjectAllocationSample` stands in for the
5772
- * allocations since the previous one, a TLAB event fires per TLAB refill or
5773
- * per allocation outside one, and async-profiler's `--alloc <bytes>` and
5774
- * `--nativemem <bytes>` set a sampling interval for the heap and
5775
- * `profiler.Malloc` events. Live-object and lock events each record one
5776
- * occurrence of what their kind names, so their rate is per object or per
5711
+ * allocations since the previous one, a TLAB event stands for a whole TLAB
5712
+ * refill or for one allocation made outside a TLAB, and async-profiler's
5713
+ * `--alloc <bytes>` and `--nativemem <bytes>` set a sampling interval for the
5714
+ * heap and `profiler.Malloc` events. Live-object and lock events each record
5715
+ * one occurrence of what their kind names, so their rate is per object or per
5777
5716
  * contention rather than per sample.
5778
5717
  */
5779
5718
  const KINDS = [
@@ -5836,7 +5775,7 @@ const EVENT_KINDS_BY_NAME = [
5836
5775
  }],
5837
5776
  [`jdk.ObjectAllocationInNewTLAB`, {
5838
5777
  kind: `alloc`,
5839
- weightField: `allocationSize`,
5778
+ weightField: `tlabSize`,
5840
5779
  allocFamily: `tlab`
5841
5780
  }],
5842
5781
  [`jdk.ObjectAllocationOutsideTLAB`, {
@@ -9339,7 +9278,12 @@ const profileFieldWireTypes = [
9339
9278
  //#endregion
9340
9279
  //#region src/formats/pprof/parse.ts
9341
9280
  const parsePprof = (bytes) => {
9342
- const profile = Profile.decode(bytes);
9281
+ let profile;
9282
+ try {
9283
+ profile = Profile.decode(bytes);
9284
+ } catch (error) {
9285
+ throw new FormatParseError(`invalid protobuf encoding: ${reasonOf(error)}`, { cause: error });
9286
+ }
9343
9287
  const string = makeStringReader(profile);
9344
9288
  const originHint = pprofOriginHint(profile, string);
9345
9289
  const layouts = parseValueLayouts(profile, string);
@@ -9513,7 +9457,7 @@ const parseFunctionStackFrames = (profile, string) => {
9513
9457
  location: {
9514
9458
  type: `file`,
9515
9459
  urlOrPath: string(func.filename),
9516
- line: knownPprofLine(Number(func.startLine))
9460
+ line: knownPprofLine(func.startLine)
9517
9461
  }
9518
9462
  });
9519
9463
  }
@@ -9523,11 +9467,20 @@ const parseFunctionStackFrames = (profile, string) => {
9523
9467
  };
9524
9468
  };
9525
9469
  /**
9526
- * Normalizes a pprof line to `undefined` when unknown: proto3 has no field
9527
- * presence for scalars, so an unset `Function.start_line` or `Line.line`
9528
- * decodes to `0`.
9470
+ * Normalizes a pprof line to `undefined` when unknown.
9471
+ *
9472
+ * proto3 has no field presence for scalars, so an unset `Function.start_line`
9473
+ * or `Line.line` decodes to `0`.
9474
+ *
9475
+ * Some profilers (e.g. PProf.jl) write `-1` for an unknown line, which
9476
+ * `pprof-format` decodes as the unsigned 64-bit value, so a line is read back
9477
+ * as the signed integer the field is declared as.
9529
9478
  */
9530
- const knownPprofLine = (line) => line !== void 0 && line > 0 ? line : void 0;
9479
+ const knownPprofLine = (line) => {
9480
+ if (line === void 0) return;
9481
+ const signedLine = typeof line === `bigint` ? BigInt.asIntN(64, line) : line;
9482
+ return signedLine > 0 ? Number(signedLine) : void 0;
9483
+ };
9531
9484
  /**
9532
9485
  * Each location resolves to its frame indices and lines, dropping any frame
9533
9486
  * whose function is absent from the table (unsymbolized) rather than passing a
@@ -9539,7 +9492,7 @@ const resolveLocationStackFrames = (profile, frameIndexByFunctionId) => {
9539
9492
  const frame = frameIndexByFunctionId.get(functionId);
9540
9493
  return frame === void 0 ? [] : {
9541
9494
  frame,
9542
- line: Number(line)
9495
+ line
9543
9496
  };
9544
9497
  }));
9545
9498
  return framesByLocationId;
@@ -9741,6 +9694,127 @@ const decodeHeaderLine = (bytes) => {
9741
9694
  const NEWLINE = 10;
9742
9695
  let textDecoder;
9743
9696
 
9697
+ //#endregion
9698
+ //#region src/formats/parse.ts
9699
+ const parseAsFormatAsync = async (converter, data) => {
9700
+ try {
9701
+ return classifyLazyParseFailures(converter, converter.type === `json` ? converter.parse(await parseJsonAsync(data)) : await converter.parseAsync(guardStreamReads(dataToStream(data))));
9702
+ } catch (error) {
9703
+ rethrowInputReadFailure(error);
9704
+ throw toFormatRejectionError(converter, error);
9705
+ }
9706
+ };
9707
+ /**
9708
+ * Wraps each lazily consumed iterable of the parsed inputs, so an error the
9709
+ * parser throws while aggregation consumes it is classified the same way as
9710
+ * one it throws before returning.
9711
+ *
9712
+ * The wrapper is a plain iterator object, because a delegating generator costs
9713
+ * more per item.
9714
+ */
9715
+ const classifyLazyParseFailures = (converter, parsed) => {
9716
+ const toError = (error) => toFormatRejectionError(converter, error);
9717
+ return parsed.map((input) => {
9718
+ switch (input.type) {
9719
+ case `call-stack-profile`: return {
9720
+ ...input,
9721
+ observations: classifyIterableFailures(input.observations, toError),
9722
+ ...input.lineMetrics && { lineMetrics: classifyIterableFailures(input.lineMetrics, toError) }
9723
+ };
9724
+ case `call-graph`: return input;
9725
+ case `heap-snapshot`: return {
9726
+ ...input,
9727
+ nodes: classifyIterableFailures(input.nodes, toError)
9728
+ };
9729
+ }
9730
+ });
9731
+ };
9732
+ const classifyIterableFailures = (iterable, toError) => ({ [Symbol.iterator]: () => {
9733
+ const iterator = iterable[Symbol.iterator]();
9734
+ return {
9735
+ next: () => {
9736
+ try {
9737
+ return iterator.next();
9738
+ } catch (error) {
9739
+ throw toError(error);
9740
+ }
9741
+ },
9742
+ return: (value) => iterator.return?.(value) ?? {
9743
+ done: true,
9744
+ value: void 0
9745
+ }
9746
+ };
9747
+ } });
9748
+ /**
9749
+ * Decodes JSON, wrapping a decoding failure in a {@link FormatParseError}.
9750
+ *
9751
+ * A JSON format's parser cannot check anything before decoding succeeds, so a
9752
+ * decoding failure is the input's, however the decoder reports it. A failure to
9753
+ * read the data propagates as an {@link InputReadError} instead.
9754
+ */
9755
+ const parseJson = (data) => {
9756
+ try {
9757
+ return JumboJSON.parse(typeof data === `string` || ArrayBuffer.isView(data) || Array.isArray(data) ? data : guardIterableReads(data));
9758
+ } catch (error) {
9759
+ throw toInvalidJsonError(error);
9760
+ }
9761
+ };
9762
+ const parseJsonAsync = async (data) => {
9763
+ try {
9764
+ return await JumboJSON.parseAsync(guardStreamReads(dataToStream(data)), { sizeHint: data instanceof Blob ? data.size : void 0 });
9765
+ } catch (error) {
9766
+ throw toInvalidJsonError(error);
9767
+ }
9768
+ };
9769
+ const toInvalidJsonError = (error) => error instanceof InputReadError ? error : new FormatParseError(`invalid JSON: ${reasonOf(error)}`, { cause: error });
9770
+ /**
9771
+ * Thrown in place of an error the caller's data threw while a parser read it,
9772
+ * so a failure to read the data is told apart from a failure to parse it.
9773
+ */
9774
+ var InputReadError = class extends Error {
9775
+ constructor(cause) {
9776
+ super(`failed to read the input`, { cause });
9777
+ this.name = "InputReadError";
9778
+ }
9779
+ };
9780
+ /** Rethrows the error the caller's data threw, when the error stands in for one. */
9781
+ const rethrowInputReadFailure = (error) => {
9782
+ if (error instanceof InputReadError) throw error.cause;
9783
+ };
9784
+ function* guardIterableReads(iterable) {
9785
+ try {
9786
+ yield* iterable;
9787
+ } catch (error) {
9788
+ throw new InputReadError(error);
9789
+ }
9790
+ }
9791
+ const guardStreamReads = (stream) => {
9792
+ const reader = stream.getReader();
9793
+ return new ReadableStream({
9794
+ pull: async (controller) => {
9795
+ let result;
9796
+ try {
9797
+ result = await reader.read();
9798
+ } catch (error) {
9799
+ throw new InputReadError(error);
9800
+ }
9801
+ if (result.done) controller.close();
9802
+ else controller.enqueue(result.value);
9803
+ },
9804
+ cancel: (reason) => reader.cancel(reason)
9805
+ });
9806
+ };
9807
+ const dataToStream = (data) => data instanceof Blob ? data.stream() : data;
9808
+ const toFormatRejectionError = (converter, error) => new FormatRejectionError(describeParseFailure(converter, error), { cause: error });
9809
+ /**
9810
+ * A parse's failure as `<title>: <reason>`.
9811
+ *
9812
+ * A {@link FormatParseError}'s message states the violation the parser
9813
+ * identified. The parser did not classify any other error, so its reason is
9814
+ * `failed to parse the input: <message>`.
9815
+ */
9816
+ const describeParseFailure = (converter, error) => `${converter.title}: ${error instanceof FormatParseError ? reasonOf(error) : `failed to parse the input: ${reasonOf(error)}`}`;
9817
+
9744
9818
  //#endregion
9745
9819
  //#region src/formats/systing/parse.ts
9746
9820
  const parseSysting = (bytes) => {
@@ -9830,7 +9904,7 @@ var SystingProfileBuilder = class {
9830
9904
  }
9831
9905
  }
9832
9906
  #addRecord(line) {
9833
- const record = JSON.parse(line);
9907
+ const record = parseJson(line);
9834
9908
  if (!Array.isArray(record)) throw new FormatParseError(`record is not an array`);
9835
9909
  switch (record[0]) {
9836
9910
  case `f`: {
@@ -9923,12 +9997,7 @@ const cpuMetric = (header) => {
9923
9997
  * stack order is unsupported.
9924
9998
  */
9925
9999
  const parseSystingHeader = (line) => {
9926
- let json;
9927
- try {
9928
- json = JSON.parse(line);
9929
- } catch {
9930
- throw new FormatParseError(`header is not JSON`);
9931
- }
10000
+ const json = parseJson(line);
9932
10001
  if (typeof json !== `object` || json === null || Array.isArray(json)) throw new FormatParseError(`header is not an object`);
9933
10002
  const header = json;
9934
10003
  const version = header.systing_profile_export;
@@ -10390,7 +10459,7 @@ const formatRetainerEdgeLabel = (retainerOrdinal, edgeIndex, snapshot, fieldLayo
10390
10459
  const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) => {
10391
10460
  const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
10392
10461
  const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
10393
- if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
10462
+ if (edgeType === fieldLayout.edgeTypeElement) return Number.isSafeInteger(edgeNameOrIndex) ? `[${edgeNameOrIndex}]` : `[<unknown>]`;
10394
10463
  const rawEdgeName = strings[edgeNameOrIndex];
10395
10464
  const fileReference = rawEdgeName ? makeFileReference(rawEdgeName) : void 0;
10396
10465
  return `.${fileReference ? formatSourceLocation(fileReference, options) : rawEdgeName}`;
@@ -10447,16 +10516,16 @@ const V8_NODE_TYPE_TO_CATEGORY = /* @__PURE__ */ new Map([
10447
10516
  [`object`, `object`],
10448
10517
  [`array`, `array`],
10449
10518
  [`string`, `string`],
10450
- [`concatenated string`, `concatenated string`],
10451
- [`sliced string`, `sliced string`],
10519
+ [`concatenated string`, `concatenated-string`],
10520
+ [`sliced string`, `sliced-string`],
10452
10521
  [`closure`, `function`],
10453
10522
  [`code`, `code`],
10454
10523
  [`regexp`, `regexp`],
10455
10524
  [`number`, `number`],
10456
- [`bigint`, `big number`],
10525
+ [`bigint`, `big-number`],
10457
10526
  [`symbol`, `symbol`],
10458
10527
  [`native`, `native`],
10459
- [`object shape`, `object shape`],
10528
+ [`object shape`, `object-shape`],
10460
10529
  [`hidden`, `internal`],
10461
10530
  [`synthetic`, `synthetic`]
10462
10531
  ]);
@@ -10808,7 +10877,7 @@ const CATEGORY_TO_CLASS_NAMES = {
10808
10877
  */
10809
10878
  const jscConstructorCategory = (name) => CLASS_NAME_TO_CATEGORY.get(name);
10810
10879
  const CLASS_NAME_TO_CATEGORY = new Map(Object.entries({
10811
- Structure: `object shape`,
10880
+ Structure: `object-shape`,
10812
10881
  "Immutable Butterfly": `array`,
10813
10882
  SparseArrayValueMap: `array`,
10814
10883
  Callee: `function`,
@@ -11260,17 +11329,63 @@ const ELIXIR_CORE_MODULES = /* @__PURE__ */ new Set([
11260
11329
  /**
11261
11330
  * The Excimer sampling profiler for PHP.
11262
11331
  *
11263
- * Markerless: its speedscope output carries plain file paths with no
11264
- * interpreter-specific evidence. Detection instead relies on the speedscope
11265
- * parser's origin hint from the file's self-identifying `exporter` field.
11332
+ * Its speedscope output contains plain file paths and its collapsed output
11333
+ * contains no location, so {@link CLOSURE_FRAME} is the only evidence in either
11334
+ * format. Detection also uses the speedscope parser's origin hint from the
11335
+ * file's self-identifying `exporter` field.
11266
11336
  */
11267
11337
  const excimerOriginSpec = {
11268
11338
  id: `excimer`,
11269
11339
  title: `Excimer`,
11270
- formats: [`speedscope`],
11271
- isMarkerEntry: () => false,
11272
- categorizeEntry: categorizeGenericEntry
11340
+ formats: [`collapsed`, `speedscope`],
11341
+ isMarkerEntry: ({ name }) => name !== void 0 && CLOSURE_FRAME.test(name),
11342
+ categorizeEntry: (entry) => vendorCategory(entry) ?? (entry.location ? `ours` : `unknown`),
11343
+ normalizeStackFrame: (input) => {
11344
+ const { name, location } = input;
11345
+ if (name === void 0) return input;
11346
+ const closure = CLOSURE_FRAME.exec(name);
11347
+ if (closure) {
11348
+ const { file, line } = closure.groups;
11349
+ return { location: {
11350
+ type: `file`,
11351
+ urlOrPath: file,
11352
+ line: Number(line)
11353
+ } };
11354
+ }
11355
+ if (location) return input;
11356
+ if (name.includes(`/`)) return { location: {
11357
+ type: `file`,
11358
+ urlOrPath: name
11359
+ } };
11360
+ const separator = name.lastIndexOf(`::`);
11361
+ if (separator === -1) return input;
11362
+ return {
11363
+ name: name.slice(separator + 2),
11364
+ location: {
11365
+ type: `logical`,
11366
+ name: name.slice(0, separator)
11367
+ }
11368
+ };
11369
+ }
11273
11370
  };
11371
+ /**
11372
+ * An anonymous function, which Excimer names by its file and the line its
11373
+ * definition starts on: `{closure:/srv/app/Hooks.php(42)}`.
11374
+ *
11375
+ * PHP itself writes `{closure}`, and from 8.4 `{closure:/srv/app/Hooks.php:42}`,
11376
+ * so the parenthesized line marks Excimer's output in either format.
11377
+ */
11378
+ const CLOSURE_FRAME = /^\{closure:(?<file>.+)\((?<line>\d+)\)\}$/su;
11379
+ /**
11380
+ * Categorizes a frame under Composer's `vendor/` as `third-party`.
11381
+ *
11382
+ * A collapsed frame keeps its declaring class instead of a file, and a class
11383
+ * name contains no install directory, so only file-scope and closure frames
11384
+ * reach this rule.
11385
+ */
11386
+ const vendorCategory = ({ location }) => location && VENDOR_DIRECTORY.test(sourceReferencePathOrName(location)) ? `third-party` : void 0;
11387
+ /** Composer's install directory, at the root of a project or of a package. */
11388
+ const VENDOR_DIRECTORY = /(?:^|\/)vendor\//u;
11274
11389
 
11275
11390
  //#endregion
11276
11391
  //#region src/origins/specs/ghc.ts
@@ -11327,7 +11442,7 @@ const BOOT_LIBRARY_SOURCE = /^libraries\/[^/]+\//u;
11327
11442
  */
11328
11443
  const runtimeActivityCategory = ({ name, location }) => location || name === void 0 ? void 0 : RUNTIME_ACTIVITY_CATEGORIES.get(name);
11329
11444
  /** The built-in cost centre names that name a runtime activity. */
11330
- const RUNTIME_ACTIVITY_CATEGORIES = /* @__PURE__ */ new Map([[`GC.GC`, `garbage collector`], [`IDLE.IDLE`, `idle`]]);
11445
+ const RUNTIME_ACTIVITY_CATEGORIES = /* @__PURE__ */ new Map([[`GC.GC`, `garbage-collector`], [`IDLE.IDLE`, `idle`]]);
11331
11446
 
11332
11447
  //#endregion
11333
11448
  //#region src/origins/specs/go.ts
@@ -11337,19 +11452,32 @@ const RUNTIME_ACTIVITY_CATEGORIES = /* @__PURE__ */ new Map([[`GC.GC`, `garbage
11337
11452
  *
11338
11453
  * Go function names embed the import path of their package
11339
11454
  * (`encoding/json.Marshal`, `github.com/user/repo/pkg.Func`, `main.work`), so
11340
- * categorization follows Go's own convention: a first path segment without a
11341
- * dot is a standard-library package, a domain-like first segment is a
11342
- * downloaded module, and the `main` package is the profiled program.
11455
+ * categorization follows Go's own convention: the `main` package is the
11456
+ * profiled program, and a first path segment naming a standard-library
11457
+ * package is Go's own code where the file agrees. A dependency's location
11458
+ * categorizes it, since the profiled program's own import paths may resemble a
11459
+ * dependency's.
11460
+ *
11461
+ * A `-trimpath` build rewrites every file path to the import path alone,
11462
+ * stripping the GOROOT prefix from the standard library and the module cache
11463
+ * prefix from a downloaded module, and leaves function names unchanged. The
11464
+ * profiled program's own packages keep their module path, so under `-trimpath`
11465
+ * they take the domain-like shape of a downloaded module. Only the module
11466
+ * cache's `@version` segment separates the two.
11467
+ *
11468
+ * A `GO111MODULE=off` build resolves a dependency and the profiled program's
11469
+ * own packages alike under `$GOPATH/src/`, under equally domain-like import
11470
+ * paths, so its dependencies are categorized `ours`.
11343
11471
  */
11344
11472
  const goOriginSpec = {
11345
11473
  id: `go`,
11346
11474
  title: `pprof`,
11347
11475
  formats: [`pprof`],
11348
- isMarkerEntry: (entry) => (entry.name?.startsWith(`runtime.`) ?? false) && entry.location !== void 0 && sourceReferencePathOrName(entry.location).includes(`/go/src/`),
11349
- categorizeEntry: (entry) => goCollectorCategory(entry) ?? goModuleCacheCategory(entry) ?? locationlessCategory(entry) ?? goPackageCategory(entry)
11476
+ isMarkerEntry: (entry) => (entry.name?.startsWith(`runtime.`) ?? false) && isStdlibLocated(entry.location),
11477
+ categorizeEntry: (entry) => goCollectorCategory(entry) ?? goDependencyCategory(entry) ?? locationlessCategory(entry) ?? goPackageCategory(entry)
11350
11478
  };
11351
11479
  /**
11352
- * Categorizes Go's collector as `garbage collector`: the background mark
11480
+ * Categorizes Go's collector as `garbage-collector`: the background mark
11353
11481
  * workers and their drain loops, the sweeper, and the assist path a goroutine
11354
11482
  * enters when it allocates faster than the collector reclaims.
11355
11483
  *
@@ -11358,17 +11486,36 @@ const goOriginSpec = {
11358
11486
  * would report most of a heap profile as collection cost, a claim the profile
11359
11487
  * doesn't make.
11360
11488
  *
11361
- * The GOROOT guard keeps a package of the profiled program named `runtime` from
11362
- * matching, since the location distinguishes them and the name doesn't.
11489
+ * The standard-library guard keeps a package of the profiled program named
11490
+ * `runtime` from matching, since only the location distinguishes them.
11363
11491
  */
11364
- const goCollectorCategory = ({ name, location }) => name !== void 0 && GO_COLLECTOR.test(name) && (location === void 0 || sourceReferencePathOrName(location).includes(`/go/src/`)) ? `garbage collector` : void 0;
11492
+ const goCollectorCategory = ({ name, location }) => name !== void 0 && GO_COLLECTOR.test(name) && (location === void 0 || isStdlibLocated(location)) ? `garbage-collector` : void 0;
11365
11493
  /** Go's collector entry points, all in the `runtime` package. */
11366
11494
  const GO_COLLECTOR = /^runtime\.(?:gc(?!WriteBarrier)[A-Z]|gcstopm|bgsweep|sweepone|\(\*sweepLocked\)\.sweep)/u;
11367
11495
  /**
11368
- * Categorizes a frame resolved from the Go module cache (`$GOPATH/pkg/mod/`),
11369
- * where `go get` downloads dependencies, as `third-party`.
11496
+ * Categorizes a frame resolved from a dependency as `third-party`.
11497
+ *
11498
+ * `go get` writes a downloaded module to `$GOPATH/pkg/mod/`, in a directory
11499
+ * whose name ends with `@version`. A `-trimpath` build strips the prefix and
11500
+ * leaves the `@version` segment. `go mod vendor` instead copies a dependency
11501
+ * into the profiled program's own `vendor/` directory, a path with neither the
11502
+ * prefix nor the `@version` segment.
11503
+ *
11504
+ * The standard library vendors packages of its own, so the standard-library
11505
+ * check runs first.
11506
+ */
11507
+ const goDependencyCategory = ({ location }) => {
11508
+ if (!location || isStdlibLocated(location)) return;
11509
+ const path = sourceReferencePathOrName(location);
11510
+ return path.includes(`/pkg/mod/`) || path.includes(`/vendor/`) || MODULE_CACHE_VERSION.test(path) ? `third-party` : void 0;
11511
+ };
11512
+ /**
11513
+ * The `@version` a module cache directory name ends with. Every Go module
11514
+ * version starts with a `v` followed by the major number, so the pattern
11515
+ * distinguishes the segment from an `@` in a directory containing the profiled
11516
+ * program.
11370
11517
  */
11371
- const goModuleCacheCategory = ({ location }) => location && sourceReferencePathOrName(location).includes(`/pkg/mod/`) ? `third-party` : void 0;
11518
+ const MODULE_CACHE_VERSION = /@v\d/u;
11372
11519
  /**
11373
11520
  * Categorizes a located frame by the import path embedded in its function name.
11374
11521
  *
@@ -11376,14 +11523,116 @@ const goModuleCacheCategory = ({ location }) => location && sourceReferencePathO
11376
11523
  * before here.
11377
11524
  */
11378
11525
  const goPackageCategory = ({ name, location }) => {
11379
- if (name === void 0) return `ours`;
11526
+ const stdlibLocated = isStdlibLocated(location);
11527
+ if (name === void 0) return stdlibLocated ? `stdlib` : `ours`;
11380
11528
  if (name === `main` || name.startsWith(`main.`)) return `ours`;
11381
- const dot = name.indexOf(`.`);
11382
- if (dot === -1) return `ours`;
11383
- const slash = name.indexOf(`/`);
11384
- if (slash !== -1 && dot < slash) return `third-party`;
11385
- return location !== void 0 && sourceReferencePathOrName(location).includes(`/go/src/`) ? `stdlib` : `ours`;
11529
+ const packagePath = goPackagePath(name);
11530
+ if (packagePath === void 0) return stdlibLocated ? `stdlib` : `ours`;
11531
+ return GO_STDLIB_PACKAGES.has(packagePath.split(`/`)[0]) && stdlibLocated ? `stdlib` : `ours`;
11532
+ };
11533
+ /**
11534
+ * Returns the import path of the package {@link name} declares, or `undefined`
11535
+ * for a bare linker symbol with no package.
11536
+ *
11537
+ * The symbol follows the import path after a dot, and both may contain further
11538
+ * dots (`encoding/json.(*decodeState).value`), so the package ends at the
11539
+ * first dot after the last slash. A generic instantiation's type arguments
11540
+ * contain import paths of their own
11541
+ * (`slices.Sort[go.shape.[]github.com/user/repo.T]`), so they are dropped
11542
+ * first.
11543
+ */
11544
+ const goPackagePath = (name) => {
11545
+ const path = name.slice(0, indexOrEnd(name, `[`));
11546
+ const dot = path.indexOf(`.`, path.lastIndexOf(`/`) + 1);
11547
+ return dot === -1 ? void 0 : path.slice(0, dot);
11548
+ };
11549
+ const indexOrEnd = (value, search) => {
11550
+ const index = value.indexOf(search);
11551
+ return index === -1 ? value.length : index;
11386
11552
  };
11553
+ /**
11554
+ * Returns whether {@link location} is in Go's own standard library.
11555
+ *
11556
+ * An ordinary build locates it in a GOROOT source tree. A `-trimpath` build
11557
+ * leaves each file at the relative import path of the package declaring it,
11558
+ * which starts with a standard-library package name. The path's own package
11559
+ * categorizes the frame, since Go inlines across packages and reports the
11560
+ * inlined frame at the file it was inlined into (`reflect.typedmemmove` at
11561
+ * `runtime/mbarrier.go`).
11562
+ *
11563
+ * The extension excludes a relative path another language's profiler wrote,
11564
+ * since the Go toolchain compiles Go and assembly sources alone. An absolute
11565
+ * path starts with an empty segment, which no package name matches.
11566
+ */
11567
+ const isStdlibLocated = (location) => {
11568
+ if (!location) return false;
11569
+ const path = sourceReferencePathOrName(location);
11570
+ return path.includes(`/go/src/`) || GO_STDLIB_PACKAGES.has(path.slice(0, indexOrEnd(path, `/`))) && GO_SOURCE_EXTENSION.test(path);
11571
+ };
11572
+ /** The extensions of the source files the Go compiler and assembler read. */
11573
+ const GO_SOURCE_EXTENSION = /\.(?:go|s)$/u;
11574
+ /**
11575
+ * Go's top-level standard-library import paths, as reported by `go list std`.
11576
+ * A dot-less first segment is reserved for the standard library, but the `go`
11577
+ * command still accepts a domain-less module path, so matching the set rather
11578
+ * than the shape keeps such a module's packages out of `stdlib`.
11579
+ *
11580
+ * Keep this set in sync with `go-std-packages.txt`, a pinned `go list std`,
11581
+ * since a top-level package a later Go release adds would otherwise be
11582
+ * categorized `ours`.
11583
+ */
11584
+ const GO_STDLIB_PACKAGES = /* @__PURE__ */ new Set([
11585
+ `archive`,
11586
+ `bufio`,
11587
+ `bytes`,
11588
+ `cmp`,
11589
+ `compress`,
11590
+ `container`,
11591
+ `context`,
11592
+ `crypto`,
11593
+ `database`,
11594
+ `debug`,
11595
+ `embed`,
11596
+ `encoding`,
11597
+ `errors`,
11598
+ `expvar`,
11599
+ `flag`,
11600
+ `fmt`,
11601
+ `go`,
11602
+ `hash`,
11603
+ `html`,
11604
+ `image`,
11605
+ `index`,
11606
+ `internal`,
11607
+ `io`,
11608
+ `iter`,
11609
+ `log`,
11610
+ `maps`,
11611
+ `math`,
11612
+ `mime`,
11613
+ `net`,
11614
+ `os`,
11615
+ `path`,
11616
+ `plugin`,
11617
+ `reflect`,
11618
+ `regexp`,
11619
+ `runtime`,
11620
+ `slices`,
11621
+ `sort`,
11622
+ `strconv`,
11623
+ `strings`,
11624
+ `structs`,
11625
+ `sync`,
11626
+ `syscall`,
11627
+ `testing`,
11628
+ `text`,
11629
+ `time`,
11630
+ `unicode`,
11631
+ `unique`,
11632
+ `unsafe`,
11633
+ `vendor`,
11634
+ `weak`
11635
+ ]);
11387
11636
 
11388
11637
  //#endregion
11389
11638
  //#region src/origins/swift.ts
@@ -11549,9 +11798,9 @@ const PACKED_ANONYMOUS = /^\(anonymous:L#(?<line>\d+):C#(?<column>\d+)\)$/u;
11549
11798
  const NODE_PROTOCOLS$1 = [`node:`];
11550
11799
  /**
11551
11800
  * Categorizes the `pprof` package's garbage-collection frame, labelled
11552
- * `Garbage Collection`, as `garbage collector`.
11801
+ * `Garbage Collection`, as `garbage-collector`.
11553
11802
  */
11554
- const garbageCollectionCategory = ({ name }) => name === `Garbage Collection` ? `garbage collector` : void 0;
11803
+ const garbageCollectionCategory = ({ name }) => name === `Garbage Collection` ? `garbage-collector` : void 0;
11555
11804
 
11556
11805
  //#endregion
11557
11806
  //#region src/origins/specs/node.ts
@@ -11724,8 +11973,8 @@ const JULIA_TYPE_CATEGORIES = new Map([
11724
11973
  [`Symbol`, `symbol`],
11725
11974
  [`Regex`, `regexp`],
11726
11975
  [`Base.Regex`, `regexp`],
11727
- [`BigInt`, `big number`],
11728
- [`BigFloat`, `big number`],
11976
+ [`BigInt`, `big-number`],
11977
+ [`BigFloat`, `big-number`],
11729
11978
  [`Base.BitSet`, `array`],
11730
11979
  [`Core.SimpleVector`, `array`],
11731
11980
  ...[`Bool`, `Char`].map((name) => [name, `number`]),
@@ -12344,34 +12593,254 @@ const makeFormatToOriginSpecs = () => {
12344
12593
  const formatToOriginSpecs = makeFormatToOriginSpecs();
12345
12594
 
12346
12595
  //#endregion
12347
- //#region src/modalities/stack-frame.ts
12348
- /**
12349
- * An input's distinct {@link StackFrame}s, owning everything derived
12350
- * from them: origin detection over the raw frames and, once the context is
12351
- * resolved, the {@link StackFrameFunctionTable} the frames resolve to.
12352
- *
12353
- * One table exists per frames array. Formats that yield multiple inputs
12354
- * sometimes share the frames; the table shares the derived data
12355
- * so each computation runs once, not once per input.
12356
- */
12357
- var StackFrameTable = class StackFrameTable {
12358
- /**
12359
- * A `WeakMap` rather than per-file state so sharing needs no extra
12360
- * parameter passed through the pipeline: each table is reclaimed with its
12361
- * frames array.
12362
- */
12363
- static #tables = /* @__PURE__ */ new WeakMap();
12364
- static for(frames) {
12365
- let table = StackFrameTable.#tables.get(frames);
12366
- if (!table) {
12367
- table = new StackFrameTable(frames);
12368
- StackFrameTable.#tables.set(frames, table);
12369
- }
12370
- return table;
12371
- }
12372
- #frames;
12373
- /** Per frame index, a lazily-filled cache of the frame's parsed function. */
12374
- #functions = [];
12596
+ //#region src/options.ts
12597
+ const normalizeProfileInput = (input) => typeof input === `object` && input !== null && `data` in input ? {
12598
+ data: input.data,
12599
+ format: input.format,
12600
+ origin: input.origin
12601
+ } : {
12602
+ data: input,
12603
+ format: void 0,
12604
+ origin: void 0
12605
+ };
12606
+ /** Every category {@link FunctionCategory} allows. */
12607
+ const FUNCTION_CATEGORIES = [
12608
+ `ours`,
12609
+ `third-party`,
12610
+ `stdlib`,
12611
+ `native`,
12612
+ `unknown`,
12613
+ `garbage-collector`,
12614
+ `compiler`,
12615
+ `jit`,
12616
+ `regexp`,
12617
+ `kernel`,
12618
+ `idle`
12619
+ ];
12620
+ const normalizeProfileToMdOptions = ({ topN = 20, minCategoryShare = .01, baseURL, sourceMaps = [], matchEntry = defaultMatchEntry, categorizeFunctions = defaultCategorizeFunctions, showEntry = defaultShowEntry } = {}) => ({
12621
+ topN: normalizeTopN(topN),
12622
+ minCategoryShare: normalizeMinCategoryShare(minCategoryShare),
12623
+ baseURL: normalizeBaseURL(baseURL),
12624
+ sourceMaps: normalizeSourceMaps(sourceMaps),
12625
+ entryMatchKeys: cacheEntryFunction((entry, context) => entryMatchKeys(entry, context, matchEntry)),
12626
+ categorizeFunctions: (entries, context) => {
12627
+ const categories = categorizeFunctions(entries, context);
12628
+ if (categories.length !== entries.length) throw new ProfilerMdError(`categorizeFunctions must return one category per entry, aligned by index, got: ${categories.length} categories for ${entries.length} entries`);
12629
+ return categories;
12630
+ },
12631
+ showEntry: cacheEntryFunction(showEntry)
12632
+ });
12633
+ const normalizeTopN = (topN) => {
12634
+ if (!(Number.isSafeInteger(topN) && topN >= 0)) throw new ProfilerMdError(`topN must be a non-negative integer, got: ${topN}`);
12635
+ return topN;
12636
+ };
12637
+ const normalizeMinCategoryShare = (minCategoryShare) => {
12638
+ if (!(minCategoryShare >= 0 && minCategoryShare <= 1)) throw new ProfilerMdError(`minCategoryShare must be a fraction between 0 and 1, got: ${minCategoryShare}`);
12639
+ return minCategoryShare;
12640
+ };
12641
+ const normalizeBaseURL = (baseURL) => {
12642
+ if (baseURL === null) return;
12643
+ if (baseURL === `auto`) return `auto`;
12644
+ let url;
12645
+ if (baseURL === void 0) {
12646
+ if (typeof process !== `undefined`) url = new URL(`file://${process.cwd()}/`);
12647
+ } else if (typeof baseURL === `string`) {
12648
+ const fileReference = makeFileReference(baseURL);
12649
+ if (fileReference?.type !== `absolute`) throw new ProfilerMdError(`baseURL must be an absolute path or URL, got: ${baseURL}`);
12650
+ ({url} = fileReference);
12651
+ } else url = baseURL;
12652
+ if (url) url = ensureTrailingSlash(url);
12653
+ return url;
12654
+ };
12655
+ const ensureTrailingSlash = (url) => {
12656
+ if (url.pathname.endsWith(`/`)) return url;
12657
+ url = new URL(url.href);
12658
+ url.pathname += `/`;
12659
+ return url;
12660
+ };
12661
+ /** Returns an entry's diff match keys. */
12662
+ const entryMatchKeys = (entry, context, matchEntry) => {
12663
+ const match = matchEntry(entry, context);
12664
+ const name = match?.name ?? entry.name ?? ``;
12665
+ const location = match?.location ?? (entry.location ? sourceReferenceId(entry.location) : void 0);
12666
+ if (!location) return {
12667
+ name,
12668
+ nameAndLocation: name
12669
+ };
12670
+ return {
12671
+ name,
12672
+ nameAndLocation: `${name}\0${entry.location ? sourceReferenceKind(entry.location) : ``}\0${location}`
12673
+ };
12674
+ };
12675
+ const cacheEntryFunction = (func) => {
12676
+ const cache = /* @__PURE__ */ new WeakMap();
12677
+ return (entry, context) => {
12678
+ let cached = cache.get(entry);
12679
+ if (cached === void 0) {
12680
+ cached = func(entry, context);
12681
+ cache.set(entry, cached);
12682
+ }
12683
+ return cached;
12684
+ };
12685
+ };
12686
+ /**
12687
+ * The default {@link ProfileToMdOptions.matchEntry}.
12688
+ *
12689
+ * Applies the origin's match normalization to the entry, stripping the origin's
12690
+ * known run-varying identifiers (e.g. Rust build hashes for `pprof-rs`, JVM
12691
+ * runtime addresses for `jdk`), or `undefined` if the entry contains none.
12692
+ */
12693
+ const defaultMatchEntry = (entry, { origin }) => matchEntryForOrigin(entry, origin);
12694
+ /**
12695
+ * The default {@link ProfileToMdOptions.categorizeFunctions}.
12696
+ *
12697
+ * Applies the library's origin-aware categorization to each entry.
12698
+ */
12699
+ const defaultCategorizeFunctions = (entries, { origin }) => entries.map((entry) => categorizeEntryForOrigin(entry, origin));
12700
+ /**
12701
+ * Returns whether to include the given entry in the Markdown output.
12702
+ *
12703
+ * Excludes synthetic entries, which correspond to nothing in the profiled
12704
+ * program. Every function it ran is shown, and each ranking breaks down by
12705
+ * category, so a reader chooses which code to read.
12706
+ */
12707
+ const defaultShowEntry = (entry) => !isSyntheticEntry(entry);
12708
+ /**
12709
+ * Returns true if the entry is synthetic.
12710
+ *
12711
+ * The profiler invents these entries; they correspond to nothing that exists
12712
+ * in code or at runtime (e.g. a synthetic `(root)` node for heap snapshots).
12713
+ *
12714
+ * A heap snapshot node holding text takes the text as its name, so a string
12715
+ * whose value equals a synthetic name is not a synthetic entry.
12716
+ */
12717
+ const isSyntheticEntry = ({ name, category }) => !TEXT_CATEGORIES.has(category) && (name === `(root)` || name === `<root>` || name === `(module)`);
12718
+ /** The categories of a heap snapshot node named by the text it holds. */
12719
+ const TEXT_CATEGORIES = /* @__PURE__ */ new Set([
12720
+ `string`,
12721
+ `concatenated-string`,
12722
+ `sliced-string`
12723
+ ]);
12724
+
12725
+ //#endregion
12726
+ //#region src/helpers/graph.ts
12727
+ /**
12728
+ * Assigns each node its strongly connected component index via iterative
12729
+ * Tarjan. Nodes in one component are reachable from each other, so they form a
12730
+ * cycle.
12731
+ *
12732
+ * A node is an index into {@link nodeToEdges}, which contains its outgoing
12733
+ * edges, and {@link select} maps an edge to the node it points to.
12734
+ */
12735
+ const stronglyConnectedComponents = (nodeToEdges, select) => new ComponentSearch(nodeToEdges, select).search();
12736
+ /** One iterative Tarjan run over a graph's outgoing edges. */
12737
+ var ComponentSearch = class {
12738
+ #nodeToEdges;
12739
+ #select;
12740
+ /** Per node, its discovery index, or `-1` before it is reached. */
12741
+ #indices;
12742
+ /** Per node, the lowest discovery index reachable from it. */
12743
+ #lowLinks;
12744
+ #componentIndices;
12745
+ /** The nodes whose component is still open, and their membership. */
12746
+ #stack = [];
12747
+ #onStack;
12748
+ #nextIndex = 0;
12749
+ #nextComponent = 0;
12750
+ constructor(nodeToEdges, select) {
12751
+ const count = nodeToEdges.length;
12752
+ this.#nodeToEdges = nodeToEdges;
12753
+ this.#select = select;
12754
+ this.#indices = new Array(count).fill(-1);
12755
+ this.#lowLinks = new Array(count).fill(-1);
12756
+ this.#componentIndices = new Array(count).fill(-1);
12757
+ this.#onStack = new Array(count).fill(false);
12758
+ }
12759
+ search() {
12760
+ for (let start = 0; start < this.#nodeToEdges.length; start++) if (this.#indices[start] === -1) this.#searchFrom(start);
12761
+ return this.#componentIndices;
12762
+ }
12763
+ /** Traverses every unreached node reachable from {@link start}. */
12764
+ #searchFrom(start) {
12765
+ const traversal = [this.#discover(start)];
12766
+ while (traversal.length > 0) {
12767
+ const frame = traversal.at(-1);
12768
+ if (frame.nextEdge < frame.edges.length) {
12769
+ const target = this.#select(frame.edges[frame.nextEdge++]);
12770
+ if (this.#indices[target] === -1) traversal.push(this.#discover(target));
12771
+ else if (this.#onStack[target]) this.#lowerLink(frame.node, this.#indices[target]);
12772
+ continue;
12773
+ }
12774
+ traversal.pop();
12775
+ if (this.#lowLinks[frame.node] === this.#indices[frame.node]) this.#closeComponent(frame.node);
12776
+ const source = traversal.at(-1);
12777
+ if (source) this.#lowerLink(source.node, this.#lowLinks[frame.node]);
12778
+ }
12779
+ }
12780
+ /**
12781
+ * Records a node reached for the first time and returns its traversal frame,
12782
+ * which resumes partway through the edges after the traversal returns from a
12783
+ * target.
12784
+ */
12785
+ #discover(node) {
12786
+ this.#indices[node] = this.#nextIndex;
12787
+ this.#lowLinks[node] = this.#nextIndex;
12788
+ this.#nextIndex++;
12789
+ this.#stack.push(node);
12790
+ this.#onStack[node] = true;
12791
+ return {
12792
+ node,
12793
+ edges: this.#nodeToEdges[node],
12794
+ nextEdge: 0
12795
+ };
12796
+ }
12797
+ #lowerLink(node, lowLink) {
12798
+ this.#lowLinks[node] = Math.min(this.#lowLinks[node], lowLink);
12799
+ }
12800
+ /**
12801
+ * Assigns a component to {@link root} and to every node stacked above it, the
12802
+ * rest of the cycle it forms.
12803
+ */
12804
+ #closeComponent(root) {
12805
+ while (true) {
12806
+ const member = this.#stack.pop();
12807
+ this.#onStack[member] = false;
12808
+ this.#componentIndices[member] = this.#nextComponent;
12809
+ if (member === root) break;
12810
+ }
12811
+ this.#nextComponent++;
12812
+ }
12813
+ };
12814
+
12815
+ //#endregion
12816
+ //#region src/modalities/stack-frame.ts
12817
+ /**
12818
+ * An input's distinct {@link StackFrame}s, owning everything derived
12819
+ * from them: origin detection over the raw frames and, once the context is
12820
+ * resolved, the {@link StackFrameFunctionTable} the frames resolve to.
12821
+ *
12822
+ * One table exists per frames array. Formats that yield multiple inputs
12823
+ * sometimes share the frames; the table shares the derived data
12824
+ * so each computation runs once, not once per input.
12825
+ */
12826
+ var StackFrameTable = class StackFrameTable {
12827
+ /**
12828
+ * A `WeakMap` rather than per-file state so sharing needs no extra
12829
+ * parameter passed through the pipeline: each table is reclaimed with its
12830
+ * frames array.
12831
+ */
12832
+ static #tables = /* @__PURE__ */ new WeakMap();
12833
+ static for(frames) {
12834
+ let table = StackFrameTable.#tables.get(frames);
12835
+ if (!table) {
12836
+ table = new StackFrameTable(frames);
12837
+ StackFrameTable.#tables.set(frames, table);
12838
+ }
12839
+ return table;
12840
+ }
12841
+ #frames;
12842
+ /** Per frame index, a lazily-filled cache of the frame's parsed function. */
12843
+ #functions = [];
12375
12844
  #detected = false;
12376
12845
  #functionTable;
12377
12846
  constructor(frames) {
@@ -13172,56 +13641,6 @@ const formatDiffDirectionFunctions$1 = ({ diff, measure, categories, options, he
13172
13641
  });
13173
13642
  };
13174
13643
 
13175
- //#endregion
13176
- //#region src/modalities/call-stack-profile/diff.ts
13177
- /**
13178
- * What one count of both profiles measures. The diff reports it only when the
13179
- * two count the same thing.
13180
- *
13181
- * Throws when the two count different things and share no metric, because the
13182
- * diff would then have nothing to rank.
13183
- */
13184
- const matchDiffedCountMetrics = (base, current, ranksByCount) => {
13185
- const { countMetric } = base;
13186
- if (countMetric && current.countMetric && metricsEqual(countMetric, current.countMetric)) return countMetric;
13187
- if (ranksByCount) throw new ProfilerMdError(`cannot diff profiles with no metrics in common that count different things, got: ${describeCounts(base, current)} and ${describeCounts(current, base)}`);
13188
- return null;
13189
- };
13190
- const describeCounts = ({ countMetric }, { countMetric: otherCountMetric }) => {
13191
- if (!countMetric) return `nothing`;
13192
- const { titleNoun, columnNoun } = countMetric.phrases;
13193
- return countMetric.type === `count` && columnNoun !== otherCountMetric?.phrases.columnNoun ? columnNoun : titleNoun;
13194
- };
13195
- /**
13196
- * Diffs {@link base} and {@link current} by matching up their metrics,
13197
- * functions, and categories.
13198
- *
13199
- * Throws if the profiles have no metrics in common.
13200
- */
13201
- const diffAggregatedCallStackProfiles = (base, current, options) => {
13202
- const metrics = matchDiffedMetrics(base.metrics, current.metrics);
13203
- if (metrics.length === 0 && (base.metrics.length > 0 || current.metrics.length > 0)) throw new ProfilerMdError(`cannot diff profiles with no metrics in common`);
13204
- const { entryMatchKeys } = options;
13205
- const functions = matchDiffedEntries(base.functions, current.functions, (func) => entryMatchKeys(func, base.context).nameAndLocation, (func) => entryMatchKeys(func, current.context).nameAndLocation).map(({ base: baseFunc, current: currentFunc }) => {
13206
- const { name, location, category } = currentFunc ?? baseFunc;
13207
- return {
13208
- name,
13209
- location,
13210
- category,
13211
- base: baseFunc,
13212
- current: currentFunc
13213
- };
13214
- });
13215
- return {
13216
- base,
13217
- current,
13218
- metrics,
13219
- countMetric: matchDiffedCountMetrics(base, current, metrics.length === 0),
13220
- categoryToMetrics: matchDiffedMaps(base.categoryToMetrics, current.categoryToMetrics),
13221
- functions
13222
- };
13223
- };
13224
-
13225
13644
  //#endregion
13226
13645
  //#region src/modalities/call-stack-profile/measure.ts
13227
13646
  /**
@@ -14193,264 +14612,140 @@ var ObservationsAggregator = class {
14193
14612
  const func = functions[i];
14194
14613
  const category = categories[i];
14195
14614
  func.category = category;
14196
- if (func.selfCount === 0) continue;
14197
- let metric = categoryToMetrics.get(category);
14198
- if (!metric) {
14199
- metric = {
14200
- count: 0,
14201
- values: new Float64Array(this.#metrics.length)
14202
- };
14203
- categoryToMetrics.set(category, metric);
14204
- }
14205
- metric.count += func.selfCount;
14206
- for (let i = 0; i < func.selfValues.length; i++) metric.values[i] += func.selfValues[i];
14207
- }
14208
- return categoryToMetrics;
14209
- }
14210
- };
14211
- /**
14212
- * Key for the single shared anonymous function that stackless observations
14213
- * (empty {@link Observation.frameIndices}) are attributed to. A symbol so it
14214
- * can never collide with a {@link StackFrameFunction.key}. All stackless
14215
- * observations merge into one bucket because nothing distinguishes them.
14216
- */
14217
- const ANONYMOUS_FUNCTION_KEY = Symbol(`anonymous`);
14218
- /** Whether two frame lists reference the same functions in the same order. */
14219
- const sameStackFrameIds = (left, right) => {
14220
- if (left.length !== right.length) return false;
14221
- for (let i = 0; i < left.length; i++) if (left[i].id !== right[i].id) return false;
14222
- return true;
14223
- };
14224
-
14225
- //#endregion
14226
- //#region src/options.ts
14227
- const normalizeProfileInput = (input) => typeof input === `object` && input !== null && `data` in input ? {
14228
- data: input.data,
14229
- format: input.format,
14230
- origin: input.origin
14231
- } : {
14232
- data: input,
14233
- format: void 0,
14234
- origin: void 0
14235
- };
14236
- /** Every category {@link FunctionCategory} allows. */
14237
- const FUNCTION_CATEGORIES = [
14238
- `ours`,
14239
- `third-party`,
14240
- `stdlib`,
14241
- `native`,
14242
- `unknown`,
14243
- `garbage collector`,
14244
- `compiler`,
14245
- `jit`,
14246
- `regexp`,
14247
- `kernel`,
14248
- `idle`
14249
- ];
14250
- const normalizeProfileToMdOptions = ({ topN = 20, minCategoryShare = .01, baseURL, sourceMaps = [], matchEntry = defaultMatchEntry, categorizeFunctions = defaultCategorizeFunctions, showEntry = defaultShowEntry } = {}) => ({
14251
- topN,
14252
- minCategoryShare: normalizeMinCategoryShare(minCategoryShare),
14253
- baseURL: normalizeBaseURL(baseURL),
14254
- sourceMaps: normalizeSourceMaps(sourceMaps),
14255
- entryMatchKeys: cacheEntryFunction((entry, context) => entryMatchKeys(entry, context, matchEntry)),
14256
- categorizeFunctions: (entries, context) => {
14257
- const categories = categorizeFunctions(entries, context);
14258
- if (categories.length !== entries.length) throw new ProfilerMdError(`categorizeFunctions must return one category per entry, aligned by index, got: ${categories.length} categories for ${entries.length} entries`);
14259
- return categories;
14260
- },
14261
- showEntry: cacheEntryFunction(showEntry)
14262
- });
14263
- const normalizeMinCategoryShare = (minCategoryShare) => {
14264
- if (!(minCategoryShare >= 0 && minCategoryShare <= 1)) throw new ProfilerMdError(`minCategoryShare must be a fraction between 0 and 1, got: ${minCategoryShare}`);
14265
- return minCategoryShare;
14266
- };
14267
- const normalizeBaseURL = (baseURL) => {
14268
- if (baseURL === null) return;
14269
- if (baseURL === `auto`) return `auto`;
14270
- let url;
14271
- if (baseURL === void 0) {
14272
- if (typeof process !== `undefined`) url = new URL(`file://${process.cwd()}/`);
14273
- } else if (typeof baseURL === `string`) {
14274
- const fileReference = makeFileReference(baseURL);
14275
- if (fileReference?.type !== `absolute`) throw new ProfilerMdError(`baseURL must be an absolute path or URL, got: ${baseURL}`);
14276
- ({url} = fileReference);
14277
- } else url = baseURL;
14278
- if (url) url = ensureTrailingSlash(url);
14279
- return url;
14280
- };
14281
- const ensureTrailingSlash = (url) => {
14282
- if (url.pathname.endsWith(`/`)) return url;
14283
- url = new URL(url.href);
14284
- url.pathname += `/`;
14285
- return url;
14286
- };
14287
- /** Returns an entry's diff match keys. */
14288
- const entryMatchKeys = (entry, context, matchEntry) => {
14289
- const match = matchEntry(entry, context);
14290
- const name = match?.name ?? entry.name ?? ``;
14291
- const location = match?.location ?? (entry.location ? sourceReferenceId(entry.location) : void 0);
14292
- if (!location) return {
14293
- name,
14294
- nameAndLocation: name
14295
- };
14296
- return {
14297
- name,
14298
- nameAndLocation: `${name}\0${entry.location ? sourceReferenceKind(entry.location) : ``}\0${location}`
14299
- };
14300
- };
14301
- const cacheEntryFunction = (func) => {
14302
- const cache = /* @__PURE__ */ new WeakMap();
14303
- return (entry, context) => {
14304
- let cached = cache.get(entry);
14305
- if (cached === void 0) {
14306
- cached = func(entry, context);
14307
- cache.set(entry, cached);
14308
- }
14309
- return cached;
14310
- };
14311
- };
14312
- /**
14313
- * The default {@link ProfileToMdOptions.matchEntry}.
14314
- *
14315
- * Applies the origin's match normalization to the entry, stripping the origin's
14316
- * known run-varying identifiers (e.g. Rust build hashes for `pprof-rs`, JVM
14317
- * runtime addresses for `jdk`), or `undefined` if the entry contains none.
14318
- */
14319
- const defaultMatchEntry = (entry, { origin }) => matchEntryForOrigin(entry, origin);
14320
- /**
14321
- * The default {@link ProfileToMdOptions.categorizeFunctions}.
14322
- *
14323
- * Applies the library's origin-aware categorization to each entry.
14324
- */
14325
- const defaultCategorizeFunctions = (entries, { origin }) => entries.map((entry) => categorizeEntryForOrigin(entry, origin));
14326
- /**
14327
- * Returns whether to include the given entry in the Markdown output.
14328
- *
14329
- * Excludes synthetic entries, which correspond to nothing in the profiled
14330
- * program. Every function it ran is shown, and each ranking breaks down by
14331
- * category, so a reader chooses which code to read.
14332
- */
14333
- const defaultShowEntry = (entry) => !isSyntheticEntry(entry);
14615
+ if (func.selfCount === 0) continue;
14616
+ let metric = categoryToMetrics.get(category);
14617
+ if (!metric) {
14618
+ metric = {
14619
+ count: 0,
14620
+ values: new Float64Array(this.#metrics.length)
14621
+ };
14622
+ categoryToMetrics.set(category, metric);
14623
+ }
14624
+ metric.count += func.selfCount;
14625
+ for (let i = 0; i < func.selfValues.length; i++) metric.values[i] += func.selfValues[i];
14626
+ }
14627
+ return categoryToMetrics;
14628
+ }
14629
+ };
14334
14630
  /**
14335
- * Returns true if the entry is synthetic.
14336
- *
14337
- * The profiler invents these entries; they correspond to nothing that exists
14338
- * in code or at runtime (e.g. a synthetic `(root)` node for heap snapshots).
14339
- *
14340
- * A heap snapshot node holding text takes the text as its name, so a string
14341
- * whose value equals a synthetic name is not a synthetic entry.
14631
+ * Key for the single shared anonymous function that stackless observations
14632
+ * (empty {@link Observation.frameIndices}) are attributed to. A symbol so it
14633
+ * can never collide with a {@link StackFrameFunction.key}. All stackless
14634
+ * observations merge into one bucket because nothing distinguishes them.
14342
14635
  */
14343
- const isSyntheticEntry = ({ name, category }) => !TEXT_CATEGORIES.has(category) && (name === `(root)` || name === `<root>` || name === `(module)`);
14344
- /** The categories of a heap snapshot node named by the text it holds. */
14345
- const TEXT_CATEGORIES = /* @__PURE__ */ new Set([
14346
- `string`,
14347
- `concatenated string`,
14348
- `sliced string`
14349
- ]);
14636
+ const ANONYMOUS_FUNCTION_KEY = Symbol(`anonymous`);
14637
+ /** Whether two frame lists reference the same functions in the same order. */
14638
+ const sameStackFrameIds = (left, right) => {
14639
+ if (left.length !== right.length) return false;
14640
+ for (let i = 0; i < left.length; i++) if (left[i].id !== right[i].id) return false;
14641
+ return true;
14642
+ };
14350
14643
 
14351
14644
  //#endregion
14352
- //#region src/formats/index.ts
14645
+ //#region src/modalities/call-stack-profile/diff.ts
14353
14646
  /**
14354
- * Asynchronously converts the given profile data to Markdown.
14647
+ * What one count of both profiles measures. The diff reports it only when the
14648
+ * two count the same thing.
14355
14649
  *
14356
- * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14357
- * for supported formats and generation instructions.
14650
+ * Throws when the two count different things and share no metric, because the
14651
+ * diff would then have nothing to rank.
14358
14652
  */
14359
- const profileToMdAsync = async (input, options = {}) => {
14360
- const normalizedOptions = normalizeProfileToMdOptions(options);
14361
- const aggregatedInputs = await aggregateInputAsync(input, normalizedOptions);
14362
- return formatAggregatedInputs(aggregatedInputs, normalizedOptions);
14653
+ const matchDiffedCountMetrics = (base, current, ranksByCount) => {
14654
+ const { countMetric } = base;
14655
+ if (countMetric && current.countMetric && metricsEqual(countMetric, current.countMetric)) return countMetric;
14656
+ if (ranksByCount) throw new ProfilerMdError(`cannot diff profiles with no metrics in common that count different things, got: ${describeCounts(base, current)} and ${describeCounts(current, base)}`);
14657
+ return null;
14658
+ };
14659
+ const describeCounts = ({ countMetric }, { countMetric: otherCountMetric }) => {
14660
+ if (!countMetric) return `nothing`;
14661
+ const { titleNoun, columnNoun } = countMetric.phrases;
14662
+ return countMetric.type === `count` && columnNoun !== otherCountMetric?.phrases.columnNoun ? columnNoun : titleNoun;
14363
14663
  };
14364
14664
  /**
14365
- * Asynchronously diffs the given base and current profile data, returning the
14366
- * difference as Markdown.
14367
- *
14368
- * Each side accepts the same input as {@link profileToMdAsync}.
14665
+ * Diffs {@link base} and {@link current} by matching up their metrics,
14666
+ * functions, and categories.
14369
14667
  *
14370
- * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14371
- * for supported formats and generation instructions.
14668
+ * Throws if the profiles have no metrics in common.
14372
14669
  */
14373
- const diffProfilesAsync = async (base, current, options = {}) => {
14374
- const normalizedOptions = normalizeProfileToMdOptions(options);
14375
- return formatAggregatedDiff(...await Promise.all([aggregateInputAsync(base, normalizedOptions), aggregateInputAsync(current, normalizedOptions)]), normalizedOptions);
14376
- };
14377
- const aggregateInputAsync = async (input, options) => {
14378
- const { data, format, origin } = normalizeProfileInput(input);
14379
- if (format) {
14380
- const converter = specifiedFormatConverter(format);
14381
- const context = makeContext(format, origin);
14382
- return converter.type === `json` ? aggregateJsonInput(converter, await JumboJSON.parseAsync(data), options, context) : aggregateBinaryInputAsync(converter, data instanceof Blob ? data.stream() : data, options, context);
14383
- }
14384
- const buffered = data instanceof Blob ? data : await streamToUint8Array(data);
14385
- let json;
14386
- let jsonError;
14387
- if (buffered instanceof Blob ? await maybeJsonAsync(buffered) : maybeJson(buffered)) try {
14388
- json = buffered instanceof Blob ? await JumboJSON.parseAsync(buffered) : JumboJSON.parse(buffered);
14389
- } catch (error) {
14390
- jsonError = (buffered instanceof Blob ? await startsJsonDocumentAsync(buffered) : startsJsonDocument(buffered)) ? error : void 0;
14391
- }
14392
- const rejections = [];
14393
- if (json !== void 0) {
14394
- const inputs = detectFromJson(json, options, origin, rejections);
14395
- if (inputs !== void 0) return inputs;
14396
- }
14397
- const bytes = buffered instanceof Blob ? await buffered.bytes() : buffered;
14398
- const inputs = detectFromBytes(bytes, options, origin, rejections);
14399
- if (inputs !== void 0) return inputs;
14400
- throw undetectedFormatError(rejections, jsonError);
14670
+ const diffAggregatedCallStackProfiles = (base, current, options) => {
14671
+ const metrics = matchDiffedMetrics(base.metrics, current.metrics);
14672
+ if (metrics.length === 0 && (base.metrics.length > 0 || current.metrics.length > 0)) throw new ProfilerMdError(`cannot diff profiles with no metrics in common`);
14673
+ const { entryMatchKeys } = options;
14674
+ const functions = matchDiffedEntries(base.functions, current.functions, (func) => entryMatchKeys(func, base.context).nameAndLocation, (func) => entryMatchKeys(func, current.context).nameAndLocation).map(({ base: baseFunc, current: currentFunc }) => {
14675
+ const { name, location, category } = currentFunc ?? baseFunc;
14676
+ return {
14677
+ name,
14678
+ location,
14679
+ category,
14680
+ base: baseFunc,
14681
+ current: currentFunc
14682
+ };
14683
+ });
14684
+ return {
14685
+ base,
14686
+ current,
14687
+ metrics,
14688
+ countMetric: matchDiffedCountMetrics(base, current, metrics.length === 0),
14689
+ categoryToMetrics: matchDiffedMaps(base.categoryToMetrics, current.categoryToMetrics),
14690
+ functions
14691
+ };
14401
14692
  };
14693
+
14694
+ //#endregion
14695
+ //#region src/formats/aggregate.ts
14402
14696
  /**
14403
- * The converter for a format the caller specified. Its parses report a
14404
- * rejection as that format's, so the caller receives the reason and the format
14405
- * that rejected the input.
14697
+ * Aggregates each parsed input through its modality's uniform pipeline.
14406
14698
  *
14407
- * Auto-detection uses the registry's converters directly, because it names
14408
- * each rejecting format when it reports the rejections together.
14699
+ * The origin is detected once across all inputs.
14409
14700
  */
14410
- const specifiedFormatConverter = (format) => {
14411
- const converter = formatConverters[format];
14412
- if (converter.type === `json`) return {
14413
- ...converter,
14414
- parse: (json) => rejectAsFormat(converter, () => converter.parse(json))
14415
- };
14416
- return {
14417
- ...converter,
14418
- parse: (bytes) => rejectAsFormat(converter, () => converter.parse(bytes)),
14419
- parseAsync: async (stream) => {
14420
- try {
14421
- return await converter.parseAsync(stream);
14422
- } catch (error) {
14423
- throw asFormatRejection(converter, error);
14424
- }
14701
+ const aggregateParsedInputs = (parsed, options, context) => {
14702
+ const aggregators = parsed.map((input) => {
14703
+ switch (input.type) {
14704
+ case `call-stack-profile`: return new CallStackProfileAggregator(input);
14705
+ case `call-graph`: return new CallGraphAggregator(input);
14706
+ case `heap-snapshot`: return new HeapSnapshotAggregator(input);
14425
14707
  }
14708
+ });
14709
+ const detector = new OriginDetector(context);
14710
+ for (const aggregator of aggregators) aggregator.detectOrigin(detector);
14711
+ const resolvedContext = {
14712
+ format: context.format,
14713
+ origin: detector.resolve()
14426
14714
  };
14427
- };
14428
- const rejectAsFormat = (converter, parse) => {
14429
- try {
14430
- return parse();
14431
- } catch (error) {
14432
- throw asFormatRejection(converter, error);
14433
- }
14715
+ return aggregators.map((aggregator) => aggregator.aggregate(options, resolvedContext));
14434
14716
  };
14435
14717
  /**
14436
- * Prefixes a {@link FormatParseError} with the format's title. Any other error
14437
- * passes through, because it reports a bug instead of an unusable input.
14718
+ * Builds the conversion context, which contains the resolved format and the
14719
+ * explicit origin (or `null` when none was given).
14438
14720
  */
14439
- const asFormatRejection = (converter, error) => error instanceof FormatParseError ? new ProfilerMdError(`${converter.title}: ${error.message}`, { cause: error }) : error;
14440
- const detectFromJson = (json, options, origin, rejections) => {
14721
+ const makeContext = (format, origin) => ({
14722
+ format,
14723
+ origin: origin ?? null
14724
+ });
14725
+
14726
+ //#endregion
14727
+ //#region src/formats/detect.ts
14728
+ const detectJsonFormat = (json, rejections) => {
14441
14729
  for (const [format, converter] of jsonFormatConverters) {
14442
- const parsed = detectWithConverter(converter, () => converter.matches(json), () => converter.parse(json), rejections);
14443
- if (parsed) return aggregateParsedInputs(parsed, options, makeContext(format, origin));
14730
+ const parsed = detectWithConverter(converter, json, rejections);
14731
+ if (parsed) return {
14732
+ format,
14733
+ parsed
14734
+ };
14444
14735
  }
14445
14736
  };
14446
- const formatConverterEntries = formats.map((format) => [format, formatConverters[format]]);
14447
- const jsonFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `json`);
14448
- const detectFromBytes = (bytes, options, origin, rejections) => {
14737
+ const detectBinaryFormat = (bytes, rejections) => {
14449
14738
  for (const [format, converter] of binaryFormatConverters) {
14450
- const parsed = detectWithConverter(converter, () => converter.matches(bytes), () => converter.parse(bytes), rejections);
14451
- if (parsed) return aggregateParsedInputs(parsed, options, makeContext(format, origin));
14739
+ const parsed = detectWithConverter(converter, bytes, rejections);
14740
+ if (parsed) return {
14741
+ format,
14742
+ parsed
14743
+ };
14452
14744
  }
14453
14745
  };
14746
+ const formatConverterEntries = formats.map((format) => [format, formatConverters[format]]);
14747
+ const jsonFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `json`);
14748
+ const binaryFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `binary`);
14454
14749
  /**
14455
14750
  * Runs a converter's detection and parse, recording a rejection instead of
14456
14751
  * throwing when the converter recognized the input but failed to parse it.
@@ -14458,14 +14753,14 @@ const detectFromBytes = (bytes, options, origin, rejections) => {
14458
14753
  * A `matches` that throws counts as no match, because it is a cheap prefilter
14459
14754
  * that never validates the input.
14460
14755
  */
14461
- const detectWithConverter = (converter, matches, parse, rejections) => {
14756
+ const detectWithConverter = (converter, input, rejections) => {
14462
14757
  try {
14463
- if (!matches()) return;
14758
+ if (!converter.matches(input)) return;
14464
14759
  } catch {
14465
14760
  return;
14466
14761
  }
14467
14762
  try {
14468
- return parse();
14763
+ return classifyLazyParseFailures(converter, converter.parse(input));
14469
14764
  } catch (error) {
14470
14765
  rejections.push({
14471
14766
  converter,
@@ -14474,38 +14769,6 @@ const detectWithConverter = (converter, matches, parse, rejections) => {
14474
14769
  return;
14475
14770
  }
14476
14771
  };
14477
- const aggregateJsonInput = (converter, json, options, context) => aggregateParsedInputs(converter.parse(json), options, context);
14478
- const aggregateBinaryInputAsync = async (converter, stream, options, context) => aggregateParsedInputs(await converter.parseAsync(stream), options, context);
14479
- /**
14480
- * Aggregates each parsed input through its modality's uniform pipeline.
14481
- *
14482
- * The origin is detected once across all inputs.
14483
- */
14484
- const aggregateParsedInputs = (parsed, options, context) => {
14485
- const aggregators = parsed.map((input) => {
14486
- switch (input.type) {
14487
- case `call-stack-profile`: return new CallStackProfileAggregator(input);
14488
- case `call-graph`: return new CallGraphAggregator(input);
14489
- case `heap-snapshot`: return new HeapSnapshotAggregator(input);
14490
- }
14491
- });
14492
- const detector = new OriginDetector(context);
14493
- for (const aggregator of aggregators) aggregator.detectOrigin(detector);
14494
- const resolvedContext = {
14495
- format: context.format,
14496
- origin: detector.resolve()
14497
- };
14498
- return aggregators.map((aggregator) => aggregator.aggregate(options, resolvedContext));
14499
- };
14500
- /**
14501
- * Builds the conversion context, which carries the resolved format and the
14502
- * explicit origin (or `null` when none was given).
14503
- */
14504
- const makeContext = (format, origin) => ({
14505
- format,
14506
- origin: origin ?? null
14507
- });
14508
- const binaryFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `binary`);
14509
14772
  /**
14510
14773
  * Reports why auto-detection resolved no format.
14511
14774
  *
@@ -14513,17 +14776,16 @@ const binaryFormatConverters = formatConverterEntries.filter((entry) => entry[1]
14513
14776
  * is that format and failed to parse. Several rejections name each format with
14514
14777
  * its reason. No rejection means no format recognized the input.
14515
14778
  */
14516
- const undetectedFormatError = (rejections, jsonError) => {
14779
+ const toUndetectedFormatError = (rejections, jsonError) => {
14517
14780
  const [rejection] = rejections;
14518
- if (rejections.length === 1) return new FormatDetectError(describeRejection(rejection), [rejection.error], { cause: rejection.error });
14519
- if (rejections.length > 1) return new FormatDetectError(`could not detect the profile format, rejected by: ${rejections.map((rejected) => describeRejection(rejected)).join(`, `)}`, rejections.map(({ error }) => error));
14520
- if (jsonError !== void 0) return new FormatDetectError(`could not detect the profile format, the input reads as JSON but failed to parse: ${reasonOf$1(jsonError)}`, [jsonError], { cause: jsonError });
14781
+ if (rejections.length === 1) return new FormatDetectError(describeParseFailure(rejection.converter, rejection.error), [rejection.error], { cause: rejection.error });
14782
+ if (rejections.length > 1) return new FormatDetectError(`could not detect the profile format, rejected by: ${rejections.map(({ converter, error }) => describeParseFailure(converter, error)).join(`, `)}`, rejections.map(({ error }) => error));
14783
+ if (jsonError !== void 0) return new FormatDetectError(`could not detect the profile format, the input reads as JSON but is ${reasonOf(jsonError)}`, [jsonError], { cause: jsonError });
14521
14784
  return new FormatDetectError(`could not detect the profile format, expected one of: ${formats.join(`, `)}`, []);
14522
14785
  };
14523
- /** A rejection as `<title>: <reason>`. */
14524
- const describeRejection = ({ converter, error }) => `${converter.title}: ${reasonOf$1(error)}`;
14525
- /** An error's message on one line, for embedding in another message. */
14526
- const reasonOf$1 = (error) => (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, ` `).trim();
14786
+
14787
+ //#endregion
14788
+ //#region src/formats/format.ts
14527
14789
  const formatAggregatedInputs = (inputs, options) => {
14528
14790
  const formattingOptions = makeFormattingProfileToMdOptions(options, inputs);
14529
14791
  const contents = inputs.flatMap((input) => {
@@ -14600,11 +14862,55 @@ const collectInferableURLs = (inputs, options) => {
14600
14862
  return urls;
14601
14863
  };
14602
14864
 
14865
+ //#endregion
14866
+ //#region src/formats/index.ts
14867
+ /**
14868
+ * Asynchronously converts the given profile data to Markdown.
14869
+ *
14870
+ * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14871
+ * for supported formats and generation instructions.
14872
+ */
14873
+ const profileToMdAsync = async (input, options = {}) => {
14874
+ const normalizedOptions = normalizeProfileToMdOptions(options);
14875
+ return formatAggregatedInputs(await aggregateInputAsync(input, normalizedOptions), normalizedOptions);
14876
+ };
14877
+ /**
14878
+ * Asynchronously diffs the given base and current profile data, returning the
14879
+ * difference as Markdown.
14880
+ *
14881
+ * Each side accepts the same input as {@link profileToMdAsync}.
14882
+ *
14883
+ * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14884
+ * for supported formats and generation instructions.
14885
+ */
14886
+ const diffProfilesAsync = async (base, current, options = {}) => {
14887
+ const normalizedOptions = normalizeProfileToMdOptions(options);
14888
+ return formatAggregatedDiff(...await Promise.all([aggregateInputAsync(base, normalizedOptions), aggregateInputAsync(current, normalizedOptions)]), normalizedOptions);
14889
+ };
14890
+ const aggregateInputAsync = async (input, options) => {
14891
+ const { data, format, origin } = normalizeProfileInput(input);
14892
+ if (format) return aggregateParsedInputs(await parseAsFormatAsync(formatConverters[format], data), options, makeContext(format, origin));
14893
+ const buffered = data instanceof Blob ? data : await streamToUint8Array(data);
14894
+ let json;
14895
+ let jsonError;
14896
+ if (buffered instanceof Blob ? await maybeJsonAsync(buffered) : maybeJson(buffered)) try {
14897
+ json = buffered instanceof Blob ? await parseJsonAsync(buffered) : parseJson(buffered);
14898
+ } catch (error) {
14899
+ rethrowInputReadFailure(error);
14900
+ jsonError = (buffered instanceof Blob ? await startsJsonDocumentAsync(buffered) : startsJsonDocument(buffered)) ? error : void 0;
14901
+ }
14902
+ const rejections = [];
14903
+ const detected = (json === void 0 ? void 0 : detectJsonFormat(json, rejections)) ?? detectBinaryFormat(buffered instanceof Blob ? await buffered.bytes() : buffered, rejections);
14904
+ if (!detected) throw toUndetectedFormatError(rejections, jsonError);
14905
+ return aggregateParsedInputs(detected.parsed, options, makeContext(detected.format, origin));
14906
+ };
14907
+
14603
14908
  //#endregion
14604
14909
  //#region package.json
14605
14910
  var name = "profiler-md";
14606
- var version = "0.7.0";
14911
+ var version = "0.8.1";
14607
14912
  var description = "Converts performance profiles to human and LLM friendly Markdown.";
14913
+ var bugs = { "url": "https://github.com/TomerAberbach/profiler-md/issues" };
14608
14914
 
14609
14915
  //#endregion
14610
14916
  //#region src/cli/languages.ts
@@ -14760,7 +15066,7 @@ const parseRegex = (pattern, flags) => {
14760
15066
  } catch (error) {
14761
15067
  return {
14762
15068
  success: false,
14763
- error: message`expected a valid regex, got: ${value(pattern)} (${text(error instanceof Error ? error.message : String(error))})`
15069
+ error: message`expected a valid regex, got: ${value(pattern)} (${text(reasonOf(error))})`
14764
15070
  };
14765
15071
  }
14766
15072
  };
@@ -14816,12 +15122,18 @@ const regexCategory = () => ({
14816
15122
  },
14817
15123
  format: ([regex, category]) => `${regex.source}=${category}`
14818
15124
  });
15125
+ /** The `--format` and `--origin` value meaning the format or origin is detected. */
15126
+ const AUTO = `auto`;
15127
+ const specified = (value) => value === AUTO ? void 0 : value;
14819
15128
  const parser = object({
14820
15129
  help: optional(or(option(`-h`, `--help`, choice(helpTopics, { metavar: `[TOPIC]` }), { description: message`Show this help message or topic docs` }), flag(`-h`, `--help`, { hidden: `help` }))),
14821
- format: optional(option(`-f`, `--format`, choice(formats, { metavar: `FORMAT` }), { description: message`Input profile format (default: auto)` })),
14822
- origin: optional(option(`-r`, `--origin`, choice(origins, { metavar: `ORIGIN` }), { description: message`Input profile origin (default: auto)` })),
15130
+ format: map(optional(option(`-f`, `--format`, choice([AUTO, ...formats], { metavar: `FORMAT` }), { description: message`Input profile format (default: auto)` })), specified),
15131
+ origin: map(optional(option(`-r`, `--origin`, choice([AUTO, ...origins], { metavar: `ORIGIN` }), { description: message`Input profile origin (default: auto)` })), specified),
14823
15132
  output: withDefault(option(`-o`, `--output`, path({ metavar: `FILE` }), { description: message`Output file (default: - for stdout)` }), `-`),
14824
- topN: optional(option(`--top-n`, integer({ metavar: `N` }), { description: message`Entries to show per ranking, including category subsections (default: 20)` })),
15133
+ topN: optional(option(`--top-n`, integer({
15134
+ metavar: `N`,
15135
+ min: 0
15136
+ }), { description: message`Entries to show per ranking, including category subsections (default: 20)` })),
14825
15137
  minCategoryShare: optional(option(`--min-category-share`, float({
14826
15138
  metavar: `FRACTION`,
14827
15139
  min: 0,
@@ -14860,18 +15172,18 @@ const getHelpText = () => {
14860
15172
  return `${[
14861
15173
  formatDocPage(program.metadata.name, docPage, {
14862
15174
  termWidth,
14863
- maxWidth: process.stdout.columns ?? 80
15175
+ maxWidth: getMaxWidth()
14864
15176
  }),
14865
15177
  `Formats: ${formats.join(`, `)}`,
14866
15178
  `Origins: ${origins.join(`, `)}`,
14867
- `Function categories (--category, --hide-category, --show-category): ${FUNCTION_CATEGORIES.join(`, `)}`,
14868
- `Heap snapshot categories (--hide-category, --show-category): ${HEAP_SNAPSHOT_NODE_CATEGORIES.join(`, `)}`,
15179
+ `Function categories: ${FUNCTION_CATEGORIES.join(`, `)}`,
15180
+ `Heap snapshot categories: ${HEAP_SNAPSHOT_NODE_CATEGORIES.join(`, `)}`,
14869
15181
  `Languages: ${[...languages.entries()].map(([id, { aliases }]) => [id, ...aliases?.map((alias) => alias.id) ?? []].join(`/`)).join(`, `)}`
14870
15182
  ].join(`\n`)}\n`;
14871
15183
  };
14872
15184
  const parseArgs = () => runParser(parser, program.metadata.name, process.argv.slice(2), {
14873
15185
  colors: false,
14874
- maxWidth: process.stdout.columns ?? 80,
15186
+ maxWidth: getMaxWidth(),
14875
15187
  version: {
14876
15188
  value: version,
14877
15189
  option: true,
@@ -14886,6 +15198,8 @@ const parseArgs = () => runParser(parser, program.metadata.name, process.argv.sl
14886
15198
  },
14887
15199
  onError: () => process.exit(2)
14888
15200
  });
15201
+ const getMaxWidth = () => Math.max(MIN_WIDTH, process.stdout.columns || Number(process.env.COLUMNS) || 80);
15202
+ const MIN_WIDTH = 40;
14889
15203
 
14890
15204
  //#endregion
14891
15205
  //#region src/cli/error.ts
@@ -14900,15 +15214,24 @@ var CliError = class extends ProfilerMdError {
14900
15214
  const reportError = (error) => {
14901
15215
  if (error instanceof ProfilerMdError) {
14902
15216
  process.stderr.write(`error: ${error.message}\n`);
15217
+ const parseFailures = unclassifiedParseFailures(error);
15218
+ if (parseFailures.length > 0) process.stderr.write(bugReport(`If the input opens in its profiler, report this as a bug in ${name}:`, parseFailures));
14903
15219
  process.exit(error instanceof CliError ? error.exitCode : 1);
14904
15220
  }
14905
- if (error instanceof Error) {
14906
- process.stderr.write(error.stack ? `${error.stack}\n` : `error: ${error.message}\n`);
14907
- process.exit(1);
14908
- }
14909
- process.stderr.write(`error: ${String(error)}\n`);
15221
+ process.stderr.write(`error: ${reasonOf(error)}\n`);
15222
+ process.stderr.write(bugReport(`This is a bug in ${name}. Report it:`, [error]));
14910
15223
  process.exit(1);
14911
15224
  };
15225
+ /** The bug report request that follows an error line, with the given traces. */
15226
+ const bugReport = (request, errors) => [
15227
+ request,
15228
+ `${bugs.url}/new`,
15229
+ `Include the command you ran, the input if you can share it, and this trace:`,
15230
+ ...errors.map(stackOf),
15231
+ ``
15232
+ ].join(`\n`);
15233
+ /** An error's stack trace, or its description when it has none. */
15234
+ const stackOf = (error) => error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` : `error: ${String(error)}`;
14912
15235
 
14913
15236
  //#endregion
14914
15237
  //#region src/cli/ansis.ts
@@ -14928,22 +15251,50 @@ const makeAnsis = ({ isTTY }) => {
14928
15251
 
14929
15252
  //#endregion
14930
15253
  //#region src/cli/pager.ts
14931
- const openPager = async () => {
15254
+ /**
15255
+ * Opens the user's pager, or `less`, for stdout output. Returns `null` when an
15256
+ * empty `PAGER` opts out of paging or no pager spawns.
15257
+ *
15258
+ * A pager that fails before it shows anything would lose the output, so the
15259
+ * returned output writes to `fallback` when the pager exits with a non-zero
15260
+ * status.
15261
+ */
15262
+ const openPager = async (fallback) => {
14932
15263
  const raw = process.env.PAGER;
14933
15264
  if (raw?.trim() === ``) return null;
14934
15265
  const env = {
14935
- LESS: `FRSX -#6`,
15266
+ LESS: `FIRSX -#6`,
14936
15267
  ...process.env
14937
15268
  };
14938
15269
  const child = (raw === void 0 ? null : await trySpawn(raw, env)) ?? await trySpawn(`less`, env);
14939
15270
  if (!child) return null;
14940
15271
  return { write: async (text) => {
14941
- await new Promise((resolve) => {
14942
- child.stdin.write(text, () => child.stdin.end(resolve));
14943
- });
14944
- await waitForExit(child);
15272
+ const exitCode = await page(child, text);
15273
+ if (exitCode !== 0 && exitCode !== null) {
15274
+ process.stderr.write(`warning: pager exited with status ${exitCode}\n`);
15275
+ await fallback.write(text);
15276
+ }
14945
15277
  } };
14946
15278
  };
15279
+ /**
15280
+ * Writes the text to the pager and resolves to its exit status once it quits,
15281
+ * or `null` when a signal killed it.
15282
+ *
15283
+ * A terminal's Ctrl-C signals this process and the pager together. The pager
15284
+ * handles its own interrupt and keeps running, so exiting here would orphan
15285
+ * it on the terminal. This process ignores SIGINT while the pager runs, as
15286
+ * git does, so quitting the pager ends the run instead.
15287
+ */
15288
+ const page = async (child, text) => {
15289
+ process.on(`SIGINT`, ignoreSignal);
15290
+ try {
15291
+ const [exitCode] = await Promise.all([waitForExit(child), writeStdin(child, text)]);
15292
+ return exitCode;
15293
+ } finally {
15294
+ process.off(`SIGINT`, ignoreSignal);
15295
+ }
15296
+ };
15297
+ const ignoreSignal = () => {};
14947
15298
  const trySpawn = (command, env) => {
14948
15299
  const [bin, ...args] = command.trim().split(/\s+/u);
14949
15300
  if (!bin) return Promise.resolve(null);
@@ -14956,38 +15307,80 @@ const trySpawn = (command, env) => {
14956
15307
  env
14957
15308
  });
14958
15309
  return new Promise((resolve) => {
14959
- child.once(`spawn`, () => {
14960
- child.stdin.on(`error`, (error) => {
14961
- if (error.code !== `EPIPE`) throw error;
14962
- });
14963
- resolve(child);
14964
- });
15310
+ child.once(`spawn`, () => resolve(child));
14965
15311
  child.once(`error`, () => resolve(null));
14966
15312
  });
14967
15313
  };
15314
+ const writeStdin = (child, text) => new Promise((resolve, reject) => {
15315
+ const finish = (error) => {
15316
+ if (!error || error.code === `EPIPE` || error.code === `ECANCELED`) resolve();
15317
+ else reject(error);
15318
+ };
15319
+ child.stdin.on(`error`, finish);
15320
+ child.stdin.write(text, (error) => error ? finish(error) : child.stdin.end(finish));
15321
+ });
15322
+ /** Resolves to the pager's exit status, or `null` when a signal killed it. */
14968
15323
  const waitForExit = (child) => new Promise((resolve, reject) => {
14969
- child.once(`exit`, () => resolve());
15324
+ child.once(`exit`, (code) => resolve(code));
14970
15325
  child.once(`error`, reject);
14971
15326
  });
14972
15327
 
14973
15328
  //#endregion
14974
15329
  //#region src/cli/output.ts
14975
15330
  const writeOutput = async (text, outputPath, { pager }) => {
14976
- await ((pager && isTTYOutput(outputPath) ? await openPager() : null) ?? await openOutput(outputPath)).write(text);
15331
+ const output = await openOutput(outputPath);
15332
+ await ((pager && isTTYOutput(outputPath) ? await openPager(output) : null) ?? output).write(text);
14977
15333
  };
14978
15334
  const isTTYOutput = (outputPath) => outputPath === `-` && Boolean(process.stdout.isTTY);
15335
+ /**
15336
+ * Rejects an output path that cannot be written.
15337
+ *
15338
+ * A path must be a writable file, or absent from a writable directory. The
15339
+ * check creates no file.
15340
+ */
15341
+ const checkOutputPath = async (outputPath) => {
15342
+ if (outputPath === `-`) return;
15343
+ let isDirectory;
15344
+ try {
15345
+ isDirectory = (await stat(outputPath)).isDirectory();
15346
+ await access(outputPath, constants.W_OK);
15347
+ } catch (error) {
15348
+ if (errorCodeOf(error) !== `ENOENT`) throw writeError(outputPath, error);
15349
+ try {
15350
+ await access(dirname(outputPath), constants.W_OK);
15351
+ } catch (directoryError) {
15352
+ throw writeError(outputPath, directoryError);
15353
+ }
15354
+ return;
15355
+ }
15356
+ if (isDirectory) throw new CliError(`cannot write ${outputPath}: is a directory`, 1);
15357
+ };
14979
15358
  const openOutput = async (outputPath) => {
14980
15359
  if (outputPath === `-`) return { write: (text) => new Promise((resolve, reject) => {
14981
- process.stdout.write(text, (error) => error ? reject(error) : resolve());
15360
+ const finish = (error) => {
15361
+ if (!error || error.code === `EPIPE`) resolve();
15362
+ else reject(error);
15363
+ };
15364
+ process.stdout.on(`error`, finish);
15365
+ process.stdout.write(text, finish);
14982
15366
  }) };
14983
15367
  const stream = createWriteStream(outputPath);
14984
15368
  await new Promise((resolve, reject) => {
14985
- stream.once(`open`, () => resolve()).once(`error`, reject);
15369
+ stream.once(`open`, () => resolve()).once(`error`, (error) => reject(writeError(outputPath, error)));
14986
15370
  });
14987
15371
  return { write: (text) => new Promise((resolve, reject) => {
14988
- stream.write(text, (error) => error ? reject(error) : stream.end(resolve));
15372
+ stream.write(text, (error) => error ? reject(writeError(outputPath, error)) : stream.end(resolve));
14989
15373
  }) };
14990
15374
  };
15375
+ const writeError = (outputPath, error) => new CliError(`cannot write ${outputPath}: ${WRITE_ERROR_REASONS.get(errorCodeOf(error)) ?? reasonOf(error)}`, 1, { cause: error });
15376
+ const errorCodeOf = (error) => error instanceof Error && `code` in error && typeof error.code === `string` ? error.code : void 0;
15377
+ const WRITE_ERROR_REASONS = /* @__PURE__ */ new Map([
15378
+ [`ENOENT`, `no such directory`],
15379
+ [`ENOTDIR`, `no such directory`],
15380
+ [`EISDIR`, `is a directory`],
15381
+ [`EACCES`, `permission denied`],
15382
+ [`EPERM`, `permission denied`]
15383
+ ]);
14991
15384
 
14992
15385
  //#endregion
14993
15386
  //#region src/cli/theme-kindling.ts
@@ -15604,7 +15997,7 @@ const printHelpTopic = async (topic, { pager }) => {
15604
15997
  //#region src/cli/input.ts
15605
15998
  const openInputAsBlob = async (filePath) => decompressBlob(await openRawInputAsBlob(filePath), filePath);
15606
15999
  const openRawInputAsBlob = async (filePath) => {
15607
- if (!filePath) return blob(process.stdin);
16000
+ if (!filePath || STDIN_PATHS.has(filePath)) return await readStreamAsBlob(process.stdin, filePath ?? `stdin`);
15608
16001
  let stats;
15609
16002
  try {
15610
16003
  stats = await stat(filePath);
@@ -15613,12 +16006,37 @@ const openRawInputAsBlob = async (filePath) => {
15613
16006
  throw new CliError(`cannot read ${filePath}: ${reasonOf(error)}`, 1, { cause: error });
15614
16007
  }
15615
16008
  if (stats.isDirectory()) throw new CliError(`cannot read ${filePath}: is a directory`, 1);
16009
+ try {
16010
+ await access(filePath, constants.R_OK);
16011
+ } catch (error) {
16012
+ throw new CliError(`cannot read ${filePath}: permission denied`, 1, { cause: error });
16013
+ }
16014
+ if (!stats.isFile()) return await readStreamAsBlob(createReadStream(filePath), filePath);
15616
16015
  try {
15617
16016
  return await openAsBlob(filePath);
15618
16017
  } catch (error) {
15619
16018
  throw new CliError(`cannot read ${filePath}: ${reasonOf(error)}`, 1, { cause: error });
15620
16019
  }
15621
16020
  };
16021
+ /**
16022
+ * The paths that name the process's own standard input.
16023
+ *
16024
+ * Opening one of these paths creates a second descriptor on the same pipe, and
16025
+ * reads on it fail with `EAGAIN`, so read `process.stdin` instead.
16026
+ */
16027
+ const STDIN_PATHS = /* @__PURE__ */ new Set([
16028
+ `-`,
16029
+ `/dev/stdin`,
16030
+ `/dev/fd/0`,
16031
+ `/proc/self/fd/0`
16032
+ ]);
16033
+ const readStreamAsBlob = async (stream, source) => {
16034
+ try {
16035
+ return await blob(stream);
16036
+ } catch (error) {
16037
+ throw new CliError(`cannot read ${source}: ${reasonOf(error)}`, 1, { cause: error });
16038
+ }
16039
+ };
15622
16040
  const decompressBlob = async (data, filePath) => {
15623
16041
  try {
15624
16042
  if (filePath?.endsWith(`.br`)) return await decompressStream(data, createBrotliDecompress({ chunkSize: DECOMPRESS_CHUNK_SIZE }));
@@ -15629,7 +16047,6 @@ const decompressBlob = async (data, filePath) => {
15629
16047
  throw new CliError(`cannot decompress ${filePath ?? `stdin`}: ${reasonOf(error)}`, 1, { cause: error });
15630
16048
  }
15631
16049
  };
15632
- const reasonOf = (error) => error instanceof Error ? error.message : String(error);
15633
16050
  /**
15634
16051
  * The output buffer size for the decompression transforms. With zlib's 16 KiB
15635
16052
  * default, a transform emits a large decompressed input as thousands of
@@ -15698,13 +16115,25 @@ const matchesEntry = (regex, { name, location }) => name !== void 0 && regex.tes
15698
16115
  const loadSourceMaps = async (patterns) => {
15699
16116
  const paths = (await Promise.all(patterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
15700
16117
  return Promise.all(paths.map(async (path) => {
15701
- const content = await readFile(path, `utf8`);
15702
- const inlineSourceMap = convertSourceMap.fromSource(content)?.toObject();
15703
- if (!inlineSourceMap) return resolveSourceMapSources(JSON.parse(content), path);
15704
- inlineSourceMap.file ??= pathToFileURL(resolve(path)).href;
15705
- return resolveSourceMapSources(inlineSourceMap, path);
16118
+ let content;
16119
+ try {
16120
+ content = await readFile(path, `utf8`);
16121
+ } catch (error) {
16122
+ throw new CliError(`cannot read source map ${path}: ${reasonOf(error)}`, 1, { cause: error });
16123
+ }
16124
+ try {
16125
+ return parseSourceMap(content, path);
16126
+ } catch (error) {
16127
+ throw new CliError(`cannot parse source map ${path}: ${reasonOf(error)}`, 1, { cause: error });
16128
+ }
15706
16129
  }));
15707
16130
  };
16131
+ const parseSourceMap = (content, path) => {
16132
+ const inlineSourceMap = convertSourceMap.fromSource(content)?.toObject();
16133
+ if (!inlineSourceMap) return resolveSourceMapSources(JSON.parse(content), path);
16134
+ inlineSourceMap.file ??= pathToFileURL(resolve(path)).href;
16135
+ return resolveSourceMapSources(inlineSourceMap, path);
16136
+ };
15708
16137
  /**
15709
16138
  * Pre-resolves relative source paths against the map file's directory so that
15710
16139
  * `source-map-js` returns absolute URLs.
@@ -15724,6 +16153,7 @@ try {
15724
16153
  const [basePath, currentPath] = typeof input === `string` || input === void 0 ? [input, void 0] : input;
15725
16154
  if (help !== void 0) await printHelpTopic(typeof help === `string` ? help : void 0, { pager });
15726
16155
  if (basePath === void 0 && process.stdin.isTTY) await printHelpTopic(void 0, { pager });
16156
+ await checkOutputPath(outputPath);
15727
16157
  const toInput = (data) => format || origin ? {
15728
16158
  data,
15729
16159
  format,