npm package: @scom/bundler
Description: SCOM packages Bundler
Latest version: 0.1.6

# @scom/bundler

Advanced TypeScript compiler and module bundler for Secure Compute (SCOM) packages, designed to work in both Node.js and browser environments.

## Overview

The `@scom/bundler` is a sophisticated compilation and bundling system that provides TypeScript compilation, module resolution, and dependency management for SCOM packages. It features a unique architecture that enables TypeScript compilation directly in the browser while maintaining full compatibility with Node.js environments.

## Key Features

- **Universal TypeScript Compilation**: Compile TypeScript in both Node.js and browser environments
- **Advanced Module Resolution**: Intelligent resolution of local and remote modules
- **Flexible Import System**: Support for file and module importers with custom implementations
- **Memory-Based Storage**: Efficient in-memory compilation with virtual file systems
- **React Integration**: Built-in support for React and ReactDOM type definitions
- **Dual Build Targets**: Separate builds optimized for Node.js and browser environments

## Installation

```bash
npm install @scom/bundler
```

## Architecture

### Core Components

- **Compiler**: TypeScript compilation engine with environment detection
- **Importer**: Flexible import system for files and modules
- **Storage**: Memory-based virtual file system for compilation artifacts
- **Interfaces**: TypeScript interfaces for extensible import implementations

### Build Targets

- **Node.js Build** (`lib/`): Full-featured bundler for server-side compilation with file system access
- **Browser Build** (`dist/index.js`): Single-file AMD bundle for client-side TypeScript compilation

## Usage

### Basic Compilation

```typescript
import { TypeScriptCompiler } from '@scom/bundler';

// Create compiler instance
const compiler = new TypeScriptCompiler();

// Compile TypeScript code
const result = await compiler.compile({
  'index.ts': `
    import React from 'react';
    
    export const MyComponent = () => {
      return <div>Hello World</div>;
    };
  `
});

console.log(result.outputFiles);
```

### Custom File Importer

**Note**: File and module importers are only available in the Node.js build. For browser usage, files must be provided directly to the compiler.

```typescript
import { FileImporter, TypeScriptCompiler } from '@scom/bundler';

class CustomFileImporter implements FileImporter {
  async importFile(fileName: string): Promise<string | undefined> {
    // Custom logic to fetch file content
    // Could be from database, API, etc.
    return await fetchFileFromAPI(fileName);
  }

  async fileExists(fileName: string): Promise<boolean> {
    return await checkFileExistsInAPI(fileName);
  }
}

const compiler = new TypeScriptCompiler({
  fileImporter: new CustomFileImporter()
});
```

### Module Resolution

```typescript
import { ModuleImporter, TypeScriptCompiler } from '@scom/bundler';

class CustomModuleImporter implements ModuleImporter {
  async resolveModule(moduleName: string, startDir: string): Promise<string | null> {
    // Custom module resolution logic
    // Could resolve from CDN, custom registry, etc.
    return await resolveFromCustomRegistry(moduleName);
  }

  async importModule(modulePath: string): Promise<string | undefined> {
    // Import module type definitions from resolved path
    return await fetchModuleTypes(modulePath);
  }
}

const compiler = new TypeScriptCompiler({
  moduleImporter: new CustomModuleImporter()
});
```

## Scripts

### Development

```bash
# Build both Node.js and browser versions
npm run build

# Build Node.js version only
npm run build:node

# Build browser version only
npm run build:browser
```

### Testing

```bash
# Run tests
npm test

# Run browser tests with server
npm run test:browser

# Run automated browser tests
npm run test:browser:auto
```

## Project Structure

```
@scom/bundler/
├── src/
│   ├── index.ts              # Node.js entry point
│   ├── browser.ts            # Browser entry point  
│   ├── compiler.ts           # TypeScript compilation engine
│   ├── importer.ts           # File and module import system (Node.js only)
│   ├── storage.ts            # Memory-based storage system
│   ├── interfaces.ts         # TypeScript interfaces
│   └── lib/                  # Bundled TypeScript and React definitions
│       ├── typescript.js     # TypeScript compiler bundle
│       ├── typescript.d.ts   # TypeScript type definitions
│       ├── react.d.ts        # React type definitions
│       └── react-dom/        # ReactDOM type definitions
├── lib/                      # Node.js build output
├── dist/                     # Browser build output (single AMD file)
│   └── index.js              # Browser bundle with TypeScript compiler
├── types/                    # Generated TypeScript definitions
└── tests/                    # Test files and browser test setup
```

## Browser Compilation

One of the unique features of `@scom/bundler` is its ability to compile TypeScript directly in the browser. **Note**: The browser build only includes the compiler and interfaces - file and module importers are not available.

```html
<script src="node_modules/@scom/bundler/dist/index.js"></script>
<script>
  // The browser build is an AMD module named "@scom/cli"
  require(['@scom/cli'], function(SCOMBundler) {
    const compiler = new SCOMBundler.TypeScriptCompiler();
    
    compiler.compile({
      'app.tsx': `
        import React from 'react';
        export const App = () => <h1>Browser Compiled!</h1>;
      `
    }).then(result => {
      console.log('Compiled in browser:', result);
    });
  });
</script>
```

## Integration with SCOM Ecosystem

The bundler integrates seamlessly with other SCOM tools:

- **@scom/cli**: Separate CLI package that uses this bundler internally for the `bundle` command
- **@scom/serve**: Provides development server capabilities during compilation
- **@scom/test**: Testing framework for compilation and bundling workflows
- **@scom/core**: Provides runtime dependencies for compiled modules

**Note**: This package provides the bundling engine. For CLI functionality, install `@scom/cli` separately.

## Configuration

The bundler supports various TypeScript compiler options and can be configured through:

- **CompilerOptions**: Standard TypeScript compiler configuration
- **Custom Importers**: Pluggable file and module import systems
- **Memory Storage**: Configurable virtual file system settings
- **Environment Detection**: Automatic Node.js vs browser environment handling

## Advanced Features

### Virtual File System

The bundler uses an in-memory virtual file system for efficient compilation:

```typescript
import { MemoryStorage } from '@scom/bundler';

const storage = new MemoryStorage();
storage.writeFile('/virtual/file.ts', 'export const value = 42;');

const compiler = new TypeScriptCompiler({ storage });
```

### Multi-Environment Support

The same bundler code works in both environments, with some limitations:

```typescript
// Works in Node.js (full feature set)
import { TypeScriptCompiler, LocalFileImporter, LocalModuleImporter } from '@scom/bundler';
const nodeCompiler = new TypeScriptCompiler({
  fileImporter: new LocalFileImporter(),
  moduleImporter: new LocalModuleImporter()
});

// Works in browser (compiler and interfaces only)
// Note: Import statements must be provided directly, no file system access
const browserCompiler = new TypeScriptCompiler();
```

## Dependencies

- **TypeScript**: Full TypeScript compiler integration
- **React & ReactDOM**: Type definitions for React development
- **@scom/serve**: Development server capabilities
- **@scom/test**: Testing framework integration

## Performance

- **Memory-Based**: Fast compilation using in-memory virtual file systems
- **Incremental**: Support for incremental compilation where possible
- **Environment Optimized**: Separate builds optimized for Node.js and browser performance
- **Efficient Bundling**: Minimal overhead with intelligent module resolution