npm package: @oatlas/tapi
Description: Ocean Telephony Api Library for js
Author: Ocean Inc.
Latest version: 1.0.7

# Ocean Telephony API for JavaScript (@oatlas/tapi)

[![npm version](https://img.shields.io/npm/v/@oatlas/tapi.svg?style=flat)](https://www.npmjs.com/package/@oatlas/tapi/)
[![npm downloads](https://img.shields.io/npm/dm/@oatlas/tapi.svg)](https://nodei.co/npm/@oatlas/tapi/)
[![codecov](https://codecov.io/gh/OAtlas/ocean-telephony-api-for-js/branch/main/graph/badge.svg?flag=tapi)](https://codecov.io/gh/OAtlas/ocean-telephony-api-for-js)
[![build](https://github.com/OAtlas/ocean-telephony-api-for-js/workflows/CI/badge.svg)](https://github.com/OAtlas/ocean-telephony-api-for-js/actions)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

| <a href="https://docs.oatlas.io/tapi/quickstart" target="_blank">Quickstart</a> | <a href="https://docs.oatlas.io/tapi/api" target="_blank">API Docs</a> | <a href="https://github.com/OAtlas/ocean-telephony-api-for-js/wiki" target="_blank">Wiki</a> | <a href="https://github.com/OAtlas/ocean-telephony-api-for-js/discussions" target="_blank">Discussions</a> |
| ------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------- |

## Table of Contents

1. [About](#about)
2. [Features](#features)
3. [Supported Providers](#supported-providers)
4. [Quick Start](#quick-start)
5. [Installation](#installation)
6. [Documentation](#documentation)
7. [Examples](#examples)
8. [Architecture](#architecture)
9. [Contributing](#contributing)
10. [Security](#security)
11. [License](#license)

---

## About

**Ocean Telephony API (@oatlas/tapi)** is a unified, provider-agnostic JavaScript library for integrating Computer Telephony Integration (CTI) capabilities into web and Node.js applications.

Built with the same quality standards as the **Ocean Authentication Library (OAL)**, @oatlas/tapi enables developers to:

- 📞 **Manage calls** (make, receive, transfer, conference)
- 🎤 **Control devices** (phones, headsets, mobile devices)
- 👤 **Handle presence** (status, availability, DND)
- 📋 **Track history** (CDR, call logs, recording URLs)
- 🔔 **Handle events** (real-time call notifications)
- 🔄 **Multi-provider support** (Karel, RingCentral, Avaya, FreePBX, MS Teams)

The `@oatlas/tapi` package provides a common, unified telephony API used by platform-specific packages:

- **[@oatlas/tapi-browser](https://github.com/OAtlas/ocean-telephony-api-for-js/tree/main/lib/tapi-browser)** - Browser/SPA support
- **[@oatlas/tapi-node](https://github.com/OAtlas/ocean-telephony-api-for-js/tree/main/lib/tapi-node)** - Node.js support
- **[@oatlas/tapi-react](https://github.com/OAtlas/ocean-telephony-api-for-js/tree/main/lib/tapi-react)** - React hooks & components

---

## Features

### Core Capabilities

✅ **Multi-Provider Support**
- Karel PBX (REST API + WebSocket)
- RingCentral Cloud (Official SDK)
- Avaya Enterprise (TSAPI/JTAPI)
- FreePBX Open Source (AMI)
- Microsoft Teams (Graph API)

✅ **Call Management**
- Originate calls
- Answer incoming calls
- Transfer (blind & attended)
- Conference (multi-party)
- Hold/Resume
- Mute/Unmute
- Recording

✅ **Device Management**
- List devices
- Set active device
- Monitor device state

✅ **User Management**
- Get user info
- Set presence/status
- Monitor presence changes

✅ **Call History**
- Retrieve CDR (Call Detail Records)
- Search call logs
- Access recording URLs

✅ **Real-Time Events**
- Incoming calls
- Call state changes
- Device changes
- Presence updates
- Connection status

✅ **Enterprise Features**
- Auto-reconnect with exponential backoff
- Error recovery
- Connection pooling
- Event aggregation
- Comprehensive logging
- Full TypeScript support

---

## Supported Providers

| Provider | Status | Type | Authentication | Real-Time |
|----------|--------|------|-----------------|-----------|
| **Karel** | ✅ Complete | On-Premise PBX | REST API Token | WebSocket |
| **RingCentral** | ✅ Complete | Cloud PBX | OAuth 2.0 SDK | Subscriptions |
| **MS Teams** | ✅ Complete | UC Platform | Azure AD (Graph API) | Webhooks |
| **Avaya** | 🔄 In Progress | Enterprise PBX | TSAPI/JTAPI | Various |
| **FreePBX** | 🔄 In Progress | Open Source | AMI | Polling |

---

## Quick Start

### Installation

```bash
npm install @oatlas/tapi
npm install @oatlas/tapi-browser  # For browser
# or
npm install @oatlas/tapi-node     # For Node.js
```

### Basic Usage

```typescript
import { TapiManager, TapiEventType } from '@oatlas/tapi';

// Initialize with provider config
const manager = new TapiManager({
  provider: 'karel',
  apiUrl: 'https://pbx.example.com/api',
  username: 'user@example.com',
  password: 'password',
  enableCallLog: true,
  enableRecording: true
});

// Connect to telephony system
await manager.initialize();

// Listen for incoming calls
manager.on(TapiEventType.CALL_INCOMING, (event) => {
  console.log('Incoming call from:', event.data.from);
  console.log('Called number:', event.data.to);
});

// Make a call
const result = await manager.makeCall('+1-555-123-4567');
if (result.success) {
  console.log('Call made:', result.data.id);
} else {
  console.error('Call failed:', result.error?.message);
}

// Answer incoming call
await manager.answerCall();

// Transfer to another extension
await manager.transferCall({
  targetNumber: '101',
  blind: false  // Attended transfer (consult first)
});

// Listen to errors
manager.onError((error) => {
  console.error('Telephony Error:', error.code, error.message);
});

// Cleanup
await manager.disconnect();
```

---

## Installation

### Via NPM

```bash
npm install @oatlas/tapi
```

### Via Yarn

```bash
yarn add @oatlas/tapi
```

### Via pnpm

```bash
pnpm add @oatlas/tapi
```

### From GitHub

```bash
npm install github:OAtlas/ocean-telephony-api-for-js#main
```

---

## Documentation

### Getting Started

- [Quickstart Guide](https://docs.oatlas.io/tapi/quickstart)
- [Installation & Setup](https://docs.oatlas.io/tapi/installation)
- [Configuration Guide](https://docs.oatlas.io/tapi/configuration)

### API Reference

- [TapiManager API](https://docs.oatlas.io/tapi/api/manager)
- [Types & Interfaces](https://docs.oatlas.io/tapi/api/types)
- [Error Handling](https://docs.oatlas.io/tapi/api/errors)
- [Events](https://docs.oatlas.io/tapi/api/events)

### Provider Guides

- [Karel PBX Integration](https://docs.oatlas.io/tapi/providers/karel)
- [RingCentral Setup](https://docs.oatlas.io/tapi/providers/ringcentral)
- [MS Teams Integration](https://docs.oatlas.io/tapi/providers/teams)
- [Avaya Enterprise](https://docs.oatlas.io/tapi/providers/avaya)
- [FreePBX Setup](https://docs.oatlas.io/tapi/providers/freepbx)

### Advanced Topics

- [Custom Adapters](https://docs.oatlas.io/tapi/advanced/custom-adapters)
- [Event Handling](https://docs.oatlas.io/tapi/advanced/events)
- [Error Recovery](https://docs.oatlas.io/tapi/advanced/error-handling)
- [Performance Optimization](https://docs.oatlas.io/tapi/advanced/performance)

---

## Examples

### Example 1: Basic Call Control

```typescript
import { TapiManager } from '@oatlas/tapi';

const manager = new TapiManager({
  provider: 'karel',
  apiUrl: 'https://pbx.example.com/api',
  username: 'user@example.com',
  password: 'password'
});

await manager.initialize();

// Make call
const call = await manager.makeCall('+1-555-123-4567');
console.log(`Call ID: ${call.data?.id}`);

// Answer call (when incoming)
await manager.answerCall();

// Hold call
await manager.holdCall();

// Resume call
await manager.resumeCall();

// End call
await manager.endCall();
```

### Example 2: Conference Calls

```typescript
// Create conference
const conference = await manager.createConference({
  participants: ['+1-555-111-1111', '+1-555-222-2222'],
  name: 'Team Meeting',
  recordingEnabled: true,
  maxDuration: 3600  // 1 hour
});

// Add participant
await manager.addParticipant(conference.data!.id, '+1-555-333-3333');

// Remove participant
await manager.removeParticipant(conference.data!.id, 'participant-id');
```

### Example 3: Event Monitoring

```typescript
// Incoming call
manager.on(TapiEventType.CALL_INCOMING, (event) => {
  console.log('Incoming:', event.data.from);
  // Auto-answer if from specific number
  if (event.data.from === '+1-555-123-4567') {
    manager.answerCall(event.data.id);
  }
});

// Call answered
manager.on(TapiEventType.CALL_ANSWERED, (event) => {
  console.log('Call answered, duration start');
  startTimer();
});

// Call ended
manager.on(TapiEventType.CALL_ENDED, (event) => {
  console.log('Call ended', event.data.endReason);
  saveCallLog(event.data);
});

// Presence changed
manager.on(TapiEventType.PRESENCE_CHANGED, (event) => {
  console.log('Presence:', event.data.presence);
  updateUI(event.data);
});
```

### Example 4: Error Handling & Recovery

```typescript
manager.onError((error) => {
  switch (error.code) {
    case 'NETWORK_ERROR':
      console.error('Network error:', error.message);
      // App handles auto-reconnect
      break;
    
    case 'CALL_FAILED':
      console.error('Call failed:', error.details);
      showErrorDialog('Unable to make call');
      break;
    
    case 'DEVICE_NOT_FOUND':
      console.warn('Device removed, switching to default');
      break;
  }
});
```

### Example 5: Call Recording

```typescript
// Start recording call
const call = await manager.makeCall('+1-555-123-4567');

await manager.startRecording(call.data!.id, {
  format: 'mp3',
  quality: 'high'
});

// ... call continues ...

// Stop recording
const stopResult = await manager.stopRecording(call.data!.id);

// Get recording URL from call history
const history = await manager.getCallHistory({ limit: 1 });
const recordingUrl = history.data?.[0].recordingUrl;
```

### Example 6: Multi-Provider Setup

```typescript
// Karel production
const primaryManager = new TapiManager({
  provider: 'karel',
  apiUrl: 'https://pbx-primary.example.com/api',
  username: 'user@example.com',
  password: 'password',
  autoReconnect: true
});

// RingCentral backup
const backupManager = new TapiManager({
  provider: 'ringcentral',
  clientId: 'xxxxx',
  clientSecret: 'xxxxx',
  autoReconnect: true
});

// Failover logic
primaryManager.onError(async (error) => {
  if (error.code === 'CONNECTION_ERROR') {
    console.log('Primary failed, switching to backup...');
    await backupManager.initialize();
  }
});
```

---

## Architecture

### High-Level Design

```
┌─────────────────────────────────┐
│   Web/Node Application          │
└────────────┬────────────────────┘
             │
    ┌────────▼────────┐
    │   TapiManager   │  (Unified API)
    │  (Main API)     │
    └────────┬────────┘
             │
    ┌────────▼────────┐
    │  TapiAdapter    │  (Abstract Interface)
    │  (Abstract)     │
    └────────┬────────┘
             │
    ┌────────▼───────────────────────┐
    │    Provider Adapters           │
    ├────────────────────────────────┤
    │ • KarelAdapter                 │
    │ • RingCentralAdapter           │
    │ • MSTeamsAdapter               │
    │ • AvayaAdapter                 │
    │ • FreePBXAdapter               │
    └────────┬───────────────────────┘
             │
    ┌────────▼────────────────────────┐
    │   Telephony Systems            │
    ├────────────────────────────────┤
    │ • Karel PBX                    │
    │ • RingCentral Cloud            │
    │ • Avaya Enterprise             │
    │ • FreePBX Server               │
    │ • Microsoft Teams              │
    └────────────────────────────────┘
```

### Adapter Pattern

@oatlas/tapi uses the **Adapter Design Pattern** to normalize different telephony APIs:

```
Different APIs          Adapter Pattern         Unified Interface
────────────────────────────────────────────────────────────────
Karel REST API          KarelAdapter      │
  (Different format) ─→ (Conversion)  ────┤
                                           ├─→ TapiManager API
RingCentral SDK         RingCentralAdapter│    (Standard Interface)
  (Different format) ─→ (Conversion)  ────┤
                                           │
MS Teams Graph API      MSTeamsAdapter     │
  (Different format) ─→ (Conversion)  ────┘
```

---

## Contributing

We welcome contributions! Here's how:

1. **Fork the repository**
   ```bash
   git clone https://github.com/OAtlas/ocean-telephony-api-for-js.git
   cd ocean-telephony-api-for-js
   ```

2. **Create a feature branch**
   ```bash
   git checkout -b feature/amazing-feature
   ```

3. **Install dependencies**
   ```bash
   npm install
   ```

4. **Make your changes**
   - Follow our [Code of Conduct](./CODE_OF_CONDUCT.md)
   - Follow our [Contribution Guidelines](./CONTRIBUTING.md)
   - Add tests for new features
   - Update documentation

5. **Run tests**
   ```bash
   npm run test
   npm run test:coverage
   ```

6. **Commit and push**
   ```bash
   git commit -m "feat: Add amazing feature"
   git push origin feature/amazing-feature
   ```

7. **Create a Pull Request**
   - Reference related issues
   - Describe your changes
   - Include any breaking changes

---

## Security

### Reporting Security Issues

⚠️ **Do not open public GitHub issues for security vulnerabilities.**

If you discover a security vulnerability, please email **security@oatlas.io** with:

- Description of the vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix (if any)

We will:
- Acknowledge your report within 48 hours
- Work with you to understand the issue
- Develop and test a fix
- Credit you in the fix release (if desired)

### Security Best Practices

1. **Credentials Management**
   - Never commit credentials to version control
   - Use environment variables
   - Rotate API keys regularly

2. **Transport Security**
   - Always use HTTPS/WSS (encrypted)
   - Validate SSL certificates
   - Use OAuth 2.0 where available

3. **Update Regularly**
   ```bash
   npm outdated
   npm update
   ```

See [SECURITY.md](./SECURITY.md) for more details.

---

## Performance

### Benchmarks

- Connection time: < 100ms (average)
- Call setup latency: < 200ms
- Memory footprint: < 5MB
- Event latency: < 50ms (95th percentile)

See [PERFORMANCE.md](./docs/PERFORMANCE.md) for detailed benchmarks.

---

## FAQ

**Q: Which version of Node.js is supported?**
A: Node.js 14+, with 16+ recommended.

**Q: Can I use this in the browser?**
A: Yes! Use `@oatlas/tapi-browser` for browser-specific features.

**Q: Does it support TypeScript?**
A: Yes, full TypeScript support with type definitions included.

**Q: How do I handle network failures?**
A: Set `autoReconnect: true` in config. See [Error Handling Guide](./docs/ERROR_HANDLING.md).

**Q: Can I use multiple adapters simultaneously?**
A: Yes, create multiple `TapiManager` instances with different configs.

**Q: What's the license?**
A: MIT License. See [LICENSE](./LICENSE) file.

See [FAQ.md](./docs/FAQ.md) for more questions.

---

## Changelog

See [CHANGELOG.md](./CHANGELOG.md) for version history and breaking changes.

---

## Related Projects

- [OAL (Ocean Authentication Library)](https://github.com/OAtlas/ocean-authentication-library-for-js) - Authentication
- [TAPI Browser](https://github.com/OAtlas/ocean-telephony-api-for-js/tree/main/lib/tapi-browser) - Browser support
- [TAPI Node](https://github.com/OAtlas/ocean-telephony-api-for-js/tree/main/lib/tapi-node) - Node.js support
- [TAPI React](https://github.com/OAtlas/ocean-telephony-api-for-js/tree/main/lib/tapi-react) - React hooks

---

## License

Copyright (c) Ocean Corporation. All rights reserved.

Licensed under the MIT License - see [LICENSE](./LICENSE) file for details.

```
MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
```

---

## Code of Conduct

We value and adhere to the [Ocean Open Source Code of Conduct](https://opensource.oceansln.com/codeofconduct/).

For more information, see the [Code of Conduct FAQ](https://opensource.oceansln.com/codeofconduct/faq/) or contact [opencode@oceansln.com](mailto:opencode@oceansln.com).

---

## Support

- 📖 [Documentation](https://docs.oatlas.io/tapi)
- 💬 [GitHub Discussions](https://github.com/OAtlas/ocean-telephony-api-for-js/discussions)
- 🐛 [Issue Tracker](https://github.com/OAtlas/ocean-telephony-api-for-js/issues)
- 📧 [Email Support](mailto:support@oatlas.io)
- 🌐 [Website](https://oatlas.io)

---

**Made with ❤️ by the OAtlas Team**