@cosmosapp/pay_sdk 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/managers/AnalyticsManager.ts","../src/structures/Base.ts","../src/structures/Customer.ts","../src/managers/BaseManager.ts","../src/managers/CustomerManager.ts","../src/managers/HealthManager.ts","../src/types/index.ts","../src/structures/PaymentIntent.ts","../src/common/addresses.ts","../src/common/assets.ts","../src/common/intent-input.ts","../src/managers/PaymentIntentManager.ts","../src/structures/Product.ts","../src/managers/ProductManager.ts","../src/structures/WebhookDelivery.ts","../src/structures/WebhookEndpoint.ts","../src/util/Constants.ts","../src/util/Webhooks.ts","../src/managers/WebhookManager.ts","../src/errors/CosmosPayError.ts","../src/rest/REST.ts","../src/util/shared.ts","../src/client/Client.ts","../src/common/wallets.ts"],"names":["EventEmitter","createHmac","timingSafeEqual"],"mappings":";;;;;;;;AAaO,IAAM,mBAAN,MAAuB;AAAA,EAG5B,YAAY,MAAA,EAAgB;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,IAAY,IAAA,GAAa;AACvB,IAAA,OAAO,KAAK,MAAA,CAAO,IAAA;AAAA,EACrB;AAAA;AAAA,EAGO,OAAA,GAAyC;AAC9C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA0B,UAAU,CAAA;AAAA,EACvD;AAAA;AAAA,EAGO,QAAA,GAA2C;AAChD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA2B,WAAW,CAAA;AAAA,EACzD;AAAA;AAAA,EAGO,OAAA,GAAgC;AACrC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAiB,OAAO,CAAA;AAAA,EAC3C;AAAA;AAAA,EAGO,WAAA,GAAwC;AAC7C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAqB,gBAA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AA,EACR,MAAA,EAAQ;AACV","file":"index.cjs","sourcesContent":["import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n AnalyticsBalancesData,\n AnalyticsSummaryData,\n ApiLogsData,\n WebhookLogsData,\n} from '@/types/index';\n\n/**\n * Read-only analytics derived from the consumer's intents and deliveries —\n * `client.analytics`. Powers dashboard-style Overview / Balances / Logs views.\n */\nexport class AnalyticsManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Overview metrics: totals, settled volume, webhook health, 30-day series. */\n public summary(): Promise<AnalyticsSummaryData> {\n return this.rest.get<AnalyticsSummaryData>('/summary');\n }\n\n /** Settled (and pending) amount per asset. */\n public balances(): Promise<AnalyticsBalancesData> {\n return this.rest.get<AnalyticsBalancesData>('/balances');\n }\n\n /** Recent API requests reaching the service (with details). */\n public apiLogs(): Promise<ApiLogsData> {\n return this.rest.get<ApiLogsData>('/logs');\n }\n\n /** Recent webhook deliveries across all endpoints (with details). */\n public webhookLogs(): Promise<WebhookLogsData> {\n return this.rest.get<WebhookLogsData>('/logs/webhooks');\n }\n}\n","import type { Client } from '@/client/Client';\n\n/**\n * Root of every API structure. Holds a back-reference to the {@link Client} so\n * instances can perform their own actions (e.g. `paymentIntent.delete()`), and\n * provides the `_patch`/`toJSON` plumbing shared by all structures.\n */\nexport abstract class Base<Data extends { id: string }> {\n /** The client that instantiated this structure. */\n public readonly client: Client;\n /** Unique identifier of the resource. */\n public id!: string;\n\n protected constructor(client: Client, data: Data) {\n this.client = client;\n this._patch(data);\n }\n\n /** Merge raw API data onto this instance. Subclasses override and call super. */\n protected _patch(data: Data): this {\n this.id = data.id;\n return this;\n }\n\n /** Return the raw API representation of this structure. */\n public abstract toJSON(): Data;\n\n /** Allow `String(structure)` / template literals to resolve to the id. */\n public valueOf(): string {\n return this.id;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { CustomerData, UpdateCustomerOptions } from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A customer record, optionally enriched with on-chain payment stats. */\nexport class Customer extends Base<CustomerData> {\n public consumerId!: string;\n public name!: string;\n public alias!: string | null;\n public note!: string | null;\n public email!: string | null;\n /** Optional Stellar account associated with the customer. */\n public account!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n /** Number of payment intents from this customer's account (list view only). */\n public payments: number | null = null;\n /** Number of succeeded payments (list view only). */\n public succeeded: number | null = null;\n /** Total settled amount as a decimal string (list view only). */\n public total: string | null = null;\n\n constructor(client: Client, data: CustomerData) {\n super(client, data);\n }\n\n protected override _patch(data: CustomerData): this {\n super._patch(data);\n this.consumerId = data.consumerId;\n this.name = data.name;\n this.alias = data.alias;\n this.note = data.note;\n this.email = data.email;\n this.account = data.account;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n if (data.payments !== undefined) this.payments = data.payments;\n if (data.succeeded !== undefined) this.succeeded = data.succeeded;\n if (data.total !== undefined) this.total = data.total;\n return this;\n }\n\n /** Re-fetch this customer. */\n public fetch(): Promise<Customer> {\n return this.client.customers.fetch(this.id);\n }\n\n /** Update this customer. Mutates and returns this. */\n public async edit(options: UpdateCustomerOptions): Promise<this> {\n const updated = await this.client.customers.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Delete this customer. */\n public delete() {\n return this.client.customers.delete(this.id);\n }\n\n public toJSON(): CustomerData {\n return {\n id: this.id,\n consumerId: this.consumerId,\n name: this.name,\n alias: this.alias,\n note: this.note,\n email: this.email,\n account: this.account,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n ...(this.payments !== null ? { payments: this.payments } : {}),\n ...(this.succeeded !== null ? { succeeded: this.succeeded } : {}),\n ...(this.total !== null ? { total: this.total } : {}),\n };\n }\n}\n","import { EventEmitter } from 'node:events';\nimport type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\n\n/**\n * Base class for all resource managers. Each manager owns a slice of the API\n * (payment intents, webhooks, ...) and a lightweight in-memory cache of the\n * structures it has materialized — an atomic, per-resource manager pattern.\n *\n * Extends EventEmitter so managers that surface real-time events (e.g. the\n * webhook listener) can `emit`/`on` without extra plumbing.\n */\nexport abstract class BaseManager<\n Structure extends { id: string },\n> extends EventEmitter {\n public readonly client: Client;\n /** Cache of structures keyed by id, populated on fetch/create. */\n public readonly cache: Map<string, Structure> = new Map();\n\n constructor(client: Client) {\n super();\n this.client = client;\n }\n\n /** Shortcut to the shared REST instance. */\n protected get rest(): REST {\n return this.client.rest;\n }\n\n /** Store a structure in the cache and return it. */\n protected _add(structure: Structure): Structure {\n this.cache.set(structure.id, structure);\n return structure;\n }\n\n /** Resolve an id from either a raw id or a structure instance. */\n public resolveId(idOrStructure: string | { id: string }): string {\n return typeof idOrStructure === 'string' ? idOrStructure : idOrStructure.id;\n }\n}\n","import { Customer } from '@/structures/Customer';\nimport type {\n CreateCustomerOptions,\n CustomerData,\n CustomerListData,\n UpdateCustomerOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype CustomerDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages customers — `client.customers`.\n *\n * @example\n * const customer = await client.customers.create({\n * name: 'Acme Inc.', email: 'billing@acme.com',\n * });\n */\nexport class CustomerManager extends BaseManager<Customer> {\n private readonly route = '/customers';\n\n /** Create a customer. */\n public async create(options: CreateCustomerOptions): Promise<Customer> {\n const data = await this.rest.post<CustomerData>(this.route, { body: options });\n return this._add(new Customer(this.client, data));\n }\n\n /** List the consumer's customers (with payment stats). */\n public async list(): Promise<Customer[]> {\n const data = await this.rest.get<CustomerListData>(this.route);\n return data.data.map((d) => this._add(new Customer(this.client, d)));\n }\n\n /** Get a customer by id. */\n public async fetch(id: string): Promise<Customer> {\n const data = await this.rest.get<CustomerData>(`${this.route}/${id}`);\n return this._add(new Customer(this.client, data));\n }\n\n /** Update a customer. */\n public async update(\n id: string,\n options: UpdateCustomerOptions,\n ): Promise<Customer> {\n const data = await this.rest.patch<CustomerData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Customer(this.client, data));\n }\n\n /** Delete a customer. */\n public async delete(id: string): Promise<CustomerDeletedData> {\n const result = await this.rest.delete<CustomerDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type { HealthCheckData } from '@/types/index';\n\n/**\n * Service health probes — `client.health`. These routes are public (they don't\n * require an authenticated consumer).\n */\nexport class HealthManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Liveness probe — resolves when the service is up. */\n public async liveness(): Promise<boolean> {\n await this.rest.get<unknown>('/health/liveness');\n return true;\n }\n\n /** Readiness probe (checks the database). Returns the health report. */\n public readiness(): Promise<HealthCheckData> {\n return this.rest.get<HealthCheckData>('/health/readiness');\n }\n}\n","/**\n * Type definitions for the Cosmos Pay Payments API.\n *\n * These mirror the server's OpenAPI schema (Stellar SEP-7 payment intents,\n * webhooks, products, customers and analytics). Every type is exported so\n * TypeScript consumers get full intellisense; JavaScript consumers can ignore\n * them entirely.\n */\n\nimport type { AssetRef } from '@/common/assets';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Enums (provided both as runtime objects and as string-literal unions)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Lifecycle state of a payment intent. */\nexport const PaymentIntentStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Cancelled: 'CANCELLED',\n Expired: 'EXPIRED',\n} as const;\nexport type PaymentIntentStatus =\n (typeof PaymentIntentStatus)[keyof typeof PaymentIntentStatus];\n\n/** SEP-7 operation a payment intent represents. */\nexport const PaymentIntentKind = {\n /** Source account is known → unsigned XDR + `web+stellar:tx` URI. */\n Tx: 'TX',\n /** No source → `web+stellar:pay` URI only (wallet picks the source). */\n Pay: 'PAY',\n} as const;\nexport type PaymentIntentKind =\n (typeof PaymentIntentKind)[keyof typeof PaymentIntentKind];\n\n/** Domain events an integrator can subscribe a webhook to. */\nexport const WebhookEventType = {\n PaymentIntentCreated: 'PAYMENT_INTENT_CREATED',\n PaymentIntentUpdated: 'PAYMENT_INTENT_UPDATED',\n PaymentIntentSucceeded: 'PAYMENT_INTENT_SUCCEEDED',\n PaymentIntentFailed: 'PAYMENT_INTENT_FAILED',\n PaymentIntentCancelled: 'PAYMENT_INTENT_CANCELLED',\n PaymentIntentDeleted: 'PAYMENT_INTENT_DELETED',\n} as const;\nexport type WebhookEventType =\n (typeof WebhookEventType)[keyof typeof WebhookEventType];\n\n/** Delivery state of a single webhook attempt. */\nexport const WebhookDeliveryStatus = {\n Pending: 'PENDING',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n} as const;\nexport type WebhookDeliveryStatus =\n (typeof WebhookDeliveryStatus)[keyof typeof WebhookDeliveryStatus];\n\n/** Product billing kind. */\nexport const ProductKind = {\n Recurring: 'recurring',\n OneTime: 'one_time',\n Link: 'link',\n} as const;\nexport type ProductKind = (typeof ProductKind)[keyof typeof ProductKind];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Payment intents\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/payment-intents/tx`. */\nexport interface CreateTxPaymentIntentOptions {\n /** Payer's Stellar account — the transaction source. A registered address-book name also works. */\n source: string;\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount as a decimal string (max 7 decimals). */\n amount: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code. Omit (or `XLM`/`native`) for native lumens. */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback` where the wallet POSTs the signed XDR, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `POST /v1/payment-intents/pay`. */\nexport interface CreatePayPaymentIntentOptions {\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount the destination should receive. Omit to let the user enter it (e.g. donations). */\n amount?: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code the destination receives. Omit for native lumens (XLM). */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback`, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `PATCH /v1/payment-intents/:id`. */\nexport interface UpdatePaymentIntentOptions {\n status?: PaymentIntentStatus;\n /** Stellar transaction hash once the signed tx is submitted. */\n txHash?: string;\n /** Merchant reference. */\n reference?: string;\n}\n\n/** Query for `GET /v1/payment-intents`. */\nexport interface ListPaymentIntentsOptions {\n status?: PaymentIntentStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Raw payment intent payload returned by the API. */\nexport interface PaymentIntentData {\n id: string;\n kind: PaymentIntentKind;\n status: PaymentIntentStatus;\n network: string;\n source: string | null;\n destination: string;\n amount: string | null;\n asset: string;\n assetIssuer: string | null;\n memo: string;\n msg: string | null;\n callback: string | null;\n xdr: string | null;\n uri: string;\n qr: string;\n txHash: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of payment intents. */\nexport interface PaymentIntentListData {\n data: PaymentIntentData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Body for `POST /v1/payment-intents/:id/validate`. */\nexport interface ValidatePaymentIntentOptions {\n /** Hash of the submitted Stellar transaction to validate against this intent. */\n txHash: string;\n}\n\n/** Raw outcome of a validation attempt. */\nexport interface ValidationOutcomeData {\n valid: boolean;\n status: PaymentIntentStatus;\n reason?: string | null;\n paymentIntent?: PaymentIntentData;\n}\n\n/** Raw `{ id, deleted }` response. */\nexport interface DeletedData {\n id: string;\n deleted: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Webhooks\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/webhooks`. */\nexport interface CreateWebhookEndpointOptions {\n /** HTTPS URL that will receive POSTed event notifications. */\n url: string;\n description?: string;\n /** Event types to subscribe to. Omit/empty to receive all events. */\n eventTypes?: WebhookEventType[];\n}\n\n/** Body for `PATCH /v1/webhooks/:id`. */\nexport interface UpdateWebhookEndpointOptions {\n url?: string;\n description?: string;\n /** Pause/resume deliveries to this endpoint. */\n enabled?: boolean;\n eventTypes?: WebhookEventType[];\n}\n\n/** Raw webhook endpoint payload. */\nexport interface WebhookEndpointData {\n id: string;\n url: string;\n description: string | null;\n enabled: boolean;\n eventTypes: WebhookEventType[];\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw webhook endpoint payload including the one-time signing secret. */\nexport interface WebhookEndpointWithSecretData extends WebhookEndpointData {\n /** HMAC signing secret — shown once. Store it securely. */\n secret: string;\n}\n\n/** Raw result of a webhook ping. */\nexport interface WebhookPingData {\n ok: boolean;\n responseStatus: number | null;\n error: string | null;\n}\n\n/** Raw webhook delivery (audit) record. */\nexport interface WebhookDeliveryData {\n id: string;\n endpointId: string;\n eventType: WebhookEventType;\n eventId: string;\n payload: Record<string, unknown>;\n status: WebhookDeliveryStatus;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n lastAttemptAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of webhook deliveries. */\nexport interface WebhookDeliveryListData {\n data: WebhookDeliveryData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Query for `GET /v1/webhooks/:id/deliveries`. */\nexport interface ListWebhookDeliveriesOptions {\n status?: WebhookDeliveryStatus;\n take?: number;\n skip?: number;\n}\n\n/** Shape of the JSON body POSTed to an integrator's webhook URL. */\nexport interface WebhookEvent<T = PaymentIntentData> {\n /** Stable event id (use for idempotency). */\n id: string;\n type: WebhookEventType;\n createdAt: string;\n data: T;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Products\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/products`. */\nexport interface CreateProductOptions {\n name: string;\n description?: string;\n /** Decimal price (≤ 7 decimals). Omit for a customer-set amount. */\n amount?: string;\n /** Asset code the price is in. Omit for native lumens (XLM). */\n assetCode?: string;\n kind?: ProductKind;\n active?: boolean;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/products/:id`. */\nexport type UpdateProductOptions = Partial<CreateProductOptions>;\n\n/** Raw product payload. */\nexport interface ProductData {\n id: string;\n name: string;\n description: string | null;\n amount: string | null;\n asset: string;\n kind: ProductKind;\n active: boolean;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Customers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/customers`. */\nexport interface CreateCustomerOptions {\n name: string;\n alias?: string;\n note?: string;\n email?: string;\n /** Optional Stellar account to associate the customer with. */\n account?: string;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/customers/:id`. */\nexport type UpdateCustomerOptions = Partial<CreateCustomerOptions>;\n\n/** Raw customer payload. */\nexport interface CustomerData {\n id: string;\n consumerId: string;\n name: string;\n alias: string | null;\n note: string | null;\n email: string | null;\n account: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n /** Derived on-chain stats (present in list responses). */\n payments?: number;\n succeeded?: number;\n total?: string;\n}\n\n/** Raw `{ data, total }` list of customers. */\nexport interface CustomerListData {\n data: CustomerData[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Analytics\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface AnalyticsVolumeEntry {\n asset: string;\n amount: string;\n count: number;\n}\n\nexport interface AnalyticsSeriesPoint {\n date: string;\n count: number;\n volume: string;\n}\n\nexport interface AnalyticsRecentRow {\n id: string;\n kind: string;\n status: PaymentIntentStatus;\n amount: string | null;\n asset: string;\n destination: string;\n createdAt: string;\n}\n\n/** Raw overview metrics returned by `GET /v1/summary`. */\nexport interface AnalyticsSummaryData {\n totals: {\n all: number;\n succeeded: number;\n pending: number;\n submitted: number;\n failed: number;\n cancelled: number;\n expired: number;\n successRate: number;\n };\n volume: AnalyticsVolumeEntry[];\n webhooks: {\n endpoints: number;\n deliveries: number;\n failedDeliveries: number;\n };\n customers: number;\n series: AnalyticsSeriesPoint[];\n recent: AnalyticsRecentRow[];\n}\n\nexport interface AnalyticsBalanceEntry {\n asset: string;\n amount: string;\n pending: string;\n count: number;\n}\n\n/** Raw balances returned by `GET /v1/balances`. */\nexport interface AnalyticsBalancesData {\n data: AnalyticsBalanceEntry[];\n total: number;\n}\n\nexport interface ApiLogRow {\n id: string;\n method: string;\n path: string;\n statusCode: number;\n durationMs: number;\n ip: string | null;\n userAgent: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw API request log returned by `GET /v1/logs`. */\nexport interface ApiLogsData {\n data: ApiLogRow[];\n total: number;\n}\n\nexport interface WebhookLogRow {\n id: string;\n endpointId: string;\n url: string | null;\n eventType: WebhookEventType;\n eventId: string;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw webhook delivery log returned by `GET /v1/logs/webhooks`. */\nexport interface WebhookLogsData {\n data: WebhookLogRow[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Health\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface HealthCheckData {\n status: string;\n info?: Record<string, { status: string } & Record<string, unknown>> | null;\n error?: Record<string, { status: string } & Record<string, unknown>> | null;\n details?: Record<string, { status: string } & Record<string, unknown>>;\n}\n","import type { Client } from '@/client/Client';\nimport {\n PaymentIntentKind,\n PaymentIntentStatus,\n type PaymentIntentData,\n type UpdatePaymentIntentOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A Stellar SEP-7 payment intent.\n *\n * Wraps the raw API payload with typed accessors and atomic action methods so\n * you can operate on it directly: `await intent.validate(txHash)`,\n * `await intent.cancel()`, `await intent.delete()`.\n */\nexport class PaymentIntent extends Base<PaymentIntentData> {\n public kind!: PaymentIntentKind;\n public status!: PaymentIntentStatus;\n public network!: string;\n /** Payer account (null for PAY intents). */\n public source!: string | null;\n public destination!: string;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public assetIssuer!: string | null;\n /** Mandatory MEMO_ID. */\n public memo!: string;\n public msg!: string | null;\n public callback!: string | null;\n /** Unsigned transaction envelope (base64 XDR); null for PAY intents. */\n public xdr!: string | null;\n /** SEP-7 deep link (`tx` or `pay`). */\n public uri!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n public txHash!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: PaymentIntentData) {\n super(client, data);\n }\n\n protected override _patch(data: PaymentIntentData): this {\n super._patch(data);\n this.kind = data.kind;\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.destination = data.destination;\n this.amount = data.amount;\n this.asset = data.asset;\n this.assetIssuer = data.assetIssuer;\n this.memo = data.memo;\n this.msg = data.msg;\n this.callback = data.callback;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.qr = data.qr;\n this.txHash = data.txHash;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether this is a SEP-7 `tx` intent (known source, has XDR). */\n public get isTx(): boolean {\n return this.kind === PaymentIntentKind.Tx;\n }\n\n /** Whether this is a SEP-7 `pay` intent (no source). */\n public get isPay(): boolean {\n return this.kind === PaymentIntentKind.Pay;\n }\n\n /** Whether the payment has settled on-chain. */\n public get isSucceeded(): boolean {\n return this.status === PaymentIntentStatus.Succeeded;\n }\n\n /** Whether the intent is still awaiting payment. */\n public get isPending(): boolean {\n return this.status === PaymentIntentStatus.Pending;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this intent from the API, returning a fresh instance. */\n public fetch(): Promise<PaymentIntent> {\n return this.client.paymentIntents.fetch(this.id);\n }\n\n /** Update this intent (status / txHash / reference). Mutates and returns it. */\n public async edit(options: UpdatePaymentIntentOptions): Promise<this> {\n const updated = await this.client.paymentIntents.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /**\n * Validate a submitted transaction against this intent. On a match the status\n * is finalized server-side and the webhook fires.\n */\n public validate(txHash: string) {\n return this.client.paymentIntents.validate(this.id, { txHash });\n }\n\n /** Mark this intent as cancelled. */\n public cancel(): Promise<this> {\n return this.edit({ status: PaymentIntentStatus.Cancelled });\n }\n\n /** Delete this intent. */\n public delete() {\n return this.client.paymentIntents.delete(this.id);\n }\n\n public toJSON(): PaymentIntentData {\n return {\n id: this.id,\n kind: this.kind,\n status: this.status,\n network: this.network,\n source: this.source,\n destination: this.destination,\n amount: this.amount,\n asset: this.asset,\n assetIssuer: this.assetIssuer,\n memo: this.memo,\n msg: this.msg,\n callback: this.callback,\n xdr: this.xdr,\n uri: this.uri,\n qr: this.qr,\n txHash: this.txHash,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/**\n * Stellar address helpers + a tiny named-address book.\n *\n * So integrators don't have to sprinkle raw `G...` strings everywhere (and risk\n * typos), they can name the accounts they care about once and reference them by\n * name. A plain address string always keeps working — `resolveAddress` only\n * substitutes registered names and otherwise passes the value straight through.\n */\n\n// Stellar strkeys are base32 (RFC 4648 alphabet, no padding). These checks are\n// length/prefix sanity checks, not full checksum validation.\nconst G_ADDRESS = /^G[A-Z2-7]{55}$/; // ed25519 public key (account)\nconst M_ADDRESS = /^M[A-Z2-7]{68}$/; // muxed account\nconst C_ADDRESS = /^C[A-Z2-7]{55}$/; // contract id\n\n/** Whether a value looks like a Stellar account address (`G…`). */\nexport function isStellarAddress(value: unknown): value is string {\n return typeof value === 'string' && G_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a muxed account address (`M…`). */\nexport function isMuxedAddress(value: unknown): value is string {\n return typeof value === 'string' && M_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a Soroban contract id (`C…`). */\nexport function isContractAddress(value: unknown): value is string {\n return typeof value === 'string' && C_ADDRESS.test(value);\n}\n\n/** Whether a value is any kind of Stellar address (account, muxed or contract). */\nexport function isAddress(value: unknown): value is string {\n return isStellarAddress(value) || isMuxedAddress(value) || isContractAddress(value);\n}\n\n/** Throw unless `value` is a valid Stellar account/muxed/contract address. */\nexport function assertAddress(value: unknown, label = 'address'): string {\n if (!isAddress(value)) {\n throw new TypeError(`Invalid Stellar ${label}: ${String(value)}`);\n }\n return value;\n}\n\n/**\n * A registry of named Stellar addresses. Register the accounts you use a lot —\n * your merchant payout account, a treasury, frequent counterparties — and refer\n * to them by name anywhere an address is accepted.\n *\n * @example\n * addresses.define('merchant', 'GC...');\n * await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });\n */\nexport class AddressBook {\n private readonly entries = new Map<string, string>();\n\n constructor(initial: Record<string, string> = {}) {\n for (const [name, address] of Object.entries(initial)) {\n this.define(name, address);\n }\n }\n\n /** Register (or overwrite) a named address. The address is validated. */\n public define(name: string, address: string): this {\n this.entries.set(name, assertAddress(address, `address for \"${name}\"`));\n return this;\n }\n\n /** Whether a name is registered. */\n public has(name: string): boolean {\n return this.entries.has(name);\n }\n\n /** Look up a registered address by name. */\n public get(name: string): string | undefined {\n return this.entries.get(name);\n }\n\n /** Remove a named address. */\n public delete(name: string): boolean {\n return this.entries.delete(name);\n }\n\n /** All registered names. */\n public names(): string[] {\n return [...this.entries.keys()];\n }\n\n /**\n * Resolve a reference to a concrete address: a registered name is substituted,\n * any other string is returned unchanged (so raw `G…`, muxed `M…`, federation\n * `name*domain`, etc. all keep working).\n */\n public resolve(ref: string): string {\n return this.entries.get(ref) ?? ref;\n }\n}\n\n/** Process-wide default address book. Use `addresses.define(...)` to populate it. */\nexport const addresses = new AddressBook();\n\n/** Anything accepted where an address is expected: a raw address or a name in a book. */\nexport type AddressRef = string;\n\n/**\n * Resolve an {@link AddressRef} using the given book (the shared {@link addresses}\n * by default). Lenient: unknown strings pass through unchanged.\n */\nexport function resolveAddress(ref: AddressRef, book: AddressBook = addresses): string {\n return book.resolve(ref);\n}\n","/**\n * A typed, extensible catalog of Stellar assets.\n *\n * Instead of hunting down an asset's issuer (or pasting the wrong one), use the\n * built-in catalog — `Assets.USDC`, `Assets.EURC`, `Assets.XLM` — which carries\n * the verified issuer for you. Need something else? `defineAsset(...)` makes a\n * typed asset you can reuse. And a plain code string still works everywhere.\n *\n * ⚠️ Issuers are network-specific. The {@link Assets} catalog targets **mainnet**;\n * {@link TestnetAssets} carries the testnet issuers. Bare code strings (e.g.\n * `'USDC'`) are treated as *code only* (no issuer) for backwards compatibility —\n * use the catalog object or `defineAsset` when you want the issuer filled in.\n */\n\nimport { isStellarAddress } from '@/common/addresses';\n\n/** A fully-described Stellar asset. */\nexport interface AssetDefinition {\n /** Asset code, e.g. `USDC`. Use `XLM` (or omit the issuer) for native lumens. */\n code: string;\n /** Issuer account (`G…`). `null`/omitted means the native asset (XLM). */\n issuer?: string | null;\n /** Optional Soroban contract id (`C…`) for the SAC / token contract. */\n contract?: string;\n /** Human-readable name. */\n name?: string;\n /** Network the `issuer` is valid on. */\n network?: 'public' | 'testnet';\n}\n\n/** Anything accepted where an asset is expected: a code string or a definition. */\nexport type AssetRef = string | AssetDefinition;\n\n/** Normalized asset: a code plus a concrete issuer (or `null` for native). */\nexport interface ResolvedAsset {\n /** `XLM` for the native asset, otherwise the asset code. */\n code: string;\n /** Issuer `G…`, or `null` for the native asset. */\n issuer: string | null;\n /** Optional Soroban contract id. */\n contract?: string;\n}\n\nconst NATIVE: AssetDefinition = { code: 'XLM', issuer: null, name: 'Stellar Lumens' };\n\n/**\n * Built-in **mainnet** assets with verified issuers. Extend with your own via\n * {@link defineAsset}. Issuers sourced from the official issuers (Circle for\n * USDC/EURC).\n */\nexport const Assets = {\n /** Native lumens. */\n XLM: NATIVE,\n /** USD Coin by Circle (mainnet). */\n USDC: {\n code: 'USDC',\n issuer: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN',\n name: 'USD Coin',\n network: 'public',\n },\n /** Euro Coin by Circle (mainnet). */\n EURC: {\n code: 'EURC',\n issuer: 'GDHU6WRG4IEQXM5NZ4BMPKOXHW76MZM4Y2IEMFDVXBSDP6SJY4ITNPP2',\n name: 'Euro Coin',\n network: 'public',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Built-in **testnet** assets (Circle's Test SDF Network issuers). */\nexport const TestnetAssets = {\n XLM: NATIVE,\n USDC: {\n code: 'USDC',\n issuer: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5',\n name: 'USD Coin',\n network: 'testnet',\n },\n EURC: {\n code: 'EURC',\n issuer: 'GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU25GO7VTC3NM2ZTVO',\n name: 'Euro Coin',\n network: 'testnet',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Whether a reference denotes the native asset (XLM). */\nexport function isNativeAsset(ref: AssetRef): boolean {\n if (typeof ref === 'string') {\n const code = ref.trim().toLowerCase();\n return code === '' || code === 'xlm' || code === 'native';\n }\n return !ref.issuer || isNativeAsset(ref.code);\n}\n\n/**\n * Create a reusable, typed custom asset. Validates the issuer/contract format so\n * a typo surfaces immediately rather than on-chain.\n *\n * @example\n * const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ...', name: 'Aquarius' });\n * await client.paymentIntents.createPay({ destination, amount: '5', asset: AQUA });\n */\nexport function defineAsset(def: AssetDefinition): AssetDefinition {\n if (!def.code) throw new TypeError('defineAsset requires a `code`.');\n if (def.issuer != null && !isStellarAddress(def.issuer)) {\n throw new TypeError(`defineAsset: invalid issuer for ${def.code}: ${def.issuer}`);\n }\n if (def.contract != null && !/^C[A-Z2-7]{55}$/.test(def.contract)) {\n throw new TypeError(`defineAsset: invalid contract for ${def.code}: ${def.contract}`);\n }\n return Object.freeze({ ...def });\n}\n\n/**\n * Normalize an {@link AssetRef} into `{ code, issuer, contract }`.\n *\n * - A bare string is treated as *code only* (`issuer: null`) — pass a catalog\n * object or `defineAsset(...)` result when you want the issuer included.\n * - The native asset normalizes to `{ code: 'XLM', issuer: null }`.\n */\nexport function resolveAsset(ref: AssetRef): ResolvedAsset {\n if (isNativeAsset(ref)) return { code: 'XLM', issuer: null };\n if (typeof ref === 'string') return { code: ref, issuer: null };\n return {\n code: ref.code,\n issuer: ref.issuer ?? null,\n ...(ref.contract ? { contract: ref.contract } : {}),\n };\n}\n","/**\n * Shared resolution of \"create intent\" input, used by both the server SDK and\n * the web client so the convenience layers behave identically: a typed\n * {@link AssetRef} (e.g. `Assets.USDC`) is expanded into `assetCode`/`assetIssuer`,\n * and named addresses are substituted via an {@link AddressBook}.\n */\n\nimport { addresses as defaultBook, AddressBook, resolveAddress } from '@/common/addresses';\nimport { resolveAsset, type AssetRef } from '@/common/assets';\n\n/** Fields the resolver understands (everything else passes through untouched). */\nexport interface ResolvableIntentInput {\n destination?: string;\n source?: string;\n /** Typed asset (`Assets.USDC`, `defineAsset(...)`) — fills code + issuer. */\n asset?: AssetRef;\n assetCode?: string;\n assetIssuer?: string;\n}\n\n/**\n * Expand `asset` into `assetCode`/`assetIssuer` and resolve named\n * `destination`/`source` addresses. Existing `assetCode`/`assetIssuer` win over a\n * provided `asset`; native assets leave the code unset (the API treats an omitted\n * asset as native XLM). Returns a new object — the input is not mutated.\n */\nexport function resolveIntentBody<T extends ResolvableIntentInput>(\n options: T,\n book: AddressBook = defaultBook,\n): Omit<T, 'asset'> {\n const out: Record<string, unknown> = { ...(options as Record<string, unknown>) };\n\n if (typeof out['destination'] === 'string') {\n out['destination'] = resolveAddress(out['destination'], book);\n }\n if (typeof out['source'] === 'string') {\n out['source'] = resolveAddress(out['source'], book);\n }\n\n if (out['asset'] != null) {\n const { code, issuer } = resolveAsset(out['asset'] as AssetRef);\n delete out['asset'];\n if (issuer) {\n // Non-native: fill code + issuer unless the caller set them explicitly.\n out['assetCode'] ??= code;\n out['assetIssuer'] ??= issuer;\n }\n // Native (issuer == null) → leave assetCode/assetIssuer omitted = native XLM.\n }\n\n return out as Omit<T, 'asset'>;\n}\n","import { PaymentIntent } from '@/structures/PaymentIntent';\nimport type {\n CreatePayPaymentIntentOptions,\n CreateTxPaymentIntentOptions,\n DeletedData,\n ListPaymentIntentsOptions,\n PaymentIntentData,\n PaymentIntentListData,\n UpdatePaymentIntentOptions,\n ValidatePaymentIntentOptions,\n ValidationOutcomeData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { resolveIntentBody } from '@/common/intent-input';\n\n/** A page of payment intents plus its pagination metadata. */\nexport interface PaymentIntentPage {\n items: PaymentIntent[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Validation outcome with the (optional) refreshed intent materialized. */\nexport interface ValidationOutcome {\n valid: boolean;\n status: ValidationOutcomeData['status'];\n reason: string | null;\n paymentIntent: PaymentIntent | null;\n}\n\n/**\n * Manages Stellar payment intents — `client.paymentIntents`.\n *\n * @example\n * const intent = await client.paymentIntents.createTx({\n * source: 'G...', destination: 'G...', amount: '25.5',\n * });\n * console.log(intent.uri, intent.qr);\n */\nexport class PaymentIntentManager extends BaseManager<PaymentIntent> {\n private readonly route = '/payment-intents';\n\n /** Create a SEP-7 `tx` intent (source known → unsigned XDR + tx URI + QR). */\n public async createTx(\n options: CreateTxPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/tx`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Create a SEP-7 `pay` intent (no source → pay URI + QR, no XDR). */\n public async createPay(\n options: CreatePayPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/pay`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Get a single payment intent by id. */\n public async fetch(id: string): Promise<PaymentIntent> {\n const data = await this.rest.get<PaymentIntentData>(`${this.route}/${id}`);\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** List the consumer's payment intents (paginated). */\n public async list(\n options: ListPaymentIntentsOptions = {},\n ): Promise<PaymentIntentPage> {\n const data = await this.rest.get<PaymentIntentListData>(this.route, {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new PaymentIntent(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Update a payment intent (status / txHash / reference). */\n public async update(\n id: string,\n options: UpdatePaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.patch<PaymentIntentData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Delete a payment intent. */\n public async delete(id: string): Promise<DeletedData> {\n const result = await this.rest.delete<DeletedData>(`${this.route}/${id}`);\n this.cache.delete(id);\n return result;\n }\n\n /**\n * Validate a submitted transaction against the intent (tx success +\n * destination + amount + memo). Finalizes status server-side and fires events.\n */\n public async validate(\n id: string,\n options: ValidatePaymentIntentOptions,\n ): Promise<ValidationOutcome> {\n const data = await this.rest.post<ValidationOutcomeData>(\n `${this.route}/${id}/validate`,\n { body: options },\n );\n const paymentIntent = data.paymentIntent\n ? this._add(new PaymentIntent(this.client, data.paymentIntent))\n : null;\n return {\n valid: data.valid,\n status: data.status,\n reason: data.reason ?? null,\n paymentIntent,\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n ProductKind,\n type ProductData,\n type UpdateProductOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A product / price the consumer can charge for. */\nexport class Product extends Base<ProductData> {\n public name!: string;\n public description!: string | null;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public kind!: ProductKind;\n public active!: boolean;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: ProductData) {\n super(client, data);\n }\n\n protected override _patch(data: ProductData): this {\n super._patch(data);\n this.name = data.name;\n this.description = data.description;\n this.amount = data.amount;\n this.asset = data.asset;\n this.kind = data.kind;\n this.active = data.active;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this product. */\n public fetch(): Promise<Product> {\n return this.client.products.fetch(this.id);\n }\n\n /** Update this product. Mutates and returns this. */\n public async edit(options: UpdateProductOptions): Promise<this> {\n const updated = await this.client.products.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Mark the product active. */\n public activate(): Promise<this> {\n return this.edit({ active: true });\n }\n\n /** Mark the product inactive. */\n public deactivate(): Promise<this> {\n return this.edit({ active: false });\n }\n\n /** Delete this product. */\n public delete() {\n return this.client.products.delete(this.id);\n }\n\n public toJSON(): ProductData {\n return {\n id: this.id,\n name: this.name,\n description: this.description,\n amount: this.amount,\n asset: this.asset,\n kind: this.kind,\n active: this.active,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { Product } from '@/structures/Product';\nimport type {\n CreateProductOptions,\n ProductData,\n UpdateProductOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype ProductDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages products / prices — `client.products`.\n *\n * @example\n * const product = await client.products.create({\n * name: 'Pro plan — monthly', amount: '49.00', assetCode: 'USDC',\n * });\n */\nexport class ProductManager extends BaseManager<Product> {\n private readonly route = '/products';\n\n /** Create a product. */\n public async create(options: CreateProductOptions): Promise<Product> {\n const data = await this.rest.post<ProductData>(this.route, { body: options });\n return this._add(new Product(this.client, data));\n }\n\n /** List the consumer's products. */\n public async list(): Promise<Product[]> {\n const data = await this.rest.get<ProductData[]>(this.route);\n return data.map((d) => this._add(new Product(this.client, d)));\n }\n\n /** Get a product by id. */\n public async fetch(id: string): Promise<Product> {\n const data = await this.rest.get<ProductData>(`${this.route}/${id}`);\n return this._add(new Product(this.client, data));\n }\n\n /** Update a product. */\n public async update(\n id: string,\n options: UpdateProductOptions,\n ): Promise<Product> {\n const data = await this.rest.patch<ProductData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Product(this.client, data));\n }\n\n /** Delete a product. */\n public async delete(id: string): Promise<ProductDeletedData> {\n const result = await this.rest.delete<ProductDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n WebhookDeliveryStatus,\n WebhookEventType,\n type WebhookDeliveryData,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A single attempt to deliver an event to a webhook endpoint (audit record). */\nexport class WebhookDelivery extends Base<WebhookDeliveryData> {\n public endpointId!: string;\n public eventType!: WebhookEventType;\n public eventId!: string;\n public payload!: Record<string, unknown>;\n public status!: WebhookDeliveryStatus;\n public attempts!: number;\n public responseStatus!: number | null;\n public error!: string | null;\n public lastAttemptAt!: Date | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: WebhookDeliveryData) {\n super(client, data);\n }\n\n protected override _patch(data: WebhookDeliveryData): this {\n super._patch(data);\n this.endpointId = data.endpointId;\n this.eventType = data.eventType;\n this.eventId = data.eventId;\n this.payload = data.payload;\n this.status = data.status;\n this.attempts = data.attempts;\n this.responseStatus = data.responseStatus;\n this.error = data.error;\n this.lastAttemptAt = data.lastAttemptAt ? new Date(data.lastAttemptAt) : null;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n public get isSucceeded(): boolean {\n return this.status === WebhookDeliveryStatus.Succeeded;\n }\n\n /** Manually re-send this delivery. */\n public redeliver(): Promise<WebhookDelivery> {\n return this.client.webhooks.redeliver(this.endpointId, this.id);\n }\n\n public toJSON(): WebhookDeliveryData {\n return {\n id: this.id,\n endpointId: this.endpointId,\n eventType: this.eventType,\n eventId: this.eventId,\n payload: this.payload,\n status: this.status,\n attempts: this.attempts,\n responseStatus: this.responseStatus,\n error: this.error,\n lastAttemptAt: this.lastAttemptAt ? this.lastAttemptAt.toISOString() : null,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport type {\n ListWebhookDeliveriesOptions,\n UpdateWebhookEndpointOptions,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEventType,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A registered webhook endpoint.\n *\n * Note: the signing `secret` is only ever present on the instance returned by\n * `create()` / `rotateSecret()` — list/get responses never include it.\n */\nexport class WebhookEndpoint extends Base<WebhookEndpointData> {\n public url!: string;\n public description!: string | null;\n public enabled!: boolean;\n public eventTypes!: WebhookEventType[];\n public createdAt!: Date;\n public updatedAt!: Date;\n /** HMAC signing secret — only set on create/rotate responses. */\n public readonly secret: string | null;\n\n constructor(\n client: Client,\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ) {\n super(client, data);\n this.secret = 'secret' in data ? data.secret : null;\n }\n\n protected override _patch(\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ): this {\n super._patch(data);\n this.url = data.url;\n this.description = data.description;\n this.enabled = data.enabled;\n this.eventTypes = data.eventTypes;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether the endpoint receives all events (empty subscription). */\n public get receivesAllEvents(): boolean {\n return this.eventTypes.length === 0;\n }\n\n /** Re-fetch this endpoint. */\n public fetch(): Promise<WebhookEndpoint> {\n return this.client.webhooks.fetch(this.id);\n }\n\n /** Update url/description/enabled/eventTypes. Mutates and returns this. */\n public async edit(options: UpdateWebhookEndpointOptions): Promise<this> {\n const updated = await this.client.webhooks.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Pause deliveries to this endpoint. */\n public disable(): Promise<this> {\n return this.edit({ enabled: false });\n }\n\n /** Resume deliveries to this endpoint. */\n public enable(): Promise<this> {\n return this.edit({ enabled: true });\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public rotateSecret(): Promise<WebhookEndpoint> {\n return this.client.webhooks.rotateSecret(this.id);\n }\n\n /** Send a test event to verify the endpoint. */\n public ping() {\n return this.client.webhooks.ping(this.id);\n }\n\n /** List delivery attempts for this endpoint. */\n public fetchDeliveries(options?: ListWebhookDeliveriesOptions) {\n return this.client.webhooks.fetchDeliveries(this.id, options);\n }\n\n /** Delete this endpoint. */\n public delete() {\n return this.client.webhooks.delete(this.id);\n }\n\n public toJSON(): WebhookEndpointData {\n return {\n id: this.id,\n url: this.url,\n description: this.description,\n enabled: this.enabled,\n eventTypes: this.eventTypes,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/** Library version, kept in sync with package.json. */\nexport const version = '1.1.0';\n\n/**\n * Default base URL of the Cosmos Pay gateway. Maintained by Cosmos Pay — users\n * never need to set this; it's part of the {@link shared} configuration. Override\n * only when self-hosting or pointing at a staging gateway.\n *\n * This is the public APISIX gateway: requests under `/cosmos-api/*` are\n * authenticated (API key) and proxied to the Payments API. The version segment\n * (`/v1`, see {@link DEFAULT_VERSION}) is appended by the REST layer, producing\n * e.g. `https://api.cosmospay.lat/cosmos-api/v1/payment-intents/pay`.\n */\nexport const DEFAULT_BASE_URL = 'https://api.cosmospay.lat/cosmos-api';\n\n/** Default API version segment prefixed to every route (`/v1/...`). */\nexport const DEFAULT_VERSION = 'v1';\n\n/** Default request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT = 30_000;\n\n/** Default number of retries for transient failures (network / 429 / 5xx). */\nexport const DEFAULT_RETRIES = 2;\n\n/** Default HMAC signature header sent by the Cosmos Pay webhook dispatcher. */\nexport const SIGNATURE_HEADER = 'x-cosmos-signature';\n\n/**\n * Client debug/telemetry events. The {@link Client} extends EventEmitter and\n * emits these for observability (`debug`/`rateLimit`-style events).\n */\nexport const Events = {\n Debug: 'debug',\n Request: 'request',\n Response: 'response',\n RateLimited: 'rateLimited',\n} as const;\nexport type ClientEvent = (typeof Events)[keyof typeof Events];\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\nimport type { WebhookEvent } from '@/types/index';\n\n/** Options for {@link Webhooks.verify} / {@link Webhooks.constructEvent}. */\nexport interface VerifyWebhookOptions {\n /**\n * Tolerance in seconds between the signed timestamp and now. Protects against\n * replay attacks. Defaults to 300 (5 minutes). Pass 0 to disable the check.\n */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — useful for testing. */\n now?: number;\n}\n\n/** Thrown when a webhook signature fails verification. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WebhookSignatureError';\n }\n}\n\n/**\n * Stateless helpers to verify the HMAC signatures the Cosmos Pay dispatcher\n * sends with each webhook delivery, and to safely parse the event body.\n *\n * The dispatcher signs each POST with:\n * `X-Cosmos-Signature: t=<unixSeconds>,v1=<hexHmacSha256>`\n * where the HMAC-SHA256 is computed over `${t}.${rawBody}` using the endpoint's\n * `whsec_...` secret.\n *\n * @example\n * // Express raw-body handler\n * app.post('/hooks', express.raw({ type: '*​/*' }), (req, res) => {\n * try {\n * const event = Webhooks.constructEvent(\n * req.body, // the RAW body (Buffer/string)\n * req.header('X-Cosmos-Signature'),\n * process.env.WEBHOOK_SECRET,\n * );\n * // event.type, event.data ...\n * res.sendStatus(200);\n * } catch {\n * res.sendStatus(400);\n * }\n * });\n */\nexport const Webhooks = {\n /** Header name the dispatcher uses for the signature. */\n SIGNATURE_HEADER,\n\n /**\n * Verify a webhook signature. Returns `true` on success, throws\n * {@link WebhookSignatureError} on any failure (so it never silently passes).\n */\n verify(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): boolean {\n if (!signatureHeader) {\n throw new WebhookSignatureError('Missing signature header.');\n }\n if (!secret) {\n throw new WebhookSignatureError('Missing signing secret.');\n }\n\n const { timestamp, signature } = parseSignatureHeader(signatureHeader);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n\n const expected = createHmac('sha256', secret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n\n if (!safeEqualHex(expected, signature)) {\n throw new WebhookSignatureError('Signature mismatch.');\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n if (tolerance > 0) {\n const now = options.now ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n throw new WebhookSignatureError(\n `Timestamp outside tolerance (${tolerance}s).`,\n );\n }\n }\n\n return true;\n },\n\n /**\n * Verify the signature and return the parsed {@link WebhookEvent}. Throws\n * {@link WebhookSignatureError} if verification fails.\n */\n constructEvent<T = unknown>(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): WebhookEvent<T> {\n this.verify(rawBody, signatureHeader, secret, options);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n try {\n return JSON.parse(payload) as WebhookEvent<T>;\n } catch {\n throw new WebhookSignatureError('Body is not valid JSON.');\n }\n },\n};\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction parseSignatureHeader(header: string): {\n timestamp: number;\n signature: string;\n} {\n let timestamp: number | undefined;\n let signature: string | undefined;\n for (const part of header.split(',')) {\n const [key, value] = part.split('=');\n if (!key || value === undefined) continue;\n const k = key.trim();\n if (k === 't') timestamp = Number(value.trim());\n else if (k === 'v1') signature = value.trim();\n }\n if (timestamp === undefined || Number.isNaN(timestamp) || !signature) {\n throw new WebhookSignatureError('Malformed signature header.');\n }\n return { timestamp, signature };\n}\n\nfunction safeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n try {\n return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));\n } catch {\n return false;\n }\n}\n\nfunction decode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('utf8');\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { WebhookDelivery } from '@/structures/WebhookDelivery';\nimport { WebhookEndpoint } from '@/structures/WebhookEndpoint';\nimport type {\n CreateWebhookEndpointOptions,\n ListWebhookDeliveriesOptions,\n PaymentIntentData,\n UpdateWebhookEndpointOptions,\n WebhookDeliveryData,\n WebhookDeliveryListData,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEvent,\n WebhookPingData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { Webhooks, WebhookSignatureError } from '@/util/Webhooks';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\n\n// Local alias — the deleted shape mirrors DeletedData.\ntype WebhookDeletedData = { id: string; deleted: boolean };\n\n/** A page of webhook deliveries plus its pagination metadata. */\nexport interface WebhookDeliveryPage {\n items: WebhookDelivery[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Options for verifying + dispatching an incoming webhook. */\nexport interface WebhookProcessOptions {\n /** Signing secret. Falls back to the client's `webhookSecret` when omitted. */\n secret?: string;\n /** Replay tolerance in seconds (default 300; 0 disables). */\n toleranceSeconds?: number;\n}\n\n/** Options for the built-in HTTP webhook handlers. */\nexport type WebhookHandlerOptions = WebhookProcessOptions;\n\n/**\n * Listener signatures for {@link WebhookManager}. You can subscribe with the raw\n * event type (`PAYMENT_INTENT_SUCCEEDED`), its camelCase alias\n * (`paymentIntentSucceeded`), or `event` to catch them all.\n */\nexport interface WebhookListenerEvents {\n event: [WebhookEvent<PaymentIntentData>];\n\n PAYMENT_INTENT_CREATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_UPDATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_SUCCEEDED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_FAILED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_CANCELLED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_DELETED: [WebhookEvent<PaymentIntentData>];\n\n paymentIntentCreated: [WebhookEvent<PaymentIntentData>];\n paymentIntentUpdated: [WebhookEvent<PaymentIntentData>];\n paymentIntentSucceeded: [WebhookEvent<PaymentIntentData>];\n paymentIntentFailed: [WebhookEvent<PaymentIntentData>];\n paymentIntentCancelled: [WebhookEvent<PaymentIntentData>];\n paymentIntentDeleted: [WebhookEvent<PaymentIntentData>];\n}\n\n/** Minimal Express-like request (so we don't depend on `@types/express`). */\ninterface RequestLike {\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n rawBody?: unknown;\n [key: string]: unknown;\n}\n\n/** Minimal Express-like response. */\ninterface ResponseLike {\n status(code: number): ResponseLike;\n send(body?: unknown): unknown;\n end(body?: unknown): unknown;\n}\n\n// Typed event overloads (declaration merging onto the class).\nexport interface WebhookManager {\n on<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n once<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n off<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n emit<E extends keyof WebhookListenerEvents>(\n event: E,\n ...args: WebhookListenerEvents[E]\n ): boolean;\n}\n\n/**\n * Manages webhook endpoints, their delivery audit trail, **and** the incoming\n * event listener — `client.webhooks`.\n *\n * Registering endpoints (server-side CRUD):\n * @example\n * const endpoint = await client.webhooks.create({\n * url: 'https://me.example.com/hooks',\n * eventTypes: ['PAYMENT_INTENT_SUCCEEDED'],\n * });\n * console.log(endpoint.secret); // shown once — store it!\n *\n * Receiving events (listener):\n * @example\n * client.webhooks.on('paymentIntentSucceeded', (event) => {\n * console.log('Paid!', event.data.id);\n * });\n *\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler()).listen(4242);\n */\nexport class WebhookManager extends BaseManager<WebhookEndpoint> {\n private readonly route = '/webhooks';\n\n // ── Endpoint CRUD ───────────────────────────────────────────────────────────\n\n /** Register a webhook endpoint (the returned instance carries the secret once). */\n public async create(\n options: CreateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(this.route, {\n body: options,\n });\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** List the consumer's webhook endpoints. */\n public async list(): Promise<WebhookEndpoint[]> {\n const data = await this.rest.get<WebhookEndpointData[]>(this.route);\n return data.map((d) => this._add(new WebhookEndpoint(this.client, d)));\n }\n\n /** Get a webhook endpoint by id. */\n public async fetch(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.get<WebhookEndpointData>(`${this.route}/${id}`);\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Update a webhook endpoint (url/description/enabled/eventTypes). */\n public async update(\n id: string,\n options: UpdateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.patch<WebhookEndpointData>(\n `${this.route}/${id}`,\n { body: options },\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Delete a webhook endpoint. */\n public async delete(id: string): Promise<WebhookDeletedData> {\n const result = await this.rest.delete<WebhookDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public async rotateSecret(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(\n `${this.route}/${id}/rotate-secret`,\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Send a test event to verify the endpoint. */\n public ping(id: string): Promise<WebhookPingData> {\n return this.rest.post<WebhookPingData>(`${this.route}/${id}/ping`);\n }\n\n /** List delivery attempts for an endpoint (audit trail). */\n public async fetchDeliveries(\n id: string,\n options: ListWebhookDeliveriesOptions = {},\n ): Promise<WebhookDeliveryPage> {\n const data = await this.rest.get<WebhookDeliveryListData>(\n `${this.route}/${id}/deliveries`,\n {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n },\n );\n return {\n items: data.data.map((d) => new WebhookDelivery(this.client, d)),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Manually re-send a past delivery. */\n public async redeliver(\n id: string,\n deliveryId: string,\n ): Promise<WebhookDelivery> {\n const data = await this.rest.post<WebhookDeliveryData>(\n `${this.route}/${id}/deliveries/${deliveryId}/redeliver`,\n );\n return new WebhookDelivery(this.client, data);\n }\n\n // ── Incoming event listener ──────────────────────────────────────────────────\n\n /**\n * Verify a raw incoming webhook request and dispatch it to the listeners\n * registered via {@link WebhookManager.on}. Returns the parsed event.\n *\n * Emits, in order: the raw type (`PAYMENT_INTENT_SUCCEEDED`), the camelCase\n * alias (`paymentIntentSucceeded`) and the catch-all `event`.\n *\n * @throws {WebhookSignatureError} when the signature is missing/invalid.\n */\n public process(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n options: WebhookProcessOptions = {},\n ): WebhookEvent<PaymentIntentData> {\n const secret = options.secret ?? this.client.webhookSecret;\n if (!secret) {\n throw new WebhookSignatureError(\n 'No webhook secret configured. Pass `{ secret }` or set `webhookSecret` on the client.',\n );\n }\n\n const event = Webhooks.constructEvent<PaymentIntentData>(\n rawBody,\n signatureHeader,\n secret,\n { toleranceSeconds: options.toleranceSeconds },\n );\n\n this.emit(event.type, event);\n this.emit(toCamelEvent(event.type), event);\n this.emit('event', event);\n return event;\n }\n\n /**\n * Build a Node.js `http`/`https` request handler that verifies the signature,\n * dispatches the event to your listeners, and replies `200`/`400`.\n *\n * @example\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler({ secret })).listen(4242);\n */\n public createHandler(\n options: WebhookHandlerOptions = {},\n ): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void this.collectBody(req)\n .then((raw) => {\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n this.process(raw, sig, options);\n res.statusCode = 200;\n res.end('ok');\n })\n .catch((err: unknown) => {\n res.statusCode = err instanceof WebhookSignatureError ? 400 : 500;\n res.end(\n err instanceof WebhookSignatureError ? 'invalid signature' : 'error',\n );\n });\n };\n }\n\n /**\n * Express-style middleware. Expects the **raw** body (e.g. mounted with\n * `express.raw({ type: '*​/*' })`). On success it attaches the parsed event to\n * `req.cosmosEvent` and calls `next()`; on a bad signature it replies `400`.\n *\n * @example\n * app.post('/hooks', express.raw({ type: '*​/*' }), client.webhooks.middleware({ secret }));\n */\n public middleware(\n options: WebhookHandlerOptions = {},\n ): (req: RequestLike, res: ResponseLike, next: (err?: unknown) => void) => void {\n return (req, res, next) => {\n try {\n const raw = extractRawBody(req);\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n const event = this.process(raw, sig, options);\n req.cosmosEvent = event;\n next();\n } catch (err) {\n if (err instanceof WebhookSignatureError) {\n res.status(400).send('invalid signature');\n return;\n }\n next(err);\n }\n };\n }\n\n /** Read a Node.js request stream into a single Buffer. */\n private collectBody(req: IncomingMessage): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\n/** `PAYMENT_INTENT_SUCCEEDED` → `paymentIntentSucceeded`. */\nfunction toCamelEvent(type: string): keyof WebhookListenerEvents {\n return type\n .toLowerCase()\n .replace(/_([a-z])/g, (_, c: string) =>\n c.toUpperCase(),\n ) as keyof WebhookListenerEvents;\n}\n\nfunction headerValue(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction extractRawBody(req: RequestLike): string | Uint8Array {\n const candidate = req.rawBody ?? req.body;\n if (typeof candidate === 'string' || candidate instanceof Uint8Array) {\n return candidate;\n }\n // express.json() already parsed it — re-stringify so the signature still matches\n // only if the original raw body is unavailable (best-effort).\n if (candidate && typeof candidate === 'object') {\n return JSON.stringify(candidate);\n }\n return '';\n}\n","/**\n * Error thrown when the Cosmos Pay API responds with a non-2xx status.\n *\n * Carries the HTTP status, the parsed response body and the request context so\n * callers can branch on `error.status` (e.g. 404 → not found, 403 → gateway).\n */\nexport class CosmosPayAPIError extends Error {\n /** HTTP status code returned by the API. */\n public readonly status: number;\n /** HTTP method of the failed request. */\n public readonly method: string;\n /** Absolute URL of the failed request. */\n public readonly url: string;\n /** Parsed response body (object when JSON, string otherwise, or null). */\n public readonly body: unknown;\n /** Machine-readable error code extracted from the body when present. */\n public readonly code: string | undefined;\n\n constructor(options: {\n status: number;\n method: string;\n url: string;\n body: unknown;\n }) {\n const message = CosmosPayAPIError.resolveMessage(options.status, options.body);\n super(message);\n this.name = 'CosmosPayAPIError';\n this.status = options.status;\n this.method = options.method;\n this.url = options.url;\n this.body = options.body;\n this.code = CosmosPayAPIError.resolveCode(options.body);\n Error.captureStackTrace?.(this, CosmosPayAPIError);\n }\n\n private static resolveMessage(status: number, body: unknown): string {\n if (body && typeof body === 'object') {\n const maybe = body as { message?: unknown; error?: unknown };\n const msg = maybe.message ?? maybe.error;\n if (Array.isArray(msg)) return `[${status}] ${msg.join(', ')}`;\n if (typeof msg === 'string') return `[${status}] ${msg}`;\n }\n if (typeof body === 'string' && body.length) return `[${status}] ${body}`;\n return `[${status}] Request failed`;\n }\n\n private static resolveCode(body: unknown): string | undefined {\n if (body && typeof body === 'object') {\n const maybe = body as { code?: unknown; error?: unknown };\n if (typeof maybe.code === 'string') return maybe.code;\n if (typeof maybe.error === 'string') return maybe.error;\n }\n return undefined;\n }\n}\n\n/**\n * Error thrown when a request never reaches the API: network failure, abort or\n * timeout. Distinct from {@link CosmosPayAPIError}, which always has a status.\n */\nexport class CosmosPayRequestError extends Error {\n public readonly method: string;\n public readonly url: string;\n public readonly cause: unknown;\n\n constructor(options: { method: string; url: string; cause: unknown }) {\n const reason =\n options.cause instanceof Error ? options.cause.message : String(options.cause);\n super(`Request to ${options.method} ${options.url} failed: ${reason}`);\n this.name = 'CosmosPayRequestError';\n this.method = options.method;\n this.url = options.url;\n this.cause = options.cause;\n Error.captureStackTrace?.(this, CosmosPayRequestError);\n }\n}\n","import { EventEmitter } from 'node:events';\nimport {\n CosmosPayAPIError,\n CosmosPayRequestError,\n} from '@/errors/CosmosPayError';\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT,\n DEFAULT_VERSION,\n Events,\n version,\n} from '@/util/Constants';\n\n/** A `fetch`-compatible function (defaults to the global `fetch`). */\nexport type FetchLike = typeof fetch;\n\n/** Options accepted when constructing a {@link REST} instance. */\nexport interface RESTOptions {\n /**\n * Base URL of the Cosmos Pay gateway (no trailing slash), e.g.\n * `https://api.cosmospay.lat/cosmos-api`. The version segment is appended\n * automatically.\n */\n baseURL: string;\n /**\n * API key issued by the Cosmos developer platform. Sent as\n * `Authorization: Bearer <apiKey>` (and `apikey: <apiKey>`) to the gateway.\n */\n apiKey?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only needed when calling the\n * service directly (bypassing APISIX) — typically local development.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Pair with\n * `gatewaySecret` for direct service access.\n */\n consumerUsername?: string;\n /**\n * API version segment prefixed to every route. Defaults to `v1`. Set to an\n * empty string when your gateway already injects the version.\n */\n version?: string;\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n}\n\n/** Internal options for a single request. */\nexport interface RequestOptions {\n /** Query string parameters; `undefined`/`null` values are dropped. */\n query?: Record<string, string | number | boolean | undefined | null>;\n /** JSON body to send. */\n body?: unknown;\n /** Per-request header overrides. */\n headers?: Record<string, string>;\n /** Per-request AbortSignal. */\n signal?: AbortSignal;\n}\n\nconst RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * The HTTP layer. Owns the base URL, authentication and retry/timeout policy,\n * and exposes thin verb helpers (`get`/`post`/`patch`/`delete`). Managers call\n * these — they never touch `fetch` directly.\n */\nexport class REST extends EventEmitter {\n public baseURL: string;\n public readonly version: string;\n private readonly timeout: number;\n private readonly retries: number;\n private readonly fetchFn: FetchLike;\n private readonly extraHeaders: Record<string, string>;\n private apiKey?: string;\n private gatewaySecret?: string;\n private consumerUsername?: string;\n\n constructor(options: RESTOptions) {\n super();\n if (!options.baseURL) {\n throw new TypeError('REST requires a `baseURL`.');\n }\n this.baseURL = options.baseURL.replace(/\\/+$/, '');\n this.version = options.version ?? DEFAULT_VERSION;\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT;\n this.retries = options.retries ?? DEFAULT_RETRIES;\n this.extraHeaders = options.headers ?? {};\n this.apiKey = options.apiKey;\n this.gatewaySecret = options.gatewaySecret;\n this.consumerUsername = options.consumerUsername;\n\n const fetchFn = options.fetch ?? globalThis.fetch;\n if (typeof fetchFn !== 'function') {\n throw new TypeError(\n 'No global `fetch` found. Use Node.js >= 18 or pass a `fetch` implementation in the client options.',\n );\n }\n this.fetchFn = fetchFn.bind(globalThis);\n }\n\n /** Replace the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.apiKey = apiKey;\n return this;\n }\n\n /** Set direct-access gateway credentials (local/dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.gatewaySecret = secret;\n this.consumerUsername = consumerUsername;\n return this;\n }\n\n public get<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n\n public post<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('POST', path, options);\n }\n\n public patch<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('PATCH', path, options);\n }\n\n public delete<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n /** Build the absolute URL for a route, applying the version prefix + query. */\n public buildURL(path: string, query?: RequestOptions['query']): string {\n const clean = path.startsWith('/') ? path : `/${path}`;\n const prefix = this.version ? `/${this.version}` : '';\n const url = new URL(`${this.baseURL}${prefix}${clean}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n }\n\n private buildHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': `@cosmosapp/pay_sdk/${version}`,\n ...this.extraHeaders,\n };\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n headers['apikey'] = this.apiKey;\n }\n if (this.gatewaySecret) headers['X-Gateway-Secret'] = this.gatewaySecret;\n if (this.consumerUsername) {\n headers['X-Consumer-Username'] = this.consumerUsername;\n }\n return { ...headers, ...extra };\n }\n\n /** Core request with retry, timeout and structured error handling. */\n public async request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n const url = this.buildURL(path, options.query);\n const headers = this.buildHeaders(options.headers);\n\n let serializedBody: string | undefined;\n if (options.body !== undefined) {\n serializedBody = JSON.stringify(options.body);\n headers['Content-Type'] = 'application/json';\n }\n\n let attempt = 0;\n let lastError: unknown;\n\n while (attempt <= this.retries) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n const signal = options.signal\n ? anySignal([options.signal, controller.signal])\n : controller.signal;\n\n this.emit(Events.Request, { method, url, attempt });\n\n try {\n const response = await this.fetchFn(url, {\n method,\n headers,\n body: serializedBody,\n signal,\n });\n clearTimeout(timer);\n\n this.emit(Events.Response, {\n method,\n url,\n status: response.status,\n attempt,\n });\n\n if (response.status === 429) {\n this.emit(Events.RateLimited, { method, url, attempt });\n }\n\n if (!response.ok) {\n const body = await safeParse(response);\n if (RETRYABLE_STATUS.has(response.status) && attempt < this.retries) {\n await this.backoff(response, attempt);\n attempt++;\n continue;\n }\n throw new CosmosPayAPIError({ status: response.status, method, url, body });\n }\n\n return (await safeParse(response)) as T;\n } catch (error) {\n clearTimeout(timer);\n if (error instanceof CosmosPayAPIError) throw error;\n\n // Network/abort/timeout → retry, then surface as a request error.\n lastError = error;\n if (attempt < this.retries) {\n await sleep(backoffDelay(attempt));\n attempt++;\n continue;\n }\n throw new CosmosPayRequestError({ method, url, cause: error });\n }\n }\n\n throw new CosmosPayRequestError({ method, url, cause: lastError });\n }\n\n private async backoff(response: Response, attempt: number): Promise<void> {\n const retryAfter = response.headers.get('retry-after');\n const ms = retryAfter\n ? Number(retryAfter) * 1000\n : backoffDelay(attempt);\n await sleep(Number.isFinite(ms) ? ms : backoffDelay(attempt));\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction backoffDelay(attempt: number): number {\n return Math.min(1000 * 2 ** attempt, 8000);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function safeParse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.includes('application/json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\n/** Combine multiple AbortSignals into one (first to abort wins). */\nfunction anySignal(signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n const onAbort = (signal: AbortSignal) => () => controller.abort(signal.reason);\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n break;\n }\n signal.addEventListener('abort', onAbort(signal), { once: true });\n }\n return controller.signal;\n}\n","import { DEFAULT_BASE_URL, DEFAULT_VERSION } from '@/util/Constants';\n\n/**\n * Internal (\"shared\") configuration that Cosmos Pay maintains on the user's\n * behalf. These are the gateway / infrastructure details an integrator should\n * **not** have to know about — they're pre-filled here so that, in practice, the\n * only credential a user provides is their `apiKey`.\n *\n * Every value is overridable (per-client via {@link ClientOptions}, or globally\n * via {@link Client.shared}) for self-hosting, staging or local development.\n */\nexport interface SharedConfig {\n /** Base URL of the Cosmos Pay gateway. */\n baseURL: string;\n /** API version segment prefixed to every route (`/v1/...`). */\n version: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only used when talking to the\n * service directly, bypassing the gateway (local development). Internal.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Paired with\n * `gatewaySecret` for direct service access. Internal.\n */\n consumerUsername?: string;\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.process` / handlers) when no secret is passed explicitly.\n */\n webhookSecret?: string;\n}\n\n/**\n * The mutable, process-wide defaults. Cosmos Pay ships sane values here; you can\n * tweak them once at startup (e.g. `Client.shared.baseURL = '...'`) and every\n * client created afterwards inherits them.\n */\nexport const shared: SharedConfig = {\n baseURL: DEFAULT_BASE_URL,\n version: DEFAULT_VERSION,\n};\n\n/** Merge a partial override on top of the current shared defaults. */\nexport function resolveShared(overrides: Partial<SharedConfig> = {}): SharedConfig {\n const defined: Partial<SharedConfig> = {};\n for (const key of Object.keys(overrides) as (keyof SharedConfig)[]) {\n const value = overrides[key];\n if (value !== undefined) {\n Object.assign(defined, { [key]: value });\n }\n }\n return { ...shared, ...defined };\n}\n","import { EventEmitter } from 'node:events';\nimport { AnalyticsManager } from '@/managers/AnalyticsManager';\nimport { CustomerManager } from '@/managers/CustomerManager';\nimport { HealthManager } from '@/managers/HealthManager';\nimport { PaymentIntentManager } from '@/managers/PaymentIntentManager';\nimport { ProductManager } from '@/managers/ProductManager';\nimport { WebhookManager } from '@/managers/WebhookManager';\nimport { REST, type FetchLike } from '@/rest/REST';\nimport { version } from '@/util/Constants';\nimport { resolveShared, shared, type SharedConfig } from '@/util/shared';\n\n/**\n * Options accepted by the {@link Client} constructor.\n *\n * In practice the only value you provide is `apiKey` — everything else (the\n * gateway URL, version and other infrastructure details) is pre-filled from the\n * {@link Client.shared} defaults that Cosmos Pay maintains for you.\n */\nexport interface ClientOptions {\n /**\n * Your Cosmos Pay API key. Sent to the gateway as `Authorization: Bearer\n * <apiKey>`. The key type determines the network (`dv_` → testnet, `prod_` →\n * mainnet). This is the only credential a typical integration needs.\n */\n apiKey: string;\n\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.on(...)` + handlers) when you don't pass one explicitly.\n */\n webhookSecret?: string;\n\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n\n // ── Advanced / internal overrides (you normally never set these) ────────────\n /**\n * Override the gateway base URL. Defaults to {@link Client.shared}`.baseURL`.\n * Only needed for self-hosting or a staging gateway.\n * @internal\n */\n baseURL?: string;\n /**\n * Override the API version segment. Defaults to `v1`.\n * @internal\n */\n version?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`) for direct, gateway-bypassing\n * access (local development). Maintained internally.\n * @internal\n */\n gatewaySecret?: string;\n /**\n * Consumer username (`X-Consumer-Username`) for direct access. Internal.\n * @internal\n */\n consumerUsername?: string;\n}\n\n/** Payloads emitted by the {@link Client} for observability. */\nexport interface ClientEvents {\n request: [{ method: string; url: string; attempt: number }];\n response: [{ method: string; url: string; status: number; attempt: number }];\n rateLimited: [{ method: string; url: string; attempt: number }];\n debug: [message: string];\n}\n\nexport interface Client {\n on<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n once<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n off<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n emit<E extends keyof ClientEvents>(\n event: E,\n ...args: ClientEvents[E]\n ): boolean;\n}\n\n/**\n * The main entry point of the SDK — a single, atomic client that exposes every\n * resource through its own manager — an atomic, single-client design.\n *\n * @example\n * import { Client } from '@cosmosapp/pay_sdk';\n *\n * // The user only provides their API key — the gateway is handled for them.\n * const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });\n *\n * const intent = await client.paymentIntents.createPay({ destination: 'G...', amount: '10' });\n * console.log(intent.uri);\n */\nexport class Client extends EventEmitter {\n /** Library version. */\n public static readonly version = version;\n\n /**\n * Process-wide shared defaults maintained by Cosmos Pay (gateway URL, version,\n * internal secrets). Mutate once at startup to change them for every client\n * (e.g. self-hosting): `Client.shared.baseURL = 'https://gateway.your-domain.com'`.\n */\n public static readonly shared: SharedConfig = shared;\n\n /** Resolved shared configuration for this client instance. */\n public readonly shared: SharedConfig;\n\n /** Default webhook signing secret for the webhook listener (if configured). */\n public webhookSecret: string | undefined;\n\n /** The underlying HTTP layer. Shared by every manager. */\n public readonly rest: REST;\n\n /** Stellar payment intents — create/list/fetch/update/delete/validate. */\n public readonly paymentIntents: PaymentIntentManager;\n /** Webhook endpoints, delivery audit trail, and the event listener. */\n public readonly webhooks: WebhookManager;\n /** Products / prices. */\n public readonly products: ProductManager;\n /** Customers. */\n public readonly customers: CustomerManager;\n /** Read-only analytics (summary, balances, logs). */\n public readonly analytics: AnalyticsManager;\n /** Service health probes (public). */\n public readonly health: HealthManager;\n\n constructor(options: ClientOptions) {\n super();\n if (!options || !options.apiKey) {\n throw new TypeError('Client requires an `apiKey` option.');\n }\n\n // Fill the infrastructure details from the shared defaults; the user only\n // had to bring their apiKey.\n this.shared = resolveShared({\n baseURL: options.baseURL,\n version: options.version,\n gatewaySecret: options.gatewaySecret,\n consumerUsername: options.consumerUsername,\n webhookSecret: options.webhookSecret,\n });\n this.webhookSecret = this.shared.webhookSecret;\n\n this.rest = new REST({\n baseURL: this.shared.baseURL,\n apiKey: options.apiKey,\n gatewaySecret: this.shared.gatewaySecret,\n consumerUsername: this.shared.consumerUsername,\n version: this.shared.version,\n timeout: options.timeout,\n retries: options.retries,\n headers: options.headers,\n fetch: options.fetch,\n });\n\n // Re-emit REST telemetry through the client so consumers can subscribe to\n // `client.on('request' | 'response' | 'rateLimited' | 'debug', ...)`.\n this.rest.on('request', (p) => this.emit('request', p));\n this.rest.on('response', (p) => this.emit('response', p));\n this.rest.on('rateLimited', (p) => this.emit('rateLimited', p));\n\n this.paymentIntents = new PaymentIntentManager(this);\n this.webhooks = new WebhookManager(this);\n this.products = new ProductManager(this);\n this.customers = new CustomerManager(this);\n this.analytics = new AnalyticsManager(this);\n this.health = new HealthManager(this);\n }\n\n /** Update the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.rest.setApiKey(apiKey);\n return this;\n }\n\n /** Set the default webhook signing secret for the webhook listener. */\n public setWebhookSecret(secret: string): this {\n this.webhookSecret = secret;\n return this;\n }\n\n /** Set direct-access gateway credentials (internal / local dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.rest.setGatewayCredentials(secret, consumerUsername);\n return this;\n }\n}\n","/**\n * Typed identifiers for the wallets the web client knows about, so you can write\n * `Wallets.FREIGHTER` instead of remembering the `'freighter'` magic string —\n * while any custom adapter id still works.\n */\n\n/** Built-in wallet ids (matches each adapter's `id`). */\nexport const Wallets = {\n FREIGHTER: 'freighter',\n XBULL: 'xbull',\n RABET: 'rabet',\n LOBSTR: 'lobstr',\n ALBEDO: 'albedo',\n} as const;\n\n/** A known wallet id, or any custom adapter id (autocomplete for the built-ins). */\nexport type WalletId = (typeof Wallets)[keyof typeof Wallets] | (string & {});\n"]}
1
+ {"version":3,"sources":["../src/managers/AnalyticsManager.ts","../src/structures/Base.ts","../src/structures/Customer.ts","../src/managers/BaseManager.ts","../src/managers/CustomerManager.ts","../src/managers/HealthManager.ts","../src/types/index.ts","../src/structures/PaymentIntent.ts","../src/common/addresses.ts","../src/common/assets.ts","../src/common/intent-input.ts","../src/managers/PaymentIntentManager.ts","../src/structures/Product.ts","../src/managers/ProductManager.ts","../src/structures/Swap.ts","../src/managers/SwapManager.ts","../src/structures/WebhookDelivery.ts","../src/structures/WebhookEndpoint.ts","../src/util/Constants.ts","../src/util/Webhooks.ts","../src/managers/WebhookManager.ts","../src/errors/CosmosPayError.ts","../src/rest/REST.ts","../src/util/shared.ts","../src/client/Client.ts","../src/common/wallets.ts"],"names":["EventEmitter","createHmac","timingSafeEqual"],"mappings":";;;;;;;;AAaO,IAAM,mBAAN,MAAuB;AAAA,EAG5B,YAAY,MAAA,EAAgB;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,IAAY,IAAA,GAAa;AACvB,IAAA,OAAO,KAAK,MAAA,CAAO,IAAA;AAAA,EACrB;AAAA;AAAA,EAGO,OAAA,GAAyC;AAC9C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA0B,UAAU,CAAA;AAAA,EACvD;AAAA;AAAA,EAGO,QAAA,GAA2C;AAChD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA2B,WAA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AAA;AAE9D,IAAA,IAAA,CAAK,cAAA,GAAiB,IAAI,oBAAA,CAAqB,IAAI,CAAA;AACnD,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,cAAA,CAAe,IAAI,CAAA;AACvC,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,cAAA,CAAe,IAAI,CAAA;AACvC,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAI,WAAA,CAAY,IAAI,CAAA;AACjC,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,eAAA,CAAgB,IAAI,CAAA;AACzC,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,gBAAA,CAAiB,IAAI,CAAA;AAC1C,IAAA,IAAA,CAAK,MAAA,GAAS,IAAI,aAAA,CAAc,IAAI,CAAA;AAAA,EACtC;AAAA;AAAA,EAGO,UAAU,MAAA,EAAsB;AACrC,IAAA,IAAA,CAAK,IAAA,CAAK,UAAU,MAAM,CAAA;AAC1B,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA,EAGO,iBAAiB,MAAA,EAAsB;AAC5C,IAAA,IAAA,CAAK,aAAA,GAAgB,MAAA;AACrB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA,EAGO,qBAAA,CAAsB,QAAgB,gBAAA,EAAgC;AAC3E,IAAA,IAAA,CAAK,IAAA,CAAK,qBAAA,CAAsB,MAAA,EAAQ,gBAAgB,CAAA;AACxD,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;;ACpMO,IAAM,OAAA,GAAU;AAAA,EACrB,SAAA,EAAW,WAAA;AAAA,EACX,KAAA,EAAO,OAAA;AAAA,EACP,KAAA,EAAO,OAAA;AAAA,EACP,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ;AACV","file":"index.cjs","sourcesContent":["import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n AnalyticsBalancesData,\n AnalyticsSummaryData,\n ApiLogsData,\n WebhookLogsData,\n} from '@/types/index';\n\n/**\n * Read-only analytics derived from the consumer's intents and deliveries —\n * `client.analytics`. Powers dashboard-style Overview / Balances / Logs views.\n */\nexport class AnalyticsManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Overview metrics: totals, settled volume, webhook health, 30-day series. */\n public summary(): Promise<AnalyticsSummaryData> {\n return this.rest.get<AnalyticsSummaryData>('/summary');\n }\n\n /** Settled (and pending) amount per asset. */\n public balances(): Promise<AnalyticsBalancesData> {\n return this.rest.get<AnalyticsBalancesData>('/balances');\n }\n\n /** Recent API requests reaching the service (with details). */\n public apiLogs(): Promise<ApiLogsData> {\n return this.rest.get<ApiLogsData>('/logs');\n }\n\n /** Recent webhook deliveries across all endpoints (with details). */\n public webhookLogs(): Promise<WebhookLogsData> {\n return this.rest.get<WebhookLogsData>('/logs/webhooks');\n }\n}\n","import type { Client } from '@/client/Client';\n\n/**\n * Root of every API structure. Holds a back-reference to the {@link Client} so\n * instances can perform their own actions (e.g. `paymentIntent.delete()`), and\n * provides the `_patch`/`toJSON` plumbing shared by all structures.\n */\nexport abstract class Base<Data extends { id: string }> {\n /** The client that instantiated this structure. */\n public readonly client: Client;\n /** Unique identifier of the resource. */\n public id!: string;\n\n protected constructor(client: Client, data: Data) {\n this.client = client;\n this._patch(data);\n }\n\n /** Merge raw API data onto this instance. Subclasses override and call super. */\n protected _patch(data: Data): this {\n this.id = data.id;\n return this;\n }\n\n /** Return the raw API representation of this structure. */\n public abstract toJSON(): Data;\n\n /** Allow `String(structure)` / template literals to resolve to the id. */\n public valueOf(): string {\n return this.id;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { CustomerData, UpdateCustomerOptions } from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A customer record, optionally enriched with on-chain payment stats. */\nexport class Customer extends Base<CustomerData> {\n public consumerId!: string;\n public name!: string;\n public alias!: string | null;\n public note!: string | null;\n public email!: string | null;\n /** Optional Stellar account associated with the customer. */\n public account!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n /** Number of payment intents from this customer's account (list view only). */\n public payments: number | null = null;\n /** Number of succeeded payments (list view only). */\n public succeeded: number | null = null;\n /** Total settled amount as a decimal string (list view only). */\n public total: string | null = null;\n\n constructor(client: Client, data: CustomerData) {\n super(client, data);\n }\n\n protected override _patch(data: CustomerData): this {\n super._patch(data);\n this.consumerId = data.consumerId;\n this.name = data.name;\n this.alias = data.alias;\n this.note = data.note;\n this.email = data.email;\n this.account = data.account;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n if (data.payments !== undefined) this.payments = data.payments;\n if (data.succeeded !== undefined) this.succeeded = data.succeeded;\n if (data.total !== undefined) this.total = data.total;\n return this;\n }\n\n /** Re-fetch this customer. */\n public fetch(): Promise<Customer> {\n return this.client.customers.fetch(this.id);\n }\n\n /** Update this customer. Mutates and returns this. */\n public async edit(options: UpdateCustomerOptions): Promise<this> {\n const updated = await this.client.customers.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Delete this customer. */\n public delete() {\n return this.client.customers.delete(this.id);\n }\n\n public toJSON(): CustomerData {\n return {\n id: this.id,\n consumerId: this.consumerId,\n name: this.name,\n alias: this.alias,\n note: this.note,\n email: this.email,\n account: this.account,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n ...(this.payments !== null ? { payments: this.payments } : {}),\n ...(this.succeeded !== null ? { succeeded: this.succeeded } : {}),\n ...(this.total !== null ? { total: this.total } : {}),\n };\n }\n}\n","import { EventEmitter } from 'node:events';\nimport type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\n\n/**\n * Base class for all resource managers. Each manager owns a slice of the API\n * (payment intents, webhooks, ...) and a lightweight in-memory cache of the\n * structures it has materialized — an atomic, per-resource manager pattern.\n *\n * Extends EventEmitter so managers that surface real-time events (e.g. the\n * webhook listener) can `emit`/`on` without extra plumbing.\n */\nexport abstract class BaseManager<\n Structure extends { id: string },\n> extends EventEmitter {\n public readonly client: Client;\n /** Cache of structures keyed by id, populated on fetch/create. */\n public readonly cache: Map<string, Structure> = new Map();\n\n constructor(client: Client) {\n super();\n this.client = client;\n }\n\n /** Shortcut to the shared REST instance. */\n protected get rest(): REST {\n return this.client.rest;\n }\n\n /** Store a structure in the cache and return it. */\n protected _add(structure: Structure): Structure {\n this.cache.set(structure.id, structure);\n return structure;\n }\n\n /** Resolve an id from either a raw id or a structure instance. */\n public resolveId(idOrStructure: string | { id: string }): string {\n return typeof idOrStructure === 'string' ? idOrStructure : idOrStructure.id;\n }\n}\n","import { Customer } from '@/structures/Customer';\nimport type {\n CreateCustomerOptions,\n CustomerData,\n CustomerListData,\n UpdateCustomerOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype CustomerDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages customers — `client.customers`.\n *\n * @example\n * const customer = await client.customers.create({\n * name: 'Acme Inc.', email: 'billing@acme.com',\n * });\n */\nexport class CustomerManager extends BaseManager<Customer> {\n private readonly route = '/customers';\n\n /** Create a customer. */\n public async create(options: CreateCustomerOptions): Promise<Customer> {\n const data = await this.rest.post<CustomerData>(this.route, { body: options });\n return this._add(new Customer(this.client, data));\n }\n\n /** List the consumer's customers (with payment stats). */\n public async list(): Promise<Customer[]> {\n const data = await this.rest.get<CustomerListData>(this.route);\n return data.data.map((d) => this._add(new Customer(this.client, d)));\n }\n\n /** Get a customer by id. */\n public async fetch(id: string): Promise<Customer> {\n const data = await this.rest.get<CustomerData>(`${this.route}/${id}`);\n return this._add(new Customer(this.client, data));\n }\n\n /** Update a customer. */\n public async update(\n id: string,\n options: UpdateCustomerOptions,\n ): Promise<Customer> {\n const data = await this.rest.patch<CustomerData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Customer(this.client, data));\n }\n\n /** Delete a customer. */\n public async delete(id: string): Promise<CustomerDeletedData> {\n const result = await this.rest.delete<CustomerDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type { HealthCheckData } from '@/types/index';\n\n/**\n * Service health probes — `client.health`. These routes are public (they don't\n * require an authenticated consumer).\n */\nexport class HealthManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Liveness probe — resolves when the service is up. */\n public async liveness(): Promise<boolean> {\n await this.rest.get<unknown>('/health/liveness');\n return true;\n }\n\n /** Readiness probe (checks the database). Returns the health report. */\n public readiness(): Promise<HealthCheckData> {\n return this.rest.get<HealthCheckData>('/health/readiness');\n }\n}\n","/**\n * Type definitions for the Cosmos Pay Payments API.\n *\n * These mirror the server's OpenAPI schema (Stellar SEP-7 payment intents,\n * webhooks, products, customers and analytics). Every type is exported so\n * TypeScript consumers get full intellisense; JavaScript consumers can ignore\n * them entirely.\n */\n\nimport type { AssetRef } from '@/common/assets';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Enums (provided both as runtime objects and as string-literal unions)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Lifecycle state of a payment intent. */\nexport const PaymentIntentStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Cancelled: 'CANCELLED',\n Expired: 'EXPIRED',\n} as const;\nexport type PaymentIntentStatus =\n (typeof PaymentIntentStatus)[keyof typeof PaymentIntentStatus];\n\n/** SEP-7 operation a payment intent represents. */\nexport const PaymentIntentKind = {\n /** Source account is known → unsigned XDR + `web+stellar:tx` URI. */\n Tx: 'TX',\n /** No source → `web+stellar:pay` URI only (wallet picks the source). */\n Pay: 'PAY',\n} as const;\nexport type PaymentIntentKind =\n (typeof PaymentIntentKind)[keyof typeof PaymentIntentKind];\n\n/** Domain events an integrator can subscribe a webhook to. */\nexport const WebhookEventType = {\n PaymentIntentCreated: 'PAYMENT_INTENT_CREATED',\n PaymentIntentUpdated: 'PAYMENT_INTENT_UPDATED',\n PaymentIntentSucceeded: 'PAYMENT_INTENT_SUCCEEDED',\n PaymentIntentFailed: 'PAYMENT_INTENT_FAILED',\n PaymentIntentCancelled: 'PAYMENT_INTENT_CANCELLED',\n PaymentIntentDeleted: 'PAYMENT_INTENT_DELETED',\n} as const;\nexport type WebhookEventType =\n (typeof WebhookEventType)[keyof typeof WebhookEventType];\n\n/** Delivery state of a single webhook attempt. */\nexport const WebhookDeliveryStatus = {\n Pending: 'PENDING',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n} as const;\nexport type WebhookDeliveryStatus =\n (typeof WebhookDeliveryStatus)[keyof typeof WebhookDeliveryStatus];\n\n/** Product billing kind. */\nexport const ProductKind = {\n Recurring: 'recurring',\n OneTime: 'one_time',\n Link: 'link',\n} as const;\nexport type ProductKind = (typeof ProductKind)[keyof typeof ProductKind];\n\n/** Lifecycle state of a swap. */\nexport const SwapStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Expired: 'EXPIRED',\n} as const;\nexport type SwapStatus = (typeof SwapStatus)[keyof typeof SwapStatus];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Payment intents\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/payment-intents/tx`. */\nexport interface CreateTxPaymentIntentOptions {\n /** Payer's Stellar account — the transaction source. A registered address-book name also works. */\n source: string;\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount as a decimal string (max 7 decimals). */\n amount: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code. Omit (or `XLM`/`native`) for native lumens. */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback` where the wallet POSTs the signed XDR, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `POST /v1/payment-intents/pay`. */\nexport interface CreatePayPaymentIntentOptions {\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount the destination should receive. Omit to let the user enter it (e.g. donations). */\n amount?: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code the destination receives. Omit for native lumens (XLM). */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback`, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `PATCH /v1/payment-intents/:id`. */\nexport interface UpdatePaymentIntentOptions {\n status?: PaymentIntentStatus;\n /** Stellar transaction hash once the signed tx is submitted. */\n txHash?: string;\n /** Merchant reference. */\n reference?: string;\n}\n\n/** Query for `GET /v1/payment-intents`. */\nexport interface ListPaymentIntentsOptions {\n status?: PaymentIntentStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Raw payment intent payload returned by the API. */\nexport interface PaymentIntentData {\n id: string;\n kind: PaymentIntentKind;\n status: PaymentIntentStatus;\n network: string;\n source: string | null;\n destination: string;\n amount: string | null;\n asset: string;\n assetIssuer: string | null;\n memo: string;\n msg: string | null;\n callback: string | null;\n xdr: string | null;\n uri: string;\n qr: string;\n txHash: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of payment intents. */\nexport interface PaymentIntentListData {\n data: PaymentIntentData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Body for `POST /v1/payment-intents/:id/validate`. */\nexport interface ValidatePaymentIntentOptions {\n /** Hash of the submitted Stellar transaction to validate against this intent. */\n txHash: string;\n}\n\n/** Raw outcome of a validation attempt. */\nexport interface ValidationOutcomeData {\n valid: boolean;\n status: PaymentIntentStatus;\n reason?: string | null;\n paymentIntent?: PaymentIntentData;\n}\n\n/** Raw `{ id, deleted }` response. */\nexport interface DeletedData {\n id: string;\n deleted: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Webhooks\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/webhooks`. */\nexport interface CreateWebhookEndpointOptions {\n /** HTTPS URL that will receive POSTed event notifications. */\n url: string;\n description?: string;\n /** Event types to subscribe to. Omit/empty to receive all events. */\n eventTypes?: WebhookEventType[];\n}\n\n/** Body for `PATCH /v1/webhooks/:id`. */\nexport interface UpdateWebhookEndpointOptions {\n url?: string;\n description?: string;\n /** Pause/resume deliveries to this endpoint. */\n enabled?: boolean;\n eventTypes?: WebhookEventType[];\n}\n\n/** Raw webhook endpoint payload. */\nexport interface WebhookEndpointData {\n id: string;\n url: string;\n description: string | null;\n enabled: boolean;\n eventTypes: WebhookEventType[];\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw webhook endpoint payload including the one-time signing secret. */\nexport interface WebhookEndpointWithSecretData extends WebhookEndpointData {\n /** HMAC signing secret — shown once. Store it securely. */\n secret: string;\n}\n\n/** Raw result of a webhook ping. */\nexport interface WebhookPingData {\n ok: boolean;\n responseStatus: number | null;\n error: string | null;\n}\n\n/** Raw webhook delivery (audit) record. */\nexport interface WebhookDeliveryData {\n id: string;\n endpointId: string;\n eventType: WebhookEventType;\n eventId: string;\n payload: Record<string, unknown>;\n status: WebhookDeliveryStatus;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n lastAttemptAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of webhook deliveries. */\nexport interface WebhookDeliveryListData {\n data: WebhookDeliveryData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Query for `GET /v1/webhooks/:id/deliveries`. */\nexport interface ListWebhookDeliveriesOptions {\n status?: WebhookDeliveryStatus;\n take?: number;\n skip?: number;\n}\n\n/** Shape of the JSON body POSTed to an integrator's webhook URL. */\nexport interface WebhookEvent<T = PaymentIntentData> {\n /** Stable event id (use for idempotency). */\n id: string;\n type: WebhookEventType;\n createdAt: string;\n data: T;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Products\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/products`. */\nexport interface CreateProductOptions {\n name: string;\n description?: string;\n /** Decimal price (≤ 7 decimals). Omit for a customer-set amount. */\n amount?: string;\n /** Asset code the price is in. Omit for native lumens (XLM). */\n assetCode?: string;\n kind?: ProductKind;\n active?: boolean;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/products/:id`. */\nexport type UpdateProductOptions = Partial<CreateProductOptions>;\n\n/** Raw product payload. */\nexport interface ProductData {\n id: string;\n name: string;\n description: string | null;\n amount: string | null;\n asset: string;\n kind: ProductKind;\n active: boolean;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Customers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/customers`. */\nexport interface CreateCustomerOptions {\n name: string;\n alias?: string;\n note?: string;\n email?: string;\n /** Optional Stellar account to associate the customer with. */\n account?: string;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/customers/:id`. */\nexport type UpdateCustomerOptions = Partial<CreateCustomerOptions>;\n\n/** Raw customer payload. */\nexport interface CustomerData {\n id: string;\n consumerId: string;\n name: string;\n alias: string | null;\n note: string | null;\n email: string | null;\n account: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n /** Derived on-chain stats (present in list responses). */\n payments?: number;\n succeeded?: number;\n total?: string;\n}\n\n/** Raw `{ data, total }` list of customers. */\nexport interface CustomerListData {\n data: CustomerData[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Analytics\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface AnalyticsVolumeEntry {\n asset: string;\n amount: string;\n count: number;\n}\n\nexport interface AnalyticsSeriesPoint {\n date: string;\n count: number;\n volume: string;\n}\n\nexport interface AnalyticsRecentRow {\n id: string;\n kind: string;\n status: PaymentIntentStatus;\n amount: string | null;\n asset: string;\n destination: string;\n createdAt: string;\n}\n\n/** Raw overview metrics returned by `GET /v1/summary`. */\nexport interface AnalyticsSummaryData {\n totals: {\n all: number;\n succeeded: number;\n pending: number;\n submitted: number;\n failed: number;\n cancelled: number;\n expired: number;\n successRate: number;\n };\n volume: AnalyticsVolumeEntry[];\n webhooks: {\n endpoints: number;\n deliveries: number;\n failedDeliveries: number;\n };\n customers: number;\n series: AnalyticsSeriesPoint[];\n recent: AnalyticsRecentRow[];\n}\n\nexport interface AnalyticsBalanceEntry {\n asset: string;\n amount: string;\n pending: string;\n count: number;\n}\n\n/** Raw balances returned by `GET /v1/balances`. */\nexport interface AnalyticsBalancesData {\n data: AnalyticsBalanceEntry[];\n total: number;\n}\n\nexport interface ApiLogRow {\n id: string;\n method: string;\n path: string;\n statusCode: number;\n durationMs: number;\n ip: string | null;\n userAgent: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw API request log returned by `GET /v1/logs`. */\nexport interface ApiLogsData {\n data: ApiLogRow[];\n total: number;\n}\n\nexport interface WebhookLogRow {\n id: string;\n endpointId: string;\n url: string | null;\n eventType: WebhookEventType;\n eventId: string;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw webhook delivery log returned by `GET /v1/logs/webhooks`. */\nexport interface WebhookLogsData {\n data: WebhookLogRow[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Health\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface HealthCheckData {\n status: string;\n info?: Record<string, { status: string } & Record<string, unknown>> | null;\n error?: Record<string, { status: string } & Record<string, unknown>> | null;\n details?: Record<string, { status: string } & Record<string, unknown>>;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Swaps\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/swaps/quote` (pricing only; no fee parameter — the fee is enforced server-side per organization). */\nexport interface QuoteSwapOptions {\n /** Amount to send, as a decimal string (max 7 decimals). */\n amount: string;\n /** Source asset code. Omit (or `XLM`/`native`) for native lumens. */\n sourceAssetCode?: string;\n /** Issuer account for a non-native source asset. */\n sourceAssetIssuer?: string;\n /** Destination asset code the swap should deliver. */\n destAssetCode: string;\n /** Issuer account for a non-native destination asset. */\n destAssetIssuer?: string;\n /** Allowed slippage in basis points. */\n slippageBps?: number;\n}\n\n/** Body for `POST /v1/swaps`. */\nexport interface CreateSwapOptions extends QuoteSwapOptions {\n /** Source account performing the swap. A registered address-book name also works. */\n source: string;\n /** Destination account that receives the swapped asset. Defaults to the source. */\n destination?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. */\n memo?: string;\n}\n\n/** Body for `POST /v1/swaps/:id/submit`. */\nexport interface SubmitSwapOptions {\n /** Signed transaction envelope (base64 XDR) to relay to the network. */\n signedXdr: string;\n}\n\n/** Query for `GET /v1/swaps`. */\nexport interface ListSwapsOptions {\n status?: SwapStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Raw swap payload returned by the API. */\nexport interface SwapData {\n id: string;\n status: SwapStatus;\n network: string;\n source: string;\n destination: string;\n sendAsset: string;\n sendAssetIssuer: string | null;\n sendAmount: string;\n feeAmount: string;\n feeBps: number;\n swapAmount: string;\n destAsset: string;\n destAssetIssuer: string | null;\n destEstimated: string;\n destMin: string;\n slippageBps: number;\n path: { code: string; issuer: string | null }[];\n memo: string | null;\n xdr: string;\n uri: string;\n txHash: string;\n qr: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of swaps. */\nexport interface SwapListData {\n data: SwapData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Raw pricing quote returned by `POST /v1/swaps/quote`. */\nexport interface SwapQuoteData {\n network: string;\n source: { asset: string; issuer: string | null; amount: string };\n fee: { asset: string; issuer: string | null; amount: string; bps: number; wallet: string | null };\n swap: { asset: string; issuer: string | null; amount: string };\n destination: {\n asset: string;\n issuer: string | null;\n estimated: string;\n minimum: string;\n slippageBps: number;\n };\n path: { code: string; issuer: string | null }[];\n}\n\n/** Raw outcome of relaying a signed swap transaction. */\nexport interface SwapSubmitOutcomeData {\n submitted: boolean;\n status: SwapStatus;\n txHash?: string;\n reason?: string;\n resultCodes?: string[];\n swap: SwapData;\n}\n","import type { Client } from '@/client/Client';\nimport {\n PaymentIntentKind,\n PaymentIntentStatus,\n type PaymentIntentData,\n type UpdatePaymentIntentOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A Stellar SEP-7 payment intent.\n *\n * Wraps the raw API payload with typed accessors and atomic action methods so\n * you can operate on it directly: `await intent.validate(txHash)`,\n * `await intent.cancel()`, `await intent.delete()`.\n */\nexport class PaymentIntent extends Base<PaymentIntentData> {\n public kind!: PaymentIntentKind;\n public status!: PaymentIntentStatus;\n public network!: string;\n /** Payer account (null for PAY intents). */\n public source!: string | null;\n public destination!: string;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public assetIssuer!: string | null;\n /** Mandatory MEMO_ID. */\n public memo!: string;\n public msg!: string | null;\n public callback!: string | null;\n /** Unsigned transaction envelope (base64 XDR); null for PAY intents. */\n public xdr!: string | null;\n /** SEP-7 deep link (`tx` or `pay`). */\n public uri!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n public txHash!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: PaymentIntentData) {\n super(client, data);\n }\n\n protected override _patch(data: PaymentIntentData): this {\n super._patch(data);\n this.kind = data.kind;\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.destination = data.destination;\n this.amount = data.amount;\n this.asset = data.asset;\n this.assetIssuer = data.assetIssuer;\n this.memo = data.memo;\n this.msg = data.msg;\n this.callback = data.callback;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.qr = data.qr;\n this.txHash = data.txHash;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether this is a SEP-7 `tx` intent (known source, has XDR). */\n public get isTx(): boolean {\n return this.kind === PaymentIntentKind.Tx;\n }\n\n /** Whether this is a SEP-7 `pay` intent (no source). */\n public get isPay(): boolean {\n return this.kind === PaymentIntentKind.Pay;\n }\n\n /** Whether the payment has settled on-chain. */\n public get isSucceeded(): boolean {\n return this.status === PaymentIntentStatus.Succeeded;\n }\n\n /** Whether the intent is still awaiting payment. */\n public get isPending(): boolean {\n return this.status === PaymentIntentStatus.Pending;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this intent from the API, returning a fresh instance. */\n public fetch(): Promise<PaymentIntent> {\n return this.client.paymentIntents.fetch(this.id);\n }\n\n /** Update this intent (status / txHash / reference). Mutates and returns it. */\n public async edit(options: UpdatePaymentIntentOptions): Promise<this> {\n const updated = await this.client.paymentIntents.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /**\n * Validate a submitted transaction against this intent. On a match the status\n * is finalized server-side and the webhook fires.\n */\n public validate(txHash: string) {\n return this.client.paymentIntents.validate(this.id, { txHash });\n }\n\n /** Mark this intent as cancelled. */\n public cancel(): Promise<this> {\n return this.edit({ status: PaymentIntentStatus.Cancelled });\n }\n\n /** Delete this intent. */\n public delete() {\n return this.client.paymentIntents.delete(this.id);\n }\n\n public toJSON(): PaymentIntentData {\n return {\n id: this.id,\n kind: this.kind,\n status: this.status,\n network: this.network,\n source: this.source,\n destination: this.destination,\n amount: this.amount,\n asset: this.asset,\n assetIssuer: this.assetIssuer,\n memo: this.memo,\n msg: this.msg,\n callback: this.callback,\n xdr: this.xdr,\n uri: this.uri,\n qr: this.qr,\n txHash: this.txHash,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/**\n * Stellar address helpers + a tiny named-address book.\n *\n * So integrators don't have to sprinkle raw `G...` strings everywhere (and risk\n * typos), they can name the accounts they care about once and reference them by\n * name. A plain address string always keeps working — `resolveAddress` only\n * substitutes registered names and otherwise passes the value straight through.\n */\n\n// Stellar strkeys are base32 (RFC 4648 alphabet, no padding). These checks are\n// length/prefix sanity checks, not full checksum validation.\nconst G_ADDRESS = /^G[A-Z2-7]{55}$/; // ed25519 public key (account)\nconst M_ADDRESS = /^M[A-Z2-7]{68}$/; // muxed account\nconst C_ADDRESS = /^C[A-Z2-7]{55}$/; // contract id\n\n/** Whether a value looks like a Stellar account address (`G…`). */\nexport function isStellarAddress(value: unknown): value is string {\n return typeof value === 'string' && G_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a muxed account address (`M…`). */\nexport function isMuxedAddress(value: unknown): value is string {\n return typeof value === 'string' && M_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a Soroban contract id (`C…`). */\nexport function isContractAddress(value: unknown): value is string {\n return typeof value === 'string' && C_ADDRESS.test(value);\n}\n\n/** Whether a value is any kind of Stellar address (account, muxed or contract). */\nexport function isAddress(value: unknown): value is string {\n return isStellarAddress(value) || isMuxedAddress(value) || isContractAddress(value);\n}\n\n/** Throw unless `value` is a valid Stellar account/muxed/contract address. */\nexport function assertAddress(value: unknown, label = 'address'): string {\n if (!isAddress(value)) {\n throw new TypeError(`Invalid Stellar ${label}: ${String(value)}`);\n }\n return value;\n}\n\n/**\n * A registry of named Stellar addresses. Register the accounts you use a lot —\n * your merchant payout account, a treasury, frequent counterparties — and refer\n * to them by name anywhere an address is accepted.\n *\n * @example\n * addresses.define('merchant', 'GC...');\n * await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });\n */\nexport class AddressBook {\n private readonly entries = new Map<string, string>();\n\n constructor(initial: Record<string, string> = {}) {\n for (const [name, address] of Object.entries(initial)) {\n this.define(name, address);\n }\n }\n\n /** Register (or overwrite) a named address. The address is validated. */\n public define(name: string, address: string): this {\n this.entries.set(name, assertAddress(address, `address for \"${name}\"`));\n return this;\n }\n\n /** Whether a name is registered. */\n public has(name: string): boolean {\n return this.entries.has(name);\n }\n\n /** Look up a registered address by name. */\n public get(name: string): string | undefined {\n return this.entries.get(name);\n }\n\n /** Remove a named address. */\n public delete(name: string): boolean {\n return this.entries.delete(name);\n }\n\n /** All registered names. */\n public names(): string[] {\n return [...this.entries.keys()];\n }\n\n /**\n * Resolve a reference to a concrete address: a registered name is substituted,\n * any other string is returned unchanged (so raw `G…`, muxed `M…`, federation\n * `name*domain`, etc. all keep working).\n */\n public resolve(ref: string): string {\n return this.entries.get(ref) ?? ref;\n }\n}\n\n/** Process-wide default address book. Use `addresses.define(...)` to populate it. */\nexport const addresses = new AddressBook();\n\n/** Anything accepted where an address is expected: a raw address or a name in a book. */\nexport type AddressRef = string;\n\n/**\n * Resolve an {@link AddressRef} using the given book (the shared {@link addresses}\n * by default). Lenient: unknown strings pass through unchanged.\n */\nexport function resolveAddress(ref: AddressRef, book: AddressBook = addresses): string {\n return book.resolve(ref);\n}\n","/**\n * A typed, extensible catalog of Stellar assets.\n *\n * Instead of hunting down an asset's issuer (or pasting the wrong one), use the\n * built-in catalog — `Assets.USDC`, `Assets.EURC`, `Assets.XLM` — which carries\n * the verified issuer for you. Need something else? `defineAsset(...)` makes a\n * typed asset you can reuse. And a plain code string still works everywhere.\n *\n * ⚠️ Issuers are network-specific. The {@link Assets} catalog targets **mainnet**;\n * {@link TestnetAssets} carries the testnet issuers. Bare code strings (e.g.\n * `'USDC'`) are treated as *code only* (no issuer) for backwards compatibility —\n * use the catalog object or `defineAsset` when you want the issuer filled in.\n */\n\nimport { isStellarAddress } from '@/common/addresses';\n\n/** A fully-described Stellar asset. */\nexport interface AssetDefinition {\n /** Asset code, e.g. `USDC`. Use `XLM` (or omit the issuer) for native lumens. */\n code: string;\n /** Issuer account (`G…`). `null`/omitted means the native asset (XLM). */\n issuer?: string | null;\n /** Optional Soroban contract id (`C…`) for the SAC / token contract. */\n contract?: string;\n /** Human-readable name. */\n name?: string;\n /** Network the `issuer` is valid on. */\n network?: 'public' | 'testnet';\n}\n\n/** Anything accepted where an asset is expected: a code string or a definition. */\nexport type AssetRef = string | AssetDefinition;\n\n/** Normalized asset: a code plus a concrete issuer (or `null` for native). */\nexport interface ResolvedAsset {\n /** `XLM` for the native asset, otherwise the asset code. */\n code: string;\n /** Issuer `G…`, or `null` for the native asset. */\n issuer: string | null;\n /** Optional Soroban contract id. */\n contract?: string;\n}\n\nconst NATIVE: AssetDefinition = { code: 'XLM', issuer: null, name: 'Stellar Lumens' };\n\n/**\n * Built-in **mainnet** assets with verified issuers. Extend with your own via\n * {@link defineAsset}. Issuers sourced from the official issuers (Circle for\n * USDC/EURC).\n */\nexport const Assets = {\n /** Native lumens. */\n XLM: NATIVE,\n /** USD Coin by Circle (mainnet). */\n USDC: {\n code: 'USDC',\n issuer: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN',\n name: 'USD Coin',\n network: 'public',\n },\n /** Euro Coin by Circle (mainnet). */\n EURC: {\n code: 'EURC',\n issuer: 'GDHU6WRG4IEQXM5NZ4BMPKOXHW76MZM4Y2IEMFDVXBSDP6SJY4ITNPP2',\n name: 'Euro Coin',\n network: 'public',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Built-in **testnet** assets (Circle's Test SDF Network issuers). */\nexport const TestnetAssets = {\n XLM: NATIVE,\n USDC: {\n code: 'USDC',\n issuer: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5',\n name: 'USD Coin',\n network: 'testnet',\n },\n EURC: {\n code: 'EURC',\n issuer: 'GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU25GO7VTC3NM2ZTVO',\n name: 'Euro Coin',\n network: 'testnet',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Whether a reference denotes the native asset (XLM). */\nexport function isNativeAsset(ref: AssetRef): boolean {\n if (typeof ref === 'string') {\n const code = ref.trim().toLowerCase();\n return code === '' || code === 'xlm' || code === 'native';\n }\n return !ref.issuer || isNativeAsset(ref.code);\n}\n\n/**\n * Create a reusable, typed custom asset. Validates the issuer/contract format so\n * a typo surfaces immediately rather than on-chain.\n *\n * @example\n * const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ...', name: 'Aquarius' });\n * await client.paymentIntents.createPay({ destination, amount: '5', asset: AQUA });\n */\nexport function defineAsset(def: AssetDefinition): AssetDefinition {\n if (!def.code) throw new TypeError('defineAsset requires a `code`.');\n if (def.issuer != null && !isStellarAddress(def.issuer)) {\n throw new TypeError(`defineAsset: invalid issuer for ${def.code}: ${def.issuer}`);\n }\n if (def.contract != null && !/^C[A-Z2-7]{55}$/.test(def.contract)) {\n throw new TypeError(`defineAsset: invalid contract for ${def.code}: ${def.contract}`);\n }\n return Object.freeze({ ...def });\n}\n\n/**\n * Normalize an {@link AssetRef} into `{ code, issuer, contract }`.\n *\n * - A bare string is treated as *code only* (`issuer: null`) — pass a catalog\n * object or `defineAsset(...)` result when you want the issuer included.\n * - The native asset normalizes to `{ code: 'XLM', issuer: null }`.\n */\nexport function resolveAsset(ref: AssetRef): ResolvedAsset {\n if (isNativeAsset(ref)) return { code: 'XLM', issuer: null };\n if (typeof ref === 'string') return { code: ref, issuer: null };\n return {\n code: ref.code,\n issuer: ref.issuer ?? null,\n ...(ref.contract ? { contract: ref.contract } : {}),\n };\n}\n","/**\n * Shared resolution of \"create intent\" input, used by both the server SDK and\n * the web client so the convenience layers behave identically: a typed\n * {@link AssetRef} (e.g. `Assets.USDC`) is expanded into `assetCode`/`assetIssuer`,\n * and named addresses are substituted via an {@link AddressBook}.\n */\n\nimport { addresses as defaultBook, AddressBook, resolveAddress } from '@/common/addresses';\nimport { resolveAsset, type AssetRef } from '@/common/assets';\n\n/** Fields the resolver understands (everything else passes through untouched). */\nexport interface ResolvableIntentInput {\n destination?: string;\n source?: string;\n /** Typed asset (`Assets.USDC`, `defineAsset(...)`) — fills code + issuer. */\n asset?: AssetRef;\n assetCode?: string;\n assetIssuer?: string;\n}\n\n/**\n * Expand `asset` into `assetCode`/`assetIssuer` and resolve named\n * `destination`/`source` addresses. Existing `assetCode`/`assetIssuer` win over a\n * provided `asset`; native assets leave the code unset (the API treats an omitted\n * asset as native XLM). Returns a new object — the input is not mutated.\n */\nexport function resolveIntentBody<T extends ResolvableIntentInput>(\n options: T,\n book: AddressBook = defaultBook,\n): Omit<T, 'asset'> {\n const out: Record<string, unknown> = { ...(options as Record<string, unknown>) };\n\n if (typeof out['destination'] === 'string') {\n out['destination'] = resolveAddress(out['destination'], book);\n }\n if (typeof out['source'] === 'string') {\n out['source'] = resolveAddress(out['source'], book);\n }\n\n if (out['asset'] != null) {\n const { code, issuer } = resolveAsset(out['asset'] as AssetRef);\n delete out['asset'];\n if (issuer) {\n // Non-native: fill code + issuer unless the caller set them explicitly.\n out['assetCode'] ??= code;\n out['assetIssuer'] ??= issuer;\n }\n // Native (issuer == null) → leave assetCode/assetIssuer omitted = native XLM.\n }\n\n return out as Omit<T, 'asset'>;\n}\n","import { PaymentIntent } from '@/structures/PaymentIntent';\nimport type {\n CreatePayPaymentIntentOptions,\n CreateTxPaymentIntentOptions,\n DeletedData,\n ListPaymentIntentsOptions,\n PaymentIntentData,\n PaymentIntentListData,\n UpdatePaymentIntentOptions,\n ValidatePaymentIntentOptions,\n ValidationOutcomeData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { resolveIntentBody } from '@/common/intent-input';\n\n/** A page of payment intents plus its pagination metadata. */\nexport interface PaymentIntentPage {\n items: PaymentIntent[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Validation outcome with the (optional) refreshed intent materialized. */\nexport interface ValidationOutcome {\n valid: boolean;\n status: ValidationOutcomeData['status'];\n reason: string | null;\n paymentIntent: PaymentIntent | null;\n}\n\n/**\n * Manages Stellar payment intents — `client.paymentIntents`.\n *\n * @example\n * const intent = await client.paymentIntents.createTx({\n * source: 'G...', destination: 'G...', amount: '25.5',\n * });\n * console.log(intent.uri, intent.qr);\n */\nexport class PaymentIntentManager extends BaseManager<PaymentIntent> {\n private readonly route = '/payment-intents';\n\n /** Create a SEP-7 `tx` intent (source known → unsigned XDR + tx URI + QR). */\n public async createTx(\n options: CreateTxPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/tx`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Create a SEP-7 `pay` intent (no source → pay URI + QR, no XDR). */\n public async createPay(\n options: CreatePayPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/pay`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Get a single payment intent by id. */\n public async fetch(id: string): Promise<PaymentIntent> {\n const data = await this.rest.get<PaymentIntentData>(`${this.route}/${id}`);\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** List the consumer's payment intents (paginated). */\n public async list(\n options: ListPaymentIntentsOptions = {},\n ): Promise<PaymentIntentPage> {\n const data = await this.rest.get<PaymentIntentListData>(this.route, {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new PaymentIntent(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Update a payment intent (status / txHash / reference). */\n public async update(\n id: string,\n options: UpdatePaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.patch<PaymentIntentData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Delete a payment intent. */\n public async delete(id: string): Promise<DeletedData> {\n const result = await this.rest.delete<DeletedData>(`${this.route}/${id}`);\n this.cache.delete(id);\n return result;\n }\n\n /**\n * Validate a submitted transaction against the intent (tx success +\n * destination + amount + memo). Finalizes status server-side and fires events.\n */\n public async validate(\n id: string,\n options: ValidatePaymentIntentOptions,\n ): Promise<ValidationOutcome> {\n const data = await this.rest.post<ValidationOutcomeData>(\n `${this.route}/${id}/validate`,\n { body: options },\n );\n const paymentIntent = data.paymentIntent\n ? this._add(new PaymentIntent(this.client, data.paymentIntent))\n : null;\n return {\n valid: data.valid,\n status: data.status,\n reason: data.reason ?? null,\n paymentIntent,\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n ProductKind,\n type ProductData,\n type UpdateProductOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A product / price the consumer can charge for. */\nexport class Product extends Base<ProductData> {\n public name!: string;\n public description!: string | null;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public kind!: ProductKind;\n public active!: boolean;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: ProductData) {\n super(client, data);\n }\n\n protected override _patch(data: ProductData): this {\n super._patch(data);\n this.name = data.name;\n this.description = data.description;\n this.amount = data.amount;\n this.asset = data.asset;\n this.kind = data.kind;\n this.active = data.active;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this product. */\n public fetch(): Promise<Product> {\n return this.client.products.fetch(this.id);\n }\n\n /** Update this product. Mutates and returns this. */\n public async edit(options: UpdateProductOptions): Promise<this> {\n const updated = await this.client.products.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Mark the product active. */\n public activate(): Promise<this> {\n return this.edit({ active: true });\n }\n\n /** Mark the product inactive. */\n public deactivate(): Promise<this> {\n return this.edit({ active: false });\n }\n\n /** Delete this product. */\n public delete() {\n return this.client.products.delete(this.id);\n }\n\n public toJSON(): ProductData {\n return {\n id: this.id,\n name: this.name,\n description: this.description,\n amount: this.amount,\n asset: this.asset,\n kind: this.kind,\n active: this.active,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { Product } from '@/structures/Product';\nimport type {\n CreateProductOptions,\n ProductData,\n UpdateProductOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype ProductDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages products / prices — `client.products`.\n *\n * @example\n * const product = await client.products.create({\n * name: 'Pro plan — monthly', amount: '49.00', assetCode: 'USDC',\n * });\n */\nexport class ProductManager extends BaseManager<Product> {\n private readonly route = '/products';\n\n /** Create a product. */\n public async create(options: CreateProductOptions): Promise<Product> {\n const data = await this.rest.post<ProductData>(this.route, { body: options });\n return this._add(new Product(this.client, data));\n }\n\n /** List the consumer's products. */\n public async list(): Promise<Product[]> {\n const data = await this.rest.get<ProductData[]>(this.route);\n return data.map((d) => this._add(new Product(this.client, d)));\n }\n\n /** Get a product by id. */\n public async fetch(id: string): Promise<Product> {\n const data = await this.rest.get<ProductData>(`${this.route}/${id}`);\n return this._add(new Product(this.client, data));\n }\n\n /** Update a product. */\n public async update(\n id: string,\n options: UpdateProductOptions,\n ): Promise<Product> {\n const data = await this.rest.patch<ProductData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Product(this.client, data));\n }\n\n /** Delete a product. */\n public async delete(id: string): Promise<ProductDeletedData> {\n const result = await this.rest.delete<ProductDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n SwapStatus,\n type SubmitSwapOptions,\n type SwapData,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\nimport type { SwapSubmitOutcome } from '@/managers/SwapManager';\n\n/**\n * A Stellar path-payment swap.\n *\n * Wraps the raw API payload with typed accessors and atomic action methods so\n * you can operate on it directly: `await swap.fetch()`,\n * `await swap.submit({ signedXdr })`.\n */\nexport class Swap extends Base<SwapData> {\n public status!: SwapStatus;\n public network!: string;\n /** Account performing the swap. */\n public source!: string;\n /** Account that receives the swapped asset. */\n public destination!: string;\n /** Asset code being sent, or `native` for XLM. */\n public sendAsset!: string;\n public sendAssetIssuer!: string | null;\n public sendAmount!: string;\n public feeAmount!: string;\n public feeBps!: number;\n /** Amount swapped after the fee is deducted. */\n public swapAmount!: string;\n /** Asset code being received, or `native` for XLM. */\n public destAsset!: string;\n public destAssetIssuer!: string | null;\n public destEstimated!: string;\n public destMin!: string;\n public slippageBps!: number;\n public path!: { code: string; issuer: string | null }[];\n public memo!: string | null;\n /** Unsigned transaction envelope (base64 XDR). */\n public xdr!: string;\n /** SEP-7 deep link. */\n public uri!: string;\n public txHash!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: SwapData) {\n super(client, data);\n }\n\n protected override _patch(data: SwapData): this {\n super._patch(data);\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.destination = data.destination;\n this.sendAsset = data.sendAsset;\n this.sendAssetIssuer = data.sendAssetIssuer;\n this.sendAmount = data.sendAmount;\n this.feeAmount = data.feeAmount;\n this.feeBps = data.feeBps;\n this.swapAmount = data.swapAmount;\n this.destAsset = data.destAsset;\n this.destAssetIssuer = data.destAssetIssuer;\n this.destEstimated = data.destEstimated;\n this.destMin = data.destMin;\n this.slippageBps = data.slippageBps;\n this.path = data.path;\n this.memo = data.memo;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.txHash = data.txHash;\n this.qr = data.qr;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether the swap has settled on-chain. */\n public get isSucceeded(): boolean {\n return this.status === SwapStatus.Succeeded;\n }\n\n /** Whether the swap is still awaiting submission. */\n public get isPending(): boolean {\n return this.status === SwapStatus.Pending;\n }\n\n /** Human-readable send asset label (`XLM` for native). */\n public get sendAssetLabel(): string {\n return !this.sendAsset || this.sendAsset === 'native' ? 'XLM' : this.sendAsset;\n }\n\n /** Human-readable destination asset label (`XLM` for native). */\n public get destAssetLabel(): string {\n return !this.destAsset || this.destAsset === 'native' ? 'XLM' : this.destAsset;\n }\n\n /** Re-fetch this swap from the API, returning a fresh instance. */\n public fetch(): Promise<Swap> {\n return this.client.swaps.fetch(this.id);\n }\n\n /**\n * Relay the signed transaction for this swap. Mutates this instance from the\n * refreshed swap in the outcome and returns the outcome.\n */\n public async submit(options: SubmitSwapOptions): Promise<SwapSubmitOutcome> {\n const outcome = await this.client.swaps.submit(this.id, options);\n this._patch(outcome.swap.toJSON());\n return outcome;\n }\n\n public toJSON(): SwapData {\n return {\n id: this.id,\n status: this.status,\n network: this.network,\n source: this.source,\n destination: this.destination,\n sendAsset: this.sendAsset,\n sendAssetIssuer: this.sendAssetIssuer,\n sendAmount: this.sendAmount,\n feeAmount: this.feeAmount,\n feeBps: this.feeBps,\n swapAmount: this.swapAmount,\n destAsset: this.destAsset,\n destAssetIssuer: this.destAssetIssuer,\n destEstimated: this.destEstimated,\n destMin: this.destMin,\n slippageBps: this.slippageBps,\n path: this.path,\n memo: this.memo,\n xdr: this.xdr,\n uri: this.uri,\n txHash: this.txHash,\n qr: this.qr,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { Swap } from '@/structures/Swap';\nimport type {\n CreateSwapOptions,\n ListSwapsOptions,\n QuoteSwapOptions,\n SubmitSwapOptions,\n SwapData,\n SwapListData,\n SwapQuoteData,\n SwapStatus,\n SwapSubmitOutcomeData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\n/** A page of swaps plus its pagination metadata. */\nexport interface SwapPage {\n items: Swap[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Submission outcome with the refreshed swap materialized. */\nexport interface SwapSubmitOutcome {\n submitted: boolean;\n status: SwapStatus;\n txHash: string | null;\n reason: string | null;\n resultCodes: string[] | null;\n swap: Swap;\n}\n\n/**\n * Manages Stellar swaps — `client.swaps`.\n *\n * @example\n * const quote = await client.swaps.quote({\n * amount: '100', destAssetCode: 'USDC',\n * });\n * const swap = await client.swaps.create({\n * amount: '100', destAssetCode: 'USDC', source: 'G...',\n * });\n * console.log(swap.uri, swap.qr);\n */\nexport class SwapManager extends BaseManager<Swap> {\n private readonly route = '/swaps';\n\n /** Price a swap without creating it. Returns a plain quote (not a {@link Swap}). */\n public async quote(options: QuoteSwapOptions): Promise<SwapQuoteData> {\n return this.rest.post<SwapQuoteData>(`${this.route}/quote`, {\n body: options,\n });\n }\n\n /** Create a swap (unsigned XDR + SEP-7 URI + QR). */\n public async create(options: CreateSwapOptions): Promise<Swap> {\n const data = await this.rest.post<SwapData>(this.route, { body: options });\n return this._add(new Swap(this.client, data));\n }\n\n /** Get a single swap by id. */\n public async fetch(id: string): Promise<Swap> {\n const data = await this.rest.get<SwapData>(`${this.route}/${id}`);\n return this._add(new Swap(this.client, data));\n }\n\n /** List the consumer's swaps (paginated). */\n public async list(options: ListSwapsOptions = {}): Promise<SwapPage> {\n const data = await this.rest.get<SwapListData>(this.route, {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new Swap(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /**\n * Relay a signed swap transaction to the network. Finalizes status\n * server-side and returns the outcome with the refreshed swap materialized.\n */\n public async submit(\n id: string,\n options: SubmitSwapOptions,\n ): Promise<SwapSubmitOutcome> {\n const data = await this.rest.post<SwapSubmitOutcomeData>(\n `${this.route}/${id}/submit`,\n { body: options },\n );\n return {\n submitted: data.submitted,\n status: data.status,\n txHash: data.txHash ?? null,\n reason: data.reason ?? null,\n resultCodes: data.resultCodes ?? null,\n swap: this._add(new Swap(this.client, data.swap)),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n WebhookDeliveryStatus,\n WebhookEventType,\n type WebhookDeliveryData,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A single attempt to deliver an event to a webhook endpoint (audit record). */\nexport class WebhookDelivery extends Base<WebhookDeliveryData> {\n public endpointId!: string;\n public eventType!: WebhookEventType;\n public eventId!: string;\n public payload!: Record<string, unknown>;\n public status!: WebhookDeliveryStatus;\n public attempts!: number;\n public responseStatus!: number | null;\n public error!: string | null;\n public lastAttemptAt!: Date | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: WebhookDeliveryData) {\n super(client, data);\n }\n\n protected override _patch(data: WebhookDeliveryData): this {\n super._patch(data);\n this.endpointId = data.endpointId;\n this.eventType = data.eventType;\n this.eventId = data.eventId;\n this.payload = data.payload;\n this.status = data.status;\n this.attempts = data.attempts;\n this.responseStatus = data.responseStatus;\n this.error = data.error;\n this.lastAttemptAt = data.lastAttemptAt ? new Date(data.lastAttemptAt) : null;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n public get isSucceeded(): boolean {\n return this.status === WebhookDeliveryStatus.Succeeded;\n }\n\n /** Manually re-send this delivery. */\n public redeliver(): Promise<WebhookDelivery> {\n return this.client.webhooks.redeliver(this.endpointId, this.id);\n }\n\n public toJSON(): WebhookDeliveryData {\n return {\n id: this.id,\n endpointId: this.endpointId,\n eventType: this.eventType,\n eventId: this.eventId,\n payload: this.payload,\n status: this.status,\n attempts: this.attempts,\n responseStatus: this.responseStatus,\n error: this.error,\n lastAttemptAt: this.lastAttemptAt ? this.lastAttemptAt.toISOString() : null,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport type {\n ListWebhookDeliveriesOptions,\n UpdateWebhookEndpointOptions,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEventType,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A registered webhook endpoint.\n *\n * Note: the signing `secret` is only ever present on the instance returned by\n * `create()` / `rotateSecret()` — list/get responses never include it.\n */\nexport class WebhookEndpoint extends Base<WebhookEndpointData> {\n public url!: string;\n public description!: string | null;\n public enabled!: boolean;\n public eventTypes!: WebhookEventType[];\n public createdAt!: Date;\n public updatedAt!: Date;\n /** HMAC signing secret — only set on create/rotate responses. */\n public readonly secret: string | null;\n\n constructor(\n client: Client,\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ) {\n super(client, data);\n this.secret = 'secret' in data ? data.secret : null;\n }\n\n protected override _patch(\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ): this {\n super._patch(data);\n this.url = data.url;\n this.description = data.description;\n this.enabled = data.enabled;\n this.eventTypes = data.eventTypes;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether the endpoint receives all events (empty subscription). */\n public get receivesAllEvents(): boolean {\n return this.eventTypes.length === 0;\n }\n\n /** Re-fetch this endpoint. */\n public fetch(): Promise<WebhookEndpoint> {\n return this.client.webhooks.fetch(this.id);\n }\n\n /** Update url/description/enabled/eventTypes. Mutates and returns this. */\n public async edit(options: UpdateWebhookEndpointOptions): Promise<this> {\n const updated = await this.client.webhooks.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Pause deliveries to this endpoint. */\n public disable(): Promise<this> {\n return this.edit({ enabled: false });\n }\n\n /** Resume deliveries to this endpoint. */\n public enable(): Promise<this> {\n return this.edit({ enabled: true });\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public rotateSecret(): Promise<WebhookEndpoint> {\n return this.client.webhooks.rotateSecret(this.id);\n }\n\n /** Send a test event to verify the endpoint. */\n public ping() {\n return this.client.webhooks.ping(this.id);\n }\n\n /** List delivery attempts for this endpoint. */\n public fetchDeliveries(options?: ListWebhookDeliveriesOptions) {\n return this.client.webhooks.fetchDeliveries(this.id, options);\n }\n\n /** Delete this endpoint. */\n public delete() {\n return this.client.webhooks.delete(this.id);\n }\n\n public toJSON(): WebhookEndpointData {\n return {\n id: this.id,\n url: this.url,\n description: this.description,\n enabled: this.enabled,\n eventTypes: this.eventTypes,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/** Library version, kept in sync with package.json. */\nexport const version = '1.2.0';\n\n/**\n * Default base URL of the Cosmos Pay gateway. Maintained by Cosmos Pay — users\n * never need to set this; it's part of the {@link shared} configuration. Override\n * only when self-hosting or pointing at a staging gateway.\n *\n * This is the public APISIX gateway: requests under `/cosmos-api/*` are\n * authenticated (API key) and proxied to the Payments API. The version segment\n * (`/v1`, see {@link DEFAULT_VERSION}) is appended by the REST layer, producing\n * e.g. `https://api.cosmospay.lat/cosmos-api/v1/payment-intents/pay`.\n */\nexport const DEFAULT_BASE_URL = 'https://api.cosmospay.lat/cosmos-api';\n\n/** Default API version segment prefixed to every route (`/v1/...`). */\nexport const DEFAULT_VERSION = 'v1';\n\n/** Default request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT = 30_000;\n\n/** Default number of retries for transient failures (network / 429 / 5xx). */\nexport const DEFAULT_RETRIES = 2;\n\n/** Default HMAC signature header sent by the Cosmos Pay webhook dispatcher. */\nexport const SIGNATURE_HEADER = 'x-cosmos-signature';\n\n/**\n * Client debug/telemetry events. The {@link Client} extends EventEmitter and\n * emits these for observability (`debug`/`rateLimit`-style events).\n */\nexport const Events = {\n Debug: 'debug',\n Request: 'request',\n Response: 'response',\n RateLimited: 'rateLimited',\n} as const;\nexport type ClientEvent = (typeof Events)[keyof typeof Events];\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\nimport type { WebhookEvent } from '@/types/index';\n\n/** Options for {@link Webhooks.verify} / {@link Webhooks.constructEvent}. */\nexport interface VerifyWebhookOptions {\n /**\n * Tolerance in seconds between the signed timestamp and now. Protects against\n * replay attacks. Defaults to 300 (5 minutes). Pass 0 to disable the check.\n */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — useful for testing. */\n now?: number;\n}\n\n/** Thrown when a webhook signature fails verification. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WebhookSignatureError';\n }\n}\n\n/**\n * Stateless helpers to verify the HMAC signatures the Cosmos Pay dispatcher\n * sends with each webhook delivery, and to safely parse the event body.\n *\n * The dispatcher signs each POST with:\n * `X-Cosmos-Signature: t=<unixSeconds>,v1=<hexHmacSha256>`\n * where the HMAC-SHA256 is computed over `${t}.${rawBody}` using the endpoint's\n * `whsec_...` secret.\n *\n * @example\n * // Express raw-body handler\n * app.post('/hooks', express.raw({ type: '*​/*' }), (req, res) => {\n * try {\n * const event = Webhooks.constructEvent(\n * req.body, // the RAW body (Buffer/string)\n * req.header('X-Cosmos-Signature'),\n * process.env.WEBHOOK_SECRET,\n * );\n * // event.type, event.data ...\n * res.sendStatus(200);\n * } catch {\n * res.sendStatus(400);\n * }\n * });\n */\nexport const Webhooks = {\n /** Header name the dispatcher uses for the signature. */\n SIGNATURE_HEADER,\n\n /**\n * Verify a webhook signature. Returns `true` on success, throws\n * {@link WebhookSignatureError} on any failure (so it never silently passes).\n */\n verify(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): boolean {\n if (!signatureHeader) {\n throw new WebhookSignatureError('Missing signature header.');\n }\n if (!secret) {\n throw new WebhookSignatureError('Missing signing secret.');\n }\n\n const { timestamp, signature } = parseSignatureHeader(signatureHeader);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n\n const expected = createHmac('sha256', secret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n\n if (!safeEqualHex(expected, signature)) {\n throw new WebhookSignatureError('Signature mismatch.');\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n if (tolerance > 0) {\n const now = options.now ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n throw new WebhookSignatureError(\n `Timestamp outside tolerance (${tolerance}s).`,\n );\n }\n }\n\n return true;\n },\n\n /**\n * Verify the signature and return the parsed {@link WebhookEvent}. Throws\n * {@link WebhookSignatureError} if verification fails.\n */\n constructEvent<T = unknown>(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): WebhookEvent<T> {\n this.verify(rawBody, signatureHeader, secret, options);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n try {\n return JSON.parse(payload) as WebhookEvent<T>;\n } catch {\n throw new WebhookSignatureError('Body is not valid JSON.');\n }\n },\n};\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction parseSignatureHeader(header: string): {\n timestamp: number;\n signature: string;\n} {\n let timestamp: number | undefined;\n let signature: string | undefined;\n for (const part of header.split(',')) {\n const [key, value] = part.split('=');\n if (!key || value === undefined) continue;\n const k = key.trim();\n if (k === 't') timestamp = Number(value.trim());\n else if (k === 'v1') signature = value.trim();\n }\n if (timestamp === undefined || Number.isNaN(timestamp) || !signature) {\n throw new WebhookSignatureError('Malformed signature header.');\n }\n return { timestamp, signature };\n}\n\nfunction safeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n try {\n return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));\n } catch {\n return false;\n }\n}\n\nfunction decode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('utf8');\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { WebhookDelivery } from '@/structures/WebhookDelivery';\nimport { WebhookEndpoint } from '@/structures/WebhookEndpoint';\nimport type {\n CreateWebhookEndpointOptions,\n ListWebhookDeliveriesOptions,\n PaymentIntentData,\n UpdateWebhookEndpointOptions,\n WebhookDeliveryData,\n WebhookDeliveryListData,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEvent,\n WebhookPingData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { Webhooks, WebhookSignatureError } from '@/util/Webhooks';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\n\n// Local alias — the deleted shape mirrors DeletedData.\ntype WebhookDeletedData = { id: string; deleted: boolean };\n\n/** A page of webhook deliveries plus its pagination metadata. */\nexport interface WebhookDeliveryPage {\n items: WebhookDelivery[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Options for verifying + dispatching an incoming webhook. */\nexport interface WebhookProcessOptions {\n /** Signing secret. Falls back to the client's `webhookSecret` when omitted. */\n secret?: string;\n /** Replay tolerance in seconds (default 300; 0 disables). */\n toleranceSeconds?: number;\n}\n\n/** Options for the built-in HTTP webhook handlers. */\nexport type WebhookHandlerOptions = WebhookProcessOptions;\n\n/**\n * Listener signatures for {@link WebhookManager}. You can subscribe with the raw\n * event type (`PAYMENT_INTENT_SUCCEEDED`), its camelCase alias\n * (`paymentIntentSucceeded`), or `event` to catch them all.\n */\nexport interface WebhookListenerEvents {\n event: [WebhookEvent<PaymentIntentData>];\n\n PAYMENT_INTENT_CREATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_UPDATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_SUCCEEDED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_FAILED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_CANCELLED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_DELETED: [WebhookEvent<PaymentIntentData>];\n\n paymentIntentCreated: [WebhookEvent<PaymentIntentData>];\n paymentIntentUpdated: [WebhookEvent<PaymentIntentData>];\n paymentIntentSucceeded: [WebhookEvent<PaymentIntentData>];\n paymentIntentFailed: [WebhookEvent<PaymentIntentData>];\n paymentIntentCancelled: [WebhookEvent<PaymentIntentData>];\n paymentIntentDeleted: [WebhookEvent<PaymentIntentData>];\n}\n\n/** Minimal Express-like request (so we don't depend on `@types/express`). */\ninterface RequestLike {\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n rawBody?: unknown;\n [key: string]: unknown;\n}\n\n/** Minimal Express-like response. */\ninterface ResponseLike {\n status(code: number): ResponseLike;\n send(body?: unknown): unknown;\n end(body?: unknown): unknown;\n}\n\n// Typed event overloads (declaration merging onto the class).\nexport interface WebhookManager {\n on<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n once<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n off<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n emit<E extends keyof WebhookListenerEvents>(\n event: E,\n ...args: WebhookListenerEvents[E]\n ): boolean;\n}\n\n/**\n * Manages webhook endpoints, their delivery audit trail, **and** the incoming\n * event listener — `client.webhooks`.\n *\n * Registering endpoints (server-side CRUD):\n * @example\n * const endpoint = await client.webhooks.create({\n * url: 'https://me.example.com/hooks',\n * eventTypes: ['PAYMENT_INTENT_SUCCEEDED'],\n * });\n * console.log(endpoint.secret); // shown once — store it!\n *\n * Receiving events (listener):\n * @example\n * client.webhooks.on('paymentIntentSucceeded', (event) => {\n * console.log('Paid!', event.data.id);\n * });\n *\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler()).listen(4242);\n */\nexport class WebhookManager extends BaseManager<WebhookEndpoint> {\n private readonly route = '/webhooks';\n\n // ── Endpoint CRUD ───────────────────────────────────────────────────────────\n\n /** Register a webhook endpoint (the returned instance carries the secret once). */\n public async create(\n options: CreateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(this.route, {\n body: options,\n });\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** List the consumer's webhook endpoints. */\n public async list(): Promise<WebhookEndpoint[]> {\n const data = await this.rest.get<WebhookEndpointData[]>(this.route);\n return data.map((d) => this._add(new WebhookEndpoint(this.client, d)));\n }\n\n /** Get a webhook endpoint by id. */\n public async fetch(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.get<WebhookEndpointData>(`${this.route}/${id}`);\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Update a webhook endpoint (url/description/enabled/eventTypes). */\n public async update(\n id: string,\n options: UpdateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.patch<WebhookEndpointData>(\n `${this.route}/${id}`,\n { body: options },\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Delete a webhook endpoint. */\n public async delete(id: string): Promise<WebhookDeletedData> {\n const result = await this.rest.delete<WebhookDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public async rotateSecret(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(\n `${this.route}/${id}/rotate-secret`,\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Send a test event to verify the endpoint. */\n public ping(id: string): Promise<WebhookPingData> {\n return this.rest.post<WebhookPingData>(`${this.route}/${id}/ping`);\n }\n\n /** List delivery attempts for an endpoint (audit trail). */\n public async fetchDeliveries(\n id: string,\n options: ListWebhookDeliveriesOptions = {},\n ): Promise<WebhookDeliveryPage> {\n const data = await this.rest.get<WebhookDeliveryListData>(\n `${this.route}/${id}/deliveries`,\n {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n },\n );\n return {\n items: data.data.map((d) => new WebhookDelivery(this.client, d)),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Manually re-send a past delivery. */\n public async redeliver(\n id: string,\n deliveryId: string,\n ): Promise<WebhookDelivery> {\n const data = await this.rest.post<WebhookDeliveryData>(\n `${this.route}/${id}/deliveries/${deliveryId}/redeliver`,\n );\n return new WebhookDelivery(this.client, data);\n }\n\n // ── Incoming event listener ──────────────────────────────────────────────────\n\n /**\n * Verify a raw incoming webhook request and dispatch it to the listeners\n * registered via {@link WebhookManager.on}. Returns the parsed event.\n *\n * Emits, in order: the raw type (`PAYMENT_INTENT_SUCCEEDED`), the camelCase\n * alias (`paymentIntentSucceeded`) and the catch-all `event`.\n *\n * @throws {WebhookSignatureError} when the signature is missing/invalid.\n */\n public process(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n options: WebhookProcessOptions = {},\n ): WebhookEvent<PaymentIntentData> {\n const secret = options.secret ?? this.client.webhookSecret;\n if (!secret) {\n throw new WebhookSignatureError(\n 'No webhook secret configured. Pass `{ secret }` or set `webhookSecret` on the client.',\n );\n }\n\n const event = Webhooks.constructEvent<PaymentIntentData>(\n rawBody,\n signatureHeader,\n secret,\n { toleranceSeconds: options.toleranceSeconds },\n );\n\n this.emit(event.type, event);\n this.emit(toCamelEvent(event.type), event);\n this.emit('event', event);\n return event;\n }\n\n /**\n * Build a Node.js `http`/`https` request handler that verifies the signature,\n * dispatches the event to your listeners, and replies `200`/`400`.\n *\n * @example\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler({ secret })).listen(4242);\n */\n public createHandler(\n options: WebhookHandlerOptions = {},\n ): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void this.collectBody(req)\n .then((raw) => {\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n this.process(raw, sig, options);\n res.statusCode = 200;\n res.end('ok');\n })\n .catch((err: unknown) => {\n res.statusCode = err instanceof WebhookSignatureError ? 400 : 500;\n res.end(\n err instanceof WebhookSignatureError ? 'invalid signature' : 'error',\n );\n });\n };\n }\n\n /**\n * Express-style middleware. Expects the **raw** body (e.g. mounted with\n * `express.raw({ type: '*​/*' })`). On success it attaches the parsed event to\n * `req.cosmosEvent` and calls `next()`; on a bad signature it replies `400`.\n *\n * @example\n * app.post('/hooks', express.raw({ type: '*​/*' }), client.webhooks.middleware({ secret }));\n */\n public middleware(\n options: WebhookHandlerOptions = {},\n ): (req: RequestLike, res: ResponseLike, next: (err?: unknown) => void) => void {\n return (req, res, next) => {\n try {\n const raw = extractRawBody(req);\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n const event = this.process(raw, sig, options);\n req.cosmosEvent = event;\n next();\n } catch (err) {\n if (err instanceof WebhookSignatureError) {\n res.status(400).send('invalid signature');\n return;\n }\n next(err);\n }\n };\n }\n\n /** Read a Node.js request stream into a single Buffer. */\n private collectBody(req: IncomingMessage): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\n/** `PAYMENT_INTENT_SUCCEEDED` → `paymentIntentSucceeded`. */\nfunction toCamelEvent(type: string): keyof WebhookListenerEvents {\n return type\n .toLowerCase()\n .replace(/_([a-z])/g, (_, c: string) =>\n c.toUpperCase(),\n ) as keyof WebhookListenerEvents;\n}\n\nfunction headerValue(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction extractRawBody(req: RequestLike): string | Uint8Array {\n const candidate = req.rawBody ?? req.body;\n if (typeof candidate === 'string' || candidate instanceof Uint8Array) {\n return candidate;\n }\n // express.json() already parsed it — re-stringify so the signature still matches\n // only if the original raw body is unavailable (best-effort).\n if (candidate && typeof candidate === 'object') {\n return JSON.stringify(candidate);\n }\n return '';\n}\n","/**\n * Error thrown when the Cosmos Pay API responds with a non-2xx status.\n *\n * Carries the HTTP status, the parsed response body and the request context so\n * callers can branch on `error.status` (e.g. 404 → not found, 403 → gateway).\n */\nexport class CosmosPayAPIError extends Error {\n /** HTTP status code returned by the API. */\n public readonly status: number;\n /** HTTP method of the failed request. */\n public readonly method: string;\n /** Absolute URL of the failed request. */\n public readonly url: string;\n /** Parsed response body (object when JSON, string otherwise, or null). */\n public readonly body: unknown;\n /** Machine-readable error code extracted from the body when present. */\n public readonly code: string | undefined;\n\n constructor(options: {\n status: number;\n method: string;\n url: string;\n body: unknown;\n }) {\n const message = CosmosPayAPIError.resolveMessage(options.status, options.body);\n super(message);\n this.name = 'CosmosPayAPIError';\n this.status = options.status;\n this.method = options.method;\n this.url = options.url;\n this.body = options.body;\n this.code = CosmosPayAPIError.resolveCode(options.body);\n Error.captureStackTrace?.(this, CosmosPayAPIError);\n }\n\n private static resolveMessage(status: number, body: unknown): string {\n if (body && typeof body === 'object') {\n const maybe = body as { message?: unknown; error?: unknown };\n const msg = maybe.message ?? maybe.error;\n if (Array.isArray(msg)) return `[${status}] ${msg.join(', ')}`;\n if (typeof msg === 'string') return `[${status}] ${msg}`;\n }\n if (typeof body === 'string' && body.length) return `[${status}] ${body}`;\n return `[${status}] Request failed`;\n }\n\n private static resolveCode(body: unknown): string | undefined {\n if (body && typeof body === 'object') {\n const maybe = body as { code?: unknown; error?: unknown };\n if (typeof maybe.code === 'string') return maybe.code;\n if (typeof maybe.error === 'string') return maybe.error;\n }\n return undefined;\n }\n}\n\n/**\n * Error thrown when a request never reaches the API: network failure, abort or\n * timeout. Distinct from {@link CosmosPayAPIError}, which always has a status.\n */\nexport class CosmosPayRequestError extends Error {\n public readonly method: string;\n public readonly url: string;\n public readonly cause: unknown;\n\n constructor(options: { method: string; url: string; cause: unknown }) {\n const reason =\n options.cause instanceof Error ? options.cause.message : String(options.cause);\n super(`Request to ${options.method} ${options.url} failed: ${reason}`);\n this.name = 'CosmosPayRequestError';\n this.method = options.method;\n this.url = options.url;\n this.cause = options.cause;\n Error.captureStackTrace?.(this, CosmosPayRequestError);\n }\n}\n","import { EventEmitter } from 'node:events';\nimport {\n CosmosPayAPIError,\n CosmosPayRequestError,\n} from '@/errors/CosmosPayError';\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT,\n DEFAULT_VERSION,\n Events,\n version,\n} from '@/util/Constants';\n\n/** A `fetch`-compatible function (defaults to the global `fetch`). */\nexport type FetchLike = typeof fetch;\n\n/** Options accepted when constructing a {@link REST} instance. */\nexport interface RESTOptions {\n /**\n * Base URL of the Cosmos Pay gateway (no trailing slash), e.g.\n * `https://api.cosmospay.lat/cosmos-api`. The version segment is appended\n * automatically.\n */\n baseURL: string;\n /**\n * API key issued by the Cosmos developer platform. Sent as\n * `Authorization: Bearer <apiKey>` (and `apikey: <apiKey>`) to the gateway.\n */\n apiKey?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only needed when calling the\n * service directly (bypassing APISIX) — typically local development.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Pair with\n * `gatewaySecret` for direct service access.\n */\n consumerUsername?: string;\n /**\n * API version segment prefixed to every route. Defaults to `v1`. Set to an\n * empty string when your gateway already injects the version.\n */\n version?: string;\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n}\n\n/** Internal options for a single request. */\nexport interface RequestOptions {\n /** Query string parameters; `undefined`/`null` values are dropped. */\n query?: Record<string, string | number | boolean | undefined | null>;\n /** JSON body to send. */\n body?: unknown;\n /** Per-request header overrides. */\n headers?: Record<string, string>;\n /** Per-request AbortSignal. */\n signal?: AbortSignal;\n}\n\nconst RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * The HTTP layer. Owns the base URL, authentication and retry/timeout policy,\n * and exposes thin verb helpers (`get`/`post`/`patch`/`delete`). Managers call\n * these — they never touch `fetch` directly.\n */\nexport class REST extends EventEmitter {\n public baseURL: string;\n public readonly version: string;\n private readonly timeout: number;\n private readonly retries: number;\n private readonly fetchFn: FetchLike;\n private readonly extraHeaders: Record<string, string>;\n private apiKey?: string;\n private gatewaySecret?: string;\n private consumerUsername?: string;\n\n constructor(options: RESTOptions) {\n super();\n if (!options.baseURL) {\n throw new TypeError('REST requires a `baseURL`.');\n }\n this.baseURL = options.baseURL.replace(/\\/+$/, '');\n this.version = options.version ?? DEFAULT_VERSION;\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT;\n this.retries = options.retries ?? DEFAULT_RETRIES;\n this.extraHeaders = options.headers ?? {};\n this.apiKey = options.apiKey;\n this.gatewaySecret = options.gatewaySecret;\n this.consumerUsername = options.consumerUsername;\n\n const fetchFn = options.fetch ?? globalThis.fetch;\n if (typeof fetchFn !== 'function') {\n throw new TypeError(\n 'No global `fetch` found. Use Node.js >= 18 or pass a `fetch` implementation in the client options.',\n );\n }\n this.fetchFn = fetchFn.bind(globalThis);\n }\n\n /** Replace the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.apiKey = apiKey;\n return this;\n }\n\n /** Set direct-access gateway credentials (local/dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.gatewaySecret = secret;\n this.consumerUsername = consumerUsername;\n return this;\n }\n\n public get<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n\n public post<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('POST', path, options);\n }\n\n public patch<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('PATCH', path, options);\n }\n\n public delete<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n /** Build the absolute URL for a route, applying the version prefix + query. */\n public buildURL(path: string, query?: RequestOptions['query']): string {\n const clean = path.startsWith('/') ? path : `/${path}`;\n const prefix = this.version ? `/${this.version}` : '';\n const url = new URL(`${this.baseURL}${prefix}${clean}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n }\n\n private buildHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': `@cosmosapp/pay_sdk/${version}`,\n ...this.extraHeaders,\n };\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n headers['apikey'] = this.apiKey;\n }\n if (this.gatewaySecret) headers['X-Gateway-Secret'] = this.gatewaySecret;\n if (this.consumerUsername) {\n headers['X-Consumer-Username'] = this.consumerUsername;\n }\n return { ...headers, ...extra };\n }\n\n /** Core request with retry, timeout and structured error handling. */\n public async request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n const url = this.buildURL(path, options.query);\n const headers = this.buildHeaders(options.headers);\n\n let serializedBody: string | undefined;\n if (options.body !== undefined) {\n serializedBody = JSON.stringify(options.body);\n headers['Content-Type'] = 'application/json';\n }\n\n let attempt = 0;\n let lastError: unknown;\n\n while (attempt <= this.retries) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n const signal = options.signal\n ? anySignal([options.signal, controller.signal])\n : controller.signal;\n\n this.emit(Events.Request, { method, url, attempt });\n\n try {\n const response = await this.fetchFn(url, {\n method,\n headers,\n body: serializedBody,\n signal,\n });\n clearTimeout(timer);\n\n this.emit(Events.Response, {\n method,\n url,\n status: response.status,\n attempt,\n });\n\n if (response.status === 429) {\n this.emit(Events.RateLimited, { method, url, attempt });\n }\n\n if (!response.ok) {\n const body = await safeParse(response);\n if (RETRYABLE_STATUS.has(response.status) && attempt < this.retries) {\n await this.backoff(response, attempt);\n attempt++;\n continue;\n }\n throw new CosmosPayAPIError({ status: response.status, method, url, body });\n }\n\n return (await safeParse(response)) as T;\n } catch (error) {\n clearTimeout(timer);\n if (error instanceof CosmosPayAPIError) throw error;\n\n // Network/abort/timeout → retry, then surface as a request error.\n lastError = error;\n if (attempt < this.retries) {\n await sleep(backoffDelay(attempt));\n attempt++;\n continue;\n }\n throw new CosmosPayRequestError({ method, url, cause: error });\n }\n }\n\n throw new CosmosPayRequestError({ method, url, cause: lastError });\n }\n\n private async backoff(response: Response, attempt: number): Promise<void> {\n const retryAfter = response.headers.get('retry-after');\n const ms = retryAfter\n ? Number(retryAfter) * 1000\n : backoffDelay(attempt);\n await sleep(Number.isFinite(ms) ? ms : backoffDelay(attempt));\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction backoffDelay(attempt: number): number {\n return Math.min(1000 * 2 ** attempt, 8000);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function safeParse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.includes('application/json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\n/** Combine multiple AbortSignals into one (first to abort wins). */\nfunction anySignal(signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n const onAbort = (signal: AbortSignal) => () => controller.abort(signal.reason);\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n break;\n }\n signal.addEventListener('abort', onAbort(signal), { once: true });\n }\n return controller.signal;\n}\n","import { DEFAULT_BASE_URL, DEFAULT_VERSION } from '@/util/Constants';\n\n/**\n * Internal (\"shared\") configuration that Cosmos Pay maintains on the user's\n * behalf. These are the gateway / infrastructure details an integrator should\n * **not** have to know about — they're pre-filled here so that, in practice, the\n * only credential a user provides is their `apiKey`.\n *\n * Every value is overridable (per-client via {@link ClientOptions}, or globally\n * via {@link Client.shared}) for self-hosting, staging or local development.\n */\nexport interface SharedConfig {\n /** Base URL of the Cosmos Pay gateway. */\n baseURL: string;\n /** API version segment prefixed to every route (`/v1/...`). */\n version: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only used when talking to the\n * service directly, bypassing the gateway (local development). Internal.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Paired with\n * `gatewaySecret` for direct service access. Internal.\n */\n consumerUsername?: string;\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.process` / handlers) when no secret is passed explicitly.\n */\n webhookSecret?: string;\n}\n\n/**\n * The mutable, process-wide defaults. Cosmos Pay ships sane values here; you can\n * tweak them once at startup (e.g. `Client.shared.baseURL = '...'`) and every\n * client created afterwards inherits them.\n */\nexport const shared: SharedConfig = {\n baseURL: DEFAULT_BASE_URL,\n version: DEFAULT_VERSION,\n};\n\n/** Merge a partial override on top of the current shared defaults. */\nexport function resolveShared(overrides: Partial<SharedConfig> = {}): SharedConfig {\n const defined: Partial<SharedConfig> = {};\n for (const key of Object.keys(overrides) as (keyof SharedConfig)[]) {\n const value = overrides[key];\n if (value !== undefined) {\n Object.assign(defined, { [key]: value });\n }\n }\n return { ...shared, ...defined };\n}\n","import { EventEmitter } from 'node:events';\nimport { AnalyticsManager } from '@/managers/AnalyticsManager';\nimport { CustomerManager } from '@/managers/CustomerManager';\nimport { HealthManager } from '@/managers/HealthManager';\nimport { PaymentIntentManager } from '@/managers/PaymentIntentManager';\nimport { ProductManager } from '@/managers/ProductManager';\nimport { SwapManager } from '@/managers/SwapManager';\nimport { WebhookManager } from '@/managers/WebhookManager';\nimport { REST, type FetchLike } from '@/rest/REST';\nimport { version } from '@/util/Constants';\nimport { resolveShared, shared, type SharedConfig } from '@/util/shared';\n\n/**\n * Options accepted by the {@link Client} constructor.\n *\n * In practice the only value you provide is `apiKey` — everything else (the\n * gateway URL, version and other infrastructure details) is pre-filled from the\n * {@link Client.shared} defaults that Cosmos Pay maintains for you.\n */\nexport interface ClientOptions {\n /**\n * Your Cosmos Pay API key. Sent to the gateway as `Authorization: Bearer\n * <apiKey>`. The key type determines the network (`dv_` → testnet, `prod_` →\n * mainnet). This is the only credential a typical integration needs.\n */\n apiKey: string;\n\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.on(...)` + handlers) when you don't pass one explicitly.\n */\n webhookSecret?: string;\n\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n\n // ── Advanced / internal overrides (you normally never set these) ────────────\n /**\n * Override the gateway base URL. Defaults to {@link Client.shared}`.baseURL`.\n * Only needed for self-hosting or a staging gateway.\n * @internal\n */\n baseURL?: string;\n /**\n * Override the API version segment. Defaults to `v1`.\n * @internal\n */\n version?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`) for direct, gateway-bypassing\n * access (local development). Maintained internally.\n * @internal\n */\n gatewaySecret?: string;\n /**\n * Consumer username (`X-Consumer-Username`) for direct access. Internal.\n * @internal\n */\n consumerUsername?: string;\n}\n\n/** Payloads emitted by the {@link Client} for observability. */\nexport interface ClientEvents {\n request: [{ method: string; url: string; attempt: number }];\n response: [{ method: string; url: string; status: number; attempt: number }];\n rateLimited: [{ method: string; url: string; attempt: number }];\n debug: [message: string];\n}\n\nexport interface Client {\n on<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n once<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n off<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n emit<E extends keyof ClientEvents>(\n event: E,\n ...args: ClientEvents[E]\n ): boolean;\n}\n\n/**\n * The main entry point of the SDK — a single, atomic client that exposes every\n * resource through its own manager — an atomic, single-client design.\n *\n * @example\n * import { Client } from '@cosmosapp/pay_sdk';\n *\n * // The user only provides their API key — the gateway is handled for them.\n * const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });\n *\n * const intent = await client.paymentIntents.createPay({ destination: 'G...', amount: '10' });\n * console.log(intent.uri);\n */\nexport class Client extends EventEmitter {\n /** Library version. */\n public static readonly version = version;\n\n /**\n * Process-wide shared defaults maintained by Cosmos Pay (gateway URL, version,\n * internal secrets). Mutate once at startup to change them for every client\n * (e.g. self-hosting): `Client.shared.baseURL = 'https://gateway.your-domain.com'`.\n */\n public static readonly shared: SharedConfig = shared;\n\n /** Resolved shared configuration for this client instance. */\n public readonly shared: SharedConfig;\n\n /** Default webhook signing secret for the webhook listener (if configured). */\n public webhookSecret: string | undefined;\n\n /** The underlying HTTP layer. Shared by every manager. */\n public readonly rest: REST;\n\n /** Stellar payment intents — create/list/fetch/update/delete/validate. */\n public readonly paymentIntents: PaymentIntentManager;\n /** Webhook endpoints, delivery audit trail, and the event listener. */\n public readonly webhooks: WebhookManager;\n /** Products / prices. */\n public readonly products: ProductManager;\n /** Stellar swaps — quote/create/fetch/list/submit. */\n public readonly swaps: SwapManager;\n /** Customers. */\n public readonly customers: CustomerManager;\n /** Read-only analytics (summary, balances, logs). */\n public readonly analytics: AnalyticsManager;\n /** Service health probes (public). */\n public readonly health: HealthManager;\n\n constructor(options: ClientOptions) {\n super();\n if (!options || !options.apiKey) {\n throw new TypeError('Client requires an `apiKey` option.');\n }\n\n // Fill the infrastructure details from the shared defaults; the user only\n // had to bring their apiKey.\n this.shared = resolveShared({\n baseURL: options.baseURL,\n version: options.version,\n gatewaySecret: options.gatewaySecret,\n consumerUsername: options.consumerUsername,\n webhookSecret: options.webhookSecret,\n });\n this.webhookSecret = this.shared.webhookSecret;\n\n this.rest = new REST({\n baseURL: this.shared.baseURL,\n apiKey: options.apiKey,\n gatewaySecret: this.shared.gatewaySecret,\n consumerUsername: this.shared.consumerUsername,\n version: this.shared.version,\n timeout: options.timeout,\n retries: options.retries,\n headers: options.headers,\n fetch: options.fetch,\n });\n\n // Re-emit REST telemetry through the client so consumers can subscribe to\n // `client.on('request' | 'response' | 'rateLimited' | 'debug', ...)`.\n this.rest.on('request', (p) => this.emit('request', p));\n this.rest.on('response', (p) => this.emit('response', p));\n this.rest.on('rateLimited', (p) => this.emit('rateLimited', p));\n\n this.paymentIntents = new PaymentIntentManager(this);\n this.webhooks = new WebhookManager(this);\n this.products = new ProductManager(this);\n this.swaps = new SwapManager(this);\n this.customers = new CustomerManager(this);\n this.analytics = new AnalyticsManager(this);\n this.health = new HealthManager(this);\n }\n\n /** Update the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.rest.setApiKey(apiKey);\n return this;\n }\n\n /** Set the default webhook signing secret for the webhook listener. */\n public setWebhookSecret(secret: string): this {\n this.webhookSecret = secret;\n return this;\n }\n\n /** Set direct-access gateway credentials (internal / local dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.rest.setGatewayCredentials(secret, consumerUsername);\n return this;\n }\n}\n","/**\n * Typed identifiers for the wallets the web client knows about, so you can write\n * `Wallets.FREIGHTER` instead of remembering the `'freighter'` magic string —\n * while any custom adapter id still works.\n */\n\n/** Built-in wallet ids (matches each adapter's `id`). */\nexport const Wallets = {\n FREIGHTER: 'freighter',\n XBULL: 'xbull',\n RABET: 'rabet',\n LOBSTR: 'lobstr',\n ALBEDO: 'albedo',\n} as const;\n\n/** A known wallet id, or any custom adapter id (autocomplete for the built-ins). */\nexport type WalletId = (typeof Wallets)[keyof typeof Wallets] | (string & {});\n"]}