@iyowei/sweep-node-modules 0.4.0 → 0.5.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/LICENSE +1 -1
- package/README.md +612 -93
- package/README.zh-CN.md +612 -93
- package/dist/classify.d.ts +48 -0
- package/dist/codes.d.ts +41 -0
- package/dist/config.d.ts +115 -0
- package/dist/delete.d.ts +155 -0
- package/dist/display.d.ts +29 -0
- package/dist/errors.d.ts +43 -0
- package/dist/guard.d.ts +230 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +1775 -0
- package/dist/manifest.json +4 -3
- package/dist/runtime.d.ts +26 -0
- package/dist/scan-native.d.ts +2 -0
- package/dist/scan-parallel.d.ts +2 -0
- package/dist/scan-prune.d.ts +2 -0
- package/dist/scan.d.ts +6 -0
- package/dist/size-du.d.ts +33 -0
- package/dist/size-js.d.ts +2 -0
- package/dist/size.d.ts +2 -0
- package/dist/skip.d.ts +35 -0
- package/dist/summary.d.ts +38 -0
- package/dist/sweep.d.ts +7 -0
- package/dist/types.d.ts +458 -0
- package/package.json +14 -52
- package/bin/sweep-nm.mjs +0 -190
- package/dist/cli.js +0 -1699
package/README.md
CHANGED
|
@@ -1,156 +1,675 @@
|
|
|
1
1
|
# sweep-node-modules
|
|
2
2
|
|
|
3
|
+
[](https://github.com/iyowei/sweep-node-modules/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/@iyowei/sweep-node-modules)
|
|
5
|
+
[](https://www.npmjs.com/package/@iyowei/sweep-node-modules)
|
|
6
|
+

|
|
7
|
+

|
|
8
|
+
|
|
3
9
|
**English** | [中文](README.zh-CN.md)
|
|
4
10
|
|
|
5
|
-
|
|
11
|
+
Programmable API to sweep `node_modules` across workspace roots: scan, measure, and safely remove them from your own scripts and tools. The CLI package is a thin shell over this same API.
|
|
12
|
+
|
|
13
|
+
> **Package repositioning**: up to 0.4.0, `@iyowei/sweep-node-modules` was the command-line tool. From 0.5.0 on, the name carries the API package (a pure library, no `bin`), and the CLI lives in its own package: **[@iyowei/sweep-node-modules-cli](https://www.npmjs.com/package/@iyowei/sweep-node-modules-cli)**. If you came here for the `sweep-nm` command, install that package; the command name, its flags, and the config file carry over. If you had the old name installed as a CLI, upgrading it yields this library and no command: uninstall the old global install and switch to the `-cli` package. The release notes carry the details.
|
|
14
|
+
|
|
15
|
+
## Contents
|
|
6
16
|
|
|
7
|
-
|
|
17
|
+
- [Requirements](#requirements)
|
|
18
|
+
- [Installation](#installation)
|
|
19
|
+
- [Quick start](#quick-start)
|
|
20
|
+
- [Two export layers](#two-export-layers)
|
|
21
|
+
- [Orchestration layer](#orchestration-layer)
|
|
22
|
+
- [Primitive layer](#primitive-layer)
|
|
23
|
+
- [Errors and codes](#errors-and-codes)
|
|
24
|
+
- [Progress and cancellation](#progress-and-cancellation)
|
|
25
|
+
- [Safety model](#safety-model)
|
|
26
|
+
- [Data shapes and stability](#data-shapes-and-stability)
|
|
27
|
+
- [Development](#development)
|
|
28
|
+
- [Documentation](#documentation)
|
|
8
29
|
|
|
9
30
|
## Requirements
|
|
10
31
|
|
|
11
|
-
- **Dual runtime
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
32
|
+
- **Dual runtime**: bun first, node fallback (identical behavior; bun starts faster). Node floor: `>= 22.18.0` (this package's `engines` field).
|
|
33
|
+
- Zero third-party runtime dependencies: built-in runtime capabilities only (see [ADR 0003](../../docs/adrs/0003-zero-runtime-deps.md)).
|
|
34
|
+
- Windows, macOS, and Linux (see [ADR 0007](../../docs/adrs/0007-platform-portability.md)).
|
|
35
|
+
- Written in TypeScript; type declarations ship with the package.
|
|
15
36
|
|
|
16
37
|
## Installation
|
|
17
38
|
|
|
18
|
-
|
|
39
|
+
```shell
|
|
40
|
+
npm install @iyowei/sweep-node-modules
|
|
41
|
+
bun add @iyowei/sweep-node-modules
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
This package installs no command: it is a library. For the command-line tool, install [@iyowei/sweep-node-modules-cli](https://www.npmjs.com/package/@iyowei/sweep-node-modules-cli).
|
|
19
45
|
|
|
20
|
-
|
|
46
|
+
## Quick start
|
|
21
47
|
|
|
22
|
-
|
|
48
|
+
```ts
|
|
49
|
+
import {
|
|
50
|
+
createSweeper,
|
|
51
|
+
formatBytes,
|
|
52
|
+
summarizeReport,
|
|
53
|
+
} from '@iyowei/sweep-node-modules';
|
|
23
54
|
|
|
24
|
-
|
|
55
|
+
// The orchestration layer never reads the platform config file: pass what to sweep yourself.
|
|
56
|
+
const sweeper = createSweeper({
|
|
57
|
+
roots: ['/Users/me/workspace/development'], // absolute paths
|
|
58
|
+
});
|
|
25
59
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
bunx @iyowei/sweep-node-modules
|
|
60
|
+
// plan(): read-only. Scan + measure + classify + device check + batch construction; zero deletions.
|
|
61
|
+
const plan = await sweeper.plan();
|
|
29
62
|
|
|
30
|
-
|
|
31
|
-
|
|
63
|
+
for (const entry of plan.entries) {
|
|
64
|
+
const size = entry.bytes === undefined ? '?' : formatBytes(entry.bytes);
|
|
65
|
+
const note = entry.inBatch ? '' : ` (${entry.skipNote})`;
|
|
66
|
+
console.log(
|
|
67
|
+
`${entry.inBatch ? '*' : '-'} ${size.padStart(9)} ${entry.target}${note}`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
console.log(`${plan.batch.length} target(s) ready to remove`);
|
|
71
|
+
|
|
72
|
+
// run(): re-decides every fact against the disk as it is now, passes the safety guard, then deletes.
|
|
73
|
+
const report = await sweeper.run({
|
|
74
|
+
expectedBatch: plan.batch, // keep the delete surface to the list just approved
|
|
75
|
+
staleTargets: 'missing', // a target someone else already removed is not a failure
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const summary = summarizeReport(report);
|
|
79
|
+
console.log(
|
|
80
|
+
`removed ${summary.counts.removed}, released ${formatBytes(report.releasedBytes)}`,
|
|
81
|
+
);
|
|
32
82
|
```
|
|
33
83
|
|
|
34
|
-
|
|
35
|
-
- Zero install; the package is resolved once per run
|
|
36
|
-
- Note: `bunx` and `npx` are not interchangeable; each is tied to one runtime: a bun-only machine has no `npx`, and a node-only machine has no `bunx`
|
|
84
|
+
Three things worth knowing before the first call:
|
|
37
85
|
|
|
38
|
-
|
|
86
|
+
- `roots` are absolute paths, and for deletion they must be **real paths**: no symlink on a root or any of its ancestors. macOS `tmpdir()` goes through `/var` (a system link), so normalize before using it as a root: `const root = await realpath(await mkdtemp(...))`. The read side is not subject to this.
|
|
87
|
+
- The orchestration layer never loads the platform config, and the interactive wizard stays in the CLI package. The config loaders further down are optional primitives for callers who want the same behavior inside their own tool.
|
|
88
|
+
- Nothing in this package writes to stdout or stderr: every piece of human-readable text is returned as a string, and where it goes is your call.
|
|
39
89
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
90
|
+
## Two export layers
|
|
91
|
+
|
|
92
|
+
| Layer | What it is | Reach for it when |
|
|
93
|
+
| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
|
94
|
+
| Orchestration: `createSweeper(...).plan()` / `.run()` | The whole chain: scan → measure → classify → device check → batch construction → safety guard → removal → report | You want the default. You say what to sweep and decide what the report means |
|
|
95
|
+
| Primitives: `createScanner` / `createSizer` / `validateTargets` / `removeTargets` / ... | Single-point capabilities, each usable on its own | You need step-by-step control, or one link of the chain inside a pipeline of your own |
|
|
96
|
+
|
|
97
|
+
The CLI package is a thin shell over the orchestration layer: parse → call → render → confirm. Business semantics live here in one place; the CLI is a consumer, not a second implementation of the same logic.
|
|
98
|
+
|
|
99
|
+
## Orchestration layer
|
|
100
|
+
|
|
101
|
+
### `createSweeper(options): Sweeper`
|
|
102
|
+
|
|
103
|
+
Creates the orchestrator: the whole chain behind one object. Factories do no IO, so a second instance costs nothing.
|
|
104
|
+
|
|
105
|
+
- `options` `SweepOptions`:
|
|
106
|
+
- `roots` `string[]` (required, non-empty): scan roots, absolute paths.
|
|
107
|
+
- `exclude?` `string[]`: directory names to skip; a match at any level between a root and a hit skips the whole subtree. Defaults to `DEFAULT_EXCLUDE` (the same built-in list the CLI applies).
|
|
108
|
+
- `include?` `string[]`: allow list; a hit is taken only when one of these names appears between a root and the `node_modules`. Defaults to `[]` (no filtering). When a name matches both lists, `exclude` wins.
|
|
109
|
+
- `home?` `string | null`: the home directory (one shared semantics for list abbreviation and the hidden-dir classification). Defaults to `os.homedir()`; `null` turns off the home-body guard and the hidden-dir classification.
|
|
110
|
+
- `style?` `PathStyle`: path flavor; native by default (for tests).
|
|
111
|
+
- `policy?` `SweepPolicy`: `{ releaseSuspects: boolean }`. Defaults to `{ releaseSuspects: false }`.
|
|
112
|
+
- Returns: `Sweeper`:
|
|
113
|
+
- `options` `Readonly<ResolvedSweepOptions>`: the resolved read-only snapshot (defaults merged), handy for logging and audit.
|
|
114
|
+
- `plan(options?)`: the read-only pass, see below.
|
|
115
|
+
- `run(options?)`: the executing pass, see below.
|
|
116
|
+
|
|
117
|
+
Parameter errors (`roots` empty, or not a string array) **throw synchronously** at construction: fail fast, before any IO. Every asynchronous entry point below rejects its promise instead.
|
|
118
|
+
|
|
119
|
+
- The name lists take the same merge the CLI applies (`mergeNames`): duplicates dropped, and `node_modules` / `.git` silently removed since a name can never take effect there.
|
|
120
|
+
- `policy.releaseSuspects` is the library-side `--force`: it lets suspected install trees into the delete batch, releases only that category, and relaxes no guard invariant. Cross-device targets are unaffected either way.
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
const sweeper = createSweeper({
|
|
124
|
+
roots, // required, non-empty: scan roots, absolute paths
|
|
125
|
+
exclude, // default: DEFAULT_EXCLUDE (the same built-in list the CLI applies)
|
|
126
|
+
include, // default: [] (no filtering)
|
|
127
|
+
home, // default: os.homedir(); null turns off the home-body guard and the hidden-dir classification
|
|
128
|
+
style, // posix / win32 path flavor; native by default (for tests)
|
|
129
|
+
policy: { releaseSuspects: false },
|
|
130
|
+
});
|
|
43
131
|
```
|
|
44
132
|
|
|
45
|
-
|
|
46
|
-
- Install once, then run `sweep-nm` directly; when bun is present, the actual work still prefers bun
|
|
133
|
+
### `sweeper.plan(options?): Promise<SweepPlan>`
|
|
47
134
|
|
|
48
|
-
|
|
135
|
+
The read-only pass: scan + measure + classify + device check + batch construction, zero deletions.
|
|
49
136
|
|
|
50
|
-
|
|
137
|
+
- `options?` `SweepPlanOptions`:
|
|
138
|
+
- `onProgress?` `(event: SweepProgressEvent) => void`: progress callback; phase events plus every primitive event passed through.
|
|
139
|
+
- `signal?` `AbortSignal`: cancellation signal, passed to each layer.
|
|
140
|
+
- Returns: `Promise<SweepPlan>`:
|
|
141
|
+
- `roots` / `exclude` / `include` / `policy`: the effective inputs, echoed for audit (the names have already been through `mergeNames`).
|
|
142
|
+
- `basis?` `SizeBasis`: the size basis of this run, when anything was measured (same value as every `entry.basis`).
|
|
143
|
+
- `entries` `SweepEntry[]`: one entry per hit: `target` / `project` / `root` / `bytes?` / `basis?` / `kind` / `kindReason?` / `crossDevice?` / `unmeasuredCode?` / `unmeasuredReason?` / `inBatch`, plus `skipReason` and `skipNote` when out of the batch (the code and the human note travel on the entry, so a review table needs no join).
|
|
144
|
+
- `batch` `string[]`: the targets that would be deleted, in list order.
|
|
145
|
+
- `skipped` `SkippedTarget[]`: every out-of-batch target with its `reason` and `note`.
|
|
146
|
+
- `warnings` `SweepWarning[]`: non-fatal scan / size warnings (`{ code, message, path?, errno? }`); `code` is a `SweepWarningCode`, the union of `ScanWarningCode` and `SizeWarningCode`.
|
|
147
|
+
- `nameMatches`: `{ exclude: NameMatch[]; include: NameMatch[] }`, per-name hit counts for both lists, so a name that never matched (a typo) is visible before it matters.
|
|
51
148
|
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
|
|
149
|
+
```ts
|
|
150
|
+
const plan = await sweeper.plan({ onProgress, signal });
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### `sweeper.run(options?): Promise<SweepReport>`
|
|
154
|
+
|
|
155
|
+
Runs the read-only pass first (an old plan is never replayed: every fact is re-decided against the disk as it is now), then sends the batch through the safety guard and removes it.
|
|
156
|
+
|
|
157
|
+
- `options?` `SweepRunOptions` (extends `SweepPlanOptions`, so `onProgress` and `signal` carry over):
|
|
158
|
+
- `expectedBatch?` `readonly string[]`: the list that was approved. The delete surface becomes `expectedBatch` ∩ the live batch: targets that appeared since are not deleted (they show up in `drift.added`, with outcome `{ kind: 'not-expected' }`), and targets that vanished or got blocked since are not deleted either (`drift.removed`). It narrows the scope; it does not skip re-validation.
|
|
159
|
+
- `staleTargets?` `'reject' | 'missing'` (default `'reject'`): what to do with targets that no longer exist when the guard runs. `'missing'` pulls them out of the batch and counts them as already achieved (success side) without aborting the batch (think: a concurrent cleaner got there first); the default keeps the conservative rule that one rejection aborts the whole batch with zero deletions. Only `GUARD_TARGET_MISSING` is eligible; unreadable targets and every other rejection still reject the batch.
|
|
160
|
+
- Returns: `Promise<SweepReport>`:
|
|
161
|
+
- `status` `SweepRunStatus`: `'executed'` | `'rejected'` (whole batch) | `'nothing-to-do'` (empty batch).
|
|
162
|
+
- `plan` `SweepPlan`: the live plan this run actually used. If it differs from an earlier `plan()`, this one wins, and the delta is in `drift`.
|
|
163
|
+
- `validation?` `ValidationResult` / `removal?` `RemovalResult`: the guard result and the removal buckets (`removed` / `missing` / `failed` / `aborted`); absent when nothing was executed.
|
|
164
|
+
- `entries` `SweepOutcomeEntry[]`: one per plan entry, same order (the entry plus `outcome`).
|
|
165
|
+
- `stale` `string[]`: targets pulled out by `staleTargets: 'missing'`.
|
|
166
|
+
- `drift?` `SweepDrift`: `{ added, removed }`, present when `expectedBatch` was given.
|
|
167
|
+
- `releasedBytes` `number`: the measured bytes on the success side (removed + missing + stale).
|
|
168
|
+
|
|
169
|
+
`outcome` is the `EntryOutcome` discriminated union. Its `kind` is one of: `removed` / `missing` / `stale` (the success side: deleted, verified already gone, or never reached the delete surface), `failed`, `rejected`, `not-attempted` (a batch abort stopped before it), `not-expected` (outside `expectedBatch`), `skipped` (policy kept it out of the batch).
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
const report = await sweeper.run({
|
|
173
|
+
onProgress,
|
|
174
|
+
signal,
|
|
175
|
+
expectedBatch,
|
|
176
|
+
staleTargets,
|
|
177
|
+
});
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### `isSuccessOutcome(outcome): boolean`
|
|
181
|
+
|
|
182
|
+
- `outcome` `EntryOutcome`
|
|
183
|
+
- Returns: `boolean`: `true` for the success side (`removed` / `missing` / `stale`), `false` for everything else (real failures and unprocessed entries).
|
|
184
|
+
|
|
185
|
+
Use it instead of hand-rolling `kind !== 'x' && kind !== 'y'`: the hand-rolled version silently misjudges the day a new kind ships, while the library function moves with the version.
|
|
186
|
+
|
|
187
|
+
### `summarizeReport(report): SweepSummary`
|
|
188
|
+
|
|
189
|
+
- `report` `SweepReport`
|
|
190
|
+
- Returns: `SweepSummary`:
|
|
191
|
+
- `counts` `Record<EntryOutcomeKind, number>`: per-kind counts, always present, `0` by default.
|
|
192
|
+
- `succeeded` `number`: `removed` + `missing` + `stale`.
|
|
193
|
+
- `unprocessed` `number`: `skipped` + `rejected` + `not-attempted` + `not-expected`.
|
|
194
|
+
- `failed` `number`: real failures.
|
|
195
|
+
- `aborted` `boolean`: whether a batch abort happened (a `removal.aborted` exists).
|
|
196
|
+
|
|
197
|
+
### Success and exit codes
|
|
198
|
+
|
|
199
|
+
What counts as a failed run is a product decision, not a data fact, so there is no `ok` field to read; the library hands you the numbers and three common recipes:
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
const summary = summarizeReport(report);
|
|
203
|
+
|
|
204
|
+
// Strict (the CLI package's posture): anything unprocessed or failed makes the run a failure
|
|
205
|
+
const strict =
|
|
206
|
+
summary.failed === 0 &&
|
|
207
|
+
summary.unprocessed === 0 &&
|
|
208
|
+
!summary.aborted &&
|
|
209
|
+
report.status !== 'rejected';
|
|
210
|
+
|
|
211
|
+
// Relaxed (interactive tools): only real failures and a batch abort count
|
|
212
|
+
const relaxed =
|
|
213
|
+
summary.failed === 0 && !summary.aborted && report.status !== 'rejected';
|
|
214
|
+
|
|
215
|
+
// Read-only pass: nothing counts as a failure, just report the numbers
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## Primitive layer
|
|
219
|
+
|
|
220
|
+
Every primitive stands alone, imports without side effects, and prints nothing; async entries reject on failure. A read-only snapshot is just `scan` → `measure` → `classifyTarget`, and nothing on that path can delete.
|
|
221
|
+
|
|
222
|
+
### Scanning
|
|
223
|
+
|
|
224
|
+
#### `createScanner(): Scanner`
|
|
55
225
|
|
|
56
|
-
|
|
226
|
+
- Returns: `Scanner`:
|
|
227
|
+
- `name` `string`: the candidate's neutral id (`'parallel'`), for benchmarks and logs to tell implementations apart.
|
|
228
|
+
- `scan(options)`: see below.
|
|
57
229
|
|
|
58
|
-
|
|
59
|
-
|
|
230
|
+
#### `scanner.scan(options): Promise<ScanResult>`
|
|
231
|
+
|
|
232
|
+
- `options` `ScanOptions`:
|
|
233
|
+
- `roots` `string[]` (required): scan roots (the caller guarantees absolute paths).
|
|
234
|
+
- `exclude` `string[]` (required here: pass `[]` to disable): directory names; a match at any level between a root and a hit skips the whole subtree.
|
|
235
|
+
- `include` `string[]` (required here): allow list; an empty array means no filtering; `exclude` wins when both match.
|
|
236
|
+
- `signal?` `AbortSignal`: checked before each walk task starts; an abort rejects with `SweepError('CANCELLED')`.
|
|
237
|
+
- `onProgress?` `(event: ScanProgressEvent) => void`: one `hit` event per hit.
|
|
238
|
+
- Returns: `Promise<ScanResult>`:
|
|
239
|
+
- `hits` `ScanHit[]`: `{ project, target, root }[]`, ascending by `target`, deduped by real path. `root` is the first root (in input order) that reaches the hit, so grouping by root is deterministic and reproducible.
|
|
240
|
+
- `warnings` `SweepWarning[]`: non-fatal scan warnings (`code` is a `ScanWarningCode`); a root that is missing or unreadable does not stop the walk.
|
|
241
|
+
- `excludeMatches` / `includeMatches` `NameMatch[]`: `{ name, hits }[]`, always present (unmatched names are listed with `hits: 0`), so a name that never matched is visible before it matters.
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
const scan = await createScanner().scan({
|
|
245
|
+
roots,
|
|
246
|
+
exclude: [...DEFAULT_EXCLUDE], // required here: pass [] to disable
|
|
247
|
+
include: [],
|
|
248
|
+
signal,
|
|
249
|
+
onProgress: (event) => ..., // one 'hit' event per hit
|
|
250
|
+
});
|
|
60
251
|
```
|
|
61
252
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
253
|
+
### Measuring
|
|
254
|
+
|
|
255
|
+
#### `createSizer(): Sizer`
|
|
256
|
+
|
|
257
|
+
- Returns: `Sizer`:
|
|
258
|
+
- `name` `string`: the candidate's neutral id (`'du'` for the `du` fast path, `'js'` for the pure implementation), for benchmarks and logs.
|
|
259
|
+
- `basis` `SizeBasis`: this instance's size basis, readable before the call.
|
|
260
|
+
- `measure(targets, options?)`: see below.
|
|
261
|
+
|
|
262
|
+
#### `sizer.measure(targets, options?): Promise<SizeResult>`
|
|
263
|
+
|
|
264
|
+
- `targets` `string[]`: the paths to measure (typically `scan.hits.map((hit) => hit.target)`).
|
|
265
|
+
- `options?` `MeasureOptions`:
|
|
266
|
+
- `signal?` `AbortSignal`: checked between targets (the `du` batch path checks before and after the batch).
|
|
267
|
+
- `onProgress?` `(event: MeasureProgressEvent) => void`: one event per target (`measured` / `unmeasured` / `gone`).
|
|
268
|
+
- Returns: `Promise<SizeResult>`:
|
|
269
|
+
- `entries` `SizeEntry[]`: measured targets (`{ target, bytes }`), ascending by `target`.
|
|
270
|
+
- `basis` `SizeBasis`: `'disk-usage'` (the `du` fast path reports what the disk actually holds) or `'logical-bytes'` (the pure implementation reports logical bytes). One call, one basis; read it instead of guessing, before or after the call. Windows always measures `logical-bytes`.
|
|
271
|
+
- `warnings` `SweepWarning[]`: non-fatal size warnings (`code` is a `SizeWarningCode`).
|
|
272
|
+
- `unmeasured` `UnmeasuredEntry[]`: exists but cannot be measured (`{ target, code, reason }`, with `code` an `UnmeasuredCode`), ascending by `target`.
|
|
273
|
+
- `gone` `string[]`: no longer exists at measure time, input order kept.
|
|
274
|
+
|
|
275
|
+
Every input target lands in exactly one bucket, and there is no fourth case: `entries` (measured), `unmeasured` (exists but cannot be measured), `gone` (no longer exists at measure time). That identity is a contract, so no `'unknown'` fallback branch is needed.
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
const size = await createSizer().measure(targets, { signal, onProgress });
|
|
73
279
|
```
|
|
74
280
|
|
|
75
|
-
|
|
281
|
+
### Classifying
|
|
76
282
|
|
|
77
|
-
|
|
78
|
-
- The most direct entry point; afterwards just run `sweep-nm` (on Windows via `bin\sweep-nm.cmd`)
|
|
283
|
+
#### `classifyTarget(target, options?): Classification`
|
|
79
284
|
|
|
80
|
-
|
|
285
|
+
- `target` `string`: a `node_modules` path.
|
|
286
|
+
- `options?` `ClassifyOptions`:
|
|
287
|
+
- `style?` `PathStyle`: path flavor; native by default.
|
|
288
|
+
- `home?` `string | null`: the home directory, for the hidden-dir form below. Defaults to `os.homedir()`; `null` turns that form off.
|
|
289
|
+
- Returns: `Classification`:
|
|
290
|
+
- `kind` `TargetKind`: `'project'` | `'suspect-install-tree'`.
|
|
291
|
+
- `reason?` `string`: the human phrase for a suspected install tree.
|
|
81
292
|
|
|
82
|
-
|
|
83
|
-
# preview: list every node_modules under the configured roots with its size; nothing is touched
|
|
84
|
-
sweep-nm
|
|
293
|
+
Pure path judgment, no IO, the same semantics as the CLI's list markers. The suspect forms, in order: an ancestor segment on the built-in list (plus `extensions` and `_npx`), a parent directory named `lib` (version managers keep global packages at `<version>/lib/node_modules`), and a `node_modules` under a hidden directory of the home directory. Comparisons fold case on every platform: an extra false positive lands on the safe side.
|
|
85
294
|
|
|
86
|
-
|
|
87
|
-
|
|
295
|
+
```ts
|
|
296
|
+
const { kind, reason } = classifyTarget(target, options?);
|
|
297
|
+
// kind: 'project' | 'suspect-install-tree'
|
|
298
|
+
```
|
|
88
299
|
|
|
89
|
-
|
|
90
|
-
sweep-nm --yes --force
|
|
300
|
+
### Safety guard
|
|
91
301
|
|
|
92
|
-
|
|
93
|
-
sweep-nm --exclude my-kits --exclude url-tool
|
|
302
|
+
#### `validateTargets(targets, options): Promise<ValidationResult>`
|
|
94
303
|
|
|
95
|
-
|
|
96
|
-
|
|
304
|
+
- `targets` `string[]`: candidate targets.
|
|
305
|
+
- `options` `ValidateOptions`:
|
|
306
|
+
- `roots` `string[]` (required): scan roots spelled as configured; the anchor check reads the spelling, not the real path.
|
|
307
|
+
- `home?` `string | null`: the home-body guard; defaults to `os.homedir()`, `null` turns it off.
|
|
308
|
+
- `style?` `PathStyle`: path flavor; native by default.
|
|
309
|
+
- `signal?` `AbortSignal`: checked between targets.
|
|
310
|
+
- Returns: `Promise<ValidationResult>`:
|
|
311
|
+
- `accepted` `string[]`: the removable targets: realpath-normalized, deduped, input order kept.
|
|
312
|
+
- `rejected` `RejectedTarget[]`: `{ target, code, message, details? }` per refusal, aligned one-to-one with the input; `code` is a `GuardCode`, and `details?` a `RejectionDetails` (`{ errno?, root?, symlink? }`).
|
|
313
|
+
- `mappings` `PathMapping[]`: `{ original, real }` pairs positionally aligned with `accepted`; show `original`, delete `real`, and stop aligning by index position by hand.
|
|
97
314
|
|
|
98
|
-
|
|
99
|
-
sweep-nm config
|
|
315
|
+
The invariants are judged per target with early exit: the leaf must be exactly `node_modules`; the target must exist and be readable (realpath); a root whose configured spelling chain carries a symlink rejects targets under it; filesystem root bodies and the home directory itself are refused; the real path must still end in `node_modules`, sit under a declared root, and be unique by real path. Rejections are **returned, not thrown**: the whole list is always processed, and every refusal carries a `code` to branch on.
|
|
100
316
|
|
|
101
|
-
|
|
102
|
-
|
|
317
|
+
### Device boundary
|
|
318
|
+
|
|
319
|
+
#### `findCrossDeviceTargets(targets, options): Promise<CrossDeviceEntry[]>`
|
|
320
|
+
|
|
321
|
+
- `targets` `string[]`
|
|
322
|
+
- `options` `CrossDeviceOptions`:
|
|
323
|
+
- `roots` `string[]` (required): the owning root of a target is the most specific root that contains it.
|
|
324
|
+
- `style?` `PathStyle`: path flavor; native by default.
|
|
325
|
+
- `probe?` `DeviceProbe`: the device-number probe; defaults to `fsDeviceProbe` (inject to test cross-device flows on one filesystem).
|
|
326
|
+
- Returns: `Promise<CrossDeviceEntry[]>`: `{ target, kind }` entries in input order; an empty array when nothing is cross-device.
|
|
327
|
+
|
|
328
|
+
`kind: CrossDeviceKind` is `'on-path' | 'target-itself'`: either the mount point sits between the root and the target, or the target itself is the mount point. The two forms have different remedies (declare the mount point as its own root, or unmount the volume), so they are reported apart, and neither is released by policy. The result is an array rather than a `Map` so it survives `JSON.stringify` into an audit.
|
|
329
|
+
|
|
330
|
+
#### `crossDeviceIndex(entries): ReadonlyMap<string, CrossDeviceKind>`
|
|
331
|
+
|
|
332
|
+
- `entries` `readonly CrossDeviceEntry[]`
|
|
333
|
+
- Returns: `ReadonlyMap<string, CrossDeviceKind>`: the lookup view (the `has` / `get` shape the skip family takes as its second parameter).
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
const crossDevice = await findCrossDeviceTargets(targets, { roots });
|
|
337
|
+
const index = crossDeviceIndex(crossDevice); // the lookup view, for the skip family
|
|
103
338
|
```
|
|
104
339
|
|
|
105
|
-
|
|
340
|
+
#### `fsDeviceProbe(path, follow): Promise<number | null>`
|
|
106
341
|
|
|
107
|
-
|
|
342
|
+
- `path` `string`
|
|
343
|
+
- `follow` `boolean`: `true` takes `stat` semantics (resolve a final symlink), `false` takes `lstat` semantics (do not).
|
|
344
|
+
- Returns: `Promise<number | null>`: the `st_dev` of the path, or `null` when it cannot be read (the path is gone, or unreadable).
|
|
108
345
|
|
|
109
|
-
The
|
|
346
|
+
The default implementation of `DeviceProbe` (`(path: string, follow: boolean) => Promise<number | null>`). Both semantics exist because the two call sites need opposite readings: a root is read with `follow: true` (its resolved directory is the reference), a target with `follow: false` (aligned with `fs.rm`, which deletes a link, not through it).
|
|
110
347
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
348
|
+
### Path flavor and anchor checks
|
|
349
|
+
|
|
350
|
+
The guard's path layer, exposed for tests and custom flows. Every predicate takes its `PathStyle` explicitly and does no IO.
|
|
351
|
+
|
|
352
|
+
#### `POSIX_STYLE` / `WIN32_STYLE`
|
|
353
|
+
|
|
354
|
+
- `PathStyle` constants, ready for injection: `WIN32_STYLE` folds case before every comparison; `POSIX_STYLE` does not.
|
|
355
|
+
- `PathStyle`: `{ name: 'posix' | 'win32', ops: PathOps, caseInsensitive: boolean }`, where `PathOps` is the minimal path capability set (`sep` / `basename` / `relative` / `isAbsolute` / `parse` / `join` / `resolve` / `dirname`), satisfied by both `node:path` flavors.
|
|
356
|
+
|
|
357
|
+
#### `nativeStyle(): PathStyle`
|
|
358
|
+
|
|
359
|
+
- Returns: `PathStyle`: the flavor of the current platform; the default wherever a `style` option is omitted.
|
|
360
|
+
|
|
361
|
+
#### `dedupeKey(realPath, style): string`
|
|
362
|
+
|
|
363
|
+
- `realPath` `string`, `style` `PathStyle`
|
|
364
|
+
- Returns: `string`: the dedupe key of a real path (case-folded on win32).
|
|
365
|
+
|
|
366
|
+
#### `hasNodeModulesLeaf(target, style): boolean`
|
|
367
|
+
|
|
368
|
+
- `target` `string`, `style` `PathStyle`
|
|
369
|
+
- Returns: `boolean`: whether the last segment is exactly `node_modules` (case-insensitive on win32).
|
|
370
|
+
|
|
371
|
+
#### `insideAnyRoot(realPath, roots, style): boolean`
|
|
372
|
+
|
|
373
|
+
- `realPath` `string`, `roots` `string[]`, `style` `PathStyle`
|
|
374
|
+
- Returns: `boolean`: whether the path sits strictly under one of the roots, by `path.relative` semantics rather than string prefixes. Equal to a root, an escape (`..`) and an absolute result (a cross-drive path on win32) all count as outside.
|
|
375
|
+
|
|
376
|
+
#### `isFilesystemRootBody(realPath, style): boolean`
|
|
377
|
+
|
|
378
|
+
- `realPath` `string`, `style` `PathStyle`
|
|
379
|
+
- Returns: `boolean`: whether the path is the filesystem root itself (posix `/`, a drive root on win32).
|
|
380
|
+
|
|
381
|
+
#### `isHomeBody(realPath, home, style): boolean`
|
|
382
|
+
|
|
383
|
+
- `realPath` `string`, `home` `string | null`, `style` `PathStyle`
|
|
384
|
+
- Returns: `boolean`: whether the path is the home directory itself; `home: null` turns the check off.
|
|
385
|
+
|
|
386
|
+
#### `firstSymlinkOnAnchor(links): string | null`
|
|
387
|
+
|
|
388
|
+
- `links` `AnchorLink[]`: `{ path, symlink }` per chain level, `symlink` judged by `lstat` (a link to anywhere counts, dangling included: the fact of a link on the chain is the evidence).
|
|
389
|
+
- Returns: `string | null`: the path of the first symlink level, or `null` when every level is a real directory.
|
|
390
|
+
|
|
391
|
+
Anchors are judged on the configured spelling, not on realpath: realpath always reports the current resolution, so a name swapped for a link leaves no trace in it, while the spelling is where the swap shows. A system link (macOS `/var`, `/tmp`) hits the same check, on purpose: on the spelling layer, a user environment and an attack are indistinguishable, so both are rejected, and the fix is to spell the real path.
|
|
392
|
+
|
|
393
|
+
#### `anchorChainPaths(root, style): string[]`
|
|
394
|
+
|
|
395
|
+
- `root` `string`: a scan root or any write target; the endpoint itself is included, and the filesystem root is not (it cannot be a symlink).
|
|
396
|
+
- Returns: `string[]`: the level-by-level prefixes from the filesystem root's first child down to the endpoint. A relative spelling is first absolutized under the given style (the same frame the `lstat` calls read).
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
anchorChainPaths('/Users/x/ws/app', POSIX_STYLE);
|
|
400
|
+
// ['/Users', '/Users/x', '/Users/x/ws', '/Users/x/ws/app']
|
|
120
401
|
```
|
|
121
402
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
-
|
|
125
|
-
-
|
|
126
|
-
|
|
127
|
-
- `
|
|
128
|
-
|
|
403
|
+
#### `firstSymlinkOnTarget(target): Promise<string | null>`
|
|
404
|
+
|
|
405
|
+
- `target` `string`
|
|
406
|
+
- Returns: `Promise<string | null>`: the first symlink on the chain, or `null` when the chain is all real directories or no level can be verified.
|
|
407
|
+
|
|
408
|
+
Collection (a per-level `lstat` walk) and detection in one call. The write side uses it before a write: a write follows a link and rewrites its target, so the same chain reading the delete side applies here, under one shared implementation.
|
|
409
|
+
|
|
410
|
+
#### `firstSymlinkOnRoot(root): Promise<string | null>`
|
|
411
|
+
|
|
412
|
+
- `root` `string`
|
|
413
|
+
- Returns: `Promise<string | null>`: the same implementation as `firstSymlinkOnTarget`, kept under its own name because the call site reads it as the trust anchor of a scan root.
|
|
414
|
+
|
|
415
|
+
### Removal
|
|
416
|
+
|
|
417
|
+
#### `removeTargets(targets, options): Promise<RemovalResult>`
|
|
418
|
+
|
|
419
|
+
- `targets` `string[]`: guard-validated targets (realpath form).
|
|
420
|
+
- `options` `RemovalOptions`:
|
|
421
|
+
- `roots` `TrustRoot[]` (required): the trust roots that own the targets; a target under none of them aborts the batch.
|
|
422
|
+
- `signal?` `AbortSignal`: checked between entries (the mid-`rm` rule is in [Progress and cancellation](#progress-and-cancellation)).
|
|
423
|
+
- `onProgress?` `(event: RemovalProgressEvent) => void`: one event per entry leaving its bucket (`removed` / `missing` / `failed` / `aborted`).
|
|
424
|
+
- Returns: `Promise<RemovalResult>`:
|
|
425
|
+
- `removed` `string[]`: deleted, input order kept.
|
|
426
|
+
- `missing` `string[]`: `rm` reported ENOENT and a re-check confirmed the target itself is gone (counted as success, input order kept).
|
|
427
|
+
- `failed` `TargetFailure[]`: `{ target, code, errno?, message, partialRisk }`, with `code` a `RemoveFailureCode`; `partialRisk: true` means content may be partially deleted, so flag it for human review (a `partialRisk: false` failure never attempted a deletion).
|
|
428
|
+
- `aborted?` `AbortedBatch`: the guard's re-check failed mid-batch (`{ target, code, message, path? }`, with `code` an `AbortCode`); nothing from the abort point on was attempted.
|
|
429
|
+
|
|
430
|
+
Right before removing each target, the chain from the root down to the target's parent is re-verified component by component; a swap found mid-way stops the whole batch.
|
|
431
|
+
|
|
432
|
+
```ts
|
|
433
|
+
const removal = await removeTargets(accepted, {
|
|
434
|
+
roots: await toTrustRoots(roots),
|
|
435
|
+
signal,
|
|
436
|
+
onProgress,
|
|
437
|
+
});
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
#### `toTrustRoots(roots): Promise<TrustRoot[]>`
|
|
441
|
+
|
|
442
|
+
- `roots` `string[]`: configured spellings.
|
|
443
|
+
- Returns: `Promise<TrustRoot[]>`: `{ configured, real }` pairs, one per root; `real` falls back to the spelling when realpath fails.
|
|
444
|
+
|
|
445
|
+
Pairs each configured root with its real path. The pairing is half of the anchor defense; do not hand-roll it.
|
|
446
|
+
|
|
447
|
+
#### `removeBatch(targets, options): Promise<BatchOutcome>`
|
|
448
|
+
|
|
449
|
+
The recommended write-side entry: safety guard + whole-batch rejection rule + trust pairing + removal in one call, and the caller never needs to know `TrustRoot` exists.
|
|
450
|
+
|
|
451
|
+
- `targets` `string[]`
|
|
452
|
+
- `options` `RemoveBatchOptions`:
|
|
453
|
+
- `roots` `string[]` (required): scan roots spelled as configured; the guard judges containment and anchors on them, and the pairing helper feeds the delete side.
|
|
454
|
+
- `home?` / `style?` / `signal?` / `onProgress?`: as in `validateTargets` and `removeTargets`.
|
|
455
|
+
- `staleTargets?` `'reject' | 'missing'`: the same narrow tolerance as `sweeper.run`.
|
|
456
|
+
- Returns: `Promise<BatchOutcome>`: `{ status: 'rejected', rejected }` (zero deletions) or `{ status: 'executed', accepted, mappings, stale, removal }`.
|
|
457
|
+
|
|
458
|
+
```ts
|
|
459
|
+
const outcome = await removeBatch(targets, { roots, staleTargets });
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
### Skip set
|
|
463
|
+
|
|
464
|
+
For assembling the "what will not be deleted, and why" list yourself:
|
|
465
|
+
|
|
466
|
+
| You have / want | Use |
|
|
467
|
+
| ------------------------------------------------- | --------------------------------------------- |
|
|
468
|
+
| hits + size + classification, need candidates | `toSkipCandidates(hits, size, options?)` |
|
|
469
|
+
| "does this one enter the batch?" (single boolean) | `skipsBatch(entry, crossDevice, policy)` |
|
|
470
|
+
| "why doesn't it?" (single code) | `skipReasonOf(entry, crossDevice, policy)` |
|
|
471
|
+
| only the batch target list | `deletionBatch(entries, crossDevice, policy)` |
|
|
472
|
+
| the whole book: codes + notes + trailer | `collectSkips(entries, crossDevice, policy)` |
|
|
473
|
+
| the human label for a cross-device form | `crossDeviceNote(kind)` |
|
|
474
|
+
|
|
475
|
+
#### `toSkipCandidates(hits, size, options?): SkipCandidate[]`
|
|
476
|
+
|
|
477
|
+
- `hits` `readonly ScanHit[]`: scan hits.
|
|
478
|
+
- `size` `SizeResult`: the size result for those hits.
|
|
479
|
+
- `options?` `ClassifyOptions`: classification options passed through.
|
|
480
|
+
- Returns: `SkipCandidate[]`: `{ target, bytes?, unmeasuredReason?, suspect }`, in hit order (targets in `size.gone` are produced as well, with `bytes` undefined).
|
|
481
|
+
|
|
482
|
+
#### `skipsBatch(entry, crossDevice, policy): boolean`
|
|
483
|
+
|
|
484
|
+
- `entry` `SkipCandidate`; `crossDevice` `ReadonlyMap<string, CrossDeviceKind>` (build it with `crossDeviceIndex`); `policy` `SweepPolicy`.
|
|
485
|
+
- Returns: `boolean`: whether the entry is held out of the delete batch.
|
|
486
|
+
|
|
487
|
+
#### `skipReasonOf(entry, crossDevice, policy): SkipReason | null`
|
|
488
|
+
|
|
489
|
+
- Same parameters.
|
|
490
|
+
- Returns: `SkipReason | null`, where `null` means the entry is in the batch. The check order is the priority: cross-device (both forms, unaffected by policy), then unmeasured, then suspected install tree (released only by `policy.releaseSuspects`).
|
|
491
|
+
|
|
492
|
+
#### `deletionBatch(entries, crossDevice, policy): string[]`
|
|
493
|
+
|
|
494
|
+
- Same parameters.
|
|
495
|
+
- Returns: `string[]`: the batch targets, in list order.
|
|
496
|
+
|
|
497
|
+
#### `collectSkips(entries, crossDevice, policy): SkipBook`
|
|
498
|
+
|
|
499
|
+
- Same parameters.
|
|
500
|
+
- Returns: `SkipBook`:
|
|
501
|
+
- `entries` `ReadonlyArray<SkippedTarget>`: `{ target, reason, note }`, the code and the human note in one place (same source and values as `plan.skipped`).
|
|
502
|
+
- `trailer` `string[]`: the closing lines, one per category, present only when that category appears.
|
|
503
|
+
- `hints` `ReadonlyMap<string, string>`: target to trailing note, measured entries only.
|
|
504
|
+
|
|
505
|
+
`SkipCandidate.suspect` is required by design: it carries the entire "will the semantic gate stop this?" information, so that a bare size entry cannot slip into the write side and have the safety semantics silently default away. `toSkipCandidates` fills the field for you.
|
|
506
|
+
|
|
507
|
+
#### `crossDeviceNote(kind): string`
|
|
508
|
+
|
|
509
|
+
- `kind` `CrossDeviceKind`
|
|
510
|
+
- Returns: `string`: the human label for a cross-device form.
|
|
511
|
+
|
|
512
|
+
### Config (optional primitives)
|
|
513
|
+
|
|
514
|
+
The library never reads the platform config file on its own; these loaders exist for callers who want the CLI's config behavior inside their own tool:
|
|
515
|
+
|
|
516
|
+
#### `resolveConfigPath(options): ResolvedConfigPath`
|
|
517
|
+
|
|
518
|
+
- `options` `ResolveConfigPathOptions`:
|
|
519
|
+
- `flag?` `string`: the `--config` flag value, the highest priority.
|
|
520
|
+
- `platform?` `string`: platform id; defaults to `process.platform` (inject `'win32'` in tests).
|
|
521
|
+
- `homedir?` `string`: defaults to `os.homedir()`.
|
|
522
|
+
- `env?` `EnvTable`: environment-variable table; defaults to `process.env` (it carries `SWEEP_NM_CONFIG` and, on win32, `APPDATA` / `USERPROFILE`).
|
|
523
|
+
- Returns: `ResolvedConfigPath`: `{ path, source }` with `source: ConfigSource` being `'flag' | 'env' | 'platform-default'`.
|
|
524
|
+
|
|
525
|
+
Priority: the `--config` flag > the `SWEEP_NM_CONFIG` env > the platform default. The platform default is `~/.config/sweep-node-modules/config.json`; on win32, `%APPDATA%\sweep-node-modules\config.json`, falling back to `USERPROFILE\AppData\Roaming` when `APPDATA` is unset.
|
|
526
|
+
|
|
527
|
+
#### `loadConfig(path): Promise<LoadConfigResult>`
|
|
528
|
+
|
|
529
|
+
- `path` `string`
|
|
530
|
+
- Returns: `Promise<LoadConfigResult>`: `{ state: 'ok', config }` or `{ state: 'absent' }`. A missing file is a normal state (the wizard branches on it); a corrupted file or a read failure throws `SweepError` (`CONFIG_CORRUPT_JSON` / `CONFIG_CORRUPT_SHAPE` / `CONFIG_READ_FAILED`).
|
|
531
|
+
|
|
532
|
+
In the `ok` case, `Config` carries `roots` (required) / `exclude` / `include`: an omitted `exclude` field defaults to `DEFAULT_EXCLUDE`, an omitted `include` to `[]`, while an explicitly written empty array stands for taking over the list.
|
|
533
|
+
|
|
534
|
+
#### `loadResolvedConfig(resolved): Promise<LoadConfigResult>`
|
|
535
|
+
|
|
536
|
+
- `resolved` `ResolvedConfigPath`
|
|
537
|
+
- Returns: the same shape as `loadConfig`.
|
|
538
|
+
- Stricter when the source is explicit: an `--config` flag or `SWEEP_NM_CONFIG` path that does not exist throws (`SweepError('CONFIG_ABSENT')`) instead of returning `absent`, so a mistyped path cannot silently degrade into "no config". The platform-default source keeps the soft behavior.
|
|
539
|
+
|
|
540
|
+
#### `mergeNames(configNames, cliNames): string[]`
|
|
541
|
+
|
|
542
|
+
- `configNames` `string[]`, `cliNames` `string[]`
|
|
543
|
+
- Returns: `string[]`: config names first, CLI names appended, deduped across sources (first occurrence wins), with `node_modules` and `.git` silently dropped (neither can ever take effect in a name list).
|
|
544
|
+
|
|
545
|
+
#### `DEFAULT_EXCLUDE`
|
|
546
|
+
|
|
547
|
+
- `readonly string[]`: the built-in exclusion list: package-manager and version-manager install trees, editor extension directories, and system / application data roots.
|
|
548
|
+
|
|
549
|
+
### Display helpers
|
|
550
|
+
|
|
551
|
+
#### `formatBytes(bytes): string`
|
|
552
|
+
|
|
553
|
+
- `bytes` `number`
|
|
554
|
+
- Returns: `string`: the list's human-readable size, stepping through `B` / `KB` / `MB` / `GB` / `TB` by 1024; one decimal, dropped for integer values.
|
|
555
|
+
|
|
556
|
+
#### `sanitizeLine(text): string`
|
|
557
|
+
|
|
558
|
+
- `text` `string`
|
|
559
|
+
- Returns: `string`: control characters stripped (C0 incl. ESC and DEL, C1, bidi controls, zero-width and BOM), remaining whitespace (newlines included) folded to single spaces, ends trimmed.
|
|
560
|
+
|
|
561
|
+
#### `sanitizeOutputLine(text): string`
|
|
562
|
+
|
|
563
|
+
- `text` `string`
|
|
564
|
+
- Returns: `string`: `sanitizeLine` except that leading indentation is kept on each line (the tool's own hierarchy device); inner whitespace folds as usual.
|
|
565
|
+
|
|
566
|
+
`sanitizeLine` / `sanitizeOutputLine` are the single shared implementation of output sanitization. Run external data (paths, names) through these before it reaches any output surface; the CLI does, and no second implementation should exist.
|
|
567
|
+
|
|
568
|
+
## Errors and codes
|
|
569
|
+
|
|
570
|
+
One rule decides the channel: **failures that can be listed are returned; failures that stop everything are thrown.**
|
|
571
|
+
|
|
572
|
+
| Channel | What goes there | Where it shows up |
|
|
573
|
+
| ------------ | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
|
|
574
|
+
| Return value | Expected domain outcomes: guard rejections, removal failures, batch aborts, unmeasurable targets, policy skips | `rejected` / `failed` / `aborted` / `unmeasured` / `gone` / `skipped` |
|
|
575
|
+
| Throw | Cannot start or cannot continue: bad arguments, broken config, cancellation | Sync entries throw; async entries reject |
|
|
576
|
+
|
|
577
|
+
### `SweepError`
|
|
578
|
+
|
|
579
|
+
- `class SweepError extends Error`: `{ name: 'SweepError', code, message, details? }`.
|
|
580
|
+
- `code` `SweepErrorCode`: `CONFIG_READ_FAILED` / `CONFIG_CORRUPT_JSON` / `CONFIG_CORRUPT_SHAPE` / `CONFIG_ABSENT` / `INVALID_ARGUMENT` / `CANCELLED`.
|
|
581
|
+
- `message` `string`: the readable text (see the code rules below).
|
|
582
|
+
- `details?` `SweepErrorDetails`: a discriminated union keyed by `code`: `{ path, errno? }`, `{ path }`, `{ path, field }`, `{ path, source }`, `{ field }`, `{ phase, partial? }`.
|
|
583
|
+
- Constructor: `new SweepError(code, message, details?)`.
|
|
584
|
+
- The only class in the package: every other instance comes from a `createXxx()` factory, and every domain datum is a plain object.
|
|
585
|
+
|
|
586
|
+
### `isSweepError(value): value is SweepError`
|
|
587
|
+
|
|
588
|
+
- `value` `unknown`
|
|
589
|
+
- Returns: `value is SweepError`: a shape-based check (an `Error` shape plus `name` and a known `code`), not a class check.
|
|
590
|
+
|
|
591
|
+
In packaged or multi-instance environments (where two copies of the library can coexist in one process), `instanceof SweepError` gives false negatives; use the shape-based guard there. Unexpected internal exceptions are not wrapped: they bubble unchanged.
|
|
592
|
+
|
|
593
|
+
### Code families
|
|
594
|
+
|
|
595
|
+
Domain codes by family (the full trigger table per code lives in the [API surface design](../../docs/designs/api-surface.md)):
|
|
596
|
+
|
|
597
|
+
```text
|
|
598
|
+
Guard (validateTargets → rejected[].code)
|
|
599
|
+
GUARD_LEAF_NOT_NODE_MODULES · GUARD_TARGET_MISSING · GUARD_TARGET_UNREADABLE ·
|
|
600
|
+
GUARD_REALPATH_FAILED · GUARD_ROOT_ANCHOR_SYMLINK · GUARD_FILESYSTEM_ROOT_BODY ·
|
|
601
|
+
GUARD_HOME_BODY · GUARD_REAL_LEAF_NOT_NODE_MODULES · GUARD_OUTSIDE_ROOTS ·
|
|
602
|
+
GUARD_DUPLICATE_TARGET
|
|
603
|
+
|
|
604
|
+
Removal failures (RemovalResult.failed[].code)
|
|
605
|
+
REMOVE_FAILED · REMOVE_ENOENT_SURVIVOR · REVIEW_UNVERIFIED · REVIEW_COMPONENT_VANISHED
|
|
606
|
+
|
|
607
|
+
Batch aborts (RemovalResult.aborted.code)
|
|
608
|
+
REVIEW_NOT_UNDER_ANY_ROOT · REVIEW_HEAD_SYMLINK · REVIEW_COMPONENT_REPLACED
|
|
609
|
+
|
|
610
|
+
Size, unmeasured (SizeResult.unmeasured[].code)
|
|
611
|
+
SIZE_UNMEASURED_PERMISSION · SIZE_UNMEASURED_NOT_DIR · SIZE_UNMEASURED_LOOP ·
|
|
612
|
+
SIZE_UNMEASURED_UNPARSEABLE · SIZE_UNMEASURED_CONTROL_CHAR · SIZE_UNMEASURED_OTHER
|
|
613
|
+
|
|
614
|
+
Warnings (SweepWarning.code)
|
|
615
|
+
SCAN_ROOT_MISSING · SCAN_ROOT_UNREADABLE · SCAN_ROOT_NOT_DIR · SCAN_ROOT_UNAVAILABLE ·
|
|
616
|
+
SCAN_DIR_UNREADABLE · SIZE_DU_OUTPUT_MISMATCH · SIZE_DU_LINE_UNATTRIBUTED ·
|
|
617
|
+
SIZE_SUBPATH_FAILED · SIZE_TARGET_VANISHED · SIZE_DU_UNAVAILABLE
|
|
618
|
+
|
|
619
|
+
Skip reasons (SweepEntry.skipReason / SkippedTarget.reason)
|
|
620
|
+
suspect-install-tree · cross-device:on-path · cross-device:target-itself · unmeasured
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
Rules that matter:
|
|
624
|
+
|
|
625
|
+
- **Branch on `code` and `details`; never parse `message`.** `message` is plain language for humans (currently Chinese). To localize, drop `message` and build your own text from `code` + `details`.
|
|
626
|
+
- The three realpath rejection codes share one `message` on purpose; they are told apart by `code` and `details.errno` (`ENOENT` / `EACCES` / the rest), because their handling points in opposite directions: "no longer exists" is tolerable, "unreadable" is not.
|
|
627
|
+
- Codes are frozen once shipped: new ones are added, none are re-pointed, no value is recycled. Keep a `default` branch in a `switch` and record the raw value rather than folding it into "other".
|
|
628
|
+
|
|
629
|
+
## Progress and cancellation
|
|
129
630
|
|
|
130
|
-
|
|
631
|
+
Pass `onProgress` and / or `signal` to `plan` / `run`, or to any primitive that supports them (`scan`, `measure`, `validateTargets`, `removeTargets`, `removeBatch`).
|
|
131
632
|
|
|
132
|
-
|
|
633
|
+
Event kinds: `phase` (start / done per pipeline phase, `SweepPhase`: `scan` · `measure` · `classify` · `device` · `plan` · `validate` · `remove`), the primitive events (`hit` · `measured` · `unmeasured` · `skipped` · `removed` · `failed` · `aborted` · `warning`), and a terminal event: a `plan()` stream always ends with `plan-done` (carrying the full plan), a `run()` stream always ends with `done` (carrying the run status). Nothing follows a terminal event; on cancellation the stream ends with a throw instead.
|
|
133
634
|
|
|
134
|
-
|
|
635
|
+
- Callbacks run synchronously and are not awaited; a throwing callback bubbles and aborts the call (no swallowing).
|
|
636
|
+
- Events are high-frequency and not order-bound (concurrent completion order); results are order-bound (hits ascending, buckets keep input order).
|
|
637
|
+
- Do not call the same `Sweeper` instance from inside a callback, and do not run two calls on one instance at once (reentrancy is undefined). Factories do no IO, so a second instance costs nothing.
|
|
638
|
+
- Cancellation is checked between items and at phase boundaries; the call rejects with `SweepError('CANCELLED')`. Removal never interrupts a single `rm` midway (that would only manufacture a new half-deleted state): cancellation lands between targets, and the error carries `details.partial` with what was already done. Other phases carry `details.phase` and no partial results.
|
|
135
639
|
|
|
136
|
-
|
|
640
|
+
The library has no `watch()` async iterator: the CLI consumes callbacks directly, and that is the common case. The design doc carries a ~20-line bridge reference for editor-style hosts that want a `for await` loop.
|
|
137
641
|
|
|
138
|
-
|
|
642
|
+
## Safety model
|
|
139
643
|
|
|
140
|
-
|
|
644
|
+
> The character of this package in one line: when anything is uncertain, the default is not to delete.
|
|
141
645
|
|
|
142
|
-
**
|
|
646
|
+
- **Importing does nothing; `plan()` deletes nothing.** Deletion only happens through an explicit `run()` / `removeTargets()` / `removeBatch()` call.
|
|
647
|
+
- **Name and location both decide.** Only directories named exactly `node_modules` are eligible, and only under the roots you declared; containment is judged by path hierarchy, not string prefixes, so `..` traversal and lookalike paths are rejected. Filesystem root bodies and the home directory itself are refused outright.
|
|
648
|
+
- **Real paths, or the batch is refused.** The delete side requires roots (and their ancestors) to be symlink-free; hitting one rejects the whole batch and points at the link. The read side still scans through a symlinked root. The threshold follows reversibility: the irreversible step gets no benefit of the doubt.
|
|
649
|
+
- **One rejection stops the whole batch** (zero deletions) rather than letting the rest through; right before removal, the path from the root down to the target's parent is re-verified component by component, and a swap mid-way halts the remaining deletions. The single narrow exception is an explicit `staleTargets: 'missing'`, and it only tolerates "the target is already gone": it relaxes no invariant and never adds a target to the delete surface.
|
|
650
|
+
- **Two categories stay out of the batch**: suspected install trees (released only by an explicit `policy.releaseSuspects`) and cross-device targets (not released by policy at all; fix the layout instead: declare the mount point as its own root, or unmount the volume). Targets whose size cannot be measured are never deleted: keep rather than guess.
|
|
651
|
+
- **External data is sanitized before it reaches output.** `sanitizeLine` / `sanitizeOutputLine` are the single implementation every output surface shares; use them, not a copy.
|
|
143
652
|
|
|
144
|
-
|
|
653
|
+
## Data shapes and stability
|
|
145
654
|
|
|
146
|
-
|
|
655
|
+
- All domain data is plain objects and arrays: `JSON.stringify` is lossless (no classes, no `Map` / `Set`, no functions). The one class in the package is `SweepError`.
|
|
656
|
+
- Time-free by design: no timestamps on domain data (the only clock reading is `elapsedMs` on progress events). A shape written into today's JSONL audit reads back as tomorrow's decision input.
|
|
657
|
+
- Deterministic results: `hits` ascending by target, buckets keep input order, scan dedupes by real path. Event order is explicitly not promised.
|
|
658
|
+
- No side effects at import; no stdout / stderr writes; no TTY probing (the interactive wizard is a CLI-only surface).
|
|
147
659
|
|
|
148
|
-
|
|
660
|
+
| Tier | What | The promise |
|
|
661
|
+
| ------------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------- |
|
|
662
|
+
| Frozen | Domain type field names, `code` values, `SkipReason` values, function signatures, `EntryOutcome` kinds | A breaking change takes a major version |
|
|
663
|
+
| Frozen, additions allowed | Option objects (`SweepOptions`, `SweepRunOptions`, `MeasureOptions`, etc.) | New fields are a minor |
|
|
664
|
+
| Evolving | `message` / `reason` / `note` wording | Not stable verbatim |
|
|
665
|
+
| Not promised | Progress event order, order inside `warnings` | Result order is promised, event order is not |
|
|
149
666
|
|
|
150
667
|
## Development
|
|
151
668
|
|
|
152
|
-
Environment setup, common commands, dual-runtime verification, and commit hooks: see the [development guide](docs/development.md).
|
|
669
|
+
Environment setup, common commands, dual-runtime verification, and commit hooks: see the [development guide](../../docs/development.md). This package lives in the `packages/sweep-node-modules` directory of that repository.
|
|
153
670
|
|
|
154
671
|
## Documentation
|
|
155
672
|
|
|
156
|
-
- [Engineering documentation index](docs/README.md)
|
|
673
|
+
- [Engineering documentation index](../../docs/README.md)
|
|
674
|
+
- [API surface design](../../docs/designs/api-surface.md): the authoritative export surface, error codes, and behavior contracts behind this page
|
|
675
|
+
- [Safety guardrails](../../docs/safety-guardrails.md), the full account (in Chinese)
|