@takeal/cusfront-sdk 0.2.8 → 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 (77) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +367 -5
  3. package/dist/devices-C3JHi2Hi.d.cts +165 -0
  4. package/dist/devices-DP_hxwmW.d.ts +165 -0
  5. package/dist/{http-BkCfOCR0.d.cts → http-B-OQwMYn.d.cts} +9 -1
  6. package/dist/{http-BkCfOCR0.d.ts → http-B-OQwMYn.d.ts} +9 -1
  7. package/dist/index.cjs +280 -20
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +65 -9
  10. package/dist/index.d.ts +65 -9
  11. package/dist/index.js +277 -21
  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 +62 -3
  16. package/dist/react/index.d.ts +62 -3
  17. package/dist/react/index.js +131 -8
  18. package/dist/react/index.js.map +1 -1
  19. package/dist/resources/auth.cjs +36 -11
  20. package/dist/resources/auth.cjs.map +1 -1
  21. package/dist/resources/auth.d.cts +57 -5
  22. package/dist/resources/auth.d.ts +57 -5
  23. package/dist/resources/auth.js +36 -11
  24. package/dist/resources/auth.js.map +1 -1
  25. package/dist/resources/balance.d.cts +1 -1
  26. package/dist/resources/balance.d.ts +1 -1
  27. package/dist/resources/blog.d.cts +1 -1
  28. package/dist/resources/blog.d.ts +1 -1
  29. package/dist/resources/branding.d.cts +1 -1
  30. package/dist/resources/branding.d.ts +1 -1
  31. package/dist/resources/cards.cjs +33 -1
  32. package/dist/resources/cards.cjs.map +1 -1
  33. package/dist/resources/cards.d.cts +105 -4
  34. package/dist/resources/cards.d.ts +105 -4
  35. package/dist/resources/cards.js +33 -1
  36. package/dist/resources/cards.js.map +1 -1
  37. package/dist/resources/deposits.d.cts +1 -1
  38. package/dist/resources/deposits.d.ts +1 -1
  39. package/dist/resources/devices.cjs +92 -0
  40. package/dist/resources/devices.cjs.map +1 -0
  41. package/dist/resources/devices.d.cts +3 -0
  42. package/dist/resources/devices.d.ts +3 -0
  43. package/dist/resources/devices.js +89 -0
  44. package/dist/resources/devices.js.map +1 -0
  45. package/dist/resources/me.cjs +32 -0
  46. package/dist/resources/me.cjs.map +1 -0
  47. package/dist/resources/me.d.cts +40 -0
  48. package/dist/resources/me.d.ts +40 -0
  49. package/dist/resources/me.js +30 -0
  50. package/dist/resources/me.js.map +1 -0
  51. package/dist/resources/notifications.cjs +53 -0
  52. package/dist/resources/notifications.cjs.map +1 -0
  53. package/dist/resources/notifications.d.cts +109 -0
  54. package/dist/resources/notifications.d.ts +109 -0
  55. package/dist/resources/notifications.js +51 -0
  56. package/dist/resources/notifications.js.map +1 -0
  57. package/dist/resources/push.cjs +8 -4
  58. package/dist/resources/push.cjs.map +1 -1
  59. package/dist/resources/push.d.cts +14 -17
  60. package/dist/resources/push.d.ts +14 -17
  61. package/dist/resources/push.js +8 -4
  62. package/dist/resources/push.js.map +1 -1
  63. package/dist/resources/sessions.d.cts +1 -1
  64. package/dist/resources/sessions.d.ts +1 -1
  65. package/dist/resources/subscriptions.cjs.map +1 -1
  66. package/dist/resources/subscriptions.d.cts +8 -1
  67. package/dist/resources/subscriptions.d.ts +8 -1
  68. package/dist/resources/subscriptions.js.map +1 -1
  69. package/dist/resources/wallet.d.cts +1 -1
  70. package/dist/resources/wallet.d.ts +1 -1
  71. package/dist/telegram.cjs +321 -23
  72. package/dist/telegram.cjs.map +1 -1
  73. package/dist/telegram.d.cts +62 -7
  74. package/dist/telegram.d.ts +62 -7
  75. package/dist/telegram.js +320 -24
  76. package/dist/telegram.js.map +1 -1
  77. package/package.json +17 -2
@@ -1,6 +1,6 @@
1
- import { CreateClientOptions, CusfrontClient } from './index.cjs';
2
- import { JwtIssued } from './resources/auth.cjs';
3
- import './http-BkCfOCR0.cjs';
1
+ import { CusfrontClient, CreateClientOptions } from './index.cjs';
2
+ import { JwtIssued, TelegramUnknown } from './resources/auth.cjs';
3
+ import './http-B-OQwMYn.cjs';
4
4
  import './resources/deposits.cjs';
5
5
  import './customer-CoxPwe5o.cjs';
6
6
  import './resources/cards.cjs';
@@ -11,6 +11,9 @@ import './resources/blog.cjs';
11
11
  import './resources/subscriptions.cjs';
12
12
  import './resources/sessions.cjs';
13
13
  import './resources/push.cjs';
14
+ import './resources/me.cjs';
15
+ import './resources/notifications.cjs';
16
+ import './devices-C3JHi2Hi.cjs';
14
17
 
15
18
  /**
16
19
  * `@takeal/cusfront-sdk/telegram` — Telegram Mini App adapter.
@@ -79,15 +82,65 @@ interface FromInitDataOptions extends WellFormedOptions {
79
82
  * sole judge. Default false — the fail-fast check saves a round-trip on
80
83
  * obviously-bad input. */
81
84
  skipWellFormedCheck?: boolean;
85
+ /** Create an account for a Telegram id the deployment has not seen before.
86
+ * Default `true`. With `false`, an unknown id makes {@link fromInitData} /
87
+ * {@link fromTelegramWebApp} throw {@link TelegramUnknownError} (and
88
+ * {@link exchangeInitData} resolve with `session.stage === "unknown"`)
89
+ * instead of creating anything. */
90
+ provision?: boolean;
91
+ /** After a successful exchange, register this Mini App as a
92
+ * `telegram_miniapp` device so notifications reach the user as bot
93
+ * messages. Default `true`. Best-effort: a failure is logged as a
94
+ * warning and never fails the sign-in. */
95
+ registerDevice?: boolean;
96
+ }
97
+ /** Thrown by {@link fromInitData} / {@link fromTelegramWebApp} when
98
+ * `provision: false` was passed and the Telegram id has no account yet.
99
+ * Nothing was created and no JWT was stored. `initData` is the payload that
100
+ * was exchanged, so the app can go on with
101
+ * `client.auth.linkTelegram({ initData, email, password })` or retry with
102
+ * `provision: true`. */
103
+ declare class TelegramUnknownError extends Error {
104
+ readonly initData: string;
105
+ constructor(initData: string);
106
+ }
107
+ /** What {@link exchangeInitData} resolves to. When `session.stage` is
108
+ * `"jwt"` the client is signed in; when it is `"unknown"` the client is
109
+ * built but has no session. */
110
+ interface InitDataExchange {
111
+ client: CusfrontClient;
112
+ session: JwtIssued | TelegramUnknown;
82
113
  }
83
114
  /**
84
- * Build an authenticated client from a raw `initData` string.
115
+ * Build a client from a raw `initData` string and exchange the payload,
116
+ * returning both the client and the exchange result.
85
117
  *
86
118
  * 1. (unless skipped) structurally validate the payload — throws
87
119
  * {@link InitDataError} on malformed/stale input.
88
120
  * 2. exchange it at `POST /auth/telegram/exchange` — the server validates the
89
121
  * HMAC; a bad signature throws a 401 `ApiError`.
90
- * 3. store the returned JWT and return the ready-to-use client.
122
+ * 3. on `stage: "jwt"` the JWT is stored and the client is ready. With
123
+ * `provision: false` and a Telegram id nobody has signed in with,
124
+ * `session` is `{ stage: "unknown" }` and the client is unauthenticated;
125
+ * continue with `client.auth.linkTelegram(...)` or
126
+ * `client.auth.exchangeTelegram({ initData, provision: true })`.
127
+ * 4. on `stage: "jwt"` the Mini App is registered as a `telegram_miniapp`
128
+ * device (unless `registerDevice: false`), so the user's notifications
129
+ * arrive as bot messages. Errors here are only logged.
130
+ *
131
+ * The client announces itself as `telegram-miniapp` in `X-Takeal-Client`
132
+ * whatever `config.client.platform` says; a given `config.client.version`
133
+ * is kept.
134
+ *
135
+ * Use this when the app wants to branch on the outcome itself;
136
+ * {@link fromInitData} is the throwing shorthand.
137
+ */
138
+ declare function exchangeInitData(initData: string, config: CreateClientOptions, opts?: FromInitDataOptions): Promise<InitDataExchange>;
139
+ /**
140
+ * Build an authenticated client from a raw `initData` string. Thin wrapper
141
+ * over {@link exchangeInitData} that never hands back a client without a
142
+ * session: with `provision: false` and an unknown Telegram id it throws
143
+ * {@link TelegramUnknownError} (carrying `initData`) instead.
91
144
  *
92
145
  * Read `client.auth.me()` (or call `client.auth.exchangeTelegram` directly for
93
146
  * the raw session) to check `email_pending` and prompt for an email.
@@ -98,11 +151,13 @@ declare function fromInitData(initData: string, config: CreateClientOptions, opt
98
151
  declare function readWebAppInitData(): string | null;
99
152
  /**
100
153
  * Convenience entry for a Mini App: read `initData` from the Telegram WebApp
101
- * SDK and exchange it. Throws if not running inside a Telegram Mini App.
154
+ * SDK and exchange it. Throws {@link InitDataError} if not running inside a
155
+ * Telegram Mini App, and {@link TelegramUnknownError} when `provision: false`
156
+ * was passed and the Telegram id has no account yet.
102
157
  */
103
158
  declare function fromTelegramWebApp(config: CreateClientOptions, opts?: FromInitDataOptions): Promise<CusfrontClient>;
104
159
  /** Convenience accessor for the typed exchange session (incl. `email_pending`)
105
160
  * when you need the envelope rather than just the client. */
106
161
  type TelegramExchangeSession = JwtIssued;
107
162
 
108
- export { type FromInitDataOptions, InitDataError, type ParsedInitData, type TelegramExchangeSession, type TelegramUser, type WellFormedOptions, assertWellFormed, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
163
+ export { type FromInitDataOptions, InitDataError, type InitDataExchange, type ParsedInitData, type TelegramExchangeSession, TelegramUnknownError, type TelegramUser, type WellFormedOptions, assertWellFormed, exchangeInitData, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
@@ -1,6 +1,6 @@
1
- import { CreateClientOptions, CusfrontClient } from './index.js';
2
- import { JwtIssued } from './resources/auth.js';
3
- import './http-BkCfOCR0.js';
1
+ import { CusfrontClient, CreateClientOptions } from './index.js';
2
+ import { JwtIssued, TelegramUnknown } from './resources/auth.js';
3
+ import './http-B-OQwMYn.js';
4
4
  import './resources/deposits.js';
5
5
  import './customer-CoxPwe5o.js';
6
6
  import './resources/cards.js';
@@ -11,6 +11,9 @@ import './resources/blog.js';
11
11
  import './resources/subscriptions.js';
12
12
  import './resources/sessions.js';
13
13
  import './resources/push.js';
14
+ import './resources/me.js';
15
+ import './resources/notifications.js';
16
+ import './devices-DP_hxwmW.js';
14
17
 
15
18
  /**
16
19
  * `@takeal/cusfront-sdk/telegram` — Telegram Mini App adapter.
@@ -79,15 +82,65 @@ interface FromInitDataOptions extends WellFormedOptions {
79
82
  * sole judge. Default false — the fail-fast check saves a round-trip on
80
83
  * obviously-bad input. */
81
84
  skipWellFormedCheck?: boolean;
85
+ /** Create an account for a Telegram id the deployment has not seen before.
86
+ * Default `true`. With `false`, an unknown id makes {@link fromInitData} /
87
+ * {@link fromTelegramWebApp} throw {@link TelegramUnknownError} (and
88
+ * {@link exchangeInitData} resolve with `session.stage === "unknown"`)
89
+ * instead of creating anything. */
90
+ provision?: boolean;
91
+ /** After a successful exchange, register this Mini App as a
92
+ * `telegram_miniapp` device so notifications reach the user as bot
93
+ * messages. Default `true`. Best-effort: a failure is logged as a
94
+ * warning and never fails the sign-in. */
95
+ registerDevice?: boolean;
96
+ }
97
+ /** Thrown by {@link fromInitData} / {@link fromTelegramWebApp} when
98
+ * `provision: false` was passed and the Telegram id has no account yet.
99
+ * Nothing was created and no JWT was stored. `initData` is the payload that
100
+ * was exchanged, so the app can go on with
101
+ * `client.auth.linkTelegram({ initData, email, password })` or retry with
102
+ * `provision: true`. */
103
+ declare class TelegramUnknownError extends Error {
104
+ readonly initData: string;
105
+ constructor(initData: string);
106
+ }
107
+ /** What {@link exchangeInitData} resolves to. When `session.stage` is
108
+ * `"jwt"` the client is signed in; when it is `"unknown"` the client is
109
+ * built but has no session. */
110
+ interface InitDataExchange {
111
+ client: CusfrontClient;
112
+ session: JwtIssued | TelegramUnknown;
82
113
  }
83
114
  /**
84
- * Build an authenticated client from a raw `initData` string.
115
+ * Build a client from a raw `initData` string and exchange the payload,
116
+ * returning both the client and the exchange result.
85
117
  *
86
118
  * 1. (unless skipped) structurally validate the payload — throws
87
119
  * {@link InitDataError} on malformed/stale input.
88
120
  * 2. exchange it at `POST /auth/telegram/exchange` — the server validates the
89
121
  * HMAC; a bad signature throws a 401 `ApiError`.
90
- * 3. store the returned JWT and return the ready-to-use client.
122
+ * 3. on `stage: "jwt"` the JWT is stored and the client is ready. With
123
+ * `provision: false` and a Telegram id nobody has signed in with,
124
+ * `session` is `{ stage: "unknown" }` and the client is unauthenticated;
125
+ * continue with `client.auth.linkTelegram(...)` or
126
+ * `client.auth.exchangeTelegram({ initData, provision: true })`.
127
+ * 4. on `stage: "jwt"` the Mini App is registered as a `telegram_miniapp`
128
+ * device (unless `registerDevice: false`), so the user's notifications
129
+ * arrive as bot messages. Errors here are only logged.
130
+ *
131
+ * The client announces itself as `telegram-miniapp` in `X-Takeal-Client`
132
+ * whatever `config.client.platform` says; a given `config.client.version`
133
+ * is kept.
134
+ *
135
+ * Use this when the app wants to branch on the outcome itself;
136
+ * {@link fromInitData} is the throwing shorthand.
137
+ */
138
+ declare function exchangeInitData(initData: string, config: CreateClientOptions, opts?: FromInitDataOptions): Promise<InitDataExchange>;
139
+ /**
140
+ * Build an authenticated client from a raw `initData` string. Thin wrapper
141
+ * over {@link exchangeInitData} that never hands back a client without a
142
+ * session: with `provision: false` and an unknown Telegram id it throws
143
+ * {@link TelegramUnknownError} (carrying `initData`) instead.
91
144
  *
92
145
  * Read `client.auth.me()` (or call `client.auth.exchangeTelegram` directly for
93
146
  * the raw session) to check `email_pending` and prompt for an email.
@@ -98,11 +151,13 @@ declare function fromInitData(initData: string, config: CreateClientOptions, opt
98
151
  declare function readWebAppInitData(): string | null;
99
152
  /**
100
153
  * Convenience entry for a Mini App: read `initData` from the Telegram WebApp
101
- * SDK and exchange it. Throws if not running inside a Telegram Mini App.
154
+ * SDK and exchange it. Throws {@link InitDataError} if not running inside a
155
+ * Telegram Mini App, and {@link TelegramUnknownError} when `provision: false`
156
+ * was passed and the Telegram id has no account yet.
102
157
  */
103
158
  declare function fromTelegramWebApp(config: CreateClientOptions, opts?: FromInitDataOptions): Promise<CusfrontClient>;
104
159
  /** Convenience accessor for the typed exchange session (incl. `email_pending`)
105
160
  * when you need the envelope rather than just the client. */
106
161
  type TelegramExchangeSession = JwtIssued;
107
162
 
108
- export { type FromInitDataOptions, InitDataError, type ParsedInitData, type TelegramExchangeSession, type TelegramUser, type WellFormedOptions, assertWellFormed, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
163
+ export { type FromInitDataOptions, InitDataError, type InitDataExchange, type ParsedInitData, type TelegramExchangeSession, TelegramUnknownError, type TelegramUser, type WellFormedOptions, assertWellFormed, exchangeInitData, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
package/dist/telegram.js CHANGED
@@ -17,6 +17,9 @@ var NetworkError = class extends Error {
17
17
  this.name = "NetworkError";
18
18
  }
19
19
  };
20
+ function isApiError(e) {
21
+ return typeof e === "object" && e !== null && e.isApiError === true;
22
+ }
20
23
 
21
24
  // src/http.ts
22
25
  var API_VERSION = "/v1";
@@ -29,10 +32,11 @@ function versionedPath(path) {
29
32
  return `${API_VERSION}${p}`;
30
33
  }
31
34
  var HttpClient = class {
32
- constructor(baseUrl, tokens, fetchImpl) {
35
+ constructor(baseUrl, tokens, fetchImpl, defaultHeaders = {}) {
33
36
  this.baseUrl = baseUrl;
34
37
  this.tokens = tokens;
35
38
  this.fetchImpl = fetchImpl;
39
+ this.defaultHeaders = defaultHeaders;
36
40
  if (!baseUrl) throw new Error("HttpClient: baseUrl is required");
37
41
  }
38
42
  async get(path, opts = {}) {
@@ -53,7 +57,8 @@ var HttpClient = class {
53
57
  async request(method, path, opts) {
54
58
  const url = this.absolute(path);
55
59
  const headers = {
56
- Accept: "application/json"
60
+ Accept: "application/json",
61
+ ...this.defaultHeaders
57
62
  };
58
63
  if (opts.body !== void 0) headers["Content-Type"] = "application/json";
59
64
  if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
@@ -191,18 +196,38 @@ var AuthResource = class {
191
196
  skipAuth: true
192
197
  });
193
198
  }
194
- /** Exchange a signed Telegram Mini App `initData` payload for a session
195
- * JWT. The server validates the initData HMAC against the deployment's bot
196
- * token, then find-or-creates the end-user. First-time Telegram users are
197
- * auto-provisioned with `user.email_pending === true` — prompt them for a
198
- * real email and call {@link linkEmail}. Stores the JWT on success.
199
- *
200
- * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`
201
- * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when
202
- * you already hold a configured client. */
203
199
  async exchangeTelegram(input) {
204
- const resp = await this.http.post("/auth/telegram/exchange", {
205
- body: { init_data: input.initData },
200
+ const body = { init_data: input.initData };
201
+ if (input.provision !== void 0) body.provision = input.provision;
202
+ let resp;
203
+ try {
204
+ resp = await this.http.post("/auth/telegram/exchange", {
205
+ body,
206
+ skipAuth: true
207
+ });
208
+ } catch (e) {
209
+ if (isApiError(e) && e.status === 404 && e.code === "telegram_unknown") {
210
+ return { stage: "unknown" };
211
+ }
212
+ throw e;
213
+ }
214
+ await Promise.resolve(this.tokens.set(resp.access_token));
215
+ return resp;
216
+ }
217
+ /** Attach the Telegram account behind `initData` to an existing email +
218
+ * password account and sign in as that account. No bearer needed; the
219
+ * password is checked the same way `login` checks it. The JWT is stored.
220
+ *
221
+ * Errors: 401 `unauthenticated` (wrong email or password, as with
222
+ * `login`) / `invalid_init_data`; 403
223
+ * `user_disabled` / `second_factor_required` (accounts that sign in with
224
+ * a second factor can't be linked from a Mini App); 409
225
+ * `telegram_already_linked_other` (this account already has a different
226
+ * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
227
+ * another account); 503 `telegram_not_configured`. */
228
+ async linkTelegram(input) {
229
+ const resp = await this.http.post("/auth/telegram/link", {
230
+ body: { init_data: input.initData, email: input.email, password: input.password },
206
231
  skipAuth: true
207
232
  });
208
233
  await Promise.resolve(this.tokens.set(resp.access_token));
@@ -286,12 +311,44 @@ var CardsResource = class {
286
311
  * `failure_reason` on the result.
287
312
  */
288
313
  async create(input) {
289
- const { idempotencyKey, ...body } = input;
314
+ const { idempotencyKey, productId, name, designId, ...rest } = input;
315
+ const body = { ...rest };
316
+ if (productId !== void 0) body["product_id"] = productId;
317
+ if (name !== void 0) body["name"] = name;
318
+ if (designId !== void 0) body["design_id"] = designId;
290
319
  return this.http.post("/me/cards", {
291
320
  body,
292
321
  idempotencyKey
293
322
  });
294
323
  }
324
+ /**
325
+ * The cards the caller can order, in the order the deployment offers them
326
+ * (the default product first). Each item carries its name, description,
327
+ * artwork, the issuance price after the caller's subscription discount,
328
+ * and the currency. Pass an item's `id` as `productId` to {@link create}.
329
+ */
330
+ async listProducts() {
331
+ return this.http.get("/me/card-products");
332
+ }
333
+ /** One product from the catalog. 404 when unknown, disabled or hidden. */
334
+ async getProduct(id) {
335
+ return this.http.get(
336
+ `/me/card-products/${encodeURIComponent(id)}`
337
+ );
338
+ }
339
+ /**
340
+ * Rename the caller's own card or change its design. Resolves to the
341
+ * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /
342
+ * `design_not_allowed` on a bad value.
343
+ */
344
+ async update(id, input) {
345
+ const body = {};
346
+ if (input.name !== void 0) body["name"] = input.name;
347
+ if (input.designId !== void 0) body["design_id"] = input.designId;
348
+ return this.http.patch(`/me/cards/${encodeURIComponent(id)}`, {
349
+ body
350
+ });
351
+ }
295
352
  /** Fetch one card by id. */
296
353
  async get(id) {
297
354
  return this.http.get(`/me/cards/${encodeURIComponent(id)}`);
@@ -491,17 +548,20 @@ var PushResource = class {
491
548
  return this.http.get("/me/push-subscription");
492
549
  }
493
550
  /** Store a subscription you created yourself.
494
- * 409 `push_disabled` when the deployment has no VAPID keys. */
551
+ * 409 `push_disabled` when the deployment has no VAPID keys.
552
+ * @deprecated Use `client.devices.register({ kind: "webpush", ... })`. */
495
553
  async save(input) {
496
554
  return this.http.put("/me/push-subscription", { body: input });
497
555
  }
498
- /** Delete the stored subscription. Safe when nothing is stored. */
556
+ /** Delete the stored subscription. Safe when nothing is stored.
557
+ * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */
499
558
  async remove() {
500
559
  await this.http.delete("/me/push-subscription");
501
560
  }
502
561
  /** Subscribe this browser and store the subscription. Ask for
503
562
  * notification permission before calling. Throws when push isn't set up
504
- * on the deployment. */
563
+ * on the deployment.
564
+ * @deprecated Use `client.devices.registerWebPush(registration)`. */
505
565
  async enable(registration) {
506
566
  const { vapid_public_key } = await this.status();
507
567
  if (!vapid_public_key) {
@@ -520,7 +580,8 @@ var PushResource = class {
520
580
  keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
521
581
  });
522
582
  }
523
- /** Unsubscribe this browser and delete the stored subscription. */
583
+ /** Unsubscribe this browser and delete the stored subscription.
584
+ * @deprecated Use `client.devices.unregisterWebPush(registration)`. */
524
585
  async disable(registration) {
525
586
  const sub = await registration.pushManager.getSubscription();
526
587
  if (sub) await sub.unsubscribe();
@@ -536,6 +597,185 @@ function base64UrlToBytes(input) {
536
597
  return out;
537
598
  }
538
599
 
600
+ // src/resources/me.ts
601
+ var MeResource = class {
602
+ constructor(http) {
603
+ this.http = http;
604
+ }
605
+ /** Attach the Telegram account behind `initData` to the signed-in user.
606
+ * Returns the updated user (`telegram` is set). Repeating the call with
607
+ * the same Telegram is fine.
608
+ *
609
+ * Errors: 401 `invalid_init_data`; 403 `user_disabled` /
610
+ * `second_factor_required`; 409 `telegram_already_linked_other` (the
611
+ * account already has a different Telegram; `unlinkTelegram` first) /
612
+ * `telegram_in_use` (that Telegram belongs to another account); 503
613
+ * `telegram_not_configured`. */
614
+ async linkTelegram(initData) {
615
+ return this.http.post("/me/telegram", { body: { init_data: initData } });
616
+ }
617
+ /** Detach the Telegram account from the signed-in user. Returns the
618
+ * updated user (`telegram` is `null`).
619
+ *
620
+ * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
621
+ * account has no password, so Telegram is its only way to sign in. */
622
+ async unlinkTelegram() {
623
+ return this.http.delete("/me/telegram");
624
+ }
625
+ };
626
+
627
+ // src/resources/notifications.ts
628
+ var NotificationsResource = class {
629
+ constructor(http) {
630
+ this.http = http;
631
+ }
632
+ /** One page of the inbox, newest first. */
633
+ async list(params = {}) {
634
+ const q = new URLSearchParams();
635
+ if (params.cursor) q.set("cursor", params.cursor);
636
+ if (params.limit !== void 0) q.set("limit", String(params.limit));
637
+ if (params.unreadOnly) q.set("unread", "true");
638
+ if (params.category) q.set("category", params.category);
639
+ const qs = q.toString();
640
+ return this.http.get(`/me/notifications${qs ? `?${qs}` : ""}`);
641
+ }
642
+ /** How many items are unread. Cheap; fine to poll for a badge. */
643
+ async unreadCount() {
644
+ const { unread } = await this.http.get("/me/notifications/unread-count");
645
+ return unread;
646
+ }
647
+ /** Mark one item read. Returns the item; calling it again is harmless. */
648
+ async markRead(id) {
649
+ return this.http.post(`/me/notifications/${encodeURIComponent(id)}/read`);
650
+ }
651
+ /** Mark every unread item read, or only those created before `before`
652
+ * (ISO timestamp). Returns how many changed. */
653
+ async markAllRead(before) {
654
+ return this.http.post("/me/notifications/read-all", {
655
+ body: before ? { before } : {}
656
+ });
657
+ }
658
+ /** Delete one item. 404 when it isn't the user's. */
659
+ async remove(id) {
660
+ await this.http.delete(`/me/notifications/${encodeURIComponent(id)}`);
661
+ }
662
+ /** The user's channel and language settings. */
663
+ async getPreferences() {
664
+ return this.http.get("/me/notification-preferences");
665
+ }
666
+ /** Change some settings; the rest stay. Returns the stored view.
667
+ * 400 `validation` for an unknown category, channel or locale. */
668
+ async setPreferences(input) {
669
+ return this.http.put("/me/notification-preferences", {
670
+ body: input
671
+ });
672
+ }
673
+ };
674
+
675
+ // src/resources/devices.ts
676
+ function devicePlatformOf(platform) {
677
+ return platform === "telegram-miniapp" ? "telegram" : platform;
678
+ }
679
+ var DevicesResource = class {
680
+ constructor(http, client) {
681
+ this.http = http;
682
+ this.client = client;
683
+ }
684
+ /** Every device the user has, disabled ones included. */
685
+ async list() {
686
+ return this.http.get("/me/devices");
687
+ }
688
+ /** Register a device, or refresh it when the same credential is already
689
+ * known (then `last_seen_at`, `label` and `app_version` update and a
690
+ * disabled device comes back). `app_version` defaults to the client
691
+ * version sent in `X-Takeal-Client`.
692
+ *
693
+ * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
694
+ * deployment has no VAPID keys. */
695
+ async register(input) {
696
+ return this.http.put("/me/devices", {
697
+ body: { app_version: this.client.version, ...input }
698
+ });
699
+ }
700
+ /** Delete one device. 404 when it isn't the user's. */
701
+ async remove(id) {
702
+ await this.http.delete(`/me/devices/${encodeURIComponent(id)}`);
703
+ }
704
+ /** Subscribe this browser to Web Push and register it as a device. Ask
705
+ * for notification permission before calling. Throws when push isn't
706
+ * set up on the deployment. */
707
+ async registerWebPush(registration, opts = {}) {
708
+ const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
709
+ if (!key) {
710
+ throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
711
+ }
712
+ const sub = await registration.pushManager.subscribe({
713
+ userVisibleOnly: true,
714
+ applicationServerKey: base64UrlToBytes(key)
715
+ });
716
+ const json = sub.toJSON();
717
+ if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
718
+ throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
719
+ }
720
+ return this.register({
721
+ kind: "webpush",
722
+ platform: devicePlatformOf(this.client.platform),
723
+ credential: {
724
+ endpoint: json.endpoint,
725
+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
726
+ },
727
+ ...opts.label ? { label: opts.label } : {}
728
+ });
729
+ }
730
+ /** Unsubscribe this browser from Web Push and delete the matching device
731
+ * (see {@link UnregisterWebPushOptions}). Safe when nothing is
732
+ * registered. */
733
+ async unregisterWebPush(registration, opts = {}) {
734
+ const sub = await registration.pushManager.getSubscription();
735
+ if (sub) await sub.unsubscribe();
736
+ if (opts.deviceId) {
737
+ await this.remove(opts.deviceId);
738
+ return;
739
+ }
740
+ const mine = (await this.list()).filter((d) => d.kind === "webpush" && d.is_current);
741
+ for (const d of mine) await this.remove(d.id);
742
+ }
743
+ async vapidPublicKey() {
744
+ const { vapid_public_key } = await this.http.get(
745
+ "/me/push-subscription"
746
+ );
747
+ return vapid_public_key ?? null;
748
+ }
749
+ };
750
+
751
+ // src/version.ts
752
+ var SDK_VERSION = "0.3.0";
753
+
754
+ // src/client-platform.ts
755
+ var CLIENT_HEADER = "X-Takeal-Client";
756
+ function detectClientPlatform() {
757
+ const g = globalThis;
758
+ const initData = g.Telegram?.WebApp?.initData;
759
+ if (typeof initData === "string" && initData.length > 0) return "telegram-miniapp";
760
+ if (g.navigator?.standalone === true) return "pwa";
761
+ if (typeof g.matchMedia === "function") {
762
+ try {
763
+ if (g.matchMedia("(display-mode: standalone)").matches) return "pwa";
764
+ } catch {
765
+ }
766
+ }
767
+ return "web";
768
+ }
769
+ function resolveClientDescriptor(given) {
770
+ return {
771
+ platform: given?.platform ?? detectClientPlatform(),
772
+ version: given?.version || SDK_VERSION
773
+ };
774
+ }
775
+ function clientHeaderValue(desc) {
776
+ return `${desc.platform}; ${desc.version}`;
777
+ }
778
+
539
779
  // src/token-store.ts
540
780
  function defaultBrowserStore(key = "takeal_jwt") {
541
781
  const fallback = inMemoryStore();
@@ -572,14 +812,30 @@ function inMemoryStore() {
572
812
  };
573
813
  }
574
814
 
815
+ // src/assets.ts
816
+ function resolveAssetUrl(baseUrl, url) {
817
+ if (isAbsolute(url)) return url;
818
+ const base = baseUrl.replace(/\/+$/, "");
819
+ const path = url.startsWith("/") ? url : `/${url}`;
820
+ return `${base}${path}`;
821
+ }
822
+ function isAbsolute(url) {
823
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url);
824
+ }
825
+
575
826
  // src/index.ts
576
827
  function createClient(opts) {
577
828
  const tokens = opts.tokenStore ?? pickDefaultStore();
578
829
  const fetchImpl = opts.fetch ?? defaultFetch();
579
- const http = new HttpClient(opts.baseUrl, tokens, fetchImpl);
830
+ const client = resolveClientDescriptor(opts.client);
831
+ const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {
832
+ [CLIENT_HEADER]: clientHeaderValue(client)
833
+ });
580
834
  return {
581
835
  brand: opts.brand,
836
+ client,
582
837
  tokens,
838
+ assetUrl: (url) => resolveAssetUrl(opts.baseUrl, url),
583
839
  auth: new AuthResource(http, tokens),
584
840
  deposits: new DepositsResource(http),
585
841
  cards: new CardsResource(http),
@@ -589,7 +845,10 @@ function createClient(opts) {
589
845
  blog: new BlogResource(http),
590
846
  subscriptions: new SubscriptionsResource(http),
591
847
  sessions: new SessionsResource(http),
592
- push: new PushResource(http)
848
+ push: new PushResource(http),
849
+ me: new MeResource(http),
850
+ notifications: new NotificationsResource(http),
851
+ devices: new DevicesResource(http, client)
593
852
  };
594
853
  }
595
854
  function pickDefaultStore() {
@@ -664,10 +923,47 @@ function assertWellFormed(initData, opts = {}) {
664
923
  }
665
924
  return parsed;
666
925
  }
667
- async function fromInitData(initData, config, opts = {}) {
926
+ var TelegramUnknownError = class extends Error {
927
+ constructor(initData) {
928
+ super("this Telegram account is not linked to any user (provision: false)");
929
+ this.initData = initData;
930
+ this.name = "TelegramUnknownError";
931
+ }
932
+ };
933
+ async function exchangeInitData(initData, config, opts = {}) {
668
934
  if (!opts.skipWellFormedCheck) assertWellFormed(initData, opts);
669
- const client = createClient(config);
670
- await client.auth.exchangeTelegram({ initData });
935
+ const client = createClient({
936
+ ...config,
937
+ client: { ...config.client, platform: "telegram-miniapp" }
938
+ });
939
+ const session = await client.auth.exchangeTelegram({
940
+ initData,
941
+ ...opts.provision !== void 0 ? { provision: opts.provision } : {}
942
+ });
943
+ if (session.stage === "jwt" && opts.registerDevice !== false) {
944
+ await registerMiniAppDevice(client, initData);
945
+ }
946
+ return { client, session };
947
+ }
948
+ async function registerMiniAppDevice(client, initData) {
949
+ const locale = parseInitData(initData).user?.language_code;
950
+ try {
951
+ await client.devices.register({
952
+ kind: "telegram_miniapp",
953
+ platform: "telegram",
954
+ credential: {},
955
+ ...locale ? { locale } : {}
956
+ });
957
+ } catch (e) {
958
+ console.warn(
959
+ "@takeal/cusfront-sdk/telegram: could not register the Mini App as a device; notifications may not reach this user in Telegram",
960
+ e
961
+ );
962
+ }
963
+ }
964
+ async function fromInitData(initData, config, opts = {}) {
965
+ const { client, session } = await exchangeInitData(initData, config, opts);
966
+ if (session.stage === "unknown") throw new TelegramUnknownError(initData);
671
967
  return client;
672
968
  }
673
969
  function readWebAppInitData() {
@@ -685,6 +981,6 @@ async function fromTelegramWebApp(config, opts = {}) {
685
981
  return fromInitData(initData, config, opts);
686
982
  }
687
983
 
688
- export { InitDataError, assertWellFormed, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
984
+ export { InitDataError, TelegramUnknownError, assertWellFormed, exchangeInitData, fromInitData, fromTelegramWebApp, parseInitData, readWebAppInitData };
689
985
  //# sourceMappingURL=telegram.js.map
690
986
  //# sourceMappingURL=telegram.js.map