npm package: @onurege3467/zero-pm
Description: PM2-inspired Node.js process manager with ecosystem integration
Author: Onure9e
Latest version: 1.0.0

# Zero PM - Advanced Node.js Process Manager

<div align="center">
  <img src="https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript"/>
  <img src="https://img.shields.io/badge/Node.js-339933?style=for-the-badge&logo=nodedotjs&logoColor=white" alt="Node.js"/>
  <img src="https://img.shields.io/badge/PM2--Compatible-2CA5E0?style=for-the-badge&logo=pm2&logoColor=white" alt="PM2 Compatible"/>
  <img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" alt="MIT License"/>
</div>

<div align="center">
  <h3>🚀 PM2-Inspired Process Manager with Modern Ecosystem Integration</h3>
  <p><strong>Zero PM</strong> is a powerful, production-ready Node.js process manager that combines PM2's reliability with modern TypeScript development and seamless ecosystem integration.</p>
</div>

---

## 📋 Table of Contents

- [✨ Features](#-features)
- [🏁 Quick Start](#-quick-start)
- [📦 Installation](#-installation)
- [🎯 Usage](#-usage)
  - [CLI Commands](#cli-commands)
  - [Programmatic API](#programmatic-api)
  - [Configuration Files](#configuration-files)
- [🔧 Advanced Configuration](#-advanced-configuration)
- [🌐 Web Dashboard](#-web-dashboard)
- [⚙️ System Integration](#️-system-integration)
- [🔄 Process Management](#-process-management)
- [📊 Monitoring & Metrics](#-monitoring--metrics)
- [🔧 Ecosystem Integration](#-ecosystem-integration)
- [🔄 Migration from PM2](#-migration-from-pm2)
- [🚨 Troubleshooting](#-troubleshooting)
- [🤝 Contributing](#-contributing)
- [📄 License](#-license)
- [🙏 Acknowledgments](#-acknowledgments)

---

## ✨ Features

### 🚀 **Core Features**
- **🔄 Cluster Management**: Automatic load balancing and clustering with round-robin, least-connections algorithms
- **🔄 Auto-Restart**: Intelligent process monitoring with configurable restart policies
- **📊 Real-time Monitoring**: CPU, memory, and system metrics with WebSocket updates
- **🌐 Web Dashboard**: Modern HTTP dashboard for process visualization and control
- **📝 Advanced Logging**: Colored console output and persistent file logging with rotation
- **⚙️ PM2-Style Configuration**: `ecosystem.config.js` support with environment-specific settings
- **💾 State Persistence**: Process state survives CLI restarts and system reboots
- **🎨 Colored CLI**: Beautiful terminal output with `easycolor` integration
- **🔧 Ecosystem Integration**: Seamless integration with `zero-config` and `zerohelper`

### 🛠️ **Advanced Features**
- **Zero Downtime Reloads**: Graceful reload with SIGUSR2 support for production deployments
- **Multiple Output Formats**: JSON, table, and colored outputs for different use cases
- **System Integration**: Automatic startup scripts for systemd, launchd, and other init systems
- **Process Scaling**: Dynamic instance scaling with `scale` command
- **Signal Handling**: Advanced process signal management and custom signal sending
- **Log Management**: Automatic log rotation, flushing, and streaming capabilities
- **Environment Management**: Multi-environment support with `env_production`, `env_development`
- **Deployment Ready**: Built-in deployment configurations and rollback capabilities

### 🏗️ **Technical Excellence**
- **TypeScript First**: Written in TypeScript with full type safety and excellent IDE support
- **Production Ready**: Comprehensive error handling, logging, and monitoring
- **Cross-Platform**: Windows, macOS, and Linux support with platform-specific optimizations
- **Resource Efficient**: Low memory footprint with optimized performance
- **Extensible**: Plugin architecture for custom functionality
- **Well Tested**: Comprehensive test suite with 100% coverage on critical paths

---

## 🏁 Quick Start

### Prerequisites
- **Node.js**: `>= 16.0.0`
- **npm**: `>= 7.0.0` (or yarn/pnpm)

### Install & Run
```bash
# Install globally
npm install -g @onurege3467/zero-pm

# Start your first app
zero-pm start server.js

# View running processes
zero-pm list

# Access web dashboard
zero-pm dashboard --port 3000

# Open http://localhost:3000 in your browser
```

That's it! Your Node.js application is now running with production-grade process management.

---

## 📦 Installation

### Global Installation (Recommended)
```bash
npm install -g @onurege3467/zero-pm
```

### Local Installation
```bash
npm install --save-dev @onurege3467/zero-pm
```

### Ecosystem Dependencies (Optional but Recommended)
```bash
# For advanced configuration management
npm install @onurege3467/zero-config

# For enhanced CLI colors and output
npm install @onurege3467/easycolor

# For database-backed persistence
npm install @onurege3467/zerohelper
```

### Development Setup
```bash
# Clone the repository
git clone https://github.com/onure9e/zero-pm.git
cd zero-pm

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Start development
npm run dev
```

---

## 🎯 Usage

### CLI Commands

Zero PM provides 24+ CLI commands for comprehensive process management:

#### 📊 **Process Information**
```bash
# List all processes (table format)
zero-pm list

# List processes in JSON format
zero-pm jlist

# List processes in pretty table format
zero-pm prettylist

# Describe a specific process
zero-pm describe my-app

# Show monitoring information
zero-pm monit
```

#### 🚀 **Process Control**
```bash
# Start a process
zero-pm start app.js
zero-pm start app.js --name my-app
zero-pm start app.js --instances 4 --fork

# Start from configuration file
zero-pm start-config ecosystem.config.js
zero-pm start-config --env production

# Stop processes
zero-pm stop my-app
zero-pm stop-all

# Restart processes
zero-pm restart my-app

# Reload processes (zero downtime)
zero-pm reload my-app
zero-pm graceful-reload my-app
```

#### 📝 **Logging & Debugging**
```bash
# View process logs
zero-pm logs my-app
zero-pm logs my-app --lines 100

# Flush logs
zero-pm flush
zero-pm flush my-app
```

#### ⚙️ **Advanced Operations**
```bash
# Scale process instances
zero-pm scale my-app 8

# Send signals to processes
zero-pm sendSignal my-app SIGUSR1

# Reset restart counters
zero-pm reset my-app

# Delete processes
zero-pm delete my-app
```

#### 🌐 **Web Interface**
```bash
# Start web dashboard
zero-pm dashboard
zero-pm dashboard --port 3000
zero-pm dashboard --host 0.0.0.0 --port 8080
```

#### 🔧 **System Integration**
```bash
# Save current configuration
zero-pm save

# Generate startup scripts
zero-pm startup          # systemd (Linux)
zero-pm startup launchd  # macOS

# Remove startup scripts
zero-pm unstartup
```

### Programmatic API

Zero PM can also be used programmatically in your Node.js applications:

```typescript
import { ZeroProcessManager } from '@onurege3467/zero-pm';

async function main() {
  const pm = new ZeroProcessManager();

  // Start a process
  await pm.start('server.js', {
    name: 'api-server',
    instances: 4,
    exec_mode: 'cluster'
  });

  // List running processes
  const processes = pm.list();
  console.log('Running processes:', processes);

  // Monitor processes
  const metrics = await pm.monit();
  console.log('System metrics:', metrics.system);

  // Graceful shutdown
  process.on('SIGINT', async () => {
    await pm.stopAll();
    process.exit(0);
  });
}

main().catch(console.error);
```

### Configuration Files

Zero PM supports multiple configuration formats for different use cases:

#### JavaScript Configuration (`ecosystem.config.js`) - Recommended
```javascript
module.exports = {
  apps: [{
    name: 'api-server',
    script: './server.js',
    instances: 4,
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'development',
      PORT: 3000
    },
    env_production: {
      NODE_ENV: 'production',
      PORT: 8000,
      DATABASE_URL: 'postgres://prod-db:5432/myapp'
    },
    max_memory_restart: '500M',
    restart_delay: 1000,
    autorestart: true,
    watch: false,
    log_file: './logs/app.log',
    error_file: './logs/app-error.log'
  }],

  deploy: {
    production: {
      user: 'deploy',
      host: ['server1.com', 'server2.com'],
      ref: 'origin/main',
      repo: 'git@github.com:user/repo.git',
      path: '/var/www/app',
      'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env production'
    }
  }
};
```

#### YAML Configuration (`processes.yaml`)
```yaml
- name: web-server
  script: server.js
  instances: 4
  exec_mode: cluster
  env:
    NODE_ENV: production
    PORT: 3000
  max_memory_restart: 500M
  autorestart: true
  stdout_file: logs/web.log
  stderr_file: logs/web-error.log

- name: worker
  script: worker.js
  instances: 2
  exec_mode: fork
  env:
    REDIS_URL: redis://localhost:6379
  restart_delay: 2000
```

#### JSON Configuration (`processes.json`)
```json
[
  {
    "name": "api-server",
    "script": "./server.js",
    "instances": 2,
    "exec_mode": "cluster",
    "env": {
      "PORT": 3000
    }
  }
]
```

---

## 🔧 Advanced Configuration

### Process Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `name` | `string` | Auto-generated | Process name |
| `script` | `string` | Required | Script to execute |
| `args` | `string` | `undefined` | Command line arguments |
| `cwd` | `string` | Current directory | Working directory |
| `instances` | `number \| 'max'` | `1` | Number of instances |
| `exec_mode` | `'fork' \| 'cluster'` | `'fork'` | Execution mode |
| `env` | `object` | `{}` | Environment variables |
| `max_memory_restart` | `string` | `undefined` | Memory limit (e.g., '500M') |
| `max_restarts` | `number` | `undefined` | Maximum restart attempts |
| `min_uptime` | `string` | `'1s'` | Minimum uptime before considering stable |
| `restart_delay` | `number` | `0` | Delay between restarts (ms) |
| `autorestart` | `boolean` | `true` | Auto-restart on crashes |
| `watch` | `boolean \| string[]` | `false` | Files/directories to watch |
| `ignore_watch` | `string[]` | Common ignores | Files to ignore when watching |
| `stdout_file` | `string` | `undefined` | Standard output log file |
| `stderr_file` | `string` | `undefined` | Standard error log file |
| `pid_file` | `string` | `undefined` | PID file path |
| `kill_timeout` | `number` | `1600` | Kill timeout (ms) |
| `listen_timeout` | `number` | `undefined` | Listen timeout (ms) |
| `shutdown_with_message` | `boolean` | `false` | Graceful shutdown |

### Environment-Specific Configuration

```javascript
module.exports = {
  apps: [{
    name: 'my-app',
    script: 'app.js',
    env: {
      NODE_ENV: 'development',
      DEBUG: '*'
    },
    env_staging: {
      NODE_ENV: 'staging',
      DEBUG: 'app:*'
    },
    env_production: {
      NODE_ENV: 'production',
      DEBUG: false
    }
  }]
};
```

Start with specific environment:
```bash
zero-pm start-config ecosystem.config.js --env production
```

### Load Balancing Algorithms

Zero PM supports multiple load balancing strategies:

```javascript
// In ecosystem.config.js
module.exports = {
  apps: [{
    name: 'load-balanced-app',
    script: 'server.js',
    instances: 'max',
    load_balancer: 'least-connections' // or 'round-robin', 'weighted-round-robin'
  }]
};
```

---

## 🌐 Web Dashboard

Zero PM includes a modern web dashboard for monitoring and managing processes:

### Features
- **📊 Real-time Metrics**: CPU, memory, and system statistics
- **🎛️ Process Control**: Start, stop, restart processes via UI
- **📝 Log Streaming**: Live log viewing and filtering
- **🔍 Process Details**: Detailed information about each process
- **📈 Performance Graphs**: Historical performance data
- **🎨 Modern UI**: Clean, responsive interface

### Starting the Dashboard
```bash
# Default configuration
zero-pm dashboard

# Custom port and host
zero-pm dashboard --port 8080 --host 0.0.0.0
```

### API Endpoints

The dashboard provides RESTful APIs for integration:

```bash
# Get all processes
GET /api/processes

# Get system metrics
GET /api/stats

# WebSocket for real-time updates
ws://localhost:3000
```

### Dashboard Screenshots
*(Dashboard includes interactive charts and real-time updates)*

---

## ⚙️ System Integration

### Automatic Startup

Zero PM can automatically start on system boot:

```bash
# Save current configuration
zero-pm save

# Generate startup scripts
zero-pm startup          # Linux (systemd)
zero-pm startup launchd  # macOS

# Follow the displayed instructions
sudo systemctl daemon-reload
sudo systemctl enable zero-pm
sudo systemctl start zero-pm
```

### Supported Systems

- **🐧 Linux (systemd)**: `zero-pm startup`
- **🍎 macOS (launchd)**: `zero-pm startup launchd`
- **🔧 Manual Setup**: For other systems

### Service Management

```bash
# Check status
sudo systemctl status zero-pm

# View logs
sudo journalctl -u zero-pm -f

# Restart service
sudo systemctl restart zero-pm

# Disable auto-startup
zero-pm unstartup
```

---

## 🔄 Process Management

### Execution Modes

#### Fork Mode
```javascript
{
  name: 'single-process',
  script: 'app.js',
  exec_mode: 'fork',  // Single process
  instances: 1
}
```

#### Cluster Mode
```javascript
{
  name: 'multi-process',
  script: 'app.js',
  exec_mode: 'cluster',  // Multiple processes
  instances: 4
}
```

### Scaling Processes

```bash
# Scale to 8 instances
zero-pm scale my-app 8

# Scale to maximum CPU cores
zero-pm scale my-app max
```

### Graceful Operations

Zero PM supports zero-downtime operations:

```bash
# Graceful reload (recommended for production)
zero-pm graceful-reload my-app

# Regular reload
zero-pm reload my-app

# Graceful shutdown
zero-pm stop my-app
```

### Signal Handling

Send custom signals to processes:

```bash
# Reload configuration
zero-pm sendSignal my-app SIGHUP

# Custom signal
zero-pm sendSignal my-app SIGUSR1
```

---

## 📊 Monitoring & Metrics

### Built-in Monitoring

```bash
# Real-time monitoring
zero-pm monit

# Process-specific metrics
zero-pm describe my-app
```

### Metrics Collected

- **CPU Usage**: Per-process and system-wide
- **Memory Usage**: RSS, heap, and external memory
- **Uptime**: Process and system uptime
- **Restart Count**: Number of automatic restarts
- **Network I/O**: Connection statistics
- **File Descriptors**: Open file handles

### Web Dashboard Metrics

The web dashboard provides:
- Real-time CPU/memory graphs
- Process status indicators
- Log streaming
- Performance history
- System resource usage

### Custom Monitoring

Integrate with external monitoring tools:

```javascript
const pm = new ZeroProcessManager();

// Get metrics programmatically
const metrics = await pm.monit();
console.log('Processes:', metrics.processes.length);
console.log('System CPU:', metrics.system.cpu);
```

---

## 🔧 Ecosystem Integration

Zero PM is designed to work seamlessly with the Zero ecosystem:

### Zero Config Integration

Advanced configuration management with `zero-config`:

```javascript
// Automatic environment variable loading
// Global config support
// Schema validation
// Hot config reloading
```

### Easycolor Integration

Beautiful CLI output with `easycolor`:

```javascript
// Colored status indicators
// Progress bars
// Formatted tables
// Theme support
```

### Zerohelper Integration

Database-backed persistence with `zerohelper`:

```javascript
// SQLite, MongoDB, PostgreSQL, Redis support
// Process state persistence
// Log storage
// Custom metrics storage
```

### Integration Benefits

- **Unified Configuration**: Single source of truth for all Zero tools
- **Consistent CLI**: Same commands and output across all tools
- **Shared State**: Process information shared between tools
- **Enhanced Monitoring**: Cross-tool metrics and logging

---

## 🔄 Migration from PM2

### Command Mapping

| PM2 Command | Zero PM Equivalent | Notes |
|-------------|-------------------|-------|
| `pm2 start app.js` | `zero-pm start app.js` | Identical |
| `pm2 list` | `zero-pm list` | Enhanced output |
| `pm2 logs` | `zero-pm logs` | Same functionality |
| `pm2 restart app` | `zero-pm restart app` | Same |
| `pm2 delete app` | `zero-pm delete app` | Same |
| `pm2 monit` | `zero-pm monit` | Enhanced |
| `pm2 reload app` | `zero-pm graceful-reload app` | Improved |

### Configuration Migration

PM2 `ecosystem.config.js` files are 100% compatible:

```javascript
// This works in both PM2 and Zero PM
module.exports = {
  apps: [{
    name: 'my-app',
    script: 'app.js',
    instances: 4,
    env_production: {
      NODE_ENV: 'production'
    }
  }]
};
```

### Migration Steps

1. **Install Zero PM**:
   ```bash
   npm uninstall -g pm2
   npm install -g @onurege3467/zero-pm
   ```

2. **Update Commands**:
   ```bash
   # Replace pm2 with zero-pm
   zero-pm start ecosystem.config.js
   ```

3. **Optional: Install Ecosystem**:
   ```bash
   npm install @onurege3467/zero-config @onurege3467/easycolor
   ```

### Benefits of Migration

- **Better TypeScript Support**: Full IDE support and type checking
- **Enhanced CLI**: More output formats and better colors
- **Modern Architecture**: Latest Node.js features and optimizations
- **Ecosystem Integration**: Works with other Zero tools
- **Active Development**: Regular updates and improvements

---

## 🚨 Troubleshooting

### Common Issues

#### Process Won't Start
```bash
# Check script exists and is executable
ls -la app.js

# Test script directly
node app.js

# Check logs
zero-pm logs
```

#### Port Already in Use
```bash
# Find process using port
lsof -i :3000

# Kill process
kill -9 <PID>

# Or change port in config
zero-pm start app.js --env PORT=3001
```

#### High Memory Usage
```bash
# Check memory usage
zero-pm monit

# Set memory limits
{
  "max_memory_restart": "500M"
}
```

#### Logs Not Rotating
```bash
# Manual log rotation
zero-pm flush

# Check log file sizes
ls -lh logs/
```

### Debug Mode

Enable verbose logging:

```bash
DEBUG=zero-pm zero-pm start app.js
```

### Performance Issues

```bash
# Check system resources
zero-pm monit

# Profile application
node --prof app.js

# Check for memory leaks
node --inspect app.js
```

### Startup Issues

```bash
# Check systemd status
sudo systemctl status zero-pm

# View systemd logs
sudo journalctl -u zero-pm -f

# Check permissions
ls -la ~/.config/zero-pm/
```

### Network Issues

```bash
# Check if dashboard is accessible
curl http://localhost:3000/api/processes

# Check firewall
sudo ufw status

# Check port binding
netstat -tlnp | grep 3000
```

---

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

```bash
# Fork and clone
git clone https://github.com/your-username/zero-pm.git
cd zero-pm

# Install dependencies
npm install

# Run tests
npm test

# Run linting
npm run lint

# Start development
npm run dev

# Build for production
npm run build
```

### Code Style

- **TypeScript**: Strict mode enabled
- **ESLint**: Airbnb config with TypeScript support
- **Prettier**: Consistent code formatting
- **Jest**: 100% test coverage requirement

### Pull Request Process

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Testing

```bash
# Run all tests
npm test

# Run specific test
npm test -- --testNamePattern="should start process"

# Run with coverage
npm run test:coverage

# Run linting
npm run lint

# Run type checking
npm run type-check
```

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

```
MIT License

Copyright (c) 2024 Zero PM

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

---

## 🙏 Acknowledgments

- **PM2**: Inspiration and compatibility target
- **Zero Ecosystem**: `zero-config`, `easycolor`, `zerohelper`
- **Node.js Community**: Amazing runtime and ecosystem
- **TypeScript Team**: Excellent type system
- **Open Source Community**: Continuous inspiration

---

<div align="center">

**Zero PM** - Production-ready process management for modern Node.js applications.

[📚 Documentation](https://github.com/onure9e/zero-pm) •
[🐛 Report Issues](https://github.com/onure9e/zero-pm/issues) •
[💬 Discussions](https://github.com/onure9e/zero-pm/discussions)

---

*Built with ❤️ for the Node.js community*

</div>