@runapi.ai/core
Advanced tools
| /** HTTP methods supported by the SDK. */ | ||
| type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; | ||
| /** Query parameters for HTTP requests. Null and undefined values are omitted. */ | ||
| type QueryParams = Record<string, string | number | boolean | null | undefined>; | ||
| /** | ||
| * Configuration options for API clients. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const client = new SunoClient({ | ||
| * apiKey: 'your-api-key', | ||
| * baseUrl: 'https://runapi.ai', | ||
| * timeoutMs: 60000, | ||
| * maxRetries: 3, | ||
| * }); | ||
| * ``` | ||
| */ | ||
| interface ClientOptions { | ||
| /** | ||
| * API key for authentication. If omitted, the SDK reads | ||
| * `RUNAPI_API_KEY` from the environment (Node runtimes only). | ||
| */ | ||
| apiKey?: string; | ||
| /** Base URL for API requests. Defaults to `https://runapi.ai`. */ | ||
| baseUrl?: string; | ||
| /** Request timeout in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| timeoutMs?: number; | ||
| /** Maximum number of retry attempts. Defaults to 2. */ | ||
| maxRetries?: number; | ||
| /** Base delay between retries in milliseconds. Defaults to 500. */ | ||
| retryBaseDelayMs?: number; | ||
| /** Maximum delay between retries in milliseconds. Defaults to 5000. */ | ||
| retryMaxDelayMs?: number; | ||
| /** Custom `fetch` implementation. Defaults to the global `fetch`. */ | ||
| fetch?: typeof fetch; | ||
| /** | ||
| * Extra options passed to every `fetch` call (e.g. `cache`, `credentials`, `keepalive`). | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Per-request options that override client-level defaults. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * await client.textToImage.run( | ||
| * { prompt: 'A sunset' }, | ||
| * { timeoutMs: 30000, headers: { 'X-Custom': 'value' } } | ||
| * ); | ||
| * ``` | ||
| */ | ||
| interface RequestOptions { | ||
| /** Additional HTTP headers. Merged with client-level headers. */ | ||
| headers?: Record<string, string>; | ||
| /** Request timeout in milliseconds. Overrides client-level timeout. */ | ||
| timeoutMs?: number; | ||
| /** Maximum retry attempts. Overrides client-level maxRetries. */ | ||
| maxRetries?: number; | ||
| /** Abort signal for request cancellation. */ | ||
| signal?: AbortSignal; | ||
| /** | ||
| * Per-request fetch options that override client-level `fetchOptions`. | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Options for polling async task completion. | ||
| * Used internally by resource `run()` methods. | ||
| */ | ||
| interface PollingOptions { | ||
| /** Polling interval in milliseconds. Defaults to 2000 (2 seconds). */ | ||
| pollIntervalMs?: number; | ||
| /** Maximum wait time in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| maxWaitMs?: number; | ||
| } | ||
| /** Task status values returned by async operations. */ | ||
| type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed'; | ||
| /** | ||
| * Status for async task results (excludes 'pending'). | ||
| * Used for polling results that have already started processing. | ||
| */ | ||
| type AsyncTaskStatus = Exclude<TaskStatus, 'pending'>; | ||
| /** | ||
| * Persisted billing facts included in every task-based media response. | ||
| * Create responses do not always have a status, so they use this separately | ||
| * from TaskResponse. | ||
| */ | ||
| interface TaskBillingResponse { | ||
| /** | ||
| * Persisted billing facts for this Task. Older or incomplete responses may | ||
| * omit this field; once present, unavailable individual facts are `null`. | ||
| */ | ||
| billing?: TaskBillingFacts; | ||
| } | ||
| /** | ||
| * Response structure for async task operations. | ||
| * Specific API methods extend this with additional fields. | ||
| */ | ||
| interface TaskResponse extends TaskBillingResponse { | ||
| /** Task ID for tracking and retrieval. */ | ||
| id?: string; | ||
| /** Current task status. */ | ||
| status: TaskStatus | string; | ||
| /** Error message if task failed. */ | ||
| error?: string; | ||
| /** Additional task-specific fields. */ | ||
| [key: string]: unknown; | ||
| } | ||
| interface TaskBillingFacts { | ||
| reservation: TaskReservation | null; | ||
| settlement: TaskSettlement | null; | ||
| refund: TaskRefund | null; | ||
| } | ||
| interface TaskReservation { | ||
| amount_cents: number; | ||
| } | ||
| interface TaskSettlement { | ||
| charged_amount_cents: number; | ||
| amount_micro_cents: number; | ||
| } | ||
| interface TaskRefund { | ||
| refunded_at: string; | ||
| } | ||
| export type { AsyncTaskStatus as A, ClientOptions as C, HttpMethod as H, PollingOptions as P, QueryParams as Q, RequestOptions as R, TaskBillingFacts as T, TaskBillingResponse as a, TaskRefund as b, TaskReservation as c, TaskResponse as d, TaskSettlement as e, TaskStatus as f }; |
| /** HTTP methods supported by the SDK. */ | ||
| type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; | ||
| /** Query parameters for HTTP requests. Null and undefined values are omitted. */ | ||
| type QueryParams = Record<string, string | number | boolean | null | undefined>; | ||
| /** | ||
| * Configuration options for API clients. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const client = new SunoClient({ | ||
| * apiKey: 'your-api-key', | ||
| * baseUrl: 'https://runapi.ai', | ||
| * timeoutMs: 60000, | ||
| * maxRetries: 3, | ||
| * }); | ||
| * ``` | ||
| */ | ||
| interface ClientOptions { | ||
| /** | ||
| * API key for authentication. If omitted, the SDK reads | ||
| * `RUNAPI_API_KEY` from the environment (Node runtimes only). | ||
| */ | ||
| apiKey?: string; | ||
| /** Base URL for API requests. Defaults to `https://runapi.ai`. */ | ||
| baseUrl?: string; | ||
| /** Request timeout in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| timeoutMs?: number; | ||
| /** Maximum number of retry attempts. Defaults to 2. */ | ||
| maxRetries?: number; | ||
| /** Base delay between retries in milliseconds. Defaults to 500. */ | ||
| retryBaseDelayMs?: number; | ||
| /** Maximum delay between retries in milliseconds. Defaults to 5000. */ | ||
| retryMaxDelayMs?: number; | ||
| /** Custom `fetch` implementation. Defaults to the global `fetch`. */ | ||
| fetch?: typeof fetch; | ||
| /** | ||
| * Extra options passed to every `fetch` call (e.g. `cache`, `credentials`, `keepalive`). | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Per-request options that override client-level defaults. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * await client.textToImage.run( | ||
| * { prompt: 'A sunset' }, | ||
| * { timeoutMs: 30000, headers: { 'X-Custom': 'value' } } | ||
| * ); | ||
| * ``` | ||
| */ | ||
| interface RequestOptions { | ||
| /** Additional HTTP headers. Merged with client-level headers. */ | ||
| headers?: Record<string, string>; | ||
| /** Request timeout in milliseconds. Overrides client-level timeout. */ | ||
| timeoutMs?: number; | ||
| /** Maximum retry attempts. Overrides client-level maxRetries. */ | ||
| maxRetries?: number; | ||
| /** Abort signal for request cancellation. */ | ||
| signal?: AbortSignal; | ||
| /** | ||
| * Per-request fetch options that override client-level `fetchOptions`. | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Options for polling async task completion. | ||
| * Used internally by resource `run()` methods. | ||
| */ | ||
| interface PollingOptions { | ||
| /** Polling interval in milliseconds. Defaults to 2000 (2 seconds). */ | ||
| pollIntervalMs?: number; | ||
| /** Maximum wait time in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| maxWaitMs?: number; | ||
| } | ||
| /** Task status values returned by async operations. */ | ||
| type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed'; | ||
| /** | ||
| * Status for async task results (excludes 'pending'). | ||
| * Used for polling results that have already started processing. | ||
| */ | ||
| type AsyncTaskStatus = Exclude<TaskStatus, 'pending'>; | ||
| /** | ||
| * Persisted billing facts included in every task-based media response. | ||
| * Create responses do not always have a status, so they use this separately | ||
| * from TaskResponse. | ||
| */ | ||
| interface TaskBillingResponse { | ||
| /** | ||
| * Persisted billing facts for this Task. Older or incomplete responses may | ||
| * omit this field; once present, unavailable individual facts are `null`. | ||
| */ | ||
| billing?: TaskBillingFacts; | ||
| } | ||
| /** | ||
| * Response structure for async task operations. | ||
| * Specific API methods extend this with additional fields. | ||
| */ | ||
| interface TaskResponse extends TaskBillingResponse { | ||
| /** Task ID for tracking and retrieval. */ | ||
| id?: string; | ||
| /** Current task status. */ | ||
| status: TaskStatus | string; | ||
| /** Error message if task failed. */ | ||
| error?: string; | ||
| /** Additional task-specific fields. */ | ||
| [key: string]: unknown; | ||
| } | ||
| interface TaskBillingFacts { | ||
| reservation: TaskReservation | null; | ||
| settlement: TaskSettlement | null; | ||
| refund: TaskRefund | null; | ||
| } | ||
| interface TaskReservation { | ||
| amount_cents: number; | ||
| } | ||
| interface TaskSettlement { | ||
| charged_amount_cents: number; | ||
| amount_micro_cents: number; | ||
| } | ||
| interface TaskRefund { | ||
| refunded_at: string; | ||
| } | ||
| export type { AsyncTaskStatus as A, ClientOptions as C, HttpMethod as H, PollingOptions as P, QueryParams as Q, RequestOptions as R, TaskBillingFacts as T, TaskBillingResponse as a, TaskRefund as b, TaskReservation as c, TaskResponse as d, TaskSettlement as e, TaskStatus as f }; |
+76
-6
@@ -1,3 +0,3 @@ | ||
| import { C as ClientOptions, H as HttpMethod, R as RequestOptions, Q as QueryParams } from './types-B4_rq_8F.mjs'; | ||
| export { A as AsyncTaskStatus, P as PollingOptions, T as TaskResponse, a as TaskStatus } from './types-B4_rq_8F.mjs'; | ||
| import { C as ClientOptions, H as HttpMethod, R as RequestOptions, Q as QueryParams } from './types-ClO2hfPY.mjs'; | ||
| export { A as AsyncTaskStatus, P as PollingOptions, T as TaskBillingFacts, a as TaskBillingResponse, b as TaskRefund, c as TaskReservation, d as TaskResponse, e as TaskSettlement, f as TaskStatus } from './types-ClO2hfPY.mjs'; | ||
@@ -139,2 +139,4 @@ /** | ||
| declare function resolveApiKey(options: ClientOptions): string; | ||
| /** Resolve an API key when present without requiring one for public resources. */ | ||
| declare function resolveOptionalApiKey(options: ClientOptions): string | undefined; | ||
@@ -144,2 +146,6 @@ interface HttpRequestOptions extends RequestOptions { | ||
| body?: unknown; | ||
| /** Treat HTTP 304 as a successful conditional request result. */ | ||
| allowNotModified?: boolean; | ||
| /** Internal response-header capture for resources that support HTTP revalidation. */ | ||
| captureResponseHeaders?: Record<string, string>; | ||
| } | ||
@@ -242,6 +248,68 @@ interface HttpClient { | ||
| interface PriceScheduleFilters extends QueryParams { | ||
| service?: string; | ||
| action?: string; | ||
| model?: string; | ||
| } | ||
| interface PriceSchedule { | ||
| service: string; | ||
| action: string; | ||
| model: string | null; | ||
| pricing_status: 'available' | 'pending' | string; | ||
| catalog_status: 'active' | 'maintenance' | 'disabled' | string; | ||
| currency: string; | ||
| billing_unit: string; | ||
| billing_strategy: string; | ||
| unit_price_cents: number | null; | ||
| input_price_per_1m_cents: number | null; | ||
| output_price_per_1m_cents: number | null; | ||
| cache_read_price_per_1m_cents: number | null; | ||
| cache_write_5m_price_per_1m_cents: number | null; | ||
| cache_write_1h_price_per_1m_cents: number | null; | ||
| billing_config: Record<string, unknown>; | ||
| } | ||
| interface PriceScheduleListResponse { | ||
| as_of: string; | ||
| price_schedules: PriceSchedule[]; | ||
| /** HTTP ETag for revalidating this schedule on a later request. */ | ||
| etag?: string; | ||
| } | ||
| interface PriceScheduleNotModifiedResponse { | ||
| not_modified: true; | ||
| etag?: string; | ||
| } | ||
| type PriceScheduleListResult = PriceScheduleListResponse | PriceScheduleNotModifiedResponse; | ||
| interface PriceQuoteParams { | ||
| service: string; | ||
| action: string; | ||
| model?: string | null; | ||
| params?: Record<string, unknown>; | ||
| } | ||
| interface PriceQuoteResponse { | ||
| service: string; | ||
| action: string; | ||
| model: string | null; | ||
| pricing_status: 'available' | string; | ||
| currency: string; | ||
| reservation_amount_cents: number; | ||
| estimate_basis: string; | ||
| as_of: string; | ||
| } | ||
| /** Live Price Schedule lookup and request-specific Price Quote operations. */ | ||
| declare class Pricing { | ||
| private readonly http; | ||
| constructor(http: HttpClient); | ||
| list(filters?: PriceScheduleFilters, options?: RequestOptions): Promise<PriceScheduleListResult>; | ||
| quote(params: PriceQuoteParams, options?: RequestOptions): Promise<PriceQuoteResponse>; | ||
| } | ||
| /** Standalone live Pricing client with optional API authentication. */ | ||
| declare class PricingClient extends Pricing { | ||
| constructor(options?: ClientOptions); | ||
| } | ||
| /** | ||
| * Base class for every RunAPI client. Resolves the API key, builds the shared | ||
| * HTTP client, and exposes the Universal Resources (file upload, account) that | ||
| * are available on any client regardless of which model package was imported. | ||
| * Base class for RunAPI Provider Clients. Resolves the API key, builds the | ||
| * shared HTTP client, and exposes the Universal Resources (file upload, | ||
| * account, pricing) that are available on any client regardless of which model | ||
| * package was imported. | ||
| * | ||
@@ -255,2 +323,4 @@ * Provider clients extend this and build their model resources from `this.http`. | ||
| readonly account: Account; | ||
| /** Live Price Schedule lookup and Price Quote operations. */ | ||
| readonly pricing: Pricing; | ||
| protected readonly http: HttpClient; | ||
@@ -264,2 +334,2 @@ private readonly apiKey; | ||
| export { Account, type AccountBalanceResponse, type AccountInfoResponse, type ActionSchema, AuthenticationError, BaseClient, ClientOptions, DEFAULT_BASE_URL, type FileCreateParams, type FileSource, type FileUploadResponse, Files, type HttpClient, HttpMethod, type HttpRequestOptions, InsufficientCreditsError, NetworkError, NotFoundError, QueryParams, RETRY_CONFIG, RateLimitError, RequestOptions, type RetryOptions, RunApiError, type RunApiErrorOptions, SDK_USER_AGENT, ServiceUnavailableError, TIMEOUTS, TaskFailedError, TaskTimeoutError, TimeoutError, ValidationError, compactParams, createHttpClient, errorFromResponse, getRetryDelayMs, isIdempotentMethod, isRetryableStatus, parseRetryAfterMs, resolveApiKey, validateParams, version }; | ||
| export { Account, type AccountBalanceResponse, type AccountInfoResponse, type ActionSchema, AuthenticationError, BaseClient, ClientOptions, DEFAULT_BASE_URL, type FileCreateParams, type FileSource, type FileUploadResponse, Files, type HttpClient, HttpMethod, type HttpRequestOptions, InsufficientCreditsError, NetworkError, NotFoundError, type PriceQuoteParams, type PriceQuoteResponse, type PriceSchedule, type PriceScheduleFilters, type PriceScheduleListResponse, type PriceScheduleListResult, type PriceScheduleNotModifiedResponse, Pricing, PricingClient, QueryParams, RETRY_CONFIG, RateLimitError, RequestOptions, type RetryOptions, RunApiError, type RunApiErrorOptions, SDK_USER_AGENT, ServiceUnavailableError, TIMEOUTS, TaskFailedError, TaskTimeoutError, TimeoutError, ValidationError, compactParams, createHttpClient, errorFromResponse, getRetryDelayMs, isIdempotentMethod, isRetryableStatus, parseRetryAfterMs, resolveApiKey, resolveOptionalApiKey, validateParams, version }; |
+76
-6
@@ -1,3 +0,3 @@ | ||
| import { C as ClientOptions, H as HttpMethod, R as RequestOptions, Q as QueryParams } from './types-B4_rq_8F.js'; | ||
| export { A as AsyncTaskStatus, P as PollingOptions, T as TaskResponse, a as TaskStatus } from './types-B4_rq_8F.js'; | ||
| import { C as ClientOptions, H as HttpMethod, R as RequestOptions, Q as QueryParams } from './types-ClO2hfPY.js'; | ||
| export { A as AsyncTaskStatus, P as PollingOptions, T as TaskBillingFacts, a as TaskBillingResponse, b as TaskRefund, c as TaskReservation, d as TaskResponse, e as TaskSettlement, f as TaskStatus } from './types-ClO2hfPY.js'; | ||
@@ -139,2 +139,4 @@ /** | ||
| declare function resolveApiKey(options: ClientOptions): string; | ||
| /** Resolve an API key when present without requiring one for public resources. */ | ||
| declare function resolveOptionalApiKey(options: ClientOptions): string | undefined; | ||
@@ -144,2 +146,6 @@ interface HttpRequestOptions extends RequestOptions { | ||
| body?: unknown; | ||
| /** Treat HTTP 304 as a successful conditional request result. */ | ||
| allowNotModified?: boolean; | ||
| /** Internal response-header capture for resources that support HTTP revalidation. */ | ||
| captureResponseHeaders?: Record<string, string>; | ||
| } | ||
@@ -242,6 +248,68 @@ interface HttpClient { | ||
| interface PriceScheduleFilters extends QueryParams { | ||
| service?: string; | ||
| action?: string; | ||
| model?: string; | ||
| } | ||
| interface PriceSchedule { | ||
| service: string; | ||
| action: string; | ||
| model: string | null; | ||
| pricing_status: 'available' | 'pending' | string; | ||
| catalog_status: 'active' | 'maintenance' | 'disabled' | string; | ||
| currency: string; | ||
| billing_unit: string; | ||
| billing_strategy: string; | ||
| unit_price_cents: number | null; | ||
| input_price_per_1m_cents: number | null; | ||
| output_price_per_1m_cents: number | null; | ||
| cache_read_price_per_1m_cents: number | null; | ||
| cache_write_5m_price_per_1m_cents: number | null; | ||
| cache_write_1h_price_per_1m_cents: number | null; | ||
| billing_config: Record<string, unknown>; | ||
| } | ||
| interface PriceScheduleListResponse { | ||
| as_of: string; | ||
| price_schedules: PriceSchedule[]; | ||
| /** HTTP ETag for revalidating this schedule on a later request. */ | ||
| etag?: string; | ||
| } | ||
| interface PriceScheduleNotModifiedResponse { | ||
| not_modified: true; | ||
| etag?: string; | ||
| } | ||
| type PriceScheduleListResult = PriceScheduleListResponse | PriceScheduleNotModifiedResponse; | ||
| interface PriceQuoteParams { | ||
| service: string; | ||
| action: string; | ||
| model?: string | null; | ||
| params?: Record<string, unknown>; | ||
| } | ||
| interface PriceQuoteResponse { | ||
| service: string; | ||
| action: string; | ||
| model: string | null; | ||
| pricing_status: 'available' | string; | ||
| currency: string; | ||
| reservation_amount_cents: number; | ||
| estimate_basis: string; | ||
| as_of: string; | ||
| } | ||
| /** Live Price Schedule lookup and request-specific Price Quote operations. */ | ||
| declare class Pricing { | ||
| private readonly http; | ||
| constructor(http: HttpClient); | ||
| list(filters?: PriceScheduleFilters, options?: RequestOptions): Promise<PriceScheduleListResult>; | ||
| quote(params: PriceQuoteParams, options?: RequestOptions): Promise<PriceQuoteResponse>; | ||
| } | ||
| /** Standalone live Pricing client with optional API authentication. */ | ||
| declare class PricingClient extends Pricing { | ||
| constructor(options?: ClientOptions); | ||
| } | ||
| /** | ||
| * Base class for every RunAPI client. Resolves the API key, builds the shared | ||
| * HTTP client, and exposes the Universal Resources (file upload, account) that | ||
| * are available on any client regardless of which model package was imported. | ||
| * Base class for RunAPI Provider Clients. Resolves the API key, builds the | ||
| * shared HTTP client, and exposes the Universal Resources (file upload, | ||
| * account, pricing) that are available on any client regardless of which model | ||
| * package was imported. | ||
| * | ||
@@ -255,2 +323,4 @@ * Provider clients extend this and build their model resources from `this.http`. | ||
| readonly account: Account; | ||
| /** Live Price Schedule lookup and Price Quote operations. */ | ||
| readonly pricing: Pricing; | ||
| protected readonly http: HttpClient; | ||
@@ -264,2 +334,2 @@ private readonly apiKey; | ||
| export { Account, type AccountBalanceResponse, type AccountInfoResponse, type ActionSchema, AuthenticationError, BaseClient, ClientOptions, DEFAULT_BASE_URL, type FileCreateParams, type FileSource, type FileUploadResponse, Files, type HttpClient, HttpMethod, type HttpRequestOptions, InsufficientCreditsError, NetworkError, NotFoundError, QueryParams, RETRY_CONFIG, RateLimitError, RequestOptions, type RetryOptions, RunApiError, type RunApiErrorOptions, SDK_USER_AGENT, ServiceUnavailableError, TIMEOUTS, TaskFailedError, TaskTimeoutError, TimeoutError, ValidationError, compactParams, createHttpClient, errorFromResponse, getRetryDelayMs, isIdempotentMethod, isRetryableStatus, parseRetryAfterMs, resolveApiKey, validateParams, version }; | ||
| export { Account, type AccountBalanceResponse, type AccountInfoResponse, type ActionSchema, AuthenticationError, BaseClient, ClientOptions, DEFAULT_BASE_URL, type FileCreateParams, type FileSource, type FileUploadResponse, Files, type HttpClient, HttpMethod, type HttpRequestOptions, InsufficientCreditsError, NetworkError, NotFoundError, type PriceQuoteParams, type PriceQuoteResponse, type PriceSchedule, type PriceScheduleFilters, type PriceScheduleListResponse, type PriceScheduleListResult, type PriceScheduleNotModifiedResponse, Pricing, PricingClient, QueryParams, RETRY_CONFIG, RateLimitError, RequestOptions, type RetryOptions, RunApiError, type RunApiErrorOptions, SDK_USER_AGENT, ServiceUnavailableError, TIMEOUTS, TaskFailedError, TaskTimeoutError, TimeoutError, ValidationError, compactParams, createHttpClient, errorFromResponse, getRetryDelayMs, isIdempotentMethod, isRetryableStatus, parseRetryAfterMs, resolveApiKey, resolveOptionalApiKey, validateParams, version }; |
+63
-5
@@ -31,2 +31,4 @@ "use strict"; | ||
| NotFoundError: () => NotFoundError, | ||
| Pricing: () => Pricing, | ||
| PricingClient: () => PricingClient, | ||
| RETRY_CONFIG: () => RETRY_CONFIG, | ||
@@ -50,2 +52,3 @@ RateLimitError: () => RateLimitError, | ||
| resolveApiKey: () => resolveApiKey, | ||
| resolveOptionalApiKey: () => resolveOptionalApiKey, | ||
| validateParams: () => validateParams, | ||
@@ -367,4 +370,3 @@ version: () => version | ||
| function resolveApiKey(options) { | ||
| const explicit = options.apiKey?.trim(); | ||
| const apiKey = explicit || readApiKeyFromEnv(); | ||
| const apiKey = resolveOptionalApiKey(options); | ||
| if (!apiKey) { | ||
@@ -377,2 +379,6 @@ throw new AuthenticationError( | ||
| } | ||
| function resolveOptionalApiKey(options) { | ||
| const explicit = options.apiKey?.trim(); | ||
| return explicit || readApiKeyFromEnv(); | ||
| } | ||
@@ -476,3 +482,3 @@ // src/http.ts | ||
| function createHttpClient(options) { | ||
| const apiKey = resolveApiKey(options); | ||
| const apiKey = resolveOptionalApiKey(options); | ||
| const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL; | ||
@@ -491,4 +497,4 @@ const clientTimeoutMs = options.timeoutMs; | ||
| accept: "application/json", | ||
| authorization: `Bearer ${apiKey}`, | ||
| "user-agent": SDK_USER_AGENT | ||
| "user-agent": SDK_USER_AGENT, | ||
| ...apiKey ? { authorization: `Bearer ${apiKey}` } : {} | ||
| }, | ||
@@ -516,2 +522,9 @@ requestOptions.headers | ||
| const { text, json } = await parseResponseBody(response); | ||
| if (response.status === 304 && requestOptions.allowNotModified) { | ||
| captureResponseHeaders(response, requestOptions.captureResponseHeaders); | ||
| return { | ||
| not_modified: true, | ||
| etag: response.headers.get("etag") ?? void 0 | ||
| }; | ||
| } | ||
| if (!response.ok) { | ||
@@ -526,2 +539,3 @@ if (attempt < requestMaxRetries && shouldRetryRequest(method, response.status)) { | ||
| } | ||
| captureResponseHeaders(response, requestOptions.captureResponseHeaders); | ||
| return json ?? text; | ||
@@ -591,2 +605,8 @@ } catch (error) { | ||
| } | ||
| function captureResponseHeaders(response, target) { | ||
| if (!target) return; | ||
| response.headers.forEach((value, key) => { | ||
| target[key] = value; | ||
| }); | ||
| } | ||
@@ -983,2 +1003,34 @@ // src/params.ts | ||
| // src/pricing.ts | ||
| var SCHEDULES_ENDPOINT = "/api/v1/price_schedules"; | ||
| var QUOTES_ENDPOINT = "/api/v1/price_quotes"; | ||
| var Pricing = class { | ||
| constructor(http) { | ||
| this.http = http; | ||
| } | ||
| http; | ||
| async list(filters = {}, options) { | ||
| const responseHeaders = {}; | ||
| const result = await this.http.request("GET", SCHEDULES_ENDPOINT, { | ||
| ...options, | ||
| query: filters, | ||
| allowNotModified: true, | ||
| captureResponseHeaders: responseHeaders | ||
| }); | ||
| return "not_modified" in result ? result : { ...result, etag: responseHeaders.etag }; | ||
| } | ||
| async quote(params, options) { | ||
| const response = await this.http.request("POST", QUOTES_ENDPOINT, { | ||
| ...options, | ||
| body: params | ||
| }); | ||
| return response.price_quote; | ||
| } | ||
| }; | ||
| var PricingClient = class extends Pricing { | ||
| constructor(options = {}) { | ||
| super(createHttpClient(options)); | ||
| } | ||
| }; | ||
| // src/base-client.ts | ||
@@ -990,2 +1042,4 @@ var BaseClient = class { | ||
| account; | ||
| /** Live Price Schedule lookup and Price Quote operations. */ | ||
| pricing; | ||
| http; | ||
@@ -998,2 +1052,3 @@ apiKey; | ||
| this.account = new Account(this.http); | ||
| this.pricing = new Pricing(this.http); | ||
| } | ||
@@ -1017,2 +1072,4 @@ getApiKey() { | ||
| NotFoundError, | ||
| Pricing, | ||
| PricingClient, | ||
| RETRY_CONFIG, | ||
@@ -1036,2 +1093,3 @@ RateLimitError, | ||
| resolveApiKey, | ||
| resolveOptionalApiKey, | ||
| validateParams, | ||
@@ -1038,0 +1096,0 @@ version |
+60
-5
@@ -34,4 +34,3 @@ import { | ||
| function resolveApiKey(options) { | ||
| const explicit = options.apiKey?.trim(); | ||
| const apiKey = explicit || readApiKeyFromEnv(); | ||
| const apiKey = resolveOptionalApiKey(options); | ||
| if (!apiKey) { | ||
@@ -44,2 +43,6 @@ throw new AuthenticationError( | ||
| } | ||
| function resolveOptionalApiKey(options) { | ||
| const explicit = options.apiKey?.trim(); | ||
| return explicit || readApiKeyFromEnv(); | ||
| } | ||
@@ -143,3 +146,3 @@ // src/http.ts | ||
| function createHttpClient(options) { | ||
| const apiKey = resolveApiKey(options); | ||
| const apiKey = resolveOptionalApiKey(options); | ||
| const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL; | ||
@@ -158,4 +161,4 @@ const clientTimeoutMs = options.timeoutMs; | ||
| accept: "application/json", | ||
| authorization: `Bearer ${apiKey}`, | ||
| "user-agent": SDK_USER_AGENT | ||
| "user-agent": SDK_USER_AGENT, | ||
| ...apiKey ? { authorization: `Bearer ${apiKey}` } : {} | ||
| }, | ||
@@ -183,2 +186,9 @@ requestOptions.headers | ||
| const { text, json } = await parseResponseBody(response); | ||
| if (response.status === 304 && requestOptions.allowNotModified) { | ||
| captureResponseHeaders(response, requestOptions.captureResponseHeaders); | ||
| return { | ||
| not_modified: true, | ||
| etag: response.headers.get("etag") ?? void 0 | ||
| }; | ||
| } | ||
| if (!response.ok) { | ||
@@ -193,2 +203,3 @@ if (attempt < requestMaxRetries && shouldRetryRequest(method, response.status)) { | ||
| } | ||
| captureResponseHeaders(response, requestOptions.captureResponseHeaders); | ||
| return json ?? text; | ||
@@ -258,2 +269,8 @@ } catch (error) { | ||
| } | ||
| function captureResponseHeaders(response, target) { | ||
| if (!target) return; | ||
| response.headers.forEach((value, key) => { | ||
| target[key] = value; | ||
| }); | ||
| } | ||
@@ -650,2 +667,34 @@ // src/params.ts | ||
| // src/pricing.ts | ||
| var SCHEDULES_ENDPOINT = "/api/v1/price_schedules"; | ||
| var QUOTES_ENDPOINT = "/api/v1/price_quotes"; | ||
| var Pricing = class { | ||
| constructor(http) { | ||
| this.http = http; | ||
| } | ||
| http; | ||
| async list(filters = {}, options) { | ||
| const responseHeaders = {}; | ||
| const result = await this.http.request("GET", SCHEDULES_ENDPOINT, { | ||
| ...options, | ||
| query: filters, | ||
| allowNotModified: true, | ||
| captureResponseHeaders: responseHeaders | ||
| }); | ||
| return "not_modified" in result ? result : { ...result, etag: responseHeaders.etag }; | ||
| } | ||
| async quote(params, options) { | ||
| const response = await this.http.request("POST", QUOTES_ENDPOINT, { | ||
| ...options, | ||
| body: params | ||
| }); | ||
| return response.price_quote; | ||
| } | ||
| }; | ||
| var PricingClient = class extends Pricing { | ||
| constructor(options = {}) { | ||
| super(createHttpClient(options)); | ||
| } | ||
| }; | ||
| // src/base-client.ts | ||
@@ -657,2 +706,4 @@ var BaseClient = class { | ||
| account; | ||
| /** Live Price Schedule lookup and Price Quote operations. */ | ||
| pricing; | ||
| http; | ||
@@ -665,2 +716,3 @@ apiKey; | ||
| this.account = new Account(this.http); | ||
| this.pricing = new Pricing(this.http); | ||
| } | ||
@@ -683,2 +735,4 @@ getApiKey() { | ||
| NotFoundError, | ||
| Pricing, | ||
| PricingClient, | ||
| RETRY_CONFIG, | ||
@@ -702,2 +756,3 @@ RateLimitError, | ||
| resolveApiKey, | ||
| resolveOptionalApiKey, | ||
| validateParams, | ||
@@ -704,0 +759,0 @@ version |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../src/auth.ts","../src/http.ts","../src/params.ts","../src/validate.ts","../src/md5.ts","../src/files.ts","../src/account.ts","../src/base-client.ts","../src/index.ts"],"sourcesContent":["import { AuthenticationError } from './errors';\nimport type { ClientOptions } from './types';\n\nconst ENV_VAR_NAME = 'RUNAPI_API_KEY';\n\nfunction readApiKeyFromEnv(): string | undefined {\n if (typeof process === 'undefined' || !process.env) {\n return undefined;\n }\n const trimmed = process.env[ENV_VAR_NAME]?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Resolve the API key from explicit options or the `RUNAPI_API_KEY` environment\n * variable. Throws `AuthenticationError` when neither is provided.\n */\nexport function resolveApiKey(options: ClientOptions): string {\n const explicit = options.apiKey?.trim();\n const apiKey = explicit || readApiKeyFromEnv();\n if (!apiKey) {\n throw new AuthenticationError(\n `API key is required. Pass \\`apiKey\\` or set the \\`${ENV_VAR_NAME}\\` environment variable.`\n );\n }\n return apiKey;\n}\n","import { resolveApiKey } from './auth';\nimport {\n errorFromResponse,\n NetworkError,\n RunApiError,\n TimeoutError,\n} from './errors';\nimport {\n getRetryDelayMs,\n isIdempotentMethod,\n isRetryableStatus,\n parseRetryAfterMs,\n} from './retry';\nimport type { ClientOptions, HttpMethod, QueryParams, RequestOptions } from './types';\nimport {\n DEFAULT_BASE_URL,\n RETRY_CONFIG,\n SDK_USER_AGENT,\n TIMEOUTS,\n} from './constants';\n\nexport interface HttpRequestOptions extends RequestOptions {\n query?: QueryParams;\n body?: unknown;\n}\n\nexport interface HttpClient {\n request<T>(\n method: HttpMethod,\n path: string,\n options?: HttpRequestOptions\n ): Promise<T>;\n /**\n * PUT bytes straight to an absolute upload URL with the exact headers issued\n * for it. Skips the base URL, auth, and retries — the URL is single-use and\n * pre-authorized, and the body is not safe to replay.\n */\n upload(\n url: string,\n options: { headers: Record<string, string>; body: BodyInit; timeoutMs?: number; signal?: AbortSignal }\n ): Promise<void>;\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: QueryParams): string {\n const normalizedBase = baseUrl.replace(/\\/+$/, '');\n const normalizedPath = path.startsWith('/') ? path : `/${path}`;\n const url = new URL(`${normalizedBase}${normalizedPath}`);\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n url.searchParams.set(key, String(value));\n }\n }\n\n return url.toString();\n}\n\nfunction mergeHeaders(\n base: Record<string, string>,\n extra?: Record<string, string>\n): Record<string, string> {\n return { ...base, ...(extra || {}) };\n}\n\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n const target = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === target);\n}\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== 'undefined' && body instanceof FormData;\n}\n\nfunction prepareBody(body: unknown, headers: Record<string, string>): BodyInit | undefined {\n if (body === undefined || body === null) {\n return undefined;\n }\n\n if (isFormData(body) || body instanceof URLSearchParams) {\n return body as BodyInit;\n }\n\n if (typeof body === 'string' || body instanceof Blob || body instanceof ArrayBuffer) {\n return body as BodyInit;\n }\n\n if (!hasHeader(headers, 'content-type')) {\n headers['content-type'] = 'application/json';\n }\n\n return JSON.stringify(body);\n}\n\nasync function parseResponseBody(response: Response): Promise<{\n text: string | null;\n json: unknown;\n}> {\n const text = await response.text();\n if (!text) {\n return { text: null, json: undefined };\n }\n\n try {\n return { text, json: JSON.parse(text) };\n } catch {\n return { text, json: undefined };\n }\n}\n\nfunction createAbortController(\n timeoutMs: number,\n signal?: AbortSignal\n): { controller: AbortController; cleanup: () => void; timedOut: () => boolean } {\n const controller = new AbortController();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let didTimeOut = false;\n\n if (signal) {\n if (signal.aborted) {\n controller.abort();\n } else {\n signal.addEventListener(\n 'abort',\n () => {\n controller.abort();\n },\n { once: true }\n );\n }\n }\n\n if (timeoutMs > 0) {\n timeoutId = setTimeout(() => {\n didTimeOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n return {\n controller,\n cleanup: () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n },\n timedOut: () => didTimeOut,\n };\n}\n\nfunction shouldRetryRequest(method: HttpMethod, status: number | undefined): boolean {\n if (status === undefined) {\n return false;\n }\n\n if (!isRetryableStatus(status)) {\n return false;\n }\n\n if (isIdempotentMethod(method)) {\n return true;\n }\n\n return false;\n}\n\nexport function createHttpClient(options: ClientOptions): HttpClient {\n const apiKey = resolveApiKey(options);\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const clientTimeoutMs = options.timeoutMs;\n const maxRetries = options.maxRetries ?? RETRY_CONFIG.MAX_RETRIES;\n const retryBaseDelayMs = options.retryBaseDelayMs ?? RETRY_CONFIG.BASE_DELAY;\n const retryMaxDelayMs = options.retryMaxDelayMs ?? RETRY_CONFIG.MAX_DELAY;\n const fetchImpl = options.fetch ?? fetch;\n const clientFetchOptions = options.fetchOptions ?? {};\n\n return {\n async request<T>(\n method: HttpMethod,\n path: string,\n requestOptions: HttpRequestOptions = {}\n ) {\n const url = buildUrl(baseUrl, path, requestOptions.query);\n const headers = mergeHeaders(\n {\n accept: 'application/json',\n authorization: `Bearer ${apiKey}`,\n 'user-agent': SDK_USER_AGENT,\n },\n requestOptions.headers\n );\n\n const body = prepareBody(requestOptions.body, headers);\n const requestTimeoutMs = requestOptions.timeoutMs ?? clientTimeoutMs ?? TIMEOUTS.HTTP_REQUEST;\n const requestMaxRetries = requestOptions.maxRetries ?? maxRetries;\n\n for (let attempt = 0; attempt <= requestMaxRetries; attempt += 1) {\n const { controller, cleanup, timedOut } = createAbortController(\n requestTimeoutMs,\n requestOptions.signal\n );\n\n try {\n const response = await fetchImpl(url, {\n ...clientFetchOptions,\n ...(requestOptions.fetchOptions ?? {}),\n method,\n headers,\n body,\n signal: controller.signal,\n });\n\n cleanup();\n\n const { text, json } = await parseResponseBody(response);\n\n if (!response.ok) {\n if (\n attempt < requestMaxRetries &&\n shouldRetryRequest(method, response.status)\n ) {\n const retryAfterMs = parseRetryAfterMs(response);\n const delayMs =\n retryAfterMs ??\n getRetryDelayMs(attempt, retryBaseDelayMs, retryMaxDelayMs);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n continue;\n }\n\n throw errorFromResponse(response, text, json);\n }\n\n return (json ?? text) as T;\n } catch (error) {\n cleanup();\n\n if (timedOut()) {\n if (attempt < requestMaxRetries && isIdempotentMethod(method)) {\n const delayMs = getRetryDelayMs(\n attempt,\n retryBaseDelayMs,\n retryMaxDelayMs\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n continue;\n }\n\n throw new TimeoutError('Request timed out');\n }\n\n if (requestOptions.signal?.aborted) {\n throw new RunApiError('Request aborted', { cause: error as Error });\n }\n\n if (error instanceof RunApiError) {\n throw error;\n }\n\n if (attempt < requestMaxRetries && isIdempotentMethod(method)) {\n const delayMs = getRetryDelayMs(\n attempt,\n retryBaseDelayMs,\n retryMaxDelayMs\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n continue;\n }\n\n throw new NetworkError('Network error', { cause: error as Error });\n }\n }\n\n // Unreachable at runtime, but required for TypeScript return type inference\n throw new NetworkError('Network error');\n },\n\n async upload(url, uploadOptions) {\n const timeoutMs = uploadOptions.timeoutMs ?? clientTimeoutMs ?? TIMEOUTS.HTTP_REQUEST;\n const { controller, cleanup, timedOut } = createAbortController(timeoutMs, uploadOptions.signal);\n\n try {\n const response = await fetchImpl(url, {\n ...clientFetchOptions,\n method: 'PUT',\n headers: uploadOptions.headers,\n body: uploadOptions.body,\n signal: controller.signal,\n });\n cleanup();\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new RunApiError(`Direct upload failed with status ${response.status}${text ? `: ${text}` : ''}`);\n }\n } catch (error) {\n cleanup();\n if (timedOut()) {\n throw new TimeoutError('Direct upload timed out');\n }\n if (error instanceof RunApiError) {\n throw error;\n }\n throw new NetworkError('Direct upload network error', { cause: error as Error });\n }\n },\n };\n}\n","export function compactParams<T extends object>(params: T): Partial<T> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n if (typeof value === 'string' && value.trim() === '') continue;\n result[key] = value;\n }\n return result as Partial<T>;\n}\n","import { ValidationError } from './errors';\n\n/** One action entry from a package's generated contract. */\nexport interface ActionSchema {\n models?: readonly string[];\n rules?: readonly Record<string, any>[];\n fields_by_model?: Record<string, Record<string, any>>;\n}\n\ntype Params = Record<string, unknown>;\n\n/**\n * Validates request params against a generated action schema: model\n * membership, then declared cross-field rules, then per-field\n * required/enum/integer/min/max/length. A missing schema is a no-op.\n */\nexport function validateParams(schema: ActionSchema | undefined, params: Params): void {\n if (!schema) return;\n\n const model = params['model'];\n const models = schema.models ?? [];\n let fields: Record<string, any>;\n if (models.length === 0) {\n fields = schema.fields_by_model?.['_'] ?? {};\n } else {\n if (typeof model !== 'string' || !models.includes(model)) {\n const sorted = [...models].sort();\n throw new ValidationError(`model must be one of: ${sorted.join(', ')}`);\n }\n\n fields = schema.fields_by_model?.[model] ?? {};\n }\n\n const rules = schema.rules;\n if (Array.isArray(rules)) {\n for (const rule of rules) enforceContractRule(params, rule);\n }\n\n const keys = Object.keys(fields).sort();\n for (const field of keys) {\n validateSchemaField(params, field, fields[field]);\n }\n}\n\nfunction validateSchemaField(params: Params, field: string, rules: Record<string, any>): void {\n const value = params[field];\n if (value != null && ('min_items' in rules || 'max_items' in rules)) {\n validateSchemaItemCount(field, value, rules);\n }\n\n const present = fieldPresent(params, field);\n if (rules.required && !present) {\n throw new ValidationError(`${field} is required`);\n }\n if (!present) return;\n\n if (rules.enum !== undefined && !enumValueAllowed(rules.enum, value)) {\n throw new ValidationError(`${field} must be one of: ${formatEnumValues(rules.enum)}`);\n }\n\n if (rules.type === 'integer') {\n validateSchemaInteger(field, value, rules);\n }\n\n if ('min' in rules || 'max' in rules) {\n validateSchemaRange(field, value, rules);\n }\n}\n\nfunction validateSchemaItemCount(field: string, value: unknown, rules: Record<string, any>): void {\n if (!Array.isArray(value)) {\n throw new ValidationError(`${field} must be an array`);\n }\n\n const min = rules.min_items;\n const max = rules.max_items;\n if ((min == null || value.length >= min) && (max == null || value.length <= max)) return;\n throw new ValidationError(itemCountMessage(field, min, max));\n}\n\nfunction itemCountMessage(field: string, min: unknown, max: unknown): string {\n if (min != null && max != null) {\n return `${field} must contain between ${formatValue(min)} and ${formatValue(max)} items`;\n }\n if (min != null) {\n return `${field} must contain at least ${formatValue(min)} items`;\n }\n return `${field} must contain at most ${formatValue(max)} items`;\n}\n\n// Mirrors GatewayEntry#validate_schema_integer!: a type: integer field rejects\n// non-integer numbers (e.g. 11.5), which min/max alone admit. JS has no integer\n// type, so whole-valued floats count — they serialize to an integer on the wire.\nfunction validateSchemaInteger(field: string, value: unknown, rules: Record<string, any>): void {\n if (typeof value === 'number' && Number.isInteger(value)) return;\n const detail =\n rules.min != null && rules.max != null\n ? ` between ${formatValue(rules.min)} and ${formatValue(rules.max)}`\n : '';\n throw new ValidationError(`${field} must be an integer${detail}`);\n}\n\nfunction validateSchemaRange(field: string, value: unknown, rules: Record<string, any>): void {\n let measured: number;\n let unit: string | null;\n if (rules.length) {\n measured = [...String(value)].length;\n unit = 'characters';\n } else {\n if (typeof value !== 'number') {\n throw new ValidationError(`${field} must be a number`);\n }\n measured = value;\n unit = null;\n }\n\n const min = rules.min;\n const max = rules.max;\n if ((min == null || measured >= min) && (max == null || measured <= max)) return;\n throw new ValidationError(rangeMessage(field, min, max, unit));\n}\n\nfunction rangeMessage(field: string, min: unknown, max: unknown, unit: string | null): string {\n const suffix = unit ? ` ${unit}` : '';\n if (min != null && max != null) {\n return `${field} must be between ${formatValue(min)} and ${formatValue(max)}${suffix}`;\n }\n if (min != null) {\n return `${field} must be at least ${formatValue(min)}${suffix}`;\n }\n return `${field} must be at most ${formatValue(max)}${suffix}`;\n}\n\nfunction enumValueAllowed(enumValues: readonly unknown[], value: unknown): boolean {\n const valueIsNum = typeof value === 'number';\n for (const allowed of enumValues) {\n const allowedIsNum = typeof allowed === 'number';\n if (allowedIsNum) {\n if (valueIsNum && value === allowed) return true;\n } else if (valueIsNum) {\n // allowed non-numeric while value is numeric never matches.\n } else if (String(allowed) === String(value)) {\n return true;\n }\n }\n return false;\n}\n\nfunction enforceContractRule(params: Params, rule: Record<string, any>): void {\n const conditions: Record<string, unknown> = rule.when ?? {};\n const keys = Object.keys(conditions);\n for (const key of keys) {\n if (!ruleConditionMet(params, key, conditions[key])) return;\n }\n\n const context = keys.map((key) => `${key} is ${formatValue(conditions[key])}`).join(' and ');\n for (const field of rule.required ?? []) {\n if (!fieldPresent(params, field)) {\n throw new ValidationError(`${field} is required when ${context}`);\n }\n }\n for (const field of rule.forbidden ?? []) {\n if (fieldPresent(params, field)) {\n throw new ValidationError(`${field} is not allowed when ${context}`);\n }\n }\n}\n\nfunction ruleConditionMet(params: Params, field: string, value: unknown): boolean {\n if (!(field in params)) return false;\n return String(params[field]) === String(value);\n}\n\nfunction fieldPresent(params: Params, field: string): boolean {\n if (!(field in params)) return false;\n const value = params[field];\n if (value === false) return true;\n if (Array.isArray(value)) return value.some(presentValue);\n return presentValue(value);\n}\n\nfunction presentValue(value: unknown): boolean {\n if (value === null || value === undefined || value === false) return false;\n if (value === true) return true;\n if (typeof value === 'string') return value.trim() !== '';\n if (Array.isArray(value)) return value.length > 0;\n if (typeof value === 'object') return Object.keys(value).length > 0;\n return true;\n}\n\nfunction formatValue(value: unknown): string {\n return typeof value === 'string' ? value : String(value);\n}\n\n// JS collapses float literals (0.0 -> 0), losing the float type the other SDKs\n// keep. When an enum has a fractional member it is a float enum, so render its\n// whole-number members with a trailing .0 to match the gateway/Go/Ruby/Python\n// message text (e.g. \"0.0, 0.5, 1.0\", not \"0, 0.5, 1\").\nfunction formatEnumValues(values: readonly unknown[]): string {\n const floatEnum = values.some((v) => typeof v === 'number' && !Number.isInteger(v));\n return values\n .map((v) => (floatEnum && typeof v === 'number' ? formatFloat(v) : formatValue(v)))\n .join(', ');\n}\n\nfunction formatFloat(value: number): string {\n const text = String(value);\n return /[.eE]/.test(text) ? text : `${text}.0`;\n}\n","// RFC 1321 MD5 over raw bytes, returning the Base64 of the 16-byte digest — the\n// value the upload target expects as the Content-MD5 header on a direct-upload\n// PUT. Web Crypto has no MD5, so direct upload needs this pure implementation to\n// run in browsers as well as Node.\n\nconst SHIFTS = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,\n];\n\nconst K = Array.from({ length: 64 }, (_v, i) =>\n Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296),\n);\n\nfunction add32(a: number, b: number): number {\n return (a + b) & 0xffffffff;\n}\n\nfunction rotl(value: number, bits: number): number {\n return (value << bits) | (value >>> (32 - bits));\n}\n\nfunction md5Bytes(input: Uint8Array): Uint8Array {\n const withOne = input.length + 1;\n const totalLen = withOne + ((56 - (withOne % 64) + 64) % 64) + 8;\n const msg = new Uint8Array(totalLen);\n msg.set(input);\n msg[input.length] = 0x80;\n\n const view = new DataView(msg.buffer);\n const bitLen = input.length * 8;\n view.setUint32(totalLen - 8, bitLen >>> 0, true);\n view.setUint32(totalLen - 4, Math.floor(bitLen / 0x100000000) >>> 0, true);\n\n let a0 = 0x67452301;\n let b0 = 0xefcdab89;\n let c0 = 0x98badcfe;\n let d0 = 0x10325476;\n\n const m = new Int32Array(16);\n for (let offset = 0; offset < totalLen; offset += 64) {\n for (let j = 0; j < 16; j += 1) {\n m[j] = view.getUint32(offset + j * 4, true);\n }\n\n let a = a0;\n let b = b0;\n let c = c0;\n let d = d0;\n\n for (let i = 0; i < 64; i += 1) {\n let f: number;\n let g: number;\n if (i < 16) {\n f = (b & c) | (~b & d);\n g = i;\n } else if (i < 32) {\n f = (d & b) | (~d & c);\n g = (5 * i + 1) % 16;\n } else if (i < 48) {\n f = b ^ c ^ d;\n g = (3 * i + 5) % 16;\n } else {\n f = c ^ (b | ~d);\n g = (7 * i) % 16;\n }\n\n f = add32(add32(f, a), add32(K[i], m[g]));\n a = d;\n d = c;\n c = b;\n b = add32(b, rotl(f, SHIFTS[i]));\n }\n\n a0 = add32(a0, a);\n b0 = add32(b0, b);\n c0 = add32(c0, c);\n d0 = add32(d0, d);\n }\n\n const out = new Uint8Array(16);\n const outView = new DataView(out.buffer);\n outView.setUint32(0, a0 >>> 0, true);\n outView.setUint32(4, b0 >>> 0, true);\n outView.setUint32(8, c0 >>> 0, true);\n outView.setUint32(12, d0 >>> 0, true);\n return out;\n}\n\nconst BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let out = '';\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i];\n const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n out += BASE64_CHARS[b0 >> 2];\n out += BASE64_CHARS[((b0 & 3) << 4) | (b1 >> 4)];\n out += i + 1 < bytes.length ? BASE64_CHARS[((b1 & 15) << 2) | (b2 >> 6)] : '=';\n out += i + 2 < bytes.length ? BASE64_CHARS[b2 & 63] : '=';\n }\n return out;\n}\n\nexport function md5Base64(bytes: Uint8Array): string {\n return bytesToBase64(md5Bytes(bytes));\n}\n","import type { HttpClient } from './http';\nimport type { RequestOptions } from './types';\nimport { compactParams } from './params';\nimport { md5Base64 } from './md5';\n\nconst ENDPOINT = '/api/v1/files';\nconst PREPARE_ENDPOINT = `${ENDPOINT}/prepare`;\nconst CONFIRM_ENDPOINT = `${ENDPOINT}/confirm`;\n\ninterface PrepareResponse {\n signed_id: string;\n upload_url: string;\n headers: Record<string, string>;\n}\n\nexport interface FileUploadResponse {\n file_name: string;\n url: string;\n size_bytes: number;\n mime_type: string;\n created_at: string;\n expires_at: string;\n}\n\nexport type FileSource =\n | { type: 'url'; url: string }\n | { type: 'base64'; data: string };\n\nexport type FileCreateParams =\n | {\n file: Blob;\n file_name?: string;\n source?: never;\n }\n | {\n source: FileSource;\n file_name?: string;\n file?: never;\n };\n\nexport class Files {\n constructor(private readonly http: HttpClient) {}\n\n async create(params: FileCreateParams, options?: RequestOptions): Promise<FileUploadResponse> {\n const rawParams = params as { file?: Blob; source?: FileSource; file_name?: string };\n const hasFile = Boolean(rawParams.file);\n const hasSource = Boolean(rawParams.source);\n if (Number(hasFile) + Number(hasSource) !== 1) {\n throw new Error('Exactly one source is required: file or source');\n }\n\n if (hasFile) {\n return this.uploadDirect(rawParams.file as Blob, params.file_name, options);\n }\n\n return this.http.request<FileUploadResponse>('POST', ENDPOINT, {\n body: compactParams(params),\n ...options,\n });\n }\n\n // Local files upload straight to storage: ask for a pre-authorized target,\n // PUT the bytes there (never through the API), then confirm. The caller still\n // sees a single create() call.\n private async uploadDirect(\n file: Blob,\n fileName: string | undefined,\n options?: RequestOptions,\n ): Promise<FileUploadResponse> {\n const bytes = new Uint8Array(await file.arrayBuffer());\n const filename = fileName ?? (file as { name?: string }).name ?? 'upload';\n const contentType = file.type || 'application/octet-stream';\n\n const prepared = await this.http.request<PrepareResponse>('POST', PREPARE_ENDPOINT, {\n body: {\n filename,\n byte_size: bytes.byteLength,\n checksum: md5Base64(bytes),\n content_type: contentType,\n },\n ...options,\n });\n\n await this.http.upload(prepared.upload_url, {\n headers: prepared.headers,\n body: bytes,\n timeoutMs: options?.timeoutMs,\n signal: options?.signal,\n });\n\n return this.http.request<FileUploadResponse>('POST', CONFIRM_ENDPOINT, {\n body: { signed_id: prepared.signed_id },\n ...options,\n });\n }\n}\n","import type { HttpClient } from './http';\nimport type { RequestOptions } from './types';\n\nconst INFO_ENDPOINT = '/api/v1/me';\nconst BALANCE_ENDPOINT = '/api/v1/me/balance';\n\nexport interface AccountInfoResponse {\n id: number;\n name: string;\n email: string;\n account: {\n id: number;\n name: string;\n };\n}\n\nexport interface AccountBalanceResponse {\n balance_cents: number;\n paid_balance_cents: number;\n bonus_balance_cents: number;\n spent_cents_today: number;\n spent_cents_total: number;\n}\n\nexport class Account {\n constructor(private readonly http: HttpClient) {}\n\n async info(options?: RequestOptions): Promise<AccountInfoResponse> {\n return this.http.request<AccountInfoResponse>('GET', INFO_ENDPOINT, { ...options });\n }\n\n async balance(options?: RequestOptions): Promise<AccountBalanceResponse> {\n return this.http.request<AccountBalanceResponse>('GET', BALANCE_ENDPOINT, { ...options });\n }\n}\n","import { createHttpClient, type HttpClient } from './http';\nimport { resolveApiKey } from './auth';\nimport type { ClientOptions } from './types';\nimport { Files } from './files';\nimport { Account } from './account';\n\n/**\n * Base class for every RunAPI client. Resolves the API key, builds the shared\n * HTTP client, and exposes the Universal Resources (file upload, account) that\n * are available on any client regardless of which model package was imported.\n *\n * Provider clients extend this and build their model resources from `this.http`.\n */\nexport class BaseClient {\n /** Temporary file upload operations. */\n public readonly files: Files;\n /** Account info and balance operations. */\n public readonly account: Account;\n\n protected readonly http: HttpClient;\n private readonly apiKey: string;\n\n constructor(options: ClientOptions = {}) {\n this.apiKey = resolveApiKey(options);\n this.http = createHttpClient(options);\n this.files = new Files(this.http);\n this.account = new Account(this.http);\n }\n\n getApiKey() {\n return this.apiKey;\n }\n}\n","// Types\nexport type {\n HttpMethod,\n QueryParams,\n ClientOptions,\n RequestOptions,\n PollingOptions,\n TaskStatus,\n AsyncTaskStatus,\n TaskResponse,\n} from './types';\n\n// Constants\nexport { TIMEOUTS, RETRY_CONFIG, DEFAULT_BASE_URL, SDK_USER_AGENT } from './constants';\n\n// Errors\nexport {\n RunApiError,\n AuthenticationError,\n RateLimitError,\n InsufficientCreditsError,\n NotFoundError,\n ValidationError,\n ServiceUnavailableError,\n NetworkError,\n TimeoutError,\n TaskTimeoutError,\n TaskFailedError,\n errorFromResponse,\n} from './errors';\nexport type { RunApiErrorOptions } from './errors';\n\n// Auth\nexport { resolveApiKey } from './auth';\n\n// HTTP Client\nexport { createHttpClient } from './http';\nexport type { HttpClient, HttpRequestOptions } from './http';\n\n// Retry (高级用户可用)\nexport {\n getRetryDelayMs,\n isRetryableStatus,\n isIdempotentMethod,\n parseRetryAfterMs,\n} from './retry';\nexport type { RetryOptions } from './retry';\n\n// Params\nexport { compactParams } from './params';\n\n// Contract validation\nexport { validateParams } from './validate';\nexport type { ActionSchema } from './validate';\n\n// Files\nexport { Files } from './files';\nexport type { FileCreateParams, FileSource, FileUploadResponse } from './files';\n\n// Account\nexport { Account } from './account';\nexport type { AccountInfoResponse, AccountBalanceResponse } from './account';\n\n// Base client\nexport { BaseClient } from './base-client';\n\n// Version\nexport const version = '0.1.0';\n\n// Note: pollUntilComplete 不从主入口导出,避免 PollingOptions 类型暴露\n// 各 API 包(suno/veo-3-1 等)通过 '@runapi.ai/core/internal' 导入\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAM,eAAe;AAErB,SAAS,oBAAwC;AAC/C,MAAI,OAAO,YAAY,eAAe,CAAC,QAAQ,KAAK;AAClD,WAAO;AAAA,EACT;AACA,QAAM,UAAU,QAAQ,IAAI,YAAY,GAAG,KAAK;AAChD,SAAO,UAAU,UAAU;AAC7B;AAMO,SAAS,cAAc,SAAgC;AAC5D,QAAM,WAAW,QAAQ,QAAQ,KAAK;AACtC,QAAM,SAAS,YAAY,kBAAkB;AAC7C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,qDAAqD,YAAY;AAAA,IACnE;AAAA,EACF;AACA,SAAO;AACT;;;ACiBA,SAAS,SAAS,SAAiB,MAAc,OAA6B;AAC5E,QAAM,iBAAiB,QAAQ,QAAQ,QAAQ,EAAE;AACjD,QAAM,iBAAiB,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI;AAC7D,QAAM,MAAM,IAAI,IAAI,GAAG,cAAc,GAAG,cAAc,EAAE;AAExD,MAAI,OAAO;AACT,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,UAAI,UAAU,UAAa,UAAU,MAAM;AACzC;AAAA,MACF;AACA,UAAI,aAAa,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,IACzC;AAAA,EACF;AAEA,SAAO,IAAI,SAAS;AACtB;AAEA,SAAS,aACP,MACA,OACwB;AACxB,SAAO,EAAE,GAAG,MAAM,GAAI,SAAS,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AS,UAAU;AAAA,MACtC,GAAG;AAAA,IACL,CAAC;AAAA,EACH;AACF;;;AC5FA,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AAoBlB,IAAM,UAAN,MAAc;AAAA,EACnB,YAA6B,MAAkB;AAAlB;AAAA,EAAmB;AAAA,EAAnB;AAAA,EAE7B,MAAM,KAAK,SAAwD;AACjE,WAAO,KAAK,KAAK,QAA6B,OAAO,eAAe,EAAE,GAAG,QAAQ,CAAC;AAAA,EACpF;AAAA,EAEA,MAAM,QAAQ,SAA2D;AACvE,WAAO,KAAK,KAAK,QAAgC,OAAO,kBAAkB,EAAE,GAAG,QAAQ,CAAC;AAAA,EAC1F;AACF;;;ACrBO,IAAM,aAAN,MAAiB;AAAA;AAAA,EAEN;AAAA;AAAA,EAEA;AAAA,EAEG;AAAA,EACF;AAAA,EAEjB,YAAY,UAAyB,CAAC,GAAG;AACvC,SAAK,SAAS,cAAc,OAAO;AACnC,SAAK,OAAO,iBAAiB,OAAO;AACpC,SAAK,QAAQ,IAAI,MAAM,KAAK,IAAI;AAChC,SAAK,UAAU,IAAI,QAAQ,KAAK,IAAI;AAAA,EACtC;AAAA,EAEA,YAAY;AACV,WAAO,KAAK;AAAA,EACd;AACF;;;ACmCO,IAAM,UAAU;","names":[]} | ||
| {"version":3,"sources":["../src/auth.ts","../src/http.ts","../src/params.ts","../src/validate.ts","../src/md5.ts","../src/files.ts","../src/account.ts","../src/pricing.ts","../src/base-client.ts","../src/index.ts"],"sourcesContent":["import { AuthenticationError } from './errors';\nimport type { ClientOptions } from './types';\n\nconst ENV_VAR_NAME = 'RUNAPI_API_KEY';\n\nfunction readApiKeyFromEnv(): string | undefined {\n if (typeof process === 'undefined' || !process.env) {\n return undefined;\n }\n const trimmed = process.env[ENV_VAR_NAME]?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Resolve the API key from explicit options or the `RUNAPI_API_KEY` environment\n * variable. Throws `AuthenticationError` when neither is provided.\n */\nexport function resolveApiKey(options: ClientOptions): string {\n const apiKey = resolveOptionalApiKey(options);\n if (!apiKey) {\n throw new AuthenticationError(\n `API key is required. Pass \\`apiKey\\` or set the \\`${ENV_VAR_NAME}\\` environment variable.`\n );\n }\n return apiKey;\n}\n\n/** Resolve an API key when present without requiring one for public resources. */\nexport function resolveOptionalApiKey(options: ClientOptions): string | undefined {\n const explicit = options.apiKey?.trim();\n return explicit || readApiKeyFromEnv();\n}\n","import { resolveOptionalApiKey } from './auth';\nimport {\n errorFromResponse,\n NetworkError,\n RunApiError,\n TimeoutError,\n} from './errors';\nimport {\n getRetryDelayMs,\n isIdempotentMethod,\n isRetryableStatus,\n parseRetryAfterMs,\n} from './retry';\nimport type { ClientOptions, HttpMethod, QueryParams, RequestOptions } from './types';\nimport {\n DEFAULT_BASE_URL,\n RETRY_CONFIG,\n SDK_USER_AGENT,\n TIMEOUTS,\n} from './constants';\n\nexport interface HttpRequestOptions extends RequestOptions {\n query?: QueryParams;\n body?: unknown;\n /** Treat HTTP 304 as a successful conditional request result. */\n allowNotModified?: boolean;\n /** Internal response-header capture for resources that support HTTP revalidation. */\n captureResponseHeaders?: Record<string, string>;\n}\n\nexport interface HttpClient {\n request<T>(\n method: HttpMethod,\n path: string,\n options?: HttpRequestOptions\n ): Promise<T>;\n /**\n * PUT bytes straight to an absolute upload URL with the exact headers issued\n * for it. Skips the base URL, auth, and retries — the URL is single-use and\n * pre-authorized, and the body is not safe to replay.\n */\n upload(\n url: string,\n options: { headers: Record<string, string>; body: BodyInit; timeoutMs?: number; signal?: AbortSignal }\n ): Promise<void>;\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: QueryParams): string {\n const normalizedBase = baseUrl.replace(/\\/+$/, '');\n const normalizedPath = path.startsWith('/') ? path : `/${path}`;\n const url = new URL(`${normalizedBase}${normalizedPath}`);\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n url.searchParams.set(key, String(value));\n }\n }\n\n return url.toString();\n}\n\nfunction mergeHeaders(\n base: Record<string, string>,\n extra?: Record<string, string>\n): Record<string, string> {\n return { ...base, ...(extra || {}) };\n}\n\nfunction hasHeader(headers: Record<string, string>, name: string): boolean {\n const target = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === target);\n}\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== 'undefined' && body instanceof FormData;\n}\n\nfunction prepareBody(body: unknown, headers: Record<string, string>): BodyInit | undefined {\n if (body === undefined || body === null) {\n return undefined;\n }\n\n if (isFormData(body) || body instanceof URLSearchParams) {\n return body as BodyInit;\n }\n\n if (typeof body === 'string' || body instanceof Blob || body instanceof ArrayBuffer) {\n return body as BodyInit;\n }\n\n if (!hasHeader(headers, 'content-type')) {\n headers['content-type'] = 'application/json';\n }\n\n return JSON.stringify(body);\n}\n\nasync function parseResponseBody(response: Response): Promise<{\n text: string | null;\n json: unknown;\n}> {\n const text = await response.text();\n if (!text) {\n return { text: null, json: undefined };\n }\n\n try {\n return { text, json: JSON.parse(text) };\n } catch {\n return { text, json: undefined };\n }\n}\n\nfunction createAbortController(\n timeoutMs: number,\n signal?: AbortSignal\n): { controller: AbortController; cleanup: () => void; timedOut: () => boolean } {\n const controller = new AbortController();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let didTimeOut = false;\n\n if (signal) {\n if (signal.aborted) {\n controller.abort();\n } else {\n signal.addEventListener(\n 'abort',\n () => {\n controller.abort();\n },\n { once: true }\n );\n }\n }\n\n if (timeoutMs > 0) {\n timeoutId = setTimeout(() => {\n didTimeOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n return {\n controller,\n cleanup: () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n },\n timedOut: () => didTimeOut,\n };\n}\n\nfunction shouldRetryRequest(method: HttpMethod, status: number | undefined): boolean {\n if (status === undefined) {\n return false;\n }\n\n if (!isRetryableStatus(status)) {\n return false;\n }\n\n if (isIdempotentMethod(method)) {\n return true;\n }\n\n return false;\n}\n\nexport function createHttpClient(options: ClientOptions): HttpClient {\n const apiKey = resolveOptionalApiKey(options);\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const clientTimeoutMs = options.timeoutMs;\n const maxRetries = options.maxRetries ?? RETRY_CONFIG.MAX_RETRIES;\n const retryBaseDelayMs = options.retryBaseDelayMs ?? RETRY_CONFIG.BASE_DELAY;\n const retryMaxDelayMs = options.retryMaxDelayMs ?? RETRY_CONFIG.MAX_DELAY;\n const fetchImpl = options.fetch ?? fetch;\n const clientFetchOptions = options.fetchOptions ?? {};\n\n return {\n async request<T>(\n method: HttpMethod,\n path: string,\n requestOptions: HttpRequestOptions = {}\n ) {\n const url = buildUrl(baseUrl, path, requestOptions.query);\n const headers = mergeHeaders(\n {\n accept: 'application/json',\n 'user-agent': SDK_USER_AGENT,\n ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),\n },\n requestOptions.headers\n );\n\n const body = prepareBody(requestOptions.body, headers);\n const requestTimeoutMs = requestOptions.timeoutMs ?? clientTimeoutMs ?? TIMEOUTS.HTTP_REQUEST;\n const requestMaxRetries = requestOptions.maxRetries ?? maxRetries;\n\n for (let attempt = 0; attempt <= requestMaxRetries; attempt += 1) {\n const { controller, cleanup, timedOut } = createAbortController(\n requestTimeoutMs,\n requestOptions.signal\n );\n\n try {\n const response = await fetchImpl(url, {\n ...clientFetchOptions,\n ...(requestOptions.fetchOptions ?? {}),\n method,\n headers,\n body,\n signal: controller.signal,\n });\n\n cleanup();\n\n const { text, json } = await parseResponseBody(response);\n\n if (response.status === 304 && requestOptions.allowNotModified) {\n captureResponseHeaders(response, requestOptions.captureResponseHeaders);\n return {\n not_modified: true,\n etag: response.headers.get('etag') ?? undefined,\n } as T;\n }\n\n if (!response.ok) {\n if (\n attempt < requestMaxRetries &&\n shouldRetryRequest(method, response.status)\n ) {\n const retryAfterMs = parseRetryAfterMs(response);\n const delayMs =\n retryAfterMs ??\n getRetryDelayMs(attempt, retryBaseDelayMs, retryMaxDelayMs);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n continue;\n }\n\n throw errorFromResponse(response, text, json);\n }\n\n captureResponseHeaders(response, requestOptions.captureResponseHeaders);\n return (json ?? text) as T;\n } catch (error) {\n cleanup();\n\n if (timedOut()) {\n if (attempt < requestMaxRetries && isIdempotentMethod(method)) {\n const delayMs = getRetryDelayMs(\n attempt,\n retryBaseDelayMs,\n retryMaxDelayMs\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n continue;\n }\n\n throw new TimeoutError('Request timed out');\n }\n\n if (requestOptions.signal?.aborted) {\n throw new RunApiError('Request aborted', { cause: error as Error });\n }\n\n if (error instanceof RunApiError) {\n throw error;\n }\n\n if (attempt < requestMaxRetries && isIdempotentMethod(method)) {\n const delayMs = getRetryDelayMs(\n attempt,\n retryBaseDelayMs,\n retryMaxDelayMs\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n continue;\n }\n\n throw new NetworkError('Network error', { cause: error as Error });\n }\n }\n\n // Unreachable at runtime, but required for TypeScript return type inference\n throw new NetworkError('Network error');\n },\n\n async upload(url, uploadOptions) {\n const timeoutMs = uploadOptions.timeoutMs ?? clientTimeoutMs ?? TIMEOUTS.HTTP_REQUEST;\n const { controller, cleanup, timedOut } = createAbortController(timeoutMs, uploadOptions.signal);\n\n try {\n const response = await fetchImpl(url, {\n ...clientFetchOptions,\n method: 'PUT',\n headers: uploadOptions.headers,\n body: uploadOptions.body,\n signal: controller.signal,\n });\n cleanup();\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new RunApiError(`Direct upload failed with status ${response.status}${text ? `: ${text}` : ''}`);\n }\n } catch (error) {\n cleanup();\n if (timedOut()) {\n throw new TimeoutError('Direct upload timed out');\n }\n if (error instanceof RunApiError) {\n throw error;\n }\n throw new NetworkError('Direct upload network error', { cause: error as Error });\n }\n },\n };\n}\n\nfunction captureResponseHeaders(\n response: Response,\n target: Record<string, string> | undefined,\n): void {\n if (!target) return;\n\n response.headers.forEach((value, key) => {\n target[key] = value;\n });\n}\n","export function compactParams<T extends object>(params: T): Partial<T> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n if (typeof value === 'string' && value.trim() === '') continue;\n result[key] = value;\n }\n return result as Partial<T>;\n}\n","import { ValidationError } from './errors';\n\n/** One action entry from a package's generated contract. */\nexport interface ActionSchema {\n models?: readonly string[];\n rules?: readonly Record<string, any>[];\n fields_by_model?: Record<string, Record<string, any>>;\n}\n\ntype Params = Record<string, unknown>;\n\n/**\n * Validates request params against a generated action schema: model\n * membership, then declared cross-field rules, then per-field\n * required/enum/integer/min/max/length. A missing schema is a no-op.\n */\nexport function validateParams(schema: ActionSchema | undefined, params: Params): void {\n if (!schema) return;\n\n const model = params['model'];\n const models = schema.models ?? [];\n let fields: Record<string, any>;\n if (models.length === 0) {\n fields = schema.fields_by_model?.['_'] ?? {};\n } else {\n if (typeof model !== 'string' || !models.includes(model)) {\n const sorted = [...models].sort();\n throw new ValidationError(`model must be one of: ${sorted.join(', ')}`);\n }\n\n fields = schema.fields_by_model?.[model] ?? {};\n }\n\n const rules = schema.rules;\n if (Array.isArray(rules)) {\n for (const rule of rules) enforceContractRule(params, rule);\n }\n\n const keys = Object.keys(fields).sort();\n for (const field of keys) {\n validateSchemaField(params, field, fields[field]);\n }\n}\n\nfunction validateSchemaField(params: Params, field: string, rules: Record<string, any>): void {\n const value = params[field];\n if (value != null && ('min_items' in rules || 'max_items' in rules)) {\n validateSchemaItemCount(field, value, rules);\n }\n\n const present = fieldPresent(params, field);\n if (rules.required && !present) {\n throw new ValidationError(`${field} is required`);\n }\n if (!present) return;\n\n if (rules.enum !== undefined && !enumValueAllowed(rules.enum, value)) {\n throw new ValidationError(`${field} must be one of: ${formatEnumValues(rules.enum)}`);\n }\n\n if (rules.type === 'integer') {\n validateSchemaInteger(field, value, rules);\n }\n\n if ('min' in rules || 'max' in rules) {\n validateSchemaRange(field, value, rules);\n }\n}\n\nfunction validateSchemaItemCount(field: string, value: unknown, rules: Record<string, any>): void {\n if (!Array.isArray(value)) {\n throw new ValidationError(`${field} must be an array`);\n }\n\n const min = rules.min_items;\n const max = rules.max_items;\n if ((min == null || value.length >= min) && (max == null || value.length <= max)) return;\n throw new ValidationError(itemCountMessage(field, min, max));\n}\n\nfunction itemCountMessage(field: string, min: unknown, max: unknown): string {\n if (min != null && max != null) {\n return `${field} must contain between ${formatValue(min)} and ${formatValue(max)} items`;\n }\n if (min != null) {\n return `${field} must contain at least ${formatValue(min)} items`;\n }\n return `${field} must contain at most ${formatValue(max)} items`;\n}\n\n// Mirrors GatewayEntry#validate_schema_integer!: a type: integer field rejects\n// non-integer numbers (e.g. 11.5), which min/max alone admit. JS has no integer\n// type, so whole-valued floats count — they serialize to an integer on the wire.\nfunction validateSchemaInteger(field: string, value: unknown, rules: Record<string, any>): void {\n if (typeof value === 'number' && Number.isInteger(value)) return;\n const detail =\n rules.min != null && rules.max != null\n ? ` between ${formatValue(rules.min)} and ${formatValue(rules.max)}`\n : '';\n throw new ValidationError(`${field} must be an integer${detail}`);\n}\n\nfunction validateSchemaRange(field: string, value: unknown, rules: Record<string, any>): void {\n let measured: number;\n let unit: string | null;\n if (rules.length) {\n measured = [...String(value)].length;\n unit = 'characters';\n } else {\n if (typeof value !== 'number') {\n throw new ValidationError(`${field} must be a number`);\n }\n measured = value;\n unit = null;\n }\n\n const min = rules.min;\n const max = rules.max;\n if ((min == null || measured >= min) && (max == null || measured <= max)) return;\n throw new ValidationError(rangeMessage(field, min, max, unit));\n}\n\nfunction rangeMessage(field: string, min: unknown, max: unknown, unit: string | null): string {\n const suffix = unit ? ` ${unit}` : '';\n if (min != null && max != null) {\n return `${field} must be between ${formatValue(min)} and ${formatValue(max)}${suffix}`;\n }\n if (min != null) {\n return `${field} must be at least ${formatValue(min)}${suffix}`;\n }\n return `${field} must be at most ${formatValue(max)}${suffix}`;\n}\n\nfunction enumValueAllowed(enumValues: readonly unknown[], value: unknown): boolean {\n const valueIsNum = typeof value === 'number';\n for (const allowed of enumValues) {\n const allowedIsNum = typeof allowed === 'number';\n if (allowedIsNum) {\n if (valueIsNum && value === allowed) return true;\n } else if (valueIsNum) {\n // allowed non-numeric while value is numeric never matches.\n } else if (String(allowed) === String(value)) {\n return true;\n }\n }\n return false;\n}\n\nfunction enforceContractRule(params: Params, rule: Record<string, any>): void {\n const conditions: Record<string, unknown> = rule.when ?? {};\n const keys = Object.keys(conditions);\n for (const key of keys) {\n if (!ruleConditionMet(params, key, conditions[key])) return;\n }\n\n const context = keys.map((key) => `${key} is ${formatValue(conditions[key])}`).join(' and ');\n for (const field of rule.required ?? []) {\n if (!fieldPresent(params, field)) {\n throw new ValidationError(`${field} is required when ${context}`);\n }\n }\n for (const field of rule.forbidden ?? []) {\n if (fieldPresent(params, field)) {\n throw new ValidationError(`${field} is not allowed when ${context}`);\n }\n }\n}\n\nfunction ruleConditionMet(params: Params, field: string, value: unknown): boolean {\n if (!(field in params)) return false;\n return String(params[field]) === String(value);\n}\n\nfunction fieldPresent(params: Params, field: string): boolean {\n if (!(field in params)) return false;\n const value = params[field];\n if (value === false) return true;\n if (Array.isArray(value)) return value.some(presentValue);\n return presentValue(value);\n}\n\nfunction presentValue(value: unknown): boolean {\n if (value === null || value === undefined || value === false) return false;\n if (value === true) return true;\n if (typeof value === 'string') return value.trim() !== '';\n if (Array.isArray(value)) return value.length > 0;\n if (typeof value === 'object') return Object.keys(value).length > 0;\n return true;\n}\n\nfunction formatValue(value: unknown): string {\n return typeof value === 'string' ? value : String(value);\n}\n\n// JS collapses float literals (0.0 -> 0), losing the float type the other SDKs\n// keep. When an enum has a fractional member it is a float enum, so render its\n// whole-number members with a trailing .0 to match the gateway/Go/Ruby/Python\n// message text (e.g. \"0.0, 0.5, 1.0\", not \"0, 0.5, 1\").\nfunction formatEnumValues(values: readonly unknown[]): string {\n const floatEnum = values.some((v) => typeof v === 'number' && !Number.isInteger(v));\n return values\n .map((v) => (floatEnum && typeof v === 'number' ? formatFloat(v) : formatValue(v)))\n .join(', ');\n}\n\nfunction formatFloat(value: number): string {\n const text = String(value);\n return /[.eE]/.test(text) ? text : `${text}.0`;\n}\n","// RFC 1321 MD5 over raw bytes, returning the Base64 of the 16-byte digest — the\n// value the upload target expects as the Content-MD5 header on a direct-upload\n// PUT. Web Crypto has no MD5, so direct upload needs this pure implementation to\n// run in browsers as well as Node.\n\nconst SHIFTS = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,\n];\n\nconst K = Array.from({ length: 64 }, (_v, i) =>\n Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296),\n);\n\nfunction add32(a: number, b: number): number {\n return (a + b) & 0xffffffff;\n}\n\nfunction rotl(value: number, bits: number): number {\n return (value << bits) | (value >>> (32 - bits));\n}\n\nfunction md5Bytes(input: Uint8Array): Uint8Array {\n const withOne = input.length + 1;\n const totalLen = withOne + ((56 - (withOne % 64) + 64) % 64) + 8;\n const msg = new Uint8Array(totalLen);\n msg.set(input);\n msg[input.length] = 0x80;\n\n const view = new DataView(msg.buffer);\n const bitLen = input.length * 8;\n view.setUint32(totalLen - 8, bitLen >>> 0, true);\n view.setUint32(totalLen - 4, Math.floor(bitLen / 0x100000000) >>> 0, true);\n\n let a0 = 0x67452301;\n let b0 = 0xefcdab89;\n let c0 = 0x98badcfe;\n let d0 = 0x10325476;\n\n const m = new Int32Array(16);\n for (let offset = 0; offset < totalLen; offset += 64) {\n for (let j = 0; j < 16; j += 1) {\n m[j] = view.getUint32(offset + j * 4, true);\n }\n\n let a = a0;\n let b = b0;\n let c = c0;\n let d = d0;\n\n for (let i = 0; i < 64; i += 1) {\n let f: number;\n let g: number;\n if (i < 16) {\n f = (b & c) | (~b & d);\n g = i;\n } else if (i < 32) {\n f = (d & b) | (~d & c);\n g = (5 * i + 1) % 16;\n } else if (i < 48) {\n f = b ^ c ^ d;\n g = (3 * i + 5) % 16;\n } else {\n f = c ^ (b | ~d);\n g = (7 * i) % 16;\n }\n\n f = add32(add32(f, a), add32(K[i], m[g]));\n a = d;\n d = c;\n c = b;\n b = add32(b, rotl(f, SHIFTS[i]));\n }\n\n a0 = add32(a0, a);\n b0 = add32(b0, b);\n c0 = add32(c0, c);\n d0 = add32(d0, d);\n }\n\n const out = new Uint8Array(16);\n const outView = new DataView(out.buffer);\n outView.setUint32(0, a0 >>> 0, true);\n outView.setUint32(4, b0 >>> 0, true);\n outView.setUint32(8, c0 >>> 0, true);\n outView.setUint32(12, d0 >>> 0, true);\n return out;\n}\n\nconst BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let out = '';\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i];\n const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n out += BASE64_CHARS[b0 >> 2];\n out += BASE64_CHARS[((b0 & 3) << 4) | (b1 >> 4)];\n out += i + 1 < bytes.length ? BASE64_CHARS[((b1 & 15) << 2) | (b2 >> 6)] : '=';\n out += i + 2 < bytes.length ? BASE64_CHARS[b2 & 63] : '=';\n }\n return out;\n}\n\nexport function md5Base64(bytes: Uint8Array): string {\n return bytesToBase64(md5Bytes(bytes));\n}\n","import type { HttpClient } from './http';\nimport type { RequestOptions } from './types';\nimport { compactParams } from './params';\nimport { md5Base64 } from './md5';\n\nconst ENDPOINT = '/api/v1/files';\nconst PREPARE_ENDPOINT = `${ENDPOINT}/prepare`;\nconst CONFIRM_ENDPOINT = `${ENDPOINT}/confirm`;\n\ninterface PrepareResponse {\n signed_id: string;\n upload_url: string;\n headers: Record<string, string>;\n}\n\nexport interface FileUploadResponse {\n file_name: string;\n url: string;\n size_bytes: number;\n mime_type: string;\n created_at: string;\n expires_at: string;\n}\n\nexport type FileSource =\n | { type: 'url'; url: string }\n | { type: 'base64'; data: string };\n\nexport type FileCreateParams =\n | {\n file: Blob;\n file_name?: string;\n source?: never;\n }\n | {\n source: FileSource;\n file_name?: string;\n file?: never;\n };\n\nexport class Files {\n constructor(private readonly http: HttpClient) {}\n\n async create(params: FileCreateParams, options?: RequestOptions): Promise<FileUploadResponse> {\n const rawParams = params as { file?: Blob; source?: FileSource; file_name?: string };\n const hasFile = Boolean(rawParams.file);\n const hasSource = Boolean(rawParams.source);\n if (Number(hasFile) + Number(hasSource) !== 1) {\n throw new Error('Exactly one source is required: file or source');\n }\n\n if (hasFile) {\n return this.uploadDirect(rawParams.file as Blob, params.file_name, options);\n }\n\n return this.http.request<FileUploadResponse>('POST', ENDPOINT, {\n body: compactParams(params),\n ...options,\n });\n }\n\n // Local files upload straight to storage: ask for a pre-authorized target,\n // PUT the bytes there (never through the API), then confirm. The caller still\n // sees a single create() call.\n private async uploadDirect(\n file: Blob,\n fileName: string | undefined,\n options?: RequestOptions,\n ): Promise<FileUploadResponse> {\n const bytes = new Uint8Array(await file.arrayBuffer());\n const filename = fileName ?? (file as { name?: string }).name ?? 'upload';\n const contentType = file.type || 'application/octet-stream';\n\n const prepared = await this.http.request<PrepareResponse>('POST', PREPARE_ENDPOINT, {\n body: {\n filename,\n byte_size: bytes.byteLength,\n checksum: md5Base64(bytes),\n content_type: contentType,\n },\n ...options,\n });\n\n await this.http.upload(prepared.upload_url, {\n headers: prepared.headers,\n body: bytes,\n timeoutMs: options?.timeoutMs,\n signal: options?.signal,\n });\n\n return this.http.request<FileUploadResponse>('POST', CONFIRM_ENDPOINT, {\n body: { signed_id: prepared.signed_id },\n ...options,\n });\n }\n}\n","import type { HttpClient } from './http';\nimport type { RequestOptions } from './types';\n\nconst INFO_ENDPOINT = '/api/v1/me';\nconst BALANCE_ENDPOINT = '/api/v1/me/balance';\n\nexport interface AccountInfoResponse {\n id: number;\n name: string;\n email: string;\n account: {\n id: number;\n name: string;\n };\n}\n\nexport interface AccountBalanceResponse {\n balance_cents: number;\n paid_balance_cents: number;\n bonus_balance_cents: number;\n spent_cents_today: number;\n spent_cents_total: number;\n}\n\nexport class Account {\n constructor(private readonly http: HttpClient) {}\n\n async info(options?: RequestOptions): Promise<AccountInfoResponse> {\n return this.http.request<AccountInfoResponse>('GET', INFO_ENDPOINT, { ...options });\n }\n\n async balance(options?: RequestOptions): Promise<AccountBalanceResponse> {\n return this.http.request<AccountBalanceResponse>('GET', BALANCE_ENDPOINT, { ...options });\n }\n}\n","import { createHttpClient, type HttpClient } from './http';\nimport type { ClientOptions, QueryParams, RequestOptions } from './types';\n\nconst SCHEDULES_ENDPOINT = '/api/v1/price_schedules';\nconst QUOTES_ENDPOINT = '/api/v1/price_quotes';\n\nexport interface PriceScheduleFilters extends QueryParams {\n service?: string;\n action?: string;\n model?: string;\n}\n\nexport interface PriceSchedule {\n service: string;\n action: string;\n model: string | null;\n pricing_status: 'available' | 'pending' | string;\n catalog_status: 'active' | 'maintenance' | 'disabled' | string;\n currency: string;\n billing_unit: string;\n billing_strategy: string;\n unit_price_cents: number | null;\n input_price_per_1m_cents: number | null;\n output_price_per_1m_cents: number | null;\n cache_read_price_per_1m_cents: number | null;\n cache_write_5m_price_per_1m_cents: number | null;\n cache_write_1h_price_per_1m_cents: number | null;\n billing_config: Record<string, unknown>;\n}\n\nexport interface PriceScheduleListResponse {\n as_of: string;\n price_schedules: PriceSchedule[];\n /** HTTP ETag for revalidating this schedule on a later request. */\n etag?: string;\n}\n\nexport interface PriceScheduleNotModifiedResponse {\n not_modified: true;\n etag?: string;\n}\n\nexport type PriceScheduleListResult = PriceScheduleListResponse | PriceScheduleNotModifiedResponse;\n\nexport interface PriceQuoteParams {\n service: string;\n action: string;\n model?: string | null;\n params?: Record<string, unknown>;\n}\n\nexport interface PriceQuoteResponse {\n service: string;\n action: string;\n model: string | null;\n pricing_status: 'available' | string;\n currency: string;\n reservation_amount_cents: number;\n estimate_basis: string;\n as_of: string;\n}\n\n/** Live Price Schedule lookup and request-specific Price Quote operations. */\nexport class Pricing {\n constructor(private readonly http: HttpClient) {}\n\n async list(\n filters: PriceScheduleFilters = {},\n options?: RequestOptions,\n ): Promise<PriceScheduleListResult> {\n const responseHeaders: Record<string, string> = {};\n const result = await this.http.request<PriceScheduleListResult>('GET', SCHEDULES_ENDPOINT, {\n ...options,\n query: filters,\n allowNotModified: true,\n captureResponseHeaders: responseHeaders,\n });\n\n return 'not_modified' in result ? result : {...result, etag: responseHeaders.etag};\n }\n\n async quote(\n params: PriceQuoteParams,\n options?: RequestOptions,\n ): Promise<PriceQuoteResponse> {\n const response = await this.http.request<{ price_quote: PriceQuoteResponse }>('POST', QUOTES_ENDPOINT, {\n ...options,\n body: params,\n });\n return response.price_quote;\n }\n}\n\n/** Standalone live Pricing client with optional API authentication. */\nexport class PricingClient extends Pricing {\n constructor(options: ClientOptions = {}) {\n super(createHttpClient(options));\n }\n}\n","import { createHttpClient, type HttpClient } from './http';\nimport { resolveApiKey } from './auth';\nimport type { ClientOptions } from './types';\nimport { Files } from './files';\nimport { Account } from './account';\nimport { Pricing } from './pricing';\n\n/**\n * Base class for RunAPI Provider Clients. Resolves the API key, builds the\n * shared HTTP client, and exposes the Universal Resources (file upload,\n * account, pricing) that are available on any client regardless of which model\n * package was imported.\n *\n * Provider clients extend this and build their model resources from `this.http`.\n */\nexport class BaseClient {\n /** Temporary file upload operations. */\n public readonly files: Files;\n /** Account info and balance operations. */\n public readonly account: Account;\n /** Live Price Schedule lookup and Price Quote operations. */\n public readonly pricing: Pricing;\n\n protected readonly http: HttpClient;\n private readonly apiKey: string;\n\n constructor(options: ClientOptions = {}) {\n this.apiKey = resolveApiKey(options);\n this.http = createHttpClient(options);\n this.files = new Files(this.http);\n this.account = new Account(this.http);\n this.pricing = new Pricing(this.http);\n }\n\n getApiKey(): string {\n return this.apiKey;\n }\n}\n","// Types\nexport type {\n HttpMethod,\n QueryParams,\n ClientOptions,\n RequestOptions,\n PollingOptions,\n TaskStatus,\n AsyncTaskStatus,\n TaskBillingResponse,\n TaskResponse,\n TaskBillingFacts,\n TaskReservation,\n TaskSettlement,\n TaskRefund,\n} from './types';\n\n// Constants\nexport { TIMEOUTS, RETRY_CONFIG, DEFAULT_BASE_URL, SDK_USER_AGENT } from './constants';\n\n// Errors\nexport {\n RunApiError,\n AuthenticationError,\n RateLimitError,\n InsufficientCreditsError,\n NotFoundError,\n ValidationError,\n ServiceUnavailableError,\n NetworkError,\n TimeoutError,\n TaskTimeoutError,\n TaskFailedError,\n errorFromResponse,\n} from './errors';\nexport type { RunApiErrorOptions } from './errors';\n\n// Auth\nexport { resolveApiKey, resolveOptionalApiKey } from './auth';\n\n// HTTP Client\nexport { createHttpClient } from './http';\nexport type { HttpClient, HttpRequestOptions } from './http';\n\n// Retry (高级用户可用)\nexport {\n getRetryDelayMs,\n isRetryableStatus,\n isIdempotentMethod,\n parseRetryAfterMs,\n} from './retry';\nexport type { RetryOptions } from './retry';\n\n// Params\nexport { compactParams } from './params';\n\n// Contract validation\nexport { validateParams } from './validate';\nexport type { ActionSchema } from './validate';\n\n// Files\nexport { Files } from './files';\nexport type { FileCreateParams, FileSource, FileUploadResponse } from './files';\n\n// Account\nexport { Account } from './account';\nexport type { AccountInfoResponse, AccountBalanceResponse } from './account';\n\n// Pricing\nexport { Pricing, PricingClient } from './pricing';\nexport type {\n PriceScheduleFilters,\n PriceSchedule,\n PriceScheduleListResponse,\n PriceScheduleNotModifiedResponse,\n PriceScheduleListResult,\n PriceQuoteParams,\n PriceQuoteResponse,\n} from './pricing';\n\n// Base client\nexport { BaseClient } from './base-client';\n\n// Version\nexport const version = '0.1.0';\n\n// Note: pollUntilComplete 不从主入口导出,避免 PollingOptions 类型暴露\n// 各 API 包(suno/veo-3-1 等)通过 '@run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AA,EAClB;AACF;AAGO,IAAM,gBAAN,cAA4B,QAAQ;AAAA,EACzC,YAAY,UAAyB,CAAC,GAAG;AACvC,UAAM,iBAAiB,OAAO,CAAC;AAAA,EACjC;AACF;;;ACnFO,IAAM,aAAN,MAAiB;AAAA;AAAA,EAEN;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAEG;AAAA,EACF;AAAA,EAEjB,YAAY,UAAyB,CAAC,GAAG;AACvC,SAAK,SAAS,cAAc,OAAO;AACnC,SAAK,OAAO,iBAAiB,OAAO;AACpC,SAAK,QAAQ,IAAI,MAAM,KAAK,IAAI;AAChC,SAAK,UAAU,IAAI,QAAQ,KAAK,IAAI;AACpC,SAAK,UAAU,IAAI,QAAQ,KAAK,IAAI;AAAA,EACtC;AAAA,EAEA,YAAoB;AAClB,WAAO,KAAK;AAAA,EACd;AACF;;;AC+CO,IAAM,UAAU;","names":[]} |
@@ -1,2 +0,2 @@ | ||
| import { T as TaskResponse, P as PollingOptions } from './types-B4_rq_8F.mjs'; | ||
| import { d as TaskResponse, P as PollingOptions } from './types-ClO2hfPY.mjs'; | ||
@@ -3,0 +3,0 @@ declare function pollUntilComplete<T extends TaskResponse>(fetcher: () => Promise<T>, options?: PollingOptions): Promise<T>; |
@@ -1,2 +0,2 @@ | ||
| import { T as TaskResponse, P as PollingOptions } from './types-B4_rq_8F.js'; | ||
| import { d as TaskResponse, P as PollingOptions } from './types-ClO2hfPY.js'; | ||
@@ -3,0 +3,0 @@ declare function pollUntilComplete<T extends TaskResponse>(fetcher: () => Promise<T>, options?: PollingOptions): Promise<T>; |
+1
-1
@@ -6,3 +6,3 @@ { | ||
| }, | ||
| "version": "0.2.15", | ||
| "version": "0.3.0", | ||
| "description": "RunAPI core SDK for JavaScript, Python, Ruby, Go, Java, and PHP", | ||
@@ -9,0 +9,0 @@ "main": "./dist/index.js", |
+30
-1
@@ -15,2 +15,26 @@ # RunAPI Core JavaScript SDK | ||
| ## Live Pricing | ||
| Every Provider Client exposes `pricing`. Schedule lookup and quotes use the live API response and do not retain a local price cache. | ||
| ```typescript | ||
| const schedules = await client.pricing.list({ service: 'suno' }); | ||
| const quote = await client.pricing.quote({ | ||
| service: 'suno', | ||
| action: 'convert_audio', | ||
| params: {}, | ||
| }); | ||
| ``` | ||
| Public schedule lookup and quotes that use only public parameters work without an API key. Pass a standard API key when a quote references an account-owned source Task. | ||
| Use `PricingClient` when pricing is the only capability needed: | ||
| ```typescript | ||
| import { PricingClient } from '@runapi.ai/core'; | ||
| const pricing = new PricingClient(); | ||
| const schedules = await pricing.list({ service: 'suno' }); | ||
| ``` | ||
| ## Request identifiers | ||
@@ -20,6 +44,11 @@ | ||
| Task-creation calls also accept an optional opaque `Idempotency-Key` up to 512 characters. Generate one value per logical task and reuse it only with identical input after an unknown result. Reusing the value with different input returns `409 Conflict`; do not derive it from `X-Client-Request-Id`. | ||
| ```typescript | ||
| await client.textToImage.create( | ||
| { prompt: 'A sunset over the ocean' }, | ||
| { headers: { 'X-Client-Request-Id': 'order-123' } } | ||
| { headers: { | ||
| 'X-Client-Request-Id': 'order-123', | ||
| 'Idempotency-Key': 'opaque-logical-task-123' | ||
| } } | ||
| ); | ||
@@ -26,0 +55,0 @@ ``` |
| /** HTTP methods supported by the SDK. */ | ||
| type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; | ||
| /** Query parameters for HTTP requests. Null and undefined values are omitted. */ | ||
| type QueryParams = Record<string, string | number | boolean | null | undefined>; | ||
| /** | ||
| * Configuration options for API clients. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const client = new SunoClient({ | ||
| * apiKey: 'your-api-key', | ||
| * baseUrl: 'https://runapi.ai', | ||
| * timeoutMs: 60000, | ||
| * maxRetries: 3, | ||
| * }); | ||
| * ``` | ||
| */ | ||
| interface ClientOptions { | ||
| /** | ||
| * API key for authentication. If omitted, the SDK reads | ||
| * `RUNAPI_API_KEY` from the environment (Node runtimes only). | ||
| */ | ||
| apiKey?: string; | ||
| /** Base URL for API requests. Defaults to `https://runapi.ai`. */ | ||
| baseUrl?: string; | ||
| /** Request timeout in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| timeoutMs?: number; | ||
| /** Maximum number of retry attempts. Defaults to 2. */ | ||
| maxRetries?: number; | ||
| /** Base delay between retries in milliseconds. Defaults to 500. */ | ||
| retryBaseDelayMs?: number; | ||
| /** Maximum delay between retries in milliseconds. Defaults to 5000. */ | ||
| retryMaxDelayMs?: number; | ||
| /** Custom `fetch` implementation. Defaults to the global `fetch`. */ | ||
| fetch?: typeof fetch; | ||
| /** | ||
| * Extra options passed to every `fetch` call (e.g. `cache`, `credentials`, `keepalive`). | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Per-request options that override client-level defaults. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * await client.textToImage.run( | ||
| * { prompt: 'A sunset' }, | ||
| * { timeoutMs: 30000, headers: { 'X-Custom': 'value' } } | ||
| * ); | ||
| * ``` | ||
| */ | ||
| interface RequestOptions { | ||
| /** Additional HTTP headers. Merged with client-level headers. */ | ||
| headers?: Record<string, string>; | ||
| /** Request timeout in milliseconds. Overrides client-level timeout. */ | ||
| timeoutMs?: number; | ||
| /** Maximum retry attempts. Overrides client-level maxRetries. */ | ||
| maxRetries?: number; | ||
| /** Abort signal for request cancellation. */ | ||
| signal?: AbortSignal; | ||
| /** | ||
| * Per-request fetch options that override client-level `fetchOptions`. | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Options for polling async task completion. | ||
| * Used internally by resource `run()` methods. | ||
| */ | ||
| interface PollingOptions { | ||
| /** Polling interval in milliseconds. Defaults to 2000 (2 seconds). */ | ||
| pollIntervalMs?: number; | ||
| /** Maximum wait time in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| maxWaitMs?: number; | ||
| } | ||
| /** Task status values returned by async operations. */ | ||
| type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed'; | ||
| /** | ||
| * Status for async task results (excludes 'pending'). | ||
| * Used for polling results that have already started processing. | ||
| */ | ||
| type AsyncTaskStatus = Exclude<TaskStatus, 'pending'>; | ||
| /** | ||
| * Response structure for async task operations. | ||
| * Specific API methods extend this with additional fields. | ||
| */ | ||
| interface TaskResponse { | ||
| /** Task ID for tracking and retrieval. */ | ||
| id?: string; | ||
| /** Current task status. */ | ||
| status: TaskStatus | string; | ||
| /** Error message if task failed. */ | ||
| error?: string; | ||
| /** Additional task-specific fields. */ | ||
| [key: string]: unknown; | ||
| } | ||
| export type { AsyncTaskStatus as A, ClientOptions as C, HttpMethod as H, PollingOptions as P, QueryParams as Q, RequestOptions as R, TaskResponse as T, TaskStatus as a }; |
| /** HTTP methods supported by the SDK. */ | ||
| type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; | ||
| /** Query parameters for HTTP requests. Null and undefined values are omitted. */ | ||
| type QueryParams = Record<string, string | number | boolean | null | undefined>; | ||
| /** | ||
| * Configuration options for API clients. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const client = new SunoClient({ | ||
| * apiKey: 'your-api-key', | ||
| * baseUrl: 'https://runapi.ai', | ||
| * timeoutMs: 60000, | ||
| * maxRetries: 3, | ||
| * }); | ||
| * ``` | ||
| */ | ||
| interface ClientOptions { | ||
| /** | ||
| * API key for authentication. If omitted, the SDK reads | ||
| * `RUNAPI_API_KEY` from the environment (Node runtimes only). | ||
| */ | ||
| apiKey?: string; | ||
| /** Base URL for API requests. Defaults to `https://runapi.ai`. */ | ||
| baseUrl?: string; | ||
| /** Request timeout in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| timeoutMs?: number; | ||
| /** Maximum number of retry attempts. Defaults to 2. */ | ||
| maxRetries?: number; | ||
| /** Base delay between retries in milliseconds. Defaults to 500. */ | ||
| retryBaseDelayMs?: number; | ||
| /** Maximum delay between retries in milliseconds. Defaults to 5000. */ | ||
| retryMaxDelayMs?: number; | ||
| /** Custom `fetch` implementation. Defaults to the global `fetch`. */ | ||
| fetch?: typeof fetch; | ||
| /** | ||
| * Extra options passed to every `fetch` call (e.g. `cache`, `credentials`, `keepalive`). | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Per-request options that override client-level defaults. | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * await client.textToImage.run( | ||
| * { prompt: 'A sunset' }, | ||
| * { timeoutMs: 30000, headers: { 'X-Custom': 'value' } } | ||
| * ); | ||
| * ``` | ||
| */ | ||
| interface RequestOptions { | ||
| /** Additional HTTP headers. Merged with client-level headers. */ | ||
| headers?: Record<string, string>; | ||
| /** Request timeout in milliseconds. Overrides client-level timeout. */ | ||
| timeoutMs?: number; | ||
| /** Maximum retry attempts. Overrides client-level maxRetries. */ | ||
| maxRetries?: number; | ||
| /** Abort signal for request cancellation. */ | ||
| signal?: AbortSignal; | ||
| /** | ||
| * Per-request fetch options that override client-level `fetchOptions`. | ||
| * SDK-managed fields (`method`, `headers`, `body`, `signal`) cannot be overridden. | ||
| */ | ||
| fetchOptions?: Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>; | ||
| } | ||
| /** | ||
| * Options for polling async task completion. | ||
| * Used internally by resource `run()` methods. | ||
| */ | ||
| interface PollingOptions { | ||
| /** Polling interval in milliseconds. Defaults to 2000 (2 seconds). */ | ||
| pollIntervalMs?: number; | ||
| /** Maximum wait time in milliseconds. Defaults to 900000 (15 minutes). */ | ||
| maxWaitMs?: number; | ||
| } | ||
| /** Task status values returned by async operations. */ | ||
| type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed'; | ||
| /** | ||
| * Status for async task results (excludes 'pending'). | ||
| * Used for polling results that have already started processing. | ||
| */ | ||
| type AsyncTaskStatus = Exclude<TaskStatus, 'pending'>; | ||
| /** | ||
| * Response structure for async task operations. | ||
| * Specific API methods extend this with additional fields. | ||
| */ | ||
| interface TaskResponse { | ||
| /** Task ID for tracking and retrieval. */ | ||
| id?: string; | ||
| /** Current task status. */ | ||
| status: TaskStatus | string; | ||
| /** Error message if task failed. */ | ||
| error?: string; | ||
| /** Additional task-specific fields. */ | ||
| [key: string]: unknown; | ||
| } | ||
| export type { AsyncTaskStatus as A, ClientOptions as C, HttpMethod as H, PollingOptions as P, QueryParams as Q, RequestOptions as R, TaskResponse as T, TaskStatus as a }; |
Sorry, the diff of this file is too big to display
267682
9.79%2747
8.19%74
64.44%