TypeScript SDK
Getting Started

HiveForge SDK

The HiveForge TypeScript SDK provides a complete interface for hosted deployments to interact with HiveForge platform services, including entitlement management, AI proxy, billing, email, vector search, webhooks, and more.

Installation

npm install @producthacker/hiveforge-sdk

Environment Variables

Set these in your .env file or hosting environment:

HIVEFORGE_DEPLOYMENT_ID=d9f2a1b4-7c3e-4f8a-b5d6-1e2f3a4b5c6d
HIVEFORGE_DEPLOYMENT_SECRET=sk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
HIVEFORGE_API_URL=https://api.hiveforge.dev/api/v1   # Optional, this is the default
VariableRequiredDescription
HIVEFORGE_DEPLOYMENT_IDYesYour deployment's unique identifier from the HiveForge dashboard
HIVEFORGE_DEPLOYMENT_SECRETYesSecret key for authenticating API requests
HIVEFORGE_API_URLNoAPI base URL. Defaults to https://api.hiveforge.dev/api/v1

Client Initialization

Manual Configuration

import { HiveForgeClient } from '@producthacker/hiveforge-sdk';
 
const hiveforge = new HiveForgeClient({
  deploymentId: process.env.HIVEFORGE_DEPLOYMENT_ID!,
  deploymentSecret: process.env.HIVEFORGE_DEPLOYMENT_SECRET!,
  apiUrl: process.env.HIVEFORGE_API_URL,  // optional
  debug: false,                            // optional, enables console logging
});
 
// Must be called before using any features
await hiveforge.initialize();

From Environment Variables

import { createHiveForgeClient } from '@producthacker/hiveforge-sdk';
 
// Reads HIVEFORGE_DEPLOYMENT_ID and HIVEFORGE_DEPLOYMENT_SECRET from env
const hiveforge = createHiveForgeClient({
  debug: process.env.NODE_ENV === 'development',
});
 
await hiveforge.initialize();
⚠️

You must call initialize() before using any SDK features. This fetches your deployment's entitlements from the server and starts background refresh.

Configuration Options

The HiveForgeConfig interface accepts the following options:

ParameterTypeRequiredDefaultDescription
deploymentIdstringYes--Deployment ID from HiveForge dashboard
deploymentSecretstringYes--Deployment secret key
apiUrlstringNohttps://api.hiveforge.dev/api/v1API base URL
debugbooleanNofalseEnable debug logging to console
fetchtypeof fetchNoglobalThis.fetchCustom fetch implementation (useful for testing)

API Modules

After initialization, the client exposes these proxy modules:

ModuleAccessDescription
aihiveforge.aiChat completions, streaming, embeddings
billinghiveforge.billingStripe checkout sessions, customer portal, prices
creditshiveforge.creditsCredit balance, usage, packs, costs
emailhiveforge.emailTransactional email delivery
vectorshiveforge.vectorsSemantic vector search and storage
webhookshiveforge.webhooksReliable outbound webhook delivery

Entitlement Methods

These methods are available directly on the HiveForgeClient instance after initialization.

isEnabled(feature)

Check if a feature flag is enabled for the current deployment.

if (hiveforge.isEnabled('ai_enabled')) {
  // AI features are available
}
 
if (hiveforge.isEnabled('billing_enabled')) {
  // Billing features are available
}

Parameters:

NameTypeDescription
featurekeyof FeatureFlagsFeature flag name to check

Returns: boolean

getStatus()

Get the current subscription status.

const status = hiveforge.getStatus();
// 'active' | 'trialing' | 'past_due' | 'grace_period' | 'suspended' | 'canceled'

Returns: SubscriptionStatus

getTier()

Get the current subscription tier.

const tier = hiveforge.getTier();
// 'sandbox' | 'trial' | 'launch' | 'growth' | 'enterprise'

Returns: string

getMessage()

Get the user-facing message from entitlements (e.g., trial expiration warnings).

const message = hiveforge.getMessage();
// "Trial expires in 3 days" or null

Returns: string | null

getEntitlements()

Get the full entitlements object.

const entitlements = hiveforge.getEntitlements();
if (entitlements) {
  console.log(entitlements.tier);
  console.log(entitlements.features.ai_monthly_limit);
  console.log(entitlements.quotas);
}

Returns: Entitlements | null

getQuota(resource)

Get quota information for a specific resource.

const aiQuota = hiveforge.getQuota('ai_tokens');
if (aiQuota) {
  console.log(`Used: ${aiQuota.used}, Limit: ${aiQuota.limit}, Remaining: ${aiQuota.remaining}`);
}

Returns: QuotaInfo | null

isSuspended()

Check if the deployment is in suspended state.

if (hiveforge.isSuspended()) {
  // Show suspension UI
}

Returns: boolean

isInGracePeriod()

Check if the deployment is in grace period.

if (hiveforge.isInGracePeriod()) {
  // Show grace period warning banner
}

Returns: boolean

refreshEntitlements()

Manually refresh entitlements from the server.

const entitlements = await hiveforge.refreshEntitlements();

Returns: Promise<Entitlements>

shutdown()

Stop background entitlement refresh and clean up.

hiveforge.shutdown();

Event System

Subscribe to SDK events for real-time updates.

// Entitlements refreshed
const unsub1 = hiveforge.on('entitlements:updated', (entitlements) => {
  console.log('Tier:', entitlements.tier);
  console.log('Status:', entitlements.status);
});
 
// Subscription status changed
const unsub2 = hiveforge.on('status:changed', ({ previous, current }) => {
  console.log(`Status changed: ${previous} -> ${current}`);
});
 
// Quota approaching limit (80% threshold)
const unsub3 = hiveforge.on('quota:warning', ({ resource, used, limit }) => {
  console.warn(`${resource} at ${Math.round((used / limit) * 100)}% usage`);
});
 
// Quota exceeded
const unsub4 = hiveforge.on('quota:exceeded', ({ resource, used, limit }) => {
  console.error(`${resource} quota exceeded: ${used}/${limit}`);
});
 
// Entitlement refresh failed
const unsub5 = hiveforge.on('entitlements:error', (error) => {
  console.error('Failed to refresh entitlements:', error.message);
});
 
// Unsubscribe when done
unsub1();
unsub2();

Event Reference

EventPayloadDescription
entitlements:updatedEntitlementsEntitlements successfully refreshed
entitlements:errorErrorEntitlement refresh failed
quota:warning{ resource, used, limit }Resource usage above 80%
quota:exceeded{ resource, used, limit }Resource usage at or above limit
status:changed{ previous, current }Subscription status changed

Feature Flags Reference

FlagTypeDescription
ai_enabledbooleanWhether AI proxy is available
ai_monthly_limitnumber | nullMonthly token limit (null = unlimited)
billing_enabledbooleanWhether billing proxy is available
custom_domainbooleanCustom domain support
white_labelbooleanWhite labeling enabled
api_rate_limitnumber | nullAPI rate limit (null = unlimited)
support_levelstringSupport tier: community, email, priority, or dedicated

Subscription Statuses

StatusDescription
activeSubscription is active and in good standing
trialingCurrently in trial period
past_duePayment failed, system is retrying
grace_periodSubscription lapsed, features limited temporarily
suspendedAccount fully suspended, features disabled
canceledSubscription canceled

TypeScript Types

All types are exported for use in your application:

import type {
  HiveForgeConfig,
  Entitlements,
  SubscriptionStatus,
  FeatureFlags,
  QuotaInfo,
  ChatMessage,
  AICompletionOptions,
  AICompletionResponse,
  AIStreamOptions,
  AIStreamChunk,
  AIEmbeddingOptions,
  AIEmbeddingResponse,
  AIQuotaResponse,
  CheckoutOptions,
  CheckoutResponse,
  PortalOptions,
  PortalResponse,
  HiveForgeEvent,
  HiveForgeEventData,
  HiveForgeEventHandler,
} from '@producthacker/hiveforge-sdk';

Server-Side Usage (Next.js)

// lib/hiveforge.ts
import { HiveForgeClient } from '@producthacker/hiveforge-sdk';
 
export const hiveforge = new HiveForgeClient({
  deploymentId: process.env.HIVEFORGE_DEPLOYMENT_ID!,
  deploymentSecret: process.env.HIVEFORGE_DEPLOYMENT_SECRET!,
});
 
// Initialize once on server start
if (typeof window === 'undefined') {
  hiveforge.initialize().catch(console.error);
}
// pages/api/ai.ts (or app/api/ai/route.ts)
import { hiveforge } from '@/lib/hiveforge';
 
export default async function handler(req, res) {
  const { message } = req.body;
 
  const response = await hiveforge.ai.complete({
    messages: [{ role: 'user', content: message }],
  });
 
  res.json({ content: response.content });
}