ccleanup 1.0.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.
@@ -0,0 +1,263 @@
1
+ export const ESC = String.fromCharCode(0x1b);
2
+ export const BEL = String.fromCharCode(0x07);
3
+ export const ELLIPSIS = String.fromCodePoint(0x2026);
4
+ // CSI sequences (colors, cursor moves) and OSC sequences ended by BEL or ST
5
+ const ANSI = new RegExp(String.raw `${ESC}\[[0-?]*[ -/]*[@-~]|${ESC}\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\)`, "g");
6
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
7
+ const EMOJI = /\p{Emoji_Presentation}/u;
8
+ const PICTOGRAPHIC = /\p{Extended_Pictographic}/u;
9
+ const REGIONAL = /\p{Regional_Indicator}/u;
10
+ const MARK = /^\p{M}+$/u;
11
+ const VARIATION_SELECTOR = 0xfe0f;
12
+ const ZWJ = 0x200d;
13
+ // Code point ranges drawn on two cells: Hangul, CJK, fullwidth forms
14
+ const WIDE = [
15
+ [0x1100, 0x115f],
16
+ [0x2329, 0x232a],
17
+ [0x2e80, 0x303e],
18
+ [0x3041, 0x33ff],
19
+ [0x3400, 0x4dbf],
20
+ [0x4e00, 0x9fff],
21
+ [0xa000, 0xa4cf],
22
+ [0xa960, 0xa97f],
23
+ [0xac00, 0xd7a3],
24
+ [0xf900, 0xfaff],
25
+ [0xfe30, 0xfe4f],
26
+ [0xff00, 0xff60],
27
+ [0xffe0, 0xffe6],
28
+ [0x16fe0, 0x18aff],
29
+ [0x1b000, 0x1b2ff],
30
+ [0x20000, 0x3fffd],
31
+ ];
32
+ // Invisible code points: zero-width characters and variation selectors
33
+ const ZERO_WIDTH = [
34
+ [0x200b, 0x200f],
35
+ [0x2060, 0x2060],
36
+ [0xfe00, 0xfe0f],
37
+ ];
38
+ // Bidirectional formatting code points, dropped from transcript text
39
+ const BIDI = [
40
+ [0x200e, 0x200f],
41
+ [0x202a, 0x202e],
42
+ [0x2066, 0x2069],
43
+ ];
44
+ /**
45
+ * Tells whether a code point falls in one of the given inclusive ranges.
46
+ *
47
+ * @param code - Unicode code point
48
+ * @param ranges - Inclusive [from, to] pairs
49
+ * @returns True when one range holds the code point
50
+ */
51
+ function inRanges(code, ranges) {
52
+ return ranges.some(([from, to]) => code >= from && code <= to);
53
+ }
54
+ /**
55
+ * Tells whether a code point is a C0 or C1 control character.
56
+ *
57
+ * @param code - Unicode code point
58
+ * @returns True for 0x00-0x1f and 0x7f-0x9f
59
+ */
60
+ function isControl(code) {
61
+ return code < 0x20 || (code >= 0x7f && code < 0xa0);
62
+ }
63
+ /**
64
+ * Lists the code points of a string.
65
+ *
66
+ * @param text - Any string
67
+ * @returns One number per code point, surrogate pairs combined
68
+ */
69
+ function codePoints(text) {
70
+ return Array.from(text, (char) => char.codePointAt(0) ?? 0);
71
+ }
72
+ // Code point ranges always one cell wide, the interface glyphs included
73
+ const NARROW = [
74
+ [0x20, 0x7e],
75
+ [0xa0, 0x2ff],
76
+ [0x2010, 0x2027],
77
+ [0x2303, 0x2304],
78
+ [0x2500, 0x25fc],
79
+ [0x2713, 0x2713],
80
+ [0x2717, 0x2717],
81
+ [0x276f, 0x276f],
82
+ [0x2800, 0x28ff],
83
+ ];
84
+ const CACHE_LIMIT = 4096;
85
+ const widthCache = new Map();
86
+ /**
87
+ * Width of a string made only of single-cell code units, without segmentation.
88
+ *
89
+ * @param text - Plain text, without escape sequences
90
+ * @returns The number of code units, or undefined when one of them needs the full rules
91
+ */
92
+ function simpleWidth(text) {
93
+ for (let i = 0; i < text.length; i++) {
94
+ if (!inRanges(text.charCodeAt(i), NARROW))
95
+ return undefined;
96
+ }
97
+ return text.length;
98
+ }
99
+ /**
100
+ * Removes the escape sequences of a styled string.
101
+ *
102
+ * @param text - String that may hold CSI and OSC sequences
103
+ * @returns The visible text only
104
+ */
105
+ export function stripAnsi(text) {
106
+ return text.includes(ESC) ? text.replace(ANSI, "") : text;
107
+ }
108
+ /**
109
+ * Number of terminal cells a single grapheme takes.
110
+ *
111
+ * Emoji with a default emoji presentation, flags, pictographs followed by a variation
112
+ * selector and East Asian wide characters take two cells; marks and joiners take none.
113
+ *
114
+ * @param grapheme - One user-perceived character, as split by Intl.Segmenter
115
+ * @returns 0, 1 or 2
116
+ */
117
+ function graphemeWidth(grapheme) {
118
+ const points = codePoints(grapheme);
119
+ const first = points[0] ?? 0;
120
+ if (isControl(first))
121
+ return 0;
122
+ if (MARK.test(grapheme) || points.every((code) => inRanges(code, ZERO_WIDTH)))
123
+ return 0;
124
+ if (EMOJI.test(grapheme) || REGIONAL.test(grapheme))
125
+ return 2;
126
+ if (points.includes(VARIATION_SELECTOR) && PICTOGRAPHIC.test(grapheme))
127
+ return 2;
128
+ return inRanges(first, WIDE) ? 2 : 1;
129
+ }
130
+ /**
131
+ * Splits a string into graphemes.
132
+ *
133
+ * @param text - Plain text, without escape sequences
134
+ * @returns The user-perceived characters, in order
135
+ */
136
+ function graphemes(text) {
137
+ return Array.from(segmenter.segment(text), (part) => part.segment);
138
+ }
139
+ /**
140
+ * Measures a string as the terminal draws it.
141
+ *
142
+ * @param text - Text that may hold escape sequences, which take no cell
143
+ * @returns The width in terminal cells
144
+ */
145
+ export function width(text) {
146
+ const plain = stripAnsi(text);
147
+ const simple = simpleWidth(plain);
148
+ if (simple !== undefined)
149
+ return simple;
150
+ const cached = widthCache.get(plain);
151
+ if (cached !== undefined)
152
+ return cached;
153
+ let cells = 0;
154
+ for (const grapheme of graphemes(plain))
155
+ cells += graphemeWidth(grapheme);
156
+ if (widthCache.size >= CACHE_LIMIT)
157
+ widthCache.clear();
158
+ widthCache.set(plain, cells);
159
+ return cells;
160
+ }
161
+ /**
162
+ * Shortens plain text to a number of cells, on grapheme boundaries.
163
+ *
164
+ * @param text - Plain text, without escape sequences
165
+ * @param cells - Maximum width in terminal cells
166
+ * @param ellipsis - Ending added when something was cut
167
+ * @returns The text itself when it fits, else its start followed by the ellipsis
168
+ */
169
+ export function cut(text, cells, ellipsis = ELLIPSIS) {
170
+ if (cells <= 0)
171
+ return "";
172
+ if (width(text) <= cells)
173
+ return text;
174
+ // Too narrow for the ellipsis: cut bare, so the width holds.
175
+ if (width(ellipsis) >= cells)
176
+ return cut(text, cells, "");
177
+ const limit = cells - width(ellipsis);
178
+ if (simpleWidth(text) !== undefined)
179
+ return text.slice(0, Math.max(0, limit)) + ellipsis;
180
+ let out = "";
181
+ let used = 0;
182
+ for (const grapheme of graphemes(text)) {
183
+ const cell = graphemeWidth(grapheme);
184
+ if (used + cell > limit)
185
+ break;
186
+ out += grapheme;
187
+ used += cell;
188
+ }
189
+ return out + ellipsis;
190
+ }
191
+ /**
192
+ * Cuts or pads plain text to an exact number of cells, for table columns.
193
+ *
194
+ * @param text - Plain text, without escape sequences
195
+ * @param cells - Width of the column in terminal cells
196
+ * @param align - Side the text sticks to; the padding goes on the other side
197
+ * @param ellipsis - Ending of a cut, the glyph of the theme in the interface
198
+ * @returns A string exactly `cells` cells wide
199
+ */
200
+ export function fit(text, cells, align = "left", ellipsis = ELLIPSIS) {
201
+ const short = cut(text, cells, ellipsis);
202
+ const pad = " ".repeat(Math.max(0, cells - width(short)));
203
+ return align === "left" ? short + pad : pad + short;
204
+ }
205
+ /**
206
+ * Makes text read from a transcript safe and stable to print.
207
+ *
208
+ * Control characters become spaces and bidirectional controls are dropped. Emoji
209
+ * sequences whose width depends on the terminal (joined families, skin tones) are
210
+ * reduced to their first emoji, so every terminal draws them on the same cells.
211
+ *
212
+ * @param text - Untrusted text, such as a prompt or a title
213
+ * @returns Text without control characters, safe for a single terminal line
214
+ */
215
+ export function sanitize(text) {
216
+ return graphemes(text)
217
+ .map((grapheme) => {
218
+ const points = codePoints(grapheme).filter((code) => !inRanges(code, BIDI));
219
+ if (points.length === 0)
220
+ return "";
221
+ if (points.every(isControl))
222
+ return " ";
223
+ const skinTone = points.some((code) => code >= 0x1f3fb && code <= 0x1f3ff);
224
+ if (!points.includes(ZWJ) && !skinTone)
225
+ return String.fromCodePoint(...points);
226
+ const head = String.fromCodePoint(points[0]);
227
+ return points.includes(VARIATION_SELECTOR)
228
+ ? head + String.fromCodePoint(VARIATION_SELECTOR)
229
+ : head;
230
+ })
231
+ .join("");
232
+ }
233
+ /**
234
+ * Drops the first cells of a plain text, the counterpart of cut.
235
+ *
236
+ * @param text - Text without escape codes
237
+ * @param cells - Cells to drop; a wide character cut in half leaves a space
238
+ * @returns What lies after those cells
239
+ */
240
+ export function skip(text, cells) {
241
+ if (cells <= 0)
242
+ return text;
243
+ let used = 0;
244
+ let out = "";
245
+ for (const grapheme of graphemes(text)) {
246
+ const cell = graphemeWidth(grapheme);
247
+ if (used >= cells)
248
+ out += grapheme;
249
+ else if (used + cell > cells)
250
+ out += " ".repeat(used + cell - cells);
251
+ used += cell;
252
+ }
253
+ return out;
254
+ }
255
+ /**
256
+ * Folds a text for searching: lowercase, accents removed.
257
+ *
258
+ * @param text - Any text
259
+ * @returns The folded text, so "Été" matches "ete"
260
+ */
261
+ export function fold(text) {
262
+ return text.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
263
+ }
@@ -0,0 +1,56 @@
1
+ import { emitKeypressEvents } from "node:readline";
2
+ import { PassThrough } from "node:stream";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { BEL, ESC } from "../lib/text.js";
5
+ // Terminal replies that must never read as keys: OSC strings and device attributes
6
+ const REPLY = new RegExp(String.raw `${ESC}\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\)|${ESC}\[\?[\d;]*c`, "g");
7
+ // The start of a reply cut at the end of a chunk, kept until the next chunk
8
+ const PARTIAL = new RegExp(String.raw `${ESC}(?:\][^${BEL}${ESC}]*${ESC}?|\[\?[\d;]*)?$`);
9
+ const CARRY_MS = 50;
10
+ /**
11
+ * Decodes keys from stdin, after removing the replies the terminal sends on its own.
12
+ *
13
+ * Replies to the background probe can arrive late, on a slow link: without this filter,
14
+ * readline would turn `rgb:2a2a/...` into the keys r, g, b and a, which mark sessions.
15
+ *
16
+ * @param stdin - Terminal input, already in raw mode
17
+ * @param onKey - Called for each decoded key, as readline reports it
18
+ * @returns The input, to close when the interface ends
19
+ */
20
+ export function createInput(stdin, onKey) {
21
+ const relay = new PassThrough();
22
+ const decoder = new StringDecoder("utf8");
23
+ let carry = "";
24
+ let timer;
25
+ const flush = () => {
26
+ timer = undefined;
27
+ if (carry)
28
+ relay.write(carry);
29
+ carry = "";
30
+ };
31
+ const onData = (chunk) => {
32
+ clearTimeout(timer);
33
+ let text = (carry + decoder.write(chunk)).replace(REPLY, "");
34
+ carry = "";
35
+ const partial = PARTIAL.exec(text);
36
+ if (partial?.[0]) {
37
+ carry = partial[0];
38
+ text = text.slice(0, partial.index);
39
+ timer = setTimeout(flush, CARRY_MS);
40
+ }
41
+ if (text)
42
+ relay.write(text);
43
+ };
44
+ emitKeypressEvents(relay);
45
+ relay.on("keypress", onKey);
46
+ stdin.on("data", onData);
47
+ stdin.resume();
48
+ return {
49
+ close() {
50
+ clearTimeout(timer);
51
+ stdin.removeListener("data", onData);
52
+ relay.removeAllListeners("keypress");
53
+ relay.end();
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,44 @@
1
+ import { cut, width } from "../lib/text.js";
2
+ /**
3
+ * Joins styled segments into one line that never exceeds a width.
4
+ *
5
+ * @param theme - Theme of the output: colors, depth and glyph set
6
+ * @param segments - Text and style pairs, in order
7
+ * @param cols - Maximum width in cells; the segment that crosses it is cut with an ellipsis
8
+ * @param base - Style applied over every segment, such as the selection background
9
+ * @param pad - Fill the rest of the line with the base style, for a full-width bar
10
+ * @returns The painted line
11
+ */
12
+ export function line(theme, segments, cols, base = {}, pad = false) {
13
+ let out = "";
14
+ let used = 0;
15
+ for (const [text, style = {}] of segments) {
16
+ if (used >= cols)
17
+ break;
18
+ const room = cols - used;
19
+ const piece = width(text) > room ? cut(text, room, theme.glyphs.ellipsis) : text;
20
+ const merged = { ...style, ...base, fg: style.fg, bg: style.bg ?? base.bg };
21
+ const plain = style.fg === undefined || style.fg === "text";
22
+ if (base.bg && !style.bg && plain)
23
+ merged.fg = "selFg";
24
+ // Reverse video: a colored piece would break the bar.
25
+ if (base.inverse)
26
+ delete merged.fg;
27
+ out += theme.paint(piece, merged);
28
+ used += width(piece);
29
+ }
30
+ if (pad && used < cols)
31
+ out += theme.paint(" ".repeat(cols - used), base);
32
+ return out;
33
+ }
34
+ /**
35
+ * Style of the selected row.
36
+ *
37
+ * @param theme - Theme of the output: colors, depth and glyph set
38
+ * @returns A tinted background with 256 colors or more, reverse video below
39
+ */
40
+ export function selectionStyle(theme) {
41
+ if (!theme.enabled)
42
+ return {};
43
+ return theme.depth >= 8 ? { bg: "selBg" } : { inverse: true };
44
+ }
@@ -0,0 +1,167 @@
1
+ import { mix } from "./theme.js";
2
+ const WORD = "ccleanup";
3
+ // Block font: "#" full, "^" upper half, "_" lower half, two pixels per cell
4
+ const LETTERS = {
5
+ c: ["#^^", "# ", "^^^"],
6
+ l: ["# ", "# ", "^^^"],
7
+ e: ["#^^", "#^ ", "^^^"],
8
+ a: ["#^#", "#^#", "^ ^"],
9
+ n: ["#_ #", "# ^#", "^ ^"],
10
+ u: ["# #", "# #", "^^^"],
11
+ p: ["#^#", "#^^", "^ "],
12
+ };
13
+ // The spark mascot; its blank sixth row lines it up with the word
14
+ const MASCOT = ["..#..", "#.#.#", ".###.", "#.#.#", "..#..", "....."];
15
+ const MASCOT_GAP = 2;
16
+ const SHAPE_ROWS = 6;
17
+ // Pixel rows that hold ink; the blank row under them takes the shadow
18
+ const INK_ROWS = SHAPE_ROWS - 1;
19
+ // Bitmap of the mascot and the word, one string per pixel row
20
+ const SHAPE = Array.from({ length: SHAPE_ROWS }, (_, pixelRow) => MASCOT[pixelRow] +
21
+ ".".repeat(MASCOT_GAP) +
22
+ [...WORD]
23
+ .map((letter) => LETTERS[letter][Math.floor(pixelRow / 2)])
24
+ .join(" ")
25
+ .replace(/./g, (char) => {
26
+ const upper = pixelRow % 2 === 0;
27
+ const on = char === "#" || (char === "^" && upper) || (char === "_" && !upper);
28
+ return on ? "#" : ".";
29
+ }));
30
+ // The shadow falls one pixel down and right
31
+ const TERMINAL_ROWS = SHAPE_ROWS / 2;
32
+ export const LOGO_WIDTH = SHAPE[0].length + 1;
33
+ const FULL = String.fromCodePoint(0x2588);
34
+ const UPPER = String.fromCodePoint(0x2580);
35
+ const LOWER = String.fromCodePoint(0x2584);
36
+ // Painted logo per theme: it never changes while the interface runs
37
+ const logoCache = new WeakMap();
38
+ /**
39
+ * Tells whether a pixel of the mascot or the word is on.
40
+ *
41
+ * @param row - Pixel row, 0 at the top; rows outside the bitmap are off
42
+ * @param col - Pixel column, 0 at the left
43
+ * @returns True for an on pixel
44
+ */
45
+ function pixel(row, col) {
46
+ return SHAPE[row]?.[col] === "#";
47
+ }
48
+ /**
49
+ * Tells whether a pixel lies in the shadow: off itself, with an on pixel up and left.
50
+ *
51
+ * @param row - Pixel row, 0 at the top
52
+ * @param col - Pixel column, 0 at the left
53
+ * @returns True for a shadow pixel
54
+ */
55
+ function shadowed(row, col) {
56
+ return !pixel(row, col) && pixel(row - 1, col - 1);
57
+ }
58
+ /**
59
+ * Color of one pixel of the logo, on a gradient from left to right and from top to
60
+ * bottom between the four corner tokens of the theme.
61
+ *
62
+ * @param theme - Theme of the output
63
+ * @param row - Pixel row, 0 at the top
64
+ * @param col - Pixel column, 0 at the left
65
+ * @returns The bilinear mix of the corner colors at that pixel
66
+ */
67
+ function shade(theme, row, col) {
68
+ const x = col / (LOGO_WIDTH - 1);
69
+ const y = row / (INK_ROWS - 1);
70
+ const top = mix(theme.rgb("logoTopLeft"), theme.rgb("logoTopRight"), x);
71
+ const bottom = mix(theme.rgb("logoBottomLeft"), theme.rgb("logoBottomRight"), x);
72
+ return mix(top, bottom, y);
73
+ }
74
+ /**
75
+ * Color of a pixel with its shadow.
76
+ *
77
+ * @param theme - Theme of the output
78
+ * @param row - Pixel row, 0 at the top
79
+ * @param col - Pixel column, 0 at the left
80
+ * @returns The gradient color of an on pixel, the shadow color, or undefined for an empty pixel
81
+ */
82
+ function colorAt(theme, row, col) {
83
+ if (pixel(row, col))
84
+ return shade(theme, row, col);
85
+ if (shadowed(row, col))
86
+ return theme.rgb("logoShadow");
87
+ return undefined;
88
+ }
89
+ /**
90
+ * Draws one terminal row of the logo with its 2D gradient and its drop shadow.
91
+ *
92
+ * A terminal row holds two pixel rows: the upper half block takes the color of the upper
93
+ * pixel as foreground and, when both pixels are filled, the lower one as background.
94
+ *
95
+ * @param theme - Theme of the output, with at least 256 colors
96
+ * @param row - Terminal row, 0 at the top
97
+ * @returns The painted row, LOGO_WIDTH cells wide
98
+ */
99
+ function gradientRow(theme, row) {
100
+ let out = "";
101
+ for (let col = 0; col < LOGO_WIDTH; col++) {
102
+ const upper = colorAt(theme, row * 2, col);
103
+ const lower = colorAt(theme, row * 2 + 1, col);
104
+ if (upper && lower)
105
+ out += theme.paint(UPPER, { rgb: upper, bgRgb: lower });
106
+ else if (upper)
107
+ out += theme.paint(UPPER, { rgb: upper });
108
+ else if (lower)
109
+ out += theme.paint(LOWER, { rgb: lower });
110
+ else
111
+ out += " ";
112
+ }
113
+ return out;
114
+ }
115
+ /**
116
+ * Draws one terminal row of the logo in a single color and without shadow, for 16-color
117
+ * terminals.
118
+ *
119
+ * @param theme - Theme of the output
120
+ * @param row - Terminal row, 0 at the top
121
+ * @returns The painted row, LOGO_WIDTH cells wide
122
+ */
123
+ function flatRow(theme, row) {
124
+ let out = "";
125
+ for (let col = 0; col < LOGO_WIDTH; col++) {
126
+ const high = pixel(row * 2, col);
127
+ const low = pixel(row * 2 + 1, col);
128
+ out += high && low ? FULL : high ? UPPER : low ? LOWER : " ";
129
+ }
130
+ return theme.paint(out, { fg: "accent", bold: true });
131
+ }
132
+ /**
133
+ * Draws the pixel logo, painted once per theme.
134
+ *
135
+ * @param theme - Theme of the output: a 2D gradient from 256 colors up, one color below
136
+ * @returns Three rows of LOGO_WIDTH cells, or the bold word alone without Unicode
137
+ */
138
+ export function logo(theme) {
139
+ const cached = logoCache.get(theme);
140
+ if (cached)
141
+ return cached;
142
+ const draw = (row) => theme.depth >= 8 ? gradientRow(theme, row) : flatRow(theme, row);
143
+ const rows = theme.unicode
144
+ ? Array.from({ length: TERMINAL_ROWS }, (_, row) => draw(row))
145
+ : [theme.paint(WORD, { fg: "accent", bold: true })];
146
+ logoCache.set(theme, rows);
147
+ return rows;
148
+ }
149
+ /**
150
+ * Writes the word "ccleanup" across the logo colors, for one-line headers and the exit
151
+ * summary.
152
+ *
153
+ * @param theme - Theme of the output; below 256 colors the word takes the accent
154
+ * @returns The painted word, plain when the output is not a terminal
155
+ */
156
+ export function wordmark(theme) {
157
+ if (!theme.enabled)
158
+ return WORD;
159
+ if (theme.depth < 8)
160
+ return theme.paint(WORD, { fg: "accent", bold: true });
161
+ return [...WORD]
162
+ .map((char, i) => theme.paint(char, {
163
+ rgb: shade(theme, 1, (i / (WORD.length - 1)) * (LOGO_WIDTH - 1)),
164
+ bold: true,
165
+ }))
166
+ .join("");
167
+ }