    <p align="center">
  <img src="./Logo/Icon.png" alt="Ark.Alliance Logo" width="100"/>
</p>

<h1 align="center">ark-alliance-core</h1>

<p align="center">
  <strong>Universal, extensible, and production-ready TypeScript/Node.js core foundation</strong>
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/ark-alliance-core"><img src="https://img.shields.io/npm/v/ark-alliance-core?color=blue&label=npm" alt="npm version"/></a>
  <a href="https://github.com/M2H-Machine-to-Human-Race/Ark.Alliance.Core/actions/workflows/ci.yml"><img src="https://github.com/M2H-Machine-to-Human-Race/Ark.Alliance.Core/actions/workflows/ci.yml/badge.svg" alt="CI/CD"/></a>
  <a href="https://github.com/M2H-Machine-to-Human-Race/Ark.Alliance.Core/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/ark-alliance-core" alt="License"/></a>
  <img src="https://img.shields.io/badge/TypeScript-5.6+-blue?logo=typescript&logoColor=white" alt="TypeScript"/>
  <img src="https://img.shields.io/badge/Node.js-20%2B-green?logo=node.js&logoColor=white" alt="Node.js"/>
</p>

---

## Overview

`ark-alliance-core` provides battle-tested patterns for building resilient, maintainable backend applications. Built on **Clean Architecture** and **DDD principles** with zero mandatory dependencies.

| Principle | Description |
|-----------|-------------|
| **Zero Mandatory Dependencies** | Core features work with pure TypeScript/Node.js |
| **Railway-Oriented Programming** | Errors are values, not exceptions |
| **Resilience by Default** | Built-in circuit breaker, retry, timeout, bulkhead |
| **Observability-Ready** | Correlation IDs, structured logging, tracing |
| **Provider Abstraction** | Manifest-driven external service integration |

---

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Module Documentation](#module-documentation)
  - [Core Layer](#core-layer)
  - [Infrastructure Layer](#infrastructure-layer)
  - [Domain Layer](#domain-layer)
  - [Controllers](#controllers)
  - [Shared](#shared)
- [Provider Configuration](#provider-configuration)
- [Development](#development)
- [License](#license)

---

## Quick Links

| Resource | Link |
|----------|------|
| **Root README** | [Ark.Alliance.Core](../README.md) |
| **Math Library** | [Ark.Alliance.TypeScript.Core.Math](../Ark.Alliance.TypeScript.Core.Math/README.md) |
| **Core Tests** | [Ark.Alliance.TypeScript.Core.Tests](../Ark.Alliance.TypeScript.Core.Tests/README.md) |
| **Math Tests** | [Ark.Alliance.TypeScript.Core.Math.Test](../Ark.Alliance.TypeScript.Core.Math.Test/README.md) |
| **Contributing** | [CONTRIBUTING.md](../CONTRIBUTING.md) |
| **Changelog** | [CHANGELOG.md](../CHANGELOG.md) |

## Installation

```bash
# npm
npm install ark-alliance-core

# yarn
yarn add ark-alliance-core

# pnpm
pnpm add ark-alliance-core
```

---

## Quick Start

### Result Pattern

Type-safe success/failure handling with railway-oriented programming:

```typescript
import { Result } from 'ark-alliance-core';

async function fetchUser(id: string): Promise<Result<User>> {
    try {
        const user = await db.users.findById(id);
        if (!user) {
            return Result.NotFound.withReason(`User ${id} not found`);
        }
        return Result.ok(user);
    } catch (error) {
        return Result.fromError(error);
    }
}

// Chain operations with automatic error propagation
const result = await fetchUser('123')
    .flatMap(user => validateUser(user))
    .flatMap(user => enrichUserProfile(user));

if (result.isSuccess) {
    console.log('User:', result.data);
} else {
    console.error('Error:', result.error);
}
```

### Resilience Pipeline

Compose fault-tolerance patterns for production-ready operations:

```typescript
import { ResiliencePipeline } from 'ark-alliance-core';

const pipeline = ResiliencePipeline.create()
    .withTimeout({ timeoutMs: 5000 })
    .withRetry({ maxAttempts: 3, useExponentialBackoff: true })
    .withCircuitBreaker({ failureThreshold: 5 })
    .withBulkhead({ maxConcurrency: 10 });

const result = await pipeline.execute(() => httpClient.get('/api/data'));
```

---

## Module Documentation

### Core Layer

The core layer contains business-agnostic patterns and building blocks.

#### Result Pattern

> 📖 [Detailed Documentation](./src/core/result/README.md)

Type-safe alternative to exceptions with 15+ pre-built result types:

```typescript
import { Result, ResultStatus } from 'ark-alliance-core';

// Static shortcuts
const success = Result.ok({ id: 1, name: 'User' });
const notFound = Result.NotFound.withReason('Resource not found');
const timeout = Result.Timeout.withReason('Operation timed out');

// Railway composition
const invoice = await validateOrder(orderId)
    .flatMap(order => calculateTotal(order))
    .flatMap(total => generateInvoice(total));

// Pattern matching
const message = result.match(
    (data) => `Success: ${data.name}`,
    (error) => `Error: ${error.message}`
);
```

| Export | Description |
|--------|-------------|
| `Result<T>` | Core result type with success/failure semantics |
| `PagedResult<T>` | Paginated result for list APIs |
| `ResultStatus` | 20+ status codes with HTTP mapping |
| `safeExecuteAsync()` | Wrap async operations safely |

---

#### Authentication

> 📖 [Detailed Documentation](./src/core/auth/README.md)

Enterprise-grade RBAC, JWT tokens, and multi-provider authentication:

```typescript
import { 
    AuthService, TokenService, UserRole, 
    hasPermission, Permission 
} from 'ark-alliance-core';

// Initialize services
const tokenService = new TokenService({
    accessTokenSecret: process.env.JWT_ACCESS_SECRET!,
    refreshTokenSecret: process.env.JWT_REFRESH_SECRET!,
    accessTokenExpiry: '15m',
    refreshTokenExpiry: '7d',
}, jwt);

const authService = new AuthService(
    { requireEmailVerification: true, maxConcurrentSessions: 5 },
    userRepository, sessionRepository, tokenService, passwordHasher
);

// Register and login
const registerResult = await authService.register({
    email: 'user@example.com',
    password: 'SecurePass123!',
    displayName: 'John Doe',
});

// Check permissions
if (hasPermission(user.permissions, Permission.USERS_WRITE)) {
    // User can create/update users
}
```

| Export | Description |
|--------|-------------|
| `AuthService` | High-level authentication operations |
| `TokenService` | JWT generation/validation with versioning |
| `UserRole` | 5 hierarchical roles (GUEST → SUPERADMIN) |
| `Permission` | 24 granular permissions |

---

#### Identity

> 📖 [Detailed Documentation](./src/core/identity/README.md)

Base entities, DTOs, and repository contracts for user management:

```typescript
import { IBaseUserEntity, IUserRepository, Result } from 'ark-alliance-core';

// Implement repository with your ORM
class UserRepository implements IUserRepository<UserEntity> {
    async findById(id: string): Promise<Result<UserEntity | null>> {
        return Result.tryAsync(() => this.repo.findOne({ where: { id } }));
    }

    async findByEmail(email: string): Promise<Result<UserEntity | null>> {
        return Result.tryAsync(() => 
            this.repo.findOne({ where: { email: email.toLowerCase() } })
        );
    }
}
```

| Export | Description |
|--------|-------------|
| `IBaseUserEntity` | User entity with auth and role info |
| `IBaseCredentialEntity` | Encrypted API credentials (AES-256-GCM) |
| `IBaseTradingAccountEntity` | Trading account linked to credentials |
| `IBaseSessionEntity` | Session with device tracking |

---

#### Notification

> 📖 [Detailed Documentation](./src/core/notification/README.md)

Provider-agnostic, multi-channel notification abstraction:

```typescript
import { 
    NotificationService, NotificationChannel, Priority 
} from 'ark-alliance-core';

const service = new NotificationService({ serviceId: 'notif-svc' });

// Register channel providers
service.registerProvider(NotificationChannel.EMAIL, emailProvider);
service.registerProvider(NotificationChannel.SMS, smsProvider);

// Send notification
const result = await service.send({
    channel: NotificationChannel.EMAIL,
    recipient: { to: 'user@example.com', name: 'John Doe' },
    content: {
        subject: 'Welcome',
        templateId: 'welcome-email',
        templateData: { firstName: 'John' }
    },
    priority: Priority.HIGH
});
```

| Channel | Description |
|---------|-------------|
| SMS, Email, Push | Standard notification channels |
| WhatsApp, Telegram, Signal | Messaging platforms |
| Voice, In-App, P2P | Alternative delivery methods |

---

### Infrastructure Layer

Cross-cutting technical concerns that support business logic.

> 📖 [Layer Overview](./src/infrastructure/README.md)

#### Resilience Patterns

> 📖 [Detailed Documentation](./src/infrastructure/resilience/README.md)

Battle-tested fault tolerance with Result-based policies:

```typescript
import { 
    ResiliencePipeline, RetryPolicy, 
    CircuitBreakerPolicy, BulkheadPolicy 
} from 'ark-alliance-core';

// Individual policies
const retry = new RetryPolicy({
    maxAttempts: 3,
    baseDelayMs: 1000,
    useExponentialBackoff: true,
    jitterFactor: 0.25
});

const circuitBreaker = new CircuitBreakerPolicy({
    failureThreshold: 5,
    successThreshold: 2,
    openDurationMs: 30000
});

// Compose into pipeline (fluent API)
const pipeline = ResiliencePipeline.create()
    .withTimeout({ timeoutMs: 5000 })
    .withRetry({ maxAttempts: 3 })
    .withCircuitBreaker({ failureThreshold: 5 })
    .withBulkhead({ maxConcurrency: 10 })
    .withFallback({ fallback: () => defaultValue });

const result = await pipeline.execute(() => riskyOperation());
```

---

#### HTTP Client

> 📖 [Detailed Documentation](./src/infrastructure/http/README.md)

Type-safe HTTP communication with Result pattern:

```typescript
import { RestHttpClient } from 'ark-alliance-core';

const client = new RestHttpClient({
    baseUrl: 'https://api.example.com',
    timeout: 10000,
    retry: {
        maxAttempts: 3,
        exponentialBackoff: true,
        retryOnCodes: [429, 500, 502, 503, 504]
    }
});

// Type-safe requests
const users = await client.get<User[]>('/users');
if (users.isSuccess) {
    users.data.forEach(u => console.log(u.name));
}

// POST with body
const created = await client.post<User>('/users', { 
    name: 'John Doe', email: 'john@example.com' 
});
```

---

#### Cache

> 📖 [Detailed Documentation](./src/infrastructure/cache/README.md)

High-performance concurrent caching with LRU/TTL eviction:

```typescript
import { ConcurrentCache } from 'ark-alliance-core';

const cache = new ConcurrentCache<string, User>({
    maxSize: 1000,
    ttlMs: 60000,  // 1 minute
    evictionPolicy: 'lru'
});

// Thread-safe operations
await cache.set('user:123', userData);
const user = await cache.get('user:123');
await cache.delete('user:123');
```

---

#### Concurrency

> 📖 [Detailed Documentation](./src/infrastructure/concurrency/README.md)

Low-level synchronization primitives:

```typescript
import { Semaphore, AsyncLock } from 'ark-alliance-core';

// Limit concurrent operations
const semaphore = new Semaphore(5);

await semaphore.acquire();
try {
    await processRequest();
} finally {
    semaphore.release();
}

// Serialize async operations
const lock = new AsyncLock();

await lock.runExclusive(async () => {
    await criticalSection();
});

---

#### Logging

> 📖 [Detailed Documentation](./src/infrastructure/logging/README.md)

Production-ready structured logging with pluggable transports:

```typescript
import { 
    LoggingService, LogLevel, LogRepository, 
    DatabaseTransport 
} from 'ark-alliance-core';

// Create logger with custom transport
const logger = new LoggingService({
    serviceName: 'my-service',
    minLevel: LogLevel.INFO,
});

// Add database persistence
const repository = new LogRepository({ adapter: dbAdapter });
logger.addTransport(new DatabaseTransport({ repository }));

// Log with structured context
logger.info('User logged in', { 
    userId: 123, 
    method: 'oauth2' 
});

// Create child logger for component
const authLogger = logger.createChild({ component: 'auth' });
authLogger.warn('Rate limit approaching', { remaining: 5 });

// Query logs from repository
const result = await repository.getLogs({
    level: LogLevel.ERROR,
    startDate: new Date('2024-01-01'),
    limit: 100
});
```

| Export | Description |
|--------|-------------|
| `LoggingService` | Main logger with transport system |
| `LogLevel` | 7-level enum with platform mappings |
| `LogRepository` | Database persistence with async queue |
| `DatabaseTransport` | Transport for database storage |

---

#### Data Access

> 📖 [Detailed Documentation](./src/infrastructure/data/README.md)

Database-agnostic data access layer with Result pattern:

```typescript
import { 
    BaseRepository, IDatabaseAdapter, 
    AsyncOperationQueue 
} from 'ark-alliance-core';

// Implement custom repository
class UserRepository extends BaseRepository<User, UserRow> {
    constructor(adapter: IDatabaseAdapter) {
        super({
            adapter,
            tableName: 'users',
            rowToEntity: (row) => ({
                id: row.id,
                name: row.name,
                email: row.email
            })
        });
    }
}

// Use async queue for non-blocking writes
const queue = new AsyncOperationQueue({ batchSize: 50 });
queue.start();

queue.enqueue({
    type: 'insert',
    priority: 'normal',
    operation: () => db.insert(data)
});
```

| Export | Description |
|--------|-------------|
| `IDatabaseAdapter` | Database-agnostic interface |
| `BaseRepository` | Generic CRUD with Result pattern |
| `AsyncOperationQueue` | Non-blocking batched writes |
| `NullDatabaseAdapter` | No-op adapter for testing |

---

#### Providers

> 📖 [Detailed Documentation](./src/infrastructure/providers/README.md)

Universal, manifest-driven provider abstraction:

```typescript
import { 
    ProviderRegistry, ResilientProvider, 
    GenericProviderAdapter 
} from 'ark-alliance-core';
import githubManifest from './providers/JsonProvidersConfiguration/Git/github.json';

// Register provider with manifest
ProviderRegistry.instance.register({
    manifest: githubManifest,
    factory: () => new GitHubClient(githubManifest, config)
});

// Create and use with resilience
const github = ProviderRegistry.instance.create('git', 'github');
const resilient = new ResilientProvider(github, {
    retry: { enabled: true, maxAttempts: 3 },
    circuitBreaker: { enabled: true, failureThreshold: 5 }
});

await resilient.connect({ auth: { type: 'pat', token: process.env.GITHUB_TOKEN } });
const repos = await resilient.executeWithResilience(() => 
    github.call('listRepositories', { owner: 'my-org' })
);
```

---

#### Mapping

> 📖 [Detailed Documentation](./src/infrastructure/providers/mapping/README.md)

Universal data transformation between models:

```typescript
import { BaseFeatureMapper, getMappingRegistry } from 'ark-alliance-core';

const registry = getMappingRegistry();

// Register mapping configuration
registry.register('order-api', {
    enums: [{
        abstractEnum: 'OrderStatus',
        targetEnum: 'status',
        values: [
            { abstract: 'PENDING', target: 'P' },
            { abstract: 'SHIPPED', target: 'S' }
        ]
    }],
    fields: [
        { abstractField: 'createdAt', targetField: 'created_at' }
    ]
}, 'ecommerce');

// Use mapper
const mapper = registry.getMapper('order-api');
const abstractData = mapper.mapObjectFromSource(sourceData);
```

---

### Domain Layer

> 📖 [Detailed Documentation](./src/domain/README.md)

Generic DDD patterns for event-driven architecture:

```typescript
import { DomainEvent } from 'ark-alliance-core';

// Create domain events (past tense - facts that happened)
export class UserRegisteredEvent extends DomainEvent {
    readonly eventType = 'UserRegistered';
    
    constructor(
        userId: string,
        public readonly email: string,
        public readonly displayName: string
    ) {
        super(userId, 'User', 1);
    }
    
    protected getPayload(): Record<string, unknown> {
        return { email: this.email, displayName: this.displayName };
    }
}

// Usage
const event = new UserRegisteredEvent('user-123', 'john@example.com', 'John');
console.log(event.toJSON());
```

---

### Controllers

> 📖 [Detailed Documentation](./src/controllers/README.md)

Request handling and middleware infrastructure:

```typescript
import { TokenBucketRateLimiter, SlidingWindowRateLimiter } from 'ark-alliance-core';

// Token bucket - allows bursts
const limiter = TokenBucketRateLimiter.perMinute(100);

// Check request
const result = await limiter.check(request);
if (!result.data?.allowed) {
    return res.status(429).json({ 
        error: 'Too Many Requests',
        retryAfter: result.data?.retryAfter 
    });
}

// Strict mode for sensitive endpoints (5 req/min)
const loginLimiter = TokenBucketRateLimiter.strict();
```

---

### Shared

> 📖 [Detailed Documentation](./src/shared/README.md)

Cross-cutting enums and utilities:

```typescript
import { 
    HttpMethod, ConnectionState, HealthStatus, 
    Priority, TimeUnit, toMilliseconds 
} from 'ark-alliance-core';

// Type-safe enums
const method: HttpMethod = HttpMethod.GET;
const state: ConnectionState = ConnectionState.CONNECTING;
const health: HealthStatus = HealthStatus.HEALTHY;

// Time utilities
const ms = toMilliseconds(5, TimeUnit.MINUTES); // 300000
```

---

## Provider Configuration

The Providers module uses JSON manifests for declarative configuration. Located in `src/infrastructure/providers/JsonProvidersConfiguration/`:

### Available Provider Categories

| Category | Providers |
|----------|-----------|
| **Brokers** | RabbitMQ, Kafka, IBM MQ, ZeroMQ |
| **Git** | GitHub, GitLab, Bitbucket, Azure DevOps, Gitea, HuggingFace |
| **Storage** | Azure Blob Storage |
| **Notifications** | Twilio, SendGrid, Firebase FCM, Telegram, Signal |
| **Hardware** | Camera, Microphone, Geolocation, Accelerometer, Gamepad |
| **Protocols** | SFTP, MQTT |

### Using Provider Manifests

```typescript
// Load manifest
import githubManifest from './JsonProvidersConfiguration/Git/github.json';

// Manifest structure includes:
// - connection: baseUrl, authentication methods
// - endpoints: API paths with parameters
// - rateLimits: request limits per tier
// - resilience: retry, circuit breaker, timeout config
// - mappings: enum and field translation

// Create client from manifest
const client = new GitHubClient(githubManifest, {
    auth: { type: 'pat', token: process.env.GITHUB_TOKEN }
});

// Manifest-driven resilience
const resilience = createResiliencePipeline(githubManifest.resilience);
// Creates pipeline with retry (3 attempts), circuit breaker, 30s timeout
```

### Sample Manifest Structure

```json
{
    "id": "git-github",
    "name": "GitHub",
    "type": "git",
    "connection": {
        "baseUrl": "https://api.github.com",
        "timeout": 30000
    },
    "authentication": {
        "methods": [
            { "type": "pat", "required": ["token"] },
            { "type": "oauth", "required": ["clientId", "clientSecret"] }
        ]
    },
    "resilience": {
        "retry": { "enabled": true, "maxAttempts": 3 },
        "circuitBreaker": { "enabled": true, "failureThreshold": 5 }
    },
    "mappings": {
        "enums": [{ "enumName": "PullRequestState", "entries": [...] }]
    }
}
```

---

## Development

### Building from Source

```bash
# Clone repository
git clone https://github.com/M2H-Machine-to-Human-Race/Ark.Alliance.Core.git
cd Ark.Alliance.Core/Ark.Alliance.TypeScript.Core

# Install dependencies
npm install

# Build
npm run build

# Type check
npm run typecheck

# Lint
npm run lint
```

### Running Tests

```bash
# From repository root
cd Ark.Alliance.TypeScript.Core.Tests
npm install
npm test

# With coverage
npm run test:coverage
```

### Available Scripts

| Command | Description |
|---------|-------------|
| `npm run build` | Build library (ESM + CJS + DTS) |
| `npm run dev` | Watch mode for development |
| `npm run lint` | Run ESLint |
| `npm run lint:fix` | Fix ESLint issues |
| `npm run typecheck` | TypeScript type checking |
| `npm run format` | Format code with Prettier |

---

## License

MIT License - see [LICENSE](./LICENSE) for details.

---

<p align="center">
  <sub>M2H.IO (c) 2025 - Ark.Alliance Ecosystem - Armand Richelet-Kleinberg</sub>
</p>
