@iyowei/sweep-node-modules 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,12 +1,37 @@
1
1
  // src/cli.ts
2
- import { lstat as lstat2, mkdir, realpath as realpath3 } from "node:fs/promises";
3
- import { homedir as homedir4 } from "node:os";
2
+ import { lstat as lstat3, mkdir, realpath as realpath3 } from "node:fs/promises";
3
+ import { homedir as homedir5 } from "node:os";
4
4
  import { basename, dirname } from "node:path";
5
5
 
6
+ // src/classify.ts
7
+ import { homedir as homedir3 } from "node:os";
8
+
6
9
  // src/config.ts
7
10
  import { readFile } from "node:fs/promises";
8
11
  import { homedir } from "node:os";
9
12
  import { posix, win32 } from "node:path";
13
+ var DEFAULT_EXCLUDE = [
14
+ ".bun",
15
+ ".npm",
16
+ ".pnpm-store",
17
+ ".yarn",
18
+ ".nvm",
19
+ "nvm",
20
+ ".fnm",
21
+ ".volta",
22
+ ".asdf",
23
+ ".n",
24
+ ".vscode",
25
+ ".vscode-insiders",
26
+ ".vscode-server",
27
+ ".cursor",
28
+ ".antigravity",
29
+ "Library",
30
+ ".local",
31
+ ".config",
32
+ ".cache",
33
+ ".claude"
34
+ ];
10
35
  function platformDefaultPath(platform, env, home) {
11
36
  if (platform === "win32") {
12
37
  const roaming = env.APPDATA || win32.join(env.USERPROFILE || home, "AppData", "Roaming");
@@ -89,7 +114,7 @@ async function loadConfig(path) {
89
114
  state: "ok",
90
115
  config: {
91
116
  roots: raw.roots,
92
- exclude: raw.exclude ?? [],
117
+ exclude: raw.exclude ?? [...DEFAULT_EXCLUDE],
93
118
  include: raw.include ?? []
94
119
  }
95
120
  };
@@ -105,8 +130,230 @@ function mergeNames(configNames, cliNames) {
105
130
  return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
106
131
  }
107
132
 
133
+ // src/guard.ts
134
+ import { lstat, realpath, stat } from "node:fs/promises";
135
+ import { homedir as homedir2 } from "node:os";
136
+ import { posix as posix2, win32 as win322 } from "node:path";
137
+ var POSIX_STYLE = {
138
+ name: "posix",
139
+ ops: posix2,
140
+ caseInsensitive: false
141
+ };
142
+ var WIN32_STYLE = {
143
+ name: "win32",
144
+ ops: win322,
145
+ caseInsensitive: true
146
+ };
147
+ function nativeStyle() {
148
+ return process.platform === "win32" ? WIN32_STYLE : POSIX_STYLE;
149
+ }
150
+ function fold(p, style) {
151
+ return style.caseInsensitive ? p.toLowerCase() : p;
152
+ }
153
+ function dedupeKey(realPath, style) {
154
+ return fold(realPath, style);
155
+ }
156
+ function hasNodeModulesLeaf(target, style) {
157
+ return fold(style.ops.basename(target), style) === "node_modules";
158
+ }
159
+ function insideAnyRoot(realPath, roots, style) {
160
+ return roots.some((root) => {
161
+ const rel = style.ops.relative(fold(root, style), fold(realPath, style));
162
+ if (rel === "" || style.ops.isAbsolute(rel))
163
+ return false;
164
+ return rel !== ".." && !rel.startsWith(`..${style.ops.sep}`);
165
+ });
166
+ }
167
+ function isFilesystemRootBody(realPath, style) {
168
+ return fold(style.ops.parse(realPath).root, style) === fold(realPath, style);
169
+ }
170
+ function isHomeBody(realPath, home, style) {
171
+ return home !== null && dedupeKey(realPath, style) === dedupeKey(home, style);
172
+ }
173
+ function firstSymlinkOnAnchor(links) {
174
+ for (const link of links) {
175
+ if (link.symlink)
176
+ return link.path;
177
+ }
178
+ return null;
179
+ }
180
+ function anchorChainPaths(root, style) {
181
+ const absolute = style.ops.isAbsolute(root) ? root : style.ops.resolve(root);
182
+ const prefix = style.ops.parse(absolute).root;
183
+ const chain = [];
184
+ let cursor = prefix;
185
+ for (const part of absolute.slice(prefix.length).split(style.ops.sep)) {
186
+ if (part === "")
187
+ continue;
188
+ cursor = style.ops.join(cursor, part);
189
+ chain.push(cursor);
190
+ }
191
+ return chain;
192
+ }
193
+ async function tryRealpath(p) {
194
+ try {
195
+ return await realpath(p);
196
+ } catch {
197
+ return null;
198
+ }
199
+ }
200
+ async function collectAnchorLinks(root, style) {
201
+ const links = [];
202
+ for (const path of anchorChainPaths(root, style)) {
203
+ try {
204
+ links.push({ path, symlink: (await lstat(path)).isSymbolicLink() });
205
+ } catch {}
206
+ }
207
+ return links;
208
+ }
209
+ async function firstSymlinkOnTarget(target) {
210
+ return firstSymlinkOnAnchor(await collectAnchorLinks(target, nativeStyle()));
211
+ }
212
+ async function firstSymlinkOnRoot(root) {
213
+ return firstSymlinkOnTarget(root);
214
+ }
215
+ async function validateTargets(targets, options) {
216
+ const style = options.style ?? nativeStyle();
217
+ const homeOption = options.home === undefined ? homedir2() : options.home;
218
+ const anchors = [];
219
+ for (const root of options.roots) {
220
+ anchors.push({
221
+ configured: root,
222
+ real: await tryRealpath(root),
223
+ link: firstSymlinkOnAnchor(await collectAnchorLinks(root, style))
224
+ });
225
+ }
226
+ const brokenAnchors = anchors.filter((anchor) => anchor.real !== null && anchor.link !== null);
227
+ const roots = [];
228
+ for (const anchor of anchors) {
229
+ if (anchor.real !== null)
230
+ roots.push(anchor.real);
231
+ }
232
+ const home = homeOption === null ? null : await tryRealpath(homeOption) ?? homeOption;
233
+ const accepted = [];
234
+ const rejected = [];
235
+ const seen = new Set;
236
+ for (const target of targets) {
237
+ if (!hasNodeModulesLeaf(target, style)) {
238
+ rejected.push({ target, reason: "路径末段不是 node_modules" });
239
+ continue;
240
+ }
241
+ const real = await tryRealpath(target);
242
+ if (real === null) {
243
+ rejected.push({ target, reason: "realpath 失败 (目标不存在或不可读)" });
244
+ continue;
245
+ }
246
+ const brokenAnchor = brokenAnchors.find((anchor) => insideAnyRoot(real, [anchor.real], style));
247
+ if (brokenAnchor !== undefined) {
248
+ rejected.push({
249
+ target,
250
+ reason: `根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`
251
+ });
252
+ continue;
253
+ }
254
+ if (isFilesystemRootBody(real, style)) {
255
+ rejected.push({ target, reason: "目标是文件系统根本体" });
256
+ continue;
257
+ }
258
+ if (isHomeBody(real, home, style)) {
259
+ rejected.push({ target, reason: "目标是 home 本体" });
260
+ continue;
261
+ }
262
+ if (!hasNodeModulesLeaf(real, style)) {
263
+ rejected.push({ target, reason: "realpath 后的末段不是 node_modules" });
264
+ continue;
265
+ }
266
+ if (!insideAnyRoot(real, roots, style)) {
267
+ rejected.push({ target, reason: "realpath 后不在任何 root 之下" });
268
+ continue;
269
+ }
270
+ const key = dedupeKey(real, style);
271
+ if (seen.has(key)) {
272
+ rejected.push({ target, reason: "重复目标 (realpath 去重)" });
273
+ continue;
274
+ }
275
+ seen.add(key);
276
+ accepted.push(real);
277
+ }
278
+ return { accepted, rejected };
279
+ }
280
+ var fsDeviceProbe = async (path, follow) => {
281
+ try {
282
+ return (await (follow ? stat : lstat)(path)).dev;
283
+ } catch {
284
+ return null;
285
+ }
286
+ };
287
+ function owningRoot(target, roots, style) {
288
+ let best = null;
289
+ for (const root of roots) {
290
+ if (!insideAnyRoot(target, [root], style))
291
+ continue;
292
+ if (best === null || root.length > best.length)
293
+ best = root;
294
+ }
295
+ return best;
296
+ }
297
+ async function findCrossDeviceTargets(targets, options) {
298
+ const style = options.style ?? nativeStyle();
299
+ const probe = options.probe ?? fsDeviceProbe;
300
+ const devices = new Map;
301
+ const found = new Map;
302
+ for (const target of targets) {
303
+ const root = owningRoot(target, options.roots, style);
304
+ if (root === null)
305
+ continue;
306
+ let rootDev = devices.get(root);
307
+ if (rootDev === undefined) {
308
+ rootDev = await probe(root, true);
309
+ devices.set(root, rootDev);
310
+ }
311
+ if (rootDev === null)
312
+ continue;
313
+ const targetDev = await probe(target, false);
314
+ if (targetDev === null || targetDev === rootDev)
315
+ continue;
316
+ const parentDev = await probe(style.ops.dirname(target), true);
317
+ found.set(target, parentDev !== null && parentDev !== targetDev ? "target-itself" : "on-path");
318
+ }
319
+ return found;
320
+ }
321
+
322
+ // src/classify.ts
323
+ var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
324
+ var INSTALL_TREE_SEGMENTS = new Set([...DEFAULT_EXCLUDE, "extensions", "_npx"].map((name) => name.toLowerCase()));
325
+ function classifyTarget(target, options = {}) {
326
+ const style = options.style ?? nativeStyle();
327
+ const homeOption = options.home === undefined ? homedir3() : options.home;
328
+ const parts = target.split(style.ops.sep).filter((part) => part !== "");
329
+ const ancestors = parts.slice(0, -1);
330
+ for (const segment of ancestors) {
331
+ if (INSTALL_TREE_SEGMENTS.has(segment.toLowerCase()))
332
+ return {
333
+ kind: "suspect-install-tree",
334
+ reason: `位于 ${segment} 安装树目录`
335
+ };
336
+ }
337
+ const parent = ancestors[ancestors.length - 1];
338
+ if (parent !== undefined && parent.toLowerCase() === "lib")
339
+ return {
340
+ kind: "suspect-install-tree",
341
+ reason: "父目录为 lib, 形如版本管理器的 node 安装树"
342
+ };
343
+ if (homeOption !== null) {
344
+ const relative = style.ops.relative(fold2(homeOption, style), fold2(target, style));
345
+ const [first] = relative.split(style.ops.sep);
346
+ if (first !== undefined && first !== ".." && first !== "." && first.startsWith(".") && !style.ops.isAbsolute(relative))
347
+ return {
348
+ kind: "suspect-install-tree",
349
+ reason: `位于 ${first} (家目录下的隐藏目录)`
350
+ };
351
+ }
352
+ return { kind: "project" };
353
+ }
354
+
108
355
  // src/delete.ts
109
- import { lstat, rm } from "node:fs/promises";
356
+ import { lstat as lstat2, rm } from "node:fs/promises";
110
357
  import { isAbsolute, join, relative, sep } from "node:path";
111
358
  var ERROR_HINTS = {
112
359
  EACCES: "权限不足, 拒绝删除",
@@ -133,6 +380,18 @@ function describeReviewError(target, path, error) {
133
380
  function describeVanishedReview(target, path) {
134
381
  return `安全复核未完成 (ENOENT: 路径组件消失) (目标: ${target}; 组件: ${path}; 请复查目标是否仍存在; 未执行删除; 若目标确已不存在, 可忽略此条)`;
135
382
  }
383
+ async function checkGone(path) {
384
+ try {
385
+ await lstat2(path);
386
+ return "present";
387
+ } catch (error) {
388
+ return error?.code === "ENOENT" ? "gone" : "unknown";
389
+ }
390
+ }
391
+ function describeSurvivor(target, state) {
392
+ const review = state === "present" ? "复核确认目标仍存在" : "目标是否仍存在未能核验";
393
+ return `ENOENT: 删除中途失败 (${review}) (目标: ${target}; ${PARTIAL_DELETION_HINT})`;
394
+ }
136
395
  function isUnder(root, target) {
137
396
  const rel = relative(root, target);
138
397
  if (rel === "" || isAbsolute(rel))
@@ -148,10 +407,17 @@ function componentChain(root, target) {
148
407
  }
149
408
  return chain;
150
409
  }
410
+ async function isSymlinkHead(path) {
411
+ try {
412
+ return (await lstat2(path)).isSymbolicLink();
413
+ } catch {
414
+ return false;
415
+ }
416
+ }
151
417
  async function reviewComponents(chain) {
152
418
  for (const path of chain) {
153
419
  try {
154
- const stats = await lstat(path);
420
+ const stats = await lstat2(path);
155
421
  if (!stats.isDirectory())
156
422
  return { kind: "unsafe", path };
157
423
  } catch (error) {
@@ -167,7 +433,7 @@ async function removeTargets(targets, options) {
167
433
  const result = { removed: [], missing: [], failed: [] };
168
434
  const roots = options?.roots ?? [];
169
435
  for (const target of targets) {
170
- const root = roots.find((candidate) => isUnder(candidate, target));
436
+ const root = roots.find((candidate) => isUnder(candidate.real, target));
171
437
  if (root === undefined) {
172
438
  result.aborted = {
173
439
  target,
@@ -175,7 +441,14 @@ async function removeTargets(targets, options) {
175
441
  };
176
442
  break;
177
443
  }
178
- const finding = await reviewComponents(componentChain(root, target));
444
+ if (await isSymlinkHead(root.configured)) {
445
+ result.aborted = {
446
+ target,
447
+ reason: `安全复核失败 (根被替换为符号链接): ${root.configured}`
448
+ };
449
+ break;
450
+ }
451
+ const finding = await reviewComponents(componentChain(root.real, target));
179
452
  if (finding !== null) {
180
453
  if (finding.kind === "vanished") {
181
454
  result.failed.push({
@@ -202,7 +475,15 @@ async function removeTargets(targets, options) {
202
475
  result.removed.push(target);
203
476
  } catch (error) {
204
477
  if (error?.code === "ENOENT") {
205
- result.missing.push(target);
478
+ const state = await checkGone(target);
479
+ if (state === "gone") {
480
+ result.missing.push(target);
481
+ continue;
482
+ }
483
+ result.failed.push({
484
+ target,
485
+ error: describeSurvivor(target, state)
486
+ });
206
487
  continue;
207
488
  }
208
489
  result.failed.push({
@@ -214,108 +495,6 @@ async function removeTargets(targets, options) {
214
495
  return result;
215
496
  }
216
497
 
217
- // src/guard.ts
218
- import { realpath } from "node:fs/promises";
219
- import { homedir as homedir2 } from "node:os";
220
- import { posix as posix2, win32 as win322 } from "node:path";
221
- var POSIX_STYLE = {
222
- name: "posix",
223
- ops: posix2,
224
- caseInsensitive: false
225
- };
226
- var WIN32_STYLE = {
227
- name: "win32",
228
- ops: win322,
229
- caseInsensitive: true
230
- };
231
- function nativeStyle() {
232
- return process.platform === "win32" ? WIN32_STYLE : POSIX_STYLE;
233
- }
234
- function fold(p, style) {
235
- return style.caseInsensitive ? p.toLowerCase() : p;
236
- }
237
- function dedupeKey(realPath, style) {
238
- return fold(realPath, style);
239
- }
240
- function hasNodeModulesLeaf(target, style) {
241
- return fold(style.ops.basename(target), style) === "node_modules";
242
- }
243
- function insideAnyRoot(realPath, roots, style) {
244
- return roots.some((root) => {
245
- const rel = style.ops.relative(fold(root, style), fold(realPath, style));
246
- if (rel === "" || style.ops.isAbsolute(rel))
247
- return false;
248
- return rel !== ".." && !rel.startsWith(`..${style.ops.sep}`);
249
- });
250
- }
251
- function isFilesystemRootBody(realPath, style) {
252
- return fold(style.ops.parse(realPath).root, style) === fold(realPath, style);
253
- }
254
- function isHomeBody(realPath, home, style) {
255
- return home !== null && dedupeKey(realPath, style) === dedupeKey(home, style);
256
- }
257
- async function tryRealpath(p) {
258
- try {
259
- return await realpath(p);
260
- } catch {
261
- return null;
262
- }
263
- }
264
- async function validateTargets(targets, options) {
265
- const style = options.style ?? nativeStyle();
266
- const homeOption = options.home === undefined ? homedir2() : options.home;
267
- const roots = [];
268
- for (const root of options.roots) {
269
- const real = await tryRealpath(root);
270
- if (real !== null)
271
- roots.push(real);
272
- }
273
- const home = homeOption === null ? null : await tryRealpath(homeOption) ?? homeOption;
274
- const accepted = [];
275
- const rejected = [];
276
- const seen = new Set;
277
- for (const target of targets) {
278
- if (!hasNodeModulesLeaf(target, style)) {
279
- rejected.push({ target, reason: "路径末段不是 node_modules" });
280
- continue;
281
- }
282
- const real = await tryRealpath(target);
283
- if (real === null) {
284
- rejected.push({ target, reason: "realpath 失败 (目标不存在或不可读)" });
285
- continue;
286
- }
287
- if (isFilesystemRootBody(real, style)) {
288
- rejected.push({ target, reason: "目标是文件系统根本体" });
289
- continue;
290
- }
291
- if (isHomeBody(real, home, style)) {
292
- rejected.push({ target, reason: "目标是 home 本体" });
293
- continue;
294
- }
295
- if (!hasNodeModulesLeaf(real, style)) {
296
- rejected.push({ target, reason: "realpath 后的末段不是 node_modules" });
297
- continue;
298
- }
299
- if (!insideAnyRoot(real, roots, style)) {
300
- rejected.push({ target, reason: "realpath 后不在任何 root 之下" });
301
- continue;
302
- }
303
- const key = dedupeKey(real, style);
304
- if (seen.has(key)) {
305
- rejected.push({ target, reason: "重复目标 (realpath 去重)" });
306
- continue;
307
- }
308
- seen.add(key);
309
- accepted.push(real);
310
- }
311
- return { accepted, rejected };
312
- }
313
-
314
- // src/init.ts
315
- import { homedir as homedir3 } from "node:os";
316
- import { join as join2 } from "node:path";
317
- import { createInterface } from "node:readline/promises";
318
-
319
498
  // src/render.ts
320
499
  var BANNER = "SWEEP-NM";
321
500
  var BAR_BLOCK = "▍";
@@ -324,7 +503,9 @@ var NEUTRAL_BLOCK = "░";
324
503
  var PLATFORM_STYLE = nativeStyle();
325
504
  var NEUTRAL_TIER = { block: NEUTRAL_BLOCK, sgr: "2" };
326
505
  var ROOT_LIST_LIMIT = 3;
327
- var TIER_BIG = 1024 ** 3;
506
+ var bannerLine = (suffix, color) => paint(`${BAR_BLOCK} ${BANNER} ${suffix}`, "1;7", color);
507
+ var neutralLine = (text, color) => ` ${paint(`${NEUTRAL_BLOCK} ${text}`, "2", color)}`;
508
+ var TIER_BIG = 512 * 1024 ** 2;
328
509
  var TIER_MID = 100 * 1024 ** 2;
329
510
  function formatBytes(bytes) {
330
511
  if (bytes < 1024)
@@ -341,29 +522,31 @@ function formatBytes(bytes) {
341
522
  function render(options) {
342
523
  const { mode, roots, entries, color, home, releasedBytes, pathStyle } = options;
343
524
  const style = pathStyle ?? PLATFORM_STYLE;
344
- const scope = roots.length > 0 && roots.length <= ROOT_LIST_LIMIT ? `${roots.length} 个根: ${roots.map((root) => oneLine(shortenPath(root, style, home))).join(" · ")}` : `${roots.length} 个根`;
345
- const runtime = options.runtime ? ` · ${oneLine(options.runtime)}` : "";
346
- const head = paint(`${BAR_BLOCK} ${BANNER} ${mode === "execute" ? "执行" : "预览"} · ${scope}${runtime}`, "1;7", color);
347
- const notes = (options.notes ?? []).map((note) => ` ${paint(`${NEUTRAL_BLOCK} ${oneLine(note)}`, "2", color)}`);
525
+ const scope = roots.length > 0 && roots.length <= ROOT_LIST_LIMIT ? `${roots.length} 个根: ${roots.map((root) => sanitizeLine(shortenPath(root, style, home))).join(" · ")}` : `${roots.length} 个根`;
526
+ const runtime = options.runtime ? ` · ${sanitizeLine(options.runtime)}` : "";
527
+ const head = bannerLine(`${mode === "execute" ? "执行" : "预览"} · ${scope}${runtime}`, color);
528
+ const notes = (options.notes ?? []).map((note) => neutralLine(sanitizeLine(note), color));
529
+ const trailer = (options.trailer ?? []).map((line) => neutralLine(sanitizeLine(line), color));
348
530
  if (entries.length === 0) {
349
531
  return [
350
532
  head,
351
533
  ...notes,
352
- ` ${paint(`${NEUTRAL_BLOCK} 未发现 node_modules`, "2", color)}`
534
+ ` ${paint(`${NEUTRAL_BLOCK} 未发现 node_modules`, "2", color)}`,
535
+ ...trailer
353
536
  ].join(`
354
537
  `);
355
538
  }
356
539
  const rows = [...entries].sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1));
357
540
  const volumeWidth = Math.max(...rows.map((row) => displayWidth(volumeOf(row))));
358
- const nameWidth = Math.max(...rows.map((row) => displayWidth(oneLine(row.project))));
541
+ const nameWidth = Math.max(...rows.map((row) => displayWidth(sanitizeLine(row.project))));
359
542
  const body = rows.map((row) => {
360
543
  const fail = mode === "execute" && row.ok === false;
361
544
  const tier = row.bytes === undefined ? NEUTRAL_TIER : tierOf(row.bytes);
362
545
  const mark = mode === "execute" ? paint(fail ? "✗" : "✓", fail ? "31" : "32", color) : paint(tier.block, tier.sgr, color);
363
546
  const volume = padStart(volumeOf(row), volumeWidth);
364
- const name = oneLine(row.project);
365
- const rawPath = displayPath(row.target, style, home);
366
- const path = oneLine(rawPath);
547
+ const name = sanitizeLine(row.project);
548
+ const rawPath = displayPath(row.target, style, home, row.suspect === true);
549
+ const path = sanitizeLine(rawPath);
367
550
  const rewritten = name !== row.project || path !== rawPath;
368
551
  const tail = tailsOf(row, fail, rewritten);
369
552
  const shown = `${paint(padEnd(name, nameWidth), "1", color)} ${paint(path, "2", color)}`;
@@ -375,7 +558,7 @@ function render(options) {
375
558
  paint("执行删除", "2", color)
376
559
  ].join(" ");
377
560
  const foot = mode === "execute" ? footExecute(rows, color, releasedBytes) : ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`合计 ${rows.length} 处 · ${formatBytes(sum(rows))}`, "1", color)} ${hint}`;
378
- return [head, ...notes, ...body, foot].join(`
561
+ return [head, ...notes, ...body, foot, ...trailer].join(`
379
562
  `);
380
563
  }
381
564
  function footExecute(rows, color, releasedBytes) {
@@ -390,9 +573,9 @@ function tailsOf(row, fail, rewritten) {
390
573
  if (rewritten)
391
574
  parts.push(SANITIZED_NOTE);
392
575
  if (row.note)
393
- parts.push(oneLine(row.note));
576
+ parts.push(sanitizeLine(row.note));
394
577
  if (fail && row.error)
395
- parts.push(oneLine(row.error));
578
+ parts.push(sanitizeLine(row.error));
396
579
  return parts.join(" ");
397
580
  }
398
581
  function tierOf(bytes) {
@@ -404,24 +587,28 @@ function tierOf(bytes) {
404
587
  }
405
588
  var paint = (text, sgr, color) => color ? `\x1B[${sgr}m${text}\x1B[0m` : text;
406
589
  var sum = (rows) => rows.reduce((total, row) => total + (row.bytes ?? 0), 0);
407
- var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
590
+ var fold3 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
408
591
  function shortenPath(path, style, home) {
409
592
  if (!home)
410
593
  return path;
411
- if (fold2(path, style) === fold2(home, style))
594
+ if (fold3(path, style) === fold3(home, style))
412
595
  return "~";
413
596
  const prefix = `${home}${style.ops.sep}`;
414
- return fold2(path, style).startsWith(fold2(prefix, style)) ? `~${path.slice(home.length)}` : path;
597
+ return fold3(path, style).startsWith(fold3(prefix, style)) ? `~${path.slice(home.length)}` : path;
415
598
  }
416
599
  function shortenHome(path, home) {
417
600
  return shortenPath(path, PLATFORM_STYLE, home);
418
601
  }
419
- function displayPath(target, style, home) {
602
+ function displayPath(target, style, home, keepSuffix = false) {
420
603
  const suffix = `${style.ops.sep}node_modules`;
421
- const dir = fold2(target, style).endsWith(fold2(suffix, style)) ? target.slice(0, -suffix.length) : target;
604
+ const dir = keepSuffix || !fold3(target, style).endsWith(fold3(suffix, style)) ? target : target.slice(0, -suffix.length);
422
605
  return shortenPath(dir, style, home);
423
606
  }
424
- var oneLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
607
+ var sanitizeLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
608
+ var sanitizeOutputLine = (text) => {
609
+ const indent = /^[ \t]*/.exec(text)?.[0] ?? "";
610
+ return `${indent}${sanitizeLine(text)}`;
611
+ };
425
612
  var padEnd = (text, width) => text + " ".repeat(Math.max(0, width - displayWidth(text)));
426
613
  var padStart = (text, width) => " ".repeat(Math.max(0, width - displayWidth(text))) + text;
427
614
  function displayWidth(text) {
@@ -436,13 +623,50 @@ function isFullWidth(code) {
436
623
  return code >= 4352 && code <= 4447 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65135 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510;
437
624
  }
438
625
 
626
+ // src/help.ts
627
+ var COMMAND_COLUMN = 25;
628
+ function defaultConfigPath() {
629
+ return resolveConfigPath({ env: {} }).path;
630
+ }
631
+ function helpText(color) {
632
+ const row = (command, desc) => ` ${command.padEnd(COMMAND_COLUMN)} ${desc}`;
633
+ return [
634
+ bannerLine("工作区 node_modules 清理", color),
635
+ "",
636
+ row("sweep-nm", "预览: 清单 + 体积 + 合计, 零副作用"),
637
+ row("sweep-nm --yes", "执行删除"),
638
+ row("sweep-nm --force", "连同疑似安装树一并删除 (默认跳过)"),
639
+ row("sweep-nm --exclude <name>", "临时追加排除 (可重复, 与配置合并)"),
640
+ row("sweep-nm --include <name>", "只清理命中名单的目录 (可重复, 与配置合并)"),
641
+ row("sweep-nm --config <path>", "指定配置文件 (优先于 SWEEP_NM_CONFIG)"),
642
+ row("sweep-nm config", "查看实际生效的配置: 来源 + 路径 + 文件状态"),
643
+ row("sweep-nm init", "初始化向导: 交互生成配置文件"),
644
+ row("sweep-nm --help", "帮助"),
645
+ "",
646
+ "说明:",
647
+ " --exclude 按目录名精确匹配 (区分大小写), 从根到命中点的任意一级命中即跳过",
648
+ " --include 同款匹配口径, 命中才纳入; 同时命中 exclude 的照旧跳过",
649
+ " 配置未写 exclude 字段时使用内置默认名单 (包管理器 / 版本管理器 / 编辑器扩展等安装树目录)",
650
+ " --force 只放行「疑似安装树」(安装树形态的目标), 不放宽删除安全闸",
651
+ " 删除侧要求扫描根为真实路径 (根及其祖先链不含符号链接): 命中 (如 /tmp、/var 形态) 则 --yes 整批拒绝, 改写为真实路径形态 (如 /private/tmp/x) 即放行",
652
+ ` 默认配置位置 (平台自适应; 用了 --config 或 SWEEP_NM_CONFIG 时实际读的不是它): ${sanitizeLine(defaultConfigPath())}`,
653
+ " 查实际生效的路径: sweep-nm config",
654
+ "",
655
+ "退出码: 0 成功 (含预览与空结果); 1 删除失败或跳过 / 配置损坏 / 参数错误"
656
+ ].join(`
657
+ `);
658
+ }
659
+
439
660
  // src/init.ts
661
+ import { homedir as homedir4 } from "node:os";
662
+ import { join as join2 } from "node:path";
663
+ import { createInterface } from "node:readline/promises";
440
664
  var WHITESPACE = /\s/;
441
665
  function expandHome(token) {
442
666
  if (token === "~")
443
- return homedir3();
667
+ return homedir4();
444
668
  if (token.startsWith("~/") || token.startsWith("~\\"))
445
- return join2(homedir3(), token.slice(2));
669
+ return join2(homedir4(), token.slice(2));
446
670
  return token;
447
671
  }
448
672
  function splitAnswer(answer) {
@@ -486,48 +710,77 @@ function parseList(answer, fallback) {
486
710
  return items.length > 0 ? items : [...fallback];
487
711
  }
488
712
  async function runInit(deps) {
489
- const { configPath, fileExists, writeFile, io } = deps;
713
+ const {
714
+ configPath,
715
+ fileExists,
716
+ firstSymlinkOnRoot,
717
+ firstSymlinkOnTarget,
718
+ writeFile,
719
+ io
720
+ } = deps;
721
+ const { color } = io;
490
722
  function cancelled() {
491
723
  io.print("已取消, 未写入配置");
492
724
  return { state: "cancelled" };
493
725
  }
726
+ io.print(bannerLine("初始化向导", color));
494
727
  if (await fileExists(configPath)) {
495
- const overwrite = await io.confirm(`配置已存在 (${configPath}), 是否覆盖?`, false);
728
+ const overwrite = await io.confirm(`配置已存在 (${sanitizeLine(configPath)}), 是否覆盖?`, false);
496
729
  if (!overwrite)
497
730
  return { state: "declined-overwrite" };
498
731
  }
499
- io.print("首次使用, 先确定扫描范围");
500
- const home = homedir3();
732
+ io.print(neutralLine("首次使用, 先确定扫描范围", color));
733
+ const home = homedir4();
501
734
  let roots = [];
502
735
  for (;; ) {
503
- const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${home}`);
736
+ const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${sanitizeLine(shortenHome(home, home))}`);
504
737
  if (rootsAnswer === null)
505
738
  return cancelled();
506
739
  roots = parseList(rootsAnswer, [home]);
507
740
  const missing = [];
741
+ const symlinked = [];
508
742
  for (const root of roots) {
509
- if (!await fileExists(root))
743
+ if (!await fileExists(root)) {
510
744
  missing.push(root);
745
+ continue;
746
+ }
747
+ const link = await firstSymlinkOnRoot(root);
748
+ if (link !== null)
749
+ symlinked.push({ root, link });
511
750
  }
512
- if (missing.length === 0)
751
+ if (missing.length === 0 && symlinked.length === 0)
513
752
  break;
514
753
  for (const path of missing)
515
- io.print(`根不存在: ${path}`);
754
+ io.print(` ${paint("✗", "31", color)} 根不存在: ${sanitizeLine(path)}`);
755
+ for (const item of symlinked)
756
+ io.print(` ${paint("✗", "31", color)} 根锚点链上有符号链接: ${sanitizeLine(item.link)} (根: ${sanitizeLine(item.root)}); 删除侧要求真实路径, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`);
516
757
  }
517
- const excludeAnswer = await io.ask("排除名单 (目录名, 可留空)", "回车跳过");
758
+ const excludeAnswer = await io.ask("排除名单 (目录名)", `回车采用默认名单 (${DEFAULT_EXCLUDE.length} 条)`);
518
759
  if (excludeAnswer === null)
519
760
  return cancelled();
520
- const exclude = parseList(excludeAnswer, []);
521
- io.print(`将写入 roots: ${JSON.stringify(roots)} · exclude: ${JSON.stringify(exclude)}`);
522
- if (!await io.confirm("确认写入?", true))
761
+ const exclude = parseList(excludeAnswer, [...DEFAULT_EXCLUDE]);
762
+ const includeAnswer = await io.ask("包含名单 (目录名, 可留空)", "回车跳过");
763
+ if (includeAnswer === null)
523
764
  return cancelled();
524
- const config = { roots, exclude, include: [] };
765
+ const include = parseList(includeAnswer, []);
766
+ io.print(neutralLine(`将写入 ${roots.length} 个扫描根 · 排除 ${exclude.length} 条 · 包含 ${include.length} 条`, color));
767
+ for (;; ) {
768
+ if (!await io.confirm("确认写入?", true))
769
+ return cancelled();
770
+ const link = await firstSymlinkOnTarget(configPath);
771
+ if (link === null)
772
+ break;
773
+ io.print(` ${paint("✗", "31", color)} 配置路径锚点链上有符号链接: ${sanitizeLine(link)} (配置: ${sanitizeLine(configPath)}); 写入会跟随符号链接改写其目标, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`);
774
+ }
775
+ const config = { roots, exclude, include };
525
776
  const text = `${JSON.stringify(config, null, 2)}
526
777
  `;
527
778
  await writeFile(configPath, text);
528
- io.print(`配置已写入: ${shortenHome(configPath, homedir3())}`);
779
+ io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath, homedir4()))} ${paint("✓", "32", color)}`);
529
780
  io.print("");
530
- io.print(text.trimEnd());
781
+ io.print(text.trimEnd().split(`
782
+ `).map((line) => ` ${line}`).join(`
783
+ `));
531
784
  io.print("");
532
785
  return { state: "written", config };
533
786
  }
@@ -536,7 +789,7 @@ function setStdinRef(shouldRef) {
536
789
  if (typeof fn === "function")
537
790
  fn.call(process.stdin);
538
791
  }
539
- function createReadlineIO() {
792
+ function createReadlineIO(color) {
540
793
  const buffered = [];
541
794
  let rl = null;
542
795
  let ended = false;
@@ -572,8 +825,13 @@ function createReadlineIO() {
572
825
  return created;
573
826
  }
574
827
  function readLine(prompt) {
575
- if (ended)
576
- return Promise.resolve(null);
828
+ if (ended) {
829
+ const bufferedLine = buffered.shift();
830
+ if (bufferedLine === undefined)
831
+ return Promise.resolve(null);
832
+ process.stdout.write(prompt);
833
+ return Promise.resolve(bufferedLine);
834
+ }
577
835
  const created = ensure();
578
836
  created.setPrompt(prompt);
579
837
  created.prompt();
@@ -586,13 +844,14 @@ function createReadlineIO() {
586
844
  });
587
845
  }
588
846
  return {
847
+ color,
589
848
  ask(question, hint) {
590
- const prompt = hint === undefined ? `${question} ` : `${question} [${hint}] `;
849
+ const prompt = hint === undefined ? ` ${question} ` : ` ${question} [${paint(hint, "2", color)}] `;
591
850
  return readLine(prompt);
592
851
  },
593
852
  async confirm(question, defaultYes) {
594
- const mark = defaultYes ? "(Y/n)" : "(y/N)";
595
- const answer = await readLine(`${question} ${mark} `);
853
+ const mark = paint(defaultYes ? "(Y/n)" : "(y/N)", "2", color);
854
+ const answer = await readLine(` ${question} ${mark} `);
596
855
  if (answer === null)
597
856
  return false;
598
857
  const normalized = answer.trim().toLowerCase();
@@ -622,7 +881,7 @@ async function writeTextFile(path, text) {
622
881
  }
623
882
 
624
883
  // src/scan-parallel.ts
625
- import { readdir, realpath as realpath2, stat } from "node:fs/promises";
884
+ import { readdir, realpath as realpath2, stat as stat2 } from "node:fs/promises";
626
885
  import { join as join3 } from "node:path";
627
886
  var NODE_MODULES = "node_modules";
628
887
  var GIT_DIR = ".git";
@@ -752,7 +1011,7 @@ function createParallelScanner() {
752
1011
  let key;
753
1012
  try {
754
1013
  const resolved = await realpath2(root);
755
- if (!(await stat(resolved)).isDirectory()) {
1014
+ if (!(await stat2(resolved)).isDirectory()) {
756
1015
  warnings.push(`根不是目录, 已跳过: ${root}`);
757
1016
  continue;
758
1017
  }
@@ -797,7 +1056,9 @@ import { accessSync, constants } from "node:fs";
797
1056
  var DU_PROBES = ["/usr/bin/du", "/bin/du"];
798
1057
  var hasControlChar = (target) => target.includes(`
799
1058
  `) || target.includes("\r");
800
- function findDu() {
1059
+ function findDu(platform = process.platform) {
1060
+ if (platform === "win32")
1061
+ return null;
801
1062
  for (const probe of DU_PROBES) {
802
1063
  try {
803
1064
  accessSync(probe, constants.X_OK);
@@ -843,6 +1104,32 @@ function parseDuSizes(stdout) {
843
1104
  }
844
1105
  return { sizes, duplicated };
845
1106
  }
1107
+ function assessDuOutput(stdout, safeTargets) {
1108
+ const safeSet = new Set(safeTargets);
1109
+ const parsed = parseDuSizes(stdout);
1110
+ let unexpected = false;
1111
+ for (const path of parsed.sizes.keys()) {
1112
+ if (!safeSet.has(path))
1113
+ unexpected = true;
1114
+ }
1115
+ const intact = !parsed.duplicated && parsed.sizes.size <= safeTargets.length && !unexpected;
1116
+ return {
1117
+ sizes: parsed.sizes,
1118
+ intact,
1119
+ duplicated: parsed.duplicated,
1120
+ unexpected
1121
+ };
1122
+ }
1123
+ function describeAnomaly(assessment) {
1124
+ const shapes = [];
1125
+ if (assessment.duplicated)
1126
+ shapes.push("同一路径多行");
1127
+ if (assessment.unexpected)
1128
+ shapes.push("含输入之外的路径");
1129
+ if (shapes.length === 0)
1130
+ shapes.push("行数与输入不符");
1131
+ return shapes.join(" / ");
1132
+ }
846
1133
  function describeDuFailure(detail) {
847
1134
  if (/no such file or directory/i.test(detail))
848
1135
  return { reason: "不存在", missing: true };
@@ -865,8 +1152,7 @@ function parseDuErrorLine(line) {
865
1152
  return null;
866
1153
  return { path, detail };
867
1154
  }
868
- function createDuSizer() {
869
- const bin = findDu();
1155
+ function createDuSizer(bin = findDu()) {
870
1156
  return {
871
1157
  name: "du",
872
1158
  async measure(targets) {
@@ -893,9 +1179,12 @@ function createDuSizer() {
893
1179
  let intact = true;
894
1180
  if (safeTargets.length > 0) {
895
1181
  const { stdout, stderr } = await runDu(bin, safeTargets);
896
- const parsed = parseDuSizes(stdout);
897
- intact = !parsed.duplicated && parsed.sizes.size <= safeTargets.length && [...parsed.sizes.keys()].every((path) => safeSet.has(path));
898
- for (const [path, bytes] of parsed.sizes)
1182
+ const assessment = assessDuOutput(stdout, safeTargets);
1183
+ intact = assessment.intact;
1184
+ if (!intact) {
1185
+ warnings.push(`du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${safeTargets.length} 个目标的体积均未采信`);
1186
+ }
1187
+ for (const [path, bytes] of assessment.sizes)
899
1188
  sizes.set(path, bytes);
900
1189
  for (const line of stderr.split(`
901
1190
  `)) {
@@ -945,7 +1234,7 @@ function createDuSizer() {
945
1234
  }
946
1235
 
947
1236
  // src/size-js.ts
948
- import { readdir as readdir2, stat as stat2 } from "node:fs/promises";
1237
+ import { readdir as readdir2, stat as stat3 } from "node:fs/promises";
949
1238
  import { join as join4 } from "node:path";
950
1239
  function describeFailure(code) {
951
1240
  switch (code) {
@@ -979,7 +1268,7 @@ async function sumEntries(dirents, dir, warnings) {
979
1268
  }
980
1269
  } else if (dirent.isFile()) {
981
1270
  try {
982
- total += (await stat2(path)).size;
1271
+ total += (await stat3(path)).size;
983
1272
  } catch (error) {
984
1273
  warnings.push(`体积统计失败 (${describeFailure(errorCode(error))}): ${path}`);
985
1274
  }
@@ -1022,12 +1311,63 @@ function createSizer() {
1022
1311
  return findDu() !== null ? createDuSizer() : createJsSizer();
1023
1312
  }
1024
1313
 
1314
+ // src/skip.ts
1315
+ var SUSPECT_HINT = "已跳过 (加 --force 一并清理)";
1316
+ var CROSS_DEVICE_NOTES = {
1317
+ "on-path": "跨设备: 根与目标之间有挂载点",
1318
+ "target-itself": "跨设备: 目标本体即挂载点"
1319
+ };
1320
+ var CROSS_DEVICE_HINTS = {
1321
+ "on-path": "已跳过 (把该挂载点声明为独立根即可清理)",
1322
+ "target-itself": "已跳过 (挂载点无法删除, 需先卸载该卷)"
1323
+ };
1324
+ var CROSS_DEVICE_TRAILER_ACTIONS = {
1325
+ "on-path": "把根与目标之间的挂载点声明为独立根即可清理",
1326
+ "target-itself": "目标本体即挂载点, 需先卸载该卷"
1327
+ };
1328
+ function crossDeviceNote(kind) {
1329
+ return CROSS_DEVICE_NOTES[kind];
1330
+ }
1331
+ function skipsBatch(entry, crossDevice, force) {
1332
+ if (crossDevice.has(entry.target))
1333
+ return true;
1334
+ return entry.suspect === true && !force;
1335
+ }
1336
+ function deletionBatch(entries, crossDevice, force) {
1337
+ return entries.filter((entry) => entry.bytes !== undefined && !skipsBatch(entry, crossDevice, force)).map((entry) => entry.target);
1338
+ }
1339
+ function collectSkips(entries, crossDevice, force) {
1340
+ const suspectSkipped = force ? [] : entries.filter((entry) => entry.suspect === true);
1341
+ const deviceSkipped = entries.filter((entry) => crossDevice.has(entry.target));
1342
+ const trailer = [
1343
+ ...suspectSkipped.length > 0 ? [`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`] : [],
1344
+ ...["on-path", "target-itself"].flatMap((kind) => {
1345
+ const count = deviceSkipped.filter((entry) => crossDevice.get(entry.target) === kind).length;
1346
+ return count === 0 ? [] : [
1347
+ `跨设备目标 ${count} 处默认跳过 (${CROSS_DEVICE_TRAILER_ACTIONS[kind]})`
1348
+ ];
1349
+ })
1350
+ ];
1351
+ const hints = new Map;
1352
+ for (const entry of suspectSkipped) {
1353
+ if (entry.bytes !== undefined)
1354
+ hints.set(entry.target, SUSPECT_HINT);
1355
+ }
1356
+ for (const entry of deviceSkipped) {
1357
+ const kind = crossDevice.get(entry.target);
1358
+ if (entry.bytes !== undefined && kind !== undefined) {
1359
+ hints.set(entry.target, CROSS_DEVICE_HINTS[kind]);
1360
+ }
1361
+ }
1362
+ return { trailer, hints };
1363
+ }
1364
+
1025
1365
  // src/cli.ts
1026
- var COMMAND_COLUMN = 25;
1027
1366
  function parseArgs(argv) {
1028
1367
  const options = {
1029
1368
  command: "sweep",
1030
1369
  yes: false,
1370
+ force: false,
1031
1371
  exclude: [],
1032
1372
  include: [],
1033
1373
  help: false
@@ -1041,6 +1381,10 @@ function parseArgs(argv) {
1041
1381
  options.yes = true;
1042
1382
  continue;
1043
1383
  }
1384
+ if (arg === "--force") {
1385
+ options.force = true;
1386
+ continue;
1387
+ }
1044
1388
  if (arg === "--help" || arg === "-h") {
1045
1389
  options.help = true;
1046
1390
  continue;
@@ -1064,11 +1408,11 @@ function parseArgs(argv) {
1064
1408
  positionals.push(arg);
1065
1409
  }
1066
1410
  const [only] = positionals;
1067
- if (positionals.length > 1 || only !== undefined && only !== "init") {
1411
+ if (positionals.length > 1 || only !== undefined && only !== "init" && only !== "config") {
1068
1412
  return { ok: false, message: `未知参数: ${positionals.join(" ")}` };
1069
1413
  }
1070
- if (only === "init")
1071
- options.command = "init";
1414
+ if (only === "init" || only === "config")
1415
+ options.command = only;
1072
1416
  return { ok: true, options };
1073
1417
  }
1074
1418
  function colorEnabled() {
@@ -1082,67 +1426,62 @@ function print(line) {
1082
1426
  `);
1083
1427
  }
1084
1428
  function warn(line, color) {
1085
- process.stderr.write(color ? `${paint("✗", "31", color)} ${line}
1086
- ` : `${line}
1429
+ const text = sanitizeOutputLine(line);
1430
+ process.stderr.write(color ? `${paint("✗", "31", color)} ${text}
1431
+ ` : `${text}
1087
1432
  `);
1088
1433
  }
1089
1434
  function notice(line) {
1090
- process.stderr.write(`${line}
1435
+ process.stderr.write(`${sanitizeOutputLine(line)}
1091
1436
  `);
1092
1437
  }
1093
- function defaultConfigPath() {
1094
- return resolveConfigPath({ env: {} }).path;
1095
- }
1096
- function helpText(color) {
1097
- const row = (command, desc) => ` ${command.padEnd(COMMAND_COLUMN)} ${desc}`;
1098
- return [
1099
- `${paint(`${BAR_BLOCK} SWEEP-NM`, "1;7", color)} 工作区 node_modules 清理`,
1100
- "",
1101
- row("sweep-nm", "预览: 清单 + 体积 + 合计, 零副作用"),
1102
- row("sweep-nm --yes", "执行删除"),
1103
- row("sweep-nm --exclude <name>", "临时追加排除 (可重复, 与配置合并)"),
1104
- row("sweep-nm --include <name>", "只清理命中名单的目录 (可重复, 与配置合并)"),
1105
- row("sweep-nm --config <path>", "指定配置文件 (优先于 SWEEP_NM_CONFIG)"),
1106
- row("sweep-nm init", "初始化向导: 交互生成配置文件"),
1107
- row("sweep-nm --help", "帮助"),
1108
- "",
1109
- "说明:",
1110
- " --exclude 按目录名精确匹配 (区分大小写), 从根到命中点的任意一级命中即跳过",
1111
- " --include 同款匹配口径, 命中才纳入; 同时命中 exclude 的照旧跳过",
1112
- ` 默认配置位置 (平台自适应): ${defaultConfigPath()}`,
1113
- "",
1114
- "退出码: 0 成功 (含预览与空结果); 1 删除失败 / 配置损坏 / 参数错误"
1115
- ].join(`
1116
- `);
1438
+ async function fileExists(path) {
1439
+ try {
1440
+ await lstat3(path);
1441
+ return true;
1442
+ } catch {
1443
+ return false;
1444
+ }
1117
1445
  }
1118
- function runWizard(configPath) {
1446
+ function runWizard(configPath, color) {
1119
1447
  return runInit({
1120
1448
  configPath,
1121
- async fileExists(path) {
1122
- try {
1123
- await lstat2(path);
1124
- return true;
1125
- } catch {
1126
- return false;
1127
- }
1128
- },
1449
+ fileExists,
1450
+ firstSymlinkOnRoot,
1451
+ firstSymlinkOnTarget,
1129
1452
  async writeFile(path, text) {
1130
1453
  await mkdir(dirname(path), { recursive: true });
1131
1454
  await writeTextFile(path, text);
1132
1455
  },
1133
- io: createReadlineIO()
1456
+ io: createReadlineIO(color)
1134
1457
  });
1135
1458
  }
1136
- async function resolveConfig(resolved) {
1459
+ var SOURCE_LABELS = {
1460
+ flag: "--config 指定",
1461
+ env: "环境变量 SWEEP_NM_CONFIG",
1462
+ "platform-default": "平台默认"
1463
+ };
1464
+ async function reportConfig(resolved, color) {
1465
+ const exists = await fileExists(resolved.path);
1466
+ print(bannerLine(`配置 · 来源: ${SOURCE_LABELS[resolved.source]}`, color));
1467
+ print(neutralLine(`配置路径: ${sanitizeLine(resolved.path)}`, color));
1468
+ print(neutralLine(`文件状态: ${exists ? "存在" : "不存在"}`, color));
1469
+ return 0;
1470
+ }
1471
+ async function resolveConfig(resolved, color) {
1137
1472
  const loaded = await loadResolvedConfig(resolved);
1138
1473
  if (loaded.state === "ok")
1139
1474
  return { config: loaded.config, source: "file" };
1140
1475
  if (!interactive())
1141
1476
  return {
1142
- config: { roots: [process.cwd()], exclude: [], include: [] },
1477
+ config: {
1478
+ roots: [process.cwd()],
1479
+ exclude: [...DEFAULT_EXCLUDE],
1480
+ include: []
1481
+ },
1143
1482
  source: "fallback"
1144
1483
  };
1145
- const result = await runWizard(resolved.path);
1484
+ const result = await runWizard(resolved.path, color);
1146
1485
  if (result.state === "written" && result.config !== undefined) {
1147
1486
  return { config: result.config, source: "wizard" };
1148
1487
  }
@@ -1150,10 +1489,13 @@ async function resolveConfig(resolved) {
1150
1489
  return null;
1151
1490
  }
1152
1491
  var ABORTED_HINT = "整批中止, 未执行删除";
1153
- async function realRoots(roots) {
1154
- return Promise.all(roots.map(async (root) => await realpath3(root).catch(() => null) ?? root));
1492
+ async function trustRoots(roots) {
1493
+ return Promise.all(roots.map(async (root) => ({
1494
+ configured: root,
1495
+ real: await realpath3(root).catch(() => null) ?? root
1496
+ })));
1155
1497
  }
1156
- function withOutcomes(entries, batch, accepted, removal) {
1498
+ function withOutcomes(entries, batch, accepted, removal, skipped) {
1157
1499
  const outcomes = new Map;
1158
1500
  for (const target of removal.removed)
1159
1501
  outcomes.set(target, { ok: true });
@@ -1168,19 +1510,29 @@ function withOutcomes(entries, batch, accepted, removal) {
1168
1510
  if (outcome !== undefined)
1169
1511
  byTarget.set(target, outcome);
1170
1512
  }
1171
- const fallback = removal.aborted === undefined ? { ok: false } : { ok: false, error: ABORTED_HINT };
1513
+ const fallbackOf = (entry) => {
1514
+ if (removal.aborted !== undefined)
1515
+ return { ok: false, error: ABORTED_HINT };
1516
+ const hint = skipped.get(entry.target);
1517
+ if (hint !== undefined)
1518
+ return { ok: false, error: hint };
1519
+ return { ok: false };
1520
+ };
1172
1521
  return entries.map((entry) => ({
1173
1522
  ...entry,
1174
- ...byTarget.get(entry.target) ?? fallback
1523
+ ...byTarget.get(entry.target) ?? fallbackOf(entry)
1175
1524
  }));
1176
1525
  }
1526
+ var BUILTIN_EXCLUDE_NAMES = new Set(DEFAULT_EXCLUDE);
1177
1527
  function collectNameNotes(excludeMatches, includeMatches, color) {
1178
1528
  const notes = [];
1179
1529
  const tty = process.stdout.isTTY === true;
1180
1530
  for (const item of excludeMatches ?? []) {
1181
- if (item.hits === 0)
1531
+ if (item.hits === 0) {
1532
+ if (BUILTIN_EXCLUDE_NAMES.has(item.name))
1533
+ continue;
1182
1534
  warn(`排除名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`, color);
1183
- else if (tty)
1535
+ } else if (tty)
1184
1536
  notes.push(`排除生效: ${item.name} (${item.hits} 处)`);
1185
1537
  }
1186
1538
  const includes = includeMatches ?? [];
@@ -1194,7 +1546,7 @@ function collectNameNotes(excludeMatches, includeMatches, color) {
1194
1546
  warn("包含名单无一条命中, 本次扫描必为空结果 (请核对名字与大小写; 若名字位于被排除的目录之下则属预期)", color);
1195
1547
  return notes;
1196
1548
  }
1197
- function toEntries(hits, sizeResult) {
1549
+ function toEntries(hits, sizeResult, home, crossDevice) {
1198
1550
  const bytesOf = new Map(sizeResult.entries.map((entry) => [
1199
1551
  entry.target,
1200
1552
  entry.bytes
@@ -1206,9 +1558,18 @@ function toEntries(hits, sizeResult) {
1206
1558
  const entries = [];
1207
1559
  for (const hit of hits) {
1208
1560
  const project = basename(hit.project);
1561
+ const classification = classifyTarget(hit.target, { home });
1562
+ const suspect = classification.kind === "suspect-install-tree";
1563
+ const notes = [];
1564
+ if (suspect)
1565
+ notes.push(`疑似安装树: ${classification.reason}`);
1566
+ const deviceKind = crossDevice.get(hit.target);
1567
+ if (deviceKind !== undefined)
1568
+ notes.push(crossDeviceNote(deviceKind));
1569
+ const note = notes.length > 0 ? notes.join(" ") : undefined;
1209
1570
  const bytes = bytesOf.get(hit.target);
1210
1571
  if (bytes !== undefined) {
1211
- entries.push({ project, target: hit.target, bytes });
1572
+ entries.push({ project, target: hit.target, bytes, suspect, note });
1212
1573
  continue;
1213
1574
  }
1214
1575
  const reason = reasonOf.get(hit.target);
@@ -1216,7 +1577,8 @@ function toEntries(hits, sizeResult) {
1216
1577
  entries.push({
1217
1578
  project,
1218
1579
  target: hit.target,
1219
- note: `体积统计失败: ${reason}`
1580
+ suspect,
1581
+ note: note === undefined ? `体积统计失败: ${reason}` : `${note} 体积统计失败: ${reason}`
1220
1582
  });
1221
1583
  }
1222
1584
  }
@@ -1235,8 +1597,10 @@ async function sweep(config, options, color) {
1235
1597
  const sizeResult = await createSizer().measure(scanResult.hits.map((hit) => hit.target));
1236
1598
  for (const warning of sizeResult.warnings)
1237
1599
  warn(warning, color);
1238
- const entries = toEntries(scanResult.hits, sizeResult);
1239
- const home = homedir4();
1600
+ const home = homedir5();
1601
+ const crossDevice = await findCrossDeviceTargets(scanResult.hits.map((hit) => hit.target), { roots });
1602
+ const entries = toEntries(scanResult.hits, sizeResult, home, crossDevice);
1603
+ const { trailer, hints: skippedHints } = collectSkips(entries, crossDevice, options.force);
1240
1604
  if (!options.yes) {
1241
1605
  print(render({
1242
1606
  mode: "preview",
@@ -1245,11 +1609,12 @@ async function sweep(config, options, color) {
1245
1609
  color,
1246
1610
  home,
1247
1611
  notes: nameNotes,
1248
- runtime
1612
+ runtime,
1613
+ trailer
1249
1614
  }));
1250
1615
  return 0;
1251
1616
  }
1252
- const batch = entries.filter((entry) => entry.bytes !== undefined).map((entry) => entry.target);
1617
+ const batch = deletionBatch(entries, crossDevice, options.force);
1253
1618
  const { accepted, rejected } = await validateTargets(batch, { roots });
1254
1619
  if (rejected.length > 0) {
1255
1620
  warn(`整批拒绝: ${rejected.length} 个目标未通过安全闸, 未执行任何删除`, color);
@@ -1258,9 +1623,9 @@ async function sweep(config, options, color) {
1258
1623
  return 1;
1259
1624
  }
1260
1625
  const removal = await removeTargets(accepted, {
1261
- roots: await realRoots(roots)
1626
+ roots: await trustRoots(roots)
1262
1627
  });
1263
- const report = withOutcomes(entries, batch, accepted, removal);
1628
+ const report = withOutcomes(entries, batch, accepted, removal, skippedHints);
1264
1629
  const releasedBytes = report.reduce((total, entry) => entry.ok === false ? total : total + (entry.bytes ?? 0), 0);
1265
1630
  print(render({
1266
1631
  mode: "execute",
@@ -1270,7 +1635,8 @@ async function sweep(config, options, color) {
1270
1635
  home,
1271
1636
  releasedBytes,
1272
1637
  notes: nameNotes,
1273
- runtime
1638
+ runtime,
1639
+ trailer
1274
1640
  }));
1275
1641
  if (removal.aborted !== undefined) {
1276
1642
  warn(`整批中止: ${removal.aborted.reason}`, color);
@@ -1297,14 +1663,17 @@ async function main() {
1297
1663
  warn("init 需要交互终端 (请在终端直接运行, 不要重定向或经管道)", color);
1298
1664
  return 1;
1299
1665
  }
1300
- const result = await runWizard(resolvedPath.path);
1666
+ const result = await runWizard(resolvedPath.path, color);
1301
1667
  if (result.state === "written")
1302
- print("运行 sweep-nm 查看预览");
1668
+ print(neutralLine("运行 sweep-nm 查看预览", color));
1303
1669
  else
1304
1670
  print("配置未变更");
1305
1671
  return 0;
1306
1672
  }
1307
- const resolved = await resolveConfig(resolvedPath);
1673
+ if (options.command === "config") {
1674
+ return await reportConfig(resolvedPath, color);
1675
+ }
1676
+ const resolved = await resolveConfig(resolvedPath, color);
1308
1677
  if (resolved === null)
1309
1678
  return 0;
1310
1679
  if (resolved.source === "fallback") {