npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

aivawins

v1.0.1

Published

Official TypeScript/JavaScript SDK for AIVA Platform API - subscription analytics, RFM segmentation, and marketing automation

Readme

AIVA Platform API Client

Official TypeScript/JavaScript SDK for the AIVA Platform API.

npm version TypeScript License: MIT

Build subscription analytics, customer segmentation, and marketing automation into your applications with AIVA's powerful API.

Features

  • Complete TypeScript support - Full type definitions with autocomplete
  • 35+ API methods - All AIVA Merchant API endpoints covered
  • RFM Segmentation - Champions, Loyal, At Risk, Churned customers
  • Real-time Analytics - MRR, churn rate, revenue trends
  • Prize Draws - Blockchain-verified random draws
  • Marketing Automation - Campaigns, webhooks, and triggers
  • Affiliate Tracking - Commission management and sales attribution
  • Flexible Auth - API keys or customer tokens
  • Error Handling - Graceful error responses with details

Installation

npm install aivawins

Or with yarn:

yarn add aivawins

Or with pnpm:

pnpm add aivawins

Quick Start

import { createAivaClient } from 'aivawins';

const client = createAivaClient({
  baseUrl: 'https://api.aivawins.ai',
  apiKey: process.env.AIVA_API_KEY!,
  merchantId: 'merch_xyz123'
});

// Get your business metrics
const metrics = await client.getDashboardMetrics();
console.log(`MRR: $${metrics.data.mrr}`);
console.log(`Active Subscriptions: ${metrics.data.activeSubscriptions}`);

// Get Champion customers for VIP campaign
const champions = await client.getCustomers({ segment: 'Champion' });
console.log(`Champions: ${champions.data.customers.length}`);

Authentication

API Key (Recommended for Merchants)

import { createAivaClient } from 'aivawins';

const client = createAivaClient({
  baseUrl: 'https://api.aivawins.ai',
  apiKey: 'your_api_key_here',
  merchantId: 'merch_xyz123'
});

Get your API key:

  1. Login to AIVA Dashboard
  2. Navigate to Settings → API Keys
  3. Click "Generate New API Key"

Customer Token (For Customer-Facing Apps)

const client = createAivaClient({
  baseUrl: 'https://api.aivawins.ai',
  customerToken: 'customer_token_from_auth'
});

API Reference

Merchant

Get and update merchant settings.

// Get merchant info
const merchant = await client.getMerchant();
console.log(merchant.data.companyName);

// Update merchant settings
await client.updateMerchant('merch_xyz', {
  companyName: 'New Company Name',
  currency: 'USD'
});

Customers

Manage and segment customers using RFM analysis.

// Get all customers (paginated)
const customers = await client.getCustomers({
  page: 1,
  pageSize: 20
});

// Get customers by RFM segment
const champions = await client.getCustomers({
  segment: 'Champion'
});

const atRisk = await client.getCustomers({
  segment: 'At Risk'
});

// Search customers
const results = await client.getCustomers({
  search: '[email protected]'
});

// Get single customer
const customer = await client.getCustomer('cust_abc123');
console.log(`LTV: $${customer.data.lifetimeValue}`);
console.log(`Segment: ${customer.data.rfmSegment}`);

RFM Segments:

  • Champion - Best customers (high R, F, M)
  • Loyal - Regular purchasers
  • Potential Loyalist - Recent customers with potential
  • New Customers - First-time buyers
  • At Risk - Used to buy frequently, but haven't recently
  • Churned - Haven't purchased in a long time

Subscriptions

Manage customer subscriptions.

// Get all subscriptions
const subs = await client.getSubscriptions({
  page: 1,
  pageSize: 50
});

// Get customer's subscriptions
const customerSubs = await client.getCustomerSubscriptions('cust_abc123');

// Get subscription details
const sub = await client.getSubscription('sub_xyz789');

// Pause subscription
await client.pauseSubscription('sub_xyz789');

// Resume subscription
await client.resumeSubscription('sub_xyz789');

// Cancel subscription
await client.cancelSubscription('sub_xyz789', {
  reason: 'Customer requested cancellation'
});

Orders

Retrieve order history and details.

// Get all orders
const orders = await client.getOrders({
  page: 1,
  pageSize: 100
});

// Get customer's orders
const customerOrders = await client.getCustomerOrders('cust_abc123');

// Get order details
const order = await client.getOrder('ord_456def');
console.log(`Total: $${order.data.totalAmount}`);
console.log(`Items: ${order.data.items.length}`);

Analytics

Get business intelligence and revenue metrics.

// Dashboard metrics (MRR, churn, LTV)
const metrics = await client.getDashboardMetrics();
console.log(`MRR: $${metrics.data.mrr}`);
console.log(`Churn Rate: ${metrics.data.churnRate}%`);
console.log(`Avg LTV: $${metrics.data.averageLTV}`);

// MRR trend over time
const trend = await client.getMRRTrend({ months: 12 });
trend.data.forEach(month => {
  console.log(`${month.month}: $${month.mrr}`);
});

// RFM distribution
const rfm = await client.getRFMDistribution();
console.log(`Champions: ${rfm.data.segments.Champion}`);
console.log(`At Risk: ${rfm.data.segments['At Risk']}`);

// Revenue analytics
const revenue = await client.getRevenueAnalytics({
  startDate: '2025-01-01',
  endDate: '2025-11-24'
});
console.log(`Total Revenue: $${revenue.data.totalRevenue}`);

Prize Draws

Create and manage blockchain-verified prize draws.

// Get active prize draws
const active = await client.getActivePrizeDraws();

// Get all prize draws
const draws = await client.getPrizeDraws({
  page: 1,
  pageSize: 20
});

// Get prize draw details
const draw = await client.getPrizeDraw('draw_202511');
console.log(`Prize Pool: $${draw.data.prizePool}`);
console.log(`Total Entries: ${draw.data.totalEntries}`);

// Create new prize draw
const newDraw = await client.createPrizeDraw({
  name: 'November Grand Prize',
  prizePool: 5000,
  drawDate: '2025-11-30T20:00:00Z',
  description: 'Monthly grand prize draw for all subscribers'
});

// Execute prize draw (on draw date)
const result = await client.executePrizeDraw('draw_202511');
console.log(`Winner: ${result.data.winnerId}`);
console.log(`Blockchain TX: ${result.data.blockchainTxHash}`);

// Get customer's prize entries
const entries = await client.getCustomerPrizeEntries('cust_abc123');
console.log(`Total Entries: ${entries.data.totalEntries}`);

Affiliates

Manage affiliate program and track commissions.

// Get all affiliates
const affiliates = await client.getAffiliates({
  page: 1,
  pageSize: 50
});

// Get affiliate details
const affiliate = await client.getAffiliate('aff_jkl012');
console.log(`Total Commissions: $${affiliate.data.totalCommissions}`);

// Get affiliate sales
const sales = await client.getAffiliateSales('aff_jkl012', {
  startDate: '2025-11-01',
  endDate: '2025-11-30'
});
console.log(`Sales this month: ${sales.data.length}`);

// Create new affiliate
const newAffiliate = await client.createAffiliate({
  email: '[email protected]',
  firstName: 'John',
  lastName: 'Doe',
  commissionRate: 0.20 // 20%
});

Marketing

Create targeted campaigns based on RFM segments.

// Get all campaigns
const campaigns = await client.getCampaigns({
  page: 1,
  pageSize: 20
});

// Create email campaign
const campaign = await client.createCampaign({
  name: 'Win-back At Risk Customers',
  targetSegment: 'At Risk',
  channel: 'email',
  subject: 'We miss you! Here\'s 20% off',
  message: 'We noticed you haven\'t ordered recently...',
  scheduleAt: '2025-11-25T09:00:00Z'
});

// Get campaign stats
const stats = await client.getCampaignStats('camp_mno345');
console.log(`Sent: ${stats.data.sentCount}`);
console.log(`Open Rate: ${stats.data.openRate}%`);
console.log(`Click Rate: ${stats.data.clickRate}%`);

Webhooks

Set up real-time notifications for events.

// Get all webhooks
const webhooks = await client.getWebhooks();

// Create webhook
const webhook = await client.createWebhook({
  event: 'customer.segment_changed',
  url: 'https://yourdomain.com/webhooks/aiva',
  filters: {
    segment: 'At Risk'
  }
});

// Delete webhook
await client.deleteWebhook('hook_pqr678');

Available Events:

  • customer.created
  • customer.updated
  • customer.segment_changed
  • subscription.created
  • subscription.paused
  • subscription.resumed
  • subscription.cancelled
  • order.created
  • prize_draw.winner_selected
  • affiliate.sale_created

TypeScript Support

Full TypeScript definitions included:

import {
  createAivaClient,
  AivaApiClient,
  ApiClientConfig,
  Customer,
  Subscription,
  Order,
  PrizeDraw,
  Campaign,
  Affiliate,
  DashboardMetrics
} from 'aivawins';

const client: AivaApiClient = createAivaClient({
  baseUrl: 'https://api.aivawins.ai',
  apiKey: process.env.AIVA_API_KEY!,
  merchantId: 'merch_xyz'
});

// Full autocomplete and type checking
const customer: Customer = (await client.getCustomer('cust_123')).data;

Error Handling

All methods return an ApiResponse<T> with success flag:

const result = await client.getCustomer('cust_abc123');

if (result.success) {
  console.log('Customer:', result.data);
} else {
  console.error('Error:', result.error.message);
  console.error('Code:', result.error.code);
}

Common Error Codes:

  • INVALID_API_KEY - API key is missing or invalid
  • UNAUTHORIZED - API key doesn't have permission
  • NOT_FOUND - Resource doesn't exist
  • RATE_LIMIT_EXCEEDED - Too many requests
  • VALIDATION_ERROR - Invalid request data

Try/Catch Pattern:

try {
  const customer = await client.getCustomer('cust_abc123');
  if (!customer.success) {
    throw new Error(customer.error.message);
  }
  console.log(customer.data);
} catch (error) {
  console.error('Failed to fetch customer:', error);
}

Framework Examples

Next.js App Router

// app/api/customers/route.ts
import { createAivaClient } from 'aivawins';
import { NextResponse } from 'next/server';

const client = createAivaClient({
  baseUrl: process.env.AIVA_API_URL!,
  apiKey: process.env.AIVA_API_KEY!,
  merchantId: process.env.AIVA_MERCHANT_ID!
});

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const segment = searchParams.get('segment');

  const result = await client.getCustomers({
    segment: segment || undefined,
    page: 1,
    pageSize: 20
  });

  if (!result.success) {
    return NextResponse.json(
      { error: result.error.message },
      { status: 400 }
    );
  }

  return NextResponse.json(result.data);
}

React Hook (Client-Side)

⚠️ SECURITY WARNING: Never use your API key in client-side code! Use a backend API route to proxy requests.

// hooks/useAivaMetrics.ts
import { useState, useEffect } from 'react';

export function useAivaMetrics() {
  const [metrics, setMetrics] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadMetrics() {
      // Call YOUR backend API, which then calls AIVA API
      const response = await fetch('/api/aiva/metrics');
      const data = await response.json();
      setMetrics(data);
      setLoading(false);
    }
    loadMetrics();
  }, []);

  return { metrics, loading };
}

Backend API route (server-side only):

// app/api/aiva/metrics/route.ts
import { createAivaClient } from 'aivawins';
import { NextResponse } from 'next/server';

// ✅ SECURE: API key only exists on server, never sent to client
const client = createAivaClient({
  baseUrl: process.env.AIVA_API_URL!,  // No NEXT_PUBLIC_ prefix!
  apiKey: process.env.AIVA_API_KEY!,   // Never exposed to browser
  merchantId: process.env.AIVA_MERCHANT_ID!
});

export async function GET() {
  const result = await client.getDashboardMetrics();

  if (!result.success) {
    return NextResponse.json(
      { error: result.error.message },
      { status: 400 }
    );
  }

  return NextResponse.json(result.data);
}

Express.js

// server.js
const express = require('express');
const { createAivaClient } = require('aivawins');

const app = express();
const client = createAivaClient({
  baseUrl: process.env.AIVA_API_URL,
  apiKey: process.env.AIVA_API_KEY,
  merchantId: process.env.AIVA_MERCHANT_ID
});

app.get('/api/champions', async (req, res) => {
  const result = await client.getCustomers({ segment: 'Champion' });

  if (!result.success) {
    return res.status(400).json({ error: result.error.message });
  }

  res.json(result.data);
});

app.listen(3000);

Environment Variables

Create a .env file:

AIVA_API_URL=https://api.aivawins.ai
AIVA_API_KEY=your_api_key_here
AIVA_MERCHANT_ID=merch_xyz123

Then use in your code:

import { createAivaClient } from 'aivawins';

const client = createAivaClient({
  baseUrl: process.env.AIVA_API_URL!,
  apiKey: process.env.AIVA_API_KEY!,
  merchantId: process.env.AIVA_MERCHANT_ID!
});

Common Use Cases

1. Win-back Campaign for At-Risk Customers

// Get at-risk customers
const atRisk = await client.getCustomers({ segment: 'At Risk' });

// Create targeted campaign
const campaign = await client.createCampaign({
  name: 'Win-back At Risk',
  targetSegment: 'At Risk',
  channel: 'email',
  subject: 'We miss you! 20% off your next order',
  message: 'You haven\'t ordered recently. Come back with 20% off!',
  scheduleAt: '2025-11-25T09:00:00Z'
});

console.log(`Campaign created: ${campaign.data.campaignId}`);
console.log(`Targeting: ${atRisk.data.totalCount} at-risk customers`);

2. VIP Treatment for Champions

// Get Champions
const champions = await client.getCustomers({ segment: 'Champion' });

// Set up webhook to notify when someone becomes a Champion
const webhook = await client.createWebhook({
  event: 'customer.segment_changed',
  url: 'https://yourdomain.com/webhooks/new-champion',
  filters: { segment: 'Champion' }
});

// Send VIP rewards
for (const customer of champions.data.customers) {
  console.log(`VIP Customer: ${customer.email}`);
  console.log(`LTV: $${customer.lifetimeValue}`);
  // Send to your CRM, email marketing, etc.
}

3. Business Intelligence Dashboard

// Get comprehensive metrics
const metrics = await client.getDashboardMetrics();
const trend = await client.getMRRTrend({ months: 12 });
const rfm = await client.getRFMDistribution();

// Build dashboard data
const dashboard = {
  mrr: metrics.data.mrr,
  churnRate: metrics.data.churnRate,
  activeSubscriptions: metrics.data.activeSubscriptions,
  mrrTrend: trend.data,
  segmentDistribution: rfm.data.segments
};

console.log(dashboard);

4. Automated Prize Draw

// Create monthly draw
const draw = await client.createPrizeDraw({
  name: 'November Grand Prize',
  prizePool: 5000,
  drawDate: '2025-11-30T20:00:00Z',
  description: 'All active subscribers automatically entered'
});

// On draw date (via cron job)
const result = await client.executePrizeDraw(draw.data.drawId);

console.log(`Winner: ${result.data.winnerId}`);
console.log(`Blockchain Proof: ${result.data.blockchainTxHash}`);

// Notify winner
const winner = await client.getCustomer(result.data.winnerId);
console.log(`Email: ${winner.data.email}`);

Rate Limits

  • Standard Plan: 1,000 requests/hour
  • Pro Plan: 10,000 requests/hour
  • Enterprise: Custom limits

Rate limit headers returned with every response:

  • X-RateLimit-Limit - Max requests per hour
  • X-RateLimit-Remaining - Remaining requests
  • X-RateLimit-Reset - Timestamp when limit resets

Support

Documentation:

  • API Docs: https://aivawins.ai/developers/
  • Quick Start: https://aivawins.ai/quick-start/
  • RFM Guide: https://aivawins.ai/rfm-guide/

Interactive API:

  • Swagger UI: https://api.aivawins.ai/swagger

Support:


Contributing

Contributions welcome! Please submit a pull request or open an issue.


License

MIT License - see LICENSE file for details


Changelog

1.0.0 (November 2025)

  • Initial release
  • 35+ API methods
  • Full TypeScript support
  • Complete AIVA Merchant API coverage

Built with ❤️ by the AIVA Platform Team

For more information, visit aivawins.ai