@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
package/dist/index.d.cts CHANGED
@@ -1,11 +1,11 @@
1
- import { T as TokenStore, F as FetchLike } from './http-BkCfOCR0.cjs';
2
- export { d as defaultBrowserStore, i as inMemoryStore } from './http-BkCfOCR0.cjs';
1
+ import { T as TokenStore, F as FetchLike } from './http-B-OQwMYn.cjs';
2
+ export { d as defaultBrowserStore, i as inMemoryStore } from './http-B-OQwMYn.cjs';
3
3
  import { AuthResource } from './resources/auth.cjs';
4
- export { ChangePasswordInput, JwtIssued, LoginInput, LoginResponse, OtpSentResponse, RegisterInput, Session, TotpRequired, TotpSetupComplete, TotpSetupRequired, User } from './resources/auth.cjs';
4
+ export { ChangePasswordInput, ExchangeTelegramInput, JwtIssued, LinkTelegramInput, LoginInput, LoginResponse, OtpSentResponse, RegisterInput, Session, TelegramLink, TelegramUnknown, TotpRequired, TotpSetupComplete, TotpSetupRequired, User } from './resources/auth.cjs';
5
5
  import { DepositsResource } from './resources/deposits.cjs';
6
6
  export { CreateDepositRefundInput, CreateQuoteInput, Deposit, DepositMethod, DepositStatus, FundingQuote, InitiateDepositInput, Refund } from './resources/deposits.cjs';
7
7
  import { CardsResource } from './resources/cards.cjs';
8
- export { Card, CardBalance, CardStatus, CardType, CreateCardInput, RevealCardInput, RevealedCard } from './resources/cards.cjs';
8
+ export { Card, CardBalance, CardDesignRef, CardProduct, CardProductPrice, CardStatus, CardType, CreateCardInput, RevealCardInput, RevealedCard, UpdateCardInput } from './resources/cards.cjs';
9
9
  import { BalanceResource } from './resources/balance.cjs';
10
10
  export { Balance } from './resources/balance.cjs';
11
11
  import { BrandingResource } from './resources/branding.cjs';
@@ -20,6 +20,11 @@ import { SessionsResource } from './resources/sessions.cjs';
20
20
  export { UserSession } from './resources/sessions.cjs';
21
21
  import { PushResource } from './resources/push.cjs';
22
22
  export { PushCapableRegistration, PushStatus, PushSubscriptionInput } from './resources/push.cjs';
23
+ import { MeResource } from './resources/me.cjs';
24
+ import { NotificationsResource } from './resources/notifications.cjs';
25
+ export { InboxItem, ListNotificationsParams, NotificationCategory, NotificationCategoryPreferences, NotificationChannel, NotificationLocale, NotificationPage, NotificationPreferences, NotificationPreferencesInput } from './resources/notifications.cjs';
26
+ import { C as ClientDescriptor, R as ResolvedClientDescriptor, D as DevicesResource } from './devices-C3JHi2Hi.cjs';
27
+ export { a as CLIENT_HEADER, b as ClientPlatform, c as Device, d as DeviceKind, e as DevicePlatform, M as MobilePushCredential, f as RegisterDeviceInput, g as RegisterWebPushOptions, h as RegisteredDevice, U as UnregisterWebPushOptions, W as WebPushCredential, i as detectClientPlatform } from './devices-C3JHi2Hi.cjs';
23
28
  export { A as Address, C as CustomerInfo } from './customer-CoxPwe5o.cjs';
24
29
 
25
30
  /**
@@ -48,6 +53,22 @@ interface BrandConfig {
48
53
  walletLabel?: string;
49
54
  }
50
55
 
56
+ /**
57
+ * Resolve an image URL the API hands back (`design.image_url`, a logo, …)
58
+ * into something a browser can load.
59
+ *
60
+ * The API returns either an absolute URL (uploaded artwork served from
61
+ * object storage) or a path relative to the API origin (the deployment's
62
+ * default card design, `/card-designs/default.svg`). Absolute URLs — and
63
+ * `data:` / `blob:` URIs — come back unchanged; a relative path is joined
64
+ * onto `baseUrl`, which is the bare API origin the client was built with.
65
+ * These paths are host-level, so no `/v1` prefix is added.
66
+ *
67
+ * `baseUrl` is the same value passed to `createClient`; a trailing slash is
68
+ * tolerated. `client.assetUrl()` calls this with the client's own base.
69
+ */
70
+ declare function resolveAssetUrl(baseUrl: string, url: string): string;
71
+
51
72
  /**
52
73
  * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;
53
74
  * network-level / abort / serialisation failures get the generic
@@ -90,10 +111,20 @@ declare class NetworkError extends Error {
90
111
  declare function isApiError(e: unknown): e is ApiError;
91
112
  declare function isNetworkError(e: unknown): e is NetworkError;
92
113
 
114
+ /**
115
+ * The SDK's own version, sent as the default `X-Takeal-Client` version.
116
+ *
117
+ * Kept as a plain constant so every entry point (ESM, CJS, the
118
+ * sub-exports) reads the same value without a JSON import or a bundler
119
+ * `define`. `src/version.test.ts` checks it matches `package.json`, so a
120
+ * release bump that forgets this file fails the test run.
121
+ */
122
+ declare const SDK_VERSION = "0.3.0";
123
+
93
124
  /**
94
125
  * `@takeal/cusfront-sdk` — typed client for the Takeal end-user API.
95
126
  *
96
- * Entry point: `createClient({ baseUrl, brand?, tokenStore?, fetch? })`.
127
+ * Entry point: `createClient({ baseUrl, brand?, client?, tokenStore?, fetch? })`.
97
128
  * Resources are accessed off the returned client (`client.auth.login`,
98
129
  * `client.cards.list`, …). Sub-exports under `@takeal/cusfront-sdk/<resource>`
99
130
  * publish each resource independently so a Cusfront only pulls what
@@ -110,6 +141,14 @@ interface CreateClientOptions {
110
141
  /** Runtime brand config. Optional; consumer renders its own brand
111
142
  * if omitted. */
112
143
  brand?: BrandConfig;
144
+ /** What kind of app this is, sent on every request as
145
+ * `X-Takeal-Client: <platform>; <version>`. The server uses it to spot
146
+ * a sign-in from a new device and to pick the notification channel.
147
+ * `platform` is detected at runtime when omitted (`telegram-miniapp`
148
+ * inside Telegram, `pwa` when installed, `web` otherwise); `version`
149
+ * defaults to the SDK version. Native wrappers should pass
150
+ * `{ platform: "ios" | "android", version }`. */
151
+ client?: ClientDescriptor;
113
152
  /** Token persistence. Defaults to `defaultBrowserStore()` when
114
153
  * `window.localStorage` is present, else `inMemoryStore()`. */
115
154
  tokenStore?: TokenStore;
@@ -125,11 +164,13 @@ interface CreateClientOptions {
125
164
  interface CusfrontClient {
126
165
  /** Read-only brand config — pass through from createClient args. */
127
166
  readonly brand: BrandConfig | undefined;
167
+ /** The platform and version this client announces in `X-Takeal-Client`. */
168
+ readonly client: ResolvedClientDescriptor;
128
169
  /** Auth resource: login, refresh, current user, logout. */
129
170
  readonly auth: AuthResource;
130
171
  /** Deposits (money IN via a funder connector): initiate, get, list, refund. */
131
172
  readonly deposits: DepositsResource;
132
- /** Cards (money OUT via an issuer connector): create, get, list, balance. */
173
+ /** Cards (money OUT via an issuer connector): the product catalog, create, get, list, update, balance. */
133
174
  readonly cards: CardsResource;
134
175
  /** Wallet balance lookup (defaults to the wallet's own currency). */
135
176
  readonly balance: BalanceResource;
@@ -139,15 +180,30 @@ interface CusfrontClient {
139
180
  readonly branding: BrandingResource;
140
181
  /** Public blog posts, returned as structured blocks to render in your own style. */
141
182
  readonly blog: BlogResource;
142
- /** The user's announcement channel subscriptions. */
183
+ /** The user's announcement channel subscriptions.
184
+ * @deprecated Use `notifications.setPreferences({ categories: { marketing: {...} } })`. */
143
185
  readonly subscriptions: SubscriptionsResource;
144
186
  /** Where the user is signed in: list sessions, sign one or all others out. */
145
187
  readonly sessions: SessionsResource;
146
- /** Web Push subscription for the signed-in user. */
188
+ /** Web Push subscription for the signed-in user.
189
+ * @deprecated Use `devices.registerWebPush` / `devices.unregisterWebPush`. */
147
190
  readonly push: PushResource;
191
+ /** The user's inbox and notification preferences. */
192
+ readonly notifications: NotificationsResource;
193
+ /** The user's devices: browsers with Web Push, phones, the Telegram Mini App. */
194
+ readonly devices: DevicesResource;
195
+ /** Profile actions for the signed-in user: link or unlink Telegram. */
196
+ readonly me: MeResource;
148
197
  /** Direct access to the token store (e.g. for an explicit sign-out
149
198
  * on Capacitor's lifecycle "app pausing" event). */
150
199
  readonly tokens: TokenStore;
200
+ /**
201
+ * Turn an image URL from the API (`card.design.image_url`,
202
+ * `product.design.image_url`) into one a browser can load. Absolute URLs
203
+ * pass through; a path relative to the API origin (the default card
204
+ * design, `/card-designs/default.svg`) is joined onto `baseUrl`.
205
+ */
206
+ assetUrl(url: string): string;
151
207
  }
152
208
  /**
153
209
  * Build a new client. Stateless across calls — multiple clients can
@@ -159,4 +215,4 @@ interface CusfrontClient {
159
215
  */
160
216
  declare function createClient(opts: CreateClientOptions): CusfrontClient;
161
217
 
162
- export { ApiError, type BrandConfig, type CreateClientOptions, type CusfrontClient, NetworkError, TokenStore, createClient, isApiError, isNetworkError };
218
+ export { ApiError, type BrandConfig, ClientDescriptor, type CreateClientOptions, type CusfrontClient, MeResource, NetworkError, ResolvedClientDescriptor, SDK_VERSION, TokenStore, createClient, isApiError, isNetworkError, resolveAssetUrl };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { T as TokenStore, F as FetchLike } from './http-BkCfOCR0.js';
2
- export { d as defaultBrowserStore, i as inMemoryStore } from './http-BkCfOCR0.js';
1
+ import { T as TokenStore, F as FetchLike } from './http-B-OQwMYn.js';
2
+ export { d as defaultBrowserStore, i as inMemoryStore } from './http-B-OQwMYn.js';
3
3
  import { AuthResource } from './resources/auth.js';
4
- export { ChangePasswordInput, JwtIssued, LoginInput, LoginResponse, OtpSentResponse, RegisterInput, Session, TotpRequired, TotpSetupComplete, TotpSetupRequired, User } from './resources/auth.js';
4
+ export { ChangePasswordInput, ExchangeTelegramInput, JwtIssued, LinkTelegramInput, LoginInput, LoginResponse, OtpSentResponse, RegisterInput, Session, TelegramLink, TelegramUnknown, TotpRequired, TotpSetupComplete, TotpSetupRequired, User } from './resources/auth.js';
5
5
  import { DepositsResource } from './resources/deposits.js';
6
6
  export { CreateDepositRefundInput, CreateQuoteInput, Deposit, DepositMethod, DepositStatus, FundingQuote, InitiateDepositInput, Refund } from './resources/deposits.js';
7
7
  import { CardsResource } from './resources/cards.js';
8
- export { Card, CardBalance, CardStatus, CardType, CreateCardInput, RevealCardInput, RevealedCard } from './resources/cards.js';
8
+ export { Card, CardBalance, CardDesignRef, CardProduct, CardProductPrice, CardStatus, CardType, CreateCardInput, RevealCardInput, RevealedCard, UpdateCardInput } from './resources/cards.js';
9
9
  import { BalanceResource } from './resources/balance.js';
10
10
  export { Balance } from './resources/balance.js';
11
11
  import { BrandingResource } from './resources/branding.js';
@@ -20,6 +20,11 @@ import { SessionsResource } from './resources/sessions.js';
20
20
  export { UserSession } from './resources/sessions.js';
21
21
  import { PushResource } from './resources/push.js';
22
22
  export { PushCapableRegistration, PushStatus, PushSubscriptionInput } from './resources/push.js';
23
+ import { MeResource } from './resources/me.js';
24
+ import { NotificationsResource } from './resources/notifications.js';
25
+ export { InboxItem, ListNotificationsParams, NotificationCategory, NotificationCategoryPreferences, NotificationChannel, NotificationLocale, NotificationPage, NotificationPreferences, NotificationPreferencesInput } from './resources/notifications.js';
26
+ import { C as ClientDescriptor, R as ResolvedClientDescriptor, D as DevicesResource } from './devices-DP_hxwmW.js';
27
+ export { a as CLIENT_HEADER, b as ClientPlatform, c as Device, d as DeviceKind, e as DevicePlatform, M as MobilePushCredential, f as RegisterDeviceInput, g as RegisterWebPushOptions, h as RegisteredDevice, U as UnregisterWebPushOptions, W as WebPushCredential, i as detectClientPlatform } from './devices-DP_hxwmW.js';
23
28
  export { A as Address, C as CustomerInfo } from './customer-CoxPwe5o.js';
24
29
 
25
30
  /**
@@ -48,6 +53,22 @@ interface BrandConfig {
48
53
  walletLabel?: string;
49
54
  }
50
55
 
56
+ /**
57
+ * Resolve an image URL the API hands back (`design.image_url`, a logo, …)
58
+ * into something a browser can load.
59
+ *
60
+ * The API returns either an absolute URL (uploaded artwork served from
61
+ * object storage) or a path relative to the API origin (the deployment's
62
+ * default card design, `/card-designs/default.svg`). Absolute URLs — and
63
+ * `data:` / `blob:` URIs — come back unchanged; a relative path is joined
64
+ * onto `baseUrl`, which is the bare API origin the client was built with.
65
+ * These paths are host-level, so no `/v1` prefix is added.
66
+ *
67
+ * `baseUrl` is the same value passed to `createClient`; a trailing slash is
68
+ * tolerated. `client.assetUrl()` calls this with the client's own base.
69
+ */
70
+ declare function resolveAssetUrl(baseUrl: string, url: string): string;
71
+
51
72
  /**
52
73
  * Errors surfaced by the SDK. All HTTP failures map onto `ApiError`;
53
74
  * network-level / abort / serialisation failures get the generic
@@ -90,10 +111,20 @@ declare class NetworkError extends Error {
90
111
  declare function isApiError(e: unknown): e is ApiError;
91
112
  declare function isNetworkError(e: unknown): e is NetworkError;
92
113
 
114
+ /**
115
+ * The SDK's own version, sent as the default `X-Takeal-Client` version.
116
+ *
117
+ * Kept as a plain constant so every entry point (ESM, CJS, the
118
+ * sub-exports) reads the same value without a JSON import or a bundler
119
+ * `define`. `src/version.test.ts` checks it matches `package.json`, so a
120
+ * release bump that forgets this file fails the test run.
121
+ */
122
+ declare const SDK_VERSION = "0.3.0";
123
+
93
124
  /**
94
125
  * `@takeal/cusfront-sdk` — typed client for the Takeal end-user API.
95
126
  *
96
- * Entry point: `createClient({ baseUrl, brand?, tokenStore?, fetch? })`.
127
+ * Entry point: `createClient({ baseUrl, brand?, client?, tokenStore?, fetch? })`.
97
128
  * Resources are accessed off the returned client (`client.auth.login`,
98
129
  * `client.cards.list`, …). Sub-exports under `@takeal/cusfront-sdk/<resource>`
99
130
  * publish each resource independently so a Cusfront only pulls what
@@ -110,6 +141,14 @@ interface CreateClientOptions {
110
141
  /** Runtime brand config. Optional; consumer renders its own brand
111
142
  * if omitted. */
112
143
  brand?: BrandConfig;
144
+ /** What kind of app this is, sent on every request as
145
+ * `X-Takeal-Client: <platform>; <version>`. The server uses it to spot
146
+ * a sign-in from a new device and to pick the notification channel.
147
+ * `platform` is detected at runtime when omitted (`telegram-miniapp`
148
+ * inside Telegram, `pwa` when installed, `web` otherwise); `version`
149
+ * defaults to the SDK version. Native wrappers should pass
150
+ * `{ platform: "ios" | "android", version }`. */
151
+ client?: ClientDescriptor;
113
152
  /** Token persistence. Defaults to `defaultBrowserStore()` when
114
153
  * `window.localStorage` is present, else `inMemoryStore()`. */
115
154
  tokenStore?: TokenStore;
@@ -125,11 +164,13 @@ interface CreateClientOptions {
125
164
  interface CusfrontClient {
126
165
  /** Read-only brand config — pass through from createClient args. */
127
166
  readonly brand: BrandConfig | undefined;
167
+ /** The platform and version this client announces in `X-Takeal-Client`. */
168
+ readonly client: ResolvedClientDescriptor;
128
169
  /** Auth resource: login, refresh, current user, logout. */
129
170
  readonly auth: AuthResource;
130
171
  /** Deposits (money IN via a funder connector): initiate, get, list, refund. */
131
172
  readonly deposits: DepositsResource;
132
- /** Cards (money OUT via an issuer connector): create, get, list, balance. */
173
+ /** Cards (money OUT via an issuer connector): the product catalog, create, get, list, update, balance. */
133
174
  readonly cards: CardsResource;
134
175
  /** Wallet balance lookup (defaults to the wallet's own currency). */
135
176
  readonly balance: BalanceResource;
@@ -139,15 +180,30 @@ interface CusfrontClient {
139
180
  readonly branding: BrandingResource;
140
181
  /** Public blog posts, returned as structured blocks to render in your own style. */
141
182
  readonly blog: BlogResource;
142
- /** The user's announcement channel subscriptions. */
183
+ /** The user's announcement channel subscriptions.
184
+ * @deprecated Use `notifications.setPreferences({ categories: { marketing: {...} } })`. */
143
185
  readonly subscriptions: SubscriptionsResource;
144
186
  /** Where the user is signed in: list sessions, sign one or all others out. */
145
187
  readonly sessions: SessionsResource;
146
- /** Web Push subscription for the signed-in user. */
188
+ /** Web Push subscription for the signed-in user.
189
+ * @deprecated Use `devices.registerWebPush` / `devices.unregisterWebPush`. */
147
190
  readonly push: PushResource;
191
+ /** The user's inbox and notification preferences. */
192
+ readonly notifications: NotificationsResource;
193
+ /** The user's devices: browsers with Web Push, phones, the Telegram Mini App. */
194
+ readonly devices: DevicesResource;
195
+ /** Profile actions for the signed-in user: link or unlink Telegram. */
196
+ readonly me: MeResource;
148
197
  /** Direct access to the token store (e.g. for an explicit sign-out
149
198
  * on Capacitor's lifecycle "app pausing" event). */
150
199
  readonly tokens: TokenStore;
200
+ /**
201
+ * Turn an image URL from the API (`card.design.image_url`,
202
+ * `product.design.image_url`) into one a browser can load. Absolute URLs
203
+ * pass through; a path relative to the API origin (the default card
204
+ * design, `/card-designs/default.svg`) is joined onto `baseUrl`.
205
+ */
206
+ assetUrl(url: string): string;
151
207
  }
152
208
  /**
153
209
  * Build a new client. Stateless across calls — multiple clients can
@@ -159,4 +215,4 @@ interface CusfrontClient {
159
215
  */
160
216
  declare function createClient(opts: CreateClientOptions): CusfrontClient;
161
217
 
162
- export { ApiError, type BrandConfig, type CreateClientOptions, type CusfrontClient, NetworkError, TokenStore, createClient, isApiError, isNetworkError };
218
+ export { ApiError, type BrandConfig, ClientDescriptor, type CreateClientOptions, type CusfrontClient, MeResource, NetworkError, ResolvedClientDescriptor, SDK_VERSION, TokenStore, createClient, isApiError, isNetworkError, resolveAssetUrl };
package/dist/index.js CHANGED
@@ -35,10 +35,11 @@ function versionedPath(path) {
35
35
  return `${API_VERSION}${p}`;
36
36
  }
37
37
  var HttpClient = class {
38
- constructor(baseUrl, tokens, fetchImpl) {
38
+ constructor(baseUrl, tokens, fetchImpl, defaultHeaders = {}) {
39
39
  this.baseUrl = baseUrl;
40
40
  this.tokens = tokens;
41
41
  this.fetchImpl = fetchImpl;
42
+ this.defaultHeaders = defaultHeaders;
42
43
  if (!baseUrl) throw new Error("HttpClient: baseUrl is required");
43
44
  }
44
45
  async get(path, opts = {}) {
@@ -59,7 +60,8 @@ var HttpClient = class {
59
60
  async request(method, path, opts) {
60
61
  const url = this.absolute(path);
61
62
  const headers = {
62
- Accept: "application/json"
63
+ Accept: "application/json",
64
+ ...this.defaultHeaders
63
65
  };
64
66
  if (opts.body !== void 0) headers["Content-Type"] = "application/json";
65
67
  if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
@@ -197,18 +199,38 @@ var AuthResource = class {
197
199
  skipAuth: true
198
200
  });
199
201
  }
200
- /** Exchange a signed Telegram Mini App `initData` payload for a session
201
- * JWT. The server validates the initData HMAC against the deployment's bot
202
- * token, then find-or-creates the end-user. First-time Telegram users are
203
- * auto-provisioned with `user.email_pending === true` — prompt them for a
204
- * real email and call {@link linkEmail}. Stores the JWT on success.
205
- *
206
- * Most consumers use the higher-level `fromInitData` / `fromTelegramWebApp`
207
- * helpers in `@takeal/cusfront-sdk/telegram`; reach for this directly when
208
- * you already hold a configured client. */
209
202
  async exchangeTelegram(input) {
210
- const resp = await this.http.post("/auth/telegram/exchange", {
211
- body: { init_data: input.initData },
203
+ const body = { init_data: input.initData };
204
+ if (input.provision !== void 0) body.provision = input.provision;
205
+ let resp;
206
+ try {
207
+ resp = await this.http.post("/auth/telegram/exchange", {
208
+ body,
209
+ skipAuth: true
210
+ });
211
+ } catch (e) {
212
+ if (isApiError(e) && e.status === 404 && e.code === "telegram_unknown") {
213
+ return { stage: "unknown" };
214
+ }
215
+ throw e;
216
+ }
217
+ await Promise.resolve(this.tokens.set(resp.access_token));
218
+ return resp;
219
+ }
220
+ /** Attach the Telegram account behind `initData` to an existing email +
221
+ * password account and sign in as that account. No bearer needed; the
222
+ * password is checked the same way `login` checks it. The JWT is stored.
223
+ *
224
+ * Errors: 401 `unauthenticated` (wrong email or password, as with
225
+ * `login`) / `invalid_init_data`; 403
226
+ * `user_disabled` / `second_factor_required` (accounts that sign in with
227
+ * a second factor can't be linked from a Mini App); 409
228
+ * `telegram_already_linked_other` (this account already has a different
229
+ * Telegram; unlink it first) / `telegram_in_use` (this Telegram belongs to
230
+ * another account); 503 `telegram_not_configured`. */
231
+ async linkTelegram(input) {
232
+ const resp = await this.http.post("/auth/telegram/link", {
233
+ body: { init_data: input.initData, email: input.email, password: input.password },
212
234
  skipAuth: true
213
235
  });
214
236
  await Promise.resolve(this.tokens.set(resp.access_token));
@@ -292,12 +314,44 @@ var CardsResource = class {
292
314
  * `failure_reason` on the result.
293
315
  */
294
316
  async create(input) {
295
- const { idempotencyKey, ...body } = input;
317
+ const { idempotencyKey, productId, name, designId, ...rest } = input;
318
+ const body = { ...rest };
319
+ if (productId !== void 0) body["product_id"] = productId;
320
+ if (name !== void 0) body["name"] = name;
321
+ if (designId !== void 0) body["design_id"] = designId;
296
322
  return this.http.post("/me/cards", {
297
323
  body,
298
324
  idempotencyKey
299
325
  });
300
326
  }
327
+ /**
328
+ * The cards the caller can order, in the order the deployment offers them
329
+ * (the default product first). Each item carries its name, description,
330
+ * artwork, the issuance price after the caller's subscription discount,
331
+ * and the currency. Pass an item's `id` as `productId` to {@link create}.
332
+ */
333
+ async listProducts() {
334
+ return this.http.get("/me/card-products");
335
+ }
336
+ /** One product from the catalog. 404 when unknown, disabled or hidden. */
337
+ async getProduct(id) {
338
+ return this.http.get(
339
+ `/me/card-products/${encodeURIComponent(id)}`
340
+ );
341
+ }
342
+ /**
343
+ * Rename the caller's own card or change its design. Resolves to the
344
+ * updated card. 404 if the card isn't the caller's; 400 `invalid_name` /
345
+ * `design_not_allowed` on a bad value.
346
+ */
347
+ async update(id, input) {
348
+ const body = {};
349
+ if (input.name !== void 0) body["name"] = input.name;
350
+ if (input.designId !== void 0) body["design_id"] = input.designId;
351
+ return this.http.patch(`/me/cards/${encodeURIComponent(id)}`, {
352
+ body
353
+ });
354
+ }
301
355
  /** Fetch one card by id. */
302
356
  async get(id) {
303
357
  return this.http.get(`/me/cards/${encodeURIComponent(id)}`);
@@ -497,17 +551,20 @@ var PushResource = class {
497
551
  return this.http.get("/me/push-subscription");
498
552
  }
499
553
  /** Store a subscription you created yourself.
500
- * 409 `push_disabled` when the deployment has no VAPID keys. */
554
+ * 409 `push_disabled` when the deployment has no VAPID keys.
555
+ * @deprecated Use `client.devices.register({ kind: "webpush", ... })`. */
501
556
  async save(input) {
502
557
  return this.http.put("/me/push-subscription", { body: input });
503
558
  }
504
- /** Delete the stored subscription. Safe when nothing is stored. */
559
+ /** Delete the stored subscription. Safe when nothing is stored.
560
+ * @deprecated Use `client.devices.remove(id)` or `client.devices.unregisterWebPush(reg)`. */
505
561
  async remove() {
506
562
  await this.http.delete("/me/push-subscription");
507
563
  }
508
564
  /** Subscribe this browser and store the subscription. Ask for
509
565
  * notification permission before calling. Throws when push isn't set up
510
- * on the deployment. */
566
+ * on the deployment.
567
+ * @deprecated Use `client.devices.registerWebPush(registration)`. */
511
568
  async enable(registration) {
512
569
  const { vapid_public_key } = await this.status();
513
570
  if (!vapid_public_key) {
@@ -526,7 +583,8 @@ var PushResource = class {
526
583
  keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
527
584
  });
528
585
  }
529
- /** Unsubscribe this browser and delete the stored subscription. */
586
+ /** Unsubscribe this browser and delete the stored subscription.
587
+ * @deprecated Use `client.devices.unregisterWebPush(registration)`. */
530
588
  async disable(registration) {
531
589
  const sub = await registration.pushManager.getSubscription();
532
590
  if (sub) await sub.unsubscribe();
@@ -542,6 +600,185 @@ function base64UrlToBytes(input) {
542
600
  return out;
543
601
  }
544
602
 
603
+ // src/resources/me.ts
604
+ var MeResource = class {
605
+ constructor(http) {
606
+ this.http = http;
607
+ }
608
+ /** Attach the Telegram account behind `initData` to the signed-in user.
609
+ * Returns the updated user (`telegram` is set). Repeating the call with
610
+ * the same Telegram is fine.
611
+ *
612
+ * Errors: 401 `invalid_init_data`; 403 `user_disabled` /
613
+ * `second_factor_required`; 409 `telegram_already_linked_other` (the
614
+ * account already has a different Telegram; `unlinkTelegram` first) /
615
+ * `telegram_in_use` (that Telegram belongs to another account); 503
616
+ * `telegram_not_configured`. */
617
+ async linkTelegram(initData) {
618
+ return this.http.post("/me/telegram", { body: { init_data: initData } });
619
+ }
620
+ /** Detach the Telegram account from the signed-in user. Returns the
621
+ * updated user (`telegram` is `null`).
622
+ *
623
+ * Errors: 404 `telegram_not_linked`; 409 `last_credential` when the
624
+ * account has no password, so Telegram is its only way to sign in. */
625
+ async unlinkTelegram() {
626
+ return this.http.delete("/me/telegram");
627
+ }
628
+ };
629
+
630
+ // src/resources/notifications.ts
631
+ var NotificationsResource = class {
632
+ constructor(http) {
633
+ this.http = http;
634
+ }
635
+ /** One page of the inbox, newest first. */
636
+ async list(params = {}) {
637
+ const q = new URLSearchParams();
638
+ if (params.cursor) q.set("cursor", params.cursor);
639
+ if (params.limit !== void 0) q.set("limit", String(params.limit));
640
+ if (params.unreadOnly) q.set("unread", "true");
641
+ if (params.category) q.set("category", params.category);
642
+ const qs = q.toString();
643
+ return this.http.get(`/me/notifications${qs ? `?${qs}` : ""}`);
644
+ }
645
+ /** How many items are unread. Cheap; fine to poll for a badge. */
646
+ async unreadCount() {
647
+ const { unread } = await this.http.get("/me/notifications/unread-count");
648
+ return unread;
649
+ }
650
+ /** Mark one item read. Returns the item; calling it again is harmless. */
651
+ async markRead(id) {
652
+ return this.http.post(`/me/notifications/${encodeURIComponent(id)}/read`);
653
+ }
654
+ /** Mark every unread item read, or only those created before `before`
655
+ * (ISO timestamp). Returns how many changed. */
656
+ async markAllRead(before) {
657
+ return this.http.post("/me/notifications/read-all", {
658
+ body: before ? { before } : {}
659
+ });
660
+ }
661
+ /** Delete one item. 404 when it isn't the user's. */
662
+ async remove(id) {
663
+ await this.http.delete(`/me/notifications/${encodeURIComponent(id)}`);
664
+ }
665
+ /** The user's channel and language settings. */
666
+ async getPreferences() {
667
+ return this.http.get("/me/notification-preferences");
668
+ }
669
+ /** Change some settings; the rest stay. Returns the stored view.
670
+ * 400 `validation` for an unknown category, channel or locale. */
671
+ async setPreferences(input) {
672
+ return this.http.put("/me/notification-preferences", {
673
+ body: input
674
+ });
675
+ }
676
+ };
677
+
678
+ // src/resources/devices.ts
679
+ function devicePlatformOf(platform) {
680
+ return platform === "telegram-miniapp" ? "telegram" : platform;
681
+ }
682
+ var DevicesResource = class {
683
+ constructor(http, client) {
684
+ this.http = http;
685
+ this.client = client;
686
+ }
687
+ /** Every device the user has, disabled ones included. */
688
+ async list() {
689
+ return this.http.get("/me/devices");
690
+ }
691
+ /** Register a device, or refresh it when the same credential is already
692
+ * known (then `last_seen_at`, `label` and `app_version` update and a
693
+ * disabled device comes back). `app_version` defaults to the client
694
+ * version sent in `X-Takeal-Client`.
695
+ *
696
+ * Errors: 400 `validation`; 409 `push_disabled` for `webpush` when the
697
+ * deployment has no VAPID keys. */
698
+ async register(input) {
699
+ return this.http.put("/me/devices", {
700
+ body: { app_version: this.client.version, ...input }
701
+ });
702
+ }
703
+ /** Delete one device. 404 when it isn't the user's. */
704
+ async remove(id) {
705
+ await this.http.delete(`/me/devices/${encodeURIComponent(id)}`);
706
+ }
707
+ /** Subscribe this browser to Web Push and register it as a device. Ask
708
+ * for notification permission before calling. Throws when push isn't
709
+ * set up on the deployment. */
710
+ async registerWebPush(registration, opts = {}) {
711
+ const key = opts.vapidPublicKey ?? await this.vapidPublicKey();
712
+ if (!key) {
713
+ throw new Error("@takeal/cusfront-sdk: push notifications are not enabled on this deployment");
714
+ }
715
+ const sub = await registration.pushManager.subscribe({
716
+ userVisibleOnly: true,
717
+ applicationServerKey: base64UrlToBytes(key)
718
+ });
719
+ const json = sub.toJSON();
720
+ if (!json.endpoint || !json.keys?.p256dh || !json.keys.auth) {
721
+ throw new Error("@takeal/cusfront-sdk: the browser returned an incomplete push subscription");
722
+ }
723
+ return this.register({
724
+ kind: "webpush",
725
+ platform: devicePlatformOf(this.client.platform),
726
+ credential: {
727
+ endpoint: json.endpoint,
728
+ keys: { p256dh: json.keys.p256dh, auth: json.keys.auth }
729
+ },
730
+ ...opts.label ? { label: opts.label } : {}
731
+ });
732
+ }
733
+ /** Unsubscribe this browser from Web Push and delete the matching device
734
+ * (see {@link UnregisterWebPushOptions}). Safe when nothing is
735
+ * registered. */
736
+ async unregisterWebPush(registration, opts = {}) {
737
+ const sub = await registration.pushManager.getSubscription();
738
+ if (sub) await sub.unsubscribe();
739
+ if (opts.deviceId) {
740
+ await this.remove(opts.deviceId);
741
+ return;
742
+ }
743
+ const mine = (await this.list()).filter((d) => d.kind === "webpush" && d.is_current);
744
+ for (const d of mine) await this.remove(d.id);
745
+ }
746
+ async vapidPublicKey() {
747
+ const { vapid_public_key } = await this.http.get(
748
+ "/me/push-subscription"
749
+ );
750
+ return vapid_public_key ?? null;
751
+ }
752
+ };
753
+
754
+ // src/version.ts
755
+ var SDK_VERSION = "0.3.0";
756
+
757
+ // src/client-platform.ts
758
+ var CLIENT_HEADER = "X-Takeal-Client";
759
+ function detectClientPlatform() {
760
+ const g = globalThis;
761
+ const initData = g.Telegram?.WebApp?.initData;
762
+ if (typeof initData === "string" && initData.length > 0) return "telegram-miniapp";
763
+ if (g.navigator?.standalone === true) return "pwa";
764
+ if (typeof g.matchMedia === "function") {
765
+ try {
766
+ if (g.matchMedia("(display-mode: standalone)").matches) return "pwa";
767
+ } catch {
768
+ }
769
+ }
770
+ return "web";
771
+ }
772
+ function resolveClientDescriptor(given) {
773
+ return {
774
+ platform: given?.platform ?? detectClientPlatform(),
775
+ version: given?.version || SDK_VERSION
776
+ };
777
+ }
778
+ function clientHeaderValue(desc) {
779
+ return `${desc.platform}; ${desc.version}`;
780
+ }
781
+
545
782
  // src/token-store.ts
546
783
  function defaultBrowserStore(key = "takeal_jwt") {
547
784
  const fallback = inMemoryStore();
@@ -578,14 +815,30 @@ function inMemoryStore() {
578
815
  };
579
816
  }
580
817
 
818
+ // src/assets.ts
819
+ function resolveAssetUrl(baseUrl, url) {
820
+ if (isAbsolute(url)) return url;
821
+ const base = baseUrl.replace(/\/+$/, "");
822
+ const path = url.startsWith("/") ? url : `/${url}`;
823
+ return `${base}${path}`;
824
+ }
825
+ function isAbsolute(url) {
826
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url);
827
+ }
828
+
581
829
  // src/index.ts
582
830
  function createClient(opts) {
583
831
  const tokens = opts.tokenStore ?? pickDefaultStore();
584
832
  const fetchImpl = opts.fetch ?? defaultFetch();
585
- const http = new HttpClient(opts.baseUrl, tokens, fetchImpl);
833
+ const client = resolveClientDescriptor(opts.client);
834
+ const http = new HttpClient(opts.baseUrl, tokens, fetchImpl, {
835
+ [CLIENT_HEADER]: clientHeaderValue(client)
836
+ });
586
837
  return {
587
838
  brand: opts.brand,
839
+ client,
588
840
  tokens,
841
+ assetUrl: (url) => resolveAssetUrl(opts.baseUrl, url),
589
842
  auth: new AuthResource(http, tokens),
590
843
  deposits: new DepositsResource(http),
591
844
  cards: new CardsResource(http),
@@ -595,7 +848,10 @@ function createClient(opts) {
595
848
  blog: new BlogResource(http),
596
849
  subscriptions: new SubscriptionsResource(http),
597
850
  sessions: new SessionsResource(http),
598
- push: new PushResource(http)
851
+ push: new PushResource(http),
852
+ me: new MeResource(http),
853
+ notifications: new NotificationsResource(http),
854
+ devices: new DevicesResource(http, client)
599
855
  };
600
856
  }
601
857
  function pickDefaultStore() {
@@ -613,6 +869,6 @@ function defaultFetch() {
613
869
  );
614
870
  }
615
871
 
616
- export { ApiError, NetworkError, createClient, defaultBrowserStore, inMemoryStore, isApiError, isNetworkError };
872
+ export { ApiError, CLIENT_HEADER, NetworkError, SDK_VERSION, createClient, defaultBrowserStore, detectClientPlatform, inMemoryStore, isApiError, isNetworkError, resolveAssetUrl };
617
873
  //# sourceMappingURL=index.js.map
618
874
  //# sourceMappingURL=index.js.map