npm package: @khni/utils
Description: @khni/utils is a TypeScript utility library that provides essential functions for Node.js applications.
Author: Khaled Eleskandrany
Latest version: 1.0.0

# @khni/utils

A lightweight collection of TypeScript utility functions for configuration management, time handling, number operations, and environment variable parsing.

## Installation

```bash
npm install @khni/utils
pnpm add @khni/utils
yarn add @khni/utils
```

## Features

- ⚙️ **Configuration Management** - Type-safe config initialization with logging support
- ⏰ **Time Utilities** - Time string parsing and expiration date generation
- 🔢 **Number Utilities** - Random number generation and safe environment variable parsing
- 🛡️ **Type Safety** - Full TypeScript support with comprehensive type definitions
- 📝 **Logging Integration** - Built-in support for custom loggers

## Quick Start

```typescript
import {
  createConfig,
  generateExpiredDate,
  generateRandomNumber,
  getSafeNumberFromEnv,
  parseTimeString,
} from "@khni/utils";

// Configuration management
interface AppConfig {
  port: number;
  host: string;
  logger?: { info: (msg: string) => void };
}

const config = createConfig<AppConfig>("App");
config.set({ port: 3000, host: "localhost", logger: console });
const settings = config.get(); // throws if not initialized

// Time utilities
const expiryDate = generateExpiredDate("30m"); // Date 30 minutes from now
const timeInfo = parseTimeString("2h"); // { timeValue: 2, timeUnit: 'hours' }

// Number utilities
const random = generateRandomNumber(1, 100); // Random number between 1-100
const port = getSafeNumberFromEnv("PORT", 3000); // Safe env variable parsing
```

## API Reference

### Configuration Management

#### `createConfig<T>(name: string)`

Creates a type-safe configuration manager with initialization tracking.

```typescript
interface DatabaseConfig {
  host: string;
  port: number;
  logger?: { info: (msg: string) => void };
}

const dbConfig = createConfig<DatabaseConfig>("Database");

// Initialize configuration (logs to provided logger or console)
dbConfig.set({
  host: "localhost",
  port: 5432,
  logger: console, // Optional custom logger
});

// Retrieve configuration (throws if not initialized)
const config = dbConfig.get();
console.log(config.host); // 'localhost'
```

### Time Utilities

#### `generateExpiredDate(timeString: ValidTimeString): Date`

Generates a future date based on a time duration string.

**Supported formats:**

- `"500ms"` - milliseconds
- `"30s"` - seconds
- `"10m"` - minutes
- `"2h"` - hours
- `"7d"` - days

```typescript
// Get dates for various time periods
const in5Minutes = generateExpiredDate("5m");
const in2Hours = generateExpiredDate("2h");
const in1Week = generateExpiredDate("7d");

// Use for token expiration, cache TTL, etc.
const tokenExpiry = generateExpiredDate("1h");
```

#### `parseTimeString(input: ValidTimeString): { timeValue: number; timeUnit: string }`

Parses a time string into its numeric value and human-readable unit with proper pluralization.

```typescript
const result1 = parseTimeString("10m");
// { timeValue: 10, timeUnit: 'minutes' }

const result2 = parseTimeString("1h");
// { timeValue: 1, timeUnit: 'hour' }

const result3 = parseTimeString("500ms");
// { timeValue: 500, timeUnit: 'milliseconds' }
```

### Number Utilities

#### `generateRandomNumber(min: number, max: number): number`

Generates a cryptographically secure random integer between min and max (inclusive).

```typescript
// Generate various random numbers
const diceRoll = generateRandomNumber(1, 6); // 1-6
const percentage = generateRandomNumber(0, 100); // 0-100
const largeRandom = generateRandomNumber(1000, 9999); // 4-digit code

// Throws error if min > max
generateRandomNumber(10, 5); // Error: Min value cannot be greater than max value
```

#### `getSafeNumberFromEnv(key: string, fallback: number): number`

Safely parses a number from environment variables with fallback support.

```typescript
// Read from environment with fallbacks
const port = getSafeNumberFromEnv("PORT", 3000);
const maxConnections = getSafeNumberFromEnv("MAX_CONNECTIONS", 100);
const timeout = getSafeNumberFromEnv("TIMEOUT_MS", 5000);

// Handles missing or invalid values gracefully
// process.env.PORT = "8080" -> returns 8080
// process.env.PORT = "invalid" -> returns 3000
// process.env.PORT = undefined -> returns 3000
```

## Type Definitions

### Time Units

```typescript
type TimeUnit = "ms" | "s" | "m" | "h" | "d";
type ValidTimeString = `${number}${TimeUnit}`;
```

## Error Handling

All functions include proper error handling:

- `createConfig().get()` throws if config not initialized
- `generateExpiredDate()` throws on invalid time format
- `generateRandomNumber()` throws if min > max
- `parseTimeString()` throws on invalid time string format

## Examples

### Complete Application Setup

```typescript
import {
  createConfig,
  getSafeNumberFromEnv,
  generateExpiredDate,
} from "@khni/utils";

interface AppConfig {
  port: number;
  databaseUrl: string;
  sessionTimeout: string;
  logger: { info: (msg: string) => void };
}

// Initialize configuration
const appConfig = createConfig<AppConfig>("App");
appConfig.set({
  port: getSafeNumberFromEnv("PORT", 3000),
  databaseUrl: process.env.DATABASE_URL || "localhost",
  sessionTimeout: "24h",
  logger: console,
});

// Use in your application
const config = appConfig.get();
const sessionExpiry = generateExpiredDate(config.sessionTimeout);
```

## License

MIT