# Angular Transformation Rules

This directory contains the transformation rule implementations that provide automated Angular code modernization capabilities. Each rule implements the `TransformRule` interface and coordinates with orchestrators to perform complex code transformations.

## Overview

Transformation rules are the entry point for automated code changes in the Angular Modernization Platform. They:

- **Analyze** source code for transformation opportunities
- **Validate** that transformations are safe and beneficial
- **Coordinate** with orchestrators for complex logic
- **Generate** transformed code with proper syntax and imports
- **Integrate** with the MCP `transform-code` tool

This document covers 8 of the 25 transform types. For the full list see `packages/plugin-angular/CLAUDE.md`.

## Rules

### 1. ConstructorToInjectRule

**File:** `constructor-to-inject.rule.ts`  
**ID:** `angular:constructor-to-inject`  
**Purpose:** Converts Angular constructor dependency injection to modern `inject()` function calls

**Configuration:**

```typescript
{
  "constructor-to-inject": {
    "enabled": true,
    "removeEmptyConstructors": true
  }
}
```

**When Applied:**

- Components, services, and directives with constructor injection
- Classes using Angular DI patterns
- Projects migrating to standalone components

**Benefits:**

- Modern Angular syntax (v14+)
- Better tree-shaking
- Simplified testing with dependency overrides
- Reduced boilerplate code

---

### 2. DependencyInjectionMigrationRule

**File:** `dependency-injection-migration.rule.ts`  
**ID:** `angular:dependency-injection-migration`  
**Purpose:** Modernizes legacy Angular DI patterns including string tokens and ReflectiveInjector

**Configuration:**

```typescript
{
  "dependency-injection-migration": {
    "enabled": true,
    "migrateStringTokens": true,
    "migrateReflectiveInjector": true
  }
}
```

**When Applied:**

- Code using `@Inject('string-token')` patterns
- Legacy `ReflectiveInjector` usage
- Projects upgrading from AngularJS or early Angular versions

**Benefits:**

- Type-safe dependency injection
- Better IDE support and refactoring
- Modern Angular patterns
- Improved maintainability

---

### 3. FacadePatternRule

**File:** `facade-pattern.rule.ts`  
**ID:** `angular:facade-pattern`  
**Purpose:** Extracts business logic from bloated components into dedicated facade services

**Configuration:**

```typescript
{
  "facade-pattern": {
    "enabled": true,
    "maxMethodsPerComponent": 10,
    "minComplexityScore": 5,
    "extractServices": true
  }
}
```

**When Applied:**

- Components with high method counts (>10 methods)
- Components mixing UI logic with business logic
- Large components violating Single Responsibility Principle

**Benefits:**

- Separation of concerns
- Improved testability
- Better code reusability
- Reduced component complexity
- Enhanced maintainability

---

### 4. FormModernizationRule

**File:** `form-modernization.rule.ts`  
**ID:** `angular:form-modernization`  
**Purpose:** Modernizes Angular forms from template-driven to reactive patterns

**Configuration:**

```typescript
{
  "form-modernization": {
    "enabled": true,
    "convertTemplateDriven": true,
    "addValidators": true,
    "preserveValidation": true
  }
}
```

**When Applied:**

- Components using template-driven forms (`ngForm`, `ngModel`)
- Forms requiring complex validation logic
- Projects standardizing on reactive forms

**Benefits:**

- Type-safe form handling
- Better testability
- Complex validation logic support
- Immutable form state management
- Enhanced performance with OnPush

---

### 5. InterfaceExtractionRule

**File:** `interface-extraction.rule.ts`  
**ID:** `angular:interface-extraction`  
**Purpose:** Extracts inline type literals into named interfaces for better code organization

**Configuration:**

```typescript
{
  "interface-extraction": {
    "enabled": true,
    "minComplexity": 3,
    "generateUniqueNames": true,
    "addToSeparateFile": false
  }
}
```

**When Applied:**

- Components with complex inline type literals
- Services with repeated type definitions
- Codebases needing better type organization

**Benefits:**

- Improved code readability
- Better type reusability
- Enhanced IDE support
- Easier refactoring
- Reduced code duplication

---

### 6. ConstructorInjectionTransformRule

**File:** `constructor-injection-transform.rule.ts`  
**ID:** `angular:constructor-injection-transform`  
**Purpose:** Converts manual service instantiation (`new Service()`) to proper `inject(Service)` calls

**Configuration:**

```typescript
{
  "constructor-injection-transform": {
    "enabled": true,
    "serviceSuffixes": ["Service", "Repository", "Client", "Store"],
    "handleComplexExpressions": true
  }
}
```

**When Applied:**

- Classes with manual service instantiation (`new HttpClient()`)
- Components violating Dependency Inversion Principle
- Codebases needing proper Angular DI patterns

**Benefits:**

- Proper dependency injection
- DIP compliance
- Better testability
- Improved maintainability
- Modern Angular patterns

---

### 7. ComponentInputsInterfaceExtractionRule

**File:** `component-inputs-interface-extraction.rule.ts`  
**ID:** `angular:component-inputs-interface-extraction`  
**Purpose:** Extracts component input properties into dedicated interfaces for better type safety

**Configuration:**

```typescript
{
  "component-inputs-interface-extraction": {
    "enabled": true,
    "minInputsThreshold": 3,
    "generateUniqueNames": true,
    "addToSeparateFile": false
  }
}
```

**When Applied:**

- Components with multiple `@Input()` properties
- Components needing better type organization
- Large components with complex input interfaces

**Benefits:**

- Improved type safety
- Better code organization
- Enhanced reusability
- Easier refactoring
- Reduced boilerplate

---

### 8. ServiceInjectionCleanupRule

**File:** `service-injection-cleanup.rule.ts`  
**ID:** `angular:service-injection-cleanup`  
**Purpose:** Converts pseudo-services (classes with manual instantiation) to proper Angular services

**Configuration:**

```typescript
{
  "service-injection-cleanup": {
    "enabled": true,
    "servicePatterns": ["Service$", "Client$", "Repository$"],
    "handleComplexExpressions": true
  }
}
```

**When Applied:**

- Classes with manual service instantiation patterns
- Components mixing service logic with UI logic
- Codebases needing proper service separation

**Benefits:**

- Proper service architecture
- Dependency injection compliance
- Better separation of concerns
- Improved testability
- Enhanced maintainability

## Architecture

### Rule-Orchestrator Pattern

Each transformation rule follows the **"thin rule, thick orchestrator"** pattern:

```
Rule (Thin Layer)
├── Configuration validation
├── High-level coordination
├── Result aggregation
└── Error handling

Orchestrator (Thick Layer)
├── AST analysis
├── Code generation
├── Import management
├── Syntax validation
└── Complex transformations
```

### Rule Interface

All rules implement the `TransformRule` interface:

```typescript
interface TransformRule {
  readonly id: string;
  readonly name: string;

  transform(context: TransformContext): Promise<TransformResult>;
}
```

### Transform Context

Rules receive a `TransformContext` with:

- `sourceFile`: The ts-morph SourceFile to transform
- `project`: The complete TypeScript project
- `api`: Public API for analysis tools
- `config`: Rule-specific configuration
- `transformationType`: The requested transformation type

### Transform Result

Rules return a `TransformResult` with:

- `modified`: Whether the file was changed
- `content`: The new file content (if modified)
- `additionalFiles`: Any new files created (facades, interfaces)
- `errors`: Any transformation errors encountered

## Usage

### Via MCP Tool

```bash
# Transform constructor injection
transform-code --filePath src/app/user.component.ts --transformation constructor-to-inject

# Extract interfaces
transform-code --filePath src/app/models.ts --transformation interface-extraction

# Apply facade pattern
transform-code --filePath src/app/user-list.component.ts --transformation facade-pattern
```

### Programmatic Usage

```typescript
import { AngularPlugin } from '@angular-modernizer/plugin-angular';

const plugin = new AngularPlugin();
const rules = plugin.getTransformRules();

const facadeRule = rules.find((rule) => rule.id === 'angular:facade-pattern');

const result = await facadeRule.transform({
  sourceFile,
  project,
  api: createPublicApi(),
  config: { 'facade-pattern': { maxMethodsPerComponent: 8 } },
  transformationType: 'facade-pattern',
});

if (result.modified) {
  console.log('Transformation applied:', result.content);
}
```

## Configuration

Rules are configured through the plugin configuration:

```typescript
const config = {
  transformations: {
    'constructor-to-inject': {
      enabled: true,
      removeEmptyConstructors: true,
    },
    'facade-pattern': {
      enabled: true,
      maxMethodsPerComponent: 10,
      minComplexityScore: 5,
    },
    // ... other rule configs
  },
};
```

## Testing

Each rule has comprehensive tests in `../../__tests__/transform-rules/` covering:

- **Happy Path**: Successful transformations with various inputs
- **Edge Cases**: Boundary conditions and complex scenarios
- **Error Handling**: Invalid inputs and transformation failures
- **Integration**: End-to-end transformation workflows
- **Configuration**: Different config options and their effects

## Error Handling

Rules handle errors gracefully:

- **Validation Errors**: Invalid source code or configurations
- **AST Errors**: Malformed TypeScript syntax
- **Generation Errors**: Failed code generation
- **Import Errors**: Missing or circular dependencies

Errors are reported in the `TransformResult.errors` array with detailed messages and suggestions.

## Contributing

When adding new transformation rules:

1. **Create the Rule**: Implement `TransformRule` interface in this directory
2. **Create the Orchestrator**: Add complex logic to `../orchestrators/`
3. **Add Tests**: Create comprehensive tests in `../../__tests__/transform-rules/`
4. **Update Documentation**: Add rule documentation to this README
5. **Update MCP**: Add the rule to the MCP transform-code tool
6. **Integration Test**: Verify end-to-end functionality

### Rule Template

```typescript
export class NewTransformationRule implements TransformRule {
  readonly id = 'angular:new-transformation';
  readonly name = 'New Transformation';

  async transform(context: TransformContext): Promise<TransformResult> {
    // Validate configuration
    const config = context.config[this.id] || {};

    // Use orchestrator for complex logic
    const orchestrator = new NewTransformationOrchestrator();
    const analysis = await orchestrator.analyze(context);

    if (!analysis.shouldTransform) {
      return { modified: false };
    }

    // Generate transformed code
    const result = await orchestrator.transform(context);

    return {
      modified: true,
      content: result.content,
      additionalFiles: result.additionalFiles || [],
    };
  }
}
```

## Performance Considerations

- Rules are designed to be fast and memory-efficient
- Large files are processed incrementally
- AST analysis is cached where possible
- Transformations are atomic (all-or-nothing)
- Memory usage scales with file complexity, not project size
