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

@subtrak/angular

v2.0.6

Published

Angular SDK for Subtrak - Subscription billing and entitlement management (IN DEVELOPMENT)

Readme

@subtrak/angular

npm version Angular TypeScript License: MIT

IMPORTANT: This is a part of a developer-first SaaS Billing software that is still IN DEVELOPMENT. Send an email to [email protected] of you are interested in trying it out.

Official Angular SDK for Subtrak - The complete subscription billing and entitlement management solution for your SaaS application.

🚀 Quick Start

npm install @subtrak/angular

Configuration

// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideSubtrak, authInterceptor, caseTransformInterceptor } from '@subtrak/angular';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(
      withInterceptors([authInterceptor, caseTransformInterceptor])
    ),
    provideSubtrak({
      publicKey: 'pk_test_your_key_here',
      apiUrl: 'https://api.subtrak.com/v5'
    })
  ]
});

Basic Usage

import { Component } from '@angular/core';
import { SubscriptionStatusComponent } from '@subtrak/angular';

@Component({
  selector: 'app-billing',
  standalone: true,
  imports: [SubscriptionStatusComponent],
  template: `
    <subtrak-subscription-status
      [customerId]="customerId"
      [showEntitlements]="true"
      [showUsageMeters]="true"
      (upgradeClicked)="onUpgrade()">
    </subtrak-subscription-status>
  `
})
export class BillingComponent {
  customerId = 'cus_123';

  onUpgrade() {
    // Handle upgrade action
  }
}

✨ Features

🎨 6 Pre-Built Components

  • SubscriptionStatusComponent - Display subscription status with management actions
  • EntitlementDisplayComponent - Auto-format entitlement values by type
  • UsageMeterComponent - Real-time usage tracking with progress bars
  • PaymentProviderCardComponent - Multi-provider payment forms (Stripe + Paymob)
  • PricingTableComponent - Feature comparison and plan selection
  • BillingPortalComponent - All-in-one billing management widget

⚡ 5 Complete Services

  • SubscriptionsService - Subscription lifecycle management
  • EntitlementsService - Feature access and limit checking
  • UsageService - Metered usage tracking
  • InvoicesService - Invoice history and PDF downloads
  • PaymentMethodsService - Payment method management

🛡️ Additional Features

  • 2 Directives - *subFeatureGate, *subQuotaGuard for feature gating
  • 1 Route Guard - EntitlementGuard for route protection
  • 3 Pipes - Format entitlement values in templates
  • Multi-Provider Payments - Automatic Stripe/Paymob detection
  • TypeScript - Full type safety with 350+ type definitions
  • Standalone Components - Angular 17+ modern architecture
  • RxJS - Reactive data streams

📚 Component Examples

Subscription Status

<subtrak-subscription-status
  [customerId]="customerId"
  [showEntitlements]="true"
  [showUsageMeters]="true"
  [showUpgradeButton]="true"
  (upgradeClicked)="onUpgrade()">
</subtrak-subscription-status>

Usage Meter

<subtrak-usage-meter
  [meterId]="'api_calls'"
  [customerId]="customerId"
  [limitCode]="'max_api_calls'"
  [showOverageWarning]="true"
  [warningThreshold]="0.9">
</subtrak-usage-meter>

Payment Provider Card

<!-- Auto-detects country from customer data -->
<subtrak-payment-provider-card
  [customerId]="customerId"
  (paymentMethodAdded)="onPaymentMethodAdded($event)"
  (error)="onPaymentError($event)">
</subtrak-payment-provider-card>

<!-- Or specify country explicitly -->
<subtrak-payment-provider-card
  [customerId]="customerId"
  [countryCode]="'US'"
  (paymentMethodAdded)="onPaymentMethodAdded($event)">
</subtrak-payment-provider-card>

Pricing Table

<!-- Auto-detects country from customer data -->
<subtrak-pricing-table
  [customerId]="customerId"
  [currentPlanId]="currentPlan?.id"
  (planSelected)="onPlanSelected($event)">
</subtrak-pricing-table>

<!-- Or specify country explicitly -->
<subtrak-pricing-table
  [countryCode]="'US'"
  [highlightEntitlements]="['premium_analytics', 'priority_support']"
  (planSelected)="onPlanSelected($event)">
</subtrak-pricing-table>

Billing Portal (All-in-One)

<!-- Complete billing management in one component -->
<subtrak-billing-portal
  [customerId]="customerId">
</subtrak-billing-portal>

🔧 Service Examples

Subscriptions

import { SubscriptionsService } from '@subtrak/angular';

constructor(private subscriptions: SubscriptionsService) {}

// Get current subscription
this.subscriptions.getCurrentSubscription('cus_123').subscribe(subscription => {
  console.log('Current plan:', subscription.price.nickname);
});

// Create subscription
this.subscriptions.createSubscription({
  customerId: 'cus_123',
  priceId: 'price_456',
  quantity: 1
}).subscribe();

// Upgrade subscription
this.subscriptions.upgradeSubscription('sub_789', 'price_premium').subscribe();

Entitlements

import { EntitlementsService, EntitlementChecker } from '@subtrak/angular';

constructor(private entitlements: EntitlementsService) {}

// Get all entitlements
this.entitlements.getEntitlements('cus_123').subscribe(entitlements => {
  const checker = new EntitlementChecker(entitlements);

  // Check BOOLEAN features
  if (checker.hasFeature('premium_analytics')) {
    // Show premium analytics
  }

  // Check NUMERIC limits
  const maxProjects = checker.getLimit('max_projects'); // 25
  const remaining = checker.getRemainingQuota('max_projects', currentCount);

  // Check ENUM values
  const supportLevel = checker.getEnumValue('support_level'); // 'priority'
});

Usage Tracking

import { UsageService } from '@subtrak/angular';

constructor(private usage: UsageService) {}

// Record usage event
this.usage.recordUsage({
  meterId: 'meter_api_calls',
  customerId: 'cus_123',
  eventName: 'api_call',
  properties: { endpoint: '/api/data', method: 'GET' },
  value: 1
}).subscribe();

// Get current usage
this.usage.getCurrentUsage('meter_api_calls', 'cus_123').subscribe(summary => {
  console.log('Total usage:', summary.totalUsage);
  console.log('Billable units:', summary.billableUnits);
});

Invoices

import { InvoicesService } from '@subtrak/angular';

constructor(private invoices: InvoicesService) {}

// List invoices
this.invoices.listInvoices({
  customerId: 'cus_123',
  status: InvoiceStatus.PAID
}).subscribe(response => {
  console.log('Invoices:', response.data);
});

// Download PDF
this.invoices.downloadInvoicePdf('inv_123').subscribe(blob => {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'invoice.pdf';
  a.click();
});

🎯 Directives

Feature Gate

import { FeatureGateDirective } from '@subtrak/angular';

// Show/hide based on BOOLEAN entitlements
<div *subFeatureGate="'premium_analytics'; customerId: customerId; else: upgrade">
  <app-premium-analytics></app-premium-analytics>
</div>

<ng-template #upgrade>
  <button (click)="showUpgradeModal()">Upgrade to Pro</button>
</ng-template>

Quota Guard

import { QuotaGuardDirective } from '@subtrak/angular';

// Show/hide based on NUMERIC limits
<button
  *subQuotaGuard="'max_projects'; current: projectCount; customerId: customerId; else: limitReached"
  (click)="createProject()">
  Create New Project
</button>

<ng-template #limitReached>
  <p>Project limit reached. Upgrade to create more.</p>
</ng-template>

🔒 Route Guards

import { Routes } from '@angular/router';
import { EntitlementGuard } from '@subtrak/angular';

export const routes: Routes = [
  {
    path: 'analytics',
    component: AnalyticsComponent,
    canActivate: [EntitlementGuard],
    data: {
      entitlement: 'premium_analytics',
      type: 'BOOLEAN',
      redirectTo: '/upgrade'
    }
  }
];

🌍 Multi-Provider Payments

The SDK automatically detects and uses the correct payment provider based on customer location:

  • Stripe - Global countries (US, CA, GB, EU, etc.)
  • Paymob - MENA region (Egypt, KSA, UAE, Oman, Pakistan)
// Automatic provider detection based on country
<subtrak-payment-provider-card
  [customerId]="customerId"
  [countryCode]="'EG'"  // Automatically uses Paymob
  (paymentMethodAdded)="onSuccess($event)">
</subtrak-payment-provider-card>

📦 Installation & Setup

Step 1: Install Package

npm install @subtrak/angular

Step 2: Configure Providers

// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideSubtrak, authInterceptor, caseTransformInterceptor } from '@subtrak/angular';

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes),
    provideHttpClient(
      withInterceptors([
        authInterceptor,
        caseTransformInterceptor
      ])
    ),
    provideSubtrak({
      publicKey: 'pk_test_your_key_here',  // Your Subtrak public key
      apiUrl: 'https://api.subtrak.com/v5' // Your API URL
    })
  ]
}).catch(err => console.error(err));

Step 3: Import Components

import { Component } from '@angular/core';
import {
  SubscriptionStatusComponent,
  PricingTableComponent,
  BillingPortalComponent
} from '@subtrak/angular';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    SubscriptionStatusComponent,
    PricingTableComponent,
    BillingPortalComponent
  ],
  template: `
    <subtrak-billing-portal [customerId]="customerId">
    </subtrak-billing-portal>
  `
})
export class AppComponent {
  customerId = 'cus_123';
}

🎨 Entitlement Types

Subtrak supports 4 types of entitlements:

BOOLEAN - Feature Flags

{ key: 'premium_analytics', type: 'BOOLEAN', value: true }
// Display: ✓ Enabled or ✗ Disabled

NUMERIC - Limits & Quotas

{ key: 'max_projects', type: 'NUMERIC', value: 25 }
// Display: 25 or 25 Projects

ENUM - Selection Values

{ key: 'support_level', type: 'ENUM', value: 'priority' }
// Display: Priority Support

METERED - Usage-Based

{ key: 'api_calls', type: 'METERED', currentUsage: 8500, limit: 10000 }
// Display: 8,500 / 10,000 (85%)

🔧 Configuration Options

interface SubtrakConfig {
  // API Authentication (required)
  publicKey?: string;   // For frontend apps
  secretKey?: string;   // For backend apps (use publicKey in browser)

  // API Configuration
  apiUrl?: string;      // Default: staging API
  timeout?: number;     // Request timeout (default: 30000ms)
  maxRetries?: number;  // Max retry attempts (default: 3)

  // Customer Context
  customerId?: string;  // Pre-set customer ID for all requests

  // Debugging
  debug?: boolean;      // Enable debug logging (default: false)
}

🌟 Angular 19.2 Support

This package is fully compatible with Angular 19.2:

  • ✅ Angular 19.2.x (recommended)
  • ✅ Angular 18.x
  • ✅ Angular 17.x
  • ✅ TypeScript 5.6
  • ✅ RxJS 7.8 & 8.x
  • ✅ Zone.js 0.15
  • ✅ Standalone components
  • ✅ Functional interceptors
  • ✅ Modern build tools

📊 Bundle Size

  • Unpacked: ~850 KB
  • Gzipped: ~120 KB
  • Tree-shakeable: Import only what you need

🔐 Error Handling

import { ApiError, ValidationError, AuthError, NotFoundError } from '@subtrak/angular';

this.subscriptions.createSubscription({...}).subscribe({
  next: (subscription) => {
    // Success
  },
  error: (error) => {
    if (error instanceof ValidationError) {
      console.error('Validation failed:', error.details);
    } else if (error instanceof AuthError) {
      this.router.navigate(['/login']);
    } else if (error instanceof NotFoundError) {
      console.error('Resource not found');
    }
  }
});

📖 Documentation

🐛 Issues & Support

Found a bug or need help?

📝 License

MIT License - see LICENSE file for details.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

🔄 Changelog

See CHANGELOG.md for a list of changes.

🏷️ Version

Current version: 2.0.0

  • Full Angular 19.2 support
  • Backward compatible with Angular 17 & 18
  • Zero breaking changes from v1.x

Made with ❤️ by the Subtrak team

For more information, visit subtrak.com