@blundergoat/gruff-ts 0.4.0 → 0.6.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
package/src/discovery.ts CHANGED
@@ -1,30 +1,31 @@
1
- // Filesystem discovery, ignore-policy matching, and display-path normalization for deterministic scans.
1
+ // Discovers scannable TypeScript, JavaScript, and config files under a project root for every CLI command.
2
+ //
3
+ // Owns the single allowlist of scannable extensions (`pushSourceFile`), applies ignore rules in precedence order
4
+ // (`paths.ignore`, VCS directories, `.gitignore`, third-party/minified defaults, and fallback directories), and normalizes display paths.
2
5
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
6
  import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
4
7
  import type { AnalysisOptions, Config, IgnoreSource, ScanSurfaceNote, SkippedPath } from "./types.ts";
5
8
 
6
- // `absolutePath` is what `node:fs` operates on; `displayPath` is the project-relative POSIX form
7
- // embedded in findings and baselines. They must stay aligned - diverging them breaks fingerprint stability.
9
+ // `absolutePath` is what `node:fs` operates on; `displayPath` is project-relative inside the run root and absolute outside it.
10
+ // Both paths must stay aligned because finding fingerprints hash `displayPath`.
8
11
  export interface SourceFile {
9
12
  absolutePath: string;
10
13
  displayPath: string;
11
14
  isScript: boolean;
12
15
  }
13
16
 
14
- // Mutable accumulator used during the walk. `ignoredPaths` is a Set because the walker may visit
15
- // the same parent path through multiple roots; finalised into a sorted array on return.
17
+ // Mutable accumulator used during the directory walk; `skipped` is keyed by display path so repeated roots deduplicate before sorting.
16
18
  interface SourceDiscovery {
17
19
  files: SourceFile[];
18
20
  missingPaths: string[];
19
21
  skipped: Map<string, SkippedPath>;
20
22
  }
21
23
 
22
- // Public discovery result. `files` are sorted by display path and deduped; `ignoredPaths` (the
23
- // back-compatible string[] of excluded paths) and `skipped` (the same paths enriched with ignore
24
- // source + matched pattern) are sorted so reports stay deterministic even when the underlying
25
- // filesystem returns directory entries in arbitrary order. `notes` carries one entry per requested
26
- // input that exists but contributed zero analysable files, so an all-skipped scan is never a
27
- // silent zero-finding success.
24
+ // Deterministic discovery output returned to the analyser and `check-ignore`:
25
+ //
26
+ // - `files` are sorted and deduplicated by `displayPath` so reports never depend on filesystem readdir order;
27
+ // - `ignoredPaths` and `skipped` record excluded paths with their ignore source and matched pattern;
28
+ // - `notes` lists existing targets that produced zero analysable files so an all-skipped run never looks silently clean.
28
29
  export interface SourceDiscoveryResult {
29
30
  files: SourceFile[];
30
31
  missingPaths: string[];
@@ -33,8 +34,7 @@ export interface SourceDiscoveryResult {
33
34
  notes: ScanSurfaceNote[];
34
35
  }
35
36
 
36
- // A single line from a `.gitignore`. The combination of `isAnchored`, `isDirectoryOnly`, and `hasSlash`
37
- // reproduces git's documented matching semantics; missing any one of them yields wrong matches.
37
+ // One parsed `.gitignore` line whose flags (`isAnchored`, `isDirectoryOnly`, `hasSlash`, `isNegated`) preserve git's matching semantics.
38
38
  interface GitIgnoreRule {
39
39
  basePath: string;
40
40
  pattern: string;
@@ -44,9 +44,15 @@ interface GitIgnoreRule {
44
44
  hasSlash: boolean;
45
45
  }
46
46
 
47
- // Public entry point. Reads from the filesystem and returns a sorted, deduped, deterministic
48
- // result so finding ordering and report-path metadata remain stable across runs - this is part of
49
- // the schema invariant that makes baseline matching reproducible.
47
+ /**
48
+ * Reads the filesystem, resolving options' paths against projectRoot and using config and options to decide what to skip.
49
+ * With no paths, scans projectRoot. Deduplicates files by absolute path and sorts files and skips to preserve stable report order.
50
+ *
51
+ * @param projectRoot - base directory used to resolve requested paths and format report paths
52
+ * @param options - scan options supplying target paths and ignore bypass settings
53
+ * @param config - user configuration supplying explicit ignore patterns
54
+ * @returns discovered files, missing paths, skipped paths and reasons, and notes for inputs that add no files or missing paths
55
+ */
50
56
  export function discoverSources(projectRoot: string, options: AnalysisOptions, config: Config): SourceDiscoveryResult {
51
57
  const discovery: SourceDiscovery = { files: [], missingPaths: [], skipped: new Map<string, SkippedPath>() };
52
58
  const inputs = options.paths.length > 0 ? options.paths : ["."];
@@ -67,9 +73,14 @@ export function discoverSources(projectRoot: string, options: AnalysisOptions, c
67
73
  return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped, notes };
68
74
  }
69
75
 
70
- // A requested input that exists but contributed no analysable files is a per-input note, never a
71
- // diagnostic - exit codes stay unchanged. The skip count names the likely cause (parent gitignore
72
- // or config ignore rules hiding the whole subtree) so the caller does not read 0 findings as clean.
76
+ /**
77
+ * Builds an informational note for an existing input that contributed no analysable files, so zero findings cannot be mistaken for a clean scan.
78
+ * A positive count reports newly recorded skips, while a zero count reports no analysable source files.
79
+ *
80
+ * @param input - requested file or directory path that produced no analysable files
81
+ * @param skippedCount - number of newly recorded skipped paths under the input
82
+ * @returns scan surface note describing why the input contributed no analysable files
83
+ */
73
84
  function zeroFileInputNote(input: string, skippedCount: number): ScanSurfaceNote {
74
85
  const cause = skippedCount > 0
75
86
  ? `${skippedCount} path(s) under it were excluded by ignore rules`
@@ -81,11 +92,18 @@ function zeroFileInputNote(input: string, skippedCount: number): ScanSurfaceNote
81
92
  };
82
93
  }
83
94
 
84
- // Resolves the input against `node:fs`. Missing inputs go into `missingPaths` so the CLI can
85
- // report them as diagnostics rather than silently producing no findings. CI output depends on that
86
- // distinction. An explicitly supplied file still honours config `paths.ignore` (authoritative in
87
- // every invocation, per ADR-007); default/gitignore stay directory-walk-only (ADR-003), so passing
88
- // empty gitignore rules here keeps an explicit file scannable unless config excludes it.
95
+ /**
96
+ * Collects files, missing inputs, and exclusion reasons for one requested path.
97
+ * Explicit files honour config and VCS exclusions and bypass Git ignore rules and all other default exclusions.
98
+ * If no exclusion matches, an explicit file outside the scan allowlist adds no entry.
99
+ *
100
+ * @param projectRoot - base directory for resolving input and formatting report paths
101
+ * @param input - requested file or directory path
102
+ * @param options - scan options controlling inclusion of ignored paths
103
+ * @param config - user configuration supplying explicit ignore patterns
104
+ * @param discovery - accumulator mutated with files, missingPaths, and skipped entries
105
+ * @returns Nothing. Records discovered files, missing paths, or exclusions in discovery.
106
+ */
89
107
  function discoverSourceInput(projectRoot: string, input: string, options: AnalysisOptions, config: Config, discovery: SourceDiscovery): void {
90
108
  const absolute = absolutize(projectRoot, input);
91
109
  if (!existsSync(absolute)) {
@@ -95,7 +113,16 @@ function discoverSourceInput(projectRoot: string, input: string, options: Analys
95
113
  const stats = statSync(absolute);
96
114
  if (stats.isFile()) {
97
115
  const display = displayPath(projectRoot, absolute);
98
- const match = classifyIgnore(display, false, options, config, []);
116
+ const match = classifyIgnore({
117
+ projectRoot,
118
+ absolute,
119
+ display,
120
+ isDirectory: false,
121
+ options,
122
+ config,
123
+ gitIgnoreRules: [],
124
+ isExplicitFile: true,
125
+ });
99
126
  if (match) {
100
127
  discovery.skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
101
128
  return;
@@ -107,6 +134,18 @@ function discoverSourceInput(projectRoot: string, input: string, options: Analys
107
134
  walk(projectRoot, absolute, options, config, discovery.skipped, discovery.files, gitIgnoreRules);
108
135
  }
109
136
 
137
+ /**
138
+ * Reads directory entries depth first to collect supported files and prunes ignored subtrees to avoid reading their contents.
139
+ *
140
+ * @param projectRoot - base directory for report paths and ignore-rule ownership
141
+ * @param directory - directory whose entries are scanned
142
+ * @param options - controls whether to bypass Git rules and non-VCS defaults
143
+ * @param config - user configuration supplying explicit ignore patterns
144
+ * @param skipped - map mutated with excluded paths and their reasons
145
+ * @param files - array mutated with admitted source records
146
+ * @param gitIgnoreRules - inherited rules extended for each child directory unless ignored paths are included
147
+ * @returns Nothing. Adds eligible source records to files and records exclusions in skipped.
148
+ */
110
149
  function walk(
111
150
  projectRoot: string,
112
151
  directory: string,
@@ -120,9 +159,21 @@ function walk(
120
159
  const absolute = join(directory, entry.name);
121
160
  const display = displayPath(projectRoot, absolute);
122
161
  if (entry.isDirectory() || entry.isFile()) {
123
- const match = classifyIgnore(display, entry.isDirectory(), options, config, gitIgnoreRules);
162
+ const match = classifyIgnore({
163
+ projectRoot,
164
+ absolute,
165
+ display,
166
+ isDirectory: entry.isDirectory(),
167
+ options,
168
+ config,
169
+ gitIgnoreRules,
170
+ isExplicitFile: false,
171
+ });
124
172
  if (match) {
125
- skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
173
+ // Default minified-file exclusions record skips only for scannable file types; explicit config or .gitignore rules always record skips.
174
+ if (match.source !== "default" || match.pattern !== MINIFIED_FILE_PATTERN || isScannableSourceFile(absolute)) {
175
+ skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
176
+ }
126
177
  continue;
127
178
  }
128
179
  }
@@ -134,31 +185,93 @@ function walk(
134
185
  }
135
186
  }
136
187
 
137
- // Single source of truth for which extensions count as scannable. Adding a new file kind here will
138
- // expand the rule set's reach across an entire project - coordinate with rule descriptors before changing.
188
+ /** Extensions parsed as code. Widening this reaches every rule that inspects script syntax. */
189
+ export const SCRIPT_FILE_EXTENSIONS: readonly string[] = ["ts", "tsx", "js", "jsx", "mjs", "cjs"];
190
+
191
+ /** Extensions read as config or text assets, which only the text-oriented rules inspect. */
192
+ export const TEXT_FILE_EXTENSIONS: readonly string[] = ["conf", "config", "env", "ini", "json", "toml", "xml", "yaml", "yml"];
193
+
194
+ /** Extensionless credential files that stay scannable without admitting every dotfile. */
195
+ export const EXACT_SECRET_TEXT_FILES: readonly string[] = [".npmrc", ".pypirc", ".envrc", ".netrc"];
196
+
197
+ /**
198
+ * Adds a supported path to the scan list; release-truth.test.ts pins the allowlists defining the documented scan surface.
199
+ *
200
+ * @param projectRoot - base directory for formatting the file's report path
201
+ * @param absolutePath - candidate file path checked against the script and text allowlists
202
+ * @param files - accumulator receiving a source record for supported files; unsupported paths leave it unchanged
203
+ * @returns Nothing. Adds the source record for a supported path to files.
204
+ */
139
205
  function pushSourceFile(projectRoot: string, absolutePath: string, files: SourceFile[]): void {
140
- const extension = extname(absolutePath).slice(1).toLowerCase();
141
- const name = basename(absolutePath);
142
- const isScript = ["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(extension);
143
- const isText =
144
- ["conf", "config", "env", "ini", "json", "toml", "xml", "yaml", "yml"].includes(extension) ||
145
- name.startsWith(".env") ||
146
- isExactSecretTextFile(name);
147
- if (isScript || isText) {
148
- files.push({ absolutePath, displayPath: displayPath(projectRoot, absolutePath), isScript });
206
+ if (isScannableSourceFile(absolutePath)) {
207
+ files.push({ absolutePath, displayPath: displayPath(projectRoot, absolutePath), isScript: isScriptFile(absolutePath) });
149
208
  }
150
209
  }
151
210
 
152
- // Exact extensionless secret files stay scannable without opening the door to every dotfile.
153
- function isExactSecretTextFile(name: string): boolean {
154
- return [".npmrc", ".pypirc", ".envrc", ".netrc"].includes(name);
155
- }
156
-
157
- // The default-ignore list is part of the documented schema contract: callers can override with
158
- // `--include-ignored`, but the list itself must not silently change between releases without notice.
159
- function isDefaultIgnoredDir(path: string): boolean {
160
- const first = path.split("/")[0] ?? path;
161
- return [".git", ".hg", ".svn", ".idea", ".vscode", "build", "cache", "coverage", "dist", "generated", "node_modules", "target", "tmp", "vendor"].includes(first);
211
+ /**
212
+ * Reports whether pushSourceFile would admit a path, so the walk lists a skipped minified file only when it is scannable.
213
+ *
214
+ * @param absolutePath - candidate file path whose extension and basename are checked against script and text allowlists
215
+ * @returns true when the file matches a supported script, text, or secret-file allowlist entry
216
+ */
217
+ function isScannableSourceFile(absolutePath: string): boolean {
218
+ const name = basename(absolutePath);
219
+ const isText = TEXT_FILE_EXTENSIONS.includes(extname(absolutePath).slice(1).toLowerCase()) || name.startsWith(".env") || EXACT_SECRET_TEXT_FILES.includes(name);
220
+ return isScriptFile(absolutePath) || isText;
221
+ }
222
+
223
+ /**
224
+ * Reports whether a path's extension is parsed as code.
225
+ *
226
+ * @param absolutePath - candidate file path whose lowercase extension is checked
227
+ * @returns true when the extension belongs to the script file allowlist
228
+ */
229
+ function isScriptFile(absolutePath: string): boolean {
230
+ return SCRIPT_FILE_EXTENSIONS.includes(extname(absolutePath).slice(1).toLowerCase());
231
+ }
232
+
233
+ const VCS_DIRECTORIES = [".git", ".hg", ".svn"] as const;
234
+ const FALLBACK_DIRECTORIES = [".fleet", ".idea", ".vscode", "build", "coverage", "node_modules"] as const;
235
+
236
+ // Third-party copy directories plus `dist`, skipped at any depth under ASCII case folding even when a `.gitignore` governs the directory.
237
+ // `build` and `coverage` stay fallback-only (FAMILY-CONTRACT.md section 7, amended by precision-floor M04).
238
+ const THIRD_PARTY_DIRECTORIES: readonly string[] = ["bower_components", "dist", "third-party", "third_party", "vendor", "vendors"];
239
+
240
+ /** Pattern recorded for a minified file such as `jquery.min.js`, which section 7 skips as generated. */
241
+ export const MINIFIED_FILE_PATTERN = "*.min.*";
242
+
243
+ /**
244
+ * Folds only ASCII capital letters to lowercase so directory and filename checks use consistent case folding.
245
+ *
246
+ * @param pathComponent - single path segment or filename to normalize
247
+ * @returns the path component with ASCII uppercase letters converted to lowercase
248
+ */
249
+ function asciiLower(pathComponent: string): string {
250
+ return pathComponent.replace(/[A-Z]/gu, (character) => character.toLowerCase());
251
+ }
252
+
253
+ /**
254
+ * Finds the outermost third-party or build-output directory on display using ASCII-lowercased components.
255
+ *
256
+ * @param display - slash-separated display path to inspect
257
+ * @param isDirectory - controls whether to check the final component, so a/Vendor/x.ts gives vendor and a file named dist gives no match
258
+ * @returns lowercase matched directory name, or undefined when this policy supplies no exclusion
259
+ */
260
+ function matchedThirdPartyDirectory(display: string, isDirectory: boolean): string | undefined {
261
+ const components = display.split("/");
262
+ const directories = isDirectory ? components : components.slice(0, -1);
263
+ return directories.map(asciiLower).find((component) => THIRD_PARTY_DIRECTORIES.includes(component));
264
+ }
265
+
266
+ /**
267
+ * Reports whether the base name has an ASCII case-insensitive .min. marker directly before its final extension.
268
+ * For example, jquery.MIN.js matches, while app.min.js.map and admin.mini.js do not.
269
+ *
270
+ * @param name - file basename to check for a minified marker
271
+ * @returns true when the name ends with a .min. marker followed by a single final extension
272
+ */
273
+ function isMinifiedName(name: string): boolean {
274
+ return /\.min\.[^.]+$/u.test(asciiLower(name));
162
275
  }
163
276
 
164
277
  // The matched ignore source and the exact pattern that excluded a path. Returned by `classifyIgnore`.
@@ -167,26 +280,55 @@ interface IgnoreMatch {
167
280
  pattern: string;
168
281
  }
169
282
 
170
- // Single ignore decision shared by the directory walk, explicit-file handling, and `check-ignore`,
171
- // so there is exactly one glob/ignore implementation. Returns the first matching source with its
172
- // pattern, or undefined. Evaluation order is default -> gitignore -> config, but config is the
173
- // authoritative source: it is checked regardless of `--include-ignored` and applies to explicit file
174
- // operands (which pass empty gitignore rules so default/gitignore cannot match them, per ADR-003).
175
- function classifyIgnore(display: string, isDirectory: boolean, options: AnalysisOptions, config: Config, gitIgnoreRules: GitIgnoreRule[]): IgnoreMatch | undefined {
176
- const defaultMatch = defaultIgnoreMatch(display, isDirectory, options, false);
177
- if (defaultMatch) {
178
- return defaultMatch;
179
- }
180
- if (!options.shouldIncludeIgnored) {
181
- const rule = matchedGitIgnoreRule(gitIgnoreRules, display, isDirectory);
182
- if (rule) {
183
- return { source: "gitignore", pattern: rule.pattern };
184
- }
185
- }
283
+ // Bundles one ignore decision so adding policy context does not expand the helper's parameter list.
284
+ interface IgnoreClassificationInput {
285
+ projectRoot: string;
286
+ absolute: string;
287
+ display: string;
288
+ isDirectory: boolean;
289
+ options: AnalysisOptions;
290
+ config: Config;
291
+ gitIgnoreRules: GitIgnoreRule[];
292
+ isExplicitFile: boolean;
293
+ }
294
+
295
+ /**
296
+ * Classifies the path in input using its location, kind, scan options, config, and Git ignore rules.
297
+ * Config and VCS exclusions always apply; explicit files and --include-ignored bypass Git and remaining default exclusions.
298
+ *
299
+ * @param input - bundled path coordinates, kind, options, config, and inherited Git ignore rules
300
+ * @returns the first matching ignore source and pattern, or undefined to keep the path eligible
301
+ */
302
+ function classifyIgnore(input: IgnoreClassificationInput): IgnoreMatch | undefined {
303
+ const { projectRoot, absolute, display, isDirectory, options, config, gitIgnoreRules, isExplicitFile } = input;
186
304
  const configPattern = config.ignoredPaths.find((pattern) => pathMatches(pattern, display));
187
305
  if (configPattern !== undefined) {
188
306
  return { source: "config", pattern: configPattern };
189
307
  }
308
+ // Match the absolute path, not the report path: `analyse ../repo/.git/config.ts` roots the run inside `.git`, which drops the component from `display`.
309
+ const vcsComponent = matchedDirectoryComponent(absolute.replaceAll("\\", "/"), VCS_DIRECTORIES);
310
+ if (vcsComponent !== undefined) {
311
+ return { source: "default", pattern: `${vcsComponent}/` };
312
+ }
313
+ if (options.shouldIncludeIgnored || isExplicitFile) {
314
+ return undefined;
315
+ }
316
+ const rule = matchedGitIgnoreRule(gitIgnoreRules, display, isDirectory);
317
+ if (rule) {
318
+ return { source: "gitignore", pattern: rule.pattern };
319
+ }
320
+ // When Git has no match, a third-party directory takes priority over a minified file name in the reported reason.
321
+ const thirdPartyDirectory = matchedThirdPartyDirectory(display, isDirectory);
322
+ if (thirdPartyDirectory !== undefined) {
323
+ return { source: "default", pattern: `${thirdPartyDirectory}/` };
324
+ }
325
+ if (!isDirectory && isMinifiedName(basename(display))) {
326
+ return { source: "default", pattern: MINIFIED_FILE_PATTERN };
327
+ }
328
+ const fallbackComponent = matchedDirectoryComponent(display, FALLBACK_DIRECTORIES);
329
+ if (fallbackComponent !== undefined && fallbackAppliesAt(projectRoot, absolute)) {
330
+ return { source: "default", pattern: `${fallbackComponent}/` };
331
+ }
190
332
  return undefined;
191
333
  }
192
334
 
@@ -200,34 +342,98 @@ export interface PathIgnoreClassification {
200
342
  pattern?: string;
201
343
  }
202
344
 
203
- // Classifies one caller-supplied path without analysing it, preserving the shared ignore contract.
345
+ /**
346
+ * Reports the shared ignore decision for one path without scanning its contents.
347
+ * Existing regular files bypass Git and default exclusions, while config and VCS exclusions still apply.
348
+ *
349
+ * @param projectRoot - base directory for resolving input and formatting the reported path
350
+ * @param input - path to classify. Missing paths are treated as non-directories and receive no explicit-file bypass
351
+ * @param options - controls whether ignored paths are included
352
+ * @param config - user configuration supplying explicit ignore patterns
353
+ * @returns display path and isIgnored; ignored paths also include the exclusion source and pattern
354
+ */
204
355
  export function classifyPathIgnore(projectRoot: string, input: string, options: AnalysisOptions, config: Config): PathIgnoreClassification {
205
356
  const absolute = absolutize(projectRoot, input);
206
357
  const display = displayPath(projectRoot, absolute);
207
- const isDirectory = existsSync(absolute) && statSync(absolute).isDirectory();
208
- const defaultMatch = defaultIgnoreMatch(display, isDirectory, options, true);
209
- if (defaultMatch) {
210
- return { path: display, isIgnored: true, source: defaultMatch.source, pattern: defaultMatch.pattern };
211
- }
212
- const ruleDirectory = isDirectory ? absolute : dirname(absolute);
213
- const gitIgnoreRules = options.shouldIncludeIgnored || !isDirectory ? [] : gitIgnoreRulesForDirectory(projectRoot, ruleDirectory);
214
- const match = classifyIgnore(display, isDirectory, options, config, gitIgnoreRules);
358
+ const exists = existsSync(absolute);
359
+ const isDirectory = exists && statSync(absolute).isDirectory();
360
+ const isExplicitFile = exists && statSync(absolute).isFile();
361
+ const gitIgnoreLookupDirectory = isInsideProject(projectRoot, dirname(absolute)) ? dirname(absolute) : projectRoot;
362
+ const gitIgnoreRules = options.shouldIncludeIgnored || isExplicitFile
363
+ ? []
364
+ : gitIgnoreRulesForDirectory(projectRoot, gitIgnoreLookupDirectory);
365
+ const match = classifyIgnore({
366
+ projectRoot,
367
+ absolute,
368
+ display,
369
+ isDirectory,
370
+ options,
371
+ config,
372
+ gitIgnoreRules,
373
+ isExplicitFile,
374
+ });
215
375
  return match ? { path: display, isIgnored: true, source: match.source, pattern: match.pattern } : { path: display, isIgnored: false };
216
376
  }
217
377
 
218
- // Default ignores are directory-walk policy; `check-ignore` also needs parent-dir answers for
219
- // changed-file prefilters so generated paths under `dist/` agree with what `analyse .` would scan.
220
- function defaultIgnoreMatch(display: string, isDirectory: boolean, options: AnalysisOptions, includeParentDir: boolean): IgnoreMatch | undefined {
221
- if (options.shouldIncludeIgnored) {
222
- return undefined;
378
+ /**
379
+ * Finds the first path component owned by one directory-policy set.
380
+ *
381
+ * @param path - slash-separated path whose components are inspected
382
+ * @param candidates - directory names belonging to a specific exclusion policy
383
+ * @returns the first matching component, or undefined when no component belongs to candidates
384
+ */
385
+ function matchedDirectoryComponent(path: string, candidates: readonly string[]): string | undefined {
386
+ return path.split("/").find((component) => candidates.includes(component));
387
+ }
388
+
389
+ /**
390
+ * Reports whether fallback exclusions apply to absolute: outside projectRoot they always apply.
391
+ * Inside projectRoot they apply only if no regular .gitignore exists from the root through the candidate's parent.
392
+ *
393
+ * @param projectRoot - run root directory that bounds .gitignore lookup
394
+ * @param absolute - resolved candidate path being evaluated
395
+ * @returns true when fallback directory exclusions govern the candidate path
396
+ */
397
+ function fallbackAppliesAt(projectRoot: string, absolute: string): boolean {
398
+ if (!isInsideProject(projectRoot, absolute)) {
399
+ return true;
223
400
  }
224
- const defaultIgnored = includeParentDir ? isDefaultIgnoredDir(display) : isDirectory && isDefaultIgnoredDir(display);
225
- return defaultIgnored ? { source: "default", pattern: `${display.split("/")[0] ?? display}/` } : undefined;
401
+ const parentDirectory = dirname(absolute);
402
+ const relativeParent = isInsideProject(projectRoot, parentDirectory)
403
+ ? relative(projectRoot, parentDirectory).replaceAll("\\", "/")
404
+ : "";
405
+ const segments = relativeParent === "" ? [] : relativeParent.split("/");
406
+ let current = projectRoot;
407
+ if (isGitIgnoreFile(join(current, ".gitignore"))) {
408
+ return false;
409
+ }
410
+ for (const segment of segments) {
411
+ current = join(current, segment);
412
+ if (isGitIgnoreFile(join(current, ".gitignore"))) {
413
+ return false;
414
+ }
415
+ }
416
+ return true;
417
+ }
418
+
419
+ /**
420
+ * Distinguishes a regular .gitignore file from a missing path or directory.
421
+ *
422
+ * @param path - filesystem path to check for a regular file
423
+ * @returns true when the path exists on the filesystem and is a regular file
424
+ */
425
+ function isGitIgnoreFile(path: string): boolean {
426
+ return existsSync(path) && statSync(path).isFile();
226
427
  }
227
428
 
228
- // Walks .gitignore files top-down from project root to the target directory so child rules can
229
- // override parents - this must match git's documented inheritance order or the scan will diverge
230
- // from `git status` on the same tree, and reads each `.gitignore` it encounters along the way.
429
+ /**
430
+ * Collects .gitignore rules from projectRoot through directory in parent-before-child order, so later child rules can override parents.
431
+ * Reads every regular .gitignore along the chain.
432
+ *
433
+ * @param projectRoot - root directory beyond which .gitignore files are not read
434
+ * @param directory - target directory whose ancestor .gitignore chain is loaded
435
+ * @returns ordered ignore rules, or an empty list outside projectRoot or when no file contributes usable rules
436
+ */
231
437
  function gitIgnoreRulesForDirectory(projectRoot: string, directory: string): GitIgnoreRule[] {
232
438
  if (!isInsideProject(projectRoot, directory)) {
233
439
  return [];
@@ -244,8 +450,15 @@ function gitIgnoreRulesForDirectory(projectRoot: string, directory: string): Git
244
450
  return rules;
245
451
  }
246
452
 
247
- // Reads one `.gitignore` and appends its rules to the inherited stack. Returns the original array
248
- // untouched when no file exists so the walker can pass results around without spurious allocations.
453
+ /**
454
+ * Reads directory's .gitignore with rule paths based at projectRoot and appends its rules after inheritedRules.
455
+ * Preserves the caller's inherited stack by returning a new array when rules are added.
456
+ *
457
+ * @param projectRoot - root directory used to compute the .gitignore basePath
458
+ * @param directory - directory inspected for a regular .gitignore file
459
+ * @param inheritedRules - parent ignore rules that stay unchanged when no usable rules are found
460
+ * @returns inheritedRules unchanged if no usable rules apply, otherwise a new combined array
461
+ */
249
462
  function appendGitIgnoreRules(projectRoot: string, directory: string, inheritedRules: GitIgnoreRule[]): GitIgnoreRule[] {
250
463
  const ignoreFile = join(directory, ".gitignore");
251
464
  if (!existsSync(ignoreFile) || !statSync(ignoreFile).isFile()) {
@@ -257,8 +470,13 @@ function appendGitIgnoreRules(projectRoot: string, directory: string, inheritedR
257
470
  return parsedRules.length > 0 ? [...inheritedRules, ...parsedRules] : inheritedRules;
258
471
  }
259
472
 
260
- // One rule per non-empty, non-comment line. Empty results are dropped here so downstream matchers
261
- // never need to guard against undefined patterns.
473
+ /**
474
+ * Parses .gitignore source into ordered rules owned by basePath, dropping comments, blanks, and marker-only lines.
475
+ *
476
+ * @param source - raw .gitignore file text with LF or CRLF line endings
477
+ * @param basePath - directory path owning these rules relative to the project root, or empty string for the root
478
+ * @returns ordered parsed rules, or an empty array when no usable rules remain
479
+ */
262
480
  function parseGitIgnoreRules(source: string, basePath: string): GitIgnoreRule[] {
263
481
  const rules: GitIgnoreRule[] = [];
264
482
  for (const rawLine of source.replace(/\r\n/g, "\n").split("\n")) {
@@ -270,9 +488,13 @@ function parseGitIgnoreRules(source: string, basePath: string): GitIgnoreRule[]
270
488
  return rules;
271
489
  }
272
490
 
273
- // Extracts the four flags git applies per pattern: negation (`!`), directory-only (trailing `/`),
274
- // path-scoped (leading `/` or contains `/`), and the cleaned pattern itself. Undefined return means
275
- // the line was blank or a comment - callers must not treat it as a "match nothing" rule.
491
+ /**
492
+ * Parses rawLine from the .gitignore owned by basePath into its normalized pattern and matching flags.
493
+ *
494
+ * @param rawLine - single line from a .gitignore file
495
+ * @param basePath - owning directory path relative to the project root; an empty string attaches the rule to the root
496
+ * @returns parsed rule, or undefined for comments, blank lines, or lines whose negation or slash markers leave no pattern
497
+ */
276
498
  function parseGitIgnoreRule(rawLine: string, basePath: string): GitIgnoreRule | undefined {
277
499
  const initial = unescapedGitIgnoreLine(rawLine);
278
500
  if (!initial) {
@@ -292,8 +514,12 @@ function parseGitIgnoreRule(rawLine: string, basePath: string): GitIgnoreRule |
292
514
  return { basePath, pattern, isNegated, isDirectoryOnly, isAnchored, hasSlash: pattern.includes("/") };
293
515
  }
294
516
 
295
- // Blank and comment lines return undefined so the caller can skip them cleanly. Trailing spaces are
296
- // ignored only when they are not escaped, matching gitignore's literal-space escape.
517
+ /**
518
+ * Normalizes a raw .gitignore line, ignoring trailing spaces only when they are not escaped to match gitignore's literal-space escape.
519
+ *
520
+ * @param rawLine - single line read from a .gitignore file
521
+ * @returns trimmed pattern text, or undefined for blank or comment lines so the caller can skip them cleanly
522
+ */
297
523
  function unescapedGitIgnoreLine(rawLine: string): string | undefined {
298
524
  const line = trimUnescapedTrailingSpaces(rawLine);
299
525
  if (line.length === 0 || line.startsWith("#")) {
@@ -302,8 +528,13 @@ function unescapedGitIgnoreLine(rawLine: string): string | undefined {
302
528
  return line;
303
529
  }
304
530
 
305
- // Gitignore treats trailing spaces as insignificant unless escaped. Walk back from the end so a
306
- // literal `\ ` stays part of the pattern while editor-added padding disappears.
531
+ /**
532
+ * Strips unescaped trailing spaces from a .gitignore line because Git treats them as padding.
533
+ * A backslash-escaped trailing space stays part of the pattern.
534
+ *
535
+ * @param rawLine - raw line from a .gitignore file
536
+ * @returns line text without unescaped trailing spaces
537
+ */
307
538
  function trimUnescapedTrailingSpaces(rawLine: string): string {
308
539
  let end = rawLine.length;
309
540
  while (end > 0 && rawLine[end - 1] === " " && !isEscapedAt(rawLine, end - 1)) {
@@ -312,8 +543,14 @@ function trimUnescapedTrailingSpaces(rawLine: string): string {
312
543
  return rawLine.slice(0, end);
313
544
  }
314
545
 
315
- // True when the character at `index` has an odd number of backslashes immediately before it.
316
- // Even runs cancel out because `\\ ` means a literal slash followed by an unescaped space.
546
+ /**
547
+ * Checks whether the character at index in source has an odd number of backslashes immediately before it.
548
+ * Even runs cancel out because a pair represents a literal backslash and leaves the next character unescaped.
549
+ *
550
+ * @param source - string containing the character to test
551
+ * @param index - zero-based position of the character in source
552
+ * @returns true when an odd run of backslashes precedes index
553
+ */
317
554
  function isEscapedAt(source: string, index: number): boolean {
318
555
  let slashCount = 0;
319
556
  for (let cursor = index - 1; cursor >= 0 && source[cursor] === "\\"; cursor -= 1) {
@@ -322,8 +559,13 @@ function isEscapedAt(source: string, index: number): boolean {
322
559
  return slashCount % 2 === 1;
323
560
  }
324
561
 
325
- // Strips leading and trailing slashes (those flags are already captured in `isAnchored` /
326
- // `isDirectoryOnly`) and collapses any internal `//` runs so the glob matcher sees canonical segments.
562
+ /**
563
+ * Builds the canonical matcher pattern for a gitignore line after its anchor and directory-only flags have been captured.
564
+ * Removes edge slashes and empty internal segments.
565
+ *
566
+ * @param line - unescaped gitignore line without negation prefix
567
+ * @returns normalized pattern, or an empty string for an all-slash line so the caller drops the rule
568
+ */
327
569
  function normalizedGitIgnorePattern(line: string): string {
328
570
  return line
329
571
  .replace(/^\/+/, "")
@@ -333,9 +575,15 @@ function normalizedGitIgnorePattern(line: string): string {
333
575
  .join("/");
334
576
  }
335
577
 
336
- // Sequential evaluation, last match wins. This is the same algorithm git uses and is the reason
337
- // negations later in a file (or in a child `.gitignore`) can reinstate previously ignored paths.
338
- // Returns the deciding rule (for source + pattern reporting) when the path ends up ignored.
578
+ /**
579
+ * Evaluates rules in inherited file order against display so later negations can clear an earlier exclusion.
580
+ * The last matching rule decides whether the path is ignored.
581
+ *
582
+ * @param rules - ordered .gitignore rules from root through parent directories
583
+ * @param display - candidate path formatted relative to the project root
584
+ * @param isDirectory - identifies whether the candidate path is a directory
585
+ * @returns the deciding rule for an ignored path, or undefined when no rule matches or the last match is a negation
586
+ */
339
587
  function matchedGitIgnoreRule(rules: GitIgnoreRule[], display: string, isDirectory: boolean): GitIgnoreRule | undefined {
340
588
  let matched: GitIgnoreRule | undefined;
341
589
  let isIgnored = false;
@@ -348,8 +596,15 @@ function matchedGitIgnoreRule(rules: GitIgnoreRule[], display: string, isDirecto
348
596
  return isIgnored ? matched : undefined;
349
597
  }
350
598
 
351
- // First rebases the display path against the rule's basePath (rules don't reach outside their
352
- // owning directory), then dispatches to the directory-only or file matcher.
599
+ /**
600
+ * Reports whether rule matches the candidate display path after rebasing it against the rule's owning directory.
601
+ * The owner never matches, and nested rules reject paths outside their base; files can still match through an ancestor directory.
602
+ *
603
+ * @param rule - parsed .gitignore rule to evaluate
604
+ * @param display - candidate project-relative display path supplied by discovery
605
+ * @param isDirectory - tells directory-only rules whether they can test the leaf itself
606
+ * @returns true when the rule matches the rebased path
607
+ */
353
608
  function gitIgnoreRuleMatches(rule: GitIgnoreRule, display: string, isDirectory: boolean): boolean {
354
609
  const relativePath = pathRelativeToBase(rule.basePath, display);
355
610
  if (relativePath === undefined || relativePath.length === 0) {
@@ -362,8 +617,14 @@ function gitIgnoreRuleMatches(rule: GitIgnoreRule, display: string, isDirectory:
362
617
  return gitIgnoreFileRuleMatches(rule, relativePath, isDirectory);
363
618
  }
364
619
 
365
- // Path-scoped patterns (with `/` or anchored) match against progressive sub-paths; bare patterns
366
- // match any path segment. Mirrors git's distinction between `foo` (any segment) and `dir/foo`.
620
+ /**
621
+ * Reports whether a non-directory-only rule matches relativePath, testing successive prefixes for path-scoped patterns and segments for bare ones.
622
+ *
623
+ * @param rule - parsed .gitignore rule without a trailing slash restriction
624
+ * @param relativePath - candidate path relative to the rule's owning directory
625
+ * @param isDirectory - candidate kind passed to the prefix helper while both files and directories include the leaf
626
+ * @returns true when the rule pattern matches any candidate prefix or segment
627
+ */
367
628
  function gitIgnoreFileRuleMatches(rule: GitIgnoreRule, relativePath: string, isDirectory: boolean): boolean {
368
629
  if (isPathScopedGitIgnoreRule(rule)) {
369
630
  return gitIgnorePathCandidates(relativePath, isDirectory, true).some((candidate) => gitIgnoreGlobMatches(rule.pattern, candidate));
@@ -371,8 +632,15 @@ function gitIgnoreFileRuleMatches(rule: GitIgnoreRule, relativePath: string, isD
371
632
  return relativePath.split("/").some((segment) => gitIgnoreGlobMatches(rule.pattern, segment));
372
633
  }
373
634
 
374
- // Like the file matcher but only considers directory segments - `node_modules/` must not match the
375
- // leaf file name even if a file happened to be called `node_modules`.
635
+ /**
636
+ * Reports whether a directory-only rule matches a directory in relativePath.
637
+ * A rule such as node_modules/ must skip a same-named file leaf while still matching ancestor directories.
638
+ *
639
+ * @param rule - parsed directory-only .gitignore rule
640
+ * @param relativePath - candidate path relative to the rule's owning directory
641
+ * @param isDirectory - includes the final segment as a candidate only when true
642
+ * @returns true when the rule pattern matches a directory prefix or directory segment
643
+ */
376
644
  function gitIgnoreDirectoryRuleMatches(rule: GitIgnoreRule, relativePath: string, isDirectory: boolean): boolean {
377
645
  if (isPathScopedGitIgnoreRule(rule)) {
378
646
  return gitIgnorePathCandidates(relativePath, isDirectory, false).some((candidate) => gitIgnoreGlobMatches(rule.pattern, candidate));
@@ -382,15 +650,26 @@ function gitIgnoreDirectoryRuleMatches(rule: GitIgnoreRule, relativePath: string
382
650
  return directorySegments.some((segment) => gitIgnoreGlobMatches(rule.pattern, segment));
383
651
  }
384
652
 
385
- // A rule is "path scoped" when it was anchored (leading `/`) or contained a `/` - both signal that
386
- // the pattern should be matched against multi-segment sub-paths rather than individual names.
653
+ /**
654
+ * Reports whether rule has a leading slash or an internal slash, so its pattern is tested against prefixes from its owning directory.
655
+ * A prefix can be a single component, such as the candidate for an anchored pattern with one name.
656
+ *
657
+ * @param rule - parsed .gitignore rule to inspect
658
+ * @returns true when the rule is anchored or contains an internal slash
659
+ */
387
660
  function isPathScopedGitIgnoreRule(rule: GitIgnoreRule): boolean {
388
661
  return rule.isAnchored || rule.hasSlash;
389
662
  }
390
663
 
391
- // Enumerates progressively longer prefixes of `relativePath` so a single-segment pattern can match
392
- // at any nesting depth. `shouldIncludeFilePath` controls whether the leaf segment is part of the prefix set
393
- // - directory-only rules omit it because `dir/` must not match a file called `dir`.
664
+ /**
665
+ * Builds successive prefixes of relativePath so a matching ancestor can exclude descendants.
666
+ * Excluding the leaf of a single-component file path yields an empty list because there is no ancestor prefix to test.
667
+ *
668
+ * @param relativePath - slash-separated path relative to the rule's owning directory
669
+ * @param isDirectory - includes the leaf prefix when true
670
+ * @param shouldIncludeFilePath - decides whether to include the leaf when isDirectory is false
671
+ * @returns ordered path prefixes from shallowest ancestor to the permitted leaf
672
+ */
394
673
  function gitIgnorePathCandidates(relativePath: string, isDirectory: boolean, shouldIncludeFilePath: boolean): string[] {
395
674
  const segments = relativePath.split("/");
396
675
  const limit = isDirectory || shouldIncludeFilePath ? segments.length : segments.length - 1;
@@ -401,15 +680,24 @@ function gitIgnorePathCandidates(relativePath: string, isDirectory: boolean, sho
401
680
  return candidates;
402
681
  }
403
682
 
404
- // Compiles the pattern on demand. Compilation is cheap relative to the surrounding walk so caching
405
- // across calls is not worth the cache-invalidation footgun.
683
+ /**
684
+ * Reports whether candidatePath matches the complete gitignore pattern.
685
+ *
686
+ * @param pattern - normalized gitignore glob pattern
687
+ * @param candidatePath - path prefix or segment tested against the compiled pattern
688
+ * @returns true when the entire candidatePath matches the pattern
689
+ */
406
690
  function gitIgnoreGlobMatches(pattern: string, candidatePath: string): boolean {
407
691
  return gitIgnoreGlobRegex(pattern).test(candidatePath);
408
692
  }
409
693
 
410
- // Translates a git glob into a JS RegExp. `**`, `*`, and `?` get their git-flavoured semantics:
411
- // `*` matches a single segment (`[^/]*`), `**` can cross segment boundaries, and `?` matches one
412
- // non-slash character.
694
+ /**
695
+ * Translates a git glob pattern into a JS RegExp with Git wildcard semantics.
696
+ * Single stars stay within a segment, supported double-star forms cross segments, and question marks match one non-slash character.
697
+ *
698
+ * @param pattern - normalized gitignore glob pattern
699
+ * @returns anchored regular expression matching complete candidate strings
700
+ */
413
701
  function gitIgnoreGlobRegex(pattern: string): RegExp {
414
702
  let source = "^";
415
703
  for (let index = 0; index < pattern.length; index += 1) {
@@ -420,8 +708,14 @@ function gitIgnoreGlobRegex(pattern: string): RegExp {
420
708
  return new RegExp(`${source}$`);
421
709
  }
422
710
 
423
- // One pattern character → one regex fragment. `*` dispatches to the star helper because `**` and
424
- // `**/ ` need special handling; everything else falls through to literal escape via `escapeRegex`.
711
+ /**
712
+ * Converts the token at index in pattern into a regex fragment, handling stars, wildcards, classes, and escapes.
713
+ * An unparsed class opener or trailing backslash is kept as a literal.
714
+ *
715
+ * @param pattern - normalized gitignore glob pattern
716
+ * @param index - zero-based cursor position in pattern
717
+ * @returns regex source fragment and the number of extra characters consumed past index
718
+ */
425
719
  function gitIgnoreGlobFragment(pattern: string, index: number): { source: string; skip: number } {
426
720
  const character = pattern[index] ?? "";
427
721
  if (character === "*") {
@@ -439,9 +733,14 @@ function gitIgnoreGlobFragment(pattern: string, index: number): { source: string
439
733
  return { source: escapeRegex(character), skip: 0 };
440
734
  }
441
735
 
442
- // Three star modes from the git spec: single `*` is segment-local, `**/` matches zero or more
443
- // segments, and trailing `**` matches anything. The `skip` return lets the caller advance past the
444
- // extra characters consumed.
736
+ /**
737
+ * Converts the star at index in pattern to regex source according to Git single-star and double-star rules.
738
+ * Leading or slash-delimited star pairs followed by a slash consume zero or more directories; trailing star pairs after a slash cross directories.
739
+ *
740
+ * @param pattern - normalized gitignore glob pattern
741
+ * @param index - index of the leading asterisk in pattern
742
+ * @returns regex source fragment and extra pattern character count consumed
743
+ */
445
744
  function gitIgnoreStarFragment(pattern: string, index: number): { source: string; skip: number } {
446
745
  const next = pattern[index + 1];
447
746
  const afterNext = pattern[index + 2];
@@ -457,8 +756,13 @@ function gitIgnoreStarFragment(pattern: string, index: number): { source: string
457
756
  return { source: "[^/]*", skip: 1 };
458
757
  }
459
758
 
460
- // Converts `[abc]`, `[!abc]`, and escaped class characters into regex class syntax. Split into
461
- // header/body helpers because git classes have positional exceptions that are easier to audit separately.
759
+ /**
760
+ * Converts the character class starting at index in pattern to regex source and an extra-character skip count.
761
+ *
762
+ * @param pattern - normalized gitignore glob pattern
763
+ * @param index - index of the opening bracket in pattern
764
+ * @returns regex fragment and skip count, or undefined for an unterminated or empty class so the caller matches `[` literally
765
+ */
462
766
  function gitIgnoreCharacterClassFragment(pattern: string, index: number): { source: string; skip: number } | undefined {
463
767
  const parsed = parseGitIgnoreCharacterClass(pattern, index);
464
768
  if (!parsed) {
@@ -474,8 +778,13 @@ interface GitIgnoreCharacterClass {
474
778
  skip: number;
475
779
  }
476
780
 
477
- // Walks a character class until the first valid closing `]`. The leading `]` exception is handled
478
- // before the loop because git treats `[]a]` as a class containing `]` and `a`.
781
+ /**
782
+ * Parses a character class beginning at index in pattern, including a literal `]` allowed first after optional negation.
783
+ *
784
+ * @param pattern - normalized gitignore glob pattern
785
+ * @param index - index of the opening bracket in pattern
786
+ * @returns regex body, negation flag, and extra-character skip count, or undefined when no valid closing bracket is found
787
+ */
479
788
  function parseGitIgnoreCharacterClass(pattern: string, index: number): GitIgnoreCharacterClass | undefined {
480
789
  const header = gitIgnoreCharacterClassHeader(pattern, index);
481
790
  let cursor = header.cursor;
@@ -492,7 +801,13 @@ function parseGitIgnoreCharacterClass(pattern: string, index: number): GitIgnore
492
801
  return undefined;
493
802
  }
494
803
 
495
- // Reads negation (`!`/`^`) and the special literal `]` when it appears first in the class body.
804
+ /**
805
+ * Parses optional negation (`!` or `^`) and an initial literal `]` after the opening bracket at index in pattern.
806
+ *
807
+ * @param pattern - normalized gitignore glob pattern
808
+ * @param index - index of the opening bracket in pattern
809
+ * @returns next body cursor, initial body text (empty unless `]` was consumed), and negation flag
810
+ */
496
811
  function gitIgnoreCharacterClassHeader(pattern: string, index: number): { cursor: number; body: string; isNegated: boolean } {
497
812
  let cursor = index + 1;
498
813
  const isNegated = pattern[cursor] === "!" || pattern[cursor] === "^";
@@ -505,8 +820,13 @@ function gitIgnoreCharacterClassHeader(pattern: string, index: number): { cursor
505
820
  return { cursor, body: "", isNegated };
506
821
  }
507
822
 
508
- // Returns the regex-ready body fragment for one class character, consuming an escaped literal pair
509
- // when gitignore used a backslash.
823
+ /**
824
+ * Builds the regex-ready body fragment for one class character, consuming an escaped literal pair when gitignore used a backslash.
825
+ *
826
+ * @param pattern - normalized gitignore glob pattern
827
+ * @param cursor - index of the current character inside the character class
828
+ * @returns escaped class character fragment and extra character skip count (1 for a backslash pair, 0 otherwise)
829
+ */
510
830
  function gitIgnoreClassBodyFragment(pattern: string, cursor: number): { source: string; skip: number } {
511
831
  if (pattern[cursor] === "\\" && pattern[cursor + 1]) {
512
832
  return { source: escapeRegexClassCharacter(pattern[cursor + 1] ?? ""), skip: 1 };
@@ -514,14 +834,24 @@ function gitIgnoreClassBodyFragment(pattern: string, cursor: number): { source:
514
834
  return { source: escapeRegexClassCharacter(pattern[cursor] ?? ""), skip: 0 };
515
835
  }
516
836
 
517
- // Escapes only characters with special meaning inside a regex character class. Escaping `-` would
518
- // change valid git ranges like `[a-z]`, so the set is intentionally narrower than normal regex escaping.
837
+ /**
838
+ * Escapes only characters with special meaning inside a regex character class, preserving hyphens so valid git ranges like `[a-z]` stay intact.
839
+ *
840
+ * @param character - single character to place inside a JavaScript RegExp character class
841
+ * @returns escaped character safe for regex character-class interpolation without altering range hyphens
842
+ */
519
843
  function escapeRegexClassCharacter(character: string): string {
520
844
  return character.replace(/[\\\]^]/g, "\\$&");
521
845
  }
522
846
 
523
- // Strips the basePath prefix so a rule from `subdir/.gitignore` is matched against paths relative
524
- // to `subdir`. Returns undefined when `display` is outside the base - those rules cannot apply.
847
+ /**
848
+ * Rebases display relative to basePath for matching rules owned by that directory.
849
+ * An empty basePath means the project root; the base itself yields an empty string and is not matched by the caller.
850
+ *
851
+ * @param basePath - project-relative owning directory of a .gitignore rule, or empty string for the root
852
+ * @param display - candidate project-relative display path
853
+ * @returns path relative to basePath, empty string for the base itself, or undefined when outside the base
854
+ */
525
855
  function pathRelativeToBase(basePath: string, display: string): string | undefined {
526
856
  if (basePath.length === 0) {
527
857
  return display === "." ? "" : display;
@@ -532,15 +862,27 @@ function pathRelativeToBase(basePath: string, display: string): string | undefin
532
862
  return display.startsWith(`${basePath}/`) ? display.slice(basePath.length + 1) : undefined;
533
863
  }
534
864
 
535
- // Guards against `..`-traversal and absolute-path inputs that point outside the requested root.
536
- // Required so a malformed CLI path cannot drag the .gitignore walker into the user's home directory.
865
+ /**
866
+ * Reports whether path is lexically equal to projectRoot or lies below it.
867
+ * The ignore walker uses this check to restrict project .gitignore lookup to paths within the requested root.
868
+ *
869
+ * @param projectRoot - root directory defining the project boundary
870
+ * @param path - filesystem path tested for lexical containment
871
+ * @returns true when path equals projectRoot or is a descendant of it
872
+ */
537
873
  function isInsideProject(projectRoot: string, path: string): boolean {
538
874
  const relativePath = relative(projectRoot, path).replaceAll("\\", "/");
539
875
  return relativePath === "" || (!relativePath.startsWith("../") && relativePath !== ".." && !isAbsolute(relativePath));
540
876
  }
541
877
 
542
- // User config ignore patterns. Simpler than gitignore: literal, `prefix/**`, glob with `*` / `**`,
543
- // or plain prefix. No negation - config ignores are additive on top of gitignore.
878
+ /**
879
+ * Reports whether the candidate path matches a user config ignore pattern; these exclusions are additive and have no negation.
880
+ * Supports literal directory prefixes, star globs, and patterns ending in slash and two stars for a literal prefix and its descendants.
881
+ *
882
+ * @param pattern - user config ignore pattern from config.ignoredPaths
883
+ * @param path - candidate display path to test
884
+ * @returns true when the candidate path matches the config ignore pattern
885
+ */
544
886
  function pathMatches(pattern: string, path: string): boolean {
545
887
  if (pattern === path) {
546
888
  return true;
@@ -557,8 +899,13 @@ function pathMatches(pattern: string, path: string): boolean {
557
899
  return path === prefix || path.startsWith(`${prefix}/`);
558
900
  }
559
901
 
560
- // Same absolute path can be reached through multiple CLI inputs. First-seen wins because that
561
- // preserves the deterministic sort imposed by `discoverSources` and keeps fingerprint stability.
902
+ /**
903
+ * Deduplicates files by absolute path because multiple CLI inputs can reach the same file.
904
+ * Keeps the first entry for each path in files to preserve the deterministic sort imposed by discoverSources.
905
+ *
906
+ * @param files - sorted list of discovered source file records
907
+ * @returns new array containing the first record for each unique absolutePath
908
+ */
562
909
  function uniqueFiles(files: SourceFile[]): SourceFile[] {
563
910
  const seen = new Set<string>();
564
911
  return files.filter((file) => {
@@ -570,19 +917,45 @@ function uniqueFiles(files: SourceFile[]): SourceFile[] {
570
917
  });
571
918
  }
572
919
 
573
- // Anchors a relative CLI argument against the project root; absolute paths pass through unchanged.
920
+ /**
921
+ * Anchors a relative CLI argument against the project root; absolute paths pass through unchanged.
922
+ *
923
+ * @param projectRoot - base directory used to resolve relative paths
924
+ * @param path - CLI path argument, either relative or absolute
925
+ * @returns resolved absolute path
926
+ */
574
927
  export function absolutize(projectRoot: string, path: string): string {
575
928
  return isAbsolute(path) ? path : join(projectRoot, path);
576
929
  }
577
930
 
578
- // Project-relative form with forward slashes - the report contract uses POSIX-style display paths
579
- // on every platform. "" collapses to "." so the root has a stable label in findings.
580
- export function displayPath(projectRoot: string, path: string): string {
581
- const relativePath = relative(projectRoot, path).replaceAll("\\", "/");
582
- return relativePath === "" ? "." : relativePath;
583
- }
584
-
585
- // Escapes the standard regex metacharacters so untrusted patterns can be embedded literally.
931
+ /**
932
+ * Formats a scanned path for findings, diagnostics, and baselines.
933
+ * Paths inside the run root stay relative; outside paths are absolute so editor and CI links remain usable.
934
+ *
935
+ * @param projectRoot - run root that anchors relative report paths
936
+ * @param inputPath - scanned path; an empty path addresses the run root itself
937
+ * @returns POSIX report path; a single dot means the input is the run root
938
+ */
939
+ export function displayPath(projectRoot: string, inputPath: string): string {
940
+ const absoluteInputPath = isAbsolute(inputPath) ? inputPath : join(projectRoot, inputPath);
941
+ const projectRelativePath = relative(projectRoot, absoluteInputPath).replaceAll("\\", "/");
942
+ // The run root itself needs a non-empty label in reports.
943
+ if (projectRelativePath === "") {
944
+ return ".";
945
+ }
946
+ // Give paths outside the run root an absolute label so report consumers can resolve them without the original run root.
947
+ if (projectRelativePath === ".." || projectRelativePath.startsWith("../") || isAbsolute(projectRelativePath)) {
948
+ return absoluteInputPath.replaceAll("\\", "/");
949
+ }
950
+ return projectRelativePath;
951
+ }
952
+
953
+ /**
954
+ * Escapes the standard regex metacharacters so untrusted patterns can be embedded literally.
955
+ *
956
+ * @param rawText - raw literal text to embed in a regular expression
957
+ * @returns text with regex metacharacters backslash-escaped
958
+ */
586
959
  function escapeRegex(rawText: string): string {
587
960
  return rawText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
588
961
  }