ostia 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/index.d.ts +127 -99
  2. package/package.json +1 -1
  3. package/src/ab/ab-runner.ts +57 -44
  4. package/src/ab/index.ts +186 -112
  5. package/src/baseline/index.ts +3 -9
  6. package/src/bench/index.ts +177 -123
  7. package/src/bench/projects.ts +14 -10
  8. package/src/bench/registry.ts +70 -68
  9. package/src/bench/run-tasks.ts +26 -23
  10. package/src/bench/run.ts +2 -1
  11. package/src/bench/runner.ts +20 -5
  12. package/src/bench/support.ts +26 -26
  13. package/src/bench/sweep.ts +7 -5
  14. package/src/cache/fingerprint.ts +9 -6
  15. package/src/cache/store.ts +17 -5
  16. package/src/capture/bunflags.ts +12 -11
  17. package/src/capture/cpu-parse.ts +36 -24
  18. package/src/capture/cpu.ts +7 -4
  19. package/src/capture/frames.ts +7 -1
  20. package/src/capture/heap-parse.ts +30 -5
  21. package/src/capture/heap.ts +9 -5
  22. package/src/capture/inspector.ts +8 -7
  23. package/src/capture/jsc-parse.ts +8 -8
  24. package/src/capture/jsc.ts +4 -4
  25. package/src/ci/index.ts +64 -40
  26. package/src/cli/flags.ts +42 -43
  27. package/src/cli/output.ts +29 -35
  28. package/src/cli/run.ts +95 -95
  29. package/src/compare/index.ts +39 -32
  30. package/src/config/env.ts +13 -0
  31. package/src/config/index.ts +31 -23
  32. package/src/config/validate.ts +33 -27
  33. package/src/format.ts +5 -6
  34. package/src/glob.ts +9 -12
  35. package/src/index.ts +19 -4
  36. package/src/ir/cpu.ts +2 -2
  37. package/src/ir/defined.ts +12 -0
  38. package/src/ir/document.ts +93 -73
  39. package/src/ir/fp.ts +7 -10
  40. package/src/ir/git.ts +4 -3
  41. package/src/ir/types.ts +3 -3
  42. package/src/measure/alloc.ts +7 -8
  43. package/src/measure/cpu.ts +12 -20
  44. package/src/measure/environment.ts +5 -8
  45. package/src/measure/inprocess.ts +15 -15
  46. package/src/measure/instructions.ts +22 -16
  47. package/src/measure/loop.ts +24 -17
  48. package/src/measure/noise.ts +8 -8
  49. package/src/measure/paired.ts +39 -47
  50. package/src/measure/peak.ts +20 -21
  51. package/src/measure/timing.ts +23 -23
  52. package/src/profile.ts +2 -1
  53. package/src/renderers/collapsed.ts +28 -21
  54. package/src/renderers/cpu-tree.ts +43 -35
  55. package/src/renderers/format.ts +16 -26
  56. package/src/renderers/index.ts +14 -4
  57. package/src/renderers/json.ts +2 -2
  58. package/src/renderers/jsonl.ts +11 -7
  59. package/src/renderers/markdown.ts +54 -36
  60. package/src/renderers/mermaid.ts +43 -31
  61. package/src/renderers/minimal.ts +15 -15
  62. package/src/renderers/paired.ts +31 -37
  63. package/src/renderers/relative.ts +10 -14
  64. package/src/renderers/select.ts +17 -39
  65. package/src/renderers/speedscope.ts +52 -48
  66. package/src/renderers/terminal.ts +37 -33
  67. package/src/spawn/index.ts +38 -47
  68. package/src/stats/bootstrap.ts +56 -58
  69. package/src/stats/index.ts +16 -12
  70. package/src/stats/mannwhitney.ts +11 -10
  71. package/src/time.ts +51 -39
package/src/ci/index.ts CHANGED
@@ -31,7 +31,7 @@ import { formatSignedPct, workloadLabel } from "../renderers/format.ts";
31
31
  import { abortedWarning } from "../time.ts";
32
32
  import { TOOL_VERSION } from "../version.ts";
33
33
 
34
- export interface CiOptions {
34
+ interface CiOptions {
35
35
  config: OstiaConfig;
36
36
  full: boolean;
37
37
  baselineName?: string;
@@ -43,9 +43,8 @@ export interface CiOptions {
43
43
  signal?: AbortSignal;
44
44
  }
45
45
 
46
- /**
47
- * Hung workloads time out rather than block a CI job;
48
- * `WorkloadConfig.timeoutMs` / `BenchConfig.timeoutMs` override this. */
46
+ // So a hung workload times out instead of blocking a CI job;
47
+ // `WorkloadConfig.timeoutMs` / `BenchConfig.timeoutMs` override this.
49
48
  const DEFAULT_CI_TIMEOUT_MS = 600_000;
50
49
 
51
50
  type WorkloadStatus = "cached" | "executed";
@@ -64,7 +63,7 @@ interface CiWorkloadResult extends MeasuredWorkload {
64
63
  comparison?: Comparison;
65
64
  }
66
65
 
67
- export interface CiSummary {
66
+ interface CiSummary {
68
67
  total: number;
69
68
  cached: number;
70
69
  executed: number;
@@ -90,13 +89,15 @@ export interface CiSummary {
90
89
  export class BaselineError extends OstiaUsageError {}
91
90
 
92
91
  export class BaselineNotFoundError extends BaselineError {
93
- constructor(public readonly path: string) {
92
+ readonly path: string;
93
+
94
+ constructor(path: string) {
94
95
  super(
95
96
  `No baseline document at ${path}. Create one with: ostia baseline save ${path
96
- .split("/")
97
- .pop()!
97
+ .slice(path.lastIndexOf("/") + 1)
98
98
  .replace(/\.json$/, "")}`,
99
99
  );
100
+ this.path = path;
100
101
  }
101
102
  }
102
103
 
@@ -104,23 +105,26 @@ export class BaselineNotFoundError extends BaselineError {
104
105
  * Thrown by `runCi` when the `onMissingBaseline` policy makes unmatched
105
106
  * workloads a hard error. */
106
107
  export class MissingBaselineError extends BaselineError {
107
- constructor(
108
- public readonly path: string,
109
- public readonly missing: number,
110
- public readonly total: number,
111
- ) {
108
+ readonly path: string;
109
+ readonly missing: number;
110
+ readonly total: number;
111
+
112
+ constructor(path: string, missing: number, total: number) {
112
113
  super(
113
114
  `${missing} of ${total} configured workload(s) have no matching row in baseline ${path} (by workload id). Re-seed with: ostia baseline save`,
114
115
  );
116
+ this.path = path;
117
+ this.missing = missing;
118
+ this.total = total;
115
119
  }
116
120
  }
117
121
 
118
- export interface MeasureConfigWorkloadsResult {
122
+ interface MeasureConfigWorkloadsResult {
119
123
  results: MeasuredWorkload[];
120
124
  /**
121
125
  * One reference measurement taken before any workload runs, unless
122
126
  * `config.noiseCheck` is false. */
123
- environment?: Environment;
127
+ environment?: Environment | undefined;
124
128
  /** The signal fired: `results` holds only what completed. */
125
129
  aborted: boolean;
126
130
  }
@@ -128,16 +132,17 @@ export interface MeasureConfigWorkloadsResult {
128
132
  async function measureSuiteWorkloads(
129
133
  config: OstiaConfig,
130
134
  wc: WorkloadConfig,
135
+ suites: string[],
131
136
  noiseWarning: Warning | undefined,
132
137
  signal: AbortSignal | undefined,
133
138
  ): Promise<MeasuredWorkload[]> {
134
139
  // Always executes: a suite file's task ids (so its cache keys) are unknown
135
140
  // without importing it.
136
- const suiteFiles = await scanGlobs(wc.suites!, process.cwd());
141
+ const suiteFiles = await scanGlobs(suites, process.cwd());
137
142
  if (suiteFiles.length === 0) {
138
143
  // Gating zero tasks would pass silently.
139
144
  throw new OstiaUsageError(
140
- `Workload suites ${JSON.stringify(wc.suites)} matched no files.`,
145
+ `Workload suites ${JSON.stringify(suites)} matched no files.`,
141
146
  );
142
147
  }
143
148
  // Same CLI-over-config resolution as `ostia bench`; only the defaults
@@ -149,9 +154,8 @@ async function measureSuiteWorkloads(
149
154
  const doc = await bench({
150
155
  ...benchOpts,
151
156
  outDir: benchOpts.outDir ?? config.outDir,
152
- // The workload's own limit, then `bench.timeoutMs`, as for a command.
153
157
  timeoutMs: wc.timeoutMs ?? benchOpts.timeoutMs ?? DEFAULT_CI_TIMEOUT_MS,
154
- signal,
158
+ ...(signal && { signal }),
155
159
  });
156
160
  const results: MeasuredWorkload[] = [];
157
161
  for (const workload of doc.workloads) {
@@ -169,13 +173,14 @@ async function measureSuiteWorkloads(
169
173
  async function measureCommandWorkload(
170
174
  config: OstiaConfig,
171
175
  wc: WorkloadConfig,
176
+ command: string[],
172
177
  full: boolean,
173
178
  noiseWarning: Warning | undefined,
174
179
  signal: AbortSignal | undefined,
175
180
  ): Promise<MeasuredWorkload> {
176
- const workload = makeSubprocessWorkload(wc.command!, wc.label, {
177
- prepare: wc.prepare,
178
- timeSource: wc.timeSource,
181
+ const workload = makeSubprocessWorkload(command, wc.label, {
182
+ ...(wc.prepare !== undefined && { prepare: wc.prepare }),
183
+ ...(wc.timeSource !== undefined && { timeSource: wc.timeSource }),
179
184
  });
180
185
  const cfgFp = configFingerprint({
181
186
  samples: config.samples ?? null,
@@ -206,22 +211,26 @@ async function measureCommandWorkload(
206
211
  run = cachedRun;
207
212
  } else {
208
213
  const phaseResult = await runTimingPhase({
209
- argv: wc.command!,
210
- samples: config.samples,
211
- budgetMs: config.budgetMs,
212
- minSamples: config.minSamples,
213
- warmup: config.warmup,
214
- prepare: wc.prepare,
215
- timeSource: wc.timeSource,
214
+ argv: command,
215
+ ...(config.samples !== undefined && { samples: config.samples }),
216
+ ...(config.budgetMs !== undefined && { budgetMs: config.budgetMs }),
217
+ ...(config.minSamples !== undefined && {
218
+ minSamples: config.minSamples,
219
+ }),
220
+ ...(config.warmup !== undefined && { warmup: config.warmup }),
221
+ ...(wc.prepare !== undefined && { prepare: wc.prepare }),
222
+ ...(wc.timeSource !== undefined && { timeSource: wc.timeSource }),
216
223
  timeoutMs: wc.timeoutMs ?? DEFAULT_CI_TIMEOUT_MS,
217
- ignoreExitCodes: wc.ignoreExitCodes,
218
- signal,
224
+ ...(wc.ignoreExitCodes !== undefined && {
225
+ ignoreExitCodes: wc.ignoreExitCodes,
226
+ }),
227
+ ...(signal && { signal }),
219
228
  });
220
229
  run = makeTimingMeasurement({
221
230
  workload,
222
231
  configFingerprint: cfgFp,
223
232
  trials: phaseResult.trials,
224
- timing: phaseResult.timing,
233
+ ...(phaseResult.timing && { timing: phaseResult.timing }),
225
234
  warnings: noiseWarning
226
235
  ? [...phaseResult.warnings, noiseWarning]
227
236
  : phaseResult.warnings,
@@ -240,10 +249,8 @@ async function measureCommandWorkload(
240
249
  };
241
250
  }
242
251
 
243
- /**
244
- * Runs every configured workload (or reads it from cache) with no baseline
245
- * comparison. Shared by `runCi` and `ostia baseline save`, so a saved
246
- * baseline comes from the same code path `ci` gates against. */
252
+ // No baseline comparison. Shared by `runCi` and `ostia baseline save`, so
253
+ // a saved baseline comes from the same code path `ci` gates against.
247
254
  export async function measureConfigWorkloads(
248
255
  config: OstiaConfig,
249
256
  full: boolean,
@@ -258,12 +265,29 @@ export async function measureConfigWorkloads(
258
265
  if (signal?.aborted) break;
259
266
  if (wc.suites) {
260
267
  results.push(
261
- ...(await measureSuiteWorkloads(config, wc, noiseWarning, signal)),
268
+ ...(await measureSuiteWorkloads(
269
+ config,
270
+ wc,
271
+ wc.suites,
272
+ noiseWarning,
273
+ signal,
274
+ )),
262
275
  );
263
- } else {
276
+ } else if (wc.command) {
264
277
  results.push(
265
- await measureCommandWorkload(config, wc, full, noiseWarning, signal),
278
+ await measureCommandWorkload(
279
+ config,
280
+ wc,
281
+ wc.command,
282
+ full,
283
+ noiseWarning,
284
+ signal,
285
+ ),
266
286
  );
287
+ } else {
288
+ // invariant: config validation gives every workload exactly one of
289
+ // `command` and `suites`.
290
+ throw new Error("ci: a workload has neither command nor suites");
267
291
  }
268
292
  }
269
293
  const aborted = signal?.aborted ?? false;
@@ -400,7 +424,7 @@ export function renderCiReport(summary: CiSummary): string {
400
424
  const regressionDetails = summary.results
401
425
  .filter((r) => r.comparison?.verdict === "fail")
402
426
  .map((r) => {
403
- const t = r.comparison!.timing;
427
+ const t = r.comparison?.timing;
404
428
  const label = workloadLabel(r.workload);
405
429
  return t
406
430
  ? `${formatSignedPct(t.medianDeltaPct)} median on ${label}`
package/src/cli/flags.ts CHANGED
@@ -23,12 +23,11 @@ export const VIZ_FORMATS = [
23
23
  "cpuprofile",
24
24
  ] as const;
25
25
 
26
- export const REPORT_FORMATS = [...DOCUMENT_FORMATS, ...VIZ_FORMATS] as const;
26
+ export const REPORT_FORMATS: readonly [
27
+ ...typeof DOCUMENT_FORMATS,
28
+ ...typeof VIZ_FORMATS,
29
+ ] = [...DOCUMENT_FORMATS, ...VIZ_FORMATS] as const;
27
30
 
28
- /**
29
- * Integer flag value >= `opts.min` (default 1); `opts.allowAuto` also
30
- * accepts "auto" as the available job count.
31
- */
32
31
  export function parseIntFlag(
33
32
  name: string,
34
33
  raw: string | undefined,
@@ -78,25 +77,22 @@ type FlagTable = Record<string, FlagDef>;
78
77
 
79
78
  const def = (dest: string, spec: FlagSpec): FlagDef => ({ dest, spec });
80
79
 
81
- /**
82
- * Builders for `FlagTable` entries; `dest` is the property set on the
83
- * parsed args.
84
- */
85
80
  export const flag = {
86
- str: (dest: string) => def(dest, { kind: "string" }),
87
- int: (dest: string, min = 1, allowAuto = false) =>
81
+ str: (dest: string): FlagDef => def(dest, { kind: "string" }),
82
+ int: (dest: string, min: number = 1, allowAuto: boolean = false): FlagDef =>
88
83
  def(dest, { kind: "int", min, allowAuto }),
89
- num: (dest: string, min: number) => def(dest, { kind: "number", min }),
90
- on: (dest: string) => def(dest, { kind: "bool", value: true }),
91
- off: (dest: string) => def(dest, { kind: "bool", value: false }),
92
- oneOf: (dest: string, values: readonly string[]) =>
84
+ num: (dest: string, min: number): FlagDef =>
85
+ def(dest, { kind: "number", min }),
86
+ on: (dest: string): FlagDef => def(dest, { kind: "bool", value: true }),
87
+ off: (dest: string): FlagDef => def(dest, { kind: "bool", value: false }),
88
+ oneOf: (dest: string, values: readonly string[]): FlagDef =>
93
89
  def(dest, { kind: "enum", values }),
94
90
  /** Repeatable; each occurrence appends one value. */
95
- list: (dest: string) => def(dest, { kind: "list" }),
91
+ list: (dest: string): FlagDef => def(dest, { kind: "list" }),
96
92
  /** Repeatable; each occurrence is whitespace-split and appended. */
97
- words: (dest: string) => def(dest, { kind: "words" }),
93
+ words: (dest: string): FlagDef => def(dest, { kind: "words" }),
98
94
  /** `--flag[=CODE,...]`: bare means every non-zero exit code. */
99
- exitCodes: (dest: string) => def(dest, { kind: "exitCodes" }),
95
+ exitCodes: (dest: string): FlagDef => def(dest, { kind: "exitCodes" }),
100
96
  };
101
97
 
102
98
  export interface OutputArgs {
@@ -116,7 +112,9 @@ export const OUTPUT_DEFAULTS = {
116
112
  help: false,
117
113
  } as const;
118
114
 
119
- export const RUN_DEFAULTS = { ...OUTPUT_DEFAULTS, noiseCheck: true } as const;
115
+ export const RUN_DEFAULTS: typeof OUTPUT_DEFAULTS & {
116
+ readonly noiseCheck: true;
117
+ } = { ...OUTPUT_DEFAULTS, noiseCheck: true } as const;
120
118
 
121
119
  export const HELP_FLAGS: FlagTable = {
122
120
  "--help": flag.on("help"),
@@ -134,10 +132,6 @@ export const NOISE_CHECK_FLAGS: FlagTable = {
134
132
  "--no-noise-check": flag.off("noiseCheck"),
135
133
  };
136
134
 
137
- /**
138
- * `--config PATH`: for the commands that read a config file (bench, ab,
139
- * compare, ci, baseline).
140
- */
141
135
  export const CONFIG_FLAGS: FlagTable = {
142
136
  "--config": flag.str("config"),
143
137
  };
@@ -146,10 +140,8 @@ export interface ConfigArgs {
146
140
  config?: string;
147
141
  }
148
142
 
149
- /**
150
- * Flags shared by every command that runs measurements (`ci` has no
151
- * per-run flags).
152
- */
143
+ // Every command that runs measurements takes these, except `ci`, which
144
+ // doesn't take per-run flags.
153
145
  export const RUN_FLAGS: FlagTable = {
154
146
  ...OUTPUT_FLAGS,
155
147
  ...NOISE_CHECK_FLAGS,
@@ -157,7 +149,6 @@ export const RUN_FLAGS: FlagTable = {
157
149
  "--out-dir": flag.str("outDir"),
158
150
  };
159
151
 
160
- /** Flags shared by `bench` and `ab`. */
161
152
  export const SUITE_FLAGS: FlagTable = {
162
153
  ...RUN_FLAGS,
163
154
  ...CONFIG_FLAGS,
@@ -166,6 +157,16 @@ export const SUITE_FLAGS: FlagTable = {
166
157
  "--bun-flags": flag.words("bunFlags"),
167
158
  };
168
159
 
160
+ // invariant: a repeatable flag's `dest` starts as an array in the
161
+ // command's defaults.
162
+ function listAt(args: object, dest: string): unknown[] {
163
+ const list: unknown = Reflect.get(args, dest);
164
+ if (!Array.isArray(list)) {
165
+ throw new TypeError(`ostia: flag destination "${dest}" isn't an array`);
166
+ }
167
+ return list;
168
+ }
169
+
169
170
  interface ParseSpec<T> {
170
171
  command: string;
171
172
  flags: FlagTable;
@@ -179,17 +180,15 @@ interface ParseSpec<T> {
179
180
  rest?: (rest: string[], args: T) => void;
180
181
  }
181
182
 
182
- /**
183
- * Parses `argv` into `args` per `flags`; `--flag=value` equals `--flag
184
- * value`. Throws `CliUsageError`.
185
- */
183
+ // Throws only `CliUsageError`, so the dispatcher can print a `--help`
184
+ // pointer for any parse failure. `--flag=value` equals `--flag value`.
186
185
  export function parseFlags<T extends object>(
187
186
  argv: string[],
188
187
  { command, flags, args, positional, rest }: ParseSpec<T>,
189
188
  ): T {
190
- const bag = args as Record<string, unknown>;
189
+ const set = (dest: string, value: unknown) => Reflect.set(args, dest, value);
191
190
  for (let i = 0; i < argv.length; i++) {
192
- const arg = argv[i]!;
191
+ const arg = argv[i] ?? "";
193
192
  if (arg === "--" && rest) {
194
193
  rest(argv.slice(i + 1), args);
195
194
  break;
@@ -211,15 +210,15 @@ export function parseFlags<T extends object>(
211
210
  if (i + 1 >= argv.length) {
212
211
  throw new CliUsageError(`Missing value for ${name}.`);
213
212
  }
214
- return argv[++i]!;
213
+ return argv[++i] ?? "";
215
214
  };
216
215
  const { dest, spec } = flagDef;
217
216
  switch (spec.kind) {
218
217
  case "string":
219
- bag[dest] = value();
218
+ set(dest, value());
220
219
  break;
221
220
  case "int":
222
- bag[dest] = parseIntFlag(name, value(), spec);
221
+ set(dest, parseIntFlag(name, value(), spec));
223
222
  break;
224
223
  case "number": {
225
224
  const raw = value();
@@ -229,20 +228,20 @@ export function parseFlags<T extends object>(
229
228
  `Invalid ${name} "${raw}": expected a number ≥ ${spec.min}`,
230
229
  );
231
230
  }
232
- bag[dest] = n;
231
+ set(dest, n);
233
232
  break;
234
233
  }
235
234
  case "bool":
236
- bag[dest] = spec.value;
235
+ set(dest, spec.value);
237
236
  break;
238
237
  case "list":
239
- (bag[dest] as string[]).push(value());
238
+ listAt(args, dest).push(value());
240
239
  break;
241
240
  case "words":
242
- (bag[dest] as string[]).push(...splitCommand(value()));
241
+ listAt(args, dest).push(...splitCommand(value()));
243
242
  break;
244
243
  case "exitCodes":
245
- (bag[dest] as number[]).push(
244
+ listAt(args, dest).push(
246
245
  ...(eq > 0
247
246
  ? parseExitCodes(name, arg.slice(eq + 1))
248
247
  : Array.from({ length: 255 }, (_, n) => n + 1)),
@@ -255,7 +254,7 @@ export function parseFlags<T extends object>(
255
254
  `Invalid ${name} "${raw}": expected one of: ${spec.values.join(", ")}`,
256
255
  );
257
256
  }
258
- bag[dest] = raw;
257
+ set(dest, raw);
259
258
  break;
260
259
  }
261
260
  }
package/src/cli/output.ts CHANGED
@@ -12,9 +12,10 @@ import {
12
12
  type MinimalRenderOptions,
13
13
  } from "../renderers/minimal.ts";
14
14
 
15
- // Bun.write skips process.stdout/stderr's Node stream setup, which costs
16
- // startup time.
17
- export const out = (text: string) => Bun.write(Bun.stdout, text);
15
+ // Bun.write, because it skips the Node stream setup process.stdout and
16
+ // process.stderr cost at startup.
17
+ export const out = (text: string): Promise<number> =>
18
+ Bun.write(Bun.stdout, text);
18
19
  const errOut = (text: string) => Bun.write(Bun.stderr, text);
19
20
 
20
21
  /**
@@ -38,20 +39,20 @@ export type CliErrorCode =
38
39
 
39
40
  /** Thrown to abort a command with exit 2; the dispatcher reports it. */
40
41
  export class CliError extends Error {
42
+ readonly code: CliErrorCode;
43
+ // Structured detail for the `error` event's `data`.
44
+ readonly data?: Record<string, unknown> | undefined;
41
45
  constructor(
42
- readonly code: CliErrorCode,
46
+ code: CliErrorCode,
43
47
  message: string,
44
- /** Structured detail for the `error` event's `data`. */
45
- readonly data?: Record<string, unknown>,
48
+ data?: Record<string, unknown>,
46
49
  ) {
47
50
  super(message);
51
+ this.code = code;
52
+ this.data = data;
48
53
  }
49
54
  }
50
55
 
51
- /**
52
- * Runs `run`, turning any failure into a `CliError` of `code` with
53
- * `message` as a prefix.
54
- */
55
56
  export async function orFail<T>(
56
57
  code: CliErrorCode,
57
58
  message: string,
@@ -70,12 +71,11 @@ export async function orFail<T>(
70
71
 
71
72
  const MACHINE_FORMATS = new Set(["minimal", "json", "jsonl"]);
72
73
 
73
- /**
74
- * Machine errors are for scripts and agents: stderr isn't a terminal, or a
75
- * machine `--format` was asked for.
76
- */
74
+ // Machine errors are for scripts and agents: stderr isn't a terminal, or a
75
+ // machine `--format` was asked for.
77
76
  async function wantsMachineErrors(): Promise<boolean> {
78
- // Imported lazily: loading node:tty up front costs every invocation ~15ms.
77
+ // perf: imported lazily, since loading node:tty up front costs every
78
+ // invocation ~15ms.
79
79
  const { isatty } = await import("node:tty");
80
80
  if (!isatty(2)) return true;
81
81
  const argv = process.argv.slice(2);
@@ -87,10 +87,8 @@ async function wantsMachineErrors(): Promise<boolean> {
87
87
  );
88
88
  }
89
89
 
90
- /**
91
- * Writes `message` to stderr, then for a machine reader one JSON `error`
92
- * line (first line of `message` only). Never touches stdout.
93
- */
90
+ // Writes `message` to stderr, then for a machine reader one JSON `error`
91
+ // line (first line of `message` only). Never touches stdout.
94
92
  export async function writeCliError(
95
93
  code: CliErrorCode,
96
94
  message: string,
@@ -109,11 +107,10 @@ export async function writeCliError(
109
107
  );
110
108
  }
111
109
 
112
- /**
113
- * Prints help and returns the exit code: 0 when asked for, 2 when shown
114
- * for missing input.
115
- */
116
- export async function showHelp(text: string, requested: boolean) {
110
+ export async function showHelp(
111
+ text: string,
112
+ requested: boolean,
113
+ ): Promise<0 | 2> {
117
114
  await out(text);
118
115
  return requested ? 0 : 2;
119
116
  }
@@ -126,14 +123,15 @@ export async function writeRenderResult(
126
123
 
127
124
  if (!result.files || result.files.length === 0) return;
128
125
 
126
+ const only = result.files.length === 1 ? result.files[0] : undefined;
129
127
  if (outDir) {
130
128
  for (const f of result.files) {
131
129
  const path = f.path ? `${outDir}/${f.path}` : outDir;
132
130
  await Bun.write(path, f.content);
133
131
  await out(`wrote ${path}\n`);
134
132
  }
135
- } else if (result.files.length === 1) {
136
- await out(result.files[0]!.content);
133
+ } else if (only) {
134
+ await out(only.content);
137
135
  } else {
138
136
  for (const f of result.files) {
139
137
  await out(`--- ${f.path ?? "(unnamed)"} ---\n${f.content}\n`);
@@ -147,11 +145,9 @@ interface OutputOptions {
147
145
  quiet: boolean;
148
146
  }
149
147
 
150
- /**
151
- * Honors `--export-json`; returns the JSON text when `--format json` will
152
- * print it (the json renderer's output is exactly this, so serialize
153
- * once).
154
- */
148
+ // Honors `--export-json`; returns the JSON text when `--format json` will
149
+ // print it (the json renderer's output is exactly this, so serialize
150
+ // once).
155
151
  export async function exportDocument(
156
152
  doc: ProfileDocument,
157
153
  { exportJson, format, quiet }: OutputOptions,
@@ -165,10 +161,8 @@ export async function exportDocument(
165
161
  return jsonText;
166
162
  }
167
163
 
168
- /**
169
- * Shared tail of time/bench/ab/compare: `--export-json`, then the report
170
- * unless `--quiet`. `rendererOptions` reaches the renderer verbatim.
171
- */
164
+ // Shared tail of time/bench/ab/compare: `--export-json`, then the report
165
+ // unless `--quiet`. `rendererOptions` reaches the renderer verbatim.
172
166
  export async function emitDocument(
173
167
  doc: ProfileDocument,
174
168
  args: OutputOptions,