@subscribe.dev/client
Version:
JavaScript/TypeScript client for SubscribeDev API - A drop-in for AI generation across 100+ models with built-in billing and rate limiting
486 lines (449 loc) • 13.7 kB
TypeScript
import { EventEmitter } from 'eventemitter3';
/**
* Error thrown when access to a resource is denied
*/
export declare class AccessDeniedError extends SubscribeDevError {
constructor(message: string, requestId?: string);
}
/**
* Error thrown for authentication failures
*/
export declare class AuthenticationError extends SubscribeDevError {
constructor(message: string, requestId?: string);
}
export declare interface BalanceInfo {
allocatedCredits: number;
usedCredits: number;
remainingCredits: number;
}
export declare interface ChatMessage {
role: 'system' | 'user' | 'assistant';
content: string | MultimodalMessageContent[];
}
export declare interface CheckoutSessionRequest {
planId: string;
userId: string;
userEmail: string;
successUrl?: string;
cancelUrl?: string;
}
export declare interface CheckoutSessionResponse {
checkoutUrl: string;
sessionId: string;
}
export declare interface FreeSignupRequest {
userId: string;
userEmail: string;
}
export declare interface FreeSignupResponse {
success: boolean;
message: string;
plan: {
id: string;
name: string;
price: number;
tokenLimit: number;
};
}
/**
* Error thrown when account has insufficient balance
*/
export declare class InsufficientBalanceError extends SubscribeDevError {
constructor(message: string, remainingCredits?: number, requiredCredits?: number, requestId?: string);
}
export declare interface MultimodalMessageContent {
type: 'text' | 'image_url';
text?: string;
image_url?: {
url: string;
detail?: 'low' | 'high' | 'auto';
};
}
/**
* Error thrown when a resource is not found
*/
export declare class NotFoundError extends SubscribeDevError {
constructor(message: string, requestId?: string);
}
export declare interface Prediction {
id: string;
version?: string;
created_at: string;
started_at?: string;
completed_at?: string;
status: 'starting' | 'processing' | 'succeeded' | 'failed' | 'canceled';
input: Record<string, any>;
output?: any;
error?: string;
logs?: string;
metrics?: Record<string, number>;
urls: {
get: string;
cancel?: string;
};
}
export declare interface PredictionOptions {
}
export declare type ProgressCallback = (prediction: Prediction) => void;
export declare interface ProjectBalance {
projectId: string;
totalCredits: number;
usedCredits: number;
remainingCredits: number;
lastUpdated: Date;
}
/**
* Error thrown when rate limit is exceeded
*/
export declare class RateLimitError extends SubscribeDevError {
readonly resetTime?: string;
readonly retryAfter?: number;
constructor(message: string, resetTime?: string, retryAfter?: number, requestId?: string);
}
export declare interface RateLimitInfo {
concurrent: {
allowed: boolean;
currentRequests: number;
maxRequests: number;
reason?: string;
};
minute?: {
allowed: boolean;
currentRequests: number;
maxRequests: number;
resetTime: string;
reason?: string;
};
hour?: {
allowed: boolean;
currentRequests: number;
maxRequests: number;
resetTime: string;
reason?: string;
};
day?: {
allowed: boolean;
currentRequests: number;
maxRequests: number;
resetTime: string;
reason?: string;
};
}
export declare interface ReplicateRequest {
model: string;
input: Record<string, unknown>;
response_format?: ResponseFormat;
}
export declare interface ReplicateResponse {
id: string;
version: string;
urls: {
get: string;
cancel: string;
};
created_at: string;
started_at?: string;
completed_at?: string;
status: 'starting' | 'processing' | 'succeeded' | 'failed' | 'canceled';
input: Record<string, unknown>;
output?: unknown;
error?: string;
logs?: string;
metrics?: {
predict_time?: number;
total_time?: number;
};
}
export declare type ResponseFormat = {
type: 'json_object';
} | {
type: 'json_schema';
json_schema: {
name: string;
strict?: boolean;
schema: Record<string, unknown>;
};
};
export declare interface StorageOptions {
/** App version for storage isolation (defaults to "default") */
appVersion?: string;
}
/**
* SubscribeDevClient - Drop-in replacement for Replicate.js with billing and rate limiting
*/
export declare class SubscribeDevClient extends EventEmitter {
private readonly config;
private readonly queue;
private readonly fetch;
constructor(config: SubscribeDevClientConfig);
get pricingUrl(): string;
/**
* Run a prediction (main method matching Replicate.js API)
* Note: Now returns completed predictions directly - no polling needed
*/
run(model: string, options: {
input: Record<string, any>;
response_format?: ResponseFormat;
wait?: boolean;
}): Promise<any>;
/**
* Create a new prediction
*/
createPrediction(model: string, options: {
input: Record<string, any>;
response_format?: ResponseFormat;
}): Promise<Prediction>;
/**
* Get prediction status
* @deprecated Since predictions now complete synchronously, this is mainly for historical lookups
*/
getPrediction(id: string): Promise<Prediction>;
/**
* Cancel a prediction
*/
cancelPrediction(id: string): Promise<Prediction>;
/**
* Wait for prediction completion with optional progress callback
* @deprecated Since predictions now complete synchronously, this method is no longer needed
*/
waitForPrediction(id: string, progressCallback?: ProgressCallback): Promise<Prediction>;
/**
* Get account balance information
*/
getBalance(): Promise<BalanceInfo>;
/**
* Get transaction history
*/
getTransactions(options?: TransactionHistoryOptions): Promise<TransactionHistory>;
/**
* Get rate limit information
*/
getRateLimits(): Promise<RateLimitInfo>;
/**
* Get user storage data using auth context
*/
getStorage(options?: StorageOptions): Promise<UserStorage>;
/**
* Update user storage data using auth context
*/
setStorage(sessionData: Record<string, any>, options?: StorageOptions): Promise<UserStorage>;
/**
* Delete user storage data using auth context
*/
deleteStorage(options?: StorageOptions): Promise<void>;
/**
* Browser convenience method: Persist session data locally and sync to server
* Automatically saves the entire session object to localStorage and server
*/
persistSessionData(options?: StorageOptions): Promise<UserStorage>;
/**
* Browser convenience method: Get session data from server and update localStorage
* Always fetches from server to ensure data is synchronized
*/
getSessionData(options?: StorageOptions): Promise<Record<string, any>>;
/**
* Get user's subscription status using userKey authentication
* Requires userKey to be provided in client configuration
*/
getSubscriptionStatus(): Promise<SubscriptionStatus>;
/**
* Get available subscription plans for the project
*/
getSubscriptionPlans(): Promise<SubscriptionPlansResponse>;
/**
* Create a checkout session for subscription payment
* Requires userKey to be provided in client configuration
*/
createCheckoutSession(request: CheckoutSessionRequest): Promise<CheckoutSessionResponse>;
/**
* Sign up for the free plan
* Requires userKey to be provided in client configuration
*/
signupForFree(request: FreeSignupRequest): Promise<FreeSignupResponse>;
/**
* Cancel user subscription
* Requires userKey to be provided in client configuration
*/
cancelSubscription(userId: string, cancelAtPeriodEnd?: boolean): Promise<{
success: boolean;
cancelledAt: string;
}>;
/**
* Get comprehensive usage limits and current consumption
* Requires userKey to be provided in client configuration
*/
getUsageLimits(): Promise<UsageLimits>;
/**
* Get comprehensive usage information including credits, rate limits, and consumption
* Alias for getUsageLimits() - Requires userKey to be provided in client configuration
*/
getUsage(): Promise<UsageLimits>;
/**
* Make authenticated HTTP request to SubscribeDev API
*/
private makeRequest;
/**
* Handle error responses and throw appropriate error types
*/
private handleErrorResponse;
/**
* Transform API response to match Replicate.js format
*/
private transformResponse;
/**
* Debug logging
*/
private debug;
/**
* Static method to create client (for convenience)
*/
static create(config: SubscribeDevClientConfig): SubscribeDevClient;
}
export declare interface SubscribeDevClientConfig {
/** Public API key (project bearer token) */
apiKey: string;
/** Optional user token for user-specific limits */
userKey?: string;
/** API base URL (defaults to production) */
baseUrl?: string;
/** Request timeout in milliseconds (default: 300000) */
timeout?: number;
/** Maximum retry attempts (default: 3) */
maxRetries?: number;
/** Enable debug logging (default: false) */
debug?: boolean;
}
/**
* Base error class for SubscribeDev client errors
*/
export declare class SubscribeDevError extends Error {
readonly code: string;
readonly statusCode?: number;
readonly details?: Record<string, any>;
readonly requestId?: string;
constructor(message: string, code: string, statusCode?: number, details?: Record<string, any>, requestId?: string);
}
export declare interface SubscriptionPlan {
id: string;
name: string;
price: number;
tokenLimit: number;
subtitle?: string;
description?: string;
features: string[];
stripePriceId?: string;
isDefault: boolean;
createdAt: string;
updatedAt: string;
}
export declare interface SubscriptionPlansResponse {
plans: SubscriptionPlan[];
projectName: string;
}
export declare interface SubscriptionStatus {
hasActiveSubscription: boolean;
plan?: {
id: string;
name: string;
price: number;
tokenLimit: number;
subtitle?: string;
description?: string;
features: string[];
};
status: 'active' | 'inactive' | 'cancelled' | 'expired' | 'none';
startedAt?: string;
endsAt?: string;
}
export declare interface Transaction {
id: string;
projectId: string;
userId?: string;
modelName: string;
operationType: 'prediction' | 'training';
replicatePredictionId?: string;
estimatedCost: number;
actualCost?: number;
status: 'pending' | 'completed' | 'failed' | 'cancelled';
createdAt: Date;
completedAt?: Date;
metadata?: Record<string, unknown>;
}
export declare interface TransactionHistory {
transactions: Transaction[];
pagination: {
limit: number;
offset: number;
total: number;
};
}
export declare interface TransactionHistoryOptions {
limit?: number;
offset?: number;
status?: 'pending' | 'completed' | 'failed' | 'cancelled';
model?: string;
startDate?: string;
endDate?: string;
}
/**
* Error thrown when user is not subscribed (unsubscribed 402 error)
*/
export declare class UnsubscribedError extends SubscribeDevError {
constructor(message: string, requestId?: string);
}
export declare interface UsageLimits {
credits: {
userBalance?: {
allocatedCredits: number;
usedCredits: number;
remainingCredits: number;
lastUpdated: string;
};
limits: {
maxCreditsPerMonth: number;
maxCreditsPerDay: number;
userCreditLimit: number;
};
usage: {
currentMonthUsage: number;
currentDayUsage: number;
};
};
rateLimits: {
concurrent: any;
minute: any;
hour: any;
day: any;
};
modelRestrictions: {
allowedModels: string[];
blockedModels: string[];
};
requestLimits: {
maxConcurrentRequests: number;
currentConcurrentRequests: number;
};
}
export declare interface UserBalance {
projectId: string;
userId: string;
allocatedCredits: number;
usedCredits: number;
remainingCredits: number;
lastUpdated: Date;
}
export declare interface UserStorage {
projectId: string;
userId: string;
appVersion: string;
sessionData: Record<string, any>;
createdAt: string;
updatedAt: string;
}
/**
* Error thrown for request validation failures
*/
export declare class ValidationError extends SubscribeDevError {
constructor(message: string, details?: Record<string, any>, requestId?: string);
}
export { }