npm package: @kadi.build/container-registry-ability
Description: Dynamic Container Registry for KADI Agent with S3 and OCI support
Author: Corey Clark
Latest version: 0.0.9

# Tunneled Container Registry

A **production-ready** Node.js library that creates temporary Docker registries with public internet access, enabling instant container sharing across machines and networks without complex infrastructure.

[![Node.js 20+](https://img.shields.io/badge/Node.js-20+-green.svg)](https://nodejs.org/)
[![Docker](https://img.shields.io/badge/Docker-Compatible-blue.svg)](https://docker.com/)
[![Podman](https://img.shields.io/badge/Podman-Compatible-purple.svg)](https://podman.io/)
[![Tests](https://img.shields.io/badge/Tests-217%2B%20Passing-brightgreen.svg)](#testing--quality)

## 🚀 Features

### 🐳 **Advanced Container Management**
- **Multi-Container Support**: Process multiple containers simultaneously with batch operations
- **Auto-Detection**: Automatically discovers Docker and Podman engines across the system
- **Auto-Discovery**: Intelligent container discovery with filtering and pagination
- **Multi-Engine**: Works with Docker, Podman, or both simultaneously  
- **Version Validation**: Ensures compatibility with your container engines
- **Graceful Fallback**: Handles missing engines with clear error messages

### 🌐 **Public Internet Access**
- **Multiple Tunnel Services**: KĀDI (default), Serveo, ngrok, localtunnel
- **Instant Public URLs**: Share containers globally in seconds
- **No Infrastructure**: No need for cloud registries or servers
- **Docker Registry v2 API**: Full compatibility with standard Docker tools

### 📦 **Flexible Container Sources**
- **Live Containers**: Export from running Docker/Podman engines
- **Batch Processing**: Handle multiple containers with progress tracking
- **OCI Compliance**: Generates standard Docker Registry structures
- **Mock Containers**: Create test containers without real engines
- **Tar Archives**: Process existing container exports

### ⚡ **Ready-to-Use Commands**
- **Auto-Generated**: Creates Docker and Podman login/pull/run commands
- **Multi-Container**: Generates commands for all containers in the registry
- **One-Click Copy**: Copy-paste commands for immediate use
- **Cross-Platform**: Commands work on Windows, macOS, and Linux
- **Multiple Formats**: Step-by-step or one-line execution

### 🔐 **Production Security**
- **Temporary Credentials**: Auto-expiring access keys (default: 30 minutes)
- **Access Control**: Configurable permissions and authentication
- **Secure Tunnels**: End-to-end encrypted tunnel connections
- **Resource Cleanup**: Automatic cleanup of temporary files and processes

### 📊 **Analytics & Monitoring**
- **Live Progress**: Monitor downloads and transfers in real-time
- **Statistics Collection**: Comprehensive registry and performance metrics
- **Usage Analytics**: Track downloads, data transfer, and user activity
- **Health Checks**: Tunnel status and registry availability monitoring
- **Rich Events**: Comprehensive event system for integration
- **Performance Stats**: Transfer rates, completion times, usage analytics
- **Historical Analysis**: Trend analysis and usage patterns
- **Export Capabilities**: Statistics export in multiple formats

## 🎯 Quick Start

### Installation

```bash
npm install tunneled-container-registry
```

### Basic Usage

```javascript
import { TunneledContainerRegistry } from 'tunneled-container-registry';

// Create and start a public registry with analytics
const registry = new TunneledContainerRegistry({
  enableAnalytics: true,
  downloadTracking: true
});
await registry.start();

// Add a single container
await registry.addContainer({ name: 'nginx:latest' });

// Add multiple containers with batch processing
await registry.addContainers([
  { name: 'nginx:latest' },
  { name: 'alpine:latest' },
  { name: 'node:18' }
]);

// Auto-discover and add containers
const discovered = await registry.autoDiscoverContainers({
  engines: ['docker', 'podman'],
  filter: { minSize: '1MB' }
});
await registry.addContainers(discovered.slice(0, 5));

// Get public access information
const urls = await registry.getRegistryUrls();
const commands = await registry.getDockerCommands();

console.log('🌐 Public URL:', urls.tunnelUrl);
console.log('🚀 Login command:', commands.loginCommands.docker);

// Get analytics and statistics
const stats = await registry.getRegistryStats();
const performance = await registry.getPerformanceMetrics();
console.log('� Statistics:', stats);
console.log('⚡ Performance:', performance);
```

### Live Demo

See it working in seconds:

```bash
git clone <repository-url>
cd container-registry-ability/demos/validation-demo
npm install && npm start
```

**Example output:**
```
🚀 Tunneled Container Registry - Validation Demo
=================================================

✅ Container engines detected: docker, podman (using docker)
✅ Container added: validation-demo-app
✅ Registry started with public tunnel

🌐 Registry URLs:
   Public: https://abc123.serveo.net

⚡ One-Line Command (Copy & Paste):
echo "password" | docker login --username "user" --password-stdin abc123.serveo.net && docker run --rm -it --pull=always abc123.serveo.net/validation-demo-app:latest
```

**Test from anywhere:** Copy the command to any machine with Docker - it will pull and run your container instantly!

## 📖 API Reference

### TunneledContainerRegistry

The main class for creating and managing tunneled container registries.

#### Constructor

```javascript
const registry = new TunneledContainerRegistry(options);
```

**Options:**

```javascript
{
  // Server Configuration
  port: 3000,                           // Port number (0 = random)
  serverName: 'tunneled-container-registry',
  
  // Tunnel Configuration  
  tunnelService: '',                    // '' (KĀDI default) | 'kadi' | 'serveo' | 'ngrok' | 'localtunnel' | 'none'
  tunnelOptions: {
    subdomain: 'my-registry',           // Preferred subdomain (ngrok)
    region: 'us',                       // ngrok region
    authtoken: process.env.NGROK_TOKEN, // ngrok auth token
    transport: 'wss',                   // KĀDI tunnel transport ('wss' or 'tcp')
    wssControlHost: 'tunnel-control.kadi.build' // KĀDI WSS control host
  },
  
  // Container Engine
  preferredEngine: 'auto',              // 'docker' | 'podman' | 'auto'
  
  // Security & Access
  credentials: {
    expiry: 1800,                       // Seconds (30 min default)
    permissions: ['read']               // Access permissions
  },
  
  // Analytics & Monitoring
  enableAnalytics: true,                // Enable statistics collection
  downloadTracking: true,               // Track download progress
  enableMonitoring: false,              // Enable monitoring dashboard
  
  // Multi-Container Management
  batchSize: 10,                        // Max containers per batch operation
  parallelOperations: 3,                // Concurrent operations limit
  
  // Auto-Discovery
  autoDiscovery: {
    enabled: true,                      // Enable auto-discovery
    engines: ['docker', 'podman'],      // Engines to scan
    filters: {
      minSize: '1MB',                   // Minimum container size
      maxAge: '30d',                    // Maximum container age
      excludePatterns: ['scratch']      // Patterns to exclude
    }
  },
  
  // Shutdown Configuration
  autoShutdown: false,                  // Auto-shutdown on completion
  shutdownOptions: {
    completionDelay: 30000,             // Delay after completion (ms)
    maxIdleTime: 300000,                // Max idle time (5 min)
    maxTotalTime: 7200000               // Max total time (2 hours)
  }
}
```

#### Core Methods

##### `start()`
Initialize and start the registry with public tunnel.

```javascript
await registry.start();
// Registry is now accessible publicly
```

##### `stop()`
Gracefully shutdown the registry and clean up resources.

```javascript
await registry.stop();
// All resources cleaned up
```

##### `addContainer(containerSpec)`
Add a container to the registry from various sources.

```javascript
// From Docker/Podman
await registry.addContainer({ name: 'nginx:latest' });
await registry.addContainer({ name: 'my-app', engine: 'podman' });

// From tar file
await registry.addContainer({ 
  tarPath: '/path/to/container.tar',
  name: 'my-container'
});

// Mock container (for testing)
await registry.addContainer({
  type: 'mock',
  name: 'test-app',
  tag: 'v1.0.0'
});
```

##### `addContainers(containerSpecs)`
Add multiple containers with batch processing and progress tracking.

```javascript
const containers = [
  { name: 'nginx:latest' },
  { name: 'alpine:latest' },
  { name: 'node:18' }
];

const results = await registry.addContainers(containers);
console.log(`Successfully added ${results.length} containers`);
```

##### `autoDiscoverContainers(options)`
Automatically discover available containers across engines.

```javascript
const discovered = await registry.autoDiscoverContainers({
  engines: ['docker', 'podman'],
  filter: {
    minSize: '1MB',
    maxAge: '7d',
    excludePatterns: ['scratch', '<none>']
  },
  limit: 20
});

console.log(`Discovered ${discovered.length} containers`);
```

##### `removeContainer(containerName)`
Remove a container from the registry.

```javascript
await registry.removeContainer('nginx:latest');
```

##### `updateContainer(containerName, newSpec)`
Update an existing container in the registry.

```javascript
await registry.updateContainer('my-app:v1', {
  name: 'my-app:v2',
  source: 'my-app:v2'
});
```

##### `getRegistryUrls()`
Get local and public registry URLs.

```javascript
const urls = await registry.getRegistryUrls();
console.log(urls.localUrl);    // http://localhost:3000
console.log(urls.tunnelUrl);   // https://abc123.serveo.net
```

##### `getDockerCommands(containerName?)`
Get ready-to-use Docker commands for accessing containers.

```javascript
const commands = await registry.getDockerCommands();

// Login command
console.log(commands.loginCommands.docker);
// Output: echo "password" | docker login --username "user" --password-stdin abc123.serveo.net

// Pull commands for all containers
Object.entries(commands.pullCommands).forEach(([name, cmd]) => {
  console.log(`${name}: ${cmd}`);
});

// Run commands
Object.entries(commands.runCommands).forEach(([name, cmd]) => {
  console.log(`${name}: ${cmd}`);
});
```

##### `getPodmanCommands(containerName?)`
Get ready-to-use Podman commands (same structure as Docker commands).

```javascript
const commands = await registry.getPodmanCommands();
console.log(commands.loginCommands.podman);
```

##### `getAccessCredentials()`
Get current authentication credentials.

```javascript
const creds = await registry.getAccessCredentials();
console.log(creds.username);   // Generated username
console.log(creds.password);   // Generated password
console.log(creds.expiresAt);  // Expiration timestamp
```

##### `listContainers()`
List all containers in the registry.

```javascript
const containers = registry.listContainers();
containers.forEach(container => {
  console.log(`${container.name}:${container.tag} (${container.size})`);
});
```

#### Analytics & Statistics Methods

##### `getRegistryStats()`
Get comprehensive registry statistics.

```javascript
const stats = await registry.getRegistryStats();
console.log('Total containers:', stats.totalContainers);
console.log('Total size:', stats.totalSize);
console.log('Active sessions:', stats.activeSessions);
console.log('Download count:', stats.downloadCount);
```

##### `getPerformanceMetrics()`
Get performance and efficiency metrics.

```javascript
const metrics = await registry.getPerformanceMetrics();
console.log('Average response time:', metrics.averageResponseTime);
console.log('Throughput:', metrics.throughput);
console.log('Cache hit rate:', metrics.cacheHitRate);
console.log('Error rate:', metrics.errorRate);
```

##### `getUsageStatistics()`
Get detailed usage analytics.

```javascript
const usage = await registry.getUsageStatistics();
console.log('Downloads today:', usage.downloadsToday);
console.log('Data transferred:', usage.dataTransferred);
console.log('Peak users:', usage.peakConcurrentUsers);
console.log('Popular containers:', usage.popularContainers);
```

##### `getHealthMetrics()`
Get system health and status metrics.

```javascript
const health = await registry.getHealthMetrics();
console.log('Uptime:', health.uptime);
console.log('Memory usage:', health.memoryUsage);
console.log('CPU usage:', health.cpuUsage);
console.log('Tunnel status:', health.tunnelStatus);
```

##### `getHistoricalAnalysis(timeRange)`
Get historical trends and analysis.

```javascript
const analysis = await registry.getHistoricalAnalysis('24h');
console.log('Usage trends:', analysis.usageTrends);
console.log('Peak times:', analysis.peakTimes);
console.log('Growth rate:', analysis.growthRate);
```

##### `exportStatistics(format)`
Export statistics in various formats.

```javascript
// Export as JSON
const jsonStats = await registry.exportStatistics('json');

// Export as CSV
const csvStats = await registry.exportStatistics('csv');

// Export summary report
const report = await registry.exportStatistics('report');
```

#### Events

The registry emits comprehensive events for monitoring and integration:

```javascript
// Core Events
registry.on('server:started', (info) => {
  console.log('Registry started:', info.port, info.tunnelUrl);
});

registry.on('container:added', (container) => {
  console.log('Container added:', container.name);
});

registry.on('container:removed', (container) => {
  console.log('Container removed:', container.name);
});

// Download & Transfer Events
registry.on('download:started', (stats) => {
  console.log('Download started:', stats.containerName);
});

registry.on('download:progress', (stats) => {
  console.log(`Download progress: ${stats.progress}% (${stats.speed})`);
});

registry.on('download:completed', (stats) => {
  console.log('Download completed:', stats.transferTime);
});

// Batch Operation Events
registry.on('batch:started', (info) => {
  console.log(`Batch operation started: ${info.operation} (${info.count} items)`);
});

registry.on('batch:progress', (progress) => {
  console.log(`Batch progress: ${progress.completed}/${progress.total}`);
});

registry.on('batch:completed', (result) => {
  console.log(`Batch completed: ${result.successful} successful, ${result.failed} failed`);
});

// Auto-Discovery Events
registry.on('discovery:started', (info) => {
  console.log('Auto-discovery started:', info.engines);
});

registry.on('discovery:found', (containers) => {
  console.log(`Discovered ${containers.length} containers`);
});

// Analytics Events
registry.on('stats:updated', (stats) => {
  console.log('Statistics updated:', stats.timestamp);
});

registry.on('analytics:threshold', (alert) => {
  console.log('Analytics threshold reached:', alert.metric, alert.value);
});

// System Events
registry.on('tunnel:established', (info) => {
  console.log('Tunnel connected:', info.publicUrl);
});

registry.on('health:check', (status) => {
  console.log('Health check:', status.overall);
});

registry.on('error', (error) => {
  console.error('Registry error:', error.message);
});
```

#### Container Download Completion Events

The registry provides granular container download tracking with component-level events:

```javascript
// Container-level events (aggregated from all components)
registry.on('container:download:started', (info) => {
  console.log(`Container download started: ${info.containerName} (${info.totalComponents} components)`);
});

registry.on('container:download:progress', (progress) => {
  console.log(`Container progress: ${progress.containerName} ${progress.progress}% (${progress.completedComponents}/${progress.totalComponents})`);
});

registry.on('container:download:completed', (info) => {
  console.log(`Container download completed: ${info.containerName} (${info.totalSize} bytes in ${info.downloadTime}ms)`);
});

// Component-level events (manifest, config, layers)
registry.on('container:manifest:started', (info) => {
  console.log(`Manifest download started: ${info.containerName}`);
});

registry.on('container:manifest:completed', (info) => {
  console.log(`Manifest download completed: ${info.containerName}`);
});

registry.on('container:config:started', (info) => {
  console.log(`Config download started: ${info.containerName}`);
});

registry.on('container:config:completed', (info) => {
  console.log(`Config download completed: ${info.containerName}`);
});

// Layer-specific events (with layer numbers)
registry.on('container:layer:started', (info) => {
  console.log(`Layer ${info.layerIndex} download started: ${info.containerName}`);
});

registry.on('container:layer:completed', (info) => {
  console.log(`Layer ${info.layerIndex} download completed: ${info.containerName}`);
});

// Special milestone events
registry.on('container:layers:completed', (info) => {
  console.log(`All ${info.totalLayers} layers completed: ${info.containerName}`);
});

// Generic component events (catch-all for any component type)
registry.on('container:component:progress', (info) => {
  console.log(`Component ${info.componentId} progress: ${info.progress}%`);
});
```

#### Container Download Status API

Query container download status and component information:

```javascript
// Get all container download statuses
const downloads = await registry.getContainerDownloads();

// Get specific container status
const status = await registry.getContainerDownloadStatus('my-container');

// Get component inventory (discover what components exist)
const inventory = await registry.getContainerComponentInventory('my-container');
console.log(`Container has ${inventory.componentTypes.layerCount} layers`);
console.log('Available components:', inventory.components);

// Get simplified component list
const componentList = await registry.getContainerComponentList('my-container');
console.log('Layer indices:', componentList.layerIndices); // [0, 1, 2]
console.log('Max layer:', componentList.maxLayerIndex); // 2

// Get component-specific status
const manifestStatus = await registry.getContainerComponentStatus('my-container', 'manifest');
const configStatus = await registry.getContainerComponentStatus('my-container', 'config');
const allLayers = await registry.getContainerComponentStatus('my-container', 'layer');
const specificLayer = await registry.getContainerComponentStatus('my-container', 'layer', 2);

// Get layer-specific status summary
const layerStatus = await registry.getLayerDownloadStatus('my-container');
console.log(`Layers: ${layerStatus.completedLayers}/${layerStatus.totalLayers} completed`);

// Get active downloads only
const active = await registry.getActiveContainerDownloads();

// Setup container download tracking
await registry.setupContainerDownloadTracking('my-container', 'my-app', ['manifest', 'config', 'layer-0', 'layer-1']);
```

##### Component Inventory Response Format

```javascript
// Container component inventory
{
  containerId: 'my-container',
  containerName: 'my-app',
  totalComponents: 5,
  componentTypes: {
    hasManifest: true,
    hasConfig: true,
    layerCount: 3
  },
  components: {
    manifest: {
      componentId: 'manifest',
      filename: 'manifest.json',
      size: 1456,
      mediaType: 'application/vnd.docker.distribution.manifest.v2+json',
      description: 'Container manifest with layer and config references'
    },
    config: {
      componentId: 'config',
      filename: 'config.json',
      size: 7234,
      mediaType: 'application/vnd.docker.container.image.v1+json',
      description: 'Container configuration and metadata'
    },
    layers: [
      {
        componentId: 'layer-0',
        layerIndex: 0,
        filename: 'layer-0.tar',
        size: 52428800,
        mediaType: 'application/vnd.docker.image.rootfs.diff.tar',
        description: 'Filesystem layer 0'
      }
      // ... additional layers
    ]
  },
  downloadPaths: {
    manifest: '/containers/my-app/manifest.json',
    config: '/containers/my-app/config.json',
    layers: ['/containers/my-app/layer-0.tar', '/containers/my-app/layer-1.tar']
  },
  totalSize: 55543808,
  estimatedDownloadTime: 55543
}
```

## ⚙️ Configuration Examples

### Basic Multi-Container Registry

```javascript
const registry = new TunneledContainerRegistry({
  // KĀDI tunnel is the default — no configuration needed
  enableAnalytics: true,
  downloadTracking: true
});

await registry.start();

// Add multiple containers with auto-discovery
const discovered = await registry.autoDiscoverContainers({
  engines: ['docker'],
  limit: 5
});
await registry.addContainers(discovered);
```

### Professional Analytics Setup

```javascript
const registry = new TunneledContainerRegistry({
  tunnelService: 'ngrok',
  tunnelOptions: {
    authtoken: process.env.NGROK_TOKEN,
    region: 'us',
    subdomain: 'my-company-registry'  // Custom subdomain
  },
  credentials: {
    expiry: 3600  // 1 hour access
  },
  enableAnalytics: true,
  downloadTracking: true,
  autoDiscovery: {
    enabled: true,
    engines: ['docker', 'podman'],
    filters: {
      minSize: '10MB',
      excludePatterns: ['scratch', 'test-*']
    }
  }
});

// Monitor analytics in real-time
registry.on('stats:updated', async () => {
  const stats = await registry.getRegistryStats();
  console.log('Current usage:', stats);
});
```
    region: 'us',
    subdomain: 'my-company-registry'  // Custom subdomain
  },
  credentials: {
    expiry: 3600  // 1 hour access
  }
});
```

### Private Registry (No Public Access)

```javascript
const registry = new TunneledContainerRegistry({
  tunnelService: 'none',  // Local network only
  port: 5000
});

// Access via http://localhost:5000 or LAN IP
```

### Auto-Shutdown for CI/CD

```javascript
const registry = new TunneledContainerRegistry({
  autoShutdown: true,
  shutdownOptions: {
    completionDelay: 60000,   // Wait 1 minute after last download
    maxTotalTime: 1800000     // Max 30 minutes total
  }
});
```

## 🎭 Use Cases

### 1. **Multi-Container Development Sharing**
Share entire development environments with team members instantly:

```javascript
// Developer's machine - discover and share all project containers
const registry = new TunneledContainerRegistry({
  enableAnalytics: true,
  autoDiscovery: { enabled: true }
});

await registry.start();

// Auto-discover project containers
const projectContainers = await registry.autoDiscoverContainers({
  engines: ['docker'],
  filter: { excludePatterns: ['scratch', 'test-*'] }
});

// Batch add all discovered containers
await registry.addContainers(projectContainers);

const commands = await registry.getDockerCommands();
// Share login and pull commands for entire environment
```

### 2. **CI/CD Multi-Service Deployment**
Distribute multiple build artifacts to deployment environments:

```javascript
// CI pipeline - batch process build artifacts
const registry = new TunneledContainerRegistry({
  autoShutdown: true,
  credentials: { expiry: 900 },  // 15 minutes
  enableAnalytics: true,
  downloadTracking: true
});

await registry.start();

// Add multiple services from build
const services = [
  { name: `api-service:${BUILD_ID}` },
  { name: `web-app:${BUILD_ID}` },
  { name: `worker:${BUILD_ID}` }
];
await registry.addContainers(services);

// Monitor deployment analytics
const stats = await registry.getUsageStatistics();
console.log('Deployment metrics:', stats);
```

### 3. **Analytics-Driven Container Distribution**
Monitor and optimize container sharing with detailed analytics:

```javascript
const registry = new TunneledContainerRegistry({
  enableAnalytics: true,
  downloadTracking: true
});

// Set up analytics monitoring
registry.on('download:completed', async (stats) => {
  const performance = await registry.getPerformanceMetrics();
  if (performance.averageResponseTime > 5000) {
    console.warn('Performance degradation detected');
  }
});

// Generate usage reports
const analysis = await registry.getHistoricalAnalysis('7d');
const report = await registry.exportStatistics('report');
```

### 4. **Cross-Platform Auto-Discovery**
Automatically discover and share containers across different platforms:

```javascript
// Works with both Docker and Podman - discovers everything
const registry = new TunneledContainerRegistry({
  preferredEngine: 'auto',
  autoDiscovery: {
    enabled: true,
    engines: ['docker', 'podman'],
    filters: {
      minSize: '1MB',
      maxAge: '30d'
    }
  }
});

await registry.start();

// Auto-discover all available containers
const allContainers = await registry.autoDiscoverContainers();
console.log(`Found ${allContainers.length} containers across all engines`);

// Batch add top containers
await registry.addContainers(allContainers.slice(0, 10));
```

### 5. **Production Monitoring & Analytics**
Create monitored registries with comprehensive analytics for production use:

```javascript
const registry = new TunneledContainerRegistry({
  enableAnalytics: true,
  downloadTracking: true,
  autoShutdown: true,
  shutdownOptions: { maxTotalTime: 3600000 },  // 1 hour max
});

// Real-time monitoring
registry.on('analytics:threshold', (alert) => {
  if (alert.metric === 'concurrent_users' && alert.value > 100) {
    console.warn('High usage detected - consider scaling');
  }
});

// Periodic health checks
setInterval(async () => {
  const health = await registry.getHealthMetrics();
  const performance = await registry.getPerformanceMetrics();
  
  console.log('Health:', health.overall);
  console.log('Performance:', performance.throughput, 'req/min');
}, 30000);
```

## 🔧 Requirements

### System Requirements
- **Node.js**: 20.0.0 or higher
- **Operating System**: Windows, macOS, Linux
- **Internet**: Required for tunnel services
- **Storage**: Temporary disk space for container exports

### Container Engines (Optional)
- **Docker**: 20.0.0+ (for real container export)
- **Podman**: 3.0.0+ (alternative to Docker)
- **Note**: Mock containers work without any container engine

### Tunnel Service Requirements

#### KĀDI (Default)
- **Requirements**: `frpc` binary in PATH (included with KĀDI agent)
- **Signup**: KĀDI tunnel credentials (set via `KADI_TUNNEL_TOKEN` env var)
- **Benefits**: Fast connection (~500ms), reliable, HTTPS with auto TLS
- **Configuration**: Set `KADI_TUNNEL_*` environment variables, or configure via `config.yml` + vault (see `@kadi.build/tunnel-services` docs)

##### WSS Transport (v0.2.1+)

The KĀDI tunnel now uses **WSS (WebSocket Secure)** transport by default (port 443)
instead of direct TCP (port 7000). This resolves connection failures on enterprise
and campus networks that block non-standard ports.

| Env Var | Values | Default |
|---------|--------|---------|
| `KADI_TUNNEL_TRANSPORT` | `'wss'` or `'tcp'` | `'wss'` |
| `KADI_TUNNEL_WSS_HOST` | hostname string | — |

To fall back to legacy TCP: `KADI_TUNNEL_TRANSPORT=tcp`

#### Serveo (Free)
- **Requirements**: SSH client (pre-installed on most systems)
- **Signup**: Not required
- **Limitations**: Shared domains, no custom subdomains guaranteed

#### ngrok (Professional)
- **Requirements**: ngrok account and authtoken
- **Setup**: 
  ```bash
  export NGROK_TOKEN="your-token-here"
  ```
- **Benefits**: Custom subdomains, regions, enhanced reliability

#### localtunnel (Free)
- **Requirements**: Internet access only
- **Limitations**: Shared domains, occasional downtime

## 📊 Testing & Quality

### Comprehensive Test Suite
- **217+ Tests**: Complete coverage of all functionality including advanced features
- **Real-World Validation**: Working demo with public internet access
- **Cross-Platform**: Tested on macOS, Linux, and Windows
- **Engine Compatibility**: Docker 20+, Podman 3+, and mock containers
- **Analytics Validation**: Statistics accuracy and performance metrics testing

### Run Tests

```bash
# Run all tests
npm test

# Run specific test phases
npm run test:phase1  # Core functionality
npm run test:phase2  # Engine detection
npm run test:phase3  # Container export
npm run test:phase4  # Registry & API
npm run test:phase5  # Tunnel integration
npm run test:phase6  # Advanced features & analytics

# Run individual test suites
npm run test:constructor
npm run test:config
npm run test:validation
npm run test:errors
npm run test:multi-container
npm run test:auto-discovery
npm run test:download-monitoring
npm run test:statistics
```

### Test Results
Tests produce detailed results in the `test_results/` directory with JSON logs for CI/CD integration.

## 🔍 Validation Demo

Experience the complete functionality with our comprehensive validation demo:

```bash
cd demos/validation-demo
npm install

# Basic demo
npm start

# Full feature demo with analytics
npm run demo:phase6

# Interactive mode
npm run demo:interactive
```

**The demo validates:**
- ✅ Auto-detection of Docker and Podman engines
- ✅ Multi-container batch processing
- ✅ Container auto-discovery across engines
- ✅ Real container export and OCI compliance
- ✅ Public tunnel establishment and URL generation
- ✅ Docker Registry v2 API compatibility
- ✅ Authentication and access control
- ✅ Command generation for multiple containers
- ✅ Real-time download monitoring and progress tracking
- ✅ Comprehensive analytics and statistics collection
- ✅ Performance metrics and usage analytics

## 🛠️ Troubleshooting

### Common Issues

#### "No container engines detected"
```javascript
// Solution: Specify mock containers
await registry.addContainer({
  type: 'mock',
  name: 'test-app',
  tag: 'latest'
});
```

#### "Tunnel connection failed"
```javascript
// Solution: Try different tunnel service
const registry = new TunneledContainerRegistry({
  tunnelService: 'serveo'  // Alternative to default KĀDI tunnel
});
```

#### "Port already in use"
```javascript
// Solution: Use random port
const registry = new TunneledContainerRegistry({
  port: 0  // Automatically assigns available port
});
```

### Debug Mode

Enable detailed logging for troubleshooting:

```javascript
const registry = new TunneledContainerRegistry({
  logLevel: 'debug',
  enableLogging: true
});
```

### Error Handling

The library provides structured error handling:

```javascript
import { RegistryError } from 'tunneled-container-registry';

try {
  await registry.start();
} catch (error) {
  if (error instanceof RegistryError) {
    console.log('Error Code:', error.code);
    console.log('Message:', error.message);
    console.log('Details:', error.details);
  }
}
```

## 📜 License

MIT License - See `package.json` for details.

## 🤝 Contributing

Contributions are welcome! This project maintains high quality standards:

1. **Tests**: All changes must include tests
2. **Documentation**: Update README for API changes  
3. **Code Quality**: Follow existing patterns and conventions
4. **Real-World Testing**: Validate with the demo

### Development Setup

```bash
git clone <repository-url>
cd container-registry-ability
npm install
npm test  # Ensure all tests pass
```

### Project Structure
```
tunneled-container-registry/
├── src/
│   ├── TunneledContainerRegistry.js    # Main implementation
│   ├── errors/                         # Error handling
│   ├── utils/                          # Utilities
│   └── types/                          # TypeScript definitions
├── test/
│   ├── phase1-5/                       # Comprehensive test suites
│   └── utils/                          # Test utilities
├── demos/
│   └── validation-demo/                # Real-world validation
└── docs/                               # Additional documentation
```

## 🌟 Why Tunneled Container Registry?

### ✅ **Production Ready**
- Battle-tested with 217+ comprehensive tests including advanced features
- Real-world validation with public internet access
- Professional error handling and comprehensive monitoring
- Analytics-driven performance optimization

### ✅ **Advanced Multi-Container Management**
- Batch processing with progress tracking
- Auto-discovery across multiple container engines
- Intelligent filtering and container selection
- Comprehensive statistics and usage analytics

### ✅ **Zero Infrastructure**
- No need for cloud registries or servers
- Works with existing container engines
- Temporary and secure by design
- Automatic resource cleanup and management

### ✅ **Developer Friendly**
- Copy-paste commands that just work
- Auto-detection of available tools
- Rich event system for comprehensive integration
- Real-time monitoring and progress tracking

### ✅ **Cross-Platform & Multi-Engine**
- Windows, macOS, Linux support
- Docker and Podman compatibility
- Multiple tunnel service options
- Seamless multi-container operations

### ✅ **Analytics & Insights**
- Comprehensive usage statistics
- Performance metrics and optimization insights
- Historical analysis and trend tracking
- Export capabilities for reporting and integration

### ✅ **Secure by Default**
- Temporary credentials with auto-expiration
- Encrypted tunnel connections
- Automatic resource cleanup
- Access control and permissions management

---

**Ready to share containers instantly?** Try the [validation demo](#validation-demo) or jump into the [Quick Start](#quick-start) guide!