npm package: @hyperdrive.bot/serverless-utils
Description: Common utilities for DevSquad serverless plugins and tools
Author: DevSquad
Latest version: 1.0.13

# Serverless Utils

Common utilities for DevSquad Serverless Framework plugins and tools. This package extracts shared functionality from `composer`, `module-registry`, `artifact-manager`, and `arn-prefixer` to eliminate code duplication and provide consistent behavior.

## 📦 Installation

```bash
npm install @hyperdrive.bot/serverless-utils
```

## 🚀 Features

- **Universal Logger**: Consistent logging across all serverless plugins
- **Variable Resolution**: Cross-version Serverless Framework variable resolution  
- **Object Utilities**: Deep merge, cloning, and manipulation functions
- **CloudFormation Support**: YAML schema with intrinsic function support
- **Build Configurations**: Standardized TypeScript, ESLint, and Jest configs

## 📖 Usage

### Logger

Create consistent, colorful logs across all serverless plugins:

```typescript
import { createLogger } from '@hyperdrive.bot/serverless-utils'

const logger = createLogger(serverless, 'my-plugin')

logger.info('Processing started')
logger.success('Operation completed successfully') 
logger.warning('Configuration missing')
logger.error('Deployment failed')
logger.step('Processing next phase')

// Structured sections
logger.section('Deployment Summary')
logger.sectionItem('Service', serviceName, 'cyan')
logger.sectionItem('Functions', functionCount.toString(), 'green')
logger.sectionEnd()
```

### Variable Resolution

Handle Serverless Framework variables across all versions:

```typescript
import { resolveVarsSafely, detectServerlessVersion } from '@hyperdrive.bot/serverless-utils'

const version = detectServerlessVersion(serverless)
const resolved = await resolveVarsSafely(serverless, {
  tableName: '${arn:prefix}-users',
  bucketName: '${env:BUCKET_NAME}'
})
```

### Object Utilities

Merge and manipulate objects safely:

```typescript
import { deepMerge, isPlainObject, chunkArray } from '@hyperdrive.bot/serverless-utils'

const merged = deepMerge(target, source)
const batches = chunkArray(largeArray, 25) // For DynamoDB batch operations
const resourceName = sanitizeResourceName('my-resource-name!')
```

### CloudFormation Support

Parse YAML with CloudFormation intrinsic functions:

```typescript
import { loadCloudFormationYaml, cloudFormationSchema } from '@hyperdrive.bot/serverless-utils'

const config = loadCloudFormationYaml('./serverless.yml')
// Handles !Ref, !GetAtt, !Sub, !Join, etc.
```

### Build Configurations

Use standardized build configurations:

```typescript
// tsup.config.ts
import { createTSUpConfig } from '@hyperdrive.bot/serverless-utils/config'

export default createTSUpConfig({
  nodeTarget: 'node16',
  externalDeps: ['serverless', 'custom-dep']
})
```

```json
// tsconfig.json
{
  "extends": "@hyperdrive.bot/serverless-utils/src/config/tsconfig.base.json"
}
```

```json
// .eslintrc.json
{
  "extends": ["@hyperdrive.bot/serverless-utils/src/config/eslint.base.json"]
}
```

## 🎯 Benefits

### Before (Duplicated Code)
- 4 different logger implementations
- 2 different variable resolution implementations  
- 4 sets of identical build configurations
- Inconsistent error handling and messaging

### After (Unified Utilities)
- ✅ Single logger with customizable prefixes
- ✅ Unified variable resolution for all Serverless versions
- ✅ Shared build configurations via extends/imports
- ✅ Consistent error handling and user experience
- ✅ Easier maintenance and updates
- ✅ Better testing coverage

## 🔧 Migration Guide

### From Composer Plugin

**Before:**
```typescript
import { EnhancedLogger } from './logger'
import { resolveVarsSafely, deepMerge } from './utils'

const logger = new EnhancedLogger(serverless)
```

**After:**
```typescript
import { createLogger, resolveVarsSafely, deepMerge } from '@hyperdrive.bot/serverless-utils'

const logger = createLogger(serverless, 'composer')
```

### From Module Registry Plugin

**Before:**
```typescript
// Custom logger implementation
const logger = createModuleRegistryLogger('my-handler')
```

**After:**
```typescript
import { createLogger } from '@hyperdrive.bot/serverless-utils'

const logger = createLogger({ cli: { log: console.log } }, 'module-registry')
```

## 📋 API Reference

### Logger Methods

- `info(message, color?)` - Info message with optional color
- `success(message)` - Green success message with checkmark
- `warning(message)` - Yellow warning message with warning icon
- `error(message)` - Red error message with X icon
- `step(message)` - Blue step message with arrow
- `section(title)` - Formatted section header
- `sectionItem(key, value, color?)` - Indented section item
- `sectionEnd()` - Section footer
- `progress(category, fileCount)` - Processing progress
- `variableResolution(category, variableCount)` - Variable resolution progress

### Utility Functions

- `deepMerge(target, source)` - Deep merge objects
- `isPlainObject(obj)` - Check if object is plain
- `chunkArray(array, size)` - Split array into chunks
- `sanitizeResourceName(name)` - CloudFormation-safe names
- `deepClone(obj)` - Deep clone objects
- `isEmpty(obj)` - Check if object/array is empty

### Variable Resolution

- `resolveVarsSafely(serverless, payload)` - Cross-version variable resolution
- `detectServerlessVersion(serverless)` - Detect v2 vs v3+
- `resolveVariablesManually(payload, sources, serverless)` - Manual resolution

## 📄 License

MIT License - see the [LICENSE](LICENSE) file for details.