computer-vitals 0.0.0-stage → 0.1.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,346 @@
1
+ // check_disk and find_large_files: what is using the disk space. Read-only: files are counted,
2
+ // never opened, moved or deleted. check_disk reports sizes of standard folders only (no file
3
+ // names); find_large_files lists file names, and only in one standard folder picked from a fixed list.
4
+ import os from "node:os";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { readText } from "./run.js";
9
+ import { runWinScript, arr } from "./win.js";
10
+ import { parseMountinfo } from "./parse.js";
11
+ import { driveSpace } from "./gather.js";
12
+ import { diskSize } from "./units.js";
13
+ import { cleanText } from "./text.js";
14
+
15
+ const PLATFORM = process.platform;
16
+ const YEAR_MS = 365 * 24 * 3600 * 1000;
17
+
18
+ export const FOLDERS = ["downloads", "desktop", "documents", "pictures", "videos", "music"];
19
+ const LABEL = { downloads: "Downloads", desktop: "Desktop", documents: "Documents", pictures: "Pictures", videos: PLATFORM === "darwin" ? "Movies" : "Videos", music: "Music" };
20
+
21
+ // Folders that are really one thing (a photo library, an app, a virtual machine). They are
22
+ // reported as a single item instead of the thousands of files inside.
23
+ const BUNDLE = /\.(photoslibrary|app|imovielibrary|fcpbundle|logicx|band|vmwarevm|pvm|utm|sparsebundle|aplibrary|musiclibrary|tvlibrary|xcarchive)$/i;
24
+
25
+ // ---------- counting ----------------------------------------------------------------------------
26
+
27
+ const realSize = (st) => (PLATFORM !== "win32" && Number.isFinite(st.blocks) ? st.blocks * 512 : st.size);
28
+
29
+ /**
30
+ * Adds up a folder. Never follows links. Stops at the deadline or the entry limit and says so.
31
+ * Returns { exists, denied, bytes, files, oldBytes, partial, unreadable, top }.
32
+ */
33
+ export async function measure(root, { deadline = Date.now() + 20000, maxEntries = 2000000, top = 0, now = Date.now() } = {}) {
34
+ const out = { exists: true, denied: false, bytes: 0, files: 0, oldBytes: 0, partial: false, unreadable: 0, top: [] };
35
+ let entries = 0;
36
+ const keep = (item) => {
37
+ if (!top || (out.top.length >= top && item.bytes <= out.top[out.top.length - 1].bytes)) return;
38
+ out.top.push(item);
39
+ out.top.sort((a, b) => b.bytes - a.bytes);
40
+ if (out.top.length > top) out.top.length = top;
41
+ };
42
+
43
+ // Adds up one folder tree; returns its total so a bundle can be listed as one item.
44
+ // Reading is done in quick direct calls (far faster than queued ones for hundreds of thousands
45
+ // of files), pausing regularly so the server stays responsive and other folders get their turn.
46
+ let sinceYield = 0;
47
+ async function walk(start, asBundle) {
48
+ let subtotal = 0;
49
+ let newest = 0;
50
+ const stack = [start];
51
+ while (stack.length) {
52
+ if (Date.now() > deadline || entries > maxEntries) {
53
+ out.partial = true;
54
+ break;
55
+ }
56
+ const dir = stack.pop();
57
+ let list;
58
+ try {
59
+ list = fs.readdirSync(dir, { withFileTypes: true });
60
+ } catch (e) {
61
+ if (dir === root) {
62
+ if (e.code === "ENOENT" || e.code === "ENOTDIR") out.exists = false;
63
+ else out.denied = true;
64
+ } else out.unreadable += 1;
65
+ continue;
66
+ }
67
+ entries += list.length;
68
+ for (const d of list) {
69
+ if (d.isSymbolicLink()) continue;
70
+ const full = path.join(dir, d.name);
71
+ if (d.isDirectory()) {
72
+ if (top && !asBundle && BUNDLE.test(d.name)) {
73
+ const inner = await walk(full, true);
74
+ keep({ rel: path.relative(root, full), bytes: inner.bytes, mtimeMs: inner.newest, bundle: true });
75
+ } else stack.push(full);
76
+ continue;
77
+ }
78
+ if (!d.isFile()) continue;
79
+ let st;
80
+ try {
81
+ st = fs.lstatSync(full);
82
+ } catch {
83
+ continue;
84
+ }
85
+ const size = realSize(st);
86
+ out.bytes += size;
87
+ out.files += 1;
88
+ subtotal += size;
89
+ if (st.mtimeMs > newest) newest = st.mtimeMs;
90
+ if (now - st.mtimeMs > YEAR_MS) out.oldBytes += size;
91
+ if (!asBundle) keep({ rel: path.relative(root, full), bytes: size, mtimeMs: st.mtimeMs, bundle: false });
92
+ }
93
+ sinceYield += list.length;
94
+ if (sinceYield >= 2000) {
95
+ sinceYield = 0;
96
+ await new Promise((r) => setImmediate(r));
97
+ }
98
+ }
99
+ return { bytes: subtotal, newest };
100
+ }
101
+
102
+ await walk(root, false);
103
+ return out;
104
+ }
105
+
106
+ // ---------- where things are ----------------------------------------------------------------------
107
+
108
+ function linuxUserDirs(home) {
109
+ const dirs = {};
110
+ const text = readText(path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "user-dirs.dirs")) || "";
111
+ const map = { DOWNLOAD: "downloads", DESKTOP: "desktop", DOCUMENTS: "documents", PICTURES: "pictures", VIDEOS: "videos", MUSIC: "music" };
112
+ for (const m of text.matchAll(/^XDG_([A-Z]+)_DIR="?([^"\n]+)"?/gm)) {
113
+ if (map[m[1]]) dirs[map[m[1]]] = m[2].replace(/^\$HOME/, home);
114
+ }
115
+ return dirs;
116
+ }
117
+
118
+ const REAL_FS = /^(ext[234]|xfs|btrfs|f2fs|zfs|ntfs3?|vfat|exfat|fuseblk|apfs|hfsplus|bcachefs)$/;
119
+
120
+ function linuxDrives(home) {
121
+ const seen = new Set();
122
+ const out = [];
123
+ let other = 0;
124
+ for (const m of parseMountinfo(readText("/proc/self/mountinfo"))) {
125
+ if (!REAL_FS.test(m.fstype) || seen.has(m.source) || /^\/(snap|boot|run|sys|proc|dev|var\/lib\/(docker|snapd|containers))(\/|$)/.test(m.mount)) continue;
126
+ seen.add(m.source);
127
+ const space = driveSpace(m.mount);
128
+ if (!space) continue;
129
+ const label = m.mount === "/" ? "System drive" : home === m.mount || home.startsWith(`${m.mount}/`) ? "Home drive" : `Other drive ${(other += 1)}`;
130
+ out.push({ label, system: m.mount === "/", ...space });
131
+ }
132
+ return out;
133
+ }
134
+
135
+ function macDrives() {
136
+ const out = [];
137
+ const main = driveSpace("/System/Volumes/Data") || driveSpace("/");
138
+ if (main) out.push({ label: "Startup disk", system: true, ...main });
139
+ let other = 0;
140
+ try {
141
+ for (const v of fs.readdirSync("/Volumes")) {
142
+ const p = path.join("/Volumes", v);
143
+ try {
144
+ if (fs.realpathSync(p) === "/") continue;
145
+ } catch {
146
+ continue;
147
+ }
148
+ const space = driveSpace(p);
149
+ // Volumes that share the startup disk's space (Recovery, and other parts of the same APFS
150
+ // container) show the same size and free space; they are not another drive.
151
+ const sameContainer = main && space && space.total === main.total && Math.abs(space.free - main.free) <= main.total * 0.001;
152
+ if (space && !sameContainer) out.push({ label: `Other drive ${(other += 1)}`, system: false, ...space });
153
+ }
154
+ } catch {
155
+ /* no /Volumes */
156
+ }
157
+ return out;
158
+ }
159
+
160
+ /** The standard places to measure on this computer, and its drives. Paths stay inside this module. */
161
+ export async function standardPlaces() {
162
+ const home = os.homedir();
163
+ const places = [];
164
+ const add = (key, label, p, kind = "folder") => p && places.push({ key, label, path: p, kind });
165
+ if (PLATFORM === "win32") {
166
+ const j = (await runWinScript("folders")) || {};
167
+ const f = j.folders || {};
168
+ for (const k of FOLDERS) add(k, LABEL[k], f[k] || path.join(home, LABEL[k]));
169
+ const sysDrive = j.systemDrive || process.env.SystemDrive || "C:";
170
+ if (j.sid) add("trash", "Recycle Bin", `${sysDrive}\\$Recycle.Bin\\${j.sid}`, "trash");
171
+ add("temp", "Temporary files", f.temp || os.tmpdir(), "temp");
172
+ if (f.appData) add("phone", "iPhone and iPad backups", path.join(f.appData, "Apple Computer", "MobileSync", "Backup"), "phone");
173
+ add("phone2", "iPhone and iPad backups", path.join(f.profile || home, "Apple", "MobileSync", "Backup"), "phone");
174
+ const drives = arr(j.drives).map((d) => ({ label: `${d.letter}${String(d.letter).toUpperCase() === String(sysDrive).toUpperCase() ? " (system drive)" : d.type === 2 ? " (removable)" : ""}`, system: String(d.letter).toUpperCase() === String(sysDrive).toUpperCase(), total: d.size, free: d.free })).filter((d) => d.total > 0);
175
+ if (!drives.length) {
176
+ const s = driveSpace(`${sysDrive}\\`);
177
+ if (s) drives.push({ label: `${sysDrive} (system drive)`, system: true, ...s });
178
+ }
179
+ return { places, drives, cloudRoots: arr(j.oneDrive) };
180
+ }
181
+ if (PLATFORM === "darwin") {
182
+ for (const k of FOLDERS) add(k, LABEL[k], path.join(home, LABEL[k]));
183
+ add("trash", "Trash", path.join(home, ".Trash"), "trash");
184
+ add("cache", "App caches", path.join(home, "Library", "Caches"), "cache");
185
+ add("temp", "Temporary files", os.tmpdir(), "temp");
186
+ add("phone", "iPhone and iPad backups", path.join(home, "Library", "Application Support", "MobileSync", "Backup"), "phone");
187
+ return { places, drives: macDrives(), cloudRoots: [] };
188
+ }
189
+ const xdg = linuxUserDirs(home);
190
+ for (const k of FOLDERS) add(k, LABEL[k], xdg[k] && xdg[k] !== home && xdg[k] !== `${home}/` ? xdg[k] : path.join(home, LABEL[k]));
191
+ add("trash", "Trash", path.join(process.env.XDG_DATA_HOME || path.join(home, ".local", "share"), "Trash"), "trash");
192
+ add("cache", "App caches", process.env.XDG_CACHE_HOME || path.join(home, ".cache"), "cache");
193
+ add("temp", "Temporary files", os.tmpdir(), "temp");
194
+ return { places, drives: linuxDrives(home), cloudRoots: [] };
195
+ }
196
+
197
+ // ---------- check_disk --------------------------------------------------------------------------
198
+
199
+ export async function gatherDisk({ budgetMs = 20000, info = null } = {}) {
200
+ const t0 = Date.now();
201
+ const where = info || (await standardPlaces());
202
+ const deadline = Date.now() + budgetMs;
203
+ const measured = await Promise.all(where.places.map(async (p) => ({ ...p, ...(await measure(p.path, { deadline })) })));
204
+ // Windows keeps phone backups in one of two places; show them as one line.
205
+ const places = [];
206
+ for (const m of measured) {
207
+ const twin = m.kind === "phone" ? places.find((x) => x.kind === "phone") : null;
208
+ if (twin) {
209
+ for (const k of ["bytes", "files", "oldBytes", "unreadable"]) twin[k] += m[k];
210
+ twin.exists = twin.exists || m.exists;
211
+ twin.partial = twin.partial || m.partial;
212
+ twin.denied = twin.denied && m.denied;
213
+ } else places.push(m);
214
+ }
215
+ const inCloud = (p) => where.cloudRoots.some((r) => r && p.toLowerCase().startsWith(String(r).toLowerCase()));
216
+ return {
217
+ platform: PLATFORM,
218
+ seconds: Math.round((Date.now() - t0) / 1000),
219
+ drives: where.drives,
220
+ // The paths were only needed for counting; they are not kept.
221
+ places: places.map(({ path: p, ...rest }) => ({ ...rest, inCloud: inCloud(p) })),
222
+ };
223
+ }
224
+
225
+ const GB = 1024 ** 3;
226
+ const DENIED_HELP = {
227
+ darwin: "macOS did not let me look. To allow it: System Settings > Privacy & Security > Files and Folders, find the app you are asking from, and switch this folder on.",
228
+ win32: "Windows did not let me look in this folder.",
229
+ linux: "I am not allowed to look in this folder.",
230
+ };
231
+ const DENIED_FULL = "macOS keeps this place private. To allow it: System Settings > Privacy & Security > Full Disk Access, and switch on the app you are asking from.";
232
+
233
+ export function renderDisk(d) {
234
+ const size = (b) => diskSize(b, d.platform);
235
+ const lines = ["Computer Vitals: disk space check", ""];
236
+ lines.push("Drives");
237
+ if (!d.drives.length) lines.push(" I could not read the drives on this computer.");
238
+ for (const v of d.drives) {
239
+ const usedPct = Math.round(100 * (1 - v.free / v.total));
240
+ lines.push(` ${v.label}: ${size(v.free)} free of ${size(v.total)} (${usedPct}% full)`);
241
+ }
242
+ const shown = d.places.filter((p) => p.exists && (p.denied || p.bytes > 0 || p.kind === "folder"));
243
+ shown.sort((a, b) => Number(a.denied) - Number(b.denied) || b.bytes - a.bytes);
244
+ lines.push("", "Your folders, largest first");
245
+ let total = 0;
246
+ for (const p of shown) {
247
+ if (p.denied) {
248
+ lines.push(` ${p.label}: ${p.kind === "folder" ? DENIED_HELP[d.platform] : d.platform === "darwin" ? DENIED_FULL : DENIED_HELP[d.platform]}`);
249
+ continue;
250
+ }
251
+ total += p.bytes;
252
+ if (!p.files && !p.partial && !p.unreadable) {
253
+ lines.push(` ${p.label}: empty`);
254
+ continue;
255
+ }
256
+ const bits = [`${p.partial ? "at least " : ""}${size(p.bytes)}`, `${p.files.toLocaleString("en-US")} file${p.files === 1 ? "" : "s"}`];
257
+ if (p.kind === "folder" && p.oldBytes >= 0.1 * GB) bits.push(`${size(p.oldBytes)} not changed for over a year`);
258
+ if (p.partial) bits.push("only partly counted: it holds more files than I could count in the time");
259
+ if (p.unreadable) bits.push(`${p.unreadable} subfolder${p.unreadable === 1 ? "" : "s"} I could not open`);
260
+ if (p.inCloud) bits.push("inside OneDrive; files kept online-only are counted at full size");
261
+ lines.push(` ${p.label}: ${bits.join(", ")}`);
262
+ }
263
+ const sys = d.drives.find((v) => v.system);
264
+ if (sys) {
265
+ const used = sys.total - sys.free;
266
+ lines.push(
267
+ "",
268
+ `Together these come to ${size(total)} of the ${size(used)} in use on the system drive. The rest is apps, the system itself, other people's accounts, and anything stored outside these folders. This check does not measure those.`,
269
+ );
270
+ }
271
+
272
+ const steps = [];
273
+ const get = (k) => d.places.find((p) => p.key === k && p.exists && !p.denied);
274
+ const trash = d.places.find((p) => p.kind === "trash" && p.exists && !p.denied);
275
+ if (trash && trash.bytes >= 0.5 * GB) steps.push(`Empty the ${trash.label}. That frees ${size(trash.bytes)} at once.`);
276
+ const dl = get("downloads");
277
+ if (dl && dl.oldBytes >= 1 * GB) steps.push(`Look through Downloads: ${size(dl.oldBytes)} there has not been changed for over a year. Old installers and extra copies can usually go.`);
278
+ const phone = d.places.find((p) => p.kind === "phone" && p.exists && !p.denied);
279
+ if (phone && phone.bytes >= 2 * GB) {
280
+ steps.push(
281
+ `Phone and tablet backups take ${size(phone.bytes)}. Delete backups of devices you no longer own: ${d.platform === "darwin" ? "System Settings > General > Storage > iOS Files" : "in the Apple Devices app or iTunes, under Preferences > Devices"}.`,
282
+ );
283
+ }
284
+ const temp = get("temp");
285
+ if (temp && temp.bytes >= 2 * GB) steps.push(`Temporary files take ${size(temp.bytes)}. ${d.platform === "win32" ? "Clear them in Settings > System > Storage > Temporary files." : "Restarting the computer clears most of them."}`);
286
+ const cache = get("cache");
287
+ if (cache && cache.bytes >= 5 * GB) steps.push(`App caches take ${size(cache.bytes)}. Apps rebuild these, so they are safe to lose, but do not delete them by hand: use the storage tool below, or clear the cache from inside the app that owns it (web browsers have a "clear browsing data" option).`);
288
+ const biggest = shown.filter((p) => p.kind === "folder" && !p.denied && p.bytes >= 5 * GB)[0];
289
+ if (biggest) steps.push(`${biggest.label} is your largest folder. Ask me to list the biggest files in ${biggest.label} to see what is worth removing.`);
290
+ steps.push(
291
+ {
292
+ win32: "Open Settings > System > Storage to see what Windows suggests removing, and turn on Storage Sense so it cleans up by itself. Apps you no longer use can be removed under Settings > Apps > Installed apps, sorted by size.",
293
+ darwin: "Open System Settings > General > Storage. It shows what is using space by kind, with recommendations, and lets you remove apps you no longer use.",
294
+ linux: "The \"Disk Usage Analyzer\" app shows everything on the drive as a picture, including what this check does not measure.",
295
+ }[d.platform] || "Remove apps you no longer use.",
296
+ );
297
+ if (sys && sys.free / sys.total < 0.1) steps.push("Move large files you want to keep, such as videos and photos, to an external drive or cloud storage.");
298
+ lines.push("", "What to do");
299
+ steps.forEach((s, i) => lines.push(`${i + 1}. ${s}`));
300
+ lines.push("", `Nothing was deleted or changed. Only sizes were counted; no file names were read into this report. (Took ${d.seconds} s.)`);
301
+ return lines.join("\n");
302
+ }
303
+
304
+ // ---------- find_large_files -----------------------------------------------------------------------
305
+
306
+ export async function gatherLargeFiles(folder, { budgetMs = 15000, count = 15, info = null } = {}) {
307
+ const key = String(folder || "").toLowerCase().trim();
308
+ if (!FOLDERS.includes(key)) return { ok: false, folder: key };
309
+ const where = info || (await standardPlaces());
310
+ const place = where.places.find((p) => p.key === key);
311
+ if (!place) return { ok: false, folder: key };
312
+ const m = await measure(place.path, { deadline: Date.now() + budgetMs, top: count });
313
+ return { ok: true, platform: PLATFORM, folder: key, label: place.label, ...m };
314
+ }
315
+
316
+ export function age(mtimeMs, now = Date.now()) {
317
+ const days = Math.max(0, Math.floor((now - mtimeMs) / 86400000));
318
+ if (days < 1) return "today";
319
+ if (days < 60) return `${days} day${days === 1 ? "" : "s"} ago`;
320
+ if (days < 730) return `${Math.round(days / 30)} months ago`;
321
+ return `${Math.floor(days / 365)} years ago`;
322
+ }
323
+
324
+ const shorten = (s, max = 72) => (s.length <= max ? s : `${s.slice(0, Math.floor(max / 2) - 2)}...${s.slice(-(Math.ceil(max / 2) - 1))}`);
325
+
326
+ export function renderLargeFiles(r) {
327
+ if (!r.ok) return `Computer Vitals: biggest files\n\nI can only look in one of these folders: ${FOLDERS.join(", ")}.`;
328
+ const head = `Computer Vitals: biggest files in ${r.label}`;
329
+ if (!r.exists) return `${head}\n\nThis computer has no ${r.label} folder in the usual place.`;
330
+ if (r.denied) return `${head}\n\n${DENIED_HELP[r.platform] || DENIED_HELP.linux}`;
331
+ if (!r.top.length) return `${head}\n\nThe folder is empty.`;
332
+ const size = (b) => diskSize(b, r.platform);
333
+ const lines = [head, ""];
334
+ r.top.forEach((f, i) => {
335
+ lines.push(`${String(i + 1).padStart(2)}. ${size(f.bytes).padStart(8)} ${shorten(cleanText(f.rel, 400))}${f.bundle ? " (a library or package: one item)" : ""}, last changed ${age(f.mtimeMs)}`);
336
+ });
337
+ const sum = r.top.reduce((a, f) => a + f.bytes, 0);
338
+ lines.push("", `These ${r.top.length} take ${size(sum)} of the ${r.partial ? "at least " : ""}${size(r.bytes)} in ${r.label} (${r.files.toLocaleString("en-US")} files).`);
339
+ if (r.partial) lines.push("The folder is very large, so I stopped counting at the time limit. There may be bigger files I did not reach.");
340
+ if (r.unreadable) lines.push(`${r.unreadable} subfolder${r.unreadable === 1 ? "" : "s"} could not be opened.`);
341
+ lines.push(
342
+ "",
343
+ `Nothing was deleted or changed. To free space, delete the ones you no longer need, then empty the ${r.platform === "win32" ? "Recycle Bin" : "Trash"}. If you are not sure what a file is, ask before deleting it.`,
344
+ );
345
+ return lines.join("\n");
346
+ }