@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/dist/index.cjs CHANGED
@@ -27,11 +27,21 @@ function isNetworkError(e) {
27
27
  }
28
28
 
29
29
  // src/http.ts
30
+ var API_VERSION = "/v1";
31
+ var UNVERSIONED = /* @__PURE__ */ new Set(["/health", "/ready", "/branding", "/favicon.ico"]);
32
+ function versionedPath(path) {
33
+ const p = path.startsWith("/") ? path : `/${path}`;
34
+ const bare = p.split("?")[0];
35
+ if (UNVERSIONED.has(bare)) return p;
36
+ if (bare === API_VERSION || bare.startsWith(`${API_VERSION}/`)) return p;
37
+ return `${API_VERSION}${p}`;
38
+ }
30
39
  var HttpClient = class {
31
- constructor(baseUrl, tokens, fetchImpl) {
40
+ constructor(baseUrl, tokens, fetchImpl, defaultHeaders = {}) {
32
41
  this.baseUrl = baseUrl;
33
42
  this.tokens = tokens;
34
43
  this.fetchImpl = fetchImpl;
44
+ this.defaultHeaders = defaultHeaders;
35
45
  if (!baseUrl) throw new Error("HttpClient: baseUrl is required");
36
46
  }
37
47
  async get(path, opts = {}) {
@@ -52,7 +62,8 @@ var HttpClient = class {
52
62
  async request(method, path, opts) {
53
63
  const url = this.absolute(path);
54
64
  const headers = {
55
- Accept: "application/json"
65
+ Accept: "application/json",
66
+ ...this.defaultHeaders
56
67
  };
57
68
  if (opts.body !== void 0) headers["Content-Type"] = "application/json";
58
69
  if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
@@ -83,8 +94,7 @@ var HttpClient = class {
83
94
  absolute(path) {
84
95
  if (path.startsWith("http://") || path.startsWith("https://")) return path;
85
96
  const base = this.baseUrl.replace(/\/+$/, "");
86
- const tail = path.startsWith("/") ? path : `/${path}`;
87
- return `${base}${tail}`;
97
+ return `${base}${versionedPath(path)}`;
88
98
  }
89
99
  };
90
100
  async function parseResponse(resp) {
@@ -149,6 +159,40 @@ var AuthResource = class {
149
159
  await Promise.resolve(this.tokens.set(resp.access_token));
150
160
  return resp;
151
161
  }
162
+ /** Create an end-user account and sign it in. The JWT is stored.
163
+ * `wallet_currency` must be one the deployment offers; omit it to take
164
+ * the deployment default (it can be switched later via `client.wallet`
165
+ * while the wallet is empty).
166
+ * Errors: 400 `validation` / `currency_not_allowed`, 409 email taken. */
167
+ async register(input) {
168
+ const resp = await this.http.post("/auth/register", {
169
+ body: input,
170
+ skipAuth: true
171
+ });
172
+ await Promise.resolve(this.tokens.set(resp.access_token));
173
+ return resp;
174
+ }
175
+ /** Finish a `totp_setup_required` login: send the first code from the
176
+ * authenticator app. The JWT is stored. The response carries ten
177
+ * one-time `backup_codes` that are never returned again, so show them to
178
+ * the user right away and don't keep them on the device. */
179
+ async completeTotpSetup(input) {
180
+ const resp = await this.http.post("/auth/login/totp-setup", {
181
+ body: input,
182
+ skipAuth: true
183
+ });
184
+ await Promise.resolve(this.tokens.set(resp.access_token));
185
+ return resp;
186
+ }
187
+ /** Change the signed-in user's password. Every other session of the
188
+ * account is signed out; this one stays valid.
189
+ * Errors: 400 when the new password fails the policy, 401 when the
190
+ * current one is wrong. */
191
+ async changePassword(input) {
192
+ return this.http.post("/auth/password", {
193
+ body: input
194
+ });
195
+ }
152
196
  /** Swap the 2FA method mid-flow. Resolves to `otp_sent` for
153
197
  * telegram/email; for TOTP it short-circuits back to the challenge. */
154
198
  async switchMethod(input) {
@@ -157,18 +201,38 @@ var AuthResource = class {
157
201
  skipAuth: true
158
202
  });
159
203
  }
160
- /** Exchange a signed Telegram Mini App `initData` payload for a session
161
- * JWT. The server validates the initData HMAC against the deployment's bot
162
- * token, then find-or-creates the end-user. First-time Telegram users are
163
- * auto-provisioned with `user.email_pending === true` — prompt them for a
164
- * real email and call {@link linkEmail}. Stores the JWT on success.
165
- *
166
- * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`
167
- * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when
168
- * you already hold a configured client. */
169
204
  async exchangeTelegram(input) {
170
- const resp = await this.http.post("/auth/telegram/exchange", {
171
- body: { init_data: input.initData },
205
+ const body = { init_data: input.initData };
206
+ if (input.provision !== void 0) body.provision = input.provision;
207
+ let resp;
208
+ try {
209
+ resp = await this.http.post("/auth/telegram/exchange", {
210
+ body,
211
+ skipAuth: true
212
+ });
213
+ } catch (e) {
214
+ if (isApiError(e) && e.status === 404 && e.code === "telegram_unknown") {
215
+ return { stage: "unknown" };
216
+ }
217
+ throw e;
218
+ }
219
+ await Promise.resolve(this.tokens.set(resp.access_token));
220
+ return resp;
221
+ }
222
+ /** Attach the Telegram account behind `initData` to an existing email +
223
+ * password account and sign in as that account. No bearer needed; the
224
+ * password is checked the same way `login` checks it. The JWT is stored.
225
+ *
226
+ * Errors: 401 `unauthenticated` (wrong email or password, as with
227
+ * `login`) / `invalid_init_data`; 403
228
+ * `user_disabled` / `second_factor_required` (accounts that sign in with
229
+ * a second factor can't be linked from a Mini App); 409
230
+ * `telegram_already_linked_other` (this account already has a different
231
+ * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
232
+ * another account); 503 `telegram_not_configured`. */
233
+ async linkTelegram(input) {
234
+ const resp = await this.http.post("/auth/telegram/link", {
235
+ body: { init_data: input.initData, email: input.email, password: input.password },
172
236
  skipAuth: true
173
237
  });
174
238
  await Promise.resolve(this.tokens.set(resp.access_token));
@@ -185,10 +249,9 @@ var AuthResource = class {
185
249
  async me() {
186
250
  return this.http.get("/auth/me");
187
251
  }
188
- /** Local sign-out. The SDK doesn't currently call a server-side
189
- * endpoint (the Takeal API issues stateless JWTs); clearing the
190
- * store is enough. Server-side session invalidation may land
191
- * with a future session table. */
252
+ /** Local sign-out: forgets the stored JWT. To end the session on the
253
+ * server as well, revoke it first with `client.sessions.revoke(jti)`
254
+ * (the current one is marked `current: true` in `client.sessions.list()`). */
192
255
  async signOut() {
193
256
  await Promise.resolve(this.tokens.clear());
194
257
  }
@@ -253,12 +316,44 @@ var CardsResource = class {
253
316
  * `failure_reason` on the result.
254
317
  */
255
318
  async create(input) {
256
- const { idempotencyKey, ...body } = input;
319
+ const { idempotencyKey, productId, name, designId, ...rest } = input;
320
+ const body = { ...rest };
321
+ if (productId !== void 0) body["product_id"] = productId;
322
+ if (name !== void 0) body["name"] = name;
323
+ if (designId !== void 0) body["design_id"] = designId;
257
324
  return this.http.post("/me/cards", {
258
325
  body,
259
326
  idempotencyKey
260
327
  });
261
328
  }
329
+ /**
330
+ * The cards the caller can order, in the order the deployment offers them
331
+ * (the default product first). Each item carries its name, description,
332
+ * artwork, the issuance price after the caller's subscription discount,
333
+ * and the currency. Pass an item's `id` as `productId` to {@link create}.
334
+ */
335
+ async listProducts() {
336
+ return this.http.get("/me/card-products");
337
+ }
338
+ /** One product from the catalog. 404 when unknown, disabled or hidden. */
339
+ async getProduct(id) {
340
+ return this.http.get(
341
+ `/me/card-products/${encodeURIComponent(id)}`
342
+ );
343
+ }
344
+ /**
345
+ * Rename the caller's own card or change its design. Resolves to the
346
+ * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /
347
+ * `design_not_allowed` on a bad value.
348
+ */
349
+ async update(id, input) {
350
+ const body = {};
351
+ if (input.name !== void 0) body["name"] = input.name;
352
+ if (input.designId !== void 0) body["design_id"] = input.designId;
353
+ return this.http.patch(`/me/cards/${encodeURIComponent(id)}`, {
354
+ body
355
+ });
356
+ }
262
357
  /** Fetch one card by id. */
263
358
  async get(id) {
264
359
  return this.http.get(`/me/cards/${encodeURIComponent(id)}`);
@@ -333,11 +428,12 @@ var BalanceResource = class {
333
428
  this.http = http;
334
429
  }
335
430
  /**
336
- * Fetch the user's wallet balance for `currency` (ISO 4217, e.g. `"USD"`).
337
- * Required — the ledger holds a separate balance per currency, so there is
338
- * no "total" without one.
431
+ * Fetch the user's wallet balance. Omit `currency` for the wallet's own
432
+ * currency; pass an ISO 4217 code (e.g. `"USD"`) to read another one —
433
+ * the ledger holds a separate balance per currency.
339
434
  */
340
435
  async get(currency) {
436
+ if (!currency) return this.http.get("/me/balance");
341
437
  const q = new URLSearchParams({ currency }).toString();
342
438
  return this.http.get(`/me/balance?${q}`);
343
439
  }
@@ -354,6 +450,25 @@ var BrandingResource = class {
354
450
  }
355
451
  };
356
452
 
453
+ // src/resources/wallet.ts
454
+ var WalletResource = class {
455
+ constructor(http) {
456
+ this.http = http;
457
+ }
458
+ /** Current wallet currency + the currencies the user may switch to. */
459
+ async get(opts = {}) {
460
+ return this.http.get("/me/wallet", { signal: opts.signal });
461
+ }
462
+ /**
463
+ * Switch the wallet currency. Fails with `409 wallet_not_empty` while any
464
+ * balance is non-zero, and `400 currency_not_allowed` for a currency the
465
+ * deployment does not offer.
466
+ */
467
+ async set(currency, opts = {}) {
468
+ return this.http.put("/me/wallet", { body: { currency }, signal: opts.signal });
469
+ }
470
+ };
471
+
357
472
  // src/resources/blog.ts
358
473
  var BlogResource = class {
359
474
  constructor(http) {
@@ -407,6 +522,265 @@ var SubscriptionsResource = class {
407
522
  }
408
523
  };
409
524
 
525
+ // src/resources/sessions.ts
526
+ var SessionsResource = class {
527
+ constructor(http) {
528
+ this.http = http;
529
+ }
530
+ /** All live sessions of the account, this one included. */
531
+ async list() {
532
+ return this.http.get("/me/sessions");
533
+ }
534
+ /** Sign out one session. Works on the current one too; the stored JWT
535
+ * stops working, so follow with `client.auth.signOut()`.
536
+ * 404 when the session is unknown or already signed out. */
537
+ async revoke(jti) {
538
+ await this.http.delete(`/me/sessions/${encodeURIComponent(jti)}`);
539
+ }
540
+ /** Sign out every session except this one. */
541
+ async revokeOthers() {
542
+ return this.http.post("/me/sessions/terminate-others");
543
+ }
544
+ };
545
+
546
+ // src/resources/push.ts
547
+ var PushResource = class {
548
+ constructor(http) {
549
+ this.http = http;
550
+ }
551
+ /** Whether the user is subscribed, plus the VAPID key to subscribe with. */
552
+ async status() {
553
+ return this.http.get("/me/push-subscription");
554
+ }
555
+ /** Store a subscription you created yourself.
556
+ * 409 `push_disabled` when the deployment has no VAPID keys.
557
+ * @deprecated Use `client.devices.register({ kind: "webpush", ... })`. */
558
+ async save(input) {
559
+ return this.http.put("/me/push-subscription", { body: input });
560
+ }
561
+ /** Delete the stored subscription. Safe when nothing is stored.
562
+ * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */
563
+ async remove() {
564
+ await this.http.delete("/me/push-subscription");
565
+ }
566
+ /** Subscribe this browser and store the subscription. Ask for
567
+ * notification permission before calling. Throws when push isn't set up
568
+ * on the deployment.
569
+ * @deprecated Use `client.devices.registerWebPush(registration)`. */
570
+ async enable(registration) {
571
+ const { vapid_public_key } = await this.status();
572
+ if (!vapid_public_key) {
573
+ throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
574
+ }
575
+ const sub = await registration.pushManager.subscribe({
576
+ userVisibleOnly: true,
577
+ applicationServerKey: base64UrlToBytes(vapid_public_key)
578
+ });
579
+ const json = sub.toJSON();
580
+ if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
581
+ throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
582
+ }
583
+ return this.save({
584
+ endpoint: json.endpoint,
585
+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
586
+ });
587
+ }
588
+ /** Unsubscribe this browser and delete the stored subscription.
589
+ * @deprecated Use `client.devices.unregisterWebPush(registration)`. */
590
+ async disable(registration) {
591
+ const sub = await registration.pushManager.getSubscription();
592
+ if (sub) await sub.unsubscribe();
593
+ await this.remove();
594
+ }
595
+ };
596
+ function base64UrlToBytes(input) {
597
+ const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
598
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
599
+ const bin = atob(padded);
600
+ const out = new Uint8Array(bin.length);
601
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
602
+ return out;
603
+ }
604
+
605
+ // src/resources/me.ts
606
+ var MeResource = class {
607
+ constructor(http) {
608
+ this.http = http;
609
+ }
610
+ /** Attach the Telegram account behind `initData` to the signed-in user.
611
+ * Returns the updated user (`telegram` is set). Repeating the call with
612
+ * the same Telegram is fine.
613
+ *
614
+ * Errors: 401 `invalid_init_data`; 403 `user_disabled` /
615
+ * `second_factor_required`; 409 `telegram_already_linked_other` (the
616
+ * account already has a different Telegram; `unlinkTelegram` first) /
617
+ * `telegram_in_use` (that Telegram belongs to another account); 503
618
+ * `telegram_not_configured`. */
619
+ async linkTelegram(initData) {
620
+ return this.http.post("/me/telegram", { body: { init_data: initData } });
621
+ }
622
+ /** Detach the Telegram account from the signed-in user. Returns the
623
+ * updated user (`telegram` is `null`).
624
+ *
625
+ * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
626
+ * account has no password, so Telegram is its only way to sign in. */
627
+ async unlinkTelegram() {
628
+ return this.http.delete("/me/telegram");
629
+ }
630
+ };
631
+
632
+ // src/resources/notifications.ts
633
+ var NotificationsResource = class {
634
+ constructor(http) {
635
+ this.http = http;
636
+ }
637
+ /** One page of the inbox, newest first. */
638
+ async list(params = {}) {
639
+ const q = new URLSearchParams();
640
+ if (params.cursor) q.set("cursor", params.cursor);
641
+ if (params.limit !== void 0) q.set("limit", String(params.limit));
642
+ if (params.unreadOnly) q.set("unread", "true");
643
+ if (params.category) q.set("category", params.category);
644
+ const qs = q.toString();
645
+ return this.http.get(`/me/notifications${qs ? `?${qs}` : ""}`);
646
+ }
647
+ /** How many items are unread. Cheap; fine to poll for a badge. */
648
+ async unreadCount() {
649
+ const { unread } = await this.http.get("/me/notifications/unread-count");
650
+ return unread;
651
+ }
652
+ /** Mark one item read. Returns the item; calling it again is harmless. */
653
+ async markRead(id) {
654
+ return this.http.post(`/me/notifications/${encodeURIComponent(id)}/read`);
655
+ }
656
+ /** Mark every unread item read, or only those created before `before`
657
+ * (ISO timestamp). Returns how many changed. */
658
+ async markAllRead(before) {
659
+ return this.http.post("/me/notifications/read-all", {
660
+ body: before ? { before } : {}
661
+ });
662
+ }
663
+ /** Delete one item. 404 when it isn't the user's. */
664
+ async remove(id) {
665
+ await this.http.delete(`/me/notifications/${encodeURIComponent(id)}`);
666
+ }
667
+ /** The user's channel and language settings. */
668
+ async getPreferences() {
669
+ return this.http.get("/me/notification-preferences");
670
+ }
671
+ /** Change some settings; the rest stay. Returns the stored view.
672
+ * 400 `validation` for an unknown category, channel or locale. */
673
+ async setPreferences(input) {
674
+ return this.http.put("/me/notification-preferences", {
675
+ body: input
676
+ });
677
+ }
678
+ };
679
+
680
+ // src/resources/devices.ts
681
+ function devicePlatformOf(platform) {
682
+ return platform === "telegram-miniapp" ? "telegram" : platform;
683
+ }
684
+ var DevicesResource = class {
685
+ constructor(http, client) {
686
+ this.http = http;
687
+ this.client = client;
688
+ }
689
+ /** Every device the user has, disabled ones included. */
690
+ async list() {
691
+ return this.http.get("/me/devices");
692
+ }
693
+ /** Register a device, or refresh it when the same credential is already
694
+ * known (then `last_seen_at`, `label` and `app_version` update and a
695
+ * disabled device comes back). `app_version` defaults to the client
696
+ * version sent in `X-Takeal-Client`.
697
+ *
698
+ * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
699
+ * deployment has no VAPID keys. */
700
+ async register(input) {
701
+ return this.http.put("/me/devices", {
702
+ body: { app_version: this.client.version, ...input }
703
+ });
704
+ }
705
+ /** Delete one device. 404 when it isn't the user's. */
706
+ async remove(id) {
707
+ await this.http.delete(`/me/devices/${encodeURIComponent(id)}`);
708
+ }
709
+ /** Subscribe this browser to Web Push and register it as a device. Ask
710
+ * for notification permission before calling. Throws when push isn't
711
+ * set up on the deployment. */
712
+ async registerWebPush(registration, opts = {}) {
713
+ const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
714
+ if (!key) {
715
+ throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
716
+ }
717
+ const sub = await registration.pushManager.subscribe({
718
+ userVisibleOnly: true,
719
+ applicationServerKey: base64UrlToBytes(key)
720
+ });
721
+ const json = sub.toJSON();
722
+ if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
723
+ throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
724
+ }
725
+ return this.register({
726
+ kind: "webpush",
727
+ platform: devicePlatformOf(this.client.platform),
728
+ credential: {
729
+ endpoint: json.endpoint,
730
+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
731
+ },
732
+ ...opts.label ? { label: opts.label } : {}
733
+ });
734
+ }
735
+ /** Unsubscribe this browser from Web Push and delete the matching device
736
+ * (see {@link UnregisterWebPushOptions}). Safe when nothing is
737
+ * registered. */
738
+ async unregisterWebPush(registration, opts = {}) {
739
+ const sub = await registration.pushManager.getSubscription();
740
+ if (sub) await sub.unsubscribe();
741
+ if (opts.deviceId) {
742
+ await this.remove(opts.deviceId);
743
+ return;
744
+ }
745
+ const mine = (await this.list()).filter((d) => d.kind === "webpush" && d.is_current);
746
+ for (const d of mine) await this.remove(d.id);
747
+ }
748
+ async vapidPublicKey() {
749
+ const { vapid_public_key } = await this.http.get(
750
+ "/me/push-subscription"
751
+ );
752
+ return vapid_public_key ?? null;
753
+ }
754
+ };
755
+
756
+ // src/version.ts
757
+ var SDK_VERSION = "0.3.0";
758
+
759
+ // src/client-platform.ts
760
+ var CLIENT_HEADER = "X-Takeal-Client";
761
+ function detectClientPlatform() {
762
+ const g = globalThis;
763
+ const initData = g.Telegram?.WebApp?.initData;
764
+ if (typeof initData === "string" && initData.length > 0) return "telegram-miniapp";
765
+ if (g.navigator?.standalone === true) return "pwa";
766
+ if (typeof g.matchMedia === "function") {
767
+ try {
768
+ if (g.matchMedia("(display-mode: standalone)").matches) return "pwa";
769
+ } catch {
770
+ }
771
+ }
772
+ return "web";
773
+ }
774
+ function resolveClientDescriptor(given) {
775
+ return {
776
+ platform: given?.platform ?? detectClientPlatform(),
777
+ version: given?.version || SDK_VERSION
778
+ };
779
+ }
780
+ function clientHeaderValue(desc) {
781
+ return `${desc.platform}; ${desc.version}`;
782
+ }
783
+
410
784
  // src/token-store.ts
411
785
  function defaultBrowserStore(key = "takeal_jwt") {
412
786
  const fallback = inMemoryStore();
@@ -443,21 +817,43 @@ function inMemoryStore() {
443
817
  };
444
818
  }
445
819
 
820
+ // src/assets.ts
821
+ function resolveAssetUrl(baseUrl, url) {
822
+ if (isAbsolute(url)) return url;
823
+ const base = baseUrl.replace(/\/+$/, "");
824
+ const path = url.startsWith("/") ? url : `/${url}`;
825
+ return `${base}${path}`;
826
+ }
827
+ function isAbsolute(url) {
828
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url);
829
+ }
830
+
446
831
  // src/index.ts
447
832
  function createClient(opts) {
448
833
  const tokens = opts.tokenStore ?? pickDefaultStore();
449
834
  const fetchImpl = opts.fetch ?? defaultFetch();
450
- const http = new HttpClient(opts.baseUrl, tokens, fetchImpl);
835
+ const client = resolveClientDescriptor(opts.client);
836
+ const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {
837
+ [CLIENT_HEADER]: clientHeaderValue(client)
838
+ });
451
839
  return {
452
840
  brand: opts.brand,
841
+ client,
453
842
  tokens,
843
+ assetUrl: (url) => resolveAssetUrl(opts.baseUrl, url),
454
844
  auth: new AuthResource(http, tokens),
455
845
  deposits: new DepositsResource(http),
456
846
  cards: new CardsResource(http),
457
847
  balance: new BalanceResource(http),
848
+ wallet: new WalletResource(http),
458
849
  branding: new BrandingResource(http),
459
850
  blog: new BlogResource(http),
460
- subscriptions: new SubscriptionsResource(http)
851
+ subscriptions: new SubscriptionsResource(http),
852
+ sessions: new SessionsResource(http),
853
+ push: new PushResource(http),
854
+ me: new MeResource(http),
855
+ notifications: new NotificationsResource(http),
856
+ devices: new DevicesResource(http, client)
461
857
  };
462
858
  }
463
859
  function pickDefaultStore() {
@@ -476,11 +872,15 @@ function defaultFetch() {
476
872
  }
477
873
 
478
874
  exports.ApiError = ApiError;
875
+ exports.CLIENT_HEADER = CLIENT_HEADER;
479
876
  exports.NetworkError = NetworkError;
877
+ exports.SDK_VERSION = SDK_VERSION;
480
878
  exports.createClient = createClient;
481
879
  exports.defaultBrowserStore = defaultBrowserStore;
880
+ exports.detectClientPlatform = detectClientPlatform;
482
881
  exports.inMemoryStore = inMemoryStore;
483
882
  exports.isApiError = isApiError;
484
883
  exports.isNetworkError = isNetworkError;
884
+ exports.resolveAssetUrl = resolveAssetUrl;
485
885
  //# sourceMappingURL=index.cjs.map
486
886
  //# sourceMappingURL=index.cjs.map