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

@nasca/sdk

v0.2.4

Published

Per-user AI cost tracking and rate limiting for indie developers

Readme

@nasca/sdk

AI monetisation infrastructure for indie developers. Track per-user AI spend, enforce daily/weekly/monthly limits, sell credit packs, and redirect blocked users to Stripe checkout — all in one SDK.

Works with OpenAI, Anthropic Claude, and any OpenRouter model.

Installation

npm install @nasca/sdk

Quick start

1. Initialise once per project

import { Nasca } from '@nasca/sdk'

const nasca = new Nasca({
  accountId: process.env.NASCA_ACCOUNT_ID!,
  workerUrl: process.env.NASCA_WORKER_URL!,
  apiKey: process.env.NASCA_API_KEY!,

  // Return the current end-user's ID from your request context
  getUserId: (ctx) => ctx.user.id,

  // Optional: map users to tiers you've defined in the dashboard
  getUserTier: (ctx) => ctx.user.plan, // e.g. 'free', 'pro'

  // Optional: enables checkout_url on NascaBlockedError
  successUrl: 'https://yourapp.com/credits/success',
  cancelUrl:  'https://yourapp.com/credits/cancel',
})

2. Wrap your AI function once

import OpenAI from 'openai'

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })

const callAI = nasca.wrap(
  openai.chat.completions.create.bind(openai.chat.completions)
)

Works identically for Anthropic:

import Anthropic from '@anthropic-ai/sdk'

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })

const callAI = nasca.wrap(
  anthropic.messages.create.bind(anthropic.messages)
)

And for OpenRouter (via the OpenAI SDK):

const openai = new OpenAI({
  apiKey: process.env.OPENROUTER_API_KEY,
  baseURL: 'https://openrouter.ai/api/v1',
})

const callAI = nasca.wrap(
  openai.chat.completions.create.bind(openai.chat.completions)
)

3. Use it identically everywhere

const result = await callAI(
  { model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }] },
  ctx  // your request context — getUserId extracts the user from here
)

Handling blocked users

When a user exceeds their limit and has no credits, the SDK throws NascaBlockedError:

import { NascaBlockedError } from '@nasca/sdk'

try {
  const result = await callAI({ model: 'gpt-4o', messages }, ctx)
} catch (e) {
  if (e instanceof NascaBlockedError) {
    return res.status(402).json({
      message: e.upgrade_message,   // your custom message from the dashboard
      checkout_url: e.checkout_url, // direct link to Stripe checkout (if configured)
    })
  }
  throw e
}

NascaBlockedError fields:

| Field | Type | Description | |---|---|---| | upgrade_message | string | The message you configured in the dashboard for this tier | | remaining_budget | number | Always 0 when blocked | | checkout_url | string \| null | Stripe checkout URL — populated when successUrl/cancelUrl are configured | | credit_balance_display | number \| null | Remaining credit balance in display dollars (always null when blocked — use getUsage()) | | credit_percent | number \| null | Remaining credit percentage (always null when blocked — use getUsage()) |

Credit packs and getUsage()

When a user has purchased credits, the SDK allows them through even if their tier limits are exceeded. Credits deplete as they make AI calls. Once credits run out, users see NascaBlockedError with a checkout_url to buy more.

Fetch the full usage snapshot to display progress to your users:

const usage = await nasca.getUsage(ctx)

// Tier allowance
console.log(usage.monthly_spend)    // 1.40
console.log(usage.monthly_limit)    // 2.00
console.log(usage.monthly_percent)  // 70

// Daily/weekly limits (if set on the user's tier)
console.log(usage.daily_spend)      // 0.04
console.log(usage.daily_limit)      // 0.10

// Credit balance
console.log(usage.credit_balance_display)  // 3.20  (display dollars)
console.log(usage.credit_percent)          // 64    (% of pack remaining)

// State
console.log(usage.is_blocked)   // false
console.log(usage.resets_at)    // "2026-07-01T00:00:00.000Z"

getUsage() calls the worker directly and throws if it is unreachable.

Streaming

Streaming works without changes. The SDK injects stream_options: { include_usage: true } for OpenAI automatically, and accumulates usage events for Anthropic across message_start and message_delta. Usage is logged after the stream closes.

const stream = await callAI({ model: 'gpt-4o', messages, stream: true }, ctx)

for await (const chunk of stream) {
  // identical to the raw OpenAI stream
}

How it works

  1. First call per user — registers the user against your account (once per process lifecycle, deduplicated).
  2. Before every AI call/intercept checks Redis: blocked flag → daily limit → weekly limit → monthly limit. Each limit falls back to the user's credit balance before blocking. Under 50ms round trip. Fails open if the worker is unreachable.
  3. After every AI call/log fires in the background (fire-and-forget). Increments daily, weekly, and monthly spend counters. Deducts from credits if this call was credit-covered. Sets the blocked flag if a limit is permanently exhausted.

Nasca never estimates token counts. All cost figures come from the usage object in the provider response.

Environment variables

NASCA_ACCOUNT_ID=   # your account UUID from the Nasca dashboard
NASCA_WORKER_URL=   # your Cloudflare Worker URL
NASCA_API_KEY=      # your nsk_... API key from the dashboard

Auth provider snippets

// Supabase Auth
getUserId: (ctx) => ctx.user.id

// Clerk
getUserId: (ctx) => ctx.auth.userId

// NextAuth
getUserId: (ctx) => ctx.session.user.id

getUserTier is optional. Return a tier name matching one you defined in the Nasca dashboard (e.g. "free", "pro"). New users without a matching tier are placed on your account's default tier.