# Auto Node Switch

English | [简体中文](./README.zh-CN.md)

🚀 **Intelligent Node.js Version Manager** - Automatically switch to the appropriate Node.js version for different projects

[![npm version](https://badge.fury.io/js/auto-node-switch.svg)](https://badge.fury.io/js/auto-node-switch)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D16-brightgreen.svg)](https://nodejs.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![GitHub Tests](https://github.com/jiangding1990/auto-node-switch/workflows/test/badge.svg)](https://github.com/jiangding1990/auto-node-switch/actions)
[![Platform Support](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-blue.svg)]()
[![Shell Support](https://img.shields.io/badge/shell-bash%20%7C%20zsh%20%7C%20fish%20%7C%20powershell-green.svg)]()

> **🎉 Latest Version v0.1.4** - Fixed nested directory configuration priority issue, ensuring deep directory configurations take effect accurately!

## ✨ Features

### 🚀 Core Functionality

- 🔄 **Automatic Version Switching**: Automatically switches to the specified Node.js version when entering a project directory and restores when leaving
- 📂 **Multiple Working Directories**: Perfect support for any number of concurrent working directory configurations, accurately matching each project
- 📦 **Multiple Package Managers**: Full support for npm, yarn, pnpm command interception and version management
- 🎯 **Intelligent Version Management**: Support for intelligent version management of commands like `npm run dev`, `yarn start`, `pnpm dev`
- ⚡ **One-Click Stop**: `Ctrl+C` stops services and automatically restores versions

### 🛡️ Security & Stability

- 🔒 **Enterprise-Grade Security**: Built-in path injection protection, version validation, Shell escaping, and multiple security mechanisms
- 💾 **Automatic Backup**: Configuration files are automatically backed up, supporting version history and recovery
- 🔧 **Atomic Operations**: Hook generation uses backup-write-verify atomic operation mode
- 🛠️ **Error Recovery**: Comprehensive error handling and automatic recovery mechanisms

### 🔧 Compatibility

- 🔨 **Version Managers**: Intelligent detection and compatibility with mainstream tools like nvm, n, fnm, nvm-windows, nvs
  - **nvm-Specific Optimization**: Multi-level detection algorithm for shell function characteristics
  - **Cross-Platform Adaptation**: Different detection strategies for Windows and Unix systems
  - **Intelligent Recognition**: Multiple verification mechanisms including environment variables, installation paths, and command detection
- 🐚 **Multi-Shell Support**: Full support for Bash, Zsh, Fish, PowerShell (including Core versions)
- 📁 **Configuration Management**: Modern configuration management compliant with XDG Base Directory specification
- 🌍 **Cross-Platform**: Native support for macOS, Linux, Windows systems

### 🖥️ User Experience

- ✨ **Interactive Interface**: Beautiful terminal interactive interface with keyboard navigation and real-time feedback
- 📋 **Command-Line Mode**: Complete CLI command support, suitable for scripting and automation
- 🎨 **ASCII Art**: Exquisite terminal banners and status prompts
- 📏 **Adaptive Layout**: Automatically adjusts display content based on terminal size

> 📋 **View Changelog**: [CHANGELOG.md](./CHANGELOG.md) - Learn about detailed updates in the latest version

## 📦 Installation

### Global Installation (Recommended)

```bash
npm install -g auto-node-switch
```

### Using yarn

```bash
yarn global add auto-node-switch
```

### Using pnpm

```bash
pnpm add -g auto-node-switch
```

### System Requirements

- **Node.js**: >= 16.0.0
- **Operating System**: macOS, Linux, Windows
- **Supported Shells**:
  - **Unix/Linux**: bash, zsh, fish
  - **Windows**: PowerShell, PowerShell Core
- **Version Managers** (at least one required):
  - **macOS/Linux**: nvm, n, fnm
  - **Windows**: nvm-windows, fnm, nvs

## 🚀 Quick Start

### 1. Interactive Mode (Recommended)

```bash
# Launch interactive interface
auto-node-switch
```

First-time setup will guide you through initial configuration:

1. Select shell type (zsh/bash/fish)
2. Select version management tool (nvm/n/fnm)

### 2. Command-Line Mode

```bash
# View help
auto-node-switch help

# Add project configuration
auto-node-switch add ~/my-project 18.17.1

# Remove project configuration
auto-node-switch remove ~/my-project

# View all configurations
auto-node-switch list

# View configuration file information
auto-node-switch info

# Regenerate Shell Hooks
auto-node-switch regenerate

# Clean all Hooks
auto-node-switch clean
```

## 📋 Detailed Usage

### Adding Project Configuration

#### Method 1: Interactive Mode

1. Run `auto-node-switch`
2. Select "⚡ Quick Setup - Add New Project Configuration"
3. Enter project path
4. Enter Node.js version

#### Method 2: Command-Line Mode

```bash
auto-node-switch add <project-path> <Node.js-version>

# Examples: Configure multiple working directories
auto-node-switch add ~/projects/my-app 18.17.1
auto-node-switch add /Users/username/work/api-server v20.10.0
auto-node-switch add ./frontend 16
auto-node-switch add ~/microservices/user-service 14.21.3
auto-node-switch add ~/legacy-project 12.22.12

# View all configurations
auto-node-switch list
```

### Supported Version Formats

- `18.17.1` - Specific version number
- `v18.17.1` - Version number with v prefix
- `18` - Major version number
- `lts/*` - Latest LTS version (nvm)
- `latest` - Latest version (nvm)

### Version File Support

The tool automatically detects and creates version files:

- `.nvmrc` - nvm configuration file
- `.node-version` - Configuration file for n and other tools
- `package.json` - Reads engines.node field

### Shell Hook Documentation

The tool adds hooks to the respective shell configuration files:

- **Bash**: `~/.bashrc`, `~/.bash_profile`, `~/.profile`
- **Zsh**: `~/.zshrc`
- **Fish**: `~/.config/fish/config.fish`
- **PowerShell**: `$PROFILE` (Microsoft.PowerShell_profile.ps1)

#### Hook Features

- 🎯 **Intelligent Directory Detection**: Automatically switches versions when entering configured project directories
- 🔄 **Automatic Version Restore**: Automatically restores to previous version after command execution
- 📦 **Multiple Package Manager Support**: Full interception of npm, yarn, pnpm commands
- 🛡️ **Safe Execution**: Falls back to native commands if version switching fails
- ⚡ **Performance Optimization**: Intelligent caching and minimal version switching overhead

#### Supported Commands

- `npm install`, `npm run dev`, `npm start`, and all npm commands
- `yarn install`, `yarn start`, `yarn build`, and all yarn commands
- `pnpm install`, `pnpm dev`, `pnpm build`, and all pnpm commands

### Configuration File Management

Configuration file locations (compliant with XDG Base Directory specification):

- **Main Configuration**: `~/.config/node-workdir/config.json`
- **Backup Directory**: `~/.config/node-workdir/backups/`
- **Legacy Path**: `~/.node_workdir_config.json` (automatically migrated)

#### Configuration Features

- 🔄 **Automatic Migration**: Legacy configuration files automatically migrated to new location
- 💾 **Timestamped Backups**: Automatically creates timestamped backups with each modification
- 🔒 **Permission Protection**: Configuration files use secure permission settings
- ⚡ **Intelligent Caching**: Memory caching mechanism improves configuration read performance

## 🛠️ Advanced Configuration

### Configuration File Structure

```json
{
	"shell": "zsh",
	"manager": "nvm",
	"workdirs": [
		{
			"dir": "/Users/username/projects/app1",
			"version": "18.17.1"
		},
		{
			"dir": "/Users/username/projects/app2",
			"version": "20.10.0"
		}
	],
	"lastUpdated": "2024-01-15T10:30:00.000Z"
}
```

### Regenerating Hooks

If shell configuration files are modified or corrupted, you can regenerate:

```bash
# Command-line mode
auto-node-switch regenerate

# Or select "🔄 Regenerate Hooks" in interactive mode
```

### Cleaning Hooks

Completely remove all shell hooks:

```bash
# Command-line mode
auto-node-switch clean

# Or select "🧹 Clean All Hooks" in interactive mode
```

## 🔒 Security Features

- **Path Validation**: Prevents path injection attacks
- **Version Validation**: Validates Node.js version format validity
- **Permission Checks**: Ensures secure access to configuration files
- **Backup Mechanism**: Automatically backs up important configuration files

## 🐛 Troubleshooting

### Common Issues

**1. Hooks Not Working**

```bash
# Reload shell configuration
source ~/.zshrc  # or corresponding configuration file

# Or regenerate hooks
auto-node-switch regenerate
```

**2. Version Manager Detection Failed**

If version manager shows "not installed" but is actually installed:

```bash
# Check environment variables
echo $NVM_DIR        # Unix/Linux/macOS
echo $NVM_HOME       # Windows

# Check default installation paths
ls ~/.nvm/nvm.sh     # Unix/Linux/macOS
ls "C:\nvm\nvm.exe"  # Windows

# Restart terminal or reload configuration
source ~/.zshrc      # or corresponding configuration file
```

**3. Version Switching Failed**

- Ensure version manager is correctly installed and detected by the tool
- Check if the specified Node.js version is installed
- Review terminal output for error messages

**4. Configuration File Issues**

```bash
# View configuration file information
auto-node-switch info

# If needed, delete configuration file and reconfigure
rm ~/.config/node-workdir/config.json

# View backup files
ls -la ~/.config/node-workdir/backups/
```

**5. PowerShell Configuration Issues**

```powershell
# Check PowerShell configuration file
Test-Path $PROFILE

# Reload PowerShell configuration
. $PROFILE

# Or restart PowerShell to apply configuration
```

### Getting Help

```bash
# View all available commands
auto-node-switch help

# View configuration status
auto-node-switch list
auto-node-switch info
```

## 🤝 Contributing

Issues and Pull Requests are welcome!

## 📄 License

MIT License

## 🧪 Testing

### Test Coverage

This project includes a comprehensive testing system ensuring stability and reliability of all functional modules:

#### 🔬 Unit Tests

- **Configuration Management Module**: Configuration file creation, reading, saving, and migration functionality
- **Security Validation Module**: Security mechanisms including path validation, version validation, Shell string escaping
- **Hook Manager**: Hook addition, removal, and management functionality for shell configuration files
- **Integration Tests**: End-to-end testing of complete configuration processes and configuration update flows
- **Error Handling**: Verification of exception handling for SecurityError, ValidationError, and other cases

#### 🚀 Running Tests

```bash
# Run all tests
npm test

# Run unit tests only
npm run test:unit

# Run comprehensive tests
npm run test:comprehensive

# Run all tests (including performance tests)
npm run test:all

# Run tests in parallel (faster)
npm run test:parallel

# Run performance tests
npm run test:performance
```

#### 📊 Test Statistics

- **Unit Tests**: all passed (100%)
- **Comprehensive Functional Tests**: all passed
- **Test Suites**: 6 core modules + 9 functional scenarios
- **Coverage Modules**: Configuration management, security validation, Hook management, multiple working directories, package manager compatibility, boundary condition handling
- **Validation Scenarios**: 60+ complete functional flow tests

#### 🔍 Test Features

- **Environment Isolation**: Uses independent test environment, doesn't affect user configuration
- **Automatic Cleanup**: Automatically cleans up temporary files and configurations after tests complete
- **Cross-Platform**: Supports test execution on macOS, Linux, Windows platforms
- **Native Testing**: Based on Node.js native test API, no additional test framework dependencies required

### CI/CD Continuous Integration

The project is configured with GitHub Actions automated testing:

- **Multi-Platform Testing**: Ubuntu, macOS, Windows
- **Multiple Node Versions**: Node.js 16, 18, 20
- **Automated Workflow**: Code checking → Build → Testing → Release

## 🏗️ Development

### Development Environment Setup

```bash
# Clone the repository
git clone https://github.com/jiangding1990/auto-node-switch.git
cd auto-node-switch

# Install dependencies
npm install

# Development mode (watch for file changes)
npm run dev

# Build project
npm run build

# Run tests
npm test

# Code checking and formatting
npm run lint
npm run lint:fix

# Test CLI locally
npm run start
# or
node dist/cli.js
```

### Project Structure

```
auto-node-switch/
├── source/                 # TypeScript source code
│   ├── app.tsx            # React/Ink main app component
│   ├── cli.tsx            # CLI entry file
│   └── lib/               # Core modules
│       ├── config.ts      # Configuration management
│       ├── security.ts    # Security validation
│       ├── hook-manager.ts # Hook manager
│       ├── version-detector.ts # Version detection
│       ├── ascii-art.ts   # Terminal ASCII art
│       ├── shell-configs/ # Hook templates for each shell
│       ├── template-engine.ts # Hook template rendering engine
│       └── package-manager-detector.ts # Package manager detection
├── dist/                  # Compiled JavaScript code
├── tests/                 # Test files
│   ├── unit-tests.mjs     # Unit tests
│   ├── comprehensive-test.sh # Comprehensive test script
│   └── run-tests.sh       # Test runner script
├── .github/workflows/     # GitHub Actions CI/CD
└── package.json           # Project configuration
```

### Code Quality

- **TypeScript**: Strict type checking ensures code quality
- **ESLint v9**: Modern code style and quality checking using custom rule configuration
- **Prettier**: Automatic code formatting
- **Complexity Control**: Function complexity ≤20, nesting depth ≤4
- **Secure Coding**: Input validation, Shell escaping, path security, etc.

### Release Process

```bash
# Version update
npm version patch|minor|major

# Build and test
npm run prepublishOnly

# Publish to npm
npm publish
```
