API Reference

SDK Reference

Complete API documentation for the @billai/sdk package.

Installation

Terminal
npm install @billai/sdk
# or
yarn add @billai/sdk
# or
pnpm add @billai/sdk

AccessControl

The main class for checking user access to features. Create one instance and reuse it throughout your application.

Constructor

Signature
new AccessControl(config: AccessControlConfig)

AccessControlConfig

apiKey
string
Your BillAI API key. Get this from the dashboard.
appId
string
Your application ID (e.g., 'app_xxx').
baseUrl?
string
API base URL. Default: 'https://api.billai.dev'
timeout?
number
Request timeout in milliseconds. Default: 5000
maxRetries?
number
Maximum retry attempts for failed requests. Default: 3
debug?
boolean
Enable debug logging. Default: false (or true if DEBUG env is set)
Example
import { AccessControl } from '@billai/sdk';

const access = new AccessControl({
  apiKey: process.env.BILLAI_API_KEY!,
  appId: process.env.BILLAI_APP_ID!,
  timeout: 3000,
  maxRetries: 2,
  debug: process.env.NODE_ENV === 'development',
});

check()

Check if a user has access to a specific feature. Optionally increment usage for usage-based features.

Signature
async check(
  userId: string,
  feature: string,
  options?: CheckOptions
): Promise<CheckResult>

Parameters

userId
string
Unique identifier for the end user in your system.
feature
string
The feature identifier to check access for.
options?
CheckOptions
Optional parameters for the check.

CheckOptions

increment?
number
For usage-based features, increment usage by this amount.
metadata?
Record<string, unknown>
Additional metadata to include with the request.

CheckResult

granted
boolean
Whether access is granted.
upgradeUrl?
string
URL for upgrading. Only present when access is denied.
reason?
string
Human-readable reason for the result.
usage?
number
Current usage count (for usage-based features).
limit?
number
Usage limit (for usage-based features).

Examples

Boolean feature check

const result = await access.check('user_123', 'premium_export');

if (result.granted) {
  // User has access
  await performExport();
} else {
  // Show upgrade prompt
  console.log('Upgrade at:', result.upgradeUrl);
}

Usage-based feature with increment

const result = await access.check('user_123', 'api_calls', {
  increment: 1,
});

console.log(`API calls: ${result.usage}/${result.limit}`);

if (!result.granted) {
  throw new Error('API limit exceeded');
}

Check without incrementing

// Just check remaining usage without counting
const result = await access.check('user_123', 'api_calls');

console.log(`Remaining: ${(result.limit || 0) - (result.usage || 0)}`);

Error Handling

The SDK exports several error classes for handling different error scenarios.

BillAIErrorBase error class

Base class for all SDK errors. Contains code,statusCode, and retryable properties.

InvalidApiKeyErrorcode: INVALID_API_KEY

Thrown when the API key is invalid or missing.

InvalidAppIdErrorcode: INVALID_APP_ID

Thrown when the app ID is invalid or the app doesn't exist.

RateLimitErrorcode: RATE_LIMITED

Thrown when rate limit is exceeded. Contains retryAfter property.

NetworkErrorcode: NETWORK_ERROR

Thrown when a network error occurs (e.g., no internet connection).

TimeoutErrorcode: TIMEOUT

Thrown when a request times out.

ServerErrorcode: SERVER_ERROR

Thrown when the server returns a 5xx error.

Error Handling Example

import { 
  AccessControl, 
  InvalidApiKeyError,
  RateLimitError,
  NetworkError,
} from '@billai/sdk';

try {
  const result = await access.check(userId, feature);
  // Handle result
} catch (error) {
  if (error instanceof InvalidApiKeyError) {
    console.error('Invalid API key - check your configuration');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfter}s`);
  } else if (error instanceof NetworkError) {
    console.error('Network error - check your connection');
  } else {
    console.error('Unexpected error:', error);
  }
}

Fail-Open Design

By default, the SDK is designed to fail open. If an unexpected error occurs during an access check, consider allowing access rather than blocking users due to service issues.

TypeScript Types

All types are exported from the package for use in TypeScript projects.

import type {
  AccessControlConfig,
  CheckOptions,
  CheckResult,
  ErrorCode,
} from '@billai/sdk';

// ErrorCode type
type ErrorCode =
  | 'INVALID_API_KEY'
  | 'INVALID_APP_ID'
  | 'RATE_LIMITED'
  | 'SERVER_ERROR'
  | 'NETWORK_ERROR'
  | 'TIMEOUT'
  | 'UNKNOWN';

Environment Variables

BILLAI_API_KEY
string
Your API key for authentication.
BILLAI_APP_ID
string
Your application ID.
DEBUG?
boolean
Set to enable debug logging in the SDK.
.env.example
# BillAI Configuration
BILLAI_API_KEY=sk_live_xxxxxxxxxxxx
BILLAI_APP_ID=app_xxxxxxxxxxxx

# Optional: Enable debug logging
DEBUG=true