npm package: @lunarcore/node
Description: TypeScript-first foundational SDK for Node.js backends - secure, typed, framework-agnostic
Author: LunarBit Studios
Latest version: 0.1.1

# LunarCore Node

**TypeScript-first foundational SDK for Node.js backends**

[![npm version](https://badge.fury.io/js/%40lunarcore%2Fnode.svg)](https://www.npmjs.com/package/@lunarcore/node)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

LunarCore Node is a secure, type-safe foundational SDK for building Node.js backend applications. It provides essential utilities without framework coupling, making it perfect for any Node.js project.

## Features

- **TypeScript-First** - Built with strict TypeScript for maximum type safety
- **Secure by Default** - Security best practices baked in
- **Zero Framework Coupling** - Use with Express, Fastify, or any framework
- **Modular Design** - Import only what you need
- **Production Ready** - Comprehensive error handling and logging

## Installation

```bash
npm install @lunarcore/node zod
```

## Quick Start

```typescript
import { createLogger, loadEnv, retry } from '@lunarcore/node';
import { z } from 'zod';

// Type-safe environment loading
const env = loadEnv(z.object({
  PORT: z.string().transform(Number),
  API_KEY: z.string(),
}));

// Structured logging
const logger = createLogger({ level: 'info' });
logger.info('Server starting', { port: env.PORT });

// Safe async operations
const data = await retry(() => fetchData(), { maxAttempts: 3 });
```

## Core Modules

### Error Handling

Type-safe error classes with structured context:

```typescript
import { AppError, ValidationError, isAppError } from '@lunarcore/node';

// Custom errors with context
throw new ValidationError('Invalid email', { email: 'test@' });

// Type-safe error handling
try {
  await operation();
} catch (error) {
  if (isAppError(error)) {
    console.log(error.code, error.statusCode, error.context);
  }
}
```

### Environment Variables

Schema-based environment validation with Zod:

```typescript
import { loadEnv, envNumber, envBoolean } from '@lunarcore/node';
import { z } from 'zod';

const env = loadEnv(z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']),
  PORT: envNumber.default(3000),
  ENABLE_CACHE: envBoolean.default(true),
  ALLOWED_ORIGINS: envList, // Comma-separated lists
}));
```

### Configuration Management

Flexible configuration loading with validation:

```typescript
import { ConfigManager, createJsonLoader } from '@lunarcore/node';

const manager = new ConfigManager(
  createJsonLoader('./config.json'),
  (config) => validateConfig(config)
);

const config = await manager.load(); // Load and cache
const cached = manager.get(); // Get cached config
await manager.reload(); // Force reload
```

### Structured Logging

Production-ready logging with context:

```typescript
import { createLogger, LogLevel } from '@lunarcore/node';

const logger = createLogger({
  level: LogLevel.INFO,
  defaultContext: { service: 'api' },
});

logger.info('User login', { userId: 123, ip: '1.2.3.4' });

// Child loggers inherit context
const requestLogger = logger.child({ requestId: 'req-456' });
requestLogger.info('Processing'); // Includes requestId
```

### Async Utilities

Safe async operations with retry, timeout, and concurrency control:

```typescript
import { 
  retry, 
  withTimeout, 
  asyncResult, 
  promiseLimit 
} from '@lunarcore/node';

// Retry with exponential backoff
const data = await retry(
  () => fetchData(),
  { maxAttempts: 3, initialDelay: 1000 }
);

// Add timeout
const result = await withTimeout(
  slowOperation(),
  5000,
  'Operation timed out'
);

// Safe Result type (no throws)
const result = await asyncResult(riskyOperation());
if (result.ok) {
  console.log(result.value);
} else {
  console.error(result.error);
}

// Concurrency control
const results = await promiseLimit(
  urls,
  (url) => fetch(url),
  5 // Max 5 concurrent requests
);
```

## Examples

Complete usage examples are available in the `examples/` directory:

- **env-loader.ts** - Environment variable loading with schema validation
- **logger.ts** - Structured logging patterns
- **error-handling.ts** - Error handling and custom errors
- **config-loader.ts** - Configuration management strategies
- **async-helpers.ts** - Async utilities and patterns

## Design Principles

### Type Safety First

Every API is designed with strict TypeScript in mind. No `any` types, comprehensive type inference, and full IntelliSense support.

### Secure by Default

- Input validation with Zod schemas
- No eval or code execution
- Safe error serialization (no sensitive data leaks)
- Security best practices in all utilities

### Framework Agnostic

LunarCore Node provides foundational utilities without coupling to specific frameworks. Use it with Express, Fastify, Koa, or any Node.js setup.

### Modular Architecture

```typescript
// Import only what you need
import { createLogger } from '@lunarcore/node/logger';
import { retry } from '@lunarcore/node/async';
```

## API Reference

### Errors

- `AppError` - Base error class
- `ValidationError` - Input validation errors (400)
- `ConfigurationError` - Configuration errors (500)
- `NotFoundError` - Resource not found (404)
- `TimeoutError` - Operation timeout (408)
- `isAppError()` - Type guard
- `isOperationalError()` - Check if error is operational

### Environment

- `loadEnv()` - Load and validate environment
- `safeLoadEnv()` - Non-throwing variant
- `envNumber` - Parse number from string
- `envBoolean` - Parse boolean from string
- `envList` - Parse comma-separated list
- `envWithDefault()` - Add default values

### Config

- `ConfigManager` - Configuration management
- `JsonConfigLoader` - Load from JSON files
- `ObjectConfigLoader` - Load from objects
- `CompositeConfigLoader` - Merge multiple sources

### Logger

- `createLogger()` - Create logger instance
- `Logger` - Logger class
- `LogLevel` - Log level enum
- `ConsoleTransport` - Console output
- `JsonTransport` - JSON output

### Async

- `asyncResult()` - Wrap promise in Result type
- `retry()` - Retry with exponential backoff
- `withTimeout()` - Add timeout to promise
- `sleep()` - Promise-based delay
- `promiseLimit()` - Concurrency control
- `batchProcess()` - Process items in batches
- `debounce()` - Debounce async function
- `throttle()` - Throttle async function

## TypeScript Configuration

LunarCore Node requires strict TypeScript settings. Add to your `tsconfig.json`:

```json
{
  "compilerOptions": {
    "strict": true,
    "target": "ES2022",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true
  }
}
```

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## Security

For security concerns, please see [SECURITY.md](SECURITY.md).

## Publishing

See [PUBLISHING.md](PUBLISHING.md) for detailed instructions on publishing this package to npm as `@lunarcore/node`.

## License

MIT © LunarBit Studios

## Related Projects

- [LunarCore Spec](https://github.com/LunarBit-dev/LunarCore-spec) - Specification and design principles
- More LunarCore modules coming soon

## Support

- [Documentation](https://github.com/LunarBit-dev/LunarCore-node)
- [Issue Tracker](https://github.com/LunarBit-dev/LunarCore-node/issues)
- [Discussions](https://github.com/LunarBit-dev/LunarCore-node/discussions)