npm package: @severus-lab-llc/severus-nexus
Description: Connect to unlimited APIs with OpenAPI, config-driven, or generic approaches. Methods are auto-generated at runtime—no code generation needed.
Author: Steven A. Matías Pérez
Latest version: 1.0.0

# Severus Nexus 🚀

A powerful, flexible TypeScript library for integrating with unlimited APIs. Supports OpenAPI/Swagger specifications, config-driven definitions, and generic HTTP clients. **Methods are auto-generated at runtime** - no code generation needed!

## ⚡ Quick Start

### Installation

```bash
npm install @severus-lab-llc/severus-nexus
# or
pnpm add @severus-lab-llc/severus-nexus
# or
yarn add @severus-lab-llc/severus-nexus
```

### 30-Second Example

```typescript
import { SeverusNexus } from '@severus-lab-llc/severus-nexus';

const gateway = new SeverusNexus();

// Add any API and start using it!
const api = await gateway.addGeneric(
  'my-api',
  'https://api.example.com',
  { type: 'bearer', token: 'your-token' },
  {}
);

const data = await api.callGet('/users');
```

## 🎯 How It Works

**Magic happens at RUNTIME** ✨

When you load an API definition, methods are **automatically generated** on the fly:

```typescript
const stripe = await gateway.addFromConfigFile('./stripe.yaml', { token: '...' });

// Methods are created dynamically!
const customer = await stripe.createCustomer({ email: 'test@test.com' });
//                          ^^^^^^^^^^^^^^ ← This method was just created!
```

**No build step. No code generation. Just instant availability.**

[Read detailed explanation →](HOW_IT_WORKS.md)

## ✨ Features

- **🔌 OpenAPI/Swagger Support** - Automatically generate methods from OpenAPI specs
- **📋 Config-Driven** - Define APIs using simple YAML/JSON files
- **🌐 Generic HTTP Client** - Quick integration for any REST API
- **⚡ Runtime Generation** - Methods created on-the-fly, no build step needed
- **🔐 Multiple Auth Types** - API Key, Bearer, Basic, OAuth2, Custom
- **⏱️ Rate Limiting** - Token bucket algorithm for API rate limits
- **🔄 Retry Logic** - Exponential backoff for failed requests
- **💾 Credential Management** - Encrypted storage, environment variables, in-memory
- **🎯 Type-Safe** - Full TypeScript support with comprehensive types
- **🛡️ Production Ready** - Error handling, logging, and best practices
- **🔧 CLI Tools** - Commands to manage APIs and generate types

## 🔧 CLI Commands

Manage your APIs with simple commands:

```bash
# Pull OpenAPI spec and create config
npm run api:add https://petstore3.swagger.io/api/v3/openapi.json petstore

# Apply/register a config file
npm run api:apply ./configs/providers/stripe.yaml

# List all registered APIs
npm run api:list

# Generate TypeScript types for full type safety
npm run api:generate-types ./configs/providers/stripe.yaml
```

**Methods are generated at runtime** - just add the config and start coding!

[Full CLI Reference →](CLI_REFERENCE.md) | [How Runtime Generation Works →](HOW_IT_WORKS.md)

## Installation

```bash
npm install severus-nexus
# or
pnpm add severus-nexus
```

## Quick Start

### 1. Generic Provider (Most Flexible)

Perfect for quick API integrations without configuration:

```typescript
import { SeverusNexus } from '@severus-lab-llc/severus-nexus';

const gateway = new SeverusNexus();

// Add any REST API
const api = await gateway.addGeneric(
  'my-api',
  'https://api.example.com',
  { type: 'bearer', token: 'your-token' },
  {}
);

// Make requests
const data = await api.callGet('/users');
const newUser = await api.callPost('/users', { name: 'John' });
```

### 2. Config-Driven Provider (Best for Multiple Endpoints)

Define your API in a YAML file and get auto-generated methods:

```yaml
# stripe.yaml
name: stripe
baseUrl: https://api.stripe.com/v1
auth:
  type: bearer
endpoints:
  create_customer:
    method: POST
    path: /customers
    bodyParams:
      - email
      - name
  list_customers:
    method: GET
    path: /customers
    queryParams:
      - limit
```

```typescript
const stripe = await gateway.addFromConfigFile(
  './stripe.yaml',
  { token: 'sk_test_...' }
);

// Use auto-generated methods
const customer = await stripe.createCustomer({
  email: 'test@example.com',
  name: 'John Doe'
});

const customers = await stripe.listCustomers({ limit: 10 });
```

### 3. OpenAPI Provider (Best for Standards-Compliant APIs)

Load from OpenAPI/Swagger spec and get instant integration:

```typescript
const petstore = await gateway.addFromOpenAPIUrl(
  'petstore',
  'https://petstore3.swagger.io/api/v3/openapi.json',
  {},
  { auth: { type: 'none' } }
);

// All operations auto-generated
const pets = await petstore.findPetsByStatus({ status: 'available' });
```

## Authentication Types

### API Key

```typescript
await gateway.addGeneric(
  'api-with-key',
  'https://api.example.com',
  {
    type: 'api_key',
    key: 'X-API-Key',
    value: 'your-api-key',
    location: 'header' // or 'query'
  },
  {}
);
```

### Bearer Token

```typescript
await gateway.addGeneric(
  'api-with-bearer',
  'https://api.example.com',
  {
    type: 'bearer',
    token: 'your-token'
  },
  {}
);
```

### Basic Auth

```typescript
await gateway.addGeneric(
  'api-with-basic',
  'https://api.example.com',
  {
    type: 'basic',
    username: 'user',
    password: 'pass'
  },
  {}
);
```

### OAuth2

```typescript
await gateway.addGeneric(
  'api-with-oauth',
  'https://api.example.com',
  {
    type: 'oauth2',
    accessToken: 'access-token',
    refreshToken: 'refresh-token',
    tokenUrl: 'https://oauth.example.com/token',
    clientId: 'client-id',
    clientSecret: 'client-secret',
    expiresAt: Date.now() + 3600000 // Auto-refresh when expired
  },
  {}
);
```

## Advanced Features

### Rate Limiting

```typescript
await gateway.addGeneric(
  'rate-limited-api',
  'https://api.example.com',
  { type: 'bearer', token: 'token' },
  {},
  {
    rateLimit: {
      maxRequests: 100,    // 100 requests
      windowMs: 60000      // per minute
    }
  }
);
```

### Retry Logic

```typescript
await gateway.addGeneric(
  'retry-api',
  'https://api.example.com',
  { type: 'bearer', token: 'token' },
  {},
  {
    retry: {
      maxRetries: 3,
      retryDelay: 1000,
      exponentialBackoff: true,
      retryableStatuses: [408, 429, 500, 502, 503, 504]
    }
  }
);
```

### Encrypted Credential Storage

```typescript
import { SeverusNexus, EncryptedFileCredentialStore } from '@severus-lab-llc/severus-nexus';

const credStore = new EncryptedFileCredentialStore(
  './credentials.enc',
  'your-encryption-key-min-32-chars'
);

await credStore.load();
const gateway = new SeverusNexus(credStore);

// Credentials are automatically encrypted and saved
```

### Environment Variable Storage

```typescript
import { EnvCredentialStore } from '@severus-lab-llc/severus-nexus';

const credStore = new EnvCredentialStore('API_'); // Prefix for env vars
const gateway = new SeverusNexus(credStore);

// Reads from API_STRIPE, API_GITHUB, etc.
```

## Configuration File Format

### YAML Example

```yaml
name: my-api
baseUrl: https://api.example.com
auth:
  type: bearer
version: v1

# Optional: Rate limiting
rateLimit:
  maxRequests: 100
  windowMs: 60000

# Optional: Retry configuration
retry:
  maxRetries: 3
  retryDelay: 1000
  exponentialBackoff: true

# Optional: Default headers
headers:
  Accept: application/json
  User-Agent: MyApp/1.0

# Endpoint definitions
endpoints:
  get_user:
    method: GET
    path: /users/{id}
    pathParams:
      - id
    description: Get a user by ID
  
  list_users:
    method: GET
    path: /users
    queryParams:
      - page
      - limit
      - sort
    description: List all users
  
  create_user:
    method: POST
    path: /users
    bodyParams:
      - name
      - email
      - role
    description: Create a new user
  
  update_user:
    method: PUT
    path: /users/{id}
    pathParams:
      - id
    bodyParams:
      - name
      - email
    description: Update a user
  
  delete_user:
    method: DELETE
    path: /users/{id}
    pathParams:
      - id
    description: Delete a user
```

## Real-World Examples

### Stripe Integration

```typescript
const stripe = await gateway.addFromConfigFile(
  './configs/stripe.yaml',
  { token: process.env.STRIPE_API_KEY }
);

// Create customer
const customer = await stripe.createCustomer({
  email: 'customer@example.com',
  name: 'John Doe',
  metadata: { user_id: '123' }
});

// Create payment intent
const payment = await stripe.createPaymentIntent({
  amount: 1000,
  currency: 'usd',
  customer: customer.data.id
});

// List charges
const charges = await stripe.listCharges({ 
  customer: customer.data.id,
  limit: 10 
});
```

### GitHub Integration

```typescript
const github = await gateway.addFromConfigFile(
  './configs/github.yaml',
  { token: process.env.GITHUB_TOKEN }
);

// Get repositories
const repos = await github.listUserRepos({
  username: 'octocat',
  per_page: 10
});

// Create issue
const issue = await github.createIssue({
  owner: 'owner',
  repo: 'repo',
  title: 'Bug found',
  body: 'Description of the bug',
  labels: ['bug']
});

// Create pull request
const pr = await github.createPullRequest({
  owner: 'owner',
  repo: 'repo',
  title: 'Fix bug',
  head: 'feature-branch',
  base: 'main',
  body: 'This PR fixes the bug'
});
```

### Slack Integration

```typescript
const slack = await gateway.addFromConfigFile(
  './configs/slack.yaml',
  { token: process.env.SLACK_TOKEN }
);

// Post message
const message = await slack.postMessage({
  channel: '#general',
  text: 'Hello from Severus Nexus!'
});

// Upload file
const file = await slack.uploadFile({
  channels: '#general',
  file: fileBuffer,
  filename: 'report.pdf',
  title: 'Monthly Report'
});

// List channels
const channels = await slack.listChannels({
  types: 'public_channel,private_channel'
});
```

## API Reference

### SeverusNexus

Main gateway class for managing API providers.

#### Methods

- `addGeneric(name, baseUrl, auth, credentials, config?)` - Add generic provider
- `addFromConfigFile(path, credentials)` - Add from YAML/JSON config
- `addFromConfig(definition, credentials)` - Add from config object
- `addFromOpenAPIUrl(name, specUrl, credentials, config?)` - Add from OpenAPI URL
- `addFromOpenAPISpec(name, spec, credentials, config?)` - Add from OpenAPI object
- `get<T>(name)` - Get provider by name
- `has(name)` - Check if provider exists
- `remove(name)` - Remove provider
- `listProviders()` - List all provider names
- `count()` - Get provider count
- `clear()` - Remove all providers

### Provider Types

#### GenericProvider

- `call(config)` - Make custom request
- `callGet(endpoint, params?)` - GET request
- `callPost(endpoint, body?, params?)` - POST request
- `callPut(endpoint, body?, params?)` - PUT request
- `callPatch(endpoint, body?, params?)` - PATCH request
- `callDelete(endpoint, params?)` - DELETE request

#### ConfigDrivenProvider

- Auto-generated methods based on config
- `getEndpoints()` - List available endpoints
- `getEndpointDefinition(name)` - Get endpoint details
- `hasEndpoint(name)` - Check if endpoint exists

#### OpenAPIProvider

- Auto-generated methods based on OpenAPI spec
- `loadSpecFromUrl(url)` - Load spec from URL
- `loadSpec(spec)` - Load spec from object
- `getOperations()` - List available operations
- `getOperationDetails(operationId)` - Get operation details
- `getSpec()` - Get OpenAPI spec

## Examples

Run the included examples:

```bash
# Basic usage with all three provider types
npm run example:basic

# Advanced features (rate limiting, retry, auth)
npm run example:advanced

# Config-driven provider examples
npm run example:config
```

## Environment Variables

Create a `.env` file:

```env
# Encryption for credential storage
ENCRYPTION_KEY=your-32-character-minimum-key

# API Credentials
STRIPE_API_KEY=sk_test_...
GITHUB_TOKEN=ghp_...
SLACK_TOKEN=xoxb-...
OPENAI_API_KEY=sk-...
```

## Architecture

```
┌─────────────────────────────────────┐
│      Severus Nexus          │
└──────────────┬──────────────────────┘
               │
       ┌───────┴────────┬─────────────┐
       │                │             │
┌──────▼─────┐  ┌──────▼────┐  ┌─────▼────────┐
│  OpenAPI   │  │  Config   │  │   Generic    │
│  Provider  │  │  Provider │  │   Provider   │
└──────┬─────┘  └──────┬────┘  └──────┬───────┘
       │                │              │
       └────────┬───────┴──────────────┘
                │
        ┌───────▼────────┐
        │  Base Provider │
        └───────┬────────┘
                │
    ┌───────────┼───────────┐
    │           │           │
┌───▼──┐  ┌────▼───┐  ┌────▼─────┐
│ Auth │  │ Rate   │  │  Retry   │
│      │  │ Limit  │  │  Logic   │
└──────┘  └────────┘  └──────────┘
```

## Publishing (for maintainers)

Repository is set to [Severus-Lab-LLC/Severus-Nexus](https://github.com/Severus-Lab-LLC/Severus-Nexus). For initial commit and GitHub repo setup, see [GITHUB_SETUP.md](GITHUB_SETUP.md). Before publishing to npm:

1. Run `npm run build` then `npm publish --access public` (scoped package under [@severus-lab-llc](https://www.npmjs.com/org/severus-lab-llc)).

## Contributing

Contributions welcome! Please read our contributing guidelines.

## License

MIT License - see LICENSE file for details

## Author

Steven A. Matías Pérez

## Support

For issues and feature requests, please open an issue on GitHub.