@litfamily/litmuse 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ // The opt-in icon font of `install --round`: the symbols-only Nerd Font, which holds the round ends (U+E0B6, U+E0B4).
2
+ // It comes from one pinned release archive, and archive and files must match their SHA-256. A file that is already there
3
+ // is never replaced, and icon-font.json in LitMuse's data folder lists what LitMuse added, so uninstall removes only that.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
6
+ import { linkSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { inflateRawSync } from 'node:zlib';
9
+ import { forgetIconFont, iconFontInstalled } from './glyphs.mjs';
10
+ import { FONT_FILES, assertFontPath, assertSafeWritePath, fontFolder, fontFolderProblem } from './guard.mjs';
11
+ import { paths } from './paths.mjs';
12
+ import { realExistingAncestor, writeFileAtomic } from './safe-write.mjs';
13
+
14
+ const MIB = 1024 * 1024;
15
+ export const ICON_FONT = Object.freeze({
16
+ release: 'v3.5.1',
17
+ url: 'https://github.com/ryanoasis/nerd-fonts/releases/download/v3.5.1/NerdFontsSymbolsOnly.zip',
18
+ sha256: 'fdca3682534f6f65e1ccb2345b0362ccf67d9b8eca7c8025330946e93e2473bc',
19
+ maxBytes: 8 * MIB,
20
+ files: Object.freeze([
21
+ Object.freeze({ entry: 'SymbolsNerdFontMono-Regular.ttf', name: FONT_FILES.font, sha256: 'fe471e538392f51910faab985fa8e192a39dd3426125edd15b71b3680df0e749' }),
22
+ Object.freeze({ entry: 'LICENSE', name: FONT_FILES.license, sha256: '84a7a98c82140fb12c37fe42b93805baa16024cb3e5acc599b7ffe612c55d847' }),
23
+ ]),
24
+ });
25
+ const DOWNLOAD_MS = 60_000;
26
+
27
+ const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
28
+ const lstatOrNull = (path) => {
29
+ try {
30
+ return lstatSync(path);
31
+ } catch {
32
+ return null;
33
+ }
34
+ };
35
+ // absent, same (a regular file with exactly these bytes) or other.
36
+ const stateOf = (path, hash) => {
37
+ const st = lstatOrNull(path);
38
+ if (!st) return 'absent';
39
+ return st.isFile() && sha256(readFileSync(path)) === hash ? 'same' : 'other';
40
+ };
41
+
42
+ /** Bytes of the named entries of a zip held in memory; a missing name is left out. */
43
+ export function unzip(zip, names) {
44
+ const out = new Map();
45
+ let end = zip.length - 22;
46
+ while (end >= 0 && zip.readUInt32LE(end) !== 0x06054b50) end -= 1;
47
+ if (end < 0) throw new Error('the archive is not a zip file');
48
+ let at = zip.readUInt32LE(end + 16);
49
+ for (let left = zip.readUInt16LE(end + 10); left > 0; left -= 1) {
50
+ const [nameSize, extraSize, noteSize] = [28, 30, 32].map((offset) => zip.readUInt16LE(at + offset));
51
+ const name = zip.toString('utf8', at + 46, at + 46 + nameSize);
52
+ if (names.includes(name)) {
53
+ const local = zip.readUInt32LE(at + 42);
54
+ const from = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
55
+ const data = zip.subarray(from, from + zip.readUInt32LE(at + 20));
56
+ const method = zip.readUInt16LE(at + 10);
57
+ if (method !== 0 && method !== 8) throw new Error(`the archive packs ${name} in a way LitMuse does not read`);
58
+ out.set(name, method === 0 ? Buffer.from(data) : inflateRawSync(data, { maxOutputLength: 4 * ICON_FONT.maxBytes }));
59
+ }
60
+ at += 46 + nameSize + extraSize + noteSize;
61
+ }
62
+ return out;
63
+ }
64
+
65
+ async function download(pins, fetchImpl) {
66
+ const res = await fetchImpl(pins.url, { redirect: 'follow', signal: AbortSignal.timeout(DOWNLOAD_MS) });
67
+ if (!res.ok) throw new Error(`the download answered HTTP ${res.status}`);
68
+ const chunks = [];
69
+ let size = 0;
70
+ for await (const chunk of res.body) {
71
+ size += chunk.length;
72
+ if (size > pins.maxBytes) throw new Error('the download is larger than 8 MiB');
73
+ chunks.push(chunk);
74
+ }
75
+ return Buffer.concat(chunks);
76
+ }
77
+
78
+ /** The pinned archive: the file LITMUSE_ICON_FONT_SOURCE names (tests, offline), else the download. */
79
+ async function archiveBytes({ env, pins, fetchImpl }) {
80
+ const local = env.LITMUSE_ICON_FONT_SOURCE;
81
+ let bytes;
82
+ if (local) {
83
+ const st = lstatSync(local);
84
+ if (!st.isFile() || st.size > pins.maxBytes) throw new Error(`${local} is not a regular file of at most 8 MiB`);
85
+ bytes = readFileSync(local);
86
+ } else bytes = await download(pins, fetchImpl);
87
+ if (sha256(bytes) !== pins.sha256) throw new Error('the archive does not match its pinned SHA-256');
88
+ return bytes;
89
+ }
90
+
91
+ const readManifest = (file) => {
92
+ try {
93
+ const { files } = lstatSync(file).isFile() ? JSON.parse(readFileSync(file, 'utf8')) : {};
94
+ return Array.isArray(files) ? files.filter((f) => typeof f?.path === 'string' && typeof f?.sha256 === 'string') : [];
95
+ } catch {
96
+ return [];
97
+ }
98
+ };
99
+
100
+ // Why the folder or the font's own place in it cannot take the file, or null. Nothing is written or fetched before this.
101
+ function blocked(target, where) {
102
+ const problem = fontFolderProblem(where);
103
+ if (problem) return problem;
104
+ assertSafeWritePath(realExistingAncestor(dirname(target)));
105
+ return lstatOrNull(target) ? `something else is already at ${target}` : null;
106
+ }
107
+
108
+ // The bytes go to a temporary file in LitMuse's own folder; the hard link that claims the name fails when anything is
109
+ // there already. Returns false in that case.
110
+ function claim(target, bytes, data, write) {
111
+ mkdirSync(data, { recursive: true });
112
+ const staged = join(data, `.icon-font-${process.pid}`);
113
+ try {
114
+ write(staged, bytes, { flag: 'wx', mode: 0o644 });
115
+ try {
116
+ linkSync(staged, target);
117
+ } catch (e) {
118
+ if (e.code === 'EEXIST') return false;
119
+ throw e.code === 'EXDEV' ? new Error(`${dirname(target)} and ${data} are on different disks`) : e;
120
+ }
121
+ return true;
122
+ } finally {
123
+ rmSync(staged, { force: true });
124
+ }
125
+ }
126
+
127
+ /** What `--round` would do, for the plan and the dry run. */
128
+ export function iconFontPlan({ env = process.env, platform = process.platform, hasFont = () => iconFontInstalled({ env, platform }) } = {}) {
129
+ if (hasFont()) return 'an icon font is already here; nothing is added';
130
+ const dir = fontFolder({ env, platform });
131
+ if (!dir) return 'no font is installed on Windows (Windows Terminal and VS Code draw the round ends)';
132
+ return `add ${FONT_FILES.font} and its licence (${FONT_FILES.license}) to ${dir}, ${env.LITMUSE_ICON_FONT_SOURCE ? `from ${env.LITMUSE_ICON_FONT_SOURCE}` : `downloaded from ${ICON_FONT.url}`}`;
133
+ }
134
+
135
+ /**
136
+ * Adds the icon font when none is here. Returns `{status, why?, written}` with status here, added, unsupported or failed;
137
+ * it never throws, because an install succeeds with square ends too.
138
+ */
139
+ export async function addIconFont({
140
+ env = process.env, platform = process.platform, pins = ICON_FONT, fetchImpl = globalThis.fetch, spawn = spawnSync, write = writeFileSync,
141
+ hasFont = () => iconFontInstalled({ env, platform }),
142
+ } = {}) {
143
+ const linked = [];
144
+ try {
145
+ if (hasFont()) return { status: 'here', written: [] };
146
+ const p = paths(env);
147
+ const dir = fontFolder({ env, platform });
148
+ if (!dir) return { status: 'unsupported', why: 'LitMuse installs no font on Windows', written: [] };
149
+ const why = blocked(join(dir, FONT_FILES.font), { env, platform });
150
+ if (why) return { status: 'failed', why, written: [] };
151
+ const entries = unzip(await archiveBytes({ env, pins, fetchImpl }), pins.files.map((f) => f.entry));
152
+ for (const f of pins.files) {
153
+ const bytes = entries.get(f.entry);
154
+ if (!bytes || sha256(bytes) !== f.sha256) throw new Error(`${f.entry} in the archive does not match its pinned SHA-256`);
155
+ }
156
+ mkdirSync(dir, { recursive: true });
157
+ const late = blocked(join(dir, FONT_FILES.font), { env, platform });
158
+ if (late) throw new Error(late);
159
+ for (const f of pins.files) {
160
+ const path = assertFontPath(join(dir, f.name), { env, platform });
161
+ if (claim(path, entries.get(f.entry), p.data, write)) linked.push({ path, sha256: f.sha256 });
162
+ else if (f.name === FONT_FILES.font) throw new Error(`something else is already at ${path}`);
163
+ }
164
+ const kept = readManifest(p.iconFont).filter((f) => !linked.some((l) => l.path === f.path) && stateOf(f.path, f.sha256) === 'same');
165
+ writeFileAtomic(p.iconFont, `${JSON.stringify({ release: pins.release, files: [...kept, ...linked] }, null, 2)}\n`);
166
+ if (platform !== 'darwin') spawn('fc-cache', ['-f', dir], { stdio: 'ignore', timeout: DOWNLOAD_MS });
167
+ return { status: 'added', written: [...linked.map((f) => f.path), p.iconFont] };
168
+ } catch (e) {
169
+ for (const f of linked) rmSync(f.path, { force: true });
170
+ return { status: 'failed', why: e.name === 'TimeoutError' ? 'the download took longer than 60 seconds' : e.code ? `${e.code}${e.path ? ` ${e.path}` : ''}` : e.message, written: [] };
171
+ } finally {
172
+ forgetIconFont();
173
+ }
174
+ }
175
+
176
+ /** The files LitMuse added that are still exactly as written (`remove`), and those that changed since (`keep`). */
177
+ export function ownedIconFont({ env = process.env, platform = process.platform } = {}) {
178
+ const out = { remove: [], keep: [] };
179
+ const linked = fontFolderProblem({ env, platform });
180
+ for (const f of readManifest(paths(env).iconFont)) {
181
+ let state = 'other';
182
+ try {
183
+ const found = stateOf(assertFontPath(f.path, { env, platform }), f.sha256);
184
+ state = linked && found === 'same' ? 'other' : found;
185
+ } catch { /* not a path LitMuse writes: left alone */ }
186
+ if (state !== 'absent') out[state === 'same' ? 'remove' : 'keep'].push(f.path);
187
+ }
188
+ return out;
189
+ }
190
+
191
+ export function removeIconFont({ env = process.env, platform = process.platform } = {}) {
192
+ const owned = ownedIconFont({ env, platform });
193
+ for (const path of owned.remove) rmSync(path, { force: true });
194
+ const list = assertSafeWritePath(paths(env).iconFont);
195
+ if (lstatOrNull(list)?.isFile()) rmSync(list);
196
+ forgetIconFont();
197
+ return owned;
198
+ }
@@ -0,0 +1,406 @@
1
+ // The cards a person at a terminal sees during `litmuse install` and `litmuse uninstall`: the mark, the questions, the
2
+ // work, one row per answer, and the closing panel. Every value starts in column 24, and one blank row parts two blocks. cardsFor() returns null for everything else (a pipe, CI, --yes, --dry-run,
3
+ // TERM=dumb, a small window, LITMUSE_AGENT_FILE), and then install and uninstall print their plain lines.
4
+ import { emitKeypressEvents } from 'node:readline';
5
+ import { CAP_LEFT, CAP_RIGHT, roundGlyphs } from './glyphs.mjs';
6
+ import { SIZES, colourDepth, markRows, sample } from './mark.mjs';
7
+ import { displayWidth } from '../plugin/lib/rewind/gauge.mjs';
8
+
9
+ const MIN_COLS = 40;
10
+ const MIN_ROWS = 12;
11
+ const MAX_CARD = 100;
12
+ const FOLD = 20;
13
+ const LABEL = 19;
14
+ const STEP = 19;
15
+ const BUTTON = 15;
16
+ // Keys already typed when a card appears are dropped, and so is the Enter that follows a y or n out of habit.
17
+ const SETTLE_MS = 30;
18
+ const HABIT_MS = 400;
19
+
20
+ const ESC = '\u001b';
21
+ const PINK = '#ff2d95';
22
+ const VIOLET = '#b48cff';
23
+ const CYAN = '#8be9fd';
24
+ const ORANGE = '#ff8f3c';
25
+ const GREEN = '#50e68c';
26
+ const AMBER = '#ffb02e';
27
+ const RED = '#ff5577';
28
+ const INK = '#0b0e14';
29
+ const BASIC = { [PINK]: 95, [VIOLET]: 94, [CYAN]: 96, [ORANGE]: 93, [GREEN]: 92, [AMBER]: 93, [RED]: 91, [INK]: 30 };
30
+
31
+ const DRAWN = {
32
+ box: ['╭', '╮', '╰', '╯', '─', '│'], chosen: ['╔', '╗', '╚', '╝', '═', '║'], done: '✓', fail: '✗', warn: '!', note: '·', busy: '⠙', pointer: '❯', arrows: '← →',
33
+ };
34
+ const TYPED = {
35
+ box: ['+', '+', '+', '+', '-', '|'], chosen: ['#', '#', '#', '#', '=', '#'], done: 'ok', fail: 'x', warn: '!', note: '-', busy: '*', pointer: '>', arrows: 'Left Right',
36
+ };
37
+ const TYPED_FOR = { '·': '-', '—': '-', '→': '->', '…': '...' };
38
+
39
+ const bare = (text) => text.replace(/\u001b\[[0-9;]*m/g, '');
40
+ const cells = (text) => displayWidth(bare(text));
41
+ const pad = (text, width) => text + ' '.repeat(Math.max(0, width - cells(text)));
42
+
43
+ // Wraps at spaces, keeping a line's own indent. A longer word (a path) continues on the next line; nothing is dropped.
44
+ export function wrap(text, width) {
45
+ const indent = /^ */.exec(text)[0];
46
+ const lines = [indent];
47
+ for (const word of text.trim().split(/ +/)) {
48
+ const last = lines.length - 1;
49
+ const empty = lines[last].trim() === '';
50
+ if (cells(lines[last]) + (empty ? 0 : 1) + cells(word) <= width) {
51
+ lines[last] += empty ? word : ` ${word}`;
52
+ continue;
53
+ }
54
+ if (!empty) lines.push(indent);
55
+ for (const ch of word) {
56
+ if (cells(lines.at(-1) + ch) > width) lines.push(indent);
57
+ lines[lines.length - 1] += ch;
58
+ }
59
+ }
60
+ return lines;
61
+ }
62
+
63
+ const cubeLevel = (v) => (v < 48 ? 0 : v < 115 ? 1 : Math.floor((v - 35) / 40));
64
+
65
+ function painter(depth) {
66
+ const code = (hex, back, basic) => {
67
+ if (depth === '16') return String(basic + (back ? 10 : 0));
68
+ const [r, g, b] = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
69
+ const value = depth === 'truecolor' ? `2;${r};${g};${b}` : `5;${16 + 36 * cubeLevel(r) + 6 * cubeLevel(g) + cubeLevel(b)}`;
70
+ return `${back ? 48 : 38};${value}`;
71
+ };
72
+ const paint = (text, { fg, bg, bold, dim, basic }) => {
73
+ if (depth === 'none' || !text) return text;
74
+ const codes = [bold && 1, dim && 2, fg && code(fg, false, BASIC[fg] ?? basic), bg && code(bg, true, BASIC[bg] ?? basic)].filter(Boolean);
75
+ return `${ESC}[${codes.join(';')}m${text}${ESC}[0m`;
76
+ };
77
+ // `text` along `stops`; `at` and `of` say where it lies on a longer run, so a border cut by its title stays one ramp.
78
+ const ramp = (text, stops, { onto = 'fg', at = 0, of = [...text].length, bold = false } = {}) => {
79
+ if (depth === 'none') return text;
80
+ const parts = [];
81
+ [...text].forEach((ch, i) => {
82
+ const step = Math.round(((at + i) / Math.max(1, of - 1)) * 20) / 20;
83
+ if (parts.at(-1)?.step === step) parts.at(-1).text += ch;
84
+ else parts.push({ step, text: ch });
85
+ });
86
+ return parts.map((p) => paint(p.text, {
87
+ [onto]: sample(stops, p.step), basic: BASIC[stops[Math.round(p.step * (stops.length - 1))]], bold, ...(onto === 'bg' ? { fg: INK } : {}),
88
+ })).join('');
89
+ };
90
+ return { paint, ramp };
91
+ }
92
+
93
+ // NO_COLOR keeps the cards without colour; a terminal below 256 colours gets the sixteen basic ones.
94
+ function depthOf(env, stdout) {
95
+ if (env.NO_COLOR) return 'none';
96
+ const depth = colourDepth({ env, isTTY: stdout.isTTY });
97
+ return depth === 'none' ? '16' : depth;
98
+ }
99
+
100
+ const typedLocale = (env) => {
101
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || '';
102
+ return locale !== '' && !/utf-?8/i.test(locale);
103
+ };
104
+
105
+ /** Panel rows for `[label, value]` pairs of what is about to happen. */
106
+ export const planRows = (pairs) => pairs.map(([label, value]) => ({ mark: 'note', label, value }));
107
+
108
+ const lightTerminal = (env) => /;(7|15)$/.test(env.COLORFGBG ?? '');
109
+
110
+ /** The cards for this terminal, or null when the plain lines should be printed. */
111
+ export function cardsFor({ env = process.env, flags = {}, stdin = process.stdin, stdout = process.stdout, ...rest } = {}) {
112
+ const person = stdin.isTTY && stdout.isTTY && typeof stdin.setRawMode === 'function' && !env.CI && !/^dumb$/i.test(env.TERM ?? '');
113
+ if (!person || flags.yes || flags.dryRun || env.LITMUSE_AGENT_FILE) return null;
114
+ if ((stdout.columns || 80) < MIN_COLS || (stdout.rows || 24) < MIN_ROWS) return null;
115
+ return createCards({ env, stdin, stdout, ...rest });
116
+ }
117
+
118
+ export function createCards({ env, stdin, stdout, proc = process, now = Date.now, settleMs = SETTLE_MS }) {
119
+ const depth = depthOf(env, stdout);
120
+ const typed = typedLocale(env);
121
+ // Decided once, so a run never mixes round and square.
122
+ const round = depth === 'truecolor' && !typed && !lightTerminal(env) && roundGlyphs(env);
123
+ const sign = typed ? TYPED : DRAWN;
124
+ const { paint, ramp } = painter(depth);
125
+ const cols = () => stdout.columns || 80;
126
+ const rows = () => stdout.rows || 24;
127
+ const width = () => Math.min(MAX_CARD, cols() - 2);
128
+ const inner = () => width() - 4;
129
+ const say = (text) => (typed ? String(text).replace(/[·—→…]/g, (ch) => TYPED_FOR[ch]) : String(text));
130
+ const bold = (text) => paint(text, { bold: true });
131
+ const dim = (text) => paint(text, { dim: true });
132
+ let letterAt = -Infinity;
133
+ // Folded rows stand together; any other two blocks have one blank row between them.
134
+ let last = null;
135
+ const apart = (kind) => {
136
+ const blank = last !== null && !(last === 'fold' && kind === 'fold') ? '\n' : '';
137
+ last = kind;
138
+ return blank;
139
+ };
140
+ const home = env.HOME && env.HOME !== '/' ? `${env.HOME.replace(/[\\/]$/, '')}` : null;
141
+ /** Paths under the home folder start with `~`. */
142
+ const short = (value) => (home ? String(value).replaceAll(`${home}/`, '~/').replaceAll(`${home}\\`, '~\\') : String(value));
143
+
144
+ // Text on a gradient fill, one cell wider on each side: a round cap, or a cell of the fill.
145
+ const filled = (text, stops) => {
146
+ const size = cells(text) + 2;
147
+ if (!round) return ramp(` ${text} `, stops, { onto: 'bg', bold: true });
148
+ return paint(CAP_LEFT, { fg: stops[0] }) + ramp(text, stops, { onto: 'bg', bold: true, at: 1, of: size }) + paint(CAP_RIGHT, { fg: stops.at(-1) });
149
+ };
150
+
151
+ const frame = ({ tag = 'LIT', title, body, bad }) => {
152
+ const w = width();
153
+ const [tl, tr, bl, br, h, v] = sign.box;
154
+ const edge = (text, at) => ramp(text, bad ? [RED, RED] : [PINK, VIOLET, CYAN], { at, of: w });
155
+ const pill = depth === 'none' ? `[${tag}]` : filled(tag, [ORANGE, PINK]);
156
+ const name = say(title);
157
+ const fits = cells(pill) + cells(name) + 9 <= w;
158
+ const head = ` ${pill} ${fits ? `${dim(say('·'))} ${bold(name)} ` : ''}`;
159
+ const used = 2 + cells(head);
160
+ const inside = fits ? body : [...wrap(name, w - 4).map(bold), ...body];
161
+ return [
162
+ ` ${edge(tl + h, 0)}${head}${edge(h.repeat(w - used - 1) + tr, used)}`,
163
+ ...inside.map((row) => ` ${edge(v, 0)} ${pad(row, w - 4)} ${edge(v, w - 1)}`),
164
+ ` ${edge(bl + h.repeat(w - 2) + br, 0)}`,
165
+ ];
166
+ };
167
+
168
+ const marked = (mark) => paint(sign[mark], { fg: { done: GREEN, fail: RED, warn: AMBER, note: VIOLET, busy: PINK }[mark], bold: true });
169
+
170
+ // A folded row's value starts in column 24; a long label, or a narrow window, puts it after one space.
171
+ const rowLines = (mark, label, value) => {
172
+ const lead = ` ${marked(mark)} `;
173
+ const name = say(label);
174
+ const room = cols() - 1;
175
+ const wide = pad(lead + name, 3 + FOLD + 1);
176
+ const start = cells(wide) + cells(say(value)) <= room || room - cells(wide) >= 24 ? wide : `${lead}${name} `;
177
+ return wrap(say(value), Math.max(12, room - cells(start))).map((line, i) => (i ? ' '.repeat(cells(start)) : start) + bold(line));
178
+ };
179
+
180
+ /** One folded answer or step. */
181
+ const row = (mark, label, value) => { stdout.write(`${apart('fold')}${rowLines(mark, label, value).join('\n')}\n`); };
182
+
183
+ /** The LIT mark centred over the cards, as large as the window allows, then one dim line about the run. */
184
+ const intro = (line) => {
185
+ const most = rows() >= 48 ? 0 : rows() >= 34 ? 1 : 2;
186
+ const size = SIZES.slice(most).find(([, min]) => width() >= min);
187
+ const art = markRows({ cols: cols(), depth: colourDepth({ env, isTTY: true }), size: size?.[0] });
188
+ const indent = ' '.repeat(Math.max(0, 1 + Math.floor((width() - Math.max(...art.map(cells))) / 2)));
189
+ stdout.write(`\n${art.map((r) => indent + r).join('\n')}\n\n${wrap(say(short(line)), width()).map((l) => ` ${dim(l)}`).join('\n')}\n`);
190
+ last = 'text';
191
+ };
192
+
193
+ const textLines = (heading, lines) => [
194
+ ...wrap(say(heading), width()).map((l) => ` ${bold(l)}`),
195
+ ...lines.flatMap((line) => (/^ {4}/.test(line) ? [` ${line}`] : wrap(say(line), width() - 2).map((l) => ` ${l}`))),
196
+ ];
197
+ /** Wrapped text under a heading. A command (four spaces in) stays on one line, so it can be copied. */
198
+ const text = (heading, lines) => { stdout.write(`${apart('text')}${textLines(heading, lines).join('\n')}\n`); };
199
+
200
+ /** One line that is never wrapped, so it can be found and copied whole. */
201
+ const line = (words) => { stdout.write(`${apart('text')} ${bold(say(words))}\n`); };
202
+
203
+ /** A finished card: sections of { head, rows: [{ mark, label, value }] }. Values wrap and are never cut. The first of `hints` that fits takes the empty top row. */
204
+ const panel = ({ title, sections, bad = false, hints: lines = [] }) => {
205
+ const markCells = 2;
206
+ const labelCells = inner() < 56 ? 0 : LABEL;
207
+ const body = sections.flatMap(({ head, rows: list }) => [
208
+ '',
209
+ ...(head ? [paint(head, { fg: bad ? RED : PINK, bold: true })] : []),
210
+ ...list.flatMap(({ mark = 'done', label = '', value }) => {
211
+ const lead = pad(marked(mark), Math.max(markCells, cells(marked(mark)) + 1));
212
+ const loud = mark === 'warn' || mark === 'fail' ? bold : (line) => line;
213
+ const name = say(label);
214
+ if (label && !labelCells) return [...wrap(name, inner() - markCells).map((line, i) => (i ? ' '.repeat(markCells) : lead) + bold(line)), ...wrap(say(short(value)), inner() - markCells).map((line) => ' '.repeat(markCells) + loud(line))];
215
+ const named = label ? lead + bold(name) : lead;
216
+ const start = !label ? lead : cells(named) < markCells + labelCells ? pad(named, markCells + labelCells) : `${named} `;
217
+ return wrap(say(short(value)), inner() - cells(start)).map((line, i) => (i ? ' '.repeat(cells(start)) : start) + loud(line));
218
+ }),
219
+ ]);
220
+ const hint = lines.find((line) => cells(line) <= inner());
221
+ if (hint) body[0] = dim(say(hint));
222
+ stdout.write(`${apart('card')}${frame({ title, body, bad }).join('\n')}\n`);
223
+ };
224
+
225
+ /**
226
+ * The work card: `steps` are [name, what it does]. next() starts a step, done() folds the card to one row, and fail()
227
+ * leaves it on screen with the running step marked.
228
+ */
229
+ const work = (title, label, steps) => {
230
+ let at = -1;
231
+ let shown = 0;
232
+ const joins = last === 'fold';
233
+ const draw = (stopped = false) => {
234
+ const list = steps.map(([name, what], i) => {
235
+ const mark = i < at ? 'done' : i > at ? 'note' : stopped ? 'fail' : 'busy';
236
+ const lead = `${pad(marked(mark), 2)}${mark === 'done' || mark === 'note' ? name : bold(name)}`;
237
+ const start = pad(lead, 2 + (inner() < 56 ? Math.max(...steps.map(([n]) => cells(n))) + 2 : STEP));
238
+ return cells(start) + cells(what) <= inner() ? start + (mark === 'note' || mark === 'done' ? dim(say(what)) : say(what)) : lead;
239
+ });
240
+ const lines = frame({ title, body: ['', ...list] });
241
+ const lead = shown ? `${ESC}[${shown}A\r` : apart('card');
242
+ shown = lines.length;
243
+ stdout.write(`${lead}${lines.map((line) => `${line}${ESC}[K`).join('\n')}\n`);
244
+ };
245
+ return {
246
+ next: () => {
247
+ at += 1;
248
+ draw();
249
+ },
250
+ fail: () => draw(true),
251
+ done: () => {
252
+ // The blank row over the card goes too when the row joins others.
253
+ stdout.write(`${ESC}[${shown + (joins ? 1 : 0)}A\r${ESC}[J${rowLines('done', label, `${steps.length} of ${steps.length} checked`).join('\n')}\n`);
254
+ last = 'fold';
255
+ },
256
+ };
257
+ };
258
+
259
+ const buttons = (yes, defaultYes, small) => {
260
+ const ending = inner() >= 44 ? ' (default)' : ' default';
261
+ const size = inner() >= 44 ? BUTTON : BUTTON - 2;
262
+ const drawn = [true, false].map((value) => {
263
+ const on = value === yes;
264
+ const label = pad(`${on ? sign.pointer : ' '} ${value ? 'Yes' : 'No'}${value === defaultYes ? ending : ''}`, size);
265
+ const plain = depth === 'none' || typed;
266
+ if (small) return [on ? (depth === 'none' ? `[${label}]` : filled(label, [PINK, VIOLET])) : dim(` ${label} `)];
267
+ const [tl, tr, bl, br, h, v] = on && plain ? sign.chosen : sign.box;
268
+ const wide = size + 6;
269
+ const line = (chars, at) => (on ? ramp(chars, [PINK, VIOLET], { at, of: wide, bold: plain }) : dim(chars));
270
+ const face = !on ? ` ${label} ` : plain ? ` ${bold(label)} ` : filled(label, [PINK, VIOLET]);
271
+ return [line(tl + h.repeat(wide - 2) + tr, 0), `${line(v, 0)} ${face} ${line(v, wide - 1)}`, line(bl + h.repeat(wide - 2) + br, 0)];
272
+ });
273
+ return drawn[0].map((left, i) => `${left} ${drawn[1][i]}`);
274
+ };
275
+
276
+ const hints = (list) => list.reduce((lines, hint) => {
277
+ const joined = lines.length ? `${lines.at(-1)} ${hint}` : hint;
278
+ return lines.length && cells(joined) > inner() ? [...lines, hint] : [...lines.slice(0, -1), joined];
279
+ }, []).map(dim);
280
+
281
+ // Roomy when the window allows, then tighter; the note and both buttons always stay.
282
+ const question = ({ tag, title, note, list }, defaultYes, yes) => {
283
+ const noteLines = wrap(say(note), inner());
284
+ const enter = `Enter = ${yes ? 'Yes' : 'No'}`;
285
+ const see = list ? [list.hint] : [];
286
+ const keys = hints(['y / n answer', `${sign.arrows} switch`, enter, ...see, 'Ctrl+C stop']);
287
+ const small = buttons(yes, defaultYes, true);
288
+ const big = buttons(yes, defaultYes, false);
289
+ const pair = cells(big[0]) <= inner() ? big : small;
290
+ const heading = `${title} ${defaultYes ? '[Y/n]' : '[y/N]'}`;
291
+ const drawn = [
292
+ ['', ...noteLines, '', ...pair, '', ...keys],
293
+ [...noteLines, '', ...pair, '', ...keys],
294
+ [...noteLines, ...small, ...keys],
295
+ [...noteLines, ...small, ...hints(['y / n', enter, ...see, 'Ctrl+C stop'])],
296
+ ].map((body, i) => [...(i < 2 ? [''] : []), ...frame({ tag, title: heading, body })]);
297
+ return drawn.find((list) => list.length < rows()) ?? drawn.at(-1).slice(-(rows() - 1));
298
+ };
299
+
300
+ /** Asks with a card: `card` is { tag, title, note, yes, no, list? }; `list` is { hint, heading, lines }, printed above
301
+ * the card when the person types l. Ctrl+C and Ctrl+D throw, as they do at the plain prompt. */
302
+ const ask = async (_plain, { defaultYes = false, card }) => {
303
+ let yes = defaultYes;
304
+ let shown = [];
305
+ let held = false;
306
+ const lift = (count) => (count ? `${ESC}[${count}A` : '');
307
+ const draw = (over = shown.length) => {
308
+ shown = question(card, defaultYes, yes);
309
+ stdout.write(`${lift(over)}\r${shown.map((line) => `${line}${ESC}[K\r\n`).join('')}${ESC}[J`);
310
+ };
311
+ const wipe = () => `${lift(shown.length)}\r${ESC}[J`;
312
+ const fold = (mark, value) => stdout.write(`${wipe()}${apart('fold')}${rowLines(mark, card.title, value).join('\n')}\n`);
313
+ const showList = () => {
314
+ stdout.write(`${wipe()}${apart('text')}${textLines(card.list.heading, card.list.lines).join('\n')}\n`);
315
+ draw(0);
316
+ };
317
+ const take = () => {
318
+ held = true;
319
+ stdin.setRawMode(true);
320
+ stdin.resume();
321
+ stdout.write(`${ESC}[?25l`);
322
+ };
323
+ const give = () => {
324
+ if (!held) return;
325
+ held = false;
326
+ stdout.write(`${ESC}[?25h`);
327
+ stdin.setRawMode(false);
328
+ stdin.pause();
329
+ };
330
+ const undo = [];
331
+ const on = (source, event, fn) => {
332
+ source.on(event, fn);
333
+ undo.push(() => source.removeListener(event, fn));
334
+ };
335
+ const release = () => {
336
+ give();
337
+ for (const fn of undo.splice(0)) fn();
338
+ };
339
+
340
+ take();
341
+ on(proc, 'exit', give);
342
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
343
+ on(proc, signal, () => {
344
+ release();
345
+ proc.kill(proc.pid, signal);
346
+ });
347
+ }
348
+ try {
349
+ const answer = await new Promise((resolve, reject) => {
350
+ let ready = false;
351
+ let settling;
352
+ const stop = (reason) => {
353
+ clearTimeout(settling);
354
+ reject(new Error(reason));
355
+ };
356
+ const suspend = () => {
357
+ stdout.write(`${ESC}[?25h`);
358
+ stdin.setRawMode(false);
359
+ proc.once('SIGCONT', () => {
360
+ if (!held) return;
361
+ stdin.setRawMode(true);
362
+ stdout.write(`${ESC}[?25l`);
363
+ draw(0);
364
+ });
365
+ proc.kill(0, 'SIGTSTP');
366
+ };
367
+ emitKeypressEvents(stdin);
368
+ on(stdin, 'keypress', (ch, key = {}) => {
369
+ if (key.ctrl && key.name === 'c') stop('Aborted with Ctrl+C');
370
+ else if (!ready || key.meta || key.name === 'escape') return;
371
+ else if (key.ctrl && key.name === 'd') stop('Aborted with Ctrl+D');
372
+ else if (key.ctrl && key.name === 'z' && proc.platform !== 'win32') suspend();
373
+ else if (key.ctrl) return;
374
+ else if (key.name === 'return' || key.name === 'enter') {
375
+ if (now() - letterAt >= HABIT_MS) resolve(yes);
376
+ } else if (/^[yn]$/i.test(ch ?? '')) {
377
+ letterAt = now();
378
+ resolve(/y/i.test(ch));
379
+ } else if (card.list && /^l$/i.test(ch ?? '')) showList();
380
+ else if (['left', 'right', 'tab'].includes(key.name)) {
381
+ yes = !yes;
382
+ draw();
383
+ }
384
+ });
385
+ on(stdin, 'end', () => stop('Aborted: the terminal closed'));
386
+ on(stdout, 'resize', () => {
387
+ // The old rows may have wrapped in the new width: step over what they take up now.
388
+ if (ready) draw(Math.min(shown.reduce((sum, line) => sum + Math.max(1, Math.ceil(cells(line) / cols())), 0), rows() - 1));
389
+ });
390
+ settling = setTimeout(() => {
391
+ ready = true;
392
+ draw();
393
+ }, settleMs);
394
+ });
395
+ fold('done', answer ? card.yes : card.no);
396
+ return answer;
397
+ } catch (err) {
398
+ fold('fail', 'stopped');
399
+ throw err;
400
+ } finally {
401
+ release();
402
+ }
403
+ };
404
+
405
+ return { ask, row, text, line, panel, work, intro, short };
406
+ }