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 🙏

© 2026 – Pkg Stats / Ryan Hefner

saas-platform-subscription-client

v1.3.1

Published

Subscription client for SaaS platform subscription-service

Readme

@saas-platform/subscription-client

TypeScript/JavaScript client for SaaS platform subscription service.

Features

  • 📋 Subscription Management - Create, update, cancel subscriptions
  • 💼 Plan Management - Define and manage subscription plans
  • Feature Management - Control feature access and limits
  • 📊 Usage Tracking - Track and analyze feature usage
  • 📈 Analytics - Subscription and usage reporting
  • 🔐 Secure - JWT token authentication with automatic refresh
  • 📦 TypeScript Support - Full type safety with Zod validation

Installation

npm install @saas-platform/subscription-client @saas-platform/core-client @saas-platform/auth-client

Basic Usage

import { AuthClient } from '@saas-platform/auth-client';
import { SubscriptionClient } from '@saas-platform/subscription-client';

// Setup authentication
const authClient = new AuthClient({
  saasId: 'your-saas-id',
  authServiceUrl: 'http://localhost:8000'
});

// Login to get tokens
await authClient.login({
  email: '[email protected]',
  password: 'password123',
  saasId: 'your-saas-id'
});

// Create subscription client with auth manager
const subscriptionClient = new SubscriptionClient({
  saasId: 'your-saas-id',
  authServiceUrl: 'http://localhost:8000',
  subscriptionServiceUrl: 'http://localhost:8001'
}, authClient.authManager);

Subscription Management

Create Subscription

const subscription = await subscriptionClient.createSubscription({
  customerId: 'customer-uuid',
  planId: 'plan-uuid',
  startDate: '2024-01-01T00:00:00Z',
  billingInterval: 'monthly',
  metadata: {
    source: 'website',
    campaign: 'winter2024'
  }
});

if (subscription.success) {
  console.log('Subscription created:', subscription.data?.id);
}

Get Subscriptions

const subscriptions = await subscriptionClient.getSubscriptions({
  customerId: 'customer-uuid',
  status: 'active',
  page: 1,
  pageSize: 20,
  sortBy: 'createdAt',
  sortOrder: 'desc'
});

if (subscriptions.success) {
  subscriptions.data?.items.forEach(sub => {
    console.log(`${sub.plan.name}: ${sub.status} - Next billing: ${sub.nextBillingDate}`);
  });
}

Cancel Subscription

// Cancel at end of billing period
const cancelled = await subscriptionClient.cancelSubscription('subscription-uuid', false);

// Cancel immediately
const cancelledNow = await subscriptionClient.cancelSubscription('subscription-uuid', true);

Change Plan

const upgraded = await subscriptionClient.changeSubscriptionPlan(
  'subscription-uuid',
  'premium-plan-uuid',
  false // Apply at next billing cycle
);

Plan Management

Create Plan

const plan = await subscriptionClient.createPlan({
  name: 'Premium Plan',
  description: 'Our premium offering with advanced features',
  type: 'premium',
  price: 99.99,
  currency: 'USD',
  billingInterval: 'monthly',
  features: [
    {
      featureId: 'feature-1-uuid',
      limit: 10000,
      enabled: true
    },
    {
      featureId: 'feature-2-uuid',
      enabled: true
    }
  ],
  isActive: true
});

Get Available Plans

const plans = await subscriptionClient.getAvailablePlans('customer-uuid');

if (plans.success) {
  plans.data?.forEach(plan => {
    console.log(`${plan.name}: ${plan.price} ${plan.currency}/${plan.billingInterval}`);
  });
}

Feature Management

Create Feature

const feature = await subscriptionClient.createFeature({
  name: 'API Requests',
  key: 'api_requests',
  description: 'Number of API requests per month',
  type: 'numeric',
  defaultValue: 1000,
  category: 'api',
  isActive: true
});

Get Features

const features = await subscriptionClient.getFeatures({
  type: 'numeric',
  category: 'api',
  isActive: true,
  page: 1,
  pageSize: 50
});

Check Feature Access

const access = await subscriptionClient.checkFeatureAccess(
  'subscription-uuid',
  'api_requests'
);

if (access.success) {
  console.log('Has access:', access.data?.hasAccess);
  console.log('Current usage:', access.data?.currentUsage);
  console.log('Limit:', access.data?.limit);
  console.log('Remaining:', access.data?.remainingUsage);
}

Usage Tracking

Record Usage

const usage = await subscriptionClient.recordUsage({
  subscriptionId: 'subscription-uuid',
  featureKey: 'api_requests',
  usage: 100,
  timestamp: new Date().toISOString(),
  metadata: {
    endpoint: '/api/users',
    method: 'GET'
  }
});

Get Usage Summary

const summary = await subscriptionClient.getUsageSummary(
  'subscription-uuid',
  '2024-01' // Optional period (YYYY-MM)
);

if (summary.success) {
  summary.data?.forEach(feature => {
    console.log(`${feature.featureName}: ${feature.currentUsage}/${feature.limit}`);
    console.log(`Usage: ${feature.percentage}% - Over limit: ${feature.isOverLimit}`);
  });
}

Get Feature Usage

const featureUsage = await subscriptionClient.getFeatureUsage(
  'subscription-uuid',
  'api_requests',
  '2024-01'
);

if (featureUsage.success) {
  console.log('Current usage:', featureUsage.data?.currentUsage);
  console.log('Limit:', featureUsage.data?.limit);
  console.log('Usage history:', featureUsage.data?.history);
}

Customer Methods

Get Customer Subscriptions

const customerSubs = await subscriptionClient.getCustomerSubscriptions('customer-uuid');

if (customerSubs.success) {
  customerSubs.data?.forEach(sub => {
    console.log(`Plan: ${sub.plan.name}, Status: ${sub.status}`);
  });
}

Get Active Subscription

const activeSub = await subscriptionClient.getCustomerActiveSubscription('customer-uuid');

if (activeSub.success && activeSub.data) {
  console.log('Active plan:', activeSub.data.plan.name);
  console.log('Next billing:', activeSub.data.nextBillingDate);
}

Analytics

Subscription Summary

const summary = await subscriptionClient.getSubscriptionSummary(
  '2024-01-01',
  '2024-12-31'
);

if (summary.success) {
  console.log('Total subscriptions:', summary.data?.totalSubscriptions);
  console.log('Active subscriptions:', summary.data?.activeSubscriptions);
  console.log('Total revenue:', summary.data?.totalRevenue);
  console.log('Monthly revenue:', summary.data?.monthlyRevenue);
}

Metrics by Plan

const planMetrics = await subscriptionClient.getSubscriptionMetricsByPlan(
  '2024-01-01',
  '2024-12-31'
);

if (planMetrics.success) {
  planMetrics.data?.forEach(plan => {
    console.log(`${plan.planName}: ${plan.subscriptions} subs, ${plan.revenue} revenue`);
    console.log(`Churn rate: ${plan.churnRate}%`);
  });
}

Feature Usage Analytics

const usageAnalytics = await subscriptionClient.getFeatureUsageAnalytics(
  'api_requests',
  '2024-01-01',
  '2024-12-31'
);

if (usageAnalytics.success) {
  usageAnalytics.data?.forEach(feature => {
    console.log(`${feature.featureName}: ${feature.totalUsage} total usage`);
    console.log(`${feature.uniqueUsers} unique users, avg: ${feature.averageUsage}`);
  });
}

Error Handling

All methods return a standardized response:

const response = await subscriptionClient.createSubscription(subscriptionData);

if (!response.success) {
  console.error('Subscription creation failed:', response.error?.message);
  
  switch (response.error?.code) {
    case 'PLAN_NOT_FOUND':
      // Handle plan not found
      break;
    case 'CUSTOMER_NOT_FOUND':
      // Handle customer not found
      break;
    case 'USAGE_LIMIT_EXCEEDED':
      // Handle usage limit exceeded
      break;
  }
}

Types and Enums

Subscription Status

enum SubscriptionStatus {
  Active = 'active',
  Inactive = 'inactive',
  Cancelled = 'cancelled',
  Suspended = 'suspended',
  PendingCancellation = 'pending_cancellation'
}

Plan Types

enum PlanType {
  Free = 'free',
  Basic = 'basic',
  Premium = 'premium',
  Enterprise = 'enterprise',
  Custom = 'custom'
}

Billing Intervals

enum BillingInterval {
  Monthly = 'monthly',
  Yearly = 'yearly',
  Quarterly = 'quarterly',
  Weekly = 'weekly'
}

Feature Types

enum FeatureType {
  Boolean = 'boolean',  // On/off features
  Numeric = 'numeric',  // Usage-based features with limits
  Text = 'text'         // Text-based configuration
}

Health Check

const health = await subscriptionClient.getHealth();

if (health.success) {
  console.log('Service status:', health.data?.status);
  console.log('Dependencies:', health.data?.dependencies);
}

License

MIT