@takeal/cusfront-sdk 0.2.8 → 0.3.7

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 +100 -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 +284 -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 +280 -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 +111 -4
  34. package/dist/resources/cards.d.ts +111 -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 +57 -0
  52. package/dist/resources/notifications.cjs.map +1 -0
  53. package/dist/resources/notifications.d.cts +133 -0
  54. package/dist/resources/notifications.d.ts +133 -0
  55. package/dist/resources/notifications.js +54 -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 +23 -4
package/dist/index.cjs CHANGED
@@ -37,10 +37,11 @@ function versionedPath(path) {
37
37
  return `${API_VERSION}${p}`;
38
38
  }
39
39
  var HttpClient = class {
40
- constructor(baseUrl, tokens, fetchImpl) {
40
+ constructor(baseUrl, tokens, fetchImpl, defaultHeaders = {}) {
41
41
  this.baseUrl = baseUrl;
42
42
  this.tokens = tokens;
43
43
  this.fetchImpl = fetchImpl;
44
+ this.defaultHeaders = defaultHeaders;
44
45
  if (!baseUrl) throw new Error("HttpClient: baseUrl is required");
45
46
  }
46
47
  async get(path, opts = {}) {
@@ -61,7 +62,8 @@ var HttpClient = class {
61
62
  async request(method, path, opts) {
62
63
  const url = this.absolute(path);
63
64
  const headers = {
64
- Accept: "application/json"
65
+ Accept: "application/json",
66
+ ...this.defaultHeaders
65
67
  };
66
68
  if (opts.body !== void 0) headers["Content-Type"] = "application/json";
67
69
  if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
@@ -199,18 +201,38 @@ var AuthResource = class {
199
201
  skipAuth: true
200
202
  });
201
203
  }
202
- /** Exchange a signed Telegram Mini App `initData` payload for a session
203
- * JWT. The server validates the initData HMAC against the deployment's bot
204
- * token, then find-or-creates the end-user. First-time Telegram users are
205
- * auto-provisioned with `user.email_pending === true` — prompt them for a
206
- * real email and call {@link linkEmail}. Stores the JWT on success.
207
- *
208
- * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`
209
- * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when
210
- * you already hold a configured client. */
211
204
  async exchangeTelegram(input) {
212
- const resp = await this.http.post("/auth/telegram/exchange", {
213
- 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 },
214
236
  skipAuth: true
215
237
  });
216
238
  await Promise.resolve(this.tokens.set(resp.access_token));
@@ -294,12 +316,44 @@ var CardsResource = class {
294
316
  * `failure_reason` on the result.
295
317
  */
296
318
  async create(input) {
297
- 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;
298
324
  return this.http.post("/me/cards", {
299
325
  body,
300
326
  idempotencyKey
301
327
  });
302
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
+ }
303
357
  /** Fetch one card by id. */
304
358
  async get(id) {
305
359
  return this.http.get(`/me/cards/${encodeURIComponent(id)}`);
@@ -499,17 +553,20 @@ var PushResource = class {
499
553
  return this.http.get("/me/push-subscription");
500
554
  }
501
555
  /** Store a subscription you created yourself.
502
- * 409 `push_disabled` when the deployment has no VAPID keys. */
556
+ * 409 `push_disabled` when the deployment has no VAPID keys.
557
+ * @deprecated Use `client.devices.register({ kind: "webpush", ... })`. */
503
558
  async save(input) {
504
559
  return this.http.put("/me/push-subscription", { body: input });
505
560
  }
506
- /** Delete the stored subscription. Safe when nothing is stored. */
561
+ /** Delete the stored subscription. Safe when nothing is stored.
562
+ * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */
507
563
  async remove() {
508
564
  await this.http.delete("/me/push-subscription");
509
565
  }
510
566
  /** Subscribe this browser and store the subscription. Ask for
511
567
  * notification permission before calling. Throws when push isn't set up
512
- * on the deployment. */
568
+ * on the deployment.
569
+ * @deprecated Use `client.devices.registerWebPush(registration)`. */
513
570
  async enable(registration) {
514
571
  const { vapid_public_key } = await this.status();
515
572
  if (!vapid_public_key) {
@@ -528,7 +585,8 @@ var PushResource = class {
528
585
  keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
529
586
  });
530
587
  }
531
- /** Unsubscribe this browser and delete the stored subscription. */
588
+ /** Unsubscribe this browser and delete the stored subscription.
589
+ * @deprecated Use `client.devices.unregisterWebPush(registration)`. */
532
590
  async disable(registration) {
533
591
  const sub = await registration.pushManager.getSubscription();
534
592
  if (sub) await sub.unsubscribe();
@@ -544,6 +602,188 @@ function base64UrlToBytes(input) {
544
602
  return out;
545
603
  }
546
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
+ function isCardOtp(item) {
634
+ return item.event_type === "card_otp" && typeof item.data?.otp === "string";
635
+ }
636
+ var NotificationsResource = class {
637
+ constructor(http) {
638
+ this.http = http;
639
+ }
640
+ /** One page of the inbox, newest first. */
641
+ async list(params = {}) {
642
+ const q = new URLSearchParams();
643
+ if (params.cursor) q.set("cursor", params.cursor);
644
+ if (params.limit !== void 0) q.set("limit", String(params.limit));
645
+ if (params.unreadOnly) q.set("unread", "true");
646
+ if (params.category) q.set("category", params.category);
647
+ const qs = q.toString();
648
+ return this.http.get(`/me/notifications${qs ? `?${qs}` : ""}`);
649
+ }
650
+ /** How many items are unread. Cheap; fine to poll for a badge. */
651
+ async unreadCount() {
652
+ const { unread } = await this.http.get("/me/notifications/unread-count");
653
+ return unread;
654
+ }
655
+ /** Mark one item read. Returns the item; calling it again is harmless. */
656
+ async markRead(id) {
657
+ return this.http.post(`/me/notifications/${encodeURIComponent(id)}/read`);
658
+ }
659
+ /** Mark every unread item read, or only those created before `before`
660
+ * (ISO timestamp). Returns how many changed. */
661
+ async markAllRead(before) {
662
+ return this.http.post("/me/notifications/read-all", {
663
+ body: before ? { before } : {}
664
+ });
665
+ }
666
+ /** Delete one item. 404 when it isn't the user's. */
667
+ async remove(id) {
668
+ await this.http.delete(`/me/notifications/${encodeURIComponent(id)}`);
669
+ }
670
+ /** The user's channel and language settings. */
671
+ async getPreferences() {
672
+ return this.http.get("/me/notification-preferences");
673
+ }
674
+ /** Change some settings; the rest stay. Returns the stored view.
675
+ * 400 `validation` for an unknown category, channel or locale. */
676
+ async setPreferences(input) {
677
+ return this.http.put("/me/notification-preferences", {
678
+ body: input
679
+ });
680
+ }
681
+ };
682
+
683
+ // src/resources/devices.ts
684
+ function devicePlatformOf(platform) {
685
+ return platform === "telegram-miniapp" ? "telegram" : platform;
686
+ }
687
+ var DevicesResource = class {
688
+ constructor(http, client) {
689
+ this.http = http;
690
+ this.client = client;
691
+ }
692
+ /** Every device the user has, disabled ones included. */
693
+ async list() {
694
+ return this.http.get("/me/devices");
695
+ }
696
+ /** Register a device, or refresh it when the same credential is already
697
+ * known (then `last_seen_at`, `label` and `app_version` update and a
698
+ * disabled device comes back). `app_version` defaults to the client
699
+ * version sent in `X-Takeal-Client`.
700
+ *
701
+ * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
702
+ * deployment has no VAPID keys. */
703
+ async register(input) {
704
+ return this.http.put("/me/devices", {
705
+ body: { app_version: this.client.version, ...input }
706
+ });
707
+ }
708
+ /** Delete one device. 404 when it isn't the user's. */
709
+ async remove(id) {
710
+ await this.http.delete(`/me/devices/${encodeURIComponent(id)}`);
711
+ }
712
+ /** Subscribe this browser to Web Push and register it as a device. Ask
713
+ * for notification permission before calling. Throws when push isn't
714
+ * set up on the deployment. */
715
+ async registerWebPush(registration, opts = {}) {
716
+ const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
717
+ if (!key) {
718
+ throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
719
+ }
720
+ const sub = await registration.pushManager.subscribe({
721
+ userVisibleOnly: true,
722
+ applicationServerKey: base64UrlToBytes(key)
723
+ });
724
+ const json = sub.toJSON();
725
+ if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
726
+ throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
727
+ }
728
+ return this.register({
729
+ kind: "webpush",
730
+ platform: devicePlatformOf(this.client.platform),
731
+ credential: {
732
+ endpoint: json.endpoint,
733
+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
734
+ },
735
+ ...opts.label ? { label: opts.label } : {}
736
+ });
737
+ }
738
+ /** Unsubscribe this browser from Web Push and delete the matching device
739
+ * (see {@link UnregisterWebPushOptions}). Safe when nothing is
740
+ * registered. */
741
+ async unregisterWebPush(registration, opts = {}) {
742
+ const sub = await registration.pushManager.getSubscription();
743
+ if (sub) await sub.unsubscribe();
744
+ if (opts.deviceId) {
745
+ await this.remove(opts.deviceId);
746
+ return;
747
+ }
748
+ const mine = (await this.list()).filter((d) => d.kind === "webpush" && d.is_current);
749
+ for (const d of mine) await this.remove(d.id);
750
+ }
751
+ async vapidPublicKey() {
752
+ const { vapid_public_key } = await this.http.get(
753
+ "/me/push-subscription"
754
+ );
755
+ return vapid_public_key ?? null;
756
+ }
757
+ };
758
+
759
+ // src/version.ts
760
+ var SDK_VERSION = "0.3.7";
761
+
762
+ // src/client-platform.ts
763
+ var CLIENT_HEADER = "X-Takeal-Client";
764
+ function detectClientPlatform() {
765
+ const g = globalThis;
766
+ const initData = g.Telegram?.WebApp?.initData;
767
+ if (typeof initData === "string" && initData.length > 0) return "telegram-miniapp";
768
+ if (g.navigator?.standalone === true) return "pwa";
769
+ if (typeof g.matchMedia === "function") {
770
+ try {
771
+ if (g.matchMedia("(display-mode: standalone)").matches) return "pwa";
772
+ } catch {
773
+ }
774
+ }
775
+ return "web";
776
+ }
777
+ function resolveClientDescriptor(given) {
778
+ return {
779
+ platform: given?.platform ?? detectClientPlatform(),
780
+ version: given?.version || SDK_VERSION
781
+ };
782
+ }
783
+ function clientHeaderValue(desc) {
784
+ return `${desc.platform}; ${desc.version}`;
785
+ }
786
+
547
787
  // src/token-store.ts
548
788
  function defaultBrowserStore(key = "takeal_jwt") {
549
789
  const fallback = inMemoryStore();
@@ -580,14 +820,30 @@ function inMemoryStore() {
580
820
  };
581
821
  }
582
822
 
823
+ // src/assets.ts
824
+ function resolveAssetUrl(baseUrl, url) {
825
+ if (isAbsolute(url)) return url;
826
+ const base = baseUrl.replace(/\/+$/, "");
827
+ const path = url.startsWith("/") ? url : `/${url}`;
828
+ return `${base}${path}`;
829
+ }
830
+ function isAbsolute(url) {
831
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url);
832
+ }
833
+
583
834
  // src/index.ts
584
835
  function createClient(opts) {
585
836
  const tokens = opts.tokenStore ?? pickDefaultStore();
586
837
  const fetchImpl = opts.fetch ?? defaultFetch();
587
- const http = new HttpClient(opts.baseUrl, tokens, fetchImpl);
838
+ const client = resolveClientDescriptor(opts.client);
839
+ const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {
840
+ [CLIENT_HEADER]: clientHeaderValue(client)
841
+ });
588
842
  return {
589
843
  brand: opts.brand,
844
+ client,
590
845
  tokens,
846
+ assetUrl: (url) => resolveAssetUrl(opts.baseUrl, url),
591
847
  auth: new AuthResource(http, tokens),
592
848
  deposits: new DepositsResource(http),
593
849
  cards: new CardsResource(http),
@@ -597,7 +853,10 @@ function createClient(opts) {
597
853
  blog: new BlogResource(http),
598
854
  subscriptions: new SubscriptionsResource(http),
599
855
  sessions: new SessionsResource(http),
600
- push: new PushResource(http)
856
+ push: new PushResource(http),
857
+ me: new MeResource(http),
858
+ notifications: new NotificationsResource(http),
859
+ devices: new DevicesResource(http, client)
601
860
  };
602
861
  }
603
862
  function pickDefaultStore() {
@@ -616,11 +875,16 @@ function defaultFetch() {
616
875
  }
617
876
 
618
877
  exports.ApiError = ApiError;
878
+ exports.CLIENT_HEADER = CLIENT_HEADER;
619
879
  exports.NetworkError = NetworkError;
880
+ exports.SDK_VERSION = SDK_VERSION;
620
881
  exports.createClient = createClient;
621
882
  exports.defaultBrowserStore = defaultBrowserStore;
883
+ exports.detectClientPlatform = detectClientPlatform;
622
884
  exports.inMemoryStore = inMemoryStore;
623
885
  exports.isApiError = isApiError;
886
+ exports.isCardOtp = isCardOtp;
624
887
  exports.isNetworkError = isNetworkError;
888
+ exports.resolveAssetUrl = resolveAssetUrl;
625
889
  //# sourceMappingURL=index.cjs.map
626
890
  //# sourceMappingURL=index.cjs.map