npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@gen2code/core

v3.0.5

Published

Core utilities, types, and configurations for the Gen2Code framework

Downloads

11

Readme

@gen2code/core

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

🚀 Installation

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

📋 Table of Contents

🏗️ Types

Comprehensive TypeScript type definitions for the Gen2Code framework.

Authentication Types

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

const user: AuthUser = {
  id: 'user-123',
  email: '[email protected]',
  emailVerified: true,
  // ... other properties
};

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

User Management Types

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

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

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

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

// Basic email validation
const isValid = validateEmail('[email protected]'); // true

// Normalize email (lowercase, trim)
const normalized = normalizeEmail('  [email protected]  '); // '[email protected]'

// Extract domain
const domain = extractEmailDomain('[email protected]'); // 'example.com'

// Check for disposable email providers
const isDisposable = isDisposableEmail('[email protected]'); // true

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

Password Validation

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

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

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: '[email protected]', validators: ['required', 'email'] },
  age: { value: 25, validators: ['required', { type: 'range', min: 18, max: 65 }] }
});

Schema Validation

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

// Use pre-built schemas
const registrationSchema = createUserRegistrationSchema();
const result = validateSchema(registrationSchema, {
  email: '[email protected]',
  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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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
// 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

# 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 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