Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+171 -141
View File
@@ -1,150 +1,180 @@
---
description: Enforces best practices, coding standards, and performance considerations for Electron development. Covers code structure, security, testing, and common pitfalls to ensure robust and maintainable applications.
globs: *.js,*.jsx,*.ts,*.tsx,*.html,*.css,*.scss,*.mjs,*.cjs
description: This guide provides opinionated, actionable best practices for building secure, performant, and maintainable Electron applications using modern patterns and consistent tooling.
globs: **/*.{js,jsx}
---
- **General Practices**
- Adhere to the official Electron coding style guide. Run `npm run lint` to detect style issues using `cpplint` and `eslint`.
- Aim for line lengths between 80 and 100 characters for readability.
- Use `sh` instead of `cmd` in code blocks for cross-platform compatibility in documentation.
- Select the appropriate Electron version based on project needs and compatibility with dependencies.
- Always update electron to the latest stable version to receive security fixes and performance improvements.
# Electron Best Practices
- **Code Organization and Structure**
- **Directory Structure:**
- Structure your project logically. Consider using a structure like:
electron-app/
├── main.js # Main process entry point
├── preload.js # Preload script (for specific renderers if needed)
├── renderer/
│ ├── index.html # Main HTML file
│ ├── script.js # Renderer process scripts
│ ├── style.css # Stylesheets
│ └── components/ # Reusable components (if applicable)
├── assets/ # Static assets (images, fonts, etc.)
├── package.json
└── electron-builder.yml # Electron Builder configuration
- Organize your code into modules based on functionality (e.g., authentication, data handling, UI components).
- **File Naming Conventions:**
- Use descriptive and consistent naming conventions.
- JavaScript/TypeScript files: `camelCase` for variables and functions, `PascalCase` for classes and components.
- CSS/SCSS files: `kebab-case`.
- **Module Organization:**
- Split your application logic into separate modules for better maintainability and reusability.
- Use ES modules (`import`/`export`) or CommonJS (`require`/`module.exports`) for modularization. Be consistent throughout the project.
- **Component Architecture:**
- Design reusable UI components for the renderer process.
- Use a component-based framework (e.g., React, Vue, Angular) to manage UI complexity.
- **Code Splitting:**
- Implement code splitting to reduce the initial load time of your application.
- Use dynamic imports (`import()`) to load modules on demand.
- Consider using webpack or Parcel for bundling and code splitting.
Electron development demands a disciplined approach to security, performance, and maintainability. This guide outlines the definitive best practices for our team, leveraging modern Electron features and tooling (targeting Electron 28+).
- **Common Patterns and Anti-patterns**
- **Design Patterns:**
- **Model-View-Controller (MVC):** Organize application logic into models, views, and controllers to separate concerns.
- **Observer Pattern:** Implement a publish-subscribe mechanism for communication between different parts of the application.
- **Singleton Pattern:** Use singletons sparingly. If used, implement carefully to avoid unexpected side effects.
- **Recommended Approaches:**
- **Inter-Process Communication (IPC):** Use `ipcRenderer` and `ipcMain` for communication between the main and renderer processes. Sanitize all data passed via IPC.
- **Native Modules:** Consider using native modules for performance-critical tasks or access to platform-specific APIs.
- **Remote Module:** Avoid using the remote module, as it can introduce security vulnerabilities and performance issues. Use IPC instead.
- **Anti-patterns:**
- **Tight Coupling:** Avoid tightly coupling components or modules to make the code more flexible and testable.
- **Global State:** Minimize the use of global state. Use state management libraries or techniques to manage application state effectively.
- **Long-Running Tasks in the Renderer Process:** Move long-running tasks to the main process or use worker threads to prevent blocking the UI.
- **State Management:**
- For simple applications, use basic state management techniques (e.g., component state, context API).
- For complex applications, consider using state management libraries like Redux, Zustand, or Vuex.
- **Error Handling:**
- Implement robust error handling mechanisms throughout your application.
- Use try-catch blocks to handle exceptions and prevent crashes.
- Log errors to a file or remote logging service for debugging.
## 1. Project Setup & Structure
- **Performance Considerations**
- **Optimization Techniques:**
- **Reduce Load on the Renderer Process:** Minimize the amount of work performed in the renderer process. Offload heavy tasks to the main process or worker threads.
- **Hardware Acceleration:** Enable hardware acceleration to improve rendering performance.
- **Minimize DOM Manipulations:** Reduce the number of DOM manipulations to improve UI responsiveness.
- **Memory Management:**
- **Garbage Collection:** Be mindful of memory leaks and optimize code to reduce memory consumption.
- **Object Pools:** Use object pools to reuse objects and avoid unnecessary memory allocation.
- **Rendering Optimization:**
- **Virtual DOM:** Use a virtual DOM library (e.g., React, Vue) to optimize rendering performance.
- **CSS Sprites:** Use CSS sprites to reduce the number of HTTP requests for images.
- **Bundle Size Optimization:**
- **Code Minification:** Minify JavaScript and CSS code to reduce bundle size.
- **Tree Shaking:** Use tree shaking to remove unused code from the bundle.
- **Lazy Loading:**
- **Lazy Load Images:** Lazy load images to improve initial page load time.
- **Lazy Load Modules:** Lazy load modules on demand to reduce initial bundle size.
Always start with **Electron Forge** to standardize project structure, build pipelines, and stay aligned with the latest Electron APIs.
- **Security Best Practices**
- **Common Vulnerabilities:**
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and escaping output.
- **Remote Code Execution (RCE):** Avoid RCE vulnerabilities by validating input and preventing the execution of arbitrary code.
- **Insecure Deserialization:** Prevent insecure deserialization vulnerabilities by validating serialized data.
- **Input Validation:**
- Validate all user input to prevent malicious data from being processed.
- Use appropriate data types and formats to prevent type confusion attacks.
- **Authentication and Authorization:**
- Implement secure authentication and authorization mechanisms to protect sensitive data and resources.
- Use strong passwords and multi-factor authentication.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms to protect sensitive data.
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Validate API responses to prevent data injection attacks.
- **Enable Context Isolation:** Enable context isolation for the renderer process to prevent access to the main process's JavaScript context.
- **Disable Node.js Integration:** Disable Node.js integration in the renderer process unless strictly necessary. If needed, only expose a limited API using contextBridge.
- **Handle `new-window` events:** Validate and sanitize all URLs before allowing a new window to be opened from a renderer process.
- **Scaffolding:** Use a modern template like Vite + TypeScript.
❌ BAD: Manual setup, outdated CLIs.
✅ GOOD:
```bash
npx create-electron-app@latest my-app --template=vite-typescript
```
- **Testing Approaches**
- **Unit Testing:**
- Write unit tests to verify the functionality of individual components or modules.
- Use a testing framework like Jest or Mocha.
- **Integration Testing:**
- Write integration tests to verify the interaction between different components or modules.
- Use a testing framework like Cypress or Puppeteer.
- **End-to-End Testing:**
- Write end-to-end tests to verify the overall functionality of the application.
- Use a testing framework like Cypress or Puppeteer.
- **Test Organization:**
- Organize tests into separate files or directories based on functionality.
- Use descriptive test names to clearly identify the purpose of each test.
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate components or modules during testing.
- Use a mocking library like Jest or Sinon.
- **File Naming:** Adhere to Electron's coding style for JavaScript files.
❌ BAD: `my_module.js`
✅ GOOD: `my-module.js`
- **Common Pitfalls and Gotchas**
- **Frequent Mistakes:**
- **Not Sanitizing User Input:** Failing to sanitize user input can lead to XSS vulnerabilities.
- **Using the Remote Module:** The `remote` module provides direct access to main process functionality from the renderer, but bypassing IPC exposes security risks. Use `contextBridge` and IPC.
- **Blocking the Main Process:** Performing long-running tasks in the main process can block the UI and make the application unresponsive.
- **Edge Cases:**
- **Handling Different Screen Resolutions:** Test your application on different screen resolutions to ensure proper UI rendering.
- **Handling Different Operating Systems:** Test your application on different operating systems (Windows, macOS, Linux) to ensure compatibility.
- **Version-Specific Issues:**
- Be aware of version-specific issues and compatibility concerns when upgrading Electron or its dependencies.
- **Debugging Strategies:**
- Use the Chrome DevTools to debug the renderer process.
- Use the Electron DevTools to debug the main process.
## 2. Security Fundamentals (Non-Negotiable)
- **Tooling and Environment**
- **Recommended Development Tools:**
- **Visual Studio Code:** A popular code editor with excellent support for Electron development.
- **Electron Forge or Electron Builder:** Tools for packaging and distributing Electron applications.
- **Chrome DevTools:** A powerful debugging tool for the renderer process.
- **Build Configuration:**
- Use a build system like webpack or Parcel to bundle your application code.
- Configure the build system to optimize code for production.
- **Linting and Formatting:**
- Use a linter like ESLint to enforce code style and prevent errors.
- Use a formatter like Prettier to automatically format code.
- **Deployment Best Practices:**
- Sign your application code to prevent tampering.
- Distribute your application through a secure channel.
- **CI/CD Integration:**
- Integrate your application with a CI/CD system to automate the build, test, and deployment process.
Security is paramount. Always enable context isolation and expose APIs safely.
- **Context Isolation (Mandatory):** Keep `contextIsolation` enabled. It's on by default since Electron 12.
❌ BAD: `new BrowserWindow({ webPreferences: { contextIsolation: false } })`
✅ GOOD: (Default behavior, no explicit setting needed unless overriding)
```javascript
// main.mjs
new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.mjs'),
sandbox: true // Strongly recommended
}
})
```
- **Safe API Exposure with `contextBridge`:** Never mutate the global `window` object directly. Use `contextBridge.exposeInMainWorld` and filter arguments.
❌ BAD: Exposing `ipcRenderer.send` directly.
```javascript
// preload.mjs
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('myAPI', {
send: ipcRenderer.send // ❌ Allows renderer to send arbitrary IPC messages
});
```
✅ GOOD: Expose specific, argument-filtered functions.
```javascript
// preload.mjs
import { contextBridge, ipcRenderer } from 'electron';
contextBridge.exposeInMainWorld('electronAPI', {
loadPreferences: () => ipcRenderer.invoke('load-prefs'),
saveSettings: (settings) => {
// ✅ Validate and filter arguments before sending
if (typeof settings === 'object' && settings !== null) {
ipcRenderer.send('save-settings', settings);
} else {
console.error('Invalid settings object provided.');
}
}
});
// interface.d.ts (for TypeScript)
declare global {
interface Window {
electronAPI: {
loadPreferences: () => Promise<any>;
saveSettings: (settings: object) => void;
};
}
}
```
- **Content Security Policy (CSP):** Implement a strict CSP in your `index.html` or via `webRequest.onHeadersReceived`.
✅ GOOD:
```html
<!-- index.html -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
```
## 3. ES Modules (ESM) Adoption (Electron 28+)
Leverage native ESM for cleaner, more modern code.
- **Main Process:** Use `.mjs` extension or `"type": "module"` in `package.json`.
- **`await` for Pre-Ready APIs:** ESM imports are asynchronous. Ensure critical APIs (e.g., `app.setPath`) are `await`ed before `app.whenReady()`.
❌ BAD:
```javascript
// main.mjs
import './setup-paths.mjs'; // May resolve after app is ready
app.whenReady().then(() => { /* ... */ });
```
✅ GOOD:
```javascript
// main.mjs
import { app } from 'electron';
await import('./setup-paths.mjs'); // Guarantees execution before ready
app.whenReady().then(() => { /* ... */ });
```
- **Preload Scripts:** Always use the `.mjs` extension for ESM preload scripts.
- **Sandboxed Preloads:** Cannot use ESM imports. Bundle them if external modules are needed.
- **Context Isolation:** Required for dynamic Node.js ESM imports in unsandboxed preloads.
❌ BAD: `preload.js` with `import` statements.
✅ GOOD: `preload.mjs`
## 4. IPC Communication
Use `ipcMain.handle` and `ipcRenderer.invoke` for explicit request-response patterns.
- **Request-Response:**
❌ BAD: Using `ipcRenderer.send` for requests that expect a response.
```javascript
// renderer.js
ipcRenderer.send('get-data', someId);
ipcRenderer.on('data-response', (event, data) => { /* ... */ }); // Race condition prone
```
✅ GOOD:
```javascript
// main.mjs
ipcMain.handle('get-data', async (event, someId) => {
// ✅ Perform validation, access native APIs
return await fetchData(someId);
});
// renderer.js
const data = await window.electronAPI.getData(someId); // Assuming exposed via contextBridge
```
## 5. System Path Handling
Always use Node.js `path` and `os` modules for cross-platform compatibility.
- **File Paths:** Use `path.join()` for concatenation.
❌ BAD: `app.getPath('userData') + '/config.json'`
✅ GOOD:
```javascript
import path from 'node:path';
import { app } from 'electron';
const configPath = path.join(app.getPath('userData'), 'config.json');
```
- **Temporary Directories:** Use `os.tmpdir()`.
❌ BAD: `'/tmp/my-app-data'`
✅ GOOD:
```javascript
import os from 'node:os';
const tempDir = os.tmpdir();
```
## 6. Testing & Linting
Integrate Electron's built-in tooling for consistent code quality.
- **Linting:** Run `npm run lint` regularly and integrate into pre-commit hooks.
✅ GOOD: Ensure your `package.json` includes:
```json
"scripts": {
"lint": "electron-builder lint" // Or specific linter like 'eslint .'
}
```
- **Unit Tests:** Add new tests for any changes or new features.
✅ GOOD: `npm run test`
```json
"scripts": {
"test": "electron-mocha spec" // Example with electron-mocha
}
```
## 7. Staying Current
Electron evolves rapidly. Proactively manage updates and breaking changes.
- **Official Documentation:** Always consult the version-specific official documentation.
- **Breaking Changes:** Regularly review the "Breaking Changes" page for each major Electron release to anticipate necessary updates.