@visgate_ai/client 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,511 @@
1
+ /** Billing: GET /billing/stats, /billing/info, /billing/pricing, POST /billing/checkout, /billing/subscription */
2
+
3
+ interface BillingInfo {
4
+ tier: string;
5
+ balanceMicro: number;
6
+ billingStatus: string;
7
+ monthlyBudgetCents?: number | null;
8
+ usageThisMonthCents?: number;
9
+ supportEmail?: string | null;
10
+ companyName?: string | null;
11
+ freeModeEnabled?: boolean;
12
+ }
13
+ declare function billingInfoFromResponse(data: Record<string, unknown>): BillingInfo;
14
+ interface ModelPricing {
15
+ id: string;
16
+ providerType: string;
17
+ model: string;
18
+ modelName: string;
19
+ modelType: string;
20
+ modelClass?: string | null;
21
+ costPerUnitMicro: number;
22
+ usageCount: number;
23
+ totalSavingsMicro: number;
24
+ avgSavingsMicro: number;
25
+ }
26
+ declare function modelPricingFromResponse(data: Record<string, unknown>): ModelPricing;
27
+ interface PricingResponse {
28
+ lastUpdated: string | null;
29
+ pricing: ModelPricing[];
30
+ }
31
+ declare function pricingResponseFromResponse(data: Record<string, unknown>): PricingResponse;
32
+ interface CheckoutOptions {
33
+ customerEmail?: string | null;
34
+ firebaseUid?: string | null;
35
+ }
36
+ declare class Billing {
37
+ private _client;
38
+ constructor(_client: Client);
39
+ /** Public billing stats for landing/marketing (GET /billing/stats). May not require auth. */
40
+ getStats(): Promise<Record<string, unknown>>;
41
+ /** Organization billing info (GET /billing/info). */
42
+ getInfo(): Promise<BillingInfo>;
43
+ /** Create checkout session (POST /billing/checkout). */
44
+ checkout(amountDollars: number, returnUrl: string, options?: CheckoutOptions): Promise<Record<string, unknown>>;
45
+ /** Get pricing for all models (GET /billing/pricing). */
46
+ getPricing(): Promise<PricingResponse>;
47
+ /** Update organization subscription tier (POST /billing/subscription). */
48
+ updateSubscription(tier: string): Promise<{
49
+ success: boolean;
50
+ tier: string;
51
+ }>;
52
+ }
53
+
54
+ /** Unified image generation: POST /generate */
55
+
56
+ interface GenerateResult {
57
+ id: string;
58
+ status: string;
59
+ imageUrl: string | null;
60
+ images: string[];
61
+ model: string;
62
+ provider: string;
63
+ mode: string;
64
+ cost: number;
65
+ costPerMegapixel: number;
66
+ latencyMs: number;
67
+ resolution: Record<string, number>;
68
+ createdAt: Date | null;
69
+ }
70
+ declare function generateResultFromResponse(data: Record<string, unknown>): GenerateResult;
71
+ declare class Generate {
72
+ private _client;
73
+ constructor(_client: Client);
74
+ __call__(prompt: string, model?: string, params?: Record<string, unknown>): Promise<GenerateResult>;
75
+ }
76
+
77
+ /** Image generation: POST /images/generate */
78
+
79
+ interface ImageResult {
80
+ id: string;
81
+ /** Request status: "success" | "cached" | "failed" */
82
+ status?: string;
83
+ images: string[];
84
+ model: string;
85
+ provider: string;
86
+ cost: number;
87
+ /** True when response was served from cache (exact or semantic match). */
88
+ cacheHit: boolean;
89
+ latencyMs: number | null;
90
+ savedAmount?: number;
91
+ marginPercent?: number;
92
+ /** When cache hit: "exact" (hash match) or "semantic" (similarity match). Optional if API returns it. */
93
+ cacheSource?: "exact" | "semantic" | null;
94
+ createdAt: Date | null;
95
+ }
96
+ declare function imageResultFromResponse(data: Record<string, unknown>): ImageResult;
97
+ interface ImagesGenerateOptions {
98
+ negativePrompt?: string | null;
99
+ width?: number;
100
+ height?: number;
101
+ numImages?: number;
102
+ seed?: number | null;
103
+ /** Input image URL for image-to-image */
104
+ imageUrl?: string | null;
105
+ /** Prefer cache (exact or semantic match). Default true. Set false to force fresh generation. */
106
+ preferCache?: boolean;
107
+ /** Max acceptable latency in ms; API may use for routing. */
108
+ maxLatencyMs?: number | null;
109
+ /** URL to call when generation is complete (async callback). */
110
+ webhookUrl?: string | null;
111
+ /** ID to include in the callback payload. */
112
+ callbackId?: string | null;
113
+ params?: Record<string, unknown>;
114
+ }
115
+ declare class Images {
116
+ private _client;
117
+ constructor(_client: Client);
118
+ generate(model: string, prompt: string, options?: ImagesGenerateOptions): Promise<ImageResult>;
119
+ }
120
+
121
+ /** Model catalog: GET /models */
122
+
123
+ interface ModelInfo {
124
+ id: string;
125
+ name: string;
126
+ provider: string;
127
+ mediaType: string;
128
+ description?: string | null;
129
+ category?: string | null;
130
+ tags: string[];
131
+ coverImageUrl?: string | null;
132
+ author?: string | null;
133
+ url?: string | null;
134
+ baseCostMicro: number;
135
+ normalizedCostMicro: number;
136
+ pricing?: string | null;
137
+ pricingUnit?: string | null;
138
+ runCount: number;
139
+ inputTypes: string[];
140
+ outputType?: string | null;
141
+ capabilities: string[];
142
+ firstSeenAt?: string | null;
143
+ providerCreatedAt?: string | null;
144
+ lastSyncedAt?: string | null;
145
+ compliance?: Record<string, unknown> | null;
146
+ }
147
+ declare function modelInfoFromResponse(data: Record<string, unknown>): ModelInfo;
148
+ interface FeaturedSection {
149
+ title: string;
150
+ key: string;
151
+ models: ModelInfo[];
152
+ }
153
+ declare function featuredSectionFromResponse(data: Record<string, unknown>): FeaturedSection;
154
+ interface ModelsResponse {
155
+ models: ModelInfo[];
156
+ totalCount: number;
157
+ lastUpdated?: string | null;
158
+ featured?: FeaturedSection[] | null;
159
+ }
160
+ declare function modelsResponseFromResponse(data: Record<string, unknown>): ModelsResponse;
161
+ interface ModelsListOptions {
162
+ provider?: string | null;
163
+ mediaType?: string | null;
164
+ capability?: string | null;
165
+ search?: string | null;
166
+ sort?: string | null;
167
+ limit?: number;
168
+ featured?: boolean;
169
+ }
170
+ declare class Models {
171
+ private _client;
172
+ constructor(_client: Client);
173
+ list(options?: ModelsListOptions): Promise<ModelsResponse>;
174
+ get(modelId: string): Promise<ModelInfo>;
175
+ search(query: string, limit?: number): Promise<ModelsResponse>;
176
+ }
177
+
178
+ /** Provider key management and balance resources */
179
+
180
+ interface ProviderKeyInfo {
181
+ provider: string;
182
+ validated: boolean;
183
+ validatedAt?: string | null;
184
+ maskedKey?: string | null;
185
+ }
186
+ declare function providerKeyInfoFromResponse(data: Record<string, unknown>): ProviderKeyInfo;
187
+ interface ProviderKeysResponse {
188
+ keys: ProviderKeyInfo[];
189
+ }
190
+ declare function providerKeysResponseFromResponse(data: Record<string, unknown>): ProviderKeysResponse;
191
+ interface ProviderValidationResult {
192
+ valid: boolean;
193
+ message: string;
194
+ }
195
+ declare function providerValidationResultFromResponse(data: Record<string, unknown>): ProviderValidationResult;
196
+ interface ProviderBalanceItem {
197
+ provider: string;
198
+ configured: boolean;
199
+ available: boolean;
200
+ limit?: number | null;
201
+ remaining?: number | null;
202
+ currency?: string | null;
203
+ message?: string | null;
204
+ }
205
+ declare function providerBalanceItemFromResponse(data: Record<string, unknown>): ProviderBalanceItem;
206
+ interface ProviderBalancesResponse {
207
+ balances: ProviderBalanceItem[];
208
+ }
209
+ declare function providerBalancesResponseFromResponse(data: Record<string, unknown>): ProviderBalancesResponse;
210
+ declare class Providers {
211
+ private _client;
212
+ constructor(_client: Client);
213
+ listKeys(): Promise<ProviderKeysResponse>;
214
+ setKey(provider: string, apiKey: string): Promise<ProviderKeyInfo>;
215
+ deleteKey(provider: string): Promise<Record<string, unknown>>;
216
+ validateKey(provider: string, apiKey: string): Promise<ProviderValidationResult>;
217
+ balances(): Promise<ProviderBalancesResponse>;
218
+ }
219
+
220
+ /**
221
+ * Async generation request status: GET /v1/requests/{request_id}
222
+ * Used after POST /videos/generate or /images/generate with Prefer: respond-async (202).
223
+ */
224
+
225
+ interface RequestStatusResult {
226
+ requestId: string;
227
+ status: "pending" | "processing" | "completed" | "failed";
228
+ mediaType: string;
229
+ provider: string;
230
+ model: string;
231
+ outputUrl: string | null;
232
+ errorMessage: string | null;
233
+ createdAt: string | null;
234
+ completedAt: string | null;
235
+ }
236
+ declare function requestStatusFromResponse(data: Record<string, unknown>): RequestStatusResult;
237
+ declare class Requests {
238
+ private _client;
239
+ constructor(_client: Client);
240
+ /** Get status of an async generation request (video/image). */
241
+ get(requestId: string): Promise<RequestStatusResult>;
242
+ }
243
+
244
+ /** Usage and billing: GET /usage, /usage/logs, /dashboard */
245
+
246
+ /** Dashboard response shape (GET /dashboard). */
247
+ interface DashboardResponse {
248
+ total_generations: number;
249
+ total_cost_usd: number;
250
+ avg_latency_ms: number;
251
+ cache_hit_rate: number;
252
+ cached_requests: number;
253
+ success_rate: number;
254
+ cost_per_day: Array<{
255
+ date: string;
256
+ cost_usd: number;
257
+ requests: number;
258
+ }>;
259
+ top_models_used: Array<{
260
+ model: string;
261
+ count: number;
262
+ total_cost_usd: number;
263
+ }>;
264
+ period_days: number;
265
+ }
266
+ interface UsageSummary {
267
+ totalRequests: number;
268
+ successfulRequests: number;
269
+ failedRequests: number;
270
+ cachedRequests: number;
271
+ totalProviderCost: number;
272
+ totalBilledCost: number;
273
+ totalSavings: number;
274
+ byProvider: Record<string, number>;
275
+ byModel: Record<string, number>;
276
+ period: string;
277
+ periodStart: Date | null;
278
+ periodEnd: Date | null;
279
+ cacheHitRate: number;
280
+ /** Average latency in seconds (from API avg_latency) */
281
+ avgLatency?: number;
282
+ /** Raw provider breakdown: provider -> { requests, cost, ... } */
283
+ providerBreakdown?: Record<string, {
284
+ requests: number;
285
+ cost: number;
286
+ providerChargeCost?: number;
287
+ providerEffectiveCost?: number;
288
+ savingsCost?: number;
289
+ }>;
290
+ /** Daily/history records when returned by API */
291
+ history?: Record<string, unknown>[];
292
+ }
293
+ declare function usageSummaryFromResponse(data: Record<string, unknown>): UsageSummary;
294
+ declare class Usage {
295
+ private _client;
296
+ constructor(_client: Client);
297
+ get(period?: string): Promise<UsageSummary>;
298
+ logs(options?: {
299
+ limit?: number;
300
+ offset?: number;
301
+ }): Promise<Record<string, unknown>[]>;
302
+ dashboard(period?: string): Promise<Record<string, unknown>>;
303
+ /**
304
+ * Track a download event for a request (POST /usage/downloads).
305
+ * Increments download_count and adds timestamp to downloaded_at.
306
+ */
307
+ trackDownload(requestId: string, outputUrl: string, options?: {
308
+ mediaType?: string;
309
+ }): Promise<{
310
+ success: boolean;
311
+ request_id: string;
312
+ download_count: number;
313
+ }>;
314
+ }
315
+
316
+ /**
317
+ * Video generation: POST /videos/generate
318
+ *
319
+ * Mirrors the Python SDK example 04_videos_all_providers: managed mode and
320
+ * BYOK (Fal, Replicate, Runway) with provider-specific model IDs.
321
+ *
322
+ * @example Managed (platform keys)
323
+ * ```ts
324
+ * const r = await client.videos.generate("fal-ai/veo3", prompt, { durationSeconds: 6, skipGcsUpload: true, preferAsync: true });
325
+ * ```
326
+ *
327
+ * @example BYOK – use client options or proxy env (X-Fal-Key, X-Replicate-Key, X-Runway-Key)
328
+ * ```ts
329
+ * // Fal (veo3; alternative: fal-ai/flux-pro)
330
+ * client.videos.generate("fal-ai/veo3", prompt, { durationSeconds: 6, skipGcsUpload: true, preferAsync: true });
331
+ * // Replicate
332
+ * client.videos.generate("replicate/lucataco/cogvideox-5b", prompt, { durationSeconds: 5, skipGcsUpload: true, preferAsync: true });
333
+ * // Runway
334
+ * client.videos.generate("runway/gen4_turbo", prompt, { durationSeconds: 5, skipGcsUpload: true, preferAsync: true });
335
+ * ```
336
+ */
337
+
338
+ /** Recommended video model IDs per provider (align with working 06_videos_all_providers; Fal uses veo3). */
339
+ declare const VIDEO_MODEL_PRESETS: {
340
+ readonly fal: "fal-ai/veo3";
341
+ readonly replicate: "replicate/lucataco/cogvideox-5b";
342
+ readonly runway: "runway/gen4_turbo";
343
+ };
344
+ interface VideoResult {
345
+ id: string;
346
+ /** Request status: "success" | "cached" | "failed" */
347
+ status?: string;
348
+ videoUrl: string | null;
349
+ model: string;
350
+ provider: string;
351
+ cost: number;
352
+ /** True when response was served from cache (exact or semantic match). */
353
+ cacheHit: boolean;
354
+ latencyMs: number | null;
355
+ savedAmount?: number;
356
+ marginPercent?: number;
357
+ /** When cache hit: "exact" (hash match) or "semantic" (similarity match). */
358
+ cacheSource?: "exact" | "semantic" | null;
359
+ createdAt: Date | null;
360
+ }
361
+ declare function videoResultFromResponse(data: Record<string, unknown>): VideoResult;
362
+ /** Result when using preferAsync: true — API returns 202, poll client.requests.get(requestId). */
363
+ interface AsyncVideoAccepted {
364
+ requestId: string;
365
+ status: "accepted";
366
+ }
367
+ interface VideosGenerateOptions {
368
+ /** Input image URL for image-to-video. */
369
+ imageUrl?: string | null;
370
+ /**
371
+ * Input image as File or Blob (e.g. from file input). Converted to data URL and sent as image_url.
372
+ * Takes precedence over imageUrl if both are set.
373
+ */
374
+ imageFile?: File | Blob;
375
+ /** Duration in seconds (default 5). */
376
+ durationSeconds?: number;
377
+ fps?: number;
378
+ /** URL to call when generation is complete (async callback). */
379
+ webhookUrl?: string | null;
380
+ /** ID to include in the callback payload. */
381
+ callbackId?: string | null;
382
+ /** Skip uploading result to GCS; return provider URL directly. Faster, use when behind short timeouts. */
383
+ skipGcsUpload?: boolean;
384
+ /**
385
+ * Use async mode: API returns 202 immediately, poll client.requests.get(requestId) for status.
386
+ * Avoids 502 when video takes longer than proxy/Cloudflare timeout.
387
+ */
388
+ preferAsync?: boolean;
389
+ /** Extra provider-specific params (merged into request body). */
390
+ params?: Record<string, unknown>;
391
+ }
392
+ declare class Videos {
393
+ private _client;
394
+ constructor(_client: Client);
395
+ /**
396
+ * Generate a video from a prompt (and optional image for img2vid).
397
+ * Supports managed mode and BYOK (set falKey/replicateKey/runwayKey on client or via proxy env).
398
+ * Use preferAsync: true to avoid 502 when video takes longer than proxy/Cloudflare timeout.
399
+ */
400
+ generate(model: string, prompt: string, options?: VideosGenerateOptions): Promise<VideoResult | AsyncVideoAccepted>;
401
+ }
402
+
403
+ /**
404
+ * Visgate API client (all methods return Promises in JS).
405
+ */
406
+
407
+ interface ClientOptions {
408
+ apiKey?: string | null;
409
+ /** When set, requests go to this URL and no API key is sent (key is added by the proxy). */
410
+ proxyUrl?: string;
411
+ baseUrl?: string;
412
+ timeout?: number;
413
+ maxRetries?: number;
414
+ falKey?: string | null;
415
+ replicateKey?: string | null;
416
+ runwayKey?: string | null;
417
+ }
418
+ interface RequestInitWithBody {
419
+ body?: string;
420
+ headers?: Record<string, string>;
421
+ }
422
+ declare class Client {
423
+ readonly apiKey: string | null;
424
+ readonly baseUrl: string;
425
+ readonly maxRetries: number;
426
+ readonly timeout: number;
427
+ private readonly headers;
428
+ readonly images: Images;
429
+ readonly models: Models;
430
+ readonly videos: Videos;
431
+ readonly requests: Requests;
432
+ readonly usage: Usage;
433
+ readonly providers: Providers;
434
+ readonly billing: Billing;
435
+ private _generate;
436
+ constructor(options?: ClientOptions);
437
+ /**
438
+ * Generate an image with a single call.
439
+ */
440
+ generate(prompt: string, options?: {
441
+ model?: string;
442
+ params?: Record<string, unknown>;
443
+ }): Promise<GenerateResult>;
444
+ /**
445
+ * Check API health status.
446
+ */
447
+ health(): Promise<Record<string, unknown>>;
448
+ _request(method: string, path: string, init?: RequestInitWithBody): Promise<unknown>;
449
+ /** No-op for API compatibility (JS has no connection pool to close). */
450
+ close(): void;
451
+ toString(): string;
452
+ }
453
+ /**
454
+ * Async client — same as Client; all methods return Promises.
455
+ * Provided for API parity with Python AsyncClient.
456
+ */
457
+ declare class AsyncClient extends Client {
458
+ constructor(options?: ClientOptions);
459
+ toString(): string;
460
+ }
461
+
462
+ /** Visgate SDK exceptions. All extend VisgateError. */
463
+ interface VisgateErrorDetails {
464
+ [key: string]: unknown;
465
+ }
466
+ /**
467
+ * Base exception for all Visgate SDK errors.
468
+ */
469
+ declare class VisgateError extends Error {
470
+ readonly message: string;
471
+ readonly errorCode: string;
472
+ readonly details: VisgateErrorDetails;
473
+ readonly statusCode?: number;
474
+ constructor(message: string, errorCode?: string, details?: VisgateErrorDetails, statusCode?: number);
475
+ toString(): string;
476
+ }
477
+ /** 401 — invalid or missing API key. */
478
+ declare class AuthenticationError extends VisgateError {
479
+ constructor(message?: string);
480
+ }
481
+ /** 422 — invalid request parameters. */
482
+ declare class ValidationError extends VisgateError {
483
+ readonly field?: string;
484
+ constructor(message: string, field?: string);
485
+ }
486
+ /** 429 — too many requests. */
487
+ declare class RateLimitError extends VisgateError {
488
+ readonly retryAfter?: number;
489
+ constructor(message?: string, retryAfter?: number);
490
+ }
491
+ /** Upstream provider error (e.g. Fal, Replicate, Runway). */
492
+ declare class ProviderError extends VisgateError {
493
+ readonly provider: string;
494
+ constructor(message: string, provider?: string);
495
+ }
496
+ /** Request timed out before the server responded. */
497
+ declare class VisgateTimeoutError extends VisgateError {
498
+ constructor(message?: string);
499
+ }
500
+ /** Network connection failed. */
501
+ declare class VisgateConnectionError extends VisgateError {
502
+ constructor(message?: string);
503
+ }
504
+
505
+ /**
506
+ * Visgate JavaScript/TypeScript SDK — unified client for the Visgate vision AI gateway.
507
+ */
508
+
509
+ declare const VERSION = "0.2.2";
510
+
511
+ export { AsyncClient, type AsyncVideoAccepted, AuthenticationError, Billing, type BillingInfo, type CheckoutOptions, Client, type ClientOptions, type DashboardResponse, type FeaturedSection, Generate, type GenerateResult, type ImageResult, Images, type ImagesGenerateOptions, type ModelInfo, type ModelPricing, Models, type ModelsListOptions, type ModelsResponse, type PricingResponse, type ProviderBalanceItem, type ProviderBalancesResponse, ProviderError, type ProviderKeyInfo, type ProviderKeysResponse, type ProviderValidationResult, Providers, RateLimitError, type RequestStatusResult, Requests, Usage, type UsageSummary, VERSION, VIDEO_MODEL_PRESETS, ValidationError, type VideoResult, Videos, type VideosGenerateOptions, VisgateConnectionError, VisgateError, type VisgateErrorDetails, VisgateTimeoutError, billingInfoFromResponse, featuredSectionFromResponse, generateResultFromResponse, imageResultFromResponse, modelInfoFromResponse, modelPricingFromResponse, modelsResponseFromResponse, pricingResponseFromResponse, providerBalanceItemFromResponse, providerBalancesResponseFromResponse, providerKeyInfoFromResponse, providerKeysResponseFromResponse, providerValidationResultFromResponse, requestStatusFromResponse, usageSummaryFromResponse, videoResultFromResponse };