npm package: @maxpantech/evolution-api-wrapper
Description: TypeScript wrapper for Evolution API - WhatsApp integration made simple
Author: MaxPanTech
Latest version: 1.0.1

# Evolution API Wrapper

[![npm version](https://img.shields.io/npm/v/@maxpantech/evolution-api-wrapper.svg)](https://www.npmjs.com/package/@maxpantech/evolution-api-wrapper)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A modern, type-safe TypeScript wrapper for [Evolution API](https://github.com/EvolutionAPI/evolution-api), providing a simple and intuitive interface for WhatsApp integration.

## ✨ Features

- 🎯 **Full TypeScript support** with complete type definitions
- 🔒 **Type-safe API** with intellisense and auto-completion
- 📦 **Dual package** - Works with both ESM and CommonJS
- 🌳 **Tree-shakeable** - Only import what you need
- 🚀 **Modern axios-based** HTTP client
- 📝 **Comprehensive documentation** with examples
- ⚡ **Zero dependencies** (except peer dependency on axios)

## 📦 Installation

```bash
npm install @maxpantech/evolution-api-wrapper axios
```

or with yarn:

```bash
yarn add @maxpantech/evolution-api-wrapper axios
```

or with pnpm:

```bash
pnpm add @maxpantech/evolution-api-wrapper axios
```

## 🚀 Quick Start

### TypeScript

```typescript
import { EvolutionAPI } from '@maxpantech/evolution-api-wrapper';

// Create client instance
const client = new EvolutionAPI({
  baseUrl: 'https://your-evolution-api.com',
  apiKey: 'your-api-key-here'
});

// Create an instance
const result = await client.createInstance('my-whatsapp-instance');

if (result.success) {
  console.log('Instance created:', result.data);
  console.log('QR Code:', result.data?.qrcode);
}

// Send a text message
await client.sendTextMessage(
  'my-whatsapp-instance',
  '5511999999999',
  'Hello from TypeScript!'
);
```

### JavaScript (CommonJS)

```javascript
const { EvolutionAPI } = require('@maxpantech/evolution-api-wrapper');

const client = new EvolutionAPI({
  baseUrl: process.env.EVOLUTION_API_URL,
  apiKey: process.env.EVOLUTION_API_KEY
});

// Use the client...
```

### Using the Singleton (Recommended)

The easiest way to get started is using the pre-configured singleton instance:

```typescript
import { evolutionClient } from '@maxpantech/evolution-api-wrapper';

// Set environment variables first:
// EVOLUTION_API_URL=https://your-evolution-api.com
// EVOLUTION_API_KEY=your-api-key-here

// Use directly without instantiation
const result = await evolutionClient.createInstance('my-whatsapp-instance');

if (result.success) {
  console.log('Instance created:', result.data);
}

// Send a text message
await evolutionClient.sendTextMessage(
  'my-whatsapp-instance',
  '5511999999999',
  'Hello from the singleton!'
);

## 📖 API Documentation

### Configuration

```typescript
interface EvolutionAPIConfig {
  baseUrl: string;    // Evolution API base URL
  apiKey: string;     // Global API key
  timeout?: number;   // Request timeout in ms (default: 30000)
}
```

### Response Format

All methods return a standardized response:

```typescript
interface EvolutionAPIResponse<T> {
  success: boolean;   // Whether the operation succeeded
  data: T | null;     // Response data (null on error)
  error: string | null; // Error message (null on success)
}
```

Example:

```typescript
const result = await client.createInstance('my-instance');

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

## 🔧 Available Methods

### Instance Management

#### `createInstance(instanceName, options?)`

Creates a new WhatsApp instance.

```typescript
const result = await client.createInstance('my-instance', {
  qrcode: true,
  integration: 'WHATSAPP-BAILEYS',
  webhook: {
    url: 'https://your-webhook.com/webhook',
    enabled: true,
    events: ['MESSAGES_UPSERT', 'CONNECTION_UPDATE']
  }
});
```

**Options:**

```typescript
interface CreateInstanceOptions {
  qrcode?: boolean;  // Generate QR code (default: true)
  integration?: 'WHATSAPP-BAILEYS' | 'WHATSAPP-BUSINESS';
  webhook?: WebhookConfig;
}
```

#### `deleteInstance(instanceName)`

Permanently deletes an instance.

```typescript
await client.deleteInstance('my-instance');
```

#### `restartInstance(instanceName)`

Restarts an instance.

```typescript
await client.restartInstance('my-instance');
```

#### `fetchInstances()`

Lists all instances.

```typescript
const result = await client.fetchInstances();
console.log('Instances:', result.data);
```

#### `fetchInstanceById(instanceId)`

Fetches a specific instance by UUID.

```typescript
const result = await client.fetchInstanceById('93ecfcf2-f1a7-444b-baa2-83afee38413b');
```

#### `getInstanceStatus(instanceName)`

Gets the connection status of an instance.

```typescript
const result = await client.getInstanceStatus('my-instance');
// result.data.state: 'close' | 'connecting' | 'open'
```

**Status values:**
- `close` - Disconnected
- `connecting` - Waiting for QR code scan
- `open` - Connected and ready

#### `getQRCode(instanceName)`

Gets the current QR code for an instance.

```typescript
const result = await client.getQRCode('my-instance');
console.log('QR Code:', result.data?.base64);
```

#### `disconnectInstance(instanceName)`

Disconnects/logs out an instance.

```typescript
await client.disconnectInstance('my-instance');
```

### Message Sending

#### `sendTextMessage(instanceName, number, text, options?)`

Sends a text message.

```typescript
await client.sendTextMessage(
  'my-instance',
  '5511999999999',
  'Hello, World!',
  {
    delay: 1000,           // Delay in ms before sending
    presence: 'composing', // Show typing indicator
    linkPreview: true      // Enable link preview
  }
);
```

**Options:**

```typescript
interface SendTextOptions {
  delay?: number;
  presence?: 'composing' | 'recording';
  linkPreview?: boolean;
  mentioned?: string[];  // Array of numbers to mention
}
```

#### `sendMediaMessage(instanceName, number, media, options?)`

Sends media (image, video, audio, document).

```typescript
// Send image from URL
await client.sendMediaMessage(
  'my-instance',
  '5511999999999',
  'https://example.com/image.jpg',
  {
    mediatype: 'image',
    mimetype: 'image/jpeg',
    caption: 'Check this out!',
    fileName: 'photo.jpg'
  }
);

// Send base64 image
await client.sendMediaMessage(
  'my-instance',
  '5511999999999',
  'data:image/png;base64,iVBORw0KGgo...',
  {
    mediatype: 'image',
    caption: 'Base64 image'
  }
);

// Send document
await client.sendMediaMessage(
  'my-instance',
  '5511999999999',
  'https://example.com/document.pdf',
  {
    mediatype: 'document',
    mimetype: 'application/pdf',
    fileName: 'report.pdf'
  }
);
```

**Options:**

```typescript
interface SendMediaOptions {
  mediatype?: 'image' | 'video' | 'audio' | 'document';
  mimetype?: string;
  caption?: string;
  fileName?: string;
  delay?: number;
  presence?: 'composing' | 'recording';
}
```

#### `sendContact(instanceName, number, contact)`

Sends a contact.

```typescript
await client.sendContact(
  'my-instance',
  '5511999999999',
  {
    fullName: 'John Doe',
    wuid: '5511888888888',      // WhatsApp ID
    phoneNumber: '5511888888888',
    organization: 'Company Inc.',
    email: 'john@example.com'
  }
);
```

### Utilities

#### `checkWhatsAppNumber(instanceName, numbers)`

Checks if numbers have WhatsApp.

```typescript
const result = await client.checkWhatsAppNumber(
  'my-instance',
  ['5511999999999', '5511888888888']
);

result.data?.forEach(check => {
  console.log(`${check.number}: ${check.exists ? 'Has WhatsApp' : 'No WhatsApp'}`);
});
```

## 🎯 Advanced Usage

### Error Handling

```typescript
try {
  const result = await client.sendTextMessage(
    'my-instance',
    '5511999999999',
    'Hello!'
  );

  if (!result.success) {
    console.error('Failed to send message:', result.error);
    return;
  }

  console.log('Message sent:', result.data);
} catch (error) {
  console.error('Unexpected error:', error);
}
```

### Creating a Singleton Instance

```typescript
// api-client.ts
import { EvolutionAPI } from '@maxpantech/evolution-api-wrapper';

let instance: EvolutionAPI | null = null;

export function getEvolutionClient(): EvolutionAPI {
  if (!instance) {
    instance = new EvolutionAPI({
      baseUrl: process.env.EVOLUTION_API_URL!,
      apiKey: process.env.EVOLUTION_API_KEY!
    });
  }
  return instance;
}

// Usage in other files
import { getEvolutionClient } from './api-client';

const client = getEvolutionClient();
await client.sendTextMessage('instance', '5511999999999', 'Hello!');
```

### TypeScript Type Imports

```typescript
import type {
  EvolutionAPIResponse,
  CreateInstanceOptions,
  SendTextOptions,
  SendMediaOptions,
  Contact,
  InstanceStatus,
  MessageSendResponse
} from '@maxpantech/evolution-api-wrapper';
```

## 🔐 Environment Variables

### For Singleton Usage

The singleton automatically reads these environment variables:

```env
# Required
EVOLUTION_API_URL=https://your-evolution-api.com
EVOLUTION_API_KEY=your-global-api-key

# Optional
EVOLUTION_API_TIMEOUT=30000

## 📋 Phone Number Format

Always use international format without `+` or spaces:

- ✅ Correct: `5511999999999`
- ❌ Wrong: `+55 11 99999-9999`
- ❌ Wrong: `11999999999`

## 🛠️ Development

### Building the Library

```bash
npm run build
```

### Type Checking

```bash
npm run typecheck
```

### Linting

```bash
npm run lint
npm run lint:fix
```

### Development Mode (Watch)

```bash
npm run dev
```

## 📝 Publishing to NPM

1. Update version in `package.json`
2. Build the library:
   ```bash
   npm run build
   ```
3. Login to NPM (if not already logged in):
   ```bash
   npm login
   ```
4. Publish:
   ```bash
   npm publish --access public
   ```

## 📦 Publishing to GitHub Packages

1. Create a `.npmrc` file in the project root:
   ```
   @maxpantech:registry=https://npm.pkg.github.com
   ```

2. Update `package.json` with repository info:
   ```json
   {
     "name": "@maxpantech/evolution-api-wrapper",
     "repository": "https://github.com/maxpantech/evolution-api-wrapper"
   }
   ```

3. Authenticate with GitHub:
   ```bash
   npm login --registry=https://npm.pkg.github.com
   ```

4. Publish:
   ```bash
   npm publish
   ```

## 🔗 Using the Library in Other Projects

After publishing, install in your projects:

```bash
npm install @maxpantech/evolution-api-wrapper axios
```

For GitHub Packages, add `.npmrc` to the consuming project:

```
@maxpantech:registry=https://npm.pkg.github.com
```

## 📄 License

MIT © MaxPanTech

## 🔗 Links

- [Evolution API Documentation](https://doc.evolution-api.com/)
- [Evolution API GitHub](https://github.com/EvolutionAPI/evolution-api)

---

Made with ❤️ by MaxPanTech