@takeal/cusfront-sdk 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +104 -2
- package/README.md +393 -14
- package/dist/devices-C3JHi2Hi.d.cts +165 -0
- package/dist/devices-DP_hxwmW.d.ts +165 -0
- package/dist/{http-BkZZZI8K.d.cts → http-B-OQwMYn.d.cts} +13 -2
- package/dist/{http-BkZZZI8K.d.ts → http-B-OQwMYn.d.ts} +13 -2
- package/dist/index.cjs +425 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -8
- package/dist/index.d.ts +77 -8
- package/dist/index.js +422 -26
- package/dist/index.js.map +1 -1
- package/dist/react/index.cjs +133 -6
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +65 -3
- package/dist/react/index.d.ts +65 -3
- package/dist/react/index.js +131 -8
- package/dist/react/index.js.map +1 -1
- package/dist/resources/auth.cjs +73 -15
- package/dist/resources/auth.cjs.map +1 -1
- package/dist/resources/auth.d.cts +100 -9
- package/dist/resources/auth.d.ts +100 -9
- package/dist/resources/auth.js +73 -15
- package/dist/resources/auth.js.map +1 -1
- package/dist/resources/balance.cjs +4 -3
- package/dist/resources/balance.cjs.map +1 -1
- package/dist/resources/balance.d.cts +8 -9
- package/dist/resources/balance.d.ts +8 -9
- package/dist/resources/balance.js +4 -3
- package/dist/resources/balance.js.map +1 -1
- package/dist/resources/blog.d.cts +1 -1
- package/dist/resources/blog.d.ts +1 -1
- package/dist/resources/branding.cjs.map +1 -1
- package/dist/resources/branding.d.cts +8 -2
- package/dist/resources/branding.d.ts +8 -2
- package/dist/resources/branding.js.map +1 -1
- package/dist/resources/cards.cjs +33 -1
- package/dist/resources/cards.cjs.map +1 -1
- package/dist/resources/cards.d.cts +105 -4
- package/dist/resources/cards.d.ts +105 -4
- package/dist/resources/cards.js +33 -1
- package/dist/resources/cards.js.map +1 -1
- package/dist/resources/deposits.d.cts +1 -1
- package/dist/resources/deposits.d.ts +1 -1
- package/dist/resources/devices.cjs +92 -0
- package/dist/resources/devices.cjs.map +1 -0
- package/dist/resources/devices.d.cts +3 -0
- package/dist/resources/devices.d.ts +3 -0
- package/dist/resources/devices.js +89 -0
- package/dist/resources/devices.js.map +1 -0
- package/dist/resources/me.cjs +32 -0
- package/dist/resources/me.cjs.map +1 -0
- package/dist/resources/me.d.cts +40 -0
- package/dist/resources/me.d.ts +40 -0
- package/dist/resources/me.js +30 -0
- package/dist/resources/me.js.map +1 -0
- package/dist/resources/notifications.cjs +53 -0
- package/dist/resources/notifications.cjs.map +1 -0
- package/dist/resources/notifications.d.cts +109 -0
- package/dist/resources/notifications.d.ts +109 -0
- package/dist/resources/notifications.js +51 -0
- package/dist/resources/notifications.js.map +1 -0
- package/dist/resources/push.cjs +65 -0
- package/dist/resources/push.cjs.map +1 -0
- package/dist/resources/push.d.cts +76 -0
- package/dist/resources/push.d.ts +76 -0
- package/dist/resources/push.js +62 -0
- package/dist/resources/push.js.map +1 -0
- package/dist/resources/sessions.cjs +26 -0
- package/dist/resources/sessions.cjs.map +1 -0
- package/dist/resources/sessions.d.cts +43 -0
- package/dist/resources/sessions.d.ts +43 -0
- package/dist/resources/sessions.js +24 -0
- package/dist/resources/sessions.js.map +1 -0
- package/dist/resources/subscriptions.cjs.map +1 -1
- package/dist/resources/subscriptions.d.cts +8 -1
- package/dist/resources/subscriptions.d.ts +8 -1
- package/dist/resources/subscriptions.js.map +1 -1
- package/dist/resources/wallet.cjs +24 -0
- package/dist/resources/wallet.cjs.map +1 -0
- package/dist/resources/wallet.d.cts +39 -0
- package/dist/resources/wallet.d.ts +39 -0
- package/dist/resources/wallet.js +22 -0
- package/dist/resources/wallet.js.map +1 -0
- package/dist/telegram.cjs +466 -28
- package/dist/telegram.cjs.map +1 -1
- package/dist/telegram.d.cts +65 -7
- package/dist/telegram.d.ts +65 -7
- package/dist/telegram.js +465 -29
- package/dist/telegram.js.map +1 -1
- package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,CAAA;AAAA,MACnC,EAAE,IAAA,EAAM,EAAE,MAAA,EAAO;AAAE,KACrB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,MAAM,MAAA,CAAO,EAAA,EAAY,KAAA,EAA+C;AACtE,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA;AAAA,MACf,CAAA,UAAA,EAAa,kBAAA,CAAmB,EAAE,CAAC,CAAA,OAAA,CAAA;AAAA,MACnC,EAAE,MAAM,EAAE,QAAA,EAAU,MAAM,QAAA,EAAU,SAAA,EAAW,KAAA,CAAM,QAAA,EAAS;AAAE,KAClE;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,SAAS,EAAA,EAA2B;AACxC,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA;AAAA,MACf,CAAA,UAAA,EAAa,kBAAA,CAAmB,EAAE,CAAC,CAAA,SAAA,CAAA;AAAA,MACnC,EAAE,IAAA,EAAM,EAAC;AAAE,KACb;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,SAAA,CAAU,EAAA,EAAY,MAAA,EAAgC;AAC1D,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA;AAAA,MACf,CAAA,UAAA,EAAa,kBAAA,CAAmB,EAAE,CAAC,CAAA,UAAA,CAAA;AAAA,MACnC,EAAE,IAAA,EAAM,EAAE,MAAA,EAAO;AAAE,KACrB;AAAA,EACF;AACF","file":"cards.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\n\n/**\n * Cards resource — `client.cards.*`.\n *\n * The end-user \"money OUT\" surface: a user issues themselves a card backed by\n * their wallet balance via an issuer connector. Mirrors the Takeal API's\n * `/me/cards` routes:\n *\n * POST /me/cards → create\n * GET /me/cards → list (most recent first)\n * GET /me/cards/{id} → get\n * GET /me/cards/{id}/balance → balance (prepaid remaining)\n * POST /me/cards/{id}/freeze → freeze\n * POST /me/cards/{id}/unfreeze → unfreeze\n * POST /me/cards/{id}/terminate → terminate (one-way)\n *\n * The lifecycle actions are ownership-gated server-side: a caller can only\n * freeze / unfreeze / terminate a card that belongs to them (else 404).\n *\n * ## What is intentionally NOT here\n *\n * Card-data reveal (PAN / CVV) is a separate, security-sensitive flow with its\n * own re-auth + rate-limit + audit contract and is intentionally\n * NOT part of this resource (tracked separately).\n *\n * Today only PREPAID is wired end-to-end; CREDIT and GIFT return 400 from\n * the Takeal API until their issuer flows land.\n */\n\n/** Card product. Only `prepaid` is fully implemented today. */\nexport type CardType = \"credit\" | \"prepaid\" | \"gift\";\n\n/**\n * Card lifecycle state.\n *\n * `pending_payment` is a transient state: the row exists but the\n * per-card issuance-fee debit has not yet succeeded; such cards have no\n * provider reference and no user-visible side effects.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"active\"\n | \"frozen\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * A card record as the Takeal API returns it. Mirrors the `cards` table. Note the\n * SDK never receives the full PAN or CVV here — only `last4` + expiry. The\n * gift-card `redemption_code` is returned exactly once (on create) and\n * scrubbed from subsequent list/get responses.\n */\nexport interface Card {\n id: string;\n user_id: string;\n card_type: CardType;\n /** Slug of the issuer that minted this card, as configured by the deployment. */\n connector_slug: string;\n /** The connector's own reference, populated once it responds. */\n provider_reference: string | null;\n status: CardStatus;\n /** Last four digits of the PAN — safe to display. */\n last4: string | null;\n expiry_month: number | null;\n expiry_year: number | null;\n /** Gift cards only, present once on create then scrubbed. */\n redemption_code?: string;\n /** Decimal as a string. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface CreateCardInput {\n /** `prepaid` (the only fully-wired type today), `credit`, or `gift`. */\n type: CardType;\n /** Decimal as a string. The prepaid load amount drained from wallet balance. */\n initial_amount?: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n /**\n * Optional. Slug of a specific issuer to mint with. Omit to let\n * the Takeal API pick the first active issuer. Unknown slug → 400; empty issuer\n * list → 503.\n */\n issuer_slug?: string;\n metadata?: Record<string, string>;\n /** Structured billing details — real issuers require these for 3DS / KYC. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original card; same key + different body returns 409.\n */\n idempotencyKey: string;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n}\n\n/** Re-auth gate for {@link CardsResource.reveal}. */\nexport interface RevealCardInput {\n /** The user's account password — mandatory re-auth. */\n password: string;\n /** TOTP code; required only when the user has TOTP enrolled. */\n totpCode?: string;\n}\n\n/**\n * Full card data from a successful reveal. **Security**: never persist this —\n * keep it in volatile memory only, clear it within `expires_in_seconds`, and\n * never write it to localStorage / logs (the API marks the response no-store).\n */\nexport interface RevealedCard {\n pan: string;\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n}\n\nexport class CardsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Issue a card backed by the user's wallet balance. Resolves to the new\n * `Card`. On a ledger failure after provider creation, the Takeal API rolls the row\n * to `failed` (never an orphaned active card); inspect `status` /\n * `failure_reason` on the result.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, ...body } = input;\n return this.http.post<Card>(\"/me/cards\", {\n body,\n idempotencyKey,\n });\n }\n\n /** Fetch one card by id. */\n async get(id: string): Promise<Card> {\n return this.http.get<Card>(`/me/cards/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's cards, most recent first. */\n async list(): Promise<Card[]> {\n return this.http.get<Card[]>(\"/me/cards\");\n }\n\n /**\n * Remaining balance of a prepaid card. `currency` is required by the Takeal API and\n * forwarded as a query param.\n */\n async balance(id: string, currency: string): Promise<CardBalance> {\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<CardBalance>(\n `/me/cards/${encodeURIComponent(id)}/balance?${q}`,\n );\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze}. The optional\n * `reason` is recorded on the audit trail. Resolves to the updated card.\n * 404 if the card isn't the caller's; 501 if the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/freeze`,\n { body: { reason } },\n );\n }\n\n /**\n * Reveal the FULL PAN + CVV for the caller's own card. Re-auth gated\n * (password, + TOTP when the user has it enrolled) and rate-limited\n * server-side. The Takeal API never persists this data and marks the\n * response no-store; the SDK returns it verbatim and holds nothing.\n *\n * **Consumer security duties** (the SDK can't enforce these for you):\n * keep the result in volatile memory only, never write it to\n * localStorage / logs, and clear it within `expires_in_seconds`.\n *\n * 401 bad re-auth · 403 not your card · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 provider error.\n */\n async reveal(id: string, input: RevealCardInput): Promise<RevealedCard> {\n return this.http.post<RevealedCard>(\n `/me/cards/${encodeURIComponent(id)}/reveal`,\n { body: { password: input.password, totp_code: input.totpCode } },\n );\n }\n\n /** Unfreeze a previously-frozen card. Idempotent on an already-active card. */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/unfreeze`,\n { body: {} },\n );\n }\n\n /**\n * Terminate the caller's own card. **One-way** — a terminated card cannot be\n * reactivated. The optional `reason` is audited. Idempotent on an\n * already-terminated card.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/terminate`,\n { body: { reason } },\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/resources/cards.ts"],"names":[],"mappings":";AAyNO,IAAM,gBAAN,MAAoB;AAAA,EACzB,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AA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A,EAAW,KAAA,CAAM,QAAA,EAAS;AAAE,KAClE;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,SAAS,EAAA,EAA2B;AACxC,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA;AAAA,MACf,CAAA,UAAA,EAAa,kBAAA,CAAmB,EAAE,CAAC,CAAA,SAAA,CAAA;AAAA,MACnC,EAAE,IAAA,EAAM,EAAC;AAAE,KACb;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,SAAA,CAAU,EAAA,EAAY,MAAA,EAAgC;AAC1D,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA;AAAA,MACf,CAAA,UAAA,EAAa,kBAAA,CAAmB,EAAE,CAAC,CAAA,UAAA,CAAA;AAAA,MACnC,EAAE,IAAA,EAAM,EAAE,MAAA,EAAO;AAAE,KACrB;AAAA,EACF;AACF","file":"cards.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\nimport type { CustomerInfo } from \"../types/customer.js\";\n\n/**\n * Cards resource — `client.cards.*`.\n *\n * The end-user \"money OUT\" surface: a user issues themselves a card backed by\n * their wallet balance via an issuer connector. Mirrors the Takeal API's\n * `/me/cards` routes:\n *\n * GET /me/card-products → listProducts (the catalog)\n * GET /me/card-products/{id} → getProduct\n * POST /me/cards → create\n * GET /me/cards → list (most recent first)\n * GET /me/cards/{id} → get\n * PATCH /me/cards/{id} → update (name, design)\n * GET /me/cards/{id}/balance → balance (prepaid remaining)\n * POST /me/cards/{id}/freeze → freeze\n * POST /me/cards/{id}/unfreeze → unfreeze\n * POST /me/cards/{id}/terminate → terminate (one-way)\n *\n * The lifecycle actions are ownership-gated server-side: a caller can only\n * freeze / unfreeze / terminate a card that belongs to them (else 404).\n *\n * ## What is intentionally NOT here\n *\n * Card-data reveal (PAN / CVV) is a separate, security-sensitive flow with its\n * own re-auth + rate-limit + audit contract and is intentionally\n * NOT part of this resource (tracked separately).\n *\n * Today only PREPAID is wired end-to-end; CREDIT and GIFT return 400 from\n * the Takeal API until their issuer flows land.\n */\n\n/** Card product. Only `prepaid` is fully implemented today. */\nexport type CardType = \"credit\" | \"prepaid\" | \"gift\";\n\n/**\n * Card lifecycle state.\n *\n * `pending_payment` is a transient state: the row exists but the\n * per-card issuance-fee debit has not yet succeeded; such cards have no\n * provider reference and no user-visible side effects.\n */\nexport type CardStatus =\n | \"pending_payment\"\n | \"active\"\n | \"frozen\"\n | \"terminated\"\n | \"redeemed\"\n | \"failed\";\n\n/**\n * A card design: the artwork a card is shown with. `image_url` is either an\n * absolute URL or a path relative to the API origin (the deployment's default\n * design is `/card-designs/default.svg`) — pass it through\n * `client.assetUrl()` before rendering. `id` is `null` for the deployment\n * default, which is rendered from the branding settings.\n */\nexport interface CardDesignRef {\n id: string | null;\n name?: string;\n image_url: string;\n}\n\n/**\n * What issuing a card costs the caller. `amount` is the price after the\n * user's subscription discount; `base_amount` is the list price and\n * `discount_bps` the discount in basis points (1000 = 10 %). `label` is the\n * operator's wording for the fee line (\"Card issuance\").\n */\nexport interface CardProductPrice {\n amount: string;\n currency: string;\n label: string;\n base_amount: string;\n discount_bps: number;\n}\n\n/**\n * A card the user can order, as listed by `GET /me/card-products`. The id is\n * opaque — it names a product, never a provider. `designs` is the set the\n * user may pick from (may be empty when only the default applies); `design`\n * is what the card gets when no choice is made. `price` is `null` for a\n * free card. `features` is an operator-defined object (scheme, wallet\n * support, load limits, …) with no fixed keys.\n */\nexport interface CardProduct {\n id: string;\n name: string;\n description: string | null;\n card_type: CardType;\n currency: string | null;\n features: Record<string, unknown>;\n design: CardDesignRef;\n designs: CardDesignRef[];\n price: CardProductPrice | null;\n /** True for the product the deployment issues when none is chosen. */\n is_default: boolean;\n}\n\n/**\n * A card record as the Takeal API returns it. Mirrors the `cards` table. Note the\n * SDK never receives the full PAN or CVV here — only `last4` + expiry. The\n * gift-card `redemption_code` is returned exactly once (on create) and\n * scrubbed from subsequent list/get responses.\n */\nexport interface Card {\n id: string;\n user_id: string;\n card_type: CardType;\n /** Slug of the issuer that minted this card, as configured by the deployment. */\n connector_slug: string;\n /** The connector's own reference, populated once it responds. */\n provider_reference: string | null;\n status: CardStatus;\n /** Last four digits of the PAN — safe to display. */\n last4: string | null;\n expiry_month: number | null;\n expiry_year: number | null;\n /** Gift cards only, present once on create then scrubbed. */\n redemption_code?: string;\n /** Decimal as a string. */\n initial_amount: string | null;\n currency: string;\n failure_reason: string | null;\n /** The name the user gave the card, or `null`. */\n name: string | null;\n /** The artwork the card is shown with. Always present. */\n design: CardDesignRef;\n /** The product the card was issued from; `null` for cards issued without one. */\n product: { id: string; name: string } | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface CreateCardInput {\n /**\n * A product id from {@link CardsResource.listProducts}. Sent as\n * `product_id`. When given, `type` and `issuer_slug` may be omitted; when\n * both are given they must agree with the product (400 `product_mismatch`).\n * Unknown, disabled or hidden product → 400 `unknown_product`.\n */\n productId?: string;\n /** A name for the card, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * One of the product's `designs`. Sent as `design_id`. `null` or omitted\n * picks the product's default design; a design outside the product's set →\n * 400 `design_not_allowed`.\n */\n designId?: string | null;\n /**\n * `prepaid` (the only fully-wired type today), `credit`, or `gift`.\n * Optional when `productId` is given, required otherwise.\n */\n type?: CardType;\n /** Decimal as a string. The prepaid load amount drained from wallet balance. */\n initial_amount?: string;\n /** ISO 4217 code, e.g. `\"USD\"`. */\n currency: string;\n /**\n * Optional. Slug of a specific issuer to mint with. Omit to let\n * the Takeal API pick the first active issuer. Unknown slug → 400; empty issuer\n * list → 503.\n */\n issuer_slug?: string;\n metadata?: Record<string, string>;\n /** Structured billing details — real issuers require these for 3DS / KYC. */\n customer?: CustomerInfo;\n /**\n * Required by the Takeal API on this write endpoint. Same key + body replays the\n * original card; same key + different body returns 409.\n */\n idempotencyKey: string;\n}\n\n/** Remaining balance of a prepaid card. */\nexport interface CardBalance {\n amount: string;\n currency: string;\n}\n\n/** Fields a user can change on their own card. Omitted fields are left as they are. */\nexport interface UpdateCardInput {\n /** New name, 1–40 characters. Sent as `name`. */\n name?: string;\n /**\n * New design (one of the product's `designs`), or `null` for the product's\n * default. Sent as `design_id`.\n */\n designId?: string | null;\n}\n\n/** Re-auth gate for {@link CardsResource.reveal}. */\nexport interface RevealCardInput {\n /** The user's account password — mandatory re-auth. */\n password: string;\n /** TOTP code; required only when the user has TOTP enrolled. */\n totpCode?: string;\n}\n\n/**\n * Full card data from a successful reveal. **Security**: never persist this —\n * keep it in volatile memory only, clear it within `expires_in_seconds`, and\n * never write it to localStorage / logs (the API marks the response no-store).\n */\nexport interface RevealedCard {\n pan: string;\n cvv: string;\n expiry_month: number;\n expiry_year: number;\n holder_name: string;\n /** Display window before the client should auto-clear the data. */\n expires_in_seconds: number;\n}\n\nexport class CardsResource {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Issue a card backed by the user's wallet balance. Resolves to the new\n * `Card`. On a ledger failure after provider creation, the Takeal API rolls the row\n * to `failed` (never an orphaned active card); inspect `status` /\n * `failure_reason` on the result.\n */\n async create(input: CreateCardInput): Promise<Card> {\n const { idempotencyKey, productId, name, designId, ...rest } = input;\n const body: Record<string, unknown> = { ...rest };\n if (productId !== undefined) body[\"product_id\"] = productId;\n if (name !== undefined) body[\"name\"] = name;\n if (designId !== undefined) body[\"design_id\"] = designId;\n return this.http.post<Card>(\"/me/cards\", {\n body,\n idempotencyKey,\n });\n }\n\n /**\n * The cards the caller can order, in the order the deployment offers them\n * (the default product first). Each item carries its name, description,\n * artwork, the issuance price after the caller's subscription discount,\n * and the currency. Pass an item's `id` as `productId` to {@link create}.\n */\n async listProducts(): Promise<CardProduct[]> {\n return this.http.get<CardProduct[]>(\"/me/card-products\");\n }\n\n /** One product from the catalog. 404 when unknown, disabled or hidden. */\n async getProduct(id: string): Promise<CardProduct> {\n return this.http.get<CardProduct>(\n `/me/card-products/${encodeURIComponent(id)}`,\n );\n }\n\n /**\n * Rename the caller's own card or change its design. Resolves to the\n * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /\n * `design_not_allowed` on a bad value.\n */\n async update(id: string, input: UpdateCardInput): Promise<Card> {\n const body: Record<string, unknown> = {};\n if (input.name !== undefined) body[\"name\"] = input.name;\n if (input.designId !== undefined) body[\"design_id\"] = input.designId;\n return this.http.patch<Card>(`/me/cards/${encodeURIComponent(id)}`, {\n body,\n });\n }\n\n /** Fetch one card by id. */\n async get(id: string): Promise<Card> {\n return this.http.get<Card>(`/me/cards/${encodeURIComponent(id)}`);\n }\n\n /** List the caller's cards, most recent first. */\n async list(): Promise<Card[]> {\n return this.http.get<Card[]>(\"/me/cards\");\n }\n\n /**\n * Remaining balance of a prepaid card. `currency` is required by the Takeal API and\n * forwarded as a query param.\n */\n async balance(id: string, currency: string): Promise<CardBalance> {\n const q = new URLSearchParams({ currency }).toString();\n return this.http.get<CardBalance>(\n `/me/cards/${encodeURIComponent(id)}/balance?${q}`,\n );\n }\n\n /**\n * Freeze the caller's own card. Reversible via {@link unfreeze}. The optional\n * `reason` is recorded on the audit trail. Resolves to the updated card.\n * 404 if the card isn't the caller's; 501 if the issuer can't freeze.\n */\n async freeze(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/freeze`,\n { body: { reason } },\n );\n }\n\n /**\n * Reveal the FULL PAN + CVV for the caller's own card. Re-auth gated\n * (password, + TOTP when the user has it enrolled) and rate-limited\n * server-side. The Takeal API never persists this data and marks the\n * response no-store; the SDK returns it verbatim and holds nothing.\n *\n * **Consumer security duties** (the SDK can't enforce these for you):\n * keep the result in volatile memory only, never write it to\n * localStorage / logs, and clear it within `expires_in_seconds`.\n *\n * 401 bad re-auth · 403 not your card · 429 rate-limited · 501 connector\n * has no sensitive-data endpoint · 503 provider error.\n */\n async reveal(id: string, input: RevealCardInput): Promise<RevealedCard> {\n return this.http.post<RevealedCard>(\n `/me/cards/${encodeURIComponent(id)}/reveal`,\n { body: { password: input.password, totp_code: input.totpCode } },\n );\n }\n\n /** Unfreeze a previously-frozen card. Idempotent on an already-active card. */\n async unfreeze(id: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/unfreeze`,\n { body: {} },\n );\n }\n\n /**\n * Terminate the caller's own card. **One-way** — a terminated card cannot be\n * reactivated. The optional `reason` is audited. Idempotent on an\n * already-terminated card.\n */\n async terminate(id: string, reason?: string): Promise<Card> {\n return this.http.post<Card>(\n `/me/cards/${encodeURIComponent(id)}/terminate`,\n { body: { reason } },\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/resources/push.ts
|
|
4
|
+
function base64UrlToBytes(input) {
|
|
5
|
+
const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
6
|
+
const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
|
|
7
|
+
const bin = atob(padded);
|
|
8
|
+
const out = new Uint8Array(bin.length);
|
|
9
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
10
|
+
return out;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/resources/devices.ts
|
|
14
|
+
function devicePlatformOf(platform) {
|
|
15
|
+
return platform === "telegram-miniapp" ? "telegram" : platform;
|
|
16
|
+
}
|
|
17
|
+
var DevicesResource = class {
|
|
18
|
+
constructor(http, client) {
|
|
19
|
+
this.http = http;
|
|
20
|
+
this.client = client;
|
|
21
|
+
}
|
|
22
|
+
/** Every device the user has, disabled ones included. */
|
|
23
|
+
async list() {
|
|
24
|
+
return this.http.get("/me/devices");
|
|
25
|
+
}
|
|
26
|
+
/** Register a device, or refresh it when the same credential is already
|
|
27
|
+
* known (then `last_seen_at`, `label` and `app_version` update and a
|
|
28
|
+
* disabled device comes back). `app_version` defaults to the client
|
|
29
|
+
* version sent in `X-Takeal-Client`.
|
|
30
|
+
*
|
|
31
|
+
* Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
|
|
32
|
+
* deployment has no VAPID keys. */
|
|
33
|
+
async register(input) {
|
|
34
|
+
return this.http.put("/me/devices", {
|
|
35
|
+
body: { app_version: this.client.version, ...input }
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/** Delete one device. 404 when it isn't the user's. */
|
|
39
|
+
async remove(id) {
|
|
40
|
+
await this.http.delete(`/me/devices/${encodeURIComponent(id)}`);
|
|
41
|
+
}
|
|
42
|
+
/** Subscribe this browser to Web Push and register it as a device. Ask
|
|
43
|
+
* for notification permission before calling. Throws when push isn't
|
|
44
|
+
* set up on the deployment. */
|
|
45
|
+
async registerWebPush(registration, opts = {}) {
|
|
46
|
+
const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
|
|
47
|
+
if (!key) {
|
|
48
|
+
throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
|
|
49
|
+
}
|
|
50
|
+
const sub = await registration.pushManager.subscribe({
|
|
51
|
+
userVisibleOnly: true,
|
|
52
|
+
applicationServerKey: base64UrlToBytes(key)
|
|
53
|
+
});
|
|
54
|
+
const json = sub.toJSON();
|
|
55
|
+
if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
|
|
56
|
+
throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
|
|
57
|
+
}
|
|
58
|
+
return this.register({
|
|
59
|
+
kind: "webpush",
|
|
60
|
+
platform: devicePlatformOf(this.client.platform),
|
|
61
|
+
credential: {
|
|
62
|
+
endpoint: json.endpoint,
|
|
63
|
+
keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
|
|
64
|
+
},
|
|
65
|
+
...opts.label ? { label: opts.label } : {}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/** Unsubscribe this browser from Web Push and delete the matching device
|
|
69
|
+
* (see {@link UnregisterWebPushOptions}). Safe when nothing is
|
|
70
|
+
* registered. */
|
|
71
|
+
async unregisterWebPush(registration, opts = {}) {
|
|
72
|
+
const sub = await registration.pushManager.getSubscription();
|
|
73
|
+
if (sub) await sub.unsubscribe();
|
|
74
|
+
if (opts.deviceId) {
|
|
75
|
+
await this.remove(opts.deviceId);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const mine = (await this.list()).filter((d) => d.kind === "webpush" && d.is_current);
|
|
79
|
+
for (const d of mine) await this.remove(d.id);
|
|
80
|
+
}
|
|
81
|
+
async vapidPublicKey() {
|
|
82
|
+
const { vapid_public_key } = await this.http.get(
|
|
83
|
+
"/me/push-subscription"
|
|
84
|
+
);
|
|
85
|
+
return vapid_public_key ?? null;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
exports.DevicesResource = DevicesResource;
|
|
90
|
+
exports.devicePlatformOf = devicePlatformOf;
|
|
91
|
+
//# sourceMappingURL=devices.cjs.map
|
|
92
|
+
//# sourceMappingURL=devices.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/resources/push.ts","../../src/resources/devices.ts"],"names":[],"mappings":";;;AAsGO,SAAS,iBAAiB,KAAA,EAA2B;AAC1D,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,MAAM,GAAG,CAAA;AACtD,EAAA,MAAM,MAAA,GAAS,MAAM,GAAA,CAAI,MAAA,CAAA,CAAQ,IAAK,GAAA,CAAI,MAAA,GAAS,KAAM,CAAC,CAAA;AAC1D,EAAA,MAAM,GAAA,GAAM,KAAK,MAAM,CAAA;AACvB,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,GAAA,CAAI,MAAM,CAAA;AACrC,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,MAAA,EAAQ,CAAA,EAAA,EAAK,GAAA,CAAI,CAAC,CAAA,GAAI,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA;AAC9D,EAAA,OAAO,GAAA;AACT;;;ACEO,SAAS,iBAA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AAAA,EAEA,MAAc,cAAA,GAAyC;AACrD,IAAA,MAAM,EAAE,gBAAA,EAAiB,GAAI,MAAM,KAAK,IAAA,CAAK,GAAA;AAAA,MAC3C;AAAA,KACF;AACA,IAAA,OAAO,gBAAA,IAAoB,IAAA;AAAA,EAC7B;AACF","file":"devices.cjs","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Push resource — `client.push.*`.\n *\n * Web Push for the signed-in user, through the older single-subscription\n * endpoint. The API now keeps one device per browser (see\n * `client.devices`), and this endpoint is an alias over the Web Push\n * devices: it keeps working, but new code should call\n * `client.devices.registerWebPush(reg)` / `unregisterWebPush(reg)` instead.\n *\n * Your service worker shows the notification: the payload is JSON with\n * `title`, `body` and `url` (where a click should lead).\n */\n\nexport interface PushStatus {\n /** `true` when a subscription is stored for this user. */\n subscribed: boolean;\n /** Host of the stored endpoint, e.g. `fcm.googleapis.com`. */\n endpoint_host?: string | null;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`.\n * `null` when push is not set up on this deployment. */\n vapid_public_key?: string | null;\n}\n\nexport interface PushSubscriptionInput {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** The part of `ServiceWorkerRegistration` the SDK needs. Typed\n * structurally so the core stays free of DOM lib types. */\nexport interface PushCapableRegistration {\n pushManager: {\n getSubscription(): Promise<{ unsubscribe(): Promise<boolean> } | null>;\n subscribe(options: {\n userVisibleOnly: boolean;\n applicationServerKey: Uint8Array;\n }): Promise<{ toJSON(): { endpoint?: string; keys?: Record<string, string> } }>;\n };\n}\n\nexport class PushResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Whether the user is subscribed, plus the VAPID key to subscribe with. */\n async status(): Promise<PushStatus> {\n return this.http.get<PushStatus>(\"/me/push-subscription\");\n }\n\n /** Store a subscription you created yourself.\n * 409 `push_disabled` when the deployment has no VAPID keys.\n * @deprecated Use `client.devices.register({ kind: \"webpush\", ... })`. */\n async save(input: PushSubscriptionInput): Promise<PushStatus> {\n return this.http.put<PushStatus>(\"/me/push-subscription\", { body: input });\n }\n\n /** Delete the stored subscription. Safe when nothing is stored.\n * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */\n async remove(): Promise<void> {\n await this.http.delete<void>(\"/me/push-subscription\");\n }\n\n /** Subscribe this browser and store the subscription. Ask for\n * notification permission before calling. Throws when push isn't set up\n * on the deployment.\n * @deprecated Use `client.devices.registerWebPush(registration)`. */\n async enable(registration: PushCapableRegistration): Promise<PushStatus> {\n const { vapid_public_key } = await this.status();\n if (!vapid_public_key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(vapid_public_key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.save({\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n });\n }\n\n /** Unsubscribe this browser and delete the stored subscription.\n * @deprecated Use `client.devices.unregisterWebPush(registration)`. */\n async disable(registration: PushCapableRegistration): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n await this.remove();\n }\n}\n\n/** URL-safe base64 (padding optional) → bytes. */\nexport function base64UrlToBytes(input: string): Uint8Array {\n const b64 = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = b64 + \"=\".repeat((4 - (b64.length % 4)) % 4);\n const bin = atob(padded);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { ClientPlatform, ResolvedClientDescriptor } from \"../client-platform.js\";\nimport { base64UrlToBytes, type PushCapableRegistration } from \"./push.js\";\n\n/**\n * Devices resource — `client.devices.*`.\n *\n * A user has many devices: each browser with a Web Push subscription, each\n * phone with an FCM / APNs token, and a marker for \"uses the Telegram Mini\n * App\". The server picks the notification channel from them: a mobile app\n * first, otherwise the device seen most recently.\n *\n * The usual browser flow, once notification permission is granted:\n *\n * ```ts\n * const reg = await navigator.serviceWorker.ready;\n * const device = await client.devices.registerWebPush(reg, { label: \"Chrome on Mac\" });\n * // later, from a settings screen:\n * await client.devices.unregisterWebPush(reg);\n * ```\n */\n\nexport type DeviceKind = \"webpush\" | \"fcm\" | \"apns\" | \"telegram_miniapp\";\n\nexport type DevicePlatform = \"pwa\" | \"web\" | \"ios\" | \"android\" | \"telegram\";\n\nexport interface Device {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** Free-form name the app gave it (\"Chrome on Mac\"), or `null`. */\n label: string | null;\n locale: string | null;\n app_version: string | null;\n created_at: string;\n last_seen_at: string;\n /** Set when the device no longer receives anything (the push endpoint is\n * gone, or someone switched it off). */\n disabled_at: string | null;\n /** `true` when it was registered from the session this client holds. */\n is_current: boolean;\n}\n\n/** `PushSubscription.toJSON()` minus the parts the server doesn't need. */\nexport interface WebPushCredential {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** FCM registration token or APNs device token. */\nexport interface MobilePushCredential {\n token: string;\n}\n\nexport type RegisterDeviceInput =\n | {\n kind: \"webpush\";\n platform: DevicePlatform;\n credential: WebPushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"fcm\" | \"apns\";\n platform: DevicePlatform;\n credential: MobilePushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"telegram_miniapp\";\n platform: DevicePlatform;\n /** Nothing to send: the device is a marker. */\n credential: Record<string, never>;\n label?: string;\n locale?: string;\n app_version?: string;\n };\n\nexport interface RegisteredDevice {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`;\n * `null` when push is not set up on this deployment. */\n vapid_public_key: string | null;\n}\n\nexport interface RegisterWebPushOptions {\n /** A name to show in the user's device list (\"Chrome on Mac\"). */\n label?: string;\n /** Skip the key lookup when you already hold the deployment's VAPID\n * public key (from an earlier `register` result, for example). */\n vapidPublicKey?: string;\n}\n\nexport interface UnregisterWebPushOptions {\n /** The device to delete, from an earlier `registerWebPush` result. When\n * omitted, every Web Push device registered from this session goes. */\n deviceId?: string;\n}\n\n/** Client platform → the platform the device list uses. */\nexport function devicePlatformOf(platform: ClientPlatform): DevicePlatform {\n return platform === \"telegram-miniapp\" ? \"telegram\" : platform;\n}\n\nexport class DevicesResource {\n constructor(\n private readonly http: HttpClient,\n private readonly client: ResolvedClientDescriptor,\n ) {}\n\n /** Every device the user has, disabled ones included. */\n async list(): Promise<Device[]> {\n return this.http.get<Device[]>(\"/me/devices\");\n }\n\n /** Register a device, or refresh it when the same credential is already\n * known (then `last_seen_at`, `label` and `app_version` update and a\n * disabled device comes back). `app_version` defaults to the client\n * version sent in `X-Takeal-Client`.\n *\n * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the\n * deployment has no VAPID keys. */\n async register(input: RegisterDeviceInput): Promise<RegisteredDevice> {\n return this.http.put<RegisteredDevice>(\"/me/devices\", {\n body: { app_version: this.client.version, ...input },\n });\n }\n\n /** Delete one device. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/devices/${encodeURIComponent(id)}`);\n }\n\n /** Subscribe this browser to Web Push and register it as a device. Ask\n * for notification permission before calling. Throws when push isn't\n * set up on the deployment. */\n async registerWebPush(\n registration: PushCapableRegistration,\n opts: RegisterWebPushOptions = {},\n ): Promise<RegisteredDevice> {\n const key = opts.vapidPublicKey ?? (await this.vapidPublicKey());\n if (!key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.register({\n kind: \"webpush\",\n platform: devicePlatformOf(this.client.platform),\n credential: {\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n },\n ...(opts.label ? { label: opts.label } : {}),\n });\n }\n\n /** Unsubscribe this browser from Web Push and delete the matching device\n * (see {@link UnregisterWebPushOptions}). Safe when nothing is\n * registered. */\n async unregisterWebPush(\n registration: PushCapableRegistration,\n opts: UnregisterWebPushOptions = {},\n ): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n if (opts.deviceId) {\n await this.remove(opts.deviceId);\n return;\n }\n const mine = (await this.list()).filter((d) => d.kind === \"webpush\" && d.is_current);\n for (const d of mine) await this.remove(d.id);\n }\n\n private async vapidPublicKey(): Promise<string | null> {\n const { vapid_public_key } = await this.http.get<{ vapid_public_key?: string | null }>(\n \"/me/push-subscription\",\n );\n return vapid_public_key ?? null;\n }\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import '../http-B-OQwMYn.cjs';
|
|
2
|
+
export { c as Device, d as DeviceKind, e as DevicePlatform, D as DevicesResource, M as MobilePushCredential, f as RegisterDeviceInput, g as RegisterWebPushOptions, h as RegisteredDevice, U as UnregisterWebPushOptions, W as WebPushCredential, j as devicePlatformOf } from '../devices-C3JHi2Hi.cjs';
|
|
3
|
+
import './push.cjs';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import '../http-B-OQwMYn.js';
|
|
2
|
+
export { c as Device, d as DeviceKind, e as DevicePlatform, D as DevicesResource, M as MobilePushCredential, f as RegisterDeviceInput, g as RegisterWebPushOptions, h as RegisteredDevice, U as UnregisterWebPushOptions, W as WebPushCredential, j as devicePlatformOf } from '../devices-DP_hxwmW.js';
|
|
3
|
+
import './push.js';
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// src/resources/push.ts
|
|
2
|
+
function base64UrlToBytes(input) {
|
|
3
|
+
const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
4
|
+
const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
|
|
5
|
+
const bin = atob(padded);
|
|
6
|
+
const out = new Uint8Array(bin.length);
|
|
7
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
8
|
+
return out;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// src/resources/devices.ts
|
|
12
|
+
function devicePlatformOf(platform) {
|
|
13
|
+
return platform === "telegram-miniapp" ? "telegram" : platform;
|
|
14
|
+
}
|
|
15
|
+
var DevicesResource = class {
|
|
16
|
+
constructor(http, client) {
|
|
17
|
+
this.http = http;
|
|
18
|
+
this.client = client;
|
|
19
|
+
}
|
|
20
|
+
/** Every device the user has, disabled ones included. */
|
|
21
|
+
async list() {
|
|
22
|
+
return this.http.get("/me/devices");
|
|
23
|
+
}
|
|
24
|
+
/** Register a device, or refresh it when the same credential is already
|
|
25
|
+
* known (then `last_seen_at`, `label` and `app_version` update and a
|
|
26
|
+
* disabled device comes back). `app_version` defaults to the client
|
|
27
|
+
* version sent in `X-Takeal-Client`.
|
|
28
|
+
*
|
|
29
|
+
* Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
|
|
30
|
+
* deployment has no VAPID keys. */
|
|
31
|
+
async register(input) {
|
|
32
|
+
return this.http.put("/me/devices", {
|
|
33
|
+
body: { app_version: this.client.version, ...input }
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/** Delete one device. 404 when it isn't the user's. */
|
|
37
|
+
async remove(id) {
|
|
38
|
+
await this.http.delete(`/me/devices/${encodeURIComponent(id)}`);
|
|
39
|
+
}
|
|
40
|
+
/** Subscribe this browser to Web Push and register it as a device. Ask
|
|
41
|
+
* for notification permission before calling. Throws when push isn't
|
|
42
|
+
* set up on the deployment. */
|
|
43
|
+
async registerWebPush(registration, opts = {}) {
|
|
44
|
+
const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
|
|
45
|
+
if (!key) {
|
|
46
|
+
throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
|
|
47
|
+
}
|
|
48
|
+
const sub = await registration.pushManager.subscribe({
|
|
49
|
+
userVisibleOnly: true,
|
|
50
|
+
applicationServerKey: base64UrlToBytes(key)
|
|
51
|
+
});
|
|
52
|
+
const json = sub.toJSON();
|
|
53
|
+
if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
|
|
54
|
+
throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
|
|
55
|
+
}
|
|
56
|
+
return this.register({
|
|
57
|
+
kind: "webpush",
|
|
58
|
+
platform: devicePlatformOf(this.client.platform),
|
|
59
|
+
credential: {
|
|
60
|
+
endpoint: json.endpoint,
|
|
61
|
+
keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
|
|
62
|
+
},
|
|
63
|
+
...opts.label ? { label: opts.label } : {}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Unsubscribe this browser from Web Push and delete the matching device
|
|
67
|
+
* (see {@link UnregisterWebPushOptions}). Safe when nothing is
|
|
68
|
+
* registered. */
|
|
69
|
+
async unregisterWebPush(registration, opts = {}) {
|
|
70
|
+
const sub = await registration.pushManager.getSubscription();
|
|
71
|
+
if (sub) await sub.unsubscribe();
|
|
72
|
+
if (opts.deviceId) {
|
|
73
|
+
await this.remove(opts.deviceId);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const mine = (await this.list()).filter((d) => d.kind === "webpush" && d.is_current);
|
|
77
|
+
for (const d of mine) await this.remove(d.id);
|
|
78
|
+
}
|
|
79
|
+
async vapidPublicKey() {
|
|
80
|
+
const { vapid_public_key } = await this.http.get(
|
|
81
|
+
"/me/push-subscription"
|
|
82
|
+
);
|
|
83
|
+
return vapid_public_key ?? null;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export { DevicesResource, devicePlatformOf };
|
|
88
|
+
//# sourceMappingURL=devices.js.map
|
|
89
|
+
//# sourceMappingURL=devices.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/resources/push.ts","../../src/resources/devices.ts"],"names":[],"mappings":";AAsGO,SAAS,iBAAiB,KAAA,EAA2B;AAC1D,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,MAAM,GAAG,CAAA;AACtD,EAAA,MAAM,MAAA,GAAS,MAAM,GAAA,CAAI,MAAA,CAAA,CAAQ,IAAK,GAAA,CAAI,MAAA,GAAS,KAAM,CAAC,CAAA;AAC1D,EAAA,MAAM,GAAA,GAAM,KAAK,MAAM,CAAA;AACvB,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,GAAA,CAAI,MAAM,CAAA;AACrC,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,MAAA,EAAQ,CAAA,EAAA,EAAK,GAAA,CAAI,CAAC,CAAA,GAAI,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA;AAC9D,EAAA,OAAO,GAAA;AACT;;;ACEO,SAAS,iBAAiB,QAAA,EAA0C;AACzE,EAAA,OAAO,QAAA,KAAa,qBAAqB,UAAA,GAAa,QAAA;AACxD;AAEO,IAAM,kBAAN,MAAsB;AAAA,EAC3B,WAAA,CACmB,MACA,MAAA,EACjB;AAFiB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAChB;AAAA;AAAA,EAGH,MAAM,IAAA,GAA0B;AAC9B,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CA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,MAC/C,UAAA,EAAY;AAAA,QACV,UAAU,IAAA,CAAK,QAAA;AAAA,QACf,IAAA,EAAM,EAAE,MAAA,EAAQ,IAAA,CAAK,KAAK,MAAA,EAAQ,IAAA,EAAM,IAAA,CAAK,IAAA,CAAK,IAAA;AAAK,OACzD;AAAA,MACA,GAAI,KAAK,KAAA,GAAQ,EAAE,OAAO,IAAA,CAAK,KAAA,KAAU;AAAC,KAC3C,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,iBAAA,CACJ,YAAA,EACA,IAAA,GAAiC,EAAC,EACnB;AACf,IAAA,MAAM,GAAA,GAAM,MAAM,YAAA,CAAa,WAAA,CAAY,eAAA,EAAgB;AAC3D,IAAA,IAAI,GAAA,EAAK,MAAM,GAAA,CAAI,WAAA,EAAY;AAC/B,IAAA,IAAI,KAAK,QAAA,EAAU;AACjB,MAAA,MAAM,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA;AAC/B,MAAA;AAAA,IACF;AACA,IAAA,MAAM,IAAA,GAAA,CAAQ,MAAM,IAAA,CAAK,IAAA,EAAK,EAAG,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,SAAA,IAAa,CAAA,CAAE,UAAU,CAAA;AACnF,IAAA,KAAA,MAAW,KAAK,IAAA,EAAM,MAAM,IAAA,CAAK,MAAA,CAAO,EAAE,EAAE,CAAA;AAAA,EAC9C;AAAA,EAEA,MAAc,cAAA,GAAyC;AACrD,IAAA,MAAM,EAAE,gBAAA,EAAiB,GAAI,MAAM,KAAK,IAAA,CAAK,GAAA;AAAA,MAC3C;AAAA,KACF;AACA,IAAA,OAAO,gBAAA,IAAoB,IAAA;AAAA,EAC7B;AACF","file":"devices.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Push resource — `client.push.*`.\n *\n * Web Push for the signed-in user, through the older single-subscription\n * endpoint. The API now keeps one device per browser (see\n * `client.devices`), and this endpoint is an alias over the Web Push\n * devices: it keeps working, but new code should call\n * `client.devices.registerWebPush(reg)` / `unregisterWebPush(reg)` instead.\n *\n * Your service worker shows the notification: the payload is JSON with\n * `title`, `body` and `url` (where a click should lead).\n */\n\nexport interface PushStatus {\n /** `true` when a subscription is stored for this user. */\n subscribed: boolean;\n /** Host of the stored endpoint, e.g. `fcm.googleapis.com`. */\n endpoint_host?: string | null;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`.\n * `null` when push is not set up on this deployment. */\n vapid_public_key?: string | null;\n}\n\nexport interface PushSubscriptionInput {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** The part of `ServiceWorkerRegistration` the SDK needs. Typed\n * structurally so the core stays free of DOM lib types. */\nexport interface PushCapableRegistration {\n pushManager: {\n getSubscription(): Promise<{ unsubscribe(): Promise<boolean> } | null>;\n subscribe(options: {\n userVisibleOnly: boolean;\n applicationServerKey: Uint8Array;\n }): Promise<{ toJSON(): { endpoint?: string; keys?: Record<string, string> } }>;\n };\n}\n\nexport class PushResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Whether the user is subscribed, plus the VAPID key to subscribe with. */\n async status(): Promise<PushStatus> {\n return this.http.get<PushStatus>(\"/me/push-subscription\");\n }\n\n /** Store a subscription you created yourself.\n * 409 `push_disabled` when the deployment has no VAPID keys.\n * @deprecated Use `client.devices.register({ kind: \"webpush\", ... })`. */\n async save(input: PushSubscriptionInput): Promise<PushStatus> {\n return this.http.put<PushStatus>(\"/me/push-subscription\", { body: input });\n }\n\n /** Delete the stored subscription. Safe when nothing is stored.\n * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */\n async remove(): Promise<void> {\n await this.http.delete<void>(\"/me/push-subscription\");\n }\n\n /** Subscribe this browser and store the subscription. Ask for\n * notification permission before calling. Throws when push isn't set up\n * on the deployment.\n * @deprecated Use `client.devices.registerWebPush(registration)`. */\n async enable(registration: PushCapableRegistration): Promise<PushStatus> {\n const { vapid_public_key } = await this.status();\n if (!vapid_public_key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(vapid_public_key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.save({\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n });\n }\n\n /** Unsubscribe this browser and delete the stored subscription.\n * @deprecated Use `client.devices.unregisterWebPush(registration)`. */\n async disable(registration: PushCapableRegistration): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n await this.remove();\n }\n}\n\n/** URL-safe base64 (padding optional) → bytes. */\nexport function base64UrlToBytes(input: string): Uint8Array {\n const b64 = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = b64 + \"=\".repeat((4 - (b64.length % 4)) % 4);\n const bin = atob(padded);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n","import type { HttpClient } from \"../http.js\";\nimport type { ClientPlatform, ResolvedClientDescriptor } from \"../client-platform.js\";\nimport { base64UrlToBytes, type PushCapableRegistration } from \"./push.js\";\n\n/**\n * Devices resource — `client.devices.*`.\n *\n * A user has many devices: each browser with a Web Push subscription, each\n * phone with an FCM / APNs token, and a marker for \"uses the Telegram Mini\n * App\". The server picks the notification channel from them: a mobile app\n * first, otherwise the device seen most recently.\n *\n * The usual browser flow, once notification permission is granted:\n *\n * ```ts\n * const reg = await navigator.serviceWorker.ready;\n * const device = await client.devices.registerWebPush(reg, { label: \"Chrome on Mac\" });\n * // later, from a settings screen:\n * await client.devices.unregisterWebPush(reg);\n * ```\n */\n\nexport type DeviceKind = \"webpush\" | \"fcm\" | \"apns\" | \"telegram_miniapp\";\n\nexport type DevicePlatform = \"pwa\" | \"web\" | \"ios\" | \"android\" | \"telegram\";\n\nexport interface Device {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** Free-form name the app gave it (\"Chrome on Mac\"), or `null`. */\n label: string | null;\n locale: string | null;\n app_version: string | null;\n created_at: string;\n last_seen_at: string;\n /** Set when the device no longer receives anything (the push endpoint is\n * gone, or someone switched it off). */\n disabled_at: string | null;\n /** `true` when it was registered from the session this client holds. */\n is_current: boolean;\n}\n\n/** `PushSubscription.toJSON()` minus the parts the server doesn't need. */\nexport interface WebPushCredential {\n /** `PushSubscription.endpoint`; must be https. */\n endpoint: string;\n keys: {\n /** URL-safe base64. */\n p256dh: string;\n /** URL-safe base64. */\n auth: string;\n };\n}\n\n/** FCM registration token or APNs device token. */\nexport interface MobilePushCredential {\n token: string;\n}\n\nexport type RegisterDeviceInput =\n | {\n kind: \"webpush\";\n platform: DevicePlatform;\n credential: WebPushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"fcm\" | \"apns\";\n platform: DevicePlatform;\n credential: MobilePushCredential;\n label?: string;\n locale?: string;\n app_version?: string;\n }\n | {\n kind: \"telegram_miniapp\";\n platform: DevicePlatform;\n /** Nothing to send: the device is a marker. */\n credential: Record<string, never>;\n label?: string;\n locale?: string;\n app_version?: string;\n };\n\nexport interface RegisteredDevice {\n id: string;\n kind: DeviceKind;\n platform: DevicePlatform;\n /** VAPID public key (URL-safe base64) for `pushManager.subscribe`;\n * `null` when push is not set up on this deployment. */\n vapid_public_key: string | null;\n}\n\nexport interface RegisterWebPushOptions {\n /** A name to show in the user's device list (\"Chrome on Mac\"). */\n label?: string;\n /** Skip the key lookup when you already hold the deployment's VAPID\n * public key (from an earlier `register` result, for example). */\n vapidPublicKey?: string;\n}\n\nexport interface UnregisterWebPushOptions {\n /** The device to delete, from an earlier `registerWebPush` result. When\n * omitted, every Web Push device registered from this session goes. */\n deviceId?: string;\n}\n\n/** Client platform → the platform the device list uses. */\nexport function devicePlatformOf(platform: ClientPlatform): DevicePlatform {\n return platform === \"telegram-miniapp\" ? \"telegram\" : platform;\n}\n\nexport class DevicesResource {\n constructor(\n private readonly http: HttpClient,\n private readonly client: ResolvedClientDescriptor,\n ) {}\n\n /** Every device the user has, disabled ones included. */\n async list(): Promise<Device[]> {\n return this.http.get<Device[]>(\"/me/devices\");\n }\n\n /** Register a device, or refresh it when the same credential is already\n * known (then `last_seen_at`, `label` and `app_version` update and a\n * disabled device comes back). `app_version` defaults to the client\n * version sent in `X-Takeal-Client`.\n *\n * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the\n * deployment has no VAPID keys. */\n async register(input: RegisterDeviceInput): Promise<RegisteredDevice> {\n return this.http.put<RegisteredDevice>(\"/me/devices\", {\n body: { app_version: this.client.version, ...input },\n });\n }\n\n /** Delete one device. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/devices/${encodeURIComponent(id)}`);\n }\n\n /** Subscribe this browser to Web Push and register it as a device. Ask\n * for notification permission before calling. Throws when push isn't\n * set up on the deployment. */\n async registerWebPush(\n registration: PushCapableRegistration,\n opts: RegisterWebPushOptions = {},\n ): Promise<RegisteredDevice> {\n const key = opts.vapidPublicKey ?? (await this.vapidPublicKey());\n if (!key) {\n throw new Error(\"@takeal/cusfront-sdk: push notifications are not enabled on this deployment\");\n }\n const sub = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: base64UrlToBytes(key),\n });\n const json = sub.toJSON();\n if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {\n throw new Error(\"@takeal/cusfront-sdk: the browser returned an incomplete push subscription\");\n }\n return this.register({\n kind: \"webpush\",\n platform: devicePlatformOf(this.client.platform),\n credential: {\n endpoint: json.endpoint,\n keys: { p256dh: json.keys.p256dh, auth: json.keys.auth },\n },\n ...(opts.label ? { label: opts.label } : {}),\n });\n }\n\n /** Unsubscribe this browser from Web Push and delete the matching device\n * (see {@link UnregisterWebPushOptions}). Safe when nothing is\n * registered. */\n async unregisterWebPush(\n registration: PushCapableRegistration,\n opts: UnregisterWebPushOptions = {},\n ): Promise<void> {\n const sub = await registration.pushManager.getSubscription();\n if (sub) await sub.unsubscribe();\n if (opts.deviceId) {\n await this.remove(opts.deviceId);\n return;\n }\n const mine = (await this.list()).filter((d) => d.kind === \"webpush\" && d.is_current);\n for (const d of mine) await this.remove(d.id);\n }\n\n private async vapidPublicKey(): Promise<string | null> {\n const { vapid_public_key } = await this.http.get<{ vapid_public_key?: string | null }>(\n \"/me/push-subscription\",\n );\n return vapid_public_key ?? null;\n }\n}\n"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/resources/me.ts
|
|
4
|
+
var MeResource = class {
|
|
5
|
+
constructor(http) {
|
|
6
|
+
this.http = http;
|
|
7
|
+
}
|
|
8
|
+
/** Attach the Telegram account behind `initData` to the signed-in user.
|
|
9
|
+
* Returns the updated user (`telegram` is set). Repeating the call with
|
|
10
|
+
* the same Telegram is fine.
|
|
11
|
+
*
|
|
12
|
+
* Errors: 401 `invalid_init_data`; 403 `user_disabled` /
|
|
13
|
+
* `second_factor_required`; 409 `telegram_already_linked_other` (the
|
|
14
|
+
* account already has a different Telegram; `unlinkTelegram` first) /
|
|
15
|
+
* `telegram_in_use` (that Telegram belongs to another account); 503
|
|
16
|
+
* `telegram_not_configured`. */
|
|
17
|
+
async linkTelegram(initData) {
|
|
18
|
+
return this.http.post("/me/telegram", { body: { init_data: initData } });
|
|
19
|
+
}
|
|
20
|
+
/** Detach the Telegram account from the signed-in user. Returns the
|
|
21
|
+
* updated user (`telegram` is `null`).
|
|
22
|
+
*
|
|
23
|
+
* Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
|
|
24
|
+
* account has no password, so Telegram is its only way to sign in. */
|
|
25
|
+
async unlinkTelegram() {
|
|
26
|
+
return this.http.delete("/me/telegram");
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
exports.MeResource = MeResource;
|
|
31
|
+
//# sourceMappingURL=me.cjs.map
|
|
32
|
+
//# sourceMappingURL=me.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/resources/me.ts"],"names":[],"mappings":";;;AAkBO,IAAM,aAAN,MAAiB;AAAA,EACtB,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWhD,MAAM,aAAa,QAAA,EAAiC;AAClD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,cAAA,EAAgB,EAAE,MAAM,EAAE,SAAA,EAAW,QAAA,EAAS,EAAG,CAAA;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,cAAA,GAAgC;AACpC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,MAAA,CAAa,cAAc,CAAA;AAAA,EAC9C;AACF","file":"me.cjs","sourcesContent":["import type { HttpClient } from \"../http.js\";\nimport type { User } from \"./auth.js\";\n\n/**\n * Me resource — `client.me.*`.\n *\n * Profile-level actions for the signed-in user that don't belong to another\n * resource. Today: the Telegram link.\n *\n * ```ts\n * // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):\n * const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);\n * me.telegram; // { username, linked_at }\n *\n * // From a settings screen:\n * await client.me.unlinkTelegram();\n * ```\n */\nexport class MeResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Attach the Telegram account behind `initData` to the signed-in user.\n * Returns the updated user (`telegram` is set). Repeating the call with\n * the same Telegram is fine.\n *\n * Errors: 401 `invalid_init_data`; 403 `user_disabled` /\n * `second_factor_required`; 409 `telegram_already_linked_other` (the\n * account already has a different Telegram; `unlinkTelegram` first) /\n * `telegram_in_use` (that Telegram belongs to another account); 503\n * `telegram_not_configured`. */\n async linkTelegram(initData: string): Promise<User> {\n return this.http.post<User>(\"/me/telegram\", { body: { init_data: initData } });\n }\n\n /** Detach the Telegram account from the signed-in user. Returns the\n * updated user (`telegram` is `null`).\n *\n * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the\n * account has no password, so Telegram is its only way to sign in. */\n async unlinkTelegram(): Promise<User> {\n return this.http.delete<User>(\"/me/telegram\");\n }\n}\n"]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { H as HttpClient } from '../http-B-OQwMYn.cjs';
|
|
2
|
+
import { User } from './auth.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Me resource — `client.me.*`.
|
|
6
|
+
*
|
|
7
|
+
* Profile-level actions for the signed-in user that don't belong to another
|
|
8
|
+
* resource. Today: the Telegram link.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):
|
|
12
|
+
* const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);
|
|
13
|
+
* me.telegram; // { username, linked_at }
|
|
14
|
+
*
|
|
15
|
+
* // From a settings screen:
|
|
16
|
+
* await client.me.unlinkTelegram();
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
declare class MeResource {
|
|
20
|
+
private readonly http;
|
|
21
|
+
constructor(http: HttpClient);
|
|
22
|
+
/** Attach the Telegram account behind `initData` to the signed-in user.
|
|
23
|
+
* Returns the updated user (`telegram` is set). Repeating the call with
|
|
24
|
+
* the same Telegram is fine.
|
|
25
|
+
*
|
|
26
|
+
* Errors: 401 `invalid_init_data`; 403 `user_disabled` /
|
|
27
|
+
* `second_factor_required`; 409 `telegram_already_linked_other` (the
|
|
28
|
+
* account already has a different Telegram; `unlinkTelegram` first) /
|
|
29
|
+
* `telegram_in_use` (that Telegram belongs to another account); 503
|
|
30
|
+
* `telegram_not_configured`. */
|
|
31
|
+
linkTelegram(initData: string): Promise<User>;
|
|
32
|
+
/** Detach the Telegram account from the signed-in user. Returns the
|
|
33
|
+
* updated user (`telegram` is `null`).
|
|
34
|
+
*
|
|
35
|
+
* Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
|
|
36
|
+
* account has no password, so Telegram is its only way to sign in. */
|
|
37
|
+
unlinkTelegram(): Promise<User>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export { MeResource };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { H as HttpClient } from '../http-B-OQwMYn.js';
|
|
2
|
+
import { User } from './auth.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Me resource — `client.me.*`.
|
|
6
|
+
*
|
|
7
|
+
* Profile-level actions for the signed-in user that don't belong to another
|
|
8
|
+
* resource. Today: the Telegram link.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):
|
|
12
|
+
* const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);
|
|
13
|
+
* me.telegram; // { username, linked_at }
|
|
14
|
+
*
|
|
15
|
+
* // From a settings screen:
|
|
16
|
+
* await client.me.unlinkTelegram();
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
declare class MeResource {
|
|
20
|
+
private readonly http;
|
|
21
|
+
constructor(http: HttpClient);
|
|
22
|
+
/** Attach the Telegram account behind `initData` to the signed-in user.
|
|
23
|
+
* Returns the updated user (`telegram` is set). Repeating the call with
|
|
24
|
+
* the same Telegram is fine.
|
|
25
|
+
*
|
|
26
|
+
* Errors: 401 `invalid_init_data`; 403 `user_disabled` /
|
|
27
|
+
* `second_factor_required`; 409 `telegram_already_linked_other` (the
|
|
28
|
+
* account already has a different Telegram; `unlinkTelegram` first) /
|
|
29
|
+
* `telegram_in_use` (that Telegram belongs to another account); 503
|
|
30
|
+
* `telegram_not_configured`. */
|
|
31
|
+
linkTelegram(initData: string): Promise<User>;
|
|
32
|
+
/** Detach the Telegram account from the signed-in user. Returns the
|
|
33
|
+
* updated user (`telegram` is `null`).
|
|
34
|
+
*
|
|
35
|
+
* Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
|
|
36
|
+
* account has no password, so Telegram is its only way to sign in. */
|
|
37
|
+
unlinkTelegram(): Promise<User>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export { MeResource };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// src/resources/me.ts
|
|
2
|
+
var MeResource = class {
|
|
3
|
+
constructor(http) {
|
|
4
|
+
this.http = http;
|
|
5
|
+
}
|
|
6
|
+
/** Attach the Telegram account behind `initData` to the signed-in user.
|
|
7
|
+
* Returns the updated user (`telegram` is set). Repeating the call with
|
|
8
|
+
* the same Telegram is fine.
|
|
9
|
+
*
|
|
10
|
+
* Errors: 401 `invalid_init_data`; 403 `user_disabled` /
|
|
11
|
+
* `second_factor_required`; 409 `telegram_already_linked_other` (the
|
|
12
|
+
* account already has a different Telegram; `unlinkTelegram` first) /
|
|
13
|
+
* `telegram_in_use` (that Telegram belongs to another account); 503
|
|
14
|
+
* `telegram_not_configured`. */
|
|
15
|
+
async linkTelegram(initData) {
|
|
16
|
+
return this.http.post("/me/telegram", { body: { init_data: initData } });
|
|
17
|
+
}
|
|
18
|
+
/** Detach the Telegram account from the signed-in user. Returns the
|
|
19
|
+
* updated user (`telegram` is `null`).
|
|
20
|
+
*
|
|
21
|
+
* Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
|
|
22
|
+
* account has no password, so Telegram is its only way to sign in. */
|
|
23
|
+
async unlinkTelegram() {
|
|
24
|
+
return this.http.delete("/me/telegram");
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export { MeResource };
|
|
29
|
+
//# sourceMappingURL=me.js.map
|
|
30
|
+
//# sourceMappingURL=me.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/resources/me.ts"],"names":[],"mappings":";AAkBO,IAAM,aAAN,MAAiB;AAAA,EACtB,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWhD,MAAM,aAAa,QAAA,EAAiC;AAClD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAW,cAAA,EAAgB,EAAE,MAAM,EAAE,SAAA,EAAW,QAAA,EAAS,EAAG,CAAA;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,cAAA,GAAgC;AACpC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,MAAA,CAAa,cAAc,CAAA;AAAA,EAC9C;AACF","file":"me.js","sourcesContent":["import type { HttpClient } from \"../http.js\";\nimport type { User } from \"./auth.js\";\n\n/**\n * Me resource — `client.me.*`.\n *\n * Profile-level actions for the signed-in user that don't belong to another\n * resource. Today: the Telegram link.\n *\n * ```ts\n * // Inside a Mini App, with a signed-in client (e.g. opened via a deep link):\n * const me = await client.me.linkTelegram(window.Telegram.WebApp.initData);\n * me.telegram; // { username, linked_at }\n *\n * // From a settings screen:\n * await client.me.unlinkTelegram();\n * ```\n */\nexport class MeResource {\n constructor(private readonly http: HttpClient) {}\n\n /** Attach the Telegram account behind `initData` to the signed-in user.\n * Returns the updated user (`telegram` is set). Repeating the call with\n * the same Telegram is fine.\n *\n * Errors: 401 `invalid_init_data`; 403 `user_disabled` /\n * `second_factor_required`; 409 `telegram_already_linked_other` (the\n * account already has a different Telegram; `unlinkTelegram` first) /\n * `telegram_in_use` (that Telegram belongs to another account); 503\n * `telegram_not_configured`. */\n async linkTelegram(initData: string): Promise<User> {\n return this.http.post<User>(\"/me/telegram\", { body: { init_data: initData } });\n }\n\n /** Detach the Telegram account from the signed-in user. Returns the\n * updated user (`telegram` is `null`).\n *\n * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the\n * account has no password, so Telegram is its only way to sign in. */\n async unlinkTelegram(): Promise<User> {\n return this.http.delete<User>(\"/me/telegram\");\n }\n}\n"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/resources/notifications.ts
|
|
4
|
+
var NotificationsResource = class {
|
|
5
|
+
constructor(http) {
|
|
6
|
+
this.http = http;
|
|
7
|
+
}
|
|
8
|
+
/** One page of the inbox, newest first. */
|
|
9
|
+
async list(params = {}) {
|
|
10
|
+
const q = new URLSearchParams();
|
|
11
|
+
if (params.cursor) q.set("cursor", params.cursor);
|
|
12
|
+
if (params.limit !== void 0) q.set("limit", String(params.limit));
|
|
13
|
+
if (params.unreadOnly) q.set("unread", "true");
|
|
14
|
+
if (params.category) q.set("category", params.category);
|
|
15
|
+
const qs = q.toString();
|
|
16
|
+
return this.http.get(`/me/notifications${qs ? `?${qs}` : ""}`);
|
|
17
|
+
}
|
|
18
|
+
/** How many items are unread. Cheap; fine to poll for a badge. */
|
|
19
|
+
async unreadCount() {
|
|
20
|
+
const { unread } = await this.http.get("/me/notifications/unread-count");
|
|
21
|
+
return unread;
|
|
22
|
+
}
|
|
23
|
+
/** Mark one item read. Returns the item; calling it again is harmless. */
|
|
24
|
+
async markRead(id) {
|
|
25
|
+
return this.http.post(`/me/notifications/${encodeURIComponent(id)}/read`);
|
|
26
|
+
}
|
|
27
|
+
/** Mark every unread item read, or only those created before `before`
|
|
28
|
+
* (ISO timestamp). Returns how many changed. */
|
|
29
|
+
async markAllRead(before) {
|
|
30
|
+
return this.http.post("/me/notifications/read-all", {
|
|
31
|
+
body: before ? { before } : {}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** Delete one item. 404 when it isn't the user's. */
|
|
35
|
+
async remove(id) {
|
|
36
|
+
await this.http.delete(`/me/notifications/${encodeURIComponent(id)}`);
|
|
37
|
+
}
|
|
38
|
+
/** The user's channel and language settings. */
|
|
39
|
+
async getPreferences() {
|
|
40
|
+
return this.http.get("/me/notification-preferences");
|
|
41
|
+
}
|
|
42
|
+
/** Change some settings; the rest stay. Returns the stored view.
|
|
43
|
+
* 400 `validation` for an unknown category, channel or locale. */
|
|
44
|
+
async setPreferences(input) {
|
|
45
|
+
return this.http.put("/me/notification-preferences", {
|
|
46
|
+
body: input
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
exports.NotificationsResource = NotificationsResource;
|
|
52
|
+
//# sourceMappingURL=notifications.cjs.map
|
|
53
|
+
//# sourceMappingURL=notifications.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/resources/notifications.ts"],"names":[],"mappings":";;;AAiGO,IAAM,wBAAN,MAA4B;AAAA,EACjC,YAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA,EAAmB;AAAA;AAAA,EAGhD,MAAM,IAAA,CAAK,MAAA,GAAkC,EAAC,EAA8B;AAC1E,IAAA,MAAM,CAAA,GAAI,IAAI,eAAA,EAAgB;AAC9B,IAAA,IAAI,OAAO,MAAA,EAAQ,CAAA,CAAE,GAAA,CAAI,QAAA,EAAU,OAAO,MAAM,CAAA;AAChD,IAAA,IAAI,MAAA,CAAO,UAAU,MAAA,EAAW,CAAA,CAAE,IAAI,OAAA,EAAS,MAAA,CAAO,MAAA,CAAO,KAAK,CAAC,CAAA;AACnE,IAAA,IAAI,MAAA,CAAO,UAAA,EAAY,CAAA,CAAE,GAAA,CAAI,UAAU,MAAM,CAAA;AAC7C,IAAA,IAAI,OAAO,QAAA,EAAU,CAAA,CAAE,GAAA,CAAI,UAAA,EAAY,OAAO,QAAQ,CAAA;AACtD,IAAA,MAAM,EAAA,GAAK,EAAE,QAAA,EAAS;AACtB,IAAA,OAAO,IAAA,CAAK,KAAK,GAAA,CAAsB,CAAA,iBAAA,EAAoB,KAAK,CAAA,CAAA,EAAI,EAAE,CAAA,CAAA,GAAK,EAAE,CAAA,CAAE,CAAA;AAAA,EACjF;AAAA;AAAA,EAGA,MAAM,WAAA,GAA+B;AACnC,IAAA,MAAM,EAAE,MAAA,EAAO,GAAI,MAAM,IAAA,CAAK,IAAA,CAAK,IAAwB,gCAAgC,CAAA;AAC3F,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,SAAS,EAAA,EAAgC;AAC7C,IAAA,OAAO,KAAK,IAAA,CAAK,IAAA,CAAgB,qBAAqB,kBAAA,CAAmB,EAAE,CAAC,CAAA,KAAA,CAAO,CAAA;AAAA,EACrF;AAAA;AAAA;AAAA,EAIA,MAAM,YAAY,MAAA,EAA8C;AAC9D,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,IAAA,CAAyB,4BAAA,EAA8B;AAAA,MACtE,IAAA,EAAM,MAAA,GAAS,EAAE,MAAA,KAAW;AAAC,KAC9B,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,OAAO,EAAA,EAA2B;AACtC,IAAA,MAAM,KAAK,IAAA,CAAK,MAAA,CAAa,qBAAqB,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAAA,EAC5E;AAAA;AAAA,EAGA,MAAM,cAAA,GAAmD;AACvD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA6B,8BAA8B,CAAA;AAAA,EAC9E;AAAA;AAAA;AAAA,EAIA,MAAM,eAAe,KAAA,EAAuE;AAC1F,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA6B,8BAAA,EAAgC;AAAA,MAC5E,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACF","file":"notifications.cjs","sourcesContent":["import type { HttpClient } from \"../http.js\";\n\n/**\n * Notifications resource — `client.notifications.*`.\n *\n * Every notification a user gets is also kept server-side as an inbox item,\n * whatever else was sent (a push, a Telegram message, an email). The inbox\n * is what the app shows; the other channels are the nudge to open it.\n *\n * ```ts\n * const page = await client.notifications.list({ limit: 20 });\n * for (const item of page.items) {\n * render(item.title, item.body, item.href); // href: a path inside your app, or null\n * }\n * await client.notifications.markRead(page.items[0].id);\n * ```\n *\n * Preferences decide where the nudge goes: a primary channel (or automatic\n * when `null`), per-category switches, and the user's language.\n */\n\n/** What an item is about. `security` and `money` can't be switched off\n * completely; `marketing` is off until the user opts in. */\nexport type NotificationCategory = \"money\" | \"card\" | \"security\" | \"account\" | \"marketing\";\n\n/** A way to reach the user outside the inbox. */\nexport type NotificationChannel = \"push\" | \"telegram\" | \"email\" | \"sms\";\n\n/** Language the user reads notifications in. */\nexport type NotificationLocale = \"en\" | \"ru\" | (string & {});\n\nexport interface InboxItem {\n id: string;\n /** What happened, e.g. `deposit_confirmed`, `card_transaction`, `login_new_device`. */\n event_type: string;\n category: NotificationCategory;\n title: string;\n body: string;\n /** A path inside the client app to open on tap (`/cards/<id>`,\n * `/deposits/<id>`, `/subscription`, `/settings/sessions`), or `null`. */\n href: string | null;\n /** Event details (amount, currency, card last four and so on); the keys\n * depend on `event_type`. */\n data: Record<string, unknown>;\n /** Language the item was rendered in. */\n locale: string;\n /** When the user read it, or `null` while unread. */\n read_at: string | null;\n created_at: string;\n}\n\nexport interface NotificationPage {\n /** Newest first. */\n items: InboxItem[];\n /** Pass back as `cursor` to get the next page; `null` on the last one. */\n next_cursor: string | null;\n /** Unread items across the whole inbox, not just this page. */\n unread_count: number;\n}\n\nexport interface ListNotificationsParams {\n /** `next_cursor` from the previous page. */\n cursor?: string;\n /** Page size; the server caps it. */\n limit?: number;\n /** Only items without `read_at`. */\n unreadOnly?: boolean;\n category?: NotificationCategory;\n}\n\n/** Per-category channel switches: `{ money: { push: true, email: false } }`.\n * A channel missing from a category keeps its default. */\nexport type NotificationCategoryPreferences = Partial<\n Record<NotificationCategory, Partial<Record<NotificationChannel, boolean>>>\n>;\n\nexport interface NotificationPreferences {\n /** The channel to use first; `null` means automatic (the server picks by\n * the user's devices). */\n primary_channel: NotificationChannel | null;\n categories: NotificationCategoryPreferences;\n /** `null` when unset: the server falls back to the Telegram profile's\n * language, then the deployment default. */\n locale: NotificationLocale | null;\n /** Channels this deployment can deliver on. Render toggles only for\n * these. */\n available_channels: NotificationChannel[];\n}\n\n/** Body of `setPreferences`. Every field is optional; only the given ones\n * change. `primary_channel: null` switches back to automatic. */\nexport interface NotificationPreferencesInput {\n primary_channel?: NotificationChannel | null;\n categories?: NotificationCategoryPreferences;\n locale?: NotificationLocale | null;\n}\n\nexport class NotificationsResource {\n constructor(private readonly http: HttpClient) {}\n\n /** One page of the inbox, newest first. */\n async list(params: ListNotificationsParams = {}): Promise<NotificationPage> {\n const q = new URLSearchParams();\n if (params.cursor) q.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) q.set(\"limit\", String(params.limit));\n if (params.unreadOnly) q.set(\"unread\", \"true\");\n if (params.category) q.set(\"category\", params.category);\n const qs = q.toString();\n return this.http.get<NotificationPage>(`/me/notifications${qs ? `?${qs}` : \"\"}`);\n }\n\n /** How many items are unread. Cheap; fine to poll for a badge. */\n async unreadCount(): Promise<number> {\n const { unread } = await this.http.get<{ unread: number }>(\"/me/notifications/unread-count\");\n return unread;\n }\n\n /** Mark one item read. Returns the item; calling it again is harmless. */\n async markRead(id: string): Promise<InboxItem> {\n return this.http.post<InboxItem>(`/me/notifications/${encodeURIComponent(id)}/read`);\n }\n\n /** Mark every unread item read, or only those created before `before`\n * (ISO timestamp). Returns how many changed. */\n async markAllRead(before?: string): Promise<{ marked: number }> {\n return this.http.post<{ marked: number }>(\"/me/notifications/read-all\", {\n body: before ? { before } : {},\n });\n }\n\n /** Delete one item. 404 when it isn't the user's. */\n async remove(id: string): Promise<void> {\n await this.http.delete<void>(`/me/notifications/${encodeURIComponent(id)}`);\n }\n\n /** The user's channel and language settings. */\n async getPreferences(): Promise<NotificationPreferences> {\n return this.http.get<NotificationPreferences>(\"/me/notification-preferences\");\n }\n\n /** Change some settings; the rest stay. Returns the stored view.\n * 400 `validation` for an unknown category, channel or locale. */\n async setPreferences(input: NotificationPreferencesInput): Promise<NotificationPreferences> {\n return this.http.put<NotificationPreferences>(\"/me/notification-preferences\", {\n body: input,\n });\n }\n}\n"]}
|