npm package: @route-optimization/optimizer
Description: Route optimization integration with Google Route Optimization API and route-optimize-hono backend
Author: ks-arm
Latest version: 1.0.4

# @route-optimization/optimizer

Route optimization package with support for mock optimization and backend API integration.

## Features

- 🎯 **Mock Optimization** - Realistic nearest neighbor + 2-opt algorithm for development
- 🌐 **Backend Integration** - Connect to route-optimize-hono or Google Route Optimization API
- 📊 **Real-time Status** - Track optimization progress with status updates
- ⚡ **Fast & Efficient** - Optimized algorithms for quick results
- 🔧 **Configurable** - Flexible vehicle and constraint configuration
- 📦 **Tiny Bundle** - Minimal dependencies, tree-shakeable

## Installation

```bash
npm install @route-optimization/optimizer @route-optimization/core
# or
pnpm add @route-optimization/optimizer @route-optimization/core
# or
yarn add @route-optimization/optimizer @route-optimization/core
```

## Quick Start

### Basic Usage (Mock Mode)

```typescript
import { RouteOptimizer } from '@route-optimization/optimizer';
import type { Stop } from '@route-optimization/core';

// Create optimizer instance (mock mode by default)
const optimizer = new RouteOptimizer({
  mockMode: true,
});

// Define stops
const stops: Stop[] = [
  { id: '1', location: { lat: 13.7563, lng: 100.5018 }, name: 'Bangkok' },
  { id: '2', location: { lat: 13.765, lng: 100.538 }, name: 'Sukhumvit' },
  { id: '3', location: { lat: 13.7467, lng: 100.5348 }, name: 'Silom' },
];

// Optimize route
const result = await optimizer.optimize({ stops });

console.log('Optimized route:', result.routes[0]);
console.log('Total distance:', result.metrics.totalDistance, 'meters');
console.log('Total duration:', result.metrics.totalDuration, 'seconds');
```

### With Backend API

```typescript
const optimizer = new RouteOptimizer({
  mockMode: false,
  backend: {
    apiUrl: 'https://your-backend.com/api',
    apiToken: 'your-api-token',
    timeout: 30000,
  },
});

const result = await optimizer.optimize({
  stops,
  vehicle: {
    capacity: [{ type: 'weight', value: 1000, unit: 'kg' }],
    costPerKm: 5,
    costPerHour: 50,
  },
  constraints: {
    mode: 'balanced',
    considerTraffic: true,
  },
});
```

### Track Optimization Progress

```typescript
// Subscribe to status updates
const unsubscribe = optimizer.onStatusChange((status) => {
  console.log(`Status: ${status.status}, Progress: ${status.progress}%`);
  console.log(`Message: ${status.message}`);
});

// Optimize
await optimizer.optimize({ stops });

// Cleanup
unsubscribe();
```

## API Reference

### `RouteOptimizer`

Main optimizer class for route optimization.

#### Constructor

```typescript
new RouteOptimizer(config?: OptimizerConfig)
```

**Config Options:**

- `mockMode?: boolean` - Use mock optimization (default: true)
- `backend?: BackendConfig` - Backend API configuration
- `defaultVehicle?: VehicleConfig` - Default vehicle settings
- `defaultConstraints?: OptimizationConstraints` - Default constraints

#### Methods

##### `optimize(request: OptimizationRequest): Promise<OptimizationResult>`

Optimize a route with given stops.

```typescript
const result = await optimizer.optimize({
  stops: [...],
  vehicle: { /* vehicle config */ },
  constraints: { /* constraints */ },
  mockMode: true, // Override config
});
```

##### `onStatusChange(listener: (status: OptimizationStatus) => void): () => void`

Subscribe to optimization status updates. Returns unsubscribe function.

```typescript
const unsubscribe = optimizer.onStatusChange((status) => {
  console.log(status.status, status.progress);
});
```

##### `getStatus(): OptimizationStatus`

Get current optimization status.

##### `updateConfig(config: Partial<OptimizerConfig>): void`

Update optimizer configuration.

### Types

#### `OptimizationRequest`

```typescript
interface OptimizationRequest {
  stops: Stop[];
  vehicle?: VehicleConfig;
  constraints?: OptimizationConstraints;
  mockMode?: boolean;
}
```

#### `OptimizationResult`

```typescript
interface OptimizationResult {
  routes: Route[];
  metrics: OptimizationMetrics;
  request: OptimizationRequest;
  computeTime: number;
}
```

#### `OptimizationMetrics`

```typescript
interface OptimizationMetrics {
  totalDistance: number; // meters
  totalDuration: number; // seconds
  totalCost?: number;
  stopsServed: number;
  routeCount: number;
  improvement?: number; // percentage
}
```

#### `VehicleConfig`

```typescript
interface VehicleConfig {
  startLocation?: { lat: number; lng: number };
  endLocation?: { lat: number; lng: number };
  capacity?: CapacityConstraint[];
  costPerKm?: number;
  costPerHour?: number;
  maxRouteDuration?: number;
  maxRouteDistance?: number;
}
```

#### `OptimizationConstraints`

```typescript
interface OptimizationConstraints {
  timeWindows?: boolean;
  considerTraffic?: boolean;
  mode?: 'fastest' | 'shortest' | 'balanced';
  allowMultipleRoutes?: boolean;
}
```

## Mock Optimization Algorithm

The mock optimizer uses a realistic nearest neighbor algorithm with 2-opt improvement:

1. **Nearest Neighbor**: Start from depot, visit nearest unvisited stop iteratively
2. **2-opt Improvement**: Eliminate route crossings by reversing segments
3. **Distance Calculation**: Haversine formula for accurate distances
4. **Metrics**: Realistic duration (30 km/h avg) and cost calculations

This provides realistic optimization for development and testing without external API calls.

## Backend Integration

### route-optimize-hono Backend

Configure to use your route-optimize-hono backend:

```typescript
const optimizer = new RouteOptimizer({
  mockMode: false,
  backend: {
    apiUrl: 'http://localhost:3000/api',
    apiToken: process.env.API_TOKEN,
  },
});
```

### Expected Backend API Format

**POST /optimize**

Request:

```json
{
  "stops": [{ "id": "1", "location": { "lat": 13.7563, "lng": 100.5018 }, "name": "Stop 1" }],
  "vehicle": { "capacity": [{ "type": "weight", "value": 1000 }] },
  "constraints": { "mode": "balanced" }
}
```

Response:

```json
{
  "routes": [...],
  "metrics": {
    "totalDistance": 15000,
    "totalDuration": 1800,
    "stopsServed": 5,
    "routeCount": 1
  },
  "computeTime": 1234
}
```

## Examples

See the [examples directory](../../examples/) for complete implementations:

- **React**: `examples/react-example`
- **Vue 3**: `examples/vue3-basic`
- **Vanilla JS**: `examples/vanilla-basic`

## License

MIT © ks-arm