@terra-symposium/hygiene 0.0.0-stage → 2.4.4
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,1584 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* packages/hygiene/src/capabilities/patterns/lib/patterns.ts
|
|
3
|
+
* Generic source-pattern checks: repeated static classes and forbidden UI patterns.
|
|
4
|
+
* Kept together because both are repository-wide text inventories.
|
|
5
|
+
*/
|
|
6
|
+
/*//////////////////////////////////////////////////
|
|
7
|
+
IMPORTS
|
|
8
|
+
//////////////////////////////////////////////////*/
|
|
9
|
+
// API
|
|
10
|
+
import ts from 'typescript';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
import { dirname, extname, isAbsolute, relative, resolve } from 'node:path';
|
|
13
|
+
import { createQualityAnalysis, displayPath, srcFiles } from '@terra-symposium/hygiene/core';
|
|
14
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { pathToFileURL } from 'node:url';
|
|
16
|
+
/**
|
|
17
|
+
* Matches TSDoc blocks so generated declarations can preserve authored comments.
|
|
18
|
+
*
|
|
19
|
+
* @return A fresh global regular expression for TSDoc block comments.
|
|
20
|
+
*/
|
|
21
|
+
const S_S_G_REGEX = () => /\/\*\*[\s\S]*?\*\//g;
|
|
22
|
+
const SHARED_REGEX = /[\\/]/;
|
|
23
|
+
/**
|
|
24
|
+
* Matches non-alphanumeric runs when deriving concise identifiers.
|
|
25
|
+
*
|
|
26
|
+
* @return A fresh regular expression for splitting non-alphanumeric runs.
|
|
27
|
+
*/
|
|
28
|
+
const A_ZA_Z0_9_G_REGEX = () => /[^A-Za-z0-9]+/g;
|
|
29
|
+
/**
|
|
30
|
+
* Matches leading and trailing underscores for identifier cleanup.
|
|
31
|
+
*
|
|
32
|
+
* @return A fresh regular expression for trimming underscores.
|
|
33
|
+
*/
|
|
34
|
+
const G_REGEX = () => /^_+|_+$/g;
|
|
35
|
+
/**
|
|
36
|
+
* Matches backslashes when escaping regular-expression text.
|
|
37
|
+
*
|
|
38
|
+
* @return A fresh regular expression for matching backslashes.
|
|
39
|
+
*/
|
|
40
|
+
const G_CLASS_2 = () => /\\/g;
|
|
41
|
+
/**
|
|
42
|
+
* Captures exported constant names when scanning source sections.
|
|
43
|
+
*
|
|
44
|
+
* @return A fresh multiline regular expression for exported constants.
|
|
45
|
+
*/
|
|
46
|
+
const EXPORT_CONST_A_ZA_Z_W_B_GM_REGEX = () => /^export const ([A-Za-z_$][\w$]*)\b/gm;
|
|
47
|
+
/**
|
|
48
|
+
* Matches whitespace runs when normalizing source text.
|
|
49
|
+
*
|
|
50
|
+
* @return A fresh regular expression for matching whitespace runs.
|
|
51
|
+
*/
|
|
52
|
+
const S_G_REGEX = () => /\s+/g;
|
|
53
|
+
const COLLECTION_CALLBACKS = new Set(['filter', 'flatMap', 'forEach', 'map', 'reduce', 'some']);
|
|
54
|
+
const REPEATED_LOOKUPS = new Set(['find', 'filter', 'includes', 'indexOf', 'some']);
|
|
55
|
+
/**
|
|
56
|
+
* Returns a stable receiver expression suitable for a manual indexing recommendation.
|
|
57
|
+
*
|
|
58
|
+
* @param node Expression whose receiver may be used in a recommendation.
|
|
59
|
+
*
|
|
60
|
+
* @return The receiver text for a simple identifier/property access, otherwise `undefined`.
|
|
61
|
+
*/
|
|
62
|
+
function stableReceiver(node) {
|
|
63
|
+
if (ts.isIdentifier(node))
|
|
64
|
+
return node.text;
|
|
65
|
+
if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression))
|
|
66
|
+
return node.getText();
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Confirms that a lookup receiver is statically an array or tuple.
|
|
71
|
+
*
|
|
72
|
+
* @param checker TypeScript checker used to resolve the receiver's value type.
|
|
73
|
+
* @param expr Receiver expression of the lookup call.
|
|
74
|
+
*
|
|
75
|
+
* @return Whether the receiver supports the array lookup semantics this rule targets.
|
|
76
|
+
*/
|
|
77
|
+
function isArrayLookupReceiver(checker, expr) {
|
|
78
|
+
const type = checker.getTypeAtLocation(expr);
|
|
79
|
+
if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
|
|
80
|
+
return false;
|
|
81
|
+
const members = type.isUnionOrIntersection() ? type.types : [type];
|
|
82
|
+
return members.length > 0 && members.every(member => checker.isArrayType(member) || checker.isTupleType(member));
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Finds the nearest enclosing function passed directly to a collection method.
|
|
86
|
+
*
|
|
87
|
+
* @param node AST node whose enclosing collection callback is being sought.
|
|
88
|
+
*
|
|
89
|
+
* @return The nearest collection call whose callback contains the node, if any.
|
|
90
|
+
*/
|
|
91
|
+
function collectionCallback(node) {
|
|
92
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
93
|
+
if (!ts.isFunctionLike(current))
|
|
94
|
+
continue;
|
|
95
|
+
const call = current.parent;
|
|
96
|
+
if (!ts.isCallExpression(call) || !call.arguments.includes(current))
|
|
97
|
+
continue;
|
|
98
|
+
const callee = call.expression;
|
|
99
|
+
if (ts.isPropertyAccessExpression(callee) && COLLECTION_CALLBACKS.has(callee.name.text))
|
|
100
|
+
return call;
|
|
101
|
+
}
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Reports repeated linear lookups nested in collection callbacks without changing source.
|
|
106
|
+
*
|
|
107
|
+
* @param cfg Quality configuration that selects source files and pattern options.
|
|
108
|
+
* @param analysis Optional shared source analysis to reuse while scanning.
|
|
109
|
+
*
|
|
110
|
+
* @return Repeated linear-lookup findings, with source locations and recommendations.
|
|
111
|
+
*/
|
|
112
|
+
export function performancePatternFindings(cfg, analysis) {
|
|
113
|
+
const settings = cfg.performancePatterns;
|
|
114
|
+
if (!settings)
|
|
115
|
+
return [];
|
|
116
|
+
const exts = new Set(settings.extensions ?? ['.js', '.jsx', '.ts', '.tsx']);
|
|
117
|
+
const ignoredFiles = new Set(settings.ignoredFiles ?? []);
|
|
118
|
+
const files = (analysis?.files ?? srcFiles({ ...cfg, extensions: [...exts] })).filter(f => exts.has(f.slice(f.lastIndexOf('.'))));
|
|
119
|
+
const checker = analysis?.checker ?? createQualityAnalysis({ ...cfg, extensions: [...exts] }).checker;
|
|
120
|
+
const findings = [];
|
|
121
|
+
for (const file of files) {
|
|
122
|
+
const display = displayPath(cfg, file);
|
|
123
|
+
if (ignoredFiles.has(display))
|
|
124
|
+
continue;
|
|
125
|
+
const src = analysis?.sources.get(file) ?? ts.createSourceFile(file, analysis?.texts.get(file) ?? readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true, regexScriptKind(file));
|
|
126
|
+
if (src.parseDiagnostics?.length)
|
|
127
|
+
continue;
|
|
128
|
+
/**
|
|
129
|
+
* Walks the parsed file to find nested linear lookups.
|
|
130
|
+
*
|
|
131
|
+
* @param node Current AST node in the source file.
|
|
132
|
+
*/
|
|
133
|
+
const visit = (node) => {
|
|
134
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && REPEATED_LOOKUPS.has(node.expression.name.text) && collectionCallback(node)) {
|
|
135
|
+
const receiver = stableReceiver(node.expression.expression);
|
|
136
|
+
if (receiver && isArrayLookupReceiver(checker, node.expression.expression)) {
|
|
137
|
+
const position = src.getLineAndCharacterOfPosition(node.getStart(src));
|
|
138
|
+
findings.push({
|
|
139
|
+
file: display,
|
|
140
|
+
line: position.line + 1,
|
|
141
|
+
column: position.character + 1,
|
|
142
|
+
method: node.expression.name.text,
|
|
143
|
+
receiver,
|
|
144
|
+
recommendation: `Consider precomputing a Map or Set for ${receiver} before this collection callback; measure the representative path before changing it.`,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
ts.forEachChild(node, visit);
|
|
149
|
+
};
|
|
150
|
+
visit(src);
|
|
151
|
+
}
|
|
152
|
+
return findings;
|
|
153
|
+
}
|
|
154
|
+
/*//////////////////////////////////////////////////
|
|
155
|
+
HELPERS
|
|
156
|
+
//////////////////////////////////////////////////*/
|
|
157
|
+
/**
|
|
158
|
+
* Reports repeated static class strings without assuming a framework.
|
|
159
|
+
*
|
|
160
|
+
* @param cfg Quality configuration defining the source roots and repeated-class policy.
|
|
161
|
+
* @param analysis Optional shared analysis context for reusing source text.
|
|
162
|
+
*
|
|
163
|
+
* @return Repeated static class strings that meet the configured minimum count.
|
|
164
|
+
*/
|
|
165
|
+
export function repeatedClassFindings(cfg, analysis) {
|
|
166
|
+
const settings = cfg.repeatedClasses ?? {};
|
|
167
|
+
const min = settings.minimumCount ?? 3;
|
|
168
|
+
const exts = new Set(settings.extensions ?? ['.astro', '.html', '.js', '.jsx', '.ts', '.tsx']);
|
|
169
|
+
const vals = new Map();
|
|
170
|
+
for (const file of (analysis?.files ?? srcFiles({ ...cfg, extensions: [...exts] })).filter(f => exts.has(f.slice(f.lastIndexOf('.'))))) {
|
|
171
|
+
const src = analysis?.texts.get(file) ?? readFileSync(file, 'utf8');
|
|
172
|
+
for (const { value, offset } of repeatedClassAttrs(src, file)) {
|
|
173
|
+
const val = value.replace(S_G_REGEX(), ' ').trim();
|
|
174
|
+
if (val.includes('{') || val.split(' ').length < 2)
|
|
175
|
+
continue;
|
|
176
|
+
vals.set(val, [...(vals.get(val) ?? []), `${displayPath(cfg, file)}:${src.slice(0, offset).split('\n').length}`]);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return [...vals.entries()].filter(([, l]) => l.length >= min).map(([v, l]) => ({ value: v, count: l.length, locations: l.sort((l, r) => l.localeCompare(r, undefined, { numeric: true })) }));
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Finds static class attributes in JSX/HTML syntax while excluding ordinary JavaScript strings.
|
|
183
|
+
*
|
|
184
|
+
* @param src Source text to inspect.
|
|
185
|
+
* @param file Filename used to select the source syntax.
|
|
186
|
+
*
|
|
187
|
+
* @return Static class values with their source offsets.
|
|
188
|
+
*/
|
|
189
|
+
function repeatedClassAttrs(src, file) {
|
|
190
|
+
if (file.endsWith('.html'))
|
|
191
|
+
return [...src.matchAll(/\b(class|className)(\s*=\s*)(['"])([^'"\n]+)\3/g)].map(match => ({ value: match[4], offset: match.index, text: match[0] }));
|
|
192
|
+
const source = ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
193
|
+
const attrs = [];
|
|
194
|
+
const visit = (node) => {
|
|
195
|
+
if (ts.isJsxAttribute(node) && ts.isIdentifier(node.name) && (node.name.text === 'class' || node.name.text === 'className') && node.initializer && ts.isStringLiteral(node.initializer))
|
|
196
|
+
attrs.push({ value: node.initializer.text, offset: node.getStart(source), text: node.getText(source) });
|
|
197
|
+
ts.forEachChild(node, visit);
|
|
198
|
+
};
|
|
199
|
+
visit(source);
|
|
200
|
+
return attrs;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Converts a static class string into a stable, collision-resistant constant identifier.
|
|
204
|
+
*
|
|
205
|
+
* @param val Normalized class string being named.
|
|
206
|
+
* @param used Identifiers already present in the file.
|
|
207
|
+
*
|
|
208
|
+
* @return Upper-case identifier suitable for a generated class constant.
|
|
209
|
+
*/
|
|
210
|
+
function classConstName(val, used) {
|
|
211
|
+
let name = `${val
|
|
212
|
+
.split(/\s+/)
|
|
213
|
+
.map(t => t.replace(A_ZA_Z0_9_G_REGEX(), '_').replace(G_REGEX(), ''))
|
|
214
|
+
.filter(Boolean)
|
|
215
|
+
.join('_') || 'SHARED'}_CLASS`.toUpperCase();
|
|
216
|
+
if (/^\d/.test(name))
|
|
217
|
+
name = `CLASS_${name}`;
|
|
218
|
+
if (name.length > 80)
|
|
219
|
+
name = `${name.slice(0, 70)}_${Math.abs([...val].reduce((n, c) => (n * 31 + c.charCodeAt(0)) | 0, 0))
|
|
220
|
+
.toString(36)
|
|
221
|
+
.toUpperCase()}`;
|
|
222
|
+
let suffix = 2;
|
|
223
|
+
while (used.has(name))
|
|
224
|
+
name = `${name}_${suffix++}`;
|
|
225
|
+
used.add(name);
|
|
226
|
+
return name;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Determines whether a source offset is inside a JavaScript template literal.
|
|
230
|
+
* Template-generated markup is data, so replacing its class text with a source
|
|
231
|
+
* identifier would change the generated markup rather than reference a value.
|
|
232
|
+
*
|
|
233
|
+
* @param src Source text containing the candidate match.
|
|
234
|
+
* @param offset Candidate offset in the source text.
|
|
235
|
+
*
|
|
236
|
+
* @return Whether the offset is enclosed by an unescaped backtick.
|
|
237
|
+
*/
|
|
238
|
+
function isInsideTemplateLiteral(src, offset) {
|
|
239
|
+
let open = false;
|
|
240
|
+
for (let i = 0; i < offset; i++) {
|
|
241
|
+
if (src[i] !== '`' || (i > 0 && src[i - 1] === '\\'))
|
|
242
|
+
continue;
|
|
243
|
+
open = !open;
|
|
244
|
+
}
|
|
245
|
+
return open;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Inserts generated declarations at a CONFIG boundary or after the import group.
|
|
249
|
+
*
|
|
250
|
+
* @param src Source text to update.
|
|
251
|
+
* @param declarations Constant declarations to insert.
|
|
252
|
+
* @param file Optional source filename used to preserve its syntax and formatting conventions.
|
|
253
|
+
*
|
|
254
|
+
* @return Source text containing the declarations, or the original source when insertion is unsupported.
|
|
255
|
+
*/
|
|
256
|
+
function insertGenDeclarations(src, declarations, file) {
|
|
257
|
+
if (!declarations.length)
|
|
258
|
+
return src;
|
|
259
|
+
const cfgPattern = /\/\*\/{10,}\r?\n[ \t]*CONFIG[ \t]*\r?\n[ \t]*\/{10,}\*\//g;
|
|
260
|
+
let cfg = null;
|
|
261
|
+
for (let match = cfgPattern.exec(src); match; match = cfgPattern.exec(src)) {
|
|
262
|
+
if (!isInsideTemplateLiteral(src, match.index)) {
|
|
263
|
+
cfg = match;
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const eol = src.includes('\r\n') ? '\r\n' : '\n';
|
|
268
|
+
const gen = declarations.join(eol);
|
|
269
|
+
if (cfg) {
|
|
270
|
+
const at = cfg.index + cfg[0].length;
|
|
271
|
+
return `${src.slice(0, at)}${eol}${gen}${eol}${src.slice(at)}`;
|
|
272
|
+
}
|
|
273
|
+
// Add generated constants only to JavaScript-family sources, after imports
|
|
274
|
+
// and directive prologues so module and directive semantics remain unchanged.
|
|
275
|
+
if (!file || file.endsWith('.html'))
|
|
276
|
+
return src;
|
|
277
|
+
if (file.endsWith('.astro')) {
|
|
278
|
+
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(src);
|
|
279
|
+
if (frontmatter) {
|
|
280
|
+
const at = frontmatter[0].lastIndexOf('---');
|
|
281
|
+
return `${src.slice(0, at)}${gen}${eol}${src.slice(at)}`;
|
|
282
|
+
}
|
|
283
|
+
return `---${eol}${gen}${eol}---${eol}${src}`;
|
|
284
|
+
}
|
|
285
|
+
const ast = ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
286
|
+
let at = 0;
|
|
287
|
+
for (const statement of ast.statements) {
|
|
288
|
+
if (ts.isImportDeclaration(statement) || (ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)))
|
|
289
|
+
at = statement.end;
|
|
290
|
+
else
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
return `${src.slice(0, at)}${at ? eol : ''}${gen}${eol}${src.slice(at)}`;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Writes a generated JavaScript-family update only after TypeScript accepts its syntax.
|
|
297
|
+
* Astro files are validated structurally by the narrowly scoped attribute edits instead.
|
|
298
|
+
*
|
|
299
|
+
* @param file Source file to update.
|
|
300
|
+
* @param src Candidate source text.
|
|
301
|
+
*
|
|
302
|
+
* @return `true` when the candidate was written.
|
|
303
|
+
*/
|
|
304
|
+
function writePatternSrc(file, src) {
|
|
305
|
+
if (!file.endsWith('.astro')) {
|
|
306
|
+
if (ts.transpileModule(src, { fileName: file, reportDiagnostics: true, compilerOptions: { allowJs: true, jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext } }).diagnostics?.length)
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
writeFileSync(file, src);
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Replaces repeated static class attributes with file-local constants in the CONFIG/CLASSES group.
|
|
314
|
+
* Dynamic expressions, HTML files, and files without an existing CONFIG boundary are left unchanged.
|
|
315
|
+
*
|
|
316
|
+
* @param cfg Quality configuration defining the class threshold and source scope.
|
|
317
|
+
* @param analysis Optional shared analysis context used for discovery.
|
|
318
|
+
*
|
|
319
|
+
* @return Counts of replacements made and candidates left unchanged for safety.
|
|
320
|
+
*/
|
|
321
|
+
export function fixRepeatedClasses(cfg, analysis) {
|
|
322
|
+
const settings = cfg.repeatedClasses ?? {};
|
|
323
|
+
const min = settings.minimumCount ?? 3;
|
|
324
|
+
const exts = new Set(settings.extensions ?? ['.astro', '.html', '.js', '.jsx', '.ts', '.tsx']);
|
|
325
|
+
let fixed = 0;
|
|
326
|
+
let skipped = 0;
|
|
327
|
+
for (const file of analysis?.files ?? srcFiles({ ...cfg, extensions: [...exts] })) {
|
|
328
|
+
if (!exts.has(file.slice(file.lastIndexOf('.'))))
|
|
329
|
+
continue;
|
|
330
|
+
if (file.endsWith('.html'))
|
|
331
|
+
continue;
|
|
332
|
+
const src = analysis?.texts.get(file) ?? readFileSync(file, 'utf8');
|
|
333
|
+
const matches = repeatedClassAttrs(src, file).flatMap(({ value, offset, text }) => {
|
|
334
|
+
const match = /^(class|className)(\s*=\s*)(['"])([^\n]*)\3$/.exec(text);
|
|
335
|
+
if (!match || match[4] !== value)
|
|
336
|
+
return [];
|
|
337
|
+
return [{ match: Object.assign(match, { index: offset }), value: value.replace(S_G_REGEX(), ' ').trim() }];
|
|
338
|
+
});
|
|
339
|
+
const groups = new Map();
|
|
340
|
+
for (const entry of matches)
|
|
341
|
+
if (!entry.value.includes('{') && entry.value.split(' ').length >= 2)
|
|
342
|
+
groups.set(entry.value, [...(groups.get(entry.value) ?? []), entry]);
|
|
343
|
+
const candidates = [...groups.entries()].filter(([, e]) => e.length >= min);
|
|
344
|
+
if (!candidates.length)
|
|
345
|
+
continue;
|
|
346
|
+
const used = new Set();
|
|
347
|
+
(analysis?.sources.get(file) ?? ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)).forEachChild(n => {
|
|
348
|
+
if (!ts.isVariableStatement(n))
|
|
349
|
+
return;
|
|
350
|
+
for (const declaration of n.declarationList.declarations)
|
|
351
|
+
if (ts.isIdentifier(declaration.name))
|
|
352
|
+
used.add(declaration.name.text);
|
|
353
|
+
});
|
|
354
|
+
const declarations = [];
|
|
355
|
+
const edits = [];
|
|
356
|
+
for (const [val, entries] of candidates) {
|
|
357
|
+
const name = classConstName(val, used);
|
|
358
|
+
declarations.push(`const ${name} = '${val.replace(G_CLASS_2(), '\\\\').replace(/'/g, "\\'")}';`);
|
|
359
|
+
for (const { match } of entries)
|
|
360
|
+
edits.push({ start: match.index, end: match.index + match[0].length, replacement: `${match[1]}${match[2]}{${name}}` });
|
|
361
|
+
fixed += entries.length;
|
|
362
|
+
}
|
|
363
|
+
let updated = src;
|
|
364
|
+
for (const edit of edits.sort((a, b) => b.start - a.start))
|
|
365
|
+
updated = `${updated.slice(0, edit.start)}${edit.replacement}${updated.slice(edit.end)}`;
|
|
366
|
+
const withGroup = insertGenDeclarations(updated, declarations, file);
|
|
367
|
+
const candidateCount = candidates.reduce((n, [, e]) => n + e.length, 0);
|
|
368
|
+
if (withGroup === updated) {
|
|
369
|
+
fixed -= candidateCount;
|
|
370
|
+
skipped += candidateCount;
|
|
371
|
+
}
|
|
372
|
+
else if (!writePatternSrc(file, withGroup)) {
|
|
373
|
+
fixed -= candidateCount;
|
|
374
|
+
skipped += candidateCount;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return { fixed, skipped };
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Reports configured UI patterns that should use a shared primitive.
|
|
381
|
+
*
|
|
382
|
+
* @param cfg Quality configuration defining forbidden UI patterns and source scope.
|
|
383
|
+
* @param analysis Optional shared analysis context for reusing discovered files and text.
|
|
384
|
+
*
|
|
385
|
+
* @return Matching file/pattern pairs that should use shared UI primitives.
|
|
386
|
+
*/
|
|
387
|
+
export function uiPatternFindings(cfg, analysis) {
|
|
388
|
+
const settings = cfg.uiPatterns ?? {};
|
|
389
|
+
const patterns = (settings.forbidden ?? []).map(p => [p, new RegExp(p, 'm')]);
|
|
390
|
+
const exts = settings.extensions ?? ['.astro', '.html', '.jsx', '.tsx'];
|
|
391
|
+
return (analysis?.files ?? srcFiles({ ...cfg, extensions: exts }))
|
|
392
|
+
.filter(f => exts.includes(f.slice(f.lastIndexOf('.'))))
|
|
393
|
+
.flatMap(f => {
|
|
394
|
+
const name = displayPath(cfg, f);
|
|
395
|
+
const src = analysis?.texts.get(f) ?? readFileSync(f, 'utf8');
|
|
396
|
+
return patterns.filter(([, p]) => p.test(src)).map(([p]) => ({ file: name, pattern: p }));
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
/*//////////////////////////////////////////////////
|
|
400
|
+
TAILWIND
|
|
401
|
+
//////////////////////////////////////////////////*/
|
|
402
|
+
// hygiene-ignore single-use -- Keep the documented resolveTailwindNodeImport declaration so its parameter and return contract remains attached.
|
|
403
|
+
/**
|
|
404
|
+
* Resolves Tailwind's Node runtime from the consumer's installed integration.
|
|
405
|
+
*
|
|
406
|
+
* @param consumerRequire CommonJS resolver rooted at the consumer package.
|
|
407
|
+
* @param root Repository root whose dependency tree should be searched.
|
|
408
|
+
* @param stylesheetPath Configured stylesheet whose workspace dependencies should also be searched.
|
|
409
|
+
*
|
|
410
|
+
* @return Absolute path to Tailwind's Node runtime entry.
|
|
411
|
+
*/
|
|
412
|
+
function resolveTailwindNodeImport(consumerRequire, root, stylesheetPath) {
|
|
413
|
+
const stylesheetDir = dirname(stylesheetPath);
|
|
414
|
+
const paths = [root, resolve(root, 'astro'), stylesheetDir, resolve(stylesheetDir, '..')];
|
|
415
|
+
try {
|
|
416
|
+
return consumerRequire.resolve('tailwindcss', { paths });
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
// Try the v4 Node runtime exposed by the installed integration below.
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
return consumerRequire.resolve('@tailwindcss/node', { paths });
|
|
423
|
+
}
|
|
424
|
+
catch {
|
|
425
|
+
// The Node runtime is usually a transitive dependency of the selected v4 integration.
|
|
426
|
+
}
|
|
427
|
+
for (const integration of ['@tailwindcss/postcss', '@tailwindcss/vite', '@tailwindcss/cli']) {
|
|
428
|
+
try {
|
|
429
|
+
return createRequire(consumerRequire.resolve(integration, { paths })).resolve('@tailwindcss/node');
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
// Try the next supported Tailwind integration.
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
throw new Error('Tailwind v4 Node runtime could not be resolved from the consumer repository.');
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Runs the Tailwind v4 canonical-class diagnostic used by the quality CLI.
|
|
439
|
+
*
|
|
440
|
+
* @param cfg Quality configuration containing the Tailwind stylesheet and source roots.
|
|
441
|
+
* @param fix Whether canonical replacements should be written to source files.
|
|
442
|
+
* @param output Optional callbacks and quiet-mode control for diagnostic reporting.
|
|
443
|
+
*
|
|
444
|
+
* @return Promise resolving to zero after diagnostics or fixes complete.
|
|
445
|
+
*/
|
|
446
|
+
export async function runTailwindCanonical(cfg, fix = false, output = {}) {
|
|
447
|
+
if (!cfg.tailwindCanonical)
|
|
448
|
+
return 0;
|
|
449
|
+
const stylesheetPath = resolve(cfg.root, cfg.tailwindCanonical.stylesheet);
|
|
450
|
+
if (!existsSync(stylesheetPath))
|
|
451
|
+
throw new Error(`Tailwind stylesheet not found: ${stylesheetPath}`);
|
|
452
|
+
const consumerRequire = createRequire(resolve(cfg.root, 'package.json'));
|
|
453
|
+
let tailwind;
|
|
454
|
+
try {
|
|
455
|
+
tailwind = (await import(pathToFileURL(resolveTailwindNodeImport(consumerRequire, cfg.root, stylesheetPath)).href));
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
throw new Error('Tailwind canonical check could not load the consumer repository Tailwind v4 Node runtime.');
|
|
459
|
+
}
|
|
460
|
+
if (!tailwind.__unstable__loadDesignSystem) {
|
|
461
|
+
output.onSkip?.();
|
|
462
|
+
if (!output.quiet)
|
|
463
|
+
console.info('Tailwind canonical check skipped: installed Tailwind does not expose v4 canonical-class diagnostics.');
|
|
464
|
+
return 0;
|
|
465
|
+
}
|
|
466
|
+
const designSystem = await tailwind.__unstable__loadDesignSystem(readFileSync(stylesheetPath, 'utf8'), {
|
|
467
|
+
base: dirname(stylesheetPath),
|
|
468
|
+
from: stylesheetPath,
|
|
469
|
+
loadStylesheet: async (id, base) => {
|
|
470
|
+
let importedPath = resolve(base, id);
|
|
471
|
+
if (!existsSync(importedPath)) {
|
|
472
|
+
try {
|
|
473
|
+
importedPath = consumerRequire.resolve(id, { paths: [base, cfg.root, resolve(cfg.root, 'astro'), dirname(stylesheetPath), resolve(dirname(stylesheetPath), '..')] });
|
|
474
|
+
}
|
|
475
|
+
catch {
|
|
476
|
+
throw new Error(`Tailwind stylesheet import not found: ${id}`);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return { base: dirname(importedPath), content: readFileSync(importedPath, 'utf8'), path: importedPath };
|
|
480
|
+
},
|
|
481
|
+
});
|
|
482
|
+
const lengthInPixels = (value) => {
|
|
483
|
+
const match = /^(-?\d+(?:\.\d+)?)(px|rem)$/.exec(value);
|
|
484
|
+
if (!match)
|
|
485
|
+
return undefined;
|
|
486
|
+
const amount = Number(match[1]);
|
|
487
|
+
return match[2] === 'rem' ? amount * 16 : amount;
|
|
488
|
+
};
|
|
489
|
+
const spacing = designSystem.resolveThemeValue?.('--spacing');
|
|
490
|
+
const spacingInPixels = spacing ? lengthInPixels(spacing) : undefined;
|
|
491
|
+
const spacingSuggestions = new Map();
|
|
492
|
+
const spacingSuggestion = (orig) => {
|
|
493
|
+
if (spacingSuggestions.has(orig))
|
|
494
|
+
return spacingSuggestions.get(orig);
|
|
495
|
+
const arbitrary = /^(?<utility>.+)-\[(?<value>-?\d+(?:\.\d+)?(?:px|rem))\](?<important>!)?$/.exec(orig);
|
|
496
|
+
const valueInPixels = arbitrary?.groups?.value ? lengthInPixels(arbitrary.groups.value) : undefined;
|
|
497
|
+
const ratio = valueInPixels !== undefined && spacingInPixels ? valueInPixels / spacingInPixels : undefined;
|
|
498
|
+
if (!arbitrary?.groups?.utility || valueInPixels === undefined || valueInPixels <= 0 || !spacingInPixels || !ratio || !Number.isInteger(ratio) || !designSystem.candidatesToAst) {
|
|
499
|
+
spacingSuggestions.set(orig, undefined);
|
|
500
|
+
return undefined;
|
|
501
|
+
}
|
|
502
|
+
const proposal = `${arbitrary.groups.utility}-${ratio}${arbitrary.groups.important ?? ''}`;
|
|
503
|
+
const declarations = (candidate) => {
|
|
504
|
+
const found = [];
|
|
505
|
+
const collect = (node) => {
|
|
506
|
+
if (Array.isArray(node)) {
|
|
507
|
+
for (const child of node)
|
|
508
|
+
collect(child);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (!node || typeof node !== 'object')
|
|
512
|
+
return;
|
|
513
|
+
const record = node;
|
|
514
|
+
if (record.kind === 'declaration' && typeof record.property === 'string' && typeof record.value === 'string') {
|
|
515
|
+
found.push({ property: record.property, value: record.value, important: record.important === true });
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
if (Array.isArray(record.nodes))
|
|
519
|
+
collect(record.nodes);
|
|
520
|
+
};
|
|
521
|
+
collect(designSystem.candidatesToAst?.([candidate]));
|
|
522
|
+
return found;
|
|
523
|
+
};
|
|
524
|
+
const before = declarations(orig);
|
|
525
|
+
const after = declarations(proposal);
|
|
526
|
+
const replacement = before.length > 0 &&
|
|
527
|
+
before.length === after.length &&
|
|
528
|
+
before.every((d, i) => {
|
|
529
|
+
const replacement = after[i];
|
|
530
|
+
if (!replacement || d.property !== replacement.property || d.important !== replacement.important)
|
|
531
|
+
return false;
|
|
532
|
+
const pixels = lengthInPixels(d.value);
|
|
533
|
+
if (pixels === undefined)
|
|
534
|
+
return d.value === replacement.value;
|
|
535
|
+
const spacingScale = /^calc\(var\(--spacing\)\s\*\s*(-?\d+(?:\.\d+)?)\)$/.exec(replacement.value);
|
|
536
|
+
return spacingScale !== null && Math.abs(Number(spacingScale[1]) * spacingInPixels - pixels) < 0.0001;
|
|
537
|
+
})
|
|
538
|
+
? proposal
|
|
539
|
+
: undefined;
|
|
540
|
+
spacingSuggestions.set(orig, replacement);
|
|
541
|
+
return replacement;
|
|
542
|
+
};
|
|
543
|
+
const files = srcFiles(cfg.tailwindCanonical.sourceRoots ? { ...cfg, sourceRoots: cfg.tailwindCanonical.sourceRoots.map(r => resolve(cfg.root, r)) } : cfg).filter(f => /\.(?:astro|cjs|js|jsx|mjs|ts|tsx)$/.test(f));
|
|
544
|
+
const findings = [];
|
|
545
|
+
for (const file of files) {
|
|
546
|
+
const source = readFileSync(file, 'utf8');
|
|
547
|
+
for (const val of (function classVals(src) {
|
|
548
|
+
const vals = [];
|
|
549
|
+
const attrPattern = /\b(?:class|className)\s*=\s*(?:(['"])([\s\S]*?)\1|\{\s*`([\s\S]*?)`\s*\})/g;
|
|
550
|
+
for (const match of src.matchAll(attrPattern)) {
|
|
551
|
+
const value = match[2] ?? match[3] ?? '';
|
|
552
|
+
const valStart = match.index + match[0].indexOf(value);
|
|
553
|
+
let segmentStart = 0;
|
|
554
|
+
for (const interpolation of value.matchAll(/\$\{[\s\S]*?\}/g)) {
|
|
555
|
+
if (interpolation.index > segmentStart)
|
|
556
|
+
vals.push({ start: valStart + segmentStart, value: value.slice(segmentStart, interpolation.index) });
|
|
557
|
+
segmentStart = interpolation.index + interpolation[0].length;
|
|
558
|
+
}
|
|
559
|
+
if (segmentStart < value.length)
|
|
560
|
+
vals.push({ start: valStart + segmentStart, value: value.slice(segmentStart) });
|
|
561
|
+
}
|
|
562
|
+
const callPattern = /\b(?:cn|clsx|classnames|cva)\s*\(/g;
|
|
563
|
+
for (const call of src.matchAll(callPattern)) {
|
|
564
|
+
let depth = 1;
|
|
565
|
+
let cursor = call.index + call[0].length;
|
|
566
|
+
while (cursor < src.length && depth > 0) {
|
|
567
|
+
if (src[cursor] === '(')
|
|
568
|
+
depth += 1;
|
|
569
|
+
if (src[cursor] === ')')
|
|
570
|
+
depth -= 1;
|
|
571
|
+
cursor += 1;
|
|
572
|
+
}
|
|
573
|
+
const bodyStart = call.index + call[0].length;
|
|
574
|
+
for (const value of src.slice(bodyStart, cursor - 1).matchAll(/(['"`])([\s\S]*?)\1/g))
|
|
575
|
+
if (!value[2].includes('${'))
|
|
576
|
+
vals.push({ start: bodyStart + value.index + 1, value: value[2] });
|
|
577
|
+
}
|
|
578
|
+
return vals;
|
|
579
|
+
})(source)) {
|
|
580
|
+
for (const token of val.value.matchAll(/\S+/g)) {
|
|
581
|
+
const orig = token[0];
|
|
582
|
+
const canonical = designSystem.canonicalizeCandidates([orig])[0];
|
|
583
|
+
const replacement = canonical && canonical !== orig ? canonical : spacingSuggestion(orig);
|
|
584
|
+
if (!replacement || replacement === orig || replacement.includes(' '))
|
|
585
|
+
continue;
|
|
586
|
+
const start = val.start + token.index;
|
|
587
|
+
findings.push({
|
|
588
|
+
file,
|
|
589
|
+
start,
|
|
590
|
+
end: start + orig.length,
|
|
591
|
+
original: orig,
|
|
592
|
+
replacement,
|
|
593
|
+
...(function locationAt(src, offset) {
|
|
594
|
+
const before = src.slice(0, offset);
|
|
595
|
+
return { line: before.split('\n').length, column: offset - before.lastIndexOf('\n') };
|
|
596
|
+
})(source, start),
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
const uniqueFindings = findings.filter((f, i, a) => a.findIndex(c => c.file === f.file && c.start === f.start && c.original === f.original) === i);
|
|
602
|
+
if (fix) {
|
|
603
|
+
for (const file of new Set(uniqueFindings.map(f => f.file))) {
|
|
604
|
+
let source = readFileSync(file, 'utf8');
|
|
605
|
+
for (const finding of uniqueFindings.filter(c => c.file === file).sort((l, r) => r.start - l.start))
|
|
606
|
+
source = `${source.slice(0, finding.start)}${finding.replacement}${source.slice(finding.end)}`;
|
|
607
|
+
writeFileSync(file, source);
|
|
608
|
+
}
|
|
609
|
+
if (!output.quiet)
|
|
610
|
+
console.info(`Tailwind canonical classes fixed: ${uniqueFindings.length}`);
|
|
611
|
+
return 0;
|
|
612
|
+
}
|
|
613
|
+
for (const finding of uniqueFindings) {
|
|
614
|
+
const message = `${relative(cfg.root, finding.file)}:${finding.line}:${finding.column} ${finding.original} -> ${finding.replacement}`;
|
|
615
|
+
if (output.onFinding)
|
|
616
|
+
output.onFinding(message);
|
|
617
|
+
else
|
|
618
|
+
console.error(message);
|
|
619
|
+
}
|
|
620
|
+
if (uniqueFindings.length)
|
|
621
|
+
throw new Error(`Tailwind canonical class check failed with ${uniqueFindings.length} suggestion${uniqueFindings.length === 1 ? '' : 's'}.`);
|
|
622
|
+
if (!output.quiet)
|
|
623
|
+
console.info(`Tailwind canonical class check passed: ${files.length} source files scanned.`);
|
|
624
|
+
return 0;
|
|
625
|
+
}
|
|
626
|
+
const REGEX_REGISTRY_MARKER = '// Generated by @terra-symposium/hygiene regex-dedup. Do not edit.';
|
|
627
|
+
const REGEX_DECLARATION_MARKER = '// Generated by @terra-symposium/hygiene regex-dedup. Do not edit.';
|
|
628
|
+
/**
|
|
629
|
+
* Checks whether a generated-file marker appears before any source content.
|
|
630
|
+
*
|
|
631
|
+
* @param src File contents to inspect.
|
|
632
|
+
* @param marker Expected generated-file marker.
|
|
633
|
+
*
|
|
634
|
+
* @return Whether only leading comments and whitespace precede the marker.
|
|
635
|
+
*/
|
|
636
|
+
function hasLeadingGenMarker(src, marker) {
|
|
637
|
+
let cursor = src.startsWith('\uFEFF') ? 1 : 0;
|
|
638
|
+
while (cursor < src.length) {
|
|
639
|
+
while (/\s/u.test(src[cursor] ?? ''))
|
|
640
|
+
cursor++;
|
|
641
|
+
if (src.startsWith(marker, cursor))
|
|
642
|
+
return true;
|
|
643
|
+
if (!src.startsWith('/*', cursor) && !src.startsWith('//', cursor))
|
|
644
|
+
return false;
|
|
645
|
+
const block = src.startsWith('/*', cursor);
|
|
646
|
+
const end = block ? src.indexOf('*/', cursor + 2) : src.indexOf('\n', cursor + 2);
|
|
647
|
+
if (end < 0)
|
|
648
|
+
return false;
|
|
649
|
+
cursor = block ? end + 2 : end + 1;
|
|
650
|
+
}
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
// hygiene-ignore single-use -- Keep the documented genFilePrefix declaration so its parameter and return contract remains attached.
|
|
654
|
+
/**
|
|
655
|
+
* Preserves the generated marker and any leading file documentation.
|
|
656
|
+
*
|
|
657
|
+
* @param src Existing generated-file contents.
|
|
658
|
+
* @param marker Expected generated-file marker.
|
|
659
|
+
*
|
|
660
|
+
* @return The preserved leading documentation and marker as a newline-terminated prefix.
|
|
661
|
+
*/
|
|
662
|
+
function genFilePrefix(src, marker) {
|
|
663
|
+
const markerIndex = src.indexOf(marker);
|
|
664
|
+
if (markerIndex < 0)
|
|
665
|
+
return `${marker}\n`;
|
|
666
|
+
const leadingDocumentation = src.slice(0, markerIndex);
|
|
667
|
+
return `${leadingDocumentation}${leadingDocumentation && !leadingDocumentation.endsWith('\n') ? '\n' : ''}${marker}\n`;
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Selects the TypeScript parser mode for the given source extension.
|
|
671
|
+
*
|
|
672
|
+
* @param file Source filename used to identify JavaScript, JSX, or TypeScript syntax.
|
|
673
|
+
*
|
|
674
|
+
* @return The matching TypeScript compiler script kind.
|
|
675
|
+
*/
|
|
676
|
+
function regexScriptKind(file) {
|
|
677
|
+
if (/\.tsx$/.test(file))
|
|
678
|
+
return ts.ScriptKind.TSX;
|
|
679
|
+
if (/\.jsx$/.test(file))
|
|
680
|
+
return ts.ScriptKind.JSX;
|
|
681
|
+
return /\.(?:mjs|cjs|js)$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Collects the supported literal and static-constructor candidates used by both reporting and fixing.
|
|
685
|
+
*
|
|
686
|
+
* @param cfg Quality configuration defining the regex source scope.
|
|
687
|
+
* @param analysis Optional shared analysis context for reusing source text and ASTs.
|
|
688
|
+
*
|
|
689
|
+
* @return Regex candidates with exact source keys and source locations.
|
|
690
|
+
*/
|
|
691
|
+
function regexCandidates(cfg, analysis) {
|
|
692
|
+
const settings = cfg.regexDedup ?? {};
|
|
693
|
+
const exts = new Set(settings.extensions ?? ['.js', '.jsx', '.mjs', '.ts', '.tsx', '.mts', '.cts']);
|
|
694
|
+
const registryPath = settings.sharedModule ? resolve(cfg.root, settings.sharedModule) : '';
|
|
695
|
+
const skippedDirs = (settings.skippedDirectories ?? []).map(d => resolve(cfg.root, d));
|
|
696
|
+
const candidates = [];
|
|
697
|
+
for (const discoveredFile of analysis?.files ?? srcFiles({ ...cfg, extensions: [...exts] })) {
|
|
698
|
+
const file = resolve(discoveredFile);
|
|
699
|
+
if (!exts.has(file.slice(file.lastIndexOf('.'))) ||
|
|
700
|
+
file.endsWith('.d.mts') ||
|
|
701
|
+
(registryPath && file === registryPath) ||
|
|
702
|
+
skippedDirs.some(d => {
|
|
703
|
+
const relativePath = relative(d, file);
|
|
704
|
+
return relativePath === '' || (!relativePath.startsWith('..') && !isAbsolute(relativePath));
|
|
705
|
+
}))
|
|
706
|
+
continue;
|
|
707
|
+
const ast = analysis?.sources.get(discoveredFile) ??
|
|
708
|
+
analysis?.sources.get(file) ??
|
|
709
|
+
ts.createSourceFile(file, analysis?.texts.get(discoveredFile) ?? analysis?.texts.get(file) ?? readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true, regexScriptKind(file));
|
|
710
|
+
// hygiene-ignore single-use -- Analyze RegExp shadowing once before the AST visitor checks each candidate.
|
|
711
|
+
const shadowedRegExp = hasRegExpBinding(ast);
|
|
712
|
+
/**
|
|
713
|
+
* Collects regex literals and supported `RegExp` constructions from the file.
|
|
714
|
+
*
|
|
715
|
+
* @param node Current AST node being inspected.
|
|
716
|
+
*/
|
|
717
|
+
const visit = (node) => {
|
|
718
|
+
if (ts.isRegularExpressionLiteral(node) && !isGenLocalRegex(node) && !isInlineTestRegex(cfg, file, node)) {
|
|
719
|
+
const literal = node.getText(ast);
|
|
720
|
+
const end = literal.lastIndexOf('/');
|
|
721
|
+
const pattern = literal.slice(1, end);
|
|
722
|
+
const flags = literal.slice(end + 1);
|
|
723
|
+
candidates.push({ file, source: flags ? `${pattern}/${flags}` : pattern, expression: literal, node, ast, rewritable: true });
|
|
724
|
+
}
|
|
725
|
+
else if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'RegExp' && !node.typeArguments?.length && !isInlineTestRegex(cfg, file, node)) {
|
|
726
|
+
const [pattern, flags, ...rest] = node.arguments ?? [];
|
|
727
|
+
if (!rest.length && (ts.isStringLiteral(pattern) || ts.isNoSubstitutionTemplateLiteral(pattern)) && (!flags || ts.isStringLiteral(flags))) {
|
|
728
|
+
candidates.push({ file, source: flags ? `${pattern.getText(ast)}, ${flags.getText(ast)}` : pattern.getText(ast), expression: node.getText(ast), node, ast, rewritable: !shadowedRegExp });
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
ts.forEachChild(node, visit);
|
|
732
|
+
};
|
|
733
|
+
visit(ast);
|
|
734
|
+
}
|
|
735
|
+
return candidates;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Checks whether a regex in a test source is an inline matcher or fixture expression.
|
|
739
|
+
*
|
|
740
|
+
* Moving one-off test expressions into the application-wide regex registry makes assertions harder to read
|
|
741
|
+
* without reducing duplicated runtime behavior. Named regex bindings remain candidates so shared reusable
|
|
742
|
+
* test patterns still receive the same deduplication analysis as production patterns.
|
|
743
|
+
*
|
|
744
|
+
* @param cfg Quality configuration defining the repository root.
|
|
745
|
+
* @param file Source file containing the regex expression.
|
|
746
|
+
* @param node Regex literal or static `RegExp` construction to classify.
|
|
747
|
+
*
|
|
748
|
+
* @return Whether this is an inline regex expression in a test source file.
|
|
749
|
+
*/
|
|
750
|
+
function isInlineTestRegex(cfg, file, node) {
|
|
751
|
+
if (!/(?:^|\/)(?:test|tests|__tests__)(?:\/|$)|\.(?:test|spec)\.[cm]?[jt]sx?$/.test(relative(cfg.root, file).replaceAll('\\', '/')))
|
|
752
|
+
return false;
|
|
753
|
+
const parent = node.parent;
|
|
754
|
+
return !(ts.isVariableDeclaration(parent) && parent.initializer === node) && !(ts.isPropertyDeclaration(parent) && parent.initializer === node);
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Checks whether a regex literal belongs to a generated local `_REGEX` declaration.
|
|
758
|
+
*
|
|
759
|
+
* @param node Regular-expression literal to classify.
|
|
760
|
+
*
|
|
761
|
+
* @return Whether the literal initializes a generated local regex constant.
|
|
762
|
+
*/
|
|
763
|
+
function isGenLocalRegex(node) {
|
|
764
|
+
let declaration;
|
|
765
|
+
for (let curr = node; curr && !ts.isSourceFile(curr); curr = curr.parent) {
|
|
766
|
+
if (ts.isVariableDeclaration(curr)) {
|
|
767
|
+
declaration = curr;
|
|
768
|
+
break;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
if (!declaration || !declaration.initializer || !ts.isIdentifier(declaration.name) || !declaration.name.text.endsWith('_REGEX'))
|
|
772
|
+
return false;
|
|
773
|
+
return declaration.initializer === node || (ts.isArrowFunction(declaration.initializer) && declaration.initializer.body === node);
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Detects bindings that shadow the global `RegExp` constructor.
|
|
777
|
+
*
|
|
778
|
+
* @param ast Parsed source file to inspect.
|
|
779
|
+
*
|
|
780
|
+
* @return Whether the file declares, imports, or catches a binding named `RegExp`.
|
|
781
|
+
*/
|
|
782
|
+
function hasRegExpBinding(ast) {
|
|
783
|
+
/**
|
|
784
|
+
* Checks whether a binding pattern contains a `RegExp` name.
|
|
785
|
+
*
|
|
786
|
+
* @param name Binding name, including nested destructuring patterns.
|
|
787
|
+
*
|
|
788
|
+
* @return Whether any bound identifier is named `RegExp`.
|
|
789
|
+
*/
|
|
790
|
+
const bindingHasRegExp = (name) => {
|
|
791
|
+
if (ts.isIdentifier(name))
|
|
792
|
+
return name.text === 'RegExp';
|
|
793
|
+
return name.elements.some(e => ts.isBindingElement(e) && bindingHasRegExp(e.name));
|
|
794
|
+
};
|
|
795
|
+
let found = false;
|
|
796
|
+
/**
|
|
797
|
+
* Searches declarations and imports for a binding that shadows global `RegExp`.
|
|
798
|
+
*
|
|
799
|
+
* @param node Current AST node being inspected.
|
|
800
|
+
*/
|
|
801
|
+
const visit = (node) => {
|
|
802
|
+
if (found)
|
|
803
|
+
return;
|
|
804
|
+
if ((ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node)) &&
|
|
805
|
+
node.name &&
|
|
806
|
+
bindingHasRegExp(node.name)) {
|
|
807
|
+
found = true;
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
if (ts.isImportClause(node) && node.name?.text === 'RegExp')
|
|
811
|
+
found = true;
|
|
812
|
+
if (ts.isImportSpecifier(node) && node.name.text === 'RegExp')
|
|
813
|
+
found = true;
|
|
814
|
+
if (ts.isCatchClause(node) && node.variableDeclaration && bindingHasRegExp(node.variableDeclaration.name))
|
|
815
|
+
found = true;
|
|
816
|
+
ts.forEachChild(node, visit);
|
|
817
|
+
};
|
|
818
|
+
visit(ast);
|
|
819
|
+
return found;
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Groups parsed regex candidates by their exact source representation.
|
|
823
|
+
*
|
|
824
|
+
* @param cfg Quality configuration defining source roots and extensions.
|
|
825
|
+
* @param analysis Optional shared analysis context for reusing parsed sources.
|
|
826
|
+
*
|
|
827
|
+
* @return Candidate groups keyed by regex source and flags.
|
|
828
|
+
*/
|
|
829
|
+
function regexGroups(cfg, analysis) {
|
|
830
|
+
const groups = new Map();
|
|
831
|
+
for (const candidate of regexCandidates(cfg, analysis))
|
|
832
|
+
groups.set(candidate.source, [...(groups.get(candidate.source) ?? []), candidate]);
|
|
833
|
+
return groups;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Reports exact duplicate regular-expression sources across source files.
|
|
837
|
+
*
|
|
838
|
+
* @param cfg Quality configuration defining regex extensions and threshold.
|
|
839
|
+
* @param analysis Optional shared analysis context for reusing source text and ASTs.
|
|
840
|
+
*
|
|
841
|
+
* @return Duplicate regular-expression sources and their source locations.
|
|
842
|
+
*/
|
|
843
|
+
export function regexFindings(cfg, analysis) {
|
|
844
|
+
const min = cfg.regexDedup?.minimumCount ?? 2;
|
|
845
|
+
return [...regexGroups(cfg, analysis)]
|
|
846
|
+
.filter(([, c]) => c.length >= min)
|
|
847
|
+
.map(([s, c]) => ({
|
|
848
|
+
source: s,
|
|
849
|
+
count: c.length,
|
|
850
|
+
locations: c
|
|
851
|
+
.map(({ file: f, ast: a, node: n }) => `${displayPath(cfg, f)}:${a.getLineAndCharacterOfPosition(n.getStart(a)).line + 1}`)
|
|
852
|
+
.sort((l, r) => l.localeCompare(r, undefined, { numeric: true })),
|
|
853
|
+
}));
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* Determines whether a consumer file uses ECMAScript module syntax.
|
|
857
|
+
*
|
|
858
|
+
* @param cfg Quality configuration defining the repository root.
|
|
859
|
+
* @param file Consumer source filename whose nearest package metadata is inspected.
|
|
860
|
+
*
|
|
861
|
+
* @return Whether the file is an ESM consumer.
|
|
862
|
+
*/
|
|
863
|
+
function isEsmConsumer(cfg, file) {
|
|
864
|
+
if (/\.(?:mjs|mts)$/.test(file))
|
|
865
|
+
return true;
|
|
866
|
+
if (/\.(?:cjs|cts)$/.test(file))
|
|
867
|
+
return false;
|
|
868
|
+
for (let dir = dirname(file); dir.startsWith(cfg.root); dir = dirname(dir)) {
|
|
869
|
+
const packageFile = resolve(dir, 'package.json');
|
|
870
|
+
if (existsSync(packageFile)) {
|
|
871
|
+
try {
|
|
872
|
+
return JSON.parse(readFileSync(packageFile, 'utf8')).type === 'module';
|
|
873
|
+
}
|
|
874
|
+
catch {
|
|
875
|
+
return false;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (dir === cfg.root)
|
|
879
|
+
break;
|
|
880
|
+
}
|
|
881
|
+
return false;
|
|
882
|
+
}
|
|
883
|
+
// hygiene-ignore single-use -- Keep the documented readRegexRegistry declaration so its parameter and return contract remains attached.
|
|
884
|
+
/**
|
|
885
|
+
* Reads the generated shared-regex registry when both files are owned by this tool.
|
|
886
|
+
*
|
|
887
|
+
* @param modulePath Shared ECMAScript module path.
|
|
888
|
+
* @param declarationPath TypeScript declaration path paired with the module.
|
|
889
|
+
*
|
|
890
|
+
* @return Parsed registry state, or `null` when an existing file is user-owned.
|
|
891
|
+
*/
|
|
892
|
+
function readRegexRegistry(modulePath, declarationPath) {
|
|
893
|
+
const moduleExists = existsSync(modulePath);
|
|
894
|
+
const declarationExists = existsSync(declarationPath);
|
|
895
|
+
const module = moduleExists ? readFileSync(modulePath, 'utf8') : `${REGEX_REGISTRY_MARKER}\n`;
|
|
896
|
+
const declaration = declarationExists ? readFileSync(declarationPath, 'utf8') : `${REGEX_DECLARATION_MARKER}\n`;
|
|
897
|
+
const owned = hasLeadingGenMarker(module, REGEX_REGISTRY_MARKER) && hasLeadingGenMarker(declaration, REGEX_DECLARATION_MARKER);
|
|
898
|
+
if ((moduleExists || declarationExists) && !owned)
|
|
899
|
+
return null;
|
|
900
|
+
const keys = new Map();
|
|
901
|
+
const ast = ts.createSourceFile(modulePath, module, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
|
902
|
+
for (const statement of ast.statements) {
|
|
903
|
+
const entry = regexRegistryEntry(module, statement);
|
|
904
|
+
if (entry)
|
|
905
|
+
keys.set(entry.key, entry.name);
|
|
906
|
+
}
|
|
907
|
+
return { module, declaration, names: new Set([...module.matchAll(EXPORT_CONST_A_ZA_Z_W_B_GM_REGEX())].map(m => m[1])), keys, owned };
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Returns the key and export name attached to one generated registry declaration.
|
|
911
|
+
*
|
|
912
|
+
* @param src Registry module source.
|
|
913
|
+
* @param s Export statement to inspect.
|
|
914
|
+
*
|
|
915
|
+
* @return Generated metadata when the statement has a valid registry key.
|
|
916
|
+
*/
|
|
917
|
+
function regexRegistryEntry(src, s) {
|
|
918
|
+
if (!ts.isVariableStatement(s) || !s.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) || s.declarationList.declarations.length !== 1)
|
|
919
|
+
return;
|
|
920
|
+
const declaration = s.declarationList.declarations[0];
|
|
921
|
+
if (!ts.isIdentifier(declaration.name))
|
|
922
|
+
return;
|
|
923
|
+
const annotation = [...src.slice(s.getFullStart(), s.getStart()).matchAll(/^\/\/ @hygiene-regex-key (.+)$/gm)].at(-1);
|
|
924
|
+
if (annotation?.index === undefined)
|
|
925
|
+
return;
|
|
926
|
+
try {
|
|
927
|
+
const key = JSON.parse(annotation[1]);
|
|
928
|
+
return typeof key === 'string' ? { key, name: declaration.name.text, annotationStart: s.getFullStart() + annotation.index } : undefined;
|
|
929
|
+
}
|
|
930
|
+
catch {
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Resolves a local or configured alias import to the shared regex module path.
|
|
936
|
+
*
|
|
937
|
+
* @param cfg Quality configuration containing the alias map and repository root.
|
|
938
|
+
* @param importer Absolute path of the file containing the import.
|
|
939
|
+
* @param specifier Import specifier to resolve.
|
|
940
|
+
* @param modulePath Absolute path of the shared regex module.
|
|
941
|
+
*
|
|
942
|
+
* @return Whether the import resolves to the shared regex module.
|
|
943
|
+
*/
|
|
944
|
+
function resolvesRegexModule(cfg, importer, specifier, modulePath) {
|
|
945
|
+
const alias = Object.entries(cfg.aliases ?? {})
|
|
946
|
+
.sort(([left], [right]) => right.length - left.length)
|
|
947
|
+
.find(([prefix]) => specifier.startsWith(prefix));
|
|
948
|
+
const importedPath = alias ? resolve(cfg.root, alias[1], specifier.slice(alias[0].length)) : specifier.startsWith('.') ? resolve(dirname(importer), specifier) : undefined;
|
|
949
|
+
if (!importedPath)
|
|
950
|
+
return false;
|
|
951
|
+
const normImport = resolve(importedPath);
|
|
952
|
+
const normModule = resolve(modulePath);
|
|
953
|
+
return normImport === normModule || (!extname(normImport) && `${normImport}.mjs` === normModule);
|
|
954
|
+
}
|
|
955
|
+
// hygiene-ignore single-use -- Keep the documented referencedRegexExports declaration so its parameter and return contract remains attached.
|
|
956
|
+
/**
|
|
957
|
+
* Finds keyed registry exports that source files reference, conservatively retaining dynamic uses.
|
|
958
|
+
*
|
|
959
|
+
* @param cfg Quality configuration defining the source scope and regex extensions.
|
|
960
|
+
* @param modulePath Absolute shared-registry path.
|
|
961
|
+
* @param names Registry export names eligible for pruning.
|
|
962
|
+
* @param analysis Optional parsed-source context to reuse.
|
|
963
|
+
*
|
|
964
|
+
* @return Names that are referenced or may be used dynamically.
|
|
965
|
+
*/
|
|
966
|
+
function referencedRegexExports(cfg, modulePath, names, analysis) {
|
|
967
|
+
const referenced = new Set();
|
|
968
|
+
const exts = cfg.regexDedup?.extensions ?? ['.js', '.jsx', '.mjs', '.ts', '.tsx', '.mts', '.cts'];
|
|
969
|
+
// A changed-file run narrows cfg.sourceRoots to changed paths. Registry exports
|
|
970
|
+
// can still be used by any unchanged source in the repository.
|
|
971
|
+
for (const discoveredFile of srcFiles({ ...cfg, sourceRoots: [cfg.root], includeRoots: [], extensions: exts })) {
|
|
972
|
+
const file = resolve(discoveredFile);
|
|
973
|
+
if (file === modulePath || file.endsWith('.d.mts'))
|
|
974
|
+
continue;
|
|
975
|
+
const ast = analysis?.sources.get(discoveredFile) ??
|
|
976
|
+
analysis?.sources.get(file) ??
|
|
977
|
+
ts.createSourceFile(file, analysis?.texts.get(discoveredFile) ?? analysis?.texts.get(file) ?? readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true, regexScriptKind(file));
|
|
978
|
+
const namespaces = new Set();
|
|
979
|
+
for (const s of ast.statements) {
|
|
980
|
+
if (!(ts.isImportDeclaration(s) || ts.isExportDeclaration(s)) ||
|
|
981
|
+
!s.moduleSpecifier ||
|
|
982
|
+
!ts.isStringLiteral(s.moduleSpecifier) ||
|
|
983
|
+
!resolvesRegexModule(cfg, file, s.moduleSpecifier.text, modulePath))
|
|
984
|
+
continue;
|
|
985
|
+
if (ts.isExportDeclaration(s))
|
|
986
|
+
for (const name of names)
|
|
987
|
+
referenced.add(name);
|
|
988
|
+
else if (s.importClause?.namedBindings && ts.isNamespaceImport(s.importClause.namedBindings))
|
|
989
|
+
namespaces.add(s.importClause.namedBindings.name.text);
|
|
990
|
+
else if (s.importClause?.namedBindings && ts.isNamedImports(s.importClause.namedBindings))
|
|
991
|
+
for (const specifier of s.importClause.namedBindings.elements) {
|
|
992
|
+
const imported = (specifier.propertyName ?? specifier.name).text;
|
|
993
|
+
if (names.has(imported))
|
|
994
|
+
referenced.add(imported);
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
const visit = (node) => {
|
|
998
|
+
if (ts.isCallExpression(node) &&
|
|
999
|
+
(node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
|
|
1000
|
+
node.arguments[0] &&
|
|
1001
|
+
ts.isStringLiteralLike(node.arguments[0]) &&
|
|
1002
|
+
resolvesRegexModule(cfg, file, node.arguments[0].text, modulePath))
|
|
1003
|
+
for (const name of names)
|
|
1004
|
+
referenced.add(name);
|
|
1005
|
+
if (ts.isIdentifier(node) && namespaces.has(node.text) && !ts.isImportClause(node.parent) && !ts.isNamespaceImport(node.parent)) {
|
|
1006
|
+
const parent = node.parent;
|
|
1007
|
+
if (ts.isPropertyAccessExpression(parent) && parent.expression === node) {
|
|
1008
|
+
if (names.has(parent.name.text))
|
|
1009
|
+
referenced.add(parent.name.text);
|
|
1010
|
+
}
|
|
1011
|
+
else if (ts.isElementAccessExpression(parent) && parent.expression === node) {
|
|
1012
|
+
const arg = parent.argumentExpression;
|
|
1013
|
+
if (arg && ts.isStringLiteralLike(arg) && names.has(arg.text))
|
|
1014
|
+
referenced.add(arg.text);
|
|
1015
|
+
else
|
|
1016
|
+
for (const name of names)
|
|
1017
|
+
referenced.add(name);
|
|
1018
|
+
}
|
|
1019
|
+
else
|
|
1020
|
+
for (const name of names)
|
|
1021
|
+
referenced.add(name);
|
|
1022
|
+
}
|
|
1023
|
+
ts.forEachChild(node, visit);
|
|
1024
|
+
};
|
|
1025
|
+
visit(ast);
|
|
1026
|
+
}
|
|
1027
|
+
return referenced;
|
|
1028
|
+
}
|
|
1029
|
+
// hygiene-ignore single-use -- Keep the documented pruneUnusedRegexExports declaration so its parameter and return contract remains attached.
|
|
1030
|
+
/**
|
|
1031
|
+
* Removes only keyed generated declarations with no source references.
|
|
1032
|
+
*
|
|
1033
|
+
* @param src Generated registry module source.
|
|
1034
|
+
* @param unusedNames Keyed export names proven to have no references.
|
|
1035
|
+
*
|
|
1036
|
+
* @return Updated registry module source.
|
|
1037
|
+
*/
|
|
1038
|
+
function pruneUnusedRegexExports(src, unusedNames) {
|
|
1039
|
+
if (!unusedNames.size)
|
|
1040
|
+
return src;
|
|
1041
|
+
const removals = ts.createSourceFile('regex.mjs', src, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS).statements.flatMap(s => {
|
|
1042
|
+
const entry = regexRegistryEntry(src, s);
|
|
1043
|
+
return entry && unusedNames.has(entry.name) ? [{ start: entry.annotationStart, end: s.end }] : [];
|
|
1044
|
+
});
|
|
1045
|
+
let updated = src;
|
|
1046
|
+
for (const removal of removals.sort((l, r) => r.start - l.start))
|
|
1047
|
+
updated = `${updated.slice(0, removal.start)}${updated.slice(removal.end)}`;
|
|
1048
|
+
return updated;
|
|
1049
|
+
}
|
|
1050
|
+
// hygiene-ignore single-use -- Keep the documented pruneUnusedRegexBindings declaration so its parameter and return contract remains attached.
|
|
1051
|
+
/**
|
|
1052
|
+
* Removes unreferenced declarations left by earlier generated-registry formats.
|
|
1053
|
+
*
|
|
1054
|
+
* @param src Generated registry module source.
|
|
1055
|
+
* @param referencedNames Export names used by consumers or new replacements.
|
|
1056
|
+
*
|
|
1057
|
+
* @return Registry source containing only live generated regular-expression factories.
|
|
1058
|
+
*/
|
|
1059
|
+
function pruneUnusedRegexBindings(src, referencedNames) {
|
|
1060
|
+
const ast = ts.createSourceFile('regex.mjs', src, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
|
1061
|
+
const declarations = new Map();
|
|
1062
|
+
for (const statement of ast.statements) {
|
|
1063
|
+
if (!ts.isVariableStatement(statement))
|
|
1064
|
+
continue;
|
|
1065
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
1066
|
+
if (!ts.isIdentifier(declaration.name) || !/^REGEX_.*_REGEX(?:_\d+)?$/u.test(declaration.name.text) || !declaration.initializer)
|
|
1067
|
+
continue;
|
|
1068
|
+
const leading = src.slice(statement.getFullStart(), statement.getStart(ast));
|
|
1069
|
+
const metadataStart = [...leading.matchAll(/^\/\/ @hygiene-regex-key .+$/gm)].at(-1)?.index;
|
|
1070
|
+
const documentationStart = [...leading.matchAll(S_S_G_REGEX())].at(-1)?.index;
|
|
1071
|
+
const markerIndex = leading.indexOf(REGEX_REGISTRY_MARKER);
|
|
1072
|
+
declarations.set(declaration.name.text, [
|
|
1073
|
+
...(declarations.get(declaration.name.text) ?? []),
|
|
1074
|
+
{
|
|
1075
|
+
statement,
|
|
1076
|
+
initializer: declaration.initializer,
|
|
1077
|
+
start: metadataStart !== undefined
|
|
1078
|
+
? statement.getFullStart() + metadataStart
|
|
1079
|
+
: documentationStart !== undefined && statement.getFullStart() + documentationStart >= (markerIndex < 0 ? -1 : markerIndex + REGEX_REGISTRY_MARKER.length)
|
|
1080
|
+
? statement.getFullStart() + documentationStart
|
|
1081
|
+
: statement.getStart(ast),
|
|
1082
|
+
exported: Boolean(statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)),
|
|
1083
|
+
},
|
|
1084
|
+
]);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
if (!declarations.size)
|
|
1088
|
+
return src;
|
|
1089
|
+
const live = new Set([...referencedNames].filter(name => declarations.has(name)));
|
|
1090
|
+
const dependencies = new Map();
|
|
1091
|
+
for (const [name, entries] of declarations) {
|
|
1092
|
+
const used = new Set();
|
|
1093
|
+
const visit = (node) => {
|
|
1094
|
+
if (ts.isIdentifier(node) && declarations.has(node.text))
|
|
1095
|
+
used.add(node.text);
|
|
1096
|
+
ts.forEachChild(node, visit);
|
|
1097
|
+
};
|
|
1098
|
+
for (const { initializer: init } of entries)
|
|
1099
|
+
visit(init);
|
|
1100
|
+
dependencies.set(name, used);
|
|
1101
|
+
}
|
|
1102
|
+
for (const statement of ast.statements) {
|
|
1103
|
+
if (ts.isVariableStatement(statement) && statement.declarationList.declarations.every(declaration => ts.isIdentifier(declaration.name) && declarations.has(declaration.name.text)))
|
|
1104
|
+
continue;
|
|
1105
|
+
const visit = (node) => {
|
|
1106
|
+
if (ts.isIdentifier(node) && declarations.has(node.text))
|
|
1107
|
+
live.add(node.text);
|
|
1108
|
+
ts.forEachChild(node, visit);
|
|
1109
|
+
};
|
|
1110
|
+
visit(statement);
|
|
1111
|
+
}
|
|
1112
|
+
const pending = [...live];
|
|
1113
|
+
while (pending.length) {
|
|
1114
|
+
const name = pending.pop();
|
|
1115
|
+
for (const dependency of dependencies.get(name) ?? []) {
|
|
1116
|
+
if (live.has(dependency))
|
|
1117
|
+
continue;
|
|
1118
|
+
live.add(dependency);
|
|
1119
|
+
pending.push(dependency);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
const removals = [...declarations].flatMap(([name, entries]) => entries.flatMap(entry => ((entries.some(candidate => candidate.exported) && !entry.exported) || !live.has(name) ? [{ start: entry.start, end: entry.statement.end }] : [])));
|
|
1123
|
+
let updated = src;
|
|
1124
|
+
for (const removal of removals.sort((left, right) => right.start - left.start))
|
|
1125
|
+
updated = `${updated.slice(0, removal.start)}${updated.slice(removal.end)}`;
|
|
1126
|
+
return updated;
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* Removes the stock return sentence used by older regex-registry generators.
|
|
1130
|
+
*
|
|
1131
|
+
* @param src Generated TSDoc or registry source.
|
|
1132
|
+
*
|
|
1133
|
+
* @return Source without templated return documentation.
|
|
1134
|
+
*/
|
|
1135
|
+
function removeTemplateRegexReturnDocs(src) {
|
|
1136
|
+
return src.replace(/^[ \t]*\* @return A fresh RegExp instance so each caller owns its match state\.\r?\n/gm, '').replace(/\r?\n[ \t]*\*[ \t]*\r?\n([ \t]*\*\/)/g, '\n$1');
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Removes empty TSDoc blocks emitted by older regex-registry generators.
|
|
1140
|
+
*
|
|
1141
|
+
* @param src Generated registry or declaration source.
|
|
1142
|
+
*
|
|
1143
|
+
* @return Source without empty documentation comments.
|
|
1144
|
+
*/
|
|
1145
|
+
function removeEmptyRegexDocs(src) {
|
|
1146
|
+
return src.replace(/\/\*\*(?:\r?\n[ \t]*\*[ \t]*)*\r?\n[ \t]*\*\//g, '');
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* Carries an agent-authored comment directly attached to a regex declaration into the shared registry.
|
|
1150
|
+
*
|
|
1151
|
+
* @param candidate Regex source expression and its parsed source file.
|
|
1152
|
+
*
|
|
1153
|
+
* @return The nearest directly attached variable or property TSDoc, if the source provides one.
|
|
1154
|
+
*/
|
|
1155
|
+
function regexCandidateDocumentation(candidate) {
|
|
1156
|
+
let statement;
|
|
1157
|
+
for (let node = candidate.node.parent; node && !ts.isSourceFile(node); node = node.parent) {
|
|
1158
|
+
if (ts.isVariableStatement(node) || ts.isPropertyDeclaration(node)) {
|
|
1159
|
+
statement = node;
|
|
1160
|
+
break;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
const srcText = candidate.ast.text;
|
|
1164
|
+
const directlyAttached = (node) => {
|
|
1165
|
+
const start = node.getStart(candidate.ast);
|
|
1166
|
+
const match = [...(ts.getLeadingCommentRanges(srcText, node.getFullStart()) ?? [])]
|
|
1167
|
+
.reverse()
|
|
1168
|
+
.find(range => srcText.slice(range.pos, range.end).startsWith('/**') && srcText.slice(range.end, start).trim() === '');
|
|
1169
|
+
return match ? srcText.slice(match.pos, match.end) : undefined;
|
|
1170
|
+
};
|
|
1171
|
+
return (statement ? directlyAttached(statement) : undefined) ?? directlyAttached(candidate.node);
|
|
1172
|
+
}
|
|
1173
|
+
// hygiene-ignore single-use -- Keep the documented regexExportDeclarations declaration so its parameter and return contract remains attached.
|
|
1174
|
+
/**
|
|
1175
|
+
* Preserves existing declaration statements and their meaningful TSDoc.
|
|
1176
|
+
*
|
|
1177
|
+
* @param src Existing declaration-file source.
|
|
1178
|
+
*
|
|
1179
|
+
* @return Original declaration statements, including their leading comments.
|
|
1180
|
+
*/
|
|
1181
|
+
function regexExportDeclarations(src) {
|
|
1182
|
+
const ast = ts.createSourceFile('regex.d.mts', src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
1183
|
+
const declarations = new Map();
|
|
1184
|
+
for (const s of ast.statements) {
|
|
1185
|
+
if (!ts.isVariableStatement(s) || !s.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) || s.declarationList.declarations.length !== 1)
|
|
1186
|
+
continue;
|
|
1187
|
+
const declaration = s.declarationList.declarations[0];
|
|
1188
|
+
if (!ts.isIdentifier(declaration.name))
|
|
1189
|
+
continue;
|
|
1190
|
+
const headerDocumentation = [...src.slice(0, src.indexOf(REGEX_DECLARATION_MARKER)).matchAll(S_S_G_REGEX())].map(match => match[0]);
|
|
1191
|
+
let statement = src.slice(s.getFullStart(), s.end).replace(REGEX_DECLARATION_MARKER, '');
|
|
1192
|
+
for (const comment of headerDocumentation)
|
|
1193
|
+
statement = statement.replaceAll(comment, '');
|
|
1194
|
+
declarations.set(declaration.name.text, removeEmptyRegexDocs(removeTemplateRegexReturnDocs(statement.trim())));
|
|
1195
|
+
}
|
|
1196
|
+
return declarations;
|
|
1197
|
+
}
|
|
1198
|
+
// hygiene-ignore single-use -- Keep the documented regexExportDocumentation declaration so its parameter and return contract remains attached.
|
|
1199
|
+
/**
|
|
1200
|
+
* Reads authored TSDoc attached to generated regex exports, keyed by export name.
|
|
1201
|
+
*
|
|
1202
|
+
* @param src Generated registry module source.
|
|
1203
|
+
*
|
|
1204
|
+
* @return Exact TSDoc blocks already present in the registry.
|
|
1205
|
+
*/
|
|
1206
|
+
function regexExportDocumentation(src) {
|
|
1207
|
+
const documentation = new Map();
|
|
1208
|
+
const ast = ts.createSourceFile('regex.mjs', src, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
|
1209
|
+
for (const statement of ast.statements) {
|
|
1210
|
+
const entry = regexRegistryEntry(src, statement);
|
|
1211
|
+
if (!entry)
|
|
1212
|
+
continue;
|
|
1213
|
+
const leading = src.slice(statement.getFullStart(), statement.getStart(ast));
|
|
1214
|
+
for (const match of [...leading.matchAll(S_S_G_REGEX())].reverse()) {
|
|
1215
|
+
const comment = removeEmptyRegexDocs(removeTemplateRegexReturnDocs(match[0]));
|
|
1216
|
+
if (!comment)
|
|
1217
|
+
continue;
|
|
1218
|
+
documentation.set(entry.name, comment);
|
|
1219
|
+
break;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
return documentation;
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* Uses runtime TSDoc as the declaration source of truth, preserving declaration-only docs when absent at runtime.
|
|
1226
|
+
*
|
|
1227
|
+
* @param declarationDocumentation Existing declaration TSDoc, if present.
|
|
1228
|
+
* @param moduleDocumentation TSDoc attached to the corresponding runtime factory.
|
|
1229
|
+
*
|
|
1230
|
+
* @return Existing declaration TSDoc or the runtime TSDoc when the declaration has none.
|
|
1231
|
+
*/
|
|
1232
|
+
function regexDeclarationDocumentation(declarationDocumentation, moduleDocumentation) {
|
|
1233
|
+
return moduleDocumentation ?? declarationDocumentation;
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Creates the module specifier from a consumer file to the shared registry module.
|
|
1237
|
+
*
|
|
1238
|
+
* @param file Consumer source filename.
|
|
1239
|
+
* @param modulePath Shared module filename.
|
|
1240
|
+
*
|
|
1241
|
+
* @return A normalized relative module specifier.
|
|
1242
|
+
*/
|
|
1243
|
+
function moduleSpecifier(file, modulePath) {
|
|
1244
|
+
let specifier = relative(dirname(resolve(file)), resolve(modulePath)).replace(G_CLASS_2(), '/');
|
|
1245
|
+
if (!specifier.startsWith('.'))
|
|
1246
|
+
specifier = `./${specifier}`;
|
|
1247
|
+
return specifier;
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Finds the nearest package boundary for a file without leaving the configured repository root.
|
|
1251
|
+
*
|
|
1252
|
+
* @param file Absolute source or registry path.
|
|
1253
|
+
* @param repoRoot Configured repository root that bounds the package.json search.
|
|
1254
|
+
*
|
|
1255
|
+
* @return The nearest ancestor containing package.json, or the repository root when none exists.
|
|
1256
|
+
*/
|
|
1257
|
+
function packageRootFor(file, repoRoot) {
|
|
1258
|
+
const absoluteFile = resolve(file);
|
|
1259
|
+
const root = resolve(repoRoot);
|
|
1260
|
+
const relativePath = relative(root, absoluteFile);
|
|
1261
|
+
if (relativePath.split(SHARED_REGEX)[0] === '..' || isAbsolute(relativePath))
|
|
1262
|
+
return;
|
|
1263
|
+
let dir = dirname(absoluteFile);
|
|
1264
|
+
while (true) {
|
|
1265
|
+
if (existsSync(resolve(dir, 'package.json')))
|
|
1266
|
+
return dir;
|
|
1267
|
+
if (dir === root)
|
|
1268
|
+
return root;
|
|
1269
|
+
const relativeDir = relative(root, dir);
|
|
1270
|
+
if (relativeDir.split(SHARED_REGEX)[0] === '..' || isAbsolute(relativeDir))
|
|
1271
|
+
return;
|
|
1272
|
+
dir = dirname(dir);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Finds the nearest Git worktree boundary for a source or registry path.
|
|
1277
|
+
*
|
|
1278
|
+
* @param file Source or shared-registry path; the file itself may not exist yet.
|
|
1279
|
+
*
|
|
1280
|
+
* @return The Git worktree root, or `undefined` when no repository boundary is present.
|
|
1281
|
+
*/
|
|
1282
|
+
function gitRootFor(file) {
|
|
1283
|
+
let dir = dirname(resolve(file));
|
|
1284
|
+
while (true) {
|
|
1285
|
+
if (existsSync(resolve(dir, '.git')))
|
|
1286
|
+
return dir;
|
|
1287
|
+
const parent = dirname(dir);
|
|
1288
|
+
if (parent === dir)
|
|
1289
|
+
return;
|
|
1290
|
+
dir = parent;
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* Checks whether a consumer and shared registry belong to the same package boundary.
|
|
1295
|
+
*
|
|
1296
|
+
* @param file Absolute consumer source path.
|
|
1297
|
+
* @param modulePath Absolute shared registry path.
|
|
1298
|
+
* @param repoRoot Configured repository root used as the package-boundary fallback.
|
|
1299
|
+
*
|
|
1300
|
+
* @return Whether both paths resolve inside the same package.
|
|
1301
|
+
*/
|
|
1302
|
+
function sharesPackageBoundary(file, modulePath, repoRoot) {
|
|
1303
|
+
const consumerRoot = gitRootFor(file) ?? packageRootFor(file, repoRoot);
|
|
1304
|
+
return consumerRoot !== undefined && consumerRoot === (gitRootFor(modulePath) ?? packageRootFor(modulePath, repoRoot));
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Finds an existing namespace import for the shared registry module.
|
|
1308
|
+
*
|
|
1309
|
+
* @param ast Parsed consumer source file.
|
|
1310
|
+
* @param file Consumer source filename used to resolve import specifiers.
|
|
1311
|
+
* @param modulePath Resolved shared module filename.
|
|
1312
|
+
*
|
|
1313
|
+
* @return The imported namespace identifier, if the module is already imported.
|
|
1314
|
+
*/
|
|
1315
|
+
function namespaceImport(ast, file, modulePath) {
|
|
1316
|
+
for (const statement of ast.statements) {
|
|
1317
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
|
|
1318
|
+
continue;
|
|
1319
|
+
if (resolve(dirname(resolve(file)), statement.moduleSpecifier.text) !== resolve(modulePath))
|
|
1320
|
+
continue;
|
|
1321
|
+
if (!statement.importClause || statement.importClause.isTypeOnly || !statement.importClause.namedBindings || !ts.isNamespaceImport(statement.importClause.namedBindings))
|
|
1322
|
+
continue;
|
|
1323
|
+
return statement.importClause.namedBindings.name.text;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Adds a namespace import after directives and existing imports.
|
|
1328
|
+
*
|
|
1329
|
+
* @param src Consumer source text to update.
|
|
1330
|
+
* @param ast Parsed consumer source used to locate the import boundary.
|
|
1331
|
+
* @param alias Local name for the shared module namespace.
|
|
1332
|
+
* @param specifier Module specifier to import.
|
|
1333
|
+
*
|
|
1334
|
+
* @return Source text with the import inserted in the existing import group.
|
|
1335
|
+
*/
|
|
1336
|
+
function insertNamespaceImport(src, ast, alias, specifier) {
|
|
1337
|
+
const eol = src.includes('\r\n') ? '\r\n' : '\n';
|
|
1338
|
+
let at = 0;
|
|
1339
|
+
for (const statement of ast.statements) {
|
|
1340
|
+
if (ts.isImportDeclaration(statement) || (ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)))
|
|
1341
|
+
at = statement.end;
|
|
1342
|
+
else
|
|
1343
|
+
break;
|
|
1344
|
+
}
|
|
1345
|
+
if (!at && ast.statements.length) {
|
|
1346
|
+
const first = ast.statements[0];
|
|
1347
|
+
at = first.getStart(ast);
|
|
1348
|
+
const directive = [...src.slice(first.getFullStart(), first.getStart(ast)).matchAll(/^[ \t]*\/\/[^\r\n]*(?:eslint-disable-next-line|@ts-ignore|@ts-expect-error)[^\r\n]*/gm)].at(-1);
|
|
1349
|
+
if (directive?.index !== undefined)
|
|
1350
|
+
at = first.getFullStart() + directive.index;
|
|
1351
|
+
}
|
|
1352
|
+
if (!at && src.startsWith('#!')) {
|
|
1353
|
+
const shebangEnd = src.indexOf('\n');
|
|
1354
|
+
at = shebangEnd < 0 ? src.length : shebangEnd + 1;
|
|
1355
|
+
}
|
|
1356
|
+
const before = src.slice(0, at);
|
|
1357
|
+
const after = src.slice(at);
|
|
1358
|
+
return `${before}${at && !before.endsWith('\n') ? eol : ''}${`import * as ${alias} from '${specifier}';`}${after.startsWith('\n') || after.startsWith('\r\n') ? '' : eol}${after}`;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Collects every identifier spelling already used in a source file.
|
|
1362
|
+
*
|
|
1363
|
+
* @param ast Parsed source file to inspect.
|
|
1364
|
+
*
|
|
1365
|
+
* @return Identifier names used for collision checks.
|
|
1366
|
+
*/
|
|
1367
|
+
function identifierNames(ast) {
|
|
1368
|
+
const names = new Set();
|
|
1369
|
+
/**
|
|
1370
|
+
* Adds each identifier spelling found in the source tree.
|
|
1371
|
+
*
|
|
1372
|
+
* @param node Current AST node being inspected.
|
|
1373
|
+
*/
|
|
1374
|
+
const visit = (node) => {
|
|
1375
|
+
if (ts.isIdentifier(node))
|
|
1376
|
+
names.add(node.text);
|
|
1377
|
+
ts.forEachChild(node, visit);
|
|
1378
|
+
};
|
|
1379
|
+
visit(ast);
|
|
1380
|
+
return names;
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* Checks that generated JavaScript or TypeScript source parses successfully.
|
|
1384
|
+
*
|
|
1385
|
+
* @param file Output filename used to select the parser mode.
|
|
1386
|
+
* @param src Candidate source text to validate.
|
|
1387
|
+
*
|
|
1388
|
+
* @return Whether the candidate has no parse diagnostics.
|
|
1389
|
+
*/
|
|
1390
|
+
function validRegexOutput(file, src) {
|
|
1391
|
+
if (file.endsWith('.d.mts'))
|
|
1392
|
+
return ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS).parseDiagnostics.length === 0;
|
|
1393
|
+
if (ts.transpileModule(src, { fileName: file, reportDiagnostics: true, compilerOptions: { allowJs: true, jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext } })
|
|
1394
|
+
.diagnostics?.length)
|
|
1395
|
+
return false;
|
|
1396
|
+
return true;
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Replaces duplicate regex candidates with file-local constants or a configured shared ESM registry.
|
|
1400
|
+
* Shared factories preserve a fresh RegExp instance at every original evaluation site.
|
|
1401
|
+
*
|
|
1402
|
+
* @param cfg Quality configuration defining the regex threshold, source scope, and optional registry.
|
|
1403
|
+
* @param analysis Optional shared analysis context used for discovery.
|
|
1404
|
+
*
|
|
1405
|
+
* @return Counts of regex expressions replaced and candidates left unchanged for safety.
|
|
1406
|
+
*/
|
|
1407
|
+
export function fixRegexDedup(cfg, analysis) {
|
|
1408
|
+
if (cfg.regexDedup?.sharedModule)
|
|
1409
|
+
return fixRegexDedupShared(cfg, analysis);
|
|
1410
|
+
const min = (cfg.regexDedup ?? {}).minimumCount ?? 2;
|
|
1411
|
+
const groups = regexGroups(cfg, analysis);
|
|
1412
|
+
let fixed = 0;
|
|
1413
|
+
let skipped = 0;
|
|
1414
|
+
const files = new Map();
|
|
1415
|
+
for (const candidate of [...groups.values()].flat()) {
|
|
1416
|
+
if (!ts.isRegularExpressionLiteral(candidate.node))
|
|
1417
|
+
continue;
|
|
1418
|
+
files.set(candidate.file, [...(files.get(candidate.file) ?? []), candidate]);
|
|
1419
|
+
}
|
|
1420
|
+
for (const [file, candidates] of files) {
|
|
1421
|
+
const localGroups = new Map();
|
|
1422
|
+
for (const candidate of candidates)
|
|
1423
|
+
localGroups.set(candidate.source, [...(localGroups.get(candidate.source) ?? []), candidate]);
|
|
1424
|
+
const matches = [...localGroups].filter(([, n]) => n.length >= min);
|
|
1425
|
+
const used = identifierNames(candidates[0].ast);
|
|
1426
|
+
const declarations = [];
|
|
1427
|
+
const edits = [];
|
|
1428
|
+
for (const [, nodes] of matches) {
|
|
1429
|
+
const name = classConstName(nodes[0].expression.replace(/\W+/g, '_'), used).replace(/_CLASS$/, '_REGEX');
|
|
1430
|
+
const flags = nodes[0].expression.slice(nodes[0].expression.lastIndexOf('/') + 1);
|
|
1431
|
+
const stateful = flags.includes('g') || flags.includes('y');
|
|
1432
|
+
declarations.push(`const ${name} = ${stateful ? `() => ${nodes[0].expression}` : nodes[0].expression};`);
|
|
1433
|
+
for (const candidate of nodes)
|
|
1434
|
+
edits.push({ start: candidate.node.getStart(candidate.ast), end: candidate.node.end, replacement: stateful ? `${name}()` : name });
|
|
1435
|
+
fixed += nodes.length;
|
|
1436
|
+
}
|
|
1437
|
+
const matchingCount = matches.reduce((c, [, n]) => c + n.length, 0);
|
|
1438
|
+
if (!edits.length)
|
|
1439
|
+
continue;
|
|
1440
|
+
let updated = analysis?.texts.get(file) ?? readFileSync(file, 'utf8');
|
|
1441
|
+
for (const edit of edits.sort((l, r) => r.start - l.start))
|
|
1442
|
+
updated = `${updated.slice(0, edit.start)}${edit.replacement}${updated.slice(edit.end)}`;
|
|
1443
|
+
const withGroup = insertGenDeclarations(updated, declarations, file);
|
|
1444
|
+
if (withGroup === updated || !writePatternSrc(file, withGroup)) {
|
|
1445
|
+
fixed -= matchingCount;
|
|
1446
|
+
skipped += matchingCount;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
return { fixed, skipped };
|
|
1450
|
+
}
|
|
1451
|
+
// hygiene-ignore single-use -- Keep the documented fixRegexDedupShared declaration so its parameter and return contract remains attached.
|
|
1452
|
+
/**
|
|
1453
|
+
* Rewrites eligible duplicate regexes to factories in the configured shared module.
|
|
1454
|
+
*
|
|
1455
|
+
* @param cfg Quality configuration containing the shared module and source scope.
|
|
1456
|
+
* @param analysis Optional shared analysis context for reusing parsed sources.
|
|
1457
|
+
*
|
|
1458
|
+
* @return Counts of shared fixes applied and candidates left for review.
|
|
1459
|
+
*/
|
|
1460
|
+
function fixRegexDedupShared(cfg, analysis) {
|
|
1461
|
+
const sharedModule = cfg.regexDedup.sharedModule;
|
|
1462
|
+
if (!sharedModule.endsWith('.mjs'))
|
|
1463
|
+
throw new Error('regexDedup.sharedModule must name an ESM .mjs file.');
|
|
1464
|
+
const modulePath = resolve(cfg.root, sharedModule);
|
|
1465
|
+
const moduleRelative = relative(cfg.root, modulePath);
|
|
1466
|
+
if (moduleRelative === '..' || moduleRelative.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`))
|
|
1467
|
+
throw new Error('regexDedup.sharedModule must stay inside the repository root.');
|
|
1468
|
+
const declarationPath = modulePath.replace(/\.mjs$/, '.d.mts');
|
|
1469
|
+
const min = cfg.regexDedup?.minimumCount ?? 2;
|
|
1470
|
+
const groups = [...regexGroups(cfg, analysis)].filter(([, c]) => c.length >= min);
|
|
1471
|
+
const registry = readRegexRegistry(modulePath, declarationPath);
|
|
1472
|
+
if (!registry)
|
|
1473
|
+
return { fixed: 0, skipped: groups.reduce((c, [, v]) => c + v.length, 0) };
|
|
1474
|
+
const rewritable = groups.filter(([, candidates]) => candidates.every(candidate => candidate.rewritable && isEsmConsumer(cfg, candidate.file) && sharesPackageBoundary(candidate.file, modulePath, cfg.root)));
|
|
1475
|
+
let skipped = groups
|
|
1476
|
+
.filter(([, candidates]) => !candidates.every(candidate => candidate.rewritable && isEsmConsumer(cfg, candidate.file) && sharesPackageBoundary(candidate.file, modulePath, cfg.root)))
|
|
1477
|
+
.reduce((count, [, candidates]) => count + candidates.length, 0);
|
|
1478
|
+
const usedExports = new Set(registry.names);
|
|
1479
|
+
const namesByKey = new Map(registry.keys);
|
|
1480
|
+
const newEntries = [];
|
|
1481
|
+
const groupNames = new Map();
|
|
1482
|
+
for (const [key, candidates] of rewritable.sort(([l], [r]) => l.localeCompare(r))) {
|
|
1483
|
+
let name = namesByKey.get(key);
|
|
1484
|
+
if (!name) {
|
|
1485
|
+
name = (function regexExportName(src, used) {
|
|
1486
|
+
const base = `REGEX_${src.replace(A_ZA_Z0_9_G_REGEX(), '_').replace(G_REGEX(), '').slice(0, 60).toUpperCase() || 'PATTERN'}_REGEX`;
|
|
1487
|
+
let name = base;
|
|
1488
|
+
let suffix = 2;
|
|
1489
|
+
while (used.has(name))
|
|
1490
|
+
name = `${base}_${suffix++}`;
|
|
1491
|
+
used.add(name);
|
|
1492
|
+
return name;
|
|
1493
|
+
})(key, usedExports);
|
|
1494
|
+
namesByKey.set(key, name);
|
|
1495
|
+
newEntries.push({ key, name, expression: candidates[0].expression, documentation: candidates.map(regexCandidateDocumentation).find(comment => Boolean(comment)) });
|
|
1496
|
+
}
|
|
1497
|
+
groupNames.set(key, name);
|
|
1498
|
+
}
|
|
1499
|
+
const eol = '\n';
|
|
1500
|
+
let moduleBase = removeEmptyRegexDocs(removeTemplateRegexReturnDocs(registry.module));
|
|
1501
|
+
const referenced = referencedRegexExports(cfg, modulePath, registry.names, analysis);
|
|
1502
|
+
for (const n of groupNames.values())
|
|
1503
|
+
referenced.add(n);
|
|
1504
|
+
moduleBase = pruneUnusedRegexExports(moduleBase, new Set([...registry.keys.values()].filter(n => !referenced.has(n))));
|
|
1505
|
+
moduleBase = pruneUnusedRegexBindings(moduleBase, referenced);
|
|
1506
|
+
moduleBase = moduleBase.replace(/\n{3,}/gu, '\n\n');
|
|
1507
|
+
const moduleAdditions = newEntries
|
|
1508
|
+
.map(({ key: k, name: n, expression: e, documentation }) => `// @hygiene-regex-key ${JSON.stringify(k)}\n${documentation ? `${documentation}\n` : ''}export const ${n} = () => (\n${e
|
|
1509
|
+
.split('\n')
|
|
1510
|
+
.map(l => `\t${l}`)
|
|
1511
|
+
.join('\n')}\n);`)
|
|
1512
|
+
.join(`${eol}${eol}`);
|
|
1513
|
+
const moduleSrc = moduleAdditions ? `${moduleBase.replace(/\s*$/, '')}${eol}${eol}${moduleAdditions}${eol}` : moduleBase;
|
|
1514
|
+
const declarationSrc = (function declarationFor(module) {
|
|
1515
|
+
const names = [...new Set([...module.matchAll(EXPORT_CONST_A_ZA_Z_W_B_GM_REGEX())].map(m => m[1]))].sort();
|
|
1516
|
+
const existingDeclarations = regexExportDeclarations(registry.declaration);
|
|
1517
|
+
const moduleDocumentation = regexExportDocumentation(module);
|
|
1518
|
+
return `${genFilePrefix(registry.declaration, REGEX_DECLARATION_MARKER)}${names
|
|
1519
|
+
.map(n => {
|
|
1520
|
+
const existing = existingDeclarations.get(n);
|
|
1521
|
+
if (existing) {
|
|
1522
|
+
const existingDocumentation = /^\/\*\*[\s\S]*?\*\//.exec(existing)?.[0];
|
|
1523
|
+
const completedDocumentation = regexDeclarationDocumentation(existingDocumentation, moduleDocumentation.get(n));
|
|
1524
|
+
if (existingDocumentation && completedDocumentation !== existingDocumentation)
|
|
1525
|
+
return `${existing.replace(existingDocumentation, completedDocumentation)}`;
|
|
1526
|
+
if (!existingDocumentation && completedDocumentation)
|
|
1527
|
+
return `${completedDocumentation}\n${existing}`;
|
|
1528
|
+
return existing;
|
|
1529
|
+
}
|
|
1530
|
+
const documentation = moduleDocumentation.get(n);
|
|
1531
|
+
return `${documentation ? `${documentation}\n` : ''}export declare const ${n}: () => RegExp;`;
|
|
1532
|
+
})
|
|
1533
|
+
.join('\n')}${names.length ? '\n' : ''}`;
|
|
1534
|
+
})(moduleSrc);
|
|
1535
|
+
const srcEdits = new Map();
|
|
1536
|
+
let fixed = 0;
|
|
1537
|
+
for (const [key, candidates] of rewritable) {
|
|
1538
|
+
const name = groupNames.get(key);
|
|
1539
|
+
for (const candidate of candidates) {
|
|
1540
|
+
let fileEdits = srcEdits.get(candidate.file);
|
|
1541
|
+
if (!fileEdits) {
|
|
1542
|
+
// hygiene-ignore single-use -- Capture source bytes before resolving imports and choosing a collision-free alias.
|
|
1543
|
+
const source = analysis?.texts.get(candidate.file) ?? readFileSync(candidate.file, 'utf8');
|
|
1544
|
+
const existingAlias = namespaceImport(candidate.ast, candidate.file, modulePath);
|
|
1545
|
+
const names = identifierNames(candidate.ast);
|
|
1546
|
+
let alias = existingAlias ?? 'HygieneRegex';
|
|
1547
|
+
let suffix = 2;
|
|
1548
|
+
while (!existingAlias && names.has(alias))
|
|
1549
|
+
alias = `HygieneRegex${suffix++}`;
|
|
1550
|
+
fileEdits = { source, ast: candidate.ast, edits: [], alias, specifier: moduleSpecifier(candidate.file, modulePath) };
|
|
1551
|
+
srcEdits.set(candidate.file, fileEdits);
|
|
1552
|
+
}
|
|
1553
|
+
fileEdits.edits.push({ start: candidate.node.getStart(candidate.ast), end: candidate.node.end, replacement: `${fileEdits.alias}.${name}()` });
|
|
1554
|
+
fixed++;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
const updatedSrcs = new Map();
|
|
1558
|
+
for (const [file, fileEdits] of srcEdits) {
|
|
1559
|
+
let updated = fileEdits.source;
|
|
1560
|
+
for (const edit of fileEdits.edits.sort((l, r) => r.start - l.start))
|
|
1561
|
+
updated = `${updated.slice(0, edit.start)}${edit.replacement}${updated.slice(edit.end)}`;
|
|
1562
|
+
if (!namespaceImport(fileEdits.ast, file, modulePath))
|
|
1563
|
+
updated = insertNamespaceImport(updated, ts.createSourceFile(file, updated, ts.ScriptTarget.Latest, true, regexScriptKind(file)), fileEdits.alias, fileEdits.specifier);
|
|
1564
|
+
if (!validRegexOutput(file, updated)) {
|
|
1565
|
+
skipped += fileEdits.edits.length;
|
|
1566
|
+
fixed -= fileEdits.edits.length;
|
|
1567
|
+
continue;
|
|
1568
|
+
}
|
|
1569
|
+
updatedSrcs.set(file, updated);
|
|
1570
|
+
}
|
|
1571
|
+
if ([...updatedSrcs].length !== srcEdits.size || !validRegexOutput(modulePath, moduleSrc) || !validRegexOutput(declarationPath, declarationSrc))
|
|
1572
|
+
return { fixed: 0, skipped: groups.filter(([, c]) => c.every(c => c.rewritable && isEsmConsumer(cfg, c.file))).reduce((c, [, v]) => c + v.length, 0) + skipped };
|
|
1573
|
+
if (!(moduleSrc !== registry.module || declarationSrc !== registry.declaration || newEntries.length > 0) && !srcEdits.size)
|
|
1574
|
+
return { fixed, skipped };
|
|
1575
|
+
mkdirSync(dirname(modulePath), { recursive: true });
|
|
1576
|
+
if (moduleSrc !== registry.module || newEntries.length)
|
|
1577
|
+
writeFileSync(modulePath, moduleSrc);
|
|
1578
|
+
if (declarationSrc !== registry.declaration || newEntries.length)
|
|
1579
|
+
writeFileSync(declarationPath, declarationSrc);
|
|
1580
|
+
for (const [file, source] of updatedSrcs)
|
|
1581
|
+
writeFileSync(file, source);
|
|
1582
|
+
return { fixed, skipped };
|
|
1583
|
+
}
|
|
1584
|
+
//# sourceMappingURL=patterns.js.map
|