npm package: @ravvnen/environment-monitor
Description: Professional React environment monitoring library with feature flags, health checks, and interactive dashboards
Author: TTC Platform Team
Latest version: 1.0.0

# @ravvnen/environment-monitor

[![npm version](https://badge.fury.io/js/@ravvnen%2Fenvironment-monitor.svg)](https://badge.fury.io/js/@ravvnen%2Fenvironment-monitor)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Professional React environment monitoring library with feature flags, health checks, and interactive dashboards. Perfect for development teams who need to manage multiple environments safely and efficiently.

## ✨ Features

- 🌍 **Automatic Environment Detection** - Detect local, dev, qa, and production environments
- 🔍 **Real-time Health Monitoring** - Monitor API health with visual status indicators
- 🚀 **Feature Flags** - Environment-specific feature toggles with local overrides
- 📊 **Interactive Dashboard** - Rich UI for environment details and controls
- 🎯 **Production Safe** - Automatically hidden in production environments
- 📦 **Zero Dependencies** - Only requires React as peer dependency
- 🎨 **Customizable UI** - Flexible styling and positioning options
- � **Responsive Design** - Works on desktop and mobile

## 🚀 Quick Start

### Installation

```bash
npm install @ravvnen/environment-monitor
```

### Basic Usage

```tsx
import React from 'react'
import { EnvironmentMonitor } from '@ravvnen/environment-monitor'
import type { EnvironmentMonitorConfig } from '@ravvnen/environment-monitor'
import '@ravvnen/environment-monitor/styles.css'

const config: EnvironmentMonitorConfig = {
  detectEnvironment: () => {
    const hostname = window.location.hostname
    
    if (hostname.includes('localhost')) {
      return {
        environment: 'local',
        isLocalDev: true,
        gitCommit: 'local-dev',
        buildTime: new Date().toISOString()
      }
    }
    
    if (hostname.includes('staging')) {
      return {
        environment: 'qa',
        isLocalDev: false,
        gitCommit: process.env.REACT_APP_GIT_COMMIT || 'unknown',
        buildTime: process.env.REACT_APP_BUILD_TIME || new Date().toISOString()
      }
    }
    
    return {
      environment: 'production',
      isLocalDev: false,
      gitCommit: process.env.REACT_APP_GIT_COMMIT || 'unknown',
      buildTime: process.env.REACT_APP_BUILD_TIME || new Date().toISOString()
    }
  }
}

function App() {
  return (
    <div className="App">
      {/* Your app content */}
      
      <EnvironmentMonitor 
        config={config}
        showBadge={true}
        badgePosition="top-right"
      />
    </div>
  )
}
```

```tsx
import { EnvironmentMonitor, FeatureFlag } from '@thetechcollective/environment-monitor'

const featureFlags: FeatureFlag[] = [
  {
    key: 'newFeature',
    name: 'New Feature',
    description: 'Enable the new experimental feature',
    defaultValue: false,
    environments: {
      local: true,
      dev: true,
      qa: false,
      production: false
    }
  }
]

const config = {
  detectEnvironment: () => ({
    environment: detectCurrentEnvironment(), // Your logic
    isLocalDev: window.location.hostname === 'localhost',
    deploymentSlot: process.env.REACT_APP_DEPLOYMENT_SLOT,
    gitCommit: process.env.REACT_APP_GIT_COMMIT
  }),
  
  featureFlags,
  
  healthCheck: async () => {
    try {
      const response = await fetch('/api/health')
      return {
        status: response.ok ? 'healthy' : 'degraded',
        latency: performance.now() // Your timing logic
      }
    } catch (error) {
      return {
        status: 'down',
        error: error.message
      }
    }
  },
  
  buildInfoProvider: () => ({
    version: process.env.REACT_APP_VERSION,
    buildTime: process.env.REACT_APP_BUILD_TIME,
    nodeEnv: process.env.NODE_ENV
  }),
  
  visibility: {
    showInProduction: false,
    badge: {
      position: 'top-right',
      compact: false
    }
  }
}

<EnvironmentMonitor config={config} />
```

## 🎯 Component Usage

### Individual Components

You can also use individual components for more control:

```tsx
import { 
  EnvironmentBadge, 
  EnvironmentDashboard, 
  useEnvironmentMonitor 
} from '@thetechcollective/environment-monitor'

function CustomEnvironmentMonitor() {
  const [isOpen, setIsOpen] = useState(false)
  const { envInfo } = useEnvironmentMonitor(config)
  
  return (
    <>
      <EnvironmentBadge 
        environment={envInfo.environment}
        onClick={() => setIsOpen(true)}
      />
      
      <EnvironmentDashboard
        config={config}
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
      />
    </>
  )
}
```

### Using Feature Flags

```tsx
import { FeatureFlagManager } from '@thetechcollective/environment-monitor'

// Initialize feature flag manager
const flagManager = new FeatureFlagManager(featureFlags, 'production')

// Use in components
function MyComponent() {
  const showNewFeature = flagManager.isEnabled('newFeature')
  
  return (
    <div>
      {showNewFeature && <NewFeatureComponent />}
    </div>
  )
}
```

## 📋 API Reference

### Types

```typescript
interface EnvironmentMonitorConfig {
  // Required: Environment detection logic
  detectEnvironment: () => EnvironmentInfo
  
  // Optional: Custom environment configurations
  environmentConfigs?: Record<Environment, EnvironmentConfig>
  
  // Optional: Feature flags
  featureFlags?: FeatureFlag[]
  
  // Optional: Health check function
  healthCheck?: () => Promise<HealthCheckResult>
  
  // Optional: Build info provider
  buildInfoProvider?: () => BuildInfo
  
  // Optional: Visibility settings
  visibility?: VisibilityConfig
}

interface EnvironmentInfo {
  environment: 'local' | 'dev' | 'qa' | 'production'
  isLocalDev: boolean
  buildTime?: string
  gitCommit?: string
  deploymentSlot?: string
  appVersion?: string
  [key: string]: unknown // Custom properties
}

interface FeatureFlag {
  key: string
  name: string
  description: string
  defaultValue: boolean
  environments: Partial<Record<Environment, boolean>>
}
```

### Components

#### `<EnvironmentMonitor />`
The main component that combines badge and dashboard.

**Props:**
- `config: EnvironmentMonitorConfig` - Configuration object

#### `<EnvironmentBadge />`
Floating badge showing current environment.

**Props:**
- `environment: Environment` - Current environment
- `onClick?: () => void` - Click handler
- `position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'`
- `compact?: boolean` - Compact display mode

#### `<EnvironmentDashboard />`
Interactive dashboard modal.

**Props:**
- `config: EnvironmentMonitorConfig` - Configuration object
- `isOpen: boolean` - Modal open state
- `onClose: () => void` - Close handler

### Hooks

#### `useEnvironmentMonitor(config)`
Main hook for environment monitoring data.

**Returns:**
```typescript
{
  envInfo: EnvironmentInfo
  healthStatus: HealthStatus
  buildInfo: BuildInfo
}
```

### Utilities

#### `FeatureFlagManager`
Class for managing feature flags.

```typescript
const manager = new FeatureFlagManager(flags, environment)
manager.isEnabled('flagKey') // boolean
manager.getFlag('flagKey') // FeatureFlag | undefined
```

## 🎨 Styling

The library comes with default styles, but you can customize them:

```css
/* Override default styles */
.env-monitor-badge {
  --env-color: #your-color;
  --env-color-bg: #your-bg-color;
}

.env-monitor-dashboard {
  --env-color: #your-color;
  --env-color-bg: #your-bg-color;
}
```

## 🔧 Environment Detection Examples

### Domain-based Detection
```typescript
const detectEnvironment = (): EnvironmentInfo => {
  const hostname = window.location.hostname
  
  let environment: Environment = 'production'
  if (hostname.includes('localhost') || hostname.includes('127.0.0.1')) {
    environment = 'local'
  } else if (hostname.includes('-dev.')) {
    environment = 'dev'
  } else if (hostname.includes('-qa.')) {
    environment = 'qa'
  }
  
  return {
    environment,
    isLocalDev: environment === 'local',
    deploymentSlot: getDeploymentSlot(),
    buildTime: process.env.REACT_APP_BUILD_TIME
  }
}
```

### Environment Variable Detection
```typescript
const detectEnvironment = (): EnvironmentInfo => {
  const nodeEnv = process.env.NODE_ENV
  const appEnv = process.env.REACT_APP_ENVIRONMENT
  
  return {
    environment: (appEnv as Environment) || (nodeEnv === 'development' ? 'local' : 'production'),
    isLocalDev: nodeEnv === 'development',
    appVersion: process.env.REACT_APP_VERSION,
    gitCommit: process.env.REACT_APP_GIT_COMMIT
  }
}
```

## 🚢 Migration from Local Implementation

If you're migrating from a local implementation:

1. **Install the package:**
   ```bash
   npm install @thetechcollective/environment-monitor
   ```

2. **Update imports:**
   ```typescript
   // Before
   import { EnvironmentMonitor } from './lib/environment-monitor'
   
   // After
   import { EnvironmentMonitor } from '@thetechcollective/environment-monitor'
   import '@thetechcollective/environment-monitor/styles.css'
   ```

3. **Keep your existing configuration** - The API is designed to be compatible with most existing configurations.

## 🤝 Contributing

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

## 📄 License

MIT © TTC Platform Team

## 🔗 Links

- [GitHub Repository](https://github.com/thetechcollective/environment-monitor)
- [NPM Package](https://www.npmjs.com/package/@thetechcollective/environment-monitor)
- [Issue Tracker](https://github.com/thetechcollective/environment-monitor/issues)
- [Changelog](CHANGELOG.md)
- [Contributing Guide](CONTRIBUTING.md)

---

Made with ❤️ by the TTC Platform Team