Class_generator/CLAUDE.md
StillHammer 38920cc858 Complete architectural rewrite with ultra-modular system
Major Changes:
- Moved legacy system to Legacy/ folder for archival
- Built new modular architecture with strict separation of concerns
- Created core system: Module, EventBus, ModuleLoader, Router
- Added Application bootstrap with auto-start functionality
- Implemented development server with ES6 modules support
- Created comprehensive documentation and project context
- Converted SBS-7-8 content to JSON format
- Copied all legacy games and content to new structure

New Architecture Features:
- Sealed modules with WeakMap private data
- Strict dependency injection system
- Event-driven communication only
- Inviolable responsibility patterns
- Auto-initialization without commands
- Component-based UI foundation ready

Technical Stack:
- Vanilla JS/HTML/CSS only
- ES6 modules with proper imports/exports
- HTTP development server (no file:// protocol)
- Modular CSS with component scoping
- Comprehensive error handling and debugging

Ready for Phase 2: Converting legacy modules to new architecture

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-22 07:08:39 +08:00

8.3 KiB

CLAUDE.md - Project Context & Instructions

📋 Project Overview

Class Generator 2.0 - Complete rewrite of educational games platform with ultra-modular architecture.

🎯 Current Mission

Building a bulletproof modular system with strict separation of concerns using vanilla JavaScript, HTML, and CSS. The architecture enforces inviolable responsibility patterns with sealed modules and dependency injection.

🏗️ Architecture Status

PHASE 1 COMPLETED - Core foundation built with rigorous architectural patterns:

  • Module.js - Abstract base class with WeakMap privates and sealed instances
  • EventBus.js - Strict event system with validation and module registration
  • ModuleLoader.js - Dependency injection with proper initialization order
  • Router.js - Navigation with guards, middleware, and state management
  • Application.js - Auto-bootstrap system with lifecycle management
  • Development Server - HTTP server with ES6 modules and CORS support

🔥 Critical Requirements

Architecture Principles (NON-NEGOTIABLE)

  1. Inviolable Responsibility - Each module has exactly one purpose
  2. Zero Direct Dependencies - All communication via EventBus only
  3. Sealed Instances - Modules cannot be modified after creation
  4. Private State - Internal data completely inaccessible via WeakMap
  5. Contract Enforcement - Abstract methods must be implemented
  6. Dependency Injection - No globals, everything injected through constructor

Technical Constraints

  • Vanilla JS/HTML/CSS only - No frameworks
  • ES6 Modules - Import/export syntax required
  • HTTP Protocol - Never file:// (use development server)
  • Modular CSS - Component-scoped styling
  • Event-Driven - No direct module coupling

🚀 Development Workflow

Starting the System

# Option 1: Windows batch file
start.bat

# Option 2: Node.js directly
node server.js

# Option 3: NPM scripts
npm start

Access: http://localhost:3000

Development Server Features

  • ES6 modules support
  • CORS enabled for online communication
  • Proper MIME types for all file formats
  • Development-friendly caching (assets cached, HTML not cached)
  • Graceful error handling with styled 404 pages

📁 Project Structure

├── src/
│   ├── core/              # COMPLETED - Core system (sealed)
│   │   ├── Module.js      # Abstract base class
│   │   ├── EventBus.js    # Event communication system
│   │   ├── ModuleLoader.js # Dependency injection
│   │   ├── Router.js      # Navigation system
│   │   └── index.js       # Core exports
│   ├── components/        # TODO - UI components
│   ├── games/            # TODO - Game modules
│   ├── content/          # TODO - Content system
│   ├── styles/           # COMPLETED - Modular CSS
│   │   ├── base.css      # Foundation styles
│   │   └── components.css # Reusable UI components
│   └── Application.js    # COMPLETED - Bootstrap system
├── Legacy/               # Archived old system
├── index.html           # COMPLETED - Entry point
├── server.js            # COMPLETED - Development server
├── start.bat            # COMPLETED - Quick start script
├── package.json         # COMPLETED - Node.js config
└── README.md            # COMPLETED - Documentation

🎮 Creating New Modules

Game Module Template

import Module from '../core/Module.js';

class GameName extends Module {
    constructor(name, dependencies, config) {
        super(name, ['eventBus']); // Declare dependencies

        // Validate dependencies
        if (!dependencies.eventBus) {
            throw new Error('GameName requires EventBus dependency');
        }

        this._eventBus = dependencies.eventBus;
        this._config = config;

        Object.seal(this); // Prevent modification
    }

    async init() {
        this._validateNotDestroyed();

        // Set up event listeners
        this._eventBus.on('game:start', this._handleStart.bind(this), this.name);

        this._setInitialized();
    }

    async destroy() {
        this._validateNotDestroyed();

        // Cleanup logic here

        this._setDestroyed();
    }

    // Private methods
    _handleStart(event) {
        this._validateInitialized();
        // Game logic here
    }
}

export default GameName;

Registration in Application.js

modules: [
    {
        name: 'gameName',
        path: './games/GameName.js',
        dependencies: ['eventBus'],
        config: { difficulty: 'medium' }
    }
]

🔍 Debugging & Monitoring

Debug Panel (F12 to toggle)

  • System status and uptime
  • Loaded modules list
  • Event history
  • Module registration status

Console Access

window.app.getStatus()                    // Application status
window.app.getCore().eventBus            // EventBus instance
window.app.getCore().moduleLoader        // ModuleLoader instance
window.app.getCore().router              // Router instance

Common Commands

# Check module status
window.app.getCore().moduleLoader.getStatus()

# View event history
window.app.getCore().eventBus.getEventHistory()

# Navigate programmatically
window.app.getCore().router.navigate('/games')

🚧 Next Development Phase

Immediate Tasks (PHASE 2)

  1. Component-based UI System - Reusable UI components with scoped CSS
  2. Example Game Module - Simple memory game to validate architecture
  3. Content System Integration - Port content loading from Legacy
  4. Testing Framework - Validate module contracts and event flow

Known Legacy Issues to Fix

31 bug fixes and improvements from the old system:

  • Grammar game functionality issues
  • Word Storm duration and difficulty problems
  • Memory card display issues
  • Adventure game text repetition
  • UI alignment and feedback issues
  • Performance optimizations needed

🔒 Security & Rigidity Enforcement

Module Protection Layers

  1. Object.seal() - Prevents property addition/deletion
  2. Object.freeze() - Prevents prototype modification
  3. WeakMap privates - Internal state completely hidden
  4. Abstract enforcement - Missing methods throw errors
  5. Validation at boundaries - All inputs validated

Error Messages

The system provides explicit error messages for violations:

  • "Module is abstract and cannot be instantiated directly"
  • "Module name is required and must be a string"
  • "EventBus requires module registration before use"
  • "Module must be initialized before use"

📝 Development Guidelines

DO's

  • Always extend Module base class for game modules
  • Use EventBus for all inter-module communication
  • Validate dependencies in constructor
  • Call _setInitialized() after successful init
  • Use private methods with underscore prefix
  • Seal objects to prevent modification

DON'Ts

  • Never access another module's internals directly
  • Never use global variables for communication
  • Never modify Module base class or core system
  • Never skip dependency validation
  • Never use file:// protocol (always use HTTP server)

🎯 Success Metrics

Architecture Quality

  • Zero direct coupling between modules
  • 100% sealed instances - no external modification possible
  • Complete test coverage of module contracts
  • Event-driven communication only

Performance Targets

  • <100ms module loading time
  • <50ms event propagation time
  • <200ms application startup time
  • Zero memory leaks in module lifecycle

🔄 Migration Notes

From Legacy System

The Legacy/ folder contains the complete old system. Key architectural changes:

Old Approach:

  • Global variables and direct coupling
  • Manual module registration
  • CSS modifications in global files
  • Mixed responsibilities in single files

New Approach:

  • Strict modules with dependency injection
  • Automatic loading with dependency resolution
  • Component-scoped CSS injection
  • Single responsibility per module

Data Migration

  • Content modules need adaptation to new Module base class
  • Game logic needs EventBus integration
  • CSS needs component scoping
  • Configuration needs dependency declaration

This is a high-quality, maintainable system built for educational software that will scale.