npm package: @piiqtechnologies/doctor
Description: A CLI tool to diagnose developer local environment, check for AWS CLI installation, profiles, etc.
Author: peek-tech
Latest version: 2.0.1

# Peek Doctor Commands

A comprehensive CLI tool for diagnosing developer local environments and providing development utilities for AWS-based projects.

## Installation

```bash
# Install globally
npm install -g @piiqtechnologies/doctor

# Or use with npx
npx @piiqtechnologies/doctor <command>

# Or use locally in your project
yarn add @piiqtechnologies/doctor
```

## Commands Overview

| Command | Description | Status |
|---------|-------------|--------|
| `diagnose` | Run diagnostic checks on your local environment | ✅ |
| `cdk-diff` | Run CDK diff on a given template path | ✅ |
| `new-app` | Create a new app from template | ✅ |
| `invoke` | Invoke a Lambda function locally | ✅ |
| `api-gateway` | Start API Gateway emulator | ✅ |

---

## 🔍 Diagnose

Run comprehensive diagnostic checks on your local development environment.

### Usage

```bash
doctor diagnose
```

### What it checks

- **Node.js Version**: Ensures you're running a compatible Node.js version (≥20.0.0)
- **AWS CLI**: Verifies AWS CLI installation and version
- **AWS Profiles**: Checks for required AWS profiles:
  - `peek-root` - Root AWS credentials
  - `peek-dev` - Development environment profile
  - `peek-prod` - Production environment profile
- **AWS STS**: Validates AWS credentials and permissions
- **GitHub NPM Token**: Checks for `NPM_GH_TOKEN` environment variable
- **VPN Connection**: Verifies VPN connectivity to internal services

### Auto-fix capabilities

The diagnose command can automatically fix some issues:
- Configure AWS profiles with proper credentials
- Set up profile relationships and role assumptions
- Guide you through credential setup

### Example Output

```
✅ Node.js version: v20.10.0 is compatible with required version 20.0.0
✅ AWS CLI is installed (aws-cli/2.15.0)
✅ AWS peek-root is installed
✅ AWS peek-dev is installed
✅ AWS peek-prod is installed
✅ Github NPM Token is set
✅ VPN Connection is established
```

---

## 🔄 CDK Diff

Run CDK diff on a given template path with enhanced output and filtering.

### Usage

```bash
# Basic usage
doctor cdk-diff

# With custom template path
doctor cdk-diff --template-path ./my-cdk-out

# Short form
doctor cdk-diff -t ./my-cdk-out
```

### Options

| Option | Description | Default |
|--------|-------------|---------|
| `-t, --template-path <path>` | Template path to diff | `cdk.out` |

### Features

- **Lambda Code Filtering**: Automatically filters out Lambda code changes to focus on infrastructure changes
- **Enhanced Output**: Provides clear, colorized diff output
- **Metadata Filtering**: Removes noise from metadata changes
- **Lambda Count Summary**: Shows how many Lambda functions will be updated due to code changes

### Example Output

```
No differences for stack "MyStack"

ƛƛ 2 lambda functions will be updated due to code changes. ƛƛ
```

---

## 🆕 New App

Create a new application from a predefined template with proper project structure.

### Usage

```bash
# Create a new app
doctor new-app --name my-awesome-app

# Short form
doctor new-app -n my-awesome-app
```

### Options

| Option | Description | Required |
|--------|-------------|----------|
| `-n, --name <name>` | Name of the new app | ✅ |

### What it creates

The command generates a complete application structure in `apps/<kebab-case-name>/`:

```
apps/my-awesome-app/
├── bin/
│   └── cdk.ts
├── cdk.json
├── infra/
│   └── index.ts
├── lint-staged.config.mjs
├── package.json
├── src/
└── tsconfig.json
```

### Template Features

- **CDK Integration**: Pre-configured CDK setup
- **TypeScript**: Full TypeScript configuration
- **Linting**: ESLint and Prettier configuration
- **Package Management**: Proper package.json with dependencies
- **Name Transformations**: Automatic conversion to camelCase, kebabCase, and PascalCase

---

## ⚡ Invoke

Invoke a Lambda function locally with full AWS environment simulation.

### Usage

```bash
# Basic invocation
doctor invoke --lambda-name my-lambda-function

# With custom event data
doctor invoke -n my-lambda -e '{"key": "value"}'

# With event from file
doctor invoke -n my-lambda -e @event.json

# With custom context
doctor invoke -n my-lambda -x '{"requestId": "123"}'

# Full example
doctor invoke -n my-lambda -c ./my-cdk-out -e @event.json -x @context.json
```

### Options

| Option | Description | Default |
|--------|-------------|---------|
| `-n, --lambda-name <name>` | Name of the Lambda function to invoke | Required |
| `-c, --cdk-output <path>` | CDK output directory | `./cdk.out` |
| `-e, --event <data>` | Event data (JSON string or @file) | `{}` |
| `--context <data>` | Context data (JSON string or @file) | `{}` |

### Features

- **Environment Simulation**: Loads actual Lambda environment variables
- **SSM Parameter Resolution**: Automatically fetches SSM parameters
- **CloudFormation Exports**: Resolves CloudFormation export values
- **Dotenv Support**: Overrides with local `.env` file values
- **Timeout Handling**: Respects Lambda timeout settings
- **Error Reporting**: Comprehensive error handling and reporting
- **Architecture Warnings**: Warns about Node.js version and architecture mismatches

### Environment Resolution

The invoke command automatically resolves:
1. Lambda environment variables from CloudFormation
2. SSM parameters referenced in the template
3. CloudFormation exports
4. Local `.env` file overrides

### Example Output

```
✅ Set DATABASE_URL from SSM parameter /my-app/database-url
✅ Set API_KEY with value fetched from CloudFormation export MyApiKey
▶ Running lambda my-lambda-function from /path/to/handler.js...

Lambda executed successfully
Result:
{
  "statusCode": 200,
  "body": "Hello World"
}
```

---

## 🌐 API Gateway

Start a local API Gateway emulator that routes requests to Lambda functions.

### Usage

```bash
# Start emulator on default port
doctor api-gateway

# With custom port
doctor api-gateway --port 8080

# With custom CDK output
doctor api-gateway --cdk-output ./my-cdk-out

# Full example
doctor api-gateway -c ./my-cdk-out -p 8080
```

### Options

| Option | Description | Default |
|--------|-------------|---------|
| `-c, --cdk-output <path>` | CDK output directory | `./cdk.out` |
| `-p, --port <port>` | Port to run the emulator on | `3000` |

### Features

- **Route Discovery**: Automatically discovers API Gateway routes from CloudFormation
- **Lambda Integration**: Routes requests to appropriate Lambda functions
- **Hot Reloading**: Watches for template changes and reloads automatically
- **Request/Response Simulation**: Converts HTTP requests to API Gateway events
- **Environment Simulation**: Full Lambda environment variable resolution
- **Comprehensive Logging**: Detailed request/response logging

### Route Discovery

The emulator automatically:
1. Parses CloudFormation templates
2. Discovers API Gateway resources and methods
3. Maps routes to Lambda functions
4. Handles path parameters and query strings

### Example Output

```
🚀 Emulated API Gateway Routes:

  GET    /api/users      →  GetUsersFunction
  POST   /api/users      →  CreateUserFunction
  DELETE /api/users/{id} →  DeleteUserFunction

🚀 API Gateway emulator running at http://localhost:3000
```

### API Gateway Event Conversion

HTTP requests are automatically converted to API Gateway events:
- Headers and multi-value headers
- Query parameters
- Path parameters
- Request body (with base64 encoding support)
- Request context and identity information

---

## 🛠️ Development

### Building the Project

```bash
# Install dependencies
yarn install

# Build the project
yarn build

# Run in development mode
yarn dev

# Test CLI
yarn test:cli
```

### Adding New Commands

1. Create a new directory in `src/commands/`
2. Implement your command with proper TypeScript types
3. Export a command function following the pattern: `export async function myCommandCmd(options: MyOptions): Promise<void>`
4. Register the command in `src/cli.ts`

### Command Pattern

All commands follow this pattern:

```typescript
// types.ts - Define your options interface
export interface MyCommandOptions {
  required: string;
  optional?: string;
}

// index.ts - Implement your command
export async function myCommandCmd(options: MyCommandOptions): Promise<void> {
  // Validation
  if (!options.required) {
    console.error("❌ Error: Required parameter missing");
    process.exit(1);
  }

  try {
    // Your command logic
    console.log(`🎉 Success: ${options.required}`);
  } catch (error) {
    console.error(`❌ Error:`, error);
    process.exit(1);
  }
}
```

---

## 📝 License

This project is licensed under the MIT License.

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## 📞 Support

For issues and questions:
- Create an issue in the GitHub repository
- Contact the development team
- Check the documentation for common solutions