# Middleware Documentation

## Current Implementation

### How Middleware Works

The framework implements route-specific middleware through OpenAPI configuration. Middleware executes sequentially before controller actions using dynamic imports and Promise-based execution.

**Current Architecture Issue**: Middleware logic is embedded directly in the ExpressServerImplementation class, making it tightly coupled and harder to maintain.

**Desired Architecture**: Separate middleware functionality into a dedicated `MiddlewareAdapter` class (see forge implementation: `express_server_adapter.ts:22`, `middleware_adapter.ts`).

## Improved Architecture Pattern (From Forge)

### Separation of Concerns

The forge implementation demonstrates proper separation:

```typescript
// express_server_adapter.ts:22
export class ExpressServerAdapter extends ServerAdapter {
    constructor(
        private server: ReturnType<typeof express>,
        private manager: ComponentManager,
        private htmlRender: IHTMLRender,
        private api_adapter: ApiAdapter,
        private middleware_adapter: MiddlewareAdapter  // Injected dependency
    ) {
        super()
    }
```

### Middleware Adapter Interface

```typescript
// middleware_adapter.ts:19
async handleMiddleware(req: any, reply: any, route: IRoute, request_data: RequestData, callback: Callback): Promise<any>
```

### Execution Flow in Server Adapter

```typescript
// express_server_adapter.ts:107-118
try {
    await new Promise((resolve: any, reject: any) => {
        this.middleware_adapter.handleMiddleware(req, res, route, request_data, resolve).catch(reject)
    })
} catch(e) {
    console.log('Error in middleware', e)
    res.status(500).send(`
        <h1>500 Internal Server Error</h1>
        <pre>${e}</pre>
    `)
    return
}
```

### Middleware Adapter Implementation Features

#### Component-Based Middleware (`middleware_adapter.ts:20-26`)
```typescript
let components = await this.manager.getLayoutComponents(route)
let middleware_stack = await Promise.all(components.map(async (component) => {
    const middleware = [ ...(component.middleware||[]), ...(component.middlewares||[]) ]
    return middleware 
}))
const layout_middlewares = middleware_stack.flat() || []
```

#### Sequential Execution with Deduplication (`middleware_adapter.ts:52-76`)
```typescript
private runMiddleware<K>(middleware: K[], req: any, reply: any, callback: Callback): void {
    middleware = this.dedupe(middleware)  // Remove duplicates
    let index = 0;
    
    let next = () => {
        if (index >= middleware.length) {
            callback()
            return
        }
        const mw = middleware[index]
        index++
        if (typeof mw === 'function') {
            if(!reply.sent)
                mw(req, reply, next)
        } else {
            if (!reply.sent)
                next()
        }
    }
    next()
}
```

#### Layout + View Middleware Support (`middleware_adapter.ts:38-47`)
- **Layout Middleware**: Executed first from layout components
- **View Middleware**: Executed second from view components
- Both support `middleware` and `middlewares` array properties

---

## Current Server Implementation (Needs Refactoring)

### Configuration & Structure

#### Server Configuration
```typescript
// ServerOptions interface
interface ServerOptions {
    middleware_path?: string; // Optional absolute path to middleware directory
    controllers_base_path: string; // Fallback path if middleware_path not set
}
```

#### OpenAPI Route Configuration
```yaml
# Middleware assigned per route using x-middleware array
/user/{id}:
  get:
    x-controller: controllers/user.controller
    x-action: get
    x-middleware: 
    - user/auth           # Default export only
    - auth:*              # All exported functions
    - auth:default,cookie,parsing  # Specific functions
```

#### Module-Level Middleware (Implementation Required First)

> **⚠️ Implementation Required**: Module support does not currently exist in this server implementation. The module system exists in the forge project but needs to be ported to support module-level middleware.

**Planned Module Configuration with Top-Level BasePath**
```yaml
# This functionality requires implementing module support first
openapi: 3.0.0
info:
  title: My API
  version: 1.0.0

basePath: "/api"              # Top-level basePath applied to ALL routes

module:
  users:
    basePath: "/users"        # Module basePath (combined with top-level)
    x-middleware:             # Module-level middleware (NOT YET SUPPORTED)
      - auth                  # Applied to all routes in this module
      - logging:request       # Applied to all routes in this module
    paths:
      "/":                    # Becomes /api/users/
        get:
          x-controller: controllers/user.controller
          x-action: getAll
          x-middleware:       # Route-specific middleware
            - validation:users  # Combined with module middleware
      "/{id}":                # Becomes /api/users/{id}
        get:
          x-controller: controllers/user.controller
          x-action: get
          x-middleware:
            - validation:user-id
  posts:
    basePath: "/posts"        # Becomes /api/posts/*
    paths:
      "/":
        get:
          x-controller: controllers/post.controller
          x-action: getAll

# Direct paths also get top-level basePath
paths:
  "/health":                  # Becomes /api/health
    get:
      x-controller: controllers/health.controller
      x-action: check
```

**Implementation Requirements**:
1. **Top-Level BasePath Support**: Add support for top-level `basePath` configuration
   - Parse top-level `basePath` from OpenAPI config
   - Apply to all routes (both direct paths and module-generated paths)
2. **OpenAPI Parser Extension**: Add module parsing support (see `forge/src/parser/openapi.ts:19-61`)
   - Parse module configurations with `basePath` and module-level `x-middleware`
   - Inherit module middleware to all routes within the module
   - Flatten modules into regular `paths` structure for easier processing
3. **Route Normalization**: Implement module-to-paths normalization (`forge/src/parser/openapi.ts:94-123`)
   - Combine top-level basePath + module basePath + route path
   - Combine module routes with direct path routes
   - Write all routes back to standard `config.paths[path][method]` structure
   - Delete `config.modules` section after normalization
4. **Middleware Inheritance**: During module parsing, prepend module middleware to route middleware
5. **Flat Route Processing**: Current `ExpressServerImplementation` can remain unchanged since routes are flattened

**Module Normalization Example**:
```yaml
# Input: Configuration with top-level basePath and modules
basePath: "/api"                    # Top-level basePath

module:
  users:
    basePath: "/users"              # Module basePath
    x-middleware: [auth, logging:request]
    paths:
      "/": 
        get:
          x-controller: controllers/user.controller
          x-action: getAll
          x-middleware: [validation:users]
      "/{id}":
        get:
          x-controller: controllers/user.controller
          x-action: get

paths:
  "/health":                        # Direct path
    get:
      x-controller: controllers/health.controller
      x-action: check

# Output: Normalized to standard paths structure
paths:
  "/api/users/":                    # top-level + module + route
    get:
      x-controller: controllers/user.controller
      x-action: getAll
      x-middleware: [auth, logging:request, validation:users]  # Module middleware prepended
  "/api/users/{id}":                # top-level + module + route
    get:
      x-controller: controllers/user.controller
      x-action: get
      x-middleware: [auth, logging:request]  # Module middleware inherited
  "/api/health":                    # top-level + direct path
    get:
      x-controller: controllers/health.controller
      x-action: check
```

**Planned Module Middleware Features**:
- All routes within a module inherit the module's `x-middleware`
- Module middleware is prepended to route-specific middleware
- Module middleware applies to every path within that module
- Nested modules inherit parent module middleware (when supported)

#### Middleware Function Structure

**Default Export (Current Behavior)**
```typescript
// auth.ts - uses default export only
export default function UserAuth(req: any, res: any, next: any) {
    // Middleware logic here
    next();
}
```

**Multiple Function Exports (Extended Behavior)**
```typescript
// auth.ts - multiple middleware functions
export default function UserAuth(req: any, res: any, next: any) {
    // Default authentication
    next();
}

export function cookie(req: any, res: any, next: any) {
    // Cookie handling middleware
    next();
}

export function parsing(req: any, res: any, next: any) {
    // Request parsing middleware
    next();
}
```

#### Middleware Resolution Patterns

| Pattern | Behavior | Example |
|---------|----------|---------|
| `auth` | Load default export only | `middleware_module.default` |
| `auth:*` | Load all exported functions | `Object.values(middleware_module).filter(fn => typeof fn === 'function')` |
| `auth:default,cookie,parsing` | Load specific named functions | `[middleware_module.default, middleware_module.cookie, middleware_module.parsing]` |

#### Extended Middleware Examples

**Example 1: Using all functions from a middleware file**
```yaml
x-middleware:
  - auth:*  # Executes all exported functions in order: default, cookie, parsing
```

**Example 2: Selective function execution**
```yaml
x-middleware:
  - auth:cookie,parsing  # Only executes cookie and parsing functions, skips default
```

**Example 3: Mixed middleware patterns**
```yaml
x-middleware:
  - logging               # Default export only
  - auth:*               # All functions from auth.ts
  - validation:schema    # Only schema function from validation.ts
  - security:default,cors # Default and cors functions from security.ts
```

**Execution Order**: Functions execute in the exact order specified:
1. `logging.default`
2. `auth.default`, `auth.cookie`, `auth.parsing` (in export order)
3. `validation.schema`
4. `security.default`, `security.cors`

### Execution Flow

1. **Route Matching**: Request matches OpenAPI route definition
2. **Middleware Extraction**: Extract middleware from route configuration:
   - **Current**: Only route-level `x-middleware` from OpenAPI route definition
   - **Future**: Module middleware consolidation when module support is added
3. **Middleware Resolution**: Each middleware in the array is resolved:
   - **Path Parsing**: Split middleware string on `:` to separate file path from function selector
   - **File Resolution**: `(middleware_path || controllers_base_path) + filePath`
   - **Dynamic Import**: `await import(middleware_full_path)`
   - **Function Extraction**: Based on pattern:
     - `auth` → `[middleware_module.default]` (validate is function)
     - `auth:*` → `Object.values(middleware_module).filter(fn => typeof fn === 'function')`
     - `auth:default,cookie,parsing` → `[middleware_module.default, middleware_module.cookie, middleware_module.parsing]` (validate each is function)
4. **Function Flattening**: All resolved functions are flattened into a single execution array
5. **Sequential Execution**: For each middleware function:
   - Wrapped in Promise for async handling
   - Called with `(req, res, next)` parameters
   - Must complete before next middleware executes
6. **Error Handling**: Any middleware error halts execution with 500 response
   - **File Not Found**: Middleware file doesn't exist at resolved path
   - **Function Not Found**: Specified function doesn't exist in module
   - **Runtime Errors**: Middleware throws exception or calls `next(error)`
7. **Controller Execution**: After all middleware succeeds, controller action runs

### Current Implementation Details

#### Path Resolution (`ExpressServerImplentation.ts:183-211`)
```typescript
// Use middleware_path if provided, otherwise fall back to controller_base
const middleware_base = this.options.middleware_path || controller_base;
const middleware_full_path = path.resolve(process.cwd(), path.join(middleware_base, `${middlewarePath}`));
```

#### Middleware Execution Loop (`ExpressServerImplentation.ts:183-211`)

The middleware execution follows this detailed process for each middleware in the `x-middleware` array:

```typescript
for (const middlewarePath of middleware) {
    try {
        // 1. Path Resolution
        // Use middleware_path if provided, otherwise fall back to controller_base
        const middleware_base = this.options.middleware_path || controller_base;
        const middleware_full_path = path.resolve(process.cwd(), path.join(middleware_base, `${middlewarePath}`));
        
        // 2. Dynamic Module Import
        const middleware_module = (await import(middleware_full_path));
        const middleware_function = middleware_module.default;
        
        // 3. Function Validation & Execution
        if (middleware_function && typeof middleware_function === "function") {
            await new Promise<void>((resolve, reject) => {
                middleware_function(req, res, (error?: any) => {
                    if (error) {
                        reject(error);
                    } else {
                        resolve();
                    }
                });
            });
        }
    } catch (error) {
        // 4. Error Handling
        console.error(`Middleware execution failed for ${middlewarePath}:`, error);
        res.status(500).send({
            error: true,
            message: `Middleware execution failed: ${middlewarePath}`,
            statusCode: 500,
        });
        return // Stops execution immediately
    }
}
```

##### Step-by-Step Breakdown:

**1. Path Resolution**
- Constructs absolute path using `middleware_path` option or falls back to `controller_base`
- Uses `path.resolve(process.cwd(), path.join(base, middlewarePath))`
- Example: `middlewarePath: "user/auth"` → `/absolute/path/to/middleware/user/auth`

**2. Dynamic Module Import**
- Uses ES6 dynamic import: `await import(middleware_full_path)`
- Automatically resolves file extensions (`.js`, `.ts`, etc.)
- Extracts default export: `middleware_module.default`

**3. Function Validation & Execution**
- Validates middleware is a function before execution
- Wraps execution in Promise for async control flow
- Provides Express-style callback: `(error?: any) => void`
- Middleware must call callback to continue: `next()` or `next(error)`

**4. Error Handling**
- **Import Errors**: Module not found, syntax errors, etc.
- **Runtime Errors**: Middleware throws exception or calls `next(error)`
- **Response**: Sets 500 status with structured error message
- **Flow Control**: `return` statement halts entire request processing

##### Execution Characteristics:

- **Sequential**: Middleware executes one at a time, not in parallel
- **Blocking**: Each middleware must complete before next one starts  
- **Fail-Fast**: First error stops all subsequent middleware and controller execution
- **No Caching**: Modules are imported fresh on every request
- **Stateless**: No shared state between middleware executions

#### Error Response Format
```json
{
    "error": true,
    "message": "Middleware execution failed: user/auth",
    "statusCode": 500
}
```

#### Extended Error Handling

**File Not Found Errors**
```json
{
    "error": true,
    "message": "Middleware file not found: auth.ts",
    "statusCode": 500
}
```

**Function Not Found Errors**
```json
{
    "error": true,
    "message": "Middleware function 'cookie' not found in auth.ts",
    "statusCode": 500
}
```

**Multiple Function Errors**
```json
{
    "error": true,
    "message": "Middleware functions 'cookie,parsing' not found in auth.ts",
    "statusCode": 500
}
```

**Non-Function Export Errors**
```json
{
    "error": true,
    "message": "Middleware export 'cookie' in auth.ts is not a function",
    "statusCode": 500
}
```

**Multiple Non-Function Errors**
```json
{
    "error": true,
    "message": "Middleware exports 'cookie,config' in auth.ts are not functions",
    "statusCode": 500
}
```

**Default Export Missing**
```json
{
    "error": true,
    "message": "Middleware file auth.ts has no default export",
    "statusCode": 500
}
```

**Default Export Not Function**
```json
{
    "error": true,
    "message": "Middleware default export in auth.ts is not a function",
    "statusCode": 500
}
```

**Validation Rules**
- **File Resolution**: Must throw error if middleware file doesn't exist at resolved path
- **Function Resolution**: Must throw error if any specified function doesn't exist in module
- **Function Type Validation**: Must throw error if any resolved export is not a function
- **Default Export Validation**: 
  - `auth` pattern must fail if module has no default export or if default export is not a function
  - `auth:default` pattern must fail if module has no default export or if default export is not a function
- **Wildcard Validation**: `auth:*` should only fail if file doesn't exist, not if no functions found

### Current Limitations

- **Route-Specific Only**: No global middleware support
- **Basic Error Handling**: Generic 500 responses for all middleware failures
- **No Dependency Injection**: Middleware cannot access IoC container
- **Simple Path Resolution**: No middleware aliases or advanced routing
- **No Caching**: Middleware modules imported on every request
- **Limited Context**: No framework context or shared state between middleware