@takeal/cusfront-sdk 0.3.0 → 0.3.12

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/error.ts","../src/http.ts","../src/resources/auth.ts","../src/resources/deposits.ts","../src/resources/cards.ts","../src/resources/balance.ts","../src/resources/branding.ts","../src/resources/wallet.ts","../src/resources/blog.ts","../src/resources/subscriptions.ts","../src/resources/sessions.ts","../src/resources/push.ts","../src/resources/me.ts","../src/resources/notifications.ts","../src/resources/devices.ts","../src/version.ts","../src/client-platform.ts","../src/token-store.ts","../src/assets.ts","../src/index.ts"],"names":["ls"],"mappings":";AAQO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EAGlC,WAAA,CAEkB,MAAA,EAIA,IAAA,EAGhB,OAAA,EAGgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAZG,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAMA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAdlB,IAAA,IAAA,CAAS,UAAA,GAAa,IAAA;AAiBpB,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AAAA,EACd;AACF;AAEO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAGtC,WAAA,CAAY,SAAiC,KAAA,EAAiB;AAC5D,IAAA,KAAA,CAAM,OAAO,CAAA;AAD8B,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAF7C,IAAA,IAAA,CAAS,cAAA,GAAiB,IAAA;AAIxB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AAAA,EACd;AACF;AAGO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OACE,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,IAAS,EAA+B,UAAA,KAAe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IAAI,CAAA;AAAA,IACnC,IAAA,EAAM,IAAI,YAAA,CAAa,IAAI,CAAA;AAAA,IAC3B,aAAA,EAAe,IAAI,qBAAA,CAAsB,IAAI,CAAA;AAAA,IAC7C,QAAA,EAAU,IAAI,gBAAA,CAAiB,IAAI,CAAA;AAAA,IACnC,IAAA,EAAM,IAAI,YAAA,CAAa,IAAI,CAAA;AAAA,IAC3B,EAAA,EAAI,IAAI,UAAA,CAAW,IAAI,CAAA;AAAA,IACvB,aAAA,EAAe,IAAI,qBAAA,CAAsB,IAAI,CAAA;AAAA,IAC7C,OAAA,EAAS,IAAI,eAAA,CAAgB,IAAA,EAAM,MAAM;AAAA,GAC3C;AACF;AAEA,SAAS,gBAAA,GAA+B;AACtC,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,IAAe,cAAA,IAAkB,UAAA,EAAY;AACrE,IAAA,OAAO,mBAAA,EAAoB;AAAA,EAC7B;AACA,EAAA,OAAO,aAAA,EAAc;AACvB;AAEA,SAAS,YAAA,GAA0B;AACjC,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,IAAe,OAAO,UAAA,CAAW,UAAU,UAAA,EAAY;AAG/E,IAAA,OAAO,UAAA,CAAW,KAAA,CAAM,IAAA,CAAK,UAAU,CAAA;AAAA,EACzC;AACA,EAAA,MAAM,IAAI,KAAA;AAAA,IACR;AAAA,GAEF;AACF","file":"index.js","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(message: string, public readonly cause?: unknown) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return (\n typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true\n );\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import { ApiError, NetworkError } from \"./error.js\";\nimport type { TokenStore } from \"./token-store.js\";\n\n/**\n * Internal HTTP client. One per SDK instance; injected into each\n * resource. Responsibilities:\n *\n * - Construct absolute URLs from `baseUrl` + API version + path.\n * Resources pass contract paths (`/me/deposits`); the `/v1` prefix is\n * added here, in one place. Only the deployment-level endpoints\n * (`/ready`, `/branding`, …) stay unversioned.\n * - Set `Authorization: Bearer <jwt>` from the `TokenStore`.\n * - Set `Content-Type: application/json` on bodies.\n * - Parse JSON responses + map non-2xx to `ApiError`.\n * - Forward `Idempotency-Key` when the caller passes one.\n * - Send the constructor's `defaultHeaders` (the `X-Takeal-Client`\n * descriptor) on every request.\n * - Surface network failures (DNS, abort, broken pipe) as\n * `NetworkError`.\n *\n * Auto-refresh + retry policies are deliberately NOT in here — they\n * belong to the resource layer (auth.refresh) which has the right\n * context for \"is this refreshable\" decisions.\n */\n\nexport type FetchLike = typeof fetch;\n\n/** Current public contract revision of the Takeal API. */\nexport const API_VERSION = \"/v1\";\n\n/** Host-level endpoints that are not part of a versioned contract. */\nconst UNVERSIONED = new Set([\"/health\", \"/ready\", \"/branding\", \"/favicon.ico\"]);\n\n/**\n * `/me/deposits` → `/v1/me/deposits`. Already-versioned paths and the\n * unversioned ops endpoints pass through untouched.\n */\nexport function versionedPath(path: string): string {\n const p = path.startsWith(\"/\") ? path : `/${path}`;\n const bare = p.split(\"?\")[0]!;\n if (UNVERSIONED.has(bare)) return p;\n if (bare === API_VERSION || bare.startsWith(`${API_VERSION}/`)) return p;\n return `${API_VERSION}${p}`;\n}\n\nexport interface HttpOptions {\n /** Request body. Will be JSON-serialised if not already a\n * string / FormData / Blob. */\n body?: unknown;\n /** Idempotency key forwarded as the `Idempotency-Key` header.\n * Required by the Takeal API on most write endpoints. */\n idempotencyKey?: string;\n /** Extra headers merged after the SDK's defaults — caller wins. */\n headers?: Record<string, string>;\n /** Bypass the token store for one call (login, refresh). */\n skipAuth?: boolean;\n /** AbortSignal forwarded to fetch. */\n signal?: AbortSignal;\n}\n\nexport class HttpClient {\n constructor(\n private readonly baseUrl: string,\n private readonly tokens: TokenStore,\n private readonly fetchImpl: FetchLike,\n /** Headers sent on every request, below the per-call `headers`\n * (a caller can still override one). */\n private readonly defaultHeaders: Record<string, string> = {},\n ) {\n if (!baseUrl) throw new Error(\"HttpClient: baseUrl is required\");\n }\n\n async get<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"GET\", path, opts);\n }\n\n async post<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"POST\", path, opts);\n }\n\n async put<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PUT\", path, opts);\n }\n\n async patch<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PATCH\", path, opts);\n }\n\n async delete<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"DELETE\", path, opts);\n }\n\n private async request<T>(method: string, path: string, opts: HttpOptions): Promise<T> {\n const url = this.absolute(path);\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n ...this.defaultHeaders,\n };\n if (opts.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (opts.idempotencyKey) headers[\"Idempotency-Key\"] = opts.idempotencyKey;\n if (!opts.skipAuth) {\n const token = await Promise.resolve(this.tokens.get());\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n }\n Object.assign(headers, opts.headers ?? {});\n\n const init: RequestInit = {\n method,\n headers,\n ...(opts.signal ? { signal: opts.signal } : {}),\n };\n if (opts.body !== undefined) {\n init.body =\n typeof opts.body === \"string\" ? opts.body : JSON.stringify(opts.body);\n }\n\n let resp: Response;\n try {\n resp = await this.fetchImpl(url, init);\n } catch (e) {\n // DNS failure, connection refused, abort — anything before the\n // server returns a status. Map to NetworkError for the consumer.\n throw new NetworkError(\n e instanceof Error ? e.message : \"network error\",\n e,\n );\n }\n\n return parseResponse<T>(resp);\n }\n\n private absolute(path: string): string {\n if (path.startsWith(\"http://\") || path.startsWith(\"https://\")) return path;\n const base = this.baseUrl.replace(/\\/+$/, \"\");\n return `${base}${versionedPath(path)}`;\n }\n}\n\nasync function parseResponse<T>(resp: Response): Promise<T> {\n // Read body once — the Takeal API either returns JSON or an empty body\n // (204 No Content on some DELETEs). Empty body → undefined cast.\n const text = await resp.text();\n let body: unknown;\n if (text.length === 0) {\n body = undefined;\n } else {\n try {\n body = JSON.parse(text);\n } catch {\n // Non-JSON response. On 2xx that's unexpected but not fatal —\n // hand back the raw text under a synthetic field. On error\n // status, fold into the ApiError body.\n body = { raw: text };\n }\n }\n\n if (!resp.ok) {\n const errBody = (body ?? {}) as { code?: string; message?: string };\n throw new ApiError(\n resp.status,\n errBody.code ?? `http_${resp.status}`,\n errBody.message ?? resp.statusText ?? \"request failed\",\n body,\n );\n }\n return body as T;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n ) {}\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: input,\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await Promise.resolve(this.tokens.set(resp.access_token));\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: { init_data: string; provision?: boolean } = { init_data: input.initData };\n if (input.provision !== undefined) body.provision = input.provision;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach a real email to the current user (and clear `email_pending`).\n * Used after a Telegram exchange to satisfy the email requirement; also\n * works for a password user changing their address. 409 if taken. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Local sign-out: forgets the stored JWT. To end the session on the\n * server as well, revoke it first with `client.sessions.revoke(jti)`\n * (the current one is marked `current: true` in `client.sessions.list()`). */\n async signOut(): Promise<void> {\n await Promise.resolve(this.tokens.clear());\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\n\n/**\n * Deposits resource — `client.deposits.*`.\n *\n * The \"money IN\" surface: an end user tops up their wallet balance via a\n * funder connector. Mirrors the Takeal API's `/me/deposits` routes:\n *\n * POST /me/deposits → initiate\n * GET /me/deposits → list (most recent first)\n * GET /me/deposits/{id} → get\n * POST /me/deposits/{id}/refunds → refund\n *\n * A deposit is rarely terminal on the initiate call: real PSPs return\n * `redirect_required` (3DS / APM redirect) and flip to `confirmed` later via\n * a connector → Takeal API inbound event. Poll `get(id)` or watch the user's\n * webhook stream for the `deposit.confirmed` / `deposit.failed` outcome.\n */\n\n/** Lifecycle of a deposit. `redirect_required` carries `redirect_url`. */\nexport type DepositStatus =\n | \"pending\"\n | \"redirect_required\"\n | \"confirmed\"\n | \"failed\";\n\n/** Top-up rail. The chosen funder decides which it supports. */\nexport type DepositMethod = \"card\" | \"crypto\" | \"bank_transfer\";\n\n/**\n * A deposit record as the Takeal API returns it. Mirrors the `deposits` table; the\n * server-side `id` is the stable handle the SDK polls against. `idempotency_key`\n * and `request_fingerprint` are server-internal and never serialised.\n */\n/** Input for `quote()` — price a cross-currency deposit before paying. */\nexport interface CreateQuoteInput {\n /** Decimal string, e.g. `\"5000.00\"`. */\n amount: string;\n /** ISO 4217 source currency — must differ from the wallet's local currency. */\n currency: string;\n}\n\n/**\n * A rate-locked funding quote: pay `source_amount source_currency`, the\n * wallet is credited `credited_amount credited_currency` (net of the\n * platform's conversion spread). Execute by passing `id` as `quote_id` to\n * `initiate()` before `expires_at`; after that the API returns 409 and a new\n * quote is needed.\n */\nexport interface FundingQuote {\n id: string;\n source_amount: string;\n source_currency: string;\n credited_amount: string;\n credited_currency: string;\n /** Provider rate before spread (credited units per 1 source unit). */\n rate: string;\n spread_bps: number;\n provider: string;\n expires_at: string;\n}\n\nexport interface Deposit {\n id: string;\n user_id: string;\n /** Slug of the funder that handled this deposit, as configured by the deployment. */\n connector_slug: string;\n /** The connector's own reference, populated once it responds. */\n provider_reference: string | null;\n status: DepositStatus;\n /** Decimal serialised as a string to avoid float drift. */\n amount: string;\n currency: string;\n method: DepositMethod;\n /** Present when `status === \"redirect_required\"` — send the user here. */\n redirect_url: string | null;\n failure_reason: string | null;\n /** Final settled amount once confirmed (may differ from `amount` on FX). */\n confirmed_amount: string | null;\n confirmed_at: string | null;\n /** Set on cross-currency deposits: the quote this deposit executed against. */\n quote_id?: string | null;\n /** Locked provider rate (credited units per 1 source unit). */\n fx_rate?: string | null;\n fx_spread_bps?: number | null;\n /** The wallet's local currency the deposit converted into. */\n credited_currency?: string | null;\n /** What the wallet was actually credited, net of spread. */\n credited_amount?: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface InitiateDepositInput {\n /** Decimal as a string (`\"100.00\"`) — avoids float-precision loss on the wire. */\n amount: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n method: DepositMethod;\n /**\n * Optional. Slug of a specific funder to route through. Omit to\n * let the Takeal API pick the first active funder. Unknown slug → 400; empty\n * funder list → 503.\n */\n funder_slug?: string;\n /** Provider-specific extras. The mock funder reads `mock_scenario`. */\n metadata?: Record<string, string>;\n /** Structured billing details — real PSPs require these for 3DS / compliance. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original deposit; same key + different body returns 409. Supply a stable\n * UUID per logical attempt so a retried network call is safe.\n */\n idempotencyKey: string;\n /**\n * Required when `currency` differs from the wallet's local currency: a\n * fresh quote id from `quote()`. Cross-currency deposits without one are\n * rejected with 400; expired quotes with 409.\n */\n quote_id?: string;\n}\n\nexport interface CreateDepositRefundInput {\n /** Omit for a full refund of the original confirmed amount; same currency. */\n amount?: string;\n /** Human-readable reason, e.g. `\"customer_request\"`. */\n reason?: string;\n metadata?: Record<string, string>;\n /** Required. Replays are keyed on this. */\n idempotencyKey: string;\n}\n\n/** A refund row as the Takeal API returns it (`refunds` table, deposit-targeted). */\nexport interface Refund {\n id: string;\n target_type: string;\n deposit_id?: string;\n payment_id?: string;\n connector_slug: string;\n amount: string;\n currency: string;\n reason: string;\n status: string;\n provider_refund_reference?: string;\n failure_reason?: string;\n requestor_type: string;\n requestor_id: string;\n created_at: string;\n updated_at: string;\n}\n\nexport class DepositsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Initiate a top-up. Resolves to the freshly-created `Deposit`, whose\n * `status` may already be `confirmed` (synchronous rails / mock) or\n * `redirect_required` (3DS / APM — forward the user to `redirect_url`).\n */\n /**\n * Price a cross-currency deposit BEFORE paying. The rate is locked\n * server-side until `expires_at`; deposits in the local currency need no\n * quote (the API answers 400 `no_quote_needed`).\n */\n async quote(input: CreateQuoteInput): Promise<FundingQuote> {\n return this.http.post<FundingQuote>(\"/me/deposits/quotes\", { body: input });\n }\n\n async initiate(input: InitiateDepositInput): Promise<Deposit> {\n const { idempotencyKey, ...body } = input;\n return this.http.post<Deposit>(\"/me/deposits\", {\n body,\n idempotencyKey,\n });\n }\n\n /** Fetch one deposit by id — the poll target while a redirect resolves. */\n async get(id: string): Promise<Deposit> {\n return this.http.get<Deposit>(`/me/deposits/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's deposits, most recent first. */\n async list(): Promise<Deposit[]> {\n return this.http.get<Deposit[]>(\"/me/deposits\");\n }\n\n /**\n * Refund a previously-confirmed deposit. Synchronous when the\n * connector settles inline; otherwise the row stays `pending` and flips\n * later via the inbound `deposit.refunded` event.\n */\n async refund(\n depositId: string,\n input: CreateDepositRefundInput,\n ): Promise<Refund> {\n const { idempotencyKey, ...body } = input;\n return this.http.post<Refund>(\n `/me/deposits/${encodeURIComponent(depositId)}/refunds`,\n { body, idempotencyKey },\n );\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\n\n/**\n * Cards resource — `client.cards.*`.\n *\n * The end-user \"money OUT\" surface: a user issues themselves a card backed by\n * their wallet balance via an issuer connector. Mirrors the Takeal API's\n * `/me/cards` routes:\n *\n * GET /me/card-products → listProducts (the catalog)\n * GET /me/card-products/{id} → getProduct\n * POST /me/cards → create\n * GET /me/cards → list (most recent first)\n * GET /me/cards/{id} → get\n * PATCH /me/cards/{id} → update (name, design)\n * GET /me/cards/{id}/balance → balance (prepaid remaining)\n * POST /me/cards/{id}/freeze → freeze\n * POST /me/cards/{id}/unfreeze → unfreeze\n * POST /me/cards/{id}/terminate → terminate (one-way)\n *\n * The lifecycle actions are ownership-gated server-side: a caller can only\n * freeze / unfreeze / terminate a card that belongs to them (else 404).\n *\n * ## What is intentionally NOT here\n *\n * Card-data reveal (PAN / CVV) is a separate, security-sensitive flow with its\n * own re-auth + rate-limit + audit contract and is intentionally\n * NOT part of this resource (tracked separately).\n *\n * Today only PREPAID is wired end-to-end; CREDIT and GIFT return 400 from\n * the Takeal API until their issuer flows land.\n */\n\n/** Card product. Only `prepaid` is fully implemented today. */\nexport type CardType = \"credit\" | \"prepaid\" | \"gift\";\n\n/**\n * Card lifecycle state.\n *\n * `pending_payment` is a transient state: the row exists but the\n * per-card issuance-fee debit has not yet succeeded; such cards have no\n * provider reference and no user-visible side effects.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"active\"\n | \"frozen\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * A card design: the artwork a card is shown with. `image_url` is either an\n * absolute URL or a path relative to the API origin (the deployment's default\n * design is `/card-designs/default.svg`) — pass it through\n * `client.assetUrl()` before rendering. `id` is `null` for the deployment\n * default, which is rendered from the branding settings.\n */\nexport interface CardDesignRef {\n id: string | null;\n name?: string;\n image_url: string;\n}\n\n/**\n * What issuing a card costs the caller. `amount` is the price after the\n * user's subscription discount; `base_amount` is the list price and\n * `discount_bps` the discount in basis points (1000 = 10 %). `label` is the\n * operator's wording for the fee line (\"Card issuance\").\n */\nexport interface CardProductPrice {\n amount: string;\n currency: string;\n label: string;\n base_amount: string;\n discount_bps: number;\n}\n\n/**\n * A card the user can order, as listed by `GET /me/card-products`. The id is\n * opaque — it names a product, never a provider. `designs` is the set the\n * user may pick from (may be empty when only the default applies); `design`\n * is what the card gets when no choice is made. `price` is `null` for a\n * free card. `features` is an operator-defined object (scheme, wallet\n * support, load limits, …) with no fixed keys.\n */\nexport interface CardProduct {\n id: string;\n name: string;\n description: string | null;\n card_type: CardType;\n currency: string | null;\n features: Record<string, unknown>;\n design: CardDesignRef;\n designs: CardDesignRef[];\n price: CardProductPrice | null;\n /** True for the product the deployment issues when none is chosen. */\n is_default: boolean;\n}\n\n/**\n * A card record as the Takeal API returns it. Mirrors the `cards` table. Note the\n * SDK never receives the full PAN or CVV here — only `last4` + expiry. The\n * gift-card `redemption_code` is returned exactly once (on create) and\n * scrubbed from subsequent list/get responses.\n */\nexport interface Card {\n id: string;\n user_id: string;\n card_type: CardType;\n /** Slug of the issuer that minted this card, as configured by the deployment. */\n connector_slug: string;\n /** The connector's own reference, populated once it responds. */\n provider_reference: string | null;\n status: CardStatus;\n /** Last four digits of the PAN — safe to display. */\n last4: string | null;\n expiry_month: number | null;\n expiry_year: number | null;\n /** Gift cards only, present once on create then scrubbed. */\n redemption_code?: string;\n /** Decimal as a string. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n /** The name the user gave the card, or `null`. */\n name: string | null;\n /** The artwork the card is shown with. Always present. */\n design: CardDesignRef;\n /** The product the card was issued from; `null` for cards issued without one. */\n product: { id: string; name: string } | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface CreateCardInput {\n /**\n * A product id from {@link CardsResource.listProducts}. Sent as\n * `product_id`. When given, `type` and `issuer_slug` may be omitted; when\n * both are given they must agree with the product (400 `product_mismatch`).\n * Unknown, disabled or hidden product → 400 `unknown_product`.\n */\n productId?: string;\n /** A name for the card, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * One of the product's `designs`. Sent as `design_id`. `null` or omitted\n * picks the product's default design; a design outside the product's set →\n * 400 `design_not_allowed`.\n */\n designId?: string | null;\n /**\n * `prepaid` (the only fully-wired type today), `credit`, or `gift`.\n * Optional when `productId` is given, required otherwise.\n */\n type?: CardType;\n /** Decimal as a string. The prepaid load amount drained from wallet balance. */\n initial_amount?: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n /**\n * Optional. Slug of a specific issuer to mint with. Omit to let\n * the Takeal API pick the first active issuer. Unknown slug → 400; empty issuer\n * list → 503.\n */\n issuer_slug?: string;\n metadata?: Record<string, string>;\n /** Structured billing details — real issuers require these for 3DS / KYC. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original card; same key + different body returns 409.\n */\n idempotencyKey: string;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n}\n\n/** Fields a user can change on their own card. Omitted fields are left as they are. */\nexport interface UpdateCardInput {\n /** New name, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * New design (one of the product's `designs`), or `null` for the product's\n * default. Sent as `design_id`.\n */\n designId?: string | null;\n}\n\n/** Re-auth gate for {@link CardsResource.reveal}. */\nexport interface RevealCardInput {\n /** The user's account password — mandatory re-auth. */\n password: string;\n /** TOTP code; required only when the user has TOTP enrolled. */\n totpCode?: string;\n}\n\n/**\n * Full card data from a successful reveal. **Security**: never persist this —\n * keep it in volatile memory only, clear it within `expires_in_seconds`, and\n * never write it to localStorage / logs (the API marks the response no-store).\n */\nexport interface RevealedCard {\n pan: string;\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n}\n\nexport class CardsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Issue a card backed by the user's wallet balance. Resolves to the new\n * `Card`. On a ledger failure after provider creation, the Takeal API rolls the row\n * to `failed` (never an orphaned active card); inspect `status` /\n * `failure_reason` on the result.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, productId, name, designId, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (productId !== undefined) body[\"product_id\"] = productId;\n if (name !== undefined) body[\"name\"] = name;\n if (designId !== undefined) body[\"design_id\"] = designId;\n return this.http.post<Card>(\"/me/cards\", {\n body,\n idempotencyKey,\n });\n }\n\n /**\n * The cards the caller can order, in the order the deployment offers them\n * (the default product first). Each item carries its name, description,\n * artwork, the issuance price after the caller's subscription discount,\n * and the currency. Pass an item's `id` as `productId` to {@link create}.\n */\n async listProducts(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/me/card-products\");\n }\n\n /** One product from the catalog. 404 when unknown, disabled or hidden. */\n async getProduct(id: string): Promise<CardProduct> {\n return this.http.get<CardProduct>(\n `/me/card-products/${encodeURIComponent(id)}`,\n );\n }\n\n /**\n * Rename the caller's own card or change its design. Resolves to the\n * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /\n * `design_not_allowed` on a bad value.\n */\n async update(id: string, input: UpdateCardInput): Promise<Card> {\n const body: Record<string, unknown> = {};\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n return this.http.patch<Card>(`/me/cards/${encodeURIComponent(id)}`, {\n body,\n });\n }\n\n /** Fetch one card by id. */\n async get(id: string): Promise<Card> {\n return this.http.get<Card>(`/me/cards/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's cards, most recent first. */\n async list(): Promise<Card[]> {\n return this.http.get<Card[]>(\"/me/cards\");\n }\n\n /**\n * Remaining balance of a prepaid card. `currency` is required by the Takeal API and\n * forwarded as a query param.\n */\n async balance(id: string, currency: string): Promise<CardBalance> {\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<CardBalance>(\n `/me/cards/${encodeURIComponent(id)}/balance?${q}`,\n );\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze}. The optional\n * `reason` is recorded on the audit trail. Resolves to the updated card.\n * 404 if the card isn't the caller's; 501 if the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/freeze`,\n { body: { reason } },\n );\n }\n\n /**\n * Reveal the FULL PAN + CVV for the caller's own card. Re-auth gated\n * (password, + TOTP when the user has it enrolled) and rate-limited\n * server-side. The Takeal API never persists this data and marks the\n * response no-store; the SDK returns it verbatim and holds nothing.\n *\n * **Consumer security duties** (the SDK can't enforce these for you):\n * keep the result in volatile memory only, never write it to\n * localStorage / logs, and clear it within `expires_in_seconds`.\n *\n * 401 bad re-auth · 403 not your card · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 provider error.\n */\n async reveal(id: string, input: RevealCardInput): Promise<RevealedCard> {\n return this.http.post<RevealedCard>(\n `/me/cards/${encodeURIComponent(id)}/reveal`,\n { body: { password: input.password, totp_code: input.totpCode } },\n );\n }\n\n /** Unfreeze a previously-frozen card. Idempotent on an already-active card. */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/unfreeze`,\n { body: {} },\n );\n }\n\n /**\n * Terminate the caller's own card. **One-way** — a terminated card cannot be\n * reactivated. The optional `reason` is audited. Idempotent on an\n * already-terminated card.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/terminate`,\n { body: { reason } },\n );\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Balance resource — `client.balance.*`.\n *\n * The user's wallet balance, tracked in the ledger. Mirrors the Takeal API's\n * `GET /me/balance[?currency=<code>]` route. Balances are per-currency; with\n * no `currency` the wallet's own currency is returned (see `client.wallet`).\n */\n\n/** Wallet balance for one currency. `amount` is a decimal string. */\nexport interface Balance {\n amount: string;\n currency: string;\n}\n\nexport class BalanceResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Fetch the user's wallet balance. Omit `currency` for the wallet's own\n * currency; pass an ISO 4217 code (e.g. `\"USD\"`) to read another one —\n * the ledger holds a separate balance per currency.\n */\n async get(currency?: string): Promise<Balance> {\n if (!currency) return this.http.get<Balance>(\"/me/balance\");\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<Balance>(`/me/balance?${q}`);\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Branding resource — `client.branding.*`.\n *\n * Runtime white-label config published by the deployment at `GET /branding`\n * (public, no auth). Lets a Cusfront re-theme itself on the fly — platform\n * name, logo, favicon, brand colours and the label used for the end-user's balance — without\n * a rebuild. Pairs with the build-time `BrandConfig`: the server-side values\n * win whenever both are present.\n */\n\n/** Public brand config of the deployment. All strings; empty = use the client default. */\nexport interface Branding {\n /** Platform display name (e.g. the white-label brand). */\n platform_name: string;\n /** Name of the merchant-facing portal. */\n merchant_portal_name: string;\n /** Logo image — absolute URL or `data:` URI. Empty → client default. */\n logo_url: string;\n /** Favicon — absolute URL or `data:` URI. Empty → client default. */\n favicon_url: string;\n /** User-facing name of the balance, e.g. `\"Wallet\"` or `\"Acme Wallet\"`.\n * Display-only: the `balance` API shape never changes with it. */\n wallet_label: string;\n /** Primary brand colour as `#rrggbb`. Empty → client default palette. */\n primary_color: string;\n /** Secondary brand colour as `#rrggbb`. Empty → client default palette. */\n secondary_color: string;\n /** Accent colour as `#rrggbb`. Empty → client default palette. */\n accent_color: string;\n}\n\nexport class BrandingResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Fetch the deployment's public brand config. Safe to call before login. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Branding> {\n return this.http.get<Branding>(\"/branding\", { skipAuth: true, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Wallet resource — `client.wallet.*`.\n *\n * Which currency the user's wallet is held in. Deposits in any other\n * currency are converted on funding (quote first, see `client.deposits`);\n * cards issued in another currency are paid from the wallet with an FX leg\n * at issuance. A user may switch currency only while every balance is zero\n * and only to a currency the deployment offers (`allowed`).\n */\n\n/** The user's wallet currency and what they may switch to. */\nexport interface Wallet {\n /** ISO 4217 code the wallet is held in. */\n currency: string;\n /** `true` when chosen by the user (or set by an operator), `false` when it\n * is the deployment default. */\n explicit: boolean;\n /** Currencies accepted by `set()`. */\n allowed: string[];\n}\n\nexport class WalletResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Current wallet currency + the currencies the user may switch to. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.get<Wallet>(\"/me/wallet\", { signal: opts.signal });\n }\n\n /**\n * Switch the wallet currency. Fails with `409 wallet_not_empty` while any\n * balance is non-zero, and `400 currency_not_allowed` for a currency the\n * deployment does not offer.\n */\n async set(currency: string, opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.put<Wallet>(\"/me/wallet\", { body: { currency }, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Blog resource — `client.blog.*`.\n *\n * Posts are public: these calls work before the user logs in, which is what\n * a marketing page or a Mini App landing screen needs.\n *\n * A post arrives as a **structured document**, not as HTML. `body_blocks` is\n * a flat list of typed nodes; map each `type` onto your own component and the\n * post inherits your site's styling. `body_markdown` is there too if you'd\n * rather run your own renderer.\n *\n * ```ts\n * const { posts } = await client.blog.list({ perPage: 5 });\n * const post = await client.blog.get(posts[0].slug);\n *\n * post.body_blocks.map((b) => {\n * switch (b.type) {\n * case \"heading\": return <Heading level={b.level}>{b.text}</Heading>;\n * case \"paragraph\": return <P>{b.text}</P>;\n * case \"image\": return <Figure src={b.url} alt={b.alt} caption={b.caption} />;\n * case \"list\": return <List ordered={b.ordered} items={b.items} />;\n * case \"quote\": return <Quote>{b.text}</Quote>;\n * case \"code\": return <Code lang={b.lang}>{b.text}</Code>;\n * case \"divider\": return <Hr />;\n * }\n * });\n * ```\n *\n * Inline emphasis (`**bold**`, `[link](url)`) is left as Markdown inside\n * block text — every renderer already knows what to do with it.\n */\n\n/** One node of a post body. Discriminated on `type`. */\nexport type BlogBlock =\n | { type: \"heading\"; level: number; text: string }\n | { type: \"paragraph\"; text: string }\n | { type: \"image\"; url: string; alt?: string; caption?: string }\n | { type: \"list\"; ordered: boolean; items: string[] }\n | { type: \"quote\"; text: string }\n | { type: \"code\"; lang?: string; text: string }\n | { type: \"divider\" };\n\nexport interface BlogPost {\n /** Stable public key — link by this. */\n slug: string;\n title: string;\n /** Teaser for cards; falls back to the first paragraph. */\n excerpt: string;\n /** Image URL, relative to the API origin. Absent when no cover is set. */\n cover_url?: string;\n /** Raw Markdown, for consumers that bring their own renderer. */\n body_markdown: string;\n /** The recommended input for rendering — see the module docs. */\n body_blocks: BlogBlock[];\n tags: string[];\n /** Present only when the post declares one. */\n locale?: string;\n /** Rough read time in minutes (minimum 1). */\n reading_minutes: number;\n published_at: string | null;\n updated_at: string;\n}\n\nexport interface BlogListInput {\n /** 1-based. Default 1. */\n page?: number;\n /** 1..=50. Default 10. */\n perPage?: number;\n /** Only posts carrying this tag. */\n tag?: string;\n /** Only posts in this locale. */\n locale?: string;\n}\n\nexport interface BlogList {\n posts: BlogPost[];\n total: number;\n page: number;\n per_page: number;\n}\n\nexport class BlogResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Published posts, newest first. No authentication required. */\n async list(input: BlogListInput = {}): Promise<BlogList> {\n const q = new URLSearchParams();\n if (input.page) q.set(\"page\", String(input.page));\n if (input.perPage) q.set(\"per_page\", String(input.perPage));\n if (input.tag) q.set(\"tag\", input.tag);\n if (input.locale) q.set(\"locale\", input.locale);\n const qs = q.toString();\n return this.http.get<BlogList>(`/blog/posts${qs ? `?${qs}` : \"\"}`, {\n skipAuth: true,\n });\n }\n\n /** One post by slug. No authentication required. */\n async get(slug: string): Promise<BlogPost> {\n return this.http.get<BlogPost>(`/blog/posts/${encodeURIComponent(slug)}`, {\n skipAuth: true,\n });\n }\n\n /**\n * Absolute URL for an image path returned inside a post (`cover_url`, or an\n * image block's `url`). Handy when the app renders on a different origin\n * than the API.\n */\n imageUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Subscriptions resource — `client.subscriptions.*`.\n *\n * Which channels the signed-in user agreed to receive announcements on.\n * `available` tells you which toggles to render: a deployment with no\n * Telegram bot configured can't deliver there, so offering the switch would\n * be a lie.\n *\n * ```ts\n * const { channels, available } = await client.subscriptions.get();\n * await client.subscriptions.set([...channels, \"telegram\"]);\n * ```\n *\n * Unrelated to paid/VIP tiers — this is only about announcements.\n *\n * @deprecated Announcements are now the `marketing` category of the\n * notification preferences. Read them with\n * `client.notifications.getPreferences()` and change them with\n * `client.notifications.setPreferences({ categories: { marketing: { email: true, telegram: false } } })`.\n * This endpoint keeps working as an alias over that setting.\n */\n\nexport type BroadcastChannel = \"email\" | \"telegram\" | (string & {});\n\nexport interface Subscriptions {\n /** Channels the user currently receives announcements on. */\n channels: BroadcastChannel[];\n /** Channels this deployment can actually deliver on. */\n available: BroadcastChannel[];\n}\n\n/** @deprecated See the note at the top of this module. */\nexport class SubscriptionsResource {\n constructor(private readonly http: HttpClient) {}\n\n async get(): Promise<Subscriptions> {\n return this.http.get<Subscriptions>(\"/me/subscriptions\");\n }\n\n /**\n * Replace the whole set — this is a PUT, not a merge. Pass `[]` to opt out\n * of everything.\n */\n async set(channels: BroadcastChannel[]): Promise<Subscriptions> {\n return this.http.put<Subscriptions>(\"/me/subscriptions\", {\n body: { channels },\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Sessions resource — `client.sessions.*`.\n *\n * Every device or browser the user is signed in on. Lets a settings screen\n * show \"where you're signed in\" and sign one or all of them out.\n *\n * ```ts\n * const sessions = await client.sessions.list();\n * const others = sessions.filter((s) => !s.current);\n * await client.sessions.revokeOthers();\n * ```\n */\n\nexport interface UserSession {\n /** Session id; pass it to `revoke`. */\n jti: string;\n issued_at: string;\n expires_at: string;\n last_seen_at: string;\n /** Client IP recorded for the session, if known. */\n remote_ip?: string | null;\n /** Browser or app that opened the session, if known. */\n user_agent?: string | null;\n /** `true` for the session this client is using. */\n current: boolean;\n}\n\nexport class SessionsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** All live sessions of the account, this one included. */\n async list(): Promise<UserSession[]> {\n return this.http.get<UserSession[]>(\"/me/sessions\");\n }\n\n /** Sign out one session. Works on the current one too; the stored JWT\n * stops working, so follow with `client.auth.signOut()`.\n * 404 when the session is unknown or already signed out. */\n async revoke(jti: string): Promise<void> {\n await this.http.delete<void>(`/me/sessions/${encodeURIComponent(jti)}`);\n }\n\n /** Sign out every session except this one. */\n async revokeOthers(): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/me/sessions/terminate-others\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Push resource — `client.push.*`.\n *\n * Web Push for the signed-in user, through the older single-subscription\n * endpoint. The API now keeps one device per browser (see\n * `client.devices`), and this endpoint is an alias over the Web Push\n * devices: it keeps working, but new code should call\n * `client.devices.registerWebPush(reg)` / `unregisterWebPush(reg)` instead.\n *\n * Your service worker shows the notification: the payload is JSON with\n * `title`, `body` and `url` (where a click should lead).\n */\n\nexport interface PushStatus {\n /** `true` when a subscription is stored for this user. */\n subscribed: boolean;\n /** Host of the stored endpoint, e.g. `fcm.googleapis.com`. */\n endpoint_host?: string | null;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`.\n * `null` when push is not set up on this deployment. */\n vapid_public_key?: string | null;\n}\n\nexport interface PushSubscriptionInput {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** The part of `ServiceWorkerRegistration` the SDK needs. Typed\n * structurally so the core stays free of DOM lib types. */\nexport interface PushCapableRegistration {\n pushManager: {\n getSubscription(): Promise<{ unsubscribe(): Promise<boolean> } | null>;\n subscribe(options: {\n userVisibleOnly: boolean;\n applicationServerKey: Uint8Array;\n }): Promise<{ toJSON(): { endpoint?: string; keys?: Record<string, string> } }>;\n };\n}\n\nexport class PushResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Whether the user is subscribed, plus the VAPID key to subscribe with. */\n async status(): Promise<PushStatus> {\n return this.http.get<PushStatus>(\"/me/push-subscription\");\n }\n\n /** Store a subscription you created yourself.\n * 409 `push_disabled` when the deployment has no VAPID keys.\n * @deprecated Use `client.devices.register({ kind: \"webpush\", ... })`. */\n async save(input: PushSubscriptionInput): Promise<PushStatus> {\n return this.http.put<PushStatus>(\"/me/push-subscription\", { body: input });\n }\n\n /** Delete the stored subscription. Safe when nothing is stored.\n * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */\n async remove(): Promise<void> {\n await this.http.delete<void>(\"/me/push-subscription\");\n }\n\n /** Subscribe this browser and store the subscription. Ask for\n * notification permission before calling. Throws when push isn't set up\n * on the deployment.\n * @deprecated Use `client.devices.registerWebPush(registration)`. */\n async enable(registration: PushCapableRegistration): Promise<PushStatus> {\n const { vapid_public_key } = await this.status();\n if (!vapid_public_key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(vapid_public_key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.save({\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n });\n }\n\n /** Unsubscribe this browser and delete the stored subscription.\n * @deprecated Use `client.devices.unregisterWebPush(registration)`. */\n async disable(registration: PushCapableRegistration): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n await this.remove();\n }\n}\n\n/** URL-safe base64 (padding optional) → bytes. */\nexport function base64UrlToBytes(input: string): Uint8Array {\n const b64 = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = b64 + \"=\".repeat((4 - (b64.length % 4)) % 4);\n const bin = atob(padded);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { User } from \"./auth.js\";\n\n/**\n * Me resource — `client.me.*`.\n *\n * Profile-level actions for the signed-in user that don't belong to another\n * resource. Today: the Telegram link.\n *\n * ```ts\n * // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):\n * const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);\n * me.telegram; // { username, linked_at }\n *\n * // From a settings screen:\n * await client.me.unlinkTelegram();\n * ```\n */\nexport class MeResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Attach the Telegram account behind `initData` to the signed-in user.\n * Returns the updated user (`telegram` is set). Repeating the call with\n * the same Telegram is fine.\n *\n * Errors: 401 `invalid_init_data`; 403 `user_disabled` /\n * `second_factor_required`; 409 `telegram_already_linked_other` (the\n * account already has a different Telegram; `unlinkTelegram` first) /\n * `telegram_in_use` (that Telegram belongs to another account); 503\n * `telegram_not_configured`. */\n async linkTelegram(initData: string): Promise<User> {\n return this.http.post<User>(\"/me/telegram\", { body: { init_data: initData } });\n }\n\n /** Detach the Telegram account from the signed-in user. Returns the\n * updated user (`telegram` is `null`).\n *\n * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the\n * account has no password, so Telegram is its only way to sign in. */\n async unlinkTelegram(): Promise<User> {\n return this.http.delete<User>(\"/me/telegram\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Notifications resource — `client.notifications.*`.\n *\n * Every notification a user gets is also kept server-side as an inbox item,\n * whatever else was sent (a push, a Telegram message, an email). The inbox\n * is what the app shows; the other channels are the nudge to open it.\n *\n * ```ts\n * const page = await client.notifications.list({ limit: 20 });\n * for (const item of page.items) {\n * render(item.title, item.body, item.href); // href: a path inside your app, or null\n * }\n * await client.notifications.markRead(page.items[0].id);\n * ```\n *\n * Preferences decide where the nudge goes: a primary channel (or automatic\n * when `null`), per-category switches, and the user's language.\n */\n\n/** What an item is about. `security` and `money` can't be switched off\n * completely; `marketing` is off until the user opts in. */\nexport type NotificationCategory = \"money\" | \"card\" | \"security\" | \"account\" | \"marketing\";\n\n/** A way to reach the user outside the inbox. */\nexport type NotificationChannel = \"push\" | \"telegram\" | \"email\" | \"sms\";\n\n/** Language the user reads notifications in. */\nexport type NotificationLocale = \"en\" | \"ru\" | (string & {});\n\nexport interface InboxItem {\n id: string;\n /** What happened, e.g. `deposit_confirmed`, `card_transaction`, `login_new_device`. */\n event_type: string;\n category: NotificationCategory;\n title: string;\n body: string;\n /** A path inside the client app to open on tap (`/cards/<id>`,\n * `/deposits/<id>`, `/subscription`, `/settings/sessions`), or `null`. */\n href: string | null;\n /** Event details (amount, currency, card last four and so on); the keys\n * depend on `event_type`. */\n data: Record<string, unknown>;\n /** Language the item was rendered in. */\n locale: string;\n /** When the user read it, or `null` while unread. */\n read_at: string | null;\n created_at: string;\n}\n\nexport interface NotificationPage {\n /** Newest first. */\n items: InboxItem[];\n /** Pass back as `cursor` to get the next page; `null` on the last one. */\n next_cursor: string | null;\n /** Unread items across the whole inbox, not just this page. */\n unread_count: number;\n}\n\nexport interface ListNotificationsParams {\n /** `next_cursor` from the previous page. */\n cursor?: string;\n /** Page size; the server caps it. */\n limit?: number;\n /** Only items without `read_at`. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n}\n\n/** Per-category channel switches: `{ money: { push: true, email: false } }`.\n * A channel missing from a category keeps its default. */\nexport type NotificationCategoryPreferences = Partial<\n Record<NotificationCategory, Partial<Record<NotificationChannel, boolean>>>\n>;\n\nexport interface NotificationPreferences {\n /** The channel to use first; `null` means automatic (the server picks by\n * the user's devices). */\n primary_channel: NotificationChannel | null;\n categories: NotificationCategoryPreferences;\n /** `null` when unset: the server falls back to the Telegram profile's\n * language, then the deployment default. */\n locale: NotificationLocale | null;\n /** Channels this deployment can deliver on. Render toggles only for\n * these. */\n available_channels: NotificationChannel[];\n}\n\n/** Body of `setPreferences`. Every field is optional; only the given ones\n * change. `primary_channel: null` switches back to automatic. */\nexport interface NotificationPreferencesInput {\n primary_channel?: NotificationChannel | null;\n categories?: NotificationCategoryPreferences;\n locale?: NotificationLocale | null;\n}\n\nexport class NotificationsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** One page of the inbox, newest first. */\n async list(params: ListNotificationsParams = {}): Promise<NotificationPage> {\n const q = new URLSearchParams();\n if (params.cursor) q.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n if (params.unreadOnly) q.set(\"unread\", \"true\");\n if (params.category) q.set(\"category\", params.category);\n const qs = q.toString();\n return this.http.get<NotificationPage>(`/me/notifications${qs ? `?${qs}` : \"\"}`);\n }\n\n /** How many items are unread. Cheap; fine to poll for a badge. */\n async unreadCount(): Promise<number> {\n const { unread } = await this.http.get<{ unread: number }>(\"/me/notifications/unread-count\");\n return unread;\n }\n\n /** Mark one item read. Returns the item; calling it again is harmless. */\n async markRead(id: string): Promise<InboxItem> {\n return this.http.post<InboxItem>(`/me/notifications/${encodeURIComponent(id)}/read`);\n }\n\n /** Mark every unread item read, or only those created before `before`\n * (ISO timestamp). Returns how many changed. */\n async markAllRead(before?: string): Promise<{ marked: number }> {\n return this.http.post<{ marked: number }>(\"/me/notifications/read-all\", {\n body: before ? { before } : {},\n });\n }\n\n /** Delete one item. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/notifications/${encodeURIComponent(id)}`);\n }\n\n /** The user's channel and language settings. */\n async getPreferences(): Promise<NotificationPreferences> {\n return this.http.get<NotificationPreferences>(\"/me/notification-preferences\");\n }\n\n /** Change some settings; the rest stay. Returns the stored view.\n * 400 `validation` for an unknown category, channel or locale. */\n async setPreferences(input: NotificationPreferencesInput): Promise<NotificationPreferences> {\n return this.http.put<NotificationPreferences>(\"/me/notification-preferences\", {\n body: input,\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { ClientPlatform, ResolvedClientDescriptor } from \"../client-platform.js\";\nimport { base64UrlToBytes, type PushCapableRegistration } from \"./push.js\";\n\n/**\n * Devices resource — `client.devices.*`.\n *\n * A user has many devices: each browser with a Web Push subscription, each\n * phone with an FCM / APNs token, and a marker for \"uses the Telegram Mini\n * App\". The server picks the notification channel from them: a mobile app\n * first, otherwise the device seen most recently.\n *\n * The usual browser flow, once notification permission is granted:\n *\n * ```ts\n * const reg = await navigator.serviceWorker.ready;\n * const device = await client.devices.registerWebPush(reg, { label: \"Chrome on Mac\" });\n * // later, from a settings screen:\n * await client.devices.unregisterWebPush(reg);\n * ```\n */\n\nexport type DeviceKind = \"webpush\" | \"fcm\" | \"apns\" | \"telegram_miniapp\";\n\nexport type DevicePlatform = \"pwa\" | \"web\" | \"ios\" | \"android\" | \"telegram\";\n\nexport interface Device {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** Free-form name the app gave it (\"Chrome on Mac\"), or `null`. */\n label: string | null;\n locale: string | null;\n app_version: string | null;\n created_at: string;\n last_seen_at: string;\n /** Set when the device no longer receives anything (the push endpoint is\n * gone, or someone switched it off). */\n disabled_at: string | null;\n /** `true` when it was registered from the session this client holds. */\n is_current: boolean;\n}\n\n/** `PushSubscription.toJSON()` minus the parts the server doesn't need. */\nexport interface WebPushCredential {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** FCM registration token or APNs device token. */\nexport interface MobilePushCredential {\n token: string;\n}\n\nexport type RegisterDeviceInput =\n | {\n kind: \"webpush\";\n platform: DevicePlatform;\n credential: WebPushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"fcm\" | \"apns\";\n platform: DevicePlatform;\n credential: MobilePushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"telegram_miniapp\";\n platform: DevicePlatform;\n /** Nothing to send: the device is a marker. */\n credential: Record<string, never>;\n label?: string;\n locale?: string;\n app_version?: string;\n };\n\nexport interface RegisteredDevice {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`;\n * `null` when push is not set up on this deployment. */\n vapid_public_key: string | null;\n}\n\nexport interface RegisterWebPushOptions {\n /** A name to show in the user's device list (\"Chrome on Mac\"). */\n label?: string;\n /** Skip the key lookup when you already hold the deployment's VAPID\n * public key (from an earlier `register` result, for example). */\n vapidPublicKey?: string;\n}\n\nexport interface UnregisterWebPushOptions {\n /** The device to delete, from an earlier `registerWebPush` result. When\n * omitted, every Web Push device registered from this session goes. */\n deviceId?: string;\n}\n\n/** Client platform → the platform the device list uses. */\nexport function devicePlatformOf(platform: ClientPlatform): DevicePlatform {\n return platform === \"telegram-miniapp\" ? \"telegram\" : platform;\n}\n\nexport class DevicesResource {\n constructor(\n private readonly http: HttpClient,\n private readonly client: ResolvedClientDescriptor,\n ) {}\n\n /** Every device the user has, disabled ones included. */\n async list(): Promise<Device[]> {\n return this.http.get<Device[]>(\"/me/devices\");\n }\n\n /** Register a device, or refresh it when the same credential is already\n * known (then `last_seen_at`, `label` and `app_version` update and a\n * disabled device comes back). `app_version` defaults to the client\n * version sent in `X-Takeal-Client`.\n *\n * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the\n * deployment has no VAPID keys. */\n async register(input: RegisterDeviceInput): Promise<RegisteredDevice> {\n return this.http.put<RegisteredDevice>(\"/me/devices\", {\n body: { app_version: this.client.version, ...input },\n });\n }\n\n /** Delete one device. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/devices/${encodeURIComponent(id)}`);\n }\n\n /** Subscribe this browser to Web Push and register it as a device. Ask\n * for notification permission before calling. Throws when push isn't\n * set up on the deployment. */\n async registerWebPush(\n registration: PushCapableRegistration,\n opts: RegisterWebPushOptions = {},\n ): Promise<RegisteredDevice> {\n const key = opts.vapidPublicKey ?? (await this.vapidPublicKey());\n if (!key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.register({\n kind: \"webpush\",\n platform: devicePlatformOf(this.client.platform),\n credential: {\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n },\n ...(opts.label ? { label: opts.label } : {}),\n });\n }\n\n /** Unsubscribe this browser from Web Push and delete the matching device\n * (see {@link UnregisterWebPushOptions}). Safe when nothing is\n * registered. */\n async unregisterWebPush(\n registration: PushCapableRegistration,\n opts: UnregisterWebPushOptions = {},\n ): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n if (opts.deviceId) {\n await this.remove(opts.deviceId);\n return;\n }\n const mine = (await this.list()).filter((d) => d.kind === \"webpush\" && d.is_current);\n for (const d of mine) await this.remove(d.id);\n }\n\n private async vapidPublicKey(): Promise<string | null> {\n const { vapid_public_key } = await this.http.get<{ vapid_public_key?: string | null }>(\n \"/me/push-subscription\",\n );\n return vapid_public_key ?? null;\n }\n}\n","/**\n * The SDK's own version, sent as the default `X-Takeal-Client` version.\n *\n * Kept as a plain constant so every entry point (ESM, CJS, the\n * sub-exports) reads the same value without a JSON import or a bundler\n * `define`. `src/version.test.ts` checks it matches `package.json`, so a\n * release bump that forgets this file fails the test run.\n */\nexport const SDK_VERSION = \"0.3.0\";\n","import { SDK_VERSION } from \"./version.js\";\n\n/**\n * Which kind of app is talking to the API. Sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server keeps it on the\n * session: it decides whether a sign-in counts as a new device, and which\n * channel a notification goes out on (a Mini App gets Telegram messages, a\n * PWA gets Web Push, and so on).\n */\nexport type ClientPlatform = \"pwa\" | \"web\" | \"telegram-miniapp\" | \"ios\" | \"android\";\n\n/** The `client` option of `createClient`. */\nexport interface ClientDescriptor {\n /** What the app is. Detected at runtime when omitted; see\n * {@link detectClientPlatform}. */\n platform: ClientPlatform;\n /** The app's own version. Defaults to the SDK version. */\n version?: string;\n}\n\n/** A descriptor with every field filled in. `client.client` on a\n * {@link CusfrontClient} has this shape. */\nexport interface ResolvedClientDescriptor {\n platform: ClientPlatform;\n version: string;\n}\n\n/** Header name carrying the client descriptor. */\nexport const CLIENT_HEADER = \"X-Takeal-Client\";\n\n/**\n * Best-effort platform detection for browser runtimes:\n *\n * - `telegram-miniapp` when `window.Telegram.WebApp.initData` is non-empty\n * (the app was launched from Telegram);\n * - `pwa` when the page runs installed: iOS Safari's `navigator.standalone`\n * or a `display-mode: standalone` media query;\n * - `web` otherwise, and always outside a browser (Node, workers without a\n * `navigator`).\n *\n * Native wrappers (Capacitor, React Native) should pass `ios` / `android`\n * explicitly; there is no reliable way to tell them apart from a browser.\n */\nexport function detectClientPlatform(): ClientPlatform {\n const g = globalThis as unknown as {\n Telegram?: { WebApp?: { initData?: unknown } };\n navigator?: { standalone?: unknown };\n matchMedia?: (query: string) => { matches: boolean };\n };\n const initData = g.Telegram?.WebApp?.initData;\n if (typeof initData === \"string\" && initData.length > 0) return \"telegram-miniapp\";\n\n if (g.navigator?.standalone === true) return \"pwa\";\n if (typeof g.matchMedia === \"function\") {\n try {\n if (g.matchMedia(\"(display-mode: standalone)\").matches) return \"pwa\";\n } catch {\n // Some non-browser runtimes stub matchMedia and throw; treat as web.\n }\n }\n return \"web\";\n}\n\n/** Fill in the blanks of a `client` option. */\nexport function resolveClientDescriptor(\n given: ClientDescriptor | undefined,\n): ResolvedClientDescriptor {\n return {\n platform: given?.platform ?? detectClientPlatform(),\n version: given?.version || SDK_VERSION,\n };\n}\n\n/** `{ platform: \"pwa\", version: \"0.3.0\" }` → `\"pwa; 0.3.0\"`. */\nexport function clientHeaderValue(desc: ResolvedClientDescriptor): string {\n return `${desc.platform}; ${desc.version}`;\n}\n","/**\n * Pluggable storage for the JWT.\n *\n * Default behaviour by environment:\n * - browser → `localStorage` (synchronous, persists across reloads)\n * - Node / SSR / worker → in-memory (no global state to leak)\n * - mobile (Capacitor / RN) → consumer must inject Keychain /\n * EncryptedSharedPreferences via `createClient({ tokenStore })`\n *\n * The store is intentionally tiny — three methods, no eviction\n * policy, no encryption. Encryption is the consumer's call (mobile\n * adapters wrap platform-native secure storage). Persistence shape\n * is opaque to the SDK; tokens are passed through verbatim.\n */\nexport interface TokenStore {\n get(): string | null | Promise<string | null>;\n set(token: string): void | Promise<void>;\n clear(): void | Promise<void>;\n}\n\n/** Sync `localStorage`-backed store. Falls through to in-memory when\n * `window.localStorage` is unavailable (private mode quota, SSR). */\nexport function defaultBrowserStore(key = \"takeal_jwt\"): TokenStore {\n const fallback = inMemoryStore();\n // Probe once at construction — avoid the try/catch on every call.\n let usable = false;\n try {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n const probe = \"__takeal_probe__\";\n ls.setItem(probe, \"1\");\n ls.removeItem(probe);\n usable = true;\n }\n } catch {\n usable = false;\n }\n if (!usable) return fallback;\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n return {\n get: () => ls.getItem(key),\n set: (token) => ls.setItem(key, token),\n clear: () => ls.removeItem(key),\n };\n}\n\n/** In-memory store. Use for SSR / tests / when persistence isn't\n * desired (e.g. ephemeral kiosk sessions). */\nexport function inMemoryStore(): TokenStore {\n let value: string | null = null;\n return {\n get: () => value,\n set: (token) => {\n value = token;\n },\n clear: () => {\n value = null;\n },\n };\n}\n","/**\n * Resolve an image URL the API hands back (`design.image_url`, a logo, …)\n * into something a browser can load.\n *\n * The API returns either an absolute URL (uploaded artwork served from\n * object storage) or a path relative to the API origin (the deployment's\n * default card design, `/card-designs/default.svg`). Absolute URLs — and\n * `data:` / `blob:` URIs — come back unchanged; a relative path is joined\n * onto `baseUrl`, which is the bare API origin the client was built with.\n * These paths are host-level, so no `/v1` prefix is added.\n *\n * `baseUrl` is the same value passed to `createClient`; a trailing slash is\n * tolerated. `client.assetUrl()` calls this with the client's own base.\n */\nexport function resolveAssetUrl(baseUrl: string, url: string): string {\n if (isAbsolute(url)) return url;\n const base = baseUrl.replace(/\\/+$/, \"\");\n const path = url.startsWith(\"/\") ? url : `/${url}`;\n return `${base}${path}`;\n}\n\n/** `https://…`, `http://…`, protocol-relative `//…`, `data:` and `blob:` all count as absolute. */\nfunction isAbsolute(url: string): boolean {\n return /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(url);\n}\n","/**\n * `@takeal/cusfront-sdk` — typed client for the Takeal end-user API.\n *\n * Entry point: `createClient({ baseUrl, brand?, client?, tokenStore?, fetch? })`.\n * Resources are accessed off the returned client (`client.auth.login`,\n * `client.cards.list`, …). Sub-exports under `@takeal/cusfront-sdk/<resource>`\n * publish each resource independently so a Cusfront only pulls what\n * it imports.\n *\n * Brand-neutral by design. No customer / deployment names embedded.\n * Brand swap happens at runtime via `BrandConfig`.\n */\n\nimport { HttpClient, type FetchLike } from \"./http.js\";\nimport { AuthResource } from \"./resources/auth.js\";\nimport { DepositsResource } from \"./resources/deposits.js\";\nimport { CardsResource } from \"./resources/cards.js\";\nimport { BalanceResource } from \"./resources/balance.js\";\nimport { BrandingResource } from \"./resources/branding.js\";\nimport { WalletResource } from \"./resources/wallet.js\";\nimport { BlogResource } from \"./resources/blog.js\";\nimport { SubscriptionsResource } from \"./resources/subscriptions.js\";\nimport { SessionsResource } from \"./resources/sessions.js\";\nimport { PushResource } from \"./resources/push.js\";\nimport { MeResource } from \"./resources/me.js\";\nimport { NotificationsResource } from \"./resources/notifications.js\";\nimport { DevicesResource } from \"./resources/devices.js\";\nimport {\n CLIENT_HEADER,\n clientHeaderValue,\n resolveClientDescriptor,\n type ClientDescriptor,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\nimport {\n defaultBrowserStore,\n inMemoryStore,\n type TokenStore,\n} from \"./token-store.js\";\nimport type { BrandConfig } from \"./brand.js\";\nimport { resolveAssetUrl } from \"./assets.js\";\n\nexport type { BrandConfig } from \"./brand.js\";\nexport { resolveAssetUrl } from \"./assets.js\";\nexport { ApiError, NetworkError, isApiError, isNetworkError } from \"./error.js\";\nexport { defaultBrowserStore, inMemoryStore, type TokenStore } from \"./token-store.js\";\nexport { SDK_VERSION } from \"./version.js\";\nexport {\n CLIENT_HEADER,\n detectClientPlatform,\n type ClientDescriptor,\n type ClientPlatform,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\n\n// Re-export resource types so consumers can `import { Deposit } from\n// \"@takeal/cusfront-sdk\"` without reaching into sub-paths.\nexport type { Address, CustomerInfo } from \"./types/customer.js\";\nexport type {\n Deposit,\n DepositStatus,\n DepositMethod,\n InitiateDepositInput,\n CreateDepositRefundInput,\n Refund,\n CreateQuoteInput, FundingQuote } from \"./resources/deposits.js\";\nexport type {\n Card,\n CardType,\n CardStatus,\n CardDesignRef,\n CardProduct,\n CardProductPrice,\n CreateCardInput,\n UpdateCardInput,\n CardBalance,\n RevealCardInput,\n RevealedCard,\n} from \"./resources/cards.js\";\nexport type { Balance } from \"./resources/balance.js\";\nexport type { Branding } from \"./resources/branding.js\";\nexport type { Wallet } from \"./resources/wallet.js\";\nexport type { BlogPost, BlogBlock, BlogList, BlogListInput } from \"./resources/blog.js\";\nexport type {\n Subscriptions,\n BroadcastChannel,\n} from \"./resources/subscriptions.js\";\nexport type {\n User,\n LoginInput,\n LoginResponse,\n JwtIssued,\n TotpRequired,\n TotpSetupRequired,\n OtpSentResponse,\n RegisterInput,\n Session,\n TotpSetupComplete,\n ChangePasswordInput,\n TelegramLink,\n TelegramUnknown,\n ExchangeTelegramInput,\n LinkTelegramInput,\n} from \"./resources/auth.js\";\nexport type { MeResource } from \"./resources/me.js\";\nexport type { UserSession } from \"./resources/sessions.js\";\nexport type {\n PushStatus,\n PushSubscriptionInput,\n PushCapableRegistration,\n} from \"./resources/push.js\";\nexport type {\n NotificationCategory,\n NotificationChannel,\n NotificationLocale,\n InboxItem,\n NotificationPage,\n ListNotificationsParams,\n NotificationCategoryPreferences,\n NotificationPreferences,\n NotificationPreferencesInput,\n} from \"./resources/notifications.js\";\nexport type {\n DeviceKind,\n DevicePlatform,\n Device,\n WebPushCredential,\n MobilePushCredential,\n RegisterDeviceInput,\n RegisteredDevice,\n RegisterWebPushOptions,\n UnregisterWebPushOptions,\n} from \"./resources/devices.js\";\n\nexport interface CreateClientOptions {\n /** Absolute origin of the Takeal API deployment, no trailing slash.\n * e.g. `\"https://api.takeal.example.com\"`. */\n baseUrl: string;\n /** Runtime brand config. Optional; consumer renders its own brand\n * if omitted. */\n brand?: BrandConfig;\n /** What kind of app this is, sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server uses it to spot\n * a sign-in from a new device and to pick the notification channel.\n * `platform` is detected at runtime when omitted (`telegram-miniapp`\n * inside Telegram, `pwa` when installed, `web` otherwise); `version`\n * defaults to the SDK version. Native wrappers should pass\n * `{ platform: \"ios\" | \"android\", version }`. */\n client?: ClientDescriptor;\n /** Token persistence. Defaults to `defaultBrowserStore()` when\n * `window.localStorage` is present, else `inMemoryStore()`. */\n tokenStore?: TokenStore;\n /** Override the `fetch` implementation — useful for Node < 18,\n * React Native < 0.74, MSW intercept layers, etc. */\n fetch?: FetchLike;\n /** When true, the SDK runs every response through a zod schema\n * before handing it to the caller. Requires `zod` >= 3.22 as a\n * peer dep. Off by default; types-only validation is sufficient\n * for the steady-state case. */\n validate?: boolean;\n}\n\nexport interface CusfrontClient {\n /** Read-only brand config — pass through from createClient args. */\n readonly brand: BrandConfig | undefined;\n /** The platform and version this client announces in `X-Takeal-Client`. */\n readonly client: ResolvedClientDescriptor;\n /** Auth resource: login, refresh, current user, logout. */\n readonly auth: AuthResource;\n /** Deposits (money IN via a funder connector): initiate, get, list, refund. */\n readonly deposits: DepositsResource;\n /** Cards (money OUT via an issuer connector): the product catalog, create, get, list, update, balance. */\n readonly cards: CardsResource;\n /** Wallet balance lookup (defaults to the wallet's own currency). */\n readonly balance: BalanceResource;\n /** The wallet's currency: read it, switch it while the wallet is empty. */\n readonly wallet: WalletResource;\n /** Runtime white-label config (`GET /branding`, public): names, logo, wallet label. */\n readonly branding: BrandingResource;\n /** Public blog posts, returned as structured blocks to render in your own style. */\n readonly blog: BlogResource;\n /** The user's announcement channel subscriptions.\n * @deprecated Use `notifications.setPreferences({ categories: { marketing: {...} } })`. */\n readonly subscriptions: SubscriptionsResource;\n /** Where the user is signed in: list sessions, sign one or all others out. */\n readonly sessions: SessionsResource;\n /** Web Push subscription for the signed-in user.\n * @deprecated Use `devices.registerWebPush` / `devices.unregisterWebPush`. */\n readonly push: PushResource;\n /** The user's inbox and notification preferences. */\n readonly notifications: NotificationsResource;\n /** The user's devices: browsers with Web Push, phones, the Telegram Mini App. */\n readonly devices: DevicesResource;\n /** Profile actions for the signed-in user: link or unlink Telegram. */\n readonly me: MeResource;\n /** Direct access to the token store (e.g. for an explicit sign-out\n * on Capacitor's lifecycle \"app pausing\" event). */\n readonly tokens: TokenStore;\n /**\n * Turn an image URL from the API (`card.design.image_url`,\n * `product.design.image_url`) into one a browser can load. Absolute URLs\n * pass through; a path relative to the API origin (the default card\n * design, `/card-designs/default.svg`) is joined onto `baseUrl`.\n */\n assetUrl(url: string): string;\n}\n\n/**\n * Build a new client. Stateless across calls — multiple clients can\n * coexist (e.g. an admin Cusfront with a different baseUrl than the\n * end-user one). Each gets its own `TokenStore`.\n *\n * `validate: true` is honoured by individual resources that ship\n * matching zod schemas; resources without a schema ignore it.\n */\nexport function createClient(opts: CreateClientOptions): CusfrontClient {\n const tokens = opts.tokenStore ?? pickDefaultStore();\n const fetchImpl = opts.fetch ?? defaultFetch();\n const client = resolveClientDescriptor(opts.client);\n const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {\n [CLIENT_HEADER]: clientHeaderValue(client),\n });\n\n return {\n brand: opts.brand,\n client,\n tokens,\n assetUrl: (url: string) => resolveAssetUrl(opts.baseUrl, url),\n auth: new AuthResource(http, tokens),\n deposits: new DepositsResource(http),\n cards: new CardsResource(http),\n balance: new BalanceResource(http),\n wallet: new WalletResource(http),\n branding: new BrandingResource(http),\n blog: new BlogResource(http),\n subscriptions: new SubscriptionsResource(http),\n sessions: new SessionsResource(http),\n push: new PushResource(http),\n me: new MeResource(http),\n notifications: new NotificationsResource(http),\n devices: new DevicesResource(http, client),\n };\n}\n\nfunction pickDefaultStore(): TokenStore {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n return defaultBrowserStore();\n }\n return inMemoryStore();\n}\n\nfunction defaultFetch(): FetchLike {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.fetch === \"function\") {\n // Bind to globalThis so `this` is correct inside the implementation\n // (some polyfills choke on a detached reference).\n return globalThis.fetch.bind(globalThis);\n }\n throw new Error(\n \"@takeal/cusfront-sdk: native fetch is not available in this runtime. \" +\n \"Pass a polyfill via createClient({ fetch }).\",\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/error.ts","../src/http.ts","../src/resources/auth.ts","../src/resources/deposits.ts","../src/resources/cards.ts","../src/resources/balance.ts","../src/resources/branding.ts","../src/resources/wallet.ts","../src/resources/blog.ts","../src/resources/subscriptions.ts","../src/resources/sessions.ts","../src/resources/push.ts","../src/resources/me.ts","../src/resources/notifications.ts","../src/resources/devices.ts","../src/version.ts","../src/client-platform.ts","../src/token-store.ts","../src/assets.ts","../src/index.ts"],"names":["ls"],"mappings":";AAQO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EAGlC,WAAA,CAEkB,MAAA,EAIA,IAAA,EAGhB,OAAA,EAGgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAZG,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAMA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAdlB,IAAA,IAAA,CAAS,UAAA,GAAa,IAAA;AAiBpB,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AAAA,EACd;AACF;AAEO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAGtC,WAAA,CAAY,SAAiC,KAAA,EAAiB;AAC5D,IAAA,KAAA,CAAM,OAAO,CAAA;AAD8B,IAAA,IAAA,CAAA,KAAA,GAAA,KAA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BAAA,CAAiB,IAAI,CAAA;AAAA,IACnC,KAAA,EAAO,IAAI,aAAA,CAAc,IAAI,CAAA;AAAA,IAC7B,OAAA,EAAS,IAAI,eAAA,CAAgB,IAAI,CAAA;AAAA,IACjC,MAAA,EAAQ,IAAI,cAAA,CAAe,IAAI,CAAA;AAAA,IAC/B,QAAA,EAAU,IAAI,gBAAA,CAAiB,IAAI,CAAA;AAAA,IACnC,IAAA,EAAM,IAAI,YAAA,CAAa,IAAI,CAAA;AAAA,IAC3B,aAAA,EAAe,IAAI,qBAAA,CAAsB,IAAI,CAAA;AAAA,IAC7C,QAAA,EAAU,IAAI,gBAAA,CAAiB,IAAI,CAAA;AAAA,IACnC,IAAA,EAAM,IAAI,YAAA,CAAa,IAAI,CAAA;AAAA,IAC3B,EAAA,EAAI,IAAI,UAAA,CAAW,IAAI,CAAA;AAAA,IACvB,aAAA,EAAe,IAAI,qBAAA,CAAsB,IAAI,CAAA;AAAA,IAC7C,OAAA,EAAS,IAAI,eAAA,CAAgB,IAAA,EAAM,MAAM;AAAA,GAC3C;AACF;AAEA,SAAS,gBAAA,GAA+B;AACtC,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,IAAe,cAAA,IAAkB,UAAA,EAAY;AACrE,IAAA,OAAO,mBAAA,EAAoB;AAAA,EAC7B;AACA,EAAA,OAAO,aAAA,EAAc;AACvB;AAEA,SAAS,YAAA,GAA0B;AACjC,EAAA,IAAI,OAAO,UAAA,KAAe,WAAA,IAAe,OAAO,UAAA,CAAW,UAAU,UAAA,EAAY;AAG/E,IAAA,OAAO,UAAA,CAAW,KAAA,CAAM,IAAA,CAAK,UAAU,CAAA;AAAA,EACzC;AACA,EAAA,MAAM,IAAI,KAAA;AAAA,IACR;AAAA,GAEF;AACF","file":"index.js","sourcesContent":["/**\n * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;\n * network-level / abort / serialisation failures get the generic\n * `NetworkError`. Consumers catch on the discriminator field\n * (`isApiError` / `isNetworkError`) rather than `instanceof` — works\n * across bundler boundaries where multiple copies of the class can\n * coexist.\n */\nexport class ApiError extends Error {\n readonly isApiError = true as const;\n\n constructor(\n /** HTTP status code returned by the Takeal API. */\n public readonly status: number,\n /** Stable machine-readable code (e.g. `\"insufficient_funds\"`,\n * `\"permission_required\"`, `\"validation\"`). Same enum the\n * TypeScript types pin via openapi-typescript. */\n public readonly code: string,\n /** Human-readable message. English; the consumer maps to its\n * own i18n layer before showing to end-users. */\n message: string,\n /** Full parsed response body when available. Carries field-level\n * validation details for `code = \"validation\"`. */\n public readonly body?: unknown,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport class NetworkError extends Error {\n readonly isNetworkError = true as const;\n\n constructor(message: string, public readonly cause?: unknown) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n/** Type guard — preferred over `instanceof` (bundler-safe). */\nexport function isApiError(e: unknown): e is ApiError {\n return (\n typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true\n );\n}\n\nexport function isNetworkError(e: unknown): e is NetworkError {\n return (\n typeof e === \"object\" &&\n e !== null &&\n (e as { isNetworkError?: boolean }).isNetworkError === true\n );\n}\n","import { ApiError, NetworkError } from \"./error.js\";\nimport type { TokenStore } from \"./token-store.js\";\n\n/**\n * Internal HTTP client. One per SDK instance; injected into each\n * resource. Responsibilities:\n *\n * - Construct absolute URLs from `baseUrl` + API version + path.\n * Resources pass contract paths (`/me/deposits`); the `/v1` prefix is\n * added here, in one place. Only the deployment-level endpoints\n * (`/ready`, `/branding`, …) stay unversioned.\n * - Set `Authorization: Bearer <jwt>` from the `TokenStore`.\n * - Set `Content-Type: application/json` on bodies.\n * - Parse JSON responses + map non-2xx to `ApiError`.\n * - Forward `Idempotency-Key` when the caller passes one.\n * - Send the constructor's `defaultHeaders` (the `X-Takeal-Client`\n * descriptor) on every request.\n * - Surface network failures (DNS, abort, broken pipe) as\n * `NetworkError`.\n *\n * Auto-refresh + retry policies are deliberately NOT in here — they\n * belong to the resource layer (auth.refresh) which has the right\n * context for \"is this refreshable\" decisions.\n */\n\nexport type FetchLike = typeof fetch;\n\n/** Current public contract revision of the Takeal API. */\nexport const API_VERSION = \"/v1\";\n\n/** Host-level endpoints that are not part of a versioned contract. */\nconst UNVERSIONED = new Set([\"/health\", \"/ready\", \"/branding\", \"/favicon.ico\"]);\n\n/**\n * `/me/deposits` → `/v1/me/deposits`. Already-versioned paths and the\n * unversioned ops endpoints pass through untouched.\n */\nexport function versionedPath(path: string): string {\n const p = path.startsWith(\"/\") ? path : `/${path}`;\n const bare = p.split(\"?\")[0]!;\n if (UNVERSIONED.has(bare)) return p;\n if (bare === API_VERSION || bare.startsWith(`${API_VERSION}/`)) return p;\n return `${API_VERSION}${p}`;\n}\n\nexport interface HttpOptions {\n /** Request body. Will be JSON-serialised if not already a\n * string / FormData / Blob. */\n body?: unknown;\n /** Idempotency key forwarded as the `Idempotency-Key` header.\n * Required by the Takeal API on most write endpoints. */\n idempotencyKey?: string;\n /** Extra headers merged after the SDK's defaults — caller wins. */\n headers?: Record<string, string>;\n /** Bypass the token store for one call (login, refresh). */\n skipAuth?: boolean;\n /** AbortSignal forwarded to fetch. */\n signal?: AbortSignal;\n}\n\nexport class HttpClient {\n constructor(\n private readonly baseUrl: string,\n private readonly tokens: TokenStore,\n private readonly fetchImpl: FetchLike,\n /** Headers sent on every request, below the per-call `headers`\n * (a caller can still override one). */\n private readonly defaultHeaders: Record<string, string> = {},\n ) {\n if (!baseUrl) throw new Error(\"HttpClient: baseUrl is required\");\n }\n\n async get<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"GET\", path, opts);\n }\n\n async post<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"POST\", path, opts);\n }\n\n async put<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PUT\", path, opts);\n }\n\n async patch<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"PATCH\", path, opts);\n }\n\n async delete<T>(path: string, opts: HttpOptions = {}): Promise<T> {\n return this.request<T>(\"DELETE\", path, opts);\n }\n\n private async request<T>(method: string, path: string, opts: HttpOptions): Promise<T> {\n const url = this.absolute(path);\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n ...this.defaultHeaders,\n };\n if (opts.body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (opts.idempotencyKey) headers[\"Idempotency-Key\"] = opts.idempotencyKey;\n if (!opts.skipAuth) {\n const token = await Promise.resolve(this.tokens.get());\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n }\n Object.assign(headers, opts.headers ?? {});\n\n const init: RequestInit = {\n method,\n headers,\n ...(opts.signal ? { signal: opts.signal } : {}),\n };\n if (opts.body !== undefined) {\n init.body =\n typeof opts.body === \"string\" ? opts.body : JSON.stringify(opts.body);\n }\n\n let resp: Response;\n try {\n resp = await this.fetchImpl(url, init);\n } catch (e) {\n // DNS failure, connection refused, abort — anything before the\n // server returns a status. Map to NetworkError for the consumer.\n throw new NetworkError(\n e instanceof Error ? e.message : \"network error\",\n e,\n );\n }\n\n return parseResponse<T>(resp);\n }\n\n private absolute(path: string): string {\n if (path.startsWith(\"http://\") || path.startsWith(\"https://\")) return path;\n const base = this.baseUrl.replace(/\\/+$/, \"\");\n return `${base}${versionedPath(path)}`;\n }\n}\n\nasync function parseResponse<T>(resp: Response): Promise<T> {\n // Read body once — the Takeal API either returns JSON or an empty body\n // (204 No Content on some DELETEs). Empty body → undefined cast.\n const text = await resp.text();\n let body: unknown;\n if (text.length === 0) {\n body = undefined;\n } else {\n try {\n body = JSON.parse(text);\n } catch {\n // Non-JSON response. On 2xx that's unexpected but not fatal —\n // hand back the raw text under a synthetic field. On error\n // status, fold into the ApiError body.\n body = { raw: text };\n }\n }\n\n if (!resp.ok) {\n const errBody = (body ?? {}) as { code?: string; message?: string };\n throw new ApiError(\n resp.status,\n errBody.code ?? `http_${resp.status}`,\n errBody.message ?? resp.statusText ?? \"request failed\",\n body,\n );\n }\n return body as T;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\n\n/**\n * Auth resource — `client.auth.*`.\n *\n * Covers the end-user-facing staged auth flow: password login\n * with optional TOTP/OTP step-up. The shape mirrors the responses\n * the Takeal API returns from `/auth/login`, `/auth/login/totp`,\n * `/auth/login/otp/verify`, `/auth/login/2fa/switch`, and `/auth/me`.\n *\n * The login methods stash the JWT in the configured `TokenStore` on\n * success so subsequent `client.*` calls authenticate automatically.\n * Step-up responses (TotpRequired / OtpSent) carry their own short-\n * lived challenge token which the caller passes to the next method\n * — those tokens DO NOT go through the TokenStore (they're not the\n * end-state JWT).\n */\n\nexport interface User {\n id: string;\n email: string;\n role: string;\n is_active: boolean;\n /** True for users auto-provisioned via the Telegram Mini App who still hold\n * a synthetic placeholder email. The client should prompt for a real email\n * and attach it via `auth.linkEmail` — this flips the flag to false. */\n email_pending?: boolean;\n created_at: string;\n updated_at: string;\n /** ISO 4217 code the user's wallet is held in (their own choice, else the\n * deployment default). Present on `GET /auth/me`. */\n wallet_currency?: string;\n /** The Telegram account linked to this user, or `null` when none is.\n * Present on `GET /auth/me` and inside every `stage: \"jwt\"` envelope. */\n telegram?: TelegramLink | null;\n}\n\n/** A Telegram account attached to a user. One Telegram per account and one\n * account per Telegram. */\nexport interface TelegramLink {\n /** Telegram username without the `@`, or `null` when the user has none. */\n username: string | null;\n /** When the link was made, ISO-8601. */\n linked_at: string;\n}\n\nexport interface ExchangeTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n /** Create an account for a Telegram id the deployment has not seen before.\n * Default `true`. With `false` the exchange resolves to\n * `{ stage: \"unknown\" }` instead, so the app can offer \"create an account\"\n * or \"I already have one\". */\n provision?: boolean;\n}\n\n/** `exchangeTelegram({ provision: false })` for a Telegram id nobody has\n * signed in with yet. No account was created and no JWT was stored. */\nexport interface TelegramUnknown {\n stage: \"unknown\";\n}\n\nexport interface LinkTelegramInput {\n /** Raw `window.Telegram.WebApp.initData`, passed to the server verbatim. */\n initData: string;\n email: string;\n password: string;\n}\n\nexport interface LoginInput {\n email: string;\n password: string;\n}\n\n/** Discriminated union — `stage` is the discriminator. */\nexport type LoginResponse = JwtIssued | TotpRequired | TotpSetupRequired;\n\nexport interface JwtIssued {\n stage: \"jwt\";\n access_token: string;\n expires_at: string;\n user: User;\n /** True iff the user's role grants `system.view_hub`.\n * Cusfront ignores this; the operator console uses it to gate `/dashboard`. */\n hub_access?: boolean;\n}\n\nexport interface TotpRequired {\n stage: \"totp_required\";\n challenge_token: string;\n expires_at: string;\n /** Alternate second factors. Pick one with `/2fa/switch`. */\n available_methods: AvailableMethod[];\n}\n\nexport interface TotpSetupRequired {\n stage: \"totp_setup_required\";\n challenge_token: string;\n expires_at: string;\n /** OTPAuth URI rendered as a QR by the consumer. */\n otpauth_url: string;\n /** Same secret base32-encoded — for manual entry alongside QR. */\n secret_base32: string;\n}\n\nexport interface AvailableMethod {\n kind: \"totp\" | \"telegram_otp\" | \"email_otp\";\n /** Short user-facing hint, e.g. `\"Telegram (@user)\"` or `\"e****@example.com\"`. */\n hint?: string;\n}\n\nexport interface TotpVerifyInput {\n challenge_token: string;\n /** 6-digit TOTP code OR `XXXX-XXXX` backup code. */\n code: string;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n}\n\nexport interface SwitchMethodInput {\n challenge_token: string;\n method: AvailableMethod[\"kind\"];\n}\n\nexport interface RegisterInput {\n email: string;\n password: string;\n /** ISO 4217 code for the new wallet; must be offered by the deployment. */\n wallet_currency?: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. */\nexport type Session = Omit<JwtIssued, \"stage\">;\n\nexport interface TotpSetupComplete extends Session {\n /** Ten one-time `XXXX-XXXX` codes, returned only this once. */\n backup_codes: string[];\n}\n\nexport interface ChangePasswordInput {\n current_password: string;\n /** At least 12 characters with a lower-case letter, an upper-case letter\n * and a digit; must differ from the current password. */\n new_password: string;\n}\n\nexport interface OtpSentResponse {\n stage: \"otp_sent\";\n challenge_token: string;\n expires_at: string;\n method: AvailableMethod[\"kind\"];\n hint?: string;\n available_methods: AvailableMethod[];\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n ) {}\n\n /** Password-auth entry. May resolve to a JWT, or to a step-up\n * challenge that needs `verifyTotp` / `verifyOtp` next. */\n async login(input: LoginInput): Promise<LoginResponse> {\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body: input,\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await Promise.resolve(this.tokens.set(resp.access_token));\n }\n return resp;\n }\n\n /** Verify a TOTP code (or XXXX-XXXX backup code) against a\n * `totp_required` challenge. On success the JWT is stored. */\n async verifyTotp(input: TotpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/totp\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Verify a 6-digit OTP code (Telegram / email) against an\n * `otp_sent` challenge. */\n async verifyOtp(input: OtpVerifyInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/login/otp/verify\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Create an end-user account and sign it in. The JWT is stored.\n * `wallet_currency` must be one the deployment offers; omit it to take\n * the deployment default (it can be switched later via `client.wallet`\n * while the wallet is empty).\n * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Finish a `totp_setup_required` login: send the first code from the\n * authenticator app. The JWT is stored. The response carries ten\n * one-time `backup_codes` that are never returned again, so show them to\n * the user right away and don't keep them on the device. */\n async completeTotpSetup(input: TotpVerifyInput): Promise<TotpSetupComplete> {\n const resp = await this.http.post<TotpSetupComplete>(\"/auth/login/totp-setup\", {\n body: input,\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Change the signed-in user's password. Every other session of the\n * account is signed out; this one stays valid.\n * Errors: 400 when the new password fails the policy, 401 when the\n * current one is wrong. */\n async changePassword(input: ChangePasswordInput): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/auth/password\", {\n body: input,\n });\n }\n\n /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for\n * telegram/email; for TOTP it short-circuits back to the challenge. */\n async switchMethod(input: SwitchMethodInput): Promise<OtpSentResponse> {\n return this.http.post<OtpSentResponse>(\"/auth/login/2fa/switch\", {\n body: input,\n skipAuth: true,\n });\n }\n\n /** Exchange a signed Telegram Mini App `initData` payload for a session\n * JWT. The server validates the initData HMAC against the deployment's bot\n * token, then looks the Telegram id up. A known id signs in. An unknown id\n * gets a fresh account (`user.email_pending === true` — prompt for a real\n * email and call {@link linkEmail}) unless `provision: false` is passed, in\n * which case the call resolves to `{ stage: \"unknown\" }`, nothing is\n * created and nothing is stored; the app then offers to create the account\n * (call again with `provision: true`) or to attach the Telegram to an\n * existing one ({@link linkTelegram}). Stores the JWT on `stage: \"jwt\"`.\n *\n * Every other error still throws an `ApiError` (401 `invalid_init_data`,\n * 503 `telegram_not_configured`, …).\n *\n * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`\n * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when\n * you already hold a configured client. */\n exchangeTelegram(input: { initData: string; provision?: true }): Promise<JwtIssued>;\n exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown>;\n async exchangeTelegram(input: ExchangeTelegramInput): Promise<JwtIssued | TelegramUnknown> {\n const body: { init_data: string; provision?: boolean } = { init_data: input.initData };\n if (input.provision !== undefined) body.provision = input.provision;\n let resp: JwtIssued;\n try {\n resp = await this.http.post<JwtIssued>(\"/auth/telegram/exchange\", {\n body,\n skipAuth: true,\n });\n } catch (e) {\n if (isApiError(e) && e.status === 404 && e.code === \"telegram_unknown\") {\n return { stage: \"unknown\" };\n }\n throw e;\n }\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach the Telegram account behind `initData` to an existing email +\n * password account and sign in as that account. No bearer needed; the\n * password is checked the same way `login` checks it. The JWT is stored.\n *\n * Errors: 401 `unauthenticated` (wrong email or password, as with\n * `login`) / `invalid_init_data`; 403\n * `user_disabled` / `second_factor_required` (accounts that sign in with\n * a second factor can't be linked from a Mini App); 409\n * `telegram_already_linked_other` (this account already has a different\n * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to\n * another account); 503 `telegram_not_configured`. */\n async linkTelegram(input: LinkTelegramInput): Promise<JwtIssued> {\n const resp = await this.http.post<JwtIssued>(\"/auth/telegram/link\", {\n body: { init_data: input.initData, email: input.email, password: input.password },\n skipAuth: true,\n });\n await Promise.resolve(this.tokens.set(resp.access_token));\n return resp;\n }\n\n /** Attach a real email to the current user (and clear `email_pending`).\n * Used after a Telegram exchange to satisfy the email requirement; also\n * works for a password user changing their address. 409 if taken. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Current user — fails 401 when the stored JWT is expired or\n * missing. Useful as a \"do I have a session\" probe on app boot. */\n async me(): Promise<User> {\n return this.http.get<User>(\"/auth/me\");\n }\n\n /** Local sign-out: forgets the stored JWT. To end the session on the\n * server as well, revoke it first with `client.sessions.revoke(jti)`\n * (the current one is marked `current: true` in `client.sessions.list()`). */\n async signOut(): Promise<void> {\n await Promise.resolve(this.tokens.clear());\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\n\n/**\n * Deposits resource — `client.deposits.*`.\n *\n * The \"money IN\" surface: an end user tops up their wallet balance via a\n * funder connector. Mirrors the Takeal API's `/me/deposits` routes:\n *\n * POST /me/deposits → initiate\n * GET /me/deposits → list (most recent first)\n * GET /me/deposits/{id} → get\n * POST /me/deposits/{id}/refunds → refund\n *\n * A deposit is rarely terminal on the initiate call: real PSPs return\n * `redirect_required` (3DS / APM redirect) and flip to `confirmed` later via\n * a connector → Takeal API inbound event. Poll `get(id)` or watch the user's\n * webhook stream for the `deposit.confirmed` / `deposit.failed` outcome.\n */\n\n/** Lifecycle of a deposit. `redirect_required` carries `redirect_url`. */\nexport type DepositStatus =\n | \"pending\"\n | \"redirect_required\"\n | \"confirmed\"\n | \"failed\";\n\n/** Top-up rail. The chosen funder decides which it supports. */\nexport type DepositMethod = \"card\" | \"crypto\" | \"bank_transfer\";\n\n/**\n * A deposit record as the Takeal API returns it. Mirrors the `deposits` table; the\n * server-side `id` is the stable handle the SDK polls against. `idempotency_key`\n * and `request_fingerprint` are server-internal and never serialised.\n */\n/** Input for `quote()` — price a cross-currency deposit before paying. */\nexport interface CreateQuoteInput {\n /** Decimal string, e.g. `\"5000.00\"`. */\n amount: string;\n /** ISO 4217 source currency — must differ from the wallet's local currency. */\n currency: string;\n}\n\n/**\n * A rate-locked funding quote: pay `source_amount source_currency`, the\n * wallet is credited `credited_amount credited_currency` (net of the\n * platform's conversion spread). Execute by passing `id` as `quote_id` to\n * `initiate()` before `expires_at`; after that the API returns 409 and a new\n * quote is needed.\n */\nexport interface FundingQuote {\n id: string;\n source_amount: string;\n source_currency: string;\n credited_amount: string;\n credited_currency: string;\n /** Provider rate before spread (credited units per 1 source unit). */\n rate: string;\n spread_bps: number;\n provider: string;\n expires_at: string;\n}\n\nexport interface Deposit {\n id: string;\n user_id: string;\n /** Slug of the funder that handled this deposit, as configured by the deployment. */\n connector_slug: string;\n /** The connector's own reference, populated once it responds. */\n provider_reference: string | null;\n status: DepositStatus;\n /** Decimal serialised as a string to avoid float drift. */\n amount: string;\n currency: string;\n method: DepositMethod;\n /** Present when `status === \"redirect_required\"` — send the user here. */\n redirect_url: string | null;\n failure_reason: string | null;\n /** Final settled amount once confirmed (may differ from `amount` on FX). */\n confirmed_amount: string | null;\n confirmed_at: string | null;\n /** Set on cross-currency deposits: the quote this deposit executed against. */\n quote_id?: string | null;\n /** Locked provider rate (credited units per 1 source unit). */\n fx_rate?: string | null;\n fx_spread_bps?: number | null;\n /** The wallet's local currency the deposit converted into. */\n credited_currency?: string | null;\n /** What the wallet was actually credited, net of spread. */\n credited_amount?: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface InitiateDepositInput {\n /** Decimal as a string (`\"100.00\"`) — avoids float-precision loss on the wire. */\n amount: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n method: DepositMethod;\n /**\n * Optional. Slug of a specific funder to route through. Omit to\n * let the Takeal API pick the first active funder. Unknown slug → 400; empty\n * funder list → 503.\n */\n funder_slug?: string;\n /** Provider-specific extras. The mock funder reads `mock_scenario`. */\n metadata?: Record<string, string>;\n /** Structured billing details — real PSPs require these for 3DS / compliance. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original deposit; same key + different body returns 409. Supply a stable\n * UUID per logical attempt so a retried network call is safe.\n */\n idempotencyKey: string;\n /**\n * Required when `currency` differs from the wallet's local currency: a\n * fresh quote id from `quote()`. Cross-currency deposits without one are\n * rejected with 400; expired quotes with 409.\n */\n quote_id?: string;\n}\n\nexport interface CreateDepositRefundInput {\n /** Omit for a full refund of the original confirmed amount; same currency. */\n amount?: string;\n /** Human-readable reason, e.g. `\"customer_request\"`. */\n reason?: string;\n metadata?: Record<string, string>;\n /** Required. Replays are keyed on this. */\n idempotencyKey: string;\n}\n\n/** A refund row as the Takeal API returns it (`refunds` table, deposit-targeted). */\nexport interface Refund {\n id: string;\n target_type: string;\n deposit_id?: string;\n payment_id?: string;\n connector_slug: string;\n amount: string;\n currency: string;\n reason: string;\n status: string;\n provider_refund_reference?: string;\n failure_reason?: string;\n requestor_type: string;\n requestor_id: string;\n created_at: string;\n updated_at: string;\n}\n\nexport class DepositsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Initiate a top-up. Resolves to the freshly-created `Deposit`, whose\n * `status` may already be `confirmed` (synchronous rails / mock) or\n * `redirect_required` (3DS / APM — forward the user to `redirect_url`).\n */\n /**\n * Price a cross-currency deposit BEFORE paying. The rate is locked\n * server-side until `expires_at`; deposits in the local currency need no\n * quote (the API answers 400 `no_quote_needed`).\n */\n async quote(input: CreateQuoteInput): Promise<FundingQuote> {\n return this.http.post<FundingQuote>(\"/me/deposits/quotes\", { body: input });\n }\n\n async initiate(input: InitiateDepositInput): Promise<Deposit> {\n const { idempotencyKey, ...body } = input;\n return this.http.post<Deposit>(\"/me/deposits\", {\n body,\n idempotencyKey,\n });\n }\n\n /** Fetch one deposit by id — the poll target while a redirect resolves. */\n async get(id: string): Promise<Deposit> {\n return this.http.get<Deposit>(`/me/deposits/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's deposits, most recent first. */\n async list(): Promise<Deposit[]> {\n return this.http.get<Deposit[]>(\"/me/deposits\");\n }\n\n /**\n * Refund a previously-confirmed deposit. Synchronous when the\n * connector settles inline; otherwise the row stays `pending` and flips\n * later via the inbound `deposit.refunded` event.\n */\n async refund(\n depositId: string,\n input: CreateDepositRefundInput,\n ): Promise<Refund> {\n const { idempotencyKey, ...body } = input;\n return this.http.post<Refund>(\n `/me/deposits/${encodeURIComponent(depositId)}/refunds`,\n { body, idempotencyKey },\n );\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\n\n/**\n * Cards resource — `client.cards.*`.\n *\n * The end-user \"money OUT\" surface: a user issues themselves a card backed by\n * their wallet balance via an issuer connector. Mirrors the Takeal API's\n * `/me/cards` routes:\n *\n * GET /me/card-products → listProducts (the catalog)\n * GET /me/card-products/{id} → getProduct\n * POST /me/cards → create\n * GET /me/cards → list (most recent first)\n * GET /me/cards/{id} → get\n * PATCH /me/cards/{id} → update (name, design)\n * GET /me/cards/{id}/balance → balance (prepaid remaining)\n * POST /me/cards/{id}/freeze → freeze\n * POST /me/cards/{id}/unfreeze → unfreeze\n * POST /me/cards/{id}/terminate → terminate (one-way)\n *\n * The lifecycle actions are ownership-gated server-side: a caller can only\n * freeze / unfreeze / terminate a card that belongs to them (else 404).\n *\n * ## What is intentionally NOT here\n *\n * Card-data reveal (PAN / CVV) is a separate, security-sensitive flow with its\n * own re-auth + rate-limit + audit contract and is intentionally\n * NOT part of this resource (tracked separately).\n *\n * Today only PREPAID is wired end-to-end; CREDIT and GIFT return 400 from\n * the Takeal API until their issuer flows land.\n */\n\n/** Card product. Only `prepaid` is fully implemented today. */\nexport type CardType = \"credit\" | \"prepaid\" | \"gift\";\n\n/**\n * Card lifecycle state.\n *\n * `pending_payment` is a transient state: the row exists but the\n * per-card issuance-fee debit has not yet succeeded; such cards have no\n * provider reference and no user-visible side effects.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"active\"\n | \"frozen\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * A card design: the artwork a card is shown with. `image_url` is the front,\n * `image_url_back` the back; both are either absolute URLs or paths relative\n * to the API origin (the deployment's default design is\n * `/card-designs/default.svg`, its back `/card-designs/default.svg?side=back`)\n * — pass them through `client.assetUrl()` before rendering. `image_url_back`\n * is `null` or absent for a one-sided design: show the front on both sides.\n * The picture is in the proportions of a plastic card (1586×1000) and draws\n * no chip or card data; the client renders the number, name and expiry on\n * top. `id` is `null` for the deployment default, which is rendered from the\n * branding settings.\n */\nexport interface CardDesignRef {\n id: string | null;\n name?: string;\n image_url: string;\n image_url_back?: string | null;\n}\n\n/**\n * What issuing a card costs the caller. `amount` is the price after the\n * user's subscription discount; `base_amount` is the list price and\n * `discount_bps` the discount in basis points (1000 = 10 %). `label` is the\n * operator's wording for the fee line (\"Card issuance\").\n */\nexport interface CardProductPrice {\n amount: string;\n currency: string;\n label: string;\n base_amount: string;\n discount_bps: number;\n}\n\n/**\n * A card the user can order, as listed by `GET /me/card-products`. The id is\n * opaque — it names a product, never a provider. `designs` is the set the\n * user may pick from (may be empty when only the default applies); `design`\n * is what the card gets when no choice is made. `price` is `null` for a\n * free card. `features` is an operator-defined object (scheme, wallet\n * support, load limits, …) with no fixed keys.\n */\nexport interface CardProduct {\n id: string;\n name: string;\n description: string | null;\n card_type: CardType;\n currency: string | null;\n features: Record<string, unknown>;\n design: CardDesignRef;\n designs: CardDesignRef[];\n price: CardProductPrice | null;\n /** True for the product the deployment issues when none is chosen. */\n is_default: boolean;\n}\n\n/**\n * A card record as the Takeal API returns it. Mirrors the `cards` table. Note the\n * SDK never receives the full PAN or CVV here — only `last4` + expiry. The\n * gift-card `redemption_code` is returned exactly once (on create) and\n * scrubbed from subsequent list/get responses.\n */\nexport interface Card {\n id: string;\n user_id: string;\n card_type: CardType;\n status: CardStatus;\n /** Last four digits of the PAN — safe to display. */\n last4: string | null;\n expiry_month: number | null;\n expiry_year: number | null;\n /** Gift cards only, present once on create then scrubbed. */\n redemption_code?: string;\n /** Decimal as a string. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n /** The name the user gave the card, or `null`. */\n name: string | null;\n /** The artwork the card is shown with. Always present. */\n design: CardDesignRef;\n /** The product the card was issued from; `null` for cards issued without one. */\n product: { id: string; name: string } | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface CreateCardInput {\n /**\n * A product id from {@link CardsResource.listProducts}. Sent as\n * `product_id`. When given, `type` and `issuer_slug` may be omitted; when\n * both are given they must agree with the product (400 `product_mismatch`).\n * Unknown, disabled or hidden product → 400 `unknown_product`.\n */\n productId?: string;\n /** A name for the card, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * One of the product's `designs`. Sent as `design_id`. `null` or omitted\n * picks the product's default design; a design outside the product's set →\n * 400 `design_not_allowed`.\n */\n designId?: string | null;\n /**\n * `prepaid` (the only fully-wired type today), `credit`, or `gift`.\n * Optional when `productId` is given, required otherwise.\n */\n type?: CardType;\n /** Decimal as a string. The prepaid load amount drained from wallet balance. */\n initial_amount?: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n /**\n * Optional. Slug of a specific issuer to mint with. Omit to let\n * the Takeal API pick the first active issuer. Unknown slug → 400; empty issuer\n * list → 503.\n */\n issuer_slug?: string;\n metadata?: Record<string, string>;\n /** Structured billing details — real issuers require these for 3DS / KYC. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original card; same key + different body returns 409.\n */\n idempotencyKey: string;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n}\n\n/** Fields a user can change on their own card. Omitted fields are left as they are. */\nexport interface UpdateCardInput {\n /** New name, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * New design (one of the product's `designs`), or `null` for the product's\n * default. Sent as `design_id`.\n */\n designId?: string | null;\n}\n\n/**\n * Kept for callers written against 0.3.x: the API no longer asks for a\n * password or a code on reveal, the session is enough. Both fields are\n * ignored and will be dropped in the next major.\n * @deprecated\n */\nexport interface RevealCardInput {\n password?: string;\n totpCode?: string;\n}\n\n/**\n * Full card data from a successful reveal. **Security**: never persist this —\n * keep it in volatile memory only, clear it within `expires_in_seconds`, and\n * never write it to localStorage / logs (the API marks the response no-store).\n */\nexport interface RevealedCard {\n pan: string;\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n}\n\nexport class CardsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Issue a card backed by the user's wallet balance. Resolves to the new\n * `Card`. On a ledger failure after provider creation, the Takeal API rolls the row\n * to `failed` (never an orphaned active card); inspect `status` /\n * `failure_reason` on the result.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, productId, name, designId, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (productId !== undefined) body[\"product_id\"] = productId;\n if (name !== undefined) body[\"name\"] = name;\n if (designId !== undefined) body[\"design_id\"] = designId;\n return this.http.post<Card>(\"/me/cards\", {\n body,\n idempotencyKey,\n });\n }\n\n /**\n * The cards the caller can order, in the order the deployment offers them\n * (the default product first). Each item carries its name, description,\n * artwork, the issuance price after the caller's subscription discount,\n * and the currency. Pass an item's `id` as `productId` to {@link create}.\n */\n async listProducts(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/me/card-products\");\n }\n\n /** One product from the catalog. 404 when unknown, disabled or hidden. */\n async getProduct(id: string): Promise<CardProduct> {\n return this.http.get<CardProduct>(\n `/me/card-products/${encodeURIComponent(id)}`,\n );\n }\n\n /**\n * Rename the caller's own card or change its design. Resolves to the\n * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /\n * `design_not_allowed` on a bad value.\n */\n async update(id: string, input: UpdateCardInput): Promise<Card> {\n const body: Record<string, unknown> = {};\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n return this.http.patch<Card>(`/me/cards/${encodeURIComponent(id)}`, {\n body,\n });\n }\n\n /** Fetch one card by id. */\n async get(id: string): Promise<Card> {\n return this.http.get<Card>(`/me/cards/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's cards, most recent first. */\n async list(): Promise<Card[]> {\n return this.http.get<Card[]>(\"/me/cards\");\n }\n\n /**\n * Remaining balance of a prepaid card. `currency` is required by the Takeal API and\n * forwarded as a query param.\n */\n async balance(id: string, currency: string): Promise<CardBalance> {\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<CardBalance>(\n `/me/cards/${encodeURIComponent(id)}/balance?${q}`,\n );\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze}. The optional\n * `reason` is recorded on the audit trail. Resolves to the updated card.\n * 404 if the card isn't the caller's; 501 if the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/freeze`,\n { body: { reason } },\n );\n }\n\n /**\n * Reveal the FULL PAN + CVV for the caller's own card. The signed-in\n * session is all the API asks for; the call is rate-limited and audited\n * server-side. The Takeal API never persists this data and marks the\n * response no-store; the SDK returns it verbatim and holds nothing.\n *\n * **Consumer security duties** (the SDK can't enforce these for you):\n * keep the result in volatile memory only, never write it to\n * localStorage / logs, and clear it within `expires_in_seconds`.\n *\n * 401 bad re-auth · 403 not your card · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 provider error.\n */\n async reveal(id: string, _input?: RevealCardInput): Promise<RevealedCard> {\n return this.http.post<RevealedCard>(`/me/cards/${encodeURIComponent(id)}/reveal`);\n }\n\n /** Unfreeze a previously-frozen card. Idempotent on an already-active card. */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/unfreeze`,\n { body: {} },\n );\n }\n\n /**\n * Terminate the caller's own card. **One-way** — a terminated card cannot be\n * reactivated. The optional `reason` is audited. Idempotent on an\n * already-terminated card.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/terminate`,\n { body: { reason } },\n );\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Balance resource — `client.balance.*`.\n *\n * The user's wallet balance, tracked in the ledger. Mirrors the Takeal API's\n * `GET /me/balance[?currency=<code>]` route. Balances are per-currency; with\n * no `currency` the wallet's own currency is returned (see `client.wallet`).\n */\n\n/** Wallet balance for one currency. `amount` is a decimal string. */\nexport interface Balance {\n amount: string;\n currency: string;\n}\n\nexport class BalanceResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Fetch the user's wallet balance. Omit `currency` for the wallet's own\n * currency; pass an ISO 4217 code (e.g. `\"USD\"`) to read another one —\n * the ledger holds a separate balance per currency.\n */\n async get(currency?: string): Promise<Balance> {\n if (!currency) return this.http.get<Balance>(\"/me/balance\");\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<Balance>(`/me/balance?${q}`);\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Branding resource — `client.branding.*`.\n *\n * Runtime white-label config published by the deployment at `GET /branding`\n * (public, no auth). Lets a Cusfront re-theme itself on the fly — platform\n * name, logo, favicon, brand colours and the label used for the end-user's balance — without\n * a rebuild. Pairs with the build-time `BrandConfig`: the server-side values\n * win whenever both are present.\n */\n\n/** Public brand config of the deployment. All strings; empty = use the client default. */\nexport interface Branding {\n /** Platform display name (e.g. the white-label brand). */\n platform_name: string;\n /** Name of the merchant-facing portal. */\n merchant_portal_name: string;\n /** Logo image — absolute URL or `data:` URI. Empty → client default. */\n logo_url: string;\n /** Favicon — absolute URL or `data:` URI. Empty → client default. */\n favicon_url: string;\n /** User-facing name of the balance, e.g. `\"Wallet\"` or `\"Acme Wallet\"`.\n * Display-only: the `balance` API shape never changes with it. */\n wallet_label: string;\n /** Primary brand colour as `#rrggbb`. Empty → client default palette. */\n primary_color: string;\n /** Secondary brand colour as `#rrggbb`. Empty → client default palette. */\n secondary_color: string;\n /** Accent colour as `#rrggbb`. Empty → client default palette. */\n accent_color: string;\n}\n\nexport class BrandingResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Fetch the deployment's public brand config. Safe to call before login. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Branding> {\n return this.http.get<Branding>(\"/branding\", { skipAuth: true, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Wallet resource — `client.wallet.*`.\n *\n * Which currency the user's wallet is held in. Deposits in any other\n * currency are converted on funding (quote first, see `client.deposits`);\n * cards issued in another currency are paid from the wallet with an FX leg\n * at issuance. A user may switch currency only while every balance is zero\n * and only to a currency the deployment offers (`allowed`).\n */\n\n/** The user's wallet currency and what they may switch to. */\nexport interface Wallet {\n /** ISO 4217 code the wallet is held in. */\n currency: string;\n /** `true` when chosen by the user (or set by an operator), `false` when it\n * is the deployment default. */\n explicit: boolean;\n /** Currencies accepted by `set()`. */\n allowed: string[];\n}\n\nexport class WalletResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Current wallet currency + the currencies the user may switch to. */\n async get(opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.get<Wallet>(\"/me/wallet\", { signal: opts.signal });\n }\n\n /**\n * Switch the wallet currency. Fails with `409 wallet_not_empty` while any\n * balance is non-zero, and `400 currency_not_allowed` for a currency the\n * deployment does not offer.\n */\n async set(currency: string, opts: { signal?: AbortSignal } = {}): Promise<Wallet> {\n return this.http.put<Wallet>(\"/me/wallet\", { body: { currency }, signal: opts.signal });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Blog resource — `client.blog.*`.\n *\n * Posts are public: these calls work before the user logs in, which is what\n * a marketing page or a Mini App landing screen needs.\n *\n * A post arrives as a **structured document**, not as HTML. `body_blocks` is\n * a flat list of typed nodes; map each `type` onto your own component and the\n * post inherits your site's styling. `body_markdown` is there too if you'd\n * rather run your own renderer.\n *\n * ```ts\n * const { posts } = await client.blog.list({ perPage: 5 });\n * const post = await client.blog.get(posts[0].slug);\n *\n * post.body_blocks.map((b) => {\n * switch (b.type) {\n * case \"heading\": return <Heading level={b.level}>{b.text}</Heading>;\n * case \"paragraph\": return <P>{b.text}</P>;\n * case \"image\": return <Figure src={b.url} alt={b.alt} caption={b.caption} />;\n * case \"list\": return <List ordered={b.ordered} items={b.items} />;\n * case \"quote\": return <Quote>{b.text}</Quote>;\n * case \"code\": return <Code lang={b.lang}>{b.text}</Code>;\n * case \"divider\": return <Hr />;\n * }\n * });\n * ```\n *\n * Inline emphasis (`**bold**`, `[link](url)`) is left as Markdown inside\n * block text — every renderer already knows what to do with it.\n */\n\n/** One node of a post body. Discriminated on `type`. */\nexport type BlogBlock =\n | { type: \"heading\"; level: number; text: string }\n | { type: \"paragraph\"; text: string }\n | { type: \"image\"; url: string; alt?: string; caption?: string }\n | { type: \"list\"; ordered: boolean; items: string[] }\n | { type: \"quote\"; text: string }\n | { type: \"code\"; lang?: string; text: string }\n | { type: \"divider\" };\n\nexport interface BlogPost {\n /** Stable public key — link by this. */\n slug: string;\n title: string;\n /** Teaser for cards; falls back to the first paragraph. */\n excerpt: string;\n /** Image URL, relative to the API origin. Absent when no cover is set. */\n cover_url?: string;\n /** Raw Markdown, for consumers that bring their own renderer. */\n body_markdown: string;\n /** The recommended input for rendering — see the module docs. */\n body_blocks: BlogBlock[];\n tags: string[];\n /** Present only when the post declares one. */\n locale?: string;\n /** Rough read time in minutes (minimum 1). */\n reading_minutes: number;\n published_at: string | null;\n updated_at: string;\n}\n\nexport interface BlogListInput {\n /** 1-based. Default 1. */\n page?: number;\n /** 1..=50. Default 10. */\n perPage?: number;\n /** Only posts carrying this tag. */\n tag?: string;\n /** Only posts in this locale. */\n locale?: string;\n}\n\nexport interface BlogList {\n posts: BlogPost[];\n total: number;\n page: number;\n per_page: number;\n}\n\nexport class BlogResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Published posts, newest first. No authentication required. */\n async list(input: BlogListInput = {}): Promise<BlogList> {\n const q = new URLSearchParams();\n if (input.page) q.set(\"page\", String(input.page));\n if (input.perPage) q.set(\"per_page\", String(input.perPage));\n if (input.tag) q.set(\"tag\", input.tag);\n if (input.locale) q.set(\"locale\", input.locale);\n const qs = q.toString();\n return this.http.get<BlogList>(`/blog/posts${qs ? `?${qs}` : \"\"}`, {\n skipAuth: true,\n });\n }\n\n /** One post by slug. No authentication required. */\n async get(slug: string): Promise<BlogPost> {\n return this.http.get<BlogPost>(`/blog/posts/${encodeURIComponent(slug)}`, {\n skipAuth: true,\n });\n }\n\n /**\n * Absolute URL for an image path returned inside a post (`cover_url`, or an\n * image block's `url`). Handy when the app renders on a different origin\n * than the API.\n */\n imageUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Subscriptions resource — `client.subscriptions.*`.\n *\n * Which channels the signed-in user agreed to receive announcements on.\n * `available` tells you which toggles to render: a deployment with no\n * Telegram bot configured can't deliver there, so offering the switch would\n * be a lie.\n *\n * ```ts\n * const { channels, available } = await client.subscriptions.get();\n * await client.subscriptions.set([...channels, \"telegram\"]);\n * ```\n *\n * Unrelated to paid/VIP tiers — this is only about announcements.\n *\n * @deprecated Announcements are now the `marketing` category of the\n * notification preferences. Read them with\n * `client.notifications.getPreferences()` and change them with\n * `client.notifications.setPreferences({ categories: { marketing: { email: true, telegram: false } } })`.\n * This endpoint keeps working as an alias over that setting.\n */\n\nexport type BroadcastChannel = \"email\" | \"telegram\" | (string & {});\n\nexport interface Subscriptions {\n /** Channels the user currently receives announcements on. */\n channels: BroadcastChannel[];\n /** Channels this deployment can actually deliver on. */\n available: BroadcastChannel[];\n}\n\n/** @deprecated See the note at the top of this module. */\nexport class SubscriptionsResource {\n constructor(private readonly http: HttpClient) {}\n\n async get(): Promise<Subscriptions> {\n return this.http.get<Subscriptions>(\"/me/subscriptions\");\n }\n\n /**\n * Replace the whole set — this is a PUT, not a merge. Pass `[]` to opt out\n * of everything.\n */\n async set(channels: BroadcastChannel[]): Promise<Subscriptions> {\n return this.http.put<Subscriptions>(\"/me/subscriptions\", {\n body: { channels },\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Sessions resource — `client.sessions.*`.\n *\n * Every device or browser the user is signed in on. Lets a settings screen\n * show \"where you're signed in\" and sign one or all of them out.\n *\n * ```ts\n * const sessions = await client.sessions.list();\n * const others = sessions.filter((s) => !s.current);\n * await client.sessions.revokeOthers();\n * ```\n */\n\nexport interface UserSession {\n /** Session id; pass it to `revoke`. */\n jti: string;\n issued_at: string;\n expires_at: string;\n last_seen_at: string;\n /** Client IP recorded for the session, if known. */\n remote_ip?: string | null;\n /** Browser or app that opened the session, if known. */\n user_agent?: string | null;\n /** `true` for the session this client is using. */\n current: boolean;\n}\n\nexport class SessionsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** All live sessions of the account, this one included. */\n async list(): Promise<UserSession[]> {\n return this.http.get<UserSession[]>(\"/me/sessions\");\n }\n\n /** Sign out one session. Works on the current one too; the stored JWT\n * stops working, so follow with `client.auth.signOut()`.\n * 404 when the session is unknown or already signed out. */\n async revoke(jti: string): Promise<void> {\n await this.http.delete<void>(`/me/sessions/${encodeURIComponent(jti)}`);\n }\n\n /** Sign out every session except this one. */\n async revokeOthers(): Promise<{ revoked_sessions: number }> {\n return this.http.post<{ revoked_sessions: number }>(\"/me/sessions/terminate-others\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Push resource — `client.push.*`.\n *\n * Web Push for the signed-in user, through the older single-subscription\n * endpoint. The API now keeps one device per browser (see\n * `client.devices`), and this endpoint is an alias over the Web Push\n * devices: it keeps working, but new code should call\n * `client.devices.registerWebPush(reg)` / `unregisterWebPush(reg)` instead.\n *\n * Your service worker shows the notification: the payload is JSON with\n * `title`, `body` and `url` (where a click should lead).\n */\n\nexport interface PushStatus {\n /** `true` when a subscription is stored for this user. */\n subscribed: boolean;\n /** Host of the stored endpoint, e.g. `fcm.googleapis.com`. */\n endpoint_host?: string | null;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`.\n * `null` when push is not set up on this deployment. */\n vapid_public_key?: string | null;\n}\n\nexport interface PushSubscriptionInput {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** The part of `ServiceWorkerRegistration` the SDK needs. Typed\n * structurally so the core stays free of DOM lib types. */\nexport interface PushCapableRegistration {\n pushManager: {\n getSubscription(): Promise<{ unsubscribe(): Promise<boolean> } | null>;\n subscribe(options: {\n userVisibleOnly: boolean;\n applicationServerKey: Uint8Array;\n }): Promise<{ toJSON(): { endpoint?: string; keys?: Record<string, string> } }>;\n };\n}\n\nexport class PushResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Whether the user is subscribed, plus the VAPID key to subscribe with. */\n async status(): Promise<PushStatus> {\n return this.http.get<PushStatus>(\"/me/push-subscription\");\n }\n\n /** Store a subscription you created yourself.\n * 409 `push_disabled` when the deployment has no VAPID keys.\n * @deprecated Use `client.devices.register({ kind: \"webpush\", ... })`. */\n async save(input: PushSubscriptionInput): Promise<PushStatus> {\n return this.http.put<PushStatus>(\"/me/push-subscription\", { body: input });\n }\n\n /** Delete the stored subscription. Safe when nothing is stored.\n * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */\n async remove(): Promise<void> {\n await this.http.delete<void>(\"/me/push-subscription\");\n }\n\n /** Subscribe this browser and store the subscription. Ask for\n * notification permission before calling. Throws when push isn't set up\n * on the deployment.\n * @deprecated Use `client.devices.registerWebPush(registration)`. */\n async enable(registration: PushCapableRegistration): Promise<PushStatus> {\n const { vapid_public_key } = await this.status();\n if (!vapid_public_key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(vapid_public_key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.save({\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n });\n }\n\n /** Unsubscribe this browser and delete the stored subscription.\n * @deprecated Use `client.devices.unregisterWebPush(registration)`. */\n async disable(registration: PushCapableRegistration): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n await this.remove();\n }\n}\n\n/** URL-safe base64 (padding optional) → bytes. */\nexport function base64UrlToBytes(input: string): Uint8Array {\n const b64 = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = b64 + \"=\".repeat((4 - (b64.length % 4)) % 4);\n const bin = atob(padded);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { User } from \"./auth.js\";\n\n/**\n * Me resource — `client.me.*`.\n *\n * Profile-level actions for the signed-in user that don't belong to another\n * resource. Today: the Telegram link.\n *\n * ```ts\n * // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):\n * const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);\n * me.telegram; // { username, linked_at }\n *\n * // From a settings screen:\n * await client.me.unlinkTelegram();\n * ```\n */\nexport class MeResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Attach the Telegram account behind `initData` to the signed-in user.\n * Returns the updated user (`telegram` is set). Repeating the call with\n * the same Telegram is fine.\n *\n * Errors: 401 `invalid_init_data`; 403 `user_disabled` /\n * `second_factor_required`; 409 `telegram_already_linked_other` (the\n * account already has a different Telegram; `unlinkTelegram` first) /\n * `telegram_in_use` (that Telegram belongs to another account); 503\n * `telegram_not_configured`. */\n async linkTelegram(initData: string): Promise<User> {\n return this.http.post<User>(\"/me/telegram\", { body: { init_data: initData } });\n }\n\n /** Detach the Telegram account from the signed-in user. Returns the\n * updated user (`telegram` is `null`).\n *\n * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the\n * account has no password, so Telegram is its only way to sign in. */\n async unlinkTelegram(): Promise<User> {\n return this.http.delete<User>(\"/me/telegram\");\n }\n}\n","import type { HttpClient } from \"../http.js\";\n\n/**\n * Notifications resource — `client.notifications.*`.\n *\n * Every notification a user gets is also kept server-side as an inbox item,\n * whatever else was sent (a push, a Telegram message, an email). The inbox\n * is what the app shows; the other channels are the nudge to open it.\n *\n * ```ts\n * const page = await client.notifications.list({ limit: 20 });\n * for (const item of page.items) {\n * render(item.title, item.body, item.href); // href: a path inside your app, or null\n * }\n * await client.notifications.markRead(page.items[0].id);\n * ```\n *\n * Preferences decide where the nudge goes: a primary channel (or automatic\n * when `null`), per-category switches, and the user's language.\n */\n\n/** What an item is about. `security` and `money` can't be switched off\n * completely; `marketing` is off until the user opts in. */\nexport type NotificationCategory = \"money\" | \"card\" | \"security\" | \"account\" | \"marketing\";\n\n/** A way to reach the user outside the inbox. */\nexport type NotificationChannel = \"push\" | \"telegram\" | \"email\" | \"sms\";\n\n/** Language the user reads notifications in. */\nexport type NotificationLocale = \"en\" | \"ru\" | (string & {});\n\n/**\n * `data` of a `card_otp` item: a confirmation code the card issuer sent for a\n * 3-D Secure payment (`purpose: \"payment\"`) or for adding the card to Apple\n * Pay / Google Pay (`purpose: \"wallet\"`). The code is what the user needs\n * right now, so show it prominently with a copy button and a countdown from\n * `expires_in_minutes`; `merchant_name`, `amount` and `currency` are absent\n * for wallet codes. Narrow with `isCardOtp(item)`.\n */\nexport interface CardOtpData {\n otp: string;\n purpose: \"payment\" | \"wallet\";\n merchant_name?: string;\n amount?: string;\n currency?: string;\n last4?: string;\n card_id?: string;\n expires_in_minutes?: number;\n}\n\n/** True when the item carries a card confirmation code (`CardOtpData`). */\nexport function isCardOtp(\n item: InboxItem,\n): item is InboxItem & { event_type: \"card_otp\"; data: CardOtpData } {\n return item.event_type === \"card_otp\" && typeof item.data?.otp === \"string\";\n}\n\nexport interface InboxItem {\n id: string;\n /** What happened, e.g. `deposit_confirmed`, `card_transaction`,\n * `login_new_device`, `card_otp` (see `CardOtpData`). */\n event_type: string;\n category: NotificationCategory;\n title: string;\n body: string;\n /** A path inside the client app to open on tap (`/cards/<id>`,\n * `/deposits/<id>`, `/subscription`, `/settings/sessions`), or `null`. */\n href: string | null;\n /** Event details (amount, currency, card last four and so on); the keys\n * depend on `event_type`. */\n data: Record<string, unknown>;\n /** Language the item was rendered in. */\n locale: string;\n /** When the user read it, or `null` while unread. */\n read_at: string | null;\n created_at: string;\n}\n\nexport interface NotificationPage {\n /** Newest first. */\n items: InboxItem[];\n /** Pass back as `cursor` to get the next page; `null` on the last one. */\n next_cursor: string | null;\n /** Unread items across the whole inbox, not just this page. */\n unread_count: number;\n}\n\nexport interface ListNotificationsParams {\n /** `next_cursor` from the previous page. */\n cursor?: string;\n /** Page size; the server caps it. */\n limit?: number;\n /** Only items without `read_at`. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n}\n\n/** Per-category channel switches: `{ money: { push: true, email: false } }`.\n * A channel missing from a category keeps its default. */\nexport type NotificationCategoryPreferences = Partial<\n Record<NotificationCategory, Partial<Record<NotificationChannel, boolean>>>\n>;\n\nexport interface NotificationPreferences {\n /** The channel to use first; `null` means automatic (the server picks by\n * the user's devices). */\n primary_channel: NotificationChannel | null;\n categories: NotificationCategoryPreferences;\n /** `null` when unset: the server falls back to the Telegram profile's\n * language, then the deployment default. */\n locale: NotificationLocale | null;\n /** Channels this deployment can deliver on. Render toggles only for\n * these. */\n available_channels: NotificationChannel[];\n}\n\n/** Body of `setPreferences`. Every field is optional; only the given ones\n * change. `primary_channel: null` switches back to automatic. */\nexport interface NotificationPreferencesInput {\n primary_channel?: NotificationChannel | null;\n categories?: NotificationCategoryPreferences;\n locale?: NotificationLocale | null;\n}\n\nexport class NotificationsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** One page of the inbox, newest first. */\n async list(params: ListNotificationsParams = {}): Promise<NotificationPage> {\n const q = new URLSearchParams();\n if (params.cursor) q.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n if (params.unreadOnly) q.set(\"unread\", \"true\");\n if (params.category) q.set(\"category\", params.category);\n const qs = q.toString();\n return this.http.get<NotificationPage>(`/me/notifications${qs ? `?${qs}` : \"\"}`);\n }\n\n /** How many items are unread. Cheap; fine to poll for a badge. */\n async unreadCount(): Promise<number> {\n const { unread } = await this.http.get<{ unread: number }>(\"/me/notifications/unread-count\");\n return unread;\n }\n\n /** Mark one item read. Returns the item; calling it again is harmless. */\n async markRead(id: string): Promise<InboxItem> {\n return this.http.post<InboxItem>(`/me/notifications/${encodeURIComponent(id)}/read`);\n }\n\n /** Mark every unread item read, or only those created before `before`\n * (ISO timestamp). Returns how many changed. */\n async markAllRead(before?: string): Promise<{ marked: number }> {\n return this.http.post<{ marked: number }>(\"/me/notifications/read-all\", {\n body: before ? { before } : {},\n });\n }\n\n /** Delete one item. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/notifications/${encodeURIComponent(id)}`);\n }\n\n /** The user's channel and language settings. */\n async getPreferences(): Promise<NotificationPreferences> {\n return this.http.get<NotificationPreferences>(\"/me/notification-preferences\");\n }\n\n /** Change some settings; the rest stay. Returns the stored view.\n * 400 `validation` for an unknown category, channel or locale. */\n async setPreferences(input: NotificationPreferencesInput): Promise<NotificationPreferences> {\n return this.http.put<NotificationPreferences>(\"/me/notification-preferences\", {\n body: input,\n });\n }\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { ClientPlatform, ResolvedClientDescriptor } from \"../client-platform.js\";\nimport { base64UrlToBytes, type PushCapableRegistration } from \"./push.js\";\n\n/**\n * Devices resource — `client.devices.*`.\n *\n * A user has many devices: each browser with a Web Push subscription, each\n * phone with an FCM / APNs token, and a marker for \"uses the Telegram Mini\n * App\". The server picks the notification channel from them: a mobile app\n * first, otherwise the device seen most recently.\n *\n * The usual browser flow, once notification permission is granted:\n *\n * ```ts\n * const reg = await navigator.serviceWorker.ready;\n * const device = await client.devices.registerWebPush(reg, { label: \"Chrome on Mac\" });\n * // later, from a settings screen:\n * await client.devices.unregisterWebPush(reg);\n * ```\n */\n\nexport type DeviceKind = \"webpush\" | \"fcm\" | \"apns\" | \"telegram_miniapp\";\n\nexport type DevicePlatform = \"pwa\" | \"web\" | \"ios\" | \"android\" | \"telegram\";\n\nexport interface Device {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** Free-form name the app gave it (\"Chrome on Mac\"), or `null`. */\n label: string | null;\n locale: string | null;\n app_version: string | null;\n created_at: string;\n last_seen_at: string;\n /** Set when the device no longer receives anything (the push endpoint is\n * gone, or someone switched it off). */\n disabled_at: string | null;\n /** `true` when it was registered from the session this client holds. */\n is_current: boolean;\n}\n\n/** `PushSubscription.toJSON()` minus the parts the server doesn't need. */\nexport interface WebPushCredential {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** FCM registration token or APNs device token. */\nexport interface MobilePushCredential {\n token: string;\n}\n\nexport type RegisterDeviceInput =\n | {\n kind: \"webpush\";\n platform: DevicePlatform;\n credential: WebPushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"fcm\" | \"apns\";\n platform: DevicePlatform;\n credential: MobilePushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"telegram_miniapp\";\n platform: DevicePlatform;\n /** Nothing to send: the device is a marker. */\n credential: Record<string, never>;\n label?: string;\n locale?: string;\n app_version?: string;\n };\n\nexport interface RegisteredDevice {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`;\n * `null` when push is not set up on this deployment. */\n vapid_public_key: string | null;\n}\n\nexport interface RegisterWebPushOptions {\n /** A name to show in the user's device list (\"Chrome on Mac\"). */\n label?: string;\n /** Skip the key lookup when you already hold the deployment's VAPID\n * public key (from an earlier `register` result, for example). */\n vapidPublicKey?: string;\n}\n\nexport interface UnregisterWebPushOptions {\n /** The device to delete, from an earlier `registerWebPush` result. When\n * omitted, every Web Push device registered from this session goes. */\n deviceId?: string;\n}\n\n/** Client platform → the platform the device list uses. */\nexport function devicePlatformOf(platform: ClientPlatform): DevicePlatform {\n return platform === \"telegram-miniapp\" ? \"telegram\" : platform;\n}\n\nexport class DevicesResource {\n constructor(\n private readonly http: HttpClient,\n private readonly client: ResolvedClientDescriptor,\n ) {}\n\n /** Every device the user has, disabled ones included. */\n async list(): Promise<Device[]> {\n return this.http.get<Device[]>(\"/me/devices\");\n }\n\n /** Register a device, or refresh it when the same credential is already\n * known (then `last_seen_at`, `label` and `app_version` update and a\n * disabled device comes back). `app_version` defaults to the client\n * version sent in `X-Takeal-Client`.\n *\n * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the\n * deployment has no VAPID keys. */\n async register(input: RegisterDeviceInput): Promise<RegisteredDevice> {\n return this.http.put<RegisteredDevice>(\"/me/devices\", {\n body: { app_version: this.client.version, ...input },\n });\n }\n\n /** Delete one device. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/devices/${encodeURIComponent(id)}`);\n }\n\n /** Subscribe this browser to Web Push and register it as a device. Ask\n * for notification permission before calling. Throws when push isn't\n * set up on the deployment. */\n async registerWebPush(\n registration: PushCapableRegistration,\n opts: RegisterWebPushOptions = {},\n ): Promise<RegisteredDevice> {\n const key = opts.vapidPublicKey ?? (await this.vapidPublicKey());\n if (!key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.register({\n kind: \"webpush\",\n platform: devicePlatformOf(this.client.platform),\n credential: {\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n },\n ...(opts.label ? { label: opts.label } : {}),\n });\n }\n\n /** Unsubscribe this browser from Web Push and delete the matching device\n * (see {@link UnregisterWebPushOptions}). Safe when nothing is\n * registered. */\n async unregisterWebPush(\n registration: PushCapableRegistration,\n opts: UnregisterWebPushOptions = {},\n ): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n if (opts.deviceId) {\n await this.remove(opts.deviceId);\n return;\n }\n const mine = (await this.list()).filter((d) => d.kind === \"webpush\" && d.is_current);\n for (const d of mine) await this.remove(d.id);\n }\n\n private async vapidPublicKey(): Promise<string | null> {\n const { vapid_public_key } = await this.http.get<{ vapid_public_key?: string | null }>(\n \"/me/push-subscription\",\n );\n return vapid_public_key ?? null;\n }\n}\n","/**\n * The SDK's own version, sent as the default `X-Takeal-Client` version.\n *\n * Kept as a plain constant so every entry point (ESM, CJS, the\n * sub-exports) reads the same value without a JSON import or a bundler\n * `define`. `src/version.test.ts` checks it matches `package.json`, so a\n * release bump that forgets this file fails the test run.\n */\nexport const SDK_VERSION = \"0.3.12\";\n","import { SDK_VERSION } from \"./version.js\";\n\n/**\n * Which kind of app is talking to the API. Sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server keeps it on the\n * session: it decides whether a sign-in counts as a new device, and which\n * channel a notification goes out on (a Mini App gets Telegram messages, a\n * PWA gets Web Push, and so on).\n */\nexport type ClientPlatform = \"pwa\" | \"web\" | \"telegram-miniapp\" | \"ios\" | \"android\";\n\n/** The `client` option of `createClient`. */\nexport interface ClientDescriptor {\n /** What the app is. Detected at runtime when omitted; see\n * {@link detectClientPlatform}. */\n platform: ClientPlatform;\n /** The app's own version. Defaults to the SDK version. */\n version?: string;\n}\n\n/** A descriptor with every field filled in. `client.client` on a\n * {@link CusfrontClient} has this shape. */\nexport interface ResolvedClientDescriptor {\n platform: ClientPlatform;\n version: string;\n}\n\n/** Header name carrying the client descriptor. */\nexport const CLIENT_HEADER = \"X-Takeal-Client\";\n\n/**\n * Best-effort platform detection for browser runtimes:\n *\n * - `telegram-miniapp` when `window.Telegram.WebApp.initData` is non-empty\n * (the app was launched from Telegram);\n * - `pwa` when the page runs installed: iOS Safari's `navigator.standalone`\n * or a `display-mode: standalone` media query;\n * - `web` otherwise, and always outside a browser (Node, workers without a\n * `navigator`).\n *\n * Native wrappers (Capacitor, React Native) should pass `ios` / `android`\n * explicitly; there is no reliable way to tell them apart from a browser.\n */\nexport function detectClientPlatform(): ClientPlatform {\n const g = globalThis as unknown as {\n Telegram?: { WebApp?: { initData?: unknown } };\n navigator?: { standalone?: unknown };\n matchMedia?: (query: string) => { matches: boolean };\n };\n const initData = g.Telegram?.WebApp?.initData;\n if (typeof initData === \"string\" && initData.length > 0) return \"telegram-miniapp\";\n\n if (g.navigator?.standalone === true) return \"pwa\";\n if (typeof g.matchMedia === \"function\") {\n try {\n if (g.matchMedia(\"(display-mode: standalone)\").matches) return \"pwa\";\n } catch {\n // Some non-browser runtimes stub matchMedia and throw; treat as web.\n }\n }\n return \"web\";\n}\n\n/** Fill in the blanks of a `client` option. */\nexport function resolveClientDescriptor(\n given: ClientDescriptor | undefined,\n): ResolvedClientDescriptor {\n return {\n platform: given?.platform ?? detectClientPlatform(),\n version: given?.version || SDK_VERSION,\n };\n}\n\n/** `{ platform: \"pwa\", version: \"0.3.0\" }` → `\"pwa; 0.3.0\"`. */\nexport function clientHeaderValue(desc: ResolvedClientDescriptor): string {\n return `${desc.platform}; ${desc.version}`;\n}\n","/**\n * Pluggable storage for the JWT.\n *\n * Default behaviour by environment:\n * - browser → `localStorage` (synchronous, persists across reloads)\n * - Node / SSR / worker → in-memory (no global state to leak)\n * - mobile (Capacitor / RN) → consumer must inject Keychain /\n * EncryptedSharedPreferences via `createClient({ tokenStore })`\n *\n * The store is intentionally tiny — three methods, no eviction\n * policy, no encryption. Encryption is the consumer's call (mobile\n * adapters wrap platform-native secure storage). Persistence shape\n * is opaque to the SDK; tokens are passed through verbatim.\n */\nexport interface TokenStore {\n get(): string | null | Promise<string | null>;\n set(token: string): void | Promise<void>;\n clear(): void | Promise<void>;\n}\n\n/** Sync `localStorage`-backed store. Falls through to in-memory when\n * `window.localStorage` is unavailable (private mode quota, SSR). */\nexport function defaultBrowserStore(key = \"takeal_jwt\"): TokenStore {\n const fallback = inMemoryStore();\n // Probe once at construction — avoid the try/catch on every call.\n let usable = false;\n try {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n const probe = \"__takeal_probe__\";\n ls.setItem(probe, \"1\");\n ls.removeItem(probe);\n usable = true;\n }\n } catch {\n usable = false;\n }\n if (!usable) return fallback;\n const ls = (globalThis as { localStorage: Storage }).localStorage;\n return {\n get: () => ls.getItem(key),\n set: (token) => ls.setItem(key, token),\n clear: () => ls.removeItem(key),\n };\n}\n\n/** In-memory store. Use for SSR / tests / when persistence isn't\n * desired (e.g. ephemeral kiosk sessions). */\nexport function inMemoryStore(): TokenStore {\n let value: string | null = null;\n return {\n get: () => value,\n set: (token) => {\n value = token;\n },\n clear: () => {\n value = null;\n },\n };\n}\n","/**\n * Resolve an image URL the API hands back (`design.image_url`, a logo, …)\n * into something a browser can load.\n *\n * The API returns either an absolute URL (uploaded artwork served from\n * object storage) or a path relative to the API origin (the deployment's\n * default card design, `/card-designs/default.svg`). Absolute URLs — and\n * `data:` / `blob:` URIs — come back unchanged; a relative path is joined\n * onto `baseUrl`, which is the bare API origin the client was built with.\n * These paths are host-level, so no `/v1` prefix is added.\n *\n * `baseUrl` is the same value passed to `createClient`; a trailing slash is\n * tolerated. `client.assetUrl()` calls this with the client's own base.\n */\nexport function resolveAssetUrl(baseUrl: string, url: string): string {\n if (isAbsolute(url)) return url;\n const base = baseUrl.replace(/\\/+$/, \"\");\n const path = url.startsWith(\"/\") ? url : `/${url}`;\n return `${base}${path}`;\n}\n\n/** `https://…`, `http://…`, protocol-relative `//…`, `data:` and `blob:` all count as absolute. */\nfunction isAbsolute(url: string): boolean {\n return /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(url);\n}\n","/**\n * `@takeal/cusfront-sdk` — typed client for the Takeal end-user API.\n *\n * Entry point: `createClient({ baseUrl, brand?, client?, tokenStore?, fetch? })`.\n * Resources are accessed off the returned client (`client.auth.login`,\n * `client.cards.list`, …). Sub-exports under `@takeal/cusfront-sdk/<resource>`\n * publish each resource independently so a Cusfront only pulls what\n * it imports.\n *\n * Brand-neutral by design. No customer / deployment names embedded.\n * Brand swap happens at runtime via `BrandConfig`.\n */\n\nimport { HttpClient, type FetchLike } from \"./http.js\";\nimport { AuthResource } from \"./resources/auth.js\";\nimport { DepositsResource } from \"./resources/deposits.js\";\nimport { CardsResource } from \"./resources/cards.js\";\nimport { BalanceResource } from \"./resources/balance.js\";\nimport { BrandingResource } from \"./resources/branding.js\";\nimport { WalletResource } from \"./resources/wallet.js\";\nimport { BlogResource } from \"./resources/blog.js\";\nimport { SubscriptionsResource } from \"./resources/subscriptions.js\";\nimport { SessionsResource } from \"./resources/sessions.js\";\nimport { PushResource } from \"./resources/push.js\";\nimport { MeResource } from \"./resources/me.js\";\nimport { NotificationsResource } from \"./resources/notifications.js\";\nimport { DevicesResource } from \"./resources/devices.js\";\nimport {\n CLIENT_HEADER,\n clientHeaderValue,\n resolveClientDescriptor,\n type ClientDescriptor,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\nimport {\n defaultBrowserStore,\n inMemoryStore,\n type TokenStore,\n} from \"./token-store.js\";\nimport type { BrandConfig } from \"./brand.js\";\nimport { resolveAssetUrl } from \"./assets.js\";\n\nexport type { BrandConfig } from \"./brand.js\";\nexport { resolveAssetUrl } from \"./assets.js\";\nexport { ApiError, NetworkError, isApiError, isNetworkError } from \"./error.js\";\nexport { defaultBrowserStore, inMemoryStore, type TokenStore } from \"./token-store.js\";\nexport { SDK_VERSION } from \"./version.js\";\nexport {\n CLIENT_HEADER,\n detectClientPlatform,\n type ClientDescriptor,\n type ClientPlatform,\n type ResolvedClientDescriptor,\n} from \"./client-platform.js\";\n\n// Re-export resource types so consumers can `import { Deposit } from\n// \"@takeal/cusfront-sdk\"` without reaching into sub-paths.\nexport type { Address, CustomerInfo } from \"./types/customer.js\";\nexport type {\n Deposit,\n DepositStatus,\n DepositMethod,\n InitiateDepositInput,\n CreateDepositRefundInput,\n Refund,\n CreateQuoteInput, FundingQuote } from \"./resources/deposits.js\";\nexport type {\n Card,\n CardType,\n CardStatus,\n CardDesignRef,\n CardProduct,\n CardProductPrice,\n CreateCardInput,\n UpdateCardInput,\n CardBalance,\n RevealCardInput,\n RevealedCard,\n} from \"./resources/cards.js\";\nexport type { Balance } from \"./resources/balance.js\";\nexport type { Branding } from \"./resources/branding.js\";\nexport type { Wallet } from \"./resources/wallet.js\";\nexport type { BlogPost, BlogBlock, BlogList, BlogListInput } from \"./resources/blog.js\";\nexport type {\n Subscriptions,\n BroadcastChannel,\n} from \"./resources/subscriptions.js\";\nexport type {\n User,\n LoginInput,\n LoginResponse,\n JwtIssued,\n TotpRequired,\n TotpSetupRequired,\n OtpSentResponse,\n RegisterInput,\n Session,\n TotpSetupComplete,\n ChangePasswordInput,\n TelegramLink,\n TelegramUnknown,\n ExchangeTelegramInput,\n LinkTelegramInput,\n} from \"./resources/auth.js\";\nexport type { MeResource } from \"./resources/me.js\";\nexport type { UserSession } from \"./resources/sessions.js\";\nexport type {\n PushStatus,\n PushSubscriptionInput,\n PushCapableRegistration,\n} from \"./resources/push.js\";\nexport { isCardOtp } from \"./resources/notifications.js\";\nexport type {\n NotificationCategory,\n NotificationChannel,\n NotificationLocale,\n InboxItem,\n CardOtpData,\n NotificationPage,\n ListNotificationsParams,\n NotificationCategoryPreferences,\n NotificationPreferences,\n NotificationPreferencesInput,\n} from \"./resources/notifications.js\";\nexport type {\n DeviceKind,\n DevicePlatform,\n Device,\n WebPushCredential,\n MobilePushCredential,\n RegisterDeviceInput,\n RegisteredDevice,\n RegisterWebPushOptions,\n UnregisterWebPushOptions,\n} from \"./resources/devices.js\";\n\nexport interface CreateClientOptions {\n /** Absolute origin of the Takeal API deployment, no trailing slash.\n * e.g. `\"https://api.takeal.example.com\"`. */\n baseUrl: string;\n /** Runtime brand config. Optional; consumer renders its own brand\n * if omitted. */\n brand?: BrandConfig;\n /** What kind of app this is, sent on every request as\n * `X-Takeal-Client: <platform>; <version>`. The server uses it to spot\n * a sign-in from a new device and to pick the notification channel.\n * `platform` is detected at runtime when omitted (`telegram-miniapp`\n * inside Telegram, `pwa` when installed, `web` otherwise); `version`\n * defaults to the SDK version. Native wrappers should pass\n * `{ platform: \"ios\" | \"android\", version }`. */\n client?: ClientDescriptor;\n /** Token persistence. Defaults to `defaultBrowserStore()` when\n * `window.localStorage` is present, else `inMemoryStore()`. */\n tokenStore?: TokenStore;\n /** Override the `fetch` implementation — useful for Node < 18,\n * React Native < 0.74, MSW intercept layers, etc. */\n fetch?: FetchLike;\n /** When true, the SDK runs every response through a zod schema\n * before handing it to the caller. Requires `zod` >= 3.22 as a\n * peer dep. Off by default; types-only validation is sufficient\n * for the steady-state case. */\n validate?: boolean;\n}\n\nexport interface CusfrontClient {\n /** Read-only brand config — pass through from createClient args. */\n readonly brand: BrandConfig | undefined;\n /** The platform and version this client announces in `X-Takeal-Client`. */\n readonly client: ResolvedClientDescriptor;\n /** Auth resource: login, refresh, current user, logout. */\n readonly auth: AuthResource;\n /** Deposits (money IN via a funder connector): initiate, get, list, refund. */\n readonly deposits: DepositsResource;\n /** Cards (money OUT via an issuer connector): the product catalog, create, get, list, update, balance. */\n readonly cards: CardsResource;\n /** Wallet balance lookup (defaults to the wallet's own currency). */\n readonly balance: BalanceResource;\n /** The wallet's currency: read it, switch it while the wallet is empty. */\n readonly wallet: WalletResource;\n /** Runtime white-label config (`GET /branding`, public): names, logo, wallet label. */\n readonly branding: BrandingResource;\n /** Public blog posts, returned as structured blocks to render in your own style. */\n readonly blog: BlogResource;\n /** The user's announcement channel subscriptions.\n * @deprecated Use `notifications.setPreferences({ categories: { marketing: {...} } })`. */\n readonly subscriptions: SubscriptionsResource;\n /** Where the user is signed in: list sessions, sign one or all others out. */\n readonly sessions: SessionsResource;\n /** Web Push subscription for the signed-in user.\n * @deprecated Use `devices.registerWebPush` / `devices.unregisterWebPush`. */\n readonly push: PushResource;\n /** The user's inbox and notification preferences. */\n readonly notifications: NotificationsResource;\n /** The user's devices: browsers with Web Push, phones, the Telegram Mini App. */\n readonly devices: DevicesResource;\n /** Profile actions for the signed-in user: link or unlink Telegram. */\n readonly me: MeResource;\n /** Direct access to the token store (e.g. for an explicit sign-out\n * on Capacitor's lifecycle \"app pausing\" event). */\n readonly tokens: TokenStore;\n /**\n * Turn an image URL from the API (`card.design.image_url`,\n * `product.design.image_url`) into one a browser can load. Absolute URLs\n * pass through; a path relative to the API origin (the default card\n * design, `/card-designs/default.svg`) is joined onto `baseUrl`.\n */\n assetUrl(url: string): string;\n}\n\n/**\n * Build a new client. Stateless across calls — multiple clients can\n * coexist (e.g. an admin Cusfront with a different baseUrl than the\n * end-user one). Each gets its own `TokenStore`.\n *\n * `validate: true` is honoured by individual resources that ship\n * matching zod schemas; resources without a schema ignore it.\n */\nexport function createClient(opts: CreateClientOptions): CusfrontClient {\n const tokens = opts.tokenStore ?? pickDefaultStore();\n const fetchImpl = opts.fetch ?? defaultFetch();\n const client = resolveClientDescriptor(opts.client);\n const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {\n [CLIENT_HEADER]: clientHeaderValue(client),\n });\n\n return {\n brand: opts.brand,\n client,\n tokens,\n assetUrl: (url: string) => resolveAssetUrl(opts.baseUrl, url),\n auth: new AuthResource(http, tokens),\n deposits: new DepositsResource(http),\n cards: new CardsResource(http),\n balance: new BalanceResource(http),\n wallet: new WalletResource(http),\n branding: new BrandingResource(http),\n blog: new BlogResource(http),\n subscriptions: new SubscriptionsResource(http),\n sessions: new SessionsResource(http),\n push: new PushResource(http),\n me: new MeResource(http),\n notifications: new NotificationsResource(http),\n devices: new DevicesResource(http, client),\n };\n}\n\nfunction pickDefaultStore(): TokenStore {\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n return defaultBrowserStore();\n }\n return inMemoryStore();\n}\n\nfunction defaultFetch(): FetchLike {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.fetch === \"function\") {\n // Bind to globalThis so `this` is correct inside the implementation\n // (some polyfills choke on a detached reference).\n return globalThis.fetch.bind(globalThis);\n }\n throw new Error(\n \"@takeal/cusfront-sdk: native fetch is not available in this runtime. \" +\n \"Pass a polyfill via createClient({ fetch }).\",\n );\n}\n"]}
@@ -80,8 +80,8 @@ var CardsResource = class {
80
80
  );
81
81
  }
82
82
  /**
83
- * Reveal the FULL PAN + CVV for the caller's own card. Re-auth gated
84
- * (password, + TOTP when the user has it enrolled) and rate-limited
83
+ * Reveal the FULL PAN + CVV for the caller's own card. The signed-in
84
+ * session is all the API asks for; the call is rate-limited and audited
85
85
  * server-side. The Takeal API never persists this data and marks the
86
86
  * response no-store; the SDK returns it verbatim and holds nothing.
87
87
  *
@@ -92,11 +92,8 @@ var CardsResource = class {
92
92
  * 401 bad re-auth · 403 not your card · 429 rate-limited · 501 connector
93
93
  * has no sensitive-data endpoint · 503 provider error.
94
94
  */
95
- async reveal(id, input) {
96
- return this.http.post(
97
- `/me/cards/${encodeURIComponent(id)}/reveal`,
98
- { body: { password: input.password, totp_code: input.totpCode } }
99
- );
95
+ async reveal(id, _input) {
96
+ return this.http.post(`/me/cards/${encodeURIComponent(id)}/reveal`);
100
97
  }
101
98
  /** Unfreeze a previously-frozen card. Idempotent on an already-active card. */
102
99
  async unfreeze(id) {