ostia 0.6.1 → 0.7.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.
@@ -208,6 +208,18 @@ function runNotes(doc: ProfileDocument, paint: Paint): string[] {
208
208
  const isAborted = (doc: ProfileDocument) =>
209
209
  doc.measurements.some((m) => m.warnings.some((w) => w.code === "aborted"));
210
210
 
211
+ // A stopped bench leaves out the tasks it never ran, so its `aborted`
212
+ // warning says how many its suites planned.
213
+ function plannedTasks(doc: ProfileDocument): number | undefined {
214
+ for (const m of doc.measurements) {
215
+ for (const w of m.warnings) {
216
+ const tasks = w.code === "aborted" ? w.data?.["tasks"] : undefined;
217
+ if (typeof tasks === "number") return tasks;
218
+ }
219
+ }
220
+ return undefined;
221
+ }
222
+
211
223
  // A row's place in its group, so the group's label prints once, above
212
224
  // its first row, and its last row closes it with └.
213
225
  function grouped<T extends { group: string | undefined }>(
@@ -511,7 +523,7 @@ function timingClosing(
511
523
  return failWith(
512
524
  paint,
513
525
  "Cancelled",
514
- `${measured.length} of ${plural(rows.length, noun)} measured`,
526
+ `${measured.length} of ${plural(plannedTasks(doc) ?? rows.length, noun)} measured`,
515
527
  );
516
528
  }
517
529
  const failed = rows.filter(isFailedRow);
package/src/terminal.ts CHANGED
@@ -51,8 +51,9 @@ export function createPaint(): Paint {
51
51
 
52
52
  // The person's explicit ask wins, because they know where the output
53
53
  // goes: the flag, then NO_COLOR and FORCE_COLOR (no-color.org,
54
- // force-color.org). Otherwise color only for a terminal no coding agent
55
- // reads, since escape codes are noise to a program.
54
+ // force-color.org). Otherwise color only for a terminal that reads
55
+ // escape codes and no coding agent reads, since they're noise to
56
+ // a program.
56
57
  export function wantsColor(
57
58
  forced: boolean | undefined,
58
59
  terminal: boolean,
@@ -63,9 +64,160 @@ export function wantsColor(
63
64
  if ((env.NO_COLOR ?? "") !== "") return false;
64
65
  const force = env.FORCE_COLOR;
65
66
  if (force !== undefined && force !== "") return force !== "0";
66
- return terminal && !agent;
67
+ return terminal && !agent && !isDumb(env);
67
68
  }
68
69
 
70
+ // TERM=dumb says the terminal knows no escape sequence: no color, and no
71
+ // carriage-return redraw, so a progress line would print every frame.
72
+ export const isDumb = (
73
+ env: Readonly<Record<string, string | undefined>>,
74
+ ): boolean => env.TERM === "dumb";
75
+
76
+ // The variables a coding agent sets, one list so every tool agrees on
77
+ // what an agent is: `AGENT` and `CLAUDECODE`, which Bun reads;
78
+ // `AI_AGENT`, the cross-vendor name; and Codex's two. One that a shell
79
+ // sets without an agent, as Replit's REPL_ID, stays out.
80
+ export const AGENT_ENV = [
81
+ "AGENT",
82
+ "AI_AGENT",
83
+ "CLAUDECODE",
84
+ "CODEX_CI",
85
+ "CODEX_THREAD_ID",
86
+ ] as const;
87
+
88
+ // The first agent variable that's set, for the line saying why the
89
+ // output is the agent's. Empty or `0` is a person saying "not an agent"
90
+ // without unsetting it.
91
+ export const agentVariableOf = (
92
+ env: Readonly<Record<string, string | undefined>>,
93
+ ): string | undefined =>
94
+ AGENT_ENV.find((name) => {
95
+ const value = env[name];
96
+ return value !== undefined && value !== "" && value !== "0";
97
+ });
98
+
99
+ // Whether a coding agent runs the tool, so color and redraws are off:
100
+ // what wantsColor and wantsRedraw take as `agent`.
101
+ export const isAgent = (
102
+ env: Readonly<Record<string, string | undefined>>,
103
+ ): boolean => agentVariableOf(env) !== undefined;
104
+
105
+ /**
106
+ * The marks a component draws, one per state, and the shapes it draws
107
+ * with. The marks after `spinner` came later, so each is optional: a set
108
+ * without one draws UNICODE_GLYPHS' mark.
109
+ */
110
+ export type Glyphs = {
111
+ done: string;
112
+ failed: string;
113
+ skipped: string;
114
+ pending: string;
115
+ spinner: readonly string[];
116
+ /** The choice the cursor is on. */
117
+ pointer?: string;
118
+ /** A choice a multi-select has picked. */
119
+ picked?: string;
120
+ /** A choice a multi-select hasn't picked. */
121
+ unpicked?: string;
122
+ /** More above a window of a list. */
123
+ up?: string;
124
+ /** More below a window of a list. */
125
+ down?: string;
126
+ /** The keys that move, in a key hint. */
127
+ upDown?: string;
128
+ /** The keys that choose sideways, in a key hint. */
129
+ leftRight?: string;
130
+ /** A bar's done part. */
131
+ barDone?: string;
132
+ /** A bar's part to go. */
133
+ barTodo?: string;
134
+ };
135
+
136
+ /** The marks for a terminal whose locale is UTF-8. */
137
+ export const UNICODE_GLYPHS: Required<Glyphs> = {
138
+ done: "✓",
139
+ failed: "✗",
140
+ skipped: "-",
141
+ pending: "○",
142
+ spinner: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
143
+ pointer: "›",
144
+ picked: "●",
145
+ unpicked: "○",
146
+ up: "↑",
147
+ down: "↓",
148
+ upDown: "↑↓",
149
+ leftRight: "←→",
150
+ barDone: "━",
151
+ barTodo: "─",
152
+ };
153
+
154
+ // One frame for running, since an ASCII spinner's `-` would read as
155
+ // skipped for a frame; the seconds still move past one.
156
+ /** The same marks in ASCII, each its own shape, so none needs color. */
157
+ export const ASCII_GLYPHS: Required<Glyphs> = {
158
+ done: "+",
159
+ failed: "x",
160
+ skipped: "-",
161
+ pending: ".",
162
+ spinner: [">"],
163
+ pointer: ">",
164
+ picked: "[x]",
165
+ unpicked: "[ ]",
166
+ up: "^",
167
+ down: "v",
168
+ upDown: "up/down",
169
+ leftRight: "left/right",
170
+ barDone: "=",
171
+ barTodo: "-",
172
+ };
173
+
174
+ type Mark = Exclude<
175
+ keyof Glyphs,
176
+ "done" | "failed" | "skipped" | "pending" | "spinner"
177
+ >;
178
+
179
+ // A set made before a mark existed draws the Unicode one, so it
180
+ // needn't change.
181
+ export const markOf = (glyphs: Glyphs, mark: Mark): string =>
182
+ glyphs[mark] ?? UNICODE_GLYPHS[mark];
183
+
184
+ // An unset locale is taken as UTF-8, every current system's default,
185
+ // since CI and a GUI's shell often set none; one that names C or
186
+ // another charset gets ASCII, as TERM=dumb does.
187
+ /**
188
+ * Whether to draw ASCII_GLYPHS: under TERM=dumb, or a locale that
189
+ * isn't UTF-8.
190
+ */
191
+ export function wantsAscii(
192
+ env: Readonly<Record<string, string | undefined>>,
193
+ ): boolean {
194
+ if (isDumb(env)) return true;
195
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG;
196
+ return locale !== undefined && locale !== "" && !/utf-?8/i.test(locale);
197
+ }
198
+
199
+ const HIDE_CURSOR = "\x1b[?25l";
200
+ const SHOW_CURSOR = "\x1b[?25h";
201
+ // What this process last did to the cursor, so an exit shows it only
202
+ // when something hid it.
203
+ const cursor = { hidden: false };
204
+
205
+ // The code that hides the cursor, noted, so an exit knows to show it.
206
+ export function hideCursor(): string {
207
+ cursor.hidden = true;
208
+ return HIDE_CURSOR;
209
+ }
210
+
211
+ // The code that shows the cursor again, noted, so an exit doesn't write
212
+ // it twice.
213
+ export function showCursor(): string {
214
+ cursor.hidden = false;
215
+ return SHOW_CURSOR;
216
+ }
217
+
218
+ // Whether a component hid the cursor and hasn't shown it since.
219
+ export const cursorHidden = (): boolean => cursor.hidden;
220
+
69
221
  // "n/a", because an em dash for a missing value reads as punctuation.
70
222
  export const MISSING = "n/a";
71
223
 
@@ -88,18 +240,89 @@ export const NOTE_INDENT = " ";
88
240
 
89
241
  // The last line of a run that finished: what it did and what it took,
90
242
  // so a person sees it ended and why it took that long.
243
+ // `glyphs` gives the mark, as ASCII_GLYPHS where the locale isn't UTF-8.
91
244
  export function closingLine(
92
245
  paint: Paint,
93
246
  what: string,
94
247
  detail?: string,
248
+ glyphs: Pick<Glyphs, "done"> = UNICODE_GLYPHS,
95
249
  ): string {
96
- return `${paint.good("✓")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
250
+ return `${paint.good(glyphs.done)} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
97
251
  }
98
252
 
99
253
  // A run that found problems ends in a cross, so the last line says
100
254
  // whether to act, as the check mark does when there's nothing to do.
101
- export function failLine(paint: Paint, what: string, detail?: string): string {
102
- return `${paint.bad("✗")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
255
+ export function failLine(
256
+ paint: Paint,
257
+ what: string,
258
+ detail?: string,
259
+ glyphs: Pick<Glyphs, "failed"> = UNICODE_GLYPHS,
260
+ ): string {
261
+ return `${paint.bad(glyphs.failed)} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
262
+ }
263
+
264
+ /** A key a person can press, and what it does, for a hint line. */
265
+ export type KeyHint = { key: string; does: string };
266
+
267
+ /** Renders keys as one faint hint line: `↑↓ move · enter run · esc cancel`. */
268
+ export const keyHints = (paint: Paint, keys: readonly KeyHint[]): string =>
269
+ paint.faint(keys.map((k) => `${k.key} ${k.does}`).join(SEPARATOR));
270
+
271
+ // A swap of two neighbors counts as one edit (optimal string alignment),
272
+ // so "--otu" is one edit from "--out".
273
+ function distance(a: string, b: string): number {
274
+ const width = b.length + 1;
275
+ const cells = new Uint32Array((a.length + 1) * width);
276
+ const d = (i: number, j: number) => cells[i * width + j] ?? 0;
277
+ for (let i = 0; i <= a.length; i++) cells[i * width] = i;
278
+ for (let j = 0; j <= b.length; j++) cells[j] = j;
279
+ for (let i = 1; i <= a.length; i++) {
280
+ for (let j = 1; j <= b.length; j++) {
281
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
282
+ let best = Math.min(
283
+ d(i - 1, j) + 1,
284
+ d(i, j - 1) + 1,
285
+ d(i - 1, j - 1) + cost,
286
+ );
287
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
288
+ best = Math.min(best, d(i - 2, j - 2) + 1);
289
+ }
290
+ cells[i * width + j] = best;
291
+ }
292
+ }
293
+ return d(a.length, b.length);
294
+ }
295
+
296
+ // Dashes aside and case folded, since `-V` is a typo of `-v` and the
297
+ // dashes are shared by every flag.
298
+ function shareLetter(a: string, b: string): boolean {
299
+ const letters = new Set(a.replace(/^-+/, "").toLowerCase());
300
+ for (const c of b.replace(/^-+/, "").toLowerCase()) {
301
+ if (letters.has(c)) return true;
302
+ }
303
+ return false;
304
+ }
305
+
306
+ // The real flag or command nearest a typo, for "did you mean --json?":
307
+ // within a third of the input's length in edits, so a short typo still
308
+ // finds its flag and a word that's merely long doesn't match. The two
309
+ // names, dashes aside, share a letter, since one letter is one edit from
310
+ // every other: `-x` isn't a typo of `-h`, though `-V` may be of `-v`.
311
+ export function nearest(
312
+ input: string,
313
+ candidates: Iterable<string>,
314
+ ): string | undefined {
315
+ const most = Math.max(1, Math.floor(input.length / 3));
316
+ let best: string | undefined;
317
+ let bestDistance = most + 1;
318
+ for (const candidate of candidates) {
319
+ const d = distance(input, candidate);
320
+ if (d < bestDistance && shareLetter(input, candidate)) {
321
+ best = candidate;
322
+ bestDistance = d;
323
+ }
324
+ }
325
+ return best;
103
326
  }
104
327
 
105
328
  // Cut at a word boundary, so a label never ends mid-word; JSON keeps
@@ -160,6 +383,8 @@ export function withGutter(
160
383
 
161
384
  // eslint-disable-next-line no-control-regex -- escape codes are what it strips
162
385
  const ESCAPE = /\x1b\[[0-9;]*m/g;
386
+ // eslint-disable-next-line no-control-regex -- escape codes are what it skips
387
+ const LEADING_ESCAPE = /^\x1b\[[0-9;]*m/;
163
388
 
164
389
  // Widths come from Bun when it runs, since it counts wide characters;
165
390
  // a package that also runs on Node counts one column per code point,
@@ -172,6 +397,216 @@ export const textWidth = (text: string): number =>
172
397
  // 80 columns, because that's the width a terminal opens at.
173
398
  export const MEASURE = 80;
174
399
 
400
+ // Because a help table's second column starts after a run of two or more
401
+ // spaces, a wrapped description continues there, not at the margin.
402
+ function hangOf(line: string): number {
403
+ const plain = line.replace(ESCAPE, "");
404
+ const lead = /^ */.exec(plain)?.[0].length ?? 0;
405
+ const gap = /^ *\S.*? {2,}(?=\S)/.exec(plain);
406
+ return gap ? textWidth(gap[0]) : lead;
407
+ }
408
+
409
+ // Columns count only what shows, since a color code in the first half
410
+ // would otherwise put the split early.
411
+ function splitAt(line: string, columns: number): [string, string] {
412
+ let seen = 0;
413
+ let i = 0;
414
+ while (i < line.length && seen < columns) {
415
+ const escape = LEADING_ESCAPE.exec(line.slice(i));
416
+ if (escape) {
417
+ i += escape[0].length;
418
+ continue;
419
+ }
420
+ const ch = String.fromCodePoint(line.codePointAt(i) ?? 32);
421
+ seen += textWidth(ch);
422
+ i += ch.length;
423
+ }
424
+ return [line.slice(0, i), line.slice(i)];
425
+ }
426
+
427
+ // Help and other prose for a person: fit to the terminal, at most 80
428
+ // columns, and left whole when piped, since a program reads whole lines.
429
+ // Each line wraps alone; fitHelp rewraps a description written over
430
+ // several lines as one.
431
+ export const fitTerminal = (
432
+ text: string,
433
+ terminal: boolean,
434
+ columns: number | undefined,
435
+ ): string =>
436
+ terminal ? fitWidth(text, Math.min(MEASURE, columns || MEASURE)) : text;
437
+
438
+ // The separator stays with the word after it, so no line ends on a
439
+ // dangling "·".
440
+ function wordsOf(text: string): string[] {
441
+ const words: string[] = [];
442
+ for (const word of text.split(/ +/)) {
443
+ const last = words.at(-1);
444
+ if (last !== undefined && last.replace(ESCAPE, "") === "·") {
445
+ words[words.length - 1] = `${last} ${word}`;
446
+ } else if (word !== "") words.push(word);
447
+ }
448
+ return words;
449
+ }
450
+
451
+ // Words in lines of at most `room` columns; a word wider than that is
452
+ // cut into pieces that fit, when `breakWords`, or else left whole on a
453
+ // line of its own.
454
+ function wrapWords(
455
+ words: readonly string[],
456
+ room: number,
457
+ breakWords: boolean,
458
+ ): string[] {
459
+ const lines: string[] = [];
460
+ let current = "";
461
+ for (const word of words) {
462
+ const pieces: string[] = [];
463
+ let rest = word;
464
+ while (breakWords && textWidth(rest) > room) {
465
+ const [piece, after] = splitAt(rest, room);
466
+ pieces.push(piece);
467
+ rest = after;
468
+ }
469
+ pieces.push(rest);
470
+ for (const piece of pieces) {
471
+ const next = current === "" ? piece : `${current} ${piece}`;
472
+ if (current !== "" && textWidth(next) > room) {
473
+ lines.push(current);
474
+ current = piece;
475
+ } else {
476
+ current = next;
477
+ }
478
+ }
479
+ }
480
+ if (current !== "") lines.push(current);
481
+ return lines;
482
+ }
483
+
484
+ // Text whose lines are wider than `width`, wrapped at words: help on a
485
+ // narrow terminal, where a long line would wrap mid-word. A continuation
486
+ // line starts under its line's second column, or under its indent, so a
487
+ // table of options and their descriptions stays a table.
488
+ export function fitWidth(text: string, width: number): string {
489
+ return text
490
+ .split("\n")
491
+ .flatMap((line) => {
492
+ if (textWidth(line) <= width) return [line];
493
+ let hang = hangOf(line);
494
+ if (hang > width / 2)
495
+ hang = /^ */.exec(line.replace(ESCAPE, ""))?.[0].length ?? 0;
496
+ const [head, rest] = splitAt(line, hang);
497
+ const room = Math.max(1, width - hang);
498
+ return wrapWords(wordsOf(rest), room, false).map(
499
+ (part, k) => (k === 0 ? head : " ".repeat(hang)) + part,
500
+ );
501
+ })
502
+ .join("\n");
503
+ }
504
+
505
+ // What fitHelp does with a word wider than its line: "break" cuts it,
506
+ // so no line is wider than the terminal; "keep" leaves it whole on a
507
+ // line of its own, for a URL or a path a person copies.
508
+ export type HelpOptions = { words?: "break" | "keep" };
509
+
510
+ const LEAD = /^ */;
511
+ // A list item's lines continue under its text, not its marker, so the
512
+ // wrap hangs there.
513
+ const LIST_ITEM = /^ *(?:[-*•]|\d+[.)]) +(?=\S)/;
514
+ const leadOf = (line: string) =>
515
+ LEAD.exec(line.replace(ESCAPE, ""))?.[0].length ?? 0;
516
+ // Where a line's text continues, since a wrap hangs there: under its
517
+ // second column, an item's text, or its indent.
518
+ const columnOf = (line: string) => {
519
+ const item = LIST_ITEM.exec(line.replace(ESCAPE, ""));
520
+ return item ? textWidth(item[0]) : hangOf(line);
521
+ };
522
+
523
+ // A line continues the paragraph above when it starts where the
524
+ // paragraph's first line has its text, under the description or at the
525
+ // margin, and isn't a row or an item of its own.
526
+ function paragraphsOf(text: string): string[][] {
527
+ const paragraphs: string[][] = [];
528
+ for (const line of text.split("\n")) {
529
+ const current = paragraphs.at(-1);
530
+ const first = current?.[0];
531
+ const continues =
532
+ current !== undefined &&
533
+ first !== undefined &&
534
+ line.trim() !== "" &&
535
+ (current.at(-1) ?? "").trim() !== "" &&
536
+ !LIST_ITEM.test(line.replace(ESCAPE, "")) &&
537
+ hangOf(line) === leadOf(line) &&
538
+ leadOf(line) === columnOf(first);
539
+ if (continues) current.push(line);
540
+ else paragraphs.push([line]);
541
+ }
542
+ return paragraphs;
543
+ }
544
+
545
+ // A paragraph that fits stays as written; one with a line too wide is
546
+ // joined and wrapped as one, its description under its second column,
547
+ // or under the option, indented, when the column would leave too little
548
+ // room: past half the width, or narrower than its longest word.
549
+ function fitParagraph(
550
+ lines: readonly string[],
551
+ width: number,
552
+ breakWords: boolean,
553
+ ): string[] {
554
+ if (lines.every((line) => textWidth(line) <= width)) return [...lines];
555
+ const [first = "", ...rest] = lines;
556
+ const joined = [first.trimEnd(), ...rest.map((line) => line.trim())].join(
557
+ " ",
558
+ );
559
+ const lead = leadOf(first);
560
+ const column = columnOf(first);
561
+ const [head, body] = splitAt(joined, column);
562
+ const words = wordsOf(body);
563
+ const longest = Math.max(0, ...words.map(textWidth));
564
+ const hung = (prefix: string, indent: number) =>
565
+ wrapWords(words, Math.max(1, width - indent), breakWords).map(
566
+ (part, k) => (k === 0 ? prefix : " ".repeat(indent)) + part,
567
+ );
568
+ if (column === lead || (column <= width / 2 && column + longest <= width)) {
569
+ return hung(head, column);
570
+ }
571
+ const [margin, option] = splitAt(head.trimEnd(), lead);
572
+ const optionLines = wrapWords(
573
+ wordsOf(option),
574
+ Math.max(1, width - lead),
575
+ breakWords,
576
+ ).map((part, k) => (k === 0 ? margin : " ".repeat(lead)) + part);
577
+ const indent = lead + 4;
578
+ return [...optionLines, ...hung(" ".repeat(indent), indent)];
579
+ }
580
+
581
+ // Help as a terminal shows it: at most 80 columns, or the terminal's
582
+ // width when narrower, and as written when piped, since a program reads
583
+ // whole lines. Unlike fitTerminal, a description written over several
584
+ // lines rewraps as one, so it isn't left ragged; on a terminal too
585
+ // narrow for its column it goes under its option; and a word too long
586
+ // for a line is cut, or kept whole with `words: "keep"`.
587
+ export const fitHelp = (
588
+ text: string,
589
+ terminal: boolean,
590
+ columns: number | undefined,
591
+ options: HelpOptions = {},
592
+ ): string =>
593
+ terminal
594
+ ? wrapHelp(text, Math.min(MEASURE, columns || MEASURE), options)
595
+ : text;
596
+
597
+ // fitHelp at a given width, on a terminal or not, so a test or a caller
598
+ // that knows the width needn't fake a terminal.
599
+ export const wrapHelp = (
600
+ text: string,
601
+ width: number,
602
+ options: HelpOptions = {},
603
+ ): string =>
604
+ paragraphsOf(text)
605
+ .flatMap((lines) =>
606
+ fitParagraph(lines, width, (options.words ?? "break") === "break"),
607
+ )
608
+ .join("\n");
609
+
175
610
  // A cell that draws a rule as wide as its column, so totals read apart
176
611
  // from the rows above them.
177
612
  export const RULE = "\u0000rule";
@@ -291,6 +726,7 @@ export function createProgress(
291
726
  write: (text: string) => void,
292
727
  paint: Paint,
293
728
  nowMs: () => number,
729
+ glyphs: Glyphs = UNICODE_GLYPHS,
294
730
  ): Progress {
295
731
  const startMs = nowMs();
296
732
  let text = "";
@@ -300,7 +736,8 @@ export function createProgress(
300
736
  // Done and to-do differ in shape as well as color, so the bar reads
301
737
  // without color too.
302
738
  const bar =
303
- paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
739
+ paint.good(markOf(glyphs, "barDone").repeat(done)) +
740
+ paint.dim(markOf(glyphs, "barTodo").repeat(BAR_WIDTH - done));
304
741
  const seconds = Math.floor((nowMs() - startMs) / 1000);
305
742
  write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
306
743
  };