npm package: @gethamla/sdk
Description: Lightweight marketing SDK for e-commerce — popups, push notifications, email campaigns, and behavioral targeting. Works with Salla, Zid, and custom platforms.
Author: Alienzhouse LTD
Latest version: 2.5.1

# @gethamla/sdk

> **Intelligent multi-channel campaign SDK for e-commerce platforms**

The Hamla SDK enables smart, goal-driven marketing campaigns that automatically choose the best channel (popup, banner, toast, email, SMS, WhatsApp) and message for each visitor based on their intent, journey stage, and behavior.

## 🚀 Quick Start

### Installation

```bash
npm install @gethamla/sdk
# or
yarn add @gethamla/sdk
# or
pnpm add @gethamla/sdk
```

### Basic Usage

```html
<!-- Add to your website -->
<script>
  !function(w,d){
    w.Hamla=w.Hamla||{};
    w.Hamla.config={storeId:"your-store-id"};
    var s=d.createElement("script");
    s.async=1;
    s.src="https://cdn.hamla.io/sdk/v5/hamla.min.js";
    d.head.appendChild(s);
  }(window,document);
</script>
```

Or as an ES module:

```typescript
import { HamlaSDK } from '@gethamla/sdk';

const hamla = new HamlaSDK({
  storeId: 'your-store-id',
  debug: process.env.NODE_ENV === 'development'
});

await hamla.init();
```

## ✨ Features

### 🎯 Goal-First Campaigns
Create campaigns focused on business goals (cart recovery, product launch, loyalty) rather than just messages.

### 🧠 Intelligent Decision Making
- **Intent Detection**: Understands purchase readiness (0-1 score)
- **Journey Stage**: Detects where visitors are in the funnel
- **Fatigue Management**: Prevents over-messaging across all channels

### 📱 Multi-Channel Support
- **On-Site**: Popup, Banner, Toast, Slide-in
- **Off-Site**: Email, SMS, WhatsApp (scheduled)
- **Smart Selection**: Automatically picks the best channel per visitor

### 🔄 Advanced Orchestration
- **DO_NOTHING Option**: Sometimes not showing anything is the best decision
- **Thompson Sampling**: AI-powered message testing and optimization
- **Cross-Channel Attribution**: Track conversions across all touchpoints

### ⚡ Performance First
- **<25KB** gzipped bundle
- **<5ms** decision time
- **Zero** layout shift (CLS = 0)
- Shadow DOM isolation (no CSS conflicts)

## 📚 Documentation

### Core Concepts

1. **[Getting Started](./docs/GETTING_STARTED.md)** - Installation and basic setup
2. **[Campaign Architecture](./docs/CAMPAIGN_ARCHITECTURE.md)** - Understanding goals, channels, and messages
3. **[Intelligence System](./docs/INTELLIGENCE.md)** - Intent, journey, and fatigue tracking
4. **[Triggers](./docs/TRIGGERS.md)** - When to show campaigns
5. **[Targeting](./docs/TARGETING.md)** - Who sees campaigns
6. **[Multi-Channel Scheduling](./docs/SCHEDULING.md)** - Delayed channel execution

### Platform Guides

- **[Salla Integration](./docs/platforms/SALLA.md)** - Complete Salla platform guide
- **[Shopify Integration](./docs/platforms/SHOPIFY.md)** - Shopify setup
- **[WooCommerce Integration](./docs/platforms/WOOCOMMERCE.md)** - WordPress/WooCommerce
- **[Custom Integration](./docs/platforms/CUSTOM.md)** - Any platform via adapters

### Advanced Topics

- **[Custom Platform Adapters](./docs/PLATFORM_ADAPTERS.md)** - Build your own adapter
- **[Variable Resolution](./docs/VARIABLES.md)** - Personalize messages with {{user.firstName}}
- **[Event Tracking](./docs/EVENTS.md)** - Analytics and attribution
- **[API Reference](./docs/API_REFERENCE.md)** - Complete API documentation

## 🎨 Example: Cart Recovery Campaign

### Create in Dashboard

```typescript
{
  "goal": "CART_RECOVERY",
  "name": "Abandoned Cart Recovery",
  "channels": [
    {
      "type": "IN_SITE_NOTIFICATION",
      "priority": 1,
      "timing": { "strategy": "immediate" },
      "messages": [{
        "type": "simple",
        "text": "لديك {{cart.itemCount}} منتجات في سلتك!",
        "ctas": [
          { "text": "أكمل الشراء", "action": "link", "url": "/checkout" }
        ]
      }]
    },
    {
      "type": "EMAIL",
      "priority": 2,
      "timing": {
        "strategy": "delayed",
        "delay": "1h",
        "condition": { "type": "no_conversion" }
      },
      "messages": [{
        "type": "rich",
        "subject": "أكمل طلبك واحصل على خصم 10%",
        "sections": [
          { "type": "text", "content": { "text": "مرحباً {{user.firstName}}" } },
          { "type": "cart_preview" },
          { "type": "button", "content": { "text": "أكمل الشراء", "url": "{{cart.checkoutUrl}}" } }
        ]
      }]
    }
  ],
  "triggers": [
    { "type": "EXIT_INTENT", "enabled": true }
  ],
  "targeting": {
    "rules": [
      { "field": "cart.value", "operator": "gt", "value": 100 }
    ]
  }
}
```

### What Happens

1. **User adds items to cart** → SDK tracks cart value
2. **User moves mouse to exit** → Exit intent trigger fires
3. **SDK evaluates**:
   - ✅ Cart value > 100 (targeting passes)
   - ✅ Intent score: 0.65 (medium-high)
   - ✅ Journey stage: DECISION
   - ✅ Fatigue: Fresh (no recent campaigns)
4. **Decision**: Show notification immediately
5. **User ignores notification**
6. **1 hour later**: Background job checks if user converted
7. **Not converted?** → Email sent with cart preview

## 🔌 SDK API

### Initialization

```typescript
import { HamlaSDK } from '@gethamla/sdk';

const hamla = new HamlaSDK({
  storeId: 'store_123',
  apiUrl: 'https://api.hamla.io', // optional
  debug: true, // enable logging
});

await hamla.init();
```

### Identify User

```typescript
hamla.identify({
  userId: 'user_456',
  email: 'customer@example.com',
  phone: '+966501234567',
  attributes: {
    firstName: 'أحمد',
    segment: 'vip',
    lifetimeValue: 5000
  }
});
```

### Update Cart

```typescript
hamla.updateCart({
  items: [
    {
      productId: 'prod_1',
      name: 'iPhone 15',
      price: 3999,
      quantity: 1,
      image: 'https://...'
    }
  ],
  total: 3999,
  currency: 'SAR'
});
```

### Track Events

```typescript
// Track page view
hamla.track('page_view', {
  pageType: 'product',
  productId: 'prod_1',
  category: 'electronics'
});

// Track custom event
hamla.track('video_watched', {
  videoId: 'intro_video',
  duration: 120
});
```

### Manual Trigger

```typescript
// Trigger a campaign manually
hamla.trigger('custom_event', {
  customData: 'value'
});
```

### Manual Notification API (Testing)

```typescript
// Show test notification (bypasses all logic)
hamla.showNotification({
  type: 'toast', // or 'banner', 'popup'
  message: {
    type: 'simple',
    text: 'Test notification',
    ctas: [
      { text: 'Click me', action: 'link', url: '/test' }
    ]
  },
  position: 'bottom-right', // for toast
  dismissAfter: 5000
});
```

## 🧪 Testing & Development

### Debug Mode

```typescript
const hamla = new HamlaSDK({
  storeId: 'store_123',
  debug: true // Enables console logging
});
```

Debug mode shows:
- Campaign fetch results
- Trigger activations
- Decision reasoning (why campaign shown/skipped)
- Intelligence scores (intent, journey, fatigue)
- Channel selection logic

### Test Mode

```typescript
// Override campaigns for testing
hamla.setTestCampaigns([
  {
    id: 'test_1',
    goal: 'CART_RECOVERY',
    // ... campaign config
  }
]);

// Simulate triggers
hamla.trigger('exit_intent');
```

### Event Listeners

```typescript
// Listen to SDK events
hamla.on('notification:shown', (event) => {
  console.log('Notification shown', event);
});

hamla.on('notification:dismissed', (event) => {
  console.log('Dismissed after', event.durationShown, 'ms');
});

hamla.on('cta:clicked', (event) => {
  console.log('CTA clicked', event.ctaLabel);
});

hamla.on('conversion:tracked', (event) => {
  console.log('Conversion!', event.value);
});
```

## 🏗️ Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                     Hamla SDK v5.0                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────┐    ┌──────────────┐   ┌──────────────┐  │
│  │   Triggers   │───▶│ Orchestrator │──▶│   Channels   │  │
│  │              │    │              │   │              │  │
│  │ • Exit Intent│    │ • Campaign   │   │ • Popup      │  │
│  │ • Scroll     │    │   Selection  │   │ • Banner     │  │
│  │ • Time       │    │ • Channel    │   │ • Toast      │  │
│  │ • Cart       │    │   Selection  │   │ • Email      │  │
│  └──────────────┘    │ • Message    │   │ • SMS        │  │
│                      │   Selection  │   │ • WhatsApp   │  │
│  ┌──────────────┐    └──────────────┘   └──────────────┘  │
│  │ Intelligence │           │                              │
│  │              │           │                              │
│  │ • Intent     │───────────┘                              │
│  │ • Journey    │                                          │
│  │ • Fatigue    │           ┌──────────────┐              │
│  └──────────────┘           │  Scheduler   │              │
│                             │              │              │
│  ┌──────────────┐           │ • Email Jobs │              │
│  │  Analytics   │◀──────────│ • SMS Jobs   │              │
│  │              │           │ • Conditions │              │
│  │ • Events     │           └──────────────┘              │
│  │ • Attribution│                                          │
│  └──────────────┘                                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### Key Components

- **Triggers**: Detect user actions (exit intent, scroll, time, cart changes)
- **Intelligence**: Analyze user intent, journey stage, and fatigue
- **Orchestrator**: Decide which campaign, channel, and message to show
- **Channels**: Render campaigns via different channels (popup, email, etc.)
- **Scheduler**: Execute delayed channels (emails sent 1 hour later)
- **Analytics**: Track everything for optimization

## 🌍 Browser Support

- Chrome/Edge: Last 2 versions
- Firefox: Last 2 versions
- Safari: 14+
- Mobile Safari: iOS 14+
- Android WebView: Android 8+

## 📦 Bundle Size

| Package | Size (gzipped) |
|---------|----------------|
| Core SDK | 18KB |
| + Salla Adapter | +4KB |
| + All Features | 25KB |

## 🔒 Privacy & Security

- **GDPR Compliant**: Respects DNT headers
- **No Third-Party Cookies**: Uses first-party storage only
- **Secure by Default**: All API calls over HTTPS
- **XSS Protection**: All content sanitized
- **CSP Compatible**: Works with strict Content Security Policy

## 🤝 Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup and guidelines.

## 📄 License

MIT License - see [LICENSE](./LICENSE) for details.

## 🆘 Support

- **Documentation**: [docs.hamla.io](https://docs.hamla.io)
- **GitHub Issues**: [github.com/hamla/sdk/issues](https://github.com/hamla/sdk/issues)
- **Email**: support@hamla.io
- **Discord**: [discord.gg/hamla](https://discord.gg/hamla)

---

**Built with ❤️ by Hamla**