npm package: @hyperdrive.bot/serverless-plugin-manager
Description: Common utilities and patterns for serverless plugin CI/CD pipelines
Author: DevSquad Team
Latest version: 1.0.5

# Serverless Plugin Manager

Common utilities and patterns for serverless plugin CI/CD pipelines. This library abstracts common testing, deployment, and cleanup patterns to make serverless plugin development more consistent and reliable.

## 🚀 Features

- **🧪 Comprehensive Testing**: Package validation, feature testing, and integration testing
- **🧹 Finally-like Cleanup**: Automatic cleanup that runs even when processes fail
- **☁️ AWS Resource Management**: Automatic AWS resource cleanup and validation
- **📊 Consistent Logging**: Beautiful, structured logging with emojis and colors
- **🔧 CLI Tools**: Ready-to-use CLI commands for common operations
- **📋 Script Templates**: Pre-built script templates for quick setup

## 📦 Installation

```bash
npm install @hyperdrive.bot/serverless-plugin-manager
```

## 🏗️ Quick Start

### Using CLI Tools

```bash
# Run package validation tests
npx @hyperdrive.bot/serverless-plugin-manager test package-validation --plugin your-plugin-name

# Run feature tests  
npx @hyperdrive.bot/serverless-plugin-manager test feature-tests --plugin your-plugin-name

# Run integration tests
npx @hyperdrive.bot/serverless-plugin-manager test integration-tests --plugin your-plugin-name

# Run all tests
npx @hyperdrive.bot/serverless-plugin-manager test all --plugin your-plugin-name

# Clean up resources
npx @hyperdrive.bot/serverless-plugin-manager cleanup all --stage test
```

### Using Script Templates

Copy script templates to your project:

```bash
cp node_modules/@hyperdrive.bot/serverless-plugin-manager/templates/*.sh ./scripts/
chmod +x ./scripts/*.sh
```

Then use in package.json:

```json
{
  "scripts": {
    "test:package-validation": "./scripts/package-validation-script.sh",
    "test:features": "./scripts/feature-tests-script.sh", 
    "test:integration": "./scripts/integration-tests-script.sh",
    "cleanup": "./scripts/cleanup-script.sh"
  }
}
```

### Using Programmatically

```typescript
import { 
  TestManager, 
  createDefaultTestConfig,
  getCleanupManager,
  logger 
} from '@hyperdrive.bot/serverless-plugin-manager'

// Set up automatic cleanup
const cleanupManager = getCleanupManager()
cleanupManager.trackDirectory('./test-project')
cleanupManager.addAwsPattern({ 
  type: 'stack', 
  pattern: '*test*', 
  region: 'us-east-1' 
})

// Run tests
const config = createDefaultTestConfig('your-plugin-name')
const testManager = new TestManager(config)

const result = await testManager.runAllTests()
if (result.success) {
  logger.success('All tests passed!')
} else {
  logger.error('Tests failed')
  process.exit(1)
}

// Cleanup happens automatically on process exit
```

## 🧪 Test Management

### Package Validation
- Tests regular serverless packaging
- Tests module-specific packaging
- Validates generated artifacts
- Tests print functionality
- Validates module isolation

### Feature Testing
- Tests all plugin features
- Tests custom transformers
- Tests all supported categories
- Tests edge cases and error conditions
- Validates complex module structures

### Integration Testing
- Deploys actual AWS resources
- Tests against live deployments
- Validates API endpoints
- Tests post-deployment operations
- Ensures proper resource cleanup

## 🧹 Cleanup Management

### Automatic Cleanup
The cleanup manager provides "finally"-like behavior:

```typescript
import { getCleanupManager, trackResource, trackFile } from '@hyperdrive.bot/serverless-plugin-manager'

// Track resources for cleanup
trackResource({ type: 'stack', identifier: 'my-test-stack', region: 'us-east-1' })
trackFile('./temporary-file.txt')

// Cleanup happens automatically on:
// - Normal process exit
// - SIGINT (Ctrl+C)  
// - SIGTERM
// - Uncaught exceptions
// - Unhandled promise rejections
```

### AWS Resource Cleanup
- CloudFormation stacks
- Lambda functions
- DynamoDB tables
- SQS queues
- S3 buckets (empties before deletion)
- API Gateway APIs
- Step Functions

### Pattern-based Cleanup
Clean up resources by naming patterns:

```typescript
cleanupManager.addAwsPattern({
  type: 'stack',
  pattern: '*test*',
  region: 'us-east-1'
})
```

## 📊 Logging

### Structured Logging
```typescript
import { logger } from '@hyperdrive.bot/serverless-plugin-manager'

logger.step('Starting deployment')
logger.info('Information message')
logger.success('Operation completed')
logger.error('Something failed')
logger.aws('deploy', 'my-stack', 'us-east-1')
logger.cleanup('delete', 'test-resource')
```

### Progress Tracking
```typescript
logger.progress(3, 10, 'Processing modules...')
logger.section('Test Results')
logger.testResults('My Test', true, 'Test passed', 1500)
```

## ⚙️ Configuration

### Default Configuration
```typescript
const config = createDefaultTestConfig('your-plugin-name')
// Automatically sets up test modules, stages, and AWS regions
```

### Custom Configuration
```typescript
const config: PluginConfig = {
  pluginName: 'your-plugin-name',
  testProjectName: 'test-project',
  deploymentStage: 'dev',
  serverlessVersion: '4',
  awsRegion: 'us-east-1',
  testModules: [
    {
      name: 'auth',
      categories: [
        {
          name: 'functions',
          files: [
            {
              fileName: 'login.yml',
              type: 'yaml',
              content: '...'
            }
          ]
        }
      ],
      expectedFunctions: ['login']
    }
  ],
  transformers: [
    {
      category: 'functions',
      path: './transformers/functions.js',
      expectedTransformations: { TRANSFORMED: 'true' }
    }
  ]
}
```

## 🔧 CLI Reference

### Test Commands
```bash
# Package validation
sls-plugin-test package-validation --plugin <name> --stage <stage>

# Feature tests  
sls-plugin-test feature-tests --plugin <name> --stage <stage>

# Integration tests
sls-plugin-test integration-tests --plugin <name> --stage <stage>

# All tests
sls-plugin-test all --plugin <name> --stage <stage>
```

### Cleanup Commands
```bash
# AWS resources
sls-plugin-cleanup aws --stage <stage> --region <region>

# Local artifacts
sls-plugin-cleanup local --path <path>

# Everything
sls-plugin-cleanup all --stage <stage> --region <region>
```

### Options
- `--plugin <name>`: Plugin name
- `--stage <stage>`: Deployment stage (default: $CI_COMMIT_REF_SLUG or 'test')
- `--region <region>`: AWS region (default: 'us-east-1')
- `--serverless-version <version>`: Serverless Framework version (default: '4')

## 🎯 CI/CD Integration

### GitLab CI
```yaml
test:package-validation:
  script:
    - npm run test:package-validation

test:features:
  script:
    - npm run test:features

test:integration:
  script:
    - npm run test:integration
  after_script:
    - npm run cleanup
```

### GitHub Actions
```yaml
- name: Package Validation
  run: npm run test:package-validation

- name: Feature Tests
  run: npm run test:features

- name: Integration Tests  
  run: npm run test:integration

- name: Cleanup
  if: always()
  run: npm run cleanup
```

## 🔍 Environment Variables

- `CI_COMMIT_REF_SLUG`: Branch name (used as deployment stage)
- `AWS_DEFAULT_REGION`: Default AWS region
- `SERVERLESS_VERSION`: Serverless Framework version
- `PLUGIN_NAME`: Plugin name for testing
- `SKIP_INTEGRATION_TESTS`: Skip integration tests if set to 'true'
- `LOG_LEVEL`: Logging level (debug, info, warn, error)

## 📚 Examples

Check out these examples in the wild:
- [Serverless Composer Plugin](../composer) - Uses this library for comprehensive CI/CD

## 🤝 Contributing

1. Add new features to the appropriate modules
2. Update tests and documentation
3. Follow the established patterns
4. Ensure cleanup is comprehensive

## 📄 License

MIT © DevSquad Team