# @playcademy/vite-plugin

**Vite plugin for Playcademy game development and deployment**

This plugin integrates Playcademy's development sandbox and build tools into your Vite workflow, automatically generating manifests, managing development environments, and creating deployment-ready archives.

## Overview

The Playcademy Vite plugin streamlines game development by providing:

- **Development Sandbox**: Automatically starts a local Playcademy API server and real-time WebSocket server during development.
- **Manifest Generation**: Creates required `playcademy.manifest.json` files for platform deployment
- **Build Optimization**: Configures Vite settings for optimal Playcademy platform compatibility
- **Deployment Packaging**: Optionally creates zip archives ready for platform upload

### Key Benefits

- **Zero-Config Development**: Works out of the box with sensible defaults
- **Hot Reload Integration**: Seamless development experience with Vite's hot module replacement
- **Platform Compatibility**: Ensures builds work correctly on the Playcademy platform
- **Type Safety**: Full TypeScript support with comprehensive type definitions
- **Flexible Configuration**: Extensive options for customizing both development and build processes

## Installation

Install the plugin in your Playcademy game project:

```bash
# Using Bun (recommended)
bun add -D @playcademy/vite-plugin

# Using npm
npm install --save-dev @playcademy/vite-plugin

# Using yarn
yarn add --dev @playcademy/vite-plugin

# Using pnpm
pnpm add -D @playcademy/vite-plugin
```

## Quick Start

Add the plugin to your `vite.config.ts`:

```typescript
import { defineConfig } from 'vite'

import { playcademy } from '@playcademy/vite-plugin'

export default defineConfig({
    plugins: [
        playcademy(), // Uses all defaults
    ],
})
```

Start development:

```bash
bun dev
```

The plugin will:

- Start the sandbox server at `http://localhost:4321/api`
- Enable API integration for your game
- Provide hot reload for rapid development

## Configuration

### Basic Configuration

```typescript
import { playcademy } from '@playcademy/vite-plugin'

export default defineConfig({
    plugins: [
        playcademy({
            export: {
                bootMode: 'iframe', // 'iframe' | 'module'
                entryPoint: 'index.html', // Main HTML file
                platform: 'web', // 'web' | 'godot' | 'unity'
                autoZip: false, // Create deployment zip
                styles: [], // Additional CSS files
            },
            sandbox: {
                autoStart: true, // Start sandbox automatically
                url: 'http://localhost:4321', // Sandbox URL
                verbose: false, // Enable debug logging
                realtime: {
                    enabled: false, // Disabled by default, enable for multiplayer
                    port: 4322, // Defaults to API port + 1
                },
            },
        }),
    ],
})
```

### Production Build Configuration

```typescript
export default defineConfig({
    plugins: [
        playcademy({
            export: {
                autoZip: true, // Creates .playcademy/{project-name}.zip
            },
        }),
    ],
})
```

### Custom Sandbox Configuration

```typescript
export default defineConfig({
    plugins: [
        playcademy({
            sandbox: {
                autoStart: false, // Disable auto-start
                url: 'http://localhost:8080', // Custom port
                verbose: true, // Enable debug logs
            },
        }),
    ],
})
```

## Plugin Options

### Export Options (`export`)

Configuration for manifest generation and build output:

| Option       | Type                          | Default        | Description                     |
| ------------ | ----------------------------- | -------------- | ------------------------------- |
| `bootMode`   | `'iframe' \| 'module'`        | `'iframe'`     | How the game should be launched |
| `entryPoint` | `string`                      | `'index.html'` | Main HTML file for your game    |
| `platform`   | `'web' \| 'godot' \| 'unity'` | `'web'`        | Game engine/platform type       |
| `autoZip`    | `boolean`                     | `false`        | Create deployment zip archive   |
| `styles`     | `string[]`                    | `[]`           | Additional CSS files to load    |

### Sandbox Options (`sandbox`)

Configuration for the development sandbox server:

| Option      | Type      | Default                       | Description                      |
| ----------- | --------- | ----------------------------- | -------------------------------- |
| `autoStart` | `boolean` | `true`                        | Start sandbox during development |
| `url`       | `string`  | `'http://localhost:4321/api'` | Sandbox server URL               |
| `verbose`   | `boolean` | `false`                       | Enable verbose logging           |
| `realtime`  | `object`  | `{...}`                       | Real-time server configuration   |

## Build Output

### Development Mode

During `bun dev`, the plugin:

- Starts the sandbox server (if enabled)
- Provides game API simulation
- Enables hot reload for game code
- Seamlessly wraps your game in the Playcademy environment

Console output:

```
VITE v6.3.5  ready in 500ms

➜  Local:   http://localhost:5173/
➜  Network: use --host to expose

PLAYCADEMY v1.2.3

➜  Game:     my-game
➜  Sandbox:  http://localhost:4321/api
```

**How it works**: When you visit `http://localhost:5173/` in your browser, you'll see your game wrapped in the Playcademy development shell (which mimics the production platform environment). Inside the iframe, your game is served at the root path `/`, so client-side routers (React Router, etc.) work naturally without any special configuration.

The plugin uses the `Sec-Fetch-Dest` header to intelligently detect whether a request is from the shell's iframe or top-level browser navigation, automatically serving the appropriate content.

### Production Build

During `bun run build`, the plugin:

- Generates `playcademy.manifest.json` in `dist/`
- Creates deployment zip (if `autoZip: true`)
- Optimizes build for platform deployment

Console output:

```
dist/index.html                           2.45 kB │ gzip:  1.12 kB
dist/assets/index-Bj8fxu6c.js           135.24 kB │ gzip: 43.82 kB

[Playcademy]
playcademy.manifest.json                   0.25 kB
.playcademy/my-game.zip                1,234.56 kB
```

## Generated Files

### Manifest File

The plugin generates `dist/playcademy.manifest.json`:

```json
{
    "version": 1,
    "slug": "my-game",
    "displayName": "My Game",
    "description": "An awesome Playcademy game",
    "entryPoint": "index.html",
    "bootMode": "iframe",
    "platform": "web",
    "styles": [],
    "gameVersion": "1.0.0"
}
```

### Deployment Archive

With `autoZip: true`, creates `.playcademy/{project-name}.zip` containing all build files ready for platform upload.

## Development

### Development Workflow

```bash
# Start the development environment from monorepo root
bun dev

# This starts all applications with proper port allocation:
# - Landing: http://localhost:5173
# - Hub: http://localhost:5174
# - Docs: http://localhost:5175
# - Blog: http://localhost:5176
# - Sandbox: http://localhost:4321
```

For package-specific development:

```bash
# Change to package directory
cd packages/vite-plugin

# Build the plugin
bun run build

# Publish to npm (requires permissions)
bun run pub
```

## Dependencies

### Runtime Dependencies

- **archiver**: Zip file creation for deployment packages
- **picocolors**: Terminal color output for logging

### Development Dependencies

- **@playcademy/sandbox**: Development sandbox server
- **@types/archiver**: TypeScript definitions for archiver
- **yocto-spinner**: Progress indicators for build operations

### Peer Dependencies

- **typescript**: TypeScript compiler (v5+)

## Common Use Cases

### Basic Web Game

```typescript
// Minimal configuration for most web games
export default defineConfig({
    plugins: [playcademy()],
})
```

### Enabling Real-time Features

```typescript
// Enable the real-time server for multiplayer games
export default defineConfig({
    plugins: [
        playcademy({
            sandbox: {
                realtime: {
                    enabled: true,
                },
            },
        }),
    ],
})
```

### Godot Export

```typescript
// Configuration for Godot HTML5 exports
export default defineConfig({
    plugins: [
        playcademy({
            export: {
                platform: 'godot',
                entryPoint: 'game.html',
            },
        }),
    ],
})
```

### Production Deployment

```typescript
// Optimized for production builds
export default defineConfig(({ mode }) => ({
    plugins: [
        playcademy({
            export: {
                autoZip: mode === 'production',
            },
            sandbox: {
                verbose: mode === 'development',
            },
        }),
    ],
}))
```

## Troubleshooting

### Common Issues

**Manifest not generated**

- Ensure plugin is properly configured in `vite.config.ts`
- Check for build errors in console output
- Verify the build completes successfully

**Zip file not created**

- Enable `autoZip: true` in export options
- Check that build completed without errors
- Look for zip in `.playcademy/` directory

### Debug Mode

Enable verbose logging for troubleshooting:

```typescript
playcademy({
    sandbox: {
        verbose: true,
    },
})
```
