> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wsx.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> Understanding how WSX works under the hood

## Overview

WSX is designed with a modular architecture that separates concerns and enables easy integration with different frameworks. This document explains the core components and how they work together.

## Core Components

```mermaid theme={null}
flowchart TD
    subgraph Browser["🌐 Browser Environment"]
        UI[User Interaction]
        WSXClient[WSX Client Library]
        DOM[DOM Elements]
        
        UI --> WSXClient
        WSXClient --> DOM
    end
    
    subgraph Server["🖥️ Server Environment"]
        WSXServer[WSX Server Core]
        Handlers[Request Handlers]
        Adapter[Framework Adapter]
        Framework[Express/Hono/Custom]
        
        WSXServer --> Handlers
        WSXServer --> Adapter
        Adapter --> Framework
    end
    
    WSXClient <-->|WebSocket| WSXServer
    
    subgraph Flow["📋 Request Flow"]
        direction LR
        A[DOM Event] --> B[Process Triggers]
        B --> C[Build Request]
        C --> D[Send WebSocket]
        D --> E[Route Handler]
        E --> F[Generate Response]
        F --> G[Update DOM]
        F --> H[Broadcast OOB]
    end
    
    style UI fill:#4fc3f7,stroke:#0277bd,stroke-width:2px,color:#000
    style WSXClient fill:#42a5f5,stroke:#1565c0,stroke-width:2px,color:#fff
    style DOM fill:#29b6f6,stroke:#0277bd,stroke-width:2px,color:#000
    style WSXServer fill:#ab47bc,stroke:#7b1fa2,stroke-width:2px,color:#fff
    style Handlers fill:#66bb6a,stroke:#388e3c,stroke-width:2px,color:#000
    style Adapter fill:#9ccc65,stroke:#689f38,stroke-width:2px,color:#000
    style Framework fill:#ffb74d,stroke:#f57c00,stroke-width:2px,color:#000
    style A fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
    style B fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
    style C fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
    style D fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
    style E fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
    style F fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
    style G fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
    style H fill:#90caf9,stroke:#1976d2,stroke-width:2px,color:#000
```

### WSX Client

The browser-side JavaScript library that handles:

* WebSocket connection management
* DOM event listening and processing
* HTML swapping and updates
* Reconnection logic
* Trigger processing (throttling, debouncing, etc.)

### WSX Server

The Node.js server component that manages:

* WebSocket connections
* Request routing and handling
* Response generation
* Broadcasting to clients
* Connection lifecycle management

### WSX Adapter

Framework-specific adapters that provide:

* WebSocket server setup
* Framework integration
* Request/response handling
* Connection management hooks

## Request Flow

Here's how a typical WSX request flows through the system:

```mermaid theme={null}
sequenceDiagram
    participant Client as Browser
    participant WSXClient as WSX Client
    participant Server as WSX Server
    participant Handler as Handler Function
    participant Clients as Other Clients

    Client->>WSXClient: User clicks button
    WSXClient->>WSXClient: Process triggers
    WSXClient->>Server: Send WebSocket message
    Server->>Handler: Route to handler
    Handler->>Server: Return response
    Server->>WSXClient: Send response
    WSXClient->>Client: Update DOM
    Server->>Clients: Broadcast (if needed)
```

## Component Details

### WSX Client Architecture

The client is built around several key classes:

#### WSX Main Class

* Manages WebSocket connection
* Handles reconnection logic
* Processes incoming messages
* Manages pending requests
* Dispatches JSON channel events and binary stream payloads

#### Event System

* Listens for DOM events
* Processes trigger specifications
* Handles modifier logic (throttle, debounce, etc.)
* Manages element state

#### Swap Engine

* Parses swap specifications
* Handles DOM manipulation
* Manages timing and animation
* Processes out-of-band updates

### WSX Server Architecture

The server uses a clean, event-driven architecture:

#### WSXServer Class

* Central connection manager
* Handler registration and routing
* Broadcasting capabilities
* Connection lifecycle management
* JSON channel routing and binary stream fan-out helpers

#### Connection Management

* Each WebSocket connection is wrapped in a `WSXConnection` object
* Connections are tracked in a Map for efficient lookup
* Session data can be attached to connections

#### Handler System

* Handlers are registered with names or as catch-all functions
* Handlers receive request and connection objects
* Handlers can return single responses or arrays

### Adapter System

Adapters provide framework-specific integration:

#### Express Adapter

```javascript theme={null}
class ExpressAdapter implements WSXServerAdapter {
  setupWebSocket(path, onMessage) {
    // Sets up WebSocket server with Express
  }
  
  getApp() {
    // Returns Express app instance
  }
}
```

#### Hono Adapter

```javascript theme={null}
class HonoAdapter implements WSXServerAdapter {
  setupWebSocket(path, onMessage) {
    // Sets up WebSocket with Hono
  }
  
  getApp() {
    // Returns Hono app instance
  }
}
```

## Data Flow

### Request Processing

1. **Client Event**: User interacts with an element that has WSX attributes
2. **Trigger Processing**: Client evaluates trigger conditions and modifiers
3. **Request Construction**: Client builds a WSXRequest object
4. **WebSocket Send**: Request is serialized and sent over WebSocket
5. **Server Routing**: Server routes request to appropriate handler
6. **Handler Execution**: Handler processes request and returns response
7. **Response Processing**: Server processes response and sends back to client(s)
8. **DOM Update**: Client applies response to DOM using swap specifications

### Data Channels

WSX multiplexes three complementary payload types over the same WebSocket:

* **HTML responses** drive hypermedia swaps produced by `wsx.on()` handlers
* **JSON messages** flow through `wsx.onJson()` on the server and
  `wsx.onJson()`/`wsx:json` events on the client
* **Binary streams** move audio, files, or sensor data via `wsx.sendStream()`
  and `wsx.onStream()` APIs

Mix the channels as needed—render HTML updates, broadcast presence over JSON,
then stream raw media without opening extra sockets.

### Broadcasting

WSX supports several broadcasting patterns:

#### Broadcast to All

```javascript theme={null}
wsx.broadcast('#status', '<div>Server updated</div>');
```

#### Send to Specific Connection

```javascript theme={null}
wsx.sendToConnection(connectionId, '#notification', '<div>Personal message</div>');
```

#### Out-of-Band Updates

```javascript theme={null}
return {
  id: request.id,
  target: request.target,
  html: '<div>Main content</div>',
  oob: [
    { target: '#sidebar', html: '<div>Sidebar update</div>' },
    { target: '#header', html: '<div>Header update</div>' }
  ]
};
```

## Security Considerations

### Connection Security

* All WebSocket connections are validated
* Connection IDs are generated securely
* Session data is isolated per connection

### Input Validation

* All client requests should be validated on the server
* HTML content should be sanitized when necessary
* Rate limiting can be implemented at the handler level

### CORS and Origins

* WebSocket connections respect same-origin policies
* Configure allowed origins in production environments
* Use secure WebSocket (wss\://) in production

## Performance Characteristics

### Client Performance

* Minimal JavaScript footprint (\~15KB gzipped)
* Efficient DOM manipulation
* Smart reconnection logic
* Optimized event handling

### Server Performance

* Lightweight connection management
* Fast request routing
* Efficient broadcasting
* Minimal memory footprint per connection

### Scalability

* Horizontal scaling through load balancing
* Connection state is per-server instance
* Broadcasting can be extended with Redis/message queues

## Extension Points

### Custom Adapters

Create adapters for other frameworks:

```javascript theme={null}
class CustomAdapter implements WSXServerAdapter {
  setupWebSocket(path, onMessage) {
    // Your WebSocket setup
  }
  
  getApp() {
    // Return your framework's app instance
  }
}
```

### Middleware

Add middleware to the request pipeline:

```javascript theme={null}
wsx.use((request, connection, next) => {
  // Authentication, logging, etc.
  return next();
});
```

### Custom Triggers

Extend the client with custom trigger types:

```javascript theme={null}
WSX.addTrigger('custom', (element, trigger, event) => {
  // Custom trigger logic
});
```

## Best Practices

### Architecture Patterns

1. **Handler Organization**: Group related handlers logically
2. **State Management**: Use connection session data for user state
3. **Error Handling**: Implement comprehensive error handling
4. **Broadcasting Strategy**: Use targeted broadcasting when possible

### Performance Optimization

1. **Connection Pooling**: Reuse connections efficiently
2. **Response Caching**: Cache responses when appropriate
3. **Batch Updates**: Use out-of-band updates for multiple DOM changes
4. **Resource Cleanup**: Properly clean up connections and timers

### Security Hardening

1. **Input Validation**: Validate all client inputs
2. **Rate Limiting**: Implement per-connection rate limits
3. **Content Security**: Sanitize HTML content
4. **Authentication**: Implement proper authentication flows

## Next Steps

Now that you understand WSX's architecture, explore:

<CardGroup cols={2}>
  <Card title="Connection Management" icon="link" href="/concepts/connections">
    Learn about managing WebSocket connections
  </Card>

  <Card title="Handler System" icon="code" href="/concepts/handlers">
    Understand how request handlers work
  </Card>

  <Card title="Custom Adapters" icon="plug" href="/frameworks/custom-adapter">
    Build adapters for other frameworks
  </Card>

  <Card title="Performance Guide" icon="gauge" href="/advanced/performance">
    Optimize your WSX applications
  </Card>
</CardGroup>
