/** * TikToday-compatible OpenAPI v1 TypeScript/JavaScript Client (Zero dependencies, Node 18+/Browser) * Supports all 12 v1 endpoints, automatic retry on 429 RATE_LIMITED / 503 UNAVAILABLE using Retry-After. */ export interface TikTodayClientOptions { apiKey: string; baseUrl?: string; maxRetries?: number; timeoutMs?: number; } export interface ApiEnvelope { code: string; message: string; data: T; request_id: string; doc_url?: string; } export interface ApiCallResult { data: T; requestId: string; rateLimit: { limit?: number; remaining?: number; reset?: number }; quota: { limit?: number; remaining?: number; reset?: number }; } export class TikTodayApiError extends Error { constructor( public readonly status: number, public readonly code: string, message: string, public readonly requestId: string, public readonly docUrl?: string, ) { super(`[${status} ${code}] ${message} (request_id=${requestId})`); this.name = 'TikTodayApiError'; } } export class TikTodayClient { private readonly baseUrl: string; private readonly apiKey: string; private readonly maxRetries: number; private readonly timeoutMs: number; constructor(opts: TikTodayClientOptions) { this.apiKey = opts.apiKey; this.baseUrl = (opts.baseUrl ?? 'http://localhost:8088').replace(/\/$/, ''); this.maxRetries = opts.maxRetries ?? 2; this.timeoutMs = opts.timeoutMs ?? 15_000; } private async request(method: 'GET' | 'POST', path: string, body?: unknown): Promise> { for (let attempt = 0; attempt <= this.maxRetries; attempt++) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeoutMs); try { const res = await fetch(`${this.baseUrl}${path}`, { method, headers: { Authorization: `Bearer ${this.apiKey}`, ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), }, body: body !== undefined ? JSON.stringify(body) : undefined, signal: controller.signal, }); const json = (await res.json()) as ApiEnvelope; const retryAfter = Number(res.headers.get('retry-after') ?? 0); if ( attempt < this.maxRetries && ((res.status === 429 && json.code === 'RATE_LIMITED') || res.status === 503) ) { const waitMs = Math.min(30_000, Math.max(500, (retryAfter || 1) * 1000)); await new Promise((r) => setTimeout(r, waitMs)); continue; } if (!res.ok) { throw new TikTodayApiError( res.status, json.code ?? 'INTERNAL', json.message ?? res.statusText, json.request_id ?? res.headers.get('x-request-id') ?? '', json.doc_url, ); } const numHdr = (name: string) => { const v = res.headers.get(name); return v !== null ? Number(v) : undefined; }; return { data: json.data, requestId: json.request_id, rateLimit: { limit: numHdr('x-ratelimit-limit'), remaining: numHdr('x-ratelimit-remaining'), reset: numHdr('x-ratelimit-reset'), }, quota: { limit: numHdr('x-quota-limit'), remaining: numHdr('x-quota-remaining'), reset: numHdr('x-quota-reset'), }, }; } finally { clearTimeout(timer); } } throw new Error('Max retries exceeded'); } // Health v1 checkHealth() { return this.request<{ status: string }>('GET', '/health/v1/check'); } // Creator v1 getCreatorProfile(username: string) { return this.request>( 'GET', `/creator/v1/creators/${encodeURIComponent(username)}/profile`, ); } getCreatorAffiliate(username: string) { return this.request>( 'GET', `/creator/v1/creators/${encodeURIComponent(username)}/affiliate`, ); } searchCreators(params: { keyword?: string; count?: number } = {}) { return this.request>>('POST', '/creator/v1/creators/search', params); } getCreatorVideos(username: string, params?: { limit?: number; since?: number }) { const qs = new URLSearchParams(); if (params?.limit !== undefined) qs.set('limit', String(params.limit)); if (params?.since !== undefined) qs.set('since', String(params.since)); const suffix = qs.toString() ? `?${qs.toString()}` : ''; return this.request>>( 'GET', `/creator/v1/creators/${encodeURIComponent(username)}/videos${suffix}`, ); } // Product v1 getProductDetails(productId: string) { return this.request>( 'GET', `/product/v1/products/${encodeURIComponent(productId)}/details`, ); } searchProducts(params: { query: string; limit?: number }) { return this.request>>('POST', '/product/v1/products/search', params); } getProductAffiliate(productId: string) { return this.request>( 'GET', `/product/v1/products/${encodeURIComponent(productId)}/affiliate`, ); } searchProductAffiliates(params: { query?: string; category?: string; min_commission_rate?: number; free_sample_only?: boolean; limit?: number; } = {}) { return this.request>>( 'POST', '/product/v1/products/affiliate/search', params, ); } // Video v1 getVideoDetails(videoId: string) { return this.request>('GET', `/video/v1/videos/${encodeURIComponent(videoId)}`); } searchVideos(params: { query: string; limit?: number }) { return this.request>>('POST', '/video/v1/videos/search', params); } getVideoPlayUrl(url: string) { return this.request<{ play_url: string | null }>('POST', '/video/v1/videos/play-url', { url }); } }