@iyowei/sweep-node-modules-cli 0.1.1 → 0.2.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,12 @@
1
1
  // src/cli.ts
2
- import { lstat as lstat3, mkdir, realpath as realpath3 } from "node:fs/promises";
3
- import { homedir as homedir5 } from "node:os";
2
+ import { lstat as lstat3, mkdir } from "node:fs/promises";
3
+ import { homedir as homedir6 } from "node:os";
4
4
  import { basename, dirname } from "node:path";
5
5
 
6
- // ../api/src/classify.ts
6
+ // ../sweep-node-modules/src/classify.ts
7
7
  import { homedir as homedir3 } from "node:os";
8
8
 
9
- // ../api/src/config.ts
9
+ // ../sweep-node-modules/src/config.ts
10
10
  import { readFile } from "node:fs/promises";
11
11
  import { homedir } from "node:os";
12
12
  import { posix, win32 } from "node:path";
@@ -130,10 +130,33 @@ function mergeNames(configNames, cliNames) {
130
130
  return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
131
131
  }
132
132
 
133
- // ../api/src/guard.ts
133
+ // ../sweep-node-modules/src/guard.ts
134
134
  import { lstat, realpath, stat } from "node:fs/promises";
135
135
  import { homedir as homedir2 } from "node:os";
136
136
  import { posix as posix2, win32 as win322 } from "node:path";
137
+
138
+ // ../sweep-node-modules/src/errors.ts
139
+ var SWEEP_ERROR_CODES = new Set([
140
+ "CONFIG_READ_FAILED",
141
+ "CONFIG_CORRUPT_JSON",
142
+ "CONFIG_CORRUPT_SHAPE",
143
+ "CONFIG_ABSENT",
144
+ "INVALID_ARGUMENT",
145
+ "CANCELLED"
146
+ ]);
147
+
148
+ class SweepError extends Error {
149
+ name = "SweepError";
150
+ code;
151
+ details;
152
+ constructor(code, message, details) {
153
+ super(message);
154
+ this.code = code;
155
+ this.details = details;
156
+ }
157
+ }
158
+
159
+ // ../sweep-node-modules/src/guard.ts
137
160
  var POSIX_STYLE = {
138
161
  name: "posix",
139
162
  ops: posix2,
@@ -232,50 +255,100 @@ async function validateTargets(targets, options) {
232
255
  const home = homeOption === null ? null : await tryRealpath(homeOption) ?? homeOption;
233
256
  const accepted = [];
234
257
  const rejected = [];
258
+ const mappings = [];
235
259
  const seen = new Set;
236
260
  for (const target of targets) {
261
+ if (options.signal?.aborted) {
262
+ throw new SweepError("CANCELLED", "安全闸校验在逐目标检查点被取消", {
263
+ phase: "validate"
264
+ });
265
+ }
237
266
  if (!hasNodeModulesLeaf(target, style)) {
238
- rejected.push({ target, reason: "路径末段不是 node_modules" });
267
+ rejected.push({
268
+ target,
269
+ code: "GUARD_LEAF_NOT_NODE_MODULES",
270
+ message: "路径末段不是 node_modules"
271
+ });
239
272
  continue;
240
273
  }
241
- const real = await tryRealpath(target);
274
+ let real = null;
275
+ let realpathErrno;
276
+ try {
277
+ real = await realpath(target);
278
+ } catch (error) {
279
+ realpathErrno = error.code;
280
+ }
242
281
  if (real === null) {
243
- rejected.push({ target, reason: "realpath 失败 (目标不存在或不可读)" });
282
+ let code = "GUARD_REALPATH_FAILED";
283
+ if (realpathErrno === "ENOENT")
284
+ code = "GUARD_TARGET_MISSING";
285
+ else if (realpathErrno === "EACCES" || realpathErrno === "EPERM") {
286
+ code = "GUARD_TARGET_UNREADABLE";
287
+ }
288
+ rejected.push({
289
+ target,
290
+ code,
291
+ message: "realpath 失败 (目标不存在或不可读)",
292
+ details: { errno: realpathErrno }
293
+ });
244
294
  continue;
245
295
  }
246
296
  const brokenAnchor = brokenAnchors.find((anchor) => insideAnyRoot(real, [anchor.real], style));
247
297
  if (brokenAnchor !== undefined) {
248
298
  rejected.push({
249
299
  target,
250
- reason: `根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`
300
+ code: "GUARD_ROOT_ANCHOR_SYMLINK",
301
+ message: `根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`,
302
+ details: { root: brokenAnchor.configured, symlink: brokenAnchor.link }
251
303
  });
252
304
  continue;
253
305
  }
254
306
  if (isFilesystemRootBody(real, style)) {
255
- rejected.push({ target, reason: "目标是文件系统根本体" });
307
+ rejected.push({
308
+ target,
309
+ code: "GUARD_FILESYSTEM_ROOT_BODY",
310
+ message: "目标是文件系统根本体"
311
+ });
256
312
  continue;
257
313
  }
258
314
  if (isHomeBody(real, home, style)) {
259
- rejected.push({ target, reason: "目标是 home 本体" });
315
+ rejected.push({
316
+ target,
317
+ code: "GUARD_HOME_BODY",
318
+ message: "目标是 home 本体"
319
+ });
260
320
  continue;
261
321
  }
262
322
  if (!hasNodeModulesLeaf(real, style)) {
263
- rejected.push({ target, reason: "realpath 后的末段不是 node_modules" });
323
+ rejected.push({
324
+ target,
325
+ code: "GUARD_REAL_LEAF_NOT_NODE_MODULES",
326
+ message: "realpath 后的末段不是 node_modules"
327
+ });
264
328
  continue;
265
329
  }
266
330
  if (!insideAnyRoot(real, roots, style)) {
267
- rejected.push({ target, reason: "realpath 后不在任何 root 之下" });
331
+ rejected.push({
332
+ target,
333
+ code: "GUARD_OUTSIDE_ROOTS",
334
+ message: "realpath 后不在任何 root 之下"
335
+ });
268
336
  continue;
269
337
  }
270
338
  const key = dedupeKey(real, style);
271
339
  if (seen.has(key)) {
272
- rejected.push({ target, reason: "重复目标 (realpath 去重)" });
340
+ rejected.push({
341
+ target,
342
+ code: "GUARD_DUPLICATE_TARGET",
343
+ message: "重复目标 (realpath 去重)"
344
+ });
273
345
  continue;
274
346
  }
275
347
  seen.add(key);
276
348
  accepted.push(real);
349
+ mappings.push({ original: target, real });
277
350
  }
278
- return { accepted, rejected };
351
+ return { accepted, rejected, mappings };
279
352
  }
280
353
  var fsDeviceProbe = async (path, follow) => {
281
354
  try {
@@ -316,10 +389,13 @@ async function findCrossDeviceTargets(targets, options) {
316
389
  const parentDev = await probe(style.ops.dirname(target), true);
317
390
  found.set(target, parentDev !== null && parentDev !== targetDev ? "target-itself" : "on-path");
318
391
  }
319
- return found;
392
+ return [...found.entries()].map(([target, kind]) => ({ target, kind }));
393
+ }
394
+ function crossDeviceIndex(entries) {
395
+ return new Map(entries.map((entry) => [entry.target, entry.kind]));
320
396
  }
321
397
 
322
- // ../api/src/classify.ts
398
+ // ../sweep-node-modules/src/classify.ts
323
399
  var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
324
400
  var INSTALL_TREE_SEGMENTS = new Set([...DEFAULT_EXCLUDE, "extensions", "_npx"].map((name) => name.toLowerCase()));
325
401
  function classifyTarget(target, options = {}) {
@@ -351,8 +427,8 @@ function classifyTarget(target, options = {}) {
351
427
  }
352
428
  return { kind: "project" };
353
429
  }
354
- // ../api/src/delete.ts
355
- import { lstat as lstat2, rm } from "node:fs/promises";
430
+ // ../sweep-node-modules/src/delete.ts
431
+ import { lstat as lstat2, realpath as realpath2, rm } from "node:fs/promises";
356
432
  import { isAbsolute, join, relative, sep } from "node:path";
357
433
  var ERROR_HINTS = {
358
434
  EACCES: "权限不足, 拒绝删除",
@@ -431,69 +507,124 @@ async function reviewComponents(chain) {
431
507
  async function removeTargets(targets, options) {
432
508
  const result = { removed: [], missing: [], failed: [] };
433
509
  const roots = options?.roots ?? [];
510
+ const signal = options?.signal;
511
+ const emit = options?.onProgress;
434
512
  for (const target of targets) {
513
+ if (signal?.aborted) {
514
+ throw new SweepError("CANCELLED", "删除在条目间检查点被取消", {
515
+ phase: "remove",
516
+ partial: result
517
+ });
518
+ }
435
519
  const root = roots.find((candidate) => isUnder(candidate.real, target));
436
520
  if (root === undefined) {
437
521
  result.aborted = {
438
522
  target,
439
- reason: `安全复核失败 (目标不在任何 roots 之下): ${target}`
523
+ code: "REVIEW_NOT_UNDER_ANY_ROOT",
524
+ message: `安全复核失败 (目标不在任何 roots 之下): ${target}`,
525
+ path: target
440
526
  };
527
+ emit?.({ kind: "aborted", aborted: result.aborted });
441
528
  break;
442
529
  }
443
530
  if (await isSymlinkHead(root.configured)) {
444
531
  result.aborted = {
445
532
  target,
446
- reason: `安全复核失败 (根被替换为符号链接): ${root.configured}`
533
+ code: "REVIEW_HEAD_SYMLINK",
534
+ message: `安全复核失败 (根被替换为符号链接): ${root.configured}`,
535
+ path: root.configured
447
536
  };
537
+ emit?.({ kind: "aborted", aborted: result.aborted });
448
538
  break;
449
539
  }
450
540
  const finding = await reviewComponents(componentChain(root.real, target));
451
541
  if (finding !== null) {
452
542
  if (finding.kind === "vanished") {
453
- result.failed.push({
543
+ const vanished = {
454
544
  target,
455
- error: describeVanishedReview(target, finding.path)
456
- });
545
+ code: "REVIEW_COMPONENT_VANISHED",
546
+ message: describeVanishedReview(target, finding.path),
547
+ partialRisk: false
548
+ };
549
+ result.failed.push(vanished);
550
+ emit?.({ kind: "failed", failure: vanished });
457
551
  continue;
458
552
  }
459
553
  if (finding.kind === "unsafe") {
460
554
  result.aborted = {
461
555
  target,
462
- reason: `安全复核失败 (路径组件被替换): ${finding.path}`
556
+ code: "REVIEW_COMPONENT_REPLACED",
557
+ message: `安全复核失败 (路径组件被替换): ${finding.path}`,
558
+ path: finding.path
463
559
  };
560
+ emit?.({ kind: "aborted", aborted: result.aborted });
464
561
  break;
465
562
  }
466
- result.failed.push({
563
+ const unverified = {
467
564
  target,
468
- error: describeReviewError(target, finding.path, finding.error)
469
- });
565
+ code: "REVIEW_UNVERIFIED",
566
+ message: describeReviewError(target, finding.path, finding.error),
567
+ partialRisk: false
568
+ };
569
+ result.failed.push(unverified);
570
+ emit?.({ kind: "failed", failure: unverified });
470
571
  continue;
471
572
  }
472
573
  try {
473
574
  await rm(target, { recursive: true, force: false });
474
575
  result.removed.push(target);
576
+ emit?.({ kind: "removed", target });
475
577
  } catch (error) {
476
578
  if (error?.code === "ENOENT") {
477
579
  const state = await checkGone(target);
478
580
  if (state === "gone") {
479
581
  result.missing.push(target);
582
+ emit?.({ kind: "missing", target });
480
583
  continue;
481
584
  }
482
- result.failed.push({
585
+ const survivor = {
483
586
  target,
484
- error: describeSurvivor(target, state)
485
- });
587
+ code: "REMOVE_ENOENT_SURVIVOR",
588
+ message: describeSurvivor(target, state),
589
+ partialRisk: true
590
+ };
591
+ result.failed.push(survivor);
592
+ emit?.({ kind: "failed", failure: survivor });
486
593
  continue;
487
594
  }
488
- result.failed.push({
595
+ const failure = {
489
596
  target,
490
- error: describeRemovalError(target, error)
491
- });
597
+ code: "REMOVE_FAILED",
598
+ errno: error?.code,
599
+ message: describeRemovalError(target, error),
600
+ partialRisk: true
601
+ };
602
+ result.failed.push(failure);
603
+ emit?.({ kind: "failed", failure });
492
604
  }
493
605
  }
494
606
  return result;
495
607
  }
496
- // ../api/src/runtime.ts
608
+ async function toTrustRoots(roots) {
609
+ return Promise.all(roots.map(async (root) => ({
610
+ configured: root,
611
+ real: await realpath2(root).catch(() => null) ?? root
612
+ })));
613
+ }
614
+ function splitStaleRejections(rejected, staleTargets) {
615
+ if (staleTargets !== "missing")
616
+ return { rejected, stale: [] };
617
+ const rest = [];
618
+ const stale = [];
619
+ for (const item of rejected) {
620
+ if (item.code === "GUARD_TARGET_MISSING")
621
+ stale.push(item.target);
622
+ else
623
+ rest.push(item);
624
+ }
625
+ return { rejected: rest, stale };
626
+ }
627
+ // ../sweep-node-modules/src/runtime.ts
497
628
  import { readFile as readFile2, writeFile } from "node:fs/promises";
498
629
  var isBun = typeof Bun !== "undefined";
499
630
  var versions = process.versions;
@@ -506,8 +637,8 @@ async function writeTextFile(path, text) {
506
637
  }
507
638
  await writeFile(path, text, "utf8");
508
639
  }
509
- // ../api/src/scan-parallel.ts
510
- import { readdir, realpath as realpath2, stat as stat2 } from "node:fs/promises";
640
+ // ../sweep-node-modules/src/scan-parallel.ts
641
+ import { readdir, realpath as realpath3, stat as stat2 } from "node:fs/promises";
511
642
  import { join as join2 } from "node:path";
512
643
  var NODE_MODULES = "node_modules";
513
644
  var GIT_DIR = ".git";
@@ -519,18 +650,36 @@ function compareTarget(a, b) {
519
650
  return 1;
520
651
  return 0;
521
652
  }
522
- function describeRootFailure(error) {
653
+ function rootFailureWarning(error, root) {
523
654
  const { code } = error;
524
655
  switch (code) {
525
656
  case "ENOENT":
526
- return "根不存在";
657
+ return {
658
+ code: "SCAN_ROOT_MISSING",
659
+ message: `根不存在, 已跳过: ${root}`,
660
+ path: root
661
+ };
527
662
  case "EACCES":
528
663
  case "EPERM":
529
- return "根不可读 (权限不足)";
664
+ return {
665
+ code: "SCAN_ROOT_UNREADABLE",
666
+ message: `根不可读 (权限不足), 已跳过: ${root}`,
667
+ path: root,
668
+ errno: code
669
+ };
530
670
  case "ENOTDIR":
531
- return "根不是目录";
671
+ return {
672
+ code: "SCAN_ROOT_NOT_DIR",
673
+ message: `根不是目录, 已跳过: ${root}`,
674
+ path: root
675
+ };
532
676
  default:
533
- return `根不可用 (${code ?? "UNKNOWN"})`;
677
+ return {
678
+ code: "SCAN_ROOT_UNAVAILABLE",
679
+ message: `根不可用 (${code ?? "UNKNOWN"}), 已跳过: ${root}`,
680
+ path: root,
681
+ errno: code
682
+ };
534
683
  }
535
684
  }
536
685
  async function walkRoot(root, ctx) {
@@ -541,7 +690,9 @@ async function walkRoot(root, ctx) {
541
690
  include,
542
691
  includeCounts,
543
692
  hits,
544
- warnings
693
+ warnings,
694
+ signal,
695
+ onProgress
545
696
  } = ctx;
546
697
  const stack = [{ dir: root, included: include.size === 0 }];
547
698
  let outstanding = 1;
@@ -565,11 +716,20 @@ async function walkRoot(root, ctx) {
565
716
  }
566
717
  async function visit(dir, included) {
567
718
  try {
719
+ if (signal?.aborted) {
720
+ throw new SweepError("CANCELLED", "扫描在遍历任务检查点被取消", {
721
+ phase: "scan"
722
+ });
723
+ }
568
724
  let entries;
569
725
  try {
570
726
  entries = await readdir(dir, { withFileTypes: true });
571
727
  } catch {
572
- warnings.push(`目录不可读, 已跳过: ${dir}`);
728
+ warnings.push({
729
+ code: "SCAN_DIR_UNREADABLE",
730
+ message: `目录不可读, 已跳过: ${dir}`,
731
+ path: dir
732
+ });
573
733
  return;
574
734
  }
575
735
  for (const entry of entries) {
@@ -580,9 +740,12 @@ async function walkRoot(root, ctx) {
580
740
  if (!included)
581
741
  continue;
582
742
  const target = join2(dir, name);
583
- const key = dedupeKey(await realpath2(target).catch(() => target), style);
584
- if (!hits.has(key))
585
- hits.set(key, { project: dir, target });
743
+ const key = dedupeKey(await realpath3(target).catch(() => target), style);
744
+ if (!hits.has(key)) {
745
+ const hit = { project: dir, target, root };
746
+ hits.set(key, hit);
747
+ onProgress?.({ kind: "hit", hit });
748
+ }
586
749
  continue;
587
750
  }
588
751
  if (name === GIT_DIR)
@@ -636,14 +799,18 @@ function createParallelScanner() {
636
799
  for (const root of options.roots) {
637
800
  let key;
638
801
  try {
639
- const resolved = await realpath2(root);
802
+ const resolved = await realpath3(root);
640
803
  if (!(await stat2(resolved)).isDirectory()) {
641
- warnings.push(`根不是目录, 已跳过: ${root}`);
804
+ warnings.push({
805
+ code: "SCAN_ROOT_NOT_DIR",
806
+ message: `根不是目录, 已跳过: ${root}`,
807
+ path: root
808
+ });
642
809
  continue;
643
810
  }
644
811
  key = dedupeKey(resolved, style);
645
812
  } catch (error) {
646
- warnings.push(`${describeRootFailure(error)}, 已跳过: ${root}`);
813
+ warnings.push(rootFailureWarning(error, root));
647
814
  continue;
648
815
  }
649
816
  if (seenRoots.has(key))
@@ -658,7 +825,9 @@ function createParallelScanner() {
658
825
  include,
659
826
  includeCounts,
660
827
  hits: hitsByRealTarget,
661
- warnings
828
+ warnings,
829
+ signal: options.signal,
830
+ onProgress: options.onProgress
662
831
  };
663
832
  for (const root of roots) {
664
833
  await walkRoot(root, context);
@@ -676,7 +845,7 @@ function createParallelScanner() {
676
845
  }
677
846
  };
678
847
  }
679
- // ../api/src/size-du.ts
848
+ // ../sweep-node-modules/src/size-du.ts
680
849
  import { spawn } from "node:child_process";
681
850
  import { accessSync, constants } from "node:fs";
682
851
  var DU_PROBES = ["/usr/bin/du", "/bin/du"];
@@ -759,15 +928,31 @@ function describeAnomaly(assessment) {
759
928
  }
760
929
  function describeDuFailure(detail) {
761
930
  if (/no such file or directory/i.test(detail))
762
- return { reason: "不存在", missing: true };
931
+ return { missing: true, reason: "不存在" };
763
932
  if (/permission denied/i.test(detail))
764
- return { reason: "权限不足, 无法读取", missing: false };
933
+ return {
934
+ missing: false,
935
+ code: "SIZE_UNMEASURED_PERMISSION",
936
+ reason: "权限不足, 无法读取"
937
+ };
765
938
  if (/not a directory/i.test(detail))
766
- return { reason: "不是目录", missing: false };
939
+ return {
940
+ missing: false,
941
+ code: "SIZE_UNMEASURED_NOT_DIR",
942
+ reason: "不是目录"
943
+ };
767
944
  if (/too many levels of symbolic links/i.test(detail)) {
768
- return { reason: "符号链接层级过深", missing: false };
945
+ return {
946
+ missing: false,
947
+ code: "SIZE_UNMEASURED_LOOP",
948
+ reason: "符号链接层级过深"
949
+ };
769
950
  }
770
- return { reason: `读取失败 (${detail})`, missing: false };
951
+ return {
952
+ missing: false,
953
+ code: "SIZE_UNMEASURED_OTHER",
954
+ reason: `读取失败 (${detail})`
955
+ };
771
956
  }
772
957
  function parseDuErrorLine(line) {
773
958
  const body = line.replace(PROG_PREFIX_RE, "");
@@ -790,23 +975,37 @@ function parseDuErrorLine(line) {
790
975
  function createDuSizer(bin = findDu()) {
791
976
  return {
792
977
  name: "du",
793
- async measure(targets) {
978
+ basis: "disk-usage",
979
+ async measure(targets, options) {
794
980
  if (bin === null) {
795
981
  return {
796
982
  entries: [],
983
+ basis: "disk-usage",
797
984
  warnings: [
798
- "du 候选不可用: /usr/bin/du 与 /bin/du 均不存在, 本候选跳过体积统计"
985
+ {
986
+ code: "SIZE_DU_UNAVAILABLE",
987
+ message: "du 候选不可用: /usr/bin/du 与 /bin/du 均不存在, 本候选跳过体积统计"
988
+ }
799
989
  ],
800
- unmeasured: []
990
+ unmeasured: [],
991
+ gone: []
801
992
  };
802
993
  }
803
994
  if (targets.length === 0) {
804
- return { entries: [], warnings: [], unmeasured: [] };
995
+ return {
996
+ entries: [],
997
+ basis: "disk-usage",
998
+ warnings: [],
999
+ unmeasured: [],
1000
+ gone: []
1001
+ };
805
1002
  }
806
1003
  const sorted = [...targets].sort();
807
1004
  const warnings = [];
808
1005
  const entries = [];
809
1006
  const unmeasured = [];
1007
+ const gone = [];
1008
+ const emit = options?.onProgress;
810
1009
  const safeTargets = sorted.filter((target) => !hasControlChar(target));
811
1010
  const safeSet = new Set(safeTargets);
812
1011
  const sizes = new Map;
@@ -817,7 +1016,10 @@ function createDuSizer(bin = findDu()) {
817
1016
  const assessment = assessDuOutput(stdout, safeTargets);
818
1017
  intact = assessment.intact;
819
1018
  if (!intact) {
820
- warnings.push(`du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${safeTargets.length} 个目标的体积均未采信`);
1019
+ warnings.push({
1020
+ code: "SIZE_DU_OUTPUT_MISMATCH",
1021
+ message: `du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${safeTargets.length} 个目标的体积均未采信`
1022
+ });
821
1023
  }
822
1024
  for (const [path, bytes] of assessment.sizes)
823
1025
  sizes.set(path, bytes);
@@ -827,12 +1029,19 @@ function createDuSizer(bin = findDu()) {
827
1029
  continue;
828
1030
  const errorLine = parseDuErrorLine(line);
829
1031
  if (errorLine === null) {
830
- warnings.push(`体积统计失败 (未归因): ${line.replace(PROG_PREFIX_RE, "").trim()}`);
1032
+ warnings.push({
1033
+ code: "SIZE_DU_LINE_UNATTRIBUTED",
1034
+ message: `体积统计失败 (未归因): ${line.replace(PROG_PREFIX_RE, "").trim()}`
1035
+ });
831
1036
  continue;
832
1037
  }
833
1038
  const failure = describeDuFailure(errorLine.detail);
834
1039
  if (!safeSet.has(errorLine.path)) {
835
- warnings.push(`体积统计失败 (${failure.reason}): ${errorLine.path}`);
1040
+ warnings.push({
1041
+ code: "SIZE_SUBPATH_FAILED",
1042
+ message: `体积统计失败 (${failure.reason}): ${errorLine.path}`,
1043
+ path: errorLine.path
1044
+ });
836
1045
  continue;
837
1046
  }
838
1047
  failures.set(errorLine.path, failure);
@@ -840,52 +1049,84 @@ function createDuSizer(bin = findDu()) {
840
1049
  for (const path of failures.keys())
841
1050
  sizes.delete(path);
842
1051
  }
1052
+ const pushUnmeasured = (target, code, reason) => {
1053
+ unmeasured.push({ target, code, reason });
1054
+ emit?.({ kind: "unmeasured", target, code, reason });
1055
+ };
843
1056
  for (const target of sorted) {
1057
+ if (options?.signal?.aborted) {
1058
+ throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
1059
+ phase: "measure"
1060
+ });
1061
+ }
844
1062
  if (hasControlChar(target)) {
845
- unmeasured.push({ target, reason: "路径含控制字符" });
1063
+ pushUnmeasured(target, "SIZE_UNMEASURED_CONTROL_CHAR", "路径含控制字符");
846
1064
  continue;
847
1065
  }
848
1066
  if (!intact) {
849
- unmeasured.push({ target, reason: "输出不可解析" });
1067
+ pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
850
1068
  continue;
851
1069
  }
852
1070
  const bytes = sizes.get(target);
853
1071
  if (bytes !== undefined) {
854
1072
  entries.push({ target, bytes });
1073
+ emit?.({ kind: "measured", target, bytes, basis: "disk-usage" });
855
1074
  continue;
856
1075
  }
857
1076
  const failure = failures.get(target);
858
1077
  if (failure === undefined) {
859
- unmeasured.push({ target, reason: "输出不可解析" });
1078
+ pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
860
1079
  continue;
861
1080
  }
862
1081
  if (failure.missing) {
863
- warnings.push(`体积统计失败 (不存在): ${target}`);
1082
+ gone.push(target);
1083
+ warnings.push({
1084
+ code: "SIZE_TARGET_VANISHED",
1085
+ message: `体积统计失败 (不存在): ${target}`,
1086
+ path: target
1087
+ });
1088
+ emit?.({ kind: "gone", target });
864
1089
  continue;
865
1090
  }
866
- unmeasured.push({ target, reason: failure.reason });
1091
+ pushUnmeasured(target, failure.code, failure.reason);
867
1092
  }
868
- return { entries, warnings, unmeasured };
1093
+ return { entries, basis: "disk-usage", warnings, unmeasured, gone };
869
1094
  }
870
1095
  };
871
1096
  }
872
1097
 
873
- // ../api/src/size-js.ts
1098
+ // ../sweep-node-modules/src/size-js.ts
874
1099
  import { readdir as readdir2, stat as stat3 } from "node:fs/promises";
875
1100
  import { join as join3 } from "node:path";
876
1101
  function describeFailure(code) {
877
1102
  switch (code) {
878
1103
  case "ENOENT":
879
- return "不存在";
1104
+ return { missing: true, reason: "不存在" };
880
1105
  case "EACCES":
881
1106
  case "EPERM":
882
- return "权限不足, 无法读取";
1107
+ return {
1108
+ missing: false,
1109
+ code: "SIZE_UNMEASURED_PERMISSION",
1110
+ reason: "权限不足, 无法读取"
1111
+ };
883
1112
  case "ENOTDIR":
884
- return "不是目录";
1113
+ return {
1114
+ missing: false,
1115
+ code: "SIZE_UNMEASURED_NOT_DIR",
1116
+ reason: "不是目录"
1117
+ };
885
1118
  case "ELOOP":
886
- return "符号链接层级过深";
1119
+ return {
1120
+ missing: false,
1121
+ code: "SIZE_UNMEASURED_LOOP",
1122
+ reason: "符号链接层级过深"
1123
+ };
887
1124
  default:
888
- return code === undefined ? "读取失败" : `读取失败 (${code})`;
1125
+ return {
1126
+ missing: false,
1127
+ code: "SIZE_UNMEASURED_OTHER",
1128
+ reason: code === undefined ? "读取失败" : `读取失败 (${code})`
1129
+ };
889
1130
  }
890
1131
  }
891
1132
  function errorCode(error) {
@@ -901,13 +1142,21 @@ async function sumEntries(dirents, dir, warnings) {
901
1142
  try {
902
1143
  total += await sumEntries(await readdir2(path, { withFileTypes: true }), path, warnings);
903
1144
  } catch (error) {
904
- warnings.push(`体积统计失败 (${describeFailure(errorCode(error))}): ${path}`);
1145
+ warnings.push({
1146
+ code: "SIZE_SUBPATH_FAILED",
1147
+ message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
1148
+ path
1149
+ });
905
1150
  }
906
1151
  } else if (dirent.isFile()) {
907
1152
  try {
908
1153
  total += (await stat3(path)).size;
909
1154
  } catch (error) {
910
- warnings.push(`体积统计失败 (${describeFailure(errorCode(error))}): ${path}`);
1155
+ warnings.push({
1156
+ code: "SIZE_SUBPATH_FAILED",
1157
+ message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
1158
+ path
1159
+ });
911
1160
  }
912
1161
  }
913
1162
  }
@@ -916,38 +1165,55 @@ async function sumEntries(dirents, dir, warnings) {
916
1165
  function createJsSizer() {
917
1166
  return {
918
1167
  name: "js",
919
- async measure(targets) {
1168
+ basis: "logical-bytes",
1169
+ async measure(targets, options) {
920
1170
  const warnings = [];
921
1171
  const entries = [];
922
1172
  const unmeasured = [];
1173
+ const gone = [];
1174
+ const emit = options?.onProgress;
1175
+ const pushUnmeasured = (target, code, reason) => {
1176
+ unmeasured.push({ target, code, reason });
1177
+ emit?.({ kind: "unmeasured", target, code, reason });
1178
+ };
923
1179
  for (const target of [...targets].sort()) {
1180
+ if (options?.signal?.aborted) {
1181
+ throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
1182
+ phase: "measure"
1183
+ });
1184
+ }
924
1185
  let dirents;
925
1186
  try {
926
1187
  dirents = await readdir2(target, { withFileTypes: true });
927
1188
  } catch (error) {
928
- const code = errorCode(error);
929
- if (code === "ENOENT") {
930
- warnings.push(`体积统计失败 (不存在): ${target}`);
1189
+ const failure = describeFailure(errorCode(error));
1190
+ if (failure.missing) {
1191
+ gone.push(target);
1192
+ warnings.push({
1193
+ code: "SIZE_TARGET_VANISHED",
1194
+ message: `体积统计失败 (${failure.reason}): ${target}`,
1195
+ path: target
1196
+ });
1197
+ emit?.({ kind: "gone", target });
931
1198
  } else {
932
- unmeasured.push({ target, reason: describeFailure(code) });
1199
+ pushUnmeasured(target, failure.code, failure.reason);
933
1200
  }
934
1201
  continue;
935
1202
  }
936
- entries.push({
937
- target,
938
- bytes: await sumEntries(dirents, target, warnings)
939
- });
1203
+ const bytes = await sumEntries(dirents, target, warnings);
1204
+ entries.push({ target, bytes });
1205
+ emit?.({ kind: "measured", target, bytes, basis: "logical-bytes" });
940
1206
  }
941
- return { entries, warnings, unmeasured };
1207
+ return { entries, basis: "logical-bytes", warnings, unmeasured, gone };
942
1208
  }
943
1209
  };
944
1210
  }
945
1211
 
946
- // ../api/src/size.ts
1212
+ // ../sweep-node-modules/src/size.ts
947
1213
  function createSizer() {
948
1214
  return findDu() !== null ? createDuSizer() : createJsSizer();
949
1215
  }
950
- // ../api/src/skip.ts
1216
+ // ../sweep-node-modules/src/skip.ts
951
1217
  var SUSPECT_HINT = "已跳过 (加 --force 一并清理)";
952
1218
  var CROSS_DEVICE_NOTES = {
953
1219
  "on-path": "跨设备: 根与目标之间有挂载点",
@@ -964,16 +1230,33 @@ var CROSS_DEVICE_TRAILER_ACTIONS = {
964
1230
  function crossDeviceNote(kind) {
965
1231
  return CROSS_DEVICE_NOTES[kind];
966
1232
  }
967
- function skipsBatch(entry, crossDevice, force) {
968
- if (crossDevice.has(entry.target))
969
- return true;
970
- return entry.suspect === true && !force;
1233
+ function skipReasonOf(entry, crossDevice, policy) {
1234
+ const deviceKind = crossDevice.get(entry.target);
1235
+ if (deviceKind !== undefined) {
1236
+ return deviceKind === "on-path" ? "cross-device:on-path" : "cross-device:target-itself";
1237
+ }
1238
+ if (entry.bytes === undefined)
1239
+ return "unmeasured";
1240
+ if (entry.suspect && !policy.releaseSuspects)
1241
+ return "suspect-install-tree";
1242
+ return null;
971
1243
  }
972
- function deletionBatch(entries, crossDevice, force) {
973
- return entries.filter((entry) => entry.bytes !== undefined && !skipsBatch(entry, crossDevice, force)).map((entry) => entry.target);
1244
+ function skipsBatch(entry, crossDevice, policy) {
1245
+ return skipReasonOf(entry, crossDevice, policy) !== null;
974
1246
  }
975
- function collectSkips(entries, crossDevice, force) {
976
- const suspectSkipped = force ? [] : entries.filter((entry) => entry.suspect === true);
1247
+ function deletionBatch(entries, crossDevice, policy) {
1248
+ return entries.filter((entry) => !skipsBatch(entry, crossDevice, policy)).map((entry) => entry.target);
1249
+ }
1250
+ function noteOf(entry, reason) {
1251
+ if (reason === "suspect-install-tree")
1252
+ return SUSPECT_HINT;
1253
+ if (reason === "unmeasured") {
1254
+ return `体积统计失败: ${entry.unmeasuredReason ?? "原因未知"}`;
1255
+ }
1256
+ return CROSS_DEVICE_HINTS[reason === "cross-device:on-path" ? "on-path" : "target-itself"];
1257
+ }
1258
+ function collectSkips(entries, crossDevice, policy) {
1259
+ const suspectSkipped = policy.releaseSuspects ? [] : entries.filter((entry) => entry.suspect);
977
1260
  const deviceSkipped = entries.filter((entry) => crossDevice.has(entry.target));
978
1261
  const trailer = [
979
1262
  ...suspectSkipped.length > 0 ? [`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`] : [],
@@ -995,7 +1278,325 @@ function collectSkips(entries, crossDevice, force) {
995
1278
  hints.set(entry.target, CROSS_DEVICE_HINTS[kind]);
996
1279
  }
997
1280
  }
998
- return { trailer, hints };
1281
+ const book = [];
1282
+ for (const entry of entries) {
1283
+ const reason = skipReasonOf(entry, crossDevice, policy);
1284
+ if (reason === null)
1285
+ continue;
1286
+ book.push({ target: entry.target, reason, note: noteOf(entry, reason) });
1287
+ }
1288
+ return { entries: book, trailer, hints };
1289
+ }
1290
+ // ../sweep-node-modules/src/summary.ts
1291
+ var SUCCESS_KINDS = new Set([
1292
+ "removed",
1293
+ "missing",
1294
+ "stale"
1295
+ ]);
1296
+ function isSuccessOutcome(outcome) {
1297
+ return SUCCESS_KINDS.has(outcome.kind);
1298
+ }
1299
+ function summarizeReport(report) {
1300
+ const counts = {
1301
+ removed: 0,
1302
+ missing: 0,
1303
+ stale: 0,
1304
+ failed: 0,
1305
+ rejected: 0,
1306
+ "not-attempted": 0,
1307
+ "not-expected": 0,
1308
+ skipped: 0
1309
+ };
1310
+ for (const entry of report.entries)
1311
+ counts[entry.outcome.kind] += 1;
1312
+ return {
1313
+ counts,
1314
+ succeeded: counts.removed + counts.missing + counts.stale,
1315
+ unprocessed: counts.skipped + counts.rejected + counts["not-attempted"] + counts["not-expected"],
1316
+ failed: counts.failed,
1317
+ aborted: report.removal?.aborted !== undefined
1318
+ };
1319
+ }
1320
+ // ../sweep-node-modules/src/sweep.ts
1321
+ import { homedir as homedir4 } from "node:os";
1322
+ var invalidArgument = (field, message) => new SweepError("INVALID_ARGUMENT", `${message} (字段: ${field})`, { field });
1323
+ function assertNameArray(value, field, required) {
1324
+ if (value === undefined) {
1325
+ if (required)
1326
+ throw invalidArgument(field, "为必填项");
1327
+ return;
1328
+ }
1329
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item === ""))
1330
+ throw invalidArgument(field, "必须是非空字符串数组");
1331
+ if (required && value.length === 0)
1332
+ throw invalidArgument(field, "不能为空数组");
1333
+ }
1334
+ function assertShape(options) {
1335
+ if (typeof options !== "object" || options === null)
1336
+ throw invalidArgument("options", "构造选项必须是对象");
1337
+ assertNameArray(options.roots, "roots", true);
1338
+ assertNameArray(options.exclude, "exclude", false);
1339
+ assertNameArray(options.include, "include", false);
1340
+ if (options.home !== undefined && options.home !== null && typeof options.home !== "string")
1341
+ throw invalidArgument("home", "必须是字符串或 null");
1342
+ if (options.policy !== undefined && (typeof options.policy !== "object" || options.policy === null || typeof options.policy.releaseSuspects !== "boolean"))
1343
+ throw invalidArgument("policy", "releaseSuspects 必须是布尔值");
1344
+ }
1345
+ function resolveOptions(options) {
1346
+ assertShape(options);
1347
+ return Object.freeze({
1348
+ roots: [...options.roots],
1349
+ exclude: mergeNames(options.exclude ?? [...DEFAULT_EXCLUDE], []),
1350
+ include: mergeNames(options.include ?? [], []),
1351
+ home: options.home === undefined ? homedir4() : options.home,
1352
+ style: options.style ?? nativeStyle(),
1353
+ policy: Object.freeze({
1354
+ releaseSuspects: options.policy?.releaseSuspects ?? false
1355
+ })
1356
+ });
1357
+ }
1358
+ var cancelledAt = (phase) => new SweepError("CANCELLED", `清理在 ${phase} 阶段被取消`, { phase });
1359
+ async function withPhase(phase, emit, signal, work) {
1360
+ if (signal?.aborted)
1361
+ throw cancelledAt(phase);
1362
+ const startedAt = Date.now();
1363
+ emit?.({ kind: "phase", phase, status: "start" });
1364
+ const value = await work();
1365
+ emit?.({
1366
+ kind: "phase",
1367
+ phase,
1368
+ status: "done",
1369
+ elapsedMs: Date.now() - startedAt
1370
+ });
1371
+ return value;
1372
+ }
1373
+ async function executePlan(resolved, options, signal) {
1374
+ const emit = options?.onProgress;
1375
+ const roots = resolved.roots;
1376
+ const scanResult = await withPhase("scan", emit, signal, async () => {
1377
+ const result = await createParallelScanner().scan({
1378
+ roots,
1379
+ exclude: resolved.exclude,
1380
+ include: resolved.include,
1381
+ signal,
1382
+ onProgress: (event) => emit?.(event)
1383
+ });
1384
+ for (const warning of result.warnings)
1385
+ emit?.({ kind: "warning", warning });
1386
+ return result;
1387
+ });
1388
+ const targets = scanResult.hits.map((hit) => hit.target);
1389
+ const sizeResult = await withPhase("measure", emit, signal, async () => {
1390
+ const result = await createSizer().measure(targets, {
1391
+ signal,
1392
+ onProgress: (event) => {
1393
+ if (event.kind === "gone")
1394
+ return;
1395
+ emit?.(event);
1396
+ }
1397
+ });
1398
+ for (const warning of result.warnings)
1399
+ emit?.({ kind: "warning", warning });
1400
+ return result;
1401
+ });
1402
+ const classifications = await withPhase("classify", emit, signal, () => scanResult.hits.map((hit) => classifyTarget(hit.target, {
1403
+ home: resolved.home,
1404
+ style: resolved.style
1405
+ })));
1406
+ const crossDevice = await withPhase("device", emit, signal, async () => crossDeviceIndex(await findCrossDeviceTargets(targets, {
1407
+ roots,
1408
+ style: resolved.style
1409
+ })));
1410
+ return withPhase("plan", emit, signal, () => {
1411
+ const policy = resolved.policy;
1412
+ const bytesOf = new Map(sizeResult.entries.map((entry) => [
1413
+ entry.target,
1414
+ entry.bytes
1415
+ ]));
1416
+ const unmeasuredOf = new Map(sizeResult.unmeasured.map((item) => [item.target, item]));
1417
+ const goneSet = new Set(sizeResult.gone);
1418
+ const prepared = [];
1419
+ for (let index = 0;index < scanResult.hits.length; index += 1) {
1420
+ const hit = scanResult.hits[index];
1421
+ const classification = classifications[index];
1422
+ if (hit === undefined || classification === undefined)
1423
+ continue;
1424
+ if (goneSet.has(hit.target))
1425
+ continue;
1426
+ const bytes = bytesOf.get(hit.target);
1427
+ prepared.push({
1428
+ hit,
1429
+ classification,
1430
+ candidate: {
1431
+ target: hit.target,
1432
+ bytes,
1433
+ unmeasuredReason: bytes === undefined ? unmeasuredOf.get(hit.target)?.reason : undefined,
1434
+ suspect: classification.kind === "suspect-install-tree"
1435
+ }
1436
+ });
1437
+ }
1438
+ const candidates = prepared.map((item) => item.candidate);
1439
+ const batch = deletionBatch(candidates, crossDevice, policy);
1440
+ const book = collectSkips(candidates, crossDevice, policy);
1441
+ const noteOf = new Map(book.entries.map((item) => [item.target, item.note]));
1442
+ const entries = [];
1443
+ for (const { hit, classification, candidate } of prepared) {
1444
+ const reason = skipReasonOf(candidate, crossDevice, policy);
1445
+ const deviceKind = crossDevice.get(hit.target);
1446
+ const unmeasured = unmeasuredOf.get(hit.target);
1447
+ entries.push({
1448
+ target: hit.target,
1449
+ project: hit.project,
1450
+ root: hit.root,
1451
+ bytes: candidate.bytes,
1452
+ basis: candidate.bytes === undefined ? undefined : sizeResult.basis,
1453
+ kind: classification.kind,
1454
+ kindReason: classification.reason,
1455
+ crossDevice: deviceKind,
1456
+ unmeasuredCode: unmeasured?.code,
1457
+ unmeasuredReason: unmeasured?.reason,
1458
+ inBatch: reason === null,
1459
+ skipReason: reason ?? undefined,
1460
+ skipNote: reason === null ? undefined : noteOf.get(hit.target)
1461
+ });
1462
+ if (reason !== null)
1463
+ emit?.({ kind: "skipped", target: hit.target, reason });
1464
+ }
1465
+ return {
1466
+ roots: [...resolved.roots],
1467
+ exclude: [...resolved.exclude],
1468
+ include: [...resolved.include],
1469
+ policy,
1470
+ basis: entries.length > 0 ? sizeResult.basis : undefined,
1471
+ entries,
1472
+ batch,
1473
+ skipped: [...book.entries],
1474
+ warnings: [...scanResult.warnings, ...sizeResult.warnings],
1475
+ nameMatches: {
1476
+ exclude: scanResult.excludeMatches,
1477
+ include: scanResult.includeMatches
1478
+ }
1479
+ };
1480
+ });
1481
+ }
1482
+ function buildOutcomeEntries(plan, expectedSet, stale, rejected, removal) {
1483
+ const staleSet = new Set(stale);
1484
+ const rejectedMap = rejected.length > 0 ? new Map(rejected.map((item) => [item.target, item])) : undefined;
1485
+ const removedSet = new Set(removal?.removed ?? []);
1486
+ const missingSet = new Set(removal?.missing ?? []);
1487
+ const failedMap = new Map((removal?.failed ?? []).map((item) => [
1488
+ item.target,
1489
+ item
1490
+ ]));
1491
+ const outcomeOf = (entry) => {
1492
+ if (!entry.inBatch)
1493
+ return { kind: "skipped", reason: entry.skipReason };
1494
+ if (expectedSet !== undefined && !expectedSet.has(entry.target))
1495
+ return { kind: "not-expected" };
1496
+ if (staleSet.has(entry.target))
1497
+ return { kind: "stale" };
1498
+ if (rejectedMap !== undefined)
1499
+ return { kind: "rejected", rejection: rejectedMap.get(entry.target) };
1500
+ if (removedSet.has(entry.target))
1501
+ return { kind: "removed" };
1502
+ if (missingSet.has(entry.target))
1503
+ return { kind: "missing" };
1504
+ const failure = failedMap.get(entry.target);
1505
+ if (failure !== undefined)
1506
+ return { kind: "failed", failure };
1507
+ return { kind: "not-attempted", code: removal.aborted.code };
1508
+ };
1509
+ return plan.entries.map((entry) => ({ ...entry, outcome: outcomeOf(entry) }));
1510
+ }
1511
+ async function executeRun(resolved, options, signal) {
1512
+ const emit = options?.onProgress;
1513
+ const startedAt = Date.now();
1514
+ const plan = await executePlan(resolved, options, signal);
1515
+ const expected = options?.expectedBatch;
1516
+ const expectedSet = expected === undefined ? undefined : new Set(expected);
1517
+ const face = expectedSet === undefined ? plan.batch : plan.batch.filter((target) => expectedSet.has(target));
1518
+ const liveSet = new Set(plan.batch);
1519
+ const drift = expected === undefined || expectedSet === undefined ? undefined : {
1520
+ added: plan.batch.filter((target) => !expectedSet.has(target)),
1521
+ removed: expected.filter((target) => !liveSet.has(target))
1522
+ };
1523
+ let validation;
1524
+ let removal;
1525
+ let stale = [];
1526
+ let rejected = [];
1527
+ if (face.length > 0) {
1528
+ const raw = await withPhase("validate", emit, signal, () => validateTargets(face, {
1529
+ roots: resolved.roots,
1530
+ home: resolved.home,
1531
+ style: resolved.style,
1532
+ signal
1533
+ }));
1534
+ const split = splitStaleRejections(raw.rejected, options?.staleTargets);
1535
+ stale = split.stale;
1536
+ rejected = split.rejected;
1537
+ validation = {
1538
+ accepted: raw.accepted,
1539
+ rejected,
1540
+ mappings: raw.mappings
1541
+ };
1542
+ if (rejected.length === 0) {
1543
+ removal = await withPhase("remove", emit, signal, async () => removeTargets(raw.accepted, {
1544
+ roots: await toTrustRoots(resolved.roots),
1545
+ signal,
1546
+ onProgress: (event) => {
1547
+ if (event.kind === "removed" || event.kind === "missing") {
1548
+ emit?.({
1549
+ kind: "removed",
1550
+ target: event.target,
1551
+ outcome: event.kind
1552
+ });
1553
+ return;
1554
+ }
1555
+ emit?.(event);
1556
+ }
1557
+ }));
1558
+ }
1559
+ }
1560
+ let status;
1561
+ if (face.length === 0)
1562
+ status = "nothing-to-do";
1563
+ else if (rejected.length > 0)
1564
+ status = "rejected";
1565
+ else
1566
+ status = "executed";
1567
+ const entries = buildOutcomeEntries(plan, expectedSet, stale, rejected, removal);
1568
+ const releasedBytes = entries.reduce((sum, entry) => isSuccessOutcome(entry.outcome) ? sum + (entry.bytes ?? 0) : sum, 0);
1569
+ const report = {
1570
+ status,
1571
+ plan,
1572
+ validation,
1573
+ removal,
1574
+ entries,
1575
+ stale,
1576
+ releasedBytes,
1577
+ drift
1578
+ };
1579
+ emit?.({ kind: "done", status, elapsedMs: Date.now() - startedAt });
1580
+ return report;
1581
+ }
1582
+ function createSweeper(options) {
1583
+ const resolved = resolveOptions(options);
1584
+ return {
1585
+ options: resolved,
1586
+ async plan(planOptions) {
1587
+ const startedAt = Date.now();
1588
+ const plan = await executePlan(resolved, planOptions, planOptions?.signal);
1589
+ planOptions?.onProgress?.({
1590
+ kind: "plan-done",
1591
+ plan,
1592
+ elapsedMs: Date.now() - startedAt
1593
+ });
1594
+ return plan;
1595
+ },
1596
+ run(runOptions) {
1597
+ return executeRun(resolved, runOptions, runOptions?.signal);
1598
+ }
1599
+ };
999
1600
  }
1000
1601
  // src/render.ts
1001
1602
  var BANNER = "SWEEP-NM";
@@ -1160,15 +1761,15 @@ function helpText(color) {
1160
1761
  }
1161
1762
 
1162
1763
  // src/init.ts
1163
- import { homedir as homedir4 } from "node:os";
1764
+ import { homedir as homedir5 } from "node:os";
1164
1765
  import { join as join4 } from "node:path";
1165
1766
  import { createInterface } from "node:readline/promises";
1166
1767
  var WHITESPACE = /\s/;
1167
1768
  function expandHome(token) {
1168
1769
  if (token === "~")
1169
- return homedir4();
1770
+ return homedir5();
1170
1771
  if (token.startsWith("~/") || token.startsWith("~\\"))
1171
- return join4(homedir4(), token.slice(2));
1772
+ return join4(homedir5(), token.slice(2));
1172
1773
  return token;
1173
1774
  }
1174
1775
  function splitAnswer(answer) {
@@ -1232,7 +1833,7 @@ async function runInit(deps) {
1232
1833
  return { state: "declined-overwrite" };
1233
1834
  }
1234
1835
  io.print(neutralLine("首次使用, 先确定扫描范围", color));
1235
- const home = homedir4();
1836
+ const home = homedir5();
1236
1837
  let roots = [];
1237
1838
  for (;; ) {
1238
1839
  const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${sanitizeLine(shortenHome(home, home))}`);
@@ -1278,7 +1879,7 @@ async function runInit(deps) {
1278
1879
  const text = `${JSON.stringify(config, null, 2)}
1279
1880
  `;
1280
1881
  await writeFile(configPath, text);
1281
- io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath, homedir4()))} ${paint("✓", "32", color)}`);
1882
+ io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath, homedir5()))} ${paint("✓", "32", color)}`);
1282
1883
  io.print("");
1283
1884
  io.print(text.trimEnd().split(`
1284
1885
  `).map((line) => ` ${line}`).join(`
@@ -1495,39 +2096,57 @@ async function resolveConfig(resolved, color) {
1495
2096
  return null;
1496
2097
  }
1497
2098
  var ABORTED_HINT = "整批中止, 未执行删除";
1498
- async function trustRoots(roots) {
1499
- return Promise.all(roots.map(async (root) => ({
1500
- configured: root,
1501
- real: await realpath3(root).catch(() => null) ?? root
1502
- })));
2099
+ function toRenderEntry(entry) {
2100
+ const notes = [];
2101
+ if (entry.kind === "suspect-install-tree")
2102
+ notes.push(`疑似安装树: ${entry.kindReason}`);
2103
+ if (entry.crossDevice !== undefined)
2104
+ notes.push(crossDeviceNote(entry.crossDevice));
2105
+ if (entry.bytes === undefined && entry.unmeasuredReason !== undefined)
2106
+ notes.push(`体积统计失败: ${entry.unmeasuredReason}`);
2107
+ return {
2108
+ target: entry.target,
2109
+ bytes: entry.bytes,
2110
+ project: basename(entry.project),
2111
+ suspect: entry.kind === "suspect-install-tree",
2112
+ ...notes.length > 0 ? { note: notes.join(" ") } : {}
2113
+ };
1503
2114
  }
1504
- function withOutcomes(entries, batch, accepted, removal, skipped) {
1505
- const outcomes = new Map;
1506
- for (const target of removal.removed)
1507
- outcomes.set(target, { ok: true });
1508
- for (const target of removal.missing)
1509
- outcomes.set(target, { ok: true });
1510
- for (const item of removal.failed)
1511
- outcomes.set(item.target, { ok: false, error: item.error });
1512
- const byTarget = new Map;
1513
- for (const [index, target] of batch.entries()) {
1514
- const real = accepted[index];
1515
- const outcome = real === undefined ? undefined : outcomes.get(real);
1516
- if (outcome !== undefined)
1517
- byTarget.set(target, outcome);
1518
- }
1519
- const fallbackOf = (entry) => {
1520
- if (removal.aborted !== undefined)
2115
+ function outcomeResult(entry) {
2116
+ const { outcome } = entry;
2117
+ switch (outcome.kind) {
2118
+ case "removed":
2119
+ case "missing":
2120
+ case "stale":
2121
+ return { ok: true };
2122
+ case "failed":
2123
+ return { ok: false, error: outcome.failure.message };
2124
+ case "skipped":
2125
+ return outcome.reason === "unmeasured" ? { ok: false } : { ok: false, error: entry.skipNote };
2126
+ case "not-attempted":
1521
2127
  return { ok: false, error: ABORTED_HINT };
1522
- const hint = skipped.get(entry.target);
1523
- if (hint !== undefined)
1524
- return { ok: false, error: hint };
1525
- return { ok: false };
1526
- };
1527
- return entries.map((entry) => ({
1528
- ...entry,
1529
- ...byTarget.get(entry.target) ?? fallbackOf(entry)
2128
+ case "rejected":
2129
+ case "not-expected":
2130
+ return { ok: false };
2131
+ }
2132
+ }
2133
+ var toExecuteEntry = (entry) => ({
2134
+ ...toRenderEntry(entry),
2135
+ ...outcomeResult(entry)
2136
+ });
2137
+ function planTrailer(plan) {
2138
+ const candidates = plan.entries.map((entry) => ({
2139
+ target: entry.target,
2140
+ bytes: entry.bytes,
2141
+ unmeasuredReason: entry.unmeasuredReason,
2142
+ suspect: entry.kind === "suspect-install-tree"
1530
2143
  }));
2144
+ const device = new Map;
2145
+ for (const entry of plan.entries) {
2146
+ if (entry.crossDevice !== undefined)
2147
+ device.set(entry.target, entry.crossDevice);
2148
+ }
2149
+ return [...collectSkips(candidates, device, plan.policy).trailer];
1531
2150
  }
1532
2151
  var BUILTIN_EXCLUDE_NAMES = new Set(DEFAULT_EXCLUDE);
1533
2152
  function collectNameNotes(excludeMatches, includeMatches, color) {
@@ -1552,103 +2171,59 @@ function collectNameNotes(excludeMatches, includeMatches, color) {
1552
2171
  warn("包含名单无一条命中, 本次扫描必为空结果 (请核对名字与大小写; 若名字位于被排除的目录之下则属预期)", color);
1553
2172
  return notes;
1554
2173
  }
1555
- function toEntries(hits, sizeResult, home, crossDevice) {
1556
- const bytesOf = new Map(sizeResult.entries.map((entry) => [
1557
- entry.target,
1558
- entry.bytes
1559
- ]));
1560
- const reasonOf = new Map(sizeResult.unmeasured.map((item) => [
1561
- item.target,
1562
- item.reason
1563
- ]));
1564
- const entries = [];
1565
- for (const hit of hits) {
1566
- const project = basename(hit.project);
1567
- const classification = classifyTarget(hit.target, { home });
1568
- const suspect = classification.kind === "suspect-install-tree";
1569
- const notes = [];
1570
- if (suspect)
1571
- notes.push(`疑似安装树: ${classification.reason}`);
1572
- const deviceKind = crossDevice.get(hit.target);
1573
- if (deviceKind !== undefined)
1574
- notes.push(crossDeviceNote(deviceKind));
1575
- const note = notes.length > 0 ? notes.join(" ") : undefined;
1576
- const bytes = bytesOf.get(hit.target);
1577
- if (bytes !== undefined) {
1578
- entries.push({ project, target: hit.target, bytes, suspect, note });
1579
- continue;
1580
- }
1581
- const reason = reasonOf.get(hit.target);
1582
- if (reason !== undefined) {
1583
- entries.push({
1584
- project,
1585
- target: hit.target,
1586
- suspect,
1587
- note: note === undefined ? `体积统计失败: ${reason}` : `${note} 体积统计失败: ${reason}`
1588
- });
1589
- }
1590
- }
1591
- return entries;
1592
- }
1593
2174
  async function sweep(config, options, color) {
1594
- const roots = config.roots;
1595
- const exclude = mergeNames(config.exclude, options.exclude);
1596
- const include = mergeNames(config.include, options.include);
1597
- const scanResult = await createParallelScanner().scan({ roots, exclude, include });
1598
- for (const warning of scanResult.warnings)
1599
- warn(warning, color);
1600
- const nameNotes = collectNameNotes(scanResult.excludeMatches, scanResult.includeMatches, color);
1601
- const tty = process.stdout.isTTY === true;
1602
- const runtime = tty ? runtimeLabel : undefined;
1603
- const sizeResult = await createSizer().measure(scanResult.hits.map((hit) => hit.target));
1604
- for (const warning of sizeResult.warnings)
1605
- warn(warning, color);
1606
- const home = homedir5();
1607
- const crossDevice = await findCrossDeviceTargets(scanResult.hits.map((hit) => hit.target), { roots });
1608
- const entries = toEntries(scanResult.hits, sizeResult, home, crossDevice);
1609
- const { trailer, hints: skippedHints } = collectSkips(entries, crossDevice, options.force);
2175
+ const sweeper = createSweeper({
2176
+ roots: config.roots,
2177
+ exclude: mergeNames(config.exclude, options.exclude),
2178
+ include: mergeNames(config.include, options.include),
2179
+ policy: { releaseSuspects: options.force }
2180
+ });
2181
+ const runtime = process.stdout.isTTY === true ? runtimeLabel : undefined;
2182
+ const home = homedir6();
2183
+ const onProgress = (event) => {
2184
+ if (event.kind === "warning")
2185
+ warn(event.warning.message, color);
2186
+ };
2187
+ const nameNotesOf = (plan) => collectNameNotes(plan.nameMatches.exclude, plan.nameMatches.include, color);
1610
2188
  if (!options.yes) {
2189
+ const plan = await sweeper.plan({ onProgress });
1611
2190
  print(render({
1612
2191
  mode: "preview",
1613
- roots,
1614
- entries,
2192
+ roots: plan.roots,
2193
+ entries: plan.entries.map(toRenderEntry),
1615
2194
  color,
1616
2195
  home,
1617
- notes: nameNotes,
2196
+ notes: nameNotesOf(plan),
1618
2197
  runtime,
1619
- trailer
2198
+ trailer: planTrailer(plan)
1620
2199
  }));
1621
2200
  return 0;
1622
2201
  }
1623
- const batch = deletionBatch(entries, crossDevice, options.force);
1624
- const { accepted, rejected } = await validateTargets(batch, { roots });
1625
- if (rejected.length > 0) {
2202
+ const report = await sweeper.run({ onProgress });
2203
+ if (report.status === "rejected") {
2204
+ const rejected = report.validation?.rejected ?? [];
1626
2205
  warn(`整批拒绝: ${rejected.length} 个目标未通过安全闸, 未执行任何删除`, color);
1627
2206
  for (const item of rejected)
1628
- notice(` ${item.target} (${item.reason})`);
2207
+ notice(` ${item.target} (${item.message})`);
1629
2208
  return 1;
1630
2209
  }
1631
- const removal = await removeTargets(accepted, {
1632
- roots: await trustRoots(roots)
1633
- });
1634
- const report = withOutcomes(entries, batch, accepted, removal, skippedHints);
1635
- const releasedBytes = report.reduce((total, entry) => entry.ok === false ? total : total + (entry.bytes ?? 0), 0);
1636
2210
  print(render({
1637
2211
  mode: "execute",
1638
- roots,
1639
- entries: report,
2212
+ roots: report.plan.roots,
2213
+ entries: report.entries.map(toExecuteEntry),
1640
2214
  color,
1641
2215
  home,
1642
- releasedBytes,
1643
- notes: nameNotes,
2216
+ releasedBytes: report.releasedBytes,
2217
+ notes: nameNotesOf(report.plan),
1644
2218
  runtime,
1645
- trailer
2219
+ trailer: planTrailer(report.plan)
1646
2220
  }));
1647
- if (removal.aborted !== undefined) {
1648
- warn(`整批中止: ${removal.aborted.reason}`, color);
1649
- notice(` 本轮未执行删除: ${batch.length} 处`);
2221
+ if (report.removal?.aborted !== undefined) {
2222
+ warn(`整批中止: ${report.removal.aborted.message}`, color);
2223
+ notice(` 本轮未执行删除: ${report.plan.batch.length} 处`);
1650
2224
  }
1651
- return report.some((entry) => entry.ok === false) ? 1 : 0;
2225
+ const summary = summarizeReport(report);
2226
+ return summary.failed === 0 && summary.unprocessed === 0 && !summary.aborted ? 0 : 1;
1652
2227
  }
1653
2228
  async function main() {
1654
2229
  const color = colorEnabled();