dir-analysis-tool 2.0.7 → 3.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.
@@ -0,0 +1,539 @@
1
+ import "ignore";
2
+ //#region src/format/bytes.d.ts
3
+ /**
4
+ * Byte formatting and parsing.
5
+ *
6
+ * Two unit systems are supported:
7
+ * - `iec` (default): powers of 1024 with unambiguous IEC labels (KiB, MiB, GiB, …).
8
+ * - `si`: powers of 1000 with SI labels (kB, MB, GB, …), matching most file managers.
9
+ */
10
+ type ByteUnits = "iec" | "si";
11
+ /**
12
+ * Formats a byte count for humans, keeping three significant digits
13
+ * (`1.23 MiB`, `12.3 MiB`, `123 MiB`). Negative values keep their sign,
14
+ * which is useful for deltas.
15
+ */
16
+ export declare function formatBytes(bytes: number, units?: ByteUnits): string;
17
+ /**
18
+ * Parses a human size into bytes.
19
+ *
20
+ * - Plain numbers are bytes: `4096`.
21
+ * - Single letters and IEC suffixes are binary: `10k`, `1.5M`, `2GiB`.
22
+ * - Two-letter SI suffixes are decimal: `10kB`, `500MB`, `1GB`.
23
+ *
24
+ * Suffixes are case-insensitive. Throws a `RangeError` for anything else.
25
+ */
26
+ export declare function parseSize(input: string | number): number;
27
+ //#endregion
28
+ //#region src/types.d.ts
29
+ export declare const CATEGORIES: readonly ["code", "documents", "images", "videos", "audio", "archives", "fonts", "data", "other"];
30
+ export type Category = (typeof CATEGORIES)[number];
31
+ export interface SizeStat {
32
+ files: number;
33
+ bytes: number;
34
+ }
35
+ export interface FileEntry {
36
+ path: string;
37
+ bytes: number;
38
+ /** Last modification time, ISO 8601. */
39
+ modified: string;
40
+ }
41
+ export interface DirectoryEntry {
42
+ path: string;
43
+ /** Total apparent size of everything below this directory. */
44
+ bytes: number;
45
+ /** Total number of files below this directory. */
46
+ files: number;
47
+ }
48
+ export interface ExtensionStat extends SizeStat {
49
+ /** Lowercased extension including the dot, or `""` for files without one. */
50
+ extension: string;
51
+ }
52
+ export interface DuplicateGroup {
53
+ /** SHA-256 of the file contents, hex encoded. */
54
+ hash: string;
55
+ /** Size of each copy. */
56
+ bytes: number;
57
+ /** Space reclaimable by keeping one copy: `bytes * (files.length - 1)`. */
58
+ wastedBytes: number;
59
+ files: string[];
60
+ }
61
+ export interface ItemList<T> {
62
+ /** Number of matching items. */
63
+ count: number;
64
+ /** Combined size of the matching items. */
65
+ bytes: number;
66
+ items: T[];
67
+ }
68
+ export interface ScanError {
69
+ path: string;
70
+ /** Node.js error code, for example `EACCES` or `ELOOP`. */
71
+ code: string;
72
+ message: string;
73
+ }
74
+ export interface TreeNode {
75
+ name: string;
76
+ path: string;
77
+ type: "directory" | "file";
78
+ bytes: number;
79
+ files: number;
80
+ children?: TreeNode[];
81
+ /** Children not shown because of the per-level limit. */
82
+ omitted?: SizeStat & {
83
+ entries: number;
84
+ };
85
+ }
86
+ export type BudgetMetric = "size" | "disk" | "files" | "dirs" | "largest" | "large" | "duplicates" | "wasted" | "empty" | "stale" | "errors";
87
+ export type BudgetOperator = "<" | "<=" | ">" | ">=" | "=" | "!=";
88
+ export interface BudgetResult {
89
+ /** The rule as written, for example `size<=500MB`. */
90
+ rule: string;
91
+ metric: BudgetMetric;
92
+ operator: BudgetOperator;
93
+ limit: number;
94
+ actual: number;
95
+ passed: boolean;
96
+ }
97
+ export interface Summary {
98
+ /** Apparent size: the sum of file lengths. */
99
+ bytes: number;
100
+ /** Allocated size on disk (block usage). Equals `bytes` where the platform does not report blocks. */
101
+ diskBytes: number;
102
+ files: number;
103
+ directories: number;
104
+ /** Size of the largest file. */
105
+ largestFileBytes: number;
106
+ symlinks: number;
107
+ /** Extra hard links skipped so that shared data is counted once. */
108
+ hardlinks: number;
109
+ /** Entries skipped by exclusion rules (default excludes, --exclude, .gitignore). */
110
+ excluded: number;
111
+ /** Files skipped by size or date filters. */
112
+ filtered: number;
113
+ /** Paths that could not be read. */
114
+ errors: number;
115
+ }
116
+ export interface ToolInfo {
117
+ name: string;
118
+ version: string;
119
+ }
120
+ export interface AnalysisSettings {
121
+ exclude: string[];
122
+ defaultExcludes: boolean;
123
+ gitignore: boolean;
124
+ maxDepth: number | null;
125
+ followSymlinks: boolean;
126
+ countHardlinks: boolean;
127
+ minSize: number | null;
128
+ maxSize: number | null;
129
+ modifiedAfter: string | null;
130
+ modifiedBefore: string | null;
131
+ }
132
+ export interface AnalysisResult {
133
+ schemaVersion: 3;
134
+ tool: ToolInfo;
135
+ /** Absolute path of the analyzed directory. */
136
+ root: string;
137
+ startedAt: string;
138
+ durationMs: number;
139
+ settings: AnalysisSettings;
140
+ summary: Summary;
141
+ /** Every category is always present, including empty ones. */
142
+ types: Record<Category, SizeStat>;
143
+ /** Sorted by size, largest first. */
144
+ extensions: ExtensionStat[];
145
+ largestDirectories: DirectoryEntry[];
146
+ largestFiles: FileEntry[];
147
+ largeFiles?: ItemList<FileEntry> & {
148
+ threshold: number;
149
+ };
150
+ duplicates?: ItemList<DuplicateGroup> & {
151
+ files: number;
152
+ wastedBytes: number;
153
+ };
154
+ emptyFiles?: ItemList<FileEntry>;
155
+ emptyDirectories?: {
156
+ count: number;
157
+ items: string[];
158
+ };
159
+ staleFiles?: ItemList<FileEntry> & {
160
+ modifiedBefore: string;
161
+ };
162
+ tree?: TreeNode;
163
+ budgets?: BudgetResult[];
164
+ /** At most 100 entries; `summary.errors` has the full count. */
165
+ errors: ScanError[];
166
+ }
167
+ export interface ChangedFile {
168
+ path: string;
169
+ leftBytes: number;
170
+ rightBytes: number;
171
+ delta: number;
172
+ }
173
+ export interface DirectoryDelta {
174
+ path: string;
175
+ leftBytes: number;
176
+ rightBytes: number;
177
+ delta: number;
178
+ }
179
+ export interface ComparisonSide {
180
+ root: string;
181
+ summary: Summary;
182
+ types: Record<Category, SizeStat>;
183
+ }
184
+ export interface ComparisonResult {
185
+ schemaVersion: 3;
186
+ tool: ToolInfo;
187
+ startedAt: string;
188
+ durationMs: number;
189
+ /** How `changed` was decided: by size only, or by size then content hash. */
190
+ mode: "size" | "content";
191
+ left: ComparisonSide;
192
+ right: ComparisonSide;
193
+ delta: {
194
+ bytes: number;
195
+ diskBytes: number;
196
+ files: number;
197
+ directories: number;
198
+ };
199
+ added: ItemList<FileEntry>;
200
+ removed: ItemList<FileEntry>;
201
+ changed: {
202
+ count: number;
203
+ delta: number;
204
+ items: ChangedFile[];
205
+ };
206
+ unchanged: number;
207
+ /** Directories with the largest size change, largest absolute change first. */
208
+ directories: DirectoryDelta[];
209
+ }
210
+ //#endregion
211
+ //#region src/core/duplicates.d.ts
212
+ interface DuplicateProgress {
213
+ stage: "sample" | "full";
214
+ done: number;
215
+ total: number;
216
+ }
217
+ //#endregion
218
+ //#region src/core/exclude.d.ts
219
+ /** Directories skipped unless default excludes are turned off. */
220
+ export declare const DEFAULT_EXCLUDES: readonly string[];
221
+ //#endregion
222
+ //#region src/core/options.d.ts
223
+ /** Default number of concurrent filesystem operations. */
224
+ export declare const DEFAULT_CONCURRENCY: number;
225
+ /** Options shared by every operation that walks a directory tree. */
226
+ interface ScanSettings {
227
+ /** Gitignore-style patterns to skip, relative to the root (`*.log`, `build/`, `docs/**\/*.pdf`). */
228
+ exclude?: readonly string[] | undefined;
229
+ /** Skip `.git`, `.hg`, `.svn`, and `node_modules`. Default: `true`. */
230
+ defaultExcludes?: boolean | undefined;
231
+ /** Honor `.gitignore` files. Default: `false`. */
232
+ gitignore?: boolean | undefined;
233
+ /** Directory levels to descend below the root; `0` scans only the root's own files. Default: unlimited. */
234
+ maxDepth?: number | null | undefined;
235
+ /** Follow symbolic links (cycles are detected). Default: `false`. */
236
+ followSymlinks?: boolean | undefined;
237
+ /** Count each hard link separately instead of counting shared data once. Default: `false`. */
238
+ countHardlinks?: boolean | undefined;
239
+ /** Only include files at least this large: bytes or a size string such as `"10MB"`. */
240
+ minSize?: number | string | undefined;
241
+ /** Only include files at most this large. */
242
+ maxSize?: number | string | undefined;
243
+ /** Only include files modified at or after this time: a date, epoch ms, `YYYY-MM-DD`, or an age such as `"30d"`. */
244
+ modifiedAfter?: Date | number | string | undefined;
245
+ /** Only include files modified at or before this time. Date-only values include the whole day. */
246
+ modifiedBefore?: Date | number | string | undefined;
247
+ /** Maximum concurrent filesystem operations. Default: {@link DEFAULT_CONCURRENCY}. */
248
+ concurrency?: number | undefined;
249
+ /** Cancels the operation; the promise then rejects with an `AbortError`. */
250
+ signal?: AbortSignal | undefined;
251
+ }
252
+ /**
253
+ * Lists the directories a scan with these settings would enter, as
254
+ * root-relative `/` paths (the root itself is `""`). Files are not examined.
255
+ */
256
+ export declare function listDirectories(path: string, settings?: ScanSettings): Promise<string[]>;
257
+ //#endregion
258
+ //#region src/core/analyze.d.ts
259
+ /** Default size for "large file" detection: 100 MiB. */
260
+ export declare const DEFAULT_LARGE_FILE_THRESHOLD: number;
261
+ /** Default age for stale-file detection. */
262
+ export declare const DEFAULT_STALE_AGE: string;
263
+ interface AnalyzeOptions extends ScanSettings {
264
+ /** Length of the largest-files and largest-directories lists. Default: 10. `0` disables them. */
265
+ top?: number | undefined;
266
+ /** Report files at least this large. `true` uses 100 MiB. */
267
+ largeFiles?: boolean | number | string | undefined;
268
+ /** Find files with identical contents. */
269
+ duplicates?: boolean | undefined;
270
+ /** Ignore files smaller than this when looking for duplicates. Default: 1 byte. */
271
+ minDuplicateSize?: number | string | undefined;
272
+ /** Report empty files and empty directories. */
273
+ empty?: boolean | undefined;
274
+ /** Report files not modified since this time (or age). `true` uses one year. */
275
+ stale?: boolean | number | string | Date | undefined;
276
+ /** Build a size tree. */
277
+ tree?: boolean | {
278
+ depth?: number | undefined;
279
+ limit?: number | undefined;
280
+ } | undefined;
281
+ /** Size budgets such as `size<=500MB`; results land in `result.budgets`. */
282
+ budgets?: readonly string[] | undefined;
283
+ /** Called periodically with live counters while the analysis runs. */
284
+ onProgress?: ((progress: AnalysisProgress) => void) | undefined;
285
+ /** Milliseconds between progress callbacks. Default: 100. */
286
+ progressInterval?: number | undefined;
287
+ }
288
+ type AnalysisProgress = {
289
+ phase: "scan";
290
+ files: number;
291
+ directories: number;
292
+ bytes: number;
293
+ errors: number;
294
+ } | ({
295
+ phase: "hash";
296
+ files: number;
297
+ bytes: number;
298
+ } & DuplicateProgress);
299
+ /**
300
+ * Analyzes a directory tree in a single pass.
301
+ *
302
+ * Memory stays bounded by default: totals, type and extension statistics,
303
+ * and top-N lists are computed while scanning. Opt-in reports (large, empty,
304
+ * and stale files) hold only matching entries; duplicate detection holds one
305
+ * small record per file that shares its size with another.
306
+ *
307
+ * @example
308
+ * ```ts
309
+ * import { analyze } from 'dir-analysis-tool';
310
+ *
311
+ * const result = await analyze('.', { duplicates: true, top: 5 });
312
+ * console.log(result.summary.bytes, result.duplicates?.wastedBytes);
313
+ * ```
314
+ */
315
+ export declare function analyze(path: string, options?: AnalyzeOptions): Promise<AnalysisResult>;
316
+ //#endregion
317
+ //#region src/core/compare.d.ts
318
+ interface CompareOptions extends ScanSettings {
319
+ /** Also compare the contents of same-sized files (SHA-256). Default: `false`, size only. */
320
+ content?: boolean | undefined;
321
+ /** Length of the directory delta list. Default: 10. */
322
+ top?: number | undefined;
323
+ /** Called periodically with the number of files scanned so far. */
324
+ onProgress?: ((progress: {
325
+ phase: "scan" | "hash";
326
+ files: number;
327
+ total?: number;
328
+ }) => void) | undefined;
329
+ progressInterval?: number | undefined;
330
+ }
331
+ /**
332
+ * Compares two directory trees: what was added, removed, or changed, and
333
+ * which folders grew or shrank the most. Both sides use the same exclusion
334
+ * rules and filters. Memory grows with the number of files in both trees.
335
+ */
336
+ export declare function compare(left: string, right: string, options?: CompareOptions): Promise<ComparisonResult>;
337
+ //#endregion
338
+ //#region src/core/classify.d.ts
339
+ /**
340
+ * Extracts the lowercased extension (with the dot) from a file name.
341
+ * Dotfiles such as `.env` have no extension; `archive.tar.gz` has `.gz`.
342
+ */
343
+ export declare function extensionOf(fileName: string): string;
344
+ /** Classifies a file by its well-known name first, then by extension. */
345
+ export declare function classify(fileName: string, extension?: string): Category;
346
+ //#endregion
347
+ //#region src/core/budgets.d.ts
348
+ /** A feature a metric depends on; requesting the metric turns the feature on. */
349
+ type BudgetFeature = "largeFiles" | "duplicates" | "empty" | "stale";
350
+ interface MetricSpec {
351
+ kind: "size" | "count";
352
+ description: string;
353
+ requires?: BudgetFeature;
354
+ read: (result: AnalysisResult) => number;
355
+ }
356
+ export declare const BUDGET_METRICS: Readonly<Record<BudgetMetric, MetricSpec>>;
357
+ interface Budget {
358
+ rule: string;
359
+ metric: BudgetMetric;
360
+ operator: BudgetOperator;
361
+ limit: number;
362
+ }
363
+ /** Parses a rule such as `size<=500MB`, `duplicates=0`, or `files < 10000`. */
364
+ export declare function parseBudget(rule: string): Budget;
365
+ export declare function evaluateBudgets(budgets: readonly Budget[], result: AnalysisResult): BudgetResult[];
366
+ //#endregion
367
+ //#region src/config/schema.d.ts
368
+ /** Settings accepted in a config file. CLI flags always take precedence. */
369
+ interface DatConfig {
370
+ exclude?: string[];
371
+ defaultExcludes?: boolean;
372
+ gitignore?: boolean;
373
+ maxDepth?: number;
374
+ followSymlinks?: boolean;
375
+ countHardlinks?: boolean;
376
+ minSize?: string | number;
377
+ maxSize?: string | number;
378
+ newerThan?: string;
379
+ olderThan?: string;
380
+ top?: number;
381
+ largeFiles?: boolean | string | number;
382
+ duplicates?: boolean;
383
+ minDuplicateSize?: string | number;
384
+ empty?: boolean;
385
+ stale?: boolean | string;
386
+ extensions?: boolean;
387
+ tree?: boolean;
388
+ treeDepth?: number;
389
+ units?: "iec" | "si";
390
+ budgets?: string[];
391
+ }
392
+ interface ValidationResult {
393
+ config: DatConfig;
394
+ warnings: string[];
395
+ errors: string[];
396
+ }
397
+ /** Validates parsed JSON against {@link CONFIG_FIELDS}, translating legacy keys. */
398
+ export declare function validateConfig(raw: unknown): ValidationResult;
399
+ /** Builds the JSON Schema published as `dir-analysis-tool/schema.json`. */
400
+ export declare function buildJsonSchema(): Record<string, unknown>;
401
+ //#endregion
402
+ //#region src/config/load.d.ts
403
+ /** File names recognized during discovery, in priority order. */
404
+ export declare const CONFIG_FILE_NAMES: readonly string[];
405
+ interface LoadedConfig {
406
+ config: DatConfig;
407
+ /** Absolute path of the file that was loaded, or null when none was found. */
408
+ path: string | null;
409
+ warnings: string[];
410
+ }
411
+ /** Finds the nearest config file at or above `startDir`. */
412
+ export declare function findConfigFile(startDir: string): string | null;
413
+ /**
414
+ * Loads configuration from an explicit file, or discovers one by walking up
415
+ * from `searchFrom`. Invalid files are an error rather than silently ignored.
416
+ */
417
+ export declare function loadConfig(options: {
418
+ file?: string;
419
+ searchFrom: string;
420
+ }): Promise<LoadedConfig>;
421
+ //#endregion
422
+ //#region src/format/time.d.ts
423
+ /** Parses a duration such as `90d`, `2w`, `6mo`, `1y`, `12h`, or `30min` into milliseconds. */
424
+ export declare function parseDuration(input: string): number;
425
+ interface PointInTimeOptions {
426
+ /** Reference time for relative ages. Defaults to now. */
427
+ now?: number;
428
+ /**
429
+ * For date-only input (`YYYY-MM-DD`), resolve to the last millisecond of
430
+ * that local day instead of its first. Makes upper bounds inclusive.
431
+ */
432
+ endOfDay?: boolean;
433
+ }
434
+ /**
435
+ * Resolves a point in time from either an age relative to now (`30d` means
436
+ * "30 days ago") or an absolute date (`2024-01-31`, or any ISO 8601 timestamp).
437
+ * Date-only values are interpreted in local time. Returns epoch milliseconds.
438
+ */
439
+ export declare function parsePointInTime(input: string, options?: PointInTimeOptions): number;
440
+ //#endregion
441
+ //#region src/format/style.d.ts
442
+ /**
443
+ * Minimal ANSI styling with standard color detection.
444
+ *
445
+ * Detection order: `FORCE_COLOR` (0 disables, anything else enables), then
446
+ * `NO_COLOR` (any non-empty value disables), then `TERM=dumb`, then whether
447
+ * the stream is a TTY.
448
+ */
449
+ interface Style {
450
+ readonly enabled: boolean;
451
+ bold(text: string): string;
452
+ dim(text: string): string;
453
+ red(text: string): string;
454
+ green(text: string): string;
455
+ yellow(text: string): string;
456
+ blue(text: string): string;
457
+ magenta(text: string): string;
458
+ cyan(text: string): string;
459
+ }
460
+ export declare function createStyle(enabled: boolean): Style;
461
+ //#endregion
462
+ //#region src/reporters/pretty.d.ts
463
+ interface PrettyOptions {
464
+ style?: Style;
465
+ units?: ByteUnits;
466
+ /** Terminal width used to fit paths. Default: 100. */
467
+ width?: number;
468
+ /** Maximum items printed per list. Default: 10. */
469
+ limit?: number;
470
+ /** Show the file type breakdown. Default: true. */
471
+ types?: boolean;
472
+ /** Show the extension breakdown. Default: false. */
473
+ extensions?: boolean;
474
+ /** Reference time for ages. Default: now. */
475
+ now?: number;
476
+ }
477
+ /** Renders an analysis for a terminal. Colors only when `style` enables them. */
478
+ export declare function renderAnalysis(result: AnalysisResult, options?: PrettyOptions): string;
479
+ /** Renders a directory comparison for a terminal. */
480
+ export declare function renderComparison(result: ComparisonResult, options?: PrettyOptions): string;
481
+ //#endregion
482
+ //#region src/reporters/markdown.d.ts
483
+ interface MarkdownOptions {
484
+ units?: ByteUnits;
485
+ /** Maximum rows per table. Default: 10. */
486
+ limit?: number;
487
+ }
488
+ /** Renders an analysis as GitHub-flavored Markdown, suited to PR comments and job summaries. */
489
+ export declare function renderAnalysisMarkdown(result: AnalysisResult, options?: MarkdownOptions): string;
490
+ /** Renders a directory comparison as GitHub-flavored Markdown. */
491
+ export declare function renderComparisonMarkdown(result: ComparisonResult, options?: MarkdownOptions): string;
492
+ //#endregion
493
+ //#region src/reporters/csv.d.ts
494
+ /**
495
+ * Flattens an analysis into one table. The `section` column tells rows apart:
496
+ * summary, type, extension, largest-directory, largest-file, large-file,
497
+ * duplicate, empty-file, empty-directory, stale-file, and error.
498
+ */
499
+ export declare function renderAnalysisCsv(result: AnalysisResult): string;
500
+ /** Flattens a comparison: one row per added, removed, or changed file. */
501
+ export declare function renderComparisonCsv(result: ComparisonResult): string;
502
+ //#endregion
503
+ //#region src/reporters/html.d.ts
504
+ interface HtmlOptions {
505
+ units?: ByteUnits;
506
+ /** Maximum rows per table. Default: 500. */
507
+ limit?: number;
508
+ }
509
+ /**
510
+ * Renders a fully self-contained HTML report: no external requests, no
511
+ * frameworks, charts drawn with inline SVG. A Content-Security-Policy blocks
512
+ * all network access, so the file is safe to open and share offline.
513
+ */
514
+ export declare function renderAnalysisHtml(result: AnalysisResult, options?: HtmlOptions): string;
515
+ //#endregion
516
+ //#region src/errors.d.ts
517
+ /**
518
+ * An expected, user-facing failure (bad input, missing directory, invalid
519
+ * config). The CLI prints its message without a stack trace.
520
+ */
521
+ export declare class DatError extends Error {
522
+ override readonly name = "DatError";
523
+ /** Optional hint printed after the message. */
524
+ readonly hint: string | undefined;
525
+ constructor(message: string, options?: {
526
+ hint?: string;
527
+ cause?: unknown;
528
+ });
529
+ }
530
+ /** Thrown when an operation is cancelled through its `AbortSignal`. */
531
+ export declare class AbortError extends Error {
532
+ override readonly name = "AbortError";
533
+ constructor(message?: string);
534
+ }
535
+ //#endregion
536
+ //#region src/version.d.ts
537
+ export declare const VERSION: string;
538
+ //#endregion
539
+ export type { AnalysisProgress, AnalyzeOptions, Budget, ByteUnits, CompareOptions, DatConfig, LoadedConfig, PrettyOptions, ScanSettings, Style };