@takeal/cusfront-sdk 0.8.0 → 0.8.1
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/CHANGELOG.md +33 -0
- package/README.md +2 -1
- package/dist/analytics.cjs +88 -7
- package/dist/analytics.cjs.map +1 -1
- package/dist/analytics.d.cts +30 -2
- package/dist/analytics.d.ts +30 -2
- package/dist/analytics.js +86 -8
- package/dist/analytics.js.map +1 -1
- package/dist/index.cjs +92 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +92 -12
- package/dist/index.js.map +1 -1
- package/dist/resources/auth.cjs +6 -4
- package/dist/resources/auth.cjs.map +1 -1
- package/dist/resources/auth.d.cts +10 -4
- package/dist/resources/auth.d.ts +10 -4
- package/dist/resources/auth.js +6 -4
- package/dist/resources/auth.js.map +1 -1
- package/dist/telegram.cjs +7 -5
- package/dist/telegram.cjs.map +1 -1
- package/dist/telegram.js +7 -5
- package/dist/telegram.js.map +1 -1
- package/package.json +1 -1
package/dist/resources/auth.cjs
CHANGED
|
@@ -306,10 +306,12 @@ var AuthResource = class {
|
|
|
306
306
|
await Promise.resolve(this.tokens.set(resp.access_token));
|
|
307
307
|
return resp;
|
|
308
308
|
}
|
|
309
|
-
/**
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
* {@link requestEmailChange} and {@link confirmEmailChange}
|
|
309
|
+
/** Always answers 409 `email_change_needs_code` on platform 0.8.1 and
|
|
310
|
+
* newer: an address is attached only after a code sent to it comes back.
|
|
311
|
+
* For the first real email of a Telegram-made account use
|
|
312
|
+
* {@link requestEmailChange} and {@link confirmEmailChange}; they clear
|
|
313
|
+
* `email_pending` too.
|
|
314
|
+
* @deprecated Use {@link requestEmailChange} and {@link confirmEmailChange}. */
|
|
313
315
|
async linkEmail(input) {
|
|
314
316
|
return this.http.post("/me/email", { body: { email: input.email } });
|
|
315
317
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/error.ts","../../src/resources/attribution.ts","../../src/resources/cards.ts","../../src/resources/auth.ts"],"names":[],"mappings":";;;AA2CO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,IAAS,EAA+B,UAAA,KAAe,IAAA;AAC/F;;;AC8HA,SAAS,WAAW,IAAA,EAAkC;AACpD,EAAA,MAAM,MAAO,UAAA,CAAuC,QAAA;AACpD,EAAA,IAAI,CAAC,GAAA,EAAK,MAAA,EAAQ,OAAO,MAAA;AACzB,EAAA,KAAA,MAAW,IAAA,IAAQ,GAAA,CAAI,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AACxC,IAAA,MAAM,CAAC,GAAG,GAAG,CAAC,IAAI,IAAA,CAAK,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,CAAA;AACvC,IAAA,IAAI,MAAM,IAAA,EAAM,OAAO,mBAAmB,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT;AAqEA,IAAM,OAAA,GAAU,sBAAA;AAEhB,SAAS,OAAA,GAA+B;AACtC,EAAA,IAAI;AACF,IAAA,OAAQ,UAAA,CAA0C,YAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,MAAA,GAAuB;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,OAAA,EAAQ,EAAG,OAAA,CAAQ,OAAO,CAAA;AACtC,IAAA,MAAM,IAAI,GAAA,GAAO,IAAA,CAAK,KAAA,CAAM,GAAG,IAAqB,EAAC;AACrD,IAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,GAAO,IAAI,EAAC;AAAA,EACpD,CAAA,CAAA,MAAQ;AACN,IAAA,OA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B,KAAA,EAAyD;AAChF,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAA2B,kBAAA,EAAoB;AAAA,MAC9D,IAAA,EAAM,EAAE,KAAA,EAAO,KAAA,CAAM,KAAA;AAAM,KAC5B,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,mBAAmB,KAAA,EAA6D;AACpF,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,0BAAA,EAA4B;AAAA,MACtD,MAAM,EAAE,YAAA,EAAc,MAAM,WAAA,EAAa,IAAA,EAAM,MAAM,IAAA;AAAK,KAC3D,CAAA;AAAA,EACH;AAAA;AAAA;AAAA,EAIA,MAAM,EAAA,GAAoB;AACxB,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAU,UAAU,CAAA;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,UAAA,GAAa,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,GAAA,EAAK,CAAA,GAAI,IAAA;AAClF,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,cAAA,EAAgB;AAAA,QACzC,MAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,QAAA,KAAa,EAAC;AAAA,QACjD,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,IAAA,CAAK,YAAY,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,EACpE;AACF","file":"auth.cjs","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(\n message: string,\n public readonly cause?: unknown,\n ) {\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 typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\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 type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n","import type { Claim } from \"./claims.js\";\nimport type { CodeDiscount, CodeEffect, CodeRejection } from \"./codes.js\";\nimport type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\nimport type { Deposit, DepositMethod } from \"./deposits.js\";\nimport { analyticsIds, type AnalyticsIds } from \"./attribution.js\";\nimport { isApiError } from \"../error.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 /card-products → catalog (public, before sign-in)\n * GET /me/card-products → listProducts (the catalog, personal price)\n * GET /me/card-products/{id} → getProduct\n * GET /me/cards/{id}/topup → topUpTerms\n * POST /me/cards/{id}/topup → topUp\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}/report-lost → reportLost (lost or stolen: frozen at once)\n * POST /me/cards/{id}/transfer → transfer (to another of their cards)\n * POST /me/cards/{id}/terminate → terminate (one-way)\n * POST /me/cards/{id}/reveal → reveal (the numbers, or a provider page)\n * POST /me/cards/{id}/pin → setPin (physical cards)\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 * 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`: an order waiting for its payment, not a card yet.\n * It has no digits and no expiry, and nothing can be done with it:\n * revealing, freezing, closing or renaming it answers 409 `card_pending`.\n * Show it as \"waiting for payment\", without a way into the card's page.\n * - `pending`: the issuer accepted the order and has not issued the card\n * yet. The price is charged. Show the card as \"being issued\" with no\n * numbers; it becomes `active` on its own, or `failed` with the price\n * back on the wallet. Some issuers take minutes, some a day.\n * - `active`, `frozen`: the usual states. Read `status_source` before\n * offering to unfreeze.\n * - `terminating`: the holder (or the issuer) closed the card and the\n * issuer has not finished: the balance comes back to the wallet when it\n * does. Show it as closing; no actions apply.\n * - `terminated`, `redeemed`, `failed`: final.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"pending\"\n | \"active\"\n | \"frozen\"\n | \"terminating\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * Who made the card's last status change. `provider` on a `frozen` card\n * means the issuer froze it (a risk check, a lost-card report): the holder\n * cannot unfreeze it, so do not offer the button; say the freeze is lifted\n * through the issuer's support. `holder` and `operator` freezes are undone\n * with `unfreeze()` as usual.\n */\nexport type CardStatusSource = \"holder\" | \"operator\" | \"provider\";\n\n/** `virtual` cards show their numbers in the app; `physical` cards are plastic and have a PIN. */\nexport type CardForm = \"virtual\" | \"physical\";\n\n/**\n * Why `terminate()` is refused right now: `first_purchase_required` (the\n * card closes after its first purchase) or `card_locked` (only support can\n * change it).\n */\nexport type CloseBlockedReason = \"first_purchase_required\" | \"card_locked\";\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 /** What the user pays, decimal string, after their subscription discount. */\n amount: string;\n /**\n * ISO 4217 code: the currency the operator priced the card in, the same\n * before and after sign-in. A card order paid in this currency costs\n * exactly `amount`. It is not necessarily the currency the card is held\n * in (`CardProduct.currency`).\n */\n currency: string;\n /** Wording for the fee line, e.g. \"Card issuance\". */\n label: string;\n /** The list price before the discount, decimal string, in the same currency. */\n base_amount: string;\n /** Discount applied, in basis points (1000 = 10%). */\n discount_bps: number;\n /**\n * What issuing costs when paid from the wallet, converted the way that\n * purchase charges it. Only for a signed-in user whose wallet holds another\n * currency than the price; absent otherwise, and when there is no rate.\n */\n from_wallet?: { amount: string; currency: string } | null;\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. The list comes in the\n * order the operator arranged the storefront; `is_default` marks the\n * product issued when none is chosen, wherever it sits. `designs` is the\n * set the user may pick from (may be empty when only the default applies);\n * `design` is what the card gets when no choice is made. `price` is `null`\n * for a 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 /** One line under the name on the tile, or `null`. */\n tagline: string | null;\n description: string | null;\n /** Selling points to list on the product card, in order. May be empty. */\n benefits: string[];\n /**\n * Picture for the product tile, absolute URL, or `null`: show the card\n * design (`design.image_url`) then.\n */\n tile_image_url: 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 /**\n * The balance a new card comes with, already included in `price`; `null`\n * when the card starts empty and is funded with `topUp()` afterwards.\n */\n starting_balance: CardBalance | null;\n /** True for the product the deployment issues when none is chosen. */\n is_default: boolean;\n /**\n * Issuing this card sends the user's real personal details to the card\n * issuer. Show the consent screen before the order and send\n * `holder_data_transfer` in its `consents` (or give it once with\n * `client.consents.allowHolderData()`); without it the order fails with\n * 409 `holder_data_consent_required`. `false`: the issuer gets no real\n * details and no extra consent is asked.\n */\n holder_data_required: boolean;\n /**\n * What a card on this product costs to use, on top of the payments\n * themselves. A fee the card can't cover is owed and paid from the next\n * top-up (see `client.debt`). Every line is `\"0\"` when the product\n * charges nothing for it.\n */\n tariff: CardTariff;\n}\n\n/**\n * A card product's fees for using the card. Decimal strings: the fixed\n * amounts are in `currency` (the card's), the shares in percent of the\n * operation's amount.\n */\nexport interface CardTariff {\n /** `null` for a product held in several currencies: the card's own then. */\n currency: string | null;\n /** Per settled card payment, fixed. */\n operation_fixed: string;\n /** Per settled card payment, percent of its amount. */\n operation_percent: string;\n /**\n * Per payment declined through the user's own doing: not enough money,\n * wrong card details, a frozen card, a subscription not cancelled with the\n * merchant. A decline caused by the issuer or the platform costs nothing.\n */\n decline: string;\n /** Per cash withdrawal, fixed; charged instead of the payment fee. */\n cash_withdrawal_fixed: string;\n /** Per cash withdrawal, percent of its amount. */\n cash_withdrawal_percent: string;\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. Null until the card is paid for and issued. */\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 /** The balance the card was issued with, decimal string; `null` or `\"0\"` for a card issued empty. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n /** Who changed the status last; `null` when it never changed. See {@link CardStatusSource}. */\n status_source: CardStatusSource | null;\n /** Virtual or plastic. A `physical` card takes a PIN with {@link CardsResource.setPin}. */\n card_form: CardForm;\n /** Why the card cannot be closed right now, or `null` when it can. */\n close_blocked: CloseBlockedReason | null;\n /**\n * Top-ups the issuer has accepted and not loaded yet, summed, decimal\n * string in `currency`; `null` when there are none. It counts top-ups from\n * the wallet and top-ups paid straight to the card. Show it next to the\n * balance as money on its way to the card.\n */\n topups_pending: string | null;\n /**\n * `true` while the card's details are being prepared: the card can be\n * used and topped up, but its number can't be shown yet. Show \"Details\n * are being prepared\" instead of the reveal button and refresh the card\n * later; it turns `false` on its own, usually within minutes. Absent\n * from platforms before 0.7.6.\n */\n details_pending?: boolean;\n /**\n * Top-ups the issuer has held for too long, summed, decimal string in\n * `currency`; `null` when there are none. The money is safe and waits for\n * support to settle it; say so instead of offering a retry.\n */\n topups_held: string | null;\n /**\n * The card this one replaced: support reissued it for free because that\n * card stopped working before its term. `null` otherwise.\n */\n reissued_from_card_id?: string | null;\n /** The card support issued to replace this one, or `null`. */\n reissued_to_card_id?: string | null;\n /**\n * What was left on the card this one replaced, on its way here. Show it as\n * money in transit next to the balance, not as part of it. `null` when\n * nothing is on its way.\n */\n in_transit?: CardInTransit | 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 /** Only on the result of `create`, when bonuses paid part of the price. */\n bonus?: IssuanceBonus;\n}\n\n/**\n * The balance of a closed card on its way to the card that replaced it. It\n * waits for the old card's issuer to return the money (`stage: \"issuer\"`),\n * then it is loaded onto this card (`stage: \"loading\"`); once it is there,\n * `in_transit` is `null` and the card's balance has it. The move is in the\n * history as a `closed_card_balance` entry.\n */\nexport interface CardInTransit {\n /** Decimal string in `currency`. What the issuer returned once it did; before that, what the old card held. */\n amount: string;\n currency: string;\n /** The closed card the money comes from. */\n from_card_id: string;\n stage: \"issuer\" | \"loading\" | (string & {});\n}\n\n/** How bonuses changed a new card's price (\"was / now\"). Decimal strings in `currency`. */\nexport interface IssuanceBonus {\n /** Bonuses used. */\n units: string;\n /** The price before bonuses (\"was\"). */\n price: string;\n /** What the bonuses covered. */\n covered: string;\n /** What the wallet paid (\"now\"). */\n paid: string;\n currency: 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 /**\n * @deprecated Ignored since 0.3.21. A card is issued for its product price;\n * the balance it starts with, if the product includes one, is part of that\n * price (see `CardProduct.starting_balance`). Money is added afterwards\n * with {@link CardsResource.topUp}. The field is no longer sent.\n */\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 * Pay part of the price with bonuses. Sent as `use_bonus`. On by default\n * whenever the user has bonuses; `false` pays it all from the wallet.\n */\n useBonus?: boolean;\n /** The most bonuses to use, decimal string. Sent as `bonus_amount`. */\n bonusAmount?: string;\n /**\n * A promo code for the card's price. Sent as `promo_code`. Its discount\n * comes off before bonuses; `client.codes.validate` shows it first. A code\n * that can't be used fails the request with 400 `promo_code_*` and the\n * reason. Without one, the code the user signed up with applies when it\n * covers cards. Ignored inside `deposits.initiate({ issue_card })`: send\n * `promo_code` on the top-up there.\n */\n promoCode?: string;\n /**\n * Consents the user gave with the order (`terms`, `personal_data`,\n * `marketing`, `holder_data_transfer`). Recorded with the card, or with the\n * top-up inside `deposits.initiate({ issue_card })`, at the version of\n * their documents in force now. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\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/**\n * The wire body of a card request: the camelCase fields renamed to what\n * the API reads. Shared by {@link CardsResource.create} and the\n * `issue_card` block of `deposits.initiate`.\n */\nexport function cardRequestBody(\n input: Omit<CreateCardInput, \"idempotencyKey\" | \"currency\"> & { currency?: string },\n): Record<string, unknown> {\n const {\n productId,\n name,\n designId,\n useBonus,\n bonusAmount,\n promoCode,\n consentChannel,\n initial_amount: _ignored,\n ...rest\n } = 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 if (useBonus !== undefined) body[\"use_bonus\"] = useBonus;\n if (bonusAmount !== undefined) body[\"bonus_amount\"] = bonusAmount;\n if (promoCode !== undefined) body[\"promo_code\"] = promoCode;\n if (consentChannel !== undefined) body[\"consent_channel\"] = consentChannel;\n return body;\n}\n\n/**\n * A card bought in one step with {@link CardsResource.order}: the product and\n * how the user pays. The platform works out the amount to pay in the\n * payment's currency, locks the rate and opens the top-up that issues the\n * card.\n */\nexport interface CardOrderInput {\n /** A product id from {@link CardsResource.listProducts}. Sent as `product_id`. */\n productId: string;\n /** One of the product's designs; omit for its default. Sent as `design_id`. */\n designId?: string;\n /** A name for the card, 1 to 40 characters; defaults to the product name. */\n name?: string;\n /** How the user pays, e.g. `\"sbp\"`. */\n method: DepositMethod;\n /** The funding connector to pay through; omit to let the API pick one that takes `method`. Sent as `funder_slug`. */\n funderSlug?: string;\n /** ISO 4217 code of the payment; defaults to the currency the method is priced in. */\n currency?: string;\n /** Money to put on the card on top of its price, decimal string in the card's currency. Sent as `extra_load`. */\n extraLoad?: string;\n /** A promo code for the payment. Sent as `promo_code`. */\n promoCode?: string;\n /** Pay part of the price with bonuses; on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n /**\n * Consents given with the order. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Passed to the payment provider; `return_url` is where the payment page sends the user back. */\n metadata?: Record<string, string>;\n /** The visitor's analytics ids for the order's server-side conversions.\n * Leave out to send the ones this browser holds (see `analyticsIds`). */\n analyticsIds?: AnalyticsIds;\n /**\n * The amount the user was shown and agreed to pay: `amount` of the\n * quote. If the order comes to anything else, no payment is opened and\n * the API answers 409 `price_changed` with the new quote (see\n * {@link priceChangedQuote}). Leave it out and the payment opens for\n * whatever the order comes to. Sent as `expected_amount`.\n */\n expectedAmount?: string;\n /** `currency` of the same quote. Sent as `expected_currency`. */\n expectedCurrency?: string;\n}\n\n/**\n * A card order to price with {@link CardsResource.quote} or\n * {@link CardsResource.quotePublic}: the same fields as the order.\n */\nexport interface CardOrderQuoteInput {\n /** Sent as `product_id`. */\n productId: string;\n /** Sent as `design_id`. */\n designId?: string;\n method: DepositMethod;\n /** Sent as `funder_slug`. */\n funderSlug?: string;\n currency?: string;\n /** Sent as `extra_load`. */\n extraLoad?: string;\n /** The code the user typed. Sent as `promo_code`. */\n promoCode?: string;\n /** Signed in only: pay part of the price with bonuses, on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n}\n\n/**\n * Where a promo code stands in a quote. `applied`: its discount is in the\n * amount. `conditional` (before sign-in only): it works for someone who\n * meets `conditions`, which are checked after sign-in, and the amount is\n * provisional. `rejected`: it can't be used, for `reason`; an order that\n * keeps the code is refused, so drop it from the order. `unavailable`: it\n * couldn't be checked right now; the amount is without it.\n */\nexport type PromoCodeStatus = \"applied\" | \"conditional\" | \"rejected\" | \"unavailable\";\n\n/** What a promo code does to a card order. */\nexport interface PromoCodeQuote {\n /** The code as stored, or as typed when it wasn't found. */\n code: string;\n status: PromoCodeStatus;\n /** For `rejected`. */\n reason: CodeRejection | null;\n /**\n * For `conditional`: `not_first_operation` (first card only) or\n * `own_code` (not for the person it belongs to).\n */\n conditions: CodeRejection[];\n /** A sentence to show next to the code, in English. Null when the discount says it all. */\n message: string | null;\n /**\n * The discount and what it comes off: `card_issuance` (the card's price,\n * in `discount` of the quote) or `funding_commission` (the payment's\n * commission: the amount stays the same and more goes onto the card).\n */\n discount: CodeDiscount | null;\n /** What else the code gives, once the card is issued. */\n effects: CodeEffect[];\n /** The code the user signed up with, applied without being typed. */\n from_sign_up: boolean;\n}\n\n/** What a card order would cost now, from {@link CardsResource.quote} or {@link CardsResource.quotePublic}. */\nexport interface CardOrderQuote {\n /** What the user pays, decimal string, in `currency`. Pass it to the order as `expectedAmount`. */\n amount: string;\n /** Pass it to the order as `expectedCurrency`. */\n currency: string;\n /** The same order without the promo code, decimal string, in `currency`. */\n price: string;\n /** `price` less `amount`: what the code takes off. `\"0\"` without one. */\n discount: string;\n /** What the payment brings, in `card_currency`, as in {@link CardOrder}. */\n card_amount: string;\n card_currency: string;\n /** Card fees owed, in `card_currency`, included in `card_amount`. Always `\"0\"` before sign-in. */\n debt_withheld: string;\n /** Bonuses that pay part of the price; null before sign-in. */\n bonus_units: string | null;\n /** The amount may still change after sign-in: show it as provisional. */\n preliminary: boolean;\n /** Null when no code was typed and none applies by itself. */\n promo_code: PromoCodeQuote | null;\n}\n\n/** What {@link CardsResource.order} returns: the top-up to pay and its price. */\nexport interface CardOrder {\n /** Send the user to `deposit.redirect_url` when `deposit.status` is `redirect_required`. The card is issued once the payment is confirmed. */\n deposit: Deposit;\n /** What the user pays, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the payment brings: the card's price, what goes onto the card and `debt_withheld`, in `card_currency`. A payment in the price's own currency pays the price as it is set; only the rest is converted. */\n card_amount: string;\n card_currency: string;\n /**\n * What the user owes in card fees, in `card_currency`: included in\n * `card_amount` and paid from it first. `\"0\"` when nothing is owed. Show\n * it before the payment. Older platforms leave it out.\n */\n debt_withheld?: string;\n}\n\n/** Why a card ordered with the sign-up was not placed. The account exists all the same. */\nexport interface CardOrderError {\n code: string;\n message: string;\n /** With `code: \"price_changed\"`: what the card costs now. */\n quote?: CardOrderQuote;\n}\n\n/**\n * The new quote of an order that opened no payment because its price\n * changed (`price_changed`), from either a thrown {@link ApiError} of\n * {@link CardsResource.order} or the `card_order_error` of a sign-in.\n * Show its amount; once the user agrees, send the order again with\n * `expectedAmount` set to it. `undefined` for any other error.\n */\nexport function priceChangedQuote(error: unknown): CardOrderQuote | undefined {\n const body = isApiError(error) ? error.body : error;\n if (typeof body !== \"object\" || body === null) return undefined;\n const { code, quote } = body as { code?: unknown; quote?: unknown };\n if (code !== \"price_changed\" || typeof quote !== \"object\" || quote === null) return undefined;\n return quote as CardOrderQuote;\n}\n\n/** Build the API body of a card order quote. */\nexport function cardOrderQuoteBody(input: CardOrderQuoteInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n return body;\n}\n\n/** Build the API body of a card order. */\nexport function cardOrderBody(input: CardOrderInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.metadata !== undefined) body[\"metadata\"] = input.metadata;\n const ids = input.analyticsIds ?? analyticsIds();\n if (ids !== undefined) body[\"analytics_ids\"] = ids;\n if (input.expectedAmount !== undefined) body[\"expected_amount\"] = input.expectedAmount;\n if (input.expectedCurrency !== undefined) body[\"expected_currency\"] = input.expectedCurrency;\n return body;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n /**\n * From `cards.balance()` only: top-ups the issuer has accepted and not\n * confirmed yet, summed, decimal string in `currency`; `null` when there\n * are none. Not part of `amount`, even when the issuer already shows the\n * money: show it next to the balance as on its way.\n */\n pending?: string | null;\n}\n\n/** What a top-up of a card can be right now, from `GET /me/cards/{id}/topup`. */\nexport interface TopUpTerms {\n /** Whether the card can be topped up at this moment. */\n available: boolean;\n /** Why not, in plain words, when `available` is false. */\n reason: string | null;\n /** Currency top-ups are made in: the card's. */\n currency: string;\n /** What the wallet holds right now, in the wallet's currency. */\n wallet_available: CardBalance;\n /** Smallest single top-up the product allows, or `null` for no floor. */\n min: CardBalance | null;\n /** Largest single top-up the product allows, or `null` for no cap. */\n max: CardBalance | null;\n /**\n * What the user owes in card fees, in the card's currency, or `null` when\n * nothing is. A top-up from a wallet in the same currency pays it first\n * and the card gets the rest: show it before the top-up. Older platforms\n * leave it out.\n */\n debt?: CardBalance | null;\n}\n\nexport interface TopUpInput {\n /** Amount to add, decimal string, in the card's currency. */\n amount: string;\n /**\n * Required. Same key + same amount replays the first outcome; same key +\n * different amount is 409. Use a stable UUID per attempt so a retried\n * network call cannot move the money twice.\n */\n idempotencyKey: string;\n}\n\n/**\n * Where a top-up stands.\n *\n * - `pending`: the issuer accepted it and has not loaded the card yet. The\n * wallet is debited, the card balance is unchanged, the amount shows in\n * `Card.topups_pending`. Most issuers finish within minutes.\n * - `confirmed`: the money is on the card.\n * - `failed`: the issuer refused; the wallet is credited back.\n * - `stalled`: pending for longer than the deployment allows. The money is\n * safe and waits for support; it shows in `Card.topups_held`.\n * - `returned`: support sent the money back to the wallet.\n * - `written_off`: support closed it without the money coming back (the\n * issuer kept it); `failure_reason` says so.\n */\nexport type CardTopUpStatus =\n \"pending\" | \"confirmed\" | \"failed\" | \"stalled\" | \"returned\" | \"written_off\";\n\n/** One top-up attempt as the API records it. */\nexport interface CardTopUp {\n id: string;\n card_id: string;\n status: CardTopUpStatus;\n /** What landed on the card, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the wallet paid, decimal string, in `wallet_currency`. */\n wallet_amount: string;\n wallet_currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * The outcome of a top-up with the state to redraw: card, its balance, the\n * wallet. When `topup.status` is `pending`, the wallet has paid and\n * `card_balance` has not moved yet: show the amount as on its way\n * (`card.topups_pending`) and refresh the card later or on the\n * `card_topup` notification.\n */\nexport interface TopUpResult {\n topup: CardTopUp;\n card: Card;\n card_balance: CardBalance;\n wallet: CardBalance;\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 * What a reveal gave, so a client can switch on one field:\n *\n * - `numbers`: `pan`, `cvv` and the expiry are filled in;\n * - `page`: the issuer shows the numbers on a page of its own, `reveal_url`\n * is set and `pan` and `cvv` are empty;\n * - `pending`: the card's details are still being prepared, nothing else\n * is filled in. Show \"Details are being prepared\" and try again in a\n * minute or two; the attempt didn't count against the reveal limit.\n */\nexport type RevealState = \"numbers\" | \"page\" | \"pending\";\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 *\n * `state` says which of three answers this is (see {@link RevealState}).\n * Some issuers hand out a page that shows the numbers instead of the\n * numbers themselves; for some cards the details are still being prepared\n * right after issuance.\n */\nexport interface RevealedCard {\n /** Which answer this is; set by the SDK from the fields below. */\n state: RevealState;\n /** The card number; empty when `reveal_url` is set. */\n pan: string;\n /** The security code; empty when `reveal_url` is set. */\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /**\n * A page at the card issuer that shows the details to the holder. Present\n * only for issuers that give a page instead of the numbers. Short-lived,\n * often single use: open it at once in an `<iframe>` and never store it.\n */\n reveal_url?: string;\n /**\n * The person the card is registered to at its issuer: what a checkout\n * asks for. Absent for cards issued before holders were kept.\n */\n cardholder?: Cardholder;\n /**\n * The address the card is registered at — what a merchant's checkout asks\n * for, and the postal code some of them decline a payment over. Absent\n * when the deployment has not set one.\n */\n billing_address?: BillingAddress;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n /**\n * `true` when the details are still being prepared (`state: \"pending\"`).\n * Absent from platforms before 0.7.6.\n */\n details_pending?: boolean;\n}\n\n/** The three answers of a reveal told apart; see {@link RevealState}. */\nexport function revealState(r: Omit<RevealedCard, \"state\">): RevealState {\n if (r.details_pending) return \"pending\";\n if (r.reveal_url) return \"page\";\n return \"numbers\";\n}\n\n/** Postal address a card is registered at. Which parts exist depends on the country. */\nexport interface BillingAddress {\n line1?: string;\n line2?: string;\n city?: string;\n state?: string;\n postal_code?: string;\n country?: string;\n}\n\n/**\n * The cardholder the issuer knows: the details to type into a checkout\n * that asks for the name, phone or address on the card. `source` says\n * whether the platform made them up (`generated`), the user supplied them\n * (`provided`) or both (`mixed`).\n */\nexport interface Cardholder {\n id: string;\n first_name: string;\n last_name: string;\n /** `YYYY-MM-DD`. */\n birth_date: string;\n /** E.164. */\n phone: string;\n /** A mailbox the platform owns; mail the issuer sends there reaches the user. */\n email: string;\n address: BillingAddress;\n source: \"generated\" | \"provided\" | \"mixed\";\n}\n\n/** The new PIN for a physical card. */\nexport interface SetPinInput {\n /**\n * Four to six digits, as the user typed them. Sent once to the issuer and\n * kept nowhere: not by the SDK, not by the API. Never log it.\n */\n pin: string;\n}\n\n/** What to move, and the key that makes a retry safe. */\nexport interface TransferInput {\n /** The card the money lands on. Must be the caller's, and of the same kind and currency. */\n toCardId: string;\n /** Amount to move, decimal string, in the cards' currency. */\n amount: string;\n /**\n * Required. The same key with the same body replays the first outcome; a\n * different body on the same key is 409.\n */\n idempotencyKey: string;\n}\n\n/** One transfer attempt as the API records it. */\nexport interface CardTransfer {\n id: string;\n from_card_id: string;\n to_card_id: string;\n /**\n * `confirmed` — the money is on the other card. `on_wallet` — it came off\n * the first card but the second did not take it, so it is on the wallet\n * and `failure_reason` says so in words. `pending` / `failed` otherwise.\n */\n status: \"pending\" | \"confirmed\" | \"on_wallet\" | \"failed\";\n amount: string;\n currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A finished transfer with the balances to redraw both cards and the wallet. */\nexport interface TransferResult {\n transfer: CardTransfer;\n from_balance: CardBalance;\n to_balance: CardBalance;\n /** Holds the money when `transfer.status` is `on_wallet`. */\n wallet: CardBalance;\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 * Errors: 409 `holder_data_consent_required` when the product has\n * `holder_data_required` and the user has not agreed to it.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, ...card } = input;\n return this.http.post<Card>(\"/me/cards\", {\n body: cardRequestBody(card),\n idempotencyKey,\n });\n }\n\n /**\n * Buy a card in one step: the API prices the product in the payment's\n * currency, locks the rate and opens the top-up that issues the card.\n * Send the user to `order.deposit.redirect_url`; the card shows as\n * `pending_payment` until the payment is confirmed. The same\n * `idempotencyKey` returns the same order.\n * Errors: 400 `unknown_product` / `method_not_available` / a limit of the\n * way of paying, 409 `holder_data_consent_required` (the product has\n * `holder_data_required` and the user has not agreed to it), 409\n * `payments_on_hold` (a payment on this account was not accepted and new\n * ones wait until support sorts it out: show the message and point the\n * user to support), 409 `price_changed` (the order came to another amount\n * than `expectedAmount`; no payment was opened, and\n * {@link priceChangedQuote} gives the new quote), 503 no funding connector\n * or no exchange rate.\n */\n async order(input: CardOrderInput & { idempotencyKey: string }): Promise<CardOrder> {\n const { idempotencyKey, ...order } = input;\n return this.http.post<CardOrder>(\"/me/card-orders\", {\n body: cardOrderBody(order),\n idempotencyKey,\n });\n }\n\n /**\n * What an order of this card would cost the signed-in user now, with the\n * promo code: the same calculation {@link order} makes, with every\n * condition of the code checked. Nothing is reserved or used up. Pass\n * `amount` and `currency` to the order as `expectedAmount` and\n * `expectedCurrency`.\n */\n async quote(input: CardOrderQuoteInput): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/me/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n });\n }\n\n /**\n * The same quote before sign-in, for a landing page or the purchase form\n * before the e-mail code. Prices are list prices, and a code whose\n * conditions depend on the person (first card only, say) comes back\n * `conditional`, with `preliminary` set. Send `expectedAmount` with the\n * order placed at sign-in: if the price turns out different, no payment\n * is opened and `card_order_error` carries the new quote. The API limits\n * how often one address can ask (429 `too_many_requests`).\n */\n async quotePublic(input: Omit<CardOrderQuoteInput, \"useBonus\">): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n skipAuth: true,\n });\n }\n\n /**\n * The cards the caller can order, in the order the storefront shows them\n * (`is_default` marks the one issued when none is chosen). Each item\n * carries its product card (name, tagline, benefits, tile picture),\n * artwork, and the issuance price after the caller's subscription\n * discount, in the currency the operator set it in (`price.from_wallet`\n * is the same price from the wallet, when that holds another currency).\n * Pass an item's `id` as\n * `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>(`/me/card-products/${encodeURIComponent(id)}`);\n }\n\n /**\n * The public catalog: the same products, order and default as\n * {@link listProducts}, but readable before sign-in, for a landing page or\n * the cabinet's first screen. Prices are list prices (`discount_bps` is\n * always 0); once the user is signed in, {@link listProducts} shows what\n * they pay. The API lets caches keep this response for a minute.\n */\n async catalog(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/card-products\");\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>(`/me/cards/${encodeURIComponent(id)}/balance?${q}`);\n }\n\n /**\n * What a top-up of this card can be right now: whether it is possible, the\n * currency, the wallet balance, and the product's floor and cap for one\n * top-up. Read it before drawing the form. 404 if the card isn't the caller's.\n */\n async topUpTerms(id: string): Promise<TopUpTerms> {\n return this.http.get<TopUpTerms>(`/me/cards/${encodeURIComponent(id)}/topup`);\n }\n\n /**\n * Move money from the wallet onto the caller's own card. The wallet is\n * debited first, then the card's provider loads the card; if the provider\n * refuses, the money is back on the wallet and the error says so. Resolves\n * to the card, its new balance and the wallet balance, so no second call\n * is needed. Errors carry a sentence the user can read: 400 outside the\n * floor or cap · 402 not enough in the wallet · 404 not the caller's card ·\n * 409 card frozen, closed or still being issued · 501 provider can't top\n * up · 502/503 provider declined or unreachable (wallet untouched).\n */\n async topUp(id: string, input: TopUpInput): Promise<TopUpResult> {\n const { idempotencyKey, amount } = input;\n return this.http.post<TopUpResult>(`/me/cards/${encodeURIComponent(id)}/topup`, {\n body: { amount },\n idempotencyKey,\n });\n }\n\n /**\n * Move money from one of the caller's cards to another. Both must be\n * theirs, active, in the same currency and of the same kind. The money\n * travels through the wallet one leg at a time: when the second leg does\n * not go through, the call still resolves, `transfer.status` is\n * `on_wallet` and the money is on the wallet — never between two cards.\n * Errors carry a sentence the user can read: 400 the same card twice,\n * different currencies or different kinds · 402 the card holds less than\n * that · 404 one of the cards isn't theirs · 409 a card is frozen, closed\n * or still being issued, or the key was reused with a different body ·\n * 501/502/503 the provider cannot or will not move it.\n */\n async transfer(fromCardId: string, input: TransferInput): Promise<TransferResult> {\n const { toCardId, amount, idempotencyKey } = input;\n return this.http.post<TransferResult>(`/me/cards/${encodeURIComponent(fromCardId)}/transfer`, {\n body: { to_card_id: toCardId, amount },\n idempotencyKey,\n });\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze} while\n * `status_source` is `holder` or `operator`. The optional `reason` is\n * recorded on the audit trail. Resolves to the updated card. 404 if the\n * card isn't the caller's; 409 `card_locked` when support holds it; 501 if\n * the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/freeze`, { body: { reason } });\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 * `state` tells the three answers apart: `numbers`; `page`, with\n * `reveal_url` and empty `pan` and `cvv` when the issuer shows them on a\n * page of its own (open that page in a frame right away, it is\n * short-lived); or `pending` while the card's details are still being\n * prepared, which doesn't count against the limit. A card says the same\n * in {@link Card.details_pending}, so there is no need to call this just\n * to find out.\n *\n * 403 not your card · 409 `card_locked` · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 `provider_unavailable`.\n */\n async reveal(id: string, _input?: RevealCardInput): Promise<RevealedCard> {\n const r = await this.http.post<Omit<RevealedCard, \"state\">>(\n `/me/cards/${encodeURIComponent(id)}/reveal`,\n );\n return { ...r, state: revealState(r) };\n }\n\n /**\n * Unfreeze a previously-frozen card. Idempotent on an already-active card.\n * A card the issuer froze (`status_source: \"provider\"`) is not the\n * holder's to unfreeze: the API answers 409 `card_locked`, so hide the\n * button and say the freeze is lifted through the issuer's support.\n */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/unfreeze`, { body: {} });\n }\n\n /**\n * Report the card lost or stolen. Works at any time, on an active or a\n * frozen card. The report is recorded first with the server's time, which\n * decides who pays for operations someone else made; then the card is\n * frozen at its issuer and only support can unfreeze it. Resolves to the\n * claim (`client.claims`): show its `number` and `reported_at`. When the\n * issuer can't be reached, `card_freeze` is `\"pending\"`: the report still\n * counts and support freezes the card by hand. Reporting again while the\n * report is open returns the same claim. 404 / 403 not the user's card ·\n * 409 `card_not_open`: the card is closed or was never issued.\n */\n async reportLost(\n id: string,\n input: { kind: \"lost\" | \"stolen\"; details?: string },\n ): Promise<Claim> {\n return this.http.post<Claim>(`/me/cards/${encodeURIComponent(id)}/report-lost`, {\n body: { kind: input.kind, details: input.details },\n });\n }\n\n /**\n * Set the PIN of the caller's own physical card. The session is enough; the\n * call is rate-limited like {@link reveal} and the PIN is kept nowhere.\n * Resolves to the card; the user also gets a notification that the PIN\n * was set. 400 not four to six digits or the card is not active · 403 not\n * your card · 409 `card_locked`, or `provider_refused` when the issuer did\n * not take it · 429 too many attempts · 501 a virtual card has no PIN.\n */\n async setPin(id: string, input: SetPinInput): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/pin`, {\n body: { pin: input.pin },\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. A card that still holds money is refused (409\n * `move_balance_first` or `contact_support_to_close`): close it with\n * `client.closeRequests.request(id)` instead, and the money goes back the\n * way it was paid.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/terminate`, {\n body: { reason },\n });\n }\n}\n","import type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport { withAnalyticsIds, type SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\nimport {\n cardOrderBody,\n type CardOrder,\n type CardOrderError,\n type CardOrderInput,\n} from \"./cards.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, and signing in (or up) with a code sent\n * to the e-mail, no password. 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 /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\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 /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n /** Consents for a new account, as in `register`. Sent as `consents`;\n * ignored for an account that already exists. */\n consents?: ConsentKind[];\n /** Sent as `consent_channel`; the server takes `miniapp` when omitted. */\n consentChannel?: ConsentChannel;\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 /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\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 /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\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 /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\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 /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n /** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),\n * `personal_data`, `marketing`. A deployment can require the first two\n * (400 `consents_required` without them). */\n consents?: ConsentKind[];\n /** Where they were ticked. Read from the client header when omitted. */\n consent_channel?: ConsentChannel;\n /** Buy this card right after signing up, as `cards.order` would. The\n * sign-up's consents go with the order. The result then carries\n * `card_order` (send the user to its `deposit.redirect_url`) or, when the\n * order could not be placed, `card_order_error`; the account is created\n * either way. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\nexport interface RequestEmailCodeInput {\n email: string;\n /** Language of the e-mail when the address has no account yet (`ru`,\n * `en`, …). An account's own language wins; without either the server\n * reads the browser's. */\n locale?: string;\n}\n\n/** What `requestEmailCode` returns. The same for an address with an account\n * and one without. */\nexport interface EmailCodeSent {\n /** Send it back with the code to `verifyEmailCode`. */\n challenge_id: string;\n /** When the code stops working, ISO-8601. */\n expires_at: string;\n /** When another code can be asked for, ISO-8601: keep \"send again\" off\n * until then. */\n resend_at: string;\n}\n\nexport interface VerifyEmailCodeInput {\n /** From `requestEmailCode`. Sent as `challenge_id`. */\n challengeId: string;\n /** The six digits from the e-mail. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Wallet currency for a new account; ignored for an existing one. Sent\n * as `wallet_currency`. */\n walletCurrency?: string;\n /** Where a new user came from, as in `register`. */\n attribution?: SignupAttribution;\n /** A promo or referral code for a new account, as `code` in `register`.\n * One that covers cards also lowers the price of `cardOrder`. Sent as\n * `promo_code`; the result comes back as `code_result`. */\n promoCode?: string;\n /** The boxes ticked on the form. A new account records them with its\n * sign-up and the card order with itself. A deployment can require\n * `terms` and `personal_data` for a new account: 400\n * `consents_required`, and the same code works again with them. */\n consents?: ConsentKind[];\n /** Where they were ticked. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Buy this card right after signing in, as `cards.order` would, with\n * the consents above. The result carries `card_order` (send the user to\n * its `deposit.redirect_url`) or `card_order_error` when no payment was\n * opened; the sign-in stands either way. Set `expectedAmount` and\n * `expectedCurrency` from `cards.quotePublic`: when the price after\n * sign-in differs (a code for first cards only, say),\n * `card_order_error.code` is `price_changed` and its `quote` holds the\n * new price. Show it, and once the user agrees, order with\n * `cards.order` and the new `expectedAmount`. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\n/** What `verifyEmailCode` returns: a `stage: \"jwt\"` session, plus whether\n * the account was made just now and the card order. */\nexport type EmailCodeSession = JwtIssued & {\n /** `true` when the address had no account and got one with this code. */\n account_created: boolean;\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\n\n/** What `requestEmailChange` returns: send `challenge_id` back with the code. */\nexport interface EmailChangeRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set; with a\n * `cardOrder`, `card_order` or `card_order_error`. */\nexport type Session = Omit<JwtIssued, \"stage\"> & {\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\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\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\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 body: Record<string, unknown> = withRemember(input);\n // The analytics ids go with a sign-in too: the server reports the\n // account's later payments with them.\n const attribution = withAnalyticsIds(undefined);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body,\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\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: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\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: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\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` / `consents_required`\n * / `unknown_consent`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const { cardOrder, ...rest } = input;\n const body: Record<string, unknown> = withRemember(rest);\n const attribution = withAnalyticsIds(rest.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(cardOrder);\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Step one of signing in without a password: a six-digit code goes to\n * the address. It works for an address with an account and for a new one\n * alike, and the answer doesn't say which. The code works for 10 minutes;\n * another can be asked for after `resend_at` and replaces it.\n * Errors: 400 `validation` (not an address), 429 `resend_too_soon` /\n * `too_many_requests` (the message says when to try again), 503\n * `delivery_failed`. */\n async requestEmailCode(input: RequestEmailCodeInput): Promise<EmailCodeSent> {\n const body: Record<string, unknown> = { email: input.email };\n if (input.locale !== undefined) body[\"locale\"] = input.locale;\n return this.http.post<EmailCodeSent>(\"/auth/email-code\", { body, skipAuth: true });\n }\n\n /** Step two: the code signs in to the account with that address, or\n * creates one (no password) when there is none; `account_created` says\n * which. The JWT is stored. With `cardOrder`, the card is ordered for\n * that account in the same call.\n * Errors: 401 `invalid_code` (wrong, expired or used; after five checks a\n * new code is needed), 400 `consents_required` for a new account, 403\n * `user_disabled` / `second_factor_required` (operator accounts sign in\n * with a password and their authenticator). */\n async verifyEmailCode(input: VerifyEmailCodeInput): Promise<EmailCodeSession> {\n const body: Record<string, unknown> = {\n challenge_id: input.challengeId,\n code: input.code,\n };\n if (input.remember) body[\"remember_me\"] = true;\n if (input.walletCurrency !== undefined) body[\"wallet_currency\"] = input.walletCurrency;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(input.cardOrder);\n const resp = await this.http.post<EmailCodeSession>(\"/auth/email-code/verify\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\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: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\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: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n consents?: ConsentKind[];\n consent_channel?: ConsentChannel;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body.attribution = attribution;\n if (input.code !== undefined) body.code = input.code;\n if (input.consents !== undefined) body.consents = input.consents;\n if (input.consentChannel !== undefined) body.consent_channel = input.consentChannel;\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 the first real email to a Telegram-made account (and clear\n * `email_pending`). 409 if taken. An account that already has a real\n * address gets 409 `email_change_needs_code`: change it with\n * {@link requestEmailChange} and {@link confirmEmailChange}. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Step one of an email change: a six-digit code goes to the new address\n * and works for 5 minutes. Nothing changes yet.\n * Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`\n * (five codes an hour). */\n async requestEmailChange(input: { email: string }): Promise<EmailChangeRequested> {\n return this.http.post<EmailChangeRequested>(\"/me/email/change\", {\n body: { email: input.email },\n });\n }\n\n /** Step two: the code from the e-mail changes the address; the old one\n * gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new\n * request is needed), 409 the address was taken meanwhile. */\n async confirmEmailChange(input: { challengeId: string; code: string }): Promise<User> {\n return this.http.post<User>(\"/me/email/change/confirm\", {\n body: { challenge_id: input.challengeId, code: input.code },\n });\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 /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/error.ts","../../src/resources/attribution.ts","../../src/resources/cards.ts","../../src/resources/auth.ts"],"names":[],"mappings":";;;AA2CO,SAAS,WAAW,CAAA,EAA2B;AACpD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,KAAM,IAAA,IAAS,EAA+B,UAAA,KAAe,IAAA;AAC/F;;;AC8HA,SAAS,WAAW,IAAA,EAAkC;AACpD,EAAA,MAAM,MAAO,UAAA,CAAuC,QAAA;AACpD,EAAA,IAAI,CAAC,GAAA,EAAK,MAAA,EAAQ,OAAO,MAAA;AACzB,EAAA,KAAA,MAAW,IAAA,IAAQ,GAAA,CAAI,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AACxC,IAAA,MAAM,CAAC,GAAG,GAAG,CAAC,IAAI,IAAA,CAAK,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,CAAA;A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yB;AAC7B,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,UAAA,GAAa,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,GAAA,EAAK,CAAA,GAAI,IAAA;AAClF,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,cAAA,EAAgB;AAAA,QACzC,MAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,QAAA,KAAa,EAAC;AAAA,QACjD,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,MAAM,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AACzC,IAAA,IAAI,IAAA,CAAK,YAAY,MAAM,OAAA,CAAQ,QAAQ,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,EACpE;AACF","file":"auth.cjs","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(\n message: string,\n public readonly cause?: unknown,\n ) {\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 typeof e === \"object\" && e !== null && (e as { isApiError?: boolean }).isApiError === true;\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 type { HttpClient } from \"../http.js\";\n\n/**\n * Attribution resource — `client.attribution.*`: where users come from.\n *\n * Send a touch on page load ({@link AttributionResource.touch}); the\n * platform keeps the visits that bring something new (campaign tags, a\n * click id, a referrer from another site, a Telegram code, the first visit\n * from this browser) under the visitor's anonymous key. Pass the same key\n * to `auth.register({ attribution })` and the new account is credited with\n * those visits. After sign-up, ask \"how did you hear about us\" once\n * ({@link AttributionResource.status}, {@link AttributionResource.answerSurvey}).\n *\n * ```ts\n * const key = anonymousKey();\n * await client.attribution.touch({ anonymous_key: key, ...currentTouch() });\n * // …later, in the sign-up form:\n * await client.auth.register({ email, password, attribution: { anonymous_key: key } });\n * ```\n */\n\n/** A visit as the browser saw it. {@link currentTouch} fills it from the page. */\nexport interface TouchFields {\n /** Full address of the landing page, query included. Tags and click ids\n * are read from it; anything that looks like an e-mail address, a phone\n * number or a secret is dropped on the server. */\n url?: string;\n /** `document.referrer`; leave out or empty for none. */\n referrer?: string;\n /** The code of a Telegram link to the bot or the Mini App. */\n campaign_code?: string;\n /** `web`, `miniapp` or `app`. Taken from the client's platform when left out. */\n platform?: \"web\" | \"miniapp\" | \"app\";\n /** When the visit happened, ISO 8601, for a touch sent later. Defaults to now. */\n occurred_at?: string;\n /** Yandex Metrica client id (`_ym_uid` cookie). */\n metrika_client_id?: string;\n /** Google Analytics client id (from the `_ga` cookie). */\n ga_client_id?: string;\n}\n\nexport interface TouchInput extends TouchFields {\n /** The visitor's anonymous id, see {@link anonymousKey}. */\n anonymous_key: string;\n}\n\nexport interface TouchResult {\n /** `false` when the visit brought nothing new or the visitor already has fifty touches. */\n recorded: boolean;\n}\n\n/** Sent with `auth.register` and `auth.exchangeTelegram`. */\nexport interface SignupAttribution {\n /** The key the touches were sent with. Ignored in the Mini App, where the\n * Telegram id is the key. */\n anonymous_key?: string;\n /** The first touch this browser kept. Used only when none of its touches\n * reached the server (a blocker, a flaky network). */\n first_touch?: TouchFields;\n /** The last touch before sign-up, on the same terms. */\n last_touch?: TouchFields;\n metrika_client_id?: string;\n ga_client_id?: string;\n /** PostHog distinct id, so a report can open the session recording. */\n posthog_distinct_id?: string;\n}\n\nexport type SurveyAnswer =\n \"friend\" | \"telegram_channel\" | \"search\" | \"ads\" | \"review\" | \"other\" | \"skipped\";\n\n/**\n * The visitor's ids at the analytics platforms (TKL-329). The SDK keeps\n * them from the moment the visitor agreed to analytics cookies and sends\n * them with an order, a top-up and a sign-in, so the server can report the\n * payment and the issued card to the platforms after the person has left\n * for the bank or Telegram. See {@link analyticsIds}.\n */\nexport interface AnalyticsIds {\n /** Yandex Metrica's ClientID, from `getClientID`. A string: it does not fit a number. */\n metrika_client_id?: string;\n /** Google Analytics' client id, from the `_ga` cookie: `1234567890.1700000000`. */\n ga_client_id?: string;\n}\n\nexport interface HandoffToken {\n /** Goes into the Mini App link's `startapp` after two underscores. */\n token: string;\n expires_at: string;\n}\n\nexport interface AttributionStatus {\n /** `true` while the app should ask \"how did you hear about us\". */\n survey_pending: boolean;\n /** The answer given, `skipped`, or `null`. */\n survey_answer: SurveyAnswer | null;\n}\n\nexport class AttributionResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Record a visit. No session needed; safe to call on every page load. */\n async touch(input: TouchInput): Promise<TouchResult> {\n return this.http.post<TouchResult>(\"/attribution/touches\", { body: input, skipAuth: true });\n }\n\n /** A one-day token that carries the visitor's analytics ids into the\n * Telegram Mini App, whose sign-in reads it back. Most callers want\n * {@link AttributionResource.telegramStartParam}. Errors: 400 when none of\n * the ids is valid. */\n async handoff(ids: AnalyticsIds): Promise<HandoffToken> {\n return this.http.post<HandoffToken>(\"/attribution/handoff\", { body: ids, skipAuth: true });\n }\n\n /**\n * The `startapp` value for a link from the site to the Mini App: the code\n * as it is, followed by `__<token>` when the visitor has analytics ids, so\n * a payment made in Telegram is still credited to the visit it came from.\n * Without ids, or when the token can't be had, just the code.\n *\n * ```ts\n * const start = await client.attribution.telegramStartParam(\"SPRING\");\n * location.href = `https://t.me/our_bot/app?startapp=${start}`;\n * ```\n */\n async telegramStartParam(code = \"\"): Promise<string> {\n const ids = analyticsIds();\n if (!ids) return code;\n try {\n const { token } = await this.handoff(ids);\n return `${code}__${token}`;\n } catch {\n return code;\n }\n }\n\n /** Send the visitor's analytics ids for the signed-in account, e.g. right\n * after they agreed to analytics cookies in the cabinet. Without an\n * argument the ids this browser holds are sent; nothing is sent when it\n * holds none. */\n async sendAnalyticsIds(ids: AnalyticsIds | undefined = analyticsIds()): Promise<void> {\n if (!ids) return;\n await this.http.post<void>(\"/me/analytics/ids\", { body: ids });\n }\n\n /** Whether to ask the signed-in user how they heard about us. */\n async status(): Promise<AttributionStatus> {\n return this.http.get<AttributionStatus>(\"/me/attribution\");\n }\n\n /** Answer the question once. Send `\"skipped\"` when the user closes it.\n * `otherText` is kept only with `\"other\"`, up to 500 characters.\n * Errors: 400 `validation`, 409 `survey_answered`. */\n async answerSurvey(answer: SurveyAnswer, otherText?: string): Promise<AttributionStatus> {\n const body: { answer: SurveyAnswer; other_text?: string } = { answer };\n if (otherText !== undefined) body.other_text = otherText;\n return this.http.put<AttributionStatus>(\"/me/attribution/survey\", { body });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Browser helpers\n// ---------------------------------------------------------------------------\n\ninterface TelegramGlobal {\n Telegram?: { WebApp?: { initDataUnsafe?: { user?: { id?: number }; start_param?: string } } };\n}\n\nfunction tgWebApp() {\n return (globalThis as unknown as TelegramGlobal).Telegram?.WebApp?.initDataUnsafe;\n}\n\nfunction readCookie(name: string): string | undefined {\n const doc = (globalThis as { document?: Document }).document;\n if (!doc?.cookie) return undefined;\n for (const part of doc.cookie.split(\";\")) {\n const [k, ...v] = part.trim().split(\"=\");\n if (k === name) return decodeURIComponent(v.join(\"=\"));\n }\n return undefined;\n}\n\nexport interface AnonymousKeyOptions {\n /** Cookie and storage name. Default `takeal_anon`. */\n name?: string;\n /** Cookie domain, e.g. `.example.com` to share the key between the site and the app. */\n cookieDomain?: string;\n}\n\nconst KEY_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/**\n * The visitor's anonymous key. In the Telegram Mini App it is\n * `tg:<telegram id>`. In a browser it is a random id kept both in a cookie\n * and in `localStorage` for a year: if one of the two is lost it comes back\n * from the other, and the cookie's year is renewed on every call while its\n * value never changes. Returns `undefined` outside a browser.\n */\nexport function anonymousKey(opts: AnonymousKeyOptions = {}): string | undefined {\n const tgId = tgWebApp()?.user?.id;\n if (tgId) return `tg:${tgId}`;\n const g = globalThis as { document?: Document; localStorage?: Storage; crypto?: Crypto };\n if (!g.document) return undefined;\n const name = opts.name ?? \"takeal_anon\";\n let stored: string | undefined;\n try {\n stored = g.localStorage?.getItem(name) ?? undefined;\n } catch {\n stored = undefined;\n }\n const fromCookie = readCookie(name);\n let key = [fromCookie, stored].find((k): k is string => !!k && KEY_SHAPE.test(k));\n if (!key) {\n key =\n g.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;\n }\n try {\n g.localStorage?.setItem(name, key);\n } catch {\n // Storage full or blocked: the cookie still holds it.\n }\n const domain = opts.cookieDomain ? `; domain=${opts.cookieDomain}` : \"\";\n g.document.cookie = `${name}=${encodeURIComponent(key)}; max-age=31536000; path=/; SameSite=Lax${domain}`;\n return key;\n}\n\n/** The current page as a touch: address, referrer, the Mini App's start\n * code and the analytics cookies. Empty outside a browser. */\nexport function currentTouch(): TouchFields {\n const g = globalThis as { location?: Location; document?: Document };\n const tg = tgWebApp();\n const out: TouchFields = {};\n if (g.location?.href) out.url = g.location.href;\n if (g.document?.referrer) out.referrer = g.document.referrer;\n if (tg?.start_param) out.campaign_code = tg.start_param;\n if (tg?.user?.id) out.platform = \"miniapp\";\n const ym = readCookie(\"_ym_uid\");\n if (ym) out.metrika_client_id = ym;\n // `_ga` is `GA1.1.<id>.<timestamp>`; the client id is the last two parts.\n const ga = readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\");\n if (ga) out.ga_client_id = ga;\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Analytics ids (TKL-329)\n// ---------------------------------------------------------------------------\n\nconst IDS_KEY = \"takeal_analytics_ids\";\n\nfunction storage(): Storage | undefined {\n try {\n return (globalThis as { localStorage?: Storage }).localStorage;\n } catch {\n return undefined;\n }\n}\n\nfunction stored(): AnalyticsIds {\n try {\n const raw = storage()?.getItem(IDS_KEY);\n const v = raw ? (JSON.parse(raw) as AnalyticsIds) : {};\n return typeof v === \"object\" && v !== null ? v : {};\n } catch {\n return {};\n }\n}\n\nfunction clean(ids: AnalyticsIds): AnalyticsIds | undefined {\n const out: AnalyticsIds = {};\n const ym = ids.metrika_client_id?.trim();\n if (ym && /^\\d{1,32}$/.test(ym)) out.metrika_client_id = ym;\n const ga = ids.ga_client_id?.trim();\n if (ga && /^\\d+\\.\\d+$/.test(ga) && ga.length <= 64) out.ga_client_id = ga;\n return out.metrika_client_id || out.ga_client_id ? out : undefined;\n}\n\n/**\n * Keep analytics ids for this browser, on top of the ones kept before. The\n * Metrica sink of `initAnalytics` calls it with `getClientID`'s answer once\n * the visitor agreed to analytics; call it yourself for another platform.\n */\nexport function rememberAnalyticsIds(ids: AnalyticsIds): void {\n const merged = clean({ ...stored(), ...ids });\n if (!merged) return;\n try {\n storage()?.setItem(IDS_KEY, JSON.stringify(merged));\n } catch {\n // Storage full or blocked: the cookies still hold them.\n }\n}\n\n/** Forget the kept analytics ids: the visitor declined analytics. */\nexport function forgetAnalyticsIds(): void {\n try {\n storage()?.removeItem(IDS_KEY);\n } catch {\n // Nothing kept, or nothing to reach.\n }\n}\n\n/**\n * The visitor's analytics ids: the ones kept by {@link rememberAnalyticsIds},\n * and failing those the platforms' own cookies (`_ym_uid`, `_ga`), which\n * exist only once the visitor agreed to analytics. `undefined` when there\n * are none. The site and the cabinet share them when they share the origin.\n */\nexport function analyticsIds(): AnalyticsIds | undefined {\n const kept = stored();\n return clean({\n metrika_client_id: kept.metrika_client_id ?? readCookie(\"_ym_uid\"),\n ga_client_id: kept.ga_client_id ?? readCookie(\"_ga\")?.split(\".\").slice(-2).join(\".\"),\n });\n}\n\n/** `attribution` with the visitor's analytics ids filled in where it has none. */\nexport function withAnalyticsIds(\n attribution: SignupAttribution | undefined,\n): SignupAttribution | undefined {\n const ids = analyticsIds();\n if (!ids) return attribution;\n return {\n ...attribution,\n metrika_client_id: attribution?.metrika_client_id ?? ids.metrika_client_id,\n ga_client_id: attribution?.ga_client_id ?? ids.ga_client_id,\n };\n}\n","import type { Claim } from \"./claims.js\";\nimport type { CodeDiscount, CodeEffect, CodeRejection } from \"./codes.js\";\nimport type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\nimport type { Deposit, DepositMethod } from \"./deposits.js\";\nimport { analyticsIds, type AnalyticsIds } from \"./attribution.js\";\nimport { isApiError } from \"../error.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 /card-products → catalog (public, before sign-in)\n * GET /me/card-products → listProducts (the catalog, personal price)\n * GET /me/card-products/{id} → getProduct\n * GET /me/cards/{id}/topup → topUpTerms\n * POST /me/cards/{id}/topup → topUp\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}/report-lost → reportLost (lost or stolen: frozen at once)\n * POST /me/cards/{id}/transfer → transfer (to another of their cards)\n * POST /me/cards/{id}/terminate → terminate (one-way)\n * POST /me/cards/{id}/reveal → reveal (the numbers, or a provider page)\n * POST /me/cards/{id}/pin → setPin (physical cards)\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 * 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`: an order waiting for its payment, not a card yet.\n * It has no digits and no expiry, and nothing can be done with it:\n * revealing, freezing, closing or renaming it answers 409 `card_pending`.\n * Show it as \"waiting for payment\", without a way into the card's page.\n * - `pending`: the issuer accepted the order and has not issued the card\n * yet. The price is charged. Show the card as \"being issued\" with no\n * numbers; it becomes `active` on its own, or `failed` with the price\n * back on the wallet. Some issuers take minutes, some a day.\n * - `active`, `frozen`: the usual states. Read `status_source` before\n * offering to unfreeze.\n * - `terminating`: the holder (or the issuer) closed the card and the\n * issuer has not finished: the balance comes back to the wallet when it\n * does. Show it as closing; no actions apply.\n * - `terminated`, `redeemed`, `failed`: final.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"pending\"\n | \"active\"\n | \"frozen\"\n | \"terminating\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * Who made the card's last status change. `provider` on a `frozen` card\n * means the issuer froze it (a risk check, a lost-card report): the holder\n * cannot unfreeze it, so do not offer the button; say the freeze is lifted\n * through the issuer's support. `holder` and `operator` freezes are undone\n * with `unfreeze()` as usual.\n */\nexport type CardStatusSource = \"holder\" | \"operator\" | \"provider\";\n\n/** `virtual` cards show their numbers in the app; `physical` cards are plastic and have a PIN. */\nexport type CardForm = \"virtual\" | \"physical\";\n\n/**\n * Why `terminate()` is refused right now: `first_purchase_required` (the\n * card closes after its first purchase) or `card_locked` (only support can\n * change it).\n */\nexport type CloseBlockedReason = \"first_purchase_required\" | \"card_locked\";\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 /** What the user pays, decimal string, after their subscription discount. */\n amount: string;\n /**\n * ISO 4217 code: the currency the operator priced the card in, the same\n * before and after sign-in. A card order paid in this currency costs\n * exactly `amount`. It is not necessarily the currency the card is held\n * in (`CardProduct.currency`).\n */\n currency: string;\n /** Wording for the fee line, e.g. \"Card issuance\". */\n label: string;\n /** The list price before the discount, decimal string, in the same currency. */\n base_amount: string;\n /** Discount applied, in basis points (1000 = 10%). */\n discount_bps: number;\n /**\n * What issuing costs when paid from the wallet, converted the way that\n * purchase charges it. Only for a signed-in user whose wallet holds another\n * currency than the price; absent otherwise, and when there is no rate.\n */\n from_wallet?: { amount: string; currency: string } | null;\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. The list comes in the\n * order the operator arranged the storefront; `is_default` marks the\n * product issued when none is chosen, wherever it sits. `designs` is the\n * set the user may pick from (may be empty when only the default applies);\n * `design` is what the card gets when no choice is made. `price` is `null`\n * for a 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 /** One line under the name on the tile, or `null`. */\n tagline: string | null;\n description: string | null;\n /** Selling points to list on the product card, in order. May be empty. */\n benefits: string[];\n /**\n * Picture for the product tile, absolute URL, or `null`: show the card\n * design (`design.image_url`) then.\n */\n tile_image_url: 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 /**\n * The balance a new card comes with, already included in `price`; `null`\n * when the card starts empty and is funded with `topUp()` afterwards.\n */\n starting_balance: CardBalance | null;\n /** True for the product the deployment issues when none is chosen. */\n is_default: boolean;\n /**\n * Issuing this card sends the user's real personal details to the card\n * issuer. Show the consent screen before the order and send\n * `holder_data_transfer` in its `consents` (or give it once with\n * `client.consents.allowHolderData()`); without it the order fails with\n * 409 `holder_data_consent_required`. `false`: the issuer gets no real\n * details and no extra consent is asked.\n */\n holder_data_required: boolean;\n /**\n * What a card on this product costs to use, on top of the payments\n * themselves. A fee the card can't cover is owed and paid from the next\n * top-up (see `client.debt`). Every line is `\"0\"` when the product\n * charges nothing for it.\n */\n tariff: CardTariff;\n}\n\n/**\n * A card product's fees for using the card. Decimal strings: the fixed\n * amounts are in `currency` (the card's), the shares in percent of the\n * operation's amount.\n */\nexport interface CardTariff {\n /** `null` for a product held in several currencies: the card's own then. */\n currency: string | null;\n /** Per settled card payment, fixed. */\n operation_fixed: string;\n /** Per settled card payment, percent of its amount. */\n operation_percent: string;\n /**\n * Per payment declined through the user's own doing: not enough money,\n * wrong card details, a frozen card, a subscription not cancelled with the\n * merchant. A decline caused by the issuer or the platform costs nothing.\n */\n decline: string;\n /** Per cash withdrawal, fixed; charged instead of the payment fee. */\n cash_withdrawal_fixed: string;\n /** Per cash withdrawal, percent of its amount. */\n cash_withdrawal_percent: string;\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. Null until the card is paid for and issued. */\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 /** The balance the card was issued with, decimal string; `null` or `\"0\"` for a card issued empty. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n /** Who changed the status last; `null` when it never changed. See {@link CardStatusSource}. */\n status_source: CardStatusSource | null;\n /** Virtual or plastic. A `physical` card takes a PIN with {@link CardsResource.setPin}. */\n card_form: CardForm;\n /** Why the card cannot be closed right now, or `null` when it can. */\n close_blocked: CloseBlockedReason | null;\n /**\n * Top-ups the issuer has accepted and not loaded yet, summed, decimal\n * string in `currency`; `null` when there are none. It counts top-ups from\n * the wallet and top-ups paid straight to the card. Show it next to the\n * balance as money on its way to the card.\n */\n topups_pending: string | null;\n /**\n * `true` while the card's details are being prepared: the card can be\n * used and topped up, but its number can't be shown yet. Show \"Details\n * are being prepared\" instead of the reveal button and refresh the card\n * later; it turns `false` on its own, usually within minutes. Absent\n * from platforms before 0.7.6.\n */\n details_pending?: boolean;\n /**\n * Top-ups the issuer has held for too long, summed, decimal string in\n * `currency`; `null` when there are none. The money is safe and waits for\n * support to settle it; say so instead of offering a retry.\n */\n topups_held: string | null;\n /**\n * The card this one replaced: support reissued it for free because that\n * card stopped working before its term. `null` otherwise.\n */\n reissued_from_card_id?: string | null;\n /** The card support issued to replace this one, or `null`. */\n reissued_to_card_id?: string | null;\n /**\n * What was left on the card this one replaced, on its way here. Show it as\n * money in transit next to the balance, not as part of it. `null` when\n * nothing is on its way.\n */\n in_transit?: CardInTransit | 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 /** Only on the result of `create`, when bonuses paid part of the price. */\n bonus?: IssuanceBonus;\n}\n\n/**\n * The balance of a closed card on its way to the card that replaced it. It\n * waits for the old card's issuer to return the money (`stage: \"issuer\"`),\n * then it is loaded onto this card (`stage: \"loading\"`); once it is there,\n * `in_transit` is `null` and the card's balance has it. The move is in the\n * history as a `closed_card_balance` entry.\n */\nexport interface CardInTransit {\n /** Decimal string in `currency`. What the issuer returned once it did; before that, what the old card held. */\n amount: string;\n currency: string;\n /** The closed card the money comes from. */\n from_card_id: string;\n stage: \"issuer\" | \"loading\" | (string & {});\n}\n\n/** How bonuses changed a new card's price (\"was / now\"). Decimal strings in `currency`. */\nexport interface IssuanceBonus {\n /** Bonuses used. */\n units: string;\n /** The price before bonuses (\"was\"). */\n price: string;\n /** What the bonuses covered. */\n covered: string;\n /** What the wallet paid (\"now\"). */\n paid: string;\n currency: 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 /**\n * @deprecated Ignored since 0.3.21. A card is issued for its product price;\n * the balance it starts with, if the product includes one, is part of that\n * price (see `CardProduct.starting_balance`). Money is added afterwards\n * with {@link CardsResource.topUp}. The field is no longer sent.\n */\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 * Pay part of the price with bonuses. Sent as `use_bonus`. On by default\n * whenever the user has bonuses; `false` pays it all from the wallet.\n */\n useBonus?: boolean;\n /** The most bonuses to use, decimal string. Sent as `bonus_amount`. */\n bonusAmount?: string;\n /**\n * A promo code for the card's price. Sent as `promo_code`. Its discount\n * comes off before bonuses; `client.codes.validate` shows it first. A code\n * that can't be used fails the request with 400 `promo_code_*` and the\n * reason. Without one, the code the user signed up with applies when it\n * covers cards. Ignored inside `deposits.initiate({ issue_card })`: send\n * `promo_code` on the top-up there.\n */\n promoCode?: string;\n /**\n * Consents the user gave with the order (`terms`, `personal_data`,\n * `marketing`, `holder_data_transfer`). Recorded with the card, or with the\n * top-up inside `deposits.initiate({ issue_card })`, at the version of\n * their documents in force now. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\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/**\n * The wire body of a card request: the camelCase fields renamed to what\n * the API reads. Shared by {@link CardsResource.create} and the\n * `issue_card` block of `deposits.initiate`.\n */\nexport function cardRequestBody(\n input: Omit<CreateCardInput, \"idempotencyKey\" | \"currency\"> & { currency?: string },\n): Record<string, unknown> {\n const {\n productId,\n name,\n designId,\n useBonus,\n bonusAmount,\n promoCode,\n consentChannel,\n initial_amount: _ignored,\n ...rest\n } = 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 if (useBonus !== undefined) body[\"use_bonus\"] = useBonus;\n if (bonusAmount !== undefined) body[\"bonus_amount\"] = bonusAmount;\n if (promoCode !== undefined) body[\"promo_code\"] = promoCode;\n if (consentChannel !== undefined) body[\"consent_channel\"] = consentChannel;\n return body;\n}\n\n/**\n * A card bought in one step with {@link CardsResource.order}: the product and\n * how the user pays. The platform works out the amount to pay in the\n * payment's currency, locks the rate and opens the top-up that issues the\n * card.\n */\nexport interface CardOrderInput {\n /** A product id from {@link CardsResource.listProducts}. Sent as `product_id`. */\n productId: string;\n /** One of the product's designs; omit for its default. Sent as `design_id`. */\n designId?: string;\n /** A name for the card, 1 to 40 characters; defaults to the product name. */\n name?: string;\n /** How the user pays, e.g. `\"sbp\"`. */\n method: DepositMethod;\n /** The funding connector to pay through; omit to let the API pick one that takes `method`. Sent as `funder_slug`. */\n funderSlug?: string;\n /** ISO 4217 code of the payment; defaults to the currency the method is priced in. */\n currency?: string;\n /** Money to put on the card on top of its price, decimal string in the card's currency. Sent as `extra_load`. */\n extraLoad?: string;\n /** A promo code for the payment. Sent as `promo_code`. */\n promoCode?: string;\n /** Pay part of the price with bonuses; on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n /**\n * Consents given with the order. A product with `holder_data_required`\n * needs `holder_data_transfer` here unless it was given before.\n */\n consents?: ConsentKind[];\n /** Where they were given. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Passed to the payment provider; `return_url` is where the payment page sends the user back. */\n metadata?: Record<string, string>;\n /** The visitor's analytics ids for the order's server-side conversions.\n * Leave out to send the ones this browser holds (see `analyticsIds`). */\n analyticsIds?: AnalyticsIds;\n /**\n * The amount the user was shown and agreed to pay: `amount` of the\n * quote. If the order comes to anything else, no payment is opened and\n * the API answers 409 `price_changed` with the new quote (see\n * {@link priceChangedQuote}). Leave it out and the payment opens for\n * whatever the order comes to. Sent as `expected_amount`.\n */\n expectedAmount?: string;\n /** `currency` of the same quote. Sent as `expected_currency`. */\n expectedCurrency?: string;\n}\n\n/**\n * A card order to price with {@link CardsResource.quote} or\n * {@link CardsResource.quotePublic}: the same fields as the order.\n */\nexport interface CardOrderQuoteInput {\n /** Sent as `product_id`. */\n productId: string;\n /** Sent as `design_id`. */\n designId?: string;\n method: DepositMethod;\n /** Sent as `funder_slug`. */\n funderSlug?: string;\n currency?: string;\n /** Sent as `extra_load`. */\n extraLoad?: string;\n /** The code the user typed. Sent as `promo_code`. */\n promoCode?: string;\n /** Signed in only: pay part of the price with bonuses, on by default. Sent as `use_bonus`. */\n useBonus?: boolean;\n}\n\n/**\n * Where a promo code stands in a quote. `applied`: its discount is in the\n * amount. `conditional` (before sign-in only): it works for someone who\n * meets `conditions`, which are checked after sign-in, and the amount is\n * provisional. `rejected`: it can't be used, for `reason`; an order that\n * keeps the code is refused, so drop it from the order. `unavailable`: it\n * couldn't be checked right now; the amount is without it.\n */\nexport type PromoCodeStatus = \"applied\" | \"conditional\" | \"rejected\" | \"unavailable\";\n\n/** What a promo code does to a card order. */\nexport interface PromoCodeQuote {\n /** The code as stored, or as typed when it wasn't found. */\n code: string;\n status: PromoCodeStatus;\n /** For `rejected`. */\n reason: CodeRejection | null;\n /**\n * For `conditional`: `not_first_operation` (first card only) or\n * `own_code` (not for the person it belongs to).\n */\n conditions: CodeRejection[];\n /** A sentence to show next to the code, in English. Null when the discount says it all. */\n message: string | null;\n /**\n * The discount and what it comes off: `card_issuance` (the card's price,\n * in `discount` of the quote) or `funding_commission` (the payment's\n * commission: the amount stays the same and more goes onto the card).\n */\n discount: CodeDiscount | null;\n /** What else the code gives, once the card is issued. */\n effects: CodeEffect[];\n /** The code the user signed up with, applied without being typed. */\n from_sign_up: boolean;\n}\n\n/** What a card order would cost now, from {@link CardsResource.quote} or {@link CardsResource.quotePublic}. */\nexport interface CardOrderQuote {\n /** What the user pays, decimal string, in `currency`. Pass it to the order as `expectedAmount`. */\n amount: string;\n /** Pass it to the order as `expectedCurrency`. */\n currency: string;\n /** The same order without the promo code, decimal string, in `currency`. */\n price: string;\n /** `price` less `amount`: what the code takes off. `\"0\"` without one. */\n discount: string;\n /** What the payment brings, in `card_currency`, as in {@link CardOrder}. */\n card_amount: string;\n card_currency: string;\n /** Card fees owed, in `card_currency`, included in `card_amount`. Always `\"0\"` before sign-in. */\n debt_withheld: string;\n /** Bonuses that pay part of the price; null before sign-in. */\n bonus_units: string | null;\n /** The amount may still change after sign-in: show it as provisional. */\n preliminary: boolean;\n /** Null when no code was typed and none applies by itself. */\n promo_code: PromoCodeQuote | null;\n}\n\n/** What {@link CardsResource.order} returns: the top-up to pay and its price. */\nexport interface CardOrder {\n /** Send the user to `deposit.redirect_url` when `deposit.status` is `redirect_required`. The card is issued once the payment is confirmed. */\n deposit: Deposit;\n /** What the user pays, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the payment brings: the card's price, what goes onto the card and `debt_withheld`, in `card_currency`. A payment in the price's own currency pays the price as it is set; only the rest is converted. */\n card_amount: string;\n card_currency: string;\n /**\n * What the user owes in card fees, in `card_currency`: included in\n * `card_amount` and paid from it first. `\"0\"` when nothing is owed. Show\n * it before the payment. Older platforms leave it out.\n */\n debt_withheld?: string;\n}\n\n/** Why a card ordered with the sign-up was not placed. The account exists all the same. */\nexport interface CardOrderError {\n code: string;\n message: string;\n /** With `code: \"price_changed\"`: what the card costs now. */\n quote?: CardOrderQuote;\n}\n\n/**\n * The new quote of an order that opened no payment because its price\n * changed (`price_changed`), from either a thrown {@link ApiError} of\n * {@link CardsResource.order} or the `card_order_error` of a sign-in.\n * Show its amount; once the user agrees, send the order again with\n * `expectedAmount` set to it. `undefined` for any other error.\n */\nexport function priceChangedQuote(error: unknown): CardOrderQuote | undefined {\n const body = isApiError(error) ? error.body : error;\n if (typeof body !== \"object\" || body === null) return undefined;\n const { code, quote } = body as { code?: unknown; quote?: unknown };\n if (code !== \"price_changed\" || typeof quote !== \"object\" || quote === null) return undefined;\n return quote as CardOrderQuote;\n}\n\n/** Build the API body of a card order quote. */\nexport function cardOrderQuoteBody(input: CardOrderQuoteInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n return body;\n}\n\n/** Build the API body of a card order. */\nexport function cardOrderBody(input: CardOrderInput): Record<string, unknown> {\n const body: Record<string, unknown> = {\n product_id: input.productId,\n method: input.method,\n };\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.funderSlug !== undefined) body[\"funder_slug\"] = input.funderSlug;\n if (input.currency !== undefined) body[\"currency\"] = input.currency;\n if (input.extraLoad !== undefined) body[\"extra_load\"] = input.extraLoad;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.useBonus !== undefined) body[\"use_bonus\"] = input.useBonus;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.metadata !== undefined) body[\"metadata\"] = input.metadata;\n const ids = input.analyticsIds ?? analyticsIds();\n if (ids !== undefined) body[\"analytics_ids\"] = ids;\n if (input.expectedAmount !== undefined) body[\"expected_amount\"] = input.expectedAmount;\n if (input.expectedCurrency !== undefined) body[\"expected_currency\"] = input.expectedCurrency;\n return body;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n /**\n * From `cards.balance()` only: top-ups the issuer has accepted and not\n * confirmed yet, summed, decimal string in `currency`; `null` when there\n * are none. Not part of `amount`, even when the issuer already shows the\n * money: show it next to the balance as on its way.\n */\n pending?: string | null;\n}\n\n/** What a top-up of a card can be right now, from `GET /me/cards/{id}/topup`. */\nexport interface TopUpTerms {\n /** Whether the card can be topped up at this moment. */\n available: boolean;\n /** Why not, in plain words, when `available` is false. */\n reason: string | null;\n /** Currency top-ups are made in: the card's. */\n currency: string;\n /** What the wallet holds right now, in the wallet's currency. */\n wallet_available: CardBalance;\n /** Smallest single top-up the product allows, or `null` for no floor. */\n min: CardBalance | null;\n /** Largest single top-up the product allows, or `null` for no cap. */\n max: CardBalance | null;\n /**\n * What the user owes in card fees, in the card's currency, or `null` when\n * nothing is. A top-up from a wallet in the same currency pays it first\n * and the card gets the rest: show it before the top-up. Older platforms\n * leave it out.\n */\n debt?: CardBalance | null;\n}\n\nexport interface TopUpInput {\n /** Amount to add, decimal string, in the card's currency. */\n amount: string;\n /**\n * Required. Same key + same amount replays the first outcome; same key +\n * different amount is 409. Use a stable UUID per attempt so a retried\n * network call cannot move the money twice.\n */\n idempotencyKey: string;\n}\n\n/**\n * Where a top-up stands.\n *\n * - `pending`: the issuer accepted it and has not loaded the card yet. The\n * wallet is debited, the card balance is unchanged, the amount shows in\n * `Card.topups_pending`. Most issuers finish within minutes.\n * - `confirmed`: the money is on the card.\n * - `failed`: the issuer refused; the wallet is credited back.\n * - `stalled`: pending for longer than the deployment allows. The money is\n * safe and waits for support; it shows in `Card.topups_held`.\n * - `returned`: support sent the money back to the wallet.\n * - `written_off`: support closed it without the money coming back (the\n * issuer kept it); `failure_reason` says so.\n */\nexport type CardTopUpStatus =\n \"pending\" | \"confirmed\" | \"failed\" | \"stalled\" | \"returned\" | \"written_off\";\n\n/** One top-up attempt as the API records it. */\nexport interface CardTopUp {\n id: string;\n card_id: string;\n status: CardTopUpStatus;\n /** What landed on the card, decimal string, in `currency`. */\n amount: string;\n currency: string;\n /** What the wallet paid, decimal string, in `wallet_currency`. */\n wallet_amount: string;\n wallet_currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/**\n * The outcome of a top-up with the state to redraw: card, its balance, the\n * wallet. When `topup.status` is `pending`, the wallet has paid and\n * `card_balance` has not moved yet: show the amount as on its way\n * (`card.topups_pending`) and refresh the card later or on the\n * `card_topup` notification.\n */\nexport interface TopUpResult {\n topup: CardTopUp;\n card: Card;\n card_balance: CardBalance;\n wallet: CardBalance;\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 * What a reveal gave, so a client can switch on one field:\n *\n * - `numbers`: `pan`, `cvv` and the expiry are filled in;\n * - `page`: the issuer shows the numbers on a page of its own, `reveal_url`\n * is set and `pan` and `cvv` are empty;\n * - `pending`: the card's details are still being prepared, nothing else\n * is filled in. Show \"Details are being prepared\" and try again in a\n * minute or two; the attempt didn't count against the reveal limit.\n */\nexport type RevealState = \"numbers\" | \"page\" | \"pending\";\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 *\n * `state` says which of three answers this is (see {@link RevealState}).\n * Some issuers hand out a page that shows the numbers instead of the\n * numbers themselves; for some cards the details are still being prepared\n * right after issuance.\n */\nexport interface RevealedCard {\n /** Which answer this is; set by the SDK from the fields below. */\n state: RevealState;\n /** The card number; empty when `reveal_url` is set. */\n pan: string;\n /** The security code; empty when `reveal_url` is set. */\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /**\n * A page at the card issuer that shows the details to the holder. Present\n * only for issuers that give a page instead of the numbers. Short-lived,\n * often single use: open it at once in an `<iframe>` and never store it.\n */\n reveal_url?: string;\n /**\n * The person the card is registered to at its issuer: what a checkout\n * asks for. Absent for cards issued before holders were kept.\n */\n cardholder?: Cardholder;\n /**\n * The address the card is registered at — what a merchant's checkout asks\n * for, and the postal code some of them decline a payment over. Absent\n * when the deployment has not set one.\n */\n billing_address?: BillingAddress;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n /**\n * `true` when the details are still being prepared (`state: \"pending\"`).\n * Absent from platforms before 0.7.6.\n */\n details_pending?: boolean;\n}\n\n/** The three answers of a reveal told apart; see {@link RevealState}. */\nexport function revealState(r: Omit<RevealedCard, \"state\">): RevealState {\n if (r.details_pending) return \"pending\";\n if (r.reveal_url) return \"page\";\n return \"numbers\";\n}\n\n/** Postal address a card is registered at. Which parts exist depends on the country. */\nexport interface BillingAddress {\n line1?: string;\n line2?: string;\n city?: string;\n state?: string;\n postal_code?: string;\n country?: string;\n}\n\n/**\n * The cardholder the issuer knows: the details to type into a checkout\n * that asks for the name, phone or address on the card. `source` says\n * whether the platform made them up (`generated`), the user supplied them\n * (`provided`) or both (`mixed`).\n */\nexport interface Cardholder {\n id: string;\n first_name: string;\n last_name: string;\n /** `YYYY-MM-DD`. */\n birth_date: string;\n /** E.164. */\n phone: string;\n /** A mailbox the platform owns; mail the issuer sends there reaches the user. */\n email: string;\n address: BillingAddress;\n source: \"generated\" | \"provided\" | \"mixed\";\n}\n\n/** The new PIN for a physical card. */\nexport interface SetPinInput {\n /**\n * Four to six digits, as the user typed them. Sent once to the issuer and\n * kept nowhere: not by the SDK, not by the API. Never log it.\n */\n pin: string;\n}\n\n/** What to move, and the key that makes a retry safe. */\nexport interface TransferInput {\n /** The card the money lands on. Must be the caller's, and of the same kind and currency. */\n toCardId: string;\n /** Amount to move, decimal string, in the cards' currency. */\n amount: string;\n /**\n * Required. The same key with the same body replays the first outcome; a\n * different body on the same key is 409.\n */\n idempotencyKey: string;\n}\n\n/** One transfer attempt as the API records it. */\nexport interface CardTransfer {\n id: string;\n from_card_id: string;\n to_card_id: string;\n /**\n * `confirmed` — the money is on the other card. `on_wallet` — it came off\n * the first card but the second did not take it, so it is on the wallet\n * and `failure_reason` says so in words. `pending` / `failed` otherwise.\n */\n status: \"pending\" | \"confirmed\" | \"on_wallet\" | \"failed\";\n amount: string;\n currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A finished transfer with the balances to redraw both cards and the wallet. */\nexport interface TransferResult {\n transfer: CardTransfer;\n from_balance: CardBalance;\n to_balance: CardBalance;\n /** Holds the money when `transfer.status` is `on_wallet`. */\n wallet: CardBalance;\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 * Errors: 409 `holder_data_consent_required` when the product has\n * `holder_data_required` and the user has not agreed to it.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, ...card } = input;\n return this.http.post<Card>(\"/me/cards\", {\n body: cardRequestBody(card),\n idempotencyKey,\n });\n }\n\n /**\n * Buy a card in one step: the API prices the product in the payment's\n * currency, locks the rate and opens the top-up that issues the card.\n * Send the user to `order.deposit.redirect_url`; the card shows as\n * `pending_payment` until the payment is confirmed. The same\n * `idempotencyKey` returns the same order.\n * Errors: 400 `unknown_product` / `method_not_available` / a limit of the\n * way of paying, 409 `holder_data_consent_required` (the product has\n * `holder_data_required` and the user has not agreed to it), 409\n * `payments_on_hold` (a payment on this account was not accepted and new\n * ones wait until support sorts it out: show the message and point the\n * user to support), 409 `price_changed` (the order came to another amount\n * than `expectedAmount`; no payment was opened, and\n * {@link priceChangedQuote} gives the new quote), 503 no funding connector\n * or no exchange rate.\n */\n async order(input: CardOrderInput & { idempotencyKey: string }): Promise<CardOrder> {\n const { idempotencyKey, ...order } = input;\n return this.http.post<CardOrder>(\"/me/card-orders\", {\n body: cardOrderBody(order),\n idempotencyKey,\n });\n }\n\n /**\n * What an order of this card would cost the signed-in user now, with the\n * promo code: the same calculation {@link order} makes, with every\n * condition of the code checked. Nothing is reserved or used up. Pass\n * `amount` and `currency` to the order as `expectedAmount` and\n * `expectedCurrency`.\n */\n async quote(input: CardOrderQuoteInput): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/me/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n });\n }\n\n /**\n * The same quote before sign-in, for a landing page or the purchase form\n * before the e-mail code. Prices are list prices, and a code whose\n * conditions depend on the person (first card only, say) comes back\n * `conditional`, with `preliminary` set. Send `expectedAmount` with the\n * order placed at sign-in: if the price turns out different, no payment\n * is opened and `card_order_error` carries the new quote. The API limits\n * how often one address can ask (429 `too_many_requests`).\n */\n async quotePublic(input: Omit<CardOrderQuoteInput, \"useBonus\">): Promise<CardOrderQuote> {\n return this.http.post<CardOrderQuote>(\"/card-orders/quote\", {\n body: cardOrderQuoteBody(input),\n skipAuth: true,\n });\n }\n\n /**\n * The cards the caller can order, in the order the storefront shows them\n * (`is_default` marks the one issued when none is chosen). Each item\n * carries its product card (name, tagline, benefits, tile picture),\n * artwork, and the issuance price after the caller's subscription\n * discount, in the currency the operator set it in (`price.from_wallet`\n * is the same price from the wallet, when that holds another currency).\n * Pass an item's `id` as\n * `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>(`/me/card-products/${encodeURIComponent(id)}`);\n }\n\n /**\n * The public catalog: the same products, order and default as\n * {@link listProducts}, but readable before sign-in, for a landing page or\n * the cabinet's first screen. Prices are list prices (`discount_bps` is\n * always 0); once the user is signed in, {@link listProducts} shows what\n * they pay. The API lets caches keep this response for a minute.\n */\n async catalog(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/card-products\");\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>(`/me/cards/${encodeURIComponent(id)}/balance?${q}`);\n }\n\n /**\n * What a top-up of this card can be right now: whether it is possible, the\n * currency, the wallet balance, and the product's floor and cap for one\n * top-up. Read it before drawing the form. 404 if the card isn't the caller's.\n */\n async topUpTerms(id: string): Promise<TopUpTerms> {\n return this.http.get<TopUpTerms>(`/me/cards/${encodeURIComponent(id)}/topup`);\n }\n\n /**\n * Move money from the wallet onto the caller's own card. The wallet is\n * debited first, then the card's provider loads the card; if the provider\n * refuses, the money is back on the wallet and the error says so. Resolves\n * to the card, its new balance and the wallet balance, so no second call\n * is needed. Errors carry a sentence the user can read: 400 outside the\n * floor or cap · 402 not enough in the wallet · 404 not the caller's card ·\n * 409 card frozen, closed or still being issued · 501 provider can't top\n * up · 502/503 provider declined or unreachable (wallet untouched).\n */\n async topUp(id: string, input: TopUpInput): Promise<TopUpResult> {\n const { idempotencyKey, amount } = input;\n return this.http.post<TopUpResult>(`/me/cards/${encodeURIComponent(id)}/topup`, {\n body: { amount },\n idempotencyKey,\n });\n }\n\n /**\n * Move money from one of the caller's cards to another. Both must be\n * theirs, active, in the same currency and of the same kind. The money\n * travels through the wallet one leg at a time: when the second leg does\n * not go through, the call still resolves, `transfer.status` is\n * `on_wallet` and the money is on the wallet — never between two cards.\n * Errors carry a sentence the user can read: 400 the same card twice,\n * different currencies or different kinds · 402 the card holds less than\n * that · 404 one of the cards isn't theirs · 409 a card is frozen, closed\n * or still being issued, or the key was reused with a different body ·\n * 501/502/503 the provider cannot or will not move it.\n */\n async transfer(fromCardId: string, input: TransferInput): Promise<TransferResult> {\n const { toCardId, amount, idempotencyKey } = input;\n return this.http.post<TransferResult>(`/me/cards/${encodeURIComponent(fromCardId)}/transfer`, {\n body: { to_card_id: toCardId, amount },\n idempotencyKey,\n });\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze} while\n * `status_source` is `holder` or `operator`. The optional `reason` is\n * recorded on the audit trail. Resolves to the updated card. 404 if the\n * card isn't the caller's; 409 `card_locked` when support holds it; 501 if\n * the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/freeze`, { body: { reason } });\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 * `state` tells the three answers apart: `numbers`; `page`, with\n * `reveal_url` and empty `pan` and `cvv` when the issuer shows them on a\n * page of its own (open that page in a frame right away, it is\n * short-lived); or `pending` while the card's details are still being\n * prepared, which doesn't count against the limit. A card says the same\n * in {@link Card.details_pending}, so there is no need to call this just\n * to find out.\n *\n * 403 not your card · 409 `card_locked` · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 `provider_unavailable`.\n */\n async reveal(id: string, _input?: RevealCardInput): Promise<RevealedCard> {\n const r = await this.http.post<Omit<RevealedCard, \"state\">>(\n `/me/cards/${encodeURIComponent(id)}/reveal`,\n );\n return { ...r, state: revealState(r) };\n }\n\n /**\n * Unfreeze a previously-frozen card. Idempotent on an already-active card.\n * A card the issuer froze (`status_source: \"provider\"`) is not the\n * holder's to unfreeze: the API answers 409 `card_locked`, so hide the\n * button and say the freeze is lifted through the issuer's support.\n */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/unfreeze`, { body: {} });\n }\n\n /**\n * Report the card lost or stolen. Works at any time, on an active or a\n * frozen card. The report is recorded first with the server's time, which\n * decides who pays for operations someone else made; then the card is\n * frozen at its issuer and only support can unfreeze it. Resolves to the\n * claim (`client.claims`): show its `number` and `reported_at`. When the\n * issuer can't be reached, `card_freeze` is `\"pending\"`: the report still\n * counts and support freezes the card by hand. Reporting again while the\n * report is open returns the same claim. 404 / 403 not the user's card ·\n * 409 `card_not_open`: the card is closed or was never issued.\n */\n async reportLost(\n id: string,\n input: { kind: \"lost\" | \"stolen\"; details?: string },\n ): Promise<Claim> {\n return this.http.post<Claim>(`/me/cards/${encodeURIComponent(id)}/report-lost`, {\n body: { kind: input.kind, details: input.details },\n });\n }\n\n /**\n * Set the PIN of the caller's own physical card. The session is enough; the\n * call is rate-limited like {@link reveal} and the PIN is kept nowhere.\n * Resolves to the card; the user also gets a notification that the PIN\n * was set. 400 not four to six digits or the card is not active · 403 not\n * your card · 409 `card_locked`, or `provider_refused` when the issuer did\n * not take it · 429 too many attempts · 501 a virtual card has no PIN.\n */\n async setPin(id: string, input: SetPinInput): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/pin`, {\n body: { pin: input.pin },\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. A card that still holds money is refused (409\n * `move_balance_first` or `contact_support_to_close`): close it with\n * `client.closeRequests.request(id)` instead, and the money goes back the\n * way it was paid.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(`/me/cards/${encodeURIComponent(id)}/terminate`, {\n body: { reason },\n });\n }\n}\n","import type { ConsentChannel, ConsentKind } from \"./consents.js\";\nimport type { HttpClient } from \"../http.js\";\nimport type { TokenStore } from \"../token-store.js\";\nimport { isApiError } from \"../error.js\";\nimport { withAnalyticsIds, type SignupAttribution } from \"./attribution.js\";\nimport type { CodeResult } from \"./codes.js\";\nimport {\n cardOrderBody,\n type CardOrder,\n type CardOrderError,\n type CardOrderInput,\n} from \"./cards.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, and signing in (or up) with a code sent\n * to the e-mail, no password. 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 /** Analytics ids for a new account. The Telegram id is the anonymous key\n * here, and a `startapp` code in `initData` is read by the server. */\n attribution?: SignupAttribution;\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 /** A promo or referral code for a new account. Without it the server\n * reads the `startapp` of the link the Mini App was opened with, when\n * that is a code. The result comes back as `code_result`. */\n code?: string;\n /** Consents for a new account, as in `register`. Sent as `consents`;\n * ignored for an account that already exists. */\n consents?: ConsentKind[];\n /** Sent as `consent_channel`; the server takes `miniapp` when omitted. */\n consentChannel?: ConsentChannel;\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 /** Keep this browser signed in: the SDK stores the remember token it gets\n * and renews the session by itself when it ends. For accounts with a\n * second factor, pass it again to `verifyTotp` / `verifyOtp` /\n * `completeTotpSetup`. */\n remember?: boolean;\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 /** `exchangeTelegram` for a new account opened with a code (`startapp`\n * or `code`): whether it was applied and what it gave. */\n code_result?: CodeResult;\n /** Present when the sign-in was remembered. The SDK keeps it in the\n * remember store; you don't need to. */\n remember_token?: string;\n remember_expires_at?: string;\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 /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n}\n\nexport interface OtpVerifyInput {\n challenge_token: string;\n /** 6-digit one-time code delivered via the selected channel. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\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 /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Where the new user came from: the anonymous key their visits were\n * sent with (`client.attribution.touch`) and the analytics ids. Without\n * it the account is recorded with an unknown source. */\n attribution?: SignupAttribution;\n /** A promo or referral code. An unknown or expired code doesn't stop the\n * sign-up: the account is created and `code_result` says why the code\n * was not applied, so the app can show it. */\n code?: string;\n /** The boxes the user ticked: `terms` (offer, tariffs and privacy policy),\n * `personal_data`, `marketing`. A deployment can require the first two\n * (400 `consents_required` without them). */\n consents?: ConsentKind[];\n /** Where they were ticked. Read from the client header when omitted. */\n consent_channel?: ConsentChannel;\n /** Buy this card right after signing up, as `cards.order` would. The\n * sign-up's consents go with the order. The result then carries\n * `card_order` (send the user to its `deposit.redirect_url`) or, when the\n * order could not be placed, `card_order_error`; the account is created\n * either way. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\nexport interface RequestEmailCodeInput {\n email: string;\n /** Language of the e-mail when the address has no account yet (`ru`,\n * `en`, …). An account's own language wins; without either the server\n * reads the browser's. */\n locale?: string;\n}\n\n/** What `requestEmailCode` returns. The same for an address with an account\n * and one without. */\nexport interface EmailCodeSent {\n /** Send it back with the code to `verifyEmailCode`. */\n challenge_id: string;\n /** When the code stops working, ISO-8601. */\n expires_at: string;\n /** When another code can be asked for, ISO-8601: keep \"send again\" off\n * until then. */\n resend_at: string;\n}\n\nexport interface VerifyEmailCodeInput {\n /** From `requestEmailCode`. Sent as `challenge_id`. */\n challengeId: string;\n /** The six digits from the e-mail. */\n code: string;\n /** Keep this browser signed in, as in `login`. */\n remember?: boolean;\n /** Wallet currency for a new account; ignored for an existing one. Sent\n * as `wallet_currency`. */\n walletCurrency?: string;\n /** Where a new user came from, as in `register`. */\n attribution?: SignupAttribution;\n /** A promo or referral code for a new account, as `code` in `register`.\n * One that covers cards also lowers the price of `cardOrder`. Sent as\n * `promo_code`; the result comes back as `code_result`. */\n promoCode?: string;\n /** The boxes ticked on the form. A new account records them with its\n * sign-up and the card order with itself. A deployment can require\n * `terms` and `personal_data` for a new account: 400\n * `consents_required`, and the same code works again with them. */\n consents?: ConsentKind[];\n /** Where they were ticked. Sent as `consent_channel`. */\n consentChannel?: ConsentChannel;\n /** Buy this card right after signing in, as `cards.order` would, with\n * the consents above. The result carries `card_order` (send the user to\n * its `deposit.redirect_url`) or `card_order_error` when no payment was\n * opened; the sign-in stands either way. Set `expectedAmount` and\n * `expectedCurrency` from `cards.quotePublic`: when the price after\n * sign-in differs (a code for first cards only, say),\n * `card_order_error.code` is `price_changed` and its `quote` holds the\n * new price. Show it, and once the user agrees, order with\n * `cards.order` and the new `expectedAmount`. */\n cardOrder?: Omit<CardOrderInput, \"consents\" | \"consentChannel\">;\n}\n\n/** What `verifyEmailCode` returns: a `stage: \"jwt\"` session, plus whether\n * the account was made just now and the card order. */\nexport type EmailCodeSession = JwtIssued & {\n /** `true` when the address had no account and got one with this code. */\n account_created: boolean;\n /** `true` when this code proved the mailbox of an existing account for\n * the first time and the password and linked sign-ins set before that\n * were removed. */\n credentials_reset?: boolean;\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\n\n/** What `requestEmailChange` returns: send `challenge_id` back with the code. */\nexport interface EmailChangeRequested {\n challenge_id: string;\n /** Where the code went, partly hidden: `al***@example.com`. */\n destination_hint: string;\n expires_at: string;\n}\n\n/** A signed-in session without the login `stage` marker — what\n * `register` returns. With a `code`, `code_result` is set; with a\n * `cardOrder`, `card_order` or `card_order_error`. */\nexport type Session = Omit<JwtIssued, \"stage\"> & {\n card_order?: CardOrder;\n card_order_error?: CardOrderError;\n};\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\n/** Send `remember` as the API's `remember_me`. */\nfunction withRemember<T extends { remember?: boolean }>(\n input: T,\n): Omit<T, \"remember\"> & { remember_me?: boolean } {\n const { remember, ...rest } = input;\n return remember ? { ...rest, remember_me: true } : rest;\n}\n\nexport class AuthResource {\n constructor(\n private readonly http: HttpClient,\n private readonly tokens: TokenStore,\n private readonly remembered?: TokenStore,\n ) {\n if (remembered) http.setRefresher(() => this.renew().then((r) => r.kind !== \"gone\"));\n }\n\n /** Store what a finished sign-in returned. */\n private async keep(resp: { access_token: string; remember_token?: string }): Promise<void> {\n await Promise.resolve(this.tokens.set(resp.access_token));\n if (resp.remember_token && this.remembered) {\n await Promise.resolve(this.remembered.set(resp.remember_token));\n }\n }\n\n /** Renew a remembered sign-in: a new session and a new remember token,\n * both stored. Resolves `null` (and forgets the remember token) when there\n * is none or it no longer works; the app then shows the sign-in form.\n * The SDK does this by itself on a 401; call it on app start to resume a\n * session without a request failing first. */\n async refresh(): Promise<JwtIssued | null> {\n const r = await this.renew();\n if (r.kind === \"renewed\") return r.resp;\n if (r.kind === \"taken_over\") {\n // Another tab renewed first: its session is already stored.\n const access = await Promise.resolve(this.tokens.get());\n const user = await this.me();\n return { stage: \"jwt\", access_token: access ?? \"\", expires_at: \"\", user };\n }\n return null;\n }\n\n /** The renewal itself, for the 401 path: it must not call the API again\n * through the client, or a second 401 would wait on this very renewal. */\n private async renew(): Promise<\n { kind: \"renewed\"; resp: JwtIssued } | { kind: \"taken_over\" } | { kind: \"gone\" }\n > {\n const token = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n if (!token) return { kind: \"gone\" };\n try {\n const resp = await this.http.post<JwtIssued>(\"/auth/refresh\", {\n body: { remember_token: token },\n skipAuth: true,\n });\n await this.keep(resp);\n return { kind: \"renewed\", resp };\n } catch (e) {\n if (isApiError(e) && e.status === 401) {\n // Another tab of the same browser may have renewed first; its\n // tokens are then already in the (shared) stores.\n const now = await Promise.resolve(this.remembered!.get());\n if (now && now !== token && (await Promise.resolve(this.tokens.get()))) {\n return { kind: \"taken_over\" };\n }\n await Promise.resolve(this.remembered!.clear());\n await Promise.resolve(this.tokens.clear());\n return { kind: \"gone\" };\n }\n throw e;\n }\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 body: Record<string, unknown> = withRemember(input);\n // The analytics ids go with a sign-in too: the server reports the\n // account's later payments with them.\n const attribution = withAnalyticsIds(undefined);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n const resp = await this.http.post<LoginResponse>(\"/auth/login\", {\n body,\n skipAuth: true,\n });\n if (resp.stage === \"jwt\") {\n await this.keep(resp);\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: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\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: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\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` / `consents_required`\n * / `unknown_consent`, 409 email taken. */\n async register(input: RegisterInput): Promise<Session> {\n const { cardOrder, ...rest } = input;\n const body: Record<string, unknown> = withRemember(rest);\n const attribution = withAnalyticsIds(rest.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(cardOrder);\n const resp = await this.http.post<Session>(\"/auth/register\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\n return resp;\n }\n\n /** Step one of signing in without a password: a six-digit code goes to\n * the address. It works for an address with an account and for a new one\n * alike, and the answer doesn't say which. The code works for 10 minutes;\n * another can be asked for after `resend_at` and replaces it.\n * Errors: 400 `validation` (not an address), 429 `resend_too_soon` /\n * `too_many_requests` (the message says when to try again), 503\n * `delivery_failed`. */\n async requestEmailCode(input: RequestEmailCodeInput): Promise<EmailCodeSent> {\n const body: Record<string, unknown> = { email: input.email };\n if (input.locale !== undefined) body[\"locale\"] = input.locale;\n return this.http.post<EmailCodeSent>(\"/auth/email-code\", { body, skipAuth: true });\n }\n\n /** Step two: the code signs in to the account with that address, or\n * creates one (no password) when there is none; `account_created` says\n * which. The JWT is stored. With `cardOrder`, the card is ordered for\n * that account in the same call.\n * Errors: 401 `invalid_code` (wrong, expired or used; after five checks a\n * new code is needed), 400 `consents_required` for a new account, 403\n * `user_disabled` / `second_factor_required` (operator accounts sign in\n * with a password and their authenticator). */\n async verifyEmailCode(input: VerifyEmailCodeInput): Promise<EmailCodeSession> {\n const body: Record<string, unknown> = {\n challenge_id: input.challengeId,\n code: input.code,\n };\n if (input.remember) body[\"remember_me\"] = true;\n if (input.walletCurrency !== undefined) body[\"wallet_currency\"] = input.walletCurrency;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body[\"attribution\"] = attribution;\n if (input.promoCode !== undefined) body[\"promo_code\"] = input.promoCode;\n if (input.consents !== undefined) body[\"consents\"] = input.consents;\n if (input.consentChannel !== undefined) body[\"consent_channel\"] = input.consentChannel;\n if (input.cardOrder !== undefined) body[\"card_order\"] = cardOrderBody(input.cardOrder);\n const resp = await this.http.post<EmailCodeSession>(\"/auth/email-code/verify\", {\n body,\n skipAuth: true,\n });\n await this.keep(resp);\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: withRemember(input),\n skipAuth: true,\n });\n await this.keep(resp);\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: {\n init_data: string;\n provision?: boolean;\n attribution?: SignupAttribution;\n code?: string;\n consents?: ConsentKind[];\n consent_channel?: ConsentChannel;\n } = {\n init_data: input.initData,\n };\n if (input.provision !== undefined) body.provision = input.provision;\n const attribution = withAnalyticsIds(input.attribution);\n if (attribution !== undefined) body.attribution = attribution;\n if (input.code !== undefined) body.code = input.code;\n if (input.consents !== undefined) body.consents = input.consents;\n if (input.consentChannel !== undefined) body.consent_channel = input.consentChannel;\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 /** Always answers 409 `email_change_needs_code` on platform 0.8.1 and\n * newer: an address is attached only after a code sent to it comes back.\n * For the first real email of a Telegram-made account use\n * {@link requestEmailChange} and {@link confirmEmailChange}; they clear\n * `email_pending` too.\n * @deprecated Use {@link requestEmailChange} and {@link confirmEmailChange}. */\n async linkEmail(input: { email: string }): Promise<User> {\n return this.http.post<User>(\"/me/email\", { body: { email: input.email } });\n }\n\n /** Step one of an email change: a six-digit code goes to the new address\n * and works for 5 minutes. Nothing changes yet.\n * Errors: 400 `same_email`, 409 address taken, 429 `too_many_requests`\n * (five codes an hour). */\n async requestEmailChange(input: { email: string }): Promise<EmailChangeRequested> {\n return this.http.post<EmailChangeRequested>(\"/me/email/change\", {\n body: { email: input.email },\n });\n }\n\n /** Step two: the code from the e-mail changes the address; the old one\n * gets a notice. Errors: 401 `invalid_code` (after five wrong codes a new\n * request is needed), 409 the address was taken meanwhile. */\n async confirmEmailChange(input: { challengeId: string; code: string }): Promise<User> {\n return this.http.post<User>(\"/me/email/change/confirm\", {\n body: { challenge_id: input.challengeId, code: input.code },\n });\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 /** Sign out: ends this session and the remembered sign-in on the\n * server (best effort: a network failure still signs out locally), then\n * forgets both tokens. */\n async signOut(): Promise<void> {\n const remember = this.remembered ? await Promise.resolve(this.remembered.get()) : null;\n try {\n await this.http.post<void>(\"/auth/logout\", {\n body: remember ? { remember_token: remember } : {},\n retried: true,\n });\n } catch {\n // Signed out locally either way.\n }\n await Promise.resolve(this.tokens.clear());\n if (this.remembered) await Promise.resolve(this.remembered.clear());\n }\n}\n"]}
|
|
@@ -230,6 +230,10 @@ interface VerifyEmailCodeInput {
|
|
|
230
230
|
type EmailCodeSession = JwtIssued & {
|
|
231
231
|
/** `true` when the address had no account and got one with this code. */
|
|
232
232
|
account_created: boolean;
|
|
233
|
+
/** `true` when this code proved the mailbox of an existing account for
|
|
234
|
+
* the first time and the password and linked sign-ins set before that
|
|
235
|
+
* were removed. */
|
|
236
|
+
credentials_reset?: boolean;
|
|
233
237
|
card_order?: CardOrder;
|
|
234
238
|
card_order_error?: CardOrderError;
|
|
235
239
|
};
|
|
@@ -362,10 +366,12 @@ declare class AuthResource {
|
|
|
362
366
|
* Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
|
|
363
367
|
* another account); 503 `telegram_not_configured`. */
|
|
364
368
|
linkTelegram(input: LinkTelegramInput): Promise<JwtIssued>;
|
|
365
|
-
/**
|
|
366
|
-
*
|
|
367
|
-
*
|
|
368
|
-
* {@link requestEmailChange} and {@link confirmEmailChange}
|
|
369
|
+
/** Always answers 409 `email_change_needs_code` on platform 0.8.1 and
|
|
370
|
+
* newer: an address is attached only after a code sent to it comes back.
|
|
371
|
+
* For the first real email of a Telegram-made account use
|
|
372
|
+
* {@link requestEmailChange} and {@link confirmEmailChange}; they clear
|
|
373
|
+
* `email_pending` too.
|
|
374
|
+
* @deprecated Use {@link requestEmailChange} and {@link confirmEmailChange}. */
|
|
369
375
|
linkEmail(input: {
|
|
370
376
|
email: string;
|
|
371
377
|
}): Promise<User>;
|
package/dist/resources/auth.d.ts
CHANGED
|
@@ -230,6 +230,10 @@ interface VerifyEmailCodeInput {
|
|
|
230
230
|
type EmailCodeSession = JwtIssued & {
|
|
231
231
|
/** `true` when the address had no account and got one with this code. */
|
|
232
232
|
account_created: boolean;
|
|
233
|
+
/** `true` when this code proved the mailbox of an existing account for
|
|
234
|
+
* the first time and the password and linked sign-ins set before that
|
|
235
|
+
* were removed. */
|
|
236
|
+
credentials_reset?: boolean;
|
|
233
237
|
card_order?: CardOrder;
|
|
234
238
|
card_order_error?: CardOrderError;
|
|
235
239
|
};
|
|
@@ -362,10 +366,12 @@ declare class AuthResource {
|
|
|
362
366
|
* Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
|
|
363
367
|
* another account); 503 `telegram_not_configured`. */
|
|
364
368
|
linkTelegram(input: LinkTelegramInput): Promise<JwtIssued>;
|
|
365
|
-
/**
|
|
366
|
-
*
|
|
367
|
-
*
|
|
368
|
-
* {@link requestEmailChange} and {@link confirmEmailChange}
|
|
369
|
+
/** Always answers 409 `email_change_needs_code` on platform 0.8.1 and
|
|
370
|
+
* newer: an address is attached only after a code sent to it comes back.
|
|
371
|
+
* For the first real email of a Telegram-made account use
|
|
372
|
+
* {@link requestEmailChange} and {@link confirmEmailChange}; they clear
|
|
373
|
+
* `email_pending` too.
|
|
374
|
+
* @deprecated Use {@link requestEmailChange} and {@link confirmEmailChange}. */
|
|
369
375
|
linkEmail(input: {
|
|
370
376
|
email: string;
|
|
371
377
|
}): Promise<User>;
|