Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:16:43 +08:00
commit 5fce0eef2b
46 changed files with 8067 additions and 0 deletions

View File

@@ -0,0 +1,250 @@
# Bulletproof React Audit Criteria
Complete checklist for auditing React/TypeScript applications against Bulletproof React architecture principles.
## 1. Project Structure
### Feature-Based Organization
- [ ] 80%+ of code organized in src/features/
- [ ] Each feature has its own directory
- [ ] Features are independent (no cross-feature imports)
- [ ] Feature subdirectories: api/, components/, hooks/, stores/, types/, utils/
### Top-Level Directories
- [ ] src/app/ exists (application layer)
- [ ] src/features/ exists and contains features
- [ ] src/components/ for truly shared components only
- [ ] src/hooks/ for shared custom hooks
- [ ] src/lib/ for third-party configurations
- [ ] src/utils/ for shared utilities
- [ ] src/types/ for shared TypeScript types
- [ ] src/stores/ for global state (if needed)
### Unidirectional Dependencies
- [ ] No cross-feature imports
- [ ] Shared code imported into features (not vice versa)
- [ ] App layer imports from features
- [ ] Clean dependency flow: shared → features → app
## 2. Component Architecture
### Component Design
- [ ] Components < 300 lines of code
- [ ] No large components (> 500 LOC)
- [ ] Components accept < 7-10 props
- [ ] No nested render functions
- [ ] Component colocation (near where used)
- [ ] Proper use of composition over excessive props
### File Organization
- [ ] Kebab-case file naming
- [ ] Components colocated with tests
- [ ] Styles colocated with components
- [ ] Feature-specific components in features/
- [ ] Only truly shared components in src/components/
### Abstraction
- [ ] No premature abstractions
- [ ] Repetition identified before creating abstractions
- [ ] Components are focused and single-purpose
## 3. State Management
### State Categories
- [ ] Component state with useState/useReducer
- [ ] Global state with Context, Zustand, or Jotai
- [ ] Server cache state with React Query or SWR
- [ ] Form state with React Hook Form or Formik
- [ ] URL state with React Router
### State Localization
- [ ] State as local as possible
- [ ] Global state only when necessary
- [ ] No single massive global state object
- [ ] Context split into multiple focused providers
### Server State
- [ ] React Query or SWR for API data
- [ ] Proper caching configuration
- [ ] No manual loading/error state for API calls
- [ ] Optimistic updates where appropriate
## 4. API Layer
### Centralized Configuration
- [ ] Single API client instance
- [ ] Configured in src/lib/
- [ ] Base URL configuration
- [ ] Request/response interceptors
- [ ] Error handling interceptors
### Request Organization
- [ ] API calls colocated in features/*/api/
- [ ] Type-safe request declarations
- [ ] Custom hooks for each endpoint
- [ ] Validation schemas with types
- [ ] Proper error handling
## 5. Testing Strategy
### Coverage
- [ ] 80%+ line coverage
- [ ] 75%+ branch coverage
- [ ] 100% coverage on critical paths
- [ ] Coverage reports generated
### Testing Trophy Distribution
- [ ] ~70% integration tests
- [ ] ~20% unit tests
- [ ] ~10% E2E tests
### Test Quality
- [ ] Tests named "should X when Y"
- [ ] Semantic queries (getByRole, getByLabelText)
- [ ] Testing user behavior, not implementation
- [ ] No brittle tests (exact counts, element ordering)
- [ ] Tests isolated and independent
- [ ] No flaky tests
### Testing Tools
- [ ] Vitest or Jest configured
- [ ] @testing-library/react installed
- [ ] @testing-library/jest-dom for assertions
- [ ] Playwright or Cypress for E2E (optional)
## 6. Styling Patterns
### Styling Approach
- [ ] Consistent styling method chosen
- [ ] Component library (Chakra, Radix, MUI) OR
- [ ] Utility CSS (Tailwind) OR
- [ ] CSS-in-JS (Emotion, styled-components)
- [ ] Styles colocated with components
### Design System
- [ ] Design tokens defined
- [ ] Color palette established
- [ ] Typography scale defined
- [ ] Spacing system consistent
## 7. Error Handling
### Error Boundaries
- [ ] Multiple error boundaries at strategic locations
- [ ] Route-level error boundaries
- [ ] Feature-level error boundaries
- [ ] User-friendly error messages
- [ ] Error recovery mechanisms
### API Errors
- [ ] API error interceptors configured
- [ ] User notifications for errors
- [ ] Automatic retry logic where appropriate
- [ ] Unauthorized user logout
### Error Tracking
- [ ] Sentry or similar service configured
- [ ] User context added to errors
- [ ] Environment-specific error handling
- [ ] Source maps configured for production
## 8. Performance
### Code Splitting
- [ ] React.lazy() for route components
- [ ] Suspense boundaries with loading states
- [ ] Large features split into chunks
- [ ] Bundle size monitored and optimized
### React Performance
- [ ] State localized to prevent re-renders
- [ ] React.memo for expensive components
- [ ] useMemo for expensive calculations
- [ ] useCallback for stable function references
- [ ] Children prop optimization patterns
### Asset Optimization
- [ ] Images lazy loaded
- [ ] Images in modern formats (WebP)
- [ ] Responsive images with srcset
- [ ] Images < 500KB
- [ ] Videos lazy loaded or streamed
## 9. Security
### Authentication
- [ ] JWT stored in HttpOnly cookies (not localStorage)
- [ ] Secure session management
- [ ] Token refresh logic
- [ ] Logout functionality
### Authorization
- [ ] RBAC or PBAC implemented
- [ ] Protected routes
- [ ] Permission checks on actions
- [ ] API-level authorization
### XSS Prevention
- [ ] Input sanitization (DOMPurify)
- [ ] No dangerouslySetInnerHTML without sanitization
- [ ] Output encoding
- [ ] Content Security Policy
### CSRF Protection
- [ ] CSRF tokens for state-changing requests
- [ ] SameSite cookie attribute
- [ ] Verify origin headers
## 10. Standards Compliance
### ESLint
- [ ] .eslintrc or eslint.config.js configured
- [ ] React rules enabled
- [ ] TypeScript rules enabled
- [ ] Accessibility rules (jsx-a11y)
- [ ] Architectural rules (import restrictions)
### TypeScript
- [ ] strict: true in tsconfig.json
- [ ] No `any` types
- [ ] Explicit return types
- [ ] Type definitions for third-party libraries
- [ ] Types colocated with features
### Prettier
- [ ] Prettier configured
- [ ] Format on save enabled
- [ ] Consistent code style
- [ ] .prettierrc configuration
### Git Hooks
- [ ] Husky configured
- [ ] Pre-commit linting
- [ ] Pre-commit type checking
- [ ] Pre-commit tests (optional)
### File Naming
- [ ] Kebab-case for files and directories
- [ ] Consistent naming conventions
- [ ] ESLint rule to enforce naming
### Absolute Imports
- [ ] TypeScript paths configured (@/ prefix)
- [ ] Imports use @/ instead of relative paths
- [ ] Easier refactoring and moving files
## Compliance Scoring
### Grade Scale
- **A (90-100)**: Excellent Bulletproof React compliance
- **B (80-89)**: Good compliance, minor improvements needed
- **C (70-79)**: Moderate compliance, significant refactoring recommended
- **D (60-69)**: Poor compliance, major architectural changes needed
- **F (<60)**: Non-compliant, complete restructuring required
### Category Weights
All categories weighted equally for overall score.
---
**Note**: This checklist represents the ideal Bulletproof React architecture. Adapt based on your project's specific needs and constraints while maintaining the core principles.

View File

@@ -0,0 +1,248 @@
# Severity Matrix
Priority levels and response times for Bulletproof React audit findings.
## Severity Levels
### Critical (P0)
**Fix immediately (within 24 hours)**
#### Criteria
- Security vulnerabilities (tokens in localStorage, XSS risks)
- Breaking architectural violations that prevent scalability
- No testing framework in production app
- TypeScript strict mode disabled with widespread `any` usage
#### Examples
- Authentication tokens stored in localStorage
- No error boundaries in production app
- Zero test coverage on critical paths
- Multiple cross-feature dependencies creating circular imports
#### Impact
- Security breaches possible
- Application instability
- Cannot safely refactor or add features
- Technical debt compounds rapidly
---
### High (P1)
**Fix this sprint (within 2 weeks)**
#### Criteria
- Major architectural misalignment with Bulletproof React
- No data fetching library (manual API state management)
- Test coverage < 80%
- Large components (> 400 LOC) with multiple responsibilities
- No features/ directory with >50 components
#### Examples
- Flat structure instead of feature-based
- Scattered fetch calls throughout components
- No React Query/SWR for server state
- Components with 15+ props
- No error tracking service (Sentry)
#### Impact
- Difficult to maintain and extend
- Poor developer experience
- Slow feature development
- Bugs hard to track and fix
- Testing becomes increasingly difficult
---
### Medium (P2)
**Fix next quarter (within 3 months)**
#### Criteria
- Component design anti-patterns
- State management could be improved
- Missing recommended directories
- Some cross-feature imports
- No code splitting
- Inconsistent styling approaches
#### Examples
- Components 200-400 LOC
- Context with 5+ state values
- Too many shared components (should be feature-specific)
- Nested render functions instead of components
- Multiple styling systems in use
- Large images not optimized
#### Impact
- Code is maintainable but could be better
- Some technical debt accumulating
- Refactoring is more difficult than it should be
- Performance could be better
- Developer onboarding takes longer
---
### Low (P3)
**Backlog (schedule when convenient)**
#### Criteria
- Minor deviations from Bulletproof React patterns
- Stylistic improvements
- Missing nice-to-have features
- Small optimizations
#### Examples
- Files not using kebab-case naming
- No Prettier configured
- No git hooks (Husky)
- Missing some recommended directories
- Test naming doesn't follow "should X when Y"
- Some components could be better colocated
#### Impact
- Minimal impact on development
- Minor inconsistencies
- Small developer experience improvements possible
- Low-priority technical debt
---
## Effort Estimation
### Low Effort (< 1 day)
- Installing dependencies
- Creating configuration files
- Renaming files
- Adding error boundaries
- Setting up Prettier/ESLint
- Configuring git hooks
### Medium Effort (1-5 days)
- Creating features/ structure
- Organizing existing code into features
- Refactoring large components
- Adding React Query/SWR
- Setting up comprehensive error handling
- Improving test coverage to 80%
### High Effort (1-3 weeks)
- Complete architecture restructuring
- Migrating from flat to feature-based structure
- Comprehensive security improvements
- Building out full test suite
- Large-scale refactoring
- Multiple concurrent improvements
---
## Priority Decision Matrix
| Severity | Effort Low | Effort Medium | Effort High |
|----------|------------|---------------|-------------|
| **Critical** | P0 - Do Now | P0 - Do Now | P0 - Plan & Start |
| **High** | P1 - This Sprint | P1 - This Sprint | P1 - This Quarter |
| **Medium** | P2 - Next Sprint | P2 - Next Quarter | P2 - This Year |
| **Low** | P3 - Backlog | P3 - Backlog | P3 - Nice to Have |
---
## Response Time Guidelines
### Critical (P0)
- **Notification**: Immediate (Slack/email alert)
- **Acknowledgment**: Within 1 hour
- **Plan**: Within 4 hours
- **Fix**: Within 24 hours
- **Verification**: Immediately after fix
- **Documentation**: ADR created
### High (P1)
- **Notification**: Within 1 day
- **Acknowledgment**: Within 1 day
- **Plan**: Within 2 days
- **Fix**: Within current sprint (2 weeks)
- **Verification**: Before sprint end
- **Documentation**: Updated in sprint retrospective
### Medium (P2)
- **Notification**: Within 1 week
- **Acknowledgment**: Within 1 week
- **Plan**: Within sprint planning
- **Fix**: Within quarter (3 months)
- **Verification**: Quarterly review
- **Documentation**: Included in quarterly planning
### Low (P3)
- **Notification**: Added to backlog
- **Acknowledgment**: During backlog refinement
- **Plan**: When capacity available
- **Fix**: Opportunistic
- **Verification**: As completed
- **Documentation**: Optional
---
## Category-Specific Severity Guidelines
### Structure Issues
- **Critical**: No features/, flat structure with 100+ components
- **High**: Missing features/, cross-feature dependencies
- **Medium**: Some organizational issues
- **Low**: Minor folder organization improvements
### Component Issues
- **Critical**: Components > 1000 LOC, widespread violations
- **High**: Many components > 400 LOC, 15+ props
- **Medium**: Some large components, nested renders
- **Low**: Minor design improvements needed
### State Management
- **Critical**: No proper state management in complex app
- **High**: No data fetching library, manual API state
- **Medium**: State could be better localized
- **Low**: Could use better state management tool
### Testing Issues
- **Critical**: No testing framework, 0% coverage
- **High**: Coverage < 50%, wrong test distribution
- **Medium**: Coverage 50-79%, some brittle tests
- **Low**: Coverage > 80%, minor test improvements
### Security Issues
- **Critical**: Tokens in localStorage, XSS vulnerabilities
- **High**: No error tracking, missing CSRF protection
- **Medium**: Minor security improvements needed
- **Low**: Security best practices could be better
---
## Migration Planning
### Phase 1: Critical (Week 1)
1. Fix all P0 security issues
2. Establish basic architecture (features/)
3. Set up testing framework
4. Configure error tracking
### Phase 2: High Priority (Weeks 2-6)
1. Migrate to feature-based structure
2. Add React Query/SWR
3. Improve test coverage to 80%
4. Refactor large components
5. Add error boundaries
### Phase 3: Medium Priority (Months 2-3)
1. Optimize component architecture
2. Implement code splitting
3. Improve state management
4. Add comprehensive testing
5. Performance optimizations
### Phase 4: Low Priority (Ongoing)
1. Stylistic improvements
2. Developer experience enhancements
3. Documentation updates
4. Minor refactoring
---
**Note**: These guidelines should be adapted based on your team size, release cadence, and business priorities. Always balance technical debt reduction with feature development.