@kongyo2/ts-comment-scanner 1.4.0 → 1.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/src/files.ts CHANGED
@@ -12,7 +12,10 @@ const DEFAULT_IGNORE_DIRS = ["node_modules", ".git"];
12
12
  export interface CollectOptions {
13
13
  /** File extensions to include (with or without a leading dot, case-insensitive). */
14
14
  extensions?: string[];
15
- /** Directory names that are never traversed. Default: node_modules, .git */
15
+ /**
16
+ * Directory names that are never traversed, input directories included
17
+ * (case-insensitively on Windows). Default: node_modules, .git
18
+ */
16
19
  ignoreDirs?: string[];
17
20
  /**
18
21
  * Glob patterns for files and directories to skip (picomatch syntax).
@@ -26,19 +29,24 @@ type IgnoreMatcher = (path: string, root: string) => boolean;
26
29
 
27
30
  export async function collectFiles(inputs: string[], options: CollectOptions = {}): Promise<string[]> {
28
31
  const extensions = normalizeExtensions(options.extensions ?? DEFAULT_EXTENSIONS);
29
- const ignoreDirs = new Set(options.ignoreDirs ?? DEFAULT_IGNORE_DIRS);
32
+ const ignoreDirs = new Set((options.ignoreDirs ?? DEFAULT_IGNORE_DIRS).map(foldName));
30
33
  const isIgnored = buildIgnoreMatcher(options.ignore ?? []);
31
- // Keyed by the resolved path so different spellings of one file (relative vs
32
- // absolute, `.` segments, case on Windows) collapse into a single entry; the
33
- // first spelling seen is the one reported.
34
+ // Keyed by the real path so different spellings of one file (relative vs
35
+ // absolute, `.` segments, case on Windows, symlink aliases) collapse into a
36
+ // single entry; the first spelling seen is the one reported.
34
37
  const found = new Map<string, string>();
35
- const remember = (path: string): void => {
36
- const key = canonicalKey(path);
38
+ const remember = (path: string, realPath: string): void => {
39
+ const key = canonicalKey(realPath);
37
40
  if (!found.has(key)) found.set(key, path);
38
41
  };
39
42
 
43
+ // Walks remember their discoveries mid-traversal; explicitly listed files
44
+ // are resolved concurrently but remembered afterwards in input order, so
45
+ // which spelling of an aliased file gets reported never depends on
46
+ // filesystem timing.
47
+ const explicitFiles = new Array<{ path: string; real: string } | undefined>(inputs.length);
40
48
  await Promise.all(
41
- inputs.map(async (rawInput) => {
49
+ inputs.map(async (rawInput, index) => {
42
50
  if (rawInput === "") {
43
51
  // normalize("") would resolve to "." and silently widen the scan.
44
52
  throw new Error("empty path is not a valid input");
@@ -46,16 +54,20 @@ export async function collectFiles(inputs: string[], options: CollectOptions = {
46
54
  const input = normalize(rawInput);
47
55
  const info = await statInput(input);
48
56
  if (info.isDirectory()) {
49
- // Directory inputs are themselves subject to the ignore patterns;
50
- // only explicitly listed files bypass them.
51
- if (!isIgnored(input, input)) {
57
+ // Directory inputs are themselves subject to the ignored directory
58
+ // names and the ignore patterns; only explicitly listed files bypass
59
+ // them.
60
+ if (!ignoreDirs.has(foldName(basename(input))) && !isIgnored(input, input)) {
52
61
  await walk(input, { extensions, ignoreDirs, isIgnored, root: input, visited: new Set() }, remember);
53
62
  }
54
63
  } else {
55
- remember(input);
64
+ explicitFiles[index] = { path: input, real: await realpathInput(input) };
56
65
  }
57
66
  }),
58
67
  );
68
+ for (const file of explicitFiles) {
69
+ if (file !== undefined) remember(file.path, file.real);
70
+ }
59
71
 
60
72
  return [...found.values()].sort();
61
73
  }
@@ -67,6 +79,11 @@ function canonicalKey(path: string): string {
67
79
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
68
80
  }
69
81
 
82
+ /** Folds directory names the way the platform compares them, matching canonicalKey. */
83
+ function foldName(name: string): string {
84
+ return process.platform === "win32" ? name.toLowerCase() : name;
85
+ }
86
+
70
87
  async function statInput(input: string): Promise<Stats> {
71
88
  try {
72
89
  return await stat(input);
@@ -78,6 +95,29 @@ async function statInput(input: string): Promise<Stats> {
78
95
  }
79
96
  }
80
97
 
98
+ /** Real path of an explicit input, with the same friendly error statInput gives. */
99
+ async function realpathInput(input: string): Promise<string> {
100
+ try {
101
+ return await realpath(input);
102
+ } catch (error) {
103
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
104
+ throw new Error(`path not found: ${input}`, { cause: error });
105
+ }
106
+ throw error;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * True for the errors a walk may step over: entries that vanished mid-walk
112
+ * (ENOENT, ENOTDIR after a directory was replaced) and symlinks that do not
113
+ * resolve (broken targets, ELOOP cycles). Anything else — permissions, I/O
114
+ * failures — propagates, so a partial scan cannot masquerade as a clean one.
115
+ */
116
+ function isSkippableWalkError(error: unknown): boolean {
117
+ const code = (error as NodeJS.ErrnoException).code;
118
+ return code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP";
119
+ }
120
+
81
121
  interface WalkContext {
82
122
  extensions: string[];
83
123
  ignoreDirs: Set<string>;
@@ -88,12 +128,17 @@ interface WalkContext {
88
128
  visited: Set<string>;
89
129
  }
90
130
 
91
- async function walk(dir: string, context: WalkContext, remember: (path: string) => void): Promise<void> {
131
+ async function walk(
132
+ dir: string,
133
+ context: WalkContext,
134
+ remember: (path: string, realPath: string) => void,
135
+ ): Promise<void> {
92
136
  let real: string;
93
137
  try {
94
138
  real = await realpath(dir);
95
- } catch {
96
- return; // the directory vanished mid-walk
139
+ } catch (error) {
140
+ if (isSkippableWalkError(error)) return; // the directory vanished mid-walk
141
+ throw error;
97
142
  }
98
143
  if (context.visited.has(real)) return;
99
144
  context.visited.add(real);
@@ -112,16 +157,26 @@ async function walk(dir: string, context: WalkContext, remember: (path: string)
112
157
  const info = await stat(full);
113
158
  isDirectory = info.isDirectory();
114
159
  isFile = info.isFile();
115
- } catch {
116
- return; // broken symlink
160
+ } catch (error) {
161
+ if (isSkippableWalkError(error)) return; // broken symlink
162
+ throw error;
117
163
  }
118
164
  }
119
165
  if (isDirectory) {
120
- if (!context.ignoreDirs.has(entry.name) && !context.isIgnored(full, context.root)) {
166
+ if (!context.ignoreDirs.has(foldName(entry.name)) && !context.isIgnored(full, context.root)) {
121
167
  await walk(full, context, remember);
122
168
  }
123
169
  } else if (isFile && hasExtension(entry.name, context.extensions) && !context.isIgnored(full, context.root)) {
124
- remember(full);
170
+ // Remembered under its real path, so several symlinks to one target
171
+ // (or a link plus the target itself) count — and get rewritten — once.
172
+ let realFile: string;
173
+ try {
174
+ realFile = await realpath(full);
175
+ } catch (error) {
176
+ if (isSkippableWalkError(error)) return; // the file vanished mid-walk
177
+ throw error;
178
+ }
179
+ remember(full, realFile);
125
180
  }
126
181
  }),
127
182
  );
@@ -231,16 +286,27 @@ function decodeUtf16Be(body: Buffer): string {
231
286
  return Buffer.from(even).swap16().toString("utf16le");
232
287
  }
233
288
 
234
- /** Re-encodes decoded text in the encoding (and BOM) it was read with. */
289
+ /**
290
+ * Re-encodes decoded text in the encoding (and BOM) it was read with. Note
291
+ * that `bom: false` UTF-16 output cannot be recognised by decodeFileText,
292
+ * which identifies UTF-16 by its byte-order mark — request it only for
293
+ * consumers that expect mark-less UTF-16.
294
+ */
235
295
  export function encodeFileText(text: string, target: { encoding: FileEncoding; bom: boolean }): Buffer {
236
- if (target.encoding === "utf16le") {
237
- return Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, "utf16le")]);
238
- }
239
- if (target.encoding === "utf16be") {
240
- return Buffer.concat([Buffer.from([0xfe, 0xff]), Buffer.from(text, "utf16le").swap16()]);
241
- }
242
- const bom = target.bom ? Buffer.from([0xef, 0xbb, 0xbf]) : Buffer.alloc(0);
243
- return Buffer.concat([bom, Buffer.from(text, "utf8")]);
296
+ const body =
297
+ target.encoding === "utf16le"
298
+ ? Buffer.from(text, "utf16le")
299
+ : target.encoding === "utf16be"
300
+ ? Buffer.from(text, "utf16le").swap16()
301
+ : Buffer.from(text, "utf8");
302
+ if (!target.bom) return body;
303
+ const bom =
304
+ target.encoding === "utf16le"
305
+ ? Buffer.from([0xff, 0xfe])
306
+ : target.encoding === "utf16be"
307
+ ? Buffer.from([0xfe, 0xff])
308
+ : Buffer.from([0xef, 0xbb, 0xbf]);
309
+ return Buffer.concat([bom, body]);
244
310
  }
245
311
 
246
312
  export async function readFileText(file: string): Promise<FileText> {
package/src/remove.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { isLegalComment } from "./directives.js";
1
+ import { activePositionalDirectives, isLegalComment, type DirectivePlacement } from "./directives.js";
2
2
  import { scanComments } from "./scanner.js";
3
3
  import type { Comment } from "./types.js";
4
4
 
@@ -18,7 +18,9 @@ export interface RemoveResult {
18
18
  removed: Comment[];
19
19
  /**
20
20
  * Comments kept because they are protected: directives, license headers,
21
- * and comments whose removal would shift code under a next-line directive.
21
+ * comments whose removal would shift code under a next-line directive, and
22
+ * comments whose removal would move a position-dependent directive
23
+ * (prettier's first-comment pragma, Bun's file-start marker) into effect.
22
24
  */
23
25
  kept: Comment[];
24
26
  /** Comments excluded from removal by the `shouldRemove` predicate. */
@@ -33,17 +35,22 @@ export interface RemoveResult {
33
35
  * - AST-based ranges: strings, template literals and regexes are never affected.
34
36
  * - Directives (`@ts-expect-error`, `eslint-disable`, ...) and license headers are
35
37
  * kept by default, since deleting them changes build/lint behaviour.
38
+ * - Surviving comments keep their directive semantics: when deleting a leading
39
+ * comment would newly activate a position-dependent directive in a kept
40
+ * comment (prettier's `@format` docblock pragma counts only as the file's
41
+ * first comment, Bun's `// @bun` only at the very start), the leading
42
+ * comment is kept instead.
36
43
  * - A space is inserted where removing a block comment would merge two tokens,
37
44
  * and a line break is kept where the comment acted as one (ASI stays intact).
38
- * - A leading byte-order mark is preserved.
45
+ * - A leading byte-order mark is preserved. Reported positions index into the
46
+ * `source` string exactly as `scanComments(source)` reports them (a BOM
47
+ * counts as its first character).
39
48
  * - The result is re-scanned; if the remaining comments do not match the kept
40
49
  * set, an error is thrown instead of returning corrupted output.
41
50
  */
42
51
  export function removeComments(source: string, options: RemoveOptions = {}): RemoveResult {
43
52
  const jsx = options.jsx === true;
44
- const bom = source.startsWith("\uFEFF") ? "\uFEFF" : "";
45
- const body = bom === "" ? source : source.slice(bom.length);
46
- const comments = scanComments(body, { jsx });
53
+ const comments = scanComments(source, { jsx });
47
54
 
48
55
  let removed: Comment[] = [];
49
56
  const kept: Comment[] = [];
@@ -58,30 +65,116 @@ export function removeComments(source: string, options: RemoveOptions = {}): Rem
58
65
  }
59
66
  }
60
67
 
61
- removed = shieldNextLineDirectives(body, removed, kept, skipped);
68
+ for (;;) {
69
+ removed = shieldNextLineDirectives(source, removed, kept, skipped);
62
70
 
63
- if (removed.length === 0) {
64
- return { code: source, removed, kept, skipped, changed: false };
71
+ if (removed.length === 0) {
72
+ return { code: source, removed, kept, skipped, changed: false };
73
+ }
74
+
75
+ const code = spliceKeepingBom(source, removed);
76
+ const survivor = firstChangedSurvivor(source, code, scanComments(code, { jsx }), kept, skipped);
77
+ if (survivor === undefined) {
78
+ return { code, removed, kept, skipped, changed: true };
79
+ }
80
+
81
+ // A surviving comment changed meaning: with everything before it deleted
82
+ // it became the file's first comment (or its very first bytes), turning a
83
+ // previously inert positional directive live. Re-protect the removal
84
+ // candidate closest before it and try again: that comment then keeps
85
+ // holding the survivor away from the activating position, exactly as the
86
+ // input did. (Looping, because the re-protected comment can itself be a
87
+ // next-line directive that shields further lines.)
88
+ const blocker = closestRemovalBefore(removed, survivor);
89
+ if (blocker === undefined) {
90
+ throw unexpectedResult();
91
+ }
92
+ removed = removed.filter((comment) => comment !== blocker);
93
+ kept.push(blocker);
94
+ kept.sort((a, b) => a.start - b.start);
65
95
  }
96
+ }
66
97
 
67
- const code = bom + splice(body, removed);
98
+ function unexpectedResult(): Error {
99
+ return new Error("comment removal produced an unexpected result; refusing to continue");
100
+ }
68
101
 
69
- if (!sameCommentTexts(scanComments(code, { jsx }), [...kept, ...skipped])) {
70
- throw new Error("comment removal produced an unexpected result; refusing to continue");
102
+ /**
103
+ * Compares the spliced output's comments against the comments meant to
104
+ * survive, in document order (removal never reorders them). Throws when the
105
+ * texts themselves differ (the output would be corrupted) and returns the
106
+ * first surviving comment whose directive semantics changed, or undefined
107
+ * when the output is exactly as expected. Besides the canonical directive
108
+ * name, the position-dependent pragmas are compared on their own: a comment
109
+ * can carry an inert `@format` underneath the directive an earlier rule
110
+ * already named (an eslint config block, say), and that pragma going live
111
+ * must not hide behind the unchanged name.
112
+ */
113
+ function firstChangedSurvivor(
114
+ source: string,
115
+ code: string,
116
+ actual: Comment[],
117
+ kept: Comment[],
118
+ skipped: Comment[],
119
+ ): Comment | undefined {
120
+ const expected = [...kept, ...skipped].sort((a, b) => a.start - b.start);
121
+ if (actual.length !== expected.length) {
122
+ throw unexpectedResult();
123
+ }
124
+ for (const [index, comment] of expected.entries()) {
125
+ const survivor = actual[index] as Comment;
126
+ if (survivor.text !== comment.text) {
127
+ throw unexpectedResult();
128
+ }
129
+ if (survivor.directive !== comment.directive) return comment;
130
+ const before = activePositionalDirectives(comment.kind, comment.text, positionalPlacement(source, comment));
131
+ const after = activePositionalDirectives(survivor.kind, survivor.text, positionalPlacement(code, survivor));
132
+ if (before.join("\n") !== after.join("\n")) return comment;
71
133
  }
134
+ return undefined;
135
+ }
136
+
137
+ /**
138
+ * The placement bits the position-dependent directives care about, derived
139
+ * without a parse: the comment is the file's first comment when nothing but
140
+ * whitespace (or a shebang) precedes it — any earlier comment's text keeps
141
+ * the slice non-blank — and it sits at the file start when it begins at
142
+ * offset zero. Header status needs the token structure, but removing
143
+ * comments never moves a comment across the first token, so the positional
144
+ * check does not consult it.
145
+ */
146
+ function positionalPlacement(text: string, comment: Comment): DirectivePlacement {
147
+ const shebangLength = /^#!.*/.exec(text)?.[0].length ?? 0;
148
+ return {
149
+ header: false,
150
+ firstComment: isBlank(text.slice(shebangLength, comment.start)),
151
+ fileStart: comment.start === 0,
152
+ };
153
+ }
72
154
 
73
- return { code, removed, kept, skipped, changed: true };
155
+ /** The removal candidate that starts closest before the comment, if any. */
156
+ function closestRemovalBefore(removals: readonly Comment[], comment: Comment): Comment | undefined {
157
+ let closest: Comment | undefined;
158
+ for (const removal of removals) {
159
+ if (removal.start < comment.start) closest = removal;
160
+ }
161
+ return closest;
74
162
  }
75
163
 
76
164
  /**
77
- * True when both lists contain the same comment texts (as multisets).
78
- * Positions shift during removal, so the texts are what must survive intact.
165
+ * Splices the removals out of the source, restoring the byte-order mark when
166
+ * dropping a comment-only first line took it along: the mark is an encoding
167
+ * artifact, not line content.
79
168
  */
80
- function sameCommentTexts(actual: Comment[], expected: Comment[]): boolean {
81
- if (actual.length !== expected.length) return false;
82
- const actualTexts = actual.map((comment) => comment.text).sort();
83
- const expectedTexts = expected.map((comment) => comment.text).sort();
84
- return actualTexts.every((text, index) => text === expectedTexts[index]);
169
+ function spliceKeepingBom(source: string, removals: readonly Comment[]): string {
170
+ if (!source.startsWith("\uFEFF")) return splice(source, removals);
171
+ // The splicing itself works on the BOM-less body (with ranges shifted to
172
+ // match) so its line handling never sees the mark, then the mark is
173
+ // re-attached; this keeps `\uFEFF// gone\n...` from losing the mark with
174
+ // the dropped line.
175
+ const body = source.slice(1);
176
+ const shifted = removals.map((comment) => ({ ...comment, start: comment.start - 1, end: comment.end - 1 }));
177
+ return `\uFEFF${splice(body, shifted)}`;
85
178
  }
86
179
 
87
180
  function isProtected(comment: Comment, options: RemoveOptions): boolean {
@@ -310,6 +403,18 @@ const isHorizontalSpace = (char: string | undefined): boolean => char === " " ||
310
403
 
311
404
  const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
312
405
 
406
+ // Every ECMAScript line break the way the scanner counts them: CRLF as one
407
+ // break, then lone LF / CR and the U+2028/U+2029 separators.
408
+ const NEXT_LINE_BREAK = /\r\n|[\n\r\u2028\u2029]/g;
409
+
410
+ /** End offset (exclusive) of the last line break in the chunk, or -1 when it has none. */
411
+ function lastLineBreakEnd(chunk: string): number {
412
+ for (let index = chunk.length - 1; index >= 0; index -= 1) {
413
+ if (LINE_TERMINATOR.test(chunk[index] as string)) return index + 1;
414
+ }
415
+ return -1;
416
+ }
417
+
313
418
  /**
314
419
  * Splices sorted, non-overlapping comment ranges out of the source, tidying lines.
315
420
  * Output is accumulated as segments with incremental line-state tracking, so the
@@ -326,8 +431,8 @@ function splice(source: string, removals: readonly Comment[]): string {
326
431
  const push = (chunk: string): void => {
327
432
  if (chunk === "") return;
328
433
  segments.push(chunk);
329
- const newlineIndex = chunk.lastIndexOf("\n");
330
- lineIsBlank = newlineIndex === -1 ? lineIsBlank && isBlank(chunk) : isBlank(chunk.slice(newlineIndex + 1));
434
+ const breakEnd = lastLineBreakEnd(chunk);
435
+ lineIsBlank = breakEnd === -1 ? lineIsBlank && isBlank(chunk) : isBlank(chunk.slice(breakEnd));
331
436
  lastChar = chunk.slice(-1);
332
437
  };
333
438
 
@@ -335,14 +440,14 @@ function splice(source: string, removals: readonly Comment[]): string {
335
440
  const dropCurrentLine = (): void => {
336
441
  while (segments.length > 0) {
337
442
  const last = segments[segments.length - 1] as string;
338
- const newlineIndex = last.lastIndexOf("\n");
339
- if (newlineIndex === -1) {
443
+ const breakEnd = lastLineBreakEnd(last);
444
+ if (breakEnd === -1) {
340
445
  segments.pop();
341
446
  continue;
342
447
  }
343
- segments[segments.length - 1] = last.slice(0, newlineIndex + 1);
448
+ segments[segments.length - 1] = last.slice(0, breakEnd);
344
449
  lineIsBlank = true;
345
- lastChar = "\n";
450
+ lastChar = last.charAt(breakEnd - 1);
346
451
  return;
347
452
  }
348
453
  lineIsBlank = true;
@@ -370,11 +475,11 @@ function splice(source: string, removals: readonly Comment[]): string {
370
475
  push(source.slice(cursor, comment.start));
371
476
  cursor = comment.end;
372
477
 
373
- const newlineIndex = source.indexOf("\n", cursor);
374
- const lineEnd = newlineIndex === -1 ? source.length : newlineIndex + 1;
375
- const rest = source.slice(cursor, lineEnd);
376
- const eolLength = rest.endsWith("\r\n") ? 2 : rest.endsWith("\n") ? 1 : 0;
377
- const restContent = rest.slice(0, rest.length - eolLength);
478
+ NEXT_LINE_BREAK.lastIndex = cursor;
479
+ const lineBreak = NEXT_LINE_BREAK.exec(source);
480
+ const contentEnd = lineBreak === null ? source.length : lineBreak.index;
481
+ const lineEnd = lineBreak === null ? source.length : lineBreak.index + lineBreak[0].length;
482
+ const restContent = source.slice(cursor, contentEnd);
378
483
 
379
484
  if (lineIsBlank && isBlank(restContent)) {
380
485
  // The comment occupied whole line(s): drop them entirely.
@@ -383,7 +488,7 @@ function splice(source: string, removals: readonly Comment[]): string {
383
488
  } else if (isBlank(restContent)) {
384
489
  // Trailing comment after code: trim the gap, keep the line break.
385
490
  trimLineEnd();
386
- push(rest.slice(restContent.length));
491
+ push(source.slice(contentEnd, lineEnd));
387
492
  cursor = lineEnd;
388
493
  } else if (!lineIsBlank && LINE_TERMINATOR.test(comment.text)) {
389
494
  // Code on both sides of a block comment that spans lines. Per ECMA-262
package/src/run.ts CHANGED
@@ -136,11 +136,26 @@ async function collectTargets(options: CliOptions, collectOptions: CollectOption
136
136
 
137
137
  const first = resolve(options.paths[0] as string);
138
138
  const anchor = (await stat(first)).isDirectory() ? first : dirname(first);
139
- const changed = new Set((await changedFiles(options.diff, anchor)).map(caseFold));
140
- // Realpath only the directory part: spellings through symlinked directories
141
- // then compare equal, while a tracked symlink still matches the path git
142
- // reports it at instead of dereferencing to its target.
143
- return files.filter((file) => changed.has(caseFold(join(realpathSync(dirname(file)), basename(file)))));
139
+ // Both the spelling git reports and the real file it refers to count as
140
+ // changed: the collector keeps one spelling per real file, so a changed
141
+ // symlink may have been remembered under its target's path (or a scanned
142
+ // alias may point at the changed file), and either spelling names the same
143
+ // content. Broken links (a symlink re-pointed at nothing) only match by
144
+ // their reported spelling.
145
+ const changed = new Set<string>();
146
+ for (const path of await changedFiles(options.diff, anchor)) {
147
+ changed.add(caseFold(path));
148
+ const real = tryRealpath(path);
149
+ if (real !== undefined) changed.add(caseFold(real));
150
+ }
151
+ // Realpath only the directory part first: spellings through symlinked
152
+ // directories then compare equal while a tracked symlink still matches the
153
+ // path git reports it at; the fully dereferenced path is the fallback.
154
+ return files.filter((file) => {
155
+ if (changed.has(caseFold(join(realpathSync.native(dirname(file)), basename(file))))) return true;
156
+ const real = tryRealpath(file);
157
+ return real !== undefined && changed.has(caseFold(real));
158
+ });
144
159
  }
145
160
 
146
161
  /**
@@ -152,6 +167,20 @@ function caseFold(path: string): string {
152
167
  return process.platform === "win32" ? path.toLowerCase() : path;
153
168
  }
154
169
 
170
+ /**
171
+ * Native realpath — changedFiles resolves the repository root with the
172
+ * (native) promises realpath, and on Windows only the native calls expand
173
+ * 8.3 short names like RUNNER~1, so every path compared against it must be
174
+ * expanded the same way. Undefined when the path cannot be resolved.
175
+ */
176
+ function tryRealpath(path: string): string | undefined {
177
+ try {
178
+ return realpathSync.native(path);
179
+ } catch {
180
+ return undefined;
181
+ }
182
+ }
183
+
155
184
  /** True when -h/--help appears before any `--` separator. */
156
185
  function wantsHelp(argv: string[]): boolean {
157
186
  for (const arg of argv) {
@@ -242,16 +271,21 @@ function renderRemoval(removals: FileRemoval[], options: CliOptions): string {
242
271
  const totalSkipped = removals.reduce((sum, entry) => sum + entry.skipped.length, 0);
243
272
  const changedEntries = removals.filter((entry) => entry.removed.length > 0);
244
273
  const keptNote = totalKept > 0 ? ` Kept ${count(totalKept, "protected comment")}.` : "";
245
- // Directives held back by --skip-directives are invisible in the removal
246
- // counts; say how many were left untouched so "removed N" is not mistaken
247
- // for "the files are now comment-free".
248
- const skippedNote = totalSkipped > 0 ? ` Skipped ${count(totalSkipped, "comment")} (--skip-directives).` : "";
274
+ // Comments held out of scope by --skip-directives / --only-directives are
275
+ // invisible in the removal counts; say how many were left untouched, naming
276
+ // the flag actually responsible, so "removed N" is not mistaken for "the
277
+ // files are now comment-free".
278
+ const skippedReason = options.directives === "only" ? "outside --only-directives" : "--skip-directives";
279
+ const skippedNote = totalSkipped > 0 ? ` Skipped ${count(totalSkipped, "comment")} (${skippedReason}).` : "";
249
280
 
250
281
  if (options.format === "json") {
251
282
  return JSON.stringify(
252
283
  {
253
284
  summary: {
254
- files: changedEntries.length,
285
+ // `files` counts the entries of `files` below, like the scan JSON;
286
+ // `changedFiles` is how many of them actually had comments removed.
287
+ files: removals.length,
288
+ changedFiles: changedEntries.length,
255
289
  removed: totalRemoved,
256
290
  kept: totalKept,
257
291
  skipped: totalSkipped,