npm package: @flightdev/bundler-turboflight
Description: Turboflight bundler adapter for Flight Framework
Latest version: 0.3.6

# @flightdev/bundler-turboflight

High-performance native bundler adapter for Flight Framework. Provides Rust-powered bundling via NAPI bindings with support for React Server Components, Fast Refresh, Lazy Compilation, and Module Federation.

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Features](#features)
- [API Reference](#api-reference)
- [Configuration](#configuration)
- [Advanced Usage](#advanced-usage)
- [Troubleshooting](#troubleshooting)
- [License](#license)

---

## Installation

```bash
npm install @flightdev/bundler-turboflight
```

Or with pnpm/yarn:

```bash
pnpm add @flightdev/bundler-turboflight
# or
yarn add @flightdev/bundler-turboflight
```

### Platform Requirements

Native bindings are available for:

| Platform | Architecture | Package |
|----------|--------------|---------|
| Windows | x64 | `@turboflight/native-win32-x64-msvc` |
| macOS | ARM64 | `@turboflight/native-darwin-arm64` |
| macOS | x64 | `@turboflight/native-darwin-x64` |
| Linux | x64 | `@turboflight/native-linux-x64-gnu` |

---

## Quick Start

### Basic Usage

```typescript
import { turboflight } from '@flightdev/bundler-turboflight';

// Create bundler adapter
const bundler = turboflight({
    debug: false,
    format: 'esm',
});

// Use with Flight Framework
export default defineConfig({
    bundler: bundler,
});
```

### Standalone Build

```typescript
import { turboflight } from '@flightdev/bundler-turboflight';

const bundler = turboflight();

const result = await bundler.build({
    entry: ['src/index.ts'],
    outDir: 'dist',
    minify: true,
    sourcemap: true,
});

console.log(`Built ${result.moduleCount} modules in ${result.duration}ms`);
```

---

## Features

### Core Bundling

- Tree-shaking with ES module analysis
- Code splitting (automatic and manual)
- Source map generation
- Minification via SWC
- Path alias resolution
- External module handling

### React Server Components (RSC)

Full support for the React Server Components architecture:

```typescript
import { rscDetectDirective, rscAnalyzeBoundary } from '@flightdev/bundler-turboflight';

// Detect 'use client' or 'use server' directives
const directive = rscDetectDirective(sourceCode);
// { directive: 'client', isValid: true, line: 1 }

// Analyze component boundaries
const boundary = rscAnalyzeBoundary(filePath, sourceCode);
// { boundaryType: 'client', clientRefs: [...], serverOnlyImports: [...] }
```

### React Fast Refresh

Hot module replacement with state preservation:

```typescript
import { 
    refreshExtractSignatures, 
    refreshGeneratePreamble,
    refreshGenerateRegistration 
} from '@flightdev/bundler-turboflight';

// Extract component signatures
const signatures = refreshExtractSignatures('Button.tsx', code);

// Generate refresh runtime
const preamble = refreshGeneratePreamble();
const registration = refreshGenerateRegistration(signatures, moduleId);
```

### Lazy Compilation

On-demand module compilation for faster development:

```typescript
import { LazyRegistry, lazyGeneratePlaceholder } from '@flightdev/bundler-turboflight';

// Create registry
const registry = new LazyRegistry();
registry.register('./src/heavy-component.tsx');

// Generate placeholder for lazy loading
const placeholder = lazyGeneratePlaceholder(
    './src/heavy-component.tsx',
    'http://localhost:5173'
);
```

### Module Federation 2.0

Share code between independent applications:

```typescript
import { federationInit, federationGenerateRuntime } from '@flightdev/bundler-turboflight';

const manifest = federationInit({
    name: 'host',
    remotes: {
        remote1: 'http://localhost:3001/remoteEntry.js',
    },
    exposes: {
        './Button': './src/components/Button.tsx',
    },
    shared: [
        { name: 'react', singleton: true },
        { name: 'react-dom', singleton: true },
    ],
});

const runtime = federationGenerateRuntime(manifest);
```

### Incremental Builds

Cache compiled modules for faster rebuilds:

```typescript
import { BuildCache, incrementalHash } from '@flightdev/bundler-turboflight';

const cache = new BuildCache();

// Check cache
const hash = incrementalHash(sourceCode);
const cached = cache.get(filePath, hash);

if (!cached) {
    // Compile and cache
    const compiled = await compile(sourceCode);
    cache.set({
        path: filePath,
        hash,
        code: compiled,
        timestamp: Date.now(),
        dependencies: deps,
    });
}

// View statistics
const stats = cache.stats();
console.log(`Cache hit ratio: ${(stats.hitRatio * 100).toFixed(1)}%`);
```

---

## API Reference

### Bundler Adapter

```typescript
function turboflight(options?: TurboflightOptions): BundlerAdapter;
```

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | `boolean` | `false` | Enable debug logging |
| `external` | `string[]` | `[]` | Modules to exclude from bundle |
| `alias` | `Record<string, string>` | `{}` | Path aliases |
| `format` | `'esm' \| 'cjs' \| 'iife'` | `'esm'` | Output format |
| `entry` | `string[]` | - | Entry points |

### Transform

```typescript
function transform(
    filename: string,
    code: string,
    options?: { target?: string; sourcemap?: boolean }
): TransformResult;
```

Transform a single file using SWC.

### Resolve

```typescript
function resolve(
    specifier: string,
    from: string,
    options?: { root?: string; external?: string[] }
): ResolveResult;
```

Resolve module specifiers with Node.js resolution algorithm.

### Analyze

```typescript
function analyze(filename: string, code: string): ModuleAnalysis;
```

Parse and analyze a module's imports, exports, and characteristics.

### Version

```typescript
function version(): string;
```

Returns the Turboflight version.

---

## Configuration

### With Flight Config

```typescript
// flight.config.ts
import { defineConfig } from '@flightdev/core';
import { turboflight } from '@flightdev/bundler-turboflight';

export default defineConfig({
    bundler: turboflight({
        debug: process.env.DEBUG === 'true',
        external: ['fsevents'],
        alias: {
            '@': './src',
            '@components': './src/components',
        },
    }),

    build: {
        minify: true,
        sourcemap: true,
    },
});
```

### Environment Variables

| Variable | Description |
|----------|-------------|
| `TURBOFLIGHT_LOG` | Log level: trace, debug, info, warn, error |
| `TURBOFLIGHT_CACHE_DIR` | Custom cache directory |
| `TURBOFLIGHT_WORKERS` | Number of worker threads |

---

## Advanced Usage

### Custom RSC Processing

```typescript
import { 
    rscDetectDirective,
    rscAnalyzeBoundary,
    rscFlightChunk,
    rscCreateActionManifest 
} from '@flightdev/bundler-turboflight';

// Process server components
async function processRSC(files: string[]) {
    const serverActions = [];
    
    for (const file of files) {
        const code = await fs.readFile(file, 'utf-8');
        const directive = rscDetectDirective(code);
        
        if (directive.directive === 'server') {
            const boundary = rscAnalyzeBoundary(file, code);
            // Process server-only imports
        }
    }
    
    // Generate action manifest
    const manifest = rscCreateActionManifest(serverActions);
}
```

### Custom Error Overlay

```typescript
import { refreshGenerateOverlay } from '@flightdev/bundler-turboflight';

// Generate overlay with custom position
const overlay = refreshGenerateOverlay('bottom-left');
// Positions: 'bottom-right', 'bottom-left', 'top-right', 'top-left', 'center'
```

### Change Detection

```typescript
import { incrementalDetectChanges } from '@flightdev/bundler-turboflight';

const changes = incrementalDetectChanges(
    previousHashes,  // { 'file.ts': 'abc123' }
    currentHashes    // { 'file.ts': 'def456' }
);

console.log('Changed files:', changes.direct);
console.log('Affected dependents:', changes.transitive);
```

---

## Troubleshooting

### Native Binding Not Found

Ensure the correct platform package is installed:

```bash
npm install @turboflight/native-win32-x64-msvc  # Windows
npm install @turboflight/native-darwin-arm64    # macOS ARM
npm install @turboflight/native-darwin-x64      # macOS Intel
npm install @turboflight/native-linux-x64-gnu   # Linux
```

### Build Performance

For large projects, enable incremental builds:

```typescript
const bundler = turboflight({
    incremental: true,
    cacheDir: '.turboflight-cache',
});
```

### Memory Issues

Increase Node.js memory limit:

```bash
NODE_OPTIONS="--max-old-space-size=8192" flight build
```

### Debug Mode

Enable verbose logging:

```bash
TURBOFLIGHT_LOG=debug flight dev
```

Or in code:

```typescript
const bundler = turboflight({ debug: true });
```

---

## Comparison

| Feature | Turboflight | esbuild | Vite | Webpack |
|---------|-------------|---------|------|---------|
| Language | Rust | Go | JS | JS |
| RSC Support | Yes | No | No | Plugin |
| Fast Refresh | Yes | No | Yes | Plugin |
| Module Federation | Yes | No | No | Yes |
| Lazy Compilation | Yes | No | Yes | Yes |
| Incremental | Yes | Limited | Yes | Yes |

---

## License

MIT