@iyowei/sweep-node-modules 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # sweep-node-modules
2
2
 
3
- [![CI](https://github.com/iyowei/sweep-node-modules/actions/workflows/ci.yml/badge.svg)](https://github.com/iyowei/sweep-node-modules/actions/workflows/ci.yml)
3
+ [![CI](https://github.com/iyowei/clis/actions/workflows/ci.yml/badge.svg)](https://github.com/iyowei/clis/actions/workflows/ci.yml)
4
4
  [![npm version](https://img.shields.io/npm/v/@iyowei/sweep-node-modules)](https://www.npmjs.com/package/@iyowei/sweep-node-modules)
5
5
  [![npm downloads](https://img.shields.io/npm/dm/@iyowei/sweep-node-modules)](https://www.npmjs.com/package/@iyowei/sweep-node-modules)
6
6
  ![node](https://img.shields.io/node/v/@iyowei/sweep-node-modules)
7
- ![bun](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fiyowei%2Fsweep-node-modules%2Fmain%2Fpackage.json&query=%24.packageManager&label=bun)
7
+ ![bun](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fiyowei%2Fclis%2Fmain%2Fpackage.json&query=%24.packageManager&label=bun)
8
8
 
9
9
  **English** | [中文](README.zh-CN.md)
10
10
 
@@ -30,8 +30,8 @@ Programmable API to sweep `node_modules` across workspace roots: scan, measure,
30
30
  ## Requirements
31
31
 
32
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)).
33
+ - Zero third-party runtime dependencies: built-in runtime capabilities only (see [ADR 0003](https://github.com/iyowei/clis/blob/main/packages/sweep-node-modules/docs/adrs/0003-zero-runtime-deps.md)).
34
+ - Windows, macOS, and Linux (see [ADR 0007](https://github.com/iyowei/clis/blob/main/packages/sweep-node-modules/docs/adrs/0007-platform-portability.md)).
35
35
  - Written in TypeScript; type declarations ship with the package.
36
36
 
37
37
  ## Installation
@@ -100,7 +100,7 @@ The CLI package is a thin shell over the orchestration layer: parse → call →
100
100
 
101
101
  ### `createSweeper(options): Sweeper`
102
102
 
103
- Creates the orchestrator: the whole chain behind one object. Factories do no IO, so a second instance costs nothing.
103
+ Creates the orchestrator: the whole chain behind one object. A second instance costs next to nothing (factories do no scan- or delete-level IO).
104
104
 
105
105
  - `options` `SweepOptions`:
106
106
  - `roots` `string[]` (required, non-empty): scan roots, absolute paths.
@@ -114,7 +114,7 @@ Creates the orchestrator: the whole chain behind one object. Factories do no IO,
114
114
  - `plan(options?)`: the read-only pass, see below.
115
115
  - `run(options?)`: the executing pass, see below.
116
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.
117
+ Parameter errors — empty `roots`, relative paths in `roots` (on win32, drive-relative paths like `/app` or `\app` are also rejected), empty-string or non-string items in `roots` / `exclude` / `include`, `home === ''`, or non-boolean `policy.releaseSuspects` — **throw synchronously** (`SweepError('INVALID_ARGUMENT', ..., { field })`) at construction: fail fast, before any IO. Every asynchronous entry point below rejects its promise instead.
118
118
 
119
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
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.
@@ -139,10 +139,11 @@ The read-only pass: scan + measure + classify + device check + batch constructio
139
139
  - `signal?` `AbortSignal`: cancellation signal, passed to each layer.
140
140
  - Returns: `Promise<SweepPlan>`:
141
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).
142
+ - `basis?` `SizeBasis`: the size basis of this run, present whenever the plan has any entries (it may differ from the per-entry bases when nothing was measured).
143
+ - `entries` `SweepEntry[]`: one entry per hit that still exists at measure time (a hit gone by then produces no entry; see `gone` in `SizeResult`): `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
144
  - `batch` `string[]`: the targets that would be deleted, in list order.
145
145
  - `skipped` `SkippedTarget[]`: every out-of-batch target with its `reason` and `note`.
146
+ - `trailer?` `string[]`: closing summary lines for skipped categories (same source as `SkipBook.trailer`, one line per category or cross-device form that occurred; empty array when nothing was skipped).
146
147
  - `warnings` `SweepWarning[]`: non-fatal scan / size warnings (`{ code, message, path?, errno? }`); `code` is a `SweepWarningCode`, the union of `ScanWarningCode` and `SizeWarningCode`.
147
148
  - `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.
148
149
 
@@ -160,7 +161,7 @@ Runs the read-only pass first (an old plan is never replayed: every fact is re-d
160
161
  - Returns: `Promise<SweepReport>`:
161
162
  - `status` `SweepRunStatus`: `'executed'` | `'rejected'` (whole batch) | `'nothing-to-do'` (empty batch).
162
163
  - `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
+ - `validation?` `ValidationResult`: present once the run entered the guard (a whole-batch rejection has it, with zero deletions). `removal?` `RemovalResult`: the removal buckets (`removed` / `missing` / `failed` / `aborted`); absent when no removal was executed.
164
165
  - `entries` `SweepOutcomeEntry[]`: one per plan entry, same order (the entry plus `outcome`).
165
166
  - `stale` `string[]`: targets pulled out by `staleTargets: 'missing'`.
166
167
  - `drift?` `SweepDrift`: `{ added, removed }`, present when `expectedBatch` was given.
@@ -270,7 +271,7 @@ const scan = await createScanner().scan({
270
271
  - `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
272
  - `warnings` `SweepWarning[]`: non-fatal size warnings (`code` is a `SizeWarningCode`).
272
273
  - `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
+ - `gone` `string[]`: no longer exists at measure time, ascending by `target` (all three buckets order this way).
274
275
 
275
276
  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
 
@@ -320,7 +321,7 @@ The invariants are judged per target with early exit: the leaf must be exactly `
320
321
 
321
322
  - `targets` `string[]`
322
323
  - `options` `CrossDeviceOptions`:
323
- - `roots` `string[]` (required): the owning root of a target is the most specific root that contains it.
324
+ - `roots` `string[]` (required): the owning root of a target is the innermost root containing it under strict path-containment order (`insideAnyRoot`, unaffected by literal string length from redundant separators).
324
325
  - `style?` `PathStyle`: path flavor; native by default.
325
326
  - `probe?` `DeviceProbe`: the device-number probe; defaults to `fsDeviceProbe` (inject to test cross-device flows on one filesystem).
326
327
  - Returns: `Promise<CrossDeviceEntry[]>`: `{ target, kind }` entries in input order; an empty array when nothing is cross-device.
@@ -352,7 +353,7 @@ The guard's path layer, exposed for tests and custom flows. Every predicate take
352
353
  #### `POSIX_STYLE` / `WIN32_STYLE`
353
354
 
354
355
  - `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
+ - `PathStyle`: `{ name: 'posix' | 'win32', ops: PathOps, caseInsensitive: boolean }`, where `PathOps` is the minimal path capability set (`sep` / `basename` / `relative` / `isAbsolute` / `parse` / `join` / `resolve` / `dirname` / `normalize`), satisfied by both `node:path` flavors.
356
357
 
357
358
  #### `nativeStyle(): PathStyle`
358
359
 
@@ -419,15 +420,16 @@ Collection (a per-level `lstat` walk) and detection in one call. The write side
419
420
  - `targets` `string[]`: guard-validated targets (realpath form).
420
421
  - `options` `RemovalOptions`:
421
422
  - `roots` `TrustRoot[]` (required): the trust roots that own the targets; a target under none of them aborts the batch.
423
+ - `style?` `PathStyle`: path flavor (win32 case folding and separator semantics); native by default.
422
424
  - `signal?` `AbortSignal`: checked between entries (the mid-`rm` rule is in [Progress and cancellation](#progress-and-cancellation)).
423
425
  - `onProgress?` `(event: RemovalProgressEvent) => void`: one event per entry leaving its bucket (`removed` / `missing` / `failed` / `aborted`).
424
426
  - Returns: `Promise<RemovalResult>`:
425
427
  - `removed` `string[]`: deleted, input order kept.
426
428
  - `missing` `string[]`: `rm` reported ENOENT and a re-check confirmed the target itself is gone (counted as success, input order kept).
427
429
  - `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.
430
+ - `aborted?` `AbortedBatch`: the pre-removal check failed mid-batch (`{ target, code, message, path? }`, with `code` an `AbortCode`); dispatching stops immediately (already in-flight entries in the 4-way concurrency window finish and are reported truthfully, while undispatched entries are never touched).
429
431
 
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.
432
+ Before touching disk, `removeTargets` synchronously hard-rejects malformed targets — trailing separators (`/` or `\`), relative `.` / `..` segments, a non-`node_modules` leaf, or a target outside every `roots[].real` — aborting the batch with `REVIEW_NOT_UNDER_ANY_ROOT`. Right before removing each target, it `lstat`-verifies the owning root's full ancestor chain (both `configured` and `real`, deduplicated) and then every component from `root.real` down to the target's parent: any non-directory (symlink included) aborts the batch (`REVIEW_HEAD_SYMLINK` / `REVIEW_COMPONENT_REPLACED`), and any vanished or unverifiable level fails closed on that entry (`REVIEW_COMPONENT_VANISHED` / `REVIEW_UNVERIFIED`, `partialRisk: false`, zero deletion).
431
433
 
432
434
  ```ts
433
435
  const removal = await removeTargets(accepted, {
@@ -561,7 +563,7 @@ In the `ok` case, `Config` carries `roots` (required) / `exclude` / `include`: a
561
563
  #### `sanitizeOutputLine(text): string`
562
564
 
563
565
  - `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.
566
+ - Returns: `string`: `sanitizeLine` except that the indentation at the very start of the input is kept (call it once per line to preserve per-line indentation, the tool's own hierarchy device); inner whitespace folds as usual.
565
567
 
566
568
  `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
569
 
@@ -576,23 +578,23 @@ One rule decides the channel: **failures that can be listed are returned; failur
576
578
 
577
579
  ### `SweepError`
578
580
 
579
- - `class SweepError extends Error`: `{ name: 'SweepError', code, message, details? }`.
581
+ - `class SweepError<Code extends SweepErrorCode = SweepErrorCode> extends Error`: `{ name: 'SweepError', code, message, details? }`.
580
582
  - `code` `SweepErrorCode`: `CONFIG_READ_FAILED` / `CONFIG_CORRUPT_JSON` / `CONFIG_CORRUPT_SHAPE` / `CONFIG_ABSENT` / `INVALID_ARGUMENT` / `CANCELLED`.
581
583
  - `message` `string`: the readable text (see the code rules below).
582
584
  - `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?)`.
585
+ - Constructor: `new SweepError(code, message, details?, options?)` (`options` accepts standard `ErrorOptions`, e.g. `{ cause }`).
584
586
  - The only class in the package: every other instance comes from a `createXxx()` factory, and every domain datum is a plain object.
585
587
 
586
- ### `isSweepError(value): value is SweepError`
588
+ ### `isSweepError(value): value is NarrowedSweepError` / `isSweepErrorCode(value, code)`
587
589
 
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
+ - `isSweepError(value)`: shape-based check (`name === 'SweepError'`, known `code`, and `typeof message === 'string'`; `instanceof Error` is not required), narrowing `details` by `code`.
591
+ - `isSweepErrorCode(value, code)`: narrows `value` directly to `SweepError<C>` with its exact `SweepErrorDetailsByCode[C]`.
590
592
 
591
593
  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
594
 
593
595
  ### Code families
594
596
 
595
- Domain codes by family (the full trigger table per code lives in the [API surface design](../../docs/designs/api-surface.md)):
597
+ Domain codes by family (the full trigger table per code lives in the [API surface design](https://github.com/iyowei/clis/blob/main/packages/sweep-node-modules/docs/designs/api-surface.md)):
596
598
 
597
599
  ```text
598
600
  Guard (validateTargets → rejected[].code)
@@ -633,8 +635,8 @@ Pass `onProgress` and / or `signal` to `plan` / `run`, or to any primitive that
633
635
  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.
634
636
 
635
637
  - 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
+ - Events are high-frequency and not order-bound (concurrent completion order); results are order-bound (hits and the three size buckets ascending by `target`; removal buckets and `stale` keep input order).
639
+ - 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 scan- or delete-level IO (a size factory probes for `du` once), so a second instance costs next to nothing.
638
640
  - 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.
639
641
 
640
642
  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.
@@ -652,9 +654,9 @@ The library has no `watch()` async iterator: the CLI consumes callbacks directly
652
654
 
653
655
  ## Data shapes and stability
654
656
 
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`.
657
+ - All **persisted / audit** domain data is plain objects and arrays: `JSON.stringify` is lossless (no classes, no `Map` / `Set`, no functions). Query helpers (`SkipBook.hints`, `crossDeviceIndex()`) return `ReadonlyMap`; they are lookup surfaces, not audit data. The one class in the package is `SweepError`.
656
658
  - 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.
659
+ - Deterministic results: `hits` and the three size buckets ascending by target; removal buckets and `stale` keep input order; scan dedupes by real path. Event order is explicitly not promised.
658
660
  - No side effects at import; no stdout / stderr writes; no TTY probing (the interactive wizard is a CLI-only surface).
659
661
 
660
662
  | Tier | What | The promise |
@@ -666,10 +668,11 @@ The library has no `watch()` async iterator: the CLI consumes callbacks directly
666
668
 
667
669
  ## Development
668
670
 
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.
671
+ Environment setup, common commands, dual-runtime verification, and commit hooks: see the [development guide](https://github.com/iyowei/clis/blob/main/docs/development.md). This package lives in the `packages/sweep-node-modules` directory of that repository.
670
672
 
671
673
  ## Documentation
672
674
 
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)
675
+ - [Engineering documentation index](https://github.com/iyowei/clis/blob/main/docs/README.md)
676
+ - [Product docs & ADRs](https://github.com/iyowei/clis/blob/main/packages/sweep-node-modules/docs/README.md)
677
+ - [API surface design](https://github.com/iyowei/clis/blob/main/packages/sweep-node-modules/docs/designs/api-surface.md): the authoritative export surface, error codes, and behavior contracts behind this page
678
+ - [Safety guardrails](https://github.com/iyowei/clis/blob/main/packages/sweep-node-modules/docs/designs/safety-guardrails.md), the full account (in Chinese)