# @xcons/vite-plugin

> Development environment Vite plugin for XCon Studio widgets created with @xcons/widget package - Provides hot reload, debugging and breakpoint support

[![npm version](https://badge.fury.io/js/%40xcons%2Fvite-plugin.svg)](https://www.npmjs.com/package/@xcons/vite-plugin)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## ⚠️ Important Note

This plugin is designed **for development environment only**. It should not be used in production builds. The plugin's purpose is to provide:

- 🔥 **Hot Module Replacement (HMR)** - Auto-refresh on template and style changes
- 🐛 **Debugging Support** - Advanced debugging with source maps
- 🔍 **Breakpoint Support** - Set breakpoints in original source files
- ⚡ **Fast Development** - Instant code change preview

## 🚀 Quick Start

### Requirements

This plugin is developed for widgets created with the **@xcons/widget** package:

```bash
# First install the widget package
npm install @xcons/widget

# Then install the development plugin
npm install @xcons/vite-plugin --save-dev
```

### Basic Usage

**vite.config.ts** (Development Only)
```typescript
import { defineConfig } from 'vite';
import xconVitePlugin from '@xcons/vite-plugin';

export default defineConfig({
  plugins: [
    xconVitePlugin({
      // Development settings
      development: true,
      sourceMap: true,          // For debugging
      watchFiles: true,         // For hot reload
      showProcessedFiles: true  // Show processed files
    })
  ]
});
```

**Define Widget with @xcons/widget**
```typescript
import { Widget } from '@xcons/widget';

@Widget({
  selector: 'my-widget',
  templateUrl: './my-widget.component.html',  // HTML file
  styleUrls: ['./my-widget.component.css']
})
export class MyWidget {
  // Your widget logic
}
```

The plugin automatically:
- ✅ `templateUrl` → `template` (HTML content inlined)
- ✅ `styleUrls` → `styles` (CSS content inlined)
- ✅ **Hot Reload** - Auto-refresh on file changes
- ✅ **Source Maps** - Debugging and breakpoint support
- ✅ **Watch Mode** - Monitors template and style files

## ✨ Features

### 🔥 Hot Module Replacement (HMR)
- Template file changes → Auto widget refresh
- Style file changes → Instant style update
- Live preview without page reload

### 🐛 Advanced Debugging
- **Source Maps** - Access to original source files
- **Breakpoint Support** - Breakpoints in HTML/CSS files
- **Stack Trace** - Detailed stack trace for debugging
- **Console Mapping** - Logs show original file locations

### ⚡ Development Features
- 📄 **HTML Template Processing** - Converts `.html` files to inline templates
- 🎨 **Style Processing** - Converts CSS/SCSS/SASS/LESS files to inline styles array
- 🔍 **File Watching** - Auto-monitors template and style changes
- 🗺️ **Source Map Support** - Precise source map generation with magic-string
- 🔧 **TypeScript Support** - Full TypeScript support with strong type checking
- 📦 **@xcons/widget Compatibility** - Full integration with widget decorators

## 📋 Configuration Options

### Basic Options

```typescript
interface XConVitePluginOptions {
  // Processing options
  minifyTemplates?: boolean;        // Default: true
  minifyStyles?: boolean;           // Default: true
  removeComments?: boolean;         // Default: true
  watchFiles?: boolean;             // Default: true
  preserveWhitespace?: boolean;     // Default: false

  // Resource options
  resourceBaseUrl?: string;         // Default: ''
  processResources?: boolean;       // Default: true

  // Logging options
  showProcessedFiles?: boolean;     // Default: false
  logger?: Partial<LoggerConfig>;   // Logger configuration

  // File extension options
  fileExtensions?: string[];        // Default: ['.ts', '.js']
  templateExtensions?: string[];    // Default: ['.html']
  styleExtensions?: string[];       // Default: ['.css', '.scss', '.sass', '.less']

  // Minification options
  useTerser?: boolean;              // Default: true
  terserOptions?: TerserOptions;    // Terser configuration

  // Advanced options
  customProcessors?: ProcessorFunction[];
  excludeFiles?: string[];
  includeFiles?: string[];

  // Development options
  development?: boolean;            // Default: false
  sourceMap?: boolean;              // Default: true
}
```

### Example Configurations

#### Development Environment (Recommended)

```typescript
import xconVitePlugin from '@xcons/vite-plugin';

export default defineConfig({
  plugins: [
    xconVitePlugin({
      // Development features
      development: true,
      sourceMap: true,               // REQUIRED for debugging
      watchFiles: true,              // REQUIRED for hot reload
      
      // Minification off for readability
      minifyTemplates: false,
      minifyStyles: false,
      removeComments: false,
      
      // Detailed logging
      showProcessedFiles: true,
      logger: {
        enabled: true,
        level: 3,                    // DEBUG level
        timestamp: true,
        colors: true
      }
    })
  ]
});
```

#### ⚠️ Do NOT Use for Production

This plugin is for development only. For production builds:

```typescript
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    // DO NOT use @xcons/vite-plugin
    // Widgets will be already inlined in production
  ],
  build: {
    // Normal Vite production settings
    minify: 'terser',
    sourcemap: false
  }
});
```

#### Customized Configuration

```typescript
import xconVitePlugin from '@xcons/vite-plugin';

export default defineConfig({
  plugins: [
    xconVitePlugin({
      // Development features
      development: true,
      sourceMap: true,
      watchFiles: true,
      
      // File filtering
      includeFiles: ['widget', 'component'],
      excludeFiles: ['test', 'spec'],
      
      // Custom extensions
      templateExtensions: ['.html', '.htm'],
      styleExtensions: ['.css', '.scss', '.less'],
      
      // Detailed logging
      showProcessedFiles: true,
      logger: {
        enabled: true,
        level: 3,
        colors: true
      }
    })
  ]
});
```

## 🎯 Usage Examples

### Using with @xcons/widget

**my-widget.component.ts:**
```typescript
import { Widget } from '@xcons/widget';

@Widget({
  selector: 'my-widget',
  templateUrl: './my-widget.component.html',
  styleUrls: ['./my-widget.component.css']
})
export class MyWidget {
  // Your widget logic
}
```

**my-widget.component.html:**
```html
<div class="widget-container">
  <h1>Hello Widget!</h1>
  <p>This is an XCon widget.</p>
</div>
```

**After (Development Build - For Debugging):**
```typescript
import { Widget } from '@xcons/widget';

@Widget({
  selector: 'my-widget',
  template: `<div class="widget-container">
  <h1>Hello Widget!</h1>
  <p>This is an XCon widget.</p>
</div>`,
  styles: ['.widget-container{padding:20px;background:#f5f5f5}...']
})
export class MyWidget {}

// ✅ Thanks to source maps:
// - You can set breakpoints in the HTML file
// - Error messages show the original file
// - Changes reflect instantly with hot reload
```

### Hot Reload Example

**While Development Server is Running:**

```bash
npm run dev
```

1. **Edit my-widget.component.html** file:
```html
<div class="widget-container">
  <h1>Updated Title!</h1>  <!-- Change -->
  <p>This is an XCon widget.</p>
</div>
```

2. **Save the file** → Widget auto-refreshes ✨
3. **No page reload**, only widget updates
4. **Source map** allows debugging in original HTML

### Debugging and Breakpoints

**In Chrome DevTools:**

1. Open **Sources** tab
2. Find **my-widget.component.html** file
3. Set a **breakpoint** on any line
4. Widget stops at breakpoint when rendered
5. **Call stack** shows original files

```typescript
// When error occurs in console:
Error: Something went wrong
    at MyWidget.render (my-widget.component.ts:45:12)  // ✅ Original file
    at WidgetManager.initialize (widget-manager.ts:23:8)
```

### Style Processing and Hot Reload

**my-widget.component.css:**
```css
.widget-container {
  padding: 20px;
  background: #f5f5f5;
}

.widget-container h1 {
  color: #333;
  font-size: 24px;
}
```

**In Development:**
1. Edit the CSS file
2. Save → Styles update **instantly**
3. No page reload, only CSS applied
4. Style debugging with source maps

### Resource Management

Widget decorator resource definitions (as metadata only):

```typescript
import { Widget } from '@xcons/widget';

@Widget({
  selector: 'my-widget',
  templateUrl: './my-widget.component.html',
  resources: [
    { 
      name: 'chart-lib', 
      type: 'js', 
      url: '/assets/chart.min.js' 
    }
  ]
})
export class MyWidget {}

// Note: resources are used as metadata only
// Plugin doesn't modify this field, only preserves it
```

## 🔧 Advanced Usage

### Logger Integration

The plugin provides advanced logging using the `@xcons/common` package:

```typescript
import xconVitePlugin from '@xcons/vite-plugin';

export default defineConfig({
  plugins: [
    xconVitePlugin({
      logger: {
        enabled: true,
        level: 3,              // 0: ERROR, 1: WARN, 2: INFO, 3: DEBUG, 4: TRACE
        prefix: 'XCON-VITE',
        timestamp: true,
        colors: true
      }
    })
  ]
});
```

### Multiple Widget Project

```typescript
// vite.config.ts
import xconVitePlugin from '@xcons/vite-plugin';

export default defineConfig({
  plugins: [
    xconVitePlugin({
      development: true,
      sourceMap: true,
      watchFiles: true,
      
      // Process only widget files
      includeFiles: ['widget', 'component'],
      excludeFiles: ['test', 'spec', 'mock'],
      
      // Custom extensions
      templateExtensions: ['.html', '.htm'],
      styleExtensions: ['.css', '.scss', '.less']
    })
  ]
});
```

### File Watching Customization

```typescript
export default defineConfig({
  plugins: [
    xconVitePlugin({
      watchFiles: true,  // Watch file changes
      
      // File extensions to watch
      fileExtensions: ['.ts', '.js'],
      templateExtensions: ['.html'],
      styleExtensions: ['.css', '.scss'],
      
      // Detailed log for performance
      showProcessedFiles: true
    })
  ]
});
```

## 🔍 Debugging

### Using Source Maps

The plugin creates precise source maps using `magic-string`:

```bash
# Required for source map support
npm install magic-string --save-dev
```

```typescript
export default defineConfig({
  plugins: [
    xconVitePlugin({
      sourceMap: true  // Automatically uses magic-string if available
    })
  ]
});
```

**Benefits:**
- ✅ Breakpoints in original HTML/CSS files
- ✅ Error messages show real file locations
- ✅ Call stack shows original source code
- ✅ Console.log shows correct line numbers

### Detailed Logging

```typescript
xconVitePlugin({
  showProcessedFiles: true,  // Show processed files
  logger: {
    enabled: true,
    level: 3,  // DEBUG - Most detailed
    timestamp: true
  }
})
```

### Console Output

```
[XCon Plugin] 🚀 XCon Vite Plugin started
[XCon Plugin] 🔧 Configuration: { 
  development: true, 
  sourceMap: true, 
  watchFiles: true 
}
[XCon Plugin] 🔄 Processed: my-widget.component.ts
[XCon Plugin] 📄 Loaded HTML template: my-widget.component.html (1.2KB)
[XCon Plugin] 🎨 Loaded style: my-widget.component.css (856B)
[XCon Plugin] 🗺️  Source map generated for debugging
[XCon Plugin] ✅ XCon Vite Plugin finished
```

### Common Issues

**Problem:** Hot reload not working

```typescript
// Solution: Enable watchFiles
xconVitePlugin({
  watchFiles: true,  // ✅ This is REQUIRED
  development: true
})
```

**Problem:** Breakpoints not working

```bash
# Solution 1: Install magic-string
npm install magic-string --save-dev

# Solution 2: Enable source maps
# vite.config.ts
xconVitePlugin({
  sourceMap: true  // ✅ This is REQUIRED
})
```

**Problem:** Template not found

```typescript
// ✅ Correct: Use relative path
templateUrl: './my-widget.component.html'

// ❌ Wrong: Without relative path
templateUrl: 'my-widget.component.html'
```

**Problem:** Incompatibility with @xcons/widget

```bash
# Solution: Use latest versions of both packages
npm install @xcons/widget@latest
npm install @xcons/vite-plugin@latest --save-dev
```

## 📦 Dependencies

### Installation (Recommended)

```bash
# Widget package (production dependency)
npm install @xcons/widget

# Development plugin
npm install @xcons/vite-plugin --save-dev

# For source map support (RECOMMENDED)
npm install magic-string --save-dev

# For advanced logging (optional)
npm install @xcons/common --save-dev
```

### package.json Example

```json
{
  "dependencies": {
    "@xcons/widget": "^1.2.1"
  },
  "devDependencies": {
    "@xcons/vite-plugin": "^1.2.1",
    "vite": "^7.1.5",
    "magic-string": "^0.30.18",
    "@xcons/common": "^2.0.7",
    "typescript": "^5.5.2"
  }
}
```

**Note:** Use specific version numbers (with `^`). Using `"latest"` can lead to unexpected incompatibilities.

## 🧪 Testing and Development

### Development Server

```bash
# Start development server in your widget project
npm run dev

# Plugin automatically:
# - Watches template changes
# - Applies style updates
# - Refreshes widgets with hot reload
# - Generates source maps
```

### Example Project Structure

```
my-widget-project/
├── src/
│   ├── widgets/
│   │   ├── my-widget/
│   │   │   ├── my-widget.component.ts       # @xcons/widget
│   │   │   ├── my-widget.component.html     # Template
│   │   │   └── my-widget.component.css      # Styles
│   └── main.ts
├── vite.config.ts                            # Plugin configuration
└── package.json
```

### Development Workflow

1. **Create widget** (with @xcons/widget)
```typescript
import { Widget } from '@xcons/widget';

@Widget({
  selector: 'my-widget',
  templateUrl: './my-widget.component.html',
  styleUrls: ['./my-widget.component.css']
})
export class MyWidget {}
```

2. **Start dev server**
```bash
npm run dev
```

3. **Develop and debug**
- Edit template → Auto refresh
- Change CSS → Instant update
- Set breakpoint → Debug with source maps

4. **Production build** (without plugin)
```bash
npm run build
```

## 📄 License

MIT © [XCon Studio](https://xcon.studio)

## 🔗 Links

- [NPM Package](https://www.npmjs.com/package/@xcons/vite-plugin)
- [@xcons/widget Package](https://www.npmjs.com/package/@xcons/widget)
- [GitHub Repository](https://github.com/xcon-studio/vite-plugin.git)
- [XCon Studio](https://xcon.studio)
- [Documentation](https://xcon.studio/docs)
- [Issues](https://github.com/xcon-studio/vite-plugin/issues)

## ⭐ Support

If this project helped you, give it a ⭐️!

---

Made with ❤️ by [XCon Studio](https://xcon.studio)