Skip to main content

JavaScript API

bursar for TypeScript/JavaScript is published as @zonastery/bursar on npm. Requires Node.js 18+.

Installation

npm install @zonastery/bursar

# PostgreSQL store (optional)
npm install pg

# YAML pricing loading (optional)
npm install js-yaml

Core Classes

Class / TypeExported fromDescription
PricingEngine@zonastery/bursarPure calculation layer — no DB dependency
CreditManager@zonastery/bursarOrchestrates credit lifecycle
HttpxSupabaseStore@zonastery/bursarSupabase-backed store (native fetch, no extra deps)
PostgresStore@zonastery/bursarDirect PostgreSQL via pg
MemoryStore@zonastery/bursar/nodeIn-memory store for testing (Node.js only)
CreditEventEmitter@zonastery/bursarTyped pub/sub for credit lifecycle events
UsageMetrics@zonastery/bursarInput interface for calculate() / deduct()
CostBreakdown@zonastery/bursarStructured cost breakdown (all fields Decimal)
CreditManagerOptions@zonastery/bursarConstructor options (policy, thresholds, TTL, …)
PricingConfigData@zonastery/bursarSchema for a pricing config dict
DeductionResult@zonastery/bursarReturn type of deduct() / settle()
LeaseResult@zonastery/bursarReturn type of reserve() / renew()
BalanceResult@zonastery/bursarReturn type of getBalance()
CanAffordResult@zonastery/bursarReturn type of canAfford() — includes .spendable (effective spending power)
TierBalancesResult@zonastery/bursarReturn type of getCreditTiers() — per-tier balance breakdown
TierDefinition@zonastery/bursarCredit tier definition (priority, expiry, default/overdraft flags)
LowBalanceConfig@zonastery/bursarCreditManagerOptions.lowBalance shape: { thresholds, onTrigger }
CapabilityNotSupportedError@zonastery/bursarThrown by a store's default implementation of an optional capability (analytics, transaction listing, teams) that wasn't overridden

All money values (balances, amounts, costs) are Decimal from decimal.js, never binary number.

Quick Example

import { CreditManager, PostgresStore } from "@zonastery/bursar";
// For tests / local dev, use MemoryStore from the Node subpath:
import { MemoryStore } from "@zonastery/bursar/node";

const store = new MemoryStore();
const manager = new CreditManager(store);

await manager.publishPricingFromDict({
models: { "gpt-4": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)" },
});

await manager.addCredits("user_abc", 1000);
const result = await manager.deduct(
"user_abc",
{ model: "gpt-4", inputTokens: 500, outputTokens: 200 },
"idempotency-key-123",
);
// result.amount is a Decimal — use .toString() or .toNumber()
console.log(`Deducted ${result.amount.toString()} credits`);