@blundergoat/gruff-ts 0.5.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 +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  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 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  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 +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  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 +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  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 +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -1,4 +1,7 @@
1
- // Package and tsconfig health checks that emit deterministic project-config findings from JSON files.
1
+ // Checks `package.json` and `tsconfig.json` files for supply-chain, packaging, and strictness findings.
2
+ //
3
+ // Flags remote curl/wget install scripts, URL or git dependencies, overly broad runtime ranges, broken bin targets,
4
+ // and disabled TypeScript strict flags while honoring `extends` inheritance and JSONC comments.
2
5
  import { existsSync, statSync } from "node:fs";
3
6
  import { basename, dirname as dirnamePath, isAbsolute, join } from "node:path";
4
7
  import { platform } from "node:process";
@@ -14,10 +17,14 @@ interface ConfigSourceFile {
14
17
  displayPath: string;
15
18
  }
16
19
 
17
- /*
18
- * Dispatcher for package.json / tsconfig.json health rules. Only these two filenames are inspected;
19
- * any other JSON files in the project are out of scope to keep the rule surface bounded. The
20
- * stable, deterministic Finding[] emission order is what makes baselines reproducible.
20
+ /**
21
+ * Run configuration checks for package.json, tsconfig.json, and named variants such as tsconfig.build.json.
22
+ * Keep finding order stable so that baseline reports are reproducible.
23
+ *
24
+ * @param file - Configuration file whose basename selects the checks and whose path identifies their findings.
25
+ * @param source - Original JSON text to parse and use when locating findings.
26
+ * @param findings - Collector for package or TypeScript configuration findings.
27
+ * @returns Nothing. Appends findings only for supported filenames whose contents parse as a JSON object.
21
28
  */
22
29
  function analyseProjectConfigRules(file: ConfigSourceFile, source: string, findings: Finding[]): void {
23
30
  const name = basename(file.displayPath);
@@ -35,24 +42,40 @@ function analyseProjectConfigRules(file: ConfigSourceFile, source: string, findi
35
42
  }
36
43
  }
37
44
 
38
- // Accepts the default tsconfig plus named variants such as `tsconfig.base.json`. This keeps
39
- // workspace/shared config files inside the same strictness rule surface as the root config.
45
+ /**
46
+ * Reports whether a filename is `tsconfig.json` or a named variant such as `tsconfig.base.json`.
47
+ * Keeps shared and workspace configs subject to the same strictness checks as the root config.
48
+ *
49
+ * @param name - Config basename to match against supported tsconfig naming patterns.
50
+ * @returns True when `name` is `tsconfig.json` or `tsconfig.<variant>.json`; false otherwise.
51
+ */
40
52
  function isTsconfigFileName(name: string): boolean {
41
53
  return name === "tsconfig.json" || /^tsconfig\.[^.]+(?:\.[^.]+)*\.json$/.test(name);
42
54
  }
43
55
 
44
- // Three sub-pillars in fixed order (scripts → dependencies → bins). This deterministic order is
45
- // the stable emission contract that lets fingerprints survive cosmetic reorderings of package.json.
56
+ /**
57
+ * Runs script, dependency, and bin checks in that order to preserve the stable order of finding groups.
58
+ *
59
+ * @param file - Package manifest file whose path identifies findings and resolves relative bin targets.
60
+ * @param source - Original manifest text used to locate script, dependency, and bin declarations.
61
+ * @param pkg - Parsed package object supplying `scripts`, dependency sections, and `bin` fields to check.
62
+ * @param findings - Collector to which any reported package findings are appended.
63
+ * @returns Nothing. Appends any reported findings to the supplied list.
64
+ */
46
65
  function analysePackageJson(file: ConfigSourceFile, source: string, pkg: Record<string, unknown>, findings: Finding[]): void {
47
66
  analysePackageScripts(file, source, objectValue(pkg.scripts), findings);
48
67
  analysePackageDependencies(file, source, pkg, findings);
49
68
  analysePackageBins(file, source, pkg, findings);
50
69
  }
51
70
 
52
- /*
53
- * Iterates `package.json#scripts` in declaration order - the stable Finding[] emission contract
54
- * relies on this. Each script is funnelled through both the remote-installer and lifecycle-script
55
- * checks because one script can match both.
71
+ /**
72
+ * Checks script strings for remote shell execution in stable object entry order.
73
+ *
74
+ * @param file - package manifest whose path is reported
75
+ * @param source - manifest text used to locate each script
76
+ * @param scripts - parsed script entries, with missing sections and nonstring commands skipped
77
+ * @param findings - destination for remote execution findings
78
+ * @returns Nothing. Appends findings for matching commands to the supplied list.
56
79
  */
57
80
  function analysePackageScripts(file: ConfigSourceFile, source: string, scripts: Record<string, unknown> | undefined, findings: Finding[]): void {
58
81
  if (!scripts) {
@@ -63,14 +86,19 @@ function analysePackageScripts(file: ConfigSourceFile, source: string, scripts:
63
86
  continue;
64
87
  }
65
88
  pushRemoteInstallScriptFinding(file, source, scriptName, scriptCommand, findings);
66
- pushLifecycleScriptFinding(file, source, scriptName, scriptCommand, findings);
67
89
  }
68
90
  }
69
91
 
70
- /*
71
- * Reports `security.remote-install-script` for `curl|wget … | sh` patterns. Severity is `error`
72
- * because remote shell execution at install time is a contract red flag in the modern supply-chain
73
- * landscape.
92
+ /**
93
+ * Flags curl or wget with an HTTP(S) URL piped to sh, bash or zsh, optionally via sudo, under the security.remote-install-script contract.
94
+ * The finding is an error because running a matching script can execute code fetched from a remote server.
95
+ *
96
+ * @param file - package manifest whose path is reported
97
+ * @param source - manifest text used to locate the named script
98
+ * @param scriptName - manifest key to report for a matching command
99
+ * @param scriptCommand - script text inspected for remote shell execution
100
+ * @param findings - destination for the error finding
101
+ * @returns Nothing. Appends an error only when the script matches.
74
102
  */
75
103
  function pushRemoteInstallScriptFinding(file: ConfigSourceFile, source: string, scriptName: string, scriptCommand: string, findings: Finding[]): void {
76
104
  if (!isRemoteInstallScript(scriptCommand)) {
@@ -92,35 +120,15 @@ function pushRemoteInstallScriptFinding(file: ConfigSourceFile, source: string,
92
120
  );
93
121
  }
94
122
 
95
- /*
96
- * Reports the stable `security.risky-lifecycle-script` finding for install-time and side-effectful
97
- * publish hooks. Validation-only publish gates stay quiet, but install/prepare hooks stay visible
98
- * because they run in broader contexts than an explicit release check.
99
- */
100
- function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scriptName: string, scriptCommand: string, findings: Finding[]): void {
101
- if (!isLifecycleScript(scriptName) || isValidationOnlyLifecycleCommand(scriptName, scriptCommand)) {
102
- return;
103
- }
104
- findings.push(
105
- makeFinding({
106
- ruleId: "security.risky-lifecycle-script",
107
- message: `Package lifecycle script \`${scriptName}\` runs automatically during install or publish flows.`,
108
- filePath: file.displayPath,
109
- line: jsonKeyLine(source, scriptName),
110
- severity: "warning",
111
- pillar: "security",
112
- confidence: "medium",
113
- symbol: scriptName,
114
- remediation: "Review whether lifecycle execution is required; keep install/publish side effects behind explicit commands when possible.",
115
- metadata: { scriptName },
116
- }),
117
- );
118
- }
119
-
120
- /*
121
- * Walks every dependency section in a stable, deterministic order. The `isRuntimeDependency` flag
122
- * separates devDependencies from the rest because the broad-version rule should only fire for
123
- * runtime drift.
123
+ /**
124
+ * Checks string entries in dependencies, optionalDependencies, peerDependencies and devDependencies in that stable order.
125
+ * The broad-version check applies only to dependencies and optionalDependencies because those are the runtime sections for this rule.
126
+ *
127
+ * @param file - package manifest whose path is reported
128
+ * @param source - manifest text used to locate dependency entries
129
+ * @param pkg - parsed manifest supplying the dependency sections, with missing or non-object sections skipped
130
+ * @param findings - destination for findings from the dependency checks
131
+ * @returns Nothing. Appends findings from the checks on eligible entries.
124
132
  */
125
133
  function analysePackageDependencies(file: ConfigSourceFile, source: string, pkg: Record<string, unknown>, findings: Finding[]): void {
126
134
  for (const section of ["dependencies", "optionalDependencies", "peerDependencies", "devDependencies"]) {
@@ -137,7 +145,18 @@ function analysePackageDependencies(file: ConfigSourceFile, source: string, pkg:
137
145
  }
138
146
  }
139
147
 
140
- // Runs both per-dependency checks for one entry; the emission order is a stable contract.
148
+ /**
149
+ * Checks one dependency for a URL spec, then checks for a broad spec when the runtime flag is set, to preserve stable finding order.
150
+ *
151
+ * @param file - Package manifest file whose display path is recorded on any emitted findings.
152
+ * @param source - Manifest text searched by section, name, and version for URL findings and by name for broad versions.
153
+ * @param section - Dependency section name where the entry was declared.
154
+ * @param packageName - Declared dependency name used as the finding symbol and for line lookup.
155
+ * @param versionSpec - Declared dependency version or target specifier to inspect.
156
+ * @param isRuntimeDependency - Whether the entry belongs to a runtime dependency section (`dependencies` or `optionalDependencies`).
157
+ * @param findings - Collector for matching URL-dependency or broad-runtime-version findings.
158
+ * @returns Nothing. Appends any matching findings to the supplied list.
159
+ */
141
160
  function analysePackageDependency(
142
161
  file: ConfigSourceFile,
143
162
  source: string,
@@ -151,8 +170,18 @@ function analysePackageDependency(
151
170
  pushBroadRuntimeDependencyFinding(file, source, section, packageName, versionSpec, isRuntimeDependency, findings);
152
171
  }
153
172
 
154
- // Flags URL/git/file version specs, which bypass registry auditing.
155
- // Stable `security.url-dependency` contract: reports exactly one finding per offending spec.
173
+ /**
174
+ * Appends one stable `security.url-dependency` finding for recognized URL, Git, or file specs because they bypass normal registry auditing.
175
+ *
176
+ * @param file - Package manifest file whose display path is reported on the finding.
177
+ * @param source - Manifest text used to locate the entry by section, name, and version, with a name-only fallback.
178
+ * @param section - Dependency section name recorded in the message and metadata.
179
+ * @param packageName - Declared dependency name recorded as the finding symbol and in metadata.
180
+ * @param versionSpec - Declared specifier checked against recognized URL, Git, and local file formats.
181
+ * @param isRuntimeDependency - Runtime dependency flag recorded in the finding metadata.
182
+ * @param findings - Collector that receives the finding when `versionSpec` matches.
183
+ * @returns Nothing. Leaves `findings` unchanged for non-URL version specs.
184
+ */
156
185
  function pushUrlDependencyFinding(
157
186
  file: ConfigSourceFile,
158
187
  source: string,
@@ -170,7 +199,7 @@ function pushUrlDependencyFinding(
170
199
  ruleId: "security.url-dependency",
171
200
  message: `Dependency \`${packageName}\` in \`${section}\` installs from a URL, git, or local file spec.`,
172
201
  filePath: file.displayPath,
173
- line: jsonKeyLine(source, packageName),
202
+ line: dependencyEntryLine(source, section, packageName, versionSpec),
174
203
  severity: "warning",
175
204
  pillar: "security",
176
205
  confidence: "medium",
@@ -181,8 +210,18 @@ function pushUrlDependencyFinding(
181
210
  );
182
211
  }
183
212
 
184
- // Flags broad runtime version ranges (`*`, `latest`, bare majors) under the stable
185
- // `waste.broad-runtime-version` contract: reports runtime sections only; dev sections must stay exempt.
213
+ /**
214
+ * Under the stable `waste.broad-runtime-version` contract, flags broad specs such as `*`, `x`, or `latest` for runtime entries.
215
+ *
216
+ * @param file - Package manifest file whose display path is reported on the finding.
217
+ * @param source - Manifest text searched by section, name, and version, with a name-only fallback.
218
+ * @param section - Dependency section name recorded in finding metadata and used for line lookup.
219
+ * @param packageName - Declared dependency name used as the finding symbol and in metadata.
220
+ * @param versionSpec - Declared specifier tested for overly broad version ranges and recorded in metadata.
221
+ * @param isRuntimeDependency - Whether the dependency belongs to a runtime section; non-runtime entries are skipped.
222
+ * @param findings - Collector that receives the advisory finding when both checks qualify.
223
+ * @returns Nothing. Appends to `findings` only when `isRuntimeDependency` and the broad-version check both qualify the entry.
224
+ */
186
225
  function pushBroadRuntimeDependencyFinding(
187
226
  file: ConfigSourceFile,
188
227
  source: string,
@@ -200,7 +239,7 @@ function pushBroadRuntimeDependencyFinding(
200
239
  ruleId: "waste.broad-runtime-version",
201
240
  message: `Runtime dependency \`${packageName}\` uses overly broad version spec \`${versionSpec}\`.`,
202
241
  filePath: file.displayPath,
203
- line: jsonKeyLine(source, packageName),
242
+ line: dependencyEntryLine(source, section, packageName, versionSpec),
204
243
  severity: "advisory",
205
244
  pillar: "maintainability",
206
245
  confidence: "medium",
@@ -211,26 +250,38 @@ function pushBroadRuntimeDependencyFinding(
211
250
  );
212
251
  }
213
252
 
214
- /*
215
- * Expands `bin` into (command, target) pairs (handling both string and object forms), then checks
216
- * each one in a deterministic, stable order. Returns nothing when `bin` is absent - the rule does
217
- * not require packages to ship CLIs.
253
+ /**
254
+ * Checks string bin declarations and string targets in bin maps in stable entry order. Missing declarations and nonstring targets are skipped.
255
+ *
256
+ * @param file - package manifest used to resolve relative bin targets
257
+ * @param source - manifest text used to locate bin declarations
258
+ * @param pkg - parsed manifest supplying the bin declaration, scripts, and the name for a string bin, which defaults to bin
259
+ * @param findings - destination for findings raised by the target checks
260
+ * @returns Nothing. Appends any findings from checking the declared targets.
218
261
  */
219
262
  function analysePackageBins(file: ConfigSourceFile, source: string, pkg: Record<string, unknown>, findings: Finding[]): void {
263
+ const hasBuildScript = hasPackageBuildScript(pkg);
220
264
  for (const [command, target] of packageBinEntries(pkg)) {
221
- analysePackageBin(file, source, command, target, findings);
265
+ analysePackageBin(file, source, command, target, hasBuildScript, findings);
222
266
  }
223
267
  }
224
268
 
225
- /*
226
- * Reads the bin target from disk. The stable mapping: missing → `package-bin-missing`;
227
- * non-executable → `package-bin-not-executable`. Executable files pass silently so the rule cannot
228
- * fail a healthy install pipeline.
269
+ /**
270
+ * Checks a declared CLI target on disk. The stable rules distinguish missing targets from existing targets that are not executable files.
271
+ * Windows skips the executable-file check because POSIX execute bits do not apply there.
272
+ *
273
+ * @param file - package manifest used to resolve and report the target
274
+ * @param source - manifest text used to locate the bin declaration
275
+ * @param command - declared CLI name to report if the check fails
276
+ * @param target - declared path checked as given when absolute and relative to the manifest directory otherwise
277
+ * @param hasBuildScript - true when `package.json` defines a non-empty `scripts.build` command
278
+ * @param findings - destination for any finding raised by this check
279
+ * @returns Nothing. Appends a finding for a missing target or, outside Windows, a target that is not an executable file.
229
280
  */
230
- function analysePackageBin(file: ConfigSourceFile, source: string, command: string, target: string, findings: Finding[]): void {
281
+ function analysePackageBin(file: ConfigSourceFile, source: string, command: string, target: string, hasBuildScript: boolean, findings: Finding[]): void {
231
282
  const absolute = packageBinPath(file, target);
232
283
  if (!existsSync(absolute)) {
233
- pushMissingPackageBinFinding(file, source, command, target, findings);
284
+ pushMissingPackageBinFinding(file, source, command, target, hasBuildScript && isBuildOutputBinTarget(target), findings);
234
285
  return;
235
286
  }
236
287
  const stats = statSync(absolute);
@@ -242,34 +293,80 @@ function analysePackageBin(file: ConfigSourceFile, source: string, command: stri
242
293
  }
243
294
  }
244
295
 
245
- // Bin targets are resolved against the directory of the owning package.json, not the project root.
246
- // Required because workspace packages can live in subdirectories and have their own bins.
296
+ /**
297
+ * Reports whether `package.json` declares a non-empty `scripts.build` entry, signaling that compiled bin artifacts may not exist before building.
298
+ *
299
+ * @param pkg - parsed `package.json` manifest object
300
+ * @returns True when `pkg.scripts.build` is a non-empty string; false otherwise.
301
+ */
302
+ function hasPackageBuildScript(pkg: Record<string, unknown>): boolean {
303
+ const scripts = objectValue(pkg.scripts);
304
+ return typeof scripts?.build === "string" && scripts.build.trim().length > 0;
305
+ }
306
+
307
+ /**
308
+ * Reports whether a relative package bin target points into a conventional compiled output directory (`dist/`, `build/`, or `lib/`).
309
+ *
310
+ * @param target - bin target string declared in `package.json`
311
+ * @returns True when the normalized relative path begins with `dist/`, `build/`, or `lib/`; false otherwise.
312
+ */
313
+ function isBuildOutputBinTarget(target: string): boolean {
314
+ const normalized = target.replaceAll("\\", "/").replace(/^\.\//, "");
315
+ return /^(?:dist|build|lib)\//.test(normalized);
316
+ }
317
+
318
+ /**
319
+ * Resolves a declared bin target against the owning `package.json` directory because workspace packages can live in subdirectories.
320
+ *
321
+ * @param file - Package manifest file whose `absolutePath` directory anchors relative bin targets.
322
+ * @param target - Declared bin path from `package.json`.
323
+ * @returns `target` unchanged when already absolute, or joined with the owning manifest directory otherwise.
324
+ */
247
325
  function packageBinPath(file: ConfigSourceFile, target: string): string {
248
326
  return isAbsolute(target) ? target : join(dirnamePath(file.absolutePath), target);
249
327
  }
250
328
 
251
- /*
252
- * Reports the `design.package-bin-missing` finding for a declared bin whose file does not exist
253
- * on disk - emitted with stable command + target metadata that other tooling can key off.
329
+ /**
330
+ * Records design.package-bin-missing for a declared CLI whose target is missing, with stable command and target metadata.
331
+ * Downgrades unbuilt build-output targets to advisory so fresh unbuilt checkouts do not draw a hard warning.
332
+ *
333
+ * @param file - package manifest whose path is reported
334
+ * @param source - manifest text used to locate the bin declaration
335
+ * @param command - declared CLI name recorded in the finding
336
+ * @param target - missing path as declared in the manifest
337
+ * @param isUnbuiltOutput - true when the missing path sits under `dist/`, `build/`, or `lib/` in a package with a `build` script
338
+ * @param findings - destination for the finding
339
+ * @returns Nothing. Appends the finding to the supplied list.
254
340
  */
255
- function pushMissingPackageBinFinding(file: ConfigSourceFile, source: string, command: string, target: string, findings: Finding[]): void {
341
+ function pushMissingPackageBinFinding(file: ConfigSourceFile, source: string, command: string, target: string, isUnbuiltOutput: boolean, findings: Finding[]): void {
256
342
  findings.push(
257
343
  packageBinFinding({
258
344
  file,
259
345
  source,
260
346
  ruleId: "design.package-bin-missing",
261
- message: `Package bin \`${command}\` points to missing file \`${target}\`.`,
347
+ message: isUnbuiltOutput
348
+ ? `Package bin \`${command}\` points to unbuilt output \`${target}\` (run the package build script first).`
349
+ : `Package bin \`${command}\` points to missing file \`${target}\`.`,
262
350
  command,
263
351
  target,
264
- remediation: "Update the bin path or add the executable file.",
352
+ severity: isUnbuiltOutput ? "advisory" : "warning",
353
+ isUnbuiltOutput,
354
+ remediation: isUnbuiltOutput
355
+ ? "Run the package build script before verifying compiled bin targets, or update the bin path if the output path changed."
356
+ : "Update the bin path or add the executable file.",
265
357
  }),
266
358
  );
267
359
  }
268
360
 
269
- /*
270
- * Reports the stable `design.package-bin-not-executable` finding - the file exists but lacks the
271
- * execute bit. Common on Windows checkouts; the remediation message reminds maintainers to also
272
- * keep the shebang valid.
361
+ /**
362
+ * Records the stable design.package-bin-not-executable finding when the caller finds an existing target that is not an executable file.
363
+ *
364
+ * @param file - package manifest whose path is reported
365
+ * @param source - manifest text used to locate the bin declaration
366
+ * @param command - declared CLI name used in the finding
367
+ * @param target - declared bin path recorded with the command
368
+ * @param findings - destination for the finding
369
+ * @returns Nothing. Appends the finding to the supplied list.
273
370
  */
274
371
  function pushNonExecutablePackageBinFinding(file: ConfigSourceFile, source: string, command: string, target: string, findings: Finding[]): void {
275
372
  findings.push(
@@ -280,12 +377,14 @@ function pushNonExecutablePackageBinFinding(file: ConfigSourceFile, source: stri
280
377
  message: `Package bin \`${command}\` points to a file that is not executable.`,
281
378
  command,
282
379
  target,
380
+ severity: "warning",
381
+ isUnbuiltOutput: false,
283
382
  remediation: "Make the bin target executable and keep its shebang valid.",
284
383
  }),
285
384
  );
286
385
  }
287
386
 
288
- // Argument bundle for `packageBinFinding`. Grouped into a struct because the helper accepts seven
387
+ // Argument bundle for `packageBinFinding`. Grouped into a struct because the helper accepts nine
289
388
  // fields and an inline parameter list would silently break call sites on field shuffles.
290
389
  interface PackageBinFindingInput {
291
390
  file: ConfigSourceFile;
@@ -294,31 +393,42 @@ interface PackageBinFindingInput {
294
393
  message: string;
295
394
  command: string;
296
395
  target: string;
396
+ severity: "advisory" | "warning";
397
+ isUnbuiltOutput: boolean;
297
398
  remediation: string;
298
399
  }
299
400
 
300
- // Single makeFinding call site for both bin-missing and bin-not-executable. The `command` symbol
301
- // is what the fingerprint anchors on, so renaming a bin entry intentionally invalidates the baseline.
401
+ /**
402
+ * Builds the missing-bin or non-executable-bin finding described by `input`, including its package location and remediation.
403
+ * The `command` symbol contributes to the fingerprint, so renaming a bin entry changes its baseline identity.
404
+ *
405
+ * @param input - Finding inputs including manifest file, source text, rule details, bin command, target, and build status.
406
+ * @returns Constructed `design` finding anchored at the declared `command` line in `input.source`.
407
+ */
302
408
  function packageBinFinding(input: PackageBinFindingInput): Finding {
303
409
  return makeFinding({
304
410
  ruleId: input.ruleId,
305
411
  message: input.message,
306
412
  filePath: input.file.displayPath,
307
413
  line: jsonKeyLine(input.source, input.command),
308
- severity: "warning",
414
+ severity: input.severity,
309
415
  pillar: "design",
310
416
  confidence: "high",
311
417
  symbol: input.command,
312
418
  remediation: input.remediation,
313
- metadata: { command: input.command, target: input.target },
419
+ metadata: input.isUnbuiltOutput ? { command: input.command, target: input.target, unbuiltOutput: true } : { command: input.command, target: input.target },
314
420
  });
315
421
  }
316
422
 
317
- /*
318
- * Three TypeScript strictness flags whose absence is a documentation-worthy compromise: `strict`,
319
- * `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`. Reports each missing flag as its own
320
- * finding; the list is intentionally short - adding new flags here changes the rule surface and
321
- * warrants a schema discussion.
423
+ /**
424
+ * Checks the TypeScript strictness contract covered by the rule documentation.
425
+ * An extends entry can supply an omitted flag, so the check skips omissions when inheritance is declared.
426
+ *
427
+ * @param file - Config file used to name the path in each finding.
428
+ * @param source - Config text used to locate the option in each finding.
429
+ * @param tsconfigData - Parsed config used to read compilerOptions and detect extends.
430
+ * @param findings - Accumulator for the strictness findings.
431
+ * @returns Nothing. Appends one finding per checked flag that is neither true nor omitted with extends.
322
432
  */
323
433
  function analyseTsconfigJson(file: ConfigSourceFile, source: string, tsconfigData: Record<string, unknown>, findings: Finding[]): void {
324
434
  const compilerOptions = objectValue(tsconfigData.compilerOptions) ?? {};
@@ -333,8 +443,7 @@ function analyseTsconfigJson(file: ConfigSourceFile, source: string, tsconfigDat
333
443
  if (optionValue === true) {
334
444
  continue;
335
445
  }
336
- // When the tsconfig `extends` another file we can't see the resolved compilerOptions, so an
337
- // absent flag may already be `true` in the base. Only an explicit `false` is reportable.
446
+ // Skip an omitted flag with extends because the unresolved base config may already enable it.
338
447
  if (optionValue === undefined && hasExtends) {
339
448
  continue;
340
449
  }
@@ -362,8 +471,13 @@ interface TsconfigFindingInput {
362
471
  currentValue: unknown;
363
472
  }
364
473
 
365
- // Single makeFinding site for tsconfig strictness findings. `optionName` is the symbol anchor and
366
- // `currentValue` is preserved verbatim in metadata for downstream tooling - both are part of the stable contract.
474
+ /**
475
+ * Builds a strictness finding from the supplied tsconfig file, source text, rule details, and observed option value.
476
+ * The stable contract uses `optionName` as the symbol and retains `currentValue` in metadata.
477
+ *
478
+ * @param input - Finding inputs including config file, source text to locate the option key, rule details, option name, and current value.
479
+ * @returns Constructed `modernisation` finding anchored at the option key line in `input.source`.
480
+ */
367
481
  function tsconfigFinding(input: TsconfigFindingInput): Finding {
368
482
  return makeFinding({
369
483
  ruleId: input.ruleId,
@@ -379,9 +493,12 @@ function tsconfigFinding(input: TsconfigFindingInput): Finding {
379
493
  });
380
494
  }
381
495
 
382
- /*
383
- * Swallows parse errors and returns undefined as a fallback so a malformed package.json doesn't
384
- * fail the whole analysis run - the rest of the file scan continues.
496
+ /**
497
+ * Parses `source` as JSONC and returns its object root so rules skip malformed text and non-object roots.
498
+ * Parse failures stay unlogged because this rule pass only emits findings for successfully decoded objects.
499
+ *
500
+ * @param source - Raw JSON or JSONC file text to strip and parse.
501
+ * @returns Parsed root object, or `undefined` when parsing fails or the root is not a plain object.
385
502
  */
386
503
  function parseJsonObject(source: string): Record<string, unknown> | undefined {
387
504
  try {
@@ -391,59 +508,91 @@ function parseJsonObject(source: string): Record<string, unknown> | undefined {
391
508
  }
392
509
  }
393
510
 
394
- // Approximate line lookup - finds the first `"key":` occurrence. JSON allows the same key in
395
- // nested objects, but for package.json/tsconfig the top-level keys we report on are unique.
511
+ /**
512
+ * Locates the first quoted key followed by a colon in `source` for approximate finding locations.
513
+ * Nested keys and text inside comments can match; a missing match falls back to line 1.
514
+ *
515
+ * @param source - Raw JSON or JSONC text to scan.
516
+ * @param key - Unescaped property name to find before a colon.
517
+ * @returns One-based line number of the first match, or `1` when absent.
518
+ */
396
519
  function jsonKeyLine(source: string, key: string): number {
397
520
  const escapedKey = escapeRegex(key);
398
521
  return firstLine(source, new RegExp(`"${escapedKey}"\\s*:`));
399
522
  }
400
523
 
401
- // Pattern matches `curl|wget … | sh` or its inline-pipe variants. The negative lookaheads for `|`,
402
- // `;`, `&` prevent overlong matches that would span multiple shell commands.
403
- function isRemoteInstallScript(command: string): boolean {
404
- return /\b(?:curl|wget)\b[^\n|;&]*https?:\/\/[^\n|;&]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh)\b/i.test(command);
405
- }
406
-
407
- // The closed list of npm/yarn/pnpm install-time hooks. Adding entries here expands rule coverage.
408
- function isLifecycleScript(scriptName: string): boolean {
409
- return ["preinstall", "install", "postinstall", "prepare", "prepublish", "prepublishOnly"].includes(scriptName);
410
- }
411
-
412
- // Allows closed-list validation commands in publish hooks while rejecting shell composition.
413
- function isValidationOnlyLifecycleCommand(scriptName: string, command: string): boolean {
414
- if (!["prepublish", "prepublishOnly"].includes(scriptName)) {
415
- return false;
416
- }
417
- const normalizedCommand = command.trim().replace(/\s+/g, " ");
418
- if (/[;&|`$<>]/.test(normalizedCommand)) {
419
- return false;
524
+ /**
525
+ * Finds `packageName` with `versionSpec` in `source` starting from the first `section` key, matching across line breaks.
526
+ * Falls back to the first `packageName` key or line 1 when no section-scoped entry matches.
527
+ *
528
+ * @param source - Raw manifest text to search across lines.
529
+ * @param section - Dependency section key where the search begins if present.
530
+ * @param packageName - Dependency name to match alongside its version specifier.
531
+ * @param versionSpec - Dependency version or URL specifier paired with `packageName`.
532
+ * @returns One-based line number of the matched dependency entry, or the key-only fallback line.
533
+ */
534
+ function dependencyEntryLine(source: string, section: string, packageName: string, versionSpec: string): number {
535
+ const sectionMatch = new RegExp(`"${escapeRegex(section)}"\\s*:`).exec(source);
536
+ const searchStart = sectionMatch?.index ?? 0;
537
+ // Match across line breaks so a multiline `"pkg":\n "https://..."` entry in `dependencies` is not skipped for `devDependencies`.
538
+ const entry = new RegExp(`${escapeRegex(JSON.stringify(packageName))}\\s*:\\s*${escapeRegex(JSON.stringify(versionSpec))}`);
539
+ const match = entry.exec(source.slice(searchStart));
540
+ if (!match) {
541
+ return jsonKeyLine(source, packageName);
420
542
  }
421
- return VALIDATION_ONLY_LIFECYCLE_COMMANDS.has(normalizedCommand);
543
+ return source.slice(0, searchStart + match.index).split(/\r?\n/).length;
422
544
  }
423
545
 
424
- const VALIDATION_ONLY_LIFECYCLE_COMMANDS = new Set(["npm run check", "npm test", "npm run test", "npm run lint", "npm run typecheck", "npm run publish:check"]);
546
+ /**
547
+ * Reports whether `command` downloads an HTTP(S) URL via `curl` or `wget` and pipes it to `sh`, `bash`, or `zsh`, optionally via `sudo`.
548
+ * The pattern stops at shell separators or a newline before that pipe to avoid matching across commands.
549
+ *
550
+ * @param command - Package script command text to inspect.
551
+ * @returns True when `command` matches the remote install pipeline pattern; false otherwise.
552
+ */
553
+ function isRemoteInstallScript(command: string): boolean {
554
+ return /\b(?:curl|wget)\b[^\n|;&]*https?:\/\/[^\n|;&]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh)\b/i.test(command);
555
+ }
425
556
 
426
- // Recognises non-registry installs: full URLs, git+ssh, file:, and npm-hosting shortcuts.
427
- // These specs cannot be reproducibly locked the way registry versions can.
557
+ /**
558
+ * Reports whether `versionSpec` starts with a recognized URL, Git, or local file prefix or matches a bare repository shortcut.
559
+ *
560
+ * @param versionSpec - Dependency specifier value from `package.json`.
561
+ * @returns True when `versionSpec` resolves outside the standard package registry; false otherwise.
562
+ */
428
563
  function isUrlDependency(versionSpec: string): boolean {
429
564
  return /^(?:https?:\/\/|git(?:\+https?|\+ssh)?:\/\/|ssh:\/\/|github:|gitlab:|bitbucket:|file:|git@[^:]+:[^/]+\/|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$)/i.test(versionSpec);
430
565
  }
431
566
 
432
- // Catches `*`, `x`, `latest`, unbounded `>=` ranges, and OR-joined ranges. All let dependency
433
- // resolution drift arbitrarily - lockfile or not, the declared intent is "anything goes".
567
+ /**
568
+ * Reports whether `versionSpec` matches the broad-version heuristic after trimming and case folding.
569
+ * Matches bare `*`, `x`, or `latest`, any `||`, or a leading `>=` followed by optional whitespace and a digit with no `<` anywhere.
570
+ *
571
+ * @param versionSpec - Dependency version specifier to evaluate.
572
+ * @returns True when `versionSpec` represents an unbounded or overly broad range; false otherwise.
573
+ */
434
574
  function isBroadRuntimeVersion(versionSpec: string): boolean {
435
575
  const normalized = versionSpec.trim().toLowerCase();
436
576
  return normalized === "*" || normalized === "x" || normalized === "latest" || (/^>=\s*\d/.test(normalized) && !normalized.includes("<")) || normalized.includes("||");
437
577
  }
438
578
 
439
- // JSONC normalization used for tsconfig files: strip BOM, comments, then trailing commas while
440
- // preserving line breaks so `jsonKeyLine` still points at the original source location.
579
+ /**
580
+ * Strips a leading BOM, JSONC comments, and trailing commas from `source` while keeping LF line breaks for `JSON.parse`.
581
+ *
582
+ * @param source - Raw JSON or JSONC input text.
583
+ * @returns Normalized JSON text ready for `JSON.parse`.
584
+ */
441
585
  function jsonParseSource(source: string): string {
442
586
  return stripJsonTrailingCommas(stripJsonComments(source.replace(/^\uFEFF/, "")));
443
587
  }
444
588
 
445
- // Removes `//` and `/* */` comments outside strings, replacing comment bytes with spaces/newlines
446
- // so later parse errors and line lookups remain aligned with the original file.
589
+ /**
590
+ * Replaces line and block comments outside strings in `source` with spaces while preserving LF line breaks.
591
+ * Keeps output length unchanged so each character outside a comment stays at its original offset in this step.
592
+ *
593
+ * @param source - JSONC text that may contain line or block comments and string literals.
594
+ * @returns Text of the same length with non-string comments replaced by spaces and preserved newlines.
595
+ */
447
596
  function stripJsonComments(source: string): string {
448
597
  let result = "";
449
598
  const quoteState: JsonQuoteState = { quote: "", isEscaped: false };
@@ -468,8 +617,14 @@ function stripJsonComments(source: string): string {
468
617
  return result;
469
618
  }
470
619
 
471
- // Replacement text for a line comment. Spaces keep column alignment; the end index lets the caller
472
- // resume at the newline without losing the line break.
620
+ /**
621
+ * Scans `source` from a line comment's `startIndex` up to (but not including) the next newline so the caller retains the newline.
622
+ * A line comment reaching EOF ends at `source.length - 1`.
623
+ *
624
+ * @param source - JSONC source text being stripped of comments.
625
+ * @param startIndex - Index of the opening slash of the line comment.
626
+ * @returns Equal-width space replacement string and the last replaced index (`endIndex`).
627
+ */
473
628
  function lineCommentSpan(source: string, startIndex: number): { replacement: string; endIndex: number } {
474
629
  let endIndex = startIndex;
475
630
  while (endIndex < source.length && source[endIndex] !== "\n") {
@@ -478,9 +633,14 @@ function lineCommentSpan(source: string, startIndex: number): { replacement: str
478
633
  return { replacement: " ".repeat(endIndex - startIndex), endIndex: endIndex - 1 };
479
634
  }
480
635
 
481
- // Replacement text for a block comment, preserving every newline encountered. The character loop
482
- // exists because block comments can span lines; fallback behaviour turns unterminated comments into
483
- // spaces through EOF because malformed JSONC should simply reach JSON.parse failure.
636
+ /**
637
+ * Computes replacement text for a block comment while preserving every newline encountered across multi-line comments.
638
+ * Turns unterminated block comments into spaces through EOF because malformed JSONC should simply reach `JSON.parse` failure.
639
+ *
640
+ * @param source - JSONC source text being stripped of comments.
641
+ * @param startIndex - Index of the opening slash of the block comment.
642
+ * @returns Space-and-newline replacement string and the index of the closing slash or EOF (`endIndex`).
643
+ */
484
644
  function blockCommentSpan(source: string, startIndex: number): { replacement: string; endIndex: number } {
485
645
  let endIndex = startIndex + 2;
486
646
  let replacement = " ";
@@ -496,8 +656,12 @@ function blockCommentSpan(source: string, startIndex: number): { replacement: st
496
656
  return { replacement, endIndex: source.length - 1 };
497
657
  }
498
658
 
499
- // Removes commas that are followed only by whitespace and a JSON object/array closer. Quote state
500
- // prevents commas inside string literals from being treated as structural punctuation.
659
+ /**
660
+ * Removes commas followed only by whitespace and a JSON object or array closer, using quote state to preserve commas inside string literals.
661
+ *
662
+ * @param source - Comment-stripped JSON text that may contain trailing commas.
663
+ * @returns JSON text with structural trailing commas removed.
664
+ */
501
665
  function stripJsonTrailingCommas(source: string): string {
502
666
  let result = "";
503
667
  const quoteState: JsonQuoteState = { quote: "", isEscaped: false };
@@ -512,7 +676,13 @@ function stripJsonTrailingCommas(source: string): string {
512
676
  return result;
513
677
  }
514
678
 
515
- // Looks past whitespace to decide whether a comma is trailing before `}` or `]`.
679
+ /**
680
+ * Scans ahead in `source` from `startIndex` to determine whether a comma precedes an object or array closing token.
681
+ *
682
+ * @param source - Comment-stripped JSON text being scanned for trailing commas.
683
+ * @param startIndex - Index immediately after the candidate comma.
684
+ * @returns True if the next non-whitespace character is `}` or `]`; false for any other token or end of input.
685
+ */
516
686
  function isJsonClosingTokenAhead(source: string, startIndex: number): boolean {
517
687
  for (let index = startIndex; index < source.length; index += 1) {
518
688
  const character = source[index] ?? "";
@@ -529,8 +699,14 @@ interface JsonQuoteState {
529
699
  isEscaped: boolean;
530
700
  }
531
701
 
532
- // Tracks whether the cursor is inside a JSON string and whether the prior character was a
533
- // backslash. Callers use this to avoid rewriting comment/comma-like text inside string values.
702
+ /**
703
+ * Consumes `character` and mutates `quoteState` to track JSON string membership and whether the next character is escaped.
704
+ * Preserves comment-like and comma-like text inside strings for callers.
705
+ *
706
+ * @param character - Single character at the current scan position.
707
+ * @param quoteState - Mutable lexer state tracking active quote delimiter and escape flag.
708
+ * @returns Nothing. Updates `quoteState` in place.
709
+ */
534
710
  function updateJsonQuoteState(character: string, quoteState: JsonQuoteState): void {
535
711
  if (!quoteState.quote && character === "\"") {
536
712
  quoteState.quote = character;
@@ -548,9 +724,13 @@ function updateJsonQuoteState(character: string, quoteState: JsonQuoteState): vo
548
724
  }
549
725
  }
550
726
 
551
- // Normalises both npm bin forms: a string (uses the package name as the command) and an object
552
- // (each key is a command name). Non-string entries are silently dropped because nothing valid can
553
- // be done with them.
727
+ /**
728
+ * Extracts command/target pairs from `pkg.bin`, defaulting string declarations to `pkg.name` or `"bin"` when `pkg.name` is not a string.
729
+ * Missing or invalid `bin` declarations yield no pairs, and non-string targets are dropped.
730
+ *
731
+ * @param pkg - Parsed `package.json` manifest object.
732
+ * @returns Array of `[command, target]` tuples for valid string bin targets.
733
+ */
554
734
  function packageBinEntries(pkg: Record<string, unknown>): Array<[string, string]> {
555
735
  const bin = pkg.bin;
556
736
  if (isString(bin)) {
@@ -564,8 +744,12 @@ function packageBinEntries(pkg: Record<string, unknown>): Array<[string, string]
564
744
  return Object.entries(bins).filter((entry): entry is [string, string] => isString(entry[1]));
565
745
  }
566
746
 
567
- // Local copy of the regex-escape helper - `discovery.ts` has its own copy because this module
568
- // is intentionally a leaf with no cross-module dependency on path helpers.
747
+ /**
748
+ * Escapes regular-expression metacharacters in `rawText` so callers can match it literally.
749
+ *
750
+ * @param rawText - Literal text to embed into a `RegExp` pattern.
751
+ * @returns Escaped string safe for literal regex matching.
752
+ */
569
753
  function escapeRegex(rawText: string): string {
570
754
  return rawText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
571
755
  }