npm package: @nekuda/nekuda-js
Description: nekuda Node.js SDK for payment processing
Author: Nekuda AI
Latest version: 0.2.14

# nekuda Node.js SDK

[![npm version](https://img.shields.io/npm/v/nekuda.svg)](https://www.npmjs.com/package/nekuda)
[![npm downloads](https://img.shields.io/npm/dm/nekuda.svg)](https://www.npmjs.com/package/nekuda)
[![License](https://img.shields.io/npm/l/nekuda.svg)](https://github.com/nekuda-ai/nekuda-sdk-typescript/blob/main/LICENSE)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)

The official TypeScript SDK for [nekuda](https://nekuda.ai) - secure credit card handling for AI web agents and crawlers.
Full documentation is available at [nekuda Docs](https://docs.nekuda.ai/nekuda-sdk/getting-started).

## Purpose

The nekuda SDK enables AI agents to securely collect and handle credit card information without ever handling sensitive card data directly. It provides a lightweight TypeScript client that:

1. **Creates mandates** - Describes what the AI agent intends to purchase on behalf of users
2. **Manages secure tokens** - Handles the token-based flow for revealing card details
3. **Ensures compliance** - Keeps your AI application PCI-compliant by design

## Requirements

Node.js 14.0 or higher.

## Installation

```bash
npm install @nekuda/nekuda-js
# or with yarn
yarn add @nekuda/nekuda-js
# or with pnpm
pnpm add @nekuda/nekuda-js
```

## Quick Start

### Card Reveal Flow

```typescript
import { NekudaClient, MandateData } from '@nekuda/nekuda-js';

// Initialize client with your API key
const client = NekudaClient.fromEnv();
const user = client.user('user_123');

// 1. Create a mandate describing the purchase
const mandate = new MandateData({
  product: 'Premium Subscription',
  price: 49.99,
  currency: 'USD',
  merchant: 'Example Corp',
  confidenceScore: 0.95,
});

const mandateResponse = await user.createMandate(mandate);
const mandateId = mandateResponse.mandateId;

// 2. Request a one-time reveal token
const tokenData = await user.requestCardRevealToken(mandateId);
const revealToken = tokenData.revealToken;

// 3. Exchange token for card details (one-time use)
const card = await user.revealCardDetails(revealToken);
console.log(`Card: **** **** **** ${card.last4Digits}`);

// 4. Optionally retrieve billing details for shipping/contact info
const billingDetails = await user.getBillingDetails();
console.log(`Billing: ${billingDetails.cardholderName}, ${billingDetails.phoneNumber}`);
```

### Billing Details Retrieval

```typescript
import { NekudaClient } from '@nekuda/nekuda-js';

const client = NekudaClient.fromEnv();
const user = client.user('user_123');

// Retrieve non-sensitive billing information for shipping/contact
const billingDetails = await user.getBillingDetails();

console.log('Billing Details:', {
  cardholder: billingDetails.cardholderName,
  phone: billingDetails.phoneNumber,
  address: billingDetails.billingAddress,
  city: billingDetails.city,
  state: billingDetails.state,
  zipCode: billingDetails.zipCode
});
```

**Use Cases:**
- **Shipping verification** - Pre-fill shipping address forms
- **Contact information** - Send order updates and notifications
- **Address validation** - Verify billing vs shipping addresses
- **Customer service** - Support and assistance
- **Express checkout** - Faster checkout experiences

**Key differences from card details:**
- Contains no sensitive payment data (no card numbers, CVV, etc.)
- Safe for logging and storage (non-PCI data)
- Uses separate API endpoint with customer_id context

## Key Features

### Core Capabilities
- **Fully typed**: Complete TypeScript support with comprehensive type definitions
- **Promise-based**: Modern async/await API
- **Secure authentication**: Private API key authentication
- **Retry logic**: Automatic retry with exponential backoff for transient failures
- **Modern JavaScript**: ES2018+ compatible with tree-shaking support

### Enhanced Error Handling
- **Context-aware errors**: Detailed error messages with operation and user context
- **Authentication guidance**: Clear messages for authentication failures
- **Troubleshooting help**: Built-in guidance for common error scenarios
- **Debug logging**: Built-in logging to help troubleshoot integration issues

## Example Use Cases

The SDK is designed for AI agents that need to:

- Purchase products on e-commerce sites
- Subscribe to services
- Book travel arrangements
- Make any other legitimate purchases on behalf of users

## Error Handling

The SDK provides granular exception types for different error scenarios:

```typescript
import { NekudaClient } from '@nekuda/nekuda-js';
import {
  AuthenticationError,
  InvalidRequestError,
  RateLimitError,
  ServerError,
  NekudaValidationError,
} from '@nekuda/nekuda-js';

try {
  // Create mandate and reveal card
  const mandate = new MandateData({ product: 'Test Product', price: 10.00 });
  const mandateResponse = await user.createMandate(mandate);
  const tokenData = await user.requestCardRevealToken(mandateResponse.mandateId);
  const card = await user.revealCardDetails(tokenData.revealToken);
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log('Check your API key');
  } else if (error instanceof RateLimitError) {
    console.log('Rate limited, implement exponential backoff');
  } else if (error instanceof ServerError) {
    console.log('Server error, retry with backoff');
  } else if (error instanceof NekudaValidationError) {
    console.log(`Validation error: ${error.message}`);
  }
}
```

## Configuration

### Environment Variables

Set these environment variables:

```env
NEKUDA_API_KEY=sk_test_your_api_key_here
NEKUDA_BASE_URL=https://api.nekuda.ai  # Optional, defaults to production
```

### Client Configuration

```typescript
import { NekudaClient } from '@nekuda/nekuda-js';

// Option 1: From environment variables
const client = NekudaClient.fromEnv();

// Option 2: Explicit configuration
const client = new NekudaClient('your-api-key', {
  timeout: 30000,
  maxRetries: 3,
});

// Option 3: Mixed (env vars + overrides)
const client = NekudaClient.fromEnv({
  timeout: 60000,
  maxRetries: 5,
});
```

## TypeScript Support

This SDK is written in TypeScript and provides complete type definitions:

```typescript
import {
  NekudaClient,
  MandateData,
  CardRevealTokenResponse,
  CardDetailsResponse,
  MandateCreateResponse,
} from '@nekuda/nekuda-js';

// All methods return properly typed promises
const tokenResponse: CardRevealTokenResponse = await client.requestCardRevealToken(
  'user123',
  'mandate456'
);

// TypeScript will catch errors at compile time
const card: CardDetailsResponse = await client.revealCardDetails(
  'user123',
  tokenResponse.revealToken
);
```

## API Reference

### Core Methods

#### Create Mandate
```typescript
const mandate = new MandateData({
  product: 'Premium Plan',
  price: 99.99,
  currency: 'USD',
  merchant: 'Your Company',
  confidenceScore: 0.95,
});

const mandateResponse = await user.createMandate(mandate);
```

#### Request Card Reveal Token
```typescript
const tokenData = await user.requestCardRevealToken(mandateId);
const revealToken = tokenData.revealToken;
```

#### Reveal Card Details
```typescript
const card = await user.revealCardDetails(revealToken);
console.log(`Card ending in: ${card.last4Digits}`);
```

#### Get Billing Details
```typescript
const billingDetails = await user.getBillingDetails();
console.log(`Billing: ${billingDetails.cardholderName}, ${billingDetails.phoneNumber}`);
```

### Response Types

#### Card Details Response
```typescript
interface CardDetailsResponse {
  cardNumber?: string;        // Optional - not always available for security
  cardExpiryDate: string;     // MM/YY format
  cardholderName: string;     // Cardholder name
  last4Digits?: string;       // Last 4 digits of card
  cardCvv?: string;           // CVV (when available)
  email?: string;             // Email address
  billingAddress?: string;    // Billing address
  city?: string;              // City
  state?: string;             // State/province
  zipCode?: string;           // ZIP code
  phoneNumber?: string;       // Phone number
}
```

#### Card Reveal Token Response
```typescript
interface CardRevealTokenResponse {
  revealToken: string;        // One-time token for card reveal
  expiresAt?: Date;           // Token expiration time
}
```

#### Mandate Create Response
```typescript
interface MandateCreateResponse {
  mandateId: number;          // Unique mandate identifier
  requestId: string;          // Request tracking ID
  customerId: string;         // Customer ID
  createdAt: Date;            // Creation timestamp
  updatedAt?: Date;           // Last update timestamp
}
```

#### Billing Details Response
```typescript
interface BillingDetailsResponse {
  userId: string;             // User identifier
  cardholderName: string;     // Cardholder name
  phoneNumber: string;        // Phone number in E.164 format
  billingAddress: string;     // Street address
  city?: string;              // City (optional)
  state?: string;             // State/province (optional)
  zipCode: string;            // ZIP/postal code
}
```

## Development & Release

### Building from Source

```bash
# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm test

# Run comprehensive validation
npm run validate:publish
```

### Release Process

This SDK uses an automated release process with environment-specific publishing:

#### Development Releases
For testing experimental features and early development:
```bash
git tag dev_v1.2.3
git push origin dev_v1.2.3
```
Publishes to: `@nekuda/nekuda-js-dev` (PRIVATE) with `dev` tag

#### Test/Staging Releases  
For pre-production validation:
```bash
git tag test_v1.2.3
git push origin test_v1.2.3
```
Publishes to: `@nekuda/nekuda-js-test` (PRIVATE) with `test` tag

#### Production Releases
For stable, production-ready releases:
```bash
git tag prod_v1.2.3
git push origin prod_v1.2.3
```
Publishes to: `@nekuda/nekuda-js` (PUBLIC) with `latest` tag

#### Release Validation

Before creating any release, ensure:
- [ ] All tests pass: `npm test`
- [ ] Code coverage ≥ 70%: `npm run test:coverage`
- [ ] No linting errors: `npm run lint`
- [ ] TypeScript compiles: `npm run typecheck`
- [ ] Build validation passes: `npm run validate:build`

See [SDK_PUBLISH_CHECKLIST.md](./SDK_PUBLISH_CHECKLIST.md) for the complete release checklist.

#### GitHub Actions

The release process is fully automated via GitHub Actions:
1. Extract version from git tag
2. Update package.json with environment-specific naming
3. Run comprehensive tests and validation
4. Build and verify artifacts
5. Publish to NPM with appropriate tag
6. Create GitHub release (production only)

## License

Apache License 2.0 - see [LICENSE](LICENSE) for details.

## Support

- [Documentation](https://docs.nekuda.ai)
- [Email Support](mailto:support@nekuda.ai)

## Security

The nekuda SDK is designed with security as a priority:

- **No card data storage**: Card details are never stored locally
- **Token-based flow**: One-time tokens minimize exposure
- **TLS encryption**: All API communication is encrypted
- **PCI compliance**: Helps keep your application compliant