real-size 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 App & Flow
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,332 @@
1
- # Temporary Holding Version
1
+ # real-size
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ How many bytes deleting a folder would actually free, as opposed to what `du`
4
+ shows. A command-line tool and a Node library for macOS, Linux and Windows. It
5
+ ships an [agent skill](#agent-skill) so coding agents reach for it instead of
6
+ `du`.
7
+
8
+ ```console
9
+ $ du -sh node_modules
10
+ 4.4G node_modules
11
+ $ npx real-size node_modules
12
+ node_modules: at least 90.3 MB private, 4.8 GB allocated, 168433 files
13
+ ```
14
+
15
+ ## Why `du` misleads
16
+
17
+ `du` adds up the blocks of every file under a path. That is the space the files
18
+ occupy, but not the space their deletion returns, because modern filesystems
19
+ share blocks between files:
20
+
21
+ - **Clones.** On APFS, `cp -c`, Finder copies and tools such as pnpm and
22
+ Xcode create copy-on-write clones. A clone shares every block with its
23
+ original until one of them changes. Deleting the clone frees nothing.
24
+ - **Hard links.** A package store (pnpm, Nix, Bazel caches) links one file
25
+ into many folders. Deleting one folder removes a link, not the data, while
26
+ another link exists outside it.
27
+ - **Reflinks and block clones.** Btrfs and XFS (`cp --reflink`) and ReFS or
28
+ Dev Drive on Windows share extents between files that each have a single
29
+ link, which a link count does not show.
30
+
31
+ `real-size` walks the tree and counts only the bytes no file outside it
32
+ shares.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ npm install --global real-size
38
+ ```
39
+
40
+ Or run it without installing: `npx real-size <path>`.
41
+
42
+ The package ships prebuilt binaries and has no install scripts and no runtime
43
+ dependencies.
44
+
45
+ On macOS and Linux the `real-size` command is a `#!/bin/sh` script that finds
46
+ the binary for the machine and `exec`s it, so no Node process is involved and
47
+ it adds a few milliseconds to the binary's start-up. It works when installed
48
+ with npm, pnpm, Yarn classic and Yarn Berry's `node-modules` linker, locally
49
+ or globally, through `npx`, `pnpm dlx` and `yarn dlx`, and with BusyBox `sh`
50
+ on Alpine. `yarn real-size` under Yarn Berry, including Plug'n'Play, runs the
51
+ command through Node; the same file is also a Node script that starts the
52
+ binary.
53
+
54
+ On Windows the command is **`real-size-windows`**, with the same arguments:
55
+
56
+ ```bat
57
+ npm install --global real-size
58
+ real-size-windows node_modules
59
+ npx --package real-size real-size-windows node_modules
60
+ ```
61
+
62
+ npm and pnpm generate Windows launchers from a command's `#!` line, so the
63
+ `real-size` command's `#!/bin/sh` needs an `sh` on Windows (Git Bash has one;
64
+ cmd.exe and PowerShell do not). `real-size-windows` is the x64 binary itself,
65
+ which the launchers start directly in cmd.exe, Windows PowerShell and
66
+ PowerShell, without Node. On Windows on Arm it starts the arm64 binary beside
67
+ it with the same arguments and returns its exit status. `real-size --version`
68
+ prints the version and the binary's platform, for example `0.1.0
69
+ (win32-arm64)`.
70
+
71
+ ## Command line
72
+
73
+ ```text
74
+ real-size [--json] <path>...
75
+ ```
76
+
77
+ Each path is measured on its own. Plain output prints one line per path, and a
78
+ total when several paths are given:
79
+
80
+ ```console
81
+ $ real-size build packages
82
+ build: at least 24.6 kB private, 167.9 kB allocated, 3 files
83
+ packages: at least 94.7 MB private, 19.8 GB allocated, 68181 files
84
+ total: at least 94.7 MB private, 19.8 GB allocated, 68184 files
85
+ ```
86
+
87
+ Sizes use decimal units (1 MB is 1,000,000 bytes). "at least" marks a result
88
+ that is not exact.
89
+
90
+ `--json` prints exactly one JSON document on stdout:
91
+
92
+ ```json
93
+ {
94
+ "paths": [
95
+ {
96
+ "path": "node_modules",
97
+ "allocated": 4767227904,
98
+ "private": 90292224,
99
+ "files": 168433,
100
+ "exact": false
101
+ }
102
+ ],
103
+ "total": {
104
+ "allocated": 4767227904,
105
+ "private": 90292224,
106
+ "files": 168433,
107
+ "exact": false
108
+ }
109
+ }
110
+ ```
111
+
112
+ | Exit status | Meaning |
113
+ | ----------- | ------------------------------------------------------------------------------------- |
114
+ | 0 | Every path was measured. |
115
+ | 1 | A usage error, or a path could not be read. The reason is on stderr, stdout is empty. |
116
+ | 2 | The filesystem cannot report what deleting a path would free. Stdout is empty. |
117
+
118
+ `--version` prints the version and `--help` prints usage.
119
+
120
+ ## Library
121
+
122
+ ```js
123
+ import { realSize, binaryPath, RealSizeError } from "real-size";
124
+
125
+ const { paths, total } = await realSize(["node_modules", "ios/Pods"], {
126
+ timeoutMs: 30_000,
127
+ });
128
+ console.log(`${total.private} bytes reclaimable`);
129
+ ```
130
+
131
+ `realSize(paths, { signal, timeoutMs })` runs the binary in a child process
132
+ and resolves with the same document `--json` prints. The walk runs in its own
133
+ process so that a slow or hung filesystem cannot block the caller: at
134
+ `timeoutMs`, or when `signal` aborts, the child is killed with `SIGKILL` and
135
+ the promise rejects at once. It rejects with a `RealSizeError` whose `code` is:
136
+
137
+ - `unsupported`: no prebuilt binary for this platform, or exit status 2.
138
+ - `timeout`: `timeoutMs` ran out.
139
+ - `failed`: exit status 1 or the binary could not start. `message` holds the
140
+ binary's error.
141
+
142
+ An aborted `signal` rejects with the signal's reason.
143
+
144
+ `binaryPath()` returns the absolute path of the prebuilt binary for this
145
+ platform, or `null` when the package has none, so you can spawn it yourself,
146
+ for example at a lower CPU or I/O priority.
147
+
148
+ TypeScript types are included. Node `^20.19.4 || >=22.12.0`.
149
+
150
+ ## Output fields
151
+
152
+ - `allocated`: the bytes the tree's regular files occupy on disk. A file with
153
+ several hard links in the tree counts once.
154
+ - `private`: the bytes deleting the tree would free.
155
+ - `files`: the regular files counted, each hard-linked file once.
156
+ - `exact`: `true` when `private` is the exact answer, `false` when it is a
157
+ lower bound.
158
+
159
+ Directories, symbolic links and metadata are not counted. Symbolic links are
160
+ never followed, and neither are Windows junctions.
161
+
162
+ A file with more links than the tree holds is shared with a path outside the
163
+ tree and contributes nothing to `private`. That rule is exact on every
164
+ platform.
165
+
166
+ `exact` is `false` when some counted file shares blocks with another file
167
+ (a clone, reflink or block clone) and the other file could be inside the tree
168
+ too. Each copy then reports only its unshared bytes, so deleting both may free
169
+ more than the sum. The answer is a lower bound and the true figure lies
170
+ between `private` and `allocated`.
171
+
172
+ ## Platforms
173
+
174
+ | Platform | Prebuilt | Hard links | Clones and shared extents | `exact` |
175
+ | --------------------------- | ---------- | ---------- | --------------------------------- | --------------------------------- |
176
+ | macOS, APFS | arm64, x64 | Exact | APFS private size per file | `false` when a file shares blocks |
177
+ | macOS, other volumes | | | | Exit status 2 |
178
+ | Linux, ext2/3/4, tmpfs | x64, arm64 | Exact | Not possible on these filesystems | Always `true` |
179
+ | Linux, btrfs, XFS | x64, arm64 | Exact | `FIEMAP` shared extent flag | `false` when an extent is shared |
180
+ | Linux, other filesystems | | | | Exit status 2 |
181
+ | Windows, NTFS, FAT, exFAT | x64, arm64 | Exact | Not possible on these volumes | Always `true` |
182
+ | Windows, ReFS and Dev Drive | x64, arm64 | Exact | Per-extent reference counts | `false` when an extent is shared |
183
+ | Windows, network shares | | | | Exit status 2 |
184
+
185
+ The Linux binaries are statically linked, so they run on glibc and musl
186
+ distributions alike.
187
+
188
+ ### macOS
189
+
190
+ The walk uses `getattrlistbulk` and reads each file's
191
+ `ATTR_CMNEXT_PRIVATESIZE`, which APFS reports as the bytes the file does not
192
+ share with a clone. On a volume that does not report it (HFS+, FAT, SMB) the
193
+ exit status is 2. The walk descends into volumes mounted inside the tree.
194
+
195
+ APFS also reports a private size below the allocation for transparently
196
+ compressed files (decmpfs, for example files installed by some system tools),
197
+ so a tree that holds them reports `exact: false` and a lower bound even
198
+ without clones.
199
+
200
+ ### Linux
201
+
202
+ The walk uses `fstatat`. `allocated` is `st_blocks` times 512. The filesystem
203
+ is identified by its `statfs` `f_type`, again for each volume mounted inside
204
+ the tree:
205
+
206
+ - ext2, ext3, ext4 and tmpfs share blocks only through hard links, so the
207
+ result is exact.
208
+ - Btrfs and XFS can share extents between files. Each file is opened
209
+ read-only and mapped with the `FS_IOC_FIEMAP` ioctl; extents flagged
210
+ `FIEMAP_EXTENT_SHARED` do not count as private, and any shared extent sets
211
+ `exact: false`. A file on these filesystems that cannot be opened, or whose
212
+ mapping fails, counts as entirely shared: it adds to `allocated`, nothing to
213
+ `private`, and sets `exact: false`.
214
+ - Any other filesystem (overlayfs, NFS, ZFS, bcachefs, FUSE mounts, sysfs
215
+ and so on) exits with status 2, because it may share blocks in ways the
216
+ walk cannot see. Container users meet this first: a Docker container's root
217
+ is overlayfs, while a bind-mounted host folder on ext4 works.
218
+
219
+ ### Windows
220
+
221
+ The walk uses `FindFirstFileExW` with `\\?\` long paths, so paths longer than
222
+ `MAX_PATH` and any Unicode name work. Each file is opened for its attributes
223
+ only. `allocated` is the allocation size from `FILE_STANDARD_INFO`, or for a
224
+ compressed or sparse NTFS file its compressed size from
225
+ `FILE_COMPRESSION_INFO`, whichever is smaller. Hard links use
226
+ `nNumberOfLinks` with the volume serial number and the 128-bit `FILE_ID_INFO`
227
+ file id, which is unique on ReFS where the 64-bit index is not.
228
+
229
+ Reparse points whose tag is a name surrogate (symbolic links, junctions,
230
+ volume mount points) are not followed, so the walk never leaves the volume.
231
+
232
+ On a volume that supports block cloning (`FILE_SUPPORTS_BLOCK_REFCOUNTING`:
233
+ ReFS, and Dev Drive), each file's extents are read with
234
+ [`FSCTL_GET_RETRIEVAL_POINTERS_AND_REFCOUNT`](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/80ac720b-374c-40b7-847c-e57874260b64).
235
+ An extent whose
236
+ [reference count](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/dd2be29e-4f60-4bb4-b68a-20f2c34ac0d2)
237
+ is above 1 is shared and does not count as private, and sets
238
+ `exact: false`. ReFS supports this control code from Windows 10 1703 and
239
+ Windows Server 2019
240
+ ([product notes](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fsa/4e3695bd-7574-4f24-a223-b4679c065b63)).
241
+ Microsoft documents it in the protocol specifications only, and the count it
242
+ reports is the count of the cluster each extent starts at. A file whose
243
+ extents cannot be read counts as entirely shared, as on Linux.
244
+
245
+ Cloud placeholders (OneDrive and other Cloud Files providers) are not read:
246
+ the walk opens each file for its attributes only, which Microsoft's
247
+ placeholder guidance treats as an attribute-only open that should not recall
248
+ data, though no page guarantees it. A file marked
249
+ `FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS`, `RECALL_ON_OPEN` or `OFFLINE`
250
+ contributes its local allocation, which for a dehydrated placeholder is close
251
+ to zero. Data Deduplication on Windows Server stores optimized files in a
252
+ chunk store that only a garbage collection job reclaims; those files report
253
+ their own allocation, so `private` overstates what deleting them frees at
254
+ once. Network shares (UNC paths and mapped drives) exit with status 2.
255
+
256
+ ## Speed
257
+
258
+ Warm-cache wall time of the bare binary against `du -sk` (macOS, Linux) or
259
+ `robocopy /L` (Windows), 10 runs each. Method, cold-cache runs and every
260
+ runner are in [docs/benchmarks.md](docs/benchmarks.md).
261
+
262
+ | Machine | Filesystem | Tree | real-size | Baseline | Ratio |
263
+ | ------------------------------ | ---------- | ------------------------------------- | --------- | -------- | ----- |
264
+ | Apple M4 Pro, 14 cores | APFS | pnpm `node_modules`, 168,433 files | 1.01 s | 876.4 ms | 1.15x |
265
+ | Apple M4 Pro | APFS | 30,000 files hard-linked from a store | 184.4 ms | 123.8 ms | 1.49x |
266
+ | Apple M4 Pro | APFS | 117,186 small files, 7 levels | 754.7 ms | 551.9 ms | 1.37x |
267
+ | GitHub ubuntu-latest, 4 cores | ext4 | 30,000 hard-linked files | 91.4 ms | 123.8 ms | 0.74x |
268
+ | GitHub ubuntu-latest | ext4 | 117,186 small files | 352.0 ms | 594.5 ms | 0.59x |
269
+ | GitHub ubuntu-latest | btrfs | 117,186 small files | 1.47 s | 619.8 ms | 2.37x |
270
+ | GitHub ubuntu-latest | XFS | 117,186 small files | 747.1 ms | 521.4 ms | 1.43x |
271
+ | GitHub windows-latest, 4 cores | NTFS | 30,000 hard-linked files | 337.8 ms | 135.1 ms | 2.50x |
272
+ | GitHub windows-latest | NTFS | 117,186 small files | 1.66 s | 690.4 ms | 2.40x |
273
+
274
+ The extra time is the per-file question `du` does not ask: the private size
275
+ on APFS, the extent map on btrfs and XFS, and the link count on Windows.
276
+
277
+ ## Limitations
278
+
279
+ - Each path is measured on its own and the total is their sum. Two paths that
280
+ hard-link or clone each other's files each report those bytes as shared, so
281
+ the total can be lower than what deleting both would free.
282
+ - The macOS and Linux walks stop at 256 nested directories and the Windows
283
+ walk at 256 as well; deeper trees exit with status 1.
284
+ - A path that cannot be read, such as a directory without read permission,
285
+ exits with status 1 rather than reporting a partial size.
286
+ - Files changed during the walk may be counted in either state.
287
+ - The plain output's sizes are rounded; use `--json` for bytes.
288
+ - On Linux, filesystems other than ext2/3/4, tmpfs, btrfs and XFS exit with
289
+ status 2 even where an answer could be given, for example ZFS without
290
+ block cloning.
291
+ - On Windows the command is `real-size-windows`, not `real-size`, in cmd.exe
292
+ and PowerShell (see [Install](#install)). Yarn classic's Windows launchers
293
+ are not guaranteed.
294
+ - On macOS and Linux, `real-size-windows` is installed too and points at a
295
+ Windows binary that does not run there.
296
+ - On Windows, files compressed by the Windows Overlay Filter (`compact
297
+ /exe`) report their main stream's allocation.
298
+
299
+ ## Agent skill
300
+
301
+ The package includes a skill at [`skill/SKILL.md`](skill/SKILL.md) that tells
302
+ coding agents to use `real-size` rather than `du` when the question is how
303
+ much space deleting something would free. Install it with:
304
+
305
+ ```bash
306
+ npx skills add appandflow/real-size
307
+ ```
308
+
309
+ Or copy the `skill` folder into your agent's skills directory under the name
310
+ `real-size`, for example `~/.claude/skills/real-size/SKILL.md` for Claude
311
+ Code. The installed npm package also contains it at
312
+ `node_modules/real-size/skill/SKILL.md`.
313
+
314
+ ## Development
315
+
316
+ Building needs a C11 compiler: `cc` on macOS and Linux (a static glibc for the
317
+ Linux build), MSVC `cl` on Windows.
318
+
319
+ ```sh
320
+ npm ci --ignore-scripts
321
+ npm run build
322
+ npm run typecheck
323
+ npm run format:check
324
+ npm test
325
+ ```
326
+
327
+ CI builds and tests every platform, then assembles the release tarball with
328
+ `npm run pack:release`. See [RELEASING.md](RELEASING.md).
329
+
330
+ ## License
331
+
332
+ MIT
package/bin/real-size ADDED
@@ -0,0 +1,45 @@
1
+ #!/bin/sh
2
+ true /*
3
+ self=$0
4
+ while [ -h "$self" ]; do
5
+ link=$(readlink "$self")
6
+ case $link in
7
+ /*) self=$link ;;
8
+ *) self=${self%/*}/$link ;;
9
+ esac
10
+ done
11
+ dir=${self%/*}
12
+ [ "$dir" = "$self" ] && dir=.
13
+ case $(uname -sm) in
14
+ "Darwin arm64") target=darwin-arm64 ;;
15
+ "Darwin x86_64") target=darwin-x64 ;;
16
+ "Linux x86_64" | "Linux amd64") target=linux-x64 ;;
17
+ "Linux aarch64" | "Linux arm64") target=linux-arm64 ;;
18
+ *) target= ;;
19
+ esac
20
+ binary=$dir/../prebuilds/$target/real-size
21
+ if [ -z "$target" ] || [ ! -x "$binary" ]; then
22
+ echo "real-size: no prebuilt binary for $(uname -sm)" >&2
23
+ exit 2
24
+ fi
25
+ exec "$binary" "$@"
26
+ : <<'//'
27
+ */
28
+ const { spawnSync } = process.getBuiltinModule("node:child_process");
29
+ const { existsSync, realpathSync } = process.getBuiltinModule("node:fs");
30
+ const { dirname, join } = process.getBuiltinModule("node:path");
31
+ const target = `${process.platform}-${process.arch}`;
32
+ const name = process.platform === "win32" ? "real-size.exe" : "real-size";
33
+ const binary = join(dirname(realpathSync(process.argv[1])), "..", "prebuilds", target, name);
34
+ if (!existsSync(binary)) {
35
+ console.error(`real-size: no prebuilt binary for ${target}`);
36
+ process.exit(2);
37
+ }
38
+ const result = spawnSync(binary, process.argv.slice(2), { stdio: "inherit" });
39
+ if (result.error) {
40
+ console.error(`real-size: ${result.error.message}`);
41
+ process.exit(2);
42
+ }
43
+ if (result.signal) process.kill(process.pid, result.signal);
44
+ process.exit(result.status ?? 1);
45
+ //
package/index.d.mts ADDED
@@ -0,0 +1,56 @@
1
+ export interface TreeSize {
2
+ /** Bytes the regular files occupy on disk, each file counted once. */
3
+ allocated: number;
4
+ /** Bytes deleting the tree would free. A lower bound when `exact` is false. */
5
+ private: number;
6
+ /** Regular files, each counted once however many links it has in the tree. */
7
+ files: number;
8
+ /** False when `private` is a lower bound because some counted file shares blocks with another file. */
9
+ exact: boolean;
10
+ }
11
+
12
+ export interface PathSize extends TreeSize {
13
+ /** The path as it was passed. */
14
+ path: string;
15
+ }
16
+
17
+ export interface RealSizeResult {
18
+ paths: PathSize[];
19
+ /** The sum of `paths`, each measured on its own. */
20
+ total: TreeSize;
21
+ }
22
+
23
+ export interface RealSizeOptions {
24
+ /** Aborting kills the walk and rejects with the signal's reason. */
25
+ signal?: AbortSignal;
26
+ /** Kills the walk and rejects with a `timeout` error after this many milliseconds. */
27
+ timeoutMs?: number;
28
+ }
29
+
30
+ export type RealSizeErrorCode = "unsupported" | "timeout" | "failed";
31
+
32
+ export declare class RealSizeError extends Error {
33
+ constructor(
34
+ code: RealSizeErrorCode,
35
+ message: string,
36
+ options?: { cause?: unknown; exitCode?: number | null },
37
+ );
38
+ readonly name: "RealSizeError";
39
+ /**
40
+ * `unsupported`: no prebuilt binary for this platform, or the filesystem cannot report the bytes deleting the path
41
+ * would free (exit status 2). `timeout`: `timeoutMs` ran out. `failed`: a usage or I/O error (exit status 1), or the
42
+ * binary could not run.
43
+ */
44
+ readonly code: RealSizeErrorCode;
45
+ /** The binary's exit status, null when it did not exit on its own. */
46
+ readonly exitCode: number | null;
47
+ }
48
+
49
+ /** Measures each directory in its own walk, run in a child process. */
50
+ export declare function realSize(
51
+ paths: string | readonly string[],
52
+ options?: RealSizeOptions,
53
+ ): Promise<RealSizeResult>;
54
+
55
+ /** The absolute path of the prebuilt binary for this platform, or null when the package has none. */
56
+ export declare function binaryPath(): string | null;
package/index.mjs ADDED
@@ -0,0 +1,119 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ export class RealSizeError extends Error {
6
+ /**
7
+ * @param {"unsupported" | "timeout" | "failed"} code
8
+ * @param {string} message
9
+ * @param {{ cause?: unknown; exitCode?: number | null }} [options]
10
+ */
11
+ constructor(code, message, options = {}) {
12
+ super(message, { cause: options.cause });
13
+ this.name = "RealSizeError";
14
+ this.code = code;
15
+ this.exitCode = options.exitCode ?? null;
16
+ }
17
+ }
18
+
19
+ /** @returns {string | null} */
20
+ export function binaryPath() {
21
+ const name = process.platform === "win32" ? "real-size.exe" : "real-size";
22
+ const file = fileURLToPath(
23
+ new URL(
24
+ `./prebuilds/${process.platform}-${process.arch}/${name}`,
25
+ import.meta.url,
26
+ ),
27
+ );
28
+ return existsSync(file) ? file : null;
29
+ }
30
+
31
+ /**
32
+ * @param {string | readonly string[]} paths
33
+ * @param {{ signal?: AbortSignal; timeoutMs?: number }} [options]
34
+ * @returns {Promise<import("./index.d.mts").RealSizeResult>}
35
+ */
36
+ export function realSize(paths, options = {}) {
37
+ const { signal, timeoutMs } = options;
38
+ const list = typeof paths === "string" ? [paths] : [...paths];
39
+ return new Promise((resolve, reject) => {
40
+ if (signal?.aborted) return reject(signal.reason);
41
+ if (list.length === 0)
42
+ return reject(new TypeError("realSize needs at least one path"));
43
+ const binary = binaryPath();
44
+ if (!binary)
45
+ return reject(
46
+ new RealSizeError(
47
+ "unsupported",
48
+ `real-size has no prebuilt binary for ${process.platform}-${process.arch}`,
49
+ ),
50
+ );
51
+ const child = spawn(binary, ["--json", "--", ...list], {
52
+ stdio: ["ignore", "pipe", "pipe"],
53
+ windowsHide: true,
54
+ });
55
+ let stdout = "";
56
+ let stderr = "";
57
+ child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
58
+ child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
59
+ let settled = false;
60
+ /** @type {NodeJS.Timeout | undefined} */
61
+ let timer;
62
+ const onAbort = () => {
63
+ child.kill("SIGKILL");
64
+ finish(() => reject(signal?.reason));
65
+ };
66
+ /** @param {() => void} settle */
67
+ const finish = (settle) => {
68
+ if (settled) return;
69
+ settled = true;
70
+ clearTimeout(timer);
71
+ signal?.removeEventListener("abort", onAbort);
72
+ settle();
73
+ };
74
+ if (timeoutMs !== undefined)
75
+ timer = setTimeout(() => {
76
+ child.kill("SIGKILL");
77
+ finish(() =>
78
+ reject(
79
+ new RealSizeError(
80
+ "timeout",
81
+ `real-size did not finish within ${timeoutMs} ms`,
82
+ ),
83
+ ),
84
+ );
85
+ }, timeoutMs);
86
+ signal?.addEventListener("abort", onAbort, { once: true });
87
+ child.on("error", (error) =>
88
+ finish(() =>
89
+ reject(new RealSizeError("failed", error.message, { cause: error })),
90
+ ),
91
+ );
92
+ child.on("close", (exitCode, exitSignal) =>
93
+ finish(() => {
94
+ const message = stderr.trim().replace(/^real-size: /, "");
95
+ if (exitCode === 0) {
96
+ try {
97
+ resolve(JSON.parse(stdout));
98
+ } catch (error) {
99
+ reject(
100
+ new RealSizeError("failed", "real-size printed invalid JSON", {
101
+ cause: error,
102
+ exitCode,
103
+ }),
104
+ );
105
+ }
106
+ } else if (exitCode === 2)
107
+ reject(new RealSizeError("unsupported", message, { exitCode }));
108
+ else
109
+ reject(
110
+ new RealSizeError(
111
+ "failed",
112
+ message || `real-size exited with ${exitCode ?? exitSignal}`,
113
+ { exitCode },
114
+ ),
115
+ );
116
+ }),
117
+ );
118
+ });
119
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "real-size",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The bytes deleting a folder would actually free, on APFS clones, hard links and reflinks",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": "^20.19.4 || >=22.12.0"
8
+ },
9
+ "os": [
10
+ "darwin",
11
+ "linux",
12
+ "win32"
13
+ ],
14
+ "bin": {
15
+ "real-size": "bin/real-size",
16
+ "real-size-windows": "prebuilds/win32-x64/real-size.exe"
17
+ },
18
+ "exports": {
19
+ ".": {
20
+ "types": "./index.d.mts",
21
+ "import": "./index.mjs"
22
+ }
23
+ },
24
+ "files": [
25
+ "bin",
26
+ "index.mjs",
27
+ "index.d.mts",
28
+ "prebuilds",
29
+ "skill",
30
+ "LICENSE",
31
+ "README.md"
32
+ ],
33
+ "keywords": [
34
+ "disk-usage",
35
+ "du",
36
+ "apfs",
37
+ "clone",
38
+ "hard-link",
39
+ "reflink",
40
+ "btrfs",
41
+ "xfs",
42
+ "refs"
43
+ ],
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/appandflow/real-size.git"
47
+ },
48
+ "license": "MIT",
49
+ "scripts": {
50
+ "build": "node scripts/build.mjs",
51
+ "test": "node --test --test-concurrency=1 test/cli.test.mjs test/api.test.mjs test/launcher.test.mjs test/darwin.test.mjs test/linux.test.mjs test/windows.test.mjs test/package.test.mjs",
52
+ "test:package": "node scripts/package-smoke.mjs",
53
+ "pack:release": "node scripts/pack-release.mjs",
54
+ "typecheck": "tsc",
55
+ "format": "prettier --write .",
56
+ "format:check": "prettier --check ."
57
+ },
58
+ "devDependencies": {
59
+ "@types/node": "^22.0.0",
60
+ "prettier": "^3.0.0",
61
+ "typescript": "^5.0.0"
62
+ }
63
+ }
Binary file
Binary file
Binary file
Binary file
package/skill/SKILL.md ADDED
@@ -0,0 +1,33 @@
1
+ ---
2
+ name: real-size
3
+ description: Use real-size to measure how much disk space a folder really uses or how much deleting it would free. Use it when deciding what to delete to free space, when sizing node_modules, build outputs, caches, worktrees or clones on macOS (APFS clones), Linux (hard links, btrfs and XFS reflinks) or Windows (NTFS hard links, ReFS block clones), and any time `du` or `du -sh` is about to be used to answer "how much will I get back".
4
+ ---
5
+
6
+ # real-size
7
+
8
+ `du` adds up every file's blocks. On a copy-on-write or hard-linked tree that is the wrong answer to "what would deleting this free": an APFS clone, a reflink copy, a ReFS block clone or a pnpm store hard link shares its blocks with a file elsewhere, and deleting it frees nothing. Use `real-size` for that question. `du` stays the right tool for apparent size or for how much a tree occupies regardless of sharing.
9
+
10
+ ```bash
11
+ npx real-size <path>... # one line per path, plus a total
12
+ npx real-size --json <path>... # one JSON document: { paths: [...], total }
13
+ ```
14
+
15
+ On Windows in cmd.exe or PowerShell the command is `real-size-windows` (`npx --package real-size real-size-windows <path>`).
16
+
17
+ Fields:
18
+
19
+ - `allocated`: bytes the tree's files occupy on disk, each file counted once.
20
+ - `private`: bytes deleting the tree would free. Report this one as reclaimable.
21
+ - `files`: regular files counted.
22
+ - `exact`: `false` means `private` is a lower bound: some file shares blocks with another file, possibly one inside the same tree, so deleting the whole tree may free more. Say "at least".
23
+
24
+ Exit status 2 means the filesystem cannot report this (for example NFS, overlayfs, a network share, or a non-APFS volume on macOS). Then say real-size cannot tell on this filesystem, fall back to `du -sh`, and present that number as an upper bound. Exit status 1 is a usage or I/O error, with the reason on stderr.
25
+
26
+ Example, a pnpm worktree's `node_modules` on macOS:
27
+
28
+ ```
29
+ $ du -sh node_modules 4.4G node_modules
30
+ $ npx real-size node_modules node_modules: at least 90.3 MB private, 4.8 GB allocated, 168433 files
31
+ ```
32
+
33
+ Deleting it gets back about 90 MB, not 4.4 GB. Symbolic links and Windows junctions are never followed. On Windows, NTFS hard links are exact; ReFS and Dev Drive block clones are read from the volume's per-extent reference counts and give `exact: false`, and network shares exit 2.