@aiready/testability 0.1.1

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