Skip to content

ziegel-core

The @breadstone/ziegel-core package is the foundation of the ziegel Enterprise TypeScript Framework. It provides essential building blocks including LINQ2 implementation, generic collections, exception handling, reactive patterns, and comprehensive utilities that power all other ziegel packages.

Foundation Package: The backbone of the ziegel ecosystem, delivering enterprise-grade TypeScript utilities and patterns.

🚀 Why ziegel-core?

  • 🔗 LINQ2 Implementation: Complete LINQ-to-Objects with fluent querying for TypeScript
  • 📚 Generic Collections: Type-safe Queue, Stack, Dictionary, LinkedList, Bag, Heap, Set implementations
  • ⚡ Extensions: Rich extension methods for Array, String, Number, Date, Object, Map, and Function
  • 🎨 Color System: Advanced color manipulation with RGB, HSL, HSB, CMYK, YUV support
  • 🔒 Security: MD5, SHA1 hash algorithms with crypto service providers
  • ⏰ Time Management: DateTime, TimeSpan, DateRange with comprehensive operations
  • 🏗️ Exception System: Structured exception hierarchy for robust error handling
  • 🎯 Type Safety: Advanced TypeScript utilities and type guards

📦 Installation

bash
npm install @breadstone/ziegel-core
# or
yarn add @breadstone/ziegel-core

⭐ Key Features

LINQ2 Implementation

Powerful LINQ-style querying with full TypeScript support:

typescript
import { linq } from '@breadstone/ziegel-core';

const users = [
  { id: 1, name: 'Alice', age: 30, department: 'Engineering' },
  { id: 2, name: 'Bob', age: 25, department: 'Marketing' },
  { id: 3, name: 'Charlie', age: 35, department: 'Engineering' }
];

// Find senior engineers
const seniorEngineers = linq(users)
  .where(u => u.department === 'Engineering')
  .where(u => u.age >= 30)
  .select(u => ({ name: u.name, experience: 'Senior' }))
  .toArray();

// Group by department with averages
const departmentStats = linq(users)
  .groupBy(u => u.department)
  .select(g => ({
    department: g.key,
    count: g.count(),
    averageAge: g.average(u => u.age)
  }))
  .toArray();

Generic Collections

Enterprise-grade collections with full type safety:

typescript
import { Queue, Stack, Dictionary, LinkedList, Set } from '@breadstone/ziegel-core';

// Type-safe queue operations
const taskQueue = new Queue<string&gt;();
taskQueue.enqueue('Process order');
taskQueue.enqueue('Send email');
const nextTask = taskQueue.dequeue(); // 'Process order'

// Dictionary with custom key-value types
const userCache = new Dictionary<string, User&gt;();
userCache.add('user123', { id: '123', name: 'Alice' });
const user = userCache.get('user123');

// Mathematical set operations
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);
const intersection = setA.intersect(setB); // [3, 4]
const union = setA.union(setB); // [1, 2, 3, 4, 5, 6]

Rich Extension Methods

Enhance built-in types with powerful extensions:

typescript
import '@breadstone/ziegel-core/Extensions';

// Array extensions
const numbers = [1, 2, 3, 4, 5];
numbers.shuffle(); // Randomize order
const chunked = numbers.chunk(2); // [[1,2], [3,4], [5]]
const flattened = [[1, 2], [3, 4]].flatten(); // [1, 2, 3, 4]

// String extensions
const text = "Hello World";
text.capitalize(); // "Hello world"
text.slugify(); // "hello-world"
text.truncate(8); // "Hello..."
text.stripHtml(); // Remove HTML tags

// Number extensions
const price = 123.456;
price.round(2); // 123.46
price.clamp(0, 100); // 100
price.toBytes(); // "123.46 B"

// Date extensions
const date = new Date();
date.addDays(7); // Next week
date.addMonths(3); // Quarter ahead
date.isWeekend(); // Boolean
date.quarter(); // 1-4

Advanced Color System

Professional color manipulation with multiple color spaces:

typescript
import { Color, Colors } from '@breadstone/ziegel-core';

// Create colors from different formats
const red = Color.fromRgb(255, 0, 0);
const blue = Color.fromHex('#0066FF');
const green = Color.fromHsl(120, 100, 50);

// Color transformations
const lighterRed = red.lighten(0.2);
const darkerBlue = blue.darken(0.3);
const complement = red.complement();
const analogous = red.analogous();

// Color space conversions
const hslValues = red.toHsl(); // { h: 0, s: 100, l: 50 }
const cmykValues = red.toCmyk(); // { c: 0, m: 100, y: 100, k: 0 }

// Predefined color palette
const primaryBlue = Colors.Blue.Primary;
const accentOrange = Colors.Orange.Accent;
### Exception System

Robust exception hierarchy for enterprise error handling:

```typescript
import {
  ArgumentNullException,
  ArgumentOutOfRangeException,
  InvalidOperationException,
  NotImplementedException
} from '@breadstone/ziegel-core';

// Type-safe exception handling
function processUserData(data: unknown, index: number) {
  if (data === null || data === undefined) {
    throw new ArgumentNullException('data');
  }

  if (index < 0) {
    throw new ArgumentOutOfRangeException('index', 'Index must be non-negative');
  }

  // Business logic...
}

// Custom exception with context
try {
  processUserData(null, -1);
} catch (error) {
  if (error instanceof ArgumentNullException) {
    console.log(`Null argument: ${error.paramName}`);
  }
}

Security & Cryptography

Hash algorithms with crypto service providers:

typescript
import { MD5, SHA1, MD5CryptoServiceProvider } from '@breadstone/ziegel-core';

// Hash computation
const md5 = new MD5();
const sha1 = new SHA1();

const data = 'sensitive data';
const md5Hash = md5.computeHash(data);
const sha1Hash = sha1.computeHash(data);

// Crypto service provider pattern
const md5Provider = new MD5CryptoServiceProvider();
const hashedPassword = md5Provider.computeHash(password + salt);

Time Management

Comprehensive date and time operations:

typescript
import { DateTime, TimeSpan, DateRange } from '@breadstone/ziegel-core';

// DateTime operations
const now = DateTime.now();
const utcNow = DateTime.utcNow();
const birthday = DateTime.parse('1990-05-15');

const age = now.subtract(birthday);
const nextYear = now.addYears(1);

// TimeSpan calculations
const duration = TimeSpan.fromHours(2.5);
const totalMinutes = duration.totalMinutes(); // 150

// Date ranges
const projectRange = new DateRange(
  DateTime.parse('2024-01-01'),
  DateTime.parse('2024-12-31')
);

const isActive = projectRange.contains(DateTime.now());
const overlap = projectRange.intersect(otherRange);

Reactive Patterns

Disposables and observable patterns:

typescript
import { CompositeDisposable, AnonymousDisposable } from '@breadstone/ziegel-core';

// Manage multiple subscriptions
const subscriptions = new CompositeDisposable();

subscriptions.add(
  AnonymousDisposable.create(() => {
    console.log('Cleanup resource 1');
  })
);

subscriptions.add(
  AnonymousDisposable.create(() => {
    console.log('Cleanup resource 2');
  })
);

// Dispose all at once
subscriptions.dispose();

Advanced Type System

Professional TypeScript utilities:

typescript
import {
  Nullable, Optional, NonEmptyArray,
  DeepPartial, DeepRequired, Func1, Action1,
  TypeGuard, Guard
} from '@breadstone/ziegel-core';

// Advanced type definitions
type UserProfile = {
  id: string;
  name: string;
  email: Nullable<string&gt;;
  preferences: Optional<UserPreferences&gt;;
};

// Type-safe functions
const processUsers: Func1<NonEmptyArray&lt;User&gt;, ProcessResult&gt; = (users) => {
  return users.map(user => processUser(user));
};

// Runtime type checking
function validateUser(data: unknown): data is User {
  return TypeGuard.isObject(data) &&
         TypeGuard.hasProperty(data, 'id') &&
         TypeGuard.isString(data.id);
}

// Guard clauses
function updateUser(user: User, updates: DeepPartial<User&gt;) {
  Guard.notNull(user, 'user');
  Guard.notEmpty(updates, 'updates');

  // Safe to proceed...
}

age: Rules.number().min(18).max(120), name: Rules.required().minLength(2).maxLength(50) });

const result = userValidator.validate({ email: 'john@example.com', age: 25, name: 'John Doe' });

if (result.isValid) { console.log('User data is valid!'); } else { console.log('Validation errors:', result.errors); }


## API Reference

For detailed API documentation, see the [generated API reference](../api/ziegel-core/index.md).

## Best Practices

### 1. Use Type Guards
Always use the built-in type guards for runtime type checking:

```typescript
import { Guard } from '@breadstone/ziegel-core';

function processData(data: unknown) {
  Guard.isArray(data, 'Data must be an array');
  // TypeScript now knows data is an array
}

2. Prefer StringExtensions

Use StringExtensions for all string operations instead of manual implementations:

typescript
// ✅ Good
const formatted = StringExtensions.format('User {0} has {1} points', name, points);

// ❌ Avoid
const formatted = `User ${name} has ${points} points`;

3. Validate Early

Use the validation framework at your application boundaries:

typescript
// ✅ Good - validate at API entry points
app.post('/users', (req, res) => {
  const validationResult = userValidator.validate(req.body);
  if (!validationResult.isValid) {
    return res.status(400).json({ errors: validationResult.errors });
  }
  // Process valid data
});

Migration from Other Libraries

From Lodash

ziegel-core provides many utilities that replace common Lodash functions:

typescript
// Lodash
import _ from 'lodash';
const grouped = _.groupBy(array, 'property');

// ziegel-core
import { Collections } from '@breadstone/ziegel-core';
const grouped = Collections.groupBy(array, item => item.property);

From Joi/Yup

The built-in validation system provides a modern alternative:

typescript
// Joi
const schema = Joi.object({
  email: Joi.string().email().required(),
  age: Joi.number().min(18)
});

// ziegel-core
const validator = Validator.create({
  email: Rules.required().email(),
  age: Rules.number().min(18)
});