# Architecture Guide ## ๐Ÿ—๏ธ Core Principles ### 1. Single Responsibility Each module has exactly one purpose. No mixing of concerns. ### 2. Event-Driven Communication All inter-module communication happens through EventBus. Zero direct dependencies. ```javascript // โŒ BAD - Direct access const gameManager = window.app.modules.gameManager; gameManager.startGame(); // โœ… GOOD - EventBus eventBus.emit('game:start', { difficulty: 'medium' }); ``` ### 3. Sealed Modules Modules cannot be modified after creation using `Object.seal()`. ```javascript constructor() { super('ModuleName'); this._privateState = {}; Object.seal(this); // Prevents adding/removing properties } ``` ### 4. WeakMap Private State Internal data is completely inaccessible from outside. ```javascript const privateData = new WeakMap(); class SecureModule { constructor() { privateData.set(this, { apiKey: 'secret', internalState: {} }); } getPrivateData() { return privateData.get(this); } } ``` ### 5. Dependency Injection No globals. Everything injected through constructor. ```javascript class GameModule extends Module { constructor(name, dependencies, config) { super(name, ['eventBus', 'renderer']); // Dependencies injected, not accessed globally this._eventBus = dependencies.eventBus; this._renderer = dependencies.renderer; this._config = config; } } ``` ## ๐Ÿ”„ Module Lifecycle ``` 1. REGISTRATION โ†’ Application.js modules array 2. LOADING โ†’ ModuleLoader imports class 3. INSTANTIATION โ†’ new Module(name, deps, config) 4. INITIALIZATION โ†’ module.init() called 5. READY โ†’ Module emits 'ready' event 6. DESTRUCTION โ†’ module.destroy() on cleanup ``` ## ๐Ÿ“ฆ System Components ### Core Layer (`src/core/`) **Module.js** - Abstract base class - WeakMap private state - Lifecycle management (init/destroy) - State validation - Abstract enforcement **EventBus.js** - Event communication - Module registration required - Event history tracking - Cross-module isolation - Memory leak prevention **ModuleLoader.js** - Dependency injection - Topological sort for dependencies - Circular dependency detection - Proper initialization order - Dynamic import system **Router.js** - Navigation system - Route guards - Middleware execution - State management - History integration **Application.js** - Bootstrap system - Auto-initialization - Module registration - Lifecycle coordination - Debug panel ### DRS Layer (`src/DRS/`) **Exercise Modules** (`exercise-modules/`) - VocabularyModule - Flashcard spaced repetition - TextAnalysisModule - AI text comprehension - GrammarAnalysisModule - AI grammar correction - TranslationModule - AI translation validation - OpenResponseModule - Free-form AI evaluation **Services** (`services/`) - IAEngine - Multi-provider AI system - LLMValidator - Answer validation - ContentLoader - Content generation - ProgressTracker - Progress management - PrerequisiteEngine - Prerequisite checking **Interfaces** (`interfaces/`) - StrictInterface - Base enforcement class - ProgressItemInterface - Progress tracking contract - ProgressSystemInterface - Progress system contract - DRSExerciseInterface - Exercise module contract ### Games Layer (`src/games/`) Independent game modules for entertainment (NOT part of DRS). - FlashcardLearning.js - Standalone flashcard game - Future games... ## ๐Ÿšซ Separation Rules ### DRS vs Games - NEVER MIX **DRS** = Educational exercises with strict interfaces **Games** = Entertainment with different architecture ```javascript // โŒ FORBIDDEN - DRS importing games import FlashcardLearning from '../games/FlashcardLearning.js'; // โœ… CORRECT - DRS uses its own modules import VocabularyModule from './exercise-modules/VocabularyModule.js'; ``` ## ๐Ÿ”’ Security Layers 1. **Object.seal()** - Prevents property addition/deletion 2. **Object.freeze()** - Prevents prototype modification 3. **WeakMap** - Internal state hidden 4. **Abstract enforcement** - Missing methods throw errors 5. **Validation at boundaries** - All inputs validated ## ๐Ÿ“Š Data Flow ``` User Action โ†“ UI Component โ†“ Event Emission (EventBus) โ†“ Module Event Handler โ†“ Business Logic โ†“ State Update โ†“ Event Emission (state changed) โ†“ UI Update ``` ## ๐ŸŽฏ Module Types ### 1. Core Modules System-level functionality. Never modify these. ### 2. Game Modules Entertainment-focused, extend Module base class. ### 3. DRS Exercise Modules Educational exercises, implement DRSExerciseInterface. ### 4. Service Modules Support functionality (AI, progress, content). ### 5. UI Components Reusable interface elements (future phase). ## โšก Performance Targets - **<100ms** module loading time - **<50ms** event propagation time - **<200ms** application startup time - **Zero** memory leaks in module lifecycle ## ๐Ÿงช Testing Strategy 1. **Unit Tests** - Individual module behavior 2. **Integration Tests** - Module communication via EventBus 3. **Interface Tests** - Contract compliance (ImplementationValidator) 4. **E2E Tests** - Complete user flows ## ๐Ÿ“‹ Architecture Checklist For every new feature: - [ ] Single responsibility maintained - [ ] EventBus for all communication - [ ] No direct module dependencies - [ ] Proper dependency injection - [ ] Object.seal() applied - [ ] Abstract methods implemented - [ ] Lifecycle methods complete - [ ] Memory cleanup in destroy() - [ ] Interface compliance validated - [ ] No global variables used ## ๐Ÿ” Debug Tools ```javascript // Application status window.app.getStatus() // Module inspection window.app.getCore().moduleLoader.getStatus() // Event history window.app.getCore().eventBus.getEventHistory() // Navigate programmatically window.app.getCore().router.navigate('/path') ``` ## ๐Ÿšจ Common Violations 1. **Direct module access** โ†’ Use EventBus 2. **Global variables** โ†’ Use dependency injection 3. **Mixed responsibilities** โ†’ Split into separate modules 4. **No cleanup** โ†’ Implement destroy() properly 5. **Hardcoded dependencies** โ†’ Declare in constructor 6. **Missing validation** โ†’ Validate all inputs 7. **Modifying core** โ†’ Extend, don't modify ## ๐Ÿ“– Further Reading - `docs/creating-new-module.md` - Module creation guide - `docs/interfaces.md` - Interface system details - `docs/progress-system.md` - Progress tracking guide - `README.md` - Project overview