@aiready/testability 0.1.5 → 0.1.8

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.
@@ -1,6 +1,6 @@
1
1
 
2
2
  
3
- > @aiready/testability@0.1.5 build /Users/pengcao/projects/aiready/packages/testability
3
+ > @aiready/testability@0.1.8 build /Users/pengcao/projects/aiready/packages/testability
4
4
  > tsup src/index.ts src/cli.ts --format cjs,esm --dts
5
5
 
6
6
  CLI Building entry: src/cli.ts, src/index.ts
@@ -9,16 +9,16 @@
9
9
  CLI Target: es2020
10
10
  CJS Build start
11
11
  ESM Build start
12
- CJS dist/cli.js 19.50 KB
13
- CJS dist/index.js 12.85 KB
14
- CJS ⚡️ Build success in 379ms
15
12
  ESM dist/index.mjs 152.00 B
16
- ESM dist/chunk-CYZ7DTWN.mjs 11.64 KB
17
- ESM dist/cli.mjs 6.24 KB
18
- ESM ⚡️ Build success in 402ms
13
+ ESM dist/cli.mjs 6.37 KB
14
+ ESM dist/chunk-DDNB7FI4.mjs 10.93 KB
15
+ ESM ⚡️ Build success in 89ms
16
+ CJS dist/cli.js 18.89 KB
17
+ CJS dist/index.js 12.12 KB
18
+ CJS ⚡️ Build success in 115ms
19
19
  DTS Build start
20
- DTS ⚡️ Build success in 23828ms
20
+ DTS ⚡️ Build success in 10647ms
21
21
  DTS dist/cli.d.ts 20.00 B
22
- DTS dist/index.d.ts 2.54 KB
22
+ DTS dist/index.d.ts 2.64 KB
23
23
  DTS dist/cli.d.mts 20.00 B
24
- DTS dist/index.d.mts 2.54 KB
24
+ DTS dist/index.d.mts 2.64 KB
@@ -0,0 +1,5 @@
1
+
2
+ 
3
+ > @aiready/testability@0.1.6 lint /Users/pengcao/projects/aiready/packages/testability
4
+ > eslint src
5
+
@@ -1,18 +1,17 @@
1
1
 
2
2
  
3
- > @aiready/testability@0.1.5 test /Users/pengcao/projects/aiready/packages/testability
3
+ > @aiready/testability@0.1.8 test /Users/pengcao/projects/aiready/packages/testability
4
4
  > vitest run
5
5
 
6
6
  [?25l
7
7
   RUN  v4.0.18 /Users/pengcao/projects/aiready/packages/testability
8
8
 
9
- ✓ src/__tests__/analyzer.test.ts (3 tests) 1236ms
10
- ✓ should calculate ratio of test files to source files  732ms
11
- ✓ should detect interfaces with too many methods  473ms
9
+ ✓ src/__tests__/analyzer.test.ts (3 tests) 559ms
10
+ ✓ should calculate ratio of test files to source files  376ms
12
11
 
13
12
   Test Files  1 passed (1)
14
13
   Tests  3 passed (3)
15
-  Start at  14:38:43
16
-  Duration  21.61s (transform 5.52s, setup 0ms, import 17.77s, tests 1.24s, environment 1ms)
14
+  Start at  00:56:24
15
+  Duration  4.86s (transform 1.13s, setup 0ms, import 3.38s, tests 559ms, environment 0ms)
17
16
 
18
17
  [?25h
@@ -0,0 +1,332 @@
1
+ // src/analyzer.ts
2
+ import { scanFiles, calculateTestabilityIndex } from "@aiready/core";
3
+ import { readFileSync, existsSync } from "fs";
4
+ import { join } from "path";
5
+ import { parse } from "@typescript-eslint/typescript-estree";
6
+ function countMethodsInInterface(node) {
7
+ if (node.type === "TSInterfaceDeclaration") {
8
+ return node.body.body.filter(
9
+ (m) => m.type === "TSMethodSignature" || m.type === "TSPropertySignature"
10
+ ).length;
11
+ }
12
+ if (node.type === "TSTypeAliasDeclaration" && node.typeAnnotation.type === "TSTypeLiteral") {
13
+ return node.typeAnnotation.members.length;
14
+ }
15
+ return 0;
16
+ }
17
+ function hasDependencyInjection(node) {
18
+ for (const member of node.body.body) {
19
+ if (member.type === "MethodDefinition" && member.key.type === "Identifier" && member.key.name === "constructor") {
20
+ const fn = member.value;
21
+ if (fn.params && fn.params.length > 0) {
22
+ const typedParams = fn.params.filter((p) => {
23
+ const param = p;
24
+ return param.typeAnnotation != null || param.parameter?.typeAnnotation != null;
25
+ });
26
+ if (typedParams.length > 0) return true;
27
+ }
28
+ }
29
+ }
30
+ return false;
31
+ }
32
+ function isPureFunction(fn) {
33
+ let hasReturn = false;
34
+ let hasSideEffect = false;
35
+ function walk(node) {
36
+ if (node.type === "ReturnStatement" && node.argument) hasReturn = true;
37
+ if (node.type === "AssignmentExpression" && node.left.type === "MemberExpression")
38
+ hasSideEffect = true;
39
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && ["console", "process", "window", "document", "fs"].includes(
40
+ node.callee.object.name
41
+ ))
42
+ hasSideEffect = true;
43
+ for (const key of Object.keys(node)) {
44
+ if (key === "parent") continue;
45
+ const child = node[key];
46
+ if (child && typeof child === "object") {
47
+ if (Array.isArray(child)) {
48
+ child.forEach((c) => c?.type && walk(c));
49
+ } else if (child.type) {
50
+ walk(child);
51
+ }
52
+ }
53
+ }
54
+ }
55
+ if (fn.body?.type === "BlockStatement") {
56
+ fn.body.body.forEach((s) => walk(s));
57
+ } else if (fn.body) {
58
+ hasReturn = true;
59
+ }
60
+ return hasReturn && !hasSideEffect;
61
+ }
62
+ function hasExternalStateMutation(fn) {
63
+ let found = false;
64
+ function walk(node) {
65
+ if (found) return;
66
+ if (node.type === "AssignmentExpression" && node.left.type === "MemberExpression")
67
+ found = true;
68
+ for (const key of Object.keys(node)) {
69
+ if (key === "parent") continue;
70
+ const child = node[key];
71
+ if (child && typeof child === "object") {
72
+ if (Array.isArray(child)) child.forEach((c) => c?.type && walk(c));
73
+ else if (child.type) walk(child);
74
+ }
75
+ }
76
+ }
77
+ if (fn.body?.type === "BlockStatement") fn.body.body.forEach((s) => walk(s));
78
+ return found;
79
+ }
80
+ function analyzeFileTestability(filePath) {
81
+ const result = {
82
+ pureFunctions: 0,
83
+ totalFunctions: 0,
84
+ injectionPatterns: 0,
85
+ totalClasses: 0,
86
+ bloatedInterfaces: 0,
87
+ totalInterfaces: 0,
88
+ externalStateMutations: 0
89
+ };
90
+ let code;
91
+ try {
92
+ code = readFileSync(filePath, "utf-8");
93
+ } catch {
94
+ return result;
95
+ }
96
+ let ast;
97
+ try {
98
+ ast = parse(code, {
99
+ jsx: filePath.endsWith(".tsx") || filePath.endsWith(".jsx"),
100
+ range: false,
101
+ loc: false
102
+ });
103
+ } catch {
104
+ return result;
105
+ }
106
+ function visit(node) {
107
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
108
+ result.totalFunctions++;
109
+ if (isPureFunction(node)) result.pureFunctions++;
110
+ if (hasExternalStateMutation(node)) result.externalStateMutations++;
111
+ }
112
+ if (node.type === "ClassDeclaration" || node.type === "ClassExpression") {
113
+ result.totalClasses++;
114
+ if (hasDependencyInjection(node)) result.injectionPatterns++;
115
+ }
116
+ if (node.type === "TSInterfaceDeclaration" || node.type === "TSTypeAliasDeclaration") {
117
+ result.totalInterfaces++;
118
+ const methodCount = countMethodsInInterface(node);
119
+ if (methodCount > 10) result.bloatedInterfaces++;
120
+ }
121
+ for (const key of Object.keys(node)) {
122
+ if (key === "parent") continue;
123
+ const child = node[key];
124
+ if (child && typeof child === "object") {
125
+ if (Array.isArray(child)) child.forEach((c) => c?.type && visit(c));
126
+ else if (child.type) visit(child);
127
+ }
128
+ }
129
+ }
130
+ ast.body.forEach(visit);
131
+ return result;
132
+ }
133
+ function detectTestFramework(rootDir) {
134
+ const pkgPath = join(rootDir, "package.json");
135
+ if (!existsSync(pkgPath)) return false;
136
+ try {
137
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
138
+ const allDeps = {
139
+ ...pkg.dependencies ?? {},
140
+ ...pkg.devDependencies ?? {}
141
+ };
142
+ const testFrameworks = [
143
+ "jest",
144
+ "vitest",
145
+ "mocha",
146
+ "jasmine",
147
+ "ava",
148
+ "tap",
149
+ "pytest",
150
+ "unittest"
151
+ ];
152
+ return testFrameworks.some((fw) => allDeps[fw]);
153
+ } catch {
154
+ return false;
155
+ }
156
+ }
157
+ var TEST_PATTERNS = [
158
+ /\.(test|spec)\.(ts|tsx|js|jsx)$/,
159
+ /__tests__\//,
160
+ /\/tests?\//,
161
+ /\/e2e\//,
162
+ /\/fixtures\//
163
+ ];
164
+ function isTestFile(filePath, extra) {
165
+ if (TEST_PATTERNS.some((p) => p.test(filePath))) return true;
166
+ if (extra) return extra.some((p) => filePath.includes(p));
167
+ return false;
168
+ }
169
+ async function analyzeTestability(options) {
170
+ const allFiles = await scanFiles({
171
+ ...options,
172
+ include: options.include || ["**/*.{ts,tsx,js,jsx}"]
173
+ });
174
+ const sourceFiles = allFiles.filter(
175
+ (f) => !isTestFile(f, options.testPatterns)
176
+ );
177
+ const testFiles = allFiles.filter((f) => isTestFile(f, options.testPatterns));
178
+ const aggregated = {
179
+ pureFunctions: 0,
180
+ totalFunctions: 0,
181
+ injectionPatterns: 0,
182
+ totalClasses: 0,
183
+ bloatedInterfaces: 0,
184
+ totalInterfaces: 0,
185
+ externalStateMutations: 0
186
+ };
187
+ let processed = 0;
188
+ for (const f of sourceFiles) {
189
+ processed++;
190
+ options.onProgress?.(
191
+ processed,
192
+ sourceFiles.length,
193
+ `testability: analyzing files`
194
+ );
195
+ const a = analyzeFileTestability(f);
196
+ for (const key of Object.keys(aggregated)) {
197
+ aggregated[key] += a[key];
198
+ }
199
+ }
200
+ const hasTestFramework = detectTestFramework(options.rootDir);
201
+ const indexResult = calculateTestabilityIndex({
202
+ testFiles: testFiles.length,
203
+ sourceFiles: sourceFiles.length,
204
+ pureFunctions: aggregated.pureFunctions,
205
+ totalFunctions: Math.max(1, aggregated.totalFunctions),
206
+ injectionPatterns: aggregated.injectionPatterns,
207
+ totalClasses: Math.max(1, aggregated.totalClasses),
208
+ bloatedInterfaces: aggregated.bloatedInterfaces,
209
+ totalInterfaces: Math.max(1, aggregated.totalInterfaces),
210
+ externalStateMutations: aggregated.externalStateMutations,
211
+ hasTestFramework
212
+ });
213
+ const issues = [];
214
+ const minCoverage = options.minCoverageRatio ?? 0.3;
215
+ const actualRatio = sourceFiles.length > 0 ? testFiles.length / sourceFiles.length : 0;
216
+ if (!hasTestFramework) {
217
+ issues.push({
218
+ type: "low-testability",
219
+ dimension: "framework",
220
+ severity: "critical",
221
+ message: "No testing framework detected in package.json \u2014 AI changes cannot be verified at all.",
222
+ location: { file: options.rootDir, line: 0 },
223
+ suggestion: "Add Jest, Vitest, or another testing framework as a devDependency."
224
+ });
225
+ }
226
+ if (actualRatio < minCoverage) {
227
+ const needed = Math.ceil(sourceFiles.length * minCoverage) - testFiles.length;
228
+ issues.push({
229
+ type: "low-testability",
230
+ dimension: "test-coverage",
231
+ severity: actualRatio === 0 ? "critical" : "major",
232
+ message: `Test ratio is ${Math.round(actualRatio * 100)}% (${testFiles.length} test files for ${sourceFiles.length} source files). Need at least ${Math.round(minCoverage * 100)}%.`,
233
+ location: { file: options.rootDir, line: 0 },
234
+ suggestion: `Add ~${needed} test file(s) to reach the ${Math.round(minCoverage * 100)}% minimum for safe AI assistance.`
235
+ });
236
+ }
237
+ if (indexResult.dimensions.purityScore < 50) {
238
+ issues.push({
239
+ type: "low-testability",
240
+ dimension: "purity",
241
+ severity: "major",
242
+ message: `Only ${indexResult.dimensions.purityScore}% of functions are pure \u2014 side-effectful functions require complex test setup.`,
243
+ location: { file: options.rootDir, line: 0 },
244
+ suggestion: "Extract pure transformation logic from I/O and mutation code."
245
+ });
246
+ }
247
+ if (indexResult.dimensions.observabilityScore < 50) {
248
+ issues.push({
249
+ type: "low-testability",
250
+ dimension: "observability",
251
+ severity: "major",
252
+ message: `Many functions mutate external state directly \u2014 outputs are invisible to unit tests.`,
253
+ location: { file: options.rootDir, line: 0 },
254
+ suggestion: "Prefer returning values over mutating shared state."
255
+ });
256
+ }
257
+ return {
258
+ summary: {
259
+ sourceFiles: sourceFiles.length,
260
+ testFiles: testFiles.length,
261
+ coverageRatio: Math.round(actualRatio * 100) / 100,
262
+ score: indexResult.score,
263
+ rating: indexResult.rating,
264
+ aiChangeSafetyRating: indexResult.aiChangeSafetyRating,
265
+ dimensions: indexResult.dimensions
266
+ },
267
+ issues,
268
+ rawData: {
269
+ sourceFiles: sourceFiles.length,
270
+ testFiles: testFiles.length,
271
+ ...aggregated,
272
+ hasTestFramework
273
+ },
274
+ recommendations: indexResult.recommendations
275
+ };
276
+ }
277
+
278
+ // src/scoring.ts
279
+ function calculateTestabilityScore(report) {
280
+ const { summary, rawData, recommendations } = report;
281
+ const factors = [
282
+ {
283
+ name: "Test Coverage",
284
+ impact: Math.round(summary.dimensions.testCoverageRatio - 50),
285
+ description: `${rawData.testFiles} test files / ${rawData.sourceFiles} source files (${Math.round(summary.coverageRatio * 100)}%)`
286
+ },
287
+ {
288
+ name: "Function Purity",
289
+ impact: Math.round(summary.dimensions.purityScore - 50),
290
+ description: `${rawData.pureFunctions}/${rawData.totalFunctions} functions are pure`
291
+ },
292
+ {
293
+ name: "Dependency Injection",
294
+ impact: Math.round(summary.dimensions.dependencyInjectionScore - 50),
295
+ description: `${rawData.injectionPatterns}/${rawData.totalClasses} classes use DI`
296
+ },
297
+ {
298
+ name: "Interface Focus",
299
+ impact: Math.round(summary.dimensions.interfaceFocusScore - 50),
300
+ description: `${rawData.bloatedInterfaces} interfaces have >10 methods`
301
+ },
302
+ {
303
+ name: "Observability",
304
+ impact: Math.round(summary.dimensions.observabilityScore - 50),
305
+ description: `${rawData.externalStateMutations} functions mutate external state`
306
+ }
307
+ ];
308
+ const recs = recommendations.map(
309
+ (action) => ({
310
+ action,
311
+ estimatedImpact: summary.aiChangeSafetyRating === "blind-risk" ? 15 : 8,
312
+ priority: summary.aiChangeSafetyRating === "blind-risk" || summary.aiChangeSafetyRating === "high-risk" ? "high" : "medium"
313
+ })
314
+ );
315
+ return {
316
+ toolName: "testability",
317
+ score: summary.score,
318
+ rawMetrics: {
319
+ ...rawData,
320
+ rating: summary.rating,
321
+ aiChangeSafetyRating: summary.aiChangeSafetyRating,
322
+ coverageRatio: summary.coverageRatio
323
+ },
324
+ factors,
325
+ recommendations: recs
326
+ };
327
+ }
328
+
329
+ export {
330
+ analyzeTestability,
331
+ calculateTestabilityScore
332
+ };