@terra-symposium/hygiene 0.0.0-stage → 2.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -2
- package/dist/accessibility.d.ts +39 -0
- package/dist/accessibility.d.ts.map +1 -0
- package/dist/accessibility.js +524 -0
- package/dist/accessibility.js.map +1 -0
- package/dist/app/workspace-test-runner.d.ts +6 -0
- package/dist/app/workspace-test-runner.d.ts.map +1 -0
- package/dist/app/workspace-test-runner.js +39 -0
- package/dist/app/workspace-test-runner.js.map +1 -0
- package/dist/capabilities/core/analysis.d.ts +22 -0
- package/dist/capabilities/core/analysis.d.ts.map +1 -0
- package/dist/capabilities/core/analysis.js +44 -0
- package/dist/capabilities/core/analysis.js.map +1 -0
- package/dist/capabilities/core/cli.d.ts +19 -0
- package/dist/capabilities/core/cli.d.ts.map +1 -0
- package/dist/capabilities/core/cli.js +58 -0
- package/dist/capabilities/core/cli.js.map +1 -0
- package/dist/capabilities/core/config.d.ts +49 -0
- package/dist/capabilities/core/config.d.ts.map +1 -0
- package/dist/capabilities/core/config.js +88 -0
- package/dist/capabilities/core/config.js.map +1 -0
- package/dist/capabilities/core/index.d.ts +11 -0
- package/dist/capabilities/core/index.d.ts.map +1 -0
- package/dist/capabilities/core/index.js +11 -0
- package/dist/capabilities/core/index.js.map +1 -0
- package/dist/capabilities/core/lib/files.d.ts +55 -0
- package/dist/capabilities/core/lib/files.d.ts.map +1 -0
- package/dist/capabilities/core/lib/files.js +287 -0
- package/dist/capabilities/core/lib/files.js.map +1 -0
- package/dist/capabilities/core/lib/progress.d.ts +25 -0
- package/dist/capabilities/core/lib/progress.d.ts.map +1 -0
- package/dist/capabilities/core/lib/progress.js +40 -0
- package/dist/capabilities/core/lib/progress.js.map +1 -0
- package/dist/capabilities/core/lib/source-kind.d.ts +14 -0
- package/dist/capabilities/core/lib/source-kind.d.ts.map +1 -0
- package/dist/capabilities/core/lib/source-kind.js +29 -0
- package/dist/capabilities/core/lib/source-kind.js.map +1 -0
- package/dist/capabilities/core/types.d.ts +156 -0
- package/dist/capabilities/core/types.d.ts.map +1 -0
- package/dist/capabilities/core/types.js +35 -0
- package/dist/capabilities/core/types.js.map +1 -0
- package/dist/capabilities/documentation/cli.d.ts +3 -0
- package/dist/capabilities/documentation/cli.d.ts.map +1 -0
- package/dist/capabilities/documentation/cli.js +14 -0
- package/dist/capabilities/documentation/cli.js.map +1 -0
- package/dist/capabilities/documentation/index.d.ts +5 -0
- package/dist/capabilities/documentation/index.d.ts.map +1 -0
- package/dist/capabilities/documentation/index.js +5 -0
- package/dist/capabilities/documentation/index.js.map +1 -0
- package/dist/capabilities/documentation/lib/documentation.d.ts +108 -0
- package/dist/capabilities/documentation/lib/documentation.d.ts.map +1 -0
- package/dist/capabilities/documentation/lib/documentation.js +1007 -0
- package/dist/capabilities/documentation/lib/documentation.js.map +1 -0
- package/dist/capabilities/formatting/cli.d.ts +3 -0
- package/dist/capabilities/formatting/cli.d.ts.map +1 -0
- package/dist/capabilities/formatting/cli.js +15 -0
- package/dist/capabilities/formatting/cli.js.map +1 -0
- package/dist/capabilities/formatting/index.d.ts +8 -0
- package/dist/capabilities/formatting/index.d.ts.map +1 -0
- package/dist/capabilities/formatting/index.js +8 -0
- package/dist/capabilities/formatting/index.js.map +1 -0
- package/dist/capabilities/formatting/lib/collapse.d.ts +13 -0
- package/dist/capabilities/formatting/lib/collapse.d.ts.map +1 -0
- package/dist/capabilities/formatting/lib/collapse.js +179 -0
- package/dist/capabilities/formatting/lib/collapse.js.map +1 -0
- package/dist/capabilities/formatting/lib/inline-if.d.ts +13 -0
- package/dist/capabilities/formatting/lib/inline-if.d.ts.map +1 -0
- package/dist/capabilities/formatting/lib/inline-if.js +49 -0
- package/dist/capabilities/formatting/lib/inline-if.js.map +1 -0
- package/dist/capabilities/formatting/lib/run-formatting.d.ts +14 -0
- package/dist/capabilities/formatting/lib/run-formatting.d.ts.map +1 -0
- package/dist/capabilities/formatting/lib/run-formatting.js +134 -0
- package/dist/capabilities/formatting/lib/run-formatting.js.map +1 -0
- package/dist/capabilities/imports/cli.d.ts +3 -0
- package/dist/capabilities/imports/cli.d.ts.map +1 -0
- package/dist/capabilities/imports/cli.js +9 -0
- package/dist/capabilities/imports/cli.js.map +1 -0
- package/dist/capabilities/imports/index.d.ts +6 -0
- package/dist/capabilities/imports/index.d.ts.map +1 -0
- package/dist/capabilities/imports/index.js +6 -0
- package/dist/capabilities/imports/index.js.map +1 -0
- package/dist/capabilities/imports/lib/imports.d.ts +19 -0
- package/dist/capabilities/imports/lib/imports.d.ts.map +1 -0
- package/dist/capabilities/imports/lib/imports.js +88 -0
- package/dist/capabilities/imports/lib/imports.js.map +1 -0
- package/dist/capabilities/languages/cli.d.ts +3 -0
- package/dist/capabilities/languages/cli.d.ts.map +1 -0
- package/dist/capabilities/languages/cli.js +9 -0
- package/dist/capabilities/languages/cli.js.map +1 -0
- package/dist/capabilities/languages/index.d.ts +6 -0
- package/dist/capabilities/languages/index.d.ts.map +1 -0
- package/dist/capabilities/languages/index.js +6 -0
- package/dist/capabilities/languages/index.js.map +1 -0
- package/dist/capabilities/languages/lib/language-profiles.d.ts +110 -0
- package/dist/capabilities/languages/lib/language-profiles.d.ts.map +1 -0
- package/dist/capabilities/languages/lib/language-profiles.js +509 -0
- package/dist/capabilities/languages/lib/language-profiles.js.map +1 -0
- package/dist/capabilities/languages/lib/run-language-checks.d.ts +12 -0
- package/dist/capabilities/languages/lib/run-language-checks.d.ts.map +1 -0
- package/dist/capabilities/languages/lib/run-language-checks.js +109 -0
- package/dist/capabilities/languages/lib/run-language-checks.js.map +1 -0
- package/dist/capabilities/naming/cli.d.ts +3 -0
- package/dist/capabilities/naming/cli.d.ts.map +1 -0
- package/dist/capabilities/naming/cli.js +15 -0
- package/dist/capabilities/naming/cli.js.map +1 -0
- package/dist/capabilities/naming/index.d.ts +5 -0
- package/dist/capabilities/naming/index.d.ts.map +1 -0
- package/dist/capabilities/naming/index.js +5 -0
- package/dist/capabilities/naming/index.js.map +1 -0
- package/dist/capabilities/naming/lib/naming.d.ts +169 -0
- package/dist/capabilities/naming/lib/naming.d.ts.map +1 -0
- package/dist/capabilities/naming/lib/naming.js +908 -0
- package/dist/capabilities/naming/lib/naming.js.map +1 -0
- package/dist/capabilities/patterns/cli.d.ts +3 -0
- package/dist/capabilities/patterns/cli.d.ts.map +1 -0
- package/dist/capabilities/patterns/cli.js +30 -0
- package/dist/capabilities/patterns/cli.js.map +1 -0
- package/dist/capabilities/patterns/index.d.ts +5 -0
- package/dist/capabilities/patterns/index.d.ts.map +1 -0
- package/dist/capabilities/patterns/index.js +5 -0
- package/dist/capabilities/patterns/index.js.map +1 -0
- package/dist/capabilities/patterns/lib/patterns.d.ts +102 -0
- package/dist/capabilities/patterns/lib/patterns.d.ts.map +1 -0
- package/dist/capabilities/patterns/lib/patterns.js +1584 -0
- package/dist/capabilities/patterns/lib/patterns.js.map +1 -0
- package/dist/capabilities/refactoring/cli.d.ts +3 -0
- package/dist/capabilities/refactoring/cli.d.ts.map +1 -0
- package/dist/capabilities/refactoring/cli.js +15 -0
- package/dist/capabilities/refactoring/cli.js.map +1 -0
- package/dist/capabilities/refactoring/index.d.ts +6 -0
- package/dist/capabilities/refactoring/index.d.ts.map +1 -0
- package/dist/capabilities/refactoring/index.js +6 -0
- package/dist/capabilities/refactoring/index.js.map +1 -0
- package/dist/capabilities/refactoring/lib/object-forwarding.d.ts +42 -0
- package/dist/capabilities/refactoring/lib/object-forwarding.d.ts.map +1 -0
- package/dist/capabilities/refactoring/lib/object-forwarding.js +166 -0
- package/dist/capabilities/refactoring/lib/object-forwarding.js.map +1 -0
- package/dist/capabilities/refactoring/lib/single-use.d.ts +61 -0
- package/dist/capabilities/refactoring/lib/single-use.d.ts.map +1 -0
- package/dist/capabilities/refactoring/lib/single-use.js +1791 -0
- package/dist/capabilities/refactoring/lib/single-use.js.map +1 -0
- package/dist/capabilities/reports/cli.d.ts +3 -0
- package/dist/capabilities/reports/cli.d.ts.map +1 -0
- package/dist/capabilities/reports/cli.js +34 -0
- package/dist/capabilities/reports/cli.js.map +1 -0
- package/dist/capabilities/reports/index.d.ts +10 -0
- package/dist/capabilities/reports/index.d.ts.map +1 -0
- package/dist/capabilities/reports/index.js +10 -0
- package/dist/capabilities/reports/index.js.map +1 -0
- package/dist/capabilities/reports/lib/github-report.d.ts +94 -0
- package/dist/capabilities/reports/lib/github-report.d.ts.map +1 -0
- package/dist/capabilities/reports/lib/github-report.js +499 -0
- package/dist/capabilities/reports/lib/github-report.js.map +1 -0
- package/dist/capabilities/reports/lib/history-report.d.ts +58 -0
- package/dist/capabilities/reports/lib/history-report.d.ts.map +1 -0
- package/dist/capabilities/reports/lib/history-report.js +300 -0
- package/dist/capabilities/reports/lib/history-report.js.map +1 -0
- package/dist/capabilities/reports/lib/node-reporter.d.ts +79 -0
- package/dist/capabilities/reports/lib/node-reporter.d.ts.map +1 -0
- package/dist/capabilities/reports/lib/node-reporter.js +244 -0
- package/dist/capabilities/reports/lib/node-reporter.js.map +1 -0
- package/dist/capabilities/reports/lib/playwright-reporter.d.ts +100 -0
- package/dist/capabilities/reports/lib/playwright-reporter.d.ts.map +1 -0
- package/dist/capabilities/reports/lib/playwright-reporter.js +122 -0
- package/dist/capabilities/reports/lib/playwright-reporter.js.map +1 -0
- package/dist/capabilities/security/cli.d.ts +3 -0
- package/dist/capabilities/security/cli.d.ts.map +1 -0
- package/dist/capabilities/security/cli.js +9 -0
- package/dist/capabilities/security/cli.js.map +1 -0
- package/dist/capabilities/security/index.d.ts +5 -0
- package/dist/capabilities/security/index.d.ts.map +1 -0
- package/dist/capabilities/security/index.js +5 -0
- package/dist/capabilities/security/index.js.map +1 -0
- package/dist/capabilities/security/lib/security.d.ts +19 -0
- package/dist/capabilities/security/lib/security.d.ts.map +1 -0
- package/dist/capabilities/security/lib/security.js +115 -0
- package/dist/capabilities/security/lib/security.js.map +1 -0
- package/dist/capabilities/ui/cli.d.ts +3 -0
- package/dist/capabilities/ui/cli.d.ts.map +1 -0
- package/dist/capabilities/ui/cli.js +22 -0
- package/dist/capabilities/ui/cli.js.map +1 -0
- package/dist/capabilities/ui/index.d.ts +8 -0
- package/dist/capabilities/ui/index.d.ts.map +1 -0
- package/dist/capabilities/ui/index.js +8 -0
- package/dist/capabilities/ui/index.js.map +1 -0
- package/dist/capabilities/ui/lib/accessibility.d.ts +37 -0
- package/dist/capabilities/ui/lib/accessibility.d.ts.map +1 -0
- package/dist/capabilities/ui/lib/accessibility.js +676 -0
- package/dist/capabilities/ui/lib/accessibility.js.map +1 -0
- package/dist/capabilities/ui/lib/display-name.d.ts +42 -0
- package/dist/capabilities/ui/lib/display-name.d.ts.map +1 -0
- package/dist/capabilities/ui/lib/display-name.js +277 -0
- package/dist/capabilities/ui/lib/display-name.js.map +1 -0
- package/dist/capabilities/ui/lib/error-boundaries.d.ts +30 -0
- package/dist/capabilities/ui/lib/error-boundaries.d.ts.map +1 -0
- package/dist/capabilities/ui/lib/error-boundaries.js +401 -0
- package/dist/capabilities/ui/lib/error-boundaries.js.map +1 -0
- package/dist/capabilities/ui/lib/ui-recommendations.d.ts +45 -0
- package/dist/capabilities/ui/lib/ui-recommendations.d.ts.map +1 -0
- package/dist/capabilities/ui/lib/ui-recommendations.js +183 -0
- package/dist/capabilities/ui/lib/ui-recommendations.js.map +1 -0
- package/dist/display-name.d.ts +44 -0
- package/dist/display-name.d.ts.map +1 -0
- package/dist/display-name.js +256 -0
- package/dist/display-name.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/accessibility.d.ts +5 -0
- package/dist/lib/accessibility.d.ts.map +1 -0
- package/dist/lib/accessibility.js +5 -0
- package/dist/lib/accessibility.js.map +1 -0
- package/dist/lib/collapse.d.ts +5 -0
- package/dist/lib/collapse.d.ts.map +1 -0
- package/dist/lib/collapse.js +5 -0
- package/dist/lib/collapse.js.map +1 -0
- package/dist/lib/dev.d.ts +3 -0
- package/dist/lib/dev.d.ts.map +1 -0
- package/dist/lib/dev.js +126 -0
- package/dist/lib/dev.js.map +1 -0
- package/dist/lib/display-name.d.ts +5 -0
- package/dist/lib/display-name.d.ts.map +1 -0
- package/dist/lib/display-name.js +5 -0
- package/dist/lib/display-name.js.map +1 -0
- package/dist/lib/documentation.d.ts +5 -0
- package/dist/lib/documentation.d.ts.map +1 -0
- package/dist/lib/documentation.js +5 -0
- package/dist/lib/documentation.js.map +1 -0
- package/dist/lib/error-boundaries-astro.d.ts +6 -0
- package/dist/lib/error-boundaries-astro.d.ts.map +1 -0
- package/dist/lib/error-boundaries-astro.js +6 -0
- package/dist/lib/error-boundaries-astro.js.map +1 -0
- package/dist/lib/error-boundaries-react.d.ts +6 -0
- package/dist/lib/error-boundaries-react.d.ts.map +1 -0
- package/dist/lib/error-boundaries-react.js +6 -0
- package/dist/lib/error-boundaries-react.js.map +1 -0
- package/dist/lib/error-boundaries.d.ts +5 -0
- package/dist/lib/error-boundaries.d.ts.map +1 -0
- package/dist/lib/error-boundaries.js +5 -0
- package/dist/lib/error-boundaries.js.map +1 -0
- package/dist/lib/eslint-api.d.ts +13 -0
- package/dist/lib/eslint-api.d.ts.map +1 -0
- package/dist/lib/eslint-api.js +24 -0
- package/dist/lib/eslint-api.js.map +1 -0
- package/dist/lib/files.d.ts +5 -0
- package/dist/lib/files.d.ts.map +1 -0
- package/dist/lib/files.js +5 -0
- package/dist/lib/files.js.map +1 -0
- package/dist/lib/formatting.d.ts +5 -0
- package/dist/lib/formatting.d.ts.map +1 -0
- package/dist/lib/formatting.js +5 -0
- package/dist/lib/formatting.js.map +1 -0
- package/dist/lib/github-report.d.ts +5 -0
- package/dist/lib/github-report.d.ts.map +1 -0
- package/dist/lib/github-report.js +5 -0
- package/dist/lib/github-report.js.map +1 -0
- package/dist/lib/history-report.d.ts +5 -0
- package/dist/lib/history-report.d.ts.map +1 -0
- package/dist/lib/history-report.js +5 -0
- package/dist/lib/history-report.js.map +1 -0
- package/dist/lib/imports.d.ts +5 -0
- package/dist/lib/imports.d.ts.map +1 -0
- package/dist/lib/imports.js +5 -0
- package/dist/lib/imports.js.map +1 -0
- package/dist/lib/index.d.ts +20 -0
- package/dist/lib/index.d.ts.map +1 -0
- package/dist/lib/index.js +20 -0
- package/dist/lib/index.js.map +1 -0
- package/dist/lib/inline-if.d.ts +5 -0
- package/dist/lib/inline-if.d.ts.map +1 -0
- package/dist/lib/inline-if.js +5 -0
- package/dist/lib/inline-if.js.map +1 -0
- package/dist/lib/language-checks.d.ts +5 -0
- package/dist/lib/language-checks.d.ts.map +1 -0
- package/dist/lib/language-checks.js +5 -0
- package/dist/lib/language-checks.js.map +1 -0
- package/dist/lib/language-profiles.d.ts +5 -0
- package/dist/lib/language-profiles.d.ts.map +1 -0
- package/dist/lib/language-profiles.js +5 -0
- package/dist/lib/language-profiles.js.map +1 -0
- package/dist/lib/naming.d.ts +5 -0
- package/dist/lib/naming.d.ts.map +1 -0
- package/dist/lib/naming.js +5 -0
- package/dist/lib/naming.js.map +1 -0
- package/dist/lib/node-reporter.d.ts +6 -0
- package/dist/lib/node-reporter.d.ts.map +1 -0
- package/dist/lib/node-reporter.js +6 -0
- package/dist/lib/node-reporter.js.map +1 -0
- package/dist/lib/object-forwarding.d.ts +5 -0
- package/dist/lib/object-forwarding.d.ts.map +1 -0
- package/dist/lib/object-forwarding.js +5 -0
- package/dist/lib/object-forwarding.js.map +1 -0
- package/dist/lib/patterns.d.ts +5 -0
- package/dist/lib/patterns.d.ts.map +1 -0
- package/dist/lib/patterns.js +5 -0
- package/dist/lib/patterns.js.map +1 -0
- package/dist/lib/playwright-reporter.d.ts +6 -0
- package/dist/lib/playwright-reporter.d.ts.map +1 -0
- package/dist/lib/playwright-reporter.js +6 -0
- package/dist/lib/playwright-reporter.js.map +1 -0
- package/dist/lib/port.d.ts +21 -0
- package/dist/lib/port.d.ts.map +1 -0
- package/dist/lib/port.js +81 -0
- package/dist/lib/port.js.map +1 -0
- package/dist/lib/progress.d.ts +5 -0
- package/dist/lib/progress.d.ts.map +1 -0
- package/dist/lib/progress.js +5 -0
- package/dist/lib/progress.js.map +1 -0
- package/dist/lib/reports.d.ts +5 -0
- package/dist/lib/reports.d.ts.map +1 -0
- package/dist/lib/reports.js +5 -0
- package/dist/lib/reports.js.map +1 -0
- package/dist/lib/runner.d.ts +150 -0
- package/dist/lib/runner.d.ts.map +1 -0
- package/dist/lib/runner.js +4522 -0
- package/dist/lib/runner.js.map +1 -0
- package/dist/lib/security.d.ts +5 -0
- package/dist/lib/security.d.ts.map +1 -0
- package/dist/lib/security.js +5 -0
- package/dist/lib/security.js.map +1 -0
- package/dist/lib/single-use.d.ts +6 -0
- package/dist/lib/single-use.d.ts.map +1 -0
- package/dist/lib/single-use.js +5 -0
- package/dist/lib/single-use.js.map +1 -0
- package/dist/lib/source-kind.d.ts +5 -0
- package/dist/lib/source-kind.d.ts.map +1 -0
- package/dist/lib/source-kind.js +5 -0
- package/dist/lib/source-kind.js.map +1 -0
- package/dist/lib/spinner-worker.d.ts +6 -0
- package/dist/lib/spinner-worker.d.ts.map +1 -0
- package/dist/lib/spinner-worker.js +33 -0
- package/dist/lib/spinner-worker.js.map +1 -0
- package/dist/lib/ui-quality.d.ts +5 -0
- package/dist/lib/ui-quality.d.ts.map +1 -0
- package/dist/lib/ui-quality.js +5 -0
- package/dist/lib/ui-quality.js.map +1 -0
- package/dist/lib/ui-recommendations.d.ts +5 -0
- package/dist/lib/ui-recommendations.d.ts.map +1 -0
- package/dist/lib/ui-recommendations.js +5 -0
- package/dist/lib/ui-recommendations.js.map +1 -0
- package/dist/spinner-worker.d.ts +6 -0
- package/dist/spinner-worker.d.ts.map +1 -0
- package/dist/spinner-worker.js +39 -0
- package/dist/spinner-worker.js.map +1 -0
- package/package.json +160 -5
- package/quality-configs/checkstyle.xml +29 -0
- package/quality-configs/pmd-rules.xml +11 -0
- package/quality.schema.json +392 -0
|
@@ -0,0 +1,4522 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* packages/hygiene/src/lib/runner.ts
|
|
4
|
+
* CLI boundary that loads configuration and coordinates repository quality checks.
|
|
5
|
+
*/
|
|
6
|
+
/*//////////////////////////////////////////////////
|
|
7
|
+
IMPORTS
|
|
8
|
+
//////////////////////////////////////////////////*/
|
|
9
|
+
// API
|
|
10
|
+
import ts from 'typescript';
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
// prettier-ignore
|
|
13
|
+
import { accessibilityFindings, displayNameFindings, errorBoundaryFindings, fixAccessibleNames, fixDisplayNames, fixErrorBoundaries, uiComponentRecommendations } from '@terra-symposium/hygiene/ui';
|
|
14
|
+
import { aliasFindings, declarationScope, isCallbackDeclaration, isProtectedPath, isRenamableDeclaration, namingFindings, parameterRenameCapturesDefault, renameDeclaration, renameId, } from '@terra-symposium/hygiene/naming';
|
|
15
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
16
|
+
import { buildGitHubReport, formatGitHubReport, hasGitHubAuth, qualityNodeReporterOptions, writeHistoryReport } from '@terra-symposium/hygiene/reports';
|
|
17
|
+
import { checkImports, duplicateImportFindings, fixDuplicateImports } from '@terra-symposium/hygiene/imports';
|
|
18
|
+
import { collapseInlineIfs, collapseTypesAndObjects } from '@terra-symposium/hygiene/formatting';
|
|
19
|
+
import { createQualityAnalysis, hasGeneratedSourceHeader, nonProgramSrcFiles, QUALITY_CHECK_NAMES, qualityProgress, setQualityProgressSuppressed, srcFiles, workingSrcFiles, } from '@terra-symposium/hygiene/core';
|
|
20
|
+
// prettier-ignore
|
|
21
|
+
import { deadCodeEditsIntroduceTypeErrors, deadCodeTypeProgram, fixObjectForwarding, fixSingleUseDeclarations, objectForwardingFindings, singleUseFindings } from '@terra-symposium/hygiene/refactoring';
|
|
22
|
+
import { documentationFindings, documentedCommandFindings, fixDocumentedCommands } from '@terra-symposium/hygiene/documentation';
|
|
23
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
24
|
+
import { fileURLToPath } from 'node:url';
|
|
25
|
+
import { isBuiltin } from 'node:module';
|
|
26
|
+
import { tmpdir } from 'node:os';
|
|
27
|
+
import { fixRegexDedup, fixRepeatedClasses, performancePatternFindings, regexFindings, repeatedClassFindings, runTailwindCanonical, uiPatternFindings } from '@terra-symposium/hygiene/patterns';
|
|
28
|
+
import { inspectLanguageProfileTool, isLanguageProfileId, resolveLanguageProfiles } from '@terra-symposium/hygiene/languages';
|
|
29
|
+
import { securityFindings } from '@terra-symposium/hygiene/security';
|
|
30
|
+
import { spawnSync } from 'node:child_process';
|
|
31
|
+
// COMPONENTS
|
|
32
|
+
import { Worker } from 'node:worker_threads';
|
|
33
|
+
// DATA
|
|
34
|
+
import { LANGUAGE_CAPABILITIES } from '@terra-symposium/hygiene/languages';
|
|
35
|
+
import { PROTECTED_IDENTIFIERS } from '@terra-symposium/hygiene/naming';
|
|
36
|
+
const BPLAYWRIGHT_B_U_REGEX = /\bplaywright\b/u;
|
|
37
|
+
/*//////////////////////////////////////////////////
|
|
38
|
+
REGEX
|
|
39
|
+
//////////////////////////////////////////////////*/
|
|
40
|
+
const NON_WORKSPACE_DIRS = new Set(['.git', '.next', '.nuxt', '.turbo', '.vercel', '.vite', '.astro', 'build', 'coverage', 'dist', 'node_modules', 'out', 'target', 'vendor']);
|
|
41
|
+
/*//////////////////////////////////////////////////
|
|
42
|
+
REGEX
|
|
43
|
+
//////////////////////////////////////////////////*/
|
|
44
|
+
const R_N_REGEX = /\r?\n/;
|
|
45
|
+
const SHARED_REGEX = /\/\*|\/\//;
|
|
46
|
+
/*//////////////////////////////////////////////////
|
|
47
|
+
REGEX
|
|
48
|
+
//////////////////////////////////////////////////*/
|
|
49
|
+
const CJS_JS_JSX_MJS_TS_TSX_REGEX = /\.(?:cjs|js|jsx|mjs|ts|tsx)$/;
|
|
50
|
+
/**
|
|
51
|
+
* Matches hyphens when normalizing source-derived names.
|
|
52
|
+
*
|
|
53
|
+
* @return A fresh regular expression for matching hyphens.
|
|
54
|
+
*/
|
|
55
|
+
const G_REGEX = () => /-/g;
|
|
56
|
+
const C_M_JS_TS_REGEX = /\.(?:c|m)?(?:js|ts)$/;
|
|
57
|
+
const CLI_CMDS = new Set([
|
|
58
|
+
'quality',
|
|
59
|
+
'history',
|
|
60
|
+
'quality:all',
|
|
61
|
+
'quality:baseline',
|
|
62
|
+
'document',
|
|
63
|
+
'maintain',
|
|
64
|
+
'format',
|
|
65
|
+
'naming',
|
|
66
|
+
'domain',
|
|
67
|
+
'single-use',
|
|
68
|
+
'dead-code',
|
|
69
|
+
'security',
|
|
70
|
+
'repeated-classes',
|
|
71
|
+
'tailwind-canonical',
|
|
72
|
+
'regex-dedup',
|
|
73
|
+
'ui-patterns',
|
|
74
|
+
'ui-recommendations',
|
|
75
|
+
'error-boundaries',
|
|
76
|
+
'imports',
|
|
77
|
+
'aliases',
|
|
78
|
+
'forwarding',
|
|
79
|
+
'documentation',
|
|
80
|
+
'github',
|
|
81
|
+
'lint',
|
|
82
|
+
'knip',
|
|
83
|
+
'types',
|
|
84
|
+
]);
|
|
85
|
+
const CLI_FLAGS = new Set([
|
|
86
|
+
'--all',
|
|
87
|
+
'--warn',
|
|
88
|
+
'--fix',
|
|
89
|
+
'--safe-fix',
|
|
90
|
+
'--strict',
|
|
91
|
+
'--skip-commands',
|
|
92
|
+
'--skip-recommendations',
|
|
93
|
+
'--help',
|
|
94
|
+
'-h',
|
|
95
|
+
'--version',
|
|
96
|
+
'-v',
|
|
97
|
+
'--report-json',
|
|
98
|
+
'--branch',
|
|
99
|
+
'--base-sha',
|
|
100
|
+
'--repository',
|
|
101
|
+
]);
|
|
102
|
+
const TOOL_OUTPUT_MAX_BUFFER = 64 * 1024 * 1024;
|
|
103
|
+
const ESLINT_CONFIG_NAMES = ['eslint.config.js', 'eslint.config.mjs', 'eslint.config.cjs', 'eslint.config.ts', 'eslint.config.mts', 'eslint.config.cts'];
|
|
104
|
+
/**
|
|
105
|
+
* Finds the repository ESLint config, preferring the centralized config directory.
|
|
106
|
+
*
|
|
107
|
+
* @param root Repository root to search first.
|
|
108
|
+
* @param configRoot Directory containing centralized tool configuration.
|
|
109
|
+
*
|
|
110
|
+
* @return Absolute config path or undefined when no flat config exists.
|
|
111
|
+
*/
|
|
112
|
+
function findEslintConfig(root, configRoot = resolve(root, 'config')) {
|
|
113
|
+
return [...ESLINT_CONFIG_NAMES.map(n => resolve(configRoot, n)), ...ESLINT_CONFIG_NAMES.map(n => resolve(root, n))].find(p => existsSync(p));
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Resolves Node's source type from an explicit extension or the nearest package boundary.
|
|
117
|
+
*
|
|
118
|
+
* @param root Repository root containing the source file.
|
|
119
|
+
* @param file Absolute source path.
|
|
120
|
+
*
|
|
121
|
+
* @return Whether the file uses CommonJS semantics.
|
|
122
|
+
*/
|
|
123
|
+
function isCommonJsSrc(root, file) {
|
|
124
|
+
const ext = extname(file);
|
|
125
|
+
if (ext === '.cjs' || ext === '.cts')
|
|
126
|
+
return true;
|
|
127
|
+
if (ext === '.mjs' || ext === '.mts')
|
|
128
|
+
return false;
|
|
129
|
+
let scope = dirname(file);
|
|
130
|
+
while (true) {
|
|
131
|
+
const relativeScope = relative(root, scope);
|
|
132
|
+
if (isAbsolute(relativeScope) || relativeScope === '..' || relativeScope.startsWith(`..${sep}`))
|
|
133
|
+
break;
|
|
134
|
+
const manifest = join(scope, 'package.json');
|
|
135
|
+
if (existsSync(manifest))
|
|
136
|
+
return JSON.parse(readFileSync(manifest, 'utf8')).type !== 'module';
|
|
137
|
+
if (scope === root)
|
|
138
|
+
break;
|
|
139
|
+
scope = dirname(scope);
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Escapes one repository-relative source path for a flat ESLint files pattern.
|
|
145
|
+
*
|
|
146
|
+
* @param root Repository root used to produce the pattern.
|
|
147
|
+
* @param file Absolute source path.
|
|
148
|
+
*
|
|
149
|
+
* @return Exact escaped ESLint pattern for the source file.
|
|
150
|
+
*/
|
|
151
|
+
function eslintFilePattern(root, file) {
|
|
152
|
+
return [...relative(root, file).split(sep).join('/')].map(character => (ESLINT_GLOB_SPECIALS.has(character) ? `\\${character}` : character)).join('');
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Resolves the configured TypeScript project, preferring `configRoot/tsconfig.json` over the root fallback.
|
|
156
|
+
*
|
|
157
|
+
* @param cfg Quality configuration containing repository paths.
|
|
158
|
+
*
|
|
159
|
+
* @return Absolute TypeScript configuration path.
|
|
160
|
+
*/
|
|
161
|
+
function projectTsconfig(cfg) {
|
|
162
|
+
if (cfg.tsconfig)
|
|
163
|
+
return resolve(cfg.root, cfg.tsconfig);
|
|
164
|
+
const candidates = [resolve(cfg.configRoot ?? resolve(cfg.root, 'config'), 'tsconfig.json'), resolve(cfg.root, 'tsconfig.json')];
|
|
165
|
+
return candidates.find(p => existsSync(p)) ?? candidates[0];
|
|
166
|
+
}
|
|
167
|
+
const ESLINT_API_FALLBACK = 78;
|
|
168
|
+
const FOCUSED_ESLINT_FALLBACK = 'HYGIENE_FOCUSED_ESLINT_UNAVAILABLE';
|
|
169
|
+
const ESLINT_GLOB_SPECIALS = new Set(['*', '?', '[', ']', '{', '}', '(', ')', '!', '\\']);
|
|
170
|
+
let reportStages;
|
|
171
|
+
let reportStageName;
|
|
172
|
+
let reportGitHubData;
|
|
173
|
+
let outputPhase;
|
|
174
|
+
let qualityCheckName;
|
|
175
|
+
let qualityDetails = [];
|
|
176
|
+
let qualitySpinner;
|
|
177
|
+
/*//////////////////////////////////////////////////
|
|
178
|
+
REGEX
|
|
179
|
+
//////////////////////////////////////////////////*/
|
|
180
|
+
const C_M_JS_TS_X_REGEX = /\.(?:c|m)?(?:js|ts)x?$/;
|
|
181
|
+
const C_M_JS_TS_X_CLASS_2 = /\.(?:(?:c|m)?(?:js|ts)x?)$/;
|
|
182
|
+
const WORKSPACE_MANIFESTS = new Map();
|
|
183
|
+
// hygiene-ignore single-use -- Compile the ANSI escape matcher once for repeated process output cleanup.
|
|
184
|
+
const ANSI_ESCAPE = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, 'g');
|
|
185
|
+
/*//////////////////////////////////////////////////
|
|
186
|
+
HELPERS
|
|
187
|
+
//////////////////////////////////////////////////*/
|
|
188
|
+
/**
|
|
189
|
+
* Checks whether a built-in quality check is enabled by configuration.
|
|
190
|
+
*
|
|
191
|
+
* @param cfg Quality configuration containing check toggles.
|
|
192
|
+
* @param check Built-in check name to query.
|
|
193
|
+
*
|
|
194
|
+
* @return `true` unless the check is explicitly disabled.
|
|
195
|
+
*/
|
|
196
|
+
export function qualityCheckEnabled(cfg, check) {
|
|
197
|
+
if (check === 'error-boundaries')
|
|
198
|
+
return true;
|
|
199
|
+
if (check === 'accessibility' || check === 'display-name' || check === 'documented-commands')
|
|
200
|
+
return cfg.enabledChecks?.[check] === true;
|
|
201
|
+
return cfg.enabledChecks?.[check] !== false;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Determines whether a check may apply its configured autofix for the current CLI invocation.
|
|
205
|
+
*
|
|
206
|
+
* @param cfg Quality configuration containing autofix toggles.
|
|
207
|
+
* @param check Autofix-capable check name to query.
|
|
208
|
+
* @param cliFix Whether the invocation allows writes.
|
|
209
|
+
*
|
|
210
|
+
* @return `true` when both the invocation and configuration permit autofix.
|
|
211
|
+
*/
|
|
212
|
+
export function qualityAutofixEnabled(cfg, check, cliFix = true) {
|
|
213
|
+
if (check === 'errorBoundaries')
|
|
214
|
+
return cliFix;
|
|
215
|
+
return cliFix && cfg.autofix?.[check] !== false;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Checks whether a configured repository command is enabled.
|
|
219
|
+
*
|
|
220
|
+
* @param cfg Quality configuration containing command toggles.
|
|
221
|
+
* @param name Configured command name to query.
|
|
222
|
+
*
|
|
223
|
+
* @return `true` when command checks and this command are enabled.
|
|
224
|
+
*/
|
|
225
|
+
export function qualityCmdEnabled(cfg, name) {
|
|
226
|
+
return qualityCheckEnabled(cfg, 'command') && cfg.enabledCommands?.[name] !== false;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Checks whether a configured recommendation command is enabled.
|
|
230
|
+
*
|
|
231
|
+
* @param cfg Quality configuration containing recommendation toggles.
|
|
232
|
+
* @param name Recommendation name to query.
|
|
233
|
+
*
|
|
234
|
+
* @return `true` when recommendations and this recommendation are enabled.
|
|
235
|
+
*/
|
|
236
|
+
export function qualityRecommendationEnabled(cfg, name) {
|
|
237
|
+
return qualityCheckEnabled(cfg, 'recommend') && cfg.enabledRecommendations?.[name] !== false;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Loads and normalizes a quality configuration file relative to its project root.
|
|
241
|
+
*
|
|
242
|
+
* @param file Configuration path; defaults to `quality.json` in the current directory.
|
|
243
|
+
*
|
|
244
|
+
* @return Normalized quality configuration with absolute repository paths.
|
|
245
|
+
*/
|
|
246
|
+
export function loadQualityCfg(file) {
|
|
247
|
+
const defaultConfig = resolve(process.cwd(), 'quality.json');
|
|
248
|
+
const path = resolve(file ?? (existsSync(defaultConfig) ? defaultConfig : resolve(process.cwd(), 'config/quality.json')));
|
|
249
|
+
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
250
|
+
const configDir = dirname(path);
|
|
251
|
+
const implicitConfigRoot = basename(configDir) === 'config' ? dirname(configDir) : configDir;
|
|
252
|
+
const root = raw.root ? resolve(implicitConfigRoot, raw.root) : implicitConfigRoot;
|
|
253
|
+
return createQualityCfg({ ...raw, root, configRoot: raw.configRoot ? resolve(root, raw.configRoot) : configDir === implicitConfigRoot ? resolve(root, 'config') : configDir });
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Applies defaults and resolves repository-relative paths in a quality configuration.
|
|
257
|
+
*
|
|
258
|
+
* @param cfg Raw or partially normalized quality configuration.
|
|
259
|
+
*
|
|
260
|
+
* @return Configuration ready for quality checks and subprocess execution.
|
|
261
|
+
*/
|
|
262
|
+
export function createQualityCfg(cfg) {
|
|
263
|
+
const root = resolve(cfg.root);
|
|
264
|
+
const unknownChecks = Object.keys(cfg.enabledChecks ?? {}).filter(check => !QUALITY_CHECK_NAMES.includes(check));
|
|
265
|
+
if (unknownChecks.length)
|
|
266
|
+
throw new Error(`Unknown quality check${unknownChecks.length === 1 ? '' : 's'}: ${unknownChecks.join(', ')}. Available checks: ${QUALITY_CHECK_NAMES.join(', ')}.`);
|
|
267
|
+
const langProfiles = cfg.languageProfiles ?? [];
|
|
268
|
+
if (!Array.isArray(langProfiles))
|
|
269
|
+
throw new Error('languageProfiles must be an array of profile names.');
|
|
270
|
+
for (const profile of langProfiles) {
|
|
271
|
+
if (typeof profile !== 'string' || !isLanguageProfileId(profile))
|
|
272
|
+
throw new Error(`Unknown language profile "${profile}". Available profiles: c, java, python.`);
|
|
273
|
+
}
|
|
274
|
+
if (new Set(langProfiles).size !== langProfiles.length)
|
|
275
|
+
throw new Error('languageProfiles must not contain duplicate profile names.');
|
|
276
|
+
return {
|
|
277
|
+
...cfg,
|
|
278
|
+
languageProfiles: langProfiles,
|
|
279
|
+
renameExports: cfg.renameExports ?? false,
|
|
280
|
+
root,
|
|
281
|
+
configRoot: resolve(root, cfg.configRoot ?? 'config'),
|
|
282
|
+
sourceRoots: cfg.sourceRoots.map(p => resolve(root, p)),
|
|
283
|
+
includeRoots: (cfg.includeRoots ?? []).map(p => resolve(root, p)),
|
|
284
|
+
skippedDirectories: cfg.skippedDirectories ?? [],
|
|
285
|
+
skippedFiles: (cfg.skippedFiles ?? []).map(p => resolve(root, p)),
|
|
286
|
+
singleUse: cfg.singleUse ? { ...cfg.singleUse, skippedDirectories: cfg.singleUse.skippedDirectories ?? [] } : undefined,
|
|
287
|
+
aliases: cfg.aliases ?? {},
|
|
288
|
+
protectedIdentifiers: cfg.protectedIdentifiers ?? [],
|
|
289
|
+
lintRoots: (cfg.lintRoots ?? []).map(p => resolve(root, p)),
|
|
290
|
+
typecheckRoots: (cfg.typecheckRoots ?? []).map(p => resolve(root, p)),
|
|
291
|
+
typecheckCommand: cfg.typecheckCommand,
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Resolves a configured tool name to a repository-local executable when available.
|
|
296
|
+
*
|
|
297
|
+
* @param cfg Quality configuration defining the repository root.
|
|
298
|
+
* @param cfgd Explicit tool path or executable name.
|
|
299
|
+
* @param fallback Default executable name when no tool is configured.
|
|
300
|
+
*
|
|
301
|
+
* @return Executable path or name suitable for spawning.
|
|
302
|
+
*/
|
|
303
|
+
function toolPath(cfg, cfgd, fallback) {
|
|
304
|
+
if (cfgd && (cfgd.includes('/') || cfgd.includes('\\')))
|
|
305
|
+
return isAbsolute(cfgd) ? cfgd : resolve(cfg.root, cfgd);
|
|
306
|
+
const executable = cfgd ?? fallback;
|
|
307
|
+
const local = resolve(cfg.root, 'node_modules', '.bin', executable);
|
|
308
|
+
return existsSync(local) ? local : executable;
|
|
309
|
+
}
|
|
310
|
+
// hygiene-ignore single-use -- Keep the documented canUseLocalEslintApi declaration so its parameter and return contract remains attached.
|
|
311
|
+
/**
|
|
312
|
+
* Checks whether a configured ESLint executable resolves to the repository's package installation.
|
|
313
|
+
*
|
|
314
|
+
* @param cfg Quality configuration containing the repository and tool roots.
|
|
315
|
+
*
|
|
316
|
+
* @return Whether the local ESLint API can preserve the configured tool.
|
|
317
|
+
*/
|
|
318
|
+
function canUseLocalEslintApi(cfg) {
|
|
319
|
+
const configured = cfg.tools?.eslint;
|
|
320
|
+
if (configured === undefined || configured === 'eslint')
|
|
321
|
+
return true;
|
|
322
|
+
return [resolve(cfg.root, 'node_modules', '.bin', 'eslint'), resolve(cfg.configRoot ?? resolve(cfg.root, 'config'), 'node_modules', '.bin', 'eslint')].includes(resolve(cfg.root, configured));
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Formats one check identifier for terminal output.
|
|
326
|
+
*
|
|
327
|
+
* @param name Internal quality check identifier.
|
|
328
|
+
*
|
|
329
|
+
* @return Readable check name.
|
|
330
|
+
*/
|
|
331
|
+
function qualityLabel(name) {
|
|
332
|
+
const key = name.replace(/^(?:command|recommendation):/u, '').replace(/^dead-code\//u, '');
|
|
333
|
+
const labels = {
|
|
334
|
+
accessibility: 'Accessibility',
|
|
335
|
+
aliases: 'Aliases',
|
|
336
|
+
'dead-code': 'Dead Code',
|
|
337
|
+
documentation: 'Documentation',
|
|
338
|
+
'documented-commands': 'Documented Commands',
|
|
339
|
+
forwarding: 'Forwarding',
|
|
340
|
+
'performance-patterns': 'Performance Patterns',
|
|
341
|
+
'repeated-classes': 'Repeated Classes',
|
|
342
|
+
'regex-dedup': 'Regex Dedup',
|
|
343
|
+
'source-analysis': 'Source Analysis',
|
|
344
|
+
'tailwind-canonical': 'Tailwind Canonical',
|
|
345
|
+
typecheck: 'Typecheck',
|
|
346
|
+
'ui-patterns': 'UI Patterns',
|
|
347
|
+
'ui-recommendations': 'UI Recommendations',
|
|
348
|
+
'error-boundaries': 'React Error Boundaries',
|
|
349
|
+
};
|
|
350
|
+
if (labels[key])
|
|
351
|
+
return labels[key];
|
|
352
|
+
return key.replace(/(^|[-/\s])([a-z])/gu, (_match, s, l) => `${s === '-' || s === '/' ? ' ' : s}${l.toUpperCase()}`).replace(/\bEslint\b/gu, 'ESLint');
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Starts the spinner and records the active check for a full quality run.
|
|
356
|
+
*
|
|
357
|
+
* @param name Internal quality check identifier.
|
|
358
|
+
* @param detail Human-readable description for non-full output.
|
|
359
|
+
*
|
|
360
|
+
* @return Nothing; full output starts the check's terminal spinner.
|
|
361
|
+
*/
|
|
362
|
+
function qualityHeader(name, detail) {
|
|
363
|
+
if (reportStages) {
|
|
364
|
+
reportStageName = name;
|
|
365
|
+
reportStages.set(name, { name, status: 'passed', findings: 0 });
|
|
366
|
+
}
|
|
367
|
+
if (outputPhase) {
|
|
368
|
+
if (outputPhase === 'PREPARING SAFE FIXES' || name.includes('/'))
|
|
369
|
+
return;
|
|
370
|
+
qualityCheckName = qualityLabel(name);
|
|
371
|
+
qualityDetails = [];
|
|
372
|
+
startQualitySpinner(qualityCheckName);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
console.error(`\n=== ${name} ===`);
|
|
376
|
+
console.error(detail);
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Reports whether a named quality check completed cleanly or found issues.
|
|
380
|
+
*
|
|
381
|
+
* @param name Check identifier used by the quality runner.
|
|
382
|
+
* @param findings Number of findings produced by the check.
|
|
383
|
+
*
|
|
384
|
+
* @return Nothing; a concise completion line is written to standard error.
|
|
385
|
+
*/
|
|
386
|
+
function printCheckStatus(name, findings) {
|
|
387
|
+
if (!outputPhase || outputPhase === 'PREPARING SAFE FIXES')
|
|
388
|
+
return;
|
|
389
|
+
stopQualitySpinner();
|
|
390
|
+
console.error(` ${findings ? '✗' : '✓'} ${qualityLabel(name)}`);
|
|
391
|
+
printQualityDetails();
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Ends a skipped check's spinner and writes its status.
|
|
395
|
+
*
|
|
396
|
+
* @param name Internal quality check identifier.
|
|
397
|
+
*
|
|
398
|
+
* @return Nothing; the skipped status is written to standard error.
|
|
399
|
+
*/
|
|
400
|
+
function printSkippedCheckStatus(name) {
|
|
401
|
+
if (!outputPhase || outputPhase === 'PREPARING SAFE FIXES')
|
|
402
|
+
return;
|
|
403
|
+
stopQualitySpinner();
|
|
404
|
+
console.error(` ↷ ${qualityLabel(name)}`);
|
|
405
|
+
printQualityDetails();
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Starts a terminal spinner outside the blocked main JavaScript thread.
|
|
409
|
+
*
|
|
410
|
+
* @param label Readable check name shown in the terminal.
|
|
411
|
+
*
|
|
412
|
+
* @return Nothing; interactive terminals receive animated frames.
|
|
413
|
+
*/
|
|
414
|
+
function startQualitySpinner(label) {
|
|
415
|
+
if (!process.stderr.isTTY) {
|
|
416
|
+
console.error(` ⠋ ${label}`);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const state = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * 3));
|
|
420
|
+
const worker = new Worker(new URL('./spinner-worker.js', import.meta.url), { workerData: { label, sharedBuffer: state.buffer } });
|
|
421
|
+
worker.unref();
|
|
422
|
+
if (Atomics.wait(state, 1, 0, 1000) === 'timed-out') {
|
|
423
|
+
void worker.terminate();
|
|
424
|
+
console.error(` ⠋ ${label}`);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
qualitySpinner = { worker, state };
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Stops the active spinner and clears its terminal line.
|
|
431
|
+
*
|
|
432
|
+
* @return Nothing; the check status can be written on a clean line.
|
|
433
|
+
*/
|
|
434
|
+
function stopQualitySpinner() {
|
|
435
|
+
const spinner = qualitySpinner;
|
|
436
|
+
if (!spinner)
|
|
437
|
+
return;
|
|
438
|
+
qualitySpinner = undefined;
|
|
439
|
+
Atomics.store(spinner.state, 0, 1);
|
|
440
|
+
Atomics.notify(spinner.state, 0);
|
|
441
|
+
if (Atomics.wait(spinner.state, 2, 0, 1000) === 'timed-out')
|
|
442
|
+
void spinner.worker.terminate();
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Buffers one diagnostic as a bullet under the active quality check.
|
|
446
|
+
*
|
|
447
|
+
* @param detail Diagnostic text to show below the check status.
|
|
448
|
+
*
|
|
449
|
+
* @return Nothing; text is buffered during a full quality run.
|
|
450
|
+
*/
|
|
451
|
+
function recordQualityDetail(detail) {
|
|
452
|
+
if (!outputPhase) {
|
|
453
|
+
for (const line of compactOutput(detail))
|
|
454
|
+
console.error(` ${line}`);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
if (!qualityCheckName)
|
|
458
|
+
qualityCheckName = 'Quality Runner';
|
|
459
|
+
qualityDetails.push(...compactOutput(detail).map(l => ` - ${l.trim().replace(/^[-•]\s*/u, '')}`));
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Prints and clears the active check's buffered diagnostic bullets.
|
|
463
|
+
*
|
|
464
|
+
* @return Nothing; buffered details are written to standard error.
|
|
465
|
+
*/
|
|
466
|
+
function printQualityDetails() {
|
|
467
|
+
for (const detail of qualityDetails)
|
|
468
|
+
console.error(detail);
|
|
469
|
+
qualityDetails = [];
|
|
470
|
+
qualityCheckName = undefined;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Records one failed check and keeps its complete diagnostic under that check.
|
|
474
|
+
*
|
|
475
|
+
* @param name Check identifier used by the quality runner.
|
|
476
|
+
* @param err Error thrown by the check.
|
|
477
|
+
*/
|
|
478
|
+
function recordQualityFailure(name, err) {
|
|
479
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
480
|
+
const stage = reportStages?.get(name);
|
|
481
|
+
if (stage)
|
|
482
|
+
stage.status = 'failed';
|
|
483
|
+
process.exitCode = 1;
|
|
484
|
+
if (outputPhase) {
|
|
485
|
+
if (!qualityCheckName) {
|
|
486
|
+
qualityCheckName = qualityLabel(name);
|
|
487
|
+
startQualitySpinner(qualityCheckName);
|
|
488
|
+
}
|
|
489
|
+
recordQualityDetail(detail);
|
|
490
|
+
}
|
|
491
|
+
else
|
|
492
|
+
console.error(`${qualityLabel(name)}: ${detail}`);
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Runs an independent action and records its error without interrupting later checks.
|
|
496
|
+
*
|
|
497
|
+
* @param name Check identifier used if the action throws.
|
|
498
|
+
* @param action Check action to run.
|
|
499
|
+
*
|
|
500
|
+
* @return Whether the action completed without throwing.
|
|
501
|
+
*/
|
|
502
|
+
function continueAfterFailure(name, action) {
|
|
503
|
+
try {
|
|
504
|
+
action();
|
|
505
|
+
return true;
|
|
506
|
+
}
|
|
507
|
+
catch (err) {
|
|
508
|
+
recordQualityFailure(name, err);
|
|
509
|
+
printCheckStatus(name, 1);
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Starts one fixed output phase for the full quality command.
|
|
515
|
+
*
|
|
516
|
+
* @param phase Phase heading owned by the Quality runner.
|
|
517
|
+
*
|
|
518
|
+
* @return Nothing; the heading is written once before the phase checks.
|
|
519
|
+
*/
|
|
520
|
+
function beginQualityPhase(phase) {
|
|
521
|
+
outputPhase = phase;
|
|
522
|
+
console.error(`\n${phase.toUpperCase()}`);
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Finds package manifests once so filtered workspace scripts can be classified.
|
|
526
|
+
*
|
|
527
|
+
* @param root Repository root whose package scripts are selected.
|
|
528
|
+
*
|
|
529
|
+
* @return Workspace package manifests outside generated and dependency directories.
|
|
530
|
+
*/
|
|
531
|
+
function workspaceManifests(root) {
|
|
532
|
+
const cached = WORKSPACE_MANIFESTS.get(root);
|
|
533
|
+
if (cached)
|
|
534
|
+
return cached;
|
|
535
|
+
const manifests = [];
|
|
536
|
+
/**
|
|
537
|
+
* Recursively discovers package manifests while skipping generated directories.
|
|
538
|
+
*
|
|
539
|
+
* @param dir Directory whose package manifests are being discovered.
|
|
540
|
+
*/
|
|
541
|
+
const visit = (dir) => {
|
|
542
|
+
let entries;
|
|
543
|
+
try {
|
|
544
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
545
|
+
}
|
|
546
|
+
catch {
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
for (const entry of entries) {
|
|
550
|
+
const path = resolve(dir, entry.name);
|
|
551
|
+
if (entry.isDirectory()) {
|
|
552
|
+
if (!NON_WORKSPACE_DIRS.has(entry.name) && !entry.name.startsWith('.'))
|
|
553
|
+
visit(path);
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
if (entry.name !== 'package.json' || !entry.isFile())
|
|
557
|
+
continue;
|
|
558
|
+
try {
|
|
559
|
+
const pkg = JSON.parse(readFileSync(path, 'utf8'));
|
|
560
|
+
manifests.push({ directory: dir, ...(typeof pkg.name === 'string' ? { name: pkg.name } : {}), scripts: pkg.scripts ?? {} });
|
|
561
|
+
}
|
|
562
|
+
catch {
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
visit(root);
|
|
568
|
+
WORKSPACE_MANIFESTS.set(root, manifests);
|
|
569
|
+
return manifests;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Finds the selected package script name without treating option values as check names.
|
|
573
|
+
*
|
|
574
|
+
* @param check Configured command whose arguments may select a package script.
|
|
575
|
+
*
|
|
576
|
+
* @return Script name for `run`, `run-script`, or a direct package-manager script command.
|
|
577
|
+
*/
|
|
578
|
+
function scriptNameForInvocation(check) {
|
|
579
|
+
const args = check.args ?? [];
|
|
580
|
+
const runIdx = args.findIndex(a => a === 'run' || a === 'run-script');
|
|
581
|
+
if (runIdx >= 0)
|
|
582
|
+
return args[runIdx + 1] ?? '';
|
|
583
|
+
if (!/^(?:pnpm|npm|yarn|bun)(?:\.cmd)?$/iu.test(basename(check.command)))
|
|
584
|
+
return '';
|
|
585
|
+
for (let idx = 0; idx < args.length; idx++) {
|
|
586
|
+
const arg = args[idx];
|
|
587
|
+
if (arg === '--filter') {
|
|
588
|
+
idx++;
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
if (arg.startsWith('--')) {
|
|
592
|
+
if (arg === '--workspace-concurrency' || arg === '--reporter' || arg === '--dir')
|
|
593
|
+
idx++;
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
if (arg.startsWith('-'))
|
|
597
|
+
continue;
|
|
598
|
+
return arg;
|
|
599
|
+
}
|
|
600
|
+
return '';
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Matches an exact workspace name or a simple repository-relative package filter.
|
|
604
|
+
*
|
|
605
|
+
* @param root Repository root that owns workspace package paths.
|
|
606
|
+
* @param selector Package name or path expression following `--filter`.
|
|
607
|
+
* @param manifest Candidate workspace package metadata.
|
|
608
|
+
*
|
|
609
|
+
* @return Whether the selector can be matched to this package without guessing.
|
|
610
|
+
*/
|
|
611
|
+
function matchesWorkspaceFilter(root, selector, manifest) {
|
|
612
|
+
const packageSelector = selector.replace(/^\.\.\./u, '').replace(/\.\.\.$/u, '');
|
|
613
|
+
if (!(packageSelector.startsWith('.') || (!packageSelector.startsWith('@') && packageSelector.includes('/'))))
|
|
614
|
+
return manifest.name === packageSelector;
|
|
615
|
+
const packagePath = resolve(root, packageSelector.replace(/^\.\//u, '').replace(/\*.*$/u, '').replace(/\/$/u, '') || '.');
|
|
616
|
+
if (!/[*?{[]/u.test(packageSelector))
|
|
617
|
+
return manifest.directory === packagePath;
|
|
618
|
+
const relativePackage = relative(packagePath, manifest.directory);
|
|
619
|
+
if (relativePackage === '..' || relativePackage.startsWith(`..${sep}`) || isAbsolute(relativePackage))
|
|
620
|
+
return false;
|
|
621
|
+
if (packageSelector.includes('**'))
|
|
622
|
+
return true;
|
|
623
|
+
return !relativePackage.includes(sep);
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Reads one display string for the command and its selected package script.
|
|
627
|
+
*
|
|
628
|
+
* @param cfg Quality configuration containing the repository root.
|
|
629
|
+
* @param check Configured command to describe.
|
|
630
|
+
*
|
|
631
|
+
* @return Lowercase command and script text; free-form argument values are excluded.
|
|
632
|
+
*/
|
|
633
|
+
function invocationText(cfg, check) {
|
|
634
|
+
return `${check.name} ${check.command} ${scriptNameForInvocation(check)} ${(function scriptsForInvocation(cfg, check) {
|
|
635
|
+
const scriptName = scriptNameForInvocation(check);
|
|
636
|
+
if (!scriptName)
|
|
637
|
+
return [];
|
|
638
|
+
const selectors = (function workspaceFilters(check) {
|
|
639
|
+
const args = check.args ?? [];
|
|
640
|
+
const selectors = [];
|
|
641
|
+
for (let idx = 0; idx < args.length; idx++) {
|
|
642
|
+
const arg = args[idx];
|
|
643
|
+
if (arg === '--filter' && args[idx + 1])
|
|
644
|
+
selectors.push(args[++idx]);
|
|
645
|
+
else if (arg.startsWith('--filter='))
|
|
646
|
+
selectors.push(arg.slice('--filter='.length));
|
|
647
|
+
}
|
|
648
|
+
return selectors;
|
|
649
|
+
})(check);
|
|
650
|
+
return (selectors.length ? workspaceManifests(cfg.root).filter(m => selectors.some(s => matchesWorkspaceFilter(cfg.root, s, m))) : workspaceManifests(cfg.root).filter(m => m.directory === cfg.root))
|
|
651
|
+
.map(m => m.scripts[scriptName])
|
|
652
|
+
.filter((s) => typeof s === 'string');
|
|
653
|
+
})(cfg, check).join(' ')}`.toLowerCase();
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Assigns a configured command to the fixed runner phase order.
|
|
657
|
+
*
|
|
658
|
+
* @param cfg Quality configuration containing repository commands.
|
|
659
|
+
* @param check Configured command to classify.
|
|
660
|
+
*
|
|
661
|
+
* @return The output and execution phase selected by Terra Quality.
|
|
662
|
+
*/
|
|
663
|
+
function phaseForInvocation(cfg, check) {
|
|
664
|
+
if (check.phase)
|
|
665
|
+
return check.phase;
|
|
666
|
+
const text = invocationText(cfg, check);
|
|
667
|
+
if ((function isTestInvocation(cfg, check) {
|
|
668
|
+
return (testRunner(cfg, check) !== 'unknown' ||
|
|
669
|
+
/\b(?:test|tests|spec|specs|playwright|vitest|jest|mocha|e2e|contract|integration)\b/u.test(invocationText(cfg, check)) ||
|
|
670
|
+
(check.args ?? []).some(a => a === '--test' || a.startsWith('--test=')));
|
|
671
|
+
})(cfg, check))
|
|
672
|
+
return 'Tests';
|
|
673
|
+
if (/\b(?:format|prettier)\b/u.test(text))
|
|
674
|
+
return 'Format';
|
|
675
|
+
if (/\b(?:typecheck|type-check|types|tsc|astro\s+check)\b/u.test(text))
|
|
676
|
+
return 'Framework / type checks';
|
|
677
|
+
if (/\b(?:build|compile|bundle)\b/u.test(text))
|
|
678
|
+
return 'Build';
|
|
679
|
+
if (/\b(?:github|diff|repository-health|repo-health)\b/u.test(text))
|
|
680
|
+
return 'Repository health';
|
|
681
|
+
return 'Static quality';
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Identifies the runner family for configured test-command reporting.
|
|
685
|
+
*
|
|
686
|
+
* @param cfg Quality configuration containing repository commands.
|
|
687
|
+
* @param check Configured test command to classify.
|
|
688
|
+
*
|
|
689
|
+
* @return Node, Playwright, or unknown when the runner cannot be inferred safely.
|
|
690
|
+
*/
|
|
691
|
+
function testRunner(cfg, check) {
|
|
692
|
+
const text = invocationText(cfg, check);
|
|
693
|
+
const args = check.args ?? [];
|
|
694
|
+
if (BPLAYWRIGHT_B_U_REGEX.test(text) || /\bplaywright\b/iu.test(args.join(' ')))
|
|
695
|
+
return 'playwright';
|
|
696
|
+
if ((/^(?:node|node\.exe)$/iu.test(basename(check.command)) && (args.some(a => a === '--test' || a.startsWith('--test=')) || args.some(a => /\.(?:mjs|cjs)$/iu.test(a)))) ||
|
|
697
|
+
/\bworkspace-test-runner\.js\b/u.test(text) ||
|
|
698
|
+
/\bnode\s+[^\n]*--test\b/u.test(text) ||
|
|
699
|
+
/\bpnpm\s+-r\s+test\b/u.test(text))
|
|
700
|
+
return 'node';
|
|
701
|
+
return 'unknown';
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Converts tool output into compact single-line messages without terminal control codes.
|
|
705
|
+
*
|
|
706
|
+
* @param val Raw child-process output.
|
|
707
|
+
*
|
|
708
|
+
* @return Output lines with ANSI codes removed and whitespace normalized.
|
|
709
|
+
*/
|
|
710
|
+
function compactOutput(val) {
|
|
711
|
+
return val
|
|
712
|
+
.replace(ANSI_ESCAPE, '')
|
|
713
|
+
.split(R_N_REGEX)
|
|
714
|
+
.map(l => l.replace(/\s+/g, ' ').trim())
|
|
715
|
+
.filter(Boolean);
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Prints one-line output emitted by a quality subprocess.
|
|
719
|
+
*
|
|
720
|
+
* @param val Raw child-process output.
|
|
721
|
+
*
|
|
722
|
+
* @return Nothing; each non-empty output line is printed once.
|
|
723
|
+
*/
|
|
724
|
+
function printChildOutput(val) {
|
|
725
|
+
if (!val)
|
|
726
|
+
return;
|
|
727
|
+
for (const line of compactOutput(val.toString()))
|
|
728
|
+
console.error(` ${line}`);
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Runs one subprocess from the configured repository root and returns its exit status.
|
|
732
|
+
*
|
|
733
|
+
* @param cfg Quality configuration defining the subprocess working directory.
|
|
734
|
+
* @param cmd Executable path or command name.
|
|
735
|
+
* @param args Arguments passed to the executable.
|
|
736
|
+
* @param opts Optional output policy; successful output can be suppressed for autofix passes.
|
|
737
|
+
*
|
|
738
|
+
* @return Child-process exit status, or `1` when spawning fails without a status.
|
|
739
|
+
*/
|
|
740
|
+
function run(cfg, cmd, args, opts = {}) {
|
|
741
|
+
const result = spawnSync(cmd, args, { cwd: cfg.root, stdio: ['inherit', 'pipe', 'pipe'], env: process.env, maxBuffer: TOOL_OUTPUT_MAX_BUFFER });
|
|
742
|
+
const status = result.status ?? 1;
|
|
743
|
+
if (result.status && reportStages && reportStageName) {
|
|
744
|
+
const stage = reportStages.get(reportStageName);
|
|
745
|
+
if (stage)
|
|
746
|
+
stage.status = 'failed';
|
|
747
|
+
}
|
|
748
|
+
if (outputPhase && status) {
|
|
749
|
+
const output = [...compactOutput(result.stdout?.toString() ?? ''), ...compactOutput(result.stderr?.toString() ?? '')];
|
|
750
|
+
recordQualityDetail(`${basename(cmd)} failed (exit ${status})`);
|
|
751
|
+
for (const line of output)
|
|
752
|
+
recordQualityDetail(line);
|
|
753
|
+
}
|
|
754
|
+
else if (!outputPhase && (!opts.quietSuccess || status)) {
|
|
755
|
+
printChildOutput(result.stdout);
|
|
756
|
+
printChildOutput(result.stderr);
|
|
757
|
+
}
|
|
758
|
+
if (result.error) {
|
|
759
|
+
const msg = `${cmd} failed: ${result.error.message}`;
|
|
760
|
+
if (outputPhase)
|
|
761
|
+
recordQualityDetail(msg);
|
|
762
|
+
else
|
|
763
|
+
console.error(` ${msg}`);
|
|
764
|
+
}
|
|
765
|
+
return status;
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Runs one selected test command with shared case reporting when its runner is known.
|
|
769
|
+
*
|
|
770
|
+
* @param cfg Quality configuration defining the repository root.
|
|
771
|
+
* @param check Test command selected by quality.json.
|
|
772
|
+
*
|
|
773
|
+
* @return Exit status and captured output for this check's detail list.
|
|
774
|
+
*/
|
|
775
|
+
function runTestSuite(cfg, check) {
|
|
776
|
+
const runner = testRunner(cfg, check);
|
|
777
|
+
const args = [...(check.args ?? [])];
|
|
778
|
+
const env = { ...process.env };
|
|
779
|
+
if (runner === 'node') {
|
|
780
|
+
env.NODE_OPTIONS = qualityNodeReporterOptions(env.NODE_OPTIONS, new URL('./node-reporter.js', import.meta.url).href);
|
|
781
|
+
env.HYGIENE_NODE_REPORTER_OWNER = '1';
|
|
782
|
+
args.splice(0, args.length, ...(function withoutNodeReporterArgs(args) {
|
|
783
|
+
const retained = [];
|
|
784
|
+
for (let idx = 0; idx < args.length; idx++) {
|
|
785
|
+
const arg = args[idx];
|
|
786
|
+
if (arg === '--test-reporter' || arg === '--test-reporter-destination') {
|
|
787
|
+
idx++;
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
if (arg.startsWith('--test-reporter=') || arg.startsWith('--test-reporter-destination='))
|
|
791
|
+
continue;
|
|
792
|
+
retained.push(arg);
|
|
793
|
+
}
|
|
794
|
+
return retained;
|
|
795
|
+
})(args));
|
|
796
|
+
}
|
|
797
|
+
else if (runner === 'playwright') {
|
|
798
|
+
const reporterArg = `--reporter=${resolve(dirname(fileURLToPath(import.meta.url)), 'playwright-reporter.js')}`;
|
|
799
|
+
const selectedArgs = [];
|
|
800
|
+
for (let idx = 0; idx < args.length; idx++) {
|
|
801
|
+
const arg = args[idx];
|
|
802
|
+
if (arg === '--reporter') {
|
|
803
|
+
idx++;
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
if (!arg.startsWith('--reporter='))
|
|
807
|
+
selectedArgs.push(arg);
|
|
808
|
+
}
|
|
809
|
+
args.splice(0, args.length, ...selectedArgs);
|
|
810
|
+
if (/\b(?:pnpm|npm|yarn)\b/u.test(check.command) && args.some(a => a === 'run' || a === 'run-script')) {
|
|
811
|
+
if (!args.includes('--'))
|
|
812
|
+
args.push('--');
|
|
813
|
+
args.push(reporterArg);
|
|
814
|
+
}
|
|
815
|
+
else {
|
|
816
|
+
const separator = args.indexOf('--');
|
|
817
|
+
if (separator < 0)
|
|
818
|
+
args.push(reporterArg);
|
|
819
|
+
else
|
|
820
|
+
args.splice(separator, 0, reporterArg);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
qualityHeader(`command:${check.name}`, '');
|
|
824
|
+
let status = 1;
|
|
825
|
+
let output = [];
|
|
826
|
+
try {
|
|
827
|
+
const result = spawnSync(check.command, args, { cwd: cfg.root, stdio: ['inherit', 'pipe', 'pipe'], env, maxBuffer: TOOL_OUTPUT_MAX_BUFFER });
|
|
828
|
+
output = [...compactOutput(result.stdout?.toString() ?? ''), ...compactOutput(result.stderr?.toString() ?? '')];
|
|
829
|
+
if (result.error)
|
|
830
|
+
output.push(result.error.message);
|
|
831
|
+
status = result.status ?? 1;
|
|
832
|
+
}
|
|
833
|
+
catch (err) {
|
|
834
|
+
output.push(err instanceof Error ? err.message : String(err));
|
|
835
|
+
}
|
|
836
|
+
if (reportStages && reportStageName) {
|
|
837
|
+
const stage = reportStages.get(reportStageName);
|
|
838
|
+
if (stage && status)
|
|
839
|
+
stage.status = 'failed';
|
|
840
|
+
}
|
|
841
|
+
if (status) {
|
|
842
|
+
process.exitCode = 1;
|
|
843
|
+
if (outputPhase) {
|
|
844
|
+
recordQualityDetail(`Command failed (exit ${status})`);
|
|
845
|
+
for (const line of output)
|
|
846
|
+
recordQualityDetail(line);
|
|
847
|
+
}
|
|
848
|
+
else
|
|
849
|
+
for (const line of output)
|
|
850
|
+
console.error(` ${line}`);
|
|
851
|
+
}
|
|
852
|
+
else if (!outputPhase)
|
|
853
|
+
for (const line of output)
|
|
854
|
+
console.error(` ${line}`);
|
|
855
|
+
printCheckStatus(check.name, status ? 1 : 0);
|
|
856
|
+
return { status, output };
|
|
857
|
+
}
|
|
858
|
+
// hygiene-ignore single-use -- Keep the documented runQualityPhase declaration so its parameter and return contract remains attached.
|
|
859
|
+
/**
|
|
860
|
+
* Runs configured and profile-provided checks assigned to one fixed phase.
|
|
861
|
+
*
|
|
862
|
+
* @param cfg Quality configuration containing the repository root and command toggles.
|
|
863
|
+
* @param phase Fixed Quality runner phase to execute.
|
|
864
|
+
* @param profileChecks Native profile checks resolved for this full quality run.
|
|
865
|
+
* @param toolResults Cached native-tool version probes shared across profile checks.
|
|
866
|
+
*
|
|
867
|
+
* @return Number of commands that failed in this phase.
|
|
868
|
+
*/
|
|
869
|
+
function runQualityPhase(cfg, phase, profileChecks, toolResults) {
|
|
870
|
+
const cmds = (function qualityInvocations(cfg, profileChecks) {
|
|
871
|
+
const configured = cfg.qualityCommands ?? [];
|
|
872
|
+
const profileNames = new Set(profileChecks.map(c => c.name));
|
|
873
|
+
const configuredByName = new Map(configured.map(c => [c.name, c]));
|
|
874
|
+
return [
|
|
875
|
+
...profileChecks.map((c) => {
|
|
876
|
+
const override = configuredByName.get(c.name);
|
|
877
|
+
return override
|
|
878
|
+
? { ...override, phase: c.phase, profileId: c.profileId, qualityChecks: c.qualityChecks }
|
|
879
|
+
: { name: c.name, command: c.command, args: c.args, phase: c.phase, profileId: c.profileId, profileTool: c.tool, qualityChecks: c.qualityChecks };
|
|
880
|
+
}),
|
|
881
|
+
...configured.filter(c => !profileNames.has(c.name)),
|
|
882
|
+
];
|
|
883
|
+
})(cfg, profileChecks).filter(c => qualityCmdEnabled(cfg, c.name) && phaseForInvocation(cfg, c) === phase);
|
|
884
|
+
/**
|
|
885
|
+
* Checks and caches the required tool for a configured language profile.
|
|
886
|
+
*
|
|
887
|
+
* @param check Quality invocation or check being evaluated.
|
|
888
|
+
*/
|
|
889
|
+
const requireProfileTool = (check) => {
|
|
890
|
+
if (!check.profileTool)
|
|
891
|
+
return;
|
|
892
|
+
const toolKey = JSON.stringify([check.profileTool.command, check.profileTool.versionArgs, check.profileTool.minimumVersion]);
|
|
893
|
+
let toolResult = toolResults.get(toolKey);
|
|
894
|
+
if (!toolResult) {
|
|
895
|
+
toolResult = inspectLanguageProfileTool(check.profileTool, cfg.root);
|
|
896
|
+
toolResults.set(toolKey, toolResult);
|
|
897
|
+
}
|
|
898
|
+
if (toolResult.error)
|
|
899
|
+
throw new Error(toolResult.error);
|
|
900
|
+
};
|
|
901
|
+
let failures = 0;
|
|
902
|
+
if (phase === 'Tests') {
|
|
903
|
+
const suites = (function uniqueTestSuites(checks) {
|
|
904
|
+
const seen = new Set();
|
|
905
|
+
/**
|
|
906
|
+
* Orders test commands so unit and integration checks run before broader suites.
|
|
907
|
+
*
|
|
908
|
+
* @param check Quality invocation or check being evaluated.
|
|
909
|
+
*
|
|
910
|
+
* @return Priority rank used to order the selected test commands.
|
|
911
|
+
*/
|
|
912
|
+
const rank = (check) => {
|
|
913
|
+
const name = check.name.toLowerCase();
|
|
914
|
+
if (/\bunit\b/u.test(name))
|
|
915
|
+
return 0;
|
|
916
|
+
if (/\bintegration\b/u.test(name))
|
|
917
|
+
return 1;
|
|
918
|
+
if (/\b(?:browser|e2e|playwright)\b/u.test(name) || BPLAYWRIGHT_B_U_REGEX.test([check.command, ...(check.args ?? [])].join(' ')))
|
|
919
|
+
return 2;
|
|
920
|
+
return 3;
|
|
921
|
+
};
|
|
922
|
+
return checks
|
|
923
|
+
.filter(c => {
|
|
924
|
+
const key = JSON.stringify([c.command, c.args ?? []]);
|
|
925
|
+
if (seen.has(key))
|
|
926
|
+
return false;
|
|
927
|
+
seen.add(key);
|
|
928
|
+
return true;
|
|
929
|
+
})
|
|
930
|
+
.sort((l, r) => rank(l) - rank(r));
|
|
931
|
+
})(cmds);
|
|
932
|
+
for (const check of suites) {
|
|
933
|
+
try {
|
|
934
|
+
requireProfileTool(check);
|
|
935
|
+
if (runTestSuite(cfg, check).status)
|
|
936
|
+
failures += 1;
|
|
937
|
+
}
|
|
938
|
+
catch (error) {
|
|
939
|
+
failures += 1;
|
|
940
|
+
recordQualityFailure(`command:${check.name}`, error);
|
|
941
|
+
printCheckStatus(check.name, 1);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
return failures;
|
|
945
|
+
}
|
|
946
|
+
for (const check of cmds) {
|
|
947
|
+
qualityHeader(`command:${check.name}`, '');
|
|
948
|
+
let status = 1;
|
|
949
|
+
try {
|
|
950
|
+
requireProfileTool(check);
|
|
951
|
+
status = run(cfg, check.command, [...(check.args ?? [])].flatMap(a => {
|
|
952
|
+
if (a !== '{classes}')
|
|
953
|
+
return [a];
|
|
954
|
+
const classes = [resolve(cfg.root, 'target/classes'), resolve(cfg.root, 'build/classes/java/main')].filter(p => existsSync(p) && statSync(p).isDirectory());
|
|
955
|
+
if (!classes.length)
|
|
956
|
+
throw new Error('SpotBugs requires compiled Java classes. Configure a build command before repository health checks or override java-spotbugs for the project.');
|
|
957
|
+
return classes;
|
|
958
|
+
}));
|
|
959
|
+
}
|
|
960
|
+
catch (error) {
|
|
961
|
+
recordQualityFailure(`command:${check.name}`, error);
|
|
962
|
+
}
|
|
963
|
+
if (status) {
|
|
964
|
+
failures += 1;
|
|
965
|
+
process.exitCode = 1;
|
|
966
|
+
}
|
|
967
|
+
printCheckStatus(`command:${check.name}`, status ? 1 : 0);
|
|
968
|
+
}
|
|
969
|
+
return failures;
|
|
970
|
+
}
|
|
971
|
+
// hygiene-ignore single-use -- Keep the documented reportSkippedLangChecks declaration so its parameter and return contract remains attached.
|
|
972
|
+
/**
|
|
973
|
+
* Records selected profile checks that cannot run because their source or optional config is absent.
|
|
974
|
+
*
|
|
975
|
+
* @param cfg Repository configuration controlling individual command toggles.
|
|
976
|
+
* @param skipped Profile checks and their source-discovery reasons.
|
|
977
|
+
*
|
|
978
|
+
* @return Nothing; terminal output and an optional JSON report mark each check skipped.
|
|
979
|
+
*/
|
|
980
|
+
function reportSkippedLangChecks(cfg, skipped) {
|
|
981
|
+
for (const check of skipped) {
|
|
982
|
+
if (!qualityCmdEnabled(cfg, check.name))
|
|
983
|
+
continue;
|
|
984
|
+
const name = `command:${check.name}`;
|
|
985
|
+
if (reportStages)
|
|
986
|
+
reportStages.set(name, { name, status: 'skipped', findings: 0, reason: check.reason });
|
|
987
|
+
console.error(` ↷ ${qualityLabel(check.name)} skipped: ${check.reason}.`);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
// hygiene-ignore single-use -- Keep the documented reportFailedLangChecks declaration so its parameter and return contract remains attached.
|
|
991
|
+
/**
|
|
992
|
+
* Marks required profile configuration failures without stopping unrelated checks.
|
|
993
|
+
*
|
|
994
|
+
* @param cfg Quality configuration that defines this check and its repository scope.
|
|
995
|
+
* @param failed Language-profile checks that could not be configured.
|
|
996
|
+
*/
|
|
997
|
+
function reportFailedLangChecks(cfg, failed) {
|
|
998
|
+
for (const check of failed) {
|
|
999
|
+
if (!qualityCmdEnabled(cfg, check.name))
|
|
1000
|
+
continue;
|
|
1001
|
+
const name = `command:${check.name}`;
|
|
1002
|
+
if (reportStages)
|
|
1003
|
+
reportStages.set(name, { name, status: 'failed', findings: 1, reason: check.reason });
|
|
1004
|
+
process.exitCode = 1;
|
|
1005
|
+
console.error(` ✗ ${qualityLabel(check.name)} failed: ${check.reason}.`);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
// hygiene-ignore single-use -- Keep the documented runLangProfileFixes declaration so its parameter and return contract remains attached.
|
|
1009
|
+
/**
|
|
1010
|
+
* Applies profile-provided safe fixes while preserving the normal read-only check commands.
|
|
1011
|
+
*
|
|
1012
|
+
* @param cfg Quality configuration that defines this check and its repository scope.
|
|
1013
|
+
* @param checks Resolved language checks or invocations selected for this phase.
|
|
1014
|
+
* @param toolResults Cache of inspected language-profile tool versions.
|
|
1015
|
+
*/
|
|
1016
|
+
function runLangProfileFixes(cfg, checks, toolResults) {
|
|
1017
|
+
for (const check of checks) {
|
|
1018
|
+
if (!check.autofix || cfg.qualityCommands?.some(c => c.name === check.name) || !qualityAutofixEnabled(cfg, check.autofix.name) || !qualityCmdEnabled(cfg, check.name))
|
|
1019
|
+
continue;
|
|
1020
|
+
if (check.tool) {
|
|
1021
|
+
const toolKey = JSON.stringify([check.tool.command, check.tool.versionArgs, check.tool.minimumVersion]);
|
|
1022
|
+
let toolResult = toolResults.get(toolKey);
|
|
1023
|
+
if (!toolResult) {
|
|
1024
|
+
toolResult = inspectLanguageProfileTool(check.tool, cfg.root);
|
|
1025
|
+
toolResults.set(toolKey, toolResult);
|
|
1026
|
+
}
|
|
1027
|
+
if (toolResult.error)
|
|
1028
|
+
throw new Error(toolResult.error);
|
|
1029
|
+
}
|
|
1030
|
+
const result = spawnSync(check.autofix.command, check.autofix.args.flatMap(a => (a === '{files}' ? check.files : [a])), { cwd: cfg.root, stdio: 'inherit' });
|
|
1031
|
+
if (result.error)
|
|
1032
|
+
throw result.error;
|
|
1033
|
+
if (result.status !== 0)
|
|
1034
|
+
throw new Error(`${check.autofix.command} exited with status ${result.status ?? 1}`);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Identifies an exact configured Git whitespace check.
|
|
1039
|
+
*
|
|
1040
|
+
* @param check Configured repository-health command.
|
|
1041
|
+
*
|
|
1042
|
+
* @return Whether the invocation duplicates the built-in `git diff --check`.
|
|
1043
|
+
*/
|
|
1044
|
+
function isGitDiffCheck(check) {
|
|
1045
|
+
return basename(check.command).toLowerCase() === 'git' && check.args?.length === 2 && check.args[0] === 'diff' && check.args[1] === '--check';
|
|
1046
|
+
}
|
|
1047
|
+
// hygiene-ignore single-use -- Keep the documented hasCfgdGitDiffCheck declaration so its parameter and return contract remains attached.
|
|
1048
|
+
/**
|
|
1049
|
+
* Detects whether an enabled repository-health command already performs Git's diff check.
|
|
1050
|
+
*
|
|
1051
|
+
* @param cfg Normalized repository configuration.
|
|
1052
|
+
*
|
|
1053
|
+
* @return Whether a selected exact Git diff check is present.
|
|
1054
|
+
*/
|
|
1055
|
+
function hasCfgdGitDiffCheck(cfg) {
|
|
1056
|
+
return (cfg.qualityCommands ?? []).some(c => qualityCmdEnabled(cfg, c.name) && isGitDiffCheck(c));
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Captures source text so automatic tools can report changed-file counts without
|
|
1060
|
+
* replaying their successful per-file output.
|
|
1061
|
+
*
|
|
1062
|
+
* @param cfg Quality configuration defining the repository root.
|
|
1063
|
+
* @param files Files modified by the automatic tool.
|
|
1064
|
+
*
|
|
1065
|
+
* @return Text snapshots keyed by absolute filename.
|
|
1066
|
+
*/
|
|
1067
|
+
function snapshotFiles(cfg, files) {
|
|
1068
|
+
return new Map(files.map(f => [f, readFileSync(resolve(cfg.root, f), 'utf8')]));
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Counts files whose contents differ from a prior snapshot.
|
|
1072
|
+
*
|
|
1073
|
+
* @param cfg Quality configuration defining the repository root.
|
|
1074
|
+
* @param files Files to compare.
|
|
1075
|
+
* @param before Initial file contents.
|
|
1076
|
+
*
|
|
1077
|
+
* @return Number of changed files.
|
|
1078
|
+
*/
|
|
1079
|
+
function changedFileCount(cfg, files, before) {
|
|
1080
|
+
return files.filter(f => before.get(f) !== readFileSync(resolve(cfg.root, f), 'utf8')).length;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Splits file arguments below a conservative process argument-size limit.
|
|
1084
|
+
*
|
|
1085
|
+
* @param files Absolute file paths passed to ESLint.
|
|
1086
|
+
*
|
|
1087
|
+
* @return Ordered file batches that fit within the argument budget.
|
|
1088
|
+
*/
|
|
1089
|
+
function argBatches(files) {
|
|
1090
|
+
const result = [];
|
|
1091
|
+
let batch = [];
|
|
1092
|
+
let bytes = 0;
|
|
1093
|
+
for (const file of files) {
|
|
1094
|
+
const size = Buffer.byteLength(file) + 1;
|
|
1095
|
+
if (batch.length && bytes + size > 64 * 1024) {
|
|
1096
|
+
result.push(batch);
|
|
1097
|
+
batch = [];
|
|
1098
|
+
bytes = 0;
|
|
1099
|
+
}
|
|
1100
|
+
batch.push(file);
|
|
1101
|
+
bytes += size;
|
|
1102
|
+
}
|
|
1103
|
+
if (batch.length)
|
|
1104
|
+
result.push(batch);
|
|
1105
|
+
return result;
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Selects either the complete configured scope or the changed working-tree scope.
|
|
1109
|
+
*
|
|
1110
|
+
* @param cfg Quality configuration defining source discovery.
|
|
1111
|
+
* @param all Whether to include every configured source file.
|
|
1112
|
+
*
|
|
1113
|
+
* @return Source files for the requested run scope.
|
|
1114
|
+
*/
|
|
1115
|
+
function filesFor(cfg, all) {
|
|
1116
|
+
return all ? srcFiles(cfg) : workingSrcFiles(cfg);
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Restricts a configuration to the files selected for a changed-file run.
|
|
1120
|
+
*
|
|
1121
|
+
* @param cfg Quality configuration to scope.
|
|
1122
|
+
* @param all Whether the full source scope should remain unchanged.
|
|
1123
|
+
*
|
|
1124
|
+
* @return Original configuration for full runs, or a configuration rooted at changed files.
|
|
1125
|
+
*/
|
|
1126
|
+
function scopedCfg(cfg, all) {
|
|
1127
|
+
return all ? cfg : { ...cfg, sourceRoots: filesFor(cfg, false) };
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Runs ESLint over the selected files in one API pass.
|
|
1131
|
+
*
|
|
1132
|
+
* @param cfg Quality configuration defining the repository and ESLint executable.
|
|
1133
|
+
* @param opts CLI options controlling scope and autofix.
|
|
1134
|
+
* @param exhaustive Whether ESLint must report zero warnings.
|
|
1135
|
+
* @param deadCodeCoordinated Whether the canonical dead-code coordinator owns unused-variable reporting.
|
|
1136
|
+
*
|
|
1137
|
+
* @return Nothing; failures are reflected in the process exit code.
|
|
1138
|
+
*/
|
|
1139
|
+
function runLint(cfg, opts, exhaustive = false, deadCodeCoordinated = false) {
|
|
1140
|
+
const files = filesFor(cfg, opts.all).filter(file => /\.(?:astro|cjs|js|jsx|mjs|ts|tsx)$/.test(file) && !hasGeneratedSourceHeader(readFileSync(file, 'utf8')));
|
|
1141
|
+
if (!files.length)
|
|
1142
|
+
return;
|
|
1143
|
+
qualityHeader('lint', `${opts.fix ? 'Fixing' : 'Checking'} ${files.length} source files with ESLint`);
|
|
1144
|
+
const flags = [
|
|
1145
|
+
'--cache',
|
|
1146
|
+
'--cache-strategy',
|
|
1147
|
+
'content',
|
|
1148
|
+
'--cache-location',
|
|
1149
|
+
'node_modules/.cache/eslint',
|
|
1150
|
+
'--no-warn-ignored',
|
|
1151
|
+
...(deadCodeCoordinated ? ['--rule', 'unused-imports/no-unused-vars: off'] : []),
|
|
1152
|
+
...(exhaustive ? ['--max-warnings=0'] : []),
|
|
1153
|
+
...(opts.fix ? ['--fix'] : []),
|
|
1154
|
+
];
|
|
1155
|
+
let failed = false;
|
|
1156
|
+
const before = opts.fix ? snapshotFiles(cfg, files) : undefined;
|
|
1157
|
+
let completed = 0;
|
|
1158
|
+
qualityProgress('ESLint', completed, files.length);
|
|
1159
|
+
let apiUnavailable = !canUseLocalEslintApi(cfg);
|
|
1160
|
+
if (!apiUnavailable) {
|
|
1161
|
+
const result = spawnSync(process.execPath, ['--input-type=module'], {
|
|
1162
|
+
cwd: cfg.root,
|
|
1163
|
+
stdio: ['pipe', 'pipe', 'inherit'],
|
|
1164
|
+
input: (function eslintApiSrc(cfg, files, opts, exhaustive, deadCodeCoordinated) {
|
|
1165
|
+
return `
|
|
1166
|
+
import { createRequire } from 'node:module';
|
|
1167
|
+
import { resolve } from 'node:path';
|
|
1168
|
+
const options = ${JSON.stringify({ root: cfg.root, files, commonJsFiles: files.filter(file => isCommonJsSrc(cfg.root, file)).map(file => ({ file, pattern: eslintFilePattern(cfg.root, file) })), fix: opts.fix, exhaustive, deadCodeCoordinated, eslintConfig: findEslintConfig(cfg.root, cfg.configRoot) })};
|
|
1169
|
+
const qualityProgress = () => {};
|
|
1170
|
+
let ESLint;
|
|
1171
|
+
let engine;
|
|
1172
|
+
try {
|
|
1173
|
+
const resolveEslint = (location) => {
|
|
1174
|
+
try {
|
|
1175
|
+
return createRequire(location)('eslint');
|
|
1176
|
+
} catch {
|
|
1177
|
+
return undefined;
|
|
1178
|
+
}
|
|
1179
|
+
};
|
|
1180
|
+
({ ESLint } = resolveEslint(resolve(options.root, 'package.json')) ?? (options.eslintConfig ? resolveEslint(options.eslintConfig) : undefined) ?? {});
|
|
1181
|
+
if (!ESLint) throw new Error('The installed ESLint package does not expose its API.');
|
|
1182
|
+
const baseOptions = {
|
|
1183
|
+
cwd: options.root,
|
|
1184
|
+
cache: true,
|
|
1185
|
+
cacheLocation: 'node_modules/.cache/eslint',
|
|
1186
|
+
cacheStrategy: 'content',
|
|
1187
|
+
warnIgnored: false,
|
|
1188
|
+
fix: options.fix,
|
|
1189
|
+
...(options.eslintConfig ? { overrideConfigFile: options.eslintConfig } : {}),
|
|
1190
|
+
};
|
|
1191
|
+
const baseEngine = new ESLint(baseOptions);
|
|
1192
|
+
const overrides = [];
|
|
1193
|
+
if (options.deadCodeCoordinated) overrides.push({ rules: { 'unused-imports/no-unused-vars': 'off' } });
|
|
1194
|
+
if (options.commonJsFiles.length) {
|
|
1195
|
+
overrides.push({ files: options.commonJsFiles.map(({ pattern }) => pattern), languageOptions: { sourceType: 'commonjs' } });
|
|
1196
|
+
const groups = new Map();
|
|
1197
|
+
for (const { file, pattern } of options.commonJsFiles) {
|
|
1198
|
+
const configuredRule = (await baseEngine.calculateConfigForFile(file))?.rules?.['@typescript-eslint/no-require-imports'];
|
|
1199
|
+
const severity = Array.isArray(configuredRule) ? configuredRule[0] : configuredRule;
|
|
1200
|
+
if (configuredRule === undefined || severity === 0 || severity === 'off') continue;
|
|
1201
|
+
const configuredOptions = Array.isArray(configuredRule) && configuredRule[1] && typeof configuredRule[1] === 'object' ? configuredRule[1] : {};
|
|
1202
|
+
const allow = Array.isArray(configuredOptions.allow) ? configuredOptions.allow : [];
|
|
1203
|
+
const rule = [severity, { ...configuredOptions, allow: [...new Set([...allow, '^.+$'])] }];
|
|
1204
|
+
const signature = JSON.stringify(rule);
|
|
1205
|
+
const group = groups.get(signature) ?? { rule, patterns: [] };
|
|
1206
|
+
group.patterns.push(pattern);
|
|
1207
|
+
groups.set(signature, group);
|
|
1208
|
+
}
|
|
1209
|
+
for (const { rule, patterns } of groups.values()) overrides.push({ files: patterns, rules: { '@typescript-eslint/no-require-imports': rule } });
|
|
1210
|
+
}
|
|
1211
|
+
engine = overrides.length ? new ESLint({ ...baseOptions, overrideConfig: overrides }) : baseEngine;
|
|
1212
|
+
} catch {
|
|
1213
|
+
process.exit(${ESLINT_API_FALLBACK});
|
|
1214
|
+
}
|
|
1215
|
+
try {
|
|
1216
|
+
const results = await engine.lintFiles(options.files);
|
|
1217
|
+
if (options.fix) await ESLint.outputFixes(results);
|
|
1218
|
+
qualityProgress('ESLint', options.files.length, options.files.length);
|
|
1219
|
+
const formatter = await engine.loadFormatter();
|
|
1220
|
+
const output = await formatter.format(results);
|
|
1221
|
+
if (output) process.stdout.write(output);
|
|
1222
|
+
const errors = results.reduce((total, result) => total + result.errorCount, 0);
|
|
1223
|
+
const warnings = results.reduce((total, result) => total + result.warningCount, 0);
|
|
1224
|
+
process.exitCode = errors || (options.exhaustive && warnings) ? 1 : 0;
|
|
1225
|
+
} catch (error) {
|
|
1226
|
+
process.stdout.write(error instanceof Error ? error.stack ?? error.message : String(error));
|
|
1227
|
+
process.exitCode = 2;
|
|
1228
|
+
}
|
|
1229
|
+
`;
|
|
1230
|
+
})(cfg, files, opts, exhaustive, deadCodeCoordinated),
|
|
1231
|
+
env: process.env,
|
|
1232
|
+
maxBuffer: TOOL_OUTPUT_MAX_BUFFER,
|
|
1233
|
+
});
|
|
1234
|
+
apiUnavailable = result.status === ESLINT_API_FALLBACK;
|
|
1235
|
+
if (!apiUnavailable) {
|
|
1236
|
+
const status = result.status ?? 1;
|
|
1237
|
+
const childOutput = result.stdout?.toString() ?? '';
|
|
1238
|
+
if (status && reportStages && reportStageName) {
|
|
1239
|
+
const stage = reportStages.get(reportStageName);
|
|
1240
|
+
if (stage)
|
|
1241
|
+
stage.status = 'failed';
|
|
1242
|
+
}
|
|
1243
|
+
if (status) {
|
|
1244
|
+
failed = true;
|
|
1245
|
+
process.exitCode = status;
|
|
1246
|
+
const details = compactOutput(childOutput);
|
|
1247
|
+
if (result.error)
|
|
1248
|
+
details.push(result.error.message);
|
|
1249
|
+
if (outputPhase) {
|
|
1250
|
+
recordQualityDetail(`ESLint failed (exit ${status})`);
|
|
1251
|
+
for (const line of details)
|
|
1252
|
+
recordQualityDetail(line);
|
|
1253
|
+
}
|
|
1254
|
+
else
|
|
1255
|
+
printChildOutput(childOutput);
|
|
1256
|
+
}
|
|
1257
|
+
else if (!outputPhase && childOutput)
|
|
1258
|
+
printChildOutput(childOutput);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
if (apiUnavailable) {
|
|
1262
|
+
const eslintConfig = findEslintConfig(cfg.root, cfg.configRoot);
|
|
1263
|
+
for (const filesBatch of argBatches(files)) {
|
|
1264
|
+
const status = run(cfg, toolPath(cfg, cfg.tools?.eslint, 'eslint'), [...flags, ...(eslintConfig ? ['--config', eslintConfig] : []), ...filesBatch], { quietSuccess: opts.fix });
|
|
1265
|
+
completed += filesBatch.length;
|
|
1266
|
+
qualityProgress('ESLint', completed, files.length);
|
|
1267
|
+
if (status) {
|
|
1268
|
+
failed = true;
|
|
1269
|
+
process.exitCode = status;
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
if (before && !outputPhase)
|
|
1274
|
+
console.error(` fixed ${changedFileCount(cfg, files, before)} files`);
|
|
1275
|
+
printCheckStatus('lint', failed ? 1 : 0);
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Removes function declarations that ESLint proves have no references.
|
|
1279
|
+
*
|
|
1280
|
+
* Knip can safely remove an unused export modifier while leaving the declaration
|
|
1281
|
+
* private. This pass completes that mechanical cleanup without guessing about
|
|
1282
|
+
* variables whose initializers may have side effects.
|
|
1283
|
+
*
|
|
1284
|
+
* @param cfg Quality configuration defining the repository and ESLint executable.
|
|
1285
|
+
* @param reports ESLint reports containing unused private function declarations.
|
|
1286
|
+
* @param changedFiles Set updated with files modified by the fixer.
|
|
1287
|
+
* @param importedConsumers Export names referenced by configured source files.
|
|
1288
|
+
*
|
|
1289
|
+
* @return Number of unused function declarations removed.
|
|
1290
|
+
*/
|
|
1291
|
+
function fixUnusedDeclarations(cfg, reports, changedFiles, importedConsumers = importedExportConsumers(cfg)) {
|
|
1292
|
+
let fixed = 0;
|
|
1293
|
+
for (const report of reports) {
|
|
1294
|
+
const unusedMsgs = report.messages.filter(m => m.ruleId === 'unused-imports/no-unused-vars');
|
|
1295
|
+
if (!unusedMsgs.length)
|
|
1296
|
+
continue;
|
|
1297
|
+
const src = readFileSync(report.filePath, 'utf8');
|
|
1298
|
+
if (hasGeneratedSourceHeader(src))
|
|
1299
|
+
continue;
|
|
1300
|
+
const ast = ts.createSourceFile(report.filePath, src, ts.ScriptTarget.Latest, true, C_M_JS_TS_X_CLASS_2.test(report.filePath) && report.filePath.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
1301
|
+
if (ast.parseDiagnostics.length)
|
|
1302
|
+
throw new Error(`ESLint reported unused declarations in unparsable source: ${report.filePath}`);
|
|
1303
|
+
const starts = new Set(unusedMsgs.map(m => ast.getPositionOfLineAndCharacter(m.line - 1, m.column - 1)));
|
|
1304
|
+
const edits = [];
|
|
1305
|
+
/**
|
|
1306
|
+
* Walks the source AST to locate declarations reported as unused.
|
|
1307
|
+
*
|
|
1308
|
+
* @param node Current syntax-tree node being inspected.
|
|
1309
|
+
*/
|
|
1310
|
+
const visit = (node) => {
|
|
1311
|
+
let declaration;
|
|
1312
|
+
const name = ts.isFunctionDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node)
|
|
1313
|
+
? node.name?.text
|
|
1314
|
+
: ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)
|
|
1315
|
+
? node.name.text
|
|
1316
|
+
: undefined;
|
|
1317
|
+
const externallyConsumed = name ? hasImportedExportConsumer(importedConsumers, report.filePath, name) : false;
|
|
1318
|
+
/**
|
|
1319
|
+
* Determines whether a declaration is directly owned by the source file.
|
|
1320
|
+
*
|
|
1321
|
+
* @param candidate Candidate declaration being classified.
|
|
1322
|
+
*
|
|
1323
|
+
* @return Whether the candidate declaration belongs directly to the source file.
|
|
1324
|
+
*/
|
|
1325
|
+
const isTopLevel = (candidate) => candidate.parent === ast ||
|
|
1326
|
+
(ts.isVariableDeclaration(candidate) && ts.isVariableDeclarationList(candidate.parent) && ts.isVariableStatement(candidate.parent.parent) && candidate.parent.parent.parent === ast);
|
|
1327
|
+
/**
|
|
1328
|
+
* Checks whether the declaration has an export modifier.
|
|
1329
|
+
*
|
|
1330
|
+
* @param candidate Candidate declaration being classified.
|
|
1331
|
+
*
|
|
1332
|
+
* @return Whether the candidate has an export modifier.
|
|
1333
|
+
*/
|
|
1334
|
+
const isExported = (candidate) => ts.canHaveModifiers(candidate) && Boolean(ts.getModifiers(candidate)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword));
|
|
1335
|
+
if (ts.isFunctionDeclaration(node) && node.name && starts.has(node.name.getStart(ast)) && isTopLevel(node) && !isExported(node) && !externallyConsumed)
|
|
1336
|
+
declaration = node;
|
|
1337
|
+
if ((ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node)) && starts.has(node.name.getStart(ast)) && isTopLevel(node) && !isExported(node) && !externallyConsumed)
|
|
1338
|
+
declaration = node;
|
|
1339
|
+
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && starts.has(node.name.getStart(ast)) && isTopLevel(node) && !externallyConsumed) {
|
|
1340
|
+
if (ts.isVariableDeclarationList(node.parent) &&
|
|
1341
|
+
(node.parent.flags & ts.NodeFlags.Const) !== 0 &&
|
|
1342
|
+
node.parent.declarations.length === 1 &&
|
|
1343
|
+
ts.isVariableStatement(node.parent.parent) &&
|
|
1344
|
+
!node.parent.parent.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) &&
|
|
1345
|
+
node.initializer &&
|
|
1346
|
+
isPureUnusedInit(node.initializer))
|
|
1347
|
+
declaration = node.parent.parent;
|
|
1348
|
+
}
|
|
1349
|
+
if (declaration) {
|
|
1350
|
+
let start = declaration.getStart(ast);
|
|
1351
|
+
const attached = (ts.getLeadingCommentRanges(src, declaration.getFullStart()) ?? []).at(-1);
|
|
1352
|
+
if (attached?.kind === ts.SyntaxKind.MultiLineCommentTrivia && src.slice(attached.end, start).trim() === '' && src.slice(attached.pos, attached.pos + 3) === '/**')
|
|
1353
|
+
start = attached.pos;
|
|
1354
|
+
let end = declaration.end;
|
|
1355
|
+
while (src[end] === ' ' || src[end] === '\t')
|
|
1356
|
+
end++;
|
|
1357
|
+
if (src.slice(end, end + 2) === '\r\n')
|
|
1358
|
+
end += 2;
|
|
1359
|
+
else if (src[end] === '\n')
|
|
1360
|
+
end++;
|
|
1361
|
+
edits.push({ start, end });
|
|
1362
|
+
}
|
|
1363
|
+
ts.forEachChild(node, visit);
|
|
1364
|
+
};
|
|
1365
|
+
visit(ast);
|
|
1366
|
+
if (!edits.length)
|
|
1367
|
+
continue;
|
|
1368
|
+
let updated = src;
|
|
1369
|
+
for (const edit of edits.sort((a, b) => b.start - a.start))
|
|
1370
|
+
updated = `${updated.slice(0, edit.start)}${updated.slice(edit.end)}`;
|
|
1371
|
+
if ((ts.transpileModule(updated, { fileName: report.filePath, reportDiagnostics: true, compilerOptions: { allowJs: true, jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext } }).diagnostics ??
|
|
1372
|
+
[]).some(d => d.category === ts.DiagnosticCategory.Error))
|
|
1373
|
+
continue;
|
|
1374
|
+
writeFileSync(report.filePath, updated);
|
|
1375
|
+
changedFiles.add(report.filePath);
|
|
1376
|
+
fixed += edits.length;
|
|
1377
|
+
}
|
|
1378
|
+
return fixed;
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Accepts only initializers whose evaluation has no observable effects.
|
|
1382
|
+
*
|
|
1383
|
+
* @param node Initializer expression to classify.
|
|
1384
|
+
*
|
|
1385
|
+
* @return Whether evaluating the expression is limited to immutable literal data or a function value.
|
|
1386
|
+
*/
|
|
1387
|
+
function isPureUnusedInit(node) {
|
|
1388
|
+
if (ts.isStringLiteralLike(node) ||
|
|
1389
|
+
ts.isNumericLiteral(node) ||
|
|
1390
|
+
ts.isBigIntLiteral(node) ||
|
|
1391
|
+
ts.isRegularExpressionLiteral(node) ||
|
|
1392
|
+
node.kind === ts.SyntaxKind.TrueKeyword ||
|
|
1393
|
+
node.kind === ts.SyntaxKind.FalseKeyword ||
|
|
1394
|
+
node.kind === ts.SyntaxKind.NullKeyword ||
|
|
1395
|
+
ts.isArrowFunction(node) ||
|
|
1396
|
+
ts.isFunctionExpression(node))
|
|
1397
|
+
return true;
|
|
1398
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isNonNullExpression(node) || ts.isSatisfiesExpression(node))
|
|
1399
|
+
return isPureUnusedInit(node.expression);
|
|
1400
|
+
if (ts.isArrayLiteralExpression(node))
|
|
1401
|
+
return node.elements.every(e => !ts.isSpreadElement(e) && isPureUnusedInit(e));
|
|
1402
|
+
if (ts.isObjectLiteralExpression(node))
|
|
1403
|
+
return node.properties.every(p => ts.isPropertyAssignment(p) && !ts.isComputedPropertyName(p.name) && isPureUnusedInit(p.initializer));
|
|
1404
|
+
return false;
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Flattens Knip issue groups while preserving the named findings in each group.
|
|
1408
|
+
* Knip reports duplicate exports as arrays of arrays; other finding kinds are flat.
|
|
1409
|
+
*
|
|
1410
|
+
* @param value Knip's finding value for one issue kind.
|
|
1411
|
+
*
|
|
1412
|
+
* @return The named finding records contained in the value.
|
|
1413
|
+
*/
|
|
1414
|
+
function flattenKnipItems(value) {
|
|
1415
|
+
if (!Array.isArray(value))
|
|
1416
|
+
throw new Error('finding kind is not an array');
|
|
1417
|
+
return value.flatMap(i => (Array.isArray(i) ? flattenKnipItems(i) : [i]));
|
|
1418
|
+
}
|
|
1419
|
+
// hygiene-ignore single-use -- Keep the documented canUseFocusedEslint declaration so its parameter and return contract remains attached.
|
|
1420
|
+
/**
|
|
1421
|
+
* Uses the repository's resolved unused-variable rule without evaluating its unrelated lint rules.
|
|
1422
|
+
*
|
|
1423
|
+
* @param cfg Quality configuration defining the repository and selected ESLint executable.
|
|
1424
|
+
* @param flatCfg Resolved flat ESLint config path.
|
|
1425
|
+
*
|
|
1426
|
+
* @return Whether the local ESLint API matches the configured executable.
|
|
1427
|
+
*/
|
|
1428
|
+
function canUseFocusedEslint(cfg, flatCfg) {
|
|
1429
|
+
if (!flatCfg)
|
|
1430
|
+
return false;
|
|
1431
|
+
const cfgdTool = cfg.tools?.eslint;
|
|
1432
|
+
if (cfgdTool && cfgdTool !== 'eslint' && resolve(cfg.root, cfgdTool) !== resolve(cfg.root, 'node_modules', '.bin', 'eslint'))
|
|
1433
|
+
return false;
|
|
1434
|
+
return existsSync(resolve(cfg.root, 'node_modules', 'eslint', 'package.json'));
|
|
1435
|
+
}
|
|
1436
|
+
// hygiene-ignore single-use -- Keep the documented focusedEslintCfgSrc declaration so its parameter and return contract remains attached.
|
|
1437
|
+
/**
|
|
1438
|
+
* Builds a temporary flat config containing only each selected file's unused-variable rule.
|
|
1439
|
+
*
|
|
1440
|
+
* @param cfg Quality configuration defining the repository.
|
|
1441
|
+
* @param flatCfg Original flat ESLint config used to resolve parser, plugin, and rule settings.
|
|
1442
|
+
* @param files Source files passed to the focused detector.
|
|
1443
|
+
*
|
|
1444
|
+
* @return JavaScript module source for ESLint's temporary config loader.
|
|
1445
|
+
*/
|
|
1446
|
+
function focusedEslintCfgSrc(cfg, flatCfg, files) {
|
|
1447
|
+
return `
|
|
1448
|
+
import { createRequire } from 'node:module';
|
|
1449
|
+
import { resolve } from 'node:path';
|
|
1450
|
+
const root = ${JSON.stringify(cfg.root)};
|
|
1451
|
+
const configPath = ${JSON.stringify(flatCfg)};
|
|
1452
|
+
const sourceFiles = ${JSON.stringify(files)};
|
|
1453
|
+
const filePatterns = ${JSON.stringify(files.map(f => eslintFilePattern(cfg.root, f)))};
|
|
1454
|
+
const commonJsFiles = new Set(${JSON.stringify(files.filter(file => isCommonJsSrc(cfg.root, file)))});
|
|
1455
|
+
try {
|
|
1456
|
+
const requireFromRepo = createRequire(resolve(root, 'package.json'));
|
|
1457
|
+
const { ESLint } = requireFromRepo('eslint');
|
|
1458
|
+
const eslint = new ESLint({ cwd: root, overrideConfigFile: configPath, ignore: false });
|
|
1459
|
+
const groups = new Map();
|
|
1460
|
+
const objectIds = new WeakMap();
|
|
1461
|
+
let nextObjectId = 0;
|
|
1462
|
+
const objectId = (value) => {
|
|
1463
|
+
if (!value || (typeof value !== 'object' && typeof value !== 'function')) return String(value);
|
|
1464
|
+
if (!objectIds.has(value)) objectIds.set(value, ++nextObjectId);
|
|
1465
|
+
return objectIds.get(value);
|
|
1466
|
+
};
|
|
1467
|
+
for (const [index, file] of sourceFiles.entries()) {
|
|
1468
|
+
const effective = await eslint.calculateConfigForFile(file);
|
|
1469
|
+
const languageOptions = effective?.languageOptions;
|
|
1470
|
+
if (!languageOptions?.parser) throw new Error('ESLint did not resolve a parser for ' + file);
|
|
1471
|
+
const parserOptions = { ...(languageOptions.parserOptions ?? {}) };
|
|
1472
|
+
for (const key of ['project', 'projectService', 'program', 'tsconfigRootDir']) delete parserOptions[key];
|
|
1473
|
+
const focusedLanguageOptions = { ...languageOptions, parserOptions, ...(commonJsFiles.has(file) ? { sourceType: 'commonjs' } : {}) };
|
|
1474
|
+
const rule = effective.rules?.['unused-imports/no-unused-vars'];
|
|
1475
|
+
const severity = Array.isArray(rule) ? rule[0] : rule;
|
|
1476
|
+
const active = rule !== undefined && severity !== 0 && severity !== 'off';
|
|
1477
|
+
const plugin = effective.plugins?.['unused-imports'];
|
|
1478
|
+
if (active && !plugin) throw new Error('ESLint resolved the unused-variable rule without its plugin for ' + file);
|
|
1479
|
+
const signature = JSON.stringify({
|
|
1480
|
+
parser: objectId(languageOptions.parser),
|
|
1481
|
+
plugin: objectId(plugin),
|
|
1482
|
+
rule: active ? rule : null,
|
|
1483
|
+
languageOptions: { ...focusedLanguageOptions, parser: undefined },
|
|
1484
|
+
settings: effective.settings,
|
|
1485
|
+
});
|
|
1486
|
+
const group = groups.get(signature) ?? {
|
|
1487
|
+
patterns: [],
|
|
1488
|
+
languageOptions: focusedLanguageOptions,
|
|
1489
|
+
plugins: plugin ? { 'unused-imports': plugin } : {},
|
|
1490
|
+
rules: active ? { 'unused-imports/no-unused-vars': rule } : {},
|
|
1491
|
+
settings: effective.settings,
|
|
1492
|
+
};
|
|
1493
|
+
group.patterns.push(filePatterns[index]);
|
|
1494
|
+
groups.set(signature, group);
|
|
1495
|
+
}
|
|
1496
|
+
const focused = new ESLint({
|
|
1497
|
+
cwd: root,
|
|
1498
|
+
ignore: false,
|
|
1499
|
+
overrideConfigFile: true,
|
|
1500
|
+
overrideConfig: [...groups.values()].map((group) => ({
|
|
1501
|
+
files: group.patterns,
|
|
1502
|
+
languageOptions: group.languageOptions,
|
|
1503
|
+
plugins: group.plugins,
|
|
1504
|
+
rules: group.rules,
|
|
1505
|
+
...(group.settings ? { settings: group.settings } : {}),
|
|
1506
|
+
})),
|
|
1507
|
+
});
|
|
1508
|
+
const results = await focused.lintFiles(sourceFiles);
|
|
1509
|
+
const reports = results.map(({ filePath, messages, fatalErrorCount }) => ({
|
|
1510
|
+
filePath: resolve(filePath),
|
|
1511
|
+
messages: messages.map(({ ruleId, line, column, message }) => ({ ruleId, line, column, message })),
|
|
1512
|
+
fatalErrorCount,
|
|
1513
|
+
}));
|
|
1514
|
+
process.stdout.write(JSON.stringify(reports));
|
|
1515
|
+
} catch (error) {
|
|
1516
|
+
console.error(${JSON.stringify(FOCUSED_ESLINT_FALLBACK)}, error instanceof Error ? error.stack ?? error.message : String(error));
|
|
1517
|
+
process.exitCode = 2;
|
|
1518
|
+
}
|
|
1519
|
+
`;
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* Runs the unused-variable detector under the extracted repository rule configuration.
|
|
1523
|
+
*
|
|
1524
|
+
* @param cfg Quality configuration defining the repository.
|
|
1525
|
+
* @param flatCfg Original flat ESLint config used to resolve the detector rule.
|
|
1526
|
+
* @param files Source files in this argument-safe batch.
|
|
1527
|
+
*
|
|
1528
|
+
* @return ESLint process result, or `undefined` when the extraction requires the full-config fallback.
|
|
1529
|
+
*/
|
|
1530
|
+
function runFocusedEslint(cfg, flatCfg, files) {
|
|
1531
|
+
const result = spawnSync(process.execPath, ['--input-type=module'], {
|
|
1532
|
+
cwd: cfg.root,
|
|
1533
|
+
encoding: 'utf8',
|
|
1534
|
+
env: { ...process.env, ESLINT_USE_FLAT_CONFIG: 'true' },
|
|
1535
|
+
input: focusedEslintCfgSrc(cfg, flatCfg, files),
|
|
1536
|
+
maxBuffer: TOOL_OUTPUT_MAX_BUFFER,
|
|
1537
|
+
});
|
|
1538
|
+
if (result.status === 2 && result.stderr?.toString().includes(FOCUSED_ESLINT_FALLBACK))
|
|
1539
|
+
return undefined;
|
|
1540
|
+
return result;
|
|
1541
|
+
}
|
|
1542
|
+
// hygiene-ignore single-use -- Keep the documented collectEslintReports declaration so its parameter and return contract remains attached.
|
|
1543
|
+
/**
|
|
1544
|
+
* Runs ESLint's machine-readable pass once for the selected source files.
|
|
1545
|
+
*
|
|
1546
|
+
* @param cfg Quality configuration defining source files and the ESLint executable.
|
|
1547
|
+
* @param all Whether to inspect every configured source file instead of changed files.
|
|
1548
|
+
* @param selectedFiles Optional exact file set to scan incrementally.
|
|
1549
|
+
*
|
|
1550
|
+
* @return Validated ESLint reports for the selected source files.
|
|
1551
|
+
*/
|
|
1552
|
+
function collectEslintReports(cfg, all, selectedFiles) {
|
|
1553
|
+
const files = (selectedFiles ?? filesFor(cfg, all)).filter(f => CJS_JS_JSX_MJS_TS_TSX_REGEX.test(f));
|
|
1554
|
+
const reports = [];
|
|
1555
|
+
const flatCfg = findEslintConfig(cfg.root, cfg.configRoot);
|
|
1556
|
+
const eslintPath = toolPath(cfg, cfg.tools?.eslint, 'eslint');
|
|
1557
|
+
const focusedEslint = canUseFocusedEslint(cfg, flatCfg);
|
|
1558
|
+
let completed = 0;
|
|
1559
|
+
qualityProgress('ESLint dead-code', completed, files.length);
|
|
1560
|
+
for (const filesBatch of argBatches(files)) {
|
|
1561
|
+
reports.push(...parseEslintReports((focusedEslint && flatCfg ? runFocusedEslint(cfg, flatCfg, filesBatch) : undefined) ??
|
|
1562
|
+
spawnSync(eslintPath, ['--format', 'json', '--no-ignore', ...(flatCfg ? ['--config', flatCfg] : []), ...filesBatch], {
|
|
1563
|
+
cwd: cfg.root,
|
|
1564
|
+
encoding: 'utf8',
|
|
1565
|
+
env: flatCfg ? { ...process.env, ESLINT_USE_FLAT_CONFIG: 'true' } : process.env,
|
|
1566
|
+
maxBuffer: TOOL_OUTPUT_MAX_BUFFER,
|
|
1567
|
+
}), filesBatch));
|
|
1568
|
+
completed += filesBatch.length;
|
|
1569
|
+
qualityProgress('ESLint dead-code', completed, files.length);
|
|
1570
|
+
}
|
|
1571
|
+
return reports;
|
|
1572
|
+
}
|
|
1573
|
+
/**
|
|
1574
|
+
* Parses ESLint JSON and fails closed when the detector cannot provide a trustworthy result.
|
|
1575
|
+
*
|
|
1576
|
+
* @param result ESLint process result containing JSON reports and an exit status.
|
|
1577
|
+
* @param files Absolute paths of every source file requested from ESLint.
|
|
1578
|
+
*
|
|
1579
|
+
* @return Validated reports covering the complete requested file set.
|
|
1580
|
+
*/
|
|
1581
|
+
function parseEslintReports(result, files) {
|
|
1582
|
+
if (result.error)
|
|
1583
|
+
throw new Error(`ESLint dead-code detector failed: ${result.error.message}`);
|
|
1584
|
+
if (result.status !== 0 && result.status !== 1)
|
|
1585
|
+
throw new Error(`ESLint dead-code detector exited ${result.status ?? 'without a status'} for ${files.length} source files (${files
|
|
1586
|
+
.slice(0, 3)
|
|
1587
|
+
.map(f => relative(process.cwd(), f))
|
|
1588
|
+
.join(', ')}${files.length > 3 ? ', …' : ''}): ${compactOutput(result.stderr?.toString() ?? '').join(' ')}`);
|
|
1589
|
+
try {
|
|
1590
|
+
const reports = JSON.parse(result.stdout?.toString() || '');
|
|
1591
|
+
if (!Array.isArray(reports))
|
|
1592
|
+
throw new Error('expected a JSON array');
|
|
1593
|
+
if (reports.some(r => !r ||
|
|
1594
|
+
typeof r.filePath !== 'string' ||
|
|
1595
|
+
!Array.isArray(r.messages) ||
|
|
1596
|
+
r.messages.some((m) => !m ||
|
|
1597
|
+
typeof m !== 'object' ||
|
|
1598
|
+
(m.ruleId === 'unused-imports/no-unused-vars' && (!Number.isInteger(m.line) || !Number.isInteger(m.column))))))
|
|
1599
|
+
throw new Error('report entries must include filePath and well-formed messages');
|
|
1600
|
+
const actual = new Set(reports.map((r) => resolve(r.filePath)));
|
|
1601
|
+
const missing = files.map(f => resolve(f)).filter(f => !actual.has(f));
|
|
1602
|
+
if (missing.length)
|
|
1603
|
+
throw new Error(`missing reports for ${missing.join(', ')}`);
|
|
1604
|
+
return reports;
|
|
1605
|
+
}
|
|
1606
|
+
catch (err) {
|
|
1607
|
+
throw new Error(`ESLint dead-code detector could not read reports for ${files.length} source files: ${err instanceof SyntaxError ? `invalid JSON: ${err.message}` : err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
// hygiene-ignore single-use -- Keep the documented unusedDeclarationFindings declaration so its parameter and return contract remains attached.
|
|
1611
|
+
/**
|
|
1612
|
+
* Reports unused private declarations, classifying only proven-safe removals as autofixable.
|
|
1613
|
+
*
|
|
1614
|
+
* @param cfg Quality configuration defining the repository and source roots.
|
|
1615
|
+
* @param reports Parsed ESLint messages used to identify unused private declarations.
|
|
1616
|
+
*
|
|
1617
|
+
* @return Findings with only unambiguous, side-effect-free function removals marked fixable.
|
|
1618
|
+
*/
|
|
1619
|
+
function unusedDeclarationFindings(cfg, reports) {
|
|
1620
|
+
const findings = [];
|
|
1621
|
+
for (const report of reports) {
|
|
1622
|
+
const src = readFileSync(report.filePath, 'utf8');
|
|
1623
|
+
const lines = src.split(R_N_REGEX);
|
|
1624
|
+
const ast = ts.createSourceFile(report.filePath, src, ts.ScriptTarget.Latest, true, C_M_JS_TS_X_CLASS_2.test(report.filePath) && report.filePath.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
1625
|
+
if (ast.parseDiagnostics.length)
|
|
1626
|
+
throw new Error(`ESLint reported unused declarations in unparsable source: ${report.filePath}`);
|
|
1627
|
+
for (const msg of report.messages.filter(e => e.ruleId === 'unused-imports/no-unused-vars')) {
|
|
1628
|
+
// hygiene-ignore single-use -- Capture the diagnostic name before AST traversal and subsequent finding construction.
|
|
1629
|
+
const name = (lines[msg.line - 1]?.slice(Math.max(0, msg.column - 1)) ?? '').match(/^[A-Za-z_$][\w$]*/)?.[0] ?? msg.message?.match(/^'([^']+)'/)?.[1] ?? '<unknown>';
|
|
1630
|
+
// hygiene-ignore single-use -- Compute the diagnostic offset once before recursively visiting AST nodes.
|
|
1631
|
+
const pos = ast.getPositionOfLineAndCharacter(msg.line - 1, msg.column - 1);
|
|
1632
|
+
let declaration;
|
|
1633
|
+
/**
|
|
1634
|
+
* Locates the unused declaration associated with an ESLint diagnostic.
|
|
1635
|
+
*
|
|
1636
|
+
* @param node Current syntax-tree node being inspected.
|
|
1637
|
+
*/
|
|
1638
|
+
const find = (node) => {
|
|
1639
|
+
if (node.name &&
|
|
1640
|
+
ts.isIdentifier(node.name) &&
|
|
1641
|
+
node.name.getStart(ast) === pos)
|
|
1642
|
+
declaration = node;
|
|
1643
|
+
ts.forEachChild(node, find);
|
|
1644
|
+
};
|
|
1645
|
+
find(ast);
|
|
1646
|
+
let autofixable = false;
|
|
1647
|
+
let reason = 'The ESLint location did not resolve to a supported private declaration.';
|
|
1648
|
+
const declarationExported = declaration &&
|
|
1649
|
+
((ts.canHaveModifiers(declaration) && Boolean(ts.getModifiers(declaration)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword))) ||
|
|
1650
|
+
(ts.isVariableDeclaration(declaration) &&
|
|
1651
|
+
ts.isVariableDeclarationList(declaration.parent) &&
|
|
1652
|
+
ts.isVariableStatement(declaration.parent.parent) &&
|
|
1653
|
+
Boolean(declaration.parent.parent.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword))));
|
|
1654
|
+
if (declaration &&
|
|
1655
|
+
!declarationExported &&
|
|
1656
|
+
(declaration.parent === ast ||
|
|
1657
|
+
(ts.isVariableDeclaration(declaration) && ts.isVariableDeclarationList(declaration.parent) && ts.isVariableStatement(declaration.parent.parent) && declaration.parent.parent.parent === ast))) {
|
|
1658
|
+
if (ts.isFunctionDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration) || ts.isInterfaceDeclaration(declaration)) {
|
|
1659
|
+
autofixable = true;
|
|
1660
|
+
reason = 'ESLint confirms this private declaration is unused and removing it has no initializer effects.';
|
|
1661
|
+
}
|
|
1662
|
+
else if (ts.isVariableDeclaration(declaration)) {
|
|
1663
|
+
autofixable =
|
|
1664
|
+
ts.isVariableDeclarationList(declaration.parent) &&
|
|
1665
|
+
(declaration.parent.flags & ts.NodeFlags.Const) !== 0 &&
|
|
1666
|
+
declaration.parent.declarations.length === 1 &&
|
|
1667
|
+
ts.isVariableStatement(declaration.parent.parent) &&
|
|
1668
|
+
Boolean(declaration.initializer && isPureUnusedInit(declaration.initializer));
|
|
1669
|
+
reason = autofixable ? 'The unused const has a side-effect-free initializer.' : 'Removing this binding may change initializer evaluation or declaration semantics.';
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
else if (declaration && !declarationExported) {
|
|
1673
|
+
reason = 'This unused binding is nested inside another declaration; removing its enclosing function or component would change behavior.';
|
|
1674
|
+
}
|
|
1675
|
+
if (autofixable && hasGeneratedSourceHeader(src)) {
|
|
1676
|
+
autofixable = false;
|
|
1677
|
+
reason = 'This declaration is in generator-owned source; update its schema or generator input and regenerate the file instead of editing it here.';
|
|
1678
|
+
}
|
|
1679
|
+
findings.push({
|
|
1680
|
+
rule: 'eslint/unused-private-declaration',
|
|
1681
|
+
file: relative(cfg.root, report.filePath),
|
|
1682
|
+
line: msg.line,
|
|
1683
|
+
name,
|
|
1684
|
+
severity: 'error',
|
|
1685
|
+
autofixable,
|
|
1686
|
+
reason,
|
|
1687
|
+
agentAction: autofixable
|
|
1688
|
+
? 'Run the canonical dead-code autofix; it should remove this declaration and its attached TSDoc without changing other source behavior.'
|
|
1689
|
+
: reason.startsWith('This unused binding is nested')
|
|
1690
|
+
? 'Remove only this local parameter or binding when appropriate; preserve its enclosing function, component, hook order, closure behavior, and control flow, then run the focused test and typecheck.'
|
|
1691
|
+
: 'Inspect the declaration and its initializer. Remove the unused binding only if initializer evaluation and control flow remain equivalent; preserve observable effects, then run the affected focused test and typecheck.',
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
return findings;
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* Runs one named repository quality command.
|
|
1699
|
+
*
|
|
1700
|
+
* @param cfg Quality configuration containing configured commands.
|
|
1701
|
+
* @param name Command name to execute.
|
|
1702
|
+
*
|
|
1703
|
+
* @return Nothing; command failures are reflected in the process exit code.
|
|
1704
|
+
*/
|
|
1705
|
+
function runCfgdCmd(cfg, name) {
|
|
1706
|
+
if (!qualityCmdEnabled(cfg, name))
|
|
1707
|
+
return;
|
|
1708
|
+
const check = cfg.qualityCommands?.find(c => c.name === name);
|
|
1709
|
+
if (!check)
|
|
1710
|
+
throw new Error(`Unknown quality domain: ${name}`);
|
|
1711
|
+
qualityHeader(`command:${name}`, '');
|
|
1712
|
+
let status = 1;
|
|
1713
|
+
try {
|
|
1714
|
+
status = run(cfg, check.command, check.args ?? []);
|
|
1715
|
+
}
|
|
1716
|
+
catch (err) {
|
|
1717
|
+
recordQualityFailure(`command:${name}`, err);
|
|
1718
|
+
}
|
|
1719
|
+
if (status)
|
|
1720
|
+
process.exitCode = 1;
|
|
1721
|
+
printCheckStatus(`command:${name}`, status ? 1 : 0);
|
|
1722
|
+
}
|
|
1723
|
+
// hygiene-ignore single-use -- Keep the documented runRecommendationCmds declaration so its parameter and return contract remains attached.
|
|
1724
|
+
/**
|
|
1725
|
+
* Runs configured recommendation commands after Knip and fails when a command fails.
|
|
1726
|
+
*
|
|
1727
|
+
* @param cfg Quality configuration containing recommendation commands.
|
|
1728
|
+
*
|
|
1729
|
+
* @return Nothing; command failures set the process exit code.
|
|
1730
|
+
*/
|
|
1731
|
+
function runRecommendationCmds(cfg) {
|
|
1732
|
+
for (const check of cfg.recommendationCommands ?? []) {
|
|
1733
|
+
if (!qualityRecommendationEnabled(cfg, check.name))
|
|
1734
|
+
continue;
|
|
1735
|
+
qualityHeader(`recommendation:${check.name}`, '');
|
|
1736
|
+
let status = 1;
|
|
1737
|
+
try {
|
|
1738
|
+
status = run(cfg, check.command, check.args ?? []);
|
|
1739
|
+
}
|
|
1740
|
+
catch (err) {
|
|
1741
|
+
recordQualityFailure(`recommendation:${check.name}`, err);
|
|
1742
|
+
}
|
|
1743
|
+
if (status)
|
|
1744
|
+
process.exitCode = 1;
|
|
1745
|
+
printCheckStatus(`recommendation:${check.name}`, status ? 1 : 0);
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
/**
|
|
1749
|
+
* Runs the configured project typecheck command or the default TypeScript compiler invocation.
|
|
1750
|
+
*
|
|
1751
|
+
* @param cfg Quality configuration containing compiler and project settings.
|
|
1752
|
+
*
|
|
1753
|
+
* @return Nothing; typecheck failures are reflected in the process exit code.
|
|
1754
|
+
*/
|
|
1755
|
+
function runProjectTypecheck(cfg) {
|
|
1756
|
+
qualityHeader('typecheck', 'Checking the configured project type boundary');
|
|
1757
|
+
if (!cfg.typecheckCommand) {
|
|
1758
|
+
const status = run(cfg, toolPath(cfg, cfg.tools?.tsc, 'tsc'), ['--noEmit', '-p', projectTsconfig(cfg)]);
|
|
1759
|
+
if (status)
|
|
1760
|
+
process.exitCode = status;
|
|
1761
|
+
printCheckStatus('typecheck', status ? 1 : 0);
|
|
1762
|
+
return;
|
|
1763
|
+
}
|
|
1764
|
+
const result = spawnSync(cfg.typecheckCommand.command, cfg.typecheckCommand.args ?? [], { cwd: cfg.root, stdio: ['inherit', 'pipe', 'pipe'], env: process.env, maxBuffer: TOOL_OUTPUT_MAX_BUFFER });
|
|
1765
|
+
const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
|
|
1766
|
+
const diagnosticsReported = /\berror\s+ts\(\d+\)/u.test(output) || /-\s+[1-9]\d*\s+errors?\b/u.test(output);
|
|
1767
|
+
const status = result.status ?? 1;
|
|
1768
|
+
if (status || diagnosticsReported) {
|
|
1769
|
+
const lines = compactOutput(output);
|
|
1770
|
+
if (outputPhase) {
|
|
1771
|
+
recordQualityDetail(`${cfg.typecheckCommand.command} ${status ? `failed (exit ${status})` : 'reported diagnostics'}`);
|
|
1772
|
+
for (const line of lines)
|
|
1773
|
+
recordQualityDetail(line);
|
|
1774
|
+
}
|
|
1775
|
+
else
|
|
1776
|
+
printChildOutput(output);
|
|
1777
|
+
}
|
|
1778
|
+
if (status || diagnosticsReported)
|
|
1779
|
+
process.exitCode = status || 1;
|
|
1780
|
+
printCheckStatus('typecheck', status || diagnosticsReported ? 1 : 0);
|
|
1781
|
+
}
|
|
1782
|
+
// hygiene-ignore single-use -- Keep the documented repairMissingImports declaration so its parameter and return contract remains attached.
|
|
1783
|
+
/**
|
|
1784
|
+
* Restores a missing local import when the repository has one unambiguous
|
|
1785
|
+
* source export for the unresolved identifier. This is deliberately narrow:
|
|
1786
|
+
* unresolved locals, globals, and symbols with multiple possible sources are
|
|
1787
|
+
* left for the compiler rather than guessed at.
|
|
1788
|
+
*
|
|
1789
|
+
* @param cfg Quality configuration defining the repository root and source scope.
|
|
1790
|
+
* @param program TypeScript program whose exports and unresolved identifiers are inspected.
|
|
1791
|
+
* @param checker TypeScript type checker used to resolve exported symbols.
|
|
1792
|
+
*
|
|
1793
|
+
* @return Nothing; unambiguous missing local imports are written into source files.
|
|
1794
|
+
*/
|
|
1795
|
+
function repairMissingImports(cfg, program, checker) {
|
|
1796
|
+
const candidates = new Map();
|
|
1797
|
+
const scopedSrcs = new Set(srcFiles(cfg)
|
|
1798
|
+
.filter(file => C_M_JS_TS_X_REGEX.test(file))
|
|
1799
|
+
.map(file => resolve(file)));
|
|
1800
|
+
for (const source of program.getSourceFiles()) {
|
|
1801
|
+
if (!scopedSrcs.has(resolve(source.fileName)) || !C_M_JS_TS_X_REGEX.test(source.fileName))
|
|
1802
|
+
continue;
|
|
1803
|
+
if (hasGeneratedSourceHeader(source.text))
|
|
1804
|
+
continue;
|
|
1805
|
+
const module = checker.getSymbolAtLocation(source);
|
|
1806
|
+
for (const exported of module ? checker.getExportsOfModule(module) : []) {
|
|
1807
|
+
const list = candidates.get(exported.name) ?? [];
|
|
1808
|
+
list.push(source);
|
|
1809
|
+
candidates.set(exported.name, list);
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
/**
|
|
1813
|
+
* Determines whether an identifier is used as a type reference.
|
|
1814
|
+
*
|
|
1815
|
+
* @param n Identifier or source value currently being analyzed.
|
|
1816
|
+
*
|
|
1817
|
+
* @return Whether the identifier appears in a type position.
|
|
1818
|
+
*/
|
|
1819
|
+
const isTypePos = (n) => {
|
|
1820
|
+
for (let parent = n.parent; parent; parent = parent.parent) {
|
|
1821
|
+
if (ts.isImportDeclaration(parent) || ts.isVariableDeclaration(parent) || ts.isFunctionDeclaration(parent))
|
|
1822
|
+
return false;
|
|
1823
|
+
if (ts.isTypeNode(parent) || ts.isTypeAliasDeclaration(parent) || ts.isInterfaceDeclaration(parent))
|
|
1824
|
+
return true;
|
|
1825
|
+
if (ts.isStatement(parent))
|
|
1826
|
+
return false;
|
|
1827
|
+
}
|
|
1828
|
+
return false;
|
|
1829
|
+
};
|
|
1830
|
+
/**
|
|
1831
|
+
* Checks whether a reference is already qualified by a type-only import expression.
|
|
1832
|
+
*
|
|
1833
|
+
* @param n Identifier whose ancestors are inspected.
|
|
1834
|
+
*
|
|
1835
|
+
* @return Whether the identifier is part of an `import('module').Type` reference.
|
|
1836
|
+
*/
|
|
1837
|
+
const isImportTypeRef = (n) => {
|
|
1838
|
+
for (let parent = n.parent; parent; parent = parent.parent) {
|
|
1839
|
+
if (ts.isImportTypeNode(parent))
|
|
1840
|
+
return true;
|
|
1841
|
+
if (ts.isStatement(parent))
|
|
1842
|
+
return false;
|
|
1843
|
+
}
|
|
1844
|
+
return false;
|
|
1845
|
+
};
|
|
1846
|
+
// WALKTHROUGH
|
|
1847
|
+
for (const src of program.getSourceFiles()) {
|
|
1848
|
+
if (!scopedSrcs.has(resolve(src.fileName)) || !C_M_JS_TS_X_REGEX.test(src.fileName))
|
|
1849
|
+
continue;
|
|
1850
|
+
const missing = new Map();
|
|
1851
|
+
const importedNames = new Set();
|
|
1852
|
+
for (const statement of src.statements.filter(ts.isImportDeclaration)) {
|
|
1853
|
+
if (!statement.importClause)
|
|
1854
|
+
continue;
|
|
1855
|
+
if (statement.importClause.name)
|
|
1856
|
+
importedNames.add(statement.importClause.name.text);
|
|
1857
|
+
if (statement.importClause.namedBindings && ts.isNamespaceImport(statement.importClause.namedBindings))
|
|
1858
|
+
importedNames.add(statement.importClause.namedBindings.name.text);
|
|
1859
|
+
if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings))
|
|
1860
|
+
for (const el of statement.importClause.namedBindings.elements)
|
|
1861
|
+
importedNames.add(el.name.text);
|
|
1862
|
+
}
|
|
1863
|
+
/**
|
|
1864
|
+
* Finds identifier references that need a missing-import repair.
|
|
1865
|
+
*
|
|
1866
|
+
* @param n Identifier or source value currently being analyzed.
|
|
1867
|
+
*/
|
|
1868
|
+
const visit = (n) => {
|
|
1869
|
+
if (ts.isIdentifier(n) &&
|
|
1870
|
+
!((ts.isJsxOpeningLikeElement(n.parent) || ts.isJsxClosingElement(n.parent)) && n.parent.tagName === n && /^[a-z]/.test(n.text)) &&
|
|
1871
|
+
!(('name' in n.parent && n.parent.name === n) || ('propertyName' in n.parent && n.parent.propertyName === n)) &&
|
|
1872
|
+
!isImportTypeRef(n) &&
|
|
1873
|
+
!checker.getSymbolAtLocation(n) &&
|
|
1874
|
+
!ts.isPropertyAccessExpression(n.parent) &&
|
|
1875
|
+
!ts.isPropertyAccessChain(n.parent) &&
|
|
1876
|
+
!ts.isQualifiedName(n.parent) &&
|
|
1877
|
+
!importedNames.has(n.text) &&
|
|
1878
|
+
!ts.isImportDeclaration(n.parent) &&
|
|
1879
|
+
!ts.isImportSpecifier(n.parent) &&
|
|
1880
|
+
!ts.isExportSpecifier(n.parent)) {
|
|
1881
|
+
const unique = [...new Set(candidates.get(n.text) ?? [])].filter(c => c !== src);
|
|
1882
|
+
if (unique.length === 1)
|
|
1883
|
+
missing.set(n.text, { source: unique[0], typeOnly: isTypePos(n) });
|
|
1884
|
+
}
|
|
1885
|
+
ts.forEachChild(n, visit);
|
|
1886
|
+
};
|
|
1887
|
+
visit(src);
|
|
1888
|
+
if (!missing.size)
|
|
1889
|
+
continue;
|
|
1890
|
+
// hygiene-ignore single-use -- Resolve missing imports before reading and rewriting the source file.
|
|
1891
|
+
const imports = [...missing.entries()].reduce((g, [n, v]) => {
|
|
1892
|
+
const specifier = relative(dirname(src.fileName), v.source.fileName)
|
|
1893
|
+
.replace(/\\/g, '/')
|
|
1894
|
+
.replace(/\.(?:c|m)?tsx?$/, '')
|
|
1895
|
+
.replace(/\.jsx?$/, '');
|
|
1896
|
+
const moduleName = specifier.startsWith('.') ? specifier : `./${specifier}`;
|
|
1897
|
+
const key = `${v.typeOnly ? 'type:' : 'value:'}${moduleName}`;
|
|
1898
|
+
const names = g.get(key) ?? { moduleName, typeOnly: v.typeOnly, names: [] };
|
|
1899
|
+
names.names.push(n);
|
|
1900
|
+
g.set(key, names);
|
|
1901
|
+
return g;
|
|
1902
|
+
}, new Map());
|
|
1903
|
+
const text = readFileSync(src.fileName, 'utf8');
|
|
1904
|
+
const pos = src.statements.find(s => !ts.isImportDeclaration(s))?.getStart(src) ?? 0;
|
|
1905
|
+
const updated = `${text.slice(0, pos)}${[...imports.values()].map(g => `import ${g.typeOnly ? 'type ' : ''}{ ${g.names.sort().join(', ')} } from '${g.moduleName}';`).join('\n')}\n${text.slice(pos)}`;
|
|
1906
|
+
if (updated !== text)
|
|
1907
|
+
writeFileSync(src.fileName, updated);
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* Runs Knip once and validates its complete machine-readable issue inventory.
|
|
1912
|
+
*
|
|
1913
|
+
* @param cfg Quality configuration defining the repository and Knip executable.
|
|
1914
|
+
*
|
|
1915
|
+
* @return Validated issue records reported by Knip.
|
|
1916
|
+
*/
|
|
1917
|
+
function readKnipIssues(cfg) {
|
|
1918
|
+
// hygiene-ignore single-use -- Resolve the Knip executable before loading or mutating its configuration.
|
|
1919
|
+
const knip = toolPath(cfg, cfg.tools?.knip, 'knip');
|
|
1920
|
+
const knipConfig = [resolve(cfg.configRoot ?? resolve(cfg.root, 'config'), 'knip.json'), resolve(cfg.root, 'knip.json')].find(p => existsSync(p));
|
|
1921
|
+
const config = loadKnipConfig(cfg, knipConfig);
|
|
1922
|
+
const knipRoot = knipWorkingDir(cfg, knipConfig, config);
|
|
1923
|
+
// hygiene-ignore single-use -- Record configured tools in Knip before mapping dependencies and deciding whether a temporary config is needed.
|
|
1924
|
+
const configuredToolUsage = addConfiguredToolsToKnipConfig(cfg, config);
|
|
1925
|
+
const mappedDependencyUsage = mappedKnipDependencyUsage(cfg);
|
|
1926
|
+
if (mappedDependencyUsage.length)
|
|
1927
|
+
config.ignoreDependencies = mergeKnipNames(config.ignoreDependencies, new Set(mappedDependencyUsage));
|
|
1928
|
+
const excludedContent = nonProgramSrcFiles(cfg)
|
|
1929
|
+
.map(path => relative(knipRoot, path).split(sep).join('/'))
|
|
1930
|
+
.filter(path => path !== '..' && !path.startsWith('../') && !isAbsolute(path));
|
|
1931
|
+
const tempConfigRoot = excludedContent.length || configuredToolUsage || mappedDependencyUsage.length ? mkdtempSync(join(tmpdir(), 'hygiene-knip-')) : undefined;
|
|
1932
|
+
let effectiveConfig = knipConfig;
|
|
1933
|
+
if (tempConfigRoot) {
|
|
1934
|
+
config.ignoreFiles = [
|
|
1935
|
+
...new Set([
|
|
1936
|
+
...(Array.isArray(config.ignoreFiles) ? config.ignoreFiles.filter((item) => typeof item === 'string') : typeof config.ignoreFiles === 'string' ? [config.ignoreFiles] : []),
|
|
1937
|
+
...excludedContent,
|
|
1938
|
+
]),
|
|
1939
|
+
];
|
|
1940
|
+
const genConfig = join(tempConfigRoot, 'knip.json');
|
|
1941
|
+
effectiveConfig = genConfig;
|
|
1942
|
+
writeFileSync(genConfig, JSON.stringify(config, null, '\t') + '\n');
|
|
1943
|
+
}
|
|
1944
|
+
let result;
|
|
1945
|
+
try {
|
|
1946
|
+
result = spawnSync(knip, [...(effectiveConfig ? ['--config', effectiveConfig] : []), '--reporter', 'json', '--no-config-hints'], {
|
|
1947
|
+
cwd: knipRoot,
|
|
1948
|
+
encoding: 'utf8',
|
|
1949
|
+
env: process.env,
|
|
1950
|
+
maxBuffer: TOOL_OUTPUT_MAX_BUFFER,
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
finally {
|
|
1954
|
+
if (tempConfigRoot)
|
|
1955
|
+
rmSync(tempConfigRoot, { recursive: true, force: true });
|
|
1956
|
+
}
|
|
1957
|
+
if (result.error || (result.status !== 0 && result.status !== 1))
|
|
1958
|
+
throw new Error(`Knip failed: ${result.error?.message ?? result.stderr ?? result.status}`);
|
|
1959
|
+
let issues;
|
|
1960
|
+
try {
|
|
1961
|
+
const parsed = JSON.parse(result.stdout);
|
|
1962
|
+
if (!Array.isArray(parsed.issues))
|
|
1963
|
+
throw new Error('missing issues array');
|
|
1964
|
+
issues = parsed.issues;
|
|
1965
|
+
for (const issue of issues) {
|
|
1966
|
+
if (!issue || typeof issue.file !== 'string' || !issue.file)
|
|
1967
|
+
throw new Error('finding without a source file');
|
|
1968
|
+
issue.file = knipRepoPath(cfg, knipRoot, issue.file);
|
|
1969
|
+
assertKnipPath(cfg, issue.file, 'finding source');
|
|
1970
|
+
for (const [kind, val] of Object.entries(issue)) {
|
|
1971
|
+
if (kind === 'file')
|
|
1972
|
+
continue;
|
|
1973
|
+
let items;
|
|
1974
|
+
try {
|
|
1975
|
+
items = flattenKnipItems(val);
|
|
1976
|
+
}
|
|
1977
|
+
catch {
|
|
1978
|
+
throw new Error(`invalid ${kind} findings for ${issue.file}`);
|
|
1979
|
+
}
|
|
1980
|
+
for (const i of items) {
|
|
1981
|
+
if (!i || typeof i !== 'object' || Array.isArray(i))
|
|
1982
|
+
throw new Error(`malformed ${kind} finding for ${issue.file}`);
|
|
1983
|
+
const named = i;
|
|
1984
|
+
if (typeof named.name !== 'string' || !named.name || (named.line !== undefined && (typeof named.line !== 'number' || !Number.isInteger(named.line) || named.line < 1)))
|
|
1985
|
+
throw new Error(`malformed ${kind} finding for ${issue.file}`);
|
|
1986
|
+
if (kind === 'files')
|
|
1987
|
+
named.name = knipRepoPath(cfg, knipRoot, named.name);
|
|
1988
|
+
if (kind === 'files')
|
|
1989
|
+
assertKnipPath(cfg, named.name, 'unreachable file');
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
catch (err) {
|
|
1995
|
+
throw new Error(`Knip returned invalid JSON: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
1996
|
+
}
|
|
1997
|
+
if (result.status === 1 && issues.length === 0)
|
|
1998
|
+
throw new Error('Knip reported failure without findings');
|
|
1999
|
+
return issues;
|
|
2000
|
+
}
|
|
2001
|
+
// hygiene-ignore single-use -- Keep the documented mappedKnipDependencyUsage declaration so its parameter and return contract remains attached.
|
|
2002
|
+
/**
|
|
2003
|
+
* Finds declared dependencies actually imported by a source tree owned by a nested package.
|
|
2004
|
+
*
|
|
2005
|
+
* @param cfg Quality configuration containing source-to-package ownership mappings.
|
|
2006
|
+
*
|
|
2007
|
+
* @return Sorted package names whose imports and manifest declarations both exist.
|
|
2008
|
+
*/
|
|
2009
|
+
function mappedKnipDependencyUsage(cfg) {
|
|
2010
|
+
const usedDependencies = new Set();
|
|
2011
|
+
const sourceFiles = srcFiles(cfg);
|
|
2012
|
+
for (const mapping of cfg.knipPackageMappings ?? []) {
|
|
2013
|
+
const packageRoot = resolve(cfg.root, mapping.packageRoot);
|
|
2014
|
+
const packageRelative = relative(cfg.root, packageRoot);
|
|
2015
|
+
if (packageRelative === '..' || packageRelative.startsWith(`..${sep}`) || isAbsolute(packageRelative))
|
|
2016
|
+
throw new Error(`Knip package root is outside the repository: ${mapping.packageRoot}`);
|
|
2017
|
+
const manifestPath = join(packageRoot, 'package.json');
|
|
2018
|
+
if (!existsSync(manifestPath))
|
|
2019
|
+
throw new Error(`Knip package root has no package.json: ${mapping.packageRoot}`);
|
|
2020
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
2021
|
+
const declaredDependencies = new Set();
|
|
2022
|
+
for (const section of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
|
|
2023
|
+
const dependencies = manifest[section];
|
|
2024
|
+
if (dependencies && typeof dependencies === 'object' && !Array.isArray(dependencies)) {
|
|
2025
|
+
for (const name of Object.keys(dependencies))
|
|
2026
|
+
declaredDependencies.add(name);
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
const srcRoots = mapping.sourceRoots.map(srcRoot => resolve(cfg.root, srcRoot));
|
|
2030
|
+
for (const sourceRoot of srcRoots) {
|
|
2031
|
+
const srcRelative = relative(cfg.root, sourceRoot);
|
|
2032
|
+
if (srcRelative === '..' || srcRelative.startsWith(`..${sep}`) || isAbsolute(srcRelative))
|
|
2033
|
+
throw new Error(`Knip source root is outside the repository: ${sourceRoot}`);
|
|
2034
|
+
}
|
|
2035
|
+
const mappedFiles = new Set(sourceFiles.filter(file => srcRoots.some(sourceRoot => file === sourceRoot || file.startsWith(`${sourceRoot}${sep}`))));
|
|
2036
|
+
for (const sourceRoot of srcRoots) {
|
|
2037
|
+
if (existsSync(sourceRoot) && statSync(sourceRoot).isDirectory()) {
|
|
2038
|
+
for (const stylesheet of stylesheetFiles(sourceRoot, cfg.skippedDirectories ?? []))
|
|
2039
|
+
mappedFiles.add(stylesheet);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
for (const file of mappedFiles) {
|
|
2043
|
+
for (const specifier of srcPackageSpecifiers(file)) {
|
|
2044
|
+
const packageName = packageNameFromSpecifier(specifier);
|
|
2045
|
+
if (packageName && declaredDependencies.has(packageName))
|
|
2046
|
+
usedDependencies.add(packageName);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
return [...usedDependencies].sort();
|
|
2051
|
+
}
|
|
2052
|
+
/**
|
|
2053
|
+
* Finds stylesheet source files under mapped roots, excluding dependency and build trees.
|
|
2054
|
+
*
|
|
2055
|
+
* @param root Mapped source directory.
|
|
2056
|
+
* @param additionalSkips Repository-specific directory names excluded from authored sources.
|
|
2057
|
+
*
|
|
2058
|
+
* @return Sorted stylesheet paths under the source root.
|
|
2059
|
+
*/
|
|
2060
|
+
function stylesheetFiles(root, additionalSkips) {
|
|
2061
|
+
const stylesheetExts = new Set(['.css', '.less', '.sass', '.scss']);
|
|
2062
|
+
const skipped = new Set([...NON_WORKSPACE_DIRS, ...additionalSkips]);
|
|
2063
|
+
const files = [];
|
|
2064
|
+
const pending = [root];
|
|
2065
|
+
while (pending.length) {
|
|
2066
|
+
const current = pending.pop();
|
|
2067
|
+
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
|
2068
|
+
const path = join(current, entry.name);
|
|
2069
|
+
if (entry.isDirectory()) {
|
|
2070
|
+
if (!skipped.has(entry.name))
|
|
2071
|
+
pending.push(path);
|
|
2072
|
+
}
|
|
2073
|
+
else if (entry.isFile() && stylesheetExts.has(extname(entry.name).toLowerCase()))
|
|
2074
|
+
files.push(path);
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
return files.sort();
|
|
2078
|
+
}
|
|
2079
|
+
/**
|
|
2080
|
+
* Extracts module specifiers from source imports and stylesheet directives.
|
|
2081
|
+
*
|
|
2082
|
+
* @param file Source file to inspect.
|
|
2083
|
+
*
|
|
2084
|
+
* @return Package and relative module specifiers found in the file.
|
|
2085
|
+
*/
|
|
2086
|
+
function srcPackageSpecifiers(file) {
|
|
2087
|
+
const text = readFileSync(file, 'utf8');
|
|
2088
|
+
const ext = extname(file).toLowerCase();
|
|
2089
|
+
const specifiers = [];
|
|
2090
|
+
const addLiteral = (node) => {
|
|
2091
|
+
if (node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)))
|
|
2092
|
+
specifiers.push(node.text);
|
|
2093
|
+
};
|
|
2094
|
+
const visit = (node) => {
|
|
2095
|
+
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node))
|
|
2096
|
+
addLiteral(node.moduleSpecifier);
|
|
2097
|
+
if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument))
|
|
2098
|
+
addLiteral(node.argument.literal);
|
|
2099
|
+
if (ts.isCallExpression(node)) {
|
|
2100
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword)
|
|
2101
|
+
addLiteral(node.arguments[0]);
|
|
2102
|
+
if (ts.isIdentifier(node.expression) && node.expression.text === 'require')
|
|
2103
|
+
addLiteral(node.arguments[0]);
|
|
2104
|
+
if (ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'resolve') {
|
|
2105
|
+
const resolver = node.expression.expression;
|
|
2106
|
+
if ((ts.isIdentifier(resolver) && resolver.text === 'require') || (ts.isMetaProperty(resolver) && resolver.keywordToken === ts.SyntaxKind.ImportKeyword && resolver.name.text === 'meta'))
|
|
2107
|
+
addLiteral(node.arguments[0]);
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
ts.forEachChild(node, visit);
|
|
2111
|
+
};
|
|
2112
|
+
visit(ts.createSourceFile(file, ext === '.astro' ? (text.match(/^---\s*\r?\n([\s\S]*?)\r?\n---/u)?.[1] ?? '') : text, ts.ScriptTarget.Latest, true, ext === '.tsx' || ext === '.jsx' || ext === '.astro' ? ts.ScriptKind.TSX : ext === '.ts' || ext === '.mts' || ext === '.cts' ? ts.ScriptKind.TS : ts.ScriptKind.JS));
|
|
2113
|
+
if (['.css', '.scss', '.sass', '.less', '.astro'].includes(ext)) {
|
|
2114
|
+
for (const match of text.matchAll(/(?:@import|@use|@forward|@plugin)\s+(?:url\()?\s*["']([^"']+)["']/gu)) {
|
|
2115
|
+
if (match[1])
|
|
2116
|
+
specifiers.push(match[1]);
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
return specifiers;
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
2122
|
+
* Reduces a module specifier to its external package name.
|
|
2123
|
+
*
|
|
2124
|
+
* @param specifier Source import specifier.
|
|
2125
|
+
*
|
|
2126
|
+
* @return External package name, or undefined for relative, absolute, or built-in imports.
|
|
2127
|
+
*/
|
|
2128
|
+
function packageNameFromSpecifier(specifier) {
|
|
2129
|
+
if (!specifier || specifier.startsWith('.') || specifier.startsWith('/') || isBuiltin(specifier))
|
|
2130
|
+
return undefined;
|
|
2131
|
+
const parts = specifier.split('/');
|
|
2132
|
+
return specifier.startsWith('@') ? (parts.length > 1 ? `${parts[0]}/${parts[1]}` : undefined) : parts[0];
|
|
2133
|
+
}
|
|
2134
|
+
// hygiene-ignore single-use -- Keep the documented loadKnipConfig declaration so its parameter and return contract remains attached.
|
|
2135
|
+
/**
|
|
2136
|
+
* Loads Knip settings for the shared source-classification overlay.
|
|
2137
|
+
*
|
|
2138
|
+
* @param cfg Quality configuration defining the repository root.
|
|
2139
|
+
* @param knipConfig Existing Knip configuration file, when present.
|
|
2140
|
+
*
|
|
2141
|
+
* @return Mutable Knip settings used for cwd selection and content-artifact patterns.
|
|
2142
|
+
*/
|
|
2143
|
+
function loadKnipConfig(cfg, knipConfig) {
|
|
2144
|
+
if (!knipConfig) {
|
|
2145
|
+
const configPackage = resolve(cfg.configRoot ?? resolve(cfg.root, 'config'), 'package.json');
|
|
2146
|
+
const packagePath = existsSync(configPackage) ? configPackage : resolve(cfg.root, 'package.json');
|
|
2147
|
+
if (!existsSync(packagePath))
|
|
2148
|
+
return {};
|
|
2149
|
+
const manifest = JSON.parse(readFileSync(packagePath, 'utf8'));
|
|
2150
|
+
return manifest.knip && typeof manifest.knip === 'object' && !Array.isArray(manifest.knip) ? manifest.knip : {};
|
|
2151
|
+
}
|
|
2152
|
+
if (/\.jsonc?$/iu.test(knipConfig)) {
|
|
2153
|
+
const parsed = ts.parseConfigFileTextToJson(knipConfig, readFileSync(knipConfig, 'utf8'));
|
|
2154
|
+
if (parsed.error)
|
|
2155
|
+
throw new Error(`Could not parse Knip configuration ${knipConfig}: ${ts.flattenDiagnosticMessageText(parsed.error.messageText, '\n')}`);
|
|
2156
|
+
if (!parsed.config || typeof parsed.config !== 'object' || Array.isArray(parsed.config))
|
|
2157
|
+
throw new Error(`Knip configuration must contain an object: ${knipConfig}`);
|
|
2158
|
+
return parsed.config;
|
|
2159
|
+
}
|
|
2160
|
+
if (/\.[cm]?js$/iu.test(knipConfig)) {
|
|
2161
|
+
const loaded = spawnSync(process.execPath, [
|
|
2162
|
+
'--input-type=module',
|
|
2163
|
+
'-e',
|
|
2164
|
+
"import { pathToFileURL } from 'node:url'; const loaded = await import(pathToFileURL(process.argv[1]).href); const config = loaded.default ?? loaded; process.stdout.write(JSON.stringify(config));",
|
|
2165
|
+
knipConfig,
|
|
2166
|
+
], { cwd: cfg.root, encoding: 'utf8', maxBuffer: TOOL_OUTPUT_MAX_BUFFER });
|
|
2167
|
+
if (loaded.error || loaded.status !== 0)
|
|
2168
|
+
throw new Error(`Could not load Knip configuration ${knipConfig}: ${loaded.error?.message ?? loaded.stderr ?? loaded.status}`);
|
|
2169
|
+
try {
|
|
2170
|
+
const parsed = JSON.parse(loaded.stdout);
|
|
2171
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
2172
|
+
throw new Error('configuration must export an object');
|
|
2173
|
+
return parsed;
|
|
2174
|
+
}
|
|
2175
|
+
catch (err) {
|
|
2176
|
+
throw new Error(`Could not read Knip configuration ${knipConfig}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
throw new Error(`Cannot apply shared source classification to Knip configuration ${knipConfig}; use a JSON, JSONC, or JavaScript config.`);
|
|
2180
|
+
}
|
|
2181
|
+
// hygiene-ignore single-use -- Keep the documented addConfiguredToolsToKnipConfig declaration so its parameter and return contract remains attached.
|
|
2182
|
+
/**
|
|
2183
|
+
* Adds configured executable usage to the temporary Knip settings.
|
|
2184
|
+
*
|
|
2185
|
+
* @param cfg Quality configuration that declares executable paths.
|
|
2186
|
+
* @param config Knip settings loaded for this run.
|
|
2187
|
+
*
|
|
2188
|
+
* @return Whether configured tool usage was added to the settings.
|
|
2189
|
+
*/
|
|
2190
|
+
function addConfiguredToolsToKnipConfig(cfg, config) {
|
|
2191
|
+
const dependencyNames = new Set();
|
|
2192
|
+
const binaryNames = new Set();
|
|
2193
|
+
for (const configuredPath of Object.values(cfg.tools ?? {})) {
|
|
2194
|
+
if (!configuredPath)
|
|
2195
|
+
continue;
|
|
2196
|
+
const executableName = basename(configuredPath).replace(/\.exe$/iu, '');
|
|
2197
|
+
const dependencyName = executableName === 'tsc' ? 'typescript' : executableName;
|
|
2198
|
+
const executablePath = configuredToolPath(cfg, configuredPath);
|
|
2199
|
+
if (executablePath && toolDependencyOwner(cfg, executablePath, dependencyName))
|
|
2200
|
+
dependencyNames.add(dependencyName);
|
|
2201
|
+
else
|
|
2202
|
+
binaryNames.add(executableName);
|
|
2203
|
+
}
|
|
2204
|
+
if (!dependencyNames.size && !binaryNames.size)
|
|
2205
|
+
return false;
|
|
2206
|
+
if (dependencyNames.size)
|
|
2207
|
+
config.ignoreDependencies = mergeKnipNames(config.ignoreDependencies, dependencyNames);
|
|
2208
|
+
if (binaryNames.size)
|
|
2209
|
+
config.ignoreBinaries = mergeKnipNames(config.ignoreBinaries, binaryNames);
|
|
2210
|
+
return true;
|
|
2211
|
+
}
|
|
2212
|
+
/**
|
|
2213
|
+
* Resolves a configured executable path from the repository or configuration package.
|
|
2214
|
+
*
|
|
2215
|
+
* @param cfg Quality configuration defining the repository and tool-config roots.
|
|
2216
|
+
* @param configuredPath Executable path or command name from quality.json.
|
|
2217
|
+
*
|
|
2218
|
+
* @return Resolved executable path when it exists locally.
|
|
2219
|
+
*/
|
|
2220
|
+
function configuredToolPath(cfg, configuredPath) {
|
|
2221
|
+
if (configuredPath.includes('/') || configuredPath.includes('\\')) {
|
|
2222
|
+
const path = isAbsolute(configuredPath) ? configuredPath : resolve(cfg.root, configuredPath);
|
|
2223
|
+
return existsSync(path) ? path : undefined;
|
|
2224
|
+
}
|
|
2225
|
+
return [resolve(cfg.root, 'node_modules', '.bin', configuredPath), resolve(cfg.configRoot ?? resolve(cfg.root, 'config'), 'node_modules', '.bin', configuredPath)].find(existsSync);
|
|
2226
|
+
}
|
|
2227
|
+
/**
|
|
2228
|
+
* Finds the nearest package manifest that declares a configured executable dependency.
|
|
2229
|
+
*
|
|
2230
|
+
* @param cfg Quality configuration defining the repository boundary.
|
|
2231
|
+
* @param executablePath Resolved executable path.
|
|
2232
|
+
* @param dependencyName Package name inferred from the executable name.
|
|
2233
|
+
*
|
|
2234
|
+
* @return Owning package root when the dependency is declared.
|
|
2235
|
+
*/
|
|
2236
|
+
function toolDependencyOwner(cfg, executablePath, dependencyName) {
|
|
2237
|
+
let dir = dirname(executablePath);
|
|
2238
|
+
while (dir === cfg.root || dir.startsWith(`${cfg.root}${sep}`)) {
|
|
2239
|
+
const manifestPath = join(dir, 'package.json');
|
|
2240
|
+
if (existsSync(manifestPath)) {
|
|
2241
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
2242
|
+
if (['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].some(field => {
|
|
2243
|
+
const deps = manifest[field];
|
|
2244
|
+
return !!deps && typeof deps === 'object' && dependencyName in deps;
|
|
2245
|
+
}))
|
|
2246
|
+
return dir;
|
|
2247
|
+
}
|
|
2248
|
+
if (dir === cfg.root)
|
|
2249
|
+
break;
|
|
2250
|
+
const parent = dirname(dir);
|
|
2251
|
+
if (parent === dir)
|
|
2252
|
+
break;
|
|
2253
|
+
dir = parent;
|
|
2254
|
+
}
|
|
2255
|
+
return undefined;
|
|
2256
|
+
}
|
|
2257
|
+
/**
|
|
2258
|
+
* Merges configured tool names into one Knip setting without duplicating existing entries.
|
|
2259
|
+
*
|
|
2260
|
+
* @param existing Existing Knip setting value.
|
|
2261
|
+
* @param additions Configured package or binary names used by Quality.
|
|
2262
|
+
*
|
|
2263
|
+
* @return Sorted unique names for the temporary Knip configuration.
|
|
2264
|
+
*/
|
|
2265
|
+
function mergeKnipNames(existing, additions) {
|
|
2266
|
+
const names = new Set(Array.isArray(existing) ? existing.filter((name) => typeof name === 'string') : typeof existing === 'string' ? [existing] : []);
|
|
2267
|
+
for (const name of additions)
|
|
2268
|
+
names.add(name);
|
|
2269
|
+
return [...names].sort();
|
|
2270
|
+
}
|
|
2271
|
+
// hygiene-ignore single-use -- Keep the documented knipWorkingDir declaration so its parameter and return contract remains attached.
|
|
2272
|
+
/**
|
|
2273
|
+
* Selects the package root for Knip while preserving explicit repository workspaces.
|
|
2274
|
+
*
|
|
2275
|
+
* @param cfg Quality configuration defining the repository and optional config root.
|
|
2276
|
+
* @param knipConfig Existing Knip configuration file, when present.
|
|
2277
|
+
* @param knipSettings Parsed Knip configuration used to detect root-relative workspaces.
|
|
2278
|
+
*
|
|
2279
|
+
* @return The directory Knip should use as its working root.
|
|
2280
|
+
*/
|
|
2281
|
+
function knipWorkingDir(cfg, knipConfig, knipSettings) {
|
|
2282
|
+
const configRoot = resolve(cfg.configRoot ?? resolve(cfg.root, 'config'));
|
|
2283
|
+
const configPath = knipConfig ? relative(configRoot, knipConfig) : existsSync(join(configRoot, 'package.json')) ? '' : '..';
|
|
2284
|
+
const workspaces = knipSettings.workspaces;
|
|
2285
|
+
if (!!workspaces && typeof workspaces === 'object' && Object.keys(workspaces).length > 0) {
|
|
2286
|
+
const scored = [...new Set([configRoot, cfg.root])].map(root => ({ root, score: knipWorkspaceRootScore(cfg.root, root, workspaces) }));
|
|
2287
|
+
scored.sort((left, right) => right.score - left.score);
|
|
2288
|
+
if (scored[0].score >= 0 && (scored.length === 1 || scored[0].score > scored[1].score))
|
|
2289
|
+
return scored[0].root;
|
|
2290
|
+
if (existsSync(join(configRoot, 'package.json')))
|
|
2291
|
+
return configRoot;
|
|
2292
|
+
return cfg.root;
|
|
2293
|
+
}
|
|
2294
|
+
let configMatches = 0;
|
|
2295
|
+
let repoMatches = 0;
|
|
2296
|
+
for (const pattern of [...(Array.isArray(knipSettings.entry) ? knipSettings.entry : []), ...(Array.isArray(knipSettings.project) ? knipSettings.project : [])]) {
|
|
2297
|
+
if (typeof pattern !== 'string')
|
|
2298
|
+
continue;
|
|
2299
|
+
const prefix = knipLiteralPrefix(pattern);
|
|
2300
|
+
if (!prefix)
|
|
2301
|
+
continue;
|
|
2302
|
+
if (existsSync(resolve(configRoot, prefix)))
|
|
2303
|
+
configMatches++;
|
|
2304
|
+
if (existsSync(resolve(cfg.root, prefix)))
|
|
2305
|
+
repoMatches++;
|
|
2306
|
+
}
|
|
2307
|
+
if (repoMatches > configMatches)
|
|
2308
|
+
return cfg.root;
|
|
2309
|
+
if (configMatches > repoMatches)
|
|
2310
|
+
return configRoot;
|
|
2311
|
+
if (configPath !== '..' && !configPath.startsWith(`..${sep}`) && !isAbsolute(configPath) && existsSync(join(configRoot, 'package.json')))
|
|
2312
|
+
return configRoot;
|
|
2313
|
+
return cfg.root;
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Scores a candidate Knip working root against explicit workspace paths and source globs.
|
|
2317
|
+
*
|
|
2318
|
+
* @param repoRoot Quality repository boundary that candidate workspace paths must remain inside.
|
|
2319
|
+
* @param workingRoot Candidate directory Knip would interpret workspace paths from.
|
|
2320
|
+
* @param workspaces Knip workspace configuration keyed by relative package paths.
|
|
2321
|
+
*
|
|
2322
|
+
* @return A nonnegative score for in-repository workspace layouts, or `-1` when a workspace escapes.
|
|
2323
|
+
*/
|
|
2324
|
+
function knipWorkspaceRootScore(repoRoot, workingRoot, workspaces) {
|
|
2325
|
+
const repo = resolve(repoRoot);
|
|
2326
|
+
const root = resolve(workingRoot);
|
|
2327
|
+
let score = 0;
|
|
2328
|
+
for (const [workspace, rawSettings] of Object.entries(workspaces)) {
|
|
2329
|
+
const workspacePrefix = knipLiteralPrefix(workspace);
|
|
2330
|
+
const workspacePath = resolve(root, workspacePrefix || '.');
|
|
2331
|
+
const workspaceRelative = relative(repo, workspacePath);
|
|
2332
|
+
if (workspaceRelative === '..' || workspaceRelative.startsWith(`..${sep}`) || isAbsolute(workspaceRelative))
|
|
2333
|
+
return -1;
|
|
2334
|
+
if (existsSync(workspacePath))
|
|
2335
|
+
score += 1;
|
|
2336
|
+
if (existsSync(join(workspacePath, 'package.json')))
|
|
2337
|
+
score += 3;
|
|
2338
|
+
else if (existsSync(workspacePath) && readdirSync(workspacePath, { withFileTypes: true }).some(entry => entry.isDirectory() && existsSync(join(workspacePath, entry.name, 'package.json'))))
|
|
2339
|
+
score += 2;
|
|
2340
|
+
if (workspacePrefix !== workspace || !rawSettings || typeof rawSettings !== 'object' || Array.isArray(rawSettings))
|
|
2341
|
+
continue;
|
|
2342
|
+
const settings = rawSettings;
|
|
2343
|
+
for (const pattern of [...(Array.isArray(settings.entry) ? settings.entry : []), ...(Array.isArray(settings.project) ? settings.project : [])]) {
|
|
2344
|
+
if (typeof pattern !== 'string' || !pattern)
|
|
2345
|
+
continue;
|
|
2346
|
+
const literalPrefix = knipLiteralPrefix(pattern);
|
|
2347
|
+
const target = resolve(workspacePath, literalPrefix || '.');
|
|
2348
|
+
const targetRelative = relative(repo, target);
|
|
2349
|
+
if (targetRelative === '..' || targetRelative.startsWith(`..${sep}`) || isAbsolute(targetRelative))
|
|
2350
|
+
return -1;
|
|
2351
|
+
if (existsSync(target))
|
|
2352
|
+
score += literalPrefix !== pattern ? 1 : 2;
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
return score;
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* Returns the non-glob path prefix of a Knip workspace or source pattern.
|
|
2359
|
+
*
|
|
2360
|
+
* @param pattern Knip-relative path that may contain glob syntax.
|
|
2361
|
+
*
|
|
2362
|
+
* @return The path before its first wildcard token.
|
|
2363
|
+
*/
|
|
2364
|
+
function knipLiteralPrefix(pattern) {
|
|
2365
|
+
const wildcardIndexes = ['*', '?', '{', '['].map(token => pattern.indexOf(token)).filter(i => i >= 0);
|
|
2366
|
+
return pattern.slice(0, wildcardIndexes.length ? Math.min(...wildcardIndexes) : pattern.length).replace(/[\\/]+$/u, '');
|
|
2367
|
+
}
|
|
2368
|
+
/**
|
|
2369
|
+
* Resolves a Knip-relative path to the repository-relative path used by Quality diagnostics.
|
|
2370
|
+
*
|
|
2371
|
+
* @param cfg Quality configuration defining the repository root.
|
|
2372
|
+
* @param knipRoot Directory from which Knip ran.
|
|
2373
|
+
* @param path Path reported by Knip.
|
|
2374
|
+
*
|
|
2375
|
+
* @return Normalized repository-relative path.
|
|
2376
|
+
*/
|
|
2377
|
+
function knipRepoPath(cfg, knipRoot, path) {
|
|
2378
|
+
return relative(cfg.root, resolve(knipRoot, path)).split(sep).join('/');
|
|
2379
|
+
}
|
|
2380
|
+
/**
|
|
2381
|
+
* Rejects malformed, missing, or out-of-repository paths in Knip's inventory.
|
|
2382
|
+
*
|
|
2383
|
+
* @param cfg Quality configuration defining the repository boundary.
|
|
2384
|
+
* @param path Relative Knip path to validate.
|
|
2385
|
+
* @param label Description used in validation errors.
|
|
2386
|
+
*
|
|
2387
|
+
* @return The resolved absolute path inside the repository.
|
|
2388
|
+
*/
|
|
2389
|
+
function assertKnipPath(cfg, path, label) {
|
|
2390
|
+
const absolute = resolve(cfg.root, path);
|
|
2391
|
+
const rel = relative(cfg.root, absolute);
|
|
2392
|
+
if (isAbsolute(path) || rel === '..' || rel.startsWith(`..${sep}`))
|
|
2393
|
+
throw new Error(`Knip returned a ${label} path outside the repository: ${path}`);
|
|
2394
|
+
if (!existsSync(absolute))
|
|
2395
|
+
throw new Error(`Knip returned a ${label} path that does not exist: ${path}`);
|
|
2396
|
+
const realRelative = relative(realpathSync(cfg.root), realpathSync(absolute));
|
|
2397
|
+
if (realRelative === '..' || realRelative.startsWith(`..${sep}`) || isAbsolute(realRelative))
|
|
2398
|
+
throw new Error(`Knip returned a ${label} symlink outside the repository: ${path}`);
|
|
2399
|
+
return absolute;
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* Checks whether a name is a configured framework-discovered route export.
|
|
2403
|
+
*
|
|
2404
|
+
* @param cfg Quality configuration containing framework entry exports.
|
|
2405
|
+
* @param file Repository-relative source filename reported by Knip.
|
|
2406
|
+
* @param name Exported identifier to check.
|
|
2407
|
+
*
|
|
2408
|
+
* @return Whether the configured file or supported TypeScript route pattern includes the export.
|
|
2409
|
+
*/
|
|
2410
|
+
function isFrameworkEntryExport(cfg, file, name) {
|
|
2411
|
+
const publicRoute = !basename(file).startsWith('_');
|
|
2412
|
+
return Object.entries(cfg.frameworkEntryExports ?? {}).some(([p, n]) => {
|
|
2413
|
+
return ((p === file ||
|
|
2414
|
+
(publicRoute && p.endsWith('/**/*.ts') && file.startsWith(p.slice(0, -8)) && file.endsWith('.ts')) ||
|
|
2415
|
+
(publicRoute && p.endsWith('/**/*.tsx') && file.startsWith(p.slice(0, -9)) && file.endsWith('.tsx'))) &&
|
|
2416
|
+
n.includes(name));
|
|
2417
|
+
});
|
|
2418
|
+
}
|
|
2419
|
+
/**
|
|
2420
|
+
* Selects the TypeScript parser mode from a source filename's extension.
|
|
2421
|
+
*
|
|
2422
|
+
* @param file Source filename to classify.
|
|
2423
|
+
*
|
|
2424
|
+
* @return The JavaScript, JSX, TypeScript, or TSX compiler script kind.
|
|
2425
|
+
*/
|
|
2426
|
+
function deadCodeScriptKind(file) {
|
|
2427
|
+
if (/\.tsx$/i.test(file))
|
|
2428
|
+
return ts.ScriptKind.TSX;
|
|
2429
|
+
if (/\.jsx$/i.test(file))
|
|
2430
|
+
return ts.ScriptKind.JSX;
|
|
2431
|
+
if (/\.(?:c|m)?js$/i.test(file))
|
|
2432
|
+
return ts.ScriptKind.JS;
|
|
2433
|
+
return ts.ScriptKind.TS;
|
|
2434
|
+
}
|
|
2435
|
+
/**
|
|
2436
|
+
* Checks whether Knip identified a direct named export that can become private.
|
|
2437
|
+
*
|
|
2438
|
+
* @param file Absolute source filename containing the export.
|
|
2439
|
+
* @param name Exported identifier reported by Knip.
|
|
2440
|
+
*
|
|
2441
|
+
* @return Whether the export modifier can be removed without an ambiguous rewrite.
|
|
2442
|
+
*/
|
|
2443
|
+
function knipExportCanBeMadePrivate(file, name) {
|
|
2444
|
+
if (!existsSync(file) || file.endsWith('.astro'))
|
|
2445
|
+
return false;
|
|
2446
|
+
const srcText = readFileSync(file, 'utf8');
|
|
2447
|
+
if (hasGeneratedSourceHeader(srcText))
|
|
2448
|
+
return false;
|
|
2449
|
+
const src = ts.createSourceFile(file, srcText, ts.ScriptTarget.Latest, true, deadCodeScriptKind(file));
|
|
2450
|
+
if (src.parseDiagnostics.length)
|
|
2451
|
+
throw new Error(`Cannot safely classify Knip export in unparsable source: ${file}`);
|
|
2452
|
+
for (const statement of src.statements) {
|
|
2453
|
+
if (!ts.canHaveModifiers(statement) || !ts.getModifiers(statement)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword))
|
|
2454
|
+
continue;
|
|
2455
|
+
if (ts.getModifiers(statement)?.some(m => m.kind === ts.SyntaxKind.DefaultKeyword))
|
|
2456
|
+
continue;
|
|
2457
|
+
if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
|
|
2458
|
+
if (statement.exportClause.elements.some(e => e.name.text === name) && !SHARED_REGEX.test(srcText.slice(statement.exportClause.getStart(src), statement.exportClause.end)))
|
|
2459
|
+
return true;
|
|
2460
|
+
}
|
|
2461
|
+
else if (ts.isVariableStatement(statement)) {
|
|
2462
|
+
const declaration = statement.declarationList.declarations[0];
|
|
2463
|
+
if (statement.declarationList.declarations.length === 1 && declaration && ts.isIdentifier(declaration.name) && declaration.name.text === name)
|
|
2464
|
+
return true;
|
|
2465
|
+
}
|
|
2466
|
+
else if ('name' in statement && statement.name && ts.isIdentifier(statement.name) && statement.name.text === name)
|
|
2467
|
+
return true;
|
|
2468
|
+
}
|
|
2469
|
+
return false;
|
|
2470
|
+
}
|
|
2471
|
+
// hygiene-ignore single-use -- Keep the documented fixKnipExports declaration so its parameter and return contract remains attached.
|
|
2472
|
+
/**
|
|
2473
|
+
* Removes only an unused export modifier that Knip identifies precisely.
|
|
2474
|
+
*
|
|
2475
|
+
* @param cfg Quality configuration defining source scope and Knip output.
|
|
2476
|
+
* @param changedFiles Set updated with files whose export modifiers are removed.
|
|
2477
|
+
*/
|
|
2478
|
+
function fixKnipExports(cfg, changedFiles) {
|
|
2479
|
+
const issues = readKnipIssues(cfg);
|
|
2480
|
+
const importedConsumers = importedExportConsumers(cfg);
|
|
2481
|
+
for (const issue of issues) {
|
|
2482
|
+
const exports = [...(Array.isArray(issue.exports) ? issue.exports : []), ...(Array.isArray(issue.types) ? issue.types : [])];
|
|
2483
|
+
if (!exports.length || issue.file.endsWith('.astro'))
|
|
2484
|
+
continue;
|
|
2485
|
+
const file = assertKnipPath(cfg, issue.file, 'finding source');
|
|
2486
|
+
const src = readFileSync(file, 'utf8');
|
|
2487
|
+
if (hasGeneratedSourceHeader(src))
|
|
2488
|
+
continue;
|
|
2489
|
+
const ast = ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, deadCodeScriptKind(file));
|
|
2490
|
+
if (ast.parseDiagnostics.length)
|
|
2491
|
+
throw new Error(`Cannot safely fix Knip exports in unparsable source: ${issue.file}`);
|
|
2492
|
+
const edits = [];
|
|
2493
|
+
const removableNames = new Set(exports.filter(f => f && typeof f.name === 'string' && !isFrameworkEntryExport(cfg, issue.file, f.name) && !hasImportedExportConsumer(importedConsumers, file, f.name)).map(f => f.name));
|
|
2494
|
+
const handledNames = new Set();
|
|
2495
|
+
for (const statement of ast.statements) {
|
|
2496
|
+
if (!ts.isExportDeclaration(statement) || !statement.exportClause || !ts.isNamedExports(statement.exportClause))
|
|
2497
|
+
continue;
|
|
2498
|
+
const removed = statement.exportClause.elements.filter(s => removableNames.has(s.name.text));
|
|
2499
|
+
if (!removed.length || SHARED_REGEX.test(src.slice(statement.exportClause.getStart(ast), statement.exportClause.end)))
|
|
2500
|
+
continue;
|
|
2501
|
+
for (const specifier of removed)
|
|
2502
|
+
handledNames.add(specifier.name.text);
|
|
2503
|
+
const retained = statement.exportClause.elements.filter(s => !removableNames.has(s.name.text));
|
|
2504
|
+
let end = statement.end;
|
|
2505
|
+
if (!retained.length) {
|
|
2506
|
+
if (src[end] === '\r' && src[end + 1] === '\n')
|
|
2507
|
+
end += 2;
|
|
2508
|
+
else if (src[end] === '\n')
|
|
2509
|
+
end++;
|
|
2510
|
+
edits.push({
|
|
2511
|
+
start: statement.getStart(ast),
|
|
2512
|
+
end,
|
|
2513
|
+
text: statement.moduleSpecifier && !statement.isTypeOnly ? `import ${statement.moduleSpecifier.getText(ast)}${src.slice(statement.moduleSpecifier.end, statement.end)}` : '',
|
|
2514
|
+
});
|
|
2515
|
+
}
|
|
2516
|
+
else {
|
|
2517
|
+
edits.push({
|
|
2518
|
+
start: statement.getStart(ast),
|
|
2519
|
+
end: statement.end,
|
|
2520
|
+
text: `${src.slice(statement.getStart(ast), statement.exportClause.getStart(ast))}{ ${retained.map(s => s.getText(ast)).join(', ')} }${src.slice(statement.exportClause.end, statement.end)}`,
|
|
2521
|
+
});
|
|
2522
|
+
}
|
|
2523
|
+
}
|
|
2524
|
+
for (const finding of exports) {
|
|
2525
|
+
if (!finding || typeof finding.name !== 'string' || !finding.name)
|
|
2526
|
+
throw new Error(`Knip returned malformed export findings for ${issue.file}`);
|
|
2527
|
+
if (!removableNames.has(finding.name) || isFrameworkEntryExport(cfg, issue.file, finding.name) || handledNames.has(finding.name))
|
|
2528
|
+
continue;
|
|
2529
|
+
const declaration = ast.statements.find(s => {
|
|
2530
|
+
if (!ts.canHaveModifiers(s) || !ts.getModifiers(s)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword))
|
|
2531
|
+
return false;
|
|
2532
|
+
if (ts.getModifiers(s)?.some(m => m.kind === ts.SyntaxKind.DefaultKeyword))
|
|
2533
|
+
return false;
|
|
2534
|
+
if (ts.isVariableStatement(s))
|
|
2535
|
+
return s.declarationList.declarations.length === 1 && ts.isIdentifier(s.declarationList.declarations[0].name) && s.declarationList.declarations[0].name.text === finding.name;
|
|
2536
|
+
return 'name' in s && s.name && ts.isIdentifier(s.name) && s.name.text === finding.name;
|
|
2537
|
+
});
|
|
2538
|
+
if (!declaration || (finding.line && declaration.getStart(ast) > ast.getPositionOfLineAndCharacter(finding.line - 1, 0)))
|
|
2539
|
+
continue;
|
|
2540
|
+
const modifier = ts.getModifiers(declaration)?.find(i => i.kind === ts.SyntaxKind.ExportKeyword);
|
|
2541
|
+
if (modifier)
|
|
2542
|
+
edits.push({ start: modifier.getStart(ast), end: src[modifier.end] === ' ' || src[modifier.end] === '\t' ? modifier.end + 1 : modifier.end });
|
|
2543
|
+
}
|
|
2544
|
+
const uniqueEdits = [...new Map(edits.map(e => [e.start, e])).values()].sort((l, r) => r.start - l.start);
|
|
2545
|
+
if (uniqueEdits.length) {
|
|
2546
|
+
writeFileSync(file, uniqueEdits.reduce((t, e) => `${t.slice(0, e.start)}${e.text ?? ''}${t.slice(e.end)}`, src));
|
|
2547
|
+
changedFiles.add(file);
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
/** Finds export names that configured source files import and actually reference. */
|
|
2552
|
+
const importedExportConsumerCache = new WeakMap();
|
|
2553
|
+
/**
|
|
2554
|
+
* Builds a cache of exported names referenced by configured source consumers.
|
|
2555
|
+
*
|
|
2556
|
+
* @param cfg Quality configuration defining roots, aliases, and skipped paths.
|
|
2557
|
+
*
|
|
2558
|
+
* @return Export names grouped by their resolved absolute source file.
|
|
2559
|
+
*/
|
|
2560
|
+
function importedExportConsumers(cfg) {
|
|
2561
|
+
const srcFiles = filesFor(cfg, true).filter(p => C_M_JS_TS_X_CLASS_2.test(p) || p.endsWith('.astro'));
|
|
2562
|
+
const signature = srcFiles
|
|
2563
|
+
.map(f => {
|
|
2564
|
+
const stats = statSync(f);
|
|
2565
|
+
return `${f}:${stats.mtimeMs}:${stats.size}`;
|
|
2566
|
+
})
|
|
2567
|
+
.join('\n');
|
|
2568
|
+
const cached = importedExportConsumerCache.get(cfg);
|
|
2569
|
+
if (cached?.signature === signature)
|
|
2570
|
+
return cached.consumers;
|
|
2571
|
+
const consumers = new Map();
|
|
2572
|
+
const compilerOpts = {
|
|
2573
|
+
baseUrl: cfg.root,
|
|
2574
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
2575
|
+
paths: Object.fromEntries(Object.entries(cfg.aliases ?? {}).map(([p, t]) => [p.endsWith('*') ? p : `${p}*`, [t.endsWith('*') ? t : `${t}*`]])),
|
|
2576
|
+
};
|
|
2577
|
+
const moduleResolutionCache = ts.createModuleResolutionCache(cfg.root, f => f, compilerOpts);
|
|
2578
|
+
const progressStep = Math.max(1, Math.ceil(srcFiles.length / 20));
|
|
2579
|
+
qualityProgress('Knip import consumers', 0, srcFiles.length);
|
|
2580
|
+
for (const [srcIdx, file] of srcFiles.entries()) {
|
|
2581
|
+
if (srcIdx % progressStep === 0 || srcIdx + 1 === srcFiles.length)
|
|
2582
|
+
qualityProgress('Knip import consumers', srcIdx + 1, srcFiles.length);
|
|
2583
|
+
const raw = readFileSync(file, 'utf8');
|
|
2584
|
+
const astro = file.endsWith('.astro') ? /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(raw) : null;
|
|
2585
|
+
if (file.endsWith('.astro') && !astro)
|
|
2586
|
+
continue;
|
|
2587
|
+
const markup = astro ? raw.slice(astro[0].length) : '';
|
|
2588
|
+
const src = ts.createSourceFile(file, astro?.[1] ?? raw, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
2589
|
+
/**
|
|
2590
|
+
* Checks whether an Astro markup section contains the given identifier spelling.
|
|
2591
|
+
*
|
|
2592
|
+
* @param name Name or identifier spelling being checked.
|
|
2593
|
+
*
|
|
2594
|
+
* @return Whether the markup contains the identifier spelling.
|
|
2595
|
+
*/
|
|
2596
|
+
const markupUses = (name) => Boolean(markup) && markup.includes(name);
|
|
2597
|
+
const referencedIdentifiers = new Set();
|
|
2598
|
+
const namespaceProps = new Map();
|
|
2599
|
+
const importTypeRefs = [];
|
|
2600
|
+
/**
|
|
2601
|
+
* Collects value identifiers and namespace properties referenced by a source file.
|
|
2602
|
+
*
|
|
2603
|
+
* @param node Current syntax-tree node being inspected.
|
|
2604
|
+
*/
|
|
2605
|
+
const collectRefs = (node) => {
|
|
2606
|
+
if (ts.isImportDeclaration(node))
|
|
2607
|
+
return;
|
|
2608
|
+
if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) && ts.isStringLiteral(node.argument.literal)) {
|
|
2609
|
+
const qualifier = node.qualifier;
|
|
2610
|
+
importTypeRefs.push({ specifier: node.argument.literal.text, name: qualifier ? (ts.isIdentifier(qualifier) ? qualifier.text : qualifier.right.text) : '*' });
|
|
2611
|
+
}
|
|
2612
|
+
if (ts.isIdentifier(node))
|
|
2613
|
+
referencedIdentifiers.add(node.text);
|
|
2614
|
+
if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
|
|
2615
|
+
const props = namespaceProps.get(node.expression.text) ?? new Set();
|
|
2616
|
+
props.add(node.name.text);
|
|
2617
|
+
namespaceProps.set(node.expression.text, props);
|
|
2618
|
+
}
|
|
2619
|
+
ts.forEachChild(node, collectRefs);
|
|
2620
|
+
};
|
|
2621
|
+
collectRefs(src);
|
|
2622
|
+
for (const statement of src.statements) {
|
|
2623
|
+
if ((!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) || !statement.moduleSpecifier || !ts.isStringLiteral(statement.moduleSpecifier))
|
|
2624
|
+
continue;
|
|
2625
|
+
const resolved = ts.resolveModuleName(statement.moduleSpecifier.text, file, compilerOpts, ts.sys, moduleResolutionCache).resolvedModule?.resolvedFileName;
|
|
2626
|
+
if (!resolved)
|
|
2627
|
+
continue;
|
|
2628
|
+
const owner = resolve(resolved);
|
|
2629
|
+
const names = consumers.get(owner) ?? new Set();
|
|
2630
|
+
if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
|
|
2631
|
+
for (const specifier of statement.exportClause.elements)
|
|
2632
|
+
names.add(specifier.propertyName?.text ?? specifier.name.text);
|
|
2633
|
+
consumers.set(owner, names);
|
|
2634
|
+
continue;
|
|
2635
|
+
}
|
|
2636
|
+
if (!ts.isImportDeclaration(statement))
|
|
2637
|
+
continue;
|
|
2638
|
+
const bindings = statement.importClause?.namedBindings;
|
|
2639
|
+
if (!bindings)
|
|
2640
|
+
continue;
|
|
2641
|
+
if (ts.isNamedImports(bindings)) {
|
|
2642
|
+
for (const specifier of bindings.elements) {
|
|
2643
|
+
if (referencedIdentifiers.has(specifier.name.text) || markupUses(specifier.name.text))
|
|
2644
|
+
names.add(specifier.propertyName?.text ?? specifier.name.text);
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
else if (ts.isNamespaceImport(bindings)) {
|
|
2648
|
+
for (const prop of namespaceProps.get(bindings.name.text) ?? [])
|
|
2649
|
+
names.add(prop);
|
|
2650
|
+
if (markupUses(bindings.name.text)) {
|
|
2651
|
+
for (const match of markup.matchAll(new RegExp(`<\\s*${bindings.name.text}\\.([A-Za-z_$][\\w$]*)(?:[\\s/>])`, 'g')))
|
|
2652
|
+
names.add(match[1]);
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
if (names.size)
|
|
2656
|
+
consumers.set(owner, names);
|
|
2657
|
+
}
|
|
2658
|
+
for (const { specifier, name } of importTypeRefs) {
|
|
2659
|
+
const resolved = ts.resolveModuleName(specifier, file, compilerOpts, ts.sys, moduleResolutionCache).resolvedModule?.resolvedFileName;
|
|
2660
|
+
if (!resolved)
|
|
2661
|
+
continue;
|
|
2662
|
+
const owner = resolve(resolved);
|
|
2663
|
+
const names = consumers.get(owner) ?? new Set();
|
|
2664
|
+
names.add(name);
|
|
2665
|
+
consumers.set(owner, names);
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
importedExportConsumerCache.set(cfg, { signature, consumers });
|
|
2669
|
+
return consumers;
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* Checks direct, namespace, and import-type references to one exported name.
|
|
2673
|
+
*
|
|
2674
|
+
* @param importedConsumers Exported names found in importing source files.
|
|
2675
|
+
* @param file Absolute path of the module that declares the export.
|
|
2676
|
+
* @param name Export name to check.
|
|
2677
|
+
*
|
|
2678
|
+
* @return Whether an importing file references the name or the module namespace.
|
|
2679
|
+
*/
|
|
2680
|
+
function hasImportedExportConsumer(importedConsumers, file, name) {
|
|
2681
|
+
const names = importedConsumers.get(resolve(file));
|
|
2682
|
+
return Boolean(names?.has(name) || names?.has('*'));
|
|
2683
|
+
}
|
|
2684
|
+
// hygiene-ignore single-use -- Keep the documented acceptTypeSafeEdits declaration so its parameter and return contract remains attached.
|
|
2685
|
+
/**
|
|
2686
|
+
* Accepts proposed edits only when they add no TypeScript errors to changed files.
|
|
2687
|
+
*
|
|
2688
|
+
* @param program TypeScript program representing the original source.
|
|
2689
|
+
* @param proposed Proposed source text keyed by absolute filename.
|
|
2690
|
+
* @param orig Original source text for the same files.
|
|
2691
|
+
* @param onBatch Optional progress callback for each validation batch.
|
|
2692
|
+
*
|
|
2693
|
+
* @return Accepted source edits and filenames rejected by the type-safety check.
|
|
2694
|
+
*/
|
|
2695
|
+
function acceptTypeSafeEdits(program, proposed, orig, onBatch) {
|
|
2696
|
+
const rejected = new Set();
|
|
2697
|
+
let checks = 0;
|
|
2698
|
+
/**
|
|
2699
|
+
* Verifies a proposed edit batch and keeps it only when type safety is preserved.
|
|
2700
|
+
*
|
|
2701
|
+
* @param entries Source edits to verify together.
|
|
2702
|
+
* @param base Accepted edit map used as the starting point for this trial.
|
|
2703
|
+
*
|
|
2704
|
+
* @return The accepted edits and files rejected by type-safety verification.
|
|
2705
|
+
*/
|
|
2706
|
+
const accept = (entries, base) => {
|
|
2707
|
+
if (!entries.length)
|
|
2708
|
+
return base;
|
|
2709
|
+
onBatch?.(++checks, entries.length);
|
|
2710
|
+
const candidate = new Map(base);
|
|
2711
|
+
for (const [file, text] of entries)
|
|
2712
|
+
candidate.set(file, text);
|
|
2713
|
+
if (!deadCodeEditsIntroduceTypeErrors(program, candidate))
|
|
2714
|
+
return candidate;
|
|
2715
|
+
if (entries.length === 1) {
|
|
2716
|
+
rejected.add(entries[0][0]);
|
|
2717
|
+
return base;
|
|
2718
|
+
}
|
|
2719
|
+
const midpoint = Math.floor(entries.length / 2);
|
|
2720
|
+
return accept(entries.slice(midpoint), accept(entries.slice(0, midpoint), base));
|
|
2721
|
+
};
|
|
2722
|
+
return {
|
|
2723
|
+
accepted: accept([...proposed].sort(([l], [r]) => l.localeCompare(r)), new Map([...proposed.keys()].map(f => [f, orig.get(f)]))),
|
|
2724
|
+
rejected,
|
|
2725
|
+
};
|
|
2726
|
+
}
|
|
2727
|
+
// hygiene-ignore single-use -- Keep the documented runDeadCode declaration so its parameter and return contract remains attached.
|
|
2728
|
+
/**
|
|
2729
|
+
* Runs every dead-code detector through one fix-and-verify boundary.
|
|
2730
|
+
*
|
|
2731
|
+
* @param cfg Quality configuration defining source scope, tools, and policy exceptions.
|
|
2732
|
+
* @param fix Whether eligible changes should be written.
|
|
2733
|
+
* @param all Whether to inspect all configured source files.
|
|
2734
|
+
* @param verify Whether to rerun the detectors after applying fixes.
|
|
2735
|
+
* @param emit Whether to print stage headings and findings.
|
|
2736
|
+
* @param changedFileNames Optional caller-owned set updated with files changed by safe fixes.
|
|
2737
|
+
*
|
|
2738
|
+
* @return Remaining findings after any eligible fixes and verification.
|
|
2739
|
+
*/
|
|
2740
|
+
function runDeadCode(cfg, fix, all, verify = true, emit = true, changedFileNames) {
|
|
2741
|
+
if (emit)
|
|
2742
|
+
qualityHeader('dead-code', `${fix ? 'Fixing safe cases and checking' : 'Read-only check of'} unused files, exports, declarations, and single-use code`);
|
|
2743
|
+
let verificationStarted = false;
|
|
2744
|
+
/**
|
|
2745
|
+
* Starts the dead-code verification phase once per run.
|
|
2746
|
+
*
|
|
2747
|
+
*/
|
|
2748
|
+
const beginVerification = () => {
|
|
2749
|
+
if (verificationStarted)
|
|
2750
|
+
return;
|
|
2751
|
+
verificationStarted = true;
|
|
2752
|
+
if (emit)
|
|
2753
|
+
qualityHeader('dead-code/verification', 'Verify remaining unused files, exports, declarations, and single-use code');
|
|
2754
|
+
};
|
|
2755
|
+
const changedFiles = new Set();
|
|
2756
|
+
const srcSnapshot = fix ? new Map(filesFor(cfg, true).map(f => [f, readFileSync(f, 'utf8')])) : new Map();
|
|
2757
|
+
// hygiene-ignore single-use -- Snapshot the initial file inventory before autofixes can create or remove sources.
|
|
2758
|
+
const initialInventory = fix ? new Set(srcSnapshot.keys()) : new Set();
|
|
2759
|
+
if (fix && emit && !outputPhase)
|
|
2760
|
+
console.error(` Preparing TypeScript baseline for ${srcSnapshot.size} configured source files...`);
|
|
2761
|
+
const typeProgram = fix ? deadCodeTypeProgram(cfg) : null;
|
|
2762
|
+
if (fix && emit && !outputPhase)
|
|
2763
|
+
console.error(' TypeScript baseline ready.');
|
|
2764
|
+
const typeRejectedFiles = new Set();
|
|
2765
|
+
const singleUseVerificationFindings = [];
|
|
2766
|
+
const eslintReportsByPath = new Map();
|
|
2767
|
+
const eslintScannedContents = new Map();
|
|
2768
|
+
let importedConsumersForRun;
|
|
2769
|
+
/**
|
|
2770
|
+
* Scans selected files with ESLint and stores the source snapshot for later comparison.
|
|
2771
|
+
*
|
|
2772
|
+
* @param selectedFiles Optional file paths to limit the ESLint scan.
|
|
2773
|
+
*
|
|
2774
|
+
* @return ESLint reports for the selected files.
|
|
2775
|
+
*/
|
|
2776
|
+
const scanEslint = (selectedFiles) => {
|
|
2777
|
+
const reports = collectEslintReports(cfg, all, selectedFiles);
|
|
2778
|
+
for (const report of reports) {
|
|
2779
|
+
const f = resolve(report.filePath);
|
|
2780
|
+
eslintReportsByPath.set(f, report);
|
|
2781
|
+
eslintScannedContents.set(f, readFileSync(f, 'utf8'));
|
|
2782
|
+
}
|
|
2783
|
+
return reports;
|
|
2784
|
+
};
|
|
2785
|
+
/**
|
|
2786
|
+
* Rescans files changed by the current safe-fix pass.
|
|
2787
|
+
*
|
|
2788
|
+
* @return Reports for files modified since their last ESLint scan.
|
|
2789
|
+
*/
|
|
2790
|
+
const scanDirtyEslintFiles = () => {
|
|
2791
|
+
const dirtyFiles = [...eslintScannedContents].filter(([f, c]) => existsSync(f) && readFileSync(f, 'utf8') !== c).map(([f]) => f);
|
|
2792
|
+
return dirtyFiles.length ? scanEslint(dirtyFiles) : [];
|
|
2793
|
+
};
|
|
2794
|
+
if (fix) {
|
|
2795
|
+
if (emit)
|
|
2796
|
+
qualityHeader('dead-code/safe-fixes', 'Apply only mechanically proven fixes');
|
|
2797
|
+
if (qualityCheckEnabled(cfg, 'knip')) {
|
|
2798
|
+
if (emit)
|
|
2799
|
+
qualityHeader('dead-code/knip-fix', 'Removing only unambiguous unused export modifiers');
|
|
2800
|
+
fixKnipExports(cfg, changedFiles);
|
|
2801
|
+
}
|
|
2802
|
+
importedConsumersForRun = qualityCheckEnabled(cfg, 'knip') || qualityCheckEnabled(cfg, 'lint') ? importedExportConsumers(cfg) : undefined;
|
|
2803
|
+
if (qualityCheckEnabled(cfg, 'lint')) {
|
|
2804
|
+
if (emit)
|
|
2805
|
+
qualityHeader('dead-code/eslint-fix', 'Scan configured files and apply only safe unused-declaration fixes');
|
|
2806
|
+
let reportsToFix = scanEslint();
|
|
2807
|
+
for (let round = 0; round < 5; round++) {
|
|
2808
|
+
if (!reportsToFix.some(r => r.messages.some(m => m.ruleId === 'unused-imports/no-unused-vars')))
|
|
2809
|
+
break;
|
|
2810
|
+
if (emit && !outputPhase)
|
|
2811
|
+
console.error(` ESLint unused-declaration pass ${round + 1}/5...`);
|
|
2812
|
+
const passChangedFiles = new Set();
|
|
2813
|
+
if (!fixUnusedDeclarations(cfg, reportsToFix, passChangedFiles, importedConsumersForRun))
|
|
2814
|
+
break;
|
|
2815
|
+
for (const file of passChangedFiles)
|
|
2816
|
+
changedFiles.add(file);
|
|
2817
|
+
reportsToFix = scanDirtyEslintFiles();
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
if (emit)
|
|
2821
|
+
qualityHeader('dead-code/single-use', 'Scan declarations and references, classify candidates, and inline only proven cases');
|
|
2822
|
+
const singleUseChangedFiles = new Set();
|
|
2823
|
+
fixSingleUseDeclarations(cfg, singleUseChangedFiles, (p, f) => {
|
|
2824
|
+
if (emit && !outputPhase)
|
|
2825
|
+
console.error(` Single-use rewrite pass ${p} starting (${f} source files changed so far).`);
|
|
2826
|
+
}, singleUseVerificationFindings);
|
|
2827
|
+
for (const file of singleUseChangedFiles)
|
|
2828
|
+
changedFiles.add(file);
|
|
2829
|
+
const currInventory = new Set(filesFor(cfg, true));
|
|
2830
|
+
const trackedInitialInventory = [...initialInventory];
|
|
2831
|
+
if ([...currInventory].length !== trackedInitialInventory.length || trackedInitialInventory.some(f => !currInventory.has(f)))
|
|
2832
|
+
throw new Error('Dead-code autofix changed the configured source inventory; file creation or deletion is not an automatic dead-code fix.');
|
|
2833
|
+
const proposed = new Map();
|
|
2834
|
+
for (const file of changedFiles) {
|
|
2835
|
+
const original = srcSnapshot.get(file);
|
|
2836
|
+
if (original === undefined || !existsSync(file))
|
|
2837
|
+
throw new Error(`Dead-code autofix changed source inventory unexpectedly: ${relative(cfg.root, file)}`);
|
|
2838
|
+
const curr = readFileSync(file, 'utf8');
|
|
2839
|
+
if (curr !== original)
|
|
2840
|
+
proposed.set(file, curr);
|
|
2841
|
+
}
|
|
2842
|
+
if (verify)
|
|
2843
|
+
beginVerification();
|
|
2844
|
+
if (proposed.size) {
|
|
2845
|
+
if (!typeProgram)
|
|
2846
|
+
throw new Error('Dead-code edit validation requires its baseline TypeScript program.');
|
|
2847
|
+
if (emit && !outputPhase)
|
|
2848
|
+
console.error(` Validating ${proposed.size} changed files against TypeScript diagnostics...`);
|
|
2849
|
+
const { accepted, rejected } = acceptTypeSafeEdits(typeProgram, proposed, srcSnapshot, (c, v) => {
|
|
2850
|
+
if (emit && !outputPhase)
|
|
2851
|
+
console.error(` TypeScript safety check ${c} (${v} candidate files).`);
|
|
2852
|
+
});
|
|
2853
|
+
for (const file of rejected) {
|
|
2854
|
+
const original = srcSnapshot.get(file);
|
|
2855
|
+
if (original !== undefined)
|
|
2856
|
+
writeFileSync(file, original);
|
|
2857
|
+
typeRejectedFiles.add(relative(cfg.root, file));
|
|
2858
|
+
changedFiles.delete(file);
|
|
2859
|
+
}
|
|
2860
|
+
for (const [file, text] of accepted)
|
|
2861
|
+
if (readFileSync(file, 'utf8') !== text)
|
|
2862
|
+
writeFileSync(file, text);
|
|
2863
|
+
}
|
|
2864
|
+
if (verify)
|
|
2865
|
+
beginVerification();
|
|
2866
|
+
if (qualityCheckEnabled(cfg, 'lint'))
|
|
2867
|
+
scanDirtyEslintFiles();
|
|
2868
|
+
}
|
|
2869
|
+
if (!verify)
|
|
2870
|
+
return [];
|
|
2871
|
+
beginVerification();
|
|
2872
|
+
const findings = [];
|
|
2873
|
+
if (qualityCheckEnabled(cfg, 'knip')) {
|
|
2874
|
+
if (emit)
|
|
2875
|
+
qualityHeader('dead-code/knip', 'Checking unused files, exports, dependencies, and reachability');
|
|
2876
|
+
findings.push(...(function collectKnipFindings(cfg, importedConsumers = importedExportConsumers(cfg)) {
|
|
2877
|
+
const issues = readKnipIssues(cfg);
|
|
2878
|
+
const findings = [];
|
|
2879
|
+
for (const issue of issues) {
|
|
2880
|
+
const filePath = assertKnipPath(cfg, issue.file, 'finding source');
|
|
2881
|
+
for (const [kind, val] of Object.entries(issue)) {
|
|
2882
|
+
if (kind === 'file')
|
|
2883
|
+
continue;
|
|
2884
|
+
for (const i of flattenKnipItems(val)) {
|
|
2885
|
+
if (kind === 'exports' && isFrameworkEntryExport(cfg, issue.file, i.name))
|
|
2886
|
+
continue;
|
|
2887
|
+
const autoFixable = (kind === 'exports' || kind === 'types') && !hasImportedExportConsumer(importedConsumers, filePath, i.name) && knipExportCanBeMadePrivate(filePath, i.name);
|
|
2888
|
+
findings.push({
|
|
2889
|
+
rule: `knip/${kind}`,
|
|
2890
|
+
file: kind === 'files' ? i.name : issue.file,
|
|
2891
|
+
line: i.line ?? 1,
|
|
2892
|
+
name: i.name,
|
|
2893
|
+
severity: 'error',
|
|
2894
|
+
autofixable: autoFixable,
|
|
2895
|
+
reason: autoFixable
|
|
2896
|
+
? 'Knip identifies an unconsumed named export with a direct, unambiguous declaration.'
|
|
2897
|
+
: kind === 'files'
|
|
2898
|
+
? 'Knip considers this file unreachable; file deletion can affect dynamic, generated, or framework references.'
|
|
2899
|
+
: hasImportedExportConsumer(importedConsumers, filePath, i.name)
|
|
2900
|
+
? 'Knip reports this export as unused, but a configured source consumer was found.'
|
|
2901
|
+
: `Knip reports an unused ${kind} that the safe export rewrite cannot identify unambiguously.`,
|
|
2902
|
+
agentAction: autoFixable
|
|
2903
|
+
? 'Run the canonical dead-code autofix; it should remove only this export modifier, then verify the declaration and its local uses remain intact.'
|
|
2904
|
+
: kind === 'files'
|
|
2905
|
+
? 'Inspect imports, dynamic loading, framework discovery, generated inventories, and tests. Delete this file only if those checks prove it unreachable; otherwise correct the explicit entry-point or source-discovery model.'
|
|
2906
|
+
: hasImportedExportConsumer(importedConsumers, filePath, i.name)
|
|
2907
|
+
? 'Reconcile the reported consumer with Knip configuration and module resolution. Preserve the export while it has a real consumer; do not add a broad ignore.'
|
|
2908
|
+
: `Inspect the exact ${kind} and its consumers. Remove it only if it is truly unused; otherwise add the concrete framework/public contract to the explicit entry model.`,
|
|
2909
|
+
});
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
return findings;
|
|
2914
|
+
})(cfg, importedConsumersForRun));
|
|
2915
|
+
}
|
|
2916
|
+
if (qualityCheckEnabled(cfg, 'lint')) {
|
|
2917
|
+
if (!fix)
|
|
2918
|
+
scanEslint();
|
|
2919
|
+
findings.push(...unusedDeclarationFindings(cfg, [...eslintReportsByPath.values()]));
|
|
2920
|
+
}
|
|
2921
|
+
const finalSingleUseFindings = fix && !typeRejectedFiles.size ? singleUseVerificationFindings : singleUseFindings(cfg);
|
|
2922
|
+
for (const single of finalSingleUseFindings) {
|
|
2923
|
+
findings.push({
|
|
2924
|
+
rule: 'typescript/single-use',
|
|
2925
|
+
file: single.file,
|
|
2926
|
+
line: single.line,
|
|
2927
|
+
name: single.name,
|
|
2928
|
+
severity: 'error',
|
|
2929
|
+
autofixable: single.autofixable,
|
|
2930
|
+
reason: single.reason,
|
|
2931
|
+
agentAction: single.agentAction,
|
|
2932
|
+
});
|
|
2933
|
+
}
|
|
2934
|
+
for (const finding of documentationFindings(scopedCfg(cfg, true)).filter(i => i.kind === 'orphan'))
|
|
2935
|
+
findings.push({
|
|
2936
|
+
rule: 'tsdoc/detached',
|
|
2937
|
+
file: finding.file,
|
|
2938
|
+
line: finding.line,
|
|
2939
|
+
name: finding.name,
|
|
2940
|
+
severity: 'error',
|
|
2941
|
+
autofixable: false,
|
|
2942
|
+
reason: finding.reason,
|
|
2943
|
+
agentAction: 'Attach this TSDoc to the declaration it describes when that relationship is clear; otherwise remove only this detached block. Preserve meaningful constraints and do not move it across unrelated code.',
|
|
2944
|
+
});
|
|
2945
|
+
const finalFindings = findings.map(f => typeRejectedFiles.has(f.file) && f.autofixable
|
|
2946
|
+
? {
|
|
2947
|
+
...f,
|
|
2948
|
+
severity: 'error',
|
|
2949
|
+
autofixable: false,
|
|
2950
|
+
reason: `The proposed rewrite in this file introduced TypeScript diagnostics and was rolled back: ${f.reason}`,
|
|
2951
|
+
agentAction: 'Inspect the exact declaration and proposed rewrite, preserve semantics and types, then apply a source-level fix or leave this case manual.',
|
|
2952
|
+
}
|
|
2953
|
+
: f);
|
|
2954
|
+
if (emit)
|
|
2955
|
+
(function printDeadCodeFindings(findings, typeSafetyVerified = true) {
|
|
2956
|
+
if (reportStages) {
|
|
2957
|
+
const stage = reportStages.get('dead-code');
|
|
2958
|
+
if (stage) {
|
|
2959
|
+
stage.findings = findings.length;
|
|
2960
|
+
if (findings.length)
|
|
2961
|
+
stage.status = 'findings';
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2964
|
+
if (!findings.length) {
|
|
2965
|
+
if (!outputPhase)
|
|
2966
|
+
console.error(' ✓ dead-code checks passed; no findings remain');
|
|
2967
|
+
return;
|
|
2968
|
+
}
|
|
2969
|
+
const errs = findings;
|
|
2970
|
+
const lines = [];
|
|
2971
|
+
for (const finding of [...findings].sort((l, r) => l.file.localeCompare(r.file) || l.line - r.line || l.rule.localeCompare(r.rule) || l.name.localeCompare(r.name))) {
|
|
2972
|
+
lines.push(` - [ERROR] ${finding.rule}: ${finding.file}:${finding.line} ${finding.name}`);
|
|
2973
|
+
lines.push(` Reason: ${finding.reason}`);
|
|
2974
|
+
lines.push(` Autofix: ${!finding.autofixable ? 'not safe or not supported' : typeSafetyVerified ? 'available' : 'candidate; fix mode checks TypeScript before writing'}`);
|
|
2975
|
+
lines.push(` Agent action: ${finding.agentAction}`);
|
|
2976
|
+
}
|
|
2977
|
+
lines.push(` ${errs.length} error${errs.length === 1 ? '' : 's'}.`);
|
|
2978
|
+
if (outputPhase) {
|
|
2979
|
+
for (const line of lines.slice(0, -1))
|
|
2980
|
+
recordQualityDetail(line.replace(/^\s*-\s*/u, ''));
|
|
2981
|
+
}
|
|
2982
|
+
else
|
|
2983
|
+
for (const line of lines)
|
|
2984
|
+
console.error(line);
|
|
2985
|
+
if (errs.length)
|
|
2986
|
+
process.exitCode = 1;
|
|
2987
|
+
})(finalFindings, fix);
|
|
2988
|
+
if (fix && changedFileNames)
|
|
2989
|
+
for (const file of changedFiles) {
|
|
2990
|
+
const original = srcSnapshot.get(file);
|
|
2991
|
+
if (original !== undefined && existsSync(file) && readFileSync(file, 'utf8') !== original)
|
|
2992
|
+
changedFileNames.add(file);
|
|
2993
|
+
}
|
|
2994
|
+
return finalFindings;
|
|
2995
|
+
}
|
|
2996
|
+
/**
|
|
2997
|
+
* Dispatches the dead-code coordinator in fix or read-only mode.
|
|
2998
|
+
*
|
|
2999
|
+
* @param cfg Quality configuration defining source scope and tools.
|
|
3000
|
+
* @param fix Whether eligible changes may be applied to source files.
|
|
3001
|
+
* @param all Whether to inspect all configured source files.
|
|
3002
|
+
*
|
|
3003
|
+
* @return Source files changed by the safe autofix pass.
|
|
3004
|
+
*/
|
|
3005
|
+
function runDeadCodeCmd(cfg, fix, all) {
|
|
3006
|
+
const changedFiles = new Set();
|
|
3007
|
+
printCheckStatus('dead-code', runDeadCode(cfg, fix, all, true, true, fix ? changedFiles : undefined).length);
|
|
3008
|
+
return [...changedFiles];
|
|
3009
|
+
}
|
|
3010
|
+
/**
|
|
3011
|
+
* Prints a grouped set of findings with one normalized line per issue.
|
|
3012
|
+
*
|
|
3013
|
+
* @param findings Findings produced by one quality stage.
|
|
3014
|
+
* @param fmt Converts one finding into a human-readable message.
|
|
3015
|
+
* @param advisory Whether the findings are informational and should not fail the stage.
|
|
3016
|
+
*
|
|
3017
|
+
* @return Nothing; findings are printed under the active check or directly to the console.
|
|
3018
|
+
*/
|
|
3019
|
+
function printFindings(findings, fmt, advisory = false) {
|
|
3020
|
+
if (reportStages && reportStageName && findings.length && !advisory) {
|
|
3021
|
+
const stage = reportStages.get(reportStageName);
|
|
3022
|
+
if (stage) {
|
|
3023
|
+
stage.findings += findings.length;
|
|
3024
|
+
stage.status = 'findings';
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
3027
|
+
if (!findings.length) {
|
|
3028
|
+
if (!outputPhase)
|
|
3029
|
+
console.error(' ✓ clean');
|
|
3030
|
+
return;
|
|
3031
|
+
}
|
|
3032
|
+
if (outputPhase) {
|
|
3033
|
+
for (const finding of findings)
|
|
3034
|
+
recordQualityDetail(fmt(finding));
|
|
3035
|
+
}
|
|
3036
|
+
else {
|
|
3037
|
+
const lines = findings.map(f => ` - ${compactOutput(fmt(f)).join(' ')}`);
|
|
3038
|
+
console.error(` ${findings.length} ${advisory ? 'advisory finding' : 'error'}${findings.length === 1 ? '' : 's'}:`);
|
|
3039
|
+
for (const line of lines)
|
|
3040
|
+
console.error(line);
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
/**
|
|
3044
|
+
* Runs one independent finding check and keeps failures from blocking later checks.
|
|
3045
|
+
*
|
|
3046
|
+
* @param name Check identifier shown in the output.
|
|
3047
|
+
* @param detail Human-readable description of the check.
|
|
3048
|
+
* @param check Function that collects findings.
|
|
3049
|
+
* @param fmt Converts one finding into a human-readable message.
|
|
3050
|
+
*
|
|
3051
|
+
* @return Findings produced by the check.
|
|
3052
|
+
*/
|
|
3053
|
+
function runFindingCheck(name, detail, check, fmt) {
|
|
3054
|
+
qualityHeader(name, detail);
|
|
3055
|
+
try {
|
|
3056
|
+
const findings = check();
|
|
3057
|
+
printFindings(findings, fmt);
|
|
3058
|
+
if (findings.length)
|
|
3059
|
+
process.exitCode = 1;
|
|
3060
|
+
printCheckStatus(name, findings.length);
|
|
3061
|
+
return findings;
|
|
3062
|
+
}
|
|
3063
|
+
catch (err) {
|
|
3064
|
+
recordQualityFailure(name, err);
|
|
3065
|
+
printCheckStatus(name, 1);
|
|
3066
|
+
return [];
|
|
3067
|
+
}
|
|
3068
|
+
}
|
|
3069
|
+
/**
|
|
3070
|
+
* Run the optional, read-only GitHub analytics stage.
|
|
3071
|
+
*
|
|
3072
|
+
* @param cfg Quality configuration containing repositories and expected settings.
|
|
3073
|
+
* @param repos Repository overrides supplied to `hygiene github`.
|
|
3074
|
+
* @param explicit Whether GitHub reporting was requested as the command itself.
|
|
3075
|
+
* @param warn Whether findings should be reported without setting a failing exit code.
|
|
3076
|
+
*/
|
|
3077
|
+
function runGitHubCheck(cfg, repos = [], explicit = false, warn = false) {
|
|
3078
|
+
qualityHeader('github', 'Reading open issues, Dependabot, code scanning, and secret scanning alerts');
|
|
3079
|
+
const tgts = repos.length ? repos : (cfg.github?.repositories ?? [inferGitHubRepo(cfg.root)].filter((r) => Boolean(r)));
|
|
3080
|
+
if (!tgts.length) {
|
|
3081
|
+
const detail = 'Set github.repositories in quality.json or pass --repository owner/name.';
|
|
3082
|
+
reportGitHubData = { schemaVersion: 1, generatedAt: new Date().toISOString(), state: 'partial', detail, repositories: [] };
|
|
3083
|
+
updateGitHubStage('failed', 0);
|
|
3084
|
+
if (outputPhase)
|
|
3085
|
+
recordQualityDetail(detail);
|
|
3086
|
+
else
|
|
3087
|
+
console.error(` GitHub: ${detail}`);
|
|
3088
|
+
process.exitCode = 1;
|
|
3089
|
+
printCheckStatus('github', 1);
|
|
3090
|
+
return;
|
|
3091
|
+
}
|
|
3092
|
+
if (!hasGitHubAuth()) {
|
|
3093
|
+
const detail = 'GitHub CLI is unavailable or unauthenticated; run gh auth login or set GH_TOKEN.';
|
|
3094
|
+
reportGitHubData = { schemaVersion: 1, generatedAt: new Date().toISOString(), state: 'skipped', detail, repositories: [] };
|
|
3095
|
+
updateGitHubStage(explicit ? 'failed' : 'skipped', 0);
|
|
3096
|
+
if (explicit) {
|
|
3097
|
+
if (outputPhase)
|
|
3098
|
+
recordQualityDetail(detail);
|
|
3099
|
+
else
|
|
3100
|
+
console.error(` GitHub: ${detail}`);
|
|
3101
|
+
process.exitCode = 1;
|
|
3102
|
+
printCheckStatus('github', 1);
|
|
3103
|
+
}
|
|
3104
|
+
else
|
|
3105
|
+
printSkippedCheckStatus('github');
|
|
3106
|
+
return;
|
|
3107
|
+
}
|
|
3108
|
+
try {
|
|
3109
|
+
reportGitHubData = buildGitHubReport(tgts, cfg.github?.requiredFeatures);
|
|
3110
|
+
const findings = reportGitHubData.repositories.flatMap(r => r.findings);
|
|
3111
|
+
const failed = reportGitHubData.state === 'partial';
|
|
3112
|
+
updateGitHubStage(failed ? 'failed' : findings.length ? 'findings' : 'passed', findings.length);
|
|
3113
|
+
const blockingFindings = findings.some(f => f.category !== 'issue' && f.category !== 'setting');
|
|
3114
|
+
if (outputPhase)
|
|
3115
|
+
for (const line of formatGitHubReport(reportGitHubData))
|
|
3116
|
+
recordQualityDetail(line);
|
|
3117
|
+
else
|
|
3118
|
+
for (const line of formatGitHubReport(reportGitHubData))
|
|
3119
|
+
console.warn(` ${line}`);
|
|
3120
|
+
if (!warn && blockingFindings)
|
|
3121
|
+
process.exitCode = 1;
|
|
3122
|
+
if (failed && !warn)
|
|
3123
|
+
process.exitCode = 1;
|
|
3124
|
+
printCheckStatus('github', !warn && (blockingFindings || failed) ? 1 : 0);
|
|
3125
|
+
}
|
|
3126
|
+
catch (err) {
|
|
3127
|
+
const detail = err instanceof Error ? err.message : 'Unknown GitHub report error.';
|
|
3128
|
+
reportGitHubData = { schemaVersion: 1, generatedAt: new Date().toISOString(), state: 'partial', detail, repositories: [] };
|
|
3129
|
+
updateGitHubStage('failed', 0);
|
|
3130
|
+
if (outputPhase)
|
|
3131
|
+
recordQualityDetail(detail);
|
|
3132
|
+
else
|
|
3133
|
+
console.error(` GitHub: ${detail}`);
|
|
3134
|
+
process.exitCode = 1;
|
|
3135
|
+
printCheckStatus('github', 1);
|
|
3136
|
+
}
|
|
3137
|
+
}
|
|
3138
|
+
/**
|
|
3139
|
+
* Update the JSON summary for the active GitHub report stage.
|
|
3140
|
+
*
|
|
3141
|
+
* @param status Result state to record.
|
|
3142
|
+
* @param findings Number of GitHub findings in the report.
|
|
3143
|
+
*/
|
|
3144
|
+
function updateGitHubStage(status, findings) {
|
|
3145
|
+
const stage = reportStages?.get('github');
|
|
3146
|
+
if (stage) {
|
|
3147
|
+
stage.status = status;
|
|
3148
|
+
stage.findings = findings;
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
// hygiene-ignore single-use -- Keep the documented inferGitHubRepo declaration so its parameter and return contract remains attached.
|
|
3152
|
+
/**
|
|
3153
|
+
* Infer the current repository slug from its GitHub origin remote.
|
|
3154
|
+
*
|
|
3155
|
+
* @param root Repository root to inspect.
|
|
3156
|
+
*
|
|
3157
|
+
* @return The owner/name slug, or undefined for a non-GitHub remote.
|
|
3158
|
+
*/
|
|
3159
|
+
function inferGitHubRepo(root) {
|
|
3160
|
+
return spawnSync('git', ['config', '--get', 'remote.origin.url'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
|
|
3161
|
+
.stdout.trim()
|
|
3162
|
+
.match(/(?:github\.com[:/])([^/]+\/[^/]+?)(?:\.git)?$/i)?.[1];
|
|
3163
|
+
}
|
|
3164
|
+
// hygiene-ignore single-use -- Keep the documented runGenericChecks declaration so its parameter and return contract remains attached.
|
|
3165
|
+
/**
|
|
3166
|
+
* Runs configured generic repository checks as part of the full quality command.
|
|
3167
|
+
*
|
|
3168
|
+
* @param cfg Quality configuration selecting enabled generic checks and their policies.
|
|
3169
|
+
* @param analysis Optional shared analysis context for regex checks in the same run.
|
|
3170
|
+
*
|
|
3171
|
+
* @return Nothing; blocking generic findings are reflected in the process exit code.
|
|
3172
|
+
*/
|
|
3173
|
+
function runGenericChecks(cfg, analysis) {
|
|
3174
|
+
const checks = [];
|
|
3175
|
+
if (qualityCheckEnabled(cfg, 'accessibility'))
|
|
3176
|
+
checks.push(['accessibility', () => accessibilityFindings(cfg, analysis)]);
|
|
3177
|
+
if (qualityCheckEnabled(cfg, 'display-name'))
|
|
3178
|
+
checks.push(['display-name', () => displayNameFindings(cfg, analysis)]);
|
|
3179
|
+
if (cfg.performancePatterns && qualityCheckEnabled(cfg, 'performance-patterns'))
|
|
3180
|
+
checks.push(['performance-patterns', () => performancePatternFindings(cfg, analysis)]);
|
|
3181
|
+
if (cfg.documentation?.commandRoots?.length && qualityCheckEnabled(cfg, 'documented-commands'))
|
|
3182
|
+
checks.push(['documented-commands', () => documentedCommandFindings(cfg)]);
|
|
3183
|
+
if (cfg.security && qualityCheckEnabled(cfg, 'security'))
|
|
3184
|
+
checks.push(['security', () => securityFindings(cfg)]);
|
|
3185
|
+
if (cfg.repeatedClasses && qualityCheckEnabled(cfg, 'repeated-classes'))
|
|
3186
|
+
checks.push(['repeated-classes', () => repeatedClassFindings(cfg, analysis)]);
|
|
3187
|
+
if (cfg.regexDedup && qualityCheckEnabled(cfg, 'regex-dedup'))
|
|
3188
|
+
checks.push(['regex-dedup', () => regexFindings(cfg, analysis)]);
|
|
3189
|
+
if (cfg.uiPatterns && qualityCheckEnabled(cfg, 'ui-patterns'))
|
|
3190
|
+
checks.push(['ui-patterns', () => uiPatternFindings(cfg, analysis)]);
|
|
3191
|
+
checks.push(['error-boundaries', () => errorBoundaryFindings(cfg)]);
|
|
3192
|
+
for (const [name, check] of checks) {
|
|
3193
|
+
qualityHeader(name, `Checking ${name.replace(G_REGEX(), ' ')}`);
|
|
3194
|
+
try {
|
|
3195
|
+
const findings = check();
|
|
3196
|
+
const advisory = name === 'performance-patterns';
|
|
3197
|
+
printFindings(findings, f => `${'file' in f ? `${f.file}: ` : ''}${'message' in f ? `${'line' in f ? `${f.line}:${f.column} ` : ''}${f.message}` : 'component' in f ? `${f.line}:${f.column} ${f.component}: ${f.recommendation}` : 'method' in f ? `${f.line}:${f.column} ${f.method}(${f.receiver}): ${f.recommendation}` : 'command' in f ? `${f.line}: ${f.recommendation} (${f.command})` : 'value' in f ? `${f.count}x ${f.value} (${f.locations.join(', ')})` : 'source' in f ? `${f.count}x ${f.source} (${f.locations.join(', ')})` : f.pattern}`, advisory);
|
|
3198
|
+
printCheckStatus(name, advisory ? 0 : findings.length);
|
|
3199
|
+
if (findings.length && !advisory)
|
|
3200
|
+
process.exitCode = 1;
|
|
3201
|
+
}
|
|
3202
|
+
catch (err) {
|
|
3203
|
+
recordQualityFailure(name, err);
|
|
3204
|
+
printCheckStatus(name, 1);
|
|
3205
|
+
}
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
/**
|
|
3209
|
+
* Runs the configured Tailwind canonical-class check and records its CLI report stage.
|
|
3210
|
+
*
|
|
3211
|
+
* @param cfg Quality configuration containing the Tailwind stylesheet and source roots.
|
|
3212
|
+
* @param fix Whether to write Tailwind's canonical class suggestions.
|
|
3213
|
+
*
|
|
3214
|
+
* @return Promise resolving when the diagnostic or autofix completes.
|
|
3215
|
+
*/
|
|
3216
|
+
function runTailwindCanonicalCheck(cfg, fix) {
|
|
3217
|
+
qualityHeader('tailwind-canonical', `${fix ? 'Fixing and checking' : 'Checking'} canonical Tailwind classes`);
|
|
3218
|
+
let skipped = false;
|
|
3219
|
+
return runTailwindCanonical(cfg, fix, {
|
|
3220
|
+
quiet: Boolean(outputPhase),
|
|
3221
|
+
onFinding: recordQualityDetail,
|
|
3222
|
+
onSkip: () => {
|
|
3223
|
+
skipped = true;
|
|
3224
|
+
},
|
|
3225
|
+
}).then(() => (skipped ? printSkippedCheckStatus('tailwind-canonical') : printCheckStatus('tailwind-canonical', 0)), (e) => {
|
|
3226
|
+
const stage = reportStages?.get('tailwind-canonical');
|
|
3227
|
+
if (stage) {
|
|
3228
|
+
stage.status = 'failed';
|
|
3229
|
+
stage.findings = Number(/failed with (\d+) suggestion/.exec(e instanceof Error ? e.message : '')?.[1] ?? 0);
|
|
3230
|
+
}
|
|
3231
|
+
throw e;
|
|
3232
|
+
});
|
|
3233
|
+
}
|
|
3234
|
+
/**
|
|
3235
|
+
* Renames safe repository-local declarations and repairs matching references.
|
|
3236
|
+
*
|
|
3237
|
+
* @param cfg Quality configuration defining source scope and naming protections.
|
|
3238
|
+
* @param all Whether to apply changes to every configured source file.
|
|
3239
|
+
*
|
|
3240
|
+
* @return Nothing; safe naming changes are written to source files.
|
|
3241
|
+
*/
|
|
3242
|
+
function fixNames(cfg, all) {
|
|
3243
|
+
// TypeScript's parser does not understand Astro frontmatter. Keep Astro in
|
|
3244
|
+
// reporting/import scope, but never apply symbol renames to it.
|
|
3245
|
+
const allowed = new Set(filesFor(cfg, all).filter(file => !isProtectedPath(file) && !file.endsWith('.astro') && !hasGeneratedSourceHeader(readFileSync(file, 'utf8'))));
|
|
3246
|
+
let program = ts.createProgram({
|
|
3247
|
+
rootNames: srcFiles(cfg).filter(f => C_M_JS_TS_X_CLASS_2.test(f)),
|
|
3248
|
+
options: {
|
|
3249
|
+
allowNonTsExtensions: true,
|
|
3250
|
+
allowJs: true,
|
|
3251
|
+
checkJs: false,
|
|
3252
|
+
jsx: ts.JsxEmit.Preserve,
|
|
3253
|
+
module: ts.ModuleKind.ESNext,
|
|
3254
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
3255
|
+
skipLibCheck: true,
|
|
3256
|
+
target: ts.ScriptTarget.ESNext,
|
|
3257
|
+
},
|
|
3258
|
+
});
|
|
3259
|
+
let checker = program.getTypeChecker();
|
|
3260
|
+
// Import repair writes source files. Rebuild the AST afterward so every
|
|
3261
|
+
// subsequent text span is anchored to the current file contents.
|
|
3262
|
+
repairMissingImports(cfg, program, checker);
|
|
3263
|
+
program = ts.createProgram({
|
|
3264
|
+
rootNames: srcFiles(cfg).filter(f => C_M_JS_TS_X_CLASS_2.test(f)),
|
|
3265
|
+
options: {
|
|
3266
|
+
allowNonTsExtensions: true,
|
|
3267
|
+
allowJs: true,
|
|
3268
|
+
checkJs: false,
|
|
3269
|
+
jsx: ts.JsxEmit.Preserve,
|
|
3270
|
+
module: ts.ModuleKind.ESNext,
|
|
3271
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
3272
|
+
skipLibCheck: true,
|
|
3273
|
+
target: ts.ScriptTarget.ESNext,
|
|
3274
|
+
},
|
|
3275
|
+
});
|
|
3276
|
+
checker = program.getTypeChecker();
|
|
3277
|
+
/**
|
|
3278
|
+
* Identifies lowercase JSX element names that are intrinsic HTML tags.
|
|
3279
|
+
*
|
|
3280
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3281
|
+
*
|
|
3282
|
+
* @return Whether the identifier names an intrinsic lowercase JSX tag.
|
|
3283
|
+
*/
|
|
3284
|
+
const isIntrinsicJsxTag = (n) => {
|
|
3285
|
+
return (ts.isJsxOpeningLikeElement(n.parent) || ts.isJsxClosingElement(n.parent)) && n.parent.tagName === n && n.text.length > 0 && n.text[0] === n.text[0].toLowerCase();
|
|
3286
|
+
};
|
|
3287
|
+
// hygiene-ignore single-use -- Keep the documented canonical declaration so its parameter and return contract remains attached.
|
|
3288
|
+
/**
|
|
3289
|
+
* Resolves an aliased symbol to its underlying declaration symbol.
|
|
3290
|
+
*
|
|
3291
|
+
* @param symbol TypeScript symbol to resolve when checking for aliases.
|
|
3292
|
+
*
|
|
3293
|
+
* @return The underlying symbol, or `undefined` when no symbol was found.
|
|
3294
|
+
*/
|
|
3295
|
+
const canonical = (symbol) => (symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol);
|
|
3296
|
+
/**
|
|
3297
|
+
* Gets the symbol bound to an identifier, including shorthand assignments.
|
|
3298
|
+
*
|
|
3299
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3300
|
+
*
|
|
3301
|
+
* @return The bound symbol, when TypeScript can resolve one.
|
|
3302
|
+
*/
|
|
3303
|
+
const identifierSymbol = (n) => canonical(ts.isShorthandPropertyAssignment(n.parent) ? (checker.getShorthandAssignmentValueSymbol(n.parent) ?? checker.getSymbolAtLocation(n)) : checker.getSymbolAtLocation(n));
|
|
3304
|
+
/**
|
|
3305
|
+
* Identifies identifiers used as property names rather than references.
|
|
3306
|
+
*
|
|
3307
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3308
|
+
*
|
|
3309
|
+
* @return Whether the identifier is used as a property key or member name.
|
|
3310
|
+
*/
|
|
3311
|
+
const isPropName = (n) => (ts.isPropertyAccessExpression(n.parent) && n.parent.name === n) ||
|
|
3312
|
+
(ts.isQualifiedName(n.parent) && n.parent.right === n) ||
|
|
3313
|
+
((ts.isPropertyAssignment(n.parent) || ts.isMethodDeclaration(n.parent) || ts.isMethodSignature(n.parent)) && n.parent.name === n);
|
|
3314
|
+
/**
|
|
3315
|
+
* Checks whether the initializer already references this declaration.
|
|
3316
|
+
*
|
|
3317
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3318
|
+
*
|
|
3319
|
+
* @return Whether the initializer references the declaration being renamed.
|
|
3320
|
+
*/
|
|
3321
|
+
const hasInitShadow = (n) => {
|
|
3322
|
+
if (!ts.isVariableDeclaration(n.parent) || !n.parent.initializer)
|
|
3323
|
+
return false;
|
|
3324
|
+
// hygiene-ignore single-use -- Resolve the declared symbol once before recursively inspecting initializer references.
|
|
3325
|
+
const tgt = checker.getSymbolAtLocation(n);
|
|
3326
|
+
let found = false;
|
|
3327
|
+
/**
|
|
3328
|
+
* Collects identifiers and namespace property accesses used by a module.
|
|
3329
|
+
*
|
|
3330
|
+
* @param child Child syntax-tree node within the current initializer.
|
|
3331
|
+
*/
|
|
3332
|
+
const visit = (child) => {
|
|
3333
|
+
if (found || child === n)
|
|
3334
|
+
return;
|
|
3335
|
+
if (ts.isIdentifier(child) && !isPropName(child) && child.text === n.text && checker.getSymbolAtLocation(child) === tgt)
|
|
3336
|
+
found = true;
|
|
3337
|
+
ts.forEachChild(child, visit);
|
|
3338
|
+
};
|
|
3339
|
+
visit(n.parent.initializer);
|
|
3340
|
+
return found;
|
|
3341
|
+
};
|
|
3342
|
+
/**
|
|
3343
|
+
* Detects same-spelled initializer references that resolve to another declaration.
|
|
3344
|
+
*
|
|
3345
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3346
|
+
*
|
|
3347
|
+
* @return Whether the initializer has a same-spelled reference to another symbol.
|
|
3348
|
+
*/
|
|
3349
|
+
const hasInitRefToOtherSymbol = (n) => {
|
|
3350
|
+
if (!ts.isVariableDeclaration(n.parent) || !n.parent.initializer)
|
|
3351
|
+
return false;
|
|
3352
|
+
// hygiene-ignore single-use -- Resolve the declared symbol once before recursively checking differently bound references.
|
|
3353
|
+
const tgt = checker.getSymbolAtLocation(n);
|
|
3354
|
+
let found = false;
|
|
3355
|
+
/**
|
|
3356
|
+
* Searches an initializer for a reference to the declared identifier.
|
|
3357
|
+
*
|
|
3358
|
+
* @param child Child syntax-tree node within the current initializer.
|
|
3359
|
+
*/
|
|
3360
|
+
const visit = (child) => {
|
|
3361
|
+
if (found || child === n)
|
|
3362
|
+
return;
|
|
3363
|
+
if (ts.isIdentifier(child) && !isPropName(child) && child.text === n.text && checker.getSymbolAtLocation(child) !== tgt)
|
|
3364
|
+
found = true;
|
|
3365
|
+
ts.forEachChild(child, visit);
|
|
3366
|
+
};
|
|
3367
|
+
visit(n.parent.initializer);
|
|
3368
|
+
return found;
|
|
3369
|
+
};
|
|
3370
|
+
/**
|
|
3371
|
+
* Checks whether a proposed name conflicts with an initializer declaration.
|
|
3372
|
+
*
|
|
3373
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3374
|
+
* @param suggestion Concise identifier spelling proposed by the naming rule.
|
|
3375
|
+
*
|
|
3376
|
+
* @return Whether the initializer contains a declaration that would collide with the suggestion.
|
|
3377
|
+
*/
|
|
3378
|
+
const hasInitRenameCollision = (n, suggestion) => {
|
|
3379
|
+
if (!ts.isVariableDeclaration(n.parent) || !n.parent.initializer)
|
|
3380
|
+
return false;
|
|
3381
|
+
let found = false;
|
|
3382
|
+
/**
|
|
3383
|
+
* Searches an initializer for a reference that resolves to a different symbol.
|
|
3384
|
+
*
|
|
3385
|
+
* @param child Child syntax-tree node within the current initializer.
|
|
3386
|
+
*/
|
|
3387
|
+
const visit = (child) => {
|
|
3388
|
+
if (found)
|
|
3389
|
+
return;
|
|
3390
|
+
if (ts.isIdentifier(child) && !isPropName(child)) {
|
|
3391
|
+
const symbol = checker.getSymbolAtLocation(child);
|
|
3392
|
+
for (const declaration of symbol?.declarations ?? []) {
|
|
3393
|
+
const name = 'name' in declaration && ts.isIdentifier(declaration.name) ? declaration.name : undefined;
|
|
3394
|
+
if (name && name !== n && renameDeclaration(name) === suggestion) {
|
|
3395
|
+
found = true;
|
|
3396
|
+
return;
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
}
|
|
3400
|
+
ts.forEachChild(child, visit);
|
|
3401
|
+
};
|
|
3402
|
+
visit(n.parent.initializer);
|
|
3403
|
+
return found;
|
|
3404
|
+
};
|
|
3405
|
+
/**
|
|
3406
|
+
* Checks module consumers for a conflicting initializer binding.
|
|
3407
|
+
*
|
|
3408
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3409
|
+
* @param suggestion Concise identifier spelling proposed by the naming rule.
|
|
3410
|
+
*
|
|
3411
|
+
* @return Whether a consumer initializer already binds the suggested name to the target.
|
|
3412
|
+
*/
|
|
3413
|
+
const hasInitConsumerCollision = (n, suggestion) => {
|
|
3414
|
+
const tgt = checker.getSymbolAtLocation(n);
|
|
3415
|
+
if (!tgt)
|
|
3416
|
+
return false;
|
|
3417
|
+
const src = n.getSourceFile();
|
|
3418
|
+
if (!allowed.has(src.fileName))
|
|
3419
|
+
return false;
|
|
3420
|
+
{
|
|
3421
|
+
let found = false;
|
|
3422
|
+
/**
|
|
3423
|
+
* Checks whether an initializer already uses a proposed replacement name.
|
|
3424
|
+
*
|
|
3425
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3426
|
+
*/
|
|
3427
|
+
const visit = (n) => {
|
|
3428
|
+
if (found)
|
|
3429
|
+
return;
|
|
3430
|
+
if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.name.text === suggestion && n.initializer) {
|
|
3431
|
+
/**
|
|
3432
|
+
* Searches a candidate initializer for a reference to the target symbol.
|
|
3433
|
+
*
|
|
3434
|
+
* @param child Child syntax-tree node within the current initializer.
|
|
3435
|
+
*/
|
|
3436
|
+
const check = (child) => {
|
|
3437
|
+
if (found)
|
|
3438
|
+
return;
|
|
3439
|
+
if (ts.isIdentifier(child) && checker.getSymbolAtLocation(child) === tgt)
|
|
3440
|
+
found = true;
|
|
3441
|
+
ts.forEachChild(child, check);
|
|
3442
|
+
};
|
|
3443
|
+
check(n.initializer);
|
|
3444
|
+
}
|
|
3445
|
+
ts.forEachChild(n, visit);
|
|
3446
|
+
};
|
|
3447
|
+
visit(src);
|
|
3448
|
+
if (found)
|
|
3449
|
+
return true;
|
|
3450
|
+
}
|
|
3451
|
+
return false;
|
|
3452
|
+
};
|
|
3453
|
+
const protectedNames = new Set([...PROTECTED_IDENTIFIERS, ...(cfg.protectedIdentifiers ?? [])]);
|
|
3454
|
+
const exported = new Set();
|
|
3455
|
+
for (const src of program.getSourceFiles()) {
|
|
3456
|
+
const module = checker.getSymbolAtLocation(src);
|
|
3457
|
+
if (module)
|
|
3458
|
+
for (const s of checker.getExportsOfModule(module))
|
|
3459
|
+
exported.add(s.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s) : s);
|
|
3460
|
+
}
|
|
3461
|
+
const replacements = new Map();
|
|
3462
|
+
const renameSafetyByScope = new Map();
|
|
3463
|
+
for (const src of program.getSourceFiles()) {
|
|
3464
|
+
if (!allowed.has(src.fileName))
|
|
3465
|
+
continue;
|
|
3466
|
+
/**
|
|
3467
|
+
* Collects safe concise-name proposals for declarations in the source file.
|
|
3468
|
+
*
|
|
3469
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3470
|
+
*/
|
|
3471
|
+
const inspect = (n) => {
|
|
3472
|
+
if (ts.isIdentifier(n) && isRenamableDeclaration(n)) {
|
|
3473
|
+
const scope = declarationScope(n);
|
|
3474
|
+
const safety = renameSafetyByScope.get(scope) ?? { declared: new Set(), proposals: new Map() };
|
|
3475
|
+
safety.declared.add(n.text);
|
|
3476
|
+
const suggestion = renameDeclaration(n);
|
|
3477
|
+
if (!n.text.startsWith('_') &&
|
|
3478
|
+
!protectedNames.has(n.text) &&
|
|
3479
|
+
!parameterRenameCapturesDefault(n, suggestion, checker) &&
|
|
3480
|
+
!hasInitShadow(n) &&
|
|
3481
|
+
!hasInitRefToOtherSymbol(n) &&
|
|
3482
|
+
!hasInitRenameCollision(n, suggestion) &&
|
|
3483
|
+
!hasInitConsumerCollision(n, suggestion)) {
|
|
3484
|
+
if (suggestion !== n.text && !isCallbackDeclaration(n))
|
|
3485
|
+
safety.proposals.set(suggestion, (safety.proposals.get(suggestion) ?? 0) + 1);
|
|
3486
|
+
}
|
|
3487
|
+
renameSafetyByScope.set(scope, safety);
|
|
3488
|
+
}
|
|
3489
|
+
ts.forEachChild(n, inspect);
|
|
3490
|
+
};
|
|
3491
|
+
inspect(src);
|
|
3492
|
+
}
|
|
3493
|
+
for (const src of program.getSourceFiles()) {
|
|
3494
|
+
if (!allowed.has(src.fileName))
|
|
3495
|
+
continue;
|
|
3496
|
+
/**
|
|
3497
|
+
* Applies eligible symbol renames after checking declaration-scope collisions.
|
|
3498
|
+
*
|
|
3499
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3500
|
+
*/
|
|
3501
|
+
const inspect = (n) => {
|
|
3502
|
+
if (ts.isIdentifier(n) && isRenamableDeclaration(n) && !n.text.startsWith('_') && !protectedNames.has(n.text) && !hasInitShadow(n) && !hasInitRefToOtherSymbol(n)) {
|
|
3503
|
+
const suggestion = renameDeclaration(n);
|
|
3504
|
+
if (parameterRenameCapturesDefault(n, suggestion, checker))
|
|
3505
|
+
return;
|
|
3506
|
+
// Reject collisions in this declaration scope below, while allowing
|
|
3507
|
+
// the same concise name in an unrelated sibling function scope.
|
|
3508
|
+
if (hasInitRenameCollision(n, suggestion) || hasInitConsumerCollision(n, suggestion))
|
|
3509
|
+
return;
|
|
3510
|
+
const safety = renameSafetyByScope.get(declarationScope(n));
|
|
3511
|
+
if (!isCallbackDeclaration(n) && (safety?.declared.has(suggestion) || (safety?.proposals.get(suggestion) ?? 0) > 1))
|
|
3512
|
+
return;
|
|
3513
|
+
const symbol = suggestion === n.text ? undefined : identifierSymbol(n);
|
|
3514
|
+
if (symbol && (!exported.has(symbol) || cfg.renameExports === true))
|
|
3515
|
+
replacements.set(symbol, suggestion);
|
|
3516
|
+
}
|
|
3517
|
+
ts.forEachChild(n, inspect);
|
|
3518
|
+
};
|
|
3519
|
+
inspect(src);
|
|
3520
|
+
}
|
|
3521
|
+
const edits = new Map();
|
|
3522
|
+
for (const src of program.getSourceFiles()) {
|
|
3523
|
+
if (!allowed.has(src.fileName))
|
|
3524
|
+
continue;
|
|
3525
|
+
/**
|
|
3526
|
+
* Collects source edits for references bound to renamed symbols.
|
|
3527
|
+
*
|
|
3528
|
+
* @param n Identifier or source value currently being analyzed.
|
|
3529
|
+
*/
|
|
3530
|
+
const inspect = (n) => {
|
|
3531
|
+
if (ts.isIdentifier(n) && !isIntrinsicJsxTag(n)) {
|
|
3532
|
+
const replacement = replacements.get(identifierSymbol(n));
|
|
3533
|
+
if (replacement && !(src.fileName.endsWith('.astro') && src.text.slice(n.end, n.end + 2) === '={' && src.text.lastIndexOf('---', n.getStart(src)) >= 0)) {
|
|
3534
|
+
const fileEdits = edits.get(src.fileName) ?? [];
|
|
3535
|
+
fileEdits.push({
|
|
3536
|
+
// Identifier `pos` can include a preceding delimiter (for example the
|
|
3537
|
+
// opening parenthesis of a call argument). Anchor edits from `end` so
|
|
3538
|
+
// expanding a shorthand binding cannot consume adjacent punctuation.
|
|
3539
|
+
span: { start: n.getStart(src), length: n.text.length },
|
|
3540
|
+
newText: !src.fileName.endsWith('.astro') &&
|
|
3541
|
+
(ts.isShorthandPropertyAssignment(n.parent) ||
|
|
3542
|
+
(ts.isBindingElement(n.parent) && n.parent.name === n && !n.parent.dotDotDotToken && !n.parent.propertyName && ts.isObjectBindingPattern(n.parent.parent)))
|
|
3543
|
+
? `${n.text}: ${replacement}`
|
|
3544
|
+
: replacement,
|
|
3545
|
+
});
|
|
3546
|
+
if (ts.isParameter(n.parent) && n.parent.name === n) {
|
|
3547
|
+
const docStart = n.parent.parent.getFullStart();
|
|
3548
|
+
const doc = src.text.slice(docStart, n.parent.parent.getStart(src));
|
|
3549
|
+
const pattern = new RegExp(`(@param\\s+(?:\\{[^}]*\\}\\s*)?)${n.text}\\b`, 'g');
|
|
3550
|
+
for (const match of doc.matchAll(pattern))
|
|
3551
|
+
fileEdits.push({ span: { start: docStart + match.index + match[1].length, length: n.text.length }, newText: replacement });
|
|
3552
|
+
}
|
|
3553
|
+
edits.set(src.fileName, fileEdits);
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
ts.forEachChild(n, inspect);
|
|
3557
|
+
};
|
|
3558
|
+
inspect(src);
|
|
3559
|
+
}
|
|
3560
|
+
for (const [fileName, fileEdits] of edits) {
|
|
3561
|
+
const src = readFileSync(fileName, 'utf8');
|
|
3562
|
+
const n = fileEdits.sort((a, b) => b.span.start - a.span.start).reduce((t, e) => `${t.slice(0, e.span.start)}${e.newText}${t.slice(e.span.start + e.span.length)}`, src);
|
|
3563
|
+
if (n !== src)
|
|
3564
|
+
writeFileSync(fileName, n);
|
|
3565
|
+
}
|
|
3566
|
+
// Renames have changed the source text, so discard the previous AST before
|
|
3567
|
+
// inspecting import spans. Otherwise an import edit can land in the wrong
|
|
3568
|
+
// token when a declaration changed length.
|
|
3569
|
+
program = ts.createProgram({
|
|
3570
|
+
rootNames: srcFiles(cfg).filter(f => C_M_JS_TS_X_CLASS_2.test(f)),
|
|
3571
|
+
options: {
|
|
3572
|
+
allowNonTsExtensions: true,
|
|
3573
|
+
allowJs: true,
|
|
3574
|
+
checkJs: false,
|
|
3575
|
+
jsx: ts.JsxEmit.Preserve,
|
|
3576
|
+
module: ts.ModuleKind.ESNext,
|
|
3577
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
3578
|
+
skipLibCheck: true,
|
|
3579
|
+
target: ts.ScriptTarget.ESNext,
|
|
3580
|
+
},
|
|
3581
|
+
});
|
|
3582
|
+
checker = program.getTypeChecker();
|
|
3583
|
+
// Export renames can leave stale named imports when a consumer was already
|
|
3584
|
+
// out of sync. Repair only an absent import whose concise spelling is an
|
|
3585
|
+
// actual export of the same module; never guess across unrelated symbols.
|
|
3586
|
+
for (const src of program.getSourceFiles()) {
|
|
3587
|
+
if (!allowed.has(src.fileName))
|
|
3588
|
+
continue;
|
|
3589
|
+
const fileEdits = [];
|
|
3590
|
+
/**
|
|
3591
|
+
* Checks consumers for an existing initializer using the proposed local name.
|
|
3592
|
+
*
|
|
3593
|
+
* @param node Current syntax-tree node being inspected.
|
|
3594
|
+
*/
|
|
3595
|
+
const visit = (node) => {
|
|
3596
|
+
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) {
|
|
3597
|
+
const module = checker.getSymbolAtLocation(node.moduleSpecifier);
|
|
3598
|
+
const exportsByName = new Map((module ? checker.getExportsOfModule(module) : []).map(s => [s.name, s]));
|
|
3599
|
+
for (const specifier of node.importClause.namedBindings.elements) {
|
|
3600
|
+
const oldName = specifier.propertyName?.text ?? specifier.name.text;
|
|
3601
|
+
if (exportsByName.has(oldName))
|
|
3602
|
+
continue;
|
|
3603
|
+
const concise = renameId(oldName);
|
|
3604
|
+
// Never guess a replacement for an unresolved module. A local-looking
|
|
3605
|
+
// specifier is not evidence that the concise spelling is exported.
|
|
3606
|
+
if (concise === oldName || !exportsByName.has(concise))
|
|
3607
|
+
continue;
|
|
3608
|
+
const imported = specifier.propertyName ?? specifier.name;
|
|
3609
|
+
fileEdits.push({ span: { start: imported.getStart(src), length: imported.text.length }, newText: concise });
|
|
3610
|
+
}
|
|
3611
|
+
}
|
|
3612
|
+
ts.forEachChild(node, visit);
|
|
3613
|
+
};
|
|
3614
|
+
visit(src);
|
|
3615
|
+
if (fileEdits.length) {
|
|
3616
|
+
const srcText = readFileSync(src.fileName, 'utf8');
|
|
3617
|
+
const updated = fileEdits.sort((a, b) => b.span.start - a.span.start).reduce((t, e) => `${t.slice(0, e.span.start)}${e.newText}${t.slice(e.span.start + e.span.length)}`, srcText);
|
|
3618
|
+
if (updated !== srcText)
|
|
3619
|
+
writeFileSync(src.fileName, updated);
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
/**
|
|
3624
|
+
* Runs the core static quality checks against one source scope.
|
|
3625
|
+
*
|
|
3626
|
+
* @param cfg Quality configuration defining checks, paths, and protections.
|
|
3627
|
+
* @param _strict Retained for call compatibility; all findings now fail quality.
|
|
3628
|
+
* @param all Whether to inspect every configured file instead of changed files.
|
|
3629
|
+
* @param analysis Optional analysis context for the selected source scope.
|
|
3630
|
+
*
|
|
3631
|
+
* @return Findings grouped by import, naming, alias, forwarding, and documentation checks.
|
|
3632
|
+
*/
|
|
3633
|
+
export function runQuality(cfg, _strict = false, all = true, analysis) {
|
|
3634
|
+
void _strict;
|
|
3635
|
+
const scoped = scopedCfg(cfg, all);
|
|
3636
|
+
const ctx = analysis;
|
|
3637
|
+
const result = {
|
|
3638
|
+
imports: [],
|
|
3639
|
+
naming: [],
|
|
3640
|
+
aliases: [],
|
|
3641
|
+
forwarding: [],
|
|
3642
|
+
documentation: [],
|
|
3643
|
+
};
|
|
3644
|
+
let duplicateImports = [];
|
|
3645
|
+
if (qualityCheckEnabled(cfg, 'import')) {
|
|
3646
|
+
qualityHeader('imports', 'Checking local import resolution');
|
|
3647
|
+
let findings = 0;
|
|
3648
|
+
try {
|
|
3649
|
+
result.imports = checkImports(scoped);
|
|
3650
|
+
printFindings(result.imports, f => `Unresolved import: ${f.importer} -> ${f.specifier}`);
|
|
3651
|
+
findings += result.imports.length;
|
|
3652
|
+
}
|
|
3653
|
+
catch (error) {
|
|
3654
|
+
recordQualityFailure('imports', error);
|
|
3655
|
+
findings += 1;
|
|
3656
|
+
}
|
|
3657
|
+
try {
|
|
3658
|
+
duplicateImports = duplicateImportFindings(ctx?.files ?? filesFor(scoped, true));
|
|
3659
|
+
printFindings(duplicateImports, f => `Duplicate named import: ${f.file}:${f.line} repeats an import from ${f.module}`);
|
|
3660
|
+
findings += duplicateImports.length;
|
|
3661
|
+
}
|
|
3662
|
+
catch (error) {
|
|
3663
|
+
recordQualityFailure('imports', error);
|
|
3664
|
+
findings += 1;
|
|
3665
|
+
}
|
|
3666
|
+
printCheckStatus('imports', findings);
|
|
3667
|
+
}
|
|
3668
|
+
if (qualityCheckEnabled(cfg, 'name'))
|
|
3669
|
+
result.naming = runFindingCheck('naming', 'Checking concise, consistent symbol names', () => namingFindings(scoped, ctx), f => `Naming error: ${f.file}: ${f.name} -> ${f.suggestion}${f.reason ? `; ${f.reason}` : ''}`);
|
|
3670
|
+
if (qualityCheckEnabled(cfg, 'alias'))
|
|
3671
|
+
result.aliases = runFindingCheck('aliases', 'Checking for unnecessary compatibility aliases', () => aliasFindings(scoped, ctx), f => `Alias: ${f.file}:${f.line} ${f.kind} ${f.name} -> ${f.replacement}`);
|
|
3672
|
+
if (qualityCheckEnabled(cfg, 'forward'))
|
|
3673
|
+
result.forwarding = runFindingCheck('forwarding', 'Checking object-forwarding opportunities', () => objectForwardingFindings(scoped, ctx), f => `Forwarding error: ${f.file}:${f.line}:${f.column} ${f.callee} repeats ${f.source}.${f.properties.join(', ')}; ${f.recommendation}.`);
|
|
3674
|
+
if (qualityCheckEnabled(cfg, 'document'))
|
|
3675
|
+
result.documentation = runFindingCheck('documentation', 'Checking meaningful file, function, and parameter documentation', () => documentationFindings(scoped, ctx), f => `Documentation error: ${f.file}:${f.line}:${f.column} ${f.name}; ${f.reason}.`);
|
|
3676
|
+
if (result.imports.length || duplicateImports.length || result.aliases.length || result.documentation.length > 0 || result.naming.length > 0 || result.forwarding.length > 0)
|
|
3677
|
+
process.exitCode = 1;
|
|
3678
|
+
return result;
|
|
3679
|
+
}
|
|
3680
|
+
/**
|
|
3681
|
+
* Applies documentation maintenance and optional formatting to the requested source scope.
|
|
3682
|
+
*
|
|
3683
|
+
* @param cfg Normalized quality configuration for the current repository.
|
|
3684
|
+
* @param opts CLI options controlling scope and writes.
|
|
3685
|
+
* @param quiet Whether the helper should omit the follow-up core quality pass.
|
|
3686
|
+
*
|
|
3687
|
+
* @return Nothing; maintenance and formatter failures are reflected in the process exit code.
|
|
3688
|
+
*/
|
|
3689
|
+
function runDocumentation(cfg, opts, quiet) {
|
|
3690
|
+
if (!qualityCheckEnabled(cfg, 'document'))
|
|
3691
|
+
return;
|
|
3692
|
+
qualityHeader('documentation', 'Checking documentation structure and meaningful descriptions');
|
|
3693
|
+
if (!quiet)
|
|
3694
|
+
runQuality(cfg, opts.strict, opts.all);
|
|
3695
|
+
}
|
|
3696
|
+
/**
|
|
3697
|
+
* Dispatches one quality CLI command after parsing its scope and autofix flags.
|
|
3698
|
+
*
|
|
3699
|
+
* @param cfg Normalized quality configuration for the current repository.
|
|
3700
|
+
* @param args CLI arguments to dispatch.
|
|
3701
|
+
*
|
|
3702
|
+
* @return A completion promise for asynchronous checks, or nothing for synchronous commands.
|
|
3703
|
+
*/
|
|
3704
|
+
export function runQualityCli(cfg, args = process.argv.slice(2)) {
|
|
3705
|
+
validCliArgs(args);
|
|
3706
|
+
const reportIdx = args.indexOf('--report-json');
|
|
3707
|
+
const reportPath = reportIdx < 0 ? undefined : args[reportIdx + 1];
|
|
3708
|
+
const cmdArgs = reportIdx < 0 ? args : args.filter((_, i) => i !== reportIdx && i !== reportIdx + 1);
|
|
3709
|
+
if (!reportPath)
|
|
3710
|
+
return dispatchQualityCli(cfg, cmdArgs);
|
|
3711
|
+
reportStages = new Map();
|
|
3712
|
+
reportStageName = undefined;
|
|
3713
|
+
reportGitHubData = undefined;
|
|
3714
|
+
/**
|
|
3715
|
+
* Writes the collected quality stage results to the requested JSON report.
|
|
3716
|
+
*
|
|
3717
|
+
*/
|
|
3718
|
+
const writeReport = () => {
|
|
3719
|
+
const executed = [...(reportStages?.values() ?? [])].filter(s => {
|
|
3720
|
+
if (s.name.includes('/') || s.name.startsWith('recommendation:'))
|
|
3721
|
+
return false;
|
|
3722
|
+
if (!qualityCheckEnabled(cfg, { imports: 'import', naming: 'name', aliases: 'alias', forwarding: 'forward', documentation: 'document', typecheck: 'type' }[s.name] ??
|
|
3723
|
+
(s.name.startsWith('command:') ? 'command' : s.name)))
|
|
3724
|
+
return false;
|
|
3725
|
+
if (s.name === 'security' && !cfg.security)
|
|
3726
|
+
return false;
|
|
3727
|
+
if (s.name === 'repeated-classes' && !cfg.repeatedClasses)
|
|
3728
|
+
return false;
|
|
3729
|
+
if (s.name === 'tailwind-canonical' && !cfg.tailwindCanonical)
|
|
3730
|
+
return false;
|
|
3731
|
+
if (s.name === 'regex-dedup' && !cfg.regexDedup)
|
|
3732
|
+
return false;
|
|
3733
|
+
if (s.name === 'ui-patterns' && !cfg.uiPatterns)
|
|
3734
|
+
return false;
|
|
3735
|
+
return true;
|
|
3736
|
+
});
|
|
3737
|
+
const capabilities = Object.entries(LANGUAGE_CAPABILITIES).flatMap(([l, c]) => [
|
|
3738
|
+
...Object.entries(c.checks).map(([n, i]) => ({ language: l, kind: 'check', name: n, ...i })),
|
|
3739
|
+
...Object.entries(c.autofixes).map(([n, i]) => ({ language: l, kind: 'autofix', name: n, ...i })),
|
|
3740
|
+
]);
|
|
3741
|
+
writeFileSync(resolve(cfg.root, reportPath), `${JSON.stringify({
|
|
3742
|
+
schemaVersion: 1,
|
|
3743
|
+
generatedAt: new Date().toISOString(),
|
|
3744
|
+
command: cmdArgs.find(a => !a.startsWith('-')) ?? 'quality',
|
|
3745
|
+
scope: cmdArgs.includes('--all') || cmdArgs.includes('quality:all') ? 'all' : 'changed',
|
|
3746
|
+
checks: [
|
|
3747
|
+
...executed,
|
|
3748
|
+
...[
|
|
3749
|
+
'documentation',
|
|
3750
|
+
'format',
|
|
3751
|
+
'imports',
|
|
3752
|
+
'naming',
|
|
3753
|
+
'forwarding',
|
|
3754
|
+
'lint',
|
|
3755
|
+
'dead-code',
|
|
3756
|
+
'typecheck',
|
|
3757
|
+
'diff',
|
|
3758
|
+
'aliases',
|
|
3759
|
+
'security',
|
|
3760
|
+
'repeated-classes',
|
|
3761
|
+
'tailwind-canonical',
|
|
3762
|
+
'regex-dedup',
|
|
3763
|
+
'ui-patterns',
|
|
3764
|
+
'github',
|
|
3765
|
+
]
|
|
3766
|
+
.filter(n => !executed.some(s => s.name === n))
|
|
3767
|
+
.map(n => ({ name: n, status: 'skipped', findings: 0 })),
|
|
3768
|
+
...capabilities
|
|
3769
|
+
.filter(i => i.kind === 'check' && i.status === 'not-applicable')
|
|
3770
|
+
.map(i => ({ name: `${i.language}:${i.name}`, status: 'not-applicable', findings: 0, reason: i.reason })),
|
|
3771
|
+
],
|
|
3772
|
+
capabilities,
|
|
3773
|
+
...(reportGitHubData ? { github: reportGitHubData } : {}),
|
|
3774
|
+
}, null, 2)}\n`);
|
|
3775
|
+
reportStages = undefined;
|
|
3776
|
+
reportStageName = undefined;
|
|
3777
|
+
};
|
|
3778
|
+
try {
|
|
3779
|
+
const result = dispatchQualityCli(cfg, cmdArgs);
|
|
3780
|
+
if (result instanceof Promise)
|
|
3781
|
+
return result.finally(writeReport);
|
|
3782
|
+
}
|
|
3783
|
+
catch (err) {
|
|
3784
|
+
writeReport();
|
|
3785
|
+
throw err;
|
|
3786
|
+
}
|
|
3787
|
+
writeReport();
|
|
3788
|
+
}
|
|
3789
|
+
// hygiene-ignore single-use -- Keep the documented runFullQuality declaration so its parameter and return contract remains attached.
|
|
3790
|
+
/**
|
|
3791
|
+
* Runs the full quality matrix in package-owned phase order.
|
|
3792
|
+
*
|
|
3793
|
+
* @param cfg Normalized repository configuration.
|
|
3794
|
+
* @param args Validated command arguments.
|
|
3795
|
+
* @param opts Scope and write controls parsed by the CLI.
|
|
3796
|
+
*
|
|
3797
|
+
* @return A promise only when the asynchronous Tailwind check is selected.
|
|
3798
|
+
*/
|
|
3799
|
+
function runFullQuality(cfg, args, opts) {
|
|
3800
|
+
process.exitCode = 0;
|
|
3801
|
+
qualityCheckName = undefined;
|
|
3802
|
+
qualityDetails = [];
|
|
3803
|
+
const profileResolution = opts.skipCommands ? { checks: [], skipped: [], failed: [] } : resolveLanguageProfiles(cfg);
|
|
3804
|
+
const profileToolResults = new Map();
|
|
3805
|
+
if (!opts.skipCommands) {
|
|
3806
|
+
reportSkippedLangChecks(cfg, profileResolution.skipped);
|
|
3807
|
+
reportFailedLangChecks(cfg, profileResolution.failed);
|
|
3808
|
+
}
|
|
3809
|
+
/**
|
|
3810
|
+
* Runs the configured commands assigned to one quality phase.
|
|
3811
|
+
*
|
|
3812
|
+
* @param phase Quality phase whose configured commands should run.
|
|
3813
|
+
*
|
|
3814
|
+
* @return Number of configured command failures in the phase.
|
|
3815
|
+
*/
|
|
3816
|
+
const runConfiguredCmds = (phase) => runQualityPhase(cfg, phase, profileResolution.checks, profileToolResults);
|
|
3817
|
+
/**
|
|
3818
|
+
* Checks whether a configured autofix is enabled for this invocation.
|
|
3819
|
+
*
|
|
3820
|
+
* @param check Quality invocation or check being evaluated.
|
|
3821
|
+
*
|
|
3822
|
+
* @return Whether the named autofix is enabled for this run.
|
|
3823
|
+
*/
|
|
3824
|
+
const fix = (check) => qualityAutofixEnabled(cfg, check, opts.fix);
|
|
3825
|
+
const scoped = scopedCfg(cfg, opts.all);
|
|
3826
|
+
if (opts.fix) {
|
|
3827
|
+
outputPhase = 'PREPARING SAFE FIXES';
|
|
3828
|
+
console.error('\nPREPARING SAFE FIXES');
|
|
3829
|
+
qualityCheckName = 'Safe Fixes';
|
|
3830
|
+
qualityDetails = [];
|
|
3831
|
+
startQualitySpinner(qualityCheckName);
|
|
3832
|
+
}
|
|
3833
|
+
let sFixFailed = false;
|
|
3834
|
+
/**
|
|
3835
|
+
* Runs one safe-fix stage and records if that stage failed.
|
|
3836
|
+
*
|
|
3837
|
+
* @param name Name or identifier spelling being checked.
|
|
3838
|
+
* @param action Safe-fix action to run under failure handling.
|
|
3839
|
+
*/
|
|
3840
|
+
const sFix = (name, action) => {
|
|
3841
|
+
if (!continueAfterFailure(name, action))
|
|
3842
|
+
sFixFailed = true;
|
|
3843
|
+
};
|
|
3844
|
+
if (fix('duplicateImports') && qualityCheckEnabled(cfg, 'import'))
|
|
3845
|
+
sFix('duplicate imports', () => {
|
|
3846
|
+
const removed = fixDuplicateImports(filesFor(cfg, opts.all));
|
|
3847
|
+
if (removed && !outputPhase)
|
|
3848
|
+
console.info(`Import fixer: ${removed} repeated declaration${removed === 1 ? '' : 's'} removed.`);
|
|
3849
|
+
});
|
|
3850
|
+
if (opts.fix && qualityCheckEnabled(cfg, 'name') && fix('name'))
|
|
3851
|
+
sFix('naming', () => {
|
|
3852
|
+
if (namingFindings(scopedCfg(cfg, opts.all)).length)
|
|
3853
|
+
fixNames(cfg, opts.all);
|
|
3854
|
+
});
|
|
3855
|
+
if (fix('accessibility') && qualityCheckEnabled(cfg, 'accessibility'))
|
|
3856
|
+
sFix('accessibility', () => fixAccessibleNames(scoped));
|
|
3857
|
+
if (fix('displayName') && qualityCheckEnabled(cfg, 'display-name'))
|
|
3858
|
+
sFix('display-name', () => fixDisplayNames(scoped));
|
|
3859
|
+
if (fix('documentedCommands') && qualityCheckEnabled(cfg, 'documented-commands'))
|
|
3860
|
+
sFix('documented-commands', () => fixDocumentedCommands(cfg));
|
|
3861
|
+
if (fix('forward') && qualityCheckEnabled(cfg, 'forward'))
|
|
3862
|
+
sFix('forwarding', () => {
|
|
3863
|
+
const result = fixObjectForwarding(scoped);
|
|
3864
|
+
if ((result.fixed || result.skipped) && !outputPhase)
|
|
3865
|
+
console.info(`Forwarding fixer: ${result.fixed} exact duplicates removed${result.skipped ? `; ${result.skipped} unsafe cases left unchanged` : ''}.`);
|
|
3866
|
+
});
|
|
3867
|
+
if (fix('repeatedClasses') && qualityCheckEnabled(cfg, 'repeated-classes'))
|
|
3868
|
+
sFix('repeated-classes', () => {
|
|
3869
|
+
const result = fixRepeatedClasses(scoped);
|
|
3870
|
+
if ((result.fixed || result.skipped) && !outputPhase)
|
|
3871
|
+
console.info(`Class fixer: ${result.fixed} attributes replaced${result.skipped ? `; ${result.skipped} unsafe cases left unchanged` : ''}.`);
|
|
3872
|
+
});
|
|
3873
|
+
if (fix('regexDedup') && qualityCheckEnabled(cfg, 'regex-dedup'))
|
|
3874
|
+
sFix('regex-dedup', () => {
|
|
3875
|
+
const result = fixRegexDedup(scoped);
|
|
3876
|
+
if ((result.fixed || result.skipped) && !outputPhase)
|
|
3877
|
+
console.info(`Regex fixer: ${result.fixed} literals replaced${result.skipped ? `; ${result.skipped} unsafe cases left unchanged` : ''}.`);
|
|
3878
|
+
});
|
|
3879
|
+
if (fix('lint') && qualityCheckEnabled(cfg, 'lint'))
|
|
3880
|
+
sFix('lint', () => runLint(cfg, { ...opts, fix: true }, true, true));
|
|
3881
|
+
if (opts.fix && qualityCheckEnabled(cfg, 'alias'))
|
|
3882
|
+
sFix('aliases', () => void aliasFindings(scoped, true));
|
|
3883
|
+
if (qualityCheckEnabled(cfg, 'document'))
|
|
3884
|
+
sFix('documentation', () => {
|
|
3885
|
+
if (opts.fix && qualityAutofixEnabled(cfg, 'document', opts.fix)) {
|
|
3886
|
+
if (filesFor(cfg, opts.all).length)
|
|
3887
|
+
runDocumentation(cfg, opts, true);
|
|
3888
|
+
}
|
|
3889
|
+
else {
|
|
3890
|
+
if (documentationFindings(scopedCfg(cfg, opts.all)).some(f => f.severity === 'error'))
|
|
3891
|
+
runDocumentation(cfg, opts, true);
|
|
3892
|
+
}
|
|
3893
|
+
});
|
|
3894
|
+
if (fix('errorBoundaries'))
|
|
3895
|
+
sFix('error-boundaries', () => {
|
|
3896
|
+
const fixed = fixErrorBoundaries(scopedCfg(cfg, opts.all));
|
|
3897
|
+
if (fixed)
|
|
3898
|
+
console.info(`Error-boundary autofix: guarded React roots in ${fixed} file${fixed === 1 ? '' : 's'}.`);
|
|
3899
|
+
});
|
|
3900
|
+
if (opts.fix && !opts.skipCommands && profileResolution.checks.some(c => c.autofix))
|
|
3901
|
+
sFix('native language fixes', () => runLangProfileFixes(cfg, profileResolution.checks, profileToolResults));
|
|
3902
|
+
if (opts.fix) {
|
|
3903
|
+
stopQualitySpinner();
|
|
3904
|
+
console.error(` ${sFixFailed ? '✗' : '✓'} Safe Fixes`);
|
|
3905
|
+
printQualityDetails();
|
|
3906
|
+
}
|
|
3907
|
+
outputPhase = undefined;
|
|
3908
|
+
beginQualityPhase('Format');
|
|
3909
|
+
if (qualityCheckEnabled(cfg, 'format'))
|
|
3910
|
+
continueAfterFailure('format', () => runFormatter(cfg, { ...opts, fix: fix('format') }, opts.all ? [] : filesFor(cfg, false)));
|
|
3911
|
+
if (!opts.skipCommands)
|
|
3912
|
+
continueAfterFailure('format', () => void runConfiguredCmds('Format'));
|
|
3913
|
+
beginQualityPhase('Static quality');
|
|
3914
|
+
/**
|
|
3915
|
+
* Runs the remaining dead-code, lint, analysis, and documentation checks.
|
|
3916
|
+
*
|
|
3917
|
+
*/
|
|
3918
|
+
const continueStaticAndLater = () => {
|
|
3919
|
+
if (qualityCheckEnabled(cfg, 'dead-code')) {
|
|
3920
|
+
let deadCodeChangedFiles = [];
|
|
3921
|
+
continueAfterFailure('dead-code', () => {
|
|
3922
|
+
deadCodeChangedFiles = runDeadCodeCmd(cfg, qualityAutofixEnabled(cfg, 'dead-code', opts.fix), opts.all);
|
|
3923
|
+
});
|
|
3924
|
+
if (deadCodeChangedFiles.length && qualityCheckEnabled(cfg, 'format')) {
|
|
3925
|
+
// hygiene-ignore single-use -- Snapshot the earlier format failure before rerunning format after dead-code fixes.
|
|
3926
|
+
const fmtFailedBeforeDeadCode = reportStages?.get('format')?.status === 'failed';
|
|
3927
|
+
continueAfterFailure('format', () => runFormatter(cfg, { ...opts, fix: true }, deadCodeChangedFiles));
|
|
3928
|
+
if (fmtFailedBeforeDeadCode) {
|
|
3929
|
+
const fmtStage = reportStages?.get('format');
|
|
3930
|
+
if (fmtStage)
|
|
3931
|
+
fmtStage.status = 'failed';
|
|
3932
|
+
}
|
|
3933
|
+
}
|
|
3934
|
+
}
|
|
3935
|
+
if (qualityCheckEnabled(cfg, 'lint'))
|
|
3936
|
+
continueAfterFailure('lint', () => runLint(cfg, { ...opts, fix: false }, true, true));
|
|
3937
|
+
qualityHeader('source-analysis', '');
|
|
3938
|
+
let analysis;
|
|
3939
|
+
try {
|
|
3940
|
+
analysis = createQualityAnalysis(scoped);
|
|
3941
|
+
printCheckStatus('source-analysis', 0);
|
|
3942
|
+
}
|
|
3943
|
+
catch (err) {
|
|
3944
|
+
recordQualityFailure('source-analysis', err);
|
|
3945
|
+
printCheckStatus('source-analysis', 1);
|
|
3946
|
+
}
|
|
3947
|
+
continueAfterFailure('static checks', () => runGenericChecks(scoped, analysis));
|
|
3948
|
+
continueAfterFailure('static checks', () => void runQuality(cfg, opts.strict, opts.all, analysis));
|
|
3949
|
+
if (!opts.skipCommands)
|
|
3950
|
+
continueAfterFailure('static quality', () => void runConfiguredCmds('Static quality'));
|
|
3951
|
+
if (!opts.skipRecommendations)
|
|
3952
|
+
continueAfterFailure('recommendations', () => runRecommendationCmds(cfg));
|
|
3953
|
+
beginQualityPhase('Tests');
|
|
3954
|
+
if (!opts.skipCommands)
|
|
3955
|
+
continueAfterFailure('tests', () => void runConfiguredCmds('Tests'));
|
|
3956
|
+
beginQualityPhase('Framework / type checks');
|
|
3957
|
+
if (qualityCheckEnabled(cfg, 'type') && (cfg.tools?.tsc || cfg.typecheckCommand))
|
|
3958
|
+
continueAfterFailure('typecheck', () => {
|
|
3959
|
+
runTypecheck(cfg);
|
|
3960
|
+
if (cfg.typecheckExtensions?.length && !cfg.typecheckRoots?.length && !cfg.typecheckCommand)
|
|
3961
|
+
runProjectTypecheck(cfg);
|
|
3962
|
+
});
|
|
3963
|
+
if (!opts.skipCommands)
|
|
3964
|
+
continueAfterFailure('framework checks', () => void runConfiguredCmds('Framework / type checks'));
|
|
3965
|
+
beginQualityPhase('Build');
|
|
3966
|
+
if (!opts.skipCommands)
|
|
3967
|
+
continueAfterFailure('build', () => void runConfiguredCmds('Build'));
|
|
3968
|
+
beginQualityPhase('Repository health');
|
|
3969
|
+
if (!opts.skipCommands)
|
|
3970
|
+
continueAfterFailure('repository health', () => void runConfiguredCmds('Repository health'));
|
|
3971
|
+
if (qualityCheckEnabled(cfg, 'diff') && !hasCfgdGitDiffCheck(cfg))
|
|
3972
|
+
continueAfterFailure('diff', () => (function runDiffCheck(cfg) {
|
|
3973
|
+
qualityHeader('diff', 'Checking Git whitespace and patch errors');
|
|
3974
|
+
const status = run(cfg, 'git', ['-c', 'core.pager=cat', 'diff', '--check']);
|
|
3975
|
+
if (status)
|
|
3976
|
+
process.exitCode = status;
|
|
3977
|
+
printCheckStatus('diff', status ? 1 : 0);
|
|
3978
|
+
})(cfg));
|
|
3979
|
+
if (qualityCheckEnabled(cfg, 'github') && cfg.github?.repositories?.length)
|
|
3980
|
+
continueAfterFailure('github', () => runGitHubCheck(cfg, [], false, args.includes('--warn')));
|
|
3981
|
+
console.error(`\n${process.exitCode ? '✗' : '✓'} Quality complete`);
|
|
3982
|
+
outputPhase = undefined;
|
|
3983
|
+
};
|
|
3984
|
+
if (cfg.tailwindCanonical && qualityCheckEnabled(cfg, 'tailwind-canonical'))
|
|
3985
|
+
return runTailwindCanonicalCheck(cfg, fix('tailwindCanonical'))
|
|
3986
|
+
.catch((e) => {
|
|
3987
|
+
recordQualityFailure('tailwind-canonical', e);
|
|
3988
|
+
printCheckStatus('tailwind-canonical', 1);
|
|
3989
|
+
})
|
|
3990
|
+
.then(continueStaticAndLater);
|
|
3991
|
+
continueStaticAndLater();
|
|
3992
|
+
}
|
|
3993
|
+
/**
|
|
3994
|
+
* Route validated arguments to the requested quality command.
|
|
3995
|
+
*
|
|
3996
|
+
* @param cfg Normalized repository quality configuration.
|
|
3997
|
+
* @param args Validated CLI arguments.
|
|
3998
|
+
*
|
|
3999
|
+
* @return A completion promise for asynchronous checks, or nothing for synchronous commands.
|
|
4000
|
+
*/
|
|
4001
|
+
function dispatchQualityCli(cfg, args) {
|
|
4002
|
+
validCliArgs(args);
|
|
4003
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
4004
|
+
console.info(JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '../../package.json'), 'utf8')).version);
|
|
4005
|
+
return;
|
|
4006
|
+
}
|
|
4007
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
4008
|
+
console.info('Usage: hygiene <command> [options]');
|
|
4009
|
+
console.info('Commands include quality, history, github, document, format, lint, knip, types, single-use, dead-code, tailwind-canonical, security, error-boundaries, ui-recommendations, and domain.');
|
|
4010
|
+
console.info('Options: --all, --warn, --fix, --safe-fix, --strict, --skip-commands, --skip-recommendations, --report-json <path>, --repository owner/name; history also accepts --branch <name> and --base-sha <sha>.');
|
|
4011
|
+
return;
|
|
4012
|
+
}
|
|
4013
|
+
const cmd = args.find(a => !a.startsWith('-')) ?? 'quality';
|
|
4014
|
+
const opts = {
|
|
4015
|
+
fix: !args.includes('--warn') && (args.includes('--fix') || args.includes('--safe-fix')),
|
|
4016
|
+
all: args.includes('--all') || cmd === 'quality:all',
|
|
4017
|
+
strict: args.includes('--strict'),
|
|
4018
|
+
skipCommands: args.includes('--skip-commands'),
|
|
4019
|
+
skipRecommendations: args.includes('--skip-recommendations'),
|
|
4020
|
+
};
|
|
4021
|
+
/**
|
|
4022
|
+
* Checks whether a configured autofix is enabled for this invocation.
|
|
4023
|
+
*
|
|
4024
|
+
* @param check Quality invocation or check being evaluated.
|
|
4025
|
+
*
|
|
4026
|
+
* @return Whether the named autofix is enabled for this run.
|
|
4027
|
+
*/
|
|
4028
|
+
const fix = (check) => qualityAutofixEnabled(cfg, check, opts.fix);
|
|
4029
|
+
if (cfg.tailwindCanonical &&
|
|
4030
|
+
qualityCheckEnabled(cfg, 'tailwind-canonical') &&
|
|
4031
|
+
!['quality', 'quality:all', 'quality:baseline'].includes(cmd) &&
|
|
4032
|
+
['imports', 'quality:patterns', 'types:architecture'].includes(cmd))
|
|
4033
|
+
return runTailwindCanonicalCheck(cfg, fix('tailwindCanonical')).then(() => {
|
|
4034
|
+
return dispatchQualityCli({ ...cfg, enabledChecks: { ...cfg.enabledChecks, 'tailwind-canonical': false } }, args);
|
|
4035
|
+
});
|
|
4036
|
+
if (cmd === 'github') {
|
|
4037
|
+
runGitHubCheck(cfg, (function optVals(args, flag) {
|
|
4038
|
+
return args.flatMap((a, i) => (a === flag && args[i + 1] ? [args[i + 1]] : []));
|
|
4039
|
+
})(args, '--repository'), true, args.includes('--warn'));
|
|
4040
|
+
return;
|
|
4041
|
+
}
|
|
4042
|
+
if (cmd === 'document' || cmd === 'maintain') {
|
|
4043
|
+
runDocumentation(cfg, opts, args.includes('--quiet'));
|
|
4044
|
+
if (qualityCheckEnabled(cfg, 'format'))
|
|
4045
|
+
runFormatter(cfg, { ...opts, fix: fix('format') }, args.slice(1));
|
|
4046
|
+
return;
|
|
4047
|
+
}
|
|
4048
|
+
if (cmd === 'format') {
|
|
4049
|
+
if (!qualityCheckEnabled(cfg, 'format'))
|
|
4050
|
+
return;
|
|
4051
|
+
runFormatter(cfg, { ...opts, fix: fix('format') }, args.slice(1));
|
|
4052
|
+
return;
|
|
4053
|
+
}
|
|
4054
|
+
if (cmd === 'naming') {
|
|
4055
|
+
if (qualityCheckEnabled(cfg, 'name') && fix('name'))
|
|
4056
|
+
fixNames(cfg, opts.all);
|
|
4057
|
+
runQuality(cfg, opts.strict, opts.all);
|
|
4058
|
+
return;
|
|
4059
|
+
}
|
|
4060
|
+
if (cmd === 'domain') {
|
|
4061
|
+
const name = args[args.indexOf('domain') + 1];
|
|
4062
|
+
if (!name)
|
|
4063
|
+
throw new Error('Pass a quality domain name.');
|
|
4064
|
+
runCfgdCmd(cfg, name);
|
|
4065
|
+
return;
|
|
4066
|
+
}
|
|
4067
|
+
if (cmd === 'single-use') {
|
|
4068
|
+
runDeadCodeCmd(cfg, qualityAutofixEnabled(cfg, 'dead-code', opts.fix), opts.all);
|
|
4069
|
+
return;
|
|
4070
|
+
}
|
|
4071
|
+
if (cmd === 'dead-code') {
|
|
4072
|
+
runDeadCodeCmd(cfg, qualityAutofixEnabled(cfg, 'dead-code', opts.fix), opts.all);
|
|
4073
|
+
return;
|
|
4074
|
+
}
|
|
4075
|
+
if (cmd === 'tailwind-canonical') {
|
|
4076
|
+
if (!qualityCheckEnabled(cfg, 'tailwind-canonical') || !cfg.tailwindCanonical)
|
|
4077
|
+
return;
|
|
4078
|
+
return runTailwindCanonicalCheck(cfg, fix('tailwindCanonical'));
|
|
4079
|
+
}
|
|
4080
|
+
if (cmd === 'security' || cmd === 'repeated-classes' || cmd === 'regex-dedup' || cmd === 'ui-patterns') {
|
|
4081
|
+
if (cmd === 'repeated-classes' && fix('repeatedClasses')) {
|
|
4082
|
+
const result = fixRepeatedClasses(cfg);
|
|
4083
|
+
console.info(` fixed ${result.fixed} class attributes${result.skipped ? `; ${result.skipped} unsafe cases left unchanged` : ''}`);
|
|
4084
|
+
}
|
|
4085
|
+
if (cmd === 'regex-dedup' && fix('regexDedup')) {
|
|
4086
|
+
const result = fixRegexDedup(cfg);
|
|
4087
|
+
console.info(` fixed ${result.fixed} regex literals${result.skipped ? `; ${result.skipped} unsafe cases left unchanged` : ''}`);
|
|
4088
|
+
}
|
|
4089
|
+
if (cmd === 'security' || cmd === 'ui-patterns') {
|
|
4090
|
+
const findings = cmd === 'security' ? securityFindings(cfg) : uiPatternFindings(cfg);
|
|
4091
|
+
qualityHeader(cmd, `Checking ${cmd.replace(G_REGEX(), ' ')}`);
|
|
4092
|
+
printFindings(findings, f => `${'file' in f ? `${f.file}: ` : ''}${'message' in f ? f.message : 'component' in f ? `${f.line}:${f.column} ${f.component}: ${f.recommendation}` : 'method' in f ? `${f.line}:${f.column} ${f.method}(${f.receiver}): ${f.recommendation}` : 'command' in f ? `${f.line}: ${f.recommendation} (${f.command})` : 'value' in f ? `${f.count}x ${f.value} (${f.locations.join(', ')})` : 'source' in f ? `${f.count}x ${f.source} (${f.locations.join(', ')})` : f.pattern}`);
|
|
4093
|
+
if (findings.length)
|
|
4094
|
+
process.exitCode = 1;
|
|
4095
|
+
return;
|
|
4096
|
+
}
|
|
4097
|
+
const findings = cmd === 'repeated-classes' ? repeatedClassFindings(cfg) : regexFindings(cfg);
|
|
4098
|
+
qualityHeader(cmd, `Checking ${cmd.replace(G_REGEX(), ' ')}`);
|
|
4099
|
+
printFindings(findings, f => `${'file' in f ? `${f.file}: ` : ''}${'message' in f ? f.message : 'component' in f ? `${f.line}:${f.column} ${f.component}: ${f.recommendation}` : 'method' in f ? `${f.line}:${f.column} ${f.method}(${f.receiver}): ${f.recommendation}` : 'command' in f ? `${f.line}: ${f.recommendation} (${f.command})` : 'value' in f ? `${f.count}x ${f.value} (${f.locations.join(', ')})` : 'source' in f ? `${f.count}x ${f.source} (${f.locations.join(', ')})` : f.pattern}`);
|
|
4100
|
+
if (findings.length)
|
|
4101
|
+
process.exitCode = 1;
|
|
4102
|
+
return;
|
|
4103
|
+
}
|
|
4104
|
+
if (cmd === 'ui-recommendations') {
|
|
4105
|
+
const findings = uiComponentRecommendations(cfg);
|
|
4106
|
+
console.error(`UI component findings (${findings.length})`);
|
|
4107
|
+
for (const finding of findings) {
|
|
4108
|
+
console.error(` [ERROR] ${finding.file}:${finding.line}:${finding.column} <${finding.element}> should use ${finding.variant ? `<${finding.component} variant="${finding.variant}">` : `<${finding.component}>`} (import from '${finding.import}') — ${finding.reason}`);
|
|
4109
|
+
}
|
|
4110
|
+
if (findings.length)
|
|
4111
|
+
process.exitCode = 1;
|
|
4112
|
+
return;
|
|
4113
|
+
}
|
|
4114
|
+
if (cmd === 'error-boundaries') {
|
|
4115
|
+
if (fix('errorBoundaries')) {
|
|
4116
|
+
const fixed = fixErrorBoundaries(scopedCfg(cfg, opts.all));
|
|
4117
|
+
if (fixed)
|
|
4118
|
+
console.info(`Error-boundary autofix: guarded React roots in ${fixed} file${fixed === 1 ? '' : 's'}.`);
|
|
4119
|
+
}
|
|
4120
|
+
const findings = errorBoundaryFindings(scopedCfg(cfg, opts.all));
|
|
4121
|
+
console.error(`React error-boundary findings (${findings.length})`);
|
|
4122
|
+
for (const finding of findings)
|
|
4123
|
+
console.error(` [ERROR] ${finding.file}:${finding.line}:${finding.column} ${finding.message}`);
|
|
4124
|
+
if (findings.length)
|
|
4125
|
+
process.exitCode = 1;
|
|
4126
|
+
return;
|
|
4127
|
+
}
|
|
4128
|
+
if (cfg.qualityCommands?.some(c => c.name === cmd)) {
|
|
4129
|
+
runCfgdCmd(cfg, cmd);
|
|
4130
|
+
return;
|
|
4131
|
+
}
|
|
4132
|
+
if (cmd === 'lint')
|
|
4133
|
+
return qualityCheckEnabled(cfg, 'lint') ? runLint(cfg, { ...opts, fix: fix('lint') }) : undefined;
|
|
4134
|
+
if (cmd === 'knip') {
|
|
4135
|
+
runDeadCodeCmd(cfg, qualityAutofixEnabled(cfg, 'dead-code', opts.fix), opts.all);
|
|
4136
|
+
return;
|
|
4137
|
+
}
|
|
4138
|
+
if (cmd === 'types') {
|
|
4139
|
+
if (!qualityCheckEnabled(cfg, 'type'))
|
|
4140
|
+
return;
|
|
4141
|
+
runTypecheck(cfg, opts.all ? [] : filesFor(cfg, false));
|
|
4142
|
+
if (cfg.typecheckExtensions?.length && !cfg.typecheckRoots?.length)
|
|
4143
|
+
runProjectTypecheck(cfg);
|
|
4144
|
+
return;
|
|
4145
|
+
}
|
|
4146
|
+
if (cmd === 'imports' || cmd === 'quality:patterns' || cmd === 'types:architecture') {
|
|
4147
|
+
runQuality(cfg, opts.strict, opts.all);
|
|
4148
|
+
return;
|
|
4149
|
+
}
|
|
4150
|
+
if (cmd === 'quality' || cmd === 'quality:all' || cmd === 'quality:baseline')
|
|
4151
|
+
return runFullQuality(cfg, args, opts);
|
|
4152
|
+
}
|
|
4153
|
+
// hygiene-ignore single-use -- Keep the documented acquireQualityLock declaration so its parameter and return contract remains attached.
|
|
4154
|
+
/**
|
|
4155
|
+
* Prevents two fixing runs from writing the same checkout at once.
|
|
4156
|
+
*
|
|
4157
|
+
* @param root Repository root to lock.
|
|
4158
|
+
*
|
|
4159
|
+
* @return A callback that releases the lock.
|
|
4160
|
+
*/
|
|
4161
|
+
function acquireQualityLock(root) {
|
|
4162
|
+
const lockDir = join(tmpdir(), `hygiene-${createHash('sha256').update(root).digest('hex').slice(0, 24)}.lock`);
|
|
4163
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
4164
|
+
try {
|
|
4165
|
+
mkdirSync(lockDir);
|
|
4166
|
+
writeFileSync(join(lockDir, 'pid'), String(process.pid));
|
|
4167
|
+
return () => {
|
|
4168
|
+
const ownerFile = join(lockDir, 'pid');
|
|
4169
|
+
if (existsSync(ownerFile) && readFileSync(ownerFile, 'utf8') === String(process.pid))
|
|
4170
|
+
rmSync(lockDir, { recursive: true, force: true });
|
|
4171
|
+
};
|
|
4172
|
+
}
|
|
4173
|
+
catch (err) {
|
|
4174
|
+
if (err.code !== 'EEXIST')
|
|
4175
|
+
throw err;
|
|
4176
|
+
let owner;
|
|
4177
|
+
try {
|
|
4178
|
+
owner = Number(readFileSync(join(lockDir, 'pid'), 'utf8'));
|
|
4179
|
+
if (owner > 0)
|
|
4180
|
+
process.kill(owner, 0);
|
|
4181
|
+
}
|
|
4182
|
+
catch (probe) {
|
|
4183
|
+
if (probe.code !== 'ESRCH')
|
|
4184
|
+
throw new Error(`Quality is already running for ${root}.`, { cause: probe });
|
|
4185
|
+
rmSync(lockDir, { recursive: true, force: true });
|
|
4186
|
+
continue;
|
|
4187
|
+
}
|
|
4188
|
+
throw new Error(`Quality is already running for ${root} (PID ${owner}).`, { cause: err });
|
|
4189
|
+
}
|
|
4190
|
+
}
|
|
4191
|
+
throw new Error(`Could not acquire the Quality lock for ${root}.`);
|
|
4192
|
+
}
|
|
4193
|
+
/**
|
|
4194
|
+
* Captures new parser errors and restores only files damaged by an autofix.
|
|
4195
|
+
*
|
|
4196
|
+
* @param cfg Quality configuration whose source files need protection.
|
|
4197
|
+
*
|
|
4198
|
+
* @return A callback that checks and restores damaged files.
|
|
4199
|
+
*/
|
|
4200
|
+
export function syntaxGuard(cfg) {
|
|
4201
|
+
const exts = /\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx)$/;
|
|
4202
|
+
const before = snapshotFiles(cfg, srcFiles(cfg).filter(path => exts.test(path)));
|
|
4203
|
+
const errs = (path, src) => {
|
|
4204
|
+
return ts.createSourceFile(path, src, ts.ScriptTarget.Latest, true, /\.tsx$/.test(path) ? ts.ScriptKind.TSX : /\.jsx$/.test(path) ? ts.ScriptKind.JSX : /\.[cm]?ts$/.test(path) ? ts.ScriptKind.TS : ts.ScriptKind.JS).parseDiagnostics.map(d => `${d.code}:${ts.flattenDiagnosticMessageText(d.messageText, ' ')}`);
|
|
4205
|
+
};
|
|
4206
|
+
return () => {
|
|
4207
|
+
for (const [path, orig] of before) {
|
|
4208
|
+
if (!existsSync(path))
|
|
4209
|
+
continue;
|
|
4210
|
+
const current = readFileSync(path, 'utf8');
|
|
4211
|
+
if (current === orig)
|
|
4212
|
+
continue;
|
|
4213
|
+
const prior = errs(path, orig);
|
|
4214
|
+
const introduced = errs(path, current).filter(msg => !prior.includes(msg));
|
|
4215
|
+
if (!introduced.length)
|
|
4216
|
+
continue;
|
|
4217
|
+
writeFileSync(path, orig);
|
|
4218
|
+
process.exitCode = 1;
|
|
4219
|
+
console.error(`Quality restored ${relative(cfg.root, path)} after an autofix introduced syntax errors: ${introduced.join('; ')}`);
|
|
4220
|
+
}
|
|
4221
|
+
};
|
|
4222
|
+
}
|
|
4223
|
+
/**
|
|
4224
|
+
* Loads the repository configuration and runs the CLI in one boundary call.
|
|
4225
|
+
*
|
|
4226
|
+
* @param file Optional path to the quality configuration file.
|
|
4227
|
+
* @param args CLI arguments passed to the dispatcher.
|
|
4228
|
+
*
|
|
4229
|
+
* @return A completion promise for asynchronous checks, or nothing for synchronous commands.
|
|
4230
|
+
*/
|
|
4231
|
+
export function runQualityFromCfg(file, args = process.argv.slice(2)) {
|
|
4232
|
+
validCliArgs(args);
|
|
4233
|
+
if (args.some(a => ['--version', '-v', '--help', '-h'].includes(a))) {
|
|
4234
|
+
runQualityCli({}, args);
|
|
4235
|
+
return;
|
|
4236
|
+
}
|
|
4237
|
+
const reportIdx = args.indexOf('--report-json');
|
|
4238
|
+
const cmd = args.find((a, i) => (reportIdx < 0 || i !== reportIdx + 1) && !a.startsWith('-')) ?? 'quality';
|
|
4239
|
+
if (cmd === 'history') {
|
|
4240
|
+
const reportPath = reportIdx < 0 ? undefined : args[reportIdx + 1];
|
|
4241
|
+
if (!reportPath)
|
|
4242
|
+
throw new Error('hygiene history requires --report-json <path>.');
|
|
4243
|
+
const branch = optVal(args, '--branch');
|
|
4244
|
+
const baseSha = optVal(args, '--base-sha');
|
|
4245
|
+
writeHistoryReport(process.cwd(), reportPath, { ...(branch ? { branch } : {}), ...(baseSha ? { baseSha } : {}) });
|
|
4246
|
+
return;
|
|
4247
|
+
}
|
|
4248
|
+
const cfg = loadQualityCfg(file);
|
|
4249
|
+
if (new Set(['quality', 'quality:all', 'quality:baseline', 'document', 'maintain', 'dead-code', 'knip', 'lint', 'naming', 'single-use']).has(cmd) && qualityCheckEnabled(cfg, 'lint')) {
|
|
4250
|
+
if (!findEslintConfig(cfg.root, cfg.configRoot))
|
|
4251
|
+
throw new Error(`ESLint flat config is required for ${cmd}. Add eslint.config.js, eslint.config.mjs, or eslint.config.ts at ${cfg.root} or ${cfg.configRoot ?? resolve(cfg.root, 'config')} before running Terra Quality.`);
|
|
4252
|
+
}
|
|
4253
|
+
if (args.includes('--warn')) {
|
|
4254
|
+
const result = runQualityCli(cfg, args);
|
|
4255
|
+
if (result instanceof Promise)
|
|
4256
|
+
return result.finally(() => {
|
|
4257
|
+
process.exitCode = 0;
|
|
4258
|
+
});
|
|
4259
|
+
process.exitCode = 0;
|
|
4260
|
+
return;
|
|
4261
|
+
}
|
|
4262
|
+
if (!new Set(['quality', 'quality:all', 'quality:baseline']).has(cmd))
|
|
4263
|
+
return runQualityCli(cfg, args);
|
|
4264
|
+
const release = acquireQualityLock(cfg.root);
|
|
4265
|
+
let valid;
|
|
4266
|
+
try {
|
|
4267
|
+
valid = syntaxGuard(cfg);
|
|
4268
|
+
const result = runQualityCli(cfg, args);
|
|
4269
|
+
const finish = () => {
|
|
4270
|
+
try {
|
|
4271
|
+
valid();
|
|
4272
|
+
}
|
|
4273
|
+
finally {
|
|
4274
|
+
release();
|
|
4275
|
+
}
|
|
4276
|
+
};
|
|
4277
|
+
if (result instanceof Promise)
|
|
4278
|
+
return result.finally(finish);
|
|
4279
|
+
finish();
|
|
4280
|
+
return;
|
|
4281
|
+
}
|
|
4282
|
+
catch (err) {
|
|
4283
|
+
release();
|
|
4284
|
+
throw err;
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
4287
|
+
/**
|
|
4288
|
+
* Reject unknown commands and flags before loading configuration or invoking a fixer.
|
|
4289
|
+
*
|
|
4290
|
+
* @param args CLI arguments to validate before configuration or source changes.
|
|
4291
|
+
*/
|
|
4292
|
+
function validCliArgs(args) {
|
|
4293
|
+
const reportIdx = args.indexOf('--report-json');
|
|
4294
|
+
if (reportIdx >= 0 && (!args[reportIdx + 1] || args[reportIdx + 1].startsWith('-') || args.lastIndexOf('--report-json') !== reportIdx))
|
|
4295
|
+
throw new Error('--report-json requires one output path.');
|
|
4296
|
+
for (const flag of ['--branch', '--base-sha', '--repository']) {
|
|
4297
|
+
const idx = args.indexOf(flag);
|
|
4298
|
+
if (flag === '--repository') {
|
|
4299
|
+
for (const occurrence of args.flatMap((a, i) => (a === flag ? [i] : []))) {
|
|
4300
|
+
if (!args[occurrence + 1] || args[occurrence + 1].startsWith('-'))
|
|
4301
|
+
throw new Error(`${flag} requires an owner/name value.`);
|
|
4302
|
+
}
|
|
4303
|
+
}
|
|
4304
|
+
else if (idx >= 0 && (!args[idx + 1] || args[idx + 1].startsWith('-') || args.lastIndexOf(flag) !== idx))
|
|
4305
|
+
throw new Error(`${flag} requires one value.`);
|
|
4306
|
+
}
|
|
4307
|
+
const cmdArgs = args.filter((_, i) => i !== reportIdx + 1 || reportIdx < 0);
|
|
4308
|
+
const cmd = cmdArgs.find(a => !a.startsWith('-')) ?? 'quality';
|
|
4309
|
+
const unknownFlags = cmdArgs.filter(a => a.startsWith('-') && !CLI_FLAGS.has(a));
|
|
4310
|
+
if (!CLI_CMDS.has(cmd) || unknownFlags.length)
|
|
4311
|
+
throw new Error(`Unknown quality CLI arguments: ${[...(!CLI_CMDS.has(cmd) ? [cmd] : []), ...unknownFlags].join(', ')}`);
|
|
4312
|
+
}
|
|
4313
|
+
/**
|
|
4314
|
+
* Read a single value following a validated CLI flag.
|
|
4315
|
+
*
|
|
4316
|
+
* @param args CLI arguments.
|
|
4317
|
+
* @param flag Flag whose following value is returned.
|
|
4318
|
+
*
|
|
4319
|
+
* @return The flag value, or undefined when the flag was not supplied.
|
|
4320
|
+
*/
|
|
4321
|
+
function optVal(args, flag) {
|
|
4322
|
+
const idx = args.indexOf(flag);
|
|
4323
|
+
return idx < 0 ? undefined : args[idx + 1];
|
|
4324
|
+
}
|
|
4325
|
+
/**
|
|
4326
|
+
* Runs Prettier after applying the quality package's safe structural formatting pass.
|
|
4327
|
+
*
|
|
4328
|
+
* @param cfg Quality configuration defining formatter, scope, and print-width settings.
|
|
4329
|
+
* @param optsOrArgs Typed options or legacy CLI-style arguments.
|
|
4330
|
+
* @param args Additional CLI arguments when typed options are supplied.
|
|
4331
|
+
*
|
|
4332
|
+
* @return Nothing; formatter failures are reflected in the process exit code.
|
|
4333
|
+
*/
|
|
4334
|
+
export function runFormatter(cfg, optsOrArgs = { fix: true, all: false, strict: false }, args = []) {
|
|
4335
|
+
const legacyArgs = Array.isArray(optsOrArgs);
|
|
4336
|
+
const opts = legacyArgs ? { fix: optsOrArgs.includes('--write') || !optsOrArgs.includes('--check'), all: optsOrArgs.includes('--all'), strict: false } : optsOrArgs;
|
|
4337
|
+
const suppliedArgs = (legacyArgs ? optsOrArgs : args).filter(a => !['--all', '--warn', '--fix', '--safe-fix', '--strict'].includes(a));
|
|
4338
|
+
const suppliedTgts = suppliedArgs.filter((a, i) => a !== 'warn' || suppliedArgs[i - 1] !== '--log-level').filter(a => !a.startsWith('-'));
|
|
4339
|
+
const authoredTargets = (targets) => targets.filter(target => {
|
|
4340
|
+
const file = resolve(cfg.root, target);
|
|
4341
|
+
return !existsSync(file) || !statSync(file).isFile() || !hasGeneratedSourceHeader(readFileSync(file, 'utf8'));
|
|
4342
|
+
});
|
|
4343
|
+
const fmtSuppliedTgts = suppliedTgts.flatMap(target => {
|
|
4344
|
+
if (/[?*{}[\]!]/u.test(target))
|
|
4345
|
+
return [target];
|
|
4346
|
+
const absolute = resolve(cfg.root, target);
|
|
4347
|
+
if (existsSync(absolute) && statSync(absolute).isDirectory())
|
|
4348
|
+
return authoredTargets(filesFor(cfg, opts.all).filter(file => resolve(file).startsWith(`${absolute}${sep}`)));
|
|
4349
|
+
return authoredTargets([target]);
|
|
4350
|
+
});
|
|
4351
|
+
const tgts = authoredTargets(fmtSuppliedTgts.length > 0 || suppliedTgts.length > 0 ? fmtSuppliedTgts : authoredTargets(filesFor(cfg, opts.all)));
|
|
4352
|
+
if (!tgts.length)
|
|
4353
|
+
return;
|
|
4354
|
+
const flags = [
|
|
4355
|
+
...(suppliedArgs.includes('--write') || suppliedArgs.includes('--check') ? [] : [opts.fix ? '--write' : '--check']),
|
|
4356
|
+
...(suppliedArgs.some(a => a.startsWith('--ignore-unknown')) ? [] : ['--ignore-unknown']),
|
|
4357
|
+
...(opts.fix && !(suppliedArgs.includes('--log-level') || suppliedArgs.some(a => a.startsWith('--log-level='))) ? ['--log-level=warn'] : []),
|
|
4358
|
+
...suppliedArgs.filter(arg => !suppliedTgts.includes(arg)),
|
|
4359
|
+
...tgts,
|
|
4360
|
+
].filter(a => a.startsWith('-'));
|
|
4361
|
+
qualityHeader('format', `${opts.fix ? 'Fixing' : 'Checking'} formatting in ${tgts.length} source files`);
|
|
4362
|
+
const before = opts.fix ? snapshotFiles(cfg, tgts) : undefined;
|
|
4363
|
+
const fmt = toolPath(cfg, cfg.tools?.prettier, 'prettier');
|
|
4364
|
+
if (opts.fix && spawnSync(fmt, ['--version'], { cwd: cfg.root, stdio: 'ignore', env: process.env }).status === 0) {
|
|
4365
|
+
// Explicit formatter targets are already the authoritative scope. Avoid
|
|
4366
|
+
// querying Git for a temporary/non-repository fixture when collapsing its
|
|
4367
|
+
// structural sources before Prettier.
|
|
4368
|
+
// Generated files stay out of Prettier and its structural rewrites.
|
|
4369
|
+
const knownFiles = (fmtSuppliedTgts.length ? srcFiles(cfg) : filesFor(cfg, opts.all)).filter(file => !hasGeneratedSourceHeader(readFileSync(file, 'utf8')));
|
|
4370
|
+
const directTgts = fmtSuppliedTgts.map(t => resolve(cfg.root, t));
|
|
4371
|
+
const collapseTgts = directTgts.length ? knownFiles.filter(f => directTgts.some(t => resolve(f) === t || resolve(f).startsWith(`${t}${sep}`))) : knownFiles;
|
|
4372
|
+
for (const file of collapseTgts) {
|
|
4373
|
+
if (!C_M_JS_TS_REGEX.test(file))
|
|
4374
|
+
continue;
|
|
4375
|
+
collapseInlineIfs(file);
|
|
4376
|
+
collapseTypesAndObjects(file);
|
|
4377
|
+
}
|
|
4378
|
+
}
|
|
4379
|
+
else if (opts.fix) {
|
|
4380
|
+
const message = 'Prettier is unavailable; skipped object and type compaction.';
|
|
4381
|
+
if (outputPhase)
|
|
4382
|
+
recordQualityDetail(message);
|
|
4383
|
+
else
|
|
4384
|
+
console.error(` ${message}`);
|
|
4385
|
+
}
|
|
4386
|
+
let failed = false;
|
|
4387
|
+
let completed = 0;
|
|
4388
|
+
qualityProgress('Prettier', completed, tgts.length);
|
|
4389
|
+
const prettierConfig = [
|
|
4390
|
+
'.prettierrc',
|
|
4391
|
+
'.prettierrc.json',
|
|
4392
|
+
'.prettierrc.yml',
|
|
4393
|
+
'.prettierrc.yaml',
|
|
4394
|
+
'.prettierrc.mjs',
|
|
4395
|
+
'.prettierrc.cjs',
|
|
4396
|
+
'prettier.config.js',
|
|
4397
|
+
'prettier.config.mjs',
|
|
4398
|
+
'prettier.config.cjs',
|
|
4399
|
+
]
|
|
4400
|
+
.flatMap(n => [resolve(cfg.configRoot ?? resolve(cfg.root, 'config'), n), resolve(cfg.root, n)])
|
|
4401
|
+
.find(p => existsSync(p));
|
|
4402
|
+
const prettierIgnore = [resolve(cfg.configRoot ?? resolve(cfg.root, 'config'), '.prettierignore'), resolve(cfg.root, '.prettierignore')].find(p => existsSync(p));
|
|
4403
|
+
const configArgs = [
|
|
4404
|
+
...(!flags.some(f => f === '--config' || f.startsWith('--config=')) && prettierConfig ? ['--config', prettierConfig] : []),
|
|
4405
|
+
...(!flags.some(f => f === '--ignore-path' || f.startsWith('--ignore-path=')) && prettierIgnore ? ['--ignore-path', prettierIgnore] : []),
|
|
4406
|
+
];
|
|
4407
|
+
const targetBatches = argBatches(tgts);
|
|
4408
|
+
for (const tgtBatch of targetBatches) {
|
|
4409
|
+
const status = run(cfg, fmt, [...flags, ...configArgs, ...tgtBatch], { quietSuccess: true });
|
|
4410
|
+
completed += tgtBatch.length;
|
|
4411
|
+
qualityProgress('Prettier', completed, tgts.length);
|
|
4412
|
+
if (status) {
|
|
4413
|
+
failed = true;
|
|
4414
|
+
process.exitCode = status;
|
|
4415
|
+
}
|
|
4416
|
+
}
|
|
4417
|
+
if (opts.fix && !failed && !flags.includes('--check')) {
|
|
4418
|
+
const checkFlags = [...flags.filter(flag => flag !== '--write'), '--check'];
|
|
4419
|
+
for (const tgtBatch of targetBatches) {
|
|
4420
|
+
const checkArgs = [...checkFlags, ...configArgs, ...tgtBatch];
|
|
4421
|
+
const check = spawnSync(fmt, checkArgs, { cwd: cfg.root, stdio: 'ignore', env: process.env, maxBuffer: TOOL_OUTPUT_MAX_BUFFER });
|
|
4422
|
+
if (!check.error && check.status === 0)
|
|
4423
|
+
continue;
|
|
4424
|
+
// Some Prettier plugins need a second write after structural transforms before output is stable.
|
|
4425
|
+
const retryStatus = run(cfg, fmt, [...flags, ...configArgs, ...tgtBatch], { quietSuccess: true });
|
|
4426
|
+
if (retryStatus) {
|
|
4427
|
+
failed = true;
|
|
4428
|
+
process.exitCode = retryStatus;
|
|
4429
|
+
continue;
|
|
4430
|
+
}
|
|
4431
|
+
const verifiedStatus = run(cfg, fmt, checkArgs, { quietSuccess: true });
|
|
4432
|
+
if (verifiedStatus) {
|
|
4433
|
+
failed = true;
|
|
4434
|
+
process.exitCode = verifiedStatus;
|
|
4435
|
+
}
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
4438
|
+
if (failed && before) {
|
|
4439
|
+
for (const [file, orig] of before) {
|
|
4440
|
+
const path = resolve(cfg.root, file);
|
|
4441
|
+
if (existsSync(path) && readFileSync(path, 'utf8') !== orig)
|
|
4442
|
+
writeFileSync(path, orig);
|
|
4443
|
+
}
|
|
4444
|
+
const message = 'Prettier failed; restored source files because formatting did not complete.';
|
|
4445
|
+
if (outputPhase)
|
|
4446
|
+
recordQualityDetail(message);
|
|
4447
|
+
else
|
|
4448
|
+
console.error(` ${message}`);
|
|
4449
|
+
}
|
|
4450
|
+
if (before && !outputPhase)
|
|
4451
|
+
console.error(` fixed ${changedFileCount(cfg, tgts, before)} files`);
|
|
4452
|
+
printCheckStatus('format', failed ? 1 : 0);
|
|
4453
|
+
}
|
|
4454
|
+
/**
|
|
4455
|
+
* Runs a configured TypeScript typecheck over either supplied files or the configured project.
|
|
4456
|
+
*
|
|
4457
|
+
* @param cfg Quality configuration containing compiler, root, and extension settings.
|
|
4458
|
+
* @param args Optional source files to typecheck in a scoped invocation.
|
|
4459
|
+
*
|
|
4460
|
+
* @return Nothing; compiler failures are reflected in the process exit code.
|
|
4461
|
+
*/
|
|
4462
|
+
export function runTypecheck(cfg, args = []) {
|
|
4463
|
+
if (cfg.typecheckCommand) {
|
|
4464
|
+
if (!args.length)
|
|
4465
|
+
runProjectTypecheck(cfg);
|
|
4466
|
+
return;
|
|
4467
|
+
}
|
|
4468
|
+
const tsc = cfg.tools?.tsc ?? 'tsc';
|
|
4469
|
+
// prettier-ignore
|
|
4470
|
+
const suppliedFiles = cfg.typecheckExtensions?.length
|
|
4471
|
+
? args.filter((f) => cfg.typecheckExtensions?.includes(f.slice(f.lastIndexOf('.'))) && (!cfg.typecheckRoots?.length || cfg.typecheckRoots.some((r) => f.startsWith(`${r}/`) || f.startsWith(`${r}\\`))))
|
|
4472
|
+
: args;
|
|
4473
|
+
if (args.length && !suppliedFiles.length)
|
|
4474
|
+
return;
|
|
4475
|
+
// prettier-ignore
|
|
4476
|
+
const typecheckFiles = cfg.typecheckExtensions?.length
|
|
4477
|
+
? srcFiles(cfg).filter((f) => cfg.typecheckExtensions?.includes(f.slice(f.lastIndexOf('.'))) && (!cfg.typecheckRoots?.length || cfg.typecheckRoots.some((r) => f.startsWith(`${r}/`) || f.startsWith(`${r}\\`))))
|
|
4478
|
+
: [];
|
|
4479
|
+
qualityHeader('typecheck', `Checking ${args.length ? 'the selected source files' : 'the configured TypeScript project'}`);
|
|
4480
|
+
const result = spawnSync(toolPath(cfg, tsc, 'tsc'), typecheckFiles.length
|
|
4481
|
+
? [
|
|
4482
|
+
'--noEmit',
|
|
4483
|
+
'--allowJs',
|
|
4484
|
+
'--checkJs',
|
|
4485
|
+
'--strict',
|
|
4486
|
+
'--skipLibCheck',
|
|
4487
|
+
'--module',
|
|
4488
|
+
'ESNext',
|
|
4489
|
+
'--moduleResolution',
|
|
4490
|
+
'Bundler',
|
|
4491
|
+
'--target',
|
|
4492
|
+
'ESNext',
|
|
4493
|
+
'--allowImportingTsExtensions',
|
|
4494
|
+
...(args.length ? suppliedFiles : typecheckFiles),
|
|
4495
|
+
]
|
|
4496
|
+
: ['--noEmit', '-p', projectTsconfig(cfg)], { cwd: cfg.root, stdio: ['inherit', 'pipe', 'pipe'], maxBuffer: TOOL_OUTPUT_MAX_BUFFER });
|
|
4497
|
+
const status = result.status ?? 1;
|
|
4498
|
+
if (status) {
|
|
4499
|
+
const output = [...compactOutput(result.stdout?.toString() ?? ''), ...compactOutput(result.stderr?.toString() ?? '')];
|
|
4500
|
+
if (outputPhase) {
|
|
4501
|
+
recordQualityDetail(`${toolPath(cfg, tsc, 'tsc')} failed (exit ${status})`);
|
|
4502
|
+
for (const line of output)
|
|
4503
|
+
recordQualityDetail(line);
|
|
4504
|
+
}
|
|
4505
|
+
else {
|
|
4506
|
+
printChildOutput(result.stdout);
|
|
4507
|
+
printChildOutput(result.stderr);
|
|
4508
|
+
}
|
|
4509
|
+
}
|
|
4510
|
+
if (status)
|
|
4511
|
+
process.exitCode = 1;
|
|
4512
|
+
printCheckStatus('typecheck', status ? 1 : 0);
|
|
4513
|
+
}
|
|
4514
|
+
if (process.argv[1] && realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url))) {
|
|
4515
|
+
setQualityProgressSuppressed(true);
|
|
4516
|
+
Promise.resolve(runQualityFromCfg()).catch((e) => {
|
|
4517
|
+
stopQualitySpinner();
|
|
4518
|
+
console.error(e instanceof Error ? e.message : e);
|
|
4519
|
+
process.exitCode = 1;
|
|
4520
|
+
});
|
|
4521
|
+
}
|
|
4522
|
+
//# sourceMappingURL=runner.js.map
|