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,235 @@
1
+ const HELP_EN = `ccleanup - interactive cleanup of Claude Code sessions
2
+
3
+ Usage:
4
+ ccleanup [options]
5
+
6
+ With no option, opens an interactive list of the sessions in ~/.claude/projects, sorted
7
+ by size. Mark the ones to delete, then confirm.
8
+
9
+ Keys:
10
+ up/down, j/k move PgUp/PgDn, g/G page, top, bottom
11
+ space mark, then follow the way you last moved
12
+ a mark all, or unmark all
13
+ o mark sessions older than --older-than (14d by default)
14
+ s, S change the sort (size, age, project), reverse the order
15
+ / search by project, title, folder or id (esc clears)
16
+ i details of the session under the cursor
17
+ ? help and legend
18
+ enter delete the marked sessions (with confirmation)
19
+ e show deletion errors
20
+ q, esc quit (Ctrl+C twice, Ctrl+Z to suspend)
21
+
22
+ Options:
23
+ -l, --list print the list, no interactive UI
24
+ --older-than <d> only target sessions older than <d> (12h, 14d, 2w, 3m)
25
+ --min-size <s> only target sessions bigger than <s> (100K, 500M, 1G)
26
+ -y, --yes delete the targeted sessions without UI (requires a filter)
27
+ -n, --dry-run show what would be deleted, delete nothing
28
+ --include-recent allow deleting sessions modified less than 30 min ago
29
+ (never those open in Claude Code)
30
+ --claude-dir <dir> Claude config folder, repeatable (default: those that exist among
31
+ $CLAUDE_CONFIG_DIR, ~/.claude and $XDG_CONFIG_HOME/claude or ~/.config/claude)
32
+
33
+ Reminder:
34
+ --install-reminder install a systemd timer that notifies when there is cleaning to do
35
+ --every <p> reminder period: daily, weekly (default) or monthly
36
+ --notify-above <s> notification threshold (default: 1G)
37
+ --uninstall-reminder remove the timer
38
+ --check what the reminder runs, by hand: summarize what can be cleaned
39
+ (14d by default), delete nothing
40
+ --notify with --check: desktop notification above the threshold
41
+
42
+ -h, --help show this help
43
+ -v, --version show the version
44
+
45
+ Environment:
46
+ CCLEANUP_LANG=fr|en interface language (default: system locale)
47
+ CCLEANUP_NOTIFY=<cmd> notification command, which receives the text, then the title
48
+ (default: notify-send)
49
+ CCLEANUP_ASCII=1 draw the interface with ASCII only
50
+ NO_COLOR, FORCE_COLOR disable or force colors
51
+ `;
52
+ /**
53
+ * English plural ending: only one takes the singular.
54
+ *
55
+ * @param count - Number the word refers to
56
+ * @returns An empty string for one, "s" otherwise, zero included
57
+ */
58
+ function pluralEn(count) {
59
+ return count === 1 ? "" : "s";
60
+ }
61
+ /**
62
+ * English texts of the interface.
63
+ */
64
+ export const en = {
65
+ help: HELP_EN,
66
+ subtitle: "Claude Code sessions",
67
+ columns: { size: "SIZE", age: "AGE", project: "PROJECT", title: "TITLE" },
68
+ stats: { sessions: "Sessions", marked: "Marked", releasable: "Releasable", freed: "Freed" },
69
+ olderTag: (days) => `over ${days} d`,
70
+ totalLine: (count, size) => `${count} session${pluralEn(count)}, ${size}`,
71
+ scanning: (done, total) => `Scanning ${done}/${total}`,
72
+ scanDone: (count, duration) => `${count} session${pluralEn(count)} scanned in ${duration}`,
73
+ deleting: (done, total) => `Deleting ${done}/${total}`,
74
+ keys: {
75
+ move: "move",
76
+ mark: "mark",
77
+ all: "all",
78
+ none: "none",
79
+ old: "old",
80
+ sort: "sort",
81
+ delete: "delete",
82
+ quit: "quit",
83
+ errors: "errors",
84
+ yes: "yes",
85
+ no: "no",
86
+ scroll: "scroll",
87
+ close: "close",
88
+ stop: "stop",
89
+ search: "search",
90
+ details: "details",
91
+ help: "help",
92
+ clear: "clear",
93
+ keep: "keep",
94
+ },
95
+ keyNames: {
96
+ arrows: "arrows",
97
+ space: "space",
98
+ enter: "enter",
99
+ esc: "esc",
100
+ yes: "y",
101
+ no: "n",
102
+ sort: "s/S",
103
+ },
104
+ usage: {
105
+ unknownOption: (option) => `Unknown option: ${option}`,
106
+ missingValue: (option) => `Missing value for ${option}`,
107
+ invalidValue: (option, value, expected) => `Invalid value for ${option}: "${value}" (expected: ${expected})`,
108
+ yesNeedsFilter: "--yes requires --older-than or --min-size, so it never deletes everything.",
109
+ hint: "Run ccleanup --help for usage.",
110
+ expected: {
111
+ "--older-than": "12h, 14d, 2w, 3m",
112
+ "--min-size": "100K, 500M, 1G",
113
+ "--notify-above": "100K, 500M, 1G",
114
+ "--every": "daily, weekly, monthly",
115
+ },
116
+ },
117
+ refusing: (path) => `Refusing to delete outside the sessions: ${path}`,
118
+ confirm: (count, size) => `Delete ${count} session${pluralEn(count)} (${size})?`,
119
+ confirmHint: "[y/N]",
120
+ confirmKeys: ["y"],
121
+ confirmTitle: "Delete",
122
+ confirmMore: (count) => `and ${count} more`,
123
+ confirmHidden: (count) => `including ${count} hidden by the search`,
124
+ confirmFinal: (count) => count === 1
125
+ ? "It can no longer be resumed with claude --resume."
126
+ : "They can no longer be resumed with claude --resume.",
127
+ guide: {
128
+ title: "Help",
129
+ sections: [
130
+ {
131
+ title: "Navigation",
132
+ rows: [
133
+ ["up/down, j/k", "move"],
134
+ ["PgUp/PgDn", "previous, next page"],
135
+ ["g/G", "top, bottom of the list"],
136
+ ],
137
+ },
138
+ {
139
+ title: "Marking",
140
+ rows: [
141
+ ["space", "mark, follow the way"],
142
+ ["a", "mark all, unmark all"],
143
+ ["o", "mark the old ones"],
144
+ ],
145
+ },
146
+ {
147
+ title: "List",
148
+ rows: [
149
+ ["/", "search (project, title, folder, id)"],
150
+ ["s/S", "change the sort, reverse it"],
151
+ ["i", "details of the session"],
152
+ ],
153
+ },
154
+ {
155
+ title: "Deletion",
156
+ rows: [
157
+ ["enter", "delete the marked ones"],
158
+ ["e", "deletion errors"],
159
+ ["esc", "close, clear the search"],
160
+ ["q", "quit"],
161
+ ],
162
+ },
163
+ ],
164
+ legendTitle: "Legend",
165
+ legend: {
166
+ marked: "marked",
167
+ markable: "can be marked",
168
+ open: "open in Claude Code, never deleted",
169
+ recent: "changed less than 30 min ago, protected",
170
+ recentAllowed: "changed less than 30 min ago (--include-recent)",
171
+ sizes: "size: grey under 10 MB, orange from 100 MB, red from 1 GB",
172
+ },
173
+ close: "esc or ? to close",
174
+ },
175
+ details: {
176
+ title: "Details",
177
+ folder: "Folder",
178
+ config: "Config",
179
+ started: "Started",
180
+ modified: "Modified",
181
+ size: "Size",
182
+ parts: {
183
+ transcript: "transcript",
184
+ folder: "folder",
185
+ history: "history",
186
+ env: "env",
187
+ debug: "debug",
188
+ },
189
+ state: "State",
190
+ states: {
191
+ open: "open in Claude Code",
192
+ recent: "recent",
193
+ marked: "marked",
194
+ idle: "idle",
195
+ },
196
+ resume: "Resume",
197
+ },
198
+ search: {
199
+ prompt: "search",
200
+ none: (query) => `No session matches "${query}".`,
201
+ count: (shown, total) => `${shown} of ${total}`,
202
+ clearHint: "esc to clear",
203
+ },
204
+ done: (count, size) => `${count} session${pluralEn(count)} deleted, ${size} freed.`,
205
+ failed: (count) => `${count} deletion${pluralEn(count)} failed.`,
206
+ stopping: "Stopping after the current session…",
207
+ ctrlCAgain: "Ctrl+C once more to quit",
208
+ errorsHint: (count) => `${count} error${pluralEn(count)}`,
209
+ errorsTitle: (count) => `Deletion errors (${count})`,
210
+ tooSmall: (cols, rows, minCols, minRows) => `Terminal too small\n${cols} × ${rows}, needs ${minCols} × ${minRows}`,
211
+ exitFreed: (size, count) => `${size} freed, ${count} session${pluralEn(count)} deleted`,
212
+ exitNothing: "Nothing deleted, see you next time.",
213
+ exitTones: ["A little breathing room.", "Nice cleanup.", "Big cleanup!"],
214
+ exitFailures: (count) => `${count} failure${pluralEn(count)}:`,
215
+ recent: "recent",
216
+ recentProtected: "Recent session, maybe running: protected (see --include-recent).",
217
+ open: "open",
218
+ openProtected: "Session open in Claude Code: protected.",
219
+ openSkipped: (count) => `${count} session${pluralEn(count)} opened meanwhile, kept.`,
220
+ nothingMarked: "Nothing marked.",
221
+ noSessions: (dirs) => `No Claude Code session found in ${dirs.join(", ")} (see --claude-dir).`,
222
+ denied: (paths) => `Permission denied, check the access rights: ${paths.join(", ")}`,
223
+ nothingMatches: "No session matches the filters.",
224
+ wouldDelete: (count, size) => `Would delete ${count} session${pluralEn(count)} (${size}). Nothing was deleted.`,
225
+ checkLine: (count, days, size) => `${count} session${pluralEn(count)} older than ${days} d can be cleaned: ${size}.`,
226
+ checkNothing: (days) => `No session older than ${days} d.`,
227
+ notifyTitle: "Claude Code sessions to clean",
228
+ notifyBody: (count, days, size) => `${size} in ${count} session${pluralEn(count)} older than ${days} d. Run "npx ccleanup".`,
229
+ notifyFailed: "Could not send the notification (is notify-send installed?).",
230
+ reminderInstalled: (every) => `${every} reminder installed (ccleanup-reminder.timer).`,
231
+ reminderRemoved: "Reminder removed.",
232
+ reminderDry: "Dry run: nothing was written or enabled.",
233
+ reminderNeedsGlobal: "ccleanup is running from the npx cache, which is temporary. Install it first: npm i -g ccleanup",
234
+ reminderNeedsSystemd: "The automatic reminder needs Linux with systemd.",
235
+ };
@@ -0,0 +1,235 @@
1
+ const HELP_FR = `ccleanup - nettoyage interactif des sessions Claude Code
2
+
3
+ Usage:
4
+ ccleanup [options]
5
+
6
+ Sans option, ouvre une liste interactive des sessions de ~/.claude/projects, triées
7
+ par taille. Marque celles à supprimer, puis valide.
8
+
9
+ Touches:
10
+ haut/bas, j/k naviguer PgUp/PgDn, g/G page, début, fin
11
+ espace marquer, puis suivre le dernier sens de déplacement
12
+ a tout marquer, ou tout démarquer
13
+ o marquer les sessions plus vieilles que --older-than (14d par défaut)
14
+ s, S changer le tri (taille, âge, projet), inverser l’ordre
15
+ / chercher par projet, titre, dossier ou id (échap efface)
16
+ i détails de la session sous le curseur
17
+ ? aide et légende
18
+ entrée supprimer les sessions marquées (avec confirmation)
19
+ e voir les erreurs de suppression
20
+ q, échap quitter (Ctrl+C deux fois, Ctrl+Z pour suspendre)
21
+
22
+ Options:
23
+ -l, --list afficher la liste sans interface interactive
24
+ --older-than <d> ne cibler que les sessions plus vieilles que <d> (12h, 14d, 2w, 3m)
25
+ --min-size <s> ne cibler que les sessions plus grosses que <s> (100K, 500M, 1G)
26
+ -y, --yes supprimer sans interface les sessions ciblées (exige un filtre)
27
+ -n, --dry-run montrer ce qui serait supprimé, sans rien supprimer
28
+ --include-recent autoriser la suppression des sessions modifiées il y a moins de 30 min
29
+ (jamais celles ouvertes dans Claude Code)
30
+ --claude-dir <dir> dossier de config Claude, répétable (défaut : ceux qui existent parmi
31
+ $CLAUDE_CONFIG_DIR, ~/.claude et $XDG_CONFIG_HOME/claude ou ~/.config/claude)
32
+
33
+ Rappel:
34
+ --install-reminder installer un timer systemd qui notifie quand il y a de quoi nettoyer
35
+ --every <p> fréquence du rappel : daily, weekly (défaut) ou monthly
36
+ --notify-above <s> seuil de la notification (défaut : 1G)
37
+ --uninstall-reminder retirer le timer
38
+ --check ce que lance le rappel, à la main : résumer ce qui est nettoyable
39
+ (14d par défaut), sans rien supprimer
40
+ --notify avec --check : notification de bureau au-dessus du seuil
41
+
42
+ -h, --help afficher cette aide
43
+ -v, --version afficher la version
44
+
45
+ Variables:
46
+ CCLEANUP_LANG=fr|en langue de l’interface (défaut : celle du système)
47
+ CCLEANUP_NOTIFY=<cmd> commande de notification, qui reçoit le texte puis le titre
48
+ (défaut : notify-send)
49
+ CCLEANUP_ASCII=1 dessiner l'interface en ASCII seulement
50
+ NO_COLOR, FORCE_COLOR désactiver ou forcer les couleurs
51
+ `;
52
+ /**
53
+ * French plural ending: zero and one take the singular.
54
+ *
55
+ * @param count - Number the word refers to
56
+ * @returns "s" above one, an empty string otherwise
57
+ */
58
+ function pluralFr(count) {
59
+ return count > 1 ? "s" : "";
60
+ }
61
+ /**
62
+ * French texts of the interface.
63
+ */
64
+ export const fr = {
65
+ help: HELP_FR,
66
+ subtitle: "sessions Claude Code",
67
+ columns: { size: "TAILLE", age: "ÂGE", project: "PROJET", title: "TITRE" },
68
+ stats: { sessions: "Sessions", marked: "Marquées", releasable: "Libérable", freed: "Libéré" },
69
+ olderTag: (days) => `plus de ${days} j`,
70
+ totalLine: (count, size) => `${count} session${pluralFr(count)}, ${size}`,
71
+ scanning: (done, total) => `Analyse ${done}/${total}`,
72
+ scanDone: (count, duration) => `${count} session${pluralFr(count)} analysée${pluralFr(count)} en ${duration}`,
73
+ deleting: (done, total) => `Suppression ${done}/${total}`,
74
+ keys: {
75
+ move: "naviguer",
76
+ mark: "marquer",
77
+ all: "tout",
78
+ none: "rien",
79
+ old: "anciennes",
80
+ sort: "tri",
81
+ delete: "supprimer",
82
+ quit: "quitter",
83
+ errors: "erreurs",
84
+ yes: "oui",
85
+ no: "non",
86
+ scroll: "défiler",
87
+ close: "fermer",
88
+ stop: "arrêter",
89
+ search: "chercher",
90
+ details: "détails",
91
+ help: "aide",
92
+ clear: "effacer",
93
+ keep: "garder",
94
+ },
95
+ keyNames: {
96
+ arrows: "flèches",
97
+ space: "espace",
98
+ enter: "entrée",
99
+ esc: "échap",
100
+ yes: "o",
101
+ no: "n",
102
+ sort: "s/S",
103
+ },
104
+ usage: {
105
+ unknownOption: (option) => `Option inconnue : ${option}`,
106
+ missingValue: (option) => `Valeur manquante pour ${option}`,
107
+ invalidValue: (option, value, expected) => `Valeur invalide pour ${option} : « ${value} » (attendu : ${expected})`,
108
+ yesNeedsFilter: "--yes exige --older-than ou --min-size, pour ne jamais tout supprimer.",
109
+ hint: "Lance ccleanup --help pour l’aide.",
110
+ expected: {
111
+ "--older-than": "12h, 14d, 2w, 3m",
112
+ "--min-size": "100K, 500M, 1G",
113
+ "--notify-above": "100K, 500M, 1G",
114
+ "--every": "daily, weekly, monthly",
115
+ },
116
+ },
117
+ refusing: (path) => `Suppression refusée hors des sessions : ${path}`,
118
+ confirm: (count, size) => `Supprimer ${count} session${pluralFr(count)} (${size}) ?`,
119
+ confirmHint: "[o/N]",
120
+ confirmKeys: ["o"],
121
+ confirmTitle: "Suppression",
122
+ confirmMore: (count) => `et ${count} autre${pluralFr(count)}`,
123
+ confirmHidden: (count) => `dont ${count} masquée${pluralFr(count)} par la recherche`,
124
+ confirmFinal: (count) => count === 1
125
+ ? "Elle ne pourra plus être reprise avec claude --resume."
126
+ : "Elles ne pourront plus être reprises avec claude --resume.",
127
+ guide: {
128
+ title: "Aide",
129
+ sections: [
130
+ {
131
+ title: "Navigation",
132
+ rows: [
133
+ ["haut/bas, j/k", "naviguer"],
134
+ ["PgUp/PgDn", "page précédente, suivante"],
135
+ ["g/G", "début, fin de la liste"],
136
+ ],
137
+ },
138
+ {
139
+ title: "Marquage",
140
+ rows: [
141
+ ["espace", "marquer, suivre le sens"],
142
+ ["a", "tout marquer, démarquer"],
143
+ ["o", "marquer les anciennes"],
144
+ ],
145
+ },
146
+ {
147
+ title: "Liste",
148
+ rows: [
149
+ ["/", "chercher (projet, titre, dossier, id)"],
150
+ ["s/S", "changer le tri, l’inverser"],
151
+ ["i", "détails de la session"],
152
+ ],
153
+ },
154
+ {
155
+ title: "Suppression",
156
+ rows: [
157
+ ["entrée", "supprimer les marquées"],
158
+ ["e", "erreurs de suppression"],
159
+ ["échap", "fermer, effacer la recherche"],
160
+ ["q", "quitter"],
161
+ ],
162
+ },
163
+ ],
164
+ legendTitle: "Légende",
165
+ legend: {
166
+ marked: "marquée",
167
+ markable: "à marquer",
168
+ open: "ouverte dans Claude Code, jamais supprimée",
169
+ recent: "modifiée il y a moins de 30 min, protégée",
170
+ recentAllowed: "modifiée il y a moins de 30 min (--include-recent)",
171
+ sizes: "taille : grise sous 10 Mo, orange dès 100 Mo, rouge dès 1 Go",
172
+ },
173
+ close: "échap ou ? pour fermer",
174
+ },
175
+ details: {
176
+ title: "Détails",
177
+ folder: "Dossier",
178
+ config: "Config",
179
+ started: "Début",
180
+ modified: "Modifiée",
181
+ size: "Taille",
182
+ parts: {
183
+ transcript: "transcript",
184
+ folder: "dossier",
185
+ history: "historique",
186
+ env: "env",
187
+ debug: "debug",
188
+ },
189
+ state: "État",
190
+ states: {
191
+ open: "ouverte dans Claude Code",
192
+ recent: "récente",
193
+ marked: "marquée",
194
+ idle: "inactive",
195
+ },
196
+ resume: "Reprendre",
197
+ },
198
+ search: {
199
+ prompt: "chercher",
200
+ none: (query) => `Aucune session ne correspond à « ${query} ».`,
201
+ count: (shown, total) => `${shown} sur ${total}`,
202
+ clearHint: "échap pour effacer",
203
+ },
204
+ done: (count, size) => `${count} session${pluralFr(count)} supprimée${pluralFr(count)}, ${size} libérés.`,
205
+ failed: (count) => `${count} suppression${pluralFr(count)} en échec.`,
206
+ stopping: "Arrêt après la session en cours…",
207
+ ctrlCAgain: "Ctrl+C encore une fois pour quitter",
208
+ errorsHint: (count) => `${count} erreur${pluralFr(count)}`,
209
+ errorsTitle: (count) => `Erreurs de suppression (${count})`,
210
+ tooSmall: (cols, rows, minCols, minRows) => `Terminal trop petit\n${cols} × ${rows}, il faut ${minCols} × ${minRows}`,
211
+ exitFreed: (size, count) => `${size} libérés, ${count} session${pluralFr(count)} supprimée${pluralFr(count)}`,
212
+ exitNothing: "Rien supprimé, à la prochaine.",
213
+ exitTones: ["Un peu d’air.", "Joli ménage.", "Gros ménage !"],
214
+ exitFailures: (count) => `${count} échec${pluralFr(count)} :`,
215
+ recent: "récente",
216
+ recentProtected: "Session récente, peut-être active : protégée (voir --include-recent).",
217
+ open: "ouverte",
218
+ openProtected: "Session ouverte dans Claude Code : protégée.",
219
+ openSkipped: (count) => `${count} session${pluralFr(count)} ouverte${pluralFr(count)} entre-temps, gardée${pluralFr(count)}.`,
220
+ nothingMarked: "Rien de marqué.",
221
+ noSessions: (dirs) => `Aucune session Claude Code trouvée dans ${dirs.join(", ")} (voir --claude-dir).`,
222
+ denied: (paths) => `Lecture refusée, vérifie les permissions : ${paths.join(", ")}`,
223
+ nothingMatches: "Aucune session ne correspond aux filtres.",
224
+ wouldDelete: (count, size) => `À supprimer : ${count} session${pluralFr(count)} (${size}). Rien n’a été supprimé.`,
225
+ checkLine: (count, days, size) => `${count} session${pluralFr(count)} de plus de ${days} j nettoyable${pluralFr(count)} : ${size}.`,
226
+ checkNothing: (days) => `Aucune session de plus de ${days} j.`,
227
+ notifyTitle: "Sessions Claude Code à nettoyer",
228
+ notifyBody: (count, days, size) => `${size} dans ${count} session${pluralFr(count)} de plus de ${days} j. Lance « npx ccleanup ».`,
229
+ notifyFailed: "Notification impossible (notify-send introuvable ?).",
230
+ reminderInstalled: (every) => `Rappel ${every} installé (ccleanup-reminder.timer).`,
231
+ reminderRemoved: "Rappel retiré.",
232
+ reminderDry: "Simulation : rien n’a été écrit ni activé.",
233
+ reminderNeedsGlobal: "ccleanup tourne depuis le cache npx, qui est temporaire. Installe-le d’abord : npm i -g ccleanup",
234
+ reminderNeedsSystemd: "Le rappel automatique demande Linux avec systemd.",
235
+ };
@@ -0,0 +1,11 @@
1
+ import { en } from "./en.js";
2
+ import { fr } from "./fr.js";
3
+ /**
4
+ * Texts of the interface.
5
+ *
6
+ * @param lang - Language picked by detectLang
7
+ * @returns The French or English texts
8
+ */
9
+ export function messages(lang) {
10
+ return lang === "fr" ? fr : en;
11
+ }
@@ -0,0 +1,129 @@
1
+ import { homedir } from "node:os";
2
+ import { sep } from "node:path";
3
+ // Unit labels per language, from bytes to terabytes
4
+ const UNITS = {
5
+ fr: ["o", "Ko", "Mo", "Go", "To"],
6
+ en: ["B", "KB", "MB", "GB", "TB"],
7
+ };
8
+ export const HOUR = 3_600_000;
9
+ export const DAY = 24 * HOUR;
10
+ export const MB = 1024 * 1024;
11
+ export const GB = 1024 * MB;
12
+ /**
13
+ * Picks the interface language from the environment.
14
+ *
15
+ * @param env - Environment to read; CCLEANUP_LANG wins over LC_ALL, LC_MESSAGES and LANG
16
+ * @returns French when the first of these variables starts with "fr", English otherwise
17
+ */
18
+ export function detectLang(env = process.env) {
19
+ const raw = env.CCLEANUP_LANG ?? env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? "";
20
+ return raw.toLowerCase().startsWith("fr") ? "fr" : "en";
21
+ }
22
+ /**
23
+ * Formats a size in binary units, with a decimal comma in French.
24
+ *
25
+ * @param bytes - Size in bytes, 0 or more
26
+ * @param lang - Language of the unit labels and of the decimal separator
27
+ * @returns One decimal under 100 of the unit ("4,2 Go"), none above or for bytes ("512 o")
28
+ */
29
+ export function formatSize(bytes, lang) {
30
+ const units = UNITS[lang];
31
+ let value = bytes;
32
+ let unit = 0;
33
+ while (value >= 1024 && unit < units.length - 1) {
34
+ value /= 1024;
35
+ unit++;
36
+ }
37
+ let text = unit === 0 || value >= 100 ? value.toFixed(0) : value.toFixed(1);
38
+ if (lang === "fr")
39
+ text = text.replace(".", ",");
40
+ return `${text} ${units[unit]}`;
41
+ }
42
+ /**
43
+ * Formats an age in the shortest readable unit.
44
+ *
45
+ * @param ageMs - Elapsed time in milliseconds
46
+ * @param lang - Language of the day suffix ("j" in French, "d" in English)
47
+ * @returns "<1h" under an hour, hours under two days, days under 60 days, then months of 30 days
48
+ */
49
+ export function formatAge(ageMs, lang) {
50
+ const hours = ageMs / HOUR;
51
+ if (hours < 1)
52
+ return "<1h";
53
+ if (hours < 48)
54
+ return `${Math.floor(hours)}h`;
55
+ const days = ageMs / DAY;
56
+ if (days < 60)
57
+ return `${Math.floor(days)}${lang === "fr" ? "j" : "d"}`;
58
+ return `${Math.floor(days / 30)}mo`;
59
+ }
60
+ /**
61
+ * Formats a duration for progress lines.
62
+ *
63
+ * @param ms - Duration in milliseconds
64
+ * @param lang - Language of the decimal separator
65
+ * @returns Tenths of a second under 10 s ("3,7 s"), whole seconds under a minute, then "2 min 05 s"
66
+ */
67
+ export function formatDuration(ms, lang) {
68
+ const seconds = ms / 1000;
69
+ if (seconds < 10) {
70
+ const text = seconds.toFixed(1);
71
+ return `${lang === "fr" ? text.replace(".", ",") : text} s`;
72
+ }
73
+ if (seconds < 60)
74
+ return `${Math.round(seconds)} s`;
75
+ const whole = Math.round(seconds);
76
+ return `${Math.floor(whole / 60)} min ${String(whole % 60).padStart(2, "0")} s`;
77
+ }
78
+ /**
79
+ * Parses a duration given on the command line.
80
+ *
81
+ * @param input - Number followed by h (hours), d (days), w (weeks) or m (months of 30 days)
82
+ * @returns The duration in milliseconds
83
+ * @throws Error when the input does not match that form
84
+ */
85
+ export function parseDuration(input) {
86
+ const match = /^(\d+(?:\.\d+)?)([hdwm])$/i.exec(input.trim());
87
+ if (!match)
88
+ throw new Error(`Invalid duration "${input}" (expected e.g. 12h, 14d, 2w, 3m)`);
89
+ const factor = { h: HOUR, d: DAY, w: 7 * DAY, m: 30 * DAY }[match[2].toLowerCase()];
90
+ return Number(match[1]) * factor;
91
+ }
92
+ /**
93
+ * Parses a size given on the command line, in binary units.
94
+ *
95
+ * @param input - Number with an optional K, M, G or T suffix and an optional trailing B
96
+ * @returns The size in bytes, rounded to an integer
97
+ * @throws Error when the input does not match that form
98
+ */
99
+ export function parseSize(input) {
100
+ const match = /^(\d+(?:\.\d+)?)\s*([kmgt]?)b?$/i.exec(input.trim());
101
+ if (!match)
102
+ throw new Error(`Invalid size "${input}" (expected e.g. 100K, 500M, 1G)`);
103
+ const suffix = match[2].toLowerCase();
104
+ const power = suffix ? "kmgt".indexOf(suffix) + 1 : 0;
105
+ return Math.round(Number(match[1]) * 1024 ** power);
106
+ }
107
+ /**
108
+ * Writes a date and time the way the language does.
109
+ *
110
+ * @param ms - Time in milliseconds since the epoch
111
+ * @param lang - Language of the output
112
+ * @returns Such as "24 nov. 2026, 14:05"
113
+ */
114
+ export function formatDate(ms, lang) {
115
+ return new Intl.DateTimeFormat(lang === "fr" ? "fr-FR" : "en-GB", {
116
+ dateStyle: "medium",
117
+ timeStyle: "short",
118
+ }).format(ms);
119
+ }
120
+ /**
121
+ * Shortens a path under the home folder for display.
122
+ *
123
+ * @param path - Absolute path
124
+ * @param home - Home folder
125
+ * @returns The path with the home folder written "~"
126
+ */
127
+ export function tildify(path, home = homedir()) {
128
+ return path === home || path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path;
129
+ }