# Industrious Office - Mailchimp Marketing Node.js Client

This is a modified version of the official Node.js client library for the Mailchimp Marketing API, enhanced for both production and testing purposes by Industrious Office.

## 🆕 Key Enhancements

### 1. TypeScript Support

Full TypeScript support with comprehensive type definitions for all API endpoints and data structures.

#### Features
- **Complete Type Safety**: Strongly typed interfaces for all API methods and responses
- **IntelliSense Support**: Full autocomplete and error checking in IDEs
- **Type Definitions**: Comprehensive `.d.ts` files included in the package
- **Zero Configuration**: Works out-of-the-box with TypeScript projects
- **Detailed Documentation**: JSDoc comments for all interfaces and methods
- **Example Files**: Complete TypeScript usage examples included

#### TypeScript Files Included
- `index.d.ts` - Main comprehensive TypeScript declarations
- `src/index.d.ts` - Additional type definitions
- `tsconfig.json` - TypeScript configuration for the package
- `examples/typescript-example.ts` - Complete usage examples
- `TYPESCRIPT.md` - Detailed integration guide

#### TypeScript Usage

```typescript
import mailchimp from '@industriousoffice/mailchimp_marketing';
// or
const mailchimp = require('@industriousoffice/mailchimp_marketing');

// Configuration with full type checking
mailchimp.setConfig({
    apiKey: 'your-api-key-us1',
    server: 'us1'
});

// Example: Ping the API with type safety
async function pingAPI(): Promise<void> {
    try {
        const response = await mailchimp.ping.get();
        console.log('API Health Status:', response.data.health_status);
    } catch (error) {
        console.error('Ping failed:', error);
    }
}

// Example: Get all lists with full type support
async function getAllLists(): Promise<void> {
    try {
        const response = await mailchimp.lists.getAllLists({
            count: 10,
            sort_field: 'date_created',
            sort_dir: 'DESC'
        });
        
        console.log(`Found ${response.data.total_items} lists`);
        response.data.lists?.forEach((list: any) => {
            console.log(`- ${list.name} (${list.stats.member_count} members)`);
        });
    } catch (error) {
        console.error('Failed to get lists:', error);
    }
}

// Example: Add a member to a list with typed parameters
async function addMemberToList(listId: string, emailAddress: string): Promise<void> {
    try {
        const member = await mailchimp.lists.addListMember(listId, {
            email_address: emailAddress,
            status: 'subscribed',
            merge_fields: {
                FNAME: 'John',
                LNAME: 'Doe'
            }
        });
        
        console.log(`Added member: ${member.data.email_address}`);
    } catch (error) {
        console.error('Failed to add member:', error);
    }
}

// Example: Create a campaign with comprehensive type checking
async function createCampaign(listId: string): Promise<string | undefined> {
    try {
        const campaign = await mailchimp.campaigns.create({
            type: 'regular',
            recipients: {
                list_id: listId
            },
            settings: {
                subject_line: 'Hello from TypeScript!',
                preview_text: 'This is a test campaign created with TypeScript',
                title: 'TypeScript Test Campaign',
                from_name: 'Your Company',
                reply_to: 'noreply@yourcompany.com',
                to_name: '*|FNAME|*'
            }
        });
        
        console.log(`Campaign created with ID: ${campaign.data.id}`);
        return campaign.data.id;
    } catch (error) {
        console.error('Failed to create campaign:', error);
    }
}

// Example: Testing with mock server
async function exampleWithMockServer(): Promise<void> {
    // For testing, set the environment variable
    process.env.MAILCHIMP_BASE_URL = 'http://localhost:3001/3.0';
    
    mailchimp.setConfig({
        apiKey: 'test-key',
        server: 'us1' // This will be ignored when MAILCHIMP_BASE_URL is set
    });
    
    try {
        const response = await mailchimp.ping.get();
        console.log('Mock server response:', response.data);
    } catch (error) {
        console.error('Mock server not available:', error);
    }
}
```

#### Available Types

- `MailchimpConfig` - Configuration object with detailed JSDoc
- `ApiResponse<T>` - Generic API response wrapper with response metadata
- `ListMember` - Complete list member data structure
- `Campaign` - Comprehensive campaign data structure  
- `ErrorResponse` - Detailed error response structure
- `PaginationOptions` - Common pagination parameters
- **`AddListMemberBody`** - Type for adding new members to lists
- **`UpdateListMemberBody`** - Type for updating existing members
- **`CreateCampaignBody`** - Type for creating new campaigns
- **`UpdateCampaignBody`** - Type for updating campaigns
- **`CreateListBody`** - Type for creating new lists
- **`UpdateListBody`** - Type for updating lists
- **`MemberTagsBody`** - Type for managing member tags
- **`StatusTag`** - Type for member status tags
- And many more comprehensive interfaces...

#### Importing Specific Types

You can now import specific interfaces for better type safety:

```typescript
import mailchimp, { 
  AddListMemberBody, 
  UpdateListMemberBody, 
  CreateCampaignBody,
  ListMember,
  Campaign,
  MemberTagsBody,
  StatusTag
} from '@industriousoffice/mailchimp_marketing';

// Use the imported types
const memberData: AddListMemberBody = {
  email_address: 'user@example.com',
  status: 'subscribed',
  merge_fields: {
    FNAME: 'John',
    LNAME: 'Doe'
  }
};

// Example: Managing member tags
const tagData: MemberTagsBody = {
  tags: [
    { name: 'VIP', status: 'active' },
    { name: 'Newsletter', status: 'inactive' }
  ]
};

// Example: Working with status tags
const statusTag: StatusTag = {
  id: 123,
  name: 'Premium Customer'
};

const campaignData: CreateCampaignBody = {
  type: 'regular',
  recipients: {
    list_id: 'your-list-id'
  },
  settings: {
    subject_line: 'Hello from TypeScript!',
    from_name: 'Your Company',
    reply_to: 'noreply@company.com'
  }
};

// Type-safe API calls
const member: ApiResponse<ListMember> = await mailchimp.lists.addListMember('list-id', memberData);
const campaign: ApiResponse<Campaign> = await mailchimp.campaigns.create(campaignData);
```

#### Example Files

The package includes comprehensive TypeScript examples:
- `examples/typescript-example.ts` - Complete usage examples
- `TYPESCRIPT.md` - Detailed TypeScript integration guide

### 2. Environment Variable Integration - `MAILCHIMP_BASE_URL`

We've enhanced the API client to support flexible endpoint configuration through the `MAILCHIMP_BASE_URL` environment variable, enabling seamless switching between production and testing environments.

#### How It Works

The `MAILCHIMP_BASE_URL` environment variable controls which Mailchimp endpoint the client connects to:

**Production Mode (Default)**
- **When**: `MAILCHIMP_BASE_URL` is NOT set
- **Behavior**: Uses the standard Mailchimp API endpoints
- **Base URL**: `https://server.api.mailchimp.com/3.0`
- **Server Resolution**: The word "server" is dynamically replaced with your configured server (e.g., 'us1', 'us2', 'us19')
- **Final URL Example**: `https://us1.api.mailchimp.com/3.0` (when server is 'us1')

**Testing/Mock Mode**
- **When**: `MAILCHIMP_BASE_URL` is set to a custom URL
- **Behavior**: Uses the custom endpoint (typically a mock server)
- **Server Config**: Ignored - server parameter has no effect
- **Final URL**: Exactly what you specify in the environment variable

#### Usage Examples

```javascript
// Production Usage
const mailchimp = require('@industriousoffice/mailchimp_marketing');

mailchimp.setConfig({
  apiKey: 'your-api-key-us1',
  server: 'us1'  // Will resolve to https://us1.api.mailchimp.com/3.0
});

// Testing Usage with Mock Server
process.env.MAILCHIMP_BASE_URL = 'http://localhost:3001/3.0';

mailchimp.setConfig({
  apiKey: 'test-api-key',
  server: 'us1'  // This is IGNORED when MAILCHIMP_BASE_URL is set
});
// Will connect to: http://localhost:3001/3.0
```

#### Environment Variable Setup

```bash
# For testing with a local mock server
export MAILCHIMP_BASE_URL="http://localhost:3001/3.0"

# For testing with a staging server
export MAILCHIMP_BASE_URL="https://staging-api.yourdomain.com/mailchimp/3.0"

# For production (don't set this variable)
unset MAILCHIMP_BASE_URL
```

#### Docker Integration

```dockerfile
# In your Dockerfile for testing
ENV MAILCHIMP_BASE_URL=http://mock-mailchimp:3001/3.0

# In your docker-compose.yml
services:
  your-app:
    environment:
      - MAILCHIMP_BASE_URL=http://mock-mailchimp:3001/3.0
```

#### Testing Benefits

1. **Isolated Testing**: Run tests against mock servers without affecting production data
2. **CI/CD Integration**: Easily configure different endpoints for different environments
3. **Development Flexibility**: Switch between local mocks and staging servers
4. **Cost Reduction**: Avoid API rate limits and costs during development

### 3. Security Updates - Vulnerable Dependencies Fixed

We've comprehensively updated all dependencies to resolve critical security vulnerabilities.

#### Security Improvements

**Before Update**
- ⚠️ **27 total vulnerabilities** (4 critical, 6 high, 17 moderate)
- Outdated dependencies with known security issues
- Potential for exploitation in production environments

**After Update**
- ✅ **0 vulnerabilities**
- All dependencies updated to latest secure versions
- Production-ready security posture

#### Updated Dependencies

| Package | Old Version | New Version | Security Impact |
|---------|-------------|-------------|-----------------|
| **superagent** | 3.8.1 | 10.2.3 | Critical security fixes, API improvements |
| **dotenv** | 8.2.0 | 16.6.1 | Multiple security patches |
| **jest** | 26.2.2 | 29.7.0 | Fixes braces vulnerability (ReDoS attacks) |
| **mocha** | 2.3.4 | 10.8.2 | Multiple critical fixes (command injection, ReDoS) |
| **sinon** | 1.17.3 | 18.0.1 | General security and stability improvements |
| **typescript** | - | 5.5.4+ | Added for TypeScript support (dev dependency) |
| **@types/node** | - | 20.14.12+ | Added for Node.js type definitions (dev dependency) |

#### Critical Vulnerabilities Resolved

1. **Growl Command Injection** (Critical)
   - CVE: GHSA-qh2h-chj9-jffq
   - Impact: Remote code execution potential
   - Resolution: Updated Mocha dependency chain

2. **Minimist Prototype Pollution** (Critical)
   - CVE: GHSA-vh95-rmgr-6w4m, GHSA-xvch-5gv4-984h
   - Impact: Application logic bypass, potential RCE
   - Resolution: Updated through dependency chain

3. **Braces ReDoS Vulnerability** (High)
   - CVE: GHSA-grv7-fg5c-xmjg
   - Impact: Denial of Service through regex attacks
   - Resolution: Updated Jest and related dependencies

4. **Debug RegEx Complexity** (High)
   - CVE: GHSA-9vvw-cc9w-f27h, GHSA-gxpj-cx7g-858c
   - Impact: Denial of Service
   - Resolution: Updated Mocha dependency chain

#### Migration Notes

**Breaking Changes Warning**
- Major version updates may introduce breaking changes
- Test your application thoroughly after updating
- Review any custom test configurations for Jest/Mocha

**SuperAgent API Changes**
- SuperAgent v10 has significant API changes from v3
- Most basic usage patterns remain compatible
- Advanced features may require code updates

## 📦 Installation

```bash
npm install @industriousoffice/mailchimp_marketing
```

## 🚀 Quick Start

### JavaScript/Node.js

```javascript
const mailchimp = require('@industriousoffice/mailchimp_marketing');

// Production setup
mailchimp.setConfig({
  apiKey: 'your-api-key-us1',
  server: 'us1'
});

// Get account info
async function getAccount() {
  try {
    const response = await mailchimp.root.getRoot();
    console.log(response);
  } catch (error) {
    console.error('Error:', error);
  }
}
```

### TypeScript

```typescript
import mailchimp from '@industriousoffice/mailchimp_marketing';

// Production setup with type checking
mailchimp.setConfig({
  apiKey: 'your-api-key-us1',
  server: 'us1'
});

// Get account info with full type support
async function getAccount(): Promise<void> {
  try {
    const response = await mailchimp.root.getRoot();
    console.log(response.data);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Ping API with type safety
async function pingAPI(): Promise<void> {
  const response = await mailchimp.ping.get();
  console.log('API Status:', response.data.health_status); // TypeScript knows this is a string
}
```

## 🧪 Testing Setup

```javascript
// Set up for testing
process.env.MAILCHIMP_BASE_URL = 'http://localhost:3001/3.0';

const mailchimp = require('@industriousoffice/mailchimp_marketing');

mailchimp.setConfig({
  apiKey: 'test-key',
  server: 'ignored-in-test-mode'
});

// Your tests here...
```

## 🔒 Security Best Practices

1. **Environment Variables**: Store API keys in environment variables, never in code
2. **Testing Isolation**: Always use mock servers for automated testing
3. **Dependency Updates**: Regularly update dependencies to patch security vulnerabilities
4. **API Key Rotation**: Rotate API keys regularly and use different keys for different environments

## 📄 License

Apache 2.0

## 🐛 Issues & Support

- **Original Issues**: [Mailchimp Client Codegen Issues](https://github.com/mailchimp/mailchimp-client-lib-codegen/issues)
- **Industrious Enhancements**: Contact your internal development team

## 📋 Version History

- **v3.1.2**: Fixed TypeScript module exports for individual interface imports
  - Added support for importing specific types like `AddListMemberBody`
  - Fixed "Module has no exported member" errors
  - Enhanced type definitions with proper module structure
- **v3.1.0**: Added comprehensive TypeScript support with complete type definitions
  - Full TypeScript declarations (`.d.ts` files)
  - IntelliSense support for all API endpoints
  - Strongly typed interfaces for all data structures
  - Complete examples and documentation
  - Maintained backward compatibility with JavaScript
- **v3.0.80**: Security updates and MAILCHIMP_BASE_URL integration
  - Enhanced for production and testing use cases
  - All critical and high-severity vulnerabilities resolved
  - Environment variable support for flexible endpoint configuration

---

**Note**: This is a modified version of the official Mailchimp Marketing API client. For original documentation, refer to the [official Mailchimp API documentation](https://mailchimp.com/developer/marketing/api/).
