From 681f645317fef8e6bb2017717c8c14b46729aebd Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 17:47:09 +0000 Subject: [PATCH] style(ui): enforce deterministic Best-Practise standard in frontend documentation Co-authored-by: beginwebdev2002 <102213457+beginwebdev2002@users.noreply.github.com> --- frontend/angular/advanced-performance.md | 95 +++++++++++++---------- frontend/angular/architecture.md | 85 +++++++++++--------- frontend/angular/data-forms.md | 74 ++++++++++-------- frontend/angular/expert-niche.md | 39 +++++----- frontend/angular/readme.md | 51 +++++++----- frontend/angular/state-management.md | 20 ++--- frontend/javascript/async-logic.md | 60 +++++++------- frontend/javascript/modern-syntax.md | 60 +++++++------- frontend/javascript/professional-niche.md | 60 +++++++------- frontend/javascript/readme.md | 36 +++++---- frontend/qwik/readme.md | 13 ++-- frontend/react/performance.md | 14 ++-- frontend/react/readme.md | 14 ++-- frontend/react/state-management.md | 20 +++-- frontend/readme.md | 8 +- frontend/solidjs/readme.md | 13 ++-- frontend/typescript/logic-safety.md | 60 +++++++------- frontend/typescript/objects-functions.md | 60 +++++++------- frontend/typescript/professional-niche.md | 60 +++++++------- frontend/typescript/readme.md | 36 +++++---- 20 files changed, 492 insertions(+), 386 deletions(-) diff --git a/frontend/angular/advanced-performance.md b/frontend/angular/advanced-performance.md index 446f9e6..baa45b8 100644 --- a/frontend/angular/advanced-performance.md +++ b/frontend/angular/advanced-performance.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Angular Advanced Performance within the frontend domain. technology: Angular domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "20" tags: [performance, advanced, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Performance Expert last_updated: 2026-03-22 -topic: Angular -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🚀 Angular Advanced Performance Best Practices & Expert Patterns + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to advanced performance best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 -## III. Advanced Performance (31-45) -## 31. Eager Loading of Heavy Components -**Context:** Bundle Size +## ⚡ III. Advanced Performance (31-45) +## ⚡ 31. Eager Loading of Heavy Components +> [!NOTE] +> **Context:** Bundle Size ### ❌ Bad Practice ```html @@ -36,8 +35,9 @@ A charting library (e.g., ECharts) loads immediately, blocking TTI (Time to Inte ``` ### 🚀 Solution Use `@defer`. This defers component code loading until a trigger occurs (viewport, interaction, timer). -## 32. Heavy Computation in Main Thread -**Context:** Event Loop Blocking +## ⚡ 32. Heavy Computation in Main Thread +> [!NOTE] +> **Context:** Event Loop Blocking ### ❌ Bad Practice Sorting an array of 100k elements directly in the component. ### ⚠️ Problem @@ -46,8 +46,9 @@ Freezes the UI. Offload computations to a Web Worker. ### 🚀 Solution Use Angular Web Workers. In v20, this is easily configured via the CLI. -## 33. Memory Leaks in `effect()` -**Context:** Signal Effects +## ⚡ 33. Memory Leaks in `effect()` +> [!NOTE] +> **Context:** Signal Effects ### ❌ Bad Practice ```typescript effect(() => { @@ -66,8 +67,9 @@ effect((onCleanup) => { ``` ### 🚀 Solution Always use the `onCleanup` callback to release resources. -## 34. Excessive Change Detection with `NgZone.run()` -**Context:** Zone Integration +## ⚡ 34. Excessive Change Detection with `NgZone.run()` +> [!NOTE] +> **Context:** Zone Integration ### ❌ Bad Practice Wrapping third-party libraries in `ngZone.run()` unnecessarily. ### ⚠️ Problem @@ -80,8 +82,9 @@ ngZone.runOutsideAngular(() => { ``` ### 🚀 Solution Run frequent events (scroll, mousemove, animationFrame) *outside* the Angular zone. Update signals only when UI updates are required. -## 35. Signals equality check default -**Context:** Signal Performance +## ⚡ 35. Signals equality check default +> [!NOTE] +> **Context:** Signal Performance ### ❌ Bad Practice ```typescript data = signal({ id: 1 }, { equal: undefined }); // Default checks reference @@ -95,8 +98,9 @@ data = signal(obj, { equal: isEqual }); ``` ### 🚀 Solution Use a custom comparison function for complex objects to avoid redundant re-renders. -## 36. Lacking `trackBy` in iterables -**Context:** Re-rendering Lists +## ⚡ 36. Lacking `trackBy` in iterables +> [!NOTE] +> **Context:** Re-rendering Lists ### ❌ Bad Practice ```html
  • {{ item }}
  • @@ -109,8 +113,9 @@ Without tracking, any array change leads to the recreation of all DOM nodes in t ``` ### 🚀 Solution Always use a unique key in `track`. This allows Angular to move DOM nodes instead of recreating them. -## 37. Recursive Template without Caching -**Context:** Tree Rendering +## ⚡ 37. Recursive Template without Caching +> [!NOTE] +> **Context:** Tree Rendering ### ❌ Bad Practice Recursive component call without `OnPush` and memoization. ### ⚠️ Problem @@ -120,9 +125,10 @@ Using the `Memoization` pattern or `computed()` to prepare the tree data structu ### 🚀 Solution -[Architectural justification of the solution] -## 38. Global Styles Leakage -**Context:** CSS Encapsulation +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 38. Global Styles Leakage +> [!NOTE] +> **Context:** CSS Encapsulation ### ❌ Bad Practice ```css /* global.css */ @@ -134,8 +140,9 @@ Global styles unpredictably affect components. Use `ViewEncapsulation.Emulated` (default) and specific selectors. ### 🚀 Solution Keep styles locally within components. -## 39. Large Component Bundle -**Context:** Split Chunks +## ⚡ 39. Large Component Bundle +> [!NOTE] +> **Context:** Split Chunks ### ❌ Bad Practice A single huge component of 3000 lines. ### ⚠️ Problem @@ -144,8 +151,9 @@ Poor readability, rendering lazy loading of UI parts impossible. Decompose into "dumb" (UI) and "smart" components. ### 🚀 Solution Break down the UI into small, reusable blocks. -## 40. Image Optimization Ignorance -**Context:** Core Web Vitals (LCP) +## ⚡ 40. Image Optimization Ignorance +> [!NOTE] +> **Context:** Core Web Vitals (LCP) ### ❌ Bad Practice ```html @@ -158,8 +166,9 @@ The browser loads the full image, shifting the layout (CLS). ``` ### 🚀 Solution Use the `NgOptimizedImage` directive. It automatically handles lazy loading, preconnect, and srcset. -## 41. Hydration Mismatch -**Context:** SSR / SSG +## ⚡ 41. Hydration Mismatch +> [!NOTE] +> **Context:** SSR / SSG ### ❌ Bad Practice Rendering `Date.now()` or random numbers (`Math.random()`) directly in the template. ### ⚠️ Problem @@ -168,8 +177,9 @@ The server generates one number, the client another. This causes "flickering" an Use stable data or defer random generation until `afterNextRender`. ### 🚀 Solution Pay attention to template determinism with SSR. -## 42. Synchronous `inject()` inside loops -**Context:** DI Performance +## ⚡ 42. Synchronous `inject()` inside loops +> [!NOTE] +> **Context:** DI Performance ### ❌ Bad Practice Calling `inject()` inside a function that loops. ### ⚠️ Problem @@ -179,9 +189,10 @@ Inject dependency once at the class/file constant level. ### 🚀 Solution -[Architectural justification of the solution] -## 43. Unused Signal Dependencies -**Context:** Signal Graph +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 43. Unused Signal Dependencies +> [!NOTE] +> **Context:** Signal Graph ### ❌ Bad Practice Reading a signal inside `computed` whose value doesn't affect the result (an unexecuted logical branch). ### ⚠️ Problem @@ -191,9 +202,10 @@ Use `untracked()` to read signals whose changes should not trigger a recalculati ### 🚀 Solution -[Architectural justification of the solution] -## 44. Excessive Wrappers (`div` soup) -**Context:** DOM Size +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 44. Excessive Wrappers (`div` soup) +> [!NOTE] +> **Context:** DOM Size ### ❌ Bad Practice ```html
    @@ -205,9 +217,10 @@ Use `` to group elements without creating extra DOM nodes. ### 🚀 Solution -[Architectural justification of the solution] -## 45. Neglecting `runOutsideAngular` for Events -**Context:** High-frequency events +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 45. Neglecting `runOutsideAngular` for Events +> [!NOTE] +> **Context:** High-frequency events ### ❌ Bad Practice `@HostListener('window:scroll')` ### ⚠️ Problem @@ -217,5 +230,5 @@ Subscribe manually in `runOutsideAngular` and update the signal only when necess ### 🚀 Solution -[Architectural justification of the solution] +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. --- diff --git a/frontend/angular/architecture.md b/frontend/angular/architecture.md index c65f3a2..33d28e7 100644 --- a/frontend/angular/architecture.md +++ b/frontend/angular/architecture.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Angular Architecture within the frontend domain. technology: Angular domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "20" tags: [architecture, dependency-injection, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Architecture Expert last_updated: 2026-03-22 -topic: Angular -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🏗 Angular Architecture & Dependency Injection Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Provide architectural best practices for Angular including DI usage, modules, routing, and guards. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 -## II. Architecture & DI (16-30) -## 16. Services provided in 'root' vs Modules -**Context:** Tree Shaking +## 🏗️ II. Architecture & DI (16-30) +## ⚡ 16. Services provided in 'root' vs Modules +> [!NOTE] +> **Context:** Tree Shaking ### ❌ Bad Practice ```typescript @NgModule({ providers: [MyService] }) @@ -32,8 +31,9 @@ The service is included in the bundle even if it is not used. ``` ### 🚀 Solution Always use `providedIn: 'root'`. This allows the bundler to remove unused services (Tree Shaking). -## 17. Class-based Guards -**Context:** Routing Security +## ⚡ 17. Class-based Guards +> [!NOTE] +> **Context:** Routing Security ### ❌ Bad Practice ```typescript @Injectable() @@ -49,8 +49,9 @@ export const authGuard: CanActivateFn = (route, state) => { ``` ### 🚀 Solution Use functional Guards (`CanActivateFn`). They are concise, easy to test, and composable. -## 18. Class-based Interceptors -**Context:** HTTP Requests +## ⚡ 18. Class-based Interceptors +> [!NOTE] +> **Context:** HTTP Requests ### ❌ Bad Practice ```typescript @Injectable() @@ -67,8 +68,9 @@ export const tokenInterceptor: HttpInterceptorFn = (req, next) => { ``` ### 🚀 Solution Use functional Interceptors (`HttpInterceptorFn`) with `provideHttpClient(withInterceptors([...]))`. -## 19. State Mutation in Services -**Context:** Data Integrity +## ⚡ 19. State Mutation in Services +> [!NOTE] +> **Context:** Data Integrity ### ❌ Bad Practice ```typescript updateUser(user: User) { @@ -86,8 +88,9 @@ updateUser(user: User) { ``` ### 🚀 Solution Use Signals for state management. They guarantee reactivity and atomicity of updates. -## 20. Calling functions inside `@for` tracking -**Context:** Rendering Performance +## ⚡ 20. Calling functions inside `@for` tracking +> [!NOTE] +> **Context:** Rendering Performance ### ❌ Bad Practice ```html @for (item of items; track getItemId(item)) @@ -100,8 +103,9 @@ The tracking function is called for each element during every re-render. ``` ### 🚀 Solution Use an object property (ID or a unique key) directly. If a function is needed, it must be as simple and pure as possible. -## 21. `host` property vs `@HostListener` -**Context:** Component Metadata +## ⚡ 21. `host` property vs `@HostListener` +> [!NOTE] +> **Context:** Component Metadata ### ❌ Bad Practice ```typescript @HostListener('click') onClick() { ... } @@ -120,8 +124,9 @@ Decorators increase class size and scatter host configuration across the file. ``` ### 🚀 Solution Use the `host` property in component metadata. This centralizes all host element settings. -## 22. Dynamic Components with `ComponentFactoryResolver` -**Context:** Dynamic Rendering +## ⚡ 22. Dynamic Components with `ComponentFactoryResolver` +> [!NOTE] +> **Context:** Dynamic Rendering ### ❌ Bad Practice ```typescript const factory = this.resolver.resolveComponentFactory(MyComponent); @@ -137,8 +142,9 @@ this.container.createComponent(MyComponent); ``` ### 🚀 Solution Use `ViewContainerRef.createComponent` directly with the component class or the `ngComponentOutlet` directive. -## 23. Shared Modules (The "Dump" Module) -**Context:** Modular Architecture +## ⚡ 23. Shared Modules (The "Dump" Module) +> [!NOTE] +> **Context:** Modular Architecture ### ❌ Bad Practice `SharedModule` imports and exports *all* UI components, pipes, and directives. ### ⚠️ Problem @@ -147,8 +153,9 @@ If a component needs a single button, it is forced to pull the entire `SharedMod Import only what is needed directly into the `imports` of the Standalone component. ### 🚀 Solution Abandon `SharedModule` in favor of granular imports of Standalone entities. -## 24. Circular Dependencies in DI -**Context:** Architecture +## ⚡ 24. Circular Dependencies in DI +> [!NOTE] +> **Context:** Architecture ### ❌ Bad Practice Service A injects Service B, which injects Service A. ### ⚠️ Problem @@ -157,8 +164,9 @@ Leads to runtime errors ("Cannot instantiate cyclic dependency"). Indicates poor Use `forwardRef()` as a crutch, but it's better to extract the shared logic into a third Service C. ### 🚀 Solution Refactoring: break services into smaller ones following SRP (Single Responsibility Principle). -## 25. Logic in Pipes -**Context:** Separation of Concerns +## ⚡ 25. Logic in Pipes +> [!NOTE] +> **Context:** Separation of Concerns ### ❌ Bad Practice A Pipe performs HTTP requests or complex business logic. ### ⚠️ Problem @@ -167,8 +175,9 @@ Pipes are intended for data transformation in the template. Side effects in pipe Pipes should be "Pure" (without side effects) and fast. ### 🚀 Solution Extract logic into services/signals. Leave only formatting to pipes. -## 26. `any` in Services -**Context:** TypeScript Safety +## ⚡ 26. `any` in Services +> [!NOTE] +> **Context:** TypeScript Safety ### ❌ Bad Practice ```typescript getData(): Observable { ... } @@ -181,8 +190,9 @@ getData(): Observable { ... } ``` ### 🚀 Solution Use DTO interfaces (generate them from Swagger/OpenAPI) and Zod for API response validation. -## 27. Multiple `async` pipes for same stream -**Context:** RxJS Subscriptions +## ⚡ 27. Multiple `async` pipes for same stream +> [!NOTE] +> **Context:** RxJS Subscriptions ### ❌ Bad Practice ```html
    {{ (user$ | async).name }}
    @@ -197,8 +207,9 @@ Each `async` pipe creates a new subscription. This can lead to duplicated HTTP r ``` ### 🚀 Solution Use aliases in the template (`as varName`) or convert the stream to a signal (`toSignal`). -## 28. ProvidedIn 'any' -**Context:** DI Scopes +## ⚡ 28. ProvidedIn 'any' +> [!NOTE] +> **Context:** DI Scopes ### ❌ Bad Practice ```typescript @Injectable({ providedIn: 'unknown' }) @@ -209,8 +220,9 @@ Creates a new service instance for each lazy-loaded module. This is often unexpe `providedIn: 'root'` or providing at the level of a specific component (`providers: []`). ### 🚀 Solution Avoid `any`. Explicitly control the scope: either global (`root`) or local. -## 29. Imperative Routing -**Context:** Navigation +## ⚡ 29. Imperative Routing +> [!NOTE] +> **Context:** Navigation ### ❌ Bad Practice ```typescript this.router.navigateByUrl('/users/' + id); @@ -223,8 +235,9 @@ this.router.navigate(['users', id]); ``` ### 🚀 Solution Use an array of segments. It is safer (automatic encoding of URL parameters) and cleaner. -## 30. Ignoring `OnPush` Strategy -**Context:** Change Detection Strategy +## ⚡ 30. Ignoring `OnPush` Strategy +> [!NOTE] +> **Context:** Change Detection Strategy ### ❌ Bad Practice Default components (`ChangeDetectionStrategy.Default`). ### ⚠️ Problem diff --git a/frontend/angular/data-forms.md b/frontend/angular/data-forms.md index 4512237..0367a79 100644 --- a/frontend/angular/data-forms.md +++ b/frontend/angular/data-forms.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Angular Data & Forms within the frontend domain. technology: Angular domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "20" tags: [forms, data, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Data Expert last_updated: 2026-03-22 -topic: Angular -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 📝 Angular Data & Forms Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Proper implementation of data management and forms in Angular applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 -## IV. Data & Forms (46-55) -## 46. Template-Driven Forms without Types -**Context:** Form Safety +## ⚡ IV. Data & Forms (46-55) +## ⚡ 46. Template-Driven Forms without Types +> [!NOTE] +> **Context:** Form Safety ### ❌ Bad Practice `[(ngModel)]` without strict model typing. ### ⚠️ Problem @@ -29,9 +28,10 @@ Use Reactive Forms with `FormControl` typing or new Signal-based Forms ( ### 🚀 Solution -[Architectural justification of the solution] -## 47. Untyped `FormGroup` -**Context:** Reactive Forms +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 47. Untyped `FormGroup` +> [!NOTE] +> **Context:** Reactive Forms ### ❌ Bad Practice ```typescript const form = new FormGroup({ ... }); // Untyped @@ -47,8 +47,9 @@ const form = new FormGroup({ ``` ### 🚀 Solution Always type forms. Use `nonNullable: true` to avoid `string | undefined` hell. -## 48. Subscribe inside Subscribe -**Context:** RxJS Patterns +## ⚡ 48. Subscribe inside Subscribe +> [!NOTE] +> **Context:** RxJS Patterns ### ❌ Bad Practice ```typescript this.route.params.subscribe(params => { @@ -65,8 +66,9 @@ this.route.params.pipe( ``` ### 🚀 Solution Use Flattening Operators (`switchMap`, `concatMap`, `mergeMap`). -## 49. Ignoring `AbortSignal` in HTTP -**Context:** Network Efficiency +## ⚡ 49. Ignoring `AbortSignal` in HTTP +> [!NOTE] +> **Context:** Network Efficiency ### ❌ Bad Practice Ignoring request cancellation when navigating away from the page. ### ⚠️ Problem @@ -76,9 +78,10 @@ HttpClient automatically supports cancellation upon unsubscription. With signals ### 🚀 Solution -[Architectural justification of the solution] -## 50. Mutating Inputs directly -**Context:** Unidirectional Data Flow +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 50. Mutating Inputs directly +> [!NOTE] +> **Context:** Unidirectional Data Flow ### ❌ Bad Practice ```typescript this.inputData.push(newItem); @@ -90,9 +93,10 @@ Emit event (`output`) upwards; the parent changes the data and passes the new ob ### 🚀 Solution -[Architectural justification of the solution] -## 51. `ngModel` inside Reactive Form -**Context:** Form Mixing +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 51. `ngModel` inside Reactive Form +> [!NOTE] +> **Context:** Form Mixing ### ❌ Bad Practice Using `formControlName` and `[(ngModel)]` on the same input. ### ⚠️ Problem @@ -102,9 +106,10 @@ Use only one approach: either Reactive or Template-driven. ### 🚀 Solution -[Architectural justification of the solution] -## 52. Complex Validators in Template -**Context:** Form Logic +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 52. Complex Validators in Template +> [!NOTE] +> **Context:** Form Logic ### ❌ Bad Practice Validation via HTML attributes for complex logic. ### ⚠️ Problem @@ -114,9 +119,10 @@ Custom Validator Functions or Async Validators in the component class. ### 🚀 Solution -[Architectural justification of the solution] -## 53. Forgetting `updateOn: 'blur'` -**Context:** Performance +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 53. Forgetting `updateOn: 'blur'` +> [!NOTE] +> **Context:** Performance ### ❌ Bad Practice Validating a complex field on every keystroke (`change`). ### ⚠️ Problem @@ -127,8 +133,9 @@ new FormControl('', { updateOn: 'blur' }); ``` ### 🚀 Solution Trigger validation/update only when the user has finished typing. -## 54. Not handling API Errors -**Context:** UX +## ⚡ 54. Not handling API Errors +> [!NOTE] +> **Context:** UX ### ❌ Bad Practice `.subscribe(data => ...)` without an error callback. ### ⚠️ Problem @@ -138,9 +145,10 @@ Global Error Handler or `catchError` in the pipe returning a safe value. ### 🚀 Solution -[Architectural justification of the solution] -## 55. Hardcoded API URLs -**Context:** Maintainability +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 55. Hardcoded API URLs +> [!NOTE] +> **Context:** Maintainability ### ❌ Bad Practice `http.get('https://api.com/users')` ### ⚠️ Problem @@ -150,5 +158,5 @@ Using InjectionToken `API_URL` and environment configuration. ### 🚀 Solution -[Architectural justification of the solution] +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. --- diff --git a/frontend/angular/expert-niche.md b/frontend/angular/expert-niche.md index 8cbeb8b..7c57dee 100644 --- a/frontend/angular/expert-niche.md +++ b/frontend/angular/expert-niche.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Angular Expert/Niche topics within the frontend domain. technology: Angular domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "20" tags: [expert, niche, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular Expert last_updated: 2026-03-22 -topic: Angular -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🧠 Angular Expert/Niche Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Deep-dive into expert and niche topics in Angular. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** Angular 20 -## V. Expert/Niche (56-60) -## 56. `untracked()` usage -**Context:** Fine-grained Reactivity +## ⚡ V. Expert/Niche (56-60) +## ⚡ 56. `untracked()` usage +> [!NOTE] +> **Context:** Fine-grained Reactivity ### ❌ Bad Practice Accidentally creating a cyclic dependency in `computed`. ### ⚠️ Problem @@ -34,8 +33,9 @@ computed(() => { ``` ### 🚀 Solution Use `untracked()` for side effects or reads that shouldn't affect recalculation. -## 57. V8 Hidden Classes Optimization -**Context:** Micro-optimization +## ⚡ 57. V8 Hidden Classes Optimization +> [!NOTE] +> **Context:** Micro-optimization ### ❌ Bad Practice ```typescript user = signal({}); @@ -51,8 +51,9 @@ user = signal({ name: null, age: null }); ``` ### 🚀 Solution Always initialize signals with the full object shape (even with null) to preserve property access monomorphism. -## 58. Signal Glitch Freedom abuse -**Context:** Reactivity Theory +## ⚡ 58. Signal Glitch Freedom abuse +> [!NOTE] +> **Context:** Reactivity Theory ### ❌ Bad Practice Relying on `effect` to fire synchronously. ### ⚠️ Problem @@ -62,9 +63,10 @@ Do not use effects to synchronize local state. Use `computed`. ### 🚀 Solution -[Architectural justification of the solution] -## 59. Memory leaks in `root` Effects -**Context:** Application Lifecycle +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## ⚡ 59. Memory leaks in `root` Effects +> [!NOTE] +> **Context:** Application Lifecycle ### ❌ Bad Practice Creating an effect in a service without `manualCleanup`. ### ⚠️ Problem @@ -74,9 +76,10 @@ Usually fine, but if the service is destroyed (rare lazy loading case), the effe ### 🚀 Solution -[Architectural justification of the solution] -## 60. `runInInjectionContext` -**Context:** Advanced DI +This approach provides a deterministic, type-safe implementation that is resilient and Agent-Readable, maintaining strict architectural boundaries. +## 📖 60. `runInInjectionContext` +> [!NOTE] +> **Context:** Advanced DI ### ❌ Bad Practice Passing an `Injector` instance manually into functions. ### ⚠️ Problem diff --git a/frontend/angular/readme.md b/frontend/angular/readme.md index 861f8c4..8421e90 100644 --- a/frontend/angular/readme.md +++ b/frontend/angular/readme.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Angular within the frontend domain. technology: Angular domain: frontend level: Senior/Architect @@ -7,10 +6,7 @@ version: "20" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Angular Performance Expert last_updated: 2026-03-22 -topic: Angular -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🎨 Angular Best Practices & Production-Ready Patterns ## 🎯 Context & Scope @@ -26,7 +22,8 @@ vibe_coding_ready: true--- ## 🚀 I. Basics & Popular (1-15) ### 🚨 1. Using `@Input()` Decorator -**Context:** Component Inputs +> [!NOTE] +> **Context:** Component Inputs #### ❌ Bad Practice ```typescript @Input() title: string = ''; @@ -42,7 +39,8 @@ Use Signal Inputs (`input()`). This allows Angular to precisely know *which* spe --- ### 🚨 2. Using `@Output()` Decorator -**Context:** Component Outputs +> [!NOTE] +> **Context:** Component Outputs #### ❌ Bad Practice ```typescript @Output() save = new EventEmitter(); @@ -58,7 +56,8 @@ Use the `output()` function. It provides strict typing, better performance, and --- ### 🚨 3. Two-Way Binding with `@Input()` and `@Output()` -**Context:** Model Synchronization +> [!NOTE] +> **Context:** Model Synchronization #### ❌ Bad Practice ```typescript @Input() value: string; @@ -75,7 +74,8 @@ Use `model()`. This creates a Signal that can be both read and written to, autom --- ### 🚨 4. Structural Directives (`*ngIf`, `*ngFor`) -**Context:** Template Control Flow +> [!NOTE] +> **Context:** Template Control Flow #### ❌ Bad Practice ```html
    @@ -99,7 +99,8 @@ Use the built-in Control Flow (`@if`, `@for`). It is built into the compiler, re --- ### 🚨 5. Subscribing in Components (Logic in `ngOnInit`) -**Context:** Data Fetching +> [!NOTE] +> **Context:** Data Fetching #### ❌ Bad Practice ```typescript data: unknown; @@ -118,7 +119,8 @@ Use `toSignal()` to convert an Observable into a Signal. This automatically mana --- ### 🚨 6. `BehaviorSubject` for Local State -**Context:** Component State Management +> [!NOTE] +> **Context:** Component State Management #### ❌ Bad Practice ```typescript private count$ = new BehaviorSubject(0); @@ -137,7 +139,8 @@ Use `signal()` for local state. It is a primitive designed specifically for sync --- ### 🚨 7. Derived State with `ngOnChanges` -**Context:** Reactivity +> [!NOTE] +> **Context:** Reactivity #### ❌ Bad Practice ```typescript ngOnChanges(changes: SimpleChanges) { @@ -157,7 +160,8 @@ Use `computed()`. The signal is recalculated *only* when its dependencies change --- ### 🚨 8. Constructor Dependency Injection -**Context:** DI Pattern +> [!NOTE] +> **Context:** DI Pattern #### ❌ Bad Practice ```typescript constructor(private http: HttpClient, private store: Store) {} @@ -174,7 +178,8 @@ Use the `inject()` function. It operates in the initialization context (fields o --- ### 🚨 9. Modules (`NgModule`) -**Context:** App Architecture +> [!NOTE] +> **Context:** App Architecture #### ❌ Bad Practice ```typescript @NgModule({ @@ -197,7 +202,8 @@ Use Standalone Components. This is the Angular v14+ standard that makes componen --- ### 🚨 10. String-based Route Loading -**Context:** Lazy Loading Routing +> [!NOTE] +> **Context:** Lazy Loading Routing #### ❌ Bad Practice ```typescript loadChildren: () => import('./module').then(m => m.UserModule) @@ -213,7 +219,8 @@ Use `loadComponent` for routing to Standalone components. This ensures minimal c --- ### 🚨 11. Heavy Logic in Templates -**Context:** Template Performance +> [!NOTE] +> **Context:** Template Performance #### ❌ Bad Practice ```html
    {{ calculateTotal(items) }}
    @@ -232,7 +239,8 @@ Extract logic into `computed()` signals or Pure Pipes. They are only executed wh --- ### 🚨 12. Manual Subscription Management (`takeUntil`) -**Context:** RxJS Memory Leaks +> [!NOTE] +> **Context:** RxJS Memory Leaks #### ❌ Bad Practice ```typescript destroy$ = new Subject(); @@ -250,7 +258,8 @@ Use the `takeUntilDestroyed()` operator. It automatically unsubscribes upon cont --- ### 🚨 13. Deeply Nested Components Passing Data -**Context:** Prop Drilling +> [!NOTE] +> **Context:** Prop Drilling #### ❌ Bad Practice ```html @@ -272,7 +281,8 @@ Use Signal Stores or services for state sharing, or the new `input()` API with c --- ### 🚨 14. Accessing DOM directly (`ElementRef.nativeElement`) -**Context:** Security & Abstraction +> [!NOTE] +> **Context:** Security & Abstraction #### ❌ Bad Practice ```typescript el.nativeElement.style.backgroundColor = 'red'; @@ -289,7 +299,8 @@ Use style/class bindings or `Renderer2`. For direct manipulations, consider dire --- ### 🚨 15. Zone.js overhead -**Context:** Change Detection +> [!NOTE] +> **Context:** Change Detection #### ❌ Bad Practice The application relies on Zone.js for any asynchronous event (setTimeout, Promise, XHR). #### ⚠️ Problem diff --git a/frontend/angular/state-management.md b/frontend/angular/state-management.md index fcc1f5a..843c539 100644 --- a/frontend/angular/state-management.md +++ b/frontend/angular/state-management.md @@ -1,16 +1,12 @@ --- -description: Vibe coding guidelines and architectural constraints for Angular State Management, focusing on Zoneless reactivity, Signals, and modern functional APIs. technology: Angular domain: frontend level: Senior/Architect -complexity: Advanced -topic: Angular State Management -vibe_coding_ready: true -last_evolution: 2026-03-28 version: "20" tags: [state-management, signals, zoneless, angular, best-practices, clean-code, scalable-code] ai_role: Senior Angular State Management Expert -last_updated: 2026-03-29--- +last_updated: 2026-03-29 +--- > 📦 [best-practise](../../README.md) / 🖥️ [frontend](../readme.md) / 🅰️ [angular](./readme.md) @@ -51,7 +47,8 @@ graph TD ## 🚀 I. Local State Management ### 🚨 1. Managing Component State with Signals -**Context:** Synchronous local state. +> [!NOTE] +> **Context:** Synchronous local state. #### ❌ Bad Practice ```typescript isLoading: boolean = false; @@ -86,7 +83,8 @@ Use `signal()`. It forces the developer to explicitly use `.set()` or `.update() ## ⚙️ II. Derived State ### 🚨 2. Computing Values -**Context:** Creating derived state based on other state values. +> [!NOTE] +> **Context:** Creating derived state based on other state values. #### ❌ Bad Practice ```typescript items = signal([1, 2, 3]); @@ -109,7 +107,8 @@ Use `computed()`. The calculated value is memoized and only re-evaluates when it ## ⚡ III. Side Effects ### 🚨 3. Handling Side Effects Safely -**Context:** Executing logic when a signal changes. +> [!NOTE] +> **Context:** Executing logic when a signal changes. #### ❌ Bad Practice Using getters or Angular lifecycle hooks like `ngDoCheck` to monitor value changes and trigger side effects like logging or generic HTTP calls. #### ⚠️ Problem @@ -129,7 +128,8 @@ Use `effect()`. Effects track dependencies automatically and ensure the side eff ## 🔗 IV. Component Communication ### 🚨 4. Modern Data Passing -**Context:** Passing data between parent and child components. +> [!NOTE] +> **Context:** Passing data between parent and child components. #### ❌ Bad Practice ```typescript @Input() user: User; diff --git a/frontend/javascript/async-logic.md b/frontend/javascript/async-logic.md index 83e2397..35710b3 100644 --- a/frontend/javascript/async-logic.md +++ b/frontend/javascript/async-logic.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for JavaScript Asynchronous Logic within the frontend domain. technology: JavaScript domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "ES2024+" tags: [javascript, async, promises, best-practices, clean-code, scalable-code] ai_role: Senior JavaScript Asynchronous Expert last_updated: 2026-03-22 -topic: JavaScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # ⏳ JavaScript Asynchronous & Logic Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Implement correct and robust asynchronous logic in JavaScript applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** ES2024+ -## III. Asynchronous & Logic -## 21. Callback Hell vs Promises -**Context:** Managing asynchronous execution flow. +## ⚡ III. Asynchronous & Logic +## ⚡ 21. Callback Hell vs Promises +> [!NOTE] +> **Context:** Managing asynchronous execution flow. ### ❌ Bad Practice ```javascript getData(url, (err, res) => { @@ -41,8 +40,9 @@ fetchData(url) ``` ### 🚀 Solution Use Promises to flatten the structure and centralize error handling with `.catch()`. -## 22. Promise.then() nesting vs Async/Await -**Context:** Modern syntax for asynchronous code. +## ⚡ 22. Promise.then() nesting vs Async/Await +> [!NOTE] +> **Context:** Modern syntax for asynchronous code. ### ❌ Bad Practice ```javascript function load() { @@ -65,8 +65,9 @@ async function load() { ``` ### 🚀 Solution Use `async/await`. It allows asynchronous code to be written and read like synchronous code, improving maintainability. -## 23. Sequential `await` in loops vs `Promise.all` -**Context:** Parallelizing independent asynchronous operations. +## ⚡ 23. Sequential `await` in loops vs `Promise.all` +> [!NOTE] +> **Context:** Parallelizing independent asynchronous operations. ### ❌ Bad Practice ```javascript for (const id of ids) { @@ -82,8 +83,9 @@ await Promise.all(promises); ``` ### 🚀 Solution Use `Promise.all` to execute independent promises in parallel. This utilizes the full network/IO bandwidth. -## 24. Missing `try/catch` in async -**Context:** Handling failures in async functions. +## ⚡ 24. Missing `try/catch` in async +> [!NOTE] +> **Context:** Handling failures in async functions. ### ❌ Bad Practice ```javascript async function getData() { @@ -106,8 +108,9 @@ async function getData() { ``` ### 🚀 Solution Wrap `await` calls in `try/catch` blocks or use a higher-order function to catch errors. -## 25. Floating point math errors (`0.1 + 0.2`) -**Context:** Precision issues in IEEE 754 arithmetic. +## ⚡ 25. Floating point math errors (`0.1 + 0.2`) +> [!NOTE] +> **Context:** Precision issues in IEEE 754 arithmetic. ### ❌ Bad Practice ```javascript if (0.1 + 0.2 === 0.3) { /* False! */ } @@ -124,8 +127,9 @@ const totalCents = (10 + 20); // 30 cents ``` ### 🚀 Solution Use `Number.EPSILON` for comparisons or represent decimals as integers (e.g., cents instead of dollars) to avoid floating point drift. -## 26. Multiple Boolean flags vs State Machine -**Context:** Managing complex component logic. +## ⚡ 26. Multiple Boolean flags vs State Machine +> [!NOTE] +> **Context:** Managing complex component logic. ### ❌ Bad Practice ```javascript const [isLoading, setIsLoading] = useState(false); @@ -140,8 +144,9 @@ const [status, setStatus] = useState('IDLE'); // IDLE, LOADING, ERROR, SUCCESS ``` ### 🚀 Solution Use a single state variable or a state machine. This ensures only one state is active at a time and simplifies transitions. -## 27. Sync logic in Event Loop -**Context:** Keeping the UI responsive. +## ⚡ 27. Sync logic in Event Loop +> [!NOTE] +> **Context:** Keeping the UI responsive. ### ❌ Bad Practice ```javascript function processLargeArray(arr) { @@ -163,8 +168,9 @@ function processInChunks(arr) { ``` ### 🚀 Solution Offload heavy tasks to Web Workers or use `requestIdleCallback`/`setTimeout` to break long tasks into smaller chunks, allowing the browser to render between frames. -## 28. Overusing `classes` where functions suffice -**Context:** Paradigm choice (OOP vs FP). +## ⚡ 28. Overusing `classes` where functions suffice +> [!NOTE] +> **Context:** Paradigm choice (OOP vs FP). ### ❌ Bad Practice ```javascript class Calculator { @@ -180,8 +186,9 @@ export const add = (a, b) => a + b; ``` ### 🚀 Solution Use simple functions and modules for logic. Use classes only when you need to manage complex stateful instances with shared behavior. -## 29. Hard-coded Error messages vs Error Classes -**Context:** Robust error handling and debugging. +## ⚡ 29. Hard-coded Error messages vs Error Classes +> [!NOTE] +> **Context:** Robust error handling and debugging. ### ❌ Bad Practice ```javascript throw new Error('User not found'); @@ -200,8 +207,9 @@ class UserNotFoundError extends Error { ``` ### 🚀 Solution Extend the `Error` class to create custom error types. Use `instanceof` check in catch blocks to handle specific errors differently. -## 30. Unhandled Rejections -**Context:** Reliability of asynchronous flows. +## ⚡ 30. Unhandled Rejections +> [!NOTE] +> **Context:** Reliability of asynchronous flows. ### ❌ Bad Practice ```javascript // No .catch() or try/catch diff --git a/frontend/javascript/modern-syntax.md b/frontend/javascript/modern-syntax.md index 9397fb8..53aa3d7 100644 --- a/frontend/javascript/modern-syntax.md +++ b/frontend/javascript/modern-syntax.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Modern JavaScript Syntax & FP within the frontend domain. technology: JavaScript domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "ES2024+" tags: [javascript, es6, functional-programming, best-practices, clean-code, scalable-code] ai_role: Senior JavaScript Expert last_updated: 2026-03-22 -topic: JavaScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # ✨ Modern JavaScript Syntax & Functional Programming Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to modern ES6+ syntax and functional programming patterns. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** ES2024+ -## II. Modern Syntax & FP (ES6-ES2024) -## 11. Manual object property assignment vs Shorthand -**Context:** Reducing boilerplate in object creation. +## ⚡ II. Modern Syntax & FP (ES6-ES2024) +## ⚡ 11. Manual object property assignment vs Shorthand +> [!NOTE] +> **Context:** Reducing boilerplate in object creation. ### ❌ Bad Practice ```javascript const name = 'Alice'; @@ -37,8 +36,9 @@ const user = { name, age }; ``` ### 🚀 Solution Use Property Shorthand. When the key and variable name match, omit the value. -## 12. Using `arguments` vs Rest parameters -**Context:** Handling variable numbers of arguments. +## ⚡ 12. Using `arguments` vs Rest parameters +> [!NOTE] +> **Context:** Handling variable numbers of arguments. ### ❌ Bad Practice ```javascript function sum() { @@ -54,8 +54,9 @@ const sum = (...args) => args.reduce((a, b) => a + b); ``` ### 🚀 Solution Use Rest Parameters (`...args`). They create a real array and are more explicit about the function's intent. -## 13. Manual array copying vs Spread -**Context:** Immutability and array manipulation. +## ⚡ 13. Manual array copying vs Spread +> [!NOTE] +> **Context:** Immutability and array manipulation. ### ❌ Bad Practice ```javascript const original = [1, 2, 3]; @@ -73,8 +74,9 @@ const copy = [...original]; ``` ### 🚀 Solution Use the Spread Operator (`...`). It is concise, declarative, and highly optimized by modern engines. -## 14. Nested Destructuring -**Context:** Extracting data from complex objects. +## ⚡ 14. Nested Destructuring +> [!NOTE] +> **Context:** Extracting data from complex objects. ### ❌ Bad Practice ```javascript const city = user.location.address.city; @@ -88,8 +90,9 @@ const { location: { address: { city, zip } } } = user; ``` ### 🚀 Solution Use nested destructuring to extract deeply nested values in a single statement. (Note: Combine with optional chaining if path existence isn't guaranteed). -## 15. Default Parameters -**Context:** Handling missing arguments. +## ⚡ 15. Default Parameters +> [!NOTE] +> **Context:** Handling missing arguments. ### ❌ Bad Practice ```javascript function setRole(role) { @@ -107,8 +110,9 @@ function setRole(role = 'guest') { ``` ### 🚀 Solution Use ES6 Default Parameters. They only apply if the argument is `undefined`. -## 16. `forEach` for data transformation vs `map/filter` -**Context:** Declarative vs Imperative programming. +## ⚡ 16. `forEach` for data transformation vs `map/filter` +> [!NOTE] +> **Context:** Declarative vs Imperative programming. ### ❌ Bad Practice ```javascript const double = []; @@ -124,8 +128,9 @@ const double = numbers.map(n => n * 2); ``` ### 🚀 Solution Use `map`, `filter`, and `reduce` for data transformations. They return new arrays and promote immutability. -## 17. Object mutation vs Immutability -**Context:** State management and predictability. +## ⚡ 17. Object mutation vs Immutability +> [!NOTE] +> **Context:** State management and predictability. ### ❌ Bad Practice ```javascript function updateAge(user) { @@ -141,8 +146,9 @@ const updateAge = (user) => ({ ...user, age: 30 }); ``` ### 🚀 Solution Treat objects as immutable. Use the spread operator to create copies with updated properties. -## 18. Switch statements vs Object Literals -**Context:** Simplifying conditional branching. +## ⚡ 18. Switch statements vs Object Literals +> [!NOTE] +> **Context:** Simplifying conditional branching. ### ❌ Bad Practice ```javascript switch (action) { @@ -163,8 +169,9 @@ return (actions[action] || doNothing)(); ``` ### 🚀 Solution Use an Object Literal (or Map) as a lookup table. It is cleaner, faster, and more extensible. -## 19. Not using Optional Chaining `?.` -**Context:** Safe property access in nested objects. +## ⚡ 19. Not using Optional Chaining `?.` +> [!NOTE] +> **Context:** Safe property access in nested objects. ### ❌ Bad Practice ```javascript const street = user && user.address && user.address.street; @@ -177,8 +184,9 @@ const street = user?.address?.street; ``` ### 🚀 Solution Use Optional Chaining (`?.`). It short-circuits to `undefined` if any part of the chain is nullish. -## 20. Not using Nullish Coalescing `??` -**Context:** Providing fallback values safely. +## ⚡ 20. Not using Nullish Coalescing `??` +> [!NOTE] +> **Context:** Providing fallback values safely. ### ❌ Bad Practice ```javascript const timeout = config.timeout || 5000; diff --git a/frontend/javascript/professional-niche.md b/frontend/javascript/professional-niche.md index feae03c..264ea4d 100644 --- a/frontend/javascript/professional-niche.md +++ b/frontend/javascript/professional-niche.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for JavaScript Professional & Niche topics within the frontend domain. technology: JavaScript domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "ES2024+" tags: [javascript, advanced, best-practices, clean-code, scalable-code] ai_role: Senior JavaScript Expert last_updated: 2026-03-22 -topic: JavaScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🧠 JavaScript Professional & Niche Best Practices (Senior Level) + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Detail advanced and niche topics in JavaScript for high-performance applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** ES2024+ -## IV. Professional & Niche (Senior Level) -## 31. Memory Leaks: Unremoved Event Listeners -**Context:** Long-lived applications (SPAs). +## ⚡ IV. Professional & Niche (Senior Level) +## ⚡ 31. Memory Leaks: Unremoved Event Listeners +> [!NOTE] +> **Context:** Long-lived applications (SPAs). ### ❌ Bad Practice ```javascript window.addEventListener('resize', () => this.handleResize()); @@ -36,8 +35,9 @@ window.removeEventListener('resize', handler); ``` ### 🚀 Solution Always remove event listeners in cleanup phases (e.g., `componentWillUnmount` or `useEffect` return). Use `AbortController` for an even more modern approach to listener cleanup. -## 32. Memory Leaks: Forgotten Intervals/Timeouts -**Context:** Managing temporal background tasks. +## ⚡ 32. Memory Leaks: Forgotten Intervals/Timeouts +> [!NOTE] +> **Context:** Managing temporal background tasks. ### ❌ Bad Practice ```javascript setInterval(() => { @@ -54,8 +54,9 @@ clearInterval(intervalId); ``` ### 🚀 Solution Store the ID returned by `setTimeout` or `setInterval` and clear it when the task is no longer relevant. -## 33. Closures inside loops (Memory/Scope issues) -**Context:** Understanding the Event Loop and closure capture. +## ⚡ 33. Closures inside loops (Memory/Scope issues) +> [!NOTE] +> **Context:** Understanding the Event Loop and closure capture. ### ❌ Bad Practice ```javascript for (var i = 0; i < 5; i++) { @@ -72,8 +73,9 @@ for (let i = 0; i < 5; i++) { ``` ### 🚀 Solution Use `let` in loop headers. It creates a new binding for each iteration, ensuring the closure captures the value of `i` at that specific moment. -## 34. Throwing Strings instead of `new Error()` -**Context:** Ensuring useful stack traces. +## ⚡ 34. Throwing Strings instead of `new Error()` +> [!NOTE] +> **Context:** Ensuring useful stack traces. ### ❌ Bad Practice ```javascript throw 'Something went wrong'; @@ -86,8 +88,9 @@ throw new Error('Something went wrong'); ``` ### 🚀 Solution Always throw an instance of `Error` (or a subclass). This captures the `stack` property, which is vital for debugging. -## 35. Modifying Built-in Prototypes -**Context:** Ecosystem compatibility and stability. +## ⚡ 35. Modifying Built-in Prototypes +> [!NOTE] +> **Context:** Ecosystem compatibility and stability. ### ❌ Bad Practice ```javascript Array.prototype.last = function() { @@ -102,8 +105,9 @@ const last = (arr) => arr[arr.length - 1]; ``` ### 🚀 Solution Use utility functions or wrapper classes instead of modifying global prototypes. -## 36. Premature Optimization (e.g., bitwise for rounding) -**Context:** Readability vs Micro-benchmarks. +## ⚡ 36. Premature Optimization (e.g., bitwise for rounding) +> [!NOTE] +> **Context:** Readability vs Micro-benchmarks. ### ❌ Bad Practice ```javascript const floor = ~~x; // Double bitwise NOT to floor @@ -116,8 +120,9 @@ const floor = Math.floor(x); ``` ### 🚀 Solution Prioritize readability. Modern JIT compilers are smart enough to optimize `Math.floor`. Only use bitwise tricks if profiling proves it's a critical bottleneck in a hot path. -## 37. V8 Hidden Classes: Changing object shape after initialization -**Context:** V8 JIT optimization. +## ⚡ 37. V8 Hidden Classes: Changing object shape after initialization +> [!NOTE] +> **Context:** V8 JIT optimization. ### ❌ Bad Practice ```javascript function User(name) { @@ -138,8 +143,9 @@ const u1 = new User('Alice', 25); ``` ### 🚀 Solution Initialize all object properties in the constructor or a factory function. Maintain a consistent object "shape" to keep V8 in the optimized path. -## 38. Array Hole (Sparse Arrays) performance -**Context:** Memory allocation and JIT optimization. +## ⚡ 38. Array Hole (Sparse Arrays) performance +> [!NOTE] +> **Context:** Memory allocation and JIT optimization. ### ❌ Bad Practice ```javascript const arr = new Array(100); @@ -153,8 +159,9 @@ const arr = Array.from({ length: 100 }, () => null); ``` ### 🚀 Solution Initialize arrays with default values (like `null` or `0`) instead of leaving empty slots. This keeps the array in "packed" mode. -## 39. Using `eval()` or `new Function()` -**Context:** Security and performance. +## ⚡ 39. Using `eval()` or `new Function()` +> [!NOTE] +> **Context:** Security and performance. ### ❌ Bad Practice ```javascript const result = eval('2 + 2'); @@ -169,8 +176,9 @@ const operations = { '+': (a, b) => a + b }; ``` ### 🚀 Solution Avoid `eval()`. Use lookup tables, JSON parsing, or safe math libraries to handle dynamic logic. -## 40. Micro-optimizations that hurt readability -**Context:** Maintaining a healthy codebase. +## ⚡ 40. Micro-optimizations that hurt readability +> [!NOTE] +> **Context:** Maintaining a healthy codebase. ### ❌ Bad Practice ```javascript for (let i = 0, len = arr.length; i < len; i++) { /* ... */ } diff --git a/frontend/javascript/readme.md b/frontend/javascript/readme.md index 6aeb4a9..6e013e3 100644 --- a/frontend/javascript/readme.md +++ b/frontend/javascript/readme.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for JavaScript within the frontend domain. technology: JavaScript domain: frontend level: Senior/Architect @@ -7,10 +6,7 @@ version: ES6-ES2024 tags: [javascript, clean-code, es6, performance, best-practices] ai_role: Senior JavaScript Performance Expert last_updated: 2026-03-22 -topic: JavaScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🎨 JavaScript Best Practise @@ -20,7 +16,8 @@ vibe_coding_ready: true--- ## 🚀 I. Fundamentals (The Basics) ### 🚨 1. `var` vs `const/let` -**Context:** Scoping and hoisting mechanisms in modern JavaScript. `var` is function-scoped and hoisted, leading to unpredictable behavior and accidental global leakage. +> [!NOTE] +> **Context:** Scoping and hoisting mechanisms in modern JavaScript. `var` is function-scoped and hoisted, leading to unpredictable behavior and accidental global leakage. #### ❌ Bad Practice ```javascript var price = 100; @@ -44,7 +41,8 @@ Use `const` by default to ensure immutability of the reference. Use `let` only w --- ### 🚨 2. Loose equality `==` -**Context:** JavaScript's type coercion rules are complex and often counter-intuitive. +> [!NOTE] +> **Context:** JavaScript's type coercion rules are complex and often counter-intuitive. #### ❌ Bad Practice ```javascript if (userCount == '0') { @@ -64,7 +62,8 @@ Always use strict equality `===` and inequality `!==`. This forces the developer --- ### 🚨 3. Global Scope Pollution -**Context:** The global namespace is shared. Overwriting global properties can break third-party libraries or browser APIs. +> [!NOTE] +> **Context:** The global namespace is shared. Overwriting global properties can break third-party libraries or browser APIs. #### ❌ Bad Practice ```javascript // In a script file @@ -88,7 +87,8 @@ Use ES Modules (`import/export`) to encapsulate code. Modules have their own sco --- ### 🚨 4. String concatenation vs Template Literals -**Context:** Readability and handling of multi-line strings/expressions. +> [!NOTE] +> **Context:** Readability and handling of multi-line strings/expressions. #### ❌ Bad Practice ```javascript const greeting = 'Hello, ' + user.firstName + ' ' + user.lastName + '! ' + @@ -106,7 +106,8 @@ Use Template Literals (backticks). They allow for embedded expressions, multi-li --- ### 🚨 5. Magic Numbers -**Context:** Numbers with no context make the codebase hard to maintain. +> [!NOTE] +> **Context:** Numbers with no context make the codebase hard to maintain. #### ❌ Bad Practice ```javascript if (user.age >= 18) { @@ -128,7 +129,8 @@ Extract magic numbers into named constants. This provides semantic meaning and a --- ### 🚨 6. Boolean comparisons `(if x === true)` -**Context:** Redundancy in conditional logic. +> [!NOTE] +> **Context:** Redundancy in conditional logic. #### ❌ Bad Practice ```javascript if (isValid === true) { /* ... */ } @@ -145,7 +147,8 @@ Leverage JavaScript's truthiness/falsiness or direct boolean evaluation. It make --- ### 🚨 7. Array/Object literal vs `new` constructor -**Context:** Object and Array instantiation. +> [!NOTE] +> **Context:** Object and Array instantiation. #### ❌ Bad Practice ```javascript const list = new Array(1, 2, 3); @@ -163,7 +166,8 @@ Use literals `[]` and `{}`. They are visually cleaner and perform slightly bette --- ### 🚨 8. Function length/complexity -**Context:** The Single Responsibility Principle (SRP). +> [!NOTE] +> **Context:** The Single Responsibility Principle (SRP). #### ❌ Bad Practice ```javascript function processOrder(order) { @@ -189,7 +193,8 @@ Break functions into smaller, pure components. Aim for functions under 20 lines --- ### 🚨 9. Deeply nested `if/else` (Arrow code) -**Context:** Cognitive load and code readability. +> [!NOTE] +> **Context:** Cognitive load and code readability. #### ❌ Bad Practice ```javascript function getData(user) { @@ -218,7 +223,8 @@ Use "Guard Clauses" to return early. This flattens the structure and handles edg --- ### 🚨 10. Improper naming (Single letters) -**Context:** Self-documenting code. +> [!NOTE] +> **Context:** Self-documenting code. #### ❌ Bad Practice ```javascript const d = new Date(); diff --git a/frontend/qwik/readme.md b/frontend/qwik/readme.md index 2580e2d..99f2ea5 100644 --- a/frontend/qwik/readme.md +++ b/frontend/qwik/readme.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Qwik within the frontend domain. technology: Qwik domain: frontend level: Senior/Architect @@ -7,12 +6,11 @@ version: "1.x" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Qwik Expert last_updated: 2026-03-22 -topic: Qwik -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # ⚡ Qwik Best Practices & Production-Ready Patterns + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to modern Qwik patterns, specifically resumability and lazy loading for optimal best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -28,8 +26,9 @@ vibe_coding_ready: true--- - Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications. - Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams. ## 🚀 I. Basics & Popular -## 1. Passing Closures as Props -**Context:** Component Props +## ⚡ 1. Passing Closures as Props +> [!NOTE] +> **Context:** Component Props ### ❌ Bad Practice ```tsx const Component = ({ onClick }) => ; diff --git a/frontend/react/performance.md b/frontend/react/performance.md index 9296f82..075af0b 100644 --- a/frontend/react/performance.md +++ b/frontend/react/performance.md @@ -1,12 +1,12 @@ --- -description: Vibe coding guidelines and architectural constraints for React Performance within the frontend domain. technology: React domain: frontend level: Senior/Architect version: "19+" tags: [react, performance, use, react-compiler, best-practices, architecture, clean-code] ai_role: Senior React Performance Expert -last_updated: 2026-03-22--- +last_updated: 2026-03-22 +--- # ⚡ React Performance & Best Practices @@ -17,8 +17,9 @@ last_updated: 2026-03-22--- - **Tech Stack Version:** React 19+ ## 📚 Topics -### 1. Manual Memoization vs React Compiler -**Context:** Avoiding unnecessary re-renders. +### 🔹 1. Manual Memoization vs React Compiler +> [!NOTE] +> **Context:** Avoiding unnecessary re-renders. #### ❌ Bad Practice ```tsx import { useMemo, useCallback } from 'react'; @@ -54,8 +55,9 @@ Rely on the **React Compiler** (introduced in React 19+). The compiler automatic - **Performance Note:** The React Compiler analyzes your component structure and injects optimal memoization (similar to SolidJS's granular updates), eliminating the overhead of manual dependency tracking. - **Security Note:** While the React Compiler does not directly impact security, it ensures components render exactly when their inputs change, reducing side effects that might otherwise expose temporary or stale data to users. -### 2. Resolving Promises During Render -**Context:** Conditionally handling promises without `useEffect` or `useState`. +### 🔹 2. Resolving Promises During Render +> [!NOTE] +> **Context:** Conditionally handling promises without `useEffect` or `useState`. #### ❌ Bad Practice ```tsx import { useEffect, useState } from 'react'; diff --git a/frontend/react/readme.md b/frontend/react/readme.md index 146c95b..343507f 100644 --- a/frontend/react/readme.md +++ b/frontend/react/readme.md @@ -1,12 +1,12 @@ --- -description: Vibe coding guidelines and architectural constraints for React within the frontend domain. technology: React domain: frontend level: Senior/Architect version: "19+" tags: [react, best-practices, architecture, clean-code, scalable-code, modern-react, server-components] ai_role: Senior React Expert -last_updated: 2026-03-22--- +last_updated: 2026-03-22 +--- # ⚛️ React Production-Ready Best Practices # 📖 Context & Scope @@ -22,8 +22,9 @@ last_updated: 2026-03-22--- - Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams. ## 🚀 I. Basics & Popular -### 1. Direct DOM Manipulation -**Context:** Updating elements in a React component. +### 🔹 1. Direct DOM Manipulation +> [!NOTE] +> **Context:** Updating elements in a React component. #### ❌ Bad Practice ```tsx function Component() { @@ -54,8 +55,9 @@ Always use state and props to drive the UI. React uses a virtual DOM to efficien - **Performance Note:** React's virtual DOM diffing algorithm is highly optimized. Bypassing it can lead to forced synchronous layouts and jank. - **Security Note:** Direct DOM manipulation can open up Cross-Site Scripting (XSS) vulnerabilities if user input is not properly sanitized before being inserted into the DOM. -### 2. Large Component Files -**Context:** Managing component complexity. +### 🔹 2. Large Component Files +> [!NOTE] +> **Context:** Managing component complexity. #### ❌ Bad Practice A single 2000-line file containing the entire page's logic and UI. #### ⚠️ Problem diff --git a/frontend/react/state-management.md b/frontend/react/state-management.md index ed2da6d..c97a8b9 100644 --- a/frontend/react/state-management.md +++ b/frontend/react/state-management.md @@ -1,16 +1,12 @@ --- -description: Vibe coding guidelines and architectural constraints for React State Management within the frontend domain. -tags: [react, state-management, server-actions, best-practices, architecture, clean-code] -topic: React State Management -complexity: Architect -last_evolution: 2026-03-22 -vibe_coding_ready: true technology: React domain: frontend level: Senior/Architect version: "19+" +tags: [react, state-management, server-actions, best-practices, architecture, clean-code] ai_role: Senior React State Management Expert -last_updated: 2026-03-22--- +last_updated: 2026-03-22 +--- # 🔄 React State Management & Server Actions Best Practices @@ -21,8 +17,9 @@ last_updated: 2026-03-22--- - **Tech Stack Version:** React 19+ ## 📚 Topics -### 1. Handling Async Actions (Forms) -**Context:** Managing state updates triggered by form submissions or asynchronous operations. +### 🔹 1. Handling Async Actions (Forms) +> [!NOTE] +> **Context:** Managing state updates triggered by form submissions or asynchronous operations. #### ❌ Bad Practice ```tsx import { useState } from 'react'; @@ -70,8 +67,9 @@ Use the `useActionState` Hook (React 19+) for seamless action state management. - **Performance Note:** `useActionState` effectively handles race conditions by ensuring only the latest action state is applied to the UI, optimizing rendering cycles. - **Security Note:** Form actions seamlessly interact with Server Actions. Ensure that `saveAction` strictly validates input server-side to prevent malicious payloads, and use CSRF tokens if required by your framework. -### 2. Using Global State Naively -**Context:** Storing local component UI state in a global store (e.g., Redux, Zustand). +### 🔹 2. Using Global State Naively +> [!NOTE] +> **Context:** Storing local component UI state in a global store (e.g., Redux, Zustand). #### ❌ Bad Practice Putting a dropdown's `isOpen` state into the global Redux store. #### ⚠️ Problem diff --git a/frontend/readme.md b/frontend/readme.md index eb59acf..5004cbf 100644 --- a/frontend/readme.md +++ b/frontend/readme.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for Frontend Architecture within the frontend domain. technology: Frontend Architecture domain: frontend level: Senior/Architect @@ -7,12 +6,11 @@ version: Agnostic tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior Frontend Architect last_updated: 2026-03-22 -topic: TypeScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🎨 Frontend Best Practices & Production-Ready Patterns + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Outline the overarching philosophy and standards for Frontend development inside the ecosystem. - **Target Tooling:** Cursor, Windsurf, Antigravity. diff --git a/frontend/solidjs/readme.md b/frontend/solidjs/readme.md index 8bb3081..89af51e 100644 --- a/frontend/solidjs/readme.md +++ b/frontend/solidjs/readme.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for SolidJS within the frontend domain. technology: SolidJS domain: frontend level: Senior/Architect @@ -7,12 +6,11 @@ version: "1.8+" tags: [best-practices, clean-code, architecture-patterns, vibe-coding, cursor-rules, typescript, software-architecture, system-design, solid-principles, production-ready, programming-standards, react-best-practices, node-js, design-patterns, scalable-code, windsurf-rules, ai-coding, fsd, ddd, enterprise-patterns] ai_role: Senior SolidJS Expert last_updated: 2026-03-22 -topic: SolidJS -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # ⚡ SolidJS Best Practices & Production-Ready Patterns + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Enforce strict adherence to modern SolidJS patterns, specifically fine-grained reactivity and functional APIs for optimal best practices. - **Target Tooling:** Cursor, Windsurf, Antigravity. @@ -28,8 +26,9 @@ vibe_coding_ready: true--- - Adhere to the defined [Architectural Patterns](../../architectures/readme.md) when building applications. - Strongly prefer **Feature Sliced Design (FSD)** for applications scaling across multiple teams. ## 🚀 I. Basics & Popular -## 1. Using JSX Map for Lists -**Context:** Rendering Lists +## ⚡ 1. Using JSX Map for Lists +> [!NOTE] +> **Context:** Rendering Lists ### ❌ Bad Practice ```tsx return
      {items().map(item =>
    • {item.name}
    • )}
    ; diff --git a/frontend/typescript/logic-safety.md b/frontend/typescript/logic-safety.md index 621b7e8..24e466a 100644 --- a/frontend/typescript/logic-safety.md +++ b/frontend/typescript/logic-safety.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for TypeScript Logic & Safety within the frontend domain. technology: TypeScript domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "5.5+" tags: [typescript, type-safety, best-practices, clean-code, scalable-code] ai_role: Senior TypeScript Expert last_updated: 2026-03-22 -topic: TypeScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🛡️ TypeScript Logic & Safety Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Enforce strict type safety and logical soundness in TypeScript. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** TypeScript 5.5+ -## II. Logic & Safety (11-20) -## 11. Type Assertions (`as`) vs Narrowing -**Context:** Telling the compiler what a type is. +## ⚡ II. Logic & Safety (11-20) +## ⚡ 11. Type Assertions (`as`) vs Narrowing +> [!NOTE] +> **Context:** Telling the compiler what a type is. ### ❌ Bad Practice ```typescript const user = response.data as User; @@ -35,8 +34,9 @@ if (isValidUser(response.data)) { ... } ``` ### 🚀 Solution Avoid type assertions. Use runtime validation (Zod, Valibot) or Type Guards to ensure the data actually matches the type you expect. -## 12. Non-null Assertion Operator (`!`) -**Context:** Dealing with potentially `null` or `undefined` values. +## ⚡ 12. Non-null Assertion Operator (`!`) +> [!NOTE] +> **Context:** Dealing with potentially `null` or `undefined` values. ### ❌ Bad Practice ```typescript const name = user!.profile!.name; @@ -49,8 +49,9 @@ const name = user?.profile?.name ?? 'Guest'; ``` ### 🚀 Solution Use Optional Chaining (`?.`) and Nullish Coalescing (`??`) to handle missing values gracefully. -## 13. Lack of Discriminated Unions -**Context:** Modeling complex states like API responses. +## ⚡ 13. Lack of Discriminated Unions +> [!NOTE] +> **Context:** Modeling complex states like API responses. ### ❌ Bad Practice ```typescript interface State { @@ -70,8 +71,9 @@ type State = ``` ### 🚀 Solution Use Discriminated Unions (with a shared literal property like `type` or `kind`). This makes states mutually exclusive and simplifies logic. -## 14. Boolean casting (`!!`) -**Context:** Converting values to booleans. +## ⚡ 14. Boolean casting (`!!`) +> [!NOTE] +> **Context:** Converting values to booleans. ### ❌ Bad Practice ```typescript const hasAccess = !!user.token; @@ -86,8 +88,9 @@ const hasAccess = user.token !== undefined; ``` ### 🚀 Solution Use the `Boolean()` constructor or explicit comparisons for clarity. -## 15. Using `Object` for non-primitive types -**Context:** Restricting types to objects. +## ⚡ 15. Using `Object` for non-primitive types +> [!NOTE] +> **Context:** Restricting types to objects. ### ❌ Bad Practice ```typescript function cache(obj: Object) { ... } @@ -100,8 +103,9 @@ function cache(obj: Record) { ... } ``` ### 🚀 Solution Use `Record` for general objects or `Record` for empty objects to ensure keys are strings and values are handled safely. -## 16. Function types vs Object types for functions -**Context:** Defining function signatures. +## ⚡ 16. Function types vs Object types for functions +> [!NOTE] +> **Context:** Defining function signatures. ### ❌ Bad Practice ```typescript type ClickHandler = { @@ -116,8 +120,9 @@ type ClickHandler = (e: Event) => void; ``` ### 🚀 Solution Use the arrow function syntax for type aliases unless you need to define properties on the function itself (callable objects). -## 17. Catching `any` in try-catch -**Context:** Handling exceptions. +## ⚡ 17. Catching `any` in try-catch +> [!NOTE] +> **Context:** Handling exceptions. ### ❌ Bad Practice ```typescript try { @@ -140,8 +145,9 @@ try { ``` ### 🚀 Solution Always check the type of the caught error. In modern TS, use `useUnknownInCatchVariables: true` to force `e` to be `unknown`. -## 18. Literal types vs General types -**Context:** Narrowing strings/numbers to specific values. +## ⚡ 18. Literal types vs General types +> [!NOTE] +> **Context:** Narrowing strings/numbers to specific values. ### ❌ Bad Practice ```typescript function setAlignment(dir: string) { ... } @@ -155,8 +161,9 @@ function setAlignment(dir: Direction) { ... } ``` ### 🚀 Solution Use Union Literal types to restrict inputs to a known set of valid values. -## 19. Optional properties vs Union with `undefined` -**Context:** Defining fields that might not exist. +## ⚡ 19. Optional properties vs Union with `undefined` +> [!NOTE] +> **Context:** Defining fields that might not exist. ### ❌ Bad Practice ```typescript interface Config { @@ -173,8 +180,9 @@ interface Config { ``` ### 🚀 Solution Use `?` for properties that can be omitted entirely. -## 20. Array index access safety -**Context:** Accessing elements by index. +## ⚡ 20. Array index access safety +> [!NOTE] +> **Context:** Accessing elements by index. ### ❌ Bad Practice ```typescript const first = users[0]; diff --git a/frontend/typescript/objects-functions.md b/frontend/typescript/objects-functions.md index 9bd9c85..9882973 100644 --- a/frontend/typescript/objects-functions.md +++ b/frontend/typescript/objects-functions.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for TypeScript Objects & Functions within the frontend domain. technology: TypeScript domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "5.5+" tags: [typescript, objects, functions, best-practices, clean-code, scalable-code] ai_role: Senior TypeScript Expert last_updated: 2026-03-22 -topic: TypeScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 📦 TypeScript Objects & Functions Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Proper typing for objects, arrays, and functions in TypeScript applications. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** TypeScript 5.5+ -## III. Objects & Functions (21-30) -## 21. Object literals vs `Record` -**Context:** Defining maps/dictionaries. +## ⚡ III. Objects & Functions (21-30) +## ⚡ 21. Object literals vs `Record` +> [!NOTE] +> **Context:** Defining maps/dictionaries. ### ❌ Bad Practice ```typescript const prices: { [key: string]: number } = { apple: 1 }; @@ -32,8 +31,9 @@ const prices: Record = { apple: 1 }; ``` ### 🚀 Solution Use the `Record` utility type for key-value maps. -## 22. Excess property checks and object spreading -**Context:** Passing objects to functions. +## ⚡ 22. Excess property checks and object spreading +> [!NOTE] +> **Context:** Passing objects to functions. ### ❌ Bad Practice ```typescript const extra = { id: 1, name: 'A', extra: true }; @@ -49,8 +49,9 @@ saveUser(validUser); ``` ### 🚀 Solution Be explicit about what data you pass. Use destructuring to strip unknown properties before passing objects to storage or APIs. -## 23. `Readonly` for Immutability -**Context:** Preventing accidental state mutation. +## ⚡ 23. `Readonly` for Immutability +> [!NOTE] +> **Context:** Preventing accidental state mutation. ### ❌ Bad Practice ```typescript function process(config: Config) { @@ -67,8 +68,9 @@ function process(config: Readonly) { ``` ### 🚀 Solution Use `Readonly` for function parameters and `as const` for configuration objects to enforce immutability at compile time. -## 24. `Awaited` for Promise Unwrapping -**Context:** Getting the resolved type of a Promise. +## ⚡ 24. `Awaited` for Promise Unwrapping +> [!NOTE] +> **Context:** Getting the resolved type of a Promise. ### ❌ Bad Practice ```typescript type Result = typeof apiCall extends Promise ? U : never; @@ -81,8 +83,9 @@ type Result = Awaited>; ``` ### 🚀 Solution Use the `Awaited` utility type (TS 4.5+) for clean promise unwrapping. -## 25. `this` typing in functions -**Context:** Ensuring correct context in callback-heavy code. +## ⚡ 25. `this` typing in functions +> [!NOTE] +> **Context:** Ensuring correct context in callback-heavy code. ### ❌ Bad Practice ```typescript function handleClick(this: unknown, event: Event) { @@ -99,8 +102,9 @@ function handleClick(this: HTMLElement, event: Event) { ``` ### 🚀 Solution Always type the first "fake" `this` parameter in functions that rely on a specific execution context. -## 26. Constructor Shorthand -**Context:** Defining class properties. +## ⚡ 26. Constructor Shorthand +> [!NOTE] +> **Context:** Defining class properties. ### ❌ Bad Practice ```typescript class User { @@ -120,8 +124,9 @@ class User { ``` ### 🚀 Solution Use parameter properties in constructors to declare and initialize class members in one step. -## 27. Abstract classes vs Interfaces -**Context:** Defining blueprints for classes. +## ⚡ 27. Abstract classes vs Interfaces +> [!NOTE] +> **Context:** Defining blueprints for classes. ### ❌ Bad Practice ```typescript class BaseService { @@ -139,8 +144,9 @@ abstract class BaseService { ``` ### 🚀 Solution Use `abstract` classes when you need to provide shared logic while forcing sub-classes to implement specific methods. -## 28. Private vs `#private` -**Context:** Encapsulating data in classes. +## ⚡ 28. Private vs `#private` +> [!NOTE] +> **Context:** Encapsulating data in classes. ### ❌ Bad Practice ```typescript class User { @@ -158,8 +164,9 @@ class User { ``` ### 🚀 Solution Use ES2020 `#private` fields for true runtime encapsulation if you are building libraries or high-security components. -## 29. Decorators (Legacy vs TC39) -**Context:** Meta-programming in TypeScript. +## ⚡ 29. Decorators (Legacy vs TC39) +> [!NOTE] +> **Context:** Meta-programming in TypeScript. ### ❌ Bad Practice ```typescript // Using experimentalDecorators: true @@ -172,8 +179,9 @@ Legacy decorators are non-standard and might break in future versions of Node/Br Use the new TC39 Decorators (TS 5.0+) which align with the official JavaScript proposal. ### 🚀 Solution If starting a new project, avoid decorators unless using a framework that mandates them (like NestJS or Angular). -## 30. Utility Types (`Omit`, `Pick`, `Partial`) -**Context:** Transforming existing types. +## ⚡ 30. Utility Types (`Omit`, `Pick`, `Partial`) +> [!NOTE] +> **Context:** Transforming existing types. ### ❌ Bad Practice ```typescript interface UserUpdate { diff --git a/frontend/typescript/professional-niche.md b/frontend/typescript/professional-niche.md index be0ff6e..c17de56 100644 --- a/frontend/typescript/professional-niche.md +++ b/frontend/typescript/professional-niche.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for TypeScript Professional & Niche topics within the frontend domain. technology: TypeScript domain: frontend level: Senior/Architect @@ -7,19 +6,19 @@ version: "5.5+" tags: [typescript, advanced, best-practices, clean-code, scalable-code] ai_role: Senior TypeScript Expert last_updated: 2026-03-22 -topic: TypeScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🧠 TypeScript Professional & Niche Best Practices + +[⬆️ Back to Top](#) # 📖 Context & Scope - **Primary Goal:** Advanced TypeScript features, metaprogramming, and precise utility types. - **Target Tooling:** Cursor, Windsurf, Antigravity. - **Tech Stack Version:** TypeScript 5.5+ -## IV. Professional & Niche (31-40) -## 31. Using `satisfies` to preserve literal types -**Context:** Checking an object against a type without widening it. +## ⚡ IV. Professional & Niche (31-40) +## ⚡ 31. Using `satisfies` to preserve literal types +> [!NOTE] +> **Context:** Checking an object against a type without widening it. ### ❌ Bad Practice ```typescript const config: Record = { @@ -38,8 +37,9 @@ const config = { ``` ### 🚀 Solution Use `satisfies` (TS 4.9+). It validates the structure but preserves the narrowest possible type for the value. -## 32. `const` type parameters (TS 5.0) -**Context:** Improving inference for generic constants. +## ⚡ 32. `const` type parameters (TS 5.0) +> [!NOTE] +> **Context:** Improving inference for generic constants. ### ❌ Bad Practice ```typescript function route(paths: T) { ... } @@ -54,8 +54,9 @@ route(['/home', '/about']); // T is readonly ['/home', '/about'] ``` ### 🚀 Solution Use `const` before a type parameter to force the compiler to treat the input as a constant, preserving literal types without requiring the caller to use `as const`. -## 33. Branding/Tagging for Nominal Typing -**Context:** Preventing accidental mixing of identical primitive types (e.g., `UserId` and `OrderId`). +## ⚡ 33. Branding/Tagging for Nominal Typing +> [!NOTE] +> **Context:** Preventing accidental mixing of identical primitive types (e.g., `UserId` and `OrderId`). ### ❌ Bad Practice ```typescript type UserId = string; @@ -77,8 +78,9 @@ const uid = 'user_1' as UserId; ``` ### 🚀 Solution Use "Branding" (adding a phantom property) to simulate nominal typing for critical identifiers. -## 34. Covariance/Contravariance in callbacks -**Context:** Ensuring safe function assignments. +## ⚡ 34. Covariance/Contravariance in callbacks +> [!NOTE] +> **Context:** Ensuring safe function assignments. ### ❌ Bad Practice ```typescript interface Logger { @@ -95,8 +97,9 @@ interface Logger { ``` ### 🚀 Solution Use method syntax in interfaces for stricter **contravariant** checking of parameters. -## 35. Avoiding "God Objects" through Mapped Types -**Context:** Transforming object structures dynamically. +## ⚡ 35. Avoiding "God Objects" through Mapped Types +> [!NOTE] +> **Context:** Transforming object structures dynamically. ### ❌ Bad Practice ```typescript interface API { @@ -115,8 +118,9 @@ type API = { ``` ### 🚀 Solution Use Mapped Types and Key Remapping (`as`) to generate interface structures from a single source of truth (like a union of keys). -## 36. Template Literal Types for string-based APIs -**Context:** Enforcing patterns in strings. +## ⚡ 36. Template Literal Types for string-based APIs +> [!NOTE] +> **Context:** Enforcing patterns in strings. ### ❌ Bad Practice ```typescript function setPadding(value: string) { ... } // Accepts "10" (invalid) @@ -130,8 +134,9 @@ function setPadding(value: CssValue) { ... } ``` ### 🚀 Solution Use Template Literal types to enforce specific string patterns at compile time. -## 37. Exhaustiveness checking with `never` -**Context:** Ensuring all cases in a union are handled. +## ⚡ 37. Exhaustiveness checking with `never` +> [!NOTE] +> **Context:** Ensuring all cases in a union are handled. ### ❌ Bad Practice ```typescript function handle(action: 'START' | 'STOP') { @@ -158,8 +163,9 @@ function handle(action: 'START' | 'STOP' | 'PAUSE') { ``` ### 🚀 Solution Assign the `default` case to a variable of type `never`. This triggers a compile error if any member of the union is unhandled. -## 38. Recursive Type Aliases -**Context:** Modeling nested structures like JSON or file trees. +## ⚡ 38. Recursive Type Aliases +> [!NOTE] +> **Context:** Modeling nested structures like JSON or file trees. ### ❌ Bad Practice ```typescript type Json = string | number | boolean | JsonObject | JsonArray; @@ -176,8 +182,9 @@ type JSONValue = ``` ### 🚀 Solution Use recursive type aliases for cleaner definitions of deeply nested data structures. -## 39. `infer` keyword in conditional types -**Context:** Extracting internal types from complex structures. +## ⚡ 39. `infer` keyword in conditional types +> [!NOTE] +> **Context:** Extracting internal types from complex structures. ### ❌ Bad Practice ```typescript // Hardcoded extraction @@ -191,8 +198,9 @@ type GetArrayType = T extends (infer U)[] ? U : never; ``` ### 🚀 Solution Use `infer` within conditional types to let TypeScript dynamically capture and name types from within generics. -## 40. Tuple types for fixed-length data -**Context:** Representing arrays with specific structures (e.g., coordinates). +## ⚡ 40. Tuple types for fixed-length data +> [!NOTE] +> **Context:** Representing arrays with specific structures (e.g., coordinates). ### ❌ Bad Practice ```typescript const point: number[] = [10, 20]; diff --git a/frontend/typescript/readme.md b/frontend/typescript/readme.md index 836be28..159e3be 100644 --- a/frontend/typescript/readme.md +++ b/frontend/typescript/readme.md @@ -1,5 +1,4 @@ --- -description: Vibe coding guidelines and architectural constraints for TypeScript within the frontend domain. technology: TypeScript domain: frontend level: Senior/Architect @@ -7,17 +6,15 @@ version: "5.0+" tags: [typescript, type-safety, clean-code, best-practices, architecture] ai_role: Senior TypeScript Architecture Expert last_updated: 2026-03-22 -topic: TypeScript -complexity: Architect -last_evolution: 2026-03-29 -vibe_coding_ready: true--- +--- # 🎨 TypeScript Best Practise ![TypeScript Logo](https://img.icons8.com/?size=100&id=uJM6fQYqDaZK&format=png&color=000000) ## 🚀 I. Fundamentals (1-10) ## ⚡ 1. `any` vs `unknown` -**Context:** Handling data of an uncertain type. `any` disables all type-checking, while `unknown` forces safety. +> [!NOTE] +> **Context:** Handling data of an uncertain type. `any` disables all type-checking, while `unknown` forces safety. ### ❌ Bad Practice ```typescript function process(data: unknown) { @@ -38,7 +35,8 @@ function process(data: unknown) { Use `unknown` for values whose type is not yet determined. It requires a type check or assertion before usage, ensuring the developer acknowledges the data's structure. --- ## ⚡ 2. `null` vs `undefined` in APIs -**Context:** Distinguishing between "value not provided" and "value is empty." +> [!NOTE] +> **Context:** Distinguishing between "value not provided" and "value is empty." ### ❌ Bad Practice ```typescript interface UserResponse { @@ -57,7 +55,8 @@ interface UserResponse { Standardize: use `undefined` (optional properties) for missing keys and `null` for intentional absence of value. Avoid using both for the same field unless strictly required by a legacy API. --- ## ⚡ 3. `Array` vs `T[]` -**Context:** Visual consistency in array declarations. +> [!NOTE] +> **Context:** Visual consistency in array declarations. ### ❌ Bad Practice ```typescript const users: Array = []; @@ -74,7 +73,8 @@ const complex: (string | number)[] = []; Prefer the shorthand `T[]`. It is idiomatic, more readable, and clearly distinguishes arrays from other generic containers like `Record` or `Promise`. --- ## ⚡ 4. `interface` vs `type` -**Context:** Defining object structures and aliases. +> [!NOTE] +> **Context:** Defining object structures and aliases. ### ❌ Bad Practice ```typescript interface Point { x: number; y: number; } @@ -92,7 +92,8 @@ type Union = 'A' | 'B'; Use `type` for almost everything (unions, primitives, intersections). Use `interface` only when you specifically need declaration merging or for public library APIs where consumers might need to extend types. --- ## ⚡ 5. Function Overloads vs Union Types -**Context:** Handling functions with different input/output combinations. +> [!NOTE] +> **Context:** Handling functions with different input/output combinations. ### ❌ Bad Practice ```typescript function format(input: string): string; @@ -113,7 +114,8 @@ function format(input: string | number): string { Prefer Union types when the implementation logic is identical for all types. Reserve overloads only for cases where the return type strictly depends on the input type and cannot be expressed via generics. --- ## 🎯 6. Global Scope Pollution (Legacy Namespaces) -**Context:** Organizing code in the ES Module era. +> [!NOTE] +> **Context:** Organizing code in the ES Module era. ### ❌ Bad Practice ```typescript namespace Utils { @@ -131,7 +133,8 @@ export const log = (msg: string) => console.log(msg); Use ES Modules (`export`/`import`). They are the industry standard, supported by all modern environments, and allow for better static analysis. --- ## ⚡ 7. `enum` vs `const object` -**Context:** Grouping related constants. +> [!NOTE] +> **Context:** Grouping related constants. ### ❌ Bad Practice ```typescript enum Status { @@ -154,7 +157,8 @@ type Status = typeof STATUS[keyof typeof STATUS]; Use `const` objects with `as const` and a derived union type. This is more predictable, emits cleaner code, and is easier to iterate over. --- ## ⚡ 8. Explicit `any` in Parameters -**Context:** Enforcing strict type safety. +> [!NOTE] +> **Context:** Enforcing strict type safety. ### ❌ Bad Practice ```typescript function save(data) { // Implicit unknown if strict: false @@ -173,7 +177,8 @@ function save(data: UserData) { Enable `noImplicitAny: true` in `tsconfig.json`. Always define specific types or use `unknown` if the type is truly dynamic. --- ## ⚡ 9. Manual Type Guards vs Type Predicates -**Context:** Narrowing types inside conditional blocks. +> [!NOTE] +> **Context:** Narrowing types inside conditional blocks. ### ❌ Bad Practice ```typescript if (typeof input === 'object' && input !== null && 'admin' in input) { @@ -196,7 +201,8 @@ if (isAdmin(input)) { Use Type Predicates (`arg is Type`) to create reusable, safe narrowing functions. --- ## ⚡ 10. Triple-Slash Directives -**Context:** Referencing types or files. +> [!NOTE] +> **Context:** Referencing types or files. ### ❌ Bad Practice ```typescript ///