Update generation system with modern prompts and Gemini 2.5 Flash

- Upgrade to gemini-2.5-flash model for better output quality
- Add date context to prompts (December 2025) for current best practices
- Implement Exa cache system to avoid redundant API calls
- Add --refresh-exa flag to bypass cache when needed
- Restructure prompts with date at end for Gemini prompt caching
- Enhance system prompt to emphasize modern patterns
- Switch from JSON mode to direct MDC format generation
- Add loguru dependency for better logging
- Remove requirements.txt in favor of uv
This commit is contained in:
sanjeed5
2025-12-17 21:12:15 +05:30
parent 9983c8b40d
commit 5cbc31aee9
8 changed files with 2818 additions and 2968 deletions
+7
View File
@@ -18,6 +18,7 @@ dependencies = [
"pyyaml>=6.0.0",
"build>=1.2.2.post1",
"twine>=6.1.0",
"loguru>=0.7.3",
]
[build-system]
@@ -26,3 +27,9 @@ build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src"]
[dependency-groups]
dev = [
"pytest>=8.3.5",
"pytest-mock>=3.14.0",
]
-5
View File
@@ -1,5 +0,0 @@
litellm>=1.30.3
python-dotenv>=1.0.1
tenacity>=8.2.3
ratelimit>=2.2.1
pydantic>=2.6.1
+183 -141
View File
@@ -1,185 +1,227 @@
---
description: This rule provides comprehensive guidelines for using Axios effectively, covering best practices, security considerations, and performance optimization. It aims to improve code quality, maintainability, and overall application resilience when working with Axios.
globs: *.js,*.jsx,*.ts,*.tsx
description: Comprehensive best practices for using the Axios HTTP client library, covering code organization, common patterns, performance, pitfalls, and testing.
globs: **/*.{js,jsx,ts,tsx}
---
- **Avoid hardcoding URLs**: Store API endpoints in configuration files or environment variables to enhance maintainability and avoid redundancy.
- **Centralize API Logic**: Create dedicated modules or services to encapsulate Axios instances and request logic. This promotes reusability and simplifies debugging.
- **Handle Errors Gracefully**: Implement comprehensive error handling using try-catch blocks, response interceptors, and centralized error logging. Display user-friendly error messages.
- **Use Asynchronous Functions**: Leverage `async/await` or Promises for cleaner and more manageable asynchronous code when making Axios requests.
- **Optimize with Request Interceptors**: Utilize request interceptors for tasks like adding authentication tokens, logging requests, or transforming request data. Response interceptors can be used for error handling or data transformation.
- **Ensure HTTP Requests When Necessary**: Verify that requests are only made when truly needed, preventing unnecessary network traffic and improving performance. Consider caching strategies.
# Axios Best Practices
### 1. Code Organization and Structure:
Axios is a powerful, promise-based HTTP client for browsers and Node.js. Adhering to best practices ensures maintainable, performant, and robust API interactions in your applications.
- **Directory Structure Best Practices**:
- Create an `api` or `services` directory to house all API-related code.
- Organize API modules based on resources or features (e.g., `api/users.js`, `api/products.js`).
- Separate Axios instance configuration into a dedicated file (e.g., `api/axios-config.js`).
## 1. Code Organization and Structure
- **File Naming Conventions**:
- Use descriptive names for API modules (e.g., `userApi.js`, `productService.js`).
- Follow a consistent naming convention (e.g., camelCase for variables, PascalCase for components).
- **Centralize Configuration with Axios Instances:** Always create dedicated Axios instances using `axios.create()` to centralize common configurations like `baseURL`, `timeout`, and default `headers`. This reduces boilerplate and ensures consistency across your application.
- **Module Organization**:
- Export individual API functions from each module (e.g., `getUser`, `createUser`).
- Use named exports for better code readability and maintainability.
javascript
// api.js or http-client.js
import axios from 'axios';
- **Component Architecture**:
- Create reusable components for handling data fetching and display.
- Decouple components from specific API calls to improve reusability.
- Utilize custom hooks to encapsulate data fetching logic.
export const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api',
timeout: 8000, // Request timeout in milliseconds
headers: {
'Content-Type': 'application/json',
},
});
- **Code Splitting Strategies**:
- Implement lazy loading for API modules that are not immediately required.
- Use dynamic imports to load modules on demand.
- Consider route-based code splitting for larger applications.
- **Dedicated API Modules/Services:** Organize your API calls into separate modules or service files, following the Single Responsibility Principle. Each module should handle requests for a specific resource or feature.
### 2. Common Patterns and Anti-patterns:
javascript
// services/userService.js
import { apiClient } from '../api';
- **Design Patterns Specific to Axios**:
- **Singleton Pattern**: Use a singleton pattern for the Axios instance to ensure a single configuration across the application.
- **Adapter Pattern**: Create an adapter layer to transform API responses into a consistent format.
- **Factory Pattern**: Use a factory pattern to create different Axios instances with specific configurations.
export const userService = {
getAllUsers: () => apiClient.get('/users'),
getUserById: (id) => apiClient.get(`/users/${id}`),
createUser: (userData) => apiClient.post('/users', userData),
updateUser: (id, userData) => apiClient.put(`/users/${id}`, userData),
deleteUser: (id) => apiClient.delete(`/users/${id}`),
};
- **Recommended Approaches for Common Tasks**:
- **Authentication**: Use request interceptors to add authentication headers (e.g., JWT tokens).
- **Error Handling**: Implement a centralized error handling function to log errors and display user-friendly messages.
- **Data Transformation**: Use response interceptors to transform data before it reaches the components.
// In a component or business logic:
// import { userService } from '../services/userService';
// const users = await userService.getAllUsers();
- **Anti-patterns and Code Smells to Avoid**:
- **Hardcoding URLs**: Avoid hardcoding API endpoints directly in the code.
- **Duplicated Request Logic**: Don't repeat API request logic across multiple components.
- **Ignoring Errors**: Never ignore errors returned by Axios; always handle them appropriately.
- **Leverage Interceptors for Global Logic:** Use request and response interceptors to centralize cross-cutting concerns like authentication, logging, error handling, and data transformation.
- **State Management Best Practices**:
- Use a state management library (e.g., Redux, Zustand, Recoil) to manage API data.
- Store API responses in a normalized format to improve performance.
- Utilize selectors to derive data from the store efficiently.
javascript
// In api.js or http-client.js, after creating apiClient
- **Error Handling Patterns**:
- Implement a global error boundary to catch unexpected errors.
- Display user-friendly error messages based on the error type.
- Log errors to a central logging service for monitoring and debugging.
// Request Interceptor: Add authentication token
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('jwt');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// Log outgoing request (optional)
console.log(`[Axios] ${config.method.toUpperCase()} ${config.url}`);
return config;
},
(error) => {
return Promise.reject(error);
}
);
### 3. Performance Considerations:
// Response Interceptor: Unified error handling and response transformation
apiClient.interceptors.response.use(
(response) => {
// You can transform response data here if needed
return response;
},
(error) => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('[Axios Error] Status:', error.response.status, 'Data:', error.response.data);
if (error.response.status === 401) {
// Handle unauthorized errors, e.g., redirect to login
console.error('Unauthorized: Redirecting to login...');
// window.location.href = '/login';
}
// You can throw a custom error here for more specific handling in components
return Promise.reject(new Error(error.response.data.message || 'An API error occurred.'));
} else if (error.request) {
// The request was made but no response was received
console.error('[Axios Error] No response received:', error.request);
return Promise.reject(new Error('No response from server. Please check your network connection.'));
} else {
// Something happened in setting up the request that triggered an Error
console.error('[Axios Error] Request setup error:', error.message);
return Promise.reject(new Error('An unexpected error occurred.'));
}
}
);
- **Optimization Techniques**:
- **Caching**: Implement caching mechanisms to avoid redundant API calls.
- **Request Debouncing**: Debounce frequent API requests to reduce server load.
- **Request Cancellation**: Cancel pending requests when the component unmounts or the user navigates away.
## 2. Common Patterns and Anti-patterns
- **Memory Management**:
- Clear Axios instances when they are no longer needed.
- Avoid creating unnecessary Axios instances.
- **Pattern: Use `async/await`:** Prefer `async/await` for cleaner, more readable asynchronous code over `.then().catch()` chains, especially when dealing with multiple sequential requests or complex logic.
- **Rendering Optimization**:
- Use memoization techniques to prevent unnecessary re-renders.
- Implement pagination or virtualized lists for large datasets.
javascript
// Good: Using async/await
async function fetchUserData(userId) {
try {
const response = await apiClient.get(`/users/${userId}`);
return response.data;
} catch (error) {
console.error('Failed to fetch user data:', error.message);
throw error; // Re-throw to allow further handling
}
}
- **Bundle Size Optimization**:
- Use tree shaking to remove unused code from the Axios library.
- Minify and compress the JavaScript bundle.
- **Pattern: Request Cancellation with `AbortController`:** For long-running requests or when a component might unmount before a request completes, use `AbortController` to cancel requests. This prevents memory leaks and unnecessary network activity.
- **Lazy Loading Strategies**:
- Lazy load API modules that are not immediately required.
- Use dynamic imports to load modules on demand.
javascript
// In a React component's useEffect or similar lifecycle hook
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
### 4. Security Best Practices:
async function fetchData() {
try {
const response = await apiClient.get('/data', { signal });
console.log(response.data);
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request cancelled:', error.message);
} else {
console.error('Error fetching data:', error.message);
}
}
}
- **Common Vulnerabilities and How to Prevent Them**:
- **Cross-Site Scripting (XSS)**: Sanitize user input to prevent XSS attacks.
- **Cross-Site Request Forgery (CSRF)**: Implement CSRF protection mechanisms.
- **Man-in-the-Middle (MITM) Attacks**: Use HTTPS to encrypt communication between the client and the server.
fetchData();
- **Input Validation**:
- Validate user input on both the client and server sides.
- Use appropriate validation libraries to prevent injection attacks.
return () => {
// Abort the request if the component unmounts
controller.abort();
};
}, []);
- **Authentication and Authorization Patterns**:
- Use a secure authentication protocol (e.g., OAuth 2.0, OpenID Connect).
- Implement role-based access control (RBAC) to restrict access to sensitive data.
- **Anti-pattern: Direct `axios` calls everywhere:** Avoid `import axios from 'axios';` and then calling `axios.get()` directly in multiple places without using a configured instance. This leads to scattered configuration and makes global changes difficult.
- **Data Protection Strategies**:
- Encrypt sensitive data at rest and in transit.
- Use appropriate data masking techniques to protect sensitive information.
- **Anti-pattern: Ignoring errors:** Always include `catch` blocks or implement comprehensive error handling via response interceptors. Unhandled promise rejections can lead to silent failures or crashes.
- **Secure API Communication**:
- Use HTTPS for all API communication.
- Implement rate limiting to prevent abuse.
- Monitor API traffic for suspicious activity.
- **Anti-pattern: Hardcoding sensitive information:** Never hardcode `baseURL`, API keys, or other sensitive credentials directly in your code. Use environment variables (e.g., `process.env.VITE_API_URL` for Vite, `process.env.REACT_APP_API_URL` for Create React App, or `.env` files for Node.js).
### 5. Testing Approaches:
## 3. Performance Considerations
- **Unit Testing Strategies**:
- Mock Axios requests using libraries like `axios-mock-adapter` or `nock`.
- Test individual API functions in isolation.
- Verify that requests are made with the correct parameters and headers.
- **Set Request Timeouts:** Always configure a `timeout` on your Axios instances or individual requests. This prevents requests from hanging indefinitely, especially in cases of network issues or unresponsive servers.
- **Integration Testing**:
- Test the interaction between API modules and components.
- Verify that data is fetched and displayed correctly.
- Use a testing framework like Jest or Mocha.
javascript
const apiClient = axios.create({
timeout: 10000, // 10 seconds
});
- **End-to-End Testing**:
- Test the entire application workflow from the user's perspective.
- Use a testing framework like Cypress or Selenium.
- **Combine `timeout` with `AbortSignal`:** Understand that `timeout` handles the time until a response is received, while `AbortSignal` allows for explicit cancellation of the underlying connection. For robust control, use both.
- **Test Organization**:
- Organize tests by module or feature.
- Use descriptive names for test cases.
- Follow a consistent testing style.
javascript
axios.get('/long-request', {
timeout: 5000, // Response timeout
signal: AbortSignal.timeout(10000) // Connection timeout after 10 seconds (Node.js 17.3+)
});
- **Mocking and Stubbing**:
- Use mocking to isolate components from external dependencies.
- Use stubbing to replace API responses with predefined data.
- **Client-Side Caching:** For frequently accessed data that doesn't change often, consider implementing client-side caching strategies (e.g., using libraries like `React Query`, `SWR`, or a custom in-memory cache). This reduces redundant network requests and improves perceived performance.
### 6. Common Pitfalls and Gotchas:
- **Request Throttling/Debouncing:** For user interactions that trigger frequent API calls (e.g., search input, scroll events), implement throttling or debouncing to limit the rate of requests sent to the server. This prevents overloading the backend and improves client-side responsiveness.
- **Frequent Mistakes Developers Make**:
- Forgetting to handle errors.
- Using incorrect HTTP methods.
- Hardcoding URLs.
- Not setting appropriate headers.
- **Minimize Bundle Size (Contextual):** While Axios is generally lightweight, for extremely small applications where every byte counts, the native `Fetch API` might be considered. However, Axios's features (interceptors, automatic JSON parsing, error handling) often justify its inclusion for most projects.
- **Edge Cases to Be Aware Of**:
- Network errors.
- Server downtime.
- Rate limiting.
- API versioning.
## 4. Common Pitfalls and Gotchas
- **Version-Specific Issues**:
- Be aware of breaking changes between Axios versions.
- Consult the Axios documentation for specific version information.
- **Forgetting to Return in Interceptors:** Request and response interceptors *must* return the `config` or `response` object, respectively, or a `Promise.reject(error)` for error handlers. Failing to do so will halt the request/response chain.
- **Compatibility Concerns**:
- Ensure that Axios is compatible with the target browsers and environments.
- Use polyfills if necessary.
- **`cancelToken` is Deprecated:** Avoid using `axios.CancelToken`. The modern and recommended approach for request cancellation is `AbortController`.
- **Debugging Strategies**:
- Use the browser's developer tools to inspect network requests.
- Log Axios requests and responses to the console.
- Use a debugging tool like VS Code's debugger.
- **Misunderstanding `timeout` vs. `AbortSignal`:** As mentioned, `timeout` is for response time, `AbortSignal` is for connection cancellation. Use both for comprehensive control.
### 7. Tooling and Environment:
- **CORS Issues:** Cross-Origin Resource Sharing (CORS) errors are common when the frontend and backend are on different domains. While primarily a backend configuration issue, ensure your frontend sends necessary headers (e.g., `Authorization`) that the backend expects for CORS preflight requests.
- **Recommended Development Tools**:
- VS Code with the ESLint and Prettier extensions.
- Axios DevTools for Chrome and Firefox.
- Postman or Insomnia for testing API endpoints.
- **Incorrect `Content-Type` for `POST`/`PUT`:** Axios automatically sets `Content-Type: application/json` for plain JavaScript objects. However, for other data types (e.g., `FormData` for file uploads), ensure you explicitly set the correct `Content-Type` header if Axios doesn't handle it automatically.
- **Build Configuration**:
- Use a build tool like Webpack or Parcel to bundle the application.
- Configure the build tool to optimize the bundle size.
- **Handling Different Error Structures:** APIs can return errors in various formats. Your response interceptor should be robust enough to parse different error structures (e.g., `error.response.data.message`, `error.response.data.errors`).
- **Linting and Formatting**:
- Use ESLint with a consistent set of rules to enforce code quality.
- Use Prettier to format the code automatically.
## 5. Testing Approaches
- **Deployment Best Practices**:
- Deploy the application to a secure hosting environment.
- Configure HTTPS for all API communication.
- Monitor the application for errors and performance issues.
- **Mocking API Responses:** For unit and integration tests, avoid making actual network requests. Use mocking libraries to simulate API responses.
- **CI/CD Integration**:
- Integrate automated testing and deployment into the CI/CD pipeline.
- Use a CI/CD tool like Jenkins, GitLab CI, or CircleCI.
- **`axios-mock-adapter`:** A popular library specifically designed for mocking Axios requests. It allows you to define expected requests and return mock responses.
javascript
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { userService } from '../services/userService'; // Your API service
const mock = new MockAdapter(axios); // Or new MockAdapter(apiClient);
describe('User Service', () => {
afterEach(() => {
mock.reset(); // Reset mocks after each test
});
test('should fetch all users', async () => {
const mockUsers = [{ id: 1, name: 'Alice' }];
mock.onGet('/users').reply(200, mockUsers);
const users = await userService.getAllUsers();
expect(users.data).toEqual(mockUsers);
});
test('should handle fetch error', async () => {
mock.onGet('/users').reply(500, { message: 'Server Error' });
await expect(userService.getAllUsers()).rejects.toThrow('An API error occurred.');
});
});
- **`MSW (Mock Service Worker)`:** A more powerful alternative that intercepts network requests at the service worker level (browser) or Node.js level. This allows for realistic mocking that works across different HTTP clients (Axios, Fetch, etc.) and is great for end-to-end testing scenarios.
- **Unit Test API Service Functions:** Write tests for your individual API service functions to ensure they construct the correct URLs, methods, and data payloads.
- **Test Interceptors:** Ensure your request and response interceptors behave as expected, e.g., that authentication tokens are added, and error responses are handled gracefully.
+122 -260
View File
@@ -1,284 +1,146 @@
---
description: Comprehensive guide to React best practices, covering code organization, performance, security, testing, and common pitfalls. Adhering to these guidelines helps developers build maintainable, scalable, and high-performing React applications.
globs: *.js,*.jsx,*.ts,*.tsx
description: Provides comprehensive best practices for writing clean, performant, and maintainable React applications, covering code organization, common patterns, performance, state management, and accessibility.
globs: **/*.{jsx,tsx}
---
# React Best Practices: A Comprehensive Guide
# React Best Practices
This document outlines the best practices for developing React applications, covering various aspects from code organization to security and testing. Following these guidelines leads to more maintainable, scalable, and performant applications.
This guide outlines best practices for developing robust, scalable, and maintainable React applications. Adhering to these principles will lead to more predictable code, easier debugging, and improved collaboration.
## 1. Code Organization and Structure
### 1.1 Directory Structure
A well-defined directory structure is crucial for maintainability. Here's a recommended structure:
src/
├── components/
│ ├── Button/
│ │ ├── Button.jsx
│ │ ├── Button.module.css
│ │ └── Button.test.jsx
│ ├── Input/
│ │ ├── Input.jsx
│ │ ├── Input.module.css
│ │ └── Input.test.jsx
│ └── ...
├── contexts/
│ ├── AuthContext.jsx
│ └── ThemeContext.jsx
├── hooks/
│ ├── useAuth.js
│ └── useTheme.js
├── pages/
│ ├── Home.jsx
│ ├── About.jsx
│ └── ...
├── services/
│ ├── api.js
│ └── auth.js
├── utils/
│ ├── helpers.js
│ └── validators.js
├── App.jsx
├── index.jsx
└── ...
- **`components/`**: Reusable UI components.
- Each component has its own directory containing the component file, associated styles (using CSS modules), and tests.
- **`contexts/`**: React context providers.
- **`hooks/`**: Custom React hooks.
- **`pages/`**: Top-level components representing different routes or views.
- **`services/`**: API interaction logic.
- **`utils/`**: Utility functions.
### 1.2 File Naming Conventions
- **Components**: Use PascalCase (e.g., `MyComponent.jsx`).
- **Hooks**: Use camelCase prefixed with `use` (e.g., `useMyHook.js`).
- **Contexts**: Use PascalCase suffixed with `Context` (e.g., `MyContext.jsx`).
- **Services/Utils**: Use camelCase (e.g., `apiService.js`, `stringUtils.js`).
- **CSS Modules**: Use `.module.css` or `.module.scss` (e.g., `Button.module.css`).
### 1.3 Module Organization
- **Co-location**: Keep related files (component, styles, tests) together in the same directory.
- **Single Responsibility**: Each module should have a clear and specific purpose.
- **Avoid Circular Dependencies**: Ensure modules don't depend on each other in a circular manner.
### 1.4 Component Architecture
- **Atomic Design**: Consider using Atomic Design principles (Atoms, Molecules, Organisms, Templates, Pages) to structure components.
- **Composition over Inheritance**: Favor component composition to reuse code and functionality.
- **Presentational and Container Components**: Separate UI rendering (presentational) from state management and logic (container).
### 1.5 Code Splitting Strategies
- **Route-Based Splitting**: Use `React.lazy` and `Suspense` to load components only when a specific route is accessed. This is very common and improves initial load time.
- **Component-Based Splitting**: Split large components into smaller chunks that can be loaded on demand.
- **Bundle Analyzer**: Use a tool like `webpack-bundle-analyzer` to identify large dependencies and optimize bundle size.
* **One Component Per File:** Generally, each React component should reside in its own file. For very small, stateless, or pure components that are tightly coupled, multiple components can be in one file.
* **Naming:** Use `PascalCase` for component files (e.g., `Button.jsx`, `UserProfile.tsx`) and `camelCase` for variables and functions.
* **Functional Components & Hooks:** Prefer functional components and React Hooks (`useState`, `useEffect`, `useContext`, `useReducer`, custom hooks) over class components for new development.
* **Sensible Folder Structure:**
* Start with a flat `src/` and evolve as the project grows.
* Common structure:
```
src/
├── assets/ # Images, icons, fonts
├── components/ # Reusable UI components (e.g., Button, Modal)
├── features/ # Domain-specific features (e.g., Auth, Products, UserProfile)
├── hooks/ # Custom React Hooks
├── pages/ # Top-level page components (e.g., HomePage, DashboardPage)
├── api/ # API service calls
├── utils/ # Utility functions (e.g., formatters, validators)
├── types/ # TypeScript type definitions
├── routes/ # Application routing configuration
├── store/ # Global state management (if applicable)
└── App.jsx
```
* **CSS Modules:** Use CSS Modules (`*.module.css`) or styled-components for encapsulated styling to prevent style conflicts.
* **Colocate Tests:** Place unit tests (`*.test.js` or `*.spec.js`) alongside the component files they test.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
### Patterns
* **Custom Hooks:** Extract reusable stateful logic into custom hooks.
```jsx
// hooks/useToggle.js
import { useState, useCallback } from 'react';
const useToggle = (initialValue = false) => {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue(prev => !prev), []);
return [value, toggle];
};
// Usage: const [isOpen, toggleOpen] = useToggle(false);
```
* **Compound Components:** For complex UI patterns where components work together (e.g., `Select.Root`, `Select.Option`).
* **Context API:** Use for sharing "global" data (e.g., theme, user info) across the component tree without prop drilling.
- **Higher-Order Components (HOCs)**: Reusable logic that wraps components (use with caution; prefer hooks).
- **Render Props**: Sharing code using a prop whose value is a function.
- **Compound Components**: Components that work together implicitly (e.g., `Tabs`, `Tab`).
- **Hooks**: Reusable stateful logic that can be shared across functional components.
### Anti-patterns
* **Prop Drilling:** Avoid passing props through many layers of components that don't directly use them. Use Context API or state management libraries instead.
* **Direct DOM Manipulation:** Let React manage the DOM. Use `useRef` sparingly for direct DOM access (e.g., focusing an input).
* **Mutating State Directly:** Never directly modify state objects or arrays. Always create a new copy.
```jsx
// BAD
// state.items.push(newItem);
// setState(state);
### 2.2 Recommended Approaches
- **Form Handling**: Use controlled components with local state or a form library like Formik or React Hook Form.
- **API Calls**: Use `useEffect` hook to make API calls and manage loading states.
- **Conditional Rendering**: Use short-circuit evaluation (`&&`) or ternary operators for simple conditions; use separate components for complex scenarios.
- **List Rendering**: Always provide a unique and stable `key` prop when rendering lists.
### 2.3 Anti-patterns and Code Smells
- **Direct DOM Manipulation**: Avoid directly manipulating the DOM; let React handle updates.
- **Mutating State Directly**: Always use `setState` or the state updater function to modify state.
- **Inline Styles**: Use CSS modules or styled-components for maintainable styles.
- **Over-Engineering**: Avoid using complex solutions for simple problems.
- **Prop Drilling**: Passing props through multiple levels of components without them being used.
### 2.4 State Management Best Practices
- **Local State**: Use `useState` for component-specific state.
- **Context API**: Use `useContext` for global state accessible to many components, but avoid for very frequently updated data.
- **Redux/Mobx**: Use these libraries for complex state management in large applications.
- **Recoil/Zustand**: Lightweight alternatives to Redux, often easier to set up and use.
- **Immutable Data**: Treat state as immutable to prevent unexpected side effects.
### 2.5 Error Handling Patterns
- **Error Boundaries**: Wrap components with error boundaries to catch errors during rendering and prevent crashes.
- **Try-Catch Blocks**: Use try-catch blocks for handling errors in asynchronous operations and event handlers.
- **Centralized Error Logging**: Implement a centralized error logging service to track errors and improve application stability.
// GOOD
setItems(prevItems => [...prevItems, newItem]);
```
* **Complex Logic in `useEffect`:** Keep `useEffect` focused on a single side effect. Extract complex logic into separate functions or custom hooks.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **`React.memo`, `useMemo`, `useCallback`:**
* `React.memo`: Memoizes functional components to prevent re-renders if props haven't changed. Use for "pure" components with expensive render logic.
* `useMemo`: Memoizes expensive calculations.
* `useCallback`: Memoizes functions to prevent unnecessary re-creation, useful for passing stable functions to `React.memo` children or `useEffect` dependencies.
* **Caution:** Don't over-optimize. These add overhead; use them when profiling indicates a performance bottleneck.
* **Key Prop in Lists:** Always provide a unique and stable `key` prop when rendering lists of elements. Avoid using array indexes as keys if the list items can change order, be added, or removed.
```jsx
{items.map(item => (
<ListItem key={item.id} item={item} />
))}
```
* **Lazy Loading / Code Splitting:** Use `React.lazy` and `Suspense` to split your application's code into smaller chunks, loading them only when needed.
```jsx
const LazyComponent = React.lazy(() => import('./MyHeavyComponent'));
function App() {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</React.Suspense>
);
}
```
* **Virtualization:** For very long lists, use libraries like `react-window` or `react-virtualized` to render only the visible items.
- **Memoization**: Use `React.memo`, `useMemo`, and `useCallback` to prevent unnecessary re-renders and recalculations.
- **Virtualization**: Use libraries like `react-window` or `react-virtualized` to efficiently render large lists or tables.
- **Debouncing/Throttling**: Limit the rate at which functions are executed (e.g., in input fields).
- **Code Splitting**: Load code on demand using `React.lazy` and `Suspense`.
## 4. Common Pitfalls and Gotchas
### 3.2 Memory Management
* **Incorrect `useEffect` Dependencies:**
* Missing dependencies can lead to stale closures or incorrect behavior.
* Over-specifying dependencies can lead to infinite loops or unnecessary re-runs.
* Use ESLint's `exhaustive-deps` rule.
* **Mutable Objects in State:** Modifying an object or array directly in state won't trigger a re-render because React performs a shallow comparison. Always create new objects/arrays.
* **Race Conditions in `useEffect`:** Handle asynchronous operations in `useEffect` with cleanup functions to prevent updates on unmounted components or outdated data.
```jsx
useEffect(() => {
let didCancel = false;
async function fetchData() {
const data = await myApiCall();
if (!didCancel) {
setData(data);
}
}
fetchData();
return () => { didCancel = true; }; // Cleanup
}, [someDependency]);
```
* **Props are Read-Only:** Never modify props directly within a component. If a value needs to change, it should be managed as state in the component itself or its parent.
- **Avoid Memory Leaks**: Clean up event listeners, timers, and subscriptions in `useEffect`'s cleanup function.
- **Release Unused Objects**: Avoid holding onto large objects in memory when they are no longer needed.
- **Garbage Collection**: Understand how JavaScript's garbage collection works and avoid creating unnecessary objects.
## 5. Component Architecture
### 3.3 Rendering Optimization
* **Single Responsibility Principle:** Each component should ideally do one thing well. This makes components easier to understand, test, and reuse.
* **Presentational vs. Container Components (Smart/Dumb):**
* **Presentational (Dumb) Components:** Focus on *how things look*. Receive data and callbacks via props, have no state of their own (or only UI state), and are typically stateless functional components.
* **Container (Smart) Components:** Focus on *how things work*. Manage state, fetch data, and pass data/callbacks to presentational components.
* **Composition Over Inheritance:** React encourages composition. Build complex UIs by composing smaller, simpler components together.
- **Minimize State Updates**: Avoid unnecessary state updates that trigger re-renders.
- **Batch Updates**: Batch multiple state updates into a single update using `ReactDOM.unstable_batchedUpdates`.
- **Keys**: Ensure that keys are unique and consistent across renders.
## 6. State Management
### 3.4 Bundle Size Optimization
* **Local Component State (`useState`):** For state that is only relevant to a single component.
* **`useReducer`:** A good alternative to `useState` for more complex state logic, especially when state transitions depend on previous state or involve multiple sub-values.
* **Context API:** For sharing state or functions that are needed by many components at different nesting levels, avoiding prop drilling.
* **External Libraries (Redux, Zustand, Jotai, Recoil):** Consider these for large applications with complex global state requirements, cross-cutting concerns, or when you need advanced features like middleware, time-travel debugging, or derived state.
- **Tree Shaking**: Remove unused code during the build process.
- **Minification**: Reduce the size of JavaScript and CSS files.
- **Image Optimization**: Compress and optimize images to reduce file size.
- **Dependency Analysis**: Use tools like `webpack-bundle-analyzer` to identify large dependencies.
## 7. Accessibility (A11y)
### 3.5 Lazy Loading Strategies
* **Semantic HTML:** Use appropriate HTML elements (`<button>`, `<input>`, `<nav>`, `<main>`, etc.) for their intended purpose.
* **ARIA Attributes:** Use `aria-*` attributes when semantic HTML isn't sufficient for custom interactive components (e.g., `aria-label`, `aria-expanded`).
* **Keyboard Navigation:** Ensure all interactive elements are reachable and operable via keyboard (Tab, Enter, Space).
* **Focus Management:** Manage focus for dynamic content like modals, dropdowns, and form submissions.
* **Alt Text for Images:** Provide meaningful `alt` attributes for all `<img>` tags.
* **ESLint `jsx-a11y` Plugin:** Integrate this plugin into your development workflow to catch common accessibility issues early.
- **Route-Based Lazy Loading**: Load components when a user navigates to a specific route.
- **Component-Based Lazy Loading**: Load components when they are about to be rendered.
- **Intersection Observer**: Load components when they become visible in the viewport.
## 8. Testing Approaches
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and Prevention
- **Cross-Site Scripting (XSS)**: Sanitize user input to prevent malicious code injection.
- **Cross-Site Request Forgery (CSRF)**: Use anti-CSRF tokens to protect against unauthorized requests.
- **Denial of Service (DoS)**: Implement rate limiting and request validation to prevent abuse.
- **Injection Attacks**: Avoid directly embedding user input into database queries or system commands.
### 4.2 Input Validation
- **Client-Side Validation**: Validate user input in the browser to provide immediate feedback.
- **Server-Side Validation**: Always validate user input on the server to prevent malicious data.
- **Sanitize Input**: Sanitize user input to remove potentially harmful characters or code.
### 4.3 Authentication and Authorization
- **Secure Authentication**: Use secure authentication mechanisms like OAuth 2.0 or JWT.
- **Role-Based Access Control (RBAC)**: Implement RBAC to control access to resources based on user roles.
- **Multi-Factor Authentication (MFA)**: Enable MFA to add an extra layer of security.
### 4.4 Data Protection Strategies
- **Encryption**: Encrypt sensitive data at rest and in transit.
- **Data Masking**: Mask sensitive data in logs and UI displays.
- **Regular Backups**: Create regular backups of application data.
### 4.5 Secure API Communication
- **HTTPS**: Use HTTPS to encrypt communication between the client and the server.
- **API Keys**: Protect API keys and secrets.
- **CORS**: Configure Cross-Origin Resource Sharing (CORS) to prevent unauthorized access to APIs.
## 5. Testing Approaches
### 5.1 Unit Testing
- **Test Components**: Test individual components in isolation.
- **Testing Library**: Use React Testing Library for UI testing, focusing on user behavior.
- **Jest**: Use Jest as the test runner.
### 5.2 Integration Testing
- **Test Component Interactions**: Test how components interact with each other.
- **Mock API Calls**: Mock API calls to test component behavior in different scenarios.
- **React Testing Library**: Effective for testing integration points in components.
### 5.3 End-to-End (E2E) Testing
- **Test Full Application Flows**: Test complete user flows, such as login, registration, and checkout.
- **Cypress/Playwright**: Use tools like Cypress or Playwright for E2E testing.
- **Automated Browser Tests**: Automate browser tests to ensure application stability.
### 5.4 Test Organization
- **Co-locate Tests**: Keep test files close to the components they test (e.g., `Button.test.jsx` in the `Button` directory).
- **Descriptive Names**: Use descriptive names for test files and test cases.
- **Test Suites**: Organize tests into logical suites.
### 5.5 Mocking and Stubbing
- **Mock Modules**: Mock external modules or API calls to isolate components during testing.
- **Stub Functions**: Stub function implementations to control component behavior.
- **Jest Mocks**: Utilize Jest's mocking capabilities for effective unit testing.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
- **Ignoring Keys in Lists**: Forgetting to provide unique and stable `key` props when rendering lists.
- **Incorrect State Updates**: Mutating state directly instead of using `setState` or the state updater function.
- **Missing Dependencies in `useEffect`**: Not including all dependencies in the dependency array of the `useEffect` hook.
- **Over-Using State**: Storing derived data in state instead of calculating it on demand.
### 6.2 Edge Cases
- **Asynchronous State Updates**: Handling state updates in asynchronous operations.
- **Race Conditions**: Preventing race conditions when making multiple API calls.
- **Handling Errors in Event Handlers**: Properly handling errors in event handlers to prevent crashes.
### 6.3 Version-Specific Issues
- **React 16 vs. React 17/18**: Understanding differences in lifecycle methods, error handling, and concurrent mode.
- **Deprecated Features**: Being aware of deprecated features and using recommended alternatives.
### 6.4 Compatibility Concerns
- **Browser Compatibility**: Ensuring compatibility with different browsers and devices.
- **Library Compatibility**: Ensuring compatibility between React and other libraries.
### 6.5 Debugging Strategies
- **React DevTools**: Use React DevTools to inspect component hierarchies, props, and state.
- **Console Logging**: Use console logging to debug code and track variables.
- **Breakpoints**: Set breakpoints in the code to step through execution and inspect variables.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **VS Code**: A popular code editor with excellent React support.
- **Create React App**: A tool for quickly setting up a new React project.
- **React DevTools**: A browser extension for inspecting React components.
- **ESLint**: A linter for enforcing code style and preventing errors.
- **Prettier**: A code formatter for automatically formatting code.
### 7.2 Build Configuration
- **Webpack/Vite**: Configure Webpack or Vite to bundle and optimize code.
- **Babel**: Configure Babel to transpile JavaScript code to older versions.
- **Environment Variables**: Use environment variables to configure different environments.
### 7.3 Linting and Formatting
- **ESLint**: Configure ESLint with recommended React rules.
- **Prettier**: Configure Prettier to automatically format code.
- **Husky/lint-staged**: Use Husky and lint-staged to run linters and formatters before committing code.
### 7.4 Deployment Best Practices
- **Static Hosting**: Host static assets on a CDN.
- **Server-Side Rendering (SSR)**: Use SSR to improve SEO and initial load time.
- **Continuous Deployment**: Automate the deployment process using CI/CD.
### 7.5 CI/CD Integration
- **GitHub Actions/GitLab CI**: Use GitHub Actions or GitLab CI to automate testing, linting, and deployment.
- **Automated Testing**: Run automated tests on every commit or pull request.
- **Automated Deployment**: Automatically deploy code to production after successful tests.
By following these best practices, React developers can build high-quality, maintainable, and scalable applications that meet the demands of modern web development. Continual education and adaptation to emerging trends in the React ecosystem are crucial for sustained success.
* **Unit Testing:** Focus on testing individual components or pure functions in isolation.
* **React Testing Library:** Preferred for testing React components. It encourages testing components the way users interact with them, focusing on behavior rather than implementation details.
* **Jest:** A popular JavaScript testing framework often used with React Testing Library.
* **Integration Testing:** Test how multiple components work together.
* **End-to-End (E2E) Testing:** Test the entire application flow from a user's perspective using tools like Cypress or Playwright.
* **Mocking:** Mock API calls and external dependencies to ensure tests are fast, reliable, and isolated.
* **Test Alongside Components:** Keep test files (`*.test.js` or `*.spec.js`) in the same directory as the components they test for easy discoverability.
+284 -622
View File
@@ -1,672 +1,334 @@
---
description: This rule provides guidelines for using Zustand, a simple and unopinionated state management library, in React applications. It covers best practices for code organization, performance optimization, testing, and common pitfalls to avoid.
globs: *.js,*.jsx,*.ts,*.tsx
description: This rule file provides definitive guidelines for using Zustand in React applications, focusing on modularity, performance, and maintainability through opinionated best practices and code examples.
globs: **/*.{js,jsx,ts,tsx}
---
# Zustand Best Practices
# zustand Best Practices
This document outlines best practices for using Zustand in your React applications. Zustand is a simple and unopinionated state management library. Following these guidelines will help you write maintainable, performant, and scalable applications.
Zustand is our go-to for global state management due to its simplicity and performance. This guide outlines our team's definitive best practices for using Zustand, ensuring consistency, maintainability, and optimal performance across all projects.
## 1. Code Organization and Structure
## 1. Store Definition & Organization
### 1.1. Directory Structure
### 1.1 Modular Slices for Large Stores
Organize your store files in a dedicated directory, such as `store` or `state`, at the root of your project or within a specific feature directory. This enhances discoverability and maintainability.
Split large stores into logical "slices" to keep files focused and maintainable. Combine these slices into a single `create` call.
❌ **BAD: Monolithic Store**
```javascript
// src/store/appStore.js
import { create } from 'zustand';
src/
├── components/
│ ├── ...
├── store/
│ ├── index.ts # Main store file (optional)
│ ├── bearStore.ts # Example store
│ ├── fishStore.ts # Example store
│ └── utils.ts # Utility functions for stores
├── App.tsx
└── ...
export const useAppStore = create((set) => ({
// Auth state
token: null,
user: null,
login: (token, user) => set({ token, user }),
logout: () => set({ token: null, user: null }),
// UI state
isLoading: false,
modalOpen: false,
setLoading: (loading) => set({ isLoading: loading }),
toggleModal: () => set((state) => ({ modalOpen: !state.modalOpen })),
### 1.2. File Naming Conventions
// Cart state
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
removeItem: (id) => set((state) => ({ items: state.items.filter(i => i.id !== id) })),
}));
```
Use descriptive names for your store files, typically reflecting the domain or feature the store manages. For example, `userStore.ts`, `cartStore.js`, or `settingsStore.tsx`. Use PascalCase for the store name itself (e.g., `UserStore`).
### 1.3. Module Organization
- **Single Store per File:** Prefer defining one Zustand store per file. This improves readability and maintainability.
- **Slices Pattern:** For complex stores, consider using the slices pattern to divide the store into smaller, more manageable pieces. Each slice manages a specific part of the state and its related actions.
typescript
// store/bearStore.ts
import { StateCreator, create } from 'zustand';
interface BearSlice {
bears: number;
addBear: () => void;
}
const createBearSlice: StateCreator<BearSlice> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
✅ **GOOD: Sliced Store**
```javascript
// src/store/authSlice.js
export const createAuthSlice = (set) => ({
token: null,
user: null,
login: (token, user) => set({ token, user }),
logout: () => set({ token: null, user: null }),
});
export const useBearStore = create<BearSlice>()((...a) => ({
...createBearSlice(...a),
// src/store/uiSlice.js
export const createUiSlice = (set) => ({
isLoading: false,
modalOpen: false,
setLoading: (loading) => set({ isLoading: loading }),
toggleModal: () => set((state) => ({ modalOpen: !state.modalOpen })),
});
// src/store/index.js
import { create } from 'zustand';
import { createAuthSlice } from './authSlice';
import { createUiSlice } from './uiSlice';
export const useAppStore = create((...a) => ({
...createAuthSlice(...a),
...createUiSlice(...a),
}));
```
> **Context:** This pattern scales better, improves type safety, and makes it easier to reason about specific parts of your state.
### 1.2 Naming Conventions & File Layout
Name store hooks `use[Feature]Store` and place them in `src/store/[feature]Store.js` (or `.ts/.tsx`). Export only the main hook.
❌ **BAD: Generic Naming & Poor Location**
```javascript
// src/components/MyComponent/store.js
import { create } from 'zustand';
export const useStore = create(() => ({ /* ... */ }));
```
✅ **GOOD: Specific Naming & Centralized Location**
```javascript
// src/store/cartStore.js
import { create } from 'zustand';
export const useCartStore = create((set) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
}));
// Another slice could be in fishStore.ts, etc.
### 1.4. Component Architecture
- **Presentational and Container Components:** Separate presentational (UI) components from container components that interact with the Zustand store. Container components fetch data from the store and pass it down to presentational components.
- **Hooks for Data Fetching:** Utilize Zustand's `useStore` hook within container components to subscribe to specific parts of the state.
### 1.5. Code Splitting Strategies
- **Lazy Loading Stores:** Load stores on demand using dynamic imports. This can reduce the initial bundle size, especially for larger applications.
- **Feature-Based Splitting:** Split your application into feature modules and create separate stores for each feature. This allows for independent loading and reduces dependencies between different parts of the application.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns Specific to Zustand
- **Colocated Actions and State:** Keep actions and the state they modify within the same store. This promotes encapsulation and makes it easier to understand how the store's state is updated.
- **Selectors:** Use selectors to derive computed values from the store's state. Selectors should be memoized to prevent unnecessary re-renders.
typescript
// store/userStore.ts
// src/store/userStore.ts (TypeScript example)
import { create } from 'zustand';
interface UserState {
name: string;
age: number;
id: string | null;
name: string | null;
fetchUser: () => Promise<void>;
}
interface UserActions {
setName: (name: string) => void;
isAdult: () => boolean; // Selector
}
export const useUserStore = create<UserState & UserActions>((set, get) => ({
name: 'John Doe',
age: 20,
setName: (name) => set({ name }),
isAdult: () => get().age >= 18, // Selector
}));
### 2.2. Recommended Approaches for Common Tasks
- **Asynchronous Actions:** Use `async/await` within actions to handle asynchronous operations such as fetching data from an API.
typescript
interface DataState {
data: any | null;
isLoading: boolean;
fetchData: () => Promise<void>;
}
export const useDataStore = create<DataState>((set) => ({
data: null,
isLoading: false,
fetchData: async () => {
set({ isLoading: true });
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
set({ data, isLoading: false });
} catch (error) {
console.error('Error fetching data:', error);
set({ isLoading: false, data: null });
}
export const useUserStore = create<UserState>((set) => ({
id: null,
name: null,
fetchUser: async () => {
// ... API call
set({ id: '123', name: 'John Doe' });
},
}));
```
> **Context:** This makes stores easily discoverable and prevents naming collisions.
## 2. State Access & Performance
- **Persisting State:** Use the `zustand/middleware`'s `persist` middleware to persist the store's state to local storage or another storage mechanism. Configure a `partialize` function to select the state you want to persist.
### 2.1 Selective Subscriptions with Selectors
typescript
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
Always use selector functions with `useStore` to subscribe only to the specific parts of the state your component needs. This prevents unnecessary re-renders. Use shallow comparison (`shallow`) for objects or arrays if the entire object/array is needed.
interface AuthState {
token: string | null;
setToken: (token: string | null) => void;
}
❌ **BAD: Subscribing to Entire State**
```javascript
// Component re-renders on ANY state change in useCartStore
const cart = useCartStore();
console.log(cart.items.length);
```
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
token: null,
setToken: (token) => set({ token }),
}),
{
name: 'auth-storage', // unique name
partialize: (state) => ({ token: state.token }), // Only persist the token
}
)
)
✅ **GOOD: Selective Subscription**
```javascript
// Component re-renders ONLY when cart.items changes
import { shallow } from 'zustand/shallow';
// For primitive values:
const itemCount = useCartStore((state) => state.items.length);
### 2.3. Anti-patterns and Code Smells to Avoid
- **Over-reliance on Global State:** Avoid storing everything in a single global store. Instead, break down your application's state into smaller, more manageable stores based on feature or domain.
- **Mutating State Directly:** Never mutate the state directly. Always use the `set` function provided by Zustand to ensure proper state updates and re-renders. Consider using Immer middleware (`zustand/middleware`) for immutable updates with mutable syntax.
- **Complex Selectors without Memoization:** Avoid complex selectors that perform expensive computations without memoization. This can lead to performance issues, especially with frequent state updates.
- **Creating Stores Inside Components:** Do not define Zustand stores inside React components. This will cause the store to be re-created on every render, leading to data loss and unexpected behavior.
### 2.4. State Management Best Practices
- **Single Source of Truth:** Treat the Zustand store as the single source of truth for your application's state.
- **Minimize State:** Store only the essential data in the store. Derive computed values using selectors.
- **Clear State Transitions:** Ensure that state transitions are predictable and well-defined. Avoid complex and convoluted update logic.
### 2.5. Error Handling Patterns
- **Try/Catch Blocks in Actions:** Wrap asynchronous actions in `try/catch` blocks to handle potential errors. Update the state to reflect the error status.
- **Error Boundary Components:** Use React error boundary components to catch errors that occur during rendering.
- **Centralized Error Logging:** Implement a centralized error logging mechanism to track errors that occur in your application. Send error reports to a monitoring service.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Selective Updates:** Use selectors to subscribe to only the specific parts of the state that your component needs. This prevents unnecessary re-renders when other parts of the state change.
- **Shallow Equality Checks:** By default, Zustand uses strict equality (`===`) for state comparisons. If you're using complex objects, use `shallow` from `zustand/shallow` as an equality function in `useStore` to avoid unnecessary re-renders.
- **Memoization:** Memoize selectors using libraries like `reselect` or `lodash.memoize` to prevent unnecessary re-computations.
- **Batch Updates:** Use `unstable_batchedUpdates` from `react-dom` to batch multiple state updates into a single render cycle.
### 3.2. Memory Management
- **Avoid Leaks:** Ensure that you are not creating memory leaks by properly cleaning up any subscriptions or event listeners that you create.
- **Limit Store Size:** Keep your stores as small as possible by only storing the data that you need.
### 3.3. Rendering Optimization
- **Virtualization:** If you are rendering large lists of data, use virtualization techniques (e.g., `react-window`, `react-virtualized`) to only render the visible items.
- **Code Splitting:** Split your application into smaller bundles to reduce the initial load time.
### 3.4. Bundle Size Optimization
- **Tree Shaking:** Ensure that your build process is configured to perform tree shaking, which removes unused code from your bundles.
- **Minimize Dependencies:** Use only the dependencies that you need. Avoid importing entire libraries when you only need a few functions.
- **Compression:** Compress your bundles using tools like Gzip or Brotli.
### 3.5. Lazy Loading Strategies
- **Component-Level Lazy Loading:** Lazy load components using `React.lazy` and `Suspense`.
- **Route-Based Lazy Loading:** Lazy load routes using `react-router-dom`'s `lazy` function.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and How to Prevent Them
- **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks.
- **Cross-Site Request Forgery (CSRF):** Protect your API endpoints from CSRF attacks by implementing CSRF tokens.
- **Sensitive Data Exposure:** Avoid storing sensitive data in the store unless absolutely necessary. Encrypt sensitive data if it must be stored.
### 4.2. Input Validation
- **Server-Side Validation:** Always validate user inputs on the server-side.
- **Client-Side Validation:** Perform client-side validation to provide immediate feedback to the user.
### 4.3. Authentication and Authorization Patterns
- **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization.
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of your application based on user roles.
### 4.4. Data Protection Strategies
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and other outputs.
### 4.5. Secure API Communication
- **HTTPS:** Use HTTPS to encrypt communication between the client and server.
- **API Rate Limiting:** Implement API rate limiting to prevent abuse.
## 5. Testing Approaches
### 5.1. Unit Testing Strategies
- **Test Store Logic:** Write unit tests to verify the logic of your Zustand stores.
- **Mock Dependencies:** Mock any external dependencies (e.g., API calls) to isolate the store logic.
- **Test State Transitions:** Ensure that state transitions are correct by asserting the expected state after each action.
### 5.2. Integration Testing
- **Test Component Interactions:** Write integration tests to verify that your components interact correctly with the Zustand store.
- **Render Components:** Render your components and simulate user interactions to test the integration between the UI and the store.
### 5.3. End-to-End Testing
- **Simulate User Flows:** Write end-to-end tests to simulate complete user flows through your application.
- **Test Real-World Scenarios:** Test real-world scenarios to ensure that your application is working correctly in a production-like environment.
### 5.4. Test Organization
- **Colocate Tests:** Colocate your tests with the code that they are testing.
- **Use Descriptive Names:** Use descriptive names for your test files and test cases.
### 5.5. Mocking and Stubbing
- **Jest Mocks:** Use Jest's mocking capabilities to mock external dependencies.
- **Sinon Stubs:** Use Sinon to create stubs for functions and methods.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes Developers Make
- **Incorrectly Using `set`:** Forgetting to use the functional form of `set` when updating state based on the previous state.
- **Not Handling Asynchronous Errors:** Failing to handle errors in asynchronous actions.
- **Over-relying on `shallow`:** Using `shallow` equality when a deep comparison is actually required.
### 6.2. Edge Cases to Be Aware Of
- **Race Conditions:** Be aware of potential race conditions when handling asynchronous actions.
- **Context Loss:** Ensure that the Zustand provider is properly configured to avoid context loss issues.
### 6.3. Version-Specific Issues
- **Check Release Notes:** Always check the release notes for new versions of Zustand to be aware of any breaking changes or new features.
### 6.4. Compatibility Concerns
- **React Version:** Ensure that your version of React is compatible with the version of Zustand that you are using.
### 6.5. Debugging Strategies
- **Zustand Devtools:** Use the Zustand Devtools extension to inspect the store's state and track state changes.
- **Console Logging:** Use console logging to debug your store logic and component interactions.
- **Breakpoints:** Set breakpoints in your code to step through the execution and inspect the state.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **VS Code:** Use VS Code as your code editor.
- **ESLint:** Use ESLint to enforce code style and prevent errors.
- **Prettier:** Use Prettier to automatically format your code.
- **Zustand Devtools:** Use the Zustand Devtools extension to inspect the store's state.
### 7.2. Build Configuration
- **Webpack:** Use Webpack to bundle your code.
- **Parcel:** Use Parcel for zero-configuration bundling.
- **Rollup:** Use Rollup for building libraries.
### 7.3. Linting and Formatting
- **ESLint:** Configure ESLint to enforce code style and best practices.
- **Prettier:** Configure Prettier to automatically format your code.
- **Husky:** Use Husky to run linters and formatters before committing code.
### 7.4. Deployment Best Practices
- **Environment Variables:** Use environment variables to configure your application for different environments.
- **CDN:** Use a CDN to serve your static assets.
- **Caching:** Implement caching to improve performance.
### 7.5. CI/CD Integration
- **GitHub Actions:** Use GitHub Actions to automate your build, test, and deployment processes.
- **CircleCI:** Use CircleCI to automate your build, test, and deployment processes.
- **Jenkins:** Use Jenkins to automate your build, test, and deployment processes.
## 8. Zustand-X (zustandx.udecode.dev)
Zustand-X builds on top of Zustand to reduce boilerplate and enhance features, providing a store factory with derived selectors and actions.
### 8.1. Key Features
- **Less Boilerplate:** Simplified store creation.
- **Modular State Management:** Derived selectors and actions.
- **Middleware Support:** Integrates with `immer`, `devtools`, and `persist`.
- **TypeScript Support:** Full TypeScript support.
- **React-Tracked Support:** Integration with `react-tracked`.
### 8.2. Usage
javascript
import { createStore } from 'zustand-x';
const repoStore = createStore('repo')({
name: 'zustandX',
stars: 0,
owner: {
name: 'someone',
email: 'someone@xxx.com',
},
});
// Hook store
repoStore.useStore;
// Vanilla store
repoStore.store;
// Selectors
repoStore.use.name();
repoStore.get.name();
// Actions
repoStore.set.name('new name');
// Extend selectors
repoStore.extendSelectors((state, get, api) => ({
validName: () => get.name().trim(),
title: (prefix) => `${prefix + get.validName()} with ${get.stars()} stars`,
}));
// Extend actions
repoStore.extendActions((set, get, api) => ({
validName: (name) => {
set.name(name.trim());
},
reset: (name) => {
set.validName(name);
set.stars(0);
},
}));
### 8.3. Global Store
Combine multiple stores into a global store for easier access.
javascript
import { mapValuesKey } from 'zustand-x';
export const rootStore = {
repo: repoStore,
// other stores
};
export const useStore = () => mapValuesKey('use', rootStore);
export const useTrackedStore = () => mapValuesKey('useTracked', rootStore);
export const store = mapValuesKey('get', rootStore);
export const actions = mapValuesKey('set', rootStore);
// Usage
useStore().repo.name();
actions.repo.stars(store.repo.stars + 1);
## 9. zustand-ards
A library of simple, opinionated utilities for Zustand to improve the developer experience.
### 9.1 Installation
bash
pnpm i zustand-ards
# or
npm i zustand-ards
### 9.2 Basic Usage
javascript
import { withZustandards } from 'zustand-ards';
const useWithZustandards = withZustandards(useStore);
const { bears, increaseBears } = useWithZustandards(['bears', 'increaseBears']);
### 9.3 Store Hook Enhancements
- **`withZustandards`:** Combines `withArraySelector` and `withDefaultShallow`.
- **`withArraySelector`:** Adds an array selector to the store hook, eliminating the need for multiple hooks or complex selector functions.
- **`withDefaultShallow`:** Makes the store hook shallow by default, equivalent to passing `shallow` from `zustand/shallow` to the original hook.
javascript
import { withArraySelector } from 'zustand-ards';
const useStoreWithArray = withArraySelector(useExampleStore);
const { bears, increaseBears } = useStoreWithArray(['bears', 'increaseBears']);
import { withDefaultShallow } from 'zustand-ards';
const useShallowStore = withDefaultShallow(useExampleStore);
const { wizards } = useShallowStore((state) => ({ wizards: state.wizards }));
## 10. TypeScript Guide
### 10.1. Basic Usage
Annotate the store's state type using `create<T>()(...)`.
typescript
import { create } from 'zustand';
interface BearState {
bears: number;
increase: (by: number) => void;
}
const useBearStore = create<BearState>()((set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by }))
}));
### 10.2. Using `combine`
`combine` infers the state, so no need to type it.
typescript
import { create } from 'zustand';
import { combine } from 'zustand/middleware';
const useBearStore = create(
combine({ bears: 0 }, (set) => ({
increase: (by: number) => set((state) => ({ bears: state.bears + by }))
}))
// For objects/arrays: use shallow comparison
const { items, total } = useCartStore(
(state) => ({ items: state.items, total: state.total }),
shallow // Important for objects/arrays to prevent re-renders on reference changes
);
```
> **Context:** This is the single most important performance optimization in Zustand. Without it, your components will re-render far more often than necessary.
### 2.2 Immutable Updates
### 10.3. Using Middlewares
Always update state immutably. Use the functional `set(state => ...)` form to ensure you're working with the latest state.
Use middlewares immediately inside `create` to ensure contextual inference works correctly. Devtools should be used last to prevent other middlewares from mutating the `setState` before it.
❌ **BAD: Direct Mutation**
```javascript
// This mutates the state directly, which can lead to bugs and difficult debugging.
// Zustand might not detect the change, or other parts of your app might get stale state.
const addItem = (item) => set((state) => {
state.items.push(item); // ❌ DIRECT MUTATION
return state;
});
```
typescript
✅ **GOOD: Functional, Immutable Updates**
```javascript
const addItem = (item) => set((state) => ({
items: [...state.items, item], // ✅ Creates a new array
}));
const updateItemQuantity = (id, quantity) => set((state) => ({
items: state.items.map(item =>
item.id === id ? { ...item, quantity } : item
),
}));
```
> **Context:** Immutability is a core principle of React and state management. It simplifies change detection and prevents subtle bugs.
## 3. Side Effects & Asynchronous Logic
### 3.1 Centralized Async Actions
Place API calls and other side effects directly within your store actions. This centralizes data fetching logic and keeps components clean.
❌ **BAD: API Calls in Components**
```javascript
// src/components/ProductList.jsx
import React, { useEffect } from 'react';
import { useProductStore } from '../../store/productStore';
import api from '../../utils/api';
function ProductList() {
const { products, setProducts } = useProductStore();
useEffect(() => {
const fetchProducts = async () => {
const response = await api.get('/products');
setProducts(response.data);
};
fetchProducts();
}, [setProducts]);
// ... render products
}
```
✅ **GOOD: Store-Managed Async Actions**
```javascript
// src/store/productStore.js
import { create } from 'zustand';
import api from '../../utils/api';
export const useProductStore = create((set) => ({
products: [],
isLoading: false,
error: null,
fetchProducts: async () => {
set({ isLoading: true, error: null });
try {
const response = await api.get('/products');
set({ products: response.data, isLoading: false });
} catch (error) {
set({ error: error.message, isLoading: false });
}
},
}));
// src/components/ProductList.jsx
import React, { useEffect } from 'react';
import { useProductStore } from '../../store/productStore';
function ProductList() {
const { products, isLoading, error, fetchProducts } = useProductStore(
(state) => ({
products: state.products,
isLoading: state.isLoading,
error: state.error,
fetchProducts: state.fetchProducts,
}),
shallow
);
useEffect(() => {
fetchProducts();
}, [fetchProducts]);
if (isLoading) return <div>Loading products...</div>;
if (error) return <div>Error: {error}</div>;
// ... render products
}
```
> **Context:** This pattern keeps your components focused on rendering UI and your stores focused on managing data and side effects.
## 4. Middleware Usage
### 4.1 Purposeful & Conditional Middleware
Only apply middleware (`devtools`, `persist`, `immer`) where they are genuinely needed. Conditionally enable `devtools` to avoid performance overhead in production.
❌ **BAD: Unnecessary Middleware in Production**
```javascript
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
interface BearState {
bears: number;
increase: (by: number) => void;
}
export const useAuthStore = create(
devtools( // Always enabled
persist( // Always enabled, even if auth token is short-lived
(set) => ({ /* ... */ }),
{ name: 'auth-storage' }
)
)
);
```
const useBearStore = create<BearState>()(
devtools(
persist(
✅ **GOOD: Conditional Devtools & Targeted Persist**
```javascript
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
// Only enable devtools in development
const devtoolsMiddleware = (f) =>
process.env.NODE_ENV === 'development' ? devtools(f) : f;
export const useAuthStore = create(
devtoolsMiddleware( // Conditionally enabled
persist( // Only persist if truly needed (e.g., user preferences, not sensitive tokens)
(set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by }))
token: null,
user: null,
login: (token, user) => set({ token, user }),
logout: () => set({ token: null, user: null }),
}),
{ name: 'bearStore' }
{
name: 'auth-storage',
// Consider `getStorage: () => sessionStorage` for shorter-lived data
// Or don't persist sensitive tokens at all, rely on server-side cookies
}
)
)
);
### 10.4. Authoring Middlewares and Advanced Usage
Zustand middlewares can mutate the store. Higher-kinded mutators are available for complex type problems.
### 10.5. Middleware Examples
**Middleware that doesn't change the store type:**
typescript
import { create, State, StateCreator, StoreMutatorIdentifier } from 'zustand';
type Logger = <
T extends State,
Mps extends [StoreMutatorIdentifier, unknown][] = [],
Mcs extends [StoreMutatorIdentifier, unknown][] = [],
>(f: StateCreator<T, Mps, Mcs>, name?: string) => StateCreator<T, Mps, Mcs>;
const loggerImpl = (f, name) => (set, get, store) => {
const loggedSet = (...a) => {
set(...a);
console.log(...(name ? [`${name}:`] : []), get());
};
const setState = store.setState;
store.setState = (...a) => {
setState(...a);
console.log(...(name ? [`${name}:`] : []), store.getState());
};
return f(loggedSet, get, store);
};
export const logger = loggerImpl;
**Middleware that changes the store type:** Requires advanced TypeScript features.
### 10.6. Slices Pattern
The slices pattern is a way to split a store into smaller, more manageable parts.
typescript
import { create, StateCreator } from 'zustand';
interface BearSlice {
bears: number;
addBear: () => void;
eatFish: () => void;
}
interface FishSlice {
fishes: number;
addFish: () => void;
}
const createBearSlice: StateCreator<BearSlice> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
eatFish: () => set((state) => ({fishes: state.fishes -1}))
});
const createFishSlice: StateCreator<FishSlice> = (set) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 }))
});
export const useBoundStore = create<BearSlice & FishSlice>()((...a) => ({
...createBearSlice(...a),
...createFishSlice(...a),
}));
### 10.7. Bounded useStore Hook for Vanilla Stores
Provides type safety when using `useStore` with vanilla stores.
## 11. Zustand Tools (zustand-tools)
Tools for simpler Zustand usage with React.
### 11.1. `createSimple(initStore, middlewares)`
Creates a simple store with correct typings and hooks for easier usage.
javascript
import { createSimple } from 'zustand-tools';
const demoStore = createSimple({ foo: 'bar' });
/*
* will provide:
* demoStore.useStore.getState().foo
* demoStore.useStore.getState().setFoo(value)
* demoStore.hooks.useFoo() => [value, setter] // like useState
*/
const useFoo = demoStore.hooks.useFoo;
function App() {
const [foo, setFoo] = useFoo();
useEffect(() => {
setFoo('newBar');
}, [setFoo]);
return <div>{foo}</div>;
}
### 11.2. `createSimpleContext(initStore, middlewares)`
Basically the same as `createSimple` but returns a provider to use the store only for a specific context.
### 11.3. `useAllData()`
Returns all data from the store using a shallow compare.
### 11.4. Adding Additional Actions
Add additional actions to the generated store.
javascript
import { createSimple } from 'zustand-tools';
const { useStore } = createSimple(
{ foo: 1 },
{
actions: (set) => ({
increaseFoo: (amount) => set((state) => ({ foo: state.foo + amount }))
// Example for a store that doesn't need persist, but benefits from devtools in dev
export const useUiStore = create(
devtoolsMiddleware(
(set) => ({
modalOpen: false,
toggleModal: () => set((state) => ({ modalOpen: !state.modalOpen })),
})
}
)
);
```
> **Context:** Middleware adds overhead. Be intentional about where and when you use it. `devtools` is invaluable for debugging but should be stripped from production builds.
useStore.getState().increaseFoo(5);
### 4.2 Immer Middleware for Complex Immutable Updates
For deeply nested or complex state updates, use the `immer` middleware to simplify immutable logic.
### 11.5. Adding Middlewares
```javascript
// src/store/settingsStore.js
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
Middlewares can be added by passing an array as middlewares in the second parameter.
javascript
import { createSimple } from 'zustand-tools';
import { devtools } from 'zustand/middleware';
const demoStore = createSimple({ foo: 'bar' }, { middlewares: [(initializer) => devtools(initializer, { enabled: true })] });
## 12. Practice with no Store Actions
### 12.1. Colocated Actions and State
The recommended usage is to colocate actions and states within the store.
javascript
export const useBoundStore = create((set) => ({
count: 0,
text: 'hello',
inc: () => set((state) => ({ count: state.count + 1 })),
setText: (text) => set({ text }),
}));
### 12.2. External Actions
An alternative approach is to define actions at the module level, external to the store.
javascript
export const useBoundStore = create(() => ({
count: 0,
text: 'hello',
}));
export const inc = () =>
useBoundStore.setState((state) => ({ count: state.count + 1 }));
export const setText = (text) => useBoundStore.setState({ text });
## Conclusion
By following these best practices, you can build robust and scalable applications using Zustand. Remember to adapt these guidelines to your specific project needs and coding style.
export const useSettingsStore = create(
immer((set) => ({
userSettings: {
theme: 'dark',
notifications: {
email: true,
sms: false,
},
},
updateTheme: (theme) =>
set((state) => {
state.userSettings.theme = theme; // ✅ Immer allows direct mutation within set
}),
toggleEmailNotifications: () =>
set((state) => {
state.userSettings.notifications.email = !state.userSettings.notifications.email;
}),
}))
);
```
> **Context:** Immer makes immutable updates feel like mutable ones, reducing boilerplate and potential errors for complex state structures. Only use it if you find the manual immutable updates cumbersome.
+1 -1
View File
@@ -5,7 +5,7 @@ paths:
exa_results_dir: "exa_results"
api:
llm_model: "gemini/gemini-2.0-flash"
llm_model: "gemini/gemini-2.5-flash"
rate_limit_calls: 2000
rate_limit_period: 60
max_retries: 3
+312 -130
View File
@@ -18,10 +18,6 @@ import yaml
import sys
import shutil
# Enable JSON schema validation in LiteLLM
import litellm
litellm.enable_json_schema_validation = True
# Get the script directory for absolute path resolution
SCRIPT_DIR = Path(__file__).parent.absolute()
@@ -58,7 +54,7 @@ DEFAULT_CONFIG = {
"exa_results_dir": "exa_results" # Directory to store Exa results
},
"api": {
"llm_model": "gemini/gemini-2.0-flash",
"llm_model": "gemini/gemini-2.5-flash",
"rate_limit_calls": 2000,
"rate_limit_period": 60,
"max_retries": 3,
@@ -192,13 +188,6 @@ class ProgressTracker:
logger.info(f"Found {len(new_libraries)} new libraries to process: {', '.join(new_libraries)}")
return new_libraries
class MDCRuleResponse(BaseModel):
"""Pydantic model for LLM response structure."""
name: str = Field(..., description="Short descriptive name for the rule")
glob_pattern: str = Field(..., description="Valid glob pattern for target files")
description: str = Field(..., description="1-2 sentence description of what the rule does")
content: str = Field(..., description="Formatted rule content using markdown")
def validate_environment_variables() -> bool:
"""Validate that all required environment variables are set."""
required_vars = []
@@ -236,25 +225,53 @@ def initialize_exa_client() -> Optional[Exa]:
logger.error(f"Failed to initialize Exa client: {str(e)}")
return None
def get_library_best_practices_exa(library_name: str, exa_client: Optional[Exa] = None, tags: List[str] = None, force_refresh: bool = False) -> Dict[str, Any]:
"""Use Exa to search for best practices for a library.
Checks for cached results first to avoid redundant API calls.
Set force_refresh=True to bypass cache and fetch fresh results.
"""
# Create a safe filename for cache lookup
safe_name = re.sub('[^a-z0-9-]+', '-', library_name.lower()).strip('-')
exa_results_dir = SCRIPT_DIR / CONFIG["paths"]["exa_results_dir"]
cache_file = exa_results_dir / f"{safe_name}_exa_result.json"
# Check cache first (unless force_refresh is True)
if not force_refresh and cache_file.exists():
try:
with open(cache_file, 'r', encoding='utf-8') as f:
cached_result = json.load(f)
# Validate cache has expected structure
if "answer" in cached_result:
logger.info(f"Using cached Exa results for {library_name}")
return cached_result
except (json.JSONDecodeError, IOError) as e:
logger.warning(f"Cache file corrupted for {library_name}, will fetch fresh: {e}")
# No cache or force refresh - call Exa API
return _fetch_from_exa(library_name, exa_client, tags, cache_file)
@retry(stop=stop_after_attempt(CONFIG["exa_api"]["max_retries"]),
wait=wait_exponential(multiplier=1, min=CONFIG["exa_api"]["retry_min_wait"], max=CONFIG["exa_api"]["retry_max_wait"]))
@sleep_and_retry
@limits(calls=CONFIG["exa_api"]["rate_limit_calls"], period=CONFIG["exa_api"]["rate_limit_period"])
def get_library_best_practices_exa(library_name: str, exa_client: Optional[Exa] = None, tags: List[str] = None) -> Dict[str, Any]:
"""Use Exa to search for best practices for a library."""
def _fetch_from_exa(library_name: str, exa_client: Optional[Exa], tags: List[str], cache_file: Path) -> Dict[str, Any]:
"""Internal function to fetch from Exa API with rate limiting and retries."""
if exa_client is None:
logger.warning("Exa client not initialized, falling back to LLM generation")
return {"answer": "", "citations": []}
try:
# Construct a query for best practices that includes tags for better context
current_year = datetime.datetime.now().year
if tags and len(tags) > 0:
# Select up to 3 most relevant tags to keep the query focused
relevant_tags = tags[:3] if len(tags) > 3 else tags
tags_str = " ".join(relevant_tags)
query = f"{library_name} best practices coding standards for {tags_str} development"
query = f"{library_name} best practices coding standards {current_year} modern {tags_str} development"
else:
query = f"{library_name} best practices coding standards"
query = f"{library_name} best practices coding standards {current_year} modern"
logger.info(f"Searching Exa for: {query}")
@@ -267,18 +284,13 @@ def get_library_best_practices_exa(library_name: str, exa_client: Optional[Exa]
"citations": result.citations if hasattr(result, 'citations') else []
}
# Save the Exa result to a file
exa_results_dir = SCRIPT_DIR / CONFIG["paths"]["exa_results_dir"]
exa_results_dir.mkdir(parents=True, exist_ok=True)
# Save the Exa result to cache file
cache_file.parent.mkdir(parents=True, exist_ok=True)
# Create a safe filename
safe_name = re.sub('[^a-z0-9-]+', '-', library_name.lower()).strip('-')
result_file = exa_results_dir / f"{safe_name}_exa_result.json"
with open(result_file, 'w', encoding='utf-8') as f:
with open(cache_file, 'w', encoding='utf-8') as f:
json.dump(result_dict, f, indent=2, default=str)
logger.info(f"Saved Exa result for {library_name} to {result_file}")
logger.info(f"Saved Exa result for {library_name} to {cache_file}")
if result_dict["answer"]:
logger.info(f"Successfully retrieved Exa results for {library_name}")
@@ -292,6 +304,116 @@ def get_library_best_practices_exa(library_name: str, exa_client: Optional[Exa]
logger.error(f"Error fetching from Exa for {library_name}: {str(e)}")
return {"answer": "", "citations": []}
def _get_relevant_sections(tags: List[str]) -> List[str]:
"""Return relevant sections based on library tags."""
# Base sections that apply to most libraries
base_sections = [
"Code Organization and Structure",
"Common Patterns and Anti-patterns",
"Performance Considerations",
"Common Pitfalls and Gotchas",
]
# Tag-specific sections
tag_sections = {
"backend": ["Security Best Practices", "Error Handling", "API Design"],
"frontend": ["Component Architecture", "State Management", "Accessibility"],
"database": ["Security Best Practices", "Query Optimization", "Data Modeling"],
"orm": ["Security Best Practices", "Query Optimization", "Migration Patterns"],
"authentication": ["Security Best Practices", "Session Management", "Token Handling"],
"security": ["Security Best Practices", "Vulnerability Prevention", "Input Validation"],
"testing": ["Test Organization", "Mocking Strategies", "Coverage Patterns"],
"css": ["Responsive Design", "Browser Compatibility", "Naming Conventions"],
"ui": ["Component Architecture", "Accessibility", "Theming"],
"state-management": ["State Organization", "Side Effects", "Debugging"],
"api": ["Error Handling", "Request/Response Patterns", "Rate Limiting"],
"cli": ["Argument Parsing", "Error Messages", "Exit Codes"],
"devops": ["Configuration Management", "Environment Variables", "Logging"],
"python": ["Type Hints", "Virtual Environments", "Packaging"],
"typescript": ["Type Safety", "Module Organization", "Strict Mode"],
"react": ["Hooks Best Practices", "Component Lifecycle", "Re-render Optimization"],
"vue": ["Composition API", "Reactivity", "Component Communication"],
"node": ["Async Patterns", "Error Handling", "Module System"],
}
# Collect additional sections based on tags
additional = []
for tag in tags:
tag_lower = tag.lower()
if tag_lower in tag_sections:
for section in tag_sections[tag_lower]:
if section not in base_sections and section not in additional:
additional.append(section)
# Add testing section if not already covered
if "Testing Approaches" not in additional and "testing" not in [t.lower() for t in tags]:
additional.append("Testing Approaches")
return base_sections + additional[:4] # Limit to avoid overwhelming the prompt
def _get_glob_hint(library_name: str, tags: List[str]) -> str:
"""Suggest a glob pattern based on library name and tags."""
# Direct library mappings for common libraries
library_globs = {
"react": "**/*.{jsx,tsx}",
"vue": "**/*.{vue,js,ts}",
"svelte": "**/*.{svelte,js,ts}",
"angular": "**/*.{ts,html}",
"next.js": "**/*.{js,jsx,ts,tsx}",
"nuxt": "**/*.{vue,js,ts}",
"prisma": "**/*.prisma",
"drizzle": "**/*.{ts,js}",
"tailwind": "**/*.{css,html,jsx,tsx,vue}",
"sass": "**/*.{scss,sass}",
"less": "**/*.less",
"express": "**/*.{js,ts}",
"fastapi": "**/*.py",
"django": "**/*.py",
"flask": "**/*.py",
"pytest": "**/*.py",
"jest": "**/*.{js,ts,jsx,tsx}",
"vitest": "**/*.{js,ts,jsx,tsx}",
"playwright": "**/*.{js,ts}",
"cypress": "**/*.{js,ts,cy.js,cy.ts}",
"docker": "**/Dockerfile,**/docker-compose*.{yml,yaml}",
"kubernetes": "**/*.{yaml,yml}",
"terraform": "**/*.tf",
"graphql": "**/*.{graphql,gql}",
"sql": "**/*.sql",
}
# Check for direct match
name_lower = library_name.lower()
if name_lower in library_globs:
return library_globs[name_lower]
# Tag-based fallbacks
tag_globs = {
"python": "**/*.py",
"typescript": "**/*.{ts,tsx}",
"javascript": "**/*.{js,jsx}",
"rust": "**/*.rs",
"go": "**/*.go",
"java": "**/*.java",
"ruby": "**/*.rb",
"php": "**/*.php",
"css": "**/*.{css,scss,sass,less}",
"html": "**/*.{html,htm}",
"yaml": "**/*.{yaml,yml}",
"json": "**/*.json",
"markdown": "**/*.{md,mdx}",
}
for tag in tags:
tag_lower = tag.lower()
if tag_lower in tag_globs:
return tag_globs[tag_lower]
# Default fallback
return "**/*"
@sleep_and_retry
@limits(calls=CONFIG["api"]["rate_limit_calls"], period=CONFIG["api"]["rate_limit_period"])
@retry(stop=stop_after_attempt(CONFIG["api"]["max_retries"]),
@@ -299,18 +421,6 @@ def get_library_best_practices_exa(library_name: str, exa_client: Optional[Exa]
def generate_mdc_rules_from_exa(library_info: LibraryInfo, exa_results: Dict[str, Any]) -> List[MDCRule]:
"""Generate MDC rules for a library using LLM directly from Exa results."""
try:
# Load MDC instructions
mdc_instructions_path = SCRIPT_DIR / CONFIG["paths"]["mdc_instructions"]
if not mdc_instructions_path.exists():
logger.warning(f"MDC instructions file not found at {mdc_instructions_path}")
mdc_instructions = "Create rules with clear descriptions and appropriate glob patterns."
else:
try:
mdc_instructions = mdc_instructions_path.read_text()
except Exception as e:
logger.warning(f"Could not read MDC instructions file: {str(e)}")
mdc_instructions = "Create rules with clear descriptions and appropriate glob patterns."
# Extract Exa answer and citations
exa_answer = exa_results.get("answer", "")
citations = exa_results.get("citations", [])
@@ -329,109 +439,190 @@ def generate_mdc_rules_from_exa(library_info: LibraryInfo, exa_results: Dict[str
# Format tags for prompt
tags_str = ", ".join(library_info.tags)
# Enhanced prompt template
enhanced_prompt_template = """Create a comprehensive Cursor rule file (.mdc) for the {library_name} library following these guidelines:
# Determine relevant sections based on tags
sections = _get_relevant_sections(library_info.tags)
sections_text = "\n".join(f"- {section}" for section in sections)
# Suggest glob pattern based on tags
glob_hint = _get_glob_hint(library_info.name, library_info.tags)
# Simplified prompt that asks for direct markdown output
prompt_template = """Create a comprehensive Cursor IDE rule file for {library_name}.
{mdc_instructions}
## About Cursor Rules
Cursor rules provide persistent instructions to the AI coding assistant. Good rules are:
- **Focused and actionable** - provide clear, specific guidance (not generic advice)
- **Under 500 lines** - keep content concise and targeted
- **Practical** - include concrete, copy-pasteable code examples
- **Clear** - write like internal documentation that your team would reference
- **Opinionated** - recommend specific approaches rather than listing all options
- **Avoid vague guidance** - be specific about *when* and *why* to use patterns
Library Information:
- Name: {library_name}
- Tags: {tags}
## Library Information
- **Name:** {library_name}
- **Tags:** {tags}
- **Target files:** {glob_hint}
{exa_content_section}
Your task is to create an EXTREMELY DETAILED and COMPREHENSIVE guide that covers:
## Content Strategy
Focus on these areas relevant to {library_name}:
{sections}
1. Code Organization and Structure
2. Common Patterns and Anti-patterns
3. Performance Considerations
4. Security Best Practices
5. Testing Approaches
6. Common Pitfalls and Gotchas
7. Tooling and Environment
## Writing Style Requirements:
1. **Be opinionated and decisive** - Say "Use X for Y" not "You could use X or Y or Z"
2. **Emphasize common mistakes** - "❌ BAD" vs "✅ GOOD" examples are highly valuable
3. **Real-world scenarios** - Focus on practical situations developers encounter daily
4. **Code-heavy** - Show, don't just tell. Every guideline should have a code example
5. **Context matters** - Explain *when* to apply patterns, not just *what* they are
6. **Modern best practices** - Focus on current, recommended approaches (e.g., hooks over classes in React)
You MUST format your response as a valid JSON object with these exact keys:
- name: A short descriptive name for the rule (e.g., "{library_name} Best Practices")
- glob_pattern: The most appropriate glob pattern for this library based on the file types it typically works with
- description: A clear 1-2 sentence description of what the rule covers
- content: The formatted rule content with comprehensive best practices in markdown format
## Output Format
Output a complete .mdc file with YAML frontmatter followed by markdown content.
DO NOT include any text outside of the JSON object. The response must be a single, valid JSON object."""
Use this EXACT format:
---
description: [A clear 1-2 sentence description focusing on WHAT this helps developers do]
globs: {glob_hint}
---
# {library_name} Best Practices
[Your comprehensive guide content here in markdown format]
## Critical Guidelines:
- Start with frontmatter (the --- YAML section)
- Use proper markdown formatting (headers, lists, code blocks)
- Include concrete, copy-pasteable code examples for EVERY recommendation
- Be specific and opinionated - recommend one good way over listing all options
- Emphasize common pitfalls with ❌ BAD vs ✅ GOOD comparisons
- Focus on real-world use cases developers face daily
- Keep under 500 lines total
- Write like clear internal documentation, not generic tutorials
- Be specific to {library_name} - avoid generic software advice
---
**IMPORTANT: Use modern best practices as of {current_date}. Focus on current, recommended approaches and avoid deprecated patterns.**"""
# Determine if we need to generate content from scratch
# Determine content section based on available information
if len(exa_answer.strip()) < 100 and len(all_citation_text.strip()) < 200:
exa_content_section = f"""I need you to research and generate comprehensive best practices for {library_info.name} from your knowledge.
Please be extremely thorough and detailed, covering all aspects of {library_info.name} development.
Your guidance should be useful for both beginners and experienced developers."""
exa_content_section = f"""## Your Task
Generate comprehensive best practices for {library_info.name} from your expert knowledge.
Be thorough and detailed, covering patterns, anti-patterns, performance, security, and testing.
Make it useful for both beginners and experienced developers."""
else:
chunk_size = CONFIG["processing"]["chunk_size"]
exa_content_section = f"""Based on the following information about {library_info.name} best practices:
exa_content_section = f"""## Reference Information
Use this information about {library_info.name} best practices as a foundation:
Exa search results:
### Research Summary:
{exa_answer}
Additional information from citations:
### Additional Context:
{all_citation_text[:chunk_size]}
Please synthesize, enhance, and expand upon this information to create the most comprehensive guide possible.
Add any important best practices that might be missing from the search results."""
## Your Task
Synthesize, enhance, and expand upon this information to create a comprehensive guide.
Add important best practices that may be missing. Focus on practical, actionable advice."""
prompt = enhanced_prompt_template.format(
# Get current date for context (at the end for prompt caching)
current_date = datetime.datetime.now().strftime("%B %Y")
prompt = prompt_template.format(
library_name=library_info.name,
tags=tags_str,
exa_content_section=exa_content_section,
mdc_instructions=mdc_instructions
sections=sections_text,
glob_hint=glob_hint,
current_date=current_date
)
logger.info(f"Sending enhanced prompt to LLM for {library_info.name}")
logger.info(f"Sending prompt to LLM for {library_info.name}")
# Use LiteLLM's completion with JSON mode
# System prompt for consistent behavior
system_prompt = """You are a senior software engineer writing internal documentation for your team.
Your team uses Cursor IDE and relies on these rules as their definitive guide.
Your writing style:
- **Opinionated** - Recommend THE best approach, not all possible options
- **Practical** - Every statement should be immediately actionable
- **Example-driven** - Show code for every guideline (❌ BAD vs ✅ GOOD format)
- **Real-world focused** - Address actual problems developers face daily
- **Concise but complete** - Dense with useful information, zero fluff
- **Modern** - Always use current best practices, avoid deprecated patterns
Output complete .mdc files with YAML frontmatter and markdown content.
Write like you're teaching a teammate who will reference this daily."""
# Use LiteLLM's completion - no JSON mode needed
response = completion(
model=CONFIG["api"]["llm_model"],
messages=[{"role": "user", "content": prompt}],
response_format={"type": "json_object"},
max_tokens=4000,
temperature=0.7
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
max_tokens=8000,
temperature=0.4
)
# Get the response content and parse it
try:
if hasattr(response.choices[0].message, 'content'):
# Standard response format
content = response.choices[0].message.content
elif hasattr(response.choices[0].message, 'text'):
# Gemini format
content = response.choices[0].message.text
else:
raise ValueError("Unexpected response format from LLM")
# Get the response content
if hasattr(response.choices[0].message, 'content'):
content = response.choices[0].message.content
elif hasattr(response.choices[0].message, 'text'):
content = response.choices[0].message.text
else:
raise ValueError("Unexpected response format from LLM")
# Clean the content to ensure it's valid JSON
content = content.strip()
if content.startswith('```json'):
content = content[7:]
# Clean up the response
content = content.strip()
# Remove markdown code fences if present
if content.startswith('```'):
# Find the end of the opening fence
first_newline = content.find('\n')
if first_newline != -1:
content = content[first_newline + 1:]
# Remove closing fence
if content.endswith('```'):
content = content[:-3]
content = content.strip()
# Parse the JSON response
json_response = json.loads(content)
# Validate against our schema
rule_data = MDCRuleResponse(**json_response)
# Create MDCRule instance using model_dump instead of dict
rule = MDCRule(**rule_data.model_dump())
logger.info(f"Successfully generated enhanced rule for {library_info.name}")
return [rule]
except json.JSONDecodeError as e:
logger.error(f"Failed to parse JSON response for {library_info.name}: {str(e)}\nResponse content: {content}")
raise
except Exception as e:
logger.error(f"Error processing response for {library_info.name}: {str(e)}")
raise
content = content[:-3].strip()
# Parse the frontmatter and content
if not content.startswith('---'):
raise ValueError(f"Response does not start with YAML frontmatter for {library_info.name}")
# Find the end of frontmatter
second_marker = content.find('---', 3)
if second_marker == -1:
raise ValueError(f"Invalid frontmatter format for {library_info.name}")
frontmatter = content[3:second_marker].strip()
markdown_content = content[second_marker + 3:].strip()
# Parse frontmatter (simple YAML parsing)
description = ""
glob_pattern = glob_hint
for line in frontmatter.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
if key == 'description':
description = value
elif key in ['globs', 'glob']:
glob_pattern = value
# Create MDCRule instance
rule = MDCRule(
name=f"{library_info.name} Best Practices",
glob_pattern=glob_pattern,
description=description if description else f"Best practices and coding standards for {library_info.name}",
content=markdown_content
)
logger.info(f"Successfully generated rule for {library_info.name}")
return [rule]
except Exception as e:
logger.error(f"Error generating MDC rule for {library_info.name}: {str(e)}")
@@ -439,21 +630,10 @@ Add any important best practices that might be missing from the search results."
def create_mdc_file(rule: MDCRule, output_path: Path) -> None:
"""Create a single .mdc file from a rule."""
# Clean up the content by removing yaml markers and extra formatting
# Content should already be clean markdown from the generation function
content = rule.content.strip()
content = content.replace('```yaml', '')
content = content.replace('```', '')
content = content.strip()
# Remove any nested frontmatter
if content.startswith('---'):
try:
second_marker = content.find('---', 3)
if second_marker != -1:
content = content[second_marker + 3:].strip()
except Exception as e:
logger.warning(f"Error removing nested frontmatter: {str(e)}")
# Create the complete .mdc file with frontmatter
mdc_content = f"""---
description: {rule.description}
globs: {rule.glob_pattern}
@@ -467,7 +647,7 @@ globs: {rule.glob_pattern}
f.write(mdc_content)
logger.info(f"Created {output_path}")
def process_single_library(library_info: Dict[str, Any], output_dir: str, exa_client: Optional[Exa] = None) -> Tuple[str, bool]:
def process_single_library(library_info: Dict[str, Any], output_dir: str, exa_client: Optional[Exa] = None, force_refresh_exa: bool = False) -> Tuple[str, bool]:
"""Process a single library and generate MDC file. Returns (library_key, success)."""
library_name = library_info["name"]
library_tags = library_info["tags"]
@@ -489,9 +669,9 @@ def process_single_library(library_info: Dict[str, Any], output_dir: str, exa_cl
tags=library_tags
)
# Get best practices using Exa
# Get best practices using Exa (uses cache unless force_refresh_exa is True)
logger.info(f"Getting best practices for {library_name} using Exa")
exa_results = get_library_best_practices_exa(library_name, exa_client, library_tags)
exa_results = get_library_best_practices_exa(library_name, exa_client, library_tags, force_refresh=force_refresh_exa)
# Store citations in library info
library_obj.citations = exa_results.get("citations", [])
@@ -521,7 +701,7 @@ def process_single_library(library_info: Dict[str, Any], output_dir: str, exa_cl
def process_rules_json(json_path: str, output_dir: str, test_mode: bool = False,
specific_library: Optional[str] = None, specific_tag: Optional[str] = None,
retry_failed_only: bool = False):
retry_failed_only: bool = False, force_refresh_exa: bool = False):
"""Process rules.json and generate MDC files."""
# Check if rules.json exists
# Use absolute paths for clarity and robustness
@@ -624,7 +804,7 @@ def process_rules_json(json_path: str, output_dir: str, test_mode: bool = False,
if test_mode:
if libraries_to_process:
test_library = libraries_to_process[0]
library_key, success = process_single_library(test_library, output_dir, exa_client)
library_key, success = process_single_library(test_library, output_dir, exa_client, force_refresh_exa)
if success:
progress_tracker.mark_library_completed(library_key)
else:
@@ -646,7 +826,7 @@ def process_rules_json(json_path: str, output_dir: str, test_mode: bool = False,
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
# Create a partial function with fixed arguments
process_func = partial(process_single_library, output_dir=output_dir, exa_client=exa_client)
process_func = partial(process_single_library, output_dir=output_dir, exa_client=exa_client, force_refresh_exa=force_refresh_exa)
# Submit all tasks
future_to_library = {
@@ -681,6 +861,7 @@ def main():
parser.add_argument("--log-dir", type=str, default="logs", help="Directory to save log files")
parser.add_argument("--exa-results-dir", type=str, default=None, help="Directory to save Exa results")
parser.add_argument("--regenerate-all", action="store_true", help="Regenerate all libraries, including previously completed ones")
parser.add_argument("--refresh-exa", action="store_true", help="Bypass Exa cache and fetch fresh results")
parser.add_argument("--debug", action="store_true", help="Enable extra debug output")
args = parser.parse_args()
@@ -727,7 +908,8 @@ def main():
test_mode=args.test,
specific_library=args.library,
specific_tag=args.tag,
retry_failed_only=not args.regenerate_all # Invert regenerate-all flag
retry_failed_only=not args.regenerate_all, # Invert regenerate-all flag
force_refresh_exa=args.refresh_exa
)
logger.info("MDC generation completed successfully!")
Generated
+1909 -1809
View File
File diff suppressed because it is too large Load Diff