npm package: @onyxon/core
Description: Reusable backend utilities for custom business apps
Latest version: 0.1.0
Deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

# @org/core

Reusable backend utilities for custom business applications.

A minimal, framework-agnostic TypeScript package providing utilities, validation schemas, types, and configuration helpers.

## Installation

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

## Features

- **Utilities**: String, date, number, and helper functions
- **Validation**: Zod schemas for common entities (User, Client, Lead)
- **Types**: Reusable TypeScript types and interfaces
- **Errors**: Custom error classes (AppError, ValidationError)
- **Config**: Environment variable validation

## Usage

### Utilities

#### String Utilities

```typescript
import { slugify, capitalize, truncate } from "@org/core";

slugify("Hello World!"); // "hello-world"
capitalize("hello"); // "Hello"
truncate("Long text here", 10); // "Long text..."
```

#### Date Utilities

```typescript
import { formatDate, formatDateShort, isValidDate, now, nowISO } from "@org/core";

formatDate(new Date()); // "2024-01-01T00:00:00.000Z"
formatDateShort(new Date()); // "2024-01-01"
isValidDate(new Date()); // true
now(); // 1704067200000
nowISO(); // "2024-01-01T00:00:00.000Z"
```

#### Number Utilities

```typescript
import { formatNumber, formatCurrency, clamp, isNumber } from "@org/core";

formatNumber(1234567); // "1,234,567"
formatCurrency(1234.56, "USD"); // "$1,234.56"
clamp(150, 0, 100); // 100
isNumber(42); // true
```

#### Helper Functions

```typescript
import { generateId, isEmpty, deepClone } from "@org/core";

generateId(); // "aB3dE5fG7hI9jK1"
generateId(32); // 32-character ID
isEmpty(null); // true
isEmpty(""); // true
isEmpty([]); // true
isEmpty({}); // true
deepClone({ a: 1, b: { c: 2 } }); // Deep copy
```

#### API Validation

```typescript
import { validate, validateSafe } from "@org/core";
import { UserSchema } from "@org/core";

// Throws ValidationError if invalid
const user = validate(UserSchema, {
  id: "123",
  email: "user@example.com",
  name: "John",
  createdAt: new Date(),
  updatedAt: new Date(),
});

// Returns result object
const result = validateSafe(UserSchema, invalidData);
if (result.success) {
  console.log(result.data);
} else {
  console.error(result.error);
}
```

### Validation Schemas

#### Common Schemas

```typescript
import {
  EmailSchema,
  PhoneSchema,
  NameSchema,
  IdSchema,
  TimestampSchema,
  PaginationSchema,
} from "@org/core";

EmailSchema.parse("user@example.com"); // ✅
EmailSchema.parse("invalid"); // ❌ throws ZodError

PhoneSchema.parse("+1234567890"); // ✅
NameSchema.parse("John Doe"); // ✅
IdSchema.parse("abc123"); // ✅
```

#### User Schema

```typescript
import {
  UserSchema,
  CreateUserSchema,
  UpdateUserSchema,
  type User,
  type CreateUser,
  type UpdateUser,
} from "@org/core";

// Validate user data
const user: User = UserSchema.parse({
  id: "123",
  email: "user@example.com",
  name: "John",
  createdAt: new Date(),
  updatedAt: new Date(),
});

// Validate create input
const newUser: CreateUser = CreateUserSchema.parse({
  email: "new@example.com",
  name: "Jane",
});

// Validate update input
const updates: UpdateUser = UpdateUserSchema.parse({
  name: "Jane Doe",
});
```

#### Client Schema

```typescript
import {
  ClientSchema,
  CreateClientSchema,
  UpdateClientSchema,
  type Client,
  type CreateClient,
  type UpdateClient,
} from "@org/core";

const client: Client = ClientSchema.parse({
  id: "123",
  name: "Acme Corp",
  email: "contact@acme.com",
  createdAt: new Date(),
  updatedAt: new Date(),
});
```

#### Lead Schema

```typescript
import {
  LeadSchema,
  CreateLeadSchema,
  UpdateLeadSchema,
  type Lead,
  type CreateLead,
  type UpdateLead,
} from "@org/core";

const lead: Lead = LeadSchema.parse({
  id: "123",
  name: "John Doe",
  email: "john@example.com",
  phone: "+1234567890",
  createdAt: new Date(),
  updatedAt: new Date(),
});
```

#### Pagination

```typescript
import { PaginationSchema } from "@org/core";

const pagination = PaginationSchema.parse({
  page: 1,
  pageSize: 20,
});
```

### Types

```typescript
import {
  GenericRecord,
  PaginatedResult,
  BaseEntity,
  type User,
  type Client,
  type Lead,
} from "@org/core";

// Generic record
const record: GenericRecord = { key: "value" };

// Paginated result
const result: PaginatedResult<User> = {
  items: [user1, user2],
  total: 100,
  page: 1,
  pageSize: 20,
  totalPages: 5,
};

// Base entity
interface CustomEntity extends BaseEntity {
  customField: string;
}
```

### Error Handling

```typescript
import { AppError, ValidationError } from "@org/core";

// Custom application error
throw new AppError("Something went wrong", "ERROR_CODE", 500);

// Validation error
throw new ValidationError("Invalid input", [
  { path: "email", message: "Invalid email format" },
]);

// Using with validation
import { validate } from "@org/core";
import { UserSchema } from "@org/core";

try {
  const user = validate(UserSchema, data);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error("Validation failed:", error.issues);
  }
}
```

### Configuration

```typescript
import { loadConfig, getConfig } from "@org/core";

// Load and validate environment variables
const config = loadConfig();
// Returns: { NODE_ENV: "development", PORT?: number, DATABASE_URL?: string }

// Get config (loads if not already loaded)
const env = getConfig();

// Access values
console.log(config.NODE_ENV); // "development"
console.log(config.PORT); // number | undefined
```

Environment variables are validated using Zod. Required variables will throw an error if missing.

## API Reference

### Utilities

#### String

- `slugify(text: string): string` - Converts string to URL-friendly slug
- `capitalize(text: string): string` - Capitalizes first letter
- `truncate(text: string, maxLength: number, ellipsis?: string): string` - Truncates string

#### Date

- `formatDate(date: Date | string | number): string` - Formats to ISO string
- `formatDateShort(date: Date | string | number): string` - Formats to YYYY-MM-DD
- `isValidDate(date: unknown): date is Date` - Checks if date is valid
- `now(): number` - Current timestamp in milliseconds
- `nowISO(): string` - Current date as ISO string

#### Number

- `formatNumber(num: number, locale?: string): string` - Formats with thousand separators
- `formatCurrency(num: number, currency?: string, locale?: string): string` - Formats as currency
- `clamp(value: number, min: number, max: number): number` - Clamps value between min and max
- `isNumber(value: unknown): value is number` - Checks if value is a valid number

#### Helpers

- `generateId(length?: number): string` - Generates random ID string
- `isEmpty(value: unknown): boolean` - Checks if value is empty
- `deepClone<T>(obj: T): T` - Deep clones an object

#### API

- `validate<T>(schema: ZodSchema<T>, data: unknown): T` - Validates and throws on error
- `validateSafe<T>(schema: ZodSchema<T>, data: unknown): { success: true; data: T } | { success: false; error: ValidationError }` - Validates and returns result

### Schemas

All schemas are Zod schemas and can be used with Zod's API:

- `EmailSchema` - Email validation
- `PhoneSchema` - Phone number validation
- `NameSchema` - Name validation (1-255 chars)
- `IdSchema` - ID validation
- `TimestampSchema` - Timestamp validation (string, Date, or number)
- `PaginationSchema` - Pagination parameters
- `UserSchema`, `CreateUserSchema`, `UpdateUserSchema` - User schemas
- `ClientSchema`, `CreateClientSchema`, `UpdateClientSchema` - Client schemas
- `LeadSchema`, `CreateLeadSchema`, `UpdateLeadSchema` - Lead schemas

### Types

- `GenericRecord` - `Record<string, unknown>`
- `PaginatedResult<T>` - Paginated result interface
- `BaseEntity` - Base entity with id, createdAt, updatedAt
- `User`, `CreateUser`, `UpdateUser` - User types
- `Client`, `CreateClient`, `UpdateClient` - Client types
- `Lead`, `CreateLead`, `UpdateLead` - Lead types

### Errors

- `AppError` - Base application error class
- `ValidationError` - Validation error class (extends AppError)

### Config

- `loadConfig()` - Loads and validates environment variables
- `getConfig()` - Gets config (loads if not already loaded)

## Development

```bash
# Install dependencies
pnpm install

# Build
pnpm build

# Watch mode
pnpm dev

# Type check
pnpm type-check

# Lint
pnpm lint

# Format
pnpm format
```

## License

MIT