// Customer API SDK for TypeScript and JavaScript (Node 18+, Deno, Bun, browsers). // Generated by cmd/sdkgen from api/openapi/customer.v3.yaml. Do not edit by hand; run `task gen`. // // Zero dependencies: it uses fetch and WebCrypto. Every POST gets an // Idempotency-Key (generated when you don't pass one), so the client retries // network failures, 429 and 5xx safely. export interface Accepted { object: "accepted"; status: "queued"; } export interface ApiError { /** Error class. Accept unknown values. */ type: string; code: string; message: string; message_fa: string; param: string | null; request_id: string; } export interface Balance { object: "balance"; livemode: boolean; balance_irr: number; credit_limit_irr: number; available_irr: number; } export interface Batch { object: "batch"; id: number; livemode: boolean; status: string; mode: string; total_irr: number; lines: number; orders: Order[]; created_at: string; } export interface BatchCreate { orders: OrderCreate[]; mode?: "all_or_nothing" | "valid_only"; } export interface BatchLineError { index: number; error: LineError; } export interface BatchResult { object: "batch_result"; batch_id: number | null; total_irr: number; orders: Order[]; errors: BatchLineError[]; } export interface Category { object: "category"; id: number; platform: string; slug: string; name_fa: string; /** profile, post, video, channel, … Accept unknown values. */ target_kind: string; } export interface CategoryList { object: "list"; data: Category[]; next_cursor: string | null; } export interface Commission { object: "referral_commission"; id: number; commission_irr: number; /** held, released, void */ status: string; release_at: string; created_at: string; } export interface CouponRedeem { code: string; } export interface CouponRedemption { object: "coupon_redemption"; kind: "voucher" | "deposit_bonus"; /** Credited now (vouchers); deposit coupons apply to the next deposit */ credited_irr: number; } export interface Credential { kind: "api_key" | "app_token"; id: number; label: string; livemode: boolean; scopes: string[]; } export interface ErrorResponse { error: ApiError; } export interface Event { object: "event"; id: number; type: string; livemode: boolean; created_at: string; /** Usually {object, previous?}: the same body webhooks carry */ data: Record; } export interface EventList { object: "list"; data: Event[]; next_cursor: string | null; } export interface Favorite { object: "favorite"; service_id: number; } export interface FavoriteCreate { service_id: number; } export interface FavoriteList { object: "list"; data: Favorite[]; next_cursor: string | null; } export interface LineError { type: string; code: string; message: string; message_fa: string; param: string | null; } export interface LinkResolution { object: "link_resolution"; platform: string; target_kind: string; normalized_link: string; compatible_service_ids: number[]; recommended_service_id: number | null; } export interface LinkResolveRequest { link: string; } export interface MarkRead { /** Omit to mark everything read */ id?: number; } export interface MarkReadResult { object: "notifications_read"; marked: number; } export interface Me { object: "user"; id: number; phone: string; display_name: string | null; email: string | null; tier: Tier; ref_code: string; credential: Credential; created_at: string; } export interface Meta { object: "meta"; api_version: string; server_time: string; } export interface Notification { object: "notification"; id: number; event: string; title_fa: string; body_fa: string; /** A panel path */ link: string; read: boolean; created_at: string; } export interface NotificationList { object: "list"; data: Notification[]; next_cursor: string | null; unread: number; } export interface Order { object: "order"; /** The public order number (the same as `order` in /api/v2) */ id: number; livemode: boolean; /** awaiting_payment, pending, dispatching, dispatch_unknown, in_progress, processing, completed, partial, canceled, failed. Accept unknown values. */ status: string; /** Pending, In progress, Processing, Completed, Partial, Canceled */ status_label: string; service_id: number; link: string; quantity: number; start_count: number | null; remains: number | null; charge_irr: number; refunded_irr: number; params: Record; client_label: string | null; batch_id: number | null; cancelable: boolean; refillable: boolean; created_at: string; updated_at: string; completed_at: string | null; } export interface OrderCreate { service_id: number; link: string; quantity: number; client_label?: string | null; /** By service type: custom_comments {comments}, mentions {usernames}, drip_feed {runs, interval_minutes}, subscription {username, min, max, posts, delay_minutes, expiry}, poll {answer_number} */ params?: Record; } export interface OrderList { object: "list"; data: Order[]; next_cursor: string | null; } export interface OtpChallenge { object: "otp_challenge"; challenge_id: string; /** Seconds */ expires_in: number; } export interface OtpRequest { phone: string; } export interface OtpVerify { challenge_id: string; code: string; device_name?: string; } export interface Payment { object: "payment"; id: number; /** created, redirected, verified, credited, failed, expired */ status: string; gateway: string; amount_irr: number; /** Open this in the user's browser (only while unpaid) */ redirect_url: string | null; return_url: string | null; created_at: string; updated_at: string; verified_at: string | null; } export interface PaymentCreate { amount_irr: number; gateway?: string; /** Where to send the user after paying (https) */ return_url?: string | null; } export interface Platform { object: "platform"; slug: string; name_fa: string; name_en: string; is_domestic: boolean; ordering_paused: boolean; } export interface PlatformList { object: "list"; data: Platform[]; next_cursor: string | null; } export interface Quote { object: "quote"; service_id: number; quantity: number; rate_irr_per_1000: number; charge_irr: number; valid_until: string; /** Your active orders for the same link and service */ duplicate_order_ids: number[]; } export interface QuoteRequest { service_id: number; quantity: number; /** Optional: also checks that the service accepts the link */ link?: string; } export interface Referrals { object: "referrals"; link: string; ref_code: string; commission_bps: number; hold_days: number; held_irr: number; released_irr: number; commissions: Commission[]; } export interface Refill { object: "refill"; id: number; order_id: number; /** pending, in_progress, completed, rejected */ status: string; error: string; created_at: string; updated_at: string; } export interface RefillList { object: "list"; data: Refill[]; next_cursor: string | null; } export interface RefreshRequest { refresh_token: string; } export interface RequestLog { object: "request_log"; id: number; method: string; path: string; status: number; duration_ms: number; request_id: string; error_code: string | null; /** Key prefix or app session */ credential: string; livemode: boolean; created_at: string; } export interface RequestLogList { object: "list"; data: RequestLog[]; next_cursor: string | null; } export interface Service { object: "service"; /** The public service number (the same as `service` in /api/v2) */ id: number; platform: string; category: string; target_kind: string; /** default, package, custom_comments, mentions, drip_feed, subscription, poll */ type: string; name_fa: string; description_fa: string; /** Your price per 1000 (tier and custom rates applied) */ rate_irr_per_1000: number; min: number; max: number; step: number; refill_days: number; cancelable: boolean; dripfeed: boolean; p50_start_seconds: number | null; p50_complete_seconds: number | null; status: string; } export interface ServiceList { object: "list"; data: Service[]; next_cursor: string | null; } export interface Target { object: "target"; id: number; link: string; platform: string; target_kind: string; label: string; tags: string[]; created_at: string; } export interface TargetCreate { link: string; label?: string; tags?: string[]; } export interface TargetList { object: "list"; data: Target[]; next_cursor: string | null; } export interface Template { object: "template"; id: number; name: string; lines: string; created_at: string; updated_at: string; } export interface TemplateCreate { name: string; /** Bulk lines: service_id | link | quantity, one per line */ lines: string; } export interface TemplateList { object: "list"; data: Template[]; next_cursor: string | null; } export interface TestBalanceRequest { amount_irr: number; } export interface Ticket { object: "ticket"; id: number; subject: string; category: string; /** open, answered, pending_customer, closed */ status: string; /** The public order number */ order_id: number | null; rating: number | null; last_message_at: string; created_at: string; closed_at: string | null; } export interface TicketCreate { subject: string; body: string; category?: "general" | "order" | "payment" | "api" | "account" | "other"; /** An order of yours this is about */ order_id?: number; } export interface TicketDetail { object: "ticket_detail"; ticket: Ticket; messages: TicketMessage[]; } export interface TicketList { object: "list"; data: Ticket[]; next_cursor: string | null; } export interface TicketMessage { object: "ticket_message"; id: number; author: "user" | "staff" | "system"; body: string; created_at: string; } export interface TicketReply { body: string; } export interface Tier { id: number; name_fa: string; discount_bps: number; } export interface TokenPair { object: "token"; token_type: "Bearer"; access_token: string; /** Seconds (15 minutes) */ expires_in: number; refresh_token: string; /** Seconds (60 days) */ refresh_expires_in: number; user_id: number; } export interface TrackingLink { object: "tracking_link"; order_id: number; url: string; } export interface TrackingLinkRequest { order_id: number; } export interface Transaction { object: "transaction"; id: number; /** deposit, charge, refund, bonus, adjustment, … Accept unknown values. */ kind: string; /** Positive adds to the wallet, negative takes from it */ amount_irr: number; balance_after_irr: number; ref_type: string; ref_id: string; memo: string; created_at: string; } export interface TransactionList { object: "list"; data: Transaction[]; next_cursor: string | null; } export interface WebhookDelivery { object: "webhook_delivery"; id: number; endpoint_id: number; event_id: number; attempt: number; /** pending, succeeded, failed */ status: string; response_code: number | null; duration_ms: number | null; error: string; next_attempt_at: string | null; created_at: string; updated_at: string; } export interface WebhookDeliveryList { object: "list"; data: WebhookDelivery[]; next_cursor: string | null; } export interface WebhookEndpoint { object: "webhook_endpoint"; id: number; url: string; events: string[]; livemode: boolean; active: boolean; failing_since: string | null; created_at: string; updated_at: string; } export interface WebhookEndpointCreate { /** https only */ url: string; /** Event types, or ["*"] for all (default) */ events?: string[]; } export interface WebhookEndpointCreated { object: "webhook_endpoint"; id: number; url: string; events: string[]; livemode: boolean; active: boolean; failing_since: string | null; created_at: string; updated_at: string; /** The signing secret (whsec_…). Shown once. */ secret: string; } export interface WebhookEndpointList { object: "list"; data: WebhookEndpoint[]; next_cursor: string | null; } export interface WebhookEndpointUpdate { active?: boolean; events?: string[]; url?: string; } export interface ListCategoriesParams { /** Platform slug, e.g. instagram */ platform?: string; } export interface ListEventsParams { type?: string; created_after?: string; /** 1–100, default 25 */ limit?: number; /** The next_cursor of the previous page (opaque) */ cursor?: string; } export interface ListNotificationsParams { /** 1–100, default 25 */ limit?: number; /** The next_cursor of the previous page (opaque) */ cursor?: string; } export interface ListOrdersParams { status?: string; service_id?: number; client_label?: string; link?: string; batch_id?: number; created_after?: string; created_before?: string; /** 1–100, default 25 */ limit?: number; /** The next_cursor of the previous page (opaque) */ cursor?: string; } export interface ListRefillsParams { order_id?: number; /** 1–100, default 25 */ limit?: number; } export interface ListRequestLogsParams { /** 1–100, default 25 */ limit?: number; /** The next_cursor of the previous page (opaque) */ cursor?: string; } export interface ListServicesParams { platform?: string; /** Category slug */ category?: string; target_kind?: string; /** Search in the Persian name */ q?: string; } export interface ListTargetsParams { tag?: string; } export interface ListTicketsParams { /** 1–100, default 25 */ limit?: number; /** The next_cursor of the previous page (opaque) */ cursor?: string; } export interface ListTransactionsParams { kind?: string; created_after?: string; created_before?: string; /** 1–100, default 25 */ limit?: number; /** The next_cursor of the previous page (opaque) */ cursor?: string; } export interface ListWebhookDeliveriesParams { /** 1–100, default 25 */ limit?: number; /** The next_cursor of the previous page (opaque) */ cursor?: string; } /** The standard error object, thrown for every non-2xx response. */ export class SmmError extends Error { readonly status: number; readonly type: string; readonly code: string; readonly messageFa: string; readonly param: string | null; readonly requestId: string; constructor(status: number, e: Partial) { super(e.message ?? "request failed with status " + status); this.name = "SmmError"; this.status = status; this.type = e.type ?? "api_error"; this.code = e.code ?? "unknown"; this.messageFa = e.message_fa ?? ""; this.param = e.param ?? null; this.requestId = e.request_id ?? ""; } } export interface ClientOptions { /** An API key (smm_live_… or smm_test_…) or an app access token (smm_at_…). */ apiKey: string; /** The site's address, for example https://example.com (the SDK appends /api/v3). */ baseUrl: string; /** Retries for network errors, 429 and 5xx (default 2). */ maxRetries?: number; /** Per-request timeout in milliseconds (default 30000). */ timeoutMs?: number; fetch?: typeof fetch; } export interface RequestOptions { /** Reuse the same key when you retry the same POST yourself. */ idempotencyKey?: string; signal?: AbortSignal; } interface InternalOptions extends RequestOptions { body?: unknown; query?: object; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); export class SmmClient { readonly baseUrl: string; apiKey: string; readonly maxRetries: number; readonly timeoutMs: number; readonly fetchImpl: typeof fetch; /** The last response's rate-limit headers. */ rateLimit: { limit: number; remaining: number; reset: number } | null = null; constructor(opts: ClientOptions) { if (!opts.apiKey) throw new Error("SmmClient: apiKey is required"); this.baseUrl = opts.baseUrl.replace(/\/+$/, "") + "/api/v3"; this.apiKey = opts.apiKey; this.maxRetries = opts.maxRetries ?? 2; this.timeoutMs = opts.timeoutMs ?? 30000; this.fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis); } /** Sends a request; most code calls the typed methods below instead. */ async request(method: string, path: string, opts: InternalOptions = {}): Promise { let url = this.baseUrl + path; if (opts.query) { const q = new URLSearchParams(); for (const [k, v] of Object.entries(opts.query)) { if (v !== undefined && v !== null) q.set(k, String(v)); } const s = q.toString(); if (s) url += "?" + s; } const headers: Record = { Authorization: "Bearer " + this.apiKey, Accept: "application/json" }; if (opts.body !== undefined) headers["Content-Type"] = "application/json"; if (method === "POST") headers["Idempotency-Key"] = opts.idempotencyKey ?? globalThis.crypto.randomUUID(); for (let attempt = 0; ; attempt++) { let res: Response; try { res = await this.fetchImpl(url, { method, headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body), signal: opts.signal ?? AbortSignal.timeout(this.timeoutMs), }); } catch (err) { if (attempt < this.maxRetries) { await sleep(500 * 2 ** attempt); continue; } throw err; } const lim = res.headers.get("RateLimit-Limit"); if (lim) { this.rateLimit = { limit: Number(lim), remaining: Number(res.headers.get("RateLimit-Remaining") ?? 0), reset: Number(res.headers.get("RateLimit-Reset") ?? 1), }; } if ((res.status === 429 || res.status >= 500) && attempt < this.maxRetries) { const after = Number(res.headers.get("Retry-After") ?? 0); await sleep(after > 0 ? after * 1000 : 500 * 2 ** attempt); continue; } if (res.status === 204) return undefined as T; const text = await res.text(); const data = text ? JSON.parse(text) : undefined; if (!res.ok) throw new SmmError(res.status, (data && data.error) || {}); return data as T; } } /** Iterates every item of a list endpoint, following next_cursor. */ async *paginate( list: (params: { cursor?: string; limit?: number }) => Promise<{ data: T[]; next_cursor: string | null }>, params: { limit?: number } = {}, ): AsyncGenerator { let cursor: string | undefined; for (;;) { const page = await list({ ...params, cursor }); for (const item of page.data) yield item; if (!page.next_cursor) return; cursor = page.next_cursor; } } // ---- operations ------------------------------------------------------ /** Sign the app out (revokes the current app session) */ logout(options: RequestOptions = {}): Promise { return this.request("POST", `/auth/logout`, { ...options }); } /** Send a login code to a phone number */ requestOtp(body: OtpRequest, options: RequestOptions = {}): Promise { return this.request("POST", `/auth/otp`, { body, ...options }); } /** Verify the code and receive app tokens */ verifyOtp(body: OtpVerify, options: RequestOptions = {}): Promise { return this.request("POST", `/auth/otp/verify`, { body, ...options }); } /** Rotate the refresh token and get a new access token */ refreshToken(body: RefreshRequest, options: RequestOptions = {}): Promise { return this.request("POST", `/auth/refresh`, { body, ...options }); } /** Wallet balance (the test wallet for test keys) (scope: read) */ getBalance(options: RequestOptions = {}): Promise { return this.request("GET", `/balance`, { ...options }); } /** A batch and its orders (scope: read) */ getBatch(id: number, options: RequestOptions = {}): Promise { return this.request("GET", `/batches/${encodeURIComponent(String(id))}`, { ...options }); } /** Categories (scope: read) */ listCategories(params: ListCategoriesParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/categories`, { query: params, ...options }); } /** Redeem a voucher (credited now) or a deposit coupon (applied to the next deposit) (scope: payments) */ redeemCoupon(body: CouponRedeem, options: RequestOptions = {}): Promise { return this.request("POST", `/coupons/redeem`, { body, ...options }); } /** Your events from the last 30 days, newest first (scope: read) */ listEvents(params: ListEventsParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/events`, { query: params, ...options }); } /** An event (scope: read) */ getEvent(id: number, options: RequestOptions = {}): Promise { return this.request("GET", `/events/${encodeURIComponent(String(id))}`, { ...options }); } /** Favorite services (scope: read) */ listFavorites(options: RequestOptions = {}): Promise { return this.request("GET", `/favorites`, { ...options }); } /** Add a favorite service (scope: orders) */ addFavorite(body: FavoriteCreate, options: RequestOptions = {}): Promise { return this.request("POST", `/favorites`, { body, ...options }); } /** Remove a favorite (the id is the service id) (scope: orders) */ deleteFavorite(id: number, options: RequestOptions = {}): Promise { return this.request("DELETE", `/favorites/${encodeURIComponent(String(id))}`, { ...options }); } /** Detect the platform and target of a link, and the services that accept it (scope: read) */ resolveLink(body: LinkResolveRequest, options: RequestOptions = {}): Promise { return this.request("POST", `/links/resolve`, { body, ...options }); } /** The signed-in user and the current credential (scope: read) */ getMe(options: RequestOptions = {}): Promise { return this.request("GET", `/me`, { ...options }); } /** API metadata and server time */ getMeta(options: RequestOptions = {}): Promise { return this.request("GET", `/meta`, { ...options }); } /** In-app notifications, newest first (scope: read) */ listNotifications(params: ListNotificationsParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/notifications`, { query: params, ...options }); } /** Mark one notification (id) or all of them read (scope: read) */ markNotificationsRead(body: MarkRead, options: RequestOptions = {}): Promise { return this.request("POST", `/notifications/read`, { body, ...options }); } /** Your orders, newest first (scope: read) */ listOrders(params: ListOrdersParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/orders`, { query: params, ...options }); } /** Place an order (always send an Idempotency-Key) (scope: orders) */ createOrder(body: OrderCreate, options: RequestOptions = {}): Promise { return this.request("POST", `/orders`, { body, ...options }); } /** Place up to 100 orders in one charge (scope: orders) */ createOrderBatch(body: BatchCreate, options: RequestOptions = {}): Promise { return this.request("POST", `/orders/batch`, { body, ...options }); } /** Price an order without placing it (scope: read) */ quoteOrder(body: QuoteRequest, options: RequestOptions = {}): Promise { return this.request("POST", `/orders/quote`, { body, ...options }); } /** An order (scope: read) */ getOrder(id: number, options: RequestOptions = {}): Promise { return this.request("GET", `/orders/${encodeURIComponent(String(id))}`, { ...options }); } /** Ask to cancel an order (the refund follows when it is canceled) (scope: orders) */ cancelOrder(id: number, options: RequestOptions = {}): Promise { return this.request("POST", `/orders/${encodeURIComponent(String(id))}/cancel`, { ...options }); } /** Request a refill within the service's refill window (scope: orders) */ refillOrder(id: number, options: RequestOptions = {}): Promise { return this.request("POST", `/orders/${encodeURIComponent(String(id))}/refill`, { ...options }); } /** Start a wallet top-up through the gateway (scope: payments) */ createPayment(body: PaymentCreate, options: RequestOptions = {}): Promise { return this.request("POST", `/payments`, { body, ...options }); } /** A payment (scope: read) */ getPayment(id: number, options: RequestOptions = {}): Promise { return this.request("GET", `/payments/${encodeURIComponent(String(id))}`, { ...options }); } /** Platforms (scope: read) */ listPlatforms(options: RequestOptions = {}): Promise { return this.request("GET", `/platforms`, { ...options }); } /** Your referral link, totals and recent commissions (scope: read) */ getReferrals(options: RequestOptions = {}): Promise { return this.request("GET", `/referrals`, { ...options }); } /** Your refills, newest first (scope: read) */ listRefills(params: ListRefillsParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/refills`, { query: params, ...options }); } /** A refill (scope: read) */ getRefill(id: number, options: RequestOptions = {}): Promise { return this.request("GET", `/refills/${encodeURIComponent(String(id))}`, { ...options }); } /** Your API request log (writes and errors, 14 days) (scope: read) */ listRequestLogs(params: ListRequestLogsParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/request-logs`, { query: params, ...options }); } /** Active services with your prices (scope: read) */ listServices(params: ListServicesParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/services`, { query: params, ...options }); } /** A service (scope: read) */ getService(id: number, options: RequestOptions = {}): Promise { return this.request("GET", `/services/${encodeURIComponent(String(id))}`, { ...options }); } /** Saved targets (links and usernames) (scope: read) */ listTargets(params: ListTargetsParams = {}, options: RequestOptions = {}): Promise { return this.request("GET", `/targets`, { query: params, ...options }); } /** Save a target (scope: orders) */ createTarget(body: TargetCreate, options: RequestOptions = {}): Promise { return this.request("POST", `/targets`, { body, ...options }); } /** Delete a saved target (scope: orders) */ deleteTarget(id: number, options: RequestOptions = {}): Promise { return this.request("DELETE", `/targets/${encodeURIComponent(String(id))}`, { ...options }); } /** Order templates (bulk lines) (scope: read) */ listTemplates(options: RequestOptions = {}): Promise { return this.request("GET", `/templates`, { ...options }); } /** Save a template (same name replaces it) (scope: orders) */ createTemplate(body: TemplateCreate, options: RequestOptions = {}): Promise