@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
@@ -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. `runtimeDependency` 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"]) {
@@ -128,35 +136,59 @@ function analysePackageDependencies(file: ConfigSourceFile, source: string, pkg:
128
136
  if (!dependencies) {
129
137
  continue;
130
138
  }
131
- const runtimeDependency = section === "dependencies" || section === "optionalDependencies";
139
+ const isRuntimeDependency = section === "dependencies" || section === "optionalDependencies";
132
140
  for (const [packageName, value] of Object.entries(dependencies)) {
133
141
  if (isString(value)) {
134
- analysePackageDependency(file, source, section, packageName, value, runtimeDependency, findings);
142
+ analysePackageDependency(file, source, section, packageName, value, isRuntimeDependency, findings);
135
143
  }
136
144
  }
137
145
  }
138
146
  }
139
147
 
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
+ */
140
160
  function analysePackageDependency(
141
161
  file: ConfigSourceFile,
142
162
  source: string,
143
163
  section: string,
144
164
  packageName: string,
145
165
  versionSpec: string,
146
- runtimeDependency: boolean,
166
+ isRuntimeDependency: boolean,
147
167
  findings: Finding[],
148
168
  ): void {
149
- pushUrlDependencyFinding(file, source, section, packageName, versionSpec, runtimeDependency, findings);
150
- pushBroadRuntimeDependencyFinding(file, source, section, packageName, versionSpec, runtimeDependency, findings);
151
- }
152
-
169
+ pushUrlDependencyFinding(file, source, section, packageName, versionSpec, isRuntimeDependency, findings);
170
+ pushBroadRuntimeDependencyFinding(file, source, section, packageName, versionSpec, isRuntimeDependency, findings);
171
+ }
172
+
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
+ */
153
185
  function pushUrlDependencyFinding(
154
186
  file: ConfigSourceFile,
155
187
  source: string,
156
188
  section: string,
157
189
  packageName: string,
158
190
  versionSpec: string,
159
- runtimeDependency: boolean,
191
+ isRuntimeDependency: boolean,
160
192
  findings: Finding[],
161
193
  ): void {
162
194
  if (!isUrlDependency(versionSpec)) {
@@ -167,27 +199,39 @@ function pushUrlDependencyFinding(
167
199
  ruleId: "security.url-dependency",
168
200
  message: `Dependency \`${packageName}\` in \`${section}\` installs from a URL, git, or local file spec.`,
169
201
  filePath: file.displayPath,
170
- line: jsonKeyLine(source, packageName),
202
+ line: dependencyEntryLine(source, section, packageName, versionSpec),
171
203
  severity: "warning",
172
204
  pillar: "security",
173
205
  confidence: "medium",
174
206
  symbol: packageName,
175
207
  remediation: "Prefer a registry package version that can be locked and audited.",
176
- metadata: { packageName, section, runtimeDependency },
208
+ metadata: { packageName, section, runtimeDependency: isRuntimeDependency },
177
209
  }),
178
210
  );
179
211
  }
180
212
 
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
+ */
181
225
  function pushBroadRuntimeDependencyFinding(
182
226
  file: ConfigSourceFile,
183
227
  source: string,
184
228
  section: string,
185
229
  packageName: string,
186
230
  versionSpec: string,
187
- runtimeDependency: boolean,
231
+ isRuntimeDependency: boolean,
188
232
  findings: Finding[],
189
233
  ): void {
190
- if (!runtimeDependency || !isBroadRuntimeVersion(versionSpec)) {
234
+ if (!isRuntimeDependency || !isBroadRuntimeVersion(versionSpec)) {
191
235
  return;
192
236
  }
193
237
  findings.push(
@@ -195,7 +239,7 @@ function pushBroadRuntimeDependencyFinding(
195
239
  ruleId: "waste.broad-runtime-version",
196
240
  message: `Runtime dependency \`${packageName}\` uses overly broad version spec \`${versionSpec}\`.`,
197
241
  filePath: file.displayPath,
198
- line: jsonKeyLine(source, packageName),
242
+ line: dependencyEntryLine(source, section, packageName, versionSpec),
199
243
  severity: "advisory",
200
244
  pillar: "maintainability",
201
245
  confidence: "medium",
@@ -206,26 +250,38 @@ function pushBroadRuntimeDependencyFinding(
206
250
  );
207
251
  }
208
252
 
209
- /*
210
- * Expands `bin` into (command, target) pairs (handling both string and object forms), then checks
211
- * each one in a deterministic, stable order. Returns nothing when `bin` is absent - the rule does
212
- * 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.
213
261
  */
214
262
  function analysePackageBins(file: ConfigSourceFile, source: string, pkg: Record<string, unknown>, findings: Finding[]): void {
263
+ const hasBuildScript = hasPackageBuildScript(pkg);
215
264
  for (const [command, target] of packageBinEntries(pkg)) {
216
- analysePackageBin(file, source, command, target, findings);
265
+ analysePackageBin(file, source, command, target, hasBuildScript, findings);
217
266
  }
218
267
  }
219
268
 
220
- /*
221
- * Reads the bin target from disk. The stable mapping: missing → `package-bin-missing`;
222
- * non-executable → `package-bin-not-executable`. Executable files pass silently so the rule cannot
223
- * 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.
224
280
  */
225
- 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 {
226
282
  const absolute = packageBinPath(file, target);
227
283
  if (!existsSync(absolute)) {
228
- pushMissingPackageBinFinding(file, source, command, target, findings);
284
+ pushMissingPackageBinFinding(file, source, command, target, hasBuildScript && isBuildOutputBinTarget(target), findings);
229
285
  return;
230
286
  }
231
287
  const stats = statSync(absolute);
@@ -237,34 +293,80 @@ function analysePackageBin(file: ConfigSourceFile, source: string, command: stri
237
293
  }
238
294
  }
239
295
 
240
- // Bin targets are resolved against the directory of the owning package.json, not the project root.
241
- // 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
+ */
242
325
  function packageBinPath(file: ConfigSourceFile, target: string): string {
243
326
  return isAbsolute(target) ? target : join(dirnamePath(file.absolutePath), target);
244
327
  }
245
328
 
246
- /*
247
- * Reports the `design.package-bin-missing` finding for a declared bin whose file does not exist
248
- * 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.
249
340
  */
250
- 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 {
251
342
  findings.push(
252
343
  packageBinFinding({
253
344
  file,
254
345
  source,
255
346
  ruleId: "design.package-bin-missing",
256
- 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}\`.`,
257
350
  command,
258
351
  target,
259
- 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.",
260
357
  }),
261
358
  );
262
359
  }
263
360
 
264
- /*
265
- * Reports the stable `design.package-bin-not-executable` finding - the file exists but lacks the
266
- * execute bit. Common on Windows checkouts; the remediation message reminds maintainers to also
267
- * 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.
268
370
  */
269
371
  function pushNonExecutablePackageBinFinding(file: ConfigSourceFile, source: string, command: string, target: string, findings: Finding[]): void {
270
372
  findings.push(
@@ -275,12 +377,14 @@ function pushNonExecutablePackageBinFinding(file: ConfigSourceFile, source: stri
275
377
  message: `Package bin \`${command}\` points to a file that is not executable.`,
276
378
  command,
277
379
  target,
380
+ severity: "warning",
381
+ isUnbuiltOutput: false,
278
382
  remediation: "Make the bin target executable and keep its shebang valid.",
279
383
  }),
280
384
  );
281
385
  }
282
386
 
283
- // 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
284
388
  // fields and an inline parameter list would silently break call sites on field shuffles.
285
389
  interface PackageBinFindingInput {
286
390
  file: ConfigSourceFile;
@@ -289,31 +393,42 @@ interface PackageBinFindingInput {
289
393
  message: string;
290
394
  command: string;
291
395
  target: string;
396
+ severity: "advisory" | "warning";
397
+ isUnbuiltOutput: boolean;
292
398
  remediation: string;
293
399
  }
294
400
 
295
- // Single makeFinding call site for both bin-missing and bin-not-executable. The `command` symbol
296
- // 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
+ */
297
408
  function packageBinFinding(input: PackageBinFindingInput): Finding {
298
409
  return makeFinding({
299
410
  ruleId: input.ruleId,
300
411
  message: input.message,
301
412
  filePath: input.file.displayPath,
302
413
  line: jsonKeyLine(input.source, input.command),
303
- severity: "warning",
414
+ severity: input.severity,
304
415
  pillar: "design",
305
416
  confidence: "high",
306
417
  symbol: input.command,
307
418
  remediation: input.remediation,
308
- 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 },
309
420
  });
310
421
  }
311
422
 
312
- /*
313
- * Three TypeScript strictness flags whose absence is a documentation-worthy compromise: `strict`,
314
- * `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`. Reports each missing flag as its own
315
- * finding; the list is intentionally short - adding new flags here changes the rule surface and
316
- * 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.
317
432
  */
318
433
  function analyseTsconfigJson(file: ConfigSourceFile, source: string, tsconfigData: Record<string, unknown>, findings: Finding[]): void {
319
434
  const compilerOptions = objectValue(tsconfigData.compilerOptions) ?? {};
@@ -328,8 +443,7 @@ function analyseTsconfigJson(file: ConfigSourceFile, source: string, tsconfigDat
328
443
  if (optionValue === true) {
329
444
  continue;
330
445
  }
331
- // When the tsconfig `extends` another file we can't see the resolved compilerOptions, so an
332
- // 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.
333
447
  if (optionValue === undefined && hasExtends) {
334
448
  continue;
335
449
  }
@@ -357,8 +471,13 @@ interface TsconfigFindingInput {
357
471
  currentValue: unknown;
358
472
  }
359
473
 
360
- // Single makeFinding site for tsconfig strictness findings. `optionName` is the symbol anchor and
361
- // `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
+ */
362
481
  function tsconfigFinding(input: TsconfigFindingInput): Finding {
363
482
  return makeFinding({
364
483
  ruleId: input.ruleId,
@@ -374,9 +493,12 @@ function tsconfigFinding(input: TsconfigFindingInput): Finding {
374
493
  });
375
494
  }
376
495
 
377
- /*
378
- * Swallows parse errors and returns undefined as a fallback so a malformed package.json doesn't
379
- * 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.
380
502
  */
381
503
  function parseJsonObject(source: string): Record<string, unknown> | undefined {
382
504
  try {
@@ -386,59 +508,91 @@ function parseJsonObject(source: string): Record<string, unknown> | undefined {
386
508
  }
387
509
  }
388
510
 
389
- // Approximate line lookup - finds the first `"key":` occurrence. JSON allows the same key in
390
- // 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
+ */
391
519
  function jsonKeyLine(source: string, key: string): number {
392
520
  const escapedKey = escapeRegex(key);
393
521
  return firstLine(source, new RegExp(`"${escapedKey}"\\s*:`));
394
522
  }
395
523
 
396
- // Pattern matches `curl|wget … | sh` or its inline-pipe variants. The negative lookaheads for `|`,
397
- // `;`, `&` prevent overlong matches that would span multiple shell commands.
398
- function isRemoteInstallScript(command: string): boolean {
399
- return /\b(?:curl|wget)\b[^\n|;&]*https?:\/\/[^\n|;&]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh)\b/i.test(command);
400
- }
401
-
402
- // The closed list of npm/yarn/pnpm install-time hooks. Adding entries here expands rule coverage.
403
- function isLifecycleScript(scriptName: string): boolean {
404
- return ["preinstall", "install", "postinstall", "prepare", "prepublish", "prepublishOnly"].includes(scriptName);
405
- }
406
-
407
- // Allows closed-list validation commands in publish hooks while rejecting shell composition.
408
- function isValidationOnlyLifecycleCommand(scriptName: string, command: string): boolean {
409
- if (!["prepublish", "prepublishOnly"].includes(scriptName)) {
410
- return false;
411
- }
412
- const normalizedCommand = command.trim().replace(/\s+/g, " ");
413
- if (/[;&|`$<>]/.test(normalizedCommand)) {
414
- 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);
415
542
  }
416
- return VALIDATION_ONLY_LIFECYCLE_COMMANDS.has(normalizedCommand);
543
+ return source.slice(0, searchStart + match.index).split(/\r?\n/).length;
417
544
  }
418
545
 
419
- 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
+ }
420
556
 
421
- // Recognises non-registry installs: full URLs, git+ssh, file:, and npm-hosting shortcuts.
422
- // 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
+ */
423
563
  function isUrlDependency(versionSpec: string): boolean {
424
564
  return /^(?:https?:\/\/|git(?:\+https?|\+ssh)?:\/\/|ssh:\/\/|github:|gitlab:|bitbucket:|file:|git@[^:]+:[^/]+\/|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$)/i.test(versionSpec);
425
565
  }
426
566
 
427
- // Catches `*`, `x`, `latest`, unbounded `>=` ranges, and OR-joined ranges. All let dependency
428
- // 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
+ */
429
574
  function isBroadRuntimeVersion(versionSpec: string): boolean {
430
575
  const normalized = versionSpec.trim().toLowerCase();
431
576
  return normalized === "*" || normalized === "x" || normalized === "latest" || (/^>=\s*\d/.test(normalized) && !normalized.includes("<")) || normalized.includes("||");
432
577
  }
433
578
 
434
- // JSONC normalization used for tsconfig files: strip BOM, comments, then trailing commas while
435
- // 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
+ */
436
585
  function jsonParseSource(source: string): string {
437
586
  return stripJsonTrailingCommas(stripJsonComments(source.replace(/^\uFEFF/, "")));
438
587
  }
439
588
 
440
- // Removes `//` and `/* */` comments outside strings, replacing comment bytes with spaces/newlines
441
- // 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
+ */
442
596
  function stripJsonComments(source: string): string {
443
597
  let result = "";
444
598
  const quoteState: JsonQuoteState = { quote: "", isEscaped: false };
@@ -463,8 +617,14 @@ function stripJsonComments(source: string): string {
463
617
  return result;
464
618
  }
465
619
 
466
- // Replacement text for a line comment. Spaces keep column alignment; the end index lets the caller
467
- // 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
+ */
468
628
  function lineCommentSpan(source: string, startIndex: number): { replacement: string; endIndex: number } {
469
629
  let endIndex = startIndex;
470
630
  while (endIndex < source.length && source[endIndex] !== "\n") {
@@ -473,9 +633,14 @@ function lineCommentSpan(source: string, startIndex: number): { replacement: str
473
633
  return { replacement: " ".repeat(endIndex - startIndex), endIndex: endIndex - 1 };
474
634
  }
475
635
 
476
- // Replacement text for a block comment, preserving every newline encountered. The character loop
477
- // exists because block comments can span lines; fallback behaviour turns unterminated comments into
478
- // 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
+ */
479
644
  function blockCommentSpan(source: string, startIndex: number): { replacement: string; endIndex: number } {
480
645
  let endIndex = startIndex + 2;
481
646
  let replacement = " ";
@@ -491,8 +656,12 @@ function blockCommentSpan(source: string, startIndex: number): { replacement: st
491
656
  return { replacement, endIndex: source.length - 1 };
492
657
  }
493
658
 
494
- // Removes commas that are followed only by whitespace and a JSON object/array closer. Quote state
495
- // 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
+ */
496
665
  function stripJsonTrailingCommas(source: string): string {
497
666
  let result = "";
498
667
  const quoteState: JsonQuoteState = { quote: "", isEscaped: false };
@@ -507,7 +676,13 @@ function stripJsonTrailingCommas(source: string): string {
507
676
  return result;
508
677
  }
509
678
 
510
- // 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
+ */
511
686
  function isJsonClosingTokenAhead(source: string, startIndex: number): boolean {
512
687
  for (let index = startIndex; index < source.length; index += 1) {
513
688
  const character = source[index] ?? "";
@@ -524,8 +699,14 @@ interface JsonQuoteState {
524
699
  isEscaped: boolean;
525
700
  }
526
701
 
527
- // Tracks whether the cursor is inside a JSON string and whether the prior character was a
528
- // 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
+ */
529
710
  function updateJsonQuoteState(character: string, quoteState: JsonQuoteState): void {
530
711
  if (!quoteState.quote && character === "\"") {
531
712
  quoteState.quote = character;
@@ -543,9 +724,13 @@ function updateJsonQuoteState(character: string, quoteState: JsonQuoteState): vo
543
724
  }
544
725
  }
545
726
 
546
- // Normalises both npm bin forms: a string (uses the package name as the command) and an object
547
- // (each key is a command name). Non-string entries are silently dropped because nothing valid can
548
- // 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
+ */
549
734
  function packageBinEntries(pkg: Record<string, unknown>): Array<[string, string]> {
550
735
  const bin = pkg.bin;
551
736
  if (isString(bin)) {
@@ -559,8 +744,12 @@ function packageBinEntries(pkg: Record<string, unknown>): Array<[string, string]
559
744
  return Object.entries(bins).filter((entry): entry is [string, string] => isString(entry[1]));
560
745
  }
561
746
 
562
- // Local copy of the regex-escape helper - `discovery.ts` has its own copy because this module
563
- // 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
+ */
564
753
  function escapeRegex(rawText: string): string {
565
754
  return rawText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
566
755
  }