sniff-check
Version:
๐ฏ Opinionated TypeScript/Next.js Development Toolkit - Find large files, unused imports, broken imports, and enforce code quality standards with lightning speed
838 lines (662 loc) โข 24.7 kB
Markdown
# sniff-check
[](https://badge.fury.io/js/sniff-check)
[](https://www.npmjs.com/package/sniff-check)
[](https://opensource.org/licenses/MIT)
> Opinionated TypeScript/Next.js Development Toolkit
A comprehensive, high-performance Rust CLI tool that enforces opinionated code quality standards for TypeScript/Next.js projects. Built for speed, reliability, and developer productivity with advanced performance optimizations and comprehensive testing.
**๐ NEW in v0.2.0: Component Analysis!** Smart component splitting analyzer for React/Vue/Angular components with complexity scoring and refactoring guidance.
[](https://ko-fi.com/rizkyviali)
## ๐ฅ Core Philosophy
- **Files over 100 lines are considered "smelly code"** and should be refactored
- **TypeScript 'any' usage is forbidden** - strict typing enforced
- **Clean separation** between utilities and components
- **Zero-tolerance** for unused imports and dead code
- **Comprehensive pre-deployment validation**
- **Performance-first architecture** - optimized for large codebases
## โก Performance Features
- **Smart File Discovery** - Automatically excludes binary files, images, and build artifacts
- **Parallel Processing** - Multi-threaded analysis for projects with 20+ files
- **Memory-Mapped I/O** - Efficient handling of large files (1MB+) using memory mapping
- **Intelligent Caching** - Reduces redundant file system operations
- **Performance Monitoring** - Built-in timing and metrics (use `SNIFF_PERF_DEBUG=1`)
- **Optimized Regex Engine** - Shared pattern compilation for faster analysis
## ๐ Quick Start
```bash
# Install globally via npm (Recommended)
npm install -g sniff-check
# Or use without installation
npx sniff-check
# Or add to your project
npm install --save-dev sniff-check
```
### Alternative Installation Methods
<details>
<summary>Via Cargo (Rust)</summary>
```bash
# Install from crates.io
cargo install sniff-check
# Or build from source
git clone https://github.com/rizkyviali/sniff-check
cd sniff-check
cargo build --release
```
</details>
### Requirements
- **Node.js 16+** (for npm installation)
- **Rust 1.70+** (only for cargo installation)
## ๐ Usage
### ๐ฏ Most Common Commands
```bash
# ๐ Find large files that need refactoring (>100 lines)
sniff large
# ๐งฉ Analyze and split large components (NEW in v0.2.0!)
sniff components
# ๐ซ Detect unused AND broken imports
sniff imports
# ๐ Check TypeScript code quality ('any' usage, type coverage)
sniff types
# ๐ Complete pre-deployment validation
sniff deploy
```
### Interactive Menu
```bash
sniff
# or
sniff menu
```
Shows a beautiful terminal menu with all available commands.
### Core Commands
#### ๐ Large Files Detection
```bash
sniff large
sniff --json large # JSON output
sniff --quiet large # Quiet mode
```
Scans all TypeScript/JavaScript files and flags files over the threshold as "smelly code". Provides specific refactoring suggestions based on file type (component, service, API, etc.).
**Severity Levels:**
- **Warning** (100-200 lines): Needs attention
- **Error** (200-400 lines): Should be refactored
- **Critical** (400+ lines): Must be refactored immediately
#### ๐งฉ Component Analysis & Splitting
```bash
sniff components
sniff components --threshold 150 # Custom line threshold
```
Smart analysis of React, Vue, Angular, and Svelte components:
- **Complexity scoring** based on hooks, props, state, and nesting
- **Framework-specific detection** and recommendations
- **Extractable parts identification** (custom hooks, utility functions, sub-components)
- **Refactoring guidance** with specific splitting strategies
- **Multi-concern detection** for components handling too many responsibilities
**Analysis includes:**
- Hook usage patterns (useState, useEffect, custom hooks)
- Props complexity (too many props suggests multiple concerns)
- Component nesting depth and complexity
- Business logic that could be extracted
- UI elements that could become reusable components
#### ๐ TypeScript Quality Check
```bash
sniff types
```
Comprehensive TypeScript analysis:
- Detects 'any' type usage (CRITICAL)
- Finds missing return type annotations
- Identifies @ts-ignore/@ts-expect-error comments
- Calculates type coverage score (0-100%)
#### ๐ซ Unused & Broken Imports Detection
```bash
sniff imports
```
Comprehensive analysis of import statements:
- **Unused Imports**: Detects unused default, named, and namespace imports
- **Broken Imports**: Identifies imports referencing non-existent files or uninstalled packages
- **Smart Suggestions**: Provides fix suggestions for broken imports (perfect for refactoring)
- **Refactoring Support**: Instantly spots issues after moving/renaming files
- Handles complex usage patterns (JSX components, type annotations)
- Shows potential bundle size savings
- Supports ES6, CommonJS, and dynamic imports
#### ๐ฆ Bundle Analysis
```bash
sniff bundle
```
Analyzes build output for optimization opportunities:
- Identifies largest chunks and files
- Calculates compression ratios
- Warns about oversized bundles (>2MB total, >500KB per chunk)
- Provides specific optimization recommendations
#### ๐ Performance Auditing
```bash
sniff perf
```
Comprehensive performance analysis with Lighthouse integration:
- Runs Lighthouse audits on local development servers
- Checks Core Web Vitals (LCP, FID, CLS)
- Analyzes performance, accessibility, best practices, and SEO
- Provides bundle size analysis and optimization recommendations
- Falls back to basic performance checks if Lighthouse unavailable
#### ๐ง Memory Leak Detection
```bash
sniff memory
```
Advanced memory leak pattern detection:
- Scans for common memory leak patterns in TypeScript/JavaScript
- Detects unremoved event listeners, timer leaks, circular references
- Monitors running Node.js processes for high memory usage
- Provides specific cleanup recommendations and best practices
#### ๐ง Environment Validation
```bash
sniff env
```
Complete environment variable validation:
- Checks required environment variables for TypeScript/Next.js projects
- Validates format for URLs, database connections, and Node environments
- Scans .env files for security issues and sensitive data exposure
- Provides environment health score and configuration recommendations
#### ๐๏ธ Project Context Analysis
```bash
sniff context
```
Comprehensive project structure and context analysis:
- Analyzes project information (name, version, framework, languages)
- Maps directory structure and identifies file purposes
- Detects architectural patterns and organization quality
- Provides insights into project complexity and recommendations
- Supports multiple frameworks: Next.js, React, Vue, Angular, Svelte
#### ๐ Pre-deployment Pipeline
```bash
sniff deploy
```
Comprehensive pre-deployment validation pipeline:
- Runs all quality checks in sequence (env, types, large files, imports, bundle)
- Provides deployment readiness assessment
- Shows detailed results for each check with timing information
- Fails fast on critical issues, allows warnings for non-blocking problems
#### โ๏ธ Configuration Management
```bash
sniff config init # Initialize default configuration file
sniff config show # Show current configuration
sniff config validate # Validate configuration file
sniff config get types # Show configuration for specific command
```
### Output Formats
```bash
# JSON output for programmatic usage
sniff --json large
# Quiet mode for CI environments
sniff --quiet large
# Custom configuration
sniff --config custom.toml large
# Version information
sniff --version
# Help information
sniff --help
sniff large --help
# Performance debugging (shows detailed timing)
SNIFF_PERF_DEBUG=1 sniff large
```
### Performance Monitoring
Set `SNIFF_PERF_DEBUG=1` to see detailed performance breakdowns:
```bash
SNIFF_PERF_DEBUG=1 sniff large
# Output includes:
# --- Performance Report ---
# Total time: 285ms
# File discovery: 283ms (ฮ 283ms)
# File analysis: 1.3ms (ฮ 1.3ms)
# Summary creation: 600ns (ฮ 600ns)
# Files processed: 1247
# Large files found: 23
```
## ๐ฏ Features
### โ
Fully Implemented
- **Interactive Menu** - Beautiful terminal UI with categorized commands
- **Large Files Detection** - Find and refactor "smelly code" files with optimized parallel analysis
- **TypeScript Quality Check** - Comprehensive type analysis and scoring
- **Unused Imports Detection** - Clean up dead imports automatically
- **Bundle Analysis** - Optimize build output and bundle sizes
- **Performance Auditing** - Lighthouse integration for performance testing
- **Memory Leak Detection** - Monitor Node.js memory usage patterns
- **Environment Validation** - Check required environment variables
- **Project Context Analysis** - Comprehensive project structure and insights
- **Pre-deployment Pipeline** - Complete validation before deployment
- **Configuration System** - Project-specific settings and overrides
### โก Performance & Architecture (v0.1.5)
- **Optimized File Walker** - Smart directory filtering and parallel processing
- **Memory-Mapped I/O** - Efficient large file handling (1MB+ files)
- **Shared Utilities** - Eliminated 300+ lines of duplicate code
- **Unified JSON Output** - Standardized responses with metadata and timing
- **Performance Monitoring** - Built-in profiling and debugging tools
- **Comprehensive Test Suite** - Shared test utilities and integration tests
- **Error Handling** - Standardized exit codes and error reporting
## ๐ ๏ธ Configuration
Create a `sniff.toml` file in your project root for project-specific settings:
```toml
[large_files]
threshold = 100
excluded_dirs = [
"node_modules",
".next",
"dist",
".git",
"target",
"build",
"coverage",
".cache",
"tmp",
"temp",
]
excluded_files = [
"*.min.js",
"*.bundle.js",
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
"bun.lockb",
"*.d.ts",
"*.config.js",
"*.config.ts",
]
[large_files.severity_levels]
warning = 100
error = 200
critical = 400
[typescript]
strict_any_check = true
allow_ts_ignore = false
require_return_types = true
min_type_coverage = 80.0
[imports]
auto_fix = false
excluded_patterns = [
"react",
"@types/*",
]
check_dev_dependencies = true
[bundle]
max_bundle_size_mb = 2.0
max_chunk_size_mb = 0.5
build_dirs = [
".next",
"dist",
"build",
"out",
]
warn_on_large_chunks = true
[performance]
lighthouse_enabled = true
min_performance_score = 75.0
min_accessibility_score = 90.0
server_urls = [
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:8000",
"http://localhost:8080",
]
[memory]
check_patterns = true
check_processes = true
max_process_memory_mb = 1000.0
pattern_severity_threshold = "high"
[environment]
required_vars = [
"NODE_ENV",
"NEXT_PUBLIC_APP_URL",
"NEXTAUTH_SECRET",
"NEXTAUTH_URL",
"DATABASE_URL",
"VERCEL_URL",
]
check_security = true
allow_empty_values = false
env_files = [
".env",
".env.local",
".env.development",
".env.production",
".env.staging",
".env.test",
]
# File type classification for enhanced analysis
[file_types]
# Next.js specific patterns
api_routes = ["**/api/**/*.ts", "**/api/**/*.js"]
server_components = ["**/app/**/*.tsx", "**/app/**/page.tsx", "**/app/**/layout.tsx"]
client_components = ["**/*client*.tsx", "**/*client*.ts", "**/*.client.tsx", "**/*.client.ts"]
middleware = ["middleware.ts", "middleware.js", "**/middleware/**/*.ts"]
custom_hooks = ["**/*use*.ts", "**/*use*.tsx", "**/hooks/**/*.ts"]
type_definitions = ["**/*.d.ts", "**/types/**/*.ts", "**/@types/**/*.ts"]
configuration = ["**/*.config.*", "**/config/**/*", "**/*.env*"]
```
Use `sniff config init` to generate a default configuration file, or `sniff config show` to see your current settings.
## ๐ Recent Updates
**v0.1.8** delivers critical TypeScript import parsing fix:
- **๐ TypeScript Import Fix**: Fixed false positive detection in inline type imports like `import { type NextRequest }`
- **๐ฏ Parser Enhancement**: Now correctly extracts type names instead of reporting "type" as unused
- **โ
Backward Compatible**: All existing functionality preserved with improved accuracy
**v0.1.7** delivered production-ready stability with critical bug fixes and quality improvements:
- **๐ Critical Bug Fixes**: Resolved import parsing issues with trailing comments and TypeScript type imports
- **๐งช Test Suite Reliability**: All tests now pass consistently, ensuring stable releases
- **โก Performance Infrastructure**: Added progress tracking foundation for large projects
- **๐ Enhanced JSON Output**: Broken imports properly included in CI/CD responses
- **๐ฏ Better User Experience**: Improved error messages and visual feedback
**v0.1.6** introduced powerful broken imports detection alongside existing unused imports analysis:
- **๐ฅ Broken Imports Detection**: Identifies imports to non-existent files and uninstalled packages
- **๐ก Smart Suggestions**: Provides intelligent fix recommendations for broken imports
- **๐ฏ Refactoring Support**: Perfect for detecting issues after moving/renaming files
- **๐ Unified Reporting**: Shows both unused and broken imports together
**v0.1.5** introduced major performance and architecture improvements:
- **โก Performance**: File analysis improved from ~283ms to ~1.3ms
- **๐ Architecture**: New shared utilities eliminate 300+ lines of duplicate code
- **๐ JSON Output**: Standardized format with timestamps and metadata
See [CHANGELOG.md](./CHANGELOG.md) for complete release notes and version history.
## ๐ Example Output
### Large Files Report
```
๐ Scanning for large files...
๐ Large Files Report
====================
๐จ CRITICAL FILES
src/components/UserDashboard.tsx (423 lines) - Component
โข Break into smaller sub-components
โข Extract custom hooks for logic
โข Move utility functions to separate files
โ ๏ธ ERROR FILES
src/services/api.ts (287 lines) - Service
โข Split into multiple service classes
โข Extract interfaces and types
โข Use dependency injection
๐ SUMMARY
โโโโโโโโโ
Files scanned: 156
Large files found: 8
Critical: 1
Errors: 3
Warnings: 4
๐ก TIP: Files over 100 lines are considered 'smelly code' and should be refactored
```
### Imports Analysis Report
```
๐ Scanning for unused and broken imports...
๐ Imports Analysis Report
==========================
src/components/UserProfile.tsx
Line 12: import React from 'react';
๐ซ Unused: React
Line 15: import { validateEmail } from '../utils/validation';
๐ซ Unused: validateEmail
Line 18: import OldComponent from './old-component';
๐ฅ File not found: ./old-component
๐ก Suggestion: ./components/UserComponent
Line 22: import lodash from 'lodash';
๐ฅ Module not installed: lodash
๐ก Run: npm install lodash
๐ SUMMARY
โโโโโโโโโ
Files scanned: 156
Total imports: 284
Unused imports: 12
Broken imports: 8
Potential savings: ~12 lines of code
๐ก TIP: Remove unused imports to reduce bundle size and improve build performance
๐ง Consider using an IDE extension or linter to automatically remove unused imports
๐ง Fix broken imports to resolve compilation errors
๐ก Check if files were moved/renamed, or if packages need to be installed
```
### TypeScript Quality Report
```
๐ Checking TypeScript type coverage...
๐ TypeScript Quality Report
===========================
๐ซ 'ANY' TYPE USAGE (CRITICAL)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
src/utils/helpers.ts:42 - Usage of 'any' type detected
๐ก Consider using a more specific type
๐ SUMMARY
โโโโโโโโโ
Files scanned: 89
Total issues: 12
'any' usage: 5
Missing return types: 4
TS suppressions: 3
Type Coverage Score: 87.2%
๐ซ CRITICAL: Usage of 'any' type is strictly forbidden!
All 'any' types must be replaced with specific types.
```
### Project Context Report
```
๐ Analyzing project structure and context...
๐ Project Context Report
========================
๐๏ธ PROJECT OVERVIEW
โโโโโโโโโโโโโโโโโโโโโ
Name: my-nextjs-app
Version: 1.2.0
Description: Modern e-commerce platform
Framework: NextJs
Languages: [TypeScript, JavaScript, CSS, JSON]
Total Files: 247
Total Lines: 12,485
๐ PROJECT STRUCTURE
โโโโโโโโโโโโโโโโโโโโโโ
Key Directories:
โข src/components (45 files, 3,241 lines)
Purpose: Components | File types: tsx, ts, css
โข src/pages (23 files, 2,156 lines)
Purpose: Pages | File types: tsx, ts
โข src/api (18 files, 1,489 lines)
Purpose: Api | File types: ts
โข src/utils (12 files, 892 lines)
Purpose: Utils | File types: ts
๐๏ธ ARCHITECTURE INSIGHTS
โโโโโโโโโโโโโโโโโโโโโโโโโ
Organization Score: 85.2%
Complexity Level: Moderate
Detected Patterns:
โข LayeredArchitecture
โข ComponentComposition
โข CustomHooks
```
## ๐ฏ Recommended Workflows
### Daily Development
```bash
sniff large && sniff imports
```
### Pre-commit Hook
```bash
sniff types && sniff env
```
### Performance Testing
```bash
sniff perf && sniff memory
```
### Pre-deployment (Complete Pipeline)
```bash
sniff deploy # Runs comprehensive validation: env, types, large files, imports, bundle
```
### Individual Checks
```bash
sniff menu # Interactive command selection
sniff large # Check file sizes
sniff types # TypeScript quality
sniff imports # Unused imports
sniff bundle # Bundle analysis
sniff perf # Performance audit
sniff memory # Memory leak detection
sniff env # Environment validation
sniff context # Project structure analysis
```
## ๐ฆ Exit Codes
- **0**: All checks passed (Success)
- **1**: General error
- **2**: Validation failed (issues found that need attention)
- **3**: Threshold exceeded (critical issues found)
- **4**: Configuration error
## ๐ CI/CD Integration
### GitHub Actions
Add this workflow to `.github/workflows/sniff-check.yml`:
```yaml
name: Code Quality Check
on:
pull_request:
branches: [ main, develop ]
push:
branches: [ main, develop ]
jobs:
quality-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Install sniff-check
run: npx sniff-check@latest --version || npm install -g sniff-check
- name: Run code quality checks
run: |
echo "๐ Running sniff-check quality analysis..."
sniff --json large > large-files.json
sniff --json types > type-issues.json
sniff --json imports > unused-imports.json
# Show results in human-readable format
echo "๐ Large Files Report:"
sniff large
echo "๐ TypeScript Quality:"
sniff types
echo "๐ซ Unused Imports:"
sniff imports
echo "๐๏ธ Project Context:"
sniff context
- name: Upload reports as artifacts
uses: actions/upload-artifact@v4
if: always()
with:
name: sniff-check-reports
path: |
large-files.json
type-issues.json
unused-imports.json
retention-days: 30
- name: Comment PR with results
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
try {
const largeFiles = JSON.parse(fs.readFileSync('large-files.json', 'utf8'));
const typeIssues = JSON.parse(fs.readFileSync('type-issues.json', 'utf8'));
let comment = '## ๐ Code Quality Report\n\n';
comment += `**Large Files:** ${largeFiles.summary.large_files_found} found\n`;
comment += `**Type Issues:** ${typeIssues.summary.total_issues} found\n`;
comment += `**Type Coverage:** ${typeIssues.summary.type_coverage_score.toFixed(1)}%\n\n`;
if (largeFiles.summary.critical > 0) {
comment += '๐จ **Critical:** Files over 400 lines found - immediate refactoring needed!\n';
}
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
} catch (error) {
console.log('Could not create PR comment:', error);
}
performance-check:
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build project
run: npm run build
- name: Install sniff-check
run: npm install -g sniff-check
- name: Run performance analysis
run: |
sniff --json bundle > bundle-analysis.json
sniff --json perf > performance-audit.json || echo "Performance audit skipped (no dev server)"
sniff --json memory > memory-check.json
# Show bundle analysis
echo "๐ฆ Bundle Analysis:"
sniff bundle
- name: Upload performance reports
uses: actions/upload-artifact@v4
with:
name: performance-reports
path: |
bundle-analysis.json
performance-audit.json
memory-check.json
```
### Pre-deployment Pipeline
For production deployments:
```yaml
name: Pre-deployment Check
on:
push:
branches: [ main ]
jobs:
deploy-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Install sniff-check
run: npm install -g sniff-check
- name: Run complete deployment validation
run: |
echo "๐ Running complete pre-deployment validation..."
sniff deploy
# Additional context analysis
echo "๐ Final project analysis:"
sniff --json context > final-context.json
- name: Block deployment on critical issues
run: |
# This will fail the workflow if critical issues are found
if sniff --quiet types | grep -q "CRITICAL"; then
echo "โ Critical type issues found - blocking deployment"
exit 1
fi
if sniff --quiet large | grep -q "CRITICAL"; then
echo "โ Critical large files found - blocking deployment"
exit 1
fi
echo "โ
All checks passed - ready for deployment"
```
## ๐ค Contributing
1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Run `cargo test` and `cargo fmt`
5. Submit a pull request
## ๐ License
MIT License - see [LICENSE](LICENSE) file for details.
## ๐ Support
If you find **sniff-check** helpful, consider supporting its development:
[](https://ko-fi.com/rizkyviali)
Your support helps maintain and improve this tool for the entire TypeScript/Next.js community! โ
## ๐ Acknowledgments
Built with:
- [clap](https://github.com/clap-rs/clap) - Command line argument parsing
- [tokio](https://github.com/tokio-rs/tokio) - Async runtime
- [rayon](https://github.com/rayon-rs/rayon) - Parallel processing
- [regex](https://github.com/rust-lang/regex) - Pattern matching
- [colored](https://github.com/mackwic/colored) - Terminal colors
**sniff-check**: The definitive code quality tool for TypeScript/Next.js projects that developers actually want to use. ๐ฏ