code-gauge 0.0.0-semantically-released
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/LICENSE +201 -0
- package/README.md +147 -0
- package/dist/architectureMetrics.cjs +2 -0
- package/dist/architectureMetrics.cjs.map +1 -0
- package/dist/architectureMetrics.d.ts +41 -0
- package/dist/architectureMetrics.js +2 -0
- package/dist/architectureMetrics.js.map +1 -0
- package/dist/cli.cjs +3 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +3 -0
- package/dist/cli.js.map +1 -0
- package/dist/cliConfig.cjs +2 -0
- package/dist/cliConfig.cjs.map +1 -0
- package/dist/cliConfig.d.ts +92 -0
- package/dist/cliConfig.js +2 -0
- package/dist/cliConfig.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/languages.cjs +2 -0
- package/dist/languages.cjs.map +1 -0
- package/dist/languages.d.ts +4 -0
- package/dist/languages.js +2 -0
- package/dist/languages.js.map +1 -0
- package/dist/metrics.cjs +2 -0
- package/dist/metrics.cjs.map +1 -0
- package/dist/metrics.d.ts +9 -0
- package/dist/metrics.js +2 -0
- package/dist/metrics.js.map +1 -0
- package/dist/types.d.ts +137 -0
- package/dist/typescriptProject.cjs +2 -0
- package/dist/typescriptProject.cjs.map +1 -0
- package/dist/typescriptProject.d.ts +24 -0
- package/dist/typescriptProject.js +2 -0
- package/dist/typescriptProject.js.map +1 -0
- package/package.json +80 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# code-gauge
|
|
2
|
+
|
|
3
|
+
[](https://github.com/WillBooster/code-gauge/actions/workflows/test.yml)
|
|
4
|
+
[](https://github.com/semantic-release/semantic-release)
|
|
5
|
+
|
|
6
|
+
A command-line tool for measuring code metrics with tree-sitter. It scans a project and reports high-risk files, functions, and React components so you can spot code that is worth refactoring. A [programmatic API](#programmatic-api) is also available.
|
|
7
|
+
|
|
8
|
+
## Getting started
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
# Run without installing
|
|
12
|
+
npx code-gauge path/to/project
|
|
13
|
+
|
|
14
|
+
# Or install globally
|
|
15
|
+
npm install -g code-gauge
|
|
16
|
+
code-gauge path/to/project
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The CLI scans JavaScript, JSX, TypeScript, TSX, Python, and Go files. By default it skips generated, vendor, test, and tool directories, prints a summary, and lists the highest-risk findings. TypeScript project metrics and React component classification turn on automatically when a `tsconfig.json` is found.
|
|
20
|
+
|
|
21
|
+
## Options
|
|
22
|
+
|
|
23
|
+
| Option | Description |
|
|
24
|
+
| -------------------------- | --------------------------------------------------------------------------- |
|
|
25
|
+
| `--config <path>` | Use this config file instead of the auto-detected `code-gauge.config.json`. |
|
|
26
|
+
| `--include-tests` | Include test files and test directories. |
|
|
27
|
+
| `--tsconfig <path>` | Use this `tsconfig.json` instead of the auto-detected one. |
|
|
28
|
+
| `--max-findings <n>` | Maximum number of findings to print (default: 20). |
|
|
29
|
+
| `--json` | Print machine-readable JSON. |
|
|
30
|
+
| `--fail-on-risk` | Exit with code 1 when any high-risk finding is reported. |
|
|
31
|
+
| `--fail-on-error` | Exit with code 1 when any file or directory cannot be scanned. |
|
|
32
|
+
| `--<metric>-threshold <n>` | Override a risk threshold (see below). |
|
|
33
|
+
|
|
34
|
+
## Risk thresholds
|
|
35
|
+
|
|
36
|
+
A finding is reported when a measured value is **greater than or equal to** its threshold. Every threshold can be set on the command line (e.g. `--file-loc-threshold 400`) or in a config file; the command line wins over the config file, which wins over the defaults.
|
|
37
|
+
|
|
38
|
+
`code-gauge` looks for `code-gauge.config.json` by walking up from the target directory (override with `--config`). The following config reproduces every built-in default:
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{
|
|
42
|
+
"thresholds": {
|
|
43
|
+
"fileLoc": 500,
|
|
44
|
+
"functionLoc": 120,
|
|
45
|
+
"componentLoc": 350,
|
|
46
|
+
"cognitive": 25,
|
|
47
|
+
"cyclomatic": 20,
|
|
48
|
+
"call": 50,
|
|
49
|
+
"import": 25,
|
|
50
|
+
"fanOut": 10,
|
|
51
|
+
"parameter": 8,
|
|
52
|
+
"duplicateBlock": 2,
|
|
53
|
+
"transitiveDependency": 25,
|
|
54
|
+
"structuralBreadth": 8,
|
|
55
|
+
"structuralCoordination": 300,
|
|
56
|
+
"stateMutation": 50,
|
|
57
|
+
"duplicateSymbolGroup": 5
|
|
58
|
+
},
|
|
59
|
+
"languageThresholds": {
|
|
60
|
+
"python": { "stateMutation": 90, "structuralCoordination": 350 },
|
|
61
|
+
"react": { "import": 30 }
|
|
62
|
+
},
|
|
63
|
+
"maxFindings": 20,
|
|
64
|
+
"includeTests": false,
|
|
65
|
+
"failOnRisk": false,
|
|
66
|
+
"failOnError": false
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
| Threshold | CLI flag | Reports when a … |
|
|
71
|
+
| ------------------------ | ------------------------------------- | ------------------------------------------------ |
|
|
72
|
+
| `fileLoc` | `--file-loc-threshold` | file's code LOC is large. |
|
|
73
|
+
| `functionLoc` | `--function-loc-threshold` | function's physical LOC span is large. |
|
|
74
|
+
| `componentLoc` | `--component-loc-threshold` | React component's physical LOC span is large. |
|
|
75
|
+
| `cognitive` | `--cognitive-threshold` | function's cognitive complexity is high. |
|
|
76
|
+
| `cyclomatic` | `--cyclomatic-threshold` | function's cyclomatic complexity is high. |
|
|
77
|
+
| `call` | `--call-threshold` | function makes many calls. |
|
|
78
|
+
| `import` | `--import-threshold` | file has many unique import sources. |
|
|
79
|
+
| `fanOut` | `--fan-out-threshold` | function calls many other in-file functions. |
|
|
80
|
+
| `parameter` | `--parameter-threshold` | function declares many parameters. |
|
|
81
|
+
| `duplicateBlock` | `--duplicate-block-threshold` | file contains copy-pasted code blocks. |
|
|
82
|
+
| `transitiveDependency` | `--transitive-dependency-threshold` | file transitively reaches many local files. |
|
|
83
|
+
| `structuralBreadth` | `--structural-breadth-threshold` | file coordinates many structural concerns. |
|
|
84
|
+
| `structuralCoordination` | `--structural-coordination-threshold` | file's structural coordination score is high. |
|
|
85
|
+
| `stateMutation` | `--state-mutation-threshold` | file mutates state heavily. |
|
|
86
|
+
| `duplicateSymbolGroup` | `--duplicate-symbol-group-threshold` | file shares many duplicated symbols with others. |
|
|
87
|
+
|
|
88
|
+
### Per-language thresholds
|
|
89
|
+
|
|
90
|
+
Some metrics distribute very differently by language or file type, so a single global threshold either
|
|
91
|
+
over-flags one language or under-flags another. `languageThresholds` overrides individual thresholds for a
|
|
92
|
+
profile without repeating the whole set. Each file resolves its thresholds as **base → its language profile →
|
|
93
|
+
the `react` profile** (the last applies when the file contains a React component), so later profiles win.
|
|
94
|
+
|
|
95
|
+
Valid profile keys are `javascript`, `jsx`, `typescript`, `tsx`, `python`, `go`, and `react`. Built-in
|
|
96
|
+
overrides raise `stateMutation` and `structuralCoordination` for Python (every binding is an assignment, so
|
|
97
|
+
these run far higher than in TypeScript) and raise `import` for React files (which pull in many components).
|
|
98
|
+
Anything you specify is merged on top of the built-in overrides, so `{ "python": { "stateMutation": 8 } }`
|
|
99
|
+
restores the global value for Python while keeping the other built-in adjustments.
|
|
100
|
+
|
|
101
|
+
```json
|
|
102
|
+
{
|
|
103
|
+
"languageThresholds": {
|
|
104
|
+
"python": { "stateMutation": 120 },
|
|
105
|
+
"react": { "componentLoc": 400, "import": 35 }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Command-line `--<metric>-threshold` flags set the global base only; use the config file for per-language tuning.
|
|
111
|
+
|
|
112
|
+
## Metrics
|
|
113
|
+
|
|
114
|
+
- Physical LOC, code lines, comment-only lines, and blank lines
|
|
115
|
+
- Function and class counts
|
|
116
|
+
- Cyclomatic and cognitive complexity (per function and maximum)
|
|
117
|
+
- Nesting depth
|
|
118
|
+
- Intra-file call graph metrics: call counts, fan-in/fan-out, recursion, call depth, and parameter counts
|
|
119
|
+
- Within-file structural duplication: copy-pasted code blocks (distinct from cross-file duplicate symbol names)
|
|
120
|
+
- File coupling (imports/exports) and cohesion (shared function identifiers)
|
|
121
|
+
- Architecture metrics: transitive local dependencies, structural coordination and breadth, state mutation, and cross-file duplicate symbols
|
|
122
|
+
- TypeScript type-shape metrics: annotations, aliases, interfaces, generics, unions, intersections, assertions, and conditional types
|
|
123
|
+
- Halstead metrics and the maintainability index
|
|
124
|
+
|
|
125
|
+
## Supported languages
|
|
126
|
+
|
|
127
|
+
Built-in parsers cover JavaScript, JSX, TypeScript, TSX, Python, and Go. Additional tree-sitter grammars can be registered with `TreeMeasurer.registerLanguage`.
|
|
128
|
+
|
|
129
|
+
## Programmatic API
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { measureCode } from 'code-gauge';
|
|
133
|
+
|
|
134
|
+
const metrics = measureCode(
|
|
135
|
+
`
|
|
136
|
+
function score(value) {
|
|
137
|
+
if (value < 0 || value == null) {
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
return value > 10 ? 10 : value;
|
|
141
|
+
}
|
|
142
|
+
`,
|
|
143
|
+
{ language: 'javascript' }
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
console.log(metrics.cyclomaticComplexity);
|
|
147
|
+
```
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var t=require("node:path");function e(e,n,o){if(!n.startsWith("."))return;const r=function(e,n){const o=t.dirname(e);if(function(t){return t.startsWith("./")||t.startsWith("../")||t.includes("/")}(n))return[t.normalize(t.join(o,n))];const r=/^(?<dots>\.+)(?<module>.*)$/u.exec(n),a=r?.groups?.dots,i=r?.groups?.module;if(!a||void 0===i)return[];let u=o;for(let e=1;e<a.length;e+=1)u=t.dirname(u);const l=i.replaceAll(".",t.sep);return[t.normalize(t.join(u,l))]}(e,n),a=r.flatMap(e=>{const n=t.extname(e);return n?[e.slice(0,-n.length),e]:[e]});for(const e of a)for(const n of[`${e}.ts`,`${e}.tsx`,`${e}.js`,`${e}.jsx`,`${e}.py`,t.join(e,"index.ts"),t.join(e,"index.tsx"),t.join(e,"index.js"),t.join(e,"__init__.py")])if(o.has(n))return n}function n(t,e){const n=new Set,o=[...e.get(t)??[]];for(;o.length>0;){const t=o.pop();t&&!n.has(t)&&(n.add(t),o.push(...e.get(t)??[]))}return n.size}function o(t){return t.name.length>=5}function r(t,e){return{file:t,line:e.startLine}}function a(t,e){return t.file.localeCompare(e.file)||t.line-e.line}function i(t,e,n){n&&t.add(e)}function u(t,e){return Math.max(0,...t.map(t=>t[e]).filter(t=>"number"==typeof t))}exports.measureArchitecture=function(l,s){const c=l.map(e=>({...e,relativeFile:t.relative(s,e.file)||t.basename(e.file)})),p=function(t){const n=new Set(t.map(t=>t.relativeFile)),o=new Map;for(const r of t){const t=new Set;for(const o of r.metrics.module.importSources){const a=e(r.relativeFile,o,n);a&&t.add(a)}o.set(r.relativeFile,t)}return o}(c),m=function(t){const e=new Map;for(const n of t)for(const t of n.metrics.module.declarations){if(!o(t))continue;const a=e.get(t.name)??[];a.push(r(n.relativeFile,t)),e.set(t.name,a)}return[...e.entries()].flatMap(([t,e])=>{const n=[...new Set(e.map(t=>t.file))].toSorted();return n.length>1?[{declarations:e.toSorted(a),files:n,name:t}]:[]}).toSorted((t,e)=>e.files.length-t.files.length||t.name.localeCompare(e.name))}(c),f=function(t){const e=new Map;for(const n of t)for(const t of n.files)e.set(t,(e.get(t)??0)+1);return e}(m),d=c.map(t=>{const e=p.get(t.relativeFile)??new Set,o=function(t){const e=t.syntaxFeatures.awaitExpressionCount,n=t.syntaxFeatures.tryStatementCount+t.syntaxFeatures.throwStatementCount,o=t.syntaxFeatures.mutableBindingCount+t.syntaxFeatures.assignmentCount,r=t.cyclomaticComplexity+t.syntaxFeatures.loopStatementCount+t.syntaxFeatures.returnStatementCount,a=t.callGraph.callCount+2*t.callGraph.internalEdgeCount+3*t.callGraph.maxCallDepth;return{asyncBoundaryCount:e,branchingScore:r,exceptionHandlingCount:n,moduleInteractionScore:a,score:2*e+3*n+o+r+a,stateMutationScore:o}}(t.metrics),r=function(t){const e=new Set;return i(e,"class-shapes",t.classCount>0),i(e,"control-flow",t.cognitiveComplexity>0),i(e,"external-dependencies",t.coupling.externalImportCount>0),i(e,"functions",t.functionCount>0),i(e,"local-dependencies",t.coupling.relativeImportCount>0),i(e,"module-api",t.coupling.exportCount>0||t.module.declarations.length>0),i(e,"state-mutation",t.syntaxFeatures.mutableBindingCount+t.syntaxFeatures.assignmentCount>0),i(e,"type-shapes",function(t){return t.typeComplexity.typeAnnotationCount+t.typeComplexity.typeAliasCount+t.typeComplexity.interfaceCount+t.typeComplexity.genericParameterCount+t.typeComplexity.unionTypeCount+t.typeComplexity.intersectionTypeCount+t.typeComplexity.conditionalTypeCount>0}(t)),[...e].toSorted()}(t.metrics);return{file:t.relativeFile,directLocalDependencyCount:e.size,duplicateSymbolGroupCount:f.get(t.relativeFile)??0,structuralBreadthScore:r.length,structuralCoordination:o,structuralFeatureGroups:r,transitiveLocalDependencyCount:n(t.relativeFile,p)}});return{duplicateSymbolGroups:m,files:d,maxDirectLocalDependencyCount:u(d,"directLocalDependencyCount"),maxDuplicateSymbolGroupCount:u(d,"duplicateSymbolGroupCount"),maxStructuralBreadthScore:u(d,"structuralBreadthScore"),maxStructuralCoordinationScore:Math.max(0,...d.map(t=>t.structuralCoordination.score)),maxTransitiveLocalDependencyCount:u(d,"transitiveLocalDependencyCount")}};
|
|
2
|
+
//# sourceMappingURL=architectureMetrics.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"architectureMetrics.cjs","sources":["../src/architectureMetrics.ts"],"sourcesContent":["import path from 'node:path';\nimport type { CodeMetrics, DeclarationMetrics } from './types.js';\n\nexport interface ArchitectureSourceFile {\n file: string;\n metrics: CodeMetrics;\n}\n\nexport interface ArchitectureFileMetrics {\n directLocalDependencyCount: number;\n duplicateSymbolGroupCount: number;\n file: string;\n structuralBreadthScore: number;\n structuralCoordination: StructuralCoordinationMetrics;\n structuralFeatureGroups: string[];\n transitiveLocalDependencyCount: number;\n}\n\nexport interface ArchitectureMetrics {\n duplicateSymbolGroups: DuplicateSymbolGroup[];\n files: ArchitectureFileMetrics[];\n maxDirectLocalDependencyCount: number;\n maxDuplicateSymbolGroupCount: number;\n maxStructuralBreadthScore: number;\n maxStructuralCoordinationScore: number;\n maxTransitiveLocalDependencyCount: number;\n}\n\nexport interface DuplicateSymbolGroup {\n declarations: DuplicateSymbolDeclaration[];\n files: string[];\n name: string;\n}\n\nexport interface DuplicateSymbolDeclaration {\n file: string;\n line: number;\n}\n\nexport interface StructuralCoordinationMetrics {\n asyncBoundaryCount: number;\n branchingScore: number;\n exceptionHandlingCount: number;\n moduleInteractionScore: number;\n score: number;\n stateMutationScore: number;\n}\n\ninterface SourceFile {\n file: string;\n metrics: CodeMetrics;\n relativeFile: string;\n}\n\nconst duplicateSymbolNameLengthThreshold = 5;\n\nexport function measureArchitecture(\n files: readonly ArchitectureSourceFile[],\n displayRoot: string\n): ArchitectureMetrics {\n const sourceFiles = files.map((file) => ({\n ...file,\n relativeFile: path.relative(displayRoot, file.file) || path.basename(file.file),\n }));\n const dependencyGraph = measureDependencyGraph(sourceFiles);\n const duplicateSymbolGroups = measureDuplicateSymbolGroups(sourceFiles);\n const duplicateGroupCountByFile = measureDuplicateGroupCountByFile(duplicateSymbolGroups);\n const metrics = sourceFiles.map((sourceFile) => {\n const directDependencies = dependencyGraph.get(sourceFile.relativeFile) ?? new Set<string>();\n const structuralCoordination = measureStructuralCoordination(sourceFile.metrics);\n const structuralFeatureGroups = measureStructuralFeatureGroups(sourceFile.metrics);\n return {\n file: sourceFile.relativeFile,\n directLocalDependencyCount: directDependencies.size,\n duplicateSymbolGroupCount: duplicateGroupCountByFile.get(sourceFile.relativeFile) ?? 0,\n structuralBreadthScore: structuralFeatureGroups.length,\n structuralCoordination,\n structuralFeatureGroups,\n transitiveLocalDependencyCount: measureTransitiveDependencyCount(sourceFile.relativeFile, dependencyGraph),\n };\n });\n\n return {\n duplicateSymbolGroups,\n files: metrics,\n maxDirectLocalDependencyCount: maxFileMetric(metrics, 'directLocalDependencyCount'),\n maxDuplicateSymbolGroupCount: maxFileMetric(metrics, 'duplicateSymbolGroupCount'),\n maxStructuralBreadthScore: maxFileMetric(metrics, 'structuralBreadthScore'),\n maxStructuralCoordinationScore: Math.max(0, ...metrics.map((file) => file.structuralCoordination.score)),\n maxTransitiveLocalDependencyCount: maxFileMetric(metrics, 'transitiveLocalDependencyCount'),\n };\n}\n\nfunction measureDependencyGraph(files: SourceFile[]): Map<string, Set<string>> {\n const fileSet = new Set(files.map((file) => file.relativeFile));\n const graph = new Map<string, Set<string>>();\n for (const file of files) {\n const dependencies = new Set<string>();\n for (const source of file.metrics.module.importSources) {\n const resolved = resolveLocalImport(file.relativeFile, source, fileSet);\n if (resolved) {\n dependencies.add(resolved);\n }\n }\n graph.set(file.relativeFile, dependencies);\n }\n return graph;\n}\n\nfunction resolveLocalImport(fromFile: string, source: string, fileSet: Set<string>): string | undefined {\n if (!source.startsWith('.')) {\n return undefined;\n }\n const bases = localImportBases(fromFile, source);\n const stems = bases.flatMap((base) => {\n const extension = path.extname(base);\n return extension ? [base.slice(0, -extension.length), base] : [base];\n });\n for (const stem of stems) {\n for (const candidate of [\n `${stem}.ts`,\n `${stem}.tsx`,\n `${stem}.js`,\n `${stem}.jsx`,\n `${stem}.py`,\n path.join(stem, 'index.ts'),\n path.join(stem, 'index.tsx'),\n path.join(stem, 'index.js'),\n path.join(stem, '__init__.py'),\n ]) {\n if (fileSet.has(candidate)) {\n return candidate;\n }\n }\n }\n return undefined;\n}\n\nfunction localImportBases(fromFile: string, source: string): string[] {\n const fromDirectory = path.dirname(fromFile);\n if (isPathRelativeImport(source)) {\n return [path.normalize(path.join(fromDirectory, source))];\n }\n\n const match = /^(?<dots>\\.+)(?<module>.*)$/u.exec(source);\n const dots = match?.groups?.dots;\n const moduleName = match?.groups?.module;\n if (!dots || moduleName === undefined) {\n return [];\n }\n\n let baseDirectory = fromDirectory;\n for (let index = 1; index < dots.length; index += 1) {\n baseDirectory = path.dirname(baseDirectory);\n }\n\n const modulePath = moduleName.replaceAll('.', path.sep);\n return [path.normalize(path.join(baseDirectory, modulePath))];\n}\n\nfunction isPathRelativeImport(source: string): boolean {\n return source.startsWith('./') || source.startsWith('../') || source.includes('/');\n}\n\nfunction measureTransitiveDependencyCount(file: string, graph: Map<string, Set<string>>): number {\n const visited = new Set<string>();\n const pending = [...(graph.get(file) ?? [])];\n while (pending.length > 0) {\n const current = pending.pop();\n if (!current || visited.has(current)) {\n continue;\n }\n visited.add(current);\n pending.push(...(graph.get(current) ?? []));\n }\n return visited.size;\n}\n\nfunction measureDuplicateSymbolGroups(files: SourceFile[]): DuplicateSymbolGroup[] {\n const declarationsBySymbol = new Map<string, DuplicateSymbolDeclaration[]>();\n for (const file of files) {\n for (const declaration of file.metrics.module.declarations) {\n if (!isDuplicateSymbolCandidate(declaration)) {\n continue;\n }\n const declarations = declarationsBySymbol.get(declaration.name) ?? [];\n declarations.push(toDuplicateSymbolDeclaration(file.relativeFile, declaration));\n declarationsBySymbol.set(declaration.name, declarations);\n }\n }\n return [...declarationsBySymbol.entries()]\n .flatMap(([name, declarations]) => {\n const duplicateFiles = [...new Set(declarations.map((declaration) => declaration.file))].toSorted();\n return duplicateFiles.length > 1\n ? [{ declarations: declarations.toSorted(compareDuplicateDeclarations), files: duplicateFiles, name }]\n : [];\n })\n .toSorted((left, right) => right.files.length - left.files.length || left.name.localeCompare(right.name));\n}\n\nfunction isDuplicateSymbolCandidate(declaration: DeclarationMetrics): boolean {\n return declaration.name.length >= duplicateSymbolNameLengthThreshold;\n}\n\nfunction toDuplicateSymbolDeclaration(file: string, declaration: DeclarationMetrics): DuplicateSymbolDeclaration {\n return { file, line: declaration.startLine };\n}\n\nfunction compareDuplicateDeclarations(left: DuplicateSymbolDeclaration, right: DuplicateSymbolDeclaration): number {\n return left.file.localeCompare(right.file) || left.line - right.line;\n}\n\nfunction measureDuplicateGroupCountByFile(groups: DuplicateSymbolGroup[]): Map<string, number> {\n const counts = new Map<string, number>();\n for (const group of groups) {\n for (const file of group.files) {\n counts.set(file, (counts.get(file) ?? 0) + 1);\n }\n }\n return counts;\n}\n\nfunction measureStructuralCoordination(metrics: CodeMetrics): StructuralCoordinationMetrics {\n const asyncBoundaryCount = metrics.syntaxFeatures.awaitExpressionCount;\n const exceptionHandlingCount = metrics.syntaxFeatures.tryStatementCount + metrics.syntaxFeatures.throwStatementCount;\n const stateMutationScore = metrics.syntaxFeatures.mutableBindingCount + metrics.syntaxFeatures.assignmentCount;\n const branchingScore =\n metrics.cyclomaticComplexity +\n metrics.syntaxFeatures.loopStatementCount +\n metrics.syntaxFeatures.returnStatementCount;\n const moduleInteractionScore =\n metrics.callGraph.callCount + metrics.callGraph.internalEdgeCount * 2 + metrics.callGraph.maxCallDepth * 3;\n\n return {\n asyncBoundaryCount,\n branchingScore,\n exceptionHandlingCount,\n moduleInteractionScore,\n score:\n asyncBoundaryCount * 2 +\n exceptionHandlingCount * 3 +\n stateMutationScore +\n branchingScore +\n moduleInteractionScore,\n stateMutationScore,\n };\n}\n\nfunction measureStructuralFeatureGroups(metrics: CodeMetrics): string[] {\n const groups = new Set<string>();\n addGroup(groups, 'class-shapes', metrics.classCount > 0);\n addGroup(groups, 'control-flow', metrics.cognitiveComplexity > 0);\n addGroup(groups, 'external-dependencies', metrics.coupling.externalImportCount > 0);\n addGroup(groups, 'functions', metrics.functionCount > 0);\n addGroup(groups, 'local-dependencies', metrics.coupling.relativeImportCount > 0);\n addGroup(groups, 'module-api', metrics.coupling.exportCount > 0 || metrics.module.declarations.length > 0);\n addGroup(\n groups,\n 'state-mutation',\n metrics.syntaxFeatures.mutableBindingCount + metrics.syntaxFeatures.assignmentCount > 0\n );\n addGroup(groups, 'type-shapes', hasTypeShapeMetrics(metrics));\n return [...groups].toSorted();\n}\n\nfunction addGroup(groups: Set<string>, group: string, condition: boolean): void {\n if (condition) {\n groups.add(group);\n }\n}\n\nfunction hasTypeShapeMetrics(metrics: CodeMetrics): boolean {\n return (\n metrics.typeComplexity.typeAnnotationCount +\n metrics.typeComplexity.typeAliasCount +\n metrics.typeComplexity.interfaceCount +\n metrics.typeComplexity.genericParameterCount +\n metrics.typeComplexity.unionTypeCount +\n metrics.typeComplexity.intersectionTypeCount +\n metrics.typeComplexity.conditionalTypeCount >\n 0\n );\n}\n\nfunction maxFileMetric(metrics: ArchitectureFileMetrics[], key: keyof ArchitectureFileMetrics): number {\n return Math.max(\n 0,\n ...metrics.map((metric) => metric[key]).filter((value): value is number => typeof value === 'number')\n );\n}\n"],"names":["resolveLocalImport","fromFile","source","fileSet","startsWith","bases","fromDirectory","path","dirname","includes","isPathRelativeImport","normalize","join","match","exec","dots","groups","moduleName","module","undefined","baseDirectory","index","length","modulePath","replaceAll","sep","localImportBases","stems","flatMap","base","extension","extname","slice","stem","candidate","has","measureTransitiveDependencyCount","file","graph","visited","Set","pending","get","current","pop","add","push","size","isDuplicateSymbolCandidate","declaration","name","toDuplicateSymbolDeclaration","line","startLine","compareDuplicateDeclarations","left","right","localeCompare","addGroup","group","condition","maxFileMetric","metrics","key","Math","max","map","metric","filter","value","files","displayRoot","sourceFiles","relativeFile","relative","basename","dependencyGraph","Map","dependencies","importSources","resolved","set","measureDependencyGraph","duplicateSymbolGroups","declarationsBySymbol","declarations","entries","duplicateFiles","toSorted","measureDuplicateSymbolGroups","duplicateGroupCountByFile","counts","measureDuplicateGroupCountByFile","sourceFile","directDependencies","structuralCoordination","asyncBoundaryCount","syntaxFeatures","awaitExpressionCount","exceptionHandlingCount","tryStatementCount","throwStatementCount","stateMutationScore","mutableBindingCount","assignmentCount","branchingScore","cyclomaticComplexity","loopStatementCount","returnStatementCount","moduleInteractionScore","callGraph","callCount","internalEdgeCount","maxCallDepth","score","measureStructuralCoordination","structuralFeatureGroups","classCount","cognitiveComplexity","coupling","externalImportCount","functionCount","relativeImportCount","exportCount","typeComplexity","typeAnnotationCount","typeAliasCount","interfaceCount","genericParameterCount","unionTypeCount","intersectionTypeCount","conditionalTypeCount","hasTypeShapeMetrics","measureStructuralFeatureGroups","directLocalDependencyCount","duplicateSymbolGroupCount","structuralBreadthScore","transitiveLocalDependencyCount","maxDirectLocalDependencyCount","maxDuplicateSymbolGroupCount","maxStructuralBreadthScore","maxStructuralCoordinationScore","maxTransitiveLocalDependencyCount"],"mappings":"wCA6GA,SAASA,EAAmBC,EAAkBC,EAAgBC,GAC5D,IAAKD,EAAOE,WAAW,KACrB,OAEF,MAAMC,EAyBR,SAA0BJ,EAAkBC,GAC1C,MAAMI,EAAgBC,EAAKC,QAAQP,GACnC,GAoBF,SAA8BC,GAC5B,OAAOA,EAAOE,WAAW,OAASF,EAAOE,WAAW,QAAUF,EAAOO,SAAS,IAChF,CAtBMC,CAAqBR,GACvB,MAAO,CAACK,EAAKI,UAAUJ,EAAKK,KAAKN,EAAeJ,KAGlD,MAAMW,EAAQ,+BAA+BC,KAAKZ,GAC5Ca,EAAOF,GAAOG,QAAQD,KACtBE,EAAaJ,GAAOG,QAAQE,OAClC,IAAKH,QAAuBI,IAAfF,EACX,MAAO,GAGT,IAAIG,EAAgBd,EACpB,IAAK,IAAIe,EAAQ,EAAGA,EAAQN,EAAKO,OAAQD,GAAS,EAChDD,EAAgBb,EAAKC,QAAQ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sB8C,EAAQyD,SAASG,oBAAsB,GAC9EhE,EAAS1C,EAAQ,aAAc8C,EAAQyD,SAASI,YAAc,GAAK7D,EAAQ5C,OAAOmE,aAAa/D,OAAS,GACxGoC,EACE1C,EACA,iBACA8C,EAAQmC,eAAeM,oBAAsBzC,EAAQmC,eAAeO,gBAAkB,GAExF9C,EAAS1C,EAAQ,cAUnB,SAA6B8C,GAC3B,OACEA,EAAQ8D,eAAeC,oBACrB/D,EAAQ8D,eAAeE,eACvBhE,EAAQ8D,eAAeG,eACvBjE,EAAQ8D,eAAeI,sBACvBlE,EAAQ8D,eAAeK,eACvBnE,EAAQ8D,eAAeM,sBACvBpE,EAAQ8D,eAAeO,qBACzB,CAEJ,CArBkCC,CAAoBtE,IAC7C,IAAI9C,GAAQwE,UACrB,CAjMoC6C,CAA+BxC,EAAW/B,SAC1E,MAAO,CACLzB,KAAMwD,EAAWpB,aACjB6D,2BAA4BxC,EAAmB/C,KAC/CwF,0BAA2B7C,EAA0BhD,IAAImD,EAAWpB,eAAiB,EACrF+D,uBAAwBpB,EAAwB9F,OAChDyE,yBACAqB,0BACAqB,+BAAgCrG,EAAiCyD,EAAWpB,aAAcG,MAI9F,MAAO,CACLO,wBACAb,MAAOR,EACP4E,8BAA+B7E,EAAcC,EAAS,8BACtD6E,6BAA8B9E,EAAcC,EAAS,6BACrD8E,0BAA2B/E,EAAcC,EAAS,0BAClD+E,+BAAgC7E,KAAKC,IAAI,KAAMH,EAAQI,IAAK7B,GAASA,EAAK0D,uBAAuBmB,QACjG4B,kCAAmCjF,EAAcC,EAAS,kCAE9D"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { CodeMetrics } from './types.js';
|
|
2
|
+
export interface ArchitectureSourceFile {
|
|
3
|
+
file: string;
|
|
4
|
+
metrics: CodeMetrics;
|
|
5
|
+
}
|
|
6
|
+
export interface ArchitectureFileMetrics {
|
|
7
|
+
directLocalDependencyCount: number;
|
|
8
|
+
duplicateSymbolGroupCount: number;
|
|
9
|
+
file: string;
|
|
10
|
+
structuralBreadthScore: number;
|
|
11
|
+
structuralCoordination: StructuralCoordinationMetrics;
|
|
12
|
+
structuralFeatureGroups: string[];
|
|
13
|
+
transitiveLocalDependencyCount: number;
|
|
14
|
+
}
|
|
15
|
+
export interface ArchitectureMetrics {
|
|
16
|
+
duplicateSymbolGroups: DuplicateSymbolGroup[];
|
|
17
|
+
files: ArchitectureFileMetrics[];
|
|
18
|
+
maxDirectLocalDependencyCount: number;
|
|
19
|
+
maxDuplicateSymbolGroupCount: number;
|
|
20
|
+
maxStructuralBreadthScore: number;
|
|
21
|
+
maxStructuralCoordinationScore: number;
|
|
22
|
+
maxTransitiveLocalDependencyCount: number;
|
|
23
|
+
}
|
|
24
|
+
export interface DuplicateSymbolGroup {
|
|
25
|
+
declarations: DuplicateSymbolDeclaration[];
|
|
26
|
+
files: string[];
|
|
27
|
+
name: string;
|
|
28
|
+
}
|
|
29
|
+
export interface DuplicateSymbolDeclaration {
|
|
30
|
+
file: string;
|
|
31
|
+
line: number;
|
|
32
|
+
}
|
|
33
|
+
export interface StructuralCoordinationMetrics {
|
|
34
|
+
asyncBoundaryCount: number;
|
|
35
|
+
branchingScore: number;
|
|
36
|
+
exceptionHandlingCount: number;
|
|
37
|
+
moduleInteractionScore: number;
|
|
38
|
+
score: number;
|
|
39
|
+
stateMutationScore: number;
|
|
40
|
+
}
|
|
41
|
+
export declare function measureArchitecture(files: readonly ArchitectureSourceFile[], displayRoot: string): ArchitectureMetrics;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import t from"node:path";function e(e,s){const c=e.map(e=>({...e,relativeFile:t.relative(s,e.file)||t.basename(e.file)})),p=function(t){const e=new Set(t.map(t=>t.relativeFile)),o=new Map;for(const r of t){const t=new Set;for(const o of r.metrics.module.importSources){const a=n(r.relativeFile,o,e);a&&t.add(a)}o.set(r.relativeFile,t)}return o}(c),m=function(t){const e=new Map;for(const n of t)for(const t of n.metrics.module.declarations){if(!r(t))continue;const o=e.get(t.name)??[];o.push(a(n.relativeFile,t)),e.set(t.name,o)}return[...e.entries()].flatMap(([t,e])=>{const n=[...new Set(e.map(t=>t.file))].toSorted();return n.length>1?[{declarations:e.toSorted(i),files:n,name:t}]:[]}).toSorted((t,e)=>e.files.length-t.files.length||t.name.localeCompare(e.name))}(c),f=function(t){const e=new Map;for(const n of t)for(const t of n.files)e.set(t,(e.get(t)??0)+1);return e}(m),d=c.map(t=>{const e=p.get(t.relativeFile)??new Set,n=function(t){const e=t.syntaxFeatures.awaitExpressionCount,n=t.syntaxFeatures.tryStatementCount+t.syntaxFeatures.throwStatementCount,o=t.syntaxFeatures.mutableBindingCount+t.syntaxFeatures.assignmentCount,r=t.cyclomaticComplexity+t.syntaxFeatures.loopStatementCount+t.syntaxFeatures.returnStatementCount,a=t.callGraph.callCount+2*t.callGraph.internalEdgeCount+3*t.callGraph.maxCallDepth;return{asyncBoundaryCount:e,branchingScore:r,exceptionHandlingCount:n,moduleInteractionScore:a,score:2*e+3*n+o+r+a,stateMutationScore:o}}(t.metrics),r=function(t){const e=new Set;return u(e,"class-shapes",t.classCount>0),u(e,"control-flow",t.cognitiveComplexity>0),u(e,"external-dependencies",t.coupling.externalImportCount>0),u(e,"functions",t.functionCount>0),u(e,"local-dependencies",t.coupling.relativeImportCount>0),u(e,"module-api",t.coupling.exportCount>0||t.module.declarations.length>0),u(e,"state-mutation",t.syntaxFeatures.mutableBindingCount+t.syntaxFeatures.assignmentCount>0),u(e,"type-shapes",function(t){return t.typeComplexity.typeAnnotationCount+t.typeComplexity.typeAliasCount+t.typeComplexity.interfaceCount+t.typeComplexity.genericParameterCount+t.typeComplexity.unionTypeCount+t.typeComplexity.intersectionTypeCount+t.typeComplexity.conditionalTypeCount>0}(t)),[...e].toSorted()}(t.metrics);return{file:t.relativeFile,directLocalDependencyCount:e.size,duplicateSymbolGroupCount:f.get(t.relativeFile)??0,structuralBreadthScore:r.length,structuralCoordination:n,structuralFeatureGroups:r,transitiveLocalDependencyCount:o(t.relativeFile,p)}});return{duplicateSymbolGroups:m,files:d,maxDirectLocalDependencyCount:l(d,"directLocalDependencyCount"),maxDuplicateSymbolGroupCount:l(d,"duplicateSymbolGroupCount"),maxStructuralBreadthScore:l(d,"structuralBreadthScore"),maxStructuralCoordinationScore:Math.max(0,...d.map(t=>t.structuralCoordination.score)),maxTransitiveLocalDependencyCount:l(d,"transitiveLocalDependencyCount")}}function n(e,n,o){if(!n.startsWith("."))return;const r=function(e,n){const o=t.dirname(e);if(function(t){return t.startsWith("./")||t.startsWith("../")||t.includes("/")}(n))return[t.normalize(t.join(o,n))];const r=/^(?<dots>\.+)(?<module>.*)$/u.exec(n),a=r?.groups?.dots,i=r?.groups?.module;if(!a||void 0===i)return[];let u=o;for(let e=1;e<a.length;e+=1)u=t.dirname(u);const l=i.replaceAll(".",t.sep);return[t.normalize(t.join(u,l))]}(e,n),a=r.flatMap(e=>{const n=t.extname(e);return n?[e.slice(0,-n.length),e]:[e]});for(const e of a)for(const n of[`${e}.ts`,`${e}.tsx`,`${e}.js`,`${e}.jsx`,`${e}.py`,t.join(e,"index.ts"),t.join(e,"index.tsx"),t.join(e,"index.js"),t.join(e,"__init__.py")])if(o.has(n))return n}function o(t,e){const n=new Set,o=[...e.get(t)??[]];for(;o.length>0;){const t=o.pop();t&&!n.has(t)&&(n.add(t),o.push(...e.get(t)??[]))}return n.size}function r(t){return t.name.length>=5}function a(t,e){return{file:t,line:e.startLine}}function i(t,e){return t.file.localeCompare(e.file)||t.line-e.line}function u(t,e,n){n&&t.add(e)}function l(t,e){return Math.max(0,...t.map(t=>t[e]).filter(t=>"number"==typeof t))}export{e as measureArchitecture};
|
|
2
|
+
//# sourceMappingURL=architectureMetrics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"architectureMetrics.js","sources":["../src/architectureMetrics.ts"],"sourcesContent":["import path from 'node:path';\nimport type { CodeMetrics, DeclarationMetrics } from './types.js';\n\nexport interface ArchitectureSourceFile {\n file: string;\n metrics: CodeMetrics;\n}\n\nexport interface ArchitectureFileMetrics {\n directLocalDependencyCount: number;\n duplicateSymbolGroupCount: number;\n file: string;\n structuralBreadthScore: number;\n structuralCoordination: StructuralCoordinationMetrics;\n structuralFeatureGroups: string[];\n transitiveLocalDependencyCount: number;\n}\n\nexport interface ArchitectureMetrics {\n duplicateSymbolGroups: DuplicateSymbolGroup[];\n files: ArchitectureFileMetrics[];\n maxDirectLocalDependencyCount: number;\n maxDuplicateSymbolGroupCount: number;\n maxStructuralBreadthScore: number;\n maxStructuralCoordinationScore: number;\n maxTransitiveLocalDependencyCount: number;\n}\n\nexport interface DuplicateSymbolGroup {\n declarations: DuplicateSymbolDeclaration[];\n files: string[];\n name: string;\n}\n\nexport interface DuplicateSymbolDeclaration {\n file: string;\n line: number;\n}\n\nexport interface StructuralCoordinationMetrics {\n asyncBoundaryCount: number;\n branchingScore: number;\n exceptionHandlingCount: number;\n moduleInteractionScore: number;\n score: number;\n stateMutationScore: number;\n}\n\ninterface SourceFile {\n file: string;\n metrics: CodeMetrics;\n relativeFile: string;\n}\n\nconst duplicateSymbolNameLengthThreshold = 5;\n\nexport function measureArchitecture(\n files: readonly ArchitectureSourceFile[],\n displayRoot: string\n): ArchitectureMetrics {\n const sourceFiles = files.map((file) => ({\n ...file,\n relativeFile: path.relative(displayRoot, file.file) || path.basename(file.file),\n }));\n const dependencyGraph = measureDependencyGraph(sourceFiles);\n const duplicateSymbolGroups = measureDuplicateSymbolGroups(sourceFiles);\n const duplicateGroupCountByFile = measureDuplicateGroupCountByFile(duplicateSymbolGroups);\n const metrics = sourceFiles.map((sourceFile) => {\n const directDependencies = dependencyGraph.get(sourceFile.relativeFile) ?? new Set<string>();\n const structuralCoordination = measureStructuralCoordination(sourceFile.metrics);\n const structuralFeatureGroups = measureStructuralFeatureGroups(sourceFile.metrics);\n return {\n file: sourceFile.relativeFile,\n directLocalDependencyCount: directDependencies.size,\n duplicateSymbolGroupCount: duplicateGroupCountByFile.get(sourceFile.relativeFile) ?? 0,\n structuralBreadthScore: structuralFeatureGroups.length,\n structuralCoordination,\n structuralFeatureGroups,\n transitiveLocalDependencyCount: measureTransitiveDependencyCount(sourceFile.relativeFile, dependencyGraph),\n };\n });\n\n return {\n duplicateSymbolGroups,\n files: metrics,\n maxDirectLocalDependencyCount: maxFileMetric(metrics, 'directLocalDependencyCount'),\n maxDuplicateSymbolGroupCount: maxFileMetric(metrics, 'duplicateSymbolGroupCount'),\n maxStructuralBreadthScore: maxFileMetric(metrics, 'structuralBreadthScore'),\n maxStructuralCoordinationScore: Math.max(0, ...metrics.map((file) => file.structuralCoordination.score)),\n maxTransitiveLocalDependencyCount: maxFileMetric(metrics, 'transitiveLocalDependencyCount'),\n };\n}\n\nfunction measureDependencyGraph(files: SourceFile[]): Map<string, Set<string>> {\n const fileSet = new Set(files.map((file) => file.relativeFile));\n const graph = new Map<string, Set<string>>();\n for (const file of files) {\n const dependencies = new Set<string>();\n for (const source of file.metrics.module.importSources) {\n const resolved = resolveLocalImport(file.relativeFile, source, fileSet);\n if (resolved) {\n dependencies.add(resolved);\n }\n }\n graph.set(file.relativeFile, dependencies);\n }\n return graph;\n}\n\nfunction resolveLocalImport(fromFile: string, source: string, fileSet: Set<string>): string | undefined {\n if (!source.startsWith('.')) {\n return undefined;\n }\n const bases = localImportBases(fromFile, source);\n const stems = bases.flatMap((base) => {\n const extension = path.extname(base);\n return extension ? [base.slice(0, -extension.length), base] : [base];\n });\n for (const stem of stems) {\n for (const candidate of [\n `${stem}.ts`,\n `${stem}.tsx`,\n `${stem}.js`,\n `${stem}.jsx`,\n `${stem}.py`,\n path.join(stem, 'index.ts'),\n path.join(stem, 'index.tsx'),\n path.join(stem, 'index.js'),\n path.join(stem, '__init__.py'),\n ]) {\n if (fileSet.has(candidate)) {\n return candidate;\n }\n }\n }\n return undefined;\n}\n\nfunction localImportBases(fromFile: string, source: string): string[] {\n const fromDirectory = path.dirname(fromFile);\n if (isPathRelativeImport(source)) {\n return [path.normalize(path.join(fromDirectory, source))];\n }\n\n const match = /^(?<dots>\\.+)(?<module>.*)$/u.exec(source);\n const dots = match?.groups?.dots;\n const moduleName = match?.groups?.module;\n if (!dots || moduleName === undefined) {\n return [];\n }\n\n let baseDirectory = fromDirectory;\n for (let index = 1; index < dots.length; index += 1) {\n baseDirectory = path.dirname(baseDirectory);\n }\n\n const modulePath = moduleName.replaceAll('.', path.sep);\n return [path.normalize(path.join(baseDirectory, modulePath))];\n}\n\nfunction isPathRelativeImport(source: string): boolean {\n return source.startsWith('./') || source.startsWith('../') || source.includes('/');\n}\n\nfunction measureTransitiveDependencyCount(file: string, graph: Map<string, Set<string>>): number {\n const visited = new Set<string>();\n const pending = [...(graph.get(file) ?? [])];\n while (pending.length > 0) {\n const current = pending.pop();\n if (!current || visited.has(current)) {\n continue;\n }\n visited.add(current);\n pending.push(...(graph.get(current) ?? []));\n }\n return visited.size;\n}\n\nfunction measureDuplicateSymbolGroups(files: SourceFile[]): DuplicateSymbolGroup[] {\n const declarationsBySymbol = new Map<string, DuplicateSymbolDeclaration[]>();\n for (const file of files) {\n for (const declaration of file.metrics.module.declarations) {\n if (!isDuplicateSymbolCandidate(declaration)) {\n continue;\n }\n const declarations = declarationsBySymbol.get(declaration.name) ?? [];\n declarations.push(toDuplicateSymbolDeclaration(file.relativeFile, declaration));\n declarationsBySymbol.set(declaration.name, declarations);\n }\n }\n return [...declarationsBySymbol.entries()]\n .flatMap(([name, declarations]) => {\n const duplicateFiles = [...new Set(declarations.map((declaration) => declaration.file))].toSorted();\n return duplicateFiles.length > 1\n ? [{ declarations: declarations.toSorted(compareDuplicateDeclarations), files: duplicateFiles, name }]\n : [];\n })\n .toSorted((left, right) => right.files.length - left.files.length || left.name.localeCompare(right.name));\n}\n\nfunction isDuplicateSymbolCandidate(declaration: DeclarationMetrics): boolean {\n return declaration.name.length >= duplicateSymbolNameLengthThreshold;\n}\n\nfunction toDuplicateSymbolDeclaration(file: string, declaration: DeclarationMetrics): DuplicateSymbolDeclaration {\n return { file, line: declaration.startLine };\n}\n\nfunction compareDuplicateDeclarations(left: DuplicateSymbolDeclaration, right: DuplicateSymbolDeclaration): number {\n return left.file.localeCompare(right.file) || left.line - right.line;\n}\n\nfunction measureDuplicateGroupCountByFile(groups: DuplicateSymbolGroup[]): Map<string, number> {\n const counts = new Map<string, number>();\n for (const group of groups) {\n for (const file of group.files) {\n counts.set(file, (counts.get(file) ?? 0) + 1);\n }\n }\n return counts;\n}\n\nfunction measureStructuralCoordination(metrics: CodeMetrics): StructuralCoordinationMetrics {\n const asyncBoundaryCount = metrics.syntaxFeatures.awaitExpressionCount;\n const exceptionHandlingCount = metrics.syntaxFeatures.tryStatementCount + metrics.syntaxFeatures.throwStatementCount;\n const stateMutationScore = metrics.syntaxFeatures.mutableBindingCount + metrics.syntaxFeatures.assignmentCount;\n const branchingScore =\n metrics.cyclomaticComplexity +\n metrics.syntaxFeatures.loopStatementCount +\n metrics.syntaxFeatures.returnStatementCount;\n const moduleInteractionScore =\n metrics.callGraph.callCount + metrics.callGraph.internalEdgeCount * 2 + metrics.callGraph.maxCallDepth * 3;\n\n return {\n asyncBoundaryCount,\n branchingScore,\n exceptionHandlingCount,\n moduleInteractionScore,\n score:\n asyncBoundaryCount * 2 +\n exceptionHandlingCount * 3 +\n stateMutationScore +\n branchingScore +\n moduleInteractionScore,\n stateMutationScore,\n };\n}\n\nfunction measureStructuralFeatureGroups(metrics: CodeMetrics): string[] {\n const groups = new Set<string>();\n addGroup(groups, 'class-shapes', metrics.classCount > 0);\n addGroup(groups, 'control-flow', metrics.cognitiveComplexity > 0);\n addGroup(groups, 'external-dependencies', metrics.coupling.externalImportCount > 0);\n addGroup(groups, 'functions', metrics.functionCount > 0);\n addGroup(groups, 'local-dependencies', metrics.coupling.relativeImportCount > 0);\n addGroup(groups, 'module-api', metrics.coupling.exportCount > 0 || metrics.module.declarations.length > 0);\n addGroup(\n groups,\n 'state-mutation',\n metrics.syntaxFeatures.mutableBindingCount + metrics.syntaxFeatures.assignmentCount > 0\n );\n addGroup(groups, 'type-shapes', hasTypeShapeMetrics(metrics));\n return [...groups].toSorted();\n}\n\nfunction addGroup(groups: Set<string>, group: string, condition: boolean): void {\n if (condition) {\n groups.add(group);\n }\n}\n\nfunction hasTypeShapeMetrics(metrics: CodeMetrics): boolean {\n return (\n metrics.typeComplexity.typeAnnotationCount +\n metrics.typeComplexity.typeAliasCount +\n metrics.typeComplexity.interfaceCount +\n metrics.typeComplexity.genericParameterCount +\n metrics.typeComplexity.unionTypeCount +\n metrics.typeComplexity.intersectionTypeCount +\n metrics.typeComplexity.conditionalTypeCount >\n 0\n );\n}\n\nfunction maxFileMetric(metrics: ArchitectureFileMetrics[], key: keyof ArchitectureFileMetrics): number {\n return Math.max(\n 0,\n ...metrics.map((metric) => metric[key]).filter((value): value is number => typeof value === 'number')\n );\n}\n"],"names":["measureArchitecture","files","displayRoot","sourceFiles","map","file","relativeFile","path","relative","basename","dependencyGraph","fileSet","Set","graph","Map","dependencies","source","metrics","module","importSources","resolved","resolveLocalImport","add","set","measureDependencyGraph","duplicateSymbolGroups","declarationsBySymbol","declaration","declarations","isDuplicateSymbolCandidate","get","name","push","toDuplicateSymbolDeclaration","entries","flatMap","duplicateFiles","toSorted","length","compareDuplicateDeclarations","left","right","localeCompare","measureDuplicateSymbolGroups","duplicateGroupCountByFile","groups","counts","group","measureDuplicateGroupCountByFile","sourceFile","directDependencies","structuralCoordination","asyncBoundaryCount","syntaxFeatures","awaitExpressionCount","exceptionHandlingCount","tryStatementCount","throwStatementCount","stateMutationScore","mutableBindingCount","assignmentCount","branchingScore","cyclomaticComplexity","loopStatementCount","returnStatementCount","moduleInteractionScore","callGraph","callCount","internalEdgeCount","maxCallDepth","score","measureStructuralCoordination","structuralFeatureGroups","addGroup","classCount","cognitiveComplexity","coupling","externalImportCount","functionCount","relativeImportCount","exportCount","typeComplexity","typeAnnotationCount","typeAliasCount","interfaceCount","genericParameterCount","unionTypeCount","intersectionTypeCount","conditionalTypeCount","hasTypeShapeMetrics","measureStructuralFeatureGroups","directLocalDependencyCount","size","duplicateSymbolGroupCount","structuralBreadthScore","transitiveLocalDependencyCount","measureTransitiveDependencyCount","maxDirectLocalDependencyCount","maxFileMetric","maxDuplicateSymbolGroupCount","maxStructuralBreadthScore","maxStructuralCoordinationScore","Math","max","maxTransitiveLocalDependencyCount","fromFile","startsWith","bases","fromDirectory","dirname","includes","isPathRelativeImport","normalize","join","match","exec","dots","moduleName","undefined","baseDirectory","index","modulePath","replaceAll","sep","localImportBases","stems","base","extension","extname","slice","stem","candidate","has","visited","pending","current","pop","line","startLine","condition","key","metric","filter","value"],"mappings":"yBAwDO,SAASA,EACdC,EACAC,GAEA,MAAMC,EAAcF,EAAMG,IAAKC,IAAI,IAC9BA,EACHC,aAAcC,EAAKC,SAASN,EAAaG,EAAKA,OAASE,EAAKE,SAASJ,EAAKA,SAEtEK,EA6BR,SAAgCT,GAC9B,MAAMU,EAAU,IAAIC,IAAIX,EAAMG,IAAKC,GAASA,EAAKC,eAC3CO,EAAQ,IAAIC,IAClB,IAAK,MAAMT,KAAQJ,EAAO,CACxB,MAAMc,EAAe,IAAIH,IACzB,IAAK,MAAMI,KAAUX,EAAKY,QAAQC,OAAOC,cAAe,CACtD,MAAMC,EAAWC,EAAmBhB,EAAKC,aAAcU,EAAQL,GAC3DS,GACFL,EAAaO,IAAIF,EAErB,CACAP,EAAMU,IAAIlB,EAAKC,aAAcS,EAC/B,CACA,OAAOF,CACT,CA3C0BW,CAAuBrB,GACzCsB,EAiHR,SAAsCxB,GACpC,MAAMyB,EAAuB,IAAIZ,IACjC,IAAK,MAAMT,KAAQJ,EACjB,IAAK,MAAM0B,KAAetB,EAAKY,QAAQC,OAAOU,aAAc,CAC1D,IAAKC,EAA2BF,GAC9B,SAEF,MAAMC,EAAeF,EAAqBI,IAAIH,EAAYI,OAAS,GACnEH,EAAaI,KAAKC,EAA6B5B,EAAKC,aAAcqB,IAClED,EAAqBH,IAAII,EA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AAMwH,EAAU,IAAIzH,IACd0H,EAAU,IAAKzH,EAAMiB,IAAIzB,IAAS,IACxC,KAAOiI,EAAQhG,OAAS,GAAG,CACzB,MAAMiG,EAAUD,EAAQE,MACnBD,IAAWF,EAAQD,IAAIG,KAG5BF,EAAQ/G,IAAIiH,GACZD,EAAQtG,QAASnB,EAAMiB,IAAIyG,IAAY,IACzC,CACA,OAAOF,EAAQzC,IACjB,CAwBA,SAAS/D,EAA2BF,GAClC,OAAOA,EAAYI,KAAKO,QAnJiB,CAoJ3C,CAEA,SAASL,EAA6B5B,EAAcsB,GAClD,MAAO,CAAEtB,OAAMoI,KAAM9G,EAAY+G,UACnC,CAEA,SAASnG,EAA6BC,EAAkCC,GACtE,OAAOD,EAAKnC,KAAKqC,cAAcD,EAAMpC,OAASmC,EAAKiG,KAAOhG,EAAMgG,IAClE,CAuDA,SAAShE,EAAS5B,EAAqBE,EAAe4F,GAChDA,GACF9F,EAAOvB,IAAIyB,EAEf,CAeA,SAASmD,EAAcjF,EAAoC2H,GACzD,OAAOtC,KAAKC,IACV,KACGtF,EAAQb,IAAKyI,GAAWA,EAAOD,IAAME,OAAQC,GAA4C,iBAAVA,GAEtF"}
|
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var t=require("node:fs/promises"),e=require("node:os"),n=require("node:path"),i=require("commander"),o=require("./architectureMetrics.cjs"),r=require("./cliConfig.cjs"),a=require("./metrics.cjs"),c=require("./typescriptProject.cjs");const s=new Map([[".cjs","javascript"],[".cts","typescript"],[".go","go"],[".js","javascript"],[".jsx","jsx"],[".mjs","javascript"],[".mts","typescript"],[".py","python"],[".ts","typescript"],[".tsx","tsx"]]),l=new Set([".agents",".claude",".cursor",".git",".next",".playwright-cli",".tox",".tmp",".turbo",".venv",".yarn","__fixtures__","__generated__","__pycache__","coverage","dist","fixtures","generated","node_modules","test-fixtures","vendor","venv"]),u=new Set(["__tests__","test","tests"]),m=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-]test)\.[^.]+$/iu;function p(t){return"~"===t?e.homedir():t.startsWith("~/")?n.join(e.homedir(),t.slice(2)):n.resolve(t)}async function d(e){try{return(await t.stat(e)).isFile()}catch{return!1}}async function f(e,i,o,r,a,c,s){let l,u;try{l=await t.realpath(e)}catch(t){return void r.push(`${R(e,s)}: ${T(t)}`)}if(E(l,s)&&!a.has(l)){a.add(l);try{u=await t.readdir(e,{withFileTypes:!0})}catch(t){return void r.push(`${R(e,s)}: ${T(t)}`)}for(const t of u){const l=n.join(e,t.name);if(t.isSymbolicLink())await h(t.name,l,i,o,r,a,c,s);else if(t.isDirectory()){if(_(t.name,i))continue;await f(l,i,o,r,a,c,s)}else t.isFile()&&await y(l,i,o,r,c,s)}}}async function h(e,i,o,r,a,c,s,l){let u,m;try{u=await t.realpath(i)}catch(t){return void a.push(`${R(i,l)}: ${T(t)}`)}if(E(u,l)){try{m=await t.stat(i)}catch(t){return void a.push(`${R(i,l)}: ${T(t)}`)}if(m.isDirectory()){if(_(e,o)||_(n.basename(u),o))return;await f(i,o,r,a,c,s,l)}else m.isFile()&&await y(i,o,r,a,s,l,u,u)}}async function y(t,e,n,i,o,r,a=t,c){const s=M(a,e);s&&await g(t,s,n,i,o,r,c)}async function g(e,n,i,o,r,c,s){try{const o=s??await t.realpath(e);if(r.has(o))return;r.add(o);const c=await t.readFile(e,"utf8");i.push({file:e,metrics:a.measureCode(c,{language:n})})}catch(t){o.push(`${R(e,c)}: ${T(t)}`)}}function C(t,e,n,i,o){const r=[],a=R(t,o);if($(r,"file LOC",e.lines.code,i.fileLoc),$(r,"import sources",e.coupling.importSourceCount,i.import),$(r,"duplicated blocks",e.duplication.duplicateBlockCount,i.duplicateBlock),n){(e.lines.code>=100||n.directLocalDependencyCount>=8)&&$(r,"transitive local dependencies",n.transitiveLocalDependencyCount,i.transitiveDependency),(r.length>0||n.directLocalDependencyCount>=8||n.structuralCoordination.score>=i.structuralCoordination)&&$(r,"structural breadth",n.structuralBreadthScore,i.structuralBreadth),$(r,"structural coordination",n.structuralCoordination.score,i.structuralCoordination),$(r,"state mutation",n.structuralCoordination.stateMutationScore,i.stateMutation),$(r,"duplicate symbol groups",n.duplicateSymbolGroupCount,i.duplicateSymbolGroup)}return 0===r.length?[]:[{file:a,language:e.language,kind:"file",cyclomaticComplexity:e.cyclomaticComplexity,cognitiveComplexity:e.cognitiveComplexity,triggers:r,score:b(r)}]}function $(t,e,n,i){n<i||t.push({metric:e,value:n,threshold:i,score:n/i})}function x(t,e,n,i){return n?.has(v(t,e.startLine,e.startColumn))||!!e.name&&i?.has(w(t,e.name,e.startLine))||!1}function v(t,e,i){return`${n.resolve(t)}:${e}:${i}`}function w(t,e,i){return`${n.resolve(t)}:${e}:${i}`}function b(t){return Math.max(...t.map(t=>t.score))}function j(t,e){return e.score-t.score||t.file.localeCompare(e.file)||(t.startLine??0)-(e.startLine??0)||(t.endLine??0)-(e.endLine??0)||t.kind.localeCompare(e.kind)}function L(t){return void 0===t.startLine||void 0===t.endLine?t.file:`${t.file}:${t.startLine}-${t.endLine}`}function S(t){return t.name?`${t.kind} ${t.name}`:t.kind}function k(t){return`(${t.triggers.map(t=>`${t.metric} ${O(t.value)} >= ${O(t.threshold)}`).join(", ")}; cyclomatic ${t.cyclomaticComplexity}, cognitive ${t.cognitiveComplexity})`}function O(t){return Number.isInteger(t)?String(t):t.toFixed(2)}function F(t){let e=0,n=0,i=0,o=0,r=0,a=0,c=0,s=0,l=0,u=0,m=0,p=0,d=0,f=0,h=0,y=0;for(const g of t)e+=g.metrics.functionCount,n+=g.metrics.lines.code,i=Math.max(i,g.metrics.maxCyclomaticComplexity),o=Math.max(o,g.metrics.maxCognitiveComplexity),r+=g.metrics.callGraph.callCount,a+=g.metrics.callGraph.internalCallCount,c=Math.max(c,g.metrics.callGraph.maxCallDepth),s+=g.metrics.coupling.importSourceCount,l+=g.metrics.coupling.relativeImportCount,u+=g.metrics.coupling.externalImportCount,m+=g.metrics.coupling.exportCount,p+=g.metrics.cohesion.averageFunctionIdentifierOverlap,d+=g.metrics.typeComplexity.typeAnnotationCount,f+=g.metrics.typeComplexity.typeAliasCount,h+=g.metrics.typeComplexity.interfaceCount,y+=g.metrics.typeComplexity.genericParameterCount;return{fileCount:t.length,functionCount:e,linesOfCode:n,maxCyclomaticComplexity:i,maxCognitiveComplexity:o,callCount:r,internalCallCount:a,maxCallDepth:c,importSourceCount:s,relativeImportCount:l,externalImportCount:u,exportCount:m,averageFunctionIdentifierOverlap:0===t.length?0:p/t.length,typeAnnotationCount:d,typeAliasCount:f,interfaceCount:h,genericParameterCount:y}}function _(t,e){return!!l.has(t)||!e.includeTests&&u.has(t)}function E(t,e){const i=n.relative(e,t);return""===i||".."!==i&&!i.startsWith(`..${n.sep}`)&&!n.isAbsolute(i)}function M(t,e,i=!1){const o=t.toLowerCase();if((i||!(o.endsWith(".d.ts")||o.endsWith(".d.mts")||o.endsWith(".d.cts")||o.endsWith(".min.js")||o.endsWith(".pnp.cjs")))&&(i||e.includeTests||!m.test(n.basename(t))))return s.get(n.extname(o))}function D(t){if(!/^[1-9]\d*$/u.test(t))throw new i.InvalidArgumentError("Expected a positive integer.");const e=Number(t);if(!Number.isSafeInteger(e)||e<1)throw new i.InvalidArgumentError("Expected a positive integer.");return e}function R(t,e){return n.relative(e,t)||n.basename(t)}function A(t){process.stdout.write(t)}function P(t){process.stderr.write(t)}function T(t){return t instanceof Error?t.message:String(t)}(async function(){const e=(new i.Command).name("code-gauge").description("Measure code metrics and list high-risk findings.").argument("[target]","file or directory to measure",".").option("--config <path>",`config file to use instead of the auto-detected ${r.configFileName}`).option("--file-loc-threshold <number>","minimum file code LOC to report",D).option("--function-loc-threshold <number>","minimum function physical LOC span to report",D).option("--component-loc-threshold <number>","minimum React component physical LOC span to report",D).option("--cognitive-threshold <number>","minimum cognitive complexity to report",D).option("--cyclomatic-threshold <number>","minimum cyclomatic complexity to report",D).option("--call-threshold <number>","minimum function call count to report",D).option("--import-threshold <number>","minimum unique import sources per file to report",D).option("--fan-out-threshold <number>","minimum intra-file fan-out per function to report",D).option("--parameter-threshold <number>","minimum function parameter count to report",D).option("--duplicate-block-threshold <number>","minimum count of duplicated code blocks per file to report",D).option("--transitive-dependency-threshold <number>","minimum transitively reachable local files to report",D).option("--structural-breadth-threshold <number>","minimum structural breadth score to report",D).option("--structural-coordination-threshold <number>","minimum structural coordination score to report",D).option("--state-mutation-threshold <number>","minimum state mutation score to report",D).option("--duplicate-symbol-group-threshold <number>","minimum duplicate symbol group count to report",D).option("--max-findings <number>","maximum number of risk findings to print",D).option("--include-tests","include test files and test directories").option("--tsconfig <path>","TypeScript project file to use instead of auto-detected tsconfig.json").option("--json","print JSON output").option("--fail-on-error","exit with code 1 when files or directories cannot be scanned").option("--fail-on-risk","exit with code 1 when high-risk findings are found");e.action(async(e,i)=>{const a=p(e),s=await r.loadConfig(i.config,await async function(e){try{return(await t.stat(e)).isDirectory()?e:n.dirname(e)}catch{return n.dirname(e)}}(a)),l=r.resolveOptions(i,s),u=await async function(e,i){const o=[],r=[],a=new Set;let c=e;try{c=await t.realpath(e)}catch{}const s=n.dirname(c);let l;try{l=await t.stat(c)}catch(t){const e=`${R(c,s)}: ${T(t)}`;return{displayRoot:s,files:o,errors:[e],fatalError:e}}if(l.isFile()){const t=n.dirname(c),e=M(c,i,!0);if(!e){const e=`${R(c,t)}: unsupported file type`;return{displayRoot:t,files:o,errors:[e],fatalError:e}}return await g(c,e,o,r,a,t,c),{displayRoot:t,files:o,errors:r}}return await f(c,i,o,r,new Set,a,c),{displayRoot:c,files:o,errors:r}}(a,l);await async function(t){if(t.fatalError)return;try{t.architecture=o.measureArchitecture(t.files.map(({file:t,metrics:e})=>({file:t,metrics:e})),t.displayRoot)}catch(e){t.errors.push(`architecture metrics: ${T(e)}`)}}(u),await async function(e,i,o){if(e.fatalError)return;if(0===e.files.length)return;const r=i.tsconfig,a=void 0!==r;if(!a&&!e.files.some(({file:t})=>function(t){return[".cjs",".cts",".js",".jsx",".mjs",".mts",".ts",".tsx"].includes(n.extname(t))}(t)))return;const s=r?p(r):await async function(e){const i=await t.stat(e);let o=i.isDirectory()?e:n.dirname(e);for(;;){const t=n.join(o,"tsconfig.json");if(await d(t))return t;const e=n.dirname(o);if(e===o)return;o=e}}(o);if(!s)return;try{e.typeScriptProject=await c.measureTypeScriptProject(s,e.files.map(({file:t})=>t)),e.componentFunctionKeys=new Set(e.typeScriptProject.reactComponentFunctions.map(t=>v(t.file,t.startLine,t.startColumn))),e.namedComponentFunctionKeys=new Set(e.typeScriptProject.reactComponentFunctions.flatMap(t=>t.name?[w(t.file,t.name,t.startLine)]:[]))}catch(t){a&&e.errors.push(`${R(s,e.displayRoot)}: ${T(t)}`)}}(u,l,a);const m=function(t,e,n,i,o,a){const c=new Map(e?.files.map(t=>[t.file,t])),s=t.flatMap(({file:t,metrics:e})=>{const s=e.functions.some(e=>e.returnsJsx||x(t,e,n,i)),l=r.resolveThresholds(o,e.language,s);return[...C(t,e,c.get(R(t,a)),l,a),...e.functions.flatMap(o=>function(t,e,n,i,o,r,a){const c=n.endLine-n.startLine+1,s=x(t,n,r,a),l=s?"component":"function",u=[];if($(u,"cognitive complexity",n.cognitiveComplexity,i.cognitive),$(u,"cyclomatic complexity",n.cyclomaticComplexity,i.cyclomatic),$(u,s?"component LOC":"function LOC",c,function(t,e){return t?e.componentLoc:e.functionLoc}(s,i)),$(u,"function calls",n.callCount,i.call),$(u,"fan-out",n.fanOut,i.fanOut),$(u,"parameters",n.parameterCount,i.parameter),0===u.length)return[];return[{file:R(t,o),language:e,kind:l,name:n.name??"<anonymous>",startLine:n.startLine,endLine:n.endLine,cyclomaticComplexity:n.cyclomaticComplexity,cognitiveComplexity:n.cognitiveComplexity,triggers:u,score:b(u)}]}(t,e.language,o,l,a,n,i))]});return s.sort(j),s}(u.files,u.architecture,u.componentFunctionKeys,u.namedComponentFunctionKeys,l,u.displayRoot);l.json?function(t,e,n){const i=F(t.files),o=e.slice(0,n.maxFindings);A(JSON.stringify({summary:i,thresholds:n.thresholds,profileThresholds:n.profileThresholds,totalRisks:e.length,truncated:o.length<e.length,architecture:t.architecture,typeScriptProject:t.typeScriptProject,risks:o,errors:t.errors},void 0,2)+"\n")}(u,m,l):function(t,e,n,i){if(e.fatalError)return void P(`Error: ${e.fatalError}\n`);const{thresholds:o}=i,r=F(e.files);A(`Measured ${r.fileCount} files under ${t}\n`),A(`LOC ${r.linesOfCode}, functions ${r.functionCount}, max cyclomatic ${r.maxCyclomaticComplexity}, max cognitive ${r.maxCognitiveComplexity}\n`),A(`Calls ${r.callCount}, internal edges ${r.internalCallCount}, max call depth ${r.maxCallDepth}, imports ${r.importSourceCount}, exports ${r.exportCount}\n`),A(`Type annotations ${r.typeAnnotationCount}, type aliases ${r.typeAliasCount}, interfaces ${r.interfaceCount}, avg cohesion ${r.averageFunctionIdentifierOverlap.toFixed(2)}\n`),e.architecture&&A(`${function(t){const e=Math.max(0,...t.files.map(t=>t.structuralCoordination.stateMutationScore));return`Architecture max reachable files ${t.maxTransitiveLocalDependencyCount}, max structural breadth ${t.maxStructuralBreadthScore}, max structural coordination ${t.maxStructuralCoordinationScore}, max state mutation ${e}, duplicate symbol groups ${t.duplicateSymbolGroups.length}`}(e.architecture)}\n`);e.typeScriptProject&&A(`${function(t){return`TypeScript project root files ${t.rootFileCount}, measured roots ${t.measuredRootFileCount}, semantic diagnostics ${t.semanticDiagnosticCount}, resolved calls ${t.resolvedCallExpressionCount}/${t.callExpressionCount} (${(100*t.resolvedCallExpressionRatio).toFixed(1)}%)`}(e.typeScriptProject)}\n`);A(`Risk thresholds: file LOC >= ${o.fileLoc}, function LOC >= ${o.functionLoc}, component LOC >= ${o.componentLoc}, cognitive >= ${o.cognitive}, cyclomatic >= ${o.cyclomatic}, calls >= ${o.call}, imports >= ${o.import}, fan-out >= ${o.fanOut}, parameters >= ${o.parameter}, duplicated blocks >= ${o.duplicateBlock}\n`);const a=(c=i.profileThresholds,Object.entries(c).map(([t,e])=>`${t} { ${Object.entries(e).map(([t,e])=>`${t} ${e}`).join(", ")} }`).join("; "));var c;a&&A(`Per-language overrides: ${a}\n`);if(0===n.length)A("No high-risk findings found.\n");else{const t=n.slice(0,i.maxFindings),e=n.length>t.length?` of ${n.length}`:"";A(`\nHigh-risk findings (top ${t.length}${e}):\n`);for(const e of t)A(`${L(e)} ${S(e)} ${k(e)}\n`)}if(e.errors.length>0){P(`\nSkipped ${e.errors.length} files or directories:\n`);for(const t of e.errors.slice(0,10))P(`- ${t}\n`);e.errors.length>10&&P(`- ... ${e.errors.length-10} more\n`)}}(a,u,m,l),(u.fatalError||l.failOnError&&u.errors.length>0||l.failOnRisk&&m.length>0)&&(process.exitCode=1)}),await e.parseAsync()})().catch(t=>{P(`Error: ${T(t)}\n`),process.exitCode=1});
|
|
3
|
+
//# sourceMappingURL=cli.cjs.map
|