static-code-analyzer
Version:
Universal static code analysis tool for calculating API operation costs across multiple frameworks (NestJS, Express, Fastify)
283 lines (226 loc) ⢠7.12 kB
Markdown
typescript
// Detects parallel operations automatically
const [user, profile, permissions] = await Promise.all([
prisma.user.findUnique({ where: { id } }), // Cost: 1
prisma.profile.findUnique({ where: { userId: id } }), // Cost: 1
prisma.permission.findMany({ where: { userId: id } }) // Cost: 1
]);
// Total parallel cost: 1 (max of group, not sum)
// vs Sequential (would be cost: 3)
const user = await prisma.user.findUnique({ where: { id } });
const profile = await prisma.profile.findUnique({ where: { userId: id } });
const permissions = await prisma.permission.findMany({ where: { userId: id } });
```
### **Cost Variance Analysis**
Identifies methods with high cost variance between execution paths:
```
ā ļø High cost variance (2-6) - Consider optimizing expensive paths
š” Consider caching frequently accessed data
šÆ Use Promise.all() for independent operations
```
### **Framework Detection**
Automatically detects and configures for popular ORMs and frameworks:
- **Prisma**: `prisma.model.operation()`
- **TypeORM**: `repository.operation()`
- **Mongoose**: `Model.operation()`
- **Supabase**: `supabase.from().operation()`
- **HTTP Clients**: `axios.get()`, `fetch()`
- **Cache**: Redis operations
## š Development Workflow
### **Development Mode**
```bash
# Watch files during development
sca watch ./src/users/users.service.ts --framework nestjs
# Outputs real-time cost analysis as you code
š Watching ./src/users/users.service.ts for changes...
š File changed, re-analyzing...
ā
Method: createUser - Cost: 2-3 requests (2 paths)
ā ļø Method: updateUser - Cost: 1-5 requests (3 paths) - High variance detected
```
### **IDE Integration**
Add to VS Code tasks (`.vscode/tasks.json`):
```json
{
"version": "2.0.0",
"tasks": [
{
"label": "Analyze API Costs",
"type": "shell",
"command": "sca",
"args": ["file", "${file}", "--framework", "nestjs"],
"group": "build",
"presentation": {
"echo": true,
"reveal": "always"
}
}
]
}
```
## š Optimization Strategies
### **Recommended Patterns**
1. **Use Parallel Execution**
```typescript
// ā Sequential (Cost: 3)
const user = await getUser(id);
const posts = await getPosts(id);
const comments = await getComments(id);
// ā
Parallel (Cost: 1)
const [user, posts, comments] = await Promise.all([
getUser(id),
getPosts(id),
getComments(id)
]);
```
2. **Reduce Database Roundtrips**
```typescript
// ā Multiple queries (Cost: N+1)
const users = await prisma.user.findMany();
for (const user of users) {
user.profile = await prisma.profile.findUnique({ where: { userId: user.id } });
}
// ā
Single query with relations (Cost: 1)
const users = await prisma.user.findMany({
include: { profile: true }
});
```
3. **Implement Caching**
```typescript
// Add caching layer for expensive operations
@Cache('user-profile', 300) // 5 minutes
async getUserProfile(id: string) {
return await prisma.user.findUnique({
where: { id },
include: { profile: true }
});
}
```
4. **Use Batch Operations**
```typescript
// ā Multiple inserts (Cost: N)
for (const userData of users) {
await prisma.user.create({ data: userData });
}
// ā
Batch insert (Cost: 1)
await prisma.user.createMany({ data: users });
```
## š ļø Troubleshooting
### **Common Issues**
1. **"No operations found"**
- Check if your patterns match your code
- Verify framework preset is correct
- Add custom patterns for non-standard operations
2. **"File not found" error**
- Use absolute paths or correct relative paths
- Ensure TypeScript files are accessible
3. **Incorrect costs**
- Update operation costs in configuration
- Add custom patterns for your specific operations
### **Custom Pattern Examples**
```json
{
"patterns": {
"custom_database": {
"pattern": "myDB\\.(query|execute|find)",
"defaultCost": 1,
"description": "Custom database operations"
},
"external_api": {
"pattern": "apiClient\\.(get|post|put|delete)",
"defaultCost": 2,
"description": "External API calls"
},
"cache_operations": {
"pattern": "cache\\.(get|set|del)",
"defaultCost": 0.5,
"description": "Cache operations"
}
}
}
```
## š API Reference
### **Core Classes**
#### `ApiCostAnalyzer`
```typescript
class ApiCostAnalyzer {
constructor(config?: Partial<AnalyzerConfig>)
setFramework(framework: string): void
updateConfig(config: Partial<AnalyzerConfig>): void
analyzeFile(filePath: string): FileAnalysis
analyzeFiles(filePaths: string[]): FileAnalysis[]
analyzeProject(projectPath: string, patterns?: string[]): ProjectAnalysis
}
```
#### `ReportGenerator`
```typescript
class ReportGenerator {
static generateFileReport(analysis: FileAnalysis, format: ReportFormat): string
static generateProjectReport(files: FileAnalysis[], format: ReportFormat): string
static saveReport(content: string, filePath: string): void
}
```
### **Configuration Types**
```typescript
interface AnalyzerConfig {
operations: Record<string, number>;
patterns: Record<string, PatternConfig>;
parallelExecutionPatterns: string[];
ignorePatterns: string[];
costMultipliers: CostMultipliers;
methodCosts?: Record<string, MethodCostConfig>;
}
interface FileAnalysis {
filePath: string;
fileName: string;
methods: MethodAnalysis[];
summary: FileSummary;
}
interface MethodAnalysis {
methodName: string;
className?: string;
totalPaths: number;
paths: ExecutionPath[];
summary: MethodSummary;
recommendations: string[];
}
```
## š¤ Contributing
### **Development Setup**
```bash
git clone https://github.com/mtalhazulf/static-code-analyzer
cd static-code-analyzer
bun install
bun run build
bun test
```
### **Adding Framework Support**
1. Add framework preset in `src/config.ts`
2. Define operation patterns and costs
3. Add tests for the new framework
4. Update documentation
### **Contributing Guidelines**
- Follow TypeScript best practices
- Add tests for new features
- Update documentation
- Follow semantic versioning
## š License
MIT License - see [LICENSE](LICENSE) file for details.
## š Acknowledgments
- Built with TypeScript Compiler API
- Inspired by static analysis tools like ESLint and SonarQube
- Designed for modern JavaScript/TypeScript frameworks
## š Support
- š **Issues**: [GitHub Issues](https://github.com/mtalhazulf/static-code-analyzer/issues)
- š **Documentation**: [GitHub Wiki](https://github.com/mtalhazulf/static-code-analyzer/wiki)
- š¬ **Discussions**: [GitHub Discussions](https://github.com/mtalhazulf/static-code-analyzer/discussions)
---
**Made with ā¤ļø for the TypeScript/JavaScript community**
Start optimizing your API costs today:
```bash
# Using Bun (recommended)
bun install -g static-code-analyzer
sca init --framework nestjs
sca project ./src
# Or using npm
npm install -g static-code-analyzer
```