@hncode/hncode 0.7.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/diff.js ADDED
@@ -0,0 +1,186 @@
1
+ // Diff construction and syntax colouring for a diff body.
2
+ //
3
+ // Both halves of one job: an Edit reports what it replaced, and this module turns that into numbered rows and paints
4
+ // them. Nothing here knows about the transcript, so a caller can diff without a screen.
5
+
6
+ import { highlightLine, langForPath } from './highlight.js';
7
+
8
+ /**
9
+ * How many unchanged lines to keep either side of a change, when a diff is elided.
10
+ *
11
+ * FIVE, not three: three was too few to place a change among near-identical neighbours — several small functions, or
12
+ * two `}` a couple of rows apart, look the same inside a three-row window — and the rows just past the window are
13
+ * exactly what a reader uses to tell one site from another.
14
+ *
15
+ * Shared by both builders so a change can never be shown with one amount of surrounding context in the model's tool
16
+ * result and another on screen.
17
+ */
18
+ export const DIFF_CONTEXT_LINES = 5;
19
+
20
+ /**
21
+ * Colour one line of code, carrying block-comment state across rows.
22
+ *
23
+ * The state matters: a block comment that opens on one row and closes on the next left the second row looking like
24
+ * ordinary code, so `extends` and `const` inside a comment were coloured as keywords.
25
+ *
26
+ * @param {string} text The row.
27
+ * @param {object} lang The language entry, or null.
28
+ * @param {string} bg The background colour, or '' for none.
29
+ * @param {boolean} [inComment] Whether the previous row ended inside a block comment.
30
+ * @returns {{text: string, inComment: boolean}}
31
+ */
32
+ export function paintCode(text, lang, bg, inComment = false) {
33
+ const result = lang ? highlightLine(text, lang, inComment) : { text: String(text), inComment: false };
34
+ const raw = result.text;
35
+ if (!bg) return result;
36
+ // THE BACKGROUND GOES ON BEFORE ANY TOKEN COLOUR AND COMES BACK AFTER EVERY RESET.
37
+ //
38
+ // Prefixing only after `\x1b[0m` left the run of text BEFORE the first token uncoloured — a comment line has its
39
+ // whole body inside one token, so it drew with no wash at all while the code below it was washed, and the block
40
+ // looked striped. Seeding the background at the front covers that first run; the replacement covers every run after
41
+ // it, because each token closes with a reset that would otherwise drop back to the page background.
42
+ //
43
+ // ESC[39m, NOT ESC[0m: a bare reset clears the background too, and the row's wash must survive past the last token.
44
+ // The final glyph is still inside the coloured run, so nothing is left over to clear.
45
+ return { text: bg + raw.replace(/\x1b\[0m/g, `\x1b[0m${bg}`) + '\x1b[39m', inComment: result.inComment };
46
+ }
47
+
48
+ /**
49
+ * Align two line arrays into `same` / `del` / `add` steps (longest common subsequence).
50
+ *
51
+ * The table is O(n*m), which is right for the block an edit replaces — a handful of lines — and wrong for a whole
52
+ * file. Past the cap on either side it falls back to "everything replaced", which is exactly what the old code always
53
+ * did, so a pathological case is no worse than before and the common one is much better.
54
+ */
55
+ export function alignLines(a, b) {
56
+ const n = a.length;
57
+ const m = b.length;
58
+ const MAX = 400;
59
+ const all = () => [
60
+ ...a.map((_, i) => ({ op: 'del', a: i, b: 0 })),
61
+ ...b.map((_, j) => ({ op: 'add', a: 0, b: j })),
62
+ ];
63
+ if (n * m > MAX * MAX) return all();
64
+
65
+ // `dp[i][j]` is the LCS length of a[i..] against b[j..], filled from the bottom right.
66
+ const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
67
+ for (let i = n - 1; i >= 0; i--) {
68
+ for (let j = m - 1; j >= 0; j--) {
69
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
70
+ }
71
+ }
72
+ const steps = [];
73
+ let i = 0;
74
+ let j = 0;
75
+ while (i < n && j < m) {
76
+ if (a[i] === b[j]) { steps.push({ op: 'same', a: i, b: j }); i++; j++; }
77
+ else if (dp[i + 1][j] >= dp[i][j + 1]) { steps.push({ op: 'del', a: i, b: j }); i++; }
78
+ else { steps.push({ op: 'add', a: i, b: j }); j++; }
79
+ }
80
+ while (i < n) { steps.push({ op: 'del', a: i, b: j }); i++; }
81
+ while (j < m) { steps.push({ op: 'add', a: i, b: j }); j++; }
82
+ return steps;
83
+ }
84
+
85
+ /**
86
+ * Drop context rows further than DIFF_CONTEXT_LINES from any change, one `gap` per run.
87
+ *
88
+ * Shared by both diff builders so a change can never be shown with one amount of surrounding context in the model's
89
+ * tool result and another on screen.
90
+ */
91
+ export function elideContext(raw) {
92
+ const isChange = (k) => raw[k] && raw[k].type !== 'ctx';
93
+ const out = [];
94
+ for (let k = 0; k < raw.length; k++) {
95
+ if (raw[k].type !== 'ctx') { out.push(raw[k]); continue; }
96
+ // Distance to the NEAREST change on either side; keep when within the window.
97
+ let dist = Infinity;
98
+ for (let t = k - 1; t >= 0 && t >= k - DIFF_CONTEXT_LINES; t--) { if (isChange(t)) { dist = Math.min(dist, k - t); break; } }
99
+ for (let t = k + 1; t < raw.length && t <= k + DIFF_CONTEXT_LINES; t++) { if (isChange(t)) { dist = Math.min(dist, t - k); break; } }
100
+ if (dist <= DIFF_CONTEXT_LINES) { out.push(raw[k]); continue; }
101
+ // Elide this context row, marking the gap once.
102
+ if (out.length && out[out.length - 1].type !== 'gap') out.push({ type: 'gap' });
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /**
108
+ * Rows for an Edit, from the tool's own diff payload.
109
+ *
110
+ * The tool KNOWS what it replaced, so there is nothing to infer: the surrounding lines it reports are context, its
111
+ * `old` is what went, its `new` is what arrived. Running the spliced text through `lineDiff`'s LCS instead made it
112
+ * MIS-READ them — a context block prepended to the old text and appended to the new has a different shape on each
113
+ * side, so the LCS paired the wrong lines and rendered five unchanged context rows as `-`/`+` pairs.
114
+ *
115
+ * Rows are numbered from the real file: `before` carries its own line numbers, and the change starts at `startLine`.
116
+ */
117
+ export function editDiffRows(diff) {
118
+ if (!diff || typeof diff.old !== 'string' || typeof diff.new !== 'string') return [];
119
+ // An empty side is ZERO lines and a trailing newline is not a line: `''.split('\n')` is `['']`, which drew a
120
+ // phantom blank row, and `'a\n'` split to `['a', '']`, which drew one past the end.
121
+ const split = (s) => {
122
+ const t = String(s).replace(/\r\n/g, '\n').replace(/\n$/, '');
123
+ return t === '' ? [] : t.split('\n');
124
+ };
125
+ const ctx = diff.context || {};
126
+ const before = Array.isArray(ctx.before) ? ctx.before : [];
127
+ const after = Array.isArray(ctx.after) ? ctx.after : [];
128
+ const startLine = Number(diff.startLine) > 0 ? Number(diff.startLine) : 1;
129
+
130
+ // AN EDIT THAT CHANGED ONE LINE SHOWS ONE LINE CHANGED.
131
+ //
132
+ // Emitting every old line as `del` and every new line as `add` meant replacing three lines whose last one changed
133
+ // produced three deletions and three additions — the two identical lines scrolled past as noise and the one real
134
+ // change was buried. Aligning the two sides and emitting the unchanged pairs as CONTEXT is what a diff is.
135
+ const oldLines = split(diff.old);
136
+ const newLines = split(diff.new);
137
+
138
+ const out = [];
139
+ for (const c of before) out.push({ type: 'ctx', text: String(c.text), no: c.n });
140
+ let oldNo = startLine;
141
+ let newNo = startLine;
142
+ const steps = alignLines(oldLines, newLines);
143
+ for (let k = 0; k < steps.length; k++) {
144
+ const step = steps[k];
145
+ if (step.op === 'same') { out.push({ type: 'ctx', text: oldLines[step.a], no: newNo }); oldNo++; newNo++; continue; }
146
+ if (step.op === 'del') { out.push({ type: 'del', text: oldLines[step.a], no: oldNo++ }); continue; }
147
+ out.push({ type: 'add', text: newLines[step.b], no: newNo++ });
148
+ }
149
+ for (const c of after) out.push({ type: 'ctx', text: String(c.text), no: c.n });
150
+ // THE LANGUAGE TRAVELS WITH THE ROWS. The renderer draws a diff several layers away from the tool call, with no
151
+ // path of its own, so resolving the highlighter here — from the diff's own `path` — is the only place that still
152
+ // knows what file this is.
153
+ const lang = diff.path ? langForPath(diff.path) : null;
154
+ if (lang) for (const r of out) r.lang = lang;
155
+ return elideContext(out);
156
+ }
157
+
158
+ /**
159
+ * A diff between two whole strings, for callers that have the text rather than a tool payload.
160
+ *
161
+ * Same window rule as `editDiffRows`, from the one helper: a change must never be shown with a different amount of
162
+ * surrounding context on screen and in the model's tool result.
163
+ */
164
+ export function lineDiff(oldStr, newStr, startLine = 1) {
165
+ const a = String(oldStr == null ? '' : oldStr).replace(/\r\n/g, '\n').split('\n');
166
+ const b = String(newStr == null ? '' : newStr).replace(/\r\n/g, '\n').split('\n');
167
+ const n = a.length, m = b.length;
168
+ const dp = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
169
+ for (let i = n - 1; i >= 0; i--) {
170
+ for (let j = m - 1; j >= 0; j--) {
171
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
172
+ }
173
+ }
174
+ const raw = [];
175
+ let i = 0, j = 0;
176
+ // Line numbers as they appear in the real file (startLine = first old line).
177
+ let oldNo = startLine, newNo = startLine;
178
+ while (i < n && j < m) {
179
+ if (a[i] === b[j]) { raw.push({ type: 'ctx', text: a[i], no: oldNo }); i++; j++; oldNo++; newNo++; }
180
+ else if (dp[i + 1][j] >= dp[i][j + 1]) { raw.push({ type: 'del', text: a[i], no: oldNo }); i++; oldNo++; }
181
+ else { raw.push({ type: 'add', text: b[j], no: newNo }); j++; newNo++; }
182
+ }
183
+ while (i < n) { raw.push({ type: 'del', text: a[i], no: oldNo }); i++; oldNo++; }
184
+ while (j < m) { raw.push({ type: 'add', text: b[j], no: newNo }); j++; newNo++; }
185
+ return elideContext(raw);
186
+ }
package/src/format.js ADDED
@@ -0,0 +1,275 @@
1
+ // Number, money and time formatting for the readouts.
2
+ //
3
+ // One rule per quantity, stated once: a token count must read the same in the context gauge and in the working row, and
4
+ // a cost must never round a real amount down to `0.00`.
5
+
6
+ import { fitAnsi, visualCol } from './text.js';
7
+
8
+ export function trimDecimal(v) {
9
+ const s = v.toFixed(1);
10
+ return s.endsWith('.0') ? s.slice(0, -2) : s;
11
+ }
12
+
13
+ /**
14
+ * One unit's worth of a count: `1.2`, `97`, `262`.
15
+ *
16
+ * One decimal below 100, whole numbers at and above it. Used by every token formatter so the same quantity cannot read
17
+ * two ways on one screen.
18
+ */
19
+ export function scaleUnit(v) {
20
+ if (v < 100) return v.toFixed(1).replace(/\.0$/, '');
21
+ const r = Math.round(v);
22
+ // A value that ROUNDS to the whole number keeps its decimal: 1048576/1e6 is 1.048576, and printing `1` put it in the
23
+ // same bucket as a plain million.
24
+ if (r >= 100 && Math.abs(v - r) <= 0.5) return String(r);
25
+ return v.toFixed(1).replace(/\.0$/, '');
26
+ }
27
+
28
+ /**
29
+ * Token counts use DECIMAL units, the same ones `fmtTokensShort` uses for the working row.
30
+ *
31
+ * This was 1024-based, on the reasoning that a context size is a power of two. Two things outweighed that:
32
+ *
33
+ * * TOKENS ARE NOT BYTES. Dividing by 1024 turns 97000 tokens into "94.7k", which is simply wrong — and the context
34
+ * window is not the only figure here, since /ctx and /usage also report live counts that are not powers of two.
35
+ * * IT DISAGREED WITH ITSELF ON SCREEN. The working row divided by 1000 and this divided by 1024, so one frame showed
36
+ * "97k" for the turn and "94.7k" for the context it was using.
37
+ *
38
+ * A model's window is advertised in decimal terms anyway (200k, 128k), so nothing is lost at the size that matters.
39
+ */
40
+ export function fmtTokens(n) {
41
+ const v = Math.max(0, Math.floor(Number(n) || 0));
42
+ if (!Number.isFinite(v)) return '0';
43
+ const units = [
44
+ { at: 1e12, suffix: 'T' },
45
+ { at: 1e9, suffix: 'B' },
46
+ { at: 1e6, suffix: 'M' },
47
+ { at: 1e3, suffix: 'k' },
48
+ ];
49
+ for (let i = 0; i < units.length; i++) {
50
+ const u = units[i];
51
+ if (v < u.at) continue;
52
+ // The SAME scaling rule as `fmtTokensShort`: a tenth is information at `1.2k` and noise at `262.1k`. Sharing the
53
+ // rule is what keeps one frame from showing `262.1k` for the context and `262k` for the turn that filled it.
54
+ const shown = scaleUnit(v / u.at);
55
+ // Rounding can reach the next unit (`999999` is `1000k`, which is `1m`).
56
+ if (Number(shown) >= 1000 && i > 0) return scaleUnit(v / units[i - 1].at) + units[i - 1].suffix;
57
+ return shown + u.suffix;
58
+ }
59
+ return String(v);
60
+ }
61
+
62
+ /**
63
+ * Thousands separators for a plain count.
64
+ *
65
+ * `fmtTokens` rounds to k/M, which is right for a context gauge but wrong for a token BILL: "1.5M input tokens" hides
66
+ * whether that is 1.45M or 1.54M, and the cost readout next to it is precise.
67
+ */
68
+ export function fmtCount(n) {
69
+ const v = Number(n);
70
+ if (!Number.isFinite(v)) return '0';
71
+ return Math.round(v).toLocaleString('en-US');
72
+ }
73
+
74
+ /**
75
+ * A money amount, at a precision that stays readable across five orders of magnitude: a single cheap request is
76
+ * fractions of a cent, a long session is dollars. A bare `0.00` for a real cost is the failure to avoid, so anything
77
+ * non-zero under a cent keeps its decimals rather than rounding away. The symbol is the caller's business — the status
78
+ * row puts it AFTER the number.
79
+ */
80
+ export function moneyAmount(v, currency = 'USD') {
81
+ const n = Number(v);
82
+ if (!Number.isFinite(n)) return 'n/a';
83
+ // CNY is about 7x USD, so the same amount crosses these thresholds one step sooner; scaling the comparison keeps both
84
+ // currencies at the same precision.
85
+ const scale = currency === 'CNY' ? 7 : 1;
86
+ if (n === 0) return '0.00';
87
+ if (n * scale < 0.01) return n.toFixed(5);
88
+ if (n * scale < 1) return n.toFixed(4);
89
+ return n.toFixed(2);
90
+ }
91
+
92
+ /** `$12.34` / `¥86.51` — the amount with its symbol in front. */
93
+ export function formatCost(amount, currency = 'USD') {
94
+ const n = Number(amount);
95
+ if (!Number.isFinite(n)) return 'unknown';
96
+ return `${currency === 'CNY' ? '¥' : '$'}${moneyAmount(n, currency)}`;
97
+ }
98
+
99
+ /**
100
+ * A tiny ASCII line chart for a numeric series (context growth over steps).
101
+ *
102
+ * Renders `height` rows; each column is one sample, scaled to the series max. No dependency.
103
+ */
104
+ export function sparkChart(values, width, height) {
105
+ const series = (values || []).filter((v) => Number.isFinite(v));
106
+ if (series.length < 2) return [];
107
+ // Downsample to `width` columns by taking evenly spaced samples.
108
+ const cols = Math.min(width, series.length);
109
+ const sampled = [];
110
+ for (let i = 0; i < cols; i++) {
111
+ sampled.push(series[Math.round(i / (cols - 1) * (series.length - 1))]);
112
+ }
113
+ const max = Math.max(...sampled, 1);
114
+ const min = Math.min(...sampled, 0);
115
+ const span = Math.max(1, max - min);
116
+ const rows = [];
117
+ const BLOCK = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
118
+ // Single-row sparkline.
119
+ if (height <= 1) {
120
+ rows.push(sampled.map((v) => BLOCK[Math.min(8, Math.round((v - min) / span * 8))]).join(''));
121
+ return rows;
122
+ }
123
+ for (let r = height - 1; r >= 0; r--) {
124
+ let line = '';
125
+ for (const v of sampled) {
126
+ const level = (v - min) / span * (height - 1);
127
+ line += level >= r ? '█' : ' ';
128
+ }
129
+ rows.push(line);
130
+ }
131
+ return rows;
132
+ }
133
+
134
+ /**
135
+ * Usage as a whole-number percentage of `max`, ceiled so any non-zero usage shows at least 1%, clamped to [0, 100].
136
+ *
137
+ * `used` can be undefined on a session resumed before any usage was recorded; without the guard the division produced
138
+ * NaN and the row printed `NaN%` where it should have printed `0%`.
139
+ */
140
+ export function usagePercent(used, max) {
141
+ if (!Number.isFinite(used)) return 0;
142
+ if (!Number.isFinite(max) || max <= 0) return 0;
143
+ return Math.min(100, Math.max(0, Math.ceil((used / max) * 100)));
144
+ }
145
+
146
+ /** `1h 2m 3s` — every non-zero unit, seconds always shown. */
147
+ export function fmtDuration(ms) {
148
+ ms = Math.max(0, Math.floor(ms));
149
+ const sec = Math.floor(ms / 1000) % 60;
150
+ const min = Math.floor(ms / 60000) % 60;
151
+ const hour = Math.floor(ms / 3600000) % 24;
152
+ const day = Math.floor(ms / 86400000) % 30;
153
+ const mon = Math.floor(ms / 2592000000) % 12;
154
+ const year = Math.floor(ms / 31536000000);
155
+ const parts = [];
156
+ if (year) parts.push(year + 'y');
157
+ if (mon) parts.push(mon + 'mon');
158
+ if (day) parts.push(day + 'd');
159
+ if (hour) parts.push(hour + 'h');
160
+ if (min) parts.push(min + 'm');
161
+ // Seconds are always shown (at least "0s").
162
+ parts.push(sec + 's');
163
+ return parts.join(' ');
164
+ }
165
+
166
+ /**
167
+ * The turn's output tokens as `50k`, `1.2k`, `999`, or `0 tokens`.
168
+ *
169
+ * The rule is the one `Intl` compact notation applies, so a figure read in one tool is not read differently in the
170
+ * other:
171
+ *
172
+ * 1200 -> 1.2k one decimal while it carries information
173
+ * 9999 -> 10k compact rounds here, so the decimal falls away on its own
174
+ * 12400 -> 12.4k STILL one decimal — whole thousands would lose the 400
175
+ * 1234567 -> 1.2M and each thousand-group gets its own unit
176
+ */
177
+ export function fmtTokensShort(n) {
178
+ const v = Math.max(0, Math.floor(Number(n) || 0));
179
+ if (v < 1000) return `${v} token${v === 1 ? '' : 's'}`;
180
+ const units = [
181
+ { at: 1e12, suffix: 'T' },
182
+ { at: 1e9, suffix: 'B' },
183
+ { at: 1e6, suffix: 'M' },
184
+ { at: 1e3, suffix: 'k' },
185
+ ];
186
+ for (let i = 0; i < units.length; i++) {
187
+ const u = units[i];
188
+ if (v < u.at) continue;
189
+ const scaled = v / u.at;
190
+ // One decimal, dropped when it is a zero — the shape compact notation gives (`1k`, not `1.0k`).
191
+ const shown = scaled < 100 ? scaled.toFixed(1).replace(/\.0$/, '') : String(Math.round(scaled));
192
+ // ROUNDING CAN REACH THE NEXT UNIT. 999999 is 999.999k, which rounds to `1000k`, and `1000k` is `1m` — showing the
193
+ // first makes the reader convert a unit themselves. `units` is ordered largest-first, so `i - 1` is it.
194
+ if (Number(shown) >= 1000 && i > 0) {
195
+ const up = units[i - 1];
196
+ const upScaled = v / up.at;
197
+ const upShown = upScaled < 100 ? upScaled.toFixed(1).replace(/\.0$/, '') : String(Math.round(upScaled));
198
+ return `${upShown}${up.suffix} tokens`;
199
+ }
200
+ return `${shown}${u.suffix} tokens`;
201
+ }
202
+ return `${v} tokens`;
203
+ }
204
+
205
+ /**
206
+ * A prose setting as one short cell, for a list that has room for about forty characters.
207
+ *
208
+ * A truncated paragraph fills that space with text nobody can read and pushes the label out of line with every other
209
+ * row; the size is the fact worth showing at a glance.
210
+ */
211
+ export function proseSummary(value) {
212
+ const text = String(value == null ? '' : value);
213
+ if (!text.trim()) return '(unset)';
214
+ if (text === '(unset)') return text; // already a placeholder, not prose
215
+ const lines = text.split(/\r?\n/);
216
+ const first = lines[0].trim();
217
+ // One short line with no newline fits as-is — that IS the whole value.
218
+ if (lines.length === 1 && first.length <= 32) return first;
219
+ return `${lines.length} line${lines.length === 1 ? '' : 's'}, ${text.length} chars`;
220
+ }
221
+
222
+ /**
223
+ * The `[2s | ↓40]` tail shown at the end of the Working row, WITHOUT brackets.
224
+ *
225
+ * The brackets belong to the caller, because the two rows want them in different places: the live row wraps the TAIL,
226
+ * the settled row wraps word AND tail. Putting them here produced `[turn took [6m 44s | …]`.
227
+ *
228
+ * The token count is shown FROM THE FIRST FRAME: it used to be hidden for thirty seconds on the theory that a small
229
+ * number is noise, but the row is the only place that number exists, and a count that appears partway through reads as
230
+ * something that just started rather than as a running total.
231
+ */
232
+ export function elapsedTail(ms, tokens) {
233
+ return `${fmtDuration(ms)} | ↓ ${fmtTokensShort(tokens)}`;
234
+ }
235
+
236
+ /**
237
+ * Has the turn gone quiet, and how much should that show?
238
+ *
239
+ * A turn that produces no tokens for a few seconds is either thinking, waiting on a tool, or stuck — and from outside
240
+ * those look identical. The one case that matters is the last: a request that hangs leaves the row spinning forever
241
+ * with no way to tell it apart from a long answer.
242
+ *
243
+ * Returns 0 while healthy and 1 at full stall, so the caller can interpolate rather than switch abruptly. NEVER
244
+ * reports a stall while a tool is running — a long install is working, not stalled, and flashing at it would train the
245
+ * user to ignore the signal.
246
+ */
247
+ export const STALL_AFTER_MS = 3000;
248
+ export const STALL_FADE_MS = 2000;
249
+
250
+ export function stallIntensity({ sinceLastTokenMs, hasActiveTools }) {
251
+ if (hasActiveTools) return 0;
252
+ const quiet = Number(sinceLastTokenMs) || 0;
253
+ if (quiet <= STALL_AFTER_MS) return 0;
254
+ return Math.min((quiet - STALL_AFTER_MS) / STALL_FADE_MS, 1);
255
+ }
256
+
257
+ /**
258
+ * Left/right justify: left text, then padding, then right text flush to `w`.
259
+ *
260
+ * ANSI codes are ignored for width so coloured segments still align exactly. When both do not fit, the LEFT is preserved
261
+ * and the RIGHT is truncated — the left is what the user is reading.
262
+ */
263
+ export function justify(left, right, w) {
264
+ const lw = visualCol(left);
265
+ const rw = visualCol(right);
266
+ if (left && right) {
267
+ if (lw + rw + 1 <= w) return left + ' '.repeat(w - lw - rw) + right;
268
+ const room = w - lw - 1;
269
+ if (room > 0) return left + ' ' + fitAnsi(right, room);
270
+ return fitAnsi(left, w);
271
+ }
272
+ if (!left) return ' '.repeat(Math.max(0, w - rw)) + right;
273
+ if (!right) return left + ' '.repeat(Math.max(0, w - lw));
274
+ return fitAnsi(left, w);
275
+ }