npm package: @gen2code/core
Description: Core utilities, types, and configurations for the Gen2Code framework
Author: WebHouse
Latest version: 3.0.5

# @gen2code/core

The foundational package of the Gen2Code framework, providing shared utilities, types, configurations, and React hooks for building modern web applications.

## 🚀 Installation

```bash
npm install @gen2code/core
# or
yarn add @gen2code/core
# or
pnpm add @gen2code/core
```

## 📋 Table of Contents

- [Types](#-types)
- [Validation](#-validation)
- [Formatting](#-formatting)
- [Cryptography](#-cryptography)
- [Configuration Management](#-configuration-management)
- [React Hooks](#-react-hooks)
- [API Utilities](#-api-utilities)
- [Error Handling](#-error-handling)
- [TypeScript Support](#-typescript-support)
- [Testing](#-testing)

## 🏗️ Types

Comprehensive TypeScript type definitions for the Gen2Code framework.

### Authentication Types

```typescript
import type { 
  AuthUser, 
  AuthSession, 
  Permission, 
  Role,
  AuthProvider 
} from '@gen2code/core';

const user: AuthUser = {
  id: 'user-123',
  email: 'user@example.com',
  emailVerified: true,
  // ... other properties
};

const session: AuthSession = {
  user,
  accessToken: 'token',
  refreshToken: 'refresh',
  expiresAt: new Date(),
  // ... other properties
};
```

### User Management Types

```typescript
import type { 
  User, 
  UserProfile, 
  UserSettings, 
  UserRole,
  Avatar 
} from '@gen2code/core';

const userProfile: UserProfile = {
  firstName: 'John',
  lastName: 'Doe',
  bio: 'Software Developer',
  avatar: {
    url: 'https://example.com/avatar.jpg',
    alt: 'John Doe'
  }
};
```

### Team Management Types

```typescript
import type { 
  Team, 
  TeamMember, 
  TeamInvitation, 
  TeamRole,
  TeamPermission 
} from '@gen2code/core';

const team: Team = {
  id: 'team-123',
  name: 'Development Team',
  slug: 'dev-team',
  // ... other properties
};
```

### API Types

```typescript
import type { 
  ApiResponse, 
  ApiError, 
  PaginatedResponse, 
  RequestConfig 
} from '@gen2code/core';

const response: ApiResponse<User[]> = {
  data: users,
  success: true,
  message: 'Users retrieved successfully'
};
```

## ✅ Validation

Comprehensive validation utilities with TypeScript support and detailed error reporting.

### Email Validation

```typescript
import { 
  validateEmail, 
  normalizeEmail, 
  extractEmailDomain,
  isDisposableEmail,
  validateEmailDomain 
} from '@gen2code/core';

// Basic email validation
const isValid = validateEmail('user@example.com'); // true

// Normalize email (lowercase, trim)
const normalized = normalizeEmail('  USER@EXAMPLE.COM  '); // 'user@example.com'

// Extract domain
const domain = extractEmailDomain('user@example.com'); // 'example.com'

// Check for disposable email providers
const isDisposable = isDisposableEmail('user@tempmail.com'); // true

// Validate specific domains
const isDomainValid = validateEmailDomain('example.com', {
  allowedDomains: ['example.com', 'company.com']
}); // true
```

### Password Validation

```typescript
import { 
  validatePassword, 
  getPasswordStrengthDescription,
  getPasswordStrengthColor,
  generatePasswordSuggestions,
  detectPasswordPatterns,
  estimatePasswordCrackTime 
} from '@gen2code/core';

// Comprehensive password validation
const result = validatePassword('MySecurePassword123!', {
  minLength: 8,
  requireUppercase: true,
  requireLowercase: true,
  requireNumbers: true,
  requireSymbols: true,
  maxLength: 128
});

console.log(result.isValid); // true
console.log(result.strength); // 0-5 strength score
console.log(result.feedback); // Array of feedback messages

// Get human-readable strength description
const description = getPasswordStrengthDescription(result.strength); // 'Very Strong'

// Get color for UI display
const color = getPasswordStrengthColor(result.strength); // '#22c55e'

// Generate improvement suggestions
const suggestions = generatePasswordSuggestions('weak123');
// ['Add uppercase letters', 'Add symbols', 'Increase length']

// Detect common patterns
const patterns = detectPasswordPatterns('password123');
// ['common_word', 'sequential_numbers']

// Estimate crack time
const crackTime = estimatePasswordCrackTime('MySecurePassword123!');
// { seconds: 1.2e+15, display: 'centuries' }
```

### URL and Phone Validation

```typescript
import { validateUrl, validatePhone } from '@gen2code/core';

// URL validation with protocol checking
const isValidUrl = validateUrl('https://example.com', {
  protocols: ['http', 'https'],
  requireProtocol: true
}); // true

// International phone number validation
const isValidPhone = validatePhone('+1-555-123-4567', {
  country: 'US',
  format: 'international'
}); // true
```

### Field Validation

```typescript
import { 
  validateRequired,
  validateLength,
  validateRange,
  validateArray,
  validateObject,
  validateEnum,
  validateDate,
  validateBoolean,
  validateFields 
} from '@gen2code/core';

// Individual field validation
const requiredResult = validateRequired('value'); // { isValid: true }
const lengthResult = validateLength('hello', { min: 3, max: 10 }); // { isValid: true }
const rangeResult = validateRange(25, { min: 18, max: 65 }); // { isValid: true }

// Validate multiple fields at once
const fieldsResult = validateFields({
  email: { value: 'user@example.com', validators: ['required', 'email'] },
  age: { value: 25, validators: ['required', { type: 'range', min: 18, max: 65 }] }
});
```

### Schema Validation

```typescript
import { 
  validateSchema,
  validateSchemaSafe,
  createEmailSchema,
  createPasswordSchema,
  createUserRegistrationSchema,
  createUserLoginSchema,
  createTeamSchema 
} from '@gen2code/core';

// Use pre-built schemas
const registrationSchema = createUserRegistrationSchema();
const result = validateSchema(registrationSchema, {
  email: 'user@example.com',
  password: 'SecurePassword123!',
  firstName: 'John',
  lastName: 'Doe'
});

if (result.isValid) {
  console.log('Valid user data:', result.data);
} else {
  console.log('Validation errors:', result.errors);
}

// Safe validation (doesn't throw)
const safeResult = validateSchemaSafe(registrationSchema, userData);

// Create custom schemas
const emailSchema = createEmailSchema({
  allowedDomains: ['company.com'],
  blockDisposable: true
});

const passwordSchema = createPasswordSchema({
  minLength: 12,
  requireSymbols: true
});
```

## 🎨 Formatting

Utilities for formatting dates, numbers, text, and other data types.

### Date and Time Formatting

```typescript
import { formatDate, formatRelativeTime } from '@gen2code/core';

// Format dates with timezone support
const formatted = formatDate(new Date(), {
  format: 'yyyy-MM-dd HH:mm:ss',
  timezone: 'America/New_York',
  locale: 'en-US'
}); // '2024-01-15 14:30:00'

// Relative time formatting
const relative = formatRelativeTime(new Date(Date.now() - 3600000)); // '1 hour ago'
```

### Number and Currency Formatting

```typescript
import { 
  formatNumber, 
  formatCurrency, 
  formatFileSize,
  formatPercentage 
} from '@gen2code/core';

// Number formatting with locale support
const number = formatNumber(1234567.89, {
  locale: 'en-US',
  minimumFractionDigits: 2
}); // '1,234,567.89'

// Currency formatting
const price = formatCurrency(99.99, {
  currency: 'USD',
  locale: 'en-US'
}); // '$99.99'

// File size formatting
const size = formatFileSize(1024 * 1024 * 2.5); // '2.5 MB'

// Percentage formatting
const percent = formatPercentage(0.1234, { decimals: 2 }); // '12.34%'
```

### Text Formatting

```typescript
import { 
  truncateText, 
  generateSlug, 
  capitalizeWords,
  formatInitials,
  formatPhoneNumber 
} from '@gen2code/core';

// Text truncation with ellipsis
const truncated = truncateText('This is a very long text', {
  maxLength: 20,
  ellipsis: '...'
}); // 'This is a very long...'

// URL-friendly slug generation
const slug = generateSlug('Hello World! This is a Test'); // 'hello-world-this-is-a-test'

// Capitalize words
const capitalized = capitalizeWords('hello world'); // 'Hello World'

// Generate initials
const initials = formatInitials('John Doe Smith'); // 'JDS'

// Format phone numbers
const phone = formatPhoneNumber('+15551234567', {
  format: 'national'
}); // '(555) 123-4567'
```

## 🔐 Cryptography

Secure cryptographic utilities for password hashing, data encryption, and token generation.

### Password Hashing

```typescript
import { 
  hashPassword, 
  verifyPassword, 
  generateSalt 
} from '@gen2code/core';

// Hash password with automatic salt generation
const hashedPassword = await hashPassword('userPassword123');

// Verify password against hash
const isValid = await verifyPassword('userPassword123', hashedPassword); // true

// Generate custom salt
const salt = generateSalt(16); // 16-byte salt
```

### Data Encryption

```typescript
import { 
  encryptData, 
  decryptData, 
  generateEncryptionKey 
} from '@gen2code/core';

// Generate encryption key
const key = generateEncryptionKey();

// Encrypt sensitive data
const encrypted = encryptData('sensitive information', key);

// Decrypt data
const decrypted = decryptData(encrypted, key); // 'sensitive information'
```

### Token and String Generation

```typescript
import { 
  generateToken, 
  generateSecureString,
  generateChecksum,
  verifyChecksum,
  constantTimeCompare 
} from '@gen2code/core';

// Generate secure tokens
const token = generateToken(32); // 32-byte random token
const secureString = generateSecureString(16); // 16-character secure string

// Generate and verify checksums
const data = 'important data';
const checksum = generateChecksum(data);
const isValid = verifyChecksum(data, checksum); // true

// Constant-time string comparison (prevents timing attacks)
const isEqual = constantTimeCompare('secret1', 'secret2'); // false
```

## ⚙️ Configuration Management

Comprehensive configuration management system with environment variable handling and validation.

### Configuration Manager

```typescript
import { 
  ConfigManager, 
  config, 
  getConfig,
  getConfigValue,
  updateConfig,
  validateConfig,
  initializeConfig 
} from '@gen2code/core';

// Initialize configuration
await initializeConfig({
  environment: 'development',
  configPath: './config'
});

// Get configuration values
const dbConfig = getConfig('database');
const apiUrl = getConfigValue('api.baseUrl', 'http://localhost:3000');

// Update configuration
await updateConfig('features.enableNewUI', true);

// Validate configuration
const validation = validateConfig();
if (!validation.isValid) {
  console.error('Configuration errors:', validation.errors);
}
```

### Environment Variable Management

```typescript
import { 
  EnvManager,
  env,
  getEnvString,
  getEnvNumber,
  getEnvBoolean,
  getEnvArray,
  getEnvJson,
  getEnvUrl,
  loadEnvFiles,
  getCurrentEnvironment,
  isDevelopment,
  isProduction 
} from '@gen2code/core';

// Load environment files
await loadEnvFiles(['.env', '.env.local']);

// Get typed environment variables
const dbUrl = getEnvString('DATABASE_URL', 'postgresql://localhost:5432/db');
const port = getEnvNumber('PORT', 3000);
const enableFeature = getEnvBoolean('ENABLE_FEATURE', false);
const allowedOrigins = getEnvArray('ALLOWED_ORIGINS', []);
const config = getEnvJson('APP_CONFIG', {});
const apiUrl = getEnvUrl('API_URL');

// Environment detection
const currentEnv = getCurrentEnvironment(); // 'development' | 'production' | 'test' | 'staging'
const isDev = isDevelopment(); // true in development
const isProd = isProduction(); // true in production
```

## ⚛️ React Hooks

Production-ready React hooks for common functionality.

### API Hooks

```typescript
import { 
  useApi, 
  useMutation, 
  useQuery, 
  usePagination,
  useWebSocket 
} from '@gen2code/core';

// Generic API hook with loading states
const { data, loading, error, execute } = useApi<User[]>({
  url: '/api/users',
  method: 'GET'
});

// Mutation hook for data modifications
const { mutate, loading: mutating } = useMutation<User>({
  url: '/api/users',
  method: 'POST',
  onSuccess: (user) => console.log('User created:', user),
  onError: (error) => console.error('Failed to create user:', error)
});

// Query hook with caching
const { data: users, refetch } = useQuery<User[]>({
  queryKey: 'users',
  url: '/api/users',
  cacheTime: 5 * 60 * 1000 // 5 minutes
});

// Pagination hook
const { 
  data, 
  currentPage, 
  totalPages, 
  nextPage, 
  prevPage, 
  goToPage 
} = usePagination<User>({
  url: '/api/users',
  pageSize: 20
});

// WebSocket hook
const { 
  data, 
  sendMessage, 
  readyState, 
  connect, 
  disconnect 
} = useWebSocket('ws://localhost:8080', {
  onMessage: (message) => console.log('Received:', message),
  reconnectAttempts: 3
});
```

### Authentication Hooks

```typescript
import { 
  useAuth, 
  useSession, 
  usePermissions,
  useAuthRedirect,
  useAuthForm 
} from '@gen2code/core';

// Authentication state management
const { 
  user, 
  isAuthenticated, 
  login, 
  logout, 
  register,
  loading 
} = useAuth();

// Session management
const { 
  session, 
  refreshSession, 
  clearSession,
  isExpired 
} = useSession();

// Permission checking
const { 
  hasPermission, 
  hasRole, 
  canAccess,
  permissions 
} = usePermissions();

// Automatic redirect for protected routes
useAuthRedirect({
  redirectTo: '/login',
  requireAuth: true,
  requiredRoles: ['admin']
});

// Form handling for auth forms
const { 
  formData, 
  errors, 
  isValid, 
  handleChange, 
  handleSubmit,
  reset 
} = useAuthForm({
  initialData: { email: '', password: '' },
  validationSchema: loginSchema,
  onSubmit: async (data) => await login(data)
});
```

### Utility Hooks

```typescript
import { 
  useLocalStorage, 
  useDebounce,
  useTheme,
  useMediaQuery,
  useClipboard 
} from '@gen2code/core';

// Local storage with TypeScript support
const [user, setUser] = useLocalStorage<User>('user', null);

// Debounce values and callbacks
const debouncedValue = useDebounce(searchTerm, 500);
const debouncedCallback = useDebounceCallback(
  (query: string) => searchUsers(query),
  300
);

// Theme management
const { 
  theme, 
  setTheme, 
  resolvedTheme,
  systemTheme 
} = useTheme();

// Media queries and responsive design
const isMobile = useMediaQuery('(max-width: 768px)');
const { isMobile: mobile, isTablet, isDesktop } = useBreakpoints();

// Clipboard operations
const { 
  copy, 
  copied, 
  copyFormatted,
  isSupported 
} = useClipboard({
  timeout: 2000
});

// Usage
await copy('Text to copy');
console.log(copied); // true for 2 seconds
```

## 🌐 API Utilities

Comprehensive API utilities with error handling, caching, and retry logic.

### HTTP Client

```typescript
import { 
  createHttpClient,
  HttpApiError,
  NetworkError,
  handleApiError 
} from '@gen2code/core';

// Create configured HTTP client
const client = createHttpClient({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  retries: 3,
  headers: {
    'Authorization': 'Bearer token'
  }
});

// Make requests with automatic error handling
try {
  const response = await client.get<User[]>('/users');
  console.log(response.data);
} catch (error) {
  if (error instanceof HttpApiError) {
    console.error('API Error:', error.message, error.statusCode);
  } else if (error instanceof NetworkError) {
    console.error('Network Error:', error.message);
  }
}
```

### Caching and Retry Logic

```typescript
import { 
  createCache,
  createRetryConfig,
  isRetryableError 
} from '@gen2code/core';

// Create cache instance
const cache = createCache({
  maxSize: 100,
  ttl: 5 * 60 * 1000 // 5 minutes
});

// Cache API responses
cache.set('users', usersData);
const cachedUsers = cache.get('users');

// Retry configuration
const retryConfig = createRetryConfig({
  attempts: 3,
  delay: 1000,
  backoff: 'exponential',
  retryCondition: (error) => isRetryableError(error)
});
```

## 🚨 Error Handling

Comprehensive error handling system with logging, reporting, and user-friendly messages.

### Error Classes

```typescript
import { 
  AppError,
  ValidationError,
  AuthenticationError,
  AuthorizationError,
  HttpApiError 
} from '@gen2code/core';

// Create custom application errors
throw new AppError('Something went wrong', 'APP_ERROR', {
  userId: '123',
  action: 'updateProfile'
});

// Validation errors with field details
throw new ValidationError('Invalid input', {
  email: ['Invalid email format'],
  password: ['Password too weak']
});

// Authentication errors
throw new AuthenticationError('Invalid credentials', 'INVALID_CREDENTIALS');

// Authorization errors
throw new AuthorizationError('Insufficient permissions', 'INSUFFICIENT_PERMISSIONS');
```

### Error Logging and Reporting

```typescript
import { 
  ErrorLogger,
  logError,
  logWarn,
  logInfo,
  reportError,
  createUserFriendlyError 
} from '@gen2code/core';

// Log errors with context
logError('Database connection failed', {
  database: 'users',
  host: 'localhost',
  port: 5432
});

// Log warnings and info
logWarn('API rate limit approaching');
logInfo('User logged in successfully');

// Report errors to external service
await reportError(error, {
  userId: '123',
  userAgent: navigator.userAgent,
  url: window.location.href
});

// Create user-friendly error messages
const friendlyError = createUserFriendlyError(error);
console.log(friendlyError.message); // User-friendly message
console.log(friendlyError.actions); // Suggested actions
```

## 📚 TypeScript Support

This package is built with TypeScript and provides comprehensive type definitions:

- **Strict Type Safety**: All functions and utilities are fully typed
- **Generic Support**: Many utilities support generic types for flexibility
- **Type Guards**: Built-in type checking utilities
- **Interface Definitions**: Complete interfaces for all data structures
- **Enum Types**: Predefined enums for common values

```typescript
// Example of generic type support
import type { ApiResponse, PaginatedResponse } from '@gen2code/core';

interface CustomData {
  id: string;
  name: string;
}

// Fully typed API response
const response: ApiResponse<CustomData[]> = await fetchData();

// Fully typed paginated response
const paginatedResponse: PaginatedResponse<CustomData> = await fetchPaginatedData();
```

## 🧪 Testing

The package includes comprehensive test coverage:

- **67 test suites** with **1,214 individual tests**
- **100% code coverage** for all exported functions
- **Integration tests** for complex workflows
- **Performance tests** for critical utilities
- **Edge case testing** for robust error handling

### Running Tests

```bash
# Run all tests
pnpm test

# Run tests with coverage
pnpm test --coverage

# Run specific test suite
pnpm test validation

# Watch mode for development
pnpm test --watch
```

## 🤝 Contributing

This package is part of the Gen2Code framework. Please refer to the main repository for contribution guidelines.

## 📄 License

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

## 🔗 Related Packages

- `@gen2code/api-framework` - API documentation and standards
- `@gen2code/access-control` - Authentication and authorization
- `@gen2code/user-management` - User profiles and settings
- `@gen2code/team-management` - Multi-tenant organization management

---

**Built with ❤️ by the Gen2Code team**