@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.
Files changed (91) hide show
  1. package/CHANGELOG.md +104 -2
  2. package/README.md +393 -14
  3. package/dist/devices-C3JHi2Hi.d.cts +165 -0
  4. package/dist/devices-DP_hxwmW.d.ts +165 -0
  5. package/dist/{http-BkZZZI8K.d.cts → http-B-OQwMYn.d.cts} +13 -2
  6. package/dist/{http-BkZZZI8K.d.ts → http-B-OQwMYn.d.ts} +13 -2
  7. package/dist/index.cjs +425 -25
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +77 -8
  10. package/dist/index.d.ts +77 -8
  11. package/dist/index.js +422 -26
  12. package/dist/index.js.map +1 -1
  13. package/dist/react/index.cjs +133 -6
  14. package/dist/react/index.cjs.map +1 -1
  15. package/dist/react/index.d.cts +65 -3
  16. package/dist/react/index.d.ts +65 -3
  17. package/dist/react/index.js +131 -8
  18. package/dist/react/index.js.map +1 -1
  19. package/dist/resources/auth.cjs +73 -15
  20. package/dist/resources/auth.cjs.map +1 -1
  21. package/dist/resources/auth.d.cts +100 -9
  22. package/dist/resources/auth.d.ts +100 -9
  23. package/dist/resources/auth.js +73 -15
  24. package/dist/resources/auth.js.map +1 -1
  25. package/dist/resources/balance.cjs +4 -3
  26. package/dist/resources/balance.cjs.map +1 -1
  27. package/dist/resources/balance.d.cts +8 -9
  28. package/dist/resources/balance.d.ts +8 -9
  29. package/dist/resources/balance.js +4 -3
  30. package/dist/resources/balance.js.map +1 -1
  31. package/dist/resources/blog.d.cts +1 -1
  32. package/dist/resources/blog.d.ts +1 -1
  33. package/dist/resources/branding.cjs.map +1 -1
  34. package/dist/resources/branding.d.cts +8 -2
  35. package/dist/resources/branding.d.ts +8 -2
  36. package/dist/resources/branding.js.map +1 -1
  37. package/dist/resources/cards.cjs +33 -1
  38. package/dist/resources/cards.cjs.map +1 -1
  39. package/dist/resources/cards.d.cts +105 -4
  40. package/dist/resources/cards.d.ts +105 -4
  41. package/dist/resources/cards.js +33 -1
  42. package/dist/resources/cards.js.map +1 -1
  43. package/dist/resources/deposits.d.cts +1 -1
  44. package/dist/resources/deposits.d.ts +1 -1
  45. package/dist/resources/devices.cjs +92 -0
  46. package/dist/resources/devices.cjs.map +1 -0
  47. package/dist/resources/devices.d.cts +3 -0
  48. package/dist/resources/devices.d.ts +3 -0
  49. package/dist/resources/devices.js +89 -0
  50. package/dist/resources/devices.js.map +1 -0
  51. package/dist/resources/me.cjs +32 -0
  52. package/dist/resources/me.cjs.map +1 -0
  53. package/dist/resources/me.d.cts +40 -0
  54. package/dist/resources/me.d.ts +40 -0
  55. package/dist/resources/me.js +30 -0
  56. package/dist/resources/me.js.map +1 -0
  57. package/dist/resources/notifications.cjs +53 -0
  58. package/dist/resources/notifications.cjs.map +1 -0
  59. package/dist/resources/notifications.d.cts +109 -0
  60. package/dist/resources/notifications.d.ts +109 -0
  61. package/dist/resources/notifications.js +51 -0
  62. package/dist/resources/notifications.js.map +1 -0
  63. package/dist/resources/push.cjs +65 -0
  64. package/dist/resources/push.cjs.map +1 -0
  65. package/dist/resources/push.d.cts +76 -0
  66. package/dist/resources/push.d.ts +76 -0
  67. package/dist/resources/push.js +62 -0
  68. package/dist/resources/push.js.map +1 -0
  69. package/dist/resources/sessions.cjs +26 -0
  70. package/dist/resources/sessions.cjs.map +1 -0
  71. package/dist/resources/sessions.d.cts +43 -0
  72. package/dist/resources/sessions.d.ts +43 -0
  73. package/dist/resources/sessions.js +24 -0
  74. package/dist/resources/sessions.js.map +1 -0
  75. package/dist/resources/subscriptions.cjs.map +1 -1
  76. package/dist/resources/subscriptions.d.cts +8 -1
  77. package/dist/resources/subscriptions.d.ts +8 -1
  78. package/dist/resources/subscriptions.js.map +1 -1
  79. package/dist/resources/wallet.cjs +24 -0
  80. package/dist/resources/wallet.cjs.map +1 -0
  81. package/dist/resources/wallet.d.cts +39 -0
  82. package/dist/resources/wallet.d.ts +39 -0
  83. package/dist/resources/wallet.js +22 -0
  84. package/dist/resources/wallet.js.map +1 -0
  85. package/dist/telegram.cjs +466 -28
  86. package/dist/telegram.cjs.map +1 -1
  87. package/dist/telegram.d.cts +65 -7
  88. package/dist/telegram.d.ts +65 -7
  89. package/dist/telegram.js +465 -29
  90. package/dist/telegram.js.map +1 -1
  91. package/package.json +37 -3
package/CHANGELOG.md CHANGED
@@ -4,10 +4,112 @@ All notable changes to `@takeal/cusfront-sdk` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
- ## [Unreleased]
7
+ ## [0.3.0] — 2026-09-15
8
8
 
9
9
  ### Added
10
10
 
11
+ - `client.notifications` (sub-export `@takeal/cusfront-sdk/notifications`):
12
+ the inbox and notification preferences. `list({ cursor?, limit?,
13
+ unreadOnly?, category? })`, `unreadCount()`, `markRead(id)`,
14
+ `markAllRead(before?)`, `remove(id)`, `getPreferences()` and
15
+ `setPreferences({ primary_channel?, categories?, locale? })`. Types
16
+ `InboxItem`, `NotificationPage`, `NotificationPreferences`,
17
+ `NotificationCategory`, `NotificationChannel`.
18
+ - `client.devices` (sub-export `@takeal/cusfront-sdk/devices`): `list()`,
19
+ `register(input)`, `remove(id)`, plus `registerWebPush(registration,
20
+ { label?, vapidPublicKey? })` and `unregisterWebPush(registration,
21
+ { deviceId? })`, which subscribe or unsubscribe the browser and keep the
22
+ device list in step. Types `Device`, `DeviceKind`, `DevicePlatform`,
23
+ `RegisterDeviceInput`, `RegisteredDevice`.
24
+ - `createClient({ client: { platform, version? } })`. Every request now
25
+ carries `X-Takeal-Client: <platform>; <version>`. `platform` is detected
26
+ when omitted (`telegram-miniapp` inside Telegram, `pwa` when installed,
27
+ `web` otherwise); `version` defaults to the SDK version. The resolved
28
+ descriptor is readable as `client.client`; `SDK_VERSION`,
29
+ `detectClientPlatform` and `CLIENT_HEADER` are exported from the root.
30
+ - `@takeal/cusfront-sdk/telegram`: the Mini App helpers announce
31
+ `telegram-miniapp` and, after a successful exchange, register the app as a
32
+ `telegram_miniapp` device (best-effort; `registerDevice: false` skips it).
33
+ - `useNotifications(opts?)` and `useUnreadCount({ pollMs? })` in
34
+ `@takeal/cusfront-sdk/react`. The badge count refreshes on an interval and
35
+ on a `{ type: "takeal:push" }` message from the service worker;
36
+ `PUSH_MESSAGE_TYPE` carries the string.
37
+
38
+ - Card catalog: `client.cards.listProducts()` and `client.cards.getProduct(id)`
39
+ return the cards a user can order (`CardProduct`: name, description, type,
40
+ currency, artwork, the designs to choose from, the issuance price after the
41
+ user's subscription discount, free-form `features`).
42
+ - `client.cards.create()` takes `productId`, `name` and `designId`; with a
43
+ `productId`, `type` is optional. `client.cards.update(id, { name?, designId? })`
44
+ renames a card or changes its design.
45
+ - `Card` gains `name`, `design` and `product`.
46
+ - `client.assetUrl(url)` and the standalone `resolveAssetUrl(baseUrl, url)`
47
+ turn the image URLs the API returns (absolute, or relative to the API origin
48
+ like the default card design) into ones a browser can load.
49
+ - `useCardProducts()` in `@takeal/cusfront-sdk/react`.
50
+ - `client.auth.exchangeTelegram()` takes `provision` (default `true`). With
51
+ `provision: false` an unknown Telegram id resolves to `{ stage: "unknown" }`
52
+ instead of creating an account, so a Mini App can ask the user whether to
53
+ create one or attach the Telegram to an account they already have.
54
+ - `client.auth.linkTelegram({ initData, email, password })` attaches the
55
+ Telegram account behind `initData` to an existing email + password account
56
+ and signs in. Same envelope as `login`; the JWT is stored.
57
+ - `client.me` (sub-export `@takeal/cusfront-sdk/me`): `linkTelegram(initData)`
58
+ and `unlinkTelegram()` for a signed-in user.
59
+ - `User.telegram` — `{ username, linked_at }` or `null`.
60
+ - `@takeal/cusfront-sdk/telegram`: `provision` in the options of
61
+ `fromInitData` / `fromTelegramWebApp`; a new `exchangeInitData()` that
62
+ returns `{ client, session }` for apps that want to branch on the outcome;
63
+ `TelegramUnknownError` (carries `initData`), thrown by `fromInitData` /
64
+ `fromTelegramWebApp` when `provision: false` is set and the Telegram id
65
+ has no account.
66
+
67
+ ### Deprecated
68
+
69
+ - `client.push` (`enable`, `disable`, `save`, `remove`, `status`): the
70
+ endpoint keeps working as an alias over Web Push devices, but new code
71
+ should call `client.devices.registerWebPush` / `unregisterWebPush`.
72
+ - `client.subscriptions`: announcement channels are now the `marketing`
73
+ category of the notification preferences. The endpoint keeps working; use
74
+ `client.notifications.setPreferences({ categories: { marketing: { ... } } })`.
75
+
76
+ ### Changed
77
+
78
+ - `exchangeTelegram()` is typed to return `JwtIssued | TelegramUnknown` when
79
+ `provision` is passed as a `boolean`. Calls without `provision` (or with
80
+ `provision: true`) keep returning `JwtIssued`, so existing code compiles
81
+ unchanged.
82
+
83
+ ## [0.2.8] — 2026-09-13
84
+
85
+ The version number now matches the Takeal platform release the SDK was
86
+ checked against, so this release jumps from 0.1.0 to 0.2.8 (platform tag
87
+ `v0.2.8`).
88
+
89
+ ### Changed
90
+
91
+ - **API paths are versioned.** Every request now goes to `/v1/...`
92
+ (`/v1/auth/login`, `/v1/me/deposits`, …); the SDK adds the prefix itself,
93
+ so `baseUrl` stays the bare API origin and resource calls are unchanged.
94
+ Only `/ready` and `/branding` remain unversioned. The API answers the old
95
+ unversioned paths with `410 Gone`, so 0.1.0 no longer works against it.
96
+ - The npm page links to the repository with a plain `https://` URL.
97
+
98
+ ### Added
99
+
100
+ - `client.auth.register()` creates an account and signs it in. Takes an
101
+ optional `wallet_currency`.
102
+ - `client.auth.completeTotpSetup()` finishes a `totp_setup_required` login
103
+ and returns the ten one-time backup codes.
104
+ - `client.auth.changePassword()`. The account's other sessions are signed out.
105
+ - `client.sessions`: `list()`, `revoke(jti)` and `revokeOthers()`.
106
+ - `client.push`: `status()`, `save()`, `remove()`, plus `enable(registration)`
107
+ and `disable(registration)`, which subscribe or unsubscribe the browser and
108
+ update the server in one call.
109
+ - Sub-exports `@takeal/cusfront-sdk/wallet`, `/sessions` and `/push`. Auth
110
+ types (`User`, `LoginResponse`, `Session` and the rest) are exported from
111
+ the package root.
112
+
11
113
  - `client.blog.list()` / `client.blog.get(slug)` — public posts returned as
12
114
  structured blocks (`body_blocks`) plus raw Markdown, so a site renders them
13
115
  in its own components instead of fighting server-side HTML.
@@ -31,7 +133,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
31
133
  billing fields, issuing metrics, branding). `refresh-types` now scrubs
32
134
  internal references from doc comments before generating.
33
135
 
34
- ## [0.1.0] — first public release
136
+ ## [0.1.0] — 2026-08-25 — first public release
35
137
 
36
138
  Initial release of the typed client for the Takeal end-user API.
37
139
 
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @takeal/cusfront-sdk
2
2
 
3
- Typed TypeScript client for the **Takeal end-user API** — auth, deposits, cards, balance, and webhook signature verification.
3
+ Typed TypeScript client for the **Takeal end-user API**: sign-up and login, wallet, deposits, cards, sessions, the notification inbox, devices and webhook signature verification.
4
4
 
5
- The SDK powers any "Cusfront" (consumer front-end) on top of a Takeal deployment: a PWA, a Capacitor-wrapped mobile app, a Telegram Mini App, or anything else that talks to the `/auth/*` + `/me/*` surface. One client, runtime brand swap, zero runtime deps in the core.
5
+ The SDK powers any end-user client app on top of a Takeal deployment: a PWA, a Capacitor-wrapped mobile app, a Telegram Mini App, or anything else that talks to the `/auth/*` + `/me/*` surface. One client, runtime brand swap, zero runtime deps in the core.
6
6
 
7
- > **Status:** 0.x — pre-release scaffold. Auth resource lands first; deposits + cards + balance + webhook verifier ship in subsequent releases.
7
+ > **Versioning:** the SDK version matches the Takeal platform release it was checked against (SDK 0.2.8 goes with API release v0.2.8). Until 1.0, a minor version can break things; read the [changelog](./CHANGELOG.md) before upgrading.
8
8
 
9
9
  ## Install
10
10
 
@@ -42,9 +42,84 @@ if (result.stage === "jwt") {
42
42
  } else if (result.stage === "totp_required") {
43
43
  // Step-up required. Prompt the user for their TOTP code,
44
44
  // then call client.auth.verifyTotp({ challenge_token, code }).
45
+ } else if (result.stage === "totp_setup_required") {
46
+ // The account has to enrol an authenticator first. Show result.otpauth_url
47
+ // as a QR code, then call client.auth.completeTotpSetup({ challenge_token, code })
48
+ // and show the backup_codes it returns. They are never sent again.
45
49
  }
46
50
  ```
47
51
 
52
+ New users sign up with `register`, which also signs them in:
53
+
54
+ ```ts
55
+ await client.auth.register({
56
+ email: "user@example.com",
57
+ password: "a-long-Passw0rd",
58
+ wallet_currency: "EUR", // optional; must be offered by the deployment
59
+ });
60
+ ```
61
+
62
+ ## Choosing a card
63
+
64
+ The API publishes a catalog of the cards a user can order, and the client
65
+ walks it from the list to the issued card:
66
+
67
+ ```ts
68
+ // 1. The catalog: what the user can order, default product first.
69
+ const products = await client.cards.listProducts();
70
+
71
+ for (const p of products) {
72
+ // Artwork: `image_url` is absolute for uploaded designs and a path
73
+ // relative to the API for the deployment default. `assetUrl` handles both.
74
+ const img = client.assetUrl(p.design.image_url);
75
+
76
+ // Price after the user's subscription discount; `null` means free.
77
+ const price = p.price
78
+ ? p.price.discount_bps > 0
79
+ ? `${p.price.amount} ${p.price.currency} (was ${p.price.base_amount}, ${p.price.discount_bps / 100}% off)`
80
+ : `${p.price.amount} ${p.price.currency}`
81
+ : "free";
82
+
83
+ console.log(p.name, p.card_type, p.currency, price, img, p.description);
84
+ }
85
+
86
+ // 2. Issue from a product. `type` and `issuer_slug` are no longer needed:
87
+ // the product settles both. The user picks a name and, when the product
88
+ // offers a choice, one of `p.designs`.
89
+ const product = products.find((p) => p.is_default) ?? products[0];
90
+ const card = await client.cards.create({
91
+ productId: product.id,
92
+ name: "Groceries",
93
+ designId: product.designs[0]?.id ?? null, // null = the product's default design
94
+ initial_amount: "50.00",
95
+ currency: product.currency ?? "USD",
96
+ idempotencyKey: crypto.randomUUID(),
97
+ customer: { email: "user@example.com", first_name: "Alice", last_name: "Tester" },
98
+ });
99
+
100
+ // The card carries what was chosen.
101
+ card.name; // "Groceries"
102
+ client.assetUrl(card.design.image_url); // ready for <img src>
103
+ card.product; // { id, name } or null for older cards
104
+
105
+ // 3. Rename or change the design later.
106
+ await client.cards.update(card.id, { name: "Coffee" });
107
+ await client.cards.update(card.id, { designId: null });
108
+ ```
109
+
110
+ `cards.getProduct(id)` fetches one entry. `product.features` is a free-form
111
+ object the operator fills in (payment scheme, wallet support, load limits and
112
+ so on), so read the keys you need and ignore the rest. Names are 1 to 40
113
+ characters; a design outside the product's `designs` and an unknown or hidden
114
+ product are rejected with a 400 whose `code` says which check failed
115
+ (`invalid_name`, `design_not_allowed`, `unknown_product`, `product_mismatch`).
116
+
117
+ Calls without `productId` keep working as before: `type` is then required and
118
+ the deployment picks the product.
119
+
120
+ `resolveAssetUrl(baseUrl, url)` is the same helper as a standalone function,
121
+ exported from the package root, for code that has no client at hand.
122
+
48
123
  ## Telegram Mini App
49
124
 
50
125
  Run inside a Telegram Mini App? Exchange the Telegram-signed `initData` for a
@@ -89,14 +164,275 @@ How it works end-to-end:
89
164
  4. First-time Telegram users are **auto-provisioned**. They have no email yet, so
90
165
  `me.email_pending === true` — prompt for an address and call
91
166
  `client.auth.linkEmail` to clear it.
167
+ 5. Once signed in, the Mini App registers itself as a `telegram_miniapp`
168
+ device, so the user's notifications arrive as messages from the bot. A
169
+ failure here is logged as a warning and never blocks the sign-in; pass
170
+ `{ registerDevice: false }` to skip it. The client also announces itself as
171
+ `telegram-miniapp` in `X-Takeal-Client` (see [Client platform](#client-platform-x-takeal-client)).
92
172
 
93
173
  For the lower-level call returning the raw session envelope (including
94
174
  `email_pending`), use `client.auth.exchangeTelegram({ initData })` on a client
95
175
  you built yourself.
96
176
 
177
+ ### "I already have an account"
178
+
179
+ By default an unknown Telegram id gets a fresh account. That's wrong for a user
180
+ who signed up on the website with an email and a password and then opens the
181
+ Mini App: they'd end up with a second, empty account. Pass `provision: false`
182
+ to find out first, then let the user choose:
183
+
184
+ ```ts
185
+ import {
186
+ fromTelegramWebApp,
187
+ TelegramUnknownError,
188
+ } from "@takeal/cusfront-sdk/telegram";
189
+ import { createClient } from "@takeal/cusfront-sdk";
190
+
191
+ const config = { baseUrl: "https://api.your-deployment.example.com" };
192
+
193
+ try {
194
+ // Known Telegram → signed-in client, as before.
195
+ const client = await fromTelegramWebApp(config, { provision: false });
196
+ } catch (e) {
197
+ if (!(e instanceof TelegramUnknownError)) throw e;
198
+
199
+ // Nobody has signed in with this Telegram yet. Nothing was created.
200
+ const client = createClient(config);
201
+ const choice = await askUser(); // "create" | "link"
202
+
203
+ if (choice === "create") {
204
+ // Same as the default flow: a new account, email_pending === true.
205
+ await client.auth.exchangeTelegram({ initData: e.initData, provision: true });
206
+ } else {
207
+ // Attach this Telegram to the existing email + password account.
208
+ const { email, password } = await askCredentials();
209
+ await client.auth.linkTelegram({ initData: e.initData, email, password });
210
+ }
211
+ // client is signed in either way.
212
+ }
213
+ ```
214
+
215
+ If you'd rather branch on a value than catch an error, `exchangeInitData`
216
+ returns both the client and the outcome:
217
+
218
+ ```ts
219
+ import { exchangeInitData, readWebAppInitData } from "@takeal/cusfront-sdk/telegram";
220
+
221
+ const initData = readWebAppInitData()!;
222
+ const { client, session } = await exchangeInitData(initData, config, { provision: false });
223
+ if (session.stage === "unknown") {
224
+ // client has no session yet; call client.auth.linkTelegram or
225
+ // client.auth.exchangeTelegram({ initData, provision: true }).
226
+ }
227
+ ```
228
+
229
+ `linkTelegram` checks the password the same way `login` does and returns the
230
+ same `stage: "jwt"` envelope. On the next launch the plain exchange finds the
231
+ link and signs the user straight in. Errors to expect:
232
+
233
+ - `401 unauthenticated` — wrong email or password.
234
+ - `403 second_factor_required` — the account signs in with a second factor;
235
+ such accounts can't be linked from a Mini App.
236
+ - `409 telegram_already_linked_other` — the account already has a different
237
+ Telegram. Unlink it first.
238
+ - `409 telegram_in_use` — this Telegram already belongs to another account
239
+ that has been used. A Telegram can be attached to one account only, and the
240
+ API does not merge accounts.
241
+
242
+ Two more calls for a signed-in user:
243
+
244
+ ```ts
245
+ // Attach Telegram to the current session (e.g. the Mini App was opened
246
+ // through a deep link that already carried a session):
247
+ await client.me.linkTelegram(window.Telegram.WebApp.initData);
248
+
249
+ // Detach it. Refused with 409 `last_credential` when the account has no
250
+ // password, because Telegram would be its only way to sign in.
251
+ await client.me.unlinkTelegram();
252
+ ```
253
+
254
+ The user object (`client.auth.me()` and the `user` in every `stage: "jwt"`
255
+ envelope) carries the state, so a settings screen needs no extra request:
256
+
257
+ ```ts
258
+ type User = {
259
+ // ...
260
+ telegram: { username: string | null; linked_at: string } | null;
261
+ };
262
+ ```
263
+
264
+ ## Notifications (inbox)
265
+
266
+ Everything the API tells a user (a confirmed deposit, a card transaction, a
267
+ sign-in from a new device) is kept as an inbox item, whatever else was sent
268
+ as a nudge (a push, a Telegram message, an email). The inbox is what your app
269
+ shows; `client.notifications` reads it.
270
+
271
+ ```ts
272
+ const page = await client.notifications.list({ limit: 20 });
273
+ // page.items (newest first), page.next_cursor, page.unread_count
274
+
275
+ const more = await client.notifications.list({ cursor: page.next_cursor! });
276
+ const onlyMoney = await client.notifications.list({ unreadOnly: true, category: "money" });
277
+
278
+ await client.notifications.markRead(page.items[0].id);
279
+ await client.notifications.markAllRead(); // or markAllRead(isoTimestamp)
280
+ await client.notifications.remove(page.items[1].id);
281
+ const badge = await client.notifications.unreadCount();
282
+ ```
283
+
284
+ An item has `title`, `body`, a `category` (`money`, `card`, `security`,
285
+ `account`, `marketing`), `read_at` (`null` while unread), free-form `data`
286
+ about the event, and `href`: a path inside your app to open on tap
287
+ (`/cards/<id>`, `/deposits/<id>`, `/subscription`, `/settings/sessions`) or
288
+ `null`. Route `href` through your own router; the SDK doesn't navigate.
289
+
290
+ A small inbox screen:
291
+
292
+ ```tsx
293
+ function Inbox() {
294
+ const [page, setPage] = useState<NotificationPage | null>(null);
295
+ useEffect(() => { client.notifications.list({ limit: 20 }).then(setPage); }, []);
296
+ if (!page) return <Spinner />;
297
+ return (
298
+ <ul>
299
+ {page.items.map((n) => (
300
+ <li key={n.id} className={n.read_at ? "" : "unread"}
301
+ onClick={async () => { await client.notifications.markRead(n.id); if (n.href) router.push(n.href); }}>
302
+ <strong>{n.title}</strong>
303
+ <p>{n.body}</p>
304
+ </li>
305
+ ))}
306
+ </ul>
307
+ );
308
+ }
309
+ ```
310
+
311
+ (The React entry has `useNotifications()` and `useUnreadCount()`, which do the
312
+ state handling for you; see [React hooks](#react-hooks-takealcusfront-sdkreact).)
313
+
314
+ ### Preferences
315
+
316
+ Where the nudge goes is up to the user:
317
+
318
+ ```ts
319
+ const prefs = await client.notifications.getPreferences();
320
+ // prefs.primary_channel: "push" | "telegram" | "email" | "sms" | null (automatic)
321
+ // prefs.categories: { money: { push: true, email: false }, ... }
322
+ // prefs.locale: "en" | "ru" | null
323
+ // prefs.available_channels: what this deployment can deliver on; render toggles only for these
324
+
325
+ await client.notifications.setPreferences({
326
+ primary_channel: "telegram",
327
+ categories: { marketing: { email: true, telegram: false } },
328
+ locale: "ru",
329
+ });
330
+ ```
331
+
332
+ Every field of `setPreferences` is optional; only what you pass changes.
333
+ `primary_channel: null` goes back to automatic (the server picks by the user's
334
+ devices). `security` and `money` can't be switched off completely: the inbox
335
+ always gets them and at least one outward channel stays on. `marketing` is off
336
+ until the user opts in. A `locale` of `null` means "use the language of the
337
+ Telegram profile, else the deployment's default".
338
+
339
+ `client.subscriptions` (announcement channels) is deprecated: it now reads and
340
+ writes `categories.marketing` and keeps working, but new code should use
341
+ `setPreferences({ categories: { marketing: { ... } } })`.
342
+
343
+ ## Devices
344
+
345
+ A user has many devices: each browser with a Web Push subscription, each phone
346
+ with an FCM or APNs token, and a marker that says "uses the Telegram Mini App".
347
+ The server picks where a notification goes from them: a mobile app first,
348
+ otherwise the device seen most recently. What each platform can receive:
349
+
350
+ | Platform | Outward channel | Inbox |
351
+ |---|---|---|
352
+ | PWA / browser | Web Push | yes |
353
+ | Telegram Mini App | messages from the bot (no Web Push) | yes |
354
+ | iOS / Android app | FCM / APNs (tokens are accepted now; delivery comes later) | yes |
355
+
356
+ Web Push in a browser, once notification permission is granted:
357
+
358
+ ```ts
359
+ const reg = await navigator.serviceWorker.ready;
360
+ if ((await Notification.requestPermission()) === "granted") {
361
+ const device = await client.devices.registerWebPush(reg, { label: "Chrome on Mac" });
362
+ // device.id, device.vapid_public_key
363
+ }
364
+
365
+ // Settings screen, later:
366
+ await client.devices.unregisterWebPush(reg); // this session's Web Push devices
367
+ await client.devices.unregisterWebPush(reg, { deviceId }); // or exactly one
368
+ ```
369
+
370
+ `registerWebPush` fetches the deployment's VAPID key, subscribes the browser
371
+ and registers the subscription as a `webpush` device on the client's platform
372
+ (`pwa` or `web`). It throws when push isn't set up on the deployment. Pass
373
+ `vapidPublicKey` in the options to skip the key lookup when you already hold it.
374
+
375
+ Anything else goes through `register` / `list` / `remove`:
376
+
377
+ ```ts
378
+ // A native app with a push token:
379
+ await client.devices.register({ kind: "fcm", platform: "android", credential: { token }, app_version: "1.4.0" });
380
+ // A Telegram Mini App (done for you by @takeal/cusfront-sdk/telegram):
381
+ await client.devices.register({ kind: "telegram_miniapp", platform: "telegram", credential: {} });
382
+
383
+ const devices = await client.devices.list(); // is_current marks the ones from this session
384
+ await client.devices.remove(devices[0].id);
385
+ ```
386
+
387
+ Registering the same credential twice refreshes the device (and re-enables a
388
+ disabled one) instead of creating another. `app_version` defaults to the
389
+ version in `X-Takeal-Client`.
390
+
391
+ `client.push` (`enable`, `disable`, `save`, `remove`, `status`) is deprecated.
392
+ The endpoint behind it keeps working as an alias over Web Push devices, but
393
+ new code should use `devices.registerWebPush` / `devices.unregisterWebPush`.
394
+
395
+ Your service worker shows the notification; the payload is JSON with `title`,
396
+ `body` and `url`. To keep an open tab's badge fresh, also post a message to
397
+ the open clients:
398
+
399
+ ```js
400
+ self.addEventListener("push", (event) => {
401
+ const payload = event.data.json();
402
+ event.waitUntil(Promise.all([
403
+ self.registration.showNotification(payload.title, { body: payload.body, data: { url: payload.url } }),
404
+ self.clients.matchAll({ type: "window" }).then((clients) =>
405
+ clients.forEach((c) => c.postMessage({ type: "takeal:push" }))),
406
+ ]));
407
+ });
408
+ ```
409
+
410
+ ## Client platform (`X-Takeal-Client`)
411
+
412
+ Every request carries `X-Takeal-Client: <platform>; <version>`, for example
413
+ `pwa; 0.3.0` or `telegram-miniapp; 0.2.8`. The server stores it on the session
414
+ and uses it to notice a sign-in from a new device and to choose the
415
+ notification channel. Set it with the `client` option:
416
+
417
+ ```ts
418
+ const client = createClient({
419
+ baseUrl: "https://api.your-deployment.example.com",
420
+ client: { platform: "ios", version: "1.4.0" },
421
+ });
422
+ client.client; // { platform: "ios", version: "1.4.0" }
423
+ ```
424
+
425
+ `platform` is one of `pwa`, `web`, `telegram-miniapp`, `ios`, `android`.
426
+ When you leave the option out, the SDK detects it: `telegram-miniapp` when
427
+ `window.Telegram.WebApp.initData` is present, `pwa` when the page runs
428
+ installed (`navigator.standalone` or a `display-mode: standalone` media
429
+ query), `web` otherwise and on any non-browser runtime. Native wrappers
430
+ (Capacitor, React Native) can't be told apart from a browser, so pass `ios`
431
+ or `android` yourself. `version` defaults to the SDK version (`SDK_VERSION`).
432
+
97
433
  ## Brand config
98
434
 
99
- Whitelabel-friendly by design — the SDK ships no embedded brand. Pass `brand` at runtime and the consumer Cusfront reads it back via `client.brand`:
435
+ Whitelabel-friendly by design — the SDK ships no embedded brand. Pass `brand` at runtime and the client app reads it back via `client.brand`:
100
436
 
101
437
  ```ts
102
438
  type BrandConfig = {
@@ -112,8 +448,9 @@ Switching brands does **not** require forking or re-publishing the SDK.
112
448
 
113
449
  The deployment also publishes its live brand config at `GET /branding` (public,
114
450
  no login needed) — `client.branding.get()` returns `platform_name`,
115
- `merchant_portal_name`, `logo_url`, `favicon_url` and `wallet_label`, so a
116
- Cusfront can re-theme itself at runtime and call the balance whatever the
451
+ `merchant_portal_name`, `logo_url`, `favicon_url`, `wallet_label` and the
452
+ `primary_color` / `secondary_color` / `accent_color` hex values, so a
453
+ client app can re-theme itself at runtime and call the balance whatever the
117
454
  operator configured. Server values win over the build-time `brand` when both
118
455
  are present.
119
456
 
@@ -133,9 +470,15 @@ Available now:
133
470
  - `@takeal/cusfront-sdk/cards` — `CardsResource` (cards backed by the wallet balance).
134
471
  - `@takeal/cusfront-sdk/balance` — `BalanceResource` (per-currency wallet balance).
135
472
  - `@takeal/cusfront-sdk/blog` — `BlogResource` (public posts as structured blocks).
136
- - `@takeal/cusfront-sdk/subscriptions` — `SubscriptionsResource` (announcement channels).
473
+ - `@takeal/cusfront-sdk/subscriptions` — `SubscriptionsResource` (announcement channels; deprecated, see [Preferences](#preferences)).
474
+ - `@takeal/cusfront-sdk/wallet` — `WalletResource` (the wallet's currency).
475
+ - `@takeal/cusfront-sdk/sessions` — `SessionsResource` (where the user is signed in).
476
+ - `@takeal/cusfront-sdk/push` — `PushResource` (Web Push subscription; deprecated, see [Devices](#devices)).
477
+ - `@takeal/cusfront-sdk/notifications` — `NotificationsResource` (the inbox and notification preferences).
478
+ - `@takeal/cusfront-sdk/devices` — `DevicesResource` (Web Push, mobile push tokens, the Telegram Mini App marker).
479
+ - `@takeal/cusfront-sdk/me` — `MeResource` (link or unlink Telegram for the signed-in user).
137
480
  - `@takeal/cusfront-sdk/webhooks` — HMAC-SHA256 signature verifier (no network, isomorphic).
138
- - `@takeal/cusfront-sdk/react` — optional React hooks layer (`ClientProvider` + `useMe` / `useDeposits` / `useCards` / `useBalance`). React is a `peerDependency`, never bundled.
481
+ - `@takeal/cusfront-sdk/react` — optional React hooks layer (`ClientProvider` + `useMe` / `useDeposits` / `useCards` / `useCardProducts` / `useBalance` / `useNotifications` / `useUnreadCount`). React is a `peerDependency`, never bundled.
139
482
  - `@takeal/cusfront-sdk/telegram` — Telegram Mini App `initData` → authenticated client bridge.
140
483
 
141
484
  ### Verifying webhooks
@@ -158,11 +501,11 @@ if (!ok) return res.status(401).end();
158
501
  Algorithm: HMAC-SHA256, header `X-Takeal-Signature: sha256=<hex>`, signed over
159
502
  the raw body bytes (no timestamp). Comparison is constant-time.
160
503
 
161
- > **Card lifecycle note:** card-data reveal (PAN / CVV) is a separate,
162
- > security-gated flow with its own re-auth + rate-limit + audit contract, so it
163
- > is intentionally not part of `client.cards`. The cards resource covers
164
- > create / get / list / balance plus the ownership-gated freeze / unfreeze /
165
- > terminate lifecycle actions.
504
+ > **Card details:** `client.cards.reveal()` returns the full card number and
505
+ > CVV. It asks for the user's password again (and a TOTP code if they have one
506
+ > enrolled), and the API rate-limits and logs every call. The rest of
507
+ > `client.cards` is listProducts, getProduct, create, get, list, update,
508
+ > balance, freeze, unfreeze and terminate.
166
509
 
167
510
  ## React hooks (`@takeal/cusfront-sdk/react`)
168
511
 
@@ -212,8 +555,44 @@ Every hook returns the same shape — `{ data, error, loading, refetch }`:
212
555
  - `useMe()` — current authenticated user (`client.auth.me()`).
213
556
  - `useDeposits()` — the user's deposits (`client.deposits.list()`).
214
557
  - `useCards()` — the user's cards (`client.cards.list()`).
558
+ - `useCardProducts()` — the cards the user can order (`client.cards.listProducts()`).
215
559
  - `useBalance(currency)` — wallet balance for one currency
216
560
  (`client.balance.get(currency)`); re-fetches when `currency` changes.
561
+ - `useUnreadCount({ pollMs? })` — unread inbox items for a badge
562
+ (`client.notifications.unreadCount()`). Refreshes in the background every
563
+ `pollMs` (default 30000; `0` turns polling off) and whenever the page's
564
+ service worker posts `{ type: "takeal:push" }` (see [Devices](#devices)),
565
+ without flipping `loading`.
566
+
567
+ `useNotifications({ unreadOnly?, category?, limit? })` returns the same shape
568
+ plus `markRead(id)`, `markAllRead()`, `loadMore()` and `loadingMore`.
569
+ `loadMore` fetches the next page by `next_cursor` and appends its items to
570
+ `data.items`; the two mark helpers update `data` right away so the list
571
+ doesn't flicker.
572
+
573
+ ```tsx
574
+ function Inbox() {
575
+ const inbox = useNotifications({ limit: 20 });
576
+ const unread = useUnreadCount();
577
+
578
+ if (inbox.loading) return <Spinner />;
579
+ if (inbox.error) return <ErrorBanner onRetry={inbox.refetch} />;
580
+ return (
581
+ <>
582
+ <h2>Inbox {unread.data ? `(${unread.data})` : ""}</h2>
583
+ <button onClick={() => void inbox.markAllRead()}>Mark all read</button>
584
+ {inbox.data!.items.map((n) => (
585
+ <Row key={n.id} unread={!n.read_at} onClick={() => void inbox.markRead(n.id)}>
586
+ {n.title}
587
+ </Row>
588
+ ))}
589
+ {inbox.data!.next_cursor && (
590
+ <button disabled={inbox.loadingMore} onClick={() => void inbox.loadMore()}>More</button>
591
+ )}
592
+ </>
593
+ );
594
+ }
595
+ ```
217
596
 
218
597
  `useClient()` exposes the raw client from context for one-off writes
219
598
  (e.g. `client.deposits.initiate(...)`) — it throws a clear error if called
@@ -274,7 +653,7 @@ pnpm typecheck # tsc --noEmit
274
653
  The OpenAPI snapshot lives at `openapi-snapshot.json` and is committed; refresh it from a running Takeal deployment with:
275
654
 
276
655
  ```sh
277
- curl https://api.your-deployment.example.com/api/docs/openapi.json > openapi-snapshot.json
656
+ curl https://api.your-deployment.example.com/docs/openapi.json > openapi-snapshot.json
278
657
  pnpm refresh-types
279
658
  ```
280
659